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