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