diff --git a/clang-tools-extra/clang-tidy/bugprone/MisplacedWideningCastCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/MisplacedWideningCastCheck.cpp index d508e2aaba53c..f040235322a4f 100644 --- a/clang-tools-extra/clang-tidy/bugprone/MisplacedWideningCastCheck.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/MisplacedWideningCastCheck.cpp @@ -52,8 +52,8 @@ static unsigned getMaxCalculationWidth(const ASTContext &Context, E = E->IgnoreParenImpCasts(); if (const auto *Bop = dyn_cast(E)) { - unsigned LHSWidth = getMaxCalculationWidth(Context, Bop->getLHS()); - unsigned RHSWidth = getMaxCalculationWidth(Context, Bop->getRHS()); + const unsigned LHSWidth = getMaxCalculationWidth(Context, Bop->getLHS()); + const unsigned RHSWidth = getMaxCalculationWidth(Context, Bop->getRHS()); if (Bop->getOpcode() == BO_Mul) return LHSWidth + RHSWidth; if (Bop->getOpcode() == BO_Add) @@ -79,7 +79,7 @@ static unsigned getMaxCalculationWidth(const ASTContext &Context, if (Uop->getOpcode() == UO_Not) return 1024U; - QualType T = Uop->getType(); + const QualType T = Uop->getType(); return T->isIntegerType() ? Context.getIntWidth(T) : 1024U; } else if (const auto *I = dyn_cast(E)) { return I->getValue().getActiveBits(); @@ -190,10 +190,10 @@ void MisplacedWideningCastCheck::check(const MatchFinder::MatchResult &Result) { Calc->isTypeDependent() || Calc->isValueDependent()) return; - ASTContext &Context = *Result.Context; + const ASTContext &Context = *Result.Context; - QualType CastType = Cast->getType(); - QualType CalcType = Calc->getType(); + const QualType CastType = Cast->getType(); + const QualType CalcType = Calc->getType(); // Explicit truncation using cast. if (Context.getIntWidth(CastType) < Context.getIntWidth(CalcType)) diff --git a/clang-tools-extra/clang-tidy/bugprone/MoveForwardingReferenceCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/MoveForwardingReferenceCheck.cpp index 66559a0e5d7b5..e182df75b1d9a 100644 --- a/clang-tools-extra/clang-tidy/bugprone/MoveForwardingReferenceCheck.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/MoveForwardingReferenceCheck.cpp @@ -21,7 +21,7 @@ static void replaceMoveWithForward(const UnresolvedLookupExpr *Callee, const SourceManager &SM = Context.getSourceManager(); const LangOptions &LangOpts = Context.getLangOpts(); - CharSourceRange CallRange = + const CharSourceRange CallRange = Lexer::makeFileCharRange(CharSourceRange::getTokenRange( Callee->getBeginLoc(), Callee->getEndLoc()), SM, LangOpts); @@ -39,7 +39,7 @@ static void replaceMoveWithForward(const UnresolvedLookupExpr *Callee, // std::move(). This will hopefully prevent erroneous replacements if the // code does unusual things (e.g. create an alias for std::move() in // another namespace). - NestedNameSpecifier NNS = Callee->getQualifier(); + const NestedNameSpecifier NNS = Callee->getQualifier(); switch (NNS.getKind()) { case NestedNameSpecifier::Kind::Null: // Called as "move" (i.e. presumably the code had a "using std::move;"). diff --git a/clang-tools-extra/clang-tidy/bugprone/MultiLevelImplicitPointerConversionCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/MultiLevelImplicitPointerConversionCheck.cpp index 2eff013b2ab7d..78f2017984a96 100644 --- a/clang-tools-extra/clang-tidy/bugprone/MultiLevelImplicitPointerConversionCheck.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/MultiLevelImplicitPointerConversionCheck.cpp @@ -86,8 +86,9 @@ MultiLevelImplicitPointerConversionCheck::getCheckTraversalKind() const { void MultiLevelImplicitPointerConversionCheck::check( const MatchFinder::MatchResult &Result) { const auto *MatchedExpr = Result.Nodes.getNodeAs("expr"); - QualType Target = MatchedExpr->getType().getDesugaredType(*Result.Context); - QualType Source = + const QualType Target = + MatchedExpr->getType().getDesugaredType(*Result.Context); + const QualType Source = MatchedExpr->getSubExpr()->getType().getDesugaredType(*Result.Context); diag(MatchedExpr->getExprLoc(), "multilevel pointer conversion from %0 to " diff --git a/clang-tools-extra/clang-tidy/bugprone/MultipleNewInOneExpressionCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/MultipleNewInOneExpressionCheck.cpp index 17aea9392bd26..b81d2b438d58d 100644 --- a/clang-tools-extra/clang-tidy/bugprone/MultipleNewInOneExpressionCheck.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/MultipleNewInOneExpressionCheck.cpp @@ -51,7 +51,8 @@ namespace { AST_MATCHER_P(CXXTryStmt, hasHandlerFor, ast_matchers::internal::Matcher, InnerMatcher) { - for (unsigned NH = Node.getNumHandlers(), I = 0; I < NH; ++I) { + const unsigned NH = Node.getNumHandlers(); + for (unsigned I = 0; I < NH; ++I) { const CXXCatchStmt *CatchS = Node.getHandler(I); // Check for generic catch handler (match anything). if (CatchS->getCaughtType().isNull()) @@ -66,7 +67,7 @@ AST_MATCHER_P(CXXTryStmt, hasHandlerFor, } AST_MATCHER(CXXNewExpr, mayThrow) { - FunctionDecl *OperatorNew = Node.getOperatorNew(); + const FunctionDecl *OperatorNew = Node.getOperatorNew(); if (!OperatorNew) return false; return !OperatorNew->getType()->castAs()->isNothrow(); diff --git a/clang-tools-extra/clang-tidy/bugprone/NarrowingConversionsCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/NarrowingConversionsCheck.cpp index 287ee95a4db55..501a82d67d558 100644 --- a/clang-tools-extra/clang-tidy/bugprone/NarrowingConversionsCheck.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/NarrowingConversionsCheck.cpp @@ -29,15 +29,15 @@ AST_MATCHER_P(QualType, hasAnyType, std::vector, Names) { if (Names.empty()) return false; - std::string Name = Node.getLocalUnqualifiedType().getAsString(); + const std::string Name = Node.getLocalUnqualifiedType().getAsString(); return llvm::is_contained(Names, Name); } AST_MATCHER(FieldDecl, hasIntBitwidth) { assert(Node.isBitField()); const ASTContext &Ctx = Node.getASTContext(); - unsigned IntBitWidth = Ctx.getIntWidth(Ctx.IntTy); - unsigned CurrentBitWidth = Node.getBitWidthValue(); + const unsigned IntBitWidth = Ctx.getIntWidth(Ctx.IntTy); + const unsigned CurrentBitWidth = Node.getBitWidthValue(); return IntBitWidth == CurrentBitWidth; } @@ -79,7 +79,7 @@ void NarrowingConversionsCheck::registerMatchers(MatchFinder *Finder) { const auto IsCeilFloorCallExpr = expr(callExpr(callee(functionDecl( hasAnyName("::ceil", "::std::ceil", "::floor", "::std::floor"))))); - std::vector IgnoreConversionFromTypesVec = + const std::vector IgnoreConversionFromTypesVec = utils::options::parseStringList(IgnoreConversionFromTypes); // We may want to exclude other types from the checks, such as `size_type` @@ -243,7 +243,7 @@ struct IntegerRange { static IntegerRange createFromType(const ASTContext &Context, const BuiltinType &T) { if (T.isFloatingPoint()) { - unsigned PrecisionBits = llvm::APFloatBase::semanticsPrecision( + const unsigned PrecisionBits = llvm::APFloatBase::semanticsPrecision( Context.getFloatTypeSemantics(T.desugar())); // Contrary to two's complement integer, floating point values are // symmetric and have the same number of positive and negative values. @@ -262,8 +262,8 @@ static IntegerRange createFromType(const ASTContext &Context, return {LowerValue, UpperValue}; } assert(T.isInteger() && "Unexpected builtin type"); - uint64_t TypeSize = Context.getTypeSize(&T); - bool IsUnsignedInteger = T.isUnsignedInteger(); + const uint64_t TypeSize = Context.getTypeSize(&T); + const bool IsUnsignedInteger = T.isUnsignedInteger(); return {llvm::APSInt::getMinValue(TypeSize, IsUnsignedInteger), llvm::APSInt::getMaxValue(TypeSize, IsUnsignedInteger)}; } @@ -271,15 +271,15 @@ static IntegerRange createFromType(const ASTContext &Context, static bool isWideEnoughToHold(const ASTContext &Context, const BuiltinType &FromType, const BuiltinType &ToType) { - IntegerRange FromIntegerRange = createFromType(Context, FromType); - IntegerRange ToIntegerRange = createFromType(Context, ToType); + const IntegerRange FromIntegerRange = createFromType(Context, FromType); + const IntegerRange ToIntegerRange = createFromType(Context, ToType); return ToIntegerRange.contains(FromIntegerRange); } static bool isWideEnoughToHold(const ASTContext &Context, const llvm::APSInt &IntegerConstant, const BuiltinType &ToType) { - IntegerRange ToIntegerRange = createFromType(Context, ToType); + const IntegerRange ToIntegerRange = createFromType(Context, ToType); return ToIntegerRange.contains(IntegerConstant); } @@ -289,13 +289,13 @@ static bool isWideEnoughToHold(const ASTContext &Context, static bool isFloatExactlyRepresentable(const ASTContext &Context, const llvm::APFloat &FloatConstant, const QualType &DestType) { - unsigned DestWidth = Context.getIntWidth(DestType); - bool DestSigned = DestType->isSignedIntegerOrEnumerationType(); + const unsigned DestWidth = Context.getIntWidth(DestType); + const bool DestSigned = DestType->isSignedIntegerOrEnumerationType(); llvm::APSInt Result = llvm::APSInt(DestWidth, !DestSigned); bool IsExact = false; - bool Overflows = FloatConstant.convertToInteger( - Result, llvm::APFloat::rmTowardZero, &IsExact) & - llvm::APFloat::opInvalidOp; + const bool Overflows = FloatConstant.convertToInteger( + Result, llvm::APFloat::rmTowardZero, &IsExact) & + llvm::APFloat::opInvalidOp; return !Overflows && IsExact; } @@ -321,8 +321,8 @@ bool NarrowingConversionsCheck::isWarningInhibitedByEquivalentSize( // With this option, we don't warn on conversions that have equivalent width // in bits. eg. uint32 <-> int32. if (!WarnOnEquivalentBitWidth) { - uint64_t FromTypeSize = Context.getTypeSize(&FromType); - uint64_t ToTypeSize = Context.getTypeSize(&ToType); + const uint64_t FromTypeSize = Context.getTypeSize(&FromType); + const uint64_t ToTypeSize = Context.getTypeSize(&ToType); if (FromTypeSize == ToTypeSize) { return true; } @@ -406,8 +406,8 @@ void NarrowingConversionsCheck::handleIntegralCast(const ASTContext &Context, // With this option, we don't warn on conversions that have equivalent width // in bits. eg. uint32 <-> int32. if (!WarnOnEquivalentBitWidth) { - uint64_t FromTypeSize = Context.getTypeSize(FromType); - uint64_t ToTypeSize = Context.getTypeSize(ToType); + const uint64_t FromTypeSize = Context.getTypeSize(FromType); + const uint64_t ToTypeSize = Context.getTypeSize(ToType); if (FromTypeSize == ToTypeSize) return; } @@ -583,7 +583,7 @@ void NarrowingConversionsCheck::handleImplicitCast( return; if (handleConditionalOperator(Context, Lhs, Rhs)) return; - SourceLocation SourceLoc = Lhs.getExprLoc(); + const SourceLocation SourceLoc = Lhs.getExprLoc(); switch (Cast.getCastKind()) { case CK_BooleanToSignedIntegral: handleBooleanToSignedIntegral(Context, SourceLoc, Lhs, Rhs); diff --git a/clang-tools-extra/clang-tidy/bugprone/NondeterministicPointerIterationOrderCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/NondeterministicPointerIterationOrderCheck.cpp index abde115d10a1b..40305cab81c7f 100644 --- a/clang-tools-extra/clang-tidy/bugprone/NondeterministicPointerIterationOrderCheck.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/NondeterministicPointerIterationOrderCheck.cpp @@ -60,7 +60,7 @@ void NondeterministicPointerIterationOrderCheck::check( TemplateArgs[0].getAsType()->isPointerType(); if (IsAlgoArgPointer) { - SourceRange R = RangeInit->getSourceRange(); + const SourceRange R = RangeInit->getSourceRange(); diag(R.getBegin(), "iteration of pointers is nondeterministic") << R; } } @@ -69,7 +69,7 @@ void NondeterministicPointerIterationOrderCheck::check( const auto *SortPointers = Result.Nodes.getNodeAs("sortsemantic"); if ((SortPointers) && !(SortPointers->getBeginLoc().isMacroID())) { - SourceRange R = SortPointers->getSourceRange(); + const SourceRange R = SortPointers->getSourceRange(); diag(R.getBegin(), "sorting pointers is nondeterministic") << R; } } diff --git a/clang-tools-extra/clang-tidy/bugprone/NotNullTerminatedResultCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/NotNullTerminatedResultCheck.cpp index 08fae7b59bae5..7198c1b1c8aaf 100644 --- a/clang-tools-extra/clang-tidy/bugprone/NotNullTerminatedResultCheck.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/NotNullTerminatedResultCheck.cpp @@ -120,18 +120,18 @@ static int getGivenLength(const MatchFinder::MatchResult &Result) { if (Result.Nodes.getNodeAs(UnknownLengthName)) return 0; - if (int Length = + if (const int Length = getLength(Result.Nodes.getNodeAs(WrongLengthExprName), Result)) return Length; - if (int Length = + if (const int Length = getLength(Result.Nodes.getNodeAs(LengthExprName), Result)) return Length; // Special case, for example 'strlen("foo")'. if (const CallExpr *StrlenCE = getStrlenExpr(Result)) if (const Expr *Arg = StrlenCE->getArg(0)->IgnoreImpCasts()) - if (int ArgLength = getLength(Arg, Result)) + if (const int ArgLength = getLength(Arg, Result)) return ArgLength; return 0; @@ -174,9 +174,9 @@ static bool isKnownDest(const MatchFinder::MatchResult &Result) { // True if the capacity of the destination array is based on the given length, // therefore we assume that it cannot overflow (e.g. 'malloc(given_length + 1)' static bool isDestBasedOnGivenLength(const MatchFinder::MatchResult &Result) { - StringRef DestCapacityExprStr = + const StringRef DestCapacityExprStr = exprToStr(getDestCapacityExpr(Result), Result).trim(); - StringRef LengthExprStr = + const StringRef LengthExprStr = exprToStr(Result.Nodes.getNodeAs(LengthExprName), Result).trim(); return !DestCapacityExprStr.empty() && !LengthExprStr.empty() && @@ -226,8 +226,9 @@ isGivenLengthEqualToSrcLength(const MatchFinder::MatchResult &Result) { if (isStringDataAndLength(Result)) return true; - int GivenLength = getGivenLength(Result); - int SrcLength = getLength(Result.Nodes.getNodeAs(SrcExprName), Result); + const int GivenLength = getGivenLength(Result); + const int SrcLength = + getLength(Result.Nodes.getNodeAs(SrcExprName), Result); if (GivenLength != 0 && SrcLength != 0 && GivenLength == SrcLength) return true; @@ -261,15 +262,15 @@ static bool isDestCapacityOverflows(const MatchFinder::MatchResult &Result) { return true; const Expr *DestCapacityExpr = getDestCapacityExpr(Result); - int DestCapacity = getLength(DestCapacityExpr, Result); - int GivenLength = getGivenLength(Result); + const int DestCapacity = getLength(DestCapacityExpr, Result); + const int GivenLength = getGivenLength(Result); if (GivenLength != 0 && DestCapacity != 0) return isGivenLengthEqualToSrcLength(Result) && DestCapacity == GivenLength; // Assume that the destination array's capacity cannot overflow if the // expression of the memory allocation contains '+ 1'. - StringRef DestCapacityExprStr = exprToStr(DestCapacityExpr, Result); + const StringRef DestCapacityExprStr = exprToStr(DestCapacityExpr, Result); if (DestCapacityExprStr.contains("+1") || DestCapacityExprStr.contains("+ 1")) return false; @@ -297,7 +298,7 @@ static void lengthExprHandle(const Expr *LengthExpr, // See whether we work with a macro. bool IsMacroDefinition = false; - StringRef LengthExprStr = exprToStr(LengthExpr, Result); + const StringRef LengthExprStr = exprToStr(LengthExpr, Result); Preprocessor::macro_iterator It = PP->macro_begin(); while (It != PP->macro_end() && !IsMacroDefinition) { if (It->first->getName() == LengthExprStr) @@ -309,7 +310,7 @@ static void lengthExprHandle(const Expr *LengthExpr, // Try to obtain an 'IntegerLiteral' and adjust it. if (!IsMacroDefinition) { if (const auto *LengthIL = dyn_cast(LengthExpr)) { - uint64_t NewLength = + const uint64_t NewLength = LengthIL->getValue().getZExtValue() + (LengthHandle == LengthHandleKind::Increase ? 1 : -1); @@ -347,7 +348,7 @@ static void lengthExprHandle(const Expr *LengthExpr, } // Try to inject the '+ 1'/'- 1' string. - bool NeedInnerParen = BO && BO->getOpcode() != BO_Add; + const bool NeedInnerParen = BO && BO->getOpcode() != BO_Add; if (NeedInnerParen) Diag << FixItHint::CreateInsertion(LengthExpr->getBeginLoc(), "("); @@ -384,8 +385,8 @@ static bool isDestExprFix(const MatchFinder::MatchResult &Result, if (!Dest) return false; - std::string TempTyStr = Dest->getType().getAsString(); - StringRef TyStr = TempTyStr; + const std::string TempTyStr = Dest->getType().getAsString(); + const StringRef TyStr = TempTyStr; if (TyStr.starts_with("char") || TyStr.starts_with("wchar_t")) return false; @@ -397,7 +398,7 @@ static bool isDestExprFix(const MatchFinder::MatchResult &Result, // increase the capacity by one to create space for the null terminator. static bool isDestCapacityFix(const MatchFinder::MatchResult &Result, DiagnosticBuilder &Diag) { - bool IsOverflows = isDestCapacityOverflows(Result); + const bool IsOverflows = isDestCapacityOverflows(Result); if (IsOverflows) if (const Expr *CapacityExpr = getDestCapacityExpr(Result)) lengthExprHandle(CapacityExpr, LengthHandleKind::Increase, Result, Diag); @@ -424,9 +425,9 @@ static void renameFunc(StringRef NewFuncName, const MatchFinder::MatchResult &Result, DiagnosticBuilder &Diag) { const auto *FunctionExpr = Result.Nodes.getNodeAs(FunctionExprName); - int FuncNameLength = + const int FuncNameLength = FunctionExpr->getDirectCallee()->getIdentifier()->getLength(); - SourceRange FuncNameRange( + const SourceRange FuncNameRange( FunctionExpr->getBeginLoc(), FunctionExpr->getBeginLoc().getLocWithOffset(FuncNameLength - 1)); @@ -451,7 +452,7 @@ static void insertDestCapacityArg(bool IsOverflows, StringRef Name, const auto *FunctionExpr = Result.Nodes.getNodeAs(FunctionExprName); SmallString<64> NewSecondArg; - if (int DestLength = getDestCapacity(Result)) { + if (const int DestLength = getDestCapacity(Result)) { NewSecondArg = Twine(IsOverflows ? DestLength + 1 : DestLength).str(); } else { NewSecondArg = @@ -470,12 +471,12 @@ static void insertNullTerminatorExpr(StringRef Name, const MatchFinder::MatchResult &Result, DiagnosticBuilder &Diag) { const auto *FunctionExpr = Result.Nodes.getNodeAs(FunctionExprName); - int FuncLocStartColumn = Result.SourceManager->getPresumedColumnNumber( + const int FuncLocStartColumn = Result.SourceManager->getPresumedColumnNumber( FunctionExpr->getBeginLoc()); - SourceRange SpaceRange( + const SourceRange SpaceRange( FunctionExpr->getBeginLoc().getLocWithOffset(-FuncLocStartColumn + 1), FunctionExpr->getBeginLoc()); - StringRef SpaceBeforeStmtStr = Lexer::getSourceText( + const StringRef SpaceBeforeStmtStr = Lexer::getSourceText( CharSourceRange::getCharRange(SpaceRange), *Result.SourceManager, Result.Context->getLangOpts(), nullptr); @@ -717,10 +718,10 @@ void NotNullTerminatedResultCheck::registerMatchers(MatchFinder *Finder) { }; auto MatchCall = [=](CallContext CC) { - std::string CharHandlerFuncName = "::" + CC.Name.str(); + const std::string CharHandlerFuncName = "::" + CC.Name.str(); // Try to match with 'wchar_t' based function calls. - std::string WcharHandlerFuncName = + const std::string WcharHandlerFuncName = "::" + (CC.Name.starts_with("mem") ? "w" + CC.Name.str() : "wcs" + CC.Name.substr(3).str()); @@ -804,7 +805,8 @@ void NotNullTerminatedResultCheck::check( if (MI) { const auto &T = MI->tokens().back(); if (T.isLiteral() && T.getLiteralData()) { - StringRef ValueStr = StringRef(T.getLiteralData(), T.getLength()); + const StringRef ValueStr = + StringRef(T.getLiteralData(), T.getLength()); llvm::APInt IntValue; ValueStr.getAsInteger(10, IntValue); AreSafeFunctionsWanted = IntValue.getZExtValue(); @@ -819,7 +821,7 @@ void NotNullTerminatedResultCheck::check( UseSafeFunctions = *AreSafeFunctionsWanted; } - StringRef Name = FunctionExpr->getDirectCallee()->getName(); + const StringRef Name = FunctionExpr->getDirectCallee()->getName(); if (Name.starts_with("mem") || Name.starts_with("wmem")) memoryHandlerFunctionFix(Name, Result); else if (Name == "strerror_s") @@ -864,16 +866,16 @@ void NotNullTerminatedResultCheck::memoryHandlerFunctionFix( void NotNullTerminatedResultCheck::memcpyFix( StringRef Name, const MatchFinder::MatchResult &Result, DiagnosticBuilder &Diag) { - bool IsOverflows = isDestCapacityFix(Result, Diag); - bool IsDestFixed = isDestExprFix(Result, Diag); + const bool IsOverflows = isDestCapacityFix(Result, Diag); + const bool IsDestFixed = isDestExprFix(Result, Diag); - bool IsCopy = + const bool IsCopy = isGivenLengthEqualToSrcLength(Result) || isDestBasedOnGivenLength(Result); - bool IsSafe = UseSafeFunctions && IsOverflows && isKnownDest(Result) && - !isDestBasedOnGivenLength(Result); + const bool IsSafe = UseSafeFunctions && IsOverflows && isKnownDest(Result) && + !isDestBasedOnGivenLength(Result); - bool IsDestLengthNotRequired = + const bool IsDestLengthNotRequired = IsSafe && getLangOpts().CPlusPlus && Result.Nodes.getNodeAs(DestArrayTyName) && !IsDestFixed; @@ -892,14 +894,14 @@ void NotNullTerminatedResultCheck::memcpyFix( void NotNullTerminatedResultCheck::memcpySFix( StringRef Name, const MatchFinder::MatchResult &Result, DiagnosticBuilder &Diag) { - bool IsOverflows = isDestCapacityFix(Result, Diag); - bool IsDestFixed = isDestExprFix(Result, Diag); + const bool IsOverflows = isDestCapacityFix(Result, Diag); + const bool IsDestFixed = isDestExprFix(Result, Diag); - bool RemoveDestLength = getLangOpts().CPlusPlus && - Result.Nodes.getNodeAs(DestArrayTyName) && - !IsDestFixed; - bool IsCopy = isGivenLengthEqualToSrcLength(Result); - bool IsSafe = IsOverflows; + const bool RemoveDestLength = + getLangOpts().CPlusPlus && + Result.Nodes.getNodeAs(DestArrayTyName) && !IsDestFixed; + const bool IsCopy = isGivenLengthEqualToSrcLength(Result); + const bool IsSafe = IsOverflows; renameMemcpy(Name, IsCopy, IsSafe, Result, Diag); @@ -932,7 +934,7 @@ void NotNullTerminatedResultCheck::memchrFix( Diag << CastRemoveFix; } - StringRef NewFuncName = (Name[0] != 'w') ? "strchr" : "wcschr"; + const StringRef NewFuncName = (Name[0] != 'w') ? "strchr" : "wcschr"; renameFunc(NewFuncName, Result, Diag); removeArg(2, Result, Diag); } @@ -940,7 +942,7 @@ void NotNullTerminatedResultCheck::memchrFix( void NotNullTerminatedResultCheck::memmoveFix( StringRef Name, const MatchFinder::MatchResult &Result, DiagnosticBuilder &Diag) const { - bool IsOverflows = isDestCapacityFix(Result, Diag); + const bool IsOverflows = isDestCapacityFix(Result, Diag); if (UseSafeFunctions && isKnownDest(Result)) { renameFunc((Name[0] != 'w') ? "memmove_s" : "wmemmove_s", Result, Diag); @@ -970,15 +972,15 @@ void NotNullTerminatedResultCheck::ncmpFix( if (const CallExpr *StrlenExpr = getStrlenExpr(Result)) { const Expr *LengthExprArg = StrlenExpr->getArg(0); - StringRef FirstExprStr = exprToStr(FirstArgExpr, Result).trim(); - StringRef SecondExprStr = exprToStr(SecondArgExpr, Result).trim(); - StringRef LengthArgStr = exprToStr(LengthExprArg, Result).trim(); + const StringRef FirstExprStr = exprToStr(FirstArgExpr, Result).trim(); + const StringRef SecondExprStr = exprToStr(SecondArgExpr, Result).trim(); + const StringRef LengthArgStr = exprToStr(LengthExprArg, Result).trim(); IsLengthTooLong = LengthArgStr == FirstExprStr || LengthArgStr == SecondExprStr; } else { - int SrcLength = + const int SrcLength = getLength(Result.Nodes.getNodeAs(SrcExprName), Result); - int GivenLength = getGivenLength(Result); + const int GivenLength = getGivenLength(Result); if (SrcLength != 0 && GivenLength != 0) IsLengthTooLong = GivenLength > SrcLength; } diff --git a/clang-tools-extra/clang-tidy/bugprone/PosixReturnCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/PosixReturnCheck.cpp index 57196adf38fb6..0084ace7d0fcc 100644 --- a/clang-tools-extra/clang-tidy/bugprone/PosixReturnCheck.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/PosixReturnCheck.cpp @@ -66,8 +66,8 @@ void PosixReturnCheck::registerMatchers(MatchFinder *Finder) { void PosixReturnCheck::check(const MatchFinder::MatchResult &Result) { if (const auto *LessThanZeroOp = Result.Nodes.getNodeAs("ltzop")) { - SourceLocation OperatorLoc = LessThanZeroOp->getOperatorLoc(); - StringRef NewBinOp = + const SourceLocation OperatorLoc = LessThanZeroOp->getOperatorLoc(); + const StringRef NewBinOp = LessThanZeroOp->getOpcode() == BinaryOperator::Opcode::BO_LT ? ">" : "<"; diag(OperatorLoc, "the comparison always evaluates to false because %0 " diff --git a/clang-tools-extra/clang-tidy/bugprone/RedundantBranchConditionCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/RedundantBranchConditionCheck.cpp index 6abe53f47b8f9..528c254dbe17e 100644 --- a/clang-tools-extra/clang-tidy/bugprone/RedundantBranchConditionCheck.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/RedundantBranchConditionCheck.cpp @@ -112,7 +112,7 @@ void RedundantBranchConditionCheck::check( if (isa(InnerIf->getCond()->IgnoreParenImpCasts()) || (BinOpCond && BinOpCond->getOpcode() == BO_LOr)) { - SourceLocation IfBegin = InnerIf->getBeginLoc(); + const SourceLocation IfBegin = InnerIf->getBeginLoc(); const Stmt *Body = InnerIf->getThen(); const Expr *OtherSide = nullptr; if (BinOpCond) { @@ -132,9 +132,9 @@ void RedundantBranchConditionCheck::check( // If the other side has side effects then keep it. if (OtherSide && OtherSide->HasSideEffects(*Result.Context)) { - SourceLocation BeforeOtherSide = + const SourceLocation BeforeOtherSide = OtherSide->getBeginLoc().getLocWithOffset(-1); - SourceLocation AfterOtherSide = + const SourceLocation AfterOtherSide = Lexer::findNextToken(OtherSide->getEndLoc(), *Result.SourceManager, getLangOpts()) ->getLocation(); @@ -161,12 +161,12 @@ void RedundantBranchConditionCheck::check( const auto *LeftDRE = dyn_cast(CondOp->getLHS()->IgnoreParenImpCasts()); if (LeftDRE && LeftDRE->getDecl() == CondVar) { - SourceLocation BeforeRHS = + const SourceLocation BeforeRHS = CondOp->getRHS()->getBeginLoc().getLocWithOffset(-1); Diag << FixItHint::CreateRemoval(CharSourceRange::getTokenRange( CondOp->getLHS()->getBeginLoc(), BeforeRHS)); } else { - SourceLocation AfterLHS = + const SourceLocation AfterLHS = Lexer::findNextToken(CondOp->getLHS()->getEndLoc(), *Result.SourceManager, getLangOpts()) ->getLocation(); diff --git a/clang-tools-extra/clang-tidy/bugprone/ReturnConstRefFromParameterCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/ReturnConstRefFromParameterCheck.cpp index a3265293bef58..1107cefe4d3c6 100644 --- a/clang-tools-extra/clang-tidy/bugprone/ReturnConstRefFromParameterCheck.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/ReturnConstRefFromParameterCheck.cpp @@ -83,7 +83,7 @@ static const Decl *findRVRefOverload(const FunctionDecl &FD, // FIXME: // 1. overload in anonymous namespace // 2. forward reference - DeclContext::lookup_result LookupResult = + const DeclContext::lookup_result LookupResult = FD.getParent()->lookup(FD.getNameInfo().getName()); if (LookupResult.isSingleResult()) { return nullptr; diff --git a/clang-tools-extra/clang-tidy/bugprone/SignalHandlerCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/SignalHandlerCheck.cpp index c262b1c05b047..b9a0b9ee3a6c6 100644 --- a/clang-tools-extra/clang-tidy/bugprone/SignalHandlerCheck.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/SignalHandlerCheck.cpp @@ -283,7 +283,7 @@ static bool isStandardFunction(const FunctionDecl *FD) { /// This includes all statements that have a class name with "CXX" prefix /// and every other statement that is declared in file ExprCXX.h. static bool isCXXOnlyStmt(const Stmt *S) { - StringRef Name = S->getStmtClassName(); + const StringRef Name = S->getStmtClassName(); if (Name.starts_with("CXX")) return true; // Check for all other class names in ExprCXX.h that have no 'CXX' prefix. @@ -317,7 +317,7 @@ static SourceRange getSourceRangeOfStmt(const Stmt *S, ASTContext &Ctx) { ParentMapContext &PM = Ctx.getParentMapContext(); DynTypedNode P = DynTypedNode::create(*S); while (P.getSourceRange().isInvalid()) { - DynTypedNodeList PL = PM.getParents(P); + const DynTypedNodeList PL = PM.getParents(P); if (PL.size() != 1) return {}; P = PL[0]; @@ -401,14 +401,15 @@ void SignalHandlerCheck::check(const MatchFinder::MatchResult &Result) { } // FIXME: Update CallGraph::getNode to use canonical decl? - CallGraphNode *HandlerNode = CG.getNode(HandlerDecl->getCanonicalDecl()); + const CallGraphNode *HandlerNode = + CG.getNode(HandlerDecl->getCanonicalDecl()); assert(HandlerNode && "Handler with body should be present in the call graph."); // Start from signal handler and visit every function call. auto Itr = llvm::df_begin(HandlerNode), ItrE = llvm::df_end(HandlerNode); while (Itr != ItrE) { const auto *CallF = dyn_cast((*Itr)->getDecl()); - unsigned int PathL = Itr.getPathLength(); + const unsigned int PathL = Itr.getPathLength(); if (CallF) { // A signal handler or a function transitively reachable from the signal // handler was found to be unsafe. @@ -435,7 +436,7 @@ void SignalHandlerCheck::check(const MatchFinder::MatchResult &Result) { bool SignalHandlerCheck::checkFunction( const FunctionDecl *FD, const Expr *CallOrRef, std::function ChainReporter) { - bool FunctionIsCalled = isa(CallOrRef); + const bool FunctionIsCalled = isa(CallOrRef); if (isStandardFunction(FD)) { if (!isStandardFunctionAsyncSafe(FD)) { @@ -492,7 +493,7 @@ bool SignalHandlerCheck::checkFunctionCPP14( for (const auto &Match : Matches) { const auto *FoundS = Match.getNodeAs("stmt"); if (isCXXOnlyStmt(FoundS)) { - SourceRange R = getSourceRangeOfStmt(FoundS, Ctx); + const SourceRange R = getSourceRangeOfStmt(FoundS, Ctx); if (R.isInvalid()) continue; diag(R.getBegin(), @@ -531,7 +532,7 @@ bool SignalHandlerCheck::isStandardFunctionAsyncSafe( } void SignalHandlerCheck::reportHandlerChain( - const llvm::df_iterator &Itr, + const llvm::df_iterator &Itr, const DeclRefExpr *HandlerRef, bool SkipPathEnd) { int CallLevel = Itr.getPathLength() - 2; assert(CallLevel >= -1 && "Empty iterator?"); diff --git a/clang-tools-extra/clang-tidy/bugprone/SignalHandlerCheck.h b/clang-tools-extra/clang-tidy/bugprone/SignalHandlerCheck.h index b5317793cbf45..67bdc9e292764 100644 --- a/clang-tools-extra/clang-tidy/bugprone/SignalHandlerCheck.h +++ b/clang-tools-extra/clang-tidy/bugprone/SignalHandlerCheck.h @@ -65,8 +65,9 @@ class SignalHandlerCheck : public ClangTidyCheck { /// registered as signal handler. /// @param SkipPathEnd If true the last item of the call chain (farthest away /// from the \c signal call) is omitted from note generation. - void reportHandlerChain(const llvm::df_iterator &Itr, - const DeclRefExpr *HandlerRef, bool SkipPathEnd); + void + reportHandlerChain(const llvm::df_iterator &Itr, + const DeclRefExpr *HandlerRef, bool SkipPathEnd); clang::CallGraph CG; diff --git a/clang-tools-extra/clang-tidy/bugprone/SignedCharMisuseCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/SignedCharMisuseCheck.cpp index 742d85bb7bab9..31c5413b8aa4c 100644 --- a/clang-tools-extra/clang-tidy/bugprone/SignedCharMisuseCheck.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/SignedCharMisuseCheck.cpp @@ -140,7 +140,7 @@ void SignedCharMisuseCheck::check(const MatchFinder::MatchResult &Result) { if (!SignedCastExpression->isValueDependent() && SignedCastExpression->getSubExpr()->EvaluateAsInt(EVResult, *Result.Context)) { - llvm::APSInt Value = EVResult.Val.getInt(); + const llvm::APSInt Value = EVResult.Val.getInt(); if (Value.isNonNegative()) return; } @@ -154,7 +154,7 @@ void SignedCharMisuseCheck::check(const MatchFinder::MatchResult &Result) { if (!UnSignedCastExpression->isValueDependent() && UnSignedCastExpression->getSubExpr()->EvaluateAsInt(EVResult, *Result.Context)) { - llvm::APSInt Value = EVResult.Val.getInt(); + const llvm::APSInt Value = EVResult.Val.getInt(); if (Value <= UnsignedASCIIUpperBound) return; } diff --git a/clang-tools-extra/clang-tidy/bugprone/SizeofExpressionCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/SizeofExpressionCheck.cpp index 2672dc74f82f7..49ba3b83795dd 100644 --- a/clang-tools-extra/clang-tidy/bugprone/SizeofExpressionCheck.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/SizeofExpressionCheck.cpp @@ -407,9 +407,9 @@ void SizeofExpressionCheck::check(const MatchFinder::MatchResult &Result) { const auto *ElementTy = Result.Nodes.getNodeAs("elem-type"); const auto *PointedTy = Result.Nodes.getNodeAs("elem-ptr-type"); - CharUnits NumeratorSize = getSizeOfType(Ctx, NumTy); - CharUnits DenominatorSize = getSizeOfType(Ctx, DenomTy); - CharUnits ElementSize = getSizeOfType(Ctx, ElementTy); + const CharUnits NumeratorSize = getSizeOfType(Ctx, NumTy); + const CharUnits DenominatorSize = getSizeOfType(Ctx, DenomTy); + const CharUnits ElementSize = getSizeOfType(Ctx, ElementTy); if (DenominatorSize > CharUnits::Zero() && !NumeratorSize.isMultipleOf(DenominatorSize)) { diff --git a/clang-tools-extra/clang-tidy/bugprone/SmartPtrArrayMismatchCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/SmartPtrArrayMismatchCheck.cpp index f76e4a722a508..af478b105fdd1 100644 --- a/clang-tools-extra/clang-tidy/bugprone/SmartPtrArrayMismatchCheck.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/SmartPtrArrayMismatchCheck.cpp @@ -93,10 +93,10 @@ void SmartPtrArrayMismatchCheck::check(const MatchFinder::MatchResult &Result) { assert(TSTypeLoc.getNumArgs() >= 1 && "Matched type should have at least 1 template argument."); - SourceRange TemplateArgumentRange = TSTypeLoc.getArgLoc(0) - .getTypeSourceInfo() - ->getTypeLoc() - .getSourceRange(); + const SourceRange TemplateArgumentRange = TSTypeLoc.getArgLoc(0) + .getTypeSourceInfo() + ->getTypeLoc() + .getSourceRange(); D << TemplateArgumentRange; if (isInSingleDeclStmt(VarOrField)) { @@ -104,7 +104,7 @@ void SmartPtrArrayMismatchCheck::check(const MatchFinder::MatchResult &Result) { if (!utils::rangeCanBeFixed(TemplateArgumentRange, &SM)) return; - SourceLocation InsertLoc = Lexer::getLocForEndOfToken( + const SourceLocation InsertLoc = Lexer::getLocForEndOfToken( TemplateArgumentRange.getEnd(), 0, SM, Ctx.getLangOpts()); D << FixItHint::CreateInsertion(InsertLoc, "[]"); } diff --git a/clang-tools-extra/clang-tidy/bugprone/SpuriouslyWakeUpFunctionsCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/SpuriouslyWakeUpFunctionsCheck.cpp index 1e8058bc4abc9..a093b094de4c7 100644 --- a/clang-tools-extra/clang-tidy/bugprone/SpuriouslyWakeUpFunctionsCheck.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/SpuriouslyWakeUpFunctionsCheck.cpp @@ -77,7 +77,7 @@ void SpuriouslyWakeUpFunctionsCheck::registerMatchers(MatchFinder *Finder) { void SpuriouslyWakeUpFunctionsCheck::check( const MatchFinder::MatchResult &Result) { const auto *MatchedWait = Result.Nodes.getNodeAs("wait"); - StringRef WaitName = MatchedWait->getDirectCallee()->getName(); + const StringRef WaitName = MatchedWait->getDirectCallee()->getName(); diag(MatchedWait->getExprLoc(), "'%0' should be placed inside a while statement %select{|or used with a " "conditional parameter}1") diff --git a/clang-tools-extra/clang-tidy/bugprone/StandaloneEmptyCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/StandaloneEmptyCheck.cpp index a7958cc229ffe..056ae4b80f109 100644 --- a/clang-tools-extra/clang-tidy/bugprone/StandaloneEmptyCheck.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/StandaloneEmptyCheck.cpp @@ -117,12 +117,13 @@ void StandaloneEmptyCheck::check(const MatchFinder::MatchResult &Result) { if (ParentReturnStmt) return; - SourceLocation MemberLoc = MemberCall->getBeginLoc(); - SourceLocation ReplacementLoc = MemberCall->getExprLoc(); - SourceRange ReplacementRange = SourceRange(ReplacementLoc, ReplacementLoc); + const SourceLocation MemberLoc = MemberCall->getBeginLoc(); + const SourceLocation ReplacementLoc = MemberCall->getExprLoc(); + const SourceRange ReplacementRange = + SourceRange(ReplacementLoc, ReplacementLoc); ASTContext &Context = MemberCall->getRecordDecl()->getASTContext(); - DeclarationName Name = + const DeclarationName Name = Context.DeclarationNames.getIdentifier(&Context.Idents.get("clear")); auto Candidates = HeuristicResolver(Context).lookupDependentName( @@ -133,11 +134,12 @@ void StandaloneEmptyCheck::check(const MatchFinder::MatchResult &Result) { !llvm::cast(ND)->isConst(); }); - bool HasClear = !Candidates.empty(); + const bool HasClear = !Candidates.empty(); if (HasClear) { const auto *Clear = llvm::cast(Candidates.at(0)); - QualType RangeType = MemberCall->getImplicitObjectArgument()->getType(); - bool QualifierIncompatible = + const QualType RangeType = + MemberCall->getImplicitObjectArgument()->getType(); + const bool QualifierIncompatible = (!Clear->isVolatile() && RangeType.isVolatileQualified()) || RangeType.isConstQualified(); if (!QualifierIncompatible) { @@ -162,8 +164,8 @@ void StandaloneEmptyCheck::check(const MatchFinder::MatchResult &Result) { if (NonMemberCall->getNumArgs() != 1) return; - SourceLocation NonMemberLoc = NonMemberCall->getExprLoc(); - SourceLocation NonMemberEndLoc = NonMemberCall->getEndLoc(); + const SourceLocation NonMemberLoc = NonMemberCall->getExprLoc(); + const SourceLocation NonMemberEndLoc = NonMemberCall->getEndLoc(); const Expr *Arg = NonMemberCall->getArg(0); CXXRecordDecl *ArgRecordDecl = Arg->getType()->getAsCXXRecordDecl(); @@ -171,7 +173,7 @@ void StandaloneEmptyCheck::check(const MatchFinder::MatchResult &Result) { return; ASTContext &Context = ArgRecordDecl->getASTContext(); - DeclarationName Name = + const DeclarationName Name = Context.DeclarationNames.getIdentifier(&Context.Idents.get("clear")); auto Candidates = HeuristicResolver(Context).lookupDependentName( @@ -182,20 +184,20 @@ void StandaloneEmptyCheck::check(const MatchFinder::MatchResult &Result) { !llvm::cast(ND)->isConst(); }); - bool HasClear = !Candidates.empty(); + const bool HasClear = !Candidates.empty(); if (HasClear) { const auto *Clear = llvm::cast(Candidates.at(0)); - bool QualifierIncompatible = + const bool QualifierIncompatible = (!Clear->isVolatile() && Arg->getType().isVolatileQualified()) || Arg->getType().isConstQualified(); if (!QualifierIncompatible) { - std::string ReplacementText = + const std::string ReplacementText = std::string(Lexer::getSourceText( CharSourceRange::getTokenRange(Arg->getSourceRange()), *Result.SourceManager, getLangOpts())) + ".clear()"; - SourceRange ReplacementRange = + const SourceRange ReplacementRange = SourceRange(NonMemberLoc, NonMemberEndLoc); diag(NonMemberLoc, "ignoring the result of '%0'; did you mean 'clear()'?") diff --git a/clang-tools-extra/clang-tidy/bugprone/StdNamespaceModificationCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/StdNamespaceModificationCheck.cpp index 13e5c03d7c4d3..1dff741be3c08 100644 --- a/clang-tools-extra/clang-tidy/bugprone/StdNamespaceModificationCheck.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/StdNamespaceModificationCheck.cpp @@ -20,12 +20,12 @@ AST_POLYMORPHIC_MATCHER_P( AST_POLYMORPHIC_SUPPORTED_TYPES(ClassTemplateSpecializationDecl, TemplateSpecializationType, FunctionDecl), clang::ast_matchers::internal::Matcher, InnerMatcher) { - ArrayRef Args = + const ArrayRef Args = clang::ast_matchers::internal::getTemplateSpecializationArgs(Node); for (const auto &Arg : Args) { if (Arg.getKind() != TemplateArgument::Pack) continue; - ArrayRef PackArgs = Arg.getPackAsArray(); + const ArrayRef PackArgs = Arg.getPackAsArray(); if (matchesFirstInRange(InnerMatcher, PackArgs.begin(), PackArgs.end(), Finder, Builder) != PackArgs.end()) return true; diff --git a/clang-tools-extra/clang-tidy/bugprone/StringConstructorCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/StringConstructorCheck.cpp index 832377e376feb..d2e631e539b78 100644 --- a/clang-tools-extra/clang-tidy/bugprone/StringConstructorCheck.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/StringConstructorCheck.cpp @@ -29,8 +29,8 @@ static std::vector removeNamespaces(const std::vector &Names) { std::vector Result; Result.reserve(Names.size()); - for (StringRef Name : Names) { - std::string::size_type ColonPos = Name.rfind(':'); + for (const StringRef Name : Names) { + const std::string::size_type ColonPos = Name.rfind(':'); Result.push_back( Name.substr(ColonPos == std::string::npos ? 0 : ColonPos + 1)); } @@ -168,7 +168,7 @@ void StringConstructorCheck::check(const MatchFinder::MatchResult &Result) { const ASTContext &Ctx = *Result.Context; const auto *E = Result.Nodes.getNodeAs("constructor"); assert(E && "missing constructor expression"); - SourceLocation Loc = E->getBeginLoc(); + const SourceLocation Loc = E->getBeginLoc(); if (Result.Nodes.getNodeAs("swapped-parameter")) { const Expr *P0 = E->getArg(0);