/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/Sema/AnalysisBasedWarnings.cpp
Line | Count | Source (jump to first uncovered line) |
1 | | //=- AnalysisBasedWarnings.cpp - Sema warnings based on libAnalysis -*- C++ -*-=// |
2 | | // |
3 | | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
4 | | // See https://llvm.org/LICENSE.txt for license information. |
5 | | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
6 | | // |
7 | | //===----------------------------------------------------------------------===// |
8 | | // |
9 | | // This file defines analysis_warnings::[Policy,Executor]. |
10 | | // Together they are used by Sema to issue warnings based on inexpensive |
11 | | // static analysis algorithms in libAnalysis. |
12 | | // |
13 | | //===----------------------------------------------------------------------===// |
14 | | |
15 | | #include "clang/Sema/AnalysisBasedWarnings.h" |
16 | | #include "clang/AST/DeclCXX.h" |
17 | | #include "clang/AST/DeclObjC.h" |
18 | | #include "clang/AST/EvaluatedExprVisitor.h" |
19 | | #include "clang/AST/ExprCXX.h" |
20 | | #include "clang/AST/ExprObjC.h" |
21 | | #include "clang/AST/ParentMap.h" |
22 | | #include "clang/AST/RecursiveASTVisitor.h" |
23 | | #include "clang/AST/StmtCXX.h" |
24 | | #include "clang/AST/StmtObjC.h" |
25 | | #include "clang/AST/StmtVisitor.h" |
26 | | #include "clang/Analysis/Analyses/CFGReachabilityAnalysis.h" |
27 | | #include "clang/Analysis/Analyses/CalledOnceCheck.h" |
28 | | #include "clang/Analysis/Analyses/Consumed.h" |
29 | | #include "clang/Analysis/Analyses/ReachableCode.h" |
30 | | #include "clang/Analysis/Analyses/ThreadSafety.h" |
31 | | #include "clang/Analysis/Analyses/UninitializedValues.h" |
32 | | #include "clang/Analysis/AnalysisDeclContext.h" |
33 | | #include "clang/Analysis/CFG.h" |
34 | | #include "clang/Analysis/CFGStmtMap.h" |
35 | | #include "clang/Basic/SourceLocation.h" |
36 | | #include "clang/Basic/SourceManager.h" |
37 | | #include "clang/Lex/Preprocessor.h" |
38 | | #include "clang/Sema/ScopeInfo.h" |
39 | | #include "clang/Sema/SemaInternal.h" |
40 | | #include "llvm/ADT/ArrayRef.h" |
41 | | #include "llvm/ADT/BitVector.h" |
42 | | #include "llvm/ADT/MapVector.h" |
43 | | #include "llvm/ADT/SmallString.h" |
44 | | #include "llvm/ADT/SmallVector.h" |
45 | | #include "llvm/ADT/StringRef.h" |
46 | | #include "llvm/Support/Casting.h" |
47 | | #include <algorithm> |
48 | | #include <deque> |
49 | | #include <iterator> |
50 | | |
51 | | using namespace clang; |
52 | | |
53 | | //===----------------------------------------------------------------------===// |
54 | | // Unreachable code analysis. |
55 | | //===----------------------------------------------------------------------===// |
56 | | |
57 | | namespace { |
58 | | class UnreachableCodeHandler : public reachable_code::Callback { |
59 | | Sema &S; |
60 | | SourceRange PreviousSilenceableCondVal; |
61 | | |
62 | | public: |
63 | 163 | UnreachableCodeHandler(Sema &s) : S(s) {} |
64 | | |
65 | | void HandleUnreachable(reachable_code::UnreachableKind UK, |
66 | | SourceLocation L, |
67 | | SourceRange SilenceableCondVal, |
68 | | SourceRange R1, |
69 | 177 | SourceRange R2) override { |
70 | | // Avoid reporting multiple unreachable code diagnostics that are |
71 | | // triggered by the same conditional value. |
72 | 177 | if (PreviousSilenceableCondVal.isValid() && |
73 | 177 | SilenceableCondVal.isValid()25 && |
74 | 177 | PreviousSilenceableCondVal == SilenceableCondVal25 ) |
75 | 2 | return; |
76 | 175 | PreviousSilenceableCondVal = SilenceableCondVal; |
77 | | |
78 | 175 | unsigned diag = diag::warn_unreachable; |
79 | 175 | switch (UK) { |
80 | 16 | case reachable_code::UK_Break: |
81 | 16 | diag = diag::warn_unreachable_break; |
82 | 16 | break; |
83 | 34 | case reachable_code::UK_Return: |
84 | 34 | diag = diag::warn_unreachable_return; |
85 | 34 | break; |
86 | 3 | case reachable_code::UK_Loop_Increment: |
87 | 3 | diag = diag::warn_unreachable_loop_increment; |
88 | 3 | break; |
89 | 122 | case reachable_code::UK_Other: |
90 | 122 | break; |
91 | 175 | } |
92 | | |
93 | 175 | S.Diag(L, diag) << R1 << R2; |
94 | | |
95 | 175 | SourceLocation Open = SilenceableCondVal.getBegin(); |
96 | 175 | if (Open.isValid()) { |
97 | 43 | SourceLocation Close = SilenceableCondVal.getEnd(); |
98 | 43 | Close = S.getLocForEndOfToken(Close); |
99 | 43 | if (Close.isValid()) { |
100 | 43 | S.Diag(Open, diag::note_unreachable_silence) |
101 | 43 | << FixItHint::CreateInsertion(Open, "/* DISABLES CODE */ (") |
102 | 43 | << FixItHint::CreateInsertion(Close, ")"); |
103 | 43 | } |
104 | 43 | } |
105 | 175 | } |
106 | | }; |
107 | | } // anonymous namespace |
108 | | |
109 | | /// CheckUnreachable - Check for unreachable code. |
110 | 165 | static void CheckUnreachable(Sema &S, AnalysisDeclContext &AC) { |
111 | | // As a heuristic prune all diagnostics not in the main file. Currently |
112 | | // the majority of warnings in headers are false positives. These |
113 | | // are largely caused by configuration state, e.g. preprocessor |
114 | | // defined code, etc. |
115 | | // |
116 | | // Note that this is also a performance optimization. Analyzing |
117 | | // headers many times can be expensive. |
118 | 165 | if (!S.getSourceManager().isInMainFile(AC.getDecl()->getBeginLoc())) |
119 | 2 | return; |
120 | | |
121 | 163 | UnreachableCodeHandler UC(S); |
122 | 163 | reachable_code::FindUnreachableCode(AC, S.getPreprocessor(), UC); |
123 | 163 | } |
124 | | |
125 | | namespace { |
126 | | /// Warn on logical operator errors in CFGBuilder |
127 | | class LogicalErrorHandler : public CFGCallback { |
128 | | Sema &S; |
129 | | |
130 | | public: |
131 | 42.3k | LogicalErrorHandler(Sema &S) : S(S) {} |
132 | | |
133 | 1.22k | static bool HasMacroID(const Expr *E) { |
134 | 1.22k | if (E->getExprLoc().isMacroID()) |
135 | 6 | return true; |
136 | | |
137 | | // Recurse to children. |
138 | 1.21k | for (const Stmt *SubStmt : E->children()) |
139 | 1.07k | if (const Expr *SubExpr = dyn_cast_or_null<Expr>(SubStmt)) |
140 | 1.07k | if (HasMacroID(SubExpr)) |
141 | 16 | return true; |
142 | | |
143 | 1.19k | return false; |
144 | 1.21k | } |
145 | | |
146 | 104 | void compareAlwaysTrue(const BinaryOperator *B, bool isAlwaysTrue) override { |
147 | 104 | if (HasMacroID(B)) |
148 | 2 | return; |
149 | | |
150 | 102 | SourceRange DiagRange = B->getSourceRange(); |
151 | 102 | S.Diag(B->getExprLoc(), diag::warn_tautological_overlap_comparison) |
152 | 102 | << DiagRange << isAlwaysTrue; |
153 | 102 | } |
154 | | |
155 | | void compareBitwiseEquality(const BinaryOperator *B, |
156 | 28 | bool isAlwaysTrue) override { |
157 | 28 | if (HasMacroID(B)) |
158 | 4 | return; |
159 | | |
160 | 24 | SourceRange DiagRange = B->getSourceRange(); |
161 | 24 | S.Diag(B->getExprLoc(), diag::warn_comparison_bitwise_always) |
162 | 24 | << DiagRange << isAlwaysTrue; |
163 | 24 | } |
164 | | |
165 | 16 | void compareBitwiseOr(const BinaryOperator *B) override { |
166 | 16 | if (HasMacroID(B)) |
167 | 0 | return; |
168 | | |
169 | 16 | SourceRange DiagRange = B->getSourceRange(); |
170 | 16 | S.Diag(B->getExprLoc(), diag::warn_comparison_bitwise_or) << DiagRange; |
171 | 16 | } |
172 | | |
173 | | static bool hasActiveDiagnostics(DiagnosticsEngine &Diags, |
174 | 551k | SourceLocation Loc) { |
175 | 551k | return !Diags.isIgnored(diag::warn_tautological_overlap_comparison, Loc) || |
176 | 551k | !Diags.isIgnored(diag::warn_comparison_bitwise_or, Loc)466k ; |
177 | 551k | } |
178 | | }; |
179 | | } // anonymous namespace |
180 | | |
181 | | //===----------------------------------------------------------------------===// |
182 | | // Check for infinite self-recursion in functions |
183 | | //===----------------------------------------------------------------------===// |
184 | | |
185 | | // Returns true if the function is called anywhere within the CFGBlock. |
186 | | // For member functions, the additional condition of being call from the |
187 | | // this pointer is required. |
188 | 43.9k | static bool hasRecursiveCallInPath(const FunctionDecl *FD, CFGBlock &Block) { |
189 | | // Process all the Stmt's in this block to find any calls to FD. |
190 | 448k | for (const auto &B : Block) { |
191 | 448k | if (B.getKind() != CFGElement::Statement) |
192 | 744 | continue; |
193 | | |
194 | 447k | const CallExpr *CE = dyn_cast<CallExpr>(B.getAs<CFGStmt>()->getStmt()); |
195 | 447k | if (!CE || !CE->getCalleeDecl()44.3k || |
196 | 447k | CE->getCalleeDecl()->getCanonicalDecl() != FD44.3k ) |
197 | 447k | continue; |
198 | | |
199 | | // Skip function calls which are qualified with a templated class. |
200 | 18 | if (const DeclRefExpr *DRE = |
201 | 18 | dyn_cast<DeclRefExpr>(CE->getCallee()->IgnoreParenImpCasts())) { |
202 | 15 | if (NestedNameSpecifier *NNS = DRE->getQualifier()) { |
203 | 1 | if (NNS->getKind() == NestedNameSpecifier::TypeSpec && |
204 | 1 | isa<TemplateSpecializationType>(NNS->getAsType())) { |
205 | 1 | continue; |
206 | 1 | } |
207 | 1 | } |
208 | 15 | } |
209 | | |
210 | 17 | const CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(CE); |
211 | 17 | if (!MCE || isa<CXXThisExpr>(MCE->getImplicitObjectArgument())3 || |
212 | 17 | !MCE->getMethodDecl()->isVirtual()1 ) |
213 | 17 | return true; |
214 | 17 | } |
215 | 43.9k | return false; |
216 | 43.9k | } |
217 | | |
218 | | // Returns true if every path from the entry block passes through a call to FD. |
219 | 42.3k | static bool checkForRecursiveFunctionCall(const FunctionDecl *FD, CFG *cfg) { |
220 | 42.3k | llvm::SmallPtrSet<CFGBlock *, 16> Visited; |
221 | 42.3k | llvm::SmallVector<CFGBlock *, 16> WorkList; |
222 | | // Keep track of whether we found at least one recursive path. |
223 | 42.3k | bool foundRecursion = false; |
224 | | |
225 | 42.3k | const unsigned ExitID = cfg->getExit().getBlockID(); |
226 | | |
227 | | // Seed the work list with the entry block. |
228 | 42.3k | WorkList.push_back(&cfg->getEntry()); |
229 | | |
230 | 85.5k | while (!WorkList.empty()) { |
231 | 85.5k | CFGBlock *Block = WorkList.pop_back_val(); |
232 | | |
233 | 129k | for (auto I = Block->succ_begin(), E = Block->succ_end(); I != E; ++I44.0k ) { |
234 | 86.3k | if (CFGBlock *SuccBlock = *I) { |
235 | 86.2k | if (!Visited.insert(SuccBlock).second) |
236 | 55 | continue; |
237 | | |
238 | | // Found a path to the exit node without a recursive call. |
239 | 86.2k | if (ExitID == SuccBlock->getBlockID()) |
240 | 42.2k | return false; |
241 | | |
242 | | // If the successor block contains a recursive call, end analysis there. |
243 | 43.9k | if (hasRecursiveCallInPath(FD, *SuccBlock)) { |
244 | 17 | foundRecursion = true; |
245 | 17 | continue; |
246 | 17 | } |
247 | | |
248 | 43.9k | WorkList.push_back(SuccBlock); |
249 | 43.9k | } |
250 | 86.3k | } |
251 | 85.5k | } |
252 | 16 | return foundRecursion; |
253 | 42.3k | } |
254 | | |
255 | | static void checkRecursiveFunction(Sema &S, const FunctionDecl *FD, |
256 | 42.3k | const Stmt *Body, AnalysisDeclContext &AC) { |
257 | 42.3k | FD = FD->getCanonicalDecl(); |
258 | | |
259 | | // Only run on non-templated functions and non-templated members of |
260 | | // templated classes. |
261 | 42.3k | if (FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate && |
262 | 42.3k | FD->getTemplatedKind() != FunctionDecl::TK_MemberSpecialization55 ) |
263 | 31 | return; |
264 | | |
265 | 42.3k | CFG *cfg = AC.getCFG(); |
266 | 42.3k | if (!cfg) return0 ; |
267 | | |
268 | | // If the exit block is unreachable, skip processing the function. |
269 | 42.3k | if (cfg->getExit().pred_empty()) |
270 | 7 | return; |
271 | | |
272 | | // Emit diagnostic if a recursive function call is detected for all paths. |
273 | 42.3k | if (checkForRecursiveFunctionCall(FD, cfg)) |
274 | 14 | S.Diag(Body->getBeginLoc(), diag::warn_infinite_recursive_function); |
275 | 42.3k | } |
276 | | |
277 | | //===----------------------------------------------------------------------===// |
278 | | // Check for throw in a non-throwing function. |
279 | | //===----------------------------------------------------------------------===// |
280 | | |
281 | | /// Determine whether an exception thrown by E, unwinding from ThrowBlock, |
282 | | /// can reach ExitBlock. |
283 | | static bool throwEscapes(Sema &S, const CXXThrowExpr *E, CFGBlock &ThrowBlock, |
284 | 81 | CFG *Body) { |
285 | 81 | SmallVector<CFGBlock *, 16> Stack; |
286 | 81 | llvm::BitVector Queued(Body->getNumBlockIDs()); |
287 | | |
288 | 81 | Stack.push_back(&ThrowBlock); |
289 | 81 | Queued[ThrowBlock.getBlockID()] = true; |
290 | | |
291 | 173 | while (!Stack.empty()) { |
292 | 138 | CFGBlock &UnwindBlock = *Stack.back(); |
293 | 138 | Stack.pop_back(); |
294 | | |
295 | 160 | for (auto &Succ : UnwindBlock.succs()) { |
296 | 160 | if (!Succ.isReachable() || Queued[Succ->getBlockID()]) |
297 | 0 | continue; |
298 | | |
299 | 160 | if (Succ->getBlockID() == Body->getExit().getBlockID()) |
300 | 46 | return true; |
301 | | |
302 | 114 | if (auto *Catch = |
303 | 114 | dyn_cast_or_null<CXXCatchStmt>(Succ->getLabel())) { |
304 | 57 | QualType Caught = Catch->getCaughtType(); |
305 | 57 | if (Caught.isNull() || // catch (...) catches everything |
306 | 57 | !E->getSubExpr()53 || // throw; is considered cuaght by any handler |
307 | 57 | S.handlerCanCatch(Caught, E->getSubExpr()->getType())50 ) |
308 | | // Exception doesn't escape via this path. |
309 | 35 | break; |
310 | 57 | } else { |
311 | 57 | Stack.push_back(Succ); |
312 | 57 | Queued[Succ->getBlockID()] = true; |
313 | 57 | } |
314 | 114 | } |
315 | 138 | } |
316 | | |
317 | 35 | return false; |
318 | 81 | } |
319 | | |
320 | | static void visitReachableThrows( |
321 | | CFG *BodyCFG, |
322 | 7.97k | llvm::function_ref<void(const CXXThrowExpr *, CFGBlock &)> Visit) { |
323 | 7.97k | llvm::BitVector Reachable(BodyCFG->getNumBlockIDs()); |
324 | 7.97k | clang::reachable_code::ScanReachableFromBlock(&BodyCFG->getEntry(), Reachable); |
325 | 25.6k | for (CFGBlock *B : *BodyCFG) { |
326 | 25.6k | if (!Reachable[B->getBlockID()]) |
327 | 36 | continue; |
328 | 52.5k | for (CFGElement &E : *B)25.6k { |
329 | 52.5k | Optional<CFGStmt> S = E.getAs<CFGStmt>(); |
330 | 52.5k | if (!S) |
331 | 579 | continue; |
332 | 51.9k | if (auto *Throw = dyn_cast<CXXThrowExpr>(S->getStmt())) |
333 | 81 | Visit(Throw, *B); |
334 | 51.9k | } |
335 | 25.6k | } |
336 | 7.97k | } |
337 | | |
338 | | static void EmitDiagForCXXThrowInNonThrowingFunc(Sema &S, SourceLocation OpLoc, |
339 | 46 | const FunctionDecl *FD) { |
340 | 46 | if (!S.getSourceManager().isInSystemHeader(OpLoc) && |
341 | 46 | FD->getTypeSourceInfo()) { |
342 | 46 | S.Diag(OpLoc, diag::warn_throw_in_noexcept_func) << FD; |
343 | 46 | if (S.getLangOpts().CPlusPlus11 && |
344 | 46 | (isa<CXXDestructorDecl>(FD) || |
345 | 46 | FD->getDeclName().getCXXOverloadedOperator() == OO_Delete35 || |
346 | 46 | FD->getDeclName().getCXXOverloadedOperator() == OO_Array_Delete34 )) { |
347 | 12 | if (const auto *Ty = FD->getTypeSourceInfo()->getType()-> |
348 | 12 | getAs<FunctionProtoType>()) |
349 | 12 | S.Diag(FD->getLocation(), diag::note_throw_in_dtor) |
350 | 12 | << !isa<CXXDestructorDecl>(FD) << !Ty->hasExceptionSpec() |
351 | 12 | << FD->getExceptionSpecSourceRange(); |
352 | 12 | } else |
353 | 34 | S.Diag(FD->getLocation(), diag::note_throw_in_function) |
354 | 34 | << FD->getExceptionSpecSourceRange(); |
355 | 46 | } |
356 | 46 | } |
357 | | |
358 | | static void checkThrowInNonThrowingFunc(Sema &S, const FunctionDecl *FD, |
359 | 7.97k | AnalysisDeclContext &AC) { |
360 | 7.97k | CFG *BodyCFG = AC.getCFG(); |
361 | 7.97k | if (!BodyCFG) |
362 | 2 | return; |
363 | 7.97k | if (BodyCFG->getExit().pred_empty()) |
364 | 0 | return; |
365 | 7.97k | visitReachableThrows(BodyCFG, [&](const CXXThrowExpr *Throw, CFGBlock &Block) { |
366 | 81 | if (throwEscapes(S, Throw, Block, BodyCFG)) |
367 | 46 | EmitDiagForCXXThrowInNonThrowingFunc(S, Throw->getThrowLoc(), FD); |
368 | 81 | }); |
369 | 7.97k | } |
370 | | |
371 | 160k | static bool isNoexcept(const FunctionDecl *FD) { |
372 | 160k | const auto *FPT = FD->getType()->castAs<FunctionProtoType>(); |
373 | 160k | if (FPT->isNothrow() || FD->hasAttr<NoThrowAttr>()152k ) |
374 | 7.97k | return true; |
375 | 152k | return false; |
376 | 160k | } |
377 | | |
378 | | //===----------------------------------------------------------------------===// |
379 | | // Check for missing return value. |
380 | | //===----------------------------------------------------------------------===// |
381 | | |
382 | | enum ControlFlowKind { |
383 | | UnknownFallThrough, |
384 | | NeverFallThrough, |
385 | | MaybeFallThrough, |
386 | | AlwaysFallThrough, |
387 | | NeverFallThroughOrReturn |
388 | | }; |
389 | | |
390 | | /// CheckFallThrough - Check that we don't fall off the end of a |
391 | | /// Statement that should return a value. |
392 | | /// |
393 | | /// \returns AlwaysFallThrough iff we always fall off the end of the statement, |
394 | | /// MaybeFallThrough iff we might or might not fall off the end, |
395 | | /// NeverFallThroughOrReturn iff we never fall off the end of the statement or |
396 | | /// return. We assume NeverFallThrough iff we never fall off the end of the |
397 | | /// statement but we may return. We assume that functions not marked noreturn |
398 | | /// will return. |
399 | 140k | static ControlFlowKind CheckFallThrough(AnalysisDeclContext &AC) { |
400 | 140k | CFG *cfg = AC.getCFG(); |
401 | 140k | if (!cfg) return UnknownFallThrough30 ; |
402 | | |
403 | | // The CFG leaves in dead things, and we don't want the dead code paths to |
404 | | // confuse us, so we mark all live things first. |
405 | 140k | llvm::BitVector live(cfg->getNumBlockIDs()); |
406 | 140k | unsigned count = reachable_code::ScanReachableFromBlock(&cfg->getEntry(), |
407 | 140k | live); |
408 | | |
409 | 140k | bool AddEHEdges = AC.getAddEHEdges(); |
410 | 140k | if (!AddEHEdges && count != cfg->getNumBlockIDs()) |
411 | | // When there are things remaining dead, and we didn't add EH edges |
412 | | // from CallExprs to the catch clauses, we have to go back and |
413 | | // mark them as live. |
414 | 6.93k | for (const auto *B : *cfg)941 { |
415 | 6.93k | if (!live[B->getBlockID()]) { |
416 | 1.61k | if (B->pred_begin() == B->pred_end()) { |
417 | 894 | const Stmt *Term = B->getTerminatorStmt(); |
418 | 894 | if (Term && isa<CXXTryStmt>(Term)124 ) |
419 | | // When not adding EH edges from calls, catch clauses |
420 | | // can otherwise seem dead. Avoid noting them as dead. |
421 | 38 | count += reachable_code::ScanReachableFromBlock(B, live); |
422 | 894 | continue; |
423 | 894 | } |
424 | 1.61k | } |
425 | 6.93k | } |
426 | | |
427 | | // Now we know what is live, we check the live precessors of the exit block |
428 | | // and look for fall through paths, being careful to ignore normal returns, |
429 | | // and exceptional paths. |
430 | 140k | bool HasLiveReturn = false; |
431 | 140k | bool HasFakeEdge = false; |
432 | 140k | bool HasPlainEdge = false; |
433 | 140k | bool HasAbnormalEdge = false; |
434 | | |
435 | | // Ignore default cases that aren't likely to be reachable because all |
436 | | // enums in a switch(X) have explicit case statements. |
437 | 140k | CFGBlock::FilterOptions FO; |
438 | 140k | FO.IgnoreDefaultsWithCoveredEnums = 1; |
439 | | |
440 | 140k | for (CFGBlock::filtered_pred_iterator I = |
441 | 140k | cfg->getExit().filtered_pred_start_end(FO); |
442 | 285k | I.hasMore(); ++I144k ) { |
443 | 144k | const CFGBlock &B = **I; |
444 | 144k | if (!live[B.getBlockID()]) |
445 | 693 | continue; |
446 | | |
447 | | // Skip blocks which contain an element marked as no-return. They don't |
448 | | // represent actually viable edges into the exit block, so mark them as |
449 | | // abnormal. |
450 | 143k | if (B.hasNoReturnElement()) { |
451 | 302 | HasAbnormalEdge = true; |
452 | 302 | continue; |
453 | 302 | } |
454 | | |
455 | | // Destructors can appear after the 'return' in the CFG. This is |
456 | | // normal. We need to look pass the destructors for the return |
457 | | // statement (if it exists). |
458 | 143k | CFGBlock::const_reverse_iterator ri = B.rbegin(), re = B.rend(); |
459 | | |
460 | 144k | for ( ; ri != re ; ++ri1.70k ) |
461 | 144k | if (ri->getAs<CFGStmt>()) |
462 | 142k | break; |
463 | | |
464 | | // No more CFGElements in the block? |
465 | 143k | if (ri == re) { |
466 | 599 | const Stmt *Term = B.getTerminatorStmt(); |
467 | 599 | if (Term && (27 isa<CXXTryStmt>(Term)27 || isa<ObjCAtTryStmt>(Term)8 )) { |
468 | 23 | HasAbnormalEdge = true; |
469 | 23 | continue; |
470 | 23 | } |
471 | | // A labeled empty statement, or the entry block... |
472 | 576 | HasPlainEdge = true; |
473 | 576 | continue; |
474 | 599 | } |
475 | | |
476 | 142k | CFGStmt CS = ri->castAs<CFGStmt>(); |
477 | 142k | const Stmt *S = CS.getStmt(); |
478 | 142k | if (isa<ReturnStmt>(S) || isa<CoreturnStmt>(S)360 ) { |
479 | 142k | HasLiveReturn = true; |
480 | 142k | continue; |
481 | 142k | } |
482 | 328 | if (isa<ObjCAtThrowStmt>(S)) { |
483 | 5 | HasFakeEdge = true; |
484 | 5 | continue; |
485 | 5 | } |
486 | 323 | if (isa<CXXThrowExpr>(S)) { |
487 | 52 | HasFakeEdge = true; |
488 | 52 | continue; |
489 | 52 | } |
490 | 271 | if (isa<MSAsmStmt>(S)) { |
491 | | // TODO: Verify this is correct. |
492 | 16 | HasFakeEdge = true; |
493 | 16 | HasLiveReturn = true; |
494 | 16 | continue; |
495 | 16 | } |
496 | 255 | if (isa<CXXTryStmt>(S)) { |
497 | 0 | HasAbnormalEdge = true; |
498 | 0 | continue; |
499 | 0 | } |
500 | 255 | if (!llvm::is_contained(B.succs(), &cfg->getExit())) { |
501 | 0 | HasAbnormalEdge = true; |
502 | 0 | continue; |
503 | 0 | } |
504 | | |
505 | 255 | HasPlainEdge = true; |
506 | 255 | } |
507 | 140k | if (!HasPlainEdge) { |
508 | 140k | if (HasLiveReturn) |
509 | 139k | return NeverFallThrough; |
510 | 287 | return NeverFallThroughOrReturn; |
511 | 140k | } |
512 | 822 | if (HasAbnormalEdge || HasFakeEdge804 || HasLiveReturn804 ) |
513 | 42 | return MaybeFallThrough; |
514 | | // This says AlwaysFallThrough for calls to functions that are not marked |
515 | | // noreturn, that don't return. If people would like this warning to be more |
516 | | // accurate, such functions should be marked as noreturn. |
517 | 780 | return AlwaysFallThrough; |
518 | 822 | } |
519 | | |
520 | | namespace { |
521 | | |
522 | | struct CheckFallThroughDiagnostics { |
523 | | unsigned diag_MaybeFallThrough_HasNoReturn; |
524 | | unsigned diag_MaybeFallThrough_ReturnsNonVoid; |
525 | | unsigned diag_AlwaysFallThrough_HasNoReturn; |
526 | | unsigned diag_AlwaysFallThrough_ReturnsNonVoid; |
527 | | unsigned diag_NeverFallThroughOrReturn; |
528 | | enum { Function, Block, Lambda, Coroutine } funMode; |
529 | | SourceLocation FuncLoc; |
530 | | |
531 | 262k | static CheckFallThroughDiagnostics MakeForFunction(const Decl *Func) { |
532 | 262k | CheckFallThroughDiagnostics D; |
533 | 262k | D.FuncLoc = Func->getLocation(); |
534 | 262k | D.diag_MaybeFallThrough_HasNoReturn = |
535 | 262k | diag::warn_falloff_noreturn_function; |
536 | 262k | D.diag_MaybeFallThrough_ReturnsNonVoid = |
537 | 262k | diag::warn_maybe_falloff_nonvoid_function; |
538 | 262k | D.diag_AlwaysFallThrough_HasNoReturn = |
539 | 262k | diag::warn_falloff_noreturn_function; |
540 | 262k | D.diag_AlwaysFallThrough_ReturnsNonVoid = |
541 | 262k | diag::warn_falloff_nonvoid_function; |
542 | | |
543 | | // Don't suggest that virtual functions be marked "noreturn", since they |
544 | | // might be overridden by non-noreturn functions. |
545 | 262k | bool isVirtualMethod = false; |
546 | 262k | if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Func)) |
547 | 50.8k | isVirtualMethod = Method->isVirtual(); |
548 | | |
549 | | // Don't suggest that template instantiations be marked "noreturn" |
550 | 262k | bool isTemplateInstantiation = false; |
551 | 262k | if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(Func)) |
552 | 257k | isTemplateInstantiation = Function->isTemplateInstantiation(); |
553 | | |
554 | 262k | if (!isVirtualMethod && !isTemplateInstantiation259k ) |
555 | 243k | D.diag_NeverFallThroughOrReturn = |
556 | 243k | diag::warn_suggest_noreturn_function; |
557 | 19.2k | else |
558 | 19.2k | D.diag_NeverFallThroughOrReturn = 0; |
559 | | |
560 | 262k | D.funMode = Function; |
561 | 262k | return D; |
562 | 262k | } |
563 | | |
564 | 178 | static CheckFallThroughDiagnostics MakeForCoroutine(const Decl *Func) { |
565 | 178 | CheckFallThroughDiagnostics D; |
566 | 178 | D.FuncLoc = Func->getLocation(); |
567 | 178 | D.diag_MaybeFallThrough_HasNoReturn = 0; |
568 | 178 | D.diag_MaybeFallThrough_ReturnsNonVoid = |
569 | 178 | diag::warn_maybe_falloff_nonvoid_coroutine; |
570 | 178 | D.diag_AlwaysFallThrough_HasNoReturn = 0; |
571 | 178 | D.diag_AlwaysFallThrough_ReturnsNonVoid = |
572 | 178 | diag::warn_falloff_nonvoid_coroutine; |
573 | 178 | D.funMode = Coroutine; |
574 | 178 | return D; |
575 | 178 | } |
576 | | |
577 | 2.19k | static CheckFallThroughDiagnostics MakeForBlock() { |
578 | 2.19k | CheckFallThroughDiagnostics D; |
579 | 2.19k | D.diag_MaybeFallThrough_HasNoReturn = |
580 | 2.19k | diag::err_noreturn_block_has_return_expr; |
581 | 2.19k | D.diag_MaybeFallThrough_ReturnsNonVoid = |
582 | 2.19k | diag::err_maybe_falloff_nonvoid_block; |
583 | 2.19k | D.diag_AlwaysFallThrough_HasNoReturn = |
584 | 2.19k | diag::err_noreturn_block_has_return_expr; |
585 | 2.19k | D.diag_AlwaysFallThrough_ReturnsNonVoid = |
586 | 2.19k | diag::err_falloff_nonvoid_block; |
587 | 2.19k | D.diag_NeverFallThroughOrReturn = 0; |
588 | 2.19k | D.funMode = Block; |
589 | 2.19k | return D; |
590 | 2.19k | } |
591 | | |
592 | 3.73k | static CheckFallThroughDiagnostics MakeForLambda() { |
593 | 3.73k | CheckFallThroughDiagnostics D; |
594 | 3.73k | D.diag_MaybeFallThrough_HasNoReturn = |
595 | 3.73k | diag::err_noreturn_lambda_has_return_expr; |
596 | 3.73k | D.diag_MaybeFallThrough_ReturnsNonVoid = |
597 | 3.73k | diag::warn_maybe_falloff_nonvoid_lambda; |
598 | 3.73k | D.diag_AlwaysFallThrough_HasNoReturn = |
599 | 3.73k | diag::err_noreturn_lambda_has_return_expr; |
600 | 3.73k | D.diag_AlwaysFallThrough_ReturnsNonVoid = |
601 | 3.73k | diag::warn_falloff_nonvoid_lambda; |
602 | 3.73k | D.diag_NeverFallThroughOrReturn = 0; |
603 | 3.73k | D.funMode = Lambda; |
604 | 3.73k | return D; |
605 | 3.73k | } |
606 | | |
607 | | bool checkDiagnostics(DiagnosticsEngine &D, bool ReturnsVoid, |
608 | 268k | bool HasNoReturn) const { |
609 | 268k | if (funMode == Function) { |
610 | 262k | return (ReturnsVoid || |
611 | 262k | D.isIgnored(diag::warn_maybe_falloff_nonvoid_function, |
612 | 139k | FuncLoc)) && |
613 | 262k | (123k !HasNoReturn123k || |
614 | 123k | D.isIgnored(diag::warn_noreturn_function_has_return_expr, |
615 | 162 | FuncLoc)) && |
616 | 262k | (123k !ReturnsVoid123k || |
617 | 123k | D.isIgnored(diag::warn_suggest_noreturn_block, FuncLoc)122k ); |
618 | 262k | } |
619 | 6.11k | if (funMode == Coroutine) { |
620 | 178 | return (ReturnsVoid || |
621 | 178 | D.isIgnored(diag::warn_maybe_falloff_nonvoid_function, FuncLoc)39 || |
622 | 178 | D.isIgnored(diag::warn_maybe_falloff_nonvoid_coroutine, |
623 | 39 | FuncLoc)) && |
624 | 178 | (!HasNoReturn)139 ; |
625 | 178 | } |
626 | | // For blocks / lambdas. |
627 | 5.93k | return ReturnsVoid && !HasNoReturn4.56k ; |
628 | 6.11k | } |
629 | | }; |
630 | | |
631 | | } // anonymous namespace |
632 | | |
633 | | /// CheckFallThroughForBody - Check that we don't fall off the end of a |
634 | | /// function that should return a value. Check that we don't fall off the end |
635 | | /// of a noreturn function. We assume that functions and blocks not marked |
636 | | /// noreturn will return. |
637 | | static void CheckFallThroughForBody(Sema &S, const Decl *D, const Stmt *Body, |
638 | | QualType BlockType, |
639 | | const CheckFallThroughDiagnostics &CD, |
640 | | AnalysisDeclContext &AC, |
641 | 268k | sema::FunctionScopeInfo *FSI) { |
642 | | |
643 | 268k | bool ReturnsVoid = false; |
644 | 268k | bool HasNoReturn = false; |
645 | 268k | bool IsCoroutine = FSI->isCoroutine(); |
646 | | |
647 | 268k | if (const auto *FD = dyn_cast<FunctionDecl>(D)) { |
648 | 261k | if (const auto *CBody = dyn_cast<CoroutineBodyStmt>(Body)) |
649 | 180 | ReturnsVoid = CBody->getFallthroughHandler() != nullptr; |
650 | 260k | else |
651 | 260k | ReturnsVoid = FD->getReturnType()->isVoidType(); |
652 | 261k | HasNoReturn = FD->isNoReturn(); |
653 | 261k | } |
654 | 7.55k | else if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) { |
655 | 5.35k | ReturnsVoid = MD->getReturnType()->isVoidType(); |
656 | 5.35k | HasNoReturn = MD->hasAttr<NoReturnAttr>(); |
657 | 5.35k | } |
658 | 2.19k | else if (isa<BlockDecl>(D)) { |
659 | 2.19k | if (const FunctionType *FT = |
660 | 2.19k | BlockType->getPointeeType()->getAs<FunctionType>()) { |
661 | 2.19k | if (FT->getReturnType()->isVoidType()) |
662 | 1.77k | ReturnsVoid = true; |
663 | 2.19k | if (FT->getNoReturnAttr()) |
664 | 1 | HasNoReturn = true; |
665 | 2.19k | } |
666 | 2.19k | } |
667 | | |
668 | 268k | DiagnosticsEngine &Diags = S.getDiagnostics(); |
669 | | |
670 | | // Short circuit for compilation speed. |
671 | 268k | if (CD.checkDiagnostics(Diags, ReturnsVoid, HasNoReturn)) |
672 | 127k | return; |
673 | 140k | SourceLocation LBrace = Body->getBeginLoc(), RBrace = Body->getEndLoc(); |
674 | 140k | auto EmitDiag = [&](SourceLocation Loc, unsigned DiagID) { |
675 | 776 | if (IsCoroutine) |
676 | 14 | S.Diag(Loc, DiagID) << FSI->CoroutinePromise->getType(); |
677 | 762 | else |
678 | 762 | S.Diag(Loc, DiagID); |
679 | 776 | }; |
680 | | |
681 | | // cpu_dispatch functions permit empty function bodies for ICC compatibility. |
682 | 140k | if (D->getAsFunction() && D->getAsFunction()->isCPUDispatchMultiVersion()137k ) |
683 | 10 | return; |
684 | | |
685 | | // Either in a function body compound statement, or a function-try-block. |
686 | 140k | switch (CheckFallThrough(AC)) { |
687 | 30 | case UnknownFallThrough: |
688 | 30 | break; |
689 | | |
690 | 42 | case MaybeFallThrough: |
691 | 42 | if (HasNoReturn) |
692 | 0 | EmitDiag(RBrace, CD.diag_MaybeFallThrough_HasNoReturn); |
693 | 42 | else if (!ReturnsVoid) |
694 | 41 | EmitDiag(RBrace, CD.diag_MaybeFallThrough_ReturnsNonVoid); |
695 | 42 | break; |
696 | 780 | case AlwaysFallThrough: |
697 | 780 | if (HasNoReturn) |
698 | 101 | EmitDiag(RBrace, CD.diag_AlwaysFallThrough_HasNoReturn); |
699 | 679 | else if (!ReturnsVoid) |
700 | 634 | EmitDiag(RBrace, CD.diag_AlwaysFallThrough_ReturnsNonVoid); |
701 | 780 | break; |
702 | 287 | case NeverFallThroughOrReturn: |
703 | 287 | if (ReturnsVoid && !HasNoReturn69 && CD.diag_NeverFallThroughOrReturn9 ) { |
704 | 4 | if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { |
705 | 3 | S.Diag(LBrace, CD.diag_NeverFallThroughOrReturn) << 0 << FD; |
706 | 3 | } else if (const ObjCMethodDecl *1 MD1 = dyn_cast<ObjCMethodDecl>(D)) { |
707 | 1 | S.Diag(LBrace, CD.diag_NeverFallThroughOrReturn) << 1 << MD; |
708 | 1 | } else { |
709 | 0 | S.Diag(LBrace, CD.diag_NeverFallThroughOrReturn); |
710 | 0 | } |
711 | 4 | } |
712 | 287 | break; |
713 | 139k | case NeverFallThrough: |
714 | 139k | break; |
715 | 140k | } |
716 | 140k | } |
717 | | |
718 | | //===----------------------------------------------------------------------===// |
719 | | // -Wuninitialized |
720 | | //===----------------------------------------------------------------------===// |
721 | | |
722 | | namespace { |
723 | | /// ContainsReference - A visitor class to search for references to |
724 | | /// a particular declaration (the needle) within any evaluated component of an |
725 | | /// expression (recursively). |
726 | | class ContainsReference : public ConstEvaluatedExprVisitor<ContainsReference> { |
727 | | bool FoundReference; |
728 | | const DeclRefExpr *Needle; |
729 | | |
730 | | public: |
731 | | typedef ConstEvaluatedExprVisitor<ContainsReference> Inherited; |
732 | | |
733 | | ContainsReference(ASTContext &Context, const DeclRefExpr *Needle) |
734 | 70 | : Inherited(Context), FoundReference(false), Needle(Needle) {} |
735 | | |
736 | 301 | void VisitExpr(const Expr *E) { |
737 | | // Stop evaluating if we already have a reference. |
738 | 301 | if (FoundReference) |
739 | 25 | return; |
740 | | |
741 | 276 | Inherited::VisitExpr(E); |
742 | 276 | } |
743 | | |
744 | 128 | void VisitDeclRefExpr(const DeclRefExpr *E) { |
745 | 128 | if (E == Needle) |
746 | 67 | FoundReference = true; |
747 | 61 | else |
748 | 61 | Inherited::VisitDeclRefExpr(E); |
749 | 128 | } |
750 | | |
751 | 70 | bool doesContainReference() const { return FoundReference; } |
752 | | }; |
753 | | } // anonymous namespace |
754 | | |
755 | 1.12k | static bool SuggestInitializationFixit(Sema &S, const VarDecl *VD) { |
756 | 1.12k | QualType VariableTy = VD->getType().getCanonicalType(); |
757 | 1.12k | if (VariableTy->isBlockPointerType() && |
758 | 1.12k | !VD->hasAttr<BlocksAttr>()3 ) { |
759 | 3 | S.Diag(VD->getLocation(), diag::note_block_var_fixit_add_initialization) |
760 | 3 | << VD->getDeclName() |
761 | 3 | << FixItHint::CreateInsertion(VD->getLocation(), "__block "); |
762 | 3 | return true; |
763 | 3 | } |
764 | | |
765 | | // Don't issue a fixit if there is already an initializer. |
766 | 1.12k | if (VD->getInit()) |
767 | 3 | return false; |
768 | | |
769 | | // Don't suggest a fixit inside macros. |
770 | 1.12k | if (VD->getEndLoc().isMacroID()) |
771 | 2 | return false; |
772 | | |
773 | 1.11k | SourceLocation Loc = S.getLocForEndOfToken(VD->getEndLoc()); |
774 | | |
775 | | // Suggest possible initialization (if any). |
776 | 1.11k | std::string Init = S.getFixItZeroInitializerForType(VariableTy, Loc); |
777 | 1.11k | if (Init.empty()) |
778 | 5 | return false; |
779 | | |
780 | 1.11k | S.Diag(Loc, diag::note_var_fixit_add_initialization) << VD->getDeclName() |
781 | 1.11k | << FixItHint::CreateInsertion(Loc, Init); |
782 | 1.11k | return true; |
783 | 1.11k | } |
784 | | |
785 | | /// Create a fixit to remove an if-like statement, on the assumption that its |
786 | | /// condition is CondVal. |
787 | | static void CreateIfFixit(Sema &S, const Stmt *If, const Stmt *Then, |
788 | | const Stmt *Else, bool CondVal, |
789 | 23 | FixItHint &Fixit1, FixItHint &Fixit2) { |
790 | 23 | if (CondVal) { |
791 | | // If condition is always true, remove all but the 'then'. |
792 | 12 | Fixit1 = FixItHint::CreateRemoval( |
793 | 12 | CharSourceRange::getCharRange(If->getBeginLoc(), Then->getBeginLoc())); |
794 | 12 | if (Else) { |
795 | 2 | SourceLocation ElseKwLoc = S.getLocForEndOfToken(Then->getEndLoc()); |
796 | 2 | Fixit2 = |
797 | 2 | FixItHint::CreateRemoval(SourceRange(ElseKwLoc, Else->getEndLoc())); |
798 | 2 | } |
799 | 12 | } else { |
800 | | // If condition is always false, remove all but the 'else'. |
801 | 11 | if (Else) |
802 | 11 | Fixit1 = FixItHint::CreateRemoval(CharSourceRange::getCharRange( |
803 | 11 | If->getBeginLoc(), Else->getBeginLoc())); |
804 | 0 | else |
805 | 0 | Fixit1 = FixItHint::CreateRemoval(If->getSourceRange()); |
806 | 11 | } |
807 | 23 | } |
808 | | |
809 | | /// DiagUninitUse -- Helper function to produce a diagnostic for an |
810 | | /// uninitialized use of a variable. |
811 | | static void DiagUninitUse(Sema &S, const VarDecl *VD, const UninitUse &Use, |
812 | 1.12k | bool IsCapturedByBlock) { |
813 | 1.12k | bool Diagnosed = false; |
814 | | |
815 | 1.12k | switch (Use.getKind()) { |
816 | 1.02k | case UninitUse::Always: |
817 | 1.02k | S.Diag(Use.getUser()->getBeginLoc(), diag::warn_uninit_var) |
818 | 1.02k | << VD->getDeclName() << IsCapturedByBlock |
819 | 1.02k | << Use.getUser()->getSourceRange(); |
820 | 1.02k | return; |
821 | | |
822 | 7 | case UninitUse::AfterDecl: |
823 | 13 | case UninitUse::AfterCall: |
824 | 13 | S.Diag(VD->getLocation(), diag::warn_sometimes_uninit_var) |
825 | 13 | << VD->getDeclName() << IsCapturedByBlock |
826 | 13 | << (Use.getKind() == UninitUse::AfterDecl ? 47 : 56 ) |
827 | 13 | << const_cast<DeclContext*>(VD->getLexicalDeclContext()) |
828 | 13 | << VD->getSourceRange(); |
829 | 13 | S.Diag(Use.getUser()->getBeginLoc(), diag::note_uninit_var_use) |
830 | 13 | << IsCapturedByBlock << Use.getUser()->getSourceRange(); |
831 | 13 | return; |
832 | | |
833 | 32 | case UninitUse::Maybe: |
834 | 85 | case UninitUse::Sometimes: |
835 | | // Carry on to report sometimes-uninitialized branches, if possible, |
836 | | // or a 'may be used uninitialized' diagnostic otherwise. |
837 | 85 | break; |
838 | 1.12k | } |
839 | | |
840 | | // Diagnose each branch which leads to a sometimes-uninitialized use. |
841 | 85 | for (UninitUse::branch_iterator I = Use.branch_begin(), E = Use.branch_end(); |
842 | 140 | I != E; ++I55 ) { |
843 | 55 | assert(Use.getKind() == UninitUse::Sometimes); |
844 | | |
845 | 0 | const Expr *User = Use.getUser(); |
846 | 55 | const Stmt *Term = I->Terminator; |
847 | | |
848 | | // Information used when building the diagnostic. |
849 | 55 | unsigned DiagKind; |
850 | 55 | StringRef Str; |
851 | 55 | SourceRange Range; |
852 | | |
853 | | // FixIts to suppress the diagnostic by removing the dead condition. |
854 | | // For all binary terminators, branch 0 is taken if the condition is true, |
855 | | // and branch 1 is taken if the condition is false. |
856 | 55 | int RemoveDiagKind = -1; |
857 | 55 | const char *FixitStr = |
858 | 55 | S.getLangOpts().CPlusPlus ? (47 I->Output47 ? "true"20 : "false"27 ) |
859 | 55 | : (8 I->Output8 ? "1"4 : "0"4 ); |
860 | 55 | FixItHint Fixit1, Fixit2; |
861 | | |
862 | 55 | switch (Term ? Term->getStmtClass() : Stmt::DeclStmtClass0 ) { |
863 | 0 | default: |
864 | | // Don't know how to report this. Just fall back to 'may be used |
865 | | // uninitialized'. FIXME: Can this happen? |
866 | 0 | continue; |
867 | | |
868 | | // "condition is true / condition is false". |
869 | 19 | case Stmt::IfStmtClass: { |
870 | 19 | const IfStmt *IS = cast<IfStmt>(Term); |
871 | 19 | DiagKind = 0; |
872 | 19 | Str = "if"; |
873 | 19 | Range = IS->getCond()->getSourceRange(); |
874 | 19 | RemoveDiagKind = 0; |
875 | 19 | CreateIfFixit(S, IS, IS->getThen(), IS->getElse(), |
876 | 19 | I->Output, Fixit1, Fixit2); |
877 | 19 | break; |
878 | 0 | } |
879 | 4 | case Stmt::ConditionalOperatorClass: { |
880 | 4 | const ConditionalOperator *CO = cast<ConditionalOperator>(Term); |
881 | 4 | DiagKind = 0; |
882 | 4 | Str = "?:"; |
883 | 4 | Range = CO->getCond()->getSourceRange(); |
884 | 4 | RemoveDiagKind = 0; |
885 | 4 | CreateIfFixit(S, CO, CO->getTrueExpr(), CO->getFalseExpr(), |
886 | 4 | I->Output, Fixit1, Fixit2); |
887 | 4 | break; |
888 | 0 | } |
889 | 12 | case Stmt::BinaryOperatorClass: { |
890 | 12 | const BinaryOperator *BO = cast<BinaryOperator>(Term); |
891 | 12 | if (!BO->isLogicalOp()) |
892 | 0 | continue; |
893 | 12 | DiagKind = 0; |
894 | 12 | Str = BO->getOpcodeStr(); |
895 | 12 | Range = BO->getLHS()->getSourceRange(); |
896 | 12 | RemoveDiagKind = 0; |
897 | 12 | if ((BO->getOpcode() == BO_LAnd && I->Output4 ) || |
898 | 12 | (10 BO->getOpcode() == BO_LOr10 && !I->Output8 )) |
899 | | // true && y -> y, false || y -> y. |
900 | 8 | Fixit1 = FixItHint::CreateRemoval( |
901 | 8 | SourceRange(BO->getBeginLoc(), BO->getOperatorLoc())); |
902 | 4 | else |
903 | | // false && y -> false, true || y -> true. |
904 | 4 | Fixit1 = FixItHint::CreateReplacement(BO->getSourceRange(), FixitStr); |
905 | 12 | break; |
906 | 12 | } |
907 | | |
908 | | // "loop is entered / loop is exited". |
909 | 4 | case Stmt::WhileStmtClass: |
910 | 4 | DiagKind = 1; |
911 | 4 | Str = "while"; |
912 | 4 | Range = cast<WhileStmt>(Term)->getCond()->getSourceRange(); |
913 | 4 | RemoveDiagKind = 1; |
914 | 4 | Fixit1 = FixItHint::CreateReplacement(Range, FixitStr); |
915 | 4 | break; |
916 | 4 | case Stmt::ForStmtClass: |
917 | 4 | DiagKind = 1; |
918 | 4 | Str = "for"; |
919 | 4 | Range = cast<ForStmt>(Term)->getCond()->getSourceRange(); |
920 | 4 | RemoveDiagKind = 1; |
921 | 4 | if (I->Output) |
922 | 2 | Fixit1 = FixItHint::CreateRemoval(Range); |
923 | 2 | else |
924 | 2 | Fixit1 = FixItHint::CreateReplacement(Range, FixitStr); |
925 | 4 | break; |
926 | 4 | case Stmt::CXXForRangeStmtClass: |
927 | 4 | if (I->Output == 1) { |
928 | | // The use occurs if a range-based for loop's body never executes. |
929 | | // That may be impossible, and there's no syntactic fix for this, |
930 | | // so treat it as a 'may be uninitialized' case. |
931 | 2 | continue; |
932 | 2 | } |
933 | 2 | DiagKind = 1; |
934 | 2 | Str = "for"; |
935 | 2 | Range = cast<CXXForRangeStmt>(Term)->getRangeInit()->getSourceRange(); |
936 | 2 | break; |
937 | | |
938 | | // "condition is true / loop is exited". |
939 | 4 | case Stmt::DoStmtClass: |
940 | 4 | DiagKind = 2; |
941 | 4 | Str = "do"; |
942 | 4 | Range = cast<DoStmt>(Term)->getCond()->getSourceRange(); |
943 | 4 | RemoveDiagKind = 1; |
944 | 4 | Fixit1 = FixItHint::CreateReplacement(Range, FixitStr); |
945 | 4 | break; |
946 | | |
947 | | // "switch case is taken". |
948 | 2 | case Stmt::CaseStmtClass: |
949 | 2 | DiagKind = 3; |
950 | 2 | Str = "case"; |
951 | 2 | Range = cast<CaseStmt>(Term)->getLHS()->getSourceRange(); |
952 | 2 | break; |
953 | 2 | case Stmt::DefaultStmtClass: |
954 | 2 | DiagKind = 3; |
955 | 2 | Str = "default"; |
956 | 2 | Range = cast<DefaultStmt>(Term)->getDefaultLoc(); |
957 | 2 | break; |
958 | 55 | } |
959 | | |
960 | 53 | S.Diag(Range.getBegin(), diag::warn_sometimes_uninit_var) |
961 | 53 | << VD->getDeclName() << IsCapturedByBlock << DiagKind |
962 | 53 | << Str << I->Output << Range; |
963 | 53 | S.Diag(User->getBeginLoc(), diag::note_uninit_var_use) |
964 | 53 | << IsCapturedByBlock << User->getSourceRange(); |
965 | 53 | if (RemoveDiagKind != -1) |
966 | 47 | S.Diag(Fixit1.RemoveRange.getBegin(), diag::note_uninit_fixit_remove_cond) |
967 | 47 | << RemoveDiagKind << Str << I->Output << Fixit1 << Fixit2; |
968 | | |
969 | 53 | Diagnosed = true; |
970 | 53 | } |
971 | | |
972 | 85 | if (!Diagnosed) |
973 | 34 | S.Diag(Use.getUser()->getBeginLoc(), diag::warn_maybe_uninit_var) |
974 | 34 | << VD->getDeclName() << IsCapturedByBlock |
975 | 34 | << Use.getUser()->getSourceRange(); |
976 | 85 | } |
977 | | |
978 | | /// Diagnose uninitialized const reference usages. |
979 | | static bool DiagnoseUninitializedConstRefUse(Sema &S, const VarDecl *VD, |
980 | 14 | const UninitUse &Use) { |
981 | 14 | S.Diag(Use.getUser()->getBeginLoc(), diag::warn_uninit_const_reference) |
982 | 14 | << VD->getDeclName() << Use.getUser()->getSourceRange(); |
983 | 14 | return true; |
984 | 14 | } |
985 | | |
986 | | /// DiagnoseUninitializedUse -- Helper function for diagnosing uses of an |
987 | | /// uninitialized variable. This manages the different forms of diagnostic |
988 | | /// emitted for particular types of uses. Returns true if the use was diagnosed |
989 | | /// as a warning. If a particular use is one we omit warnings for, returns |
990 | | /// false. |
991 | | static bool DiagnoseUninitializedUse(Sema &S, const VarDecl *VD, |
992 | | const UninitUse &Use, |
993 | 1.19k | bool alwaysReportSelfInit = false) { |
994 | 1.19k | if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Use.getUser())) { |
995 | | // Inspect the initializer of the variable declaration which is |
996 | | // being referenced prior to its initialization. We emit |
997 | | // specialized diagnostics for self-initialization, and we |
998 | | // specifically avoid warning about self references which take the |
999 | | // form of: |
1000 | | // |
1001 | | // int x = x; |
1002 | | // |
1003 | | // This is used to indicate to GCC that 'x' is intentionally left |
1004 | | // uninitialized. Proven code paths which access 'x' in |
1005 | | // an uninitialized state after this will still warn. |
1006 | 1.18k | if (const Expr *Initializer = VD->getInit()) { |
1007 | 70 | if (!alwaysReportSelfInit && DRE == Initializer->IgnoreParenImpCasts()67 ) |
1008 | 0 | return false; |
1009 | | |
1010 | 70 | ContainsReference CR(S.Context, DRE); |
1011 | 70 | CR.Visit(Initializer); |
1012 | 70 | if (CR.doesContainReference()) { |
1013 | 67 | S.Diag(DRE->getBeginLoc(), diag::warn_uninit_self_reference_in_init) |
1014 | 67 | << VD->getDeclName() << VD->getLocation() << DRE->getSourceRange(); |
1015 | 67 | return true; |
1016 | 67 | } |
1017 | 70 | } |
1018 | | |
1019 | 1.12k | DiagUninitUse(S, VD, Use, false); |
1020 | 1.12k | } else { |
1021 | 5 | const BlockExpr *BE = cast<BlockExpr>(Use.getUser()); |
1022 | 5 | if (VD->getType()->isBlockPointerType() && !VD->hasAttr<BlocksAttr>()3 ) |
1023 | 3 | S.Diag(BE->getBeginLoc(), |
1024 | 3 | diag::warn_uninit_byref_blockvar_captured_by_block) |
1025 | 3 | << VD->getDeclName() |
1026 | 3 | << VD->getType().getQualifiers().hasObjCLifetime(); |
1027 | 2 | else |
1028 | 2 | DiagUninitUse(S, VD, Use, true); |
1029 | 5 | } |
1030 | | |
1031 | | // Report where the variable was declared when the use wasn't within |
1032 | | // the initializer of that declaration & we didn't already suggest |
1033 | | // an initialization fixit. |
1034 | 1.12k | if (!SuggestInitializationFixit(S, VD)) |
1035 | 10 | S.Diag(VD->getBeginLoc(), diag::note_var_declared_here) |
1036 | 10 | << VD->getDeclName(); |
1037 | | |
1038 | 1.12k | return true; |
1039 | 1.19k | } |
1040 | | |
1041 | | namespace { |
1042 | | class FallthroughMapper : public RecursiveASTVisitor<FallthroughMapper> { |
1043 | | public: |
1044 | | FallthroughMapper(Sema &S) |
1045 | | : FoundSwitchStatements(false), |
1046 | 124 | S(S) { |
1047 | 124 | } |
1048 | | |
1049 | 124 | bool foundSwitchStatements() const { return FoundSwitchStatements; } |
1050 | | |
1051 | 54 | void markFallthroughVisited(const AttributedStmt *Stmt) { |
1052 | 54 | bool Found = FallthroughStmts.erase(Stmt); |
1053 | 54 | assert(Found); |
1054 | 0 | (void)Found; |
1055 | 54 | } |
1056 | | |
1057 | | typedef llvm::SmallPtrSet<const AttributedStmt*, 8> AttrStmts; |
1058 | | |
1059 | 98 | const AttrStmts &getFallthroughStmts() const { |
1060 | 98 | return FallthroughStmts; |
1061 | 98 | } |
1062 | | |
1063 | 79 | void fillReachableBlocks(CFG *Cfg) { |
1064 | 79 | assert(ReachableBlocks.empty() && "ReachableBlocks already filled"); |
1065 | 0 | std::deque<const CFGBlock *> BlockQueue; |
1066 | | |
1067 | 79 | ReachableBlocks.insert(&Cfg->getEntry()); |
1068 | 79 | BlockQueue.push_back(&Cfg->getEntry()); |
1069 | | // Mark all case blocks reachable to avoid problems with switching on |
1070 | | // constants, covered enums, etc. |
1071 | | // These blocks can contain fall-through annotations, and we don't want to |
1072 | | // issue a warn_fallthrough_attr_unreachable for them. |
1073 | 690 | for (const auto *B : *Cfg) { |
1074 | 690 | const Stmt *L = B->getLabel(); |
1075 | 690 | if (L && isa<SwitchCase>(L)282 && ReachableBlocks.insert(B).second279 ) |
1076 | 279 | BlockQueue.push_back(B); |
1077 | 690 | } |
1078 | | |
1079 | 731 | while (!BlockQueue.empty()) { |
1080 | 652 | const CFGBlock *P = BlockQueue.front(); |
1081 | 652 | BlockQueue.pop_front(); |
1082 | 874 | for (const CFGBlock *B : P->succs()) { |
1083 | 874 | if (B && ReachableBlocks.insert(B).second849 ) |
1084 | 294 | BlockQueue.push_back(B); |
1085 | 874 | } |
1086 | 652 | } |
1087 | 79 | } |
1088 | | |
1089 | | bool checkFallThroughIntoBlock(const CFGBlock &B, int &AnnotatedCnt, |
1090 | 279 | bool IsTemplateInstantiation) { |
1091 | 279 | assert(!ReachableBlocks.empty() && "ReachableBlocks empty"); |
1092 | | |
1093 | 0 | int UnannotatedCnt = 0; |
1094 | 279 | AnnotatedCnt = 0; |
1095 | | |
1096 | 279 | std::deque<const CFGBlock*> BlockQueue(B.pred_begin(), B.pred_end()); |
1097 | 733 | while (!BlockQueue.empty()) { |
1098 | 454 | const CFGBlock *P = BlockQueue.front(); |
1099 | 454 | BlockQueue.pop_front(); |
1100 | 454 | if (!P) continue7 ; |
1101 | | |
1102 | 447 | const Stmt *Term = P->getTerminatorStmt(); |
1103 | 447 | if (Term && isa<SwitchStmt>(Term)302 ) |
1104 | 277 | continue; // Switch statement, good. |
1105 | | |
1106 | 170 | const SwitchCase *SW = dyn_cast_or_null<SwitchCase>(P->getLabel()); |
1107 | 170 | if (SW && SW->getSubStmt() == B.getLabel()126 && P->begin() == P->end()5 ) |
1108 | 5 | continue; // Previous case label has no statements, good. |
1109 | | |
1110 | 165 | const LabelStmt *L = dyn_cast_or_null<LabelStmt>(P->getLabel()); |
1111 | 165 | if (L && L->getSubStmt() == B.getLabel()3 && P->begin() == P->end()3 ) |
1112 | 3 | continue; // Case label is preceded with a normal label, good. |
1113 | | |
1114 | 162 | if (!ReachableBlocks.count(P)) { |
1115 | 36 | for (const CFGElement &Elem : llvm::reverse(*P)) { |
1116 | 36 | if (Optional<CFGStmt> CS = Elem.getAs<CFGStmt>()) { |
1117 | 34 | if (const AttributedStmt *AS = asFallThroughAttr(CS->getStmt())) { |
1118 | | // Don't issue a warning for an unreachable fallthrough |
1119 | | // attribute in template instantiations as it may not be |
1120 | | // unreachable in all instantiations of the template. |
1121 | 10 | if (!IsTemplateInstantiation) |
1122 | 9 | S.Diag(AS->getBeginLoc(), |
1123 | 9 | diag::warn_unreachable_fallthrough_attr); |
1124 | 10 | markFallthroughVisited(AS); |
1125 | 10 | ++AnnotatedCnt; |
1126 | 10 | break; |
1127 | 10 | } |
1128 | | // Don't care about other unreachable statements. |
1129 | 34 | } |
1130 | 36 | } |
1131 | | // If there are no unreachable statements, this may be a special |
1132 | | // case in CFG: |
1133 | | // case X: { |
1134 | | // A a; // A has a destructor. |
1135 | | // break; |
1136 | | // } |
1137 | | // // <<<< This place is represented by a 'hanging' CFG block. |
1138 | | // case Y: |
1139 | 22 | continue; |
1140 | 22 | } |
1141 | | |
1142 | 140 | const Stmt *LastStmt = getLastStmt(*P); |
1143 | 140 | if (const AttributedStmt *AS = asFallThroughAttr(LastStmt)) { |
1144 | 44 | markFallthroughVisited(AS); |
1145 | 44 | ++AnnotatedCnt; |
1146 | 44 | continue; // Fallthrough annotation, good. |
1147 | 44 | } |
1148 | | |
1149 | 96 | if (!LastStmt) { // This block contains no executable statements. |
1150 | | // Traverse its predecessors. |
1151 | 2 | std::copy(P->pred_begin(), P->pred_end(), |
1152 | 2 | std::back_inserter(BlockQueue)); |
1153 | 2 | continue; |
1154 | 2 | } |
1155 | | |
1156 | 94 | ++UnannotatedCnt; |
1157 | 94 | } |
1158 | 279 | return !!UnannotatedCnt; |
1159 | 279 | } |
1160 | | |
1161 | | // RecursiveASTVisitor setup. |
1162 | 13 | bool shouldWalkTypesOfTypeLocs() const { return false; } |
1163 | | |
1164 | 75 | bool VisitAttributedStmt(AttributedStmt *S) { |
1165 | 75 | if (asFallThroughAttr(S)) |
1166 | 74 | FallthroughStmts.insert(S); |
1167 | 75 | return true; |
1168 | 75 | } |
1169 | | |
1170 | 104 | bool VisitSwitchStmt(SwitchStmt *S) { |
1171 | 104 | FoundSwitchStatements = true; |
1172 | 104 | return true; |
1173 | 104 | } |
1174 | | |
1175 | | // We don't want to traverse local type declarations. We analyze their |
1176 | | // methods separately. |
1177 | 27 | bool TraverseDecl(Decl *D) { return true; } |
1178 | | |
1179 | | // We analyze lambda bodies separately. Skip them here. |
1180 | 1 | bool TraverseLambdaExpr(LambdaExpr *LE) { |
1181 | | // Traverse the captures, but not the body. |
1182 | 1 | for (const auto C : zip(LE->captures(), LE->capture_inits())) |
1183 | 0 | TraverseLambdaCapture(LE, &std::get<0>(C), std::get<1>(C)); |
1184 | 1 | return true; |
1185 | 1 | } |
1186 | | |
1187 | | private: |
1188 | | |
1189 | 249 | static const AttributedStmt *asFallThroughAttr(const Stmt *S) { |
1190 | 249 | if (const AttributedStmt *AS = dyn_cast_or_null<AttributedStmt>(S)) { |
1191 | 129 | if (hasSpecificAttr<FallThroughAttr>(AS->getAttrs())) |
1192 | 128 | return AS; |
1193 | 129 | } |
1194 | 121 | return nullptr; |
1195 | 249 | } |
1196 | | |
1197 | 140 | static const Stmt *getLastStmt(const CFGBlock &B) { |
1198 | 140 | if (const Stmt *Term = B.getTerminatorStmt()) |
1199 | 21 | return Term; |
1200 | 119 | for (const CFGElement &Elem : llvm::reverse(B)) |
1201 | 113 | if (Optional<CFGStmt> CS = Elem.getAs<CFGStmt>()) |
1202 | 113 | return CS->getStmt(); |
1203 | | // Workaround to detect a statement thrown out by CFGBuilder: |
1204 | | // case X: {} case Y: |
1205 | | // case X: ; case Y: |
1206 | 6 | if (const SwitchCase *SW = dyn_cast_or_null<SwitchCase>(B.getLabel())) |
1207 | 4 | if (!isa<SwitchCase>(SW->getSubStmt())) |
1208 | 4 | return SW->getSubStmt(); |
1209 | | |
1210 | 2 | return nullptr; |
1211 | 6 | } |
1212 | | |
1213 | | bool FoundSwitchStatements; |
1214 | | AttrStmts FallthroughStmts; |
1215 | | Sema &S; |
1216 | | llvm::SmallPtrSet<const CFGBlock *, 16> ReachableBlocks; |
1217 | | }; |
1218 | | } // anonymous namespace |
1219 | | |
1220 | | static StringRef getFallthroughAttrSpelling(Preprocessor &PP, |
1221 | 69 | SourceLocation Loc) { |
1222 | 69 | TokenValue FallthroughTokens[] = { |
1223 | 69 | tok::l_square, tok::l_square, |
1224 | 69 | PP.getIdentifierInfo("fallthrough"), |
1225 | 69 | tok::r_square, tok::r_square |
1226 | 69 | }; |
1227 | | |
1228 | 69 | TokenValue ClangFallthroughTokens[] = { |
1229 | 69 | tok::l_square, tok::l_square, PP.getIdentifierInfo("clang"), |
1230 | 69 | tok::coloncolon, PP.getIdentifierInfo("fallthrough"), |
1231 | 69 | tok::r_square, tok::r_square |
1232 | 69 | }; |
1233 | | |
1234 | 69 | bool PreferClangAttr = !PP.getLangOpts().CPlusPlus17 && !PP.getLangOpts().C2x43 ; |
1235 | | |
1236 | 69 | StringRef MacroName; |
1237 | 69 | if (PreferClangAttr) |
1238 | 42 | MacroName = PP.getLastMacroWithSpelling(Loc, ClangFallthroughTokens); |
1239 | 69 | if (MacroName.empty()) |
1240 | 62 | MacroName = PP.getLastMacroWithSpelling(Loc, FallthroughTokens); |
1241 | 69 | if (MacroName.empty() && !PreferClangAttr54 ) |
1242 | 22 | MacroName = PP.getLastMacroWithSpelling(Loc, ClangFallthroughTokens); |
1243 | 69 | if (MacroName.empty()) { |
1244 | 44 | if (!PreferClangAttr) |
1245 | 12 | MacroName = "[[fallthrough]]"; |
1246 | 32 | else if (PP.getLangOpts().CPlusPlus) |
1247 | 25 | MacroName = "[[clang::fallthrough]]"; |
1248 | 7 | else |
1249 | 7 | MacroName = "__attribute__((fallthrough))"; |
1250 | 44 | } |
1251 | 69 | return MacroName; |
1252 | 69 | } |
1253 | | |
1254 | | static void DiagnoseSwitchLabelsFallthrough(Sema &S, AnalysisDeclContext &AC, |
1255 | 124 | bool PerFunction) { |
1256 | 124 | FallthroughMapper FM(S); |
1257 | 124 | FM.TraverseStmt(AC.getBody()); |
1258 | | |
1259 | 124 | if (!FM.foundSwitchStatements()) |
1260 | 44 | return; |
1261 | | |
1262 | 80 | if (PerFunction && FM.getFallthroughStmts().empty()19 ) |
1263 | 1 | return; |
1264 | | |
1265 | 79 | CFG *Cfg = AC.getCFG(); |
1266 | | |
1267 | 79 | if (!Cfg) |
1268 | 0 | return; |
1269 | | |
1270 | 79 | FM.fillReachableBlocks(Cfg); |
1271 | | |
1272 | 690 | for (const CFGBlock *B : llvm::reverse(*Cfg)) { |
1273 | 690 | const Stmt *Label = B->getLabel(); |
1274 | | |
1275 | 690 | if (!isa_and_nonnull<SwitchCase>(Label)) |
1276 | 411 | continue; |
1277 | | |
1278 | 279 | int AnnotatedCnt; |
1279 | | |
1280 | 279 | bool IsTemplateInstantiation = false; |
1281 | 279 | if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(AC.getDecl())) |
1282 | 276 | IsTemplateInstantiation = Function->isTemplateInstantiation(); |
1283 | 279 | if (!FM.checkFallThroughIntoBlock(*B, AnnotatedCnt, |
1284 | 279 | IsTemplateInstantiation)) |
1285 | 193 | continue; |
1286 | | |
1287 | 86 | S.Diag(Label->getBeginLoc(), |
1288 | 86 | PerFunction ? diag::warn_unannotated_fallthrough_per_function14 |
1289 | 86 | : diag::warn_unannotated_fallthrough72 ); |
1290 | | |
1291 | 86 | if (!AnnotatedCnt) { |
1292 | 85 | SourceLocation L = Label->getBeginLoc(); |
1293 | 85 | if (L.isMacroID()) |
1294 | 10 | continue; |
1295 | | |
1296 | 75 | const Stmt *Term = B->getTerminatorStmt(); |
1297 | | // Skip empty cases. |
1298 | 121 | while (B->empty() && !Term52 && B->succ_size() == 146 ) { |
1299 | 46 | B = *B->succ_begin(); |
1300 | 46 | Term = B->getTerminatorStmt(); |
1301 | 46 | } |
1302 | 75 | if (!(B->empty() && Term6 && isa<BreakStmt>(Term)6 )) { |
1303 | 69 | Preprocessor &PP = S.getPreprocessor(); |
1304 | 69 | StringRef AnnotationSpelling = getFallthroughAttrSpelling(PP, L); |
1305 | 69 | SmallString<64> TextToInsert(AnnotationSpelling); |
1306 | 69 | TextToInsert += "; "; |
1307 | 69 | S.Diag(L, diag::note_insert_fallthrough_fixit) |
1308 | 69 | << AnnotationSpelling |
1309 | 69 | << FixItHint::CreateInsertion(L, TextToInsert); |
1310 | 69 | } |
1311 | 75 | S.Diag(L, diag::note_insert_break_fixit) |
1312 | 75 | << FixItHint::CreateInsertion(L, "break; "); |
1313 | 75 | } |
1314 | 86 | } |
1315 | | |
1316 | 79 | for (const auto *F : FM.getFallthroughStmts()) |
1317 | 20 | S.Diag(F->getBeginLoc(), diag::err_fallthrough_attr_invalid_placement); |
1318 | 79 | } |
1319 | | |
1320 | | static bool isInLoop(const ASTContext &Ctx, const ParentMap &PM, |
1321 | 69 | const Stmt *S) { |
1322 | 69 | assert(S); |
1323 | | |
1324 | 417 | do { |
1325 | 417 | switch (S->getStmtClass()) { |
1326 | 2 | case Stmt::ForStmtClass: |
1327 | 6 | case Stmt::WhileStmtClass: |
1328 | 8 | case Stmt::CXXForRangeStmtClass: |
1329 | 18 | case Stmt::ObjCForCollectionStmtClass: |
1330 | 18 | return true; |
1331 | 4 | case Stmt::DoStmtClass: { |
1332 | 4 | Expr::EvalResult Result; |
1333 | 4 | if (!cast<DoStmt>(S)->getCond()->EvaluateAsInt(Result, Ctx)) |
1334 | 2 | return true; |
1335 | 2 | return Result.Val.getInt().getBoolValue(); |
1336 | 4 | } |
1337 | 395 | default: |
1338 | 395 | break; |
1339 | 417 | } |
1340 | 417 | } while ((S = PM.getParent(S))395 ); |
1341 | | |
1342 | 47 | return false; |
1343 | 69 | } |
1344 | | |
1345 | | static void diagnoseRepeatedUseOfWeak(Sema &S, |
1346 | | const sema::FunctionScopeInfo *CurFn, |
1347 | | const Decl *D, |
1348 | 112 | const ParentMap &PM) { |
1349 | 112 | typedef sema::FunctionScopeInfo::WeakObjectProfileTy WeakObjectProfileTy; |
1350 | 112 | typedef sema::FunctionScopeInfo::WeakObjectUseMap WeakObjectUseMap; |
1351 | 112 | typedef sema::FunctionScopeInfo::WeakUseVector WeakUseVector; |
1352 | 112 | typedef std::pair<const Stmt *, WeakObjectUseMap::const_iterator> |
1353 | 112 | StmtUsesPair; |
1354 | | |
1355 | 112 | ASTContext &Ctx = S.getASTContext(); |
1356 | | |
1357 | 112 | const WeakObjectUseMap &WeakMap = CurFn->getWeakObjectUses(); |
1358 | | |
1359 | | // Extract all weak objects that are referenced more than once. |
1360 | 112 | SmallVector<StmtUsesPair, 8> UsesByStmt; |
1361 | 112 | for (WeakObjectUseMap::const_iterator I = WeakMap.begin(), E = WeakMap.end(); |
1362 | 267 | I != E; ++I155 ) { |
1363 | 155 | const WeakUseVector &Uses = I->second; |
1364 | | |
1365 | | // Find the first read of the weak object. |
1366 | 155 | WeakUseVector::const_iterator UI = Uses.begin(), UE = Uses.end(); |
1367 | 217 | for ( ; UI != UE; ++UI62 ) { |
1368 | 197 | if (UI->isUnsafe()) |
1369 | 135 | break; |
1370 | 197 | } |
1371 | | |
1372 | | // If there were only writes to this object, don't warn. |
1373 | 155 | if (UI == UE) |
1374 | 20 | continue; |
1375 | | |
1376 | | // If there was only one read, followed by any number of writes, and the |
1377 | | // read is not within a loop, don't warn. Additionally, don't warn in a |
1378 | | // loop if the base object is a local variable -- local variables are often |
1379 | | // changed in loops. |
1380 | 135 | if (UI == Uses.begin()) { |
1381 | 117 | WeakUseVector::const_iterator UI2 = UI; |
1382 | 143 | for (++UI2; UI2 != UE; ++UI226 ) |
1383 | 74 | if (UI2->isUnsafe()) |
1384 | 48 | break; |
1385 | | |
1386 | 117 | if (UI2 == UE) { |
1387 | 69 | if (!isInLoop(Ctx, PM, UI->getUseExpr())) |
1388 | 49 | continue; |
1389 | | |
1390 | 20 | const WeakObjectProfileTy &Profile = I->first; |
1391 | 20 | if (!Profile.isExactProfile()) |
1392 | 2 | continue; |
1393 | | |
1394 | 18 | const NamedDecl *Base = Profile.getBase(); |
1395 | 18 | if (!Base) |
1396 | 2 | Base = Profile.getProperty(); |
1397 | 18 | assert(Base && "A profile always has a base or property."); |
1398 | | |
1399 | 18 | if (const VarDecl *BaseVar = dyn_cast<VarDecl>(Base)) |
1400 | 18 | if (BaseVar->hasLocalStorage() && !isa<ParmVarDecl>(Base)16 ) |
1401 | 2 | continue; |
1402 | 18 | } |
1403 | 117 | } |
1404 | | |
1405 | 82 | UsesByStmt.push_back(StmtUsesPair(UI->getUseExpr(), I)); |
1406 | 82 | } |
1407 | | |
1408 | 112 | if (UsesByStmt.empty()) |
1409 | 46 | return; |
1410 | | |
1411 | | // Sort by first use so that we emit the warnings in a deterministic order. |
1412 | 66 | SourceManager &SM = S.getSourceManager(); |
1413 | 66 | llvm::sort(UsesByStmt, |
1414 | 66 | [&SM](const StmtUsesPair &LHS, const StmtUsesPair &RHS) { |
1415 | 24 | return SM.isBeforeInTranslationUnit(LHS.first->getBeginLoc(), |
1416 | 24 | RHS.first->getBeginLoc()); |
1417 | 24 | }); |
1418 | | |
1419 | | // Classify the current code body for better warning text. |
1420 | | // This enum should stay in sync with the cases in |
1421 | | // warn_arc_repeated_use_of_weak and warn_arc_possible_repeated_use_of_weak. |
1422 | | // FIXME: Should we use a common classification enum and the same set of |
1423 | | // possibilities all throughout Sema? |
1424 | 66 | enum { |
1425 | 66 | Function, |
1426 | 66 | Method, |
1427 | 66 | Block, |
1428 | 66 | Lambda |
1429 | 66 | } FunctionKind; |
1430 | | |
1431 | 66 | if (isa<sema::BlockScopeInfo>(CurFn)) |
1432 | 2 | FunctionKind = Block; |
1433 | 64 | else if (isa<sema::LambdaScopeInfo>(CurFn)) |
1434 | 0 | FunctionKind = Lambda; |
1435 | 64 | else if (isa<ObjCMethodDecl>(D)) |
1436 | 6 | FunctionKind = Method; |
1437 | 58 | else |
1438 | 58 | FunctionKind = Function; |
1439 | | |
1440 | | // Iterate through the sorted problems and emit warnings for each. |
1441 | 82 | for (const auto &P : UsesByStmt) { |
1442 | 82 | const Stmt *FirstRead = P.first; |
1443 | 82 | const WeakObjectProfileTy &Key = P.second->first; |
1444 | 82 | const WeakUseVector &Uses = P.second->second; |
1445 | | |
1446 | | // For complicated expressions like 'a.b.c' and 'x.b.c', WeakObjectProfileTy |
1447 | | // may not contain enough information to determine that these are different |
1448 | | // properties. We can only be 100% sure of a repeated use in certain cases, |
1449 | | // and we adjust the diagnostic kind accordingly so that the less certain |
1450 | | // case can be turned off if it is too noisy. |
1451 | 82 | unsigned DiagKind; |
1452 | 82 | if (Key.isExactProfile()) |
1453 | 68 | DiagKind = diag::warn_arc_repeated_use_of_weak; |
1454 | 14 | else |
1455 | 14 | DiagKind = diag::warn_arc_possible_repeated_use_of_weak; |
1456 | | |
1457 | | // Classify the weak object being accessed for better warning text. |
1458 | | // This enum should stay in sync with the cases in |
1459 | | // warn_arc_repeated_use_of_weak and warn_arc_possible_repeated_use_of_weak. |
1460 | 82 | enum { |
1461 | 82 | Variable, |
1462 | 82 | Property, |
1463 | 82 | ImplicitProperty, |
1464 | 82 | Ivar |
1465 | 82 | } ObjectKind; |
1466 | | |
1467 | 82 | const NamedDecl *KeyProp = Key.getProperty(); |
1468 | 82 | if (isa<VarDecl>(KeyProp)) |
1469 | 6 | ObjectKind = Variable; |
1470 | 76 | else if (isa<ObjCPropertyDecl>(KeyProp)) |
1471 | 64 | ObjectKind = Property; |
1472 | 12 | else if (isa<ObjCMethodDecl>(KeyProp)) |
1473 | 4 | ObjectKind = ImplicitProperty; |
1474 | 8 | else if (isa<ObjCIvarDecl>(KeyProp)) |
1475 | 8 | ObjectKind = Ivar; |
1476 | 0 | else |
1477 | 0 | llvm_unreachable("Unexpected weak object kind!"); |
1478 | | |
1479 | | // Do not warn about IBOutlet weak property receivers being set to null |
1480 | | // since they are typically only used from the main thread. |
1481 | 82 | if (const ObjCPropertyDecl *Prop = dyn_cast<ObjCPropertyDecl>(KeyProp)) |
1482 | 64 | if (Prop->hasAttr<IBOutletAttr>()) |
1483 | 4 | continue; |
1484 | | |
1485 | | // Show the first time the object was read. |
1486 | 78 | S.Diag(FirstRead->getBeginLoc(), DiagKind) |
1487 | 78 | << int(ObjectKind) << KeyProp << int(FunctionKind) |
1488 | 78 | << FirstRead->getSourceRange(); |
1489 | | |
1490 | | // Print all the other accesses as notes. |
1491 | 164 | for (const auto &Use : Uses) { |
1492 | 164 | if (Use.getUseExpr() == FirstRead) |
1493 | 78 | continue; |
1494 | 86 | S.Diag(Use.getUseExpr()->getBeginLoc(), |
1495 | 86 | diag::note_arc_weak_also_accessed_here) |
1496 | 86 | << Use.getUseExpr()->getSourceRange(); |
1497 | 86 | } |
1498 | 78 | } |
1499 | 66 | } |
1500 | | |
1501 | | namespace clang { |
1502 | | namespace { |
1503 | | typedef SmallVector<PartialDiagnosticAt, 1> OptionalNotes; |
1504 | | typedef std::pair<PartialDiagnosticAt, OptionalNotes> DelayedDiag; |
1505 | | typedef std::list<DelayedDiag> DiagList; |
1506 | | |
1507 | | struct SortDiagBySourceLocation { |
1508 | | SourceManager &SM; |
1509 | 2.34k | SortDiagBySourceLocation(SourceManager &SM) : SM(SM) {} |
1510 | | |
1511 | 2.74k | bool operator()(const DelayedDiag &left, const DelayedDiag &right) { |
1512 | | // Although this call will be slow, this is only called when outputting |
1513 | | // multiple warnings. |
1514 | 2.74k | return SM.isBeforeInTranslationUnit(left.first.first, right.first.first); |
1515 | 2.74k | } |
1516 | | }; |
1517 | | } // anonymous namespace |
1518 | | } // namespace clang |
1519 | | |
1520 | | namespace { |
1521 | | class UninitValsDiagReporter : public UninitVariablesHandler { |
1522 | | Sema &S; |
1523 | | typedef SmallVector<UninitUse, 2> UsesVec; |
1524 | | typedef llvm::PointerIntPair<UsesVec *, 1, bool> MappedType; |
1525 | | // Prefer using MapVector to DenseMap, so that iteration order will be |
1526 | | // the same as insertion order. This is needed to obtain a deterministic |
1527 | | // order of diagnostics when calling flushDiagnostics(). |
1528 | | typedef llvm::MapVector<const VarDecl *, MappedType> UsesMap; |
1529 | | UsesMap uses; |
1530 | | UsesMap constRefUses; |
1531 | | |
1532 | | public: |
1533 | 58.3k | UninitValsDiagReporter(Sema &S) : S(S) {} |
1534 | 58.3k | ~UninitValsDiagReporter() override { flushDiagnostics(); } |
1535 | | |
1536 | 2.31k | MappedType &getUses(UsesMap &um, const VarDecl *vd) { |
1537 | 2.31k | MappedType &V = um[vd]; |
1538 | 2.31k | if (!V.getPointer()) |
1539 | 1.22k | V.setPointer(new UsesVec()); |
1540 | 2.31k | return V; |
1541 | 2.31k | } |
1542 | | |
1543 | | void handleUseOfUninitVariable(const VarDecl *vd, |
1544 | 2.28k | const UninitUse &use) override { |
1545 | 2.28k | getUses(uses, vd).getPointer()->push_back(use); |
1546 | 2.28k | } |
1547 | | |
1548 | | void handleConstRefUseOfUninitVariable(const VarDecl *vd, |
1549 | 15 | const UninitUse &use) override { |
1550 | 15 | getUses(constRefUses, vd).getPointer()->push_back(use); |
1551 | 15 | } |
1552 | | |
1553 | 9 | void handleSelfInit(const VarDecl *vd) override { |
1554 | 9 | getUses(uses, vd).setInt(true); |
1555 | 9 | getUses(constRefUses, vd).setInt(true); |
1556 | 9 | } |
1557 | | |
1558 | 58.3k | void flushDiagnostics() { |
1559 | 58.3k | for (const auto &P : uses) { |
1560 | 1.19k | const VarDecl *vd = P.first; |
1561 | 1.19k | const MappedType &V = P.second; |
1562 | | |
1563 | 1.19k | UsesVec *vec = V.getPointer(); |
1564 | 1.19k | bool hasSelfInit = V.getInt(); |
1565 | | |
1566 | | // Specially handle the case where we have uses of an uninitialized |
1567 | | // variable, but the root cause is an idiomatic self-init. We want |
1568 | | // to report the diagnostic at the self-init since that is the root cause. |
1569 | 1.19k | if (!vec->empty() && hasSelfInit1.19k && hasAlwaysUninitializedUse(vec)4 ) |
1570 | 2 | DiagnoseUninitializedUse(S, vd, |
1571 | 2 | UninitUse(vd->getInit()->IgnoreParenCasts(), |
1572 | 2 | /* isAlwaysUninit */ true), |
1573 | 2 | /* alwaysReportSelfInit */ true); |
1574 | 1.19k | else { |
1575 | | // Sort the uses by their SourceLocations. While not strictly |
1576 | | // guaranteed to produce them in line/column order, this will provide |
1577 | | // a stable ordering. |
1578 | 1.19k | llvm::sort(vec->begin(), vec->end(), |
1579 | 1.19k | [](const UninitUse &a, const UninitUse &b) { |
1580 | | // Prefer a more confident report over a less confident one. |
1581 | 1.09k | if (a.getKind() != b.getKind()) |
1582 | 5 | return a.getKind() > b.getKind(); |
1583 | 1.08k | return a.getUser()->getBeginLoc() < b.getUser()->getBeginLoc(); |
1584 | 1.09k | }); |
1585 | | |
1586 | 1.19k | for (const auto &U : *vec) { |
1587 | | // If we have self-init, downgrade all uses to 'may be uninitialized'. |
1588 | 1.19k | UninitUse Use = hasSelfInit ? UninitUse(U.getUser(), false)2 : U1.18k ; |
1589 | | |
1590 | 1.19k | if (DiagnoseUninitializedUse(S, vd, Use)) |
1591 | | // Skip further diagnostics for this variable. We try to warn only |
1592 | | // on the first point at which a variable is used uninitialized. |
1593 | 1.19k | break; |
1594 | 1.19k | } |
1595 | 1.19k | } |
1596 | | |
1597 | | // Release the uses vector. |
1598 | 1.19k | delete vec; |
1599 | 1.19k | } |
1600 | | |
1601 | 58.3k | uses.clear(); |
1602 | | |
1603 | | // Flush all const reference uses diags. |
1604 | 58.3k | for (const auto &P : constRefUses) { |
1605 | 23 | const VarDecl *vd = P.first; |
1606 | 23 | const MappedType &V = P.second; |
1607 | | |
1608 | 23 | UsesVec *vec = V.getPointer(); |
1609 | 23 | bool hasSelfInit = V.getInt(); |
1610 | | |
1611 | 23 | if (!vec->empty() && hasSelfInit15 && hasAlwaysUninitializedUse(vec)1 ) |
1612 | 1 | DiagnoseUninitializedUse(S, vd, |
1613 | 1 | UninitUse(vd->getInit()->IgnoreParenCasts(), |
1614 | 1 | /* isAlwaysUninit */ true), |
1615 | 1 | /* alwaysReportSelfInit */ true); |
1616 | 22 | else { |
1617 | 22 | for (const auto &U : *vec) { |
1618 | 14 | if (DiagnoseUninitializedConstRefUse(S, vd, U)) |
1619 | 14 | break; |
1620 | 14 | } |
1621 | 22 | } |
1622 | | |
1623 | | // Release the uses vector. |
1624 | 23 | delete vec; |
1625 | 23 | } |
1626 | | |
1627 | 58.3k | constRefUses.clear(); |
1628 | 58.3k | } |
1629 | | |
1630 | | private: |
1631 | 5 | static bool hasAlwaysUninitializedUse(const UsesVec* vec) { |
1632 | 5 | return llvm::any_of(*vec, [](const UninitUse &U) { |
1633 | 5 | return U.getKind() == UninitUse::Always || |
1634 | 5 | U.getKind() == UninitUse::AfterCall2 || |
1635 | 5 | U.getKind() == UninitUse::AfterDecl2 ; |
1636 | 5 | }); |
1637 | 5 | } |
1638 | | }; |
1639 | | |
1640 | | /// Inter-procedural data for the called-once checker. |
1641 | | class CalledOnceInterProceduralData { |
1642 | | public: |
1643 | | // Add the delayed warning for the given block. |
1644 | | void addDelayedWarning(const BlockDecl *Block, |
1645 | 8 | PartialDiagnosticAt &&Warning) { |
1646 | 8 | DelayedBlockWarnings[Block].emplace_back(std::move(Warning)); |
1647 | 8 | } |
1648 | | // Report all of the warnings we've gathered for the given block. |
1649 | 9 | void flushWarnings(const BlockDecl *Block, Sema &S) { |
1650 | 9 | for (const PartialDiagnosticAt &Delayed : DelayedBlockWarnings[Block]) |
1651 | 5 | S.Diag(Delayed.first, Delayed.second); |
1652 | | |
1653 | 9 | discardWarnings(Block); |
1654 | 9 | } |
1655 | | // Discard all of the warnings we've gathered for the given block. |
1656 | 16 | void discardWarnings(const BlockDecl *Block) { |
1657 | 16 | DelayedBlockWarnings.erase(Block); |
1658 | 16 | } |
1659 | | |
1660 | | private: |
1661 | | using DelayedDiagnostics = SmallVector<PartialDiagnosticAt, 2>; |
1662 | | llvm::DenseMap<const BlockDecl *, DelayedDiagnostics> DelayedBlockWarnings; |
1663 | | }; |
1664 | | |
1665 | | class CalledOnceCheckReporter : public CalledOnceCheckHandler { |
1666 | | public: |
1667 | | CalledOnceCheckReporter(Sema &S, CalledOnceInterProceduralData &Data) |
1668 | 10.5k | : S(S), Data(Data) {} |
1669 | | void handleDoubleCall(const ParmVarDecl *Parameter, const Expr *Call, |
1670 | | const Expr *PrevCall, bool IsCompletionHandler, |
1671 | 29 | bool Poised) override { |
1672 | 29 | auto DiagToReport = IsCompletionHandler |
1673 | 29 | ? diag::warn_completion_handler_called_twice7 |
1674 | 29 | : diag::warn_called_once_gets_called_twice22 ; |
1675 | 29 | S.Diag(Call->getBeginLoc(), DiagToReport) << Parameter; |
1676 | 29 | S.Diag(PrevCall->getBeginLoc(), diag::note_called_once_gets_called_twice) |
1677 | 29 | << Poised; |
1678 | 29 | } |
1679 | | |
1680 | | void handleNeverCalled(const ParmVarDecl *Parameter, |
1681 | 10 | bool IsCompletionHandler) override { |
1682 | 10 | auto DiagToReport = IsCompletionHandler |
1683 | 10 | ? diag::warn_completion_handler_never_called4 |
1684 | 10 | : diag::warn_called_once_never_called6 ; |
1685 | 10 | S.Diag(Parameter->getBeginLoc(), DiagToReport) |
1686 | 10 | << Parameter << /* Captured */ false; |
1687 | 10 | } |
1688 | | |
1689 | | void handleNeverCalled(const ParmVarDecl *Parameter, const Decl *Function, |
1690 | | const Stmt *Where, NeverCalledReason Reason, |
1691 | | bool IsCalledDirectly, |
1692 | 43 | bool IsCompletionHandler) override { |
1693 | 43 | auto DiagToReport = IsCompletionHandler |
1694 | 43 | ? diag::warn_completion_handler_never_called_when19 |
1695 | 43 | : diag::warn_called_once_never_called_when24 ; |
1696 | 43 | PartialDiagnosticAt Warning(Where->getBeginLoc(), S.PDiag(DiagToReport) |
1697 | 43 | << Parameter |
1698 | 43 | << IsCalledDirectly |
1699 | 43 | << (unsigned)Reason); |
1700 | | |
1701 | 43 | if (const auto *Block = dyn_cast<BlockDecl>(Function)) { |
1702 | | // We shouldn't report these warnings on blocks immediately |
1703 | 8 | Data.addDelayedWarning(Block, std::move(Warning)); |
1704 | 35 | } else { |
1705 | 35 | S.Diag(Warning.first, Warning.second); |
1706 | 35 | } |
1707 | 43 | } |
1708 | | |
1709 | | void handleCapturedNeverCalled(const ParmVarDecl *Parameter, |
1710 | | const Decl *Where, |
1711 | 0 | bool IsCompletionHandler) override { |
1712 | 0 | auto DiagToReport = IsCompletionHandler |
1713 | 0 | ? diag::warn_completion_handler_never_called |
1714 | 0 | : diag::warn_called_once_never_called; |
1715 | 0 | S.Diag(Where->getBeginLoc(), DiagToReport) |
1716 | 0 | << Parameter << /* Captured */ true; |
1717 | 0 | } |
1718 | | |
1719 | | void |
1720 | 9 | handleBlockThatIsGuaranteedToBeCalledOnce(const BlockDecl *Block) override { |
1721 | 9 | Data.flushWarnings(Block, S); |
1722 | 9 | } |
1723 | | |
1724 | 7 | void handleBlockWithNoGuarantees(const BlockDecl *Block) override { |
1725 | 7 | Data.discardWarnings(Block); |
1726 | 7 | } |
1727 | | |
1728 | | private: |
1729 | | Sema &S; |
1730 | | CalledOnceInterProceduralData &Data; |
1731 | | }; |
1732 | | |
1733 | | constexpr unsigned CalledOnceWarnings[] = { |
1734 | | diag::warn_called_once_never_called, |
1735 | | diag::warn_called_once_never_called_when, |
1736 | | diag::warn_called_once_gets_called_twice}; |
1737 | | |
1738 | | constexpr unsigned CompletionHandlerWarnings[]{ |
1739 | | diag::warn_completion_handler_never_called, |
1740 | | diag::warn_completion_handler_never_called_when, |
1741 | | diag::warn_completion_handler_called_twice}; |
1742 | | |
1743 | | bool shouldAnalyzeCalledOnceImpl(llvm::ArrayRef<unsigned> DiagIDs, |
1744 | | const DiagnosticsEngine &Diags, |
1745 | 21.1k | SourceLocation At) { |
1746 | 41.9k | return llvm::any_of(DiagIDs, [&Diags, At](unsigned DiagID) { |
1747 | 41.9k | return !Diags.isIgnored(DiagID, At); |
1748 | 41.9k | }); |
1749 | 21.1k | } |
1750 | | |
1751 | | bool shouldAnalyzeCalledOnceConventions(const DiagnosticsEngine &Diags, |
1752 | 10.5k | SourceLocation At) { |
1753 | 10.5k | return shouldAnalyzeCalledOnceImpl(CompletionHandlerWarnings, Diags, At); |
1754 | 10.5k | } |
1755 | | |
1756 | | bool shouldAnalyzeCalledOnceParameters(const DiagnosticsEngine &Diags, |
1757 | 10.5k | SourceLocation At) { |
1758 | 10.5k | return shouldAnalyzeCalledOnceImpl(CalledOnceWarnings, Diags, At) || |
1759 | 10.5k | shouldAnalyzeCalledOnceConventions(Diags, At)30 ; |
1760 | 10.5k | } |
1761 | | } // anonymous namespace |
1762 | | |
1763 | | //===----------------------------------------------------------------------===// |
1764 | | // -Wthread-safety |
1765 | | //===----------------------------------------------------------------------===// |
1766 | | namespace clang { |
1767 | | namespace threadSafety { |
1768 | | namespace { |
1769 | | class ThreadSafetyReporter : public clang::threadSafety::ThreadSafetyHandler { |
1770 | | Sema &S; |
1771 | | DiagList Warnings; |
1772 | | SourceLocation FunLocation, FunEndLocation; |
1773 | | |
1774 | | const FunctionDecl *CurrentFunction; |
1775 | | bool Verbose; |
1776 | | |
1777 | 2.58k | OptionalNotes getNotes() const { |
1778 | 2.58k | if (Verbose && CurrentFunction14 ) { |
1779 | 14 | PartialDiagnosticAt FNote(CurrentFunction->getBody()->getBeginLoc(), |
1780 | 14 | S.PDiag(diag::note_thread_warning_in_fun) |
1781 | 14 | << CurrentFunction); |
1782 | 14 | return OptionalNotes(1, FNote); |
1783 | 14 | } |
1784 | 2.56k | return OptionalNotes(); |
1785 | 2.58k | } |
1786 | | |
1787 | 450 | OptionalNotes getNotes(const PartialDiagnosticAt &Note) const { |
1788 | 450 | OptionalNotes ONS(1, Note); |
1789 | 450 | if (Verbose && CurrentFunction6 ) { |
1790 | 6 | PartialDiagnosticAt FNote(CurrentFunction->getBody()->getBeginLoc(), |
1791 | 6 | S.PDiag(diag::note_thread_warning_in_fun) |
1792 | 6 | << CurrentFunction); |
1793 | 6 | ONS.push_back(std::move(FNote)); |
1794 | 6 | } |
1795 | 450 | return ONS; |
1796 | 450 | } |
1797 | | |
1798 | | OptionalNotes getNotes(const PartialDiagnosticAt &Note1, |
1799 | 0 | const PartialDiagnosticAt &Note2) const { |
1800 | 0 | OptionalNotes ONS; |
1801 | 0 | ONS.push_back(Note1); |
1802 | 0 | ONS.push_back(Note2); |
1803 | 0 | if (Verbose && CurrentFunction) { |
1804 | 0 | PartialDiagnosticAt FNote(CurrentFunction->getBody()->getBeginLoc(), |
1805 | 0 | S.PDiag(diag::note_thread_warning_in_fun) |
1806 | 0 | << CurrentFunction); |
1807 | 0 | ONS.push_back(std::move(FNote)); |
1808 | 0 | } |
1809 | 0 | return ONS; |
1810 | 0 | } |
1811 | | |
1812 | 278 | OptionalNotes makeLockedHereNote(SourceLocation LocLocked, StringRef Kind) { |
1813 | 278 | return LocLocked.isValid() |
1814 | 278 | ? getNotes(PartialDiagnosticAt( |
1815 | 278 | LocLocked, S.PDiag(diag::note_locked_here) << Kind)) |
1816 | 278 | : getNotes()0 ; |
1817 | 278 | } |
1818 | | |
1819 | | OptionalNotes makeUnlockedHereNote(SourceLocation LocUnlocked, |
1820 | 106 | StringRef Kind) { |
1821 | 106 | return LocUnlocked.isValid() |
1822 | 106 | ? getNotes(PartialDiagnosticAt( |
1823 | 54 | LocUnlocked, S.PDiag(diag::note_unlocked_here) << Kind)) |
1824 | 106 | : getNotes()52 ; |
1825 | 106 | } |
1826 | | |
1827 | | public: |
1828 | | ThreadSafetyReporter(Sema &S, SourceLocation FL, SourceLocation FEL) |
1829 | | : S(S), FunLocation(FL), FunEndLocation(FEL), |
1830 | 2.25k | CurrentFunction(nullptr), Verbose(false) {} |
1831 | | |
1832 | 42 | void setVerbose(bool b) { Verbose = b; } |
1833 | | |
1834 | | /// Emit all buffered diagnostics in order of sourcelocation. |
1835 | | /// We need to output diagnostics produced while iterating through |
1836 | | /// the lockset in deterministic order, so this function orders diagnostics |
1837 | | /// and outputs them. |
1838 | 2.25k | void emitDiagnostics() { |
1839 | 2.25k | Warnings.sort(SortDiagBySourceLocation(S.getSourceManager())); |
1840 | 3.03k | for (const auto &Diag : Warnings) { |
1841 | 3.03k | S.Diag(Diag.first.first, Diag.first.second); |
1842 | 3.03k | for (const auto &Note : Diag.second) |
1843 | 470 | S.Diag(Note.first, Note.second); |
1844 | 3.03k | } |
1845 | 2.25k | } |
1846 | | |
1847 | 0 | void handleInvalidLockExp(SourceLocation Loc) override { |
1848 | 0 | PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_cannot_resolve_lock) |
1849 | 0 | << Loc); |
1850 | 0 | Warnings.emplace_back(std::move(Warning), getNotes()); |
1851 | 0 | } |
1852 | | |
1853 | | void handleUnmatchedUnlock(StringRef Kind, Name LockName, SourceLocation Loc, |
1854 | 106 | SourceLocation LocPreviousUnlock) override { |
1855 | 106 | if (Loc.isInvalid()) |
1856 | 0 | Loc = FunLocation; |
1857 | 106 | PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_unlock_but_no_lock) |
1858 | 106 | << Kind << LockName); |
1859 | 106 | Warnings.emplace_back(std::move(Warning), |
1860 | 106 | makeUnlockedHereNote(LocPreviousUnlock, Kind)); |
1861 | 106 | } |
1862 | | |
1863 | | void handleIncorrectUnlockKind(StringRef Kind, Name LockName, |
1864 | | LockKind Expected, LockKind Received, |
1865 | | SourceLocation LocLocked, |
1866 | 18 | SourceLocation LocUnlock) override { |
1867 | 18 | if (LocUnlock.isInvalid()) |
1868 | 0 | LocUnlock = FunLocation; |
1869 | 18 | PartialDiagnosticAt Warning( |
1870 | 18 | LocUnlock, S.PDiag(diag::warn_unlock_kind_mismatch) |
1871 | 18 | << Kind << LockName << Received << Expected); |
1872 | 18 | Warnings.emplace_back(std::move(Warning), |
1873 | 18 | makeLockedHereNote(LocLocked, Kind)); |
1874 | 18 | } |
1875 | | |
1876 | | void handleDoubleLock(StringRef Kind, Name LockName, SourceLocation LocLocked, |
1877 | 79 | SourceLocation LocDoubleLock) override { |
1878 | 79 | if (LocDoubleLock.isInvalid()) |
1879 | 0 | LocDoubleLock = FunLocation; |
1880 | 79 | PartialDiagnosticAt Warning(LocDoubleLock, S.PDiag(diag::warn_double_lock) |
1881 | 79 | << Kind << LockName); |
1882 | 79 | Warnings.emplace_back(std::move(Warning), |
1883 | 79 | makeLockedHereNote(LocLocked, Kind)); |
1884 | 79 | } |
1885 | | |
1886 | | void handleMutexHeldEndOfScope(StringRef Kind, Name LockName, |
1887 | | SourceLocation LocLocked, |
1888 | | SourceLocation LocEndOfScope, |
1889 | 181 | LockErrorKind LEK) override { |
1890 | 181 | unsigned DiagID = 0; |
1891 | 181 | switch (LEK) { |
1892 | 42 | case LEK_LockedSomePredecessors: |
1893 | 42 | DiagID = diag::warn_lock_some_predecessors; |
1894 | 42 | break; |
1895 | 42 | case LEK_LockedSomeLoopIterations: |
1896 | 42 | DiagID = diag::warn_expecting_lock_held_on_loop; |
1897 | 42 | break; |
1898 | 65 | case LEK_LockedAtEndOfFunction: |
1899 | 65 | DiagID = diag::warn_no_unlock; |
1900 | 65 | break; |
1901 | 32 | case LEK_NotLockedAtEndOfFunction: |
1902 | 32 | DiagID = diag::warn_expecting_locked; |
1903 | 32 | break; |
1904 | 181 | } |
1905 | 181 | if (LocEndOfScope.isInvalid()) |
1906 | 127 | LocEndOfScope = FunEndLocation; |
1907 | | |
1908 | 181 | PartialDiagnosticAt Warning(LocEndOfScope, S.PDiag(DiagID) << Kind |
1909 | 181 | << LockName); |
1910 | 181 | Warnings.emplace_back(std::move(Warning), |
1911 | 181 | makeLockedHereNote(LocLocked, Kind)); |
1912 | 181 | } |
1913 | | |
1914 | | void handleExclusiveAndShared(StringRef Kind, Name LockName, |
1915 | | SourceLocation Loc1, |
1916 | 36 | SourceLocation Loc2) override { |
1917 | 36 | PartialDiagnosticAt Warning(Loc1, |
1918 | 36 | S.PDiag(diag::warn_lock_exclusive_and_shared) |
1919 | 36 | << Kind << LockName); |
1920 | 36 | PartialDiagnosticAt Note(Loc2, S.PDiag(diag::note_lock_exclusive_and_shared) |
1921 | 36 | << Kind << LockName); |
1922 | 36 | Warnings.emplace_back(std::move(Warning), getNotes(Note)); |
1923 | 36 | } |
1924 | | |
1925 | | void handleNoMutexHeld(const NamedDecl *D, ProtectedOperationKind POK, |
1926 | 34 | AccessKind AK, SourceLocation Loc) override { |
1927 | 34 | assert((POK == POK_VarAccess || POK == POK_VarDereference) && |
1928 | 34 | "Only works for variables"); |
1929 | 34 | unsigned DiagID = POK == POK_VarAccess? |
1930 | 25 | diag::warn_variable_requires_any_lock: |
1931 | 34 | diag::warn_var_deref_requires_any_lock9 ; |
1932 | 34 | PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) |
1933 | 34 | << D << getLockKindFromAccessKind(AK)); |
1934 | 34 | Warnings.emplace_back(std::move(Warning), getNotes()); |
1935 | 34 | } |
1936 | | |
1937 | | void handleMutexNotHeld(StringRef Kind, const NamedDecl *D, |
1938 | | ProtectedOperationKind POK, Name LockName, |
1939 | | LockKind LK, SourceLocation Loc, |
1940 | 1.30k | Name *PossibleMatch) override { |
1941 | 1.30k | unsigned DiagID = 0; |
1942 | 1.30k | if (PossibleMatch) { |
1943 | 76 | switch (POK) { |
1944 | 56 | case POK_VarAccess: |
1945 | 56 | DiagID = diag::warn_variable_requires_lock_precise; |
1946 | 56 | break; |
1947 | 0 | case POK_VarDereference: |
1948 | 0 | DiagID = diag::warn_var_deref_requires_lock_precise; |
1949 | 0 | break; |
1950 | 20 | case POK_FunctionCall: |
1951 | 20 | DiagID = diag::warn_fun_requires_lock_precise; |
1952 | 20 | break; |
1953 | 0 | case POK_PassByRef: |
1954 | 0 | DiagID = diag::warn_guarded_pass_by_reference; |
1955 | 0 | break; |
1956 | 0 | case POK_PtPassByRef: |
1957 | 0 | DiagID = diag::warn_pt_guarded_pass_by_reference; |
1958 | 0 | break; |
1959 | 76 | } |
1960 | 76 | PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << Kind |
1961 | 76 | << D |
1962 | 76 | << LockName << LK); |
1963 | 76 | PartialDiagnosticAt Note(Loc, S.PDiag(diag::note_found_mutex_near_match) |
1964 | 76 | << *PossibleMatch); |
1965 | 76 | if (Verbose && POK == POK_VarAccess0 ) { |
1966 | 0 | PartialDiagnosticAt VNote(D->getLocation(), |
1967 | 0 | S.PDiag(diag::note_guarded_by_declared_here) |
1968 | 0 | << D->getDeclName()); |
1969 | 0 | Warnings.emplace_back(std::move(Warning), getNotes(Note, VNote)); |
1970 | 0 | } else |
1971 | 76 | Warnings.emplace_back(std::move(Warning), getNotes(Note)); |
1972 | 1.22k | } else { |
1973 | 1.22k | switch (POK) { |
1974 | 694 | case POK_VarAccess: |
1975 | 694 | DiagID = diag::warn_variable_requires_lock; |
1976 | 694 | break; |
1977 | 216 | case POK_VarDereference: |
1978 | 216 | DiagID = diag::warn_var_deref_requires_lock; |
1979 | 216 | break; |
1980 | 206 | case POK_FunctionCall: |
1981 | 206 | DiagID = diag::warn_fun_requires_lock; |
1982 | 206 | break; |
1983 | 88 | case POK_PassByRef: |
1984 | 88 | DiagID = diag::warn_guarded_pass_by_reference; |
1985 | 88 | break; |
1986 | 20 | case POK_PtPassByRef: |
1987 | 20 | DiagID = diag::warn_pt_guarded_pass_by_reference; |
1988 | 20 | break; |
1989 | 1.22k | } |
1990 | 1.22k | PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << Kind |
1991 | 1.22k | << D |
1992 | 1.22k | << LockName << LK); |
1993 | 1.22k | if (Verbose && POK == POK_VarAccess12 ) { |
1994 | 6 | PartialDiagnosticAt Note(D->getLocation(), |
1995 | 6 | S.PDiag(diag::note_guarded_by_declared_here)); |
1996 | 6 | Warnings.emplace_back(std::move(Warning), getNotes(Note)); |
1997 | 6 | } else |
1998 | 1.21k | Warnings.emplace_back(std::move(Warning), getNotes()); |
1999 | 1.22k | } |
2000 | 1.30k | } |
2001 | | |
2002 | | void handleNegativeNotHeld(StringRef Kind, Name LockName, Name Neg, |
2003 | 1.11k | SourceLocation Loc) override { |
2004 | 1.11k | PartialDiagnosticAt Warning(Loc, |
2005 | 1.11k | S.PDiag(diag::warn_acquire_requires_negative_cap) |
2006 | 1.11k | << Kind << LockName << Neg); |
2007 | 1.11k | Warnings.emplace_back(std::move(Warning), getNotes()); |
2008 | 1.11k | } |
2009 | | |
2010 | | void handleNegativeNotHeld(const NamedDecl *D, Name LockName, |
2011 | 14 | SourceLocation Loc) override { |
2012 | 14 | PartialDiagnosticAt Warning( |
2013 | 14 | Loc, S.PDiag(diag::warn_fun_requires_negative_cap) << D << LockName); |
2014 | 14 | Warnings.emplace_back(std::move(Warning), getNotes()); |
2015 | 14 | } |
2016 | | |
2017 | | void handleFunExcludesLock(StringRef Kind, Name FunName, Name LockName, |
2018 | 77 | SourceLocation Loc) override { |
2019 | 77 | PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_fun_excludes_mutex) |
2020 | 77 | << Kind << FunName << LockName); |
2021 | 77 | Warnings.emplace_back(std::move(Warning), getNotes()); |
2022 | 77 | } |
2023 | | |
2024 | | void handleLockAcquiredBefore(StringRef Kind, Name L1Name, Name L2Name, |
2025 | 49 | SourceLocation Loc) override { |
2026 | 49 | PartialDiagnosticAt Warning(Loc, |
2027 | 49 | S.PDiag(diag::warn_acquired_before) << Kind << L1Name << L2Name); |
2028 | 49 | Warnings.emplace_back(std::move(Warning), getNotes()); |
2029 | 49 | } |
2030 | | |
2031 | 20 | void handleBeforeAfterCycle(Name L1Name, SourceLocation Loc) override { |
2032 | 20 | PartialDiagnosticAt Warning(Loc, |
2033 | 20 | S.PDiag(diag::warn_acquired_before_after_cycle) << L1Name); |
2034 | 20 | Warnings.emplace_back(std::move(Warning), getNotes()); |
2035 | 20 | } |
2036 | | |
2037 | 2.13k | void enterFunction(const FunctionDecl* FD) override { |
2038 | 2.13k | CurrentFunction = FD; |
2039 | 2.13k | } |
2040 | | |
2041 | 2.07k | void leaveFunction(const FunctionDecl* FD) override { |
2042 | 2.07k | CurrentFunction = nullptr; |
2043 | 2.07k | } |
2044 | | }; |
2045 | | } // anonymous namespace |
2046 | | } // namespace threadSafety |
2047 | | } // namespace clang |
2048 | | |
2049 | | //===----------------------------------------------------------------------===// |
2050 | | // -Wconsumed |
2051 | | //===----------------------------------------------------------------------===// |
2052 | | |
2053 | | namespace clang { |
2054 | | namespace consumed { |
2055 | | namespace { |
2056 | | class ConsumedWarningsHandler : public ConsumedWarningsHandlerBase { |
2057 | | |
2058 | | Sema &S; |
2059 | | DiagList Warnings; |
2060 | | |
2061 | | public: |
2062 | | |
2063 | 98 | ConsumedWarningsHandler(Sema &S) : S(S) {} |
2064 | | |
2065 | 95 | void emitDiagnostics() override { |
2066 | 95 | Warnings.sort(SortDiagBySourceLocation(S.getSourceManager())); |
2067 | 110 | for (const auto &Diag : Warnings) { |
2068 | 110 | S.Diag(Diag.first.first, Diag.first.second); |
2069 | 110 | for (const auto &Note : Diag.second) |
2070 | 0 | S.Diag(Note.first, Note.second); |
2071 | 110 | } |
2072 | 95 | } |
2073 | | |
2074 | | void warnLoopStateMismatch(SourceLocation Loc, |
2075 | 2 | StringRef VariableName) override { |
2076 | 2 | PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_loop_state_mismatch) << |
2077 | 2 | VariableName); |
2078 | | |
2079 | 2 | Warnings.emplace_back(std::move(Warning), OptionalNotes()); |
2080 | 2 | } |
2081 | | |
2082 | | void warnParamReturnTypestateMismatch(SourceLocation Loc, |
2083 | | StringRef VariableName, |
2084 | | StringRef ExpectedState, |
2085 | 2 | StringRef ObservedState) override { |
2086 | | |
2087 | 2 | PartialDiagnosticAt Warning(Loc, S.PDiag( |
2088 | 2 | diag::warn_param_return_typestate_mismatch) << VariableName << |
2089 | 2 | ExpectedState << ObservedState); |
2090 | | |
2091 | 2 | Warnings.emplace_back(std::move(Warning), OptionalNotes()); |
2092 | 2 | } |
2093 | | |
2094 | | void warnParamTypestateMismatch(SourceLocation Loc, StringRef ExpectedState, |
2095 | 6 | StringRef ObservedState) override { |
2096 | | |
2097 | 6 | PartialDiagnosticAt Warning(Loc, S.PDiag( |
2098 | 6 | diag::warn_param_typestate_mismatch) << ExpectedState << ObservedState); |
2099 | | |
2100 | 6 | Warnings.emplace_back(std::move(Warning), OptionalNotes()); |
2101 | 6 | } |
2102 | | |
2103 | | void warnReturnTypestateForUnconsumableType(SourceLocation Loc, |
2104 | 1 | StringRef TypeName) override { |
2105 | 1 | PartialDiagnosticAt Warning(Loc, S.PDiag( |
2106 | 1 | diag::warn_return_typestate_for_unconsumable_type) << TypeName); |
2107 | | |
2108 | 1 | Warnings.emplace_back(std::move(Warning), OptionalNotes()); |
2109 | 1 | } |
2110 | | |
2111 | | void warnReturnTypestateMismatch(SourceLocation Loc, StringRef ExpectedState, |
2112 | 1 | StringRef ObservedState) override { |
2113 | | |
2114 | 1 | PartialDiagnosticAt Warning(Loc, S.PDiag( |
2115 | 1 | diag::warn_return_typestate_mismatch) << ExpectedState << ObservedState); |
2116 | | |
2117 | 1 | Warnings.emplace_back(std::move(Warning), OptionalNotes()); |
2118 | 1 | } |
2119 | | |
2120 | | void warnUseOfTempInInvalidState(StringRef MethodName, StringRef State, |
2121 | 4 | SourceLocation Loc) override { |
2122 | | |
2123 | 4 | PartialDiagnosticAt Warning(Loc, S.PDiag( |
2124 | 4 | diag::warn_use_of_temp_in_invalid_state) << MethodName << State); |
2125 | | |
2126 | 4 | Warnings.emplace_back(std::move(Warning), OptionalNotes()); |
2127 | 4 | } |
2128 | | |
2129 | | void warnUseInInvalidState(StringRef MethodName, StringRef VariableName, |
2130 | 94 | StringRef State, SourceLocation Loc) override { |
2131 | | |
2132 | 94 | PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_use_in_invalid_state) << |
2133 | 94 | MethodName << VariableName << State); |
2134 | | |
2135 | 94 | Warnings.emplace_back(std::move(Warning), OptionalNotes()); |
2136 | 94 | } |
2137 | | }; |
2138 | | } // anonymous namespace |
2139 | | } // namespace consumed |
2140 | | } // namespace clang |
2141 | | |
2142 | | //===----------------------------------------------------------------------===// |
2143 | | // AnalysisBasedWarnings - Worker object used by Sema to execute analysis-based |
2144 | | // warnings on a function, method, or block. |
2145 | | //===----------------------------------------------------------------------===// |
2146 | | |
2147 | 88.2k | sema::AnalysisBasedWarnings::Policy::Policy() { |
2148 | 88.2k | enableCheckFallThrough = 1; |
2149 | 88.2k | enableCheckUnreachable = 0; |
2150 | 88.2k | enableThreadSafetyAnalysis = 0; |
2151 | 88.2k | enableConsumedAnalysis = 0; |
2152 | 88.2k | } |
2153 | | |
2154 | | /// InterProceduralData aims to be a storage of whatever data should be passed |
2155 | | /// between analyses of different functions. |
2156 | | /// |
2157 | | /// At the moment, its primary goal is to make the information gathered during |
2158 | | /// the analysis of the blocks available during the analysis of the enclosing |
2159 | | /// function. This is important due to the fact that blocks are analyzed before |
2160 | | /// the enclosed function is even parsed fully, so it is not viable to access |
2161 | | /// anything in the outer scope while analyzing the block. On the other hand, |
2162 | | /// re-building CFG for blocks and re-analyzing them when we do have all the |
2163 | | /// information (i.e. during the analysis of the enclosing function) seems to be |
2164 | | /// ill-designed. |
2165 | | class sema::AnalysisBasedWarnings::InterProceduralData { |
2166 | | public: |
2167 | | // It is important to analyze blocks within functions because it's a very |
2168 | | // common pattern to capture completion handler parameters by blocks. |
2169 | | CalledOnceInterProceduralData CalledOnceData; |
2170 | | }; |
2171 | | |
2172 | 529k | static unsigned isEnabled(DiagnosticsEngine &D, unsigned diag) { |
2173 | 529k | return (unsigned)!D.isIgnored(diag, SourceLocation()); |
2174 | 529k | } |
2175 | | |
2176 | | sema::AnalysisBasedWarnings::AnalysisBasedWarnings(Sema &s) |
2177 | | : S(s), IPData(std::make_unique<InterProceduralData>()), |
2178 | | NumFunctionsAnalyzed(0), NumFunctionsWithBadCFGs(0), NumCFGBlocks(0), |
2179 | | MaxCFGBlocksPerFunction(0), NumUninitAnalysisFunctions(0), |
2180 | | NumUninitAnalysisVariables(0), MaxUninitAnalysisVariablesPerFunction(0), |
2181 | | NumUninitAnalysisBlockVisits(0), |
2182 | 88.2k | MaxUninitAnalysisBlockVisitsPerFunction(0) { |
2183 | | |
2184 | 88.2k | using namespace diag; |
2185 | 88.2k | DiagnosticsEngine &D = S.getDiagnostics(); |
2186 | | |
2187 | 88.2k | DefaultPolicy.enableCheckUnreachable = |
2188 | 88.2k | isEnabled(D, warn_unreachable) || isEnabled(D, warn_unreachable_break)88.2k || |
2189 | 88.2k | isEnabled(D, warn_unreachable_return)88.2k || |
2190 | 88.2k | isEnabled(D, warn_unreachable_loop_increment)88.2k ; |
2191 | | |
2192 | 88.2k | DefaultPolicy.enableThreadSafetyAnalysis = isEnabled(D, warn_double_lock); |
2193 | | |
2194 | 88.2k | DefaultPolicy.enableConsumedAnalysis = |
2195 | 88.2k | isEnabled(D, warn_use_in_invalid_state); |
2196 | 88.2k | } |
2197 | | |
2198 | | // We need this here for unique_ptr with forward declared class. |
2199 | 83.4k | sema::AnalysisBasedWarnings::~AnalysisBasedWarnings() = default; |
2200 | | |
2201 | 837 | static void flushDiagnostics(Sema &S, const sema::FunctionScopeInfo *fscope) { |
2202 | 837 | for (const auto &D : fscope->PossiblyUnreachableDiags) |
2203 | 2 | S.Diag(D.Loc, D.PD); |
2204 | 837 | } |
2205 | | |
2206 | | void clang::sema::AnalysisBasedWarnings::IssueWarnings( |
2207 | | sema::AnalysisBasedWarnings::Policy P, sema::FunctionScopeInfo *fscope, |
2208 | 3.44M | const Decl *D, QualType BlockType) { |
2209 | | |
2210 | | // We avoid doing analysis-based warnings when there are errors for |
2211 | | // two reasons: |
2212 | | // (1) The CFGs often can't be constructed (if the body is invalid), so |
2213 | | // don't bother trying. |
2214 | | // (2) The code already has problems; running the analysis just takes more |
2215 | | // time. |
2216 | 3.44M | DiagnosticsEngine &Diags = S.getDiagnostics(); |
2217 | | |
2218 | | // Do not do any analysis if we are going to just ignore them. |
2219 | 3.44M | if (Diags.getIgnoreAllWarnings() || |
2220 | 3.44M | (3.36M Diags.getSuppressSystemWarnings()3.36M && |
2221 | 3.36M | S.SourceMgr.isInSystemHeader(D->getLocation())3.35M )) |
2222 | 3.16M | return; |
2223 | | |
2224 | | // For code in dependent contexts, we'll do this at instantiation time. |
2225 | 287k | if (cast<DeclContext>(D)->isDependentContext()) |
2226 | 11.5k | return; |
2227 | | |
2228 | 276k | if (S.hasUncompilableErrorOccurred()) { |
2229 | | // Flush out any possibly unreachable diagnostics. |
2230 | 837 | flushDiagnostics(S, fscope); |
2231 | 837 | return; |
2232 | 837 | } |
2233 | | |
2234 | 275k | const Stmt *Body = D->getBody(); |
2235 | 275k | assert(Body); |
2236 | | |
2237 | | // Construct the analysis context with the specified CFG build options. |
2238 | 0 | AnalysisDeclContext AC(/* AnalysisDeclContextManager */ nullptr, D); |
2239 | | |
2240 | | // Don't generate EH edges for CallExprs as we'd like to avoid the n^2 |
2241 | | // explosion for destructors that can result and the compile time hit. |
2242 | 275k | AC.getCFGBuildOptions().PruneTriviallyFalseEdges = true; |
2243 | 275k | AC.getCFGBuildOptions().AddEHEdges = false; |
2244 | 275k | AC.getCFGBuildOptions().AddInitializers = true; |
2245 | 275k | AC.getCFGBuildOptions().AddImplicitDtors = true; |
2246 | 275k | AC.getCFGBuildOptions().AddTemporaryDtors = true; |
2247 | 275k | AC.getCFGBuildOptions().AddCXXNewAllocator = false; |
2248 | 275k | AC.getCFGBuildOptions().AddCXXDefaultInitExprInCtors = true; |
2249 | | |
2250 | | // Force that certain expressions appear as CFGElements in the CFG. This |
2251 | | // is used to speed up various analyses. |
2252 | | // FIXME: This isn't the right factoring. This is here for initial |
2253 | | // prototyping, but we need a way for analyses to say what expressions they |
2254 | | // expect to always be CFGElements and then fill in the BuildOptions |
2255 | | // appropriately. This is essentially a layering violation. |
2256 | 275k | if (P.enableCheckUnreachable || P.enableThreadSafetyAnalysis275k || |
2257 | 275k | P.enableConsumedAnalysis273k ) { |
2258 | | // Unreachable code analysis and thread safety require a linearized CFG. |
2259 | 2.46k | AC.getCFGBuildOptions().setAllAlwaysAdd(); |
2260 | 2.46k | } |
2261 | 273k | else { |
2262 | 273k | AC.getCFGBuildOptions() |
2263 | 273k | .setAlwaysAdd(Stmt::BinaryOperatorClass) |
2264 | 273k | .setAlwaysAdd(Stmt::CompoundAssignOperatorClass) |
2265 | 273k | .setAlwaysAdd(Stmt::BlockExprClass) |
2266 | 273k | .setAlwaysAdd(Stmt::CStyleCastExprClass) |
2267 | 273k | .setAlwaysAdd(Stmt::DeclRefExprClass) |
2268 | 273k | .setAlwaysAdd(Stmt::ImplicitCastExprClass) |
2269 | 273k | .setAlwaysAdd(Stmt::UnaryOperatorClass); |
2270 | 273k | } |
2271 | | |
2272 | | // Install the logical handler. |
2273 | 275k | llvm::Optional<LogicalErrorHandler> LEH; |
2274 | 275k | if (LogicalErrorHandler::hasActiveDiagnostics(Diags, D->getBeginLoc())) { |
2275 | 42.3k | LEH.emplace(S); |
2276 | 42.3k | AC.getCFGBuildOptions().Observer = &*LEH; |
2277 | 42.3k | } |
2278 | | |
2279 | | // Emit delayed diagnostics. |
2280 | 275k | if (!fscope->PossiblyUnreachableDiags.empty()) { |
2281 | 11.1k | bool analyzed = false; |
2282 | | |
2283 | | // Register the expressions with the CFGBuilder. |
2284 | 15.8k | for (const auto &D : fscope->PossiblyUnreachableDiags) { |
2285 | 15.8k | for (const Stmt *S : D.Stmts) |
2286 | 16.1k | AC.registerForcedBlockExpression(S); |
2287 | 15.8k | } |
2288 | | |
2289 | 11.1k | if (AC.getCFG()) { |
2290 | 11.1k | analyzed = true; |
2291 | 15.8k | for (const auto &D : fscope->PossiblyUnreachableDiags) { |
2292 | 15.8k | bool AllReachable = true; |
2293 | 16.1k | for (const Stmt *S : D.Stmts) { |
2294 | 16.1k | const CFGBlock *block = AC.getBlockForRegisteredExpression(S); |
2295 | 16.1k | CFGReverseBlockReachabilityAnalysis *cra = |
2296 | 16.1k | AC.getCFGReachablityAnalysis(); |
2297 | | // FIXME: We should be able to assert that block is non-null, but |
2298 | | // the CFG analysis can skip potentially-evaluated expressions in |
2299 | | // edge cases; see test/Sema/vla-2.c. |
2300 | 16.1k | if (block && cra14.9k ) { |
2301 | | // Can this block be reached from the entrance? |
2302 | 14.9k | if (!cra->isReachable(&AC.getCFG()->getEntry(), block)) { |
2303 | 120 | AllReachable = false; |
2304 | 120 | break; |
2305 | 120 | } |
2306 | 14.9k | } |
2307 | | // If we cannot map to a basic block, assume the statement is |
2308 | | // reachable. |
2309 | 16.1k | } |
2310 | | |
2311 | 15.8k | if (AllReachable) |
2312 | 15.7k | S.Diag(D.Loc, D.PD); |
2313 | 15.8k | } |
2314 | 11.1k | } |
2315 | | |
2316 | 11.1k | if (!analyzed) |
2317 | 0 | flushDiagnostics(S, fscope); |
2318 | 11.1k | } |
2319 | | |
2320 | | // Warning: check missing 'return' |
2321 | 275k | if (P.enableCheckFallThrough) { |
2322 | 268k | const CheckFallThroughDiagnostics &CD = |
2323 | 268k | (isa<BlockDecl>(D) |
2324 | 268k | ? CheckFallThroughDiagnostics::MakeForBlock()2.19k |
2325 | 268k | : (266k isa<CXXMethodDecl>(D)266k && |
2326 | 266k | cast<CXXMethodDecl>(D)->getOverloadedOperator() == OO_Call54.5k && |
2327 | 266k | cast<CXXMethodDecl>(D)->getParent()->isLambda()3.87k ) |
2328 | 266k | ? CheckFallThroughDiagnostics::MakeForLambda()3.73k |
2329 | 266k | : (262k fscope->isCoroutine()262k |
2330 | 262k | ? CheckFallThroughDiagnostics::MakeForCoroutine(D)178 |
2331 | 262k | : CheckFallThroughDiagnostics::MakeForFunction(D)262k )); |
2332 | 268k | CheckFallThroughForBody(S, D, Body, BlockType, CD, AC, fscope); |
2333 | 268k | } |
2334 | | |
2335 | | // Warning: check for unreachable code |
2336 | 275k | if (P.enableCheckUnreachable) { |
2337 | | // Only check for unreachable code on non-template instantiations. |
2338 | | // Different template instantiations can effectively change the control-flow |
2339 | | // and it is very difficult to prove that a snippet of code in a template |
2340 | | // is unreachable for all instantiations. |
2341 | 169 | bool isTemplateInstantiation = false; |
2342 | 169 | if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) |
2343 | 165 | isTemplateInstantiation = Function->isTemplateInstantiation(); |
2344 | 169 | if (!isTemplateInstantiation) |
2345 | 165 | CheckUnreachable(S, AC); |
2346 | 169 | } |
2347 | | |
2348 | | // Check for thread safety violations |
2349 | 275k | if (P.enableThreadSafetyAnalysis) { |
2350 | 2.25k | SourceLocation FL = AC.getDecl()->getLocation(); |
2351 | 2.25k | SourceLocation FEL = AC.getDecl()->getEndLoc(); |
2352 | 2.25k | threadSafety::ThreadSafetyReporter Reporter(S, FL, FEL); |
2353 | 2.25k | if (!Diags.isIgnored(diag::warn_thread_safety_beta, D->getBeginLoc())) |
2354 | 2.17k | Reporter.setIssueBetaWarnings(true); |
2355 | 2.25k | if (!Diags.isIgnored(diag::warn_thread_safety_verbose, D->getBeginLoc())) |
2356 | 42 | Reporter.setVerbose(true); |
2357 | | |
2358 | 2.25k | threadSafety::runThreadSafetyAnalysis(AC, Reporter, |
2359 | 2.25k | &S.ThreadSafetyDeclCache); |
2360 | 2.25k | Reporter.emitDiagnostics(); |
2361 | 2.25k | } |
2362 | | |
2363 | | // Check for violations of consumed properties. |
2364 | 275k | if (P.enableConsumedAnalysis) { |
2365 | 98 | consumed::ConsumedWarningsHandler WarningHandler(S); |
2366 | 98 | consumed::ConsumedAnalyzer Analyzer(WarningHandler); |
2367 | 98 | Analyzer.run(AC); |
2368 | 98 | } |
2369 | | |
2370 | 275k | if (!Diags.isIgnored(diag::warn_uninit_var, D->getBeginLoc()) || |
2371 | 275k | !Diags.isIgnored(diag::warn_sometimes_uninit_var, D->getBeginLoc())217k || |
2372 | 275k | !Diags.isIgnored(diag::warn_maybe_uninit_var, D->getBeginLoc())217k || |
2373 | 275k | !Diags.isIgnored(diag::warn_uninit_const_reference, D->getBeginLoc())217k ) { |
2374 | 58.3k | if (CFG *cfg = AC.getCFG()) { |
2375 | 58.3k | UninitValsDiagReporter reporter(S); |
2376 | 58.3k | UninitVariablesAnalysisStats stats; |
2377 | 58.3k | std::memset(&stats, 0, sizeof(UninitVariablesAnalysisStats)); |
2378 | 58.3k | runUninitializedVariablesAnalysis(*cast<DeclContext>(D), *cfg, AC, |
2379 | 58.3k | reporter, stats); |
2380 | | |
2381 | 58.3k | if (S.CollectStats && stats.NumVariablesAnalyzed > 00 ) { |
2382 | 0 | ++NumUninitAnalysisFunctions; |
2383 | 0 | NumUninitAnalysisVariables += stats.NumVariablesAnalyzed; |
2384 | 0 | NumUninitAnalysisBlockVisits += stats.NumBlockVisits; |
2385 | 0 | MaxUninitAnalysisVariablesPerFunction = |
2386 | 0 | std::max(MaxUninitAnalysisVariablesPerFunction, |
2387 | 0 | stats.NumVariablesAnalyzed); |
2388 | 0 | MaxUninitAnalysisBlockVisitsPerFunction = |
2389 | 0 | std::max(MaxUninitAnalysisBlockVisitsPerFunction, |
2390 | 0 | stats.NumBlockVisits); |
2391 | 0 | } |
2392 | 58.3k | } |
2393 | 58.3k | } |
2394 | | |
2395 | | // Check for violations of "called once" parameter properties. |
2396 | 275k | if (S.getLangOpts().ObjC && !S.getLangOpts().CPlusPlus29.1k && |
2397 | 275k | shouldAnalyzeCalledOnceParameters(Diags, D->getBeginLoc())10.5k ) { |
2398 | 10.5k | if (AC.getCFG()) { |
2399 | 10.5k | CalledOnceCheckReporter Reporter(S, IPData->CalledOnceData); |
2400 | 10.5k | checkCalledOnceParameters( |
2401 | 10.5k | AC, Reporter, |
2402 | 10.5k | shouldAnalyzeCalledOnceConventions(Diags, D->getBeginLoc())); |
2403 | 10.5k | } |
2404 | 10.5k | } |
2405 | | |
2406 | 275k | bool FallThroughDiagFull = |
2407 | 275k | !Diags.isIgnored(diag::warn_unannotated_fallthrough, D->getBeginLoc()); |
2408 | 275k | bool FallThroughDiagPerFunction = !Diags.isIgnored( |
2409 | 275k | diag::warn_unannotated_fallthrough_per_function, D->getBeginLoc()); |
2410 | 275k | if (FallThroughDiagFull || FallThroughDiagPerFunction275k || |
2411 | 275k | fscope->HasFallthroughStmt275k ) { |
2412 | 124 | DiagnoseSwitchLabelsFallthrough(S, AC, !FallThroughDiagFull); |
2413 | 124 | } |
2414 | | |
2415 | 275k | if (S.getLangOpts().ObjCWeak && |
2416 | 275k | !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, D->getBeginLoc())1.53k ) |
2417 | 112 | diagnoseRepeatedUseOfWeak(S, fscope, D, AC.getParentMap()); |
2418 | | |
2419 | | |
2420 | | // Check for infinite self-recursion in functions |
2421 | 275k | if (!Diags.isIgnored(diag::warn_infinite_recursive_function, |
2422 | 275k | D->getBeginLoc())) { |
2423 | 42.3k | if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { |
2424 | 42.3k | checkRecursiveFunction(S, FD, Body, AC); |
2425 | 42.3k | } |
2426 | 42.3k | } |
2427 | | |
2428 | | // Check for throw out of non-throwing function. |
2429 | 275k | if (!Diags.isIgnored(diag::warn_throw_in_noexcept_func, D->getBeginLoc())) |
2430 | 275k | if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) |
2431 | 267k | if (S.getLangOpts().CPlusPlus && isNoexcept(FD)160k ) |
2432 | 7.97k | checkThrowInNonThrowingFunc(S, FD, AC); |
2433 | | |
2434 | | // If none of the previous checks caused a CFG build, trigger one here |
2435 | | // for the logical error handler. |
2436 | 275k | if (LogicalErrorHandler::hasActiveDiagnostics(Diags, D->getBeginLoc())) { |
2437 | 42.3k | AC.getCFG(); |
2438 | 42.3k | } |
2439 | | |
2440 | | // Collect statistics about the CFG if it was built. |
2441 | 275k | if (S.CollectStats && AC.isCFGBuilt()4 ) { |
2442 | 3 | ++NumFunctionsAnalyzed; |
2443 | 3 | if (CFG *cfg = AC.getCFG()) { |
2444 | | // If we successfully built a CFG for this context, record some more |
2445 | | // detail information about it. |
2446 | 3 | NumCFGBlocks += cfg->getNumBlockIDs(); |
2447 | 3 | MaxCFGBlocksPerFunction = std::max(MaxCFGBlocksPerFunction, |
2448 | 3 | cfg->getNumBlockIDs()); |
2449 | 3 | } else { |
2450 | 0 | ++NumFunctionsWithBadCFGs; |
2451 | 0 | } |
2452 | 3 | } |
2453 | 275k | } |
2454 | | |
2455 | 4 | void clang::sema::AnalysisBasedWarnings::PrintStats() const { |
2456 | 4 | llvm::errs() << "\n*** Analysis Based Warnings Stats:\n"; |
2457 | | |
2458 | 4 | unsigned NumCFGsBuilt = NumFunctionsAnalyzed - NumFunctionsWithBadCFGs; |
2459 | 4 | unsigned AvgCFGBlocksPerFunction = |
2460 | 4 | !NumCFGsBuilt ? 01 : NumCFGBlocks/NumCFGsBuilt3 ; |
2461 | 4 | llvm::errs() << NumFunctionsAnalyzed << " functions analyzed (" |
2462 | 4 | << NumFunctionsWithBadCFGs << " w/o CFGs).\n" |
2463 | 4 | << " " << NumCFGBlocks << " CFG blocks built.\n" |
2464 | 4 | << " " << AvgCFGBlocksPerFunction |
2465 | 4 | << " average CFG blocks per function.\n" |
2466 | 4 | << " " << MaxCFGBlocksPerFunction |
2467 | 4 | << " max CFG blocks per function.\n"; |
2468 | | |
2469 | 4 | unsigned AvgUninitVariablesPerFunction = !NumUninitAnalysisFunctions ? 0 |
2470 | 4 | : NumUninitAnalysisVariables/NumUninitAnalysisFunctions0 ; |
2471 | 4 | unsigned AvgUninitBlockVisitsPerFunction = !NumUninitAnalysisFunctions ? 0 |
2472 | 4 | : NumUninitAnalysisBlockVisits/NumUninitAnalysisFunctions0 ; |
2473 | 4 | llvm::errs() << NumUninitAnalysisFunctions |
2474 | 4 | << " functions analyzed for uninitialiazed variables\n" |
2475 | 4 | << " " << NumUninitAnalysisVariables << " variables analyzed.\n" |
2476 | 4 | << " " << AvgUninitVariablesPerFunction |
2477 | 4 | << " average variables per function.\n" |
2478 | 4 | << " " << MaxUninitAnalysisVariablesPerFunction |
2479 | 4 | << " max variables per function.\n" |
2480 | 4 | << " " << NumUninitAnalysisBlockVisits << " block visits.\n" |
2481 | 4 | << " " << AvgUninitBlockVisitsPerFunction |
2482 | 4 | << " average block visits per function.\n" |
2483 | 4 | << " " << MaxUninitAnalysisBlockVisitsPerFunction |
2484 | 4 | << " max block visits per function.\n"; |
2485 | 4 | } |