1 //===--- CloneDetection.cpp - Finds code clones in an AST -------*- C++ -*-===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 /// 10 /// This file implements classes for searching and anlyzing source code clones. 11 /// 12 //===----------------------------------------------------------------------===// 13 14 #include "clang/Analysis/CloneDetection.h" 15 16 #include "clang/AST/ASTContext.h" 17 #include "clang/AST/RecursiveASTVisitor.h" 18 #include "clang/AST/Stmt.h" 19 #include "clang/AST/StmtVisitor.h" 20 #include "clang/Lex/Lexer.h" 21 #include "llvm/ADT/StringRef.h" 22 #include "llvm/Support/MD5.h" 23 #include "llvm/Support/raw_ostream.h" 24 25 using namespace clang; 26 27 StmtSequence::StmtSequence(const CompoundStmt *Stmt, ASTContext &Context, 28 unsigned StartIndex, unsigned EndIndex) 29 : S(Stmt), Context(&Context), StartIndex(StartIndex), EndIndex(EndIndex) { 30 assert(Stmt && "Stmt must not be a nullptr"); 31 assert(StartIndex < EndIndex && "Given array should not be empty"); 32 assert(EndIndex <= Stmt->size() && "Given array too big for this Stmt"); 33 } 34 35 StmtSequence::StmtSequence(const Stmt *Stmt, ASTContext &Context) 36 : S(Stmt), Context(&Context), StartIndex(0), EndIndex(0) {} 37 38 StmtSequence::StmtSequence() 39 : S(nullptr), Context(nullptr), StartIndex(0), EndIndex(0) {} 40 41 bool StmtSequence::contains(const StmtSequence &Other) const { 42 // If both sequences reside in different translation units, they can never 43 // contain each other. 44 if (Context != Other.Context) 45 return false; 46 47 const SourceManager &SM = Context->getSourceManager(); 48 49 // Otherwise check if the start and end locations of the current sequence 50 // surround the other sequence. 51 bool StartIsInBounds = 52 SM.isBeforeInTranslationUnit(getStartLoc(), Other.getStartLoc()) || 53 getStartLoc() == Other.getStartLoc(); 54 if (!StartIsInBounds) 55 return false; 56 57 bool EndIsInBounds = 58 SM.isBeforeInTranslationUnit(Other.getEndLoc(), getEndLoc()) || 59 Other.getEndLoc() == getEndLoc(); 60 return EndIsInBounds; 61 } 62 63 StmtSequence::iterator StmtSequence::begin() const { 64 if (!holdsSequence()) { 65 return &S; 66 } 67 auto CS = cast<CompoundStmt>(S); 68 return CS->body_begin() + StartIndex; 69 } 70 71 StmtSequence::iterator StmtSequence::end() const { 72 if (!holdsSequence()) { 73 return reinterpret_cast<StmtSequence::iterator>(&S) + 1; 74 } 75 auto CS = cast<CompoundStmt>(S); 76 return CS->body_begin() + EndIndex; 77 } 78 79 SourceLocation StmtSequence::getStartLoc() const { 80 return front()->getLocStart(); 81 } 82 83 SourceLocation StmtSequence::getEndLoc() const { return back()->getLocEnd(); } 84 85 namespace { 86 87 /// \brief Analyzes the pattern of the referenced variables in a statement. 88 class VariablePattern { 89 90 /// \brief Describes an occurence of a variable reference in a statement. 91 struct VariableOccurence { 92 /// The index of the associated VarDecl in the Variables vector. 93 size_t KindID; 94 /// The source range in the code where the variable was referenced. 95 SourceRange Range; 96 97 VariableOccurence(size_t KindID, SourceRange Range) 98 : KindID(KindID), Range(Range) {} 99 }; 100 101 /// All occurences of referenced variables in the order of appearance. 102 std::vector<VariableOccurence> Occurences; 103 /// List of referenced variables in the order of appearance. 104 /// Every item in this list is unique. 105 std::vector<const VarDecl *> Variables; 106 107 /// \brief Adds a new variable referenced to this pattern. 108 /// \param VarDecl The declaration of the variable that is referenced. 109 /// \param Range The SourceRange where this variable is referenced. 110 void addVariableOccurence(const VarDecl *VarDecl, SourceRange Range) { 111 // First check if we already reference this variable 112 for (size_t KindIndex = 0; KindIndex < Variables.size(); ++KindIndex) { 113 if (Variables[KindIndex] == VarDecl) { 114 // If yes, add a new occurence that points to the existing entry in 115 // the Variables vector. 116 Occurences.emplace_back(KindIndex, Range); 117 return; 118 } 119 } 120 // If this variable wasn't already referenced, add it to the list of 121 // referenced variables and add a occurence that points to this new entry. 122 Occurences.emplace_back(Variables.size(), Range); 123 Variables.push_back(VarDecl); 124 } 125 126 /// \brief Adds each referenced variable from the given statement. 127 void addVariables(const Stmt *S) { 128 // Sometimes we get a nullptr (such as from IfStmts which often have nullptr 129 // children). We skip such statements as they don't reference any 130 // variables. 131 if (!S) 132 return; 133 134 // Check if S is a reference to a variable. If yes, add it to the pattern. 135 if (auto D = dyn_cast<DeclRefExpr>(S)) { 136 if (auto VD = dyn_cast<VarDecl>(D->getDecl()->getCanonicalDecl())) 137 addVariableOccurence(VD, D->getSourceRange()); 138 } 139 140 // Recursively check all children of the given statement. 141 for (const Stmt *Child : S->children()) { 142 addVariables(Child); 143 } 144 } 145 146 public: 147 /// \brief Creates an VariablePattern object with information about the given 148 /// StmtSequence. 149 VariablePattern(const StmtSequence &Sequence) { 150 for (const Stmt *S : Sequence) 151 addVariables(S); 152 } 153 154 /// \brief Counts the differences between this pattern and the given one. 155 /// \param Other The given VariablePattern to compare with. 156 /// \param FirstMismatch Output parameter that will be filled with information 157 /// about the first difference between the two patterns. This parameter 158 /// can be a nullptr, in which case it will be ignored. 159 /// \return Returns the number of differences between the pattern this object 160 /// is following and the given VariablePattern. 161 /// 162 /// For example, the following statements all have the same pattern and this 163 /// function would return zero: 164 /// 165 /// if (a < b) return a; return b; 166 /// if (x < y) return x; return y; 167 /// if (u2 < u1) return u2; return u1; 168 /// 169 /// But the following statement has a different pattern (note the changed 170 /// variables in the return statements) and would have two differences when 171 /// compared with one of the statements above. 172 /// 173 /// if (a < b) return b; return a; 174 /// 175 /// This function should only be called if the related statements of the given 176 /// pattern and the statements of this objects are clones of each other. 177 unsigned countPatternDifferences( 178 const VariablePattern &Other, 179 CloneDetector::SuspiciousClonePair *FirstMismatch = nullptr) { 180 unsigned NumberOfDifferences = 0; 181 182 assert(Other.Occurences.size() == Occurences.size()); 183 for (unsigned i = 0; i < Occurences.size(); ++i) { 184 auto ThisOccurence = Occurences[i]; 185 auto OtherOccurence = Other.Occurences[i]; 186 if (ThisOccurence.KindID == OtherOccurence.KindID) 187 continue; 188 189 ++NumberOfDifferences; 190 191 // If FirstMismatch is not a nullptr, we need to store information about 192 // the first difference between the two patterns. 193 if (FirstMismatch == nullptr) 194 continue; 195 196 // Only proceed if we just found the first difference as we only store 197 // information about the first difference. 198 if (NumberOfDifferences != 1) 199 continue; 200 201 const VarDecl *FirstSuggestion = nullptr; 202 // If there is a variable available in the list of referenced variables 203 // which wouldn't break the pattern if it is used in place of the 204 // current variable, we provide this variable as the suggested fix. 205 if (OtherOccurence.KindID < Variables.size()) 206 FirstSuggestion = Variables[OtherOccurence.KindID]; 207 208 // Store information about the first clone. 209 FirstMismatch->FirstCloneInfo = 210 CloneDetector::SuspiciousClonePair::SuspiciousCloneInfo( 211 Variables[ThisOccurence.KindID], ThisOccurence.Range, 212 FirstSuggestion); 213 214 // Same as above but with the other clone. We do this for both clones as 215 // we don't know which clone is the one containing the unintended 216 // pattern error. 217 const VarDecl *SecondSuggestion = nullptr; 218 if (ThisOccurence.KindID < Other.Variables.size()) 219 SecondSuggestion = Other.Variables[ThisOccurence.KindID]; 220 221 // Store information about the second clone. 222 FirstMismatch->SecondCloneInfo = 223 CloneDetector::SuspiciousClonePair::SuspiciousCloneInfo( 224 Variables[ThisOccurence.KindID], OtherOccurence.Range, 225 SecondSuggestion); 226 227 // SuspiciousClonePair guarantees that the first clone always has a 228 // suggested variable associated with it. As we know that one of the two 229 // clones in the pair always has suggestion, we swap the two clones 230 // in case the first clone has no suggested variable which means that 231 // the second clone has a suggested variable and should be first. 232 if (!FirstMismatch->FirstCloneInfo.Suggestion) 233 std::swap(FirstMismatch->FirstCloneInfo, 234 FirstMismatch->SecondCloneInfo); 235 236 // This ensures that we always have at least one suggestion in a pair. 237 assert(FirstMismatch->FirstCloneInfo.Suggestion); 238 } 239 240 return NumberOfDifferences; 241 } 242 }; 243 } 244 245 /// \brief Prints the macro name that contains the given SourceLocation into 246 /// the given raw_string_ostream. 247 static void printMacroName(llvm::raw_string_ostream &MacroStack, 248 ASTContext &Context, SourceLocation Loc) { 249 MacroStack << Lexer::getImmediateMacroName(Loc, Context.getSourceManager(), 250 Context.getLangOpts()); 251 252 // Add an empty space at the end as a padding to prevent 253 // that macro names concatenate to the names of other macros. 254 MacroStack << " "; 255 } 256 257 /// \brief Returns a string that represents all macro expansions that 258 /// expanded into the given SourceLocation. 259 /// 260 /// If 'getMacroStack(A) == getMacroStack(B)' is true, then the SourceLocations 261 /// A and B are expanded from the same macros in the same order. 262 static std::string getMacroStack(SourceLocation Loc, ASTContext &Context) { 263 std::string MacroStack; 264 llvm::raw_string_ostream MacroStackStream(MacroStack); 265 SourceManager &SM = Context.getSourceManager(); 266 267 // Iterate over all macros that expanded into the given SourceLocation. 268 while (Loc.isMacroID()) { 269 // Add the macro name to the stream. 270 printMacroName(MacroStackStream, Context, Loc); 271 Loc = SM.getImmediateMacroCallerLoc(Loc); 272 } 273 MacroStackStream.flush(); 274 return MacroStack; 275 } 276 277 namespace { 278 /// \brief Collects the data of a single Stmt. 279 /// 280 /// This class defines what a code clone is: If it collects for two statements 281 /// the same data, then those two statements are considered to be clones of each 282 /// other. 283 /// 284 /// All collected data is forwarded to the given data consumer of the type T. 285 /// The data consumer class needs to provide a member method with the signature: 286 /// update(StringRef Str) 287 template <typename T> 288 class StmtDataCollector : public ConstStmtVisitor<StmtDataCollector<T>> { 289 290 ASTContext &Context; 291 /// \brief The data sink to which all data is forwarded. 292 T &DataConsumer; 293 294 public: 295 /// \brief Collects data of the given Stmt. 296 /// \param S The given statement. 297 /// \param Context The ASTContext of S. 298 /// \param DataConsumer The data sink to which all data is forwarded. 299 StmtDataCollector(const Stmt *S, ASTContext &Context, T &DataConsumer) 300 : Context(Context), DataConsumer(DataConsumer) { 301 this->Visit(S); 302 } 303 304 // Below are utility methods for appending different data to the vector. 305 306 void addData(CloneDetector::DataPiece Integer) { 307 DataConsumer.update( 308 StringRef(reinterpret_cast<char *>(&Integer), sizeof(Integer))); 309 } 310 311 void addData(llvm::StringRef Str) { DataConsumer.update(Str); } 312 313 void addData(const QualType &QT) { addData(QT.getAsString()); } 314 315 // The functions below collect the class specific data of each Stmt subclass. 316 317 // Utility macro for defining a visit method for a given class. This method 318 // calls back to the ConstStmtVisitor to visit all parent classes. 319 #define DEF_ADD_DATA(CLASS, CODE) \ 320 void Visit##CLASS(const CLASS *S) { \ 321 CODE; \ 322 ConstStmtVisitor<StmtDataCollector>::Visit##CLASS(S); \ 323 } 324 325 DEF_ADD_DATA(Stmt, { 326 addData(S->getStmtClass()); 327 // This ensures that macro generated code isn't identical to macro-generated 328 // code. 329 addData(getMacroStack(S->getLocStart(), Context)); 330 addData(getMacroStack(S->getLocEnd(), Context)); 331 }) 332 DEF_ADD_DATA(Expr, { addData(S->getType()); }) 333 334 //--- Builtin functionality ----------------------------------------------// 335 DEF_ADD_DATA(ArrayTypeTraitExpr, { addData(S->getTrait()); }) 336 DEF_ADD_DATA(ExpressionTraitExpr, { addData(S->getTrait()); }) 337 DEF_ADD_DATA(PredefinedExpr, { addData(S->getIdentType()); }) 338 DEF_ADD_DATA(TypeTraitExpr, { 339 addData(S->getTrait()); 340 for (unsigned i = 0; i < S->getNumArgs(); ++i) 341 addData(S->getArg(i)->getType()); 342 }) 343 344 //--- Calls --------------------------------------------------------------// 345 DEF_ADD_DATA(CallExpr, { 346 // Function pointers don't have a callee and we just skip hashing it. 347 if (const FunctionDecl *D = S->getDirectCallee()) { 348 // If the function is a template specialization, we also need to handle 349 // the template arguments as they are not included in the qualified name. 350 if (auto Args = D->getTemplateSpecializationArgs()) { 351 std::string ArgString; 352 353 // Print all template arguments into ArgString 354 llvm::raw_string_ostream OS(ArgString); 355 for (unsigned i = 0; i < Args->size(); ++i) { 356 Args->get(i).print(Context.getLangOpts(), OS); 357 // Add a padding character so that 'foo<X, XX>()' != 'foo<XX, X>()'. 358 OS << '\n'; 359 } 360 OS.flush(); 361 362 addData(ArgString); 363 } 364 addData(D->getQualifiedNameAsString()); 365 } 366 }) 367 368 //--- Exceptions ---------------------------------------------------------// 369 DEF_ADD_DATA(CXXCatchStmt, { addData(S->getCaughtType()); }) 370 371 //--- C++ OOP Stmts ------------------------------------------------------// 372 DEF_ADD_DATA(CXXDeleteExpr, { 373 addData(S->isArrayFormAsWritten()); 374 addData(S->isGlobalDelete()); 375 }) 376 377 //--- Casts --------------------------------------------------------------// 378 DEF_ADD_DATA(ObjCBridgedCastExpr, { addData(S->getBridgeKind()); }) 379 380 //--- Miscellaneous Exprs ------------------------------------------------// 381 DEF_ADD_DATA(BinaryOperator, { addData(S->getOpcode()); }) 382 DEF_ADD_DATA(UnaryOperator, { addData(S->getOpcode()); }) 383 384 //--- Control flow -------------------------------------------------------// 385 DEF_ADD_DATA(GotoStmt, { addData(S->getLabel()->getName()); }) 386 DEF_ADD_DATA(IndirectGotoStmt, { 387 if (S->getConstantTarget()) 388 addData(S->getConstantTarget()->getName()); 389 }) 390 DEF_ADD_DATA(LabelStmt, { addData(S->getDecl()->getName()); }) 391 DEF_ADD_DATA(MSDependentExistsStmt, { addData(S->isIfExists()); }) 392 DEF_ADD_DATA(AddrLabelExpr, { addData(S->getLabel()->getName()); }) 393 394 //--- Objective-C --------------------------------------------------------// 395 DEF_ADD_DATA(ObjCIndirectCopyRestoreExpr, { addData(S->shouldCopy()); }) 396 DEF_ADD_DATA(ObjCPropertyRefExpr, { 397 addData(S->isSuperReceiver()); 398 addData(S->isImplicitProperty()); 399 }) 400 DEF_ADD_DATA(ObjCAtCatchStmt, { addData(S->hasEllipsis()); }) 401 402 //--- Miscellaneous Stmts ------------------------------------------------// 403 DEF_ADD_DATA(CXXFoldExpr, { 404 addData(S->isRightFold()); 405 addData(S->getOperator()); 406 }) 407 DEF_ADD_DATA(GenericSelectionExpr, { 408 for (unsigned i = 0; i < S->getNumAssocs(); ++i) { 409 addData(S->getAssocType(i)); 410 } 411 }) 412 DEF_ADD_DATA(LambdaExpr, { 413 for (const LambdaCapture &C : S->captures()) { 414 addData(C.isPackExpansion()); 415 addData(C.getCaptureKind()); 416 if (C.capturesVariable()) 417 addData(C.getCapturedVar()->getType()); 418 } 419 addData(S->isGenericLambda()); 420 addData(S->isMutable()); 421 }) 422 DEF_ADD_DATA(DeclStmt, { 423 auto numDecls = std::distance(S->decl_begin(), S->decl_end()); 424 addData(static_cast<CloneDetector::DataPiece>(numDecls)); 425 for (const Decl *D : S->decls()) { 426 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 427 addData(VD->getType()); 428 } 429 } 430 }) 431 DEF_ADD_DATA(AsmStmt, { 432 addData(S->isSimple()); 433 addData(S->isVolatile()); 434 addData(S->generateAsmString(Context)); 435 for (unsigned i = 0; i < S->getNumInputs(); ++i) { 436 addData(S->getInputConstraint(i)); 437 } 438 for (unsigned i = 0; i < S->getNumOutputs(); ++i) { 439 addData(S->getOutputConstraint(i)); 440 } 441 for (unsigned i = 0; i < S->getNumClobbers(); ++i) { 442 addData(S->getClobber(i)); 443 } 444 }) 445 DEF_ADD_DATA(AttributedStmt, { 446 for (const Attr *A : S->getAttrs()) { 447 addData(std::string(A->getSpelling())); 448 } 449 }) 450 }; 451 } // end anonymous namespace 452 453 namespace { 454 /// Generates CloneSignatures for a set of statements and stores the results in 455 /// a CloneDetector object. 456 class CloneSignatureGenerator { 457 458 CloneDetector &CD; 459 ASTContext &Context; 460 461 /// \brief Generates CloneSignatures for all statements in the given statement 462 /// tree and stores them in the CloneDetector. 463 /// 464 /// \param S The root of the given statement tree. 465 /// \param ParentMacroStack A string representing the macros that generated 466 /// the parent statement or an empty string if no 467 /// macros generated the parent statement. 468 /// See getMacroStack() for generating such a string. 469 /// \return The CloneSignature of the root statement. 470 CloneDetector::CloneSignature 471 generateSignatures(const Stmt *S, const std::string &ParentMacroStack) { 472 // Create an empty signature that will be filled in this method. 473 CloneDetector::CloneSignature Signature; 474 475 llvm::MD5 Hash; 476 477 // Collect all relevant data from S and hash it. 478 StmtDataCollector<llvm::MD5>(S, Context, Hash); 479 480 // Look up what macros expanded into the current statement. 481 std::string StartMacroStack = getMacroStack(S->getLocStart(), Context); 482 std::string EndMacroStack = getMacroStack(S->getLocEnd(), Context); 483 484 // First, check if ParentMacroStack is not empty which means we are currently 485 // dealing with a parent statement which was expanded from a macro. 486 // If this parent statement was expanded from the same macros as this 487 // statement, we reduce the initial complexity of this statement to zero. 488 // This causes that a group of statements that were generated by a single 489 // macro expansion will only increase the total complexity by one. 490 // Note: This is not the final complexity of this statement as we still 491 // add the complexity of the child statements to the complexity value. 492 if (!ParentMacroStack.empty() && (StartMacroStack == ParentMacroStack && 493 EndMacroStack == ParentMacroStack)) { 494 Signature.Complexity = 0; 495 } 496 497 // Storage for the signatures of the direct child statements. This is only 498 // needed if the current statement is a CompoundStmt. 499 std::vector<CloneDetector::CloneSignature> ChildSignatures; 500 const CompoundStmt *CS = dyn_cast<const CompoundStmt>(S); 501 502 // The signature of a statement includes the signatures of its children. 503 // Therefore we create the signatures for every child and add them to the 504 // current signature. 505 for (const Stmt *Child : S->children()) { 506 // Some statements like 'if' can have nullptr children that we will skip. 507 if (!Child) 508 continue; 509 510 // Recursive call to create the signature of the child statement. This 511 // will also create and store all clone groups in this child statement. 512 // We pass only the StartMacroStack along to keep things simple. 513 auto ChildSignature = generateSignatures(Child, StartMacroStack); 514 515 // Add the collected data to the signature of the current statement. 516 Signature.Complexity += ChildSignature.Complexity; 517 Hash.update(StringRef(reinterpret_cast<char *>(&ChildSignature.Hash), 518 sizeof(ChildSignature.Hash))); 519 520 // If the current statement is a CompoundStatement, we need to store the 521 // signature for the generation of the sub-sequences. 522 if (CS) 523 ChildSignatures.push_back(ChildSignature); 524 } 525 526 // If the current statement is a CompoundStmt, we also need to create the 527 // clone groups from the sub-sequences inside the children. 528 if (CS) 529 handleSubSequences(CS, ChildSignatures); 530 531 // Create the final hash code for the current signature. 532 llvm::MD5::MD5Result HashResult; 533 Hash.final(HashResult); 534 535 // Copy as much of the generated hash code to the signature's hash code. 536 std::memcpy(&Signature.Hash, &HashResult, 537 std::min(sizeof(Signature.Hash), sizeof(HashResult))); 538 539 // Save the signature for the current statement in the CloneDetector object. 540 CD.add(StmtSequence(S, Context), Signature); 541 542 return Signature; 543 } 544 545 /// \brief Adds all possible sub-sequences in the child array of the given 546 /// CompoundStmt to the CloneDetector. 547 /// \param CS The given CompoundStmt. 548 /// \param ChildSignatures A list of calculated signatures for each child in 549 /// the given CompoundStmt. 550 void handleSubSequences( 551 const CompoundStmt *CS, 552 const std::vector<CloneDetector::CloneSignature> &ChildSignatures) { 553 554 // FIXME: This function has quadratic runtime right now. Check if skipping 555 // this function for too long CompoundStmts is an option. 556 557 // The length of the sub-sequence. We don't need to handle sequences with 558 // the length 1 as they are already handled in CollectData(). 559 for (unsigned Length = 2; Length <= CS->size(); ++Length) { 560 // The start index in the body of the CompoundStmt. We increase the 561 // position until the end of the sub-sequence reaches the end of the 562 // CompoundStmt body. 563 for (unsigned Pos = 0; Pos <= CS->size() - Length; ++Pos) { 564 // Create an empty signature and add the signatures of all selected 565 // child statements to it. 566 CloneDetector::CloneSignature SubSignature; 567 llvm::MD5 SubHash; 568 569 for (unsigned i = Pos; i < Pos + Length; ++i) { 570 SubSignature.Complexity += ChildSignatures[i].Complexity; 571 size_t ChildHash = ChildSignatures[i].Hash; 572 573 SubHash.update(StringRef(reinterpret_cast<char *>(&ChildHash), 574 sizeof(ChildHash))); 575 } 576 577 // Create the final hash code for the current signature. 578 llvm::MD5::MD5Result HashResult; 579 SubHash.final(HashResult); 580 581 // Copy as much of the generated hash code to the signature's hash code. 582 std::memcpy(&SubSignature.Hash, &HashResult, 583 std::min(sizeof(SubSignature.Hash), sizeof(HashResult))); 584 585 // Save the signature together with the information about what children 586 // sequence we selected. 587 CD.add(StmtSequence(CS, Context, Pos, Pos + Length), SubSignature); 588 } 589 } 590 } 591 592 public: 593 explicit CloneSignatureGenerator(CloneDetector &CD, ASTContext &Context) 594 : CD(CD), Context(Context) {} 595 596 /// \brief Generates signatures for all statements in the given function body. 597 void consumeCodeBody(const Stmt *S) { generateSignatures(S, ""); } 598 }; 599 } // end anonymous namespace 600 601 void CloneDetector::analyzeCodeBody(const Decl *D) { 602 assert(D); 603 assert(D->hasBody()); 604 CloneSignatureGenerator Generator(*this, D->getASTContext()); 605 Generator.consumeCodeBody(D->getBody()); 606 } 607 608 void CloneDetector::add(const StmtSequence &S, 609 const CloneSignature &Signature) { 610 Sequences.push_back(std::make_pair(Signature, S)); 611 } 612 613 namespace { 614 /// \brief Returns true if and only if \p Stmt contains at least one other 615 /// sequence in the \p Group. 616 bool containsAnyInGroup(StmtSequence &Stmt, CloneDetector::CloneGroup &Group) { 617 for (StmtSequence &GroupStmt : Group.Sequences) { 618 if (Stmt.contains(GroupStmt)) 619 return true; 620 } 621 return false; 622 } 623 624 /// \brief Returns true if and only if all sequences in \p OtherGroup are 625 /// contained by a sequence in \p Group. 626 bool containsGroup(CloneDetector::CloneGroup &Group, 627 CloneDetector::CloneGroup &OtherGroup) { 628 // We have less sequences in the current group than we have in the other, 629 // so we will never fulfill the requirement for returning true. This is only 630 // possible because we know that a sequence in Group can contain at most 631 // one sequence in OtherGroup. 632 if (Group.Sequences.size() < OtherGroup.Sequences.size()) 633 return false; 634 635 for (StmtSequence &Stmt : Group.Sequences) { 636 if (!containsAnyInGroup(Stmt, OtherGroup)) 637 return false; 638 } 639 return true; 640 } 641 } // end anonymous namespace 642 643 namespace { 644 /// \brief Wrapper around FoldingSetNodeID that it can be used as the template 645 /// argument of the StmtDataCollector. 646 class FoldingSetNodeIDWrapper { 647 648 llvm::FoldingSetNodeID &FS; 649 650 public: 651 FoldingSetNodeIDWrapper(llvm::FoldingSetNodeID &FS) : FS(FS) {} 652 653 void update(StringRef Str) { FS.AddString(Str); } 654 }; 655 } // end anonymous namespace 656 657 /// \brief Writes the relevant data from all statements and child statements 658 /// in the given StmtSequence into the given FoldingSetNodeID. 659 static void CollectStmtSequenceData(const StmtSequence &Sequence, 660 FoldingSetNodeIDWrapper &OutputData) { 661 for (const Stmt *S : Sequence) { 662 StmtDataCollector<FoldingSetNodeIDWrapper>(S, Sequence.getASTContext(), 663 OutputData); 664 665 for (const Stmt *Child : S->children()) { 666 if (!Child) 667 continue; 668 669 CollectStmtSequenceData(StmtSequence(Child, Sequence.getASTContext()), 670 OutputData); 671 } 672 } 673 } 674 675 /// \brief Returns true if both sequences are clones of each other. 676 static bool areSequencesClones(const StmtSequence &LHS, 677 const StmtSequence &RHS) { 678 // We collect the data from all statements in the sequence as we did before 679 // when generating a hash value for each sequence. But this time we don't 680 // hash the collected data and compare the whole data set instead. This 681 // prevents any false-positives due to hash code collisions. 682 llvm::FoldingSetNodeID DataLHS, DataRHS; 683 FoldingSetNodeIDWrapper LHSWrapper(DataLHS); 684 FoldingSetNodeIDWrapper RHSWrapper(DataRHS); 685 686 CollectStmtSequenceData(LHS, LHSWrapper); 687 CollectStmtSequenceData(RHS, RHSWrapper); 688 689 return DataLHS == DataRHS; 690 } 691 692 /// \brief Finds all actual clone groups in a single group of presumed clones. 693 /// \param Result Output parameter to which all found groups are added. 694 /// \param Group A group of presumed clones. The clones are allowed to have a 695 /// different variable pattern and may not be actual clones of each 696 /// other. 697 /// \param CheckVariablePattern If true, every clone in a group that was added 698 /// to the output follows the same variable pattern as the other 699 /// clones in its group. 700 static void createCloneGroups(std::vector<CloneDetector::CloneGroup> &Result, 701 const CloneDetector::CloneGroup &Group, 702 bool CheckVariablePattern) { 703 // We remove the Sequences one by one, so a list is more appropriate. 704 std::list<StmtSequence> UnassignedSequences(Group.Sequences.begin(), 705 Group.Sequences.end()); 706 707 // Search for clones as long as there could be clones in UnassignedSequences. 708 while (UnassignedSequences.size() > 1) { 709 710 // Pick the first Sequence as a protoype for a new clone group. 711 StmtSequence Prototype = UnassignedSequences.front(); 712 UnassignedSequences.pop_front(); 713 714 CloneDetector::CloneGroup FilteredGroup(Prototype, Group.Signature); 715 716 // Analyze the variable pattern of the prototype. Every other StmtSequence 717 // needs to have the same pattern to get into the new clone group. 718 VariablePattern PrototypeFeatures(Prototype); 719 720 // Search all remaining StmtSequences for an identical variable pattern 721 // and assign them to our new clone group. 722 auto I = UnassignedSequences.begin(), E = UnassignedSequences.end(); 723 while (I != E) { 724 // If the sequence doesn't fit to the prototype, we have encountered 725 // an unintended hash code collision and we skip it. 726 if (!areSequencesClones(Prototype, *I)) { 727 ++I; 728 continue; 729 } 730 731 // If we weren't asked to check for a matching variable pattern in clone 732 // groups we can add the sequence now to the new clone group. 733 // If we were asked to check for matching variable pattern, we first have 734 // to check that there are no differences between the two patterns and 735 // only proceed if they match. 736 if (!CheckVariablePattern || 737 VariablePattern(*I).countPatternDifferences(PrototypeFeatures) == 0) { 738 FilteredGroup.Sequences.push_back(*I); 739 I = UnassignedSequences.erase(I); 740 continue; 741 } 742 743 // We didn't found a matching variable pattern, so we continue with the 744 // next sequence. 745 ++I; 746 } 747 748 // Add a valid clone group to the list of found clone groups. 749 if (!FilteredGroup.isValid()) 750 continue; 751 752 Result.push_back(FilteredGroup); 753 } 754 } 755 756 void CloneDetector::findClones(std::vector<CloneGroup> &Result, 757 unsigned MinGroupComplexity, 758 bool CheckPatterns) { 759 // A shortcut (and necessary for the for-loop later in this function). 760 if (Sequences.empty()) 761 return; 762 763 // We need to search for groups of StmtSequences with the same hash code to 764 // create our initial clone groups. By sorting all known StmtSequences by 765 // their hash value we make sure that StmtSequences with the same hash code 766 // are grouped together in the Sequences vector. 767 // Note: We stable sort here because the StmtSequences are added in the order 768 // in which they appear in the source file. We want to preserve that order 769 // because we also want to report them in that order in the CloneChecker. 770 std::stable_sort(Sequences.begin(), Sequences.end(), 771 [](std::pair<CloneSignature, StmtSequence> LHS, 772 std::pair<CloneSignature, StmtSequence> RHS) { 773 return LHS.first.Hash < RHS.first.Hash; 774 }); 775 776 std::vector<CloneGroup> CloneGroups; 777 778 // Check for each CloneSignature if its successor has the same hash value. 779 // We don't check the last CloneSignature as it has no successor. 780 // Note: The 'size - 1' in the condition is safe because we check for an empty 781 // Sequences vector at the beginning of this function. 782 for (unsigned i = 0; i < Sequences.size() - 1; ++i) { 783 const auto Current = Sequences[i]; 784 const auto Next = Sequences[i + 1]; 785 786 if (Current.first.Hash != Next.first.Hash) 787 continue; 788 789 // It's likely that we just found an sequence of CloneSignatures that 790 // represent a CloneGroup, so we create a new group and start checking and 791 // adding the CloneSignatures in this sequence. 792 CloneGroup Group; 793 Group.Signature = Current.first; 794 795 for (; i < Sequences.size(); ++i) { 796 const auto &Signature = Sequences[i]; 797 798 // A different hash value means we have reached the end of the sequence. 799 if (Current.first.Hash != Signature.first.Hash) { 800 // The current Signature could be the start of a new CloneGroup. So we 801 // decrement i so that we visit it again in the outer loop. 802 // Note: i can never be 0 at this point because we are just comparing 803 // the hash of the Current CloneSignature with itself in the 'if' above. 804 assert(i != 0); 805 --i; 806 break; 807 } 808 809 // Skip CloneSignatures that won't pass the complexity requirement. 810 if (Signature.first.Complexity < MinGroupComplexity) 811 continue; 812 813 Group.Sequences.push_back(Signature.second); 814 } 815 816 // There is a chance that we haven't found more than two fitting 817 // CloneSignature because not enough CloneSignatures passed the complexity 818 // requirement. As a CloneGroup with less than two members makes no sense, 819 // we ignore this CloneGroup and won't add it to the result. 820 if (!Group.isValid()) 821 continue; 822 823 CloneGroups.push_back(Group); 824 } 825 826 // Add every valid clone group that fulfills the complexity requirement. 827 for (const CloneGroup &Group : CloneGroups) { 828 createCloneGroups(Result, Group, CheckPatterns); 829 } 830 831 std::vector<unsigned> IndexesToRemove; 832 833 // Compare every group in the result with the rest. If one groups contains 834 // another group, we only need to return the bigger group. 835 // Note: This doesn't scale well, so if possible avoid calling any heavy 836 // function from this loop to minimize the performance impact. 837 for (unsigned i = 0; i < Result.size(); ++i) { 838 for (unsigned j = 0; j < Result.size(); ++j) { 839 // Don't compare a group with itself. 840 if (i == j) 841 continue; 842 843 if (containsGroup(Result[j], Result[i])) { 844 IndexesToRemove.push_back(i); 845 break; 846 } 847 } 848 } 849 850 // Erasing a list of indexes from the vector should be done with decreasing 851 // indexes. As IndexesToRemove is constructed with increasing values, we just 852 // reverse iterate over it to get the desired order. 853 for (auto I = IndexesToRemove.rbegin(); I != IndexesToRemove.rend(); ++I) { 854 Result.erase(Result.begin() + *I); 855 } 856 } 857 858 void CloneDetector::findSuspiciousClones( 859 std::vector<CloneDetector::SuspiciousClonePair> &Result, 860 unsigned MinGroupComplexity) { 861 std::vector<CloneGroup> Clones; 862 // Reuse the normal search for clones but specify that the clone groups don't 863 // need to have a common referenced variable pattern so that we can manually 864 // search for the kind of pattern errors this function is supposed to find. 865 findClones(Clones, MinGroupComplexity, false); 866 867 for (const CloneGroup &Group : Clones) { 868 for (unsigned i = 0; i < Group.Sequences.size(); ++i) { 869 VariablePattern PatternA(Group.Sequences[i]); 870 871 for (unsigned j = i + 1; j < Group.Sequences.size(); ++j) { 872 VariablePattern PatternB(Group.Sequences[j]); 873 874 CloneDetector::SuspiciousClonePair ClonePair; 875 // For now, we only report clones which break the variable pattern just 876 // once because multiple differences in a pattern are an indicator that 877 // those differences are maybe intended (e.g. because it's actually 878 // a different algorithm). 879 // TODO: In very big clones even multiple variables can be unintended, 880 // so replacing this number with a percentage could better handle such 881 // cases. On the other hand it could increase the false-positive rate 882 // for all clones if the percentage is too high. 883 if (PatternA.countPatternDifferences(PatternB, &ClonePair) == 1) { 884 Result.push_back(ClonePair); 885 break; 886 } 887 } 888 } 889 } 890 } 891