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