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