2 -- | The Vectorisation monad.
7 noV, traceNoV, ensureV, traceEnsureV, tryV, maybeV, traceMaybeV, orElseV,
8 onlyIfV, fixV, localV, closedV,
9 initV, cantVectorise, maybeCantVectorise, maybeCantVectoriseM,
11 cloneName, cloneId, cloneVar,
12 newExportedVar, newLocalVar, newLocalVars, newDummyVar, newTyVar,
14 Builtins(..), sumTyCon, prodTyCon, prodDataCon,
15 selTy, selReplicate, selPick, selTags, selElements,
16 combinePDVar, scalarZip, closureCtrFun,
21 readGEnv, setGEnv, updGEnv,
24 readLEnv, setLEnv, updLEnv,
28 lookupVar, defGlobalVar, globalScalars,
29 lookupTyCon, defTyCon,
30 lookupDataCon, defDataCon,
31 lookupTyConPA, defTyConPA, defTyConPAs,
34 lookupPrimMethod, lookupPrimPArray,
35 lookupTyVarPA, defLocalTyVar, defLocalTyVarWithPA, localTyVars,
37 lookupInst, lookupFamInst
40 #include "HsVersions.h"
44 import HscTypes hiding ( MonadThings(..) )
45 import Module ( PackageId )
65 import SrcLoc ( noSrcSpan )
69 -- | Indicates what scope something (a variable) is in.
70 data Scope a b = Global a | Local b
73 -- | The global environment.
74 data GlobalEnv = GlobalEnv {
75 -- | Mapping from global variables to their vectorised versions.
77 global_vars :: VarEnv Var
79 -- | Purely scalar variables. Code which mentions only these
80 -- variables doesn't have to be lifted.
81 , global_scalars :: VarSet
83 -- | Exported variables which have a vectorised version
85 , global_exported_vars :: VarEnv (Var, Var)
87 -- | Mapping from TyCons to their vectorised versions.
88 -- TyCons which do not have to be vectorised are mapped to
91 , global_tycons :: NameEnv TyCon
93 -- | Mapping from DataCons to their vectorised versions
95 , global_datacons :: NameEnv DataCon
97 -- | Mapping from TyCons to their PA dfuns
99 , global_pa_funs :: NameEnv Var
101 -- | Mapping from TyCons to their PR dfuns
102 , global_pr_funs :: NameEnv Var
104 -- | Mapping from unboxed TyCons to their boxed versions
105 , global_boxed_tycons :: NameEnv TyCon
107 -- | External package inst-env & home-package inst-env for class
110 , global_inst_env :: (InstEnv, InstEnv)
112 -- | External package inst-env & home-package inst-env for family
115 , global_fam_inst_env :: FamInstEnvs
117 -- | Hoisted bindings
118 , global_bindings :: [(Var, CoreExpr)]
121 -- | The local environment.
122 data LocalEnv = LocalEnv {
123 -- Mapping from local variables to their vectorised and
126 local_vars :: VarEnv (Var, Var)
128 -- In-scope type variables
130 , local_tyvars :: [TyVar]
132 -- Mapping from tyvars to their PA dictionaries
133 , local_tyvar_pa :: VarEnv CoreExpr
135 -- Local binding name
136 , local_bind_name :: FastString
140 -- | Create an initial global environment
141 initGlobalEnv :: VectInfo -> (InstEnv, InstEnv) -> FamInstEnvs -> GlobalEnv
142 initGlobalEnv info instEnvs famInstEnvs
144 global_vars = mapVarEnv snd $ vectInfoVar info
145 , global_scalars = emptyVarSet
146 , global_exported_vars = emptyVarEnv
147 , global_tycons = mapNameEnv snd $ vectInfoTyCon info
148 , global_datacons = mapNameEnv snd $ vectInfoDataCon info
149 , global_pa_funs = mapNameEnv snd $ vectInfoPADFun info
150 , global_pr_funs = emptyNameEnv
151 , global_boxed_tycons = emptyNameEnv
152 , global_inst_env = instEnvs
153 , global_fam_inst_env = famInstEnvs
154 , global_bindings = []
158 -- Operators on Global Environments -------------------------------------------
159 extendImportedVarsEnv :: [(Var, Var)] -> GlobalEnv -> GlobalEnv
160 extendImportedVarsEnv ps genv
161 = genv { global_vars = extendVarEnvList (global_vars genv) ps }
163 extendScalars :: [Var] -> GlobalEnv -> GlobalEnv
164 extendScalars vs genv
165 = genv { global_scalars = extendVarSetList (global_scalars genv) vs }
167 setFamInstEnv :: FamInstEnv -> GlobalEnv -> GlobalEnv
168 setFamInstEnv l_fam_inst genv
169 = genv { global_fam_inst_env = (g_fam_inst, l_fam_inst) }
171 (g_fam_inst, _) = global_fam_inst_env genv
173 extendTyConsEnv :: [(Name, TyCon)] -> GlobalEnv -> GlobalEnv
174 extendTyConsEnv ps genv
175 = genv { global_tycons = extendNameEnvList (global_tycons genv) ps }
177 extendDataConsEnv :: [(Name, DataCon)] -> GlobalEnv -> GlobalEnv
178 extendDataConsEnv ps genv
179 = genv { global_datacons = extendNameEnvList (global_datacons genv) ps }
181 extendPAFunsEnv :: [(Name, Var)] -> GlobalEnv -> GlobalEnv
182 extendPAFunsEnv ps genv
183 = genv { global_pa_funs = extendNameEnvList (global_pa_funs genv) ps }
185 setPRFunsEnv :: [(Name, Var)] -> GlobalEnv -> GlobalEnv
187 = genv { global_pr_funs = mkNameEnv ps }
189 setBoxedTyConsEnv :: [(Name, TyCon)] -> GlobalEnv -> GlobalEnv
190 setBoxedTyConsEnv ps genv
191 = genv { global_boxed_tycons = mkNameEnv ps }
194 -- | Create an empty local environment.
195 emptyLocalEnv :: LocalEnv
196 emptyLocalEnv = LocalEnv {
197 local_vars = emptyVarEnv
199 , local_tyvar_pa = emptyVarEnv
200 , local_bind_name = fsLit "fn"
204 updVectInfo :: GlobalEnv -> TypeEnv -> VectInfo -> VectInfo
205 updVectInfo env tyenv info
207 vectInfoVar = global_exported_vars env
208 , vectInfoTyCon = mk_env typeEnvTyCons global_tycons
209 , vectInfoDataCon = mk_env typeEnvDataCons global_datacons
210 , vectInfoPADFun = mk_env typeEnvTyCons global_pa_funs
213 mk_env from_tyenv from_env = mkNameEnv [(name, (from,to))
214 | from <- from_tyenv tyenv
215 , let name = getName from
216 , Just to <- [lookupNameEnv (from_env env) name]]
219 -- The Vectorisation Monad ----------------------------------------------------
221 -- Vectorisation can either succeed with new envionment and a value,
222 -- or return with failure.
224 data VResult a = Yes GlobalEnv LocalEnv a | No
226 newtype VM a = VM { runVM :: Builtins -> GlobalEnv -> LocalEnv -> DsM (VResult a) }
228 instance Monad VM where
229 return x = VM $ \_ genv lenv -> return (Yes genv lenv x)
230 VM p >>= f = VM $ \bi genv lenv -> do
233 Yes genv' lenv' x -> runVM (f x) bi genv' lenv'
237 -- | Throw an error saying we can't vectorise something
238 cantVectorise :: String -> SDoc -> a
239 cantVectorise s d = pgmError
241 $ vcat [text "*** Vectorisation error ***",
242 nest 4 $ sep [text s, nest 4 d]]
244 maybeCantVectorise :: String -> SDoc -> Maybe a -> a
245 maybeCantVectorise s d Nothing = cantVectorise s d
246 maybeCantVectorise _ _ (Just x) = x
248 maybeCantVectoriseM :: Monad m => String -> SDoc -> m (Maybe a) -> m a
249 maybeCantVectoriseM s d p
254 Nothing -> cantVectorise s d
257 -- Control --------------------------------------------------------------------
258 -- | Return some result saying we've failed.
260 noV = VM $ \_ _ _ -> return No
262 traceNoV :: String -> SDoc -> VM a
263 traceNoV s d = pprTrace s d noV
266 -- | If True then carry on, otherwise fail.
267 ensureV :: Bool -> VM ()
269 ensureV True = return ()
272 -- | If True then return the first argument, otherwise fail.
273 onlyIfV :: Bool -> VM a -> VM a
274 onlyIfV b p = ensureV b >> p
276 traceEnsureV :: String -> SDoc -> Bool -> VM ()
277 traceEnsureV s d False = traceNoV s d
278 traceEnsureV _ _ True = return ()
281 -- | Try some vectorisation computaton.
282 -- If it succeeds then return Just the result,
283 -- otherwise return Nothing.
284 tryV :: VM a -> VM (Maybe a)
285 tryV (VM p) = VM $ \bi genv lenv ->
289 Yes genv' lenv' x -> return (Yes genv' lenv' (Just x))
290 No -> return (Yes genv lenv Nothing)
293 maybeV :: VM (Maybe a) -> VM a
294 maybeV p = maybe noV return =<< p
296 traceMaybeV :: String -> SDoc -> VM (Maybe a) -> VM a
297 traceMaybeV s d p = maybe (traceNoV s d) return =<< p
299 orElseV :: VM a -> VM a -> VM a
300 orElseV p q = maybe q return =<< tryV p
302 fixV :: (a -> VM a) -> VM a
303 fixV f = VM (\bi genv lenv -> fixDs $ \r -> runVM (f (unYes r)) bi genv lenv )
305 -- NOTE: It is essential that we are lazy in r above so do not replace
306 -- calls to this function by an explicit case.
307 unYes (Yes _ _ x) = x
308 unYes No = panic "VectMonad.fixV: no result"
311 -- Local Environments ---------------------------------------------------------
312 -- | Perform a computation in its own local environment.
313 -- This does not alter the environment of the current state.
314 localV :: VM a -> VM a
321 -- | Perform a computation in an empty local environment.
322 closedV :: VM a -> VM a
325 setLEnv (emptyLocalEnv { local_bind_name = local_bind_name env })
330 -- Lifting --------------------------------------------------------------------
331 -- | Lift a desugaring computation into the vectorisation monad.
332 liftDs :: DsM a -> VM a
333 liftDs p = VM $ \_ genv lenv -> do { x <- p; return (Yes genv lenv x) }
337 -- Builtins -------------------------------------------------------------------
338 -- Operations on Builtins
339 liftBuiltinDs :: (Builtins -> DsM a) -> VM a
340 liftBuiltinDs p = VM $ \bi genv lenv -> do { x <- p bi; return (Yes genv lenv x)}
343 -- | Project something from the set of builtins.
344 builtin :: (Builtins -> a) -> VM a
345 builtin f = VM $ \bi genv lenv -> return (Yes genv lenv (f bi))
347 builtins :: (a -> Builtins -> b) -> VM (a -> b)
348 builtins f = VM $ \bi genv lenv -> return (Yes genv lenv (`f` bi))
351 -- Environments ---------------------------------------------------------------
352 -- | Project something from the global environment.
353 readGEnv :: (GlobalEnv -> a) -> VM a
354 readGEnv f = VM $ \_ genv lenv -> return (Yes genv lenv (f genv))
356 setGEnv :: GlobalEnv -> VM ()
357 setGEnv genv = VM $ \_ _ lenv -> return (Yes genv lenv ())
359 updGEnv :: (GlobalEnv -> GlobalEnv) -> VM ()
360 updGEnv f = VM $ \_ genv lenv -> return (Yes (f genv) lenv ())
363 -- | Project something from the local environment.
364 readLEnv :: (LocalEnv -> a) -> VM a
365 readLEnv f = VM $ \_ genv lenv -> return (Yes genv lenv (f lenv))
367 setLEnv :: LocalEnv -> VM ()
368 setLEnv lenv = VM $ \_ genv _ -> return (Yes genv lenv ())
370 updLEnv :: (LocalEnv -> LocalEnv) -> VM ()
371 updLEnv f = VM $ \_ genv lenv -> return (Yes genv (f lenv) ())
374 -- InstEnv --------------------------------------------------------------------
375 getInstEnv :: VM (InstEnv, InstEnv)
376 getInstEnv = readGEnv global_inst_env
378 getFamInstEnv :: VM FamInstEnvs
379 getFamInstEnv = readGEnv global_fam_inst_env
382 -- Names ----------------------------------------------------------------------
383 -- | Get the name of the local binding currently being vectorised.
384 getBindName :: VM FastString
385 getBindName = readLEnv local_bind_name
387 inBind :: Id -> VM a -> VM a
389 = do updLEnv $ \env -> env { local_bind_name = occNameFS (getOccName id) }
392 cloneName :: (OccName -> OccName) -> Name -> VM Name
393 cloneName mk_occ name = liftM make (liftDs newUnique)
395 occ_name = mk_occ (nameOccName name)
397 make u | isExternalName name = mkExternalName u (nameModule name)
400 | otherwise = mkSystemName u occ_name
402 cloneId :: (OccName -> OccName) -> Id -> Type -> VM Id
405 name <- cloneName mk_occ (getName id)
406 let id' | isExportedId id = Id.mkExportedLocalId name ty
407 | otherwise = Id.mkLocalId name ty
410 -- Make a fresh instance of this var, with a new unique.
411 cloneVar :: Var -> VM Var
412 cloneVar var = liftM (setIdUnique var) (liftDs newUnique)
414 newExportedVar :: OccName -> Type -> VM Var
415 newExportedVar occ_name ty
417 mod <- liftDs getModuleDs
418 u <- liftDs newUnique
420 let name = mkExternalName u mod occ_name noSrcSpan
422 return $ Id.mkExportedLocalId name ty
424 newLocalVar :: FastString -> Type -> VM Var
427 u <- liftDs newUnique
428 return $ mkSysLocal fs u ty
430 newLocalVars :: FastString -> [Type] -> VM [Var]
431 newLocalVars fs = mapM (newLocalVar fs)
433 newDummyVar :: Type -> VM Var
434 newDummyVar = newLocalVar (fsLit "vv")
436 newTyVar :: FastString -> Kind -> VM Var
439 u <- liftDs newUnique
440 return $ mkTyVar (mkSysTvName u fs) k
442 defGlobalVar :: Var -> Var -> VM ()
443 defGlobalVar v v' = updGEnv $ \env ->
444 env { global_vars = extendVarEnv (global_vars env) v v'
445 , global_exported_vars = upd (global_exported_vars env)
448 upd env | isExportedId v = extendVarEnv env v (v, v')
451 -- | Lookup the vectorised and\/or lifted versions of this variable.
452 -- If it's in the global environment we get the vectorised version.
453 -- If it's in the local environment we get both the vectorised and lifted version.
455 lookupVar :: Var -> VM (Scope Var (Var, Var))
458 r <- readLEnv $ \env -> lookupVarEnv (local_vars env) v
460 Just e -> return (Local e)
461 Nothing -> liftM Global
462 . maybeCantVectoriseM "Variable not vectorised:" (ppr v)
463 . readGEnv $ \env -> lookupVarEnv (global_vars env) v
465 globalScalars :: VM VarSet
466 globalScalars = readGEnv global_scalars
468 lookupTyCon :: TyCon -> VM (Maybe TyCon)
470 | isUnLiftedTyCon tc || isTupleTyCon tc = return (Just tc)
472 | otherwise = readGEnv $ \env -> lookupNameEnv (global_tycons env) (tyConName tc)
474 defTyCon :: TyCon -> TyCon -> VM ()
475 defTyCon tc tc' = updGEnv $ \env ->
476 env { global_tycons = extendNameEnv (global_tycons env) (tyConName tc) tc' }
478 lookupDataCon :: DataCon -> VM (Maybe DataCon)
480 | isTupleTyCon (dataConTyCon dc) = return (Just dc)
481 | otherwise = readGEnv $ \env -> lookupNameEnv (global_datacons env) (dataConName dc)
483 defDataCon :: DataCon -> DataCon -> VM ()
484 defDataCon dc dc' = updGEnv $ \env ->
485 env { global_datacons = extendNameEnv (global_datacons env) (dataConName dc) dc' }
487 lookupPrimPArray :: TyCon -> VM (Maybe TyCon)
488 lookupPrimPArray = liftBuiltinDs . primPArray
490 lookupPrimMethod :: TyCon -> String -> VM (Maybe Var)
491 lookupPrimMethod tycon = liftBuiltinDs . primMethod tycon
493 lookupTyConPA :: TyCon -> VM (Maybe Var)
494 lookupTyConPA tc = readGEnv $ \env -> lookupNameEnv (global_pa_funs env) (tyConName tc)
496 defTyConPA :: TyCon -> Var -> VM ()
497 defTyConPA tc pa = updGEnv $ \env ->
498 env { global_pa_funs = extendNameEnv (global_pa_funs env) (tyConName tc) pa }
500 defTyConPAs :: [(TyCon, Var)] -> VM ()
501 defTyConPAs ps = updGEnv $ \env ->
502 env { global_pa_funs = extendNameEnvList (global_pa_funs env)
503 [(tyConName tc, pa) | (tc, pa) <- ps] }
505 lookupTyVarPA :: Var -> VM (Maybe CoreExpr)
506 lookupTyVarPA tv = readLEnv $ \env -> lookupVarEnv (local_tyvar_pa env) tv
508 lookupTyConPR :: TyCon -> VM (Maybe Var)
509 lookupTyConPR tc = readGEnv $ \env -> lookupNameEnv (global_pr_funs env) (tyConName tc)
511 lookupBoxedTyCon :: TyCon -> VM (Maybe TyCon)
512 lookupBoxedTyCon tc = readGEnv $ \env -> lookupNameEnv (global_boxed_tycons env)
515 defLocalTyVar :: TyVar -> VM ()
516 defLocalTyVar tv = updLEnv $ \env ->
517 env { local_tyvars = tv : local_tyvars env
518 , local_tyvar_pa = local_tyvar_pa env `delVarEnv` tv
521 defLocalTyVarWithPA :: TyVar -> CoreExpr -> VM ()
522 defLocalTyVarWithPA tv pa = updLEnv $ \env ->
523 env { local_tyvars = tv : local_tyvars env
524 , local_tyvar_pa = extendVarEnv (local_tyvar_pa env) tv pa
527 localTyVars :: VM [TyVar]
528 localTyVars = readLEnv (reverse . local_tyvars)
530 -- Look up the dfun of a class instance.
532 -- The match must be unique - ie, match exactly one instance - but the
533 -- type arguments used for matching may be more specific than those of
534 -- the class instance declaration. The found class instances must not have
535 -- any type variables in the instance context that do not appear in the
536 -- instances head (i.e., no flexi vars); for details for what this means,
537 -- see the docs at InstEnv.lookupInstEnv.
539 lookupInst :: Class -> [Type] -> VM (DFunId, [Type])
541 = do { instEnv <- getInstEnv
542 ; case lookupInstEnv instEnv cls tys of
543 ([(inst, inst_tys)], _)
544 | noFlexiVar -> return (instanceDFunId inst, inst_tys')
545 | otherwise -> pprPanic "VectMonad.lookupInst: flexi var: "
546 (ppr $ mkTyConApp (classTyCon cls) tys)
548 inst_tys' = [ty | Right ty <- inst_tys]
549 noFlexiVar = all isRight inst_tys
551 pprPanic "VectMonad.lookupInst: not found " (ppr cls <+> ppr tys)
554 isRight (Left _) = False
555 isRight (Right _) = True
557 -- Look up the representation tycon of a family instance.
559 -- The match must be unique - ie, match exactly one instance - but the
560 -- type arguments used for matching may be more specific than those of
561 -- the family instance declaration.
563 -- Return the instance tycon and its type instance. For example, if we have
565 -- lookupFamInst 'T' '[Int]' yields (':R42T', 'Int')
567 -- then we have a coercion (ie, type instance of family instance coercion)
569 -- :Co:R42T Int :: T [Int] ~ :R42T Int
571 -- which implies that :R42T was declared as 'data instance T [a]'.
573 lookupFamInst :: TyCon -> [Type] -> VM (TyCon, [Type])
574 lookupFamInst tycon tys
575 = ASSERT( isOpenTyCon tycon )
576 do { instEnv <- getFamInstEnv
577 ; case lookupFamInstEnv instEnv tycon tys of
578 [(fam_inst, rep_tys)] -> return (famInstTyCon fam_inst, rep_tys)
580 pprPanic "VectMonad.lookupFamInst: not found: "
581 (ppr $ mkTyConApp tycon tys)
584 initV :: PackageId -> HscEnv -> ModGuts -> VectInfo -> VM a -> IO (Maybe (VectInfo, a))
585 initV pkg hsc_env guts info p
587 -- XXX: ignores error messages and warnings, check that this is
588 -- indeed ok (the use of "Just r" suggests so)
589 (_,Just r) <- initDs hsc_env (mg_module guts)
598 builtins <- initBuiltins pkg
599 builtin_vars <- initBuiltinVars builtins
600 builtin_tycons <- initBuiltinTyCons builtins
601 let builtin_datacons = initBuiltinDataCons builtins
602 builtin_boxed <- initBuiltinBoxedTyCons builtins
603 builtin_scalars <- initBuiltinScalars builtins
605 eps <- liftIO $ hscEPS hsc_env
606 let famInstEnvs = (eps_fam_inst_env eps, mg_fam_inst_env guts)
607 instEnvs = (eps_inst_env eps, mg_inst_env guts)
609 builtin_prs <- initBuiltinPRs builtins instEnvs
610 builtin_pas <- initBuiltinPAs builtins instEnvs
612 let genv = extendImportedVarsEnv builtin_vars
613 . extendScalars builtin_scalars
614 . extendTyConsEnv builtin_tycons
615 . extendDataConsEnv builtin_datacons
616 . extendPAFunsEnv builtin_pas
617 . setPRFunsEnv builtin_prs
618 . setBoxedTyConsEnv builtin_boxed
619 $ initGlobalEnv info instEnvs famInstEnvs
621 r <- runVM p builtins genv emptyLocalEnv
623 Yes genv _ x -> return $ Just (new_info genv, x)
626 new_info genv = updVectInfo genv (mg_types guts) info