Commit 5f96b146

5f96b1460568Merged

Yukihiro "Matz" Matsumoto <[email protected]> · 5 months ago · 3 files · +2 added · ~1 modified

Description

analyze: type a literal integer power that overflows int64 as a bigint

10 ** 30 / 2 ** 70 lowered through sp_int_pow, which computes the power in double precision and casts back to mrb_int -- saturating to LLONG_MAX (10 ** 30 printed 9223372036854775807). A literal power whose result exceeds int64 is a Bignum in every overflow mode in CRuby, independent of --int-overflow.

When both operands of ** are plain int literals and base**exp does not fit in signed 64 bits, infer it as TY_BIGINT; the existing bigint operator codegen then emits sp_bigint_pow(sp_bigint_new_int(base), exp). A power that fits (2 ** 10) stays a plain Integer, so normal exponents are unaffected.

Co-Authored-By: Claude Opus 4.8 [email protected]

Details

Commit
5f96b1460568
Parent
9089156cb709

src/analyze_infer.cmodifiedView file

@@ -250,6 +250,25 @@
250250 return ivar_array_elems_all_int_array(c, cid, ivname);
251251 }
252252
253+/* A plain int literal value (not an out-of-int64 bigint literal). */
254+static int infer_const_int_node(const NodeTable *nt, int id, long long *out) {
255+ const char *ty = nt_type(nt, id);
256+ if (!ty || strcmp(ty, "IntegerNode")) return 0;
257+ if (nt_str(nt, id, "bigval")) return 0;
258+ *out = (long long)nt_int(nt, id, "value", 0);
259+ return 1;
260+}
261+
262+/* Whether base**exp does not fit in signed 64 bits (so it must be a Bignum). */
263+static int infer_int_pow_overflows(long long base, long long exp) {
264+ if (exp <= 0) return 0;
265+ if (base >= -1 && base <= 1) return 0;
266+ long long r = 1;
267+ for (long long i = 0; i < exp; i++)
268+ if (__builtin_mul_overflow(r, base, &r)) return 1;
269+ return 0;
270+}
271+
253272 TyKind infer_call(Compiler *c, int id) {
254273 const NodeTable *nt = c->nt;
255274 const char *name = nt_str(nt, id, "name");
@@ -263,6 +282,16 @@
263282 TyKind rt = recv >= 0 ? infer_type(c, recv) : TY_UNKNOWN;
264283 TyKind a0 = argc >= 1 ? infer_type(c, argv[0]) : TY_UNKNOWN;
265284
285+ /* A literal integer power whose result exceeds int64 (`10 ** 30`, `2 ** 70`)
286+ is a Bignum in every overflow mode (CRuby). Type it bigint so codegen emits
287+ sp_bigint_pow rather than the saturating float sp_int_pow. */
288+ if (!strcmp(name, "**") && recv >= 0 && argc == 1) {
289+ long long base, exp;
290+ if (infer_const_int_node(nt, recv, &base) && infer_const_int_node(nt, argv[0], &exp) &&
291+ infer_int_pow_overflows(base, exp))
292+ return TY_BIGINT;
293+ }
294+
266295 /* `@table[i][j]` on a poly-array dispatch table of int-returning entries
267296 yields an int (a method/peek table). Resolves the optcarrot CPU's
268297 fetch/peek/store, which would otherwise run boxed-poly. */