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 )
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, splitTyConApp_maybe, splitNewType_maybe
35 import PrimOp ( PrimOp(..) )
36 import TysPrim ( realWorldStatePrimTy, intPrimTy,
37 byteArrayPrimTyCon, mutableByteArrayPrimTyCon
39 import TyCon ( 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, boolTyConKey, unitTyConKey,
49 int8TyConKey, int16TyConKey, int32TyConKey,
50 word8TyConKey, word16TyConKey, word32TyConKey
52 import VarSet ( varSetElems )
53 import Constants ( wORD_SIZE)
57 Desugaring of @ccall@s consists of adding some state manipulation,
58 unboxing any boxed primitive arguments and boxing the result if
61 The state stuff just consists of adding in
62 @PrimIO (\ s -> case s of { S# s# -> ... })@ in an appropriate place.
64 The unboxing is straightforward, as all information needed to unbox is
65 available from the type. For each boxed-primitive argument, we
68 _ccall_ foo [ r, t1, ... tm ] e1 ... em
72 case e1 of { T1# x1# ->
74 case em of { Tm# xm# -> xm#
75 ccall# foo [ r, t1#, ... tm# ] x1# ... xm#
79 The reboxing of a @_ccall_@ result is a bit tricker: the types don't
80 contain information about the state-pairing functions so we have to
81 keep a list of \tr{(type, s-p-function)} pairs. We transform as
84 ccall# foo [ r, t1#, ... tm# ] e1# ... em#
88 \ s# -> case (ccall# foo [ r, t1#, ... tm# ] s# e1# ... em#) of
89 (StateAnd<r># result# state#) -> (R# result#, realWorld#)
93 dsCCall :: CLabelString -- C routine to invoke
94 -> [CoreExpr] -- Arguments (desugared)
95 -> Safety -- Safety of the call
96 -> Bool -- True <=> really a "_casm_"
97 -> Type -- Type of the result: IO t
100 dsCCall lbl args may_gc is_asm result_ty
101 = mapAndUnzipDs unboxArg args `thenDs` \ (unboxed_args, arg_wrappers) ->
102 boxResult [] result_ty `thenDs` \ (ccall_result_ty, res_wrapper) ->
103 getUniqueDs `thenDs` \ uniq ->
105 target | is_asm = CasmTarget lbl
106 | otherwise = StaticTarget lbl
107 the_fcall = CCall (CCallSpec target CCallConv may_gc)
108 the_prim_app = mkFCall uniq the_fcall unboxed_args ccall_result_ty
110 returnDs (foldr ($) (res_wrapper the_prim_app) arg_wrappers)
112 mkFCall :: Unique -> ForeignCall
113 -> [CoreExpr] -- Args
114 -> Type -- Result type
116 -- Construct the ccall. The only tricky bit is that the ccall Id should have
117 -- no free vars, so if any of the arg tys do we must give it a polymorphic type.
118 -- [I forget *why* it should have no free vars!]
120 -- mkCCall ... [s::StablePtr (a->b), x::Addr, c::Char]
122 -- Here we build a ccall thus
123 -- (ccallid::(forall a b. StablePtr (a -> b) -> Addr -> Char -> IO Addr))
125 mkFCall uniq the_fcall val_args res_ty
126 = mkApps (mkVarApps (Var the_fcall_id) tyvars) val_args
128 arg_tys = map exprType val_args
129 body_ty = (mkFunTys arg_tys res_ty)
130 tyvars = varSetElems (tyVarsOfType body_ty)
131 ty = mkForAllTys tyvars body_ty
132 the_fcall_id = mkFCallId uniq the_fcall ty
136 unboxArg :: CoreExpr -- The supplied argument
137 -> DsM (CoreExpr, -- To pass as the actual argument
138 CoreExpr -> CoreExpr -- Wrapper to unbox the arg
140 -- Example: if the arg is e::Int, unboxArg will return
141 -- (x#::Int#, \W. case x of I# x# -> W)
142 -- where W is a CoreExpr that probably mentions x#
145 -- Primtive types: nothing to unbox
146 | isPrimitiveType arg_ty
147 = returnDs (arg, \body -> body)
149 -- Recursive newtypes
150 | Just rep_ty <- splitNewType_maybe arg_ty
151 = unboxArg (mkCoerce2 rep_ty arg_ty arg)
154 | Just (tc,_) <- splitTyConApp_maybe arg_ty,
155 tc `hasKey` boolTyConKey
156 = newSysLocalDs intPrimTy `thenDs` \ prim_arg ->
157 returnDs (Var prim_arg,
158 \ body -> Case (Case arg (mkWildId arg_ty)
159 [(DataAlt falseDataCon,[],mkIntLit 0),
160 (DataAlt trueDataCon, [],mkIntLit 1)])
164 -- Data types with a single constructor, which has a single, primitive-typed arg
165 -- This deals with Int, Float etc
166 | is_product_type && data_con_arity == 1
167 = ASSERT(isUnLiftedType data_con_arg_ty1 ) -- Typechecker ensures this
168 newSysLocalDs arg_ty `thenDs` \ case_bndr ->
169 newSysLocalDs data_con_arg_ty1 `thenDs` \ prim_arg ->
170 returnDs (Var prim_arg,
171 \ body -> Case arg case_bndr [(DataAlt data_con,[prim_arg],body)]
174 -- Byte-arrays, both mutable and otherwise; hack warning
175 -- We're looking for values of type ByteArray, MutableByteArray
176 -- data ByteArray ix = ByteArray ix ix ByteArray#
177 -- data MutableByteArray s ix = MutableByteArray ix ix (MutableByteArray# s)
179 data_con_arity == 3 &&
180 maybeToBool maybe_arg3_tycon &&
181 (arg3_tycon == byteArrayPrimTyCon ||
182 arg3_tycon == mutableByteArrayPrimTyCon)
183 -- and, of course, it is an instance of CCallable
184 = newSysLocalDs arg_ty `thenDs` \ case_bndr ->
185 newSysLocalsDs data_con_arg_tys `thenDs` \ vars@[l_var, r_var, arr_cts_var] ->
186 returnDs (Var arr_cts_var,
187 \ body -> Case arg case_bndr [(DataAlt data_con,vars,body)]
191 = getSrcLocDs `thenDs` \ l ->
192 pprPanic "unboxArg: " (ppr l <+> ppr arg_ty)
194 arg_ty = exprType arg
195 maybe_product_type = splitProductType_maybe arg_ty
196 is_product_type = maybeToBool maybe_product_type
197 Just (_, _, data_con, data_con_arg_tys) = maybe_product_type
198 data_con_arity = dataConSourceArity data_con
199 (data_con_arg_ty1 : _) = data_con_arg_tys
201 (_ : _ : data_con_arg_ty3 : _) = data_con_arg_tys
202 maybe_arg3_tycon = splitTyConApp_maybe data_con_arg_ty3
203 Just (arg3_tycon,_) = maybe_arg3_tycon
208 boxResult :: [Id] -> Type -> DsM (Type, CoreExpr -> CoreExpr)
210 -- Takes the result of the user-level ccall:
212 -- or maybe just t for an side-effect-free call
213 -- Returns a wrapper for the primitive ccall itself, along with the
214 -- type of the result of the primitive ccall. This result type
215 -- will be of the form
216 -- State# RealWorld -> (# State# RealWorld, t' #)
217 -- where t' is the unwrapped form of t. If t is simply (), then
218 -- the result type will be
219 -- State# RealWorld -> (# State# RealWorld #)
221 boxResult arg_ids result_ty
222 = case tcSplitTyConApp_maybe result_ty of
223 -- This split absolutely has to be a tcSplit, because we must
224 -- see the IO type; and it's a newtype which is transparent to splitTyConApp.
226 -- The result is IO t, so wrap the result in an IO constructor
227 Just (io_tycon, [io_res_ty]) | io_tycon `hasKey` ioTyConKey
228 -> mk_alt return_result
229 (resultWrapper io_res_ty) `thenDs` \ (ccall_res_ty, the_alt) ->
230 newSysLocalDs realWorldStatePrimTy `thenDs` \ state_id ->
232 io_data_con = head (tyConDataCons io_tycon)
234 mkApps (Var (dataConWrapId io_data_con))
237 Case (App the_call (Var state_id))
238 (mkWildId ccall_res_ty)
242 returnDs (realWorldStatePrimTy `mkFunTy` ccall_res_ty, wrap)
244 return_result state ans = mkConApp unboxedPairDataCon
245 [Type realWorldStatePrimTy, Type io_res_ty,
248 -- It isn't, so do unsafePerformIO
249 -- It's not conveniently available, so we inline it
250 other -> mk_alt return_result
251 (resultWrapper result_ty) `thenDs` \ (ccall_res_ty, the_alt) ->
253 wrap = \ the_call -> Case (App the_call (Var realWorldPrimId))
254 (mkWildId ccall_res_ty)
257 returnDs (realWorldStatePrimTy `mkFunTy` ccall_res_ty, wrap)
259 return_result state ans = ans
261 mk_alt return_result (Nothing, wrap_result)
262 = -- The ccall returns ()
263 newSysLocalDs realWorldStatePrimTy `thenDs` \ state_id ->
265 the_rhs = return_result (Var state_id)
266 (wrap_result (panic "boxResult"))
268 ccall_res_ty = mkTyConApp unboxedSingletonTyCon [realWorldStatePrimTy]
269 the_alt = (DataAlt unboxedSingletonDataCon, [state_id], the_rhs)
271 returnDs (ccall_res_ty, the_alt)
273 mk_alt return_result (Just prim_res_ty, wrap_result)
274 = -- The ccall returns a non-() value
275 newSysLocalDs prim_res_ty `thenDs` \ result_id ->
276 newSysLocalDs realWorldStatePrimTy `thenDs` \ state_id ->
278 the_rhs = return_result (Var state_id)
279 (wrap_result (Var result_id))
281 ccall_res_ty = mkTyConApp unboxedPairTyCon [realWorldStatePrimTy, prim_res_ty]
282 the_alt = (DataAlt unboxedPairDataCon, [state_id, result_id], the_rhs)
284 returnDs (ccall_res_ty, the_alt)
287 resultWrapper :: Type
288 -> (Maybe Type, -- Type of the expected result, if any
289 CoreExpr -> CoreExpr) -- Wrapper for the result
290 resultWrapper result_ty
291 -- Base case 1: primitive types
292 | isPrimitiveType result_ty
293 = (Just result_ty, \e -> e)
295 -- Base case 2: the unit type ()
296 | Just (tc,_) <- maybe_tc_app, tc `hasKey` unitTyConKey
297 = (Nothing, \e -> Var unitDataConId)
299 -- Base case 3: the boolean type
300 | Just (tc,_) <- maybe_tc_app, tc `hasKey` boolTyConKey
301 = (Just intPrimTy, \e -> Case e (mkWildId intPrimTy)
302 [(DEFAULT ,[],Var trueDataConId ),
303 (LitAlt (mkMachInt 0),[],Var falseDataConId)])
305 -- Recursive newtypes
306 | Just rep_ty <- splitNewType_maybe result_ty
308 (maybe_ty, wrapper) = resultWrapper rep_ty
310 (maybe_ty, \e -> mkCoerce2 result_ty rep_ty (wrapper e))
312 -- Data types with a single constructor, which has a single arg
313 | Just (tycon, tycon_arg_tys, data_con, data_con_arg_tys) <- splitProductType_maybe result_ty,
314 dataConSourceArity data_con == 1
316 (maybe_ty, wrapper) = resultWrapper unwrapped_res_ty
317 (unwrapped_res_ty : _) = data_con_arg_tys
318 narrow_wrapper = maybeNarrow tycon
320 (maybe_ty, \e -> mkApps (Var (dataConWrapId data_con))
321 (map Type tycon_arg_tys ++ [wrapper (narrow_wrapper e)]))
324 = pprPanic "resultWrapper" (ppr result_ty)
326 maybe_tc_app = splitTyConApp_maybe result_ty
328 -- When the result of a foreign call is smaller than the word size, we
329 -- need to sign- or zero-extend the result up to the word size. The C
330 -- standard appears to say that this is the responsibility of the
331 -- caller, not the callee.
333 maybeNarrow :: TyCon -> (CoreExpr -> CoreExpr)
335 | tycon `hasKey` int8TyConKey = \e -> App (Var (mkPrimOpId Narrow8IntOp)) e
336 | tycon `hasKey` int16TyConKey = \e -> App (Var (mkPrimOpId Narrow16IntOp)) e
337 | tycon `hasKey` int32TyConKey
338 && wORD_SIZE > 4 = \e -> App (Var (mkPrimOpId Narrow32IntOp)) e
340 | tycon `hasKey` word8TyConKey = \e -> App (Var (mkPrimOpId Narrow8WordOp)) e
341 | tycon `hasKey` word16TyConKey = \e -> App (Var (mkPrimOpId Narrow16WordOp)) e
342 | tycon `hasKey` word32TyConKey
343 && wORD_SIZE > 4 = \e -> App (Var (mkPrimOpId Narrow32WordOp)) e