1 //===--- EasilySwappableParametersCheck.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 "EasilySwappableParametersCheck.h" 10 #include "../utils/OptionsUtils.h" 11 #include "clang/AST/ASTContext.h" 12 #include "clang/AST/RecursiveASTVisitor.h" 13 #include "clang/ASTMatchers/ASTMatchFinder.h" 14 #include "clang/Lex/Lexer.h" 15 #include "llvm/ADT/SmallSet.h" 16 17 #define DEBUG_TYPE "EasilySwappableParametersCheck" 18 #include "llvm/Support/Debug.h" 19 20 namespace optutils = clang::tidy::utils::options; 21 22 /// The default value for the MinimumLength check option. 23 static constexpr std::size_t DefaultMinimumLength = 2; 24 25 /// The default value for ignored parameter names. 26 static const std::string DefaultIgnoredParameterNames = 27 optutils::serializeStringList({"\"\"", "iterator", "Iterator", "begin", 28 "Begin", "end", "End", "first", "First", 29 "last", "Last", "lhs", "LHS", "rhs", "RHS"}); 30 31 /// The default value for ignored parameter type suffixes. 32 static const std::string DefaultIgnoredParameterTypeSuffixes = 33 optutils::serializeStringList({"bool", 34 "Bool", 35 "_Bool", 36 "it", 37 "It", 38 "iterator", 39 "Iterator", 40 "inputit", 41 "InputIt", 42 "forwardit", 43 "FowardIt", 44 "bidirit", 45 "BidirIt", 46 "constiterator", 47 "const_iterator", 48 "Const_Iterator", 49 "Constiterator", 50 "ConstIterator", 51 "RandomIt", 52 "randomit", 53 "random_iterator", 54 "ReverseIt", 55 "reverse_iterator", 56 "reverse_const_iterator", 57 "ConstReverseIterator", 58 "Const_Reverse_Iterator", 59 "const_reverse_iterator" 60 "Constreverseiterator", 61 "constreverseiterator"}); 62 63 /// The default value for the QualifiersMix check option. 64 static constexpr bool DefaultQualifiersMix = false; 65 66 /// The default value for the ModelImplicitConversions check option. 67 static constexpr bool DefaultModelImplicitConversions = true; 68 69 /// The default value for suppressing diagnostics about parameters that are 70 /// used together. 71 static constexpr bool DefaultSuppressParametersUsedTogether = true; 72 73 /// The default value for the NamePrefixSuffixSilenceDissimilarityTreshold 74 /// check option. 75 static constexpr std::size_t 76 DefaultNamePrefixSuffixSilenceDissimilarityTreshold = 1; 77 78 using namespace clang::ast_matchers; 79 80 namespace clang { 81 namespace tidy { 82 namespace bugprone { 83 84 using TheCheck = EasilySwappableParametersCheck; 85 86 namespace filter { 87 class SimilarlyUsedParameterPairSuppressor; 88 89 static bool isIgnoredParameter(const TheCheck &Check, const ParmVarDecl *Node); 90 static inline bool 91 isSimilarlyUsedParameter(const SimilarlyUsedParameterPairSuppressor &Suppressor, 92 const ParmVarDecl *Param1, const ParmVarDecl *Param2); 93 static bool prefixSuffixCoverUnderThreshold(std::size_t Threshold, 94 StringRef Str1, StringRef Str2); 95 } // namespace filter 96 97 namespace model { 98 99 /// The language features involved in allowing the mix between two parameters. 100 enum class MixFlags : unsigned char { 101 Invalid = 0, ///< Sentinel bit pattern. DO NOT USE! 102 103 /// Certain constructs (such as pointers to noexcept/non-noexcept functions) 104 /// have the same CanonicalType, which would result in false positives. 105 /// During the recursive modelling call, this flag is set if a later diagnosed 106 /// canonical type equivalence should be thrown away. 107 WorkaroundDisableCanonicalEquivalence = 1, 108 109 None = 2, ///< Mix between the two parameters is not possible. 110 Trivial = 4, ///< The two mix trivially, and are the exact same type. 111 Canonical = 8, ///< The two mix because the types refer to the same 112 /// CanonicalType, but we do not elaborate as to how. 113 TypeAlias = 16, ///< The path from one type to the other involves 114 /// desugaring type aliases. 115 ReferenceBind = 32, ///< The mix involves the binding power of "const &". 116 Qualifiers = 64, ///< The mix involves change in the qualifiers. 117 ImplicitConversion = 128, ///< The mixing of the parameters is possible 118 /// through implicit conversions between the types. 119 120 LLVM_MARK_AS_BITMASK_ENUM(/* LargestValue =*/ImplicitConversion) 121 }; 122 LLVM_ENABLE_BITMASK_ENUMS_IN_NAMESPACE(); 123 124 /// Returns whether the SearchedFlag is turned on in the Data. 125 static inline bool hasFlag(MixFlags Data, MixFlags SearchedFlag) { 126 assert(SearchedFlag != MixFlags::Invalid && 127 "can't be used to detect lack of all bits!"); 128 129 // "Data & SearchedFlag" would need static_cast<bool>() in conditions. 130 return (Data & SearchedFlag) == SearchedFlag; 131 } 132 133 #ifndef NDEBUG 134 135 // The modelling logic of this check is more complex than usual, and 136 // potentially hard to understand without the ability to see into the 137 // representation during the recursive descent. This debug code is only 138 // compiled in 'Debug' mode, or if LLVM_ENABLE_ASSERTIONS config is turned on. 139 140 /// Formats the MixFlags enum into a useful, user-readable representation. 141 static inline std::string formatMixFlags(MixFlags F) { 142 if (F == MixFlags::Invalid) 143 return "#Inv!"; 144 145 SmallString<8> Str{"-------"}; 146 147 if (hasFlag(F, MixFlags::None)) 148 // Shows the None bit explicitly, as it can be applied in the recursion 149 // even if other bits are set. 150 Str[0] = '!'; 151 if (hasFlag(F, MixFlags::Trivial)) 152 Str[1] = 'T'; 153 if (hasFlag(F, MixFlags::Canonical)) 154 Str[2] = 'C'; 155 if (hasFlag(F, MixFlags::TypeAlias)) 156 Str[3] = 't'; 157 if (hasFlag(F, MixFlags::ReferenceBind)) 158 Str[4] = '&'; 159 if (hasFlag(F, MixFlags::Qualifiers)) 160 Str[5] = 'Q'; 161 if (hasFlag(F, MixFlags::ImplicitConversion)) 162 Str[6] = 'i'; 163 164 if (hasFlag(F, MixFlags::WorkaroundDisableCanonicalEquivalence)) 165 Str.append("(~C)"); 166 167 return Str.str().str(); 168 } 169 170 #endif // NDEBUG 171 172 /// The results of the steps of an Implicit Conversion Sequence is saved in 173 /// an instance of this record. 174 /// 175 /// A ConversionSequence maps the steps of the conversion with a member for 176 /// each type involved in the conversion. Imagine going from a hypothetical 177 /// Complex class to projecting it to the real part as a const double. 178 /// 179 /// I.e., given: 180 /// 181 /// struct Complex { 182 /// operator double() const; 183 /// }; 184 /// 185 /// void functionBeingAnalysed(Complex C, const double R); 186 /// 187 /// we will get the following sequence: 188 /// 189 /// (Begin=) Complex 190 /// 191 /// The first standard conversion is a qualification adjustment. 192 /// (AfterFirstStandard=) const Complex 193 /// 194 /// Then the user-defined conversion is executed. 195 /// (UDConvOp.ConversionOperatorResultType=) double 196 /// 197 /// Then this 'double' is qualifier-adjusted to 'const double'. 198 /// (AfterSecondStandard=) double 199 /// 200 /// The conversion's result has now been calculated, so it ends here. 201 /// (End=) double. 202 /// 203 /// Explicit storing of Begin and End in this record is needed, because 204 /// getting to what Begin and End here are needs further resolution of types, 205 /// e.g. in the case of typedefs: 206 /// 207 /// using Comp = Complex; 208 /// using CD = const double; 209 /// void functionBeingAnalysed2(Comp C, CD R); 210 /// 211 /// In this case, the user will be diagnosed with a potential conversion 212 /// between the two typedefs as written in the code, but to elaborate the 213 /// reasoning behind this conversion, we also need to show what the typedefs 214 /// mean. See FormattedConversionSequence towards the bottom of this file! 215 struct ConversionSequence { 216 enum UserDefinedConversionKind { UDCK_None, UDCK_Ctor, UDCK_Oper }; 217 218 struct UserDefinedConvertingConstructor { 219 const CXXConstructorDecl *Fun; 220 QualType ConstructorParameterType; 221 QualType UserDefinedType; 222 }; 223 224 struct UserDefinedConversionOperator { 225 const CXXConversionDecl *Fun; 226 QualType UserDefinedType; 227 QualType ConversionOperatorResultType; 228 }; 229 230 /// The type the conversion stared from. 231 QualType Begin; 232 233 /// The intermediate type after the first Standard Conversion Sequence. 234 QualType AfterFirstStandard; 235 236 /// The details of the user-defined conversion involved, as a tagged union. 237 union { 238 char None; 239 UserDefinedConvertingConstructor UDConvCtor; 240 UserDefinedConversionOperator UDConvOp; 241 }; 242 UserDefinedConversionKind UDConvKind; 243 244 /// The intermediate type after performing the second Standard Conversion 245 /// Sequence. 246 QualType AfterSecondStandard; 247 248 /// The result type the conversion targeted. 249 QualType End; 250 251 ConversionSequence() : None(0), UDConvKind(UDCK_None) {} 252 ConversionSequence(QualType From, QualType To) 253 : Begin(From), None(0), UDConvKind(UDCK_None), End(To) {} 254 255 explicit operator bool() const { 256 return !AfterFirstStandard.isNull() || UDConvKind != UDCK_None || 257 !AfterSecondStandard.isNull(); 258 } 259 260 /// Returns all the "steps" (non-unique and non-similar) types involved in 261 /// the conversion sequence. This method does **NOT** return Begin and End. 262 SmallVector<QualType, 4> getInvolvedTypesInSequence() const { 263 SmallVector<QualType, 4> Ret; 264 auto EmplaceIfDifferent = [&Ret](QualType QT) { 265 if (QT.isNull()) 266 return; 267 if (Ret.empty()) 268 Ret.emplace_back(QT); 269 else if (Ret.back() != QT) 270 Ret.emplace_back(QT); 271 }; 272 273 EmplaceIfDifferent(AfterFirstStandard); 274 switch (UDConvKind) { 275 case UDCK_Ctor: 276 EmplaceIfDifferent(UDConvCtor.ConstructorParameterType); 277 EmplaceIfDifferent(UDConvCtor.UserDefinedType); 278 break; 279 case UDCK_Oper: 280 EmplaceIfDifferent(UDConvOp.UserDefinedType); 281 EmplaceIfDifferent(UDConvOp.ConversionOperatorResultType); 282 break; 283 case UDCK_None: 284 break; 285 } 286 EmplaceIfDifferent(AfterSecondStandard); 287 288 return Ret; 289 } 290 291 /// Updates the steps of the conversion sequence with the steps from the 292 /// other instance. 293 /// 294 /// \note This method does not check if the resulting conversion sequence is 295 /// sensible! 296 ConversionSequence &update(const ConversionSequence &RHS) { 297 if (!RHS.AfterFirstStandard.isNull()) 298 AfterFirstStandard = RHS.AfterFirstStandard; 299 switch (RHS.UDConvKind) { 300 case UDCK_Ctor: 301 UDConvKind = UDCK_Ctor; 302 UDConvCtor = RHS.UDConvCtor; 303 break; 304 case UDCK_Oper: 305 UDConvKind = UDCK_Oper; 306 UDConvOp = RHS.UDConvOp; 307 break; 308 case UDCK_None: 309 break; 310 } 311 if (!RHS.AfterSecondStandard.isNull()) 312 AfterSecondStandard = RHS.AfterSecondStandard; 313 314 return *this; 315 } 316 317 /// Sets the user-defined conversion to the given constructor. 318 void setConversion(const UserDefinedConvertingConstructor &UDCC) { 319 UDConvKind = UDCK_Ctor; 320 UDConvCtor = UDCC; 321 } 322 323 /// Sets the user-defined conversion to the given operator. 324 void setConversion(const UserDefinedConversionOperator &UDCO) { 325 UDConvKind = UDCK_Oper; 326 UDConvOp = UDCO; 327 } 328 329 /// Returns the type in the conversion that's formally "in our hands" once 330 /// the user-defined conversion is executed. 331 QualType getTypeAfterUserDefinedConversion() const { 332 switch (UDConvKind) { 333 case UDCK_Ctor: 334 return UDConvCtor.UserDefinedType; 335 case UDCK_Oper: 336 return UDConvOp.ConversionOperatorResultType; 337 case UDCK_None: 338 return {}; 339 } 340 llvm_unreachable("Invalid UDConv kind."); 341 } 342 343 const CXXMethodDecl *getUserDefinedConversionFunction() const { 344 switch (UDConvKind) { 345 case UDCK_Ctor: 346 return UDConvCtor.Fun; 347 case UDCK_Oper: 348 return UDConvOp.Fun; 349 case UDCK_None: 350 return {}; 351 } 352 llvm_unreachable("Invalid UDConv kind."); 353 } 354 355 /// Returns the SourceRange in the text that corresponds to the interesting 356 /// part of the user-defined conversion. This is either the parameter type 357 /// in a converting constructor, or the conversion result type in a conversion 358 /// operator. 359 SourceRange getUserDefinedConversionHighlight() const { 360 switch (UDConvKind) { 361 case UDCK_Ctor: 362 return UDConvCtor.Fun->getParamDecl(0)->getSourceRange(); 363 case UDCK_Oper: 364 // getReturnTypeSourceRange() does not work for CXXConversionDecls as the 365 // returned type is physically behind the declaration's name ("operator"). 366 if (const FunctionTypeLoc FTL = UDConvOp.Fun->getFunctionTypeLoc()) 367 if (const TypeLoc RetLoc = FTL.getReturnLoc()) 368 return RetLoc.getSourceRange(); 369 return {}; 370 case UDCK_None: 371 return {}; 372 } 373 llvm_unreachable("Invalid UDConv kind."); 374 } 375 }; 376 377 /// Contains the metadata for the mixability result between two types, 378 /// independently of which parameters they were calculated from. 379 struct MixData { 380 /// The flag bits of the mix indicating what language features allow for it. 381 MixFlags Flags = MixFlags::Invalid; 382 383 /// A potentially calculated common underlying type after desugaring, that 384 /// both sides of the mix can originate from. 385 QualType CommonType; 386 387 /// The steps an implicit conversion performs to get from one type to the 388 /// other. 389 ConversionSequence Conversion, ConversionRTL; 390 391 /// True if the MixData was specifically created with only a one-way 392 /// conversion modelled. 393 bool CreatedFromOneWayConversion = false; 394 395 MixData(MixFlags Flags) : Flags(Flags) {} 396 MixData(MixFlags Flags, QualType CommonType) 397 : Flags(Flags), CommonType(CommonType) {} 398 MixData(MixFlags Flags, ConversionSequence Conv) 399 : Flags(Flags), Conversion(Conv), CreatedFromOneWayConversion(true) {} 400 MixData(MixFlags Flags, ConversionSequence LTR, ConversionSequence RTL) 401 : Flags(Flags), Conversion(LTR), ConversionRTL(RTL) {} 402 MixData(MixFlags Flags, QualType CommonType, ConversionSequence LTR, 403 ConversionSequence RTL) 404 : Flags(Flags), CommonType(CommonType), Conversion(LTR), 405 ConversionRTL(RTL) {} 406 407 void sanitize() { 408 assert(Flags != MixFlags::Invalid && "sanitize() called on invalid bitvec"); 409 410 MixFlags CanonicalAndWorkaround = 411 MixFlags::Canonical | MixFlags::WorkaroundDisableCanonicalEquivalence; 412 if ((Flags & CanonicalAndWorkaround) == CanonicalAndWorkaround) { 413 // A workaround for too eagerly equivalent canonical types was requested, 414 // and a canonical equivalence was proven. Fulfill the request and throw 415 // this result away. 416 Flags = MixFlags::None; 417 return; 418 } 419 420 if (hasFlag(Flags, MixFlags::None)) { 421 // If anywhere down the recursion a potential mix "path" is deemed 422 // impossible, throw away all the other bits because the mix is not 423 // possible. 424 Flags = MixFlags::None; 425 return; 426 } 427 428 if (Flags == MixFlags::Trivial) 429 return; 430 431 if (static_cast<bool>(Flags ^ MixFlags::Trivial)) 432 // If the mix involves somewhere trivial equivalence but down the 433 // recursion other bit(s) were set, remove the trivial bit, as it is not 434 // trivial. 435 Flags &= ~MixFlags::Trivial; 436 437 bool ShouldHaveImplicitConvFlag = false; 438 if (CreatedFromOneWayConversion && Conversion) 439 ShouldHaveImplicitConvFlag = true; 440 else if (!CreatedFromOneWayConversion && Conversion && ConversionRTL) 441 // Only say that we have implicit conversion mix possibility if it is 442 // bidirectional. Otherwise, the compiler would report an *actual* swap 443 // at a call site... 444 ShouldHaveImplicitConvFlag = true; 445 446 if (ShouldHaveImplicitConvFlag) 447 Flags |= MixFlags::ImplicitConversion; 448 else 449 Flags &= ~MixFlags::ImplicitConversion; 450 } 451 452 bool isValid() const { return Flags >= MixFlags::None; } 453 454 bool indicatesMixability() const { return Flags > MixFlags::None; } 455 456 /// Add the specified flag bits to the flags. 457 MixData operator|(MixFlags EnableFlags) const { 458 if (CreatedFromOneWayConversion) { 459 MixData M{Flags | EnableFlags, Conversion}; 460 M.CommonType = CommonType; 461 return M; 462 } 463 return {Flags | EnableFlags, CommonType, Conversion, ConversionRTL}; 464 } 465 466 /// Add the specified flag bits to the flags. 467 MixData &operator|=(MixFlags EnableFlags) { 468 Flags |= EnableFlags; 469 return *this; 470 } 471 472 /// Add the specified qualifiers to the common type in the Mix. 473 MixData qualify(Qualifiers Quals) const { 474 SplitQualType Split = CommonType.split(); 475 Split.Quals.addQualifiers(Quals); 476 QualType CommonType{Split.Ty, Split.Quals.getAsOpaqueValue()}; 477 478 if (CreatedFromOneWayConversion) { 479 MixData M{Flags, Conversion}; 480 M.CommonType = CommonType; 481 return M; 482 } 483 return {Flags, CommonType, Conversion, ConversionRTL}; 484 } 485 }; 486 487 /// A named tuple that contains the information for a mix between two concrete 488 /// parameters. 489 struct Mix { 490 const ParmVarDecl *First, *Second; 491 MixData Data; 492 493 Mix(const ParmVarDecl *F, const ParmVarDecl *S, MixData Data) 494 : First(F), Second(S), Data(std::move(Data)) {} 495 496 void sanitize() { Data.sanitize(); } 497 MixFlags flags() const { return Data.Flags; } 498 bool flagsValid() const { return Data.isValid(); } 499 bool mixable() const { return Data.indicatesMixability(); } 500 QualType commonUnderlyingType() const { return Data.CommonType; } 501 const ConversionSequence &leftToRightConversionSequence() const { 502 return Data.Conversion; 503 } 504 const ConversionSequence &rightToLeftConversionSequence() const { 505 return Data.ConversionRTL; 506 } 507 }; 508 509 // NOLINTNEXTLINE(misc-redundant-expression): Seems to be a bogus warning. 510 static_assert(std::is_trivially_copyable<Mix>::value && 511 std::is_trivially_move_constructible<Mix>::value && 512 std::is_trivially_move_assignable<Mix>::value, 513 "Keep frequently used data simple!"); 514 515 struct MixableParameterRange { 516 /// A container for Mixes. 517 using MixVector = SmallVector<Mix, 8>; 518 519 /// The number of parameters iterated to build the instance. 520 std::size_t NumParamsChecked = 0; 521 522 /// The individual flags and supporting information for the mixes. 523 MixVector Mixes; 524 525 /// Gets the leftmost parameter of the range. 526 const ParmVarDecl *getFirstParam() const { 527 // The first element is the LHS of the very first mix in the range. 528 assert(!Mixes.empty()); 529 return Mixes.front().First; 530 } 531 532 /// Gets the rightmost parameter of the range. 533 const ParmVarDecl *getLastParam() const { 534 // The builder function breaks building an instance of this type if it 535 // finds something that can not be mixed with the rest, by going *forward* 536 // in the list of parameters. So at any moment of break, the RHS of the last 537 // element of the mix vector is also the last element of the mixing range. 538 assert(!Mixes.empty()); 539 return Mixes.back().Second; 540 } 541 }; 542 543 /// Helper enum for the recursive calls in the modelling that toggle what kinds 544 /// of implicit conversions are to be modelled. 545 enum class ImplicitConversionModellingMode : unsigned char { 546 /// No implicit conversions are modelled. 547 None, 548 549 /// The full implicit conversion sequence is modelled. 550 All, 551 552 /// Only model a unidirectional implicit conversion and within it only one 553 /// standard conversion sequence. 554 OneWaySingleStandardOnly 555 }; 556 557 static MixData 558 isLRefEquallyBindingToType(const TheCheck &Check, 559 const LValueReferenceType *LRef, QualType Ty, 560 const ASTContext &Ctx, bool IsRefRHS, 561 ImplicitConversionModellingMode ImplicitMode); 562 563 static MixData 564 approximateImplicitConversion(const TheCheck &Check, QualType LType, 565 QualType RType, const ASTContext &Ctx, 566 ImplicitConversionModellingMode ImplicitMode); 567 568 static inline bool isUselessSugar(const Type *T) { 569 return isa<DecayedType, ElaboratedType, ParenType>(T); 570 } 571 572 /// Approximate the way how LType and RType might refer to "essentially the 573 /// same" type, in a sense that at a particular call site, an expression of 574 /// type LType and RType might be successfully passed to a variable (in our 575 /// specific case, a parameter) of type RType and LType, respectively. 576 /// Note the swapped order! 577 /// 578 /// The returned data structure is not guaranteed to be properly set, as this 579 /// function is potentially recursive. It is the caller's responsibility to 580 /// call sanitize() on the result once the recursion is over. 581 static MixData 582 calculateMixability(const TheCheck &Check, QualType LType, QualType RType, 583 const ASTContext &Ctx, 584 ImplicitConversionModellingMode ImplicitMode) { 585 LLVM_DEBUG(llvm::dbgs() << ">>> calculateMixability for LType:\n"; 586 LType.dump(llvm::dbgs(), Ctx); llvm::dbgs() << "\nand RType:\n"; 587 RType.dump(llvm::dbgs(), Ctx); llvm::dbgs() << '\n';); 588 589 // Certain constructs match on the last catch-all getCanonicalType() equality, 590 // which is perhaps something not what we want. If this variable is true, 591 // the canonical type equality will be ignored. 592 bool RecursiveReturnDiscardingCanonicalType = false; 593 594 if (LType == RType) { 595 LLVM_DEBUG(llvm::dbgs() << "<<< calculateMixability. Trivial equality.\n"); 596 return {MixFlags::Trivial, LType}; 597 } 598 599 // Dissolve certain type sugars that do not affect the mixability of one type 600 // with the other, and also do not require any sort of elaboration for the 601 // user to understand. 602 if (isUselessSugar(LType.getTypePtr())) { 603 LLVM_DEBUG(llvm::dbgs() 604 << "--- calculateMixability. LHS is useless sugar.\n"); 605 return calculateMixability(Check, LType.getSingleStepDesugaredType(Ctx), 606 RType, Ctx, ImplicitMode); 607 } 608 if (isUselessSugar(RType.getTypePtr())) { 609 LLVM_DEBUG(llvm::dbgs() 610 << "--- calculateMixability. RHS is useless sugar.\n"); 611 return calculateMixability( 612 Check, LType, RType.getSingleStepDesugaredType(Ctx), Ctx, ImplicitMode); 613 } 614 615 // At a particular call site, what could be passed to a 'T' or 'const T' might 616 // also be passed to a 'const T &' without the call site putting a direct 617 // side effect on the passed expressions. 618 if (const auto *LRef = LType->getAs<LValueReferenceType>()) { 619 LLVM_DEBUG(llvm::dbgs() << "--- calculateMixability. LHS is &.\n"); 620 return isLRefEquallyBindingToType(Check, LRef, RType, Ctx, false, 621 ImplicitMode) | 622 MixFlags::ReferenceBind; 623 } 624 if (const auto *RRef = RType->getAs<LValueReferenceType>()) { 625 LLVM_DEBUG(llvm::dbgs() << "--- calculateMixability. RHS is &.\n"); 626 return isLRefEquallyBindingToType(Check, RRef, LType, Ctx, true, 627 ImplicitMode) | 628 MixFlags::ReferenceBind; 629 } 630 631 // Dissolve typedefs after the qualifiers outside the typedef are dealt with. 632 if (LType->getAs<TypedefType>()) { 633 LLVM_DEBUG(llvm::dbgs() << "--- calculateMixability. LHS is typedef.\n"); 634 return calculateMixability(Check, LType.getSingleStepDesugaredType(Ctx), 635 RType, Ctx, ImplicitMode) | 636 MixFlags::TypeAlias; 637 } 638 if (RType->getAs<TypedefType>()) { 639 LLVM_DEBUG(llvm::dbgs() << "--- calculateMixability. RHS is typedef.\n"); 640 return calculateMixability(Check, LType, 641 RType.getSingleStepDesugaredType(Ctx), Ctx, 642 ImplicitMode) | 643 MixFlags::TypeAlias; 644 } 645 646 // A parameter of type 'cvr1 T' and another of potentially differently 647 // qualified 'cvr2 T' may bind with the same power, if the user so requested. 648 if (LType.getLocalCVRQualifiers() != RType.getLocalCVRQualifiers()) { 649 LLVM_DEBUG(if (LType.getLocalCVRQualifiers()) llvm::dbgs() 650 << "--- calculateMixability. LHS is CVR.\n"); 651 LLVM_DEBUG(if (RType.getLocalCVRQualifiers()) llvm::dbgs() 652 << "--- calculateMixability. RHS is CVR.\n"); 653 654 if (!Check.QualifiersMix) { 655 LLVM_DEBUG(llvm::dbgs() 656 << "<<< calculateMixability. QualifiersMix turned off.\n"); 657 return {MixFlags::None}; 658 } 659 660 return calculateMixability(Check, LType.getLocalUnqualifiedType(), 661 RType.getLocalUnqualifiedType(), Ctx, 662 ImplicitMode) | 663 MixFlags::Qualifiers; 664 } 665 if (LType.getLocalCVRQualifiers() == RType.getLocalCVRQualifiers() && 666 LType.getLocalCVRQualifiers() != 0) { 667 LLVM_DEBUG(llvm::dbgs() 668 << "--- calculateMixability. LHS and RHS same CVR.\n"); 669 // Apply the same qualifier back into the found common type if we found 670 // a common type between the unqualified versions. 671 return calculateMixability(Check, LType.getLocalUnqualifiedType(), 672 RType.getLocalUnqualifiedType(), Ctx, 673 ImplicitMode) 674 .qualify(LType.getLocalQualifiers()); 675 } 676 677 if (LType->isPointerType() && RType->isPointerType()) { 678 // If both types are pointers, and pointed to the exact same type, 679 // LType == RType took care of that. Try to see if the pointee type has 680 // some other match. However, this must not consider implicit conversions. 681 LLVM_DEBUG(llvm::dbgs() 682 << "--- calculateMixability. LHS and RHS are Ptrs.\n"); 683 MixData MixOfPointee = calculateMixability( 684 Check, LType->getPointeeType(), RType->getPointeeType(), Ctx, 685 ImplicitConversionModellingMode::None); 686 if (hasFlag(MixOfPointee.Flags, 687 MixFlags::WorkaroundDisableCanonicalEquivalence)) 688 RecursiveReturnDiscardingCanonicalType = true; 689 690 MixOfPointee.sanitize(); 691 if (MixOfPointee.indicatesMixability()) { 692 LLVM_DEBUG(llvm::dbgs() 693 << "<<< calculateMixability. Pointees are mixable.\n"); 694 return MixOfPointee; 695 } 696 } 697 698 if (ImplicitMode > ImplicitConversionModellingMode::None) { 699 LLVM_DEBUG(llvm::dbgs() << "--- calculateMixability. Start implicit...\n"); 700 MixData MixLTR = 701 approximateImplicitConversion(Check, LType, RType, Ctx, ImplicitMode); 702 LLVM_DEBUG( 703 if (hasFlag(MixLTR.Flags, MixFlags::ImplicitConversion)) llvm::dbgs() 704 << "--- calculateMixability. Implicit Left -> Right found.\n";); 705 706 if (ImplicitMode == 707 ImplicitConversionModellingMode::OneWaySingleStandardOnly && 708 MixLTR.Conversion && !MixLTR.Conversion.AfterFirstStandard.isNull() && 709 MixLTR.Conversion.UDConvKind == ConversionSequence::UDCK_None && 710 MixLTR.Conversion.AfterSecondStandard.isNull()) { 711 // The invoker of the method requested only modelling a single standard 712 // conversion, in only the forward direction, and they got just that. 713 LLVM_DEBUG(llvm::dbgs() << "<<< calculateMixability. Implicit " 714 "conversion, one-way, standard-only.\n"); 715 return {MixFlags::ImplicitConversion, MixLTR.Conversion}; 716 } 717 718 // Otherwise if the invoker requested a full modelling, do the other 719 // direction as well. 720 MixData MixRTL = 721 approximateImplicitConversion(Check, RType, LType, Ctx, ImplicitMode); 722 LLVM_DEBUG( 723 if (hasFlag(MixRTL.Flags, MixFlags::ImplicitConversion)) llvm::dbgs() 724 << "--- calculateMixability. Implicit Right -> Left found.\n";); 725 726 if (MixLTR.Conversion && MixRTL.Conversion) { 727 LLVM_DEBUG( 728 llvm::dbgs() 729 << "<<< calculateMixability. Implicit conversion, bidirectional.\n"); 730 return {MixFlags::ImplicitConversion, MixLTR.Conversion, 731 MixRTL.Conversion}; 732 } 733 } 734 735 if (RecursiveReturnDiscardingCanonicalType) 736 LLVM_DEBUG(llvm::dbgs() << "--- calculateMixability. Before CanonicalType, " 737 "Discard was enabled.\n"); 738 739 // Certain kinds unfortunately need to be side-stepped for canonical type 740 // matching. 741 if (LType->getAs<FunctionProtoType>() || RType->getAs<FunctionProtoType>()) { 742 // Unfortunately, the canonical type of a function pointer becomes the 743 // same even if exactly one is "noexcept" and the other isn't, making us 744 // give a false positive report irrespective of implicit conversions. 745 LLVM_DEBUG(llvm::dbgs() 746 << "--- calculateMixability. Discarding potential canonical " 747 "equivalence on FunctionProtoTypes.\n"); 748 RecursiveReturnDiscardingCanonicalType = true; 749 } 750 751 MixData MixToReturn{MixFlags::None}; 752 753 // If none of the previous logic found a match, try if Clang otherwise 754 // believes the types to be the same. 755 QualType LCanonical = LType.getCanonicalType(); 756 if (LCanonical == RType.getCanonicalType()) { 757 LLVM_DEBUG(llvm::dbgs() 758 << "<<< calculateMixability. Same CanonicalType.\n"); 759 MixToReturn = {MixFlags::Canonical, LCanonical}; 760 } 761 762 if (RecursiveReturnDiscardingCanonicalType) 763 MixToReturn |= MixFlags::WorkaroundDisableCanonicalEquivalence; 764 765 LLVM_DEBUG(if (MixToReturn.Flags == MixFlags::None) llvm::dbgs() 766 << "<<< calculateMixability. No match found.\n"); 767 return MixToReturn; 768 } 769 770 /// Calculates if the reference binds an expression of the given type. This is 771 /// true iff 'LRef' is some 'const T &' type, and the 'Ty' is 'T' or 'const T'. 772 /// 773 /// \param ImplicitMode is forwarded in the possible recursive call to 774 /// calculateMixability. 775 static MixData 776 isLRefEquallyBindingToType(const TheCheck &Check, 777 const LValueReferenceType *LRef, QualType Ty, 778 const ASTContext &Ctx, bool IsRefRHS, 779 ImplicitConversionModellingMode ImplicitMode) { 780 LLVM_DEBUG(llvm::dbgs() << ">>> isLRefEquallyBindingToType for LRef:\n"; 781 LRef->dump(llvm::dbgs(), Ctx); llvm::dbgs() << "\nand Type:\n"; 782 Ty.dump(llvm::dbgs(), Ctx); llvm::dbgs() << '\n';); 783 784 QualType ReferredType = LRef->getPointeeType(); 785 if (!ReferredType.isLocalConstQualified() && 786 ReferredType->getAs<TypedefType>()) { 787 LLVM_DEBUG( 788 llvm::dbgs() 789 << "--- isLRefEquallyBindingToType. Non-const LRef to Typedef.\n"); 790 ReferredType = ReferredType.getDesugaredType(Ctx); 791 if (!ReferredType.isLocalConstQualified()) { 792 LLVM_DEBUG(llvm::dbgs() 793 << "<<< isLRefEquallyBindingToType. Typedef is not const.\n"); 794 return {MixFlags::None}; 795 } 796 797 LLVM_DEBUG(llvm::dbgs() << "--- isLRefEquallyBindingToType. Typedef is " 798 "const, considering as const LRef.\n"); 799 } else if (!ReferredType.isLocalConstQualified()) { 800 LLVM_DEBUG(llvm::dbgs() 801 << "<<< isLRefEquallyBindingToType. Not const LRef.\n"); 802 return {MixFlags::None}; 803 }; 804 805 assert(ReferredType.isLocalConstQualified() && 806 "Reaching this point means we are sure LRef is effectively a const&."); 807 808 if (ReferredType == Ty) { 809 LLVM_DEBUG( 810 llvm::dbgs() 811 << "<<< isLRefEquallyBindingToType. Type of referred matches.\n"); 812 return {MixFlags::Trivial, ReferredType}; 813 } 814 815 QualType NonConstReferredType = ReferredType; 816 NonConstReferredType.removeLocalConst(); 817 if (NonConstReferredType == Ty) { 818 LLVM_DEBUG(llvm::dbgs() << "<<< isLRefEquallyBindingToType. Type of " 819 "referred matches to non-const qualified.\n"); 820 return {MixFlags::Trivial, NonConstReferredType}; 821 } 822 823 LLVM_DEBUG( 824 llvm::dbgs() 825 << "--- isLRefEquallyBindingToType. Checking mix for underlying type.\n"); 826 return IsRefRHS ? calculateMixability(Check, Ty, NonConstReferredType, Ctx, 827 ImplicitMode) 828 : calculateMixability(Check, NonConstReferredType, Ty, Ctx, 829 ImplicitMode); 830 } 831 832 static inline bool isDerivedToBase(const CXXRecordDecl *Derived, 833 const CXXRecordDecl *Base) { 834 return Derived && Base && Derived->isCompleteDefinition() && 835 Base->isCompleteDefinition() && Derived->isDerivedFrom(Base); 836 } 837 838 static Optional<QualType> 839 approximateStandardConversionSequence(const TheCheck &Check, QualType From, 840 QualType To, const ASTContext &Ctx) { 841 LLVM_DEBUG(llvm::dbgs() << ">>> approximateStdConv for LType:\n"; 842 From.dump(llvm::dbgs(), Ctx); llvm::dbgs() << "\nand RType:\n"; 843 To.dump(llvm::dbgs(), Ctx); llvm::dbgs() << '\n';); 844 845 // A standard conversion sequence consists of the following, in order: 846 // * Maybe either LValue->RValue conv., Array->Ptr conv., Function->Ptr conv. 847 // * Maybe Numeric promotion or conversion. 848 // * Maybe function pointer conversion. 849 // * Maybe qualifier adjustments. 850 QualType WorkType = From; 851 // Get out the qualifiers of the original type. This will always be 852 // re-applied to the WorkType to ensure it is the same qualification as the 853 // original From was. 854 auto QualifiersToApply = From.split().Quals.getAsOpaqueValue(); 855 856 // LValue->RValue is irrelevant for the check, because it is a thing to be 857 // done at a call site, and will be performed if need be performed. 858 859 // Array->Ptr decay. 860 if (const auto *ArrayT = dyn_cast<ArrayType>(From)) { 861 LLVM_DEBUG(llvm::dbgs() << "--- approximateStdConv. Array->Ptr decayed.\n"); 862 WorkType = ArrayT->getPointeeType(); 863 } 864 865 // Function->Pointer conversions are also irrelevant, because a 866 // "FunctionType" cannot be the type of a parameter variable, so this 867 // conversion is only meaningful at call sites. 868 869 // Numeric promotions and conversions. 870 const auto *FromBuiltin = WorkType->getAs<BuiltinType>(); 871 const auto *ToBuiltin = To->getAs<BuiltinType>(); 872 bool FromNumeric = FromBuiltin && (FromBuiltin->isIntegerType() || 873 FromBuiltin->isFloatingType()); 874 bool ToNumeric = 875 ToBuiltin && (ToBuiltin->isIntegerType() || ToBuiltin->isFloatingType()); 876 if (FromNumeric && ToNumeric) { 877 // If both are integral types, the numeric conversion is performed. 878 // Reapply the qualifiers of the original type, however, so 879 // "const int -> double" in this case moves over to 880 // "const double -> double". 881 LLVM_DEBUG(llvm::dbgs() 882 << "--- approximateStdConv. Conversion between numerics.\n"); 883 WorkType = QualType{ToBuiltin, QualifiersToApply}; 884 } 885 886 const auto *FromEnum = WorkType->getAs<EnumType>(); 887 const auto *ToEnum = To->getAs<EnumType>(); 888 if (FromEnum && ToNumeric && FromEnum->isUnscopedEnumerationType()) { 889 // Unscoped enumerations (or enumerations in C) convert to numerics. 890 LLVM_DEBUG(llvm::dbgs() 891 << "--- approximateStdConv. Unscoped enum to numeric.\n"); 892 WorkType = QualType{ToBuiltin, QualifiersToApply}; 893 } else if (FromNumeric && ToEnum && ToEnum->isUnscopedEnumerationType()) { 894 // Numeric types convert to enumerations only in C. 895 if (Ctx.getLangOpts().CPlusPlus) { 896 LLVM_DEBUG(llvm::dbgs() << "<<< approximateStdConv. Numeric to unscoped " 897 "enum, not possible in C++!\n"); 898 return {}; 899 } 900 901 LLVM_DEBUG(llvm::dbgs() 902 << "--- approximateStdConv. Numeric to unscoped enum.\n"); 903 WorkType = QualType{ToEnum, QualifiersToApply}; 904 } 905 906 // Check for pointer conversions. 907 const auto *FromPtr = WorkType->getAs<PointerType>(); 908 const auto *ToPtr = To->getAs<PointerType>(); 909 if (FromPtr && ToPtr) { 910 if (ToPtr->isVoidPointerType()) { 911 LLVM_DEBUG(llvm::dbgs() << "--- approximateStdConv. To void pointer.\n"); 912 WorkType = QualType{ToPtr, QualifiersToApply}; 913 } 914 915 const auto *FromRecordPtr = FromPtr->getPointeeCXXRecordDecl(); 916 const auto *ToRecordPtr = ToPtr->getPointeeCXXRecordDecl(); 917 if (isDerivedToBase(FromRecordPtr, ToRecordPtr)) { 918 LLVM_DEBUG(llvm::dbgs() << "--- approximateStdConv. Derived* to Base*\n"); 919 WorkType = QualType{ToPtr, QualifiersToApply}; 920 } 921 } 922 923 // Model the slicing Derived-to-Base too, as "BaseT temporary = derived;" 924 // can also be compiled. 925 const auto *FromRecord = WorkType->getAsCXXRecordDecl(); 926 const auto *ToRecord = To->getAsCXXRecordDecl(); 927 if (isDerivedToBase(FromRecord, ToRecord)) { 928 LLVM_DEBUG(llvm::dbgs() << "--- approximateStdConv. Derived To Base.\n"); 929 WorkType = QualType{ToRecord->getTypeForDecl(), QualifiersToApply}; 930 } 931 932 if (Ctx.getLangOpts().CPlusPlus17 && FromPtr && ToPtr) { 933 // Function pointer conversion: A noexcept function pointer can be passed 934 // to a non-noexcept one. 935 const auto *FromFunctionPtr = 936 FromPtr->getPointeeType()->getAs<FunctionProtoType>(); 937 const auto *ToFunctionPtr = 938 ToPtr->getPointeeType()->getAs<FunctionProtoType>(); 939 if (FromFunctionPtr && ToFunctionPtr && 940 FromFunctionPtr->hasNoexceptExceptionSpec() && 941 !ToFunctionPtr->hasNoexceptExceptionSpec()) { 942 LLVM_DEBUG(llvm::dbgs() << "--- approximateStdConv. noexcept function " 943 "pointer to non-noexcept.\n"); 944 WorkType = QualType{ToPtr, QualifiersToApply}; 945 } 946 } 947 948 // Qualifier adjustments are modelled according to the user's request in 949 // the QualifiersMix check config. 950 LLVM_DEBUG(llvm::dbgs() 951 << "--- approximateStdConv. Trying qualifier adjustment...\n"); 952 MixData QualConv = calculateMixability(Check, WorkType, To, Ctx, 953 ImplicitConversionModellingMode::None); 954 QualConv.sanitize(); 955 if (hasFlag(QualConv.Flags, MixFlags::Qualifiers)) { 956 LLVM_DEBUG(llvm::dbgs() 957 << "<<< approximateStdConv. Qualifiers adjusted.\n"); 958 WorkType = To; 959 } 960 961 if (WorkType == To) { 962 LLVM_DEBUG(llvm::dbgs() << "<<< approximateStdConv. Reached 'To' type.\n"); 963 return {WorkType}; 964 } 965 966 LLVM_DEBUG(llvm::dbgs() << "<<< approximateStdConv. Did not reach 'To'.\n"); 967 return {}; 968 } 969 970 namespace { 971 972 /// Helper class for storing possible user-defined conversion calls that 973 /// *could* take place in an implicit conversion, and selecting the one that 974 /// most likely *does*, if any. 975 class UserDefinedConversionSelector { 976 public: 977 /// The conversion associated with a conversion function, together with the 978 /// mixability flags of the conversion function's parameter or return type 979 /// to the rest of the sequence the selector is used in, and the sequence 980 /// that applied through the conversion itself. 981 struct PreparedConversion { 982 const CXXMethodDecl *ConversionFun; 983 MixFlags Flags; 984 ConversionSequence Seq; 985 986 PreparedConversion(const CXXMethodDecl *CMD, MixFlags F, 987 ConversionSequence S) 988 : ConversionFun(CMD), Flags(F), Seq(S) {} 989 }; 990 991 UserDefinedConversionSelector(const TheCheck &Check) : Check(Check) {} 992 993 /// Adds the conversion between the two types for the given function into 994 /// the possible implicit conversion set. FromType and ToType is either: 995 /// * the result of a standard sequence and a converting ctor parameter 996 /// * the return type of a conversion operator and the expected target of 997 /// an implicit conversion. 998 void addConversion(const CXXMethodDecl *ConvFun, QualType FromType, 999 QualType ToType) { 1000 // Try to go from the FromType to the ToType wiht only a single implicit 1001 // conversion, to see if the conversion function is applicable. 1002 MixData Mix = calculateMixability( 1003 Check, FromType, ToType, ConvFun->getASTContext(), 1004 ImplicitConversionModellingMode::OneWaySingleStandardOnly); 1005 Mix.sanitize(); 1006 if (!Mix.indicatesMixability()) 1007 return; 1008 1009 LLVM_DEBUG(llvm::dbgs() << "--- tryConversion. Found viable with flags: " 1010 << formatMixFlags(Mix.Flags) << '\n'); 1011 FlaggedConversions.emplace_back(ConvFun, Mix.Flags, Mix.Conversion); 1012 } 1013 1014 /// Selects the best conversion function that is applicable from the 1015 /// prepared set of potential conversion functions taken. 1016 Optional<PreparedConversion> operator()() const { 1017 if (FlaggedConversions.empty()) { 1018 LLVM_DEBUG(llvm::dbgs() << "--- selectUserDefinedConv. Empty.\n"); 1019 return {}; 1020 } 1021 if (FlaggedConversions.size() == 1) { 1022 LLVM_DEBUG(llvm::dbgs() << "--- selectUserDefinedConv. Single.\n"); 1023 return FlaggedConversions.front(); 1024 } 1025 1026 Optional<PreparedConversion> BestConversion; 1027 unsigned short HowManyGoodConversions = 0; 1028 for (const auto &Prepared : FlaggedConversions) { 1029 LLVM_DEBUG(llvm::dbgs() << "--- selectUserDefinedConv. Candidate flags: " 1030 << formatMixFlags(Prepared.Flags) << '\n'); 1031 if (!BestConversion) { 1032 BestConversion = Prepared; 1033 ++HowManyGoodConversions; 1034 continue; 1035 } 1036 1037 bool BestConversionHasImplicit = 1038 hasFlag(BestConversion->Flags, MixFlags::ImplicitConversion); 1039 bool ThisConversionHasImplicit = 1040 hasFlag(Prepared.Flags, MixFlags::ImplicitConversion); 1041 if (!BestConversionHasImplicit && ThisConversionHasImplicit) 1042 // This is a worse conversion, because a better one was found earlier. 1043 continue; 1044 1045 if (BestConversionHasImplicit && !ThisConversionHasImplicit) { 1046 // If the so far best selected conversion needs a previous implicit 1047 // conversion to match the user-defined converting function, but this 1048 // conversion does not, this is a better conversion, and we can throw 1049 // away the previously selected conversion(s). 1050 BestConversion = Prepared; 1051 HowManyGoodConversions = 1; 1052 continue; 1053 } 1054 1055 if (BestConversionHasImplicit == ThisConversionHasImplicit) 1056 // The current conversion is the same in term of goodness than the 1057 // already selected one. 1058 ++HowManyGoodConversions; 1059 } 1060 1061 if (HowManyGoodConversions == 1) { 1062 LLVM_DEBUG(llvm::dbgs() 1063 << "--- selectUserDefinedConv. Unique result. Flags: " 1064 << formatMixFlags(BestConversion->Flags) << '\n'); 1065 return BestConversion; 1066 } 1067 1068 LLVM_DEBUG(llvm::dbgs() 1069 << "--- selectUserDefinedConv. No, or ambiguous.\n"); 1070 return {}; 1071 } 1072 1073 private: 1074 llvm::SmallVector<PreparedConversion, 2> FlaggedConversions; 1075 const TheCheck &Check; 1076 }; 1077 1078 } // namespace 1079 1080 static Optional<ConversionSequence> 1081 tryConversionOperators(const TheCheck &Check, const CXXRecordDecl *RD, 1082 QualType ToType) { 1083 if (!RD || !RD->isCompleteDefinition()) 1084 return {}; 1085 RD = RD->getDefinition(); 1086 1087 LLVM_DEBUG(llvm::dbgs() << ">>> tryConversionOperators: " << RD->getName() 1088 << " to:\n"; 1089 ToType.dump(llvm::dbgs(), RD->getASTContext()); 1090 llvm::dbgs() << '\n';); 1091 1092 UserDefinedConversionSelector ConversionSet{Check}; 1093 1094 for (const NamedDecl *Method : RD->getVisibleConversionFunctions()) { 1095 const auto *Con = dyn_cast<CXXConversionDecl>(Method); 1096 if (!Con || Con->isExplicit()) 1097 continue; 1098 LLVM_DEBUG(llvm::dbgs() << "--- tryConversionOperators. Trying:\n"; 1099 Con->dump(llvm::dbgs()); llvm::dbgs() << '\n';); 1100 1101 // Try to go from the result of conversion operator to the expected type, 1102 // without calculating another user-defined conversion. 1103 ConversionSet.addConversion(Con, Con->getConversionType(), ToType); 1104 } 1105 1106 if (Optional<UserDefinedConversionSelector::PreparedConversion> 1107 SelectedConversion = ConversionSet()) { 1108 QualType RecordType{RD->getTypeForDecl(), 0}; 1109 1110 ConversionSequence Result{RecordType, ToType}; 1111 // The conversion from the operator call's return type to ToType was 1112 // modelled as a "pre-conversion" in the operator call, but it is the 1113 // "post-conversion" from the point of view of the original conversion 1114 // we are modelling. 1115 Result.AfterSecondStandard = SelectedConversion->Seq.AfterFirstStandard; 1116 1117 ConversionSequence::UserDefinedConversionOperator ConvOp; 1118 ConvOp.Fun = cast<CXXConversionDecl>(SelectedConversion->ConversionFun); 1119 ConvOp.UserDefinedType = RecordType; 1120 ConvOp.ConversionOperatorResultType = ConvOp.Fun->getConversionType(); 1121 Result.setConversion(ConvOp); 1122 1123 LLVM_DEBUG(llvm::dbgs() << "<<< tryConversionOperators. Found result.\n"); 1124 return Result; 1125 } 1126 1127 LLVM_DEBUG(llvm::dbgs() << "<<< tryConversionOperators. No conversion.\n"); 1128 return {}; 1129 } 1130 1131 static Optional<ConversionSequence> 1132 tryConvertingConstructors(const TheCheck &Check, QualType FromType, 1133 const CXXRecordDecl *RD) { 1134 if (!RD || !RD->isCompleteDefinition()) 1135 return {}; 1136 RD = RD->getDefinition(); 1137 1138 LLVM_DEBUG(llvm::dbgs() << ">>> tryConveringConstructors: " << RD->getName() 1139 << " from:\n"; 1140 FromType.dump(llvm::dbgs(), RD->getASTContext()); 1141 llvm::dbgs() << '\n';); 1142 1143 UserDefinedConversionSelector ConversionSet{Check}; 1144 1145 for (const CXXConstructorDecl *Con : RD->ctors()) { 1146 if (Con->isCopyOrMoveConstructor() || 1147 !Con->isConvertingConstructor(/* AllowExplicit =*/false)) 1148 continue; 1149 LLVM_DEBUG(llvm::dbgs() << "--- tryConvertingConstructors. Trying:\n"; 1150 Con->dump(llvm::dbgs()); llvm::dbgs() << '\n';); 1151 1152 // Try to go from the original FromType to the converting constructor's 1153 // parameter type without another user-defined conversion. 1154 ConversionSet.addConversion(Con, FromType, Con->getParamDecl(0)->getType()); 1155 } 1156 1157 if (Optional<UserDefinedConversionSelector::PreparedConversion> 1158 SelectedConversion = ConversionSet()) { 1159 QualType RecordType{RD->getTypeForDecl(), 0}; 1160 1161 ConversionSequence Result{FromType, RecordType}; 1162 Result.AfterFirstStandard = SelectedConversion->Seq.AfterFirstStandard; 1163 1164 ConversionSequence::UserDefinedConvertingConstructor Ctor; 1165 Ctor.Fun = cast<CXXConstructorDecl>(SelectedConversion->ConversionFun); 1166 Ctor.ConstructorParameterType = Ctor.Fun->getParamDecl(0)->getType(); 1167 Ctor.UserDefinedType = RecordType; 1168 Result.setConversion(Ctor); 1169 1170 LLVM_DEBUG(llvm::dbgs() 1171 << "<<< tryConvertingConstructors. Found result.\n"); 1172 return Result; 1173 } 1174 1175 LLVM_DEBUG(llvm::dbgs() << "<<< tryConvertingConstructors. No conversion.\n"); 1176 return {}; 1177 } 1178 1179 /// Returns whether an expression of LType can be used in an RType context, as 1180 /// per the implicit conversion rules. 1181 /// 1182 /// Note: the result of this operation, unlike that of calculateMixability, is 1183 /// **NOT** symmetric. 1184 static MixData 1185 approximateImplicitConversion(const TheCheck &Check, QualType LType, 1186 QualType RType, const ASTContext &Ctx, 1187 ImplicitConversionModellingMode ImplicitMode) { 1188 LLVM_DEBUG(llvm::dbgs() << ">>> approximateImplicitConversion for LType:\n"; 1189 LType.dump(llvm::dbgs(), Ctx); llvm::dbgs() << "\nand RType:\n"; 1190 RType.dump(llvm::dbgs(), Ctx); 1191 llvm::dbgs() << "\nimplicit mode: "; switch (ImplicitMode) { 1192 case ImplicitConversionModellingMode::None: 1193 llvm::dbgs() << "None"; 1194 break; 1195 case ImplicitConversionModellingMode::All: 1196 llvm::dbgs() << "All"; 1197 break; 1198 case ImplicitConversionModellingMode::OneWaySingleStandardOnly: 1199 llvm::dbgs() << "OneWay, Single, STD Only"; 1200 break; 1201 } llvm::dbgs() << '\n';); 1202 if (LType == RType) 1203 return {MixFlags::Trivial, LType}; 1204 1205 // An implicit conversion sequence consists of the following, in order: 1206 // * Maybe standard conversion sequence. 1207 // * Maybe user-defined conversion. 1208 // * Maybe standard conversion sequence. 1209 ConversionSequence ImplicitSeq{LType, RType}; 1210 QualType WorkType = LType; 1211 1212 Optional<QualType> AfterFirstStdConv = 1213 approximateStandardConversionSequence(Check, LType, RType, Ctx); 1214 if (AfterFirstStdConv) { 1215 LLVM_DEBUG(llvm::dbgs() << "--- approximateImplicitConversion. Standard " 1216 "Pre-Conversion found!\n"); 1217 ImplicitSeq.AfterFirstStandard = AfterFirstStdConv.getValue(); 1218 WorkType = ImplicitSeq.AfterFirstStandard; 1219 } 1220 1221 if (ImplicitMode == ImplicitConversionModellingMode::OneWaySingleStandardOnly) 1222 // If the caller only requested modelling of a standard conversion, bail. 1223 return {ImplicitSeq.AfterFirstStandard.isNull() 1224 ? MixFlags::None 1225 : MixFlags::ImplicitConversion, 1226 ImplicitSeq}; 1227 1228 if (Ctx.getLangOpts().CPlusPlus) { 1229 bool FoundConversionOperator = false, FoundConvertingCtor = false; 1230 1231 if (const auto *LRD = WorkType->getAsCXXRecordDecl()) { 1232 Optional<ConversionSequence> ConversionOperatorResult = 1233 tryConversionOperators(Check, LRD, RType); 1234 if (ConversionOperatorResult) { 1235 LLVM_DEBUG(llvm::dbgs() << "--- approximateImplicitConversion. Found " 1236 "conversion operator.\n"); 1237 ImplicitSeq.update(ConversionOperatorResult.getValue()); 1238 WorkType = ImplicitSeq.getTypeAfterUserDefinedConversion(); 1239 FoundConversionOperator = true; 1240 } 1241 } 1242 1243 if (const auto *RRD = RType->getAsCXXRecordDecl()) { 1244 // Use the original "LType" here, and not WorkType, because the 1245 // conversion to the converting constructors' parameters will be 1246 // modelled in the recursive call. 1247 Optional<ConversionSequence> ConvCtorResult = 1248 tryConvertingConstructors(Check, LType, RRD); 1249 if (ConvCtorResult) { 1250 LLVM_DEBUG(llvm::dbgs() << "--- approximateImplicitConversion. Found " 1251 "converting constructor.\n"); 1252 ImplicitSeq.update(ConvCtorResult.getValue()); 1253 WorkType = ImplicitSeq.getTypeAfterUserDefinedConversion(); 1254 FoundConvertingCtor = true; 1255 } 1256 } 1257 1258 if (FoundConversionOperator && FoundConvertingCtor) { 1259 // If both an operator and a ctor matches, the sequence is ambiguous. 1260 LLVM_DEBUG(llvm::dbgs() 1261 << "<<< approximateImplicitConversion. Found both " 1262 "user-defined conversion kinds in the same sequence!\n"); 1263 return {MixFlags::None}; 1264 } 1265 } 1266 1267 // After the potential user-defined conversion, another standard conversion 1268 // sequence might exist. 1269 LLVM_DEBUG( 1270 llvm::dbgs() 1271 << "--- approximateImplicitConversion. Try to find post-conversion.\n"); 1272 MixData SecondStdConv = approximateImplicitConversion( 1273 Check, WorkType, RType, Ctx, 1274 ImplicitConversionModellingMode::OneWaySingleStandardOnly); 1275 if (SecondStdConv.indicatesMixability()) { 1276 LLVM_DEBUG(llvm::dbgs() << "--- approximateImplicitConversion. Standard " 1277 "Post-Conversion found!\n"); 1278 1279 // The single-step modelling puts the modelled conversion into the "PreStd" 1280 // variable in the recursive call, but from the PoV of this function, it is 1281 // the post-conversion. 1282 ImplicitSeq.AfterSecondStandard = 1283 SecondStdConv.Conversion.AfterFirstStandard; 1284 WorkType = ImplicitSeq.AfterSecondStandard; 1285 } 1286 1287 if (ImplicitSeq) { 1288 LLVM_DEBUG(llvm::dbgs() 1289 << "<<< approximateImplicitConversion. Found a conversion.\n"); 1290 return {MixFlags::ImplicitConversion, ImplicitSeq}; 1291 } 1292 1293 LLVM_DEBUG( 1294 llvm::dbgs() << "<<< approximateImplicitConversion. No match found.\n"); 1295 return {MixFlags::None}; 1296 } 1297 1298 static MixableParameterRange modelMixingRange( 1299 const TheCheck &Check, const FunctionDecl *FD, std::size_t StartIndex, 1300 const filter::SimilarlyUsedParameterPairSuppressor &UsageBasedSuppressor) { 1301 std::size_t NumParams = FD->getNumParams(); 1302 assert(StartIndex < NumParams && "out of bounds for start"); 1303 const ASTContext &Ctx = FD->getASTContext(); 1304 1305 MixableParameterRange Ret; 1306 // A parameter at index 'StartIndex' had been trivially "checked". 1307 Ret.NumParamsChecked = 1; 1308 1309 for (std::size_t I = StartIndex + 1; I < NumParams; ++I) { 1310 const ParmVarDecl *Ith = FD->getParamDecl(I); 1311 StringRef ParamName = Ith->getName(); 1312 LLVM_DEBUG(llvm::dbgs() 1313 << "Check param #" << I << " '" << ParamName << "'...\n"); 1314 if (filter::isIgnoredParameter(Check, Ith)) { 1315 LLVM_DEBUG(llvm::dbgs() << "Param #" << I << " is ignored. Break!\n"); 1316 break; 1317 } 1318 1319 StringRef PrevParamName = FD->getParamDecl(I - 1)->getName(); 1320 if (!ParamName.empty() && !PrevParamName.empty() && 1321 filter::prefixSuffixCoverUnderThreshold( 1322 Check.NamePrefixSuffixSilenceDissimilarityTreshold, PrevParamName, 1323 ParamName)) { 1324 LLVM_DEBUG(llvm::dbgs() << "Parameter '" << ParamName 1325 << "' follows a pattern with previous parameter '" 1326 << PrevParamName << "'. Break!\n"); 1327 break; 1328 } 1329 1330 // Now try to go forward and build the range of [Start, ..., I, I + 1, ...] 1331 // parameters that can be messed up at a call site. 1332 MixableParameterRange::MixVector MixesOfIth; 1333 for (std::size_t J = StartIndex; J < I; ++J) { 1334 const ParmVarDecl *Jth = FD->getParamDecl(J); 1335 LLVM_DEBUG(llvm::dbgs() 1336 << "Check mix of #" << J << " against #" << I << "...\n"); 1337 1338 if (isSimilarlyUsedParameter(UsageBasedSuppressor, Ith, Jth)) { 1339 // Consider the two similarly used parameters to not be possible in a 1340 // mix-up at the user's request, if they enabled this heuristic. 1341 LLVM_DEBUG(llvm::dbgs() << "Parameters #" << I << " and #" << J 1342 << " deemed related, ignoring...\n"); 1343 1344 // If the parameter #I and #J mixes, then I is mixable with something 1345 // in the current range, so the range has to be broken and I not 1346 // included. 1347 MixesOfIth.clear(); 1348 break; 1349 } 1350 1351 Mix M{Jth, Ith, 1352 calculateMixability(Check, Jth->getType(), Ith->getType(), Ctx, 1353 Check.ModelImplicitConversions 1354 ? ImplicitConversionModellingMode::All 1355 : ImplicitConversionModellingMode::None)}; 1356 LLVM_DEBUG(llvm::dbgs() << "Mix flags (raw) : " 1357 << formatMixFlags(M.flags()) << '\n'); 1358 M.sanitize(); 1359 LLVM_DEBUG(llvm::dbgs() << "Mix flags (after sanitize): " 1360 << formatMixFlags(M.flags()) << '\n'); 1361 1362 assert(M.flagsValid() && "All flags decayed!"); 1363 1364 if (M.mixable()) 1365 MixesOfIth.emplace_back(std::move(M)); 1366 } 1367 1368 if (MixesOfIth.empty()) { 1369 // If there weren't any new mixes stored for Ith, the range is 1370 // [Start, ..., I]. 1371 LLVM_DEBUG(llvm::dbgs() 1372 << "Param #" << I 1373 << " does not mix with any in the current range. Break!\n"); 1374 break; 1375 } 1376 1377 Ret.Mixes.insert(Ret.Mixes.end(), MixesOfIth.begin(), MixesOfIth.end()); 1378 ++Ret.NumParamsChecked; // Otherwise a new param was iterated. 1379 } 1380 1381 return Ret; 1382 } 1383 1384 } // namespace model 1385 1386 /// Matches DeclRefExprs and their ignorable wrappers to ParmVarDecls. 1387 AST_MATCHER_FUNCTION(ast_matchers::internal::Matcher<Stmt>, paramRefExpr) { 1388 return expr(ignoringParenImpCasts(ignoringElidableConstructorCall( 1389 declRefExpr(to(parmVarDecl().bind("param")))))); 1390 } 1391 1392 namespace filter { 1393 1394 /// Returns whether the parameter's name or the parameter's type's name is 1395 /// configured by the user to be ignored from analysis and diagnostic. 1396 static bool isIgnoredParameter(const TheCheck &Check, const ParmVarDecl *Node) { 1397 LLVM_DEBUG(llvm::dbgs() << "Checking if '" << Node->getName() 1398 << "' is ignored.\n"); 1399 1400 if (!Node->getIdentifier()) 1401 return llvm::find(Check.IgnoredParameterNames, "\"\"") != 1402 Check.IgnoredParameterNames.end(); 1403 1404 StringRef NodeName = Node->getName(); 1405 if (llvm::find(Check.IgnoredParameterNames, NodeName) != 1406 Check.IgnoredParameterNames.end()) { 1407 LLVM_DEBUG(llvm::dbgs() << "\tName ignored.\n"); 1408 return true; 1409 } 1410 1411 StringRef NodeTypeName = [Node] { 1412 const ASTContext &Ctx = Node->getASTContext(); 1413 const SourceManager &SM = Ctx.getSourceManager(); 1414 SourceLocation B = Node->getTypeSpecStartLoc(); 1415 SourceLocation E = Node->getTypeSpecEndLoc(); 1416 LangOptions LO; 1417 1418 LLVM_DEBUG(llvm::dbgs() << "\tType name code is '" 1419 << Lexer::getSourceText( 1420 CharSourceRange::getTokenRange(B, E), SM, LO) 1421 << "'...\n"); 1422 if (B.isMacroID()) { 1423 LLVM_DEBUG(llvm::dbgs() << "\t\tBeginning is macro.\n"); 1424 B = SM.getTopMacroCallerLoc(B); 1425 } 1426 if (E.isMacroID()) { 1427 LLVM_DEBUG(llvm::dbgs() << "\t\tEnding is macro.\n"); 1428 E = Lexer::getLocForEndOfToken(SM.getTopMacroCallerLoc(E), 0, SM, LO); 1429 } 1430 LLVM_DEBUG(llvm::dbgs() << "\tType name code is '" 1431 << Lexer::getSourceText( 1432 CharSourceRange::getTokenRange(B, E), SM, LO) 1433 << "'...\n"); 1434 1435 return Lexer::getSourceText(CharSourceRange::getTokenRange(B, E), SM, LO); 1436 }(); 1437 1438 LLVM_DEBUG(llvm::dbgs() << "\tType name is '" << NodeTypeName << "'\n"); 1439 if (!NodeTypeName.empty()) { 1440 if (llvm::any_of(Check.IgnoredParameterTypeSuffixes, 1441 [NodeTypeName](const std::string &E) { 1442 return !E.empty() && NodeTypeName.endswith(E); 1443 })) { 1444 LLVM_DEBUG(llvm::dbgs() << "\tType suffix ignored.\n"); 1445 return true; 1446 } 1447 } 1448 1449 return false; 1450 } 1451 1452 /// This namespace contains the implementations for the suppression of 1453 /// diagnostics from similaly used ("related") parameters. 1454 namespace relatedness_heuristic { 1455 1456 static constexpr std::size_t SmallDataStructureSize = 4; 1457 1458 template <typename T, std::size_t N = SmallDataStructureSize> 1459 using ParamToSmallSetMap = 1460 llvm::DenseMap<const ParmVarDecl *, llvm::SmallSet<T, N>>; 1461 1462 /// Returns whether the sets mapped to the two elements in the map have at 1463 /// least one element in common. 1464 template <typename MapTy, typename ElemTy> 1465 bool lazyMapOfSetsIntersectionExists(const MapTy &Map, const ElemTy &E1, 1466 const ElemTy &E2) { 1467 auto E1Iterator = Map.find(E1); 1468 auto E2Iterator = Map.find(E2); 1469 if (E1Iterator == Map.end() || E2Iterator == Map.end()) 1470 return false; 1471 1472 for (const auto &E1SetElem : E1Iterator->second) 1473 if (llvm::find(E2Iterator->second, E1SetElem) != E2Iterator->second.end()) 1474 return true; 1475 1476 return false; 1477 } 1478 1479 /// Implements the heuristic that marks two parameters related if there is 1480 /// a usage for both in the same strict expression subtree. A strict 1481 /// expression subtree is a tree which only includes Expr nodes, i.e. no 1482 /// Stmts and no Decls. 1483 class AppearsInSameExpr : public RecursiveASTVisitor<AppearsInSameExpr> { 1484 using Base = RecursiveASTVisitor<AppearsInSameExpr>; 1485 1486 const FunctionDecl *FD; 1487 const Expr *CurrentExprOnlyTreeRoot = nullptr; 1488 llvm::DenseMap<const ParmVarDecl *, 1489 llvm::SmallPtrSet<const Expr *, SmallDataStructureSize>> 1490 ParentExprsForParamRefs; 1491 1492 public: 1493 void setup(const FunctionDecl *FD) { 1494 this->FD = FD; 1495 TraverseFunctionDecl(const_cast<FunctionDecl *>(FD)); 1496 } 1497 1498 bool operator()(const ParmVarDecl *Param1, const ParmVarDecl *Param2) const { 1499 return lazyMapOfSetsIntersectionExists(ParentExprsForParamRefs, Param1, 1500 Param2); 1501 } 1502 1503 bool TraverseDecl(Decl *D) { 1504 CurrentExprOnlyTreeRoot = nullptr; 1505 return Base::TraverseDecl(D); 1506 } 1507 1508 bool TraverseStmt(Stmt *S, DataRecursionQueue *Queue = nullptr) { 1509 if (auto *E = dyn_cast_or_null<Expr>(S)) { 1510 bool RootSetInCurrentStackFrame = false; 1511 if (!CurrentExprOnlyTreeRoot) { 1512 CurrentExprOnlyTreeRoot = E; 1513 RootSetInCurrentStackFrame = true; 1514 } 1515 1516 bool Ret = Base::TraverseStmt(S); 1517 1518 if (RootSetInCurrentStackFrame) 1519 CurrentExprOnlyTreeRoot = nullptr; 1520 1521 return Ret; 1522 } 1523 1524 // A Stmt breaks the strictly Expr subtree. 1525 CurrentExprOnlyTreeRoot = nullptr; 1526 return Base::TraverseStmt(S); 1527 } 1528 1529 bool VisitDeclRefExpr(DeclRefExpr *DRE) { 1530 if (!CurrentExprOnlyTreeRoot) 1531 return true; 1532 1533 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) 1534 if (llvm::find(FD->parameters(), PVD)) 1535 ParentExprsForParamRefs[PVD].insert(CurrentExprOnlyTreeRoot); 1536 1537 return true; 1538 } 1539 }; 1540 1541 /// Implements the heuristic that marks two parameters related if there are 1542 /// two separate calls to the same function (overload) and the parameters are 1543 /// passed to the same index in both calls, i.e f(a, b) and f(a, c) passes 1544 /// b and c to the same index (2) of f(), marking them related. 1545 class PassedToSameFunction { 1546 ParamToSmallSetMap<std::pair<const FunctionDecl *, unsigned>> TargetParams; 1547 1548 public: 1549 void setup(const FunctionDecl *FD) { 1550 auto ParamsAsArgsInFnCalls = 1551 match(functionDecl(forEachDescendant( 1552 callExpr(forEachArgumentWithParam( 1553 paramRefExpr(), parmVarDecl().bind("passed-to"))) 1554 .bind("call-expr"))), 1555 *FD, FD->getASTContext()); 1556 for (const auto &Match : ParamsAsArgsInFnCalls) { 1557 const auto *PassedParamOfThisFn = Match.getNodeAs<ParmVarDecl>("param"); 1558 const auto *CE = Match.getNodeAs<CallExpr>("call-expr"); 1559 const auto *PassedToParam = Match.getNodeAs<ParmVarDecl>("passed-to"); 1560 assert(PassedParamOfThisFn && CE && PassedToParam); 1561 1562 const FunctionDecl *CalledFn = CE->getDirectCallee(); 1563 if (!CalledFn) 1564 continue; 1565 1566 llvm::Optional<unsigned> TargetIdx; 1567 unsigned NumFnParams = CalledFn->getNumParams(); 1568 for (unsigned Idx = 0; Idx < NumFnParams; ++Idx) 1569 if (CalledFn->getParamDecl(Idx) == PassedToParam) 1570 TargetIdx.emplace(Idx); 1571 1572 assert(TargetIdx.hasValue() && "Matched, but didn't find index?"); 1573 TargetParams[PassedParamOfThisFn].insert( 1574 {CalledFn->getCanonicalDecl(), *TargetIdx}); 1575 } 1576 } 1577 1578 bool operator()(const ParmVarDecl *Param1, const ParmVarDecl *Param2) const { 1579 return lazyMapOfSetsIntersectionExists(TargetParams, Param1, Param2); 1580 } 1581 }; 1582 1583 /// Implements the heuristic that marks two parameters related if the same 1584 /// member is accessed (referred to) inside the current function's body. 1585 class AccessedSameMemberOf { 1586 ParamToSmallSetMap<const Decl *> AccessedMembers; 1587 1588 public: 1589 void setup(const FunctionDecl *FD) { 1590 auto MembersCalledOnParams = match( 1591 functionDecl(forEachDescendant( 1592 memberExpr(hasObjectExpression(paramRefExpr())).bind("mem-expr"))), 1593 *FD, FD->getASTContext()); 1594 1595 for (const auto &Match : MembersCalledOnParams) { 1596 const auto *AccessedParam = Match.getNodeAs<ParmVarDecl>("param"); 1597 const auto *ME = Match.getNodeAs<MemberExpr>("mem-expr"); 1598 assert(AccessedParam && ME); 1599 AccessedMembers[AccessedParam].insert( 1600 ME->getMemberDecl()->getCanonicalDecl()); 1601 } 1602 } 1603 1604 bool operator()(const ParmVarDecl *Param1, const ParmVarDecl *Param2) const { 1605 return lazyMapOfSetsIntersectionExists(AccessedMembers, Param1, Param2); 1606 } 1607 }; 1608 1609 /// Implements the heuristic that marks two parameters related if different 1610 /// ReturnStmts return them from the function. 1611 class Returned { 1612 llvm::SmallVector<const ParmVarDecl *, SmallDataStructureSize> ReturnedParams; 1613 1614 public: 1615 void setup(const FunctionDecl *FD) { 1616 // TODO: Handle co_return. 1617 auto ParamReturns = match(functionDecl(forEachDescendant( 1618 returnStmt(hasReturnValue(paramRefExpr())))), 1619 *FD, FD->getASTContext()); 1620 for (const auto &Match : ParamReturns) { 1621 const auto *ReturnedParam = Match.getNodeAs<ParmVarDecl>("param"); 1622 assert(ReturnedParam); 1623 1624 if (find(FD->parameters(), ReturnedParam) == FD->param_end()) 1625 // Inside the subtree of a FunctionDecl there might be ReturnStmts of 1626 // a parameter that isn't the parameter of the function, e.g. in the 1627 // case of lambdas. 1628 continue; 1629 1630 ReturnedParams.emplace_back(ReturnedParam); 1631 } 1632 } 1633 1634 bool operator()(const ParmVarDecl *Param1, const ParmVarDecl *Param2) const { 1635 return llvm::find(ReturnedParams, Param1) != ReturnedParams.end() && 1636 llvm::find(ReturnedParams, Param2) != ReturnedParams.end(); 1637 } 1638 }; 1639 1640 } // namespace relatedness_heuristic 1641 1642 /// Helper class that is used to detect if two parameters of the same function 1643 /// are used in a similar fashion, to suppress the result. 1644 class SimilarlyUsedParameterPairSuppressor { 1645 const bool Enabled; 1646 relatedness_heuristic::AppearsInSameExpr SameExpr; 1647 relatedness_heuristic::PassedToSameFunction PassToFun; 1648 relatedness_heuristic::AccessedSameMemberOf SameMember; 1649 relatedness_heuristic::Returned Returns; 1650 1651 public: 1652 SimilarlyUsedParameterPairSuppressor(const FunctionDecl *FD, bool Enable) 1653 : Enabled(Enable) { 1654 if (!Enable) 1655 return; 1656 1657 SameExpr.setup(FD); 1658 PassToFun.setup(FD); 1659 SameMember.setup(FD); 1660 Returns.setup(FD); 1661 } 1662 1663 /// Returns whether the specified two parameters are deemed similarly used 1664 /// or related by the heuristics. 1665 bool operator()(const ParmVarDecl *Param1, const ParmVarDecl *Param2) const { 1666 if (!Enabled) 1667 return false; 1668 1669 LLVM_DEBUG(llvm::dbgs() 1670 << "::: Matching similar usage / relatedness heuristic...\n"); 1671 1672 if (SameExpr(Param1, Param2)) { 1673 LLVM_DEBUG(llvm::dbgs() << "::: Used in the same expression.\n"); 1674 return true; 1675 } 1676 1677 if (PassToFun(Param1, Param2)) { 1678 LLVM_DEBUG(llvm::dbgs() 1679 << "::: Passed to same function in different calls.\n"); 1680 return true; 1681 } 1682 1683 if (SameMember(Param1, Param2)) { 1684 LLVM_DEBUG(llvm::dbgs() 1685 << "::: Same member field access or method called.\n"); 1686 return true; 1687 } 1688 1689 if (Returns(Param1, Param2)) { 1690 LLVM_DEBUG(llvm::dbgs() << "::: Both parameter returned.\n"); 1691 return true; 1692 } 1693 1694 LLVM_DEBUG(llvm::dbgs() << "::: None.\n"); 1695 return false; 1696 } 1697 }; 1698 1699 // (This function hoists the call to operator() of the wrapper, so we do not 1700 // need to define the previous class at the top of the file.) 1701 static inline bool 1702 isSimilarlyUsedParameter(const SimilarlyUsedParameterPairSuppressor &Suppressor, 1703 const ParmVarDecl *Param1, const ParmVarDecl *Param2) { 1704 return Suppressor(Param1, Param2); 1705 } 1706 1707 static void padStringAtEnd(SmallVectorImpl<char> &Str, std::size_t ToLen) { 1708 while (Str.size() < ToLen) 1709 Str.emplace_back('\0'); 1710 } 1711 1712 static void padStringAtBegin(SmallVectorImpl<char> &Str, std::size_t ToLen) { 1713 while (Str.size() < ToLen) 1714 Str.insert(Str.begin(), '\0'); 1715 } 1716 1717 static bool isCommonPrefixWithoutSomeCharacters(std::size_t N, StringRef S1, 1718 StringRef S2) { 1719 assert(S1.size() >= N && S2.size() >= N); 1720 StringRef S1Prefix = S1.take_front(S1.size() - N), 1721 S2Prefix = S2.take_front(S2.size() - N); 1722 return S1Prefix == S2Prefix && !S1Prefix.empty(); 1723 } 1724 1725 static bool isCommonSuffixWithoutSomeCharacters(std::size_t N, StringRef S1, 1726 StringRef S2) { 1727 assert(S1.size() >= N && S2.size() >= N); 1728 StringRef S1Suffix = S1.take_back(S1.size() - N), 1729 S2Suffix = S2.take_back(S2.size() - N); 1730 return S1Suffix == S2Suffix && !S1Suffix.empty(); 1731 } 1732 1733 /// Returns whether the two strings are prefixes or suffixes of each other with 1734 /// at most Threshold characters differing on the non-common end. 1735 static bool prefixSuffixCoverUnderThreshold(std::size_t Threshold, 1736 StringRef Str1, StringRef Str2) { 1737 if (Threshold == 0) 1738 return false; 1739 1740 // Pad the two strings to the longer length. 1741 std::size_t BiggerLength = std::max(Str1.size(), Str2.size()); 1742 1743 if (BiggerLength <= Threshold) 1744 // If the length of the strings is still smaller than the threshold, they 1745 // would be covered by an empty prefix/suffix with the rest differing. 1746 // (E.g. "A" and "X" with Threshold = 1 would mean we think they are 1747 // similar and do not warn about them, which is a too eager assumption.) 1748 return false; 1749 1750 SmallString<32> S1PadE{Str1}, S2PadE{Str2}; 1751 padStringAtEnd(S1PadE, BiggerLength); 1752 padStringAtEnd(S2PadE, BiggerLength); 1753 1754 if (isCommonPrefixWithoutSomeCharacters( 1755 Threshold, StringRef{S1PadE.begin(), BiggerLength}, 1756 StringRef{S2PadE.begin(), BiggerLength})) 1757 return true; 1758 1759 SmallString<32> S1PadB{Str1}, S2PadB{Str2}; 1760 padStringAtBegin(S1PadB, BiggerLength); 1761 padStringAtBegin(S2PadB, BiggerLength); 1762 1763 if (isCommonSuffixWithoutSomeCharacters( 1764 Threshold, StringRef{S1PadB.begin(), BiggerLength}, 1765 StringRef{S2PadB.begin(), BiggerLength})) 1766 return true; 1767 1768 return false; 1769 } 1770 1771 } // namespace filter 1772 1773 /// Matches functions that have at least the specified amount of parameters. 1774 AST_MATCHER_P(FunctionDecl, parameterCountGE, unsigned, N) { 1775 return Node.getNumParams() >= N; 1776 } 1777 1778 /// Matches *any* overloaded unary and binary operators. 1779 AST_MATCHER(FunctionDecl, isOverloadedUnaryOrBinaryOperator) { 1780 switch (Node.getOverloadedOperator()) { 1781 case OO_None: 1782 case OO_New: 1783 case OO_Delete: 1784 case OO_Array_New: 1785 case OO_Array_Delete: 1786 case OO_Conditional: 1787 case OO_Coawait: 1788 return false; 1789 1790 default: 1791 return Node.getNumParams() <= 2; 1792 } 1793 } 1794 1795 /// Returns the DefaultMinimumLength if the Value of requested minimum length 1796 /// is less than 2. Minimum lengths of 0 or 1 are not accepted. 1797 static inline unsigned clampMinimumLength(const unsigned Value) { 1798 return Value < 2 ? DefaultMinimumLength : Value; 1799 } 1800 1801 // FIXME: Maybe unneeded, getNameForDiagnostic() is expected to change to return 1802 // a crafted location when the node itself is unnamed. (See D84658, D85033.) 1803 /// Returns the diagnostic-friendly name of the node, or empty string. 1804 static SmallString<64> getName(const NamedDecl *ND) { 1805 SmallString<64> Name; 1806 llvm::raw_svector_ostream OS{Name}; 1807 ND->getNameForDiagnostic(OS, ND->getASTContext().getPrintingPolicy(), false); 1808 return Name; 1809 } 1810 1811 /// Returns the diagnostic-friendly name of the node, or a constant value. 1812 static SmallString<64> getNameOrUnnamed(const NamedDecl *ND) { 1813 auto Name = getName(ND); 1814 if (Name.empty()) 1815 Name = "<unnamed>"; 1816 return Name; 1817 } 1818 1819 /// Returns whether a particular Mix between two parameters should have the 1820 /// types involved diagnosed to the user. This is only a flag check. 1821 static inline bool needsToPrintTypeInDiagnostic(const model::Mix &M) { 1822 using namespace model; 1823 return static_cast<bool>( 1824 M.flags() & 1825 (MixFlags::TypeAlias | MixFlags::ReferenceBind | MixFlags::Qualifiers)); 1826 } 1827 1828 /// Returns whether a particular Mix between the two parameters should have 1829 /// implicit conversions elaborated. 1830 static inline bool needsToElaborateImplicitConversion(const model::Mix &M) { 1831 return hasFlag(M.flags(), model::MixFlags::ImplicitConversion); 1832 } 1833 1834 namespace { 1835 1836 /// This class formats a conversion sequence into a "Ty1 -> Ty2 -> Ty3" line 1837 /// that can be used in diagnostics. 1838 struct FormattedConversionSequence { 1839 std::string DiagnosticText; 1840 1841 /// The formatted sequence is trivial if it is "Ty1 -> Ty2", but Ty1 and 1842 /// Ty2 are the types that are shown in the code. A trivial diagnostic 1843 /// does not need to be printed. 1844 bool Trivial; 1845 1846 FormattedConversionSequence(const PrintingPolicy &PP, 1847 StringRef StartTypeAsDiagnosed, 1848 const model::ConversionSequence &Conv, 1849 StringRef DestinationTypeAsDiagnosed) { 1850 Trivial = true; 1851 llvm::raw_string_ostream OS{DiagnosticText}; 1852 1853 // Print the type name as it is printed in other places in the diagnostic. 1854 OS << '\'' << StartTypeAsDiagnosed << '\''; 1855 std::string LastAddedType = StartTypeAsDiagnosed.str(); 1856 std::size_t NumElementsAdded = 1; 1857 1858 // However, the parameter's defined type might not be what the implicit 1859 // conversion started with, e.g. if a typedef is found to convert. 1860 std::string SeqBeginTypeStr = Conv.Begin.getAsString(PP); 1861 std::string SeqEndTypeStr = Conv.End.getAsString(PP); 1862 if (StartTypeAsDiagnosed != SeqBeginTypeStr) { 1863 OS << " (as '" << SeqBeginTypeStr << "')"; 1864 LastAddedType = SeqBeginTypeStr; 1865 Trivial = false; 1866 } 1867 1868 auto AddType = [&](StringRef ToAdd) { 1869 if (LastAddedType != ToAdd && ToAdd != SeqEndTypeStr) { 1870 OS << " -> '" << ToAdd << "'"; 1871 LastAddedType = ToAdd.str(); 1872 ++NumElementsAdded; 1873 } 1874 }; 1875 for (QualType InvolvedType : Conv.getInvolvedTypesInSequence()) 1876 // Print every type that's unique in the sequence into the diagnosis. 1877 AddType(InvolvedType.getAsString(PP)); 1878 1879 if (LastAddedType != DestinationTypeAsDiagnosed) { 1880 OS << " -> '" << DestinationTypeAsDiagnosed << "'"; 1881 LastAddedType = DestinationTypeAsDiagnosed.str(); 1882 ++NumElementsAdded; 1883 } 1884 1885 // Same reasoning as with the Begin, e.g. if the converted-to type is a 1886 // typedef, it will not be the same inside the conversion sequence (where 1887 // the model already tore off typedefs) as in the code. 1888 if (DestinationTypeAsDiagnosed != SeqEndTypeStr) { 1889 OS << " (as '" << SeqEndTypeStr << "')"; 1890 LastAddedType = SeqEndTypeStr; 1891 Trivial = false; 1892 } 1893 1894 if (Trivial && NumElementsAdded > 2) 1895 // If the thing is still marked trivial but we have more than the 1896 // from and to types added, it should not be trivial, and elaborated 1897 // when printing the diagnostic. 1898 Trivial = false; 1899 } 1900 }; 1901 1902 /// Retains the elements called with and returns whether the call is done with 1903 /// a new element. 1904 template <typename E, std::size_t N> class InsertOnce { 1905 llvm::SmallSet<E, N> CalledWith; 1906 1907 public: 1908 bool operator()(E El) { return CalledWith.insert(std::move(El)).second; } 1909 1910 bool calledWith(const E &El) const { return CalledWith.contains(El); } 1911 }; 1912 1913 struct SwappedEqualQualTypePair { 1914 QualType LHSType, RHSType; 1915 1916 bool operator==(const SwappedEqualQualTypePair &Other) const { 1917 return (LHSType == Other.LHSType && RHSType == Other.RHSType) || 1918 (LHSType == Other.RHSType && RHSType == Other.LHSType); 1919 } 1920 1921 bool operator<(const SwappedEqualQualTypePair &Other) const { 1922 return LHSType < Other.LHSType && RHSType < Other.RHSType; 1923 } 1924 }; 1925 1926 struct TypeAliasDiagnosticTuple { 1927 QualType LHSType, RHSType, CommonType; 1928 1929 bool operator==(const TypeAliasDiagnosticTuple &Other) const { 1930 return CommonType == Other.CommonType && 1931 ((LHSType == Other.LHSType && RHSType == Other.RHSType) || 1932 (LHSType == Other.RHSType && RHSType == Other.LHSType)); 1933 } 1934 1935 bool operator<(const TypeAliasDiagnosticTuple &Other) const { 1936 return CommonType < Other.CommonType && LHSType < Other.LHSType && 1937 RHSType < Other.RHSType; 1938 } 1939 }; 1940 1941 /// Helper class to only emit a diagnostic related to MixFlags::TypeAlias once. 1942 class UniqueTypeAliasDiagnosticHelper 1943 : public InsertOnce<TypeAliasDiagnosticTuple, 8> { 1944 using Base = InsertOnce<TypeAliasDiagnosticTuple, 8>; 1945 1946 public: 1947 /// Returns whether the diagnostic for LHSType and RHSType which are both 1948 /// referring to CommonType being the same has not been emitted already. 1949 bool operator()(QualType LHSType, QualType RHSType, QualType CommonType) { 1950 if (CommonType.isNull() || CommonType == LHSType || CommonType == RHSType) 1951 return Base::operator()({LHSType, RHSType, {}}); 1952 1953 TypeAliasDiagnosticTuple ThreeTuple{LHSType, RHSType, CommonType}; 1954 if (!Base::operator()(ThreeTuple)) 1955 return false; 1956 1957 bool AlreadySaidLHSAndCommonIsSame = calledWith({LHSType, CommonType, {}}); 1958 bool AlreadySaidRHSAndCommonIsSame = calledWith({RHSType, CommonType, {}}); 1959 if (AlreadySaidLHSAndCommonIsSame && AlreadySaidRHSAndCommonIsSame) { 1960 // "SomeInt == int" && "SomeOtherInt == int" => "Common(SomeInt, 1961 // SomeOtherInt) == int", no need to diagnose it. Save the 3-tuple only 1962 // for shortcut if it ever appears again. 1963 return false; 1964 } 1965 1966 return true; 1967 } 1968 }; 1969 1970 } // namespace 1971 1972 EasilySwappableParametersCheck::EasilySwappableParametersCheck( 1973 StringRef Name, ClangTidyContext *Context) 1974 : ClangTidyCheck(Name, Context), 1975 MinimumLength(clampMinimumLength( 1976 Options.get("MinimumLength", DefaultMinimumLength))), 1977 IgnoredParameterNames(optutils::parseStringList( 1978 Options.get("IgnoredParameterNames", DefaultIgnoredParameterNames))), 1979 IgnoredParameterTypeSuffixes(optutils::parseStringList( 1980 Options.get("IgnoredParameterTypeSuffixes", 1981 DefaultIgnoredParameterTypeSuffixes))), 1982 QualifiersMix(Options.get("QualifiersMix", DefaultQualifiersMix)), 1983 ModelImplicitConversions(Options.get("ModelImplicitConversions", 1984 DefaultModelImplicitConversions)), 1985 SuppressParametersUsedTogether( 1986 Options.get("SuppressParametersUsedTogether", 1987 DefaultSuppressParametersUsedTogether)), 1988 NamePrefixSuffixSilenceDissimilarityTreshold( 1989 Options.get("NamePrefixSuffixSilenceDissimilarityTreshold", 1990 DefaultNamePrefixSuffixSilenceDissimilarityTreshold)) {} 1991 1992 void EasilySwappableParametersCheck::storeOptions( 1993 ClangTidyOptions::OptionMap &Opts) { 1994 Options.store(Opts, "MinimumLength", MinimumLength); 1995 Options.store(Opts, "IgnoredParameterNames", 1996 optutils::serializeStringList(IgnoredParameterNames)); 1997 Options.store(Opts, "IgnoredParameterTypeSuffixes", 1998 optutils::serializeStringList(IgnoredParameterTypeSuffixes)); 1999 Options.store(Opts, "QualifiersMix", QualifiersMix); 2000 Options.store(Opts, "ModelImplicitConversions", ModelImplicitConversions); 2001 Options.store(Opts, "SuppressParametersUsedTogether", 2002 SuppressParametersUsedTogether); 2003 Options.store(Opts, "NamePrefixSuffixSilenceDissimilarityTreshold", 2004 NamePrefixSuffixSilenceDissimilarityTreshold); 2005 } 2006 2007 void EasilySwappableParametersCheck::registerMatchers(MatchFinder *Finder) { 2008 const auto BaseConstraints = functionDecl( 2009 // Only report for definition nodes, as fixing the issues reported 2010 // requires the user to be able to change code. 2011 isDefinition(), parameterCountGE(MinimumLength), 2012 unless(isOverloadedUnaryOrBinaryOperator())); 2013 2014 Finder->addMatcher( 2015 functionDecl(BaseConstraints, 2016 unless(ast_matchers::isTemplateInstantiation())) 2017 .bind("func"), 2018 this); 2019 Finder->addMatcher( 2020 functionDecl(BaseConstraints, isExplicitTemplateSpecialization()) 2021 .bind("func"), 2022 this); 2023 } 2024 2025 void EasilySwappableParametersCheck::check( 2026 const MatchFinder::MatchResult &Result) { 2027 using namespace model; 2028 using namespace filter; 2029 2030 const auto *FD = Result.Nodes.getNodeAs<FunctionDecl>("func"); 2031 assert(FD); 2032 2033 const PrintingPolicy &PP = FD->getASTContext().getPrintingPolicy(); 2034 std::size_t NumParams = FD->getNumParams(); 2035 std::size_t MixableRangeStartIndex = 0; 2036 2037 // Spawn one suppressor and if the user requested, gather information from 2038 // the AST for the parameters' usages. 2039 filter::SimilarlyUsedParameterPairSuppressor UsageBasedSuppressor{ 2040 FD, SuppressParametersUsedTogether}; 2041 2042 LLVM_DEBUG(llvm::dbgs() << "Begin analysis of " << getName(FD) << " with " 2043 << NumParams << " parameters...\n"); 2044 while (MixableRangeStartIndex < NumParams) { 2045 if (isIgnoredParameter(*this, FD->getParamDecl(MixableRangeStartIndex))) { 2046 LLVM_DEBUG(llvm::dbgs() 2047 << "Parameter #" << MixableRangeStartIndex << " ignored.\n"); 2048 ++MixableRangeStartIndex; 2049 continue; 2050 } 2051 2052 MixableParameterRange R = modelMixingRange( 2053 *this, FD, MixableRangeStartIndex, UsageBasedSuppressor); 2054 assert(R.NumParamsChecked > 0 && "Ensure forward progress!"); 2055 MixableRangeStartIndex += R.NumParamsChecked; 2056 if (R.NumParamsChecked < MinimumLength) { 2057 LLVM_DEBUG(llvm::dbgs() << "Ignoring range of " << R.NumParamsChecked 2058 << " lower than limit.\n"); 2059 continue; 2060 } 2061 2062 bool NeedsAnyTypeNote = llvm::any_of(R.Mixes, needsToPrintTypeInDiagnostic); 2063 bool HasAnyImplicits = 2064 llvm::any_of(R.Mixes, needsToElaborateImplicitConversion); 2065 const ParmVarDecl *First = R.getFirstParam(), *Last = R.getLastParam(); 2066 std::string FirstParamTypeAsWritten = First->getType().getAsString(PP); 2067 { 2068 StringRef DiagText; 2069 2070 if (HasAnyImplicits) 2071 DiagText = "%0 adjacent parameters of %1 of convertible types are " 2072 "easily swapped by mistake"; 2073 else if (NeedsAnyTypeNote) 2074 DiagText = "%0 adjacent parameters of %1 of similar type are easily " 2075 "swapped by mistake"; 2076 else 2077 DiagText = "%0 adjacent parameters of %1 of similar type ('%2') are " 2078 "easily swapped by mistake"; 2079 2080 auto Diag = diag(First->getOuterLocStart(), DiagText) 2081 << static_cast<unsigned>(R.NumParamsChecked) << FD; 2082 if (!NeedsAnyTypeNote) 2083 Diag << FirstParamTypeAsWritten; 2084 2085 CharSourceRange HighlightRange = CharSourceRange::getTokenRange( 2086 First->getBeginLoc(), Last->getEndLoc()); 2087 Diag << HighlightRange; 2088 } 2089 2090 // There is a chance that the previous highlight did not succeed, e.g. when 2091 // the two parameters are on different lines. For clarity, show the user 2092 // the involved variable explicitly. 2093 diag(First->getLocation(), "the first parameter in the range is '%0'", 2094 DiagnosticIDs::Note) 2095 << getNameOrUnnamed(First) 2096 << CharSourceRange::getTokenRange(First->getLocation(), 2097 First->getLocation()); 2098 diag(Last->getLocation(), "the last parameter in the range is '%0'", 2099 DiagnosticIDs::Note) 2100 << getNameOrUnnamed(Last) 2101 << CharSourceRange::getTokenRange(Last->getLocation(), 2102 Last->getLocation()); 2103 2104 // Helper classes to silence elaborative diagnostic notes that would be 2105 // too verbose. 2106 UniqueTypeAliasDiagnosticHelper UniqueTypeAlias; 2107 InsertOnce<SwappedEqualQualTypePair, 8> UniqueBindPower; 2108 InsertOnce<SwappedEqualQualTypePair, 8> UniqueImplicitConversion; 2109 2110 for (const model::Mix &M : R.Mixes) { 2111 assert(M.mixable() && "Sentinel or false mix in result."); 2112 if (!needsToPrintTypeInDiagnostic(M) && 2113 !needsToElaborateImplicitConversion(M)) 2114 continue; 2115 2116 // Typedefs might result in the type of the variable needing to be 2117 // emitted to a note diagnostic, so prepare it. 2118 const ParmVarDecl *LVar = M.First; 2119 const ParmVarDecl *RVar = M.Second; 2120 QualType LType = LVar->getType(); 2121 QualType RType = RVar->getType(); 2122 QualType CommonType = M.commonUnderlyingType(); 2123 std::string LTypeStr = LType.getAsString(PP); 2124 std::string RTypeStr = RType.getAsString(PP); 2125 std::string CommonTypeStr = CommonType.getAsString(PP); 2126 2127 if (hasFlag(M.flags(), MixFlags::TypeAlias) && 2128 UniqueTypeAlias(LType, RType, CommonType)) { 2129 StringRef DiagText; 2130 bool ExplicitlyPrintCommonType = false; 2131 if (LTypeStr == CommonTypeStr || RTypeStr == CommonTypeStr) 2132 if (hasFlag(M.flags(), MixFlags::Qualifiers)) 2133 DiagText = "after resolving type aliases, '%0' and '%1' share a " 2134 "common type"; 2135 else 2136 DiagText = 2137 "after resolving type aliases, '%0' and '%1' are the same"; 2138 else if (!CommonType.isNull()) { 2139 DiagText = "after resolving type aliases, the common type of '%0' " 2140 "and '%1' is '%2'"; 2141 ExplicitlyPrintCommonType = true; 2142 } 2143 2144 auto Diag = 2145 diag(LVar->getOuterLocStart(), DiagText, DiagnosticIDs::Note) 2146 << LTypeStr << RTypeStr; 2147 if (ExplicitlyPrintCommonType) 2148 Diag << CommonTypeStr; 2149 } 2150 2151 if ((hasFlag(M.flags(), MixFlags::ReferenceBind) || 2152 hasFlag(M.flags(), MixFlags::Qualifiers)) && 2153 UniqueBindPower({LType, RType})) { 2154 StringRef DiagText = "'%0' and '%1' parameters accept and bind the " 2155 "same kind of values"; 2156 diag(RVar->getOuterLocStart(), DiagText, DiagnosticIDs::Note) 2157 << LTypeStr << RTypeStr; 2158 } 2159 2160 if (needsToElaborateImplicitConversion(M) && 2161 UniqueImplicitConversion({LType, RType})) { 2162 const model::ConversionSequence <R = 2163 M.leftToRightConversionSequence(); 2164 const model::ConversionSequence &RTL = 2165 M.rightToLeftConversionSequence(); 2166 FormattedConversionSequence LTRFmt{PP, LTypeStr, LTR, RTypeStr}; 2167 FormattedConversionSequence RTLFmt{PP, RTypeStr, RTL, LTypeStr}; 2168 2169 StringRef DiagText = "'%0' and '%1' may be implicitly converted"; 2170 if (!LTRFmt.Trivial || !RTLFmt.Trivial) 2171 DiagText = "'%0' and '%1' may be implicitly converted: %2, %3"; 2172 2173 { 2174 auto Diag = 2175 diag(RVar->getOuterLocStart(), DiagText, DiagnosticIDs::Note) 2176 << LTypeStr << RTypeStr; 2177 2178 if (!LTRFmt.Trivial || !RTLFmt.Trivial) 2179 Diag << LTRFmt.DiagnosticText << RTLFmt.DiagnosticText; 2180 } 2181 2182 StringRef ConversionFunctionDiagText = 2183 "the implicit conversion involves the " 2184 "%select{|converting constructor|conversion operator}0 " 2185 "declared here"; 2186 if (const FunctionDecl *LFD = LTR.getUserDefinedConversionFunction()) 2187 diag(LFD->getLocation(), ConversionFunctionDiagText, 2188 DiagnosticIDs::Note) 2189 << static_cast<unsigned>(LTR.UDConvKind) 2190 << LTR.getUserDefinedConversionHighlight(); 2191 if (const FunctionDecl *RFD = RTL.getUserDefinedConversionFunction()) 2192 diag(RFD->getLocation(), ConversionFunctionDiagText, 2193 DiagnosticIDs::Note) 2194 << static_cast<unsigned>(RTL.UDConvKind) 2195 << RTL.getUserDefinedConversionHighlight(); 2196 } 2197 } 2198 } 2199 } 2200 2201 } // namespace bugprone 2202 } // namespace tidy 2203 } // namespace clang 2204