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