204 Commits

Author SHA1 Message Date
Hiroaki Nakamura
3e667fd292 Use Managed.len in sub, divFloor, and divTrunc too 2022-07-16 11:46:13 +09:00
Hiroaki Nakamura
0cee8372cf Use Managed.len() instead of Managed.toConst().limbs.len 2022-07-16 08:14:16 +09:00
Hiroaki Nakamura
d63604b116 Fix std.math.big.int.Managed capacity after mul and sqr 2022-07-16 00:08:55 +09:00
Andrew Kelley
92bc3cbe27 stage2: fix comptime bitcast involving f80
* Sema: implement comptime bitcast of f80 with integer-like types
  bitwise rather than taking a round trip through memory layout.
* Type: introduce `isAbiInt`.
* Value: comptime memory write of f80 writes 0 bytes for padding
  instead of leaving the memory uninitialized.
* Value: floatReadFromMemory has a more general implementation, checking
  the endianness rather than checking for specific architectures.

This fixes behavior test failures occurring on MIPS.
2022-07-13 13:14:37 -07:00
Andrew Kelley
efe34243c6 std.math: add inline to some functions
These functions semantically benefit from being inline; it makes sense
that `isInf(x)` where `x` is comptime-known should have a
comptime-known result.
2022-07-13 11:14:46 -07:00
Andrew Kelley
6bc6e47b15 stage2: lower float negation explicitly
Rather than lowering float negation as `0.0 - x`.

 * Add AIR instruction for float negation.
 * Add compiler-rt functions for f128, f80 negation

closes #11853
2022-06-30 00:02:00 -07:00
Andrew Kelley
54454fd010 std.math.big.int: breaking API changes to prevent UAF
Many of the Managed methods accepted by-val parameters which could
reference Limb slices that became invalid memory after any
ensureCapacity calls. Now, Managed methods accept `*const Managed`
parameters so that if the function allows aliasing and the
ensure-capacity call resizes the Limb slice, it also affects the
aliased parameters, avoiding use-after-free bugs.

This is a breaking change that reduces the requirement for callsites to
manually make the ensure-capacity changes prior to calling many of the
Managed methods.

Closes #11897
2022-06-29 22:06:27 -04:00
Mikael Berthe
47c4d44502
std.math.big.int: update Managed.toString() to use provided allocator (#11839) 2022-06-13 17:19:37 +02:00
Veikka Tuominen
6b36774adc std: disable failing tests, add zig2 build test-std to CI 2022-06-12 10:43:28 +03:00
Cody Tapscott
70dc910086 std.math: Add O(log N) implementation of log2(x) for comptime_int
Since Zig provides @clz and not @ffs (find-first-set), log2 for comptime
integers needs to be computed algorithmically. To avoid hitting the
backward branch quota, this updates log2(x) to use a simple O(log N)
algorithm.
2022-06-07 20:07:40 -04:00
Veikka Tuominen
413577c881 std: adjust for stage2 semantics 2022-06-07 21:27:07 +03:00
Veikka Tuominen
9431100736 Sema: apply previous changes to validateUnionInit 2022-06-01 13:01:39 +03:00
Ali Chraghi
0e6285c8fc math: make cast return optional instead of an error 2022-05-27 16:43:33 -04:00
alice
951ab802a3
std.math: simpler error handling 2022-05-17 22:04:12 +01:00
alice
70b6b98e91
Simplify Copysign 2022-05-17 21:55:22 +01:00
alice
ceeec8d19f
Simplify signbit 2022-05-17 21:41:57 +01:00
leesongun
1de7b8d26c
std.math.powi: use standard definition of underflow/overflow, implement u0, i0, i1 edge case (#11499) 2022-05-16 18:28:20 -04:00
Andrew Kelley
0ffe82e624 std: use float builtins instead of std.math 2022-04-27 19:35:28 -07:00
Andrew Kelley
09f1d62bdf add new builtin function @tan
The reason for having `@tan` is that we already have `@sin` and `@cos`
because some targets have machine code instructions for them, but in the
case that the implementation needs to go into compiler-rt, sin, cos, and
tan all share a common dependency which includes a table of data. To
avoid duplicating this table of data, we promote tan to become a builtin
alongside sin and cos.

ZIR: The tag enum is at capacity so this commit moves
`field_call_bind_named` to be `extended`. I measured this as one of
the least used tags in the zig codebase.

Fix libc math suffix for `f32` being wrong in both stage1 and stage2.
stage1: add missing libc prefix for float functions.
2022-04-27 16:45:23 -07:00
Andrew Kelley
087aedfa38 stage2: fix recent LLVM backend code
* std.math.snan: fix compilation error. Also make it and nan inline.
 * LLVM: use a proper enum type for float op instead of enum literal.
   Also various cleanups.
 * LLVM: use LLVMBuildVectorSplat for vector splat AIR instruction.
   - also the bindings had parameter order wrong
 * LLVM: additionally handle f16 lowering. For now all targets report OK
   but I think we will need to add some exceptions to this list.
2022-04-27 14:18:34 -07:00
Andrew Kelley
41dd2beaac compiler-rt: math functions reorg
* unify the logic for exporting math functions from compiler-rt,
   with the appropriate suffixes and prefixes.
   - add all missing f128 and f80 exports. Functions with missing
     implementations call other functions and have TODO comments.
   - also add f16 functions
 * move math functions from freestanding libc to compiler-rt (#7265)
 * enable all the f128 and f80 code in the stage2 compiler and behavior
   tests (#11161).
 * update std lib to use builtins rather than `std.math`.
2022-04-27 12:20:44 -07:00
Cody Tapscott
f5540778b5 stdlib: Fix hex-float printing for f80 2022-04-25 17:21:09 -07:00
vi
4ad1480298
std.math.fabs: enable f80 testing 2022-04-15 16:52:02 -06:00
vi
2ef9a0d9ae
std.math: enable f80 tests on freebsd 2022-04-15 16:50:00 -06:00
Veikka Tuominen
845a30624f std: add workaround for stage2 bug 2022-04-15 11:17:19 +03:00
vi
6ad9ac59e7 std.math.float: fix f80-backed c_longdouble consts 2022-04-14 02:55:46 -04:00
Cody Tapscott
319555a669 Add floatFractionalBits to replace floatMantissaDigits 2022-04-12 12:33:16 -07:00
viri
f9a9e8ba73
std.math.isInf: add tests for +-NaN 2022-04-08 20:13:30 -06:00
viri
e46c612503
use math/float.zig everywhere 2022-04-07 05:04:38 -06:00
viri
5d6a5a1236
std.math.is*Inf: make generic, support f80 2022-04-07 05:04:03 -06:00
viri
c5c6260534
std.math: generalise inf, even simpler isFinite 2022-04-07 02:38:31 -06:00
viri
a2f5f0da5c
std.math.isFinite: make generic, support f80 2022-04-07 02:38:28 -06:00
viri
7b7f45dc2a std.{fmt, math}: derive float constants from std
This also addresses a nit from #10133 where IntT might be a confusing
name because it might imply signed integer (iX, not uX). We settled on
TBits for math/float.zig so I've applied that change here too.

When I originally wrote ldexp() I copied the name from parse_hex_float.
2022-04-06 15:50:36 +02:00
viri
cb019b80ac math.fabs: simplify implementation, add tests 2022-04-06 15:50:36 +02:00
viri
2f6ee4a97d math.isNormal: simplify implementation, add tests 2022-04-06 15:50:36 +02:00
viri
5b8ac9821d derive float constants in a generic way (#10133) 2022-04-06 15:50:36 +02:00
Damien Firmenich
5fafcc2b62
zig fmt: remove trailing whitespace on doc comments
Fixes #11353

The renderer treats comments and doc comments differently since doc
comments are parsed into the Ast. This commit adds a check after getting
the text for the doc comment and trims whitespace at the end before
rendering.

The `a = 0,` in the test is here to avoid a ParseError while parsing the
test.
2022-04-05 18:08:33 +03:00
BlueAlmost
406507c6dc
std.math.Complex: add 'negation' and 'mulitply by i' 2022-03-27 11:54:43 +03:00
Marc Tiehuis
2e0de0b4e2
math/big: correct fix for divmod (#11271)
Fixes #11166.
2022-03-23 19:24:25 +01:00
Andrew Kelley
2a50a4629b freestanding libc: include roundl 2022-03-14 00:11:46 -07:00
Marc Tiehuis
8bab1b405f math: fix big.int div, gcd and bitAnd edge-cases
Fixes #10932.
2022-03-10 13:56:07 -05:00
Andrew Kelley
71b8760d3b stage2: rework @mulAdd
* mul_add AIR instruction: use `pl_op` instead of `ty_pl`. The type is
   always the same as the operand; no need to waste bytes redundantly
   storing the type.
 * AstGen: use coerced_ty for all the operands except for one which we
   use to communicate the type.
 * Sema: use the correct source location for requireRuntimeBlock in
   handling of `@mulAdd`.
 * native backends: handle liveness even for the functions that are
   TODO.
 * C backend: implement `@mulAdd`. It lowers to libc calls.
 * LLVM backend: make `@mulAdd` handle all float types.
   - improved fptrunc and fpext to handle f80 with compiler-rt calls.
 * Value.mulAdd: handle all float types and use the `@mulAdd` builtin.
 * behavior tests: revert the changes to testing `@mulAdd`. These
   changes broke the test coverage, making it only tested at
   compile-time.

Improved f80 support:
 * std.math.fma handles f80
 * move fma functions from freestanding libc to compiler-rt
   - add __fmax and fmal
   - make __fmax and fmaq only exported when they don't alias fmal.
   - make their linkage weak just like the rest of compiler-rt symbols.
 * removed `longDoubleIsF128` and replaced it with `longDoubleIs` which
   takes a type as a parameter. The implementation is now more accurate
   and handles more targets. Similarly, in stage2 the function
   CTypes.sizeInBits is more accurate for long double for more targets.
2022-03-06 16:11:39 -07:00
Cody Tapscott
ef417f19e1 stage2: Implement @bitReverse and @byteSwap
This change implements the above built-ins for Sema and the LLVM
backend. Other backends have had placeholders added for lowering.
2022-02-18 14:28:32 -07:00
Andrew Kelley
736b9dcdd6
Merge pull request #10858 from topolarity/stage2-bitcast
stage2 sema: Fix sign handling of exotic integers in `@bitCast`
2022-02-18 13:49:00 -05:00
J87
b837855317 Replace magic numbers with clearer representation
Replaces two magic numbers with the procedure used to generate them, in order to keep consistent with other implementations for f64 & f128.
2022-02-17 21:20:04 -05:00
Cody Tapscott
c586e3ba1b Add additional tests for @bitCast 2022-02-13 13:28:08 -07:00
Cody Tapscott
7b72fc6bbc Add abi_size parameter to read/writeTwosComplement
Big-int functions were updated to respect the provided abi_size, rather
than inferring a potentially incorrect abi_size implicitly.

In combination with the convention that any required padding bits are
added on the MSB end, this means that exotic integers can potentially
have a well-defined memory layout.
2022-02-13 13:26:59 -07:00
Cody Tapscott
70d7f87be0 Fix up sign handling and add arbitrary-length integer support to @bitCast() 2022-02-11 08:49:19 -07:00
Marc Tiehuis
53e6c719ef std/math: optimize division with divisors less than a half-limb
This adds a new path which avoids using compiler_rt generated div
udivmod instructions in the case that a divisor is less than half the
max usize value. Two half-limb divisions are performed instead which
ensures that non-emulated division instructions are actually used. This
does not improve the udivmod code which should still be reviewed
independently of this issue.

Notably this improves the performance of the toString implementation of
non-power-of-two bases considerably.

Division performance is improved ~1000% based on some coarse testing.

The following test code is used to provide a rough comparison between
the old vs. new method.

```
const std = @import("std");
const Managed = std.math.big.int.Managed;

const allocator = std.heap.c_allocator;

fn fib(a: *Managed, n: usize) !void {
    var b = try Managed.initSet(allocator, 1);
    defer b.deinit();
    var c = try Managed.init(allocator);
    defer c.deinit();

    var i: usize = 0;
    while (i < n) : (i += 1) {
        try c.add(a.toConst(), b.toConst());

        a.swap(&b);
        b.swap(&c);
    }
}

pub fn main() !void {
    var a = try Managed.initSet(allocator, 0);
    defer a.deinit();

    try fib(&a, 1_000_000);

    // Note: Next two lines (and printed digit count) omitted on no-print version.
    const as = try a.toString(allocator, 10, .lower);
    defer allocator.free(as);

    std.debug.print("fib: digit count: {}, limb count: {}\n", .{ as.len, a.limbs.len });
}
```

```
==> time.no-print <==
limb count: 10849

________________________________________________________
Executed in   10.60 secs    fish           external
   usr time   10.44 secs    0.00 millis   10.44 secs
   sys time    0.02 secs    1.12 millis    0.02 secs

==> time.old <==
fib: digit count: 208988, limb count: 10849

________________________________________________________
Executed in   22.78 secs    fish           external
   usr time   22.43 secs    1.01 millis   22.43 secs
   sys time    0.03 secs    0.13 millis    0.03 secs

==> time.optimized <==
fib: digit count: 208988, limb count: 10849

________________________________________________________
Executed in   11.59 secs    fish           external
   usr time   11.56 secs    1.03 millis   11.56 secs
   sys time    0.03 secs    0.12 millis    0.03 secs
```

Perf data for non-optimized and optimized, verifying no udivmod is
generated by the new code.

```
$ perf report -i perf.data.old --stdio
- Total Lost Samples: 0
-
- Samples: 90K of event 'cycles:u'
- Event count (approx.): 71603695208
-
- Overhead  Command  Shared Object     Symbol
- ........  .......  ................  ...........................................
-
    52.97%  t        t                 [.] compiler_rt.udivmod.udivmod
    45.97%  t        t                 [.] std.math.big.int.Mutable.addCarry
     0.83%  t        t                 [.] main
     0.08%  t        libc-2.33.so      [.] __memmove_avx_unaligned_erms
     0.08%  t        t                 [.] __udivti3
     0.03%  t        [unknown]         [k] 0xffffffff9a0010a7
     0.02%  t        t                 [.] std.math.big.int.Managed.ensureCapacity
     0.01%  t        libc-2.33.so      [.] _int_malloc
     0.00%  t        libc-2.33.so      [.] __malloc_usable_size
     0.00%  t        libc-2.33.so      [.] _int_free
     0.00%  t        t                 [.] 0x0000000000004a80
     0.00%  t        t                 [.] std.heap.CAllocator.resize
     0.00%  t        libc-2.33.so      [.] _mid_memalign
     0.00%  t        libc-2.33.so      [.] sysmalloc
     0.00%  t        libc-2.33.so      [.] __posix_memalign
     0.00%  t        t                 [.] std.heap.CAllocator.alloc
     0.00%  t        ld-2.33.so        [.] do_lookup_x

$ perf report -i perf.data.optimized --stdio
- Total Lost Samples: 0
-
- Samples: 46K of event 'cycles:u'
- Event count (approx.): 36790112336
-
- Overhead  Command  Shared Object     Symbol
- ........  .......  ................  ...........................................
-
    79.98%  t        t                 [.] std.math.big.int.Mutable.addCarry
    15.14%  t        t                 [.] main
     4.58%  t        t                 [.] std.math.big.int.Managed.ensureCapacity
     0.21%  t        libc-2.33.so      [.] __memmove_avx_unaligned_erms
     0.05%  t        [unknown]         [k] 0xffffffff9a0010a7
     0.02%  t        libc-2.33.so      [.] _int_malloc
     0.01%  t        t                 [.] std.heap.CAllocator.alloc
     0.01%  t        libc-2.33.so      [.] __malloc_usable_size
     0.00%  t        libc-2.33.so      [.] systrim.constprop.0
     0.00%  t        libc-2.33.so      [.] _mid_memalign
     0.00%  t        t                 [.] 0x0000000000000c7d
     0.00%  t        libc-2.33.so      [.] malloc
     0.00%  t        ld-2.33.so        [.] check_match
```

Closes #10630.
2022-02-06 21:39:34 -05:00
Jonathan S
aca665cebd
Fix overflow in std.math.isNormal when applied to -Inf or a negative NaN 2022-01-29 18:11:49 +02:00