Update Trac ticket URLs to point to GitLab
[ghc.git] / testsuite / tests / codeGen / should_run / cgrun071.hs
1 {-# LANGUAGE BangPatterns, CPP, MagicHash #-}
2
3 module Main ( main ) where
4
5 import Data.Bits
6 import GHC.Prim
7 import GHC.Word
8
9 #include "MachDeps.h"
10
11 main = putStr
12 (test_popCnt ++ "\n"
13 ++ test_popCnt8 ++ "\n"
14 ++ test_popCnt16 ++ "\n"
15 ++ test_popCnt32 ++ "\n"
16 ++ test_popCnt64 ++ "\n"
17 ++ "\n"
18 )
19
20 popcnt :: Word -> Word
21 popcnt (W# w#) = W# (popCnt# w#)
22
23 popcnt8 :: Word -> Word
24 popcnt8 (W# w#) = W# (popCnt8# w#)
25
26 popcnt16 :: Word -> Word
27 popcnt16 (W# w#) = W# (popCnt16# w#)
28
29 popcnt32 :: Word -> Word
30 popcnt32 (W# w#) = W# (popCnt32# w#)
31
32 popcnt64 :: Word64 -> Word
33 popcnt64 (W64# w#) =
34 #if SIZEOF_HSWORD == 4
35 W# (popCnt64# w#)
36 #else
37 W# (popCnt# w#)
38 #endif
39
40 -- Cribbed from https://gitlab.haskell.org/ghc/ghc/issues/3563
41 slowPopcnt :: Word -> Word
42 slowPopcnt x = count' (bitSize x) x 0
43 where
44 count' 0 _ !acc = acc
45 count' n x acc = count' (n-1) (x `shiftR` 1)
46 (acc + if x .&. 1 == 1 then 1 else 0)
47
48 test_popCnt = test popcnt slowPopcnt
49 test_popCnt8 = test popcnt8 (slowPopcnt . fromIntegral . (mask 8 .&.))
50 test_popCnt16 = test popcnt16 (slowPopcnt . fromIntegral . (mask 16 .&.))
51 test_popCnt32 = test popcnt32 (slowPopcnt . fromIntegral . (mask 32 .&.))
52 test_popCnt64 = test popcnt64 (slowPopcnt . fromIntegral . (mask 64 .&.))
53
54 mask n = (2 ^ n) - 1
55
56 test :: (Show a, Num a) => (a -> Word) -> (a -> Word) -> String
57 test fast slow = case failing of
58 [] -> "OK"
59 ((_, e, a, i):xs) ->
60 "FAIL\n" ++ " Input: " ++ show i ++ "\nExpected: " ++ show e ++
61 "\n Actual: " ++ show a
62 where
63 failing = dropWhile ( \(b,_,_,_) -> b)
64 . map (\ x -> (slow x == fast x, slow x, fast x, x)) $ cases
65 expected = map slow cases
66 actual = map fast cases
67 -- 10 random numbers
68 #if SIZEOF_HSWORD == 4
69 cases = [1480294021,1626858410,2316287658,1246556957,3806579062,65945563,
70 1521588071,791321966,1355466914,2284998160]
71 #elif SIZEOF_HSWORD == 8
72 cases = [11004539497957619752,5625461252166958202,1799960778872209546,
73 16979826074020750638,12789915432197771481,11680809699809094550,
74 13208678822802632247,13794454868797172383,13364728999716654549,
75 17516539991479925226]
76 #else
77 # error Unexpected word size
78 #endif