Fix warnings
[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,
9   mkPADictType, mkPArrayType, mkPDataType, mkPReprType, mkPArray,
10
11   pdataReprTyCon, pdataReprDataCon, mkVScrut,
12   prDFunOfTyCon,
13   paDictArgType, paDictOfType, paDFunType,
14   paMethod, mkPR, 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 voidTyCon []
102
103 mkClosureTypes :: [Type] -> Type -> VM Type
104 mkClosureTypes = mkBuiltinTyConApps closureTyCon
105
106 mkPReprType :: Type -> VM Type
107 mkPReprType ty = mkBuiltinTyConApp preprTyCon [ty]
108
109 mkPADictType :: Type -> VM Type
110 mkPADictType ty = mkBuiltinTyConApp paTyCon [ty]
111
112 mkPArrayType :: Type -> VM Type
113 mkPArrayType ty
114   | Just tycon <- splitPrimTyCon ty
115   = do
116       r <- lookupPrimPArray tycon
117       case r of
118         Just arr -> return $ mkTyConApp arr []
119         Nothing  -> cantVectorise "Primitive tycon not vectorised" (ppr tycon)
120 mkPArrayType ty = mkBuiltinTyConApp parrayTyCon [ty]
121
122 mkPDataType :: Type -> VM Type
123 mkPDataType ty = mkBuiltinTyConApp pdataTyCon [ty]
124
125 mkPArray :: Type -> CoreExpr -> CoreExpr -> VM CoreExpr
126 mkPArray ty len dat = do
127                         tc <- builtin parrayTyCon
128                         let [dc] = tyConDataCons tc
129                         return $ mkConApp dc [Type ty, len, dat]
130
131 mkBuiltinCo :: (Builtins -> TyCon) -> VM Coercion
132 mkBuiltinCo get_tc
133   = do
134       tc <- builtin get_tc
135       return $ mkTyConApp tc []
136
137 pdataReprTyCon :: Type -> VM (TyCon, [Type])
138 pdataReprTyCon ty = builtin pdataTyCon >>= (`lookupFamInst` [ty])
139
140 pdataReprDataCon :: Type -> VM (DataCon, [Type])
141 pdataReprDataCon ty
142   = do
143       (tc, arg_tys) <- pdataReprTyCon ty
144       let [dc] = tyConDataCons tc
145       return (dc, arg_tys)
146
147 mkVScrut :: VExpr -> VM (CoreExpr, CoreExpr, TyCon, [Type])
148 mkVScrut (ve, le)
149   = do
150       (tc, arg_tys) <- pdataReprTyCon ty
151       return (ve, unwrapFamInstScrut tc arg_tys le, tc, arg_tys)
152   where
153     ty = exprType ve
154
155 prDFunOfTyCon :: TyCon -> VM CoreExpr
156 prDFunOfTyCon tycon
157   = liftM Var
158   . maybeCantVectoriseM "No PR dictionary for tycon" (ppr tycon)
159   $ lookupTyConPR tycon
160
161 paDictArgType :: TyVar -> VM (Maybe Type)
162 paDictArgType tv = go (TyVarTy tv) (tyVarKind tv)
163   where
164     go ty k | Just k' <- kindView k = go ty k'
165     go ty (FunTy k1 k2)
166       = do
167           tv   <- newTyVar (fsLit "a") k1
168           mty1 <- go (TyVarTy tv) k1
169           case mty1 of
170             Just ty1 -> do
171                           mty2 <- go (AppTy ty (TyVarTy tv)) k2
172                           return $ fmap (ForAllTy tv . FunTy ty1) mty2
173             Nothing  -> go ty k2
174
175     go ty k
176       | isLiftedTypeKind k
177       = liftM Just (mkPADictType ty)
178
179     go _ _ = return Nothing
180
181 paDictOfType :: Type -> VM CoreExpr
182 paDictOfType ty = paDictOfTyApp ty_fn ty_args
183   where
184     (ty_fn, ty_args) = splitAppTys ty
185
186 paDictOfTyApp :: Type -> [Type] -> VM CoreExpr
187 paDictOfTyApp ty_fn ty_args
188   | Just ty_fn' <- coreView ty_fn = paDictOfTyApp ty_fn' ty_args
189 paDictOfTyApp (TyVarTy tv) ty_args
190   = do
191       dfun <- maybeV (lookupTyVarPA tv)
192       paDFunApply dfun ty_args
193 paDictOfTyApp (TyConApp tc _) ty_args
194   = do
195       dfun <- maybeCantVectoriseM "No PA dictionary for tycon" (ppr tc)
196             $ lookupTyConPA tc
197       paDFunApply (Var dfun) ty_args
198 paDictOfTyApp ty _
199   = cantVectorise "Can't construct PA dictionary for type" (ppr ty)
200
201 paDFunType :: TyCon -> VM Type
202 paDFunType tc
203   = do
204       margs <- mapM paDictArgType tvs
205       res   <- mkPADictType (mkTyConApp tc arg_tys)
206       return . mkForAllTys tvs
207              $ mkFunTys [arg | Just arg <- margs] res
208   where
209     tvs = tyConTyVars tc
210     arg_tys = mkTyVarTys tvs
211
212 paDFunApply :: CoreExpr -> [Type] -> VM CoreExpr
213 paDFunApply dfun tys
214   = do
215       dicts <- mapM paDictOfType tys
216       return $ mkApps (mkTyApps dfun tys) dicts
217
218 paMethod :: (Builtins -> Var) -> String -> Type -> VM CoreExpr
219 paMethod _ name ty
220   | Just tycon <- splitPrimTyCon ty
221   = liftM Var
222   . maybeCantVectoriseM "No PA method" (text name <+> text "for" <+> ppr tycon)
223   $ lookupPrimMethod tycon name
224
225 paMethod method _ ty
226   = do
227       fn   <- builtin method
228       dict <- paDictOfType ty
229       return $ mkApps (Var fn) [Type ty, dict]
230
231 mkPR :: Type -> VM CoreExpr
232 mkPR ty
233   = do
234       fn   <- builtin mkPRVar
235       dict <- paDictOfType ty
236       return $ mkApps (Var fn) [Type ty, dict]
237
238 replicatePD :: CoreExpr -> CoreExpr -> VM CoreExpr
239 replicatePD len x = liftM (`mkApps` [len,x])
240                           (paMethod replicatePDVar "replicatePD" (exprType x))
241
242 emptyPD :: Type -> VM CoreExpr
243 emptyPD = paMethod emptyPDVar "emptyPD"
244
245 packPD :: Type -> CoreExpr -> CoreExpr -> CoreExpr -> VM CoreExpr
246 packPD ty xs len sel = liftM (`mkApps` [xs, len, sel])
247                              (paMethod packPDVar "packPD" ty)
248
249 combinePD :: Type -> CoreExpr -> CoreExpr -> [CoreExpr]
250           -> VM CoreExpr
251 combinePD ty len sel xs
252   = liftM (`mkApps` (len : sel : xs))
253           (paMethod (combinePDVar n) ("combine" ++ show n ++ "PD") ty)
254   where
255     n = length xs
256
257 liftPD :: CoreExpr -> VM CoreExpr
258 liftPD x
259   = do
260       lc <- builtin liftingContext
261       replicatePD (Var lc) x
262
263 zipScalars :: [Type] -> Type -> VM CoreExpr
264 zipScalars arg_tys res_ty
265   = do
266       scalar <- builtin scalarClass
267       (dfuns, _) <- mapAndUnzipM (\ty -> lookupInst scalar [ty]) ty_args
268       zipf <- builtin (scalarZip $ length arg_tys)
269       return $ Var zipf `mkTyApps` ty_args `mkApps` map Var dfuns
270     where
271       ty_args = arg_tys ++ [res_ty]
272
273 scalarClosure :: [Type] -> Type -> CoreExpr -> CoreExpr -> VM CoreExpr
274 scalarClosure arg_tys res_ty scalar_fun array_fun
275   = do
276       ctr <- builtin (closureCtrFun $ length arg_tys)
277       pas <- mapM paDictOfType (init arg_tys)
278       return $ Var ctr `mkTyApps` (arg_tys ++ [res_ty])
279                        `mkApps`   (pas ++ [scalar_fun, array_fun])
280
281 newLocalVVar :: FastString -> Type -> VM VVar
282 newLocalVVar fs vty
283   = do
284       lty <- mkPDataType vty
285       vv  <- newLocalVar fs vty
286       lv  <- newLocalVar fs lty
287       return (vv,lv)
288
289 polyAbstract :: [TyVar] -> ((CoreExpr -> CoreExpr) -> VM a) -> VM a
290 polyAbstract tvs p
291   = localV
292   $ do
293       mdicts <- mapM mk_dict_var tvs
294       zipWithM_ (\tv -> maybe (defLocalTyVar tv) (defLocalTyVarWithPA tv . Var)) tvs mdicts
295       p (mk_lams mdicts)
296   where
297     mk_dict_var tv = do
298                        r <- paDictArgType tv
299                        case r of
300                          Just ty -> liftM Just (newLocalVar (fsLit "dPA") ty)
301                          Nothing -> return Nothing
302
303     mk_lams mdicts = mkLams (tvs ++ [dict | Just dict <- mdicts])
304
305 polyApply :: CoreExpr -> [Type] -> VM CoreExpr
306 polyApply expr tys
307   = do
308       dicts <- mapM paDictOfType tys
309       return $ expr `mkTyApps` tys `mkApps` dicts
310
311 polyVApply :: VExpr -> [Type] -> VM VExpr
312 polyVApply expr tys
313   = do
314       dicts <- mapM paDictOfType tys
315       return $ mapVect (\e -> e `mkTyApps` tys `mkApps` dicts) expr
316
317 hoistBinding :: Var -> CoreExpr -> VM ()
318 hoistBinding v e = updGEnv $ \env ->
319   env { global_bindings = (v,e) : global_bindings env }
320
321 hoistExpr :: FastString -> CoreExpr -> VM Var
322 hoistExpr fs expr
323   = do
324       var <- newLocalVar fs (exprType expr)
325       hoistBinding var expr
326       return var
327
328 hoistVExpr :: VExpr -> VM VVar
329 hoistVExpr (ve, le)
330   = do
331       fs <- getBindName
332       vv <- hoistExpr ('v' `consFS` fs) ve
333       lv <- hoistExpr ('l' `consFS` fs) le
334       return (vv, lv)
335
336 hoistPolyVExpr :: [TyVar] -> VM VExpr -> VM VExpr
337 hoistPolyVExpr tvs p
338   = do
339       expr <- closedV . polyAbstract tvs $ \abstract ->
340               liftM (mapVect abstract) p
341       fn   <- hoistVExpr expr
342       polyVApply (vVar fn) (mkTyVarTys tvs)
343
344 takeHoisted :: VM [(Var, CoreExpr)]
345 takeHoisted
346   = do
347       env <- readGEnv id
348       setGEnv $ env { global_bindings = [] }
349       return $ global_bindings env
350
351 {-
352 boxExpr :: Type -> VExpr -> VM VExpr
353 boxExpr ty (vexpr, lexpr)
354   | Just (tycon, []) <- splitTyConApp_maybe ty
355   , isUnLiftedTyCon tycon
356   = do
357       r <- lookupBoxedTyCon tycon
358       case r of
359         Just tycon' -> let [dc] = tyConDataCons tycon'
360                        in
361                        return (mkConApp dc [vexpr], lexpr)
362         Nothing     -> return (vexpr, lexpr)
363 -}
364
365 mkClosure :: Type -> Type -> Type -> VExpr -> VExpr -> VM VExpr
366 mkClosure arg_ty res_ty env_ty (vfn,lfn) (venv,lenv)
367   = do
368       dict <- paDictOfType env_ty
369       mkv  <- builtin closureVar
370       mkl  <- builtin liftedClosureVar
371       return (Var mkv `mkTyApps` [arg_ty, res_ty, env_ty] `mkApps` [dict, vfn, lfn, venv],
372               Var mkl `mkTyApps` [arg_ty, res_ty, env_ty] `mkApps` [dict, vfn, lfn, lenv])
373
374 mkClosureApp :: Type -> Type -> VExpr -> VExpr -> VM VExpr
375 mkClosureApp arg_ty res_ty (vclo, lclo) (varg, larg)
376   = do
377       vapply <- builtin applyVar
378       lapply <- builtin liftedApplyVar
379       lc     <- builtin liftingContext
380       return (Var vapply `mkTyApps` [arg_ty, res_ty] `mkApps` [vclo, varg],
381               Var lapply `mkTyApps` [arg_ty, res_ty] `mkApps` [Var lc, lclo, larg])
382
383 buildClosures :: [TyVar] -> [VVar] -> [Type] -> Type -> VM VExpr -> VM VExpr
384 buildClosures _   _    [] _ mk_body
385   = mk_body
386 buildClosures tvs vars [arg_ty] res_ty mk_body
387   = liftM vInlineMe (buildClosure tvs vars arg_ty res_ty mk_body)
388 buildClosures tvs vars (arg_ty : arg_tys) res_ty mk_body
389   = do
390       res_ty' <- mkClosureTypes arg_tys res_ty
391       arg <- newLocalVVar (fsLit "x") arg_ty
392       liftM vInlineMe
393         . buildClosure tvs vars arg_ty res_ty'
394         . hoistPolyVExpr tvs
395         $ do
396             lc <- builtin liftingContext
397             clo <- buildClosures tvs (vars ++ [arg]) arg_tys res_ty mk_body
398             return $ vLams lc (vars ++ [arg]) clo
399
400 -- (clo <x1,...,xn> <f,f^>, aclo (Arr lc xs1 ... xsn) <f,f^>)
401 --   where
402 --     f  = \env v -> case env of <x1,...,xn> -> e x1 ... xn v
403 --     f^ = \env v -> case env of Arr l xs1 ... xsn -> e^ l x1 ... xn v
404 --
405 buildClosure :: [TyVar] -> [VVar] -> Type -> Type -> VM VExpr -> VM VExpr
406 buildClosure tvs vars arg_ty res_ty mk_body
407   = do
408       (env_ty, env, bind) <- buildEnv vars
409       env_bndr <- newLocalVVar (fsLit "env") env_ty
410       arg_bndr <- newLocalVVar (fsLit "arg") arg_ty
411
412       fn <- hoistPolyVExpr tvs
413           $ do
414               lc    <- builtin liftingContext
415               body  <- mk_body
416               return . vInlineMe
417                      . vLams lc [env_bndr, arg_bndr]
418                      $ bind (vVar env_bndr)
419                             (vVarApps lc body (vars ++ [arg_bndr]))
420
421       mkClosure arg_ty res_ty env_ty fn env
422
423 buildEnv :: [VVar] -> VM (Type, VExpr, VExpr -> VExpr -> VExpr)
424 buildEnv [] = do
425              ty    <- voidType
426              void  <- builtin voidVar
427              pvoid <- builtin pvoidVar
428              return (ty, vVar (void, pvoid), \_ body -> body)
429
430 buildEnv [v] = return (vVarType v, vVar v,
431                     \env body -> vLet (vNonRec v env) body)
432
433 buildEnv vs
434   = do
435       
436       (lenv_tc, lenv_tyargs) <- pdataReprTyCon ty
437
438       let venv_con   = tupleCon Boxed (length vs) 
439           [lenv_con] = tyConDataCons lenv_tc
440
441           venv       = mkCoreTup (map Var vvs)
442           lenv       = Var (dataConWrapId lenv_con)
443                        `mkTyApps` lenv_tyargs
444                        `mkApps`   map Var lvs
445
446           vbind env body = mkWildCase env ty (exprType body)
447                            [(DataAlt venv_con, vvs, body)]
448
449           lbind env body =
450             let scrut = unwrapFamInstScrut lenv_tc lenv_tyargs env
451             in
452             mkWildCase scrut (exprType scrut) (exprType body)
453               [(DataAlt lenv_con, lvs, body)]
454
455           bind (venv, lenv) (vbody, lbody) = (vbind venv vbody,
456                                               lbind lenv lbody)
457
458       return (ty, (venv, lenv), bind)
459   where
460     (vvs, lvs) = unzip vs
461     tys        = map vVarType vs
462     ty         = mkCoreTupTy tys
463