forked from llvm/llvm-project
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLazyValueInfo.cpp
1981 lines (1721 loc) · 76.5 KB
/
LazyValueInfo.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//===- LazyValueInfo.cpp - Value constraint analysis ------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file defines the interface for lazy computation of value constraint
// information.
//
//===----------------------------------------------------------------------===//
#include "llvm/Analysis/LazyValueInfo.h"
#include "llvm/ADT/DenseSet.h"
#include "llvm/ADT/Optional.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/Analysis/AssumptionCache.h"
#include "llvm/Analysis/ConstantFolding.h"
#include "llvm/Analysis/InstructionSimplify.h"
#include "llvm/Analysis/TargetLibraryInfo.h"
#include "llvm/Analysis/ValueLattice.h"
#include "llvm/Analysis/ValueTracking.h"
#include "llvm/IR/AssemblyAnnotationWriter.h"
#include "llvm/IR/CFG.h"
#include "llvm/IR/ConstantRange.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/Dominators.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/Intrinsics.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/PatternMatch.h"
#include "llvm/IR/ValueHandle.h"
#include "llvm/InitializePasses.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/FormattedStream.h"
#include "llvm/Support/KnownBits.h"
#include "llvm/Support/raw_ostream.h"
#include <map>
using namespace llvm;
using namespace PatternMatch;
#define DEBUG_TYPE "lazy-value-info"
// This is the number of worklist items we will process to try to discover an
// answer for a given value.
static const unsigned MaxProcessedPerValue = 500;
char LazyValueInfoWrapperPass::ID = 0;
LazyValueInfoWrapperPass::LazyValueInfoWrapperPass() : FunctionPass(ID) {
initializeLazyValueInfoWrapperPassPass(*PassRegistry::getPassRegistry());
}
INITIALIZE_PASS_BEGIN(LazyValueInfoWrapperPass, "lazy-value-info",
"Lazy Value Information Analysis", false, true)
INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
INITIALIZE_PASS_END(LazyValueInfoWrapperPass, "lazy-value-info",
"Lazy Value Information Analysis", false, true)
namespace llvm {
FunctionPass *createLazyValueInfoPass() { return new LazyValueInfoWrapperPass(); }
}
AnalysisKey LazyValueAnalysis::Key;
/// Returns true if this lattice value represents at most one possible value.
/// This is as precise as any lattice value can get while still representing
/// reachable code.
static bool hasSingleValue(const ValueLatticeElement &Val) {
if (Val.isConstantRange() &&
Val.getConstantRange().isSingleElement())
// Integer constants are single element ranges
return true;
if (Val.isConstant())
// Non integer constants
return true;
return false;
}
/// Combine two sets of facts about the same value into a single set of
/// facts. Note that this method is not suitable for merging facts along
/// different paths in a CFG; that's what the mergeIn function is for. This
/// is for merging facts gathered about the same value at the same location
/// through two independent means.
/// Notes:
/// * This method does not promise to return the most precise possible lattice
/// value implied by A and B. It is allowed to return any lattice element
/// which is at least as strong as *either* A or B (unless our facts
/// conflict, see below).
/// * Due to unreachable code, the intersection of two lattice values could be
/// contradictory. If this happens, we return some valid lattice value so as
/// not confuse the rest of LVI. Ideally, we'd always return Undefined, but
/// we do not make this guarantee. TODO: This would be a useful enhancement.
static ValueLatticeElement intersect(const ValueLatticeElement &A,
const ValueLatticeElement &B) {
// Undefined is the strongest state. It means the value is known to be along
// an unreachable path.
if (A.isUnknown())
return A;
if (B.isUnknown())
return B;
// If we gave up for one, but got a useable fact from the other, use it.
if (A.isOverdefined())
return B;
if (B.isOverdefined())
return A;
// Can't get any more precise than constants.
if (hasSingleValue(A))
return A;
if (hasSingleValue(B))
return B;
// Could be either constant range or not constant here.
if (!A.isConstantRange() || !B.isConstantRange()) {
// TODO: Arbitrary choice, could be improved
return A;
}
// Intersect two constant ranges
ConstantRange Range =
A.getConstantRange().intersectWith(B.getConstantRange());
// Note: An empty range is implicitly converted to unknown or undef depending
// on MayIncludeUndef internally.
return ValueLatticeElement::getRange(
std::move(Range), /*MayIncludeUndef=*/A.isConstantRangeIncludingUndef() ||
B.isConstantRangeIncludingUndef());
}
//===----------------------------------------------------------------------===//
// LazyValueInfoCache Decl
//===----------------------------------------------------------------------===//
namespace {
/// A callback value handle updates the cache when values are erased.
class LazyValueInfoCache;
struct LVIValueHandle final : public CallbackVH {
LazyValueInfoCache *Parent;
LVIValueHandle(Value *V, LazyValueInfoCache *P = nullptr)
: CallbackVH(V), Parent(P) { }
void deleted() override;
void allUsesReplacedWith(Value *V) override {
deleted();
}
};
} // end anonymous namespace
namespace {
using NonNullPointerSet = SmallDenseSet<AssertingVH<Value>, 2>;
/// This is the cache kept by LazyValueInfo which
/// maintains information about queries across the clients' queries.
class LazyValueInfoCache {
/// This is all of the cached information for one basic block. It contains
/// the per-value lattice elements, as well as a separate set for
/// overdefined values to reduce memory usage. Additionally pointers
/// dereferenced in the block are cached for nullability queries.
struct BlockCacheEntry {
SmallDenseMap<AssertingVH<Value>, ValueLatticeElement, 4> LatticeElements;
SmallDenseSet<AssertingVH<Value>, 4> OverDefined;
// None indicates that the nonnull pointers for this basic block
// block have not been computed yet.
Optional<NonNullPointerSet> NonNullPointers;
};
/// Cached information per basic block.
DenseMap<PoisoningVH<BasicBlock>, std::unique_ptr<BlockCacheEntry>>
BlockCache;
/// Set of value handles used to erase values from the cache on deletion.
DenseSet<LVIValueHandle, DenseMapInfo<Value *>> ValueHandles;
const BlockCacheEntry *getBlockEntry(BasicBlock *BB) const {
auto It = BlockCache.find_as(BB);
if (It == BlockCache.end())
return nullptr;
return It->second.get();
}
BlockCacheEntry *getOrCreateBlockEntry(BasicBlock *BB) {
auto It = BlockCache.find_as(BB);
if (It == BlockCache.end())
It = BlockCache.insert({ BB, std::make_unique<BlockCacheEntry>() })
.first;
return It->second.get();
}
void addValueHandle(Value *Val) {
auto HandleIt = ValueHandles.find_as(Val);
if (HandleIt == ValueHandles.end())
ValueHandles.insert({ Val, this });
}
public:
void insertResult(Value *Val, BasicBlock *BB,
const ValueLatticeElement &Result) {
BlockCacheEntry *Entry = getOrCreateBlockEntry(BB);
// Insert over-defined values into their own cache to reduce memory
// overhead.
if (Result.isOverdefined())
Entry->OverDefined.insert(Val);
else
Entry->LatticeElements.insert({ Val, Result });
addValueHandle(Val);
}
Optional<ValueLatticeElement> getCachedValueInfo(Value *V,
BasicBlock *BB) const {
const BlockCacheEntry *Entry = getBlockEntry(BB);
if (!Entry)
return None;
if (Entry->OverDefined.count(V))
return ValueLatticeElement::getOverdefined();
auto LatticeIt = Entry->LatticeElements.find_as(V);
if (LatticeIt == Entry->LatticeElements.end())
return None;
return LatticeIt->second;
}
bool isNonNullAtEndOfBlock(
Value *V, BasicBlock *BB,
function_ref<NonNullPointerSet(BasicBlock *)> InitFn) {
BlockCacheEntry *Entry = getOrCreateBlockEntry(BB);
if (!Entry->NonNullPointers) {
Entry->NonNullPointers = InitFn(BB);
for (Value *V : *Entry->NonNullPointers)
addValueHandle(V);
}
return Entry->NonNullPointers->count(V);
}
/// clear - Empty the cache.
void clear() {
BlockCache.clear();
ValueHandles.clear();
}
/// Inform the cache that a given value has been deleted.
void eraseValue(Value *V);
/// This is part of the update interface to inform the cache
/// that a block has been deleted.
void eraseBlock(BasicBlock *BB);
/// Updates the cache to remove any influence an overdefined value in
/// OldSucc might have (unless also overdefined in NewSucc). This just
/// flushes elements from the cache and does not add any.
void threadEdgeImpl(BasicBlock *OldSucc,BasicBlock *NewSucc);
};
}
void LazyValueInfoCache::eraseValue(Value *V) {
for (auto &Pair : BlockCache) {
Pair.second->LatticeElements.erase(V);
Pair.second->OverDefined.erase(V);
if (Pair.second->NonNullPointers)
Pair.second->NonNullPointers->erase(V);
}
auto HandleIt = ValueHandles.find_as(V);
if (HandleIt != ValueHandles.end())
ValueHandles.erase(HandleIt);
}
void LVIValueHandle::deleted() {
// This erasure deallocates *this, so it MUST happen after we're done
// using any and all members of *this.
Parent->eraseValue(*this);
}
void LazyValueInfoCache::eraseBlock(BasicBlock *BB) {
BlockCache.erase(BB);
}
void LazyValueInfoCache::threadEdgeImpl(BasicBlock *OldSucc,
BasicBlock *NewSucc) {
// When an edge in the graph has been threaded, values that we could not
// determine a value for before (i.e. were marked overdefined) may be
// possible to solve now. We do NOT try to proactively update these values.
// Instead, we clear their entries from the cache, and allow lazy updating to
// recompute them when needed.
// The updating process is fairly simple: we need to drop cached info
// for all values that were marked overdefined in OldSucc, and for those same
// values in any successor of OldSucc (except NewSucc) in which they were
// also marked overdefined.
std::vector<BasicBlock*> worklist;
worklist.push_back(OldSucc);
const BlockCacheEntry *Entry = getBlockEntry(OldSucc);
if (!Entry || Entry->OverDefined.empty())
return; // Nothing to process here.
SmallVector<Value *, 4> ValsToClear(Entry->OverDefined.begin(),
Entry->OverDefined.end());
// Use a worklist to perform a depth-first search of OldSucc's successors.
// NOTE: We do not need a visited list since any blocks we have already
// visited will have had their overdefined markers cleared already, and we
// thus won't loop to their successors.
while (!worklist.empty()) {
BasicBlock *ToUpdate = worklist.back();
worklist.pop_back();
// Skip blocks only accessible through NewSucc.
if (ToUpdate == NewSucc) continue;
// If a value was marked overdefined in OldSucc, and is here too...
auto OI = BlockCache.find_as(ToUpdate);
if (OI == BlockCache.end() || OI->second->OverDefined.empty())
continue;
auto &ValueSet = OI->second->OverDefined;
bool changed = false;
for (Value *V : ValsToClear) {
if (!ValueSet.erase(V))
continue;
// If we removed anything, then we potentially need to update
// blocks successors too.
changed = true;
}
if (!changed) continue;
llvm::append_range(worklist, successors(ToUpdate));
}
}
namespace {
/// An assembly annotator class to print LazyValueCache information in
/// comments.
class LazyValueInfoImpl;
class LazyValueInfoAnnotatedWriter : public AssemblyAnnotationWriter {
LazyValueInfoImpl *LVIImpl;
// While analyzing which blocks we can solve values for, we need the dominator
// information.
DominatorTree &DT;
public:
LazyValueInfoAnnotatedWriter(LazyValueInfoImpl *L, DominatorTree &DTree)
: LVIImpl(L), DT(DTree) {}
void emitBasicBlockStartAnnot(const BasicBlock *BB,
formatted_raw_ostream &OS) override;
void emitInstructionAnnot(const Instruction *I,
formatted_raw_ostream &OS) override;
};
}
namespace {
// The actual implementation of the lazy analysis and update. Note that the
// inheritance from LazyValueInfoCache is intended to be temporary while
// splitting the code and then transitioning to a has-a relationship.
class LazyValueInfoImpl {
/// Cached results from previous queries
LazyValueInfoCache TheCache;
/// This stack holds the state of the value solver during a query.
/// It basically emulates the callstack of the naive
/// recursive value lookup process.
SmallVector<std::pair<BasicBlock*, Value*>, 8> BlockValueStack;
/// Keeps track of which block-value pairs are in BlockValueStack.
DenseSet<std::pair<BasicBlock*, Value*> > BlockValueSet;
/// Push BV onto BlockValueStack unless it's already in there.
/// Returns true on success.
bool pushBlockValue(const std::pair<BasicBlock *, Value *> &BV) {
if (!BlockValueSet.insert(BV).second)
return false; // It's already in the stack.
LLVM_DEBUG(dbgs() << "PUSH: " << *BV.second << " in "
<< BV.first->getName() << "\n");
BlockValueStack.push_back(BV);
return true;
}
AssumptionCache *AC; ///< A pointer to the cache of @llvm.assume calls.
const DataLayout &DL; ///< A mandatory DataLayout
/// Declaration of the llvm.experimental.guard() intrinsic,
/// if it exists in the module.
Function *GuardDecl;
Optional<ValueLatticeElement> getBlockValue(Value *Val, BasicBlock *BB,
Instruction *CxtI);
Optional<ValueLatticeElement> getEdgeValue(Value *V, BasicBlock *F,
BasicBlock *T, Instruction *CxtI = nullptr);
// These methods process one work item and may add more. A false value
// returned means that the work item was not completely processed and must
// be revisited after going through the new items.
bool solveBlockValue(Value *Val, BasicBlock *BB);
Optional<ValueLatticeElement> solveBlockValueImpl(Value *Val, BasicBlock *BB);
Optional<ValueLatticeElement> solveBlockValueNonLocal(Value *Val,
BasicBlock *BB);
Optional<ValueLatticeElement> solveBlockValuePHINode(PHINode *PN,
BasicBlock *BB);
Optional<ValueLatticeElement> solveBlockValueSelect(SelectInst *S,
BasicBlock *BB);
Optional<ConstantRange> getRangeFor(Value *V, Instruction *CxtI,
BasicBlock *BB);
Optional<ValueLatticeElement> solveBlockValueBinaryOpImpl(
Instruction *I, BasicBlock *BB,
std::function<ConstantRange(const ConstantRange &,
const ConstantRange &)> OpFn);
Optional<ValueLatticeElement> solveBlockValueBinaryOp(BinaryOperator *BBI,
BasicBlock *BB);
Optional<ValueLatticeElement> solveBlockValueCast(CastInst *CI,
BasicBlock *BB);
Optional<ValueLatticeElement> solveBlockValueOverflowIntrinsic(
WithOverflowInst *WO, BasicBlock *BB);
Optional<ValueLatticeElement> solveBlockValueIntrinsic(IntrinsicInst *II,
BasicBlock *BB);
Optional<ValueLatticeElement> solveBlockValueExtractValue(
ExtractValueInst *EVI, BasicBlock *BB);
bool isNonNullAtEndOfBlock(Value *Val, BasicBlock *BB);
void intersectAssumeOrGuardBlockValueConstantRange(Value *Val,
ValueLatticeElement &BBLV,
Instruction *BBI);
void solve();
public:
/// This is the query interface to determine the lattice value for the
/// specified Value* at the context instruction (if specified) or at the
/// start of the block.
ValueLatticeElement getValueInBlock(Value *V, BasicBlock *BB,
Instruction *CxtI = nullptr);
/// This is the query interface to determine the lattice value for the
/// specified Value* at the specified instruction using only information
/// from assumes/guards and range metadata. Unlike getValueInBlock(), no
/// recursive query is performed.
ValueLatticeElement getValueAt(Value *V, Instruction *CxtI);
/// This is the query interface to determine the lattice
/// value for the specified Value* that is true on the specified edge.
ValueLatticeElement getValueOnEdge(Value *V, BasicBlock *FromBB,
BasicBlock *ToBB,
Instruction *CxtI = nullptr);
/// Complete flush all previously computed values
void clear() {
TheCache.clear();
}
/// Printing the LazyValueInfo Analysis.
void printLVI(Function &F, DominatorTree &DTree, raw_ostream &OS) {
LazyValueInfoAnnotatedWriter Writer(this, DTree);
F.print(OS, &Writer);
}
/// This is part of the update interface to inform the cache
/// that a block has been deleted.
void eraseBlock(BasicBlock *BB) {
TheCache.eraseBlock(BB);
}
/// This is the update interface to inform the cache that an edge from
/// PredBB to OldSucc has been threaded to be from PredBB to NewSucc.
void threadEdge(BasicBlock *PredBB,BasicBlock *OldSucc,BasicBlock *NewSucc);
LazyValueInfoImpl(AssumptionCache *AC, const DataLayout &DL,
Function *GuardDecl)
: AC(AC), DL(DL), GuardDecl(GuardDecl) {}
};
} // end anonymous namespace
void LazyValueInfoImpl::solve() {
SmallVector<std::pair<BasicBlock *, Value *>, 8> StartingStack(
BlockValueStack.begin(), BlockValueStack.end());
unsigned processedCount = 0;
while (!BlockValueStack.empty()) {
processedCount++;
// Abort if we have to process too many values to get a result for this one.
// Because of the design of the overdefined cache currently being per-block
// to avoid naming-related issues (IE it wants to try to give different
// results for the same name in different blocks), overdefined results don't
// get cached globally, which in turn means we will often try to rediscover
// the same overdefined result again and again. Once something like
// PredicateInfo is used in LVI or CVP, we should be able to make the
// overdefined cache global, and remove this throttle.
if (processedCount > MaxProcessedPerValue) {
LLVM_DEBUG(
dbgs() << "Giving up on stack because we are getting too deep\n");
// Fill in the original values
while (!StartingStack.empty()) {
std::pair<BasicBlock *, Value *> &e = StartingStack.back();
TheCache.insertResult(e.second, e.first,
ValueLatticeElement::getOverdefined());
StartingStack.pop_back();
}
BlockValueSet.clear();
BlockValueStack.clear();
return;
}
std::pair<BasicBlock *, Value *> e = BlockValueStack.back();
assert(BlockValueSet.count(e) && "Stack value should be in BlockValueSet!");
if (solveBlockValue(e.second, e.first)) {
// The work item was completely processed.
assert(BlockValueStack.back() == e && "Nothing should have been pushed!");
#ifndef NDEBUG
Optional<ValueLatticeElement> BBLV =
TheCache.getCachedValueInfo(e.second, e.first);
assert(BBLV && "Result should be in cache!");
LLVM_DEBUG(
dbgs() << "POP " << *e.second << " in " << e.first->getName() << " = "
<< *BBLV << "\n");
#endif
BlockValueStack.pop_back();
BlockValueSet.erase(e);
} else {
// More work needs to be done before revisiting.
assert(BlockValueStack.back() != e && "Stack should have been pushed!");
}
}
}
Optional<ValueLatticeElement> LazyValueInfoImpl::getBlockValue(
Value *Val, BasicBlock *BB, Instruction *CxtI) {
// If already a constant, there is nothing to compute.
if (Constant *VC = dyn_cast<Constant>(Val))
return ValueLatticeElement::get(VC);
if (Optional<ValueLatticeElement> OptLatticeVal =
TheCache.getCachedValueInfo(Val, BB)) {
intersectAssumeOrGuardBlockValueConstantRange(Val, *OptLatticeVal, CxtI);
return OptLatticeVal;
}
// We have hit a cycle, assume overdefined.
if (!pushBlockValue({ BB, Val }))
return ValueLatticeElement::getOverdefined();
// Yet to be resolved.
return None;
}
static ValueLatticeElement getFromRangeMetadata(Instruction *BBI) {
switch (BBI->getOpcode()) {
default: break;
case Instruction::Load:
case Instruction::Call:
case Instruction::Invoke:
if (MDNode *Ranges = BBI->getMetadata(LLVMContext::MD_range))
if (isa<IntegerType>(BBI->getType())) {
return ValueLatticeElement::getRange(
getConstantRangeFromMetadata(*Ranges));
}
break;
};
// Nothing known - will be intersected with other facts
return ValueLatticeElement::getOverdefined();
}
bool LazyValueInfoImpl::solveBlockValue(Value *Val, BasicBlock *BB) {
assert(!isa<Constant>(Val) && "Value should not be constant");
assert(!TheCache.getCachedValueInfo(Val, BB) &&
"Value should not be in cache");
// Hold off inserting this value into the Cache in case we have to return
// false and come back later.
Optional<ValueLatticeElement> Res = solveBlockValueImpl(Val, BB);
if (!Res)
// Work pushed, will revisit
return false;
TheCache.insertResult(Val, BB, *Res);
return true;
}
Optional<ValueLatticeElement> LazyValueInfoImpl::solveBlockValueImpl(
Value *Val, BasicBlock *BB) {
Instruction *BBI = dyn_cast<Instruction>(Val);
if (!BBI || BBI->getParent() != BB)
return solveBlockValueNonLocal(Val, BB);
if (PHINode *PN = dyn_cast<PHINode>(BBI))
return solveBlockValuePHINode(PN, BB);
if (auto *SI = dyn_cast<SelectInst>(BBI))
return solveBlockValueSelect(SI, BB);
// If this value is a nonnull pointer, record it's range and bailout. Note
// that for all other pointer typed values, we terminate the search at the
// definition. We could easily extend this to look through geps, bitcasts,
// and the like to prove non-nullness, but it's not clear that's worth it
// compile time wise. The context-insensitive value walk done inside
// isKnownNonZero gets most of the profitable cases at much less expense.
// This does mean that we have a sensitivity to where the defining
// instruction is placed, even if it could legally be hoisted much higher.
// That is unfortunate.
PointerType *PT = dyn_cast<PointerType>(BBI->getType());
if (PT && isKnownNonZero(BBI, DL))
return ValueLatticeElement::getNot(ConstantPointerNull::get(PT));
if (BBI->getType()->isIntegerTy()) {
if (auto *CI = dyn_cast<CastInst>(BBI))
return solveBlockValueCast(CI, BB);
if (BinaryOperator *BO = dyn_cast<BinaryOperator>(BBI))
return solveBlockValueBinaryOp(BO, BB);
if (auto *EVI = dyn_cast<ExtractValueInst>(BBI))
return solveBlockValueExtractValue(EVI, BB);
if (auto *II = dyn_cast<IntrinsicInst>(BBI))
return solveBlockValueIntrinsic(II, BB);
}
LLVM_DEBUG(dbgs() << " compute BB '" << BB->getName()
<< "' - unknown inst def found.\n");
return getFromRangeMetadata(BBI);
}
static void AddNonNullPointer(Value *Ptr, NonNullPointerSet &PtrSet) {
// TODO: Use NullPointerIsDefined instead.
if (Ptr->getType()->getPointerAddressSpace() == 0)
PtrSet.insert(getUnderlyingObject(Ptr));
}
static void AddNonNullPointersByInstruction(
Instruction *I, NonNullPointerSet &PtrSet) {
if (LoadInst *L = dyn_cast<LoadInst>(I)) {
AddNonNullPointer(L->getPointerOperand(), PtrSet);
} else if (StoreInst *S = dyn_cast<StoreInst>(I)) {
AddNonNullPointer(S->getPointerOperand(), PtrSet);
} else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) {
if (MI->isVolatile()) return;
// FIXME: check whether it has a valuerange that excludes zero?
ConstantInt *Len = dyn_cast<ConstantInt>(MI->getLength());
if (!Len || Len->isZero()) return;
AddNonNullPointer(MI->getRawDest(), PtrSet);
if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI))
AddNonNullPointer(MTI->getRawSource(), PtrSet);
}
}
bool LazyValueInfoImpl::isNonNullAtEndOfBlock(Value *Val, BasicBlock *BB) {
if (NullPointerIsDefined(BB->getParent(),
Val->getType()->getPointerAddressSpace()))
return false;
Val = Val->stripInBoundsOffsets();
return TheCache.isNonNullAtEndOfBlock(Val, BB, [](BasicBlock *BB) {
NonNullPointerSet NonNullPointers;
for (Instruction &I : *BB)
AddNonNullPointersByInstruction(&I, NonNullPointers);
return NonNullPointers;
});
}
Optional<ValueLatticeElement> LazyValueInfoImpl::solveBlockValueNonLocal(
Value *Val, BasicBlock *BB) {
ValueLatticeElement Result; // Start Undefined.
// If this is the entry block, we must be asking about an argument. The
// value is overdefined.
if (BB->isEntryBlock()) {
assert(isa<Argument>(Val) && "Unknown live-in to the entry block");
return ValueLatticeElement::getOverdefined();
}
// Loop over all of our predecessors, merging what we know from them into
// result. If we encounter an unexplored predecessor, we eagerly explore it
// in a depth first manner. In practice, this has the effect of discovering
// paths we can't analyze eagerly without spending compile times analyzing
// other paths. This heuristic benefits from the fact that predecessors are
// frequently arranged such that dominating ones come first and we quickly
// find a path to function entry. TODO: We should consider explicitly
// canonicalizing to make this true rather than relying on this happy
// accident.
for (BasicBlock *Pred : predecessors(BB)) {
Optional<ValueLatticeElement> EdgeResult = getEdgeValue(Val, Pred, BB);
if (!EdgeResult)
// Explore that input, then return here
return None;
Result.mergeIn(*EdgeResult);
// If we hit overdefined, exit early. The BlockVals entry is already set
// to overdefined.
if (Result.isOverdefined()) {
LLVM_DEBUG(dbgs() << " compute BB '" << BB->getName()
<< "' - overdefined because of pred (non local).\n");
return Result;
}
}
// Return the merged value, which is more precise than 'overdefined'.
assert(!Result.isOverdefined());
return Result;
}
Optional<ValueLatticeElement> LazyValueInfoImpl::solveBlockValuePHINode(
PHINode *PN, BasicBlock *BB) {
ValueLatticeElement Result; // Start Undefined.
// Loop over all of our predecessors, merging what we know from them into
// result. See the comment about the chosen traversal order in
// solveBlockValueNonLocal; the same reasoning applies here.
for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
BasicBlock *PhiBB = PN->getIncomingBlock(i);
Value *PhiVal = PN->getIncomingValue(i);
// Note that we can provide PN as the context value to getEdgeValue, even
// though the results will be cached, because PN is the value being used as
// the cache key in the caller.
Optional<ValueLatticeElement> EdgeResult =
getEdgeValue(PhiVal, PhiBB, BB, PN);
if (!EdgeResult)
// Explore that input, then return here
return None;
Result.mergeIn(*EdgeResult);
// If we hit overdefined, exit early. The BlockVals entry is already set
// to overdefined.
if (Result.isOverdefined()) {
LLVM_DEBUG(dbgs() << " compute BB '" << BB->getName()
<< "' - overdefined because of pred (local).\n");
return Result;
}
}
// Return the merged value, which is more precise than 'overdefined'.
assert(!Result.isOverdefined() && "Possible PHI in entry block?");
return Result;
}
static ValueLatticeElement getValueFromCondition(Value *Val, Value *Cond,
bool isTrueDest = true);
// If we can determine a constraint on the value given conditions assumed by
// the program, intersect those constraints with BBLV
void LazyValueInfoImpl::intersectAssumeOrGuardBlockValueConstantRange(
Value *Val, ValueLatticeElement &BBLV, Instruction *BBI) {
BBI = BBI ? BBI : dyn_cast<Instruction>(Val);
if (!BBI)
return;
BasicBlock *BB = BBI->getParent();
for (auto &AssumeVH : AC->assumptionsFor(Val)) {
if (!AssumeVH)
continue;
// Only check assumes in the block of the context instruction. Other
// assumes will have already been taken into account when the value was
// propagated from predecessor blocks.
auto *I = cast<CallInst>(AssumeVH);
if (I->getParent() != BB || !isValidAssumeForContext(I, BBI))
continue;
BBLV = intersect(BBLV, getValueFromCondition(Val, I->getArgOperand(0)));
}
// If guards are not used in the module, don't spend time looking for them
if (GuardDecl && !GuardDecl->use_empty() &&
BBI->getIterator() != BB->begin()) {
for (Instruction &I : make_range(std::next(BBI->getIterator().getReverse()),
BB->rend())) {
Value *Cond = nullptr;
if (match(&I, m_Intrinsic<Intrinsic::experimental_guard>(m_Value(Cond))))
BBLV = intersect(BBLV, getValueFromCondition(Val, Cond));
}
}
if (BBLV.isOverdefined()) {
// Check whether we're checking at the terminator, and the pointer has
// been dereferenced in this block.
PointerType *PTy = dyn_cast<PointerType>(Val->getType());
if (PTy && BB->getTerminator() == BBI &&
isNonNullAtEndOfBlock(Val, BB))
BBLV = ValueLatticeElement::getNot(ConstantPointerNull::get(PTy));
}
}
static ConstantRange getConstantRangeOrFull(const ValueLatticeElement &Val,
Type *Ty, const DataLayout &DL) {
if (Val.isConstantRange())
return Val.getConstantRange();
return ConstantRange::getFull(DL.getTypeSizeInBits(Ty));
}
Optional<ValueLatticeElement> LazyValueInfoImpl::solveBlockValueSelect(
SelectInst *SI, BasicBlock *BB) {
// Recurse on our inputs if needed
Optional<ValueLatticeElement> OptTrueVal =
getBlockValue(SI->getTrueValue(), BB, SI);
if (!OptTrueVal)
return None;
ValueLatticeElement &TrueVal = *OptTrueVal;
Optional<ValueLatticeElement> OptFalseVal =
getBlockValue(SI->getFalseValue(), BB, SI);
if (!OptFalseVal)
return None;
ValueLatticeElement &FalseVal = *OptFalseVal;
if (TrueVal.isConstantRange() || FalseVal.isConstantRange()) {
const ConstantRange &TrueCR =
getConstantRangeOrFull(TrueVal, SI->getType(), DL);
const ConstantRange &FalseCR =
getConstantRangeOrFull(FalseVal, SI->getType(), DL);
Value *LHS = nullptr;
Value *RHS = nullptr;
SelectPatternResult SPR = matchSelectPattern(SI, LHS, RHS);
// Is this a min specifically of our two inputs? (Avoid the risk of
// ValueTracking getting smarter looking back past our immediate inputs.)
if (SelectPatternResult::isMinOrMax(SPR.Flavor) &&
((LHS == SI->getTrueValue() && RHS == SI->getFalseValue()) ||
(RHS == SI->getTrueValue() && LHS == SI->getFalseValue()))) {
ConstantRange ResultCR = [&]() {
switch (SPR.Flavor) {
default:
llvm_unreachable("unexpected minmax type!");
case SPF_SMIN: /// Signed minimum
return TrueCR.smin(FalseCR);
case SPF_UMIN: /// Unsigned minimum
return TrueCR.umin(FalseCR);
case SPF_SMAX: /// Signed maximum
return TrueCR.smax(FalseCR);
case SPF_UMAX: /// Unsigned maximum
return TrueCR.umax(FalseCR);
};
}();
return ValueLatticeElement::getRange(
ResultCR, TrueVal.isConstantRangeIncludingUndef() ||
FalseVal.isConstantRangeIncludingUndef());
}
if (SPR.Flavor == SPF_ABS) {
if (LHS == SI->getTrueValue())
return ValueLatticeElement::getRange(
TrueCR.abs(), TrueVal.isConstantRangeIncludingUndef());
if (LHS == SI->getFalseValue())
return ValueLatticeElement::getRange(
FalseCR.abs(), FalseVal.isConstantRangeIncludingUndef());
}
if (SPR.Flavor == SPF_NABS) {
ConstantRange Zero(APInt::getZero(TrueCR.getBitWidth()));
if (LHS == SI->getTrueValue())
return ValueLatticeElement::getRange(
Zero.sub(TrueCR.abs()), FalseVal.isConstantRangeIncludingUndef());
if (LHS == SI->getFalseValue())
return ValueLatticeElement::getRange(
Zero.sub(FalseCR.abs()), FalseVal.isConstantRangeIncludingUndef());
}
}
// Can we constrain the facts about the true and false values by using the
// condition itself? This shows up with idioms like e.g. select(a > 5, a, 5).
// TODO: We could potentially refine an overdefined true value above.
Value *Cond = SI->getCondition();
TrueVal = intersect(TrueVal,
getValueFromCondition(SI->getTrueValue(), Cond, true));
FalseVal = intersect(FalseVal,
getValueFromCondition(SI->getFalseValue(), Cond, false));
ValueLatticeElement Result = TrueVal;
Result.mergeIn(FalseVal);
return Result;
}
Optional<ConstantRange> LazyValueInfoImpl::getRangeFor(Value *V,
Instruction *CxtI,
BasicBlock *BB) {
Optional<ValueLatticeElement> OptVal = getBlockValue(V, BB, CxtI);
if (!OptVal)
return None;
return getConstantRangeOrFull(*OptVal, V->getType(), DL);
}
Optional<ValueLatticeElement> LazyValueInfoImpl::solveBlockValueCast(
CastInst *CI, BasicBlock *BB) {
// Without knowing how wide the input is, we can't analyze it in any useful
// way.
if (!CI->getOperand(0)->getType()->isSized())
return ValueLatticeElement::getOverdefined();
// Filter out casts we don't know how to reason about before attempting to
// recurse on our operand. This can cut a long search short if we know we're
// not going to be able to get any useful information anways.
switch (CI->getOpcode()) {
case Instruction::Trunc:
case Instruction::SExt:
case Instruction::ZExt:
case Instruction::BitCast:
break;
default:
// Unhandled instructions are overdefined.
LLVM_DEBUG(dbgs() << " compute BB '" << BB->getName()
<< "' - overdefined (unknown cast).\n");
return ValueLatticeElement::getOverdefined();
}
// Figure out the range of the LHS. If that fails, we still apply the
// transfer rule on the full set since we may be able to locally infer
// interesting facts.
Optional<ConstantRange> LHSRes = getRangeFor(CI->getOperand(0), CI, BB);
if (!LHSRes.hasValue())
// More work to do before applying this transfer rule.
return None;
const ConstantRange &LHSRange = LHSRes.getValue();
const unsigned ResultBitWidth = CI->getType()->getIntegerBitWidth();
// NOTE: We're currently limited by the set of operations that ConstantRange
// can evaluate symbolically. Enhancing that set will allows us to analyze
// more definitions.
return ValueLatticeElement::getRange(LHSRange.castOp(CI->getOpcode(),
ResultBitWidth));
}
Optional<ValueLatticeElement> LazyValueInfoImpl::solveBlockValueBinaryOpImpl(
Instruction *I, BasicBlock *BB,
std::function<ConstantRange(const ConstantRange &,
const ConstantRange &)> OpFn) {
// Figure out the ranges of the operands. If that fails, use a
// conservative range, but apply the transfer rule anyways. This
// lets us pick up facts from expressions like "and i32 (call i32
// @foo()), 32"
Optional<ConstantRange> LHSRes = getRangeFor(I->getOperand(0), I, BB);
Optional<ConstantRange> RHSRes = getRangeFor(I->getOperand(1), I, BB);
if (!LHSRes.hasValue() || !RHSRes.hasValue())
// More work to do before applying this transfer rule.
return None;
const ConstantRange &LHSRange = LHSRes.getValue();
const ConstantRange &RHSRange = RHSRes.getValue();
return ValueLatticeElement::getRange(OpFn(LHSRange, RHSRange));
}
Optional<ValueLatticeElement> LazyValueInfoImpl::solveBlockValueBinaryOp(
BinaryOperator *BO, BasicBlock *BB) {
assert(BO->getOperand(0)->getType()->isSized() &&
"all operands to binary operators are sized");
if (BO->getOpcode() == Instruction::Xor) {
// Xor is the only operation not supported by ConstantRange::binaryOp().
LLVM_DEBUG(dbgs() << " compute BB '" << BB->getName()
<< "' - overdefined (unknown binary operator).\n");
return ValueLatticeElement::getOverdefined();
}
if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(BO)) {
unsigned NoWrapKind = 0;
if (OBO->hasNoUnsignedWrap())
NoWrapKind |= OverflowingBinaryOperator::NoUnsignedWrap;
if (OBO->hasNoSignedWrap())
NoWrapKind |= OverflowingBinaryOperator::NoSignedWrap;
return solveBlockValueBinaryOpImpl(
BO, BB,
[BO, NoWrapKind](const ConstantRange &CR1, const ConstantRange &CR2) {
return CR1.overflowingBinaryOp(BO->getOpcode(), CR2, NoWrapKind);
});
}
return solveBlockValueBinaryOpImpl(
BO, BB, [BO](const ConstantRange &CR1, const ConstantRange &CR2) {
return CR1.binaryOp(BO->getOpcode(), CR2);
});
}
Optional<ValueLatticeElement>
LazyValueInfoImpl::solveBlockValueOverflowIntrinsic(WithOverflowInst *WO,
BasicBlock *BB) {
return solveBlockValueBinaryOpImpl(
WO, BB, [WO](const ConstantRange &CR1, const ConstantRange &CR2) {
return CR1.binaryOp(WO->getBinaryOp(), CR2);
});
}
Optional<ValueLatticeElement> LazyValueInfoImpl::solveBlockValueIntrinsic(
IntrinsicInst *II, BasicBlock *BB) {
if (!ConstantRange::isIntrinsicSupported(II->getIntrinsicID())) {
LLVM_DEBUG(dbgs() << " compute BB '" << BB->getName()
<< "' - unknown intrinsic.\n");
return getFromRangeMetadata(II);