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 )
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,
34 import PrimOp ( PrimOp(TouchOp) )
35 import TysPrim ( realWorldStatePrimTy,
36 byteArrayPrimTyCon, mutableByteArrayPrimTyCon,
37 intPrimTy, foreignObjPrimTy
39 import TyCon ( tyConDataCons )
40 import TysWiredIn ( unitDataConId,
41 unboxedSingletonDataCon, unboxedPairDataCon,
42 unboxedSingletonTyCon, unboxedPairTyCon,
43 trueDataCon, falseDataCon,
44 trueDataConId, falseDataConId
46 import Literal ( mkMachInt )
47 import CStrings ( CLabelString )
48 import PrelNames ( Unique, hasKey, ioTyConKey )
49 import VarSet ( varSetElems )
53 Desugaring of @ccall@s consists of adding some state manipulation,
54 unboxing any boxed primitive arguments and boxing the result if
57 The state stuff just consists of adding in
58 @PrimIO (\ s -> case s of { S# s# -> ... })@ in an appropriate place.
60 The unboxing is straightforward, as all information needed to unbox is
61 available from the type. For each boxed-primitive argument, we
64 _ccall_ foo [ r, t1, ... tm ] e1 ... em
68 case e1 of { T1# x1# ->
70 case em of { Tm# xm# -> xm#
71 ccall# foo [ r, t1#, ... tm# ] x1# ... xm#
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
80 ccall# foo [ r, t1#, ... tm# ] e1# ... em#
84 \ s# -> case (ccall# foo [ r, t1#, ... tm# ] s# e1# ... em#) of
85 (StateAnd<r># result# state#) -> (R# result#, realWorld#)
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
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 ->
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
106 returnDs (foldr ($) (res_wrapper the_prim_app) arg_wrappers)
108 mkFCall :: Unique -> ForeignCall
109 -> [CoreExpr] -- Args
110 -> Type -- Result type
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!]
116 -- mkCCall ... [s::StablePtr (a->b), x::Addr, c::Char]
118 -- Here we build a ccall thus
119 -- (ccallid::(forall a b. StablePtr (a -> b) -> Addr -> Char -> IO Addr))
121 mkFCall uniq the_fcall val_args res_ty
122 = mkApps (mkVarApps (Var the_fcall_id) tyvars) val_args
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
132 unboxArg :: CoreExpr -- The supplied argument
133 -> DsM (CoreExpr, -- To pass as the actual argument
134 CoreExpr -> CoreExpr -- Wrapper to unbox the arg
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#
141 -- Primtive types: nothing to unbox
142 | isPrimitiveType arg_ty
143 = returnDs (arg, \body -> body)
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)])
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)]
165 -- Byte-arrays, both mutable and otherwise; hack warning
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)]
179 = getSrcLocDs `thenDs` \ l ->
180 pprPanic "unboxArg: " (ppr l <+> ppr arg_ty)
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
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
196 boxResult :: [Id] -> Type -> DsM (Type, CoreExpr -> CoreExpr)
198 -- Takes the result of the user-level ccall:
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 #)
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.
214 boxResult arg_ids result_ty
215 = case tcSplitTyConApp_maybe result_ty of
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 ->
223 io_data_con = head (tyConDataCons io_tycon)
225 mkApps (Var (dataConWrapId io_data_con))
228 Case (App the_call (Var state_id))
229 (mkWildId ccall_res_ty)
233 returnDs (realWorldStatePrimTy `mkFunTy` ccall_res_ty, wrap)
235 return_result state ans = mkConApp unboxedPairDataCon
236 [Type realWorldStatePrimTy, Type io_res_ty,
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) ->
244 wrap = \ the_call -> Case (App the_call (Var realWorldPrimId))
245 (mkWildId ccall_res_ty)
248 returnDs (realWorldStatePrimTy `mkFunTy` ccall_res_ty, wrap)
250 return_result state ans = ans
252 mk_alt return_result (Nothing, wrap_result)
253 = -- The ccall returns ()
255 rhs_fun state_id = return_result (Var state_id)
256 (wrap_result (panic "boxResult"))
258 newSysLocalDs realWorldStatePrimTy `thenDs` \ state_id ->
259 mkTouches arg_ids state_id rhs_fun `thenDs` \ the_rhs ->
261 ccall_res_ty = mkTyConApp unboxedSingletonTyCon [realWorldStatePrimTy]
262 the_alt = (DataAlt unboxedSingletonDataCon, [state_id], the_rhs)
264 returnDs (ccall_res_ty, the_alt)
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 ->
270 rhs_fun state_id = return_result (Var state_id)
271 (wrap_result (Var result_id))
273 newSysLocalDs realWorldStatePrimTy `thenDs` \ state_id ->
274 mkTouches arg_ids state_id rhs_fun `thenDs` \ the_rhs ->
276 ccall_res_ty = mkTyConApp unboxedPairTyCon [realWorldStatePrimTy, prim_res_ty]
277 the_alt = (DataAlt unboxedPairDataCon, [state_id, result_id], the_rhs)
279 returnDs (ccall_res_ty, the_alt)
281 touchzh = mkPrimOpId TouchOp
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,
290 [(DEFAULT, [], rest)])
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)
300 -- Base case 1: the unit type ()
302 = (Nothing, \e -> Var unitDataConId)
305 = (Just intPrimTy, \e -> Case e (mkWildId intPrimTy)
306 [(DEFAULT ,[],Var trueDataConId ),
307 (LitAlt (mkMachInt 0),[],Var falseDataConId)])
309 -- Data types with a single constructor, which has a single arg
310 | is_product_type && data_con_arity == 1
312 (maybe_ty, wrapper) = resultWrapper unwrapped_res_ty
313 (unwrapped_res_ty : _) = data_con_arg_tys
315 (maybe_ty, \e -> mkApps (Var (dataConWrapId data_con))
316 (map Type tycon_arg_tys ++ [wrapper e]))
319 = pprPanic "resultWrapper" (ppr result_ty)
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