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