clang 19.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"
13#include "llvm/ADT/STLExtras.h"
14
15namespace clang {
16using 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
24static 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
93namespace {
94
95AST_MATCHER_P(LambdaExpr, hasCaptureInit, const Expr *, E) {
96 return llvm::is_contained(Node.capture_inits(), E);
97}
98
99AST_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
105AST_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.
117AST_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
129const ast_matchers::internal::VariadicDynCastAllOfMatcher<Stmt, CXXTypeidExpr>
130 cxxTypeidExpr;
131
132AST_MATCHER(CXXTypeidExpr, isPotentiallyEvaluated) {
133 return Node.isPotentiallyEvaluated();
134}
135
136AST_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
150AST_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
157template <typename T>
158ast_matchers::internal::Matcher<T>
159findFirst(const ast_matchers::internal::Matcher<T> &Matcher) {
160 return anyOf(Matcher, hasDescendant(Matcher));
161}
162
163const auto nonConstReferenceType = [] {
164 return hasUnqualifiedDesugaredType(
165 referenceType(pointee(unless(isConstQualified()))));
166};
167
168const auto nonConstPointerType = [] {
169 return hasUnqualifiedDesugaredType(
170 pointerType(pointee(unless(isConstQualified()))));
171};
172
173const 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
183template <class T> struct NodeID;
184template <> struct NodeID<Expr> { static constexpr StringRef value = "expr"; };
185template <> struct NodeID<Decl> { static constexpr StringRef value = "decl"; };
186constexpr StringRef NodeID<Expr>::value;
187constexpr StringRef NodeID<Decl>::value;
188
189template <class T,
190 class F = const Stmt *(ExprMutationAnalyzer::Analyzer::*)(const T *)>
191const Stmt *tryEachMatch(ArrayRef<ast_matchers::BoundNodes> Matches,
192 ExprMutationAnalyzer::Analyzer *Analyzer, F Finder) {
193 const StringRef ID = NodeID<T>::value;
194 for (const auto &Nodes : Matches) {
195 if (const Stmt *S = (Analyzer->*Finder)(Nodes.getNodeAs<T>(ID)))
196 return S;
197 }
198 return nullptr;
199}
200
201} // namespace
202
204 return findMutationMemoized(
205 Exp,
206 {&ExprMutationAnalyzer::Analyzer::findDirectMutation,
207 &ExprMutationAnalyzer::Analyzer::findMemberMutation,
208 &ExprMutationAnalyzer::Analyzer::findArrayElementMutation,
209 &ExprMutationAnalyzer::Analyzer::findCastMutation,
210 &ExprMutationAnalyzer::Analyzer::findRangeLoopMutation,
211 &ExprMutationAnalyzer::Analyzer::findReferenceMutation,
212 &ExprMutationAnalyzer::Analyzer::findFunctionArgMutation},
213 Memorized.Results);
214}
215
217 return tryEachDeclRef(Dec, &ExprMutationAnalyzer::Analyzer::findMutation);
218}
219
220const Stmt *
222 return findMutationMemoized(Exp, {/*TODO*/}, Memorized.PointeeResults);
223}
224
225const Stmt *
227 return tryEachDeclRef(Dec,
229}
230
231const Stmt *ExprMutationAnalyzer::Analyzer::findMutationMemoized(
232 const Expr *Exp, llvm::ArrayRef<MutationFinder> Finders,
233 Memoized::ResultMap &MemoizedResults) {
234 const auto Memoized = MemoizedResults.find(Exp);
235 if (Memoized != MemoizedResults.end())
236 return Memoized->second;
237
238 // Assume Exp is not mutated before analyzing Exp.
239 MemoizedResults[Exp] = nullptr;
240 if (isUnevaluated(Exp))
241 return nullptr;
242
243 for (const auto &Finder : Finders) {
244 if (const Stmt *S = (this->*Finder)(Exp))
245 return MemoizedResults[Exp] = S;
246 }
247
248 return nullptr;
249}
250
251const Stmt *
252ExprMutationAnalyzer::Analyzer::tryEachDeclRef(const Decl *Dec,
253 MutationFinder Finder) {
254 const auto Refs = match(
255 findAll(
256 declRefExpr(to(
257 // `Dec` or a binding if `Dec` is a decomposition.
258 anyOf(equalsNode(Dec),
259 bindingDecl(forDecomposition(equalsNode(Dec))))
260 //
261 ))
262 .bind(NodeID<Expr>::value)),
263 Stm, Context);
264 for (const auto &RefNodes : Refs) {
265 const auto *E = RefNodes.getNodeAs<Expr>(NodeID<Expr>::value);
266 if ((this->*Finder)(E))
267 return E;
268 }
269 return nullptr;
270}
271
273 const Stmt &Stm,
274 ASTContext &Context) {
275 return selectFirst<Stmt>(
276 NodeID<Expr>::value,
277 match(
278 findFirst(
279 stmt(canResolveToExpr(Exp),
280 anyOf(
281 // `Exp` is part of the underlying expression of
282 // decltype/typeof if it has an ancestor of
283 // typeLoc.
287 // `UnaryExprOrTypeTraitExpr` is unevaluated
288 // unless it's sizeof on VLA.
290 hasArgumentOfType(variableArrayType())))),
291 // `CXXTypeidExpr` is unevaluated unless it's
292 // applied to an expression of glvalue of
293 // polymorphic class type.
294 cxxTypeidExpr(
295 unless(isPotentiallyEvaluated())),
296 // The controlling expression of
297 // `GenericSelectionExpr` is unevaluated.
298 genericSelectionExpr(hasControllingExpr(
299 hasDescendant(equalsNode(Exp)))),
300 cxxNoexceptExpr())))))
301 .bind(NodeID<Expr>::value)),
302 Stm, Context)) != nullptr;
303}
304
306 return isUnevaluated(Exp, Stm, Context);
307}
308
309const Stmt *
310ExprMutationAnalyzer::Analyzer::findExprMutation(ArrayRef<BoundNodes> Matches) {
311 return tryEachMatch<Expr>(Matches, this,
313}
314
315const Stmt *
316ExprMutationAnalyzer::Analyzer::findDeclMutation(ArrayRef<BoundNodes> Matches) {
317 return tryEachMatch<Decl>(Matches, this,
319}
320
321const Stmt *ExprMutationAnalyzer::Analyzer::findExprPointeeMutation(
322 ArrayRef<ast_matchers::BoundNodes> Matches) {
323 return tryEachMatch<Expr>(
325}
326
327const Stmt *ExprMutationAnalyzer::Analyzer::findDeclPointeeMutation(
328 ArrayRef<ast_matchers::BoundNodes> Matches) {
329 return tryEachMatch<Decl>(
331}
332
333const Stmt *
334ExprMutationAnalyzer::Analyzer::findDirectMutation(const Expr *Exp) {
335 // LHS of any assignment operators.
336 const auto AsAssignmentLhs =
337 binaryOperator(isAssignmentOperator(), hasLHS(canResolveToExpr(Exp)));
338
339 // Operand of increment/decrement operators.
340 const auto AsIncDecOperand =
341 unaryOperator(anyOf(hasOperatorName("++"), hasOperatorName("--")),
342 hasUnaryOperand(canResolveToExpr(Exp)));
343
344 // Invoking non-const member function.
345 // A member function is assumed to be non-const when it is unresolved.
346 const auto NonConstMethod = cxxMethodDecl(unless(isConst()));
347
348 const auto AsNonConstThis = expr(anyOf(
349 cxxMemberCallExpr(on(canResolveToExpr(Exp)), unless(isConstCallee())),
350 cxxOperatorCallExpr(callee(NonConstMethod),
351 hasArgument(0, canResolveToExpr(Exp))),
352 // In case of a templated type, calling overloaded operators is not
353 // resolved and modelled as `binaryOperator` on a dependent type.
354 // Such instances are considered a modification, because they can modify
355 // in different instantiations of the template.
356 binaryOperator(isTypeDependent(),
357 hasEitherOperand(ignoringImpCasts(canResolveToExpr(Exp)))),
358 // A fold expression may contain `Exp` as it's initializer.
359 // We don't know if the operator modifies `Exp` because the
360 // operator is type dependent due to the parameter pack.
361 cxxFoldExpr(hasFoldInit(ignoringImpCasts(canResolveToExpr(Exp)))),
362 // Within class templates and member functions the member expression might
363 // not be resolved. In that case, the `callExpr` is considered to be a
364 // modification.
365 callExpr(callee(expr(anyOf(
366 unresolvedMemberExpr(hasObjectExpression(canResolveToExpr(Exp))),
368 hasObjectExpression(canResolveToExpr(Exp))))))),
369 // Match on a call to a known method, but the call itself is type
370 // dependent (e.g. `vector<T> v; v.push(T{});` in a templated function).
372 isTypeDependent(),
373 callee(memberExpr(hasDeclaration(NonConstMethod),
374 hasObjectExpression(canResolveToExpr(Exp))))))));
375
376 // Taking address of 'Exp'.
377 // We're assuming 'Exp' is mutated as soon as its address is taken, though in
378 // theory we can follow the pointer and see whether it escaped `Stm` or is
379 // dereferenced and then mutated. This is left for future improvements.
380 const auto AsAmpersandOperand =
381 unaryOperator(hasOperatorName("&"),
382 // A NoOp implicit cast is adding const.
383 unless(hasParent(implicitCastExpr(hasCastKind(CK_NoOp)))),
384 hasUnaryOperand(canResolveToExpr(Exp)));
385 const auto AsPointerFromArrayDecay = castExpr(
386 hasCastKind(CK_ArrayToPointerDecay),
387 unless(hasParent(arraySubscriptExpr())), has(canResolveToExpr(Exp)));
388 // Treat calling `operator->()` of move-only classes as taking address.
389 // These are typically smart pointers with unique ownership so we treat
390 // mutation of pointee as mutation of the smart pointer itself.
391 const auto AsOperatorArrowThis = cxxOperatorCallExpr(
393 callee(
394 cxxMethodDecl(ofClass(isMoveOnly()), returns(nonConstPointerType()))),
395 argumentCountIs(1), hasArgument(0, canResolveToExpr(Exp)));
396
397 // Used as non-const-ref argument when calling a function.
398 // An argument is assumed to be non-const-ref when the function is unresolved.
399 // Instantiated template functions are not handled here but in
400 // findFunctionArgMutation which has additional smarts for handling forwarding
401 // references.
402 const auto NonConstRefParam = forEachArgumentWithParamType(
403 anyOf(canResolveToExpr(Exp),
404 memberExpr(hasObjectExpression(canResolveToExpr(Exp)))),
405 nonConstReferenceType());
406 const auto NotInstantiated = unless(hasDeclaration(isInstantiated()));
407 const auto TypeDependentCallee =
410 hasType(templateTypeParmType()), isTypeDependent())));
411
412 const auto AsNonConstRefArg = anyOf(
413 callExpr(NonConstRefParam, NotInstantiated),
414 cxxConstructExpr(NonConstRefParam, NotInstantiated),
415 callExpr(TypeDependentCallee, hasAnyArgument(canResolveToExpr(Exp))),
416 cxxUnresolvedConstructExpr(hasAnyArgument(canResolveToExpr(Exp))),
417 // Previous False Positive in the following Code:
418 // `template <typename T> void f() { int i = 42; new Type<T>(i); }`
419 // Where the constructor of `Type` takes its argument as reference.
420 // The AST does not resolve in a `cxxConstructExpr` because it is
421 // type-dependent.
422 parenListExpr(hasDescendant(expr(canResolveToExpr(Exp)))),
423 // If the initializer is for a reference type, there is no cast for
424 // the variable. Values are cast to RValue first.
425 initListExpr(hasAnyInit(expr(canResolveToExpr(Exp)))));
426
427 // Captured by a lambda by reference.
428 // If we're initializing a capture with 'Exp' directly then we're initializing
429 // a reference capture.
430 // For value captures there will be an ImplicitCastExpr <LValueToRValue>.
431 const auto AsLambdaRefCaptureInit = lambdaExpr(hasCaptureInit(Exp));
432
433 // Returned as non-const-ref.
434 // If we're returning 'Exp' directly then it's returned as non-const-ref.
435 // For returning by value there will be an ImplicitCastExpr <LValueToRValue>.
436 // For returning by const-ref there will be an ImplicitCastExpr <NoOp> (for
437 // adding const.)
438 const auto AsNonConstRefReturn =
439 returnStmt(hasReturnValue(canResolveToExpr(Exp)));
440
441 // It is used as a non-const-reference for initializing a range-for loop.
442 const auto AsNonConstRefRangeInit = cxxForRangeStmt(hasRangeInit(declRefExpr(
443 allOf(canResolveToExpr(Exp), hasType(nonConstReferenceType())))));
444
445 const auto Matches = match(
446 traverse(
447 TK_AsIs,
448 findFirst(stmt(anyOf(AsAssignmentLhs, AsIncDecOperand, AsNonConstThis,
449 AsAmpersandOperand, AsPointerFromArrayDecay,
450 AsOperatorArrowThis, AsNonConstRefArg,
451 AsLambdaRefCaptureInit, AsNonConstRefReturn,
452 AsNonConstRefRangeInit))
453 .bind("stmt"))),
454 Stm, Context);
455 return selectFirst<Stmt>("stmt", Matches);
456}
457
458const Stmt *
459ExprMutationAnalyzer::Analyzer::findMemberMutation(const Expr *Exp) {
460 // Check whether any member of 'Exp' is mutated.
461 const auto MemberExprs = match(
462 findAll(expr(anyOf(memberExpr(hasObjectExpression(canResolveToExpr(Exp))),
464 hasObjectExpression(canResolveToExpr(Exp))),
465 binaryOperator(hasOperatorName(".*"),
466 hasLHS(equalsNode(Exp)))))
467 .bind(NodeID<Expr>::value)),
468 Stm, Context);
469 return findExprMutation(MemberExprs);
470}
471
472const Stmt *
473ExprMutationAnalyzer::Analyzer::findArrayElementMutation(const Expr *Exp) {
474 // Check whether any element of an array is mutated.
475 const auto SubscriptExprs = match(
477 anyOf(hasBase(canResolveToExpr(Exp)),
478 hasBase(implicitCastExpr(allOf(
479 hasCastKind(CK_ArrayToPointerDecay),
480 hasSourceExpression(canResolveToExpr(Exp)))))))
481 .bind(NodeID<Expr>::value)),
482 Stm, Context);
483 return findExprMutation(SubscriptExprs);
484}
485
486const Stmt *ExprMutationAnalyzer::Analyzer::findCastMutation(const Expr *Exp) {
487 // If the 'Exp' is explicitly casted to a non-const reference type the
488 // 'Exp' is considered to be modified.
489 const auto ExplicitCast =
490 match(findFirst(stmt(castExpr(hasSourceExpression(canResolveToExpr(Exp)),
491 explicitCastExpr(hasDestinationType(
492 nonConstReferenceType()))))
493 .bind("stmt")),
494 Stm, Context);
495
496 if (const auto *CastStmt = selectFirst<Stmt>("stmt", ExplicitCast))
497 return CastStmt;
498
499 // If 'Exp' is casted to any non-const reference type, check the castExpr.
500 const auto Casts = match(
501 findAll(expr(castExpr(hasSourceExpression(canResolveToExpr(Exp)),
502 anyOf(explicitCastExpr(hasDestinationType(
503 nonConstReferenceType())),
504 implicitCastExpr(hasImplicitDestinationType(
505 nonConstReferenceType())))))
506 .bind(NodeID<Expr>::value)),
507 Stm, Context);
508
509 if (const Stmt *S = findExprMutation(Casts))
510 return S;
511 // Treat std::{move,forward} as cast.
512 const auto Calls =
514 hasAnyName("::std::move", "::std::forward"))),
515 hasArgument(0, canResolveToExpr(Exp)))
516 .bind("expr")),
517 Stm, Context);
518 return findExprMutation(Calls);
519}
520
521const Stmt *
522ExprMutationAnalyzer::Analyzer::findRangeLoopMutation(const Expr *Exp) {
523 // Keep the ordering for the specific initialization matches to happen first,
524 // because it is cheaper to match all potential modifications of the loop
525 // variable.
526
527 // The range variable is a reference to a builtin array. In that case the
528 // array is considered modified if the loop-variable is a non-const reference.
529 const auto DeclStmtToNonRefToArray = declStmt(hasSingleDecl(varDecl(hasType(
530 hasUnqualifiedDesugaredType(referenceType(pointee(arrayType())))))));
531 const auto RefToArrayRefToElements = match(
532 findFirst(stmt(cxxForRangeStmt(
533 hasLoopVariable(
534 varDecl(anyOf(hasType(nonConstReferenceType()),
535 hasType(nonConstPointerType())))
536 .bind(NodeID<Decl>::value)),
537 hasRangeStmt(DeclStmtToNonRefToArray),
538 hasRangeInit(canResolveToExpr(Exp))))
539 .bind("stmt")),
540 Stm, Context);
541
542 if (const auto *BadRangeInitFromArray =
543 selectFirst<Stmt>("stmt", RefToArrayRefToElements))
544 return BadRangeInitFromArray;
545
546 // Small helper to match special cases in range-for loops.
547 //
548 // It is possible that containers do not provide a const-overload for their
549 // iterator accessors. If this is the case, the variable is used non-const
550 // no matter what happens in the loop. This requires special detection as it
551 // is then faster to find all mutations of the loop variable.
552 // It aims at a different modification as well.
553 const auto HasAnyNonConstIterator =
554 anyOf(allOf(hasMethod(allOf(hasName("begin"), unless(isConst()))),
555 unless(hasMethod(allOf(hasName("begin"), isConst())))),
556 allOf(hasMethod(allOf(hasName("end"), unless(isConst()))),
557 unless(hasMethod(allOf(hasName("end"), isConst())))));
558
559 const auto DeclStmtToNonConstIteratorContainer = declStmt(
560 hasSingleDecl(varDecl(hasType(hasUnqualifiedDesugaredType(referenceType(
561 pointee(hasDeclaration(cxxRecordDecl(HasAnyNonConstIterator)))))))));
562
563 const auto RefToContainerBadIterators = match(
564 findFirst(stmt(cxxForRangeStmt(allOf(
565 hasRangeStmt(DeclStmtToNonConstIteratorContainer),
566 hasRangeInit(canResolveToExpr(Exp)))))
567 .bind("stmt")),
568 Stm, Context);
569
570 if (const auto *BadIteratorsContainer =
571 selectFirst<Stmt>("stmt", RefToContainerBadIterators))
572 return BadIteratorsContainer;
573
574 // If range for looping over 'Exp' with a non-const reference loop variable,
575 // check all declRefExpr of the loop variable.
576 const auto LoopVars =
578 hasLoopVariable(varDecl(hasType(nonConstReferenceType()))
579 .bind(NodeID<Decl>::value)),
580 hasRangeInit(canResolveToExpr(Exp)))),
581 Stm, Context);
582 return findDeclMutation(LoopVars);
583}
584
585const Stmt *
586ExprMutationAnalyzer::Analyzer::findReferenceMutation(const Expr *Exp) {
587 // Follow non-const reference returned by `operator*()` of move-only classes.
588 // These are typically smart pointers with unique ownership so we treat
589 // mutation of pointee as mutation of the smart pointer itself.
590 const auto Ref = match(
593 callee(cxxMethodDecl(ofClass(isMoveOnly()),
594 returns(nonConstReferenceType()))),
595 argumentCountIs(1), hasArgument(0, canResolveToExpr(Exp)))
596 .bind(NodeID<Expr>::value)),
597 Stm, Context);
598 if (const Stmt *S = findExprMutation(Ref))
599 return S;
600
601 // If 'Exp' is bound to a non-const reference, check all declRefExpr to that.
602 const auto Refs = match(
604 varDecl(hasType(nonConstReferenceType()),
605 hasInitializer(anyOf(
606 canResolveToExpr(Exp),
607 memberExpr(hasObjectExpression(canResolveToExpr(Exp))))),
608 hasParent(declStmt().bind("stmt")),
609 // Don't follow the reference in range statement, we've
610 // handled that separately.
612 hasRangeStmt(equalsBoundNode("stmt"))))))))
613 .bind(NodeID<Decl>::value))),
614 Stm, Context);
615 return findDeclMutation(Refs);
616}
617
618const Stmt *
619ExprMutationAnalyzer::Analyzer::findFunctionArgMutation(const Expr *Exp) {
620 const auto NonConstRefParam = forEachArgumentWithParam(
621 canResolveToExpr(Exp),
622 parmVarDecl(hasType(nonConstReferenceType())).bind("parm"));
623 const auto IsInstantiated = hasDeclaration(isInstantiated());
624 const auto FuncDecl = hasDeclaration(functionDecl().bind("func"));
625 const auto Matches = match(
626 traverse(
627 TK_AsIs,
628 findAll(
629 expr(anyOf(callExpr(NonConstRefParam, IsInstantiated, FuncDecl,
631 "::std::move", "::std::forward"))))),
632 cxxConstructExpr(NonConstRefParam, IsInstantiated,
633 FuncDecl)))
634 .bind(NodeID<Expr>::value))),
635 Stm, Context);
636 for (const auto &Nodes : Matches) {
637 const auto *Exp = Nodes.getNodeAs<Expr>(NodeID<Expr>::value);
638 const auto *Func = Nodes.getNodeAs<FunctionDecl>("func");
639 if (!Func->getBody() || !Func->getPrimaryTemplate())
640 return Exp;
641
642 const auto *Parm = Nodes.getNodeAs<ParmVarDecl>("parm");
643 const ArrayRef<ParmVarDecl *> AllParams =
644 Func->getPrimaryTemplate()->getTemplatedDecl()->parameters();
645 QualType ParmType =
646 AllParams[std::min<size_t>(Parm->getFunctionScopeIndex(),
647 AllParams.size() - 1)]
648 ->getType();
649 if (const auto *T = ParmType->getAs<PackExpansionType>())
650 ParmType = T->getPattern();
651
652 // If param type is forwarding reference, follow into the function
653 // definition and see whether the param is mutated inside.
654 if (const auto *RefType = ParmType->getAs<RValueReferenceType>()) {
655 if (!RefType->getPointeeType().getQualifiers() &&
656 RefType->getPointeeType()->getAs<TemplateTypeParmType>()) {
659 *Func, Context, Memorized);
660 if (Analyzer->findMutation(Parm))
661 return Exp;
662 continue;
663 }
664 }
665 // Not forwarding reference.
666 return Exp;
667 }
668 return nullptr;
669}
670
671FunctionParmMutationAnalyzer::FunctionParmMutationAnalyzer(
672 const FunctionDecl &Func, ASTContext &Context,
673 ExprMutationAnalyzer::Memoized &Memorized)
674 : BodyAnalyzer(*Func.getBody(), Context, Memorized) {
675 if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(&Func)) {
676 // CXXCtorInitializer might also mutate Param but they're not part of
677 // function body, check them eagerly here since they're typically trivial.
678 for (const CXXCtorInitializer *Init : Ctor->inits()) {
679 ExprMutationAnalyzer::Analyzer InitAnalyzer(*Init->getInit(), Context,
680 Memorized);
681 for (const ParmVarDecl *Parm : Ctor->parameters()) {
682 if (Results.contains(Parm))
683 continue;
684 if (const Stmt *S = InitAnalyzer.findMutation(Parm))
685 Results[Parm] = S;
686 }
687 }
688 }
689}
690
691const Stmt *
693 const auto Memoized = Results.find(Parm);
694 if (Memoized != Results.end())
695 return Memoized->second;
696 // To handle call A -> call B -> call A. Assume parameters of A is not mutated
697 // before analyzing parameters of A. Then when analyzing the second "call A",
698 // FunctionParmMutationAnalyzer can use this memoized value to avoid infinite
699 // recursion.
700 Results[Parm] = nullptr;
701 if (const Stmt *S = BodyAnalyzer.findMutation(Parm))
702 return Results[Parm] = S;
703 return Results[Parm];
704}
705
706} // 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
llvm::MachO::Target Target
Definition: MachO.h:50
SourceRange Range
Definition: SemaObjC.cpp:754
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:182
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
static bool isUnevaluated(const Stmt *Smt, const Stmt &Stm, ASTContext &Context)
This represents one expression.
Definition: Expr.h:110
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3055
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:1761
Stmt - This represents one statement.
Definition: Stmt.h:84
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8126
@ Decl
The l-value was an access to a declared entity or something equivalently strong, like the address of ...
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< Stmt, UnresolvedLookupExpr > unresolvedLookupExpr
Matches reference to a name that can be looked up during parsing but could not be resolved to a speci...
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:3079
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< 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::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:3058
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 AstTypeMatcher< TemplateTypeParmType > templateTypeParmType
Matches template type parameter types.
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:3142
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:817
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:3568
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:3653
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.
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.
const FunctionProtoType * T
static bool canExprResolveTo(const Expr *Source, const Expr *Target)
static bool isUnevaluated(const Stmt *Smt, const Stmt &Stm, ASTContext &Context)
const Stmt * findPointeeMutation(const Expr *Exp)
const Stmt * findMutation(const Expr *Exp)
llvm::DenseMap< const Expr *, const Stmt * > ResultMap