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