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