hsmt-0.1.0.0: src/HSMT/Theory/FloatBlast.hs
-- | Bit-blasting of the SMT-LIB floating-point theory.
--
-- A floating-point term of the format @(eb, sb)@ is the list of the
-- @eb + sb@ bits of its IEEE pattern, least significant first (trailing
-- significand, then exponent, then sign). Every NaN is the canonical
-- pattern ('HSMT.Core.Float.canonicalNaN'), so equality of values is
-- equality of bits; circuits keep this invariant and 'fpInvariant' imposes
-- it on unconstrained bits. A rounding mode is 3 bits holding
-- 'fromEnum' of 'HSMT.Core.Float.RoundingMode'.
--
-- Arithmetic unpacks its operands into a sign, a signed exponent and a
-- normalized significand (leading one at the top), computes a result with
-- enough extra bits and a sticky bit, and rounds it once (@roundTo@), as in
-- SymFPU (Brain, Schanda and Sun, 2019). Division and square root are
-- defined by constraints (@a = q b + r@ and @R^2 <= X < (R + 1)^2@), like
-- bit-vector division. The remainder iterates over the largest exponent
-- difference of the format, so its circuit grows with @2^eb@.
module HSMT.Theory.FloatBlast
( -- * Invariants
fpInvariant
, rmInvariant
-- * Classification
, fpIsNaN
, fpIsInf
, fpIsZero
, fpIsNormal
, fpIsSubnormal
, fpIsNegative
, fpIsPositive
-- * Comparisons
, fpLt
, fpLeq
, fpEq
-- * Operations
, fpAbs
, fpNeg
, fpFromFields
, fpFromBits
, fpAdd
, fpSub
, fpMul
, fpDiv
, fpFma
, fpSqrt
, fpRem
, fpRoundToIntegral
, fpMin
, fpMax
, fpConvert
, fpFromInt
, fpToInt
) where
import Control.Monad (foldM)
import HSMT.Core.Float (canonicalNaN)
import HSMT.SAT.Types
import HSMT.Theory.BitBlast (Bits, Circuit)
import qualified HSMT.Theory.BitBlast as BB
-- | A floating-point format: exponent and significand widths (the
-- significand width counts the hidden bit).
type Format = (Int, Int)
-------------------------------------------------------------------------------
-- Helpers
bitLen :: Int -> Int
bitLen n = length (takeWhile (> 0) (iterate (`div` 2) n))
-- | Width of the signed exponents of computations over the formats (and
-- over integers of the given widths): exponents and their differences stay
-- within @2^(eb + 1) + 4 sb@ in magnitude.
expWidth :: [Format] -> [Int] -> Int
expWidth fmts ints =
bitLen (maximum ([2 ^ (eb + 1) + 4 * sb | (eb, sb) <- fmts] <> map (* 4) ints)) + 2
falses :: Circuit -> Int -> Bits
falses c k = replicate k (BB.cFalse c)
trues :: Circuit -> Int -> Bits
trues c k = replicate k (BB.cTrue c)
-- | A signed constant of the given width.
sconst :: Circuit -> Int -> Integer -> Bits
sconst c w k = BB.constBits c w (k `mod` (2 ^ w))
zext :: Circuit -> Int -> Bits -> Bits
zext c w bs = take w (bs <> falses c (w - length bs))
notL :: Lit -> Lit
notL = litNeg
orN, andN :: Circuit -> [Lit] -> IO Lit
orN = BB.orN
andN = BB.andN
-- | Priority selection: the first case whose condition holds.
select :: Circuit -> [(Lit, Bits)] -> Bits -> IO Bits
select c cases def = foldM (\acc (l, bs) -> BB.bvIte c l bs acc) def (reverse cases)
fields :: Format -> Bits -> (Bits, Bits, Lit)
fields (eb, sb) bs = (take (sb - 1) bs, take eb (drop (sb - 1) bs), bs !! (eb + sb - 1))
pattern :: Circuit -> Format -> Integer -> Bits
pattern c (eb, sb) = BB.constBits c (eb + sb)
nanBits :: Circuit -> Format -> Bits
nanBits c (eb, sb) = pattern c (eb, sb) (canonicalNaN eb sb)
infBits :: Circuit -> Format -> Lit -> Bits
infBits c (eb, sb) s = falses c (sb - 1) <> trues c eb <> [s]
zeroBits :: Circuit -> Format -> Lit -> Bits
zeroBits c (eb, sb) s = falses c (eb + sb - 1) <> [s]
-- | Shift left by a constant, within the width.
shl :: Circuit -> Int -> Bits -> Bits
shl c k bs = take (length bs) (falses c k <> bs)
-- | Normalize to a leading one at the top: the shifted bits and the shift
-- (the number of leading zeros, for a non-zero input).
normalize :: Circuit -> Bits -> IO (Bits, Bits)
normalize c bs0 = do
let n = length bs0
stages = reverse (takeWhile (< n) (iterate (* 2) 1))
(bs, counts) <-
foldM
( \(cur, cs) k -> do
anyTop <- orN c (drop (n - k) cur)
let z = notL anyTop
cur' <- BB.bvIte c z (shl c k cur) cur
pure (cur', z : cs)
)
(bs0, [])
stages
-- The last stage (shift by one) is the first count bit: low first.
pure (bs, counts)
-- | Logical right shift by an unsigned amount, with the OR of the bits
-- shifted out.
shiftRightSticky :: Circuit -> Bits -> Bits -> IO (Bits, Lit)
shiftRightSticky c bs0 amount = do
let n = length bs0
foldM
( \(cur, st) (j, bit) -> do
let k = 2 ^ (j :: Int) :: Int
(out, shifted) =
if k >= n
then (cur, falses c n)
else (take k cur, drop k cur <> falses c k)
o <- orN c out
lost <- BB.andG c bit o
st' <- BB.orG c st lost
cur' <- BB.bvIte c bit shifted cur
pure (cur', st')
)
(bs0, BB.cFalse c)
(zip [0 ..] amount)
-------------------------------------------------------------------------------
-- Rounding modes
data RM = RM {rmRNE, rmRNA, rmRTP, rmRTN :: Lit}
roundingMode :: Circuit -> Bits -> IO RM
roundingMode c bits = do
let is k = BB.bvEq c bits (BB.constBits c 3 k)
RM <$> is 0 <*> is 1 <*> is 2 <*> is 3
-- | Whether to increment a truncated magnitude: its sign, its least
-- significant bit, the first bit cut off and the OR of the others.
roundUp :: Circuit -> RM -> Lit -> Lit -> Lit -> Lit -> IO Lit
roundUp c rm s lsb g st = do
gs <- BB.orG c g st
ne <- BB.andG c g =<< BB.orG c st lsb
up <- BB.andG c (notL s) gs
down <- BB.andG c s gs
orN c =<< sequence [BB.andG c (rmRNE rm) ne, BB.andG c (rmRNA rm) g, BB.andG c (rmRTP rm) up, BB.andG c (rmRTN rm) down]
-------------------------------------------------------------------------------
-- Unpacking and rounding
-- | A decoded operand. For finite non-zero values the value is
-- @sig * 2^(exp - (length sig - 1))@ with the top bit of @sig@ set; for the
-- other values @sig@ is @100..0@ (so that divisions are well defined).
data Unpacked = Unpacked
{ uNaN, uInf, uZero, uSign :: Lit
, uExp :: Bits
, uSig :: Bits
}
unpack :: Circuit -> Format -> Int -> Bits -> IO Unpacked
unpack c (eb, sb) ew bits = do
let (frac, ef, s) = fields (eb, sb) bits
bias = 2 ^ (eb - 1) - 1 :: Integer
allOnes <- andN c ef
anyE <- orN c ef
anyF <- orN c frac
nan <- BB.andG c allOnes anyF
inf <- BB.andG c allOnes (notL anyF)
zero <- BB.andG c (notL anyE) (notL anyF)
sub <- BB.andG c (notL anyE) anyF
expNormal <- BB.bvSub c (zext c ew ef) (sconst c ew bias)
(sigSub, lz) <- normalize c (frac <> [BB.cFalse c])
expSub <- BB.bvSub c (sconst c ew (1 - bias)) (zext c ew lz)
special <- orN c [nan, inf, zero]
sig0 <- BB.bvIte c sub sigSub (frac <> [BB.cTrue c])
sig <- BB.bvIte c special (BB.constBits c sb (2 ^ (sb - 1))) sig0
e <- BB.bvIte c sub expSub expNormal
pure (Unpacked nan inf zero s e sig)
-- | Round a non-zero value into the format: sign, exponent of the leading
-- bit (signed, width @ew@), normalized significand of at least @sb + 2@
-- bits and the OR of the bits below it. Handles subnormal results,
-- underflow to zero and overflow.
roundTo :: Circuit -> RM -> Format -> Int -> Lit -> Bits -> Bits -> Lit -> IO Bits
roundTo c rm (eb, sb) ew s e sig0 st0 = do
let sig = if length sig0 >= sb + 2 then sig0 else falses c (sb + 2 - length sig0) <> sig0
p = length sig
bias = 2 ^ (eb - 1) - 1 :: Integer
amtW = bitLen (p + 1)
be <- BB.bvAdd c e (sconst c ew bias)
tiny <- BB.bvSLt c be (sconst c ew 1)
d <- BB.bvSub c (sconst c ew 1) be
big <- BB.bvSLe c (sconst c ew (toInteger (p + 1))) d
amount0 <- BB.bvIte c big (BB.constBits c amtW (toInteger (p + 1))) (take amtW d)
amount <- BB.bvIte c tiny amount0 (falses c amtW)
(sh, st1) <- shiftRightSticky c sig amount
let m = drop (p - sb) sh
g = sh !! (p - sb - 1)
rest = take (p - sb - 1) sh
st <- orN c (st0 : st1 : rest)
inc <- roundUp c rm s (m !! 0) g st
m' <- BB.bvAdd c (m <> [BB.cFalse c]) (inc : falses c sb)
let carry = m' !! sb
hidden = m' !! (sb - 1)
frac = take (sb - 1) m'
beInc <- BB.bvAdd c be (carry : falses c (ew - 1))
field <- BB.bvIte c tiny (hidden : falses c (ew - 1)) beInc
overflow <- BB.andG c (notL tiny) =<< BB.bvSLe c (sconst c ew (2 ^ eb - 1)) field
toInf <-
orN c
=<< sequence [pure (rmRNE rm), pure (rmRNA rm), BB.andG c (rmRTP rm) (notL s), BB.andG c (rmRTN rm) s]
let normal = frac <> take eb field <> [s]
largest = trues c (sb - 1) <> (BB.cFalse c : trues c (eb - 1)) <> [s]
ovf <- BB.bvIte c toInf (infBits c (eb, sb) s) largest
BB.bvIte c overflow ovf normal
-- | Round the value @mag * 2^scale@ (an unsigned magnitude, non-zero).
roundInt :: Circuit -> RM -> Format -> Int -> Lit -> Bits -> Bits -> IO Bits
roundInt c rm fmt ew s mag scale = do
let w = length mag
(mn, lz) <- normalize c mag
e <- BB.bvSub c scale (zext c ew lz) >>= BB.bvAdd c (sconst c ew (toInteger (w - 1)))
roundTo c rm fmt ew s e mn (BB.cFalse c)
exactRM :: Circuit -> RM
exactRM c = RM (BB.cTrue c) (BB.cFalse c) (BB.cFalse c) (BB.cFalse c)
-------------------------------------------------------------------------------
-- Invariants and classification
-- | Clauses forcing bits to be a canonical floating-point pattern.
fpInvariant :: Circuit -> Format -> Bits -> IO ()
fpInvariant c fmt bits = do
nan <- fpIsNaN c fmt bits
let canon = nanBits c fmt
sequence_
[ BB.emitClause c [notL nan, if BB.isConstLit c k == Just True then b else notL b]
| (b, k) <- zip bits canon
]
-- | Clauses forcing bits to be a rounding mode.
rmInvariant :: Circuit -> Bits -> IO ()
rmInvariant c bits = BB.bvULe c bits (BB.constBits c 3 4) >>= \l -> BB.emitClause c [l]
-- | Classification predicates (@fp.isNaN@, @fp.isInfinite@, @fp.isZero@,
-- @fp.isNormal@, @fp.isSubnormal@, @fp.isNegative@, @fp.isPositive@) of a
-- value of the given format. Zeros and infinities have a sign, so
-- 'fpIsNegative' and 'fpIsPositive' hold for them; both are false for NaN.
fpIsNaN, fpIsInf, fpIsZero, fpIsNormal, fpIsSubnormal, fpIsNegative, fpIsPositive :: Circuit -> Format -> Bits -> IO Lit
fpIsNaN c fmt bits = do
let (frac, ef, _) = fields fmt bits
BB.andG c <$> andN c ef <*> orN c frac >>= id
fpIsInf c fmt bits = do
let (frac, ef, _) = fields fmt bits
BB.andG c <$> andN c ef <*> (notL <$> orN c frac) >>= id
fpIsZero c fmt bits = do
let (frac, ef, _) = fields fmt bits
notL <$> orN c (frac <> ef)
fpIsNormal c fmt bits = do
let (_, ef, _) = fields fmt bits
BB.andG c <$> orN c ef <*> (notL <$> andN c ef) >>= id
fpIsSubnormal c fmt bits = do
let (frac, ef, _) = fields fmt bits
BB.andG c <$> (notL <$> orN c ef) <*> orN c frac >>= id
fpIsNegative c fmt bits = do
let (_, _, s) = fields fmt bits
nan <- fpIsNaN c fmt bits
BB.andG c s (notL nan)
fpIsPositive c fmt bits = do
let (_, _, s) = fields fmt bits
nan <- fpIsNaN c fmt bits
BB.andG c (notL s) (notL nan)
-------------------------------------------------------------------------------
-- Comparisons
-- | IEEE comparisons @a < b@, @a <= b@ and @a = b@ (@fp.lt@, @fp.leq@,
-- @fp.eq@): false when either argument is NaN, and the two zeros are equal.
fpLt, fpLeq, fpEq :: Circuit -> Format -> Bits -> Bits -> IO Lit
fpLt c fmt a b = do
nanA <- fpIsNaN c fmt a
nanB <- fpIsNaN c fmt b
zeroA <- fpIsZero c fmt a
zeroB <- fpIsZero c fmt b
let (_, _, sa) = fields fmt a
(_, _, sb) = fields fmt b
magA = init a
magB = init b
ltMag <- BB.bvULt c magA magB
gtMag <- BB.bvULt c magB magA
both0 <- BB.andG c zeroA zeroB
whenNeg <- BB.iteG c sb gtMag (BB.cTrue c)
whenPos <- BB.iteG c sb (BB.cFalse c) ltMag
r <- BB.iteG c sa whenNeg whenPos
andN c [notL nanA, notL nanB, notL both0, r]
fpEq c fmt a b = do
nanA <- fpIsNaN c fmt a
nanB <- fpIsNaN c fmt b
both0 <- BB.andG c <$> fpIsZero c fmt a <*> fpIsZero c fmt b >>= id
same <- BB.bvEq c a b
andN c [notL nanA, notL nanB] >>= \ok -> BB.andG c ok =<< BB.orG c both0 same
fpLeq c fmt a b = BB.orG c <$> fpLt c fmt a b <*> fpEq c fmt a b >>= id
-------------------------------------------------------------------------------
-- Sign operations and constructors
canonical :: Circuit -> Format -> Bits -> IO Bits
canonical c fmt bits = do
nan <- fpIsNaN c fmt bits
BB.bvIte c nan (nanBits c fmt) bits
-- | Absolute value (clears the sign bit) and negation (flips it, keeping NaN
-- canonical).
fpAbs, fpNeg :: Circuit -> Format -> Bits -> IO Bits
fpAbs c _ bits = pure (init bits <> [BB.cFalse c])
fpNeg c fmt bits = do
nan <- fpIsNaN c fmt bits
BB.bvIte c nan bits (init bits <> [notL (last bits)])
-- | The @fp@ constructor (bits low first: sign, exponent, trailing
-- significand as given).
fpFromFields :: Circuit -> Format -> Bits -> Bits -> Bits -> IO Bits
fpFromFields c fmt s e f = canonical c fmt (f <> e <> s)
-- | @(_ to_fp eb sb)@ of a bit-vector: its bits as a pattern.
fpFromBits :: Circuit -> Format -> Bits -> IO Bits
fpFromBits = canonical
-------------------------------------------------------------------------------
-- Arithmetic
-- | Sum of two finite non-zero values with normalized significands of the
-- same width: whether it is an exact zero, and the sign, exponent and
-- significand (with three extra bits) to round.
addCore :: Circuit -> Int -> (Lit, Bits, Bits) -> (Lit, Bits, Bits) -> IO (Lit, Lit, Bits, Bits)
addCore c ew (sa, ea, ma) (sb, eb, mb) = do
let q = length ma
p = q + 3
amtW = bitLen p
eGt <- BB.bvSLt c eb ea
eEq <- BB.bvEq c ea eb
mGe <- BB.bvULe c mb ma
aBig <- BB.orG c eGt =<< BB.andG c eEq mGe
sx <- BB.iteG c aBig sa sb
sy <- BB.iteG c aBig sb sa
ex <- BB.bvIte c aBig ea eb
ey <- BB.bvIte c aBig eb ea
mx <- BB.bvIte c aBig ma mb
my <- BB.bvIte c aBig mb ma
d <- BB.bvSub c ex ey
big <- BB.bvSLe c (sconst c ew (toInteger p)) d
amount <- BB.bvIte c big (BB.constBits c amtW (toInteger p)) (take amtW d)
let xExt = falses c 3 <> mx
(ySh, st) <- shiftRightSticky c (falses c 3 <> my) amount
jam <- BB.orG c (ySh !! 0) st
let yJam = jam : drop 1 ySh
isSub <- BB.xorG c sx sy
-- Effective addition: at most one more bit.
total <- BB.bvAdd c (xExt <> [BB.cFalse c]) (yJam <> [BB.cFalse c])
let top = total !! p
low <- BB.orG c (total !! 0) (total !! 1)
sumSig <- BB.bvIte c top (low : drop 2 total) (take p total)
exPlus <- BB.bvAdd c ex (BB.cTrue c : falses c (ew - 1))
sumExp <- BB.bvIte c top exPlus ex
-- Effective subtraction: cancellation of leading bits.
diff <- BB.bvSub c xExt yJam
nonZero <- orN c diff
(diffSig, lz) <- normalize c diff
diffExp <- BB.bvSub c ex (zext c ew lz)
sig <- BB.bvIte c isSub diffSig sumSig
e <- BB.bvIte c isSub diffExp sumExp
exactZero <- BB.andG c isSub (notL nonZero)
pure (exactZero, sx, e, sig)
-- | @fp.add@, @fp.sub@, @fp.mul@ and @fp.div@: the rounding mode bits come
-- first, then the operands; the result is correctly rounded.
fpAdd, fpSub, fpMul, fpDiv :: Circuit -> Format -> Bits -> Bits -> Bits -> IO Bits
fpAdd c fmt@(eb, sb) rmBits a b = do
let ew = expWidth [(eb, sb)] []
rm <- roundingMode c rmBits
ua <- unpack c fmt ew a
ub <- unpack c fmt ew b
(exactZero, s, e, m) <- addCore c ew (uSign ua, uExp ua, uSig ua) (uSign ub, uExp ub, uSig ub)
r <- roundTo c rm fmt ew s e m (BB.cFalse c)
opposite <- BB.xorG c (uSign ua) (uSign ub)
nan <- orN c =<< sequence [pure (uNaN ua), pure (uNaN ub), andN c [uInf ua, uInf ub, opposite]]
inf <- BB.orG c (uInf ua) (uInf ub)
infSign <- BB.iteG c (uInf ua) (uSign ua) (uSign ub)
bothZero <- BB.andG c (uZero ua) (uZero ub)
zeroSign <- BB.orG c <$> BB.andG c (uSign ua) (uSign ub) <*> (BB.andG c (rmRTN rm) =<< BB.orG c (uSign ua) (uSign ub)) >>= id
select
c
[ (nan, nanBits c fmt)
, (inf, infBits c fmt infSign)
, (bothZero, zeroBits c fmt zeroSign)
, (uZero ua, b)
, (uZero ub, a)
, (exactZero, zeroBits c fmt (rmRTN rm))
]
r
fpSub c fmt rmBits a b = fpNeg c fmt b >>= fpAdd c fmt rmBits a
fpMul c fmt@(eb, sb) rmBits a b = do
let ew = expWidth [(eb, sb)] []
rm <- roundingMode c rmBits
ua <- unpack c fmt ew a
ub <- unpack c fmt ew b
(s, e, m) <- product' c ew ua ub
r <- roundTo c rm fmt ew s e m (BB.cFalse c)
nan <- orN c =<< sequence [pure (uNaN ua), pure (uNaN ub), BB.andG c (uInf ua) (uZero ub), BB.andG c (uZero ua) (uInf ub)]
inf <- BB.orG c (uInf ua) (uInf ub)
zero <- BB.orG c (uZero ua) (uZero ub)
select c [(nan, nanBits c fmt), (inf, infBits c fmt s), (zero, zeroBits c fmt s)] r
fpDiv c fmt@(eb, sb) rmBits a b = do
let ew = expWidth [(eb, sb)] []
w = 2 * sb + 2
rm <- roundingMode c rmBits
ua <- unpack c fmt ew a
ub <- unpack c fmt ew b
s <- BB.xorG c (uSign ua) (uSign ub)
let num = falses c (sb + 2) <> uSig ua
den = zext c w (uSig ub)
q <- BB.bvUDiv c num den
r0 <- BB.bvURem c num den
st <- orN c r0
let qq = take (sb + 3) q
top = qq !! (sb + 2)
sig <- BB.bvIte c top qq (shl c 1 qq)
e0 <- BB.bvSub c (uExp ua) (uExp ub)
eMinus <- BB.bvSub c e0 (BB.cTrue c : falses c (ew - 1))
e <- BB.bvIte c top e0 eMinus
r <- roundTo c rm fmt ew s e sig st
nan <- orN c =<< sequence [pure (uNaN ua), pure (uNaN ub), BB.andG c (uInf ua) (uInf ub), BB.andG c (uZero ua) (uZero ub)]
inf <- BB.orG c (uInf ua) (uZero ub)
zero <- BB.orG c (uZero ua) (uInf ub)
select c [(nan, nanBits c fmt), (inf, infBits c fmt s), (zero, zeroBits c fmt s)] r
-- | Exact product of two unpacked values: sign, exponent and a normalized
-- significand of twice the width.
product' :: Circuit -> Int -> Unpacked -> Unpacked -> IO (Lit, Bits, Bits)
product' c ew ua ub = do
let sb = length (uSig ua)
w = 2 * sb
s <- BB.xorG c (uSign ua) (uSign ub)
prod <- BB.bvMul c (zext c w (uSig ua)) (zext c w (uSig ub))
let top = prod !! (w - 1)
sig <- BB.bvIte c top prod (shl c 1 prod)
e0 <- BB.bvAdd c (uExp ua) (uExp ub)
ePlus <- BB.bvAdd c e0 (BB.cTrue c : falses c (ew - 1))
e <- BB.bvIte c top ePlus e0
pure (s, e, sig)
-- | Fused multiply-add @fp.fma rm a b z@, i.e. @a * b + z@ with a single
-- rounding.
fpFma :: Circuit -> Format -> Bits -> Bits -> Bits -> Bits -> IO Bits
fpFma c fmt@(eb, sb) rmBits a b z = do
let ew = expWidth [(eb, 2 * sb)] []
rm <- roundingMode c rmBits
ua <- unpack c fmt ew a
ub <- unpack c fmt ew b
uz <- unpack c fmt ew z
(ps, pe, pm) <- product' c ew ua ub
(exactZero, s, e, m) <- addCore c ew (ps, pe, pm) (uSign uz, uExp uz, falses c sb <> uSig uz)
r <- roundTo c rm fmt ew s e m (BB.cFalse c)
rProd <- roundTo c rm fmt ew ps pe pm (BB.cFalse c)
prodInf <- BB.orG c (uInf ua) (uInf ub)
prodZero <- BB.orG c (uZero ua) (uZero ub)
opposite <- BB.xorG c ps (uSign uz)
nan <-
orN c
=<< sequence
[ pure (uNaN ua)
, pure (uNaN ub)
, pure (uNaN uz)
, BB.andG c (uInf ua) (uZero ub)
, BB.andG c (uZero ua) (uInf ub)
, andN c [prodInf, uInf uz, opposite]
]
inf <- BB.orG c prodInf (uInf uz)
infSign <- BB.iteG c prodInf ps (uSign uz)
bothZero <- BB.andG c prodZero (uZero uz)
zeroSign <- BB.orG c <$> BB.andG c ps (uSign uz) <*> (BB.andG c (rmRTN rm) =<< BB.orG c ps (uSign uz)) >>= id
select
c
[ (nan, nanBits c fmt)
, (inf, infBits c fmt infSign)
, (bothZero, zeroBits c fmt zeroSign)
, (prodZero, z)
, (uZero uz, rProd)
, (exactZero, zeroBits c fmt (rmRTN rm))
]
r
-- | Correctly rounded square root (@fp.sqrt@) under the given rounding
-- mode; NaN for negative non-zero arguments.
fpSqrt :: Circuit -> Format -> Bits -> Bits -> IO Bits
fpSqrt c fmt@(eb, sb) rmBits a = do
let ew = expWidth [(eb, 3 * sb + 8)] []
k = sb + 2
rm <- roundingMode c rmBits
ua <- unpack c fmt ew a
-- value = sig * 2^t with t = exp - (sb - 1); make t even.
t <- BB.bvSub c (uExp ua) (sconst c ew (toInteger (sb - 1)))
let odd' = t !! 0
sig1 = zext c (sb + 1) (uSig ua)
sig2 <- BB.bvIte c odd' (shl c 1 sig1) sig1
t2 <- BB.bvSub c t (odd' : falses c (ew - 1))
let x = falses c (2 * k) <> sig2
wx = length x
wr = (wx + 1) `div` 2
w2 = 2 * wr + 2
root <- BB.freshBits c wr
let rootW = zext c w2 root
xW = zext c w2 x
sq <- BB.bvMul c rootW rootW
BB.bvULe c sq xW >>= \l -> BB.emitClause c [l]
-- (r + 1)^2 = r^2 + 2r + 1
twice <- BB.bvAdd c sq (shl c 1 rootW)
next <- BB.bvAdd c twice (BB.constBits c w2 1)
BB.bvULt c xW next >>= \l -> BB.emitClause c [l]
exact <- BB.bvEq c sq xW
-- sqrt(value) = root * 2^(t2 / 2 - k), up to the sticky bit.
let half = drop 1 t2 <> [last t2]
scale <- BB.bvSub c half (sconst c ew (toInteger k))
r <- do
(mn, lz) <- normalize c root
e <- BB.bvSub c scale (zext c ew lz) >>= BB.bvAdd c (sconst c ew (toInteger (wr - 1)))
roundTo c rm fmt ew (BB.cFalse c) e mn (notL exact)
negative <- BB.andG c (uSign ua) (notL (uZero ua))
nan <- BB.orG c (uNaN ua) negative
select c [(nan, nanBits c fmt), (uInf ua, a), (uZero ua, a)] r
-- | IEEE remainder (@fp.rem@): @a - b * n@ where @n@ is @a / b@ rounded to
-- the nearest integer, ties to even; exact, so it takes no rounding mode.
fpRem :: Circuit -> Format -> Bits -> Bits -> IO Bits
fpRem c fmt@(eb, sb) a b = do
let ew = expWidth [(eb, sb)] []
bias = 2 ^ (eb - 1) - 1 :: Integer
dMax = (bias - (1 - bias)) + toInteger sb - 1
rm = exactRM c
ua <- unpack c fmt ew a
ub <- unpack c fmt ew b
d <- BB.bvSub c (uExp ua) (uExp ub)
let w = sb + 1
ma = zext c w (uSig ua)
mb = zext c w (uSig ub)
ge0 <- BB.bvULe c mb ma
r0 <- BB.bvSub c ma mb >>= \df -> BB.bvIte c ge0 df ma
(rFinal, qFinal) <-
foldM
( \(r, q) i -> do
active <- BB.bvSLe c (sconst c ew i) d
let r2 = shl c 1 r
ge <- BB.bvULe c mb r2
rn <- BB.bvSub c r2 mb >>= \df -> BB.bvIte c ge df r2
r' <- BB.bvIte c active rn r
q' <- BB.iteG c active ge q
pure (r', q')
)
(r0, ge0)
[1 .. dMax]
-- Round the quotient to nearest, ties to even.
let twoR = shl c 1 rFinal
gt <- BB.bvULt c mb twoR
tie <- BB.bvEq c mb twoR
up <- BB.orG c gt =<< BB.andG c tie qFinal
mag <- BB.bvSub c mb rFinal >>= \df -> BB.bvIte c up df rFinal
sgn <- BB.xorG c (uSign ua) up
magZero <- notL <$> orN c mag
scaleB <- BB.bvSub c (uExp ub) (sconst c ew (toInteger (sb - 1)))
r1 <- roundInt c rm fmt ew sgn mag scaleB
-- Exponent difference -1: |x| >= |y| / 2.
gtHalf <- BB.bvULt c mb ma
mag2 <- BB.bvSub c (shl c 1 mb) ma
scaleA <- BB.bvSub c (uExp ua) (sconst c ew (toInteger (sb - 1)))
r2 <- roundInt c rm fmt ew (notL (uSign ua)) mag2 scaleA
minusOne <- BB.bvEq c d (sconst c ew (-1))
negD <- BB.bvSLt c d (sconst c ew 0)
nan <- orN c [uNaN ua, uNaN ub, uInf ua, uZero ub]
keep <- BB.orG c (uInf ub) (uZero ua)
close <- BB.andG c minusOne gtHalf
select
c
[ (nan, nanBits c fmt)
, (keep, a)
, (close, r2)
, (negD, a)
, (magZero, zeroBits c fmt (uSign ua))
]
r1
-- | Round a finite value to an integer magnitude (at most @2^sb@), given
-- its unpacked form: the magnitude and whether the value already was an
-- integer.
integerPart :: Circuit -> RM -> Format -> Int -> Unpacked -> IO (Bits, Lit)
integerPart c rm (_, sb) ew ua = do
isInt <- BB.bvSLe c (sconst c ew (toInteger (sb - 1))) (uExp ua)
sAmt <- BB.bvSub c (sconst c ew (toInteger (sb - 1))) (uExp ua)
let amtW = bitLen (sb + 1)
big <- BB.bvSLe c (sconst c ew (toInteger (sb + 1))) sAmt
amount <- BB.bvIte c big (BB.constBits c amtW (toInteger (sb + 1))) (take amtW sAmt)
(sh, st) <- shiftRightSticky c (BB.cFalse c : uSig ua) amount
let g = sh !! 0
m = drop 1 sh
inc <- roundUp c rm (uSign ua) (m !! 0) g st
n <- BB.bvAdd c (m <> [BB.cFalse c]) (inc : falses c sb)
pure (n, isInt)
-- | Round to an integral value in the same format (@fp.roundToIntegral@)
-- under the given rounding mode; the sign of zero results is kept.
fpRoundToIntegral :: Circuit -> Format -> Bits -> Bits -> IO Bits
fpRoundToIntegral c fmt@(eb, sb) rmBits a = do
let ew = expWidth [(eb, sb)] []
rm <- roundingMode c rmBits
ua <- unpack c fmt ew a
(n, isInt) <- integerPart c rm fmt ew ua
nZero <- notL <$> orN c n
r <- roundInt c (exactRM c) fmt ew (uSign ua) n (sconst c ew 0)
special <- orN c [uNaN ua, uInf ua, uZero ua, isInt]
select c [(special, a), (nZero, zeroBits c fmt (uSign ua))] r
-- | @fp.min@ / @fp.max@: the result when specified, and whether the
-- arguments are zeros of different signs (unspecified result).
fpMin, fpMax :: Circuit -> Format -> Bits -> Bits -> IO (Bits, Lit)
fpMin c fmt a b = minMax c fmt a b True
fpMax c fmt a b = minMax c fmt a b False
minMax :: Circuit -> Format -> Bits -> Bits -> Bool -> IO (Bits, Lit)
minMax c fmt a b isMin = do
nanA <- fpIsNaN c fmt a
nanB <- fpIsNaN c fmt b
takeB <- if isMin then fpLt c fmt b a else fpLt c fmt a b
r <- select c [(nanA, b), (nanB, a), (takeB, b)] a
zeroA <- fpIsZero c fmt a
zeroB <- fpIsZero c fmt b
differ <- BB.xorG c (last a) (last b)
unspecified <- andN c [zeroA, zeroB, differ]
pure (r, unspecified)
-------------------------------------------------------------------------------
-- Conversions
-- | Conversion between formats.
fpConvert :: Circuit -> Format -> Format -> Bits -> Bits -> IO Bits
fpConvert c from to rmBits a = do
let ew = expWidth [from, to] []
rm <- roundingMode c rmBits
ua <- unpack c from ew a
r <- roundTo c rm to ew (uSign ua) (uExp ua) (uSig ua) (BB.cFalse c)
select
c
[ (uNaN ua, nanBits c to)
, (uInf ua, infBits c to (uSign ua))
, (uZero ua, zeroBits c to (uSign ua))
]
r
-- | Conversion from a signed (flag set) or unsigned bit-vector.
fpFromInt :: Circuit -> Format -> Bool -> Bits -> Bits -> IO Bits
fpFromInt c fmt@(eb, sb) signed rmBits x = do
let w = length x
ew = expWidth [(eb, sb)] [w]
rm <- roundingMode c rmBits
let s = if signed then last x else BB.cFalse c
mag <- if signed then BB.bvNeg c x >>= \nx -> BB.bvIte c s nx x else pure x
zero <- notL <$> orN c mag
r <- roundInt c rm fmt ew s mag (sconst c ew 0)
BB.bvIte c zero (zeroBits c fmt (BB.cFalse c)) r
-- | Conversion to a signed (flag set) or unsigned bit-vector of the given
-- width: the result and whether it is specified (not NaN, infinite or out
-- of range).
fpToInt :: Circuit -> Format -> Bool -> Int -> Bits -> Bits -> IO (Bits, Lit)
fpToInt c fmt@(eb, sb) signed w rmBits a = do
let ew = expWidth [(eb, sb)] [w + 2]
ww = max (sb + 1) (w + 2)
amtW = bitLen ww
rm <- roundingMode c rmBits
ua <- unpack c fmt ew a
(nSmall, isInt) <- integerPart c rm fmt ew ua
shiftAmt <- BB.bvSub c (uExp ua) (sconst c ew (toInteger (sb - 1)))
large <- BB.bvShl c (zext c ww (uSig ua)) (zext c ww (take amtW shiftAmt))
nMag <- BB.bvIte c isInt large (zext c ww nSmall)
big <- BB.bvSLe c (sconst c ew (toInteger (w + 1))) (uExp ua)
nZero <- notL <$> orN c nMag
let s = uSign ua
fits <-
if signed
then do
limit <- BB.bvIte c s (BB.constBits c ww (2 ^ (w - 1))) (BB.constBits c ww (2 ^ (w - 1) - 1))
BB.bvULe c nMag limit
else do
small <- BB.bvULt c nMag (BB.constBits c ww (2 ^ w))
BB.andG c small =<< BB.orG c nZero (notL s)
inRange <- andN c [notL (uNaN ua), notL (uInf ua), notL big, fits]
specified <- BB.orG c (uZero ua) inRange
negated <- BB.bvNeg c nMag
value <- BB.bvIte c s negated nMag
result <- BB.bvIte c (uZero ua) (falses c w) (take w value)
pure (result, specified)