[Tarantool-patches] [PATCH luajit] Fix narrowing of unary minus.

Maksim Kokryashkin max.kokryashkin at gmail.com
Fri Sep 9 15:15:28 MSK 2022


From: Mike Pall <mike>

With DUALNUM mode disabled, unary minus narrowing can produce
inconsistent results on zeros, returning both -0 and 0 on the
same chunk of code.

This patch fixes the inconsistency by adding checks for zeros.

Part of tarantool/tarantool#7230
Resolves tarantool/tarantool#6976
---
Issue: https://github.com/tarantool/tarantool/issues/6976
Branch: https://github.com/tarantool/luajit/tree/fckxorg/gh-6976-narrowing-of-unary-minus
PR: https://github.com/tarantool/tarantool/pull/7662

 src/lj_opt_narrow.c                           |  9 +++--
 .../gh-6976-narrowing-of-unary-minus.test.lua | 34 +++++++++++++++++++
 2 files changed, 41 insertions(+), 2 deletions(-)
 create mode 100644 test/tarantool-tests/gh-6976-narrowing-of-unary-minus.test.lua

diff --git a/src/lj_opt_narrow.c b/src/lj_opt_narrow.c
index cd96ca4b..bb61f97b 100644
--- a/src/lj_opt_narrow.c
+++ b/src/lj_opt_narrow.c
@@ -551,8 +551,13 @@ TRef lj_opt_narrow_unm(jit_State *J, TRef rc, TValue *vc)
 {
   rc = conv_str_tonum(J, rc, vc);
   if (tref_isinteger(rc)) {
-    if ((uint32_t)numberVint(vc) != 0x80000000u)
-      return emitir(IRTGI(IR_SUBOV), lj_ir_kint(J, 0), rc);
+    uint32_t k = (uint32_t)numberVint(vc);
+    if ((LJ_DUALNUM || k != 0) && k != 0x80000000u) {
+      TRef zero = lj_ir_kint(J, 0);
+      if (!LJ_DUALNUM)
+	emitir(IRTGI(IR_NE), rc, zero);
+      return emitir(IRTGI(IR_SUBOV), zero, rc);
+    }
     rc = emitir(IRTN(IR_CONV), rc, IRCONV_NUM_INT);
   }
   return emitir(IRTN(IR_NEG), rc, lj_ir_ksimd(J, LJ_KSIMD_NEG));
diff --git a/test/tarantool-tests/gh-6976-narrowing-of-unary-minus.test.lua b/test/tarantool-tests/gh-6976-narrowing-of-unary-minus.test.lua
new file mode 100644
index 00000000..caae8c34
--- /dev/null
+++ b/test/tarantool-tests/gh-6976-narrowing-of-unary-minus.test.lua
@@ -0,0 +1,34 @@
+require("utils").skipcond(
+  jit.arch ~= "x86" and jit.arch ~= "x64",
+  "DUALNUM mode must be disabled"
+)
+
+local tap = require("tap")
+local test = tap.test("gh-6976-narrowing-of-unary-minus")
+test:plan(1)
+
+jit.off()
+jit.flush()
+jit.opt.start('hotloop=1')
+jit.on()
+
+local has_error = false
+
+-- The first two iterations are needed to write trace in a way
+-- where `a` is treated like a non-zero integer value. After the
+-- first two iterations 'a' becomes a zero integer, but it is still
+-- processed by the same trace. Finally, roughly ten loop
+-- iterations later, a new trace is formed, where `a` is treated
+-- like a number.
+for i=1,20 do
+  local a = 1
+  if i > 2 then
+    a = 0
+  end
+  a = -a
+  has_error = has_error or tostring(a):match("%-%d") == nil
+end
+
+test:ok(has_error == false, "inconsistent unary minus result")
+os.exit(test:check() and 0 or 1)
+
-- 
2.32.1 (Apple Git-133)



More information about the Tarantool-patches mailing list