GHC issueshttps://gitlab.haskell.org/ghc/ghc/-/issues2019-08-20T23:35:34Zhttps://gitlab.haskell.org/ghc/ghc/-/issues/16150Data races in itimer_thread_func reported by ThreadSanitizer2019-08-20T23:35:34ZgnezdoData races in itimer_thread_func reported by ThreadSanitizerOur local environment allows running Haskell programs under ThreadSanitizer. Even though the GHC runtime and compiled Haskell code are not instrumented, ThreadSanitizer still found a bug through interceptor instrumentation. I'll try to m...Our local environment allows running Haskell programs under ThreadSanitizer. Even though the GHC runtime and compiled Haskell code are not instrumented, ThreadSanitizer still found a bug through interceptor instrumentation. I'll try to minimize the case and create a reproducer, but in case somebody wants to look at this with just the report, here it is (mildly massaged to remove irrelevant addresses):
```
==================
WARNING: ThreadSanitizer: data race (pid=2367)
Write of size 1 at 0x55986a3e4f10 by thread T1:
#0 pthread_mutex_destroy llvm/compiler-rt/lib/tsan/rtl/tsan_interceptors.cc:1245:3
#1 itimer_thread_func vendor_src/v8_4_4/rts/posix/itimer/Pthread.c:152:5
Previous atomic read of size 1 at 0x55986a3e4f10 by main thread:
#0 pthread_mutex_lock llvm/compiler-rt/lib/sanitizer_common/sanitizer_common_interceptors.inc:4097:3
#1 startTicker vendor_src/v8_4_4/rts/posix/itimer/Pthread.c:184:5
#2 exitTicker vendor_src/v8_4_4/rts/posix/itimer/Pthread.c:206
#3 __libc_start_main <null> (libc.so.6+0x38bbc)
Location is global 'mutex' of size 40 at 0x55986a3e4f10
Thread T1 'ghc_ticker' (tid=2369, running) created by main thread at:
#0 pthread_create llvm/compiler-rt/lib/tsan/rtl/tsan_interceptors.cc:980:3
#1 initTicker vendor_src/v8_4_4/rts/posix/itimer/Pthread.c:171:11
#2 __libc_start_main <null> (libc.so.6+0x38bbc)
SUMMARY: ThreadSanitizer: data race vendor_src/v8_4_4/rts/posix/itimer/Pthread.c:152:5 in itimer_thread_func
==================
==================
WARNING: ThreadSanitizer: data race (pid=2367)
Write of size 8 at 0x55986a3e4ee0 by thread T1:
#0 pthread_cond_destroy llvm/compiler-rt/lib/tsan/rtl/tsan_interceptors.cc:1216:3
#1 itimer_thread_func vendor_src/v8_4_4/rts/posix/itimer/Pthread.c:153:5
Previous read of size 8 at 0x55986a3e4ee0 by main thread (mutexes: write M146179626018688784):
#0 pthread_cond_signal llvm/compiler-rt/lib/tsan/rtl/tsan_interceptors.cc:1202:3
#1 signalCondition vendor_src/v8_4_4/rts/posix/OSThreads.c:111:11
#2 __libc_start_main <null> (libc.so.6+0x38bbc)
Location is global 'start_cond' of size 48 at 0x55986a3e4ee0
Mutex M146179626018688784 is already destroyed.
Thread T1 'ghc_ticker' (tid=2369, running) created by main thread at:
#0 pthread_create llvm/compiler-rt/lib/tsan/rtl/tsan_interceptors.cc:980:3
#1 initTicker vendor_src/v8_4_4/rts/posix/itimer/Pthread.c:171:11
#2 __libc_start_main <null> (libc.so.6+0x38bbc)
SUMMARY: ThreadSanitizer: data race vendor_src/v8_4_4/rts/posix/itimer/Pthread.c:153:5 in itimer_thread_func
==================
ThreadSanitizer: reported 2 warnings
```
<details><summary>Trac metadata</summary>
| Trac field | Value |
| ---------------------- | ------------------ |
| Version | 8.4.4 |
| Type | Bug |
| TypeOfFailure | OtherFailure |
| Priority | normal |
| Resolution | Unresolved |
| Component | Runtime System |
| Test case | |
| Differential revisions | |
| BlockedBy | |
| Related | |
| Blocking | |
| CC | dvyukov@google.com |
| Operating system | |
| Architecture | |
</details>
<!-- {"blocked_by":[],"summary":"Data races in itimer_thread_func reported by ThreadSanitizer","status":"New","operating_system":"","component":"Runtime System","related":[],"milestone":"","resolution":"Unresolved","owner":{"tag":"Unowned"},"version":"8.4.4","keywords":[],"differentials":[],"test_case":"","architecture":"","cc":["dvyukov@google.com"],"type":"Bug","description":"Our local environment allows running Haskell programs under ThreadSanitizer. Even though the GHC runtime and compiled Haskell code are not instrumented, ThreadSanitizer still found a bug through interceptor instrumentation. I'll try to minimize the case and create a reproducer, but in case somebody wants to look at this with just the report, here it is (mildly massaged to remove irrelevant addresses):\r\n\r\n{{{\r\n==================\r\nWARNING: ThreadSanitizer: data race (pid=2367)\r\n Write of size 1 at 0x55986a3e4f10 by thread T1:\r\n #0 pthread_mutex_destroy llvm/compiler-rt/lib/tsan/rtl/tsan_interceptors.cc:1245:3 \r\n #1 itimer_thread_func vendor_src/v8_4_4/rts/posix/itimer/Pthread.c:152:5 \r\n\r\n Previous atomic read of size 1 at 0x55986a3e4f10 by main thread:\r\n #0 pthread_mutex_lock llvm/compiler-rt/lib/sanitizer_common/sanitizer_common_interceptors.inc:4097:3 \r\n #1 startTicker vendor_src/v8_4_4/rts/posix/itimer/Pthread.c:184:5 \r\n #2 exitTicker vendor_src/v8_4_4/rts/posix/itimer/Pthread.c:206 \r\n #3 __libc_start_main <null> (libc.so.6+0x38bbc)\r\n\r\n Location is global 'mutex' of size 40 at 0x55986a3e4f10 \r\n\r\n Thread T1 'ghc_ticker' (tid=2369, running) created by main thread at:\r\n #0 pthread_create llvm/compiler-rt/lib/tsan/rtl/tsan_interceptors.cc:980:3 \r\n #1 initTicker vendor_src/v8_4_4/rts/posix/itimer/Pthread.c:171:11 \r\n #2 __libc_start_main <null> (libc.so.6+0x38bbc)\r\n\r\nSUMMARY: ThreadSanitizer: data race vendor_src/v8_4_4/rts/posix/itimer/Pthread.c:152:5 in itimer_thread_func\r\n==================\r\n==================\r\nWARNING: ThreadSanitizer: data race (pid=2367)\r\n Write of size 8 at 0x55986a3e4ee0 by thread T1:\r\n #0 pthread_cond_destroy llvm/compiler-rt/lib/tsan/rtl/tsan_interceptors.cc:1216:3 \r\n #1 itimer_thread_func vendor_src/v8_4_4/rts/posix/itimer/Pthread.c:153:5 \r\n\r\n Previous read of size 8 at 0x55986a3e4ee0 by main thread (mutexes: write M146179626018688784):\r\n #0 pthread_cond_signal llvm/compiler-rt/lib/tsan/rtl/tsan_interceptors.cc:1202:3 \r\n #1 signalCondition vendor_src/v8_4_4/rts/posix/OSThreads.c:111:11 \r\n #2 __libc_start_main <null> (libc.so.6+0x38bbc)\r\n\r\n Location is global 'start_cond' of size 48 at 0x55986a3e4ee0 \r\n\r\n Mutex M146179626018688784 is already destroyed.\r\n\r\n Thread T1 'ghc_ticker' (tid=2369, running) created by main thread at:\r\n #0 pthread_create llvm/compiler-rt/lib/tsan/rtl/tsan_interceptors.cc:980:3 \r\n #1 initTicker vendor_src/v8_4_4/rts/posix/itimer/Pthread.c:171:11 \r\n #2 __libc_start_main <null> (libc.so.6+0x38bbc)\r\n\r\nSUMMARY: ThreadSanitizer: data race vendor_src/v8_4_4/rts/posix/itimer/Pthread.c:153:5 in itimer_thread_func\r\n==================\r\nThreadSanitizer: reported 2 warnings\r\n}}}","type_of_failure":"OtherFailure","blocking":[]} -->8.6.4https://gitlab.haskell.org/ghc/ghc/-/issues/16197Strictness is not preserved under -O12021-09-21T14:11:59ZAlex LangStrictness is not preserved under -O1With -O0, the attached code prints:
```
> /usr/local/ghc/ghc-8.4.1.0/bin/ghc -O0 src/foo.hs; and ./src/foo
[1 of 1] Compiling Main ( src/foo.hs, src/foo.o ) [Optimisation flags changed]
Linking src/foo ...
("exec",0)
("depth...With -O0, the attached code prints:
```
> /usr/local/ghc/ghc-8.4.1.0/bin/ghc -O0 src/foo.hs; and ./src/foo
[1 of 1] Compiling Main ( src/foo.hs, src/foo.o ) [Optimisation flags changed]
Linking src/foo ...
("exec",0)
("depth",0)
("exec",1)
("depth",0)
```
But with -O1, it prints:
```
> /usr/local/ghc/ghc-8.4.1.0/bin/ghc -O1 src/foo.hs; and ./src/foo
[1 of 1] Compiling Main ( src/foo.hs, src/foo.o )
Linking src/foo ...
("depth",0)
("depth",0)
```
Reproduced with 8.4.1 and 8.6.2. Doesn't seem to happen under 8.2.0
<details><summary>Trac metadata</summary>
| Trac field | Value |
| ---------------------- | ------------ |
| Version | 8.4.1 |
| Type | Bug |
| TypeOfFailure | OtherFailure |
| Priority | normal |
| Resolution | Unresolved |
| Component | Compiler |
| Test case | |
| Differential revisions | |
| BlockedBy | |
| Related | |
| Blocking | |
| CC | me@alang.ca |
| Operating system | |
| Architecture | |
</details>
<!-- {"blocked_by":[],"summary":"Strictness is not preserved under -O1","status":"New","operating_system":"","component":"Compiler","related":[],"milestone":"","resolution":"Unresolved","owner":{"tag":"Unowned"},"version":"8.4.1","keywords":[],"differentials":[],"test_case":"","architecture":"","cc":["me@alang.ca"],"type":"Bug","description":"With -O0, the attached code prints:\r\n\r\n{{{\r\n> /usr/local/ghc/ghc-8.4.1.0/bin/ghc -O0 src/foo.hs; and ./src/foo\r\n[1 of 1] Compiling Main ( src/foo.hs, src/foo.o ) [Optimisation flags changed]\r\nLinking src/foo ...\r\n(\"exec\",0)\r\n(\"depth\",0)\r\n(\"exec\",1)\r\n(\"depth\",0)\r\n}}}\r\n\r\nBut with -O1, it prints:\r\n\r\n{{{\r\n> /usr/local/ghc/ghc-8.4.1.0/bin/ghc -O1 src/foo.hs; and ./src/foo\r\n[1 of 1] Compiling Main ( src/foo.hs, src/foo.o )\r\nLinking src/foo ...\r\n(\"depth\",0)\r\n(\"depth\",0)\r\n}}}\r\n\r\nReproduced with 8.4.1 and 8.6.2. Doesn't seem to happen under 8.2.0\r\n","type_of_failure":"OtherFailure","blocking":[]} -->8.8.1https://gitlab.haskell.org/ghc/ghc/-/issues/16222PPC NCG: C calling convention violated for integers smaller than word size2019-07-07T18:00:54ZPeter Trommlerptrommler@acm.orgPPC NCG: C calling convention violated for integers smaller than word sizeThe C calling convention for powerpc64 and powerpc64le require simple integer types to be zero or sign extended to 64 bit. The PPC NCG assumes that all values have been promoted to word size but now we introduced integer operations on sm...The C calling convention for powerpc64 and powerpc64le require simple integer types to be zero or sign extended to 64 bit. The PPC NCG assumes that all values have been promoted to word size but now we introduced integer operations on smaller than machine word size and in general we cannot assume that values have been promoted anymore.
When a value is not promoted and passed to a foreign function on the stack that value will be in the wrong position within the stack slot on big endian systems and the function will deliver wrong results. On little endian systems we still get correct results as long as we stay in the smaller integer range.
<details><summary>Trac metadata</summary>
| Trac field | Value |
| ---------------------- | ----------------------------- |
| Version | 8.7 |
| Type | Bug |
| TypeOfFailure | OtherFailure |
| Priority | normal |
| Resolution | Unresolved |
| Component | Compiler (FFI) |
| Test case | |
| Differential revisions | |
| BlockedBy | |
| Related | |
| Blocking | |
| CC | bgamari, erikd, hvr, simonmar |
| Operating system | |
| Architecture | |
</details>
<!-- {"blocked_by":[],"summary":"PPC NCG: C calling convention violated for integers smaller than word size","status":"New","operating_system":"","component":"Compiler (FFI)","related":[],"milestone":"8.10.1","resolution":"Unresolved","owner":{"tag":"Unowned"},"version":"8.7","keywords":["big","endian"],"differentials":[],"test_case":"","architecture":"","cc":["bgamari","erikd","hvr","simonmar"],"type":"Bug","description":"The C calling convention for powerpc64 and powerpc64le require simple integer types to be zero or sign extended to 64 bit. The PPC NCG assumes that all values have been promoted to word size but now we introduced integer operations on smaller than machine word size and in general we cannot assume that values have been promoted anymore.\r\n\r\nWhen a value is not promoted and passed to a foreign function on the stack that value will be in the wrong position within the stack slot on big endian systems and the function will deliver wrong results. On little endian systems we still get correct results as long as we stay in the smaller integer range.","type_of_failure":"OtherFailure","blocking":[]} -->8.10.1Peter Trommlerptrommler@acm.orgPeter Trommlerptrommler@acm.orghttps://gitlab.haskell.org/ghc/ghc/-/issues/16258PowerPC Big-Endian: ArithInt16, ArithInt8, ArithWord16, and ArithWord8 fail2023-10-25T09:09:04ZPeter Trommlerptrommler@acm.orgPowerPC Big-Endian: ArithInt16, ArithInt8, ArithWord16, and ArithWord8 failThe tests were run on a PowerMac G5 running Linux, PowerMacs are big-endian.
I reduced the issue to this program where I get the incorrect answer `25132`:
```hs
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE MagicHash #-}
{-# LANGUAGE Unbo...The tests were run on a PowerMac G5 running Linux, PowerMacs are big-endian.
I reduced the issue to this program where I get the incorrect answer `25132`:
```hs
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE MagicHash #-}
{-# LANGUAGE UnboxedTuples #-}
module Main where
import GHC.Exts
main :: IO ()
main = do
putStrLn $ show (apply2 plusInt16# (50) (50))
apply2 :: (Int16# -> Int16# -> Int16#) -> Int -> Int -> Int
apply2 op (I# a) (I# b) =
let (# sa, sb #) = (# narrowInt16# a, narrowInt16# b #)
r = op sa sb
in I# (extendInt16# r)
{-# NOINLINE apply2 #-}
```
Curiously, when I inline `plusInt16#` and remove the op parameter the result is correct.
The test passes on little-endian PowerPC 64-bit.
Note: This bug is different from #16222, which deals with the C calling convention.8.10.1Peter Trommlerptrommler@acm.orgPeter Trommlerptrommler@acm.orghttps://gitlab.haskell.org/ghc/ghc/-/issues/16514Fix for #14619 is wrong2020-02-25T01:14:44ZDuane RyragFix for #14619 is wrongThe fix for #14619 is wrong. Please see https://gitlab.haskell.org/ghc/ghc/commit/add4e1f11b88cd603f6c01bc135eb576e1922a8e#note_190830.The fix for #14619 is wrong. Please see https://gitlab.haskell.org/ghc/ghc/commit/add4e1f11b88cd603f6c01bc135eb576e1922a8e#note_190830.8.6.5https://gitlab.haskell.org/ghc/ghc/-/issues/16586KnownNat: result changes depending on optimizations2022-09-29T15:25:07ZBodigrimKnownNat: result changes depending on optimizations# Summary
The following program changes output from `1` (without optimizations) to `331` (with `-O1`).
# Steps to reproduce
```haskell
{-# LANGUAGE DataKinds, PolyKinds, RankNTypes, ScopedTypeVariables #-}
module Main where
import D...# Summary
The following program changes output from `1` (without optimizations) to `331` (with `-O1`).
# Steps to reproduce
```haskell
{-# LANGUAGE DataKinds, PolyKinds, RankNTypes, ScopedTypeVariables #-}
module Main where
import Data.Proxy
import GHC.TypeNats
import Numeric.Natural
newtype Foo (m :: Nat) = Foo { getVal :: Word }
mul :: KnownNat m => Foo m -> Foo m -> Foo m
mul mx@(Foo x) (Foo y) =
Foo $ x * y `rem` fromIntegral (natVal mx)
pow :: KnownNat m => Foo m -> Int -> Foo m
pow x k = iterate (`mul` x) (Foo 1) !! k
modl :: (forall m. KnownNat m => Foo m) -> Natural -> Word
modl x m = case someNatVal m of
SomeNat (_ :: Proxy m) -> getVal (x :: Foo m)
main :: IO ()
main = print $ (Foo 127 `pow` 31336) `modl` 31337
dummyValue :: Word
dummyValue = (Foo 33 `pow` 44) `modl` 456
```
```
$ ghc -fforce-recomp Mod.hs && ./Mod
1
$ ghc -fforce-recomp -O Mod.hs && ./Mod
313
```
# Expected behavior
The [expected output](https://www.wolframalpha.com/input/?i=127+%5E+31336+mod+31337) is `1`.
While `dummyValue` is absolutely unused and should not have any impact, compilation with `-O` somehow replaces `31337` in `main` with `456`, producing [313](https://www.wolframalpha.com/input/?i=127+%5E+31336+mod+456). This can be also verified by dumping Core: it does not even contain `31337` anywhere, but surprisingly includes `456`.
Any of the following restores the behaviour of `-O1` program to expected:
* Remove `module Main where` line.
* Switch from `GHC.TypeNats` to `GHC.TypeLits`.
* Change ``(`mul` x)`` to `(mul x)`.
# Environment
* GHC version used: 8.6.4
* Operating System: macOS 10.14.4
* System Architecture: x648.8.1Iavor S. DiatchkiIavor S. Diatchkihttps://gitlab.haskell.org/ghc/ghc/-/issues/16617On x86_64, `castFloatToWord32` can generate bad, signed `Word32`s2019-05-24T19:53:10ZKevinBuhrOn x86_64, `castFloatToWord32` can generate bad, signed `Word32`s# Summary
On 64-bit architectures, when the primop `stgFloatToWord32#` is applied to a negative float (i.e., whose 32-bit representation has the sign bit set), it produces a sign-extended 64-bit word. As a result, `castFloatToWord32` a...# Summary
On 64-bit architectures, when the primop `stgFloatToWord32#` is applied to a negative float (i.e., whose 32-bit representation has the sign bit set), it produces a sign-extended 64-bit word. As a result, `castFloatToWord32` applied to negative floats will generate weird negative `Word32`s.
# Steps to reproduce
Under GHCi:
```
> import GHC.Float
> castFloatToWord32 (-1)
-1082130432
> castFloatToWord32 (-1) < 0
False
> toInteger (castFloatToWord32 (-1)) < 0
True
>
```
# Expected behavior
One would expect `Word32`s to stay positive, even in the face of such adversity:
```
> castFloatToWord32 (-1)
3212836864
> toInteger (castFloatToWord32 (-1)) < 0
False
>
```
# Fix
The issue is that `stg_floatToWord32zh` in `libraries/base/cbits/CastFloatWord.cmm` uses:
```
w = TO_W_(I32[ptr])
```
where `TO_W_` is `%sx64` on 64-bit architectures. I'd suggest adding macros `TO_ZW_` to `Cmm.h` for zero-extending analogues of `TO_W_` and using that in `stg_floatToWord32zh`. (No one seems to be using `%zx32` or `%zx64` anywhere in the code base, but they might want to some day.)
I'd be happy to add a new test case and submit a patch.
# Environment
* GHC version used: 8.6.4 or latest HEAD
* Operating System: Linux
* System Architecture: x86_64KevinBuhrKevinBuhrhttps://gitlab.haskell.org/ghc/ghc/-/issues/16713-fno-omit-yields doesn't work at -O02019-06-05T16:36:03Zroland-fno-omit-yields doesn't work at -O0```haskell
import Control.Concurrent
import Control.Monad
main = do
forkIO $ forever $ return ()
threadDelay 100000
putStrLn "done!"
````
In #8521 compiling with `-fno-omit-yields` was suggested, in order to make the tight loop y...```haskell
import Control.Concurrent
import Control.Monad
main = do
forkIO $ forever $ return ()
threadDelay 100000
putStrLn "done!"
````
In #8521 compiling with `-fno-omit-yields` was suggested, in order to make the tight loop yield. This appears to work at `-O1`:
```
$ ghc -O1 -threaded -fno-omit-yields Bug.hs
[1 of 1] Compiling Main ( Bug.hs, Bug.o ) [Optimisation flags changed]
Linking Bug ...
$ ./Bug +RTS -N2
done!
```
...but not at `-O0`:
```
$ ghc -O0 -threaded -fno-omit-yields Bug.hs
[1 of 1] Compiling Main ( Bug.hs, Bug.o ) [Optimisation flags changed]
Linking Bug ...
$ ./Bug +RTS -N2
^C^C
```
Also, I don't understand why `-fno-omit-yields` is at all required when running with `-N2`. If the `forever $ return ()` thread hogs one capability without yielding, wouldn't there be a second one left for the main thread to run on?
```
$ ghc --version
The Glorious Glasgow Haskell Compilation System, version 8.6.5
```https://gitlab.haskell.org/ghc/ghc/-/issues/16810Use explicit lazy binding around undefined in inlinable functions2021-10-04T14:19:35Zkazu-yamamotoUse explicit lazy binding around undefined in inlinable functions# Summary
`undefined` in inlinable functions are unintentionally evaluated if called strictly. An example:
```
{-# INLINE alloca #-}
alloca :: forall a b . Storable a => (Ptr a -> IO b) -> IO b
alloca =
allocaBytesAligned (sizeOf (u...# Summary
`undefined` in inlinable functions are unintentionally evaluated if called strictly. An example:
```
{-# INLINE alloca #-}
alloca :: forall a b . Storable a => (Ptr a -> IO b) -> IO b
alloca =
allocaBytesAligned (sizeOf (undefined :: a)) (alignment (undefined :: a))
```
# Steps to reproduce
Use `Foreign.Marshal.Alloc.alloca` with `Strict` language extension.
# Expected behavior
It should allocate a memory, not evaluating `undefined`. If `undefined`s are used in inlinable functions, lazy bindings must be used explicitly for GHC 8.0 or later.
# Environment
* GHC version used: 8.0 or later
Optional:8.9https://gitlab.haskell.org/ghc/ghc/-/issues/17151Optimizer produces Core with an infinite <<loop>> v22022-08-06T23:27:36ZAlexey KuleshevichOptimizer produces Core with an infinite <<loop>> v2## Summary
I am not quite sure what it is? Is it coincidence, my coding style or just luck. Two years later after I reported a bug #13429 about optimizer generating an infinite loop, I stumble upon exactly the same bug, while implementi...## Summary
I am not quite sure what it is? Is it coincidence, my coding style or just luck. Two years later after I reported a bug #13429 about optimizer generating an infinite loop, I stumble upon exactly the same bug, while implementing the same algorithm (convolution), but in a completely different library and using a totally different approach. There are some similarities in types, but I can't draw a concrete comparison.
Unlike previous bug #13429, which was applicable to ghc-8.0 and was supposably fixed in ghc-8.2, this one is triggered in ghc-8.2 and up, but not for the prior version.
It is way too easy not not trigger the bug, in fact I initially noticed my tests failing for ghc-8.4.4 only, but once I reduced it to a smaller example, my tests started failing for ghc-8.6.5 as well as ghc-8.8.1
I apologize for the size of the uploaded module, but it took me a while to reduce it even to that level.
## Steps to reproduce
Uploaded are the two files needed to reproduce the bug:
* [Main.hs](/uploads/336cf55e11fb30f34178d2d0cd1d4ffe/Main.hs)
* [Array.hs](/uploads/0680b1bdd353b7632f6d3d96e6d95f8b/Array.hs)
Those modules only depend on `primitive` package, but this is only for convenience, since this bug could equally well be reproduced using either `ForeignPtr` or by dropping down to `ByteArray#` or `MutableByteArray#` prims.
Compiling with optimizations is necessary to trigger the bug:
```shell
$ ghc Main.hs Array.hs -O1 -fforce-recomp && ./Main
[1 of 2] Compiling Array ( Array.hs, Array.o )
[2 of 2] Compiling Main ( Main.hs, Main.o )
Linking Main ...
Main: <<loop>>
```
When inspecting Core we can see where the loop occurs right away:
```
Rec {
-- RHS size: {terms: 1, types: 0, coercions: 0, joins: 0/0}
$s$fConstructPixe1 :: Index Int
$s$fConstructPixe1 = $s$fConstructPixe1
end Rec }
```
I found something peculiar, which could be useful for debugging this issue, is that the `Construct` instance for `P` representation is not used anywhere directly in the source code.
## Expected behavior
No infinite loop in the produced binary.
## Environment
* GHC version used: 8.2.2 - 8.8.1
Optional:
* Operating System: Ubuntu 18.04 LTS
* System Architecture: x86_648.10.2https://gitlab.haskell.org/ghc/ghc/-/issues/17206Unsound optimization with -O in ghc 8.4 and 8.6 when using unsafeCoerce (prod...2019-09-19T13:06:42ZAndreas AbelUnsound optimization with -O in ghc 8.4 and 8.6 when using unsafeCoerce (produced by Agda)## Summary
Unsound optimization of `unsafeCoerce` with `-O` under GHC 8.4 and 8.6.
The following code was shrunk from code generated by the GHC backend of Agda. Agda in essence targets the untyped lambda calculus, thus, uses `unsafeCo...## Summary
Unsound optimization of `unsafeCoerce` with `-O` under GHC 8.4 and 8.6.
The following code was shrunk from code generated by the GHC backend of Agda. Agda in essence targets the untyped lambda calculus, thus, uses `unsafeCoerce` excessively. This was unproblematic until GHC 8.2 and seems to be fine again from GHC 8.8.
## Steps to reproduce
```haskell
{-# LANGUAGE NoImplicitPrelude #-}
module Main where
import Prelude (IO, ($), (.), (>>=), putStrLn)
import System.Exit (exitFailure)
import Unsafe.Coerce (unsafeCoerce)
sequ :: IO () -> IO a -> IO a
sequ c c' = c >>= \ _ -> c'
main :: IO ()
main =
unsafeCoerce sequ (putStrLn "Hello,") $
unsafeCoerce sequ (putStrLn "world!") $
exitFailure
```
With 8.4.x or 8.6.x run
```
ghc -O Main.hs
./Main
```
The output is
```
Hello,
```
and exitcode is 0.
## Expected behavior
Output [UPDATE: this output is produced when compiling with 8.8, 8.2, 8.0]
```
Hello,
world!
```
and exitcode 1.
## Environment
* GHC version used: 8.4.4 and 8.6.4
Optional:
* Operating System: Mac Mojavehttps://gitlab.haskell.org/ghc/ghc/-/issues/17285Program hangs on ppc64el2019-11-03T11:10:47ZIlias TsitsimpisProgram hangs on ppc64el## Summary
The testsuite for terminal-progress-bar fails (hangs) on both ppc64el and ppc64 (see build logs [here](https://buildd.debian.org/status/package.php?p=haskell-terminal-progress-bar&suite=sid)).
## Steps to reproduce
In order...## Summary
The testsuite for terminal-progress-bar fails (hangs) on both ppc64el and ppc64 (see build logs [here](https://buildd.debian.org/status/package.php?p=haskell-terminal-progress-bar&suite=sid)).
## Steps to reproduce
In order to reproduce this, I tried the following on ppc64el:
```bash
$ cabal install terminal-progress-bar==0.4.1
$ cat Progress.hs
module Main where
import Data.Time.Clock
import System.ProgressBar
main = do
print $ renderProgressBar defStyle (Progress 0 1 ()) someTiming
where
someTime :: UTCTime
someTime = UTCTime (toEnum 0) 0
someTiming :: Timing
someTiming = Timing someTime someTime
$ ghc -o progress Progress.hs
$ ./progress
```
This hangs forever, with the process taking 100% CPU.
The interesting part is that if I modify the [ProgressBar.hs](https://github.com/roelvandijk/terminal-progress-bar/blob/master/lib/src/System/ProgressBar.hs) file to contain the above main function, and compile that one, it finishes successfully. This is why I assume this is a GHC bug.
## Environment
* GHC version used: 8.6.5
I tried the same think with v8.4.4 from Debian buster and it run without a problem, so this is a regression.https://gitlab.haskell.org/ghc/ghc/-/issues/17303Rounding always throws an arithmetic underflow exception when used with a rat...2022-02-03T01:23:43ZtaylorfausakRounding always throws an arithmetic underflow exception when used with a ratio of natural numbersI originally reported this in !1878.
Today I was surprised to find that `round` does not work at all for `Ratio Natural` values. For example:
``` hs
>>> round (1 :: Ratio Natural) :: Natural
*** Exception: arithmetic underflow
```
As...I originally reported this in !1878.
Today I was surprised to find that `round` does not work at all for `Ratio Natural` values. For example:
``` hs
>>> round (1 :: Ratio Natural) :: Natural
*** Exception: arithmetic underflow
```
As far as I can tell it's true regardless of the value of the `Ratio Natural` or the result type.
``` hs
>>> round (1.5 :: Ratio Natural) :: Natural
*** Exception: arithmetic underflow
>>> round (1 :: Ratio Natural) :: Integer
*** Exception: arithmetic underflow
```
For comparison, rounding works fine for `Rational`, which is an alias for `Ratio Integer`.
``` hs
>>> round (1 :: Rational) :: Integer
1
>>> round (1.5 :: Rational) :: Integer
2
>>> round (1 :: Rational) :: Natural
1
```8.10.1https://gitlab.haskell.org/ghc/ghc/-/issues/17383Data.Fixed.mod' sometimes produces nonsensical results2019-10-31T23:03:13ZRoman CheplyakaData.Fixed.mod' sometimes produces nonsensical results## Summary
```
Prelude Data.Fixed> (-3e19) `mod'` 1.4
-4096.0
Prelude Data.Fixed> 4.9098418106168856e20 `mod'` (-43.4678352235136)
65536.0
Prelude Data.Fixed> (-10) `mod'` exp (-43)
-1.7763568394002505e-15
```
## Expected behavior
My ...## Summary
```
Prelude Data.Fixed> (-3e19) `mod'` 1.4
-4096.0
Prelude Data.Fixed> 4.9098418106168856e20 `mod'` (-43.4678352235136)
65536.0
Prelude Data.Fixed> (-10) `mod'` exp (-43)
-1.7763568394002505e-15
```
## Expected behavior
My understanding is that `mod'` should yield a result whose absolute value is smaller than the absolute value of the divisor and which is positive when the divisor is positive.
The fact that some of the above results happen to be powers of 2 is also curious.
## Environment
* GHC version used:
8.6.58.10.1https://gitlab.haskell.org/ghc/ghc/-/issues/17451surprising SIGQUIT behavior "This build does not support backtraces."2019-11-08T21:51:17Zjoeyhsurprising SIGQUIT behavior "This build does not support backtraces."## Summary
I hit ctrl-\ to send a hard SIGQUIT to my program, which I knew does not install a handler for that and wanted to exit immediately (w/o running its usual SIGINT handler), and was surprised to see "This build does not support ...## Summary
I hit ctrl-\ to send a hard SIGQUIT to my program, which I knew does not install a handler for that and wanted to exit immediately (w/o running its usual SIGINT handler), and was surprised to see "This build does not support backtraces." and the program contining to run.
I happened to have run my program from a shell script, and the SIGQUIT terminated the shell that had run it, which left my program running in a kind of backgrounded state where it contended with my interactive shell. And my program happened to have run another program and was itself surprised to see that program, which also received the SIGQUIT, exiting unexpectedly with an unusual exit code.
I think there's a reasonable expectation that SIGQUIT leads to a prompt terminatation of the program, with or without a core dump or something associated with a core dump such as a backtrace. Leaving the program running and printing out an unusual (and untranslated BTW) message to stderr has a high potential to exercise unusual code paths. Some programs may have a good reason to not exit on SIGQUIT, but then the program has to be designed to work that way. ghc is assuming any program will work acceptably if it keeps running after a SIGQUIT, and that is not the case.
In Signals.c, I'd suggest only installing the SIGQUIT handler #if USE_LIBDW.
Or, if it's important to communicate the the user that it was not built with backtrace support, it could display the message and then exit.
(It looks like the program might keep running when built with LIBDW too, and maybe that's intentional in order to see repeated backtraces, but I think my reasoning on prompt termination could also apply there.)
## Steps to reproduce
Start a long-running git-annex operation, like a "git annex add" in a directory with ots of files, and send it a SIGQUIT.
## Expected behavior
Terminate immediately.
## Environment
* GHC version used: 8.6.5 from Debian
Optional:
* Operating System: Linux
* System Architecture: 864-64https://gitlab.haskell.org/ghc/ghc/-/issues/17458Runtime loop when using eqT2019-11-13T21:59:02ZMax HarmsRuntime loop when using eqT## Summary
Use of eqT causes run-time divergence in a weird edge-case.
## Steps to reproduce
This example is minimized for simplicity; my actual use case was large and it took me 5 hours to get it down to this:
```haskell
{-# LANGUAGE...## Summary
Use of eqT causes run-time divergence in a weird edge-case.
## Steps to reproduce
This example is minimized for simplicity; my actual use case was large and it took me 5 hours to get it down to this:
```haskell
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE QuantifiedConstraints #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE TypeOperators #-}
import Data.Void
import Data.Typeable
import Data.Type.Equality
class (forall k. k a => k b) => Equ a b
instance Equ a a
data Z' a where
Z' :: Z' Void
data Z where
Z :: forall a. Equ Void a => Z' a -> Z
checkZ :: Z -> Bool
checkZ (Z (Z' :: Z' a)) = case eqT of
Nothing -> False
Just (Refl :: a :~: Void) -> True
main :: IO ()
main = do
putStrLn "before..."
print $ checkZ $ Z Z'
putStrLn "after!"
```
Compiles ok. Exe output is:
```
before...
MinExample: <<loop>>
```
## Expected behavior
This should work and produce
```
before...
True
after...
```
Poking around indicates that Eq can propagate along the quantified constraint of `Equ`, but apparently something magic is happening with Typeable?
## Environment
Tested with GHC 8.6 and 8.8 on NixOS.https://gitlab.haskell.org/ghc/ghc/-/issues/17678text has different runtime behavior between GHC 8.6.5 and 8.8.12020-01-13T18:40:51ZRyan Scotttext has different runtime behavior between GHC 8.6.5 and 8.8.1If you compile the following file:
```hs
module Main (main) where
import qualified Data.Char as C
import Data.Char (isLetter, isLower)
import Data.Maybe (mapMaybe)
import qualified Data.Text as T
import Da...If you compile the following file:
```hs
module Main (main) where
import qualified Data.Char as C
import Data.Char (isLetter, isLower)
import Data.Maybe (mapMaybe)
import qualified Data.Text as T
import Data.Text (Text)
main :: IO ()
main = print $ t_toTitle_1stNotLower
$ T.pack "\4309" -- ვ
-- Taken from the text test suite
-- https://github.com/haskell/text/blob/44ec2cee65e5326ed943370e424f60d4ae6206d1/tests/Tests/Properties.hs#L388-L396
t_toTitle_1stNotLower :: Text -> Bool
t_toTitle_1stNotLower = and . notLow . T.toTitle . T.filter stable
where notLow = mapMaybe (fmap (not . isLower) . (T.find isLetter)) . T.words
-- Surprise! The Spanish/Portuguese ordinal indicators changed
-- from category Ll (letter, lowercase) to Lo (letter, other)
-- in Unicode 7.0
-- Oh, and there exist lowercase-only letters (see previous test)
stable c = if isLower c
then C.toUpper c /= c
else c /= '\170' && c /= '\186'
```
Then you'll get different runtime results depending on which version of GHC you use. Here is the answer with GHC 8.6.5:
```
$ /opt/ghc/8.6.5/bin/ghc Bug.hs -fforce-recomp -v0 && ./Bug
True
```
And here is the answer with GHC 8.8.1, 8.10.1-alpha2, and HEAD:
```
$ /opt/ghc/8.8.1/bin/ghc Bug.hs -fforce-recomp -v0 && ./Bug
False
```
This discrepancy manifests itself regardless of what GHC optimization level is used.https://gitlab.haskell.org/ghc/ghc/-/issues/17694ParallelListComp semantics differs from the documented one2021-12-21T23:01:00ZRoman CheplyakaParallelListComp semantics differs from the documented oneThe desugaring of parallel list comprehensions described [in the manual](https://downloads.haskell.org/~ghc/latest/docs/html/users_guide/glasgow_exts.html#parallel-list-comprehensions) appears to state that parallel bars (`|`) have highe...The desugaring of parallel list comprehensions described [in the manual](https://downloads.haskell.org/~ghc/latest/docs/html/users_guide/glasgow_exts.html#parallel-list-comprehensions) appears to state that parallel bars (`|`) have higher precedence than what comes after them, but this is not how they work in practice.
## Example 1
``` haskell
{-# LANGUAGE ParallelListComp #-}
main = print
[ (a, b)
| a <- [1 .. 5]
| b <- [1 .. 5]
, b >= 4
]
```
The desugaring implied by the docs is
``` haskell
main = print
[ (a, b)
| (a, b) <- zip [1 .. 5] [1 .. 5]
, b >= 4
]
```
so I'd expect the result to be [(4,4),(5,5)]. Yet the actual result is [(1,4),(2,5)], showing that the comma has higher precedence here.
## Example 2
``` haskell
{-# LANGUAGE ParallelListComp #-}
main = print
[ (a, b)
| a <- [1 .. 5]
| b <- [1 .. 5]
, a >= 4
]
```
Result:
```
parlistcomp.hs:7:5: error:
• Variable not in scope: a :: Integer
• Perhaps you meant ‘a’ (line 5)
|
7 | , a >= 4
| ^
```
Again, this is consistent with the comma binding more tightly than the bar. But also notice that ghc itself is confused about the scoping rules: it says `a` is not in scope, yet suggests `a` as a valid replacement.
## Environment
* GHC version used: 8.6.5, 8.8.1https://gitlab.haskell.org/ghc/ghc/-/issues/17950OFD locking breaks on 32-bit glibc2021-05-04T23:17:40ZBen GamariOFD locking breaks on 32-bit glibcAs noted in #17941, some [glibc versions](https://sourceware.org/bugzilla/show_bug.cgi?id=20251) use the wrong `struct` layout for the open fd locking `fcntl` on 32-bit platforms. This results in GHC being broken on many 32-bit platforms...As noted in #17941, some [glibc versions](https://sourceware.org/bugzilla/show_bug.cgi?id=20251) use the wrong `struct` layout for the open fd locking `fcntl` on 32-bit platforms. This results in GHC being broken on many 32-bit platforms by default.8.10.2Ben GamariBen Gamarihttps://gitlab.haskell.org/ghc/ghc/-/issues/17970Global variables in GHC.IO.Encoding have inappropriate inlinings2020-03-31T14:58:34ZBen GamariGlobal variables in GHC.IO.Encoding have inappropriate inliningsWhile looking into #17947 I noticed that `GHC.IO.Encoding.getFileSystemEncoding` and friends, which are supposed to be global variables, exposes an unfolding:
```haskell
$ _build/stage1/bin/ghc --show-iface _build/stage1/libraries/base/b...While looking into #17947 I noticed that `GHC.IO.Encoding.getFileSystemEncoding` and friends, which are supposed to be global variables, exposes an unfolding:
```haskell
$ _build/stage1/bin/ghc --show-iface _build/stage1/libraries/base/build/GHC/IO/Encoding.hi
...
c5f268cd1abea1e17607b29083a07ddf
getFileSystemEncoding ::
GHC.Types.IO GHC.IO.Encoding.Types.TextEncoding
[Unfolding: (case getFileSystemEncoding1 of wild { (,) getFileSystemEncoding81 setFileSystemEncoding1 ->
getFileSystemEncoding81 })]
877b4ce4c0c06df59a38c01a0a2f65ea
getFileSystemEncoding1 ::
(GHC.Types.IO GHC.IO.Encoding.Types.TextEncoding,
GHC.IO.Encoding.Types.TextEncoding -> GHC.Types.IO ())
[Unfolding: (case GHC.Magic.runRW#
@('GHC.Types.TupleRep
'[ 'GHC.Types.TupleRep '[], 'GHC.Types.LiftedRep])
@(# GHC.Prim.State# GHC.Prim.RealWorld,
(GHC.Types.IO GHC.IO.Encoding.Types.TextEncoding,
GHC.IO.Encoding.Types.TextEncoding -> GHC.Types.IO ()) #)
getFileSystemEncoding2 of ds { (#,#) ipv ipv1 ->
ipv1 })]
...
01c6dd64e835d1d407d95b7dea54fa17
getFileSystemEncoding2 ::
GHC.Prim.State# GHC.Prim.RealWorld
-> (# GHC.Prim.State# GHC.Prim.RealWorld,
(GHC.Types.IO GHC.IO.Encoding.Types.TextEncoding,
GHC.IO.Encoding.Types.TextEncoding -> GHC.Types.IO ()) #)
[Arity: 1, Strictness: <L,U>,
Unfolding: (\ (s :: GHC.Prim.State# GHC.Prim.RealWorld)[OneShot] ->
case GHC.Prim.noDuplicate# @GHC.Prim.RealWorld s of s' { DEFAULT ->
case GHC.Prim.newMutVar#
@GHC.IO.Encoding.Types.TextEncoding
@GHC.Prim.RealWorld
getFileSystemEncoding3
s' of ds { (#,#) ipv ipv1 ->
(# ipv,
((\ (eta :: GHC.Prim.State# GHC.Prim.RealWorld) ->
GHC.Prim.readMutVar#
@GHC.Prim.RealWorld
@GHC.IO.Encoding.Types.TextEncoding
ipv1
eta)
`cast`
(Sym (GHC.Types.N:IO[0] <GHC.IO.Encoding.Types.TextEncoding>_R)),
(\ (v :: GHC.IO.Encoding.Types.TextEncoding)
(eta :: GHC.Prim.State# GHC.Prim.RealWorld) ->
case GHC.Prim.writeMutVar#
@GHC.Prim.RealWorld
@GHC.IO.Encoding.Types.TextEncoding
ipv1
v
eta of s2# { DEFAULT ->
(# s2#, GHC.Tuple.() #) })
`cast`
(<GHC.IO.Encoding.Types.TextEncoding>_R
->_R Sym (GHC.Types.N:IO[0] <()>_R))) #) } })]
```
This will break the "globalness" of these variables, potentially breaking `setFileSystemEncoding` and others.8.10.2Ben GamariBen Gamarihttps://gitlab.haskell.org/ghc/ghc/-/issues/18101DeriveGeneric gets a wrong infix constructor associativity when type is decla...2023-04-09T15:41:35ZXia Li-yaoDeriveGeneric gets a wrong infix constructor associativity when type is declared in a different module## Summary
For example, the operators `(:|)` (`NonEmpty`) and `(:)` (lists, `[]`) are `infixr 5`, but their `Generic.Rep` say otherwise (`'InfixI 'LeftAssociative 9`) (see code block below for an illustration).
My most plausible hypoth...## Summary
For example, the operators `(:|)` (`NonEmpty`) and `(:)` (lists, `[]`) are `infixr 5`, but their `Generic.Rep` say otherwise (`'InfixI 'LeftAssociative 9`) (see code block below for an illustration).
My most plausible hypothesis for the cause is that `DeriveGeneric` does not take precedence into account when the type lives in a different module from its `Generic` instance. Indeed, `NonEmpty` and `[]` have their `Generic` instances derived in `GHC.Generic`, whereas things looks fine if we declare a type with an infix constructor and derive `Generic` in the same module.
```
ghci> :kind! (Rep [Int])
(Rep [Int]) :: * -> *
= D1
('MetaData "[]" "GHC.Types" "ghc-prim" 'False)
(C1 ('MetaCons "[]" 'PrefixI 'False) U1
:+: C1
('MetaCons ":" ('InfixI 'LeftAssociative 9) 'False)
...)
ghci> :kind! (Rep (NonEmpty Int))
(Rep (NonEmpty Int)) :: * -> *
= D1
('MetaData "NonEmpty" "GHC.Base" "base" 'False)
(C1
('MetaCons ":|" ('InfixI 'LeftAssociative 9) 'False)
...)
```
## Expected behavior
These two examples should read `'InfixI 'RightAssociative 5`.
## Environment
* GHC version used: 8.6, 8.89.4.1https://gitlab.haskell.org/ghc/ghc/-/issues/18151Eta-expansion of a left-section2021-01-12T23:04:49ZRichard Eisenbergrae@richarde.devEta-expansion of a left-sectionIf I say
```hs
x = seq (True `undefined`) ()
```
what should I get when evaluating `x`?
According to my understanding of the Haskell Report, I should get `()`. And according to my understanding of GHC's source code (in `GHC.Tc.Gen.Exp...If I say
```hs
x = seq (True `undefined`) ()
```
what should I get when evaluating `x`?
According to my understanding of the Haskell Report, I should get `()`. And according to my understanding of GHC's source code (in `GHC.Tc.Gen.Expr`), I should get `()`. But I get an exception.
Why?
NB: `-XPostfixOperators` is off. If it were on, the exception would be expected.
Spun off from https://github.com/ghc-proposals/ghc-proposals/pull/275#issuecomment-6242820229.0.1Vladislav ZavialovVladislav Zavialovhttps://gitlab.haskell.org/ghc/ghc/-/issues/18269Closure size functions will return incorrect for closures with static links2020-06-02T14:12:21ZÖmer Sinan AğacanClosure size functions will return incorrect for closures with static linksNot sure if this is a bug or not, but here goes.
Closure size functions like `closureSize#` (primop) and `closure_size` (C function) don't take static link fields into account, so they will return incorrect result for top-level construc...Not sure if this is a bug or not, but here goes.
Closure size functions like `closureSize#` (primop) and `closure_size` (C function) don't take static link fields into account, so they will return incorrect result for top-level constructors (e.g. SRTs, or CAFFY constructors).
It seems like the assumption here is they'll always be passed heap-allocated closures, but as far as I can see this fact is not documented, e.g. in `ghc-heap`'s `closureSize`:
```haskell
-- | Get the size of the top-level closure in words.
-- Includes header and payload. Does not follow pointers.
--
-- @since 8.10.1
closureSize :: Box -> Int
closureSize (Box x) = I# (closureSize# x)
```
Note that, confusingly, "top-level" here means that the function does not recursively visit payloads, not that the closure is actually top-level!https://gitlab.haskell.org/ghc/ghc/-/issues/18370`BlockedIndefinitelyOnMVar` is thrown to non-blocked threads2022-09-12T00:31:00ZOle`BlockedIndefinitelyOnMVar` is thrown to non-blocked threads## Summary
`BlockedIndefinitelyOnMVar` is thrown to other threads that weren't blocked.
## Steps to reproduce
```haskell
-- Test.hs
{-# LANGUAGE TypeApplications #-}
module Main (main) where
import Control.Concurrent
import Control...## Summary
`BlockedIndefinitelyOnMVar` is thrown to other threads that weren't blocked.
## Steps to reproduce
```haskell
-- Test.hs
{-# LANGUAGE TypeApplications #-}
module Main (main) where
import Control.Concurrent
import Control.Exception
main :: IO ()
main = do
emptyVar <- newEmptyMVar @()
resultVar <- newEmptyMVar
_ <- forkIO $ do
caught <- try @SomeException (readMVar emptyVar)
putMVar resultVar caught
print ("thread", caught)
result <- readMVar resultVar
print ("main", result)
```
```
$ ghc -Wall -Wextra -threaded Test.hs
[1 of 1] Compiling Main ( Test.hs, Test.o )
Linking Test ...
$ ./Test
("thread",Left thread blocked indefinitely in an MVar operation)
Test: thread blocked indefinitely in an MVar operation
$ ./Test +RTS -N
Test: thread blocked indefinitely in an MVar operation
("thread",Left thread blocked indefinitely in an MVar operation)
```
It appears the main thread is being thrown a `BlockedIndefinitelyOnMVar` as well.
This can be decoupled from the empty MVar read:
```haskell
-- Test.hs
{-# LANGUAGE TypeApplications #-}
module Main (main) where
import Control.Concurrent
import Control.Concurrent.STM
import Control.Exception
main :: IO ()
main = do
emptyVar <- newEmptyTMVarIO @()
resultVar <- newEmptyMVar
_ <- forkIO $ do
caught <- try @SomeException (atomically (readTMVar emptyVar))
putMVar resultVar caught
print ("thread", caught)
result <- readMVar resultVar
print ("main", result)
```
```
$ ghc -Wall -Wextra -threaded Test.hs
[1 of 1] Compiling Main ( Test.hs, Test.o )
Linking Test ...
$ ./Test
("thread",Left thread blocked indefinitely in an STM transaction)
Test: thread blocked indefinitely in an MVar operation
$ ./Test +RTS -N
Test: thread blocked indefinitely in an MVar operation
("thread",Left thread blocked indefinitely in an STM transaction)
```
## Expected behavior
I expect both threads to print the result of `try` in unspecified order.
```
λ ./Test +RTS -N
("thread",Left thread blocked indefinitely in an MVar operation)
("main",Left thread blocked indefinitely in an MVar operation)
```
## Environment
* GHC version used:
- 8.10.1
- 8.8.3
Optional:
* Operating System: NixOS, Linux 5.4.31 x86_64https://gitlab.haskell.org/ghc/ghc/-/issues/18418withArgs and withProgName permanently modify argv[0]2020-07-14T14:20:26ZAndreas HerrmannwithArgs and withProgName permanently modify argv[0]## Summary
The functions `withArgs` and `withProgName` are meant to temporarily modify the program arguments, either `argv[1]` and upwards or `argv[0]`. However, they both have the side-effect to permanently modify `argv[0]`.
## Steps ...## Summary
The functions `withArgs` and `withProgName` are meant to temporarily modify the program arguments, either `argv[1]` and upwards or `argv[0]`. However, they both have the side-effect to permanently modify `argv[0]`.
## Steps to reproduce
Consider the following example program (full project attached [ghc_arg0.tgz](/uploads/d2515b74bfbbd1567dd334d1fc7db639/ghc_arg0.tgz)
):
```
module Main where
import Arg0 (getArg0)
import System.Environment (withArgs, withProgName)
main :: IO ()
main = do
before <- getArg0
during <- withProgName "manual" getArg0
-- during <- withArgs [] getArg0
after <- getArg0
putStrLn $ "before " ++ before ++ "\nduring " ++ during ++ "\nafter " ++ after
```
Observe the following behavior
```
$ cabal run
before /home/user/ghc_arg0/dist-newstyle/build/x86_64-linux/ghc-8.10.1/ghc-arg0-0.1.0.0/x/ghc-arg0/build/ghc-arg0/ghc-arg0
during manual
after ghc-arg0
```
I.e. the result of `getArg0` is different before and after `withProgName` (same with `withArgs`).
## Expected behavior
`withProgName` and `withArgs` should fully restore `argv[0]`. I.e. the output above should be
```
before /home/user/ghc_arg0/dist-newstyle/build/x86_64-linux/ghc-8.10.1/ghc-arg0-0.1.0.0/x/ghc-arg0/build/ghc-arg0/ghc-arg0
during manual
after /home/user/ghc_arg0/dist-newstyle/build/x86_64-linux/ghc-8.10.1/ghc-arg0-0.1.0.0/x/ghc-arg0/build/ghc-arg0/ghc-arg0
```
## Environment
* GHC version used: 8.10.1
Optional:
* Operating System: Ubuntu 19.10
* System Architecture: x86_64
## Additional context
As pointed out in https://gitlab.haskell.org/ghc/ghc/-/issues/3199 there is no easy access to `argv[0]` in GHC. The attached example uses a slight variation of `getProgName` that doesn't invoke `basename` on the result. Alternatively, there is https://hackage.haskell.org/package/system-argv0-0.1.1.
The motivating use-case is to determine the path by which the program was invoked, see https://github.com/tweag/rules_haskell/pull/1387 for details. Note, this is not necessarily the same as the result of `getExecutablePath` as that one uses `/proc/self/exe` and resolves symbolic links. The issue was caused by a program calling `getProgName` around an optparse-applicative parser to control the program name in error messages generated by optparse-applicative.https://gitlab.haskell.org/ghc/ghc/-/issues/18431Unboxed types in GHCi on big-endian platforms2023-10-25T09:03:58ZStefan Schulze FrielinghausUnboxed types in GHCi on big-endian platforms## Summary
Consider a file `test.hs` with content as follows:
```haskell
{-# LANGUAGE MagicHash #-}
module Main where
import GHC.Exts
data Foo = Foo Float# deriving Show
main = print $ Foo 1.0#
```
If compiled on s390x via LLVM backen...## Summary
Consider a file `test.hs` with content as follows:
```haskell
{-# LANGUAGE MagicHash #-}
module Main where
import GHC.Exts
data Foo = Foo Float# deriving Show
main = print $ Foo 1.0#
```
If compiled on s390x via LLVM backend and executed the expected output `Foo 1.0#` is printed to stdout. However, if interpreted via GHCi, the output is wrong:
```
> :load test.hs
> main
Foo 0.0#
```
This might be a big-endian bug. I tried to follow the execution of GHCi via GDB but got lost in to many continuations. I also had a look into parts of GHCi without luck. Any hint which parts of GHCi are responsible for interpreting unboxed types?
This is also the reason why test `T13825-debugger` fails on s390x.
Note, a similar bug regarding GHCi using `:print` is fixed by !3649.Stefan Schulze FrielinghausStefan Schulze Frielinghaushttps://gitlab.haskell.org/ghc/ghc/-/issues/18444GHC does not respect semantics of bang patterns2023-01-15T10:52:48ZRichard Eisenbergrae@richarde.devGHC does not respect semantics of bang patternsIf I write
```hs
a :: forall a. a -> a
a = let y :: Eq a => a
!y = undefined
in \z -> z
```
and evaluate `a True`, I get `True`. This is surprising -- I expected to see an exception thrown. The problem is that GHC does not ...If I write
```hs
a :: forall a. a -> a
a = let y :: Eq a => a
!y = undefined
in \z -> z
```
and evaluate `a True`, I get `True`. This is surprising -- I expected to see an exception thrown. The problem is that GHC does not instantiate `y` before forcing it. `y` is a function from `Eq a` to `a`, and thus is a value.
Yet https://gitlab.haskell.org/haskell/prime/-/wikis/BangPatterns describes the desugaring of the above to be
```hs
a :: forall a. a -> a
a = let y :: Eq a => a
y = undefined
in y `seq` \z -> z
```
which does not compile, as there is no `Eq a` instance. I think we should stick to the specification here and reject both programs. This means that GHC will struggle to support a strict binding of a polymorphic value, but I think that's appropriate, as I would want users to be careful in this corner and say exactly what they mean, lest they get surprised by GHC's behavior.https://gitlab.haskell.org/ghc/ghc/-/issues/18445targetByteOrder on s390x2021-09-09T03:50:06ZAndrew MartintargetByteOrder on s390x## Summary
I suspect that GHC detects the wrong byte order for s390x. This was originally reported [against the byte-order library](https://github.com/andrewthad/byte-order/issues/6), but it actually appears to be a problem with GHC its...## Summary
I suspect that GHC detects the wrong byte order for s390x. This was originally reported [against the byte-order library](https://github.com/andrewthad/byte-order/issues/6), but it actually appears to be a problem with GHC itself that manifests itself as a failure in `byte-order`'s test suite.
## Steps to reproduce
On an s390x host, run this in GHCi:
$ ghci
GHCi, version 8.8.3: https://www.haskell.org/ghc/ :? for help
Prelude> import qualified GHC.ByteOrder
Prelude GHC.ByteOrder> GHC.ByteOrder.targetByteOrder
LittleEndian
## Expected behavior
This is a big-endian architecture. The result should be `BigEndian`.
## Environment
* GHC version used: Not yet certain. I do not have access to the machine that fails.8.10.6https://gitlab.haskell.org/ghc/ghc/-/issues/18527Optimisation removes effectful computation.2020-08-16T18:35:16ZTobias DeckingOptimisation removes effectful computation.## Summary
The attached zip contains a small cabal package with a `Win32` dependency.
The problematic source file in question is `Offending.hs`, where the optimisation level was overridden.
## Steps to reproduce
When setting the optim...## Summary
The attached zip contains a small cabal package with a `Win32` dependency.
The problematic source file in question is `Offending.hs`, where the optimisation level was overridden.
## Steps to reproduce
When setting the optimisation level in `Offending.hs` to `-O1`, and doing a full rebuild
(running `cabal clean` if neccessary), the resulting program prints the following:
```
Sending mask: 0
```
Somehow, the second call to `sendMessage` in `Offending.hs` gets dropped.
## Expected behavior
When setting the optimisation level in `Offending.hs` to `-O0`, the program prints the expected result:
```
Sending mask: 0
Recieved new mask: 2
```
## Environment
* GHC version used: 8.10.1
[bug.zip](/uploads/8405f316aff914dd251394b6aeb216d1/bug.zip)https://gitlab.haskell.org/ghc/ghc/-/issues/18590GHC.HsToCore.Coverage doesn't take expressions in View Patterns into account2020-09-30T21:48:51ZZubinGHC.HsToCore.Coverage doesn't take expressions in View Patterns into account```haskell
{-# LANGUAGE ViewPatterns #-}
main = do
x <- readLn
let str (if x == 0 then id else const 2 -> y) = show y
putStrLn (str 1)
{-
$ hpc report Main
100% expressions used (7/7)
100% boolean coverage (0/0)
10...```haskell
{-# LANGUAGE ViewPatterns #-}
main = do
x <- readLn
let str (if x == 0 then id else const 2 -> y) = show y
putStrLn (str 1)
{-
$ hpc report Main
100% expressions used (7/7)
100% boolean coverage (0/0)
100% guards (0/0)
100% 'if' conditions (0/0)
100% qualifiers (0/0)
100% alternatives used (0/0)
100% local declarations used (1/1)
100% top-level declarations used (1/1)
-}
{-
Changing str to
let str z = let y = (if x == 0 then id else const 2) z in show y
results in
$ hpc report Main
86% expressions used (13/15)
0% boolean coverage (0/1)
100% guards (0/0)
0% 'if' conditions (0/1), 1 always True
100% qualifiers (0/0)
50% alternatives used (1/2)
100% local declarations used (2/2)
100% top-level declarations used (1/1)
-}
```
Specifically, the problem is in `addTickMatch` and `addTickCmdMatch`. They are defined like so:
```haskell
addTickMatch isOneOfMany isLambda match@(Match { m_pats = pats
, m_grhss = gRHSs }) =
bindLocals (collectPatsBinders pats) $ do
gRHSs' <- addTickGRHSs isOneOfMany isLambda gRHSs
return $ match { m_grhss = gRHSs' }
```
They return the `pats` as they occurred in the original expression and don't add ticks in the expressions inside them.https://gitlab.haskell.org/ghc/ghc/-/issues/18604Bignum: natural subtraction sometimes wrong2020-10-12T14:04:49ZSylvain HenryBignum: natural subtraction sometimes wrongConsider
```haskell
module Main (main) where
import Numeric.Natural
main :: IO ()
main = print (n - s)
where
n, s :: Natural
n = 137503105969312982142385040956303729937425409769904987267247644890331944583201
s = 37081411...Consider
```haskell
module Main (main) where
import Numeric.Natural
main :: IO ()
main = print (n - s)
where
n, s :: Natural
n = 137503105969312982142385040956303729937425409769904987267247644890331944583201
s = 370814112419299627365008243601943822482
```
Compiled with HEAD it prints 0.https://gitlab.haskell.org/ghc/ghc/-/issues/18619Data.Bits.shiftL should generate overflow exception for Integer operand2021-01-24T21:07:13ZSergei TrofimovichData.Bits.shiftL should generate overflow exception for Integer operand## Summary
`Data.Bits.shiftL` doc says `shiftL` should never be called with negative value. `Int` instance returns an overflow exception, but `Integer` returns something reasonable. It's confusing to see behaviour change by slightly cha...## Summary
`Data.Bits.shiftL` doc says `shiftL` should never be called with negative value. `Int` instance returns an overflow exception, but `Integer` returns something reasonable. It's confusing to see behaviour change by slightly changing the type of a program:
```
GHCi, version 8.8.4: https://www.haskell.org/ghc/ :? for help
Prelude> Data.Bits.shiftL (1 :: Integer) ((-1) :: Int)
0
Prelude> Data.Bits.shiftL (1 :: Int) ((-1) :: Int)
*** Exception: arithmetic overflow
```
Should `Integer` instance also throw an exception?https://gitlab.haskell.org/ghc/ghc/-/issues/18627Global ImplicitParams technique doesn't work with optimizations enabled2020-10-13T21:42:52ZDmitrii KovanikovGlobal ImplicitParams technique doesn't work with optimizations enabled## Summary
When using the Global Implicit Parameters technique described in [this blog post](https://kcsongor.github.io/global-implicit-parameters/) with optimizations, I observe that it doesn't work. Specifically, the global parameter ...## Summary
When using the Global Implicit Parameters technique described in [this blog post](https://kcsongor.github.io/global-implicit-parameters/) with optimizations, I observe that it doesn't work. Specifically, the global parameter is applied always, even when I override it locally. The following test:
```haskell
describe "Colour disabling works" $ do
it "Disable yellow" $
let ?colourMode = DisableColour
in yellow @Text `shouldBe` ""
```
doesn't pass with the following error:
```haskell
test/Test/Colourista.hs:44:16:
1) Colourista tests, Colour disabling works, Disable yellow
expected: ""
but got: "\ESC[93m"
```
Specifically, I'm trying to use `ImplicitParams` to implement colour disabling and enabling in the [colourista](http://hackage.haskell.org/package/colourista) library. See the following PRs for implementation:
* Implementation: https://github.com/kowainik/colourista/pull/38
* Tests: https://github.com/kowainik/colourista/pull/43
In short, the implementation looks like this:
```haskell
data ColourMode
= DisableColour
| EnableColour
deriving stock (Show, Eq, Enum, Bounded)
instance IP "colourMode" ColourMode where
ip = EnableColour
type HasColourMode = (?colourMode :: ColourMode)
withColourMode :: (HasColourMode, IsString str) => str -> str
withColourMode str = case ?colourMode of
EnableColour -> str
DisableColour -> ""
{-# INLINE withColourMode #-}
-- | Code to apply 'Yellow' colouring for the terminal output.
yellow :: (HasColourMode, IsString str) => str
yellow = withColourMode $ fromString $ setSGRCode [SetColor Foreground Vivid Yellow]
{-# SPECIALIZE yellow :: HasColourMode => String #-}
{-# SPECIALIZE yellow :: HasColourMode => Text #-}
{-# SPECIALIZE yellow :: HasColourMode => ByteString #-}
```
However, this implementation only works when I build the project with `-O0`. Morever, I see the following warnings, which emitted only when I build the project without `-O0`:
```haskell
src/Colourista/Pure.hs:92:1: warning: [-Wredundant-constraints]
• Redundant constraint: HasColourMode
• In the type signature for:
red :: HasColourMode => String
In the SPECIALISE pragma
{-# SPECIALIZE red :: HasColourMode => String #-}
|
92 | {-# SPECIALIZE red :: HasColourMode => String #-}
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
src/Colourista/Pure.hs:92:1: warning:
Forall'd constraint ‘HasColourMode’ is not bound in RULE lhs
Orig bndrs: [$dIP_a7Qk]
Orig lhs: let {
$dIsString_a7Qn :: IsString String
[LclId]
$dIsString_a7Qn = $dIsString_a7vq } in
let {
$dIP_a7Qm :: HasColourMode
[LclId]
$dIP_a7Qm = Colourista.Mode.$fIP"colourMode"ColourMode } in
red @ String $dIP_a7Qm $dIsString_a7Qn
optimised lhs: red @ String $dIP_a7Qm $dIsString_a7Qn
|
92 | {-# SPECIALIZE red :: HasColourMode => String #-}
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
```
## Steps to reproduce
1. Clone the [colourista](https://github.com/kowainik/colourista/pull/43) repository.
2. Checkout to branch `chshersh/41-Add-some-tests`
3. Run tests: `cabal test --enable-tests --test-show-details=direct`
## Expected behavior
Tests are passing.
## Environment
* GHC-8.8.3. But the error is reproducible with any GHC version.
Optional:
* Operating System: Ubuntu
* System Architecture: x86_64https://gitlab.haskell.org/ghc/ghc/-/issues/18829Strange behavior when optimization is turned on, with GHC >= 8.2.22020-11-09T15:13:23ZVanessa McHaleStrange behavior when optimization is turned on, with GHC >= 8.2.2## Summary
Test suite produces strange errors/results when run with optimizations on (for later GHCs). Also, results vary from run to run.
## Steps to reproduce
Download and install [J](https://code.jsoftware.com/wiki/System/Installat...## Summary
Test suite produces strange errors/results when run with optimizations on (for later GHCs). Also, results vary from run to run.
## Steps to reproduce
Download and install [J](https://code.jsoftware.com/wiki/System/Installation/J901/Debian).
```
git clone https://github.com/vmchale/j-hs.git
cd j-hs/
cabal test -w ghc-8.10.2
cabal test -w ghc-8.0.2
cabal test -w ghc-8.10.2 -O0
```
(revision `475755ca3d3dc5ce0557e42ef0df321457b8ebac`?)
Then this gives:
```
J dl
Performs calculation and has sensible output: OK
Reads back type in the environment: OK
Reads a string: OK
Sends an array to J: OK
Uses J to perform a complex calculation: OK
Writes strigns to J values: OK
Uses J for something Haskell would have a hard time with: j-test: internal error: index out of bounds
CallStack (from HasCallStack):
error, called at ./Test/Tasty/Ingredients/ConsoleReporter.hs:178:20 in tasty-1.3.1-268a33715c1414c235611995fa9c09de6e68f7c1c3aa3455f08d0451da953e2d:Test.Tasty.Ingredients.ConsoleReporter
Test suite j-test: FAIL
```
for GHC 8.10.2, then works fine with GHC 8.0.2 or when optimization is set to `-O0`.
Unfortunately I can't get a stack trace since compiling with `--enable-profiling` gives yet another failure mode, viz.
```
J dl
Performs calculation and has sensible output: OK
Reads back type in the environment: OK
Reads a string: OK
Sends an array to J: OK
Uses J to perform a complex calculation: OK
Writes strigns to J values: OK
Uses J for something Haskell would have a hard time with: OK
All 7 tests passed (0.00s)
Test suite j-test: FAIL
Test suite logged to:
/home/vanessa/programming/haskell/current/j/dist-newstyle/build/x86_64-linux/ghc-8.10.2/j-0.1.0.0/t/j-test/test/j-0.1.0.0-j-test.log
```
...which is puzzling/contradictory!
## Expected behavior
I expect it to pass the test suite or at least for the results to be consistent.
I definitely don't expect to see a tasty bug in the stack trace since I don't think that code is buggy.
## Environment
* GHC version used: 8.10.2, 8.8.4, 8.6.5, 8.4.4, 8.2.2, 8.0.2, 7.10.3
Optional:
* Operating System: Lubuntu 18.04
* System Architecture: x86_64Ben GamariBen Gamarihttps://gitlab.haskell.org/ghc/ghc/-/issues/18868Reversed profile stack2020-10-20T14:43:34ZDouglas RAILLARDReversed profile stack## Summary
Here are two extracts from the same profiling report file:
```
parseIntegral Trace.Internal src/Trace/Internal.hs:(101,56)-(104,61) 622 3871885 18.7 1...## Summary
Here are two extracts from the same profiling report file:
```
parseIntegral Trace.Internal src/Trace/Internal.hs:(101,56)-(104,61) 622 3871885 18.7 16.8 80.8 71.1 4084 3057274056
eventParser Trace src/Trace.hs:(343,87)-(374,9) 623 1930555 4.3 5.7 60.5 54.3 947 1027402080
parseFieldKind Trace src/Trace.hs:(454,9)-(468,48) 636 1936408 0.8 0.6 0.8 0.6 172 107905344
```
And
```
eventParser Trace src/Trace.hs:(343,87)-(374,9) 626 0 0.0 0.0 0.0 0.0 0 0
fieldParsers Trace src/Trace.hs:347:51-128 628 16 0.0 0.0 0.0 0.0 0 26880
parseFieldKind Trace src/Trace.hs:(454,9)-(468,48) 630 98 0.0 0.0 0.0 0.0 0 3472
parseIntegral Trace.Internal src/Trace/Internal.hs:(101,56)-(104,61) 635 59 0.0 0.0 0.0 0.0 0 0
```
The 2nd one shows the stack in the expected order. `parseIntegral` is a simple routine that does not make any direct or indirect call to `eventParser`. The only way I can see it could end up running `eventParser` code is through a thunk, but the documentation[1] explicitly mentions this case as being handled. Upon forcing, the stack attached to the thunk should be restored and the current cost center should therefore change to the one that created the thunk, not the one forcing it.
[1] https://downloads.haskell.org/~ghc/latest/docs/html/users_guide/profiling.html#rules-for-attributing-costs
## Steps to reproduce
Compile with `-prof` and `-fno-prof-auto`, `-fno-prof-cafs` (this is done via stack though, so other options might be included by it).
## Expected behavior
My understanding is that the first stack snippet should not exist in the profile report.
## Environment
* GHC version used: 8.10.2
Optional:
* Operating System: Archlinux
* System Architecture: x86_64https://gitlab.haskell.org/ghc/ghc/-/issues/18871Fix Alternative instance for IO2021-07-09T19:32:10ZIsaac BergerFix Alternative instance for IO
The Alternative instance for IO is currently defined in GHC.Base, using
```
(<|>) = mplusIO
```
Hunting further, mplusIO is defined in GHC.IO as
```
mplusIO :: IO a -> IO a -> IO a
mplusIO m n = m `catchException` \ (_ :: IOError) -> n...
The Alternative instance for IO is currently defined in GHC.Base, using
```
(<|>) = mplusIO
```
Hunting further, mplusIO is defined in GHC.IO as
```
mplusIO :: IO a -> IO a -> IO a
mplusIO m n = m `catchException` \ (_ :: IOError) -> n
```
## Why this is (possibly) wrong
Quoting documentation in Control.Exception
> Applying mask to an exception handler
>
> There's an implied mask around every exception handler in a call to one of the catch family of functions. This is because that is what you want most of the time - it eliminates a common race condition in starting an exception handler, because there may be no exception handler on the stack to handle another exception if one arrives immediately. If asynchronous exceptions are masked on entering the handler, though, we have time to install a new exception handler before being interrupted. If this weren't the default, one would have to write something like
>
> mask $ \restore ->
> catch (restore (...))
> (\e -> handler)
> If you need to unmask asynchronous exceptions again in the exception handler, restore can be used there too.
>
> Note that try and friends do not have a similar default, because there is no exception handler in this case. Don't use try for recovering from an asynchronous exception.
Being that `mplusIO` only catches exceptions of type `IOError`, it is not suited for cleanup work. It is more likely useful for running a fallback action should the first one fail. In this case, one would not want to prevent asynchronous exceptions from being able to interrupt the application in the alternative branch.
So I would suggest a better implementation for `mplusIO` should be based on `try` rather than `catch`
Something like:
```
mplusIO :: IO a -> IO a -> IO a
mplusIO m n = do
res <- catchException (m >>= \ v -> return (Right v)) (\e -> return (Left e))
case res of
Right a -> return a
Left (e :: IOError) -> n
```https://gitlab.haskell.org/ghc/ghc/-/issues/18876T13330 fails sporatically on Windows2020-10-22T13:47:37ZBen GamariT13330 fails sporatically on Windows`T13330` appears to fails every once in a while on Windows:
```patch
--- "C:/GitLabRunner/builds/2WeHDSFP/0/ghc/ghc/tmp/ghctest-d__9bkso/test spaces/testsuite/tests/concurrent/should_run/T13330.run/T13330.stderr.normalised" 2020-10-21 ...`T13330` appears to fails every once in a while on Windows:
```patch
--- "C:/GitLabRunner/builds/2WeHDSFP/0/ghc/ghc/tmp/ghctest-d__9bkso/test spaces/testsuite/tests/concurrent/should_run/T13330.run/T13330.stderr.normalised" 2020-10-21 15:48:19.306187300 +0000
+++ "C:/GitLabRunner/builds/2WeHDSFP/0/ghc/ghc/tmp/ghctest-d__9bkso/test spaces/testsuite/tests/concurrent/should_run/T13330.run/T13330.run.stderr.normalised" 2020-10-21 15:48:19.306187300 +0000
@@ -1,3 +0,0 @@
-T13330: Successful exception
-CallStack (from HasCallStack):
- error, called at T13330.hs:<line>:<column> in <package-id>:Main
```https://gitlab.haskell.org/ghc/ghc/-/issues/19023Segfault on s390x due to missing sign/zero extend2021-01-26T14:50:29ZStefan Schulze FrielinghausSegfault on s390x due to missing sign/zero extend## Summary
Building a recent stage1 compiler is successful. However, running the stage1 binary results in a segfault:
```
gdb --args _build/stage1/bin/ghc --version
Reading symbols from _build/stage1/bin/ghc...
(No debugging symbols fo...## Summary
Building a recent stage1 compiler is successful. However, running the stage1 binary results in a segfault:
```
gdb --args _build/stage1/bin/ghc --version
Reading symbols from _build/stage1/bin/ghc...
(No debugging symbols found in _build/stage1/bin/ghc)
(gdb) r
Starting program: /devel/ghc/ghc-master/_build/stage1/bin/ghc --version
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/lib64/libthread_db.so.1".
[New Thread 0x3fff367d870 (LWP 1001533)]
[New Thread 0x3fff2e7c870 (LWP 1001534)]
Thread 3 "ghc:w" received signal SIGSEGV, Segmentation fault.
[Switching to Thread 0x3fff2e7c870 (LWP 1001534)]
0x000003fff42b5a3c in setIOManagerControlFd (cap_no=<optimized out>, fd=6) at rts/Capability.c:1371
1371 RELAXED_STORE(&capabilities[cap_no]->io_manager_control_wr_fd, fd);
```
The 32bit parameter `cap_no` resides in a 64bit register where the high part is not zero. On s390x the C calling convention is that any value which is passed in a register must be sign/zero extended which is not the case here. For example, currently code like
```llvm
%lnb9U = bitcast i8* @setIOManagerControlFd to void (i32, i32)*
call ccc void (i32, i32) %lnb9U( i32 %lnb9S, i32 %lnb9T ) nounwind
```
is emitted where the first parameter should be zero extended and the second parameter sign extended.
I assume that this was not a problem in the past since different sized integers were finally all treated as word sized integers and therefore as 64bit integers on s390x. This has changed with commit be5d74caab64abf9d986fc7290f62731db7e73e7.
## Steps to reproduce
Since commit be5d74caab64abf9d986fc7290f62731db7e73e7 run `hadrian/build -c -j --flavour=quick-llvm && _build/stage1/bin/ghc --version` which results in a segfault.
## Environment
* GHC version used: 8.10
Optional:
* Operating System: Fedora 33
* System Architecture: s390xhttps://gitlab.haskell.org/ghc/ghc/-/issues/19053Strange behavior when using -O2020-12-15T15:54:22ZArthur KhashaevStrange behavior when using -O## Summary
I've encountered a strange behavior using `ghc -O` on the program with `Prelude.last`, `Data.List.group`, `System.Exit`, and `IO` effects.
## Steps to reproduce
```hs
import Data.List (group)
import System.Exit (exitFailure...## Summary
I've encountered a strange behavior using `ghc -O` on the program with `Prelude.last`, `Data.List.group`, `System.Exit`, and `IO` effects.
## Steps to reproduce
```hs
import Data.List (group)
import System.Exit (exitFailure, exitSuccess)
main :: IO ()
main = do
_ <- getContents
if last (group "a") == "a" then exitSuccess else exitFailure
```
```
ghc -O snippet.hs -o snippet && ./snippet
```
## Actual behaviour
```
snippet: Prelude.last: empty list
```
Even strange, this can be fixed in one of the following ways:
- Compiling without `-O`.
- Removing `_ <- getContents`.
- Reducing `(group "a")` to `["a"]` or `last (group "a")` to `"a"`.
## Expected behavior
I expect successful exit without `Prelude.last: empty list` error.
## Environment
* GHC version used: `The Glorious Glasgow Haskell Compilation System, version 8.6.5` from deb package `ghc/focal 8.8.1+dfsg1+is+8.6.5+dfsg1-3 amd64`.
Optional:
* Operating System:
`Linux host 5.4.0-48-generic #52-Ubuntu SMP Thu Sep 10 10:58:49 UTC 2020 x86_64 x86_64 x86_64 GNU/Linux`
* System Architecture:
`x86_64`https://gitlab.haskell.org/ghc/ghc/-/issues/19057CPP def name typo: THREADEDED_RTS2020-12-19T00:34:03ZCsaba HruskaCPP def name typo: THREADEDED_RTS## Summary
The `THREADEDED_RTS` CPP def symbol seems invalid.
It should be `THREADED_RTS`.
https://gitlab.haskell.org/ghc/ghc/-/blob/78580ba3f99565b0aecb25c4206718d4c8a52317/rts/RaiseAsync.c#L462## Summary
The `THREADEDED_RTS` CPP def symbol seems invalid.
It should be `THREADED_RTS`.
https://gitlab.haskell.org/ghc/ghc/-/blob/78580ba3f99565b0aecb25c4206718d4c8a52317/rts/RaiseAsync.c#L462https://gitlab.haskell.org/ghc/ghc/-/issues/19078Restarting event log results in invalid output2021-03-05T21:33:31ZBen GamariRestarting event log results in invalid outputCurrently if one calls `endEventLogging()`, followed by `beginEventLogging()`, the eventlog that results has block markers before the header, rendering the output unreadable to `ghc-events`. The problem is that `endEventLogging()` calls ...Currently if one calls `endEventLogging()`, followed by `beginEventLogging()`, the eventlog that results has block markers before the header, rendering the output unreadable to `ghc-events`. The problem is that `endEventLogging()` calls `printAndClearEventsBuf(&eventBuf)`, which posts a marker after flushing the buffer. `postHeaderEvents()` then fails to clear this marker before posting the header.
The solution seems clear: call `resetEventsBuf()` in either `endEventLogging()` or `postHeaderEvents()`.https://gitlab.haskell.org/ghc/ghc/-/issues/19080arithmetic sequence discrepancy2020-12-17T16:45:02ZDOUGLAS MCILROYarithmetic sequence discrepancyGHC 8.6.5 understands `[0.0,-1.0,-1.5]` to mean `[0.0,-1.0,-2.0]`
Haskell 2010 Report, section 6.3.4, next-to-last paragraph says, "For `Float` and `Double`, the semantics of the `enumFrom` family is given by the rules for `Int` above, ...GHC 8.6.5 understands `[0.0,-1.0,-1.5]` to mean `[0.0,-1.0,-2.0]`
Haskell 2010 Report, section 6.3.4, next-to-last paragraph says, "For `Float` and `Double`, the semantics of the `enumFrom` family is given by the rules for `Int` above, except that the list terminates when the elements become greater than `e3 + i∕2` for positive increment `i`, or when they become less than `e3 + i∕2` for negative `i`."
According to the spec, the answer should be `[0.0,-1.0]`. Either GHC or the Report is wrong.
Observed in GHC 8.6.5https://gitlab.haskell.org/ghc/ghc/-/issues/19147Error in accounting for GC cpu time in sequential collections2021-05-04T23:17:39ZDouglas Wilsondouglas@well-typed.comError in accounting for GC cpu time in sequential collections## Summary
stat_endGC accounts for cpu time consumed by a garbage collection the following fragment:
```
for (unsigned int i=0; i < par_n_threads; i++) {
gc_thread *gct = gc_threads[i];
ASSERT(gct->gc_end...## Summary
stat_endGC accounts for cpu time consumed by a garbage collection the following fragment:
```
for (unsigned int i=0; i < par_n_threads; i++) {
gc_thread *gct = gc_threads[i];
ASSERT(gct->gc_end_cpu >= gct->gc_start_cpu);
stats.gc.cpu_ns += gct->gc_end_cpu - gct->gc_start_cpu;
}
```
however, this is incorrect when accounting for a sequential collection when n_capabilities > 1. In this case, par_n_threads will be set to 1. However the cpu stats will not necessarily be on capability 0(i.e. in gc_threads[0]) which the fragment above assumes. The stats will be on the capability of the gc leader.
EDIT:
I've also seen
```
for (i=0; i < n_gc_threads; i++) {
copied += RELAXED_LOAD(&gc_threads[i]->copied);
}
```
in GC.c seems to have the same problem. Holding off fixing this for now, since I now suspect I may be confused
## Steps to reproduce
I've not constructed a demonstration.
## Expected behavior
n/a
## Environment
* GHC version used: headhttps://gitlab.haskell.org/ghc/ghc/-/issues/19158ghci's :type still ignores ill-kinded type application with -fdefer-type-errors2021-08-02T17:29:55ZJakob Brünkerghci's :type still ignores ill-kinded type application with -fdefer-type-errors## Summary
#16376 was fixed in 8.10, but the same problem is still there if -fdefer-type-errors is enabled.
## Steps to reproduce
Write `:set -fdefer-type-errors` followed by `:t id @Maybe` in ghci. It produces no ouput, neither an er...## Summary
#16376 was fixed in 8.10, but the same problem is still there if -fdefer-type-errors is enabled.
## Steps to reproduce
Write `:set -fdefer-type-errors` followed by `:t id @Maybe` in ghci. It produces no ouput, neither an error nor anything else.
## Expected output
```
<interactive>:1:5: warning: [-Wdeferred-type-errors]:
• Expecting one more argument to ‘Maybe’
Expected a type, but ‘Maybe’ has kind ‘* -> *’
• In the type ‘Maybe’
In the expression: id @Maybe
id @Maybe :: t
```
## Environment
* GHC version used: 9.1.20201223
Optional:
* Operating System: Ubuntu inside WSL2 inside Windows 10
* System Architecture: x86_64https://gitlab.haskell.org/ghc/ghc/-/issues/19170Natural shiftL 0 65 not equal to 02021-01-29T17:43:25ZChristiaan BaaijNatural shiftL 0 65 not equal to 0## Summary
```
GHCi, version 9.0.0.20201227: https://www.haskell.org/ghc/ :? for help
ghci> import Data.Bits
ghci> import GHC.Natural
ghci> shiftL 0 65 == (0 :: Natural)
False
```
## Expected behavior
0 should be equal to 0, no matte...## Summary
```
GHCi, version 9.0.0.20201227: https://www.haskell.org/ghc/ :? for help
ghci> import Data.Bits
ghci> import GHC.Natural
ghci> shiftL 0 65 == (0 :: Natural)
False
```
## Expected behavior
0 should be equal to 0, no matter how many bits you shift it to the left.
## Environment
* GHC version used: 9.0.1-rc1
Optional:
* Operating System: Ubuntu 18.04 LTS (on WSL2, Windows 10.0.19042)
* System Architecture: x86_649.0.1Sylvain HenrySylvain Henryhttps://gitlab.haskell.org/ghc/ghc/-/issues/19288Type literals in Reflection of type constructor kinds leads to SafeHaskell vi...2021-02-05T21:10:33ZKyle EhrlichType literals in Reflection of type constructor kinds leads to SafeHaskell violation## Summary
[Data.Typeable.Internal#mkTypeLitFromString](https://hackage.haskell.org/package/base-4.14.1.0/docs/src/Data.Typeable.Internal.html#mkTypeLitFromString) has a typo which causes type Natural literals are tagged with the type S...## Summary
[Data.Typeable.Internal#mkTypeLitFromString](https://hackage.haskell.org/package/base-4.14.1.0/docs/src/Data.Typeable.Internal.html#mkTypeLitFromString) has a typo which causes type Natural literals are tagged with the type Symbol type constructor. This can be used to get a `TypeRep Nat` that is equal to the true `TypeRep Symbol`.
## Steps to reproduce
Run this program:
```hs
{-# LANGUAGE DataKinds, KindSignatures, PolyKinds, TypeOperators, Safe #-}
module Main where
import Data.Maybe
import Data.Proxy
import Type.Reflection
import GHC.TypeLits
data Dat (x :: Proxy 1) = MkD1
evil :: Maybe (Nat :~~: Symbol)
evil = eqTypeRep (case (typeRepKind (typeRep :: TypeRep Dat)) of
(Fun (App _ x) _) -> typeRepKind x)
(typeRep :: TypeRep Symbol)
main :: IO ()
main = print (isJust evil)
```
The program prints True. This could easily be used to make an unsafeCast.
## Expected behavior
The program prints False
## Environment
* GHC version used: 8.10.39.0.2https://gitlab.haskell.org/ghc/ghc/-/issues/19345Optimisations cause incorrect runtime result in Integer calculation2021-03-10T21:27:06Zsheafsam.derbyshire@gmail.comOptimisations cause incorrect runtime result in Integer calculation## Summary
The following program
```haskell
module Main where
import Numeric.Natural
( Natural )
a, q :: Natural
a = fromIntegral ( 18446744073709551616 :: Integer )
q = 18446744073709551616
main :: IO ()
main = print ( fromIntegr...## Summary
The following program
```haskell
module Main where
import Numeric.Natural
( Natural )
a, q :: Natural
a = fromIntegral ( 18446744073709551616 :: Integer )
q = 18446744073709551616
main :: IO ()
main = print ( fromIntegral ( a `div` q ) :: Word )
```
runs into the following strange behaviour:
GHC 8.10 -O0
```
> main
1
```
GHC 8.10 -O1
```
> main
1
```
GHC 9.0 -O0
```
> main
1
```
GHC 9.0 -O1
```
> main
0
```
Tagging @hsyl20 as I expect him to know about what's going on.
## Steps to reproduce
Simply run the above program with either `ghc -O0` or `ghc -O1` to get the different results.
## Further remarks
Changing `fromIntegral` to `fromInteger` causes GHC 9.0 with optimisations to return the correct result, so it might be an incorrect rewrite rule involving `fromIntegral`?
## Environment
On GHC 9.0.1, Windows 10 x64.9.0.1https://gitlab.haskell.org/ghc/ghc/-/issues/19369Data.Complex doesn't consistently distinguish -0.02022-03-14T08:22:59ZJKTKopsData.Complex doesn't consistently distinguish -0.0## Summary
This is a bit of a nitpick.
I'm implementing a numeric system for an interpreter that supports complex numbers. I want to piggyback off of Data.Complex as much as possible since it would be pretty silly to just duplicate all...## Summary
This is a bit of a nitpick.
I'm implementing a numeric system for an interpreter that supports complex numbers. I want to piggyback off of Data.Complex as much as possible since it would be pretty silly to just duplicate all of the code that already exists.
Normal Haskell Doubles are IEEE doubles, which means there is both a +0.0 and a -0.0. Haskell does (because it would be more effort not to) distinguish between these values in computations, notably `1 / 0.0 = Infinity` but `1 / (-0.0) = -Infinity`. When working with `Complex Double`, this means that the difference between 0.0 and -0.0 is observable. However the implementation of phase has a short-circuit for when the argument is equal to 0 so that the phase is always 0.
As a result, since many `Floating` operations are defined in terms of `log`, which is defined in terms of `phase`, the results are incosistent with other languages at -0. Other languages (including, hopefully, mine) which distinguish 0.0 and -0.0 give `log 0.0 = -Infinity` but `log (-0.0) = -Infinity + pi*i`. Using Data.Complex, both are always `-Infinity`.
Note that the standard example of log's branch cut, `log (-1-0i)` behaves correctly, giving `0 :+ (-pi)`.
## Steps to reproduce
Apply `phase ((-0.0) :+ 0)`.
## Expected behavior
Result is `pi`.
## Environment
* base-4.14.0.0https://gitlab.haskell.org/ghc/ghc/-/issues/19411fromIntegral (2^64 :: Integer) == (0 :: Natural)2021-12-26T13:23:06ZBodigrimfromIntegral (2^64 :: Integer) == (0 :: Natural)## Summary
`powModNatural` returns a wrong answer.
## Steps to reproduce
```haskell
import Data.Bits
import GHC.Natural
main = print $ powModNatural 0 (fromIntegral n) 2
where
n = 1 `shiftL` 64 :: Integer
{-# NOINLINE n #...## Summary
`powModNatural` returns a wrong answer.
## Steps to reproduce
```haskell
import Data.Bits
import GHC.Natural
main = print $ powModNatural 0 (fromIntegral n) 2
where
n = 1 `shiftL` 64 :: Integer
{-# NOINLINE n #-}
```
```
$ ghc -O1 powmod.hs && ./powmod
[1 of 1] Compiling Main ( powmod.hs, powmod.o )
Linking powmod ...
1
```
## Expected behavior
Expected answer is 0. Removing `NOINLINE`, changing `fromIntegral` to `fromInteger`, or switching to `-O0` all rectify the situation.
## Environment
* GHC version used: 9.0.1
Optional:
* Operating System: MacOS
* System Architecture: x649.0.2Sylvain HenrySylvain Henryhttps://gitlab.haskell.org/ghc/ghc/-/issues/19413unsafePerformIO/NOINLINE tricks no longer work2023-01-06T15:54:52ZNeil MitchellunsafePerformIO/NOINLINE tricks no longer work## Summary
Starting with GHC 9.0.1, the following program:
```haskell
{-# OPTIONS_GHC -O1 #-}
import System.IO.Unsafe
import Data.IORef
{-# NOINLINE resourceId #-}
resourceId :: IO Int
resourceId = unsafePerformIO counter
counter ::...## Summary
Starting with GHC 9.0.1, the following program:
```haskell
{-# OPTIONS_GHC -O1 #-}
import System.IO.Unsafe
import Data.IORef
{-# NOINLINE resourceId #-}
resourceId :: IO Int
resourceId = unsafePerformIO counter
counter :: IO (IO Int)
counter = do
ref <- newIORef 0
pure $ atomicModifyIORef' ref $ \i -> let j = i + 1 in (j, j)
main = do
print =<< resourceId
print =<< resourceId
```
Has gone from printing `1` then `2`, to printing `1` then `1`.
Whether it's a bug or GHC just getting better at optimisation is debatable. It definitely breaks code that works with 8.10, but I appreciate that with `unsafePerformIO` that isn't evidence of anything. I'm raising a bug after looking at the core, which seems like it might be broken.
## Steps to reproduce
Using GHC 9.0:
```
$ ghc --make Test.hs
$ ./Test
1
1
```
## Expected behaviour
```
1
2
```
## Environment
GHC 9.0.1. Reproduced on Windows, but happens on Linux/Mac CI machines too.
## Core output
The reason I raised this as a bug is after looking at the output of `-ddump-simpl`, available at https://gist.github.com/ndmitchell/a45d1db2eea8f8b2ee207e5d29475fce#file-core-hs-L67. Approximately, I think it has done the equivalent of:
```haskell
resourceId = runRW $ \rw1 rw2 -> <all the work>
```
Namely, it pushed the creation of the `IORef` inside the inner `IO`, which I don't believe is allowed.https://gitlab.haskell.org/ghc/ghc/-/issues/19436Eventlog flushing in non-threaded is broken2021-03-01T16:19:18ZMatthew PickeringEventlog flushing in non-threaded is broken`flushEventLog` in non-threaded way doesn't flush the `capEventBuf[0]` event buffer.`flushEventLog` in non-threaded way doesn't flush the `capEventBuf[0]` event buffer.Matthew PickeringMatthew Pickeringhttps://gitlab.haskell.org/ghc/ghc/-/issues/19563PowerPC: IntegerToFloat test failure2021-03-23T12:40:34ZPeter Trommlerptrommler@acm.orgPowerPC: IntegerToFloat test failureHere is the result from IntegerTo Float on powerpc64 Linux:
```
0x1p36
0x1.fffffcp59
0x1p60
-0x1.fffffep59
+0x1p60
0x1p60
0x1.fffffcp63
0x1p64
```Here is the result from IntegerTo Float on powerpc64 Linux:
```
0x1p36
0x1.fffffcp59
0x1p60
-0x1.fffffep59
+0x1p60
0x1p60
0x1.fffffcp63
0x1p64
```Peter Trommlerptrommler@acm.orgPeter Trommlerptrommler@acm.orghttps://gitlab.haskell.org/ghc/ghc/-/issues/19569Floating Point regression in NoFib's `imaginary/integrate` benchmark2023-05-19T23:07:51ZSebastian GrafFloating Point regression in NoFib's `imaginary/integrate` benchmarkIt appears that recent master commits fail to pass NoFib. Specifically, [`imaginary/integrate`](https://gitlab.haskell.org/ghc/nofib/-/blob/854208b1e61ab5d92ef0d5821a78c14059c25cf2/imaginary/integrate/Main.hs) fails with a stdout mismatc...It appears that recent master commits fail to pass NoFib. Specifically, [`imaginary/integrate`](https://gitlab.haskell.org/ghc/nofib/-/blob/854208b1e61ab5d92ef0d5821a78c14059c25cf2/imaginary/integrate/Main.hs) fails with a stdout mismatch in modes norm and slow (but not fast, which was used by CI):
```
../../runstdtest/runstdtest ./integrate -o1 integrate.stdout -o1 integrate.stdout -ghc-timing +RTS -V0 -RTS 1000000;
0.64user 0.00system 0:00.65elapsed 100%CPU (0avgtext+0avgdata 11252maxresident)k 0inputs+16outputs (0major+1491minor)pagefaults 0swaps
././integrate +RTS -V0 -RTS 1000000 < /dev/null
expected stdout not matched by reality
--- integrate.stdout 2019-11-20 16:38:31.157747042 +0100
+++ /tmp/runtest553570.1 2021-03-20 18:12:57.094954877 +0100
@@ -1 +1 @@
-9.093955583391733e28
+1.9105614312239304e29
make: *** [../../mk/target.mk:101: runtests] Error 1
```
The first commit with which I could reproduce the issue was 4196969c53c5. Its direct parent, f78f001c91736e31c, doesn't report an output mismatch.
I suspect that the different literal desugaring produces floating point literals that are associated slightly differently.
I think that benchmark may be flawed anyway: I accumulates an ever-growing FP error. While fast still manages to output 0 at the end, the other modes report absurdly high deviations from the expected 0.
We should diagnose if we got something wrong and fix it before we release 9.2.9.6.1https://gitlab.haskell.org/ghc/ghc/-/issues/19680case over signum of Integer is incorrect in GHC 9.22021-05-13T01:55:47ZBodigrimcase over signum of Integer is incorrect in GHC 9.2## Summary
`case` over `signum` of `Integer` returns an incorrect result.
## Steps to reproduce
```
GHCi, version 9.2.0.20210331: https://www.haskell.org/ghc/ :? for help
ghci> signum (-1 :: Integer)
-1
ghci> case signum (-1 :: Integ...## Summary
`case` over `signum` of `Integer` returns an incorrect result.
## Steps to reproduce
```
GHCi, version 9.2.0.20210331: https://www.haskell.org/ghc/ :? for help
ghci> signum (-1 :: Integer)
-1
ghci> case signum (-1 :: Integer) of 1 -> "FOO"; -1 -> "OK"; 0 -> "BAR"; _ -> "FAIL"
"FAIL"
```
## Expected behavior
I would expect the second line to return `"OK"`.
## Environment
* GHC version used: 9.2.0.202103319.2.1Matthew PickeringMatthew Pickeringhttps://gitlab.haskell.org/ghc/ghc/-/issues/19724Non-reproducible failure in RestartEventLogging test in `threaded1` way.2021-04-22T01:01:31ZvdukhovniNon-reproducible failure in RestartEventLogging test in `threaded1` way.## Summary
Running `validate` by hand the test typically succeeds, but on one run I got:
```
...
--- tests/rts/RestartEventLogging.run/RestartEventLogging.stdout.normalised 2021-04-20 21:29:06.924934000 -0400
+++ tests/rts/RestartEventL...## Summary
Running `validate` by hand the test typically succeeds, but on one run I got:
```
...
--- tests/rts/RestartEventLogging.run/RestartEventLogging.stdout.normalised 2021-04-20 21:29:06.924934000 -0400
+++ tests/rts/RestartEventLogging.run/RestartEventLogging.run.stdout.normalised 2021-04-20 21:29:06.925062000 -0400
@@ -8,6 +8,11 @@
stop
init
Event log started with EVENT_HEADER_BEGIN
+ERROR: event does not start with EVENT_HEADER_BEGIN
+0x0 != 0x68
+0x12 != 0x64
+0x0 != 0x72
+0x0 != 0x62
stop
init
Event log started with EVENT_HEADER_BEGIN
...
tests/rts/RestartEventLogging.run RestartEventLogging [bad stdout] (threaded1)
```
The expected value is:
```
includes/rts/EventLogFormat.h:#define EVENT_HEADER_BEGIN 0x68647262 /* 'h' 'd' 'r' 'b' */
```
but we got '\0\x12\0\0'.
## Steps to reproduce
Not easily reproducible, could even be a hardware glitch, though that seems unlikely...
## Expected behavior
The test should ideally pass consistently
## Environment
* GHC version used: commit 4cfb6b89479d873f1091dce59f7fbed635d37d6a (HEAD -> freebsd-tlsgd, v/freebsd-tlsgd) of MR !5561. The merge-base with head is: commit 0619fb0fb14a98f04aac5f031f6566419fd27495 (origin/master, origin/HEAD, master)
Optional:
* Operating System: FreeBSD 12.2
* System Architecture: X86_64https://gitlab.haskell.org/ghc/ghc/-/issues/19771TH recompilation check is defeated by packages2021-06-08T19:30:57ZMatthew PickeringTH recompilation check is defeated by packagesIt's possible to defeat the recompilation checker by using and then modifying a TH definition from another package.
Reproducer: https://github.com/mpickering/special-fiesta
In the example there are two packages. Package `p` defines a l...It's possible to defeat the recompilation checker by using and then modifying a TH definition from another package.
Reproducer: https://github.com/mpickering/special-fiesta
In the example there are two packages. Package `p` defines a library
```
module Lib where
{-# NOINLINE p #-}
p = [| 0 |]
```
which is then used in package `q`:
```
module Main where
import Lib
main = print $(p)
```
Running the executable prints `0` initially.
Then modifying the library `p`,
```
module Lib where
p = [| 1 |]
```
when the executable is rerun the result should be printing `1`, but it still prints `0`.
The recompilation check fails because the ABI for `Lib` didn't change, and so GHC concluded that it didn't need to recompile `Main` again.
The logic for computing stable modules only considers stability for home package modules when it should also consider whether the object files for dependencies have changed.
A correct fix is to take the hash of all the object files in the transitive dependencies of a module (such as is already done for plugins)Matthew PickeringMatthew Pickeringhttps://gitlab.haskell.org/ghc/ghc/-/issues/19841Debug.Trace.trace optimized away when throwing exceptions, starting with GHC 8.82023-07-20T07:17:29ZAndreas AbelDebug.Trace.trace optimized away when throwing exceptions, starting with GHC 8.8## Summary
`Debug.Trace.trace` messages printed with `-O0` are optimized away (e.g. with `-O1`) in the presence of `Control.Exception.throw`, starting with GHC 8.8.
## Steps to reproduce
Compile and run this with either `-O0` or `-O1`...## Summary
`Debug.Trace.trace` messages printed with `-O0` are optimized away (e.g. with `-O1`) in the presence of `Control.Exception.throw`, starting with GHC 8.8.
## Steps to reproduce
Compile and run this with either `-O0` or `-O1`:
```haskell
import Control.Exception
import Debug.Trace
data MyException = MyException deriving Show
instance Exception MyException
main :: IO ()
main = handle (\ MyException -> putStrLn "Exception") $ do
trace "Debugging" 5
`seq` throw MyException
`seq` putStrLn "Survived Exception"
```
## Expected behavior
I expect the output
```
Debugging
Exception
```
which is delivered with `-O0` and, up to GHC 8.6, also with `-O1`.
Starting with GHC 8.8 at `-O1`, it prints only
```
Exception
```
## Further research
My mental model for `Debug.Trace.trace :: String -> a -> a` is one of
```haskell
trace msg a = unsafePerformIO (putStrLn msg) `seq` a
trace msg a = unsafePerformIO $ do
putStrLn msg
return a
```
Both of these actually work, meaning that the debug message is **not** optimized away for these simple implementations.
Trivium: I found this bug (as I would call it) when researching https://github.com/agda/agda/issues/5379.
## Environment
* GHC versions used: 8.0.2, 8.2.2, 8.4.4, 8.6.4, 8.8.4, 8.10.4, 9.0.1
Optional:
* Operating System: macOS Mojave 10.14.6
* System Architecture: Macky McMacFacehttps://gitlab.haskell.org/ghc/ghc/-/issues/19852PPC NCG: Unsigned compare with 16-bit constants broken2021-10-11T08:27:01ZPeter Trommlerptrommler@acm.orgPPC NCG: Unsigned compare with 16-bit constants brokenMany tests fail after c6de5805 because unicode encoding is messed up.
The root cause is a bug in PPC NCG where the first operand is
always sign extended (even for unsigned compare) when comparing with a small constant, i.e. a constant t...Many tests fail after c6de5805 because unicode encoding is messed up.
The root cause is a bug in PPC NCG where the first operand is
always sign extended (even for unsigned compare) when comparing with a small constant, i.e. a constant that would fit into 16 bits.
Fix is coming.Peter Trommlerptrommler@acm.orgZubinPeter Trommlerptrommler@acm.orghttps://gitlab.haskell.org/ghc/ghc/-/issues/19917Unsound optimization with `error`, introduced in GHC 8.22024-02-22T11:21:40ZAndreas AbelUnsound optimization with `error`, introduced in GHC 8.2We discovered an unsound optimization (see https://github.com/agda/agda-stdlib/pull/1512) in GHC starting with 8.2. I managed to shrink it down to the following code:
```haskell
-- Unsound compiler optimization in presence of @error@.
...We discovered an unsound optimization (see https://github.com/agda/agda-stdlib/pull/1512) in GHC starting with 8.2. I managed to shrink it down to the following code:
```haskell
-- Unsound compiler optimization in presence of @error@.
foo :: String -> String
foo d1@(_:_)
| not (all (== '-') d1)
, last d1 == '\r'
= error "OK1"
foo _ = error "OK2"
main = putStr $ foo "Hello, world!"
```
With -O0, or until GHC 8.0.2, this outputs
```
<main>: OK2
CallStack (from HasCallStack):
error, called at <loc> in main:Main
```
With -O1 or -O2 and GHC 8.2 - 9.0.1, (I tested from 8.2.2), this gives:
```
Prelude.last: empty list
```https://gitlab.haskell.org/ghc/ghc/-/issues/19935getExecutablePath returns ld loader path2021-06-04T09:44:29ZDaneel S. YaitskovgetExecutablePath returns ld loader pathif Haskell program is launched through ld linkder then
System.Environment.getExecutablePath returns path to the linker not to the program, meanwhile getArgs works correctly and first argument is not a path to the Haskell program, the la...if Haskell program is launched through ld linkder then
System.Environment.getExecutablePath returns path to the linker not to the program, meanwhile getArgs works correctly and first argument is not a path to the Haskell program, the last fact makes hard to implement workaround.
```
module Main where
import System.Environment
main :: IO ()
main = do
p <- getExecutablePath
print p
x <- getArgs
print x
```
```
ghc --make -o print-args Main.hs
```
```
readelf -a print-args | grep Requesting
[Requesting program interpreter: /lib64/ld-linux-x86-64.so.2]
/lib64/ld-linux-x86-64.so.2 $PWD/print-args a b c
"/usr/lib/x86_64-linux-gnu/ld-2.28.so"
["a","b","c"]
```
```
ghc --version
The Glorious Glasgow Haskell Compilation System, version 8.10.4
uname -a
Linux diehard 5.9.13 #1 SMP Wed Dec 9 14:12:51 MSK 2020 x86_64 GNU/Linux
```
workaround:
```
getFullProgName :: IO String
getFullProgName =
alloca $ \ p_argc ->
alloca $ \ p_argv -> do
getFullProgArgv p_argc p_argv
peek p_argv >>= peek >>= peekCString
foreign import ccall unsafe "getFullProgArgv"
getFullProgArgv :: Ptr CInt -> Ptr (Ptr CString) -> IO ()
main = getFullProgName >>= putStrLn
```https://gitlab.haskell.org/ghc/ghc/-/issues/19976Mysterious issue with bytestring "LazyWord8.fromString literal" test2021-12-26T13:23:06ZBodigrimMysterious issue with bytestring "LazyWord8.fromString literal" test# Reproduction
```
git clone https://github.com/haskell/bytestring
cd bytestring
# git checkout 06cbef10f4869c6afdac210a22d9813b4f7f2fe6
```
Run tests with GHC 8.10 and 9.0, both should succeed:
```
$ cabal run -w ghc-8.10.4 prop-compi...# Reproduction
```
git clone https://github.com/haskell/bytestring
cd bytestring
# git checkout 06cbef10f4869c6afdac210a22d9813b4f7f2fe6
```
Run tests with GHC 8.10 and 9.0, both should succeed:
```
$ cabal run -w ghc-8.10.4 prop-compiled -- --hide-successes -p "LazyWord8.fromString literal"
All 1 tests passed (0.00s)
$ cabal run -w ghc-9.0.1 prop-compiled -- --hide-successes -p "LazyWord8.fromString literal"
All 1 tests passed (0.00s)
```
Now apply an innocent patch:
```
$ git show d701a2a9a51da47da8240a7d3adf2794ba891e90
--- a/Data/ByteString/Lazy/Internal.hs
+++ b/Data/ByteString/Lazy/Internal.hs
+packBytes [] = Empty
packBytes cs0 =
packChunks 32 cs0
...
packChars :: [Char] -> ByteString
+packChars [] = Empty
packChars cs0 = packChunks 32 cs0
$ git cherry-pick d701a2a9a51da47da8240a7d3adf2794ba891e90
Auto-merging Data/ByteString/Lazy/Internal.hs
```
and rerun tests.
# Expected results
Tests suceed both in GHC 8.10.4 and 9.0.1.
# Actual results
Tests succeed in GHC 8.10.4, but fail in 9.0.1:
```
$ cabal run -w ghc-8.10.4 prop-compiled -- --hide-successes -p "LazyWord8.fromString literal"
All 1 tests passed (0.00s)
$ cabal run -w ghc-9.0.1 prop-compiled -- --hide-successes -p "LazyWord8.fromString literal"
All
LazyWord8
fromString literal: FAIL
*** Failed! Falsified (after 1 test)
```
What surprises me most is that the failing test has no apparent connection to the patch in question:
```haskell
, testProperty "fromString literal" $
fromString "\0\1\2\3\4" == B.pack [0,1,2,3,4]
```
See earlier discussion at https://github.com/haskell/bytestring/pull/394
CC @sjakobi @phadej9.0.2Matthew PickeringMatthew Pickeringhttps://gitlab.haskell.org/ghc/ghc/-/issues/20066Rule "fromIntegral/Int->Natural" is inconsistent2021-09-21T16:58:42ZSylvain HenryRule "fromIntegral/Int->Natural" is inconsistentAs noticed by @trac-vdukhovni in https://gitlab.haskell.org/ghc/ghc/-/issues/20062#note_362750:
```haskell
import GHC.Natural
i :: Int
i = -10
main :: IO ()
main = let n :: Natural
n = fromIntegral i
in print n
```
...As noticed by @trac-vdukhovni in https://gitlab.haskell.org/ghc/ghc/-/issues/20062#note_362750:
```haskell
import GHC.Natural
i :: Int
i = -10
main :: IO ()
main = let n :: Natural
n = fromIntegral i
in print n
```
- with -O2: prints 18446744073709551606
- with -O0: throw "arithmetic underflow"
While it should always throw an exception (I guess? "fromIntegral" isn't precisely defined in the report).
GHC versions: 9.0, 9.2, HEADSylvain HenrySylvain Henryhttps://gitlab.haskell.org/ghc/ghc/-/issues/20191Unicode strings are mangled in GHC 9.0.12021-08-03T14:50:55ZBodigrimUnicode strings are mangled in GHC 9.0.1## Summary
GHC 9.0.1 seems to behave weirdly, when strings contain Unicode characters, while GHC 8.10.5 and HEAD work fine.
@mpickering Is it another manifestation of #19976?
## Steps to reproduce
```haskell
{-# OPTIONS_GHC -O1 #-}
...## Summary
GHC 9.0.1 seems to behave weirdly, when strings contain Unicode characters, while GHC 8.10.5 and HEAD work fine.
@mpickering Is it another manifestation of #19976?
## Steps to reproduce
```haskell
{-# OPTIONS_GHC -O1 #-}
import Data.Text ()
import Data.Text.Internal.Fusion (unstream)
import Data.Text.Internal.Fusion.Common (streamList)
main :: IO ()
main = print (unstream (streamList "\65536"))
```
```sh
$ ghc-9.0.1 Unicode.hs && ./Unicode
[1 of 1] Compiling Main ( Unicode.hs, Unicode.o )
Linking Unicode ...
"\65536\62464\61312"
```
## Expected behavior
I'd expect to have `"\65536"` back.
## Environment
* GHC version used: 9.0.19.0.2https://gitlab.haskell.org/ghc/ghc/-/issues/20317Odd interaction between unsafePerformIO and threadDelay2024-02-27T13:58:43ZDavid FeuerOdd interaction between unsafePerformIO and threadDelay## Summary
`threadDelay` doesn't seem to resume properly after an exception in an `unsafePerformIO` context.
## Steps to reproduce
```
ghci -threaded
> import Control.Concurrent
> import System.IO.Unsafe
> import Control.Exception
> ...## Summary
`threadDelay` doesn't seem to resume properly after an exception in an `unsafePerformIO` context.
## Steps to reproduce
```
ghci -threaded
> import Control.Concurrent
> import System.IO.Unsafe
> import Control.Exception
> let okay = unsafePerformIO (evaluate (sum [1..10^7]) *> putStrLn "Hi there.")
> okay
-- Hit Ctrl-C
-- See "^CInterrupted."
> okay
-- After a few seconds, it prints "Hi there." and then "()".
> let oops = unsafePerformIO (threadDelay (10^7) *> putStrLn "Hi there.")
> oops
-- Hit Ctrl-C
-- See "^CInterrupted."
> oops
-- See "^CInterrupted."
```
## Expected behavior
I would expect the `threadDelay` call to resume, and to eventually see "Hi there." and the `()` return value.
## Environment
* GHC version used: 9.0.1
Optional:
* Operating System: Linux (OpenSUSE)
* System Architecture: x86_64Ben GamariBen Gamarihttps://gitlab.haskell.org/ghc/ghc/-/issues/20338GHC.ByteOrder is broken2021-09-09T03:50:31ZAlexey KuleshevichGHC.ByteOrder is broken`GHC.ByteOrder.targetByteOrder` does not report endianness correctly.
Here is how to reproduce:
```haskell
{-# LANGUAGE UnboxedTuples #-}
{-# LANGUAGE MagicHash #-}
{-# LANGUAGE CPP #-}
import Data.ByteString.Short.Internal
import GHC...`GHC.ByteOrder.targetByteOrder` does not report endianness correctly.
Here is how to reproduce:
```haskell
{-# LANGUAGE UnboxedTuples #-}
{-# LANGUAGE MagicHash #-}
{-# LANGUAGE CPP #-}
import Data.ByteString.Short.Internal
import GHC.ByteOrder
import GHC.Exts
import GHC.IO
#include "MachDeps.h"
data MBA = MBA (MutableByteArray# RealWorld)
homeEndian :: ByteOrder
#ifdef WORDS_BIGENDIAN
homeEndian = BigEndian
#else
homeEndian = LittleEndian
#endif
makeSBS :: IO ShortByteString
makeSBS = do
MBA mba# <-
IO $ \s# ->
case newByteArray# 16# s# of
(# s'#, mba# #) -> (# s'#, MBA mba# #)
IO $ \s# -> (# writeWord64Array# mba# 0# 0x6162636465666768## s#, () #)
IO $ \s# -> (# writeWord64Array# mba# 1# 0x4142434445464748## s#, () #)
IO $ \s# ->
case unsafeFreezeByteArray# mba# s# of
(# s'#, ba# #) -> (# s'#, SBS ba# #)
main :: IO ()
main = do
putStrLn $ "GHC.ByteOrder.targetByteOrder: " ++ show targetByteOrder
putStrLn $ "homeEndian: " ++ show homeEndian
makeSBS >>= print
```
Running this on your regular little endian Intel CPU will produce expected output:
```shell
$ ghc endian.hs -fforce-recomp && ./endian
[1 of 1] Compiling Main ( endian.hs, endian.o )
Linking endian ...
GHC.ByteOrder.targetByteOrder: LittleEndian
homeEndian: LittleEndian
"hgfedcbaHGFEDCBA"
```
However when run on a big endian machine we get:
```shell
root@24bf49042aa4:/# ghc endian.hs -fforce-recomp && ./endian
[1 of 1] Compiling Main ( endian.hs, endian.o )
Linking endian ...
GHC.ByteOrder.targetByteOrder: LittleEndian
homeEndian: BigEndian
"abcdefghABCDEFGH"
```
As you can see from the output of `homeEndian` and the actual byte order in `ShortByteString` the endianness is indeed big endian as expected and `targetByteOrder` reports it incorrectly.
`ghc-byteorder` package works fine because it does the right thing and imports: [`<ghcautoconf.h>`](https://github.com/haskell-hvr/ghc-byteorder/blob/46e84c74ceed19e64023a32012be55d34e545194/src/GHC/ByteOrder.hs#L16-L17)
```haskell
-- Required for WORDS_BIGENDIAN
#include <ghcautoconf.h>
```
which I assume was forgotten when migrated to GHC codebase.
Adding this line to `GHC.ByteOrder` should do a trick:
```haskell
#include "MachDeps.h"
```
In order to debug and replicate this problem I used this project: https://github.com/multiarch/qemu-user-static#getting-started that was suggested to me by Leonhard Markert:
```shell
$ docker run --rm --privileged multiarch/qemu-user-static --reset -p yes
$ docker run --rm -it s390x/ubuntu bash
root@24bf49042aa4:/# apt update && apt install ghc
```8.10.1https://gitlab.haskell.org/ghc/ghc/-/issues/20371Serious Data.Data dataTypeName breakage2021-12-17T14:14:08ZDavid FeuerSerious Data.Data dataTypeName breakage## Summary
Under GHC 8.0.2 and earlier, `Data.Data.dataTypeName` behaved as documented:
```haskell
Data.Data> dataTypeName (dataTypeOf (Just ""))
"Prelude.Maybe"
```
Under GHC 8.2.2 and 9.0.1 (and presumably the versions in between),
...## Summary
Under GHC 8.0.2 and earlier, `Data.Data.dataTypeName` behaved as documented:
```haskell
Data.Data> dataTypeName (dataTypeOf (Just ""))
"Prelude.Maybe"
```
Under GHC 8.2.2 and 9.0.1 (and presumably the versions in between),
the module name is omitted:
```haskell
Data.Data> dataTypeName (dataTypeOf (Just ""))
"Maybe"
```
Whoops!
## Environment
* GHC version used: 8.2.2, 9.0.1
Optional:
* Operating System:
* System Architecture:Matthew PickeringMatthew Pickeringhttps://gitlab.haskell.org/ghc/ghc/-/issues/20392Infinite loop for Alternative instance for Maybe2021-09-23T11:17:57ZXwtekInfinite loop for Alternative instance for Maybe## Summary
The Alternative Instance for Maybe currently uses the default method provided by Alternative class, that currently does an infinite loop.
## Steps to reproduce
In ghci, run `some $ Just 5` or `many $ Just 5`. It will run in...## Summary
The Alternative Instance for Maybe currently uses the default method provided by Alternative class, that currently does an infinite loop.
## Steps to reproduce
In ghci, run `some $ Just 5` or `many $ Just 5`. It will run into infinite loop without outputting anything.
## Expected behavior
`some $ Just 5` and `many $ Just 5` should both return the same output as `Just $ repeat 5`
Using the property of some and many, we get:
`some v = (:) <$> v <*> many v`
for v = Just a, we get
`some (Just a) = (:) <$> (Just a) <*> many (Just a)`
Plugging in another property `many v = some v <|> pure []` gets us
`some (Just a) = (:) <$> (Just a) <*> (some (Just a) <|> pure [])`
If, some (Just a) return Nothing, then
`some (Just a) = (:) <$> (Just a) <*> (pure [])`
`some (Just a) = Just [a]`
a contradiction, so some (Just a) must return a Just
`some (Just a) = (:) <$> (Just a) <*> some (Just a)`
`some (Just a) = Just (a: (fromJust $ some (Just a)))`
`some (Just a) = Just (a: (fromJust $ Just (a: (fromJust $ ...))))`
`some (Just a) = Just (a: (a: ...))`
`some (Just a) = Just $ repeat a`
Similarly, for many
`many v = some v <|> pure []`
`many v = (Just $ repeat a) <|> pure []`
`many v = (Just $ repeat a)`
## Environment
* GHC version used: 9.0.1
* Operating System: Ubuntu 20.04
* System Architecture: x64Matthew PickeringMatthew Pickeringhttps://gitlab.haskell.org/ghc/ghc/-/issues/20424real number floating point function errors (Windows only)2023-10-27T20:01:23Zdavjamreal number floating point function errors (Windows only)## Summary
Several mathematical functions (asinh, etc) on Double and Float give incorrect values (in Windows only).
## Steps to reproduce
Evaluate the following in GHCi on Windows:
````
> asinh 0
-0.0
> atanh (-0)
0.0
> asinh 1e300
N...## Summary
Several mathematical functions (asinh, etc) on Double and Float give incorrect values (in Windows only).
## Steps to reproduce
Evaluate the following in GHCi on Windows:
````
> asinh 0
-0.0
> atanh (-0)
0.0
> asinh 1e300
NaN
````
## Expected behavior
````
> asinh 0
0.0
> atanh (-0)
-0.0
> asinh 1e300
691.4686750787736
````
(This is correct, and what you get in Linux).
## Environment
* GHC version used: 8.10.7
Optional:
* Operating System: Windows
* System Architecture:
The third example here is the cause of issue #15670.
The cause seems to be errors in the coding of the functions in mingw-w64. I've created/updated bugs [#515](https://sourceforge.net/p/mingw-w64/bugs/515/) and [bug #916](https://sourceforge.net/p/mingw-w64/bugs/916/).
I've coded some fixes [here](https://github.com/davjam/HaskellNumericsTestsFixes/blob/main/MyFloatC.c).
The github repo also includes some tests (and I'm trying to develop more and may uncover additional issues). I'd like to include a fuller set of tests in both GHC and mingw-w64 (if it has CI testing).
The repo also has tests and fixes for complex number problems (that I'll raise as a separate issue since the fixes are in the GHC code).https://gitlab.haskell.org/ghc/ghc/-/issues/20425complex number function errors (all platforms)2022-02-24T09:26:29Zdavjamcomplex number function errors (all platforms)## Summary
Several mathematical functions (e.g. sqrt) give incorrect values for some complex numbers.
## Steps to reproduce
Evaluate the following in GHCi:
````
> :m +Data.Complex
> sqrt $ (-4) :+ (-0)
0.0 :+ 2.0
````
## Expected be...## Summary
Several mathematical functions (e.g. sqrt) give incorrect values for some complex numbers.
## Steps to reproduce
Evaluate the following in GHCi:
````
> :m +Data.Complex
> sqrt $ (-4) :+ (-0)
0.0 :+ 2.0
````
## Expected behavior
````
> sqrt $ (-4) :+ (-0)
0.0 :+ (-2.0)
````
## Environment
* GHC version used: 8.10.7
Optional:
* Operating System: Windows and Linux
* System Architecture:
The above is one example but there are several more errors. I've coded some fixes [here](https://github.com/davjam/HaskellNumericsTestsFixes/blob/main/MyComplex.hs), though these are work in progress.
The github repo also includes some tests (and I'm trying to develop more and may uncover additional issues). I'd like to include a fuller set of tests in GHC.
(I've also just raised #20424 for related issues on real numbers in Windows. Some of the fixes for complex numbers depend on these working correctly).9.4.1Ben GamariBen Gamarihttps://gitlab.haskell.org/ghc/ghc/-/issues/20451Ticky's ticker registration is racy2022-01-05T09:54:13ZBen GamariTicky's ticker registration is racyThe code generated for registration of ticky-ticky counters is currently racy. Specifically, `GHC.StgToCmm.Ticky.registerTickyCtr` adds its ticker to the `ticky_entry_ctrs` linked-list by performing a read-modify-write, which may race wi...The code generated for registration of ticky-ticky counters is currently racy. Specifically, `GHC.StgToCmm.Ticky.registerTickyCtr` adds its ticker to the `ticky_entry_ctrs` linked-list by performing a read-modify-write, which may race with other threads when compiling threaded code. This really ought to rather be an atomic exchange.Ben GamariBen Gamarihttps://gitlab.haskell.org/ghc/ghc/-/issues/20464TSAN failures in exitTicker2021-10-05T14:47:08ZBen GamariTSAN failures in exitTickerCurrently the non-threaded RTS produces spurious ThreadSanitizer failures of the form:
```
WARNING: ThreadSanitizer: data race (pid=118233)
Write of size 1 at 0x7f66710635f0 by main thread:
#0 exitTicker rts/posix/ticker/Pthread.c:...Currently the non-threaded RTS produces spurious ThreadSanitizer failures of the form:
```
WARNING: ThreadSanitizer: data race (pid=118233)
Write of size 1 at 0x7f66710635f0 by main thread:
#0 exitTicker rts/posix/ticker/Pthread.c:246 (libHSrts-1.0.2-ghc9.3.20211002.so+0x00000007ffc8)
#1 exitTimer rts/Timer.c:209 (libHSrts-1.0.2-ghc9.3.20211002.so+0x00000005b4f7)
#2 hs_exit_ rts/RtsStartup.c:478 (libHSrts-1.0.2-ghc9.3.20211002.so+0x00000004ccb0)
#3 shutdownHaskellAndExit rts/RtsStartup.c:640 (libHSrts-1.0.2-ghc9.3.20211002.so+0x00000004d375)
#4 hs_main rts/RtsMain.c:99 (libHSrts-1.0.2-ghc9.3.20211002.so+0x00000004c259)
#5 main <null> (ghc-pkg-9.3.20211002+0x00000047a574)
Previous read of size 1 at 0x7f66710635f0 by thread T1:
#0 itimer_thread_func rts/posix/ticker/Pthread.c:128 (libHSrts-1.0.2-ghc9.3.20211002.so+0x00000007fb83)
#1 <null> <null> (libtsan.so.0+0x000000024459)
Location is global 'exited' of size 1 at 0x7f66710635f0 (libHSrts-1.0.2-ghc9.3.20211002.so+0x0000000b35f0)
Thread T1 'ghc_ticker' (tid=118235, running) created by main thread at:
#0 pthread_create <null> (libtsan.so.0+0x000000027e9d)
#1 initTicker rts/posix/ticker/Pthread.c:202 (libHSrts-1.0.2-ghc9.3.20211002.so+0x00000007fe1b)
#2 initTimer rts/Timer.c:180 (libHSrts-1.0.2-ghc9.3.20211002.so+0x00000005b0fa)
#3 hs_init_ghc rts/RtsStartup.c:295 (libHSrts-1.0.2-ghc9.3.20211002.so+0x00000004cf98)
#4 hs_main rts/RtsMain.c:57 (libHSrts-1.0.2-ghc9.3.20211002.so+0x00000004c1eb)
#5 main <null> (ghc-pkg-9.3.20211002+0x00000047a574)
SUMMARY: ThreadSanitizer: data race rts/posix/ticker/Pthread.c:246 in exitTicker
```
This is because the non-threaded RTS compiles out all of the barrier and atomic operations defined in `rts/include/stg/SMP.h`. Given that the non-threaded RTS is now no longer single-threaded (as it may use the pthread ticker implementation) we should probably compile at least some of these as their threaded implementations.https://gitlab.haskell.org/ghc/ghc/-/issues/20529Instances become invisible across a component boundary2022-04-30T21:28:22ZparsonsmattInstances become invisible across a component boundary## Summary
Reproduction repository: https://github.com/parsonsmatt/visibility
It seems like instances which are considered `visible` in the library component are no longer considered visible when reifying them in the `test` component.
...## Summary
Reproduction repository: https://github.com/parsonsmatt/visibility
It seems like instances which are considered `visible` in the library component are no longer considered visible when reifying them in the `test` component.
The example repo essentially defines:
```haskell
module C where
class C a
module A where
import C
data A = A
instance C A
module B where
import C
import A
data B = B A
instance C B
module T where
import C
import B ()
data T = T
instance C T
```
Based on what I've read on visible type class instances, I would expect that `import T()` would bring into visibility the instances for `B` and `A` as well. This is confirmed - in the library, I can write:
```haskell
module Lib where
import C
import T ()
import Language.Haskell.TH
do
instances <- reifyInstances ''C [VarP (mkName "a")]
print instances
```
and it prints out instance declarations matching `A`, `B`, and `T`.
However, if I run the same code in the *test suite* for this package, then it only shows the instance `C T` - it only shows an instance if it was defined *in the module* that is being imported, not all the transitively imported instances.
## Steps to reproduce
Reproduction repository: https://github.com/parsonsmatt/visibility
`stack build` or `cabal build` should both work. I've tested with GHC 8.10.3, 8.10.7, and 9.0.1.
## Expected behavior
I would expect the instances to be visible just the same in a test-suite or library component.
## Environment
* GHC version used: 8.10.3, 8.10.7, 9.0.1
Optional:
* Operating System: UBuntu
* System Architecture: x86parsonsmattparsonsmatthttps://gitlab.haskell.org/ghc/ghc/-/issues/20594tf-random's documentation fails to build with GHC 9.2.1's haddock on aarch64-...2022-08-04T15:22:18Zsternitf-random's documentation fails to build with GHC 9.2.1's haddock on aarch64-linux## Summary
haddock shipped with GHC 9.2.1 fails to build `tf-random`'s documentation due to `haddock: internal error: dist/doc/html/tf-random/haddock-prologue1387-0.txt: hGetContents: invalid argument (invalid byte sequence)`.
This see...## Summary
haddock shipped with GHC 9.2.1 fails to build `tf-random`'s documentation due to `haddock: internal error: dist/doc/html/tf-random/haddock-prologue1387-0.txt: hGetContents: invalid argument (invalid byte sequence)`.
This seems to be due to some decoding problem that is architecture-specific as I've only have been able to reproduce it on `aarch64-linux`. Additionally, the issue doesn't seem to be limited to `haddock`, since also `Cabal` reports while building: `Warning: tf-random.cabal:0:0: UTF8 encoding problem at byte offset 1083`.
With this hint taken into account, it seems the Problem is decoding the “ł” in “Michał Pałka”.
<details>
<summary>Full build log</summary>
```
setupCompilerEnvironmentPhase
Build with /nix/store/z4wznwpkzr5swfzkmyi14nnj5rqhxzwn-ghc-9.2.1.
unpacking sources
unpacking source archive /nix/store/1nr84gxykdayb34wqhyhzapplwj6hj2x-tf-random-0.5.tar.gz
source root is tf-random-0.5
setting SOURCE_DATE_EPOCH to timestamp 1397051832 of file tf-random-0.5/tf-random.cabal
patching sources
compileBuildDriverPhase
setupCompileFlags: -package-db=/build/setup-package.conf.d -j4 +RTS -A64M -RTS -threaded -rtsopts
[1 of 1] Compiling Main ( Setup.hs, /build/Main.o )
Linking Setup ...
updateAutotoolsGnuConfigScriptsPhase
configuring
configureFlags: --verbose --prefix=/nix/store/m4c39knb9yw2c49xph4fdmm1xcggpp96-tf-random-0.5 --libdir=$prefix/lib/$compiler --libsubdir=$abi/$libname --docdir=/nix/store/pdia0inbjhx12hhyfpvavkmdnizxxbny-tf-random-0.5-doc/share/doc/tf-random-0.5 --with-gcc=gcc --package-db=/build/package.conf.d --ghc-options=-j4 +RTS -A64M -RTS --disable-split-objs --disable-library-profiling --disable-profiling --enable-shared --disable-coverage --enable-static --disable-executable-dynamic --enable-tests --disable-benchmarks --enable-library-vanilla --disable-library-for-ghci --ghc-option=-split-sections --extra-lib-dirs=/nix/store/iz9f5fjbk906c9j8zvr83skisy8mlbx7-ncurses-6.2/lib --extra-lib-dirs=/nix/store/wz31pppvk0ij3ykyafkw4xhp631b2i9m-libffi-3.4.2/lib --extra-lib-dirs=/nix/store/xwflzk66nkh7s45cqbjfmrc62qqncz3c-gmp-6.2.1/lib
Using Parsec parser
Warning: tf-random.cabal:0:0: UTF8 encoding problem at byte offset 1083
Configuring tf-random-0.5...
Dependency base >=4.2 && <5: using base-4.16.0.0
Dependency primitive >=0.3: using primitive-0.7.2.0
Dependency random: using random-1.2.1
Dependency time: using time-1.11.1.1
Source component graph: component lib
Configured component graph:
component tf-random-0.5-KP9k5IPcUYpGRNnHT8fvB9
include base-4.16.0.0
include primitive-0.7.2.0-26FrVImOeSRFMFxEAgiBFt
include random-1.2.1-4qyYj6P88hEL41FyrmzJfp
include time-1.11.1.1
Linked component graph:
unit tf-random-0.5-KP9k5IPcUYpGRNnHT8fvB9
include base-4.16.0.0
include primitive-0.7.2.0-26FrVImOeSRFMFxEAgiBFt
include random-1.2.1-4qyYj6P88hEL41FyrmzJfp
include time-1.11.1.1
System.Random.TF=tf-random-0.5-KP9k5IPcUYpGRNnHT8fvB9:System.Random.TF,System.Random.TF.Gen=tf-random-0.5-KP9k5IPcUYpGRNnHT8fvB9:System.Random.TF.Gen,System.Random.TF.Init=tf-random-0.5-KP9k5IPcUYpGRNnHT8fvB9:System.Random.TF.Init,System.Random.TF.Instances=tf-random-0.5-KP9k5IPcUYpGRNnHT8fvB9:System.Random.TF.Instances
Ready component graph:
definite tf-random-0.5-KP9k5IPcUYpGRNnHT8fvB9
depends base-4.16.0.0
depends primitive-0.7.2.0-26FrVImOeSRFMFxEAgiBFt
depends random-1.2.1-4qyYj6P88hEL41FyrmzJfp
depends time-1.11.1.1
Using Cabal-3.6.0.0 compiled by ghc-9.2
Using compiler: ghc-9.2.1
Using install prefix:
/nix/store/m4c39knb9yw2c49xph4fdmm1xcggpp96-tf-random-0.5
Executables installed in:
/nix/store/m4c39knb9yw2c49xph4fdmm1xcggpp96-tf-random-0.5/bin
Libraries installed in:
/nix/store/m4c39knb9yw2c49xph4fdmm1xcggpp96-tf-random-0.5/lib/ghc-9.2.1/aarch64-linux-ghc-9.2.1/tf-random-0.5-KP9k5IPcUYpGRNnHT8fvB9
Dynamic Libraries installed in:
/nix/store/m4c39knb9yw2c49xph4fdmm1xcggpp96-tf-random-0.5/lib/ghc-9.2.1/aarch64-linux-ghc-9.2.1
Private executables installed in:
/nix/store/m4c39knb9yw2c49xph4fdmm1xcggpp96-tf-random-0.5/libexec/aarch64-linux-ghc-9.2.1/tf-random-0.5
Data files installed in:
/nix/store/m4c39knb9yw2c49xph4fdmm1xcggpp96-tf-random-0.5/share/aarch64-linux-ghc-9.2.1/tf-random-0.5
Documentation installed in:
/nix/store/pdia0inbjhx12hhyfpvavkmdnizxxbny-tf-random-0.5-doc/share/doc/tf-random-0.5
Configuration files installed in:
/nix/store/m4c39knb9yw2c49xph4fdmm1xcggpp96-tf-random-0.5/etc
No alex found
Using ar found on system at:
/nix/store/10avvfvwvzj4y0z6zxij2qnz5pgqprg5-binutils-2.35.1/bin/ar
No c2hs found
No cpphs found
No doctest found
Using gcc version 9.3.0 given by user at:
/nix/store/1q1mif7h3lgxdaxg6j39hli5azikrfla-gcc-wrapper-9.3.0/bin/gcc
Using ghc version 9.2.1 found on system at:
/nix/store/z4wznwpkzr5swfzkmyi14nnj5rqhxzwn-ghc-9.2.1/bin/ghc
Using ghc-pkg version 9.2.1 found on system at:
/nix/store/z4wznwpkzr5swfzkmyi14nnj5rqhxzwn-ghc-9.2.1/bin/ghc-pkg
No ghcjs found
No ghcjs-pkg found
No greencard found
Using haddock version 2.26.0 found on system at:
/nix/store/z4wznwpkzr5swfzkmyi14nnj5rqhxzwn-ghc-9.2.1/bin/haddock
No happy found
Using haskell-suite found on system at: haskell-suite-dummy-location
Using haskell-suite-pkg found on system at: haskell-suite-pkg-dummy-location
No hmake found
Using hpc version 0.68 found on system at:
/nix/store/z4wznwpkzr5swfzkmyi14nnj5rqhxzwn-ghc-9.2.1/bin/hpc
Using hsc2hs version 0.68.8 found on system at:
/nix/store/z4wznwpkzr5swfzkmyi14nnj5rqhxzwn-ghc-9.2.1/bin/hsc2hs
Using hscolour version 1.24 found on system at:
/nix/store/cknsx4nddzjdm0g7vg9d9vpc9lvslscq-hscolour-1.24.4/bin/HsColour
No jhc found
Using ld found on system at:
/nix/store/579l1jpqmwjfghmlh9mnj6ykx06q2g38-binutils-wrapper-2.35.1/bin/ld.gold
No pkg-config found
Using runghc version 9.2.1 found on system at:
/nix/store/z4wznwpkzr5swfzkmyi14nnj5rqhxzwn-ghc-9.2.1/bin/runghc
Using strip version 2.35 found on system at:
/nix/store/10avvfvwvzj4y0z6zxij2qnz5pgqprg5-binutils-2.35.1/bin/strip
Using tar found on system at:
/nix/store/zfcd6sdfsfddhf5ybkarj4q241bsymn1-gnutar-1.34/bin/tar
No uhc found
building
Preprocessing library for tf-random-0.5..
Building library for tf-random-0.5..
[1 of 4] Compiling System.Random.TF.Gen ( src/System/Random/TF/Gen.hs, dist/build/System/Random/TF/Gen.o, dist/build/System/Random/TF/Gen.dyn_o )
[2 of 4] Compiling System.Random.TF.Init ( src/System/Random/TF/Init.hs, dist/build/System/Random/TF/Init.o, dist/build/System/Random/TF/Init.dyn_o )
src/System/Random/TF/Init.hs:94:5: warning: [-Wdeprecations]
In the use of `bitSize'
(imported from Data.Bits, but defined in GHC.Bits):
Deprecated: "Use 'bitSizeMaybe' or 'finiteBitSize' instead"
|
94 | | bitSize n > 64 = error "mkTFGen: case where size of Int > 64 not implemented"
| ^^^^^^^
[3 of 4] Compiling System.Random.TF ( src/System/Random/TF.hs, dist/build/System/Random/TF.o, dist/build/System/Random/TF.dyn_o )
[4 of 4] Compiling System.Random.TF.Instances ( src/System/Random/TF/Instances.hs, dist/build/System/Random/TF/Instances.o, dist/build/System/Random/TF/Instances.dyn_o )
running tests
Package has no test suites.
haddockPhase
Preprocessing library for tf-random-0.5..
Running Haddock on library for tf-random-0.5..
Warning: --source-* options are ignored when --hyperlinked-source is enabled.
100% ( 4 / 4) in 'System.Random.TF.Gen'
83% ( 5 / 6) in 'System.Random.TF.Init'
Missing documentation for:
Module header
src/System/Random/TF/Init.hs:94:5: warning: [-Wdeprecations]
In the use of `bitSize'
(imported from Data.Bits, but defined in GHC.Bits):
Deprecated: "Use 'bitSizeMaybe' or 'finiteBitSize' instead"
|
94 | | bitSize n > 64 = error "mkTFGen: case where size of Int > 64 not implemented"
| ^^^^^^^
100% ( 7 / 7) in 'System.Random.TF'
33% ( 1 / 3) in 'System.Random.TF.Instances'
Missing documentation for:
Random (src/System/Random/TF/Instances.hs:37)
randomEnum (src/System/Random/TF/Instances.hs:205)
haddock: internal error: dist/doc/html/tf-random/haddock-prologue1387-0.txt: hGetContents: invalid argument (invalid byte sequence)
builder for '/nix/store/jcfgav90wdc628xmnwy468dn5p57nj57-tf-random-0.5.drv' failed with exit code 1
```
</details>
## Steps to reproduce
Since this did not happen with GHC 9.2.1's release candidate, I've not investigated if this may have been caused by nixpkgs' build environment. To reproduce:
* Checkout nixpkgs at `a50888dc73b88ab344853c806ab63a3674728fc6`
* Run `nix-build -A haskell.packages.ghc921.tf-random` on `aarch64-linux`
## Expected behavior
Build `tf-random` successfully including its documentation and display no warnings about incorrect enconding.
## Environment
* GHC version used: 9.2.1
Optional:
* Operating System: NixOS
* System Architecture: aarch64-linux9.2.3Ben GamariBen Gamarihttps://gitlab.haskell.org/ghc/ghc/-/issues/20626Sub-word right-arithmetic-shifts appear to be wrong on x862023-08-02T10:17:55ZBen GamariSub-word right-arithmetic-shifts appear to be wrong on x86While validating bgamari/test-primops> in preparation for looking at #20594, I noticed that even the x86 NCG doesn't match the reference implementation. Specifically, consider this C-- program:
```c
test() {
bits64 ret;
ret = %zx...While validating bgamari/test-primops> in preparation for looking at #20594, I noticed that even the x86 NCG doesn't match the reference implementation. Specifically, consider this C-- program:
```c
test() {
bits64 ret;
ret = %zx64(%shra(242::bits8, 1));
return (ret);
}
```
I would expect this to return `(242>>1) | (1<<7) == 249`. However, when compiled with GHC 8.10.7 it returns 121, as demonstrated by this program:
```hs
{-# LANGUAGE GHCForeignImportPrim #-}
{-# LANGUAGE UnliftedFFITypes #-}
{-# LANGUAGE MagicHash #-}
module Main where
import GHC.Exts
import GHC.Ptr
import Foreign.Marshal.Alloc
foreign import prim "test" test :: Addr# -> Word#
main :: IO ()
main = do
Ptr p <- callocBytes (1*1000*1000)
print $ W# (test p)
```9.0.2Ben GamariBen Gamarihttps://gitlab.haskell.org/ghc/ghc/-/issues/20634Inconsistent treatment of signedness of Cmm literals2022-10-12T13:14:02ZBen GamariInconsistent treatment of signedness of Cmm literalsConsider these Cmm programs:
```c
testA() { return ( 0x8000000000000000::bits64 ); }
testB() { return ( -0x8000000000000000::bits64 ); }
testC() { return (%quot( 0x8000000000000000::bits64, 2)); }
testD() { return (%quot...Consider these Cmm programs:
```c
testA() { return ( 0x8000000000000000::bits64 ); }
testB() { return ( -0x8000000000000000::bits64 ); }
testC() { return (%quot( 0x8000000000000000::bits64, 2)); }
testD() { return (%quot(-0x8000000000000000::bits64, 2)); }
```
In general, one wouldn't expect that `0x8000000000000000::bits64` and `-0x8000000000000000::bits64` differ semantically, given that we assume a two's complement sign representation.
In the case of `testA` and `testB` GHC respects this expectation. However, in the case of `testC` and `testD` there is a surprising difference:
```
Program Value emitted in assembler
----------- ---------------------------
`testA` `-9223372036854775808`
`testB` `-9223372036854775808`
`testC` ` 4611686018427387904`
`testD` `-4611686018427387904`
```
That is, while we produce the correct result in `testD`, in `testC` we silently drop the sign bit. Given that this same behavior is not observed in `testA` and `testB`, I can only assume that this is some constant folding going awry.Ben GamariBen Gamarihttps://gitlab.haskell.org/ghc/ghc/-/issues/20637LLVM backend miscompilation2022-10-12T13:14:07ZBen GamariLLVM backend miscompilationThis Cmm program produces different result when compiled using the NCG and LLVM backends:
```c
test() {
return (%zx64(%lobits16(%zx32(%lobits8((%lobits16(%shl((1 :: bits32), (45 :: bits64))) ^ (1 :: bits16)))))));
}
```
The NCG return...This Cmm program produces different result when compiled using the NCG and LLVM backends:
```c
test() {
return (%zx64(%lobits16(%zx32(%lobits8((%lobits16(%shl((1 :: bits32), (45 :: bits64))) ^ (1 :: bits16)))))));
}
```
The NCG returns `1` while LLVM returns `0` with `-O0` and `0x7ff3a69bc010` with `-O1`. I believe `1` is correct.Ben GamariBen Gamarihttps://gitlab.haskell.org/ghc/ghc/-/issues/20638Miscompilation of signed load by ARMv8 NCG2022-10-12T13:14:13ZBen GamariMiscompilation of signed load by ARMv8 NCGThis Cmm program is miscompiled by the ARMv8 NCG.
```c
test(W_ buffer) {
return (%zx64(%shrl(bits16[buffer + (128 :: bits64)], (1 :: bits64))) & (64711 :: bits64));
}
```
With `-fllvm` (and under the bgamari/test-primops> interpreter...This Cmm program is miscompiled by the ARMv8 NCG.
```c
test(W_ buffer) {
return (%zx64(%shrl(bits16[buffer + (128 :: bits64)], (1 :: bits64))) & (64711 :: bits64));
}
```
With `-fllvm` (and under the bgamari/test-primops> interpreter) this evaluates to `0x40c0`. With the NCG it evaluates to `0xc0c0`.Ben GamariBen Gamarihttps://gitlab.haskell.org/ghc/ghc/-/issues/20640UTF-8 decoding doesn't work correctly on GHC 9.2.1+AArch64 NCG2022-04-01T17:27:28Zarata, mizukiUTF-8 decoding doesn't work correctly on GHC 9.2.1+AArch64 NCG## Summary
With GHC 9.2.1, `GHC.IO.Encoding.utf8` fails to decode non-ASCII text.
It happens on
* arm64-darwin / AArch64 NCG / ghc-9.2 branch
* aarch64-linux / AArch64 NCG / GHC 9.2.1
but does not happen on
* x86\_64
* arm64-darwin ...## Summary
With GHC 9.2.1, `GHC.IO.Encoding.utf8` fails to decode non-ASCII text.
It happens on
* arm64-darwin / AArch64 NCG / ghc-9.2 branch
* aarch64-linux / AArch64 NCG / GHC 9.2.1
but does not happen on
* x86\_64
* arm64-darwin / LLVM backend / GHC 8.10.7
* arm64-darwin / base library built with LLVM backend (`hadrian/build --flavour=default+llvm`) / ghc-9.2 branch
* arm64-darwin / AArch64 NCG / master branch
So I guess that a bug in AArch64 NCG whose fix is not backported to ghc-9.2 is affecting here.
## Steps to reproduce
The following program
```haskell
import GHC.Foreign
import GHC.IO.Encoding
import qualified Foreign.C.String as F
main = withCStringLen utf8 "\x1F424" $ \csl -> do
s <- F.peekCAStringLen csl
print s
s <- peekCStringLen utf8 csl
print s
```
prints
```haskell
"\240\159\144\164"
string.hs: recoverDecode: invalid argument (invalid byte sequence)
```
## Expected behavior
It should output
```haskell
"\240\159\144\164"
"\128036"
```
## Environment
* GHC version used: 9.2.1 release / ghc-9.2 branch (ac4496ceb190ab7c3e300c9f844ef4e8e4e75c32)
* Operating System: macOS
* System Architecture: AArch649.2.2Ben GamariBen Gamarihttps://gitlab.haskell.org/ghc/ghc/-/issues/20644Signed arithmetic miscompiled on AArch642022-11-08T20:19:13ZBen GamariSigned arithmetic miscompiled on AArch64Currently the AArch64 NCG miscompiles signed, sub-word arithmetic. For instance, consider this program:
```c
test(bits64 buffer) {
return (%zx64(%quot(%lobits8(%neg(bits64[buffer + (1 :: bits64)])), (2 :: bits8))));
}
```
This should ...Currently the AArch64 NCG miscompiles signed, sub-word arithmetic. For instance, consider this program:
```c
test(bits64 buffer) {
return (%zx64(%quot(%lobits8(%neg(bits64[buffer + (1 :: bits64)])), (2 :: bits8))));
}
```
This should evaluate to `-1 /[signed] 2 == 0`.
However, with %9.2.1 it produces the incorrect result of `127` via following assembler:
```asm
test:
.Lc3:
# Load W64 from `buffer`
mov x18, x22
ldr x18, [ x18, 1 ]
# Negate
neg x18, x18
# Narrow W64 -> W8
ubfm x18, x18, #0, #7
# Signed Divide by 2
mov w17, #2
sdiv w18, w18, w17
# The above division is wrong: it encodes word-sized division but w18 contains
# a (non-signed-extended) W8
ubfm x18, x18, #0, #7
mov x22, x18
ldr x18, [ x20 ]
br x18
```9.2.2Ben GamariBen Gamarihttps://gitlab.haskell.org/ghc/ghc/-/issues/20645LLVM backend miscompiles pext and pdep2022-10-12T13:14:29ZBen GamariLLVM backend miscompiles pext and pdepStrangely, the `W16` and `W8` `pexp` and `pdep` tests of bgamari/test-primops> currently fail with the LLVM backend:
For instance,
```
*Main> let e = parseExpr @W16 "narrow[W64→W16](load[W64](0::W64))"
*Main> let f = parseExpr @W16 "nar...Strangely, the `W16` and `W8` `pexp` and `pdep` tests of bgamari/test-primops> currently fail with the LLVM backend:
For instance,
```
*Main> let e = parseExpr @W16 "narrow[W64→W16](load[W64](0::W64))"
*Main> let f = parseExpr @W16 "narrow[W64→W16]((load[W64](0::W64)) ^ 1::W64)"
*Main> evalCallishOp comp pext (e,f)
2
*Main> evalCallishOp llvm pext (e,f)
0x1e
*Main> interpret e
0x100
*Main> interpret f
0x101
```
The result of this operation should be `2`.Ben GamariBen Gamarihttps://gitlab.haskell.org/ghc/ghc/-/issues/20646Broken C Calls on Darwin/AArch642021-11-10T14:35:07ZBen GamariBroken C Calls on Darwin/AArch64bgamari/test-primops> has discovered this failing C call shape on Darwin/AArch64 when using the LLVM backend (and presumably the NCG as well although the latter is currently too broken to judge):
```
C-Call correctness: FAIL (0.3...bgamari/test-primops> has discovered this failing C call shape on Darwin/AArch64 when using the LLVM backend (and presumably the NCG as well although the latter is currently too broken to judge):
```
C-Call correctness: FAIL (0.36s)
*** Failed! Falsified (after 1 test):
CCallDesc {callRet = SomeNumber @W16 0xef7c, callArgs = [SomeNumber @W8 0x90,SomeNumber @W8 0x2e,SomeNumber @W32 0xc4f525b5,SomeNumber @W16 0xfa13,SomeNumber @W32 0x3762a248,SomeNumber @W32 0xc91956ee,SomeNumber @W64 0x6d4c9d69ed69c6f6,SomeNumber @W32 0x6fc830de,SomeNumber @W32 0x20108891,SomeNumber @W16 0x65ae,SomeNumber @W64 0xd15099605cf94130,SomeNumber @W64 0xfa129274dad70ff,SomeNumber @W16 0x29ef,SomeNumber @W32 0x1a038aa5,SomeNumber @W64 0x33f45559c8ad4c8b,SomeNumber @W8 0x37,SomeNumber @W64 0x64827e4121b94909,SomeNumber @W8 0x38,SomeNumber @W32 0x88ac3077]}
[144,46,3304400309,64019,929210952,3373881070,7875842926644414198,1875390686,537954449,0,26030,15082723791219540272,28927,262220071,10735,165,3743711034358975627,55,0,61308] /= [144,46,3304400309,64019,929210952,3373881070,7875842926644414198,1875390686,537954449,26030,15082723791219540272,1126226630603010303,10735,436439717,3743711034358975627,55,7242489968968943881,56,2292985975,61308]
Use --quickcheck-replay=987633 to reproduce.
Use -p '/o0-llvm.C-Call correctness/' to rerun this test only.
```https://gitlab.haskell.org/ghc/ghc/-/issues/20659GHCi 9.2.1 Unicode input broken on macOS Arm642021-11-10T23:04:18ZDakotah LambertGHCi 9.2.1 Unicode input broken on macOS Arm64## Summary
Entering non-ASCII symbols into the GHCi readline environment on arm64 doesn't work (x86_64 is unaffected).
## Steps to reproduce
1. Enter the GHCi interpreter
2. Type or paste `print "¬"`
3. Observe that the Unicode replac...## Summary
Entering non-ASCII symbols into the GHCi readline environment on arm64 doesn't work (x86_64 is unaffected).
## Steps to reproduce
1. Enter the GHCi interpreter
2. Type or paste `print "¬"`
3. Observe that the Unicode replacement character has been inserted, but press return anyway
4. Observe the output "\65533\65533"
5. Note that `putStrLn "\172"` prints the expected character
## Expected behavior
Rather than "\65533\65533" (two instances of the Unicode replacement character), the output should be "\172" as it is on x86_64 builds. The symbol should behave as it does in the terminal outside of GHCi, being printed as itself rather than as the replacement character.
## Environment
* GHC version used: 9.2.1
Optional:
* Operating System: macOS 11.6
* System Architecture: arm649.2.2https://gitlab.haskell.org/ghc/ghc/-/issues/20745C backend handles signedness incorrectly2022-10-12T13:14:34ZBen GamariC backend handles signedness incorrectlyIn !6934 I noticed and fixed a few issues in the C backend to do with signedness:
### Unsigned operations can sometimes turn into signed operations if given signed arguments
Consider a program like
```c
test() {
bits64 ret,...In !6934 I noticed and fixed a few issues in the C backend to do with signedness:
### Unsigned operations can sometimes turn into signed operations if given signed arguments
Consider a program like
```c
test() {
bits64 ret, a, b;
a = %neg(43 :: bits64);
b = %neg(0x443c70fa3e465120 :: bits64);
ret = %modu(a, b);
return (ret);
}
```
In this case both `a` and `b` will be `StgInt`s in the generated C (since
`MO_Neg` is a signed operation). However, if we provide these as operands to `%` then we
will get *signed* modulus semantics, despite the user requesting *unsigned* semantics.
Therefore we must be careful to cast both arguments to `StgWord`; currently we do not do this.
### Sub-word signed results must be zero-extended
Consider a program like (from #20634):
```c
test() {
bits64 ret;
bits8 a,b;
a = 0xe1 :: bits8; // == -31 signed
b = %quot(a, 3::bits8); // == -10 signed
ret = %zx64(a); // == 0xf6 unsigned
return (ret);
}
```
This program should return `0xf6 == 246`. However, we need to be very careful
with when dealing with the result of the %quot. For instance, one might be
tempted produce code like:
```c
StgWord8 a = 0xe1U;
StgInt8 b = (StgInt8) a / (StgInt8) 0x3U;
StgWord ret = (W_) b;
```
However, this would be wrong; by widening `b` directly from `StgInt8` to
`StgWord` we will get sign-extension semantics: rather than 0xf6 we will get
`0xfffffffffffffff6`. To avoid this we must first cast `b` back to `StgWord8`,
ensuring that we get zero-extension semantics when we widen up to `StgWord`.Ben GamariBen Gamarihttps://gitlab.haskell.org/ghc/ghc/-/issues/20757GHC.SysTools.BaseDir.findToolDir "/" on Windows results in infinite loop2021-12-07T14:16:41ZJakob BrünkerGHC.SysTools.BaseDir.findToolDir "/" on Windows results in infinite loop## Summary
Calling [`GHC.SysTools.BaseDir.findToolDir "/"`](https://gitlab.haskell.org/ghc/ghc/-/blob/master/compiler/GHC/SysTools/BaseDir.hs#L182-201) on Windows results in
```
*** Exception: ghc-9.2.1.exe: could not detect mingw toolc...## Summary
Calling [`GHC.SysTools.BaseDir.findToolDir "/"`](https://gitlab.haskell.org/ghc/ghc/-/blob/master/compiler/GHC/SysTools/BaseDir.hs#L182-201) on Windows results in
```
*** Exception: ghc-9.2.1.exe: could not detect mingw toolchain in the following paths:
```
when run in GHCi, followed by GHCi hanging, and in `<<loop>>` when compiled.
This bit me when I still had `initSettings "/"` for testing purposes but forgot about it - the non-terminating error-message wasn't very helpful in reminding me.
## Expected behavior
Something along the lines of
```
*** Exception: ghc-9.2.1.exe: could not detect mingw toolchain in the following paths: ["/mingw", "/../mingw", "/../../mingw", "/../../../mingw"]
```
## Environment
* GHC version used: 9.2.1
* Operating System: Windows 10
* System Architecture: x86_64https://gitlab.haskell.org/ghc/ghc/-/issues/20836Stack overflow / OOM with UndecidableSuperClasses in 9.22023-05-31T16:35:22ZBrandon ChinnStack overflow / OOM with UndecidableSuperClasses in 9.2## Summary
Adding a recursive constraint to a typeclass on an associated type family compiles fine and runs fine in GHC < 9.2, but causes stack overflow or memory issues in GHC 9.2 (depending on optimization).
Original reddit discussio...## Summary
Adding a recursive constraint to a typeclass on an associated type family compiles fine and runs fine in GHC < 9.2, but causes stack overflow or memory issues in GHC 9.2 (depending on optimization).
Original reddit discussion: https://www.reddit.com/r/haskell/comments/riaw00/stack_overflow_oom_with_undecidablesuperclasses/
## Steps to reproduce
```hs
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE UndecidableSuperClasses #-}
import Data.Kind (Type)
class (Monad m, MonadFoo (FooM m)) => MonadFoo m where
type FooM m :: Type -> Type
runFoo :: FooM m a -> m a
newtype MyMonad m a = MyMonad { runMyMonad :: m a }
deriving (Functor, Applicative, Monad)
instance Monad m => MonadFoo (MyMonad m) where
type FooM (MyMonad m) = MyMonad m
runFoo = id
main :: IO ()
main = runMyMonad foo
foo :: MonadFoo m => m ()
foo = runFoo $ return ()
```
`ghc Foo.hs && ./Foo` works with GHC 9.0.1, but not GHC 9.2.1. The GHC 9.2 change to make dicts strict by default is probably the cause of this, which makes me think there's a regression with GHC 9.2 and `UndecidableSuperClasses`, since it seems like any recursive superclass definitions would cause infinite loops with strict dicts.
## Expected behavior
I would expect this to compile and run fine across all GHC versions supporting `UndecidableSuperClasses`.
## Environment
* GHC version used:
Optional:
* Operating System:
* System Architecture:9.2.7https://gitlab.haskell.org/ghc/ghc/-/issues/20982Control-y (yank) in GHCI acts like Control-z (suspend) on Mac2023-01-13T04:42:28ZSimon MichaelControl-y (yank) in GHCI acts like Control-z (suspend) on Mac## Summary
Control-y (yank) in GHCI acts like Control-z (suspend) on Mac, exiting to the shell.
## Steps to reproduce
~$ ghci
GHCi, version 8.10.7: https://www.haskell.org/ghc/ :? for help
Loaded package environment from ...## Summary
Control-y (yank) in GHCI acts like Control-z (suspend) on Mac, exiting to the shell.
## Steps to reproduce
~$ ghci
GHCi, version 8.10.7: https://www.haskell.org/ghc/ :? for help
Loaded package environment from /Users/simon/.ghc/aarch64-darwin-8.10.7/environments/default
Prelude>
<press Control-y>
[1]+ Stopped ghci
~$
## Expected behavior
It should do nothing (or if I had previously "killed" some text with Control-k, it should paste that text). It should not suspend the process. Ie, it should do the normal readline yank operation, as it does at a shell prompt.
## Environment
Tested with GHC 8.10.7, 9.0.2 and 9.2.1 in Terminal and iTerm2 on Mac OS 12.1 (but I have been seeing this forever). It does not happen on Linux.https://gitlab.haskell.org/ghc/ghc/-/issues/20994Generic representation for lists reports incorrect fixity2023-04-09T15:41:35ZDavid FeuerGeneric representation for lists reports incorrect fixity## Summary
The `Metadata` reported for the list cons constructor `(:)` get its fixity wrong.
## Steps to reproduce
```
import GHC.Generics as G
ghci> :kind! G.Rep [Int]
G.Rep [Int] :: * -> *
= G.M1
D
('MetaData "[]" "GHC.Types...## Summary
The `Metadata` reported for the list cons constructor `(:)` get its fixity wrong.
## Steps to reproduce
```
import GHC.Generics as G
ghci> :kind! G.Rep [Int]
G.Rep [Int] :: * -> *
= G.M1
D
('MetaData "[]" "GHC.Types" "ghc-prim" 'False)
(G.M1 C ('MetaCons "[]" 'PrefixI 'False) G.U1
G.:+: G.M1
C
('MetaCons ":" ('InfixI 'LeftAssociative 9) 'False)
(....
```
## Expected behavior
I expect the constructor metadata to be
```haskell
('MetaCons ":" ('InfixI 'RightAssociative 5) 'False)
```
That is, it should be *right* associative, with binding strength 5, not *left* associative with binding strength 9.
A pretty-printer isn't likely to use this info (since it will likely have special treatment for lists). A generic parser might do so, however, using something like `listSyntax <|> genericParse`.
## Environment
* GHC version used: 9.2
Optional:
* Operating System:
* System Architecture:9.4.1https://gitlab.haskell.org/ghc/ghc/-/issues/21082rts stats show negative productivity2022-05-09T08:14:56ZDouglas Wilsondouglas@well-typed.comrts stats show negative productivityThe following program and options show the issue. I have reproduced this on head.
```
{-
ghc -O2 -package async Main.hs -rtsopts -threaded
./Main +RTS -N8 -s -qn1
Productivity -195.4% of total user, 25.3% of total elapsed
-}
import ...The following program and options show the issue. I have reproduced this on head.
```
{-
ghc -O2 -package async Main.hs -rtsopts -threaded
./Main +RTS -N8 -s -qn1
Productivity -195.4% of total user, 25.3% of total elapsed
-}
import Control.Concurrent.Async
import Control.Monad (replicateM, forM)
import Data.List (transpose)
main = do
as <- replicateM 10 $ async $ do
let w = 5000
m = replicate w $ replicate w ()
return $! m == transpose m
print =<< forM as wait
```9.4.1Matthew PickeringMatthew Pickeringhttps://gitlab.haskell.org/ghc/ghc/-/issues/21141Nondeterministic segfault on simple hspec program with GHC 9.0 only2022-07-12T13:55:43ZRyan ScottNondeterministic segfault on simple hspec program with GHC 9.0 only_(Originally reported at https://github.com/ekmett/reflection/issues/51.)_
The [`reflection-2.1.6`](https://hackage.haskell.org/package/reflection-2.1.6) test suite nondeterministically segfaults on Linux and macOS when compiled with GH..._(Originally reported at https://github.com/ekmett/reflection/issues/51.)_
The [`reflection-2.1.6`](https://hackage.haskell.org/package/reflection-2.1.6) test suite nondeterministically segfaults on Linux and macOS when compiled with GHC 9.0.1 or 9.0.2. The furthest I've managed to minimize the issue is:
```hs
{-# LANGUAGE PackageImports #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Main (main) where
import Control.Exception (ArithException(..), evaluate)
import Numeric.Natural (Natural)
import "hspec" Test.Hspec
import "hspec" Test.Hspec.QuickCheck
import "QuickCheck" Test.QuickCheck (Negative(..), NonNegative(..))
main :: IO ()
main = hspec spec
spec :: Spec
spec =
describe "A" $ do
describe "B" $ do
prop "identity" $
\(NonNegative (i :: Integer)) -> i `shouldBe` i
prop "should throw an Underflow exception on negative inputs" $
\(Negative (i :: Integer)) ->
evaluate (fromInteger i :: Natural) `shouldThrow` (== Underflow)
```
With GHC 8.10.7 or 9.2.1, this works as expected:
```
$ ghc-8.10.7 Bug.hs && ./Bug
Loaded package environment from /home/ryanglscott/Documents/Hacking/Haskell/ci-maintenance/checkout/ekmett/reflection/.ghc.environment.x86_64-linux-8.10.7
[1 of 1] Compiling Main ( Bug.hs, Bug.o )
Linking Bug ...
A
B
identity [✔]
+++ OK, passed 100 tests.
should throw an Underflow exception on negative inputs [✔]
+++ OK, passed 100 tests.
Finished in 0.0009 seconds
2 examples, 0 failures
$ ghc-9.2.1 Bug.hs && ./Bug
Loaded package environment from /home/ryanglscott/Documents/Hacking/Haskell/ci-maintenance/checkout/ekmett/reflection/.ghc.environment.x86_64-linux-9.2.1
[1 of 1] Compiling Main ( Bug.hs, Bug.o )
Linking Bug ...
A
B
identity [✔]
+++ OK, passed 100 tests.
should throw an Underflow exception on negative inputs [✔]
+++ OK, passed 100 tests.
Finished in 0.0013 seconds
2 examples, 0 failures
```
With GHC 9.0.2, however, this can segfault:
```
$ ghc-9.0.2 Bug.hs && ./Bug
Loaded package environment from /home/ryanglscott/Documents/Hacking/Haskell/ci-maintenance/checkout/ekmett/reflection/.ghc.environment.x86_64-linux-9.0.2
[1 of 1] Compiling Main ( Bug.hs, Bug.o )
Linking Bug ...
A
B
identity [✔]
+++ OK, passed 100 tests.
should throw an Underflow exception on negative inputs [ ]Segmentation fault (core dumped)
```
This is somewhat nondeterministic. In situations where it doesn't segfault, an incorrect runtime result will be observed:
```
$ ./Bug
A
B
identity [✔]
+++ OK, passed 100 tests.
should throw an Underflow exception on negative inputs [✘]
Failures:
Bug.hs:22:47:
1) A.B should throw an Underflow exception on negative inputs
Falsifiable (after 54 tests and 2 shrinks):
Negative {getNegative = -1}
did not get expected exception: ArithException
To rerun use: --match "/A/B/should throw an Underflow exception on negative inputs/"
Randomized with seed 1065015581
Finished in 0.0028 seconds
2 examples, 1 failure
```
This example proves remarkably resistant to minimization, as attempting to delete code in various places seemingly makes the bug disappear.9.0.3Ben GamariBen Gamarihttps://gitlab.haskell.org/ghc/ghc/-/issues/21229Inlining DFuns leads to an unsound interaction with Specialise2023-09-13T12:07:03ZSebastian GrafInlining DFuns leads to an unsound interaction with Specialise!7599 unveiled a bug in the Specialiser.
* See also #21328
* Test is in `simplCore/should_run/T21229`
Back to the Specialiser. Consider
```hs
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE AllowA...!7599 unveiled a bug in the Specialiser.
* See also #21328
* Test is in `simplCore/should_run/T21229`
Back to the Specialiser. Consider
```hs
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE AllowAmbiguousTypes #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE KindSignatures #-}
data B = T | F deriving Show
class Sing (b :: B) where sing :: B
instance Sing 'T where sing = T
instance Sing 'F where sing = F
f :: forall a. Sing a => Int -> (Int -> B -> B) -> B
f 0 g = g 0 (sing @a)
f n g = f @a (n-1) g
h :: forall a. Sing a => Int -> (Int -> B -> B) -> B
h = case sing @a of
T -> f @'T
F -> f @a
{-# NOINLINE h #-}
main = print $ h @'T 0 (\ _ a -> a)
```
With -O0, this prints `T`, as expected, because `h` will ultimately call its supplied argument once with `T`.
But with -O, I get `F`. Why is that? The reason is we ultimately get the following specialisation for the second call to `f`:
```
RULES: "SPEC f @a"
forall (@(a_aXu :: B)) ($dSing_s1OW :: Sing a_aXu).
f @a_aXu $dSing_s1OW
= $sf_s1OX @a_aXu]
```
and this specialisation (for when `$dSing_s1OW` is `F`) somehow also applies at `f @'T`.
FTR, here is the output of the `pprTrace "spec_call"` in Specialise:
```
spec_call
call info: CI{SpecType a_aXu
SpecDict F `cast` (Sym (N:Sing[0] <a_aXu>_N) :: B ~R# Sing a_aXu)}
useful: True
rule_bndrs: [a_aXu, $dSing_s1OW]
lhs_args: [TYPE: a_aXu, $dSing_s1OW]
spec_bndrs: [a_aXu]
spec_args: [TYPE: a_aXu,
F `cast` (Sym (N:Sing[0] <a_aXu>_N) :: B ~R# Sing a_aXu)]
dx_binds: []
rhs_env2: <InScope = {main g_aC8 a_aXu $cshowsPrec_aY5 $cshow_aYd
$cshowList_aYl $krep_aZ1 $krep_aZ2 $krep_aZ3 $krep_aZ4 $krep_aZ5
$krep_aZ6 ds_dZX main $fShowB $fSingF F $fSingT $tc'C:Sing
$trModule $tc'F $tc'T $tcB $tcSing f h main_s19F main_s19G
main_s1OF $trModule_s1OG $trModule_s1OH $trModule_s1OI
$trModule_s1OJ $krep_s1OK $tcB_s1OL $tcB_s1OM $tc'T_s1ON $tc'T_s1OO
$tc'F_s1OP $tc'F_s1OQ $tcSing_s1OR $tcSing_s1OS $krep_s1OT
$tc'C:Sing_s1OU $tc'C:Sing_s1OV}
IdSubst = [aKV :-> F
`cast` (Sym (N:Sing[0] <a_aXu>_N) :: B ~R# Sing a_aXu)]
TvSubst = [aKU :-> a_aXu]
CvSubst = []>
[]
```
How did it come to this?! For that we have to look at the Core of `h` that Specialise sees:
```
h = \ (@(a_aWY :: B))
($dSing_aWZ :: Sing a_aWY)
(eta_B0 :: Int)
(eta_B1 :: Int -> B -> B) ->
case $dSing_aWZ
`cast` (Main.N:Sing[0] <a_aWY>_N :: Sing a_aWY ~R# B)
of {
T ->
f @'T
(Main.T `cast` (Sym (Main.N:Sing[0] <'T>_N) :: B ~R# Sing 'T))
eta_B0
eta_B1;
F ->
f @a_aWY
(Main.F
`cast` (Sym (Main.N:Sing[0] <a_aWY>_N) :: B ~R# Sing a_aWY))
eta_B0
eta_B1
}
```
Note the second call to `f`. The type argument `a_aWY` is passed, as well as `Main.F` as the dictionary. That's strange! We should know *statically* that `a_aWY` must be `F`. (In fact, ``Main.F `cast` (Sym (Main.N:Sing[0] <a_aWY>_N) :: B ~R# Sing a_aWY)`` is unsound if `a_aWY` is instantiated to `T`, which would perhaps happen if we floated that expression out of the `F` case. I guess it doesn't matter much, at least not to this ticket.)
How did we get this code? After desugaring, we still have
```
h = \ (@(a_aXu :: B)) ($dSing_aXv :: Sing a_aXu) ->
case sing @a_aXu $dSing_aXv of {
T -> f @'T Main.$fSingT;
F -> f @a_aXu $dSing_aXv
}
```
But then gentle simplification inlines `sing` and sees that `$dSing_aXv` is `F` in the `F` case, performs a binder swap and successively inlines `F` (at least that's what I believe the Simplifier does).
Then the Specialiser can't connect `F` to the arguments `$dSing_aXv` or the type arg `a` and somehow bogs up. I suspect this happens in `specHeader`, but actually I'm not completely sure.
I couldn't reproduce with GHC 9.2 and any prior release. I see that we get the same Core pre-Specialise, but it is handled soundly there and we only get a specialisation for `T`. So perhaps we want to fix this before 9.4.9.4.1https://gitlab.haskell.org/ghc/ghc/-/issues/21240haddock: ASSERTION FAILED: file rts/Stats.c, line 1413 , with --flavour=perf+...2022-03-22T15:41:29Zjwaldmannhaddock: ASSERTION FAILED: file rts/Stats.c, line 1413 , with --flavour=perf+ticky_ghcWhen I build like this
```
time ./hadrian/build -o_build_ticky -j binary-dist --flavour=perf+ticky_ghc
real 52m28.764s ...When I build like this
```
time ./hadrian/build -o_build_ticky -j binary-dist --flavour=perf+ticky_ghc
real 52m28.764s
user 211m32.191s
sys 10m13.623s
```
it's dog slow (with most of the extra time spent in haddock?) and I get lots of
```
...
haddock: ASSERTION FAILED: file rts/Stats.c, line 1413
haddock: ASSERTION FAILED: file rts/Stats.c, line 1413
| Create directory _build_ticky/stage1/haddock-timing-files | Create directory _build_ticky/stage1/haddock-timing-files
| Run Haddock BuildPackage: _build_ticky/stage1/libraries/libiserv/build/GHCi/Utils.hs (and 1 more) => _build_ticky/docs/html/libr
aries/libiserv/libiserv.haddock
| Run Haddock BuildPackage: compiler/GHC.hs (and 616 more) => _build_ticky/docs/html/libraries/ghc/ghc.haddock
| Create directory _build_ticky/stage1/haddock-timing-files
| Run Haddock BuildPackage: libraries/Cabal/Cabal-syntax/src/Distribution/Backpack.hs (and 136 more) => _build_ticky/docs/html/lib
raries/Cabal-syntax/Cabal-syntax.haddock
haddock: ASSERTION FAILED: file rts/Stats.c, line 1413
...
```
For reference, a normal build of master:
```
time ./hadrian/build -j binary-dist
real 25m44.764s
user 120m18.564s
sys 8m44.086s
```
(the last 5 min of both are spent in `xz` #20614 but that does not matter here)https://gitlab.haskell.org/ghc/ghc/-/issues/21251Compact regions with sharing can lose pointer tags.2022-03-20T03:26:06ZAndreas KlebingerCompact regions with sharing can lose pointer tags.This caused https://gitlab.haskell.org/ghc/ghc/-/issues/21189
This issue is as follows. We create a compact region with some values.
We add a constructor with strict fields, where the fields reference values *already* in the compact re...This caused https://gitlab.haskell.org/ghc/ghc/-/issues/21189
This issue is as follows. We create a compact region with some values.
We add a constructor with strict fields, where the fields reference values *already* in the compact region.
This (eventually) results in a call to `stg_compactAddWorkerzh` in order to compact the closures the constructor fields point to, with this particular snippet being executed.
```
// Everything else we should copy and evaluate the components:
case
CONSTR,
CONSTR_1_0,
CONSTR_2_0,
CONSTR_1_1: {
(should) = ccall shouldCompact(compact "ptr", p "ptr");
if (should == SHOULDCOMPACT_IN_CNF) { P_[pp] = p; return(); }
```
pp is the address to store the result in. `p` is the *untagged* pointer. The fix is simple. Use `tag | p` instead of `p` (as this code already does in other places!).
I will put up a patch shortly.
This caused https://gitlab.haskell.org/ghc/ghc/-/issues/211899.4.1https://gitlab.haskell.org/ghc/ghc/-/issues/21279Plugin installed hooks are largely ignored2023-05-05T23:14:27ZAaron AllenPlugin installed hooks are largely ignored## Summary
If a compiler plugin installs hooks, for example on compiler phases or the logger action, they do not get called as expected. This bug was introduced in GHC v9.2 in interactive mode but also occurs for make mode in other vers...## Summary
If a compiler plugin installs hooks, for example on compiler phases or the logger action, they do not get called as expected. This bug was introduced in GHC v9.2 in interactive mode but also occurs for make mode in other versions (not sure when the bug was introduced in make mode but it is present as early as 8.10.7).
## Steps to reproduce
Write a plugin that modifies the Logger:
```haskell
plugin :: Plugin
plugin = defaultPlugin
{ driverPlugin = \_ hscEnv -> do
pure hscEnv
{ hsc_logger =
pushLogHook logHook $ hsc_logger hscEnv
}
}
logHook :: LogAction -> LogAction
logHook action dynFlags warnReason sev srcSpan msgDoc =
trace "Log hook called" $! action dynFlags warnReason sev srcSpan msgDoc
```
When compiling with this plugin, the log hook is invoked for warning messages but not error messages.
For the interactive mode case, I have determined that this occurs because when the plugins are first initialized (in `setInteractiveDynFlags`), the loaded plugins are placed in the interactive context but do not end up in the `HscEnv`. This results in the plugins not being present at key points surrounding the loading of modules. The fix for this seems simple enough:
`setInteractiveDynFlags` in `compiler/GHC.hs`:
```haskell
-- Update both plugins cache and DynFlags in the interactive context.
return $ plugin_env -- use plugin_env here instead of hsc_env0
{ hsc_IC = ic0
{ ic_plugins = hsc_plugins plugin_env
, ic_dflags = hsc_dflags plugin_env
}
}
```
GHC 9.0.x does not discard the loaded plugins in this way and the bug seems to have been a side effect of moving the loaded plugins from `DynFlags` to `HscEnv`.
Similarly for phase hooks, the hook is not called at all in GHCi (and only for certain phases in make mode). I suspect the cause is the same as in the logger hook example.
I have not yet investigated why this happens for compilation in make mode (my current focus is plugins intended to be used with GHCi) but I suspect it's because plugins are simply not being initialized early enough.
## Expected behavior
The log hook should be invoked for all messages. Phase hooks should be called for all phases.
## Environment
* GHC version used: 9.2.x, head9.6.1Matthew PickeringMatthew Pickeringhttps://gitlab.haskell.org/ghc/ghc/-/issues/21336File flush failures during program deinitialization aren't indicated2024-03-21T17:37:33ZBrandon S. Allberyallbery.b@gmail.comFile flush failures during program deinitialization aren't indicated## Summary
If a flush/close of a `Handle` fails during RTS deinitialization, there is no indication of a failure. Even if `stderr` has already been closed, at minimum the exit status can be set to indicate a failure.
## Steps to reprod...## Summary
If a flush/close of a `Handle` fails during RTS deinitialization, there is no indication of a failure. Even if `stderr` has already been closed, at minimum the exit status can be set to indicate a failure.
## Steps to reproduce
The program
```
main = putStrLn "Hello, world!"
```
invoked as
```
./hello >/dev/full
```
will correctly report
```
<stdout>: commitBuffer: resource exhausted (No space left on device)
```
if run from `ghci` or `runghc`, which default `stdout` to `LineBuffering`. In a compiled program, `stdout` is set to `BlockBuffering Nothing` and the final `hFlush` is done by the RTS at a time when no exceptions can be thrown and `stderr` may already be closed, so nothing is reported and the program exits with status 0 (no error).
I suspect the same thing may happen with a `Handle` that is garbage collected, since it may be unsafe to throw an exception at that point.
## Expected behavior
Preferably report the same exception as with `ghci` or `runghc`, but at minimum report a non-zero exit status.
## Environment
* GHC version used: 8.10.7 and 9.2.1
Optional:
* Operating System: Linux (Ubuntu 20.04)
* System Architecture: x86_64https://gitlab.haskell.org/ghc/ghc/-/issues/21415`mkTick` can cause core lint errors by separating functions from type arguments.2022-12-05T11:53:06ZAndreas Klebinger`mkTick` can cause core lint errors by separating functions from type arguments.We start with
```
reallyUnsafePtrEquality
= \ (@a_akM) ->
(reallyUnsafePtrEquality#) @'Lifted @'Lifted @a_akM @a_akM
```
We call `mkTick scc e` on the expression `(reallyUnsafePtrEquality#) @'Lifted @'Lifted @a_akM @a_akM`
...We start with
```
reallyUnsafePtrEquality
= \ (@a_akM) ->
(reallyUnsafePtrEquality#) @'Lifted @'Lifted @a_akM @a_akM
```
We call `mkTick scc e` on the expression `(reallyUnsafePtrEquality#) @'Lifted @'Lifted @a_akM @a_akM`
This floats the scc tick in between the type applications giving us this lint error/result:
```
*** Core Lint errors : in result of Add late core cost-centres ***
libraries/ghc-prim/GHC/Prim/PtrEq.hs:71:1: warning:
Cannot eta expand ‘reallyUnsafePtrEquality#’
The following types do not have a fixed runtime representation:
• a_11 :: TYPE ('BoxedRep l_1c)
• b_12 :: TYPE ('BoxedRep k_1b)
In the RHS of reallyUnsafePtrEquality :: forall a. a -> a -> Int#
In the body of lambda with binder a_akM :: *
Substitution: [TCvSubst
In scope: InScope {a_akM}
Type env: [akM :-> a_akM]
Co env: []]
*** Offending Program ***
reallyUnsafePtrEquality :: forall a. a -> a -> Int#
[LclIdX,
Arity=2,
Str=<L><L>,
Unf=Unf{Src=<vanilla>, TopLvl=True, Value=True, ConLike=True,
WorkFree=True, Expandable=True,
Guidance=ALWAYS_IF(arity=0,unsat_ok=True,boring_ok=True)}]
reallyUnsafePtrEquality
= \ (@a_akM) ->
(src<libraries/ghc-prim/GHC/Prim/PtrEq.hs:72:1-50>
tick<reallyUnsafePtrEquality> reallyUnsafePtrEquality#)
@'Lifted @'Lifted @a_akM @a_akM
```
I think the program *might* be fine in the end. So it's not clear to me if mkTick should be changed or how we lint such expressions.Andreas KlebingerAndreas Klebingerhttps://gitlab.haskell.org/ghc/ghc/-/issues/21429Cost centres seem to cause invalid demand analysis results.2022-05-03T09:29:28ZAndreas KlebingerCost centres seem to cause invalid demand analysis results.With the lateCC pass we now add cost centres in some places where we didn't before and this seems to cause issues with demand analysis/core lint.
We simplify this function (taken from after float out)
```
-- RHS size: {terms: 5, types:...With the lateCC pass we now add cost centres in some places where we didn't before and this seems to cause issues with demand analysis/core lint.
We simplify this function (taken from after float out)
```
-- RHS size: {terms: 5, types: 4, coercions: 8, joins: 0/0}
fail_s9my :: (# #) -> IO ExitCode
[LclId, Arity=2, Str=<L><L>b, Cpr=b]
fail_s9my
= (\ _ [Occ=Dead, OS=OneShot]
(eta_B0 :: ghc-prim:GHC.Prim.State# ghc-prim:GHC.Prim.RealWorld) ->
((GHC.Base.failIO @ExitCode lvl_s9mw)
`cast` (ghc-prim:GHC.Types.N:IO[0] <ExitCode>_R
:: IO ExitCode
~R# (ghc-prim:GHC.Prim.State# ghc-prim:GHC.Prim.RealWorld
-> (# ghc-prim:GHC.Prim.State# ghc-prim:GHC.Prim.RealWorld,
ExitCode #))))
eta_B0)
`cast` (Sym (<(# #)>_R
%<'Many>_N ->_R ghc-prim:GHC.Types.N:IO[0] <ExitCode>_R)
:: ((# #)
-> ghc-prim:GHC.Prim.State# ghc-prim:GHC.Prim.RealWorld
-> (# ghc-prim:GHC.Prim.State# ghc-prim:GHC.Prim.RealWorld,
ExitCode #))
~R# ((# #) -> IO ExitCode))
-- RHS size: {terms: 2, types: 0, coercions: 0, joins: 0/0}
lvl_s9mz :: IO ExitCode
[LclId, Str=b, Cpr=b]
lvl_s9mz = scc<bindIO> scc<bindIO> fail_s9my ghc-prim:GHC.Prim.(##)
```
into this one (after one iteration of the simplifier)
```
lvl_s9Jy :: State# RealWorld -> (# State# RealWorld, ExitCode #)
[LclId,
Arity=1,
Str=b,
Cpr=b,
Unf=Unf{Src=<vanilla>, TopLvl=True, Value=True, ConLike=True,
WorkFree=True, Expandable=True,
Guidance=ALWAYS_IF(arity=1,unsat_ok=True,boring_ok=True)}]
lvl_s9Jy
= \ (eta_B0 :: State# RealWorld) ->
scc<bindIO>
scc<bindIO>
((failIO @ExitCode (scc<bindIO> scc<bindIO> build @Char lvl_s9mv))
`cast` (N:IO[0] <ExitCode>_R
:: IO ExitCode
~R# (State# RealWorld -> (# State# RealWorld, ExitCode #))))
eta_B0
```
But the later one results in this core lint error:
```
*** Core Linted result of Simplifier:
*** Core Lint errors : in result of Simplifier ***
<no location info>: warning:
idArity 1 exceeds arity imposed by the strictness signature b: lvl_s9Jw
In the RHS of lvl_s9Jw :: State# RealWorld
-> (# State# RealWorld, ExitCode #)
Substitution: [TCvSubst
In scope: InScope {}
Type env: []
Co env: []]
*** Offending Program ***
```
The core issue seems to be that we infer `Str=b` for
```
-- RHS size: {terms: 2, types: 0, coercions: 0, joins: 0/0}
lvl_s9mz :: IO ExitCode
[LclId, Str=b, Cpr=b]
lvl_s9mz = scc<bindIO> scc<bindIO> fail_s9my ghc-prim:GHC.Prim.(##)
```
If we expand IO/unwrap the IO newtype this function is of type:
`State# RealWorld -> (# State# RealWorld, ExitCode #)` so I don't think this should get a Str of `b` as we have to provide the RealWorld argument for it to bottom out.
I assume the cost centre annotations on the RHS somehow interfere with demand analysis in this case.
@sgraf812 Maybe you have an idea?Andreas KlebingerAndreas Klebingerhttps://gitlab.haskell.org/ghc/ghc/-/issues/21465128-bit Callee-saved registers (Windows x64) are not saved and restored corre...2022-05-30T17:12:27ZThomas Dinsdale-Young128-bit Callee-saved registers (Windows x64) are not saved and restored correctly## Summary
The Windows x64 calling convention requires that the 128-bit registers XMM6-XMM15 be [saved (and restored) by the callee](https://docs.microsoft.com/en-us/cpp/build/x64-calling-convention?view=msvc-170#callercallee-saved-regi...## Summary
The Windows x64 calling convention requires that the 128-bit registers XMM6-XMM15 be [saved (and restored) by the callee](https://docs.microsoft.com/en-us/cpp/build/x64-calling-convention?view=msvc-170#callercallee-saved-registers).
`StgRunIsImplementedInAssembler`, which handles this in the runtime, does not correctly save and restore these registers, as it uses `movq` to do so, treating them as 64-bits only.
Consequently, when the registers are restored, the high-order 64-bits are zeroed.
Instead, `movaps` should probably be used, and 16 bytes reserved for each XMM register.
The consequence of this is that FFI calls to Haskell code on Windows may violate the calling convention and lead to undefined behaviour.
## Steps to reproduce
The attached files can be compiled on Windows with `ghc Main.hs reg.c`.
[Main.hs](/uploads/625555a8de865f7114397d3d81823ef6/Main.hs)
[reg.c](/uploads/1646814458605a7f87cde873b7dbd13a/reg.c)
The Haskell main function invokes a C function `test_c`, which uses inline assembly to set a value to the XMM6 register, invoke a Haskell function `helper`, and then read out the resulting value of the XMM6 register, comparing each byte to the expected (original) value.
The output of executing `Main.exe` is:
```
This is the helper function
0: 01 01
1: 02 02
2: 03 03
3: 04 04
4: 05 05
5: 06 06
6: 07 07
7: 08 08
8: 09 00
9: 0a 00
10: 0b 00
11: 0c 00
12: 0d 00
13: 0e 00
14: 0f 00
15: 10 00
Done.
```
This indicates that the lower-order 8 bytes of the register are correctly restored after the call to `helper`, but the high-order 8 bytes are not.
This is consistent with the use of `movq` instead of `movaps` (or `movups`).
## Expected behavior
The expected output is:
```
This is the helper function
0: 01 01
1: 02 02
2: 03 03
3: 04 04
4: 05 05
5: 06 06
6: 07 07
7: 08 08
8: 09 09
9: 0a 0a
10: 0b 0b
11: 0c 0c
12: 0d 0d
13: 0e 0e
14: 0f 0f
15: 10 10
Done.
```
## Environment
* GHC version used: 9.0.2, 8.10.2
Optional:
* Operating System: Windows 8.1
* System Architecture: x86-64Ben GamariBen Gamarihttps://gitlab.haskell.org/ghc/ghc/-/issues/21575withDict produces incorrect runtime results with optimization enabled2023-08-11T07:39:14ZRyan ScottwithDict produces incorrect runtime results with optimization enabledAfter attempting to change the `reflection` library to use `withDict` instead of `unsafeCoerce` (see #21568 for the motivation) using GHC 9.4.1-alpha1, `reflection`'s test suite started to error out. Here is a minimized example of the er...After attempting to change the `reflection` library to use `withDict` instead of `unsafeCoerce` (see #21568 for the motivation) using GHC 9.4.1-alpha1, `reflection`'s test suite started to error out. Here is a minimized example of the error:
```hs
{-# LANGUAGE CPP #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE UndecidableInstances #-}
#define WITH_DICT 1
module Main (main) where
import Control.Monad (unless)
import qualified Data.Map as M
import Data.Map (Map)
#if WITH_DICT
import GHC.Exts (withDict)
#else
import Unsafe.Coerce (unsafeCoerce)
#endif
main :: IO ()
main = do
testCase (give Normal (toJSON (Foo Bar)))
(Object (M.fromList [("Foo",String "Bar")]))
testCase (give ViaShow (toJSON (Foo Bar)))
(Object (M.fromList [("Foo",String "SHOWBAR")]))
putStrLn "All tests passed!"
-----
testCase :: (Eq a, Show a) => a -> a -> IO ()
testCase expected actual =
unless (expected == actual) $
error $ unlines
[ ""
, "Expected: " ++ show expected
, "Actual: " ++ show actual
]
class Given a where
given :: a
give :: forall a r. a -> (Given a => r) -> r
#if WITH_DICT
give = withDict @a @(Given a)
#else
give a k = unsafeCoerce (Gift k :: Gift a r) a
newtype Gift a r = Gift (Given a => r)
#endif
data Foo = Foo Bar
instance Show Foo where
show _ = "SHOWFOO"
data Bar = Bar | BarBar
instance Show Bar where
show _ = "SHOWBAR"
----------------------------------------------------------------------------
-- ToJSON instances
----------------------------------------------------------------------------
instance Given Style => ToJSON Foo where
toJSON (Foo x) = Object $ M.singleton "Foo" (toJSON x)
instance Given Style => ToJSON Bar where
toJSON x = case given of
Normal -> String $ case x of
Bar -> "Bar"
BarBar -> "BarBar"
ViaShow -> String $ show x
data Style = Normal | ViaShow
----------------------------------------------------------------------------
-- Minimized aeson
----------------------------------------------------------------------------
class ToJSON a where
toJSON :: a -> Value
data Value
= Object !(Map String Value)
| String !String
deriving (Eq, Show)
```
If you compile this with GHC 9.4.1-alpha1 plus optimization, it will unexpectedly fail:
```
$ ~/Software/ghc-9.4.0.20220501/bin/ghc Bug.hs -O -fforce-recomp
[1 of 2] Compiling Main ( Bug.hs, Bug.o )
[2 of 2] Linking Bug [Objects changed]
$ ./Bug
Bug:
Expected: Object (fromList [("Foo",String "Bar")])
Actual: Object (fromList [("Foo",String "SHOWBAR")])
CallStack (from HasCallStack):
error, called at Bug.hs:33:5 in main:Main
```
On the other hand, if you compile it without optimization, it succeeds:
```
$ ~/Software/ghc-9.4.0.20220501/bin/ghc Bug.hs -O0 -fforce-recomp
[1 of 2] Compiling Main ( Bug.hs, Bug.o )
[2 of 2] Linking Bug [Objects changed]
$ ./Bug
All tests passed!
```
This behavior appears to be exclusive to `withDict`. If I define `give` in terms of `unsafeCoerce` (which is how `reflection` currently implements `give`), then it works regardless of the optimization level:
```
$ sed -i 's/#define WITH_DICT 1/#define WITH_DICT 0/' Bug.hs
$ ~/Software/ghc-9.4.0.20220501/bin/ghc Bug.hs -O -fforce-recomp
[1 of 2] Compiling Main ( Bug.hs, Bug.o )
[2 of 2] Linking Bug [Objects changed]
$ ./Bug
All tests passed!
$ ~/Software/ghc-9.4.0.20220501/bin/ghc Bug.hs -O0 -fforce-recomp
[1 of 2] Compiling Main ( Bug.hs, Bug.o )
[2 of 2] Linking Bug [Objects changed]
$ ./Bug
All tests passed!
```9.4.1Simon Peyton JonesSimon Peyton Joneshttps://gitlab.haskell.org/ghc/ghc/-/issues/21624"IntMulMayOfloOp" primop compiles to wrong Aarch64 assembly2022-08-05T14:46:34ZNatsu Kagami"IntMulMayOfloOp" primop compiles to wrong Aarch64 assembly## Summary
The primop `IntMulMayOfloOp` is being translated to a `MUL` instruction followed by a `CSET` (conditional set, with overflow flag) instruction on Aarch64 (see https://gitlab.haskell.org/ghc/ghc/-/blob/master/compiler/GHC/CmmT...## Summary
The primop `IntMulMayOfloOp` is being translated to a `MUL` instruction followed by a `CSET` (conditional set, with overflow flag) instruction on Aarch64 (see https://gitlab.haskell.org/ghc/ghc/-/blob/master/compiler/GHC/CmmToAsm/AArch64/CodeGen.hs#L894).
However, this is not correct: the overflow flag is never set on a `MUL` instruction. According to [A64 documentation](https://developer.arm.com/documentation/100076/0100/A64-Instruction-Set-Reference/Condition-Codes/Condition-flags?lang=en),
> Overflow occurs if the result of a signed add, subtract, or compare is greater than or equal to 2^31, or less than -2^31.
This means that the current primop will most likely return 0 all the time, which is wrong and potentially dangerous.
## Steps to reproduce
The following code always prints 0 in ghc 9.2.2 on Apple M1, but not in ghc 8.10.7 (which uses LLVM backend):
```hs
{-# LANGUAGE MagicHash #-}
module Main where
import GHC.Exts
import Data.Bits
unpack (I# a#) = a#
k :: Int
k = 134534534134534000 -- obviously does not fit in an int32, and so will overflow when squared.
bakaVariable = I# (mulIntMayOflo# (unpack k) (unpack k))
main = do
print bakaVariable
```
## Expected behavior
Should not print 0 at all.
## Environment
* GHC version used: 9.2.2
Optional:
* Operating System: Mac OS Monterey 12.3.1
* System Architecture: Aarch64 (Apple M1 Macbook Air)9.2.4Ben GamariBen Gamarihttps://gitlab.haskell.org/ghc/ghc/-/issues/21708Compiled program with GHC9.2.2 often causes "internal error: evacuate: strang...2022-11-07T15:55:40ZJH LeCompiled program with GHC9.2.2 often causes "internal error: evacuate: strange closure type xxx"## Summary
I cannot come up with a good title, so please bear with me with the title.
I've been using XMonad with GHC 9.0.2 fine,
but when I updated it to GHC9.2.2, it often crashes.
It sometimes leave the following message, while somet...## Summary
I cannot come up with a good title, so please bear with me with the title.
I've been using XMonad with GHC 9.0.2 fine,
but when I updated it to GHC9.2.2, it often crashes.
It sometimes leave the following message, while sometimes silently crashes.
```
xmonad-x86_64-linux: internal error: evacuate: strange closure type 0
(GHC version 9.2.2 for x86_64_unknown_linux)
Please report this as a GHC bug: https://www.haskell.org/ghc/reportabug
Aborted (core dumped)
```
(The closure type depends time to time)
Happens with the most bare-bone XMonad instance. I am lost on how to skin it down further.
Reporting this to GHC, since this specifically happens with GHC9.2.2. All previous versions work fine.
Any directions to diagnose which part is causing the issue?
## Steps to reproduce
1. Install XMonad as dynamically linked
2. Run with the default configuration
3. (At least on my end) performing some action leads to a crash from time to time
## Expected behavior
`internal error: evacuate: strange closure type 0` should not happen.
## Environment
* GHC version used: 9.2.2
Optional:
* Operating System: Ubuntu 20.04.4 LTS, 64-bit, Linux
* System Architecture: x86-649.2.4Ben GamariBen Gamari