Massive patch for the first months work adding System FC to GHC #12
[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, mkCoerce )
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           ( tcSplitIOType_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 import Coercion         ( Coercion, splitRecNewTypeCo_maybe, mkSymCoercion )
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, 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 -- Result, of type ???
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, co) <- splitRecNewTypeCo_maybe arg_ty
164   = unboxArg (mkCoerce (mkSymCoercion co) 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) = tcSplitIOType_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) = tcSplitIOType_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 -- The gruesome 'augment' and 'mbTopCon' are to do with .NET foreign calls
276 -- It looks a mess: I wonder if it could be refactored.
277
278 boxResult augment mbTopCon result_ty
279   | Just (io_tycon, io_res_ty) <- tcSplitIOType_maybe result_ty
280         -- isIOType_maybe handles the case where the type is a 
281         -- simple wrapping of IO.  E.g.
282         --      newtype Wrap a = W (IO a)
283         -- No coercion necessay because its a non-recursive newtype
284         -- (If we wanted to handle a *recursive* newtype too, we'd need
285         -- another case, and a coercion.)
286   =     -- The result is IO t, so wrap the result in an IO constructor
287         
288     resultWrapper io_res_ty             `thenDs` \ res ->
289     let aug_res          = augment res
290         extra_result_tys = case aug_res of
291                              (Just ty,_) 
292                                | isUnboxedTupleType ty 
293                                -> let (Just (_, ls)) = splitTyConApp_maybe ty in tail ls
294                              _ -> []
295
296         return_result state anss
297           = mkConApp (tupleCon Unboxed (2 + length extra_result_tys))
298                      (map Type (realWorldStatePrimTy : io_res_ty : extra_result_tys)
299                       ++ (state : anss)) 
300     in
301     mk_alt return_result aug_res        `thenDs` \ (ccall_res_ty, the_alt) ->
302     newSysLocalDs realWorldStatePrimTy  `thenDs` \ state_id ->
303     let
304         io_data_con = head (tyConDataCons io_tycon)
305         toIOCon = case mbTopCon of
306                         Nothing -> dataConWrapId io_data_con
307                         Just x  -> x
308         wrap = \ the_call -> mkApps (Var toIOCon)
309                                     [ Type io_res_ty, 
310                                       Lam state_id $
311                                        Case (App the_call (Var state_id))
312                                            (mkWildId ccall_res_ty)
313                                             (coreAltType the_alt) 
314                                            [the_alt]
315                                     ]
316     in
317     returnDs (realWorldStatePrimTy `mkFunTy` ccall_res_ty, wrap)
318
319 boxResult augment mbTopCon result_ty
320   =     -- It isn't IO, so do unsafePerformIO
321         -- It's not conveniently available, so we inline it
322     resultWrapper result_ty            `thenDs` \ res ->
323     mk_alt return_result (augment res) `thenDs` \ (ccall_res_ty, the_alt) ->
324     let
325         wrap = \ the_call -> Case (App the_call (Var realWorldPrimId)) 
326                                               (mkWildId ccall_res_ty)
327                                               (coreAltType the_alt)
328                                               [the_alt]
329     in
330     returnDs (realWorldStatePrimTy `mkFunTy` ccall_res_ty, wrap)
331   where
332     return_result state [ans] = ans
333     return_result _ _ = panic "return_result: expected single result"
334
335
336 mk_alt return_result (Nothing, wrap_result)
337   =     -- The ccall returns ()
338           newSysLocalDs realWorldStatePrimTy    `thenDs` \ state_id ->
339           let
340                 the_rhs = return_result (Var state_id) 
341                                         [wrap_result (panic "boxResult")]
342
343                 ccall_res_ty = mkTyConApp unboxedSingletonTyCon [realWorldStatePrimTy]
344                 the_alt      = (DataAlt unboxedSingletonDataCon, [state_id], the_rhs)
345           in
346           returnDs (ccall_res_ty, the_alt)
347
348 mk_alt return_result (Just prim_res_ty, wrap_result)
349                 -- The ccall returns a non-() value
350   | isUnboxedTupleType prim_res_ty
351   = let
352         Just (_, ls) = splitTyConApp_maybe prim_res_ty
353         arity = 1 + length ls
354     in
355     mappM newSysLocalDs ls              `thenDs` \ args_ids@(result_id:as) ->
356     newSysLocalDs realWorldStatePrimTy  `thenDs` \ state_id ->
357     let
358         the_rhs = return_result (Var state_id) 
359                                 (wrap_result (Var result_id) : map Var as)
360         ccall_res_ty = mkTyConApp (tupleTyCon Unboxed arity)
361                                   (realWorldStatePrimTy : ls)
362         the_alt      = ( DataAlt (tupleCon Unboxed arity)
363                        , (state_id : args_ids)
364                        , the_rhs
365                        )
366     in
367     returnDs (ccall_res_ty, the_alt)
368
369   | otherwise
370   = newSysLocalDs prim_res_ty           `thenDs` \ result_id ->
371     newSysLocalDs realWorldStatePrimTy  `thenDs` \ state_id ->
372     let
373         the_rhs = return_result (Var state_id) 
374                                 [wrap_result (Var result_id)]
375         ccall_res_ty = mkTyConApp unboxedPairTyCon [realWorldStatePrimTy, prim_res_ty]
376         the_alt      = (DataAlt unboxedPairDataCon, [state_id, result_id], the_rhs)
377     in
378     returnDs (ccall_res_ty, the_alt)
379
380
381 resultWrapper :: Type
382               -> DsM (Maybe Type,               -- Type of the expected result, if any
383                       CoreExpr -> CoreExpr)     -- Wrapper for the result 
384 resultWrapper result_ty
385   -- Base case 1: primitive types
386   | isPrimitiveType result_ty
387   = returnDs (Just result_ty, \e -> e)
388
389   -- Base case 2: the unit type ()
390   | Just (tc,_) <- maybe_tc_app, tc `hasKey` unitTyConKey
391   = returnDs (Nothing, \e -> Var unitDataConId)
392
393   -- Base case 3: the boolean type
394   | Just (tc,_) <- maybe_tc_app, tc `hasKey` boolTyConKey
395   = returnDs
396      (Just intPrimTy, \e -> Case e (mkWildId intPrimTy)
397                                    boolTy
398                                    [(DEFAULT             ,[],Var trueDataConId ),
399                                     (LitAlt (mkMachInt 0),[],Var falseDataConId)])
400
401   -- Recursive newtypes
402   | Just (rep_ty, co) <- splitRecNewTypeCo_maybe result_ty
403   = resultWrapper rep_ty `thenDs` \ (maybe_ty, wrapper) ->
404     returnDs (maybe_ty, \e -> mkCoerce co (wrapper e))
405
406   -- The type might contain foralls (eg. for dummy type arguments,
407   -- referring to 'Ptr a' is legal).
408   | Just (tyvar, rest) <- splitForAllTy_maybe result_ty
409   = resultWrapper rest `thenDs` \ (maybe_ty, wrapper) ->
410     returnDs (maybe_ty, \e -> Lam tyvar (wrapper e))
411
412   -- Data types with a single constructor, which has a single arg
413   -- This includes types like Ptr and ForeignPtr
414   | Just (tycon, tycon_arg_tys, data_con, data_con_arg_tys) <- splitProductType_maybe result_ty,
415     dataConSourceArity data_con == 1
416   = let
417         (unwrapped_res_ty : _) = data_con_arg_tys
418         narrow_wrapper         = maybeNarrow tycon
419     in
420     resultWrapper unwrapped_res_ty `thenDs` \ (maybe_ty, wrapper) ->
421     returnDs
422       (maybe_ty, \e -> mkApps (Var (dataConWrapId data_con)) 
423                               (map Type tycon_arg_tys ++ [wrapper (narrow_wrapper e)]))
424
425     -- Strings; 'dotnet' only.
426   | Just (tc, [arg_ty]) <- maybe_tc_app,               tc == listTyCon,
427     Just (cc,[])        <- splitTyConApp_maybe arg_ty, cc == charTyCon
428   = dsLookupGlobalId unmarshalStringName        `thenDs` \ pack_id ->
429     returnDs (Just addrPrimTy,
430               \ e -> App (Var pack_id) e)
431
432     -- Objects; 'dotnet' only.
433   | Just (tc, [arg_ty]) <- maybe_tc_app, 
434     tyConName tc == objectTyConName
435   = dsLookupGlobalId unmarshalObjectName        `thenDs` \ pack_id ->
436     returnDs (Just addrPrimTy,
437               \ e -> App (Var pack_id) e)
438
439   | otherwise
440   = pprPanic "resultWrapper" (ppr result_ty)
441   where
442     maybe_tc_app = splitTyConApp_maybe result_ty
443
444 -- When the result of a foreign call is smaller than the word size, we
445 -- need to sign- or zero-extend the result up to the word size.  The C
446 -- standard appears to say that this is the responsibility of the
447 -- caller, not the callee.
448
449 maybeNarrow :: TyCon -> (CoreExpr -> CoreExpr)
450 maybeNarrow tycon
451   | tycon `hasKey` int8TyConKey   = \e -> App (Var (mkPrimOpId Narrow8IntOp)) e
452   | tycon `hasKey` int16TyConKey  = \e -> App (Var (mkPrimOpId Narrow16IntOp)) e
453   | tycon `hasKey` int32TyConKey
454          && wORD_SIZE > 4         = \e -> App (Var (mkPrimOpId Narrow32IntOp)) e
455
456   | tycon `hasKey` word8TyConKey  = \e -> App (Var (mkPrimOpId Narrow8WordOp)) e
457   | tycon `hasKey` word16TyConKey = \e -> App (Var (mkPrimOpId Narrow16WordOp)) e
458   | tycon `hasKey` word32TyConKey
459          && wORD_SIZE > 4         = \e -> App (Var (mkPrimOpId Narrow32WordOp)) e
460   | otherwise                     = id
461 \end{code}