-
Notifications
You must be signed in to change notification settings - Fork 79
Expand file tree
/
Copy pathSemaBounds.cpp
More file actions
6562 lines (5849 loc) · 278 KB
/
SemaBounds.cpp
File metadata and controls
6562 lines (5849 loc) · 278 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
//===---------- SemaBounds.cpp - Operations On Bounds Expressions --------===//
//
// The LLVM Compiler Infrastructure
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file implements operations on bounds expressions for semantic analysis.
// The operations include:
// * Abstracting bounds expressions so that they can be used in function types.
// This also checks that requirements on variable references are met and
// emit diagnostics if they are not.
//
// The abstraction also removes extraneous details:
// - References to ParamVarDecl's are abstracted to positional index numbers
// in argument lists.
// - References to other VarDecls's are changed to use canonical
// declarations.
//
// Line number information is left in place for expressions, though. It
// would be a lot of work to write functions to change the line numbers to
// the invalid line number. The canonicalization of types ignores line number
// information in determining if two expressions are the same. Users of bounds
// expressions that have been abstracted need to be aware that line number
// information may be inaccurate.
// * Concretizing bounds expressions from function types. This undoes the
// abstraction by substituting parameter varaibles for the positional index
// numbers.
//
// Debugging pre-processor flags:
// - TRACE_CFG:
// Dumps AST and CFG of the visited nodes when traversing the CFG.
// - TRACE_RANGE:
// Dumps the valid bounds ranges, memory access ranges and memory
// access expressions.
//===----------------------------------------------------------------------===//
#include "clang/Analysis/CFG.h"
#include "clang/Analysis/Analyses/PostOrderCFGView.h"
#include "clang/AST/AbstractSet.h"
#include "clang/AST/CanonBounds.h"
#include "clang/AST/ExprUtils.h"
#include "clang/AST/NormalizeUtils.h"
#include "clang/AST/RecursiveASTVisitor.h"
#include "clang/Sema/AvailableFactsAnalysis.h"
#include "clang/Sema/BoundsUtils.h"
#include "clang/Sema/BoundsWideningAnalysis.h"
#include "clang/Sema/CheckedCAnalysesPrepass.h"
#include "llvm/ADT/SmallBitVector.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallString.h"
#include "TreeTransform.h"
#include <queue>
// #define TRACE_CFG 1
// #define TRACE_RANGE 1
using namespace clang;
using namespace sema;
namespace {
class AbstractBoundsExpr : public TreeTransform<AbstractBoundsExpr> {
typedef TreeTransform<AbstractBoundsExpr> BaseTransform;
typedef ArrayRef<DeclaratorChunk::ParamInfo> ParamsInfo;
private:
const ParamsInfo Params;
// TODO: change this constant when we want to error on global variables
// in parameter bounds declarations.
const bool errorOnGlobals = false;
public:
AbstractBoundsExpr(Sema &SemaRef, ParamsInfo Params) :
BaseTransform(SemaRef), Params(Params) {}
Decl *TransformDecl(SourceLocation Loc, Decl *D) {
return D->getCanonicalDecl();
}
ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
ValueDecl *D = E->getDecl();
if (VarDecl *V = dyn_cast<VarDecl>(D)) {
if (V->isLocalVarDecl())
// Parameter bounds may not be in terms of local variables
SemaRef.Diag(E->getLocation(),
diag::err_out_of_scope_function_type_local);
else if (V->isFileVarDecl() || V->isExternC()) {
// Parameter bounds may not be in terms of "global" variables
// TODO: This is guarded by a flag right now, as we don't yet
// want to error everywhere.
if (errorOnGlobals) {
SemaRef.Diag(E->getLocation(),
diag::err_out_of_scope_function_type_global);
}
}
else if (ParmVarDecl *PD = dyn_cast<ParmVarDecl>(D)) {
// Parameter bounds may be in terms of other parameters,
// in which case we'll convert to a position-based representation.
for (auto &ParamInfo : Params)
if (PD == ParamInfo.Param) {
return SemaRef.CreatePositionalParameterExpr(
PD->getFunctionScopeIndex(),
PD->getType());
}
SemaRef.Diag(E->getLocation(),
diag::err_out_of_scope_function_type_parameter);
}
}
ValueDecl *ND =
dyn_cast_or_null<ValueDecl>(BaseTransform::TransformDecl(
SourceLocation(), D));
if (D == ND || ND == nullptr)
return E;
else {
clang::NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc();
clang::DeclarationNameInfo NameInfo = E->getNameInfo();
return getDerived().RebuildDeclRefExpr(QualifierLoc, ND, NameInfo,
nullptr, nullptr);
}
}
};
}
bool Sema::AbstractForFunctionType(
BoundsAnnotations &Annots,
ArrayRef<DeclaratorChunk::ParamInfo> Params) {
BoundsExpr *Expr = Annots.getBoundsExpr();
// If there is no bounds expression, the itype does not change
// as aresult of abstraction. Just return the original annotation.
if (!Expr)
return false;
BoundsExpr *Result = nullptr;
ExprResult AbstractedBounds =
AbstractBoundsExpr(*this, Params).TransformExpr(Expr);
if (AbstractedBounds.isInvalid()) {
llvm_unreachable("unexpected failure to abstract bounds");
Result = nullptr;
} else {
Result = dyn_cast<BoundsExpr>(AbstractedBounds.get());
assert(Result && "unexpected dyn_cast failure");
}
if (Result == Expr)
return false;
Annots.setBoundsExpr(Result);
return true;
}
namespace {
class ConcretizeBoundsExpr : public TreeTransform<ConcretizeBoundsExpr> {
typedef TreeTransform<ConcretizeBoundsExpr> BaseTransform;
private:
ArrayRef<ParmVarDecl *> Parameters;
public:
ConcretizeBoundsExpr(Sema &SemaRef, ArrayRef<ParmVarDecl *> Params) :
BaseTransform(SemaRef),
Parameters(Params) { }
ExprResult TransformPositionalParameterExpr(PositionalParameterExpr *E) {
unsigned index = E->getIndex();
if (index < Parameters.size()) {
ParmVarDecl *PD = Parameters[index];
return SemaRef.BuildDeclRefExpr(PD, E->getType(),
clang::ExprValueKind::VK_LValue, SourceLocation());
} else {
llvm_unreachable("out of range index for positional parameter");
return ExprError();
}
}
};
}
BoundsExpr *Sema::ConcretizeFromFunctionType(BoundsExpr *Expr,
ArrayRef<ParmVarDecl *> Params) {
if (!Expr)
return Expr;
BoundsExpr *Result;
ExprSubstitutionScope Scope(*this); // suppress diagnostics
ExprResult ConcreteBounds = ConcretizeBoundsExpr(*this, Params).TransformExpr(Expr);
if (ConcreteBounds.isInvalid()) {
llvm_unreachable("unexpected failure in making bounds concrete");
return nullptr;
}
else {
Result = dyn_cast<BoundsExpr>(ConcreteBounds.get());
assert(Result && "unexpected dyn_cast failure");
return Result;
}
}
namespace {
class CheckForModifyingArgs : public RecursiveASTVisitor<CheckForModifyingArgs> {
private:
Sema &SemaRef;
const ArrayRef<Expr *> Arguments;
llvm::SmallBitVector VisitedArgs;
Sema::NonModifyingContext ErrorKind;
Sema::NonModifyingMessage Message;
bool ModifyingArg;
public:
CheckForModifyingArgs(Sema &SemaRef, ArrayRef<Expr *> Args,
Sema::NonModifyingContext ErrorKind,
Sema::NonModifyingMessage Message) :
SemaRef(SemaRef),
Arguments(Args),
VisitedArgs(Args.size()),
ErrorKind(ErrorKind),
Message(Message),
ModifyingArg(false) {}
bool FoundModifyingArg() {
return ModifyingArg;
}
bool VisitPositionalParameterExpr(PositionalParameterExpr *E) {
unsigned index = E->getIndex();
if (index < Arguments.size() && !VisitedArgs[index]) {
VisitedArgs.set(index);
if (!SemaRef.CheckIsNonModifying(Arguments[index], ErrorKind, Message)) {
ModifyingArg = true;
}
}
return true;
}
};
}
namespace {
class ConcretizeBoundsExprWithArgs : public TreeTransform<ConcretizeBoundsExprWithArgs> {
typedef TreeTransform<ConcretizeBoundsExprWithArgs> BaseTransform;
private:
ArrayRef<Expr *> Args;
public:
ConcretizeBoundsExprWithArgs(Sema &SemaRef, ArrayRef<Expr *> Args) :
BaseTransform(SemaRef),
Args(Args) { }
ExprResult TransformPositionalParameterExpr(PositionalParameterExpr *E) {
unsigned index = E->getIndex();
if (index < Args.size()) {
return SemaRef.MakeAssignmentImplicitCastExplicit(Args[index]);
} else {
llvm_unreachable("out of range index for positional parameter");
return ExprError();
}
}
};
}
BoundsExpr *Sema::ConcretizeFromFunctionTypeWithArgs(
BoundsExpr *Bounds, ArrayRef<Expr *> Args,
NonModifyingContext ErrorKind, NonModifyingMessage Message) {
if (!Bounds || Bounds->isInvalid())
return Bounds;
auto CheckArgs = CheckForModifyingArgs(*this, Args, ErrorKind, Message);
CheckArgs.TraverseStmt(Bounds);
if (CheckArgs.FoundModifyingArg())
return nullptr;
ExprSubstitutionScope Scope(*this); // suppress diagnostics
auto Concretizer = ConcretizeBoundsExprWithArgs(*this, Args);
ExprResult ConcreteBounds = Concretizer.TransformExpr(Bounds);
if (ConcreteBounds.isInvalid()) {
#ifndef NDEBUG
llvm::outs() << "Failed concretizing\n";
llvm::outs() << "Bounds:\n";
Bounds->dump(llvm::outs(), Context);
int count = Args.size();
for (int i = 0; i < count; i++) {
llvm::outs() << "Dumping arg " << i << "\n";
Args[i]->dump(llvm::outs(), Context);
}
llvm::outs().flush();
#endif
llvm_unreachable("unexpected failure in making function bounds concrete with arguments");
return nullptr;
}
else {
BoundsExpr *Result = dyn_cast<BoundsExpr>(ConcreteBounds.get());
assert(Result && "unexpected dyn_cast failure");
return Result;
}
}
namespace {
class ConcretizeMemberBounds : public TreeTransform<ConcretizeMemberBounds> {
typedef TreeTransform<ConcretizeMemberBounds> BaseTransform;
private:
Expr *Base;
bool IsArrow;
public:
ConcretizeMemberBounds(Sema &SemaRef, Expr *MemberBaseExpr, bool IsArrow) :
BaseTransform(SemaRef), Base(MemberBaseExpr), IsArrow(IsArrow) { }
// TODO: handle the situation where the base expression is an rvalue.
// By C semantics, the result is an rvalue. We are setting fields used in
// bounds expressions to be lvalues, so we end up with a problems when
// we expand the occurrences of the fields to be expressions that are
// rvalues.
//
// There are two problematic cases:
// - We assume field expressions are lvalues, so we will have lvalue-to-rvalue
// conversions applied to rvalues. We need to remove these conversions.
// - The address of a field is taken. It is illegal to take the address of
// an rvalue.
//
// rVvalue structs can arise from function returns of struct values.
ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
if (FieldDecl *FD = dyn_cast<FieldDecl>(E->getDecl())) {
if (Base->isRValue() && !IsArrow)
// For now, return an error if we see an rvalue base.
return ExprError();
ASTContext &Context = SemaRef.getASTContext();
ExprValueKind ResultKind;
if (IsArrow)
ResultKind = VK_LValue;
else
ResultKind = Base->isLValue() ? VK_LValue : VK_RValue;
return
MemberExpr::CreateImplicit(Context, Base, IsArrow, FD,
E->getType(), ResultKind, OK_Ordinary);
}
return E;
}
};
}
BoundsExpr *Sema::MakeMemberBoundsConcrete(
Expr *Base,
bool IsArrow,
BoundsExpr *Bounds) {
ExprSubstitutionScope Scope(*this); // suppress diagnostics
ExprResult ConcreteBounds =
ConcretizeMemberBounds(*this, Base, IsArrow).TransformExpr(Bounds);
if (ConcreteBounds.isInvalid())
return nullptr;
else {
BoundsExpr *Result = dyn_cast<BoundsExpr>(ConcreteBounds.get());
return Result;
}
}
#if 0
namespace {
// Convert occurrences of _Return_value in a return bounds expression
// to _Current_expr_value. Don't recurse into any return bounds
// expressions nested in function types. Occurrences of _Return_value
// in those shouldn't be changed to _Current_value.
class ReplaceReturnValue : public TreeTransform<ReplaceReturnValue> {
typedef TreeTransform<ReplaceReturnValue> BaseTransform;
public:
ReplaceReturnValue(Sema &SemaRef) :BaseTransform(SemaRef) { }
// Avoid transforming nested return bounds expressions.
bool TransformReturnBoundsAnnotations(BoundsAnnotations &Annot,
bool &Changed) {
return false;
}
ExprResult TransformBoundsValueExpr(BoundsValueExpr *E) {
BoundsValueExpr::Kind K = E->getKind();
bool KindChanged = false;
if (K == BoundsValueExpr::Kind::Return) {
K = BoundsValueExpr::Kind::Current;
KindChanged = true;
}
QualType QT = getDerived().TransformType(E->getType());
if (!getDerived().AlwaysRebuild() && QT == E->getType() &&
!KindChanged)
return E;
return getDerived().
RebuildBoundsValueExpr(E->getLocation(), QT,K);
}
};
}
#endif
// Convert all temporary bindings in an expression to uses of the values
// produced by a binding. This should be done for bounds expressions that
// are used in runtime checks. That way we don't try to recompute a
// temporary multiple times in an expression.
namespace {
class PruneTemporaryHelper : public TreeTransform<PruneTemporaryHelper> {
typedef TreeTransform<PruneTemporaryHelper> BaseTransform;
public:
PruneTemporaryHelper(Sema &SemaRef) :
BaseTransform(SemaRef) { }
ExprResult TransformCHKCBindTemporaryExpr(CHKCBindTemporaryExpr *E) {
return new (SemaRef.Context) BoundsValueExpr(SourceLocation(), E);
}
};
Expr *PruneTemporaryBindings(Sema &SemaRef, Expr *E, CheckedScopeSpecifier CSS) {
// Account for checked scope information when transforming the expression.
Sema::CheckedScopeRAII CheckedScope(SemaRef, CSS);
Sema::ExprSubstitutionScope Scope(SemaRef); // suppress diagnostics
ExprResult R = PruneTemporaryHelper(SemaRef).TransformExpr(E);
if (R.isInvalid())
return SemaRef.Context.getPrebuiltBoundsUnknown();
else
return R.get();
}
}
namespace {
using EqualExprTy = SmallVector<Expr *, 4>;
using DeclSetTy = llvm::DenseSet<const VarDecl *>;
// EqualExprsContainsExpr returns true if the set Exprs contains an
// expression that is equivalent to E.
bool EqualExprsContainsExpr(Sema &S, const EqualExprTy Exprs, Expr *E,
EquivExprSets *EquivExprs) {
for (auto I = Exprs.begin(); I != Exprs.end(); ++I) {
if (Lexicographic(S.Context, EquivExprs).CompareExpr(*I, E) ==
Lexicographic::Result::Equal)
return true;
}
return false;
}
// Helper class for collecting a vector of unique variables as rvalues from an
// expression. We collect rvalues because CheckingState.EquivExprSet uses
// rvalues to check equality.
class CollectVariableSetHelper
: public RecursiveASTVisitor<CollectVariableSetHelper> {
private:
Sema &SemaRef;
EqualExprTy VariableList;
public:
CollectVariableSetHelper(Sema &SemaRef)
: SemaRef(SemaRef), VariableList() {}
const EqualExprTy &GetVariableList() const { return VariableList; }
bool VisitDeclRefExpr(DeclRefExpr *E) {
// TODO: GitHub checkedc-clang issue #966. This method is quadratic
// in the number of variables in an expression. It should use a
// hashtable to determine whether E should be added to VariableList.
if (!EqualExprsContainsExpr(SemaRef, VariableList, E, nullptr)) {
VariableList.push_back(E);
}
return true;
}
};
// Collect variables in E without duplication. If E is nullptr, return an
// empty vector.
EqualExprTy CollectVariableSet(Sema &SemaRef, Expr *E) {
CollectVariableSetHelper Helper(SemaRef);
Helper.TraverseStmt(E);
return Helper.GetVariableList();
}
}
namespace {
// BoundsContextTy denotes a map of an AbstractSet to the bounds that
// are currently known to be valid for the lvalue expressions in the set.
using BoundsContextTy = llvm::DenseMap<const AbstractSet *, BoundsExpr *>;
// ExprSetTy denotes a set of expressions.
using ExprSetTy = SmallVector<Expr *, 4>;
// ExprEqualMapTy denotes a map of an expression e to the set of
// expressions that produce the same value as e.
using ExprEqualMapTy = llvm::DenseMap<Expr *, ExprSetTy>;
// Describes the position of a free variable (FR).
enum class FreeVariablePosition {
Lower = 0x1, // The FR appears in (any) lower bounds.
Upper = 0x2, // The FR appears in (any) upper bounds.
Observed = 0x4, // The FR appears in the observed bounds.
Declared = 0x8, // The FR appears in the declared bounds.
};
// FreeVariableListTy denotes a vector of <free variable, position> pairs, and
// represents a list of free variables and their positions w.r.t. the observed
// and declared bounds.
using FreeVariableListTy =
SmallVector<std::pair<Expr *, FreeVariablePosition>, 4>;
// AbstractSetSetTy denotes a set of AbstractSets.
using AbstractSetSetTy = llvm::SmallPtrSet<const AbstractSet *, 4>;
// CheckingState stores the outputs of bounds checking methods.
// These members represent the state during bounds checking
// and are updated while checking individual expressions.
class CheckingState {
public:
// ObservedBounds maps AbstractSets to their current known bounds as
// inferred by bounds checking. These bounds are updated after
// assignments to variables.
//
// ObservedBounds is named UC in the Checked C spec.
//
// The bounds in the ObservedBounds context should always be normalized
// to range bounds if possible. This allows updates to variables that
// are implicitly used in bounds declarations to update the observed
// bounds. For example, an assignment to the variable p where p has
// declared bounds count(i) should update the bounds of p, which
// normalize to bounds(p, p + i).
BoundsContextTy ObservedBounds;
// EquivExprs stores sets of expressions that are equivalent to each
// other after checking an expression e. If two expressions e1 and
// e2 are in the same set in EquivExprs, e1 and e2 produce the same
// value.
//
// EquivExprs is named UEQ in the Checked C spec.
EquivExprSets EquivExprs;
// SameValue is a set of expressions that produce the same value as an
// expression e once checking of e is complete.
//
// SameValue is named G in the Checked C spec.
ExprSetTy SameValue;
// LostLValues maps an AbstractSet A whose observed bounds are unknown
// to a pair <B, E>, where the initial observed bounds B of A have been
// set to unknown due to an assignment to the lvalue expression E, where
// E had no original value.
//
// LostLValues is used to emit notes to provide more context to the user
// when diagnosing unknown bounds errors.
llvm::DenseMap<const AbstractSet *, std::pair<BoundsExpr *, Expr *>> LostLValues;
// UnknownSrcBounds maps an AbstractSet A whose observed bounds are
// unknown to a set of expressions with unknown bounds that have been
// assigned to A.
//
// UnknownSrcBounds is used to emit notes to provide more context to the
// user when diagnosing unknown bounds errors.
llvm::DenseMap<const AbstractSet *, SmallVector<Expr *, 4>> UnknownSrcBounds;
// BlameAssignments maps an AbstractSet A to an expression in a top-level
// CFG statement that last updates any variable used in the declared
// bounds of A.
//
// BlameAssignments is used to provide more context for two types of
// diagnostic messages:
// 1. The compiler cannot prove or can disprove the declared bounds for
// A are valid after an assignment to a variable in the bounds of A; and
// 2. The inferred bounds of A become unknown after an assignment to a
// variable in the bounds of A.
//
// BlameAssignments is updated in UpdateAfterAssignment and reset after
// checking each top-level CFG statement.
llvm::DenseMap<const AbstractSet *, Expr *> BlameAssignments;
// TargetSrcEquality maps a target expression V to the most recent
// expression Src that has been assigned to V within the current
// top-level CFG statement. When validating the bounds context,
// each pair <V, Src> should be included in a set EQ that contains
// all equality facts in the EquivExprs state set. The set EQ will
// then be used to validate the bounds context.
llvm::DenseMap<Expr *, Expr *> TargetSrcEquality;
// Resets the checking state after checking a top-level CFG statement.
void Reset() {
SameValue.clear();
LostLValues.clear();
UnknownSrcBounds.clear();
BlameAssignments.clear();
TargetSrcEquality.clear();
}
};
}
namespace {
class DeclaredBoundsHelper : public RecursiveASTVisitor<DeclaredBoundsHelper> {
private:
Sema &SemaRef;
BoundsContextTy &BoundsContextRef;
AbstractSetManager &AbstractSetMgr;
public:
DeclaredBoundsHelper(Sema &SemaRef, BoundsContextTy &Context,
AbstractSetManager &AbstractSetMgr) :
SemaRef(SemaRef),
BoundsContextRef(Context),
AbstractSetMgr(AbstractSetMgr) {}
// If a variable declaration has declared bounds, modify BoundsContextRef
// to map the variable declaration to the normalized declared bounds.
//
// Returns true if visiting the variable declaration did not terminate
// early. Visiting variable declarations in DeclaredBoundsHelper should
// never terminate early.
bool VisitVarDecl(const VarDecl *D) {
if (!D)
return true;
if (D->isInvalidDecl())
return true;
if (!D->hasBoundsExpr())
return true;
// Parameters declared within a statement (e.g. in a function pointer
// declaration) should not be added to the bounds context. Parameters
// to the current function will be added to the bounds context in
// TraverseCFG.
if (isa<ParmVarDecl>(D))
return true;
// The bounds expressions in the bounds context should be normalized
// to range bounds.
if (BoundsExpr *Bounds = SemaRef.NormalizeBounds(D)) {
const AbstractSet *A = AbstractSetMgr.GetOrCreateAbstractSet(D);
BoundsContextRef[A] = Bounds;
}
return true;
}
};
// GetDeclaredBounds modifies the bounds context to map any variables
// declared in S to their declared bounds (if any).
void GetDeclaredBounds(Sema &SemaRef, BoundsContextTy &Context, Stmt *S,
AbstractSetManager &AbstractSetMgr) {
DeclaredBoundsHelper Declared(SemaRef, Context, AbstractSetMgr);
Declared.TraverseStmt(S);
}
}
namespace {
class CheckBoundsDeclarations {
private:
Sema &S;
bool DumpBounds;
bool DumpState;
bool DumpSynthesizedMembers;
uint64_t PointerWidth;
Stmt *Body;
CFG *Cfg;
// Declaration for enclosing function. Having this here allows us to emit
// the name of the function in any diagnostic message when checking return
// bounds.
FunctionDecl *FunctionDeclaration;
// Return value expression for enclosing function, if any. Having this
// here allows us to avoid reconstructing a return value for each
// return statement.
BoundsValueExpr *ReturnVal;
// Expanded declared return bounds expression for enclosing function, if
// any. Having this here allows us to avoid re-expanding the return bounds
// for each return statement.
BoundsExpr *ReturnBounds;
ASTContext &Context;
std::pair<ComparisonSet, ComparisonSet> &Facts;
// Having a BoundsWideningAnalysis object here allows us to easily invoke
// methods for bounds widening and get back the widened bounds info needed
// for bounds inference/checking.
BoundsWideningAnalysis BoundsWideningAnalyzer;
// Having an AbstractSetManager object here allows us to create
// AbstractSets for lvalue expressions while checking statements.
AbstractSetManager AbstractSetMgr;
// Map a field F in a record declaration to the sibling fields of F
// in whose declared bounds F appears.
BoundsSiblingFieldsTy BoundsSiblingFields;
// When this flag is set to true, include the null terminator in the
// bounds of a null-terminated array. This is used when calculating
// physical sizes during casts to pointers to null-terminated arrays.
bool IncludeNullTerminator;
void DumpAssignmentBounds(raw_ostream &OS, BinaryOperator *E,
BoundsExpr *LValueTargetBounds,
BoundsExpr *RHSBounds) {
OS << "\n";
E->dump(OS, Context);
if (LValueTargetBounds) {
OS << "Target Bounds:\n";
LValueTargetBounds->dump(OS, Context);
}
if (RHSBounds) {
OS << "RHS Bounds:\n ";
RHSBounds->dump(OS, Context);
}
}
void DumpBoundsCastBounds(raw_ostream &OS, CastExpr *E,
BoundsExpr *Declared, BoundsExpr *NormalizedDeclared,
BoundsExpr *SubExprBounds) {
OS << "\n";
E->dump(OS, Context);
if (Declared) {
OS << "Declared Bounds:\n";
Declared->dump(OS, Context);
}
if (NormalizedDeclared) {
OS << "Normalized Declared Bounds:\n ";
NormalizedDeclared->dump(OS, Context);
}
if (SubExprBounds) {
OS << "Inferred Subexpression Bounds:\n ";
SubExprBounds->dump(OS, Context);
}
}
void DumpInitializerBounds(raw_ostream &OS, VarDecl *D,
BoundsExpr *Target, BoundsExpr *B) {
OS << "\n";
D->dump(OS);
OS << "Declared Bounds:\n";
Target->dump(OS, Context);
OS << "Initializer Bounds:\n ";
B->dump(OS, Context);
}
void DumpExpression(raw_ostream &OS, Expr *E) {
OS << "\n";
E->dump(OS, Context);
}
void DumpCallArgumentBounds(raw_ostream &OS, BoundsExpr *Param,
Expr *Arg,
BoundsExpr *ParamBounds,
BoundsExpr *ArgBounds) {
OS << "\n";
if (Param) {
OS << "Original parameter bounds\n";
Param->dump(OS, Context);
}
if (Arg) {
OS << "Argument:\n";
Arg->dump(OS, Context);
}
if (ParamBounds) {
OS << "Parameter Bounds:\n";
ParamBounds->dump(OS, Context);
}
if (ArgBounds) {
OS << "Argument Bounds:\n ";
ArgBounds->dump(OS, Context);
}
}
void DumpCheckingState(raw_ostream &OS, Stmt *S, CheckingState &State) {
OS << "\nStatement S:\n";
S->dump(OS, Context);
OS << "Observed bounds context after checking S:\n";
DumpBoundsContext(OS, State.ObservedBounds);
OS << "Sets of equivalent expressions after checking S:\n";
if (State.EquivExprs.size() == 0)
OS << "{ }\n";
else {
OS << "{\n";
for (auto OuterList = State.EquivExprs.begin(); OuterList != State.EquivExprs.end(); ++OuterList) {
auto ExprList = *OuterList;
DumpExprsSet(OS, ExprList);
}
OS << "}\n";
}
OS << "Expressions that produce the same value as S:\n";
DumpExprsSet(OS, State.SameValue);
}
void DumpBoundsContext(raw_ostream &OS, BoundsContextTy &BoundsContext) {
if (BoundsContext.empty())
OS << "{ }\n";
else {
// The keys in an llvm::DenseMap are unordered. Create a set of
// abstract sets in the context sorted lexicographically in order
// to guarantee a deterministic output so that printing the bounds
// context can be tested.
std::vector<const AbstractSet *> OrderedSets;
for (auto const &Pair : BoundsContext)
OrderedSets.push_back(Pair.first);
llvm::sort(OrderedSets.begin(), OrderedSets.end(),
[] (const AbstractSet *A, const AbstractSet *B) {
return *(const_cast<AbstractSet *>(A)) < *(const_cast<AbstractSet *>(B));
});
OS << "{\n";
for (auto I = OrderedSets.begin(); I != OrderedSets.end(); ++I) {
const AbstractSet *A = *I;
auto It = BoundsContext.find(A);
if (It == BoundsContext.end())
continue;
OS << "LValue Expression:\n";
A->GetRepresentative()->dump(OS, Context);
OS << "Bounds:\n";
It->second->dump(OS, Context);
}
OS << "}\n";
}
}
void DumpExprsSet(raw_ostream &OS, ExprSetTy Exprs) {
if (Exprs.size() == 0)
OS << "{ }\n";
else {
OS << "{\n";
for (auto I = Exprs.begin(); I != Exprs.end(); ++I) {
Expr *E = *I;
E->dump(OS, Context);
}
OS << "}\n";
}
}
void DumpSynthesizedMemberAbstractSets(raw_ostream &OS,
AbstractSetSetTy AbstractSets) {
OS << "\nAbstractSets for member expressions:\n";
if (AbstractSets.size() == 0)
OS << "{ }\n";
else {
// The keys in an llvm::SmallPtrSet are unordered. Create a set of
// abstract sets sorted lexicographically in order to guarantee a
// deterministic output so that printing the synthesized abstract
// sets can be tested.
std::vector<const AbstractSet *> OrderedSets;
for (auto It : AbstractSets)
OrderedSets.push_back(It);
llvm::sort(OrderedSets.begin(), OrderedSets.end(),
[] (const AbstractSet *A, const AbstractSet *B) {
return *(const_cast<AbstractSet *>(A)) < *(const_cast<AbstractSet *>(B));
});
OS << "{\n";
for (auto It : OrderedSets) {
It->PrettyPrint(OS, Context);
OS << "\n";
}
OS << "}\n";
}
}
// Add bounds check to an lvalue expression, if it is an Array_ptr
// dereference. The caller has determined that the lvalue is being
// used in a way that requies a bounds check if the lvalue is an
// _Array_ptr or _Nt_array_ptr dereference. The lvalue uses are to read
// or write memory or as the base expression of a member reference.
//
// If the Array_ptr has unknown bounds, this is a compile-time error.
// Generate an error message and set the bounds to an invalid bounds
// expression.
enum class OperationKind {
Read, // just reads memory
Assign, // simple assignment to memory
Other // reads and writes memory, struct base check
};
bool AddBoundsCheck(Expr *E, OperationKind OpKind, CheckedScopeSpecifier CSS,
EquivExprSets *EquivExprs, BoundsExpr *LValueBounds) {
assert(E->isLValue());
bool NeedsBoundsCheck = false;
QualType PtrType;
if (Expr *Deref = S.GetArrayPtrDereference(E, PtrType)) {
NeedsBoundsCheck = true;
LValueBounds = S.CheckNonModifyingBounds(LValueBounds, E);
BoundsCheckKind Kind = BCK_Normal;
// Null-terminated array pointers have special semantics for
// bounds checks.
if (PtrType->isCheckedPointerNtArrayType()) {
if (OpKind == OperationKind::Read)
Kind = BCK_NullTermRead;
else if (OpKind == OperationKind::Assign)
Kind = BCK_NullTermWriteAssign;
// Otherwise, use the default range check for bounds.
}
if (LValueBounds->isUnknown()) {
S.Diag(E->getBeginLoc(), diag::err_expected_bounds) << E->getSourceRange();
LValueBounds = S.CreateInvalidBoundsExpr();
} else {
CheckBoundsAtMemoryAccess(Deref, LValueBounds, Kind, CSS, EquivExprs);
}
if (UnaryOperator *UO = dyn_cast<UnaryOperator>(Deref)) {
assert(!UO->hasBoundsExpr());
UO->setBoundsExpr(LValueBounds);
UO->setBoundsCheckKind(Kind);
} else if (ArraySubscriptExpr *AS = dyn_cast<ArraySubscriptExpr>(Deref)) {
assert(!AS->hasBoundsExpr());
AS->setBoundsExpr(LValueBounds);
AS->setBoundsCheckKind(Kind);
} else
llvm_unreachable("unexpected expression kind");
}
return NeedsBoundsCheck;
}
// Add bounds check to the base expression of a member reference, if the
// base expression is an Array_ptr dereference. Such base expressions
// always need bounds checks, even though their lvalues are only used for an
// address computation.
bool AddMemberBaseBoundsCheck(MemberExpr *E, CheckedScopeSpecifier CSS,
EquivExprSets *EquivExprs,
BoundsExpr *BaseLValueBounds,
BoundsExpr *BaseBounds) {
Expr *Base = E->getBase();
// E.F
if (!E->isArrow()) {
// The base expression only needs a bounds check if it is an lvalue.
if (Base->isLValue())
return AddBoundsCheck(Base, OperationKind::Other, CSS,
EquivExprs, BaseLValueBounds);
return false;
}
// E->F. This is equivalent to (*E).F.
if (Base->getType()->isCheckedPointerArrayType()) {
BoundsExpr *Bounds = S.CheckNonModifyingBounds(BaseBounds, Base);
if (Bounds->isUnknown()) {
S.Diag(Base->getBeginLoc(), diag::err_expected_bounds) << Base->getSourceRange();
Bounds = S.CreateInvalidBoundsExpr();
} else {
CheckBoundsAtMemoryAccess(E, Bounds, BCK_Normal, CSS, EquivExprs);
}
E->setBoundsExpr(Bounds);
return true;
}
return false;
}
// The result of trying to prove a statement about bounds declarations.
// The proof system is incomplete, so there are will be statements that
// cannot be proved true or false. That's why "maybe" is a result.
enum class ProofResult {
True, // Definitely provable.
False, // Definitely false (an error)
Maybe // We're not sure yet.
};
// The kind of statement that we are trying to prove true or false.
//
// This enum is used in generating diagnostic messages. If you change the order,
// update the messages in DiagnosticSemaKinds.td used in
// ExplainProofFailure
enum class ProofStmtKind : unsigned {
BoundsDeclaration,
StaticBoundsCast,
ReturnStmt,
MemoryAccess,
MemberArrowBase
};
// ProofFailure: codes that explain why a statement is false. This is a
// bitmask because there may be multiple reasons why a statement false.
enum class ProofFailure : unsigned {
None = 0x0,
LowerBound = 0x1, // The destination lower bound is below the source lower bound.
UpperBound = 0x2, // The destination upper bound is above the source upper bound.
SrcEmpty = 0x4, // The source bounds are empty (LB == UB)
SrcInvalid = 0x8, // The source bounds are invalid (LB > UB).
DstEmpty = 0x10, // The destination bounds are empty (LB == UB).
DstInvalid = 0x20, // The destination bounds are invalid (LB > UB).
Width = 0x40, // The source bounds are narrower than the destination bounds.
PartialOverlap = 0x80, // There was only partial overlap of the destination bounds with
// the source bounds.
HasFreeVariables = 0x100 // Source or destination has free variables.
};
enum class DiagnosticNameForTarget {
Destination = 0x0,
Target = 0x1
};
enum class DiagnosticBoundsName {
Declared,
Inferred
};
enum class DiagnosticBoundsComponent {
Lower,
Upper,
Base
};
// Combine proof failure codes.
static constexpr ProofFailure CombineFailures(ProofFailure A,
ProofFailure B) {