forked from llvm/llvm-project
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLazyValueInfo.cpp
1611 lines (1389 loc) · 56 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++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// 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/STLExtras.h"
#include "llvm/Analysis/AssumptionCache.h"
#include "llvm/Analysis/ConstantFolding.h"
#include "llvm/Analysis/TargetLibraryInfo.h"
#include "llvm/Analysis/ValueTracking.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/LLVMContext.h"
#include "llvm/IR/PatternMatch.h"
#include "llvm/IR/ValueHandle.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
#include <map>
#include <stack>
using namespace llvm;
using namespace PatternMatch;
#define DEBUG_TYPE "lazy-value-info"
char LazyValueInfo::ID = 0;
INITIALIZE_PASS_BEGIN(LazyValueInfo, "lazy-value-info",
"Lazy Value Information Analysis", false, true)
INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
INITIALIZE_PASS_END(LazyValueInfo, "lazy-value-info",
"Lazy Value Information Analysis", false, true)
namespace llvm {
FunctionPass *createLazyValueInfoPass() { return new LazyValueInfo(); }
}
//===----------------------------------------------------------------------===//
// LVILatticeVal
//===----------------------------------------------------------------------===//
/// This is the information tracked by LazyValueInfo for each value.
///
/// FIXME: This is basically just for bringup, this can be made a lot more rich
/// in the future.
///
namespace {
class LVILatticeVal {
enum LatticeValueTy {
/// This Value has no known value yet.
undefined,
/// This Value has a specific constant value.
constant,
/// This Value is known to not have the specified value.
notconstant,
/// The Value falls within this range.
constantrange,
/// This value is not known to be constant, and we know that it has a value.
overdefined
};
/// Val: This stores the current lattice value along with the Constant* for
/// the constant if this is a 'constant' or 'notconstant' value.
LatticeValueTy Tag;
Constant *Val;
ConstantRange Range;
public:
LVILatticeVal() : Tag(undefined), Val(nullptr), Range(1, true) {}
static LVILatticeVal get(Constant *C) {
LVILatticeVal Res;
if (!isa<UndefValue>(C))
Res.markConstant(C);
return Res;
}
static LVILatticeVal getNot(Constant *C) {
LVILatticeVal Res;
if (!isa<UndefValue>(C))
Res.markNotConstant(C);
return Res;
}
static LVILatticeVal getRange(ConstantRange CR) {
LVILatticeVal Res;
Res.markConstantRange(std::move(CR));
return Res;
}
static LVILatticeVal getOverdefined() {
LVILatticeVal Res;
Res.markOverdefined();
return Res;
}
bool isUndefined() const { return Tag == undefined; }
bool isConstant() const { return Tag == constant; }
bool isNotConstant() const { return Tag == notconstant; }
bool isConstantRange() const { return Tag == constantrange; }
bool isOverdefined() const { return Tag == overdefined; }
Constant *getConstant() const {
assert(isConstant() && "Cannot get the constant of a non-constant!");
return Val;
}
Constant *getNotConstant() const {
assert(isNotConstant() && "Cannot get the constant of a non-notconstant!");
return Val;
}
ConstantRange getConstantRange() const {
assert(isConstantRange() &&
"Cannot get the constant-range of a non-constant-range!");
return Range;
}
/// Return true if this is a change in status.
bool markOverdefined() {
if (isOverdefined())
return false;
Tag = overdefined;
return true;
}
/// Return true if this is a change in status.
bool markConstant(Constant *V) {
assert(V && "Marking constant with NULL");
if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
return markConstantRange(ConstantRange(CI->getValue()));
if (isa<UndefValue>(V))
return false;
assert((!isConstant() || getConstant() == V) &&
"Marking constant with different value");
assert(isUndefined());
Tag = constant;
Val = V;
return true;
}
/// Return true if this is a change in status.
bool markNotConstant(Constant *V) {
assert(V && "Marking constant with NULL");
if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
return markConstantRange(ConstantRange(CI->getValue()+1, CI->getValue()));
if (isa<UndefValue>(V))
return false;
assert((!isConstant() || getConstant() != V) &&
"Marking constant !constant with same value");
assert((!isNotConstant() || getNotConstant() == V) &&
"Marking !constant with different value");
assert(isUndefined() || isConstant());
Tag = notconstant;
Val = V;
return true;
}
/// Return true if this is a change in status.
bool markConstantRange(ConstantRange NewR) {
if (isConstantRange()) {
if (NewR.isEmptySet())
return markOverdefined();
bool changed = Range != NewR;
Range = std::move(NewR);
return changed;
}
assert(isUndefined());
if (NewR.isEmptySet())
return markOverdefined();
Tag = constantrange;
Range = std::move(NewR);
return true;
}
/// Merge the specified lattice value into this one, updating this
/// one and returning true if anything changed.
bool mergeIn(const LVILatticeVal &RHS, const DataLayout &DL) {
if (RHS.isUndefined() || isOverdefined()) return false;
if (RHS.isOverdefined()) return markOverdefined();
if (isUndefined()) {
Tag = RHS.Tag;
Val = RHS.Val;
Range = RHS.Range;
return true;
}
if (isConstant()) {
if (RHS.isConstant()) {
if (Val == RHS.Val)
return false;
return markOverdefined();
}
if (RHS.isNotConstant()) {
if (Val == RHS.Val)
return markOverdefined();
// Unless we can prove that the two Constants are different, we must
// move to overdefined.
if (ConstantInt *Res =
dyn_cast<ConstantInt>(ConstantFoldCompareInstOperands(
CmpInst::ICMP_NE, getConstant(), RHS.getNotConstant(), DL)))
if (Res->isOne())
return markNotConstant(RHS.getNotConstant());
return markOverdefined();
}
// RHS is a ConstantRange, LHS is a non-integer Constant.
// FIXME: consider the case where RHS is a range [1, 0) and LHS is
// a function. The correct result is to pick up RHS.
return markOverdefined();
}
if (isNotConstant()) {
if (RHS.isConstant()) {
if (Val == RHS.Val)
return markOverdefined();
// Unless we can prove that the two Constants are different, we must
// move to overdefined.
if (ConstantInt *Res =
dyn_cast<ConstantInt>(ConstantFoldCompareInstOperands(
CmpInst::ICMP_NE, getNotConstant(), RHS.getConstant(), DL)))
if (Res->isOne())
return false;
return markOverdefined();
}
if (RHS.isNotConstant()) {
if (Val == RHS.Val)
return false;
return markOverdefined();
}
return markOverdefined();
}
assert(isConstantRange() && "New LVILattice type?");
if (!RHS.isConstantRange())
return markOverdefined();
ConstantRange NewR = Range.unionWith(RHS.getConstantRange());
if (NewR.isFullSet())
return markOverdefined();
return markConstantRange(NewR);
}
};
} // end anonymous namespace.
namespace llvm {
raw_ostream &operator<<(raw_ostream &OS, const LVILatticeVal &Val)
LLVM_ATTRIBUTE_USED;
raw_ostream &operator<<(raw_ostream &OS, const LVILatticeVal &Val) {
if (Val.isUndefined())
return OS << "undefined";
if (Val.isOverdefined())
return OS << "overdefined";
if (Val.isNotConstant())
return OS << "notconstant<" << *Val.getNotConstant() << '>';
else if (Val.isConstantRange())
return OS << "constantrange<" << Val.getConstantRange().getLower() << ", "
<< Val.getConstantRange().getUpper() << '>';
return OS << "constant<" << *Val.getConstant() << '>';
}
}
/// 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(LVILatticeVal 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 LVILatticeVal intersect(LVILatticeVal A, LVILatticeVal B) {
// Undefined is the strongest state. It means the value is known to be along
// an unreachable path.
if (A.isUndefined())
return A;
if (B.isUndefined())
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 overdefined internally.
// TODO: We could instead use Undefined here since we've proven a conflict
// and thus know this path must be unreachable.
return LVILatticeVal::getRange(std::move(Range));
}
//===----------------------------------------------------------------------===//
// 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)
: CallbackVH(V), Parent(P) { }
void deleted() override;
void allUsesReplacedWith(Value *V) override {
deleted();
}
};
}
namespace {
/// This is the cache kept by LazyValueInfo which
/// maintains information about queries across the clients' queries.
class LazyValueInfoCache {
/// This is all of the cached block information for exactly one Value*.
/// The entries are sorted by the BasicBlock* of the
/// entries, allowing us to do a lookup with a binary search.
/// Over-defined lattice values are recorded in OverDefinedCache to reduce
/// memory overhead.
typedef SmallDenseMap<AssertingVH<BasicBlock>, LVILatticeVal, 4>
ValueCacheEntryTy;
/// This is all of the cached information for all values,
/// mapped from Value* to key information.
std::map<LVIValueHandle, ValueCacheEntryTy> ValueCache;
/// This tracks, on a per-block basis, the set of values that are
/// over-defined at the end of that block.
typedef DenseMap<AssertingVH<BasicBlock>, SmallPtrSet<Value *, 4>>
OverDefinedCacheTy;
OverDefinedCacheTy OverDefinedCache;
/// Keep track of all blocks that we have ever seen, so we
/// don't spend time removing unused blocks from our caches.
DenseSet<AssertingVH<BasicBlock> > SeenBlocks;
/// This stack holds the state of the value solver during a query.
/// It basically emulates the callstack of the naive
/// recursive value lookup process.
std::stack<std::pair<BasicBlock*, Value*> > 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.
DEBUG(dbgs() << "PUSH: " << *BV.second << " in " << BV.first->getName()
<< "\n");
BlockValueStack.push(BV);
return true;
}
AssumptionCache *AC; ///< A pointer to the cache of @llvm.assume calls.
const DataLayout &DL; ///< A mandatory DataLayout
DominatorTree *DT; ///< An optional DT pointer.
friend struct LVIValueHandle;
void insertResult(Value *Val, BasicBlock *BB, const LVILatticeVal &Result) {
SeenBlocks.insert(BB);
// Insert over-defined values into their own cache to reduce memory
// overhead.
if (Result.isOverdefined())
OverDefinedCache[BB].insert(Val);
else
lookup(Val)[BB] = Result;
}
LVILatticeVal getBlockValue(Value *Val, BasicBlock *BB);
bool getEdgeValue(Value *V, BasicBlock *F, BasicBlock *T,
LVILatticeVal &Result,
Instruction *CxtI = nullptr);
bool hasBlockValue(Value *Val, BasicBlock *BB);
// 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);
bool solveBlockValueNonLocal(LVILatticeVal &BBLV,
Value *Val, BasicBlock *BB);
bool solveBlockValuePHINode(LVILatticeVal &BBLV,
PHINode *PN, BasicBlock *BB);
bool solveBlockValueSelect(LVILatticeVal &BBLV,
SelectInst *S, BasicBlock *BB);
bool solveBlockValueConstantRange(LVILatticeVal &BBLV,
Instruction *BBI, BasicBlock *BB);
void intersectAssumeBlockValueConstantRange(Value *Val, LVILatticeVal &BBLV,
Instruction *BBI);
void solve();
ValueCacheEntryTy &lookup(Value *V) {
return ValueCache[LVIValueHandle(V, this)];
}
bool isOverdefined(Value *V, BasicBlock *BB) const {
auto ODI = OverDefinedCache.find(BB);
if (ODI == OverDefinedCache.end())
return false;
return ODI->second.count(V);
}
bool hasCachedValueInfo(Value *V, BasicBlock *BB) {
if (isOverdefined(V, BB))
return true;
LVIValueHandle ValHandle(V, this);
auto I = ValueCache.find(ValHandle);
if (I == ValueCache.end())
return false;
return I->second.count(BB);
}
LVILatticeVal getCachedValueInfo(Value *V, BasicBlock *BB) {
if (isOverdefined(V, BB))
return LVILatticeVal::getOverdefined();
return lookup(V)[BB];
}
public:
/// This is the query interface to determine the lattice
/// value for the specified Value* at the end of the specified block.
LVILatticeVal 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 (generally
/// from an assume intrinsic).
LVILatticeVal 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.
LVILatticeVal getValueOnEdge(Value *V, BasicBlock *FromBB,BasicBlock *ToBB,
Instruction *CxtI = nullptr);
/// 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);
/// This is part of the update interface to inform the cache
/// that a block has been deleted.
void eraseBlock(BasicBlock *BB);
/// clear - Empty the cache.
void clear() {
SeenBlocks.clear();
ValueCache.clear();
OverDefinedCache.clear();
}
LazyValueInfoCache(AssumptionCache *AC, const DataLayout &DL,
DominatorTree *DT = nullptr)
: AC(AC), DL(DL), DT(DT) {}
};
} // end anonymous namespace
void LVIValueHandle::deleted() {
SmallVector<AssertingVH<BasicBlock>, 4> ToErase;
for (auto &I : Parent->OverDefinedCache) {
SmallPtrSetImpl<Value *> &ValueSet = I.second;
if (ValueSet.count(getValPtr()))
ValueSet.erase(getValPtr());
if (ValueSet.empty())
ToErase.push_back(I.first);
}
for (auto &BB : ToErase)
Parent->OverDefinedCache.erase(BB);
// This erasure deallocates *this, so it MUST happen after we're done
// using any and all members of *this.
Parent->ValueCache.erase(*this);
}
void LazyValueInfoCache::eraseBlock(BasicBlock *BB) {
// Shortcut if we have never seen this block.
DenseSet<AssertingVH<BasicBlock> >::iterator I = SeenBlocks.find(BB);
if (I == SeenBlocks.end())
return;
SeenBlocks.erase(I);
auto ODI = OverDefinedCache.find(BB);
if (ODI != OverDefinedCache.end())
OverDefinedCache.erase(ODI);
for (auto I = ValueCache.begin(), E = ValueCache.end(); I != E; ++I)
I->second.erase(BB);
}
void LazyValueInfoCache::solve() {
while (!BlockValueStack.empty()) {
std::pair<BasicBlock*, Value*> &e = BlockValueStack.top();
assert(BlockValueSet.count(e) && "Stack value should be in BlockValueSet!");
if (solveBlockValue(e.second, e.first)) {
// The work item was completely processed.
assert(BlockValueStack.top() == e && "Nothing should have been pushed!");
assert(hasCachedValueInfo(e.second, e.first) &&
"Result should be in cache!");
DEBUG(dbgs() << "POP " << *e.second << " in " << e.first->getName()
<< " = " << getCachedValueInfo(e.second, e.first) << "\n");
BlockValueStack.pop();
BlockValueSet.erase(e);
} else {
// More work needs to be done before revisiting.
assert(BlockValueStack.top() != e && "Stack should have been pushed!");
}
}
}
bool LazyValueInfoCache::hasBlockValue(Value *Val, BasicBlock *BB) {
// If already a constant, there is nothing to compute.
if (isa<Constant>(Val))
return true;
return hasCachedValueInfo(Val, BB);
}
LVILatticeVal LazyValueInfoCache::getBlockValue(Value *Val, BasicBlock *BB) {
// If already a constant, there is nothing to compute.
if (Constant *VC = dyn_cast<Constant>(Val))
return LVILatticeVal::get(VC);
SeenBlocks.insert(BB);
return getCachedValueInfo(Val, BB);
}
static LVILatticeVal 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 LVILatticeVal::getRange(getConstantRangeFromMetadata(*Ranges));
}
break;
};
// Nothing known - will be intersected with other facts
return LVILatticeVal::getOverdefined();
}
bool LazyValueInfoCache::solveBlockValue(Value *Val, BasicBlock *BB) {
if (isa<Constant>(Val))
return true;
if (hasCachedValueInfo(Val, BB)) {
// If we have a cached value, use that.
DEBUG(dbgs() << " reuse BB '" << BB->getName()
<< "' val=" << getCachedValueInfo(Val, BB) << '\n');
// Since we're reusing a cached value, we don't need to update the
// OverDefinedCache. The cache will have been properly updated whenever the
// cached value was inserted.
return true;
}
// Hold off inserting this value into the Cache in case we have to return
// false and come back later.
LVILatticeVal Res;
Instruction *BBI = dyn_cast<Instruction>(Val);
if (!BBI || BBI->getParent() != BB) {
if (!solveBlockValueNonLocal(Res, Val, BB))
return false;
insertResult(Val, BB, Res);
return true;
}
if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
if (!solveBlockValuePHINode(Res, PN, BB))
return false;
insertResult(Val, BB, Res);
return true;
}
if (auto *SI = dyn_cast<SelectInst>(BBI)) {
if (!solveBlockValueSelect(Res, SI, BB))
return false;
insertResult(Val, BB, Res);
return true;
}
// If this value is a nonnull pointer, record it's range and bailout.
PointerType *PT = dyn_cast<PointerType>(BBI->getType());
if (PT && isKnownNonNull(BBI)) {
Res = LVILatticeVal::getNot(ConstantPointerNull::get(PT));
insertResult(Val, BB, Res);
return true;
}
// If this is an instruction which supports range metadata, intersect the
// implied range.
Res = intersect(Res, getFromRangeMetadata(BBI));
// We can only analyze the definitions of certain classes of instructions
// (integral binops and casts at the moment), so bail if this isn't one.
LVILatticeVal Result;
if ((!isa<BinaryOperator>(BBI) && !isa<CastInst>(BBI)) ||
!BBI->getType()->isIntegerTy()) {
DEBUG(dbgs() << " compute BB '" << BB->getName()
<< "' - overdefined because inst def found.\n");
Res.markOverdefined();
insertResult(Val, BB, Res);
return true;
}
// FIXME: We're currently limited to binops with a constant RHS. This should
// be improved.
BinaryOperator *BO = dyn_cast<BinaryOperator>(BBI);
if (BO && !isa<ConstantInt>(BO->getOperand(1))) {
DEBUG(dbgs() << " compute BB '" << BB->getName()
<< "' - overdefined because inst def found.\n");
Res.markOverdefined();
insertResult(Val, BB, Res);
return true;
}
if (!solveBlockValueConstantRange(Res, BBI, BB))
return false;
insertResult(Val, BB, Res);
return true;
}
static bool InstructionDereferencesPointer(Instruction *I, Value *Ptr) {
if (LoadInst *L = dyn_cast<LoadInst>(I)) {
return L->getPointerAddressSpace() == 0 &&
GetUnderlyingObject(L->getPointerOperand(),
L->getModule()->getDataLayout()) == Ptr;
}
if (StoreInst *S = dyn_cast<StoreInst>(I)) {
return S->getPointerAddressSpace() == 0 &&
GetUnderlyingObject(S->getPointerOperand(),
S->getModule()->getDataLayout()) == Ptr;
}
if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) {
if (MI->isVolatile()) return false;
// FIXME: check whether it has a valuerange that excludes zero?
ConstantInt *Len = dyn_cast<ConstantInt>(MI->getLength());
if (!Len || Len->isZero()) return false;
if (MI->getDestAddressSpace() == 0)
if (GetUnderlyingObject(MI->getRawDest(),
MI->getModule()->getDataLayout()) == Ptr)
return true;
if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI))
if (MTI->getSourceAddressSpace() == 0)
if (GetUnderlyingObject(MTI->getRawSource(),
MTI->getModule()->getDataLayout()) == Ptr)
return true;
}
return false;
}
bool LazyValueInfoCache::solveBlockValueNonLocal(LVILatticeVal &BBLV,
Value *Val, BasicBlock *BB) {
LVILatticeVal Result; // Start Undefined.
// If this is a pointer, and there's a load from that pointer in this BB,
// then we know that the pointer can't be NULL.
bool NotNull = false;
if (Val->getType()->isPointerTy()) {
if (isKnownNonNull(Val)) {
NotNull = true;
} else {
const DataLayout &DL = BB->getModule()->getDataLayout();
Value *UnderlyingVal = GetUnderlyingObject(Val, DL);
// If 'GetUnderlyingObject' didn't converge, skip it. It won't converge
// inside InstructionDereferencesPointer either.
if (UnderlyingVal == GetUnderlyingObject(UnderlyingVal, DL, 1)) {
for (Instruction &I : *BB) {
if (InstructionDereferencesPointer(&I, UnderlyingVal)) {
NotNull = true;
break;
}
}
}
}
}
// If this is the entry block, we must be asking about an argument. The
// value is overdefined.
if (BB == &BB->getParent()->getEntryBlock()) {
assert(isa<Argument>(Val) && "Unknown live-in to the entry block");
if (NotNull) {
PointerType *PTy = cast<PointerType>(Val->getType());
Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
} else {
Result.markOverdefined();
}
BBLV = Result;
return true;
}
// Loop over all of our predecessors, merging what we know from them into
// result.
bool EdgesMissing = false;
for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
LVILatticeVal EdgeResult;
EdgesMissing |= !getEdgeValue(Val, *PI, BB, EdgeResult);
if (EdgesMissing)
continue;
Result.mergeIn(EdgeResult, DL);
// If we hit overdefined, exit early. The BlockVals entry is already set
// to overdefined.
if (Result.isOverdefined()) {
DEBUG(dbgs() << " compute BB '" << BB->getName()
<< "' - overdefined because of pred (non local).\n");
// If we previously determined that this is a pointer that can't be null
// then return that rather than giving up entirely.
if (NotNull) {
PointerType *PTy = cast<PointerType>(Val->getType());
Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
}
BBLV = Result;
return true;
}
}
if (EdgesMissing)
return false;
// Return the merged value, which is more precise than 'overdefined'.
assert(!Result.isOverdefined());
BBLV = Result;
return true;
}
bool LazyValueInfoCache::solveBlockValuePHINode(LVILatticeVal &BBLV,
PHINode *PN, BasicBlock *BB) {
LVILatticeVal Result; // Start Undefined.
// Loop over all of our predecessors, merging what we know from them into
// result.
bool EdgesMissing = false;
for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
BasicBlock *PhiBB = PN->getIncomingBlock(i);
Value *PhiVal = PN->getIncomingValue(i);
LVILatticeVal EdgeResult;
// 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.
EdgesMissing |= !getEdgeValue(PhiVal, PhiBB, BB, EdgeResult, PN);
if (EdgesMissing)
continue;
Result.mergeIn(EdgeResult, DL);
// If we hit overdefined, exit early. The BlockVals entry is already set
// to overdefined.
if (Result.isOverdefined()) {
DEBUG(dbgs() << " compute BB '" << BB->getName()
<< "' - overdefined because of pred (local).\n");
BBLV = Result;
return true;
}
}
if (EdgesMissing)
return false;
// Return the merged value, which is more precise than 'overdefined'.
assert(!Result.isOverdefined() && "Possible PHI in entry block?");
BBLV = Result;
return true;
}
static bool getValueFromFromCondition(Value *Val, ICmpInst *ICI,
LVILatticeVal &Result,
bool isTrueDest = true);
// If we can determine a constraint on the value given conditions assumed by
// the program, intersect those constraints with BBLV
void LazyValueInfoCache::intersectAssumeBlockValueConstantRange(Value *Val,
LVILatticeVal &BBLV,
Instruction *BBI) {
BBI = BBI ? BBI : dyn_cast<Instruction>(Val);
if (!BBI)
return;
for (auto &AssumeVH : AC->assumptions()) {
if (!AssumeVH)
continue;
auto *I = cast<CallInst>(AssumeVH);
if (!isValidAssumeForContext(I, BBI, DT))
continue;
Value *C = I->getArgOperand(0);
if (ICmpInst *ICI = dyn_cast<ICmpInst>(C)) {
LVILatticeVal Result;
if (getValueFromFromCondition(Val, ICI, Result))
BBLV = intersect(BBLV, Result);
}
}
}
bool LazyValueInfoCache::solveBlockValueSelect(LVILatticeVal &BBLV,
SelectInst *SI, BasicBlock *BB) {
// Recurse on our inputs if needed
if (!hasBlockValue(SI->getTrueValue(), BB)) {
if (pushBlockValue(std::make_pair(BB, SI->getTrueValue())))
return false;
BBLV.markOverdefined();
return true;
}
LVILatticeVal TrueVal = getBlockValue(SI->getTrueValue(), BB);
// If we hit overdefined, don't ask more queries. We want to avoid poisoning
// extra slots in the table if we can.
if (TrueVal.isOverdefined()) {
BBLV.markOverdefined();
return true;
}
if (!hasBlockValue(SI->getFalseValue(), BB)) {
if (pushBlockValue(std::make_pair(BB, SI->getFalseValue())))
return false;
BBLV.markOverdefined();
return true;
}
LVILatticeVal FalseVal = getBlockValue(SI->getFalseValue(), BB);
// If we hit overdefined, don't ask more queries. We want to avoid poisoning
// extra slots in the table if we can.
if (FalseVal.isOverdefined()) {
BBLV.markOverdefined();
return true;
}
if (TrueVal.isConstantRange() && FalseVal.isConstantRange()) {
ConstantRange TrueCR = TrueVal.getConstantRange();
ConstantRange FalseCR = FalseVal.getConstantRange();
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()) {
switch (SPR.Flavor) {
default:
llvm_unreachable("unexpected minmax type!");
case SPF_SMIN: /// Signed minimum
BBLV.markConstantRange(TrueCR.smin(FalseCR));
return true;
case SPF_UMIN: /// Unsigned minimum
BBLV.markConstantRange(TrueCR.umin(FalseCR));
return true;
case SPF_SMAX: /// Signed maximum
BBLV.markConstantRange(TrueCR.smax(FalseCR));
return true;
case SPF_UMAX: /// Unsigned maximum
BBLV.markConstantRange(TrueCR.umax(FalseCR));
return true;
};
}
// TODO: ABS, NABS from the SelectPatternResult
}
// 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.
if (auto *ICI = dyn_cast<ICmpInst>(SI->getCondition())) {
LVILatticeVal TrueValTaken, FalseValTaken;
if (!getValueFromFromCondition(SI->getTrueValue(), ICI,
TrueValTaken, true))
TrueValTaken.markOverdefined();
if (!getValueFromFromCondition(SI->getFalseValue(), ICI,
FalseValTaken, false))
FalseValTaken.markOverdefined();
TrueVal = intersect(TrueVal, TrueValTaken);
FalseVal = intersect(FalseVal, FalseValTaken);
// Handle clamp idioms such as:
// %24 = constantrange<0, 17>
// %39 = icmp eq i32 %24, 0
// %40 = add i32 %24, -1
// %siv.next = select i1 %39, i32 16, i32 %40
// %siv.next = constantrange<0, 17> not <-1, 17>
// In general, this can handle any clamp idiom which tests the edge
// condition via an equality or inequality.
ICmpInst::Predicate Pred = ICI->getPredicate();
Value *A = ICI->getOperand(0);
if (ConstantInt *CIBase = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
auto addConstants = [](ConstantInt *A, ConstantInt *B) {
assert(A->getType() == B->getType());
return ConstantInt::get(A->getType(), A->getValue() + B->getValue());
};
// See if either input is A + C2, subject to the constraint from the
// condition that A != C when that input is used. We can assume that
// that input doesn't include C + C2.
ConstantInt *CIAdded;
switch (Pred) {
default: break;
case ICmpInst::ICMP_EQ:
if (match(SI->getFalseValue(), m_Add(m_Specific(A),
m_ConstantInt(CIAdded)))) {
auto ResNot = addConstants(CIBase, CIAdded);
FalseVal = intersect(FalseVal,
LVILatticeVal::getNot(ResNot));
}
break;
case ICmpInst::ICMP_NE:
if (match(SI->getTrueValue(), m_Add(m_Specific(A),
m_ConstantInt(CIAdded)))) {
auto ResNot = addConstants(CIBase, CIAdded);
TrueVal = intersect(TrueVal,
LVILatticeVal::getNot(ResNot));
}
break;
};
}
}