2 % (c) The AQUA Project, Glasgow University, 1994-1998
4 \section[DsCCall]{Desugaring C calls}
15 #include "HsVersions.h"
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 )
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,
38 import PrimOp ( PrimOp(..) )
39 import TysPrim ( realWorldStatePrimTy, intPrimTy,
40 byteArrayPrimTyCon, mutableByteArrayPrimTyCon,
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,
52 import BasicTypes ( Boxity(..) )
53 import Literal ( mkMachInt )
54 import PrelNames ( Unique, hasKey, ioTyConKey, boolTyConKey, unitTyConKey,
55 int8TyConKey, int16TyConKey, int32TyConKey,
56 word8TyConKey, word16TyConKey, word32TyConKey
58 , marshalStringName, unmarshalStringName
59 , marshalObjectName, unmarshalObjectName
62 import VarSet ( varSetElems )
63 import Constants ( wORD_SIZE)
72 Desugaring of @ccall@s consists of adding some state manipulation,
73 unboxing any boxed primitive arguments and boxing the result if
76 The state stuff just consists of adding in
77 @PrimIO (\ s -> case s of { S# s# -> ... })@ in an appropriate place.
79 The unboxing is straightforward, as all information needed to unbox is
80 available from the type. For each boxed-primitive argument, we
83 _ccall_ foo [ r, t1, ... tm ] e1 ... em
87 case e1 of { T1# x1# ->
89 case em of { Tm# xm# -> xm#
90 ccall# foo [ r, t1#, ... tm# ] x1# ... xm#
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
99 ccall# foo [ r, t1#, ... tm# ] e1# ... em#
103 \ s# -> case (ccall# foo [ r, t1#, ... tm# ] s# e1# ... em#) of
104 (StateAnd<r># result# state#) -> (R# result#, realWorld#)
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
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 ->
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
123 returnDs (foldr ($) (res_wrapper the_prim_app) arg_wrappers)
125 mkFCall :: Unique -> ForeignCall
126 -> [CoreExpr] -- Args
127 -> Type -- Result type
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!]
133 -- mkCCall ... [s::StablePtr (a->b), x::Addr, c::Char]
135 -- Here we build a ccall thus
136 -- (ccallid::(forall a b. StablePtr (a -> b) -> Addr -> Char -> IO Addr))
138 mkFCall uniq the_fcall val_args res_ty
139 = mkApps (mkVarApps (Var the_fcall_id) tyvars) val_args
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
149 unboxArg :: CoreExpr -- The supplied argument
150 -> DsM (CoreExpr, -- To pass as the actual argument
151 CoreExpr -> CoreExpr -- Wrapper to unbox the arg
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#
158 -- Primtive types: nothing to unbox
159 | isPrimitiveType arg_ty
160 = returnDs (arg, \body -> body)
162 -- Recursive newtypes
163 | Just rep_ty <- splitRecNewType_maybe arg_ty
164 = unboxArg (mkCoerce2 rep_ty arg_ty arg)
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!
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)]
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)
195 data_con_arity == 3 &&
196 maybeToBool maybe_arg3_tycon &&
197 (arg3_tycon == byteArrayPrimTyCon ||
198 arg3_tycon == mutableByteArrayPrimTyCon)
199 -- and, of course, it is an instance of CCallable
200 = newSysLocalDs arg_ty `thenDs` \ case_bndr ->
201 newSysLocalsDs data_con_arg_tys `thenDs` \ vars@[l_var, r_var, arr_cts_var] ->
202 returnDs (Var arr_cts_var,
203 \ body -> Case arg case_bndr (exprType body) [(DataAlt data_con,vars,body)]
207 | Just (tc, [arg_ty]) <- splitTyConApp_maybe arg_ty,
209 Just (cc,[]) <- splitTyConApp_maybe arg_ty,
211 -- String; dotnet only
212 = dsLookupGlobalId marshalStringName `thenDs` \ unpack_id ->
213 newSysLocalDs addrPrimTy `thenDs` \ prim_string ->
214 returnDs (Var prim_string,
217 io_ty = exprType body
218 (Just (_,[io_arg])) = tcSplitTyConApp_maybe io_ty
220 mkApps (Var unpack_id)
223 , Lam prim_string body
225 | Just (tc, [arg_ty]) <- splitTyConApp_maybe arg_ty,
226 tyConName tc == objectTyConName
227 -- Object; dotnet only
228 = dsLookupGlobalId marshalObjectName `thenDs` \ unpack_id ->
229 newSysLocalDs addrPrimTy `thenDs` \ prim_obj ->
230 returnDs (Var prim_obj,
233 io_ty = exprType body
234 (Just (_,[io_arg])) = tcSplitTyConApp_maybe io_ty
236 mkApps (Var unpack_id)
243 = getSrcSpanDs `thenDs` \ l ->
244 pprPanic "unboxArg: " (ppr l <+> ppr arg_ty)
246 arg_ty = exprType arg
247 maybe_product_type = splitProductType_maybe arg_ty
248 is_product_type = maybeToBool maybe_product_type
249 Just (_, _, data_con, data_con_arg_tys) = maybe_product_type
250 data_con_arity = dataConSourceArity data_con
251 (data_con_arg_ty1 : _) = data_con_arg_tys
253 (_ : _ : data_con_arg_ty3 : _) = data_con_arg_tys
254 maybe_arg3_tycon = splitTyConApp_maybe data_con_arg_ty3
255 Just (arg3_tycon,_) = maybe_arg3_tycon
260 boxResult :: ((Maybe Type, CoreExpr -> CoreExpr) -> (Maybe Type, CoreExpr -> CoreExpr))
263 -> DsM (Type, CoreExpr -> CoreExpr)
265 -- Takes the result of the user-level ccall:
267 -- or maybe just t for an side-effect-free call
268 -- Returns a wrapper for the primitive ccall itself, along with the
269 -- type of the result of the primitive ccall. This result type
270 -- will be of the form
271 -- State# RealWorld -> (# State# RealWorld, t' #)
272 -- where t' is the unwrapped form of t. If t is simply (), then
273 -- the result type will be
274 -- State# RealWorld -> (# State# RealWorld #)
276 boxResult augment mbTopCon result_ty
277 = case tcSplitTyConApp_maybe result_ty of
278 -- This split absolutely has to be a tcSplit, because we must
279 -- see the IO type; and it's a newtype which is transparent to splitTyConApp.
281 -- The result is IO t, so wrap the result in an IO constructor
282 Just (io_tycon, [io_res_ty]) | io_tycon `hasKey` ioTyConKey
283 -> resultWrapper io_res_ty `thenDs` \ res ->
284 let aug_res = augment res
288 | isUnboxedTupleType ty ->
289 let (Just (_, ls)) = splitTyConApp_maybe ty in tail ls
292 mk_alt (return_result extra_result_tys) aug_res
293 `thenDs` \ (ccall_res_ty, the_alt) ->
294 newSysLocalDs realWorldStatePrimTy `thenDs` \ state_id ->
296 io_data_con = head (tyConDataCons io_tycon)
299 Nothing -> dataConWrapId io_data_con
305 Case (App the_call (Var state_id))
306 (mkWildId ccall_res_ty)
307 (coreAltType the_alt)
311 returnDs (realWorldStatePrimTy `mkFunTy` ccall_res_ty, wrap)
313 return_result ts state anss
314 = mkConApp (tupleCon Unboxed (2 + length ts))
315 (Type realWorldStatePrimTy : Type io_res_ty : map Type ts ++
317 -- It isn't, so do unsafePerformIO
318 -- It's not conveniently available, so we inline it
319 other -> resultWrapper result_ty `thenDs` \ res ->
320 mk_alt return_result (augment res) `thenDs` \ (ccall_res_ty, the_alt) ->
322 wrap = \ the_call -> Case (App the_call (Var realWorldPrimId))
323 (mkWildId ccall_res_ty)
324 (coreAltType the_alt)
327 returnDs (realWorldStatePrimTy `mkFunTy` ccall_res_ty, wrap)
329 return_result state [ans] = ans
330 return_result _ _ = panic "return_result: expected single result"
332 mk_alt return_result (Nothing, wrap_result)
333 = -- The ccall returns ()
334 newSysLocalDs realWorldStatePrimTy `thenDs` \ state_id ->
336 the_rhs = return_result (Var state_id)
337 [wrap_result (panic "boxResult")]
339 ccall_res_ty = mkTyConApp unboxedSingletonTyCon [realWorldStatePrimTy]
340 the_alt = (DataAlt unboxedSingletonDataCon, [state_id], the_rhs)
342 returnDs (ccall_res_ty, the_alt)
344 mk_alt return_result (Just prim_res_ty, wrap_result)
345 -- The ccall returns a non-() value
346 | isUnboxedTupleType prim_res_ty
348 Just (_, ls) = splitTyConApp_maybe prim_res_ty
349 arity = 1 + length ls
351 mappM newSysLocalDs ls `thenDs` \ args_ids@(result_id:as) ->
352 newSysLocalDs realWorldStatePrimTy `thenDs` \ state_id ->
354 the_rhs = return_result (Var state_id)
355 (wrap_result (Var result_id) : map Var as)
356 ccall_res_ty = mkTyConApp (tupleTyCon Unboxed arity)
357 (realWorldStatePrimTy : ls)
358 the_alt = ( DataAlt (tupleCon Unboxed arity)
359 , (state_id : args_ids)
363 returnDs (ccall_res_ty, the_alt)
365 = newSysLocalDs prim_res_ty `thenDs` \ result_id ->
366 newSysLocalDs realWorldStatePrimTy `thenDs` \ state_id ->
368 the_rhs = return_result (Var state_id)
369 [wrap_result (Var result_id)]
371 ccall_res_ty = mkTyConApp unboxedPairTyCon [realWorldStatePrimTy, prim_res_ty]
372 the_alt = (DataAlt unboxedPairDataCon, [state_id, result_id], the_rhs)
374 returnDs (ccall_res_ty, the_alt)
377 resultWrapper :: Type
378 -> DsM (Maybe Type, -- Type of the expected result, if any
379 CoreExpr -> CoreExpr) -- Wrapper for the result
380 resultWrapper result_ty
381 -- Base case 1: primitive types
382 | isPrimitiveType result_ty
383 = returnDs (Just result_ty, \e -> e)
385 -- Base case 2: the unit type ()
386 | Just (tc,_) <- maybe_tc_app, tc `hasKey` unitTyConKey
387 = returnDs (Nothing, \e -> Var unitDataConId)
389 -- Base case 3: the boolean type
390 | Just (tc,_) <- maybe_tc_app, tc `hasKey` boolTyConKey
392 (Just intPrimTy, \e -> Case e (mkWildId intPrimTy)
394 [(DEFAULT ,[],Var trueDataConId ),
395 (LitAlt (mkMachInt 0),[],Var falseDataConId)])
397 -- Recursive newtypes
398 | Just rep_ty <- splitRecNewType_maybe result_ty
399 = resultWrapper rep_ty `thenDs` \ (maybe_ty, wrapper) ->
400 returnDs (maybe_ty, \e -> mkCoerce2 result_ty rep_ty (wrapper e))
402 -- The type might contain foralls (eg. for dummy type arguments,
403 -- referring to 'Ptr a' is legal).
404 | Just (tyvar, rest) <- splitForAllTy_maybe result_ty
405 = resultWrapper rest `thenDs` \ (maybe_ty, wrapper) ->
406 returnDs (maybe_ty, \e -> Lam tyvar (wrapper e))
408 -- Data types with a single constructor, which has a single arg
409 -- This includes types like Ptr and ForeignPtr
410 | Just (tycon, tycon_arg_tys, data_con, data_con_arg_tys) <- splitProductType_maybe result_ty,
411 dataConSourceArity data_con == 1
413 (unwrapped_res_ty : _) = data_con_arg_tys
414 narrow_wrapper = maybeNarrow tycon
416 resultWrapper unwrapped_res_ty `thenDs` \ (maybe_ty, wrapper) ->
418 (maybe_ty, \e -> mkApps (Var (dataConWrapId data_con))
419 (map Type tycon_arg_tys ++ [wrapper (narrow_wrapper e)]))
421 -- Strings; 'dotnet' only.
422 | Just (tc, [arg_ty]) <- maybe_tc_app, tc == listTyCon,
423 Just (cc,[]) <- splitTyConApp_maybe arg_ty, cc == charTyCon
424 = dsLookupGlobalId unmarshalStringName `thenDs` \ pack_id ->
425 returnDs (Just addrPrimTy,
426 \ e -> App (Var pack_id) e)
428 -- Objects; 'dotnet' only.
429 | Just (tc, [arg_ty]) <- maybe_tc_app,
430 tyConName tc == objectTyConName
431 = dsLookupGlobalId unmarshalObjectName `thenDs` \ pack_id ->
432 returnDs (Just addrPrimTy,
433 \ e -> App (Var pack_id) e)
436 = pprPanic "resultWrapper" (ppr result_ty)
438 maybe_tc_app = splitTyConApp_maybe result_ty
440 -- When the result of a foreign call is smaller than the word size, we
441 -- need to sign- or zero-extend the result up to the word size. The C
442 -- standard appears to say that this is the responsibility of the
443 -- caller, not the callee.
445 maybeNarrow :: TyCon -> (CoreExpr -> CoreExpr)
447 | tycon `hasKey` int8TyConKey = \e -> App (Var (mkPrimOpId Narrow8IntOp)) e
448 | tycon `hasKey` int16TyConKey = \e -> App (Var (mkPrimOpId Narrow16IntOp)) e
449 | tycon `hasKey` int32TyConKey
450 && wORD_SIZE > 4 = \e -> App (Var (mkPrimOpId Narrow32IntOp)) e
452 | tycon `hasKey` word8TyConKey = \e -> App (Var (mkPrimOpId Narrow8WordOp)) e
453 | tycon `hasKey` word16TyConKey = \e -> App (Var (mkPrimOpId Narrow16WordOp)) e
454 | tycon `hasKey` word32TyConKey
455 && wORD_SIZE > 4 = \e -> App (Var (mkPrimOpId Narrow32WordOp)) e