Debian Codegraph @

src-ghc/Clash/GHC/PartialEval/Eval.hs

raw
1 {-|
2 Copyright : (C) 2020-2021, QBayLogic B.V.,
3 2022 , Google Inc.
4 License : BSD2 (see the file LICENSE)
5 Maintainer : QBayLogic B.V. <[email protected]>
6
7 This module provides the "evaluation" part of the partial evaluator. This
8 is implemented in the classic "eval/apply" style, with a variant of apply for
9 performing type applications.
10 -}
11
12 {-# LANGUAGE CPP #-}
13 {-# LANGUAGE LambdaCase #-}
14 {-# LANGUAGE MagicHash #-}
15 {-# LANGUAGE OverloadedStrings #-}
16
17 module Clash.GHC.PartialEval.Eval
18 ( eval
19 , apply
20 , applyTy
21 ) where
22
23 import Control.Monad (foldM)
24 import Data.Bifunctor
25 import Data.Bitraversable
26 import Data.Either
27 import Data.Maybe
28 import Data.Primitive.ByteArray (ByteArray(..))
29 #if MIN_VERSION_base(4,15,0)
30 import GHC.Num.Integer (Integer (..))
31 #else
32 import GHC.Integer.GMP.Internals (BigNat(..), Integer(..))
33 #endif
34
35 import GHC.BasicTypes.Extra (isNoInline)
36
37 import Clash.Core.DataCon (DataCon(..))
38 import Clash.Core.HasType
39 import Clash.Core.Literal (Literal(..))
40 import Clash.Core.PartialEval.AsTerm
41 import Clash.Core.PartialEval.Monad
42 import Clash.Core.PartialEval.NormalForm
43 import Clash.Core.Subst (substTy)
44 import Clash.Core.Term
45 import Clash.Core.TyCon (tyConDataCons)
46 import Clash.Core.Type
47 import Clash.Core.TysPrim (integerPrimTy)
48 import Clash.Core.Var
49 import qualified Clash.Data.UniqMap as UniqMap
50 import Clash.Driver.Types (Binding(..), IsPrim(..))
51 import qualified Clash.Normalize.Primitives as NP (undefined, undefinedX)
52
53 -- | Evaluate a term to WHNF.
54 --
55 eval :: Term -> Eval Value
56 eval = \case
57 Var i -> evalVar i
58 Literal lit -> pure (VLiteral lit)
59 Data dc -> evalData dc
60 Prim pr -> evalPrim pr
61 Lam i x -> evalLam i x
62 TyLam i x -> evalTyLam i x
63 App x y -> evalApp x (Left y)
64 TyApp x ty -> evalApp x (Right ty)
65 Let bs x -> evalLet bs x
66 Case x ty alts -> evalCase x ty alts
67 Cast x a b -> evalCast x a b
68 Tick tick x -> evalTick tick x
69
70 delayEval :: Term -> Eval Value
71 delayEval = \case
72 Literal lit -> pure (VLiteral lit)
73 Lam i x -> evalLam i x
74 TyLam i x -> evalTyLam i x
75 Tick t x -> flip VTick t <$> delayEval x
76 term -> VThunk term <$> getLocalEnv
77
78 forceEval :: Value -> Eval Value
79 forceEval = forceEvalWith [] []
80
81 forceEvalWith :: [(TyVar, Type)] -> [(Id, Value)] -> Value -> Eval Value
82 forceEvalWith tvs ids = \case
83 VThunk term env -> do
84 tvs' <- traverse (traverse evalType) tvs
85 setLocalEnv env (withTyVars tvs' . withIds ids $ eval term)
86
87 value -> pure value
88
89 delayArg :: Arg Term -> Eval (Arg Value)
90 delayArg = bitraverse delayEval evalType
91
92 delayArgs :: Args Term -> Eval (Args Value)
93 delayArgs = traverse delayArg
94
95 evalType :: Type -> Eval Type
96 evalType ty = do
97 tcm <- getTyConMap
98 subst <- getTvSubst
99
100 pure (normalizeType tcm (substTy subst ty))
101
102 evalVar :: Id -> Eval Value
103 evalVar i
104 | isLocalId i = lookupLocal i
105 | otherwise = lookupGlobal i
106
107 lookupLocal :: Id -> Eval Value
108 lookupLocal i = do
109 var <- findId i
110 varTy <- evalType (varType i)
111 let i' = i { varType = varTy }
112
113 case var of
114 Just x -> do
115 workFree <- workFreeValue x
116 if workFree then forceEval x else pure (VNeutral (NeVar i'))
117
118 Nothing -> pure (VNeutral (NeVar i'))
119
120 lookupGlobal :: Id -> Eval Value
121 lookupGlobal i = do
122 -- inScope <- getInScope
123 fuel <- getFuel
124 var <- findBinding i
125
126 case var of
127 Just x
128 -- The binding cannot be inlined. Note that this is limited to bindings
129 -- which are not primitives in Clash, as these must be marked NOINLINE.
130 | isNoInline (bindingSpec x)
131 , bindingIsPrim x == IsFun
132 -> pure (VNeutral (NeVar i))
133
134 -- There is no fuel, meaning no more inlining can occur.
135 | fuel == 0
136 -> pure (VNeutral (NeVar i))
137
138 -- Inlining can occur, using one unit of fuel in the process.
139 | otherwise
140 -> withContext i . withFuel $ do
141 val <- forceEval (bindingTerm x)
142 replaceBinding (x { bindingTerm = val })
143 pure val
144
145 Nothing
146 -> pure (VNeutral (NeVar i))
147
148 evalData :: DataCon -> Eval Value
149 evalData dc
150 | fullyApplied (dcType dc) [] =
151 VData dc [] <$> getLocalEnv
152
153 | otherwise =
154 etaExpand (Data dc) >>= eval
155
156 evalPrim :: PrimInfo -> Eval Value
157 evalPrim pr
158 | fullyApplied (primType pr) [] =
159 evalPrimOp pr []
160
161 | otherwise =
162 etaExpand (Prim pr) >>= eval
163
164 -- TODO Hook up to primitive evaluation skeleton
165 evalPrimOp :: PrimInfo -> Args Value -> Eval Value
166 evalPrimOp pr args = pure (VNeutral (NePrim pr args))
167
168 fullyApplied :: Type -> Args a -> Bool
169 fullyApplied ty args =
170 length (fst $ splitFunForallTy ty) == length args
171
172 etaExpand :: Term -> Eval Term
173 etaExpand term = do
174 tcm <- getTyConMap
175
176 case collectArgs term of
177 x@(Data dc, _) -> expand tcm (dcType dc) x
178 x@(Prim pr, _) -> expand tcm (primType pr) x
179 _ -> pure term
180 where
181 etaNameOf =
182 either (pure . Right) (fmap Left . getUniqueId "eta")
183
184 expand tcm ty (tm, args) = do
185 let (missingTys, _) = splitFunForallTy (applyTypeToArgs tm tcm ty args)
186 missingArgs <- traverse etaNameOf missingTys
187
188 pure $ mkAbstraction
189 (mkApps term (fmap (bimap Var VarTy) missingArgs))
190 missingArgs
191
192 evalLam :: Id -> Term -> Eval Value
193 evalLam i x = do
194 varTy <- evalType (varType i)
195 let i' = i { varType = varTy }
196 env <- getLocalEnv
197
198 pure (VLam i' x env)
199
200 evalTyLam :: TyVar -> Term -> Eval Value
201 evalTyLam i x = do
202 varTy <- evalType (varType i)
203 let i' = i { varType = varTy }
204 env <- getLocalEnv
205
206 pure (VTyLam i' x env)
207
208 evalApp :: Term -> Arg Term -> Eval Value
209 evalApp x y
210 | Data dc <- f
211 = if fullyApplied (dcType dc) args
212 then do
213 argThunks <- delayArgs args
214 VData dc argThunks <$> getLocalEnv
215
216 else etaExpand term >>= eval
217
218 | Prim pr <- f
219 , prArgs <- fst $ splitFunForallTy (primType pr)
220 , numArgs <- length prArgs
221 = case compare (length args) numArgs of
222 LT ->
223 etaExpand term >>= eval
224
225 EQ -> do
226 argThunks <- delayArgs args
227 let tyVars = lefts prArgs
228 tyArgs = rights args
229
230 withTyVars (zip tyVars tyArgs) (evalPrimOp pr argThunks)
231
232 GT -> do
233 let (pArgs, rArgs) = splitAt numArgs args
234 pArgThunks <- delayArgs pArgs
235 primRes <- evalPrimOp pr pArgThunks
236 rArgThunks <- delayArgs rArgs
237
238 foldM applyArg primRes rArgThunks
239
240 | otherwise
241 = preserveFuel $ do
242 evalF <- eval f
243 argThunks <- delayArgs args
244 foldM applyArg evalF argThunks
245 where
246 term = either (App x) (TyApp x) y
247 (f, args, _ticks) = collectArgsTicks term
248
249 evalLet :: Bind Term -> Term -> Eval Value
250 evalLet (NonRec i x) body = do
251 iTy <- evalType (varType i)
252 eX <- delayEval x
253 wfX <- workFreeValue eX
254
255 eBody <- withId i eX (eval body)
256
257 -- Only keep the let binding if it performs work.
258 if wfX
259 then pure eBody
260 else pure (VNeutral (NeLet (NonRec i{varType=iTy} eX) eBody))
261
262 evalLet (Rec xs) body = do
263 binds <- traverse evalBind xs
264 eBody <- withIds binds (eval body)
265
266 pure (VNeutral (NeLet (Rec binds) eBody))
267 where
268 evalBind (i, x) = do
269 iTy <- evalType (varType i)
270 eX <- delayEval x
271
272 pure (i{varType=iTy}, eX)
273
274 evalCase :: Term -> Type -> [Alt] -> Eval Value
275 evalCase term ty as = do
276 subject <- delayEval term
277 resTy <- evalType ty
278 alts <- delayAlts as
279
280 caseCon subject resTy alts
281
282 -- | Attempt to apply the case-of-known-constructor transformation on a case
283 -- expression. If no suitable alternative can be chosen, attempt to transform
284 -- the case expression to try and expose more opportunities.
285 --
286 caseCon :: Value -> Type -> [(Pat, Value)] -> Eval Value
287 caseCon subject ty alts = do
288 forcedSubject <- keepLifted (forceEval subject)
289
290 -- If the subject is undefined, the whole expression is undefined.
291 case isUndefinedX forcedSubject of
292 True -> eval (TyApp (Prim NP.undefinedX) ty)
293 False -> case isUndefined forcedSubject of
294 True -> eval (TyApp (Prim NP.undefined) ty)
295 False ->
296 case stripValue forcedSubject of
297 -- Known literal: attempt to match or throw an error.
298 VLiteral lit -> do
299 let def = error ("caseCon: No pattern matched " <> show lit <> " in " <> show alts)
300 match <- findBestAlt (matchLiteral lit) alts
301 evalAlt def match
302
303 -- Known data constructor: attempt to match or throw an error.
304 -- The environment here is the same as the current environment.
305 VData dc args _env -> do
306 let def = error ("caseCon: No pattern matched " <> show dc <> " in " <> show alts)
307 match <- findBestAlt (matchData dc args) alts
308 evalAlt def match
309
310 -- Neutral primitives may be clash primitives which are treated as
311 -- values, like fromInteger# for various types in clash-prelude.
312 VNeutral (NePrim pr args) -> do
313 let def = VNeutral (NeCase forcedSubject ty alts)
314 match <- findBestAlt (matchClashPrim pr args) alts
315 evalAlt def match
316
317 -- We know nothing: attempt case-of-case / case-of-let.
318 _ -> tryTransformCase forcedSubject ty alts
319
320 -- | Attempt to apply a transformation to a case expression to expose more
321 -- opportunities for caseCon. If no transformations can be applied the
322 -- case expression can only be neutral.
323 --
324 tryTransformCase :: Value -> Type -> [(Pat, Value)] -> Eval Value
325 tryTransformCase subject ty alts =
326 case stripValue subject of
327 -- A case of case: pull out the inner case expression if possible and
328 -- attempt caseCon on the new case expression.
329 VNeutral (NeCase innerSubject _ innerAlts) -> do
330 forcedAlts <- forceAlts innerAlts
331
332 if all (isKnown . snd) forcedAlts
333 then let asCase v = VNeutral (NeCase v ty alts)
334 newAlts = second asCase <$> innerAlts
335 in caseCon innerSubject ty newAlts
336
337 else pure (VNeutral (NeCase subject ty alts))
338
339 -- A case of let: Pull out the let expression if possible and attempt
340 -- caseCon on the new case expression.
341 VNeutral (NeLet bindings innerSubject) -> do
342 newCase <- caseCon innerSubject ty alts
343 pure (VNeutral (NeLet bindings newCase))
344
345 -- There is no way to continue evaluating the case, do nothing.
346 -- TODO elimExistentials here.
347 _ -> pure (VNeutral (NeCase subject ty alts))
348 where
349 -- We only care about case of case if alternatives of the inner case
350 -- expression correspond to something we can do caseCon on.
351 --
352 -- TODO We may also care if it is another case of case?
353 --
354 isKnown = \case
355 VNeutral (NePrim pr _) ->
356 primName pr `elem`
357 [ "Clash.Sized.Internal.BitVector.fromInteger##"
358 , "Clash.Sized.Internal.BitVector.fromInteger#"
359 , "Clash.Sized.Internal.Index.fromInteger#"
360 , "Clash.Sized.Internal.Signed.fromInteger#"
361 , "Clash.Sized.Internal.Unsigned.fromInteger#"
362 ]
363
364 VLiteral{} -> True
365 VData{} -> True
366 _ -> False
367
368 delayAlts :: [Alt] -> Eval [(Pat, Value)]
369 delayAlts = traverse (bitraverse delayPat delayEval)
370 where
371 delayPat = \case
372 DataPat dc tvs ids -> do
373 tvsTys <- traverse evalType (fmap varType tvs)
374 idsTys <- traverse evalType (fmap varType ids)
375
376 let setTy v ty = v { varType = ty }
377 tvs' = zipWith setTy tvs tvsTys
378 ids' = zipWith setTy ids idsTys
379
380 pure (DataPat dc tvs' ids')
381
382 pat -> pure pat
383
384 forceAlts :: [(Pat, Value)] -> Eval [(Pat, Value)]
385 forceAlts = traverse (traverse forceEval)
386
387 data PatResult
388 = Match (Pat, Value) [(TyVar, Type)] [(Id, Value)]
389 | NoMatch
390
391 evalAlt :: Value -> PatResult -> Eval Value
392 evalAlt def = \case
393 Match (_, val) tvs ids ->
394 forceEvalWith tvs ids val
395
396 NoMatch -> pure def
397
398 matchLiteral :: Literal -> (Pat, Value) -> Eval PatResult
399 matchLiteral lit alt@(pat, _) =
400 case pat of
401 DataPat dc [] [i]
402 | IntegerLiteral n <- lit
403 -> case n of
404 #if MIN_VERSION_base(4,15,0)
405 IS _
406 #else
407 S# _
408 #endif
409 | dcTag dc == 1 -> pure $ Match alt [] [(i, VLiteral (IntLiteral n))]
410
411 #if MIN_VERSION_base(4,15,0)
412 IP bn
413 #else
414 Jp# bn
415 #endif
416 | dcTag dc == 2 -> matchBigNat i bn
417
418 #if MIN_VERSION_base(4,15,0)
419 IN bn
420 #else
421 Jn# bn
422 #endif
423 | dcTag dc == 3 -> matchBigNat i bn
424
425 _ -> pure NoMatch
426
427 | NaturalLiteral n <- lit
428 -> case n of
429 #if MIN_VERSION_base(4,15,0)
430 IS _
431 #else
432 S# _
433 #endif
434 | dcTag dc == 1 -> pure $ Match alt [] [(i, VLiteral (WordLiteral n))]
435
436 #if MIN_VERSION_base(4,15,0)
437 IP bn
438 #else
439 Jp# bn
440 #endif
441 | dcTag dc == 2 -> matchBigNat i bn
442
443 _ -> pure NoMatch
444
445 LitPat n
446 | lit == n -> pure $ Match alt [] []
447
448 DefaultPat -> pure $ Match alt [] []
449
450 _ -> pure NoMatch
451 where
452 -- Somewhat of a hack: We find the constructor for BigNat and apply a
453 -- ByteArray literal made from the given ByteArray to it.
454 #if MIN_VERSION_base(4,15,0)
455 matchBigNat i ba = do
456 #else
457 matchBigNat i (BN# ba) = do
458 #endif
459 tcm <- getTyConMap
460 let bnDcM = do
461 integerTcName <- fmap fst (splitTyConAppM integerPrimTy)
462 [_, jpDc, _] <- pure (tyConDataCons (UniqMap.find integerTcName tcm))
463 ([bnTy], _) <- pure (splitFunTys tcm (dcType jpDc))
464 bnTcName <- fmap fst (splitTyConAppM bnTy)
465 listToMaybe (tyConDataCons (UniqMap.find bnTcName tcm))
466
467 bnDc = fromMaybe (error "Cannot find BigNat constructor") bnDcM
468
469 let arr = ByteArrayLiteral (ByteArray ba)
470 val <- VData bnDc [Left (VLiteral arr)] <$> getLocalEnv
471
472 pure (Match alt [] [(i, val)])
473
474 matchData :: DataCon -> Args Value -> (Pat, Value) -> Eval PatResult
475 matchData dc args alt@(pat, _) =
476 case pat of
477 DataPat c tvs ids
478 | dc == c
479 -> do let (tms, tys) = bimap (zip ids) (zip tvs) (partitionEithers args)
480 pure (Match alt tys tms)
481
482 DefaultPat -> pure (Match alt [] [])
483 _ -> pure NoMatch
484
485 -- TODO Should this also consider DataPat and data constructors?
486 -- The old evaluator did not, but matchData wouldn't cover it.
487 --
488 matchClashPrim :: PrimInfo -> Args Value -> (Pat, Value) -> Eval PatResult
489 matchClashPrim pr args alt@(pat, _) =
490 case pat of
491 LitPat lit
492 -- Bit literals
493 | primName pr == "Clash.Sized.BitVector.fromInteger##"
494 , [Left mask, Left val] <- args
495 -> do VLiteral (WordLiteral m) <- forceEval mask
496 VLiteral l <- forceEval val
497
498 if m == 0 && l == lit
499 then pure (Match alt [] [])
500 else pure NoMatch
501
502 -- BitVector literals
503 | primName pr == "Clash.Sized.BitVector.fromInteger#"
504 , [Right _n, Left _knN, Left mask, Left val] <- args
505 -> do VLiteral (NaturalLiteral m) <- forceEval mask
506 VLiteral l <- forceEval val
507
508 if m == 0 && l == lit
509 then pure (Match alt [] [])
510 else pure NoMatch
511
512 -- Sized integer / natural literals
513 | primName pr `elem` clashSizedNumbers
514 , [Right _n, Left _knN, Left val] <- args
515 -> do VLiteral l <- forceEval val
516
517 if l == lit
518 then pure (Match alt [] [])
519 else pure NoMatch
520
521 -- The primitive is not a literal from clash-prelude
522 _ -> pure NoMatch
523 where
524 clashSizedNumbers =
525 [ "Clash.Sized.Internal.Index.fromInteger#"
526 , "Clash.Sized.Internal.Signed.fromInteger#"
527 , "Clash.Sized.Internal.Unsigned.fromInteger#"
528 ]
529
530 -- | Given a predicate to check if an alternative is a match, find the best
531 -- alternative that matches the predicate. Best is defined as being the most
532 -- specific matching pattern (meaning DefaultPat is only used if no other
533 -- pattern tried matches).
534 --
535 findBestAlt
536 :: ((Pat, Value) -> Eval PatResult)
537 -> [(Pat, Value)]
538 -> Eval PatResult
539 findBestAlt checkAlt =
540 go NoMatch
541 where
542 go !acc [] = pure acc
543 go !acc (a:as) = do
544 match <- checkAlt a
545 case match of
546 Match (pat, _term) _tvs _ids
547 | pat == DefaultPat -> go match as
548 | otherwise -> pure match
549
550 NoMatch -> go acc as
551
552 evalCast :: Term -> Type -> Type -> Eval Value
553 evalCast x a b = VCast <$> eval x <*> evalType a <*> evalType b
554
555 evalTick :: TickInfo -> Term -> Eval Value
556 evalTick tick x = VTick <$> eval x <*> pure tick
557
558 applyArg :: Value -> Arg Value -> Eval Value
559 applyArg val =
560 either (apply val) (applyTy val)
561
562 apply :: Value -> Value -> Eval Value
563 apply val arg = do
564 tcm <- getTyConMap
565 forced <- forceEval val
566 canApply <- workFreeValue arg
567
568 case stripValue forced of
569 -- If the LHS of application evaluates to a letrec, then add any bindings
570 -- that do work to this letrec instead of creating a new one.
571 VNeutral (NeLet bs x)
572 | canApply -> do
573 inner <- apply x arg
574 pure (VNeutral (NeLet bs inner))
575
576 | otherwise -> do
577 varTy <- evalType (valueType tcm arg)
578 var <- getUniqueId "workArg" varTy
579 inner <- apply x (VNeutral (NeVar var))
580 pure (VNeutral (NeLet bs (VNeutral (NeLet (NonRec var arg) inner))))
581
582 -- If the LHS of application is neutral, make a letrec around the neutral
583 -- application if the argument performs work.
584 VNeutral neu
585 | canApply -> pure (VNeutral (NeApp neu arg))
586 | otherwise -> do
587 varTy <- evalType (valueType tcm arg)
588 var <- getUniqueId "workArg" varTy
589 let inner = VNeutral (NeApp neu (VNeutral (NeVar var)))
590 pure (VNeutral (NeLet (NonRec var arg) inner))
591
592 -- If the LHS of application is a lambda, make a letrec with the name of
593 -- the argument around the result of evaluation if it performs work.
594 VLam i x env
595 | canApply -> setLocalEnv env $ withId i arg (eval x)
596 | otherwise -> setLocalEnv env $ do
597 inner <- withId i arg (eval x)
598 pure (VNeutral (NeLet (NonRec i arg) inner))
599
600 f ->
601 error ("apply: Cannot apply " <> show arg <> " to " <> show f)
602 where
603 -- TODO Write an instance for InferType Value and use that instead
604 valueType tcm = inferCoreTypeOf tcm . asTerm
605
606 applyTy :: Value -> Type -> Eval Value
607 applyTy val ty = do
608 forcedVal <- forceEval val
609 argTy <- evalType ty
610
611 case stripValue forcedVal of
612 VNeutral n ->
613 pure (VNeutral (NeTyApp n argTy))
614
615 VTyLam i x env ->
616 setLocalEnv env $ withTyVar i argTy (eval x)
617
618 f ->
619 error ("applyTy: Cannot apply " <> show argTy <> " to " <> show f)