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