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