[project @ 2002-09-06 14:35:42 by simonmar]
[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 boxResult arg_ids result_ty
224   = case tcSplitTyConApp_maybe result_ty of
225         -- This split absolutely has to be a tcSplit, because we must
226         -- see the IO type; and it's a newtype which is transparent to splitTyConApp.
227
228         -- The result is IO t, so wrap the result in an IO constructor
229         Just (io_tycon, [io_res_ty]) | io_tycon `hasKey` ioTyConKey
230                 -> mk_alt return_result 
231                           (resultWrapper io_res_ty)     `thenDs` \ (ccall_res_ty, the_alt) ->
232                    newSysLocalDs  realWorldStatePrimTy   `thenDs` \ state_id ->
233                    let
234                         io_data_con = head (tyConDataCons io_tycon)
235                         wrap = \ the_call -> 
236                                  mkApps (Var (dataConWrapId io_data_con))
237                                            [ Type io_res_ty, 
238                                              Lam state_id $
239                                               Case (App the_call (Var state_id))
240                                                    (mkWildId ccall_res_ty)
241                                                    [the_alt]
242                                            ]
243                    in
244                    returnDs (realWorldStatePrimTy `mkFunTy` ccall_res_ty, wrap)
245                 where
246                    return_result state ans = mkConApp unboxedPairDataCon 
247                                                       [Type realWorldStatePrimTy, Type io_res_ty, 
248                                                        state, ans]
249
250         -- It isn't, so do unsafePerformIO
251         -- It's not conveniently available, so we inline it
252         other -> mk_alt return_result
253                         (resultWrapper result_ty) `thenDs` \ (ccall_res_ty, the_alt) ->
254                  let
255                     wrap = \ the_call -> Case (App the_call (Var realWorldPrimId)) 
256                                               (mkWildId ccall_res_ty)
257                                               [the_alt]
258                  in
259                  returnDs (realWorldStatePrimTy `mkFunTy` ccall_res_ty, wrap)
260               where
261                  return_result state ans = ans
262   where
263     mk_alt return_result (Nothing, wrap_result)
264         =       -- The ccall returns ()
265           newSysLocalDs realWorldStatePrimTy    `thenDs` \ state_id ->
266           let
267                 the_rhs = return_result (Var state_id) 
268                                         (wrap_result (panic "boxResult"))
269
270                 ccall_res_ty = mkTyConApp unboxedSingletonTyCon [realWorldStatePrimTy]
271                 the_alt      = (DataAlt unboxedSingletonDataCon, [state_id], the_rhs)
272           in
273           returnDs (ccall_res_ty, the_alt)
274
275     mk_alt return_result (Just prim_res_ty, wrap_result)
276         =       -- The ccall returns a non-() value
277           newSysLocalDs prim_res_ty             `thenDs` \ result_id ->
278           newSysLocalDs realWorldStatePrimTy    `thenDs` \ state_id ->
279           let
280                 the_rhs = return_result (Var state_id) 
281                                         (wrap_result (Var result_id))
282
283                 ccall_res_ty = mkTyConApp unboxedPairTyCon [realWorldStatePrimTy, prim_res_ty]
284                 the_alt      = (DataAlt unboxedPairDataCon, [state_id, result_id], the_rhs)
285           in
286           returnDs (ccall_res_ty, the_alt)
287
288
289 resultWrapper :: Type
290               -> (Maybe Type,           -- Type of the expected result, if any
291                   CoreExpr -> CoreExpr) -- Wrapper for the result 
292 resultWrapper result_ty
293   -- Base case 1: primitive types
294   | isPrimitiveType result_ty
295   = (Just result_ty, \e -> e)
296
297   -- Base case 2: the unit type ()
298   | Just (tc,_) <- maybe_tc_app, tc `hasKey` unitTyConKey
299   = (Nothing, \e -> Var unitDataConId)
300
301   -- Base case 3: the boolean type
302   | Just (tc,_) <- maybe_tc_app, tc `hasKey` boolTyConKey
303   = (Just intPrimTy, \e -> Case e (mkWildId intPrimTy)
304                                   [(DEFAULT             ,[],Var trueDataConId ),
305                                    (LitAlt (mkMachInt 0),[],Var falseDataConId)])
306
307   -- Recursive newtypes
308   | Just rep_ty <- splitNewType_maybe result_ty
309   = let
310         (maybe_ty, wrapper) = resultWrapper rep_ty
311     in
312     (maybe_ty, \e -> mkCoerce2 result_ty rep_ty (wrapper e))
313
314   -- Data types with a single constructor, which has a single arg
315   | Just (tycon, tycon_arg_tys, data_con, data_con_arg_tys) <- splitProductType_maybe result_ty,
316     dataConSourceArity data_con == 1
317   = let
318         (maybe_ty, wrapper)    = resultWrapper unwrapped_res_ty
319         (unwrapped_res_ty : _) = data_con_arg_tys
320         narrow_wrapper         = maybeNarrow tycon
321     in
322     (maybe_ty, \e -> mkApps (Var (dataConWrapId data_con)) 
323                             (map Type tycon_arg_tys ++ [wrapper (narrow_wrapper e)]))
324
325   | otherwise
326   = pprPanic "resultWrapper" (ppr result_ty)
327   where
328     maybe_tc_app = splitTyConApp_maybe result_ty
329
330 -- When the result of a foreign call is smaller than the word size, we
331 -- need to sign- or zero-extend the result up to the word size.  The C
332 -- standard appears to say that this is the responsibility of the
333 -- caller, not the callee.
334
335 maybeNarrow :: TyCon -> (CoreExpr -> CoreExpr)
336 maybeNarrow tycon
337   | tycon `hasKey` int8TyConKey   = \e -> App (Var (mkPrimOpId Narrow8IntOp)) e
338   | tycon `hasKey` int16TyConKey  = \e -> App (Var (mkPrimOpId Narrow16IntOp)) e
339   | tycon `hasKey` int32TyConKey
340          && wORD_SIZE > 4         = \e -> App (Var (mkPrimOpId Narrow32IntOp)) e
341
342   | tycon `hasKey` word8TyConKey  = \e -> App (Var (mkPrimOpId Narrow8WordOp)) e
343   | tycon `hasKey` word16TyConKey = \e -> App (Var (mkPrimOpId Narrow16WordOp)) e
344   | tycon `hasKey` word32TyConKey
345          && wORD_SIZE > 4         = \e -> App (Var (mkPrimOpId Narrow32WordOp)) e
346   | otherwise                     = id
347 \end{code}