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