clang-tools 23.0.0git
LoopConvertUtils.cpp
Go to the documentation of this file.
1//===----------------------------------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include "LoopConvertUtils.h"
10#include "../utils/ASTUtils.h"
11#include "clang/Basic/IdentifierTable.h"
12#include "clang/Basic/LLVM.h"
13#include "clang/Basic/Lambda.h"
14#include "clang/Basic/SourceLocation.h"
15#include "clang/Basic/SourceManager.h"
16#include "clang/Basic/TokenKinds.h"
17#include "clang/Lex/Lexer.h"
18#include "llvm/ADT/APSInt.h"
19#include "llvm/ADT/FoldingSet.h"
20#include "llvm/ADT/StringRef.h"
21#include <cassert>
22#include <cstddef>
23#include <optional>
24#include <string>
25#include <utility>
26
27using namespace clang::ast_matchers;
28
29namespace clang::tidy::modernize {
30
31/// Tracks a stack of parent statements during traversal.
32///
33/// All this really does is inject push_back() before running
34/// RecursiveASTVisitor::TraverseStmt() and pop_back() afterwards. The Stmt atop
35/// the stack is the parent of the current statement (NULL for the topmost
36/// statement).
37bool StmtAncestorASTVisitor::TraverseStmt(Stmt *Statement) {
38 StmtAncestors.try_emplace(Statement, StmtStack.back());
39 StmtStack.push_back(Statement);
40 RecursiveASTVisitor<StmtAncestorASTVisitor>::TraverseStmt(Statement);
41 StmtStack.pop_back();
42 return true;
43}
44
45/// Keep track of the DeclStmt associated with each VarDecl.
46///
47/// Combined with StmtAncestors, this provides roughly the same information as
48/// Scope, as we can map a VarDecl to its DeclStmt, then walk up the parent tree
49/// using StmtAncestors.
50bool StmtAncestorASTVisitor::VisitDeclStmt(DeclStmt *Statement) {
51 for (const auto *Decl : Statement->decls())
52 if (const auto *V = dyn_cast<VarDecl>(Decl))
53 DeclParents.try_emplace(V, Statement);
54 return true;
55}
56
57/// record the DeclRefExpr as part of the parent expression.
58bool ComponentFinderASTVisitor::VisitDeclRefExpr(DeclRefExpr *E) {
59 Components.push_back(E);
60 return true;
61}
62
63/// record the MemberExpr as part of the parent expression.
64bool ComponentFinderASTVisitor::VisitMemberExpr(MemberExpr *Member) {
65 Components.push_back(Member);
66 return true;
67}
68
69/// Forward any DeclRefExprs to a check on the referenced variable
70/// declaration.
71bool DependencyFinderASTVisitor::VisitDeclRefExpr(DeclRefExpr *DeclRef) {
72 if (auto *V = dyn_cast_or_null<VarDecl>(DeclRef->getDecl()))
73 return VisitVarDecl(V);
74 return true;
75}
76
77/// Determine if any this variable is declared inside the ContainingStmt.
78bool DependencyFinderASTVisitor::VisitVarDecl(VarDecl *V) {
79 const Stmt *Curr = DeclParents->lookup(V);
80 // First, see if the variable was declared within an inner scope of the loop.
81 while (Curr != nullptr) {
82 if (Curr == ContainingStmt) {
83 DependsOnInsideVariable = true;
84 return false;
85 }
86 Curr = StmtParents->lookup(Curr);
87 }
88
89 // Next, check if the variable was removed from existence by an earlier
90 // iteration.
91 if (llvm::none_of(*ReplacedVars,
92 [&](const auto &I) { return I.second == V; }))
93 return true;
94 DependsOnInsideVariable = true;
95 return false;
96}
97
98/// If we already created a variable for TheLoop, check to make sure
99/// that the name was not already taken.
100bool DeclFinderASTVisitor::VisitForStmt(ForStmt *TheLoop) {
101 const StmtGeneratedVarNameMap::const_iterator I =
102 GeneratedDecls->find(TheLoop);
103 if (I != GeneratedDecls->end() && I->second == Name) {
104 Found = true;
105 return false;
106 }
107 return true;
108}
109
110/// If any named declaration within the AST subtree has the same name,
111/// then consider Name already taken.
112bool DeclFinderASTVisitor::VisitNamedDecl(NamedDecl *D) {
113 const IdentifierInfo *Ident = D->getIdentifier();
114 if (Ident && Ident->getName() == Name) {
115 Found = true;
116 return false;
117 }
118 return true;
119}
120
121/// Forward any declaration references to the actual check on the
122/// referenced declaration.
123bool DeclFinderASTVisitor::VisitDeclRefExpr(DeclRefExpr *DeclRef) {
124 if (auto *D = dyn_cast<NamedDecl>(DeclRef->getDecl()))
125 return VisitNamedDecl(D);
126 return true;
127}
128
129/// If the new variable name conflicts with any type used in the loop,
130/// then we mark that variable name as taken.
131bool DeclFinderASTVisitor::VisitTypeLoc(TypeLoc TL) {
132 const QualType QType = TL.getType();
133
134 // Check if our name conflicts with a type, to handle for typedefs.
135 if (QType.getAsString() == Name) {
136 Found = true;
137 return false;
138 }
139 // Check for base type conflicts. For example, when a struct is being
140 // referenced in the body of the loop, the above getAsString() will return the
141 // whole type (ex. "struct s"), but will be caught here.
142 if (const IdentifierInfo *Ident = QType.getBaseTypeIdentifier()) {
143 if (Ident->getName() == Name) {
144 Found = true;
145 return false;
146 }
147 }
148 return true;
149}
150
151/// Look through conversion/copy constructors and member functions to find the
152/// explicit initialization expression, returning it is found.
153///
154/// The main idea is that given
155/// vector<int> v;
156/// we consider either of these initializations
157/// vector<int>::iterator it = v.begin();
158/// vector<int>::iterator it(v.begin());
159/// vector<int>::const_iterator it(v.begin());
160/// and retrieve `v.begin()` as the expression used to initialize `it` but do
161/// not include
162/// vector<int>::iterator it;
163/// vector<int>::iterator it(v.begin(), 0); // if this constructor existed
164/// as being initialized from `v.begin()`
165const Expr *digThroughConstructorsConversions(const Expr *E) {
166 if (!E)
167 return nullptr;
168 E = E->IgnoreImplicit();
169 if (const auto *ConstructExpr = dyn_cast<CXXConstructExpr>(E)) {
170 // The initial constructor must take exactly one parameter, but base class
171 // and deferred constructors can take more.
172 if (ConstructExpr->getNumArgs() != 1 ||
173 ConstructExpr->getConstructionKind() != CXXConstructionKind::Complete)
174 return nullptr;
175 E = ConstructExpr->getArg(0);
176 if (const auto *Temp = dyn_cast<MaterializeTemporaryExpr>(E))
177 E = Temp->getSubExpr();
179 }
180 // If this is a conversion (as iterators commonly convert into their const
181 // iterator counterparts), dig through that as well.
182 if (const auto *ME = dyn_cast<CXXMemberCallExpr>(E))
183 if (isa<CXXConversionDecl>(ME->getMethodDecl()))
184 return digThroughConstructorsConversions(ME->getImplicitObjectArgument());
185 return E;
186}
187
188/// Returns true when two Exprs are equivalent.
189bool areSameExpr(const ASTContext *Context, const Expr *First,
190 const Expr *Second) {
191 return utils::areStatementsIdentical(First, Second, *Context, true);
192}
193
194/// Returns the DeclRefExpr represented by E, or NULL if there isn't one.
195const DeclRefExpr *getDeclRef(const Expr *E) {
196 return dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
197}
198
199/// Returns true when two ValueDecls are the same variable.
200bool areSameVariable(const ValueDecl *First, const ValueDecl *Second) {
201 return First && Second &&
202 First->getCanonicalDecl() == Second->getCanonicalDecl();
203}
204
205/// Determines if an expression is a declaration reference to a
206/// particular variable.
207static bool exprReferencesVariable(const ValueDecl *Target, const Expr *E) {
208 if (!Target || !E)
209 return false;
210 const DeclRefExpr *Decl = getDeclRef(E);
211 return Decl && areSameVariable(Target, Decl->getDecl());
212}
213
214/// If the expression is a dereference or call to operator*(), return the
215/// operand. Otherwise, return NULL.
216static const Expr *getDereferenceOperand(const Expr *E) {
217 if (const auto *Uop = dyn_cast<UnaryOperator>(E))
218 return Uop->getOpcode() == UO_Deref ? Uop->getSubExpr() : nullptr;
219
220 if (const auto *OpCall = dyn_cast<CXXOperatorCallExpr>(E)) {
221 return OpCall->getOperator() == OO_Star && OpCall->getNumArgs() == 1
222 ? OpCall->getArg(0)
223 : nullptr;
224 }
225
226 return nullptr;
227}
228
229/// Returns true when the Container contains an Expr equivalent to E.
230template <typename ContainerT>
231static bool containsExpr(ASTContext *Context, const ContainerT *Container,
232 const Expr *E) {
233 llvm::FoldingSetNodeID ID;
234 E->Profile(ID, *Context, true);
235 return llvm::any_of(*Container,
236 [&](const auto &I) { return ID == I.second; });
237}
238
239/// Returns true when the index expression is a declaration reference to
240/// IndexVar.
241///
242/// If the index variable is `index`, this function returns true on
243/// arrayExpression[index];
244/// containerExpression[index];
245/// but not
246/// containerExpression[notIndex];
247static bool isIndexInSubscriptExpr(const Expr *IndexExpr,
248 const VarDecl *IndexVar) {
249 const DeclRefExpr *Idx = getDeclRef(IndexExpr);
250 return Idx && Idx->getType()->isIntegerType() &&
251 areSameVariable(IndexVar, Idx->getDecl());
252}
253
254/// Returns true when the index expression is a declaration reference to
255/// IndexVar, Obj is the same expression as SourceExpr after all parens and
256/// implicit casts are stripped off.
257///
258/// If PermitDeref is true, IndexExpression may
259/// be a dereference (overloaded or builtin operator*).
260///
261/// This function is intended for array-like containers, as it makes sure that
262/// both the container and the index match.
263/// If the loop has index variable `index` and iterates over `container`, then
264/// isIndexInSubscriptExpr returns true for
265/// \code
266/// container[index]
267/// container.at(index)
268/// container->at(index)
269/// \endcode
270/// but not for
271/// \code
272/// container[notIndex]
273/// notContainer[index]
274/// \endcode
275/// If PermitDeref is true, then isIndexInSubscriptExpr additionally returns
276/// true on these expressions:
277/// \code
278/// (*container)[index]
279/// (*container).at(index)
280/// \endcode
281static bool isIndexInSubscriptExpr(const ASTContext *Context,
282 const Expr *IndexExpr,
283 const VarDecl *IndexVar, const Expr *Obj,
284 const Expr *SourceExpr, bool PermitDeref) {
285 if (!SourceExpr || !Obj || !isIndexInSubscriptExpr(IndexExpr, IndexVar))
286 return false;
287
288 if (areSameExpr(Context, SourceExpr->IgnoreParenImpCasts(),
289 Obj->IgnoreParenImpCasts()))
290 return true;
291
292 if (const Expr *InnerObj = getDereferenceOperand(Obj->IgnoreParenImpCasts()))
293 if (PermitDeref && areSameExpr(Context, SourceExpr->IgnoreParenImpCasts(),
294 InnerObj->IgnoreParenImpCasts()))
295 return true;
296
297 return false;
298}
299
300/// Returns true when Opcall is a call a one-parameter dereference of
301/// IndexVar.
302///
303/// For example, if the index variable is `index`, returns true for
304/// *index
305/// but not
306/// index
307/// *notIndex
308static bool isDereferenceOfOpCall(const CXXOperatorCallExpr *OpCall,
309 const VarDecl *IndexVar) {
310 return OpCall->getOperator() == OO_Star && OpCall->getNumArgs() == 1 &&
311 exprReferencesVariable(IndexVar, OpCall->getArg(0));
312}
313
314/// Returns true when Uop is a dereference of IndexVar.
315///
316/// For example, if the index variable is `index`, returns true for
317/// *index
318/// but not
319/// index
320/// *notIndex
321static bool isDereferenceOfUop(const UnaryOperator *Uop,
322 const VarDecl *IndexVar) {
323 return Uop->getOpcode() == UO_Deref &&
324 exprReferencesVariable(IndexVar, Uop->getSubExpr());
325}
326
327/// Determines whether the given Decl defines a variable initialized to
328/// the loop object.
329///
330/// This is intended to find cases such as
331/// \code
332/// for (int i = 0; i < arraySize(arr); ++i) {
333/// T t = arr[i];
334/// // use t, do not use i
335/// }
336/// \endcode
337/// and
338/// \code
339/// for (iterator i = container.begin(), e = container.end(); i != e; ++i) {
340/// T t = *i;
341/// // use t, do not use i
342/// }
343/// \endcode
344static bool isAliasDecl(const ASTContext *Context, const Decl *TheDecl,
345 const VarDecl *IndexVar) {
346 const auto *VDecl = dyn_cast<VarDecl>(TheDecl);
347 if (!VDecl)
348 return false;
349 if (!VDecl->hasInit())
350 return false;
351
352 bool OnlyCasts = true;
353 const Expr *Init = VDecl->getInit()->IgnoreParenImpCasts();
354 if (isa_and_nonnull<CXXConstructExpr>(Init)) {
356 OnlyCasts = false;
357 }
358 if (!Init)
359 return false;
360
361 // Check that the declared type is the same as (or a reference to) the
362 // container type.
363 if (!OnlyCasts) {
364 const QualType InitType = Init->getType();
365 QualType DeclarationType = VDecl->getType();
366 if (!DeclarationType.isNull() && DeclarationType->isReferenceType())
367 DeclarationType = DeclarationType.getNonReferenceType();
368
369 if (InitType.isNull() || DeclarationType.isNull() ||
370 !ASTContext::hasSameUnqualifiedType(DeclarationType, InitType))
371 return false;
372 }
373
374 switch (Init->getStmtClass()) {
375 case Stmt::ArraySubscriptExprClass: {
376 const auto *E = cast<ArraySubscriptExpr>(Init);
377 // We don't really care which array is used here. We check to make sure
378 // it was the correct one later, since the AST will traverse it next.
379 return isIndexInSubscriptExpr(E->getIdx(), IndexVar);
380 }
381
382 case Stmt::UnaryOperatorClass:
383 return isDereferenceOfUop(cast<UnaryOperator>(Init), IndexVar);
384
385 case Stmt::CXXOperatorCallExprClass: {
386 const auto *OpCall = cast<CXXOperatorCallExpr>(Init);
387 if (OpCall->getOperator() == OO_Star)
388 return isDereferenceOfOpCall(OpCall, IndexVar);
389 if (OpCall->getOperator() == OO_Subscript) {
390 return OpCall->getNumArgs() == 2 &&
391 isIndexInSubscriptExpr(OpCall->getArg(1), IndexVar);
392 }
393 break;
394 }
395
396 case Stmt::CXXMemberCallExprClass: {
397 const auto *MemCall = cast<CXXMemberCallExpr>(Init);
398 // This check is needed because getMethodDecl can return nullptr if the
399 // callee is a member function pointer.
400 const auto *MDecl = MemCall->getMethodDecl();
401 if (MDecl && !isa<CXXConversionDecl>(MDecl) &&
402 MDecl->getNameAsString() == "at" && MemCall->getNumArgs() == 1) {
403 return isIndexInSubscriptExpr(MemCall->getArg(0), IndexVar);
404 }
405 return false;
406 }
407
408 default:
409 break;
410 }
411 return false;
412}
413
414/// Determines whether the bound of a for loop condition expression is
415/// the same as the statically computable size of ArrayType.
416///
417/// Given
418/// \code
419/// const int N = 5;
420/// int arr[N];
421/// \endcode
422/// This is intended to permit
423/// \code
424/// for (int i = 0; i < N; ++i) { /* use arr[i] */ }
425/// for (int i = 0; i < arraysize(arr); ++i) { /* use arr[i] */ }
426/// \endcode
427static bool arrayMatchesBoundExpr(const ASTContext *Context,
428 const QualType &ArrayType,
429 const Expr *ConditionExpr) {
430 if (!ConditionExpr || ConditionExpr->isValueDependent())
431 return false;
432 const ConstantArrayType *ConstType =
433 Context->getAsConstantArrayType(ArrayType);
434 if (!ConstType)
435 return false;
436 std::optional<llvm::APSInt> ConditionSize =
437 ConditionExpr->getIntegerConstantExpr(*Context);
438 if (!ConditionSize)
439 return false;
440 const llvm::APSInt ArraySize(ConstType->getSize());
441 return llvm::APSInt::isSameValue(*ConditionSize, ArraySize);
442}
443
445 const VarDecl *IndexVar,
446 const VarDecl *EndVar,
447 const Expr *ContainerExpr,
448 const Expr *ArrayBoundExpr,
449 bool ContainerNeedsDereference)
450 : Context(Context), IndexVar(IndexVar), EndVar(EndVar),
451 ContainerExpr(ContainerExpr), ArrayBoundExpr(ArrayBoundExpr),
452 ContainerNeedsDereference(ContainerNeedsDereference),
453
454 ConfidenceLevel(Confidence::CL_Safe) {
455 if (ContainerExpr)
456 addComponent(ContainerExpr);
457}
458
460 TraverseStmt(const_cast<Stmt *>(Body));
461 return OnlyUsedAsIndex && ContainerExpr;
462}
463
465 // FIXME: add sort(on ID)+unique to avoid extra work.
466 for (const auto &I : Components)
467 addComponent(I);
468}
469
470void ForLoopIndexUseVisitor::addComponent(const Expr *E) {
471 llvm::FoldingSetNodeID ID;
472 const Expr *Node = E->IgnoreParenImpCasts();
473 Node->Profile(ID, *Context, true);
474 DependentExprs.emplace_back(Node, ID);
475}
476
478 SourceLocation Begin = U.Range.getBegin();
479 if (Begin.isMacroID())
480 Begin = Context->getSourceManager().getSpellingLoc(Begin);
481
482 if (UsageLocations.insert(Begin).second)
483 Usages.push_back(U);
484}
485
486/// If the unary operator is a dereference of IndexVar, include it
487/// as a valid usage and prune the traversal.
488///
489/// For example, if container.begin() and container.end() both return pointers
490/// to int, this makes sure that the initialization for `k` is not counted as an
491/// unconvertible use of the iterator `i`.
492/// \code
493/// for (int *i = container.begin(), *e = container.end(); i != e; ++i) {
494/// int k = *i + 2;
495/// }
496/// \endcode
497bool ForLoopIndexUseVisitor::TraverseUnaryOperator(UnaryOperator *Uop) {
498 // If we dereference an iterator that's actually a pointer, count the
499 // occurrence.
500 if (isDereferenceOfUop(Uop, IndexVar)) {
501 addUsage(Usage(Uop));
502 return true;
503 }
504
505 return VisitorBase::TraverseUnaryOperator(Uop);
506}
507
508/// If the member expression is operator-> (overloaded or not) on
509/// IndexVar, include it as a valid usage and prune the traversal.
510///
511/// For example, given
512/// \code
513/// struct Foo { int bar(); int x; };
514/// vector<Foo> v;
515/// \endcode
516/// the following uses will be considered convertible:
517/// \code
518/// for (vector<Foo>::iterator i = v.begin(), e = v.end(); i != e; ++i) {
519/// int b = i->bar();
520/// int k = i->x + 1;
521/// }
522/// \endcode
523/// though
524/// \code
525/// for (vector<Foo>::iterator i = v.begin(), e = v.end(); i != e; ++i) {
526/// int k = i.insert(1);
527/// }
528/// for (vector<Foo>::iterator i = v.begin(), e = v.end(); i != e; ++i) {
529/// int b = e->bar();
530/// }
531/// \endcode
532/// will not.
533bool ForLoopIndexUseVisitor::TraverseMemberExpr(MemberExpr *Member) {
534 const Expr *Base = Member->getBase();
535 const DeclRefExpr *Obj = getDeclRef(Base);
536 const Expr *ResultExpr = Member;
537 QualType ExprType;
538 if (const auto *Call =
539 dyn_cast<CXXOperatorCallExpr>(Base->IgnoreParenImpCasts())) {
540 // If operator->() is a MemberExpr containing a CXXOperatorCallExpr, then
541 // the MemberExpr does not have the expression we want. We therefore catch
542 // that instance here.
543 // For example, if vector<Foo>::iterator defines operator->(), then the
544 // example `i->bar()` at the top of this function is a CXXMemberCallExpr
545 // referring to `i->` as the member function called. We want just `i`, so
546 // we take the argument to operator->() as the base object.
547 if (Call->getOperator() == OO_Arrow) {
548 assert(Call->getNumArgs() == 1 &&
549 "Operator-> takes more than one argument");
550 Obj = getDeclRef(Call->getArg(0));
551 ResultExpr = Obj;
552 ExprType = Call->getCallReturnType(*Context);
553 }
554 }
555
556 if (Obj && exprReferencesVariable(IndexVar, Obj)) {
557 // Member calls on the iterator with '.' are not allowed.
558 if (!Member->isArrow()) {
559 OnlyUsedAsIndex = false;
560 return true;
561 }
562
563 if (ExprType.isNull())
564 ExprType = Obj->getType();
565
566 if (!ExprType->isPointerType())
567 return false;
568
569 // FIXME: This works around not having the location of the arrow operator.
570 // Consider adding OperatorLoc to MemberExpr?
571 const SourceLocation ArrowLoc = Lexer::getLocForEndOfToken(
572 Base->getExprLoc(), 0, Context->getSourceManager(),
573 Context->getLangOpts());
574 // If something complicated is happening (i.e. the next token isn't an
575 // arrow), give up on making this work.
576 if (ArrowLoc.isValid()) {
578 SourceRange(Base->getExprLoc(), ArrowLoc)));
579 return true;
580 }
581 }
582 return VisitorBase::TraverseMemberExpr(Member);
583}
584
585/// If a member function call is the at() accessor on the container with
586/// IndexVar as the single argument, include it as a valid usage and prune
587/// the traversal.
588///
589/// Member calls on other objects will not be permitted.
590/// Calls on the iterator object are not permitted, unless done through
591/// operator->(). The one exception is allowing vector::at() for pseudoarrays.
592bool ForLoopIndexUseVisitor::TraverseCXXMemberCallExpr(
593 CXXMemberCallExpr *MemberCall) {
594 auto *Member =
595 dyn_cast<MemberExpr>(MemberCall->getCallee()->IgnoreParenImpCasts());
596 if (!Member)
597 return VisitorBase::TraverseCXXMemberCallExpr(MemberCall);
598
599 // We specifically allow an accessor named "at" to let STL in, though
600 // this is restricted to pseudo-arrays by requiring a single, integer
601 // argument.
602 const IdentifierInfo *Ident = Member->getMemberDecl()->getIdentifier();
603 if (Ident && Ident->isStr("at") && MemberCall->getNumArgs() == 1) {
604 if (isIndexInSubscriptExpr(Context, MemberCall->getArg(0), IndexVar,
605 Member->getBase(), ContainerExpr,
606 ContainerNeedsDereference)) {
607 addUsage(Usage(MemberCall));
608 return true;
609 }
610 }
611
612 if (containsExpr(Context, &DependentExprs, Member->getBase()))
613 ConfidenceLevel.lowerTo(Confidence::CL_Risky);
614
615 return VisitorBase::TraverseCXXMemberCallExpr(MemberCall);
616}
617
618/// If an overloaded operator call is a dereference of IndexVar or
619/// a subscript of the container with IndexVar as the single argument,
620/// include it as a valid usage and prune the traversal.
621///
622/// For example, given
623/// \code
624/// struct Foo { int bar(); int x; };
625/// vector<Foo> v;
626/// void f(Foo);
627/// \endcode
628/// the following uses will be considered convertible:
629/// \code
630/// for (vector<Foo>::iterator i = v.begin(), e = v.end(); i != e; ++i) {
631/// f(*i);
632/// }
633/// for (int i = 0; i < v.size(); ++i) {
634/// int i = v[i] + 1;
635/// }
636/// \endcode
637bool ForLoopIndexUseVisitor::TraverseCXXOperatorCallExpr(
638 CXXOperatorCallExpr *OpCall) {
639 switch (OpCall->getOperator()) {
640 case OO_Star:
641 if (isDereferenceOfOpCall(OpCall, IndexVar)) {
642 addUsage(Usage(OpCall));
643 return true;
644 }
645 break;
646
647 case OO_Subscript:
648 if (OpCall->getNumArgs() != 2)
649 break;
650 if (isIndexInSubscriptExpr(Context, OpCall->getArg(1), IndexVar,
651 OpCall->getArg(0), ContainerExpr,
652 ContainerNeedsDereference)) {
653 addUsage(Usage(OpCall));
654 return true;
655 }
656 break;
657
658 default:
659 break;
660 }
661 return VisitorBase::TraverseCXXOperatorCallExpr(OpCall);
662}
663
664/// If we encounter an array with IndexVar as the index of an
665/// ArraySubscriptExpression, note it as a consistent usage and prune the
666/// AST traversal.
667///
668/// For example, given
669/// \code
670/// const int N = 5;
671/// int arr[N];
672/// \endcode
673/// This is intended to permit
674/// \code
675/// for (int i = 0; i < N; ++i) { /* use arr[i] */ }
676/// \endcode
677/// but not
678/// \code
679/// for (int i = 0; i < N; ++i) { /* use notArr[i] */ }
680/// \endcode
681/// and further checking needs to be done later to ensure that exactly one array
682/// is referenced.
683bool ForLoopIndexUseVisitor::TraverseArraySubscriptExpr(ArraySubscriptExpr *E) {
684 Expr *Arr = E->getBase();
685 if (!isIndexInSubscriptExpr(E->getIdx(), IndexVar))
686 return VisitorBase::TraverseArraySubscriptExpr(E);
687
688 if ((ContainerExpr && !areSameExpr(Context, Arr->IgnoreParenImpCasts(),
689 ContainerExpr->IgnoreParenImpCasts())) ||
690 !arrayMatchesBoundExpr(Context, Arr->IgnoreImpCasts()->getType(),
691 ArrayBoundExpr)) {
692 // If we have already discovered the array being indexed and this isn't it
693 // or this array doesn't match, mark this loop as unconvertible.
694 OnlyUsedAsIndex = false;
695 return VisitorBase::TraverseArraySubscriptExpr(E);
696 }
697
698 if (!ContainerExpr)
699 ContainerExpr = Arr;
700
701 addUsage(Usage(E));
702 return true;
703}
704
705/// If we encounter a reference to IndexVar in an unpruned branch of the
706/// traversal, mark this loop as unconvertible.
707///
708/// This determines the set of convertible loops: any usages of IndexVar
709/// not explicitly considered convertible by this traversal will be caught by
710/// this function.
711///
712/// Additionally, if the container expression is more complex than just a
713/// DeclRefExpr, and some part of it is appears elsewhere in the loop, lower
714/// our confidence in the transformation.
715///
716/// For example, these are not permitted:
717/// \code
718/// for (int i = 0; i < N; ++i) { printf("arr[%d] = %d", i, arr[i]); }
719/// for (vector<int>::iterator i = container.begin(), e = container.end();
720/// i != e; ++i)
721/// i.insert(0);
722/// for (vector<int>::iterator i = container.begin(), e = container.end();
723/// i != e; ++i)
724/// if (i + 1 != e)
725/// printf("%d", *i);
726/// \endcode
727///
728/// And these will raise the risk level:
729/// \code
730/// int arr[10][20];
731/// int l = 5;
732/// for (int j = 0; j < 20; ++j)
733/// int k = arr[l][j] + l; // using l outside arr[l] is considered risky
734/// for (int i = 0; i < obj.getVector().size(); ++i)
735/// obj.foo(10); // using `obj` is considered risky
736/// \endcode
737bool ForLoopIndexUseVisitor::VisitDeclRefExpr(DeclRefExpr *E) {
738 const ValueDecl *TheDecl = E->getDecl();
739 if (areSameVariable(IndexVar, TheDecl) ||
740 exprReferencesVariable(IndexVar, E) || areSameVariable(EndVar, TheDecl) ||
741 exprReferencesVariable(EndVar, E))
742 OnlyUsedAsIndex = false;
743 if (containsExpr(Context, &DependentExprs, E))
744 ConfidenceLevel.lowerTo(Confidence::CL_Risky);
745 return true;
746}
747
748/// If the loop index is captured by a lambda, replace this capture
749/// by the range-for loop variable.
750///
751/// For example:
752/// \code
753/// for (int i = 0; i < N; ++i) {
754/// auto f = [v, i](int k) {
755/// printf("%d\n", v[i] + k);
756/// };
757/// f(v[i]);
758/// }
759/// \endcode
760///
761/// Will be replaced by:
762/// \code
763/// for (auto & elem : v) {
764/// auto f = [v, elem](int k) {
765/// printf("%d\n", elem + k);
766/// };
767/// f(elem);
768/// }
769/// \endcode
770bool ForLoopIndexUseVisitor::TraverseLambdaCapture(LambdaExpr *LE,
771 const LambdaCapture *C,
772 Expr *Init) {
773 if (C->capturesVariable()) {
774 ValueDecl *VDecl = C->getCapturedVar();
775 if (areSameVariable(IndexVar, VDecl)) {
776 // FIXME: if the index is captured, it will count as an usage and the
777 // alias (if any) won't work, because it is only used in case of having
778 // exactly one usage.
779 addUsage(Usage(nullptr,
780 C->getCaptureKind() == LCK_ByCopy ? Usage::UK_CaptureByCopy
782 C->getLocation()));
783 }
784 if (VDecl->isInitCapture())
785 traverseStmtImpl(cast<VarDecl>(VDecl)->getInit());
786 }
787 return VisitorBase::TraverseLambdaCapture(LE, C, Init);
788}
789
790/// If we find that another variable is created just to refer to the loop
791/// element, note it for reuse as the loop variable.
792///
793/// See the comments for isAliasDecl.
794bool ForLoopIndexUseVisitor::VisitDeclStmt(DeclStmt *S) {
795 if (!AliasDecl && S->isSingleDecl() &&
796 isAliasDecl(Context, S->getSingleDecl(), IndexVar)) {
797 AliasDecl = S;
798 if (CurrStmtParent) {
799 if (isa<IfStmt>(CurrStmtParent) || isa<WhileStmt>(CurrStmtParent) ||
800 isa<SwitchStmt>(CurrStmtParent)) {
801 ReplaceWithAliasUse = true;
802 } else if (isa<ForStmt>(CurrStmtParent)) {
803 if (cast<ForStmt>(CurrStmtParent)->getConditionVariableDeclStmt() == S)
804 ReplaceWithAliasUse = true;
805 else
806 // It's assumed S came the for loop's init clause.
807 AliasFromForInit = true;
808 }
809 }
810 }
811
812 return true;
813}
814
815bool ForLoopIndexUseVisitor::traverseStmtImpl(Stmt *S) {
816 // All this pointer swapping is a mechanism for tracking immediate parentage
817 // of Stmts.
818 const Stmt *OldNextParent = NextStmtParent;
819 CurrStmtParent = NextStmtParent;
820 NextStmtParent = S;
821 const bool Result = VisitorBase::TraverseStmt(S);
822 NextStmtParent = OldNextParent;
823 return Result;
824}
825
826bool ForLoopIndexUseVisitor::TraverseStmt(Stmt *S) {
827 // If this is an initialization expression for a lambda capture, prune the
828 // traversal so that we don't end up diagnosing the contained DeclRefExpr as
829 // inconsistent usage. No need to record the usage here -- this is done in
830 // TraverseLambdaCapture().
831 if (const auto *LE = dyn_cast_or_null<LambdaExpr>(NextStmtParent)) {
832 // Any child of a LambdaExpr that isn't the body is an initialization
833 // expression.
834 if (S != LE->getBody())
835 return true;
836 }
837 return traverseStmtImpl(S);
838}
839
841 // FIXME: Add in naming conventions to handle:
842 // - How to handle conflicts.
843 // - An interactive process for naming.
844 std::string IteratorName;
845 StringRef ContainerName;
846 if (TheContainer)
847 ContainerName = TheContainer->getName();
848
849 const size_t Len = ContainerName.size();
850 if (Len > 1 && ContainerName.ends_with(Style == NS_UpperCase ? "S" : "s")) {
851 IteratorName = std::string(ContainerName.substr(0, Len - 1));
852 // E.g.: (auto thing : things)
853 if (!declarationExists(IteratorName) || IteratorName == OldIndex->getName())
854 return IteratorName;
855 }
856
857 if (Len > 2 && ContainerName.ends_with(Style == NS_UpperCase ? "S_" : "s_")) {
858 IteratorName = std::string(ContainerName.substr(0, Len - 2));
859 // E.g.: (auto thing : things_)
860 if (!declarationExists(IteratorName) || IteratorName == OldIndex->getName())
861 return IteratorName;
862 }
863
864 return std::string(OldIndex->getName());
865}
866
867/// Determines whether or not the name \a Symbol conflicts with
868/// language keywords or defined macros. Also checks if the name exists in
869/// LoopContext, any of its parent contexts, or any of its child statements.
870///
871/// We also check to see if the same identifier was generated by this loop
872/// converter in a loop nested within SourceStmt.
873bool VariableNamer::declarationExists(StringRef Symbol) {
874 assert(Context != nullptr && "Expected an ASTContext");
875 const IdentifierInfo &Ident = Context->Idents.get(Symbol);
876
877 // Check if the symbol is not an identifier (ie. is a keyword or alias).
878 if (!isAnyIdentifier(Ident.getTokenID()))
879 return true;
880
881 // Check for conflicting macro definitions.
882 if (Ident.hasMacroDefinition())
883 return true;
884
885 // Determine if the symbol was generated in a parent context.
886 for (const Stmt *S = SourceStmt; S != nullptr; S = ReverseAST->lookup(S)) {
887 const StmtGeneratedVarNameMap::const_iterator I = GeneratedDecls->find(S);
888 if (I != GeneratedDecls->end() && I->second == Symbol)
889 return true;
890 }
891
892 // FIXME: Rather than detecting conflicts at their usages, we should check the
893 // parent context.
894 // For some reason, lookup() always returns the pair (NULL, NULL) because its
895 // StoredDeclsMap is not initialized (i.e. LookupPtr.getInt() is false inside
896 // of DeclContext::lookup()). Why is this?
897
898 // Finally, determine if the symbol was used in the loop or a child context.
899 DeclFinderASTVisitor DeclFinder(std::string(Symbol), GeneratedDecls);
900 return DeclFinder.findUsages(SourceStmt);
901}
902
903} // namespace clang::tidy::modernize
const char Usage[]
A class to encapsulate lowering of the tool's confidence level.
ForLoopIndexUseVisitor(ASTContext *Context, const VarDecl *IndexVar, const VarDecl *EndVar, const Expr *ContainerExpr, const Expr *ArrayBoundExpr, bool ContainerNeedsDereference)
bool findAndVerifyUsages(const Stmt *Body)
Finds all uses of IndexVar in Body, placing all usages in Usages, and returns true if IndexVar was on...
void addUsage(const Usage &U)
Adds the Usage if it was not added before.
void addComponents(const ComponentVector &Components)
Add a set of components that we should consider relevant to the container.
std::string createIndexName()
Generate a new index name.
llvm::json::Object Obj
SmallVector< const Expr *, 16 > ComponentVector
A vector used to store the AST subtrees of an Expr.
static bool containsExpr(ASTContext *Context, const ContainerT *Container, const Expr *E)
Returns true when the Container contains an Expr equivalent to E.
static bool isAliasDecl(const ASTContext *Context, const Decl *TheDecl, const VarDecl *IndexVar)
Determines whether the given Decl defines a variable initialized to the loop object.
const DeclRefExpr * getDeclRef(const Expr *E)
Returns the DeclRefExpr represented by E, or NULL if there isn't one.
static bool exprReferencesVariable(const ValueDecl *Target, const Expr *E)
Determines if an expression is a declaration reference to a particular variable.
bool areSameVariable(const ValueDecl *First, const ValueDecl *Second)
Returns true when two ValueDecls are the same variable.
static const Expr * getDereferenceOperand(const Expr *E)
If the expression is a dereference or call to operator*(), return the operand.
bool areSameExpr(const ASTContext *Context, const Expr *First, const Expr *Second)
Returns true when two Exprs are equivalent.
const Expr * digThroughConstructorsConversions(const Expr *E)
Look through conversion/copy constructors and member functions to find the explicit initialization ex...
static bool arrayMatchesBoundExpr(const ASTContext *Context, const QualType &ArrayType, const Expr *ConditionExpr)
Determines whether the bound of a for loop condition expression is the same as the statically computa...
static bool isIndexInSubscriptExpr(const Expr *IndexExpr, const VarDecl *IndexVar)
Returns true when the index expression is a declaration reference to IndexVar.
static bool isDereferenceOfOpCall(const CXXOperatorCallExpr *OpCall, const VarDecl *IndexVar)
Returns true when Opcall is a call a one-parameter dereference of IndexVar.
static bool isDereferenceOfUop(const UnaryOperator *Uop, const VarDecl *IndexVar)
Returns true when Uop is a dereference of IndexVar.
bool areStatementsIdentical(const Stmt *FirstStmt, const Stmt *SecondStmt, const ASTContext &Context, bool Canonical)
Definition ASTUtils.cpp:89
The information needed to describe a valid convertible usage of an array index or iterator.