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