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