[project @ 2002-04-11 12:03:29 by simonpj]
[ghc-hetmet.git] / ghc / compiler / deSugar / DsCCall.lhs
1 %
2 % (c) The AQUA Project, Glasgow University, 1994-1998
3 %
4 \section[DsCCall]{Desugaring \tr{_ccall_}s and \tr{_casm_}s}
5
6 \begin{code}
7 module DsCCall 
8         ( dsCCall
9         , mkFCall
10         , unboxArg
11         , boxResult
12         , resultWrapper
13         ) where
14
15 #include "HsVersions.h"
16
17 import CoreSyn
18
19 import DsMonad
20
21 import CoreUtils        ( exprType, mkCoerce2 )
22 import Id               ( Id, mkWildId, idType )
23 import MkId             ( mkFCallId, realWorldPrimId, mkPrimOpId )
24 import Maybes           ( maybeToBool )
25 import ForeignCall      ( ForeignCall(..), CCallSpec(..), CCallTarget(..), Safety, CCallConv(..) )
26 import DataCon          ( splitProductType_maybe, dataConSourceArity, dataConWrapId )
27 import ForeignCall      ( ForeignCall, CCallTarget(..) )
28
29 import TcType           ( tcSplitTyConApp_maybe )
30 import Type             ( Type, isUnLiftedType, mkFunTys, mkFunTy,
31                           tyVarsOfType, mkForAllTys, mkTyConApp, 
32                           isPrimitiveType, eqType,
33                           splitTyConApp_maybe, splitNewType_maybe
34                         )
35
36 import PrimOp           ( PrimOp(..) )
37 import TysPrim          ( realWorldStatePrimTy,
38                           byteArrayPrimTyCon, mutableByteArrayPrimTyCon,
39                           intPrimTy, foreignObjPrimTy
40                         )
41 import TyCon            ( TyCon, tyConDataCons )
42 import TysWiredIn       ( unitDataConId,
43                           unboxedSingletonDataCon, unboxedPairDataCon,
44                           unboxedSingletonTyCon, unboxedPairTyCon,
45                           trueDataCon, falseDataCon, 
46                           trueDataConId, falseDataConId 
47                         )
48 import Literal          ( mkMachInt )
49 import CStrings         ( CLabelString )
50 import PrelNames        ( Unique, hasKey, ioTyConKey, boolTyConKey, unitTyConKey,
51                           int8TyConKey, int16TyConKey, int32TyConKey,
52                           word8TyConKey, word16TyConKey, word32TyConKey
53                         )
54 import VarSet           ( varSetElems )
55 import Constants        ( wORD_SIZE)
56 import Outputable
57 \end{code}
58
59 Desugaring of @ccall@s consists of adding some state manipulation,
60 unboxing any boxed primitive arguments and boxing the result if
61 desired.
62
63 The state stuff just consists of adding in
64 @PrimIO (\ s -> case s of { S# s# -> ... })@ in an appropriate place.
65
66 The unboxing is straightforward, as all information needed to unbox is
67 available from the type.  For each boxed-primitive argument, we
68 transform:
69 \begin{verbatim}
70    _ccall_ foo [ r, t1, ... tm ] e1 ... em
71    |
72    |
73    V
74    case e1 of { T1# x1# ->
75    ...
76    case em of { Tm# xm# -> xm#
77    ccall# foo [ r, t1#, ... tm# ] x1# ... xm#
78    } ... }
79 \end{verbatim}
80
81 The reboxing of a @_ccall_@ result is a bit tricker: the types don't
82 contain information about the state-pairing functions so we have to
83 keep a list of \tr{(type, s-p-function)} pairs.  We transform as
84 follows:
85 \begin{verbatim}
86    ccall# foo [ r, t1#, ... tm# ] e1# ... em#
87    |
88    |
89    V
90    \ s# -> case (ccall# foo [ r, t1#, ... tm# ] s# e1# ... em#) of
91           (StateAnd<r># result# state#) -> (R# result#, realWorld#)
92 \end{verbatim}
93
94 \begin{code}
95 dsCCall :: CLabelString -- C routine to invoke
96         -> [CoreExpr]   -- Arguments (desugared)
97         -> Safety       -- Safety of the call
98         -> Bool         -- True <=> really a "_casm_"
99         -> Type         -- Type of the result: IO t
100         -> DsM CoreExpr
101
102 dsCCall lbl args may_gc is_asm result_ty
103   = mapAndUnzipDs unboxArg args `thenDs` \ (unboxed_args, arg_wrappers) ->
104     boxResult [] result_ty      `thenDs` \ (ccall_result_ty, res_wrapper) ->
105     getUniqueDs                 `thenDs` \ uniq ->
106     let
107         target | is_asm    = CasmTarget lbl
108                | otherwise = StaticTarget lbl
109         the_fcall    = CCall (CCallSpec target CCallConv may_gc)
110         the_prim_app = mkFCall uniq the_fcall unboxed_args ccall_result_ty
111     in
112     returnDs (foldr ($) (res_wrapper the_prim_app) arg_wrappers)
113
114 mkFCall :: Unique -> ForeignCall 
115         -> [CoreExpr]   -- Args
116         -> Type         -- Result type
117         -> CoreExpr
118 -- Construct the ccall.  The only tricky bit is that the ccall Id should have
119 -- no free vars, so if any of the arg tys do we must give it a polymorphic type.
120 --      [I forget *why* it should have no free vars!]
121 -- For example:
122 --      mkCCall ... [s::StablePtr (a->b), x::Addr, c::Char]
123 --
124 -- Here we build a ccall thus
125 --      (ccallid::(forall a b.  StablePtr (a -> b) -> Addr -> Char -> IO Addr))
126 --                      a b s x c
127 mkFCall uniq the_fcall val_args res_ty
128   = mkApps (mkVarApps (Var the_fcall_id) tyvars) val_args
129   where
130     arg_tys = map exprType val_args
131     body_ty = (mkFunTys arg_tys res_ty)
132     tyvars  = varSetElems (tyVarsOfType body_ty)
133     ty      = mkForAllTys tyvars body_ty
134     the_fcall_id = mkFCallId uniq the_fcall ty
135 \end{code}
136
137 \begin{code}
138 unboxArg :: CoreExpr                    -- The supplied argument
139          -> DsM (CoreExpr,              -- To pass as the actual argument
140                  CoreExpr -> CoreExpr   -- Wrapper to unbox the arg
141                 )
142 -- Example: if the arg is e::Int, unboxArg will return
143 --      (x#::Int#, \W. case x of I# x# -> W)
144 -- where W is a CoreExpr that probably mentions x#
145
146 unboxArg arg
147   -- Primtive types: nothing to unbox
148   | isPrimitiveType arg_ty
149   = returnDs (arg, \body -> body)
150
151   -- Recursive newtypes
152   | Just rep_ty <- splitNewType_maybe arg_ty
153   = unboxArg (mkCoerce2 rep_ty arg_ty arg)
154       
155   -- Booleans
156   | Just (tc,_) <- splitTyConApp_maybe arg_ty, 
157     tc `hasKey` boolTyConKey
158   = newSysLocalDs intPrimTy             `thenDs` \ prim_arg ->
159     returnDs (Var prim_arg,
160               \ body -> Case (Case arg (mkWildId arg_ty)
161                                        [(DataAlt falseDataCon,[],mkIntLit 0),
162                                         (DataAlt trueDataCon, [],mkIntLit 1)])
163                              prim_arg 
164                              [(DEFAULT,[],body)])
165
166   -- Data types with a single constructor, which has a single, primitive-typed arg
167   -- This deals with Int, Float etc
168   | is_product_type && data_con_arity == 1 
169   = ASSERT(isUnLiftedType data_con_arg_ty1 )    -- Typechecker ensures this
170     newSysLocalDs arg_ty                `thenDs` \ case_bndr ->
171     newSysLocalDs data_con_arg_ty1      `thenDs` \ prim_arg ->
172     returnDs (Var prim_arg,
173               \ body -> Case arg case_bndr [(DataAlt data_con,[prim_arg],body)]
174     )
175
176   -- Byte-arrays, both mutable and otherwise; hack warning
177   -- We're looking for values of type ByteArray, MutableByteArray
178   --    data ByteArray          ix = ByteArray        ix ix ByteArray#
179   --    data MutableByteArray s ix = MutableByteArray ix ix (MutableByteArray# s)
180   | is_product_type &&
181     data_con_arity == 3 &&
182     maybeToBool maybe_arg3_tycon &&
183     (arg3_tycon ==  byteArrayPrimTyCon ||
184      arg3_tycon ==  mutableByteArrayPrimTyCon)
185     -- and, of course, it is an instance of CCallable
186   = newSysLocalDs arg_ty                `thenDs` \ case_bndr ->
187     newSysLocalsDs data_con_arg_tys     `thenDs` \ vars@[l_var, r_var, arr_cts_var] ->
188     returnDs (Var arr_cts_var,
189               \ body -> Case arg case_bndr [(DataAlt data_con,vars,body)]
190     )
191
192   | otherwise
193   = getSrcLocDs `thenDs` \ l ->
194     pprPanic "unboxArg: " (ppr l <+> ppr arg_ty)
195   where
196     arg_ty                                      = exprType arg
197     maybe_product_type                          = splitProductType_maybe arg_ty
198     is_product_type                             = maybeToBool maybe_product_type
199     Just (_, _, data_con, data_con_arg_tys)     = maybe_product_type
200     data_con_arity                              = dataConSourceArity data_con
201     (data_con_arg_ty1 : _)                      = data_con_arg_tys
202
203     (_ : _ : data_con_arg_ty3 : _) = data_con_arg_tys
204     maybe_arg3_tycon               = splitTyConApp_maybe data_con_arg_ty3
205     Just (arg3_tycon,_)            = maybe_arg3_tycon
206 \end{code}
207
208
209 \begin{code}
210 boxResult :: [Id] -> Type -> DsM (Type, CoreExpr -> CoreExpr)
211
212 -- Takes the result of the user-level ccall: 
213 --      either (IO t), 
214 --      or maybe just t for an side-effect-free call
215 -- Returns a wrapper for the primitive ccall itself, along with the
216 -- type of the result of the primitive ccall.  This result type
217 -- will be of the form  
218 --      State# RealWorld -> (# State# RealWorld, t' #)
219 -- where t' is the unwrapped form of t.  If t is simply (), then
220 -- the result type will be 
221 --      State# RealWorld -> (# State# RealWorld #)
222
223 -- Here is where we arrange that ForeignPtrs which are passed to a 'safe'
224 -- foreign import don't get finalized until the call returns.  For each
225 -- argument of type ForeignObj# we arrange to touch# the argument after
226 -- the call.  The arg_ids passed in are the Ids passed to the actual ccall.
227
228 boxResult arg_ids result_ty
229   = case tcSplitTyConApp_maybe result_ty of
230         -- This split absolutely has to be a tcSplit, because we must
231         -- see the IO type; and it's a newtype which is transparent to splitTyConApp.
232
233         -- The result is IO t, so wrap the result in an IO constructor
234         Just (io_tycon, [io_res_ty]) | io_tycon `hasKey` ioTyConKey
235                 -> mk_alt return_result 
236                           (resultWrapper io_res_ty)     `thenDs` \ (ccall_res_ty, the_alt) ->
237                    newSysLocalDs  realWorldStatePrimTy   `thenDs` \ state_id ->
238                    let
239                         io_data_con = head (tyConDataCons io_tycon)
240                         wrap = \ the_call -> 
241                                  mkApps (Var (dataConWrapId io_data_con))
242                                            [ Type io_res_ty, 
243                                              Lam state_id $
244                                               Case (App the_call (Var state_id))
245                                                    (mkWildId ccall_res_ty)
246                                                    [the_alt]
247                                            ]
248                    in
249                    returnDs (realWorldStatePrimTy `mkFunTy` ccall_res_ty, wrap)
250                 where
251                    return_result state ans = mkConApp unboxedPairDataCon 
252                                                       [Type realWorldStatePrimTy, Type io_res_ty, 
253                                                        state, ans]
254
255         -- It isn't, so do unsafePerformIO
256         -- It's not conveniently available, so we inline it
257         other -> mk_alt return_result
258                         (resultWrapper result_ty) `thenDs` \ (ccall_res_ty, the_alt) ->
259                  let
260                     wrap = \ the_call -> Case (App the_call (Var realWorldPrimId)) 
261                                               (mkWildId ccall_res_ty)
262                                               [the_alt]
263                  in
264                  returnDs (realWorldStatePrimTy `mkFunTy` ccall_res_ty, wrap)
265               where
266                  return_result state ans = ans
267   where
268     mk_alt return_result (Nothing, wrap_result)
269         =       -- The ccall returns ()
270           let
271                 rhs_fun state_id = return_result (Var state_id) 
272                                         (wrap_result (panic "boxResult"))
273           in
274           newSysLocalDs realWorldStatePrimTy    `thenDs` \ state_id ->
275           mkTouches arg_ids state_id rhs_fun    `thenDs` \ the_rhs ->
276           let
277                 ccall_res_ty = mkTyConApp unboxedSingletonTyCon [realWorldStatePrimTy]
278                 the_alt      = (DataAlt unboxedSingletonDataCon, [state_id], the_rhs)
279           in
280           returnDs (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           newSysLocalDs prim_res_ty             `thenDs` \ result_id ->
285           let
286                 rhs_fun state_id = return_result (Var state_id) 
287                                         (wrap_result (Var result_id))
288           in
289           newSysLocalDs realWorldStatePrimTy    `thenDs` \ state_id ->
290           mkTouches arg_ids state_id rhs_fun    `thenDs` \ the_rhs ->
291           let
292                 ccall_res_ty = mkTyConApp unboxedPairTyCon [realWorldStatePrimTy, prim_res_ty]
293                 the_alt      = (DataAlt unboxedPairDataCon, [state_id, result_id], the_rhs)
294           in
295           returnDs (ccall_res_ty, the_alt)
296
297 touchzh = mkPrimOpId TouchOp
298
299 mkTouches []     s cont = returnDs (cont s)
300 mkTouches (v:vs) s cont
301   | not (idType v `eqType` foreignObjPrimTy) = mkTouches vs s cont
302   | otherwise = newSysLocalDs realWorldStatePrimTy `thenDs` \s' -> 
303                 mkTouches vs s' cont `thenDs` \ rest ->
304                 returnDs (Case (mkApps (Var touchzh) [Type foreignObjPrimTy, 
305                                                       Var v, Var s]) s' 
306                                 [(DEFAULT, [], rest)])
307
308 resultWrapper :: Type
309               -> (Maybe Type,           -- Type of the expected result, if any
310                   CoreExpr -> CoreExpr) -- Wrapper for the result 
311 resultWrapper result_ty
312   -- Base case 1: primitive types
313   | isPrimitiveType result_ty
314   = (Just result_ty, \e -> e)
315
316   -- Base case 2: the unit type ()
317   | Just (tc,_) <- maybe_tc_app, tc `hasKey` unitTyConKey
318   = (Nothing, \e -> Var unitDataConId)
319
320   -- Base case 3: the boolean type
321   | Just (tc,_) <- maybe_tc_app, tc `hasKey` boolTyConKey
322   = (Just intPrimTy, \e -> Case e (mkWildId intPrimTy)
323                                   [(DEFAULT             ,[],Var trueDataConId ),
324                                    (LitAlt (mkMachInt 0),[],Var falseDataConId)])
325
326   -- Recursive newtypes
327   | Just rep_ty <- splitNewType_maybe result_ty
328   = let
329         (maybe_ty, wrapper) = resultWrapper rep_ty
330     in
331     (maybe_ty, \e -> mkCoerce2 result_ty rep_ty (wrapper e))
332
333   -- Data types with a single constructor, which has a single arg
334   | Just (tycon, tycon_arg_tys, data_con, data_con_arg_tys) <- splitProductType_maybe result_ty,
335     dataConSourceArity data_con == 1
336   = let
337         (maybe_ty, wrapper)    = resultWrapper unwrapped_res_ty
338         (unwrapped_res_ty : _) = data_con_arg_tys
339         narrow_wrapper         = maybeNarrow tycon
340     in
341     (maybe_ty, \e -> mkApps (Var (dataConWrapId data_con)) 
342                             (map Type tycon_arg_tys ++ [wrapper (narrow_wrapper e)]))
343
344   | otherwise
345   = pprPanic "resultWrapper" (ppr result_ty)
346   where
347     maybe_tc_app = splitTyConApp_maybe result_ty
348
349 -- When the result of a foreign call is smaller than the word size, we
350 -- need to sign- or zero-extend the result up to the word size.  The C
351 -- standard appears to say that this is the responsibility of the
352 -- caller, not the callee.
353
354 maybeNarrow :: TyCon -> (CoreExpr -> CoreExpr)
355 maybeNarrow tycon
356   | tycon `hasKey` int8TyConKey   = \e -> App (Var (mkPrimOpId Narrow8IntOp)) e
357   | tycon `hasKey` int16TyConKey  = \e -> App (Var (mkPrimOpId Narrow16IntOp)) e
358   | tycon `hasKey` int32TyConKey
359          && wORD_SIZE > 4         = \e -> App (Var (mkPrimOpId Narrow32IntOp)) e
360
361   | tycon `hasKey` word8TyConKey  = \e -> App (Var (mkPrimOpId Narrow8WordOp)) e
362   | tycon `hasKey` word16TyConKey = \e -> App (Var (mkPrimOpId Narrow16WordOp)) e
363   | tycon `hasKey` word32TyConKey
364          && wORD_SIZE > 4         = \e -> App (Var (mkPrimOpId Narrow32WordOp)) e
365   | otherwise                     = id
366 \end{code}