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