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