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