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