LLVM 24.0.0git
LazyValueInfo.cpp
Go to the documentation of this file.
1//===- LazyValueInfo.cpp - Value constraint analysis ------------*- 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// This file defines the interface for lazy computation of value constraint
10// information.
11//
12//===----------------------------------------------------------------------===//
13
15#include "AnalysisOptions.h"
16#include "llvm/ADT/DenseSet.h"
17#include "llvm/ADT/STLExtras.h"
21#include "llvm/Analysis/Loads.h"
28#include "llvm/IR/CFG.h"
30#include "llvm/IR/Constants.h"
31#include "llvm/IR/DataLayout.h"
32#include "llvm/IR/Dominators.h"
33#include "llvm/IR/InstrTypes.h"
36#include "llvm/IR/Intrinsics.h"
37#include "llvm/IR/LLVMContext.h"
38#include "llvm/IR/Module.h"
40#include "llvm/IR/ValueHandle.h"
42#include "llvm/Support/Debug.h"
46#include <optional>
47using namespace llvm;
48using namespace PatternMatch;
49
50#define DEBUG_TYPE "lazy-value-info"
51
52// This is the number of worklist items we will process to try to discover an
53// answer for a given value.
54static const unsigned MaxProcessedPerValue = 500;
55
59 "Lazy Value Information Analysis", false, true)
63 "Lazy Value Information Analysis", false, true)
64
65namespace llvm {
69} // namespace llvm
70
71AnalysisKey LazyValueAnalysis::Key;
72
73/// Returns true if this lattice value represents at most one possible value.
74/// This is as precise as any lattice value can get while still representing
75/// reachable code.
76static bool hasSingleValue(const ValueLatticeElement &Val) {
77 if (Val.isConstantRange() &&
79 // Integer constants are single element ranges
80 return true;
81 if (Val.isConstant())
82 // Non integer constants
83 return true;
84 return false;
85}
86
87//===----------------------------------------------------------------------===//
88// LazyValueInfoCache Decl
89//===----------------------------------------------------------------------===//
90
91namespace {
92 /// A callback value handle updates the cache when values are erased.
93 class LazyValueInfoCache;
94 struct LVIValueHandle final : public CallbackVH {
95 LazyValueInfoCache *Parent;
96
97 LVIValueHandle(Value *V, LazyValueInfoCache *P = nullptr)
98 : CallbackVH(V), Parent(P) { }
99
100 void deleted() override;
101 void allUsesReplacedWith(Value *V) override {
102 deleted();
103 }
104 };
105} // end anonymous namespace
106
107namespace {
108using NonNullPointerSet = SmallDenseSet<AssertingVH<Value>, 2>;
109using BBLatticeElementMap =
111using PredecessorValueLatticeMap =
112 SmallDenseMap<AssertingVH<Value>, BBLatticeElementMap, 2>;
113
114/// This is the cache kept by LazyValueInfo which
115/// maintains information about queries across the clients' queries.
116class LazyValueInfoCache {
117 /// This is all of the cached information for one basic block. It contains
118 /// the per-value lattice elements, as well as a separate set for
119 /// overdefined values to reduce memory usage. Additionally pointers
120 /// dereferenced in the block are cached for nullability queries.
121 struct BlockCacheEntry {
122 SmallDenseMap<AssertingVH<Value>, ValueLatticeElement, 4> LatticeElements;
123 SmallDenseSet<AssertingVH<Value>, 4> OverDefined;
124 // std::nullopt indicates that the nonnull pointers for this basic block
125 // block have not been computed yet.
126 std::optional<NonNullPointerSet> NonNullPointers;
127 // This is an extension of the above LatticeElements, caching, for each
128 // Value, a ValueLatticeElement, for each predecessor of the BB tracked by
129 // this entry.
130 std::optional<PredecessorValueLatticeMap> PredecessorLatticeElements;
131 };
132
133 const bool PerPredRanges;
134
135 /// Cached information per basic block, indexed by block number.
137 /// Set of value handles used to erase values from the cache on deletion.
138 DenseSet<LVIValueHandle, DenseMapInfo<Value *>> ValueHandles;
139 /// Block number epoch on construction.
140 unsigned BlockNumberEpoch;
141
142 const BlockCacheEntry *getBlockEntry(BasicBlock *BB) const {
143 assert(BlockNumberEpoch == BB->getParent()->getBlockNumberEpoch());
144 if (BB->getNumber() < BlockCache.size())
145 return BlockCache[BB->getNumber()].get();
146 return nullptr;
147 }
148
149 BlockCacheEntry *getOrCreateBlockEntry(BasicBlock *BB) {
150 assert(BlockNumberEpoch == BB->getParent()->getBlockNumberEpoch());
151 unsigned Number = BB->getNumber();
152 if (Number >= BlockCache.size())
153 BlockCache.resize(BB->getParent()->getMaxBlockNumber());
154
155 if (BlockCacheEntry *Entry = BlockCache[Number].get())
156 return Entry;
157
158 BlockCache[Number] = std::make_unique<BlockCacheEntry>();
159 if (PerPredRanges)
160 BlockCache[Number]->PredecessorLatticeElements =
161 std::make_optional<PredecessorValueLatticeMap>();
162
163 return BlockCache[Number].get();
164 }
165
166 void addValueHandle(Value *Val) {
167 auto HandleIt = ValueHandles.find_as(Val);
168 if (HandleIt == ValueHandles.end())
169 ValueHandles.insert({Val, this});
170 }
171
172public:
173 LazyValueInfoCache(const Function *F, bool PerPredRanges)
174 : PerPredRanges(PerPredRanges),
175 BlockNumberEpoch(F->getBlockNumberEpoch()) {}
176
177 void insertResult(Value *Val, BasicBlock *BB,
178 const ValueLatticeElement &Result) {
179 BlockCacheEntry *Entry = getOrCreateBlockEntry(BB);
180
181 // Insert over-defined values into their own cache to reduce memory
182 // overhead.
183 if (Result.isOverdefined())
184 Entry->OverDefined.insert(Val);
185 else
186 Entry->LatticeElements.insert({Val, Result});
187
188 addValueHandle(Val);
189 }
190
191 void insertPredecessorResults(Value *Val, BasicBlock *BB,
192 BBLatticeElementMap &PredLatticeElements) {
193 BlockCacheEntry *Entry = getOrCreateBlockEntry(BB);
194
195 Entry->PredecessorLatticeElements->insert({Val, PredLatticeElements});
196
197 addValueHandle(Val);
198 }
199
200 std::optional<BBLatticeElementMap>
201 getCachedPredecessorInfo(Value *V, BasicBlock *BB) const {
202 const BlockCacheEntry *Entry = getBlockEntry(BB);
203 if (!Entry)
204 return std::nullopt;
205
206 auto LatticeIt = Entry->PredecessorLatticeElements->find_as(V);
207 if (LatticeIt == Entry->PredecessorLatticeElements->end())
208 return std::nullopt;
209
210 return LatticeIt->second;
211 }
212
213 std::optional<ValueLatticeElement> getCachedValueInfo(Value *V,
214 BasicBlock *BB) const {
215 const BlockCacheEntry *Entry = getBlockEntry(BB);
216 if (!Entry)
217 return std::nullopt;
218
219 if (Entry->OverDefined.count(V))
221
222 auto LatticeIt = Entry->LatticeElements.find_as(V);
223 if (LatticeIt == Entry->LatticeElements.end())
224 return std::nullopt;
225
226 return LatticeIt->second;
227 }
228
229 bool
230 isNonNullAtEndOfBlock(Value *V, BasicBlock *BB,
231 function_ref<NonNullPointerSet(BasicBlock *)> InitFn) {
232 BlockCacheEntry *Entry = getOrCreateBlockEntry(BB);
233 if (!Entry->NonNullPointers) {
234 Entry->NonNullPointers = InitFn(BB);
235 for (Value *V : *Entry->NonNullPointers)
236 addValueHandle(V);
237 }
238
239 return Entry->NonNullPointers->count(V);
240 }
241
242 /// clear - Empty the cache.
243 void clear() {
244 BlockCache.clear();
245 ValueHandles.clear();
246 }
247
248 /// Inform the cache that a given value has been deleted.
249 void eraseValue(Value *V);
250
251 /// This is part of the update interface to inform the cache
252 /// that a block has been deleted.
253 void eraseBlock(BasicBlock *BB);
254
255 /// Updates the cache to remove any influence an overdefined value in
256 /// OldSucc might have (unless also overdefined in NewSucc). This just
257 /// flushes elements from the cache and does not add any.
258 void threadEdgeImpl(BasicBlock *OldSucc, BasicBlock *NewSucc);
259};
260} // namespace
261
262void LazyValueInfoCache::eraseValue(Value *V) {
263 for (auto &Elem : BlockCache) {
264 if (!Elem)
265 continue;
266
267 Elem->LatticeElements.erase(V);
268 Elem->OverDefined.erase(V);
269 if (Elem->NonNullPointers)
270 Elem->NonNullPointers->erase(V);
271 if (PerPredRanges)
272 Elem->PredecessorLatticeElements->erase(V);
273 }
274
275 auto HandleIt = ValueHandles.find_as(V);
276 if (HandleIt != ValueHandles.end())
277 ValueHandles.erase(HandleIt);
278}
279
280void LVIValueHandle::deleted() {
281 // This erasure deallocates *this, so it MUST happen after we're done
282 // using any and all members of *this.
283 Parent->eraseValue(*this);
284}
285
286void LazyValueInfoCache::eraseBlock(BasicBlock *BB) {
287 assert(BlockNumberEpoch == BB->getParent()->getBlockNumberEpoch());
288 // Clear all when a BB is removed.
289 if (PerPredRanges)
290 for (auto &Elem : BlockCache)
291 if (Elem)
292 Elem->PredecessorLatticeElements->clear();
293 if (BB->getNumber() < BlockCache.size())
294 BlockCache[BB->getNumber()].reset();
295}
296
297void LazyValueInfoCache::threadEdgeImpl(BasicBlock *OldSucc,
298 BasicBlock *NewSucc) {
299 // When an edge in the graph has been threaded, values that we could not
300 // determine a value for before (i.e. were marked overdefined) may be
301 // possible to solve now. We do NOT try to proactively update these values.
302 // Instead, we clear their entries from the cache, and allow lazy updating to
303 // recompute them when needed.
304
305 // The updating process is fairly simple: we need to drop cached info
306 // for all values that were marked overdefined in OldSucc, and for those same
307 // values in any successor of OldSucc (except NewSucc) in which they were
308 // also marked overdefined.
309 std::vector<BasicBlock*> worklist;
310 worklist.push_back(OldSucc);
311
312 const BlockCacheEntry *Entry = getBlockEntry(OldSucc);
313 if (!Entry || Entry->OverDefined.empty())
314 return; // Nothing to process here.
315 SmallVector<Value *, 4> ValsToClear(Entry->OverDefined.begin(),
316 Entry->OverDefined.end());
317
318 // Use a worklist to perform a depth-first search of OldSucc's successors.
319 // NOTE: We do not need a visited list since any blocks we have already
320 // visited will have had their overdefined markers cleared already, and we
321 // thus won't loop to their successors.
322 while (!worklist.empty()) {
323 BasicBlock *ToUpdate = worklist.back();
324 worklist.pop_back();
325
326 // Skip blocks only accessible through NewSucc.
327 if (ToUpdate == NewSucc) continue;
328
329 // If a value was marked overdefined in OldSucc, and is here too...
330 BlockCacheEntry *WorklistEntry =
331 ToUpdate->getNumber() < BlockCache.size()
332 ? BlockCache[ToUpdate->getNumber()].get()
333 : nullptr;
334 if (!WorklistEntry || WorklistEntry->OverDefined.empty())
335 continue;
336 auto &ValueSet = WorklistEntry->OverDefined;
337
338 bool changed = false;
339 for (Value *V : ValsToClear) {
340 if (!ValueSet.erase(V))
341 continue;
342
343 // If we removed anything, then we potentially need to update
344 // blocks successors too.
345 changed = true;
346 }
347
348 if (!changed) continue;
349
350 llvm::append_range(worklist, successors(ToUpdate));
351 }
352}
353
354namespace llvm {
355namespace {
356/// An assembly annotator class to print LazyValueCache information in
357/// comments.
358class LazyValueInfoAnnotatedWriter : public AssemblyAnnotationWriter {
359 LazyValueInfoImpl *LVIImpl;
360 // While analyzing which blocks we can solve values for, we need the dominator
361 // information.
362 DominatorTree &DT;
363
364public:
365 LazyValueInfoAnnotatedWriter(LazyValueInfoImpl *L, DominatorTree &DTree)
366 : LVIImpl(L), DT(DTree) {}
367
368 void emitBasicBlockStartAnnot(const BasicBlock *BB,
369 formatted_raw_ostream &OS) override;
370
371 void emitInstructionAnnot(const Instruction *I,
372 formatted_raw_ostream &OS) override;
373};
374} // namespace
375// The actual implementation of the lazy analysis and update.
377 const bool PerPredRanges;
378
379 /// Cached results from previous queries
380 LazyValueInfoCache TheCache;
381
382 /// This stack holds the state of the value solver during a query.
383 /// It basically emulates the callstack of the naive
384 /// recursive value lookup process.
386
387 /// Keeps track of which block-value pairs are in BlockValueStack.
389
390 /// Push BV onto BlockValueStack unless it's already in there.
391 /// Returns true on success.
392 bool pushBlockValue(const std::pair<BasicBlock *, Value *> &BV) {
393 if (!BlockValueSet.insert(BV).second)
394 return false; // It's already in the stack.
395
396 LLVM_DEBUG(dbgs() << "PUSH: " << *BV.second << " in "
397 << BV.first->getName() << "\n");
398 BlockValueStack.push_back(BV);
399 return true;
400 }
401
402 AssumptionCache *AC; ///< A pointer to the cache of @llvm.assume calls.
403 const DataLayout &DL; ///< A mandatory DataLayout
404
405 /// Declaration of the llvm.experimental.guard() intrinsic,
406 /// if it exists in the module.
407 Function *GuardDecl;
408
409 std::optional<ValueLatticeElement> getBlockValue(Value *Val, BasicBlock *BB,
410 Instruction *CtxI);
411 std::optional<ValueLatticeElement> getEdgeValue(Value *V, BasicBlock *F,
412 BasicBlock *T,
413 Instruction *CtxI = nullptr);
414
415 // These methods process one work item and may add more. A false value
416 // returned means that the work item was not completely processed and must
417 // be revisited after going through the new items.
418 bool solveBlockValue(Value *Val, BasicBlock *BB);
419 std::optional<ValueLatticeElement> solveBlockValueImpl(Value *Val,
420 BasicBlock *BB);
421 std::optional<ValueLatticeElement> solveBlockValueNonLocal(Value *Val,
422 BasicBlock *BB);
423 std::optional<ValueLatticeElement> solveBlockValuePHINode(PHINode *PN,
424 BasicBlock *BB);
425 std::optional<ValueLatticeElement> solveBlockValueSelect(SelectInst *S,
426 BasicBlock *BB);
427 std::optional<ConstantRange> getRangeFor(Value *V, Instruction *CtxI,
428 BasicBlock *BB);
429 std::optional<ValueLatticeElement> solveBlockValueBinaryOpImpl(
431 std::function<ConstantRange(const ConstantRange &, const ConstantRange &)>
432 OpFn);
433 std::optional<ValueLatticeElement>
434 solveBlockValueBinaryOp(BinaryOperator *BBI, BasicBlock *BB);
435 std::optional<ValueLatticeElement> solveBlockValueCast(CastInst *CI,
436 BasicBlock *BB);
437 std::optional<ValueLatticeElement>
438 solveBlockValueOverflowIntrinsic(WithOverflowInst *WO, BasicBlock *BB);
439 std::optional<ValueLatticeElement> solveBlockValueIntrinsic(IntrinsicInst *II,
440 BasicBlock *BB);
441 std::optional<ValueLatticeElement>
442 solveBlockValueInsertElement(InsertElementInst *IEI, BasicBlock *BB);
443 std::optional<ValueLatticeElement>
444 solveBlockValueExtractValue(ExtractValueInst *EVI, BasicBlock *BB);
445 bool isNonNullAtEndOfBlock(Value *Val, BasicBlock *BB);
446 void intersectAssumeOrGuardBlockValueConstantRange(Value *Val,
448 Instruction *BBI);
449
450 void solve();
451
452 // For the following methods, if UseBlockValue is true, the function may
453 // push additional values to the worklist and return nullopt. If
454 // UseBlockValue is false, it will never return nullopt.
455
456 std::optional<ValueLatticeElement>
457 getValueFromSimpleICmpCondition(CmpInst::Predicate Pred, Value *RHS,
458 const APInt &Offset, Instruction *CtxI,
459 bool UseBlockValue);
460
461 std::optional<ValueLatticeElement>
462 getValueFromICmpCondition(Value *Val, ICmpInst *ICI, bool isTrueDest,
463 bool UseBlockValue);
464 ValueLatticeElement getValueFromTrunc(Value *Val, TruncInst *Trunc,
465 bool IsTrueDest);
466
467 std::optional<ValueLatticeElement>
468 getValueFromCondition(Value *Val, Value *Cond, bool IsTrueDest,
469 bool UseBlockValue, unsigned Depth = 0);
470
471 std::optional<ValueLatticeElement> getEdgeValueLocal(Value *Val,
472 BasicBlock *BBFrom,
473 BasicBlock *BBTo,
474 bool UseBlockValue);
475
476public:
477 /// This is the query interface to determine the lattice value for the
478 /// specified Value* at the context instruction (if specified) or at the
479 /// start of the block.
481 Instruction *CtxI = nullptr);
482
483 /// This is the query interface to determine the lattice value for the
484 /// specified Value* at the specified instruction using only information
485 /// from assumes/guards and range metadata. Unlike getValueInBlock(), no
486 /// recursive query is performed.
488
489 /// This is the query interface to determine the lattice
490 /// value for the specified Value* that is true on the specified edge.
492 BasicBlock *ToBB,
493 Instruction *CtxI = nullptr);
494
495 ValueLatticeElement getValueAtUse(const Use &U, bool AssumeFrozen = false);
496
497 /// Complete flush all previously computed values
498 void clear() {
499 TheCache.clear();
500 }
501
502 /// Printing the LazyValueInfo Analysis.
504 LazyValueInfoAnnotatedWriter Writer(this, DTree);
505 F.print(OS, &Writer);
506 }
507
508 /// This is part of the update interface to remove information related to this
509 /// value from the cache.
510 void forgetValue(Value *V) { TheCache.eraseValue(V); }
511
512 /// This is part of the update interface to inform the cache
513 /// that a block has been deleted.
515 TheCache.eraseBlock(BB);
516 }
517
518 /// This is the update interface to inform the cache that an edge from
519 /// PredBB to OldSucc has been threaded to be from PredBB to NewSucc.
520 void threadEdge(BasicBlock *PredBB,BasicBlock *OldSucc,BasicBlock *NewSucc);
521
523 Function *GuardDecl)
524 : PerPredRanges(getAnalysisOptions(*F).lvi_per_pred_ranges),
525 TheCache(F, PerPredRanges), AC(AC), DL(DL), GuardDecl(GuardDecl) {}
526};
527} // namespace llvm
528
529void LazyValueInfoImpl::solve() {
531 BlockValueStack;
532
533 unsigned processedCount = 0;
534 while (!BlockValueStack.empty()) {
535 processedCount++;
536 // Abort if we have to process too many values to get a result for this one.
537 // Because of the design of the overdefined cache currently being per-block
538 // to avoid naming-related issues (IE it wants to try to give different
539 // results for the same name in different blocks), overdefined results don't
540 // get cached globally, which in turn means we will often try to rediscover
541 // the same overdefined result again and again. Once something like
542 // PredicateInfo is used in LVI or CVP, we should be able to make the
543 // overdefined cache global, and remove this throttle.
544 if (processedCount > MaxProcessedPerValue) {
546 dbgs() << "Giving up on stack because we are getting too deep\n");
547 // Fill in the original values
548 while (!StartingStack.empty()) {
549 std::pair<BasicBlock *, Value *> &e = StartingStack.back();
550 TheCache.insertResult(e.second, e.first,
552 StartingStack.pop_back();
553 }
554 BlockValueSet.clear();
555 BlockValueStack.clear();
556 return;
557 }
558 std::pair<BasicBlock *, Value *> e = BlockValueStack.back();
559 assert(BlockValueSet.count(e) && "Stack value should be in BlockValueSet!");
560 unsigned StackSize = BlockValueStack.size();
561 (void) StackSize;
562
563 if (solveBlockValue(e.second, e.first)) {
564 // The work item was completely processed.
565 assert(BlockValueStack.size() == StackSize &&
566 BlockValueStack.back() == e && "Nothing should have been pushed!");
567#ifndef NDEBUG
568 std::optional<ValueLatticeElement> BBLV =
569 TheCache.getCachedValueInfo(e.second, e.first);
570 assert(BBLV && "Result should be in cache!");
572 dbgs() << "POP " << *e.second << " in " << e.first->getName() << " = "
573 << *BBLV << "\n");
574#endif
575
576 BlockValueStack.pop_back();
577 BlockValueSet.erase(e);
578 } else {
579 // More work needs to be done before revisiting.
580 assert(BlockValueStack.size() == StackSize + 1 &&
581 "Exactly one element should have been pushed!");
582 }
583 }
584}
585
586std::optional<ValueLatticeElement>
587LazyValueInfoImpl::getBlockValue(Value *Val, BasicBlock *BB,
588 Instruction *CtxI) {
589 // If already a constant, there is nothing to compute.
590 if (Constant *VC = dyn_cast<Constant>(Val))
591 return ValueLatticeElement::get(VC);
592
593 if (std::optional<ValueLatticeElement> OptLatticeVal =
594 TheCache.getCachedValueInfo(Val, BB)) {
595 intersectAssumeOrGuardBlockValueConstantRange(Val, *OptLatticeVal, CtxI);
596 return OptLatticeVal;
597 }
598
599 // We have hit a cycle, assume overdefined.
600 if (!pushBlockValue({ BB, Val }))
602
603 // Yet to be resolved.
604 return std::nullopt;
605}
606
608 switch (BBI->getOpcode()) {
609 default:
610 break;
611 case Instruction::Call:
612 case Instruction::Invoke:
613 if (std::optional<ConstantRange> Range = cast<CallBase>(BBI)->getRange())
615 [[fallthrough]];
616 case Instruction::Load:
617 if (MDNode *Ranges = BBI->getMetadata(LLVMContext::MD_range))
618 if (isa<IntegerType>(BBI->getType())) {
621 }
622 break;
623 };
624 // Nothing known - will be intersected with other facts
626}
627
628bool LazyValueInfoImpl::solveBlockValue(Value *Val, BasicBlock *BB) {
629 assert(!isa<Constant>(Val) && "Value should not be constant");
630 assert(!TheCache.getCachedValueInfo(Val, BB) &&
631 "Value should not be in cache");
632
633 // Hold off inserting this value into the Cache in case we have to return
634 // false and come back later.
635 std::optional<ValueLatticeElement> Res = solveBlockValueImpl(Val, BB);
636 if (!Res)
637 // Work pushed, will revisit
638 return false;
639
640 TheCache.insertResult(Val, BB, *Res);
641 return true;
642}
643
644std::optional<ValueLatticeElement>
645LazyValueInfoImpl::solveBlockValueImpl(Value *Val, BasicBlock *BB) {
647 if (!BBI || BBI->getParent() != BB)
648 return solveBlockValueNonLocal(Val, BB);
649
650 if (PHINode *PN = dyn_cast<PHINode>(BBI))
651 return solveBlockValuePHINode(PN, BB);
652
653 if (auto *SI = dyn_cast<SelectInst>(BBI))
654 return solveBlockValueSelect(SI, BB);
655
656 // If this value is a nonnull pointer, record it's range and bailout. Note
657 // that for all other pointer typed values, we terminate the search at the
658 // definition. We could easily extend this to look through geps, bitcasts,
659 // and the like to prove non-nullness, but it's not clear that's worth it
660 // compile time wise. The context-insensitive value walk done inside
661 // isKnownNonZero gets most of the profitable cases at much less expense.
662 // This does mean that we have a sensitivity to where the defining
663 // instruction is placed, even if it could legally be hoisted much higher.
664 // That is unfortunate.
666 if (PT && isKnownNonZero(BBI, DL))
668
669 if (BBI->getType()->isIntOrIntVectorTy()) {
670 if (auto *CI = dyn_cast<CastInst>(BBI))
671 return solveBlockValueCast(CI, BB);
672
673 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(BBI))
674 return solveBlockValueBinaryOp(BO, BB);
675
676 if (auto *IEI = dyn_cast<InsertElementInst>(BBI))
677 return solveBlockValueInsertElement(IEI, BB);
678
679 if (auto *EVI = dyn_cast<ExtractValueInst>(BBI))
680 return solveBlockValueExtractValue(EVI, BB);
681
682 if (auto *II = dyn_cast<IntrinsicInst>(BBI))
683 return solveBlockValueIntrinsic(II, BB);
684 }
685
686 LLVM_DEBUG(dbgs() << " compute BB '" << BB->getName()
687 << "' - unknown inst def found.\n");
688 return getFromRangeMetadata(BBI);
689}
690
691static void AddNonNullPointer(Value *Ptr, NonNullPointerSet &PtrSet,
692 bool IsDereferenced = true) {
693 // TODO: Use NullPointerIsDefined instead.
694 if (Ptr->getType()->getPointerAddressSpace() == 0)
695 PtrSet.insert(IsDereferenced ? getUnderlyingObject(Ptr)
696 : Ptr->stripInBoundsOffsets());
697}
698
700 Instruction *I, NonNullPointerSet &PtrSet) {
701 if (LoadInst *L = dyn_cast<LoadInst>(I)) {
702 AddNonNullPointer(L->getPointerOperand(), PtrSet);
703 } else if (StoreInst *S = dyn_cast<StoreInst>(I)) {
704 AddNonNullPointer(S->getPointerOperand(), PtrSet);
705 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) {
706 if (MI->isVolatile()) return;
707
708 // FIXME: check whether it has a valuerange that excludes zero?
709 ConstantInt *Len = dyn_cast<ConstantInt>(MI->getLength());
710 if (!Len || Len->isZero()) return;
711
712 AddNonNullPointer(MI->getRawDest(), PtrSet);
714 AddNonNullPointer(MTI->getRawSource(), PtrSet);
715 } else if (auto *CB = dyn_cast<CallBase>(I)) {
716 for (auto &U : CB->args()) {
717 if (U->getType()->isPointerTy() &&
718 CB->paramHasNonNullAttr(CB->getArgOperandNo(&U),
719 /*AllowUndefOrPoison=*/false))
720 AddNonNullPointer(U.get(), PtrSet, /*IsDereferenced=*/false);
721 }
722 }
723}
724
725bool LazyValueInfoImpl::isNonNullAtEndOfBlock(Value *Val, BasicBlock *BB) {
728 return false;
729
730 Val = Val->stripInBoundsOffsets();
731 return TheCache.isNonNullAtEndOfBlock(Val, BB, [](BasicBlock *BB) {
732 NonNullPointerSet NonNullPointers;
733 for (Instruction &I : *BB)
734 AddNonNullPointersByInstruction(&I, NonNullPointers);
735 return NonNullPointers;
736 });
737}
738
739std::optional<ValueLatticeElement>
740LazyValueInfoImpl::solveBlockValueNonLocal(Value *Val, BasicBlock *BB) {
741 ValueLatticeElement Result; // Start Undefined.
742
743 // If this is the entry block, we must be asking about an argument.
744 if (BB->isEntryBlock()) {
745 assert(isa<Argument>(Val) && "Unknown live-in to the entry block");
746 if (std::optional<ConstantRange> Range = cast<Argument>(Val)->getRange())
749 }
750
751 // Loop over all of our predecessors, merging what we know from them into
752 // result. If we encounter an unexplored predecessor, we eagerly explore it
753 // in a depth first manner. In practice, this has the effect of discovering
754 // paths we can't analyze eagerly without spending compile times analyzing
755 // other paths. This heuristic benefits from the fact that predecessors are
756 // frequently arranged such that dominating ones come first and we quickly
757 // find a path to function entry. TODO: We should consider explicitly
758 // canonicalizing to make this true rather than relying on this happy
759 // accident.
760 std::optional<BBLatticeElementMap> PredLatticeElements;
761 if (PerPredRanges)
762 PredLatticeElements = std::make_optional<BBLatticeElementMap>();
763 for (BasicBlock *Pred : predecessors(BB)) {
764 // Skip self loops.
765 if (Pred == BB)
766 continue;
767 std::optional<ValueLatticeElement> EdgeResult = getEdgeValue(Val, Pred, BB);
768 if (!EdgeResult)
769 // Explore that input, then return here
770 return std::nullopt;
771
772 Result.mergeIn(*EdgeResult);
773
774 // If we hit overdefined, exit early. The BlockVals entry is already set
775 // to overdefined.
776 if (Result.isOverdefined()) {
777 LLVM_DEBUG(dbgs() << " compute BB '" << BB->getName()
778 << "' - overdefined because of pred '"
779 << Pred->getName() << "' (non local).\n");
780 return Result;
781 }
782 if (PerPredRanges)
783 PredLatticeElements->insert({Pred, *EdgeResult});
784 }
785
786 if (PerPredRanges)
787 TheCache.insertPredecessorResults(Val, BB, *PredLatticeElements);
788
789 // Return the merged value, which is more precise than 'overdefined'.
790 assert(!Result.isOverdefined());
791 return Result;
792}
793
794std::optional<ValueLatticeElement>
795LazyValueInfoImpl::solveBlockValuePHINode(PHINode *PN, BasicBlock *BB) {
796 ValueLatticeElement Result; // Start Undefined.
797
798 // Loop over all of our predecessors, merging what we know from them into
799 // result. See the comment about the chosen traversal order in
800 // solveBlockValueNonLocal; the same reasoning applies here.
801 std::optional<BBLatticeElementMap> PredLatticeElements;
802 if (PerPredRanges)
803 PredLatticeElements = std::make_optional<BBLatticeElementMap>();
804 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
805 BasicBlock *PhiBB = PN->getIncomingBlock(i);
806 Value *PhiVal = PN->getIncomingValue(i);
807 // Note that we can provide PN as the context value to getEdgeValue, even
808 // though the results will be cached, because PN is the value being used as
809 // the cache key in the caller.
810 std::optional<ValueLatticeElement> EdgeResult =
811 getEdgeValue(PhiVal, PhiBB, BB, PN);
812 if (!EdgeResult)
813 // Explore that input, then return here
814 return std::nullopt;
815
816 Result.mergeIn(*EdgeResult);
817
818 // If we hit overdefined, exit early. The BlockVals entry is already set
819 // to overdefined.
820 if (Result.isOverdefined()) {
821 LLVM_DEBUG(dbgs() << " compute BB '" << BB->getName()
822 << "' - overdefined because of pred (local).\n");
823
824 return Result;
825 }
826
827 if (PerPredRanges)
828 PredLatticeElements->insert({PhiBB, *EdgeResult});
829 }
830
831 if (PerPredRanges)
832 TheCache.insertPredecessorResults(PN, BB, *PredLatticeElements);
833
834 // Return the merged value, which is more precise than 'overdefined'.
835 assert(!Result.isOverdefined() && "Possible PHI in entry block?");
836 return Result;
837}
838
839// If we can determine a constraint on the value given conditions assumed by
840// the program, intersect those constraints with BBLV
841void LazyValueInfoImpl::intersectAssumeOrGuardBlockValueConstantRange(
842 Value *Val, ValueLatticeElement &BBLV, Instruction *BBI) {
843 BBI = BBI ? BBI : dyn_cast<Instruction>(Val);
844 if (!BBI)
845 return;
846
847 BasicBlock *BB = BBI->getParent();
848 for (auto &AssumeVH : AC->assumptionsFor(Val)) {
849 if (!AssumeVH)
850 continue;
851
852 // Only check assumes in the block of the context instruction. Other
853 // assumes will have already been taken into account when the value was
854 // propagated from predecessor blocks.
855 auto *I = cast<AssumeInst>(AssumeVH);
856
857 if (I->getParent() != BB || !isValidAssumeForContext(I, BBI))
858 continue;
859
860 if (AssumeVH.Index != AssumptionCache::ExprResultIdx) {
861 auto OBU = I->getOperandBundleAt(AssumeVH.Index);
862 switch (getBundleAttrFromOBU(OBU)) {
863 case BundleAttr::Range: {
864 auto [V, Range] = getAssumeRangeInfo(OBU);
865 if (Val == V) {
866 BBLV =
868 }
869 } break;
870 default:
872 I->getOperandBundleAt(AssumeVH.Index)))
875 }
876 } else {
877 BBLV = BBLV.intersect(*getValueFromCondition(Val, I->getArgOperand(0),
878 /*IsTrueDest*/ true,
879 /*UseBlockValue*/ false));
880 }
881 }
882
883 // If guards are not used in the module, don't spend time looking for them
884 if (GuardDecl && !GuardDecl->use_empty() &&
885 BBI->getIterator() != BB->begin()) {
886 for (Instruction &I :
887 make_range(std::next(BBI->getIterator().getReverse()), BB->rend())) {
888 Value *Cond = nullptr;
890 BBLV = BBLV.intersect(*getValueFromCondition(Val, Cond,
891 /*IsTrueDest*/ true,
892 /*UseBlockValue*/ false));
893 }
894 }
895
896 if (BBLV.isOverdefined()) {
897 // Check whether we're checking at the terminator, and the pointer has
898 // been dereferenced in this block.
900 if (PTy && BB->getTerminator() == BBI &&
901 isNonNullAtEndOfBlock(Val, BB))
903 }
904}
905
906std::optional<ValueLatticeElement>
907LazyValueInfoImpl::solveBlockValueSelect(SelectInst *SI, BasicBlock *BB) {
908 // Recurse on our inputs if needed
909 std::optional<ValueLatticeElement> OptTrueVal =
910 getBlockValue(SI->getTrueValue(), BB, SI);
911 if (!OptTrueVal)
912 return std::nullopt;
913 ValueLatticeElement &TrueVal = *OptTrueVal;
914
915 std::optional<ValueLatticeElement> OptFalseVal =
916 getBlockValue(SI->getFalseValue(), BB, SI);
917 if (!OptFalseVal)
918 return std::nullopt;
919 ValueLatticeElement &FalseVal = *OptFalseVal;
920
921 if (TrueVal.isConstantRange() || FalseVal.isConstantRange()) {
922 const ConstantRange &TrueCR = TrueVal.asConstantRange(SI->getType());
923 const ConstantRange &FalseCR = FalseVal.asConstantRange(SI->getType());
924 Value *LHS = nullptr;
925 Value *RHS = nullptr;
926 SelectPatternResult SPR = matchSelectPattern(SI, LHS, RHS);
927 // Is this a min specifically of our two inputs? (Avoid the risk of
928 // ValueTracking getting smarter looking back past our immediate inputs.)
930 ((LHS == SI->getTrueValue() && RHS == SI->getFalseValue()) ||
931 (RHS == SI->getTrueValue() && LHS == SI->getFalseValue()))) {
932 ConstantRange ResultCR = [&]() {
933 switch (SPR.Flavor) {
934 default:
935 llvm_unreachable("unexpected minmax type!");
936 case SPF_SMIN: /// Signed minimum
937 return TrueCR.smin(FalseCR);
938 case SPF_UMIN: /// Unsigned minimum
939 return TrueCR.umin(FalseCR);
940 case SPF_SMAX: /// Signed maximum
941 return TrueCR.smax(FalseCR);
942 case SPF_UMAX: /// Unsigned maximum
943 return TrueCR.umax(FalseCR);
944 };
945 }();
947 ResultCR, TrueVal.isConstantRangeIncludingUndef() ||
948 FalseVal.isConstantRangeIncludingUndef());
949 }
950
951 if (SPR.Flavor == SPF_ABS) {
952 if (LHS == SI->getTrueValue())
954 TrueCR.abs(), TrueVal.isConstantRangeIncludingUndef());
955 if (LHS == SI->getFalseValue())
957 FalseCR.abs(), FalseVal.isConstantRangeIncludingUndef());
958 }
959
960 if (SPR.Flavor == SPF_NABS) {
961 ConstantRange Zero(APInt::getZero(TrueCR.getBitWidth()));
962 if (LHS == SI->getTrueValue())
964 Zero.sub(TrueCR.abs()), FalseVal.isConstantRangeIncludingUndef());
965 if (LHS == SI->getFalseValue())
967 Zero.sub(FalseCR.abs()), FalseVal.isConstantRangeIncludingUndef());
968 }
969 }
970
971 // Can we constrain the facts about the true and false values by using the
972 // condition itself? This shows up with idioms like e.g. select(a > 5, a, 5).
973 // TODO: We could potentially refine an overdefined true value above.
974 Value *Cond = SI->getCondition();
975 // If the value is undef, a different value may be chosen in
976 // the select condition.
978 TrueVal =
979 TrueVal.intersect(*getValueFromCondition(SI->getTrueValue(), Cond,
980 /*IsTrueDest*/ true,
981 /*UseBlockValue*/ false));
982 FalseVal =
983 FalseVal.intersect(*getValueFromCondition(SI->getFalseValue(), Cond,
984 /*IsTrueDest*/ false,
985 /*UseBlockValue*/ false));
986 }
987
988 TrueVal.mergeIn(FalseVal);
989 return TrueVal;
990}
991
992std::optional<ConstantRange>
993LazyValueInfoImpl::getRangeFor(Value *V, Instruction *CtxI, BasicBlock *BB) {
994 std::optional<ValueLatticeElement> OptVal = getBlockValue(V, BB, CtxI);
995 if (!OptVal)
996 return std::nullopt;
997 return OptVal->asConstantRange(V->getType());
998}
999
1000std::optional<ValueLatticeElement>
1001LazyValueInfoImpl::solveBlockValueCast(CastInst *CI, BasicBlock *BB) {
1002 // Filter out casts we don't know how to reason about before attempting to
1003 // recurse on our operand. This can cut a long search short if we know we're
1004 // not going to be able to get any useful information anways.
1005 switch (CI->getOpcode()) {
1006 case Instruction::Trunc:
1007 case Instruction::SExt:
1008 case Instruction::ZExt:
1009 break;
1010 default:
1011 // Unhandled instructions are overdefined.
1012 LLVM_DEBUG(dbgs() << " compute BB '" << BB->getName()
1013 << "' - overdefined (unknown cast).\n");
1015 }
1016
1017 // Figure out the range of the LHS. If that fails, we still apply the
1018 // transfer rule on the full set since we may be able to locally infer
1019 // interesting facts.
1020 std::optional<ConstantRange> LHSRes = getRangeFor(CI->getOperand(0), CI, BB);
1021 if (!LHSRes)
1022 // More work to do before applying this transfer rule.
1023 return std::nullopt;
1024 const ConstantRange &LHSRange = *LHSRes;
1025
1026 const unsigned ResultBitWidth = CI->getType()->getScalarSizeInBits();
1027
1028 // NOTE: We're currently limited by the set of operations that ConstantRange
1029 // can evaluate symbolically. Enhancing that set will allows us to analyze
1030 // more definitions.
1031 ConstantRange Res = ConstantRange::getEmpty(ResultBitWidth);
1032 if (auto *Trunc = dyn_cast<TruncInst>(CI))
1033 Res = LHSRange.truncate(ResultBitWidth, Trunc->getNoWrapKind());
1034 else
1035 Res = LHSRange.castOp(CI->getOpcode(), ResultBitWidth);
1036
1038}
1039
1040std::optional<ValueLatticeElement>
1041LazyValueInfoImpl::solveBlockValueBinaryOpImpl(
1042 Instruction *I, BasicBlock *BB,
1043 std::function<ConstantRange(const ConstantRange &, const ConstantRange &)>
1044 OpFn) {
1045 Value *LHS = I->getOperand(0);
1046 Value *RHS = I->getOperand(1);
1047
1048 auto ThreadBinOpOverSelect =
1049 [&](Value *X, const ConstantRange &CRX, SelectInst *Y,
1050 bool XIsLHS) -> std::optional<ValueLatticeElement> {
1051 Value *Cond = Y->getCondition();
1052 // Only handle selects with constant values.
1053 Constant *TrueC = dyn_cast<Constant>(Y->getTrueValue());
1054 if (!TrueC)
1055 return std::nullopt;
1056 Constant *FalseC = dyn_cast<Constant>(Y->getFalseValue());
1057 if (!FalseC)
1058 return std::nullopt;
1060 return std::nullopt;
1061
1062 ConstantRange TrueX =
1063 CRX.intersectWith(getValueFromCondition(X, Cond, /*CondIsTrue=*/true,
1064 /*UseBlockValue=*/false)
1065 ->asConstantRange(X->getType()));
1066 ConstantRange FalseX =
1067 CRX.intersectWith(getValueFromCondition(X, Cond, /*CondIsTrue=*/false,
1068 /*UseBlockValue=*/false)
1069 ->asConstantRange(X->getType()));
1070 ConstantRange TrueY = TrueC->toConstantRange();
1071 ConstantRange FalseY = FalseC->toConstantRange();
1072
1073 if (XIsLHS)
1075 OpFn(TrueX, TrueY).unionWith(OpFn(FalseX, FalseY)));
1077 OpFn(TrueY, TrueX).unionWith(OpFn(FalseY, FalseX)));
1078 };
1079
1080 // Figure out the ranges of the operands. If that fails, use a
1081 // conservative range, but apply the transfer rule anyways. This
1082 // lets us pick up facts from expressions like "and i32 (call i32
1083 // @foo()), 32"
1084 std::optional<ConstantRange> LHSRes = getRangeFor(LHS, I, BB);
1085 if (!LHSRes)
1086 return std::nullopt;
1087
1088 // Try to thread binop over rhs select
1089 if (auto *SI = dyn_cast<SelectInst>(RHS)) {
1090 if (auto Res = ThreadBinOpOverSelect(LHS, *LHSRes, SI, /*XIsLHS=*/true))
1091 return *Res;
1092 }
1093
1094 std::optional<ConstantRange> RHSRes = getRangeFor(RHS, I, BB);
1095 if (!RHSRes)
1096 return std::nullopt;
1097
1098 // Try to thread binop over lhs select
1099 if (auto *SI = dyn_cast<SelectInst>(LHS)) {
1100 if (auto Res = ThreadBinOpOverSelect(RHS, *RHSRes, SI, /*XIsLHS=*/false))
1101 return *Res;
1102 }
1103
1104 const ConstantRange &LHSRange = *LHSRes;
1105 const ConstantRange &RHSRange = *RHSRes;
1106
1107 std::optional<ValueLatticeElement> MergedResult =
1108 ValueLatticeElement::getRange(OpFn(LHSRange, RHSRange));
1109
1110 if (!PerPredRanges)
1111 return MergedResult;
1112
1113 std::optional<BBLatticeElementMap> PredLHS =
1114 TheCache.getCachedPredecessorInfo(LHS, BB);
1115 if (!PredLHS)
1116 return MergedResult;
1117 std::optional<BBLatticeElementMap> PredRHS =
1118 TheCache.getCachedPredecessorInfo(RHS, BB);
1119 if (!PredRHS)
1120 return MergedResult;
1121
1122 const BBLatticeElementMap &LHSPredMap = *PredLHS;
1123 const BBLatticeElementMap &RHSPredMap = *PredRHS;
1124
1125 BBLatticeElementMap PredLatticeElements;
1126 ValueLatticeElement OverallPredResult;
1127 for (auto *Pred : predecessors(BB)) {
1128 auto LHSIt = LHSPredMap.find_as(Pred);
1129 if (LHSIt == LHSPredMap.end())
1130 return MergedResult;
1131 const ValueLatticeElement &LHSFromPred = LHSIt->second;
1132 std::optional<ConstantRange> LHSFromPredRes =
1133 LHSFromPred.asConstantRange(LHS->getType());
1134 if (!LHSFromPredRes)
1135 return MergedResult;
1136
1137 auto RHSIt = RHSPredMap.find_as(Pred);
1138 if (RHSIt == RHSPredMap.end())
1139 return MergedResult;
1140 const ValueLatticeElement &RHSFromPred = RHSIt->second;
1141 std::optional<ConstantRange> RHSFromPredRes =
1142 RHSFromPred.asConstantRange(RHS->getType());
1143 if (!RHSFromPredRes)
1144 return MergedResult;
1145
1146 const ConstantRange &LHSFromPredRange = *LHSFromPredRes;
1147 const ConstantRange &RHSFromPredRange = *RHSFromPredRes;
1148 std::optional<ValueLatticeElement> PredResult =
1149 ValueLatticeElement::getRange(OpFn(LHSFromPredRange, RHSFromPredRange));
1150 if (!PredResult)
1151 return MergedResult;
1152 if (PredResult->isOverdefined()) {
1153 LLVM_DEBUG(
1154 dbgs() << " pred BB '" << Pred->getName() << "' for BB '"
1155 << BB->getName()
1156 << "' overdefined. Discarding all predecessor intervals.\n");
1157 return MergedResult;
1158 }
1159 PredLatticeElements.insert({Pred, *PredResult});
1160 OverallPredResult.mergeIn(*PredResult);
1161 }
1162
1163 // If this point is reached, all predecessors for both LHS and RHS have
1164 // constant ranges previously computed. Can cache result and use the
1165 // OverallPredResult;
1166 TheCache.insertPredecessorResults(I, BB, PredLatticeElements);
1167
1168 LLVM_DEBUG(dbgs() << " Using predecessor intervals, evaluated " << *I
1169 << " to: " << OverallPredResult << ".\n");
1170
1171 if (!MergedResult)
1172 return OverallPredResult;
1173
1174 LLVM_DEBUG(dbgs() << " Intersecting intervals for " << *I << ": "
1175 << OverallPredResult << " and " << MergedResult << ".\n");
1176 return MergedResult->intersect(OverallPredResult);
1177}
1178
1179std::optional<ValueLatticeElement>
1180LazyValueInfoImpl::solveBlockValueBinaryOp(BinaryOperator *BO, BasicBlock *BB) {
1181 assert(BO->getOperand(0)->getType()->isSized() &&
1182 "all operands to binary operators are sized");
1183
1184 return solveBlockValueBinaryOpImpl(
1185 BO, BB, [BO](const ConstantRange &CR1, const ConstantRange &CR2) {
1186 return CR1.binaryOp(*BO, CR2);
1187 });
1188}
1189
1190std::optional<ValueLatticeElement>
1191LazyValueInfoImpl::solveBlockValueOverflowIntrinsic(WithOverflowInst *WO,
1192 BasicBlock *BB) {
1193 return solveBlockValueBinaryOpImpl(
1194 WO, BB, [WO](const ConstantRange &CR1, const ConstantRange &CR2) {
1195 return CR1.binaryOp(WO->getBinaryOp(), CR2);
1196 });
1197}
1198
1199std::optional<ValueLatticeElement>
1200LazyValueInfoImpl::solveBlockValueIntrinsic(IntrinsicInst *II, BasicBlock *BB) {
1201 ValueLatticeElement MetadataVal = getFromRangeMetadata(II);
1202 if (!ConstantRange::isIntrinsicSupported(II->getIntrinsicID())) {
1203 LLVM_DEBUG(dbgs() << " compute BB '" << BB->getName()
1204 << "' - unknown intrinsic.\n");
1205 return MetadataVal;
1206 }
1207
1209 for (Value *Op : II->args()) {
1210 std::optional<ConstantRange> Range = getRangeFor(Op, II, BB);
1211 if (!Range)
1212 return std::nullopt;
1213 OpRanges.push_back(*Range);
1214 }
1215
1217 ConstantRange::intrinsic(II->getIntrinsicID(), OpRanges))
1218 .intersect(MetadataVal);
1219}
1220
1221std::optional<ValueLatticeElement>
1222LazyValueInfoImpl::solveBlockValueInsertElement(InsertElementInst *IEI,
1223 BasicBlock *BB) {
1224 std::optional<ValueLatticeElement> OptEltVal =
1225 getBlockValue(IEI->getOperand(1), BB, IEI);
1226 if (!OptEltVal)
1227 return std::nullopt;
1228 ValueLatticeElement &Res = *OptEltVal;
1229
1230 std::optional<ValueLatticeElement> OptVecVal =
1231 getBlockValue(IEI->getOperand(0), BB, IEI);
1232 if (!OptVecVal)
1233 return std::nullopt;
1234
1235 // Bail out if the inserted element is a constant expression. Unlike other
1236 // ValueLattice types, these are not considered an implicit splat when a
1237 // vector type is used.
1238 // We could call ConstantFoldInsertElementInstruction here to handle these.
1239 if (OptEltVal->isConstant())
1241
1242 Res.mergeIn(*OptVecVal);
1243 return Res;
1244}
1245
1246std::optional<ValueLatticeElement>
1247LazyValueInfoImpl::solveBlockValueExtractValue(ExtractValueInst *EVI,
1248 BasicBlock *BB) {
1249 if (auto *WO = dyn_cast<WithOverflowInst>(EVI->getAggregateOperand()))
1250 if (EVI->getNumIndices() == 1 && *EVI->idx_begin() == 0)
1251 return solveBlockValueOverflowIntrinsic(WO, BB);
1252
1253 // Handle extractvalue of insertvalue to allow further simplification
1254 // based on replaced with.overflow intrinsics.
1256 EVI->getAggregateOperand(), EVI->getIndices(),
1257 EVI->getDataLayout()))
1258 return getBlockValue(V, BB, EVI);
1259
1260 LLVM_DEBUG(dbgs() << " compute BB '" << BB->getName()
1261 << "' - overdefined (unknown extractvalue).\n");
1263}
1264
1267 if (LHS == Val)
1268 return true;
1269
1270 // Handle range checking idiom produced by InstCombine. We will subtract the
1271 // offset from the allowed range for RHS in this case.
1272 const APInt *C;
1273 if (match(LHS, m_AddLike(m_Specific(Val), m_APInt(C)))) {
1274 Offset = *C;
1275 return true;
1276 }
1277
1278 // Handle the symmetric case. This appears in saturation patterns like
1279 // (x == 16) ? 16 : (x + 1).
1280 if (match(Val, m_AddLike(m_Specific(LHS), m_APInt(C)))) {
1281 Offset = -*C;
1282 return true;
1283 }
1284
1285 // If (x | y) < C, then (x < C) && (y < C).
1286 if (match(LHS, m_c_Or(m_Specific(Val), m_Value())) &&
1288 return true;
1289
1290 // If (x & y) > C, then (x > C) && (y > C).
1291 if (match(LHS, m_c_And(m_Specific(Val), m_Value())) &&
1293 return true;
1294
1295 return false;
1296}
1297
1298/// Get value range for a "(Val + Offset) Pred RHS" condition.
1299std::optional<ValueLatticeElement>
1300LazyValueInfoImpl::getValueFromSimpleICmpCondition(CmpInst::Predicate Pred,
1301 Value *RHS,
1302 const APInt &Offset,
1303 Instruction *CtxI,
1304 bool UseBlockValue) {
1305 ConstantRange RHSRange(RHS->getType()->getScalarSizeInBits(),
1306 /*isFullSet=*/true);
1307 if (auto *C = dyn_cast<Constant>(RHS)) {
1308 RHSRange = C->toConstantRange();
1309 } else if (UseBlockValue) {
1310 std::optional<ValueLatticeElement> R =
1311 getBlockValue(RHS, CtxI->getParent(), CtxI);
1312 if (!R)
1313 return std::nullopt;
1314 RHSRange = R->asConstantRange(RHS->getType());
1315 }
1316
1317 ConstantRange TrueValues =
1319 return ValueLatticeElement::getRange(TrueValues.subtract(Offset));
1320}
1321
1322static std::optional<ConstantRange>
1324 function_ref<std::optional<ConstantRange>(const APInt &)> Fn) {
1325 bool Invert = false;
1328 Invert = true;
1329 }
1330 if (Pred == ICmpInst::ICMP_SLE) {
1332 if (RHS.isMaxSignedValue())
1333 return std::nullopt; // Could also return full/empty here, if we wanted.
1334 ++RHS;
1335 }
1336 assert(Pred == ICmpInst::ICMP_SLT && "Must be signed predicate");
1337 if (auto CR = Fn(RHS))
1338 return Invert ? CR->inverse() : CR;
1339 return std::nullopt;
1340}
1341
1342/// Get value range for a "ctpop(Val) Pred RHS" condition.
1344 Value *RHS) {
1345 unsigned BitWidth = RHS->getType()->getScalarSizeInBits();
1346
1347 auto *RHSConst = dyn_cast<ConstantInt>(RHS);
1348 if (!RHSConst)
1350
1351 ConstantRange ResValRange =
1352 ConstantRange::makeExactICmpRegion(Pred, RHSConst->getValue());
1353
1354 unsigned ResMin = ResValRange.getUnsignedMin().getLimitedValue(BitWidth);
1355 unsigned ResMax = ResValRange.getUnsignedMax().getLimitedValue(BitWidth);
1356
1357 APInt ValMin = APInt::getLowBitsSet(BitWidth, ResMin);
1358 APInt ValMax = APInt::getHighBitsSet(BitWidth, ResMax);
1360 ConstantRange::getNonEmpty(std::move(ValMin), ValMax + 1));
1361}
1362
1363/// Get the unsigned range for \p V from a `mul nuw V, V` comparison.
1364static std::optional<ConstantRange>
1366 const Value *LHS, const Value *RHS) {
1367 if (!V->getType()->isIntegerTy())
1368 return std::nullopt;
1369
1370 if (!match(LHS, m_NUWMul(m_Specific(V), m_Specific(V)))) {
1372 return std::nullopt;
1373
1375 RHS = LHS;
1376 }
1377
1378 ConstantRange MulCR =
1379 ConstantRange::getFull(V->getType()->getScalarSizeInBits());
1380 const APInt *C;
1381 if (match(RHS, m_APInt(C)))
1383
1384 ConstantRange Res = MulCR.sqrtFloor();
1385 if (Res.isFullSet())
1386 return std::nullopt;
1387 return Res;
1388}
1389
1390std::optional<ValueLatticeElement> LazyValueInfoImpl::getValueFromICmpCondition(
1391 Value *Val, ICmpInst *ICI, bool isTrueDest, bool UseBlockValue) {
1392 Value *LHS = ICI->getOperand(0);
1393 Value *RHS = ICI->getOperand(1);
1394
1395 // Get the predicate that must hold along the considered edge.
1396 CmpInst::Predicate EdgePred =
1397 isTrueDest ? ICI->getPredicate() : ICI->getInversePredicate();
1398
1399 if (isa<Constant>(RHS)) {
1400 if (ICI->isEquality() && LHS == Val) {
1401 if (EdgePred == ICmpInst::ICMP_EQ) {
1403 // Record the fact that the constant ptr may have different provenance.
1404 if (Val->getType()->isPtrOrPtrVectorTy())
1405 Result.setMayHaveDifferentProvenance(true);
1406 return Result;
1407 }
1408 if (!isa<UndefValue>(RHS))
1410 }
1411 }
1412
1413 Type *Ty = Val->getType();
1414 if (!Ty->isIntOrIntVectorTy())
1416
1417 unsigned BitWidth = Ty->getScalarSizeInBits();
1418 if (auto Range = getRangeForNUWMulSquare(Val, EdgePred, LHS, RHS))
1420
1421 APInt Offset(BitWidth, 0);
1422 if (matchICmpOperand(Offset, LHS, Val, EdgePred))
1423 return getValueFromSimpleICmpCondition(EdgePred, RHS, Offset, ICI,
1424 UseBlockValue);
1425
1426 CmpInst::Predicate SwappedPred = CmpInst::getSwappedPredicate(EdgePred);
1427 if (matchICmpOperand(Offset, RHS, Val, SwappedPred))
1428 return getValueFromSimpleICmpCondition(SwappedPred, LHS, Offset, ICI,
1429 UseBlockValue);
1430
1431 if (match(LHS, m_Ctpop(m_Specific(Val))))
1432 return getValueFromICmpCtpop(EdgePred, RHS);
1433
1434 const APInt *Mask, *C;
1435 if (match(LHS, m_And(m_Specific(Val), m_APInt(Mask))) &&
1436 match(RHS, m_APInt(C))) {
1437 // If (Val & Mask) == C then all the masked bits are known and we can
1438 // compute a value range based on that.
1439 if (EdgePred == ICmpInst::ICMP_EQ) {
1440 KnownBits Known;
1441 Known.Zero = ~*C & *Mask;
1442 Known.One = *C & *Mask;
1444 ConstantRange::fromKnownBits(Known, /*IsSigned*/ false));
1445 }
1446
1447 if (EdgePred == ICmpInst::ICMP_NE)
1450 }
1451
1452 // If (X urem Modulus) >= C, then X >= C.
1453 // If trunc X >= C, then X >= C.
1454 // TODO: An upper bound could be computed as well.
1456 m_Trunc(m_Specific(Val)))) &&
1457 match(RHS, m_APInt(C))) {
1458 // Use the icmp region so we don't have to deal with different predicates.
1459 ConstantRange CR = ConstantRange::makeExactICmpRegion(EdgePred, *C);
1460 if (!CR.isEmptySet())
1462 CR.getUnsignedMin().zext(BitWidth), APInt(BitWidth, 0)));
1463 }
1464
1465 // Recognize:
1466 // icmp slt (ashr X, ShAmtC), C --> icmp slt X, C << ShAmtC
1467 // Preconditions: (C << ShAmtC) >> ShAmtC == C
1468 const APInt *ShAmtC;
1469 if (CmpInst::isSigned(EdgePred) &&
1470 match(LHS, m_AShr(m_Specific(Val), m_APInt(ShAmtC))) &&
1471 match(RHS, m_APInt(C))) {
1472 auto CR = getRangeViaSLT(
1473 EdgePred, *C, [&](const APInt &RHS) -> std::optional<ConstantRange> {
1474 APInt New = RHS << *ShAmtC;
1475 if ((New.ashr(*ShAmtC)) != RHS)
1476 return std::nullopt;
1478 APInt::getSignedMinValue(New.getBitWidth()), New);
1479 });
1480 if (CR)
1482 }
1483
1484 // a - b or ptrtoint(a) - ptrtoint(b) ==/!= 0 if a ==/!= b
1485 Value *X, *Y;
1486 if (ICI->isEquality() && match(Val, m_Sub(m_Value(X), m_Value(Y)))) {
1487 // Peek through ptrtoints
1490 if ((X == LHS && Y == RHS) || (X == RHS && Y == LHS)) {
1491 Constant *NullVal = Constant::getNullValue(Val->getType());
1492 if (EdgePred == ICmpInst::ICMP_EQ)
1493 return ValueLatticeElement::get(NullVal);
1494 return ValueLatticeElement::getNot(NullVal);
1495 }
1496 }
1497
1499}
1500
1501ValueLatticeElement LazyValueInfoImpl::getValueFromTrunc(Value *Val,
1503 bool IsTrueDest) {
1504 assert(Trunc->getType()->isIntOrIntVectorTy(1));
1505
1506 if (Trunc->getOperand(0) != Val)
1508
1509 Type *Ty = Val->getType();
1510
1511 if (Trunc->hasNoUnsignedWrap()) {
1512 if (IsTrueDest)
1513 return ValueLatticeElement::get(ConstantInt::get(Ty, 1));
1515 }
1516
1517 if (IsTrueDest)
1520}
1521
1522// Handle conditions of the form
1523// extractvalue(op.with.overflow(%x, C), 1).
1525 Value *Val, WithOverflowInst *WO, bool IsTrueDest) {
1526 // TODO: This only works with a constant RHS for now. We could also compute
1527 // the range of the RHS, but this doesn't fit into the current structure of
1528 // the edge value calculation.
1529 const APInt *C;
1530 if (WO->getLHS() != Val || !match(WO->getRHS(), m_APInt(C)))
1532
1533 // Calculate the possible values of %x for which no overflow occurs.
1535 WO->getBinaryOp(), *C, WO->getNoWrapKind());
1536
1537 // If overflow is false, %x is constrained to NWR. If overflow is true, %x is
1538 // constrained to it's inverse (all values that might cause overflow).
1539 if (IsTrueDest)
1540 NWR = NWR.inverse();
1542}
1543
1544std::optional<ValueLatticeElement>
1545LazyValueInfoImpl::getValueFromCondition(Value *Val, Value *Cond,
1546 bool IsTrueDest, bool UseBlockValue,
1547 unsigned Depth) {
1548 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Cond))
1549 return getValueFromICmpCondition(Val, ICI, IsTrueDest, UseBlockValue);
1550
1551 if (auto *Trunc = dyn_cast<TruncInst>(Cond))
1552 return getValueFromTrunc(Val, Trunc, IsTrueDest);
1553
1554 if (auto *EVI = dyn_cast<ExtractValueInst>(Cond))
1555 if (auto *WO = dyn_cast<WithOverflowInst>(EVI->getAggregateOperand()))
1556 if (EVI->getNumIndices() == 1 && *EVI->idx_begin() == 1)
1557 return getValueFromOverflowCondition(Val, WO, IsTrueDest);
1558
1561
1562 Value *N;
1563 if (match(Cond, m_Not(m_Value(N))))
1564 return getValueFromCondition(Val, N, !IsTrueDest, UseBlockValue, Depth);
1565
1566 Value *L, *R;
1567 bool IsAnd;
1568 if (match(Cond, m_LogicalAnd(m_Value(L), m_Value(R))))
1569 IsAnd = true;
1570 else if (match(Cond, m_LogicalOr(m_Value(L), m_Value(R))))
1571 IsAnd = false;
1572 else
1574
1575 std::optional<ValueLatticeElement> LV =
1576 getValueFromCondition(Val, L, IsTrueDest, UseBlockValue, Depth);
1577 if (!LV)
1578 return std::nullopt;
1579 std::optional<ValueLatticeElement> RV =
1580 getValueFromCondition(Val, R, IsTrueDest, UseBlockValue, Depth);
1581 if (!RV)
1582 return std::nullopt;
1583
1584 // if (L && R) -> intersect L and R
1585 // if (!(L || R)) -> intersect !L and !R
1586 // if (L || R) -> union L and R
1587 // if (!(L && R)) -> union !L and !R
1588 if (IsTrueDest ^ IsAnd) {
1589 LV->mergeIn(*RV);
1590 return *LV;
1591 }
1592
1593 return LV->intersect(*RV);
1594}
1595
1596// Return true if Usr has Op as an operand, otherwise false.
1597static bool usesOperand(User *Usr, Value *Op) {
1598 return is_contained(Usr->operands(), Op);
1599}
1600
1601// Return true if the instruction type of Val is supported by
1602// constantFoldUser(). Currently CastInst, BinaryOperator and FreezeInst only.
1603// Call this before calling constantFoldUser() to find out if it's even worth
1604// attempting to call it.
1605static bool isOperationFoldable(User *Usr) {
1606 return isa<CastInst>(Usr) || isa<BinaryOperator>(Usr) || isa<FreezeInst>(Usr);
1607}
1608
1609// Check if Usr can be simplified to an integer constant when the value of one
1610// of its operands Op is an integer constant OpConstVal. If so, return it as an
1611// lattice value range with a single element or otherwise return an overdefined
1612// lattice value.
1614 const APInt &OpConstVal,
1615 const DataLayout &DL) {
1616 assert(isOperationFoldable(Usr) && "Precondition");
1617 Constant* OpConst = Constant::getIntegerValue(Op->getType(), OpConstVal);
1618 // Check if Usr can be simplified to a constant.
1619 if (auto *CI = dyn_cast<CastInst>(Usr)) {
1620 assert(CI->getOperand(0) == Op && "Operand 0 isn't Op");
1621 if (auto *C = dyn_cast_or_null<ConstantInt>(
1622 simplifyCastInst(CI->getOpcode(), OpConst,
1623 CI->getDestTy(), DL))) {
1624 return ValueLatticeElement::getRange(ConstantRange(C->getValue()));
1625 }
1626 } else if (auto *BO = dyn_cast<BinaryOperator>(Usr)) {
1627 bool Op0Match = BO->getOperand(0) == Op;
1628 bool Op1Match = BO->getOperand(1) == Op;
1629 assert((Op0Match || Op1Match) &&
1630 "Operand 0 nor Operand 1 isn't a match");
1631 Value *LHS = Op0Match ? OpConst : BO->getOperand(0);
1632 Value *RHS = Op1Match ? OpConst : BO->getOperand(1);
1633 if (auto *C = dyn_cast_or_null<ConstantInt>(
1634 simplifyBinOp(BO->getOpcode(), LHS, RHS, DL))) {
1635 return ValueLatticeElement::getRange(ConstantRange(C->getValue()));
1636 }
1637 } else if (isa<FreezeInst>(Usr)) {
1638 assert(cast<FreezeInst>(Usr)->getOperand(0) == Op && "Operand 0 isn't Op");
1639 return ValueLatticeElement::getRange(ConstantRange(OpConstVal));
1640 }
1642}
1643
1644/// Compute the value of Val on the edge BBFrom -> BBTo.
1645std::optional<ValueLatticeElement>
1646LazyValueInfoImpl::getEdgeValueLocal(Value *Val, BasicBlock *BBFrom,
1647 BasicBlock *BBTo, bool UseBlockValue) {
1648 // TODO: Handle more complex conditionals. If (v == 0 || v2 < 1) is false, we
1649 // know that v != 0.
1650 if (CondBrInst *BI = dyn_cast<CondBrInst>(BBFrom->getTerminator())) {
1651 // If this is a conditional branch and only one successor goes to BBTo, then
1652 // we may be able to infer something from the condition.
1653 if (BI->getSuccessor(0) != BI->getSuccessor(1)) {
1654 bool isTrueDest = BI->getSuccessor(0) == BBTo;
1655 assert(BI->getSuccessor(!isTrueDest) == BBTo &&
1656 "BBTo isn't a successor of BBFrom");
1657 Value *Condition = BI->getCondition();
1658
1659 // If V is the condition of the branch itself, then we know exactly what
1660 // it is.
1661 // NB: The condition on a `br` can't be a vector type.
1662 if (Condition == Val)
1663 return ValueLatticeElement::get(ConstantInt::get(
1664 Type::getInt1Ty(Val->getContext()), isTrueDest));
1665
1666 // If the condition of the branch is an equality comparison, we may be
1667 // able to infer the value.
1668 std::optional<ValueLatticeElement> Result =
1669 getValueFromCondition(Val, Condition, isTrueDest, UseBlockValue);
1670 if (!Result)
1671 return std::nullopt;
1672
1673 if (!Result->isOverdefined())
1674 return Result;
1675
1676 if (User *Usr = dyn_cast<User>(Val)) {
1677 assert(Result->isOverdefined() && "Result isn't overdefined");
1678 // Check with isOperationFoldable() first to avoid linearly iterating
1679 // over the operands unnecessarily which can be expensive for
1680 // instructions with many operands.
1681 if (isa<IntegerType>(Usr->getType()) && isOperationFoldable(Usr)) {
1682 const DataLayout &DL = BBTo->getDataLayout();
1683 Value *TempCond = Condition;
1684 if (usesOperand(Usr, Condition) ||
1685 (match(Condition, m_Not(m_Value(TempCond))) &&
1686 usesOperand(Usr, TempCond))) {
1687 // If Val has Condition as an operand and Val can be folded into a
1688 // constant with either Condition == true or Condition == false,
1689 // propagate the constant.
1690 // eg.
1691 // ; %Val is true on the edge to %then.
1692 // %Val = and i1 %Condition, true.
1693 // br %Condition, label %then, label %else
1694 APInt ConditionVal(1, isTrueDest ^ (TempCond != Condition) ? 1 : 0);
1695 Result = constantFoldUser(Usr, TempCond, ConditionVal, DL);
1696 } else if (isa<TruncInst, ZExtInst, SExtInst>(Usr)) {
1697 ValueLatticeElement OpLatticeVal =
1698 *getValueFromCondition(Usr->getOperand(0), Condition,
1699 isTrueDest, /*UseBlockValue*/ false);
1700
1701 if (OpLatticeVal.isConstantRange()) {
1702 const unsigned ResultBitWidth =
1703 Usr->getType()->getScalarSizeInBits();
1704 if (auto *Trunc = dyn_cast<TruncInst>(Usr))
1706 OpLatticeVal.getConstantRange().truncate(
1707 ResultBitWidth, Trunc->getNoWrapKind()));
1708
1710 OpLatticeVal.getConstantRange().castOp(
1711 cast<CastInst>(Usr)->getOpcode(), ResultBitWidth));
1712 }
1713 if (OpLatticeVal.isConstant()) {
1714 Constant *C = OpLatticeVal.getConstant();
1715 if (auto *CastC = ConstantFoldCastOperand(
1716 cast<CastInst>(Usr)->getOpcode(), C, Usr->getType(), DL))
1717 return ValueLatticeElement::get(CastC);
1718 }
1720 } else {
1721 // If one of Val's operand has an inferred value, we may be able to
1722 // infer the value of Val.
1723 // eg.
1724 // ; %Val is 94 on the edge to %then.
1725 // %Val = add i8 %Op, 1
1726 // %Condition = icmp eq i8 %Op, 93
1727 // br i1 %Condition, label %then, label %else
1728 for (unsigned i = 0; i < Usr->getNumOperands(); ++i) {
1729 Value *Op = Usr->getOperand(i);
1730 ValueLatticeElement OpLatticeVal = *getValueFromCondition(
1731 Op, Condition, isTrueDest, /*UseBlockValue*/ false);
1732 if (std::optional<APInt> OpConst =
1733 OpLatticeVal.asConstantInteger()) {
1734 Result = constantFoldUser(Usr, Op, *OpConst, DL);
1735 break;
1736 }
1737 }
1738 }
1739 }
1740 }
1741 if (!Result->isOverdefined())
1742 return Result;
1743 }
1744 }
1745
1746 // If the edge was formed by a switch on the value, then we may know exactly
1747 // what it is.
1748 if (SwitchInst *SI = dyn_cast<SwitchInst>(BBFrom->getTerminator())) {
1749 Value *Condition = SI->getCondition();
1750 if (!isa<IntegerType>(Val->getType()))
1752 bool ValUsesConditionAndMayBeFoldable = false;
1753 if (Condition != Val) {
1754 // Check if Val has Condition as an operand.
1755 if (User *Usr = dyn_cast<User>(Val))
1756 ValUsesConditionAndMayBeFoldable = isOperationFoldable(Usr) &&
1757 usesOperand(Usr, Condition);
1758 if (!ValUsesConditionAndMayBeFoldable)
1760 }
1761 assert((Condition == Val || ValUsesConditionAndMayBeFoldable) &&
1762 "Condition != Val nor Val doesn't use Condition");
1763
1764 bool DefaultCase = SI->getDefaultDest() == BBTo;
1765 unsigned BitWidth = Val->getType()->getIntegerBitWidth();
1766 ConstantRange EdgesVals(BitWidth, DefaultCase/*isFullSet*/);
1767
1768 for (auto Case : SI->cases()) {
1769 APInt CaseValue = Case.getCaseValue()->getValue();
1770 ConstantRange EdgeVal(CaseValue);
1771 if (ValUsesConditionAndMayBeFoldable) {
1772 User *Usr = cast<User>(Val);
1773 const DataLayout &DL = BBTo->getDataLayout();
1774 ValueLatticeElement EdgeLatticeVal =
1775 constantFoldUser(Usr, Condition, CaseValue, DL);
1776 if (EdgeLatticeVal.isOverdefined())
1778 EdgeVal = EdgeLatticeVal.getConstantRange();
1779 }
1780 if (DefaultCase) {
1781 // It is possible that the default destination is the destination of
1782 // some cases. We cannot perform difference for those cases.
1783 // We know Condition != CaseValue in BBTo. In some cases we can use
1784 // this to infer Val == f(Condition) is != f(CaseValue). For now, we
1785 // only do this when f is identity (i.e. Val == Condition), but we
1786 // should be able to do this for any injective f.
1787 if (Case.getCaseSuccessor() != BBTo && Condition == Val)
1788 EdgesVals = EdgesVals.difference(EdgeVal);
1789 } else if (Case.getCaseSuccessor() == BBTo)
1790 EdgesVals = EdgesVals.unionWith(EdgeVal);
1791 }
1792 return ValueLatticeElement::getRange(std::move(EdgesVals));
1793 }
1795}
1796
1797/// Compute the value of Val on the edge BBFrom -> BBTo or the value at
1798/// the basic block if the edge does not constrain Val.
1799std::optional<ValueLatticeElement>
1800LazyValueInfoImpl::getEdgeValue(Value *Val, BasicBlock *BBFrom,
1801 BasicBlock *BBTo, Instruction *CtxI) {
1802 // If already a constant, there is nothing to compute.
1803 if (Constant *VC = dyn_cast<Constant>(Val))
1804 return ValueLatticeElement::get(VC);
1805
1806 std::optional<ValueLatticeElement> LocalResult =
1807 getEdgeValueLocal(Val, BBFrom, BBTo, /*UseBlockValue*/ true);
1808 if (!LocalResult)
1809 return std::nullopt;
1810
1811 if (hasSingleValue(*LocalResult))
1812 // Can't get any more precise here
1813 return LocalResult;
1814
1815 std::optional<ValueLatticeElement> OptInBlock =
1816 getBlockValue(Val, BBFrom, BBFrom->getTerminator());
1817 if (!OptInBlock)
1818 return std::nullopt;
1819 ValueLatticeElement &InBlock = *OptInBlock;
1820
1821 // We can use the context instruction (generically the ultimate instruction
1822 // the calling pass is trying to simplify) here, even though the result of
1823 // this function is generally cached when called from the solve* functions
1824 // (and that cached result might be used with queries using a different
1825 // context instruction), because when this function is called from the solve*
1826 // functions, the context instruction is not provided. When called from
1827 // LazyValueInfoImpl::getValueOnEdge, the context instruction is provided,
1828 // but then the result is not cached.
1829 intersectAssumeOrGuardBlockValueConstantRange(Val, InBlock, CtxI);
1830
1831 return LocalResult->intersect(InBlock);
1832}
1833
1835 Instruction *CtxI) {
1836 LLVM_DEBUG(dbgs() << "LVI Getting block end value " << *V << " at '"
1837 << BB->getName() << "'\n");
1838
1839 assert(BlockValueStack.empty() && BlockValueSet.empty());
1840 std::optional<ValueLatticeElement> OptResult = getBlockValue(V, BB, CtxI);
1841 if (!OptResult) {
1842 solve();
1843 OptResult = getBlockValue(V, BB, CtxI);
1844 assert(OptResult && "Value not available after solving");
1845 }
1846
1847 LLVM_DEBUG(dbgs() << " Result = " << *OptResult << "\n");
1848 return *OptResult;
1849}
1850
1852 LLVM_DEBUG(dbgs() << "LVI Getting value " << *V << " at '" << CtxI->getName()
1853 << "'\n");
1854
1855 if (auto *C = dyn_cast<Constant>(V))
1857
1859 if (auto *I = dyn_cast<Instruction>(V))
1860 Result = getFromRangeMetadata(I);
1861 intersectAssumeOrGuardBlockValueConstantRange(V, Result, CtxI);
1862
1863 LLVM_DEBUG(dbgs() << " Result = " << Result << "\n");
1864 return Result;
1865}
1866
1868getValueOnEdge(Value *V, BasicBlock *FromBB, BasicBlock *ToBB,
1869 Instruction *CtxI) {
1870 LLVM_DEBUG(dbgs() << "LVI Getting edge value " << *V << " from '"
1871 << FromBB->getName() << "' to '" << ToBB->getName()
1872 << "'\n");
1873
1874 std::optional<ValueLatticeElement> Result =
1875 getEdgeValue(V, FromBB, ToBB, CtxI);
1876 while (!Result) {
1877 // As the worklist only explicitly tracks block values (but not edge values)
1878 // we may have to call solve() multiple times, as the edge value calculation
1879 // may request additional block values.
1880 solve();
1881 Result = getEdgeValue(V, FromBB, ToBB, CtxI);
1882 }
1883
1884 LLVM_DEBUG(dbgs() << " Result = " << *Result << "\n");
1885 return *Result;
1886}
1887
1889 bool AssumeFrozen) {
1890 Value *V = U.get();
1891 auto *CtxI = cast<Instruction>(U.getUser());
1892 ValueLatticeElement VL = getValueInBlock(V, CtxI->getParent(), CtxI);
1893 BasicBlock *LastQueriedBB = CtxI->getParent();
1894
1895 // Check whether the only (possibly transitive) use of the value is in a
1896 // position where V can be constrained by a select or branch condition.
1897 const Use *CurrU = &U;
1898 const unsigned MaxUsesToInspect = 6;
1899 for (unsigned I = 0; I < MaxUsesToInspect; ++I) {
1900 std::optional<ValueLatticeElement> CondVal;
1901 auto *CurrI = cast<Instruction>(CurrU->getUser());
1902
1903 // All instructions on the one-use chain between the original use and CurrI
1904 // are speculatable and have a single user each, so they could be sunk to
1905 // CurrI. This means information that holds at CurrI also holds for the
1906 // original use and can be used to refine it. Skip phis, as V may not
1907 // dominate their block.
1908 if (I != 0 && !isa<PHINode>(CurrI) && CurrI->getParent() != LastQueriedBB) {
1909 LastQueriedBB = CurrI->getParent();
1910 VL = VL.intersect(getValueInBlock(V, LastQueriedBB, CurrI));
1911 }
1912
1913 if (auto *SI = dyn_cast<SelectInst>(CurrI)) {
1914 // If the value is undef, a different value may be chosen in the select
1915 // condition and at use, so bail.
1916 //
1917 // Allow if AssumeFrozen (the caller is going to freeze V).
1918 if (!AssumeFrozen && !isGuaranteedNotToBeUndef(SI->getCondition(), AC))
1919 break;
1920
1921 if (CurrU->getOperandNo() == 1)
1922 CondVal =
1923 *getValueFromCondition(V, SI->getCondition(), /*IsTrueDest*/ true,
1924 /*UseBlockValue*/ false);
1925 else if (CurrU->getOperandNo() == 2)
1926 CondVal =
1927 *getValueFromCondition(V, SI->getCondition(), /*IsTrueDest*/ false,
1928 /*UseBlockValue*/ false);
1929 } else if (auto *PHI = dyn_cast<PHINode>(CurrI)) {
1930 // TODO: Use non-local query?
1931 CondVal = *getEdgeValueLocal(V, PHI->getIncomingBlock(*CurrU),
1932 PHI->getParent(), /*UseBlockValue*/ false);
1933 }
1934 if (CondVal)
1935 VL = VL.intersect(*CondVal);
1936
1937 // Only follow one-use chain, to allow direct intersection of conditions.
1938 // If there are multiple uses, we would have to intersect with the union of
1939 // all conditions at different uses.
1940 // Stop walking if we hit a non-speculatable instruction. Even if the
1941 // result is only used under a specific condition, executing the
1942 // instruction itself may cause side effects or UB already.
1943 // This also disallows looking through phi nodes: If the phi node is part
1944 // of a cycle, we might end up reasoning about values from different cycle
1945 // iterations (PR60629).
1946 if (!CurrI->hasOneUse() ||
1948 CurrI, /*IgnoreUBImplyingAttrs=*/false))
1949 break;
1950 // Also stop walking at cross-lane operations, since they may rearrange
1951 // lanes so that a later select per-lane condition might no longer
1952 // correspond to the original value's lanes.
1953 if (V->getType()->isVectorTy() && !isNotCrossLaneOperation(CurrI))
1954 break;
1955 CurrU = &*CurrI->use_begin();
1956 }
1957 return VL;
1958}
1959
1961 BasicBlock *NewSucc) {
1962 TheCache.threadEdgeImpl(OldSucc, NewSucc);
1963}
1964
1965//===----------------------------------------------------------------------===//
1966// LazyValueInfo Impl
1967//===----------------------------------------------------------------------===//
1968
1970 Info.F = &F;
1971 Info.AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
1972
1973 if (auto *Impl = Info.getImpl())
1974 Impl->clear();
1975
1976 // Fully lazy.
1977 return false;
1978}
1979
1985
1987
1988/// This lazily constructs the LazyValueInfoImpl.
1989LazyValueInfoImpl &LazyValueInfo::getOrCreateImpl() {
1990 if (!PImpl) {
1991 const DataLayout &DL = F->getDataLayout();
1993 F->getParent(), Intrinsic::experimental_guard);
1994 PImpl = new LazyValueInfoImpl(F, AC, DL, GuardDecl);
1995 }
1996 return *PImpl;
1997}
1998
1999LazyValueInfoImpl *LazyValueInfo::getImpl() { return PImpl; }
2000
2002
2004 // If the cache was allocated, free it.
2005 if (auto *Impl = getImpl()) {
2006 delete &*Impl;
2007 PImpl = nullptr;
2008 }
2009}
2010
2012 FunctionAnalysisManager::Invalidator &Inv) {
2013 // We need to invalidate if we have either failed to preserve this analyses
2014 // result directly or if any of its dependencies have been invalidated.
2015 auto PAC = PA.getChecker<LazyValueAnalysis>();
2016 if (!(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()))
2017 return true;
2018
2019 return false;
2020}
2021
2022void LazyValueInfoWrapperPass::releaseMemory() { Info.releaseMemory(); }
2023
2026 auto &AC = FAM.getResult<AssumptionAnalysis>(F);
2027
2028 return LazyValueInfo(&F, &AC);
2029}
2030
2031/// Returns true if we can statically tell that this value will never be a
2032/// "useful" constant. In practice, this means we've got something like an
2033/// alloca or a malloc call for which a comparison against a constant can
2034/// only be guarding dead code. Note that we are potentially giving up some
2035/// precision in dead code (a constant result) in favour of avoiding a
2036/// expensive search for a easily answered common query.
2038 V = V->stripPointerCasts();
2039 // The return val of alloc cannot be a Constant.
2040 if (isa<AllocaInst>(V))
2041 return true;
2042 return false;
2043}
2044
2045/// Return the constant \p V is known to be equal to from \p Result, if any.
2046/// A pointer constant derived from an equality condition may differ from \p V
2047/// in provenance. Such a constant is only returned if \p U, the use of \p V it
2048/// is to be substituted in, is provided, and the replacement is valid for that
2049/// use.
2051 Value *V, const Use *U,
2052 const DataLayout &DL) {
2053 Constant *C = nullptr;
2054 if (Result.isConstant())
2055 C = Result.getConstant();
2056 else if (Result.isConstantRange())
2057 if (const APInt *SingleVal = Result.getConstantRange().getSingleElement())
2058 C = ConstantInt::get(V->getType(), *SingleVal);
2059 if (!C)
2060 return nullptr;
2061
2062 if (Result.mayHaveDifferentProvenance()) {
2063 if (!U)
2064 return nullptr;
2065 assert(U->get() == V && "Must be a use of V.");
2067 return nullptr;
2068 }
2069 return C;
2070}
2071
2073 const Use *U) {
2074 // Bail out early if V is known not to be a Constant.
2075 if (isKnownNonConstant(V))
2076 return nullptr;
2077
2078 BasicBlock *BB = CtxI->getParent();
2079 ValueLatticeElement Result = getOrCreateImpl().getValueInBlock(V, BB, CtxI);
2080 return getConstantFromLattice(Result, V, U, BB->getDataLayout());
2081}
2082
2084 bool UndefAllowed) {
2085 BasicBlock *BB = CtxI->getParent();
2086 ValueLatticeElement Result = getOrCreateImpl().getValueInBlock(V, BB, CtxI);
2087 return Result.asConstantRange(V->getType(), UndefAllowed);
2088}
2089
2091 bool UndefAllowed,
2092 bool AssumeFrozen) {
2093 ValueLatticeElement Result = getOrCreateImpl().getValueAtUse(U, AssumeFrozen);
2094 return Result.asConstantRange(U->getType(), UndefAllowed);
2095}
2096
2097/// Determine whether the specified value is known to be a
2098/// constant on the specified edge. Return null if not.
2100 BasicBlock *ToBB, Instruction *CtxI,
2101 const Use *U) {
2102 ValueLatticeElement Result =
2103 getOrCreateImpl().getValueOnEdge(V, FromBB, ToBB, CtxI);
2104 return getConstantFromLattice(Result, V, U, ToBB->getDataLayout());
2105}
2106
2108 BasicBlock *FromBB,
2109 BasicBlock *ToBB,
2110 Instruction *CtxI) {
2111 ValueLatticeElement Result =
2112 getOrCreateImpl().getValueOnEdge(V, FromBB, ToBB, CtxI);
2113 // TODO: Should undef be allowed here?
2114 return Result.asConstantRange(V->getType(), /*UndefAllowed*/ true);
2115}
2116
2118 const ValueLatticeElement &Val,
2119 const DataLayout &DL) {
2120 // If we know the value is a constant, evaluate the conditional.
2121 if (Val.isConstant())
2123
2124 Type *ResTy = CmpInst::makeCmpResultType(C->getType());
2125 if (Val.isConstantRange()) {
2126 const ConstantRange &CR = Val.getConstantRange();
2127 ConstantRange RHS = C->toConstantRange();
2128 if (CR.icmp(Pred, RHS))
2129 return ConstantInt::getTrue(ResTy);
2131 return ConstantInt::getFalse(ResTy);
2132 return nullptr;
2133 }
2134
2135 if (Val.isNotConstant()) {
2136 // If this is an equality comparison, we can try to fold it knowing that
2137 // "V != C1".
2138 if (Pred == ICmpInst::ICMP_EQ) {
2139 // !C1 == C -> false iff C1 == C.
2142 if (Res && Res->isNullValue())
2143 return ConstantInt::getFalse(ResTy);
2144 } else if (Pred == ICmpInst::ICMP_NE) {
2145 // !C1 != C -> true iff C1 == C.
2148 if (Res && Res->isNullValue())
2149 return ConstantInt::getTrue(ResTy);
2150 }
2151 return nullptr;
2152 }
2153
2154 return nullptr;
2155}
2156
2157/// Determine whether the specified value comparison with a constant is known to
2158/// be true or false on the specified CFG edge. Pred is a CmpInst predicate.
2160 Constant *C, BasicBlock *FromBB,
2161 BasicBlock *ToBB,
2162 Instruction *CtxI) {
2163 ValueLatticeElement Result =
2164 getOrCreateImpl().getValueOnEdge(V, FromBB, ToBB, CtxI);
2165
2166 return getPredicateResult(Pred, C, Result, FromBB->getDataLayout());
2167}
2168
2170 Constant *C, Instruction *CtxI,
2171 bool UseBlockValue) {
2172 // Is or is not NonNull are common predicates being queried. If
2173 // isKnownNonZero can tell us the result of the predicate, we can
2174 // return it quickly. But this is only a fastpath, and falling
2175 // through would still be correct.
2176 const DataLayout &DL = CtxI->getDataLayout();
2177 // NOTE: This check is meant to determine whether a pointer is semantically a
2178 // null pointer, not just whether its value equals ConstantPointerNull. If the
2179 // semantics of ConstantPointerNull change in the future, this should be
2180 // updated to use a semantic check (e.g. isKnownNonNull).
2181 if (V->getType()->isPointerTy() && C->isNullValue() &&
2182 isKnownNonZero(V->stripPointerCastsSameRepresentation(), DL)) {
2183 Type *ResTy = CmpInst::makeCmpResultType(C->getType());
2184 if (Pred == ICmpInst::ICMP_EQ)
2185 return ConstantInt::getFalse(ResTy);
2186 else if (Pred == ICmpInst::ICMP_NE)
2187 return ConstantInt::getTrue(ResTy);
2188 }
2189
2190 auto &Impl = getOrCreateImpl();
2191 ValueLatticeElement Result =
2192 UseBlockValue ? Impl.getValueInBlock(V, CtxI->getParent(), CtxI)
2193 : Impl.getValueAt(V, CtxI);
2194 Constant *Ret = getPredicateResult(Pred, C, Result, DL);
2195 if (Ret)
2196 return Ret;
2197
2198 // Note: The following bit of code is somewhat distinct from the rest of LVI;
2199 // LVI as a whole tries to compute a lattice value which is conservatively
2200 // correct at a given location. In this case, we have a predicate which we
2201 // weren't able to prove about the merged result, and we're pushing that
2202 // predicate back along each incoming edge to see if we can prove it
2203 // separately for each input. As a motivating example, consider:
2204 // bb1:
2205 // %v1 = ... ; constantrange<1, 5>
2206 // br label %merge
2207 // bb2:
2208 // %v2 = ... ; constantrange<10, 20>
2209 // br label %merge
2210 // merge:
2211 // %phi = phi [%v1, %v2] ; constantrange<1,20>
2212 // %pred = icmp eq i32 %phi, 8
2213 // We can't tell from the lattice value for '%phi' that '%pred' is false
2214 // along each path, but by checking the predicate over each input separately,
2215 // we can.
2216 // We limit the search to one step backwards from the current BB and value.
2217 // We could consider extending this to search further backwards through the
2218 // CFG and/or value graph, but there are non-obvious compile time vs quality
2219 // tradeoffs.
2220 BasicBlock *BB = CtxI->getParent();
2221
2222 // Function entry or an unreachable block. Bail to avoid confusing
2223 // analysis below.
2224 pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
2225 if (PI == PE)
2226 return nullptr;
2227
2228 // If V is a PHI node in the same block as the context, we need to ask
2229 // questions about the predicate as applied to the incoming value along
2230 // each edge. This is useful for eliminating cases where the predicate is
2231 // known along all incoming edges.
2232 if (auto *PHI = dyn_cast<PHINode>(V))
2233 if (PHI->getParent() == BB) {
2234 Constant *Baseline = nullptr;
2235 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i < e; i++) {
2236 Value *Incoming = PHI->getIncomingValue(i);
2237 BasicBlock *PredBB = PHI->getIncomingBlock(i);
2238 // Note that PredBB may be BB itself.
2239 Constant *Result =
2240 getPredicateOnEdge(Pred, Incoming, C, PredBB, BB, CtxI);
2241
2242 // Keep going as long as we've seen a consistent known result for
2243 // all inputs.
2244 Baseline = (i == 0) ? Result /* First iteration */
2245 : (Baseline == Result ? Baseline
2246 : nullptr); /* All others */
2247 if (!Baseline)
2248 break;
2249 }
2250 if (Baseline)
2251 return Baseline;
2252 }
2253
2254 // For a comparison where the V is outside this block, it's possible
2255 // that we've branched on it before. Look to see if the value is known
2256 // on all incoming edges.
2257 if (!isa<Instruction>(V) || cast<Instruction>(V)->getParent() != BB) {
2258 // For predecessor edge, determine if the comparison is true or false
2259 // on that edge. If they're all true or all false, we can conclude
2260 // the value of the comparison in this block.
2261 Constant *Baseline = getPredicateOnEdge(Pred, V, C, *PI, BB, CtxI);
2262 if (Baseline) {
2263 // Check that all remaining incoming values match the first one.
2264 while (++PI != PE) {
2265 Constant *Ret = getPredicateOnEdge(Pred, V, C, *PI, BB, CtxI);
2266 if (Ret != Baseline)
2267 break;
2268 }
2269 // If we terminated early, then one of the values didn't match.
2270 if (PI == PE) {
2271 return Baseline;
2272 }
2273 }
2274 }
2275
2276 return nullptr;
2277}
2278
2280 Value *RHS, Instruction *CtxI,
2281 bool UseBlockValue) {
2282 if (auto *C = dyn_cast<Constant>(RHS))
2283 return getPredicateAt(Pred, LHS, C, CtxI, UseBlockValue);
2284 if (auto *C = dyn_cast<Constant>(LHS))
2285 return getPredicateAt(CmpInst::getSwappedPredicate(Pred), RHS, C, CtxI,
2286 UseBlockValue);
2287
2288 // Got two non-Constant values. Try to determine the comparison results based
2289 // on the block values of the two operands, e.g. because they have
2290 // non-overlapping ranges.
2291 if (UseBlockValue) {
2293 getOrCreateImpl().getValueInBlock(LHS, CtxI->getParent(), CtxI);
2294 if (L.isOverdefined())
2295 return nullptr;
2296
2298 getOrCreateImpl().getValueInBlock(RHS, CtxI->getParent(), CtxI);
2299 Type *Ty = CmpInst::makeCmpResultType(LHS->getType());
2300 return L.getCompare(Pred, Ty, R, CtxI->getDataLayout());
2301 }
2302 return nullptr;
2303}
2304
2306 BasicBlock *NewSucc) {
2307 if (auto *Impl = getImpl())
2308 Impl->threadEdge(PredBB, OldSucc, NewSucc);
2309}
2310
2312 if (auto *Impl = getImpl())
2313 Impl->forgetValue(V);
2314}
2315
2317 if (auto *Impl = getImpl())
2318 Impl->eraseBlock(BB);
2319}
2320
2322 if (auto *Impl = getImpl())
2323 Impl->clear();
2324}
2325
2327 if (auto *Impl = getImpl())
2328 Impl->printLVI(F, DTree, OS);
2329}
2330
2331// Print the LVI for the function arguments at the start of each basic block.
2332void LazyValueInfoAnnotatedWriter::emitBasicBlockStartAnnot(
2333 const BasicBlock *BB, formatted_raw_ostream &OS) {
2334 // Find if there are latticevalues defined for arguments of the function.
2335 auto *F = BB->getParent();
2336 for (const auto &Arg : F->args()) {
2337 ValueLatticeElement Result = LVIImpl->getValueInBlock(
2338 const_cast<Argument *>(&Arg), const_cast<BasicBlock *>(BB));
2339 if (Result.isUnknown())
2340 continue;
2341 OS << "; LatticeVal for: '" << Arg << "' is: " << Result << "\n";
2342 }
2343}
2344
2345// This function prints the LVI analysis for the instruction I at the beginning
2346// of various basic blocks. It relies on calculated values that are stored in
2347// the LazyValueInfoCache, and in the absence of cached values, recalculate the
2348// LazyValueInfo for `I`, and print that info.
2349void LazyValueInfoAnnotatedWriter::emitInstructionAnnot(
2350 const Instruction *I, formatted_raw_ostream &OS) {
2351
2352 auto *ParentBB = I->getParent();
2353 SmallPtrSet<const BasicBlock*, 16> BlocksContainingLVI;
2354 // We can generate (solve) LVI values only for blocks that are dominated by
2355 // the I's parent. However, to avoid generating LVI for all dominating blocks,
2356 // that contain redundant/uninteresting information, we print LVI for
2357 // blocks that may use this LVI information (such as immediate successor
2358 // blocks, and blocks that contain uses of `I`).
2359 auto printResult = [&](const BasicBlock *BB) {
2360 if (!BlocksContainingLVI.insert(BB).second)
2361 return;
2362 ValueLatticeElement Result = LVIImpl->getValueInBlock(
2363 const_cast<Instruction *>(I), const_cast<BasicBlock *>(BB));
2364 OS << "; LatticeVal for: '" << *I << "' in BB: '";
2365 BB->printAsOperand(OS, false);
2366 OS << "' is: " << Result << "\n";
2367 };
2368
2369 printResult(ParentBB);
2370 // Print the LVI analysis results for the immediate successor blocks, that
2371 // are dominated by `ParentBB`.
2372 for (const auto *BBSucc : successors(ParentBB))
2373 if (DT.dominates(ParentBB, BBSucc))
2374 printResult(BBSucc);
2375
2376 // Print LVI in blocks where `I` is used.
2377 for (const Instruction *UseI : I->users())
2378 if (!isa<PHINode>(UseI) || DT.dominates(ParentBB, UseI->getParent()))
2379 printResult(UseI->getParent());
2380}
2381
2384 OS << "LVI for function '" << F.getName() << "':\n";
2385 auto &LVI = AM.getResult<LazyValueAnalysis>(F);
2386 auto &DTree = AM.getResult<DominatorTreeAnalysis>(F);
2387 LVI.printLVI(F, DTree, OS);
2388 return PreservedAnalyses::all();
2389}
SDValue Pred
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
Rewrite undef for PHI
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static const Function * getParent(const Value *V)
#define X(NUM, ENUM, NAME)
Definition ELF.h:665
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This file defines the DenseSet and SmallDenseSet classes.
IRTranslator LLVM IR MI
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
Module.h This file contains the declarations for the Module class.
static bool isOperationFoldable(User *Usr)
static std::optional< ConstantRange > getRangeForNUWMulSquare(const Value *V, CmpInst::Predicate Pred, const Value *LHS, const Value *RHS)
Get the unsigned range for V from a mul nuw V, V comparison.
static void AddNonNullPointer(Value *Ptr, NonNullPointerSet &PtrSet, bool IsDereferenced=true)
static void AddNonNullPointersByInstruction(Instruction *I, NonNullPointerSet &PtrSet)
static Constant * getConstantFromLattice(const ValueLatticeElement &Result, Value *V, const Use *U, const DataLayout &DL)
Return the constant V is known to be equal to from Result, if any.
static std::optional< ConstantRange > getRangeViaSLT(CmpInst::Predicate Pred, APInt RHS, function_ref< std::optional< ConstantRange >(const APInt &)> Fn)
static const unsigned MaxProcessedPerValue
static ValueLatticeElement getValueFromICmpCtpop(ICmpInst::Predicate Pred, Value *RHS)
Get value range for a "ctpop(Val) Pred RHS" condition.
static bool usesOperand(User *Usr, Value *Op)
static ValueLatticeElement constantFoldUser(User *Usr, Value *Op, const APInt &OpConstVal, const DataLayout &DL)
static ValueLatticeElement getFromRangeMetadata(Instruction *BBI)
static Constant * getPredicateResult(CmpInst::Predicate Pred, Constant *C, const ValueLatticeElement &Val, const DataLayout &DL)
static ValueLatticeElement getValueFromOverflowCondition(Value *Val, WithOverflowInst *WO, bool IsTrueDest)
static bool isKnownNonConstant(Value *V)
Returns true if we can statically tell that this value will never be a "useful" constant.
static bool matchICmpOperand(APInt &Offset, Value *LHS, Value *Val, ICmpInst::Predicate Pred)
SmallVector< MachineOperand, 4 > Cond
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define T
static void eraseBlock(MachineBasicBlock *MBB, LiveIntervals &LIS, MachineDomTreeUpdater &MDTU)
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
uint64_t IntrinsicInst * II
#define P(N)
FunctionAnalysisManager FAM
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
This file contains some templates that are useful if you are working with the STL at all.
static bool InBlock(const Value *V, const BasicBlock *BB)
#define LLVM_DEBUG(...)
Definition Debug.h:119
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
Value * RHS
Value * LHS
Class for arbitrary precision integers.
Definition APInt.h:78
LLVM_ABI APInt zext(unsigned width) const
Zero extend to a new width.
Definition APInt.cpp:1057
static APInt getSignedMinValue(unsigned numBits)
Gets minimum signed value of APInt for a specific bit width.
Definition APInt.h:215
uint64_t getLimitedValue(uint64_t Limit=UINT64_MAX) const
If this value is smaller than the specified limit, return it, otherwise return the limit value.
Definition APInt.h:471
static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet)
Constructs an APInt value that has the bottom loBitsSet bits set.
Definition APInt.h:302
static APInt getHighBitsSet(unsigned numBits, unsigned hiBitsSet)
Constructs an APInt value that has the top hiBitsSet bits set.
Definition APInt.h:292
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
Definition APInt.h:196
This templated class represents "all analyses that operate over <aparticular IR unit>" (e....
Definition Analysis.h:50
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Represent the analysis usage information of a pass.
AnalysisUsage & addRequired()
void setPreservesAll()
Set by analyses that do not transform their input at all.
This class represents an incoming formal argument to a Function.
Definition Argument.h:32
A function analysis which provides an AssumptionCache.
An immutable pass that tracks lazily created AssumptionCache objects.
A cache of @llvm.assume calls within a function.
LLVM Basic Block Representation.
Definition BasicBlock.h:61
unsigned getNumber() const
Definition BasicBlock.h:94
iterator begin()
Instruction iterator methods.
Definition BasicBlock.h:439
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:212
LLVM_ABI bool isEntryBlock() const
Return true if this is the entry block of the containing function.
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this basic block belongs to.
reverse_iterator rend()
Definition BasicBlock.h:457
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:236
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.
BinaryOps getOpcode() const
Definition InstrTypes.h:409
Value handle with callbacks on RAUW and destruction.
This is the base class for all instructions that perform data casts.
Definition InstrTypes.h:512
Instruction::CastOps getOpcode() const
Return the opcode of this CastInst.
Definition InstrTypes.h:674
Type * getDestTy() const
Return the destination type, as a convenience.
Definition InstrTypes.h:681
static Type * makeCmpResultType(Type *opnd_type)
Create a result type for fcmp/icmp.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:740
@ ICMP_SLT
signed less than
Definition InstrTypes.h:769
@ ICMP_SLE
signed less or equal
Definition InstrTypes.h:770
@ ICMP_UGE
unsigned greater or equal
Definition InstrTypes.h:764
@ ICMP_UGT
unsigned greater than
Definition InstrTypes.h:763
@ ICMP_SGT
signed greater than
Definition InstrTypes.h:767
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:765
@ ICMP_NE
not equal
Definition InstrTypes.h:762
@ ICMP_SGE
signed greater or equal
Definition InstrTypes.h:768
@ ICMP_ULE
unsigned less or equal
Definition InstrTypes.h:766
bool isSigned() const
Definition InstrTypes.h:993
Predicate getSwappedPredicate() const
For example, EQ->EQ, SLE->SGE, ULT->UGT, OEQ->OEQ, ULE->UGE, OLT->OGT, etc.
Definition InstrTypes.h:890
Predicate getInversePredicate() const
For example, EQ -> NE, UGT -> ULE, SLT -> SGE, OEQ -> UNE, UGT -> OLE, OLT -> UGE,...
Definition InstrTypes.h:852
Predicate getPredicate() const
Return the predicate for this instruction.
Definition InstrTypes.h:828
This is the shared class of boolean and integer constants.
Definition Constants.h:87
static LLVM_ABI ConstantInt * getTrue(LLVMContext &Context)
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 subtract(const APInt &CI) const
Subtract the specified constant from the endpoints of this constant range.
static LLVM_ABI ConstantRange fromKnownBits(const KnownBits &Known, bool IsSigned)
Initialize a range based on a known bits constraint.
LLVM_ABI ConstantRange sqrtFloor() const
Calculate sqrtFloor range. See APInt::sqrtFloor().
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 ConstantRange umin(const ConstantRange &Other) const
Return a new range representing the possible values resulting from an unsigned minimum of a value in ...
LLVM_ABI APInt getUnsignedMin() const
Return the smallest unsigned value contained in the ConstantRange.
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 isEmptySet() const
Return true if this set contains no members.
LLVM_ABI ConstantRange abs(bool IntMinIsPoison=false) const
Calculate absolute value range.
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 ConstantRange umax(const ConstantRange &Other) const
Return a new range representing the possible values resulting from an unsigned maximum of a value in ...
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...
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 APInt getUnsignedMax() const
Return the largest unsigned value contained in the ConstantRange.
static LLVM_ABI ConstantRange makeMaskNotEqualRange(const APInt &Mask, const APInt &C)
Initialize a range containing all values X that satisfy (X & Mask) / != C.
static ConstantRange getNonEmpty(APInt Lower, APInt Upper)
Create non-empty constant range with the given bounds.
LLVM_ABI ConstantRange smin(const ConstantRange &Other) const
Return a new range representing the possible values resulting from a signed minimum of a value in thi...
uint32_t getBitWidth() const
Get the bit width of this ConstantRange.
LLVM_ABI ConstantRange smax(const ConstantRange &Other) const
Return a new range representing the possible values resulting from a signed maximum of a value in thi...
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...
static LLVM_ABI ConstantRange makeExactNoWrapRegion(Instruction::BinaryOps BinOp, const APInt &Other, unsigned NoWrapKind)
Produce the range that contains X if and only if "X BinOp Other" does not wrap.
This is an important base class in LLVM.
Definition Constant.h:44
static LLVM_ABI Constant * getIntegerValue(Type *Ty, const APInt &V)
Return the value for an integer or pointer constant, or a vector thereof, with the given scalar value...
LLVM_ABI ConstantRange toConstantRange() const
Convert constant to an approximate constant range.
bool isNullValue() const
Return true if this is the value that would be returned by getNullValue.
Definition Constant.h:65
static LLVM_ABI Constant * getAllOnesValue(Type *Ty)
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:63
Implements a dense probed hash-table based set.
Definition DenseSet.h:283
Analysis pass which computes a DominatorTree.
Definition Dominators.h:241
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
LLVM_ABI bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
This instruction extracts a struct member or array element value from an aggregate value.
ArrayRef< unsigned > getIndices() const
unsigned getNumIndices() const
idx_iterator idx_begin() const
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:312
FunctionPass(char &pid)
Definition Pass.h:314
unsigned getMaxBlockNumber() const
Return a value larger than the largest block number.
Definition Function.h:822
unsigned getBlockNumberEpoch() const
Return the "epoch" of current block numbers.
Definition Function.h:836
Module * getParent()
Get the module that this global value is contained inside of...
This instruction compares its operands according to the predicate given to the constructor.
static bool isEquality(Predicate P)
Return true if this predicate is either EQ or NE.
This instruction inserts a single (scalar) element into a VectorType value.
LLVM_ABI const Function * getFunction() const
Return the function this instruction belongs to.
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this instruction belongs to.
A wrapper class for inspecting calls to intrinsic functions.
Analysis to compute lazy value information.
LLVM_ABI Result run(Function &F, FunctionAnalysisManager &FAM)
LazyValueInfoImpl(Function *F, AssumptionCache *AC, const DataLayout &DL, Function *GuardDecl)
ValueLatticeElement getValueOnEdge(Value *V, BasicBlock *FromBB, BasicBlock *ToBB, Instruction *CtxI=nullptr)
This is the query interface to determine the lattice value for the specified Value* that is true on t...
ValueLatticeElement getValueAtUse(const Use &U, bool AssumeFrozen=false)
ValueLatticeElement getValueAt(Value *V, Instruction *CtxI)
This is the query interface to determine the lattice value for the specified Value* at the specified ...
ValueLatticeElement getValueInBlock(Value *V, BasicBlock *BB, Instruction *CtxI=nullptr)
This is the query interface to determine the lattice value for the specified Value* at the context in...
void threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc, BasicBlock *NewSucc)
This is the update interface to inform the cache that an edge from PredBB to OldSucc has been threade...
void printLVI(Function &F, DominatorTree &DTree, raw_ostream &OS)
Printing the LazyValueInfo Analysis.
void forgetValue(Value *V)
This is part of the update interface to remove information related to this value from the cache.
void eraseBlock(BasicBlock *BB)
This is part of the update interface to inform the cache that a block has been deleted.
void clear()
Complete flush all previously computed values.
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
Wrapper around LazyValueInfo.
bool runOnFunction(Function &F) override
runOnFunction - Virtual method overriden by subclasses to do the per-function processing of the pass.
void releaseMemory() override
releaseMemory() - This member can be implemented by a pass if it wants to be able to release its memo...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
This pass computes, caches, and vends lazy value constraint information.
LLVM_ABI void eraseBlock(BasicBlock *BB)
Inform the analysis cache that we have erased a block.
LLVM_ABI Constant * getConstantOnEdge(Value *V, BasicBlock *FromBB, BasicBlock *ToBB, Instruction *CtxI=nullptr, const Use *U=nullptr)
Determine whether the specified value is known to be a constant on the specified edge.
LLVM_ABI void threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc, BasicBlock *NewSucc)
Inform the analysis cache that we have threaded an edge from PredBB to OldSucc to be from PredBB to N...
LLVM_ABI void releaseMemory()
LLVM_ABI Constant * getConstant(Value *V, Instruction *CtxI, const Use *U=nullptr)
Determine whether the specified value is known to be a constant at the specified instruction.
LLVM_ABI void printLVI(Function &F, DominatorTree &DTree, raw_ostream &OS)
Print the \LazyValueInfo Analysis.
LLVM_ABI Constant * getPredicateAt(CmpInst::Predicate Pred, Value *V, Constant *C, Instruction *CtxI, bool UseBlockValue)
Determine whether the specified value comparison with a constant is known to be true or false at the ...
LLVM_ABI void forgetValue(Value *V)
Remove information related to this value from the cache.
LLVM_ABI ConstantRange getConstantRange(Value *V, Instruction *CtxI, bool UndefAllowed)
Return the ConstantRange constraint that is known to hold for the specified value at the specified in...
LLVM_ABI ConstantRange getConstantRangeAtUse(const Use &U, bool UndefAllowed, bool AssumeFrozen=false)
Return the ConstantRange constraint that is known to hold for the value at a specific use-site.
LLVM_ABI void clear()
Complete flush all previously computed values.
LLVM_ABI ConstantRange getConstantRangeOnEdge(Value *V, BasicBlock *FromBB, BasicBlock *ToBB, Instruction *CtxI=nullptr)
Return the ConstantRage constraint that is known to hold for the specified value on the specified edg...
LLVM_ABI bool invalidate(Function &F, const PreservedAnalyses &PA, FunctionAnalysisManager::Invalidator &Inv)
Handle invalidation events in the new pass manager.
LLVM_ABI Constant * getPredicateOnEdge(CmpInst::Predicate Pred, Value *V, Constant *C, BasicBlock *FromBB, BasicBlock *ToBB, Instruction *CtxI=nullptr)
Determine whether the specified value comparison with a constant is known to be true or false on the ...
An instruction for reading from memory.
Metadata node.
Definition Metadata.h:1087
This is the common base class for memset/memcpy/memmove.
This class wraps the llvm.memcpy/memmove intrinsics.
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.
AnalysisType & getAnalysis() const
getAnalysis<AnalysisType>() - This function is used by subclasses to get to the analysis information ...
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalysisChecker getChecker() const
Build a checker for this PreservedAnalyses and the specified analysis type.
Definition Analysis.h:275
This class represents the LLVM 'select' instruction.
Implements a dense probed hash-table based set with some number of buckets stored inline.
Definition DenseSet.h:295
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
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.
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
LLVM_ABI unsigned getIntegerBitWidth() const
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
Definition Type.h:258
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
bool isSized() const
Return true if it makes sense to take the size of this type.
Definition Type.h:321
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.h:354
static LLVM_ABI IntegerType * getInt1Ty(LLVMContext &C)
Definition Type.cpp:291
bool isPtrOrPtrVectorTy() const
Return true if this is a pointer type or a vector of pointer types.
Definition Type.h:280
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
op_range operands()
Definition User.h:267
Value * getOperand(unsigned i) const
Definition User.h:207
This class represents lattice values for constants.
static ValueLatticeElement getRange(ConstantRange CR, bool MayIncludeUndef=false)
static ValueLatticeElement getNot(Constant *C)
ConstantRange asConstantRange(unsigned BW, bool UndefAllowed=false) const
std::optional< APInt > asConstantInteger() const
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)
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.
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:257
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:260
LLVM_ABI const Value * stripInBoundsOffsets(function_ref< void(const Value *)> Func=[](const Value *) {}) const
Strip off pointer casts and inbounds GEPs.
Definition Value.cpp:823
use_iterator use_begin()
Definition Value.h:366
LLVM_ABI void printAsOperand(raw_ostream &O, bool PrintType=true, const Module *M=nullptr) const
Print the name of this Value out to the specified raw_ostream.
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:314
Represents an op.with.overflow intrinsic.
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:210
bool erase(const ValueT &V)
Definition DenseSet.h:98
iterator find_as(const LookupKeyT &Val)
Alternative version of find() which allows a different, and possibly less expensive,...
Definition DenseSet.h:198
formatted_raw_ostream - A raw_ostream that wraps another one and keeps track of line and column posit...
An efficient, type-erasing, non-owning reference to a callable.
const ParentTy * getParent() const
Definition ilist_node.h:34
self_iterator getIterator()
Definition ilist_node.h:123
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
@ Entry
Definition COFF.h:862
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:83
LLVM_ABI Function * getDeclarationIfExists(const Module *M, ID id)
Look up the Function declaration of the intrinsic id in the Module M and return it if it exists.
BinaryOp_match< SrcTy, SpecificConstantMatch, TargetOpcode::G_XOR, true > m_Not(const SrcTy &&Src)
Matches a register not-ed by a G_XOR.
match_combine_or< Ty... > m_CombineOr(const Ty &...Ps)
Combine pattern matchers matching any of Ps patterns.
BinaryOp_match< LHS, RHS, Instruction::And > m_And(const LHS &L, const RHS &R)
PtrToIntSameSize_match< OpTy > m_PtrToIntSameSize(const DataLayout &DL, const OpTy &Op)
BinaryOp_match< LHS, RHS, Instruction::AShr > m_AShr(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::URem > m_URem(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.
BinaryOp_match< LHS, RHS, Instruction::And, true > m_c_And(const LHS &L, const RHS &R)
Matches an And with LHS and RHS in either order.
CastInst_match< OpTy, TruncInst > m_Trunc(const OpTy &Op)
Matches Trunc.
bool match(Val *V, const Pattern &P)
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
auto m_Value()
Match an arbitrary value and ignore it.
auto m_Ctpop(const Opnd0 &Op0)
auto m_LogicalOr()
Matches L || R where L and R are arbitrary values.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Mul, OverflowingBinaryOperator::NoUnsignedWrap > m_NUWMul(const LHS &L, const RHS &R)
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".
auto m_Intrinsic(const Ts &...Ops)
Match intrinsic calls like this: m_Intrinsic<Intrinsic::fabs>(m_Value(X))
auto m_LogicalAnd()
Matches L && R where L and R are arbitrary values.
BinaryOp_match< LHS, RHS, Instruction::Or, true > m_c_Or(const LHS &L, const RHS &R)
Matches an Or with LHS and RHS in either order.
BinaryOp_match< LHS, RHS, Instruction::Sub > m_Sub(const LHS &L, const RHS &R)
constexpr double e
@ User
could "use" a pointer
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
unsigned getOpcode(const VPValue *V)
Return the instruction opcode for the recipe defining V or 0 for unsupported recipes and VPValues not...
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:577
BundleAttr getBundleAttrFromOBU(OperandBundleUse OBU)
@ Known
Known to have no common set bits.
auto pred_end(const MachineBasicBlock *BB)
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< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2229
LLVM_ABI bool assumeBundleImpliesNonNull(const Value *Val, const Function *Context, OperandBundleUse OBU)
LLVM_ABI bool isGuaranteedNotToBeUndef(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Returns true if V cannot be undef, but may be poison.
LLVM_ABI ConstantRange getConstantRangeFromMetadata(const MDNode &RangeMD)
Parse out a conservative ConstantRange from !range metadata.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
LLVM_ABI Value * simplifyCastInst(unsigned CastOpc, Value *Op, Type *Ty, const SimplifyQuery &Q)
Given operands for a CastInst, fold the result or return null.
LLVM_ABI FunctionPass * createLazyValueInfoPass()
createLazyValueInfoPass - This creates an instance of the LazyValueInfo pass.
LLVM_ABI Constant * ConstantFoldCompareInstOperands(unsigned Predicate, Constant *LHS, Constant *RHS, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr, const Function *CtxF=nullptr)
Attempt to constant fold a compare instruction (icmp/fcmp) with the specified operands.
LLVM_ABI bool isValidAssumeForContext(const Instruction *I, const Instruction *CtxI, const DominatorTree *DT=nullptr, bool AllowEphemerals=false)
Return true if it is valid to use the assumptions provided by an assume intrinsic,...
const AnalysisOptions & getAnalysisOptions(const LLVMContext &C)
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
constexpr unsigned MaxAnalysisRecursionDepth
LLVM_ABI bool canReplacePointersInUseIfEqual(const Use &U, const Value *To, const DataLayout &DL)
Definition Loads.cpp:927
@ SPF_ABS
Floating point maxnum.
@ SPF_NABS
Absolute value.
@ SPF_UMIN
Signed minimum.
@ SPF_UMAX
Signed maximum.
@ SPF_SMAX
Unsigned minimum.
decltype(auto) get(const PointerIntPair< PointerTy, IntBits, IntType, PtrTraits, Info > &Pair)
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 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...
LLVM_ABI const Value * getUnderlyingObject(const Value *V, unsigned MaxLookup=MaxLookupSearchDepth, bool MustPreserveProvenance=false)
This method strips off any GEP address adjustments, pointer casts or llvm.threadlocal....
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 * simplifyExtractValueInst(Value *Agg, ArrayRef< unsigned > Idxs, const SimplifyQuery &Q)
Given operands for an ExtractValueInst, fold the result or return null.
LLVM_ABI bool isNotCrossLaneOperation(const Instruction *I)
Return true if the instruction doesn't potentially cross vector lanes.
LLVM_ABI bool isKnownNonZero(const Value *V, const SimplifyQuery &Q, unsigned Depth=0)
Return true if the given value is known to be non-zero when defined.
LLVM_ABI Value * simplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS, const SimplifyQuery &Q)
Given operands for a BinaryOperator, fold the result or return null.
DWARFExpression::Operation Op
bool isSafeToSpeculativelyExecuteWithVariableReplaced(const Instruction *I, bool IgnoreUBImplyingAttrs=true)
Don't use information from its non-constant operands.
PredIterator< BasicBlock, Value::user_iterator > pred_iterator
Definition CFG.h:93
static bool hasSingleValue(const ValueLatticeElement &Val)
constexpr unsigned BitWidth
auto pred_begin(const MachineBasicBlock *BB)
LLVM_ABI AssumeRangeInfo getAssumeRangeInfo(OperandBundleUse)
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
auto predecessors(const MachineBasicBlock *BB)
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
LLVM_ABI SelectPatternResult matchSelectPattern(Value *V, Value *&LHS, Value *&RHS, Instruction::CastOps *CastOp=nullptr)
Pattern match integer [SU]MIN, [SU]MAX and ABS idioms, returning the kind and providing the out param...
#define N
A special type used by analysis passes to provide an address that identifies that particular analysis...
Definition Analysis.h:29
SelectPatternFlavor Flavor
static bool isMinOrMax(SelectPatternFlavor SPF)
When implementing this min/max pattern as fcmp; select, does the fcmp have to be ordered?