Skip to content

Commit daad034

Browse files
committed
Merge from 'master' to 'sycl-web' (#57)
CONFLICT (content): Merge conflict in clang/lib/AST/DeclPrinter.cpp
2 parents 0c785d3 + c45fb35 commit daad034

File tree

285 files changed

+6241
-2876
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

285 files changed

+6241
-2876
lines changed

clang-tools-extra/clang-tidy/misc/CMakeLists.txt

+1
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ add_clang_library(clangTidyMiscModule
55
MiscTidyModule.cpp
66
MisplacedConstCheck.cpp
77
NewDeleteOverloadsCheck.cpp
8+
NoRecursionCheck.cpp
89
NonCopyableObjects.cpp
910
NonPrivateMemberVariablesInClassesCheck.cpp
1011
RedundantExpressionCheck.cpp

clang-tools-extra/clang-tidy/misc/MiscTidyModule.cpp

+2
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
#include "DefinitionsInHeadersCheck.h"
1313
#include "MisplacedConstCheck.h"
1414
#include "NewDeleteOverloadsCheck.h"
15+
#include "NoRecursionCheck.h"
1516
#include "NonCopyableObjects.h"
1617
#include "NonPrivateMemberVariablesInClassesCheck.h"
1718
#include "RedundantExpressionCheck.h"
@@ -35,6 +36,7 @@ class MiscModule : public ClangTidyModule {
3536
CheckFactories.registerCheck<MisplacedConstCheck>("misc-misplaced-const");
3637
CheckFactories.registerCheck<NewDeleteOverloadsCheck>(
3738
"misc-new-delete-overloads");
39+
CheckFactories.registerCheck<NoRecursionCheck>("misc-no-recursion");
3840
CheckFactories.registerCheck<NonCopyableObjectsCheck>(
3941
"misc-non-copyable-objects");
4042
CheckFactories.registerCheck<NonPrivateMemberVariablesInClassesCheck>(
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,276 @@
1+
//===--- NoRecursionCheck.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 "NoRecursionCheck.h"
10+
#include "clang/AST/ASTContext.h"
11+
#include "clang/ASTMatchers/ASTMatchFinder.h"
12+
#include "clang/Analysis/CallGraph.h"
13+
#include "llvm/ADT/DenseMapInfo.h"
14+
#include "llvm/ADT/SCCIterator.h"
15+
16+
using namespace clang::ast_matchers;
17+
18+
namespace clang {
19+
namespace tidy {
20+
namespace misc {
21+
22+
namespace {
23+
24+
/// Much like SmallSet, with two differences:
25+
/// 1. It can *only* be constructed from an ArrayRef<>. If the element count
26+
/// is small, there is no copy and said storage *must* outlive us.
27+
/// 2. it is immutable, the way it was constructed it will stay.
28+
template <typename T, unsigned SmallSize> class ImmutableSmallSet {
29+
ArrayRef<T> Vector;
30+
llvm::DenseSet<T> Set;
31+
32+
static_assert(SmallSize <= 32, "N should be small");
33+
34+
bool isSmall() const { return Set.empty(); }
35+
36+
public:
37+
using size_type = size_t;
38+
39+
ImmutableSmallSet() = delete;
40+
ImmutableSmallSet(const ImmutableSmallSet &) = delete;
41+
ImmutableSmallSet(ImmutableSmallSet &&) = delete;
42+
T &operator=(const ImmutableSmallSet &) = delete;
43+
T &operator=(ImmutableSmallSet &&) = delete;
44+
45+
// WARNING: Storage *must* outlive us if we decide that the size is small.
46+
ImmutableSmallSet(ArrayRef<T> Storage) {
47+
// Is size small-enough to just keep using the existing storage?
48+
if (Storage.size() <= SmallSize) {
49+
Vector = Storage;
50+
return;
51+
}
52+
53+
// We've decided that it isn't performant to keep using vector.
54+
// Let's migrate the data into Set.
55+
Set.reserve(Storage.size());
56+
Set.insert(Storage.begin(), Storage.end());
57+
}
58+
59+
/// count - Return 1 if the element is in the set, 0 otherwise.
60+
size_type count(const T &V) const {
61+
if (isSmall()) {
62+
// Since the collection is small, just do a linear search.
63+
return llvm::find(Vector, V) == Vector.end() ? 0 : 1;
64+
}
65+
66+
return Set.count(V);
67+
}
68+
};
69+
70+
/// Much like SmallSetVector, but with one difference:
71+
/// when the size is \p SmallSize or less, when checking whether an element is
72+
/// already in the set or not, we perform linear search over the vector,
73+
/// but if the size is larger than \p SmallSize, we look in set.
74+
/// FIXME: upstream this into SetVector/SmallSetVector itself.
75+
template <typename T, unsigned SmallSize> class SmartSmallSetVector {
76+
public:
77+
using size_type = size_t;
78+
79+
private:
80+
SmallVector<T, SmallSize> Vector;
81+
llvm::DenseSet<T> Set;
82+
83+
static_assert(SmallSize <= 32, "N should be small");
84+
85+
// Are we still using Vector for uniqness tracking?
86+
bool isSmall() const { return Set.empty(); }
87+
88+
// Will one more entry cause Vector to switch away from small-size storage?
89+
bool entiretyOfVectorSmallSizeIsOccupied() const {
90+
assert(isSmall() && Vector.size() <= SmallSize &&
91+
"Shouldn't ask if we have already [should have] migrated into Set.");
92+
return Vector.size() == SmallSize;
93+
}
94+
95+
void populateSet() {
96+
assert(Set.empty() && "Should not have already utilized the Set.");
97+
// Magical growth factor prediction - to how many elements do we expect to
98+
// sanely grow after switching away from small-size storage?
99+
const size_t NewMaxElts = 4 * Vector.size();
100+
Vector.reserve(NewMaxElts);
101+
Set.reserve(NewMaxElts);
102+
Set.insert(Vector.begin(), Vector.end());
103+
}
104+
105+
/// count - Return 1 if the element is in the set, 0 otherwise.
106+
size_type count(const T &V) const {
107+
if (isSmall()) {
108+
// Since the collection is small, just do a linear search.
109+
return llvm::find(Vector, V) == Vector.end() ? 0 : 1;
110+
}
111+
// Look-up in the Set.
112+
return Set.count(V);
113+
}
114+
115+
bool setInsert(const T &V) {
116+
if (count(V) != 0)
117+
return false; // Already exists.
118+
// Does not exist, Can/need to record it.
119+
if (isSmall()) { // Are we still using Vector for uniqness tracking?
120+
// Will one more entry fit within small-sized Vector?
121+
if (!entiretyOfVectorSmallSizeIsOccupied())
122+
return true; // We'll insert into vector right afterwards anyway.
123+
// Time to switch to Set.
124+
populateSet();
125+
}
126+
// Set time!
127+
// Note that this must be after `populateSet()` might have been called.
128+
bool SetInsertionSucceeded = Set.insert(V).second;
129+
(void)SetInsertionSucceeded;
130+
assert(SetInsertionSucceeded && "We did check that no such value existed");
131+
return true;
132+
}
133+
134+
public:
135+
/// Insert a new element into the SmartSmallSetVector.
136+
/// \returns true if the element was inserted into the SmartSmallSetVector.
137+
bool insert(const T &X) {
138+
bool result = setInsert(X);
139+
if (result)
140+
Vector.push_back(X);
141+
return result;
142+
}
143+
144+
/// Clear the SmartSmallSetVector and return the underlying vector.
145+
decltype(Vector) takeVector() {
146+
Set.clear();
147+
return std::move(Vector);
148+
}
149+
};
150+
151+
constexpr unsigned SmallCallStackSize = 16;
152+
constexpr unsigned SmallSCCSize = 32;
153+
154+
using CallStackTy =
155+
llvm::SmallVector<CallGraphNode::CallRecord, SmallCallStackSize>;
156+
157+
// In given SCC, find *some* call stack that will be cyclic.
158+
// This will only find *one* such stack, it might not be the smallest one,
159+
// and there may be other loops.
160+
CallStackTy PathfindSomeCycle(ArrayRef<CallGraphNode *> SCC) {
161+
// We'll need to be able to performantly look up whether some CallGraphNode
162+
// is in SCC or not, so cache all the SCC elements in a set.
163+
const ImmutableSmallSet<CallGraphNode *, SmallSCCSize> SCCElts(SCC);
164+
165+
// Is node N part if the current SCC?
166+
auto NodeIsPartOfSCC = [&SCCElts](CallGraphNode *N) {
167+
return SCCElts.count(N) != 0;
168+
};
169+
170+
// Track the call stack that will cause a cycle.
171+
SmartSmallSetVector<CallGraphNode::CallRecord, SmallCallStackSize>
172+
CallStackSet;
173+
174+
// Arbitrairly take the first element of SCC as entry point.
175+
CallGraphNode::CallRecord EntryNode(SCC.front(), /*CallExpr=*/nullptr);
176+
// Continue recursing into subsequent callees that are part of this SCC,
177+
// and are thus known to be part of the call graph loop, until loop forms.
178+
CallGraphNode::CallRecord *Node = &EntryNode;
179+
while (true) {
180+
// Did we see this node before?
181+
if (!CallStackSet.insert(*Node))
182+
break; // Cycle completed! Note that didn't insert the node into stack!
183+
// Else, perform depth-first traversal: out of all callees, pick first one
184+
// that is part of this SCC. This is not guaranteed to yield shortest cycle.
185+
Node = llvm::find_if(Node->Callee->callees(), NodeIsPartOfSCC);
186+
}
187+
188+
// Note that we failed to insert the last node, that completes the cycle.
189+
// But we really want to have it. So insert it manually into stack only.
190+
CallStackTy CallStack = CallStackSet.takeVector();
191+
CallStack.emplace_back(*Node);
192+
193+
return CallStack;
194+
}
195+
196+
} // namespace
197+
198+
void NoRecursionCheck::registerMatchers(MatchFinder *Finder) {
199+
Finder->addMatcher(translationUnitDecl().bind("TUDecl"), this);
200+
}
201+
202+
void NoRecursionCheck::handleSCC(ArrayRef<CallGraphNode *> SCC) {
203+
assert(!SCC.empty() && "Empty SCC does not make sense.");
204+
205+
// First of all, call out every stongly connected function.
206+
for (CallGraphNode *N : SCC) {
207+
Decl *D = N->getDecl();
208+
diag(D->getLocation(), "function %0 is within a recursive call chain")
209+
<< cast<NamedDecl>(D);
210+
}
211+
212+
// Now, SCC only tells us about strongly connected function declarations in
213+
// the call graph. It doesn't *really* tell us about the cycles they form.
214+
// And there may be more than one cycle in SCC.
215+
// So let's form a call stack that eventually exposes *some* cycle.
216+
const CallStackTy EventuallyCyclicCallStack = PathfindSomeCycle(SCC);
217+
assert(!EventuallyCyclicCallStack.empty() && "We should've found the cycle");
218+
219+
// While last node of the call stack does cause a loop, due to the way we
220+
// pathfind the cycle, the loop does not nessesairly begin at the first node
221+
// of the call stack, so drop front nodes of the call stack until it does.
222+
const auto CyclicCallStack =
223+
ArrayRef<CallGraphNode::CallRecord>(EventuallyCyclicCallStack)
224+
.drop_until([LastNode = EventuallyCyclicCallStack.back()](
225+
CallGraphNode::CallRecord FrontNode) {
226+
return FrontNode == LastNode;
227+
});
228+
assert(CyclicCallStack.size() >= 2 && "Cycle requires at least 2 frames");
229+
230+
// Which function we decided to be the entry point that lead to the recursion?
231+
Decl *CycleEntryFn = CyclicCallStack.front().Callee->getDecl();
232+
// And now, for ease of understanding, let's print the call sequence that
233+
// forms the cycle in question.
234+
diag(CycleEntryFn->getLocation(),
235+
"example recursive call chain, starting from function %0",
236+
DiagnosticIDs::Note)
237+
<< cast<NamedDecl>(CycleEntryFn);
238+
for (int CurFrame = 1, NumFrames = CyclicCallStack.size();
239+
CurFrame != NumFrames; ++CurFrame) {
240+
CallGraphNode::CallRecord PrevNode = CyclicCallStack[CurFrame - 1];
241+
CallGraphNode::CallRecord CurrNode = CyclicCallStack[CurFrame];
242+
243+
Decl *PrevDecl = PrevNode.Callee->getDecl();
244+
Decl *CurrDecl = CurrNode.Callee->getDecl();
245+
246+
diag(CurrNode.CallExpr->getBeginLoc(),
247+
"Frame #%0: function %1 calls function %2 here:", DiagnosticIDs::Note)
248+
<< CurFrame << cast<NamedDecl>(PrevDecl) << cast<NamedDecl>(CurrDecl);
249+
}
250+
251+
diag(CyclicCallStack.back().CallExpr->getBeginLoc(),
252+
"... which was the starting point of the recursive call chain; there "
253+
"may be other cycles",
254+
DiagnosticIDs::Note);
255+
}
256+
257+
void NoRecursionCheck::check(const MatchFinder::MatchResult &Result) {
258+
// Build call graph for the entire translation unit.
259+
const auto *TU = Result.Nodes.getNodeAs<TranslationUnitDecl>("TUDecl");
260+
CallGraph CG;
261+
CG.addToCallGraph(const_cast<TranslationUnitDecl *>(TU));
262+
263+
// Look for cycles in call graph,
264+
// by looking for Strongly Connected Comonents (SCC's)
265+
for (llvm::scc_iterator<CallGraph *> SCCI = llvm::scc_begin(&CG),
266+
SCCE = llvm::scc_end(&CG);
267+
SCCI != SCCE; ++SCCI) {
268+
if (!SCCI.hasLoop()) // We only care about cycles, not standalone nodes.
269+
continue;
270+
handleSCC(*SCCI);
271+
}
272+
}
273+
274+
} // namespace misc
275+
} // namespace tidy
276+
} // namespace clang
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
//===--- NoRecursionCheck.h - clang-tidy ------------------------*- C++ -*-===//
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+
#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_MISC_NORECURSIONCHECK_H
10+
#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_MISC_NORECURSIONCHECK_H
11+
12+
#include "../ClangTidyCheck.h"
13+
14+
namespace clang {
15+
16+
class CallGraphNode;
17+
18+
namespace tidy {
19+
namespace misc {
20+
21+
/// Finds strongly connected functions (by analyzing call graph for SCC's
22+
/// that are loops), diagnoses each function in the cycle,
23+
/// and displays one example of possible call graph loop (recursion).
24+
///
25+
/// For the user-facing documentation see:
26+
/// http://clang.llvm.org/extra/clang-tidy/checks/misc-no-recursion.html
27+
class NoRecursionCheck : public ClangTidyCheck {
28+
public:
29+
NoRecursionCheck(StringRef Name, ClangTidyContext *Context)
30+
: ClangTidyCheck(Name, Context) {}
31+
void registerMatchers(ast_matchers::MatchFinder *Finder) override;
32+
void check(const ast_matchers::MatchFinder::MatchResult &Result) override;
33+
34+
private:
35+
void handleSCC(ArrayRef<CallGraphNode *> SCC);
36+
};
37+
38+
} // namespace misc
39+
} // namespace tidy
40+
} // namespace clang
41+
42+
#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_MISC_NORECURSIONCHECK_H

clang-tools-extra/clangd/unittests/FindTargetTests.cpp

+3-6
Original file line numberDiff line numberDiff line change
@@ -215,8 +215,7 @@ TEST_F(TargetDeclTest, NestedNameSpecifier) {
215215
template <typename T>
216216
int x = [[T::]]y;
217217
)cpp";
218-
// FIXME: We don't do a good job printing TemplateTypeParmDecls, apparently!
219-
EXPECT_DECLS("NestedNameSpecifierLoc", "");
218+
EXPECT_DECLS("NestedNameSpecifierLoc", "typename T");
220219

221220
Code = R"cpp(
222221
namespace a { int x; }
@@ -256,8 +255,7 @@ TEST_F(TargetDeclTest, Types) {
256255
template<class T>
257256
void foo() { [[T]] x; }
258257
)cpp";
259-
// FIXME: We don't do a good job printing TemplateTypeParmDecls, apparently!
260-
EXPECT_DECLS("TemplateTypeParmTypeLoc", "");
258+
EXPECT_DECLS("TemplateTypeParmTypeLoc", "class T");
261259
Flags.clear();
262260

263261
// FIXME: Auto-completion in a template requires disabling delayed template
@@ -290,8 +288,7 @@ TEST_F(TargetDeclTest, Types) {
290288
static const int size = sizeof...([[E]]);
291289
};
292290
)cpp";
293-
// FIXME: We don't do a good job printing TemplateTypeParmDecls, apparently!
294-
EXPECT_DECLS("SizeOfPackExpr", "");
291+
EXPECT_DECLS("SizeOfPackExpr", "typename ...E");
295292

296293
Code = R"cpp(
297294
template <typename T>

clang-tools-extra/docs/ReleaseNotes.rst

+5
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,11 @@ New checks
9393

9494
Finds implementations of -dealloc in Objective-C categories.
9595

96+
- New :doc:`misc-no-recursion
97+
<clang-tidy/checks/misc-no-recursion>` check.
98+
99+
Finds recursive functions and diagnoses them.
100+
96101
New check aliases
97102
^^^^^^^^^^^^^^^^^
98103

clang-tools-extra/docs/clang-tidy/checks/list.rst

+1
Original file line numberDiff line numberDiff line change
@@ -189,6 +189,7 @@ Clang-Tidy Checks
189189
`misc-definitions-in-headers <misc-definitions-in-headers.html>`_, "Yes"
190190
`misc-misplaced-const <misc-misplaced-const.html>`_,
191191
`misc-new-delete-overloads <misc-new-delete-overloads.html>`_,
192+
`misc-no-recursion <misc-no-recursion>`_,
192193
`misc-non-copyable-objects <misc-non-copyable-objects.html>`_,
193194
`misc-non-private-member-variables-in-classes <misc-non-private-member-variables-in-classes.html>`_,
194195
`misc-redundant-expression <misc-redundant-expression.html>`_, "Yes"

0 commit comments

Comments
 (0)