clang-tools 24.0.0git
LoopConvertCheck.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 "LoopConvertCheck.h"
10#include "clang/AST/ASTContext.h"
11#include "clang/ASTMatchers/ASTMatchFinder.h"
12#include "clang/Basic/LLVM.h"
13#include "clang/Basic/LangOptions.h"
14#include "clang/Basic/SourceLocation.h"
15#include "clang/Basic/SourceManager.h"
16#include "clang/Lex/Lexer.h"
17#include "llvm/ADT/ArrayRef.h"
18#include "llvm/ADT/SmallVector.h"
19#include "llvm/ADT/StringRef.h"
20#include "llvm/ADT/StringSet.h"
21#include "llvm/Support/raw_ostream.h"
22#include <cassert>
23#include <cstring>
24#include <optional>
25#include <utility>
26
27using namespace clang::ast_matchers;
28using namespace llvm;
29
30namespace clang::tidy {
31
32template <> struct OptionEnumMapping<modernize::Confidence::Level> {
33 static llvm::ArrayRef<std::pair<modernize::Confidence::Level, StringRef>>
35 static constexpr std::pair<modernize::Confidence::Level, StringRef>
36 Mapping[] = {{modernize::Confidence::CL_Reasonable, "reasonable"},
39 return {Mapping};
40 }
41};
42
43template <> struct OptionEnumMapping<modernize::VariableNamer::NamingStyle> {
44 static llvm::ArrayRef<
45 std::pair<modernize::VariableNamer::NamingStyle, StringRef>>
47 static constexpr std::pair<modernize::VariableNamer::NamingStyle, StringRef>
48 Mapping[] = {{modernize::VariableNamer::NS_CamelCase, "CamelCase"},
52 return {Mapping};
53 }
54};
55
56namespace modernize {
57
58static constexpr char LoopNameArray[] = "forLoopArray";
59static constexpr char LoopNameIterator[] = "forLoopIterator";
60static constexpr char LoopNameReverseIterator[] = "forLoopReverseIterator";
61static constexpr char LoopNamePseudoArray[] = "forLoopPseudoArray";
62static constexpr char ConditionBoundName[] = "conditionBound";
63static constexpr char InitVarName[] = "initVar";
64static constexpr char BeginCallName[] = "beginCall";
65static constexpr char EndCallName[] = "endCall";
66static constexpr char EndVarName[] = "endVar";
67static constexpr char DerefByValueResultName[] = "derefByValueResult";
68static constexpr char DerefByRefResultName[] = "derefByRefResult";
69static const llvm::StringSet<> MemberNames{"begin", "cbegin", "rbegin",
70 "crbegin", "end", "cend",
71 "rend", "crend", "size"};
72static const llvm::StringSet<> ADLNames{"begin", "cbegin", "rbegin",
73 "crbegin", "end", "cend",
74 "rend", "crend", "size"};
75static const llvm::StringSet<> StdNames{
76 "std::begin", "std::cbegin", "std::rbegin", "std::crbegin", "std::end",
77 "std::cend", "std::rend", "std::crend", "std::size"};
78
79static StatementMatcher integerComparisonMatcher() {
80 return expr(ignoringParenImpCasts(
81 declRefExpr(to(varDecl(equalsBoundNode(InitVarName))))));
82}
83
84static DeclarationMatcher initToZeroMatcher() {
85 return varDecl(
86 hasInitializer(ignoringParenImpCasts(integerLiteral(equals(0)))))
87 .bind(InitVarName);
88}
89
90static StatementMatcher incrementVarMatcher() {
91 return declRefExpr(to(varDecl(equalsBoundNode(InitVarName))));
92}
93
94static StatementMatcher
95arrayConditionMatcher(const internal::Matcher<Expr> &LimitExpr) {
96 return binaryOperator(
97 anyOf(allOf(hasOperatorName("<"), hasLHS(integerComparisonMatcher()),
98 hasRHS(LimitExpr)),
99 allOf(hasOperatorName(">"), hasLHS(LimitExpr),
100 hasRHS(integerComparisonMatcher())),
101 allOf(hasOperatorName("!="),
102 hasOperands(integerComparisonMatcher(), LimitExpr))));
103}
104
105/// The matcher for loops over arrays.
106/// \code
107/// for (int i = 0; i < 3 + 2; ++i) { ... }
108/// \endcode
109/// The following string identifiers are bound to these parts of the AST:
110/// ConditionBoundName: '3 + 2' (as an Expr)
111/// InitVarName: 'i' (as a VarDecl)
112/// LoopName: The entire for loop (as a ForStmt)
113///
114/// Client code will need to make sure that:
115/// - The index variable is only used as an array index.
116/// - All arrays indexed by the loop are the same.
117static StatementMatcher makeArrayLoopMatcher() {
118 const StatementMatcher ArrayBoundMatcher =
119 expr(hasType(isInteger())).bind(ConditionBoundName);
120
121 return forStmt(unless(isInTemplateInstantiation()),
122 hasLoopInit(declStmt(hasSingleDecl(initToZeroMatcher()))),
123 hasCondition(arrayConditionMatcher(ArrayBoundMatcher)),
124 hasIncrement(
125 unaryOperator(hasOperatorName("++"),
126 hasUnaryOperand(incrementVarMatcher()))))
127 .bind(LoopNameArray);
128}
129
130/// The matcher used for iterator-based for loops.
131///
132/// This matcher is more flexible than array-based loops. It will match
133/// catch loops of the following textual forms (regardless of whether the
134/// iterator type is actually a pointer type or a class type):
135///
136/// \code
137/// for (containerType::iterator it = container.begin(),
138/// e = createIterator(); it != e; ++it) { ... }
139/// for (containerType::iterator it = container.begin();
140/// it != anotherContainer.end(); ++it) { ... }
141/// for (containerType::iterator it = begin(container),
142/// e = end(container); it != e; ++it) { ... }
143/// for (containerType::iterator it = std::begin(container),
144/// e = std::end(container); it != e; ++it) { ... }
145/// \endcode
146/// The following string identifiers are bound to the parts of the AST:
147/// InitVarName: 'it' (as a VarDecl)
148/// LoopName: The entire for loop (as a ForStmt)
149/// In the first example only:
150/// EndVarName: 'e' (as a VarDecl)
151/// In the second example only:
152/// EndCallName: 'container.end()' (as a CXXMemberCallExpr)
153/// In the third/fourth examples:
154/// 'end(container)' or 'std::end(container)' (as a CallExpr)
155///
156/// Client code will need to make sure that:
157/// - The two containers on which 'begin' and 'end' are called are the same.
158static StatementMatcher makeIteratorLoopMatcher(bool IsReverse) {
159 const auto BeginNameMatcher = IsReverse ? hasAnyName("rbegin", "crbegin")
160 : hasAnyName("begin", "cbegin");
161 const auto BeginNameMatcherStd =
162 IsReverse ? hasAnyName("::std::rbegin", "::std::crbegin")
163 : hasAnyName("::std::begin", "::std::cbegin");
164
165 const auto EndNameMatcher =
166 IsReverse ? hasAnyName("rend", "crend") : hasAnyName("end", "cend");
167 const auto EndNameMatcherStd = IsReverse
168 ? hasAnyName("::std::rend", "::std::crend")
169 : hasAnyName("::std::end", "::std::cend");
170
171 const StatementMatcher BeginCallMatcher =
172 expr(anyOf(cxxMemberCallExpr(argumentCountIs(0),
173 callee(cxxMethodDecl(BeginNameMatcher))),
174 callExpr(argumentCountIs(1),
175 callee(functionDecl(BeginNameMatcher)), usesADL()),
176 callExpr(argumentCountIs(1),
177 callee(functionDecl(BeginNameMatcherStd)))))
178 .bind(BeginCallName);
179
180 const DeclarationMatcher InitDeclMatcher =
181 varDecl(hasInitializer(anyOf(ignoringParenImpCasts(BeginCallMatcher),
182 materializeTemporaryExpr(
183 ignoringParenImpCasts(BeginCallMatcher)),
184 hasDescendant(BeginCallMatcher))))
185 .bind(InitVarName);
186
187 const DeclarationMatcher EndDeclMatcher =
188 varDecl(hasInitializer(anything())).bind(EndVarName);
189
190 const StatementMatcher EndCallMatcher = expr(anyOf(
191 cxxMemberCallExpr(argumentCountIs(0),
192 callee(cxxMethodDecl(EndNameMatcher))),
193 callExpr(argumentCountIs(1), callee(functionDecl(EndNameMatcher)),
194 usesADL()),
195 callExpr(argumentCountIs(1), callee(functionDecl(EndNameMatcherStd)))));
196
197 const StatementMatcher IteratorBoundMatcher =
198 expr(anyOf(ignoringParenImpCasts(
199 declRefExpr(to(varDecl(equalsBoundNode(EndVarName))))),
200 ignoringParenImpCasts(expr(EndCallMatcher).bind(EndCallName)),
201 materializeTemporaryExpr(ignoringParenImpCasts(
202 expr(EndCallMatcher).bind(EndCallName)))));
203
204 const StatementMatcher IteratorComparisonMatcher = expr(ignoringParenImpCasts(
205 declRefExpr(to(varDecl(equalsBoundNode(InitVarName))))));
206
207 // This matcher tests that a declaration is a CXXRecordDecl that has an
208 // overloaded operator*(). If the operator*() returns by value instead of by
209 // reference then the return type is tagged with DerefByValueResultName.
210 const internal::Matcher<VarDecl> TestDerefReturnsByValue =
211 hasType(hasUnqualifiedDesugaredType(
212 recordType(hasDeclaration(cxxRecordDecl(hasMethod(cxxMethodDecl(
213 hasOverloadedOperatorName("*"),
214 anyOf(
215 // Tag the return type if it's by value.
216 returns(qualType(unless(hasCanonicalType(referenceType())))
218 returns(
219 // Skip loops where the iterator's operator* returns an
220 // rvalue reference. This is just weird.
221 qualType(unless(hasCanonicalType(rValueReferenceType())))
222 .bind(DerefByRefResultName))))))))));
223
224 return forStmt(
225 unless(isInTemplateInstantiation()),
226 hasLoopInit(anyOf(declStmt(declCountIs(2),
227 containsDeclaration(0, InitDeclMatcher),
228 containsDeclaration(1, EndDeclMatcher)),
229 declStmt(hasSingleDecl(InitDeclMatcher)))),
230 hasCondition(ignoringImplicit(binaryOperation(
231 hasOperatorName("!="), hasOperands(IteratorComparisonMatcher,
232 IteratorBoundMatcher)))),
233 hasIncrement(anyOf(
234 unaryOperator(hasOperatorName("++"),
235 hasUnaryOperand(declRefExpr(
236 to(varDecl(equalsBoundNode(InitVarName)))))),
237 cxxOperatorCallExpr(
238 hasOverloadedOperatorName("++"),
239 hasArgument(0, declRefExpr(to(
240 varDecl(equalsBoundNode(InitVarName),
241 TestDerefReturnsByValue))))))))
242 .bind(IsReverse ? LoopNameReverseIterator : LoopNameIterator);
243}
244
245/// The matcher used for array-like containers (pseudoarrays).
246///
247/// This matcher is more flexible than array-based loops. It will match
248/// loops of the following textual forms (regardless of whether the
249/// iterator type is actually a pointer type or a class type):
250///
251/// \code
252/// for (int i = 0, j = container.size(); i < j; ++i) { ... }
253/// for (int i = 0; i < container.size(); ++i) { ... }
254/// for (int i = 0; i < size(container); ++i) { ... }
255/// \endcode
256/// The following string identifiers are bound to the parts of the AST:
257/// InitVarName: 'i' (as a VarDecl)
258/// LoopName: The entire for loop (as a ForStmt)
259/// In the first example only:
260/// EndVarName: 'j' (as a VarDecl)
261/// In the second example only:
262/// EndCallName: 'container.size()' (as a CXXMemberCallExpr) or
263/// 'size(container)' (as a CallExpr)
264///
265/// Client code will need to make sure that:
266/// - The containers on which 'size()' is called is the container indexed.
267/// - The index variable is only used in overloaded operator[] or
268/// container.at().
269/// - The container's iterators would not be invalidated during the loop.
270static StatementMatcher makePseudoArrayLoopMatcher() {
271 // Test that the incoming type has a record declaration that has methods
272 // called 'begin' and 'end'. If the incoming type is const, then make sure
273 // these methods are also marked const.
274 //
275 // FIXME: To be completely thorough this matcher should also ensure the
276 // return type of begin/end is an iterator that dereferences to the same as
277 // what operator[] or at() returns. Such a test isn't likely to fail except
278 // for pathological cases.
279 //
280 // FIXME: Also, a record doesn't necessarily need begin() and end(). Free
281 // functions called begin() and end() taking the container as an argument
282 // are also allowed.
283 const TypeMatcher RecordWithBeginEnd = qualType(anyOf(
284 qualType(isConstQualified(),
285 hasUnqualifiedDesugaredType(recordType(hasDeclaration(
286 cxxRecordDecl(isSameOrDerivedFrom(cxxRecordDecl(
287 hasMethod(cxxMethodDecl(hasName("begin"), isConst())),
288 hasMethod(cxxMethodDecl(hasName("end"),
289 isConst())))))) // hasDeclaration
290 ))), // qualType
291 qualType(unless(isConstQualified()),
292 hasUnqualifiedDesugaredType(recordType(hasDeclaration(
293 cxxRecordDecl(isSameOrDerivedFrom(cxxRecordDecl(
294 hasMethod(hasName("begin")),
295 hasMethod(hasName("end"))))))))) // qualType
296 ));
297
298 const StatementMatcher SizeCallMatcher = expr(anyOf(
299 cxxMemberCallExpr(argumentCountIs(0),
300 callee(cxxMethodDecl(hasAnyName("size", "length"))),
301 on(anyOf(hasType(pointsTo(RecordWithBeginEnd)),
302 hasType(RecordWithBeginEnd)))),
303 callExpr(argumentCountIs(1), callee(functionDecl(hasName("size"))),
304 usesADL()),
305 callExpr(argumentCountIs(1),
306 callee(functionDecl(hasName("::std::size"))))));
307
308 StatementMatcher EndInitMatcher =
309 expr(anyOf(ignoringParenImpCasts(expr(SizeCallMatcher).bind(EndCallName)),
310 explicitCastExpr(hasSourceExpression(ignoringParenImpCasts(
311 expr(SizeCallMatcher).bind(EndCallName))))));
312
313 const DeclarationMatcher EndDeclMatcher =
314 varDecl(hasInitializer(EndInitMatcher)).bind(EndVarName);
315
316 const StatementMatcher IndexBoundMatcher =
317 expr(anyOf(ignoringParenImpCasts(
318 declRefExpr(to(varDecl(equalsBoundNode(EndVarName))))),
319 EndInitMatcher));
320
321 return forStmt(unless(isInTemplateInstantiation()),
322 hasLoopInit(
323 anyOf(declStmt(declCountIs(2),
324 containsDeclaration(0, initToZeroMatcher()),
325 containsDeclaration(1, EndDeclMatcher)),
326 declStmt(hasSingleDecl(initToZeroMatcher())))),
327 hasCondition(arrayConditionMatcher(IndexBoundMatcher)),
328 hasIncrement(
329 unaryOperator(hasOperatorName("++"),
330 hasUnaryOperand(incrementVarMatcher()))))
331 .bind(LoopNamePseudoArray);
332}
333
334namespace {
335
336enum class IteratorCallKind {
337 ICK_Member,
338 ICK_ADL,
339 ICK_Std,
340};
341
342struct ContainerCall {
343 const Expr *Container;
344 StringRef Name;
345 bool IsArrow;
346 IteratorCallKind CallKind;
347};
348
349} // namespace
350
351// Find the Expr likely initializing an iterator.
352//
353// Call is either a CXXMemberCallExpr ('c.begin()') or CallExpr of a free
354// function with the first argument as a container ('begin(c)'), or nullptr.
355// Returns at a 3-tuple with the container expr, function name (begin/end/etc),
356// and whether the call is made through an arrow (->) for CXXMemberCallExprs.
357// The returned Expr* is nullptr if any of the assumptions are not met.
358// static std::tuple<const Expr *, StringRef, bool, IteratorCallKind>
359static std::optional<ContainerCall> getContainerExpr(const Expr *Call) {
360 const Expr *Dug = digThroughConstructorsConversions(Call);
361
362 IteratorCallKind CallKind = IteratorCallKind::ICK_Member;
363
364 if (const auto *TheCall = dyn_cast_or_null<CXXMemberCallExpr>(Dug)) {
365 CallKind = IteratorCallKind::ICK_Member;
366 if (const auto *Member = dyn_cast<MemberExpr>(TheCall->getCallee())) {
367 if (Member->getMemberDecl() == nullptr ||
368 !MemberNames.contains(Member->getMemberDecl()->getName()))
369 return std::nullopt;
370 return ContainerCall{TheCall->getImplicitObjectArgument(),
371 Member->getMemberDecl()->getName(),
372 Member->isArrow(), CallKind};
373 }
374 if (TheCall->getDirectCallee() == nullptr ||
375 !MemberNames.contains(TheCall->getDirectCallee()->getName()))
376 return std::nullopt;
377 return ContainerCall{TheCall->getArg(0),
378 TheCall->getDirectCallee()->getName(), false,
379 CallKind};
380 }
381 if (const auto *TheCall = dyn_cast_or_null<CallExpr>(Dug)) {
382 if (TheCall->getNumArgs() != 1)
383 return std::nullopt;
384
385 if (TheCall->usesADL()) {
386 if (TheCall->getDirectCallee() == nullptr ||
387 !ADLNames.contains(TheCall->getDirectCallee()->getName()))
388 return std::nullopt;
389 CallKind = IteratorCallKind::ICK_ADL;
390 } else {
391 if (!StdNames.contains(
392 TheCall->getDirectCallee()->getQualifiedNameAsString()))
393 return std::nullopt;
394 CallKind = IteratorCallKind::ICK_Std;
395 }
396
397 if (TheCall->getDirectCallee() == nullptr)
398 return std::nullopt;
399
400 return ContainerCall{TheCall->getArg(0),
401 TheCall->getDirectCallee()->getName(), false,
402 CallKind};
403 }
404 return std::nullopt;
405}
406
407/// Determine whether Init appears to be an initializing an iterator.
408///
409/// If it is, returns the object whose begin() or end() method is called, and
410/// the output parameter isArrow is set to indicate whether the initialization
411/// is called via . or ->.
412static std::pair<const Expr *, IteratorCallKind>
413getContainerFromBeginEndCall(const Expr *Init, bool IsBegin, bool *IsArrow,
414 bool IsReverse) {
415 // FIXME: Maybe allow declaration/initialization outside of the for loop.
416
417 std::optional<ContainerCall> Call = getContainerExpr(Init);
418 if (!Call)
419 return {};
420
421 *IsArrow = Call->IsArrow;
422 if (!Call->Name.consume_back(IsBegin ? "begin" : "end"))
423 return {};
424 if (IsReverse && !Call->Name.consume_back("r"))
425 return {};
426 if (!Call->Name.empty() && Call->Name != "c")
427 return {};
428 return {Call->Container, Call->CallKind};
429}
430
431/// Determines the container whose begin() and end() functions are called
432/// for an iterator-based loop.
433///
434/// BeginExpr must be a member call to a function named "begin()", and EndExpr
435/// must be a member.
436static const Expr *findContainer(const ASTContext *Context,
437 const Expr *BeginExpr, const Expr *EndExpr,
438 bool *ContainerNeedsDereference,
439 bool IsReverse) {
440 // Now that we know the loop variable and test expression, make sure they are
441 // valid.
442 bool BeginIsArrow = false;
443 bool EndIsArrow = false;
444 auto [BeginContainerExpr, BeginCallKind] = getContainerFromBeginEndCall(
445 BeginExpr, /*IsBegin=*/true, &BeginIsArrow, IsReverse);
446 if (!BeginContainerExpr)
447 return nullptr;
448
449 auto [EndContainerExpr, EndCallKind] = getContainerFromBeginEndCall(
450 EndExpr, /*IsBegin=*/false, &EndIsArrow, IsReverse);
451 if (BeginCallKind != EndCallKind)
452 return nullptr;
453
454 // Disallow loops that try evil things like this (note the dot and arrow):
455 // for (IteratorType It = Obj.begin(), E = Obj->end(); It != E; ++It) { }
456 if (!EndContainerExpr || BeginIsArrow != EndIsArrow ||
457 !areSameExpr(Context, EndContainerExpr, BeginContainerExpr))
458 return nullptr;
459
460 *ContainerNeedsDereference = BeginIsArrow;
461 return BeginContainerExpr;
462}
463
464/// Obtain the original source code text from a SourceRange.
465static StringRef getStringFromRange(const SourceManager &SourceMgr,
466 const LangOptions &LangOpts,
467 SourceRange Range) {
468 if (SourceMgr.getFileID(Range.getBegin()) !=
469 SourceMgr.getFileID(Range.getEnd())) {
470 return {}; // Empty string.
471 }
472
473 return Lexer::getSourceText(CharSourceRange(Range, true), SourceMgr,
474 LangOpts);
475}
476
477/// If the given expression is actually a DeclRefExpr or a MemberExpr,
478/// find and return the underlying ValueDecl; otherwise, return NULL.
479static const ValueDecl *getReferencedVariable(const Expr *E) {
480 if (const DeclRefExpr *DRE = getDeclRef(E))
481 return dyn_cast<VarDecl>(DRE->getDecl());
482 if (const auto *Mem = dyn_cast<MemberExpr>(E->IgnoreParenImpCasts()))
483 return dyn_cast<FieldDecl>(Mem->getMemberDecl());
484 return nullptr;
485}
486
487/// Returns true when the given expression is a member expression
488/// whose base is `this` (implicitly or not).
489static bool isDirectMemberExpr(const Expr *E) {
490 if (const auto *Member = dyn_cast<MemberExpr>(E->IgnoreParenImpCasts()))
491 return isa<CXXThisExpr>(Member->getBase()->IgnoreParenImpCasts());
492 return false;
493}
494
495/// Given an expression that represents an usage of an element from the
496/// container that we are iterating over, returns false when it can be
497/// guaranteed this element cannot be modified as a result of this usage.
498static bool canBeModified(ASTContext *Context, const Expr *E) {
499 if (E->getType().isConstQualified())
500 return false;
501 const auto Parents = Context->getParents(*E);
502 if (Parents.size() != 1)
503 return true;
504 if (const auto *Cast = Parents[0].get<ImplicitCastExpr>();
505 Cast &&
506 ((Cast->getCastKind() == CK_NoOp &&
507 ASTContext::hasSameType(Cast->getType(), E->getType().withConst())) ||
508 (Cast->getCastKind() == CK_LValueToRValue && !Cast->getType().isNull() &&
509 Cast->getType()->isFundamentalType())))
510 return false;
511
512 // FIXME: Make this function more generic.
513 return true;
514}
515
516/// Returns true when it can be guaranteed that the elements of the
517/// container are not being modified.
518static bool usagesAreConst(ASTContext *Context, const UsageResult &Usages) {
519 return llvm::none_of(Usages, [&Context](const Usage &U) {
520 // Lambda captures are just redeclarations (VarDecl) of the same variable,
521 // not expressions. If we want to know if a variable that is captured by
522 // reference can be modified in an usage inside the lambda's body, we need
523 // to find the expression corresponding to that particular usage, later in
524 // this loop.
525 return U.Kind != Usage::UK_CaptureByCopy &&
527 canBeModified(Context, U.Expression);
528 });
529}
530
531/// Returns true if the elements of the container are never accessed
532/// by reference.
533static bool usagesReturnRValues(const UsageResult &Usages) {
534 return llvm::all_of(Usages, [](const Usage &U) {
535 return !U.Expression || U.Expression->isPRValue();
536 });
537}
538
539/// Returns true if the container is const-qualified.
540static bool containerIsConst(const Expr *ContainerExpr, bool Dereference) {
541 if (const auto *VDec = getReferencedVariable(ContainerExpr)) {
542 QualType CType = VDec->getType();
543 if (Dereference) {
544 if (!CType->isPointerType())
545 return false;
546 CType = CType->getPointeeType();
547 }
548 // If VDec is a reference to a container, Dereference is false,
549 // but we still need to check the const-ness of the underlying container
550 // type.
551 CType = CType.getNonReferenceType();
552 return CType.isConstQualified();
553 }
554 return false;
555}
556
557// Returns true if the token at `BeginLocation` is immediately preceded by an
558// identifier or keyword token with no space between them.
559static bool
560isPrecededByAdjacentIdentifierOrKeyword(const SourceManager &SourceMgr,
561 const LangOptions &LangOpts,
562 SourceLocation BeginLocation) {
563 std::optional<Token> PrevToken =
564 Lexer::findPreviousToken(BeginLocation, SourceMgr, LangOpts, true);
565 if (!PrevToken)
566 return false;
567 // Check whether the token at `BeginLocation` is immediately adjacent to
568 // the previous token with no space between them.
569 const bool IsAdjacentToPrevToken = PrevToken->getEndLoc() == BeginLocation;
570 return PrevToken->isAnyIdentifier() && IsAdjacentToPrevToken;
571}
572
573// Returns true if the replacement text needs a leading space to avoid merging
574// with the preceding token. This occurs when `*it` is immediately adjacent to
575// a keyword, e.g. `delete*it`, where replacing `*it` with `it` would
576// incorrectly produce `deleteit`. So we insert a space b/w `delete` and `it`.
577static bool requiresLeadingSpace(const SourceManager &SourceMgr,
578 const LangOptions &LangOpts,
579 SourceLocation BeginLocation) {
580 Token StarToken;
581 if (!Lexer::getRawToken(BeginLocation, StarToken, SourceMgr, LangOpts,
582 false) &&
583 StarToken.is(tok::star)) {
584 return isPrecededByAdjacentIdentifierOrKeyword(SourceMgr, LangOpts,
585 BeginLocation);
586 }
587 return false;
588}
589
591 : ClangTidyCheck(Name, Context), TUInfo(new TUTrackingInfo),
592 MaxCopySize(Options.get("MaxCopySize", 16ULL)),
593 MinConfidence(Options.get("MinConfidence", Confidence::CL_Reasonable)),
594 NamingStyle(Options.get("NamingStyle", VariableNamer::NS_CamelCase)),
595 Inserter(Options.getLocalOrGlobal("IncludeStyle",
596 utils::IncludeSorter::IS_LLVM),
597 areDiagsSelfContained()),
598 UseCxx20IfAvailable(Options.get("UseCxx20ReverseRanges", true)),
599 ReverseFunction(Options.get("MakeReverseRangeFunction", "")),
600 ReverseHeader(Options.get("MakeReverseRangeHeader", "")) {
601 if (ReverseFunction.empty() && !ReverseHeader.empty()) {
602 configurationDiag(
603 "modernize-loop-convert: 'MakeReverseRangeHeader' is set but "
604 "'MakeReverseRangeFunction' is not, disabling reverse loop "
605 "transformation");
606 UseReverseRanges = false;
607 } else if (ReverseFunction.empty()) {
608 UseReverseRanges = UseCxx20IfAvailable && getLangOpts().CPlusPlus20;
609 } else {
610 UseReverseRanges = true;
611 }
612}
613
615 Options.store(Opts, "MaxCopySize", MaxCopySize);
616 Options.store(Opts, "MinConfidence", MinConfidence);
617 Options.store(Opts, "NamingStyle", NamingStyle);
618 Options.store(Opts, "IncludeStyle", Inserter.getStyle());
619 Options.store(Opts, "UseCxx20ReverseRanges", UseCxx20IfAvailable);
620 Options.store(Opts, "MakeReverseRangeFunction", ReverseFunction);
621 Options.store(Opts, "MakeReverseRangeHeader", ReverseHeader);
622}
623
624void LoopConvertCheck::registerPPCallbacks(const SourceManager &SM,
625 Preprocessor *PP,
626 Preprocessor *ModuleExpanderPP) {
627 Inserter.registerPreprocessor(PP);
628}
629
630void LoopConvertCheck::registerMatchers(MatchFinder *Finder) {
631 Finder->addMatcher(traverse(TK_AsIs, makeArrayLoopMatcher()), this);
632 Finder->addMatcher(traverse(TK_AsIs, makeIteratorLoopMatcher(false)), this);
633 Finder->addMatcher(traverse(TK_AsIs, makePseudoArrayLoopMatcher()), this);
634 if (UseReverseRanges)
635 Finder->addMatcher(traverse(TK_AsIs, makeIteratorLoopMatcher(true)), this);
636}
637
638/// Given the range of a single declaration, such as:
639/// \code
640/// unsigned &ThisIsADeclarationThatCanSpanSeveralLinesOfCode =
641/// InitializationValues[I];
642/// next_instruction;
643/// \endcode
644/// Finds the range that has to be erased to remove this declaration without
645/// leaving empty lines, by extending the range until the beginning of the
646/// next instruction.
647///
648/// We need to delete a potential newline after the deleted alias, as
649/// clang-format will leave empty lines untouched. For all other formatting we
650/// rely on clang-format to fix it.
651void LoopConvertCheck::getAliasRange(SourceManager &SM, SourceRange &Range) {
652 bool Invalid = false;
653 const char *TextAfter =
654 SM.getCharacterData(Range.getEnd().getLocWithOffset(1), &Invalid);
655 if (Invalid)
656 return;
657 const unsigned Offset = std::strspn(TextAfter, " \t\r\n");
658 Range =
659 SourceRange(Range.getBegin(), Range.getEnd().getLocWithOffset(Offset));
660}
661
662/// Computes the changes needed to convert a given for loop, and
663/// applies them.
664void LoopConvertCheck::doConversion(
665 ASTContext *Context, const VarDecl *IndexVar,
666 const ValueDecl *MaybeContainer, const UsageResult &Usages,
667 const DeclStmt *AliasDecl, bool AliasUseRequired, bool AliasFromForInit,
668 const ForStmt *Loop, RangeDescriptor Descriptor) {
669 std::string VarNameOrStructuredBinding;
670 const bool VarNameFromAlias = (Usages.size() == 1) && AliasDecl;
671 bool AliasVarIsRef = false;
672 bool CanCopy = true;
673 std::vector<FixItHint> FixIts;
674 if (VarNameFromAlias) {
675 const auto *AliasVar = cast<VarDecl>(AliasDecl->getSingleDecl());
676
677 // Handle structured bindings
678 if (const auto *AliasDecompositionDecl =
679 dyn_cast<DecompositionDecl>(AliasDecl->getSingleDecl())) {
680 VarNameOrStructuredBinding = "[";
681
682 assert(!AliasDecompositionDecl->bindings().empty() && "No bindings");
683 for (const BindingDecl *Binding : AliasDecompositionDecl->bindings())
684 VarNameOrStructuredBinding += Binding->getName().str() + ", ";
685
686 VarNameOrStructuredBinding.erase(VarNameOrStructuredBinding.size() - 2,
687 2);
688 VarNameOrStructuredBinding += ']';
689 } else {
690 VarNameOrStructuredBinding = AliasVar->getName().str();
691
692 // Use the type of the alias if it's not the same
693 QualType AliasVarType = AliasVar->getType();
694 assert(!AliasVarType.isNull() && "Type in VarDecl is null");
695 if (AliasVarType->isReferenceType()) {
696 AliasVarType = AliasVarType.getNonReferenceType();
697 AliasVarIsRef = true;
698 }
699 if (Descriptor.ElemType.isNull() ||
700 !ASTContext::hasSameUnqualifiedType(AliasVarType,
701 Descriptor.ElemType))
702 Descriptor.ElemType = AliasVarType;
703 }
704
705 // We keep along the entire DeclStmt to keep the correct range here.
706 SourceRange ReplaceRange = AliasDecl->getSourceRange();
707
708 std::string ReplacementText;
709 if (AliasUseRequired) {
710 ReplacementText = VarNameOrStructuredBinding;
711 } else if (AliasFromForInit) {
712 // FIXME: Clang includes the location of the ';' but only for DeclStmt's
713 // in a for loop's init clause. Need to put this ';' back while removing
714 // the declaration of the alias variable. This is probably a bug.
715 ReplacementText = ";";
716 } else {
717 // Avoid leaving empty lines or trailing whitespaces.
718 getAliasRange(Context->getSourceManager(), ReplaceRange);
719 }
720
721 FixIts.push_back(FixItHint::CreateReplacement(
722 CharSourceRange::getTokenRange(ReplaceRange), ReplacementText));
723 // No further replacements are made to the loop, since the iterator or index
724 // was used exactly once - in the initialization of AliasVar.
725 } else {
726 VariableNamer Namer(&TUInfo->getGeneratedDecls(),
727 &TUInfo->getParentFinder().getStmtToParentStmtMap(),
728 Loop, IndexVar, MaybeContainer, Context, NamingStyle);
729 VarNameOrStructuredBinding = Namer.createIndexName();
730 // First, replace all usages of the array subscript expression with our new
731 // variable.
732 for (const auto &Usage : Usages) {
733 std::string ReplaceText;
734 SourceRange Range = Usage.Range;
735 if (Usage.Expression) {
736 if (Usage.Kind == Usage::UK_Default &&
737 requiresLeadingSpace(Context->getSourceManager(), getLangOpts(),
738 Usage.Range.getBegin()))
739 ReplaceText = " ";
740 // If this is an access to a member through the arrow operator, after
741 // the replacement it must be accessed through the '.' operator.
742 ReplaceText += Usage.Kind == Usage::UK_MemberThroughArrow
743 ? VarNameOrStructuredBinding + "."
744 : VarNameOrStructuredBinding;
745 const DynTypedNodeList Parents = Context->getParents(*Usage.Expression);
746 if (Parents.size() == 1) {
747 if (const auto *Paren = Parents[0].get<ParenExpr>()) {
748 // Usage.Expression will be replaced with the new index variable,
749 // and parenthesis around a simple DeclRefExpr can always be
750 // removed except in case of a `sizeof` operator call.
751 const DynTypedNodeList GrandParents = Context->getParents(*Paren);
752 if (GrandParents.size() != 1 ||
753 (GrandParents[0].get<UnaryExprOrTypeTraitExpr>() == nullptr &&
755 Context->getSourceManager(), getLangOpts(),
756 Parents[0].getSourceRange().getBegin()))) {
757 Range = Paren->getSourceRange();
758 }
759 } else if (const auto *UOP = Parents[0].get<UnaryOperator>();
760 UOP && UOP->getOpcode() == UO_AddrOf) {
761 // If we are taking the address of the loop variable, then we must
762 // not use a copy, as it would mean taking the address of the loop's
763 // local index instead.
764 // FIXME: This won't catch cases where the address is taken outside
765 // of the loop's body (for instance, in a function that got the
766 // loop's index as a const reference parameter), or where we take
767 // the address of a member (like "&Arr[i].A.B.C").
768 CanCopy = false;
769 }
770 }
771 } else {
772 // The Usage expression is only null in case of lambda captures (which
773 // are VarDecl). If the index is captured by value, add '&' to capture
774 // by reference instead.
775 ReplaceText = Usage.Kind == Usage::UK_CaptureByCopy
776 ? "&" + VarNameOrStructuredBinding
777 : VarNameOrStructuredBinding;
778 }
779 TUInfo->getReplacedVars().try_emplace(Loop, IndexVar);
780 FixIts.push_back(FixItHint::CreateReplacement(
781 CharSourceRange::getTokenRange(Range), ReplaceText));
782 }
783 }
784
785 // Now, we need to construct the new range expression.
786 const SourceRange ParenRange(Loop->getLParenLoc(), Loop->getRParenLoc());
787
788 QualType Type = Context->getAutoDeductType();
789 if (!Descriptor.ElemType.isNull() && Descriptor.ElemType->isFundamentalType())
790 Type = Descriptor.ElemType.getUnqualifiedType();
791 Type = Type.getDesugaredType(*Context);
792
793 // If the new variable name is from the aliased variable, then the reference
794 // type for the new variable should only be used if the aliased variable was
795 // declared as a reference.
796 const bool IsCheapToCopy =
797 !Descriptor.ElemType.isNull() &&
798 Descriptor.ElemType.isTriviallyCopyableType(*Context) &&
799 !Descriptor.ElemType->isDependentSizedArrayType() &&
800 // TypeInfo::Width is in bits.
801 Context->getTypeInfo(Descriptor.ElemType).Width <= 8 * MaxCopySize;
802 const bool UseCopy =
803 CanCopy && ((VarNameFromAlias && !AliasVarIsRef) ||
804 (Descriptor.DerefByConstRef && IsCheapToCopy));
805
806 if (!UseCopy) {
807 if (Descriptor.DerefByConstRef) {
808 Type = Context->getLValueReferenceType(Context->getConstType(Type));
809 } else if (Descriptor.DerefByValue) {
810 if (!IsCheapToCopy)
811 Type = Context->getRValueReferenceType(Type);
812 } else {
813 Type = Context->getLValueReferenceType(Type);
814 }
815 }
816
817 SmallString<128> Range;
818 llvm::raw_svector_ostream Output(Range);
819 Output << '(';
820 Type.print(Output, getLangOpts());
821 Output << ' ' << VarNameOrStructuredBinding << " : ";
822 if (Descriptor.NeedsReverseCall)
823 Output << getReverseFunction() << '(';
824 if (Descriptor.ContainerNeedsDereference)
825 Output << '*';
826 Output << Descriptor.ContainerString;
827 if (Descriptor.NeedsReverseCall)
828 Output << "))";
829 else
830 Output << ')';
831 FixIts.push_back(FixItHint::CreateReplacement(
832 CharSourceRange::getTokenRange(ParenRange), Range));
833
834 if (Descriptor.NeedsReverseCall && !getReverseHeader().empty()) {
835 if (std::optional<FixItHint> Insertion = Inserter.createIncludeInsertion(
836 Context->getSourceManager().getFileID(Loop->getBeginLoc()),
837 getReverseHeader()))
838 FixIts.push_back(*Insertion);
839 }
840 diag(Loop->getForLoc(), "use range-based for loop instead") << FixIts;
841 TUInfo->getGeneratedDecls().try_emplace(Loop, VarNameOrStructuredBinding);
842}
843
844/// Returns a string which refers to the container iterated over.
845StringRef LoopConvertCheck::getContainerString(ASTContext *Context,
846 const ForStmt *Loop,
847 const Expr *ContainerExpr) {
848 StringRef ContainerString;
849 ContainerExpr = ContainerExpr->IgnoreParenImpCasts();
850 if (isa<CXXThisExpr>(ContainerExpr)) {
851 ContainerString = "this";
852 } else {
853 // For CXXOperatorCallExpr such as vector_ptr->size() we want the class
854 // object vector_ptr, but for vector[2] we need the whole expression.
855 if (const auto *E = dyn_cast<CXXOperatorCallExpr>(ContainerExpr);
856 E && E->getOperator() != OO_Subscript)
857 ContainerExpr = E->getArg(0);
858 ContainerString =
859 getStringFromRange(Context->getSourceManager(), Context->getLangOpts(),
860 ContainerExpr->getSourceRange());
861 }
862
863 return ContainerString;
864}
865
866/// Determines what kind of 'auto' must be used after converting a for
867/// loop that iterates over an array or pseudoarray.
868void LoopConvertCheck::getArrayLoopQualifiers(ASTContext *Context,
869 const BoundNodes &Nodes,
870 const Expr *ContainerExpr,
871 const UsageResult &Usages,
872 RangeDescriptor &Descriptor) {
873 // On arrays and pseudoarrays, we must figure out the qualifiers from the
874 // usages.
875 if (usagesAreConst(Context, Usages) ||
876 containerIsConst(ContainerExpr, Descriptor.ContainerNeedsDereference)) {
877 Descriptor.DerefByConstRef = true;
878 }
879 if (usagesReturnRValues(Usages)) {
880 // If the index usages (dereference, subscript, at, ...) return rvalues,
881 // then we should not use a reference, because we need to keep the code
882 // correct if it mutates the returned objects.
883 Descriptor.DerefByValue = true;
884 }
885 // Try to find the type of the elements on the container, to check if
886 // they are trivially copyable.
887 for (const Usage &U : Usages) {
888 if (!U.Expression || U.Expression->getType().isNull())
889 continue;
890 QualType Type = U.Expression->getType().getCanonicalType();
891 if (U.Kind == Usage::UK_MemberThroughArrow) {
892 if (!Type->isPointerType())
893 continue;
894 Type = Type->getPointeeType();
895 }
896 Descriptor.ElemType = Type;
897 }
898}
899
900/// Determines what kind of 'auto' must be used after converting an
901/// iterator based for loop.
902void LoopConvertCheck::getIteratorLoopQualifiers(ASTContext *Context,
903 const BoundNodes &Nodes,
904 RangeDescriptor &Descriptor) {
905 // The matchers for iterator loops provide bound nodes to obtain this
906 // information.
907 const auto *InitVar = Nodes.getNodeAs<VarDecl>(InitVarName);
908 const QualType CanonicalInitVarType = InitVar->getType().getCanonicalType();
909 const auto *DerefByValueType =
910 Nodes.getNodeAs<QualType>(DerefByValueResultName);
911 Descriptor.DerefByValue = DerefByValueType;
912
913 if (Descriptor.DerefByValue) {
914 // If the dereference operator returns by value then test for the
915 // canonical const qualification of the init variable type.
916 Descriptor.DerefByConstRef = CanonicalInitVarType.isConstQualified();
917 Descriptor.ElemType = *DerefByValueType;
918 } else if (const auto *DerefType =
919 Nodes.getNodeAs<QualType>(DerefByRefResultName)) {
920 // A node will only be bound with DerefByRefResultName if we're dealing
921 // with a user-defined iterator type. Test the const qualification of
922 // the reference type.
923 const auto ValueType = DerefType->getNonReferenceType();
924
925 Descriptor.DerefByConstRef = ValueType.isConstQualified();
926 Descriptor.ElemType = ValueType;
927 } else {
928 // By nature of the matcher this case is triggered only for built-in
929 // iterator types (i.e. pointers).
930 assert(isa<PointerType>(CanonicalInitVarType) &&
931 "Non-class iterator type is not a pointer type");
932
933 // We test for const qualification of the pointed-at type.
934 Descriptor.DerefByConstRef =
935 CanonicalInitVarType->getPointeeType().isConstQualified();
936 Descriptor.ElemType = CanonicalInitVarType->getPointeeType();
937 }
938}
939
940/// Determines the parameters needed to build the range replacement.
941void LoopConvertCheck::determineRangeDescriptor(
942 ASTContext *Context, const BoundNodes &Nodes, const ForStmt *Loop,
943 LoopFixerKind FixerKind, const Expr *ContainerExpr,
944 const UsageResult &Usages, RangeDescriptor &Descriptor) {
945 Descriptor.ContainerString =
946 std::string(getContainerString(Context, Loop, ContainerExpr));
947 Descriptor.NeedsReverseCall = (FixerKind == LFK_ReverseIterator);
948
949 if (FixerKind == LFK_Iterator || FixerKind == LFK_ReverseIterator)
950 getIteratorLoopQualifiers(Context, Nodes, Descriptor);
951 else
952 getArrayLoopQualifiers(Context, Nodes, ContainerExpr, Usages, Descriptor);
953}
954
955/// Check some of the conditions that must be met for the loop to be
956/// convertible.
957bool LoopConvertCheck::isConvertible(ASTContext *Context,
958 const ast_matchers::BoundNodes &Nodes,
959 const ForStmt *Loop,
960 LoopFixerKind FixerKind) {
961 // In self contained diagnostic mode we don't want dependencies on other
962 // loops, otherwise, If we already modified the range of this for loop, don't
963 // do any further updates on this iteration.
964 if (areDiagsSelfContained())
965 TUInfo = std::make_unique<TUTrackingInfo>();
966 else if (TUInfo->getReplacedVars().contains(Loop))
967 return false;
968
969 // Check that we have exactly one index variable and at most one end variable.
970 const auto *InitVar = Nodes.getNodeAs<VarDecl>(InitVarName);
971
972 // FIXME: Try to put most of this logic inside a matcher.
973 if (FixerKind == LFK_Iterator || FixerKind == LFK_ReverseIterator) {
974 const QualType InitVarType = InitVar->getType();
975 const QualType CanonicalInitVarType = InitVarType.getCanonicalType();
976
977 const auto *BeginCall = Nodes.getNodeAs<CallExpr>(BeginCallName);
978 assert(BeginCall && "Bad Callback. No begin call expression");
979 const QualType CanonicalBeginType =
980 BeginCall->getDirectCallee()->getReturnType().getCanonicalType();
981 if (CanonicalBeginType->isPointerType() &&
982 CanonicalInitVarType->isPointerType()) {
983 // If the initializer and the variable are both pointers check if the
984 // un-qualified pointee types match, otherwise we don't use auto.
985 return ASTContext::hasSameUnqualifiedType(
986 CanonicalBeginType->getPointeeType(),
987 CanonicalInitVarType->getPointeeType());
988 }
989
990 if (CanonicalBeginType->isBuiltinType() ||
991 CanonicalInitVarType->isBuiltinType())
992 return false;
993
994 } else if (FixerKind == LFK_PseudoArray) {
995 if (const auto *EndCall = Nodes.getNodeAs<CXXMemberCallExpr>(EndCallName);
996 EndCall && !isa<MemberExpr>(EndCall->getCallee()))
997 // This call is required to obtain the container.
998 return false;
999
1000 return Nodes.getNodeAs<CallExpr>(EndCallName) != nullptr;
1001 }
1002 return true;
1003}
1004
1005void LoopConvertCheck::check(const MatchFinder::MatchResult &Result) {
1006 const BoundNodes &Nodes = Result.Nodes;
1007 Confidence ConfidenceLevel(Confidence::CL_Safe);
1008 ASTContext *Context = Result.Context;
1009
1010 const ForStmt *Loop = nullptr;
1011 LoopFixerKind FixerKind{};
1012 RangeDescriptor Descriptor;
1013
1014 if ((Loop = Nodes.getNodeAs<ForStmt>(LoopNameArray))) {
1015 FixerKind = LFK_Array;
1016 } else if ((Loop = Nodes.getNodeAs<ForStmt>(LoopNameIterator))) {
1017 FixerKind = LFK_Iterator;
1018 } else if ((Loop = Nodes.getNodeAs<ForStmt>(LoopNameReverseIterator))) {
1019 FixerKind = LFK_ReverseIterator;
1020 } else {
1021 Loop = Nodes.getNodeAs<ForStmt>(LoopNamePseudoArray);
1022 assert(Loop && "Bad Callback. No for statement");
1023 FixerKind = LFK_PseudoArray;
1024 }
1025
1026 if (!isConvertible(Context, Nodes, Loop, FixerKind))
1027 return;
1028
1029 const auto *LoopVar = Nodes.getNodeAs<VarDecl>(InitVarName);
1030 const auto *EndVar = Nodes.getNodeAs<VarDecl>(EndVarName);
1031
1032 // If the loop calls end()/size() after each iteration, lower our confidence
1033 // level.
1034 if (FixerKind != LFK_Array && !EndVar)
1035 ConfidenceLevel.lowerTo(Confidence::CL_Reasonable);
1036
1037 // If the end comparison isn't a variable, we can try to work with the
1038 // expression the loop variable is being tested against instead.
1039 const auto *EndCall = Nodes.getNodeAs<Expr>(EndCallName);
1040 const auto *BoundExpr = Nodes.getNodeAs<Expr>(ConditionBoundName);
1041
1042 // Find container expression of iterators and pseudoarrays, and determine if
1043 // this expression needs to be dereferenced to obtain the container.
1044 // With array loops, the container is often discovered during the
1045 // ForLoopIndexUseVisitor traversal.
1046 const Expr *ContainerExpr = nullptr;
1047 if (FixerKind == LFK_Iterator || FixerKind == LFK_ReverseIterator) {
1048 ContainerExpr = findContainer(
1049 Context, LoopVar->getInit(), EndVar ? EndVar->getInit() : EndCall,
1050 &Descriptor.ContainerNeedsDereference,
1051 /*IsReverse=*/FixerKind == LFK_ReverseIterator);
1052 } else if (FixerKind == LFK_PseudoArray) {
1053 std::optional<ContainerCall> Call = getContainerExpr(EndCall);
1054 if (Call) {
1055 ContainerExpr = Call->Container;
1056 Descriptor.ContainerNeedsDereference = Call->IsArrow;
1057 }
1058 }
1059
1060 // We must know the container or an array length bound.
1061 if (!ContainerExpr && !BoundExpr)
1062 return;
1063
1064 ForLoopIndexUseVisitor Finder(Context, LoopVar, EndVar, ContainerExpr,
1065 BoundExpr,
1066 Descriptor.ContainerNeedsDereference);
1067
1068 // Find expressions and variables on which the container depends.
1069 if (ContainerExpr) {
1070 ComponentFinderASTVisitor ComponentFinder;
1071 ComponentFinder.findExprComponents(ContainerExpr->IgnoreParenImpCasts());
1072 Finder.addComponents(ComponentFinder.getComponents());
1073 }
1074
1075 // Find usages of the loop index. If they are not used in a convertible way,
1076 // stop here.
1077 if (!Finder.findAndVerifyUsages(Loop->getBody()))
1078 return;
1079 ConfidenceLevel.lowerTo(Finder.getConfidenceLevel());
1080
1081 // Obtain the container expression, if we don't have it yet.
1082 if (FixerKind == LFK_Array) {
1083 ContainerExpr = Finder.getContainerIndexed()->IgnoreParenImpCasts();
1084
1085 // Very few loops are over expressions that generate arrays rather than
1086 // array variables. Consider loops over arrays that aren't just represented
1087 // by a variable to be risky conversions.
1088 if (!getReferencedVariable(ContainerExpr) &&
1089 !isDirectMemberExpr(ContainerExpr))
1090 ConfidenceLevel.lowerTo(Confidence::CL_Risky);
1091 }
1092
1093 // Find out which qualifiers we have to use in the loop range.
1094 const TraversalKindScope RAII(*Context, TK_AsIs);
1095 const UsageResult &Usages = Finder.getUsages();
1096 determineRangeDescriptor(Context, Nodes, Loop, FixerKind, ContainerExpr,
1097 Usages, Descriptor);
1098
1099 // Ensure that we do not try to move an expression dependent on a local
1100 // variable declared inside the loop outside of it.
1101 // FIXME: Determine when the external dependency isn't an expression converted
1102 // by another loop.
1103 TUInfo->getParentFinder().gatherAncestors(*Context);
1104 DependencyFinderASTVisitor DependencyFinder(
1105 &TUInfo->getParentFinder().getStmtToParentStmtMap(),
1106 &TUInfo->getParentFinder().getDeclToParentStmtMap(),
1107 &TUInfo->getReplacedVars(), Loop);
1108
1109 if (DependencyFinder.dependsOnInsideVariable(ContainerExpr) ||
1110 Descriptor.ContainerString.empty() || Usages.empty() ||
1111 ConfidenceLevel.getLevel() < MinConfidence)
1112 return;
1113
1114 doConversion(Context, LoopVar, getReferencedVariable(ContainerExpr), Usages,
1115 Finder.getAliasDecl(), Finder.aliasUseRequired(),
1116 Finder.aliasFromForInit(), Loop, Descriptor);
1117}
1118
1119StringRef LoopConvertCheck::getReverseFunction() const {
1120 if (!ReverseFunction.empty())
1121 return ReverseFunction;
1122 if (UseReverseRanges)
1123 return "std::views::reverse";
1124 return "";
1125}
1126
1127StringRef LoopConvertCheck::getReverseHeader() const {
1128 if (!ReverseHeader.empty())
1129 return ReverseHeader;
1130 if (UseReverseRanges && ReverseFunction.empty())
1131 return "<ranges>";
1132 return "";
1133}
1134
1135} // namespace modernize
1136} // namespace clang::tidy
const char Usage[]
Every ClangTidyCheck reports errors through a DiagnosticsEngine provided by this context.
Class used to find the variables and member expressions on which an arbitrary expression depends.
void findExprComponents(const Expr *SourceExpr)
Find the components of an expression and place them in a ComponentVector.
const ComponentVector & getComponents()
Accessor for Components.
A class to encapsulate lowering of the tool's confidence level.
Level getLevel() const
Return the internal confidence level.
void lowerTo(Confidence::Level Level)
Lower the internal confidence level to Level, but do not raise it.
Class used to determine if an expression is dependent on a variable declared inside of the loop where...
bool dependsOnInsideVariable(const Stmt *Body)
Run the analysis on Body, and return true iff the expression depends on some variable declared within...
Discover usages of expressions consisting of index or iterator access.
const UsageResult & getUsages() const
Accessor for Usages.
bool aliasFromForInit() const
Indicates if the alias declaration came from the init clause of a nested for loop.
const DeclStmt * getAliasDecl() const
Returns the statement declaring the variable created as an alias for the loop element,...
bool aliasUseRequired() const
Indicates if the alias declaration was in a place where it cannot simply be removed but rather replac...
bool findAndVerifyUsages(const Stmt *Body)
Finds all uses of IndexVar in Body, placing all usages in Usages, and returns true if IndexVar was on...
Confidence::Level getConfidenceLevel() const
Accessor for ConfidenceLevel.
void addComponents(const ComponentVector &Components)
Add a set of components that we should consider relevant to the container.
const Expr * getContainerIndexed() const
Get the container indexed by IndexVar, if any.
void registerPPCallbacks(const SourceManager &SM, Preprocessor *PP, Preprocessor *ModuleExpanderPP) override
void storeOptions(ClangTidyOptions::OptionMap &Opts) override
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
LoopConvertCheck(StringRef Name, ClangTidyContext *Context)
void registerMatchers(ast_matchers::MatchFinder *Finder) override
Create names for generated variables within a particular statement.
@ Type
An inlay hint that for a type annotation.
Definition Protocol.h:1745
static constexpr char BeginCallName[]
static constexpr char DerefByRefResultName[]
static bool empty(SourceRange Range)
static constexpr char LoopNameReverseIterator[]
static const llvm::StringSet StdNames
static DeclarationMatcher initToZeroMatcher()
static StatementMatcher incrementVarMatcher()
static constexpr char EndCallName[]
static StatementMatcher makePseudoArrayLoopMatcher()
The matcher used for array-like containers (pseudoarrays).
static StatementMatcher arrayConditionMatcher(const internal::Matcher< Expr > &LimitExpr)
static constexpr char ConditionBoundName[]
static bool canBeModified(ASTContext *Context, const Expr *E)
Given an expression that represents an usage of an element from the container that we are iterating o...
static StringRef getStringFromRange(const SourceManager &SourceMgr, const LangOptions &LangOpts, SourceRange Range)
Obtain the original source code text from a SourceRange.
static std::optional< ContainerCall > getContainerExpr(const Expr *Call)
const DeclRefExpr * getDeclRef(const Expr *E)
Returns the DeclRefExpr represented by E, or NULL if there isn't one.
static const llvm::StringSet MemberNames
static const llvm::StringSet ADLNames
static StatementMatcher makeArrayLoopMatcher()
The matcher for loops over arrays.
static bool usagesReturnRValues(const UsageResult &Usages)
Returns true if the elements of the container are never accessed by reference.
static const ValueDecl * getReferencedVariable(const Expr *E)
If the given expression is actually a DeclRefExpr or a MemberExpr, find and return the underlying Val...
static constexpr char EndVarName[]
static StatementMatcher integerComparisonMatcher()
static const Expr * findContainer(const ASTContext *Context, const Expr *BeginExpr, const Expr *EndExpr, bool *ContainerNeedsDereference, bool IsReverse)
Determines the container whose begin() and end() functions are called for an iterator-based loop.
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 containerIsConst(const Expr *ContainerExpr, bool Dereference)
Returns true if the container is const-qualified.
static constexpr char LoopNamePseudoArray[]
static std::pair< const Expr *, IteratorCallKind > getContainerFromBeginEndCall(const Expr *Init, bool IsBegin, bool *IsArrow, bool IsReverse)
Determine whether Init appears to be an initializing an iterator.
static constexpr char InitVarName[]
static constexpr char LoopNameIterator[]
static constexpr char DerefByValueResultName[]
SmallVector< Usage, 8 > UsageResult
static bool isDirectMemberExpr(const Expr *E)
Returns true when the given expression is a member expression whose base is this (implicitly or not).
static StatementMatcher makeIteratorLoopMatcher(bool IsReverse)
The matcher used for iterator-based for loops.
static constexpr char LoopNameArray[]
static bool usagesAreConst(ASTContext *Context, const UsageResult &Usages)
Returns true when it can be guaranteed that the elements of the container are not being modified.
static bool requiresLeadingSpace(const SourceManager &SourceMgr, const LangOptions &LangOpts, SourceLocation BeginLocation)
static bool isPrecededByAdjacentIdentifierOrKeyword(const SourceManager &SourceMgr, const LangOptions &LangOpts, SourceLocation BeginLocation)
Some operations such as code completion produce a set of candidates.
Definition Generators.h:150
llvm::StringMap< ClangTidyValue > OptionMap
static llvm::ArrayRef< std::pair< modernize::Confidence::Level, StringRef > > getEnumMapping()
static llvm::ArrayRef< std::pair< modernize::VariableNamer::NamingStyle, StringRef > > getEnumMapping()
This class should be specialized by any enum type that needs to be converted to and from an llvm::Str...
The information needed to describe a valid convertible usage of an array index or iterator.