clang 22.0.0git
ExprMutationAnalyzer.cpp
Go to the documentation of this file.
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//===----------------------------------------------------------------------===//
9#include "clang/AST/Expr.h"
11#include "clang/AST/Stmt.h"
15#include "llvm/ADT/STLExtras.h"
16
17namespace clang {
18using namespace ast_matchers;
19
20// Check if result of Source expression could be a Target expression.
21// Checks:
22// - Implicit Casts
23// - Binary Operators
24// - ConditionalOperator
25// - BinaryConditionalOperator
26static bool canExprResolveTo(const Expr *Source, const Expr *Target) {
27 const auto IgnoreDerivedToBase = [](const Expr *E, auto Matcher) {
28 if (Matcher(E))
29 return true;
30 if (const auto *Cast = dyn_cast<ImplicitCastExpr>(E)) {
31 if ((Cast->getCastKind() == CK_DerivedToBase ||
32 Cast->getCastKind() == CK_UncheckedDerivedToBase) &&
33 Matcher(Cast->getSubExpr()))
34 return true;
35 }
36 return false;
37 };
38
39 const auto EvalCommaExpr = [](const Expr *E, auto Matcher) {
40 const Expr *Result = E;
41 while (const auto *BOComma =
42 dyn_cast_or_null<BinaryOperator>(Result->IgnoreParens())) {
43 if (!BOComma->isCommaOp())
44 break;
45 Result = BOComma->getRHS();
46 }
47
48 return Result != E && Matcher(Result);
49 };
50
51 // The 'ConditionalOperatorM' matches on `<anything> ? <expr> : <expr>`.
52 // This matching must be recursive because `<expr>` can be anything resolving
53 // to the `InnerMatcher`, for example another conditional operator.
54 // The edge-case `BaseClass &b = <cond> ? DerivedVar1 : DerivedVar2;`
55 // is handled, too. The implicit cast happens outside of the conditional.
56 // This is matched by `IgnoreDerivedToBase(canResolveToExpr(InnerMatcher))`
57 // below.
58 const auto ConditionalOperatorM = [Target](const Expr *E) {
59 if (const auto *CO = dyn_cast<AbstractConditionalOperator>(E)) {
60 const auto *TE = CO->getTrueExpr()->IgnoreParens();
61 if (TE && canExprResolveTo(TE, Target))
62 return true;
63 const auto *FE = CO->getFalseExpr()->IgnoreParens();
64 if (FE && canExprResolveTo(FE, Target))
65 return true;
66 }
67 return false;
68 };
69
70 const Expr *SourceExprP = Source->IgnoreParens();
71 return IgnoreDerivedToBase(SourceExprP,
72 [&](const Expr *E) {
73 return E == Target || ConditionalOperatorM(E);
74 }) ||
75 EvalCommaExpr(SourceExprP, [&](const Expr *E) {
76 return IgnoreDerivedToBase(
77 E->IgnoreParens(), [&](const Expr *EE) { return EE == Target; });
78 });
79}
80
81namespace {
82
83// `ArraySubscriptExpr` can switch base and idx, e.g. `a[4]` is the same as
84// `4[a]`. When type is dependent, we conservatively assume both sides are base.
85AST_MATCHER_P(ArraySubscriptExpr, hasBaseConservative,
86 ast_matchers::internal::Matcher<Expr>, InnerMatcher) {
87 if (Node.isTypeDependent()) {
88 return InnerMatcher.matches(*Node.getLHS(), Finder, Builder) ||
89 InnerMatcher.matches(*Node.getRHS(), Finder, Builder);
90 }
91 return InnerMatcher.matches(*Node.getBase(), Finder, Builder);
92}
93
94AST_MATCHER(Type, isDependentType) { return Node.isDependentType(); }
95
96AST_MATCHER_P(LambdaExpr, hasCaptureInit, const Expr *, E) {
97 return llvm::is_contained(Node.capture_inits(), E);
98}
99
100AST_MATCHER_P(CXXForRangeStmt, hasRangeStmt,
101 ast_matchers::internal::Matcher<DeclStmt>, InnerMatcher) {
102 const DeclStmt *const Range = Node.getRangeStmt();
103 return InnerMatcher.matches(*Range, Finder, Builder);
104}
105
106AST_MATCHER_P(Stmt, canResolveToExpr, const Stmt *, Inner) {
107 auto *Exp = dyn_cast<Expr>(&Node);
108 if (!Exp)
109 return true;
110 auto *Target = dyn_cast<Expr>(Inner);
111 if (!Target)
112 return false;
113 return canExprResolveTo(Exp, Target);
114}
115
116// use class member to store data can reduce stack usage to avoid stack overflow
117// when recursive call.
118class ExprPointeeResolve {
119 const Expr *T;
120
121 bool resolveExpr(const Expr *E) {
122 if (E == nullptr)
123 return false;
124 if (E == T)
125 return true;
126
127 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
128 if (BO->isAdditiveOp())
129 return (resolveExpr(BO->getLHS()) || resolveExpr(BO->getRHS()));
130 if (BO->isCommaOp())
131 return resolveExpr(BO->getRHS());
132 return false;
133 }
134
135 if (const auto *PE = dyn_cast<ParenExpr>(E))
136 return resolveExpr(PE->getSubExpr());
137
138 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
139 // only implicit cast needs to be treated as resolvable.
140 // explicit cast will be checked in `findPointeeToNonConst`
141 const CastKind kind = ICE->getCastKind();
142 if (kind == CK_LValueToRValue || kind == CK_DerivedToBase ||
143 kind == CK_UncheckedDerivedToBase)
144 return resolveExpr(ICE->getSubExpr());
145 return false;
146 }
147
148 if (const auto *ACE = dyn_cast<AbstractConditionalOperator>(E))
149 return resolve(ACE->getTrueExpr()) || resolve(ACE->getFalseExpr());
150
151 return false;
152 }
153
154public:
155 ExprPointeeResolve(const Expr *T) : T(T) {}
156 bool resolve(const Expr *S) { return resolveExpr(S); }
157};
158
159AST_MATCHER_P(Stmt, canResolveToExprPointee, const Stmt *, T) {
160 auto *Exp = dyn_cast<Expr>(&Node);
161 if (!Exp)
162 return true;
163 auto *Target = dyn_cast<Expr>(T);
164 if (!Target)
165 return false;
166 return ExprPointeeResolve{Target}.resolve(Exp);
167}
168
169// Similar to 'hasAnyArgument', but does not work because 'InitListExpr' does
170// not have the 'arguments()' method.
171AST_MATCHER_P(InitListExpr, hasAnyInit, ast_matchers::internal::Matcher<Expr>,
172 InnerMatcher) {
173 for (const Expr *Arg : Node.inits()) {
174 if (Arg == nullptr)
175 continue;
176 ast_matchers::internal::BoundNodesTreeBuilder Result(*Builder);
177 if (InnerMatcher.matches(*Arg, Finder, &Result)) {
178 *Builder = std::move(Result);
179 return true;
180 }
181 }
182 return false;
183}
184
185const ast_matchers::internal::VariadicDynCastAllOfMatcher<Stmt, CXXTypeidExpr>
186 cxxTypeidExpr;
187
188AST_MATCHER(CXXTypeidExpr, isPotentiallyEvaluated) {
189 return Node.isPotentiallyEvaluated();
190}
191
192AST_MATCHER(CXXMemberCallExpr, isConstCallee) {
193 const Decl *CalleeDecl = Node.getCalleeDecl();
194 const auto *VD = dyn_cast_or_null<ValueDecl>(CalleeDecl);
195 if (!VD)
196 return false;
197 const QualType T = VD->getType().getCanonicalType();
198 const auto *MPT = dyn_cast<MemberPointerType>(T);
199 const auto *FPT = MPT ? cast<FunctionProtoType>(MPT->getPointeeType())
200 : dyn_cast<FunctionProtoType>(T);
201 if (!FPT)
202 return false;
203 return FPT->isConst();
204}
205
206AST_MATCHER_P(GenericSelectionExpr, hasControllingExpr,
207 ast_matchers::internal::Matcher<Expr>, InnerMatcher) {
208 if (Node.isTypePredicate())
209 return false;
210 return InnerMatcher.matches(*Node.getControllingExpr(), Finder, Builder);
211}
212
213template <typename T>
214ast_matchers::internal::Matcher<T>
215findFirst(const ast_matchers::internal::Matcher<T> &Matcher) {
216 return anyOf(Matcher, hasDescendant(Matcher));
217}
218
219const auto nonConstReferenceType = [] {
220 return hasUnqualifiedDesugaredType(
221 referenceType(pointee(unless(isConstQualified()))));
222};
223
224const auto nonConstPointerType = [] {
225 return hasUnqualifiedDesugaredType(
226 pointerType(pointee(unless(isConstQualified()))));
227};
228
229const auto isMoveOnly = [] {
230 return cxxRecordDecl(
231 hasMethod(cxxConstructorDecl(isMoveConstructor(), unless(isDeleted()))),
232 hasMethod(cxxMethodDecl(isMoveAssignmentOperator(), unless(isDeleted()))),
233 unless(anyOf(hasMethod(cxxConstructorDecl(isCopyConstructor(),
234 unless(isDeleted()))),
235 hasMethod(cxxMethodDecl(isCopyAssignmentOperator(),
236 unless(isDeleted()))))));
237};
238
239template <class T> struct NodeID;
240template <> struct NodeID<Expr> { static constexpr StringRef value = "expr"; };
241template <> struct NodeID<Decl> { static constexpr StringRef value = "decl"; };
242constexpr StringRef NodeID<Expr>::value;
243constexpr StringRef NodeID<Decl>::value;
244
245template <class T,
246 class F = const Stmt *(ExprMutationAnalyzer::Analyzer::*)(const T *)>
247const Stmt *tryEachMatch(ArrayRef<ast_matchers::BoundNodes> Matches,
248 ExprMutationAnalyzer::Analyzer *Analyzer, F Finder) {
249 const StringRef ID = NodeID<T>::value;
250 for (const auto &Nodes : Matches) {
251 if (const Stmt *S = (Analyzer->*Finder)(Nodes.getNodeAs<T>(ID)))
252 return S;
253 }
254 return nullptr;
255}
256
257} // namespace
258
260 return findMutationMemoized(
261 Exp,
262 {&ExprMutationAnalyzer::Analyzer::findDirectMutation,
263 &ExprMutationAnalyzer::Analyzer::findMemberMutation,
264 &ExprMutationAnalyzer::Analyzer::findArrayElementMutation,
265 &ExprMutationAnalyzer::Analyzer::findCastMutation,
266 &ExprMutationAnalyzer::Analyzer::findRangeLoopMutation,
267 &ExprMutationAnalyzer::Analyzer::findReferenceMutation,
268 &ExprMutationAnalyzer::Analyzer::findFunctionArgMutation},
269 Memorized.Results);
270}
271
273 return tryEachDeclRef(Dec, &ExprMutationAnalyzer::Analyzer::findMutation);
274}
275
276const Stmt *
278 return findMutationMemoized(
279 Exp,
280 {
281 &ExprMutationAnalyzer::Analyzer::findPointeeValueMutation,
282 &ExprMutationAnalyzer::Analyzer::findPointeeMemberMutation,
283 &ExprMutationAnalyzer::Analyzer::findPointeeToNonConst,
284 },
285 Memorized.PointeeResults);
286}
287
288const Stmt *
290 return tryEachDeclRef(Dec,
292}
293
294const Stmt *ExprMutationAnalyzer::Analyzer::findMutationMemoized(
295 const Expr *Exp, llvm::ArrayRef<MutationFinder> Finders,
296 Memoized::ResultMap &MemoizedResults) {
297 // Assume Exp is not mutated before analyzing Exp.
298 auto [Memoized, Inserted] = MemoizedResults.try_emplace(Exp);
299 if (!Inserted)
300 return Memoized->second;
301
302 if (ExprMutationAnalyzer::isUnevaluated(Exp, Context))
303 return nullptr;
304
305 for (const auto &Finder : Finders) {
306 if (const Stmt *S = (this->*Finder)(Exp))
307 return MemoizedResults[Exp] = S;
308 }
309
310 return nullptr;
311}
312
313const Stmt *
314ExprMutationAnalyzer::Analyzer::tryEachDeclRef(const Decl *Dec,
315 MutationFinder Finder) {
316 const auto Refs = match(
317 findAll(
318 declRefExpr(to(
319 // `Dec` or a binding if `Dec` is a decomposition.
320 anyOf(equalsNode(Dec),
321 bindingDecl(forDecomposition(equalsNode(Dec))))
322 //
323 ))
324 .bind(NodeID<Expr>::value)),
325 Stm, Context);
326 for (const auto &RefNodes : Refs) {
327 const auto *E = RefNodes.getNodeAs<Expr>(NodeID<Expr>::value);
328 if ((this->*Finder)(E))
329 return E;
330 }
331 return nullptr;
332}
333
335 return !match(stmt(anyOf(
336 // `Exp` is part of the underlying expression of
337 // decltype/typeof if it has an ancestor of
338 // typeLoc.
342 // `UnaryExprOrTypeTraitExpr` is unevaluated
343 // unless it's sizeof on VLA.
345 hasArgumentOfType(variableArrayType())))),
346 // `CXXTypeidExpr` is unevaluated unless it's
347 // applied to an expression of glvalue of
348 // polymorphic class type.
349 cxxTypeidExpr(unless(isPotentiallyEvaluated())),
350 // The controlling expression of
351 // `GenericSelectionExpr` is unevaluated.
353 hasControllingExpr(hasDescendant(equalsNode(Stm)))),
354 cxxNoexceptExpr()))))),
355 *Stm, Context)
356 .empty();
357}
358
359const Stmt *
360ExprMutationAnalyzer::Analyzer::findExprMutation(ArrayRef<BoundNodes> Matches) {
361 return tryEachMatch<Expr>(Matches, this,
363}
364
365const Stmt *
366ExprMutationAnalyzer::Analyzer::findDeclMutation(ArrayRef<BoundNodes> Matches) {
367 return tryEachMatch<Decl>(Matches, this,
369}
370
371const Stmt *ExprMutationAnalyzer::Analyzer::findExprPointeeMutation(
372 ArrayRef<ast_matchers::BoundNodes> Matches) {
373 return tryEachMatch<Expr>(
375}
376
377const Stmt *ExprMutationAnalyzer::Analyzer::findDeclPointeeMutation(
378 ArrayRef<ast_matchers::BoundNodes> Matches) {
379 return tryEachMatch<Decl>(
381}
382
383const Stmt *
384ExprMutationAnalyzer::Analyzer::findDirectMutation(const Expr *Exp) {
385 // LHS of any assignment operators.
386 const auto AsAssignmentLhs =
387 binaryOperator(isAssignmentOperator(), hasLHS(canResolveToExpr(Exp)));
388
389 // Operand of increment/decrement operators.
390 const auto AsIncDecOperand =
391 unaryOperator(anyOf(hasOperatorName("++"), hasOperatorName("--")),
392 hasUnaryOperand(canResolveToExpr(Exp)));
393
394 // Invoking non-const member function.
395 // A member function is assumed to be non-const when it is unresolved.
396 const auto NonConstMethod = cxxMethodDecl(unless(isConst()));
397
398 const auto AsNonConstThis = expr(anyOf(
399 cxxMemberCallExpr(on(canResolveToExpr(Exp)), unless(isConstCallee())),
400 cxxOperatorCallExpr(callee(NonConstMethod),
401 hasArgument(0, canResolveToExpr(Exp))),
402 // In case of a templated type, calling overloaded operators is not
403 // resolved and modelled as `binaryOperator` on a dependent type.
404 // Such instances are considered a modification, because they can modify
405 // in different instantiations of the template.
406 binaryOperator(isTypeDependent(),
407 hasEitherOperand(ignoringImpCasts(canResolveToExpr(Exp)))),
408 // A fold expression may contain `Exp` as it's initializer.
409 // We don't know if the operator modifies `Exp` because the
410 // operator is type dependent due to the parameter pack.
411 cxxFoldExpr(hasFoldInit(ignoringImpCasts(canResolveToExpr(Exp)))),
412 // Within class templates and member functions the member expression might
413 // not be resolved. In that case, the `callExpr` is considered to be a
414 // modification.
415 callExpr(callee(expr(anyOf(
416 unresolvedMemberExpr(hasObjectExpression(canResolveToExpr(Exp))),
418 hasObjectExpression(canResolveToExpr(Exp))))))),
419 // Match on a call to a known method, but the call itself is type
420 // dependent (e.g. `vector<T> v; v.push(T{});` in a templated function).
422 isTypeDependent(),
423 callee(memberExpr(hasDeclaration(NonConstMethod),
424 hasObjectExpression(canResolveToExpr(Exp))))))));
425
426 // Taking address of 'Exp'.
427 // We're assuming 'Exp' is mutated as soon as its address is taken, though in
428 // theory we can follow the pointer and see whether it escaped `Stm` or is
429 // dereferenced and then mutated. This is left for future improvements.
430 const auto AsAmpersandOperand =
431 unaryOperator(hasOperatorName("&"),
432 // A NoOp implicit cast is adding const.
433 unless(hasParent(implicitCastExpr(hasCastKind(CK_NoOp)))),
434 hasUnaryOperand(canResolveToExpr(Exp)));
435 const auto AsPointerFromArrayDecay = castExpr(
436 hasCastKind(CK_ArrayToPointerDecay),
437 unless(hasParent(arraySubscriptExpr())), has(canResolveToExpr(Exp)));
438 // Treat calling `operator->()` of move-only classes as taking address.
439 // These are typically smart pointers with unique ownership so we treat
440 // mutation of pointee as mutation of the smart pointer itself.
441 const auto AsOperatorArrowThis = cxxOperatorCallExpr(
443 callee(
444 cxxMethodDecl(ofClass(isMoveOnly()), returns(nonConstPointerType()))),
445 argumentCountIs(1), hasArgument(0, canResolveToExpr(Exp)));
446
447 // Used as non-const-ref argument when calling a function.
448 // An argument is assumed to be non-const-ref when the function is unresolved.
449 // Instantiated template functions are not handled here but in
450 // findFunctionArgMutation which has additional smarts for handling forwarding
451 // references.
452 const auto NonConstRefParam = forEachArgumentWithParamType(
453 anyOf(canResolveToExpr(Exp),
455 hasObjectExpression(ignoringImpCasts(canResolveToExpr(Exp))))),
456 nonConstReferenceType());
457 const auto NotInstantiated = unless(hasDeclaration(isInstantiated()));
458
459 const auto AsNonConstRefArg =
460 anyOf(callExpr(NonConstRefParam, NotInstantiated),
461 cxxConstructExpr(NonConstRefParam, NotInstantiated),
462 // If the call is type-dependent, we can't properly process any
463 // argument because required type conversions and implicit casts
464 // will be inserted only after specialization.
465 callExpr(isTypeDependent(), hasAnyArgument(canResolveToExpr(Exp))),
466 cxxUnresolvedConstructExpr(hasAnyArgument(canResolveToExpr(Exp))),
467 // Previous False Positive in the following Code:
468 // `template <typename T> void f() { int i = 42; new Type<T>(i); }`
469 // Where the constructor of `Type` takes its argument as reference.
470 // The AST does not resolve in a `cxxConstructExpr` because it is
471 // type-dependent.
472 parenListExpr(hasDescendant(expr(canResolveToExpr(Exp)))),
473 // If the initializer is for a reference type, there is no cast for
474 // the variable. Values are cast to RValue first.
475 initListExpr(hasAnyInit(expr(canResolveToExpr(Exp)))));
476
477 // Captured by a lambda by reference.
478 // If we're initializing a capture with 'Exp' directly then we're initializing
479 // a reference capture.
480 // For value captures there will be an ImplicitCastExpr <LValueToRValue>.
481 const auto AsLambdaRefCaptureInit = lambdaExpr(hasCaptureInit(Exp));
482
483 // Returned as non-const-ref.
484 // If we're returning 'Exp' directly then it's returned as non-const-ref.
485 // For returning by value there will be an ImplicitCastExpr <LValueToRValue>.
486 // For returning by const-ref there will be an ImplicitCastExpr <NoOp> (for
487 // adding const.)
488 const auto AsNonConstRefReturn =
489 returnStmt(hasReturnValue(canResolveToExpr(Exp)));
490
491 // It is used as a non-const-reference for initializing a range-for loop.
492 const auto AsNonConstRefRangeInit = cxxForRangeStmt(hasRangeInit(declRefExpr(
493 allOf(canResolveToExpr(Exp), hasType(nonConstReferenceType())))));
494
495 const auto Matches = match(
496 traverse(
497 TK_AsIs,
498 findFirst(stmt(anyOf(AsAssignmentLhs, AsIncDecOperand, AsNonConstThis,
499 AsAmpersandOperand, AsPointerFromArrayDecay,
500 AsOperatorArrowThis, AsNonConstRefArg,
501 AsLambdaRefCaptureInit, AsNonConstRefReturn,
502 AsNonConstRefRangeInit))
503 .bind("stmt"))),
504 Stm, Context);
505 return selectFirst<Stmt>("stmt", Matches);
506}
507
508const Stmt *
509ExprMutationAnalyzer::Analyzer::findMemberMutation(const Expr *Exp) {
510 // Check whether any member of 'Exp' is mutated.
511 const auto MemberExprs = match(
512 findAll(expr(anyOf(memberExpr(hasObjectExpression(canResolveToExpr(Exp))),
514 hasObjectExpression(canResolveToExpr(Exp))),
515 binaryOperator(hasOperatorName(".*"),
516 hasLHS(equalsNode(Exp)))))
517 .bind(NodeID<Expr>::value)),
518 Stm, Context);
519 return findExprMutation(MemberExprs);
520}
521
522const Stmt *
523ExprMutationAnalyzer::Analyzer::findArrayElementMutation(const Expr *Exp) {
524 // Check whether any element of an array is mutated.
525 const auto SubscriptExprs = match(
527 anyOf(hasBaseConservative(canResolveToExpr(Exp)),
528 hasBaseConservative(implicitCastExpr(allOf(
529 hasCastKind(CK_ArrayToPointerDecay),
530 hasSourceExpression(canResolveToExpr(Exp)))))))
531 .bind(NodeID<Expr>::value)),
532 Stm, Context);
533 return findExprMutation(SubscriptExprs);
534}
535
536const Stmt *ExprMutationAnalyzer::Analyzer::findCastMutation(const Expr *Exp) {
537 // If the 'Exp' is explicitly casted to a non-const reference type the
538 // 'Exp' is considered to be modified.
539 const auto ExplicitCast =
540 match(findFirst(stmt(castExpr(hasSourceExpression(canResolveToExpr(Exp)),
541 explicitCastExpr(hasDestinationType(
542 nonConstReferenceType()))))
543 .bind("stmt")),
544 Stm, Context);
545
546 if (const auto *CastStmt = selectFirst<Stmt>("stmt", ExplicitCast))
547 return CastStmt;
548
549 // If 'Exp' is casted to any non-const reference type, check the castExpr.
550 const auto Casts = match(
551 findAll(expr(castExpr(hasSourceExpression(canResolveToExpr(Exp)),
552 anyOf(explicitCastExpr(hasDestinationType(
553 nonConstReferenceType())),
554 implicitCastExpr(hasImplicitDestinationType(
555 nonConstReferenceType())))))
556 .bind(NodeID<Expr>::value)),
557 Stm, Context);
558
559 if (const Stmt *S = findExprMutation(Casts))
560 return S;
561 // Treat std::{move,forward} as cast.
562 const auto Calls =
564 hasAnyName("::std::move", "::std::forward"))),
565 hasArgument(0, canResolveToExpr(Exp)))
566 .bind("expr")),
567 Stm, Context);
568 return findExprMutation(Calls);
569}
570
571const Stmt *
572ExprMutationAnalyzer::Analyzer::findRangeLoopMutation(const Expr *Exp) {
573 // Keep the ordering for the specific initialization matches to happen first,
574 // because it is cheaper to match all potential modifications of the loop
575 // variable.
576
577 // The range variable is a reference to a builtin array. In that case the
578 // array is considered modified if the loop-variable is a non-const reference.
579 const auto DeclStmtToNonRefToArray = declStmt(hasSingleDecl(varDecl(hasType(
580 hasUnqualifiedDesugaredType(referenceType(pointee(arrayType())))))));
581 const auto RefToArrayRefToElements = match(
582 findFirst(stmt(cxxForRangeStmt(
583 hasLoopVariable(
584 varDecl(anyOf(hasType(nonConstReferenceType()),
585 hasType(nonConstPointerType())))
586 .bind(NodeID<Decl>::value)),
587 hasRangeStmt(DeclStmtToNonRefToArray),
588 hasRangeInit(canResolveToExpr(Exp))))
589 .bind("stmt")),
590 Stm, Context);
591
592 if (const auto *BadRangeInitFromArray =
593 selectFirst<Stmt>("stmt", RefToArrayRefToElements))
594 return BadRangeInitFromArray;
595
596 // Small helper to match special cases in range-for loops.
597 //
598 // It is possible that containers do not provide a const-overload for their
599 // iterator accessors. If this is the case, the variable is used non-const
600 // no matter what happens in the loop. This requires special detection as it
601 // is then faster to find all mutations of the loop variable.
602 // It aims at a different modification as well.
603 const auto HasAnyNonConstIterator =
604 anyOf(allOf(hasMethod(allOf(hasName("begin"), unless(isConst()))),
605 unless(hasMethod(allOf(hasName("begin"), isConst())))),
606 allOf(hasMethod(allOf(hasName("end"), unless(isConst()))),
607 unless(hasMethod(allOf(hasName("end"), isConst())))));
608
609 const auto DeclStmtToNonConstIteratorContainer = declStmt(
610 hasSingleDecl(varDecl(hasType(hasUnqualifiedDesugaredType(referenceType(
611 pointee(hasDeclaration(cxxRecordDecl(HasAnyNonConstIterator)))))))));
612
613 const auto RefToContainerBadIterators = match(
614 findFirst(stmt(cxxForRangeStmt(allOf(
615 hasRangeStmt(DeclStmtToNonConstIteratorContainer),
616 hasRangeInit(canResolveToExpr(Exp)))))
617 .bind("stmt")),
618 Stm, Context);
619
620 if (const auto *BadIteratorsContainer =
621 selectFirst<Stmt>("stmt", RefToContainerBadIterators))
622 return BadIteratorsContainer;
623
624 // If range for looping over 'Exp' with a non-const reference loop variable,
625 // check all declRefExpr of the loop variable.
626 const auto LoopVars =
628 hasLoopVariable(varDecl(hasType(nonConstReferenceType()))
629 .bind(NodeID<Decl>::value)),
630 hasRangeInit(canResolveToExpr(Exp)))),
631 Stm, Context);
632 return findDeclMutation(LoopVars);
633}
634
635const Stmt *
636ExprMutationAnalyzer::Analyzer::findReferenceMutation(const Expr *Exp) {
637 // Follow non-const reference returned by `operator*()` of move-only classes.
638 // These are typically smart pointers with unique ownership so we treat
639 // mutation of pointee as mutation of the smart pointer itself.
640 const auto Ref = match(
643 callee(cxxMethodDecl(ofClass(isMoveOnly()),
644 returns(nonConstReferenceType()))),
645 argumentCountIs(1), hasArgument(0, canResolveToExpr(Exp)))
646 .bind(NodeID<Expr>::value)),
647 Stm, Context);
648 if (const Stmt *S = findExprMutation(Ref))
649 return S;
650
651 // If 'Exp' is bound to a non-const reference, check all declRefExpr to that.
652 const auto Refs = match(
654 varDecl(hasType(nonConstReferenceType()),
655 hasInitializer(anyOf(
656 canResolveToExpr(Exp),
657 memberExpr(hasObjectExpression(canResolveToExpr(Exp))))),
658 hasParent(declStmt().bind("stmt")),
659 // Don't follow the reference in range statement, we've
660 // handled that separately.
662 hasRangeStmt(equalsBoundNode("stmt"))))))))
663 .bind(NodeID<Decl>::value))),
664 Stm, Context);
665 return findDeclMutation(Refs);
666}
667
668const Stmt *
669ExprMutationAnalyzer::Analyzer::findFunctionArgMutation(const Expr *Exp) {
670 const auto NonConstRefParam = forEachArgumentWithParam(
671 canResolveToExpr(Exp),
672 parmVarDecl(hasType(nonConstReferenceType())).bind("parm"));
673 const auto IsInstantiated = hasDeclaration(isInstantiated());
674 const auto FuncDecl = hasDeclaration(functionDecl().bind("func"));
675 const auto Matches = match(
676 traverse(
677 TK_AsIs,
678 findAll(
679 expr(anyOf(callExpr(NonConstRefParam, IsInstantiated, FuncDecl,
681 "::std::move", "::std::forward"))))),
682 cxxConstructExpr(NonConstRefParam, IsInstantiated,
683 FuncDecl)))
684 .bind(NodeID<Expr>::value))),
685 Stm, Context);
686 for (const auto &Nodes : Matches) {
687 const auto *Exp = Nodes.getNodeAs<Expr>(NodeID<Expr>::value);
688 const auto *Func = Nodes.getNodeAs<FunctionDecl>("func");
689 if (!Func->getBody() || !Func->getPrimaryTemplate())
690 return Exp;
691
692 const auto *Parm = Nodes.getNodeAs<ParmVarDecl>("parm");
693 const ArrayRef<ParmVarDecl *> AllParams =
694 Func->getPrimaryTemplate()->getTemplatedDecl()->parameters();
695 QualType ParmType =
696 AllParams[std::min<size_t>(Parm->getFunctionScopeIndex(),
697 AllParams.size() - 1)]
698 ->getType();
699 if (const auto *T = ParmType->getAs<PackExpansionType>())
700 ParmType = T->getPattern();
701
702 // If param type is forwarding reference, follow into the function
703 // definition and see whether the param is mutated inside.
704 if (const auto *RefType = ParmType->getAs<RValueReferenceType>()) {
705 if (!RefType->getPointeeType().getQualifiers() &&
706 isa<TemplateTypeParmType>(
707 RefType->getPointeeType().getCanonicalType())) {
710 *Func, Context, Memorized);
711 if (Analyzer->findMutation(Parm))
712 return Exp;
713 continue;
714 }
715 }
716 // Not forwarding reference.
717 return Exp;
718 }
719 return nullptr;
720}
721
722const Stmt *
723ExprMutationAnalyzer::Analyzer::findPointeeValueMutation(const Expr *Exp) {
724 const auto Matches = match(
726 expr(anyOf(
727 // deref by *
728 unaryOperator(hasOperatorName("*"),
729 hasUnaryOperand(canResolveToExprPointee(Exp))),
730 // deref by []
732 hasBaseConservative(canResolveToExprPointee(Exp)))))
733 .bind(NodeID<Expr>::value))),
734 Stm, Context);
735 return findExprMutation(Matches);
736}
737
738const Stmt *
739ExprMutationAnalyzer::Analyzer::findPointeeMemberMutation(const Expr *Exp) {
740 const Stmt *MemberCallExpr = selectFirst<Stmt>(
742 cxxMemberCallExpr(on(canResolveToExprPointee(Exp)),
743 unless(isConstCallee()))
744 .bind("stmt"))),
745 Stm, Context));
746 if (MemberCallExpr)
747 return MemberCallExpr;
748 const auto Matches =
750 memberExpr(hasObjectExpression(canResolveToExprPointee(Exp)))
751 .bind(NodeID<Expr>::value))),
752 Stm, Context);
753 return findExprMutation(Matches);
754}
755
756const Stmt *
757ExprMutationAnalyzer::Analyzer::findPointeeToNonConst(const Expr *Exp) {
758 const auto NonConstPointerOrDependentType =
759 type(anyOf(nonConstPointerType(), isDependentType()));
760
761 // assign
762 const auto InitToNonConst =
763 varDecl(hasType(NonConstPointerOrDependentType),
764 hasInitializer(expr(canResolveToExprPointee(Exp)).bind("stmt")));
765 const auto AssignToNonConst =
766 binaryOperation(hasOperatorName("="),
767 hasLHS(expr(hasType(NonConstPointerOrDependentType))),
768 hasRHS(canResolveToExprPointee(Exp)));
769 // arguments like
770 const auto ArgOfInstantiationDependent = allOf(
771 hasAnyArgument(canResolveToExprPointee(Exp)), isInstantiationDependent());
772 const auto ArgOfNonConstParameter = forEachArgumentWithParamType(
773 canResolveToExprPointee(Exp), NonConstPointerOrDependentType);
774 const auto CallLikeMatcher =
775 anyOf(ArgOfNonConstParameter, ArgOfInstantiationDependent);
776 const auto PassAsNonConstArg =
777 expr(anyOf(cxxUnresolvedConstructExpr(ArgOfInstantiationDependent),
778 cxxConstructExpr(CallLikeMatcher), callExpr(CallLikeMatcher),
779 parenListExpr(has(canResolveToExprPointee(Exp))),
780 initListExpr(hasAnyInit(canResolveToExprPointee(Exp)))));
781 // cast
782 const auto CastToNonConst =
783 explicitCastExpr(hasSourceExpression(canResolveToExprPointee(Exp)),
784 hasDestinationType(NonConstPointerOrDependentType));
785
786 // capture
787 // FIXME: false positive if the pointee does not change in lambda
788 const auto CaptureNoConst = lambdaExpr(hasCaptureInit(Exp));
789
790 const auto Matches =
792 stmt(anyOf(AssignToNonConst, PassAsNonConstArg,
793 CastToNonConst, CaptureNoConst))
794 .bind("stmt")),
795 forEachDescendant(InitToNonConst))),
796 Stm, Context);
797 return selectFirst<Stmt>("stmt", Matches);
798}
799
800FunctionParmMutationAnalyzer::FunctionParmMutationAnalyzer(
801 const FunctionDecl &Func, ASTContext &Context,
802 ExprMutationAnalyzer::Memoized &Memorized)
803 : BodyAnalyzer(*Func.getBody(), Context, Memorized) {
804 if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(&Func)) {
805 // CXXCtorInitializer might also mutate Param but they're not part of
806 // function body, check them eagerly here since they're typically trivial.
807 for (const CXXCtorInitializer *Init : Ctor->inits()) {
808 ExprMutationAnalyzer::Analyzer InitAnalyzer(*Init->getInit(), Context,
809 Memorized);
810 for (const ParmVarDecl *Parm : Ctor->parameters()) {
811 if (Results.contains(Parm))
812 continue;
813 if (const Stmt *S = InitAnalyzer.findMutation(Parm))
814 Results[Parm] = S;
815 }
816 }
817 }
818}
819
820const Stmt *
822 auto [Place, Inserted] = Results.try_emplace(Parm);
823 if (!Inserted)
824 return Place->second;
825
826 // To handle call A -> call B -> call A. Assume parameters of A is not mutated
827 // before analyzing parameters of A. Then when analyzing the second "call A",
828 // FunctionParmMutationAnalyzer can use this memoized value to avoid infinite
829 // recursion.
830 return Place->second = BodyAnalyzer.findMutation(Parm);
831}
832
833} // namespace clang
BoundNodesTreeBuilder Nodes
DynTypedNode Node
#define AST_MATCHER(Type, DefineMatcher)
AST_MATCHER(Type, DefineMatcher) { ... } defines a zero parameter function named DefineMatcher() that...
#define AST_MATCHER_P(Type, DefineMatcher, ParamType, Param)
AST_MATCHER_P(Type, DefineMatcher, ParamType, Param) { ... } defines a single-parameter function name...
static char ID
Definition: Arena.cpp:183
Expr * E
llvm::MachO::Target Target
Definition: MachO.h:51
SourceRange Range
Definition: SemaObjC.cpp:753
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:188
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
static bool isUnevaluated(const Stmt *Stm, ASTContext &Context)
check whether stmt is unevaluated.
This represents one expression.
Definition: Expr.h:112
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3069
static FunctionParmMutationAnalyzer * getFunctionParmMutationAnalyzer(const FunctionDecl &Func, ASTContext &Context, ExprMutationAnalyzer::Memoized &Memorized)
const Stmt * findMutation(const ParmVarDecl *Parm)
Represents a parameter to a function.
Definition: Decl.h:1789
Stmt - This represents one statement.
Definition: Stmt.h:85
const T * getAs() const
Member-template getAs<specific type>'.
Definition: TypeBase.h:9159
const internal::VariadicDynCastAllOfMatcher< Decl, VarDecl > varDecl
Matches variable declarations.
const internal::VariadicDynCastAllOfMatcher< Stmt, DeclRefExpr > declRefExpr
Matches expressions that refer to declarations.
const internal::VariadicOperatorMatcherFunc< 1, 1 > unless
Matches if the provided matcher does not match.
const internal::VariadicDynCastAllOfMatcher< Stmt, ImplicitCastExpr > implicitCastExpr
Matches the implicit cast nodes of Clang's AST.
const internal::ArgumentAdaptingMatcherFunc< internal::HasDescendantMatcher > hasDescendant
Matches AST nodes that have descendant AST nodes that match the provided matcher.
const internal::VariadicDynCastAllOfMatcher< Stmt, CXXDependentScopeMemberExpr > cxxDependentScopeMemberExpr
Matches member expressions where the actual member referenced could not be resolved because the base ...
const AstTypeMatcher< PointerType > pointerType
Matches pointer types, but does not match Objective-C object pointer types.
const internal::VariadicDynCastAllOfMatcher< Decl, BindingDecl > bindingDecl
Matches binding declarations Example matches foo and bar (matcher = bindingDecl()
const internal::VariadicDynCastAllOfMatcher< Decl, ParmVarDecl > parmVarDecl
Matches parameter variable declarations.
const internal::VariadicDynCastAllOfMatcher< Stmt, GenericSelectionExpr > genericSelectionExpr
Matches C11 _Generic expression.
const internal::VariadicDynCastAllOfMatcher< Stmt, ReturnStmt > returnStmt
Matches return statements.
internal::Matcher< NamedDecl > hasName(StringRef Name)
Matches NamedDecl nodes that have the specified name.
Definition: ASTMatchers.h:3163
const internal::VariadicDynCastAllOfMatcher< Stmt, CallExpr > callExpr
Matches call expressions.
const internal::VariadicDynCastAllOfMatcher< Stmt, LambdaExpr > lambdaExpr
Matches lambda expressions.
const AstTypeMatcher< VariableArrayType > variableArrayType
Matches C arrays with a specified size that is not an integer-constant-expression.
const internal::VariadicDynCastAllOfMatcher< Stmt, UnaryExprOrTypeTraitExpr > unaryExprOrTypeTraitExpr
Matches sizeof (C99), alignof (C++11) and vec_step (OpenCL)
const internal::ArgumentAdaptingMatcherFunc< internal::ForEachDescendantMatcher > forEachDescendant
Matches AST nodes that have descendant AST nodes that match the provided matcher.
SmallVector< BoundNodes, 1 > match(MatcherT Matcher, const NodeT &Node, ASTContext &Context)
Returns the results of matching Matcher on Node.
const internal::VariadicDynCastAllOfMatcher< Decl, NamedDecl > namedDecl
Matches a declaration of anything that could have a name.
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
const internal::VariadicAllOfMatcher< TypeLoc > typeLoc
Matches TypeLocs in the clang AST.
const internal::VariadicDynCastAllOfMatcher< Stmt, ParenListExpr > parenListExpr
Matches paren list expressions.
const AstTypeMatcher< ArrayType > arrayType
Matches all kinds of arrays.
const internal::VariadicDynCastAllOfMatcher< Stmt, UnaryOperator > unaryOperator
Matches unary operator expressions.
const internal::VariadicFunction< internal::Matcher< NamedDecl >, StringRef, internal::hasAnyNameFunc > hasAnyName
Matches NamedDecl nodes that have any of the specified names.
const internal::MapAnyOfMatcher< BinaryOperator, CXXOperatorCallExpr, CXXRewrittenBinaryOperator > binaryOperation
Matches nodes which can be used with binary operators.
const internal::VariadicDynCastAllOfMatcher< Stmt, ArraySubscriptExpr > arraySubscriptExpr
Matches array subscript expressions.
const internal::VariadicDynCastAllOfMatcher< Stmt, CXXForRangeStmt > cxxForRangeStmt
Matches range-based for statements.
const internal::VariadicDynCastAllOfMatcher< Stmt, CXXMemberCallExpr > cxxMemberCallExpr
Matches member call expressions.
const internal::VariadicDynCastAllOfMatcher< Decl, CXXConstructorDecl > cxxConstructorDecl
Matches C++ constructor declarations.
internal::BindableMatcher< Stmt > sizeOfExpr(const internal::Matcher< UnaryExprOrTypeTraitExpr > &InnerMatcher)
Same as unaryExprOrTypeTraitExpr, but only matching sizeof.
Definition: ASTMatchers.h:3142
const internal::VariadicDynCastAllOfMatcher< Stmt, InitListExpr > initListExpr
Matches init list expressions.
const internal::VariadicDynCastAllOfMatcher< Stmt, CXXNoexceptExpr > cxxNoexceptExpr
Matches noexcept expressions.
const internal::VariadicDynCastAllOfMatcher< Stmt, BinaryOperator > binaryOperator
Matches binary operator expressions.
const internal::ArgumentAdaptingMatcherFunc< internal::HasMatcher > has
Matches AST nodes that have child AST nodes that match the provided matcher.
const internal::VariadicDynCastAllOfMatcher< Stmt, ExplicitCastExpr > explicitCastExpr
Matches explicit cast expressions.
const internal::VariadicDynCastAllOfMatcher< Stmt, CXXConstructExpr > cxxConstructExpr
Matches constructor call expressions (including implicit ones).
const internal::VariadicDynCastAllOfMatcher< Stmt, CXXOperatorCallExpr > cxxOperatorCallExpr
Matches overloaded operator calls.
internal::PolymorphicMatcher< internal::HasOverloadedOperatorNameMatcher, AST_POLYMORPHIC_SUPPORTED_TYPES(CXXOperatorCallExpr, FunctionDecl), std::vector< std::string > > hasOverloadedOperatorName(StringRef Name)
Matches overloaded operator names.
Definition: ASTMatchers.h:3226
const internal::VariadicOperatorMatcherFunc< 2, std::numeric_limits< unsigned >::max()> allOf
Matches if all given matchers match.
const internal::VariadicDynCastAllOfMatcher< Decl, FunctionDecl > functionDecl
Matches function declarations.
const internal::VariadicDynCastAllOfMatcher< Stmt, UnresolvedMemberExpr > unresolvedMemberExpr
Matches unresolved member expressions.
const internal::VariadicDynCastAllOfMatcher< Stmt, MemberExpr > memberExpr
Matches member expressions.
const internal::VariadicDynCastAllOfMatcher< Decl, CXXRecordDecl > cxxRecordDecl
Matches C++ class declarations.
internal::Matcher< T > traverse(TraversalKind TK, const internal::Matcher< T > &InnerMatcher)
Causes all nested matchers to be matched with the specified traversal kind.
Definition: ASTMatchers.h:832
const AstTypeMatcher< ReferenceType > referenceType
Matches both lvalue and rvalue reference types.
const internal::VariadicDynCastAllOfMatcher< Stmt, CXXUnresolvedConstructExpr > cxxUnresolvedConstructExpr
Matches unresolved constructor call expressions.
internal::Matcher< T > findAll(const internal::Matcher< T > &Matcher)
Matches if the node or any descendant matches.
Definition: ASTMatchers.h:3675
internal::PolymorphicMatcher< internal::HasDeclarationMatcher, void(internal::HasDeclarationSupportedTypes), internal::Matcher< Decl > > hasDeclaration(const internal::Matcher< Decl > &InnerMatcher)
Matches a node if the declaration associated with that node matches the given matcher.
Definition: ASTMatchers.h:3760
const internal::VariadicDynCastAllOfMatcher< Stmt, DeclStmt > declStmt
Matches declaration statements.
const internal::VariadicAllOfMatcher< Stmt > stmt
Matches statements.
const internal::VariadicDynCastAllOfMatcher< Stmt, Expr > expr
Matches expressions.
const internal::VariadicDynCastAllOfMatcher< Stmt, CXXFoldExpr > cxxFoldExpr
Matches C++17 fold expressions.
const internal::VariadicOperatorMatcherFunc< 2, std::numeric_limits< unsigned >::max()> anyOf
Matches if any of the given matchers matches.
const internal::VariadicDynCastAllOfMatcher< Decl, CXXMethodDecl > cxxMethodDecl
Matches method declarations.
const internal::VariadicDynCastAllOfMatcher< Stmt, CastExpr > castExpr
Matches any cast nodes of Clang's AST.
const internal::ArgumentAdaptingMatcherFunc< internal::HasAncestorMatcher, internal::TypeList< Decl, NestedNameSpecifierLoc, Stmt, TypeLoc, Attr >, internal::TypeList< Decl, NestedNameSpecifierLoc, Stmt, TypeLoc, Attr > > hasAncestor
Matches AST nodes that have an ancestor that matches the provided matcher.
const internal::ArgumentAdaptingMatcherFunc< internal::HasParentMatcher, internal::TypeList< Decl, NestedNameSpecifierLoc, Stmt, TypeLoc, Attr >, internal::TypeList< Decl, NestedNameSpecifierLoc, Stmt, TypeLoc, Attr > > hasParent
Matches AST nodes that have a parent that matches the provided matcher.
unsigned kind
All of the diagnostics that can be emitted by the frontend.
Definition: DiagnosticIDs.h:76
std::variant< struct RequiresDecl, struct HeaderDecl, struct UmbrellaDirDecl, struct ModuleDecl, struct ExcludeDecl, struct ExportDecl, struct ExportAsDecl, struct ExternModuleDecl, struct UseDecl, struct LinkDecl, struct ConfigMacrosDecl, struct ConflictDecl > Decl
All declarations that can appear in a module declaration.
Definition: ModuleMapFile.h:36
The JSON file list parser is used to communicate input to InstallAPI.
@ TK_AsIs
Will traverse all child nodes.
Definition: ASTTypeTraits.h:40
@ Result
The result type of a method or function.
CastKind
CastKind - The kind of operation required for a conversion.
const FunctionProtoType * T
static bool canExprResolveTo(const Expr *Source, const Expr *Target)
const Stmt * findPointeeMutation(const Expr *Exp)
const Stmt * findMutation(const Expr *Exp)
llvm::DenseMap< const Expr *, const Stmt * > ResultMap