]> git.ipfire.org Git - thirdparty/open-vm-tools.git/commitdiff
optimize clamped uadd functions
authorOliver Kurth <okurth@vmware.com>
Fri, 15 Sep 2017 18:23:41 +0000 (11:23 -0700)
committerOliver Kurth <okurth@vmware.com>
Fri, 15 Sep 2017 18:23:41 +0000 (11:23 -0700)
For unsigned adds, if there's no overflow, the result will be larger
or equal than either source operand. Consequently, if there's an
overflow, the result will be smaller than both, and checking against
one source operand is sufficient. Found accidentally...
(With just one comparison, gcc is in fact able to figure out the
comparison is really the same as the add overflowing and will omit
the comparison. But it won't do this with two comparisons.)

open-vm-tools/lib/include/clamped.h

index 9686a2206a29d13425e9d1fd09820bb8a32283f7..cbe51d5840f4a66e733a5e8f3daf7c8f1da354f9 100644 (file)
@@ -261,7 +261,10 @@ Clamped_UAdd32(uint32 *out,  // OUT
 {
    uint32 c = a + b;
 
-   if (UNLIKELY(c < a || c < b)) {
+   /*
+    * Checking against one src operand is sufficient.
+    */
+   if (UNLIKELY(c < a)) {
       *out = MAX_UINT32;
       return FALSE;
    }
@@ -298,7 +301,10 @@ Clamped_UAdd64(uint64 *out,   // OUT
 {
    uint64 c = a + b;
 
-   if(UNLIKELY(c < a || c < b)) {
+   /*
+    * Checking against one src operand is sufficient.
+    */
+   if (UNLIKELY(c < a)) {
       *out = MAX_UINT64;
       return FALSE;
    }