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