Rollback INLINE patches
[ghc-hetmet.git] / compiler / vectorise / VectType.hs
1
2 module VectType ( vectTyCon, vectAndLiftType, vectType, vectTypeEnv,
3                   mkRepr, arrShapeTys, arrShapeVars, arrSelector,
4                   buildPADict,
5                   fromVect )
6 where
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 MkCore            ( mkWildCase )
16 import BuildTyCl
17 import DataCon
18 import TyCon
19 import Type
20 import TypeRep
21 import Coercion
22 import FamInstEnv        ( FamInst, mkLocalFamInst )
23 import OccName
24 import MkId
25 import BasicTypes        ( StrictnessMark(..), boolToRecFlag )
26 import Var               ( Var, TyVar )
27 import Name              ( Name, getOccName )
28 import NameEnv
29 import TysWiredIn
30 import TysPrim           ( intPrimTy )
31
32 import Unique
33 import UniqFM
34 import UniqSet
35 import Util
36 import Digraph           ( SCC(..), stronglyConnCompFromEdgedVertices )
37
38 import Outputable
39 import FastString
40
41 import Control.Monad  ( liftM, liftM2, zipWithM, zipWithM_, mapAndUnzipM )
42 import Data.List      ( inits, tails, zipWith4, zipWith5 )
43
44 -- ----------------------------------------------------------------------------
45 -- Types
46
47 vectTyCon :: TyCon -> VM TyCon
48 vectTyCon tc
49   | isFunTyCon tc        = builtin closureTyCon
50   | isBoxedTupleTyCon tc = return tc
51   | isUnLiftedTyCon tc   = return tc
52   | otherwise            = maybeCantVectoriseM "Tycon not vectorised:" (ppr tc)
53                          $ lookupTyCon tc
54
55 vectAndLiftType :: Type -> VM (Type, Type)
56 vectAndLiftType ty | Just ty' <- coreView ty = vectAndLiftType ty'
57 vectAndLiftType ty
58   = do
59       mdicts   <- mapM paDictArgType tyvars
60       let dicts = [dict | Just dict <- mdicts]
61       vmono_ty <- vectType mono_ty
62       lmono_ty <- mkPArrayType vmono_ty
63       return (abstractType tyvars dicts vmono_ty,
64               abstractType tyvars dicts lmono_ty)
65   where
66     (tyvars, mono_ty) = splitForAllTys ty
67
68
69 vectType :: Type -> VM Type
70 vectType ty | Just ty' <- coreView ty = vectType ty'
71 vectType (TyVarTy tv) = return $ TyVarTy tv
72 vectType (AppTy ty1 ty2) = liftM2 AppTy (vectType ty1) (vectType ty2)
73 vectType (TyConApp tc tys) = liftM2 TyConApp (vectTyCon tc) (mapM vectType tys)
74 vectType (FunTy ty1 ty2)   = liftM2 TyConApp (builtin closureTyCon)
75                                              (mapM vectAndBoxType [ty1,ty2])
76 vectType ty@(ForAllTy _ _)
77   = do
78       mdicts   <- mapM paDictArgType tyvars
79       mono_ty' <- vectType mono_ty
80       return $ abstractType tyvars [dict | Just dict <- mdicts] mono_ty'
81   where
82     (tyvars, mono_ty) = splitForAllTys ty
83
84 vectType ty = cantVectorise "Can't vectorise type" (ppr ty)
85
86 vectAndBoxType :: Type -> VM Type
87 vectAndBoxType ty = vectType ty >>= boxType
88
89 abstractType :: [TyVar] -> [Type] -> Type -> Type
90 abstractType tyvars dicts = mkForAllTys tyvars . mkFunTys dicts
91
92 -- ----------------------------------------------------------------------------
93 -- Boxing
94
95 boxType :: Type -> VM Type
96 boxType ty
97   | Just (tycon, []) <- splitTyConApp_maybe ty
98   , isUnLiftedTyCon tycon
99   = do
100       r <- lookupBoxedTyCon tycon
101       case r of
102         Just tycon' -> return $ mkTyConApp tycon' []
103         Nothing     -> return ty
104 boxType ty = return ty
105
106 -- ----------------------------------------------------------------------------
107 -- Type definitions
108
109 type TyConGroup = ([TyCon], UniqSet TyCon)
110
111 vectTypeEnv :: TypeEnv -> VM (TypeEnv, [FamInst], [(Var, CoreExpr)])
112 vectTypeEnv env
113   = do
114       cs <- readGEnv $ mk_map . global_tycons
115       let (conv_tcs, keep_tcs) = classifyTyCons cs groups
116           keep_dcs             = concatMap tyConDataCons keep_tcs
117       zipWithM_ defTyCon   keep_tcs keep_tcs
118       zipWithM_ defDataCon keep_dcs keep_dcs
119       new_tcs <- vectTyConDecls conv_tcs
120
121       let orig_tcs = keep_tcs ++ conv_tcs
122           vect_tcs  = keep_tcs ++ new_tcs
123
124       repr_tcs <- zipWithM buildPReprTyCon   orig_tcs vect_tcs
125       parr_tcs <- zipWithM buildPArrayTyCon orig_tcs vect_tcs
126       dfuns    <- mapM mkPADFun vect_tcs
127       defTyConPAs (zip vect_tcs dfuns)
128       binds    <- sequence (zipWith5 buildTyConBindings orig_tcs
129                                                         vect_tcs
130                                                         repr_tcs
131                                                         parr_tcs
132                                                         dfuns)
133
134       let all_new_tcs = new_tcs ++ repr_tcs ++ parr_tcs
135
136       let new_env = extendTypeEnvList env
137                        (map ATyCon all_new_tcs
138                         ++ [ADataCon dc | tc <- all_new_tcs
139                                         , dc <- tyConDataCons tc])
140
141       return (new_env, map mkLocalFamInst (repr_tcs ++ parr_tcs), concat binds)
142   where
143     tycons = typeEnvTyCons env
144     groups = tyConGroups tycons
145
146     mk_map env = listToUFM_Directly [(u, getUnique n /= u) | (u,n) <- nameEnvUniqueElts env]
147
148
149 vectTyConDecls :: [TyCon] -> VM [TyCon]
150 vectTyConDecls tcs = fixV $ \tcs' ->
151   do
152     mapM_ (uncurry defTyCon) (zipLazy tcs tcs')
153     mapM vectTyConDecl tcs
154
155 vectTyConDecl :: TyCon -> VM TyCon
156 vectTyConDecl tc
157   = do
158       name' <- cloneName mkVectTyConOcc name
159       rhs'  <- vectAlgTyConRhs tc (algTyConRhs tc)
160
161       liftDs $ buildAlgTyCon name'
162                              tyvars
163                              []           -- no stupid theta
164                              rhs'
165                              rec_flag     -- FIXME: is this ok?
166                              False        -- FIXME: no generics
167                              False        -- not GADT syntax
168                              Nothing      -- not a family instance
169   where
170     name   = tyConName tc
171     tyvars = tyConTyVars tc
172     rec_flag = boolToRecFlag (isRecursiveTyCon tc)
173
174 vectAlgTyConRhs :: TyCon -> AlgTyConRhs -> VM AlgTyConRhs
175 vectAlgTyConRhs _ (DataTyCon { data_cons = data_cons
176                              , is_enum   = is_enum
177                              })
178   = do
179       data_cons' <- mapM vectDataCon data_cons
180       zipWithM_ defDataCon data_cons data_cons'
181       return $ DataTyCon { data_cons = data_cons'
182                          , is_enum   = is_enum
183                          }
184 vectAlgTyConRhs tc _ = cantVectorise "Can't vectorise type definition:" (ppr tc)
185
186 vectDataCon :: DataCon -> VM DataCon
187 vectDataCon dc
188   | not . null $ dataConExTyVars dc
189         = cantVectorise "Can't vectorise constructor (existentials):" (ppr dc)
190   | not . null $ dataConEqSpec   dc
191         = cantVectorise "Can't vectorise constructor (eq spec):" (ppr dc)
192   | otherwise
193   = do
194       name'    <- cloneName mkVectDataConOcc name
195       tycon'   <- vectTyCon tycon
196       arg_tys  <- mapM vectType rep_arg_tys
197
198       liftDs $ buildDataCon name'
199                             False           -- not infix
200                             (map (const NotMarkedStrict) arg_tys)
201                             []              -- no labelled fields
202                             univ_tvs
203                             []              -- no existential tvs for now
204                             []              -- no eq spec for now
205                             []              -- no context
206                             arg_tys 
207                             (mkFamilyTyConApp tycon' (mkTyVarTys univ_tvs))
208                             tycon'
209   where
210     name        = dataConName dc
211     univ_tvs    = dataConUnivTyVars dc
212     rep_arg_tys = dataConRepArgTys dc
213     tycon       = dataConTyCon dc
214
215 mk_fam_inst :: TyCon -> TyCon -> (TyCon, [Type])
216 mk_fam_inst fam_tc arg_tc
217   = (fam_tc, [mkTyConApp arg_tc . mkTyVarTys $ tyConTyVars arg_tc])
218
219 buildPReprTyCon :: TyCon -> TyCon -> VM TyCon
220 buildPReprTyCon orig_tc vect_tc
221   = do
222       name     <- cloneName mkPReprTyConOcc (tyConName orig_tc)
223       rhs_ty   <- buildPReprType vect_tc
224       prepr_tc <- builtin preprTyCon
225       liftDs $ buildSynTyCon name
226                              tyvars
227                              (SynonymTyCon rhs_ty)
228                              (typeKind rhs_ty)
229                              (Just $ mk_fam_inst prepr_tc vect_tc)
230   where
231     tyvars = tyConTyVars vect_tc
232
233
234 data Repr = ProdRepr {
235               prod_components   :: [Type]
236             , prod_tycon        :: TyCon
237             , prod_data_con     :: DataCon
238             , prod_arr_tycon    :: TyCon
239             , prod_arr_data_con :: DataCon
240             }
241
242           | SumRepr {
243               sum_components    :: [Repr]
244             , sum_tycon         :: TyCon
245             , sum_arr_tycon     :: TyCon
246             , sum_arr_data_con  :: DataCon
247             }
248
249           | IdRepr Type
250
251           | VoidRepr {
252               void_tycon        :: TyCon
253             , void_bottom       :: CoreExpr
254             }
255
256           | EnumRepr {
257               enum_tycon        :: TyCon
258             , enum_data_con     :: DataCon
259             , enum_arr_tycon    :: TyCon
260             , enum_arr_data_con :: DataCon
261             }
262
263 voidRepr :: VM Repr
264 voidRepr
265   = do
266       tycon <- builtin voidTyCon
267       var   <- builtin voidVar
268       return $ VoidRepr {
269                  void_tycon  = tycon
270                , void_bottom = Var var
271                }
272
273 {-
274 enumRepr :: VM Repr
275 enumRepr
276   = do
277       tycon <- builtin enumerationTyCon
278       let [data_con] = tyConDataCons tycon
279       (arr_tycon, _) <- parrayReprTyCon (mkTyConApp tycon [])
280       let [arr_data_con] = tyConDataCons arr_tycon
281
282       return $ EnumRepr {
283                  enum_tycon       = tycon
284                , enum_data_con     = data_con
285                , enum_arr_tycon    = arr_tycon
286                , enum_arr_data_con = arr_data_con
287                }
288 -}
289
290 unboxedProductRepr :: [Type] -> VM Repr
291 unboxedProductRepr []   = voidRepr
292 unboxedProductRepr [ty] = return $ IdRepr ty
293 unboxedProductRepr tys  = boxedProductRepr tys
294
295 boxedProductRepr :: [Type] -> VM Repr
296 boxedProductRepr tys
297   = do
298       tycon <- builtin (prodTyCon arity)
299       let [data_con] = tyConDataCons tycon
300
301       tys' <- mapM boxType tys
302       (arr_tycon, _) <- parrayReprTyCon $ mkTyConApp tycon tys'
303       let [arr_data_con] = tyConDataCons arr_tycon
304
305       return $ ProdRepr {
306                  prod_components   = tys
307                , prod_tycon        = tycon
308                , prod_data_con     = data_con
309                , prod_arr_tycon    = arr_tycon
310                , prod_arr_data_con = arr_data_con
311                }
312   where
313     arity = length tys
314
315 sumRepr :: [Repr] -> VM Repr
316 sumRepr []     = voidRepr
317 sumRepr [repr] = boxRepr repr
318 sumRepr reprs
319   = do
320       tycon <- builtin (sumTyCon arity)
321       (arr_tycon, _) <- parrayReprTyCon
322                       . mkTyConApp tycon
323                       $ map reprType reprs
324
325       let [arr_data_con] = tyConDataCons arr_tycon
326
327       return $ SumRepr {
328                  sum_components   = reprs
329                , sum_tycon        = tycon
330                , sum_arr_tycon    = arr_tycon
331                , sum_arr_data_con = arr_data_con
332                }
333   where
334     arity = length reprs
335
336 splitSumRepr :: Repr -> [Repr]
337 splitSumRepr (SumRepr { sum_components = reprs }) = reprs
338 splitSumRepr repr                                 = [repr]
339
340 boxRepr :: Repr -> VM Repr
341 boxRepr (VoidRepr {}) = boxedProductRepr []
342 boxRepr (IdRepr ty)   = boxedProductRepr [ty]
343 boxRepr repr          = return repr
344
345 reprType :: Repr -> Type
346 reprType (ProdRepr { prod_tycon = tycon, prod_components = tys })
347   = mkTyConApp tycon tys
348 reprType (SumRepr { sum_tycon = tycon, sum_components = reprs })
349   = mkTyConApp tycon (map reprType reprs)
350 reprType (IdRepr ty) = ty
351 reprType (VoidRepr { void_tycon = tycon }) = mkTyConApp tycon []
352 reprType (EnumRepr { enum_tycon = tycon }) = mkTyConApp tycon []
353
354 arrReprType :: Repr -> VM Type
355 arrReprType = mkPArrayType . reprType
356
357 arrShapeTys :: Repr -> VM [Type]
358 arrShapeTys (SumRepr  {}) = sumShapeTys
359 arrShapeTys (ProdRepr {}) = return [intPrimTy]
360 arrShapeTys (IdRepr _)    = return []
361 arrShapeTys (VoidRepr {}) = return [intPrimTy]
362 arrShapeTys (EnumRepr {}) = sumShapeTys
363
364 sumShapeTys :: VM [Type]
365 sumShapeTys = do
366                 int_arr <- builtin intPrimArrayTy
367                 return [intPrimTy, int_arr, int_arr]
368
369
370 arrShapeVars :: Repr -> VM [Var]
371 arrShapeVars repr = mapM (newLocalVar (fsLit "sh")) =<< arrShapeTys repr
372
373 replicateShape :: Repr -> CoreExpr -> CoreExpr -> VM [CoreExpr]
374 replicateShape (ProdRepr {}) len _   = return [len]
375 replicateShape (SumRepr {})  len tag = replicateSumShape len tag
376 replicateShape (IdRepr _) _ _        = return []
377 replicateShape (VoidRepr {}) len _   = return [len]
378 replicateShape (EnumRepr {}) len tag = replicateSumShape len tag
379
380 replicateSumShape :: CoreExpr -> CoreExpr -> VM [CoreExpr]
381 replicateSumShape len tag
382   = do
383       rep <- builtin replicatePAIntPrimVar
384       up  <- builtin upToPAIntPrimVar
385       return [len, Var rep `mkApps` [len, tag], Var up `App` len]
386
387 arrSelector :: Repr -> [CoreExpr] -> VM (CoreExpr, CoreExpr, CoreExpr)
388 arrSelector (SumRepr {})  [len, sel, is] = return (len, sel, is)
389 arrSelector (EnumRepr {}) [len, sel, is] = return (len, sel, is)
390 arrSelector _             _              = panic "arrSelector"
391
392 emptyArrRepr :: Repr -> VM [CoreExpr]
393 emptyArrRepr (SumRepr { sum_components = prods })
394   = liftM concat $ mapM emptyArrRepr prods
395 emptyArrRepr (ProdRepr { prod_components = [] })
396   = return [Var unitDataConId]
397 emptyArrRepr (ProdRepr { prod_components = tys })
398   = mapM emptyPA tys
399 emptyArrRepr (IdRepr ty)
400   = liftM singleton $ emptyPA ty
401 emptyArrRepr (VoidRepr { void_tycon = tycon })
402   = liftM singleton $ emptyPA (mkTyConApp tycon [])
403 emptyArrRepr (EnumRepr {})
404   = return []
405
406 arrReprTys :: Repr -> VM [Type]
407 arrReprTys (SumRepr { sum_components = reprs })
408   = liftM concat $ mapM arrReprTys reprs
409 arrReprTys (ProdRepr { prod_components = [] })
410   = return [unitTy]
411 arrReprTys (ProdRepr { prod_components = tys })
412   = mapM mkPArrayType tys
413 arrReprTys (IdRepr ty)
414   = liftM singleton $ mkPArrayType ty
415 arrReprTys (VoidRepr { void_tycon = tycon })
416   = liftM singleton $ mkPArrayType (mkTyConApp tycon [])
417 arrReprTys (EnumRepr {})
418   = return []
419
420 arrReprTys' :: Repr -> VM [[Type]]
421 arrReprTys' (SumRepr { sum_components = reprs })
422   = mapM arrReprTys reprs
423 arrReprTys' repr = liftM singleton $ arrReprTys repr
424
425 arrReprVars :: Repr -> VM [[Var]]
426 arrReprVars repr
427   = mapM (mapM (newLocalVar (fsLit "rs"))) =<< arrReprTys' repr
428
429 mkRepr :: TyCon -> VM Repr
430 mkRepr vect_tc
431   | [tys] <- rep_tys = boxedProductRepr tys
432   -- removed: | all null rep_tys = enumRepr
433   | otherwise        = sumRepr =<< mapM unboxedProductRepr rep_tys
434   where
435     rep_tys = map dataConRepArgTys $ tyConDataCons vect_tc
436
437 buildPReprType :: TyCon -> VM Type
438 buildPReprType = liftM reprType . mkRepr
439
440 buildToPRepr :: Repr -> TyCon -> TyCon -> TyCon -> VM CoreExpr
441 buildToPRepr repr vect_tc prepr_tc _
442   = do
443       arg    <- newLocalVar (fsLit "x") arg_ty
444       result <- to_repr repr (Var arg)
445
446       return . Lam arg
447              . wrapFamInstBody prepr_tc var_tys
448              $ result
449   where
450     var_tys = mkTyVarTys $ tyConTyVars vect_tc
451     arg_ty  = mkTyConApp vect_tc var_tys
452     res_ty  = reprType repr
453
454     cons    = tyConDataCons vect_tc
455     [con]   = cons
456
457     to_repr (SumRepr { sum_components = prods
458                      , sum_tycon      = tycon })
459             expr
460       = do
461           (vars, bodies) <- mapAndUnzipM to_unboxed prods
462           return . mkWildCase expr (exprType expr) res_ty
463                  $ zipWith4 mk_alt cons vars (tyConDataCons tycon) bodies
464       where
465         mk_alt con vars sum_con body
466           = (DataAlt con, vars, mkConApp sum_con (ty_args ++ [body]))
467
468         ty_args = map (Type . reprType) prods
469
470     to_repr (EnumRepr { enum_data_con = data_con }) expr
471       = return . mkWildCase expr (exprType expr) res_ty
472                $ map mk_alt cons
473       where
474         mk_alt con = (DataAlt con, [], mkConApp data_con [mkDataConTag con])
475
476     to_repr prod expr
477       = do
478           (vars, body) <- to_unboxed prod
479           return $ mkWildCase expr (exprType expr) res_ty
480                    [(DataAlt con, vars, body)]
481
482     to_unboxed (ProdRepr { prod_components = tys
483                          , prod_data_con   = data_con })
484       = do
485           vars <- mapM (newLocalVar (fsLit "r")) tys
486           return (vars, mkConApp data_con (map Type tys ++ map Var vars))
487
488     to_unboxed (IdRepr ty)
489       = do
490           var <- newLocalVar (fsLit "y") ty
491           return ([var], Var var)
492
493     to_unboxed (VoidRepr { void_bottom = bottom })
494       = return ([], bottom)
495
496     to_unboxed _ = panic "buildToPRepr/to_unboxed"
497
498
499 buildFromPRepr :: Repr -> TyCon -> TyCon -> TyCon -> VM CoreExpr
500 buildFromPRepr repr vect_tc prepr_tc _
501   = do
502       arg_ty <- mkPReprType res_ty
503       arg    <- newLocalVar (fsLit "x") arg_ty
504
505       liftM (Lam arg)
506            . from_repr repr
507            $ unwrapFamInstScrut prepr_tc var_tys (Var arg)
508   where
509     var_tys = mkTyVarTys $ tyConTyVars vect_tc
510     res_ty  = mkTyConApp vect_tc var_tys
511
512     cons    = map (`mkConApp` map Type var_tys) (tyConDataCons vect_tc)
513     [con]   = cons
514
515     from_repr repr@(SumRepr { sum_components = prods
516                             , sum_tycon      = tycon })
517               expr
518       = do
519           vars   <- mapM (newLocalVar (fsLit "x")) (map reprType prods)
520           bodies <- sequence . zipWith3 from_unboxed prods cons
521                              $ map Var vars
522           return . mkWildCase expr (reprType repr) res_ty
523                  $ zipWith3 sum_alt (tyConDataCons tycon) vars bodies
524       where
525         sum_alt data_con var body = (DataAlt data_con, [var], body)
526
527     from_repr repr@(EnumRepr { enum_data_con = data_con }) expr
528       = do
529           var <- newLocalVar (fsLit "n") intPrimTy
530
531           let res = mkWildCase (Var var) intPrimTy res_ty
532                   $ (DEFAULT, [], error_expr)
533                   : zipWith mk_alt (tyConDataCons vect_tc) cons
534
535           return $ mkWildCase expr (reprType repr) res_ty
536                    [(DataAlt data_con, [var], res)]
537       where
538         mk_alt data_con con = (LitAlt (mkDataConTagLit data_con), [], con)
539
540         error_expr = mkRuntimeErrorApp rUNTIME_ERROR_ID res_ty
541                    . showSDoc
542                    $ sep [text "Invalid NDP representation of", ppr vect_tc]
543
544     from_repr repr expr = from_unboxed repr con expr
545
546     from_unboxed prod@(ProdRepr { prod_components = tys
547                                 , prod_data_con   = data_con })
548               con
549               expr
550       = do
551           vars <- mapM (newLocalVar (fsLit "y")) tys
552           return $ mkWildCase expr (reprType prod) res_ty
553                    [(DataAlt data_con, vars, con `mkVarApps` vars)]
554
555     from_unboxed (IdRepr _) con expr
556        = return $ con `App` expr
557
558     from_unboxed (VoidRepr {}) con _
559        = return con
560
561     from_unboxed _ _ _ = panic "buildFromPRepr/from_unboxed"
562
563 buildToArrPRepr :: Repr -> TyCon -> TyCon -> TyCon -> VM CoreExpr
564 buildToArrPRepr repr vect_tc prepr_tc arr_tc
565   = do
566       arg_ty     <- mkPArrayType el_ty
567       arg        <- newLocalVar (fsLit "xs") arg_ty
568
569       res_ty     <- mkPArrayType (reprType repr)
570
571       shape_vars <- arrShapeVars repr
572       repr_vars  <- arrReprVars  repr
573
574       parray_co  <- mkBuiltinCo parrayTyCon
575
576       let Just repr_co = tyConFamilyCoercion_maybe prepr_tc
577           co           = mkAppCoercion parray_co
578                        . mkSymCoercion
579                        $ mkTyConApp repr_co var_tys
580
581           scrut   = unwrapFamInstScrut arr_tc var_tys (Var arg)
582
583       result <- to_repr shape_vars repr_vars repr
584
585       return . Lam arg
586              . mkCoerce co
587              $ mkWildCase scrut (mkTyConApp arr_tc var_tys) res_ty
588                [(DataAlt arr_dc, shape_vars ++ concat repr_vars, result)]
589   where
590     var_tys = mkTyVarTys $ tyConTyVars vect_tc
591     el_ty   = mkTyConApp vect_tc var_tys
592
593     [arr_dc] = tyConDataCons arr_tc
594
595     to_repr shape_vars@(_ : _)
596             repr_vars
597             (SumRepr { sum_components   = prods
598                      , sum_arr_tycon    = tycon
599                      , sum_arr_data_con = data_con })
600       = do
601           exprs <- zipWithM to_prod repr_vars prods
602
603           return . wrapFamInstBody tycon tys
604                  . mkConApp data_con
605                  $ map Type tys ++ map Var shape_vars ++ exprs
606       where
607         tys = map reprType prods
608
609     to_repr [len_var]
610             [repr_vars]
611             (ProdRepr { prod_components   = tys
612                       , prod_arr_tycon    = tycon
613                       , prod_arr_data_con = data_con })
614        = return . wrapFamInstBody tycon tys
615                 . mkConApp data_con
616                 $ map Type tys ++ map Var (len_var : repr_vars)
617
618     to_repr shape_vars
619             _
620             (EnumRepr { enum_arr_tycon    = tycon
621                       , enum_arr_data_con = data_con })
622       = return . wrapFamInstBody tycon []
623                . mkConApp data_con
624                 $ map Var shape_vars
625
626     to_repr _ _ _ = panic "buildToArrPRepr/to_repr"
627
628     to_prod repr_vars@(r : _)
629             (ProdRepr { prod_components   = tys@(ty : _)
630                       , prod_arr_tycon    = tycon
631                       , prod_arr_data_con = data_con })
632       = do
633           len <- lengthPA ty (Var r)
634           return . wrapFamInstBody tycon tys
635                  . mkConApp data_con
636                  $ map Type tys ++ len : map Var repr_vars
637
638     to_prod [var] (IdRepr _)    = return (Var var)
639     to_prod [var] (VoidRepr {}) = return (Var var)
640     to_prod _     _             = panic "buildToArrPRepr/to_prod"
641
642
643 buildFromArrPRepr :: Repr -> TyCon -> TyCon -> TyCon -> VM CoreExpr
644 buildFromArrPRepr repr vect_tc prepr_tc arr_tc
645   = do
646       arg_ty     <- mkPArrayType =<< mkPReprType el_ty
647       arg        <- newLocalVar (fsLit "xs") arg_ty
648
649       res_ty     <- mkPArrayType el_ty
650
651       shape_vars <- arrShapeVars repr
652       repr_vars  <- arrReprVars  repr
653
654       parray_co  <- mkBuiltinCo parrayTyCon
655
656       let Just repr_co = tyConFamilyCoercion_maybe prepr_tc
657           co           = mkAppCoercion parray_co
658                        $ mkTyConApp repr_co var_tys
659
660           scrut  = mkCoerce co (Var arg)
661
662           result = wrapFamInstBody arr_tc var_tys
663                  . mkConApp arr_dc
664                  $ map Type var_tys ++ map Var (shape_vars ++ concat repr_vars)
665
666       liftM (Lam arg)
667             (from_repr repr scrut shape_vars repr_vars res_ty result)
668   where
669     var_tys = mkTyVarTys $ tyConTyVars vect_tc
670     el_ty   = mkTyConApp vect_tc var_tys
671
672     [arr_dc] = tyConDataCons arr_tc
673
674     from_repr (SumRepr { sum_components   = prods
675                        , sum_arr_tycon    = tycon
676                        , sum_arr_data_con = data_con })
677               expr
678               shape_vars
679               repr_vars
680               res_ty
681               body
682       = do
683           vars <- mapM (newLocalVar (fsLit "xs")) =<< mapM arrReprType prods
684           result <- go prods repr_vars vars body
685
686           let scrut = unwrapFamInstScrut tycon ty_args expr
687           return . mkWildCase scrut scrut_ty res_ty
688                  $ [(DataAlt data_con, shape_vars ++ vars, result)]
689       where
690         ty_args  = map reprType prods
691         scrut_ty = mkTyConApp tycon ty_args
692
693         go [] [] [] body = return body
694         go (prod : prods) (repr_vars : rss) (var : vars) body
695           = do
696               shape_vars <- mapM (newLocalVar (fsLit "s")) =<< arrShapeTys prod
697
698               from_prod prod (Var var) shape_vars repr_vars res_ty
699                 =<< go prods rss vars body
700         go _ _ _ _ = panic "buildFromArrPRepr/go"
701
702     from_repr repr expr shape_vars [repr_vars] res_ty body
703       = from_prod repr expr shape_vars repr_vars res_ty body
704
705     from_repr _ _ _ _ _ _ = panic "buildFromArrPRepr/from_repr"
706
707     from_prod (ProdRepr { prod_components = tys
708                         , prod_arr_tycon  = tycon
709                         , prod_arr_data_con = data_con })
710               expr
711               shape_vars
712               repr_vars
713               res_ty
714               body
715       = do
716           let scrut    = unwrapFamInstScrut tycon tys expr
717               scrut_ty = mkTyConApp tycon tys
718
719           return $ mkWildCase scrut scrut_ty res_ty
720                    [(DataAlt data_con, shape_vars ++ repr_vars, body)]
721
722     from_prod (EnumRepr { enum_arr_tycon = tycon
723                         , enum_arr_data_con = data_con })
724               expr
725               shape_vars
726               _
727               res_ty
728               body
729       = let scrut    = unwrapFamInstScrut tycon [] expr
730             scrut_ty = mkTyConApp tycon []
731         in
732         return $ mkWildCase scrut scrut_ty res_ty
733                  [(DataAlt data_con, shape_vars, body)]
734
735     from_prod (IdRepr _)
736               expr
737               _shape_vars
738               [repr_var]
739               _res_ty
740               body
741       = return $ Let (NonRec repr_var expr) body
742
743     from_prod (VoidRepr {})
744               expr
745               _shape_vars
746               [repr_var]
747               _res_ty
748               body
749       = return $ Let (NonRec repr_var expr) body
750
751     from_prod _ _ _ _ _ _ = panic "buildFromArrPRepr/from_prod"
752
753 buildPRDictRepr :: Repr -> VM CoreExpr
754 buildPRDictRepr (VoidRepr { void_tycon = tycon })
755   = prDFunOfTyCon tycon
756 buildPRDictRepr (IdRepr ty) = mkPR ty
757 buildPRDictRepr (ProdRepr {
758                    prod_components = tys
759                  , prod_tycon      = tycon
760                  })
761   = do
762       prs  <- mapM mkPR tys
763       dfun <- prDFunOfTyCon tycon
764       return $ dfun `mkTyApps` tys `mkApps` prs
765
766 buildPRDictRepr (SumRepr {
767                    sum_components = prods
768                  , sum_tycon      = tycon })
769   = do
770       prs  <- mapM buildPRDictRepr prods
771       dfun <- prDFunOfTyCon tycon
772       return $ dfun `mkTyApps` map reprType prods `mkApps` prs
773
774 buildPRDictRepr (EnumRepr { enum_tycon = tycon })
775   = prDFunOfTyCon tycon
776
777 buildPRDict :: Repr -> TyCon -> TyCon -> TyCon -> VM CoreExpr
778 buildPRDict repr vect_tc prepr_tc _
779   = do
780       dict  <- buildPRDictRepr repr
781
782       pr_co <- mkBuiltinCo prTyCon
783       let co = mkAppCoercion pr_co
784              . mkSymCoercion
785              $ mkTyConApp arg_co var_tys
786
787       return $ mkCoerce co dict
788   where
789     var_tys = mkTyVarTys $ tyConTyVars vect_tc
790
791     Just arg_co = tyConFamilyCoercion_maybe prepr_tc
792
793 buildPArrayTyCon :: TyCon -> TyCon -> VM TyCon
794 buildPArrayTyCon orig_tc vect_tc = fixV $ \repr_tc ->
795   do
796     name'  <- cloneName mkPArrayTyConOcc orig_name
797     rhs    <- buildPArrayTyConRhs orig_name vect_tc repr_tc
798     parray <- builtin parrayTyCon
799
800     liftDs $ buildAlgTyCon name'
801                            tyvars
802                            []          -- no stupid theta
803                            rhs
804                            rec_flag    -- FIXME: is this ok?
805                            False       -- FIXME: no generics
806                            False       -- not GADT syntax
807                            (Just $ mk_fam_inst parray vect_tc)
808   where
809     orig_name = tyConName orig_tc
810     tyvars = tyConTyVars vect_tc
811     rec_flag = boolToRecFlag (isRecursiveTyCon vect_tc)
812
813
814 buildPArrayTyConRhs :: Name -> TyCon -> TyCon -> VM AlgTyConRhs
815 buildPArrayTyConRhs orig_name vect_tc repr_tc
816   = do
817       data_con <- buildPArrayDataCon orig_name vect_tc repr_tc
818       return $ DataTyCon { data_cons = [data_con], is_enum = False }
819
820 buildPArrayDataCon :: Name -> TyCon -> TyCon -> VM DataCon
821 buildPArrayDataCon orig_name vect_tc repr_tc
822   = do
823       dc_name  <- cloneName mkPArrayDataConOcc orig_name
824       repr     <- mkRepr vect_tc
825
826       shape_tys <- arrShapeTys repr
827       repr_tys  <- arrReprTys  repr
828
829       let tys = shape_tys ++ repr_tys
830           tvs = tyConTyVars vect_tc
831
832       liftDs $ buildDataCon dc_name
833                             False                  -- not infix
834                             (map (const NotMarkedStrict) tys)
835                             []                     -- no field labels
836                             tvs
837                             []                     -- no existentials
838                             []                     -- no eq spec
839                             []                     -- no context
840                             tys
841                             (mkFamilyTyConApp repr_tc (mkTyVarTys tvs))
842                             repr_tc
843
844 mkPADFun :: TyCon -> VM Var
845 mkPADFun vect_tc
846   = newExportedVar (mkPADFunOcc $ getOccName vect_tc) =<< paDFunType vect_tc
847
848 buildTyConBindings :: TyCon -> TyCon -> TyCon -> TyCon -> Var
849                    -> VM [(Var, CoreExpr)]
850 buildTyConBindings orig_tc vect_tc prepr_tc arr_tc dfun
851   = do
852       repr  <- mkRepr vect_tc
853       vectDataConWorkers repr orig_tc vect_tc arr_tc
854       dict <- buildPADict repr vect_tc prepr_tc arr_tc dfun
855       binds <- takeHoisted
856       return $ (dfun, dict) : binds
857
858 vectDataConWorkers :: Repr -> TyCon -> TyCon -> TyCon
859                    -> VM ()
860 vectDataConWorkers repr orig_tc vect_tc arr_tc
861   = do
862       bs <- sequence
863           . zipWith3 def_worker  (tyConDataCons orig_tc) rep_tys
864           $ zipWith4 mk_data_con (tyConDataCons vect_tc)
865                                  rep_tys
866                                  (inits reprs)
867                                  (tail $ tails reprs)
868       mapM_ (uncurry hoistBinding) bs
869   where
870     tyvars   = tyConTyVars vect_tc
871     var_tys  = mkTyVarTys tyvars
872     ty_args  = map Type var_tys
873
874     res_ty   = mkTyConApp vect_tc var_tys
875
876     rep_tys  = map dataConRepArgTys $ tyConDataCons vect_tc
877     reprs    = splitSumRepr repr
878
879     [arr_dc] = tyConDataCons arr_tc
880
881     mk_data_con con tys pre post
882       = liftM2 (,) (vect_data_con con)
883                    (lift_data_con tys pre post (mkDataConTag con))
884
885     vect_data_con con = return $ mkConApp con ty_args
886     lift_data_con tys pre_reprs post_reprs tag
887       = do
888           len  <- builtin liftingContext
889           args <- mapM (newLocalVar (fsLit "xs"))
890                   =<< mapM mkPArrayType tys
891
892           shape <- replicateShape repr (Var len) tag
893           repr  <- mk_arr_repr (Var len) (map Var args)
894
895           pre   <- liftM concat $ mapM emptyArrRepr pre_reprs
896           post  <- liftM concat $ mapM emptyArrRepr post_reprs
897
898           return . mkLams (len : args)
899                  . wrapFamInstBody arr_tc var_tys
900                  . mkConApp arr_dc
901                  $ ty_args ++ shape ++ pre ++ repr ++ post
902
903     mk_arr_repr len []
904       = do
905           units <- replicatePA len (Var unitDataConId)
906           return [units]
907
908     mk_arr_repr _ arrs = return arrs
909
910     def_worker data_con arg_tys mk_body
911       = do
912           body <- closedV
913                 . inBind orig_worker
914                 . polyAbstract tyvars $ \abstract ->
915                   liftM (abstract . vectorised)
916                 $ buildClosures tyvars [] arg_tys res_ty mk_body
917
918           vect_worker <- cloneId mkVectOcc orig_worker (exprType body)
919           defGlobalVar orig_worker vect_worker
920           return (vect_worker, body)
921       where
922         orig_worker = dataConWorkId data_con
923
924 buildPADict :: Repr -> TyCon -> TyCon -> TyCon -> Var -> VM CoreExpr
925 buildPADict repr vect_tc prepr_tc arr_tc _
926   = polyAbstract tvs $ \abstract ->
927     do
928       meth_binds <- mapM (mk_method repr) paMethods
929       let meth_exprs = map (Var . fst) meth_binds
930
931       pa_dc <- builtin paDataCon
932       let dict = mkConApp pa_dc (Type (mkTyConApp vect_tc arg_tys) : meth_exprs)
933           body = Let (Rec meth_binds) dict
934       return . mkInlineMe $ abstract body
935   where
936     tvs = tyConTyVars arr_tc
937     arg_tys = mkTyVarTys tvs
938
939     mk_method repr (name, build)
940       = localV
941       $ do
942           body <- build repr vect_tc prepr_tc arr_tc
943           var  <- newLocalVar name (exprType body)
944           return (var, mkInlineMe body)
945
946 paMethods :: [(FastString, Repr -> TyCon -> TyCon -> TyCon -> VM CoreExpr)]
947 paMethods = [(fsLit "toPRepr",      buildToPRepr),
948              (fsLit "fromPRepr",    buildFromPRepr),
949              (fsLit "toArrPRepr",   buildToArrPRepr),
950              (fsLit "fromArrPRepr", buildFromArrPRepr),
951              (fsLit "dictPRepr",    buildPRDict)]
952
953 -- | Split the given tycons into two sets depending on whether they have to be
954 -- converted (first list) or not (second list). The first argument contains
955 -- information about the conversion status of external tycons:
956 --
957 --   * tycons which have converted versions are mapped to True
958 --   * tycons which are not changed by vectorisation are mapped to False
959 --   * tycons which can't be converted are not elements of the map
960 --
961 classifyTyCons :: UniqFM Bool -> [TyConGroup] -> ([TyCon], [TyCon])
962 classifyTyCons = classify [] []
963   where
964     classify conv keep _  [] = (conv, keep)
965     classify conv keep cs ((tcs, ds) : rs)
966       | can_convert && must_convert
967         = classify (tcs ++ conv) keep (cs `addListToUFM` [(tc,True) | tc <- tcs]) rs
968       | can_convert
969         = classify conv (tcs ++ keep) (cs `addListToUFM` [(tc,False) | tc <- tcs]) rs
970       | otherwise
971         = classify conv keep cs rs
972       where
973         refs = ds `delListFromUniqSet` tcs
974
975         can_convert  = isNullUFM (refs `minusUFM` cs) && all convertable tcs
976         must_convert = foldUFM (||) False (intersectUFM_C const cs refs)
977
978         convertable tc = isDataTyCon tc && all isVanillaDataCon (tyConDataCons tc)
979
980 -- | Compute mutually recursive groups of tycons in topological order
981 --
982 tyConGroups :: [TyCon] -> [TyConGroup]
983 tyConGroups tcs = map mk_grp (stronglyConnCompFromEdgedVertices edges)
984   where
985     edges = [((tc, ds), tc, uniqSetToList ds) | tc <- tcs
986                                 , let ds = tyConsOfTyCon tc]
987
988     mk_grp (AcyclicSCC (tc, ds)) = ([tc], ds)
989     mk_grp (CyclicSCC els)       = (tcs, unionManyUniqSets dss)
990       where
991         (tcs, dss) = unzip els
992
993 tyConsOfTyCon :: TyCon -> UniqSet TyCon
994 tyConsOfTyCon
995   = tyConsOfTypes . concatMap dataConRepArgTys . tyConDataCons
996
997 tyConsOfType :: Type -> UniqSet TyCon
998 tyConsOfType ty
999   | Just ty' <- coreView ty    = tyConsOfType ty'
1000 tyConsOfType (TyVarTy _)       = emptyUniqSet
1001 tyConsOfType (TyConApp tc tys) = extend (tyConsOfTypes tys)
1002   where
1003     extend | isUnLiftedTyCon tc
1004            || isTupleTyCon   tc = id
1005
1006            | otherwise          = (`addOneToUniqSet` tc)
1007
1008 tyConsOfType (AppTy a b)       = tyConsOfType a `unionUniqSets` tyConsOfType b
1009 tyConsOfType (FunTy a b)       = (tyConsOfType a `unionUniqSets` tyConsOfType b)
1010                                  `addOneToUniqSet` funTyCon
1011 tyConsOfType (ForAllTy _ ty)   = tyConsOfType ty
1012 tyConsOfType other             = pprPanic "ClosureConv.tyConsOfType" $ ppr other
1013
1014 tyConsOfTypes :: [Type] -> UniqSet TyCon
1015 tyConsOfTypes = unionManyUniqSets . map tyConsOfType
1016
1017
1018 -- ----------------------------------------------------------------------------
1019 -- Conversions
1020
1021 fromVect :: Type -> CoreExpr -> VM CoreExpr
1022 fromVect ty expr | Just ty' <- coreView ty = fromVect ty' expr
1023 fromVect (FunTy arg_ty res_ty) expr
1024   = do
1025       arg     <- newLocalVar (fsLit "x") arg_ty
1026       varg    <- toVect arg_ty (Var arg)
1027       varg_ty <- vectType arg_ty
1028       vres_ty <- vectType res_ty
1029       apply   <- builtin applyClosureVar
1030       body    <- fromVect res_ty
1031                $ Var apply `mkTyApps` [varg_ty, vres_ty] `mkApps` [expr, varg]
1032       return $ Lam arg body
1033 fromVect ty expr
1034   = identityConv ty >> return expr
1035
1036 toVect :: Type -> CoreExpr -> VM CoreExpr
1037 toVect ty expr = identityConv ty >> return expr
1038
1039 identityConv :: Type -> VM ()
1040 identityConv ty | Just ty' <- coreView ty = identityConv ty'
1041 identityConv (TyConApp tycon tys)
1042   = do
1043       mapM_ identityConv tys
1044       identityConvTyCon tycon
1045 identityConv _ = noV
1046
1047 identityConvTyCon :: TyCon -> VM ()
1048 identityConvTyCon tc
1049   | isBoxedTupleTyCon tc = return ()
1050   | isUnLiftedTyCon tc   = return ()
1051   | otherwise            = do
1052                              tc' <- maybeV (lookupTyCon tc)
1053                              if tc == tc' then return () else noV
1054