clang-tools 24.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 (ValueDecl *D = 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 Ident && 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 ME && 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 InnerObj && PermitDeref &&
294 areSameExpr(Context, SourceExpr->IgnoreParenImpCasts(),
295 InnerObj->IgnoreParenImpCasts()))
296 return true;
297
298 return false;
299}
300
301/// Returns true when Opcall is a call a one-parameter dereference of
302/// IndexVar.
303///
304/// For example, if the index variable is `index`, returns true for
305/// *index
306/// but not
307/// index
308/// *notIndex
309static bool isDereferenceOfOpCall(const CXXOperatorCallExpr *OpCall,
310 const VarDecl *IndexVar) {
311 return OpCall->getOperator() == OO_Star && OpCall->getNumArgs() == 1 &&
312 exprReferencesVariable(IndexVar, OpCall->getArg(0));
313}
314
315/// Returns true when Uop is a dereference of IndexVar.
316///
317/// For example, if the index variable is `index`, returns true for
318/// *index
319/// but not
320/// index
321/// *notIndex
322static bool isDereferenceOfUop(const UnaryOperator *Uop,
323 const VarDecl *IndexVar) {
324 return Uop->getOpcode() == UO_Deref &&
325 exprReferencesVariable(IndexVar, Uop->getSubExpr());
326}
327
328/// Determines whether the given Decl defines a variable initialized to
329/// the loop object.
330///
331/// This is intended to find cases such as
332/// \code
333/// for (int i = 0; i < arraySize(arr); ++i) {
334/// T t = arr[i];
335/// // use t, do not use i
336/// }
337/// \endcode
338/// and
339/// \code
340/// for (iterator i = container.begin(), e = container.end(); i != e; ++i) {
341/// T t = *i;
342/// // use t, do not use i
343/// }
344/// \endcode
345static bool isAliasDecl(const ASTContext *Context, const Decl *TheDecl,
346 const VarDecl *IndexVar) {
347 const auto *VDecl = dyn_cast<VarDecl>(TheDecl);
348 if (!VDecl)
349 return false;
350 if (!VDecl->hasInit())
351 return false;
352
353 bool OnlyCasts = true;
354 const Expr *Init = VDecl->getInit()->IgnoreParenImpCasts();
355 if (isa_and_nonnull<CXXConstructExpr>(Init)) {
357 OnlyCasts = false;
358 }
359 if (!Init)
360 return false;
361
362 // Check that the declared type is the same as (or a reference to) the
363 // container type.
364 if (!OnlyCasts) {
365 const QualType InitType = Init->getType();
366 QualType DeclarationType = VDecl->getType();
367 if (!DeclarationType.isNull() && DeclarationType->isReferenceType())
368 DeclarationType = DeclarationType.getNonReferenceType();
369
370 if (InitType.isNull() || DeclarationType.isNull() ||
371 !ASTContext::hasSameUnqualifiedType(DeclarationType, InitType))
372 return false;
373 }
374
375 switch (Init->getStmtClass()) {
376 case Stmt::ArraySubscriptExprClass: {
377 const auto *E = cast<ArraySubscriptExpr>(Init);
378 // We don't really care which array is used here. We check to make sure
379 // it was the correct one later, since the AST will traverse it next.
380 return isIndexInSubscriptExpr(E->getIdx(), IndexVar);
381 }
382
383 case Stmt::UnaryOperatorClass:
384 return isDereferenceOfUop(cast<UnaryOperator>(Init), IndexVar);
385
386 case Stmt::CXXOperatorCallExprClass: {
387 const auto *OpCall = cast<CXXOperatorCallExpr>(Init);
388 if (OpCall->getOperator() == OO_Star)
389 return isDereferenceOfOpCall(OpCall, IndexVar);
390 if (OpCall->getOperator() == OO_Subscript) {
391 return OpCall->getNumArgs() == 2 &&
392 isIndexInSubscriptExpr(OpCall->getArg(1), IndexVar);
393 }
394 break;
395 }
396
397 case Stmt::CXXMemberCallExprClass: {
398 const auto *MemCall = cast<CXXMemberCallExpr>(Init);
399 // This check is needed because getMethodDecl can return nullptr if the
400 // callee is a member function pointer.
401 const auto *MDecl = MemCall->getMethodDecl();
402 if (MDecl && !isa<CXXConversionDecl>(MDecl) &&
403 MDecl->getNameAsString() == "at" && MemCall->getNumArgs() == 1) {
404 return isIndexInSubscriptExpr(MemCall->getArg(0), IndexVar);
405 }
406 return false;
407 }
408
409 default:
410 break;
411 }
412 return false;
413}
414
415/// Determines whether the bound of a for loop condition expression is
416/// the same as the statically computable size of ArrayType.
417///
418/// Given
419/// \code
420/// const int N = 5;
421/// int arr[N];
422/// \endcode
423/// This is intended to permit
424/// \code
425/// for (int i = 0; i < N; ++i) { /* use arr[i] */ }
426/// for (int i = 0; i < arraysize(arr); ++i) { /* use arr[i] */ }
427/// \endcode
428static bool arrayMatchesBoundExpr(const ASTContext *Context,
429 const QualType &ArrayType,
430 const Expr *ConditionExpr) {
431 if (!ConditionExpr || ConditionExpr->isValueDependent())
432 return false;
433 const ConstantArrayType *ConstType =
434 Context->getAsConstantArrayType(ArrayType);
435 if (!ConstType)
436 return false;
437 std::optional<llvm::APSInt> ConditionSize =
438 ConditionExpr->getIntegerConstantExpr(*Context);
439 if (!ConditionSize)
440 return false;
441 const llvm::APSInt ArraySize(ConstType->getSize());
442 return llvm::APSInt::isSameValue(*ConditionSize, ArraySize);
443}
444
446 const VarDecl *IndexVar,
447 const VarDecl *EndVar,
448 const Expr *ContainerExpr,
449 const Expr *ArrayBoundExpr,
450 bool ContainerNeedsDereference)
451 : Context(Context), IndexVar(IndexVar), EndVar(EndVar),
452 ContainerExpr(ContainerExpr), ArrayBoundExpr(ArrayBoundExpr),
453 ContainerNeedsDereference(ContainerNeedsDereference),
454
455 ConfidenceLevel(Confidence::CL_Safe) {
456 if (ContainerExpr)
457 addComponent(ContainerExpr);
458}
459
461 TraverseStmt(const_cast<Stmt *>(Body));
462 return OnlyUsedAsIndex && ContainerExpr;
463}
464
466 // FIXME: add sort(on ID)+unique to avoid extra work.
467 for (const auto &I : Components)
468 addComponent(I);
469}
470
471void ForLoopIndexUseVisitor::addComponent(const Expr *E) {
472 llvm::FoldingSetNodeID ID;
473 const Expr *Node = E->IgnoreParenImpCasts();
474 Node->Profile(ID, *Context, true);
475 DependentExprs.emplace_back(Node, ID);
476}
477
479 SourceLocation Begin = U.Range.getBegin();
480 if (Begin.isMacroID())
481 Begin = Context->getSourceManager().getSpellingLoc(Begin);
482
483 if (UsageLocations.insert(Begin).second)
484 Usages.push_back(U);
485}
486
487/// If the unary operator is a dereference of IndexVar, include it
488/// as a valid usage and prune the traversal.
489///
490/// For example, if container.begin() and container.end() both return pointers
491/// to int, this makes sure that the initialization for `k` is not counted as an
492/// unconvertible use of the iterator `i`.
493/// \code
494/// for (int *i = container.begin(), *e = container.end(); i != e; ++i) {
495/// int k = *i + 2;
496/// }
497/// \endcode
498bool ForLoopIndexUseVisitor::TraverseUnaryOperator(UnaryOperator *Uop) {
499 // If we dereference an iterator that's actually a pointer, count the
500 // occurrence.
501 if (isDereferenceOfUop(Uop, IndexVar)) {
502 addUsage(Usage(Uop));
503 return true;
504 }
505
506 return VisitorBase::TraverseUnaryOperator(Uop);
507}
508
509/// If the member expression is operator-> (overloaded or not) on
510/// IndexVar, include it as a valid usage and prune the traversal.
511///
512/// For example, given
513/// \code
514/// struct Foo { int bar(); int x; };
515/// vector<Foo> v;
516/// \endcode
517/// the following uses will be considered convertible:
518/// \code
519/// for (vector<Foo>::iterator i = v.begin(), e = v.end(); i != e; ++i) {
520/// int b = i->bar();
521/// int k = i->x + 1;
522/// }
523/// \endcode
524/// though
525/// \code
526/// for (vector<Foo>::iterator i = v.begin(), e = v.end(); i != e; ++i) {
527/// int k = i.insert(1);
528/// }
529/// for (vector<Foo>::iterator i = v.begin(), e = v.end(); i != e; ++i) {
530/// int b = e->bar();
531/// }
532/// \endcode
533/// will not.
534bool ForLoopIndexUseVisitor::TraverseMemberExpr(MemberExpr *Member) {
535 const Expr *Base = Member->getBase();
536 const DeclRefExpr *Obj = getDeclRef(Base);
537 const Expr *ResultExpr = Member;
538 QualType ExprType;
539 if (const auto *Call =
540 dyn_cast<CXXOperatorCallExpr>(Base->IgnoreParenImpCasts());
541 Call && Call->getOperator() == OO_Arrow)
542 // If operator->() is a MemberExpr containing a CXXOperatorCallExpr, then
543 // the MemberExpr does not have the expression we want. We therefore catch
544 // that instance here.
545 // For example, if vector<Foo>::iterator defines operator->(), then the
546 // example `i->bar()` at the top of this function is a CXXMemberCallExpr
547 // referring to `i->` as the member function called. We want just `i`, so
548 // we take the argument to operator->() as the base object.
549 {
550 assert(Call->getNumArgs() == 1 &&
551 "Operator-> takes more than one argument");
552 Obj = getDeclRef(Call->getArg(0));
553 ResultExpr = Obj;
554 ExprType = Call->getCallReturnType(*Context);
555 }
556
557 if (Obj && exprReferencesVariable(IndexVar, Obj)) {
558 // Member calls on the iterator with '.' are not allowed.
559 if (!Member->isArrow()) {
560 OnlyUsedAsIndex = false;
561 return true;
562 }
563
564 if (ExprType.isNull())
565 ExprType = Obj->getType();
566
567 if (!ExprType->isPointerType())
568 return false;
569
570 // FIXME: This works around not having the location of the arrow operator.
571 // Consider adding OperatorLoc to MemberExpr?
572 const SourceLocation ArrowLoc = Lexer::getLocForEndOfToken(
573 Base->getExprLoc(), 0, Context->getSourceManager(),
574 Context->getLangOpts());
575 // If something complicated is happening (i.e. the next token isn't an
576 // arrow), give up on making this work.
577 if (ArrowLoc.isValid()) {
579 SourceRange(Base->getExprLoc(), ArrowLoc)));
580 return true;
581 }
582 }
583 return VisitorBase::TraverseMemberExpr(Member);
584}
585
586/// If a member function call is the at() accessor on the container with
587/// IndexVar as the single argument, include it as a valid usage and prune
588/// the traversal.
589///
590/// Member calls on other objects will not be permitted.
591/// Calls on the iterator object are not permitted, unless done through
592/// operator->(). The one exception is allowing vector::at() for pseudoarrays.
593bool ForLoopIndexUseVisitor::TraverseCXXMemberCallExpr(
594 CXXMemberCallExpr *MemberCall) {
595 const auto *Member =
596 dyn_cast<MemberExpr>(MemberCall->getCallee()->IgnoreParenImpCasts());
597 if (!Member)
598 return VisitorBase::TraverseCXXMemberCallExpr(MemberCall);
599
600 // We specifically allow an accessor named "at" to let STL in, though
601 // this is restricted to pseudo-arrays by requiring a single, integer
602 // argument.
603 const IdentifierInfo *Ident = Member->getMemberDecl()->getIdentifier();
604 if (Ident && Ident->isStr("at") && MemberCall->getNumArgs() == 1 &&
605 isIndexInSubscriptExpr(Context, MemberCall->getArg(0), IndexVar,
606 Member->getBase(), ContainerExpr,
607 ContainerNeedsDereference)) {
608 addUsage(Usage(MemberCall));
609 return true;
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 LE && S != LE->getBody())
833 // Any child of a LambdaExpr that isn't the body is an initialization
834 // expression.
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.