Vectorise polyexprs with notes
[ghc-hetmet.git] / compiler / vectorise / Vectorise.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 Vectorise( vectorise )
9 where
10
11 #include "HsVersions.h"
12
13 import VectMonad
14 import VectUtils
15 import VectType
16 import VectCore
17
18 import DynFlags
19 import HscTypes
20
21 import CoreLint             ( showPass, endPass )
22 import CoreSyn
23 import CoreUtils
24 import CoreFVs
25 import SimplMonad           ( SimplCount, zeroSimplCount )
26 import Rules                ( RuleBase )
27 import DataCon
28 import TyCon
29 import Type
30 import FamInstEnv           ( extendFamInstEnvList )
31 import InstEnv              ( extendInstEnvList )
32 import Var
33 import VarEnv
34 import VarSet
35 import Name                 ( Name, mkSysTvName, getName )
36 import NameEnv
37 import Id
38 import MkId                 ( unwrapFamInstScrut )
39 import OccName
40 import Module               ( Module )
41
42 import DsMonad hiding (mapAndUnzipM)
43 import DsUtils              ( mkCoreTup, mkCoreTupTy )
44
45 import Literal              ( Literal )
46 import PrelNames
47 import TysWiredIn
48 import TysPrim              ( intPrimTy )
49 import BasicTypes           ( Boxity(..) )
50
51 import Outputable
52 import FastString
53 import Control.Monad        ( liftM, liftM2, zipWithM, mapAndUnzipM )
54 import Data.List            ( sortBy, unzip4 )
55
56 vectorise :: HscEnv -> UniqSupply -> RuleBase -> ModGuts
57           -> IO (SimplCount, ModGuts)
58 vectorise hsc_env _ _ guts
59   = do
60       showPass dflags "Vectorisation"
61       eps <- hscEPS hsc_env
62       let info = hptVectInfo hsc_env `plusVectInfo` eps_vect_info eps
63       Just (info', guts') <- initV hsc_env guts info (vectModule guts)
64       endPass dflags "Vectorisation" Opt_D_dump_vect (mg_binds guts')
65       return (zeroSimplCount dflags, guts' { mg_vect_info = info' })
66   where
67     dflags = hsc_dflags hsc_env
68
69 vectModule :: ModGuts -> VM ModGuts
70 vectModule guts
71   = do
72       (types', fam_insts, tc_binds) <- vectTypeEnv (mg_types guts)
73       
74       let fam_inst_env' = extendFamInstEnvList (mg_fam_inst_env guts) fam_insts
75       updGEnv (setFamInstEnv fam_inst_env')
76      
77       -- dicts   <- mapM buildPADict pa_insts
78       -- workers <- mapM vectDataConWorkers pa_insts
79       binds'  <- mapM vectTopBind (mg_binds guts)
80       return $ guts { mg_types        = types'
81                     , mg_binds        = Rec tc_binds : binds'
82                     , mg_fam_inst_env = fam_inst_env'
83                     , mg_fam_insts    = mg_fam_insts guts ++ fam_insts
84                     }
85
86 vectTopBind :: CoreBind -> VM CoreBind
87 vectTopBind b@(NonRec var expr)
88   = do
89       var'  <- vectTopBinder var
90       expr' <- vectTopRhs var expr
91       hs    <- takeHoisted
92       cexpr <- tryConvert var var' expr
93       return . Rec $ (var, cexpr) : (var', expr') : hs
94   `orElseV`
95     return b
96
97 vectTopBind b@(Rec bs)
98   = do
99       vars'  <- mapM vectTopBinder vars
100       exprs' <- zipWithM vectTopRhs vars exprs
101       hs     <- takeHoisted
102       cexprs <- sequence $ zipWith3 tryConvert vars vars' exprs
103       return . Rec $ zip vars cexprs ++ zip vars' exprs' ++ hs
104   `orElseV`
105     return b
106   where
107     (vars, exprs) = unzip bs
108
109 vectTopBinder :: Var -> VM Var
110 vectTopBinder var
111   = do
112       vty  <- vectType (idType var)
113       var' <- cloneId mkVectOcc var vty
114       defGlobalVar var var'
115       return var'
116     
117 vectTopRhs :: Var -> CoreExpr -> VM CoreExpr
118 vectTopRhs var expr
119   = do
120       closedV . liftM vectorised
121               . inBind var
122               $ vectPolyExpr (freeVars expr)
123
124 tryConvert :: Var -> Var -> CoreExpr -> VM CoreExpr
125 tryConvert var vect_var rhs
126   = fromVect (idType var) (Var vect_var) `orElseV` return rhs
127
128 -- ----------------------------------------------------------------------------
129 -- Bindings
130
131 vectBndr :: Var -> VM VVar
132 vectBndr v
133   = do
134       vty <- vectType (idType v)
135       lty <- mkPArrayType vty
136       let vv = v `Id.setIdType` vty
137           lv = v `Id.setIdType` lty
138       updLEnv (mapTo vv lv)
139       return (vv, lv)
140   where
141     mapTo vv lv env = env { local_vars = extendVarEnv (local_vars env) v (vv, lv) }
142
143 vectBndrNew :: Var -> FastString -> VM VVar
144 vectBndrNew v fs
145   = do
146       vty <- vectType (idType v)
147       vv  <- newLocalVVar fs vty
148       updLEnv (upd vv)
149       return vv
150   where
151     upd vv env = env { local_vars = extendVarEnv (local_vars env) v vv }
152
153 vectBndrIn :: Var -> VM a -> VM (VVar, a)
154 vectBndrIn v p
155   = localV
156   $ do
157       vv <- vectBndr v
158       x <- p
159       return (vv, x)
160
161 vectBndrNewIn :: Var -> FastString -> VM a -> VM (VVar, a)
162 vectBndrNewIn v fs p
163   = localV
164   $ do
165       vv <- vectBndrNew v fs
166       x  <- p
167       return (vv, x)
168
169 vectBndrIn' :: Var -> (VVar -> VM a) -> VM (VVar, a)
170 vectBndrIn' v p
171   = localV
172   $ do
173       vv <- vectBndr v
174       x  <- p vv
175       return (vv, x)
176
177 vectBndrsIn :: [Var] -> VM a -> VM ([VVar], a)
178 vectBndrsIn vs p
179   = localV
180   $ do
181       vvs <- mapM vectBndr vs
182       x <- p
183       return (vvs, x)
184
185 -- ----------------------------------------------------------------------------
186 -- Expressions
187
188 vectVar :: Var -> VM VExpr
189 vectVar v
190   = do
191       r <- lookupVar v
192       case r of
193         Local (vv,lv) -> return (Var vv, Var lv)
194         Global vv     -> do
195                            let vexpr = Var vv
196                            lexpr <- liftPA vexpr
197                            return (vexpr, lexpr)
198
199 vectPolyVar :: Var -> [Type] -> VM VExpr
200 vectPolyVar v tys
201   = do
202       vtys <- mapM vectType tys
203       r <- lookupVar v
204       case r of
205         Local (vv, lv) -> liftM2 (,) (polyApply (Var vv) vtys)
206                                      (polyApply (Var lv) vtys)
207         Global poly    -> do
208                             vexpr <- polyApply (Var poly) vtys
209                             lexpr <- liftPA vexpr
210                             return (vexpr, lexpr)
211
212 vectLiteral :: Literal -> VM VExpr
213 vectLiteral lit
214   = do
215       lexpr <- liftPA (Lit lit)
216       return (Lit lit, lexpr)
217
218 vectPolyExpr :: CoreExprWithFVs -> VM VExpr
219 vectPolyExpr (_, AnnNote note expr)
220   = liftM (vNote note) $ vectPolyExpr expr
221 vectPolyExpr expr
222   = polyAbstract tvs $ \abstract ->
223     do
224       mono' <- vectExpr mono
225       return $ mapVect abstract mono'
226   where
227     (tvs, mono) = collectAnnTypeBinders expr  
228                 
229 vectExpr :: CoreExprWithFVs -> VM VExpr
230 vectExpr (_, AnnType ty)
231   = liftM vType (vectType ty)
232
233 vectExpr (_, AnnVar v) = vectVar v
234
235 vectExpr (_, AnnLit lit) = vectLiteral lit
236
237 vectExpr (_, AnnNote note expr)
238   = liftM (vNote note) (vectExpr expr)
239
240 vectExpr e@(_, AnnApp _ arg)
241   | isAnnTypeArg arg
242   = vectTyAppExpr fn tys
243   where
244     (fn, tys) = collectAnnTypeArgs e
245
246 vectExpr (_, AnnApp fn arg)
247   = do
248       arg_ty' <- vectType arg_ty
249       res_ty' <- vectType res_ty
250       fn'     <- vectExpr fn
251       arg'    <- vectExpr arg
252       mkClosureApp arg_ty' res_ty' fn' arg'
253   where
254     (arg_ty, res_ty) = splitFunTy . exprType $ deAnnotate fn
255
256 vectExpr (_, AnnCase scrut bndr ty alts)
257   | Just (tycon, ty_args) <- splitTyConApp_maybe scrut_ty
258   , isAlgTyCon tycon
259   = vectAlgCase tycon ty_args scrut bndr ty alts
260   where
261     scrut_ty = exprType (deAnnotate scrut)
262
263 vectExpr (_, AnnCase expr bndr ty alts)
264   = panic "vectExpr: case"
265
266 vectExpr (_, AnnLet (AnnNonRec bndr rhs) body)
267   = do
268       vrhs <- localV . inBind bndr $ vectPolyExpr rhs
269       (vbndr, vbody) <- vectBndrIn bndr (vectExpr body)
270       return $ vLet (vNonRec vbndr vrhs) vbody
271
272 vectExpr (_, AnnLet (AnnRec bs) body)
273   = do
274       (vbndrs, (vrhss, vbody)) <- vectBndrsIn bndrs
275                                 $ liftM2 (,)
276                                   (zipWithM vect_rhs bndrs rhss)
277                                   (vectPolyExpr body)
278       return $ vLet (vRec vbndrs vrhss) vbody
279   where
280     (bndrs, rhss) = unzip bs
281
282     vect_rhs bndr rhs = localV
283                       . inBind bndr
284                       $ vectExpr rhs
285
286 vectExpr e@(fvs, AnnLam bndr _)
287   | not (isId bndr) = pprPanic "vectExpr" (ppr $ deAnnotate e)
288   | otherwise = vectLam fvs bs body
289   where
290     (bs,body) = collectAnnValBinders e
291
292 vectLam :: VarSet -> [Var] -> CoreExprWithFVs -> VM VExpr
293 vectLam fvs bs body
294   = do
295       tyvars <- localTyVars
296       (vs, vvs) <- readLEnv $ \env ->
297                    unzip [(var, vv) | var <- varSetElems fvs
298                                     , Just vv <- [lookupVarEnv (local_vars env) var]]
299
300       arg_tys <- mapM (vectType . idType) bs
301       res_ty  <- vectType (exprType $ deAnnotate body)
302
303       buildClosures tyvars vvs arg_tys res_ty
304         . hoistPolyVExpr tyvars
305         $ do
306             lc <- builtin liftingContext
307             (vbndrs, vbody) <- vectBndrsIn (vs ++ bs)
308                                            (vectExpr body)
309             return $ vLams lc vbndrs vbody
310   
311 vectTyAppExpr :: CoreExprWithFVs -> [Type] -> VM VExpr
312 vectTyAppExpr (_, AnnVar v) tys = vectPolyVar v tys
313 vectTyAppExpr e tys = pprPanic "vectTyAppExpr" (ppr $ deAnnotate e)
314
315 type CoreAltWithFVs = AnnAlt Id VarSet
316
317 -- We convert
318 --
319 --   case e :: t of v { ... }
320 --
321 -- to
322 --
323 --   V:    let v' = e in case v' of _ { ... }
324 --   L:    let v' = e in case v' `cast` ... of _ { ... }
325 --
326 -- When lifting, we have to do it this way because v must have the type
327 -- [:V(T):] but the scrutinee must be cast to the representation type. We also
328 -- have to handle the case where v is a wild var correctly.
329 --   
330
331 -- FIXME: this is too lazy
332 vectAlgCase tycon ty_args scrut bndr ty [(DEFAULT, [], body)]
333   = do
334       vscrut <- vectExpr scrut
335       vty    <- vectType ty
336       lty    <- mkPArrayType vty
337       (vbndr, vbody) <- vectBndrIn bndr (vectExpr body)
338       return $ vCaseDEFAULT vscrut vbndr vty lty vbody
339
340 vectAlgCase tycon ty_args scrut bndr ty [(DataAlt dc, bndrs, body)]
341   = do
342       vect_tc <- maybeV (lookupTyCon tycon)
343       vty <- vectType ty
344       lty <- mkPArrayType vty
345       vexpr <- vectExpr scrut
346       (vbndr, (vbndrs, vbody)) <- vect_scrut_bndr
347                                 . vectBndrsIn bndrs
348                                 $ vectExpr body
349
350       (vscrut, arr_tc, arg_tys) <- mkVScrut (vVar vbndr)
351       vect_dc <- maybeV (lookupDataCon dc)
352       let [arr_dc] = tyConDataCons arr_tc
353       repr <- mkRepr vect_tc
354       shape_bndrs <- arrShapeVars repr
355       return . vLet (vNonRec vbndr vexpr)
356              $ vCaseProd vscrut vty lty vect_dc arr_dc shape_bndrs vbndrs vbody
357   where
358     vect_scrut_bndr | isDeadBinder bndr = vectBndrNewIn bndr FSLIT("scrut")
359                     | otherwise         = vectBndrIn bndr
360
361 vectAlgCase tycon ty_args scrut bndr ty alts
362   = do
363       vect_tc <- maybeV (lookupTyCon tycon)
364       vty               <- vectType ty
365       lty               <- mkPArrayType vty
366
367       repr        <- mkRepr vect_tc
368       shape_bndrs <- arrShapeVars repr
369       (len, sel, indices) <- arrSelector repr (map Var shape_bndrs)
370
371       (vbndr, valts) <- vect_scrut_bndr $ mapM (proc_alt sel lty) alts'
372       let (vect_dcs, vect_bndrss, lift_bndrss, vbodies) = unzip4 valts
373
374       vexpr <- vectExpr scrut
375       (vscrut, arr_tc, arg_tys) <- mkVScrut (vVar vbndr)
376       let [arr_dc] = tyConDataCons arr_tc
377
378       let (vect_scrut,  lift_scrut)  = vscrut
379           (vect_bodies, lift_bodies) = unzip vbodies
380
381       let vect_case = Case vect_scrut (mkWildId (exprType vect_scrut)) vty
382                            (zipWith3 mk_vect_alt vect_dcs vect_bndrss vect_bodies)
383
384       lbody <- combinePA vty len sel indices lift_bodies
385       let lift_case = Case lift_scrut (mkWildId (exprType lift_scrut)) lty
386                            [(DataAlt arr_dc, shape_bndrs ++ concat lift_bndrss,
387                              lbody)]
388
389       return . vLet (vNonRec vbndr vexpr)
390              $ (vect_case, lift_case)
391   where
392     vect_scrut_bndr | isDeadBinder bndr = vectBndrNewIn bndr FSLIT("scrut")
393                     | otherwise         = vectBndrIn bndr
394
395     alts' = sortBy (\(alt1, _, _) (alt2, _, _) -> cmp alt1 alt2) alts
396
397     cmp (DataAlt dc1) (DataAlt dc2) = dataConTag dc1 `compare` dataConTag dc2
398     cmp DEFAULT       DEFAULT       = EQ
399     cmp DEFAULT       _             = LT
400     cmp _             DEFAULT       = GT
401
402     proc_alt sel lty (DataAlt dc, bndrs, body)
403       = do
404           vect_dc <- maybeV (lookupDataCon dc)
405           let tag = mkDataConTag vect_dc
406               fvs = freeVarsOf body `delVarSetList` bndrs
407           (vect_bndrs, lift_bndrs, vbody)
408             <- vect_alt_bndrs bndrs
409              $ \len -> packLiftingContext len sel tag fvs lty
410              $ vectExpr body
411
412           return (vect_dc, vect_bndrs, lift_bndrs, vbody)
413
414     vect_alt_bndrs [] p
415       = do
416           void_tc <- builtin voidTyCon
417           let void_ty = mkTyConApp void_tc []
418           arr_ty <- mkPArrayType void_ty
419           bndr   <- newLocalVar FSLIT("voids") arr_ty
420           len    <- lengthPA void_ty (Var bndr)
421           e      <- p len
422           return ([], [bndr], e)
423
424     vect_alt_bndrs bndrs p
425        = localV
426        $ do
427            vbndrs <- mapM vectBndr bndrs
428            let (vect_bndrs, lift_bndrs) = unzip vbndrs
429                vv : _ = vect_bndrs
430                lv : _ = lift_bndrs
431            len <- lengthPA (idType vv) (Var lv)
432            e   <- p len
433            return (vect_bndrs, lift_bndrs, e)
434
435     mk_vect_alt vect_dc bndrs body = (DataAlt vect_dc, bndrs, body)
436
437 packLiftingContext :: CoreExpr -> CoreExpr -> CoreExpr -> VarSet -> Type -> VM VExpr -> VM VExpr
438 packLiftingContext len shape tag fvs res_ty p
439   = do
440       select <- builtin selectPAIntPrimVar
441       let sel_expr = mkApps (Var select) [shape, tag]
442       sel_var <- newLocalVar FSLIT("sel#") (exprType sel_expr)
443       lc_var <- builtin liftingContext
444       localV $
445         do
446           bnds <- mapM (packFreeVar (Var lc_var) (Var sel_var))
447                 . filter isLocalId
448                 $ varSetElems fvs
449           (vexpr, lexpr) <- p
450           return (vexpr, Let (NonRec sel_var sel_expr)
451                          . mkLets (concat bnds)
452                          $ Case len lc_var res_ty [(DEFAULT, [], lexpr)])
453
454 packFreeVar :: CoreExpr -> CoreExpr -> Var -> VM [CoreBind]
455 packFreeVar len sel v
456   = do
457       r <- lookupVar v
458       case r of
459         Local (vv,lv) ->
460           do
461             lv' <- cloneVar lv
462             expr <- packPA (idType vv) (Var lv) len sel
463             updLEnv (upd vv lv')
464             return [(NonRec lv' expr)]
465
466         _  -> return []
467   where
468     upd vv lv' env = env { local_vars = extendVarEnv (local_vars env) v (vv, lv') }
469