2 % (c) The AQUA Project, Glasgow University, 1994-1998
4 \section[DsCCall]{Desugaring \tr{_ccall_}s and \tr{_casm_}s}
15 #include "HsVersions.h"
21 import CoreUtils ( exprType, mkCoerce )
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(..) )
29 import TcType ( tcSplitTyConApp_maybe )
30 import Type ( Type, isUnLiftedType, mkFunTys, mkFunTy,
31 tyVarsOfType, mkForAllTys, mkTyConApp,
32 isPrimitiveType, eqType,
33 splitTyConApp_maybe, splitNewType_maybe
36 import PrimOp ( PrimOp(TouchOp) )
37 import TysPrim ( realWorldStatePrimTy,
38 byteArrayPrimTyCon, mutableByteArrayPrimTyCon,
39 intPrimTy, foreignObjPrimTy
41 import TyCon ( tyConDataCons )
42 import TysWiredIn ( unitDataConId,
43 unboxedSingletonDataCon, unboxedPairDataCon,
44 unboxedSingletonTyCon, unboxedPairTyCon,
45 trueDataCon, falseDataCon,
46 trueDataConId, falseDataConId
48 import Literal ( mkMachInt )
49 import CStrings ( CLabelString )
50 import PrelNames ( Unique, hasKey, ioTyConKey, boolTyConKey, unitTyConKey )
51 import VarSet ( varSetElems )
55 Desugaring of @ccall@s consists of adding some state manipulation,
56 unboxing any boxed primitive arguments and boxing the result if
59 The state stuff just consists of adding in
60 @PrimIO (\ s -> case s of { S# s# -> ... })@ in an appropriate place.
62 The unboxing is straightforward, as all information needed to unbox is
63 available from the type. For each boxed-primitive argument, we
66 _ccall_ foo [ r, t1, ... tm ] e1 ... em
70 case e1 of { T1# x1# ->
72 case em of { Tm# xm# -> xm#
73 ccall# foo [ r, t1#, ... tm# ] x1# ... xm#
77 The reboxing of a @_ccall_@ result is a bit tricker: the types don't
78 contain information about the state-pairing functions so we have to
79 keep a list of \tr{(type, s-p-function)} pairs. We transform as
82 ccall# foo [ r, t1#, ... tm# ] e1# ... em#
86 \ s# -> case (ccall# foo [ r, t1#, ... tm# ] s# e1# ... em#) of
87 (StateAnd<r># result# state#) -> (R# result#, realWorld#)
91 dsCCall :: CLabelString -- C routine to invoke
92 -> [CoreExpr] -- Arguments (desugared)
93 -> Safety -- Safety of the call
94 -> Bool -- True <=> really a "_casm_"
95 -> Type -- Type of the result: IO t
98 dsCCall lbl args may_gc is_asm result_ty
99 = mapAndUnzipDs unboxArg args `thenDs` \ (unboxed_args, arg_wrappers) ->
100 boxResult [] result_ty `thenDs` \ (ccall_result_ty, res_wrapper) ->
101 getUniqueDs `thenDs` \ uniq ->
103 target | is_asm = CasmTarget lbl
104 | otherwise = StaticTarget lbl
105 the_fcall = CCall (CCallSpec target CCallConv may_gc)
106 the_prim_app = mkFCall uniq the_fcall unboxed_args ccall_result_ty
108 returnDs (foldr ($) (res_wrapper the_prim_app) arg_wrappers)
110 mkFCall :: Unique -> ForeignCall
111 -> [CoreExpr] -- Args
112 -> Type -- Result type
114 -- Construct the ccall. The only tricky bit is that the ccall Id should have
115 -- no free vars, so if any of the arg tys do we must give it a polymorphic type.
116 -- [I forget *why* it should have no free vars!]
118 -- mkCCall ... [s::StablePtr (a->b), x::Addr, c::Char]
120 -- Here we build a ccall thus
121 -- (ccallid::(forall a b. StablePtr (a -> b) -> Addr -> Char -> IO Addr))
123 mkFCall uniq the_fcall val_args res_ty
124 = mkApps (mkVarApps (Var the_fcall_id) tyvars) val_args
126 arg_tys = map exprType val_args
127 body_ty = (mkFunTys arg_tys res_ty)
128 tyvars = varSetElems (tyVarsOfType body_ty)
129 ty = mkForAllTys tyvars body_ty
130 the_fcall_id = mkFCallId uniq the_fcall ty
134 unboxArg :: CoreExpr -- The supplied argument
135 -> DsM (CoreExpr, -- To pass as the actual argument
136 CoreExpr -> CoreExpr -- Wrapper to unbox the arg
138 -- Example: if the arg is e::Int, unboxArg will return
139 -- (x#::Int#, \W. case x of I# x# -> W)
140 -- where W is a CoreExpr that probably mentions x#
143 -- Primtive types: nothing to unbox
144 | isPrimitiveType arg_ty
145 = returnDs (arg, \body -> body)
147 -- Recursive newtypes
148 | Just rep_ty <- splitNewType_maybe arg_ty
149 = unboxArg (mkCoerce rep_ty arg_ty arg)
152 | Just (tc,_) <- splitTyConApp_maybe arg_ty,
153 tc `hasKey` boolTyConKey
154 = newSysLocalDs intPrimTy `thenDs` \ prim_arg ->
155 returnDs (Var prim_arg,
156 \ body -> Case (Case arg (mkWildId arg_ty)
157 [(DataAlt falseDataCon,[],mkIntLit 0),
158 (DataAlt trueDataCon, [],mkIntLit 1)])
162 -- Data types with a single constructor, which has a single, primitive-typed arg
163 -- This deals with Int, Float etc
164 | is_product_type && data_con_arity == 1
165 = ASSERT(isUnLiftedType data_con_arg_ty1 ) -- Typechecker ensures this
166 newSysLocalDs arg_ty `thenDs` \ case_bndr ->
167 newSysLocalDs data_con_arg_ty1 `thenDs` \ prim_arg ->
168 returnDs (Var prim_arg,
169 \ body -> Case arg case_bndr [(DataAlt data_con,[prim_arg],body)]
172 -- Byte-arrays, both mutable and otherwise; hack warning
173 -- We're looking for values of type ByteArray, MutableByteArray
174 -- data ByteArray ix = ByteArray ix ix ByteArray#
175 -- data MutableByteArray s ix = MutableByteArray ix ix (MutableByteArray# s)
177 data_con_arity == 3 &&
178 maybeToBool maybe_arg3_tycon &&
179 (arg3_tycon == byteArrayPrimTyCon ||
180 arg3_tycon == mutableByteArrayPrimTyCon)
181 -- and, of course, it is an instance of CCallable
182 = newSysLocalDs arg_ty `thenDs` \ case_bndr ->
183 newSysLocalsDs data_con_arg_tys `thenDs` \ vars@[l_var, r_var, arr_cts_var] ->
184 returnDs (Var arr_cts_var,
185 \ body -> Case arg case_bndr [(DataAlt data_con,vars,body)]
189 = getSrcLocDs `thenDs` \ l ->
190 pprPanic "unboxArg: " (ppr l <+> ppr arg_ty)
192 arg_ty = exprType arg
193 maybe_product_type = splitProductType_maybe arg_ty
194 is_product_type = maybeToBool maybe_product_type
195 Just (_, _, data_con, data_con_arg_tys) = maybe_product_type
196 data_con_arity = dataConSourceArity data_con
197 (data_con_arg_ty1 : _) = data_con_arg_tys
199 (_ : _ : data_con_arg_ty3 : _) = data_con_arg_tys
200 maybe_arg3_tycon = splitTyConApp_maybe data_con_arg_ty3
201 Just (arg3_tycon,_) = maybe_arg3_tycon
206 boxResult :: [Id] -> Type -> DsM (Type, CoreExpr -> CoreExpr)
208 -- Takes the result of the user-level ccall:
210 -- or maybe just t for an side-effect-free call
211 -- Returns a wrapper for the primitive ccall itself, along with the
212 -- type of the result of the primitive ccall. This result type
213 -- will be of the form
214 -- State# RealWorld -> (# State# RealWorld, t' #)
215 -- where t' is the unwrapped form of t. If t is simply (), then
216 -- the result type will be
217 -- State# RealWorld -> (# State# RealWorld #)
219 -- Here is where we arrange that ForeignPtrs which are passed to a 'safe'
220 -- foreign import don't get finalized until the call returns. For each
221 -- argument of type ForeignObj# we arrange to touch# the argument after
222 -- the call. The arg_ids passed in are the Ids passed to the actual ccall.
224 boxResult arg_ids result_ty
225 = case tcSplitTyConApp_maybe result_ty of
226 -- This split absolutely has to be a tcSplit, because we must
227 -- see the IO type; and it's a newtype which is transparent to splitTyConApp.
229 -- The result is IO t, so wrap the result in an IO constructor
230 Just (io_tycon, [io_res_ty]) | io_tycon `hasKey` ioTyConKey
231 -> mk_alt return_result
232 (resultWrapper io_res_ty) `thenDs` \ (ccall_res_ty, the_alt) ->
233 newSysLocalDs realWorldStatePrimTy `thenDs` \ state_id ->
235 io_data_con = head (tyConDataCons io_tycon)
237 mkApps (Var (dataConWrapId io_data_con))
240 Case (App the_call (Var state_id))
241 (mkWildId ccall_res_ty)
245 returnDs (realWorldStatePrimTy `mkFunTy` ccall_res_ty, wrap)
247 return_result state ans = mkConApp unboxedPairDataCon
248 [Type realWorldStatePrimTy, Type io_res_ty,
251 -- It isn't, so do unsafePerformIO
252 -- It's not conveniently available, so we inline it
253 other -> mk_alt return_result
254 (resultWrapper result_ty) `thenDs` \ (ccall_res_ty, the_alt) ->
256 wrap = \ the_call -> Case (App the_call (Var realWorldPrimId))
257 (mkWildId ccall_res_ty)
260 returnDs (realWorldStatePrimTy `mkFunTy` ccall_res_ty, wrap)
262 return_result state ans = ans
264 mk_alt return_result (Nothing, wrap_result)
265 = -- The ccall returns ()
267 rhs_fun state_id = return_result (Var state_id)
268 (wrap_result (panic "boxResult"))
270 newSysLocalDs realWorldStatePrimTy `thenDs` \ state_id ->
271 mkTouches arg_ids state_id rhs_fun `thenDs` \ the_rhs ->
273 ccall_res_ty = mkTyConApp unboxedSingletonTyCon [realWorldStatePrimTy]
274 the_alt = (DataAlt unboxedSingletonDataCon, [state_id], the_rhs)
276 returnDs (ccall_res_ty, the_alt)
278 mk_alt return_result (Just prim_res_ty, wrap_result)
279 = -- The ccall returns a non-() value
280 newSysLocalDs prim_res_ty `thenDs` \ result_id ->
282 rhs_fun state_id = return_result (Var state_id)
283 (wrap_result (Var result_id))
285 newSysLocalDs realWorldStatePrimTy `thenDs` \ state_id ->
286 mkTouches arg_ids state_id rhs_fun `thenDs` \ the_rhs ->
288 ccall_res_ty = mkTyConApp unboxedPairTyCon [realWorldStatePrimTy, prim_res_ty]
289 the_alt = (DataAlt unboxedPairDataCon, [state_id, result_id], the_rhs)
291 returnDs (ccall_res_ty, the_alt)
293 touchzh = mkPrimOpId TouchOp
295 mkTouches [] s cont = returnDs (cont s)
296 mkTouches (v:vs) s cont
297 | not (idType v `eqType` foreignObjPrimTy) = mkTouches vs s cont
298 | otherwise = newSysLocalDs realWorldStatePrimTy `thenDs` \s' ->
299 mkTouches vs s' cont `thenDs` \ rest ->
300 returnDs (Case (mkApps (Var touchzh) [Type foreignObjPrimTy,
302 [(DEFAULT, [], rest)])
304 resultWrapper :: Type
305 -> (Maybe Type, -- Type of the expected result, if any
306 CoreExpr -> CoreExpr) -- Wrapper for the result
307 resultWrapper result_ty
308 -- Base case 1: primitive types
309 | isPrimitiveType result_ty
310 = (Just result_ty, \e -> e)
312 -- Base case 2: the unit type ()
313 | Just (tc,_) <- maybe_tc_app, tc `hasKey` unitTyConKey
314 = (Nothing, \e -> Var unitDataConId)
316 -- Base case 3: the boolean type
317 | Just (tc,_) <- maybe_tc_app, tc `hasKey` boolTyConKey
318 = (Just intPrimTy, \e -> Case e (mkWildId intPrimTy)
319 [(DEFAULT ,[],Var trueDataConId ),
320 (LitAlt (mkMachInt 0),[],Var falseDataConId)])
322 -- Recursive newtypes
323 | Just rep_ty <- splitNewType_maybe result_ty
325 (maybe_ty, wrapper) = resultWrapper rep_ty
327 (maybe_ty, \e -> mkCoerce result_ty rep_ty (wrapper e))
329 -- Data types with a single constructor, which has a single arg
330 | Just (_, tycon_arg_tys, data_con, data_con_arg_tys) <- splitProductType_maybe result_ty,
331 dataConSourceArity data_con == 1
333 (maybe_ty, wrapper) = resultWrapper unwrapped_res_ty
334 (unwrapped_res_ty : _) = data_con_arg_tys
336 (maybe_ty, \e -> mkApps (Var (dataConWrapId data_con))
337 (map Type tycon_arg_tys ++ [wrapper e]))
340 = pprPanic "resultWrapper" (ppr result_ty)
342 maybe_tc_app = splitTyConApp_maybe result_ty