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