This is an automated email from the ASF dual-hosted git repository.

Gabriel39 pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/doris.git


The following commit(s) were added to refs/heads/master by this push:
     new 2f99037e255 [opt](be) Avoid division in checked int128 multiplication 
(#70921)
2f99037e255 is described below

commit 2f99037e255ace3ec20ee739dda2a9cb50d000e4
Author: Gabriel <[email protected]>
AuthorDate: Tue Nov 24 18:02:01 2026 +0800

    [opt](be) Avoid division in checked int128 multiplication (#70921)
    
    ### Background
    
    Decimal multiplication checks native integer overflow before enforcing
    decimal precision and rescaling. The signed int128 check currently uses
    a compiler-rt-derived implementation with 128-bit division. This
    implementation avoids a missing `__muloti4` runtime symbol on some ARM
    toolchains.
    
    ### What problem does this PR solve?
    
    Issue Number: None
    Related PR: #51715 (introduced the ARM-compatible software check),
    #51533 (fixed signed int128 overflow detection)
    PR Type: Performance
    
    Problem Summary:
    
    The division-based check adds CPU overhead to each checked Decimal
    multiplication. Replace it with unsigned builtin multiplication on
    operand magnitudes and a sign-dependent bound, preserving the ARM
    compatibility workaround and the complete signed int128 range. Results,
    decimal types, precision checks and overflow behavior remain unchanged;
    most of the diff adds tests.
    
    ### Details
    
    - **Change map:** 46 production lines changed (14 added, 32 removed),
    240 unit/regression test lines added, and 51 automatically generated
    expected-output lines added.
    - **Why it was slow:** Ordinary nonzero/nonunit products perform a
    128-bit division to detect overflow; the baseline code-generation probes
    call `__udivti3`.
    - **Optimization:** Compute magnitudes in unsigned arithmetic so even
    `INT128_MIN` is safe, use unsigned `__builtin_mul_overflow`, then apply
    the signed bound. Negative products can have magnitude `2^127`, for
    example `(2^126) * (-2)`. Preserve the zero/unit fast path and wrapped
    result bits on overflow.
    - **Results:** Local release-mode primitive microbenchmark on a
    dual-socket Intel Xeon Platinum 8457C, Clang 20.1.8, `-O3 -DNDEBUG
    -march=x86-64-v3`. Both implementations use the same input/output arrays
    in one binary: 65,536 pairs, five warm-up batches, 100 batches per
    sample, 11 paired samples with alternating order, pinned to one logical
    CPU. The shared host was busy, so the table reports median thread CPU
    time rather than query latency.
    
    | Synthetic input distribution | Before, ns/product | After, ns/product
    |
    | --- | ---: | ---: |
    | Discount-shaped positive operands | 13.37 | 10.28 |
    | Charge-shaped positive operands | 12.33 | 8.77 |
    | Mixed signs | 18.16 | 9.23 |
    | Full-width overflowing products | 23.18 | 9.53 |
    | Random zero/unit factors | 6.22 | 6.36 |
    
    - **Applicability and cost:** Applies to checked signed int128
    multiplication, including Decimal arithmetic. No allocations or type
    changes are added. The zero/unit workload is about 2.4% slower by these
    CPU-time medians despite retaining its fast path; the other measured
    distributions improve. These measurements do not establish an end-to-end
    TPC-H or SSB speedup.
    
    ### Testing
    
    - Local ASan/UBSan BE build and FE build completed; the BE executable
    passed its GLIBC 2.17 symbol gate.
    - New unit tests compare 85,141 products with an independent 256-bit
    reference, plus aliased-output cases. Clang ASan/UBSan and GCC UBSan
    standalone runs pass. A deliberately broken minimum-value bound fails
    the boundary and power tests.
    - All six targeted BE tests pass through the standard ASan/UBSan runner:
    `run-be-ut.sh --run
    --filter='ArithmeticOverflowTest.*:CheckOverFlowTest.*'`.
    - Local regression suites `test_decimal128_checked_multiply`,
    `test_arithmetic_expressions` and `test_decimalv3_overflow` pass against
    the newly built BE. The new suite covers column/constant forms, nulls,
    signed and unsigned machine overflow, decimal precision overflow, and
    scaled wide-intermediate fallback. Its generated 41 result rows were
    independently checked with Python arbitrary-precision integers and
    Decimal.
    - Clang 16/20 x86_64 and ARM64 code-generation probes, plus GCC x86_64,
    contain no division or `__muloti4` call for the new helper. ARM
    validation is compile/code-generation only.
    - Local self-review, clang-format v16, clang-tidy, build hygiene and
    whitespace checks completed.
    
    ### Release note
    
    Reduce CPU overhead of checked Decimal multiplication while preserving
    existing results and overflow behavior.
    
    ### Check List (For Author)
    
    - Behavior changed: No
    - Does this need documentation: No
    - Pre-submission status: Ready
    
    ### AI Disclosure
    
    - Tool: Codex (GPT-6)
    - Generated: Code, unit and regression tests, and this description.
    - Human review: Not yet reviewed by a human; local self-review and
    verification were performed by Codex.
---
 be/src/exec/common/arithmetic_overflow.h           |  46 +++----
 be/test/common/arithmetic_overflow_test.cpp        | 102 +++++++++++++++
 .../decimalv3/test_decimal128_checked_multiply.out |  51 ++++++++
 .../test_decimal128_checked_multiply.groovy        | 138 +++++++++++++++++++++
 4 files changed, 305 insertions(+), 32 deletions(-)

diff --git a/be/src/exec/common/arithmetic_overflow.h 
b/be/src/exec/common/arithmetic_overflow.h
index ddf79dce2cc..61720db4bde 100644
--- a/be/src/exec/common/arithmetic_overflow.h
+++ b/be/src/exec/common/arithmetic_overflow.h
@@ -115,42 +115,24 @@ inline bool mul_overflow(long long x, long long y, long 
long& res) {
     return __builtin_smulll_overflow(x, y, &res);
 }
 
-// from __muloXi4 in llvm's compiler-rt
 static inline __int128 int128_overflow_mul(__int128 a, __int128 b, int* 
overflow) {
-    const int N = (int)(sizeof(__int128) * CHAR_BIT);
-    const auto MIN = (__int128)((__uint128_t)1 << (N - 1));
-    const __int128 MAX = ~MIN;
-    *overflow = 0;
-    __int128 result = (__uint128_t)a * b;
-    if (a == MIN) {
-        if (b != 0 && b != 1) {
-            *overflow = 1;
-        }
-        return result;
-    }
-    if (b == MIN) {
-        if (a != 0 && a != 1) {
-            *overflow = 1;
-        }
-        return result;
-    }
-    __int128 sa = a >> (N - 1);
-    __int128 abs_a = (a ^ sa) - sa;
-    __int128 sb = b >> (N - 1);
-    __int128 abs_b = (b ^ sb) - sb;
+    const bool negative = (a < 0) != (b < 0);
+    // Unsigned multiplication avoids __muloti4 on ARM toolchains using libgcc.
+    // Taking the magnitudes in unsigned arithmetic also handles INT128_MIN 
safely.
+    const auto abs_a = a < 0 ? -static_cast<__uint128_t>(a) : 
static_cast<__uint128_t>(a);
+    const auto abs_b = b < 0 ? -static_cast<__uint128_t>(b) : 
static_cast<__uint128_t>(b);
+    __uint128_t magnitude;
+    bool unsigned_overflow = false;
+    // A zero/unit factor cannot overflow unsigned 128 bits; keep this common 
case cheap.
     if (abs_a < 2 || abs_b < 2) {
-        return result;
-    }
-    if (sa == sb) {
-        if (abs_a > MAX / abs_b) {
-            *overflow = 1;
-        }
+        magnitude = abs_a * abs_b;
     } else {
-        if (abs_a > MIN / -abs_b) {
-            *overflow = 1;
-        }
+        unsigned_overflow = __builtin_mul_overflow(abs_a, abs_b, &magnitude);
     }
-    return result;
+    // Negative products may have magnitude 2^127: (2^126) * (-2) is 
INT128_MIN.
+    const __uint128_t limit = (__uint128_t(1) << 127) - !negative;
+    *overflow = unsigned_overflow || magnitude > limit;
+    return static_cast<__int128>(negative ? -magnitude : magnitude);
 }
 
 template <>
diff --git a/be/test/common/arithmetic_overflow_test.cpp 
b/be/test/common/arithmetic_overflow_test.cpp
new file mode 100644
index 00000000000..f89a61a32fe
--- /dev/null
+++ b/be/test/common/arithmetic_overflow_test.cpp
@@ -0,0 +1,102 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+#include "exec/common/arithmetic_overflow.h"
+
+#include <gtest/gtest.h>
+
+#include <array>
+#include <limits>
+#include <random>
+
+namespace doris {
+namespace {
+
+void check_int128_product(__int128 lhs, __int128 rhs) {
+    const wide::Int256 expected = wide::Int256(lhs) * wide::Int256(rhs);
+    const bool expected_overflow = expected < 
wide::Int256(std::numeric_limits<__int128>::min()) ||
+                                   expected > 
wide::Int256(std::numeric_limits<__int128>::max());
+    __int128 result = 0;
+    EXPECT_EQ(common::mul_overflow(lhs, rhs, result), expected_overflow);
+    // The low 128 bits must still be the product when the overflow flag is 
set.
+    EXPECT_EQ(static_cast<__uint128_t>(result), 
static_cast<__uint128_t>(expected));
+}
+
+} // namespace
+
+TEST(ArithmeticOverflowTest, Int128MultiplyBoundaries) {
+    constexpr __int128 min = std::numeric_limits<__int128>::min();
+    constexpr __int128 max = std::numeric_limits<__int128>::max();
+    constexpr __int128 two63 = __int128(1) << 63;
+    constexpr __int128 two64 = __int128(1) << 64;
+    const std::array<__int128, 25> inputs = {
+            min,        min + 1,     min / 2 - 1, min / 2,   min / 2 + 1, 
-two64 - 1, -two64,
+            -two64 + 1, -two63,      -3,          -2,        -1,          0,   
       1,
+            2,          3,           two63,       two64 - 1, two64,       
two64 + 1,  max / 2 - 1,
+            max / 2,    max / 2 + 1, max - 1,     max};
+    for (size_t i = 0; i < inputs.size(); ++i) {
+        for (size_t j = 0; j < inputs.size(); ++j) {
+            SCOPED_TRACE(testing::Message() << "i=" << i << ", j=" << j);
+            check_int128_product(inputs[i], inputs[j]);
+        }
+    }
+}
+
+TEST(ArithmeticOverflowTest, Int128MultiplyPowersOfTwo) {
+    for (int lhs_bit = 0; lhs_bit < 127; ++lhs_bit) {
+        for (int rhs_bit = 0; rhs_bit < 127; ++rhs_bit) {
+            SCOPED_TRACE(testing::Message() << "lhs_bit=" << lhs_bit << ", 
rhs_bit=" << rhs_bit);
+            const __int128 lhs = __int128(1) << lhs_bit;
+            const __int128 rhs = __int128(1) << rhs_bit;
+            check_int128_product(lhs, rhs);
+            check_int128_product(-lhs, rhs);
+            check_int128_product(lhs, -rhs);
+            check_int128_product(-lhs, -rhs);
+        }
+    }
+}
+
+TEST(ArithmeticOverflowTest, Int128MultiplyRandomized) {
+    std::mt19937_64 rng(0x128dec1a1);
+    for (size_t i = 0; i < 10000; ++i) {
+        SCOPED_TRACE(testing::Message() << "iteration=" << i);
+        const auto lhs = static_cast<__int128>((__uint128_t(rng()) << 64) | 
rng());
+        const auto rhs = static_cast<__int128>((__uint128_t(rng()) << 64) | 
rng());
+        check_int128_product(lhs, rhs);
+        check_int128_product(static_cast<int64_t>(lhs), 
static_cast<int64_t>(rhs));
+    }
+}
+
+TEST(ArithmeticOverflowTest, Int128MultiplyAliasedResult) {
+    constexpr __int128 min = std::numeric_limits<__int128>::min();
+    constexpr __int128 max = std::numeric_limits<__int128>::max();
+    for (const __int128 lhs : {min, min / 2, __int128(-1), __int128(0), 
__int128(1), max}) {
+        for (const __int128 rhs :
+             {__int128(-2), __int128(-1), __int128(0), __int128(1), 
__int128(2)}) {
+            __int128 expected;
+            const bool overflow = common::mul_overflow(lhs, rhs, expected);
+            __int128 left = lhs;
+            EXPECT_EQ(common::mul_overflow(left, rhs, left), overflow);
+            EXPECT_EQ(left, expected);
+            __int128 right = rhs;
+            EXPECT_EQ(common::mul_overflow(lhs, right, right), overflow);
+            EXPECT_EQ(right, expected);
+        }
+    }
+}
+
+} // namespace doris
diff --git 
a/regression-test/data/datatype_p0/decimalv3/test_decimal128_checked_multiply.out
 
b/regression-test/data/datatype_p0/decimalv3/test_decimal128_checked_multiply.out
new file mode 100644
index 00000000000..073a210b4eb
--- /dev/null
+++ 
b/regression-test/data/datatype_p0/decimalv3/test_decimal128_checked_multiply.out
@@ -0,0 +1,51 @@
+-- This file is automatically generated. You should know what you did if you 
want to edit this
+-- !vector_vector --
+1      0       0
+2      99999999999999999999999999999999999999  
99999999999999999999999999999999999999
+3      -99999999999999999999999999999999999999 
-99999999999999999999999999999999999999
+4      99999999999999999999999999999999999999  
99999999999999999999999999999999999999
+5      999999999999999998000000000000000001    
999999999999999998000000000000000001
+6      -999999999999999998000000000000000001   
-999999999999999998000000000000000001
+7      85070591730234615865843651857942052864  
85070591730234615865843651857942052864
+8      -85070591730234615865843651857942052864 
-85070591730234615865843651857942052864
+9      -85070591730234615865843651857942052864 
-85070591730234615865843651857942052864
+10     85070591730234615865843651857942052864  
85070591730234615865843651857942052864
+11     \N      \N
+12     \N      \N
+
+-- !vector_constant --
+1      0       0
+2      0       -1
+3      0       1
+4      0       99999999999999999999999999999999999999
+5      0       -999999999999999999
+6      0       999999999999999999
+7      0       -18446744073709551616
+8      0       18446744073709551616
+9      0       -18446744073709551616
+10     0       18446744073709551616
+11     \N      \N
+12     0       -2
+
+-- !constant_vector --
+1      0       0
+2      0       -1
+3      0       1
+4      0       99999999999999999999999999999999999999
+5      0       -999999999999999999
+6      0       999999999999999999
+7      0       -18446744073709551616
+8      0       18446744073709551616
+9      0       -18446744073709551616
+10     0       18446744073709551616
+11     \N      \N
+12     0       -2
+
+-- !constant_constant --
+-85070591730234615865843651857942052864
+
+-- !scaled_products --
+1      11604.9298      12533.324184    -172.557000
+2      -11604.9298     -12533.324184   172.557000
+3      0.0000  0.000000        172.557000
+4      \N      \N      \N
diff --git 
a/regression-test/suites/datatype_p0/decimalv3/test_decimal128_checked_multiply.groovy
 
b/regression-test/suites/datatype_p0/decimalv3/test_decimal128_checked_multiply.groovy
new file mode 100644
index 00000000000..3aa609603f3
--- /dev/null
+++ 
b/regression-test/suites/datatype_p0/decimalv3/test_decimal128_checked_multiply.groovy
@@ -0,0 +1,138 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+suite("test_decimal128_checked_multiply") {
+    sql "set check_overflow_for_decimal = true"
+    sql "set enable_decimal256 = false"
+    // Keep constant expressions in the BE so constant multiplication paths 
are exercised.
+    sql "set debug_skip_fold_constant = true"
+
+    sql "drop table if exists test_decimal128_checked_multiply"
+    sql """
+        create table test_decimal128_checked_multiply (
+            id int,
+            a decimal(38, 0),
+            b decimal(38, 0)
+        ) distributed by hash(id) buckets 1
+        properties("replication_num" = "1")
+    """
+    sql """
+        insert into test_decimal128_checked_multiply values
+            (1, 0, 99999999999999999999999999999999999999),
+            (2, 1, 99999999999999999999999999999999999999),
+            (3, -1, 99999999999999999999999999999999999999),
+            (4, -99999999999999999999999999999999999999, -1),
+            (5, 999999999999999999, 999999999999999999),
+            (6, -999999999999999999, 999999999999999999),
+            (7, 18446744073709551616, 4611686018427387904),
+            (8, -18446744073709551616, 4611686018427387904),
+            (9, 18446744073709551616, -4611686018427387904),
+            (10, -18446744073709551616, -4611686018427387904),
+            (11, null, 2),
+            (12, 2, null)
+    """
+
+    qt_vector_vector """
+        select id, a * b, b * a
+        from test_decimal128_checked_multiply order by id
+    """
+    qt_vector_constant """
+        select id, a * cast('0' as decimal(1, 0)), a * cast('-1' as decimal(1, 
0))
+        from test_decimal128_checked_multiply order by id
+    """
+    qt_constant_vector """
+        select id, cast('0' as decimal(1, 0)) * a, cast('-1' as decimal(1, 0)) 
* a
+        from test_decimal128_checked_multiply order by id
+    """
+    qt_constant_constant """
+        select cast('-18446744073709551616' as decimal(20, 0))
+                 * cast('4611686018427387904' as decimal(19, 0))
+    """
+
+    sql "drop table if exists test_decimal128_checked_multiply_overflow"
+    sql """
+        create table test_decimal128_checked_multiply_overflow (
+            id int,
+            a decimal(38, 0),
+            b decimal(38, 0)
+        ) distributed by hash(id) buckets 1
+        properties("replication_num" = "1")
+    """
+    sql """
+        insert into test_decimal128_checked_multiply_overflow values
+            (1, 85070591730234615865843651857942052864, 2),
+            (2, -85070591730234615865843651857942052864, -2),
+            (3, -85070591730234615865843651857942052864, 3),
+            (4, 18446744073709551616, 18446744073709551616),
+            (5, -18446744073709551616, 18446744073709551616),
+            (6, -18446744073709551616, -18446744073709551616),
+            (7, 60000000000000000000000000000000000000, 2)
+    """
+    // Cover signed-range overflow, unsigned-128 overflow and Decimal(38,0) 
precision overflow.
+    for (int id = 1; id <= 7; ++id) {
+        test {
+            sql "select a * b from test_decimal128_checked_multiply_overflow 
where id = ${id}"
+            exception "Arithmetic overflow"
+        }
+    }
+    test {
+        sql """
+            select a * cast('2' as decimal(1, 0))
+            from test_decimal128_checked_multiply_overflow where id = 1
+        """
+        exception "Arithmetic overflow"
+    }
+    test {
+        sql """
+            select cast('2' as decimal(1, 0)) * a
+            from test_decimal128_checked_multiply_overflow where id = 1
+        """
+        exception "Arithmetic overflow"
+    }
+    test {
+        sql """
+            select cast('85070591730234615865843651857942052864' as 
decimal(38, 0))
+                     * cast('2' as decimal(1, 0))
+        """
+        exception "Arithmetic overflow"
+    }
+
+    sql "drop table if exists test_decimal128_checked_multiply_scaled"
+    sql """
+        create table test_decimal128_checked_multiply_scaled (
+            id int,
+            price decimal(15, 2),
+            discount decimal(15, 2),
+            tax decimal(15, 2),
+            a decimal(38, 18),
+            b decimal(38, 18)
+        ) distributed by hash(id) buckets 1
+        properties("replication_num" = "1")
+    """
+    sql """
+        insert into test_decimal128_checked_multiply_scaled values
+            (1, 12345.67, 0.06, 0.08, -15687.000000000000000000, 
0.011000000000000000),
+            (2, -12345.67, 0.06, 0.08, 15687.000000000000000000, 
0.011000000000000000),
+            (3, 0.00, 0.00, 0.00, -15687.000000000000000000, 
-0.011000000000000000),
+            (4, null, 0.06, 0.08, null, 0.011000000000000000)
+    """
+    // The scaled products exercise the wider intermediate fallback used after 
int128 overflow.
+    qt_scaled_products """
+        select id, price * (1 - discount), price * (1 - discount) * (1 + tax), 
a * b
+        from test_decimal128_checked_multiply_scaled order by id
+    """
+}


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to