clang-tools 22.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 const char LoopNameArray[] = "forLoopArray";
59static const char LoopNameIterator[] = "forLoopIterator";
60static const char LoopNameReverseIterator[] = "forLoopReverseIterator";
61static const char LoopNamePseudoArray[] = "forLoopPseudoArray";
62static const char ConditionBoundName[] = "conditionBound";
63static const char InitVarName[] = "initVar";
64static const char BeginCallName[] = "beginCall";
65static const char EndCallName[] = "endCall";
66static const char EndVarName[] = "endVar";
67static const char DerefByValueResultName[] = "derefByValueResult";
68static const 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
160 auto BeginNameMatcher = IsReverse ? hasAnyName("rbegin", "crbegin")
161 : hasAnyName("begin", "cbegin");
162 auto BeginNameMatcherStd = IsReverse
163 ? hasAnyName("::std::rbegin", "::std::crbegin")
164 : hasAnyName("::std::begin", "::std::cbegin");
165
166 auto EndNameMatcher =
167 IsReverse ? hasAnyName("rend", "crend") : hasAnyName("end", "cend");
168 auto EndNameMatcherStd = IsReverse ? 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
339
341 const Expr *Container;
342 StringRef Name;
345};
346
347// Find the Expr likely initializing an iterator.
348//
349// Call is either a CXXMemberCallExpr ('c.begin()') or CallExpr of a free
350// function with the first argument as a container ('begin(c)'), or nullptr.
351// Returns at a 3-tuple with the container expr, function name (begin/end/etc),
352// and whether the call is made through an arrow (->) for CXXMemberCallExprs.
353// The returned Expr* is nullptr if any of the assumptions are not met.
354// static std::tuple<const Expr *, StringRef, bool, IteratorCallKind>
355static std::optional<ContainerCall> getContainerExpr(const Expr *Call) {
356 const Expr *Dug = digThroughConstructorsConversions(Call);
357
359
360 if (const auto *TheCall = dyn_cast_or_null<CXXMemberCallExpr>(Dug)) {
362 if (const auto *Member = dyn_cast<MemberExpr>(TheCall->getCallee())) {
363 if (Member->getMemberDecl() == nullptr ||
364 !MemberNames.contains(Member->getMemberDecl()->getName()))
365 return std::nullopt;
366 return ContainerCall{TheCall->getImplicitObjectArgument(),
367 Member->getMemberDecl()->getName(),
368 Member->isArrow(), CallKind};
369 }
370 if (TheCall->getDirectCallee() == nullptr ||
371 !MemberNames.contains(TheCall->getDirectCallee()->getName()))
372 return std::nullopt;
373 return ContainerCall{TheCall->getArg(0),
374 TheCall->getDirectCallee()->getName(), false,
375 CallKind};
376 }
377 if (const auto *TheCall = dyn_cast_or_null<CallExpr>(Dug)) {
378 if (TheCall->getNumArgs() != 1)
379 return std::nullopt;
380
381 if (TheCall->usesADL()) {
382 if (TheCall->getDirectCallee() == nullptr ||
383 !ADLNames.contains(TheCall->getDirectCallee()->getName()))
384 return std::nullopt;
385 CallKind = IteratorCallKind::ICK_ADL;
386 } else {
387 if (!StdNames.contains(
388 TheCall->getDirectCallee()->getQualifiedNameAsString()))
389 return std::nullopt;
390 CallKind = IteratorCallKind::ICK_Std;
391 }
392
393 if (TheCall->getDirectCallee() == nullptr)
394 return std::nullopt;
395
396 return ContainerCall{TheCall->getArg(0),
397 TheCall->getDirectCallee()->getName(), false,
398 CallKind};
399 }
400 return std::nullopt;
401}
402
403/// Determine whether Init appears to be an initializing an iterator.
404///
405/// If it is, returns the object whose begin() or end() method is called, and
406/// the output parameter isArrow is set to indicate whether the initialization
407/// is called via . or ->.
408static std::pair<const Expr *, IteratorCallKind>
409getContainerFromBeginEndCall(const Expr *Init, bool IsBegin, bool *IsArrow,
410 bool IsReverse) {
411 // FIXME: Maybe allow declaration/initialization outside of the for loop.
412
413 std::optional<ContainerCall> Call = getContainerExpr(Init);
414 if (!Call)
415 return {};
416
417 *IsArrow = Call->IsArrow;
418 if (!Call->Name.consume_back(IsBegin ? "begin" : "end"))
419 return {};
420 if (IsReverse && !Call->Name.consume_back("r"))
421 return {};
422 if (!Call->Name.empty() && Call->Name != "c")
423 return {};
424 return std::make_pair(Call->Container, Call->CallKind);
425}
426
427/// Determines the container whose begin() and end() functions are called
428/// for an iterator-based loop.
429///
430/// BeginExpr must be a member call to a function named "begin()", and EndExpr
431/// must be a member.
432static const Expr *findContainer(ASTContext *Context, const Expr *BeginExpr,
433 const Expr *EndExpr,
434 bool *ContainerNeedsDereference,
435 bool IsReverse) {
436 // Now that we know the loop variable and test expression, make sure they are
437 // valid.
438 bool BeginIsArrow = false;
439 bool EndIsArrow = false;
440 auto [BeginContainerExpr, BeginCallKind] = getContainerFromBeginEndCall(
441 BeginExpr, /*IsBegin=*/true, &BeginIsArrow, IsReverse);
442 if (!BeginContainerExpr)
443 return nullptr;
444
445 auto [EndContainerExpr, EndCallKind] = getContainerFromBeginEndCall(
446 EndExpr, /*IsBegin=*/false, &EndIsArrow, IsReverse);
447 if (BeginCallKind != EndCallKind)
448 return nullptr;
449
450 // Disallow loops that try evil things like this (note the dot and arrow):
451 // for (IteratorType It = Obj.begin(), E = Obj->end(); It != E; ++It) { }
452 if (!EndContainerExpr || BeginIsArrow != EndIsArrow ||
453 !areSameExpr(Context, EndContainerExpr, BeginContainerExpr))
454 return nullptr;
455
456 *ContainerNeedsDereference = BeginIsArrow;
457 return BeginContainerExpr;
458}
459
460/// Obtain the original source code text from a SourceRange.
461static StringRef getStringFromRange(SourceManager &SourceMgr,
462 const LangOptions &LangOpts,
463 SourceRange Range) {
464 if (SourceMgr.getFileID(Range.getBegin()) !=
465 SourceMgr.getFileID(Range.getEnd())) {
466 return {}; // Empty string.
467 }
468
469 return Lexer::getSourceText(CharSourceRange(Range, true), SourceMgr,
470 LangOpts);
471}
472
473/// If the given expression is actually a DeclRefExpr or a MemberExpr,
474/// find and return the underlying ValueDecl; otherwise, return NULL.
475static const ValueDecl *getReferencedVariable(const Expr *E) {
476 if (const DeclRefExpr *DRE = getDeclRef(E))
477 return dyn_cast<VarDecl>(DRE->getDecl());
478 if (const auto *Mem = dyn_cast<MemberExpr>(E->IgnoreParenImpCasts()))
479 return dyn_cast<FieldDecl>(Mem->getMemberDecl());
480 return nullptr;
481}
482
483/// Returns true when the given expression is a member expression
484/// whose base is `this` (implicitly or not).
485static bool isDirectMemberExpr(const Expr *E) {
486 if (const auto *Member = dyn_cast<MemberExpr>(E->IgnoreParenImpCasts()))
487 return isa<CXXThisExpr>(Member->getBase()->IgnoreParenImpCasts());
488 return false;
489}
490
491/// Given an expression that represents an usage of an element from the
492/// container that we are iterating over, returns false when it can be
493/// guaranteed this element cannot be modified as a result of this usage.
494static bool canBeModified(ASTContext *Context, const Expr *E) {
495 if (E->getType().isConstQualified())
496 return false;
497 auto Parents = Context->getParents(*E);
498 if (Parents.size() != 1)
499 return true;
500 if (const auto *Cast = Parents[0].get<ImplicitCastExpr>()) {
501 if ((Cast->getCastKind() == CK_NoOp &&
502 ASTContext::hasSameType(Cast->getType(), E->getType().withConst())) ||
503 (Cast->getCastKind() == CK_LValueToRValue &&
504 !Cast->getType().isNull() && Cast->getType()->isFundamentalType()))
505 return false;
506 }
507 // FIXME: Make this function more generic.
508 return true;
509}
510
511/// Returns true when it can be guaranteed that the elements of the
512/// container are not being modified.
513static bool usagesAreConst(ASTContext *Context, const UsageResult &Usages) {
514 for (const Usage &U : Usages) {
515 // Lambda captures are just redeclarations (VarDecl) of the same variable,
516 // not expressions. If we want to know if a variable that is captured by
517 // reference can be modified in an usage inside the lambda's body, we need
518 // to find the expression corresponding to that particular usage, later in
519 // this loop.
520 if (U.Kind != Usage::UK_CaptureByCopy && U.Kind != Usage::UK_CaptureByRef &&
521 canBeModified(Context, U.Expression))
522 return false;
523 }
524 return true;
525}
526
527/// Returns true if the elements of the container are never accessed
528/// by reference.
529static bool usagesReturnRValues(const UsageResult &Usages) {
530 for (const auto &U : Usages) {
531 if (U.Expression && !U.Expression->isPRValue())
532 return false;
533 }
534 return true;
535}
536
537/// Returns true if the container is const-qualified.
538static bool containerIsConst(const Expr *ContainerExpr, bool Dereference) {
539 if (const auto *VDec = getReferencedVariable(ContainerExpr)) {
540 QualType CType = VDec->getType();
541 if (Dereference) {
542 if (!CType->isPointerType())
543 return false;
544 CType = CType->getPointeeType();
545 }
546 // If VDec is a reference to a container, Dereference is false,
547 // but we still need to check the const-ness of the underlying container
548 // type.
549 CType = CType.getNonReferenceType();
550 return CType.isConstQualified();
551 }
552 return false;
553}
554
556 : ClangTidyCheck(Name, Context), TUInfo(new TUTrackingInfo),
557 MaxCopySize(Options.get("MaxCopySize", 16ULL)),
558 MinConfidence(Options.get("MinConfidence", Confidence::CL_Reasonable)),
559 NamingStyle(Options.get("NamingStyle", VariableNamer::NS_CamelCase)),
560 Inserter(Options.getLocalOrGlobal("IncludeStyle",
561 utils::IncludeSorter::IS_LLVM),
562 areDiagsSelfContained()),
563 UseCxx20IfAvailable(Options.get("UseCxx20ReverseRanges", true)),
564 ReverseFunction(Options.get("MakeReverseRangeFunction", "")),
565 ReverseHeader(Options.get("MakeReverseRangeHeader", "")) {
566
567 if (ReverseFunction.empty() && !ReverseHeader.empty()) {
568 configurationDiag(
569 "modernize-loop-convert: 'MakeReverseRangeHeader' is set but "
570 "'MakeReverseRangeFunction' is not, disabling reverse loop "
571 "transformation");
572 UseReverseRanges = false;
573 } else if (ReverseFunction.empty()) {
574 UseReverseRanges = UseCxx20IfAvailable && getLangOpts().CPlusPlus20;
575 } else {
576 UseReverseRanges = true;
577 }
578}
579
581 Options.store(Opts, "MaxCopySize", MaxCopySize);
582 Options.store(Opts, "MinConfidence", MinConfidence);
583 Options.store(Opts, "NamingStyle", NamingStyle);
584 Options.store(Opts, "IncludeStyle", Inserter.getStyle());
585 Options.store(Opts, "UseCxx20ReverseRanges", UseCxx20IfAvailable);
586 Options.store(Opts, "MakeReverseRangeFunction", ReverseFunction);
587 Options.store(Opts, "MakeReverseRangeHeader", ReverseHeader);
588}
589
590void LoopConvertCheck::registerPPCallbacks(const SourceManager &SM,
591 Preprocessor *PP,
592 Preprocessor *ModuleExpanderPP) {
593 Inserter.registerPreprocessor(PP);
594}
595
596void LoopConvertCheck::registerMatchers(MatchFinder *Finder) {
597 Finder->addMatcher(traverse(TK_AsIs, makeArrayLoopMatcher()), this);
598 Finder->addMatcher(traverse(TK_AsIs, makeIteratorLoopMatcher(false)), this);
599 Finder->addMatcher(traverse(TK_AsIs, makePseudoArrayLoopMatcher()), this);
600 if (UseReverseRanges)
601 Finder->addMatcher(traverse(TK_AsIs, makeIteratorLoopMatcher(true)), this);
602}
603
604/// Given the range of a single declaration, such as:
605/// \code
606/// unsigned &ThisIsADeclarationThatCanSpanSeveralLinesOfCode =
607/// InitializationValues[I];
608/// next_instruction;
609/// \endcode
610/// Finds the range that has to be erased to remove this declaration without
611/// leaving empty lines, by extending the range until the beginning of the
612/// next instruction.
613///
614/// We need to delete a potential newline after the deleted alias, as
615/// clang-format will leave empty lines untouched. For all other formatting we
616/// rely on clang-format to fix it.
617void LoopConvertCheck::getAliasRange(SourceManager &SM, SourceRange &Range) {
618 bool Invalid = false;
619 const char *TextAfter =
620 SM.getCharacterData(Range.getEnd().getLocWithOffset(1), &Invalid);
621 if (Invalid)
622 return;
623 const unsigned Offset = std::strspn(TextAfter, " \t\r\n");
624 Range =
625 SourceRange(Range.getBegin(), Range.getEnd().getLocWithOffset(Offset));
626}
627
628/// Computes the changes needed to convert a given for loop, and
629/// applies them.
630void LoopConvertCheck::doConversion(
631 ASTContext *Context, const VarDecl *IndexVar,
632 const ValueDecl *MaybeContainer, const UsageResult &Usages,
633 const DeclStmt *AliasDecl, bool AliasUseRequired, bool AliasFromForInit,
634 const ForStmt *Loop, RangeDescriptor Descriptor) {
635 std::string VarNameOrStructuredBinding;
636 const bool VarNameFromAlias = (Usages.size() == 1) && AliasDecl;
637 bool AliasVarIsRef = false;
638 bool CanCopy = true;
639 std::vector<FixItHint> FixIts;
640 if (VarNameFromAlias) {
641 const auto *AliasVar = cast<VarDecl>(AliasDecl->getSingleDecl());
642
643 // Handle structured bindings
644 if (const auto *AliasDecompositionDecl =
645 dyn_cast<DecompositionDecl>(AliasDecl->getSingleDecl())) {
646 VarNameOrStructuredBinding = "[";
647
648 assert(!AliasDecompositionDecl->bindings().empty() && "No bindings");
649 for (const BindingDecl *Binding : AliasDecompositionDecl->bindings()) {
650 VarNameOrStructuredBinding += Binding->getName().str() + ", ";
651 }
652
653 VarNameOrStructuredBinding.erase(VarNameOrStructuredBinding.size() - 2,
654 2);
655 VarNameOrStructuredBinding += "]";
656 } else {
657 VarNameOrStructuredBinding = AliasVar->getName().str();
658
659 // Use the type of the alias if it's not the same
660 QualType AliasVarType = AliasVar->getType();
661 assert(!AliasVarType.isNull() && "Type in VarDecl is null");
662 if (AliasVarType->isReferenceType()) {
663 AliasVarType = AliasVarType.getNonReferenceType();
664 AliasVarIsRef = true;
665 }
666 if (Descriptor.ElemType.isNull() ||
667 !ASTContext::hasSameUnqualifiedType(AliasVarType,
668 Descriptor.ElemType))
669 Descriptor.ElemType = AliasVarType;
670 }
671
672 // We keep along the entire DeclStmt to keep the correct range here.
673 SourceRange ReplaceRange = AliasDecl->getSourceRange();
674
675 std::string ReplacementText;
676 if (AliasUseRequired) {
677 ReplacementText = VarNameOrStructuredBinding;
678 } else if (AliasFromForInit) {
679 // FIXME: Clang includes the location of the ';' but only for DeclStmt's
680 // in a for loop's init clause. Need to put this ';' back while removing
681 // the declaration of the alias variable. This is probably a bug.
682 ReplacementText = ";";
683 } else {
684 // Avoid leaving empty lines or trailing whitespaces.
685 getAliasRange(Context->getSourceManager(), ReplaceRange);
686 }
687
688 FixIts.push_back(FixItHint::CreateReplacement(
689 CharSourceRange::getTokenRange(ReplaceRange), ReplacementText));
690 // No further replacements are made to the loop, since the iterator or index
691 // was used exactly once - in the initialization of AliasVar.
692 } else {
693 VariableNamer Namer(&TUInfo->getGeneratedDecls(),
694 &TUInfo->getParentFinder().getStmtToParentStmtMap(),
695 Loop, IndexVar, MaybeContainer, Context, NamingStyle);
696 VarNameOrStructuredBinding = Namer.createIndexName();
697 // First, replace all usages of the array subscript expression with our new
698 // variable.
699 for (const auto &Usage : Usages) {
700 std::string ReplaceText;
701 SourceRange Range = Usage.Range;
702 if (Usage.Expression) {
703 // If this is an access to a member through the arrow operator, after
704 // the replacement it must be accessed through the '.' operator.
705 ReplaceText = Usage.Kind == Usage::UK_MemberThroughArrow
706 ? VarNameOrStructuredBinding + "."
707 : VarNameOrStructuredBinding;
708 const DynTypedNodeList Parents = Context->getParents(*Usage.Expression);
709 if (Parents.size() == 1) {
710 if (const auto *Paren = Parents[0].get<ParenExpr>()) {
711 // Usage.Expression will be replaced with the new index variable,
712 // and parenthesis around a simple DeclRefExpr can always be
713 // removed except in case of a `sizeof` operator call.
714 const DynTypedNodeList GrandParents = Context->getParents(*Paren);
715 if (GrandParents.size() != 1 ||
716 GrandParents[0].get<UnaryExprOrTypeTraitExpr>() == nullptr) {
717 Range = Paren->getSourceRange();
718 }
719 } else if (const auto *UOP = Parents[0].get<UnaryOperator>()) {
720 // If we are taking the address of the loop variable, then we must
721 // not use a copy, as it would mean taking the address of the loop's
722 // local index instead.
723 // FIXME: This won't catch cases where the address is taken outside
724 // of the loop's body (for instance, in a function that got the
725 // loop's index as a const reference parameter), or where we take
726 // the address of a member (like "&Arr[i].A.B.C").
727 if (UOP->getOpcode() == UO_AddrOf)
728 CanCopy = false;
729 }
730 }
731 } else {
732 // The Usage expression is only null in case of lambda captures (which
733 // are VarDecl). If the index is captured by value, add '&' to capture
734 // by reference instead.
735 ReplaceText = Usage.Kind == Usage::UK_CaptureByCopy
736 ? "&" + VarNameOrStructuredBinding
737 : VarNameOrStructuredBinding;
738 }
739 TUInfo->getReplacedVars().insert(std::make_pair(Loop, IndexVar));
740 FixIts.push_back(FixItHint::CreateReplacement(
741 CharSourceRange::getTokenRange(Range), ReplaceText));
742 }
743 }
744
745 // Now, we need to construct the new range expression.
746 const SourceRange ParenRange(Loop->getLParenLoc(), Loop->getRParenLoc());
747
748 QualType Type = Context->getAutoDeductType();
749 if (!Descriptor.ElemType.isNull() && Descriptor.ElemType->isFundamentalType())
750 Type = Descriptor.ElemType.getUnqualifiedType();
751 Type = Type.getDesugaredType(*Context);
752
753 // If the new variable name is from the aliased variable, then the reference
754 // type for the new variable should only be used if the aliased variable was
755 // declared as a reference.
756 const bool IsCheapToCopy =
757 !Descriptor.ElemType.isNull() &&
758 Descriptor.ElemType.isTriviallyCopyableType(*Context) &&
759 !Descriptor.ElemType->isDependentSizedArrayType() &&
760 // TypeInfo::Width is in bits.
761 Context->getTypeInfo(Descriptor.ElemType).Width <= 8 * MaxCopySize;
762 const bool UseCopy =
763 CanCopy && ((VarNameFromAlias && !AliasVarIsRef) ||
764 (Descriptor.DerefByConstRef && IsCheapToCopy));
765
766 if (!UseCopy) {
767 if (Descriptor.DerefByConstRef) {
768 Type = Context->getLValueReferenceType(Context->getConstType(Type));
769 } else if (Descriptor.DerefByValue) {
770 if (!IsCheapToCopy)
771 Type = Context->getRValueReferenceType(Type);
772 } else {
773 Type = Context->getLValueReferenceType(Type);
774 }
775 }
776
777 SmallString<128> Range;
778 llvm::raw_svector_ostream Output(Range);
779 Output << '(';
780 Type.print(Output, getLangOpts());
781 Output << ' ' << VarNameOrStructuredBinding << " : ";
782 if (Descriptor.NeedsReverseCall)
783 Output << getReverseFunction() << '(';
784 if (Descriptor.ContainerNeedsDereference)
785 Output << '*';
786 Output << Descriptor.ContainerString;
787 if (Descriptor.NeedsReverseCall)
788 Output << "))";
789 else
790 Output << ')';
791 FixIts.push_back(FixItHint::CreateReplacement(
792 CharSourceRange::getTokenRange(ParenRange), Range));
793
794 if (Descriptor.NeedsReverseCall && !getReverseHeader().empty()) {
795 if (std::optional<FixItHint> Insertion = Inserter.createIncludeInsertion(
796 Context->getSourceManager().getFileID(Loop->getBeginLoc()),
797 getReverseHeader()))
798 FixIts.push_back(*Insertion);
799 }
800 diag(Loop->getForLoc(), "use range-based for loop instead") << FixIts;
801 TUInfo->getGeneratedDecls().insert(
802 make_pair(Loop, VarNameOrStructuredBinding));
803}
804
805/// Returns a string which refers to the container iterated over.
806StringRef LoopConvertCheck::getContainerString(ASTContext *Context,
807 const ForStmt *Loop,
808 const Expr *ContainerExpr) {
809 StringRef ContainerString;
810 ContainerExpr = ContainerExpr->IgnoreParenImpCasts();
811 if (isa<CXXThisExpr>(ContainerExpr)) {
812 ContainerString = "this";
813 } else {
814 // For CXXOperatorCallExpr such as vector_ptr->size() we want the class
815 // object vector_ptr, but for vector[2] we need the whole expression.
816 if (const auto *E = dyn_cast<CXXOperatorCallExpr>(ContainerExpr))
817 if (E->getOperator() != OO_Subscript)
818 ContainerExpr = E->getArg(0);
819 ContainerString =
820 getStringFromRange(Context->getSourceManager(), Context->getLangOpts(),
821 ContainerExpr->getSourceRange());
822 }
823
824 return ContainerString;
825}
826
827/// Determines what kind of 'auto' must be used after converting a for
828/// loop that iterates over an array or pseudoarray.
829void LoopConvertCheck::getArrayLoopQualifiers(ASTContext *Context,
830 const BoundNodes &Nodes,
831 const Expr *ContainerExpr,
832 const UsageResult &Usages,
833 RangeDescriptor &Descriptor) {
834 // On arrays and pseudoarrays, we must figure out the qualifiers from the
835 // usages.
836 if (usagesAreConst(Context, Usages) ||
837 containerIsConst(ContainerExpr, Descriptor.ContainerNeedsDereference)) {
838 Descriptor.DerefByConstRef = true;
839 }
840 if (usagesReturnRValues(Usages)) {
841 // If the index usages (dereference, subscript, at, ...) return rvalues,
842 // then we should not use a reference, because we need to keep the code
843 // correct if it mutates the returned objects.
844 Descriptor.DerefByValue = true;
845 }
846 // Try to find the type of the elements on the container, to check if
847 // they are trivially copyable.
848 for (const Usage &U : Usages) {
849 if (!U.Expression || U.Expression->getType().isNull())
850 continue;
851 QualType Type = U.Expression->getType().getCanonicalType();
852 if (U.Kind == Usage::UK_MemberThroughArrow) {
853 if (!Type->isPointerType()) {
854 continue;
855 }
856 Type = Type->getPointeeType();
857 }
858 Descriptor.ElemType = Type;
859 }
860}
861
862/// Determines what kind of 'auto' must be used after converting an
863/// iterator based for loop.
864void LoopConvertCheck::getIteratorLoopQualifiers(ASTContext *Context,
865 const BoundNodes &Nodes,
866 RangeDescriptor &Descriptor) {
867 // The matchers for iterator loops provide bound nodes to obtain this
868 // information.
869 const auto *InitVar = Nodes.getNodeAs<VarDecl>(InitVarName);
870 const QualType CanonicalInitVarType = InitVar->getType().getCanonicalType();
871 const auto *DerefByValueType =
872 Nodes.getNodeAs<QualType>(DerefByValueResultName);
873 Descriptor.DerefByValue = DerefByValueType;
874
875 if (Descriptor.DerefByValue) {
876 // If the dereference operator returns by value then test for the
877 // canonical const qualification of the init variable type.
878 Descriptor.DerefByConstRef = CanonicalInitVarType.isConstQualified();
879 Descriptor.ElemType = *DerefByValueType;
880 } else {
881 if (const auto *DerefType =
882 Nodes.getNodeAs<QualType>(DerefByRefResultName)) {
883 // A node will only be bound with DerefByRefResultName if we're dealing
884 // with a user-defined iterator type. Test the const qualification of
885 // the reference type.
886 auto ValueType = DerefType->getNonReferenceType();
887
888 Descriptor.DerefByConstRef = ValueType.isConstQualified();
889 Descriptor.ElemType = ValueType;
890 } else {
891 // By nature of the matcher this case is triggered only for built-in
892 // iterator types (i.e. pointers).
893 assert(isa<PointerType>(CanonicalInitVarType) &&
894 "Non-class iterator type is not a pointer type");
895
896 // We test for const qualification of the pointed-at type.
897 Descriptor.DerefByConstRef =
898 CanonicalInitVarType->getPointeeType().isConstQualified();
899 Descriptor.ElemType = CanonicalInitVarType->getPointeeType();
900 }
901 }
902}
903
904/// Determines the parameters needed to build the range replacement.
905void LoopConvertCheck::determineRangeDescriptor(
906 ASTContext *Context, const BoundNodes &Nodes, const ForStmt *Loop,
907 LoopFixerKind FixerKind, const Expr *ContainerExpr,
908 const UsageResult &Usages, RangeDescriptor &Descriptor) {
909 Descriptor.ContainerString =
910 std::string(getContainerString(Context, Loop, ContainerExpr));
911 Descriptor.NeedsReverseCall = (FixerKind == LFK_ReverseIterator);
912
913 if (FixerKind == LFK_Iterator || FixerKind == LFK_ReverseIterator)
914 getIteratorLoopQualifiers(Context, Nodes, Descriptor);
915 else
916 getArrayLoopQualifiers(Context, Nodes, ContainerExpr, Usages, Descriptor);
917}
918
919/// Check some of the conditions that must be met for the loop to be
920/// convertible.
921bool LoopConvertCheck::isConvertible(ASTContext *Context,
922 const ast_matchers::BoundNodes &Nodes,
923 const ForStmt *Loop,
924 LoopFixerKind FixerKind) {
925 // In self contained diagnostic mode we don't want dependencies on other
926 // loops, otherwise, If we already modified the range of this for loop, don't
927 // do any further updates on this iteration.
928 if (areDiagsSelfContained())
929 TUInfo = std::make_unique<TUTrackingInfo>();
930 else if (TUInfo->getReplacedVars().contains(Loop))
931 return false;
932
933 // Check that we have exactly one index variable and at most one end variable.
934 const auto *InitVar = Nodes.getNodeAs<VarDecl>(InitVarName);
935
936 // FIXME: Try to put most of this logic inside a matcher.
937 if (FixerKind == LFK_Iterator || FixerKind == LFK_ReverseIterator) {
938 const QualType InitVarType = InitVar->getType();
939 const QualType CanonicalInitVarType = InitVarType.getCanonicalType();
940
941 const auto *BeginCall = Nodes.getNodeAs<CallExpr>(BeginCallName);
942 assert(BeginCall && "Bad Callback. No begin call expression");
943 const QualType CanonicalBeginType =
944 BeginCall->getDirectCallee()->getReturnType().getCanonicalType();
945 if (CanonicalBeginType->isPointerType() &&
946 CanonicalInitVarType->isPointerType()) {
947 // If the initializer and the variable are both pointers check if the
948 // un-qualified pointee types match, otherwise we don't use auto.
949 return ASTContext::hasSameUnqualifiedType(
950 CanonicalBeginType->getPointeeType(),
951 CanonicalInitVarType->getPointeeType());
952 }
953
954 if (CanonicalBeginType->isBuiltinType() ||
955 CanonicalInitVarType->isBuiltinType())
956 return false;
957
958 } else if (FixerKind == LFK_PseudoArray) {
959 if (const auto *EndCall = Nodes.getNodeAs<CXXMemberCallExpr>(EndCallName)) {
960 // This call is required to obtain the container.
961 if (!isa<MemberExpr>(EndCall->getCallee()))
962 return false;
963 }
964 return Nodes.getNodeAs<CallExpr>(EndCallName) != nullptr;
965 }
966 return true;
967}
968
969void LoopConvertCheck::check(const MatchFinder::MatchResult &Result) {
970 const BoundNodes &Nodes = Result.Nodes;
971 Confidence ConfidenceLevel(Confidence::CL_Safe);
972 ASTContext *Context = Result.Context;
973
974 const ForStmt *Loop = nullptr;
975 LoopFixerKind FixerKind{};
976 RangeDescriptor Descriptor;
977
978 if ((Loop = Nodes.getNodeAs<ForStmt>(LoopNameArray))) {
979 FixerKind = LFK_Array;
980 } else if ((Loop = Nodes.getNodeAs<ForStmt>(LoopNameIterator))) {
981 FixerKind = LFK_Iterator;
982 } else if ((Loop = Nodes.getNodeAs<ForStmt>(LoopNameReverseIterator))) {
983 FixerKind = LFK_ReverseIterator;
984 } else {
985 Loop = Nodes.getNodeAs<ForStmt>(LoopNamePseudoArray);
986 assert(Loop && "Bad Callback. No for statement");
987 FixerKind = LFK_PseudoArray;
988 }
989
990 if (!isConvertible(Context, Nodes, Loop, FixerKind))
991 return;
992
993 const auto *LoopVar = Nodes.getNodeAs<VarDecl>(InitVarName);
994 const auto *EndVar = Nodes.getNodeAs<VarDecl>(EndVarName);
995
996 // If the loop calls end()/size() after each iteration, lower our confidence
997 // level.
998 if (FixerKind != LFK_Array && !EndVar)
999 ConfidenceLevel.lowerTo(Confidence::CL_Reasonable);
1000
1001 // If the end comparison isn't a variable, we can try to work with the
1002 // expression the loop variable is being tested against instead.
1003 const auto *EndCall = Nodes.getNodeAs<Expr>(EndCallName);
1004 const auto *BoundExpr = Nodes.getNodeAs<Expr>(ConditionBoundName);
1005
1006 // Find container expression of iterators and pseudoarrays, and determine if
1007 // this expression needs to be dereferenced to obtain the container.
1008 // With array loops, the container is often discovered during the
1009 // ForLoopIndexUseVisitor traversal.
1010 const Expr *ContainerExpr = nullptr;
1011 if (FixerKind == LFK_Iterator || FixerKind == LFK_ReverseIterator) {
1012 ContainerExpr = findContainer(
1013 Context, LoopVar->getInit(), EndVar ? EndVar->getInit() : EndCall,
1014 &Descriptor.ContainerNeedsDereference,
1015 /*IsReverse=*/FixerKind == LFK_ReverseIterator);
1016 } else if (FixerKind == LFK_PseudoArray) {
1017 std::optional<ContainerCall> Call = getContainerExpr(EndCall);
1018 if (Call) {
1019 ContainerExpr = Call->Container;
1020 Descriptor.ContainerNeedsDereference = Call->IsArrow;
1021 }
1022 }
1023
1024 // We must know the container or an array length bound.
1025 if (!ContainerExpr && !BoundExpr)
1026 return;
1027
1028 ForLoopIndexUseVisitor Finder(Context, LoopVar, EndVar, ContainerExpr,
1029 BoundExpr,
1030 Descriptor.ContainerNeedsDereference);
1031
1032 // Find expressions and variables on which the container depends.
1033 if (ContainerExpr) {
1034 ComponentFinderASTVisitor ComponentFinder;
1035 ComponentFinder.findExprComponents(ContainerExpr->IgnoreParenImpCasts());
1036 Finder.addComponents(ComponentFinder.getComponents());
1037 }
1038
1039 // Find usages of the loop index. If they are not used in a convertible way,
1040 // stop here.
1041 if (!Finder.findAndVerifyUsages(Loop->getBody()))
1042 return;
1043 ConfidenceLevel.lowerTo(Finder.getConfidenceLevel());
1044
1045 // Obtain the container expression, if we don't have it yet.
1046 if (FixerKind == LFK_Array) {
1047 ContainerExpr = Finder.getContainerIndexed()->IgnoreParenImpCasts();
1048
1049 // Very few loops are over expressions that generate arrays rather than
1050 // array variables. Consider loops over arrays that aren't just represented
1051 // by a variable to be risky conversions.
1052 if (!getReferencedVariable(ContainerExpr) &&
1053 !isDirectMemberExpr(ContainerExpr))
1054 ConfidenceLevel.lowerTo(Confidence::CL_Risky);
1055 }
1056
1057 // Find out which qualifiers we have to use in the loop range.
1058 const TraversalKindScope RAII(*Context, TK_AsIs);
1059 const UsageResult &Usages = Finder.getUsages();
1060 determineRangeDescriptor(Context, Nodes, Loop, FixerKind, ContainerExpr,
1061 Usages, Descriptor);
1062
1063 // Ensure that we do not try to move an expression dependent on a local
1064 // variable declared inside the loop outside of it.
1065 // FIXME: Determine when the external dependency isn't an expression converted
1066 // by another loop.
1067 TUInfo->getParentFinder().gatherAncestors(*Context);
1068 DependencyFinderASTVisitor DependencyFinder(
1069 &TUInfo->getParentFinder().getStmtToParentStmtMap(),
1070 &TUInfo->getParentFinder().getDeclToParentStmtMap(),
1071 &TUInfo->getReplacedVars(), Loop);
1072
1073 if (DependencyFinder.dependsOnInsideVariable(ContainerExpr) ||
1074 Descriptor.ContainerString.empty() || Usages.empty() ||
1075 ConfidenceLevel.getLevel() < MinConfidence)
1076 return;
1077
1078 doConversion(Context, LoopVar, getReferencedVariable(ContainerExpr), Usages,
1079 Finder.getAliasDecl(), Finder.aliasUseRequired(),
1080 Finder.aliasFromForInit(), Loop, Descriptor);
1081}
1082
1083llvm::StringRef LoopConvertCheck::getReverseFunction() const {
1084 if (!ReverseFunction.empty())
1085 return ReverseFunction;
1086 if (UseReverseRanges)
1087 return "std::ranges::reverse_view";
1088 return "";
1089}
1090
1091llvm::StringRef LoopConvertCheck::getReverseHeader() const {
1092 if (!ReverseHeader.empty())
1093 return ReverseHeader;
1094 if (UseReverseRanges && ReverseFunction.empty()) {
1095 return "<ranges>";
1096 }
1097 return "";
1098}
1099
1100} // namespace modernize
1101} // 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 clang::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 clang::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:1678
llvm::SmallVector< Usage, 8 > UsageResult
static const char EndCallName[]
static StringRef getStringFromRange(SourceManager &SourceMgr, const LangOptions &LangOpts, SourceRange Range)
Obtain the original source code text from a SourceRange.
static bool empty(SourceRange Range)
static const llvm::StringSet StdNames
static DeclarationMatcher initToZeroMatcher()
static StatementMatcher incrementVarMatcher()
static StatementMatcher makePseudoArrayLoopMatcher()
The matcher used for array-like containers (pseudoarrays).
static StatementMatcher arrayConditionMatcher(const internal::Matcher< Expr > &LimitExpr)
static const char DerefByValueResultName[]
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 const char LoopNamePseudoArray[]
static const char BeginCallName[]
static std::optional< ContainerCall > getContainerExpr(const Expr *Call)
static const char ConditionBoundName[]
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 StatementMatcher integerComparisonMatcher()
const Expr * digThroughConstructorsConversions(const Expr *E)
Look through conversion/copy constructors and member functions to find the explicit initialization ex...
static const char DerefByRefResultName[]
static bool containerIsConst(const Expr *ContainerExpr, bool Dereference)
Returns true if the container is const-qualified.
static const Expr * findContainer(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.
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 const char LoopNameIterator[]
static const char InitVarName[]
bool areSameExpr(ASTContext *Context, const Expr *First, const Expr *Second)
Returns true when two Exprs are equivalent.
static const char EndVarName[]
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 const char LoopNameReverseIterator[]
static const 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.
Some operations such as code completion produce a set of candidates.
Definition Generators.h:66
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.