Repository navigation
Expand file tree
/
Copy pathprogrammemory.cpp
More file actions
2458 lines (2312 loc) · 102 KB
/
Copy pathprogrammemory.cpp
File metadata and controls
2458 lines (2312 loc) · 102 KB
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
/*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2026 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "programmemory.h"
#include "astutils.h"
#include "calculate.h"
#include "infer.h"
#include "library.h"
#include "mathlib.h"
#include "refthunk.h"
#include "settings.h"
#include "standards.h"
#include "symboldatabase.h"
#include "token.h"
#include "tokenlist.h"
#include "utils.h"
#include "valueflow.h"
#include "valueptr.h"
#include "vf_common.h"
#include <algorithm>
#include <cassert>
#include <cmath>
#include <cstdlib>
#include <functional>
#include <iterator>
#include <limits>
#include <list>
#include <memory>
#include <stack>
#include <stdexcept>
#include <string>
#include <utility>
#include <vector>
ExprIdToken::ExprIdToken(const Token* tok)
: tok(tok)
{
assert(tok);
exprid = tok->exprId();
}
ExprIdToken::ExprIdToken(nonneg int exprId) : exprid(exprId) {}
nonneg int ExprIdToken::getExpressionId() const {
return exprid;
}
std::size_t ExprIdToken::Hash::operator()(ExprIdToken etok) const
{
return std::hash<nonneg int>()(etok.getExpressionId());
}
// Does the value carry its range in intvalue?
static bool isRangeValue(const ValueFlow::Value& value)
{
return value.isIntValue() || value.isContainerSizeValue() || value.isBufferSizeValue() || value.isIteratorValue();
}
// A constraint that is a lower bound: the values up to the bound are impossible
static bool isLowerBound(const ValueFlow::Value& value)
{
return value.isImpossible() && isRangeValue(value) && value.bound == ValueFlow::Value::Bound::Upper;
}
// A constraint that is an upper bound: the values from the bound on are impossible
static bool isUpperBound(const ValueFlow::Value& value)
{
return value.isImpossible() && isRangeValue(value) && value.bound == ValueFlow::Value::Bound::Lower;
}
// An impossible value of the expression, without a bound
static bool isImpossiblePoint(const ValueFlow::Value& value)
{
return value.isImpossible() && value.bound == ValueFlow::Value::Bound::Point;
}
// Is the value (a range when it is impossible with a bound) known to be nonzero?
static bool isTrue(const ValueFlow::Value& v)
{
if (v.isUninitValue())
return false;
if (v.isImpossible()) {
if (v.bound == ValueFlow::Value::Bound::Point)
return v.intvalue == 0;
// An impossible range excludes zero when it lies on one side of it
return v.isLowerEdge() ? v.rangeEdge() > 0 : v.rangeEdge() < 0;
}
return v.intvalue != 0;
}
static bool isFalse(const ValueFlow::Value& v)
{
if (v.isUninitValue())
return false;
if (v.isImpossible())
return false;
return v.intvalue == 0;
}
// Does the value satisfy the constraint of the same type?
static bool satisfies(const ValueFlow::Value& value, const ValueFlow::Value& constraint)
{
if (isImpossiblePoint(constraint))
return !value.equalValue(constraint);
if (isLowerBound(constraint))
return value.intvalue >= constraint.rangeEdge();
if (isUpperBound(constraint))
return value.intvalue <= constraint.rangeEdge();
return false;
}
static bool sameValue(const ValueFlow::Value& x, const ValueFlow::Value& y)
{
return x == y && x.bound == y.bound;
}
// Is the value already recorded: as the value of the expression, as one of its constraints, or as
// a constraint that the recorded value satisfies?
static bool isRecorded(const ProgramMemory::Values& values, const ValueFlow::Value& value)
{
if (values.empty() || values.front().valueType != value.valueType)
return false;
if (!value.isImpossible())
return values.size() == 1 && sameValue(values.front(), value);
if (!values.front().isImpossible())
return satisfies(values.front(), value);
return std::any_of(values.cbegin(), values.cend(), [&](const ValueFlow::Value& v) {
return sameValue(v, value);
});
}
void ProgramMemory::setValue(const Token* expr, const ValueFlow::Value& value) {
if (!expr)
return;
ValueFlow::Value subvalue = value;
const Token* subexpr = solveExprValue(
expr,
[&](const Token* tok) -> std::vector<MathLib::bigint> {
if (const ValueFlow::Value* v = tok->getKnownValue(ValueFlow::Value::ValueType::INT))
return {v->intvalue};
MathLib::bigint result = 0;
if (getIntValue(tok->exprId(), result))
return {result};
return {};
},
subvalue);
if (expr != subexpr)
record(expr, value);
if (subexpr)
record(subexpr, subvalue);
}
void ProgramMemory::record(const Token* expr, const ValueFlow::Value& value)
{
const Values* existing = getValues(expr->exprId());
if (existing && isRecorded(*existing, value))
return;
copyOnWrite();
Values& values = (*mValues)[expr];
// A value of the expression, a first value, a value of another type or a constraint that the
// recorded value violates replaces what is recorded. A constraint joins the recorded constraints,
// merged the way Token::addValue() merges values: weaker bounds are dropped and an impossible
// value next to a bound moves the bound past it.
if (!value.isImpossible() || values.empty() || values.front().valueType != value.valueType ||
!values.front().isImpossible()) {
values.assign(1, value);
} else {
if (values.size() >= ValueFlow::maxValues)
return;
values.push_back(value);
Token::removeContradictions(values);
}
}
void ProgramMemory::setValues(const Token* expr, const Values& values)
{
for (const ValueFlow::Value& value : values)
setValue(expr, value);
}
// The value of the expression when it has exactly one, else nullptr. A constraint counts only when
// asked for.
static const ValueFlow::Value* singleValue(const ProgramMemory::Values& values, bool impossible)
{
if (values.size() != 1 || (!impossible && values.front().isImpossible()))
return nullptr;
return &values.front();
}
const ValueFlow::Value* ProgramMemory::getValue(nonneg int exprid, bool impossible) const
{
const Values* values = getValues(exprid);
return values ? singleValue(*values, impossible) : nullptr;
}
const ProgramMemory::Values* ProgramMemory::getValues(nonneg int exprid) const
{
const auto it = find(exprid);
if (it == mValues->cend())
return nullptr;
return &it->second;
}
bool ProgramMemory::getIntValue(nonneg int exprid, MathLib::bigint& result) const
{
const ValueFlow::Value* value = getValue(exprid);
if (value && value->isIntValue()) {
result = value->intvalue;
return true;
}
return false;
}
void ProgramMemory::setIntValue(const Token* expr, MathLib::bigint value, bool impossible)
{
ValueFlow::Value v(value);
if (impossible)
v.setImpossible();
setValue(expr, v);
}
bool ProgramMemory::getTokValue(nonneg int exprid, const Token*& result) const
{
const ValueFlow::Value* value = getValue(exprid);
if (value && value->isTokValue()) {
result = value->tokvalue;
return true;
}
return false;
}
// cppcheck-suppress unusedFunction
bool ProgramMemory::getContainerSizeValue(nonneg int exprid, MathLib::bigint& result) const
{
const ValueFlow::Value* value = getValue(exprid);
if (value && value->isContainerSizeValue()) {
result = value->intvalue;
return true;
}
return false;
}
// Is the container empty according to its recorded size values? Unknown if they do not decide it.
static ValueFlow::Value containerEmptyValue(const ProgramMemory::Values& values)
{
for (const ValueFlow::Value& value : values) {
if (!value.isContainerSizeValue())
continue;
if (!value.isImpossible())
return ValueFlow::Value{value.intvalue == 0};
if (isUpperBound(value) && value.rangeEdge() <= 0)
return ValueFlow::Value{1};
if (isTrue(value))
return ValueFlow::Value{0};
}
return ValueFlow::Value::unknown();
}
bool ProgramMemory::getContainerEmptyValue(nonneg int exprid, MathLib::bigint& result) const
{
const Values* values = getValues(exprid);
if (!values)
return false;
const ValueFlow::Value isEmpty = containerEmptyValue(*values);
if (isEmpty.isUninitValue())
return false;
result = isEmpty.intvalue;
return true;
}
void ProgramMemory::setContainerSizeValue(const Token* expr, MathLib::bigint value, bool equal)
{
ValueFlow::Value v(value);
v.valueType = ValueFlow::Value::ValueType::CONTAINER_SIZE;
if (!equal)
v.valueKind = ValueFlow::Value::ValueKind::Impossible;
setValue(expr, v);
}
void ProgramMemory::setUnknown(const Token* expr) {
copyOnWrite();
(*mValues)[expr].assign(1, ValueFlow::Value::unknown());
}
bool ProgramMemory::hasValue(nonneg int exprid) const
{
const auto it = find(exprid);
return it != mValues->cend();
}
const ProgramMemory::Values& ProgramMemory::at(nonneg int exprid) const {
const auto it = find(exprid);
if (it == mValues->cend()) {
throw std::out_of_range("ProgramMemory::at");
}
return it->second;
}
ProgramMemory::Values& ProgramMemory::at(nonneg int exprid) {
copyOnWrite();
const auto it = find(exprid);
if (it == mValues->end()) {
throw std::out_of_range("ProgramMemory::at");
}
return it->second;
}
void ProgramMemory::erase_if(const std::function<bool(const ExprIdToken&)>& pred)
{
if (mValues->empty())
return;
// TODO: how to delay until we actually modify?
copyOnWrite();
for (auto it = mValues->begin(); it != mValues->end();) {
if (pred(it->first))
it = mValues->erase(it);
else
++it;
}
}
void ProgramMemory::swap(ProgramMemory &pm) noexcept
{
mValues.swap(pm.mValues);
}
void ProgramMemory::clear()
{
if (mValues->empty())
return;
copyOnWrite();
mValues->clear();
}
bool ProgramMemory::empty() const
{
return mValues->empty();
}
// Is the expression recorded as modified with an unknown value?
static bool isUnknown(const ProgramMemory::Values& values)
{
return !values.empty() && values.front().isUninitValue();
}
// NOLINTNEXTLINE(performance-unnecessary-value-param) - technically correct but we are moving the given values
void ProgramMemory::replace(ProgramMemory pm, bool skipUnknown)
{
if (pm.empty() || mValues == pm.mValues)
return;
copyOnWrite();
// The given memory may share its values with other memories; they must not be moved out from under them
pm.copyOnWrite();
for (auto&& p : (*pm.mValues)) {
if (skipUnknown) {
auto it = mValues->find(p.first);
if (it != mValues->end() && isUnknown(it->second))
continue;
}
(*mValues)[p.first] = std::move(p.second);
}
}
void ProgramMemory::copyOnWrite()
{
if (mValues.use_count() == 1)
return;
mValues = std::make_shared<Map>(*mValues);
}
ProgramMemory::Map::const_iterator ProgramMemory::find(nonneg int exprid) const
{
const auto& cvalues = utils::as_const(*mValues);
return cvalues.find(ExprIdToken::create(exprid));
}
ProgramMemory::Map::iterator ProgramMemory::find(nonneg int exprid)
{
return mValues->find(ExprIdToken::create(exprid));
}
static ValueFlow::Value execute(const Token* expr,
ProgramMemory& pm,
const Settings& settings,
const ProgramMemory::Map& vars = {});
// All values of the expression: the constraints of a range, or the single result of execute()
static ProgramMemory::Values executeValues(const Token* expr,
ProgramMemory& pm,
const Settings& settings,
const ProgramMemory::Map& vars = {});
static bool evaluateCondition(MathLib::bigint r,
const Token* condition,
ProgramMemory& pm,
const Settings& settings,
const ProgramMemory::Map& vars = {})
{
if (!condition)
return false;
MathLib::bigint result = 0;
bool error = false;
execute(condition, pm, &result, &error, settings, vars);
return !error && result == r;
}
bool conditionIsFalse(const Token* condition, ProgramMemory pm, const Settings& settings, const ProgramMemory::Map& vars)
{
return evaluateCondition(0, condition, pm, settings, vars);
}
bool conditionIsTrue(const Token* condition, ProgramMemory pm, const Settings& settings, const ProgramMemory::Map& vars)
{
return evaluateCondition(1, condition, pm, settings, vars);
}
static bool frontIs(const std::vector<MathLib::bigint>& v, bool i)
{
if (v.empty())
return false;
if (v.front())
return i;
return !i;
}
static bool isTrueOrFalse(const ValueFlow::Value& v, bool b)
{
if (b)
return isTrue(v);
return isFalse(v);
}
// Is the expression with these values known to be nonzero? It is when its value is, or when one of
// its constraints excludes zero.
static bool isTrue(const ProgramMemory::Values& values)
{
return std::any_of(values.cbegin(), values.cend(), [](const ValueFlow::Value& v) {
return isTrue(v);
});
}
static bool isFalse(const ProgramMemory::Values& values)
{
return !values.empty() && isFalse(values.front());
}
static bool isTrueOrFalse(const ProgramMemory::Values& values, bool b)
{
return b ? isTrue(values) : isFalse(values);
}
// If the scope is a non-range for loop
static bool isBasicForLoop(const Token* tok)
{
if (!tok)
return false;
if (Token::simpleMatch(tok, "}"))
return isBasicForLoop(tok->link());
if (!Token::simpleMatch(tok->previous(), ") {"))
return false;
const Token* start = tok->linkAt(-1);
if (!start)
return false;
if (!Token::simpleMatch(start->previous(), "for ("))
return false;
if (!Token::simpleMatch(start->astOperand2(), ";"))
return false;
return true;
}
// findChanged: optional cached findExpressionChanged (see ProgramMemoryState::FindChangedFn).
static void programMemoryParseCondition(ProgramMemory& pm,
const Token* tok,
const Token* endTok,
const Settings& settings,
bool then,
const ProgramMemoryState::FindChangedFn& findChanged = {})
{
auto eval = [&](const Token* t) -> std::vector<MathLib::bigint> {
if (!t)
return std::vector<MathLib::bigint>{};
if (const ValueFlow::Value* v = t->getKnownValue(ValueFlow::Value::ValueType::INT))
return {v->intvalue};
MathLib::bigint result = 0;
bool error = false;
execute(t, pm, &result, &error, settings);
if (!error)
return {result};
return std::vector<MathLib::bigint>{};
};
// Use the cached closure if given, else compute directly.
auto changed = [&](const Token* e, const Token* s, const Token* en) -> const Token* {
return findChanged ? findChanged(e, s, en) : findExpressionChanged(e, s, en, settings);
};
if (Token::Match(tok, "==|>=|<=|<|>|!=")) {
ValueFlow::Value truevalue;
ValueFlow::Value falsevalue;
const Token* vartok = parseCompareInt(tok, truevalue, falsevalue, eval);
if (!vartok)
return;
if (vartok->exprId() == 0)
return;
if (!truevalue.isIntValue())
return;
// The other operand is evaluated with its current value, so it must be unchanged as well
if (endTok && changed(tok, tok->next(), endTok))
return;
const bool impossible = (tok->str() == "==" && !then) || (tok->str() == "!=" && then);
ValueFlow::Value& v = then ? truevalue : falsevalue;
// A value with a bound is a range: record it as the range of impossible values so that it
// constrains the expression instead of standing in for its value.
if (impossible || v.bound != ValueFlow::Value::Bound::Point)
v = asImpossible(std::move(v));
pm.setValue(vartok, v);
const Token* containerTok = settings.library.getContainerFromYield(vartok, Library::Container::Yield::SIZE);
if (containerTok) {
v.valueType = ValueFlow::Value::ValueType::CONTAINER_SIZE;
pm.setValue(containerTok, v);
}
} else if (Token::simpleMatch(tok, "!")) {
programMemoryParseCondition(pm, tok->astOperand1(), endTok, settings, !then, findChanged);
} else if (then && Token::simpleMatch(tok, "&&")) {
programMemoryParseCondition(pm, tok->astOperand1(), endTok, settings, then, findChanged);
programMemoryParseCondition(pm, tok->astOperand2(), endTok, settings, then, findChanged);
} else if (!then && Token::simpleMatch(tok, "||")) {
programMemoryParseCondition(pm, tok->astOperand1(), endTok, settings, then, findChanged);
programMemoryParseCondition(pm, tok->astOperand2(), endTok, settings, then, findChanged);
} else if (Token::Match(tok, "&&|%oror%")) {
std::vector<MathLib::bigint> lhs = eval(tok->astOperand1());
std::vector<MathLib::bigint> rhs = eval(tok->astOperand2());
if (lhs.empty() || rhs.empty()) {
if (frontIs(lhs, !then))
programMemoryParseCondition(pm, tok->astOperand2(), endTok, settings, then, findChanged);
else if (frontIs(rhs, !then))
programMemoryParseCondition(pm, tok->astOperand1(), endTok, settings, then, findChanged);
else
pm.setIntValue(tok, 0, then);
}
} else if (tok && tok->exprId() > 0) {
if (endTok && changed(tok, tok->next(), endTok))
return;
pm.setIntValue(tok, 0, then);
const Token* containerTok = settings.library.getContainerFromYield(tok, Library::Container::Yield::EMPTY);
if (containerTok)
pm.setContainerSizeValue(containerTok, 0, then);
}
}
static void fillProgramMemoryFromConditions(ProgramMemory& pm,
const Scope* scope,
const Token* endTok,
const Settings& settings,
const ProgramMemoryState::FindChangedFn& findChanged)
{
if (!scope)
return;
if (!scope->isLocal())
return;
assert(scope != scope->nestedIn);
fillProgramMemoryFromConditions(pm, scope->nestedIn, endTok, settings, findChanged);
if (scope->type == ScopeType::eIf || scope->type == ScopeType::eWhile || scope->type == ScopeType::eElse || scope->type == ScopeType::eFor) {
const Token* condTok = getCondTokFromEnd(scope->bodyEnd);
if (!condTok)
return;
MathLib::bigint result = 0;
bool error = false;
execute(condTok, pm, &result, &error, settings);
if (error)
programMemoryParseCondition(pm, condTok, endTok, settings, scope->type != ScopeType::eElse, findChanged);
}
}
static void fillProgramMemoryFromConditions(ProgramMemory& pm,
const Token* tok,
const Settings& settings,
const ProgramMemoryState::FindChangedFn& findChanged = {})
{
fillProgramMemoryFromConditions(pm, tok->scope(), tok, settings, findChanged);
}
static void fillProgramMemoryFromAssignments(ProgramMemory& pm, const Token* tok, const Settings& settings, const ProgramMemory& state, const ProgramMemory::Map& vars)
{
int indentlevel = 0;
for (const Token *tok2 = tok; tok2; tok2 = tok2->previous()) {
if ((Token::simpleMatch(tok2, "=") || Token::Match(tok2->previous(), "%var% (|{")) && tok2->astOperand1() &&
tok2->astOperand2()) {
const Token* vartok = tok2->astOperand1();
if (!pm.hasValue(vartok->exprId())) {
const Token* valuetok = tok2->astOperand2();
ProgramMemory local = state;
// Tracked values are substituted by execute() when the expression is evaluated.
const ProgramMemory::Values values = executeValues(valuetok, local, settings, vars);
if (values.empty())
pm.setUnknown(vartok);
else
pm.setValues(vartok, values);
}
} else if (Token::simpleMatch(tok2, ")") && tok2->link() &&
Token::Match(tok2->link()->previous(), "assert|ASSERT ( !!)")) {
const Token* cond = tok2->link()->astOperand2();
if (!conditionIsTrue(cond, state, settings)) {
// TODO: change to assert when we can propagate the assert, for now just bail
if (conditionIsFalse(cond, state, settings))
return;
programMemoryParseCondition(pm, cond, nullptr, settings, true);
}
tok2 = tok2->link()->previous();
} else if (tok2->exprId() > 0 && Token::Match(tok2, ".|(|[|*|%var%") && !pm.hasValue(tok2->exprId()) &&
isVariableChanged(tok2, 0, settings)) {
pm.setUnknown(tok2);
}
if (tok2->str() == "{") {
if (indentlevel <= 0) {
const Token* cond = getCondTokFromEnd(tok2->link());
// Keep progressing with anonymous/do scopes and always true branches
if (!Token::Match(tok2->previous(), "do|; {") && !conditionIsTrue(cond, state, settings) &&
(cond || !isBasicForLoop(tok2)))
break;
} else
--indentlevel;
if (Token::simpleMatch(tok2->previous(), "else {"))
tok2 = tok2->linkAt(-2)->previous();
}
if (tok2->str() == "}" && !Token::Match(tok2->link()->previous(), "%var% {")) {
const Token *cond = getCondTokFromEnd(tok2);
const bool inElse = Token::simpleMatch(tok2->link()->previous(), "else {");
if (cond) {
if (conditionIsFalse(cond, state, settings)) {
if (inElse) {
++indentlevel;
continue;
}
} else if (conditionIsTrue(cond, state, settings)) {
if (inElse)
tok2 = tok2->link()->tokAt(-2);
++indentlevel;
continue;
}
}
break;
}
}
}
static void removeModifiedVars(ProgramMemory& pm, const Token* tok, const Token* origin, const Settings& settings)
{
pm.erase_if([&](const ExprIdToken& e) {
return isVariableChanged(origin, tok, e.getExpressionId(), false, settings);
});
}
static ProgramMemory getInitialProgramState(const Token* tok,
const Token* origin,
const Settings& settings,
const ProgramMemory::Map& vars = ProgramMemory::Map {})
{
ProgramMemory pm;
if (origin) {
fillProgramMemoryFromConditions(pm, origin, settings);
const ProgramMemory state = pm;
fillProgramMemoryFromAssignments(pm, tok, settings, state, vars);
removeModifiedVars(pm, tok, origin, settings);
}
return pm;
}
ProgramMemoryState::ProgramMemoryState(const Settings& s) : settings(s), changedCache(std::make_shared<ChangedCache>())
{}
void ProgramMemoryState::replace(ProgramMemory pm, const Token* origin)
{
if (origin)
for (const auto& p : pm)
origins[p.first.getExpressionId()] = origin;
state.replace(std::move(pm), /*skipUnknown*/ true);
}
static void addVars(ProgramMemory& pm, const ProgramMemory::Map& vars)
{
for (const auto& p:vars)
pm.setValues(p.first.tok, p.second);
}
void ProgramMemoryState::addState(const Token* tok, const ProgramMemory::Map& vars)
{
ProgramMemory local = state;
addVars(local, vars);
fillProgramMemoryFromConditions(local, tok, settings, getCachedFindExpressionChanged(/*skipDeadCode*/ false));
ProgramMemory pm;
fillProgramMemoryFromAssignments(pm, tok, settings, local, vars);
local.replace(std::move(pm));
addVars(local, vars);
replace(std::move(local), tok);
}
void ProgramMemoryState::assume(const Token* tok, bool b, bool isEmpty, const Token* origin)
{
ProgramMemory pm = state;
if (isEmpty)
pm.setContainerSizeValue(tok, 0, b);
else
programMemoryParseCondition(pm, tok, nullptr, settings, b);
if (!origin) {
origin = tok;
const Token* top = tok->astTop();
if (Token::Match(top->previous(), "for|while|if (") && !Token::simpleMatch(tok->astParent(), "?")) {
origin = top->link()->next();
if (!b && origin->link()) {
origin = origin->link();
// The false path runs the else block
if (Token::simpleMatch(origin, "} else {"))
origin = origin->tokAt(2);
}
}
}
replace(std::move(pm), origin);
}
ProgramMemoryState::FindChangedFn ProgramMemoryState::getCachedFindExpressionChanged(bool skipDeadCode) const
{
// Structural findExpressionChanged() is pure, so memoize it in changedCache (never invalidated).
// skipDeadCode adds the dead-code walk; it evaluates guards against a fixed state snapshot (so every
// variable follows the same path) and memoizes those evals in evalCache for the closure's lifetime.
using EvalCache = std::map<const Token*, std::vector<MathLib::bigint>>;
const std::shared_ptr<ChangedCache> cache = changedCache;
const Settings* const sp = &settings();
ProgramMemory snapshot = state;
const std::shared_ptr<EvalCache> evalCache = skipDeadCode ? std::make_shared<EvalCache>() : nullptr;
return [cache, sp, snapshot, skipDeadCode, evalCache](const Token* expr,
const Token* start,
const Token* end) -> const Token* {
const auto key = std::make_tuple(expr, start, end);
const auto it = cache->find(key);
const Token* modified = (it != cache->end())
? it->second
: cache->emplace(key, findExpressionChanged(expr, start, end, *sp)).first->second;
if (!skipDeadCode || !modified)
return modified;
auto eval = [&](const Token* cond) -> std::vector<MathLib::bigint> {
const auto cit = evalCache->find(cond);
if (cit != evalCache->end())
return cit->second;
ProgramMemory pm2 = snapshot;
const auto result = execute(cond, pm2, *sp);
std::vector<MathLib::bigint> r;
if (isTrue(result))
r = {1};
else if (isFalse(result))
r = {0};
return evalCache->emplace(cond, std::move(r)).first->second;
};
return findExpressionChangedSkipDeadCode(expr, start, end, *sp, eval);
};
}
void ProgramMemoryState::removeModifiedVars(const Token* tok)
{
const auto findChanged = getCachedFindExpressionChanged(/*skipDeadCode*/ true);
state.erase_if([&](const ExprIdToken& e) {
const Token* start = origins[e.getExpressionId()];
// The then-path skips the else block
if (Token::simpleMatch(start, "} else {"))
start = start->linkAt(2);
const Token* expr = e.tok;
const bool changed = !expr || findChanged(expr, start, tok);
if (changed)
origins.erase(e.getExpressionId());
return changed;
});
}
ProgramMemory ProgramMemoryState::get(const Token* tok, const Token* ctx, const ProgramMemory::Map& vars) const
{
ProgramMemoryState local = *this;
if (ctx)
local.addState(ctx, vars);
const Token* start = previousBeforeAstLeftmostLeaf(tok);
if (!start)
start = tok;
if (!ctx || precedes(start, ctx)) {
local.removeModifiedVars(start);
local.addState(start, vars);
} else {
local.removeModifiedVars(ctx);
}
return local.state;
}
ProgramMemory getProgramMemory(const Token* tok, const Token* expr, const ValueFlow::Value& value, const Settings& settings)
{
ProgramMemory programMemory;
programMemory.replace(getInitialProgramState(tok, value.tokvalue, settings));
programMemory.replace(getInitialProgramState(tok, value.condition, settings));
fillProgramMemoryFromConditions(programMemory, tok, settings);
programMemory.setValue(expr, value);
const ProgramMemory state = programMemory;
fillProgramMemoryFromAssignments(programMemory, tok, settings, state, {{expr, {value}}});
return programMemory;
}
static bool isNumericValue(const ValueFlow::Value& value) {
return value.isIntValue() || value.isFloatValue();
}
static double asFloat(const ValueFlow::Value& value)
{
return value.isFloatValue() ? value.floatValue : static_cast<double>(value.intvalue);
}
static MathLib::bigint asInt(const ValueFlow::Value& value)
{
return value.isFloatValue() ? static_cast<MathLib::bigint>(value.floatValue) : value.intvalue;
}
namespace {
struct assign {
template<class T, class U>
void operator()(T& x, const U& y) const
{
x = static_cast<T>(y);
}
};
}
static bool isIntegralValue(const ValueFlow::Value& value)
{
return value.isIntValue() || value.isIteratorValue() || value.isSymbolicValue();
}
static bool isBounded(const ValueFlow::Value& value)
{
return value.bound != ValueFlow::Value::Bound::Point;
}
static bool addOverflows(MathLib::bigint x, MathLib::bigint y)
{
if (y > 0)
return x > std::numeric_limits<MathLib::bigint>::max() - y;
return x < std::numeric_limits<MathLib::bigint>::min() - y;
}
static bool subtractOverflows(MathLib::bigint x, MathLib::bigint y)
{
if (y < 0)
return x > std::numeric_limits<MathLib::bigint>::max() + y;
return x < std::numeric_limits<MathLib::bigint>::min() + y;
}
static bool multiplyOverflows(MathLib::bigint x, MathLib::bigint y)
{
if (x == 0 || y == 0)
return false;
if (ValueFlow::isSaturated(x) || ValueFlow::isSaturated(y))
return true;
return std::abs(x) > std::numeric_limits<MathLib::bigint>::max() / std::abs(y);
}
// Is the left shift not defined, or does its result not fit?
static bool shiftOverflows(MathLib::bigint x, MathLib::bigint shift)
{
if (x < 0 || shift < 0 || shift >= MathLib::bigint_bits - 1)
return true;
const MathLib::biguint limit = static_cast<MathLib::biguint>(std::numeric_limits<MathLib::bigint>::max()) >>
static_cast<unsigned>(shift);
return static_cast<MathLib::biguint>(x) > limit;
}
// The operations that keep the order of the values of a range
static bool isMonotone(const std::string& op)
{
return contains({"+", "-", "*", "/", "<<", ">>"}, op);
}
static bool isComparison(const std::string& op)
{
return contains({"==", "!=", "<", ">", "<=", ">="}, op);
}
static bool isArithmetical(const std::string& op)
{
return contains({"+", "-", "*", "/", "%", "<<", ">>"}, op);
}
// "x <op> y" for the operations that keep the order of the values; unknown when the operation is not
// defined or its result does not fit the analyzer's integers, which calculate() does not check.
// Unlike calculate(), a division by a negative value is allowed.
static ValueFlow::Value applyOp(const std::string& op, MathLib::bigint x, MathLib::bigint y)
{
if (ValueFlow::isSaturated(x) || ValueFlow::isSaturated(y))
return ValueFlow::Value::unknown();
bool error = false;
if (op == "+")
error = addOverflows(x, y);
else if (op == "-")
error = subtractOverflows(x, y);
else if (op == "*")
error = multiplyOverflows(x, y);
else if (op == "/")
return y == 0 ? ValueFlow::Value::unknown() : ValueFlow::Value{x / y};
else if (op == "<<")
error = shiftOverflows(x, y);
else if (op != ">>")
return ValueFlow::Value::unknown();
if (error)
return ValueFlow::Value::unknown();
const MathLib::bigint result = calculate(op, x, y, &error);
return error ? ValueFlow::Value::unknown() : ValueFlow::Value{result};
}
// The range of "x <op> k" (or "k <op> x") when the values of x up to (or from) the bound are
// impossible: the end of the range is transformed; an operation that reverses the order of the
// values turns the range around.
static ValueFlow::Value applyToRange(const std::string& op, const ValueFlow::Value& range, MathLib::bigint k, bool rangeIsLhs)
{
// A bound at the limit of the type has no edge beyond it
if (ValueFlow::isSaturated(range.intvalue))
return ValueFlow::Value::unknown();
// Scaling by zero collapses the range; dividing or shifting by the range does not keep the order
if (((op == "*" || op == "/") && k == 0) || (!rangeIsLhs && contains({"/", "<<", ">>"}, op)))
return ValueFlow::Value::unknown();
const MathLib::bigint edge = range.rangeEdge();
const ValueFlow::Value result = applyOp(op, rangeIsLhs ? edge : k, rangeIsLhs ? k : edge);
if (result.isUninitValue())
return ValueFlow::Value::unknown();
const bool increasing = op == "-" ? rangeIsLhs : !((op == "*" || op == "/") && k < 0);
ValueFlow::Value scaled = range;
if (!scaled.setRangeEdge(result.intvalue, range.isLowerEdge() == increasing))
return ValueFlow::Value::unknown();
return scaled;
}
static ValueFlow::Value evaluate(const std::string& opStr, const ValueFlow::Value& lhs, const ValueFlow::Value& rhs)
{
ValueFlow::Value result;
if (lhs.isImpossible() && rhs.isImpossible())
return ValueFlow::Value::unknown();
// An impossible range and an int: the range of the result, for the operations that keep the order
const bool rangeIsLhs = lhs.isImpossible() && isBounded(lhs);
const ValueFlow::Value& range = rangeIsLhs ? lhs : rhs;
const ValueFlow::Value& k = rangeIsLhs ? rhs : lhs;
if (range.isImpossible() && isBounded(range) && range.isIntValue() && !k.isImpossible() && !isBounded(k) &&
k.isIntValue() && isMonotone(opStr))
return applyToRange(opStr, range, k.intvalue, rangeIsLhs);
if (lhs.isImpossible() || rhs.isImpossible()) {
// The image of an impossible value is impossible only for an injective operation
if (contains({"%", "/", "&", "|", ">>"}, opStr))
return ValueFlow::Value::unknown();
const ValueFlow::Value& factor = lhs.isImpossible() ? rhs : lhs;
if (opStr == "*" && factor.equalTo(0))
return ValueFlow::Value::unknown();
result.setImpossible();
}
if (isNumericValue(lhs) && isNumericValue(rhs)) {
if (lhs.isFloatValue() || rhs.isFloatValue()) {
result.valueType = isArithmetical(opStr) ? ValueFlow::Value::ValueType::FLOAT : ValueFlow::Value::ValueType::INT;
bool error = false;
result.floatValue = calculate(opStr, asFloat(lhs), asFloat(rhs), &error);
if (error)
return ValueFlow::Value::unknown();
return result;
}
}
// Must be integral types
if (!isIntegralValue(lhs) && !isIntegralValue(rhs))
return ValueFlow::Value::unknown();
// If not the same type then one must be int
if (lhs.valueType != rhs.valueType && !lhs.isIntValue() && !rhs.isIntValue())
return ValueFlow::Value::unknown();
const bool compareOp = isComparison(opStr);
// Comparison must be the same type