2 % (c) The AQUA Project, Glasgow University, 1998
4 \section[DsCCall]{Desugaring \tr{foreign} declarations}
6 Expanding out @foreign import@ and @foreign export@ declarations.
9 module DsForeign ( dsForeigns ) where
11 #include "HsVersions.h"
12 import TcRnMonad -- temp
16 import DsCCall ( dsCCall, mkFCall, boxResult, unboxArg, resultWrapper )
19 import HsSyn ( ForeignDecl(..), ForeignExport(..), LForeignDecl,
20 ForeignImport(..), CImportSpec(..) )
21 import DataCon ( splitProductType_maybe )
23 import DataCon ( dataConSourceArity )
24 import Type ( isUnLiftedType )
26 import MachOp ( machRepByteWidth, MachRep(..) )
27 import SMRep ( argMachRep, primRepToCgRep )
28 import CoreUtils ( exprType, mkInlineMe )
29 import Id ( Id, idType, idName, mkSysLocal, setInlinePragma )
30 import Literal ( Literal(..), mkStringLit )
31 import Module ( moduleString )
32 import Name ( getOccString, NamedThing(..) )
33 import OccName ( encodeFS )
34 import Type ( repType, coreEqType, typePrimRep )
35 import TcType ( Type, mkFunTys, mkForAllTys, mkTyConApp,
36 mkFunTy, tcSplitTyConApp_maybe,
37 tcSplitForAllTys, tcSplitFunTys, tcTyConAppArgs,
40 import BasicTypes ( Boxity(..) )
41 import HscTypes ( ForeignStubs(..) )
42 import ForeignCall ( ForeignCall(..), CCallSpec(..),
44 CExportSpec(..), CLabelString,
45 CCallConv(..), ccallConvToInt,
48 import TysWiredIn ( unitTy, tupleTyCon )
49 import TysPrim ( addrPrimTy, mkStablePtrPrimTy, alphaTy )
50 import PrelNames ( hasKey, ioTyConKey, stablePtrTyConName, newStablePtrName, bindIOName,
52 import BasicTypes ( Activation( NeverActive ) )
53 import SrcLoc ( Located(..), unLoc )
55 import Maybe ( fromJust )
59 Desugaring of @foreign@ declarations is naturally split up into
60 parts, an @import@ and an @export@ part. A @foreign import@
63 foreign import cc nm f :: prim_args -> IO prim_res
67 f :: prim_args -> IO prim_res
68 f a1 ... an = _ccall_ nm cc a1 ... an
70 so we reuse the desugaring code in @DsCCall@ to deal with these.
73 type Binding = (Id, CoreExpr) -- No rec/nonrec structure;
74 -- the occurrence analyser will sort it all out
76 dsForeigns :: [LForeignDecl Id]
77 -> DsM (ForeignStubs, [Binding])
79 = returnDs (NoStubs, [])
81 = foldlDs combine (ForeignStubs empty empty [] [], []) fos
83 combine (ForeignStubs acc_h acc_c acc_hdrs acc_feb, acc_f)
84 (L loc (ForeignImport id _ spec depr))
85 = traceIf (text "fi start" <+> ppr id) `thenDs` \ _ ->
86 dsFImport (unLoc id) spec `thenDs` \ (bs, h, c, mbhd) ->
87 warnDepr depr loc `thenDs` \ _ ->
88 traceIf (text "fi end" <+> ppr id) `thenDs` \ _ ->
89 returnDs (ForeignStubs (h $$ acc_h)
95 combine (ForeignStubs acc_h acc_c acc_hdrs acc_feb, acc_f)
96 (L loc (ForeignExport (L _ id) _ (CExport (CExportStatic ext_nm cconv)) depr))
97 = dsFExport id (idType id)
98 ext_nm cconv False `thenDs` \(h, c, _) ->
99 warnDepr depr loc `thenDs` \_ ->
100 returnDs (ForeignStubs (h $$ acc_h) (c $$ acc_c) acc_hdrs (id:acc_feb),
108 warnDepr False _ = returnDs ()
109 warnDepr True loc = dsWarn (loc, msg)
111 msg = ptext SLIT("foreign declaration uses deprecated non-standard syntax")
115 %************************************************************************
117 \subsection{Foreign import}
119 %************************************************************************
121 Desugaring foreign imports is just the matter of creating a binding
122 that on its RHS unboxes its arguments, performs the external call
123 (using the @CCallOp@ primop), before boxing the result up and returning it.
125 However, we create a worker/wrapper pair, thus:
127 foreign import f :: Int -> IO Int
129 f x = IO ( \s -> case x of { I# x# ->
130 case fw s x# of { (# s1, y# #) ->
133 fw s x# = ccall f s x#
135 The strictness/CPR analyser won't do this automatically because it doesn't look
136 inside returned tuples; but inlining this wrapper is a Really Good Idea
137 because it exposes the boxing to the call site.
142 -> DsM ([Binding], SDoc, SDoc, Maybe FastString)
143 dsFImport id (CImport cconv safety header lib spec)
144 = dsCImport id spec cconv safety no_hdrs `thenDs` \(ids, h, c) ->
145 returnDs (ids, h, c, if no_hdrs then Nothing else Just header)
147 no_hdrs = nullFastString header
149 -- FIXME: the `lib' field is needed for .NET ILX generation when invoking
150 -- routines that are external to the .NET runtime, but GHC doesn't
151 -- support such calls yet; if `nullFastString lib', the value was not given
152 dsFImport id (DNImport spec)
153 = dsFCall id (DNCall spec) True {- No headers -} `thenDs` \(ids, h, c) ->
154 returnDs (ids, h, c, Nothing)
160 -> Bool -- True <=> no headers in the f.i decl
161 -> DsM ([Binding], SDoc, SDoc)
162 dsCImport id (CLabel cid) _ _ no_hdrs
163 = resultWrapper (idType id) `thenDs` \ (resTy, foRhs) ->
164 ASSERT(fromJust resTy `coreEqType` addrPrimTy) -- typechecker ensures this
165 let rhs = foRhs (mkLit (MachLabel cid Nothing)) in
166 returnDs ([(setImpInline no_hdrs id, rhs)], empty, empty)
167 dsCImport id (CFunction target) cconv safety no_hdrs
168 = dsFCall id (CCall (CCallSpec target cconv safety)) no_hdrs
169 dsCImport id CWrapper cconv _ _
170 = dsFExportDynamic id cconv
172 setImpInline :: Bool -- True <=> No #include headers
173 -- in the foreign import declaration
175 -- If there is a #include header in the foreign import
176 -- we make the worker non-inlinable, because we currently
177 -- don't keep the #include stuff in the CCallId, and hence
178 -- it won't be visible in the importing module, which can be
180 -- (The #include stuff is just collected from the foreign import
181 -- decls in a module.)
182 -- If you want to do cross-module inlining of the c-calls themselves,
183 -- put the #include stuff in the package spec, not the foreign
185 setImpInline True id = id
186 setImpInline False id = id `setInlinePragma` NeverActive
190 %************************************************************************
192 \subsection{Foreign calls}
194 %************************************************************************
197 dsFCall fn_id fcall no_hdrs
200 (tvs, fun_ty) = tcSplitForAllTys ty
201 (arg_tys, io_res_ty) = tcSplitFunTys fun_ty
202 -- Must use tcSplit* functions because we want to
203 -- see that (IO t) in the corner
205 newSysLocalsDs arg_tys `thenDs` \ args ->
206 mapAndUnzipDs unboxArg (map Var args) `thenDs` \ (val_args, arg_wrappers) ->
209 work_arg_ids = [v | Var v <- val_args] -- All guaranteed to be vars
211 -- These are the ids we pass to boxResult, which are used to decide
212 -- whether to touch# an argument after the call (used to keep
213 -- ForeignObj#s live across a 'safe' foreign import).
214 maybe_arg_ids | unsafe_call fcall = work_arg_ids
224 dsLookupGlobalId checkDotnetResName `thenDs` \ check_id ->
225 return (Just check_id)
226 | otherwise = return Nothing
230 newSysLocalDs addrPrimTy `thenDs` \ err_res ->
231 returnDs (\ (mb_res_ty, resWrap) ->
233 Nothing -> (Just (mkTyConApp (tupleTyCon Unboxed 1)
236 Just x -> (Just (mkTyConApp (tupleTyCon Unboxed 2)
239 | otherwise = returnDs id
241 augmentResultDs `thenDs` \ augment ->
242 topConDs `thenDs` \ topCon ->
243 boxResult maybe_arg_ids augment topCon io_res_ty `thenDs` \ (ccall_result_ty, res_wrapper) ->
245 newUnique `thenDs` \ ccall_uniq ->
246 newUnique `thenDs` \ work_uniq ->
249 worker_ty = mkForAllTys tvs (mkFunTys (map idType work_arg_ids) ccall_result_ty)
250 the_ccall_app = mkFCall ccall_uniq fcall val_args ccall_result_ty
251 work_rhs = mkLams tvs (mkLams work_arg_ids the_ccall_app)
252 work_id = setImpInline no_hdrs $ -- See comments with setImpInline
253 mkSysLocal (encodeFS FSLIT("$wccall")) work_uniq worker_ty
256 work_app = mkApps (mkVarApps (Var work_id) tvs) val_args
257 wrapper_body = foldr ($) (res_wrapper work_app) arg_wrappers
258 wrap_rhs = mkInlineMe (mkLams (tvs ++ args) wrapper_body)
260 returnDs ([(work_id, work_rhs), (fn_id, wrap_rhs)], empty, empty)
262 unsafe_call (CCall (CCallSpec _ _ safety)) = playSafe safety
263 unsafe_call (DNCall _) = False
267 %************************************************************************
269 \subsection{Foreign export}
271 %************************************************************************
273 The function that does most of the work for `@foreign export@' declarations.
274 (see below for the boilerplate code a `@foreign export@' declaration expands
277 For each `@foreign export foo@' in a module M we generate:
279 \item a C function `@foo@', which calls
280 \item a Haskell stub `@M.$ffoo@', which calls
282 the user-written Haskell function `@M.foo@'.
285 dsFExport :: Id -- Either the exported Id,
286 -- or the foreign-export-dynamic constructor
287 -> Type -- The type of the thing callable from C
288 -> CLabelString -- The name to export to C land
290 -> Bool -- True => foreign export dynamic
291 -- so invoke IO action that's hanging off
292 -- the first argument's stable pointer
293 -> DsM ( SDoc -- contents of Module_stub.h
294 , SDoc -- contents of Module_stub.c
295 , [Type] -- primitive arguments expected by stub function.
298 dsFExport fn_id ty ext_name cconv isDyn
301 (_tvs,sans_foralls) = tcSplitForAllTys ty
302 (fe_arg_tys', orig_res_ty) = tcSplitFunTys sans_foralls
303 -- We must use tcSplits here, because we want to see
304 -- the (IO t) in the corner of the type!
305 fe_arg_tys | isDyn = tail fe_arg_tys'
306 | otherwise = fe_arg_tys'
308 -- Look at the result type of the exported function, orig_res_ty
309 -- If it's IO t, return (t, True)
310 -- If it's plain t, return (t, False)
311 (case tcSplitTyConApp_maybe orig_res_ty of
312 -- We must use tcSplit here so that we see the (IO t) in
313 -- the type. [IO t is transparent to plain splitTyConApp.]
315 Just (ioTyCon, [res_ty])
316 -> ASSERT( ioTyCon `hasKey` ioTyConKey )
317 -- The function already returns IO t
318 returnDs (res_ty, True)
320 other -> -- The function returns t
321 returnDs (orig_res_ty, False)
323 `thenDs` \ (res_ty, -- t
324 is_IO_res_ty) -> -- Bool
326 mkFExportCBits ext_name
327 (if isDyn then Nothing else Just fn_id)
328 fe_arg_tys res_ty is_IO_res_ty cconv
331 @foreign export dynamic@ lets you dress up Haskell IO actions
332 of some fixed type behind an externally callable interface (i.e.,
333 as a C function pointer). Useful for callbacks and stuff.
336 foreign export dynamic f :: (Addr -> Int -> IO Int) -> IO Addr
338 -- Haskell-visible constructor, which is generated from the above:
339 -- SUP: No check for NULL from createAdjustor anymore???
341 f :: (Addr -> Int -> IO Int) -> IO Addr
343 bindIO (newStablePtr cback)
344 (\StablePtr sp# -> IO (\s1# ->
345 case _ccall_ createAdjustor cconv sp# ``f_helper'' s1# of
346 (# s2#, a# #) -> (# s2#, A# a# #)))
348 foreign export "f_helper" f_helper :: StablePtr (Addr -> Int -> IO Int) -> Addr -> Int -> IO Int
349 -- `special' foreign export that invokes the closure pointed to by the
354 dsFExportDynamic :: Id
356 -> DsM ([Binding], SDoc, SDoc)
357 dsFExportDynamic id cconv
358 = newSysLocalDs ty `thenDs` \ fe_id ->
359 getModuleDs `thenDs` \ mod_name ->
361 -- hack: need to get at the name of the C stub we're about to generate.
362 fe_nm = mkFastString (moduleString mod_name ++ "_" ++ toCName fe_id)
364 newSysLocalDs arg_ty `thenDs` \ cback ->
365 dsLookupGlobalId newStablePtrName `thenDs` \ newStablePtrId ->
366 dsLookupTyCon stablePtrTyConName `thenDs` \ stable_ptr_tycon ->
368 mk_stbl_ptr_app = mkApps (Var newStablePtrId) [ Type arg_ty, Var cback ]
369 stable_ptr_ty = mkTyConApp stable_ptr_tycon [arg_ty]
370 export_ty = mkFunTy stable_ptr_ty arg_ty
372 dsLookupGlobalId bindIOName `thenDs` \ bindIOId ->
373 newSysLocalDs stable_ptr_ty `thenDs` \ stbl_value ->
374 dsFExport id export_ty fe_nm cconv True `thenDs` \ (h_code, c_code, stub_args) ->
376 stbl_app cont ret_ty = mkApps (Var bindIOId)
383 The arguments to the external function which will
384 create a little bit of (template) code on the fly
385 for allowing the (stable pointed) Haskell closure
386 to be entered using an external calling convention
389 adj_args = [ mkIntLitInt (ccallConvToInt cconv)
391 , mkLit (MachLabel fe_nm mb_sz_args)
392 , mkLit (mkStringLit arg_type_info)
394 -- name of external entry point providing these services.
395 -- (probably in the RTS.)
396 adjustor = FSLIT("createAdjustor")
398 arg_type_info = drop 2 $ map (repCharCode.argMachRep
399 .primRepToCgRep.typePrimRep)
401 repCharCode F32 = 'f'
402 repCharCode F64 = 'd'
403 repCharCode I64 = 'l'
406 -- Determine the number of bytes of arguments to the stub function,
407 -- so that we can attach the '@N' suffix to its label if it is a
408 -- stdcall on Windows.
409 mb_sz_args = case cconv of
410 StdCallConv -> Just (sum (map ty_size stub_args))
413 -- NB. the calculation here isn't strictly speaking correct.
414 -- We have a primitive Haskell type (eg. Int#, Double#), and
415 -- we want to know the size, when passed on the C stack, of
416 -- the associated C type (eg. HsInt, HsDouble). We don't have
417 -- this information to hand, but we know what GHC's conventions
418 -- are for passing around the primitive Haskell types, so we
419 -- use that instead. I hope the two coincide --SDM
420 ty_size = machRepByteWidth.argMachRep.primRepToCgRep.typePrimRep
422 dsCCall adjustor adj_args PlayRisky io_res_ty `thenDs` \ ccall_adj ->
423 -- PlayRisky: the adjustor doesn't allocate in the Haskell heap or do a callback
424 let ccall_adj_ty = exprType ccall_adj
425 ccall_io_adj = mkLams [stbl_value] $
426 Note (Coerce io_res_ty ccall_adj_ty)
428 io_app = mkLams tvs $
430 stbl_app ccall_io_adj res_ty
431 fed = (id `setInlinePragma` NeverActive, io_app)
432 -- Never inline the f.e.d. function, because the litlit
433 -- might not be in scope in other modules.
435 returnDs ([fed], h_code, c_code)
439 (tvs,sans_foralls) = tcSplitForAllTys ty
440 ([arg_ty], io_res_ty) = tcSplitFunTys sans_foralls
441 [res_ty] = tcTyConAppArgs io_res_ty
442 -- Must use tcSplit* to see the (IO t), which is a newtype
444 toCName :: Id -> String
445 toCName i = showSDoc (pprCode CStyle (ppr (idName i)))
450 \subsection{Generating @foreign export@ stubs}
454 For each @foreign export@ function, a C stub function is generated.
455 The C stub constructs the application of the exported Haskell function
456 using the hugs/ghc rts invocation API.
459 mkFExportCBits :: FastString
460 -> Maybe Id -- Just==static, Nothing==dynamic
463 -> Bool -- True <=> returns an IO type
467 [Type] -- the *primitive* argument types
469 mkFExportCBits c_nm maybe_target arg_htys res_hty is_IO_res_ty cc
470 = (header_bits, c_bits, all_prim_arg_tys)
472 -- Create up types and names for the real args
473 arg_cnames, arg_ctys :: [SDoc]
474 arg_cnames = mkCArgNames 1 arg_htys
475 arg_ctys = map showStgType arg_htys
477 -- and also for auxiliary ones; the stable ptr in the dynamic case, and
478 -- a slot for the dummy return address in the dynamic + ccall case
480 = case maybe_target of
481 Nothing -> [((text "the_stableptr", text "StgStablePtr"), mkStablePtrPrimTy alphaTy)]
484 case (maybe_target, cc) of
485 (Nothing, CCallConv) -> [((text "original_return_addr", text "void*"), addrPrimTy)]
488 all_cnames_and_ctys :: [(SDoc, SDoc)]
490 = map fst extra_cnames_and_tys ++ zip arg_cnames arg_ctys
493 = map snd extra_cnames_and_tys ++ map getPrimTyOf arg_htys
495 -- stuff to do with the return type of the C function
496 res_hty_is_unit = res_hty `coreEqType` unitTy -- Look through any newtypes
498 cResType | res_hty_is_unit = text "void"
499 | otherwise = showStgType res_hty
501 -- Now we can cook up the prototype for the exported function.
502 pprCconv = case cc of
504 StdCallConv -> text (ccallConvAttribute cc)
506 header_bits = ptext SLIT("extern") <+> fun_proto <> semi
508 fun_proto = cResType <+> pprCconv <+> ftext c_nm <>
509 parens (hsep (punctuate comma (map (\(nm,ty) -> ty <+> nm)
510 all_cnames_and_ctys)))
512 -- the target which will form the root of what we ask rts_evalIO to run
514 = case maybe_target of
515 Nothing -> text "(StgClosure*)deRefStablePtr(the_stableptr)"
516 Just hs_fn -> char '&' <> ppr hs_fn <> text "_closure"
518 -- the expression we give to rts_evalIO
520 = foldl appArg the_cfun (zip arg_cnames arg_htys)
522 appArg acc (arg_cname, arg_hty)
524 <> parens (acc <> comma <> mkHObj arg_hty <> parens arg_cname)
526 -- various other bits for inside the fn
527 declareResult = text "HaskellObj ret;"
528 declareCResult | res_hty_is_unit = empty
529 | otherwise = cResType <+> text "cret;"
531 assignCResult | res_hty_is_unit = empty
533 text "cret=" <> unpackHObj res_hty <> parens (text "ret") <> semi
535 -- an extern decl for the fn being called
537 = case maybe_target of
539 Just hs_fn -> text "extern StgClosure " <> ppr hs_fn <> text "_closure" <> semi
541 -- finally, the whole darn thing
548 , text "SchedulerStatus rc;"
552 -- create the application + perform it.
553 , text "rc=rts_evalIO" <> parens (
554 text "rts_apply" <> parens (
556 <> text (if is_IO_res_ty
558 else "runNonIO_closure")
564 , text "rts_checkSchedStatus" <> parens (doubleQuotes (ftext c_nm)
565 <> comma <> text "rc") <> semi
567 , text "rts_unlock();"
568 , if res_hty_is_unit then empty
569 else text "return cret;"
574 mkCArgNames :: Int -> [a] -> [SDoc]
575 mkCArgNames n as = zipWith (\ _ n -> text ('a':show n)) as [n..]
577 mkHObj :: Type -> SDoc
578 mkHObj t = text "rts_mk" <> text (showFFIType t)
580 unpackHObj :: Type -> SDoc
581 unpackHObj t = text "rts_get" <> text (showFFIType t)
583 showStgType :: Type -> SDoc
584 showStgType t = text "Hs" <> text (showFFIType t)
586 showFFIType :: Type -> String
587 showFFIType t = getOccString (getName tc)
589 tc = case tcSplitTyConApp_maybe (repType t) of
591 Nothing -> pprPanic "showFFIType" (ppr t)
593 -- This function returns the primitive type associated with the boxed
594 -- type argument to a foreign export (eg. Int ==> Int#). It assumes
595 -- that all the types we are interested in have a single constructor
596 -- with a single primitive-typed argument, which is true for all of the legal
597 -- foreign export argument types (see TcType.legalFEArgTyCon).
598 getPrimTyOf :: Type -> Type
600 case splitProductType_maybe (repType ty) of
601 Just (_, _, data_con, [prim_ty]) ->
602 ASSERT(dataConSourceArity data_con == 1)
603 ASSERT2(isUnLiftedType prim_ty, ppr prim_ty)
605 _other -> pprPanic "DsForeign.getPrimTyOf" (ppr ty)