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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
|
//===-- GRConstants.cpp - Simple, Path-Sens. Constant Prop. ------*- C++ -*-==//
//
// The LLValM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Constant Propagation via Graph Reachability
//
// This files defines a simple analysis that performs path-sensitive
// constant propagation within a function. An example use of this analysis
// is to perform simple checks for NULL dereferences.
//
//===----------------------------------------------------------------------===//
#include "clang/Analysis/PathSensitive/GREngine.h"
#include "clang/AST/Expr.h"
#include "clang/AST/ASTContext.h"
#include "clang/Analysis/Analyses/LiveVariables.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/DataTypes.h"
#include "llvm/ADT/APSInt.h"
#include "llvm/ADT/FoldingSet.h"
#include "llvm/ADT/ImmutableMap.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/Support/Allocator.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/Streams.h"
#include <functional>
#ifndef NDEBUG
#include "llvm/Support/GraphWriter.h"
#include <sstream>
#endif
using namespace clang;
using llvm::dyn_cast;
using llvm::cast;
using llvm::APSInt;
//===----------------------------------------------------------------------===//
/// ValueKey - A variant smart pointer that wraps either a ValueDecl* or a
/// Stmt*. Use cast<> or dyn_cast<> to get actual pointer type
//===----------------------------------------------------------------------===//
namespace {
typedef unsigned SymbolID;
class VISIBILITY_HIDDEN ValueKey {
uintptr_t Raw;
void operator=(const ValueKey& RHS); // Do not implement.
public:
enum Kind { IsSubExpr=0x0, IsBlkExpr=0x1, IsDecl=0x2, // L-Value Bindings.
IsSymbol=0x3, // Symbol Bindings.
Flags=0x3 };
inline Kind getKind() const {
return (Kind) (Raw & Flags);
}
inline void* getPtr() const {
assert (getKind() != IsSymbol);
return reinterpret_cast<void*>(Raw & ~Flags);
}
inline SymbolID getSymbolID() const {
assert (getKind() == IsSymbol);
return (SymbolID) (Raw >> 2);
}
ValueKey(const ValueDecl* VD)
: Raw(reinterpret_cast<uintptr_t>(VD) | IsDecl) {
assert(VD && "ValueDecl cannot be NULL.");
}
ValueKey(Stmt* S, bool isBlkExpr = false)
: Raw(reinterpret_cast<uintptr_t>(S) | (isBlkExpr ? IsBlkExpr : IsSubExpr)){
assert(S && "Tracked statement cannot be NULL.");
}
ValueKey(SymbolID V)
: Raw((V << 2) | IsSymbol) {}
bool isSymbol() const { return getKind() == IsSymbol; }
bool isSubExpr() const { return getKind() == IsSubExpr; }
bool isBlkExpr() const { return getKind() == IsBlkExpr; }
bool isDecl() const { return getKind() == IsDecl; }
bool isStmt() const { return getKind() <= IsBlkExpr; }
inline void Profile(llvm::FoldingSetNodeID& ID) const {
ID.AddInteger(isSymbol() ? 1 : 0);
if (isSymbol())
ID.AddInteger(getSymbolID());
else
ID.AddPointer(getPtr());
}
inline bool operator==(const ValueKey& X) const {
return isSymbol() ? getSymbolID() == X.getSymbolID()
: getPtr() == X.getPtr();
}
inline bool operator!=(const ValueKey& X) const {
return !operator==(X);
}
inline bool operator<(const ValueKey& X) const {
if (isSymbol())
return X.isSymbol() ? getSymbolID() < X.getSymbolID() : false;
return getPtr() < X.getPtr();
}
};
} // end anonymous namespace
// Machinery to get cast<> and dyn_cast<> working with ValueKey.
namespace llvm {
template<> inline bool isa<ValueDecl,ValueKey>(const ValueKey& V) {
return V.getKind() == ValueKey::IsDecl;
}
template<> inline bool isa<Stmt,ValueKey>(const ValueKey& V) {
return ((unsigned) V.getKind()) < ValueKey::IsDecl;
}
template<> struct VISIBILITY_HIDDEN cast_retty_impl<ValueDecl,ValueKey> {
typedef const ValueDecl* ret_type;
};
template<> struct VISIBILITY_HIDDEN cast_retty_impl<Stmt,ValueKey> {
typedef const Stmt* ret_type;
};
template<> struct VISIBILITY_HIDDEN simplify_type<ValueKey> {
typedef void* SimpleType;
static inline SimpleType getSimplifiedValue(const ValueKey &V) {
return V.getPtr();
}
};
} // end llvm namespace
//===----------------------------------------------------------------------===//
// ValueManager.
//===----------------------------------------------------------------------===//
namespace {
typedef llvm::ImmutableSet<APSInt > APSIntSetTy;
class VISIBILITY_HIDDEN ValueManager {
ASTContext& Ctx;
typedef llvm::FoldingSet<llvm::FoldingSetNodeWrapper<APSInt> > APSIntSetTy;
APSIntSetTy APSIntSet;
llvm::BumpPtrAllocator BPAlloc;
public:
ValueManager(ASTContext& ctx) : Ctx(ctx) {}
~ValueManager();
ASTContext& getContext() const { return Ctx; }
APSInt& getValue(const APSInt& X);
};
} // end anonymous namespace
ValueManager::~ValueManager() {
// Note that the dstor for the contents of APSIntSet will never be called,
// so we iterate over the set and invoke the dstor for each APSInt. This
// frees an aux. memory allocated to represent very large constants.
for (APSIntSetTy::iterator I=APSIntSet.begin(), E=APSIntSet.end(); I!=E; ++I)
I->getValue().~APSInt();
}
APSInt& ValueManager::getValue(const APSInt& X) {
llvm::FoldingSetNodeID ID;
void* InsertPos;
typedef llvm::FoldingSetNodeWrapper<APSInt> FoldNodeTy;
X.Profile(ID);
FoldNodeTy* P = APSIntSet.FindNodeOrInsertPos(ID, InsertPos);
if (!P) {
P = (FoldNodeTy*) BPAlloc.Allocate<FoldNodeTy>();
new (P) FoldNodeTy(X);
APSIntSet.InsertNode(P, InsertPos);
}
return *P;
}
//===----------------------------------------------------------------------===//
// Expression Values.
//===----------------------------------------------------------------------===//
namespace {
class VISIBILITY_HIDDEN RValue {
public:
enum BaseKind { LValueKind=0x0, NonLValueKind=0x1,
UninitializedKind=0x2, InvalidKind=0x3, BaseFlags = 0x3 };
private:
void* Data;
unsigned Kind;
protected:
RValue(const void* d, bool isLValue, unsigned ValKind)
: Data(const_cast<void*>(d)),
Kind((isLValue ? LValueKind : NonLValueKind) | (ValKind << 2)) {}
explicit RValue(BaseKind k)
: Data(0), Kind(k) {}
void* getRawPtr() const {
return reinterpret_cast<void*>(Data);
}
public:
~RValue() {};
RValue Cast(ValueManager& ValMgr, Expr* CastExpr) const;
unsigned getRawKind() const { return Kind; }
BaseKind getBaseKind() const { return (BaseKind) (Kind & 0x3); }
unsigned getSubKind() const { return (Kind & ~0x3) >> 2; }
void Profile(llvm::FoldingSetNodeID& ID) const {
ID.AddInteger((unsigned) getRawKind());
ID.AddPointer(reinterpret_cast<void*>(Data));
}
bool operator==(const RValue& RHS) const {
return getRawKind() == RHS.getRawKind() && Data == RHS.Data;
}
inline bool isValid() const { return getRawKind() != InvalidKind; }
inline bool isInvalid() const { return getRawKind() == InvalidKind; }
void print(std::ostream& OS) const;
void print() const { print(*llvm::cerr.stream()); }
// Implement isa<T> support.
static inline bool classof(const RValue*) { return true; }
};
class VISIBILITY_HIDDEN InvalidValue : public RValue {
public:
InvalidValue() : RValue(InvalidKind) {}
static inline bool classof(const RValue* V) {
return V->getBaseKind() == InvalidKind;
}
};
class VISIBILITY_HIDDEN UninitializedValue : public RValue {
public:
UninitializedValue() : RValue(UninitializedKind) {}
static inline bool classof(const RValue* V) {
return V->getBaseKind() == UninitializedKind;
}
};
class VISIBILITY_HIDDEN LValue : public RValue {
protected:
LValue(unsigned SubKind, void* D) : RValue(D, true, SubKind) {}
public:
// Implement isa<T> support.
static inline bool classof(const RValue* V) {
return V->getBaseKind() == LValueKind;
}
};
class VISIBILITY_HIDDEN NonLValue : public RValue {
protected:
NonLValue(unsigned SubKind, const void* d) : RValue(d, false, SubKind) {}
public:
void print(std::ostream& Out) const;
NonLValue Add(ValueManager& ValMgr, const NonLValue& RHS) const;
NonLValue Sub(ValueManager& ValMgr, const NonLValue& RHS) const;
NonLValue Mul(ValueManager& ValMgr, const NonLValue& RHS) const;
NonLValue Div(ValueManager& ValMgr, const NonLValue& RHS) const;
NonLValue Rem(ValueManager& ValMgr, const NonLValue& RHS) const;
NonLValue UnaryMinus(ValueManager& ValMgr, UnaryOperator* U) const;
static NonLValue GetValue(ValueManager& ValMgr, const APSInt& V);
static NonLValue GetValue(ValueManager& ValMgr, IntegerLiteral* I);
// Implement isa<T> support.
static inline bool classof(const RValue* V) {
return V->getBaseKind() >= NonLValueKind;
}
};
} // end anonymous namespace
//===----------------------------------------------------------------------===//
// LValues.
//===----------------------------------------------------------------------===//
namespace {
enum { LValueDeclKind, NumLValueKind };
class VISIBILITY_HIDDEN LValueDecl : public LValue {
public:
LValueDecl(const ValueDecl* vd)
: LValue(LValueDeclKind,const_cast<ValueDecl*>(vd)) {}
ValueDecl* getDecl() const {
return static_cast<ValueDecl*>(getRawPtr());
}
// Implement isa<T> support.
static inline bool classof(const RValue* V) {
return V->getSubKind() == LValueDeclKind;
}
};
} // end anonymous namespace
//===----------------------------------------------------------------------===//
// Non-LValues.
//===----------------------------------------------------------------------===//
namespace {
enum { SymbolicNonLValueKind, ConcreteIntKind, ConstrainedIntegerKind,
NumNonLValueKind };
class VISIBILITY_HIDDEN SymbolicNonLValue : public NonLValue {
public:
SymbolicNonLValue(unsigned SymID)
: NonLValue(SymbolicNonLValueKind,
reinterpret_cast<void*>((uintptr_t) SymID)) {}
SymbolID getSymbolID() const {
return (SymbolID) reinterpret_cast<uintptr_t>(getRawPtr());
}
static inline bool classof(const RValue* V) {
return V->getSubKind() == SymbolicNonLValueKind;
}
};
class VISIBILITY_HIDDEN ConcreteInt : public NonLValue {
public:
ConcreteInt(const APSInt& V) : NonLValue(ConcreteIntKind, &V) {}
const APSInt& getValue() const {
return *static_cast<APSInt*>(getRawPtr());
}
ConcreteInt Add(ValueManager& ValMgr, const ConcreteInt& V) const {
return ValMgr.getValue(getValue() + V.getValue());
}
ConcreteInt Sub(ValueManager& ValMgr, const ConcreteInt& V) const {
return ValMgr.getValue(getValue() - V.getValue());
}
ConcreteInt Mul(ValueManager& ValMgr, const ConcreteInt& V) const {
return ValMgr.getValue(getValue() * V.getValue());
}
ConcreteInt Div(ValueManager& ValMgr, const ConcreteInt& V) const {
return ValMgr.getValue(getValue() / V.getValue());
}
ConcreteInt Rem(ValueManager& ValMgr, const ConcreteInt& V) const {
return ValMgr.getValue(getValue() % V.getValue());
}
ConcreteInt Cast(ValueManager& ValMgr, Expr* CastExpr) const {
assert (CastExpr->getType()->isIntegerType());
APSInt X(getValue());
X.extOrTrunc(ValMgr.getContext().getTypeSize(CastExpr->getType(),
CastExpr->getLocStart()));
return ValMgr.getValue(X);
}
ConcreteInt UnaryMinus(ValueManager& ValMgr, UnaryOperator* U) const {
assert (U->getType() == U->getSubExpr()->getType());
assert (U->getType()->isIntegerType());
return ValMgr.getValue(-getValue());
}
// Implement isa<T> support.
static inline bool classof(const RValue* V) {
return V->getSubKind() == ConcreteIntKind;
}
};
} // end anonymous namespace
//===----------------------------------------------------------------------===//
// Transfer function dispatch.
//===----------------------------------------------------------------------===//
RValue RValue::Cast(ValueManager& ValMgr, Expr* CastExpr) const {
switch (getSubKind()) {
case ConcreteIntKind:
return cast<ConcreteInt>(this)->Cast(ValMgr, CastExpr);
default:
return InvalidValue();
}
}
NonLValue NonLValue::UnaryMinus(ValueManager& ValMgr, UnaryOperator* U) const {
switch (getSubKind()) {
case ConcreteIntKind:
return cast<ConcreteInt>(this)->UnaryMinus(ValMgr, U);
default:
return cast<NonLValue>(InvalidValue());
}
}
#define RVALUE_DISPATCH_CASE(k1,k2,Op)\
case (k1##Kind*NumNonLValueKind+k2##Kind):\
return cast<k1>(*this).Op(ValMgr,cast<k2>(RHS));
#define RVALUE_DISPATCH(Op)\
switch (getSubKind()*NumNonLValueKind+RHS.getSubKind()){\
RVALUE_DISPATCH_CASE(ConcreteInt,ConcreteInt,Op)\
default:\
if (getBaseKind() == UninitializedKind ||\
RHS.getBaseKind() == UninitializedKind)\
return cast<NonLValue>(UninitializedValue());\
assert (!isValid() || !RHS.isValid() && "Missing case.");\
break;\
}\
return cast<NonLValue>(InvalidValue());
NonLValue NonLValue::Add(ValueManager& ValMgr, const NonLValue& RHS) const {
RVALUE_DISPATCH(Add)
}
NonLValue NonLValue::Sub(ValueManager& ValMgr, const NonLValue& RHS) const {
RVALUE_DISPATCH(Sub)
}
NonLValue NonLValue::Mul(ValueManager& ValMgr, const NonLValue& RHS) const {
RVALUE_DISPATCH(Mul)
}
NonLValue NonLValue::Div(ValueManager& ValMgr, const NonLValue& RHS) const {
RVALUE_DISPATCH(Div)
}
NonLValue NonLValue::Rem(ValueManager& ValMgr, const NonLValue& RHS) const {
RVALUE_DISPATCH(Rem)
}
#undef RVALUE_DISPATCH_CASE
#undef RVALUE_DISPATCH
//===----------------------------------------------------------------------===//
// Utility methods for constructing RValues.
//===----------------------------------------------------------------------===//
NonLValue NonLValue::GetValue(ValueManager& ValMgr, const APSInt& V) {
return ConcreteInt(ValMgr.getValue(V));
}
NonLValue NonLValue::GetValue(ValueManager& ValMgr, IntegerLiteral* I) {
return ConcreteInt(ValMgr.getValue(APSInt(I->getValue(),
I->getType()->isUnsignedIntegerType())));
}
//===----------------------------------------------------------------------===//
// Pretty-Printing.
//===----------------------------------------------------------------------===//
void RValue::print(std::ostream& Out) const {
switch (getBaseKind()) {
case InvalidKind:
Out << "Invalid";
break;
case NonLValueKind:
cast<NonLValue>(this)->print(Out);
break;
case LValueKind:
assert (false && "FIXME: LValue printing not implemented.");
break;
case UninitializedKind:
Out << "Uninitialized";
break;
default:
assert (false && "Invalid RValue.");
}
}
void NonLValue::print(std::ostream& Out) const {
switch (getSubKind()) {
case ConcreteIntKind:
Out << cast<ConcreteInt>(this)->getValue().toString();
break;
default:
assert (false && "Pretty-printed not implemented for this NonLValue.");
break;
}
}
//===----------------------------------------------------------------------===//
// ValueMapTy - A ImmutableMap type Stmt*/Decl*/Symbols to RValues.
//===----------------------------------------------------------------------===//
typedef llvm::ImmutableMap<ValueKey,RValue> ValueMapTy;
namespace clang {
template<>
struct VISIBILITY_HIDDEN GRTrait<ValueMapTy> {
static inline void* toPtr(ValueMapTy M) {
return reinterpret_cast<void*>(M.getRoot());
}
static inline ValueMapTy toState(void* P) {
return ValueMapTy(static_cast<ValueMapTy::TreeTy*>(P));
}
};
}
//===----------------------------------------------------------------------===//
// The Checker.
//===----------------------------------------------------------------------===//
namespace {
class VISIBILITY_HIDDEN GRConstants {
public:
typedef ValueMapTy StateTy;
typedef GRNodeBuilder<GRConstants> NodeBuilder;
typedef ExplodedGraph<GRConstants> GraphTy;
typedef GraphTy::NodeTy NodeTy;
class NodeSet {
typedef llvm::SmallVector<NodeTy*,3> ImplTy;
ImplTy Impl;
public:
NodeSet() {}
NodeSet(NodeTy* N) { assert (N && !N->isInfeasible()); Impl.push_back(N); }
void Add(NodeTy* N) { if (N && !N->isInfeasible()) Impl.push_back(N); }
typedef ImplTy::iterator iterator;
typedef ImplTy::const_iterator const_iterator;
unsigned size() const { return Impl.size(); }
bool empty() const { return Impl.empty(); }
iterator begin() { return Impl.begin(); }
iterator end() { return Impl.end(); }
const_iterator begin() const { return Impl.begin(); }
const_iterator end() const { return Impl.end(); }
};
protected:
/// G - the simulation graph.
GraphTy& G;
/// Liveness - live-variables information the ValueDecl* and block-level
/// Expr* in the CFG. Used to prune out dead state.
LiveVariables Liveness;
/// Builder - The current GRNodeBuilder which is used when building the nodes
/// for a given statement.
NodeBuilder* Builder;
/// StateMgr - Object that manages the data for all created states.
ValueMapTy::Factory StateMgr;
/// ValueMgr - Object that manages the data for all created RValues.
ValueManager ValMgr;
/// StmtEntryNode - The immediate predecessor node.
NodeTy* StmtEntryNode;
/// CurrentStmt - The current block-level statement.
Stmt* CurrentStmt;
bool StateCleaned;
ASTContext& getContext() const { return G.getContext(); }
public:
GRConstants(GraphTy& g) : G(g), Liveness(G.getCFG(), G.getFunctionDecl()),
Builder(NULL), ValMgr(G.getContext()), StmtEntryNode(NULL),
CurrentStmt(NULL) {
// Compute liveness information.
Liveness.runOnCFG(G.getCFG());
Liveness.runOnAllBlocks(G.getCFG(), NULL, true);
}
/// getCFG - Returns the CFG associated with this analysis.
CFG& getCFG() { return G.getCFG(); }
/// getInitialState - Return the initial state used for the root vertex
/// in the ExplodedGraph.
StateTy getInitialState() {
StateTy St = StateMgr.GetEmptyMap();
// Iterate the parameters.
FunctionDecl& F = G.getFunctionDecl();
for (FunctionDecl::param_iterator I=F.param_begin(), E=F.param_end();
I!=E; ++I) {
// For now we only support symbolic values for non-pointer types.
if ((*I)->getType()->isPointerType() ||
(*I)->getType()->isReferenceType())
continue;
// FIXME: Set these values to a symbol, not Uninitialized.
St = SetValue(St, LValueDecl(*I), UninitializedValue());
}
return St;
}
/// ProcessStmt - Called by GREngine. Used to generate new successor
/// nodes by processing the 'effects' of a block-level statement.
void ProcessStmt(Stmt* S, NodeBuilder& builder);
/// RemoveDeadBindings - Return a new state that is the same as 'M' except
/// that all subexpression mappings are removed and that any
/// block-level expressions that are not live at 'S' also have their
/// mappings removed.
StateTy RemoveDeadBindings(Stmt* S, StateTy M);
StateTy SetValue(StateTy St, Stmt* S, const RValue& V);
StateTy SetValue(StateTy St, const Stmt* S, const RValue& V) {
return SetValue(St, const_cast<Stmt*>(S), V);
}
StateTy SetValue(StateTy St, const LValue& LV, const RValue& V);
RValue GetValue(const StateTy& St, Stmt* S);
inline RValue GetValue(const StateTy& St, const Stmt* S) {
return GetValue(St, const_cast<Stmt*>(S));
}
RValue GetValue(const StateTy& St, const LValue& LV);
LValue GetLValue(const StateTy& St, Stmt* S);
void Nodify(NodeSet& Dst, Stmt* S, NodeTy* Pred, StateTy St);
/// Visit - Transfer function logic for all statements. Dispatches to
/// other functions that handle specific kinds of statements.
void Visit(Stmt* S, NodeTy* Pred, NodeSet& Dst);
/// VisitCast - Transfer function logic for all casts (implicit and explicit).
void VisitCast(Expr* CastE, Expr* E, NodeTy* Pred, NodeSet& Dst);
/// VisitUnaryOperator - Transfer function logic for unary operators.
void VisitUnaryOperator(UnaryOperator* B, NodeTy* Pred, NodeSet& Dst);
/// VisitBinaryOperator - Transfer function logic for binary operators.
void VisitBinaryOperator(BinaryOperator* B, NodeTy* Pred, NodeSet& Dst);
/// VisitDeclStmt - Transfer function logic for DeclStmts.
void VisitDeclStmt(DeclStmt* DS, NodeTy* Pred, NodeSet& Dst);
};
} // end anonymous namespace
void GRConstants::ProcessStmt(Stmt* S, NodeBuilder& builder) {
Builder = &builder;
StmtEntryNode = builder.getLastNode();
CurrentStmt = S;
NodeSet Dst;
StateCleaned = false;
Visit(S, StmtEntryNode, Dst);
// If no nodes were generated, generate a new node that has all the
// dead mappings removed.
if (Dst.size() == 1 && *Dst.begin() == StmtEntryNode) {
StateTy St = RemoveDeadBindings(S, StmtEntryNode->getState());
builder.generateNode(S, St, StmtEntryNode);
}
CurrentStmt = NULL;
StmtEntryNode = NULL;
Builder = NULL;
}
RValue GRConstants::GetValue(const StateTy& St, const LValue& LV) {
switch (LV.getSubKind()) {
case LValueDeclKind: {
StateTy::TreeTy* T = St.SlimFind(cast<LValueDecl>(LV).getDecl());
return T ? T->getValue().second : InvalidValue();
}
default:
assert (false && "Invalid LValue.");
break;
}
return InvalidValue();
}
RValue GRConstants::GetValue(const StateTy& St, Stmt* S) {
for (;;) {
switch (S->getStmtClass()) {
// ParenExprs are no-ops.
case Stmt::ParenExprClass:
S = cast<ParenExpr>(S)->getSubExpr();
continue;
// DeclRefExprs can either evaluate to an LValue or a Non-LValue
// (assuming an implicit "load") depending on the context. In this
// context we assume that we are retrieving the value contained
// within the referenced variables.
case Stmt::DeclRefExprClass:
return GetValue(St, LValueDecl(cast<DeclRefExpr>(S)->getDecl()));
// Integer literals evaluate to an RValue. Simply retrieve the
// RValue for the literal.
case Stmt::IntegerLiteralClass:
return NonLValue::GetValue(ValMgr, cast<IntegerLiteral>(S));
// Casts where the source and target type are the same
// are no-ops. We blast through these to get the descendant
// subexpression that has a value.
case Stmt::ImplicitCastExprClass: {
ImplicitCastExpr* C = cast<ImplicitCastExpr>(S);
if (C->getType() == C->getSubExpr()->getType()) {
S = C->getSubExpr();
continue;
}
break;
}
case Stmt::CastExprClass: {
CastExpr* C = cast<CastExpr>(S);
if (C->getType() == C->getSubExpr()->getType()) {
S = C->getSubExpr();
continue;
}
break;
}
// Handle all other Stmt* using a lookup.
default:
break;
};
break;
}
StateTy::TreeTy* T = St.SlimFind(S);
return T ? T->getValue().second : InvalidValue();
}
LValue GRConstants::GetLValue(const StateTy& St, Stmt* S) {
while (ParenExpr* P = dyn_cast<ParenExpr>(S))
S = P->getSubExpr();
if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(S))
return LValueDecl(DR->getDecl());
return cast<LValue>(GetValue(St, S));
}
GRConstants::StateTy GRConstants::SetValue(StateTy St, Stmt* S,
const RValue& V) {
assert (S);
if (!StateCleaned) {
St = RemoveDeadBindings(CurrentStmt, St);
StateCleaned = true;
}
bool isBlkExpr = false;
if (S == CurrentStmt) {
isBlkExpr = getCFG().isBlkExpr(S);
if (!isBlkExpr)
return St;
}
return V.isValid() ? StateMgr.Add(St, ValueKey(S,isBlkExpr), V)
: St;
}
GRConstants::StateTy GRConstants::SetValue(StateTy St, const LValue& LV,
const RValue& V) {
if (!LV.isValid())
return St;
if (!StateCleaned) {
St = RemoveDeadBindings(CurrentStmt, St);
StateCleaned = true;
}
switch (LV.getSubKind()) {
case LValueDeclKind:
return V.isValid() ? StateMgr.Add(St, cast<LValueDecl>(LV).getDecl(), V)
: StateMgr.Remove(St, cast<LValueDecl>(LV).getDecl());
default:
assert ("SetValue for given LValue type not yet implemented.");
return St;
}
}
GRConstants::StateTy GRConstants::RemoveDeadBindings(Stmt* Loc, StateTy M) {
// Note: in the code below, we can assign a new map to M since the
// iterators are iterating over the tree of the *original* map.
StateTy::iterator I = M.begin(), E = M.end();
for (; I!=E && !I.getKey().isSymbol(); ++I) {
// Remove old bindings for subexpressions and "dead"
// block-level expressions.
if (I.getKey().isSubExpr() ||
I.getKey().isBlkExpr() && !Liveness.isLive(Loc,cast<Stmt>(I.getKey()))){
M = StateMgr.Remove(M, I.getKey());
}
else if (I.getKey().isDecl()) { // Remove bindings for "dead" decls.
if (VarDecl* V = dyn_cast<VarDecl>(cast<ValueDecl>(I.getKey())))
if (!Liveness.isLive(Loc, V))
M = StateMgr.Remove(M, I.getKey());
}
}
return M;
}
void GRConstants::Nodify(NodeSet& Dst, Stmt* S, GRConstants::NodeTy* Pred,
GRConstants::StateTy St) {
// If the state hasn't changed, don't generate a new node.
if (St == Pred->getState())
return;
Dst.Add(Builder->generateNode(S, St, Pred));
}
void GRConstants::VisitCast(Expr* CastE, Expr* E, GRConstants::NodeTy* Pred,
GRConstants::NodeSet& Dst) {
QualType T = CastE->getType();
// Check for redundant casts.
if (E->getType() == T) {
Dst.Add(Pred);
return;
}
NodeSet S1;
Visit(E, Pred, S1);
for (NodeSet::iterator I1=S1.begin(), E1=S1.end(); I1 != E1; ++I1) {
NodeTy* N = *I1;
StateTy St = N->getState();
const RValue& V = GetValue(St, E);
Nodify(Dst, CastE, N, SetValue(St, CastE, V.Cast(ValMgr, CastE)));
}
}
void GRConstants::VisitDeclStmt(DeclStmt* DS, GRConstants::NodeTy* Pred,
GRConstants::NodeSet& Dst) {
StateTy St = Pred->getState();
for (const ScopedDecl* D = DS->getDecl(); D; D = D->getNextDeclarator())
if (const VarDecl* VD = dyn_cast<VarDecl>(D)) {
const Expr* E = VD->getInit();
St = SetValue(St, LValueDecl(VD),
E ? GetValue(St, E) : UninitializedValue());
}
Nodify(Dst, DS, Pred, St);
if (Dst.empty())
Dst.Add(Pred);
}
void GRConstants::VisitUnaryOperator(UnaryOperator* U,
GRConstants::NodeTy* Pred,
GRConstants::NodeSet& Dst) {
NodeSet S1;
Visit(U->getSubExpr(), Pred, S1);
for (NodeSet::iterator I1=S1.begin(), E1=S1.end(); I1 != E1; ++I1) {
NodeTy* N1 = *I1;
StateTy St = N1->getState();
switch (U->getOpcode()) {
case UnaryOperator::PostInc: {
const LValue& L1 = GetLValue(St, U->getSubExpr());
NonLValue R1 = cast<NonLValue>(GetValue(St, L1));
QualType T = U->getType();
unsigned bits = getContext().getTypeSize(T, U->getLocStart());
APSInt One(llvm::APInt(bits, 1), T->isUnsignedIntegerType());
NonLValue R2 = NonLValue::GetValue(ValMgr, One);
NonLValue Result = R1.Add(ValMgr, R2);
Nodify(Dst, U, N1, SetValue(SetValue(St, U, R1), L1, Result));
break;
}
case UnaryOperator::PostDec: {
const LValue& L1 = GetLValue(St, U->getSubExpr());
NonLValue R1 = cast<NonLValue>(GetValue(St, L1));
QualType T = U->getType();
unsigned bits = getContext().getTypeSize(T, U->getLocStart());
APSInt One(llvm::APInt(bits, 1), T->isUnsignedIntegerType());
NonLValue R2 = NonLValue::GetValue(ValMgr, One);
NonLValue Result = R1.Sub(ValMgr, R2);
Nodify(Dst, U, N1, SetValue(SetValue(St, U, R1), L1, Result));
break;
}
case UnaryOperator::PreInc: {
const LValue& L1 = GetLValue(St, U->getSubExpr());
NonLValue R1 = cast<NonLValue>(GetValue(St, L1));
QualType T = U->getType();
unsigned bits = getContext().getTypeSize(T, U->getLocStart());
APSInt One(llvm::APInt(bits, 1), T->isUnsignedIntegerType());
NonLValue R2 = NonLValue::GetValue(ValMgr, One);
NonLValue Result = R1.Add(ValMgr, R2);
Nodify(Dst, U, N1, SetValue(SetValue(St, U, Result), L1, Result));
break;
}
case UnaryOperator::PreDec: {
const LValue& L1 = GetLValue(St, U->getSubExpr());
NonLValue R1 = cast<NonLValue>(GetValue(St, L1));
QualType T = U->getType();
unsigned bits = getContext().getTypeSize(T, U->getLocStart());
APSInt One(llvm::APInt(bits, 1), T->isUnsignedIntegerType());
NonLValue R2 = NonLValue::GetValue(ValMgr, One);
NonLValue Result = R1.Sub(ValMgr, R2);
Nodify(Dst, U, N1, SetValue(SetValue(St, U, Result), L1, Result));
break;
}
case UnaryOperator::Minus: {
const NonLValue& R1 = cast<NonLValue>(GetValue(St, U->getSubExpr()));
Nodify(Dst, U, N1, SetValue(St, U, R1.UnaryMinus(ValMgr, U)));
break;
}
default: ;
assert (false && "Not implemented.");
}
}
}
void GRConstants::VisitBinaryOperator(BinaryOperator* B,
GRConstants::NodeTy* Pred,
GRConstants::NodeSet& Dst) {
NodeSet S1;
Visit(B->getLHS(), Pred, S1);
for (NodeSet::iterator I1=S1.begin(), E1=S1.end(); I1 != E1; ++I1) {
NodeTy* N1 = *I1;
// When getting the value for the LHS, check if we are in an assignment.
// In such cases, we want to (initially) treat the LHS as an LValue,
// so we use GetLValue instead of GetValue so that DeclRefExpr's are
// evaluated to LValueDecl's instead of to an NonLValue.
const RValue& V1 =
B->isAssignmentOp() ? GetLValue(N1->getState(), B->getLHS())
: GetValue(N1->getState(), B->getLHS());
NodeSet S2;
Visit(B->getRHS(), N1, S2);
for (NodeSet::iterator I2=S2.begin(), E2=S2.end(); I2 != E2; ++I2) {
NodeTy* N2 = *I2;
StateTy St = N2->getState();
const RValue& V2 = GetValue(St, B->getRHS());
switch (B->getOpcode()) {
case BinaryOperator::Add: {
const NonLValue& R1 = cast<NonLValue>(V1);
const NonLValue& R2 = cast<NonLValue>(V2);
Nodify(Dst, B, N2, SetValue(St, B, R1.Add(ValMgr, R2)));
break;
}
case BinaryOperator::Sub: {
const NonLValue& R1 = cast<NonLValue>(V1);
const NonLValue& R2 = cast<NonLValue>(V2);
Nodify(Dst, B, N2, SetValue(St, B, R1.Sub(ValMgr, R2)));
break;
}
case BinaryOperator::Mul: {
const NonLValue& R1 = cast<NonLValue>(V1);
const NonLValue& R2 = cast<NonLValue>(V2);
Nodify(Dst, B, N2, SetValue(St, B, R1.Mul(ValMgr, R2)));
break;
}
case BinaryOperator::Div: {
const NonLValue& R1 = cast<NonLValue>(V1);
const NonLValue& R2 = cast<NonLValue>(V2);
Nodify(Dst, B, N2, SetValue(St, B, R1.Div(ValMgr, R2)));
break;
}
case BinaryOperator::Rem: {
const NonLValue& R1 = cast<NonLValue>(V1);
const NonLValue& R2 = cast<NonLValue>(V2);
Nodify(Dst, B, N2, SetValue(St, B, R1.Rem(ValMgr, R2)));
break;
}
case BinaryOperator::Assign: {
const LValue& L1 = cast<LValue>(V1);
const NonLValue& R2 = cast<NonLValue>(V2);
Nodify(Dst, B, N2, SetValue(SetValue(St, B, R2), L1, R2));
break;
}
case BinaryOperator::AddAssign: {
const LValue& L1 = cast<LValue>(V1);
NonLValue R1 = cast<NonLValue>(GetValue(N1->getState(), L1));
NonLValue Result = R1.Add(ValMgr, cast<NonLValue>(V2));
Nodify(Dst, B, N2, SetValue(SetValue(St, B, Result), L1, Result));
break;
}
case BinaryOperator::SubAssign: {
const LValue& L1 = cast<LValue>(V1);
NonLValue R1 = cast<NonLValue>(GetValue(N1->getState(), L1));
NonLValue Result = R1.Sub(ValMgr, cast<NonLValue>(V2));
Nodify(Dst, B, N2, SetValue(SetValue(St, B, Result), L1, Result));
break;
}
case BinaryOperator::MulAssign: {
const LValue& L1 = cast<LValue>(V1);
NonLValue R1 = cast<NonLValue>(GetValue(N1->getState(), L1));
NonLValue Result = R1.Mul(ValMgr, cast<NonLValue>(V2));
Nodify(Dst, B, N2, SetValue(SetValue(St, B, Result), L1, Result));
break;
}
case BinaryOperator::DivAssign: {
const LValue& L1 = cast<LValue>(V1);
NonLValue R1 = cast<NonLValue>(GetValue(N1->getState(), L1));
NonLValue Result = R1.Div(ValMgr, cast<NonLValue>(V2));
Nodify(Dst, B, N2, SetValue(SetValue(St, B, Result), L1, Result));
break;
}
case BinaryOperator::RemAssign: {
const LValue& L1 = cast<LValue>(V1);
NonLValue R1 = cast<NonLValue>(GetValue(N1->getState(), L1));
NonLValue Result = R1.Rem(ValMgr, cast<NonLValue>(V2));
Nodify(Dst, B, N2, SetValue(SetValue(St, B, Result), L1, Result));
break;
}
default:
Dst.Add(N2);
break;
}
}
}
}
void GRConstants::Visit(Stmt* S, GRConstants::NodeTy* Pred,
GRConstants::NodeSet& Dst) {
// FIXME: add metadata to the CFG so that we can disable
// this check when we KNOW that there is no block-level subexpression.
// The motivation is that this check requires a hashtable lookup.
if (S != CurrentStmt && getCFG().isBlkExpr(S)) {
Dst.Add(Pred);
return;
}
switch (S->getStmtClass()) {
case Stmt::BinaryOperatorClass:
case Stmt::CompoundAssignOperatorClass:
VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Dst);
break;
case Stmt::UnaryOperatorClass:
VisitUnaryOperator(cast<UnaryOperator>(S), Pred, Dst);
break;
case Stmt::ParenExprClass:
Visit(cast<ParenExpr>(S)->getSubExpr(), Pred, Dst);
break;
case Stmt::ImplicitCastExprClass: {
ImplicitCastExpr* C = cast<ImplicitCastExpr>(S);
VisitCast(C, C->getSubExpr(), Pred, Dst);
break;
}
case Stmt::CastExprClass: {
CastExpr* C = cast<CastExpr>(S);
VisitCast(C, C->getSubExpr(), Pred, Dst);
break;
}
case Stmt::DeclStmtClass:
VisitDeclStmt(cast<DeclStmt>(S), Pred, Dst);
break;
default:
Dst.Add(Pred); // No-op. Simply propagate the current state unchanged.
break;
}
}
//===----------------------------------------------------------------------===//
// Driver.
//===----------------------------------------------------------------------===//
#ifndef NDEBUG
namespace llvm {
template<>
struct VISIBILITY_HIDDEN DOTGraphTraits<GRConstants::NodeTy*> :
public DefaultDOTGraphTraits {
static void PrintKindLabel(std::ostream& Out, ValueKey::Kind kind) {
switch (kind) {
case ValueKey::IsSubExpr: Out << "Sub-Expressions:\\l"; break;
case ValueKey::IsDecl: Out << "Variables:\\l"; break;
case ValueKey::IsBlkExpr: Out << "Block-level Expressions:\\l"; break;
default: assert (false && "Unknown ValueKey type.");
}
}
static void PrintKind(std::ostream& Out, GRConstants::StateTy M,
ValueKey::Kind kind, bool isFirstGroup = false) {
bool isFirst = true;
for (GRConstants::StateTy::iterator I=M.begin(), E=M.end();I!=E;++I) {
if (I.getKey().getKind() != kind)
continue;
if (isFirst) {
if (!isFirstGroup) Out << "\\l\\l";
PrintKindLabel(Out, kind);
isFirst = false;
}
else
Out << "\\l";
Out << ' ';
if (ValueDecl* V = dyn_cast<ValueDecl>(I.getKey()))
Out << V->getName();
else {
Stmt* E = cast<Stmt>(I.getKey());
Out << " (" << (void*) E << ") ";
E->printPretty(Out);
}
Out << " : ";
I.getData().print(Out);
}
}
static std::string getNodeLabel(const GRConstants::NodeTy* N, void*) {
std::ostringstream Out;
// Program Location.
ProgramPoint Loc = N->getLocation();
switch (Loc.getKind()) {
case ProgramPoint::BlockEntranceKind:
Out << "Block Entrance: B"
<< cast<BlockEntrance>(Loc).getBlock()->getBlockID();
break;
case ProgramPoint::BlockExitKind:
assert (false);
break;
case ProgramPoint::PostStmtKind: {
const PostStmt& L = cast<PostStmt>(Loc);
Out << L.getStmt()->getStmtClassName() << ':'
<< (void*) L.getStmt() << ' ';
L.getStmt()->printPretty(Out);
break;
}
default: {
const BlockEdge& E = cast<BlockEdge>(Loc);
Out << "Edge: (B" << E.getSrc()->getBlockID() << ", B"
<< E.getDst()->getBlockID() << ')';
}
}
Out << "\\|";
PrintKind(Out, N->getState(), ValueKey::IsDecl, true);
PrintKind(Out, N->getState(), ValueKey::IsBlkExpr);
PrintKind(Out, N->getState(), ValueKey::IsSubExpr);
Out << "\\l";
return Out.str();
}
};
} // end llvm namespace
#endif
namespace clang {
void RunGRConstants(CFG& cfg, FunctionDecl& FD, ASTContext& Ctx) {
GREngine<GRConstants> Engine(cfg, FD, Ctx);
Engine.ExecuteWorkList();
#ifndef NDEBUG
llvm::ViewGraph(*Engine.getGraph().roots_begin(),"GRConstants");
#endif
}
} // end clang namespace
|