Reorganisation of the source tree
[ghc-hetmet.git] / compiler / deSugar / DsCCall.lhs
1 %
2 % (c) The AQUA Project, Glasgow University, 1994-1998
3 %
4 \section[DsCCall]{Desugaring C calls}
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
18 import CoreSyn
19
20 import DsMonad
21
22 import CoreUtils        ( exprType, coreAltType, mkCoerce2 )
23 import Id               ( Id, mkWildId )
24 import MkId             ( mkFCallId, realWorldPrimId, mkPrimOpId )
25 import Maybes           ( maybeToBool )
26 import ForeignCall      ( ForeignCall(..), CCallSpec(..), CCallTarget(..), Safety, 
27                           CCallConv(..), CLabelString )
28 import DataCon          ( splitProductType_maybe, dataConSourceArity, dataConWrapId )
29
30 import TcType           ( tcSplitTyConApp_maybe )
31 import Type             ( Type, isUnLiftedType, mkFunTys, mkFunTy,
32                           tyVarsOfType, mkForAllTys, mkTyConApp, 
33                           isPrimitiveType, splitTyConApp_maybe, 
34                           splitRecNewType_maybe, splitForAllTy_maybe,
35                           isUnboxedTupleType
36                         )
37
38 import PrimOp           ( PrimOp(..) )
39 import TysPrim          ( realWorldStatePrimTy, intPrimTy,
40                           byteArrayPrimTyCon, mutableByteArrayPrimTyCon,
41                           addrPrimTy
42                         )
43 import TyCon            ( TyCon, tyConDataCons, tyConName )
44 import TysWiredIn       ( unitDataConId,
45                           unboxedSingletonDataCon, unboxedPairDataCon,
46                           unboxedSingletonTyCon, unboxedPairTyCon,
47                           trueDataCon, falseDataCon, 
48                           trueDataConId, falseDataConId,
49                           listTyCon, charTyCon, boolTy, 
50                           tupleTyCon, tupleCon
51                         )
52 import BasicTypes       ( Boxity(..) )
53 import Literal          ( mkMachInt )
54 import PrelNames        ( Unique, hasKey, ioTyConKey, boolTyConKey, unitTyConKey,
55                           int8TyConKey, int16TyConKey, int32TyConKey,
56                           word8TyConKey, word16TyConKey, word32TyConKey
57                           -- dotnet interop
58                           , marshalStringName, unmarshalStringName
59                           , marshalObjectName, unmarshalObjectName
60                           , objectTyConName
61                         )
62 import VarSet           ( varSetElems )
63 import Constants        ( wORD_SIZE)
64 import Outputable
65
66 #ifdef DEBUG
67 import TypeRep
68 #endif
69
70 \end{code}
71
72 Desugaring of @ccall@s consists of adding some state manipulation,
73 unboxing any boxed primitive arguments and boxing the result if
74 desired.
75
76 The state stuff just consists of adding in
77 @PrimIO (\ s -> case s of { S# s# -> ... })@ in an appropriate place.
78
79 The unboxing is straightforward, as all information needed to unbox is
80 available from the type.  For each boxed-primitive argument, we
81 transform:
82 \begin{verbatim}
83    _ccall_ foo [ r, t1, ... tm ] e1 ... em
84    |
85    |
86    V
87    case e1 of { T1# x1# ->
88    ...
89    case em of { Tm# xm# -> xm#
90    ccall# foo [ r, t1#, ... tm# ] x1# ... xm#
91    } ... }
92 \end{verbatim}
93
94 The reboxing of a @_ccall_@ result is a bit tricker: the types don't
95 contain information about the state-pairing functions so we have to
96 keep a list of \tr{(type, s-p-function)} pairs.  We transform as
97 follows:
98 \begin{verbatim}
99    ccall# foo [ r, t1#, ... tm# ] e1# ... em#
100    |
101    |
102    V
103    \ s# -> case (ccall# foo [ r, t1#, ... tm# ] s# e1# ... em#) of
104           (StateAnd<r># result# state#) -> (R# result#, realWorld#)
105 \end{verbatim}
106
107 \begin{code}
108 dsCCall :: CLabelString -- C routine to invoke
109         -> [CoreExpr]   -- Arguments (desugared)
110         -> Safety       -- Safety of the call
111         -> Type         -- Type of the result: IO t
112         -> DsM CoreExpr
113
114 dsCCall lbl args may_gc result_ty
115   = mapAndUnzipDs unboxArg args        `thenDs` \ (unboxed_args, arg_wrappers) ->
116     boxResult id Nothing result_ty  `thenDs` \ (ccall_result_ty, res_wrapper) ->
117     newUnique                          `thenDs` \ uniq ->
118     let
119         target = StaticTarget lbl
120         the_fcall    = CCall (CCallSpec target CCallConv may_gc)
121         the_prim_app = mkFCall uniq the_fcall unboxed_args ccall_result_ty
122     in
123     returnDs (foldr ($) (res_wrapper the_prim_app) arg_wrappers)
124
125 mkFCall :: Unique -> ForeignCall 
126         -> [CoreExpr]   -- Args
127         -> Type         -- Result type
128         -> CoreExpr
129 -- Construct the ccall.  The only tricky bit is that the ccall Id should have
130 -- no free vars, so if any of the arg tys do we must give it a polymorphic type.
131 --      [I forget *why* it should have no free vars!]
132 -- For example:
133 --      mkCCall ... [s::StablePtr (a->b), x::Addr, c::Char]
134 --
135 -- Here we build a ccall thus
136 --      (ccallid::(forall a b.  StablePtr (a -> b) -> Addr -> Char -> IO Addr))
137 --                      a b s x c
138 mkFCall uniq the_fcall val_args res_ty
139   = mkApps (mkVarApps (Var the_fcall_id) tyvars) val_args
140   where
141     arg_tys = map exprType val_args
142     body_ty = (mkFunTys arg_tys res_ty)
143     tyvars  = varSetElems (tyVarsOfType body_ty)
144     ty      = mkForAllTys tyvars body_ty
145     the_fcall_id = mkFCallId uniq the_fcall ty
146 \end{code}
147
148 \begin{code}
149 unboxArg :: CoreExpr                    -- The supplied argument
150          -> DsM (CoreExpr,              -- To pass as the actual argument
151                  CoreExpr -> CoreExpr   -- Wrapper to unbox the arg
152                 )
153 -- Example: if the arg is e::Int, unboxArg will return
154 --      (x#::Int#, \W. case x of I# x# -> W)
155 -- where W is a CoreExpr that probably mentions x#
156
157 unboxArg arg
158   -- Primtive types: nothing to unbox
159   | isPrimitiveType arg_ty
160   = returnDs (arg, \body -> body)
161
162   -- Recursive newtypes
163   | Just rep_ty <- splitRecNewType_maybe arg_ty
164   = unboxArg (mkCoerce2 rep_ty arg_ty arg)
165       
166   -- Booleans
167   | Just (tc,_) <- splitTyConApp_maybe arg_ty, 
168     tc `hasKey` boolTyConKey
169   = newSysLocalDs intPrimTy             `thenDs` \ prim_arg ->
170     returnDs (Var prim_arg,
171               \ body -> Case (Case arg (mkWildId arg_ty) intPrimTy
172                                        [(DataAlt falseDataCon,[],mkIntLit 0),
173                                         (DataAlt trueDataCon, [],mkIntLit 1)])
174                                         -- In increasing tag order!
175                              prim_arg
176                              (exprType body) 
177                              [(DEFAULT,[],body)])
178
179   -- Data types with a single constructor, which has a single, primitive-typed arg
180   -- This deals with Int, Float etc; also Ptr, ForeignPtr
181   | is_product_type && data_con_arity == 1 
182   = ASSERT2(isUnLiftedType data_con_arg_ty1, pprType arg_ty)
183                         -- Typechecker ensures this
184     newSysLocalDs arg_ty                `thenDs` \ case_bndr ->
185     newSysLocalDs data_con_arg_ty1      `thenDs` \ prim_arg ->
186     returnDs (Var prim_arg,
187               \ body -> Case arg case_bndr (exprType body) [(DataAlt data_con,[prim_arg],body)]
188     )
189
190   -- Byte-arrays, both mutable and otherwise; hack warning
191   -- We're looking for values of type ByteArray, MutableByteArray
192   --    data ByteArray          ix = ByteArray        ix ix ByteArray#
193   --    data MutableByteArray s ix = MutableByteArray ix ix (MutableByteArray# s)
194   | is_product_type &&
195     data_con_arity == 3 &&
196     maybeToBool maybe_arg3_tycon &&
197     (arg3_tycon ==  byteArrayPrimTyCon ||
198      arg3_tycon ==  mutableByteArrayPrimTyCon)
199   = newSysLocalDs arg_ty                `thenDs` \ case_bndr ->
200     newSysLocalsDs data_con_arg_tys     `thenDs` \ vars@[l_var, r_var, arr_cts_var] ->
201     returnDs (Var arr_cts_var,
202               \ body -> Case arg case_bndr (exprType body) [(DataAlt data_con,vars,body)]
203
204     )
205
206   | Just (tc, [arg_ty]) <- splitTyConApp_maybe arg_ty,
207     tc == listTyCon,
208     Just (cc,[]) <- splitTyConApp_maybe arg_ty,
209     cc == charTyCon
210     -- String; dotnet only
211   = dsLookupGlobalId marshalStringName `thenDs` \ unpack_id ->
212     newSysLocalDs addrPrimTy           `thenDs` \ prim_string ->
213     returnDs (Var prim_string,
214               \ body ->
215                 let
216                  io_ty = exprType body
217                  (Just (_,[io_arg])) = tcSplitTyConApp_maybe io_ty
218                 in
219                 mkApps (Var unpack_id)
220                        [ Type io_arg
221                        , arg
222                        , Lam prim_string body
223                        ])
224   | Just (tc, [arg_ty]) <- splitTyConApp_maybe arg_ty,
225     tyConName tc == objectTyConName
226     -- Object; dotnet only
227   = dsLookupGlobalId marshalObjectName `thenDs` \ unpack_id ->
228     newSysLocalDs addrPrimTy           `thenDs` \ prim_obj  ->
229     returnDs (Var prim_obj,
230               \ body ->
231                 let
232                  io_ty = exprType body
233                  (Just (_,[io_arg])) = tcSplitTyConApp_maybe io_ty
234                 in
235                 mkApps (Var unpack_id)
236                        [ Type io_arg
237                        , arg
238                        , Lam prim_obj body
239                        ])
240
241   | otherwise
242   = getSrcSpanDs `thenDs` \ l ->
243     pprPanic "unboxArg: " (ppr l <+> ppr arg_ty)
244   where
245     arg_ty                                      = exprType arg
246     maybe_product_type                          = splitProductType_maybe arg_ty
247     is_product_type                             = maybeToBool maybe_product_type
248     Just (_, _, data_con, data_con_arg_tys)     = maybe_product_type
249     data_con_arity                              = dataConSourceArity data_con
250     (data_con_arg_ty1 : _)                      = data_con_arg_tys
251
252     (_ : _ : data_con_arg_ty3 : _) = data_con_arg_tys
253     maybe_arg3_tycon               = splitTyConApp_maybe data_con_arg_ty3
254     Just (arg3_tycon,_)            = maybe_arg3_tycon
255 \end{code}
256
257
258 \begin{code}
259 boxResult :: ((Maybe Type, CoreExpr -> CoreExpr) -> (Maybe Type, CoreExpr -> CoreExpr))
260           -> Maybe Id
261           -> Type
262           -> DsM (Type, CoreExpr -> CoreExpr)
263
264 -- Takes the result of the user-level ccall: 
265 --      either (IO t), 
266 --      or maybe just t for an side-effect-free call
267 -- Returns a wrapper for the primitive ccall itself, along with the
268 -- type of the result of the primitive ccall.  This result type
269 -- will be of the form  
270 --      State# RealWorld -> (# State# RealWorld, t' #)
271 -- where t' is the unwrapped form of t.  If t is simply (), then
272 -- the result type will be 
273 --      State# RealWorld -> (# State# RealWorld #)
274
275 boxResult augment mbTopCon result_ty
276   = case tcSplitTyConApp_maybe result_ty of
277         -- This split absolutely has to be a tcSplit, because we must
278         -- see the IO type; and it's a newtype which is transparent to splitTyConApp.
279
280         -- The result is IO t, so wrap the result in an IO constructor
281         Just (io_tycon, [io_res_ty]) | io_tycon `hasKey` ioTyConKey
282                 -> resultWrapper io_res_ty             `thenDs` \ res ->
283                    let aug_res          = augment res
284                        extra_result_tys =
285                          case aug_res of
286                            (Just ty,_) 
287                              | isUnboxedTupleType ty ->
288                                 let (Just (_, ls)) = splitTyConApp_maybe ty in tail ls
289                            _ -> []
290                    in
291                    mk_alt (return_result extra_result_tys) aug_res 
292                                                         `thenDs` \ (ccall_res_ty, the_alt) ->
293                    newSysLocalDs  realWorldStatePrimTy  `thenDs` \ state_id ->
294                    let
295                         io_data_con = head (tyConDataCons io_tycon)
296                         toIOCon = 
297                           case mbTopCon of
298                             Nothing -> dataConWrapId io_data_con
299                             Just x  -> x
300                         wrap = \ the_call -> 
301                                  mkApps (Var toIOCon)
302                                            [ Type io_res_ty, 
303                                              Lam state_id $
304                                               Case (App the_call (Var state_id))
305                                                    (mkWildId ccall_res_ty)
306                                                    (coreAltType the_alt) 
307                                                    [the_alt]
308                                            ]
309                    in
310                    returnDs (realWorldStatePrimTy `mkFunTy` ccall_res_ty, wrap)
311                 where
312                    return_result ts state anss 
313                      = mkConApp (tupleCon Unboxed (2 + length ts))
314                                 (Type realWorldStatePrimTy : Type io_res_ty : map Type ts ++
315                                  state : anss) 
316         -- It isn't, so do unsafePerformIO
317         -- It's not conveniently available, so we inline it
318         other -> resultWrapper result_ty            `thenDs` \ res ->
319                  mk_alt return_result (augment res) `thenDs` \ (ccall_res_ty, the_alt) ->
320                  let
321                     wrap = \ the_call -> Case (App the_call (Var realWorldPrimId)) 
322                                               (mkWildId ccall_res_ty)
323                                               (coreAltType the_alt)
324                                               [the_alt]
325                  in
326                  returnDs (realWorldStatePrimTy `mkFunTy` ccall_res_ty, wrap)
327               where
328                  return_result state [ans] = ans
329                  return_result _ _ = panic "return_result: expected single result"
330   where
331     mk_alt return_result (Nothing, wrap_result)
332         =       -- The ccall returns ()
333           newSysLocalDs realWorldStatePrimTy    `thenDs` \ state_id ->
334           let
335                 the_rhs = return_result (Var state_id) 
336                                         [wrap_result (panic "boxResult")]
337
338                 ccall_res_ty = mkTyConApp unboxedSingletonTyCon [realWorldStatePrimTy]
339                 the_alt      = (DataAlt unboxedSingletonDataCon, [state_id], the_rhs)
340           in
341           returnDs (ccall_res_ty, the_alt)
342
343     mk_alt return_result (Just prim_res_ty, wrap_result)
344                 -- The ccall returns a non-() value
345         | isUnboxedTupleType prim_res_ty
346         = let
347                 Just (_, ls) = splitTyConApp_maybe prim_res_ty
348                 arity = 1 + length ls
349           in
350           mappM newSysLocalDs ls                `thenDs` \ args_ids@(result_id:as) ->
351           newSysLocalDs realWorldStatePrimTy    `thenDs` \ state_id ->
352           let
353                 the_rhs = return_result (Var state_id) 
354                                         (wrap_result (Var result_id) : map Var as)
355                 ccall_res_ty = mkTyConApp (tupleTyCon Unboxed arity)
356                                           (realWorldStatePrimTy : ls)
357                 the_alt      = ( DataAlt (tupleCon Unboxed arity)
358                                , (state_id : args_ids)
359                                , the_rhs
360                                )
361           in
362           returnDs (ccall_res_ty, the_alt)
363         | otherwise
364         = newSysLocalDs prim_res_ty             `thenDs` \ result_id ->
365           newSysLocalDs realWorldStatePrimTy    `thenDs` \ state_id ->
366           let
367                 the_rhs = return_result (Var state_id) 
368                                         [wrap_result (Var result_id)]
369
370                 ccall_res_ty = mkTyConApp unboxedPairTyCon [realWorldStatePrimTy, prim_res_ty]
371                 the_alt      = (DataAlt unboxedPairDataCon, [state_id, result_id], the_rhs)
372           in
373           returnDs (ccall_res_ty, the_alt)
374
375
376 resultWrapper :: Type
377               -> DsM (Maybe Type,               -- Type of the expected result, if any
378                       CoreExpr -> CoreExpr)     -- Wrapper for the result 
379 resultWrapper result_ty
380   -- Base case 1: primitive types
381   | isPrimitiveType result_ty
382   = returnDs (Just result_ty, \e -> e)
383
384   -- Base case 2: the unit type ()
385   | Just (tc,_) <- maybe_tc_app, tc `hasKey` unitTyConKey
386   = returnDs (Nothing, \e -> Var unitDataConId)
387
388   -- Base case 3: the boolean type
389   | Just (tc,_) <- maybe_tc_app, tc `hasKey` boolTyConKey
390   = returnDs
391      (Just intPrimTy, \e -> Case e (mkWildId intPrimTy)
392                                    boolTy
393                                    [(DEFAULT             ,[],Var trueDataConId ),
394                                     (LitAlt (mkMachInt 0),[],Var falseDataConId)])
395
396   -- Recursive newtypes
397   | Just rep_ty <- splitRecNewType_maybe result_ty
398   = resultWrapper rep_ty `thenDs` \ (maybe_ty, wrapper) ->
399     returnDs (maybe_ty, \e -> mkCoerce2 result_ty rep_ty (wrapper e))
400
401   -- The type might contain foralls (eg. for dummy type arguments,
402   -- referring to 'Ptr a' is legal).
403   | Just (tyvar, rest) <- splitForAllTy_maybe result_ty
404   = resultWrapper rest `thenDs` \ (maybe_ty, wrapper) ->
405     returnDs (maybe_ty, \e -> Lam tyvar (wrapper e))
406
407   -- Data types with a single constructor, which has a single arg
408   -- This includes types like Ptr and ForeignPtr
409   | Just (tycon, tycon_arg_tys, data_con, data_con_arg_tys) <- splitProductType_maybe result_ty,
410     dataConSourceArity data_con == 1
411   = let
412         (unwrapped_res_ty : _) = data_con_arg_tys
413         narrow_wrapper         = maybeNarrow tycon
414     in
415     resultWrapper unwrapped_res_ty `thenDs` \ (maybe_ty, wrapper) ->
416     returnDs
417       (maybe_ty, \e -> mkApps (Var (dataConWrapId data_con)) 
418                               (map Type tycon_arg_tys ++ [wrapper (narrow_wrapper e)]))
419
420     -- Strings; 'dotnet' only.
421   | Just (tc, [arg_ty]) <- maybe_tc_app,               tc == listTyCon,
422     Just (cc,[])        <- splitTyConApp_maybe arg_ty, cc == charTyCon
423   = dsLookupGlobalId unmarshalStringName        `thenDs` \ pack_id ->
424     returnDs (Just addrPrimTy,
425               \ e -> App (Var pack_id) e)
426
427     -- Objects; 'dotnet' only.
428   | Just (tc, [arg_ty]) <- maybe_tc_app, 
429     tyConName tc == objectTyConName
430   = dsLookupGlobalId unmarshalObjectName        `thenDs` \ pack_id ->
431     returnDs (Just addrPrimTy,
432               \ e -> App (Var pack_id) e)
433
434   | otherwise
435   = pprPanic "resultWrapper" (ppr result_ty)
436   where
437     maybe_tc_app = splitTyConApp_maybe result_ty
438
439 -- When the result of a foreign call is smaller than the word size, we
440 -- need to sign- or zero-extend the result up to the word size.  The C
441 -- standard appears to say that this is the responsibility of the
442 -- caller, not the callee.
443
444 maybeNarrow :: TyCon -> (CoreExpr -> CoreExpr)
445 maybeNarrow tycon
446   | tycon `hasKey` int8TyConKey   = \e -> App (Var (mkPrimOpId Narrow8IntOp)) e
447   | tycon `hasKey` int16TyConKey  = \e -> App (Var (mkPrimOpId Narrow16IntOp)) e
448   | tycon `hasKey` int32TyConKey
449          && wORD_SIZE > 4         = \e -> App (Var (mkPrimOpId Narrow32IntOp)) e
450
451   | tycon `hasKey` word8TyConKey  = \e -> App (Var (mkPrimOpId Narrow8WordOp)) e
452   | tycon `hasKey` word16TyConKey = \e -> App (Var (mkPrimOpId Narrow16WordOp)) e
453   | tycon `hasKey` word32TyConKey
454          && wORD_SIZE > 4         = \e -> App (Var (mkPrimOpId Narrow32WordOp)) e
455   | otherwise                     = id
456 \end{code}