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