clang 24.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->getOpcode() == BO_AddAssign || BO->getOpcode() == BO_SubAssign)
131 return resolveExpr(BO->getLHS());
132 if (BO->getOpcode() == BO_Assign)
133 return (resolveExpr(BO->getLHS()) || resolveExpr(BO->getRHS()));
134 if (BO->isCommaOp())
135 return resolveExpr(BO->getRHS());
136 return false;
137 }
138
139 if (const auto *PE = dyn_cast<ParenExpr>(E))
140 return resolveExpr(PE->getSubExpr());
141
142 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
143 if (UO->getOpcode() == UO_AddrOf || UO->isIncrementDecrementOp())
144 return resolveExpr(UO->getSubExpr());
145 }
146
147 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
148 // only implicit cast needs to be treated as resolvable.
149 // explicit cast will be checked in `findPointeeToNonConst`
150 const CastKind kind = ICE->getCastKind();
151 if (kind == CK_LValueToRValue || kind == CK_DerivedToBase ||
152 kind == CK_UncheckedDerivedToBase || kind == CK_NoOp ||
153 kind == CK_BitCast)
154 return resolveExpr(ICE->getSubExpr());
155 return false;
156 }
157
158 if (const auto *ACE = dyn_cast<AbstractConditionalOperator>(E))
159 return resolve(ACE->getTrueExpr()) || resolve(ACE->getFalseExpr());
160
161 return false;
162 }
163
164public:
165 ExprPointeeResolve(const Expr *T) : T(T) {}
166 bool resolve(const Expr *S) { return resolveExpr(S); }
167};
168
169AST_MATCHER_P(Stmt, canResolveToExprPointee, const Stmt *, T) {
170 auto *Exp = dyn_cast<Expr>(&Node);
171 if (!Exp)
172 return true;
173 auto *Target = dyn_cast<Expr>(T);
174 if (!Target)
175 return false;
176 return ExprPointeeResolve{Target}.resolve(Exp);
177}
178
179// Similar to 'hasAnyArgument', but does not work because 'InitListExpr' does
180// not have the 'arguments()' method.
181AST_MATCHER_P(InitListExpr, hasAnyInit, ast_matchers::internal::Matcher<Expr>,
182 InnerMatcher) {
183 for (const Expr *Arg : Node.inits()) {
184 if (Arg == nullptr)
185 continue;
186 ast_matchers::internal::BoundNodesTreeBuilder Result(*Builder);
187 if (InnerMatcher.matches(*Arg, Finder, &Result)) {
188 *Builder = std::move(Result);
189 return true;
190 }
191 }
192 return false;
193}
194
195const ast_matchers::internal::VariadicDynCastAllOfMatcher<Stmt, CXXTypeidExpr>
196 cxxTypeidExpr;
197
198AST_MATCHER(CXXTypeidExpr, isPotentiallyEvaluated) {
199 return Node.isPotentiallyEvaluated();
200}
201
202AST_MATCHER(CXXMemberCallExpr, isConstCallee) {
203 const Decl *CalleeDecl = Node.getCalleeDecl();
204 const auto *VD = dyn_cast_or_null<ValueDecl>(CalleeDecl);
205 if (!VD)
206 return false;
207 const QualType T = VD->getType().getCanonicalType();
208 const auto *MPT = dyn_cast<MemberPointerType>(T);
209 const auto *FPT = MPT ? cast<FunctionProtoType>(MPT->getPointeeType())
210 : dyn_cast<FunctionProtoType>(T);
211 if (!FPT)
212 return false;
213 return FPT->isConst();
214}
215
216AST_MATCHER_P(GenericSelectionExpr, hasControllingExpr,
217 ast_matchers::internal::Matcher<Expr>, InnerMatcher) {
218 if (Node.isTypePredicate())
219 return false;
220 return InnerMatcher.matches(*Node.getControllingExpr(), Finder, Builder);
221}
222
223template <typename T>
224ast_matchers::internal::Matcher<T>
225findFirst(const ast_matchers::internal::Matcher<T> &Matcher) {
226 return anyOf(Matcher, hasDescendant(Matcher));
227}
228
229const auto nonConstReferenceType = [] {
230 return hasUnqualifiedDesugaredType(
231 referenceType(pointee(unless(isConstQualified()))));
232};
233
234const auto constReferenceToPointerWithNonConstPointeeType = [] {
235 return hasUnqualifiedDesugaredType(referenceType(pointee(qualType(
236 isConstQualified(), hasUnqualifiedDesugaredType(pointerType(
237 pointee(unless(isConstQualified()))))))));
238};
239
240const auto nonConstPointerType = [] {
241 return hasUnqualifiedDesugaredType(
242 pointerType(pointee(unless(isConstQualified()))));
243};
244
245const auto isMoveOnly = [] {
246 return cxxRecordDecl(
247 hasMethod(cxxConstructorDecl(isMoveConstructor(), unless(isDeleted()))),
248 hasMethod(cxxMethodDecl(isMoveAssignmentOperator(), unless(isDeleted()))),
249 unless(anyOf(hasMethod(cxxConstructorDecl(isCopyConstructor(),
250 unless(isDeleted()))),
251 hasMethod(cxxMethodDecl(isCopyAssignmentOperator(),
252 unless(isDeleted()))))));
253};
254
255template <class T> struct NodeID;
256template <> struct NodeID<Expr> {
257 static constexpr StringRef value = "expr";
258};
259template <> struct NodeID<Decl> {
260 static constexpr StringRef value = "decl";
261};
262
263template <class T,
264 class F = const Stmt *(ExprMutationAnalyzer::Analyzer::*)(const T *)>
265const Stmt *tryEachMatch(ArrayRef<ast_matchers::BoundNodes> Matches,
266 ExprMutationAnalyzer::Analyzer *Analyzer, F Finder) {
267 const StringRef ID = NodeID<T>::value;
268 for (const auto &Nodes : Matches) {
269 if (const Stmt *S = (Analyzer->*Finder)(Nodes.getNodeAs<T>(ID)))
270 return S;
271 }
272 return nullptr;
273}
274
275} // namespace
276
278 return findMutationMemoized(
279 Exp,
280 {&ExprMutationAnalyzer::Analyzer::findDirectMutation,
281 &ExprMutationAnalyzer::Analyzer::findMemberMutation,
282 &ExprMutationAnalyzer::Analyzer::findArrayElementMutation,
283 &ExprMutationAnalyzer::Analyzer::findCastMutation,
284 &ExprMutationAnalyzer::Analyzer::findRangeLoopMutation,
285 &ExprMutationAnalyzer::Analyzer::findReferenceMutation,
286 &ExprMutationAnalyzer::Analyzer::findFunctionArgMutation},
287 Memorized.Results);
288}
289
293
294const Stmt *
296 return findMutationMemoized(
297 Exp,
298 {
299 &ExprMutationAnalyzer::Analyzer::findPointeeValueMutation,
300 &ExprMutationAnalyzer::Analyzer::findPointeeMemberMutation,
301 &ExprMutationAnalyzer::Analyzer::findPointeeToNonConst,
302 },
303 Memorized.PointeeResults);
304}
305
306const Stmt *
311
312const Stmt *ExprMutationAnalyzer::Analyzer::findMutationMemoized(
313 const Expr *Exp, llvm::ArrayRef<MutationFinder> Finders,
314 Memoized::ResultMap &MemoizedResults) {
315 // Assume Exp is not mutated before analyzing Exp.
316 auto [Memoized, Inserted] = MemoizedResults.try_emplace(Exp);
317 if (!Inserted)
318 return Memoized->second;
319
320 if (ExprMutationAnalyzer::isUnevaluated(Exp, Context))
321 return nullptr;
322
323 for (const auto &Finder : Finders) {
324 if (const Stmt *S = (this->*Finder)(Exp))
325 return MemoizedResults[Exp] = S;
326 }
327
328 return nullptr;
329}
330
331const Stmt *
332ExprMutationAnalyzer::Analyzer::tryEachDeclRef(const Decl *Dec,
333 MutationFinder Finder) {
334 const auto Refs = match(
335 findAll(
336 declRefExpr(to(
337 // `Dec` or a binding if `Dec` is a decomposition.
338 anyOf(equalsNode(Dec),
339 bindingDecl(forDecomposition(equalsNode(Dec))))
340 //
341 ))
342 .bind(NodeID<Expr>::value)),
343 Stm, Context);
344 for (const auto &RefNodes : Refs) {
345 const auto *E = RefNodes.getNodeAs<Expr>(NodeID<Expr>::value);
346 if ((this->*Finder)(E))
347 return E;
348 }
349 return nullptr;
350}
351
353 return !match(stmt(anyOf(
354 // `Exp` is part of the underlying expression of
355 // decltype/typeof if it has an ancestor of
356 // typeLoc.
360 // `UnaryExprOrTypeTraitExpr` is unevaluated
361 // unless it's sizeof on VLA.
363 hasArgumentOfType(variableArrayType())))),
364 // `CXXTypeidExpr` is unevaluated unless it's
365 // applied to an expression of glvalue of
366 // polymorphic class type.
367 cxxTypeidExpr(unless(isPotentiallyEvaluated())),
368 // The controlling expression of
369 // `GenericSelectionExpr` is unevaluated.
371 hasControllingExpr(hasDescendant(equalsNode(Stm)))),
372 cxxNoexceptExpr()))))),
373 *Stm, Context)
374 .empty();
375}
376
377const Stmt *
378ExprMutationAnalyzer::Analyzer::findExprMutation(ArrayRef<BoundNodes> Matches) {
379 return tryEachMatch<Expr>(Matches, this,
381}
382
383const Stmt *
384ExprMutationAnalyzer::Analyzer::findDeclMutation(ArrayRef<BoundNodes> Matches) {
385 return tryEachMatch<Decl>(Matches, this,
387}
388
389const Stmt *ExprMutationAnalyzer::Analyzer::findExprPointeeMutation(
390 ArrayRef<ast_matchers::BoundNodes> Matches) {
391 return tryEachMatch<Expr>(
393}
394
395const Stmt *ExprMutationAnalyzer::Analyzer::findDeclPointeeMutation(
396 ArrayRef<ast_matchers::BoundNodes> Matches) {
397 return tryEachMatch<Decl>(
399}
400
401const Stmt *
402ExprMutationAnalyzer::Analyzer::findDirectMutation(const Expr *Exp) {
403 // LHS of any assignment operators.
404 const auto AsAssignmentLhs =
405 binaryOperator(isAssignmentOperator(), hasLHS(canResolveToExpr(Exp)));
406
407 // Operand of increment/decrement operators.
408 const auto AsIncDecOperand =
409 unaryOperator(anyOf(hasOperatorName("++"), hasOperatorName("--")),
410 hasUnaryOperand(canResolveToExpr(Exp)));
411
412 // Invoking non-const member function.
413 // A member function is assumed to be non-const when it is unresolved.
414 const auto NonConstMethod = cxxMethodDecl(unless(isConst()));
415
416 const auto AsNonConstThis = expr(anyOf(
417 // For member calls through a pointer, the pointer variable
418 // itself is not mutated but only the pointee is mutated.
420 on(canResolveToExpr(Exp)),
421 unless(anyOf(isConstCallee(), thisPointerType(pointerType())))),
422
423 cxxOperatorCallExpr(callee(NonConstMethod),
424 hasArgument(0, canResolveToExpr(Exp))),
425 // In case of a templated type, calling overloaded operators is not
426 // resolved and modelled as `binaryOperator` on a dependent type.
427 // Such instances are considered a modification, because they can modify
428 // in different instantiations of the template.
429 binaryOperator(isTypeDependent(),
430 hasEitherOperand(ignoringImpCasts(canResolveToExpr(Exp)))),
431 // A fold expression may contain `Exp` as it's initializer.
432 // We don't know if the operator modifies `Exp` because the
433 // operator is type dependent due to the parameter pack.
434 cxxFoldExpr(hasFoldInit(ignoringImpCasts(canResolveToExpr(Exp)))),
435 // Within class templates and member functions the member expression might
436 // not be resolved. In that case, the `callExpr` is considered to be a
437 // modification.
438 callExpr(callee(expr(anyOf(
439 unresolvedMemberExpr(hasObjectExpression(canResolveToExpr(Exp))),
441 hasObjectExpression(canResolveToExpr(Exp))))))),
442 // Match on a call to a known method, but the call itself is type
443 // dependent (e.g. `vector<T> v; v.push(T{});` in a templated function).
445 isTypeDependent(),
446 callee(memberExpr(hasDeclaration(NonConstMethod),
447 hasObjectExpression(canResolveToExpr(Exp))))))));
448
449 // Taking address of 'Exp'.
450 // We're assuming 'Exp' is mutated as soon as its address is taken, though in
451 // theory we can follow the pointer and see whether it escaped `Stm` or is
452 // dereferenced and then mutated. This is left for future improvements.
453 const auto AsAmpersandOperand =
454 unaryOperator(hasOperatorName("&"),
455 // A NoOp implicit cast is adding const.
456 unless(hasParent(implicitCastExpr(hasCastKind(CK_NoOp)))),
457 hasUnaryOperand(canResolveToExpr(Exp)));
458 const auto AsPointerFromArrayDecay = castExpr(
459 hasCastKind(CK_ArrayToPointerDecay),
460 unless(hasParent(arraySubscriptExpr())), has(canResolveToExpr(Exp)));
461 // Treat calling `operator->()` of move-only classes as taking address.
462 // These are typically smart pointers with unique ownership so we treat
463 // mutation of pointee as mutation of the smart pointer itself.
464 const auto AsOperatorArrowThis = cxxOperatorCallExpr(
466 callee(
467 cxxMethodDecl(ofClass(isMoveOnly()), returns(nonConstPointerType()))),
468 argumentCountIs(1), hasArgument(0, canResolveToExpr(Exp)));
469
470 // Used as non-const-ref argument when calling a function.
471 // An argument is assumed to be non-const-ref when the function is unresolved.
472 // Instantiated template functions are not handled here but in
473 // findFunctionArgMutation which has additional smarts for handling forwarding
474 // references.
475 const auto NonConstRefParam = forEachArgumentWithParamType(
476 anyOf(canResolveToExpr(Exp),
478 hasObjectExpression(ignoringImpCasts(canResolveToExpr(Exp))))),
479 nonConstReferenceType());
480 const auto NotInstantiated = unless(hasDeclaration(isInstantiated()));
481
482 const auto AsNonConstRefArg =
483 anyOf(callExpr(NonConstRefParam, NotInstantiated),
484 cxxConstructExpr(NonConstRefParam, NotInstantiated),
485 // If the call is type-dependent, we can't properly process any
486 // argument because required type conversions and implicit casts
487 // will be inserted only after specialization.
488 callExpr(isTypeDependent(), hasAnyArgument(canResolveToExpr(Exp))),
489 cxxUnresolvedConstructExpr(hasAnyArgument(canResolveToExpr(Exp))),
490 // Previous False Positive in the following Code:
491 // `template <typename T> void f() { int i = 42; new Type<T>(i); }`
492 // Where the constructor of `Type` takes its argument as reference.
493 // The AST does not resolve in a `cxxConstructExpr` because it is
494 // type-dependent.
495 parenListExpr(hasDescendant(expr(canResolveToExpr(Exp)))),
496 // If the initializer is for a reference type, there is no cast for
497 // the variable. Values are cast to RValue first.
498 initListExpr(hasAnyInit(expr(canResolveToExpr(Exp)))));
499
500 // Captured by a lambda by reference.
501 // If we're initializing a capture with 'Exp' directly then we're initializing
502 // a reference capture.
503 // For value captures there will be an ImplicitCastExpr <LValueToRValue>.
504 const auto AsLambdaRefCaptureInit = lambdaExpr(hasCaptureInit(Exp));
505
506 // Returned as non-const-ref.
507 // If we're returning 'Exp' directly then it's returned as non-const-ref.
508 // For returning by value there will be an ImplicitCastExpr <LValueToRValue>.
509 // For returning by const-ref there will be an ImplicitCastExpr <NoOp> (for
510 // adding const.)
511 const auto AsNonConstRefReturn =
512 returnStmt(hasReturnValue(canResolveToExpr(Exp)));
513
514 // It is used as a non-const-reference for initializing a range-for loop.
515 const auto AsNonConstRefRangeInit = cxxForRangeStmt(hasRangeInit(declRefExpr(
516 allOf(canResolveToExpr(Exp), hasType(nonConstReferenceType())))));
517
518 const auto Matches = match(
519 traverse(
520 TK_AsIs,
521 findFirst(stmt(anyOf(AsAssignmentLhs, AsIncDecOperand, AsNonConstThis,
522 AsAmpersandOperand, AsPointerFromArrayDecay,
523 AsOperatorArrowThis, AsNonConstRefArg,
524 AsLambdaRefCaptureInit, AsNonConstRefReturn,
525 AsNonConstRefRangeInit))
526 .bind("stmt"))),
527 Stm, Context);
528 return selectFirst<Stmt>("stmt", Matches);
529}
530
531const Stmt *
532ExprMutationAnalyzer::Analyzer::findMemberMutation(const Expr *Exp) {
533 // Check whether any member of 'Exp' is mutated.
534 const auto MemberExprs = match(
535 findAll(expr(anyOf(memberExpr(hasObjectExpression(canResolveToExpr(Exp))),
537 hasObjectExpression(canResolveToExpr(Exp))),
538 binaryOperator(hasOperatorName(".*"),
539 hasLHS(equalsNode(Exp)))))
540 .bind(NodeID<Expr>::value)),
541 Stm, Context);
542 return findExprMutation(MemberExprs);
543}
544
545const Stmt *
546ExprMutationAnalyzer::Analyzer::findArrayElementMutation(const Expr *Exp) {
547 // Check whether any element of an array is mutated.
548 const auto SubscriptExprs = match(
550 anyOf(hasBaseConservative(canResolveToExpr(Exp)),
551 hasBaseConservative(implicitCastExpr(allOf(
552 hasCastKind(CK_ArrayToPointerDecay),
553 hasSourceExpression(canResolveToExpr(Exp)))))))
554 .bind(NodeID<Expr>::value)),
555 Stm, Context);
556 return findExprMutation(SubscriptExprs);
557}
558
559const Stmt *ExprMutationAnalyzer::Analyzer::findCastMutation(const Expr *Exp) {
560 // If the 'Exp' is explicitly casted to a non-const reference type the
561 // 'Exp' is considered to be modified.
562 const auto ExplicitCast =
563 match(findFirst(stmt(castExpr(hasSourceExpression(canResolveToExpr(Exp)),
564 explicitCastExpr(hasDestinationType(
565 nonConstReferenceType()))))
566 .bind("stmt")),
567 Stm, Context);
568
569 if (const auto *CastStmt = selectFirst<Stmt>("stmt", ExplicitCast))
570 return CastStmt;
571
572 // If 'Exp' is casted to any non-const reference type, check the castExpr.
573 const auto Casts = match(
574 findAll(expr(castExpr(hasSourceExpression(canResolveToExpr(Exp)),
575 anyOf(explicitCastExpr(hasDestinationType(
576 nonConstReferenceType())),
577 implicitCastExpr(hasImplicitDestinationType(
578 nonConstReferenceType())))))
579 .bind(NodeID<Expr>::value)),
580 Stm, Context);
581
582 if (const Stmt *S = findExprMutation(Casts))
583 return S;
584 // Treat std::{move,forward} as cast.
585 const auto Calls =
587 hasAnyName("::std::move", "::std::forward"))),
588 hasArgument(0, canResolveToExpr(Exp)))
589 .bind("expr")),
590 Stm, Context);
591 return findExprMutation(Calls);
592}
593
594const Stmt *
595ExprMutationAnalyzer::Analyzer::findRangeLoopMutation(const Expr *Exp) {
596 // Keep the ordering for the specific initialization matches to happen first,
597 // because it is cheaper to match all potential modifications of the loop
598 // variable.
599
600 // The range variable is a reference to a builtin array. In that case the
601 // array is considered modified if the loop-variable is a non-const reference.
602 const auto DeclStmtToNonRefToArray = declStmt(hasSingleDecl(varDecl(hasType(
603 hasUnqualifiedDesugaredType(referenceType(pointee(arrayType())))))));
604 const auto RefToArrayRefToElements = match(
605 findFirst(stmt(cxxForRangeStmt(
606 hasLoopVariable(
607 varDecl(anyOf(hasType(nonConstReferenceType()),
608 hasType(nonConstPointerType())))
609 .bind(NodeID<Decl>::value)),
610 hasRangeStmt(DeclStmtToNonRefToArray),
611 hasRangeInit(canResolveToExpr(Exp))))
612 .bind("stmt")),
613 Stm, Context);
614
615 if (const auto *BadRangeInitFromArray =
616 selectFirst<Stmt>("stmt", RefToArrayRefToElements))
617 return BadRangeInitFromArray;
618
619 // Small helper to match special cases in range-for loops.
620 //
621 // It is possible that containers do not provide a const-overload for their
622 // iterator accessors. If this is the case, the variable is used non-const
623 // no matter what happens in the loop. This requires special detection as it
624 // is then faster to find all mutations of the loop variable.
625 // It aims at a different modification as well.
626 const auto HasAnyNonConstIterator =
627 anyOf(allOf(hasMethod(allOf(hasName("begin"), unless(isConst()))),
628 unless(hasMethod(allOf(hasName("begin"), isConst())))),
629 allOf(hasMethod(allOf(hasName("end"), unless(isConst()))),
630 unless(hasMethod(allOf(hasName("end"), isConst())))));
631
632 const auto DeclStmtToNonConstIteratorContainer = declStmt(
633 hasSingleDecl(varDecl(hasType(hasUnqualifiedDesugaredType(referenceType(
634 pointee(hasDeclaration(cxxRecordDecl(HasAnyNonConstIterator)))))))));
635
636 const auto RefToContainerBadIterators = match(
637 findFirst(stmt(cxxForRangeStmt(allOf(
638 hasRangeStmt(DeclStmtToNonConstIteratorContainer),
639 hasRangeInit(canResolveToExpr(Exp)))))
640 .bind("stmt")),
641 Stm, Context);
642
643 if (const auto *BadIteratorsContainer =
644 selectFirst<Stmt>("stmt", RefToContainerBadIterators))
645 return BadIteratorsContainer;
646
647 // If range for looping over 'Exp' with a non-const reference loop variable,
648 // check all declRefExpr of the loop variable.
649 const auto LoopVars =
651 hasLoopVariable(varDecl(hasType(nonConstReferenceType()))
652 .bind(NodeID<Decl>::value)),
653 hasRangeInit(canResolveToExpr(Exp)))),
654 Stm, Context);
655 return findDeclMutation(LoopVars);
656}
657
658const Stmt *
659ExprMutationAnalyzer::Analyzer::findReferenceMutation(const Expr *Exp) {
660 // Follow non-const reference returned by `operator*()` of move-only classes.
661 // These are typically smart pointers with unique ownership so we treat
662 // mutation of pointee as mutation of the smart pointer itself.
663 const auto Ref = match(
666 callee(cxxMethodDecl(ofClass(isMoveOnly()),
667 returns(nonConstReferenceType()))),
668 argumentCountIs(1), hasArgument(0, canResolveToExpr(Exp)))
669 .bind(NodeID<Expr>::value)),
670 Stm, Context);
671 if (const Stmt *S = findExprMutation(Ref))
672 return S;
673
674 // If 'Exp' is bound to a non-const reference, check all declRefExpr to that.
675 const auto Refs = match(
677 varDecl(hasType(nonConstReferenceType()),
678 hasInitializer(anyOf(
679 canResolveToExpr(Exp),
680 memberExpr(hasObjectExpression(canResolveToExpr(Exp))))),
681 hasParent(declStmt().bind("stmt")),
682 // Don't follow the reference in range statement, we've
683 // handled that separately.
685 hasRangeStmt(equalsBoundNode("stmt"))))))))
686 .bind(NodeID<Decl>::value))),
687 Stm, Context);
688 return findDeclMutation(Refs);
689}
690
691const Stmt *
692ExprMutationAnalyzer::Analyzer::findFunctionArgMutation(const Expr *Exp) {
693 const auto NonConstRefParam = forEachArgumentWithParam(
694 canResolveToExpr(Exp),
695 parmVarDecl(hasType(nonConstReferenceType())).bind("parm"));
696 const auto IsInstantiated = hasDeclaration(isInstantiated());
697 const auto FuncDecl = hasDeclaration(functionDecl().bind("func"));
698 const auto Matches = match(
699 traverse(
700 TK_AsIs,
701 findAll(
702 expr(anyOf(callExpr(NonConstRefParam, IsInstantiated, FuncDecl,
704 "::std::move", "::std::forward"))))),
705 cxxConstructExpr(NonConstRefParam, IsInstantiated,
706 FuncDecl)))
707 .bind(NodeID<Expr>::value))),
708 Stm, Context);
709 for (const auto &Nodes : Matches) {
710 const auto *Exp = Nodes.getNodeAs<Expr>(NodeID<Expr>::value);
711 const auto *Func = Nodes.getNodeAs<FunctionDecl>("func");
712 if (!Func->getBody() || !Func->getPrimaryTemplate())
713 return Exp;
714
715 const auto *Parm = Nodes.getNodeAs<ParmVarDecl>("parm");
716 const ArrayRef<ParmVarDecl *> AllParams =
717 Func->getPrimaryTemplate()->getTemplatedDecl()->parameters();
718 QualType ParmType =
719 AllParams[std::min<size_t>(Parm->getFunctionScopeIndex(),
720 AllParams.size() - 1)]
721 ->getType();
722 if (const auto *T = ParmType->getAs<PackExpansionType>())
723 ParmType = T->getPattern();
724
725 // If param type is forwarding reference, follow into the function
726 // definition and see whether the param is mutated inside.
727 if (const auto *RefType = ParmType->getAs<RValueReferenceType>()) {
728 if (!RefType->getPointeeType().getQualifiers() &&
730 RefType->getPointeeType().getCanonicalType())) {
733 *Func, Context, Memorized);
734 if (Analyzer->findMutation(Parm))
735 return Exp;
736 continue;
737 }
738 }
739 // Not forwarding reference.
740 return Exp;
741 }
742 return nullptr;
743}
744
745const Stmt *
746ExprMutationAnalyzer::Analyzer::findPointeeValueMutation(const Expr *Exp) {
747 const auto Matches = match(
749 expr(anyOf(
750 // deref by *
751 unaryOperator(hasOperatorName("*"),
752 hasUnaryOperand(canResolveToExprPointee(Exp))),
753 // deref by []
755 hasBaseConservative(canResolveToExprPointee(Exp)))))
756 .bind(NodeID<Expr>::value))),
757 Stm, Context);
758 return findExprMutation(Matches);
759}
760
761const Stmt *
762ExprMutationAnalyzer::Analyzer::findPointeeMemberMutation(const Expr *Exp) {
763 const Stmt *MemberCallExpr = selectFirst<Stmt>(
765 cxxMemberCallExpr(on(canResolveToExprPointee(Exp)),
766 unless(isConstCallee()))
767 .bind("stmt"))),
768 Stm, Context));
769 if (MemberCallExpr)
770 return MemberCallExpr;
771 const auto Matches = match(
774 hasObjectExpression(canResolveToExprPointee(Exp))),
775 binaryOperator(hasOperatorName("->*"),
776 hasLHS(canResolveToExprPointee(Exp)))))
777 .bind(NodeID<Expr>::value))),
778 Stm, Context);
779 return findExprMutation(Matches);
780}
781
782const Stmt *
783ExprMutationAnalyzer::Analyzer::findPointeeToNonConst(const Expr *Exp) {
784 const auto NonConstPointerOrNonConstRefOrDependentType = type(anyOf(
785 nonConstPointerType(), nonConstReferenceType(),
786 constReferenceToPointerWithNonConstPointeeType(), isDependentType()));
787
788 // assign
789 const auto InitToNonConst =
790 varDecl(hasType(NonConstPointerOrNonConstRefOrDependentType),
791 hasInitializer(expr(canResolveToExprPointee(Exp)).bind("stmt")));
792 const auto AssignToNonConst = binaryOperation(
793 hasOperatorName("="),
794 hasLHS(expr(hasType(NonConstPointerOrNonConstRefOrDependentType))),
795 hasRHS(canResolveToExprPointee(Exp)));
796 // arguments like
797 const auto ArgOfInstantiationDependent = allOf(
798 hasAnyArgument(canResolveToExprPointee(Exp)), isInstantiationDependent());
799 const auto ArgOfNonConstParameter =
800 forEachArgumentWithParamType(canResolveToExprPointee(Exp),
801 NonConstPointerOrNonConstRefOrDependentType);
802 const auto CallLikeMatcher =
803 anyOf(ArgOfNonConstParameter, ArgOfInstantiationDependent);
804 const auto PassAsNonConstArg = expr(
805 anyOf(cxxUnresolvedConstructExpr(ArgOfInstantiationDependent),
806 cxxNewExpr(hasAnyPlacementArg(
807 ignoringParenImpCasts(canResolveToExprPointee(Exp)))),
808 cxxConstructExpr(CallLikeMatcher), callExpr(CallLikeMatcher),
810 expr(canResolveToExprPointee(Exp),
811 hasType(NonConstPointerOrNonConstRefOrDependentType)))),
812 initListExpr(hasAnyInit(
813 expr(canResolveToExprPointee(Exp),
814 hasType(NonConstPointerOrNonConstRefOrDependentType))))));
815 // cast
816 const auto CastToNonConst = explicitCastExpr(
817 hasSourceExpression(canResolveToExprPointee(Exp)),
818 hasDestinationType(NonConstPointerOrNonConstRefOrDependentType));
819
820 // capture
821 // FIXME: false positive if the pointee does not change in lambda
822 const auto CaptureNoConst = lambdaExpr(hasCaptureInit(Exp));
823
824 const auto ReturnNoConst = returnStmt(
825 hasReturnValue(canResolveToExprPointee(Exp)),
826 forFunction(returns(NonConstPointerOrNonConstRefOrDependentType)));
827
828 const auto Matches = match(
830 stmt(anyOf(AssignToNonConst, PassAsNonConstArg,
831 CastToNonConst, CaptureNoConst, ReturnNoConst))
832 .bind("stmt")),
833 forEachDescendant(InitToNonConst))),
834 Stm, Context);
835 return selectFirst<Stmt>("stmt", Matches);
836}
837
838FunctionParmMutationAnalyzer::FunctionParmMutationAnalyzer(
839 const FunctionDecl &Func, ASTContext &Context,
840 ExprMutationAnalyzer::Memoized &Memorized)
841 : BodyAnalyzer(*Func.getBody(), Context, Memorized) {
842 if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(&Func)) {
843 // CXXCtorInitializer might also mutate Param but they're not part of
844 // function body, check them eagerly here since they're typically trivial.
845 for (const CXXCtorInitializer *Init : Ctor->inits()) {
846 ExprMutationAnalyzer::Analyzer InitAnalyzer(*Init->getInit(), Context,
847 Memorized);
848 for (const ParmVarDecl *Parm : Ctor->parameters()) {
849 if (Results.contains(Parm))
850 continue;
851 if (const Stmt *S = InitAnalyzer.findMutation(Parm))
852 Results[Parm] = S;
853 }
854 }
855 }
856}
857
858const Stmt *
860 auto [Place, Inserted] = Results.try_emplace(Parm);
861 if (!Inserted)
862 return Place->second;
863
864 // To handle call A -> call B -> call A. Assume parameters of A is not mutated
865 // before analyzing parameters of A. Then when analyzing the second "call A",
866 // FunctionParmMutationAnalyzer can use this memoized value to avoid infinite
867 // recursion.
868 return Place->second = BodyAnalyzer.findMutation(Parm);
869}
870
871} // namespace clang
#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...
*collection of selector each with an associated kind and an ordered *collection of selectors A selector has a kind
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:223
CXXForRangeStmt - This represents C++0x [stmt.ranged]'s ranged for statement, represented as 'for (ra...
Definition StmtCXX.h:136
Represents a call to a member function that may be written either with member call syntax (e....
Definition ExprCXX.h:183
A C++ typeid expression (C++ [expr.typeid]), which gets the type_info that corresponds to the supplie...
Definition ExprCXX.h:852
DeclStmt - Adaptor class for mixing declarations with statements and expressions.
Definition Stmt.h:1643
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:113
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3119
static FunctionParmMutationAnalyzer * getFunctionParmMutationAnalyzer(const FunctionDecl &Func, ASTContext &Context, ExprMutationAnalyzer::Memoized &Memorized)
const Stmt * findMutation(const ParmVarDecl *Parm)
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5421
bool isConst() const
Definition TypeBase.h:4979
Represents a C11 generic selection.
Definition Expr.h:6232
Describes an C or C++ initializer list.
Definition Expr.h:5352
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
Definition ExprCXX.h:1972
Represents a parameter to a function.
Definition Decl.h:1820
A (possibly-)qualified type.
Definition TypeBase.h:938
Stmt - This represents one statement.
Definition Stmt.h:85
The base class of the type hierarchy.
Definition TypeBase.h:1879
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9338
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 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 AstTypeMatcher< VariableArrayType > variableArrayType
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.
const internal::VariadicDynCastAllOfMatcher< Stmt, CallExpr > callExpr
Matches call expressions.
const internal::VariadicDynCastAllOfMatcher< Stmt, LambdaExpr > lambdaExpr
Matches lambda expressions.
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
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.
const internal::VariadicDynCastAllOfMatcher< Stmt, InitListExpr > initListExpr
Matches init list expressions.
const internal::VariadicDynCastAllOfMatcher< Stmt, CXXNoexceptExpr > cxxNoexceptExpr
Matches noexcept expressions.
const NodeT * selectFirst(StringRef BoundTo, const SmallVectorImpl< BoundNodes > &Results)
Returns the first result of type NodeT bound to BoundTo.
const internal::VariadicDynCastAllOfMatcher< Stmt, CXXNewExpr > cxxNewExpr
Matches new 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.
const AstTypeMatcher< PointerType > pointerType
internal::PolymorphicMatcher< internal::HasOverloadedOperatorNameMatcher, AST_POLYMORPHIC_SUPPORTED_TYPES(CXXOperatorCallExpr, FunctionDecl), std::vector< std::string > > hasOverloadedOperatorName(StringRef Name)
Matches overloaded operator names.
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.
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.
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.
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::VariadicAllOfMatcher< QualType > qualType
Matches QualTypes in the clang 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.
const AstTypeMatcher< ReferenceType > referenceType
Top level wrappers for InstallAPI frontend operations.
bool isa(CodeGen::Address addr)
Definition Address.h:330
@ TK_AsIs
Will traverse all child nodes.
@ Result
The result type of a method or function.
Definition TypeBase.h:906
const FunctionProtoType * T
CastKind
CastKind - The kind of operation required for a conversion.
static bool canExprResolveTo(const Expr *Source, const Expr *Target)
U cast(CodeGen::Address addr)
Definition Address.h:327
const Stmt * findPointeeMutation(const Expr *Exp)
const Stmt * findMutation(const Expr *Exp)
llvm::DenseMap< const Expr *, const Stmt * > ResultMap