871779a83eb2d8fb1c9589161aac5dbb739c1d88
[ghc-hetmet.git] / compiler / vectorise / VectType.hs
1 module VectType ( vectTyCon, vectType, vectTypeEnv,
2                    PAInstance, buildPADict,
3                    vectDataConWorkers )
4 where
5
6 #include "HsVersions.h"
7
8 import VectMonad
9 import VectUtils
10 import VectCore
11
12 import HscTypes          ( TypeEnv, extendTypeEnvList, typeEnvTyCons )
13 import CoreSyn
14 import CoreUtils
15 import DataCon
16 import TyCon
17 import Type
18 import TypeRep
19 import Coercion
20 import FamInstEnv        ( FamInst, mkLocalFamInst )
21 import InstEnv           ( Instance, mkLocalInstance, instanceDFunId )
22 import OccName
23 import MkId
24 import BasicTypes        ( StrictnessMark(..), OverlapFlag(..), boolToRecFlag )
25 import Var               ( Var )
26 import Id                ( mkWildId )
27 import Name              ( Name, getOccName )
28 import NameEnv
29 import TysWiredIn        ( intTy, intDataCon )
30 import TysPrim           ( intPrimTy )
31
32 import Unique
33 import UniqFM
34 import UniqSet
35 import Digraph           ( SCC(..), stronglyConnComp )
36
37 import Outputable
38
39 import Control.Monad  ( liftM, liftM2, zipWithM, zipWithM_ )
40 import Data.List      ( inits, tails )
41
42 -- ----------------------------------------------------------------------------
43 -- Types
44
45 vectTyCon :: TyCon -> VM TyCon
46 vectTyCon tc
47   | isFunTyCon tc        = builtin closureTyCon
48   | isBoxedTupleTyCon tc = return tc
49   | isUnLiftedTyCon tc   = return tc
50   | otherwise = do
51                   r <- lookupTyCon tc
52                   case r of
53                     Just tc' -> return tc'
54
55                     -- FIXME: just for now
56                     Nothing  -> pprTrace "ccTyCon:" (ppr tc) $ return tc
57
58 vectType :: Type -> VM Type
59 vectType ty | Just ty' <- coreView ty = vectType ty'
60 vectType (TyVarTy tv) = return $ TyVarTy tv
61 vectType (AppTy ty1 ty2) = liftM2 AppTy (vectType ty1) (vectType ty2)
62 vectType (TyConApp tc tys) = liftM2 TyConApp (vectTyCon tc) (mapM vectType tys)
63 vectType (FunTy ty1 ty2)   = liftM2 TyConApp (builtin closureTyCon)
64                                              (mapM vectType [ty1,ty2])
65 vectType ty@(ForAllTy _ _)
66   = do
67       mdicts   <- mapM paDictArgType tyvars
68       mono_ty' <- vectType mono_ty
69       return $ tyvars `mkForAllTys` ([dict | Just dict <- mdicts] `mkFunTys` mono_ty')
70   where
71     (tyvars, mono_ty) = splitForAllTys ty
72
73 vectType ty = pprPanic "vectType:" (ppr ty)
74
75 -- ----------------------------------------------------------------------------
76 -- Type definitions
77
78 type TyConGroup = ([TyCon], UniqSet TyCon)
79
80 data PAInstance = PAInstance {
81                     painstDFun      :: Var
82                   , painstOrigTyCon :: TyCon
83                   , painstVectTyCon :: TyCon
84                   , painstArrTyCon  :: TyCon
85                   }
86
87 vectTypeEnv :: TypeEnv -> VM (TypeEnv, [FamInst])
88 vectTypeEnv env
89   = do
90       cs <- readGEnv $ mk_map . global_tycons
91       let (conv_tcs, keep_tcs) = classifyTyCons cs groups
92           keep_dcs             = concatMap tyConDataCons keep_tcs
93       zipWithM_ defTyCon   keep_tcs keep_tcs
94       zipWithM_ defDataCon keep_dcs keep_dcs
95       new_tcs <- vectTyConDecls conv_tcs
96
97       let orig_tcs = keep_tcs ++ conv_tcs
98           vect_tcs  = keep_tcs ++ new_tcs
99
100       parr_tcs <- zipWithM buildPArrayTyCon orig_tcs vect_tcs
101       dfuns    <- mapM mkPADFun vect_tcs
102       defTyConPAs (zip vect_tcs dfuns)
103       -- pa_insts <- sequence $ zipWith3 buildPAInstance orig_tcs vect_tcs parr_tcs
104       
105       let all_new_tcs = new_tcs ++ parr_tcs
106
107       let new_env = extendTypeEnvList env
108                        (map ATyCon all_new_tcs
109                         ++ [ADataCon dc | tc <- all_new_tcs
110                                         , dc <- tyConDataCons tc])
111
112       return (new_env, map mkLocalFamInst parr_tcs)
113   where
114     tycons = typeEnvTyCons env
115     groups = tyConGroups tycons
116
117     mk_map env = listToUFM_Directly [(u, getUnique n /= u) | (u,n) <- nameEnvUniqueElts env]
118
119     keep_tc tc = let dcs = tyConDataCons tc
120                  in
121                  defTyCon tc tc >> zipWithM_ defDataCon dcs dcs
122
123
124 vectTyConDecls :: [TyCon] -> VM [TyCon]
125 vectTyConDecls tcs = fixV $ \tcs' ->
126   do
127     mapM_ (uncurry defTyCon) (lazy_zip tcs tcs')
128     mapM vectTyConDecl tcs
129   where
130     lazy_zip [] _ = []
131     lazy_zip (x:xs) ~(y:ys) = (x,y) : lazy_zip xs ys
132
133 vectTyConDecl :: TyCon -> VM TyCon
134 vectTyConDecl tc
135   = do
136       name' <- cloneName mkVectTyConOcc name
137       rhs'  <- vectAlgTyConRhs (algTyConRhs tc)
138
139       return $ mkAlgTyCon name'
140                           kind
141                           tyvars
142                           []              -- no stupid theta
143                           rhs'
144                           []              -- no selector ids
145                           NoParentTyCon   -- FIXME
146                           rec_flag        -- FIXME: is this ok?
147                           False           -- FIXME: no generics
148                           False           -- not GADT syntax
149   where
150     name   = tyConName tc
151     kind   = tyConKind tc
152     tyvars = tyConTyVars tc
153     rec_flag = boolToRecFlag (isRecursiveTyCon tc)
154
155 vectAlgTyConRhs :: AlgTyConRhs -> VM AlgTyConRhs
156 vectAlgTyConRhs (DataTyCon { data_cons = data_cons
157                            , is_enum   = is_enum
158                            })
159   = do
160       data_cons' <- mapM vectDataCon data_cons
161       zipWithM_ defDataCon data_cons data_cons'
162       return $ DataTyCon { data_cons = data_cons'
163                          , is_enum   = is_enum
164                          }
165
166 vectDataCon :: DataCon -> VM DataCon
167 vectDataCon dc
168   | not . null $ dataConExTyVars dc = pprPanic "vectDataCon: existentials" (ppr dc)
169   | not . null $ dataConEqSpec   dc = pprPanic "vectDataCon: eq spec" (ppr dc)
170   | otherwise
171   = do
172       name'    <- cloneName mkVectDataConOcc name
173       tycon'   <- vectTyCon tycon
174       arg_tys  <- mapM vectType rep_arg_tys
175       wrk_name <- cloneName mkDataConWorkerOcc name'
176
177       let ids      = mkDataConIds (panic "vectDataCon: wrapper id")
178                                   wrk_name
179                                   data_con
180           data_con = mkDataCon name'
181                                False           -- not infix
182                                (map (const NotMarkedStrict) arg_tys)
183                                []              -- no labelled fields
184                                univ_tvs
185                                []              -- no existential tvs for now
186                                []              -- no eq spec for now
187                                []              -- no theta
188                                arg_tys
189                                tycon'
190                                []              -- no stupid theta
191                                ids
192       return data_con
193   where
194     name        = dataConName dc
195     univ_tvs    = dataConUnivTyVars dc
196     rep_arg_tys = dataConRepArgTys dc
197     tycon       = dataConTyCon dc
198
199 vectDataConWorkers :: PAInstance -> VM [(Var, CoreExpr)]
200 vectDataConWorkers (PAInstance { painstOrigTyCon = orig_tc
201                                , painstVectTyCon = vect_tc
202                                , painstArrTyCon  = arr_tc
203                                })
204   = do
205       shape <- tyConShape vect_tc
206       sequence_ (zipWith3 (vectDataConWorker shape vect_tc arr_tc arr_dc)
207                           num_dcs
208                           (inits repr_tys)
209                           (tails repr_tys))
210       takeHoisted
211   where
212     orig_dcs = tyConDataCons orig_tc
213     vect_dcs = tyConDataCons vect_tc
214     [arr_dc] = tyConDataCons arr_tc
215
216     num_dcs  = zip3 orig_dcs vect_dcs [0..]
217     repr_tys = map dataConRepArgTys vect_dcs
218
219 vectDataConWorker :: Shape -> TyCon -> TyCon -> DataCon
220                   -> (DataCon, DataCon, Int) -> [[Type]] -> [[Type]]
221                   -> VM ()
222 vectDataConWorker shape vect_tc arr_tc arr_dc (orig_dc, vect_dc, dc_num) pre (dc_tys : post)
223   = do
224       clo <- closedV
225            . inBind orig_worker
226            . polyAbstract tvs $ \abstract ->
227              liftM (abstract . vectorised)
228            $ buildClosures tvs [] dc_tys res_ty (liftM2 (,) mk_vect mk_lift)
229
230       worker <- cloneId mkVectOcc orig_worker (exprType clo)
231       hoistBinding worker clo
232       defGlobalVar orig_worker worker
233       return ()
234   where
235     tvs     = tyConTyVars vect_tc
236     arg_tys = mkTyVarTys tvs
237     res_ty  = mkTyConApp vect_tc arg_tys
238
239     orig_worker = dataConWorkId orig_dc
240
241     mk_vect = return . mkConApp vect_dc $ map Type arg_tys
242     mk_lift = do
243                 len     <- newLocalVar FSLIT("n") intPrimTy
244                 arr_tys <- mapM mkPArrayType dc_tys
245                 args    <- mapM (newLocalVar FSLIT("xs")) arr_tys
246                 shapes  <- shapeReplicate shape (Var len) (mkIntLitInt dc_num)
247                 
248                 empty_pre  <- mapM emptyPA (concat pre)
249                 empty_post <- mapM emptyPA (concat post)
250
251                 return . mkLams (len : args)
252                        . wrapFamInstBody arr_tc arg_tys
253                        . mkConApp arr_dc
254                        $ map Type arg_tys ++ shapes
255                                           ++ empty_pre
256                                           ++ map Var args
257                                           ++ empty_post
258
259 data Shape = Shape {
260                shapeReprTys    :: [Type]
261              , shapeStrictness :: [StrictnessMark]
262              , shapeLength     :: [CoreExpr] -> VM CoreExpr
263              , shapeReplicate  :: CoreExpr -> CoreExpr -> VM [CoreExpr]
264              }
265
266 tyConShape :: TyCon -> VM Shape
267 tyConShape vect_tc
268   | isProductTyCon vect_tc
269   = return $ Shape {
270                 shapeReprTys    = [intPrimTy]
271               , shapeStrictness = [NotMarkedStrict]
272               , shapeLength     = \[len] -> return len
273               , shapeReplicate  = \len _ -> return [len]
274               }
275
276   | otherwise
277   = do
278       repr_ty <- mkPArrayType intTy   -- FIXME: we want to unbox this
279       return $ Shape {
280                  shapeReprTys    = [repr_ty]
281                , shapeStrictness = [MarkedStrict]
282                , shapeLength     = \[sel] -> lengthPA sel
283                , shapeReplicate  = \len n -> do
284                                                e <- replicatePA len n
285                                                return [e]
286                }
287         
288 buildPArrayTyCon :: TyCon -> TyCon -> VM TyCon
289 buildPArrayTyCon orig_tc vect_tc = fixV $ \repr_tc ->
290   do
291     name'  <- cloneName mkPArrayTyConOcc orig_name
292     parent <- buildPArrayParentInfo orig_name vect_tc repr_tc
293     rhs    <- buildPArrayTyConRhs orig_name vect_tc repr_tc
294
295     return $ mkAlgTyCon name'
296                         kind
297                         tyvars
298                         []              -- no stupid theta
299                         rhs
300                         []              -- no selector ids
301                         parent
302                         rec_flag        -- FIXME: is this ok?
303                         False           -- FIXME: no generics
304                         False           -- not GADT syntax
305   where
306     orig_name = tyConName orig_tc
307     name   = tyConName vect_tc
308     kind   = tyConKind vect_tc
309     tyvars = tyConTyVars vect_tc
310     rec_flag = boolToRecFlag (isRecursiveTyCon vect_tc)
311     
312
313 buildPArrayParentInfo :: Name -> TyCon -> TyCon -> VM TyConParent
314 buildPArrayParentInfo orig_name vect_tc repr_tc
315   = do
316       parray_tc <- builtin parrayTyCon
317       co_name <- cloneName mkInstTyCoOcc (tyConName repr_tc)
318
319       let inst_tys = [mkTyConApp vect_tc (map mkTyVarTy tyvars)]
320
321       return . FamilyTyCon parray_tc inst_tys
322              $ mkFamInstCoercion co_name
323                                  tyvars
324                                  parray_tc
325                                  inst_tys
326                                  repr_tc
327   where
328     tyvars = tyConTyVars vect_tc
329
330 buildPArrayTyConRhs :: Name -> TyCon -> TyCon -> VM AlgTyConRhs
331 buildPArrayTyConRhs orig_name vect_tc repr_tc
332   = do
333       data_con <- buildPArrayDataCon orig_name vect_tc repr_tc
334       return $ DataTyCon { data_cons = [data_con], is_enum = False }
335
336 buildPArrayDataCon :: Name -> TyCon -> TyCon -> VM DataCon
337 buildPArrayDataCon orig_name vect_tc repr_tc
338   = do
339       dc_name  <- cloneName mkPArrayDataConOcc orig_name
340       shape    <- tyConShape vect_tc
341       repr_tys <- mapM mkPArrayType types
342       wrk_name <- cloneName mkDataConWorkerOcc  dc_name
343       wrp_name <- cloneName mkDataConWrapperOcc dc_name
344
345       let ids      = mkDataConIds wrp_name wrk_name data_con
346           data_con = mkDataCon dc_name
347                                False
348                                (shapeStrictness shape ++ map (const NotMarkedStrict) repr_tys)
349                                []
350                                (tyConTyVars vect_tc)
351                                []
352                                []
353                                []
354                                (shapeReprTys shape ++ repr_tys)
355                                repr_tc
356                                []
357                                ids
358
359       return data_con
360   where
361     types = [ty | dc <- tyConDataCons vect_tc
362                 , ty <- dataConRepArgTys dc]
363
364 mkPADFun :: TyCon -> VM Var
365 mkPADFun vect_tc
366   = newExportedVar (mkPADFunOcc $ getOccName vect_tc) =<< paDFunType vect_tc
367
368 buildPAInstance :: TyCon -> TyCon -> TyCon -> VM PAInstance
369 buildPAInstance orig_tc vect_tc arr_tc
370   = do
371       dfun_ty <- paDFunType vect_tc
372       dfun <- newExportedVar (mkPADFunOcc $ getOccName vect_tc) dfun_ty
373
374       return $ PAInstance {
375                  painstDFun      = dfun
376                , painstOrigTyCon = orig_tc
377                , painstVectTyCon = vect_tc
378                , painstArrTyCon  = arr_tc
379                }
380
381 buildPADict :: PAInstance -> VM [(Var, CoreExpr)]
382 buildPADict (PAInstance {
383                painstDFun      = dfun
384              , painstVectTyCon = vect_tc
385              , painstArrTyCon  = arr_tc })
386   = polyAbstract (tyConTyVars arr_tc) $ \abstract ->
387     do
388       shape <- tyConShape vect_tc
389       meth_binds <- mapM (mk_method shape) paMethods
390       let meth_exprs = map (Var . fst) meth_binds
391
392       pa_dc <- builtin paDataCon
393       let dict = mkConApp pa_dc (Type (mkTyConApp vect_tc arg_tys) : meth_exprs)
394           body = Let (Rec meth_binds) dict
395       return [(dfun, mkInlineMe $ abstract body)]
396   where
397     tvs = tyConTyVars arr_tc
398     arg_tys = mkTyVarTys tvs
399
400     mk_method shape (name, build)
401       = localV
402       $ do
403           body <- build shape vect_tc arr_tc
404           var  <- newLocalVar name (exprType body)
405           return (var, mkInlineMe body)
406           
407 paMethods = [(FSLIT("lengthPA"),    buildLengthPA),
408              (FSLIT("replicatePA"), buildReplicatePA)]
409
410 buildLengthPA :: Shape -> TyCon -> TyCon -> VM CoreExpr
411 buildLengthPA shape vect_tc arr_tc
412   = do
413       parr_ty <- mkPArrayType (mkTyConApp vect_tc arg_tys)
414       arg    <- newLocalVar FSLIT("xs") parr_ty
415       shapes <- mapM (newLocalVar FSLIT("sh")) shape_tys
416       wilds  <- mapM newDummyVar repr_tys
417       let scrut    = unwrapFamInstScrut arr_tc arg_tys (Var arg)
418           scrut_ty = exprType scrut
419
420       body <- shapeLength shape (map Var shapes)
421
422       return . Lam arg
423              $ Case scrut (mkWildId scrut_ty) intPrimTy
424                     [(DataAlt repr_dc, shapes ++ wilds, body)]
425   where
426     arg_tys = mkTyVarTys $ tyConTyVars arr_tc
427     [repr_dc] = tyConDataCons arr_tc
428     
429     shape_tys = shapeReprTys shape
430     repr_tys  = drop (length shape_tys) (dataConRepArgTys repr_dc)
431
432 -- data T = C0 t1 ... tm
433 --          ...
434 --          Ck u1 ... un
435 --
436 -- data [:T:] = A ![:Int:] [:t1:] ... [:un:]
437 --
438 -- replicatePA :: Int# -> T -> [:T:]
439 -- replicatePA n# t
440 --   = let c = case t of
441 --               C0 _ ... _ -> 0
442 --               ...
443 --               Ck _ ... _ -> k
444 --
445 --         xs1 = case t of
446 --                 C0 x1 _ ... _ -> replicatePA @t1 n# x1
447 --                 _             -> emptyPA @t1
448 --
449 --         ...
450 --
451 --         ysn = case t of
452 --                 Ck _ ... _ yn -> replicatePA @un n# yn
453 --                 _             -> emptyPA @un
454 --     in
455 --     A (replicatePA @Int n# c) xs1 ... ysn
456 --
457 --
458
459 buildReplicatePA :: Shape -> TyCon -> TyCon -> VM CoreExpr
460 buildReplicatePA shape vect_tc arr_tc
461   = do
462       len_var <- newLocalVar FSLIT("n") intPrimTy
463       val_var <- newLocalVar FSLIT("x") val_ty
464
465       let len = Var len_var
466           val = Var val_var
467
468       shape_reprs <- shapeReplicate shape len (ctr_num val)
469       reprs <- liftM concat $ mapM (mk_comp_arrs len val) vect_dcs
470
471       return . mkLams [len_var, val_var]
472              . wrapFamInstBody arr_tc arg_tys
473              $ mkConApp arr_dc (map Type arg_tys ++ shape_reprs ++ reprs)
474   where
475     arg_tys = mkTyVarTys (tyConTyVars arr_tc)
476     val_ty  = mkTyConApp vect_tc arg_tys
477     wild    = mkWildId val_ty
478     vect_dcs = tyConDataCons vect_tc
479     [arr_dc] = tyConDataCons arr_tc
480
481     ctr_num val = Case val wild intTy (zipWith ctr_num_alt vect_dcs [0..])
482     ctr_num_alt dc i = (DataAlt dc, map mkWildId (dataConRepArgTys dc),
483                                     mkConApp intDataCon [mkIntLitInt i])
484
485
486     mk_comp_arrs len val dc = let tys = dataConRepArgTys dc
487                                   wilds = map mkWildId tys
488                               in
489                               sequence (zipWith3 (mk_comp_arr len val dc)
490                                        tys (inits wilds) (tails wilds))
491
492     mk_comp_arr len val dc ty pre (_:post)
493       = do
494           var   <- newLocalVar FSLIT("x") ty
495           rep   <- replicatePA len (Var var)
496           empty <- emptyPA ty
497           arr_ty <- mkPArrayType ty
498
499           return $ Case val wild arr_ty
500                      [(DEFAULT, [], empty), (DataAlt dc, pre ++ (var : post), rep)]
501
502 -- | Split the given tycons into two sets depending on whether they have to be
503 -- converted (first list) or not (second list). The first argument contains
504 -- information about the conversion status of external tycons:
505 -- 
506 --   * tycons which have converted versions are mapped to True
507 --   * tycons which are not changed by vectorisation are mapped to False
508 --   * tycons which can't be converted are not elements of the map
509 --
510 classifyTyCons :: UniqFM Bool -> [TyConGroup] -> ([TyCon], [TyCon])
511 classifyTyCons = classify [] []
512   where
513     classify conv keep cs [] = (conv, keep)
514     classify conv keep cs ((tcs, ds) : rs)
515       | can_convert && must_convert
516         = classify (tcs ++ conv) keep (cs `addListToUFM` [(tc,True) | tc <- tcs]) rs
517       | can_convert
518         = classify conv (tcs ++ keep) (cs `addListToUFM` [(tc,False) | tc <- tcs]) rs
519       | otherwise
520         = classify conv keep cs rs
521       where
522         refs = ds `delListFromUniqSet` tcs
523
524         can_convert  = isNullUFM (refs `minusUFM` cs) && all convertable tcs
525         must_convert = foldUFM (||) False (intersectUFM_C const cs refs)
526
527         convertable tc = isDataTyCon tc && all isVanillaDataCon (tyConDataCons tc)
528     
529 -- | Compute mutually recursive groups of tycons in topological order
530 --
531 tyConGroups :: [TyCon] -> [TyConGroup]
532 tyConGroups tcs = map mk_grp (stronglyConnComp edges)
533   where
534     edges = [((tc, ds), tc, uniqSetToList ds) | tc <- tcs
535                                 , let ds = tyConsOfTyCon tc]
536
537     mk_grp (AcyclicSCC (tc, ds)) = ([tc], ds)
538     mk_grp (CyclicSCC els)       = (tcs, unionManyUniqSets dss)
539       where
540         (tcs, dss) = unzip els
541
542 tyConsOfTyCon :: TyCon -> UniqSet TyCon
543 tyConsOfTyCon 
544   = tyConsOfTypes . concatMap dataConRepArgTys . tyConDataCons
545
546 tyConsOfType :: Type -> UniqSet TyCon
547 tyConsOfType ty
548   | Just ty' <- coreView ty    = tyConsOfType ty'
549 tyConsOfType (TyVarTy v)       = emptyUniqSet
550 tyConsOfType (TyConApp tc tys) = extend (tyConsOfTypes tys)
551   where
552     extend | isUnLiftedTyCon tc
553            || isTupleTyCon   tc = id
554
555            | otherwise          = (`addOneToUniqSet` tc)
556
557 tyConsOfType (AppTy a b)       = tyConsOfType a `unionUniqSets` tyConsOfType b
558 tyConsOfType (FunTy a b)       = (tyConsOfType a `unionUniqSets` tyConsOfType b)
559                                  `addOneToUniqSet` funTyCon
560 tyConsOfType (ForAllTy _ ty)   = tyConsOfType ty
561 tyConsOfType other             = pprPanic "ClosureConv.tyConsOfType" $ ppr other
562
563 tyConsOfTypes :: [Type] -> UniqSet TyCon
564 tyConsOfTypes = unionManyUniqSets . map tyConsOfType
565