[llvm] Cleanup edit_distance short circuiting
authorserge-sans-paille <sguelton@mozilla.com>
Thu, 19 Jan 2023 22:00:53 +0000 (23:00 +0100)
committerserge-sans-paille <sguelton@mozilla.com>
Thu, 19 Jan 2023 22:20:37 +0000 (23:20 +0100)
Also prevent integer overflow if MaximumDistance == UINT_MAX.

This is a follow-up to 6ad1b4095172373590134afff19a7fbad9d7889d

llvm/include/llvm/Option/OptTable.h
llvm/lib/Option/OptTable.cpp

index 8f13a31..0cef9b6 100644 (file)
@@ -182,7 +182,7 @@ public:
   unsigned findNearest(StringRef Option, std::string &NearestString,
                        unsigned FlagsToInclude = 0, unsigned FlagsToExclude = 0,
                        unsigned MinimumLength = 4,
-                       unsigned MaximumDistance = UINT_MAX - 1) const;
+                       unsigned MaximumDistance = UINT_MAX) const;
 
   bool findExact(StringRef Option, std::string &ExactString,
                  unsigned FlagsToInclude = 0,
index 10f0658..2e289c5 100644 (file)
@@ -233,7 +233,8 @@ unsigned OptTable::findNearest(StringRef Option, std::string &NearestString,
 
   // Consider each [option prefix + option name] pair as a candidate, finding
   // the closest match.
-  unsigned BestDistance = MaximumDistance + 1;
+  unsigned BestDistance =
+      MaximumDistance == UINT_MAX ? UINT_MAX : MaximumDistance + 1;
   SmallString<16> Candidate;
   SmallString<16> NormalizedName;
 
@@ -281,8 +282,12 @@ unsigned OptTable::findNearest(StringRef Option, std::string &NearestString,
       // characters of difference, no need to compute the edit distance, it's
       // going to be greater than BestDistance. Don't bother computing Candidate
       // at all.
-      if (std::abs((ssize_t)(CandidatePrefix.size() + CandidateName.size()) -
-                   (ssize_t)NormalizedName.size()) > (ssize_t)BestDistance) {
+      size_t CandidateSize = CandidatePrefix.size() + CandidateName.size(),
+             NormalizedSize = NormalizedName.size();
+      size_t AbsDiff = CandidateSize > NormalizedSize
+                           ? CandidateSize - NormalizedSize
+                           : NormalizedSize - CandidateSize;
+      if (AbsDiff > BestDistance) {
         continue;
       }
       Candidate = CandidatePrefix;