DsCCall.hs 14.2 KB
Newer Older
Austin Seipp's avatar
Austin Seipp committed
1 2 3 4
{-
(c) The University of Glasgow 2006
(c) The AQUA Project, Glasgow University, 1994-1998

Simon Marlow's avatar
Simon Marlow committed
5 6

Desugaring foreign calls
Austin Seipp's avatar
Austin Seipp committed
7
-}
8

9
{-# LANGUAGE CPP #-}
10 11 12 13 14 15 16
module DsCCall
        ( dsCCall
        , mkFCall
        , unboxArg
        , boxResult
        , resultWrapper
        ) where
17

18
#include "HsVersions.h"
19

20

21
import CoreSyn
22

23 24
import DsMonad

Simon Marlow's avatar
Simon Marlow committed
25
import CoreUtils
26
import MkCore
Ian Lynagh's avatar
Ian Lynagh committed
27
import Var
Simon Marlow's avatar
Simon Marlow committed
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
import MkId
import ForeignCall
import DataCon

import TcType
import Type
import Coercion
import PrimOp
import TysPrim
import TyCon
import TysWiredIn
import BasicTypes
import Literal
import PrelNames
import VarSet
Ian Lynagh's avatar
Ian Lynagh committed
43
import DynFlags
44
import Outputable
45
import Util
Icelandjack's avatar
Icelandjack committed
46 47

import Data.Maybe
48

Austin Seipp's avatar
Austin Seipp committed
49
{-
50 51 52 53 54
Desugaring of @ccall@s consists of adding some state manipulation,
unboxing any boxed primitive arguments and boxing the result if
desired.

The state stuff just consists of adding in
55
@PrimIO (\ s -> case s of { S# s# -> ... })@ in an appropriate place.
56 57 58 59 60

The unboxing is straightforward, as all information needed to unbox is
available from the type.  For each boxed-primitive argument, we
transform:
\begin{verbatim}
61
   _ccall_ foo [ r, t1, ... tm ] e1 ... em
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
   |
   |
   V
   case e1 of { T1# x1# ->
   ...
   case em of { Tm# xm# -> xm#
   ccall# foo [ r, t1#, ... tm# ] x1# ... xm#
   } ... }
\end{verbatim}

The reboxing of a @_ccall_@ result is a bit tricker: the types don't
contain information about the state-pairing functions so we have to
keep a list of \tr{(type, s-p-function)} pairs.  We transform as
follows:
\begin{verbatim}
   ccall# foo [ r, t1#, ... tm# ] e1# ... em#
   |
   |
   V
   \ s# -> case (ccall# foo [ r, t1#, ... tm# ] s# e1# ... em#) of
82
          (StateAnd<r># result# state#) -> (R# result#, realWorld#)
83
\end{verbatim}
Austin Seipp's avatar
Austin Seipp committed
84
-}
85

86 87 88 89 90
dsCCall :: CLabelString -- C routine to invoke
        -> [CoreExpr]   -- Arguments (desugared)
        -> Safety       -- Safety of the call
        -> Type         -- Type of the result: IO t
        -> DsM CoreExpr -- Result, of type ???
91

92
dsCCall lbl args may_gc result_ty
93
  = do (unboxed_args, arg_wrappers) <- mapAndUnzipM unboxArg args
94
       (ccall_result_ty, res_wrapper) <- boxResult result_ty
95
       uniq <- newUnique
Ian Lynagh's avatar
Ian Lynagh committed
96
       dflags <- getDynFlags
97
       let
98
           target = StaticTarget lbl Nothing True
99
           the_fcall    = CCall (CCallSpec target CCallConv may_gc)
Ian Lynagh's avatar
Ian Lynagh committed
100
           the_prim_app = mkFCall dflags uniq the_fcall unboxed_args ccall_result_ty
101
       return (foldr ($) (res_wrapper the_prim_app) arg_wrappers)
102

103 104 105 106
mkFCall :: DynFlags -> Unique -> ForeignCall
        -> [CoreExpr]   -- Args
        -> Type         -- Result type
        -> CoreExpr
107 108
-- Construct the ccall.  The only tricky bit is that the ccall Id should have
-- no free vars, so if any of the arg tys do we must give it a polymorphic type.
109
--      [I forget *why* it should have no free vars!]
110
-- For example:
111
--      mkCCall ... [s::StablePtr (a->b), x::Addr, c::Char]
112 113
--
-- Here we build a ccall thus
114 115
--      (ccallid::(forall a b.  StablePtr (a -> b) -> Addr -> Char -> IO Addr))
--                      a b s x c
Ian Lynagh's avatar
Ian Lynagh committed
116
mkFCall dflags uniq the_fcall val_args res_ty
117
  = mkApps (mkVarApps (Var the_fcall_id) tyvars) val_args
118 119 120 121
  where
    arg_tys = map exprType val_args
    body_ty = (mkFunTys arg_tys res_ty)
    tyvars  = varSetElems (tyVarsOfType body_ty)
122
    ty      = mkForAllTys tyvars body_ty
Ian Lynagh's avatar
Ian Lynagh committed
123
    the_fcall_id = mkFCallId dflags uniq the_fcall ty
124

125 126 127 128
unboxArg :: CoreExpr                    -- The supplied argument
         -> DsM (CoreExpr,              -- To pass as the actual argument
                 CoreExpr -> CoreExpr   -- Wrapper to unbox the arg
                )
129
-- Example: if the arg is e::Int, unboxArg will return
130
--      (x#::Int#, \W. case x of I# x# -> W)
131
-- where W is a CoreExpr that probably mentions x#
132

133
unboxArg arg
134 135
  -- Primtive types: nothing to unbox
  | isPrimitiveType arg_ty
136
  = return (arg, \body -> body)
137

138
  -- Recursive newtypes
139
  | Just(co, _rep_ty) <- topNormaliseNewType_maybe arg_ty
140
  = unboxArg (mkCast arg co)
141

142
  -- Booleans
143
  | Just tc <- tyConAppTyCon_maybe arg_ty,
144
    tc `hasKey` boolTyConKey
145 146
  = do dflags <- getDynFlags
       prim_arg <- newSysLocalDs intPrimTy
147
       return (Var prim_arg,
148
              \ body -> Case (mkWildCase arg arg_ty intPrimTy
149 150
                                       [(DataAlt falseDataCon,[],mkIntLit dflags 0),
                                        (DataAlt trueDataCon, [],mkIntLit dflags 1)])
151
                                        -- In increasing tag order!
152
                             prim_arg
153
                             (exprType body)
154
                             [(DEFAULT,[],body)])
155 156

  -- Data types with a single constructor, which has a single, primitive-typed arg
157
  -- This deals with Int, Float etc; also Ptr, ForeignPtr
158
  | is_product_type && data_con_arity == 1
159
  = ASSERT2(isUnLiftedType data_con_arg_ty1, pprType arg_ty)
160 161 162 163 164 165
                        -- Typechecker ensures this
    do case_bndr <- newSysLocalDs arg_ty
       prim_arg <- newSysLocalDs data_con_arg_ty1
       return (Var prim_arg,
               \ body -> Case arg case_bndr (exprType body) [(DataAlt data_con,[prim_arg],body)]
              )
166

167
  -- Byte-arrays, both mutable and otherwise; hack warning
168
  -- We're looking for values of type ByteArray, MutableByteArray
169 170
  --    data ByteArray          ix = ByteArray        ix ix ByteArray#
  --    data MutableByteArray s ix = MutableByteArray ix ix (MutableByteArray# s)
171
  | is_product_type &&
172
    data_con_arity == 3 &&
Icelandjack's avatar
Icelandjack committed
173
    isJust maybe_arg3_tycon &&
174 175
    (arg3_tycon ==  byteArrayPrimTyCon ||
     arg3_tycon ==  mutableByteArrayPrimTyCon)
176
  = do case_bndr <- newSysLocalDs arg_ty
Ian Lynagh's avatar
Ian Lynagh committed
177
       vars@[_l_var, _r_var, arr_cts_var] <- newSysLocalsDs data_con_arg_tys
178 179 180
       return (Var arr_cts_var,
               \ body -> Case arg case_bndr (exprType body) [(DataAlt data_con,vars,body)]
              )
181 182

  | otherwise
183 184
  = do l <- getSrcSpanDs
       pprPanic "unboxArg: " (ppr l <+> ppr arg_ty)
185
  where
186 187 188 189 190 191
    arg_ty                                      = exprType arg
    maybe_product_type                          = splitDataProductType_maybe arg_ty
    is_product_type                             = isJust maybe_product_type
    Just (_, _, data_con, data_con_arg_tys)     = maybe_product_type
    data_con_arity                              = dataConSourceArity data_con
    (data_con_arg_ty1 : _)                      = data_con_arg_tys
192

193
    (_ : _ : data_con_arg_ty3 : _) = data_con_arg_tys
194 195
    maybe_arg3_tycon               = tyConAppTyCon_maybe data_con_arg_ty3
    Just arg3_tycon                = maybe_arg3_tycon
196

197
boxResult :: Type
198
          -> DsM (Type, CoreExpr -> CoreExpr)
199

200 201 202
-- Takes the result of the user-level ccall:
--      either (IO t),
--      or maybe just t for an side-effect-free call
203 204
-- Returns a wrapper for the primitive ccall itself, along with the
-- type of the result of the primitive ccall.  This result type
205 206
-- will be of the form
--      State# RealWorld -> (# State# RealWorld, t' #)
207
-- where t' is the unwrapped form of t.  If t is simply (), then
208 209
-- the result type will be
--      State# RealWorld -> (# State# RealWorld #)
210

211
boxResult result_ty
212
  | Just (io_tycon, io_res_ty) <- tcSplitIOType_maybe result_ty
213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228
        -- isIOType_maybe handles the case where the type is a
        -- simple wrapping of IO.  E.g.
        --      newtype Wrap a = W (IO a)
        -- No coercion necessary because its a non-recursive newtype
        -- (If we wanted to handle a *recursive* newtype too, we'd need
        -- another case, and a coercion.)
        -- The result is IO t, so wrap the result in an IO constructor
  = do  { res <- resultWrapper io_res_ty
        ; let extra_result_tys
                = case res of
                     (Just ty,_)
                       | isUnboxedTupleType ty
                       -> let Just ls = tyConAppArgs_maybe ty in tail ls
                     _ -> []

              return_result state anss
229
                = mkCoreConApps (tupleDataCon Unboxed (2 + length extra_result_tys))
230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249
                                (map Type (realWorldStatePrimTy : io_res_ty : extra_result_tys)
                                 ++ (state : anss))

        ; (ccall_res_ty, the_alt) <- mk_alt return_result res

        ; state_id <- newSysLocalDs realWorldStatePrimTy
        ; let io_data_con = head (tyConDataCons io_tycon)
              toIOCon     = dataConWrapId io_data_con

              wrap the_call =
                              mkApps (Var toIOCon)
                                     [ Type io_res_ty,
                                       Lam state_id $
                                       mkWildCase (App the_call (Var state_id))
                                             ccall_res_ty
                                             (coreAltType the_alt)
                                             [the_alt]
                                     ]

        ; return (realWorldStatePrimTy `mkFunTy` ccall_res_ty, wrap) }
250

251
boxResult result_ty
252 253 254
  = do -- It isn't IO, so do unsafePerformIO
       -- It's not conveniently available, so we inline it
       res <- resultWrapper result_ty
255
       (ccall_res_ty, the_alt) <- mk_alt return_result res
256
       let
257 258 259 260
           wrap = \ the_call -> mkWildCase (App the_call (Var realWorldPrimId))
                                           ccall_res_ty
                                           (coreAltType the_alt)
                                           [the_alt]
261
       return (realWorldStatePrimTy `mkFunTy` ccall_res_ty, wrap)
262
  where
Ian Lynagh's avatar
Ian Lynagh committed
263 264
    return_result _ [ans] = ans
    return_result _ _     = panic "return_result: expected single result"
265 266


Ian Lynagh's avatar
Ian Lynagh committed
267 268 269
mk_alt :: (Expr Var -> [Expr Var] -> Expr Var)
       -> (Maybe Type, Expr Var -> Expr Var)
       -> DsM (Type, (AltCon, [Id], Expr Var))
270
mk_alt return_result (Nothing, wrap_result)
271 272 273
  = do -- The ccall returns ()
       state_id <- newSysLocalDs realWorldStatePrimTy
       let
274
             the_rhs = return_result (Var state_id)
275
                                     [wrap_result (panic "boxResult")]
276

277 278
             ccall_res_ty = mkTyConApp unboxedSingletonTyCon [realWorldStatePrimTy]
             the_alt      = (DataAlt unboxedSingletonDataCon, [state_id], the_rhs)
279

280
       return (ccall_res_ty, the_alt)
281

282
mk_alt return_result (Just prim_res_ty, wrap_result)
283
                -- The ccall returns a non-() value
284
  | isUnboxedTupleType prim_res_ty= do
285
    let
286
        Just ls = tyConAppArgs_maybe prim_res_ty
287 288 289 290
        arity = 1 + length ls
    args_ids@(result_id:as) <- mapM newSysLocalDs ls
    state_id <- newSysLocalDs realWorldStatePrimTy
    let
291
        the_rhs = return_result (Var state_id)
292
                                (wrap_result (Var result_id) : map Var as)
293
        ccall_res_ty = mkTyConApp (tupleTyCon Unboxed arity)
294
                                  (realWorldStatePrimTy : ls)
295
        the_alt      = ( DataAlt (tupleDataCon Unboxed arity)
296 297 298 299 300 301 302 303
                       , (state_id : args_ids)
                       , the_rhs
                       )
    return (ccall_res_ty, the_alt)

  | otherwise = do
    result_id <- newSysLocalDs prim_res_ty
    state_id <- newSysLocalDs realWorldStatePrimTy
304
    let
305
        the_rhs = return_result (Var state_id)
306 307 308 309
                                [wrap_result (Var result_id)]
        ccall_res_ty = mkTyConApp unboxedPairTyCon [realWorldStatePrimTy, prim_res_ty]
        the_alt      = (DataAlt unboxedPairDataCon, [state_id, result_id], the_rhs)
    return (ccall_res_ty, the_alt)
310 311 312


resultWrapper :: Type
313
              -> DsM (Maybe Type,               -- Type of the expected result, if any
314
                      CoreExpr -> CoreExpr)     -- Wrapper for the result
315 316 317
-- resultWrapper deals with the result *value*
-- E.g. foreign import foo :: Int -> IO T
-- Then resultWrapper deals with marshalling the 'T' part
318 319
resultWrapper result_ty
  -- Base case 1: primitive types
320
  | isPrimitiveType result_ty
321
  = return (Just result_ty, \e -> e)
322

323
  -- Base case 2: the unit type ()
324
  | Just (tc,_) <- maybe_tc_app, tc `hasKey` unitTyConKey
Ian Lynagh's avatar
Ian Lynagh committed
325
  = return (Nothing, \_ -> Var unitDataConId)
326

327
  -- Base case 3: the boolean type
328
  | Just (tc,_) <- maybe_tc_app, tc `hasKey` boolTyConKey
329 330 331
  = do
    dflags <- getDynFlags
    return
332
     (Just intPrimTy, \e -> mkWildCase e intPrimTy
333
                                   boolTy
334 335
                                   [(DEFAULT                    ,[],Var trueDataConId ),
                                    (LitAlt (mkMachInt dflags 0),[],Var falseDataConId)])
336

337 338
  -- Newtypes
  | Just (co, rep_ty) <- topNormaliseNewType_maybe result_ty
339
  = do (maybe_ty, wrapper) <- resultWrapper rep_ty
340
       return (maybe_ty, \e -> mkCast (wrapper e) (mkSymCo co))
341

342 343 344
  -- The type might contain foralls (eg. for dummy type arguments,
  -- referring to 'Ptr a' is legal).
  | Just (tyvar, rest) <- splitForAllTy_maybe result_ty
345 346
  = do (maybe_ty, wrapper) <- resultWrapper rest
       return (maybe_ty, \e -> Lam tyvar (wrapper e))
347

348
  -- Data types with a single constructor, which has a single arg
349
  -- This includes types like Ptr and ForeignPtr
350
  | Just (tycon, tycon_arg_tys, data_con, data_con_arg_tys) <- splitDataProductType_maybe result_ty,
351
    dataConSourceArity data_con == 1
352 353
  = do dflags <- getDynFlags
       let
354
           (unwrapped_res_ty : _) = data_con_arg_tys
355
           narrow_wrapper         = maybeNarrow dflags tycon
356 357
       (maybe_ty, wrapper) <- resultWrapper unwrapped_res_ty
       return
358
         (maybe_ty, \e -> mkApps (Var (dataConWrapId data_con))
359
                                 (map Type tycon_arg_tys ++ [wrapper (narrow_wrapper e)]))
sof's avatar
sof committed
360

361
  | otherwise
362
  = pprPanic "resultWrapper" (ppr result_ty)
363
  where
364
    maybe_tc_app = splitTyConApp_maybe result_ty
365 366 367 368 369 370

-- When the result of a foreign call is smaller than the word size, we
-- need to sign- or zero-extend the result up to the word size.  The C
-- standard appears to say that this is the responsibility of the
-- caller, not the callee.

371 372
maybeNarrow :: DynFlags -> TyCon -> (CoreExpr -> CoreExpr)
maybeNarrow dflags tycon
373 374 375
  | tycon `hasKey` int8TyConKey   = \e -> App (Var (mkPrimOpId Narrow8IntOp)) e
  | tycon `hasKey` int16TyConKey  = \e -> App (Var (mkPrimOpId Narrow16IntOp)) e
  | tycon `hasKey` int32TyConKey
376
         && wORD_SIZE dflags > 4         = \e -> App (Var (mkPrimOpId Narrow32IntOp)) e
377 378 379 380

  | tycon `hasKey` word8TyConKey  = \e -> App (Var (mkPrimOpId Narrow8WordOp)) e
  | tycon `hasKey` word16TyConKey = \e -> App (Var (mkPrimOpId Narrow16WordOp)) e
  | tycon `hasKey` word32TyConKey
381 382
         && wORD_SIZE dflags > 4         = \e -> App (Var (mkPrimOpId Narrow32WordOp)) e
  | otherwise                     = id