xref: /freebsd/contrib/llvm-project/clang/lib/Analysis/ExprMutationAnalyzer.cpp (revision 5f757f3ff9144b609b3c433dfd370cc6bdc191ad)
10b57cec5SDimitry Andric //===---------- ExprMutationAnalyzer.cpp ----------------------------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric #include "clang/Analysis/Analyses/ExprMutationAnalyzer.h"
9e8d8bef9SDimitry Andric #include "clang/AST/Expr.h"
10e8d8bef9SDimitry Andric #include "clang/AST/OperationKinds.h"
110b57cec5SDimitry Andric #include "clang/ASTMatchers/ASTMatchFinder.h"
12e8d8bef9SDimitry Andric #include "clang/ASTMatchers/ASTMatchers.h"
130b57cec5SDimitry Andric #include "llvm/ADT/STLExtras.h"
140b57cec5SDimitry Andric 
150b57cec5SDimitry Andric namespace clang {
160b57cec5SDimitry Andric using namespace ast_matchers;
170b57cec5SDimitry Andric 
180b57cec5SDimitry Andric namespace {
190b57cec5SDimitry Andric 
200b57cec5SDimitry Andric AST_MATCHER_P(LambdaExpr, hasCaptureInit, const Expr *, E) {
210b57cec5SDimitry Andric   return llvm::is_contained(Node.capture_inits(), E);
220b57cec5SDimitry Andric }
230b57cec5SDimitry Andric 
240b57cec5SDimitry Andric AST_MATCHER_P(CXXForRangeStmt, hasRangeStmt,
250b57cec5SDimitry Andric               ast_matchers::internal::Matcher<DeclStmt>, InnerMatcher) {
260b57cec5SDimitry Andric   const DeclStmt *const Range = Node.getRangeStmt();
270b57cec5SDimitry Andric   return InnerMatcher.matches(*Range, Finder, Builder);
280b57cec5SDimitry Andric }
290b57cec5SDimitry Andric 
30e8d8bef9SDimitry Andric AST_MATCHER_P(Expr, maybeEvalCommaExpr, ast_matchers::internal::Matcher<Expr>,
31e8d8bef9SDimitry Andric               InnerMatcher) {
320b57cec5SDimitry Andric   const Expr *Result = &Node;
330b57cec5SDimitry Andric   while (const auto *BOComma =
340b57cec5SDimitry Andric              dyn_cast_or_null<BinaryOperator>(Result->IgnoreParens())) {
350b57cec5SDimitry Andric     if (!BOComma->isCommaOp())
360b57cec5SDimitry Andric       break;
370b57cec5SDimitry Andric     Result = BOComma->getRHS();
380b57cec5SDimitry Andric   }
390b57cec5SDimitry Andric   return InnerMatcher.matches(*Result, Finder, Builder);
400b57cec5SDimitry Andric }
410b57cec5SDimitry Andric 
4281ad6265SDimitry Andric AST_MATCHER_P(Stmt, canResolveToExpr, ast_matchers::internal::Matcher<Stmt>,
43e8d8bef9SDimitry Andric               InnerMatcher) {
4481ad6265SDimitry Andric   auto *Exp = dyn_cast<Expr>(&Node);
4581ad6265SDimitry Andric   if (!Exp) {
4681ad6265SDimitry Andric     return stmt().matches(Node, Finder, Builder);
4781ad6265SDimitry Andric   }
4881ad6265SDimitry Andric 
49e8d8bef9SDimitry Andric   auto DerivedToBase = [](const ast_matchers::internal::Matcher<Expr> &Inner) {
50e8d8bef9SDimitry Andric     return implicitCastExpr(anyOf(hasCastKind(CK_DerivedToBase),
51e8d8bef9SDimitry Andric                                   hasCastKind(CK_UncheckedDerivedToBase)),
52e8d8bef9SDimitry Andric                             hasSourceExpression(Inner));
53e8d8bef9SDimitry Andric   };
54e8d8bef9SDimitry Andric   auto IgnoreDerivedToBase =
55e8d8bef9SDimitry Andric       [&DerivedToBase](const ast_matchers::internal::Matcher<Expr> &Inner) {
56e8d8bef9SDimitry Andric         return ignoringParens(expr(anyOf(Inner, DerivedToBase(Inner))));
57e8d8bef9SDimitry Andric       };
58e8d8bef9SDimitry Andric 
59e8d8bef9SDimitry Andric   // The 'ConditionalOperator' matches on `<anything> ? <expr> : <expr>`.
60e8d8bef9SDimitry Andric   // This matching must be recursive because `<expr>` can be anything resolving
61e8d8bef9SDimitry Andric   // to the `InnerMatcher`, for example another conditional operator.
62e8d8bef9SDimitry Andric   // The edge-case `BaseClass &b = <cond> ? DerivedVar1 : DerivedVar2;`
63e8d8bef9SDimitry Andric   // is handled, too. The implicit cast happens outside of the conditional.
64e8d8bef9SDimitry Andric   // This is matched by `IgnoreDerivedToBase(canResolveToExpr(InnerMatcher))`
65e8d8bef9SDimitry Andric   // below.
66e8d8bef9SDimitry Andric   auto const ConditionalOperator = conditionalOperator(anyOf(
67e8d8bef9SDimitry Andric       hasTrueExpression(ignoringParens(canResolveToExpr(InnerMatcher))),
68e8d8bef9SDimitry Andric       hasFalseExpression(ignoringParens(canResolveToExpr(InnerMatcher)))));
69e8d8bef9SDimitry Andric   auto const ElvisOperator = binaryConditionalOperator(anyOf(
70e8d8bef9SDimitry Andric       hasTrueExpression(ignoringParens(canResolveToExpr(InnerMatcher))),
71e8d8bef9SDimitry Andric       hasFalseExpression(ignoringParens(canResolveToExpr(InnerMatcher)))));
72e8d8bef9SDimitry Andric 
73e8d8bef9SDimitry Andric   auto const ComplexMatcher = ignoringParens(
74e8d8bef9SDimitry Andric       expr(anyOf(IgnoreDerivedToBase(InnerMatcher),
75e8d8bef9SDimitry Andric                  maybeEvalCommaExpr(IgnoreDerivedToBase(InnerMatcher)),
76e8d8bef9SDimitry Andric                  IgnoreDerivedToBase(ConditionalOperator),
77e8d8bef9SDimitry Andric                  IgnoreDerivedToBase(ElvisOperator))));
78e8d8bef9SDimitry Andric 
7981ad6265SDimitry Andric   return ComplexMatcher.matches(*Exp, Finder, Builder);
80e8d8bef9SDimitry Andric }
81e8d8bef9SDimitry Andric 
82e8d8bef9SDimitry Andric // Similar to 'hasAnyArgument', but does not work because 'InitListExpr' does
83e8d8bef9SDimitry Andric // not have the 'arguments()' method.
84e8d8bef9SDimitry Andric AST_MATCHER_P(InitListExpr, hasAnyInit, ast_matchers::internal::Matcher<Expr>,
85e8d8bef9SDimitry Andric               InnerMatcher) {
86e8d8bef9SDimitry Andric   for (const Expr *Arg : Node.inits()) {
87e8d8bef9SDimitry Andric     ast_matchers::internal::BoundNodesTreeBuilder Result(*Builder);
88e8d8bef9SDimitry Andric     if (InnerMatcher.matches(*Arg, Finder, &Result)) {
89e8d8bef9SDimitry Andric       *Builder = std::move(Result);
90e8d8bef9SDimitry Andric       return true;
91e8d8bef9SDimitry Andric     }
92e8d8bef9SDimitry Andric   }
93e8d8bef9SDimitry Andric   return false;
94e8d8bef9SDimitry Andric }
95e8d8bef9SDimitry Andric 
960b57cec5SDimitry Andric const ast_matchers::internal::VariadicDynCastAllOfMatcher<Stmt, CXXTypeidExpr>
970b57cec5SDimitry Andric     cxxTypeidExpr;
980b57cec5SDimitry Andric 
990b57cec5SDimitry Andric AST_MATCHER(CXXTypeidExpr, isPotentiallyEvaluated) {
1000b57cec5SDimitry Andric   return Node.isPotentiallyEvaluated();
1010b57cec5SDimitry Andric }
1020b57cec5SDimitry Andric 
103*5f757f3fSDimitry Andric AST_MATCHER(CXXMemberCallExpr, isConstCallee) {
104*5f757f3fSDimitry Andric   const Decl *CalleeDecl = Node.getCalleeDecl();
105*5f757f3fSDimitry Andric   const auto *VD = dyn_cast_or_null<ValueDecl>(CalleeDecl);
106*5f757f3fSDimitry Andric   if (!VD)
107*5f757f3fSDimitry Andric     return false;
108*5f757f3fSDimitry Andric   const QualType T = VD->getType().getCanonicalType();
109*5f757f3fSDimitry Andric   const auto *MPT = dyn_cast<MemberPointerType>(T);
110*5f757f3fSDimitry Andric   const auto *FPT = MPT ? cast<FunctionProtoType>(MPT->getPointeeType())
111*5f757f3fSDimitry Andric                         : dyn_cast<FunctionProtoType>(T);
112*5f757f3fSDimitry Andric   if (!FPT)
113*5f757f3fSDimitry Andric     return false;
114*5f757f3fSDimitry Andric   return FPT->isConst();
115*5f757f3fSDimitry Andric }
116*5f757f3fSDimitry Andric 
1170b57cec5SDimitry Andric AST_MATCHER_P(GenericSelectionExpr, hasControllingExpr,
1180b57cec5SDimitry Andric               ast_matchers::internal::Matcher<Expr>, InnerMatcher) {
11906c3fb27SDimitry Andric   if (Node.isTypePredicate())
12006c3fb27SDimitry Andric     return false;
1210b57cec5SDimitry Andric   return InnerMatcher.matches(*Node.getControllingExpr(), Finder, Builder);
1220b57cec5SDimitry Andric }
1230b57cec5SDimitry Andric 
1240b57cec5SDimitry Andric const auto nonConstReferenceType = [] {
1250b57cec5SDimitry Andric   return hasUnqualifiedDesugaredType(
1260b57cec5SDimitry Andric       referenceType(pointee(unless(isConstQualified()))));
1270b57cec5SDimitry Andric };
1280b57cec5SDimitry Andric 
1290b57cec5SDimitry Andric const auto nonConstPointerType = [] {
1300b57cec5SDimitry Andric   return hasUnqualifiedDesugaredType(
1310b57cec5SDimitry Andric       pointerType(pointee(unless(isConstQualified()))));
1320b57cec5SDimitry Andric };
1330b57cec5SDimitry Andric 
1340b57cec5SDimitry Andric const auto isMoveOnly = [] {
1350b57cec5SDimitry Andric   return cxxRecordDecl(
1360b57cec5SDimitry Andric       hasMethod(cxxConstructorDecl(isMoveConstructor(), unless(isDeleted()))),
1370b57cec5SDimitry Andric       hasMethod(cxxMethodDecl(isMoveAssignmentOperator(), unless(isDeleted()))),
1380b57cec5SDimitry Andric       unless(anyOf(hasMethod(cxxConstructorDecl(isCopyConstructor(),
1390b57cec5SDimitry Andric                                                 unless(isDeleted()))),
1400b57cec5SDimitry Andric                    hasMethod(cxxMethodDecl(isCopyAssignmentOperator(),
1410b57cec5SDimitry Andric                                            unless(isDeleted()))))));
1420b57cec5SDimitry Andric };
1430b57cec5SDimitry Andric 
1440b57cec5SDimitry Andric template <class T> struct NodeID;
1455ffd83dbSDimitry Andric template <> struct NodeID<Expr> { static constexpr StringRef value = "expr"; };
1465ffd83dbSDimitry Andric template <> struct NodeID<Decl> { static constexpr StringRef value = "decl"; };
1475ffd83dbSDimitry Andric constexpr StringRef NodeID<Expr>::value;
1485ffd83dbSDimitry Andric constexpr StringRef NodeID<Decl>::value;
1490b57cec5SDimitry Andric 
1500b57cec5SDimitry Andric template <class T, class F = const Stmt *(ExprMutationAnalyzer::*)(const T *)>
1510b57cec5SDimitry Andric const Stmt *tryEachMatch(ArrayRef<ast_matchers::BoundNodes> Matches,
1520b57cec5SDimitry Andric                          ExprMutationAnalyzer *Analyzer, F Finder) {
1530b57cec5SDimitry Andric   const StringRef ID = NodeID<T>::value;
1540b57cec5SDimitry Andric   for (const auto &Nodes : Matches) {
1550b57cec5SDimitry Andric     if (const Stmt *S = (Analyzer->*Finder)(Nodes.getNodeAs<T>(ID)))
1560b57cec5SDimitry Andric       return S;
1570b57cec5SDimitry Andric   }
1580b57cec5SDimitry Andric   return nullptr;
1590b57cec5SDimitry Andric }
1600b57cec5SDimitry Andric 
1610b57cec5SDimitry Andric } // namespace
1620b57cec5SDimitry Andric 
1630b57cec5SDimitry Andric const Stmt *ExprMutationAnalyzer::findMutation(const Expr *Exp) {
1640b57cec5SDimitry Andric   return findMutationMemoized(Exp,
1650b57cec5SDimitry Andric                               {&ExprMutationAnalyzer::findDirectMutation,
1660b57cec5SDimitry Andric                                &ExprMutationAnalyzer::findMemberMutation,
1670b57cec5SDimitry Andric                                &ExprMutationAnalyzer::findArrayElementMutation,
1680b57cec5SDimitry Andric                                &ExprMutationAnalyzer::findCastMutation,
1690b57cec5SDimitry Andric                                &ExprMutationAnalyzer::findRangeLoopMutation,
1700b57cec5SDimitry Andric                                &ExprMutationAnalyzer::findReferenceMutation,
1710b57cec5SDimitry Andric                                &ExprMutationAnalyzer::findFunctionArgMutation},
1720b57cec5SDimitry Andric                               Results);
1730b57cec5SDimitry Andric }
1740b57cec5SDimitry Andric 
1750b57cec5SDimitry Andric const Stmt *ExprMutationAnalyzer::findMutation(const Decl *Dec) {
1760b57cec5SDimitry Andric   return tryEachDeclRef(Dec, &ExprMutationAnalyzer::findMutation);
1770b57cec5SDimitry Andric }
1780b57cec5SDimitry Andric 
1790b57cec5SDimitry Andric const Stmt *ExprMutationAnalyzer::findPointeeMutation(const Expr *Exp) {
1800b57cec5SDimitry Andric   return findMutationMemoized(Exp, {/*TODO*/}, PointeeResults);
1810b57cec5SDimitry Andric }
1820b57cec5SDimitry Andric 
1830b57cec5SDimitry Andric const Stmt *ExprMutationAnalyzer::findPointeeMutation(const Decl *Dec) {
1840b57cec5SDimitry Andric   return tryEachDeclRef(Dec, &ExprMutationAnalyzer::findPointeeMutation);
1850b57cec5SDimitry Andric }
1860b57cec5SDimitry Andric 
1870b57cec5SDimitry Andric const Stmt *ExprMutationAnalyzer::findMutationMemoized(
1880b57cec5SDimitry Andric     const Expr *Exp, llvm::ArrayRef<MutationFinder> Finders,
1890b57cec5SDimitry Andric     ResultMap &MemoizedResults) {
1900b57cec5SDimitry Andric   const auto Memoized = MemoizedResults.find(Exp);
1910b57cec5SDimitry Andric   if (Memoized != MemoizedResults.end())
1920b57cec5SDimitry Andric     return Memoized->second;
1930b57cec5SDimitry Andric 
1940b57cec5SDimitry Andric   if (isUnevaluated(Exp))
1950b57cec5SDimitry Andric     return MemoizedResults[Exp] = nullptr;
1960b57cec5SDimitry Andric 
1970b57cec5SDimitry Andric   for (const auto &Finder : Finders) {
1980b57cec5SDimitry Andric     if (const Stmt *S = (this->*Finder)(Exp))
1990b57cec5SDimitry Andric       return MemoizedResults[Exp] = S;
2000b57cec5SDimitry Andric   }
2010b57cec5SDimitry Andric 
2020b57cec5SDimitry Andric   return MemoizedResults[Exp] = nullptr;
2030b57cec5SDimitry Andric }
2040b57cec5SDimitry Andric 
2050b57cec5SDimitry Andric const Stmt *ExprMutationAnalyzer::tryEachDeclRef(const Decl *Dec,
2060b57cec5SDimitry Andric                                                  MutationFinder Finder) {
2070b57cec5SDimitry Andric   const auto Refs =
2080b57cec5SDimitry Andric       match(findAll(declRefExpr(to(equalsNode(Dec))).bind(NodeID<Expr>::value)),
2090b57cec5SDimitry Andric             Stm, Context);
2100b57cec5SDimitry Andric   for (const auto &RefNodes : Refs) {
2110b57cec5SDimitry Andric     const auto *E = RefNodes.getNodeAs<Expr>(NodeID<Expr>::value);
2120b57cec5SDimitry Andric     if ((this->*Finder)(E))
2130b57cec5SDimitry Andric       return E;
2140b57cec5SDimitry Andric   }
2150b57cec5SDimitry Andric   return nullptr;
2160b57cec5SDimitry Andric }
2170b57cec5SDimitry Andric 
21881ad6265SDimitry Andric bool ExprMutationAnalyzer::isUnevaluated(const Stmt *Exp, const Stmt &Stm,
21981ad6265SDimitry Andric                                          ASTContext &Context) {
22081ad6265SDimitry Andric   return selectFirst<Stmt>(
2210b57cec5SDimitry Andric              NodeID<Expr>::value,
2220b57cec5SDimitry Andric              match(
2230b57cec5SDimitry Andric                  findAll(
22481ad6265SDimitry Andric                      stmt(canResolveToExpr(equalsNode(Exp)),
2250b57cec5SDimitry Andric                           anyOf(
2260b57cec5SDimitry Andric                               // `Exp` is part of the underlying expression of
2270b57cec5SDimitry Andric                               // decltype/typeof if it has an ancestor of
2280b57cec5SDimitry Andric                               // typeLoc.
2290b57cec5SDimitry Andric                               hasAncestor(typeLoc(unless(
2300b57cec5SDimitry Andric                                   hasAncestor(unaryExprOrTypeTraitExpr())))),
2310b57cec5SDimitry Andric                               hasAncestor(expr(anyOf(
2320b57cec5SDimitry Andric                                   // `UnaryExprOrTypeTraitExpr` is unevaluated
2330b57cec5SDimitry Andric                                   // unless it's sizeof on VLA.
2340b57cec5SDimitry Andric                                   unaryExprOrTypeTraitExpr(unless(sizeOfExpr(
2350b57cec5SDimitry Andric                                       hasArgumentOfType(variableArrayType())))),
2360b57cec5SDimitry Andric                                   // `CXXTypeidExpr` is unevaluated unless it's
2370b57cec5SDimitry Andric                                   // applied to an expression of glvalue of
2380b57cec5SDimitry Andric                                   // polymorphic class type.
2390b57cec5SDimitry Andric                                   cxxTypeidExpr(
2400b57cec5SDimitry Andric                                       unless(isPotentiallyEvaluated())),
2410b57cec5SDimitry Andric                                   // The controlling expression of
2420b57cec5SDimitry Andric                                   // `GenericSelectionExpr` is unevaluated.
2430b57cec5SDimitry Andric                                   genericSelectionExpr(hasControllingExpr(
2440b57cec5SDimitry Andric                                       hasDescendant(equalsNode(Exp)))),
2450b57cec5SDimitry Andric                                   cxxNoexceptExpr())))))
2460b57cec5SDimitry Andric                          .bind(NodeID<Expr>::value)),
2470b57cec5SDimitry Andric                  Stm, Context)) != nullptr;
2480b57cec5SDimitry Andric }
2490b57cec5SDimitry Andric 
25081ad6265SDimitry Andric bool ExprMutationAnalyzer::isUnevaluated(const Expr *Exp) {
25181ad6265SDimitry Andric   return isUnevaluated(Exp, Stm, Context);
25281ad6265SDimitry Andric }
25381ad6265SDimitry Andric 
2540b57cec5SDimitry Andric const Stmt *
2550b57cec5SDimitry Andric ExprMutationAnalyzer::findExprMutation(ArrayRef<BoundNodes> Matches) {
2560b57cec5SDimitry Andric   return tryEachMatch<Expr>(Matches, this, &ExprMutationAnalyzer::findMutation);
2570b57cec5SDimitry Andric }
2580b57cec5SDimitry Andric 
2590b57cec5SDimitry Andric const Stmt *
2600b57cec5SDimitry Andric ExprMutationAnalyzer::findDeclMutation(ArrayRef<BoundNodes> Matches) {
2610b57cec5SDimitry Andric   return tryEachMatch<Decl>(Matches, this, &ExprMutationAnalyzer::findMutation);
2620b57cec5SDimitry Andric }
2630b57cec5SDimitry Andric 
2640b57cec5SDimitry Andric const Stmt *ExprMutationAnalyzer::findExprPointeeMutation(
2650b57cec5SDimitry Andric     ArrayRef<ast_matchers::BoundNodes> Matches) {
2660b57cec5SDimitry Andric   return tryEachMatch<Expr>(Matches, this,
2670b57cec5SDimitry Andric                             &ExprMutationAnalyzer::findPointeeMutation);
2680b57cec5SDimitry Andric }
2690b57cec5SDimitry Andric 
2700b57cec5SDimitry Andric const Stmt *ExprMutationAnalyzer::findDeclPointeeMutation(
2710b57cec5SDimitry Andric     ArrayRef<ast_matchers::BoundNodes> Matches) {
2720b57cec5SDimitry Andric   return tryEachMatch<Decl>(Matches, this,
2730b57cec5SDimitry Andric                             &ExprMutationAnalyzer::findPointeeMutation);
2740b57cec5SDimitry Andric }
2750b57cec5SDimitry Andric 
2760b57cec5SDimitry Andric const Stmt *ExprMutationAnalyzer::findDirectMutation(const Expr *Exp) {
2770b57cec5SDimitry Andric   // LHS of any assignment operators.
2785ffd83dbSDimitry Andric   const auto AsAssignmentLhs = binaryOperator(
279e8d8bef9SDimitry Andric       isAssignmentOperator(), hasLHS(canResolveToExpr(equalsNode(Exp))));
2800b57cec5SDimitry Andric 
2810b57cec5SDimitry Andric   // Operand of increment/decrement operators.
2820b57cec5SDimitry Andric   const auto AsIncDecOperand =
2830b57cec5SDimitry Andric       unaryOperator(anyOf(hasOperatorName("++"), hasOperatorName("--")),
284e8d8bef9SDimitry Andric                     hasUnaryOperand(canResolveToExpr(equalsNode(Exp))));
2850b57cec5SDimitry Andric 
2860b57cec5SDimitry Andric   // Invoking non-const member function.
2870b57cec5SDimitry Andric   // A member function is assumed to be non-const when it is unresolved.
2880b57cec5SDimitry Andric   const auto NonConstMethod = cxxMethodDecl(unless(isConst()));
289e8d8bef9SDimitry Andric 
290e8d8bef9SDimitry Andric   const auto AsNonConstThis = expr(anyOf(
291*5f757f3fSDimitry Andric       cxxMemberCallExpr(on(canResolveToExpr(equalsNode(Exp))),
292*5f757f3fSDimitry Andric                         unless(isConstCallee())),
2930b57cec5SDimitry Andric       cxxOperatorCallExpr(callee(NonConstMethod),
294e8d8bef9SDimitry Andric                           hasArgument(0, canResolveToExpr(equalsNode(Exp)))),
295e8d8bef9SDimitry Andric       // In case of a templated type, calling overloaded operators is not
296e8d8bef9SDimitry Andric       // resolved and modelled as `binaryOperator` on a dependent type.
297e8d8bef9SDimitry Andric       // Such instances are considered a modification, because they can modify
298e8d8bef9SDimitry Andric       // in different instantiations of the template.
299*5f757f3fSDimitry Andric       binaryOperator(
300*5f757f3fSDimitry Andric           hasEitherOperand(ignoringImpCasts(canResolveToExpr(equalsNode(Exp)))),
301*5f757f3fSDimitry Andric           isTypeDependent()),
302e8d8bef9SDimitry Andric       // Within class templates and member functions the member expression might
303e8d8bef9SDimitry Andric       // not be resolved. In that case, the `callExpr` is considered to be a
304e8d8bef9SDimitry Andric       // modification.
305e8d8bef9SDimitry Andric       callExpr(
306e8d8bef9SDimitry Andric           callee(expr(anyOf(unresolvedMemberExpr(hasObjectExpression(
307e8d8bef9SDimitry Andric                                 canResolveToExpr(equalsNode(Exp)))),
308e8d8bef9SDimitry Andric                             cxxDependentScopeMemberExpr(hasObjectExpression(
309e8d8bef9SDimitry Andric                                 canResolveToExpr(equalsNode(Exp)))))))),
310e8d8bef9SDimitry Andric       // Match on a call to a known method, but the call itself is type
311e8d8bef9SDimitry Andric       // dependent (e.g. `vector<T> v; v.push(T{});` in a templated function).
312e8d8bef9SDimitry Andric       callExpr(allOf(isTypeDependent(),
313e8d8bef9SDimitry Andric                      callee(memberExpr(hasDeclaration(NonConstMethod),
314e8d8bef9SDimitry Andric                                        hasObjectExpression(canResolveToExpr(
315e8d8bef9SDimitry Andric                                            equalsNode(Exp)))))))));
3160b57cec5SDimitry Andric 
3170b57cec5SDimitry Andric   // Taking address of 'Exp'.
3180b57cec5SDimitry Andric   // We're assuming 'Exp' is mutated as soon as its address is taken, though in
3190b57cec5SDimitry Andric   // theory we can follow the pointer and see whether it escaped `Stm` or is
3200b57cec5SDimitry Andric   // dereferenced and then mutated. This is left for future improvements.
3210b57cec5SDimitry Andric   const auto AsAmpersandOperand =
3220b57cec5SDimitry Andric       unaryOperator(hasOperatorName("&"),
3230b57cec5SDimitry Andric                     // A NoOp implicit cast is adding const.
3240b57cec5SDimitry Andric                     unless(hasParent(implicitCastExpr(hasCastKind(CK_NoOp)))),
325e8d8bef9SDimitry Andric                     hasUnaryOperand(canResolveToExpr(equalsNode(Exp))));
3260b57cec5SDimitry Andric   const auto AsPointerFromArrayDecay =
3270b57cec5SDimitry Andric       castExpr(hasCastKind(CK_ArrayToPointerDecay),
3280b57cec5SDimitry Andric                unless(hasParent(arraySubscriptExpr())),
329e8d8bef9SDimitry Andric                has(canResolveToExpr(equalsNode(Exp))));
3300b57cec5SDimitry Andric   // Treat calling `operator->()` of move-only classes as taking address.
3310b57cec5SDimitry Andric   // These are typically smart pointers with unique ownership so we treat
3320b57cec5SDimitry Andric   // mutation of pointee as mutation of the smart pointer itself.
333e8d8bef9SDimitry Andric   const auto AsOperatorArrowThis = cxxOperatorCallExpr(
334e8d8bef9SDimitry Andric       hasOverloadedOperatorName("->"),
335e8d8bef9SDimitry Andric       callee(
336e8d8bef9SDimitry Andric           cxxMethodDecl(ofClass(isMoveOnly()), returns(nonConstPointerType()))),
337e8d8bef9SDimitry Andric       argumentCountIs(1), hasArgument(0, canResolveToExpr(equalsNode(Exp))));
3380b57cec5SDimitry Andric 
3390b57cec5SDimitry Andric   // Used as non-const-ref argument when calling a function.
3400b57cec5SDimitry Andric   // An argument is assumed to be non-const-ref when the function is unresolved.
3410b57cec5SDimitry Andric   // Instantiated template functions are not handled here but in
3420b57cec5SDimitry Andric   // findFunctionArgMutation which has additional smarts for handling forwarding
3430b57cec5SDimitry Andric   // references.
344e8d8bef9SDimitry Andric   const auto NonConstRefParam = forEachArgumentWithParamType(
345e8d8bef9SDimitry Andric       anyOf(canResolveToExpr(equalsNode(Exp)),
346e8d8bef9SDimitry Andric             memberExpr(hasObjectExpression(canResolveToExpr(equalsNode(Exp))))),
347e8d8bef9SDimitry Andric       nonConstReferenceType());
3480b57cec5SDimitry Andric   const auto NotInstantiated = unless(hasDeclaration(isInstantiated()));
349e8d8bef9SDimitry Andric   const auto TypeDependentCallee =
350e8d8bef9SDimitry Andric       callee(expr(anyOf(unresolvedLookupExpr(), unresolvedMemberExpr(),
351e8d8bef9SDimitry Andric                         cxxDependentScopeMemberExpr(),
352e8d8bef9SDimitry Andric                         hasType(templateTypeParmType()), isTypeDependent())));
353e8d8bef9SDimitry Andric 
3540b57cec5SDimitry Andric   const auto AsNonConstRefArg = anyOf(
3550b57cec5SDimitry Andric       callExpr(NonConstRefParam, NotInstantiated),
3560b57cec5SDimitry Andric       cxxConstructExpr(NonConstRefParam, NotInstantiated),
357e8d8bef9SDimitry Andric       callExpr(TypeDependentCallee,
358e8d8bef9SDimitry Andric                hasAnyArgument(canResolveToExpr(equalsNode(Exp)))),
359e8d8bef9SDimitry Andric       cxxUnresolvedConstructExpr(
360e8d8bef9SDimitry Andric           hasAnyArgument(canResolveToExpr(equalsNode(Exp)))),
361e8d8bef9SDimitry Andric       // Previous False Positive in the following Code:
362e8d8bef9SDimitry Andric       // `template <typename T> void f() { int i = 42; new Type<T>(i); }`
363e8d8bef9SDimitry Andric       // Where the constructor of `Type` takes its argument as reference.
364e8d8bef9SDimitry Andric       // The AST does not resolve in a `cxxConstructExpr` because it is
365e8d8bef9SDimitry Andric       // type-dependent.
366e8d8bef9SDimitry Andric       parenListExpr(hasDescendant(expr(canResolveToExpr(equalsNode(Exp))))),
367e8d8bef9SDimitry Andric       // If the initializer is for a reference type, there is no cast for
368e8d8bef9SDimitry Andric       // the variable. Values are cast to RValue first.
369e8d8bef9SDimitry Andric       initListExpr(hasAnyInit(expr(canResolveToExpr(equalsNode(Exp))))));
3700b57cec5SDimitry Andric 
3710b57cec5SDimitry Andric   // Captured by a lambda by reference.
3720b57cec5SDimitry Andric   // If we're initializing a capture with 'Exp' directly then we're initializing
3730b57cec5SDimitry Andric   // a reference capture.
3740b57cec5SDimitry Andric   // For value captures there will be an ImplicitCastExpr <LValueToRValue>.
3750b57cec5SDimitry Andric   const auto AsLambdaRefCaptureInit = lambdaExpr(hasCaptureInit(Exp));
3760b57cec5SDimitry Andric 
3770b57cec5SDimitry Andric   // Returned as non-const-ref.
3780b57cec5SDimitry Andric   // If we're returning 'Exp' directly then it's returned as non-const-ref.
3790b57cec5SDimitry Andric   // For returning by value there will be an ImplicitCastExpr <LValueToRValue>.
3800b57cec5SDimitry Andric   // For returning by const-ref there will be an ImplicitCastExpr <NoOp> (for
3810b57cec5SDimitry Andric   // adding const.)
382e8d8bef9SDimitry Andric   const auto AsNonConstRefReturn =
383e8d8bef9SDimitry Andric       returnStmt(hasReturnValue(canResolveToExpr(equalsNode(Exp))));
384e8d8bef9SDimitry Andric 
385e8d8bef9SDimitry Andric   // It is used as a non-const-reference for initalizing a range-for loop.
386e8d8bef9SDimitry Andric   const auto AsNonConstRefRangeInit = cxxForRangeStmt(
387e8d8bef9SDimitry Andric       hasRangeInit(declRefExpr(allOf(canResolveToExpr(equalsNode(Exp)),
388e8d8bef9SDimitry Andric                                      hasType(nonConstReferenceType())))));
3890b57cec5SDimitry Andric 
3905ffd83dbSDimitry Andric   const auto Matches = match(
391e8d8bef9SDimitry Andric       traverse(TK_AsIs,
392e8d8bef9SDimitry Andric                findAll(stmt(anyOf(AsAssignmentLhs, AsIncDecOperand,
393e8d8bef9SDimitry Andric                                   AsNonConstThis, AsAmpersandOperand,
394e8d8bef9SDimitry Andric                                   AsPointerFromArrayDecay, AsOperatorArrowThis,
395e8d8bef9SDimitry Andric                                   AsNonConstRefArg, AsLambdaRefCaptureInit,
396e8d8bef9SDimitry Andric                                   AsNonConstRefReturn, AsNonConstRefRangeInit))
3975ffd83dbSDimitry Andric                            .bind("stmt"))),
3980b57cec5SDimitry Andric       Stm, Context);
3990b57cec5SDimitry Andric   return selectFirst<Stmt>("stmt", Matches);
4000b57cec5SDimitry Andric }
4010b57cec5SDimitry Andric 
4020b57cec5SDimitry Andric const Stmt *ExprMutationAnalyzer::findMemberMutation(const Expr *Exp) {
4030b57cec5SDimitry Andric   // Check whether any member of 'Exp' is mutated.
4040b57cec5SDimitry Andric   const auto MemberExprs =
405e8d8bef9SDimitry Andric       match(findAll(expr(anyOf(memberExpr(hasObjectExpression(
406e8d8bef9SDimitry Andric                                    canResolveToExpr(equalsNode(Exp)))),
407e8d8bef9SDimitry Andric                                cxxDependentScopeMemberExpr(hasObjectExpression(
408*5f757f3fSDimitry Andric                                    canResolveToExpr(equalsNode(Exp)))),
409*5f757f3fSDimitry Andric                                binaryOperator(hasOperatorName(".*"),
410*5f757f3fSDimitry Andric                                               hasLHS(equalsNode(Exp)))))
4110b57cec5SDimitry Andric                         .bind(NodeID<Expr>::value)),
4120b57cec5SDimitry Andric             Stm, Context);
4130b57cec5SDimitry Andric   return findExprMutation(MemberExprs);
4140b57cec5SDimitry Andric }
4150b57cec5SDimitry Andric 
4160b57cec5SDimitry Andric const Stmt *ExprMutationAnalyzer::findArrayElementMutation(const Expr *Exp) {
4170b57cec5SDimitry Andric   // Check whether any element of an array is mutated.
418e8d8bef9SDimitry Andric   const auto SubscriptExprs =
419e8d8bef9SDimitry Andric       match(findAll(arraySubscriptExpr(
420e8d8bef9SDimitry Andric                         anyOf(hasBase(canResolveToExpr(equalsNode(Exp))),
421e8d8bef9SDimitry Andric                               hasBase(implicitCastExpr(
422e8d8bef9SDimitry Andric                                   allOf(hasCastKind(CK_ArrayToPointerDecay),
423e8d8bef9SDimitry Andric                                         hasSourceExpression(canResolveToExpr(
424e8d8bef9SDimitry Andric                                             equalsNode(Exp))))))))
4250b57cec5SDimitry Andric                         .bind(NodeID<Expr>::value)),
4260b57cec5SDimitry Andric             Stm, Context);
4270b57cec5SDimitry Andric   return findExprMutation(SubscriptExprs);
4280b57cec5SDimitry Andric }
4290b57cec5SDimitry Andric 
4300b57cec5SDimitry Andric const Stmt *ExprMutationAnalyzer::findCastMutation(const Expr *Exp) {
431e8d8bef9SDimitry Andric   // If the 'Exp' is explicitly casted to a non-const reference type the
432e8d8bef9SDimitry Andric   // 'Exp' is considered to be modified.
433e8d8bef9SDimitry Andric   const auto ExplicitCast = match(
434e8d8bef9SDimitry Andric       findAll(
435e8d8bef9SDimitry Andric           stmt(castExpr(hasSourceExpression(canResolveToExpr(equalsNode(Exp))),
436e8d8bef9SDimitry Andric                         explicitCastExpr(
437e8d8bef9SDimitry Andric                             hasDestinationType(nonConstReferenceType()))))
438e8d8bef9SDimitry Andric               .bind("stmt")),
439e8d8bef9SDimitry Andric       Stm, Context);
440e8d8bef9SDimitry Andric 
441e8d8bef9SDimitry Andric   if (const auto *CastStmt = selectFirst<Stmt>("stmt", ExplicitCast))
442e8d8bef9SDimitry Andric     return CastStmt;
443e8d8bef9SDimitry Andric 
4440b57cec5SDimitry Andric   // If 'Exp' is casted to any non-const reference type, check the castExpr.
445e8d8bef9SDimitry Andric   const auto Casts = match(
446e8d8bef9SDimitry Andric       findAll(
447e8d8bef9SDimitry Andric           expr(castExpr(hasSourceExpression(canResolveToExpr(equalsNode(Exp))),
448e8d8bef9SDimitry Andric                         anyOf(explicitCastExpr(
449e8d8bef9SDimitry Andric                                   hasDestinationType(nonConstReferenceType())),
4500b57cec5SDimitry Andric                               implicitCastExpr(hasImplicitDestinationType(
451e8d8bef9SDimitry Andric                                   nonConstReferenceType())))))
4520b57cec5SDimitry Andric               .bind(NodeID<Expr>::value)),
4530b57cec5SDimitry Andric       Stm, Context);
454e8d8bef9SDimitry Andric 
4550b57cec5SDimitry Andric   if (const Stmt *S = findExprMutation(Casts))
4560b57cec5SDimitry Andric     return S;
4570b57cec5SDimitry Andric   // Treat std::{move,forward} as cast.
4580b57cec5SDimitry Andric   const auto Calls =
4590b57cec5SDimitry Andric       match(findAll(callExpr(callee(namedDecl(
4600b57cec5SDimitry Andric                                  hasAnyName("::std::move", "::std::forward"))),
461e8d8bef9SDimitry Andric                              hasArgument(0, canResolveToExpr(equalsNode(Exp))))
4620b57cec5SDimitry Andric                         .bind("expr")),
4630b57cec5SDimitry Andric             Stm, Context);
4640b57cec5SDimitry Andric   return findExprMutation(Calls);
4650b57cec5SDimitry Andric }
4660b57cec5SDimitry Andric 
4670b57cec5SDimitry Andric const Stmt *ExprMutationAnalyzer::findRangeLoopMutation(const Expr *Exp) {
468e8d8bef9SDimitry Andric   // Keep the ordering for the specific initialization matches to happen first,
469e8d8bef9SDimitry Andric   // because it is cheaper to match all potential modifications of the loop
470e8d8bef9SDimitry Andric   // variable.
471e8d8bef9SDimitry Andric 
472e8d8bef9SDimitry Andric   // The range variable is a reference to a builtin array. In that case the
473e8d8bef9SDimitry Andric   // array is considered modified if the loop-variable is a non-const reference.
474e8d8bef9SDimitry Andric   const auto DeclStmtToNonRefToArray = declStmt(hasSingleDecl(varDecl(hasType(
475e8d8bef9SDimitry Andric       hasUnqualifiedDesugaredType(referenceType(pointee(arrayType())))))));
476972a253aSDimitry Andric   const auto RefToArrayRefToElements =
477972a253aSDimitry Andric       match(findAll(stmt(cxxForRangeStmt(
478972a253aSDimitry Andric                              hasLoopVariable(
479972a253aSDimitry Andric                                  varDecl(anyOf(hasType(nonConstReferenceType()),
480972a253aSDimitry Andric                                                hasType(nonConstPointerType())))
481e8d8bef9SDimitry Andric                                      .bind(NodeID<Decl>::value)),
482e8d8bef9SDimitry Andric                              hasRangeStmt(DeclStmtToNonRefToArray),
483e8d8bef9SDimitry Andric                              hasRangeInit(canResolveToExpr(equalsNode(Exp)))))
484e8d8bef9SDimitry Andric                         .bind("stmt")),
485e8d8bef9SDimitry Andric             Stm, Context);
486e8d8bef9SDimitry Andric 
487e8d8bef9SDimitry Andric   if (const auto *BadRangeInitFromArray =
488e8d8bef9SDimitry Andric           selectFirst<Stmt>("stmt", RefToArrayRefToElements))
489e8d8bef9SDimitry Andric     return BadRangeInitFromArray;
490e8d8bef9SDimitry Andric 
491e8d8bef9SDimitry Andric   // Small helper to match special cases in range-for loops.
492e8d8bef9SDimitry Andric   //
493e8d8bef9SDimitry Andric   // It is possible that containers do not provide a const-overload for their
494e8d8bef9SDimitry Andric   // iterator accessors. If this is the case, the variable is used non-const
495e8d8bef9SDimitry Andric   // no matter what happens in the loop. This requires special detection as it
496e8d8bef9SDimitry Andric   // is then faster to find all mutations of the loop variable.
497e8d8bef9SDimitry Andric   // It aims at a different modification as well.
498e8d8bef9SDimitry Andric   const auto HasAnyNonConstIterator =
499e8d8bef9SDimitry Andric       anyOf(allOf(hasMethod(allOf(hasName("begin"), unless(isConst()))),
500e8d8bef9SDimitry Andric                   unless(hasMethod(allOf(hasName("begin"), isConst())))),
501e8d8bef9SDimitry Andric             allOf(hasMethod(allOf(hasName("end"), unless(isConst()))),
502e8d8bef9SDimitry Andric                   unless(hasMethod(allOf(hasName("end"), isConst())))));
503e8d8bef9SDimitry Andric 
504e8d8bef9SDimitry Andric   const auto DeclStmtToNonConstIteratorContainer = declStmt(
505e8d8bef9SDimitry Andric       hasSingleDecl(varDecl(hasType(hasUnqualifiedDesugaredType(referenceType(
506e8d8bef9SDimitry Andric           pointee(hasDeclaration(cxxRecordDecl(HasAnyNonConstIterator)))))))));
507e8d8bef9SDimitry Andric 
508e8d8bef9SDimitry Andric   const auto RefToContainerBadIterators =
509e8d8bef9SDimitry Andric       match(findAll(stmt(cxxForRangeStmt(allOf(
510e8d8bef9SDimitry Andric                              hasRangeStmt(DeclStmtToNonConstIteratorContainer),
511e8d8bef9SDimitry Andric                              hasRangeInit(canResolveToExpr(equalsNode(Exp))))))
512e8d8bef9SDimitry Andric                         .bind("stmt")),
513e8d8bef9SDimitry Andric             Stm, Context);
514e8d8bef9SDimitry Andric 
515e8d8bef9SDimitry Andric   if (const auto *BadIteratorsContainer =
516e8d8bef9SDimitry Andric           selectFirst<Stmt>("stmt", RefToContainerBadIterators))
517e8d8bef9SDimitry Andric     return BadIteratorsContainer;
518e8d8bef9SDimitry Andric 
5190b57cec5SDimitry Andric   // If range for looping over 'Exp' with a non-const reference loop variable,
5200b57cec5SDimitry Andric   // check all declRefExpr of the loop variable.
5210b57cec5SDimitry Andric   const auto LoopVars =
5220b57cec5SDimitry Andric       match(findAll(cxxForRangeStmt(
5230b57cec5SDimitry Andric                 hasLoopVariable(varDecl(hasType(nonConstReferenceType()))
5240b57cec5SDimitry Andric                                     .bind(NodeID<Decl>::value)),
525e8d8bef9SDimitry Andric                 hasRangeInit(canResolveToExpr(equalsNode(Exp))))),
5260b57cec5SDimitry Andric             Stm, Context);
5270b57cec5SDimitry Andric   return findDeclMutation(LoopVars);
5280b57cec5SDimitry Andric }
5290b57cec5SDimitry Andric 
5300b57cec5SDimitry Andric const Stmt *ExprMutationAnalyzer::findReferenceMutation(const Expr *Exp) {
5310b57cec5SDimitry Andric   // Follow non-const reference returned by `operator*()` of move-only classes.
5320b57cec5SDimitry Andric   // These are typically smart pointers with unique ownership so we treat
5330b57cec5SDimitry Andric   // mutation of pointee as mutation of the smart pointer itself.
5340b57cec5SDimitry Andric   const auto Ref =
5350b57cec5SDimitry Andric       match(findAll(cxxOperatorCallExpr(
5360b57cec5SDimitry Andric                         hasOverloadedOperatorName("*"),
5370b57cec5SDimitry Andric                         callee(cxxMethodDecl(ofClass(isMoveOnly()),
5380b57cec5SDimitry Andric                                              returns(nonConstReferenceType()))),
539e8d8bef9SDimitry Andric                         argumentCountIs(1),
540e8d8bef9SDimitry Andric                         hasArgument(0, canResolveToExpr(equalsNode(Exp))))
5410b57cec5SDimitry Andric                         .bind(NodeID<Expr>::value)),
5420b57cec5SDimitry Andric             Stm, Context);
5430b57cec5SDimitry Andric   if (const Stmt *S = findExprMutation(Ref))
5440b57cec5SDimitry Andric     return S;
5450b57cec5SDimitry Andric 
5460b57cec5SDimitry Andric   // If 'Exp' is bound to a non-const reference, check all declRefExpr to that.
5470b57cec5SDimitry Andric   const auto Refs = match(
5480b57cec5SDimitry Andric       stmt(forEachDescendant(
5490b57cec5SDimitry Andric           varDecl(
5500b57cec5SDimitry Andric               hasType(nonConstReferenceType()),
551e8d8bef9SDimitry Andric               hasInitializer(anyOf(canResolveToExpr(equalsNode(Exp)),
552e8d8bef9SDimitry Andric                                    memberExpr(hasObjectExpression(
553e8d8bef9SDimitry Andric                                        canResolveToExpr(equalsNode(Exp)))))),
5540b57cec5SDimitry Andric               hasParent(declStmt().bind("stmt")),
555e8d8bef9SDimitry Andric               // Don't follow the reference in range statement, we've
556e8d8bef9SDimitry Andric               // handled that separately.
5570b57cec5SDimitry Andric               unless(hasParent(declStmt(hasParent(
5580b57cec5SDimitry Andric                   cxxForRangeStmt(hasRangeStmt(equalsBoundNode("stmt"))))))))
5590b57cec5SDimitry Andric               .bind(NodeID<Decl>::value))),
5600b57cec5SDimitry Andric       Stm, Context);
5610b57cec5SDimitry Andric   return findDeclMutation(Refs);
5620b57cec5SDimitry Andric }
5630b57cec5SDimitry Andric 
5640b57cec5SDimitry Andric const Stmt *ExprMutationAnalyzer::findFunctionArgMutation(const Expr *Exp) {
5650b57cec5SDimitry Andric   const auto NonConstRefParam = forEachArgumentWithParam(
566e8d8bef9SDimitry Andric       canResolveToExpr(equalsNode(Exp)),
5670b57cec5SDimitry Andric       parmVarDecl(hasType(nonConstReferenceType())).bind("parm"));
5680b57cec5SDimitry Andric   const auto IsInstantiated = hasDeclaration(isInstantiated());
5690b57cec5SDimitry Andric   const auto FuncDecl = hasDeclaration(functionDecl().bind("func"));
5700b57cec5SDimitry Andric   const auto Matches = match(
5715ffd83dbSDimitry Andric       traverse(
572e8d8bef9SDimitry Andric           TK_AsIs,
5735ffd83dbSDimitry Andric           findAll(
5745ffd83dbSDimitry Andric               expr(anyOf(callExpr(NonConstRefParam, IsInstantiated, FuncDecl,
5750b57cec5SDimitry Andric                                   unless(callee(namedDecl(hasAnyName(
5760b57cec5SDimitry Andric                                       "::std::move", "::std::forward"))))),
5770b57cec5SDimitry Andric                          cxxConstructExpr(NonConstRefParam, IsInstantiated,
5780b57cec5SDimitry Andric                                           FuncDecl)))
5795ffd83dbSDimitry Andric                   .bind(NodeID<Expr>::value))),
5800b57cec5SDimitry Andric       Stm, Context);
5810b57cec5SDimitry Andric   for (const auto &Nodes : Matches) {
5820b57cec5SDimitry Andric     const auto *Exp = Nodes.getNodeAs<Expr>(NodeID<Expr>::value);
5830b57cec5SDimitry Andric     const auto *Func = Nodes.getNodeAs<FunctionDecl>("func");
5840b57cec5SDimitry Andric     if (!Func->getBody() || !Func->getPrimaryTemplate())
5850b57cec5SDimitry Andric       return Exp;
5860b57cec5SDimitry Andric 
5870b57cec5SDimitry Andric     const auto *Parm = Nodes.getNodeAs<ParmVarDecl>("parm");
5880b57cec5SDimitry Andric     const ArrayRef<ParmVarDecl *> AllParams =
5890b57cec5SDimitry Andric         Func->getPrimaryTemplate()->getTemplatedDecl()->parameters();
5900b57cec5SDimitry Andric     QualType ParmType =
5910b57cec5SDimitry Andric         AllParams[std::min<size_t>(Parm->getFunctionScopeIndex(),
5920b57cec5SDimitry Andric                                    AllParams.size() - 1)]
5930b57cec5SDimitry Andric             ->getType();
5940b57cec5SDimitry Andric     if (const auto *T = ParmType->getAs<PackExpansionType>())
5950b57cec5SDimitry Andric       ParmType = T->getPattern();
5960b57cec5SDimitry Andric 
5970b57cec5SDimitry Andric     // If param type is forwarding reference, follow into the function
5980b57cec5SDimitry Andric     // definition and see whether the param is mutated inside.
5990b57cec5SDimitry Andric     if (const auto *RefType = ParmType->getAs<RValueReferenceType>()) {
6000b57cec5SDimitry Andric       if (!RefType->getPointeeType().getQualifiers() &&
6010b57cec5SDimitry Andric           RefType->getPointeeType()->getAs<TemplateTypeParmType>()) {
6020b57cec5SDimitry Andric         std::unique_ptr<FunctionParmMutationAnalyzer> &Analyzer =
6030b57cec5SDimitry Andric             FuncParmAnalyzer[Func];
6040b57cec5SDimitry Andric         if (!Analyzer)
6050b57cec5SDimitry Andric           Analyzer.reset(new FunctionParmMutationAnalyzer(*Func, Context));
6060b57cec5SDimitry Andric         if (Analyzer->findMutation(Parm))
6070b57cec5SDimitry Andric           return Exp;
6080b57cec5SDimitry Andric         continue;
6090b57cec5SDimitry Andric       }
6100b57cec5SDimitry Andric     }
6110b57cec5SDimitry Andric     // Not forwarding reference.
6120b57cec5SDimitry Andric     return Exp;
6130b57cec5SDimitry Andric   }
6140b57cec5SDimitry Andric   return nullptr;
6150b57cec5SDimitry Andric }
6160b57cec5SDimitry Andric 
6170b57cec5SDimitry Andric FunctionParmMutationAnalyzer::FunctionParmMutationAnalyzer(
6180b57cec5SDimitry Andric     const FunctionDecl &Func, ASTContext &Context)
6190b57cec5SDimitry Andric     : BodyAnalyzer(*Func.getBody(), Context) {
6200b57cec5SDimitry Andric   if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(&Func)) {
6210b57cec5SDimitry Andric     // CXXCtorInitializer might also mutate Param but they're not part of
6220b57cec5SDimitry Andric     // function body, check them eagerly here since they're typically trivial.
6230b57cec5SDimitry Andric     for (const CXXCtorInitializer *Init : Ctor->inits()) {
6240b57cec5SDimitry Andric       ExprMutationAnalyzer InitAnalyzer(*Init->getInit(), Context);
6250b57cec5SDimitry Andric       for (const ParmVarDecl *Parm : Ctor->parameters()) {
62606c3fb27SDimitry Andric         if (Results.contains(Parm))
6270b57cec5SDimitry Andric           continue;
6280b57cec5SDimitry Andric         if (const Stmt *S = InitAnalyzer.findMutation(Parm))
6290b57cec5SDimitry Andric           Results[Parm] = S;
6300b57cec5SDimitry Andric       }
6310b57cec5SDimitry Andric     }
6320b57cec5SDimitry Andric   }
6330b57cec5SDimitry Andric }
6340b57cec5SDimitry Andric 
6350b57cec5SDimitry Andric const Stmt *
6360b57cec5SDimitry Andric FunctionParmMutationAnalyzer::findMutation(const ParmVarDecl *Parm) {
6370b57cec5SDimitry Andric   const auto Memoized = Results.find(Parm);
6380b57cec5SDimitry Andric   if (Memoized != Results.end())
6390b57cec5SDimitry Andric     return Memoized->second;
6400b57cec5SDimitry Andric 
6410b57cec5SDimitry Andric   if (const Stmt *S = BodyAnalyzer.findMutation(Parm))
6420b57cec5SDimitry Andric     return Results[Parm] = S;
6430b57cec5SDimitry Andric 
6440b57cec5SDimitry Andric   return Results[Parm] = nullptr;
6450b57cec5SDimitry Andric }
6460b57cec5SDimitry Andric 
6470b57cec5SDimitry Andric } // namespace clang
648