2010-03-21 05:06:02 +08:00
|
|
|
//=- AnalysisBasedWarnings.cpp - Sema warnings based on libAnalysis -*- C++ -*-=//
|
|
|
|
//
|
|
|
|
// The LLVM Compiler Infrastructure
|
|
|
|
//
|
|
|
|
// This file is distributed under the University of Illinois Open Source
|
|
|
|
// License. See LICENSE.TXT for details.
|
|
|
|
//
|
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
//
|
|
|
|
// This file defines analysis_warnings::[Policy,Executor].
|
|
|
|
// Together they are used by Sema to issue warnings based on inexpensive
|
|
|
|
// static analysis algorithms in libAnalysis.
|
|
|
|
//
|
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
|
2010-08-13 04:07:10 +08:00
|
|
|
#include "clang/Sema/AnalysisBasedWarnings.h"
|
2010-08-25 15:42:41 +08:00
|
|
|
#include "clang/AST/DeclCXX.h"
|
2012-12-04 17:13:33 +08:00
|
|
|
#include "clang/AST/DeclObjC.h"
|
2011-04-05 04:56:00 +08:00
|
|
|
#include "clang/AST/EvaluatedExprVisitor.h"
|
2012-12-04 17:13:33 +08:00
|
|
|
#include "clang/AST/ExprCXX.h"
|
|
|
|
#include "clang/AST/ExprObjC.h"
|
2012-10-12 00:10:19 +08:00
|
|
|
#include "clang/AST/ParentMap.h"
|
2012-05-04 02:27:39 +08:00
|
|
|
#include "clang/AST/RecursiveASTVisitor.h"
|
2012-12-04 17:13:33 +08:00
|
|
|
#include "clang/AST/StmtCXX.h"
|
|
|
|
#include "clang/AST/StmtObjC.h"
|
|
|
|
#include "clang/AST/StmtVisitor.h"
|
2011-02-23 09:52:04 +08:00
|
|
|
#include "clang/Analysis/Analyses/CFGReachabilityAnalysis.h"
|
2013-08-13 05:20:55 +08:00
|
|
|
#include "clang/Analysis/Analyses/Consumed.h"
|
2012-12-04 17:13:33 +08:00
|
|
|
#include "clang/Analysis/Analyses/ReachableCode.h"
|
2011-09-10 00:11:56 +08:00
|
|
|
#include "clang/Analysis/Analyses/ThreadSafety.h"
|
2011-03-15 11:17:07 +08:00
|
|
|
#include "clang/Analysis/Analyses/UninitializedValues.h"
|
2017-09-07 05:45:03 +08:00
|
|
|
#include "clang/Analysis/AnalysisDeclContext.h"
|
2012-12-04 17:13:33 +08:00
|
|
|
#include "clang/Analysis/CFG.h"
|
|
|
|
#include "clang/Analysis/CFGStmtMap.h"
|
|
|
|
#include "clang/Basic/SourceLocation.h"
|
|
|
|
#include "clang/Basic/SourceManager.h"
|
|
|
|
#include "clang/Lex/Preprocessor.h"
|
|
|
|
#include "clang/Sema/ScopeInfo.h"
|
|
|
|
#include "clang/Sema/SemaInternal.h"
|
2010-03-21 05:06:02 +08:00
|
|
|
#include "llvm/ADT/BitVector.h"
|
2013-02-16 04:09:55 +08:00
|
|
|
#include "llvm/ADT/MapVector.h"
|
2012-09-29 19:40:46 +08:00
|
|
|
#include "llvm/ADT/SmallString.h"
|
2011-08-24 02:46:34 +08:00
|
|
|
#include "llvm/ADT/SmallVector.h"
|
2011-09-10 00:04:02 +08:00
|
|
|
#include "llvm/ADT/StringRef.h"
|
2010-03-21 05:06:02 +08:00
|
|
|
#include "llvm/Support/Casting.h"
|
2011-08-24 02:46:34 +08:00
|
|
|
#include <algorithm>
|
2012-12-04 17:13:33 +08:00
|
|
|
#include <deque>
|
2012-05-04 02:27:39 +08:00
|
|
|
#include <iterator>
|
2010-03-21 05:06:02 +08:00
|
|
|
|
|
|
|
using namespace clang;
|
|
|
|
|
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
// Unreachable code analysis.
|
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
|
|
|
|
namespace {
|
|
|
|
class UnreachableCodeHandler : public reachable_code::Callback {
|
|
|
|
Sema &S;
|
2017-01-12 18:48:03 +08:00
|
|
|
SourceRange PreviousSilenceableCondVal;
|
|
|
|
|
2010-03-21 05:06:02 +08:00
|
|
|
public:
|
|
|
|
UnreachableCodeHandler(Sema &s) : S(s) {}
|
|
|
|
|
2014-03-15 09:26:32 +08:00
|
|
|
void HandleUnreachable(reachable_code::UnreachableKind UK,
|
2014-03-29 08:35:20 +08:00
|
|
|
SourceLocation L,
|
|
|
|
SourceRange SilenceableCondVal,
|
|
|
|
SourceRange R1,
|
2014-03-12 12:55:44 +08:00
|
|
|
SourceRange R2) override {
|
2017-01-12 18:48:03 +08:00
|
|
|
// Avoid reporting multiple unreachable code diagnostics that are
|
|
|
|
// triggered by the same conditional value.
|
|
|
|
if (PreviousSilenceableCondVal.isValid() &&
|
|
|
|
SilenceableCondVal.isValid() &&
|
|
|
|
PreviousSilenceableCondVal == SilenceableCondVal)
|
|
|
|
return;
|
|
|
|
PreviousSilenceableCondVal = SilenceableCondVal;
|
|
|
|
|
2014-03-15 09:26:32 +08:00
|
|
|
unsigned diag = diag::warn_unreachable;
|
|
|
|
switch (UK) {
|
|
|
|
case reachable_code::UK_Break:
|
|
|
|
diag = diag::warn_unreachable_break;
|
|
|
|
break;
|
2014-03-20 14:07:30 +08:00
|
|
|
case reachable_code::UK_Return:
|
2014-03-15 13:47:06 +08:00
|
|
|
diag = diag::warn_unreachable_return;
|
2014-03-15 09:26:32 +08:00
|
|
|
break;
|
2014-03-21 14:02:36 +08:00
|
|
|
case reachable_code::UK_Loop_Increment:
|
|
|
|
diag = diag::warn_unreachable_loop_increment;
|
|
|
|
break;
|
2014-03-15 09:26:32 +08:00
|
|
|
case reachable_code::UK_Other:
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
|
|
|
|
S.Diag(L, diag) << R1 << R2;
|
2014-03-29 08:35:20 +08:00
|
|
|
|
|
|
|
SourceLocation Open = SilenceableCondVal.getBegin();
|
|
|
|
if (Open.isValid()) {
|
2014-05-03 11:45:55 +08:00
|
|
|
SourceLocation Close = SilenceableCondVal.getEnd();
|
|
|
|
Close = S.getLocForEndOfToken(Close);
|
2014-03-29 08:35:20 +08:00
|
|
|
if (Close.isValid()) {
|
|
|
|
S.Diag(Open, diag::note_unreachable_silence)
|
|
|
|
<< FixItHint::CreateInsertion(Open, "/* DISABLES CODE */ (")
|
|
|
|
<< FixItHint::CreateInsertion(Close, ")");
|
|
|
|
}
|
|
|
|
}
|
2010-03-21 05:06:02 +08:00
|
|
|
}
|
|
|
|
};
|
2015-10-07 07:40:43 +08:00
|
|
|
} // anonymous namespace
|
2010-03-21 05:06:02 +08:00
|
|
|
|
|
|
|
/// CheckUnreachable - Check for unreachable code.
|
2011-10-24 09:32:45 +08:00
|
|
|
static void CheckUnreachable(Sema &S, AnalysisDeclContext &AC) {
|
2014-02-26 06:35:37 +08:00
|
|
|
// As a heuristic prune all diagnostics not in the main file. Currently
|
|
|
|
// the majority of warnings in headers are false positives. These
|
|
|
|
// are largely caused by configuration state, e.g. preprocessor
|
|
|
|
// defined code, etc.
|
|
|
|
//
|
|
|
|
// Note that this is also a performance optimization. Analyzing
|
|
|
|
// headers many times can be expensive.
|
|
|
|
if (!S.getSourceManager().isInMainFile(AC.getDecl()->getLocStart()))
|
|
|
|
return;
|
|
|
|
|
2010-03-21 05:06:02 +08:00
|
|
|
UnreachableCodeHandler UC(S);
|
2014-03-09 16:13:49 +08:00
|
|
|
reachable_code::FindUnreachableCode(AC, S.getPreprocessor(), UC);
|
2010-03-21 05:06:02 +08:00
|
|
|
}
|
|
|
|
|
2015-02-17 00:53:12 +08:00
|
|
|
namespace {
|
2014-04-05 13:17:01 +08:00
|
|
|
/// \brief Warn on logical operator errors in CFGBuilder
|
|
|
|
class LogicalErrorHandler : public CFGCallback {
|
|
|
|
Sema &S;
|
|
|
|
|
|
|
|
public:
|
|
|
|
LogicalErrorHandler(Sema &S) : CFGCallback(), S(S) {}
|
|
|
|
|
|
|
|
static bool HasMacroID(const Expr *E) {
|
|
|
|
if (E->getExprLoc().isMacroID())
|
|
|
|
return true;
|
|
|
|
|
|
|
|
// Recurse to children.
|
2015-07-03 05:03:14 +08:00
|
|
|
for (const Stmt *SubStmt : E->children())
|
|
|
|
if (const Expr *SubExpr = dyn_cast_or_null<Expr>(SubStmt))
|
|
|
|
if (HasMacroID(SubExpr))
|
|
|
|
return true;
|
2014-04-05 13:17:01 +08:00
|
|
|
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
2015-04-11 10:00:23 +08:00
|
|
|
void compareAlwaysTrue(const BinaryOperator *B, bool isAlwaysTrue) override {
|
2014-04-05 13:17:01 +08:00
|
|
|
if (HasMacroID(B))
|
|
|
|
return;
|
|
|
|
|
|
|
|
SourceRange DiagRange = B->getSourceRange();
|
|
|
|
S.Diag(B->getExprLoc(), diag::warn_tautological_overlap_comparison)
|
|
|
|
<< DiagRange << isAlwaysTrue;
|
|
|
|
}
|
2014-05-21 01:31:11 +08:00
|
|
|
|
2015-04-11 10:00:23 +08:00
|
|
|
void compareBitwiseEquality(const BinaryOperator *B,
|
|
|
|
bool isAlwaysTrue) override {
|
2014-05-21 01:31:11 +08:00
|
|
|
if (HasMacroID(B))
|
|
|
|
return;
|
|
|
|
|
|
|
|
SourceRange DiagRange = B->getSourceRange();
|
|
|
|
S.Diag(B->getExprLoc(), diag::warn_comparison_bitwise_always)
|
|
|
|
<< DiagRange << isAlwaysTrue;
|
|
|
|
}
|
2014-04-05 13:17:01 +08:00
|
|
|
};
|
2015-10-07 07:40:43 +08:00
|
|
|
} // anonymous namespace
|
2014-04-05 13:17:01 +08:00
|
|
|
|
2013-12-21 10:33:43 +08:00
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
// Check for infinite self-recursion in functions
|
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
|
2015-08-21 11:43:09 +08:00
|
|
|
// Returns true if the function is called anywhere within the CFGBlock.
|
|
|
|
// For member functions, the additional condition of being call from the
|
|
|
|
// this pointer is required.
|
2015-07-24 04:11:47 +08:00
|
|
|
static bool hasRecursiveCallInPath(const FunctionDecl *FD, CFGBlock &Block) {
|
2015-08-21 11:43:09 +08:00
|
|
|
// Process all the Stmt's in this block to find any calls to FD.
|
2015-07-24 04:11:47 +08:00
|
|
|
for (const auto &B : Block) {
|
|
|
|
if (B.getKind() != CFGElement::Statement)
|
|
|
|
continue;
|
|
|
|
|
|
|
|
const CallExpr *CE = dyn_cast<CallExpr>(B.getAs<CFGStmt>()->getStmt());
|
|
|
|
if (!CE || !CE->getCalleeDecl() ||
|
|
|
|
CE->getCalleeDecl()->getCanonicalDecl() != FD)
|
|
|
|
continue;
|
|
|
|
|
|
|
|
// Skip function calls which are qualified with a templated class.
|
|
|
|
if (const DeclRefExpr *DRE =
|
|
|
|
dyn_cast<DeclRefExpr>(CE->getCallee()->IgnoreParenImpCasts())) {
|
|
|
|
if (NestedNameSpecifier *NNS = DRE->getQualifier()) {
|
|
|
|
if (NNS->getKind() == NestedNameSpecifier::TypeSpec &&
|
|
|
|
isa<TemplateSpecializationType>(NNS->getAsType())) {
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
const CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(CE);
|
|
|
|
if (!MCE || isa<CXXThisExpr>(MCE->getImplicitObjectArgument()) ||
|
|
|
|
!MCE->getMethodDecl()->isVirtual())
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
2015-08-21 11:43:09 +08:00
|
|
|
// All blocks are in one of three states. States are ordered so that blocks
|
|
|
|
// can only move to higher states.
|
|
|
|
enum RecursiveState {
|
|
|
|
FoundNoPath,
|
|
|
|
FoundPath,
|
|
|
|
FoundPathWithNoRecursiveCall
|
|
|
|
};
|
|
|
|
|
|
|
|
// Returns true if there exists a path to the exit block and every path
|
|
|
|
// to the exit block passes through a call to FD.
|
|
|
|
static bool checkForRecursiveFunctionCall(const FunctionDecl *FD, CFG *cfg) {
|
2013-12-21 10:33:43 +08:00
|
|
|
|
2015-08-21 11:43:09 +08:00
|
|
|
const unsigned ExitID = cfg->getExit().getBlockID();
|
2013-12-21 10:33:43 +08:00
|
|
|
|
2015-08-21 11:43:09 +08:00
|
|
|
// Mark all nodes as FoundNoPath, then set the status of the entry block.
|
|
|
|
SmallVector<RecursiveState, 16> States(cfg->getNumBlockIDs(), FoundNoPath);
|
|
|
|
States[cfg->getEntry().getBlockID()] = FoundPathWithNoRecursiveCall;
|
2013-12-21 10:33:43 +08:00
|
|
|
|
2015-08-21 11:43:09 +08:00
|
|
|
// Make the processing stack and seed it with the entry block.
|
|
|
|
SmallVector<CFGBlock *, 16> Stack;
|
|
|
|
Stack.push_back(&cfg->getEntry());
|
2014-01-04 09:57:42 +08:00
|
|
|
|
2015-08-21 11:43:09 +08:00
|
|
|
while (!Stack.empty()) {
|
|
|
|
CFGBlock *CurBlock = Stack.back();
|
|
|
|
Stack.pop_back();
|
|
|
|
|
|
|
|
unsigned ID = CurBlock->getBlockID();
|
|
|
|
RecursiveState CurState = States[ID];
|
2013-12-21 10:33:43 +08:00
|
|
|
|
2015-07-24 04:15:50 +08:00
|
|
|
if (CurState == FoundPathWithNoRecursiveCall) {
|
|
|
|
// Found a path to the exit node without a recursive call.
|
|
|
|
if (ExitID == ID)
|
2015-08-21 11:43:09 +08:00
|
|
|
return false;
|
2015-07-24 04:15:50 +08:00
|
|
|
|
2015-08-21 11:43:09 +08:00
|
|
|
// Only change state if the block has a recursive call.
|
|
|
|
if (hasRecursiveCallInPath(FD, *CurBlock))
|
2015-07-24 04:15:50 +08:00
|
|
|
CurState = FoundPath;
|
|
|
|
}
|
|
|
|
|
2015-08-21 11:43:09 +08:00
|
|
|
// Loop over successor blocks and add them to the Stack if their state
|
|
|
|
// changes.
|
|
|
|
for (auto I = CurBlock->succ_begin(), E = CurBlock->succ_end(); I != E; ++I)
|
|
|
|
if (*I) {
|
|
|
|
unsigned next_ID = (*I)->getBlockID();
|
|
|
|
if (States[next_ID] < CurState) {
|
|
|
|
States[next_ID] = CurState;
|
|
|
|
Stack.push_back(*I);
|
|
|
|
}
|
|
|
|
}
|
2015-07-24 04:15:50 +08:00
|
|
|
}
|
2015-08-21 11:43:09 +08:00
|
|
|
|
|
|
|
// Return true if the exit node is reachable, and only reachable through
|
|
|
|
// a recursive call.
|
|
|
|
return States[ExitID] == FoundPath;
|
2013-12-21 10:33:43 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
static void checkRecursiveFunction(Sema &S, const FunctionDecl *FD,
|
2015-08-21 11:43:09 +08:00
|
|
|
const Stmt *Body, AnalysisDeclContext &AC) {
|
2013-12-21 10:33:43 +08:00
|
|
|
FD = FD->getCanonicalDecl();
|
|
|
|
|
|
|
|
// Only run on non-templated functions and non-templated members of
|
|
|
|
// templated classes.
|
|
|
|
if (FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate &&
|
|
|
|
FD->getTemplatedKind() != FunctionDecl::TK_MemberSpecialization)
|
|
|
|
return;
|
|
|
|
|
|
|
|
CFG *cfg = AC.getCFG();
|
2014-05-26 14:22:03 +08:00
|
|
|
if (!cfg) return;
|
2013-12-21 10:33:43 +08:00
|
|
|
|
|
|
|
// If the exit block is unreachable, skip processing the function.
|
|
|
|
if (cfg->getExit().pred_empty())
|
|
|
|
return;
|
|
|
|
|
2015-08-21 11:43:09 +08:00
|
|
|
// Emit diagnostic if a recursive function call is detected for all paths.
|
|
|
|
if (checkForRecursiveFunctionCall(FD, cfg))
|
2013-12-21 10:33:43 +08:00
|
|
|
S.Diag(Body->getLocStart(), diag::warn_infinite_recursive_function);
|
|
|
|
}
|
|
|
|
|
2017-06-24 04:22:19 +08:00
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
// Check for throw in a non-throwing function.
|
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
enum ThrowState {
|
|
|
|
FoundNoPathForThrow,
|
|
|
|
FoundPathForThrow,
|
|
|
|
FoundPathWithNoThrowOutFunction,
|
|
|
|
};
|
|
|
|
|
2018-01-13 13:05:45 +08:00
|
|
|
static bool isThrowCaughtByHandlers(Sema &S,
|
|
|
|
const CXXThrowExpr *CE,
|
2017-06-24 04:22:19 +08:00
|
|
|
const CXXTryStmt *TryStmt) {
|
|
|
|
for (unsigned H = 0, E = TryStmt->getNumHandlers(); H < E; ++H) {
|
2018-01-13 13:05:45 +08:00
|
|
|
QualType Caught = TryStmt->getHandler(H)->getCaughtType();
|
|
|
|
if (Caught.isNull() || // catch (...) catches everything
|
|
|
|
(CE->getSubExpr() && // throw; is only caught by ...
|
|
|
|
S.handlerCanCatch(Caught, CE->getSubExpr()->getType())))
|
2017-06-24 04:22:19 +08:00
|
|
|
return true;
|
|
|
|
}
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
2018-01-13 13:05:45 +08:00
|
|
|
static bool doesThrowEscapePath(Sema &S, CFGBlock Block,
|
|
|
|
SourceLocation &OpLoc) {
|
2017-06-24 04:22:19 +08:00
|
|
|
for (const auto &B : Block) {
|
|
|
|
if (B.getKind() != CFGElement::Statement)
|
|
|
|
continue;
|
|
|
|
const auto *CE = dyn_cast<CXXThrowExpr>(B.getAs<CFGStmt>()->getStmt());
|
|
|
|
if (!CE)
|
|
|
|
continue;
|
|
|
|
|
|
|
|
OpLoc = CE->getThrowLoc();
|
|
|
|
for (const auto &I : Block.succs()) {
|
|
|
|
if (!I.isReachable())
|
|
|
|
continue;
|
|
|
|
if (const auto *Terminator =
|
|
|
|
dyn_cast_or_null<CXXTryStmt>(I->getTerminator()))
|
2018-01-13 13:05:45 +08:00
|
|
|
if (isThrowCaughtByHandlers(S, CE, Terminator))
|
2017-06-24 04:22:19 +08:00
|
|
|
return false;
|
|
|
|
}
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
2018-01-13 13:05:45 +08:00
|
|
|
static bool hasThrowOutNonThrowingFunc(Sema &S, SourceLocation &OpLoc,
|
|
|
|
CFG *BodyCFG) {
|
2017-06-24 04:22:19 +08:00
|
|
|
unsigned ExitID = BodyCFG->getExit().getBlockID();
|
|
|
|
|
|
|
|
SmallVector<ThrowState, 16> States(BodyCFG->getNumBlockIDs(),
|
|
|
|
FoundNoPathForThrow);
|
|
|
|
States[BodyCFG->getEntry().getBlockID()] = FoundPathWithNoThrowOutFunction;
|
|
|
|
|
|
|
|
SmallVector<CFGBlock *, 16> Stack;
|
|
|
|
Stack.push_back(&BodyCFG->getEntry());
|
|
|
|
while (!Stack.empty()) {
|
2017-10-18 01:45:21 +08:00
|
|
|
CFGBlock *CurBlock = Stack.pop_back_val();
|
2017-06-24 04:22:19 +08:00
|
|
|
|
|
|
|
unsigned ID = CurBlock->getBlockID();
|
|
|
|
ThrowState CurState = States[ID];
|
|
|
|
if (CurState == FoundPathWithNoThrowOutFunction) {
|
|
|
|
if (ExitID == ID)
|
|
|
|
continue;
|
|
|
|
|
2018-01-13 13:05:45 +08:00
|
|
|
if (doesThrowEscapePath(S, *CurBlock, OpLoc))
|
2017-06-24 04:22:19 +08:00
|
|
|
CurState = FoundPathForThrow;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Loop over successor blocks and add them to the Stack if their state
|
|
|
|
// changes.
|
|
|
|
for (const auto &I : CurBlock->succs())
|
|
|
|
if (I.isReachable()) {
|
|
|
|
unsigned NextID = I->getBlockID();
|
|
|
|
if (NextID == ExitID && CurState == FoundPathForThrow) {
|
|
|
|
States[NextID] = CurState;
|
|
|
|
} else if (States[NextID] < CurState) {
|
|
|
|
States[NextID] = CurState;
|
|
|
|
Stack.push_back(I);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
// Return true if the exit node is reachable, and only reachable through
|
|
|
|
// a throw expression.
|
|
|
|
return States[ExitID] == FoundPathForThrow;
|
|
|
|
}
|
|
|
|
|
|
|
|
static void EmitDiagForCXXThrowInNonThrowingFunc(Sema &S, SourceLocation OpLoc,
|
|
|
|
const FunctionDecl *FD) {
|
2017-07-06 00:43:45 +08:00
|
|
|
if (!S.getSourceManager().isInSystemHeader(OpLoc) &&
|
|
|
|
FD->getTypeSourceInfo()) {
|
2017-06-24 04:22:19 +08:00
|
|
|
S.Diag(OpLoc, diag::warn_throw_in_noexcept_func) << FD;
|
|
|
|
if (S.getLangOpts().CPlusPlus11 &&
|
|
|
|
(isa<CXXDestructorDecl>(FD) ||
|
|
|
|
FD->getDeclName().getCXXOverloadedOperator() == OO_Delete ||
|
2017-07-06 00:43:45 +08:00
|
|
|
FD->getDeclName().getCXXOverloadedOperator() == OO_Array_Delete)) {
|
|
|
|
if (const auto *Ty = FD->getTypeSourceInfo()->getType()->
|
|
|
|
getAs<FunctionProtoType>())
|
|
|
|
S.Diag(FD->getLocation(), diag::note_throw_in_dtor)
|
|
|
|
<< !isa<CXXDestructorDecl>(FD) << !Ty->hasExceptionSpec()
|
|
|
|
<< FD->getExceptionSpecSourceRange();
|
|
|
|
} else
|
|
|
|
S.Diag(FD->getLocation(), diag::note_throw_in_function)
|
|
|
|
<< FD->getExceptionSpecSourceRange();
|
2017-06-24 04:22:19 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
static void checkThrowInNonThrowingFunc(Sema &S, const FunctionDecl *FD,
|
|
|
|
AnalysisDeclContext &AC) {
|
|
|
|
CFG *BodyCFG = AC.getCFG();
|
|
|
|
if (!BodyCFG)
|
|
|
|
return;
|
|
|
|
if (BodyCFG->getExit().pred_empty())
|
|
|
|
return;
|
|
|
|
SourceLocation OpLoc;
|
2018-01-13 13:05:45 +08:00
|
|
|
if (hasThrowOutNonThrowingFunc(S, OpLoc, BodyCFG))
|
2017-06-24 04:22:19 +08:00
|
|
|
EmitDiagForCXXThrowInNonThrowingFunc(S, OpLoc, FD);
|
|
|
|
}
|
|
|
|
|
|
|
|
static bool isNoexcept(const FunctionDecl *FD) {
|
|
|
|
const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
|
2017-09-27 02:20:39 +08:00
|
|
|
if (FPT->isNothrow(FD->getASTContext()) || FD->hasAttr<NoThrowAttr>())
|
2017-06-24 04:22:19 +08:00
|
|
|
return true;
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
2010-03-21 05:06:02 +08:00
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
// Check for missing return value.
|
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
|
2010-05-16 17:34:11 +08:00
|
|
|
enum ControlFlowKind {
|
|
|
|
UnknownFallThrough,
|
|
|
|
NeverFallThrough,
|
|
|
|
MaybeFallThrough,
|
|
|
|
AlwaysFallThrough,
|
|
|
|
NeverFallThroughOrReturn
|
|
|
|
};
|
2010-03-21 05:06:02 +08:00
|
|
|
|
|
|
|
/// CheckFallThrough - Check that we don't fall off the end of a
|
|
|
|
/// Statement that should return a value.
|
|
|
|
///
|
2012-09-27 18:16:10 +08:00
|
|
|
/// \returns AlwaysFallThrough iff we always fall off the end of the statement,
|
|
|
|
/// MaybeFallThrough iff we might or might not fall off the end,
|
|
|
|
/// NeverFallThroughOrReturn iff we never fall off the end of the statement or
|
|
|
|
/// return. We assume NeverFallThrough iff we never fall off the end of the
|
2010-03-21 05:06:02 +08:00
|
|
|
/// statement but we may return. We assume that functions not marked noreturn
|
|
|
|
/// will return.
|
2011-10-24 09:32:45 +08:00
|
|
|
static ControlFlowKind CheckFallThrough(AnalysisDeclContext &AC) {
|
2010-03-21 05:06:02 +08:00
|
|
|
CFG *cfg = AC.getCFG();
|
2014-05-26 14:22:03 +08:00
|
|
|
if (!cfg) return UnknownFallThrough;
|
2010-03-21 05:06:02 +08:00
|
|
|
|
|
|
|
// The CFG leaves in dead things, and we don't want the dead code paths to
|
|
|
|
// confuse us, so we mark all live things first.
|
|
|
|
llvm::BitVector live(cfg->getNumBlockIDs());
|
2011-08-24 07:05:11 +08:00
|
|
|
unsigned count = reachable_code::ScanReachableFromBlock(&cfg->getEntry(),
|
2010-03-21 05:06:02 +08:00
|
|
|
live);
|
|
|
|
|
|
|
|
bool AddEHEdges = AC.getAddEHEdges();
|
|
|
|
if (!AddEHEdges && count != cfg->getNumBlockIDs())
|
|
|
|
// When there are things remaining dead, and we didn't add EH edges
|
|
|
|
// from CallExprs to the catch clauses, we have to go back and
|
|
|
|
// mark them as live.
|
2014-05-16 04:50:47 +08:00
|
|
|
for (const auto *B : *cfg) {
|
|
|
|
if (!live[B->getBlockID()]) {
|
|
|
|
if (B->pred_begin() == B->pred_end()) {
|
|
|
|
if (B->getTerminator() && isa<CXXTryStmt>(B->getTerminator()))
|
2010-03-21 05:06:02 +08:00
|
|
|
// When not adding EH edges from calls, catch clauses
|
|
|
|
// can otherwise seem dead. Avoid noting them as dead.
|
2014-05-16 04:50:47 +08:00
|
|
|
count += reachable_code::ScanReachableFromBlock(B, live);
|
2010-03-21 05:06:02 +08:00
|
|
|
continue;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Now we know what is live, we check the live precessors of the exit block
|
|
|
|
// and look for fall through paths, being careful to ignore normal returns,
|
|
|
|
// and exceptional paths.
|
|
|
|
bool HasLiveReturn = false;
|
|
|
|
bool HasFakeEdge = false;
|
|
|
|
bool HasPlainEdge = false;
|
|
|
|
bool HasAbnormalEdge = false;
|
2010-09-09 08:06:07 +08:00
|
|
|
|
|
|
|
// Ignore default cases that aren't likely to be reachable because all
|
|
|
|
// enums in a switch(X) have explicit case statements.
|
|
|
|
CFGBlock::FilterOptions FO;
|
|
|
|
FO.IgnoreDefaultsWithCoveredEnums = 1;
|
|
|
|
|
|
|
|
for (CFGBlock::filtered_pred_iterator
|
|
|
|
I = cfg->getExit().filtered_pred_start_end(FO); I.hasMore(); ++I) {
|
|
|
|
const CFGBlock& B = **I;
|
2010-03-21 05:06:02 +08:00
|
|
|
if (!live[B.getBlockID()])
|
|
|
|
continue;
|
2011-01-26 12:49:52 +08:00
|
|
|
|
2011-09-13 17:53:58 +08:00
|
|
|
// Skip blocks which contain an element marked as no-return. They don't
|
|
|
|
// represent actually viable edges into the exit block, so mark them as
|
|
|
|
// abnormal.
|
|
|
|
if (B.hasNoReturnElement()) {
|
|
|
|
HasAbnormalEdge = true;
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
|
2011-01-26 12:49:52 +08:00
|
|
|
// Destructors can appear after the 'return' in the CFG. This is
|
|
|
|
// normal. We need to look pass the destructors for the return
|
|
|
|
// statement (if it exists).
|
|
|
|
CFGBlock::const_reverse_iterator ri = B.rbegin(), re = B.rend();
|
2011-09-13 17:53:58 +08:00
|
|
|
|
|
|
|
for ( ; ri != re ; ++ri)
|
2013-02-22 04:58:29 +08:00
|
|
|
if (ri->getAs<CFGStmt>())
|
2011-01-26 12:49:52 +08:00
|
|
|
break;
|
2011-09-13 17:53:58 +08:00
|
|
|
|
2011-01-26 12:49:52 +08:00
|
|
|
// No more CFGElements in the block?
|
|
|
|
if (ri == re) {
|
2010-03-21 05:06:02 +08:00
|
|
|
if (B.getTerminator() && isa<CXXTryStmt>(B.getTerminator())) {
|
|
|
|
HasAbnormalEdge = true;
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
// A labeled empty statement, or the entry block...
|
|
|
|
HasPlainEdge = true;
|
|
|
|
continue;
|
|
|
|
}
|
2011-01-26 06:50:47 +08:00
|
|
|
|
2013-02-22 04:58:29 +08:00
|
|
|
CFGStmt CS = ri->castAs<CFGStmt>();
|
2011-08-24 07:05:04 +08:00
|
|
|
const Stmt *S = CS.getStmt();
|
2017-05-25 10:16:53 +08:00
|
|
|
if (isa<ReturnStmt>(S) || isa<CoreturnStmt>(S)) {
|
2010-03-21 05:06:02 +08:00
|
|
|
HasLiveReturn = true;
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
if (isa<ObjCAtThrowStmt>(S)) {
|
|
|
|
HasFakeEdge = true;
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
if (isa<CXXThrowExpr>(S)) {
|
|
|
|
HasFakeEdge = true;
|
|
|
|
continue;
|
|
|
|
}
|
2012-06-12 04:47:18 +08:00
|
|
|
if (isa<MSAsmStmt>(S)) {
|
|
|
|
// TODO: Verify this is correct.
|
|
|
|
HasFakeEdge = true;
|
|
|
|
HasLiveReturn = true;
|
|
|
|
continue;
|
|
|
|
}
|
2010-03-21 05:06:02 +08:00
|
|
|
if (isa<CXXTryStmt>(S)) {
|
|
|
|
HasAbnormalEdge = true;
|
|
|
|
continue;
|
|
|
|
}
|
2011-09-13 17:53:58 +08:00
|
|
|
if (std::find(B.succ_begin(), B.succ_end(), &cfg->getExit())
|
|
|
|
== B.succ_end()) {
|
|
|
|
HasAbnormalEdge = true;
|
|
|
|
continue;
|
2010-03-21 05:06:02 +08:00
|
|
|
}
|
2011-09-13 17:53:58 +08:00
|
|
|
|
|
|
|
HasPlainEdge = true;
|
2010-03-21 05:06:02 +08:00
|
|
|
}
|
|
|
|
if (!HasPlainEdge) {
|
|
|
|
if (HasLiveReturn)
|
|
|
|
return NeverFallThrough;
|
|
|
|
return NeverFallThroughOrReturn;
|
|
|
|
}
|
|
|
|
if (HasAbnormalEdge || HasFakeEdge || HasLiveReturn)
|
|
|
|
return MaybeFallThrough;
|
|
|
|
// This says AlwaysFallThrough for calls to functions that are not marked
|
|
|
|
// noreturn, that don't return. If people would like this warning to be more
|
|
|
|
// accurate, such functions should be marked as noreturn.
|
|
|
|
return AlwaysFallThrough;
|
|
|
|
}
|
|
|
|
|
2010-07-27 05:25:24 +08:00
|
|
|
namespace {
|
|
|
|
|
2010-03-21 05:06:02 +08:00
|
|
|
struct CheckFallThroughDiagnostics {
|
|
|
|
unsigned diag_MaybeFallThrough_HasNoReturn;
|
|
|
|
unsigned diag_MaybeFallThrough_ReturnsNonVoid;
|
|
|
|
unsigned diag_AlwaysFallThrough_HasNoReturn;
|
|
|
|
unsigned diag_AlwaysFallThrough_ReturnsNonVoid;
|
|
|
|
unsigned diag_NeverFallThroughOrReturn;
|
2016-10-27 15:30:31 +08:00
|
|
|
enum { Function, Block, Lambda, Coroutine } funMode;
|
2010-12-16 02:44:22 +08:00
|
|
|
SourceLocation FuncLoc;
|
2010-03-23 08:13:23 +08:00
|
|
|
|
2010-04-17 07:28:44 +08:00
|
|
|
static CheckFallThroughDiagnostics MakeForFunction(const Decl *Func) {
|
2010-03-21 05:06:02 +08:00
|
|
|
CheckFallThroughDiagnostics D;
|
2010-12-16 02:44:22 +08:00
|
|
|
D.FuncLoc = Func->getLocation();
|
2010-03-21 05:06:02 +08:00
|
|
|
D.diag_MaybeFallThrough_HasNoReturn =
|
|
|
|
diag::warn_falloff_noreturn_function;
|
|
|
|
D.diag_MaybeFallThrough_ReturnsNonVoid =
|
|
|
|
diag::warn_maybe_falloff_nonvoid_function;
|
|
|
|
D.diag_AlwaysFallThrough_HasNoReturn =
|
|
|
|
diag::warn_falloff_noreturn_function;
|
|
|
|
D.diag_AlwaysFallThrough_ReturnsNonVoid =
|
|
|
|
diag::warn_falloff_nonvoid_function;
|
2010-04-17 07:28:44 +08:00
|
|
|
|
|
|
|
// Don't suggest that virtual functions be marked "noreturn", since they
|
|
|
|
// might be overridden by non-noreturn functions.
|
|
|
|
bool isVirtualMethod = false;
|
|
|
|
if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Func))
|
|
|
|
isVirtualMethod = Method->isVirtual();
|
|
|
|
|
2011-10-11 02:15:57 +08:00
|
|
|
// Don't suggest that template instantiations be marked "noreturn"
|
|
|
|
bool isTemplateInstantiation = false;
|
2011-12-01 08:59:17 +08:00
|
|
|
if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(Func))
|
|
|
|
isTemplateInstantiation = Function->isTemplateInstantiation();
|
2011-10-11 02:15:57 +08:00
|
|
|
|
|
|
|
if (!isVirtualMethod && !isTemplateInstantiation)
|
2010-04-17 07:28:44 +08:00
|
|
|
D.diag_NeverFallThroughOrReturn =
|
|
|
|
diag::warn_suggest_noreturn_function;
|
|
|
|
else
|
|
|
|
D.diag_NeverFallThroughOrReturn = 0;
|
|
|
|
|
2012-02-16 00:20:15 +08:00
|
|
|
D.funMode = Function;
|
2010-03-21 05:06:02 +08:00
|
|
|
return D;
|
|
|
|
}
|
2010-03-23 08:13:23 +08:00
|
|
|
|
2016-10-27 15:30:31 +08:00
|
|
|
static CheckFallThroughDiagnostics MakeForCoroutine(const Decl *Func) {
|
|
|
|
CheckFallThroughDiagnostics D;
|
|
|
|
D.FuncLoc = Func->getLocation();
|
|
|
|
D.diag_MaybeFallThrough_HasNoReturn = 0;
|
|
|
|
D.diag_MaybeFallThrough_ReturnsNonVoid =
|
|
|
|
diag::warn_maybe_falloff_nonvoid_coroutine;
|
|
|
|
D.diag_AlwaysFallThrough_HasNoReturn = 0;
|
|
|
|
D.diag_AlwaysFallThrough_ReturnsNonVoid =
|
|
|
|
diag::warn_falloff_nonvoid_coroutine;
|
|
|
|
D.funMode = Coroutine;
|
|
|
|
return D;
|
|
|
|
}
|
|
|
|
|
2010-03-21 05:06:02 +08:00
|
|
|
static CheckFallThroughDiagnostics MakeForBlock() {
|
|
|
|
CheckFallThroughDiagnostics D;
|
|
|
|
D.diag_MaybeFallThrough_HasNoReturn =
|
|
|
|
diag::err_noreturn_block_has_return_expr;
|
|
|
|
D.diag_MaybeFallThrough_ReturnsNonVoid =
|
|
|
|
diag::err_maybe_falloff_nonvoid_block;
|
|
|
|
D.diag_AlwaysFallThrough_HasNoReturn =
|
|
|
|
diag::err_noreturn_block_has_return_expr;
|
|
|
|
D.diag_AlwaysFallThrough_ReturnsNonVoid =
|
|
|
|
diag::err_falloff_nonvoid_block;
|
2014-04-04 07:06:35 +08:00
|
|
|
D.diag_NeverFallThroughOrReturn = 0;
|
2012-02-16 00:20:15 +08:00
|
|
|
D.funMode = Block;
|
|
|
|
return D;
|
|
|
|
}
|
|
|
|
|
|
|
|
static CheckFallThroughDiagnostics MakeForLambda() {
|
|
|
|
CheckFallThroughDiagnostics D;
|
|
|
|
D.diag_MaybeFallThrough_HasNoReturn =
|
|
|
|
diag::err_noreturn_lambda_has_return_expr;
|
|
|
|
D.diag_MaybeFallThrough_ReturnsNonVoid =
|
|
|
|
diag::warn_maybe_falloff_nonvoid_lambda;
|
|
|
|
D.diag_AlwaysFallThrough_HasNoReturn =
|
|
|
|
diag::err_noreturn_lambda_has_return_expr;
|
|
|
|
D.diag_AlwaysFallThrough_ReturnsNonVoid =
|
|
|
|
diag::warn_falloff_nonvoid_lambda;
|
|
|
|
D.diag_NeverFallThroughOrReturn = 0;
|
|
|
|
D.funMode = Lambda;
|
2010-03-21 05:06:02 +08:00
|
|
|
return D;
|
|
|
|
}
|
2010-03-23 08:13:23 +08:00
|
|
|
|
2011-09-26 07:23:43 +08:00
|
|
|
bool checkDiagnostics(DiagnosticsEngine &D, bool ReturnsVoid,
|
2010-03-21 05:06:02 +08:00
|
|
|
bool HasNoReturn) const {
|
2012-02-16 00:20:15 +08:00
|
|
|
if (funMode == Function) {
|
2010-12-16 02:44:22 +08:00
|
|
|
return (ReturnsVoid ||
|
2014-06-16 07:30:39 +08:00
|
|
|
D.isIgnored(diag::warn_maybe_falloff_nonvoid_function,
|
|
|
|
FuncLoc)) &&
|
|
|
|
(!HasNoReturn ||
|
|
|
|
D.isIgnored(diag::warn_noreturn_function_has_return_expr,
|
|
|
|
FuncLoc)) &&
|
|
|
|
(!ReturnsVoid ||
|
|
|
|
D.isIgnored(diag::warn_suggest_noreturn_block, FuncLoc));
|
2010-03-21 05:06:02 +08:00
|
|
|
}
|
2016-10-27 15:30:31 +08:00
|
|
|
if (funMode == Coroutine) {
|
|
|
|
return (ReturnsVoid ||
|
|
|
|
D.isIgnored(diag::warn_maybe_falloff_nonvoid_function, FuncLoc) ||
|
|
|
|
D.isIgnored(diag::warn_maybe_falloff_nonvoid_coroutine,
|
|
|
|
FuncLoc)) &&
|
|
|
|
(!HasNoReturn);
|
|
|
|
}
|
2012-02-16 00:20:15 +08:00
|
|
|
// For blocks / lambdas.
|
2014-04-04 07:06:35 +08:00
|
|
|
return ReturnsVoid && !HasNoReturn;
|
2010-03-21 05:06:02 +08:00
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2015-10-07 07:40:43 +08:00
|
|
|
} // anonymous namespace
|
2010-07-27 05:25:24 +08:00
|
|
|
|
2010-03-21 05:06:02 +08:00
|
|
|
/// CheckFallThroughForFunctionDef - Check that we don't fall off the end of a
|
|
|
|
/// function that should return a value. Check that we don't fall off the end
|
|
|
|
/// of a noreturn function. We assume that functions and blocks not marked
|
|
|
|
/// noreturn will return.
|
|
|
|
static void CheckFallThroughForBody(Sema &S, const Decl *D, const Stmt *Body,
|
2011-02-23 09:51:48 +08:00
|
|
|
const BlockExpr *blkExpr,
|
2010-03-21 05:06:02 +08:00
|
|
|
const CheckFallThroughDiagnostics& CD,
|
2011-10-24 09:32:45 +08:00
|
|
|
AnalysisDeclContext &AC) {
|
2010-03-21 05:06:02 +08:00
|
|
|
|
|
|
|
bool ReturnsVoid = false;
|
|
|
|
bool HasNoReturn = false;
|
2017-05-25 10:16:53 +08:00
|
|
|
bool IsCoroutine = S.getCurFunction() && S.getCurFunction()->isCoroutine();
|
2010-03-21 05:06:02 +08:00
|
|
|
|
2016-10-27 15:30:31 +08:00
|
|
|
if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
|
|
|
|
if (const auto *CBody = dyn_cast<CoroutineBodyStmt>(Body))
|
|
|
|
ReturnsVoid = CBody->getFallthroughHandler() != nullptr;
|
|
|
|
else
|
|
|
|
ReturnsVoid = FD->getReturnType()->isVoidType();
|
2013-01-17 09:30:42 +08:00
|
|
|
HasNoReturn = FD->isNoReturn();
|
2010-03-21 05:06:02 +08:00
|
|
|
}
|
2016-10-27 15:30:31 +08:00
|
|
|
else if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
|
2014-01-26 00:55:45 +08:00
|
|
|
ReturnsVoid = MD->getReturnType()->isVoidType();
|
2010-03-21 05:06:02 +08:00
|
|
|
HasNoReturn = MD->hasAttr<NoReturnAttr>();
|
|
|
|
}
|
|
|
|
else if (isa<BlockDecl>(D)) {
|
2011-02-23 09:51:48 +08:00
|
|
|
QualType BlockTy = blkExpr->getType();
|
2010-03-23 08:13:23 +08:00
|
|
|
if (const FunctionType *FT =
|
2010-03-21 05:06:02 +08:00
|
|
|
BlockTy->getPointeeType()->getAs<FunctionType>()) {
|
2014-01-26 00:55:45 +08:00
|
|
|
if (FT->getReturnType()->isVoidType())
|
2010-03-21 05:06:02 +08:00
|
|
|
ReturnsVoid = true;
|
|
|
|
if (FT->getNoReturnAttr())
|
|
|
|
HasNoReturn = true;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2011-09-26 07:23:43 +08:00
|
|
|
DiagnosticsEngine &Diags = S.getDiagnostics();
|
2010-03-21 05:06:02 +08:00
|
|
|
|
|
|
|
// Short circuit for compilation speed.
|
|
|
|
if (CD.checkDiagnostics(Diags, ReturnsVoid, HasNoReturn))
|
|
|
|
return;
|
2014-10-24 21:19:19 +08:00
|
|
|
SourceLocation LBrace = Body->getLocStart(), RBrace = Body->getLocEnd();
|
2017-05-25 10:16:53 +08:00
|
|
|
auto EmitDiag = [&](SourceLocation Loc, unsigned DiagID) {
|
|
|
|
if (IsCoroutine)
|
|
|
|
S.Diag(Loc, DiagID) << S.getCurFunction()->CoroutinePromise->getType();
|
|
|
|
else
|
|
|
|
S.Diag(Loc, DiagID);
|
|
|
|
};
|
2014-10-24 21:19:19 +08:00
|
|
|
// Either in a function body compound statement, or a function-try-block.
|
|
|
|
switch (CheckFallThrough(AC)) {
|
|
|
|
case UnknownFallThrough:
|
|
|
|
break;
|
|
|
|
|
|
|
|
case MaybeFallThrough:
|
|
|
|
if (HasNoReturn)
|
2017-05-25 10:16:53 +08:00
|
|
|
EmitDiag(RBrace, CD.diag_MaybeFallThrough_HasNoReturn);
|
2014-10-24 21:19:19 +08:00
|
|
|
else if (!ReturnsVoid)
|
2017-05-25 10:16:53 +08:00
|
|
|
EmitDiag(RBrace, CD.diag_MaybeFallThrough_ReturnsNonVoid);
|
2014-10-24 21:19:19 +08:00
|
|
|
break;
|
|
|
|
case AlwaysFallThrough:
|
|
|
|
if (HasNoReturn)
|
2017-05-25 10:16:53 +08:00
|
|
|
EmitDiag(RBrace, CD.diag_AlwaysFallThrough_HasNoReturn);
|
2014-10-24 21:19:19 +08:00
|
|
|
else if (!ReturnsVoid)
|
2017-05-25 10:16:53 +08:00
|
|
|
EmitDiag(RBrace, CD.diag_AlwaysFallThrough_ReturnsNonVoid);
|
2014-10-24 21:19:19 +08:00
|
|
|
break;
|
|
|
|
case NeverFallThroughOrReturn:
|
|
|
|
if (ReturnsVoid && !HasNoReturn && CD.diag_NeverFallThroughOrReturn) {
|
|
|
|
if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
|
|
|
|
S.Diag(LBrace, CD.diag_NeverFallThroughOrReturn) << 0 << FD;
|
|
|
|
} else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
|
|
|
|
S.Diag(LBrace, CD.diag_NeverFallThroughOrReturn) << 1 << MD;
|
|
|
|
} else {
|
|
|
|
S.Diag(LBrace, CD.diag_NeverFallThroughOrReturn);
|
2011-08-31 17:01:53 +08:00
|
|
|
}
|
2014-10-24 21:19:19 +08:00
|
|
|
}
|
|
|
|
break;
|
|
|
|
case NeverFallThrough:
|
|
|
|
break;
|
2010-03-21 05:06:02 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2011-01-15 10:58:47 +08:00
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
// -Wuninitialized
|
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
|
2011-04-05 04:56:00 +08:00
|
|
|
namespace {
|
2011-04-05 14:48:00 +08:00
|
|
|
/// ContainsReference - A visitor class to search for references to
|
|
|
|
/// a particular declaration (the needle) within any evaluated component of an
|
|
|
|
/// expression (recursively).
|
2015-06-10 21:53:15 +08:00
|
|
|
class ContainsReference : public ConstEvaluatedExprVisitor<ContainsReference> {
|
2011-04-05 14:48:00 +08:00
|
|
|
bool FoundReference;
|
|
|
|
const DeclRefExpr *Needle;
|
|
|
|
|
2011-04-05 04:56:00 +08:00
|
|
|
public:
|
2015-06-10 21:53:15 +08:00
|
|
|
typedef ConstEvaluatedExprVisitor<ContainsReference> Inherited;
|
|
|
|
|
2011-04-05 14:48:00 +08:00
|
|
|
ContainsReference(ASTContext &Context, const DeclRefExpr *Needle)
|
2015-06-10 21:53:15 +08:00
|
|
|
: Inherited(Context), FoundReference(false), Needle(Needle) {}
|
2011-04-05 14:48:00 +08:00
|
|
|
|
2015-06-10 21:53:15 +08:00
|
|
|
void VisitExpr(const Expr *E) {
|
2011-04-05 04:56:00 +08:00
|
|
|
// Stop evaluating if we already have a reference.
|
2011-04-05 14:48:00 +08:00
|
|
|
if (FoundReference)
|
2011-04-05 04:56:00 +08:00
|
|
|
return;
|
2011-04-05 14:48:00 +08:00
|
|
|
|
2015-06-10 21:53:15 +08:00
|
|
|
Inherited::VisitExpr(E);
|
2011-04-05 04:56:00 +08:00
|
|
|
}
|
2011-04-05 14:48:00 +08:00
|
|
|
|
2015-06-10 21:53:15 +08:00
|
|
|
void VisitDeclRefExpr(const DeclRefExpr *E) {
|
2011-04-05 14:48:00 +08:00
|
|
|
if (E == Needle)
|
|
|
|
FoundReference = true;
|
|
|
|
else
|
2015-06-10 21:53:15 +08:00
|
|
|
Inherited::VisitDeclRefExpr(E);
|
2011-04-05 04:56:00 +08:00
|
|
|
}
|
2011-04-05 14:48:00 +08:00
|
|
|
|
|
|
|
bool doesContainReference() const { return FoundReference; }
|
2011-04-05 04:56:00 +08:00
|
|
|
};
|
2015-10-07 07:40:43 +08:00
|
|
|
} // anonymous namespace
|
2011-04-05 04:56:00 +08:00
|
|
|
|
2011-09-10 13:35:08 +08:00
|
|
|
static bool SuggestInitializationFixit(Sema &S, const VarDecl *VD) {
|
2012-03-08 08:22:50 +08:00
|
|
|
QualType VariableTy = VD->getType().getCanonicalType();
|
|
|
|
if (VariableTy->isBlockPointerType() &&
|
|
|
|
!VD->hasAttr<BlocksAttr>()) {
|
2014-07-09 07:46:20 +08:00
|
|
|
S.Diag(VD->getLocation(), diag::note_block_var_fixit_add_initialization)
|
|
|
|
<< VD->getDeclName()
|
|
|
|
<< FixItHint::CreateInsertion(VD->getLocation(), "__block ");
|
2012-03-08 08:22:50 +08:00
|
|
|
return true;
|
|
|
|
}
|
2013-09-20 08:27:40 +08:00
|
|
|
|
2011-09-10 13:35:08 +08:00
|
|
|
// Don't issue a fixit if there is already an initializer.
|
|
|
|
if (VD->getInit())
|
|
|
|
return false;
|
2012-05-03 09:09:59 +08:00
|
|
|
|
|
|
|
// Don't suggest a fixit inside macros.
|
|
|
|
if (VD->getLocEnd().isMacroID())
|
|
|
|
return false;
|
|
|
|
|
2014-05-03 11:45:55 +08:00
|
|
|
SourceLocation Loc = S.getLocForEndOfToken(VD->getLocEnd());
|
2013-09-20 08:27:40 +08:00
|
|
|
|
|
|
|
// Suggest possible initialization (if any).
|
|
|
|
std::string Init = S.getFixItZeroInitializerForType(VariableTy, Loc);
|
|
|
|
if (Init.empty())
|
|
|
|
return false;
|
|
|
|
|
Improve 0-argument -Wvexing-parse diagnostic by adding notes with fix-its:
- If the declarator is at the start of a line, and the previous line contained
another declarator and ended with a comma, then that comma was probably a
typo for a semicolon:
int n = 0, m = 1, l = 2, // k = 5;
myImportantFunctionCall(); // oops!
- If removing the parentheses would correctly initialize the object, then
produce a note suggesting that fix.
- Otherwise, if there is a simple initializer we can suggest which performs
value-initialization, then provide a note suggesting a correction to that
initializer.
Sema::Declarator now tracks the location of the comma prior to the declarator in
the declaration, if there is one, to facilitate providing the note. The code to
determine an appropriate initializer from the -Wuninitialized warning has been
factored out to allow use in both that and -Wvexing-parse.
llvm-svn: 148072
2012-01-13 07:53:29 +08:00
|
|
|
S.Diag(Loc, diag::note_var_fixit_add_initialization) << VD->getDeclName()
|
|
|
|
<< FixItHint::CreateInsertion(Loc, Init);
|
|
|
|
return true;
|
2011-09-10 13:35:08 +08:00
|
|
|
}
|
|
|
|
|
2012-05-26 14:20:46 +08:00
|
|
|
/// Create a fixit to remove an if-like statement, on the assumption that its
|
|
|
|
/// condition is CondVal.
|
|
|
|
static void CreateIfFixit(Sema &S, const Stmt *If, const Stmt *Then,
|
|
|
|
const Stmt *Else, bool CondVal,
|
|
|
|
FixItHint &Fixit1, FixItHint &Fixit2) {
|
|
|
|
if (CondVal) {
|
|
|
|
// If condition is always true, remove all but the 'then'.
|
|
|
|
Fixit1 = FixItHint::CreateRemoval(
|
|
|
|
CharSourceRange::getCharRange(If->getLocStart(),
|
|
|
|
Then->getLocStart()));
|
|
|
|
if (Else) {
|
2015-11-15 10:31:46 +08:00
|
|
|
SourceLocation ElseKwLoc = S.getLocForEndOfToken(Then->getLocEnd());
|
2012-05-26 14:20:46 +08:00
|
|
|
Fixit2 = FixItHint::CreateRemoval(
|
|
|
|
SourceRange(ElseKwLoc, Else->getLocEnd()));
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
// If condition is always false, remove all but the 'else'.
|
|
|
|
if (Else)
|
|
|
|
Fixit1 = FixItHint::CreateRemoval(
|
|
|
|
CharSourceRange::getCharRange(If->getLocStart(),
|
|
|
|
Else->getLocStart()));
|
|
|
|
else
|
|
|
|
Fixit1 = FixItHint::CreateRemoval(If->getSourceRange());
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// DiagUninitUse -- Helper function to produce a diagnostic for an
|
|
|
|
/// uninitialized use of a variable.
|
|
|
|
static void DiagUninitUse(Sema &S, const VarDecl *VD, const UninitUse &Use,
|
|
|
|
bool IsCapturedByBlock) {
|
|
|
|
bool Diagnosed = false;
|
|
|
|
|
2013-09-13 02:49:10 +08:00
|
|
|
switch (Use.getKind()) {
|
|
|
|
case UninitUse::Always:
|
|
|
|
S.Diag(Use.getUser()->getLocStart(), diag::warn_uninit_var)
|
|
|
|
<< VD->getDeclName() << IsCapturedByBlock
|
|
|
|
<< Use.getUser()->getSourceRange();
|
|
|
|
return;
|
|
|
|
|
|
|
|
case UninitUse::AfterDecl:
|
|
|
|
case UninitUse::AfterCall:
|
|
|
|
S.Diag(VD->getLocation(), diag::warn_sometimes_uninit_var)
|
|
|
|
<< VD->getDeclName() << IsCapturedByBlock
|
|
|
|
<< (Use.getKind() == UninitUse::AfterDecl ? 4 : 5)
|
|
|
|
<< const_cast<DeclContext*>(VD->getLexicalDeclContext())
|
|
|
|
<< VD->getSourceRange();
|
|
|
|
S.Diag(Use.getUser()->getLocStart(), diag::note_uninit_var_use)
|
|
|
|
<< IsCapturedByBlock << Use.getUser()->getSourceRange();
|
|
|
|
return;
|
|
|
|
|
|
|
|
case UninitUse::Maybe:
|
|
|
|
case UninitUse::Sometimes:
|
|
|
|
// Carry on to report sometimes-uninitialized branches, if possible,
|
|
|
|
// or a 'may be used uninitialized' diagnostic otherwise.
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
|
2012-05-26 14:20:46 +08:00
|
|
|
// Diagnose each branch which leads to a sometimes-uninitialized use.
|
2012-05-25 10:17:09 +08:00
|
|
|
for (UninitUse::branch_iterator I = Use.branch_begin(), E = Use.branch_end();
|
|
|
|
I != E; ++I) {
|
2012-05-26 14:20:46 +08:00
|
|
|
assert(Use.getKind() == UninitUse::Sometimes);
|
|
|
|
|
|
|
|
const Expr *User = Use.getUser();
|
2012-05-25 10:17:09 +08:00
|
|
|
const Stmt *Term = I->Terminator;
|
2012-05-26 14:20:46 +08:00
|
|
|
|
|
|
|
// Information used when building the diagnostic.
|
2012-05-25 10:17:09 +08:00
|
|
|
unsigned DiagKind;
|
2012-10-08 09:11:04 +08:00
|
|
|
StringRef Str;
|
2012-05-26 14:20:46 +08:00
|
|
|
SourceRange Range;
|
|
|
|
|
2013-03-02 05:41:22 +08:00
|
|
|
// FixIts to suppress the diagnostic by removing the dead condition.
|
2012-05-26 14:20:46 +08:00
|
|
|
// For all binary terminators, branch 0 is taken if the condition is true,
|
|
|
|
// and branch 1 is taken if the condition is false.
|
|
|
|
int RemoveDiagKind = -1;
|
|
|
|
const char *FixitStr =
|
|
|
|
S.getLangOpts().CPlusPlus ? (I->Output ? "true" : "false")
|
|
|
|
: (I->Output ? "1" : "0");
|
|
|
|
FixItHint Fixit1, Fixit2;
|
|
|
|
|
2013-09-13 02:49:10 +08:00
|
|
|
switch (Term ? Term->getStmtClass() : Stmt::DeclStmtClass) {
|
2012-05-25 10:17:09 +08:00
|
|
|
default:
|
2012-05-26 14:20:46 +08:00
|
|
|
// Don't know how to report this. Just fall back to 'may be used
|
2013-09-13 02:49:10 +08:00
|
|
|
// uninitialized'. FIXME: Can this happen?
|
2012-05-25 10:17:09 +08:00
|
|
|
continue;
|
|
|
|
|
|
|
|
// "condition is true / condition is false".
|
2012-05-26 14:20:46 +08:00
|
|
|
case Stmt::IfStmtClass: {
|
|
|
|
const IfStmt *IS = cast<IfStmt>(Term);
|
2012-05-25 10:17:09 +08:00
|
|
|
DiagKind = 0;
|
|
|
|
Str = "if";
|
2012-05-26 14:20:46 +08:00
|
|
|
Range = IS->getCond()->getSourceRange();
|
|
|
|
RemoveDiagKind = 0;
|
|
|
|
CreateIfFixit(S, IS, IS->getThen(), IS->getElse(),
|
|
|
|
I->Output, Fixit1, Fixit2);
|
2012-05-25 10:17:09 +08:00
|
|
|
break;
|
2012-05-26 14:20:46 +08:00
|
|
|
}
|
|
|
|
case Stmt::ConditionalOperatorClass: {
|
|
|
|
const ConditionalOperator *CO = cast<ConditionalOperator>(Term);
|
2012-05-25 10:17:09 +08:00
|
|
|
DiagKind = 0;
|
|
|
|
Str = "?:";
|
2012-05-26 14:20:46 +08:00
|
|
|
Range = CO->getCond()->getSourceRange();
|
|
|
|
RemoveDiagKind = 0;
|
|
|
|
CreateIfFixit(S, CO, CO->getTrueExpr(), CO->getFalseExpr(),
|
|
|
|
I->Output, Fixit1, Fixit2);
|
2012-05-25 10:17:09 +08:00
|
|
|
break;
|
2012-05-26 14:20:46 +08:00
|
|
|
}
|
2012-05-25 10:17:09 +08:00
|
|
|
case Stmt::BinaryOperatorClass: {
|
|
|
|
const BinaryOperator *BO = cast<BinaryOperator>(Term);
|
|
|
|
if (!BO->isLogicalOp())
|
|
|
|
continue;
|
|
|
|
DiagKind = 0;
|
|
|
|
Str = BO->getOpcodeStr();
|
|
|
|
Range = BO->getLHS()->getSourceRange();
|
2012-05-26 14:20:46 +08:00
|
|
|
RemoveDiagKind = 0;
|
|
|
|
if ((BO->getOpcode() == BO_LAnd && I->Output) ||
|
|
|
|
(BO->getOpcode() == BO_LOr && !I->Output))
|
|
|
|
// true && y -> y, false || y -> y.
|
|
|
|
Fixit1 = FixItHint::CreateRemoval(SourceRange(BO->getLocStart(),
|
|
|
|
BO->getOperatorLoc()));
|
|
|
|
else
|
|
|
|
// false && y -> false, true || y -> true.
|
|
|
|
Fixit1 = FixItHint::CreateReplacement(BO->getSourceRange(), FixitStr);
|
2012-05-25 10:17:09 +08:00
|
|
|
break;
|
|
|
|
}
|
|
|
|
|
|
|
|
// "loop is entered / loop is exited".
|
|
|
|
case Stmt::WhileStmtClass:
|
|
|
|
DiagKind = 1;
|
|
|
|
Str = "while";
|
|
|
|
Range = cast<WhileStmt>(Term)->getCond()->getSourceRange();
|
2012-05-26 14:20:46 +08:00
|
|
|
RemoveDiagKind = 1;
|
|
|
|
Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
|
2012-05-25 10:17:09 +08:00
|
|
|
break;
|
|
|
|
case Stmt::ForStmtClass:
|
|
|
|
DiagKind = 1;
|
|
|
|
Str = "for";
|
|
|
|
Range = cast<ForStmt>(Term)->getCond()->getSourceRange();
|
2012-05-26 14:20:46 +08:00
|
|
|
RemoveDiagKind = 1;
|
|
|
|
if (I->Output)
|
|
|
|
Fixit1 = FixItHint::CreateRemoval(Range);
|
|
|
|
else
|
|
|
|
Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
|
2012-05-25 10:17:09 +08:00
|
|
|
break;
|
2013-09-13 02:49:10 +08:00
|
|
|
case Stmt::CXXForRangeStmtClass:
|
|
|
|
if (I->Output == 1) {
|
|
|
|
// The use occurs if a range-based for loop's body never executes.
|
|
|
|
// That may be impossible, and there's no syntactic fix for this,
|
|
|
|
// so treat it as a 'may be uninitialized' case.
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
DiagKind = 1;
|
|
|
|
Str = "for";
|
|
|
|
Range = cast<CXXForRangeStmt>(Term)->getRangeInit()->getSourceRange();
|
|
|
|
break;
|
2012-05-25 10:17:09 +08:00
|
|
|
|
|
|
|
// "condition is true / loop is exited".
|
|
|
|
case Stmt::DoStmtClass:
|
|
|
|
DiagKind = 2;
|
|
|
|
Str = "do";
|
|
|
|
Range = cast<DoStmt>(Term)->getCond()->getSourceRange();
|
2012-05-26 14:20:46 +08:00
|
|
|
RemoveDiagKind = 1;
|
|
|
|
Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
|
2012-05-25 10:17:09 +08:00
|
|
|
break;
|
|
|
|
|
|
|
|
// "switch case is taken".
|
|
|
|
case Stmt::CaseStmtClass:
|
|
|
|
DiagKind = 3;
|
|
|
|
Str = "case";
|
|
|
|
Range = cast<CaseStmt>(Term)->getLHS()->getSourceRange();
|
|
|
|
break;
|
|
|
|
case Stmt::DefaultStmtClass:
|
|
|
|
DiagKind = 3;
|
|
|
|
Str = "default";
|
|
|
|
Range = cast<DefaultStmt>(Term)->getDefaultLoc();
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
|
2012-05-26 14:20:46 +08:00
|
|
|
S.Diag(Range.getBegin(), diag::warn_sometimes_uninit_var)
|
|
|
|
<< VD->getDeclName() << IsCapturedByBlock << DiagKind
|
|
|
|
<< Str << I->Output << Range;
|
|
|
|
S.Diag(User->getLocStart(), diag::note_uninit_var_use)
|
|
|
|
<< IsCapturedByBlock << User->getSourceRange();
|
|
|
|
if (RemoveDiagKind != -1)
|
|
|
|
S.Diag(Fixit1.RemoveRange.getBegin(), diag::note_uninit_fixit_remove_cond)
|
|
|
|
<< RemoveDiagKind << Str << I->Output << Fixit1 << Fixit2;
|
|
|
|
|
|
|
|
Diagnosed = true;
|
2012-05-25 10:17:09 +08:00
|
|
|
}
|
2012-05-26 14:20:46 +08:00
|
|
|
|
|
|
|
if (!Diagnosed)
|
2013-09-13 02:49:10 +08:00
|
|
|
S.Diag(Use.getUser()->getLocStart(), diag::warn_maybe_uninit_var)
|
2012-05-26 14:20:46 +08:00
|
|
|
<< VD->getDeclName() << IsCapturedByBlock
|
|
|
|
<< Use.getUser()->getSourceRange();
|
2012-05-25 10:17:09 +08:00
|
|
|
}
|
|
|
|
|
2011-04-06 02:27:05 +08:00
|
|
|
/// DiagnoseUninitializedUse -- Helper function for diagnosing uses of an
|
|
|
|
/// uninitialized variable. This manages the different forms of diagnostic
|
|
|
|
/// emitted for particular types of uses. Returns true if the use was diagnosed
|
2012-05-25 10:17:09 +08:00
|
|
|
/// as a warning. If a particular use is one we omit warnings for, returns
|
2011-04-06 02:27:05 +08:00
|
|
|
/// false.
|
|
|
|
static bool DiagnoseUninitializedUse(Sema &S, const VarDecl *VD,
|
2012-05-25 10:17:09 +08:00
|
|
|
const UninitUse &Use,
|
2011-10-14 02:50:06 +08:00
|
|
|
bool alwaysReportSelfInit = false) {
|
2012-05-25 10:17:09 +08:00
|
|
|
if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Use.getUser())) {
|
2012-05-10 05:08:22 +08:00
|
|
|
// Inspect the initializer of the variable declaration which is
|
|
|
|
// being referenced prior to its initialization. We emit
|
|
|
|
// specialized diagnostics for self-initialization, and we
|
|
|
|
// specifically avoid warning about self references which take the
|
|
|
|
// form of:
|
|
|
|
//
|
|
|
|
// int x = x;
|
|
|
|
//
|
|
|
|
// This is used to indicate to GCC that 'x' is intentionally left
|
|
|
|
// uninitialized. Proven code paths which access 'x' in
|
|
|
|
// an uninitialized state after this will still warn.
|
|
|
|
if (const Expr *Initializer = VD->getInit()) {
|
|
|
|
if (!alwaysReportSelfInit && DRE == Initializer->IgnoreParenImpCasts())
|
|
|
|
return false;
|
|
|
|
|
|
|
|
ContainsReference CR(S.Context, DRE);
|
2015-06-10 21:53:15 +08:00
|
|
|
CR.Visit(Initializer);
|
2012-05-10 05:08:22 +08:00
|
|
|
if (CR.doesContainReference()) {
|
2011-04-06 02:18:05 +08:00
|
|
|
S.Diag(DRE->getLocStart(),
|
|
|
|
diag::warn_uninit_self_reference_in_init)
|
2012-05-10 05:08:22 +08:00
|
|
|
<< VD->getDeclName() << VD->getLocation() << DRE->getSourceRange();
|
|
|
|
return true;
|
2011-04-06 02:18:05 +08:00
|
|
|
}
|
|
|
|
}
|
2012-05-10 05:08:22 +08:00
|
|
|
|
2012-05-26 14:20:46 +08:00
|
|
|
DiagUninitUse(S, VD, Use, false);
|
2011-04-06 02:18:05 +08:00
|
|
|
} else {
|
2012-05-25 10:17:09 +08:00
|
|
|
const BlockExpr *BE = cast<BlockExpr>(Use.getUser());
|
2012-05-26 14:20:46 +08:00
|
|
|
if (VD->getType()->isBlockPointerType() && !VD->hasAttr<BlocksAttr>())
|
|
|
|
S.Diag(BE->getLocStart(),
|
|
|
|
diag::warn_uninit_byref_blockvar_captured_by_block)
|
2012-03-08 08:22:50 +08:00
|
|
|
<< VD->getDeclName();
|
2012-05-26 14:20:46 +08:00
|
|
|
else
|
|
|
|
DiagUninitUse(S, VD, Use, true);
|
2011-04-06 02:18:05 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
// Report where the variable was declared when the use wasn't within
|
2011-09-10 13:35:08 +08:00
|
|
|
// the initializer of that declaration & we didn't already suggest
|
|
|
|
// an initialization fixit.
|
2012-05-10 05:08:22 +08:00
|
|
|
if (!SuggestInitializationFixit(S, VD))
|
2016-04-29 08:37:43 +08:00
|
|
|
S.Diag(VD->getLocStart(), diag::note_var_declared_here)
|
2011-04-06 02:18:05 +08:00
|
|
|
<< VD->getDeclName();
|
|
|
|
|
2011-04-06 02:27:05 +08:00
|
|
|
return true;
|
2011-04-06 02:18:08 +08:00
|
|
|
}
|
|
|
|
|
2012-05-04 02:27:39 +08:00
|
|
|
namespace {
|
|
|
|
class FallthroughMapper : public RecursiveASTVisitor<FallthroughMapper> {
|
|
|
|
public:
|
|
|
|
FallthroughMapper(Sema &S)
|
|
|
|
: FoundSwitchStatements(false),
|
|
|
|
S(S) {
|
|
|
|
}
|
|
|
|
|
|
|
|
bool foundSwitchStatements() const { return FoundSwitchStatements; }
|
|
|
|
|
|
|
|
void markFallthroughVisited(const AttributedStmt *Stmt) {
|
|
|
|
bool Found = FallthroughStmts.erase(Stmt);
|
|
|
|
assert(Found);
|
2012-05-04 03:46:38 +08:00
|
|
|
(void)Found;
|
2012-05-04 02:27:39 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
typedef llvm::SmallPtrSet<const AttributedStmt*, 8> AttrStmts;
|
|
|
|
|
|
|
|
const AttrStmts &getFallthroughStmts() const {
|
|
|
|
return FallthroughStmts;
|
|
|
|
}
|
|
|
|
|
2013-01-30 11:49:44 +08:00
|
|
|
void fillReachableBlocks(CFG *Cfg) {
|
|
|
|
assert(ReachableBlocks.empty() && "ReachableBlocks already filled");
|
|
|
|
std::deque<const CFGBlock *> BlockQueue;
|
|
|
|
|
|
|
|
ReachableBlocks.insert(&Cfg->getEntry());
|
|
|
|
BlockQueue.push_back(&Cfg->getEntry());
|
2013-02-07 10:17:19 +08:00
|
|
|
// Mark all case blocks reachable to avoid problems with switching on
|
|
|
|
// constants, covered enums, etc.
|
|
|
|
// These blocks can contain fall-through annotations, and we don't want to
|
|
|
|
// issue a warn_fallthrough_attr_unreachable for them.
|
2014-05-16 04:50:47 +08:00
|
|
|
for (const auto *B : *Cfg) {
|
2013-02-07 10:17:19 +08:00
|
|
|
const Stmt *L = B->getLabel();
|
2014-11-19 15:49:47 +08:00
|
|
|
if (L && isa<SwitchCase>(L) && ReachableBlocks.insert(B).second)
|
2013-02-07 10:17:19 +08:00
|
|
|
BlockQueue.push_back(B);
|
|
|
|
}
|
|
|
|
|
2013-01-30 11:49:44 +08:00
|
|
|
while (!BlockQueue.empty()) {
|
|
|
|
const CFGBlock *P = BlockQueue.front();
|
|
|
|
BlockQueue.pop_front();
|
|
|
|
for (CFGBlock::const_succ_iterator I = P->succ_begin(),
|
|
|
|
E = P->succ_end();
|
|
|
|
I != E; ++I) {
|
2014-11-19 15:49:47 +08:00
|
|
|
if (*I && ReachableBlocks.insert(*I).second)
|
2013-01-30 11:49:44 +08:00
|
|
|
BlockQueue.push_back(*I);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-03-22 09:49:19 +08:00
|
|
|
bool checkFallThroughIntoBlock(const CFGBlock &B, int &AnnotatedCnt,
|
|
|
|
bool IsTemplateInstantiation) {
|
2013-01-30 11:49:44 +08:00
|
|
|
assert(!ReachableBlocks.empty() && "ReachableBlocks empty");
|
|
|
|
|
2012-05-04 02:27:39 +08:00
|
|
|
int UnannotatedCnt = 0;
|
|
|
|
AnnotatedCnt = 0;
|
|
|
|
|
2014-05-16 04:50:47 +08:00
|
|
|
std::deque<const CFGBlock*> BlockQueue(B.pred_begin(), B.pred_end());
|
2012-05-04 02:27:39 +08:00
|
|
|
while (!BlockQueue.empty()) {
|
|
|
|
const CFGBlock *P = BlockQueue.front();
|
|
|
|
BlockQueue.pop_front();
|
2014-02-27 10:43:25 +08:00
|
|
|
if (!P) continue;
|
2012-05-04 02:27:39 +08:00
|
|
|
|
|
|
|
const Stmt *Term = P->getTerminator();
|
|
|
|
if (Term && isa<SwitchStmt>(Term))
|
|
|
|
continue; // Switch statement, good.
|
|
|
|
|
|
|
|
const SwitchCase *SW = dyn_cast_or_null<SwitchCase>(P->getLabel());
|
|
|
|
if (SW && SW->getSubStmt() == B.getLabel() && P->begin() == P->end())
|
|
|
|
continue; // Previous case label has no statements, good.
|
|
|
|
|
2013-01-26 04:44:56 +08:00
|
|
|
const LabelStmt *L = dyn_cast_or_null<LabelStmt>(P->getLabel());
|
|
|
|
if (L && L->getSubStmt() == B.getLabel() && P->begin() == P->end())
|
|
|
|
continue; // Case label is preceded with a normal label, good.
|
|
|
|
|
2013-01-30 11:49:44 +08:00
|
|
|
if (!ReachableBlocks.count(P)) {
|
2013-02-07 10:17:19 +08:00
|
|
|
for (CFGBlock::const_reverse_iterator ElemIt = P->rbegin(),
|
|
|
|
ElemEnd = P->rend();
|
|
|
|
ElemIt != ElemEnd; ++ElemIt) {
|
2013-02-23 08:29:34 +08:00
|
|
|
if (Optional<CFGStmt> CS = ElemIt->getAs<CFGStmt>()) {
|
|
|
|
if (const AttributedStmt *AS = asFallThroughAttr(CS->getStmt())) {
|
2017-03-22 09:49:19 +08:00
|
|
|
// Don't issue a warning for an unreachable fallthrough
|
|
|
|
// attribute in template instantiations as it may not be
|
|
|
|
// unreachable in all instantiations of the template.
|
|
|
|
if (!IsTemplateInstantiation)
|
|
|
|
S.Diag(AS->getLocStart(),
|
|
|
|
diag::warn_fallthrough_attr_unreachable);
|
2012-05-04 02:27:39 +08:00
|
|
|
markFallthroughVisited(AS);
|
|
|
|
++AnnotatedCnt;
|
2013-02-07 10:17:19 +08:00
|
|
|
break;
|
2012-05-04 02:27:39 +08:00
|
|
|
}
|
|
|
|
// Don't care about other unreachable statements.
|
|
|
|
}
|
|
|
|
}
|
|
|
|
// If there are no unreachable statements, this may be a special
|
|
|
|
// case in CFG:
|
|
|
|
// case X: {
|
|
|
|
// A a; // A has a destructor.
|
|
|
|
// break;
|
|
|
|
// }
|
|
|
|
// // <<<< This place is represented by a 'hanging' CFG block.
|
|
|
|
// case Y:
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
|
|
|
|
const Stmt *LastStmt = getLastStmt(*P);
|
|
|
|
if (const AttributedStmt *AS = asFallThroughAttr(LastStmt)) {
|
|
|
|
markFallthroughVisited(AS);
|
|
|
|
++AnnotatedCnt;
|
|
|
|
continue; // Fallthrough annotation, good.
|
|
|
|
}
|
|
|
|
|
|
|
|
if (!LastStmt) { // This block contains no executable statements.
|
|
|
|
// Traverse its predecessors.
|
|
|
|
std::copy(P->pred_begin(), P->pred_end(),
|
|
|
|
std::back_inserter(BlockQueue));
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
|
|
|
|
++UnannotatedCnt;
|
|
|
|
}
|
|
|
|
return !!UnannotatedCnt;
|
|
|
|
}
|
|
|
|
|
|
|
|
// RecursiveASTVisitor setup.
|
|
|
|
bool shouldWalkTypesOfTypeLocs() const { return false; }
|
|
|
|
|
|
|
|
bool VisitAttributedStmt(AttributedStmt *S) {
|
|
|
|
if (asFallThroughAttr(S))
|
|
|
|
FallthroughStmts.insert(S);
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
|
|
|
bool VisitSwitchStmt(SwitchStmt *S) {
|
|
|
|
FoundSwitchStatements = true;
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
2013-04-02 23:20:32 +08:00
|
|
|
// We don't want to traverse local type declarations. We analyze their
|
|
|
|
// methods separately.
|
|
|
|
bool TraverseDecl(Decl *D) { return true; }
|
|
|
|
|
2014-06-24 23:28:21 +08:00
|
|
|
// We analyze lambda bodies separately. Skip them here.
|
|
|
|
bool TraverseLambdaBody(LambdaExpr *LE) { return true; }
|
|
|
|
|
2012-05-04 02:27:39 +08:00
|
|
|
private:
|
|
|
|
|
|
|
|
static const AttributedStmt *asFallThroughAttr(const Stmt *S) {
|
|
|
|
if (const AttributedStmt *AS = dyn_cast_or_null<AttributedStmt>(S)) {
|
|
|
|
if (hasSpecificAttr<FallThroughAttr>(AS->getAttrs()))
|
|
|
|
return AS;
|
|
|
|
}
|
2014-05-26 14:22:03 +08:00
|
|
|
return nullptr;
|
2012-05-04 02:27:39 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
static const Stmt *getLastStmt(const CFGBlock &B) {
|
|
|
|
if (const Stmt *Term = B.getTerminator())
|
|
|
|
return Term;
|
|
|
|
for (CFGBlock::const_reverse_iterator ElemIt = B.rbegin(),
|
|
|
|
ElemEnd = B.rend();
|
|
|
|
ElemIt != ElemEnd; ++ElemIt) {
|
2013-02-23 08:29:34 +08:00
|
|
|
if (Optional<CFGStmt> CS = ElemIt->getAs<CFGStmt>())
|
|
|
|
return CS->getStmt();
|
2012-05-04 02:27:39 +08:00
|
|
|
}
|
|
|
|
// Workaround to detect a statement thrown out by CFGBuilder:
|
|
|
|
// case X: {} case Y:
|
|
|
|
// case X: ; case Y:
|
|
|
|
if (const SwitchCase *SW = dyn_cast_or_null<SwitchCase>(B.getLabel()))
|
|
|
|
if (!isa<SwitchCase>(SW->getSubStmt()))
|
|
|
|
return SW->getSubStmt();
|
|
|
|
|
2014-05-26 14:22:03 +08:00
|
|
|
return nullptr;
|
2012-05-04 02:27:39 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
bool FoundSwitchStatements;
|
|
|
|
AttrStmts FallthroughStmts;
|
|
|
|
Sema &S;
|
2013-01-30 11:49:44 +08:00
|
|
|
llvm::SmallPtrSet<const CFGBlock *, 16> ReachableBlocks;
|
2012-05-04 02:27:39 +08:00
|
|
|
};
|
2015-10-07 07:40:43 +08:00
|
|
|
} // anonymous namespace
|
2012-05-04 02:27:39 +08:00
|
|
|
|
2016-03-08 08:32:55 +08:00
|
|
|
static StringRef getFallthroughAttrSpelling(Preprocessor &PP,
|
|
|
|
SourceLocation Loc) {
|
|
|
|
TokenValue FallthroughTokens[] = {
|
|
|
|
tok::l_square, tok::l_square,
|
|
|
|
PP.getIdentifierInfo("fallthrough"),
|
|
|
|
tok::r_square, tok::r_square
|
|
|
|
};
|
|
|
|
|
|
|
|
TokenValue ClangFallthroughTokens[] = {
|
|
|
|
tok::l_square, tok::l_square, PP.getIdentifierInfo("clang"),
|
|
|
|
tok::coloncolon, PP.getIdentifierInfo("fallthrough"),
|
|
|
|
tok::r_square, tok::r_square
|
|
|
|
};
|
|
|
|
|
2017-12-05 04:27:34 +08:00
|
|
|
bool PreferClangAttr = !PP.getLangOpts().CPlusPlus17;
|
2016-03-08 08:32:55 +08:00
|
|
|
|
|
|
|
StringRef MacroName;
|
|
|
|
if (PreferClangAttr)
|
|
|
|
MacroName = PP.getLastMacroWithSpelling(Loc, ClangFallthroughTokens);
|
|
|
|
if (MacroName.empty())
|
|
|
|
MacroName = PP.getLastMacroWithSpelling(Loc, FallthroughTokens);
|
|
|
|
if (MacroName.empty() && !PreferClangAttr)
|
|
|
|
MacroName = PP.getLastMacroWithSpelling(Loc, ClangFallthroughTokens);
|
|
|
|
if (MacroName.empty())
|
|
|
|
MacroName = PreferClangAttr ? "[[clang::fallthrough]]" : "[[fallthrough]]";
|
|
|
|
return MacroName;
|
|
|
|
}
|
|
|
|
|
2012-06-02 09:01:07 +08:00
|
|
|
static void DiagnoseSwitchLabelsFallthrough(Sema &S, AnalysisDeclContext &AC,
|
2012-06-16 05:22:05 +08:00
|
|
|
bool PerFunction) {
|
2017-10-18 22:33:27 +08:00
|
|
|
// Only perform this analysis when using [[]] attributes. There is no good
|
|
|
|
// workflow for this warning when not using C++11. There is no good way to
|
|
|
|
// silence the warning (no attribute is available) unless we are using
|
|
|
|
// [[]] attributes. One could use pragmas to silence the warning, but as a
|
|
|
|
// general solution that is gross and not in the spirit of this warning.
|
2012-11-13 05:20:48 +08:00
|
|
|
//
|
2017-10-18 22:33:27 +08:00
|
|
|
// NOTE: This an intermediate solution. There are on-going discussions on
|
2012-11-13 05:20:48 +08:00
|
|
|
// how to properly support this warning outside of C++11 with an annotation.
|
2017-10-18 22:33:27 +08:00
|
|
|
if (!AC.getASTContext().getLangOpts().DoubleSquareBracketAttributes)
|
2012-11-13 05:20:48 +08:00
|
|
|
return;
|
|
|
|
|
2012-05-04 02:27:39 +08:00
|
|
|
FallthroughMapper FM(S);
|
|
|
|
FM.TraverseStmt(AC.getBody());
|
|
|
|
|
|
|
|
if (!FM.foundSwitchStatements())
|
|
|
|
return;
|
|
|
|
|
2012-06-16 05:22:05 +08:00
|
|
|
if (PerFunction && FM.getFallthroughStmts().empty())
|
2012-06-02 09:01:07 +08:00
|
|
|
return;
|
|
|
|
|
2012-05-04 02:27:39 +08:00
|
|
|
CFG *Cfg = AC.getCFG();
|
|
|
|
|
|
|
|
if (!Cfg)
|
|
|
|
return;
|
|
|
|
|
2013-01-30 11:49:44 +08:00
|
|
|
FM.fillReachableBlocks(Cfg);
|
2012-05-04 02:27:39 +08:00
|
|
|
|
2015-07-31 01:22:52 +08:00
|
|
|
for (const CFGBlock *B : llvm::reverse(*Cfg)) {
|
2013-01-25 23:49:34 +08:00
|
|
|
const Stmt *Label = B->getLabel();
|
2012-05-04 02:27:39 +08:00
|
|
|
|
|
|
|
if (!Label || !isa<SwitchCase>(Label))
|
|
|
|
continue;
|
|
|
|
|
2013-01-30 11:49:44 +08:00
|
|
|
int AnnotatedCnt;
|
|
|
|
|
2017-03-22 09:49:19 +08:00
|
|
|
bool IsTemplateInstantiation = false;
|
|
|
|
if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(AC.getDecl()))
|
|
|
|
IsTemplateInstantiation = Function->isTemplateInstantiation();
|
|
|
|
if (!FM.checkFallThroughIntoBlock(*B, AnnotatedCnt,
|
|
|
|
IsTemplateInstantiation))
|
2012-05-04 02:27:39 +08:00
|
|
|
continue;
|
|
|
|
|
2012-06-02 09:01:07 +08:00
|
|
|
S.Diag(Label->getLocStart(),
|
2012-06-16 05:22:05 +08:00
|
|
|
PerFunction ? diag::warn_unannotated_fallthrough_per_function
|
|
|
|
: diag::warn_unannotated_fallthrough);
|
2012-05-04 02:27:39 +08:00
|
|
|
|
|
|
|
if (!AnnotatedCnt) {
|
|
|
|
SourceLocation L = Label->getLocStart();
|
|
|
|
if (L.isMacroID())
|
|
|
|
continue;
|
2013-01-02 19:42:31 +08:00
|
|
|
if (S.getLangOpts().CPlusPlus11) {
|
2013-01-25 23:49:34 +08:00
|
|
|
const Stmt *Term = B->getTerminator();
|
|
|
|
// Skip empty cases.
|
|
|
|
while (B->empty() && !Term && B->succ_size() == 1) {
|
|
|
|
B = *B->succ_begin();
|
|
|
|
Term = B->getTerminator();
|
|
|
|
}
|
|
|
|
if (!(B->empty() && Term && isa<BreakStmt>(Term))) {
|
2012-09-29 06:24:03 +08:00
|
|
|
Preprocessor &PP = S.getPreprocessor();
|
2016-03-08 08:32:55 +08:00
|
|
|
StringRef AnnotationSpelling = getFallthroughAttrSpelling(PP, L);
|
2012-09-29 19:40:46 +08:00
|
|
|
SmallString<64> TextToInsert(AnnotationSpelling);
|
|
|
|
TextToInsert += "; ";
|
2012-05-26 08:49:15 +08:00
|
|
|
S.Diag(L, diag::note_insert_fallthrough_fixit) <<
|
2012-09-29 06:24:03 +08:00
|
|
|
AnnotationSpelling <<
|
2012-09-29 19:40:46 +08:00
|
|
|
FixItHint::CreateInsertion(L, TextToInsert);
|
2012-05-26 08:49:15 +08:00
|
|
|
}
|
2012-05-04 02:27:39 +08:00
|
|
|
}
|
|
|
|
S.Diag(L, diag::note_insert_break_fixit) <<
|
|
|
|
FixItHint::CreateInsertion(L, "break; ");
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2014-05-16 04:50:47 +08:00
|
|
|
for (const auto *F : FM.getFallthroughStmts())
|
2016-03-08 08:32:55 +08:00
|
|
|
S.Diag(F->getLocStart(), diag::err_fallthrough_attr_invalid_placement);
|
2012-05-04 02:27:39 +08:00
|
|
|
}
|
|
|
|
|
2012-10-30 01:46:47 +08:00
|
|
|
static bool isInLoop(const ASTContext &Ctx, const ParentMap &PM,
|
|
|
|
const Stmt *S) {
|
2012-10-12 00:10:19 +08:00
|
|
|
assert(S);
|
|
|
|
|
|
|
|
do {
|
|
|
|
switch (S->getStmtClass()) {
|
|
|
|
case Stmt::ForStmtClass:
|
|
|
|
case Stmt::WhileStmtClass:
|
|
|
|
case Stmt::CXXForRangeStmtClass:
|
|
|
|
case Stmt::ObjCForCollectionStmtClass:
|
|
|
|
return true;
|
2012-10-30 01:46:47 +08:00
|
|
|
case Stmt::DoStmtClass: {
|
|
|
|
const Expr *Cond = cast<DoStmt>(S)->getCond();
|
|
|
|
llvm::APSInt Val;
|
|
|
|
if (!Cond->EvaluateAsInt(Val, Ctx))
|
|
|
|
return true;
|
|
|
|
return Val.getBoolValue();
|
|
|
|
}
|
2012-10-12 00:10:19 +08:00
|
|
|
default:
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
} while ((S = PM.getParent(S)));
|
|
|
|
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
Add a warning (off by default) for repeated use of the same weak property.
The motivating example:
if (self.weakProp)
use(self.weakProp);
As with any non-atomic test-then-use, it is possible a weak property to be
non-nil at the 'if', but be deallocated by the time it is used. The correct
way to write this example is as follows:
id tmp = self.weakProp;
if (tmp)
use(tmp);
The warning is controlled by -Warc-repeated-use-of-receiver, and uses the
property name and base to determine if the same property on the same object
is being accessed multiple times. In cases where the base is more
complicated than just a single Decl (e.g. 'foo.bar.weakProp'), it picks a
Decl for some degree of uniquing and reports the problem under a subflag,
-Warc-maybe-repeated-use-of-receiver. This gives a way to tune the
aggressiveness of the warning for a particular project.
The warning is not on by default because it is not flow-sensitive and thus
may have a higher-than-acceptable rate of false positives, though it is
less noisy than -Wreceiver-is-weak. On the other hand, it will not warn
about some cases that may be legitimate issues that -Wreceiver-is-weak
will catch, and it does not attempt to reason about methods returning weak
values.
Even though this is not a real "analysis-based" check I've put the bug
emission code in AnalysisBasedWarnings for two reasons: (1) to run on
every kind of code body (function, method, block, or lambda), and (2) to
suggest that it may be enhanced by flow-sensitive analysis in the future.
The second (smaller) half of this work is to extend it to weak locals
and weak ivars. This should use most of the same infrastructure.
Part of <rdar://problem/12280249>
llvm-svn: 164854
2012-09-29 06:21:30 +08:00
|
|
|
static void diagnoseRepeatedUseOfWeak(Sema &S,
|
|
|
|
const sema::FunctionScopeInfo *CurFn,
|
2012-10-12 00:10:19 +08:00
|
|
|
const Decl *D,
|
|
|
|
const ParentMap &PM) {
|
Add a warning (off by default) for repeated use of the same weak property.
The motivating example:
if (self.weakProp)
use(self.weakProp);
As with any non-atomic test-then-use, it is possible a weak property to be
non-nil at the 'if', but be deallocated by the time it is used. The correct
way to write this example is as follows:
id tmp = self.weakProp;
if (tmp)
use(tmp);
The warning is controlled by -Warc-repeated-use-of-receiver, and uses the
property name and base to determine if the same property on the same object
is being accessed multiple times. In cases where the base is more
complicated than just a single Decl (e.g. 'foo.bar.weakProp'), it picks a
Decl for some degree of uniquing and reports the problem under a subflag,
-Warc-maybe-repeated-use-of-receiver. This gives a way to tune the
aggressiveness of the warning for a particular project.
The warning is not on by default because it is not flow-sensitive and thus
may have a higher-than-acceptable rate of false positives, though it is
less noisy than -Wreceiver-is-weak. On the other hand, it will not warn
about some cases that may be legitimate issues that -Wreceiver-is-weak
will catch, and it does not attempt to reason about methods returning weak
values.
Even though this is not a real "analysis-based" check I've put the bug
emission code in AnalysisBasedWarnings for two reasons: (1) to run on
every kind of code body (function, method, block, or lambda), and (2) to
suggest that it may be enhanced by flow-sensitive analysis in the future.
The second (smaller) half of this work is to extend it to weak locals
and weak ivars. This should use most of the same infrastructure.
Part of <rdar://problem/12280249>
llvm-svn: 164854
2012-09-29 06:21:30 +08:00
|
|
|
typedef sema::FunctionScopeInfo::WeakObjectProfileTy WeakObjectProfileTy;
|
|
|
|
typedef sema::FunctionScopeInfo::WeakObjectUseMap WeakObjectUseMap;
|
|
|
|
typedef sema::FunctionScopeInfo::WeakUseVector WeakUseVector;
|
2014-03-01 22:48:57 +08:00
|
|
|
typedef std::pair<const Stmt *, WeakObjectUseMap::const_iterator>
|
|
|
|
StmtUsesPair;
|
Add a warning (off by default) for repeated use of the same weak property.
The motivating example:
if (self.weakProp)
use(self.weakProp);
As with any non-atomic test-then-use, it is possible a weak property to be
non-nil at the 'if', but be deallocated by the time it is used. The correct
way to write this example is as follows:
id tmp = self.weakProp;
if (tmp)
use(tmp);
The warning is controlled by -Warc-repeated-use-of-receiver, and uses the
property name and base to determine if the same property on the same object
is being accessed multiple times. In cases where the base is more
complicated than just a single Decl (e.g. 'foo.bar.weakProp'), it picks a
Decl for some degree of uniquing and reports the problem under a subflag,
-Warc-maybe-repeated-use-of-receiver. This gives a way to tune the
aggressiveness of the warning for a particular project.
The warning is not on by default because it is not flow-sensitive and thus
may have a higher-than-acceptable rate of false positives, though it is
less noisy than -Wreceiver-is-weak. On the other hand, it will not warn
about some cases that may be legitimate issues that -Wreceiver-is-weak
will catch, and it does not attempt to reason about methods returning weak
values.
Even though this is not a real "analysis-based" check I've put the bug
emission code in AnalysisBasedWarnings for two reasons: (1) to run on
every kind of code body (function, method, block, or lambda), and (2) to
suggest that it may be enhanced by flow-sensitive analysis in the future.
The second (smaller) half of this work is to extend it to weak locals
and weak ivars. This should use most of the same infrastructure.
Part of <rdar://problem/12280249>
llvm-svn: 164854
2012-09-29 06:21:30 +08:00
|
|
|
|
2012-10-30 01:46:47 +08:00
|
|
|
ASTContext &Ctx = S.getASTContext();
|
|
|
|
|
Add a warning (off by default) for repeated use of the same weak property.
The motivating example:
if (self.weakProp)
use(self.weakProp);
As with any non-atomic test-then-use, it is possible a weak property to be
non-nil at the 'if', but be deallocated by the time it is used. The correct
way to write this example is as follows:
id tmp = self.weakProp;
if (tmp)
use(tmp);
The warning is controlled by -Warc-repeated-use-of-receiver, and uses the
property name and base to determine if the same property on the same object
is being accessed multiple times. In cases where the base is more
complicated than just a single Decl (e.g. 'foo.bar.weakProp'), it picks a
Decl for some degree of uniquing and reports the problem under a subflag,
-Warc-maybe-repeated-use-of-receiver. This gives a way to tune the
aggressiveness of the warning for a particular project.
The warning is not on by default because it is not flow-sensitive and thus
may have a higher-than-acceptable rate of false positives, though it is
less noisy than -Wreceiver-is-weak. On the other hand, it will not warn
about some cases that may be legitimate issues that -Wreceiver-is-weak
will catch, and it does not attempt to reason about methods returning weak
values.
Even though this is not a real "analysis-based" check I've put the bug
emission code in AnalysisBasedWarnings for two reasons: (1) to run on
every kind of code body (function, method, block, or lambda), and (2) to
suggest that it may be enhanced by flow-sensitive analysis in the future.
The second (smaller) half of this work is to extend it to weak locals
and weak ivars. This should use most of the same infrastructure.
Part of <rdar://problem/12280249>
llvm-svn: 164854
2012-09-29 06:21:30 +08:00
|
|
|
const WeakObjectUseMap &WeakMap = CurFn->getWeakObjectUses();
|
|
|
|
|
|
|
|
// Extract all weak objects that are referenced more than once.
|
|
|
|
SmallVector<StmtUsesPair, 8> UsesByStmt;
|
|
|
|
for (WeakObjectUseMap::const_iterator I = WeakMap.begin(), E = WeakMap.end();
|
|
|
|
I != E; ++I) {
|
|
|
|
const WeakUseVector &Uses = I->second;
|
|
|
|
|
|
|
|
// Find the first read of the weak object.
|
|
|
|
WeakUseVector::const_iterator UI = Uses.begin(), UE = Uses.end();
|
|
|
|
for ( ; UI != UE; ++UI) {
|
|
|
|
if (UI->isUnsafe())
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
|
|
|
|
// If there were only writes to this object, don't warn.
|
|
|
|
if (UI == UE)
|
|
|
|
continue;
|
|
|
|
|
2012-10-12 00:10:19 +08:00
|
|
|
// If there was only one read, followed by any number of writes, and the
|
2012-10-30 01:46:47 +08:00
|
|
|
// read is not within a loop, don't warn. Additionally, don't warn in a
|
|
|
|
// loop if the base object is a local variable -- local variables are often
|
|
|
|
// changed in loops.
|
2012-10-12 00:10:19 +08:00
|
|
|
if (UI == Uses.begin()) {
|
|
|
|
WeakUseVector::const_iterator UI2 = UI;
|
|
|
|
for (++UI2; UI2 != UE; ++UI2)
|
|
|
|
if (UI2->isUnsafe())
|
|
|
|
break;
|
|
|
|
|
2012-10-30 01:46:47 +08:00
|
|
|
if (UI2 == UE) {
|
|
|
|
if (!isInLoop(Ctx, PM, UI->getUseExpr()))
|
2012-10-12 00:10:19 +08:00
|
|
|
continue;
|
2012-10-30 01:46:47 +08:00
|
|
|
|
|
|
|
const WeakObjectProfileTy &Profile = I->first;
|
|
|
|
if (!Profile.isExactProfile())
|
|
|
|
continue;
|
|
|
|
|
|
|
|
const NamedDecl *Base = Profile.getBase();
|
|
|
|
if (!Base)
|
|
|
|
Base = Profile.getProperty();
|
|
|
|
assert(Base && "A profile always has a base or property.");
|
|
|
|
|
|
|
|
if (const VarDecl *BaseVar = dyn_cast<VarDecl>(Base))
|
|
|
|
if (BaseVar->hasLocalStorage() && !isa<ParmVarDecl>(Base))
|
|
|
|
continue;
|
|
|
|
}
|
2012-10-12 00:10:19 +08:00
|
|
|
}
|
|
|
|
|
Add a warning (off by default) for repeated use of the same weak property.
The motivating example:
if (self.weakProp)
use(self.weakProp);
As with any non-atomic test-then-use, it is possible a weak property to be
non-nil at the 'if', but be deallocated by the time it is used. The correct
way to write this example is as follows:
id tmp = self.weakProp;
if (tmp)
use(tmp);
The warning is controlled by -Warc-repeated-use-of-receiver, and uses the
property name and base to determine if the same property on the same object
is being accessed multiple times. In cases where the base is more
complicated than just a single Decl (e.g. 'foo.bar.weakProp'), it picks a
Decl for some degree of uniquing and reports the problem under a subflag,
-Warc-maybe-repeated-use-of-receiver. This gives a way to tune the
aggressiveness of the warning for a particular project.
The warning is not on by default because it is not flow-sensitive and thus
may have a higher-than-acceptable rate of false positives, though it is
less noisy than -Wreceiver-is-weak. On the other hand, it will not warn
about some cases that may be legitimate issues that -Wreceiver-is-weak
will catch, and it does not attempt to reason about methods returning weak
values.
Even though this is not a real "analysis-based" check I've put the bug
emission code in AnalysisBasedWarnings for two reasons: (1) to run on
every kind of code body (function, method, block, or lambda), and (2) to
suggest that it may be enhanced by flow-sensitive analysis in the future.
The second (smaller) half of this work is to extend it to weak locals
and weak ivars. This should use most of the same infrastructure.
Part of <rdar://problem/12280249>
llvm-svn: 164854
2012-09-29 06:21:30 +08:00
|
|
|
UsesByStmt.push_back(StmtUsesPair(UI->getUseExpr(), I));
|
|
|
|
}
|
|
|
|
|
|
|
|
if (UsesByStmt.empty())
|
|
|
|
return;
|
|
|
|
|
|
|
|
// Sort by first use so that we emit the warnings in a deterministic order.
|
2014-03-01 22:48:57 +08:00
|
|
|
SourceManager &SM = S.getSourceManager();
|
Add a warning (off by default) for repeated use of the same weak property.
The motivating example:
if (self.weakProp)
use(self.weakProp);
As with any non-atomic test-then-use, it is possible a weak property to be
non-nil at the 'if', but be deallocated by the time it is used. The correct
way to write this example is as follows:
id tmp = self.weakProp;
if (tmp)
use(tmp);
The warning is controlled by -Warc-repeated-use-of-receiver, and uses the
property name and base to determine if the same property on the same object
is being accessed multiple times. In cases where the base is more
complicated than just a single Decl (e.g. 'foo.bar.weakProp'), it picks a
Decl for some degree of uniquing and reports the problem under a subflag,
-Warc-maybe-repeated-use-of-receiver. This gives a way to tune the
aggressiveness of the warning for a particular project.
The warning is not on by default because it is not flow-sensitive and thus
may have a higher-than-acceptable rate of false positives, though it is
less noisy than -Wreceiver-is-weak. On the other hand, it will not warn
about some cases that may be legitimate issues that -Wreceiver-is-weak
will catch, and it does not attempt to reason about methods returning weak
values.
Even though this is not a real "analysis-based" check I've put the bug
emission code in AnalysisBasedWarnings for two reasons: (1) to run on
every kind of code body (function, method, block, or lambda), and (2) to
suggest that it may be enhanced by flow-sensitive analysis in the future.
The second (smaller) half of this work is to extend it to weak locals
and weak ivars. This should use most of the same infrastructure.
Part of <rdar://problem/12280249>
llvm-svn: 164854
2012-09-29 06:21:30 +08:00
|
|
|
std::sort(UsesByStmt.begin(), UsesByStmt.end(),
|
2014-03-01 22:48:57 +08:00
|
|
|
[&SM](const StmtUsesPair &LHS, const StmtUsesPair &RHS) {
|
|
|
|
return SM.isBeforeInTranslationUnit(LHS.first->getLocStart(),
|
|
|
|
RHS.first->getLocStart());
|
|
|
|
});
|
Add a warning (off by default) for repeated use of the same weak property.
The motivating example:
if (self.weakProp)
use(self.weakProp);
As with any non-atomic test-then-use, it is possible a weak property to be
non-nil at the 'if', but be deallocated by the time it is used. The correct
way to write this example is as follows:
id tmp = self.weakProp;
if (tmp)
use(tmp);
The warning is controlled by -Warc-repeated-use-of-receiver, and uses the
property name and base to determine if the same property on the same object
is being accessed multiple times. In cases where the base is more
complicated than just a single Decl (e.g. 'foo.bar.weakProp'), it picks a
Decl for some degree of uniquing and reports the problem under a subflag,
-Warc-maybe-repeated-use-of-receiver. This gives a way to tune the
aggressiveness of the warning for a particular project.
The warning is not on by default because it is not flow-sensitive and thus
may have a higher-than-acceptable rate of false positives, though it is
less noisy than -Wreceiver-is-weak. On the other hand, it will not warn
about some cases that may be legitimate issues that -Wreceiver-is-weak
will catch, and it does not attempt to reason about methods returning weak
values.
Even though this is not a real "analysis-based" check I've put the bug
emission code in AnalysisBasedWarnings for two reasons: (1) to run on
every kind of code body (function, method, block, or lambda), and (2) to
suggest that it may be enhanced by flow-sensitive analysis in the future.
The second (smaller) half of this work is to extend it to weak locals
and weak ivars. This should use most of the same infrastructure.
Part of <rdar://problem/12280249>
llvm-svn: 164854
2012-09-29 06:21:30 +08:00
|
|
|
|
|
|
|
// Classify the current code body for better warning text.
|
|
|
|
// This enum should stay in sync with the cases in
|
|
|
|
// warn_arc_repeated_use_of_weak and warn_arc_possible_repeated_use_of_weak.
|
|
|
|
// FIXME: Should we use a common classification enum and the same set of
|
|
|
|
// possibilities all throughout Sema?
|
|
|
|
enum {
|
|
|
|
Function,
|
|
|
|
Method,
|
|
|
|
Block,
|
|
|
|
Lambda
|
|
|
|
} FunctionKind;
|
|
|
|
|
|
|
|
if (isa<sema::BlockScopeInfo>(CurFn))
|
|
|
|
FunctionKind = Block;
|
|
|
|
else if (isa<sema::LambdaScopeInfo>(CurFn))
|
|
|
|
FunctionKind = Lambda;
|
|
|
|
else if (isa<ObjCMethodDecl>(D))
|
|
|
|
FunctionKind = Method;
|
|
|
|
else
|
|
|
|
FunctionKind = Function;
|
|
|
|
|
|
|
|
// Iterate through the sorted problems and emit warnings for each.
|
2014-05-16 04:50:47 +08:00
|
|
|
for (const auto &P : UsesByStmt) {
|
|
|
|
const Stmt *FirstRead = P.first;
|
|
|
|
const WeakObjectProfileTy &Key = P.second->first;
|
|
|
|
const WeakUseVector &Uses = P.second->second;
|
Add a warning (off by default) for repeated use of the same weak property.
The motivating example:
if (self.weakProp)
use(self.weakProp);
As with any non-atomic test-then-use, it is possible a weak property to be
non-nil at the 'if', but be deallocated by the time it is used. The correct
way to write this example is as follows:
id tmp = self.weakProp;
if (tmp)
use(tmp);
The warning is controlled by -Warc-repeated-use-of-receiver, and uses the
property name and base to determine if the same property on the same object
is being accessed multiple times. In cases where the base is more
complicated than just a single Decl (e.g. 'foo.bar.weakProp'), it picks a
Decl for some degree of uniquing and reports the problem under a subflag,
-Warc-maybe-repeated-use-of-receiver. This gives a way to tune the
aggressiveness of the warning for a particular project.
The warning is not on by default because it is not flow-sensitive and thus
may have a higher-than-acceptable rate of false positives, though it is
less noisy than -Wreceiver-is-weak. On the other hand, it will not warn
about some cases that may be legitimate issues that -Wreceiver-is-weak
will catch, and it does not attempt to reason about methods returning weak
values.
Even though this is not a real "analysis-based" check I've put the bug
emission code in AnalysisBasedWarnings for two reasons: (1) to run on
every kind of code body (function, method, block, or lambda), and (2) to
suggest that it may be enhanced by flow-sensitive analysis in the future.
The second (smaller) half of this work is to extend it to weak locals
and weak ivars. This should use most of the same infrastructure.
Part of <rdar://problem/12280249>
llvm-svn: 164854
2012-09-29 06:21:30 +08:00
|
|
|
|
2012-09-29 06:21:35 +08:00
|
|
|
// For complicated expressions like 'a.b.c' and 'x.b.c', WeakObjectProfileTy
|
|
|
|
// may not contain enough information to determine that these are different
|
|
|
|
// properties. We can only be 100% sure of a repeated use in certain cases,
|
|
|
|
// and we adjust the diagnostic kind accordingly so that the less certain
|
|
|
|
// case can be turned off if it is too noisy.
|
Add a warning (off by default) for repeated use of the same weak property.
The motivating example:
if (self.weakProp)
use(self.weakProp);
As with any non-atomic test-then-use, it is possible a weak property to be
non-nil at the 'if', but be deallocated by the time it is used. The correct
way to write this example is as follows:
id tmp = self.weakProp;
if (tmp)
use(tmp);
The warning is controlled by -Warc-repeated-use-of-receiver, and uses the
property name and base to determine if the same property on the same object
is being accessed multiple times. In cases where the base is more
complicated than just a single Decl (e.g. 'foo.bar.weakProp'), it picks a
Decl for some degree of uniquing and reports the problem under a subflag,
-Warc-maybe-repeated-use-of-receiver. This gives a way to tune the
aggressiveness of the warning for a particular project.
The warning is not on by default because it is not flow-sensitive and thus
may have a higher-than-acceptable rate of false positives, though it is
less noisy than -Wreceiver-is-weak. On the other hand, it will not warn
about some cases that may be legitimate issues that -Wreceiver-is-weak
will catch, and it does not attempt to reason about methods returning weak
values.
Even though this is not a real "analysis-based" check I've put the bug
emission code in AnalysisBasedWarnings for two reasons: (1) to run on
every kind of code body (function, method, block, or lambda), and (2) to
suggest that it may be enhanced by flow-sensitive analysis in the future.
The second (smaller) half of this work is to extend it to weak locals
and weak ivars. This should use most of the same infrastructure.
Part of <rdar://problem/12280249>
llvm-svn: 164854
2012-09-29 06:21:30 +08:00
|
|
|
unsigned DiagKind;
|
|
|
|
if (Key.isExactProfile())
|
|
|
|
DiagKind = diag::warn_arc_repeated_use_of_weak;
|
|
|
|
else
|
|
|
|
DiagKind = diag::warn_arc_possible_repeated_use_of_weak;
|
|
|
|
|
2012-09-29 06:21:35 +08:00
|
|
|
// Classify the weak object being accessed for better warning text.
|
|
|
|
// This enum should stay in sync with the cases in
|
|
|
|
// warn_arc_repeated_use_of_weak and warn_arc_possible_repeated_use_of_weak.
|
|
|
|
enum {
|
|
|
|
Variable,
|
|
|
|
Property,
|
|
|
|
ImplicitProperty,
|
|
|
|
Ivar
|
|
|
|
} ObjectKind;
|
|
|
|
|
2016-05-25 13:42:00 +08:00
|
|
|
const NamedDecl *KeyProp = Key.getProperty();
|
|
|
|
if (isa<VarDecl>(KeyProp))
|
2012-09-29 06:21:35 +08:00
|
|
|
ObjectKind = Variable;
|
2016-05-25 13:42:00 +08:00
|
|
|
else if (isa<ObjCPropertyDecl>(KeyProp))
|
2012-09-29 06:21:35 +08:00
|
|
|
ObjectKind = Property;
|
2016-05-25 13:42:00 +08:00
|
|
|
else if (isa<ObjCMethodDecl>(KeyProp))
|
2012-09-29 06:21:35 +08:00
|
|
|
ObjectKind = ImplicitProperty;
|
2016-05-25 13:42:00 +08:00
|
|
|
else if (isa<ObjCIvarDecl>(KeyProp))
|
2012-09-29 06:21:35 +08:00
|
|
|
ObjectKind = Ivar;
|
|
|
|
else
|
|
|
|
llvm_unreachable("Unexpected weak object kind!");
|
|
|
|
|
2016-05-25 13:41:57 +08:00
|
|
|
// Do not warn about IBOutlet weak property receivers being set to null
|
|
|
|
// since they are typically only used from the main thread.
|
2016-05-25 13:42:00 +08:00
|
|
|
if (const ObjCPropertyDecl *Prop = dyn_cast<ObjCPropertyDecl>(KeyProp))
|
2016-05-25 13:41:57 +08:00
|
|
|
if (Prop->hasAttr<IBOutletAttr>())
|
|
|
|
continue;
|
|
|
|
|
Add a warning (off by default) for repeated use of the same weak property.
The motivating example:
if (self.weakProp)
use(self.weakProp);
As with any non-atomic test-then-use, it is possible a weak property to be
non-nil at the 'if', but be deallocated by the time it is used. The correct
way to write this example is as follows:
id tmp = self.weakProp;
if (tmp)
use(tmp);
The warning is controlled by -Warc-repeated-use-of-receiver, and uses the
property name and base to determine if the same property on the same object
is being accessed multiple times. In cases where the base is more
complicated than just a single Decl (e.g. 'foo.bar.weakProp'), it picks a
Decl for some degree of uniquing and reports the problem under a subflag,
-Warc-maybe-repeated-use-of-receiver. This gives a way to tune the
aggressiveness of the warning for a particular project.
The warning is not on by default because it is not flow-sensitive and thus
may have a higher-than-acceptable rate of false positives, though it is
less noisy than -Wreceiver-is-weak. On the other hand, it will not warn
about some cases that may be legitimate issues that -Wreceiver-is-weak
will catch, and it does not attempt to reason about methods returning weak
values.
Even though this is not a real "analysis-based" check I've put the bug
emission code in AnalysisBasedWarnings for two reasons: (1) to run on
every kind of code body (function, method, block, or lambda), and (2) to
suggest that it may be enhanced by flow-sensitive analysis in the future.
The second (smaller) half of this work is to extend it to weak locals
and weak ivars. This should use most of the same infrastructure.
Part of <rdar://problem/12280249>
llvm-svn: 164854
2012-09-29 06:21:30 +08:00
|
|
|
// Show the first time the object was read.
|
|
|
|
S.Diag(FirstRead->getLocStart(), DiagKind)
|
2016-05-25 13:42:00 +08:00
|
|
|
<< int(ObjectKind) << KeyProp << int(FunctionKind)
|
Add a warning (off by default) for repeated use of the same weak property.
The motivating example:
if (self.weakProp)
use(self.weakProp);
As with any non-atomic test-then-use, it is possible a weak property to be
non-nil at the 'if', but be deallocated by the time it is used. The correct
way to write this example is as follows:
id tmp = self.weakProp;
if (tmp)
use(tmp);
The warning is controlled by -Warc-repeated-use-of-receiver, and uses the
property name and base to determine if the same property on the same object
is being accessed multiple times. In cases where the base is more
complicated than just a single Decl (e.g. 'foo.bar.weakProp'), it picks a
Decl for some degree of uniquing and reports the problem under a subflag,
-Warc-maybe-repeated-use-of-receiver. This gives a way to tune the
aggressiveness of the warning for a particular project.
The warning is not on by default because it is not flow-sensitive and thus
may have a higher-than-acceptable rate of false positives, though it is
less noisy than -Wreceiver-is-weak. On the other hand, it will not warn
about some cases that may be legitimate issues that -Wreceiver-is-weak
will catch, and it does not attempt to reason about methods returning weak
values.
Even though this is not a real "analysis-based" check I've put the bug
emission code in AnalysisBasedWarnings for two reasons: (1) to run on
every kind of code body (function, method, block, or lambda), and (2) to
suggest that it may be enhanced by flow-sensitive analysis in the future.
The second (smaller) half of this work is to extend it to weak locals
and weak ivars. This should use most of the same infrastructure.
Part of <rdar://problem/12280249>
llvm-svn: 164854
2012-09-29 06:21:30 +08:00
|
|
|
<< FirstRead->getSourceRange();
|
|
|
|
|
|
|
|
// Print all the other accesses as notes.
|
2014-05-16 04:50:47 +08:00
|
|
|
for (const auto &Use : Uses) {
|
|
|
|
if (Use.getUseExpr() == FirstRead)
|
Add a warning (off by default) for repeated use of the same weak property.
The motivating example:
if (self.weakProp)
use(self.weakProp);
As with any non-atomic test-then-use, it is possible a weak property to be
non-nil at the 'if', but be deallocated by the time it is used. The correct
way to write this example is as follows:
id tmp = self.weakProp;
if (tmp)
use(tmp);
The warning is controlled by -Warc-repeated-use-of-receiver, and uses the
property name and base to determine if the same property on the same object
is being accessed multiple times. In cases where the base is more
complicated than just a single Decl (e.g. 'foo.bar.weakProp'), it picks a
Decl for some degree of uniquing and reports the problem under a subflag,
-Warc-maybe-repeated-use-of-receiver. This gives a way to tune the
aggressiveness of the warning for a particular project.
The warning is not on by default because it is not flow-sensitive and thus
may have a higher-than-acceptable rate of false positives, though it is
less noisy than -Wreceiver-is-weak. On the other hand, it will not warn
about some cases that may be legitimate issues that -Wreceiver-is-weak
will catch, and it does not attempt to reason about methods returning weak
values.
Even though this is not a real "analysis-based" check I've put the bug
emission code in AnalysisBasedWarnings for two reasons: (1) to run on
every kind of code body (function, method, block, or lambda), and (2) to
suggest that it may be enhanced by flow-sensitive analysis in the future.
The second (smaller) half of this work is to extend it to weak locals
and weak ivars. This should use most of the same infrastructure.
Part of <rdar://problem/12280249>
llvm-svn: 164854
2012-09-29 06:21:30 +08:00
|
|
|
continue;
|
2014-05-16 04:50:47 +08:00
|
|
|
S.Diag(Use.getUseExpr()->getLocStart(),
|
Add a warning (off by default) for repeated use of the same weak property.
The motivating example:
if (self.weakProp)
use(self.weakProp);
As with any non-atomic test-then-use, it is possible a weak property to be
non-nil at the 'if', but be deallocated by the time it is used. The correct
way to write this example is as follows:
id tmp = self.weakProp;
if (tmp)
use(tmp);
The warning is controlled by -Warc-repeated-use-of-receiver, and uses the
property name and base to determine if the same property on the same object
is being accessed multiple times. In cases where the base is more
complicated than just a single Decl (e.g. 'foo.bar.weakProp'), it picks a
Decl for some degree of uniquing and reports the problem under a subflag,
-Warc-maybe-repeated-use-of-receiver. This gives a way to tune the
aggressiveness of the warning for a particular project.
The warning is not on by default because it is not flow-sensitive and thus
may have a higher-than-acceptable rate of false positives, though it is
less noisy than -Wreceiver-is-weak. On the other hand, it will not warn
about some cases that may be legitimate issues that -Wreceiver-is-weak
will catch, and it does not attempt to reason about methods returning weak
values.
Even though this is not a real "analysis-based" check I've put the bug
emission code in AnalysisBasedWarnings for two reasons: (1) to run on
every kind of code body (function, method, block, or lambda), and (2) to
suggest that it may be enhanced by flow-sensitive analysis in the future.
The second (smaller) half of this work is to extend it to weak locals
and weak ivars. This should use most of the same infrastructure.
Part of <rdar://problem/12280249>
llvm-svn: 164854
2012-09-29 06:21:30 +08:00
|
|
|
diag::note_arc_weak_also_accessed_here)
|
2014-05-16 04:50:47 +08:00
|
|
|
<< Use.getUseExpr()->getSourceRange();
|
Add a warning (off by default) for repeated use of the same weak property.
The motivating example:
if (self.weakProp)
use(self.weakProp);
As with any non-atomic test-then-use, it is possible a weak property to be
non-nil at the 'if', but be deallocated by the time it is used. The correct
way to write this example is as follows:
id tmp = self.weakProp;
if (tmp)
use(tmp);
The warning is controlled by -Warc-repeated-use-of-receiver, and uses the
property name and base to determine if the same property on the same object
is being accessed multiple times. In cases where the base is more
complicated than just a single Decl (e.g. 'foo.bar.weakProp'), it picks a
Decl for some degree of uniquing and reports the problem under a subflag,
-Warc-maybe-repeated-use-of-receiver. This gives a way to tune the
aggressiveness of the warning for a particular project.
The warning is not on by default because it is not flow-sensitive and thus
may have a higher-than-acceptable rate of false positives, though it is
less noisy than -Wreceiver-is-weak. On the other hand, it will not warn
about some cases that may be legitimate issues that -Wreceiver-is-weak
will catch, and it does not attempt to reason about methods returning weak
values.
Even though this is not a real "analysis-based" check I've put the bug
emission code in AnalysisBasedWarnings for two reasons: (1) to run on
every kind of code body (function, method, block, or lambda), and (2) to
suggest that it may be enhanced by flow-sensitive analysis in the future.
The second (smaller) half of this work is to extend it to weak locals
and weak ivars. This should use most of the same infrastructure.
Part of <rdar://problem/12280249>
llvm-svn: 164854
2012-09-29 06:21:30 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2011-01-15 10:58:47 +08:00
|
|
|
namespace {
|
|
|
|
class UninitValsDiagReporter : public UninitVariablesHandler {
|
|
|
|
Sema &S;
|
2011-07-23 18:55:15 +08:00
|
|
|
typedef SmallVector<UninitUse, 2> UsesVec;
|
2013-06-30 01:52:13 +08:00
|
|
|
typedef llvm::PointerIntPair<UsesVec *, 1, bool> MappedType;
|
2013-02-16 04:09:55 +08:00
|
|
|
// Prefer using MapVector to DenseMap, so that iteration order will be
|
|
|
|
// the same as insertion order. This is needed to obtain a deterministic
|
|
|
|
// order of diagnostics when calling flushDiagnostics().
|
|
|
|
typedef llvm::MapVector<const VarDecl *, MappedType> UsesMap;
|
2015-12-11 03:25:21 +08:00
|
|
|
UsesMap uses;
|
2011-01-22 03:41:41 +08:00
|
|
|
|
2011-01-15 10:58:47 +08:00
|
|
|
public:
|
2015-12-11 03:25:21 +08:00
|
|
|
UninitValsDiagReporter(Sema &S) : S(S) {}
|
2015-04-11 10:00:23 +08:00
|
|
|
~UninitValsDiagReporter() override { flushDiagnostics(); }
|
2011-10-14 02:50:06 +08:00
|
|
|
|
2013-02-16 04:09:55 +08:00
|
|
|
MappedType &getUses(const VarDecl *vd) {
|
2015-12-11 03:25:21 +08:00
|
|
|
MappedType &V = uses[vd];
|
2013-06-30 01:52:13 +08:00
|
|
|
if (!V.getPointer())
|
|
|
|
V.setPointer(new UsesVec());
|
2011-10-14 02:50:06 +08:00
|
|
|
return V;
|
|
|
|
}
|
2014-03-12 12:55:44 +08:00
|
|
|
|
|
|
|
void handleUseOfUninitVariable(const VarDecl *vd,
|
|
|
|
const UninitUse &use) override {
|
2013-06-30 01:52:13 +08:00
|
|
|
getUses(vd).getPointer()->push_back(use);
|
2011-10-14 02:50:06 +08:00
|
|
|
}
|
|
|
|
|
2014-03-12 12:55:44 +08:00
|
|
|
void handleSelfInit(const VarDecl *vd) override {
|
2013-06-30 01:52:13 +08:00
|
|
|
getUses(vd).setInt(true);
|
2011-01-22 03:41:41 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
void flushDiagnostics() {
|
2015-12-11 03:25:21 +08:00
|
|
|
for (const auto &P : uses) {
|
2014-05-16 04:50:47 +08:00
|
|
|
const VarDecl *vd = P.first;
|
|
|
|
const MappedType &V = P.second;
|
2011-10-14 02:50:06 +08:00
|
|
|
|
2013-06-30 01:52:13 +08:00
|
|
|
UsesVec *vec = V.getPointer();
|
|
|
|
bool hasSelfInit = V.getInt();
|
2011-10-14 02:50:06 +08:00
|
|
|
|
|
|
|
// Specially handle the case where we have uses of an uninitialized
|
|
|
|
// variable, but the root cause is an idiomatic self-init. We want
|
|
|
|
// to report the diagnostic at the self-init since that is the root cause.
|
2011-10-20 02:53:03 +08:00
|
|
|
if (!vec->empty() && hasSelfInit && hasAlwaysUninitializedUse(vec))
|
2012-05-25 10:17:09 +08:00
|
|
|
DiagnoseUninitializedUse(S, vd,
|
|
|
|
UninitUse(vd->getInit()->IgnoreParenCasts(),
|
|
|
|
/* isAlwaysUninit */ true),
|
2011-10-20 02:53:03 +08:00
|
|
|
/* alwaysReportSelfInit */ true);
|
2011-10-14 02:50:06 +08:00
|
|
|
else {
|
|
|
|
// Sort the uses by their SourceLocations. While not strictly
|
|
|
|
// guaranteed to produce them in line/column order, this will provide
|
|
|
|
// a stable ordering.
|
2014-03-01 22:48:57 +08:00
|
|
|
std::sort(vec->begin(), vec->end(),
|
|
|
|
[](const UninitUse &a, const UninitUse &b) {
|
|
|
|
// Prefer a more confident report over a less confident one.
|
|
|
|
if (a.getKind() != b.getKind())
|
|
|
|
return a.getKind() > b.getKind();
|
|
|
|
return a.getUser()->getLocStart() < b.getUser()->getLocStart();
|
|
|
|
});
|
|
|
|
|
2014-05-16 04:50:47 +08:00
|
|
|
for (const auto &U : *vec) {
|
2012-05-25 10:17:09 +08:00
|
|
|
// If we have self-init, downgrade all uses to 'may be uninitialized'.
|
2014-05-16 04:50:47 +08:00
|
|
|
UninitUse Use = hasSelfInit ? UninitUse(U.getUser(), false) : U;
|
2012-05-25 10:17:09 +08:00
|
|
|
|
|
|
|
if (DiagnoseUninitializedUse(S, vd, Use))
|
2011-10-14 02:50:06 +08:00
|
|
|
// Skip further diagnostics for this variable. We try to warn only
|
|
|
|
// on the first point at which a variable is used uninitialized.
|
|
|
|
break;
|
|
|
|
}
|
2011-04-06 02:18:08 +08:00
|
|
|
}
|
2011-10-14 02:50:06 +08:00
|
|
|
|
|
|
|
// Release the uses vector.
|
2011-01-22 03:41:41 +08:00
|
|
|
delete vec;
|
|
|
|
}
|
2015-12-11 03:25:21 +08:00
|
|
|
|
|
|
|
uses.clear();
|
2011-01-15 10:58:47 +08:00
|
|
|
}
|
2011-10-20 02:53:03 +08:00
|
|
|
|
|
|
|
private:
|
|
|
|
static bool hasAlwaysUninitializedUse(const UsesVec* vec) {
|
2014-05-16 04:50:47 +08:00
|
|
|
return std::any_of(vec->begin(), vec->end(), [](const UninitUse &U) {
|
|
|
|
return U.getKind() == UninitUse::Always ||
|
|
|
|
U.getKind() == UninitUse::AfterCall ||
|
|
|
|
U.getKind() == UninitUse::AfterDecl;
|
|
|
|
});
|
2011-10-20 02:53:03 +08:00
|
|
|
}
|
2011-01-15 10:58:47 +08:00
|
|
|
};
|
2015-10-07 07:40:43 +08:00
|
|
|
} // anonymous namespace
|
2011-01-15 10:58:47 +08:00
|
|
|
|
2011-09-10 00:04:02 +08:00
|
|
|
namespace clang {
|
2013-08-13 05:20:55 +08:00
|
|
|
namespace {
|
2013-01-13 03:30:44 +08:00
|
|
|
typedef SmallVector<PartialDiagnosticAt, 1> OptionalNotes;
|
2012-02-03 12:45:26 +08:00
|
|
|
typedef std::pair<PartialDiagnosticAt, OptionalNotes> DelayedDiag;
|
2012-03-26 22:05:40 +08:00
|
|
|
typedef std::list<DelayedDiag> DiagList;
|
2011-09-10 00:04:02 +08:00
|
|
|
|
|
|
|
struct SortDiagBySourceLocation {
|
2012-03-26 22:05:40 +08:00
|
|
|
SourceManager &SM;
|
|
|
|
SortDiagBySourceLocation(SourceManager &SM) : SM(SM) {}
|
2011-09-10 00:04:02 +08:00
|
|
|
|
|
|
|
bool operator()(const DelayedDiag &left, const DelayedDiag &right) {
|
|
|
|
// Although this call will be slow, this is only called when outputting
|
|
|
|
// multiple warnings.
|
2012-03-26 22:05:40 +08:00
|
|
|
return SM.isBeforeInTranslationUnit(left.first.first, right.first.first);
|
2011-09-10 00:04:02 +08:00
|
|
|
}
|
|
|
|
};
|
2015-10-07 07:40:43 +08:00
|
|
|
} // anonymous namespace
|
|
|
|
} // namespace clang
|
2011-09-10 00:04:02 +08:00
|
|
|
|
2013-08-13 05:20:55 +08:00
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
// -Wthread-safety
|
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
namespace clang {
|
2014-07-28 23:57:27 +08:00
|
|
|
namespace threadSafety {
|
2015-03-19 22:23:45 +08:00
|
|
|
namespace {
|
2014-07-28 23:57:27 +08:00
|
|
|
class ThreadSafetyReporter : public clang::threadSafety::ThreadSafetyHandler {
|
2011-09-10 00:04:02 +08:00
|
|
|
Sema &S;
|
|
|
|
DiagList Warnings;
|
2012-02-03 12:45:26 +08:00
|
|
|
SourceLocation FunLocation, FunEndLocation;
|
2011-09-10 00:04:02 +08:00
|
|
|
|
2014-08-15 05:40:15 +08:00
|
|
|
const FunctionDecl *CurrentFunction;
|
|
|
|
bool Verbose;
|
|
|
|
|
2014-08-15 20:38:17 +08:00
|
|
|
OptionalNotes getNotes() const {
|
2014-08-15 05:40:15 +08:00
|
|
|
if (Verbose && CurrentFunction) {
|
|
|
|
PartialDiagnosticAt FNote(CurrentFunction->getBody()->getLocStart(),
|
2014-08-15 20:38:17 +08:00
|
|
|
S.PDiag(diag::note_thread_warning_in_fun)
|
|
|
|
<< CurrentFunction->getNameAsString());
|
2014-08-15 05:40:15 +08:00
|
|
|
return OptionalNotes(1, FNote);
|
|
|
|
}
|
2014-08-15 20:38:17 +08:00
|
|
|
return OptionalNotes();
|
2014-08-15 05:40:15 +08:00
|
|
|
}
|
|
|
|
|
2014-08-15 20:38:17 +08:00
|
|
|
OptionalNotes getNotes(const PartialDiagnosticAt &Note) const {
|
2014-08-15 05:40:15 +08:00
|
|
|
OptionalNotes ONS(1, Note);
|
|
|
|
if (Verbose && CurrentFunction) {
|
|
|
|
PartialDiagnosticAt FNote(CurrentFunction->getBody()->getLocStart(),
|
2014-08-15 20:38:17 +08:00
|
|
|
S.PDiag(diag::note_thread_warning_in_fun)
|
|
|
|
<< CurrentFunction->getNameAsString());
|
2015-05-30 03:42:19 +08:00
|
|
|
ONS.push_back(std::move(FNote));
|
2014-08-15 05:40:15 +08:00
|
|
|
}
|
|
|
|
return ONS;
|
|
|
|
}
|
|
|
|
|
2014-09-19 07:02:26 +08:00
|
|
|
OptionalNotes getNotes(const PartialDiagnosticAt &Note1,
|
|
|
|
const PartialDiagnosticAt &Note2) const {
|
|
|
|
OptionalNotes ONS;
|
|
|
|
ONS.push_back(Note1);
|
|
|
|
ONS.push_back(Note2);
|
|
|
|
if (Verbose && CurrentFunction) {
|
|
|
|
PartialDiagnosticAt FNote(CurrentFunction->getBody()->getLocStart(),
|
|
|
|
S.PDiag(diag::note_thread_warning_in_fun)
|
|
|
|
<< CurrentFunction->getNameAsString());
|
2015-05-30 03:42:19 +08:00
|
|
|
ONS.push_back(std::move(FNote));
|
2014-09-19 07:02:26 +08:00
|
|
|
}
|
|
|
|
return ONS;
|
|
|
|
}
|
|
|
|
|
2011-09-10 00:04:02 +08:00
|
|
|
// Helper functions
|
2014-04-02 05:43:23 +08:00
|
|
|
void warnLockMismatch(unsigned DiagID, StringRef Kind, Name LockName,
|
|
|
|
SourceLocation Loc) {
|
2011-10-22 02:10:14 +08:00
|
|
|
// Gracefully handle rare cases when the analysis can't get a more
|
|
|
|
// precise source location.
|
|
|
|
if (!Loc.isValid())
|
|
|
|
Loc = FunLocation;
|
2014-04-02 05:43:23 +08:00
|
|
|
PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << Kind << LockName);
|
2015-05-30 03:42:19 +08:00
|
|
|
Warnings.emplace_back(std::move(Warning), getNotes());
|
2011-09-10 00:04:02 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
public:
|
2012-02-03 12:45:26 +08:00
|
|
|
ThreadSafetyReporter(Sema &S, SourceLocation FL, SourceLocation FEL)
|
2014-08-15 05:40:15 +08:00
|
|
|
: S(S), FunLocation(FL), FunEndLocation(FEL),
|
|
|
|
CurrentFunction(nullptr), Verbose(false) {}
|
|
|
|
|
|
|
|
void setVerbose(bool b) { Verbose = b; }
|
2011-09-10 00:04:02 +08:00
|
|
|
|
|
|
|
/// \brief Emit all buffered diagnostics in order of sourcelocation.
|
|
|
|
/// We need to output diagnostics produced while iterating through
|
|
|
|
/// the lockset in deterministic order, so this function orders diagnostics
|
|
|
|
/// and outputs them.
|
|
|
|
void emitDiagnostics() {
|
2012-03-26 22:05:40 +08:00
|
|
|
Warnings.sort(SortDiagBySourceLocation(S.getSourceManager()));
|
2014-05-16 04:50:47 +08:00
|
|
|
for (const auto &Diag : Warnings) {
|
|
|
|
S.Diag(Diag.first.first, Diag.first.second);
|
|
|
|
for (const auto &Note : Diag.second)
|
|
|
|
S.Diag(Note.first, Note.second);
|
2012-02-03 12:45:26 +08:00
|
|
|
}
|
2011-09-10 00:04:02 +08:00
|
|
|
}
|
|
|
|
|
2014-04-02 05:43:23 +08:00
|
|
|
void handleInvalidLockExp(StringRef Kind, SourceLocation Loc) override {
|
|
|
|
PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_cannot_resolve_lock)
|
|
|
|
<< Loc);
|
2015-05-30 03:42:19 +08:00
|
|
|
Warnings.emplace_back(std::move(Warning), getNotes());
|
2011-09-10 00:21:55 +08:00
|
|
|
}
|
2014-08-15 05:40:15 +08:00
|
|
|
|
2014-04-02 05:43:23 +08:00
|
|
|
void handleUnmatchedUnlock(StringRef Kind, Name LockName,
|
|
|
|
SourceLocation Loc) override {
|
|
|
|
warnLockMismatch(diag::warn_unlock_but_no_lock, Kind, LockName, Loc);
|
2011-09-10 00:04:02 +08:00
|
|
|
}
|
2014-08-15 05:40:15 +08:00
|
|
|
|
2014-04-02 05:43:23 +08:00
|
|
|
void handleIncorrectUnlockKind(StringRef Kind, Name LockName,
|
|
|
|
LockKind Expected, LockKind Received,
|
2014-03-21 22:48:48 +08:00
|
|
|
SourceLocation Loc) override {
|
|
|
|
if (Loc.isInvalid())
|
|
|
|
Loc = FunLocation;
|
|
|
|
PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_unlock_kind_mismatch)
|
2014-04-02 05:43:23 +08:00
|
|
|
<< Kind << LockName << Received
|
|
|
|
<< Expected);
|
2015-05-30 03:42:19 +08:00
|
|
|
Warnings.emplace_back(std::move(Warning), getNotes());
|
2014-03-21 22:48:48 +08:00
|
|
|
}
|
2014-08-15 05:40:15 +08:00
|
|
|
|
2014-04-02 05:43:23 +08:00
|
|
|
void handleDoubleLock(StringRef Kind, Name LockName, SourceLocation Loc) override {
|
|
|
|
warnLockMismatch(diag::warn_double_lock, Kind, LockName, Loc);
|
2011-09-10 00:04:02 +08:00
|
|
|
}
|
|
|
|
|
2014-04-02 05:43:23 +08:00
|
|
|
void handleMutexHeldEndOfScope(StringRef Kind, Name LockName,
|
|
|
|
SourceLocation LocLocked,
|
2012-02-03 12:45:26 +08:00
|
|
|
SourceLocation LocEndOfScope,
|
2014-03-12 12:55:44 +08:00
|
|
|
LockErrorKind LEK) override {
|
2011-09-16 01:25:19 +08:00
|
|
|
unsigned DiagID = 0;
|
|
|
|
switch (LEK) {
|
|
|
|
case LEK_LockedSomePredecessors:
|
2012-02-03 12:45:26 +08:00
|
|
|
DiagID = diag::warn_lock_some_predecessors;
|
2011-09-16 01:25:19 +08:00
|
|
|
break;
|
|
|
|
case LEK_LockedSomeLoopIterations:
|
|
|
|
DiagID = diag::warn_expecting_lock_held_on_loop;
|
|
|
|
break;
|
|
|
|
case LEK_LockedAtEndOfFunction:
|
|
|
|
DiagID = diag::warn_no_unlock;
|
|
|
|
break;
|
2012-07-03 06:16:54 +08:00
|
|
|
case LEK_NotLockedAtEndOfFunction:
|
|
|
|
DiagID = diag::warn_expecting_locked;
|
|
|
|
break;
|
2011-09-16 01:25:19 +08:00
|
|
|
}
|
2012-02-03 12:45:26 +08:00
|
|
|
if (LocEndOfScope.isInvalid())
|
|
|
|
LocEndOfScope = FunEndLocation;
|
|
|
|
|
2014-04-02 05:43:23 +08:00
|
|
|
PartialDiagnosticAt Warning(LocEndOfScope, S.PDiag(DiagID) << Kind
|
|
|
|
<< LockName);
|
2013-04-09 04:11:11 +08:00
|
|
|
if (LocLocked.isValid()) {
|
2014-04-02 05:43:23 +08:00
|
|
|
PartialDiagnosticAt Note(LocLocked, S.PDiag(diag::note_locked_here)
|
|
|
|
<< Kind);
|
2015-05-30 03:42:19 +08:00
|
|
|
Warnings.emplace_back(std::move(Warning), getNotes(Note));
|
2013-04-09 04:11:11 +08:00
|
|
|
return;
|
|
|
|
}
|
2015-05-30 03:42:19 +08:00
|
|
|
Warnings.emplace_back(std::move(Warning), getNotes());
|
2011-09-10 00:04:02 +08:00
|
|
|
}
|
|
|
|
|
2014-04-02 05:43:23 +08:00
|
|
|
void handleExclusiveAndShared(StringRef Kind, Name LockName,
|
|
|
|
SourceLocation Loc1,
|
2014-03-12 12:55:44 +08:00
|
|
|
SourceLocation Loc2) override {
|
2014-04-02 05:43:23 +08:00
|
|
|
PartialDiagnosticAt Warning(Loc1,
|
|
|
|
S.PDiag(diag::warn_lock_exclusive_and_shared)
|
|
|
|
<< Kind << LockName);
|
|
|
|
PartialDiagnosticAt Note(Loc2, S.PDiag(diag::note_lock_exclusive_and_shared)
|
|
|
|
<< Kind << LockName);
|
2015-05-30 03:42:19 +08:00
|
|
|
Warnings.emplace_back(std::move(Warning), getNotes(Note));
|
2011-09-10 00:04:02 +08:00
|
|
|
}
|
|
|
|
|
2014-04-02 05:43:23 +08:00
|
|
|
void handleNoMutexHeld(StringRef Kind, const NamedDecl *D,
|
|
|
|
ProtectedOperationKind POK, AccessKind AK,
|
|
|
|
SourceLocation Loc) override {
|
|
|
|
assert((POK == POK_VarAccess || POK == POK_VarDereference) &&
|
|
|
|
"Only works for variables");
|
2011-09-15 04:09:09 +08:00
|
|
|
unsigned DiagID = POK == POK_VarAccess?
|
|
|
|
diag::warn_variable_requires_any_lock:
|
|
|
|
diag::warn_var_deref_requires_any_lock;
|
2012-02-03 12:45:26 +08:00
|
|
|
PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID)
|
2012-09-20 03:18:29 +08:00
|
|
|
<< D->getNameAsString() << getLockKindFromAccessKind(AK));
|
2015-05-30 03:42:19 +08:00
|
|
|
Warnings.emplace_back(std::move(Warning), getNotes());
|
2011-09-10 00:04:02 +08:00
|
|
|
}
|
|
|
|
|
2014-04-02 05:43:23 +08:00
|
|
|
void handleMutexNotHeld(StringRef Kind, const NamedDecl *D,
|
|
|
|
ProtectedOperationKind POK, Name LockName,
|
|
|
|
LockKind LK, SourceLocation Loc,
|
2014-03-12 12:55:44 +08:00
|
|
|
Name *PossibleMatch) override {
|
2011-09-14 02:01:58 +08:00
|
|
|
unsigned DiagID = 0;
|
2012-09-11 03:58:23 +08:00
|
|
|
if (PossibleMatch) {
|
|
|
|
switch (POK) {
|
|
|
|
case POK_VarAccess:
|
|
|
|
DiagID = diag::warn_variable_requires_lock_precise;
|
|
|
|
break;
|
|
|
|
case POK_VarDereference:
|
|
|
|
DiagID = diag::warn_var_deref_requires_lock_precise;
|
|
|
|
break;
|
|
|
|
case POK_FunctionCall:
|
|
|
|
DiagID = diag::warn_fun_requires_lock_precise;
|
|
|
|
break;
|
2014-09-19 07:02:26 +08:00
|
|
|
case POK_PassByRef:
|
|
|
|
DiagID = diag::warn_guarded_pass_by_reference;
|
|
|
|
break;
|
|
|
|
case POK_PtPassByRef:
|
|
|
|
DiagID = diag::warn_pt_guarded_pass_by_reference;
|
|
|
|
break;
|
2012-09-11 03:58:23 +08:00
|
|
|
}
|
2014-04-02 05:43:23 +08:00
|
|
|
PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << Kind
|
|
|
|
<< D->getNameAsString()
|
|
|
|
<< LockName << LK);
|
2012-09-11 03:58:23 +08:00
|
|
|
PartialDiagnosticAt Note(Loc, S.PDiag(diag::note_found_mutex_near_match)
|
2014-04-02 05:43:23 +08:00
|
|
|
<< *PossibleMatch);
|
2014-09-19 07:02:26 +08:00
|
|
|
if (Verbose && POK == POK_VarAccess) {
|
|
|
|
PartialDiagnosticAt VNote(D->getLocation(),
|
|
|
|
S.PDiag(diag::note_guarded_by_declared_here)
|
|
|
|
<< D->getNameAsString());
|
2015-05-30 03:42:19 +08:00
|
|
|
Warnings.emplace_back(std::move(Warning), getNotes(Note, VNote));
|
2014-09-19 07:02:26 +08:00
|
|
|
} else
|
2015-05-30 03:42:19 +08:00
|
|
|
Warnings.emplace_back(std::move(Warning), getNotes(Note));
|
2012-09-11 03:58:23 +08:00
|
|
|
} else {
|
|
|
|
switch (POK) {
|
|
|
|
case POK_VarAccess:
|
|
|
|
DiagID = diag::warn_variable_requires_lock;
|
|
|
|
break;
|
|
|
|
case POK_VarDereference:
|
|
|
|
DiagID = diag::warn_var_deref_requires_lock;
|
|
|
|
break;
|
|
|
|
case POK_FunctionCall:
|
|
|
|
DiagID = diag::warn_fun_requires_lock;
|
|
|
|
break;
|
2014-09-19 07:02:26 +08:00
|
|
|
case POK_PassByRef:
|
|
|
|
DiagID = diag::warn_guarded_pass_by_reference;
|
|
|
|
break;
|
|
|
|
case POK_PtPassByRef:
|
|
|
|
DiagID = diag::warn_pt_guarded_pass_by_reference;
|
|
|
|
break;
|
2012-09-11 03:58:23 +08:00
|
|
|
}
|
2014-04-02 05:43:23 +08:00
|
|
|
PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << Kind
|
|
|
|
<< D->getNameAsString()
|
|
|
|
<< LockName << LK);
|
2014-08-15 05:40:15 +08:00
|
|
|
if (Verbose && POK == POK_VarAccess) {
|
|
|
|
PartialDiagnosticAt Note(D->getLocation(),
|
2014-08-15 20:38:17 +08:00
|
|
|
S.PDiag(diag::note_guarded_by_declared_here)
|
|
|
|
<< D->getNameAsString());
|
2015-05-30 03:42:19 +08:00
|
|
|
Warnings.emplace_back(std::move(Warning), getNotes(Note));
|
2014-08-15 20:38:17 +08:00
|
|
|
} else
|
2015-05-30 03:42:19 +08:00
|
|
|
Warnings.emplace_back(std::move(Warning), getNotes());
|
2011-09-10 00:04:02 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-04-11 10:00:23 +08:00
|
|
|
void handleNegativeNotHeld(StringRef Kind, Name LockName, Name Neg,
|
|
|
|
SourceLocation Loc) override {
|
2014-08-05 06:13:06 +08:00
|
|
|
PartialDiagnosticAt Warning(Loc,
|
|
|
|
S.PDiag(diag::warn_acquire_requires_negative_cap)
|
|
|
|
<< Kind << LockName << Neg);
|
2015-05-30 03:42:19 +08:00
|
|
|
Warnings.emplace_back(std::move(Warning), getNotes());
|
2014-08-05 06:13:06 +08:00
|
|
|
}
|
|
|
|
|
2014-04-02 05:43:23 +08:00
|
|
|
void handleFunExcludesLock(StringRef Kind, Name FunName, Name LockName,
|
2014-03-12 12:55:44 +08:00
|
|
|
SourceLocation Loc) override {
|
2014-04-02 05:43:23 +08:00
|
|
|
PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_fun_excludes_mutex)
|
|
|
|
<< Kind << FunName << LockName);
|
2015-05-30 03:42:19 +08:00
|
|
|
Warnings.emplace_back(std::move(Warning), getNotes());
|
2014-08-15 05:40:15 +08:00
|
|
|
}
|
|
|
|
|
2015-04-11 10:00:23 +08:00
|
|
|
void handleLockAcquiredBefore(StringRef Kind, Name L1Name, Name L2Name,
|
|
|
|
SourceLocation Loc) override {
|
2015-02-04 06:11:04 +08:00
|
|
|
PartialDiagnosticAt Warning(Loc,
|
|
|
|
S.PDiag(diag::warn_acquired_before) << Kind << L1Name << L2Name);
|
2015-05-30 03:42:19 +08:00
|
|
|
Warnings.emplace_back(std::move(Warning), getNotes());
|
2015-02-04 06:11:04 +08:00
|
|
|
}
|
|
|
|
|
2015-04-11 10:00:23 +08:00
|
|
|
void handleBeforeAfterCycle(Name L1Name, SourceLocation Loc) override {
|
2015-02-04 06:11:04 +08:00
|
|
|
PartialDiagnosticAt Warning(Loc,
|
|
|
|
S.PDiag(diag::warn_acquired_before_after_cycle) << L1Name);
|
2015-05-30 03:42:19 +08:00
|
|
|
Warnings.emplace_back(std::move(Warning), getNotes());
|
2015-02-04 06:11:04 +08:00
|
|
|
}
|
|
|
|
|
2014-08-15 05:40:15 +08:00
|
|
|
void enterFunction(const FunctionDecl* FD) override {
|
|
|
|
CurrentFunction = FD;
|
|
|
|
}
|
|
|
|
|
|
|
|
void leaveFunction(const FunctionDecl* FD) override {
|
2015-10-07 07:40:43 +08:00
|
|
|
CurrentFunction = nullptr;
|
2011-09-10 00:04:02 +08:00
|
|
|
}
|
|
|
|
};
|
2015-10-07 07:40:43 +08:00
|
|
|
} // anonymous namespace
|
2015-03-19 22:23:45 +08:00
|
|
|
} // namespace threadSafety
|
|
|
|
} // namespace clang
|
2011-09-10 00:04:02 +08:00
|
|
|
|
2013-08-13 05:20:55 +08:00
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
// -Wconsumed
|
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
|
|
|
|
namespace clang {
|
|
|
|
namespace consumed {
|
|
|
|
namespace {
|
|
|
|
class ConsumedWarningsHandler : public ConsumedWarningsHandlerBase {
|
|
|
|
|
|
|
|
Sema &S;
|
|
|
|
DiagList Warnings;
|
|
|
|
|
|
|
|
public:
|
2015-02-04 06:11:04 +08:00
|
|
|
|
2013-08-13 05:20:55 +08:00
|
|
|
ConsumedWarningsHandler(Sema &S) : S(S) {}
|
2014-03-12 12:55:44 +08:00
|
|
|
|
|
|
|
void emitDiagnostics() override {
|
2013-08-13 05:20:55 +08:00
|
|
|
Warnings.sort(SortDiagBySourceLocation(S.getSourceManager()));
|
2014-05-16 04:50:47 +08:00
|
|
|
for (const auto &Diag : Warnings) {
|
|
|
|
S.Diag(Diag.first.first, Diag.first.second);
|
|
|
|
for (const auto &Note : Diag.second)
|
|
|
|
S.Diag(Note.first, Note.second);
|
2013-08-13 05:20:55 +08:00
|
|
|
}
|
|
|
|
}
|
2014-03-12 12:55:44 +08:00
|
|
|
|
|
|
|
void warnLoopStateMismatch(SourceLocation Loc,
|
|
|
|
StringRef VariableName) override {
|
2013-10-10 02:30:24 +08:00
|
|
|
PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_loop_state_mismatch) <<
|
|
|
|
VariableName);
|
2015-05-30 03:42:19 +08:00
|
|
|
|
|
|
|
Warnings.emplace_back(std::move(Warning), OptionalNotes());
|
2013-10-10 02:30:24 +08:00
|
|
|
}
|
|
|
|
|
2013-10-18 06:53:04 +08:00
|
|
|
void warnParamReturnTypestateMismatch(SourceLocation Loc,
|
|
|
|
StringRef VariableName,
|
|
|
|
StringRef ExpectedState,
|
2014-03-12 12:55:44 +08:00
|
|
|
StringRef ObservedState) override {
|
2013-10-18 06:53:04 +08:00
|
|
|
|
|
|
|
PartialDiagnosticAt Warning(Loc, S.PDiag(
|
|
|
|
diag::warn_param_return_typestate_mismatch) << VariableName <<
|
|
|
|
ExpectedState << ObservedState);
|
2015-05-30 03:42:19 +08:00
|
|
|
|
|
|
|
Warnings.emplace_back(std::move(Warning), OptionalNotes());
|
2013-10-18 06:53:04 +08:00
|
|
|
}
|
|
|
|
|
2013-10-18 07:23:53 +08:00
|
|
|
void warnParamTypestateMismatch(SourceLocation Loc, StringRef ExpectedState,
|
2014-03-12 12:55:44 +08:00
|
|
|
StringRef ObservedState) override {
|
2013-10-18 07:23:53 +08:00
|
|
|
|
|
|
|
PartialDiagnosticAt Warning(Loc, S.PDiag(
|
|
|
|
diag::warn_param_typestate_mismatch) << ExpectedState << ObservedState);
|
2015-05-30 03:42:19 +08:00
|
|
|
|
|
|
|
Warnings.emplace_back(std::move(Warning), OptionalNotes());
|
2013-10-18 07:23:53 +08:00
|
|
|
}
|
|
|
|
|
2013-09-04 04:11:38 +08:00
|
|
|
void warnReturnTypestateForUnconsumableType(SourceLocation Loc,
|
2014-03-12 12:55:44 +08:00
|
|
|
StringRef TypeName) override {
|
2013-09-04 04:11:38 +08:00
|
|
|
PartialDiagnosticAt Warning(Loc, S.PDiag(
|
|
|
|
diag::warn_return_typestate_for_unconsumable_type) << TypeName);
|
2015-05-30 03:42:19 +08:00
|
|
|
|
|
|
|
Warnings.emplace_back(std::move(Warning), OptionalNotes());
|
2013-09-04 04:11:38 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
void warnReturnTypestateMismatch(SourceLocation Loc, StringRef ExpectedState,
|
2014-03-12 12:55:44 +08:00
|
|
|
StringRef ObservedState) override {
|
2013-09-04 04:11:38 +08:00
|
|
|
|
|
|
|
PartialDiagnosticAt Warning(Loc, S.PDiag(
|
|
|
|
diag::warn_return_typestate_mismatch) << ExpectedState << ObservedState);
|
2015-05-30 03:42:19 +08:00
|
|
|
|
|
|
|
Warnings.emplace_back(std::move(Warning), OptionalNotes());
|
2013-09-04 04:11:38 +08:00
|
|
|
}
|
|
|
|
|
2013-10-05 05:28:06 +08:00
|
|
|
void warnUseOfTempInInvalidState(StringRef MethodName, StringRef State,
|
2014-03-12 12:55:44 +08:00
|
|
|
SourceLocation Loc) override {
|
2013-08-13 05:20:55 +08:00
|
|
|
|
|
|
|
PartialDiagnosticAt Warning(Loc, S.PDiag(
|
2013-10-05 05:28:06 +08:00
|
|
|
diag::warn_use_of_temp_in_invalid_state) << MethodName << State);
|
2015-05-30 03:42:19 +08:00
|
|
|
|
|
|
|
Warnings.emplace_back(std::move(Warning), OptionalNotes());
|
2013-08-13 05:20:55 +08:00
|
|
|
}
|
|
|
|
|
2013-10-05 05:28:06 +08:00
|
|
|
void warnUseInInvalidState(StringRef MethodName, StringRef VariableName,
|
2014-03-12 12:55:44 +08:00
|
|
|
StringRef State, SourceLocation Loc) override {
|
2013-08-13 05:20:55 +08:00
|
|
|
|
2013-10-05 05:28:06 +08:00
|
|
|
PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_use_in_invalid_state) <<
|
|
|
|
MethodName << VariableName << State);
|
2015-05-30 03:42:19 +08:00
|
|
|
|
|
|
|
Warnings.emplace_back(std::move(Warning), OptionalNotes());
|
2013-08-13 05:20:55 +08:00
|
|
|
}
|
|
|
|
};
|
2015-10-07 07:40:43 +08:00
|
|
|
} // anonymous namespace
|
|
|
|
} // namespace consumed
|
|
|
|
} // namespace clang
|
2013-08-13 05:20:55 +08:00
|
|
|
|
2010-03-21 05:06:02 +08:00
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
// AnalysisBasedWarnings - Worker object used by Sema to execute analysis-based
|
|
|
|
// warnings on a function, method, or block.
|
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
|
2010-03-23 08:13:23 +08:00
|
|
|
clang::sema::AnalysisBasedWarnings::Policy::Policy() {
|
2010-03-21 05:06:02 +08:00
|
|
|
enableCheckFallThrough = 1;
|
2010-03-23 08:13:23 +08:00
|
|
|
enableCheckUnreachable = 0;
|
2011-08-24 02:46:34 +08:00
|
|
|
enableThreadSafetyAnalysis = 0;
|
2013-08-13 05:20:55 +08:00
|
|
|
enableConsumedAnalysis = 0;
|
2010-03-23 08:13:23 +08:00
|
|
|
}
|
2010-03-21 05:06:02 +08:00
|
|
|
|
2014-03-15 13:47:06 +08:00
|
|
|
static unsigned isEnabled(DiagnosticsEngine &D, unsigned diag) {
|
2014-06-16 07:30:39 +08:00
|
|
|
return (unsigned)!D.isIgnored(diag, SourceLocation());
|
2014-03-15 13:47:06 +08:00
|
|
|
}
|
|
|
|
|
2011-07-07 00:21:37 +08:00
|
|
|
clang::sema::AnalysisBasedWarnings::AnalysisBasedWarnings(Sema &s)
|
|
|
|
: S(s),
|
|
|
|
NumFunctionsAnalyzed(0),
|
2011-07-09 04:38:53 +08:00
|
|
|
NumFunctionsWithBadCFGs(0),
|
2011-07-07 00:21:37 +08:00
|
|
|
NumCFGBlocks(0),
|
2011-07-09 04:38:53 +08:00
|
|
|
MaxCFGBlocksPerFunction(0),
|
|
|
|
NumUninitAnalysisFunctions(0),
|
|
|
|
NumUninitAnalysisVariables(0),
|
|
|
|
MaxUninitAnalysisVariablesPerFunction(0),
|
|
|
|
NumUninitAnalysisBlockVisits(0),
|
|
|
|
MaxUninitAnalysisBlockVisitsPerFunction(0) {
|
2014-03-15 13:47:06 +08:00
|
|
|
|
|
|
|
using namespace diag;
|
2011-09-26 07:23:43 +08:00
|
|
|
DiagnosticsEngine &D = S.getDiagnostics();
|
2014-03-15 13:47:06 +08:00
|
|
|
|
|
|
|
DefaultPolicy.enableCheckUnreachable =
|
|
|
|
isEnabled(D, warn_unreachable) ||
|
|
|
|
isEnabled(D, warn_unreachable_break) ||
|
2014-03-21 14:02:36 +08:00
|
|
|
isEnabled(D, warn_unreachable_return) ||
|
|
|
|
isEnabled(D, warn_unreachable_loop_increment);
|
2014-03-15 13:47:06 +08:00
|
|
|
|
|
|
|
DefaultPolicy.enableThreadSafetyAnalysis =
|
|
|
|
isEnabled(D, warn_double_lock);
|
|
|
|
|
|
|
|
DefaultPolicy.enableConsumedAnalysis =
|
|
|
|
isEnabled(D, warn_use_in_invalid_state);
|
2010-03-21 05:06:02 +08:00
|
|
|
}
|
|
|
|
|
2014-05-16 04:50:47 +08:00
|
|
|
static void flushDiagnostics(Sema &S, const sema::FunctionScopeInfo *fscope) {
|
|
|
|
for (const auto &D : fscope->PossiblyUnreachableDiags)
|
2011-02-23 09:52:04 +08:00
|
|
|
S.Diag(D.Loc, D.PD);
|
|
|
|
}
|
|
|
|
|
2010-03-23 08:13:23 +08:00
|
|
|
void clang::sema::
|
|
|
|
AnalysisBasedWarnings::IssueWarnings(sema::AnalysisBasedWarnings::Policy P,
|
2011-02-23 09:51:53 +08:00
|
|
|
sema::FunctionScopeInfo *fscope,
|
2011-02-23 09:51:48 +08:00
|
|
|
const Decl *D, const BlockExpr *blkExpr) {
|
2010-03-21 05:11:09 +08:00
|
|
|
|
2010-03-21 05:06:02 +08:00
|
|
|
// We avoid doing analysis-based warnings when there are errors for
|
|
|
|
// two reasons:
|
|
|
|
// (1) The CFGs often can't be constructed (if the body is invalid), so
|
|
|
|
// don't bother trying.
|
|
|
|
// (2) The code already has problems; running the analysis just takes more
|
|
|
|
// time.
|
2011-09-26 07:23:43 +08:00
|
|
|
DiagnosticsEngine &Diags = S.getDiagnostics();
|
2010-05-01 05:49:25 +08:00
|
|
|
|
2017-11-23 16:15:22 +08:00
|
|
|
// Do not do any analysis if we are going to just ignore them.
|
|
|
|
if (Diags.getIgnoreAllWarnings() ||
|
|
|
|
(Diags.getSuppressSystemWarnings() &&
|
|
|
|
S.SourceMgr.isInSystemHeader(D->getLocation())))
|
2010-03-23 08:13:23 +08:00
|
|
|
return;
|
|
|
|
|
2010-08-25 13:56:39 +08:00
|
|
|
// For code in dependent contexts, we'll do this at instantiation time.
|
2012-01-24 12:51:48 +08:00
|
|
|
if (cast<DeclContext>(D)->isDependentContext())
|
|
|
|
return;
|
2010-03-21 05:06:02 +08:00
|
|
|
|
2016-07-14 04:35:26 +08:00
|
|
|
if (Diags.hasUncompilableErrorOccurred()) {
|
2011-02-23 09:52:04 +08:00
|
|
|
// Flush out any possibly unreachable diagnostics.
|
|
|
|
flushDiagnostics(S, fscope);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2010-03-21 05:06:02 +08:00
|
|
|
const Stmt *Body = D->getBody();
|
|
|
|
assert(Body);
|
|
|
|
|
2013-10-15 03:11:25 +08:00
|
|
|
// Construct the analysis context with the specified CFG build options.
|
2014-05-26 14:22:03 +08:00
|
|
|
AnalysisDeclContext AC(/* AnalysisDeclContextManager */ nullptr, D);
|
2011-07-21 13:22:47 +08:00
|
|
|
|
2010-03-21 05:06:02 +08:00
|
|
|
// Don't generate EH edges for CallExprs as we'd like to avoid the n^2
|
2013-09-09 22:48:42 +08:00
|
|
|
// explosion for destructors that can result and the compile time hit.
|
2011-07-21 13:22:47 +08:00
|
|
|
AC.getCFGBuildOptions().PruneTriviallyFalseEdges = true;
|
|
|
|
AC.getCFGBuildOptions().AddEHEdges = false;
|
|
|
|
AC.getCFGBuildOptions().AddInitializers = true;
|
|
|
|
AC.getCFGBuildOptions().AddImplicitDtors = true;
|
2012-09-06 07:11:06 +08:00
|
|
|
AC.getCFGBuildOptions().AddTemporaryDtors = true;
|
2014-01-14 01:59:19 +08:00
|
|
|
AC.getCFGBuildOptions().AddCXXNewAllocator = false;
|
2015-06-03 18:12:40 +08:00
|
|
|
AC.getCFGBuildOptions().AddCXXDefaultInitExprInCtors = true;
|
2012-09-06 07:11:06 +08:00
|
|
|
|
2011-07-19 22:18:48 +08:00
|
|
|
// Force that certain expressions appear as CFGElements in the CFG. This
|
|
|
|
// is used to speed up various analyses.
|
|
|
|
// FIXME: This isn't the right factoring. This is here for initial
|
|
|
|
// prototyping, but we need a way for analyses to say what expressions they
|
|
|
|
// expect to always be CFGElements and then fill in the BuildOptions
|
|
|
|
// appropriately. This is essentially a layering violation.
|
2013-08-13 05:20:55 +08:00
|
|
|
if (P.enableCheckUnreachable || P.enableThreadSafetyAnalysis ||
|
|
|
|
P.enableConsumedAnalysis) {
|
2011-12-09 04:23:06 +08:00
|
|
|
// Unreachable code analysis and thread safety require a linearized CFG.
|
2011-08-24 07:05:11 +08:00
|
|
|
AC.getCFGBuildOptions().setAllAlwaysAdd();
|
|
|
|
}
|
|
|
|
else {
|
|
|
|
AC.getCFGBuildOptions()
|
|
|
|
.setAlwaysAdd(Stmt::BinaryOperatorClass)
|
2012-07-17 09:27:33 +08:00
|
|
|
.setAlwaysAdd(Stmt::CompoundAssignOperatorClass)
|
2011-08-24 07:05:11 +08:00
|
|
|
.setAlwaysAdd(Stmt::BlockExprClass)
|
|
|
|
.setAlwaysAdd(Stmt::CStyleCastExprClass)
|
|
|
|
.setAlwaysAdd(Stmt::DeclRefExprClass)
|
|
|
|
.setAlwaysAdd(Stmt::ImplicitCastExprClass)
|
2012-05-04 02:27:39 +08:00
|
|
|
.setAlwaysAdd(Stmt::UnaryOperatorClass)
|
|
|
|
.setAlwaysAdd(Stmt::AttributedStmtClass);
|
2011-08-24 07:05:11 +08:00
|
|
|
}
|
2011-07-21 13:22:47 +08:00
|
|
|
|
2014-04-15 08:57:50 +08:00
|
|
|
// Install the logical handler for -Wtautological-overlap-compare
|
|
|
|
std::unique_ptr<LogicalErrorHandler> LEH;
|
2014-06-16 07:30:39 +08:00
|
|
|
if (!Diags.isIgnored(diag::warn_tautological_overlap_comparison,
|
|
|
|
D->getLocStart())) {
|
2014-04-15 08:57:50 +08:00
|
|
|
LEH.reset(new LogicalErrorHandler(S));
|
|
|
|
AC.getCFGBuildOptions().Observer = LEH.get();
|
2014-04-05 13:17:01 +08:00
|
|
|
}
|
2013-10-15 03:11:25 +08:00
|
|
|
|
2011-02-23 09:52:04 +08:00
|
|
|
// Emit delayed diagnostics.
|
2012-01-24 12:51:48 +08:00
|
|
|
if (!fscope->PossiblyUnreachableDiags.empty()) {
|
2011-02-23 09:52:04 +08:00
|
|
|
bool analyzed = false;
|
2011-03-10 11:50:34 +08:00
|
|
|
|
|
|
|
// Register the expressions with the CFGBuilder.
|
2014-05-16 04:50:47 +08:00
|
|
|
for (const auto &D : fscope->PossiblyUnreachableDiags) {
|
|
|
|
if (D.stmt)
|
|
|
|
AC.registerForcedBlockExpression(D.stmt);
|
2011-03-10 11:50:34 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
if (AC.getCFG()) {
|
|
|
|
analyzed = true;
|
2014-05-16 04:50:47 +08:00
|
|
|
for (const auto &D : fscope->PossiblyUnreachableDiags) {
|
2011-03-10 11:50:34 +08:00
|
|
|
bool processed = false;
|
2014-05-16 04:50:47 +08:00
|
|
|
if (D.stmt) {
|
|
|
|
const CFGBlock *block = AC.getBlockForRegisteredExpression(D.stmt);
|
2012-01-21 09:01:51 +08:00
|
|
|
CFGReverseBlockReachabilityAnalysis *cra =
|
|
|
|
AC.getCFGReachablityAnalysis();
|
|
|
|
// FIXME: We should be able to assert that block is non-null, but
|
|
|
|
// the CFG analysis can skip potentially-evaluated expressions in
|
|
|
|
// edge cases; see test/Sema/vla-2.c.
|
|
|
|
if (block && cra) {
|
2011-02-23 09:52:04 +08:00
|
|
|
// Can this block be reached from the entrance?
|
2011-03-10 11:50:34 +08:00
|
|
|
if (cra->isReachable(&AC.getCFG()->getEntry(), block))
|
2011-02-23 09:52:04 +08:00
|
|
|
S.Diag(D.Loc, D.PD);
|
2011-03-10 11:50:34 +08:00
|
|
|
processed = true;
|
2011-02-23 09:52:04 +08:00
|
|
|
}
|
2011-03-10 11:50:34 +08:00
|
|
|
}
|
|
|
|
if (!processed) {
|
|
|
|
// Emit the warning anyway if we cannot map to a basic block.
|
|
|
|
S.Diag(D.Loc, D.PD);
|
2011-02-23 09:52:04 +08:00
|
|
|
}
|
|
|
|
}
|
2011-03-10 11:50:34 +08:00
|
|
|
}
|
2011-02-23 09:52:04 +08:00
|
|
|
|
|
|
|
if (!analyzed)
|
|
|
|
flushDiagnostics(S, fscope);
|
|
|
|
}
|
|
|
|
|
2010-03-21 05:06:02 +08:00
|
|
|
// Warning: check missing 'return'
|
2012-01-24 12:51:48 +08:00
|
|
|
if (P.enableCheckFallThrough) {
|
2010-03-21 05:06:02 +08:00
|
|
|
const CheckFallThroughDiagnostics &CD =
|
2016-10-27 15:30:31 +08:00
|
|
|
(isa<BlockDecl>(D)
|
|
|
|
? CheckFallThroughDiagnostics::MakeForBlock()
|
|
|
|
: (isa<CXXMethodDecl>(D) &&
|
|
|
|
cast<CXXMethodDecl>(D)->getOverloadedOperator() == OO_Call &&
|
|
|
|
cast<CXXMethodDecl>(D)->getParent()->isLambda())
|
|
|
|
? CheckFallThroughDiagnostics::MakeForLambda()
|
2017-05-25 10:16:53 +08:00
|
|
|
: (fscope->isCoroutine()
|
2016-10-27 15:30:31 +08:00
|
|
|
? CheckFallThroughDiagnostics::MakeForCoroutine(D)
|
|
|
|
: CheckFallThroughDiagnostics::MakeForFunction(D)));
|
2011-02-23 09:51:48 +08:00
|
|
|
CheckFallThroughForBody(S, D, Body, blkExpr, CD, AC);
|
2010-03-21 05:06:02 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
// Warning: check for unreachable code
|
2011-12-01 05:22:09 +08:00
|
|
|
if (P.enableCheckUnreachable) {
|
|
|
|
// Only check for unreachable code on non-template instantiations.
|
|
|
|
// Different template instantiations can effectively change the control-flow
|
|
|
|
// and it is very difficult to prove that a snippet of code in a template
|
|
|
|
// is unreachable for all instantiations.
|
2011-12-01 08:59:17 +08:00
|
|
|
bool isTemplateInstantiation = false;
|
|
|
|
if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
|
|
|
|
isTemplateInstantiation = Function->isTemplateInstantiation();
|
|
|
|
if (!isTemplateInstantiation)
|
2011-12-01 05:22:09 +08:00
|
|
|
CheckUnreachable(S, AC);
|
|
|
|
}
|
2011-09-10 00:04:02 +08:00
|
|
|
|
2011-08-24 02:46:34 +08:00
|
|
|
// Check for thread safety violations
|
2012-01-24 12:51:48 +08:00
|
|
|
if (P.enableThreadSafetyAnalysis) {
|
2011-10-22 02:10:14 +08:00
|
|
|
SourceLocation FL = AC.getDecl()->getLocation();
|
2012-02-03 12:45:26 +08:00
|
|
|
SourceLocation FEL = AC.getDecl()->getLocEnd();
|
2014-07-28 23:57:27 +08:00
|
|
|
threadSafety::ThreadSafetyReporter Reporter(S, FL, FEL);
|
2014-06-16 07:30:39 +08:00
|
|
|
if (!Diags.isIgnored(diag::warn_thread_safety_beta, D->getLocStart()))
|
2012-12-05 08:06:15 +08:00
|
|
|
Reporter.setIssueBetaWarnings(true);
|
2014-08-15 05:40:15 +08:00
|
|
|
if (!Diags.isIgnored(diag::warn_thread_safety_verbose, D->getLocStart()))
|
|
|
|
Reporter.setVerbose(true);
|
2012-12-05 08:06:15 +08:00
|
|
|
|
2015-02-04 06:11:04 +08:00
|
|
|
threadSafety::runThreadSafetyAnalysis(AC, Reporter,
|
|
|
|
&S.ThreadSafetyDeclCache);
|
2011-09-10 00:04:02 +08:00
|
|
|
Reporter.emitDiagnostics();
|
|
|
|
}
|
2011-08-24 02:46:34 +08:00
|
|
|
|
2013-08-13 05:20:55 +08:00
|
|
|
// Check for violations of consumed properties.
|
|
|
|
if (P.enableConsumedAnalysis) {
|
|
|
|
consumed::ConsumedWarningsHandler WarningHandler(S);
|
2013-08-13 07:49:39 +08:00
|
|
|
consumed::ConsumedAnalyzer Analyzer(WarningHandler);
|
2013-08-13 05:20:55 +08:00
|
|
|
Analyzer.run(AC);
|
|
|
|
}
|
|
|
|
|
2014-06-16 07:30:39 +08:00
|
|
|
if (!Diags.isIgnored(diag::warn_uninit_var, D->getLocStart()) ||
|
|
|
|
!Diags.isIgnored(diag::warn_sometimes_uninit_var, D->getLocStart()) ||
|
|
|
|
!Diags.isIgnored(diag::warn_maybe_uninit_var, D->getLocStart())) {
|
2011-03-17 13:29:57 +08:00
|
|
|
if (CFG *cfg = AC.getCFG()) {
|
2011-01-19 05:18:58 +08:00
|
|
|
UninitValsDiagReporter reporter(S);
|
2011-07-17 02:31:33 +08:00
|
|
|
UninitVariablesAnalysisStats stats;
|
2011-07-17 04:13:06 +08:00
|
|
|
std::memset(&stats, 0, sizeof(UninitVariablesAnalysisStats));
|
2011-01-26 03:13:48 +08:00
|
|
|
runUninitializedVariablesAnalysis(*cast<DeclContext>(D), *cfg, AC,
|
2011-07-07 00:21:37 +08:00
|
|
|
reporter, stats);
|
|
|
|
|
|
|
|
if (S.CollectStats && stats.NumVariablesAnalyzed > 0) {
|
|
|
|
++NumUninitAnalysisFunctions;
|
|
|
|
NumUninitAnalysisVariables += stats.NumVariablesAnalyzed;
|
|
|
|
NumUninitAnalysisBlockVisits += stats.NumBlockVisits;
|
|
|
|
MaxUninitAnalysisVariablesPerFunction =
|
|
|
|
std::max(MaxUninitAnalysisVariablesPerFunction,
|
|
|
|
stats.NumVariablesAnalyzed);
|
|
|
|
MaxUninitAnalysisBlockVisitsPerFunction =
|
|
|
|
std::max(MaxUninitAnalysisBlockVisitsPerFunction,
|
|
|
|
stats.NumBlockVisits);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2012-06-02 09:01:07 +08:00
|
|
|
bool FallThroughDiagFull =
|
2014-06-16 07:30:39 +08:00
|
|
|
!Diags.isIgnored(diag::warn_unannotated_fallthrough, D->getLocStart());
|
|
|
|
bool FallThroughDiagPerFunction = !Diags.isIgnored(
|
|
|
|
diag::warn_unannotated_fallthrough_per_function, D->getLocStart());
|
2016-03-08 08:32:55 +08:00
|
|
|
if (FallThroughDiagFull || FallThroughDiagPerFunction ||
|
|
|
|
fscope->HasFallthroughStmt) {
|
2012-06-02 09:01:07 +08:00
|
|
|
DiagnoseSwitchLabelsFallthrough(S, AC, !FallThroughDiagFull);
|
2012-05-04 02:27:39 +08:00
|
|
|
}
|
|
|
|
|
Define weak and __weak to mean ARC-style weak references, even in MRC.
Previously, __weak was silently accepted and ignored in MRC mode.
That makes this a potentially source-breaking change that we have to
roll out cautiously. Accordingly, for the time being, actual support
for __weak references in MRC is experimental, and the compiler will
reject attempts to actually form such references. The intent is to
eventually enable the feature by default in all non-GC modes.
(It is, of course, incompatible with ObjC GC's interpretation of
__weak.)
If you like, you can enable this feature with
-Xclang -fobjc-weak
but like any -Xclang option, this option may be removed at any point,
e.g. if/when it is eventually enabled by default.
This patch also enables the use of the ARC __unsafe_unretained qualifier
in MRC. Unlike __weak, this is being enabled immediately. Since
variables are essentially __unsafe_unretained by default in MRC,
the only practical uses are (1) communication and (2) changing the
default behavior of by-value block capture.
As an implementation matter, this means that the ObjC ownership
qualifiers may appear in any ObjC language mode, and so this patch
removes a number of checks for getLangOpts().ObjCAutoRefCount
that were guarding the processing of these qualifiers. I don't
expect this to be a significant drain on performance; it may even
be faster to just check for these qualifiers directly on a type
(since it's probably in a register anyway) than to do N dependent
loads to grab the LangOptions.
rdar://9674298
llvm-svn: 251041
2015-10-23 02:38:17 +08:00
|
|
|
if (S.getLangOpts().ObjCWeak &&
|
2014-06-16 07:30:39 +08:00
|
|
|
!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, D->getLocStart()))
|
2012-10-12 00:10:19 +08:00
|
|
|
diagnoseRepeatedUseOfWeak(S, fscope, D, AC.getParentMap());
|
Add a warning (off by default) for repeated use of the same weak property.
The motivating example:
if (self.weakProp)
use(self.weakProp);
As with any non-atomic test-then-use, it is possible a weak property to be
non-nil at the 'if', but be deallocated by the time it is used. The correct
way to write this example is as follows:
id tmp = self.weakProp;
if (tmp)
use(tmp);
The warning is controlled by -Warc-repeated-use-of-receiver, and uses the
property name and base to determine if the same property on the same object
is being accessed multiple times. In cases where the base is more
complicated than just a single Decl (e.g. 'foo.bar.weakProp'), it picks a
Decl for some degree of uniquing and reports the problem under a subflag,
-Warc-maybe-repeated-use-of-receiver. This gives a way to tune the
aggressiveness of the warning for a particular project.
The warning is not on by default because it is not flow-sensitive and thus
may have a higher-than-acceptable rate of false positives, though it is
less noisy than -Wreceiver-is-weak. On the other hand, it will not warn
about some cases that may be legitimate issues that -Wreceiver-is-weak
will catch, and it does not attempt to reason about methods returning weak
values.
Even though this is not a real "analysis-based" check I've put the bug
emission code in AnalysisBasedWarnings for two reasons: (1) to run on
every kind of code body (function, method, block, or lambda), and (2) to
suggest that it may be enhanced by flow-sensitive analysis in the future.
The second (smaller) half of this work is to extend it to weak locals
and weak ivars. This should use most of the same infrastructure.
Part of <rdar://problem/12280249>
llvm-svn: 164854
2012-09-29 06:21:30 +08:00
|
|
|
|
2013-12-21 10:33:43 +08:00
|
|
|
|
|
|
|
// Check for infinite self-recursion in functions
|
2014-06-16 07:30:39 +08:00
|
|
|
if (!Diags.isIgnored(diag::warn_infinite_recursive_function,
|
|
|
|
D->getLocStart())) {
|
2013-12-21 10:33:43 +08:00
|
|
|
if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
|
|
|
|
checkRecursiveFunction(S, FD, Body, AC);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-06-24 04:22:19 +08:00
|
|
|
// Check for throw out of non-throwing function.
|
|
|
|
if (!Diags.isIgnored(diag::warn_throw_in_noexcept_func, D->getLocStart()))
|
|
|
|
if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
|
|
|
|
if (S.getLangOpts().CPlusPlus && isNoexcept(FD))
|
|
|
|
checkThrowInNonThrowingFunc(S, FD, AC);
|
|
|
|
|
2014-04-15 08:57:50 +08:00
|
|
|
// If none of the previous checks caused a CFG build, trigger one here
|
|
|
|
// for -Wtautological-overlap-compare
|
2014-06-16 07:30:39 +08:00
|
|
|
if (!Diags.isIgnored(diag::warn_tautological_overlap_comparison,
|
2014-04-15 08:57:50 +08:00
|
|
|
D->getLocStart())) {
|
|
|
|
AC.getCFG();
|
|
|
|
}
|
|
|
|
|
2011-07-07 00:21:37 +08:00
|
|
|
// Collect statistics about the CFG if it was built.
|
|
|
|
if (S.CollectStats && AC.isCFGBuilt()) {
|
|
|
|
++NumFunctionsAnalyzed;
|
|
|
|
if (CFG *cfg = AC.getCFG()) {
|
|
|
|
// If we successfully built a CFG for this context, record some more
|
|
|
|
// detail information about it.
|
2011-07-07 06:21:45 +08:00
|
|
|
NumCFGBlocks += cfg->getNumBlockIDs();
|
2011-07-07 00:21:37 +08:00
|
|
|
MaxCFGBlocksPerFunction = std::max(MaxCFGBlocksPerFunction,
|
2011-07-07 06:21:45 +08:00
|
|
|
cfg->getNumBlockIDs());
|
2011-07-07 00:21:37 +08:00
|
|
|
} else {
|
|
|
|
++NumFunctionsWithBadCFGs;
|
2011-01-15 10:58:47 +08:00
|
|
|
}
|
|
|
|
}
|
2010-03-21 05:06:02 +08:00
|
|
|
}
|
2011-07-07 00:21:37 +08:00
|
|
|
|
|
|
|
void clang::sema::AnalysisBasedWarnings::PrintStats() const {
|
|
|
|
llvm::errs() << "\n*** Analysis Based Warnings Stats:\n";
|
|
|
|
|
|
|
|
unsigned NumCFGsBuilt = NumFunctionsAnalyzed - NumFunctionsWithBadCFGs;
|
|
|
|
unsigned AvgCFGBlocksPerFunction =
|
|
|
|
!NumCFGsBuilt ? 0 : NumCFGBlocks/NumCFGsBuilt;
|
|
|
|
llvm::errs() << NumFunctionsAnalyzed << " functions analyzed ("
|
|
|
|
<< NumFunctionsWithBadCFGs << " w/o CFGs).\n"
|
|
|
|
<< " " << NumCFGBlocks << " CFG blocks built.\n"
|
|
|
|
<< " " << AvgCFGBlocksPerFunction
|
|
|
|
<< " average CFG blocks per function.\n"
|
|
|
|
<< " " << MaxCFGBlocksPerFunction
|
|
|
|
<< " max CFG blocks per function.\n";
|
|
|
|
|
|
|
|
unsigned AvgUninitVariablesPerFunction = !NumUninitAnalysisFunctions ? 0
|
|
|
|
: NumUninitAnalysisVariables/NumUninitAnalysisFunctions;
|
|
|
|
unsigned AvgUninitBlockVisitsPerFunction = !NumUninitAnalysisFunctions ? 0
|
|
|
|
: NumUninitAnalysisBlockVisits/NumUninitAnalysisFunctions;
|
|
|
|
llvm::errs() << NumUninitAnalysisFunctions
|
|
|
|
<< " functions analyzed for uninitialiazed variables\n"
|
|
|
|
<< " " << NumUninitAnalysisVariables << " variables analyzed.\n"
|
|
|
|
<< " " << AvgUninitVariablesPerFunction
|
|
|
|
<< " average variables per function.\n"
|
|
|
|
<< " " << MaxUninitAnalysisVariablesPerFunction
|
|
|
|
<< " max variables per function.\n"
|
|
|
|
<< " " << NumUninitAnalysisBlockVisits << " block visits.\n"
|
|
|
|
<< " " << AvgUninitBlockVisitsPerFunction
|
|
|
|
<< " average block visits per function.\n"
|
|
|
|
<< " " << MaxUninitAnalysisBlockVisitsPerFunction
|
|
|
|
<< " max block visits per function.\n";
|
|
|
|
}
|