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