-
Notifications
You must be signed in to change notification settings - Fork 12k
/
AnalysisBasedWarnings.cpp
2878 lines (2504 loc) · 104 KB
/
AnalysisBasedWarnings.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//=== AnalysisBasedWarnings.cpp - Sema warnings based on libAnalysis ------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file defines analysis_warnings::[Policy,Executor].
// Together they are used by Sema to issue warnings based on inexpensive
// static analysis algorithms in libAnalysis.
//
//===----------------------------------------------------------------------===//
#include "clang/Sema/AnalysisBasedWarnings.h"
#include "clang/AST/Decl.h"
#include "clang/AST/DeclCXX.h"
#include "clang/AST/DeclObjC.h"
#include "clang/AST/EvaluatedExprVisitor.h"
#include "clang/AST/Expr.h"
#include "clang/AST/ExprCXX.h"
#include "clang/AST/ExprObjC.h"
#include "clang/AST/OperationKinds.h"
#include "clang/AST/ParentMap.h"
#include "clang/AST/RecursiveASTVisitor.h"
#include "clang/AST/StmtCXX.h"
#include "clang/AST/StmtObjC.h"
#include "clang/AST/StmtVisitor.h"
#include "clang/AST/Type.h"
#include "clang/Analysis/Analyses/CFGReachabilityAnalysis.h"
#include "clang/Analysis/Analyses/CalledOnceCheck.h"
#include "clang/Analysis/Analyses/Consumed.h"
#include "clang/Analysis/Analyses/ReachableCode.h"
#include "clang/Analysis/Analyses/ThreadSafety.h"
#include "clang/Analysis/Analyses/UninitializedValues.h"
#include "clang/Analysis/Analyses/UnsafeBufferUsage.h"
#include "clang/Analysis/AnalysisDeclContext.h"
#include "clang/Analysis/CFG.h"
#include "clang/Analysis/CFGStmtMap.h"
#include "clang/Basic/Diagnostic.h"
#include "clang/Basic/DiagnosticSema.h"
#include "clang/Basic/SourceLocation.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/Sema/ScopeInfo.h"
#include "clang/Sema/SemaInternal.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/BitVector.h"
#include "llvm/ADT/MapVector.h"
#include "llvm/ADT/STLFunctionalExtras.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/Casting.h"
#include <algorithm>
#include <deque>
#include <iterator>
#include <optional>
using namespace clang;
//===----------------------------------------------------------------------===//
// Unreachable code analysis.
//===----------------------------------------------------------------------===//
namespace {
class UnreachableCodeHandler : public reachable_code::Callback {
Sema &S;
SourceRange PreviousSilenceableCondVal;
public:
UnreachableCodeHandler(Sema &s) : S(s) {}
void HandleUnreachable(reachable_code::UnreachableKind UK, SourceLocation L,
SourceRange SilenceableCondVal, SourceRange R1,
SourceRange R2, bool HasFallThroughAttr) override {
// If the diagnosed code is `[[fallthrough]];` and
// `-Wunreachable-code-fallthrough` is enabled, suppress `code will never
// be executed` warning to avoid generating diagnostic twice
if (HasFallThroughAttr &&
!S.getDiagnostics().isIgnored(diag::warn_unreachable_fallthrough_attr,
SourceLocation()))
return;
// Avoid reporting multiple unreachable code diagnostics that are
// triggered by the same conditional value.
if (PreviousSilenceableCondVal.isValid() &&
SilenceableCondVal.isValid() &&
PreviousSilenceableCondVal == SilenceableCondVal)
return;
PreviousSilenceableCondVal = SilenceableCondVal;
unsigned diag = diag::warn_unreachable;
switch (UK) {
case reachable_code::UK_Break:
diag = diag::warn_unreachable_break;
break;
case reachable_code::UK_Return:
diag = diag::warn_unreachable_return;
break;
case reachable_code::UK_Loop_Increment:
diag = diag::warn_unreachable_loop_increment;
break;
case reachable_code::UK_Other:
break;
}
S.Diag(L, diag) << R1 << R2;
SourceLocation Open = SilenceableCondVal.getBegin();
if (Open.isValid()) {
SourceLocation Close = SilenceableCondVal.getEnd();
Close = S.getLocForEndOfToken(Close);
if (Close.isValid()) {
S.Diag(Open, diag::note_unreachable_silence)
<< FixItHint::CreateInsertion(Open, "/* DISABLES CODE */ (")
<< FixItHint::CreateInsertion(Close, ")");
}
}
}
};
} // anonymous namespace
/// CheckUnreachable - Check for unreachable code.
static void CheckUnreachable(Sema &S, AnalysisDeclContext &AC) {
// As a heuristic prune all diagnostics not in the main file. Currently
// the majority of warnings in headers are false positives. These
// are largely caused by configuration state, e.g. preprocessor
// defined code, etc.
//
// Note that this is also a performance optimization. Analyzing
// headers many times can be expensive.
if (!S.getSourceManager().isInMainFile(AC.getDecl()->getBeginLoc()))
return;
UnreachableCodeHandler UC(S);
reachable_code::FindUnreachableCode(AC, S.getPreprocessor(), UC);
}
namespace {
/// Warn on logical operator errors in CFGBuilder
class LogicalErrorHandler : public CFGCallback {
Sema &S;
public:
LogicalErrorHandler(Sema &S) : S(S) {}
static bool HasMacroID(const Expr *E) {
if (E->getExprLoc().isMacroID())
return true;
// Recurse to children.
for (const Stmt *SubStmt : E->children())
if (const Expr *SubExpr = dyn_cast_or_null<Expr>(SubStmt))
if (HasMacroID(SubExpr))
return true;
return false;
}
void logicAlwaysTrue(const BinaryOperator *B, bool isAlwaysTrue) override {
if (HasMacroID(B))
return;
unsigned DiagID = isAlwaysTrue
? diag::warn_tautological_negation_or_compare
: diag::warn_tautological_negation_and_compare;
SourceRange DiagRange = B->getSourceRange();
S.Diag(B->getExprLoc(), DiagID) << DiagRange;
}
void compareAlwaysTrue(const BinaryOperator *B, bool isAlwaysTrue) override {
if (HasMacroID(B))
return;
SourceRange DiagRange = B->getSourceRange();
S.Diag(B->getExprLoc(), diag::warn_tautological_overlap_comparison)
<< DiagRange << isAlwaysTrue;
}
void compareBitwiseEquality(const BinaryOperator *B,
bool isAlwaysTrue) override {
if (HasMacroID(B))
return;
SourceRange DiagRange = B->getSourceRange();
S.Diag(B->getExprLoc(), diag::warn_comparison_bitwise_always)
<< DiagRange << isAlwaysTrue;
}
void compareBitwiseOr(const BinaryOperator *B) override {
if (HasMacroID(B))
return;
SourceRange DiagRange = B->getSourceRange();
S.Diag(B->getExprLoc(), diag::warn_comparison_bitwise_or) << DiagRange;
}
static bool hasActiveDiagnostics(DiagnosticsEngine &Diags,
SourceLocation Loc) {
return !Diags.isIgnored(diag::warn_tautological_overlap_comparison, Loc) ||
!Diags.isIgnored(diag::warn_comparison_bitwise_or, Loc) ||
!Diags.isIgnored(diag::warn_tautological_negation_and_compare, Loc);
}
};
} // anonymous namespace
//===----------------------------------------------------------------------===//
// Check for infinite self-recursion in functions
//===----------------------------------------------------------------------===//
// Returns true if the function is called anywhere within the CFGBlock.
// For member functions, the additional condition of being call from the
// this pointer is required.
static bool hasRecursiveCallInPath(const FunctionDecl *FD, CFGBlock &Block) {
// Process all the Stmt's in this block to find any calls to FD.
for (const auto &B : Block) {
if (B.getKind() != CFGElement::Statement)
continue;
const CallExpr *CE = dyn_cast<CallExpr>(B.getAs<CFGStmt>()->getStmt());
if (!CE || !CE->getCalleeDecl() ||
CE->getCalleeDecl()->getCanonicalDecl() != FD)
continue;
// Skip function calls which are qualified with a templated class.
if (const DeclRefExpr *DRE =
dyn_cast<DeclRefExpr>(CE->getCallee()->IgnoreParenImpCasts())) {
if (NestedNameSpecifier *NNS = DRE->getQualifier()) {
if (NNS->getKind() == NestedNameSpecifier::TypeSpec &&
isa<TemplateSpecializationType>(NNS->getAsType())) {
continue;
}
}
}
const CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(CE);
if (!MCE || isa<CXXThisExpr>(MCE->getImplicitObjectArgument()) ||
!MCE->getMethodDecl()->isVirtual())
return true;
}
return false;
}
// Returns true if every path from the entry block passes through a call to FD.
static bool checkForRecursiveFunctionCall(const FunctionDecl *FD, CFG *cfg) {
llvm::SmallPtrSet<CFGBlock *, 16> Visited;
llvm::SmallVector<CFGBlock *, 16> WorkList;
// Keep track of whether we found at least one recursive path.
bool foundRecursion = false;
const unsigned ExitID = cfg->getExit().getBlockID();
// Seed the work list with the entry block.
WorkList.push_back(&cfg->getEntry());
while (!WorkList.empty()) {
CFGBlock *Block = WorkList.pop_back_val();
for (auto I = Block->succ_begin(), E = Block->succ_end(); I != E; ++I) {
if (CFGBlock *SuccBlock = *I) {
if (!Visited.insert(SuccBlock).second)
continue;
// Found a path to the exit node without a recursive call.
if (ExitID == SuccBlock->getBlockID())
return false;
// If the successor block contains a recursive call, end analysis there.
if (hasRecursiveCallInPath(FD, *SuccBlock)) {
foundRecursion = true;
continue;
}
WorkList.push_back(SuccBlock);
}
}
}
return foundRecursion;
}
static void checkRecursiveFunction(Sema &S, const FunctionDecl *FD,
const Stmt *Body, AnalysisDeclContext &AC) {
FD = FD->getCanonicalDecl();
// Only run on non-templated functions and non-templated members of
// templated classes.
if (FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate &&
FD->getTemplatedKind() != FunctionDecl::TK_MemberSpecialization)
return;
CFG *cfg = AC.getCFG();
if (!cfg) return;
// If the exit block is unreachable, skip processing the function.
if (cfg->getExit().pred_empty())
return;
// Emit diagnostic if a recursive function call is detected for all paths.
if (checkForRecursiveFunctionCall(FD, cfg))
S.Diag(Body->getBeginLoc(), diag::warn_infinite_recursive_function);
}
//===----------------------------------------------------------------------===//
// Check for throw in a non-throwing function.
//===----------------------------------------------------------------------===//
/// Determine whether an exception thrown by E, unwinding from ThrowBlock,
/// can reach ExitBlock.
static bool throwEscapes(Sema &S, const CXXThrowExpr *E, CFGBlock &ThrowBlock,
CFG *Body) {
SmallVector<CFGBlock *, 16> Stack;
llvm::BitVector Queued(Body->getNumBlockIDs());
Stack.push_back(&ThrowBlock);
Queued[ThrowBlock.getBlockID()] = true;
while (!Stack.empty()) {
CFGBlock &UnwindBlock = *Stack.back();
Stack.pop_back();
for (auto &Succ : UnwindBlock.succs()) {
if (!Succ.isReachable() || Queued[Succ->getBlockID()])
continue;
if (Succ->getBlockID() == Body->getExit().getBlockID())
return true;
if (auto *Catch =
dyn_cast_or_null<CXXCatchStmt>(Succ->getLabel())) {
QualType Caught = Catch->getCaughtType();
if (Caught.isNull() || // catch (...) catches everything
!E->getSubExpr() || // throw; is considered cuaght by any handler
S.handlerCanCatch(Caught, E->getSubExpr()->getType()))
// Exception doesn't escape via this path.
break;
} else {
Stack.push_back(Succ);
Queued[Succ->getBlockID()] = true;
}
}
}
return false;
}
static void visitReachableThrows(
CFG *BodyCFG,
llvm::function_ref<void(const CXXThrowExpr *, CFGBlock &)> Visit) {
llvm::BitVector Reachable(BodyCFG->getNumBlockIDs());
clang::reachable_code::ScanReachableFromBlock(&BodyCFG->getEntry(), Reachable);
for (CFGBlock *B : *BodyCFG) {
if (!Reachable[B->getBlockID()])
continue;
for (CFGElement &E : *B) {
std::optional<CFGStmt> S = E.getAs<CFGStmt>();
if (!S)
continue;
if (auto *Throw = dyn_cast<CXXThrowExpr>(S->getStmt()))
Visit(Throw, *B);
}
}
}
static void EmitDiagForCXXThrowInNonThrowingFunc(Sema &S, SourceLocation OpLoc,
const FunctionDecl *FD) {
if (!S.getSourceManager().isInSystemHeader(OpLoc) &&
FD->getTypeSourceInfo()) {
S.Diag(OpLoc, diag::warn_throw_in_noexcept_func) << FD;
if (S.getLangOpts().CPlusPlus11 &&
(isa<CXXDestructorDecl>(FD) ||
FD->getDeclName().getCXXOverloadedOperator() == OO_Delete ||
FD->getDeclName().getCXXOverloadedOperator() == OO_Array_Delete)) {
if (const auto *Ty = FD->getTypeSourceInfo()->getType()->
getAs<FunctionProtoType>())
S.Diag(FD->getLocation(), diag::note_throw_in_dtor)
<< !isa<CXXDestructorDecl>(FD) << !Ty->hasExceptionSpec()
<< FD->getExceptionSpecSourceRange();
} else
S.Diag(FD->getLocation(), diag::note_throw_in_function)
<< FD->getExceptionSpecSourceRange();
}
}
static void checkThrowInNonThrowingFunc(Sema &S, const FunctionDecl *FD,
AnalysisDeclContext &AC) {
CFG *BodyCFG = AC.getCFG();
if (!BodyCFG)
return;
if (BodyCFG->getExit().pred_empty())
return;
visitReachableThrows(BodyCFG, [&](const CXXThrowExpr *Throw, CFGBlock &Block) {
if (throwEscapes(S, Throw, Block, BodyCFG))
EmitDiagForCXXThrowInNonThrowingFunc(S, Throw->getThrowLoc(), FD);
});
}
static bool isNoexcept(const FunctionDecl *FD) {
const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
if (FPT->isNothrow() || FD->hasAttr<NoThrowAttr>())
return true;
return false;
}
//===----------------------------------------------------------------------===//
// Check for missing return value.
//===----------------------------------------------------------------------===//
enum ControlFlowKind {
UnknownFallThrough,
NeverFallThrough,
MaybeFallThrough,
AlwaysFallThrough,
NeverFallThroughOrReturn
};
/// CheckFallThrough - Check that we don't fall off the end of a
/// Statement that should return a value.
///
/// \returns AlwaysFallThrough iff we always fall off the end of the statement,
/// MaybeFallThrough iff we might or might not fall off the end,
/// NeverFallThroughOrReturn iff we never fall off the end of the statement or
/// return. We assume NeverFallThrough iff we never fall off the end of the
/// statement but we may return. We assume that functions not marked noreturn
/// will return.
static ControlFlowKind CheckFallThrough(AnalysisDeclContext &AC) {
CFG *cfg = AC.getCFG();
if (!cfg) return UnknownFallThrough;
// The CFG leaves in dead things, and we don't want the dead code paths to
// confuse us, so we mark all live things first.
llvm::BitVector live(cfg->getNumBlockIDs());
unsigned count = reachable_code::ScanReachableFromBlock(&cfg->getEntry(),
live);
bool AddEHEdges = AC.getAddEHEdges();
if (!AddEHEdges && count != cfg->getNumBlockIDs())
// When there are things remaining dead, and we didn't add EH edges
// from CallExprs to the catch clauses, we have to go back and
// mark them as live.
for (const auto *B : *cfg) {
if (!live[B->getBlockID()]) {
if (B->pred_begin() == B->pred_end()) {
const Stmt *Term = B->getTerminatorStmt();
if (isa_and_nonnull<CXXTryStmt>(Term))
// When not adding EH edges from calls, catch clauses
// can otherwise seem dead. Avoid noting them as dead.
count += reachable_code::ScanReachableFromBlock(B, live);
continue;
}
}
}
// Now we know what is live, we check the live precessors of the exit block
// and look for fall through paths, being careful to ignore normal returns,
// and exceptional paths.
bool HasLiveReturn = false;
bool HasFakeEdge = false;
bool HasPlainEdge = false;
bool HasAbnormalEdge = false;
// Ignore default cases that aren't likely to be reachable because all
// enums in a switch(X) have explicit case statements.
CFGBlock::FilterOptions FO;
FO.IgnoreDefaultsWithCoveredEnums = 1;
for (CFGBlock::filtered_pred_iterator I =
cfg->getExit().filtered_pred_start_end(FO);
I.hasMore(); ++I) {
const CFGBlock &B = **I;
if (!live[B.getBlockID()])
continue;
// Skip blocks which contain an element marked as no-return. They don't
// represent actually viable edges into the exit block, so mark them as
// abnormal.
if (B.hasNoReturnElement()) {
HasAbnormalEdge = true;
continue;
}
// Destructors can appear after the 'return' in the CFG. This is
// normal. We need to look pass the destructors for the return
// statement (if it exists).
CFGBlock::const_reverse_iterator ri = B.rbegin(), re = B.rend();
for ( ; ri != re ; ++ri)
if (ri->getAs<CFGStmt>())
break;
// No more CFGElements in the block?
if (ri == re) {
const Stmt *Term = B.getTerminatorStmt();
if (Term && (isa<CXXTryStmt>(Term) || isa<ObjCAtTryStmt>(Term))) {
HasAbnormalEdge = true;
continue;
}
// A labeled empty statement, or the entry block...
HasPlainEdge = true;
continue;
}
CFGStmt CS = ri->castAs<CFGStmt>();
const Stmt *S = CS.getStmt();
if (isa<ReturnStmt>(S) || isa<CoreturnStmt>(S)) {
HasLiveReturn = true;
continue;
}
if (isa<ObjCAtThrowStmt>(S)) {
HasFakeEdge = true;
continue;
}
if (isa<CXXThrowExpr>(S)) {
HasFakeEdge = true;
continue;
}
if (isa<MSAsmStmt>(S)) {
// TODO: Verify this is correct.
HasFakeEdge = true;
HasLiveReturn = true;
continue;
}
if (isa<CXXTryStmt>(S)) {
HasAbnormalEdge = true;
continue;
}
if (!llvm::is_contained(B.succs(), &cfg->getExit())) {
HasAbnormalEdge = true;
continue;
}
HasPlainEdge = true;
}
if (!HasPlainEdge) {
if (HasLiveReturn)
return NeverFallThrough;
return NeverFallThroughOrReturn;
}
if (HasAbnormalEdge || HasFakeEdge || HasLiveReturn)
return MaybeFallThrough;
// This says AlwaysFallThrough for calls to functions that are not marked
// noreturn, that don't return. If people would like this warning to be more
// accurate, such functions should be marked as noreturn.
return AlwaysFallThrough;
}
namespace {
struct CheckFallThroughDiagnostics {
unsigned diag_MaybeFallThrough_HasNoReturn;
unsigned diag_MaybeFallThrough_ReturnsNonVoid;
unsigned diag_AlwaysFallThrough_HasNoReturn;
unsigned diag_AlwaysFallThrough_ReturnsNonVoid;
unsigned diag_NeverFallThroughOrReturn;
enum { Function, Block, Lambda, Coroutine } funMode;
SourceLocation FuncLoc;
static CheckFallThroughDiagnostics MakeForFunction(const Decl *Func) {
CheckFallThroughDiagnostics D;
D.FuncLoc = Func->getLocation();
D.diag_MaybeFallThrough_HasNoReturn =
diag::warn_falloff_noreturn_function;
D.diag_MaybeFallThrough_ReturnsNonVoid =
diag::warn_maybe_falloff_nonvoid_function;
D.diag_AlwaysFallThrough_HasNoReturn =
diag::warn_falloff_noreturn_function;
D.diag_AlwaysFallThrough_ReturnsNonVoid =
diag::warn_falloff_nonvoid_function;
// Don't suggest that virtual functions be marked "noreturn", since they
// might be overridden by non-noreturn functions.
bool isVirtualMethod = false;
if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Func))
isVirtualMethod = Method->isVirtual();
// Don't suggest that template instantiations be marked "noreturn"
bool isTemplateInstantiation = false;
if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(Func))
isTemplateInstantiation = Function->isTemplateInstantiation();
if (!isVirtualMethod && !isTemplateInstantiation)
D.diag_NeverFallThroughOrReturn =
diag::warn_suggest_noreturn_function;
else
D.diag_NeverFallThroughOrReturn = 0;
D.funMode = Function;
return D;
}
static CheckFallThroughDiagnostics MakeForCoroutine(const Decl *Func) {
CheckFallThroughDiagnostics D;
D.FuncLoc = Func->getLocation();
D.diag_MaybeFallThrough_HasNoReturn = 0;
D.diag_MaybeFallThrough_ReturnsNonVoid =
diag::warn_maybe_falloff_nonvoid_coroutine;
D.diag_AlwaysFallThrough_HasNoReturn = 0;
D.diag_AlwaysFallThrough_ReturnsNonVoid =
diag::warn_falloff_nonvoid_coroutine;
D.diag_NeverFallThroughOrReturn = 0;
D.funMode = Coroutine;
return D;
}
static CheckFallThroughDiagnostics MakeForBlock() {
CheckFallThroughDiagnostics D;
D.diag_MaybeFallThrough_HasNoReturn =
diag::err_noreturn_block_has_return_expr;
D.diag_MaybeFallThrough_ReturnsNonVoid =
diag::err_maybe_falloff_nonvoid_block;
D.diag_AlwaysFallThrough_HasNoReturn =
diag::err_noreturn_block_has_return_expr;
D.diag_AlwaysFallThrough_ReturnsNonVoid =
diag::err_falloff_nonvoid_block;
D.diag_NeverFallThroughOrReturn = 0;
D.funMode = Block;
return D;
}
static CheckFallThroughDiagnostics MakeForLambda() {
CheckFallThroughDiagnostics D;
D.diag_MaybeFallThrough_HasNoReturn =
diag::err_noreturn_lambda_has_return_expr;
D.diag_MaybeFallThrough_ReturnsNonVoid =
diag::warn_maybe_falloff_nonvoid_lambda;
D.diag_AlwaysFallThrough_HasNoReturn =
diag::err_noreturn_lambda_has_return_expr;
D.diag_AlwaysFallThrough_ReturnsNonVoid =
diag::warn_falloff_nonvoid_lambda;
D.diag_NeverFallThroughOrReturn = 0;
D.funMode = Lambda;
return D;
}
bool checkDiagnostics(DiagnosticsEngine &D, bool ReturnsVoid,
bool HasNoReturn) const {
if (funMode == Function) {
return (ReturnsVoid ||
D.isIgnored(diag::warn_maybe_falloff_nonvoid_function,
FuncLoc)) &&
(!HasNoReturn ||
D.isIgnored(diag::warn_noreturn_function_has_return_expr,
FuncLoc)) &&
(!ReturnsVoid ||
D.isIgnored(diag::warn_suggest_noreturn_block, FuncLoc));
}
if (funMode == Coroutine) {
return (ReturnsVoid ||
D.isIgnored(diag::warn_maybe_falloff_nonvoid_function, FuncLoc) ||
D.isIgnored(diag::warn_maybe_falloff_nonvoid_coroutine,
FuncLoc)) &&
(!HasNoReturn);
}
// For blocks / lambdas.
return ReturnsVoid && !HasNoReturn;
}
};
} // anonymous namespace
/// CheckFallThroughForBody - Check that we don't fall off the end of a
/// function that should return a value. Check that we don't fall off the end
/// of a noreturn function. We assume that functions and blocks not marked
/// noreturn will return.
static void CheckFallThroughForBody(Sema &S, const Decl *D, const Stmt *Body,
QualType BlockType,
const CheckFallThroughDiagnostics &CD,
AnalysisDeclContext &AC,
sema::FunctionScopeInfo *FSI) {
bool ReturnsVoid = false;
bool HasNoReturn = false;
bool IsCoroutine = FSI->isCoroutine();
if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
if (const auto *CBody = dyn_cast<CoroutineBodyStmt>(Body))
ReturnsVoid = CBody->getFallthroughHandler() != nullptr;
else
ReturnsVoid = FD->getReturnType()->isVoidType();
HasNoReturn = FD->isNoReturn();
}
else if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
ReturnsVoid = MD->getReturnType()->isVoidType();
HasNoReturn = MD->hasAttr<NoReturnAttr>();
}
else if (isa<BlockDecl>(D)) {
if (const FunctionType *FT =
BlockType->getPointeeType()->getAs<FunctionType>()) {
if (FT->getReturnType()->isVoidType())
ReturnsVoid = true;
if (FT->getNoReturnAttr())
HasNoReturn = true;
}
}
DiagnosticsEngine &Diags = S.getDiagnostics();
// Short circuit for compilation speed.
if (CD.checkDiagnostics(Diags, ReturnsVoid, HasNoReturn))
return;
SourceLocation LBrace = Body->getBeginLoc(), RBrace = Body->getEndLoc();
auto EmitDiag = [&](SourceLocation Loc, unsigned DiagID) {
if (IsCoroutine)
S.Diag(Loc, DiagID) << FSI->CoroutinePromise->getType();
else
S.Diag(Loc, DiagID);
};
// cpu_dispatch functions permit empty function bodies for ICC compatibility.
if (D->getAsFunction() && D->getAsFunction()->isCPUDispatchMultiVersion())
return;
// Either in a function body compound statement, or a function-try-block.
switch (CheckFallThrough(AC)) {
case UnknownFallThrough:
break;
case MaybeFallThrough:
if (HasNoReturn)
EmitDiag(RBrace, CD.diag_MaybeFallThrough_HasNoReturn);
else if (!ReturnsVoid)
EmitDiag(RBrace, CD.diag_MaybeFallThrough_ReturnsNonVoid);
break;
case AlwaysFallThrough:
if (HasNoReturn)
EmitDiag(RBrace, CD.diag_AlwaysFallThrough_HasNoReturn);
else if (!ReturnsVoid)
EmitDiag(RBrace, CD.diag_AlwaysFallThrough_ReturnsNonVoid);
break;
case NeverFallThroughOrReturn:
if (ReturnsVoid && !HasNoReturn && CD.diag_NeverFallThroughOrReturn) {
if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
S.Diag(LBrace, CD.diag_NeverFallThroughOrReturn) << 0 << FD;
} else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
S.Diag(LBrace, CD.diag_NeverFallThroughOrReturn) << 1 << MD;
} else {
S.Diag(LBrace, CD.diag_NeverFallThroughOrReturn);
}
}
break;
case NeverFallThrough:
break;
}
}
//===----------------------------------------------------------------------===//
// -Wuninitialized
//===----------------------------------------------------------------------===//
namespace {
/// ContainsReference - A visitor class to search for references to
/// a particular declaration (the needle) within any evaluated component of an
/// expression (recursively).
class ContainsReference : public ConstEvaluatedExprVisitor<ContainsReference> {
bool FoundReference;
const DeclRefExpr *Needle;
public:
typedef ConstEvaluatedExprVisitor<ContainsReference> Inherited;
ContainsReference(ASTContext &Context, const DeclRefExpr *Needle)
: Inherited(Context), FoundReference(false), Needle(Needle) {}
void VisitExpr(const Expr *E) {
// Stop evaluating if we already have a reference.
if (FoundReference)
return;
Inherited::VisitExpr(E);
}
void VisitDeclRefExpr(const DeclRefExpr *E) {
if (E == Needle)
FoundReference = true;
else
Inherited::VisitDeclRefExpr(E);
}
bool doesContainReference() const { return FoundReference; }
};
} // anonymous namespace
static bool SuggestInitializationFixit(Sema &S, const VarDecl *VD) {
QualType VariableTy = VD->getType().getCanonicalType();
if (VariableTy->isBlockPointerType() &&
!VD->hasAttr<BlocksAttr>()) {
S.Diag(VD->getLocation(), diag::note_block_var_fixit_add_initialization)
<< VD->getDeclName()
<< FixItHint::CreateInsertion(VD->getLocation(), "__block ");
return true;
}
// Don't issue a fixit if there is already an initializer.
if (VD->getInit())
return false;
// Don't suggest a fixit inside macros.
if (VD->getEndLoc().isMacroID())
return false;
SourceLocation Loc = S.getLocForEndOfToken(VD->getEndLoc());
// Suggest possible initialization (if any).
std::string Init = S.getFixItZeroInitializerForType(VariableTy, Loc);
if (Init.empty())
return false;
S.Diag(Loc, diag::note_var_fixit_add_initialization) << VD->getDeclName()
<< FixItHint::CreateInsertion(Loc, Init);
return true;
}
/// Create a fixit to remove an if-like statement, on the assumption that its
/// condition is CondVal.
static void CreateIfFixit(Sema &S, const Stmt *If, const Stmt *Then,
const Stmt *Else, bool CondVal,
FixItHint &Fixit1, FixItHint &Fixit2) {
if (CondVal) {
// If condition is always true, remove all but the 'then'.
Fixit1 = FixItHint::CreateRemoval(
CharSourceRange::getCharRange(If->getBeginLoc(), Then->getBeginLoc()));
if (Else) {
SourceLocation ElseKwLoc = S.getLocForEndOfToken(Then->getEndLoc());
Fixit2 =
FixItHint::CreateRemoval(SourceRange(ElseKwLoc, Else->getEndLoc()));
}
} else {
// If condition is always false, remove all but the 'else'.
if (Else)
Fixit1 = FixItHint::CreateRemoval(CharSourceRange::getCharRange(
If->getBeginLoc(), Else->getBeginLoc()));
else
Fixit1 = FixItHint::CreateRemoval(If->getSourceRange());
}
}
/// DiagUninitUse -- Helper function to produce a diagnostic for an
/// uninitialized use of a variable.
static void DiagUninitUse(Sema &S, const VarDecl *VD, const UninitUse &Use,
bool IsCapturedByBlock) {
bool Diagnosed = false;
switch (Use.getKind()) {
case UninitUse::Always:
S.Diag(Use.getUser()->getBeginLoc(), diag::warn_uninit_var)
<< VD->getDeclName() << IsCapturedByBlock
<< Use.getUser()->getSourceRange();
return;
case UninitUse::AfterDecl:
case UninitUse::AfterCall:
S.Diag(VD->getLocation(), diag::warn_sometimes_uninit_var)
<< VD->getDeclName() << IsCapturedByBlock
<< (Use.getKind() == UninitUse::AfterDecl ? 4 : 5)
<< const_cast<DeclContext*>(VD->getLexicalDeclContext())
<< VD->getSourceRange();
S.Diag(Use.getUser()->getBeginLoc(), diag::note_uninit_var_use)
<< IsCapturedByBlock << Use.getUser()->getSourceRange();
return;
case UninitUse::Maybe:
case UninitUse::Sometimes:
// Carry on to report sometimes-uninitialized branches, if possible,
// or a 'may be used uninitialized' diagnostic otherwise.
break;
}
// Diagnose each branch which leads to a sometimes-uninitialized use.
for (UninitUse::branch_iterator I = Use.branch_begin(), E = Use.branch_end();
I != E; ++I) {
assert(Use.getKind() == UninitUse::Sometimes);
const Expr *User = Use.getUser();
const Stmt *Term = I->Terminator;
// Information used when building the diagnostic.
unsigned DiagKind;
StringRef Str;
SourceRange Range;
// FixIts to suppress the diagnostic by removing the dead condition.
// For all binary terminators, branch 0 is taken if the condition is true,
// and branch 1 is taken if the condition is false.
int RemoveDiagKind = -1;
const char *FixitStr =
S.getLangOpts().CPlusPlus ? (I->Output ? "true" : "false")
: (I->Output ? "1" : "0");
FixItHint Fixit1, Fixit2;
switch (Term ? Term->getStmtClass() : Stmt::DeclStmtClass) {
default:
// Don't know how to report this. Just fall back to 'may be used
// uninitialized'. FIXME: Can this happen?
continue;
// "condition is true / condition is false".
case Stmt::IfStmtClass: {
const IfStmt *IS = cast<IfStmt>(Term);
DiagKind = 0;
Str = "if";
Range = IS->getCond()->getSourceRange();
RemoveDiagKind = 0;
CreateIfFixit(S, IS, IS->getThen(), IS->getElse(),
I->Output, Fixit1, Fixit2);
break;
}
case Stmt::ConditionalOperatorClass: {
const ConditionalOperator *CO = cast<ConditionalOperator>(Term);
DiagKind = 0;
Str = "?:";
Range = CO->getCond()->getSourceRange();
RemoveDiagKind = 0;
CreateIfFixit(S, CO, CO->getTrueExpr(), CO->getFalseExpr(),
I->Output, Fixit1, Fixit2);
break;
}
case Stmt::BinaryOperatorClass: {
const BinaryOperator *BO = cast<BinaryOperator>(Term);
if (!BO->isLogicalOp())
continue;
DiagKind = 0;
Str = BO->getOpcodeStr();
Range = BO->getLHS()->getSourceRange();
RemoveDiagKind = 0;
if ((BO->getOpcode() == BO_LAnd && I->Output) ||
(BO->getOpcode() == BO_LOr && !I->Output))
// true && y -> y, false || y -> y.
Fixit1 = FixItHint::CreateRemoval(
SourceRange(BO->getBeginLoc(), BO->getOperatorLoc()));
else
// false && y -> false, true || y -> true.
Fixit1 = FixItHint::CreateReplacement(BO->getSourceRange(), FixitStr);
break;
}
// "loop is entered / loop is exited".
case Stmt::WhileStmtClass:
DiagKind = 1;
Str = "while";
Range = cast<WhileStmt>(Term)->getCond()->getSourceRange();
RemoveDiagKind = 1;
Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
break;
case Stmt::ForStmtClass:
DiagKind = 1;
Str = "for";
Range = cast<ForStmt>(Term)->getCond()->getSourceRange();
RemoveDiagKind = 1;
if (I->Output)
Fixit1 = FixItHint::CreateRemoval(Range);
else
Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
break;
case Stmt::CXXForRangeStmtClass:
if (I->Output == 1) {
// The use occurs if a range-based for loop's body never executes.
// That may be impossible, and there's no syntactic fix for this,
// so treat it as a 'may be uninitialized' case.
continue;
}
DiagKind = 1;
Str = "for";
Range = cast<CXXForRangeStmt>(Term)->getRangeInit()->getSourceRange();
break;
// "condition is true / loop is exited".
case Stmt::DoStmtClass:
DiagKind = 2;
Str = "do";
Range = cast<DoStmt>(Term)->getCond()->getSourceRange();
RemoveDiagKind = 1;
Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
break;
// "switch case is taken".
case Stmt::CaseStmtClass:
DiagKind = 3;
Str = "case";
Range = cast<CaseStmt>(Term)->getLHS()->getSourceRange();
break;
case Stmt::DefaultStmtClass:
DiagKind = 3;
Str = "default";
Range = cast<DefaultStmt>(Term)->getDefaultLoc();
break;
}
S.Diag(Range.getBegin(), diag::warn_sometimes_uninit_var)
<< VD->getDeclName() << IsCapturedByBlock << DiagKind
<< Str << I->Output << Range;
S.Diag(User->getBeginLoc(), diag::note_uninit_var_use)
<< IsCapturedByBlock << User->getSourceRange();
if (RemoveDiagKind != -1)
S.Diag(Fixit1.RemoveRange.getBegin(), diag::note_uninit_fixit_remove_cond)
<< RemoveDiagKind << Str << I->Output << Fixit1 << Fixit2;
Diagnosed = true;
}
if (!Diagnosed)