xref: /llvm-project/clang/lib/Analysis/ExprMutationAnalyzer.cpp (revision 6eb372e4e46a6dc4511f454b6501e93eb4cad22d)
1 //===---------- ExprMutationAnalyzer.cpp ----------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 #include "clang/Analysis/Analyses/ExprMutationAnalyzer.h"
9 #include "clang/AST/Expr.h"
10 #include "clang/AST/OperationKinds.h"
11 #include "clang/ASTMatchers/ASTMatchFinder.h"
12 #include "clang/ASTMatchers/ASTMatchers.h"
13 #include "llvm/ADT/STLExtras.h"
14 
15 namespace clang {
16 using namespace ast_matchers;
17 
18 // Check if result of Source expression could be a Target expression.
19 // Checks:
20 //  - Implicit Casts
21 //  - Binary Operators
22 //  - ConditionalOperator
23 //  - BinaryConditionalOperator
24 static bool canExprResolveTo(const Expr *Source, const Expr *Target) {
25 
26   const auto IgnoreDerivedToBase = [](const Expr *E, auto Matcher) {
27     if (Matcher(E))
28       return true;
29     if (const auto *Cast = dyn_cast<ImplicitCastExpr>(E)) {
30       if ((Cast->getCastKind() == CK_DerivedToBase ||
31            Cast->getCastKind() == CK_UncheckedDerivedToBase) &&
32           Matcher(Cast->getSubExpr()))
33         return true;
34     }
35     return false;
36   };
37 
38   const auto EvalCommaExpr = [](const Expr *E, auto Matcher) {
39     const Expr *Result = E;
40     while (const auto *BOComma =
41                dyn_cast_or_null<BinaryOperator>(Result->IgnoreParens())) {
42       if (!BOComma->isCommaOp())
43         break;
44       Result = BOComma->getRHS();
45     }
46 
47     return Result != E && Matcher(Result);
48   };
49 
50   // The 'ConditionalOperatorM' matches on `<anything> ? <expr> : <expr>`.
51   // This matching must be recursive because `<expr>` can be anything resolving
52   // to the `InnerMatcher`, for example another conditional operator.
53   // The edge-case `BaseClass &b = <cond> ? DerivedVar1 : DerivedVar2;`
54   // is handled, too. The implicit cast happens outside of the conditional.
55   // This is matched by `IgnoreDerivedToBase(canResolveToExpr(InnerMatcher))`
56   // below.
57   const auto ConditionalOperatorM = [Target](const Expr *E) {
58     if (const auto *OP = dyn_cast<ConditionalOperator>(E)) {
59       if (const auto *TE = OP->getTrueExpr()->IgnoreParens())
60         if (canExprResolveTo(TE, Target))
61           return true;
62       if (const auto *FE = OP->getFalseExpr()->IgnoreParens())
63         if (canExprResolveTo(FE, Target))
64           return true;
65     }
66     return false;
67   };
68 
69   const auto ElvisOperator = [Target](const Expr *E) {
70     if (const auto *OP = dyn_cast<BinaryConditionalOperator>(E)) {
71       if (const auto *TE = OP->getTrueExpr()->IgnoreParens())
72         if (canExprResolveTo(TE, Target))
73           return true;
74       if (const auto *FE = OP->getFalseExpr()->IgnoreParens())
75         if (canExprResolveTo(FE, Target))
76           return true;
77     }
78     return false;
79   };
80 
81   const Expr *SourceExprP = Source->IgnoreParens();
82   return IgnoreDerivedToBase(SourceExprP,
83                              [&](const Expr *E) {
84                                return E == Target || ConditionalOperatorM(E) ||
85                                       ElvisOperator(E);
86                              }) ||
87          EvalCommaExpr(SourceExprP, [&](const Expr *E) {
88            return IgnoreDerivedToBase(
89                E->IgnoreParens(), [&](const Expr *EE) { return EE == Target; });
90          });
91 }
92 
93 namespace {
94 
95 AST_MATCHER_P(LambdaExpr, hasCaptureInit, const Expr *, E) {
96   return llvm::is_contained(Node.capture_inits(), E);
97 }
98 
99 AST_MATCHER_P(CXXForRangeStmt, hasRangeStmt,
100               ast_matchers::internal::Matcher<DeclStmt>, InnerMatcher) {
101   const DeclStmt *const Range = Node.getRangeStmt();
102   return InnerMatcher.matches(*Range, Finder, Builder);
103 }
104 
105 AST_MATCHER_P(Stmt, canResolveToExpr, const Stmt *, Inner) {
106   auto *Exp = dyn_cast<Expr>(&Node);
107   if (!Exp)
108     return true;
109   auto *Target = dyn_cast<Expr>(Inner);
110   if (!Target)
111     return false;
112   return canExprResolveTo(Exp, Target);
113 }
114 
115 // Similar to 'hasAnyArgument', but does not work because 'InitListExpr' does
116 // not have the 'arguments()' method.
117 AST_MATCHER_P(InitListExpr, hasAnyInit, ast_matchers::internal::Matcher<Expr>,
118               InnerMatcher) {
119   for (const Expr *Arg : Node.inits()) {
120     ast_matchers::internal::BoundNodesTreeBuilder Result(*Builder);
121     if (InnerMatcher.matches(*Arg, Finder, &Result)) {
122       *Builder = std::move(Result);
123       return true;
124     }
125   }
126   return false;
127 }
128 
129 const ast_matchers::internal::VariadicDynCastAllOfMatcher<Stmt, CXXTypeidExpr>
130     cxxTypeidExpr;
131 
132 AST_MATCHER(CXXTypeidExpr, isPotentiallyEvaluated) {
133   return Node.isPotentiallyEvaluated();
134 }
135 
136 AST_MATCHER(CXXMemberCallExpr, isConstCallee) {
137   const Decl *CalleeDecl = Node.getCalleeDecl();
138   const auto *VD = dyn_cast_or_null<ValueDecl>(CalleeDecl);
139   if (!VD)
140     return false;
141   const QualType T = VD->getType().getCanonicalType();
142   const auto *MPT = dyn_cast<MemberPointerType>(T);
143   const auto *FPT = MPT ? cast<FunctionProtoType>(MPT->getPointeeType())
144                         : dyn_cast<FunctionProtoType>(T);
145   if (!FPT)
146     return false;
147   return FPT->isConst();
148 }
149 
150 AST_MATCHER_P(GenericSelectionExpr, hasControllingExpr,
151               ast_matchers::internal::Matcher<Expr>, InnerMatcher) {
152   if (Node.isTypePredicate())
153     return false;
154   return InnerMatcher.matches(*Node.getControllingExpr(), Finder, Builder);
155 }
156 
157 template <typename T>
158 ast_matchers::internal::Matcher<T>
159 findFirst(const ast_matchers::internal::Matcher<T> &Matcher) {
160   return anyOf(Matcher, hasDescendant(Matcher));
161 }
162 
163 const auto nonConstReferenceType = [] {
164   return hasUnqualifiedDesugaredType(
165       referenceType(pointee(unless(isConstQualified()))));
166 };
167 
168 const auto nonConstPointerType = [] {
169   return hasUnqualifiedDesugaredType(
170       pointerType(pointee(unless(isConstQualified()))));
171 };
172 
173 const auto isMoveOnly = [] {
174   return cxxRecordDecl(
175       hasMethod(cxxConstructorDecl(isMoveConstructor(), unless(isDeleted()))),
176       hasMethod(cxxMethodDecl(isMoveAssignmentOperator(), unless(isDeleted()))),
177       unless(anyOf(hasMethod(cxxConstructorDecl(isCopyConstructor(),
178                                                 unless(isDeleted()))),
179                    hasMethod(cxxMethodDecl(isCopyAssignmentOperator(),
180                                            unless(isDeleted()))))));
181 };
182 
183 template <class T> struct NodeID;
184 template <> struct NodeID<Expr> { static constexpr StringRef value = "expr"; };
185 template <> struct NodeID<Decl> { static constexpr StringRef value = "decl"; };
186 constexpr StringRef NodeID<Expr>::value;
187 constexpr StringRef NodeID<Decl>::value;
188 
189 template <class T, class F = const Stmt *(ExprMutationAnalyzer::*)(const T *)>
190 const Stmt *tryEachMatch(ArrayRef<ast_matchers::BoundNodes> Matches,
191                          ExprMutationAnalyzer *Analyzer, F Finder) {
192   const StringRef ID = NodeID<T>::value;
193   for (const auto &Nodes : Matches) {
194     if (const Stmt *S = (Analyzer->*Finder)(Nodes.getNodeAs<T>(ID)))
195       return S;
196   }
197   return nullptr;
198 }
199 
200 } // namespace
201 
202 const Stmt *ExprMutationAnalyzer::findMutation(const Expr *Exp) {
203   return findMutationMemoized(Exp,
204                               {&ExprMutationAnalyzer::findDirectMutation,
205                                &ExprMutationAnalyzer::findMemberMutation,
206                                &ExprMutationAnalyzer::findArrayElementMutation,
207                                &ExprMutationAnalyzer::findCastMutation,
208                                &ExprMutationAnalyzer::findRangeLoopMutation,
209                                &ExprMutationAnalyzer::findReferenceMutation,
210                                &ExprMutationAnalyzer::findFunctionArgMutation},
211                               Results);
212 }
213 
214 const Stmt *ExprMutationAnalyzer::findMutation(const Decl *Dec) {
215   return tryEachDeclRef(Dec, &ExprMutationAnalyzer::findMutation);
216 }
217 
218 const Stmt *ExprMutationAnalyzer::findPointeeMutation(const Expr *Exp) {
219   return findMutationMemoized(Exp, {/*TODO*/}, PointeeResults);
220 }
221 
222 const Stmt *ExprMutationAnalyzer::findPointeeMutation(const Decl *Dec) {
223   return tryEachDeclRef(Dec, &ExprMutationAnalyzer::findPointeeMutation);
224 }
225 
226 const Stmt *ExprMutationAnalyzer::findMutationMemoized(
227     const Expr *Exp, llvm::ArrayRef<MutationFinder> Finders,
228     ResultMap &MemoizedResults) {
229   const auto Memoized = MemoizedResults.find(Exp);
230   if (Memoized != MemoizedResults.end())
231     return Memoized->second;
232 
233   if (isUnevaluated(Exp))
234     return MemoizedResults[Exp] = nullptr;
235 
236   for (const auto &Finder : Finders) {
237     if (const Stmt *S = (this->*Finder)(Exp))
238       return MemoizedResults[Exp] = S;
239   }
240 
241   return MemoizedResults[Exp] = nullptr;
242 }
243 
244 const Stmt *ExprMutationAnalyzer::tryEachDeclRef(const Decl *Dec,
245                                                  MutationFinder Finder) {
246   const auto Refs =
247       match(findAll(declRefExpr(to(equalsNode(Dec))).bind(NodeID<Expr>::value)),
248             Stm, Context);
249   for (const auto &RefNodes : Refs) {
250     const auto *E = RefNodes.getNodeAs<Expr>(NodeID<Expr>::value);
251     if ((this->*Finder)(E))
252       return E;
253   }
254   return nullptr;
255 }
256 
257 bool ExprMutationAnalyzer::isUnevaluated(const Stmt *Exp, const Stmt &Stm,
258                                          ASTContext &Context) {
259   return selectFirst<Stmt>(
260              NodeID<Expr>::value,
261              match(
262                  findFirst(
263                      stmt(canResolveToExpr(Exp),
264                           anyOf(
265                               // `Exp` is part of the underlying expression of
266                               // decltype/typeof if it has an ancestor of
267                               // typeLoc.
268                               hasAncestor(typeLoc(unless(
269                                   hasAncestor(unaryExprOrTypeTraitExpr())))),
270                               hasAncestor(expr(anyOf(
271                                   // `UnaryExprOrTypeTraitExpr` is unevaluated
272                                   // unless it's sizeof on VLA.
273                                   unaryExprOrTypeTraitExpr(unless(sizeOfExpr(
274                                       hasArgumentOfType(variableArrayType())))),
275                                   // `CXXTypeidExpr` is unevaluated unless it's
276                                   // applied to an expression of glvalue of
277                                   // polymorphic class type.
278                                   cxxTypeidExpr(
279                                       unless(isPotentiallyEvaluated())),
280                                   // The controlling expression of
281                                   // `GenericSelectionExpr` is unevaluated.
282                                   genericSelectionExpr(hasControllingExpr(
283                                       hasDescendant(equalsNode(Exp)))),
284                                   cxxNoexceptExpr())))))
285                          .bind(NodeID<Expr>::value)),
286                  Stm, Context)) != nullptr;
287 }
288 
289 bool ExprMutationAnalyzer::isUnevaluated(const Expr *Exp) {
290   return isUnevaluated(Exp, Stm, Context);
291 }
292 
293 const Stmt *
294 ExprMutationAnalyzer::findExprMutation(ArrayRef<BoundNodes> Matches) {
295   return tryEachMatch<Expr>(Matches, this, &ExprMutationAnalyzer::findMutation);
296 }
297 
298 const Stmt *
299 ExprMutationAnalyzer::findDeclMutation(ArrayRef<BoundNodes> Matches) {
300   return tryEachMatch<Decl>(Matches, this, &ExprMutationAnalyzer::findMutation);
301 }
302 
303 const Stmt *ExprMutationAnalyzer::findExprPointeeMutation(
304     ArrayRef<ast_matchers::BoundNodes> Matches) {
305   return tryEachMatch<Expr>(Matches, this,
306                             &ExprMutationAnalyzer::findPointeeMutation);
307 }
308 
309 const Stmt *ExprMutationAnalyzer::findDeclPointeeMutation(
310     ArrayRef<ast_matchers::BoundNodes> Matches) {
311   return tryEachMatch<Decl>(Matches, this,
312                             &ExprMutationAnalyzer::findPointeeMutation);
313 }
314 
315 const Stmt *ExprMutationAnalyzer::findDirectMutation(const Expr *Exp) {
316   // LHS of any assignment operators.
317   const auto AsAssignmentLhs =
318       binaryOperator(isAssignmentOperator(), hasLHS(canResolveToExpr(Exp)));
319 
320   // Operand of increment/decrement operators.
321   const auto AsIncDecOperand =
322       unaryOperator(anyOf(hasOperatorName("++"), hasOperatorName("--")),
323                     hasUnaryOperand(canResolveToExpr(Exp)));
324 
325   // Invoking non-const member function.
326   // A member function is assumed to be non-const when it is unresolved.
327   const auto NonConstMethod = cxxMethodDecl(unless(isConst()));
328 
329   const auto AsNonConstThis = expr(anyOf(
330       cxxMemberCallExpr(on(canResolveToExpr(Exp)), unless(isConstCallee())),
331       cxxOperatorCallExpr(callee(NonConstMethod),
332                           hasArgument(0, canResolveToExpr(Exp))),
333       // In case of a templated type, calling overloaded operators is not
334       // resolved and modelled as `binaryOperator` on a dependent type.
335       // Such instances are considered a modification, because they can modify
336       // in different instantiations of the template.
337       binaryOperator(isTypeDependent(),
338                      hasEitherOperand(ignoringImpCasts(canResolveToExpr(Exp)))),
339       // Within class templates and member functions the member expression might
340       // not be resolved. In that case, the `callExpr` is considered to be a
341       // modification.
342       callExpr(callee(expr(anyOf(
343           unresolvedMemberExpr(hasObjectExpression(canResolveToExpr(Exp))),
344           cxxDependentScopeMemberExpr(
345               hasObjectExpression(canResolveToExpr(Exp))))))),
346       // Match on a call to a known method, but the call itself is type
347       // dependent (e.g. `vector<T> v; v.push(T{});` in a templated function).
348       callExpr(allOf(
349           isTypeDependent(),
350           callee(memberExpr(hasDeclaration(NonConstMethod),
351                             hasObjectExpression(canResolveToExpr(Exp))))))));
352 
353   // Taking address of 'Exp'.
354   // We're assuming 'Exp' is mutated as soon as its address is taken, though in
355   // theory we can follow the pointer and see whether it escaped `Stm` or is
356   // dereferenced and then mutated. This is left for future improvements.
357   const auto AsAmpersandOperand =
358       unaryOperator(hasOperatorName("&"),
359                     // A NoOp implicit cast is adding const.
360                     unless(hasParent(implicitCastExpr(hasCastKind(CK_NoOp)))),
361                     hasUnaryOperand(canResolveToExpr(Exp)));
362   const auto AsPointerFromArrayDecay = castExpr(
363       hasCastKind(CK_ArrayToPointerDecay),
364       unless(hasParent(arraySubscriptExpr())), has(canResolveToExpr(Exp)));
365   // Treat calling `operator->()` of move-only classes as taking address.
366   // These are typically smart pointers with unique ownership so we treat
367   // mutation of pointee as mutation of the smart pointer itself.
368   const auto AsOperatorArrowThis = cxxOperatorCallExpr(
369       hasOverloadedOperatorName("->"),
370       callee(
371           cxxMethodDecl(ofClass(isMoveOnly()), returns(nonConstPointerType()))),
372       argumentCountIs(1), hasArgument(0, canResolveToExpr(Exp)));
373 
374   // Used as non-const-ref argument when calling a function.
375   // An argument is assumed to be non-const-ref when the function is unresolved.
376   // Instantiated template functions are not handled here but in
377   // findFunctionArgMutation which has additional smarts for handling forwarding
378   // references.
379   const auto NonConstRefParam = forEachArgumentWithParamType(
380       anyOf(canResolveToExpr(Exp),
381             memberExpr(hasObjectExpression(canResolveToExpr(Exp)))),
382       nonConstReferenceType());
383   const auto NotInstantiated = unless(hasDeclaration(isInstantiated()));
384   const auto TypeDependentCallee =
385       callee(expr(anyOf(unresolvedLookupExpr(), unresolvedMemberExpr(),
386                         cxxDependentScopeMemberExpr(),
387                         hasType(templateTypeParmType()), isTypeDependent())));
388 
389   const auto AsNonConstRefArg = anyOf(
390       callExpr(NonConstRefParam, NotInstantiated),
391       cxxConstructExpr(NonConstRefParam, NotInstantiated),
392       callExpr(TypeDependentCallee, hasAnyArgument(canResolveToExpr(Exp))),
393       cxxUnresolvedConstructExpr(hasAnyArgument(canResolveToExpr(Exp))),
394       // Previous False Positive in the following Code:
395       // `template <typename T> void f() { int i = 42; new Type<T>(i); }`
396       // Where the constructor of `Type` takes its argument as reference.
397       // The AST does not resolve in a `cxxConstructExpr` because it is
398       // type-dependent.
399       parenListExpr(hasDescendant(expr(canResolveToExpr(Exp)))),
400       // If the initializer is for a reference type, there is no cast for
401       // the variable. Values are cast to RValue first.
402       initListExpr(hasAnyInit(expr(canResolveToExpr(Exp)))));
403 
404   // Captured by a lambda by reference.
405   // If we're initializing a capture with 'Exp' directly then we're initializing
406   // a reference capture.
407   // For value captures there will be an ImplicitCastExpr <LValueToRValue>.
408   const auto AsLambdaRefCaptureInit = lambdaExpr(hasCaptureInit(Exp));
409 
410   // Returned as non-const-ref.
411   // If we're returning 'Exp' directly then it's returned as non-const-ref.
412   // For returning by value there will be an ImplicitCastExpr <LValueToRValue>.
413   // For returning by const-ref there will be an ImplicitCastExpr <NoOp> (for
414   // adding const.)
415   const auto AsNonConstRefReturn =
416       returnStmt(hasReturnValue(canResolveToExpr(Exp)));
417 
418   // It is used as a non-const-reference for initalizing a range-for loop.
419   const auto AsNonConstRefRangeInit = cxxForRangeStmt(hasRangeInit(declRefExpr(
420       allOf(canResolveToExpr(Exp), hasType(nonConstReferenceType())))));
421 
422   const auto Matches = match(
423       traverse(
424           TK_AsIs,
425           findFirst(stmt(anyOf(AsAssignmentLhs, AsIncDecOperand, AsNonConstThis,
426                                AsAmpersandOperand, AsPointerFromArrayDecay,
427                                AsOperatorArrowThis, AsNonConstRefArg,
428                                AsLambdaRefCaptureInit, AsNonConstRefReturn,
429                                AsNonConstRefRangeInit))
430                         .bind("stmt"))),
431       Stm, Context);
432   return selectFirst<Stmt>("stmt", Matches);
433 }
434 
435 const Stmt *ExprMutationAnalyzer::findMemberMutation(const Expr *Exp) {
436   // Check whether any member of 'Exp' is mutated.
437   const auto MemberExprs = match(
438       findAll(expr(anyOf(memberExpr(hasObjectExpression(canResolveToExpr(Exp))),
439                          cxxDependentScopeMemberExpr(
440                              hasObjectExpression(canResolveToExpr(Exp))),
441                          binaryOperator(hasOperatorName(".*"),
442                                         hasLHS(equalsNode(Exp)))))
443                   .bind(NodeID<Expr>::value)),
444       Stm, Context);
445   return findExprMutation(MemberExprs);
446 }
447 
448 const Stmt *ExprMutationAnalyzer::findArrayElementMutation(const Expr *Exp) {
449   // Check whether any element of an array is mutated.
450   const auto SubscriptExprs = match(
451       findAll(arraySubscriptExpr(
452                   anyOf(hasBase(canResolveToExpr(Exp)),
453                         hasBase(implicitCastExpr(allOf(
454                             hasCastKind(CK_ArrayToPointerDecay),
455                             hasSourceExpression(canResolveToExpr(Exp)))))))
456                   .bind(NodeID<Expr>::value)),
457       Stm, Context);
458   return findExprMutation(SubscriptExprs);
459 }
460 
461 const Stmt *ExprMutationAnalyzer::findCastMutation(const Expr *Exp) {
462   // If the 'Exp' is explicitly casted to a non-const reference type the
463   // 'Exp' is considered to be modified.
464   const auto ExplicitCast =
465       match(findFirst(stmt(castExpr(hasSourceExpression(canResolveToExpr(Exp)),
466                                     explicitCastExpr(hasDestinationType(
467                                         nonConstReferenceType()))))
468                           .bind("stmt")),
469             Stm, Context);
470 
471   if (const auto *CastStmt = selectFirst<Stmt>("stmt", ExplicitCast))
472     return CastStmt;
473 
474   // If 'Exp' is casted to any non-const reference type, check the castExpr.
475   const auto Casts = match(
476       findAll(expr(castExpr(hasSourceExpression(canResolveToExpr(Exp)),
477                             anyOf(explicitCastExpr(hasDestinationType(
478                                       nonConstReferenceType())),
479                                   implicitCastExpr(hasImplicitDestinationType(
480                                       nonConstReferenceType())))))
481                   .bind(NodeID<Expr>::value)),
482       Stm, Context);
483 
484   if (const Stmt *S = findExprMutation(Casts))
485     return S;
486   // Treat std::{move,forward} as cast.
487   const auto Calls =
488       match(findAll(callExpr(callee(namedDecl(
489                                  hasAnyName("::std::move", "::std::forward"))),
490                              hasArgument(0, canResolveToExpr(Exp)))
491                         .bind("expr")),
492             Stm, Context);
493   return findExprMutation(Calls);
494 }
495 
496 const Stmt *ExprMutationAnalyzer::findRangeLoopMutation(const Expr *Exp) {
497   // Keep the ordering for the specific initialization matches to happen first,
498   // because it is cheaper to match all potential modifications of the loop
499   // variable.
500 
501   // The range variable is a reference to a builtin array. In that case the
502   // array is considered modified if the loop-variable is a non-const reference.
503   const auto DeclStmtToNonRefToArray = declStmt(hasSingleDecl(varDecl(hasType(
504       hasUnqualifiedDesugaredType(referenceType(pointee(arrayType())))))));
505   const auto RefToArrayRefToElements = match(
506       findFirst(stmt(cxxForRangeStmt(
507                          hasLoopVariable(
508                              varDecl(anyOf(hasType(nonConstReferenceType()),
509                                            hasType(nonConstPointerType())))
510                                  .bind(NodeID<Decl>::value)),
511                          hasRangeStmt(DeclStmtToNonRefToArray),
512                          hasRangeInit(canResolveToExpr(Exp))))
513                     .bind("stmt")),
514       Stm, Context);
515 
516   if (const auto *BadRangeInitFromArray =
517           selectFirst<Stmt>("stmt", RefToArrayRefToElements))
518     return BadRangeInitFromArray;
519 
520   // Small helper to match special cases in range-for loops.
521   //
522   // It is possible that containers do not provide a const-overload for their
523   // iterator accessors. If this is the case, the variable is used non-const
524   // no matter what happens in the loop. This requires special detection as it
525   // is then faster to find all mutations of the loop variable.
526   // It aims at a different modification as well.
527   const auto HasAnyNonConstIterator =
528       anyOf(allOf(hasMethod(allOf(hasName("begin"), unless(isConst()))),
529                   unless(hasMethod(allOf(hasName("begin"), isConst())))),
530             allOf(hasMethod(allOf(hasName("end"), unless(isConst()))),
531                   unless(hasMethod(allOf(hasName("end"), isConst())))));
532 
533   const auto DeclStmtToNonConstIteratorContainer = declStmt(
534       hasSingleDecl(varDecl(hasType(hasUnqualifiedDesugaredType(referenceType(
535           pointee(hasDeclaration(cxxRecordDecl(HasAnyNonConstIterator)))))))));
536 
537   const auto RefToContainerBadIterators = match(
538       findFirst(stmt(cxxForRangeStmt(allOf(
539                          hasRangeStmt(DeclStmtToNonConstIteratorContainer),
540                          hasRangeInit(canResolveToExpr(Exp)))))
541                     .bind("stmt")),
542       Stm, Context);
543 
544   if (const auto *BadIteratorsContainer =
545           selectFirst<Stmt>("stmt", RefToContainerBadIterators))
546     return BadIteratorsContainer;
547 
548   // If range for looping over 'Exp' with a non-const reference loop variable,
549   // check all declRefExpr of the loop variable.
550   const auto LoopVars =
551       match(findAll(cxxForRangeStmt(
552                 hasLoopVariable(varDecl(hasType(nonConstReferenceType()))
553                                     .bind(NodeID<Decl>::value)),
554                 hasRangeInit(canResolveToExpr(Exp)))),
555             Stm, Context);
556   return findDeclMutation(LoopVars);
557 }
558 
559 const Stmt *ExprMutationAnalyzer::findReferenceMutation(const Expr *Exp) {
560   // Follow non-const reference returned by `operator*()` of move-only classes.
561   // These are typically smart pointers with unique ownership so we treat
562   // mutation of pointee as mutation of the smart pointer itself.
563   const auto Ref = match(
564       findAll(cxxOperatorCallExpr(
565                   hasOverloadedOperatorName("*"),
566                   callee(cxxMethodDecl(ofClass(isMoveOnly()),
567                                        returns(nonConstReferenceType()))),
568                   argumentCountIs(1), hasArgument(0, canResolveToExpr(Exp)))
569                   .bind(NodeID<Expr>::value)),
570       Stm, Context);
571   if (const Stmt *S = findExprMutation(Ref))
572     return S;
573 
574   // If 'Exp' is bound to a non-const reference, check all declRefExpr to that.
575   const auto Refs = match(
576       stmt(forEachDescendant(
577           varDecl(hasType(nonConstReferenceType()),
578                   hasInitializer(anyOf(
579                       canResolveToExpr(Exp),
580                       memberExpr(hasObjectExpression(canResolveToExpr(Exp))))),
581                   hasParent(declStmt().bind("stmt")),
582                   // Don't follow the reference in range statement, we've
583                   // handled that separately.
584                   unless(hasParent(declStmt(hasParent(cxxForRangeStmt(
585                       hasRangeStmt(equalsBoundNode("stmt"))))))))
586               .bind(NodeID<Decl>::value))),
587       Stm, Context);
588   return findDeclMutation(Refs);
589 }
590 
591 const Stmt *ExprMutationAnalyzer::findFunctionArgMutation(const Expr *Exp) {
592   const auto NonConstRefParam = forEachArgumentWithParam(
593       canResolveToExpr(Exp),
594       parmVarDecl(hasType(nonConstReferenceType())).bind("parm"));
595   const auto IsInstantiated = hasDeclaration(isInstantiated());
596   const auto FuncDecl = hasDeclaration(functionDecl().bind("func"));
597   const auto Matches = match(
598       traverse(
599           TK_AsIs,
600           findAll(
601               expr(anyOf(callExpr(NonConstRefParam, IsInstantiated, FuncDecl,
602                                   unless(callee(namedDecl(hasAnyName(
603                                       "::std::move", "::std::forward"))))),
604                          cxxConstructExpr(NonConstRefParam, IsInstantiated,
605                                           FuncDecl)))
606                   .bind(NodeID<Expr>::value))),
607       Stm, Context);
608   for (const auto &Nodes : Matches) {
609     const auto *Exp = Nodes.getNodeAs<Expr>(NodeID<Expr>::value);
610     const auto *Func = Nodes.getNodeAs<FunctionDecl>("func");
611     if (!Func->getBody() || !Func->getPrimaryTemplate())
612       return Exp;
613 
614     const auto *Parm = Nodes.getNodeAs<ParmVarDecl>("parm");
615     const ArrayRef<ParmVarDecl *> AllParams =
616         Func->getPrimaryTemplate()->getTemplatedDecl()->parameters();
617     QualType ParmType =
618         AllParams[std::min<size_t>(Parm->getFunctionScopeIndex(),
619                                    AllParams.size() - 1)]
620             ->getType();
621     if (const auto *T = ParmType->getAs<PackExpansionType>())
622       ParmType = T->getPattern();
623 
624     // If param type is forwarding reference, follow into the function
625     // definition and see whether the param is mutated inside.
626     if (const auto *RefType = ParmType->getAs<RValueReferenceType>()) {
627       if (!RefType->getPointeeType().getQualifiers() &&
628           RefType->getPointeeType()->getAs<TemplateTypeParmType>()) {
629         std::unique_ptr<FunctionParmMutationAnalyzer> &Analyzer =
630             FuncParmAnalyzer[Func];
631         if (!Analyzer)
632           Analyzer.reset(new FunctionParmMutationAnalyzer(*Func, Context));
633         if (Analyzer->findMutation(Parm))
634           return Exp;
635         continue;
636       }
637     }
638     // Not forwarding reference.
639     return Exp;
640   }
641   return nullptr;
642 }
643 
644 FunctionParmMutationAnalyzer::FunctionParmMutationAnalyzer(
645     const FunctionDecl &Func, ASTContext &Context)
646     : BodyAnalyzer(*Func.getBody(), Context) {
647   if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(&Func)) {
648     // CXXCtorInitializer might also mutate Param but they're not part of
649     // function body, check them eagerly here since they're typically trivial.
650     for (const CXXCtorInitializer *Init : Ctor->inits()) {
651       ExprMutationAnalyzer InitAnalyzer(*Init->getInit(), Context);
652       for (const ParmVarDecl *Parm : Ctor->parameters()) {
653         if (Results.contains(Parm))
654           continue;
655         if (const Stmt *S = InitAnalyzer.findMutation(Parm))
656           Results[Parm] = S;
657       }
658     }
659   }
660 }
661 
662 const Stmt *
663 FunctionParmMutationAnalyzer::findMutation(const ParmVarDecl *Parm) {
664   const auto Memoized = Results.find(Parm);
665   if (Memoized != Results.end())
666     return Memoized->second;
667 
668   if (const Stmt *S = BodyAnalyzer.findMutation(Parm))
669     return Results[Parm] = S;
670 
671   return Results[Parm] = nullptr;
672 }
673 
674 } // namespace clang
675