VectUtils.hs 14.2 KB
Newer Older
1
module VectUtils (
2
  collectAnnTypeBinders, collectAnnTypeArgs, isAnnTypeArg,
3
  collectAnnValBinders,
rl@cse.unsw.edu.au's avatar
rl@cse.unsw.edu.au committed
4
5
6
  dataConTagZ, mkDataConTag, mkDataConTagLit,

  newLocalVVar,
7

8
  mkBuiltinCo,
9
  mkPADictType, mkPArrayType, mkPReprType,
10

11
12
  parrayReprTyCon, parrayReprDataCon, mkVScrut,
  prDFunOfTyCon,
13
  paDictArgType, paDictOfType, paDFunType,
14
  paMethod, mkPR, lengthPA, replicatePA, emptyPA, packPA, combinePA, liftPA,
15
  polyAbstract, polyApply, polyVApply,
rl@cse.unsw.edu.au's avatar
rl@cse.unsw.edu.au committed
16
  hoistBinding, hoistExpr, hoistPolyVExpr, takeHoisted,
rl@cse.unsw.edu.au's avatar
rl@cse.unsw.edu.au committed
17
18
  buildClosure, buildClosures,
  mkClosureApp
19
20
) where

21
import VectCore
22
23
import VectMonad

24
import MkCore
25
import CoreSyn
26
import CoreUtils
rl@cse.unsw.edu.au's avatar
rl@cse.unsw.edu.au committed
27
import Coercion
28
29
import Type
import TypeRep
30
import TyCon
31
import DataCon
32
import Var
33
34
35
36
import Id                 ( mkWildId )
import MkId               ( unwrapFamInstScrut )
import TysWiredIn
import BasicTypes         ( Boxity(..) )
37
import Literal            ( Literal, mkMachInt )
38

39
import Outputable
40
import FastString
41

twanvl's avatar
twanvl committed
42
43
import Control.Monad

44

45
46
47
48
49
50
51
52
53
54
55
56
collectAnnTypeArgs :: AnnExpr b ann -> (AnnExpr b ann, [Type])
collectAnnTypeArgs expr = go expr []
  where
    go (_, AnnApp f (_, AnnType ty)) tys = go f (ty : tys)
    go e                             tys = (e, tys)

collectAnnTypeBinders :: AnnExpr Var ann -> ([Var], AnnExpr Var ann)
collectAnnTypeBinders expr = go [] expr
  where
    go bs (_, AnnLam b e) | isTyVar b = go (b:bs) e
    go bs e                           = (reverse bs, e)

57
58
59
collectAnnValBinders :: AnnExpr Var ann -> ([Var], AnnExpr Var ann)
collectAnnValBinders expr = go [] expr
  where
batterseapower's avatar
batterseapower committed
60
61
    go bs (_, AnnLam b e) | isIdVar b = go (b:bs) e
    go bs e                           = (reverse bs, e)
62

63
isAnnTypeArg :: AnnExpr b ann -> Bool
twanvl's avatar
twanvl committed
64
isAnnTypeArg (_, AnnType _) = True
65
66
isAnnTypeArg _              = False

rl@cse.unsw.edu.au's avatar
rl@cse.unsw.edu.au committed
67
68
69
dataConTagZ :: DataCon -> Int
dataConTagZ con = dataConTag con - fIRST_TAG

70
mkDataConTagLit :: DataCon -> Literal
rl@cse.unsw.edu.au's avatar
rl@cse.unsw.edu.au committed
71
mkDataConTagLit = mkMachInt . toInteger . dataConTagZ
72

73
mkDataConTag :: DataCon -> CoreExpr
rl@cse.unsw.edu.au's avatar
rl@cse.unsw.edu.au committed
74
mkDataConTag = mkIntLitInt . dataConTagZ
75

76
77
78
79
80
81
82
83
splitPrimTyCon :: Type -> Maybe TyCon
splitPrimTyCon ty
  | Just (tycon, []) <- splitTyConApp_maybe ty
  , isPrimTyCon tycon
  = Just tycon

  | otherwise = Nothing

rl@cse.unsw.edu.au's avatar
rl@cse.unsw.edu.au committed
84
85
mkBuiltinTyConApp :: (Builtins -> TyCon) -> [Type] -> VM Type
mkBuiltinTyConApp get_tc tys
86
  = do
rl@cse.unsw.edu.au's avatar
rl@cse.unsw.edu.au committed
87
88
      tc <- builtin get_tc
      return $ mkTyConApp tc tys
89

rl@cse.unsw.edu.au's avatar
rl@cse.unsw.edu.au committed
90
91
mkBuiltinTyConApps :: (Builtins -> TyCon) -> [Type] -> Type -> VM Type
mkBuiltinTyConApps get_tc tys ty
92
  = do
rl@cse.unsw.edu.au's avatar
rl@cse.unsw.edu.au committed
93
94
      tc <- builtin get_tc
      return $ foldr (mk tc) ty tys
95
  where
rl@cse.unsw.edu.au's avatar
rl@cse.unsw.edu.au committed
96
    mk tc ty1 ty2 = mkTyConApp tc [ty1,ty2]
97

twanvl's avatar
twanvl committed
98
{-
rl@cse.unsw.edu.au's avatar
rl@cse.unsw.edu.au committed
99
mkBuiltinTyConApps1 :: (Builtins -> TyCon) -> Type -> [Type] -> VM Type
twanvl's avatar
twanvl committed
100
101
mkBuiltinTyConApps1 _      dft [] = return dft
mkBuiltinTyConApps1 get_tc _   tys
102
  = do
rl@cse.unsw.edu.au's avatar
rl@cse.unsw.edu.au committed
103
104
105
106
107
108
109
110
111
      tc <- builtin get_tc
      case tys of
        [] -> pprPanic "mkBuiltinTyConApps1" (ppr tc)
        _  -> return $ foldr1 (mk tc) tys
  where
    mk tc ty1 ty2 = mkTyConApp tc [ty1,ty2]

mkClosureType :: Type -> Type -> VM Type
mkClosureType arg_ty res_ty = mkBuiltinTyConApp closureTyCon [arg_ty, res_ty]
twanvl's avatar
twanvl committed
112
-}
rl@cse.unsw.edu.au's avatar
rl@cse.unsw.edu.au committed
113
114
115
116

mkClosureTypes :: [Type] -> Type -> VM Type
mkClosureTypes = mkBuiltinTyConApps closureTyCon

117
118
119
mkPReprType :: Type -> VM Type
mkPReprType ty = mkBuiltinTyConApp preprTyCon [ty]

rl@cse.unsw.edu.au's avatar
rl@cse.unsw.edu.au committed
120
121
mkPADictType :: Type -> VM Type
mkPADictType ty = mkBuiltinTyConApp paTyCon [ty]
122
123

mkPArrayType :: Type -> VM Type
124
125
126
127
128
129
mkPArrayType ty
  | Just tycon <- splitPrimTyCon ty
  = do
      arr <- traceMaybeV "mkPArrayType" (ppr tycon)
           $ lookupPrimPArray tycon
      return $ mkTyConApp arr []
rl@cse.unsw.edu.au's avatar
rl@cse.unsw.edu.au committed
130
mkPArrayType ty = mkBuiltinTyConApp parrayTyCon [ty]
131

132
133
mkBuiltinCo :: (Builtins -> TyCon) -> VM Coercion
mkBuiltinCo get_tc
134
  = do
135
136
      tc <- builtin get_tc
      return $ mkTyConApp tc []
137

138
139
140
141
142
143
144
145
146
147
parrayReprTyCon :: Type -> VM (TyCon, [Type])
parrayReprTyCon ty = builtin parrayTyCon >>= (`lookupFamInst` [ty])

parrayReprDataCon :: Type -> VM (DataCon, [Type])
parrayReprDataCon ty
  = do
      (tc, arg_tys) <- parrayReprTyCon ty
      let [dc] = tyConDataCons tc
      return (dc, arg_tys)

148
149
150
151
152
153
mkVScrut :: VExpr -> VM (VExpr, TyCon, [Type])
mkVScrut (ve, le)
  = do
      (tc, arg_tys) <- parrayReprTyCon (exprType ve)
      return ((ve, unwrapFamInstScrut tc arg_tys le), tc, arg_tys)

154
155
156
prDFunOfTyCon :: TyCon -> VM CoreExpr
prDFunOfTyCon tycon
  = liftM Var (traceMaybeV "prDictOfTyCon" (ppr tycon) (lookupTyConPR tycon))
157

158
159
160
161
162
163
paDictArgType :: TyVar -> VM (Maybe Type)
paDictArgType tv = go (TyVarTy tv) (tyVarKind tv)
  where
    go ty k | Just k' <- kindView k = go ty k'
    go ty (FunTy k1 k2)
      = do
Ian Lynagh's avatar
Ian Lynagh committed
164
          tv   <- newTyVar (fsLit "a") k1
165
166
167
168
169
170
171
172
173
          mty1 <- go (TyVarTy tv) k1
          case mty1 of
            Just ty1 -> do
                          mty2 <- go (AppTy ty (TyVarTy tv)) k2
                          return $ fmap (ForAllTy tv . FunTy ty1) mty2
            Nothing  -> go ty k2

    go ty k
      | isLiftedTypeKind k
174
      = liftM Just (mkPADictType ty)
175

twanvl's avatar
twanvl committed
176
    go _ _ = return Nothing
177

178
179
180
181
182
183
184
185
186
187
188
189
190
191
paDictOfType :: Type -> VM CoreExpr
paDictOfType ty = paDictOfTyApp ty_fn ty_args
  where
    (ty_fn, ty_args) = splitAppTys ty

paDictOfTyApp :: Type -> [Type] -> VM CoreExpr
paDictOfTyApp ty_fn ty_args
  | Just ty_fn' <- coreView ty_fn = paDictOfTyApp ty_fn' ty_args
paDictOfTyApp (TyVarTy tv) ty_args
  = do
      dfun <- maybeV (lookupTyVarPA tv)
      paDFunApply dfun ty_args
paDictOfTyApp (TyConApp tc _) ty_args
  = do
192
      dfun <- traceMaybeV "paDictOfTyApp" (ppr tc) (lookupTyConPA tc)
193
      paDFunApply (Var dfun) ty_args
twanvl's avatar
twanvl committed
194
paDictOfTyApp ty _ = pprPanic "paDictOfTyApp" (ppr ty)
195

196
197
198
199
200
201
202
203
204
205
206
paDFunType :: TyCon -> VM Type
paDFunType tc
  = do
      margs <- mapM paDictArgType tvs
      res   <- mkPADictType (mkTyConApp tc arg_tys)
      return . mkForAllTys tvs
             $ mkFunTys [arg | Just arg <- margs] res
  where
    tvs = tyConTyVars tc
    arg_tys = mkTyVarTys tvs

207
208
209
210
211
212
paDFunApply :: CoreExpr -> [Type] -> VM CoreExpr
paDFunApply dfun tys
  = do
      dicts <- mapM paDictOfType tys
      return $ mkApps (mkTyApps dfun tys) dicts

213
214
type PAMethod = (Builtins -> Var, String)

twanvl's avatar
twanvl committed
215
pa_length, pa_replicate, pa_empty, pa_pack :: (Builtins -> Var, String)
216
217
218
pa_length    = (lengthPAVar,    "lengthPA")
pa_replicate = (replicatePAVar, "replicatePA")
pa_empty     = (emptyPAVar,     "emptyPA")
219
pa_pack      = (packPAVar,      "packPA")
220
221

paMethod :: PAMethod -> Type -> VM CoreExpr
twanvl's avatar
twanvl committed
222
paMethod (_method, name) ty
223
  | Just tycon <- splitPrimTyCon ty
224
225
226
227
228
  = do
      fn <- traceMaybeV "paMethod" (ppr tycon <+> text name)
          $ lookupPrimMethod tycon name
      return (Var fn)

twanvl's avatar
twanvl committed
229
paMethod (method, _name) ty
rl@cse.unsw.edu.au's avatar
rl@cse.unsw.edu.au committed
230
231
232
233
234
  = do
      fn   <- builtin method
      dict <- paDictOfType ty
      return $ mkApps (Var fn) [Type ty, dict]

235
mkPR :: Type -> VM CoreExpr
236
237
238
239
240
mkPR ty
  = do
      fn   <- builtin mkPRVar
      dict <- paDictOfType ty
      return $ mkApps (Var fn) [Type ty, dict]
241

242
243
lengthPA :: Type -> CoreExpr -> VM CoreExpr
lengthPA ty x = liftM (`App` x) (paMethod pa_length ty)
rl@cse.unsw.edu.au's avatar
rl@cse.unsw.edu.au committed
244
245
246

replicatePA :: CoreExpr -> CoreExpr -> VM CoreExpr
replicatePA len x = liftM (`mkApps` [len,x])
247
                          (paMethod pa_replicate (exprType x))
rl@cse.unsw.edu.au's avatar
rl@cse.unsw.edu.au committed
248

249
emptyPA :: Type -> VM CoreExpr
250
emptyPA = paMethod pa_empty
251

252
packPA :: Type -> CoreExpr -> CoreExpr -> CoreExpr -> VM CoreExpr
253
packPA ty xs len sel = liftM (`mkApps` [xs, len, sel])
254
255
                             (paMethod pa_pack ty)

256
257
258
259
260
261
262
263
combinePA :: Type -> CoreExpr -> CoreExpr -> CoreExpr -> [CoreExpr]
          -> VM CoreExpr
combinePA ty len sel is xs
  = liftM (`mkApps` (len : sel : is : xs))
          (paMethod (combinePAVar n, "combine" ++ show n ++ "PA") ty)
  where
    n = length xs

264
265
266
267
268
269
liftPA :: CoreExpr -> VM CoreExpr
liftPA x
  = do
      lc <- builtin liftingContext
      replicatePA (Var lc) x

270
271
272
273
274
275
276
277
newLocalVVar :: FastString -> Type -> VM VVar
newLocalVVar fs vty
  = do
      lty <- mkPArrayType vty
      vv  <- newLocalVar fs vty
      lv  <- newLocalVar fs lty
      return (vv,lv)

rl@cse.unsw.edu.au's avatar
rl@cse.unsw.edu.au committed
278
279
280
281
polyAbstract :: [TyVar] -> ((CoreExpr -> CoreExpr) -> VM a) -> VM a
polyAbstract tvs p
  = localV
  $ do
rl@cse.unsw.edu.au's avatar
rl@cse.unsw.edu.au committed
282
283
284
285
286
287
288
      mdicts <- mapM mk_dict_var tvs
      zipWithM_ (\tv -> maybe (defLocalTyVar tv) (defLocalTyVarWithPA tv . Var)) tvs mdicts
      p (mk_lams mdicts)
  where
    mk_dict_var tv = do
                       r <- paDictArgType tv
                       case r of
Ian Lynagh's avatar
Ian Lynagh committed
289
                         Just ty -> liftM Just (newLocalVar (fsLit "dPA") ty)
rl@cse.unsw.edu.au's avatar
rl@cse.unsw.edu.au committed
290
291
292
293
                         Nothing -> return Nothing

    mk_lams mdicts = mkLams (tvs ++ [dict | Just dict <- mdicts])

rl@cse.unsw.edu.au's avatar
rl@cse.unsw.edu.au committed
294
295
polyApply :: CoreExpr -> [Type] -> VM CoreExpr
polyApply expr tys
rl@cse.unsw.edu.au's avatar
rl@cse.unsw.edu.au committed
296
297
298
299
  = do
      dicts <- mapM paDictOfType tys
      return $ expr `mkTyApps` tys `mkApps` dicts

300
301
302
303
304
305
polyVApply :: VExpr -> [Type] -> VM VExpr
polyVApply expr tys
  = do
      dicts <- mapM paDictOfType tys
      return $ mapVect (\e -> e `mkTyApps` tys `mkApps` dicts) expr

rl@cse.unsw.edu.au's avatar
rl@cse.unsw.edu.au committed
306
307
308
309
hoistBinding :: Var -> CoreExpr -> VM ()
hoistBinding v e = updGEnv $ \env ->
  env { global_bindings = (v,e) : global_bindings env }

310
311
312
313
hoistExpr :: FastString -> CoreExpr -> VM Var
hoistExpr fs expr
  = do
      var <- newLocalVar fs (exprType expr)
rl@cse.unsw.edu.au's avatar
rl@cse.unsw.edu.au committed
314
      hoistBinding var expr
315
316
      return var

317
318
hoistVExpr :: VExpr -> VM VVar
hoistVExpr (ve, le)
319
  = do
320
      fs <- getBindName
321
322
323
      vv <- hoistExpr ('v' `consFS` fs) ve
      lv <- hoistExpr ('l' `consFS` fs) le
      return (vv, lv)
324

325
326
hoistPolyVExpr :: [TyVar] -> VM VExpr -> VM VExpr
hoistPolyVExpr tvs p
327
  = do
328
329
      expr <- closedV . polyAbstract tvs $ \abstract ->
              liftM (mapVect abstract) p
330
      fn   <- hoistVExpr expr
331
      polyVApply (vVar fn) (mkTyVarTys tvs)
332

333
334
335
336
337
338
339
takeHoisted :: VM [(Var, CoreExpr)]
takeHoisted
  = do
      env <- readGEnv id
      setGEnv $ env { global_bindings = [] }
      return $ global_bindings env

twanvl's avatar
twanvl committed
340
{-
341
342
343
344
345
346
347
348
349
350
351
boxExpr :: Type -> VExpr -> VM VExpr
boxExpr ty (vexpr, lexpr)
  | Just (tycon, []) <- splitTyConApp_maybe ty
  , isUnLiftedTyCon tycon
  = do
      r <- lookupBoxedTyCon tycon
      case r of
        Just tycon' -> let [dc] = tyConDataCons tycon'
                       in
                       return (mkConApp dc [vexpr], lexpr)
        Nothing     -> return (vexpr, lexpr)
twanvl's avatar
twanvl committed
352
-}
353

354
355
mkClosure :: Type -> Type -> Type -> VExpr -> VExpr -> VM VExpr
mkClosure arg_ty res_ty env_ty (vfn,lfn) (venv,lenv)
356
  = do
357
358
359
360
361
      dict <- paDictOfType env_ty
      mkv  <- builtin mkClosureVar
      mkl  <- builtin mkClosurePVar
      return (Var mkv `mkTyApps` [arg_ty, res_ty, env_ty] `mkApps` [dict, vfn, lfn, venv],
              Var mkl `mkTyApps` [arg_ty, res_ty, env_ty] `mkApps` [dict, vfn, lfn, lenv])
362

363
364
mkClosureApp :: Type -> Type -> VExpr -> VExpr -> VM VExpr
mkClosureApp arg_ty res_ty (vclo, lclo) (varg, larg)
rl@cse.unsw.edu.au's avatar
rl@cse.unsw.edu.au committed
365
366
367
368
369
370
  = do
      vapply <- builtin applyClosureVar
      lapply <- builtin applyClosurePVar
      return (Var vapply `mkTyApps` [arg_ty, res_ty] `mkApps` [vclo, varg],
              Var lapply `mkTyApps` [arg_ty, res_ty] `mkApps` [lclo, larg])

371
buildClosures :: [TyVar] -> [VVar] -> [Type] -> Type -> VM VExpr -> VM VExpr
twanvl's avatar
twanvl committed
372
buildClosures _   _    [] _ mk_body
373
  = mk_body
374
375
376
buildClosures tvs vars [arg_ty] res_ty mk_body
  = buildClosure tvs vars arg_ty res_ty mk_body
buildClosures tvs vars (arg_ty : arg_tys) res_ty mk_body
377
378
  = do
      res_ty' <- mkClosureTypes arg_tys res_ty
Ian Lynagh's avatar
Ian Lynagh committed
379
      arg <- newLocalVVar (fsLit "x") arg_ty
380
      buildClosure tvs vars arg_ty res_ty'
381
        . hoistPolyVExpr tvs
382
        $ do
383
384
            lc <- builtin liftingContext
            clo <- buildClosures tvs (vars ++ [arg]) arg_tys res_ty mk_body
385
386
            return $ vLams lc (vars ++ [arg]) clo

387
388
389
390
-- (clo <x1,...,xn> <f,f^>, aclo (Arr lc xs1 ... xsn) <f,f^>)
--   where
--     f  = \env v -> case env of <x1,...,xn> -> e x1 ... xn v
--     f^ = \env v -> case env of Arr l xs1 ... xsn -> e^ l x1 ... xn v
391
--
392
393
buildClosure :: [TyVar] -> [VVar] -> Type -> Type -> VM VExpr -> VM VExpr
buildClosure tvs vars arg_ty res_ty mk_body
394
  = do
395
      (env_ty, env, bind) <- buildEnv vars
Ian Lynagh's avatar
Ian Lynagh committed
396
397
      env_bndr <- newLocalVVar (fsLit "env") env_ty
      arg_bndr <- newLocalVVar (fsLit "arg") arg_ty
398

399
      fn <- hoistPolyVExpr tvs
400
          $ do
401
              lc    <- builtin liftingContext
402
403
              body  <- mk_body
              body' <- bind (vVar env_bndr)
404
                            (vVarApps lc body (vars ++ [arg_bndr]))
rl@cse.unsw.edu.au's avatar
rl@cse.unsw.edu.au committed
405
              return (vLamsWithoutLC [env_bndr, arg_bndr] body')
406

407
      mkClosure arg_ty res_ty env_ty fn env
408

409
410
buildEnv :: [VVar] -> VM (Type, VExpr, VExpr -> VExpr -> VM VExpr)
buildEnv vvs
411
  = do
412
      lc <- builtin liftingContext
413
      let (ty, venv, vbind) = mkVectEnv tys vs
414
      (lenv, lbind) <- mkLiftEnv lc tys ls
415
      return (ty, (venv, lenv),
416
417
418
419
420
              \(venv,lenv) (vbody,lbody) ->
              do
                let vbody' = vbind venv vbody
                lbody' <- lbind lenv lbody
                return (vbody', lbody'))
421
  where
422
    (vs,ls) = unzip vvs
423
    tys     = map varType vs
424
425

mkVectEnv :: [Type] -> [Var] -> (Type, CoreExpr, CoreExpr -> CoreExpr -> CoreExpr)
twanvl's avatar
twanvl committed
426
mkVectEnv []   []  = (unitTy, Var unitDataConId, \_ body -> body)
427
428
429
430
431
432
433
mkVectEnv [ty] [v] = (ty, Var v, \env body -> Let (NonRec v env) body)
mkVectEnv tys  vs  = (ty, mkCoreTup (map Var vs),
                        \env body -> Case env (mkWildId ty) (exprType body)
                                       [(DataAlt (tupleCon Boxed (length vs)), vs, body)])
  where
    ty = mkCoreTupTy tys

434
mkLiftEnv :: Var -> [Type] -> [Var] -> VM (CoreExpr, CoreExpr -> CoreExpr -> VM CoreExpr)
435
mkLiftEnv lc [ty] [v]
436
437
  = return (Var v, \env body ->
                   do
438
                     len <- lengthPA ty (Var v)
439
                     return . Let (NonRec v env)
440
                            $ Case len lc (exprType body) [(DEFAULT, [], body)])
441
442

-- NOTE: this transparently deals with empty environments
443
mkLiftEnv lc tys vs
444
  = do
445
      (env_tc, env_tyargs) <- parrayReprTyCon vty
rl@cse.unsw.edu.au's avatar
rl@cse.unsw.edu.au committed
446
447
448
449
450

      bndrs <- if null vs then do
                                 v <- newDummyVar unitTy
                                 return [v]
                          else return vs
451
452
453
      let [env_con] = tyConDataCons env_tc
          
          env = Var (dataConWrapId env_con)
454
                `mkTyApps`  env_tyargs
455
                `mkApps`    (Var lc : args)
456

457
458
          bind env body = let scrut = unwrapFamInstScrut env_tc env_tyargs env
                          in
459
460
                          return $ Case scrut (mkWildId (exprType scrut))
                                        (exprType body)
461
                                        [(DataAlt env_con, lc : bndrs, body)]
462
463
464
465
      return (env, bind)
  where
    vty = mkCoreTupTy tys

466
467
468
    args  | null vs   = [Var unitDataConId]
          | otherwise = map Var vs