r314499 - [Sema] Suppress warnings for C's zero initializer
Author: danielmarjamaki Date: Fri Sep 29 02:44:41 2017 New Revision: 314499 URL: http://llvm.org/viewvc/llvm-project?rev=314499&view=rev Log: [Sema] Suppress warnings for C's zero initializer Patch by S. Gilles! Differential Revision: https://reviews.llvm.org/D28148 Added: cfe/trunk/test/Sema/zero-initializer.c Modified: cfe/trunk/include/clang/AST/Expr.h cfe/trunk/lib/AST/Expr.cpp cfe/trunk/lib/Sema/SemaInit.cpp Modified: cfe/trunk/include/clang/AST/Expr.h URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/AST/Expr.h?rev=314499&r1=314498&r2=314499&view=diff == --- cfe/trunk/include/clang/AST/Expr.h (original) +++ cfe/trunk/include/clang/AST/Expr.h Fri Sep 29 02:44:41 2017 @@ -4011,6 +4011,10 @@ public: /// initializer)? bool isTransparent() const; + /// Is this the zero initializer {0} in a language which considers it + /// idiomatic? + bool isIdiomaticZeroInitializer(const LangOptions &LangOpts) const; + SourceLocation getLBraceLoc() const { return LBraceLoc; } void setLBraceLoc(SourceLocation Loc) { LBraceLoc = Loc; } SourceLocation getRBraceLoc() const { return RBraceLoc; } @@ -4020,6 +4024,9 @@ public: InitListExpr *getSemanticForm() const { return isSemanticForm() ? nullptr : AltForm.getPointer(); } + bool isSyntacticForm() const { +return !AltForm.getInt() || !AltForm.getPointer(); + } InitListExpr *getSyntacticForm() const { return isSemanticForm() ? AltForm.getPointer() : nullptr; } Modified: cfe/trunk/lib/AST/Expr.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/AST/Expr.cpp?rev=314499&r1=314498&r2=314499&view=diff == --- cfe/trunk/lib/AST/Expr.cpp (original) +++ cfe/trunk/lib/AST/Expr.cpp Fri Sep 29 02:44:41 2017 @@ -1951,6 +1951,17 @@ bool InitListExpr::isTransparent() const getInit(0)->getType().getCanonicalType(); } +bool InitListExpr::isIdiomaticZeroInitializer(const LangOptions &LangOpts) const { + assert(isSyntacticForm() && "only test syntactic form as zero initializer"); + + if (LangOpts.CPlusPlus || getNumInits() != 1) { +return false; + } + + const IntegerLiteral *Lit = dyn_cast(getInit(0)); + return Lit && Lit->getValue() == 0; +} + SourceLocation InitListExpr::getLocStart() const { if (InitListExpr *SyntacticForm = getSyntacticForm()) return SyntacticForm->getLocStart(); Modified: cfe/trunk/lib/Sema/SemaInit.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaInit.cpp?rev=314499&r1=314498&r2=314499&view=diff == --- cfe/trunk/lib/Sema/SemaInit.cpp (original) +++ cfe/trunk/lib/Sema/SemaInit.cpp Fri Sep 29 02:44:41 2017 @@ -886,7 +886,8 @@ void InitListChecker::CheckImplicitInitL } // Complain about missing braces. -if (T->isArrayType() || T->isRecordType()) { +if ((T->isArrayType() || T->isRecordType()) && +!ParentIList->isIdiomaticZeroInitializer(SemaRef.getLangOpts())) { SemaRef.Diag(StructuredSubobjectInitList->getLocStart(), diag::warn_missing_braces) << StructuredSubobjectInitList->getSourceRange() @@ -1833,7 +1834,9 @@ void InitListChecker::CheckStructUnionTy // worthwhile to skip over the rest of the initializer, though. RecordDecl *RD = DeclType->getAs()->getDecl(); RecordDecl::field_iterator FieldEnd = RD->field_end(); - bool CheckForMissingFields = true; + bool CheckForMissingFields = +!IList->isIdiomaticZeroInitializer(SemaRef.getLangOpts()); + while (Index < IList->getNumInits()) { Expr *Init = IList->getInit(Index); Added: cfe/trunk/test/Sema/zero-initializer.c URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Sema/zero-initializer.c?rev=314499&view=auto == --- cfe/trunk/test/Sema/zero-initializer.c (added) +++ cfe/trunk/test/Sema/zero-initializer.c Fri Sep 29 02:44:41 2017 @@ -0,0 +1,38 @@ +// RUN: %clang_cc1 -std=c99 -Wmissing-field-initializers -Wmissing-braces -verify %s + +// Tests that using {0} in struct initialization or assignment is supported +struct foo { int x; int y; }; +struct bar { struct foo a; struct foo b; }; +struct A { int a; }; +struct B { struct A a; }; +struct C { struct B b; }; + +int main(void) +{ + struct foo f = { 0 }; // no-warning + struct foo g = { 9 }; // expected-warning {{missing field 'y' initializer}} + struct foo h = { 9, 9 }; // no-warning + struct bar i = { 0 }; // no-warning + struct bar j = { 0, 0 }; // expected-warning {{suggest braces around initialization of subobject}} expected-warning {{missing field 'b' initializer}} + struct bar k = { { 9, 9 }, { 9, 9 } }; // no-warning + struct bar l = { { 9, 9 }, { 0 } }; // no-warning + struct bar m = { { 0 }, { 0 } }; // no-warning + struct
r315462 - [Analyzer] Clarify error messages for undefined result
Author: danielmarjamaki Date: Wed Oct 11 07:49:35 2017 New Revision: 315462 URL: http://llvm.org/viewvc/llvm-project?rev=315462&view=rev Log: [Analyzer] Clarify error messages for undefined result Differential Revision: https://reviews.llvm.org/D30295 Modified: cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h cfe/trunk/lib/StaticAnalyzer/Checkers/ConversionChecker.cpp cfe/trunk/lib/StaticAnalyzer/Checkers/UndefResultChecker.cpp cfe/trunk/lib/StaticAnalyzer/Core/CheckerContext.cpp cfe/trunk/test/Analysis/bitwise-ops.c Modified: cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h?rev=315462&r1=315461&r2=315462&view=diff == --- cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h (original) +++ cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h Wed Oct 11 07:49:35 2017 @@ -196,6 +196,13 @@ public: return getState()->getSVal(S, getLocationContext()); } + /// \brief Returns true if the value of \p E is greater than or equal to \p + /// Val under unsigned comparison + bool isGreaterOrEqual(const Expr *E, unsigned long long Val); + + /// Returns true if the value of \p E is negative. + bool isNegative(const Expr *E); + /// \brief Generates a new transition in the program state graph /// (ExplodedGraph). Uses the default CheckerContext predecessor node. /// Modified: cfe/trunk/lib/StaticAnalyzer/Checkers/ConversionChecker.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Checkers/ConversionChecker.cpp?rev=315462&r1=315461&r2=315462&view=diff == --- cfe/trunk/lib/StaticAnalyzer/Checkers/ConversionChecker.cpp (original) +++ cfe/trunk/lib/StaticAnalyzer/Checkers/ConversionChecker.cpp Wed Oct 11 07:49:35 2017 @@ -123,57 +123,6 @@ void ConversionChecker::reportBug(Explod C.emitReport(std::move(R)); } -// Is E value greater or equal than Val? -static bool isGreaterEqual(CheckerContext &C, const Expr *E, - unsigned long long Val) { - ProgramStateRef State = C.getState(); - SVal EVal = C.getSVal(E); - if (EVal.isUnknownOrUndef()) -return false; - if (!EVal.getAs() && EVal.getAs()) { -ProgramStateManager &Mgr = C.getStateManager(); -EVal = -Mgr.getStoreManager().getBinding(State->getStore(), EVal.castAs()); - } - if (EVal.isUnknownOrUndef() || !EVal.getAs()) -return false; - - SValBuilder &Bldr = C.getSValBuilder(); - DefinedSVal V = Bldr.makeIntVal(Val, C.getASTContext().LongLongTy); - - // Is DefinedEVal greater or equal with V? - SVal GE = Bldr.evalBinOp(State, BO_GE, EVal, V, Bldr.getConditionType()); - if (GE.isUnknownOrUndef()) -return false; - ConstraintManager &CM = C.getConstraintManager(); - ProgramStateRef StGE, StLT; - std::tie(StGE, StLT) = CM.assumeDual(State, GE.castAs()); - return StGE && !StLT; -} - -// Is E value negative? -static bool isNegative(CheckerContext &C, const Expr *E) { - ProgramStateRef State = C.getState(); - SVal EVal = State->getSVal(E, C.getLocationContext()); - if (EVal.isUnknownOrUndef() || !EVal.getAs()) -return false; - DefinedSVal DefinedEVal = EVal.castAs(); - - SValBuilder &Bldr = C.getSValBuilder(); - DefinedSVal V = Bldr.makeIntVal(0, false); - - SVal LT = - Bldr.evalBinOp(State, BO_LT, DefinedEVal, V, Bldr.getConditionType()); - - // Is E value greater than MaxVal? - ConstraintManager &CM = C.getConstraintManager(); - ProgramStateRef StNegative, StPositive; - std::tie(StNegative, StPositive) = - CM.assumeDual(State, LT.castAs()); - - return StNegative && !StPositive; -} - bool ConversionChecker::isLossOfPrecision(const ImplicitCastExpr *Cast, QualType DestType, CheckerContext &C) const { @@ -195,18 +144,18 @@ bool ConversionChecker::isLossOfPrecisio return false; unsigned long long MaxVal = 1ULL << W; - return isGreaterEqual(C, Cast->getSubExpr(), MaxVal); + return C.isGreaterOrEqual(Cast->getSubExpr(), MaxVal); } bool ConversionChecker::isLossOfSign(const ImplicitCastExpr *Cast, - CheckerContext &C) const { + CheckerContext &C) const { QualType CastType = Cast->getType(); QualType SubType = Cast->IgnoreParenImpCasts()->getType(); if (!CastType->isUnsignedIntegerType() || !SubType->isSignedIntegerType()) return false; - return isNegative(C, Cast->getSubExpr()); + return C.isNegative(Cast->getSubExpr()); } void ento::registerConversionChecker(CheckerManager &mgr) { Modified: cfe/trunk/lib/StaticAnalyzer/Checkers/UndefResultChecker.cpp URL: http://llv
r305669 - [analyzer] Fix logical not for pointers with different bit width
Author: danielmarjamaki Date: Mon Jun 19 03:55:51 2017 New Revision: 305669 URL: http://llvm.org/viewvc/llvm-project?rev=305669&view=rev Log: [analyzer] Fix logical not for pointers with different bit width Differential Revision: https://reviews.llvm.org/D31029 Modified: cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/BasicValueFactory.h cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h cfe/trunk/lib/StaticAnalyzer/Core/ExprEngineC.cpp Modified: cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/BasicValueFactory.h URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/BasicValueFactory.h?rev=305669&r1=305668&r2=305669&view=diff == --- cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/BasicValueFactory.h (original) +++ cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/BasicValueFactory.h Mon Jun 19 03:55:51 2017 @@ -180,6 +180,11 @@ public: return getValue(X); } + inline const llvm::APSInt& getZeroWithTypeSize(QualType T) { +assert(T->isScalarType()); +return getValue(0, Ctx.getTypeSize(T), true); + } + inline const llvm::APSInt& getZeroWithPtrWidth(bool isUnsigned = true) { return getValue(0, Ctx.getTypeSize(Ctx.VoidPtrTy), isUnsigned); } Modified: cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h?rev=305669&r1=305668&r2=305669&view=diff == --- cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h (original) +++ cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h Mon Jun 19 03:55:51 2017 @@ -315,6 +315,13 @@ public: return nonloc::ConcreteInt(BasicVals.getTruthValue(b)); } + /// Create NULL pointer, with proper pointer bit-width for given address + /// space. + /// \param type pointer type. + Loc makeNullWithType(QualType type) { +return loc::ConcreteInt(BasicVals.getZeroWithTypeSize(type)); + } + Loc makeNull() { return loc::ConcreteInt(BasicVals.getZeroWithPtrWidth()); } Modified: cfe/trunk/lib/StaticAnalyzer/Core/ExprEngineC.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Core/ExprEngineC.cpp?rev=305669&r1=305668&r2=305669&view=diff == --- cfe/trunk/lib/StaticAnalyzer/Core/ExprEngineC.cpp (original) +++ cfe/trunk/lib/StaticAnalyzer/Core/ExprEngineC.cpp Mon Jun 19 03:55:51 2017 @@ -980,10 +980,9 @@ void ExprEngine::VisitUnaryOperator(cons //transfer functions as "0 == E". SVal Result; if (Optional LV = V.getAs()) { -Loc X = svalBuilder.makeNull(); +Loc X = svalBuilder.makeNullWithType(Ex->getType()); Result = evalBinOp(state, BO_EQ, *LV, X, U->getType()); - } - else if (Ex->getType()->isFloatingType()) { + } else if (Ex->getType()->isFloatingType()) { // FIXME: handle floating point types. Result = UnknownVal(); } else { ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] r311984 - [clang-tidy] Fix 'misc-misplaced-widening-cast' assertion error.
Author: danielmarjamaki Date: Mon Aug 28 23:25:24 2017 New Revision: 311984 URL: http://llvm.org/viewvc/llvm-project?rev=311984&view=rev Log: [clang-tidy] Fix 'misc-misplaced-widening-cast' assertion error. Reviewers: alexfh, xazax.hun, danielmarjamaki Differential Revision: http://reviews.llvm.org/D36670 Modified: clang-tools-extra/trunk/clang-tidy/misc/MisplacedWideningCastCheck.cpp clang-tools-extra/trunk/test/clang-tidy/misc-misplaced-widening-cast-explicit-only.cpp Modified: clang-tools-extra/trunk/clang-tidy/misc/MisplacedWideningCastCheck.cpp URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/misc/MisplacedWideningCastCheck.cpp?rev=311984&r1=311983&r2=311984&view=diff == --- clang-tools-extra/trunk/clang-tidy/misc/MisplacedWideningCastCheck.cpp (original) +++ clang-tools-extra/trunk/clang-tidy/misc/MisplacedWideningCastCheck.cpp Mon Aug 28 23:25:24 2017 @@ -192,6 +192,10 @@ void MisplacedWideningCastCheck::check(c if (Calc->getLocStart().isMacroID()) return; + if (Cast->isTypeDependent() || Cast->isValueDependent() || + Calc->isTypeDependent() || Calc->isValueDependent()) +return; + ASTContext &Context = *Result.Context; QualType CastType = Cast->getType(); Modified: clang-tools-extra/trunk/test/clang-tidy/misc-misplaced-widening-cast-explicit-only.cpp URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/test/clang-tidy/misc-misplaced-widening-cast-explicit-only.cpp?rev=311984&r1=311983&r2=311984&view=diff == --- clang-tools-extra/trunk/test/clang-tidy/misc-misplaced-widening-cast-explicit-only.cpp (original) +++ clang-tools-extra/trunk/test/clang-tidy/misc-misplaced-widening-cast-explicit-only.cpp Mon Aug 28 23:25:24 2017 @@ -56,3 +56,9 @@ long ret(int a) { return (long)a * 1000; } } + +// Shall not generate an assert. https://bugs.llvm.org/show_bug.cgi?id=33660 +template class A { + enum Type {}; + static char *m_fn1() { char p = (Type)(&p - m_fn1()); } +}; ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
r282156 - Fix Wbitfield-constant-conversion false positives
Author: danielmarjamaki Date: Thu Sep 22 09:13:46 2016 New Revision: 282156 URL: http://llvm.org/viewvc/llvm-project?rev=282156&view=rev Log: Fix Wbitfield-constant-conversion false positives Summary: The diagnostic did not handle ~ well. An expression such as ~0 is often used when 'all ones' is needed. Differential Revision: https://reviews.llvm.org/D24232 Modified: cfe/trunk/lib/Sema/SemaChecking.cpp cfe/trunk/test/Sema/constant-conversion.c Modified: cfe/trunk/lib/Sema/SemaChecking.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaChecking.cpp?rev=282156&r1=282155&r2=282156&view=diff == --- cfe/trunk/lib/Sema/SemaChecking.cpp (original) +++ cfe/trunk/lib/Sema/SemaChecking.cpp Thu Sep 22 09:13:46 2016 @@ -8006,11 +8006,10 @@ bool AnalyzeBitFieldAssignment(Sema &S, unsigned OriginalWidth = Value.getBitWidth(); unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context); - if (Value.isSigned() && Value.isNegative()) + if (!Value.isSigned() || Value.isNegative()) if (UnaryOperator *UO = dyn_cast(OriginalInit)) - if (UO->getOpcode() == UO_Minus) -if (isa(UO->getSubExpr())) - OriginalWidth = Value.getMinSignedBits(); + if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not) +OriginalWidth = Value.getMinSignedBits(); if (OriginalWidth <= FieldWidth) return false; Modified: cfe/trunk/test/Sema/constant-conversion.c URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Sema/constant-conversion.c?rev=282156&r1=282155&r2=282156&view=diff == --- cfe/trunk/test/Sema/constant-conversion.c (original) +++ cfe/trunk/test/Sema/constant-conversion.c Thu Sep 22 09:13:46 2016 @@ -69,7 +69,8 @@ void test7() { unsigned int reserved:28; } f; - f.twoBits1 = ~1; // expected-warning {{implicit truncation from 'int' to bitfield changes value from -2 to 2}} + f.twoBits1 = ~0; // no-warning + f.twoBits1 = ~1; // no-warning f.twoBits2 = ~2; // expected-warning {{implicit truncation from 'int' to bitfield changes value from -3 to 1}} f.twoBits1 &= ~1; // no-warning f.twoBits2 &= ~2; // no-warning @@ -114,6 +115,8 @@ void test9() { char array_init[] = { 255, 127, 128, 129, 0 }; } +#define A 1 + void test10() { struct S { unsigned a : 4; @@ -121,7 +124,10 @@ void test10() { s.a = -1; s.a = 15; s.a = -8; + s.a = ~0; + s.a = ~0U; + s.a = ~(1
r282233 - Fix indentation
Author: danielmarjamaki Date: Fri Sep 23 03:27:24 2016 New Revision: 282233 URL: http://llvm.org/viewvc/llvm-project?rev=282233&view=rev Log: Fix indentation Modified: cfe/trunk/test/Sema/constant-conversion.c Modified: cfe/trunk/test/Sema/constant-conversion.c URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Sema/constant-conversion.c?rev=282233&r1=282232&r2=282233&view=diff == --- cfe/trunk/test/Sema/constant-conversion.c (original) +++ cfe/trunk/test/Sema/constant-conversion.c Fri Sep 23 03:27:24 2016 @@ -128,6 +128,6 @@ void test10() { s.a = ~0U; s.a = ~(1
r282242 - Minor tweak. Avoid hardcoding.
Author: danielmarjamaki Date: Fri Sep 23 07:23:44 2016 New Revision: 282242 URL: http://llvm.org/viewvc/llvm-project?rev=282242&view=rev Log: Minor tweak. Avoid hardcoding. Modified: cfe/trunk/lib/Frontend/InitPreprocessor.cpp Modified: cfe/trunk/lib/Frontend/InitPreprocessor.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Frontend/InitPreprocessor.cpp?rev=282242&r1=282241&r2=282242&view=diff == --- cfe/trunk/lib/Frontend/InitPreprocessor.cpp (original) +++ cfe/trunk/lib/Frontend/InitPreprocessor.cpp Fri Sep 23 07:23:44 2016 @@ -673,7 +673,7 @@ static void InitializePredefinedMacros(c // Define type sizing macros based on the target properties. assert(TI.getCharWidth() == 8 && "Only support 8-bit char so far"); - Builder.defineMacro("__CHAR_BIT__", "8"); + Builder.defineMacro("__CHAR_BIT__", Twine(TI.getCharWidth())); DefineTypeSize("__SCHAR_MAX__", TargetInfo::SignedChar, TI, Builder); DefineTypeSize("__SHRT_MAX__", TargetInfo::SignedShort, TI, Builder); ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
r282411 - [analyzer] Improve CastToStruct checker so it can also detect widening casts of struct data
Author: danielmarjamaki Date: Mon Sep 26 10:17:18 2016 New Revision: 282411 URL: http://llvm.org/viewvc/llvm-project?rev=282411&view=rev Log: [analyzer] Improve CastToStruct checker so it can also detect widening casts of struct data Example: struct AB { int A; int B; }; struct ABC { int A; int B; int C; }; void f() { struct AB Data; struct ABC *P = (struct ABC *)&Data; } Differential Revision: https://reviews.llvm.org/D23508 Added: cfe/trunk/test/Analysis/cast-to-struct.cpp Modified: cfe/trunk/lib/StaticAnalyzer/Checkers/CastToStructChecker.cpp cfe/trunk/test/Analysis/casts.c Modified: cfe/trunk/lib/StaticAnalyzer/Checkers/CastToStructChecker.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Checkers/CastToStructChecker.cpp?rev=282411&r1=282410&r2=282411&view=diff == --- cfe/trunk/lib/StaticAnalyzer/Checkers/CastToStructChecker.cpp (original) +++ cfe/trunk/lib/StaticAnalyzer/Checkers/CastToStructChecker.cpp Mon Sep 26 10:17:18 2016 @@ -1,4 +1,4 @@ -//=== CastToStructChecker.cpp - Fixed address usage checker *- C++ -*--===// +//=== CastToStructChecker.cpp --*- C++ -*--===// // // The LLVM Compiler Infrastructure // @@ -8,12 +8,13 @@ //===--===// // // This files defines CastToStructChecker, a builtin checker that checks for -// cast from non-struct pointer to struct pointer. +// cast from non-struct pointer to struct pointer and widening struct data cast. // This check corresponds to CWE-588. // //===--===// #include "ClangSACheckers.h" +#include "clang/AST/RecursiveASTVisitor.h" #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h" #include "clang/StaticAnalyzer/Core/Checker.h" #include "clang/StaticAnalyzer/Core/CheckerManager.h" @@ -23,18 +24,22 @@ using namespace clang; using namespace ento; namespace { -class CastToStructChecker : public Checker< check::PreStmt > { - mutable std::unique_ptr BT; +class CastToStructVisitor : public RecursiveASTVisitor { + BugReporter &BR; + const CheckerBase *Checker; + AnalysisDeclContext *AC; public: - void checkPreStmt(const CastExpr *CE, CheckerContext &C) const; + explicit CastToStructVisitor(BugReporter &B, const CheckerBase *Checker, + AnalysisDeclContext *A) + : BR(B), Checker(Checker), AC(A) {} + bool VisitCastExpr(const CastExpr *CE); }; } -void CastToStructChecker::checkPreStmt(const CastExpr *CE, - CheckerContext &C) const { +bool CastToStructVisitor::VisitCastExpr(const CastExpr *CE) { const Expr *E = CE->getSubExpr(); - ASTContext &Ctx = C.getASTContext(); + ASTContext &Ctx = AC->getASTContext(); QualType OrigTy = Ctx.getCanonicalType(E->getType()); QualType ToTy = Ctx.getCanonicalType(CE->getType()); @@ -42,34 +47,72 @@ void CastToStructChecker::checkPreStmt(c const PointerType *ToPTy = dyn_cast(ToTy.getTypePtr()); if (!ToPTy || !OrigPTy) -return; +return true; QualType OrigPointeeTy = OrigPTy->getPointeeType(); QualType ToPointeeTy = ToPTy->getPointeeType(); if (!ToPointeeTy->isStructureOrClassType()) -return; +return true; // We allow cast from void*. if (OrigPointeeTy->isVoidType()) -return; +return true; // Now the cast-to-type is struct pointer, the original type is not void*. if (!OrigPointeeTy->isRecordType()) { -if (ExplodedNode *N = C.generateNonFatalErrorNode()) { - if (!BT) -BT.reset( -new BuiltinBug(this, "Cast from non-struct type to struct type", - "Casting a non-structure type to a structure type " - "and accessing a field can lead to memory access " - "errors or data corruption.")); - auto R = llvm::make_unique(*BT, BT->getDescription(), N); - R->addRange(CE->getSourceRange()); - C.emitReport(std::move(R)); -} +SourceRange Sr[1] = {CE->getSourceRange()}; +PathDiagnosticLocation Loc(CE, BR.getSourceManager(), AC); +BR.EmitBasicReport( +AC->getDecl(), Checker, "Cast from non-struct type to struct type", +categories::LogicError, "Casting a non-structure type to a structure " +"type and accessing a field can lead to memory " +"access errors or data corruption.", +Loc, Sr); + } else { +// Don't warn when size of data is unknown. +const auto *U = dyn_cast(E); +if (!U || U->getOpcode() != UO_AddrOf) + return true; + +// Don't warn for references +const ValueDecl *VD = nullptr; +if (const auto *SE = dyn_cast(U->getSubExpr())) + VD = dyn_cast(SE->getDecl()); +else if (const aut
r282574 - [StaticAnalyzer] Fix false positives for vardecls that are technically unreachable but they are needed.
Author: danielmarjamaki Date: Wed Sep 28 05:39:53 2016 New Revision: 282574 URL: http://llvm.org/viewvc/llvm-project?rev=282574&view=rev Log: [StaticAnalyzer] Fix false positives for vardecls that are technically unreachable but they are needed. Example: switch (x) { int a; // <- This is unreachable but needed case 1: a = ... Differential Revision: https://reviews.llvm.org/D24905 Modified: cfe/trunk/lib/StaticAnalyzer/Checkers/UnreachableCodeChecker.cpp cfe/trunk/test/Analysis/unreachable-code-path.c Modified: cfe/trunk/lib/StaticAnalyzer/Checkers/UnreachableCodeChecker.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Checkers/UnreachableCodeChecker.cpp?rev=282574&r1=282573&r2=282574&view=diff == --- cfe/trunk/lib/StaticAnalyzer/Checkers/UnreachableCodeChecker.cpp (original) +++ cfe/trunk/lib/StaticAnalyzer/Checkers/UnreachableCodeChecker.cpp Wed Sep 28 05:39:53 2016 @@ -191,8 +191,10 @@ void UnreachableCodeChecker::FindUnreach // Find the Stmt* in a CFGBlock for reporting a warning const Stmt *UnreachableCodeChecker::getUnreachableStmt(const CFGBlock *CB) { for (CFGBlock::const_iterator I = CB->begin(), E = CB->end(); I != E; ++I) { -if (Optional S = I->getAs()) - return S->getStmt(); +if (Optional S = I->getAs()) { + if (!isa(S->getStmt())) +return S->getStmt(); +} } if (const Stmt *S = CB->getTerminator()) return S; Modified: cfe/trunk/test/Analysis/unreachable-code-path.c URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analysis/unreachable-code-path.c?rev=282574&r1=282573&r2=282574&view=diff == --- cfe/trunk/test/Analysis/unreachable-code-path.c (original) +++ cfe/trunk/test/Analysis/unreachable-code-path.c Wed Sep 28 05:39:53 2016 @@ -158,3 +158,18 @@ void testInlined() { } } } + +// Don't warn about unreachable VarDecl. +void dostuff(int*A); +void varDecl(int X) { + switch (X) { +int A; // No warning here. + case 1: +dostuff(&A); +break; + case 2: +dostuff(&A); +break; + } +} + ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
r283095 - [StaticAnalyzer] Fix UnreachableCode false positives.
Author: danielmarjamaki Date: Mon Oct 3 03:28:51 2016 New Revision: 283095 URL: http://llvm.org/viewvc/llvm-project?rev=283095&view=rev Log: [StaticAnalyzer] Fix UnreachableCode false positives. When there is 'do { } while (0);' in the code the ExplodedGraph and UnoptimizedCFG did not match. Differential Revision: https://reviews.llvm.org/D24759 Modified: cfe/trunk/lib/Analysis/CFG.cpp cfe/trunk/test/Analysis/unreachable-code-path.c Modified: cfe/trunk/lib/Analysis/CFG.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Analysis/CFG.cpp?rev=283095&r1=283094&r2=283095&view=diff == --- cfe/trunk/lib/Analysis/CFG.cpp (original) +++ cfe/trunk/lib/Analysis/CFG.cpp Mon Oct 3 03:28:51 2016 @@ -2983,20 +2983,19 @@ CFGBlock *CFGBuilder::VisitDoStmt(DoStmt return nullptr; } -if (!KnownVal.isFalse()) { - // Add an intermediate block between the BodyBlock and the - // ExitConditionBlock to represent the "loop back" transition. Create an - // empty block to represent the transition block for looping back to the - // head of the loop. - // FIXME: Can we do this more efficiently without adding another block? - Block = nullptr; - Succ = BodyBlock; - CFGBlock *LoopBackBlock = createBlock(); - LoopBackBlock->setLoopTarget(D); +// Add an intermediate block between the BodyBlock and the +// ExitConditionBlock to represent the "loop back" transition. Create an +// empty block to represent the transition block for looping back to the +// head of the loop. +// FIXME: Can we do this more efficiently without adding another block? +Block = nullptr; +Succ = BodyBlock; +CFGBlock *LoopBackBlock = createBlock(); +LoopBackBlock->setLoopTarget(D); +if (!KnownVal.isFalse()) // Add the loop body entry as a successor to the condition. addSuccessor(ExitConditionBlock, LoopBackBlock); -} else addSuccessor(ExitConditionBlock, nullptr); } Modified: cfe/trunk/test/Analysis/unreachable-code-path.c URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analysis/unreachable-code-path.c?rev=283095&r1=283094&r2=283095&view=diff == --- cfe/trunk/test/Analysis/unreachable-code-path.c (original) +++ cfe/trunk/test/Analysis/unreachable-code-path.c Mon Oct 3 03:28:51 2016 @@ -173,3 +173,13 @@ void varDecl(int X) { } } +// Ensure that ExplodedGraph and unoptimized CFG match. +void test12(int x) { + switch (x) { + case 1: +break; // not unreachable + case 2: +do { } while (0); +break; + } +} ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
r283096 - [StaticAnalyser] Add test case to ensure that unreachable code is found.
Author: danielmarjamaki Date: Mon Oct 3 04:45:35 2016 New Revision: 283096 URL: http://llvm.org/viewvc/llvm-project?rev=283096&view=rev Log: [StaticAnalyser] Add test case to ensure that unreachable code is found. https://reviews.llvm.org/D24905 Modified: cfe/trunk/test/Analysis/unreachable-code-path.c Modified: cfe/trunk/test/Analysis/unreachable-code-path.c URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analysis/unreachable-code-path.c?rev=283096&r1=283095&r2=283096&view=diff == --- cfe/trunk/test/Analysis/unreachable-code-path.c (original) +++ cfe/trunk/test/Analysis/unreachable-code-path.c Mon Oct 3 04:45:35 2016 @@ -161,12 +161,23 @@ void testInlined() { // Don't warn about unreachable VarDecl. void dostuff(int*A); -void varDecl(int X) { +void varDecl1(int X) { switch (X) { int A; // No warning here. case 1: dostuff(&A); break; + case 2: +dostuff(&A); +break; + } +} +void varDecl2(int X) { + switch (X) { +int A=1; // expected-warning {{never executed}} + case 1: +dostuff(&A); +break; case 2: dostuff(&A); break; ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
r283554 - [analyzer] Don't merge different return nodes in ExplodedGraph
Author: danielmarjamaki Date: Fri Oct 7 09:21:08 2016 New Revision: 283554 URL: http://llvm.org/viewvc/llvm-project?rev=283554&view=rev Log: [analyzer] Don't merge different return nodes in ExplodedGraph Returns when calling an inline function should not be merged in the ExplodedGraph unless they are same. Differential Revision: https://reviews.llvm.org/D25326 Modified: cfe/trunk/include/clang/Analysis/ProgramPoint.h cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/CoreEngine.h cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/SubEngine.h cfe/trunk/lib/StaticAnalyzer/Core/CoreEngine.cpp cfe/trunk/lib/StaticAnalyzer/Core/ExprEngine.cpp cfe/trunk/test/Analysis/inlining/InlineObjCClassMethod.m cfe/trunk/test/Analysis/unreachable-code-path.c Modified: cfe/trunk/include/clang/Analysis/ProgramPoint.h URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Analysis/ProgramPoint.h?rev=283554&r1=283553&r2=283554&view=diff == --- cfe/trunk/include/clang/Analysis/ProgramPoint.h (original) +++ cfe/trunk/include/clang/Analysis/ProgramPoint.h Fri Oct 7 09:21:08 2016 @@ -622,8 +622,8 @@ private: class CallExitBegin : public ProgramPoint { public: // CallExitBegin uses the callee's location context. - CallExitBegin(const StackFrameContext *L) -: ProgramPoint(nullptr, CallExitBeginKind, L, nullptr) {} + CallExitBegin(const StackFrameContext *L, const ReturnStmt *RS) +: ProgramPoint(RS, CallExitBeginKind, L, nullptr) { } private: friend class ProgramPoint; Modified: cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/CoreEngine.h URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/CoreEngine.h?rev=283554&r1=283553&r2=283554&view=diff == --- cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/CoreEngine.h (original) +++ cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/CoreEngine.h Fri Oct 7 09:21:08 2016 @@ -109,7 +109,8 @@ private: CoreEngine(const CoreEngine &) = delete; void operator=(const CoreEngine &) = delete; - ExplodedNode *generateCallExitBeginNode(ExplodedNode *N); + ExplodedNode *generateCallExitBeginNode(ExplodedNode *N, + const ReturnStmt *RS); public: /// Construct a CoreEngine object to analyze the provided CFG. @@ -172,7 +173,7 @@ public: /// \brief enqueue the nodes corresponding to the end of function onto the /// end of path / work list. - void enqueueEndOfFunction(ExplodedNodeSet &Set); + void enqueueEndOfFunction(ExplodedNodeSet &Set, const ReturnStmt *RS); /// \brief Enqueue a single node created as a result of statement processing. void enqueueStmtNode(ExplodedNode *N, const CFGBlock *Block, unsigned Idx); Modified: cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h?rev=283554&r1=283553&r2=283554&view=diff == --- cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h (original) +++ cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h Fri Oct 7 09:21:08 2016 @@ -262,7 +262,8 @@ public: /// Called by CoreEngine. Used to notify checkers that processing a /// function has ended. Called for both inlined and and top-level functions. void processEndOfFunction(NodeBuilderContext& BC, -ExplodedNode *Pred) override; +ExplodedNode *Pred, +const ReturnStmt *RS=nullptr) override; /// Remove dead bindings/symbols before exiting a function. void removeDeadOnEndOfFunction(NodeBuilderContext& BC, Modified: cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/SubEngine.h URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/SubEngine.h?rev=283554&r1=283553&r2=283554&view=diff == --- cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/SubEngine.h (original) +++ cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/SubEngine.h Fri Oct 7 09:21:08 2016 @@ -109,7 +109,8 @@ public: /// Called by CoreEngine. Used to notify checkers that processing a /// function has ended. Called for both inlined and and top-level functions. virtual void processEndOfFunction(NodeBuilderContext& BC, -ExplodedNode *Pred) = 0; +ExplodedNode *Pred, +const ReturnStmt *RS = nullptr) = 0; // Genera
r283725 - Fix style issue. Spaces in argument list.
Author: danielmarjamaki Date: Mon Oct 10 02:39:39 2016 New Revision: 283725 URL: http://llvm.org/viewvc/llvm-project?rev=283725&view=rev Log: Fix style issue. Spaces in argument list. Modified: cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h Modified: cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h?rev=283725&r1=283724&r2=283725&view=diff == --- cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h (original) +++ cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h Mon Oct 10 02:39:39 2016 @@ -263,7 +263,7 @@ public: /// function has ended. Called for both inlined and and top-level functions. void processEndOfFunction(NodeBuilderContext& BC, ExplodedNode *Pred, -const ReturnStmt *RS=nullptr) override; +const ReturnStmt *RS = nullptr) override; /// Remove dead bindings/symbols before exiting a function. void removeDeadOnEndOfFunction(NodeBuilderContext& BC, ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
r309799 - [StaticAnalyzer] Fix false positives for unreachable code in macros.
Author: danielmarjamaki Date: Wed Aug 2 01:26:56 2017 New Revision: 309799 URL: http://llvm.org/viewvc/llvm-project?rev=309799&view=rev Log: [StaticAnalyzer] Fix false positives for unreachable code in macros. Example: #define MACRO(C) if (C) { static int x; .. } void foo() { MACRO(0); } Differential Revision: https://reviews.llvm.org/D36141 Modified: cfe/trunk/lib/StaticAnalyzer/Checkers/UnreachableCodeChecker.cpp cfe/trunk/test/Analysis/unreachable-code-path.c Modified: cfe/trunk/lib/StaticAnalyzer/Checkers/UnreachableCodeChecker.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Checkers/UnreachableCodeChecker.cpp?rev=309799&r1=309798&r2=309799&view=diff == --- cfe/trunk/lib/StaticAnalyzer/Checkers/UnreachableCodeChecker.cpp (original) +++ cfe/trunk/lib/StaticAnalyzer/Checkers/UnreachableCodeChecker.cpp Wed Aug 2 01:26:56 2017 @@ -112,7 +112,7 @@ void UnreachableCodeChecker::checkEndAna continue; // Check for false positives -if (CB->size() > 0 && isInvalidPath(CB, *PM)) +if (isInvalidPath(CB, *PM)) continue; // It is good practice to always have a "default" label in a "switch", even Modified: cfe/trunk/test/Analysis/unreachable-code-path.c URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analysis/unreachable-code-path.c?rev=309799&r1=309798&r2=309799&view=diff == --- cfe/trunk/test/Analysis/unreachable-code-path.c (original) +++ cfe/trunk/test/Analysis/unreachable-code-path.c Wed Aug 2 01:26:56 2017 @@ -213,3 +213,13 @@ void macro(void) { RETURN(1); // no-warning } +// Avoid FP when macro argument is known +void writeSomething(int *x); +#define MACRO(C)\ + if (!C) { \ +static int x; \ +writeSomething(&x); \ + } +void macro2(void) { + MACRO(1); +} ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] r279507 - [clang-tidy] readability-non-const-parameter: add new check that warns when function parameters should be const
Author: danielmarjamaki Date: Tue Aug 23 05:09:08 2016 New Revision: 279507 URL: http://llvm.org/viewvc/llvm-project?rev=279507&view=rev Log: [clang-tidy] readability-non-const-parameter: add new check that warns when function parameters should be const The check will warn when the constness will make the function interface safer. Reviewers: alexfh Subscribers: cfe-commits Differential Revision: https://reviews.llvm.org/D15332 Added: clang-tools-extra/trunk/clang-tidy/readability/NonConstParameterCheck.cpp clang-tools-extra/trunk/clang-tidy/readability/NonConstParameterCheck.h clang-tools-extra/trunk/docs/clang-tidy/checks/readability-non-const-parameter.rst clang-tools-extra/trunk/test/clang-tidy/readability-non-const-parameter.cpp Modified: clang-tools-extra/trunk/clang-tidy/readability/CMakeLists.txt clang-tools-extra/trunk/clang-tidy/readability/ReadabilityTidyModule.cpp clang-tools-extra/trunk/docs/ReleaseNotes.rst clang-tools-extra/trunk/docs/clang-tidy/checks/list.rst Modified: clang-tools-extra/trunk/clang-tidy/readability/CMakeLists.txt URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/readability/CMakeLists.txt?rev=279507&r1=279506&r2=279507&view=diff == --- clang-tools-extra/trunk/clang-tidy/readability/CMakeLists.txt (original) +++ clang-tools-extra/trunk/clang-tidy/readability/CMakeLists.txt Tue Aug 23 05:09:08 2016 @@ -12,6 +12,7 @@ add_clang_library(clangTidyReadabilityMo InconsistentDeclarationParameterNameCheck.cpp NamedParameterCheck.cpp NamespaceCommentCheck.cpp + NonConstParameterCheck.cpp ReadabilityTidyModule.cpp RedundantControlFlowCheck.cpp RedundantStringCStrCheck.cpp Added: clang-tools-extra/trunk/clang-tidy/readability/NonConstParameterCheck.cpp URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/readability/NonConstParameterCheck.cpp?rev=279507&view=auto == --- clang-tools-extra/trunk/clang-tidy/readability/NonConstParameterCheck.cpp (added) +++ clang-tools-extra/trunk/clang-tidy/readability/NonConstParameterCheck.cpp Tue Aug 23 05:09:08 2016 @@ -0,0 +1,214 @@ +//===--- NonConstParameterCheck.cpp - clang-tidy---===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===--===// + +#include "NonConstParameterCheck.h" +#include "clang/AST/ASTContext.h" +#include "clang/ASTMatchers/ASTMatchFinder.h" + +using namespace clang::ast_matchers; + +namespace clang { +namespace tidy { +namespace readability { + +void NonConstParameterCheck::registerMatchers(MatchFinder *Finder) { + // Add parameters to Parameters. + Finder->addMatcher(parmVarDecl(unless(isInstantiated())).bind("Parm"), this); + + // C++ constructor. + Finder->addMatcher(cxxConstructorDecl().bind("Ctor"), this); + + // Track unused parameters, there is Wunused-parameter about unused + // parameters. + Finder->addMatcher(declRefExpr().bind("Ref"), this); + + // Analyse parameter usage in function. + Finder->addMatcher(stmt(anyOf(unaryOperator(anyOf(hasOperatorName("++"), +hasOperatorName("--"))), +binaryOperator(), callExpr(), returnStmt(), +cxxConstructExpr())) + .bind("Mark"), + this); + Finder->addMatcher(varDecl(hasInitializer(anything())).bind("Mark"), this); +} + +void NonConstParameterCheck::check(const MatchFinder::MatchResult &Result) { + if (const auto *Parm = Result.Nodes.getNodeAs("Parm")) { +if (const DeclContext *D = Parm->getParentFunctionOrMethod()) { + if (const auto *M = dyn_cast(D)) { +if (M->isVirtual() || M->size_overridden_methods() != 0) + return; + } +} +addParm(Parm); + } else if (const auto *Ctor = + Result.Nodes.getNodeAs("Ctor")) { +for (const auto *Parm : Ctor->parameters()) + addParm(Parm); +for (const auto *Init : Ctor->inits()) + markCanNotBeConst(Init->getInit(), true); + } else if (const auto *Ref = Result.Nodes.getNodeAs("Ref")) { +setReferenced(Ref); + } else if (const auto *S = Result.Nodes.getNodeAs("Mark")) { +if (const auto *B = dyn_cast(S)) { + if (B->isAssignmentOp()) +markCanNotBeConst(B, false); +} else if (const auto *CE = dyn_cast(S)) { + // Typically, if a parameter is const then it is fine to make the data + // const. But sometimes the data is written even though the parameter + // is const. Mark all data passed by address to the function. + for (const auto *Arg : CE->arguments()) { +markCanNot
[clang-tools-extra] r281206 - [clang-tidy] readability-misplaced-array-index: add new check that warns when array index is misplaced.
Author: danielmarjamaki Date: Mon Sep 12 07:04:13 2016 New Revision: 281206 URL: http://llvm.org/viewvc/llvm-project?rev=281206&view=rev Log: [clang-tidy] readability-misplaced-array-index: add new check that warns when array index is misplaced. Reviewers: alexfh Differential Revision: https://reviews.llvm.org/D21134 Added: clang-tools-extra/trunk/clang-tidy/readability/MisplacedArrayIndexCheck.cpp clang-tools-extra/trunk/clang-tidy/readability/MisplacedArrayIndexCheck.h clang-tools-extra/trunk/docs/clang-tidy/checks/readability-misplaced-array-index.rst clang-tools-extra/trunk/test/clang-tidy/readability-misplaced-array-index.cpp Modified: clang-tools-extra/trunk/clang-tidy/readability/CMakeLists.txt clang-tools-extra/trunk/clang-tidy/readability/ReadabilityTidyModule.cpp clang-tools-extra/trunk/docs/ReleaseNotes.rst clang-tools-extra/trunk/docs/clang-tidy/checks/list.rst Modified: clang-tools-extra/trunk/clang-tidy/readability/CMakeLists.txt URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/readability/CMakeLists.txt?rev=281206&r1=281205&r2=281206&view=diff == --- clang-tools-extra/trunk/clang-tidy/readability/CMakeLists.txt (original) +++ clang-tools-extra/trunk/clang-tidy/readability/CMakeLists.txt Mon Sep 12 07:04:13 2016 @@ -10,6 +10,7 @@ add_clang_library(clangTidyReadabilityMo IdentifierNamingCheck.cpp ImplicitBoolCastCheck.cpp InconsistentDeclarationParameterNameCheck.cpp + MisplacedArrayIndexCheck.cpp NamedParameterCheck.cpp NamespaceCommentCheck.cpp NonConstParameterCheck.cpp Added: clang-tools-extra/trunk/clang-tidy/readability/MisplacedArrayIndexCheck.cpp URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/readability/MisplacedArrayIndexCheck.cpp?rev=281206&view=auto == --- clang-tools-extra/trunk/clang-tidy/readability/MisplacedArrayIndexCheck.cpp (added) +++ clang-tools-extra/trunk/clang-tidy/readability/MisplacedArrayIndexCheck.cpp Mon Sep 12 07:04:13 2016 @@ -0,0 +1,57 @@ +//===--- MisplacedArrayIndexCheck.cpp - clang-tidy-===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===--===// + +#include "MisplacedArrayIndexCheck.h" +#include "clang/AST/ASTContext.h" +#include "clang/ASTMatchers/ASTMatchFinder.h" +#include "clang/Lex/Lexer.h" +#include "clang/Tooling/FixIt.h" + +using namespace clang::ast_matchers; + +namespace clang { +namespace tidy { +namespace readability { + +void MisplacedArrayIndexCheck::registerMatchers(MatchFinder *Finder) { + Finder->addMatcher(arraySubscriptExpr(hasLHS(hasType(isInteger())), +hasRHS(hasType(isAnyPointer( + .bind("expr"), + this); +} + +void MisplacedArrayIndexCheck::check(const MatchFinder::MatchResult &Result) { + const auto *ArraySubscriptE = + Result.Nodes.getNodeAs("expr"); + + auto Diag = diag(ArraySubscriptE->getLocStart(), "confusing array subscript " + "expression, usually the " + "index is inside the []"); + + // Only try to fixit when LHS and RHS can be swapped directly without changing + // the logic. + const Expr *RHSE = ArraySubscriptE->getRHS()->IgnoreParenImpCasts(); + if (!isa(RHSE) && !isa(RHSE) && + !isa(RHSE)) +return; + + const StringRef LText = tooling::fixit::getText( + ArraySubscriptE->getLHS()->getSourceRange(), *Result.Context); + const StringRef RText = tooling::fixit::getText( + ArraySubscriptE->getRHS()->getSourceRange(), *Result.Context); + + Diag << FixItHint::CreateReplacement( + ArraySubscriptE->getLHS()->getSourceRange(), RText); + Diag << FixItHint::CreateReplacement( + ArraySubscriptE->getRHS()->getSourceRange(), LText); +} + +} // namespace readability +} // namespace tidy +} // namespace clang Added: clang-tools-extra/trunk/clang-tidy/readability/MisplacedArrayIndexCheck.h URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/readability/MisplacedArrayIndexCheck.h?rev=281206&view=auto == --- clang-tools-extra/trunk/clang-tidy/readability/MisplacedArrayIndexCheck.h (added) +++ clang-tools-extra/trunk/clang-tidy/readability/MisplacedArrayIndexCheck.h Mon Sep 12 07:04:13 2016 @@ -0,0 +1,36 @@ +//===--- MisplacedArrayIndexCheck.h - clang-tidy-*- C++ -*-===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illino
r299523 - [analyzer] alpha.core.Conversion - Fix false positive for 'U32 += S16; ' expression, that is not unsafe
Author: danielmarjamaki Date: Wed Apr 5 03:57:04 2017 New Revision: 299523 URL: http://llvm.org/viewvc/llvm-project?rev=299523&view=rev Log: [analyzer] alpha.core.Conversion - Fix false positive for 'U32 += S16;' expression, that is not unsafe Summary: The alpha.core.Conversion was too strict about compound assignments and could warn even though there is no problem. Differential Revision: https://reviews.llvm.org/D25596 Modified: cfe/trunk/lib/StaticAnalyzer/Checkers/ConversionChecker.cpp cfe/trunk/test/Analysis/conversion.c Modified: cfe/trunk/lib/StaticAnalyzer/Checkers/ConversionChecker.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Checkers/ConversionChecker.cpp?rev=299523&r1=299522&r2=299523&view=diff == --- cfe/trunk/lib/StaticAnalyzer/Checkers/ConversionChecker.cpp (original) +++ cfe/trunk/lib/StaticAnalyzer/Checkers/ConversionChecker.cpp Wed Apr 5 03:57:04 2017 @@ -41,7 +41,8 @@ private: mutable std::unique_ptr BT; // Is there loss of precision - bool isLossOfPrecision(const ImplicitCastExpr *Cast, CheckerContext &C) const; + bool isLossOfPrecision(const ImplicitCastExpr *Cast, QualType DestType, + CheckerContext &C) const; // Is there loss of sign bool isLossOfSign(const ImplicitCastExpr *Cast, CheckerContext &C) const; @@ -73,16 +74,30 @@ void ConversionChecker::checkPreStmt(con // Loss of sign/precision in binary operation. if (const auto *B = dyn_cast(Parent)) { BinaryOperator::Opcode Opc = B->getOpcode(); -if (Opc == BO_Assign || Opc == BO_AddAssign || Opc == BO_SubAssign || -Opc == BO_MulAssign) { +if (Opc == BO_Assign) { LossOfSign = isLossOfSign(Cast, C); - LossOfPrecision = isLossOfPrecision(Cast, C); + LossOfPrecision = isLossOfPrecision(Cast, Cast->getType(), C); +} else if (Opc == BO_AddAssign || Opc == BO_SubAssign) { + // No loss of sign. + LossOfPrecision = isLossOfPrecision(Cast, B->getLHS()->getType(), C); +} else if (Opc == BO_MulAssign) { + LossOfSign = isLossOfSign(Cast, C); + LossOfPrecision = isLossOfPrecision(Cast, B->getLHS()->getType(), C); +} else if (Opc == BO_DivAssign || Opc == BO_RemAssign) { + LossOfSign = isLossOfSign(Cast, C); + // No loss of precision. +} else if (Opc == BO_AndAssign) { + LossOfSign = isLossOfSign(Cast, C); + // No loss of precision. +} else if (Opc == BO_OrAssign || Opc == BO_XorAssign) { + LossOfSign = isLossOfSign(Cast, C); + LossOfPrecision = isLossOfPrecision(Cast, B->getLHS()->getType(), C); } else if (B->isRelationalOp() || B->isMultiplicativeOp()) { LossOfSign = isLossOfSign(Cast, C); } } else if (isa(Parent)) { LossOfSign = isLossOfSign(Cast, C); -LossOfPrecision = isLossOfPrecision(Cast, C); +LossOfPrecision = isLossOfPrecision(Cast, Cast->getType(), C); } if (LossOfSign || LossOfPrecision) { @@ -113,6 +128,13 @@ static bool isGreaterEqual(CheckerContex unsigned long long Val) { ProgramStateRef State = C.getState(); SVal EVal = C.getSVal(E); + if (EVal.isUnknownOrUndef()) +return false; + if (!EVal.getAs() && EVal.getAs()) { +ProgramStateManager &Mgr = C.getStateManager(); +EVal = +Mgr.getStoreManager().getBinding(State->getStore(), EVal.castAs()); + } if (EVal.isUnknownOrUndef() || !EVal.getAs()) return false; @@ -153,22 +175,22 @@ static bool isNegative(CheckerContext &C } bool ConversionChecker::isLossOfPrecision(const ImplicitCastExpr *Cast, -CheckerContext &C) const { + QualType DestType, + CheckerContext &C) const { // Don't warn about explicit loss of precision. if (Cast->isEvaluatable(C.getASTContext())) return false; - QualType CastType = Cast->getType(); QualType SubType = Cast->IgnoreParenImpCasts()->getType(); - if (!CastType->isIntegerType() || !SubType->isIntegerType()) + if (!DestType->isIntegerType() || !SubType->isIntegerType()) return false; - if (C.getASTContext().getIntWidth(CastType) >= + if (C.getASTContext().getIntWidth(DestType) >= C.getASTContext().getIntWidth(SubType)) return false; - unsigned W = C.getASTContext().getIntWidth(CastType); + unsigned W = C.getASTContext().getIntWidth(DestType); if (W == 1 || W >= 64U) return false; Modified: cfe/trunk/test/Analysis/conversion.c URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analysis/conversion.c?rev=299523&r1=299522&r2=299523&view=diff == --- cfe/trunk/test/Analysis/conversion.c (original) +++ cfe/trunk/test/Analysis/conversion.c Wed Apr 5 03:57:04 2017 @@ -9,9 +9,67 @@ void assign(unsigned U, signed S) { if (U > 30
r295545 - [analyzer] Fix crash in CastToStruct when there is no record definition
Author: danielmarjamaki Date: Sat Feb 18 05:18:57 2017 New Revision: 295545 URL: http://llvm.org/viewvc/llvm-project?rev=295545&view=rev Log: [analyzer] Fix crash in CastToStruct when there is no record definition This crash was reported in https://bugs.llvm.org//show_bug.cgi?id=31173 Differential Revision: https://reviews.llvm.org/D28297 Modified: cfe/trunk/lib/StaticAnalyzer/Checkers/CastToStructChecker.cpp cfe/trunk/test/Analysis/cast-to-struct.cpp Modified: cfe/trunk/lib/StaticAnalyzer/Checkers/CastToStructChecker.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Checkers/CastToStructChecker.cpp?rev=295545&r1=295544&r2=295545&view=diff == --- cfe/trunk/lib/StaticAnalyzer/Checkers/CastToStructChecker.cpp (original) +++ cfe/trunk/lib/StaticAnalyzer/Checkers/CastToStructChecker.cpp Sat Feb 18 05:18:57 2017 @@ -84,6 +84,13 @@ bool CastToStructVisitor::VisitCastExpr( if (!VD || VD->getType()->isReferenceType()) return true; +// Don't warn when target type has no definition. +if (const RecordType *RD = dyn_cast(ToPointeeTy.getTypePtr())) { + if (!RD->getDecl()->getDefinition()) { +return true; + } +} + // Warn when there is widening cast. unsigned ToWidth = Ctx.getTypeInfo(ToPointeeTy).Width; unsigned OrigWidth = Ctx.getTypeInfo(OrigPointeeTy).Width; Modified: cfe/trunk/test/Analysis/cast-to-struct.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analysis/cast-to-struct.cpp?rev=295545&r1=295544&r2=295545&view=diff == --- cfe/trunk/test/Analysis/cast-to-struct.cpp (original) +++ cfe/trunk/test/Analysis/cast-to-struct.cpp Sat Feb 18 05:18:57 2017 @@ -65,3 +65,8 @@ void intToStruct(int *P) { void *VP = P; Abc = (struct ABC *)VP; } + +// https://llvm.org/bugs/show_bug.cgi?id=31173 +void dontCrash(struct AB X) { + struct UndefS *S = (struct UndefS *)&X; +} ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
r295548 - [analyzer] Revert 295545. There are buildbot failures.
Author: danielmarjamaki Date: Sat Feb 18 10:31:35 2017 New Revision: 295548 URL: http://llvm.org/viewvc/llvm-project?rev=295548&view=rev Log: [analyzer] Revert 295545. There are buildbot failures. Modified: cfe/trunk/lib/StaticAnalyzer/Checkers/CastToStructChecker.cpp cfe/trunk/test/Analysis/cast-to-struct.cpp Modified: cfe/trunk/lib/StaticAnalyzer/Checkers/CastToStructChecker.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Checkers/CastToStructChecker.cpp?rev=295548&r1=295547&r2=295548&view=diff == --- cfe/trunk/lib/StaticAnalyzer/Checkers/CastToStructChecker.cpp (original) +++ cfe/trunk/lib/StaticAnalyzer/Checkers/CastToStructChecker.cpp Sat Feb 18 10:31:35 2017 @@ -84,13 +84,6 @@ bool CastToStructVisitor::VisitCastExpr( if (!VD || VD->getType()->isReferenceType()) return true; -// Don't warn when target type has no definition. -if (const RecordType *RD = dyn_cast(ToPointeeTy.getTypePtr())) { - if (!RD->getDecl()->getDefinition()) { -return true; - } -} - // Warn when there is widening cast. unsigned ToWidth = Ctx.getTypeInfo(ToPointeeTy).Width; unsigned OrigWidth = Ctx.getTypeInfo(OrigPointeeTy).Width; Modified: cfe/trunk/test/Analysis/cast-to-struct.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analysis/cast-to-struct.cpp?rev=295548&r1=295547&r2=295548&view=diff == --- cfe/trunk/test/Analysis/cast-to-struct.cpp (original) +++ cfe/trunk/test/Analysis/cast-to-struct.cpp Sat Feb 18 10:31:35 2017 @@ -65,8 +65,3 @@ void intToStruct(int *P) { void *VP = P; Abc = (struct ABC *)VP; } - -// https://llvm.org/bugs/show_bug.cgi?id=31173 -void dontCrash(struct AB X) { - struct UndefS *S = (struct UndefS *)&X; -} ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] r296100 - [clang-tidy] Fix readability-redundant-declaration false positive
Author: danielmarjamaki Date: Fri Feb 24 03:02:44 2017 New Revision: 296100 URL: http://llvm.org/viewvc/llvm-project?rev=296100&view=rev Log: [clang-tidy] Fix readability-redundant-declaration false positive Differential Revision: https://reviews.llvm.org/D27048 Modified: clang-tools-extra/trunk/clang-tidy/readability/RedundantDeclarationCheck.cpp clang-tools-extra/trunk/test/clang-tidy/readability-redundant-declaration.cpp Modified: clang-tools-extra/trunk/clang-tidy/readability/RedundantDeclarationCheck.cpp URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/readability/RedundantDeclarationCheck.cpp?rev=296100&r1=296099&r2=296100&view=diff == --- clang-tools-extra/trunk/clang-tidy/readability/RedundantDeclarationCheck.cpp (original) +++ clang-tools-extra/trunk/clang-tidy/readability/RedundantDeclarationCheck.cpp Fri Feb 24 03:02:44 2017 @@ -19,7 +19,10 @@ namespace tidy { namespace readability { void RedundantDeclarationCheck::registerMatchers(MatchFinder *Finder) { - Finder->addMatcher(namedDecl(anyOf(varDecl(), functionDecl())).bind("Decl"), + auto UnlessDefinition = unless(isDefinition()); + Finder->addMatcher(namedDecl(anyOf(varDecl(UnlessDefinition), + functionDecl(UnlessDefinition))) + .bind("Decl"), this); } @@ -41,9 +44,6 @@ void RedundantDeclarationCheck::check(co bool MultiVar = false; if (const auto *VD = dyn_cast(D)) { -if (VD->getPreviousDecl()->getStorageClass() == SC_Extern && -VD->getStorageClass() != SC_Extern) - return; // Is this a multivariable declaration? for (const auto Other : VD->getDeclContext()->decls()) { if (Other != D && Other->getLocStart() == VD->getLocStart()) { @@ -51,10 +51,6 @@ void RedundantDeclarationCheck::check(co break; } } - } else { -const auto *FD = cast(D); -if (FD->isThisDeclarationADefinition()) - return; } SourceLocation EndLoc = Lexer::getLocForEndOfToken( Modified: clang-tools-extra/trunk/test/clang-tidy/readability-redundant-declaration.cpp URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/test/clang-tidy/readability-redundant-declaration.cpp?rev=296100&r1=296099&r2=296100&view=diff == --- clang-tools-extra/trunk/test/clang-tidy/readability-redundant-declaration.cpp (original) +++ clang-tools-extra/trunk/test/clang-tidy/readability-redundant-declaration.cpp Fri Feb 24 03:02:44 2017 @@ -1,9 +1,9 @@ // RUN: %check_clang_tidy %s readability-redundant-declaration %t extern int Xyz; -extern int Xyz; +extern int Xyz; // Xyz // CHECK-MESSAGES: :[[@LINE-1]]:12: warning: redundant 'Xyz' declaration [readability-redundant-declaration] -// CHECK-FIXES: {{^}}{{$}} +// CHECK-FIXES: {{^}}// Xyz{{$}} int Xyz = 123; extern int A; @@ -12,19 +12,25 @@ extern int A, B; // CHECK-FIXES: {{^}}extern int A, B;{{$}} extern int Buf[10]; -extern int Buf[10]; +extern int Buf[10]; // Buf[10] // CHECK-MESSAGES: :[[@LINE-1]]:12: warning: redundant 'Buf' declaration -// CHECK-FIXES: {{^}}{{$}} +// CHECK-FIXES: {{^}}// Buf[10]{{$}} static int f(); -static int f(); +static int f(); // f // CHECK-MESSAGES: :[[@LINE-1]]:12: warning: redundant 'f' declaration -// CHECK-FIXES: {{^}}{{$}} +// CHECK-FIXES: {{^}}// f{{$}} static int f() {} // Original check crashed for the code below. namespace std { - typedef decltype(sizeof(0)) size_t; +typedef decltype(sizeof(0)) size_t; } -void* operator new(std::size_t) __attribute__((__externally_visible__)); -void* operator new[](std::size_t) __attribute__((__externally_visible__)); +void *operator new(std::size_t) __attribute__((__externally_visible__)); +void *operator new[](std::size_t) __attribute__((__externally_visible__)); + +// Don't warn about static member definition. +struct C { + static int I; +}; +int C::I; ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
r296326 - [analyzer] clarify 'result is garbage value' when it is out of bounds
Author: danielmarjamaki Date: Mon Feb 27 04:44:24 2017 New Revision: 296326 URL: http://llvm.org/viewvc/llvm-project?rev=296326&view=rev Log: [analyzer] clarify 'result is garbage value' when it is out of bounds Differential Revision: https://reviews.llvm.org/D28278 Modified: cfe/trunk/lib/StaticAnalyzer/Checkers/UndefResultChecker.cpp cfe/trunk/test/Analysis/uninit-vals-ps.c Modified: cfe/trunk/lib/StaticAnalyzer/Checkers/UndefResultChecker.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Checkers/UndefResultChecker.cpp?rev=296326&r1=296325&r2=296326&view=diff == --- cfe/trunk/lib/StaticAnalyzer/Checkers/UndefResultChecker.cpp (original) +++ cfe/trunk/lib/StaticAnalyzer/Checkers/UndefResultChecker.cpp Mon Feb 27 04:44:24 2017 @@ -35,6 +35,30 @@ public: }; } // end anonymous namespace +static bool isArrayIndexOutOfBounds(CheckerContext &C, const Expr *Ex) { + ProgramStateRef state = C.getState(); + const LocationContext *LCtx = C.getLocationContext(); + + if (!isa(Ex)) +return false; + + SVal Loc = state->getSVal(Ex, LCtx); + if (!Loc.isValid()) +return false; + + const MemRegion *MR = Loc.castAs().getRegion(); + const ElementRegion *ER = dyn_cast(MR); + if (!ER) +return false; + + DefinedOrUnknownSVal Idx = ER->getIndex().castAs(); + DefinedOrUnknownSVal NumElements = C.getStoreManager().getSizeInElements( + state, ER->getSuperRegion(), ER->getValueType()); + ProgramStateRef StInBound = state->assumeInBound(Idx, NumElements, true); + ProgramStateRef StOutBound = state->assumeInBound(Idx, NumElements, false); + return StOutBound && !StInBound; +} + void UndefResultChecker::checkPostStmt(const BinaryOperator *B, CheckerContext &C) const { ProgramStateRef state = C.getState(); @@ -77,6 +101,8 @@ void UndefResultChecker::checkPostStmt(c << " operand of '" << BinaryOperator::getOpcodeStr(B->getOpcode()) << "' is a garbage value"; + if (isArrayIndexOutOfBounds(C, Ex)) +OS << " due to array index out of bounds"; } else { // Neither operand was undefined, but the result is undefined. Modified: cfe/trunk/test/Analysis/uninit-vals-ps.c URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analysis/uninit-vals-ps.c?rev=296326&r1=296325&r2=296326&view=diff == --- cfe/trunk/test/Analysis/uninit-vals-ps.c (original) +++ cfe/trunk/test/Analysis/uninit-vals-ps.c Mon Feb 27 04:44:24 2017 @@ -57,6 +57,12 @@ int f5(void) { return s.x; // no-warning } +void f6(int x) { + int a[20]; + if (x == 25) {} + if (a[x] == 123) {} // expected-warning{{The left operand of '==' is a garbage value due to array index out of bounds}} +} + int ret_uninit() { int i; int *p = &i; ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
r296477 - [Sema] Detect more array index out of bounds when C++ overloaded operators are used
Author: danielmarjamaki Date: Tue Feb 28 08:53:50 2017 New Revision: 296477 URL: http://llvm.org/viewvc/llvm-project?rev=296477&view=rev Log: [Sema] Detect more array index out of bounds when C++ overloaded operators are used Differential Revision: https://reviews.llvm.org/D30192 Modified: cfe/trunk/lib/Sema/SemaChecking.cpp cfe/trunk/test/SemaCXX/array-bounds.cpp Modified: cfe/trunk/lib/Sema/SemaChecking.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaChecking.cpp?rev=296477&r1=296476&r2=296477&view=diff == --- cfe/trunk/lib/Sema/SemaChecking.cpp (original) +++ cfe/trunk/lib/Sema/SemaChecking.cpp Tue Feb 28 08:53:50 2017 @@ -10609,6 +10609,12 @@ void Sema::CheckArrayAccess(const Expr * CheckArrayAccess(rhs); return; } + case Stmt::CXXOperatorCallExprClass: { +const auto *OCE = cast(expr); +for (const auto *Arg : OCE->arguments()) + CheckArrayAccess(Arg); +return; + } default: return; } Modified: cfe/trunk/test/SemaCXX/array-bounds.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/test/SemaCXX/array-bounds.cpp?rev=296477&r1=296476&r2=296477&view=diff == --- cfe/trunk/test/SemaCXX/array-bounds.cpp (original) +++ cfe/trunk/test/SemaCXX/array-bounds.cpp Tue Feb 28 08:53:50 2017 @@ -1,4 +1,4 @@ -// RUN: %clang_cc1 -verify %s +// RUN: %clang_cc1 -verify -std=c++11 %s int foo() { int x[2]; // expected-note 4 {{array 'x' declared here}} @@ -253,3 +253,19 @@ void test_rdar10916006(void) int a[128]; // expected-note {{array 'a' declared here}} a[(unsigned char)'\xA1'] = 1; // expected-warning {{array index 161 is past the end of the array}} } + +struct P { + int a; + int b; +}; + +void test_struct_array_index() { + struct P p[10]; // expected-note {{array 'p' declared here}} + p[11] = {0, 1}; // expected-warning {{array index 11 is past the end of the array (which contains 10 elements)}} +} + +int operator+(const struct P &s1, const struct P &s2); +int test_operator_overload_struct_array_index() { + struct P x[10] = {0}; // expected-note {{array 'x' declared here}} + return x[1] + x[11]; // expected-warning {{array index 11 is past the end of the array (which contains 10 elements)}} +} ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
r297187 - [analyzer] Fix crashes in CastToStruct checker for undefined structs
Author: danielmarjamaki Date: Tue Mar 7 13:20:48 2017 New Revision: 297187 URL: http://llvm.org/viewvc/llvm-project?rev=297187&view=rev Log: [analyzer] Fix crashes in CastToStruct checker for undefined structs This crash was reported in https://bugs.llvm.org//show_bug.cgi?id=31173 Differential Revision: https://reviews.llvm.org/D28297 Modified: cfe/trunk/lib/StaticAnalyzer/Checkers/CastToStructChecker.cpp cfe/trunk/test/Analysis/cast-to-struct.cpp Modified: cfe/trunk/lib/StaticAnalyzer/Checkers/CastToStructChecker.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Checkers/CastToStructChecker.cpp?rev=297187&r1=297186&r2=297187&view=diff == --- cfe/trunk/lib/StaticAnalyzer/Checkers/CastToStructChecker.cpp (original) +++ cfe/trunk/lib/StaticAnalyzer/Checkers/CastToStructChecker.cpp Tue Mar 7 13:20:48 2017 @@ -84,6 +84,10 @@ bool CastToStructVisitor::VisitCastExpr( if (!VD || VD->getType()->isReferenceType()) return true; +if (ToPointeeTy->isIncompleteType() || +OrigPointeeTy->isIncompleteType()) + return true; + // Warn when there is widening cast. unsigned ToWidth = Ctx.getTypeInfo(ToPointeeTy).Width; unsigned OrigWidth = Ctx.getTypeInfo(OrigPointeeTy).Width; Modified: cfe/trunk/test/Analysis/cast-to-struct.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analysis/cast-to-struct.cpp?rev=297187&r1=297186&r2=297187&view=diff == --- cfe/trunk/test/Analysis/cast-to-struct.cpp (original) +++ cfe/trunk/test/Analysis/cast-to-struct.cpp Tue Mar 7 13:20:48 2017 @@ -65,3 +65,17 @@ void intToStruct(int *P) { void *VP = P; Abc = (struct ABC *)VP; } + +// https://llvm.org/bugs/show_bug.cgi?id=31173 +void dontCrash1(struct AB X) { + struct UndefS *S = (struct UndefS *)&X; +} + +struct S; +struct T { + struct S *P; +}; +extern struct S Var1, Var2; +void dontCrash2() { + ((struct T *) &Var1)->P = &Var2; +} ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
r297283 - [analyzer] Clarify 'uninitialized function argument' messages
Author: danielmarjamaki Date: Wed Mar 8 09:22:24 2017 New Revision: 297283 URL: http://llvm.org/viewvc/llvm-project?rev=297283&view=rev Log: [analyzer] Clarify 'uninitialized function argument' messages Differential Revision: https://reviews.llvm.org/D30341 Modified: cfe/trunk/lib/StaticAnalyzer/Checkers/CallAndMessageChecker.cpp cfe/trunk/test/Analysis/NewDelete-checker-test.cpp cfe/trunk/test/Analysis/diagnostics/undef-value-param.m cfe/trunk/test/Analysis/malloc.m cfe/trunk/test/Analysis/misc-ps-region-store.m cfe/trunk/test/Analysis/misc-ps.m cfe/trunk/test/Analysis/null-deref-ps.c cfe/trunk/test/Analysis/nullptr.cpp cfe/trunk/test/Analysis/uninit-const.c cfe/trunk/test/Analysis/uninit-const.cpp cfe/trunk/test/Analysis/uninit-msg-expr.m cfe/trunk/test/Analysis/uninit-vals-ps.c cfe/trunk/test/Analysis/uninit-vals.cpp Modified: cfe/trunk/lib/StaticAnalyzer/Checkers/CallAndMessageChecker.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Checkers/CallAndMessageChecker.cpp?rev=297283&r1=297282&r2=297283&view=diff == --- cfe/trunk/lib/StaticAnalyzer/Checkers/CallAndMessageChecker.cpp (original) +++ cfe/trunk/lib/StaticAnalyzer/Checkers/CallAndMessageChecker.cpp Wed Mar 8 09:22:24 2017 @@ -21,6 +21,7 @@ #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h" #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h" #include "llvm/ADT/SmallString.h" +#include "llvm/ADT/StringExtras.h" #include "llvm/Support/raw_ostream.h" using namespace clang; @@ -71,7 +72,7 @@ public: private: bool PreVisitProcessArg(CheckerContext &C, SVal V, SourceRange ArgRange, - const Expr *ArgEx, bool IsFirstArgument, + const Expr *ArgEx, int ArgumentNumber, bool CheckUninitFields, const CallEvent &Call, std::unique_ptr &BT, const ParmVarDecl *ParamDecl) const; @@ -89,9 +90,10 @@ private: BT.reset(new BuiltinBug(this, desc)); } bool uninitRefOrPointer(CheckerContext &C, const SVal &V, - SourceRange ArgRange, - const Expr *ArgEx, std::unique_ptr &BT, - const ParmVarDecl *ParamDecl, const char *BD) const; + SourceRange ArgRange, const Expr *ArgEx, + std::unique_ptr &BT, + const ParmVarDecl *ParamDecl, const char *BD, + int ArgumentNumber) const; }; } // end anonymous namespace @@ -111,38 +113,45 @@ void CallAndMessageChecker::emitBadCall( C.emitReport(std::move(R)); } -static StringRef describeUninitializedArgumentInCall(const CallEvent &Call, - bool IsFirstArgument) { +static void describeUninitializedArgumentInCall(const CallEvent &Call, +int ArgumentNumber, +llvm::raw_svector_ostream &Os) { switch (Call.getKind()) { case CE_ObjCMessage: { const ObjCMethodCall &Msg = cast(Call); switch (Msg.getMessageKind()) { case OCM_Message: - return "Argument in message expression is an uninitialized value"; + Os << (ArgumentNumber + 1) << llvm::getOrdinalSuffix(ArgumentNumber + 1) + << " argument in message expression is an uninitialized value"; + return; case OCM_PropertyAccess: assert(Msg.isSetter() && "Getters have no args"); - return "Argument for property setter is an uninitialized value"; + Os << "Argument for property setter is an uninitialized value"; + return; case OCM_Subscript: - if (Msg.isSetter() && IsFirstArgument) -return "Argument for subscript setter is an uninitialized value"; - return "Subscript index is an uninitialized value"; + if (Msg.isSetter() && (ArgumentNumber == 0)) +Os << "Argument for subscript setter is an uninitialized value"; + else +Os << "Subscript index is an uninitialized value"; + return; } llvm_unreachable("Unknown message kind."); } case CE_Block: -return "Block call argument is an uninitialized value"; +Os << (ArgumentNumber + 1) << llvm::getOrdinalSuffix(ArgumentNumber + 1) + << " block call argument is an uninitialized value"; +return; default: -return "Function call argument is an uninitialized value"; +Os << (ArgumentNumber + 1) << llvm::getOrdinalSuffix(ArgumentNumber + 1) + << " function call argument is an uninitialized value"; +return; } } -bool CallAndMessageChecker::uninitRefOrPointer(CheckerContext &C, - const SVal &V, - SourceRange ArgRange, -
[clang-tools-extra] r287540 - readability-redundant-declaration: Fix crash
Author: danielmarjamaki Date: Mon Nov 21 08:29:53 2016 New Revision: 287540 URL: http://llvm.org/viewvc/llvm-project?rev=287540&view=rev Log: readability-redundant-declaration: Fix crash Differential Revision: https://reviews.llvm.org/D26911 Modified: clang-tools-extra/trunk/clang-tidy/readability/RedundantDeclarationCheck.cpp clang-tools-extra/trunk/test/clang-tidy/readability-redundant-declaration.cpp Modified: clang-tools-extra/trunk/clang-tidy/readability/RedundantDeclarationCheck.cpp URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/readability/RedundantDeclarationCheck.cpp?rev=287540&r1=287539&r2=287540&view=diff == --- clang-tools-extra/trunk/clang-tidy/readability/RedundantDeclarationCheck.cpp (original) +++ clang-tools-extra/trunk/clang-tidy/readability/RedundantDeclarationCheck.cpp Mon Nov 21 08:29:53 2016 @@ -28,6 +28,8 @@ void RedundantDeclarationCheck::check(co const auto *Prev = D->getPreviousDecl(); if (!Prev) return; + if (!Prev->getLocation().isValid()) +return; if (Prev->getLocation() == D->getLocation()) return; Modified: clang-tools-extra/trunk/test/clang-tidy/readability-redundant-declaration.cpp URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/test/clang-tidy/readability-redundant-declaration.cpp?rev=287540&r1=287539&r2=287540&view=diff == --- clang-tools-extra/trunk/test/clang-tidy/readability-redundant-declaration.cpp (original) +++ clang-tools-extra/trunk/test/clang-tidy/readability-redundant-declaration.cpp Mon Nov 21 08:29:53 2016 @@ -21,3 +21,10 @@ static int f(); // CHECK-MESSAGES: :[[@LINE-1]]:12: warning: redundant 'f' declaration // CHECK-FIXES: {{^}}{{$}} static int f() {} + +// Original check crashed for the code below. +namespace std { + typedef long unsigned int size_t; +} +void* operator new(std::size_t) __attribute__((__externally_visible__)); +void* operator new[](std::size_t) __attribute__((__externally_visible__)); ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] r287546 - clang-tidy: Attempt to fix build bot failure with mismatching size_t platform type.
Author: danielmarjamaki Date: Mon Nov 21 09:46:40 2016 New Revision: 287546 URL: http://llvm.org/viewvc/llvm-project?rev=287546&view=rev Log: clang-tidy: Attempt to fix build bot failure with mismatching size_t platform type. Modified: clang-tools-extra/trunk/test/clang-tidy/readability-redundant-declaration.cpp Modified: clang-tools-extra/trunk/test/clang-tidy/readability-redundant-declaration.cpp URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/test/clang-tidy/readability-redundant-declaration.cpp?rev=287546&r1=287545&r2=287546&view=diff == --- clang-tools-extra/trunk/test/clang-tidy/readability-redundant-declaration.cpp (original) +++ clang-tools-extra/trunk/test/clang-tidy/readability-redundant-declaration.cpp Mon Nov 21 09:46:40 2016 @@ -1,4 +1,4 @@ -// RUN: %check_clang_tidy %s readability-redundant-declaration %t +// RUN: %check_clang_tidy %s readability-redundant-declaration %t -- -- -target x86_64-unknown-unknown extern int Xyz; extern int Xyz; ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] r287550 - clang-tidy: improve my test for readability-redundant-declaration
Author: danielmarjamaki Date: Mon Nov 21 10:08:17 2016 New Revision: 287550 URL: http://llvm.org/viewvc/llvm-project?rev=287550&view=rev Log: clang-tidy: improve my test for readability-redundant-declaration Modified: clang-tools-extra/trunk/test/clang-tidy/readability-redundant-declaration.cpp Modified: clang-tools-extra/trunk/test/clang-tidy/readability-redundant-declaration.cpp URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/test/clang-tidy/readability-redundant-declaration.cpp?rev=287550&r1=287549&r2=287550&view=diff == --- clang-tools-extra/trunk/test/clang-tidy/readability-redundant-declaration.cpp (original) +++ clang-tools-extra/trunk/test/clang-tidy/readability-redundant-declaration.cpp Mon Nov 21 10:08:17 2016 @@ -1,4 +1,4 @@ -// RUN: %check_clang_tidy %s readability-redundant-declaration %t -- -- -target x86_64-unknown-unknown +// RUN: %check_clang_tidy %s readability-redundant-declaration %t extern int Xyz; extern int Xyz; @@ -24,7 +24,7 @@ static int f() {} // Original check crashed for the code below. namespace std { - typedef long unsigned int size_t; + typedef decltype(sizeof(0)) size_t; } void* operator new(std::size_t) __attribute__((__externally_visible__)); void* operator new[](std::size_t) __attribute__((__externally_visible__)); ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
r301913 - [analyzer] Detect bad free of function pointers
Author: danielmarjamaki Date: Tue May 2 06:46:12 2017 New Revision: 301913 URL: http://llvm.org/viewvc/llvm-project?rev=301913&view=rev Log: [analyzer] Detect bad free of function pointers Differential Revision: https://reviews.llvm.org/D31650 Modified: cfe/trunk/lib/StaticAnalyzer/Checkers/MallocChecker.cpp cfe/trunk/test/Analysis/malloc.c Modified: cfe/trunk/lib/StaticAnalyzer/Checkers/MallocChecker.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Checkers/MallocChecker.cpp?rev=301913&r1=301912&r2=301913&view=diff == --- cfe/trunk/lib/StaticAnalyzer/Checkers/MallocChecker.cpp (original) +++ cfe/trunk/lib/StaticAnalyzer/Checkers/MallocChecker.cpp Tue May 2 06:46:12 2017 @@ -401,6 +401,9 @@ private: void ReportUseZeroAllocated(CheckerContext &C, SourceRange Range, SymbolRef Sym) const; + void ReportFunctionPointerFree(CheckerContext &C, SVal ArgVal, + SourceRange Range, const Expr *FreeExpr) const; + /// Find the location of the allocation for Sym on the path leading to the /// exploded node N. LeakInfo getAllocationSite(const ExplodedNode *N, SymbolRef Sym, @@ -1564,6 +1567,11 @@ ProgramStateRef MallocChecker::FreeMemAu } } + if (SymBase->getType()->isFunctionPointerType()) { +ReportFunctionPointerFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr); +return nullptr; + } + ReleasedAllocated = (RsBase != nullptr) && (RsBase->isAllocated() || RsBase->isAllocatedOfSizeZero()); @@ -2024,10 +2032,45 @@ void MallocChecker::ReportUseZeroAllocat } } +void MallocChecker::ReportFunctionPointerFree(CheckerContext &C, SVal ArgVal, + SourceRange Range, + const Expr *FreeExpr) const { + if (!ChecksEnabled[CK_MallocChecker]) +return; + + Optional CheckKind = getCheckIfTracked(C, FreeExpr); + if (!CheckKind.hasValue()) +return; + + if (ExplodedNode *N = C.generateErrorNode()) { +if (!BT_BadFree[*CheckKind]) + BT_BadFree[*CheckKind].reset( + new BugType(CheckNames[*CheckKind], "Bad free", "Memory Error")); + +SmallString<100> Buf; +llvm::raw_svector_ostream Os(Buf); + +const MemRegion *MR = ArgVal.getAsRegion(); +while (const ElementRegion *ER = dyn_cast_or_null(MR)) + MR = ER->getSuperRegion(); + +Os << "Argument to "; +if (!printAllocDeallocName(Os, C, FreeExpr)) + Os << "deallocator"; + +Os << " is a function pointer"; + +auto R = llvm::make_unique(*BT_BadFree[*CheckKind], Os.str(), N); +R->markInteresting(MR); +R->addRange(Range); +C.emitReport(std::move(R)); + } +} + ProgramStateRef MallocChecker::ReallocMemAux(CheckerContext &C, const CallExpr *CE, bool FreesOnFail, - ProgramStateRef State, + ProgramStateRef State, bool SuffixWithN) const { if (!State) return nullptr; Modified: cfe/trunk/test/Analysis/malloc.c URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analysis/malloc.c?rev=301913&r1=301912&r2=301913&view=diff == --- cfe/trunk/test/Analysis/malloc.c (original) +++ cfe/trunk/test/Analysis/malloc.c Tue May 2 06:46:12 2017 @@ -1774,6 +1774,16 @@ int testNoCheckerDataPropogationFromLogi return ok; // no warning } +void (*fnptr)(int); +void freeIndirectFunctionPtr() { + void *p = (void *)fnptr; + free(p); // expected-warning {{Argument to free() is a function pointer}} +} + +void freeFunctionPtr() { + free((void *)fnptr); // expected-warning {{Argument to free() is a function pointer}} +} + // // False negatives. ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
r284477 - alpha.core.UnreachableCode - don't warn about unreachable code inside macro
Author: danielmarjamaki Date: Tue Oct 18 08:16:53 2016 New Revision: 284477 URL: http://llvm.org/viewvc/llvm-project?rev=284477&view=rev Log: alpha.core.UnreachableCode - don't warn about unreachable code inside macro In macros, 'do {...} while (0)' is often used. Don't warn about the condition 0 when it is unreachable. Differential Revision: https://reviews.llvm.org/D25606 Modified: cfe/trunk/lib/StaticAnalyzer/Checkers/UnreachableCodeChecker.cpp cfe/trunk/test/Analysis/unreachable-code-path.c Modified: cfe/trunk/lib/StaticAnalyzer/Checkers/UnreachableCodeChecker.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Checkers/UnreachableCodeChecker.cpp?rev=284477&r1=284476&r2=284477&view=diff == --- cfe/trunk/lib/StaticAnalyzer/Checkers/UnreachableCodeChecker.cpp (original) +++ cfe/trunk/lib/StaticAnalyzer/Checkers/UnreachableCodeChecker.cpp Tue Oct 18 08:16:53 2016 @@ -147,6 +147,14 @@ void UnreachableCodeChecker::checkEndAna PathDiagnosticLocation DL; SourceLocation SL; if (const Stmt *S = getUnreachableStmt(CB)) { + // In macros, 'do {...} while (0)' is often used. Don't warn about the + // condition 0 when it is unreachable. + if (S->getLocStart().isMacroID()) +if (const auto *I = dyn_cast(S)) + if (I->getValue() == 0ULL) +if (const Stmt *Parent = PM->getParent(S)) + if (isa(Parent)) +continue; SR = S->getSourceRange(); DL = PathDiagnosticLocation::createBegin(S, B.getSourceManager(), LC); SL = DL.asLocation(); Modified: cfe/trunk/test/Analysis/unreachable-code-path.c URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analysis/unreachable-code-path.c?rev=284477&r1=284476&r2=284477&view=diff == --- cfe/trunk/test/Analysis/unreachable-code-path.c (original) +++ cfe/trunk/test/Analysis/unreachable-code-path.c Tue Oct 18 08:16:53 2016 @@ -206,3 +206,10 @@ void test13(int i) { int x = inlineFunction(i); x && x < 10; // no-warning } + +// Don't warn in a macro +#define RETURN(X) do { return; } while (0) +void macro(void) { + RETURN(1); // no-warning +} + ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] r285689 - [clang-tidy] Add check readability-redundant-declaration
Author: danielmarjamaki Date: Tue Nov 1 08:26:15 2016 New Revision: 285689 URL: http://llvm.org/viewvc/llvm-project?rev=285689&view=rev Log: [clang-tidy] Add check readability-redundant-declaration Finds redundant variable and function declarations. extern int X; extern int X; // <- redundant Differential Revision: https://reviews.llvm.org/D24656 Added: clang-tools-extra/trunk/clang-tidy/readability/RedundantDeclarationCheck.cpp clang-tools-extra/trunk/clang-tidy/readability/RedundantDeclarationCheck.h clang-tools-extra/trunk/docs/clang-tidy/checks/readability-redundant-declaration.rst clang-tools-extra/trunk/test/clang-tidy/readability-redundant-declaration.cpp Modified: clang-tools-extra/trunk/clang-tidy/readability/CMakeLists.txt clang-tools-extra/trunk/clang-tidy/readability/ReadabilityTidyModule.cpp clang-tools-extra/trunk/docs/ReleaseNotes.rst clang-tools-extra/trunk/docs/clang-tidy/checks/list.rst Modified: clang-tools-extra/trunk/clang-tidy/readability/CMakeLists.txt URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/readability/CMakeLists.txt?rev=285689&r1=285688&r2=285689&view=diff == --- clang-tools-extra/trunk/clang-tidy/readability/CMakeLists.txt (original) +++ clang-tools-extra/trunk/clang-tidy/readability/CMakeLists.txt Tue Nov 1 08:26:15 2016 @@ -16,6 +16,7 @@ add_clang_library(clangTidyReadabilityMo NonConstParameterCheck.cpp ReadabilityTidyModule.cpp RedundantControlFlowCheck.cpp + RedundantDeclarationCheck.cpp RedundantMemberInitCheck.cpp RedundantStringCStrCheck.cpp RedundantSmartptrGetCheck.cpp Modified: clang-tools-extra/trunk/clang-tidy/readability/ReadabilityTidyModule.cpp URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/readability/ReadabilityTidyModule.cpp?rev=285689&r1=285688&r2=285689&view=diff == --- clang-tools-extra/trunk/clang-tidy/readability/ReadabilityTidyModule.cpp (original) +++ clang-tools-extra/trunk/clang-tidy/readability/ReadabilityTidyModule.cpp Tue Nov 1 08:26:15 2016 @@ -23,6 +23,7 @@ #include "NamedParameterCheck.h" #include "NonConstParameterCheck.h" #include "RedundantControlFlowCheck.h" +#include "RedundantDeclarationCheck.h" #include "RedundantMemberInitCheck.h" #include "RedundantSmartptrGetCheck.h" #include "RedundantStringCStrCheck.h" @@ -68,6 +69,8 @@ public: "readability-non-const-parameter"); CheckFactories.registerCheck( "readability-redundant-control-flow"); +CheckFactories.registerCheck( +"readability-redundant-declaration"); CheckFactories.registerCheck( "readability-redundant-smartptr-get"); CheckFactories.registerCheck( Added: clang-tools-extra/trunk/clang-tidy/readability/RedundantDeclarationCheck.cpp URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/readability/RedundantDeclarationCheck.cpp?rev=285689&view=auto == --- clang-tools-extra/trunk/clang-tidy/readability/RedundantDeclarationCheck.cpp (added) +++ clang-tools-extra/trunk/clang-tidy/readability/RedundantDeclarationCheck.cpp Tue Nov 1 08:26:15 2016 @@ -0,0 +1,71 @@ +//===--- RedundantDeclarationCheck.cpp - clang-tidy===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===--===// + +#include "RedundantDeclarationCheck.h" +#include "clang/AST/ASTContext.h" +#include "clang/ASTMatchers/ASTMatchFinder.h" +#include "clang/Lex/Lexer.h" + +using namespace clang::ast_matchers; + +namespace clang { +namespace tidy { +namespace readability { + +void RedundantDeclarationCheck::registerMatchers(MatchFinder *Finder) { + Finder->addMatcher(namedDecl(anyOf(varDecl(), functionDecl())).bind("Decl"), this); +} + +void RedundantDeclarationCheck::check(const MatchFinder::MatchResult &Result) { + const NamedDecl *D = Result.Nodes.getNodeAs("Decl"); + const auto *Prev = D->getPreviousDecl(); + if (!Prev) +return; + if (Prev->getLocation() == D->getLocation()) +return; + + const SourceManager &SM = *Result.SourceManager; + + const bool DifferentHeaders = + !SM.isInMainFile(D->getLocation()) && + !SM.isWrittenInSameFile(Prev->getLocation(), D->getLocation()); + + bool MultiVar = false; + if (const auto *VD = dyn_cast(D)) { +if (VD->getPreviousDecl()->getStorageClass() == SC_Extern && +VD->getStorageClass() != SC_Extern) + return; +// Is this a multivariable declaration? +for (const auto Other : VD->getDeclContext()->decls()) { + if (Other != D && Other->getLocStart() == VD->getLocSta
[clang-tools-extra] r252608 - [clang-tidy] misc-macro-parentheses: fix fp when using object member pointers
Author: danielmarjamaki Date: Tue Nov 10 08:32:25 2015 New Revision: 252608 URL: http://llvm.org/viewvc/llvm-project?rev=252608&view=rev Log: [clang-tidy] misc-macro-parentheses: fix fp when using object member pointers Fixes http://llvm.org/PR25208. Modified: clang-tools-extra/trunk/clang-tidy/misc/MacroParenthesesCheck.cpp clang-tools-extra/trunk/test/clang-tidy/misc-macro-parentheses.cpp Modified: clang-tools-extra/trunk/clang-tidy/misc/MacroParenthesesCheck.cpp URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/misc/MacroParenthesesCheck.cpp?rev=252608&r1=252607&r2=252608&view=diff == --- clang-tools-extra/trunk/clang-tidy/misc/MacroParenthesesCheck.cpp (original) +++ clang-tools-extra/trunk/clang-tidy/misc/MacroParenthesesCheck.cpp Tue Nov 10 08:32:25 2015 @@ -148,7 +148,8 @@ void MacroParenthesesPPCallbacks::argume continue; // Argument is a struct member. -if (Prev.isOneOf(tok::period, tok::arrow, tok::coloncolon)) +if (Prev.isOneOf(tok::period, tok::arrow, tok::coloncolon, tok::arrowstar, + tok::periodstar)) continue; // Argument is a namespace or class. Modified: clang-tools-extra/trunk/test/clang-tidy/misc-macro-parentheses.cpp URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/test/clang-tidy/misc-macro-parentheses.cpp?rev=252608&r1=252607&r2=252608&view=diff == --- clang-tools-extra/trunk/test/clang-tidy/misc-macro-parentheses.cpp (original) +++ clang-tools-extra/trunk/test/clang-tidy/misc-macro-parentheses.cpp Tue Nov 10 08:32:25 2015 @@ -34,6 +34,8 @@ #define GOOD23(type) (type::Field) #define GOOD24(t) std::set s #define GOOD25(t) std::set s +#define GOOD26(x) (a->*x) +#define GOOD27(x) (a.*x) // These are allowed for now.. #define MAYBE1*12.34 ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
r244435 - [Static Analyzer] Warn when inner and outer conditions are identical. The inner condition is always true.
Author: danielmarjamaki Date: Mon Aug 10 02:18:29 2015 New Revision: 244435 URL: http://llvm.org/viewvc/llvm-project?rev=244435&view=rev Log: [Static Analyzer] Warn when inner and outer conditions are identical. The inner condition is always true. Reviewed in http://reviews.llvm.org/D10892. Modified: cfe/trunk/lib/StaticAnalyzer/Checkers/IdenticalExprChecker.cpp cfe/trunk/test/Analysis/identical-expressions.cpp Modified: cfe/trunk/lib/StaticAnalyzer/Checkers/IdenticalExprChecker.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Checkers/IdenticalExprChecker.cpp?rev=244435&r1=244434&r2=244435&view=diff == --- cfe/trunk/lib/StaticAnalyzer/Checkers/IdenticalExprChecker.cpp (original) +++ cfe/trunk/lib/StaticAnalyzer/Checkers/IdenticalExprChecker.cpp Mon Aug 10 02:18:29 2015 @@ -108,6 +108,24 @@ bool FindIdenticalExprVisitor::VisitIfSt const Stmt *Stmt1 = I->getThen(); const Stmt *Stmt2 = I->getElse(); + // Check for identical inner condition: + // + // if (x<10) { + // if (x<10) { + // .. + if (const CompoundStmt *CS = dyn_cast(Stmt1)) { +if (!CS->body_empty()) { + const IfStmt *InnerIf = dyn_cast(*CS->body_begin()); + if (InnerIf && isIdenticalStmt(AC->getASTContext(), I->getCond(), InnerIf->getCond(), /*ignoreSideEffects=*/ false)) { +PathDiagnosticLocation ELoc(InnerIf->getCond(), BR.getSourceManager(), AC); +BR.EmitBasicReport(AC->getDecl(), Checker, "Identical conditions", + categories::LogicError, + "conditions of the inner and outer statements are identical", + ELoc); + } +} + } + // Check for identical conditions: // // if (b) { Modified: cfe/trunk/test/Analysis/identical-expressions.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analysis/identical-expressions.cpp?rev=244435&r1=244434&r2=244435&view=diff == --- cfe/trunk/test/Analysis/identical-expressions.cpp (original) +++ cfe/trunk/test/Analysis/identical-expressions.cpp Mon Aug 10 02:18:29 2015 @@ -1530,3 +1530,35 @@ void test_nowarn_long() { c = 0LL; } } + +// Identical inner conditions + +void test_warn_inner_if_1(int x) { + if (x == 1) { +if (x == 1) // expected-warning {{conditions of the inner and outer statements are identical}} + ; + } + + // FIXME: Should warn here. The warning is currently not emitted because there + // is code between the conditions. + if (x == 1) { +int y = x; +if (x == 1) + ; + } +} + +void test_nowarn_inner_if_1(int x) { + // Don't warn when condition has side effects. + if (x++ == 1) { +if (x++ == 1) + ; + } + + // Don't warn when x is changed before inner condition. + if (x < 10) { +x++; +if (x < 10) + ; + } +} ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] r260223 - [clang-tidy] Add 'misc-misplaced-widening-cast' check.
Author: danielmarjamaki Date: Tue Feb 9 08:08:49 2016 New Revision: 260223 URL: http://llvm.org/viewvc/llvm-project?rev=260223&view=rev Log: [clang-tidy] Add 'misc-misplaced-widening-cast' check. Reviewers: alexfh Subscribers: cfe-commits Differential Revision: http://reviews.llvm.org/D16310 Added: clang-tools-extra/trunk/clang-tidy/misc/MisplacedWideningCastCheck.cpp clang-tools-extra/trunk/clang-tidy/misc/MisplacedWideningCastCheck.h clang-tools-extra/trunk/docs/clang-tidy/checks/misc-misplaced-widening-cast.rst clang-tools-extra/trunk/test/clang-tidy/misc-misplaced-widening-cast.cpp Modified: clang-tools-extra/trunk/clang-tidy/misc/CMakeLists.txt clang-tools-extra/trunk/clang-tidy/misc/MiscTidyModule.cpp clang-tools-extra/trunk/docs/clang-tidy/checks/list.rst Modified: clang-tools-extra/trunk/clang-tidy/misc/CMakeLists.txt URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/misc/CMakeLists.txt?rev=260223&r1=260222&r2=260223&view=diff == --- clang-tools-extra/trunk/clang-tidy/misc/CMakeLists.txt (original) +++ clang-tools-extra/trunk/clang-tidy/misc/CMakeLists.txt Tue Feb 9 08:08:49 2016 @@ -12,6 +12,7 @@ add_clang_library(clangTidyMiscModule MacroParenthesesCheck.cpp MacroRepeatedSideEffectsCheck.cpp MiscTidyModule.cpp + MisplacedWideningCastCheck.cpp MoveConstantArgumentCheck.cpp MoveConstructorInitCheck.cpp NewDeleteOverloadsCheck.cpp Modified: clang-tools-extra/trunk/clang-tidy/misc/MiscTidyModule.cpp URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/misc/MiscTidyModule.cpp?rev=260223&r1=260222&r2=260223&view=diff == --- clang-tools-extra/trunk/clang-tidy/misc/MiscTidyModule.cpp (original) +++ clang-tools-extra/trunk/clang-tidy/misc/MiscTidyModule.cpp Tue Feb 9 08:08:49 2016 @@ -20,6 +20,7 @@ #include "InefficientAlgorithmCheck.h" #include "MacroParenthesesCheck.h" #include "MacroRepeatedSideEffectsCheck.h" +#include "MisplacedWideningCastCheck.h" #include "MoveConstantArgumentCheck.h" #include "MoveConstructorInitCheck.h" #include "NewDeleteOverloadsCheck.h" @@ -63,6 +64,8 @@ public: "misc-macro-parentheses"); CheckFactories.registerCheck( "misc-macro-repeated-side-effects"); +CheckFactories.registerCheck( +"misc-misplaced-widening-cast"); CheckFactories.registerCheck( "misc-move-const-arg"); CheckFactories.registerCheck( Added: clang-tools-extra/trunk/clang-tidy/misc/MisplacedWideningCastCheck.cpp URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/misc/MisplacedWideningCastCheck.cpp?rev=260223&view=auto == --- clang-tools-extra/trunk/clang-tidy/misc/MisplacedWideningCastCheck.cpp (added) +++ clang-tools-extra/trunk/clang-tidy/misc/MisplacedWideningCastCheck.cpp Tue Feb 9 08:08:49 2016 @@ -0,0 +1,106 @@ +//===--- MisplacedWideningCastCheck.cpp - clang-tidy---===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===--===// + +#include "MisplacedWideningCastCheck.h" +#include "clang/AST/ASTContext.h" +#include "clang/ASTMatchers/ASTMatchFinder.h" + +using namespace clang::ast_matchers; + +namespace clang { +namespace tidy { +namespace misc { + +void MisplacedWideningCastCheck::registerMatchers(MatchFinder *Finder) { + auto Calc = expr(anyOf(binaryOperator(anyOf( + hasOperatorName("+"), hasOperatorName("-"), + hasOperatorName("*"), hasOperatorName("<<"))), + unaryOperator(hasOperatorName("~"))), + hasType(isInteger())) + .bind("Calc"); + + auto Cast = explicitCastExpr(anyOf(cStyleCastExpr(), cxxStaticCastExpr(), + cxxReinterpretCastExpr()), + hasDestinationType(isInteger()), + has(Calc)) + .bind("Cast"); + + Finder->addMatcher(varDecl(has(Cast)), this); + Finder->addMatcher(returnStmt(has(Cast)), this); + Finder->addMatcher(binaryOperator(hasOperatorName("="), hasRHS(Cast)), this); +} + +static unsigned getMaxCalculationWidth(ASTContext &Context, const Expr *E) { + E = E->IgnoreParenImpCasts(); + + if (const auto *Bop = dyn_cast(E)) { +unsigned LHSWidth = getMaxCalculationWidth(Context, Bop->getLHS()); +unsigned RHSWidth = getMaxCalculationWidth(Context, Bop->getRHS()); +if (Bop->getOpcode() == BO_Mul) + return LHSWidth + RHSWidth; +if (Bop->getOpcode() == BO_Add) + return std::max(LHSWidth, RHSWidth
[clang-tools-extra] r260225 - [clang-tidy] Add -target in misc-misplaced-widening-cast test so it will work on various bots
Author: danielmarjamaki Date: Tue Feb 9 09:43:05 2016 New Revision: 260225 URL: http://llvm.org/viewvc/llvm-project?rev=260225&view=rev Log: [clang-tidy] Add -target in misc-misplaced-widening-cast test so it will work on various bots Modified: clang-tools-extra/trunk/test/clang-tidy/misc-misplaced-widening-cast.cpp Modified: clang-tools-extra/trunk/test/clang-tidy/misc-misplaced-widening-cast.cpp URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/test/clang-tidy/misc-misplaced-widening-cast.cpp?rev=260225&r1=260224&r2=260225&view=diff == --- clang-tools-extra/trunk/test/clang-tidy/misc-misplaced-widening-cast.cpp (original) +++ clang-tools-extra/trunk/test/clang-tidy/misc-misplaced-widening-cast.cpp Tue Feb 9 09:43:05 2016 @@ -1,4 +1,4 @@ -// RUN: %check_clang_tidy %s misc-misplaced-widening-cast %t +// RUN: %check_clang_tidy %s misc-misplaced-widening-cast %t -- -- -target x86_64-unknown-unknown void assign(int a, int b) { long l; ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] r260665 - [clang-tidy] improve misc-misplaced-widening-cast so it also detects portability problems.
Author: danielmarjamaki Date: Fri Feb 12 01:51:10 2016 New Revision: 260665 URL: http://llvm.org/viewvc/llvm-project?rev=260665&view=rev Log: [clang-tidy] improve misc-misplaced-widening-cast so it also detects portability problems. Reviewers: alexfh Subscribers: cfe-commits Differential Revision: http://reviews.llvm.org/D17140 Modified: clang-tools-extra/trunk/clang-tidy/misc/MisplacedWideningCastCheck.cpp clang-tools-extra/trunk/test/clang-tidy/misc-misplaced-widening-cast.cpp Modified: clang-tools-extra/trunk/clang-tidy/misc/MisplacedWideningCastCheck.cpp URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/misc/MisplacedWideningCastCheck.cpp?rev=260665&r1=260664&r2=260665&view=diff == --- clang-tools-extra/trunk/clang-tidy/misc/MisplacedWideningCastCheck.cpp (original) +++ clang-tools-extra/trunk/clang-tidy/misc/MisplacedWideningCastCheck.cpp Fri Feb 12 01:51:10 2016 @@ -27,8 +27,7 @@ void MisplacedWideningCastCheck::registe auto Cast = explicitCastExpr(anyOf(cStyleCastExpr(), cxxStaticCastExpr(), cxxReinterpretCastExpr()), - hasDestinationType(isInteger()), - has(Calc)) + hasDestinationType(isInteger()), has(Calc)) .bind("Cast"); Finder->addMatcher(varDecl(has(Cast)), this); @@ -90,9 +89,29 @@ void MisplacedWideningCastCheck::check(c QualType CastType = Cast->getType(); QualType CalcType = Calc->getType(); - if (Context.getIntWidth(CastType) <= Context.getIntWidth(CalcType)) + // Explicit truncation using cast. + if (Context.getIntWidth(CastType) < Context.getIntWidth(CalcType)) return; + // If CalcType and CastType have same size then there is no real danger, but + // there can be a portability problem. + if (Context.getIntWidth(CastType) == Context.getIntWidth(CalcType)) { +if (CalcType->isSpecificBuiltinType(BuiltinType::Int)) { + // There should be a warning when casting from int to long or long long. + if (!CastType->isSpecificBuiltinType(BuiltinType::Long) && + !CastType->isSpecificBuiltinType(BuiltinType::LongLong)) +return; +} else if (CalcType->isSpecificBuiltinType(BuiltinType::Long)) { + // There should be a warning when casting from long to long long. + if (!CastType->isSpecificBuiltinType(BuiltinType::LongLong)) +return; +} else { + return; +} + } + + // Don't write a warning if we can easily see that the result is not + // truncated. if (Context.getIntWidth(CalcType) >= getMaxCalculationWidth(Context, Calc)) return; Modified: clang-tools-extra/trunk/test/clang-tidy/misc-misplaced-widening-cast.cpp URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/test/clang-tidy/misc-misplaced-widening-cast.cpp?rev=260665&r1=260664&r2=260665&view=diff == --- clang-tools-extra/trunk/test/clang-tidy/misc-misplaced-widening-cast.cpp (original) +++ clang-tools-extra/trunk/test/clang-tidy/misc-misplaced-widening-cast.cpp Fri Feb 12 01:51:10 2016 @@ -1,4 +1,4 @@ -// RUN: %check_clang_tidy %s misc-misplaced-widening-cast %t -- -- -target x86_64-unknown-unknown +// RUN: %check_clang_tidy %s misc-misplaced-widening-cast %t void assign(int a, int b) { long l; ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] r260667 - [clang-tidy] Fix failure in 'misc-misplaced-widening-cast' test.
Author: danielmarjamaki Date: Fri Feb 12 03:38:38 2016 New Revision: 260667 URL: http://llvm.org/viewvc/llvm-project?rev=260667&view=rev Log: [clang-tidy] Fix failure in 'misc-misplaced-widening-cast' test. I added portability warnings when int results are casted to long. I forgot to handle uint, ulong and ulonglong. Tested on x86 and powerpc targets, hope it works now on all buildbots. Modified: clang-tools-extra/trunk/clang-tidy/misc/MisplacedWideningCastCheck.cpp Modified: clang-tools-extra/trunk/clang-tidy/misc/MisplacedWideningCastCheck.cpp URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/misc/MisplacedWideningCastCheck.cpp?rev=260667&r1=260666&r2=260667&view=diff == --- clang-tools-extra/trunk/clang-tidy/misc/MisplacedWideningCastCheck.cpp (original) +++ clang-tools-extra/trunk/clang-tidy/misc/MisplacedWideningCastCheck.cpp Fri Feb 12 03:38:38 2016 @@ -96,14 +96,19 @@ void MisplacedWideningCastCheck::check(c // If CalcType and CastType have same size then there is no real danger, but // there can be a portability problem. if (Context.getIntWidth(CastType) == Context.getIntWidth(CalcType)) { -if (CalcType->isSpecificBuiltinType(BuiltinType::Int)) { +if (CalcType->isSpecificBuiltinType(BuiltinType::Int) || +CalcType->isSpecificBuiltinType(BuiltinType::UInt)) { // There should be a warning when casting from int to long or long long. if (!CastType->isSpecificBuiltinType(BuiltinType::Long) && - !CastType->isSpecificBuiltinType(BuiltinType::LongLong)) + !CastType->isSpecificBuiltinType(BuiltinType::ULong) && + !CastType->isSpecificBuiltinType(BuiltinType::LongLong) && + !CastType->isSpecificBuiltinType(BuiltinType::ULongLong)) return; -} else if (CalcType->isSpecificBuiltinType(BuiltinType::Long)) { +} else if (CalcType->isSpecificBuiltinType(BuiltinType::Long) || + CalcType->isSpecificBuiltinType(BuiltinType::ULong)) { // There should be a warning when casting from long to long long. - if (!CastType->isSpecificBuiltinType(BuiltinType::LongLong)) + if (!CastType->isSpecificBuiltinType(BuiltinType::LongLong) && + !CastType->isSpecificBuiltinType(BuiltinType::ULongLong)) return; } else { return; ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] r272128 - [clang-tidy] misc-macro-parentheses - avoid adding parentheses in variable declarations
Author: danielmarjamaki Date: Wed Jun 8 05:30:24 2016 New Revision: 272128 URL: http://llvm.org/viewvc/llvm-project?rev=272128&view=rev Log: [clang-tidy] misc-macro-parentheses - avoid adding parentheses in variable declarations Fixes bugzilla issues 26273 and 27399 Reviewers: alexfh Subscribers: cfe-commits Differential Revision: http://reviews.llvm.org/D20853 Modified: clang-tools-extra/trunk/clang-tidy/misc/MacroParenthesesCheck.cpp clang-tools-extra/trunk/test/clang-tidy/misc-macro-parentheses.cpp Modified: clang-tools-extra/trunk/clang-tidy/misc/MacroParenthesesCheck.cpp URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/misc/MacroParenthesesCheck.cpp?rev=272128&r1=272127&r2=272128&view=diff == --- clang-tools-extra/trunk/clang-tidy/misc/MacroParenthesesCheck.cpp (original) +++ clang-tools-extra/trunk/clang-tidy/misc/MacroParenthesesCheck.cpp Wed Jun 8 05:30:24 2016 @@ -19,8 +19,7 @@ namespace misc { namespace { class MacroParenthesesPPCallbacks : public PPCallbacks { public: - MacroParenthesesPPCallbacks(Preprocessor *PP, - MacroParenthesesCheck *Check) + MacroParenthesesPPCallbacks(Preprocessor *PP, MacroParenthesesCheck *Check) : PP(PP), Check(Check) {} void MacroDefined(const Token &MacroNameTok, @@ -67,8 +66,46 @@ static bool isWarnOp(const Token &T) { tok::amp, tok::pipe, tok::caret); } +/// Is given Token a keyword that is used in variable declarations? +static bool isVarDeclKeyword(const Token &T) { + return T.isOneOf(tok::kw_bool, tok::kw_char, tok::kw_short, tok::kw_int, + tok::kw_long, tok::kw_float, tok::kw_double, tok::kw_const, + tok::kw_enum, tok::kw_inline, tok::kw_static, tok::kw_struct, + tok::kw_signed, tok::kw_unsigned); +} + +/// Is there a possible variable declaration at Tok? +static bool possibleVarDecl(const MacroInfo *MI, const Token *Tok) { + if (Tok == MI->tokens_end()) +return false; + + // If we see int/short/struct/etc., just assume this is a variable declaration. + if (isVarDeclKeyword(*Tok)) +return true; + + // Variable declarations start with identifier or coloncolon. + if (!Tok->isOneOf(tok::identifier, tok::raw_identifier, tok::coloncolon)) +return false; + + // Skip possible types, etc + while ( + Tok != MI->tokens_end() && + Tok->isOneOf(tok::identifier, tok::raw_identifier, tok::coloncolon, +tok::star, tok::amp, tok::ampamp, tok::less, tok::greater)) +Tok++; + + // Return true for possible variable declarations. + return Tok == MI->tokens_end() || + Tok->isOneOf(tok::equal, tok::semi, tok::l_square, tok::l_paren) || + isVarDeclKeyword(*Tok); +} + void MacroParenthesesPPCallbacks::replacementList(const Token &MacroNameTok, const MacroInfo *MI) { + // Make sure macro replacement isn't a variable declaration. + if (possibleVarDecl(MI, MI->tokens_begin())) +return; + // Count how deep we are in parentheses/braces/squares. int Count = 0; @@ -117,6 +154,9 @@ void MacroParenthesesPPCallbacks::replac void MacroParenthesesPPCallbacks::argument(const Token &MacroNameTok, const MacroInfo *MI) { + + // Skip variable declaration. + bool VarDecl = possibleVarDecl(MI, MI->tokens_begin()); for (auto TI = MI->tokens_begin(), TE = MI->tokens_end(); TI != TE; ++TI) { // First token. @@ -132,6 +172,13 @@ void MacroParenthesesPPCallbacks::argume const Token &Tok = *TI; +// There should not be extra parentheses in possible variable declaration. +if (VarDecl) { + if (Tok.isOneOf(tok::equal, tok::semi, tok::l_square, tok::l_paren)) +VarDecl = false; + continue; +} + // Only interested in identifiers. if (!Tok.isOneOf(tok::identifier, tok::raw_identifier)) continue; Modified: clang-tools-extra/trunk/test/clang-tidy/misc-macro-parentheses.cpp URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/test/clang-tidy/misc-macro-parentheses.cpp?rev=272128&r1=272127&r2=272128&view=diff == --- clang-tools-extra/trunk/test/clang-tidy/misc-macro-parentheses.cpp (original) +++ clang-tools-extra/trunk/test/clang-tidy/misc-macro-parentheses.cpp Wed Jun 8 05:30:24 2016 @@ -8,6 +8,8 @@ // CHECK-MESSAGES: :[[@LINE-1]]:28: warning: macro argument should be enclosed in parentheses [misc-macro-parentheses] #define BAD4(x) ((unsigned char)(x & 0xff)) // CHECK-MESSAGES: :[[@LINE-1]]:44: warning: macro argument should be enclosed in parentheses [misc-macro-parentheses] +#define BAD5(X) A*B=(C*)X+2 +// CHECK-MESSAGES: :[[@LINE-1]]:35: warning: macro argument should be enclosed in parentheses [misc-macr
r258673 - [Sema] Improve constness
Author: danielmarjamaki Date: Mon Jan 25 03:29:38 2016 New Revision: 258673 URL: http://llvm.org/viewvc/llvm-project?rev=258673&view=rev Log: [Sema] Improve constness Modified: cfe/trunk/lib/Sema/SemaChecking.cpp Modified: cfe/trunk/lib/Sema/SemaChecking.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaChecking.cpp?rev=258673&r1=258672&r2=258673&view=diff == --- cfe/trunk/lib/Sema/SemaChecking.cpp (original) +++ cfe/trunk/lib/Sema/SemaChecking.cpp Mon Jan 25 03:29:38 2016 @@ -6215,7 +6215,7 @@ static IntRange GetValueRange(ASTContext return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType()); } -static QualType GetExprType(Expr *E) { +static QualType GetExprType(const Expr *E) { QualType Ty = E->getType(); if (const AtomicType *AtomicRHS = Ty->getAs()) Ty = AtomicRHS->getValueType(); @@ -6226,7 +6226,7 @@ static QualType GetExprType(Expr *E) { /// range of values it might take. /// /// \param MaxWidth - the width to which the value will be truncated -static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) { +static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) { E = E->IgnoreParens(); // Try a full evaluation first. @@ -6237,7 +6237,7 @@ static IntRange GetExprRange(ASTContext // I think we only want to look through implicit casts here; if the // user has an explicit widening cast, we should treat the value as // being of the new, wider type. - if (ImplicitCastExpr *CE = dyn_cast(E)) { + if (const auto *CE = dyn_cast(E)) { if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue) return GetExprRange(C, CE->getSubExpr(), MaxWidth); @@ -6264,7 +6264,7 @@ static IntRange GetExprRange(ASTContext SubRange.NonNegative || OutputTypeRange.NonNegative); } - if (ConditionalOperator *CO = dyn_cast(E)) { + if (const auto *CO = dyn_cast(E)) { // If we can fold the condition, just take that operand. bool CondResult; if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C)) @@ -6278,7 +6278,7 @@ static IntRange GetExprRange(ASTContext return IntRange::join(L, R); } - if (BinaryOperator *BO = dyn_cast(E)) { + if (const auto *BO = dyn_cast(E)) { switch (BO->getOpcode()) { // Boolean-valued operations are single-bit and positive. @@ -6418,7 +6418,7 @@ static IntRange GetExprRange(ASTContext return IntRange::join(L, R); } - if (UnaryOperator *UO = dyn_cast(E)) { + if (const auto *UO = dyn_cast(E)) { switch (UO->getOpcode()) { // Boolean-valued operations are white-listed. case UO_LNot: @@ -6434,17 +6434,17 @@ static IntRange GetExprRange(ASTContext } } - if (OpaqueValueExpr *OVE = dyn_cast(E)) + if (const auto *OVE = dyn_cast(E)) return GetExprRange(C, OVE->getSourceExpr(), MaxWidth); - if (FieldDecl *BitField = E->getSourceBitField()) + if (const auto *BitField = E->getSourceBitField()) return IntRange(BitField->getBitWidthValue(C), BitField->getType()->isUnsignedIntegerOrEnumerationType()); return IntRange::forValueOfType(C, GetExprType(E)); } -static IntRange GetExprRange(ASTContext &C, Expr *E) { +static IntRange GetExprRange(ASTContext &C, const Expr *E) { return GetExprRange(C, E, C.getIntWidth(GetExprType(E))); } ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
r258911 - Fix array index out of bounds
Author: danielmarjamaki Date: Wed Jan 27 01:33:50 2016 New Revision: 258911 URL: http://llvm.org/viewvc/llvm-project?rev=258911&view=rev Log: Fix array index out of bounds Differential Revision: http://reviews.llvm.org/D16582 Modified: cfe/trunk/lib/Driver/MSVCToolChain.cpp Modified: cfe/trunk/lib/Driver/MSVCToolChain.cpp URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Driver/MSVCToolChain.cpp?rev=258911&r1=258910&r2=258911&view=diff == --- cfe/trunk/lib/Driver/MSVCToolChain.cpp (original) +++ cfe/trunk/lib/Driver/MSVCToolChain.cpp Wed Jan 27 01:33:50 2016 @@ -141,8 +141,8 @@ static bool getSystemRegistryString(cons nextKey++; size_t partialKeyLength = keyEnd - keyPath; char partialKey[256]; -if (partialKeyLength > sizeof(partialKey)) - partialKeyLength = sizeof(partialKey); +if (partialKeyLength >= sizeof(partialKey)) + partialKeyLength = sizeof(partialKey) - 1; strncpy(partialKey, keyPath, partialKeyLength); partialKey[partialKeyLength] = '\0'; HKEY hTopKey = NULL; ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] r254066 - [clang-tidy] code cleanup using isAssignmentOp()
Author: danielmarjamaki Date: Wed Nov 25 05:30:00 2015 New Revision: 254066 URL: http://llvm.org/viewvc/llvm-project?rev=254066&view=rev Log: [clang-tidy] code cleanup using isAssignmentOp() Modified: clang-tools-extra/trunk/clang-tidy/misc/AssertSideEffectCheck.cpp Modified: clang-tools-extra/trunk/clang-tidy/misc/AssertSideEffectCheck.cpp URL: http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/misc/AssertSideEffectCheck.cpp?rev=254066&r1=254065&r2=254066&view=diff == --- clang-tools-extra/trunk/clang-tidy/misc/AssertSideEffectCheck.cpp (original) +++ clang-tools-extra/trunk/clang-tidy/misc/AssertSideEffectCheck.cpp Wed Nov 25 05:30:00 2015 @@ -33,11 +33,7 @@ AST_MATCHER_P(Expr, hasSideEffect, bool, } if (const auto *Op = dyn_cast(E)) { -BinaryOperator::Opcode OC = Op->getOpcode(); -return OC == BO_Assign || OC == BO_MulAssign || OC == BO_DivAssign || - OC == BO_RemAssign || OC == BO_AddAssign || OC == BO_SubAssign || - OC == BO_ShlAssign || OC == BO_ShrAssign || OC == BO_AndAssign || - OC == BO_XorAssign || OC == BO_OrAssign; +return Op->isAssignmentOp(); } if (const auto *OpCallExpr = dyn_cast(E)) { ___ cfe-commits mailing list cfe-commits@lists.llvm.org http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits