Vectorisation of method types
[ghc-hetmet.git] / compiler / vectorise / VectUtils.hs
1 module VectUtils (
2   collectAnnTypeBinders, collectAnnTypeArgs, isAnnTypeArg,
3   collectAnnValBinders,
4   dataConTagZ, mkDataConTag, mkDataConTagLit,
5
6   newLocalVVar,
7
8   mkBuiltinCo, voidType, mkWrapType,
9   mkPADictType, mkPArrayType, mkPDataType, mkPReprType, mkPArray,
10
11   pdataReprTyCon, pdataReprDataCon, mkVScrut,
12   prDictOfType, prDFunOfTyCon,
13   paDictArgType, paDictOfType, paDFunType,
14   paMethod, wrapPR, replicatePD, emptyPD, packByTagPD,
15   combinePD,
16   liftPD,
17   zipScalars, scalarClosure,
18   polyAbstract, polyApply, polyVApply, polyArity,
19   Inline(..), addInlineArity, inlineMe,
20   hoistBinding, hoistExpr, hoistPolyVExpr, takeHoisted,
21   buildClosure, buildClosures,
22   mkClosureApp
23 ) where
24
25 import VectCore
26 import VectMonad
27
28 import MkCore ( mkCoreTup, mkWildCase )
29 import CoreSyn
30 import CoreUtils
31 import CoreUnfold         ( mkInlineRule )
32 import Coercion
33 import Type
34 import TypeRep
35 import TyCon
36 import DataCon
37 import Var
38 import MkId               ( unwrapFamInstScrut )
39 import Id                 ( setIdUnfolding )
40 import TysWiredIn
41 import BasicTypes         ( Boxity(..), Arity )
42 import Literal            ( Literal, mkMachInt )
43
44 import Outputable
45 import FastString
46
47 import Control.Monad
48
49 collectAnnTypeArgs :: AnnExpr b ann -> (AnnExpr b ann, [Type])
50 collectAnnTypeArgs expr = go expr []
51   where
52     go (_, AnnApp f (_, AnnType ty)) tys = go f (ty : tys)
53     go e                             tys = (e, tys)
54
55 collectAnnTypeBinders :: AnnExpr Var ann -> ([Var], AnnExpr Var ann)
56 collectAnnTypeBinders expr = go [] expr
57   where
58     go bs (_, AnnLam b e) | isTyVar b = go (b:bs) e
59     go bs e                           = (reverse bs, e)
60
61 collectAnnValBinders :: AnnExpr Var ann -> ([Var], AnnExpr Var ann)
62 collectAnnValBinders expr = go [] expr
63   where
64     go bs (_, AnnLam b e) | isId b = go (b:bs) e
65     go bs e                        = (reverse bs, e)
66
67 isAnnTypeArg :: AnnExpr b ann -> Bool
68 isAnnTypeArg (_, AnnType _) = True
69 isAnnTypeArg _              = False
70
71 dataConTagZ :: DataCon -> Int
72 dataConTagZ con = dataConTag con - fIRST_TAG
73
74 mkDataConTagLit :: DataCon -> Literal
75 mkDataConTagLit = mkMachInt . toInteger . dataConTagZ
76
77 mkDataConTag :: DataCon -> CoreExpr
78 mkDataConTag = mkIntLitInt . dataConTagZ
79
80 splitPrimTyCon :: Type -> Maybe TyCon
81 splitPrimTyCon ty
82   | Just (tycon, []) <- splitTyConApp_maybe ty
83   , isPrimTyCon tycon
84   = Just tycon
85
86   | otherwise = Nothing
87
88 mkBuiltinTyConApp :: (Builtins -> TyCon) -> [Type] -> VM Type
89 mkBuiltinTyConApp get_tc tys
90   = do
91       tc <- builtin get_tc
92       return $ mkTyConApp tc tys
93
94 mkBuiltinTyConApps :: (Builtins -> TyCon) -> [Type] -> Type -> VM Type
95 mkBuiltinTyConApps get_tc tys ty
96   = do
97       tc <- builtin get_tc
98       return $ foldr (mk tc) ty tys
99   where
100     mk tc ty1 ty2 = mkTyConApp tc [ty1,ty2]
101
102 voidType :: VM Type
103 voidType = mkBuiltinTyConApp VectMonad.voidTyCon []
104
105 mkWrapType :: Type -> VM Type
106 mkWrapType ty = mkBuiltinTyConApp wrapTyCon [ty]
107
108 mkClosureTypes :: [Type] -> Type -> VM Type
109 mkClosureTypes = mkBuiltinTyConApps closureTyCon
110
111 mkPReprType :: Type -> VM Type
112 mkPReprType ty = mkBuiltinTyConApp preprTyCon [ty]
113
114 mkPADictType :: Type -> VM Type
115 mkPADictType ty = mkBuiltinTyConApp paTyCon [ty]
116
117 mkPArrayType :: Type -> VM Type
118 mkPArrayType ty
119   | Just tycon <- splitPrimTyCon ty
120   = do
121       r <- lookupPrimPArray tycon
122       case r of
123         Just arr -> return $ mkTyConApp arr []
124         Nothing  -> cantVectorise "Primitive tycon not vectorised" (ppr tycon)
125 mkPArrayType ty = mkBuiltinTyConApp parrayTyCon [ty]
126
127 mkPDataType :: Type -> VM Type
128 mkPDataType ty = mkBuiltinTyConApp pdataTyCon [ty]
129
130 mkPArray :: Type -> CoreExpr -> CoreExpr -> VM CoreExpr
131 mkPArray ty len dat = do
132                         tc <- builtin parrayTyCon
133                         let [dc] = tyConDataCons tc
134                         return $ mkConApp dc [Type ty, len, dat]
135
136 mkBuiltinCo :: (Builtins -> TyCon) -> VM Coercion
137 mkBuiltinCo get_tc
138   = do
139       tc <- builtin get_tc
140       return $ mkTyConApp tc []
141
142 pdataReprTyCon :: Type -> VM (TyCon, [Type])
143 pdataReprTyCon ty = builtin pdataTyCon >>= (`lookupFamInst` [ty])
144
145 pdataReprDataCon :: Type -> VM (DataCon, [Type])
146 pdataReprDataCon ty
147   = do
148       (tc, arg_tys) <- pdataReprTyCon ty
149       let [dc] = tyConDataCons tc
150       return (dc, arg_tys)
151
152 mkVScrut :: VExpr -> VM (CoreExpr, CoreExpr, TyCon, [Type])
153 mkVScrut (ve, le)
154   = do
155       (tc, arg_tys) <- pdataReprTyCon ty
156       return (ve, unwrapFamInstScrut tc arg_tys le, tc, arg_tys)
157   where
158     ty = exprType ve
159
160 prDFunOfTyCon :: TyCon -> VM CoreExpr
161 prDFunOfTyCon tycon
162   = liftM Var
163   . maybeCantVectoriseM "No PR dictionary for tycon" (ppr tycon)
164   $ lookupTyConPR tycon
165
166
167 paDictArgType :: TyVar -> VM (Maybe Type)
168 paDictArgType tv = go (TyVarTy tv) (tyVarKind tv)
169   where
170     go ty k | Just k' <- kindView k = go ty k'
171     go ty (FunTy k1 k2)
172       = do
173           tv   <- newTyVar (fsLit "a") k1
174           mty1 <- go (TyVarTy tv) k1
175           case mty1 of
176             Just ty1 -> do
177                           mty2 <- go (AppTy ty (TyVarTy tv)) k2
178                           return $ fmap (ForAllTy tv . FunTy ty1) mty2
179             Nothing  -> go ty k2
180
181     go ty k
182       | isLiftedTypeKind k
183       = liftM Just (mkPADictType ty)
184
185     go _ _ = return Nothing
186
187
188 -- | Get the PA dictionary for some type, or `Nothing` if there isn't one.
189 paDictOfType :: Type -> VM (Maybe CoreExpr)
190 paDictOfType ty 
191   = paDictOfTyApp ty_fn ty_args
192   where
193     (ty_fn, ty_args) = splitAppTys ty
194
195     paDictOfTyApp :: Type -> [Type] -> VM (Maybe CoreExpr)
196     paDictOfTyApp ty_fn ty_args
197         | Just ty_fn' <- coreView ty_fn 
198         = paDictOfTyApp ty_fn' ty_args
199
200     paDictOfTyApp (TyVarTy tv) ty_args
201      = do dfun <- maybeV (lookupTyVarPA tv)
202           liftM Just $ paDFunApply dfun ty_args
203
204     paDictOfTyApp (TyConApp tc _) ty_args
205      = do mdfun <- lookupTyConPA tc
206           case mdfun of
207             Nothing     
208              -> pprTrace "VectUtils.paDictOfType"
209                          (vcat [ text "No PA dictionary"
210                                , text "for tycon: " <> ppr tc
211                                , text "in type:   " <> ppr ty])
212              $ return Nothing
213
214             Just dfun   -> liftM Just $ paDFunApply (Var dfun) ty_args
215
216     paDictOfTyApp ty _
217      = cantVectorise "Can't construct PA dictionary for type" (ppr ty)
218
219
220
221 paDFunType :: TyCon -> VM Type
222 paDFunType tc
223   = do
224       margs <- mapM paDictArgType tvs
225       res   <- mkPADictType (mkTyConApp tc arg_tys)
226       return . mkForAllTys tvs
227              $ mkFunTys [arg | Just arg <- margs] res
228   where
229     tvs = tyConTyVars tc
230     arg_tys = mkTyVarTys tvs
231
232 paDFunApply :: CoreExpr -> [Type] -> VM CoreExpr
233 paDFunApply dfun tys
234  = do Just dicts <- liftM sequence $ mapM paDictOfType tys
235       return $ mkApps (mkTyApps dfun tys) dicts
236
237
238 paMethod :: (Builtins -> Var) -> String -> Type -> VM CoreExpr
239 paMethod _ name ty
240   | Just tycon <- splitPrimTyCon ty
241   = liftM Var
242   . maybeCantVectoriseM "No PA method" (text name <+> text "for" <+> ppr tycon)
243   $ lookupPrimMethod tycon name
244
245 paMethod method _ ty
246   = do
247       fn        <- builtin method
248       Just dict <- paDictOfType ty
249       return $ mkApps (Var fn) [Type ty, dict]
250
251 prDictOfType :: Type -> VM CoreExpr
252 prDictOfType ty = prDictOfTyApp ty_fn ty_args
253   where
254     (ty_fn, ty_args) = splitAppTys ty
255
256 prDictOfTyApp :: Type -> [Type] -> VM CoreExpr
257 prDictOfTyApp ty_fn ty_args
258   | Just ty_fn' <- coreView ty_fn = prDictOfTyApp ty_fn' ty_args
259 prDictOfTyApp (TyConApp tc _) ty_args
260   = do
261       dfun <- liftM Var $ maybeV (lookupTyConPR tc)
262       prDFunApply dfun ty_args
263 prDictOfTyApp _ _ = noV
264
265 prDFunApply :: CoreExpr -> [Type] -> VM CoreExpr
266 prDFunApply dfun tys
267   = do
268       dicts <- mapM prDictOfType tys
269       return $ mkApps (mkTyApps dfun tys) dicts
270
271 wrapPR :: Type -> VM CoreExpr
272 wrapPR ty
273   = do
274       Just  pa_dict <- paDictOfType ty
275       pr_dfun       <- prDFunOfTyCon =<< builtin wrapTyCon
276       return $ mkApps pr_dfun [Type ty, pa_dict]
277
278 replicatePD :: CoreExpr -> CoreExpr -> VM CoreExpr
279 replicatePD len x = liftM (`mkApps` [len,x])
280                           (paMethod replicatePDVar "replicatePD" (exprType x))
281
282 emptyPD :: Type -> VM CoreExpr
283 emptyPD = paMethod emptyPDVar "emptyPD"
284
285 packByTagPD :: Type -> CoreExpr -> CoreExpr -> CoreExpr -> CoreExpr
286                  -> VM CoreExpr
287 packByTagPD ty xs len tags t
288   = liftM (`mkApps` [xs, len, tags, t])
289           (paMethod packByTagPDVar "packByTagPD" ty)
290
291 combinePD :: Type -> CoreExpr -> CoreExpr -> [CoreExpr]
292           -> VM CoreExpr
293 combinePD ty len sel xs
294   = liftM (`mkApps` (len : sel : xs))
295           (paMethod (combinePDVar n) ("combine" ++ show n ++ "PD") ty)
296   where
297     n = length xs
298
299 -- | Like `replicatePD` but use the lifting context in the vectoriser state.
300 liftPD :: CoreExpr -> VM CoreExpr
301 liftPD x
302   = do
303       lc <- builtin liftingContext
304       replicatePD (Var lc) x
305
306 zipScalars :: [Type] -> Type -> VM CoreExpr
307 zipScalars arg_tys res_ty
308   = do
309       scalar <- builtin scalarClass
310       (dfuns, _) <- mapAndUnzipM (\ty -> lookupInst scalar [ty]) ty_args
311       zipf <- builtin (scalarZip $ length arg_tys)
312       return $ Var zipf `mkTyApps` ty_args `mkApps` map Var dfuns
313     where
314       ty_args = arg_tys ++ [res_ty]
315
316 scalarClosure :: [Type] -> Type -> CoreExpr -> CoreExpr -> VM CoreExpr
317 scalarClosure arg_tys res_ty scalar_fun array_fun
318   = do
319       ctr      <- builtin (closureCtrFun $ length arg_tys)
320       Just pas <- liftM sequence $ mapM paDictOfType (init arg_tys)
321       return $ Var ctr `mkTyApps` (arg_tys ++ [res_ty])
322                        `mkApps`   (pas ++ [scalar_fun, array_fun])
323
324 newLocalVVar :: FastString -> Type -> VM VVar
325 newLocalVVar fs vty
326   = do
327       lty <- mkPDataType vty
328       vv  <- newLocalVar fs vty
329       lv  <- newLocalVar fs lty
330       return (vv,lv)
331
332 polyAbstract :: [TyVar] -> ([Var] -> VM a) -> VM a
333 polyAbstract tvs p
334   = localV
335   $ do
336       mdicts <- mapM mk_dict_var tvs
337       zipWithM_ (\tv -> maybe (defLocalTyVar tv)
338                               (defLocalTyVarWithPA tv . Var)) tvs mdicts
339       p (mk_args mdicts)
340   where
341     mk_dict_var tv = do
342                        r <- paDictArgType tv
343                        case r of
344                          Just ty -> liftM Just (newLocalVar (fsLit "dPA") ty)
345                          Nothing -> return Nothing
346
347     mk_args mdicts = [dict | Just dict <- mdicts]
348
349 polyArity :: [TyVar] -> VM Int
350 polyArity tvs = do
351                   tys <- mapM paDictArgType tvs
352                   return $ length [() | Just _ <- tys]
353
354 polyApply :: CoreExpr -> [Type] -> VM CoreExpr
355 polyApply expr tys
356  = do Just dicts <- liftM sequence $ mapM paDictOfType tys
357       return $ expr `mkTyApps` tys `mkApps` dicts
358
359 polyVApply :: VExpr -> [Type] -> VM VExpr
360 polyVApply expr tys
361  = do Just dicts <- liftM sequence $ mapM paDictOfType tys
362       return     $ mapVect (\e -> e `mkTyApps` tys `mkApps` dicts) expr
363
364 -- Inline ---------------------------------------------------------------------
365 -- | Records whether we should inline a particular binding.
366 data Inline 
367         = Inline Arity
368         | DontInline
369
370 -- | Add to the arity contained within an `Inline`, if any.
371 addInlineArity :: Inline -> Int -> Inline
372 addInlineArity (Inline m) n = Inline (m+n)
373 addInlineArity DontInline _ = DontInline
374
375 -- | Says to always inline a binding.
376 inlineMe :: Inline
377 inlineMe = Inline 0
378
379
380 -- Hoising --------------------------------------------------------------------
381 hoistBinding :: Var -> CoreExpr -> VM ()
382 hoistBinding v e = updGEnv $ \env ->
383   env { global_bindings = (v,e) : global_bindings env }
384
385 hoistExpr :: FastString -> CoreExpr -> Inline -> VM Var
386 hoistExpr fs expr inl
387   = do
388       var <- mk_inline `liftM` newLocalVar fs (exprType expr)
389       hoistBinding var expr
390       return var
391   where
392     mk_inline var = case inl of
393                       Inline arity -> var `setIdUnfolding`
394                                       mkInlineRule expr (Just arity)
395                       DontInline   -> var
396
397 hoistVExpr :: VExpr -> Inline -> VM VVar
398 hoistVExpr (ve, le) inl
399   = do
400       fs <- getBindName
401       vv <- hoistExpr ('v' `consFS` fs) ve inl
402       lv <- hoistExpr ('l' `consFS` fs) le (addInlineArity inl 1)
403       return (vv, lv)
404
405 hoistPolyVExpr :: [TyVar] -> Inline -> VM VExpr -> VM VExpr
406 hoistPolyVExpr tvs inline p
407   = do
408       inline' <- liftM (addInlineArity inline) (polyArity tvs)
409       expr <- closedV . polyAbstract tvs $ \args ->
410               liftM (mapVect (mkLams $ tvs ++ args)) p
411       fn   <- hoistVExpr expr inline'
412       polyVApply (vVar fn) (mkTyVarTys tvs)
413
414 takeHoisted :: VM [(Var, CoreExpr)]
415 takeHoisted
416   = do
417       env <- readGEnv id
418       setGEnv $ env { global_bindings = [] }
419       return $ global_bindings env
420
421 {-
422 boxExpr :: Type -> VExpr -> VM VExpr
423 boxExpr ty (vexpr, lexpr)
424   | Just (tycon, []) <- splitTyConApp_maybe ty
425   , isUnLiftedTyCon tycon
426   = do
427       r <- lookupBoxedTyCon tycon
428       case r of
429         Just tycon' -> let [dc] = tyConDataCons tycon'
430                        in
431                        return (mkConApp dc [vexpr], lexpr)
432         Nothing     -> return (vexpr, lexpr)
433 -}
434
435 -- Closures -------------------------------------------------------------------
436 mkClosure :: Type -> Type -> Type -> VExpr -> VExpr -> VM VExpr
437 mkClosure arg_ty res_ty env_ty (vfn,lfn) (venv,lenv)
438  = do Just dict <- paDictOfType env_ty
439       mkv       <- builtin closureVar
440       mkl       <- builtin liftedClosureVar
441       return (Var mkv `mkTyApps` [arg_ty, res_ty, env_ty] `mkApps` [dict, vfn, lfn, venv],
442               Var mkl `mkTyApps` [arg_ty, res_ty, env_ty] `mkApps` [dict, vfn, lfn, lenv])
443
444
445 mkClosureApp :: Type -> Type -> VExpr -> VExpr -> VM VExpr
446 mkClosureApp arg_ty res_ty (vclo, lclo) (varg, larg)
447  = do vapply <- builtin applyVar
448       lapply <- builtin liftedApplyVar
449       lc     <- builtin liftingContext
450       return (Var vapply `mkTyApps` [arg_ty, res_ty] `mkApps` [vclo, varg],
451               Var lapply `mkTyApps` [arg_ty, res_ty] `mkApps` [Var lc, lclo, larg])
452
453
454 buildClosures :: [TyVar] -> [VVar] -> [Type] -> Type -> VM VExpr -> VM VExpr
455 buildClosures _   _    [] _ mk_body
456   = mk_body
457 buildClosures tvs vars [arg_ty] res_ty mk_body
458   = -- liftM vInlineMe $
459       buildClosure tvs vars arg_ty res_ty mk_body
460 buildClosures tvs vars (arg_ty : arg_tys) res_ty mk_body
461   = do
462       res_ty' <- mkClosureTypes arg_tys res_ty
463       arg <- newLocalVVar (fsLit "x") arg_ty
464       -- liftM vInlineMe
465       buildClosure tvs vars arg_ty res_ty'
466         . hoistPolyVExpr tvs (Inline (length vars + 1))
467         $ do
468             lc <- builtin liftingContext
469             clo <- buildClosures tvs (vars ++ [arg]) arg_tys res_ty mk_body
470             return $ vLams lc (vars ++ [arg]) clo
471
472 -- (clo <x1,...,xn> <f,f^>, aclo (Arr lc xs1 ... xsn) <f,f^>)
473 --   where
474 --     f  = \env v -> case env of <x1,...,xn> -> e x1 ... xn v
475 --     f^ = \env v -> case env of Arr l xs1 ... xsn -> e^ l x1 ... xn v
476 --
477 buildClosure :: [TyVar] -> [VVar] -> Type -> Type -> VM VExpr -> VM VExpr
478 buildClosure tvs vars arg_ty res_ty mk_body
479   = do
480       (env_ty, env, bind) <- buildEnv vars
481       env_bndr <- newLocalVVar (fsLit "env") env_ty
482       arg_bndr <- newLocalVVar (fsLit "arg") arg_ty
483
484       fn <- hoistPolyVExpr tvs (Inline 2)
485           $ do
486               lc    <- builtin liftingContext
487               body  <- mk_body
488               return -- . vInlineMe
489                      . vLams lc [env_bndr, arg_bndr]
490                      $ bind (vVar env_bndr)
491                             (vVarApps lc body (vars ++ [arg_bndr]))
492
493       mkClosure arg_ty res_ty env_ty fn env
494
495
496 -- Environments ---------------------------------------------------------------
497 buildEnv :: [VVar] -> VM (Type, VExpr, VExpr -> VExpr -> VExpr)
498 buildEnv [] = do
499              ty    <- voidType
500              void  <- builtin voidVar
501              pvoid <- builtin pvoidVar
502              return (ty, vVar (void, pvoid), \_ body -> body)
503
504 buildEnv [v] = return (vVarType v, vVar v,
505                     \env body -> vLet (vNonRec v env) body)
506
507 buildEnv vs
508   = do
509       
510       (lenv_tc, lenv_tyargs) <- pdataReprTyCon ty
511
512       let venv_con   = tupleCon Boxed (length vs) 
513           [lenv_con] = tyConDataCons lenv_tc
514
515           venv       = mkCoreTup (map Var vvs)
516           lenv       = Var (dataConWrapId lenv_con)
517                        `mkTyApps` lenv_tyargs
518                        `mkApps`   map Var lvs
519
520           vbind env body = mkWildCase env ty (exprType body)
521                            [(DataAlt venv_con, vvs, body)]
522
523           lbind env body =
524             let scrut = unwrapFamInstScrut lenv_tc lenv_tyargs env
525             in
526             mkWildCase scrut (exprType scrut) (exprType body)
527               [(DataAlt lenv_con, lvs, body)]
528
529           bind (venv, lenv) (vbody, lbody) = (vbind venv vbody,
530                                               lbind lenv lbody)
531
532       return (ty, (venv, lenv), bind)
533   where
534     (vvs, lvs) = unzip vs
535     tys        = map vVarType vs
536     ty         = mkBoxedTupleTy tys
537