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