10b57cec5SDimitry Andric //===--- CloneDetection.cpp - Finds code clones in an AST -------*- C++ -*-===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric ///
90b57cec5SDimitry Andric /// This file implements classes for searching and analyzing source code clones.
100b57cec5SDimitry Andric ///
110b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
120b57cec5SDimitry Andric
130b57cec5SDimitry Andric #include "clang/Analysis/CloneDetection.h"
14480093f4SDimitry Andric #include "clang/AST/Attr.h"
150b57cec5SDimitry Andric #include "clang/AST/DataCollection.h"
160b57cec5SDimitry Andric #include "clang/AST/DeclTemplate.h"
175ffd83dbSDimitry Andric #include "clang/Basic/SourceManager.h"
180b57cec5SDimitry Andric #include "llvm/Support/MD5.h"
190b57cec5SDimitry Andric #include "llvm/Support/Path.h"
200b57cec5SDimitry Andric
210b57cec5SDimitry Andric using namespace clang;
220b57cec5SDimitry Andric
StmtSequence(const CompoundStmt * Stmt,const Decl * D,unsigned StartIndex,unsigned EndIndex)230b57cec5SDimitry Andric StmtSequence::StmtSequence(const CompoundStmt *Stmt, const Decl *D,
240b57cec5SDimitry Andric unsigned StartIndex, unsigned EndIndex)
250b57cec5SDimitry Andric : S(Stmt), D(D), StartIndex(StartIndex), EndIndex(EndIndex) {
260b57cec5SDimitry Andric assert(Stmt && "Stmt must not be a nullptr");
270b57cec5SDimitry Andric assert(StartIndex < EndIndex && "Given array should not be empty");
280b57cec5SDimitry Andric assert(EndIndex <= Stmt->size() && "Given array too big for this Stmt");
290b57cec5SDimitry Andric }
300b57cec5SDimitry Andric
StmtSequence(const Stmt * Stmt,const Decl * D)310b57cec5SDimitry Andric StmtSequence::StmtSequence(const Stmt *Stmt, const Decl *D)
320b57cec5SDimitry Andric : S(Stmt), D(D), StartIndex(0), EndIndex(0) {}
330b57cec5SDimitry Andric
StmtSequence()340b57cec5SDimitry Andric StmtSequence::StmtSequence()
350b57cec5SDimitry Andric : S(nullptr), D(nullptr), StartIndex(0), EndIndex(0) {}
360b57cec5SDimitry Andric
contains(const StmtSequence & Other) const370b57cec5SDimitry Andric bool StmtSequence::contains(const StmtSequence &Other) const {
380b57cec5SDimitry Andric // If both sequences reside in different declarations, they can never contain
390b57cec5SDimitry Andric // each other.
400b57cec5SDimitry Andric if (D != Other.D)
410b57cec5SDimitry Andric return false;
420b57cec5SDimitry Andric
430b57cec5SDimitry Andric const SourceManager &SM = getASTContext().getSourceManager();
440b57cec5SDimitry Andric
450b57cec5SDimitry Andric // Otherwise check if the start and end locations of the current sequence
460b57cec5SDimitry Andric // surround the other sequence.
470b57cec5SDimitry Andric bool StartIsInBounds =
480b57cec5SDimitry Andric SM.isBeforeInTranslationUnit(getBeginLoc(), Other.getBeginLoc()) ||
490b57cec5SDimitry Andric getBeginLoc() == Other.getBeginLoc();
500b57cec5SDimitry Andric if (!StartIsInBounds)
510b57cec5SDimitry Andric return false;
520b57cec5SDimitry Andric
530b57cec5SDimitry Andric bool EndIsInBounds =
540b57cec5SDimitry Andric SM.isBeforeInTranslationUnit(Other.getEndLoc(), getEndLoc()) ||
550b57cec5SDimitry Andric Other.getEndLoc() == getEndLoc();
560b57cec5SDimitry Andric return EndIsInBounds;
570b57cec5SDimitry Andric }
580b57cec5SDimitry Andric
begin() const590b57cec5SDimitry Andric StmtSequence::iterator StmtSequence::begin() const {
600b57cec5SDimitry Andric if (!holdsSequence()) {
610b57cec5SDimitry Andric return &S;
620b57cec5SDimitry Andric }
630b57cec5SDimitry Andric auto CS = cast<CompoundStmt>(S);
640b57cec5SDimitry Andric return CS->body_begin() + StartIndex;
650b57cec5SDimitry Andric }
660b57cec5SDimitry Andric
end() const670b57cec5SDimitry Andric StmtSequence::iterator StmtSequence::end() const {
680b57cec5SDimitry Andric if (!holdsSequence()) {
690b57cec5SDimitry Andric return reinterpret_cast<StmtSequence::iterator>(&S) + 1;
700b57cec5SDimitry Andric }
710b57cec5SDimitry Andric auto CS = cast<CompoundStmt>(S);
720b57cec5SDimitry Andric return CS->body_begin() + EndIndex;
730b57cec5SDimitry Andric }
740b57cec5SDimitry Andric
getASTContext() const750b57cec5SDimitry Andric ASTContext &StmtSequence::getASTContext() const {
760b57cec5SDimitry Andric assert(D);
770b57cec5SDimitry Andric return D->getASTContext();
780b57cec5SDimitry Andric }
790b57cec5SDimitry Andric
getBeginLoc() const800b57cec5SDimitry Andric SourceLocation StmtSequence::getBeginLoc() const {
810b57cec5SDimitry Andric return front()->getBeginLoc();
820b57cec5SDimitry Andric }
830b57cec5SDimitry Andric
getEndLoc() const840b57cec5SDimitry Andric SourceLocation StmtSequence::getEndLoc() const { return back()->getEndLoc(); }
850b57cec5SDimitry Andric
getSourceRange() const860b57cec5SDimitry Andric SourceRange StmtSequence::getSourceRange() const {
870b57cec5SDimitry Andric return SourceRange(getBeginLoc(), getEndLoc());
880b57cec5SDimitry Andric }
890b57cec5SDimitry Andric
analyzeCodeBody(const Decl * D)900b57cec5SDimitry Andric void CloneDetector::analyzeCodeBody(const Decl *D) {
910b57cec5SDimitry Andric assert(D);
920b57cec5SDimitry Andric assert(D->hasBody());
930b57cec5SDimitry Andric
940b57cec5SDimitry Andric Sequences.push_back(StmtSequence(D->getBody(), D));
950b57cec5SDimitry Andric }
960b57cec5SDimitry Andric
970b57cec5SDimitry Andric /// Returns true if and only if \p Stmt contains at least one other
980b57cec5SDimitry Andric /// sequence in the \p Group.
containsAnyInGroup(StmtSequence & Seq,CloneDetector::CloneGroup & Group)990b57cec5SDimitry Andric static bool containsAnyInGroup(StmtSequence &Seq,
1000b57cec5SDimitry Andric CloneDetector::CloneGroup &Group) {
1010b57cec5SDimitry Andric for (StmtSequence &GroupSeq : Group) {
1020b57cec5SDimitry Andric if (Seq.contains(GroupSeq))
1030b57cec5SDimitry Andric return true;
1040b57cec5SDimitry Andric }
1050b57cec5SDimitry Andric return false;
1060b57cec5SDimitry Andric }
1070b57cec5SDimitry Andric
1080b57cec5SDimitry Andric /// Returns true if and only if all sequences in \p OtherGroup are
1090b57cec5SDimitry Andric /// contained by a sequence in \p Group.
containsGroup(CloneDetector::CloneGroup & Group,CloneDetector::CloneGroup & OtherGroup)1100b57cec5SDimitry Andric static bool containsGroup(CloneDetector::CloneGroup &Group,
1110b57cec5SDimitry Andric CloneDetector::CloneGroup &OtherGroup) {
1120b57cec5SDimitry Andric // We have less sequences in the current group than we have in the other,
1130b57cec5SDimitry Andric // so we will never fulfill the requirement for returning true. This is only
1140b57cec5SDimitry Andric // possible because we know that a sequence in Group can contain at most
1150b57cec5SDimitry Andric // one sequence in OtherGroup.
1160b57cec5SDimitry Andric if (Group.size() < OtherGroup.size())
1170b57cec5SDimitry Andric return false;
1180b57cec5SDimitry Andric
1190b57cec5SDimitry Andric for (StmtSequence &Stmt : Group) {
1200b57cec5SDimitry Andric if (!containsAnyInGroup(Stmt, OtherGroup))
1210b57cec5SDimitry Andric return false;
1220b57cec5SDimitry Andric }
1230b57cec5SDimitry Andric return true;
1240b57cec5SDimitry Andric }
1250b57cec5SDimitry Andric
constrain(std::vector<CloneDetector::CloneGroup> & Result)1260b57cec5SDimitry Andric void OnlyLargestCloneConstraint::constrain(
1270b57cec5SDimitry Andric std::vector<CloneDetector::CloneGroup> &Result) {
1280b57cec5SDimitry Andric std::vector<unsigned> IndexesToRemove;
1290b57cec5SDimitry Andric
1300b57cec5SDimitry Andric // Compare every group in the result with the rest. If one groups contains
1310b57cec5SDimitry Andric // another group, we only need to return the bigger group.
1320b57cec5SDimitry Andric // Note: This doesn't scale well, so if possible avoid calling any heavy
1330b57cec5SDimitry Andric // function from this loop to minimize the performance impact.
1340b57cec5SDimitry Andric for (unsigned i = 0; i < Result.size(); ++i) {
1350b57cec5SDimitry Andric for (unsigned j = 0; j < Result.size(); ++j) {
1360b57cec5SDimitry Andric // Don't compare a group with itself.
1370b57cec5SDimitry Andric if (i == j)
1380b57cec5SDimitry Andric continue;
1390b57cec5SDimitry Andric
1400b57cec5SDimitry Andric if (containsGroup(Result[j], Result[i])) {
1410b57cec5SDimitry Andric IndexesToRemove.push_back(i);
1420b57cec5SDimitry Andric break;
1430b57cec5SDimitry Andric }
1440b57cec5SDimitry Andric }
1450b57cec5SDimitry Andric }
1460b57cec5SDimitry Andric
1470b57cec5SDimitry Andric // Erasing a list of indexes from the vector should be done with decreasing
1480b57cec5SDimitry Andric // indexes. As IndexesToRemove is constructed with increasing values, we just
1490b57cec5SDimitry Andric // reverse iterate over it to get the desired order.
150*349cc55cSDimitry Andric for (unsigned I : llvm::reverse(IndexesToRemove))
151*349cc55cSDimitry Andric Result.erase(Result.begin() + I);
1520b57cec5SDimitry Andric }
1530b57cec5SDimitry Andric
isAutoGenerated(const CloneDetector::CloneGroup & Group)1540b57cec5SDimitry Andric bool FilenamePatternConstraint::isAutoGenerated(
1550b57cec5SDimitry Andric const CloneDetector::CloneGroup &Group) {
1560b57cec5SDimitry Andric if (IgnoredFilesPattern.empty() || Group.empty() ||
157a7dea167SDimitry Andric !IgnoredFilesRegex->isValid())
1580b57cec5SDimitry Andric return false;
1590b57cec5SDimitry Andric
1600b57cec5SDimitry Andric for (const StmtSequence &S : Group) {
1610b57cec5SDimitry Andric const SourceManager &SM = S.getASTContext().getSourceManager();
1620b57cec5SDimitry Andric StringRef Filename = llvm::sys::path::filename(
1630b57cec5SDimitry Andric SM.getFilename(S.getContainingDecl()->getLocation()));
1640b57cec5SDimitry Andric if (IgnoredFilesRegex->match(Filename))
1650b57cec5SDimitry Andric return true;
1660b57cec5SDimitry Andric }
1670b57cec5SDimitry Andric
1680b57cec5SDimitry Andric return false;
1690b57cec5SDimitry Andric }
1700b57cec5SDimitry Andric
1710b57cec5SDimitry Andric /// This class defines what a type II code clone is: If it collects for two
1720b57cec5SDimitry Andric /// statements the same data, then those two statements are considered to be
1730b57cec5SDimitry Andric /// clones of each other.
1740b57cec5SDimitry Andric ///
1750b57cec5SDimitry Andric /// All collected data is forwarded to the given data consumer of the type T.
1760b57cec5SDimitry Andric /// The data consumer class needs to provide a member method with the signature:
1770b57cec5SDimitry Andric /// update(StringRef Str)
1780b57cec5SDimitry Andric namespace {
1790b57cec5SDimitry Andric template <class T>
1800b57cec5SDimitry Andric class CloneTypeIIStmtDataCollector
1810b57cec5SDimitry Andric : public ConstStmtVisitor<CloneTypeIIStmtDataCollector<T>> {
1820b57cec5SDimitry Andric ASTContext &Context;
1830b57cec5SDimitry Andric /// The data sink to which all data is forwarded.
1840b57cec5SDimitry Andric T &DataConsumer;
1850b57cec5SDimitry Andric
addData(const Ty & Data)1860b57cec5SDimitry Andric template <class Ty> void addData(const Ty &Data) {
1870b57cec5SDimitry Andric data_collection::addDataToConsumer(DataConsumer, Data);
1880b57cec5SDimitry Andric }
1890b57cec5SDimitry Andric
1900b57cec5SDimitry Andric public:
CloneTypeIIStmtDataCollector(const Stmt * S,ASTContext & Context,T & DataConsumer)1910b57cec5SDimitry Andric CloneTypeIIStmtDataCollector(const Stmt *S, ASTContext &Context,
1920b57cec5SDimitry Andric T &DataConsumer)
1930b57cec5SDimitry Andric : Context(Context), DataConsumer(DataConsumer) {
1940b57cec5SDimitry Andric this->Visit(S);
1950b57cec5SDimitry Andric }
1960b57cec5SDimitry Andric
1970b57cec5SDimitry Andric // Define a visit method for each class to collect data and subsequently visit
1980b57cec5SDimitry Andric // all parent classes. This uses a template so that custom visit methods by us
1990b57cec5SDimitry Andric // take precedence.
2000b57cec5SDimitry Andric #define DEF_ADD_DATA(CLASS, CODE) \
2010b57cec5SDimitry Andric template <class = void> void Visit##CLASS(const CLASS *S) { \
2020b57cec5SDimitry Andric CODE; \
2030b57cec5SDimitry Andric ConstStmtVisitor<CloneTypeIIStmtDataCollector<T>>::Visit##CLASS(S); \
2040b57cec5SDimitry Andric }
2050b57cec5SDimitry Andric
2060b57cec5SDimitry Andric #include "clang/AST/StmtDataCollectors.inc"
2070b57cec5SDimitry Andric
2080b57cec5SDimitry Andric // Type II clones ignore variable names and literals, so let's skip them.
2090b57cec5SDimitry Andric #define SKIP(CLASS) \
2100b57cec5SDimitry Andric void Visit##CLASS(const CLASS *S) { \
2110b57cec5SDimitry Andric ConstStmtVisitor<CloneTypeIIStmtDataCollector<T>>::Visit##CLASS(S); \
2120b57cec5SDimitry Andric }
2130b57cec5SDimitry Andric SKIP(DeclRefExpr)
2140b57cec5SDimitry Andric SKIP(MemberExpr)
2150b57cec5SDimitry Andric SKIP(IntegerLiteral)
2160b57cec5SDimitry Andric SKIP(FloatingLiteral)
2170b57cec5SDimitry Andric SKIP(StringLiteral)
2180b57cec5SDimitry Andric SKIP(CXXBoolLiteralExpr)
2190b57cec5SDimitry Andric SKIP(CharacterLiteral)
2200b57cec5SDimitry Andric #undef SKIP
2210b57cec5SDimitry Andric };
2220b57cec5SDimitry Andric } // end anonymous namespace
2230b57cec5SDimitry Andric
createHash(llvm::MD5 & Hash)2240b57cec5SDimitry Andric static size_t createHash(llvm::MD5 &Hash) {
2250b57cec5SDimitry Andric size_t HashCode;
2260b57cec5SDimitry Andric
2270b57cec5SDimitry Andric // Create the final hash code for the current Stmt.
2280b57cec5SDimitry Andric llvm::MD5::MD5Result HashResult;
2290b57cec5SDimitry Andric Hash.final(HashResult);
2300b57cec5SDimitry Andric
2310b57cec5SDimitry Andric // Copy as much as possible of the generated hash code to the Stmt's hash
2320b57cec5SDimitry Andric // code.
2330b57cec5SDimitry Andric std::memcpy(&HashCode, &HashResult,
2340b57cec5SDimitry Andric std::min(sizeof(HashCode), sizeof(HashResult)));
2350b57cec5SDimitry Andric
2360b57cec5SDimitry Andric return HashCode;
2370b57cec5SDimitry Andric }
2380b57cec5SDimitry Andric
2390b57cec5SDimitry Andric /// Generates and saves a hash code for the given Stmt.
2400b57cec5SDimitry Andric /// \param S The given Stmt.
2410b57cec5SDimitry Andric /// \param D The Decl containing S.
2420b57cec5SDimitry Andric /// \param StmtsByHash Output parameter that will contain the hash codes for
2430b57cec5SDimitry Andric /// each StmtSequence in the given Stmt.
2440b57cec5SDimitry Andric /// \return The hash code of the given Stmt.
2450b57cec5SDimitry Andric ///
2460b57cec5SDimitry Andric /// If the given Stmt is a CompoundStmt, this method will also generate
2470b57cec5SDimitry Andric /// hashes for all possible StmtSequences in the children of this Stmt.
2480b57cec5SDimitry Andric static size_t
saveHash(const Stmt * S,const Decl * D,std::vector<std::pair<size_t,StmtSequence>> & StmtsByHash)2490b57cec5SDimitry Andric saveHash(const Stmt *S, const Decl *D,
2500b57cec5SDimitry Andric std::vector<std::pair<size_t, StmtSequence>> &StmtsByHash) {
2510b57cec5SDimitry Andric llvm::MD5 Hash;
2520b57cec5SDimitry Andric ASTContext &Context = D->getASTContext();
2530b57cec5SDimitry Andric
2540b57cec5SDimitry Andric CloneTypeIIStmtDataCollector<llvm::MD5>(S, Context, Hash);
2550b57cec5SDimitry Andric
2560b57cec5SDimitry Andric auto CS = dyn_cast<CompoundStmt>(S);
2570b57cec5SDimitry Andric SmallVector<size_t, 8> ChildHashes;
2580b57cec5SDimitry Andric
2590b57cec5SDimitry Andric for (const Stmt *Child : S->children()) {
2600b57cec5SDimitry Andric if (Child == nullptr) {
2610b57cec5SDimitry Andric ChildHashes.push_back(0);
2620b57cec5SDimitry Andric continue;
2630b57cec5SDimitry Andric }
2640b57cec5SDimitry Andric size_t ChildHash = saveHash(Child, D, StmtsByHash);
2650b57cec5SDimitry Andric Hash.update(
2660b57cec5SDimitry Andric StringRef(reinterpret_cast<char *>(&ChildHash), sizeof(ChildHash)));
2670b57cec5SDimitry Andric ChildHashes.push_back(ChildHash);
2680b57cec5SDimitry Andric }
2690b57cec5SDimitry Andric
2700b57cec5SDimitry Andric if (CS) {
2710b57cec5SDimitry Andric // If we're in a CompoundStmt, we hash all possible combinations of child
2720b57cec5SDimitry Andric // statements to find clones in those subsequences.
2730b57cec5SDimitry Andric // We first go through every possible starting position of a subsequence.
2740b57cec5SDimitry Andric for (unsigned Pos = 0; Pos < CS->size(); ++Pos) {
2750b57cec5SDimitry Andric // Then we try all possible lengths this subsequence could have and
2760b57cec5SDimitry Andric // reuse the same hash object to make sure we only hash every child
2770b57cec5SDimitry Andric // hash exactly once.
2780b57cec5SDimitry Andric llvm::MD5 Hash;
2790b57cec5SDimitry Andric for (unsigned Length = 1; Length <= CS->size() - Pos; ++Length) {
2800b57cec5SDimitry Andric // Grab the current child hash and put it into our hash. We do
2810b57cec5SDimitry Andric // -1 on the index because we start counting the length at 1.
2820b57cec5SDimitry Andric size_t ChildHash = ChildHashes[Pos + Length - 1];
2830b57cec5SDimitry Andric Hash.update(
2840b57cec5SDimitry Andric StringRef(reinterpret_cast<char *>(&ChildHash), sizeof(ChildHash)));
2850b57cec5SDimitry Andric // If we have at least two elements in our subsequence, we can start
2860b57cec5SDimitry Andric // saving it.
2870b57cec5SDimitry Andric if (Length > 1) {
2880b57cec5SDimitry Andric llvm::MD5 SubHash = Hash;
2890b57cec5SDimitry Andric StmtsByHash.push_back(std::make_pair(
2900b57cec5SDimitry Andric createHash(SubHash), StmtSequence(CS, D, Pos, Pos + Length)));
2910b57cec5SDimitry Andric }
2920b57cec5SDimitry Andric }
2930b57cec5SDimitry Andric }
2940b57cec5SDimitry Andric }
2950b57cec5SDimitry Andric
2960b57cec5SDimitry Andric size_t HashCode = createHash(Hash);
2970b57cec5SDimitry Andric StmtsByHash.push_back(std::make_pair(HashCode, StmtSequence(S, D)));
2980b57cec5SDimitry Andric return HashCode;
2990b57cec5SDimitry Andric }
3000b57cec5SDimitry Andric
3010b57cec5SDimitry Andric namespace {
3020b57cec5SDimitry Andric /// Wrapper around FoldingSetNodeID that it can be used as the template
3030b57cec5SDimitry Andric /// argument of the StmtDataCollector.
3040b57cec5SDimitry Andric class FoldingSetNodeIDWrapper {
3050b57cec5SDimitry Andric
3060b57cec5SDimitry Andric llvm::FoldingSetNodeID &FS;
3070b57cec5SDimitry Andric
3080b57cec5SDimitry Andric public:
FoldingSetNodeIDWrapper(llvm::FoldingSetNodeID & FS)3090b57cec5SDimitry Andric FoldingSetNodeIDWrapper(llvm::FoldingSetNodeID &FS) : FS(FS) {}
3100b57cec5SDimitry Andric
update(StringRef Str)3110b57cec5SDimitry Andric void update(StringRef Str) { FS.AddString(Str); }
3120b57cec5SDimitry Andric };
3130b57cec5SDimitry Andric } // end anonymous namespace
3140b57cec5SDimitry Andric
3150b57cec5SDimitry Andric /// Writes the relevant data from all statements and child statements
3160b57cec5SDimitry Andric /// in the given StmtSequence into the given FoldingSetNodeID.
CollectStmtSequenceData(const StmtSequence & Sequence,FoldingSetNodeIDWrapper & OutputData)3170b57cec5SDimitry Andric static void CollectStmtSequenceData(const StmtSequence &Sequence,
3180b57cec5SDimitry Andric FoldingSetNodeIDWrapper &OutputData) {
3190b57cec5SDimitry Andric for (const Stmt *S : Sequence) {
3200b57cec5SDimitry Andric CloneTypeIIStmtDataCollector<FoldingSetNodeIDWrapper>(
3210b57cec5SDimitry Andric S, Sequence.getASTContext(), OutputData);
3220b57cec5SDimitry Andric
3230b57cec5SDimitry Andric for (const Stmt *Child : S->children()) {
3240b57cec5SDimitry Andric if (!Child)
3250b57cec5SDimitry Andric continue;
3260b57cec5SDimitry Andric
3270b57cec5SDimitry Andric CollectStmtSequenceData(StmtSequence(Child, Sequence.getContainingDecl()),
3280b57cec5SDimitry Andric OutputData);
3290b57cec5SDimitry Andric }
3300b57cec5SDimitry Andric }
3310b57cec5SDimitry Andric }
3320b57cec5SDimitry Andric
3330b57cec5SDimitry Andric /// Returns true if both sequences are clones of each other.
areSequencesClones(const StmtSequence & LHS,const StmtSequence & RHS)3340b57cec5SDimitry Andric static bool areSequencesClones(const StmtSequence &LHS,
3350b57cec5SDimitry Andric const StmtSequence &RHS) {
3360b57cec5SDimitry Andric // We collect the data from all statements in the sequence as we did before
3370b57cec5SDimitry Andric // when generating a hash value for each sequence. But this time we don't
3380b57cec5SDimitry Andric // hash the collected data and compare the whole data set instead. This
3390b57cec5SDimitry Andric // prevents any false-positives due to hash code collisions.
3400b57cec5SDimitry Andric llvm::FoldingSetNodeID DataLHS, DataRHS;
3410b57cec5SDimitry Andric FoldingSetNodeIDWrapper LHSWrapper(DataLHS);
3420b57cec5SDimitry Andric FoldingSetNodeIDWrapper RHSWrapper(DataRHS);
3430b57cec5SDimitry Andric
3440b57cec5SDimitry Andric CollectStmtSequenceData(LHS, LHSWrapper);
3450b57cec5SDimitry Andric CollectStmtSequenceData(RHS, RHSWrapper);
3460b57cec5SDimitry Andric
3470b57cec5SDimitry Andric return DataLHS == DataRHS;
3480b57cec5SDimitry Andric }
3490b57cec5SDimitry Andric
constrain(std::vector<CloneDetector::CloneGroup> & Sequences)3500b57cec5SDimitry Andric void RecursiveCloneTypeIIHashConstraint::constrain(
3510b57cec5SDimitry Andric std::vector<CloneDetector::CloneGroup> &Sequences) {
3520b57cec5SDimitry Andric // FIXME: Maybe we can do this in-place and don't need this additional vector.
3530b57cec5SDimitry Andric std::vector<CloneDetector::CloneGroup> Result;
3540b57cec5SDimitry Andric
3550b57cec5SDimitry Andric for (CloneDetector::CloneGroup &Group : Sequences) {
3560b57cec5SDimitry Andric // We assume in the following code that the Group is non-empty, so we
3570b57cec5SDimitry Andric // skip all empty groups.
3580b57cec5SDimitry Andric if (Group.empty())
3590b57cec5SDimitry Andric continue;
3600b57cec5SDimitry Andric
3610b57cec5SDimitry Andric std::vector<std::pair<size_t, StmtSequence>> StmtsByHash;
3620b57cec5SDimitry Andric
3630b57cec5SDimitry Andric // Generate hash codes for all children of S and save them in StmtsByHash.
3640b57cec5SDimitry Andric for (const StmtSequence &S : Group) {
3650b57cec5SDimitry Andric saveHash(S.front(), S.getContainingDecl(), StmtsByHash);
3660b57cec5SDimitry Andric }
3670b57cec5SDimitry Andric
3680b57cec5SDimitry Andric // Sort hash_codes in StmtsByHash.
3690b57cec5SDimitry Andric llvm::stable_sort(StmtsByHash, llvm::less_first());
3700b57cec5SDimitry Andric
3710b57cec5SDimitry Andric // Check for each StmtSequence if its successor has the same hash value.
3720b57cec5SDimitry Andric // We don't check the last StmtSequence as it has no successor.
3730b57cec5SDimitry Andric // Note: The 'size - 1 ' in the condition is safe because we check for an
3740b57cec5SDimitry Andric // empty Group vector at the beginning of this function.
3750b57cec5SDimitry Andric for (unsigned i = 0; i < StmtsByHash.size() - 1; ++i) {
3760b57cec5SDimitry Andric const auto Current = StmtsByHash[i];
3770b57cec5SDimitry Andric
3780b57cec5SDimitry Andric // It's likely that we just found a sequence of StmtSequences that
3790b57cec5SDimitry Andric // represent a CloneGroup, so we create a new group and start checking and
3800b57cec5SDimitry Andric // adding the StmtSequences in this sequence.
3810b57cec5SDimitry Andric CloneDetector::CloneGroup NewGroup;
3820b57cec5SDimitry Andric
3830b57cec5SDimitry Andric size_t PrototypeHash = Current.first;
3840b57cec5SDimitry Andric
3850b57cec5SDimitry Andric for (; i < StmtsByHash.size(); ++i) {
3860b57cec5SDimitry Andric // A different hash value means we have reached the end of the sequence.
3870b57cec5SDimitry Andric if (PrototypeHash != StmtsByHash[i].first) {
3880b57cec5SDimitry Andric // The current sequence could be the start of a new CloneGroup. So we
3890b57cec5SDimitry Andric // decrement i so that we visit it again in the outer loop.
3900b57cec5SDimitry Andric // Note: i can never be 0 at this point because we are just comparing
3910b57cec5SDimitry Andric // the hash of the Current StmtSequence with itself in the 'if' above.
3920b57cec5SDimitry Andric assert(i != 0);
3930b57cec5SDimitry Andric --i;
3940b57cec5SDimitry Andric break;
3950b57cec5SDimitry Andric }
3960b57cec5SDimitry Andric // Same hash value means we should add the StmtSequence to the current
3970b57cec5SDimitry Andric // group.
3980b57cec5SDimitry Andric NewGroup.push_back(StmtsByHash[i].second);
3990b57cec5SDimitry Andric }
4000b57cec5SDimitry Andric
4010b57cec5SDimitry Andric // We created a new clone group with matching hash codes and move it to
4020b57cec5SDimitry Andric // the result vector.
4030b57cec5SDimitry Andric Result.push_back(NewGroup);
4040b57cec5SDimitry Andric }
4050b57cec5SDimitry Andric }
4060b57cec5SDimitry Andric // Sequences is the output parameter, so we copy our result into it.
4070b57cec5SDimitry Andric Sequences = Result;
4080b57cec5SDimitry Andric }
4090b57cec5SDimitry Andric
constrain(std::vector<CloneDetector::CloneGroup> & Sequences)4100b57cec5SDimitry Andric void RecursiveCloneTypeIIVerifyConstraint::constrain(
4110b57cec5SDimitry Andric std::vector<CloneDetector::CloneGroup> &Sequences) {
4120b57cec5SDimitry Andric CloneConstraint::splitCloneGroups(
4130b57cec5SDimitry Andric Sequences, [](const StmtSequence &A, const StmtSequence &B) {
4140b57cec5SDimitry Andric return areSequencesClones(A, B);
4150b57cec5SDimitry Andric });
4160b57cec5SDimitry Andric }
4170b57cec5SDimitry Andric
calculateStmtComplexity(const StmtSequence & Seq,std::size_t Limit,const std::string & ParentMacroStack)4180b57cec5SDimitry Andric size_t MinComplexityConstraint::calculateStmtComplexity(
4190b57cec5SDimitry Andric const StmtSequence &Seq, std::size_t Limit,
4200b57cec5SDimitry Andric const std::string &ParentMacroStack) {
4210b57cec5SDimitry Andric if (Seq.empty())
4220b57cec5SDimitry Andric return 0;
4230b57cec5SDimitry Andric
4240b57cec5SDimitry Andric size_t Complexity = 1;
4250b57cec5SDimitry Andric
4260b57cec5SDimitry Andric ASTContext &Context = Seq.getASTContext();
4270b57cec5SDimitry Andric
4280b57cec5SDimitry Andric // Look up what macros expanded into the current statement.
4290b57cec5SDimitry Andric std::string MacroStack =
4300b57cec5SDimitry Andric data_collection::getMacroStack(Seq.getBeginLoc(), Context);
4310b57cec5SDimitry Andric
4320b57cec5SDimitry Andric // First, check if ParentMacroStack is not empty which means we are currently
4330b57cec5SDimitry Andric // dealing with a parent statement which was expanded from a macro.
4340b57cec5SDimitry Andric // If this parent statement was expanded from the same macros as this
4350b57cec5SDimitry Andric // statement, we reduce the initial complexity of this statement to zero.
4360b57cec5SDimitry Andric // This causes that a group of statements that were generated by a single
4370b57cec5SDimitry Andric // macro expansion will only increase the total complexity by one.
4380b57cec5SDimitry Andric // Note: This is not the final complexity of this statement as we still
4390b57cec5SDimitry Andric // add the complexity of the child statements to the complexity value.
4400b57cec5SDimitry Andric if (!ParentMacroStack.empty() && MacroStack == ParentMacroStack) {
4410b57cec5SDimitry Andric Complexity = 0;
4420b57cec5SDimitry Andric }
4430b57cec5SDimitry Andric
4440b57cec5SDimitry Andric // Iterate over the Stmts in the StmtSequence and add their complexity values
4450b57cec5SDimitry Andric // to the current complexity value.
4460b57cec5SDimitry Andric if (Seq.holdsSequence()) {
4470b57cec5SDimitry Andric for (const Stmt *S : Seq) {
4480b57cec5SDimitry Andric Complexity += calculateStmtComplexity(
4490b57cec5SDimitry Andric StmtSequence(S, Seq.getContainingDecl()), Limit, MacroStack);
4500b57cec5SDimitry Andric if (Complexity >= Limit)
4510b57cec5SDimitry Andric return Limit;
4520b57cec5SDimitry Andric }
4530b57cec5SDimitry Andric } else {
4540b57cec5SDimitry Andric for (const Stmt *S : Seq.front()->children()) {
4550b57cec5SDimitry Andric Complexity += calculateStmtComplexity(
4560b57cec5SDimitry Andric StmtSequence(S, Seq.getContainingDecl()), Limit, MacroStack);
4570b57cec5SDimitry Andric if (Complexity >= Limit)
4580b57cec5SDimitry Andric return Limit;
4590b57cec5SDimitry Andric }
4600b57cec5SDimitry Andric }
4610b57cec5SDimitry Andric return Complexity;
4620b57cec5SDimitry Andric }
4630b57cec5SDimitry Andric
constrain(std::vector<CloneDetector::CloneGroup> & CloneGroups)4640b57cec5SDimitry Andric void MatchingVariablePatternConstraint::constrain(
4650b57cec5SDimitry Andric std::vector<CloneDetector::CloneGroup> &CloneGroups) {
4660b57cec5SDimitry Andric CloneConstraint::splitCloneGroups(
4670b57cec5SDimitry Andric CloneGroups, [](const StmtSequence &A, const StmtSequence &B) {
4680b57cec5SDimitry Andric VariablePattern PatternA(A);
4690b57cec5SDimitry Andric VariablePattern PatternB(B);
4700b57cec5SDimitry Andric return PatternA.countPatternDifferences(PatternB) == 0;
4710b57cec5SDimitry Andric });
4720b57cec5SDimitry Andric }
4730b57cec5SDimitry Andric
splitCloneGroups(std::vector<CloneDetector::CloneGroup> & CloneGroups,llvm::function_ref<bool (const StmtSequence &,const StmtSequence &)> Compare)4740b57cec5SDimitry Andric void CloneConstraint::splitCloneGroups(
4750b57cec5SDimitry Andric std::vector<CloneDetector::CloneGroup> &CloneGroups,
4760b57cec5SDimitry Andric llvm::function_ref<bool(const StmtSequence &, const StmtSequence &)>
4770b57cec5SDimitry Andric Compare) {
4780b57cec5SDimitry Andric std::vector<CloneDetector::CloneGroup> Result;
4790b57cec5SDimitry Andric for (auto &HashGroup : CloneGroups) {
4800b57cec5SDimitry Andric // Contains all indexes in HashGroup that were already added to a
4810b57cec5SDimitry Andric // CloneGroup.
4820b57cec5SDimitry Andric std::vector<char> Indexes;
4830b57cec5SDimitry Andric Indexes.resize(HashGroup.size());
4840b57cec5SDimitry Andric
4850b57cec5SDimitry Andric for (unsigned i = 0; i < HashGroup.size(); ++i) {
4860b57cec5SDimitry Andric // Skip indexes that are already part of a CloneGroup.
4870b57cec5SDimitry Andric if (Indexes[i])
4880b57cec5SDimitry Andric continue;
4890b57cec5SDimitry Andric
4900b57cec5SDimitry Andric // Pick the first unhandled StmtSequence and consider it as the
4910b57cec5SDimitry Andric // beginning
4920b57cec5SDimitry Andric // of a new CloneGroup for now.
4930b57cec5SDimitry Andric // We don't add i to Indexes because we never iterate back.
4940b57cec5SDimitry Andric StmtSequence Prototype = HashGroup[i];
4950b57cec5SDimitry Andric CloneDetector::CloneGroup PotentialGroup = {Prototype};
4960b57cec5SDimitry Andric ++Indexes[i];
4970b57cec5SDimitry Andric
4980b57cec5SDimitry Andric // Check all following StmtSequences for clones.
4990b57cec5SDimitry Andric for (unsigned j = i + 1; j < HashGroup.size(); ++j) {
5000b57cec5SDimitry Andric // Skip indexes that are already part of a CloneGroup.
5010b57cec5SDimitry Andric if (Indexes[j])
5020b57cec5SDimitry Andric continue;
5030b57cec5SDimitry Andric
5040b57cec5SDimitry Andric // If a following StmtSequence belongs to our CloneGroup, we add it.
5050b57cec5SDimitry Andric const StmtSequence &Candidate = HashGroup[j];
5060b57cec5SDimitry Andric
5070b57cec5SDimitry Andric if (!Compare(Prototype, Candidate))
5080b57cec5SDimitry Andric continue;
5090b57cec5SDimitry Andric
5100b57cec5SDimitry Andric PotentialGroup.push_back(Candidate);
5110b57cec5SDimitry Andric // Make sure we never visit this StmtSequence again.
5120b57cec5SDimitry Andric ++Indexes[j];
5130b57cec5SDimitry Andric }
5140b57cec5SDimitry Andric
5150b57cec5SDimitry Andric // Otherwise, add it to the result and continue searching for more
5160b57cec5SDimitry Andric // groups.
5170b57cec5SDimitry Andric Result.push_back(PotentialGroup);
5180b57cec5SDimitry Andric }
5190b57cec5SDimitry Andric
5200b57cec5SDimitry Andric assert(llvm::all_of(Indexes, [](char c) { return c == 1; }));
5210b57cec5SDimitry Andric }
5220b57cec5SDimitry Andric CloneGroups = Result;
5230b57cec5SDimitry Andric }
5240b57cec5SDimitry Andric
addVariableOccurence(const VarDecl * VarDecl,const Stmt * Mention)5250b57cec5SDimitry Andric void VariablePattern::addVariableOccurence(const VarDecl *VarDecl,
5260b57cec5SDimitry Andric const Stmt *Mention) {
5270b57cec5SDimitry Andric // First check if we already reference this variable
5280b57cec5SDimitry Andric for (size_t KindIndex = 0; KindIndex < Variables.size(); ++KindIndex) {
5290b57cec5SDimitry Andric if (Variables[KindIndex] == VarDecl) {
5300b57cec5SDimitry Andric // If yes, add a new occurrence that points to the existing entry in
5310b57cec5SDimitry Andric // the Variables vector.
5320b57cec5SDimitry Andric Occurences.emplace_back(KindIndex, Mention);
5330b57cec5SDimitry Andric return;
5340b57cec5SDimitry Andric }
5350b57cec5SDimitry Andric }
5360b57cec5SDimitry Andric // If this variable wasn't already referenced, add it to the list of
5370b57cec5SDimitry Andric // referenced variables and add a occurrence that points to this new entry.
5380b57cec5SDimitry Andric Occurences.emplace_back(Variables.size(), Mention);
5390b57cec5SDimitry Andric Variables.push_back(VarDecl);
5400b57cec5SDimitry Andric }
5410b57cec5SDimitry Andric
addVariables(const Stmt * S)5420b57cec5SDimitry Andric void VariablePattern::addVariables(const Stmt *S) {
5430b57cec5SDimitry Andric // Sometimes we get a nullptr (such as from IfStmts which often have nullptr
5440b57cec5SDimitry Andric // children). We skip such statements as they don't reference any
5450b57cec5SDimitry Andric // variables.
5460b57cec5SDimitry Andric if (!S)
5470b57cec5SDimitry Andric return;
5480b57cec5SDimitry Andric
5490b57cec5SDimitry Andric // Check if S is a reference to a variable. If yes, add it to the pattern.
5500b57cec5SDimitry Andric if (auto D = dyn_cast<DeclRefExpr>(S)) {
5510b57cec5SDimitry Andric if (auto VD = dyn_cast<VarDecl>(D->getDecl()->getCanonicalDecl()))
5520b57cec5SDimitry Andric addVariableOccurence(VD, D);
5530b57cec5SDimitry Andric }
5540b57cec5SDimitry Andric
5550b57cec5SDimitry Andric // Recursively check all children of the given statement.
5560b57cec5SDimitry Andric for (const Stmt *Child : S->children()) {
5570b57cec5SDimitry Andric addVariables(Child);
5580b57cec5SDimitry Andric }
5590b57cec5SDimitry Andric }
5600b57cec5SDimitry Andric
countPatternDifferences(const VariablePattern & Other,VariablePattern::SuspiciousClonePair * FirstMismatch)5610b57cec5SDimitry Andric unsigned VariablePattern::countPatternDifferences(
5620b57cec5SDimitry Andric const VariablePattern &Other,
5630b57cec5SDimitry Andric VariablePattern::SuspiciousClonePair *FirstMismatch) {
5640b57cec5SDimitry Andric unsigned NumberOfDifferences = 0;
5650b57cec5SDimitry Andric
5660b57cec5SDimitry Andric assert(Other.Occurences.size() == Occurences.size());
5670b57cec5SDimitry Andric for (unsigned i = 0; i < Occurences.size(); ++i) {
5680b57cec5SDimitry Andric auto ThisOccurence = Occurences[i];
5690b57cec5SDimitry Andric auto OtherOccurence = Other.Occurences[i];
5700b57cec5SDimitry Andric if (ThisOccurence.KindID == OtherOccurence.KindID)
5710b57cec5SDimitry Andric continue;
5720b57cec5SDimitry Andric
5730b57cec5SDimitry Andric ++NumberOfDifferences;
5740b57cec5SDimitry Andric
5750b57cec5SDimitry Andric // If FirstMismatch is not a nullptr, we need to store information about
5760b57cec5SDimitry Andric // the first difference between the two patterns.
5770b57cec5SDimitry Andric if (FirstMismatch == nullptr)
5780b57cec5SDimitry Andric continue;
5790b57cec5SDimitry Andric
5800b57cec5SDimitry Andric // Only proceed if we just found the first difference as we only store
5810b57cec5SDimitry Andric // information about the first difference.
5820b57cec5SDimitry Andric if (NumberOfDifferences != 1)
5830b57cec5SDimitry Andric continue;
5840b57cec5SDimitry Andric
5850b57cec5SDimitry Andric const VarDecl *FirstSuggestion = nullptr;
5860b57cec5SDimitry Andric // If there is a variable available in the list of referenced variables
5870b57cec5SDimitry Andric // which wouldn't break the pattern if it is used in place of the
5880b57cec5SDimitry Andric // current variable, we provide this variable as the suggested fix.
5890b57cec5SDimitry Andric if (OtherOccurence.KindID < Variables.size())
5900b57cec5SDimitry Andric FirstSuggestion = Variables[OtherOccurence.KindID];
5910b57cec5SDimitry Andric
5920b57cec5SDimitry Andric // Store information about the first clone.
5930b57cec5SDimitry Andric FirstMismatch->FirstCloneInfo =
5940b57cec5SDimitry Andric VariablePattern::SuspiciousClonePair::SuspiciousCloneInfo(
5950b57cec5SDimitry Andric Variables[ThisOccurence.KindID], ThisOccurence.Mention,
5960b57cec5SDimitry Andric FirstSuggestion);
5970b57cec5SDimitry Andric
5980b57cec5SDimitry Andric // Same as above but with the other clone. We do this for both clones as
5990b57cec5SDimitry Andric // we don't know which clone is the one containing the unintended
6000b57cec5SDimitry Andric // pattern error.
6010b57cec5SDimitry Andric const VarDecl *SecondSuggestion = nullptr;
6020b57cec5SDimitry Andric if (ThisOccurence.KindID < Other.Variables.size())
6030b57cec5SDimitry Andric SecondSuggestion = Other.Variables[ThisOccurence.KindID];
6040b57cec5SDimitry Andric
6050b57cec5SDimitry Andric // Store information about the second clone.
6060b57cec5SDimitry Andric FirstMismatch->SecondCloneInfo =
6070b57cec5SDimitry Andric VariablePattern::SuspiciousClonePair::SuspiciousCloneInfo(
6080b57cec5SDimitry Andric Other.Variables[OtherOccurence.KindID], OtherOccurence.Mention,
6090b57cec5SDimitry Andric SecondSuggestion);
6100b57cec5SDimitry Andric
6110b57cec5SDimitry Andric // SuspiciousClonePair guarantees that the first clone always has a
6120b57cec5SDimitry Andric // suggested variable associated with it. As we know that one of the two
6130b57cec5SDimitry Andric // clones in the pair always has suggestion, we swap the two clones
6140b57cec5SDimitry Andric // in case the first clone has no suggested variable which means that
6150b57cec5SDimitry Andric // the second clone has a suggested variable and should be first.
6160b57cec5SDimitry Andric if (!FirstMismatch->FirstCloneInfo.Suggestion)
6170b57cec5SDimitry Andric std::swap(FirstMismatch->FirstCloneInfo, FirstMismatch->SecondCloneInfo);
6180b57cec5SDimitry Andric
6190b57cec5SDimitry Andric // This ensures that we always have at least one suggestion in a pair.
6200b57cec5SDimitry Andric assert(FirstMismatch->FirstCloneInfo.Suggestion);
6210b57cec5SDimitry Andric }
6220b57cec5SDimitry Andric
6230b57cec5SDimitry Andric return NumberOfDifferences;
6240b57cec5SDimitry Andric }
625