From 5034ce882ff4ab49fc4a874009ce638b377bcdaa Mon Sep 17 00:00:00 2001 From: Oliver Kurth Date: Fri, 15 Sep 2017 11:23:41 -0700 Subject: [PATCH] optimize clamped uadd functions 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 | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/open-vm-tools/lib/include/clamped.h b/open-vm-tools/lib/include/clamped.h index 9686a2206..cbe51d584 100644 --- a/open-vm-tools/lib/include/clamped.h +++ b/open-vm-tools/lib/include/clamped.h @@ -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; } -- 2.47.3