2 % (c) The University of Glasgow 2006
3 % (c) The AQUA Project, Glasgow University, 1998
6 Desugaring foreign declarations (see also DsCCall).
9 module DsForeign ( dsForeigns ) where
11 #include "HsVersions.h"
12 import TcRnMonad -- temp
51 Desugaring of @foreign@ declarations is naturally split up into
52 parts, an @import@ and an @export@ part. A @foreign import@
55 foreign import cc nm f :: prim_args -> IO prim_res
59 f :: prim_args -> IO prim_res
60 f a1 ... an = _ccall_ nm cc a1 ... an
62 so we reuse the desugaring code in @DsCCall@ to deal with these.
65 type Binding = (Id, CoreExpr) -- No rec/nonrec structure;
66 -- the occurrence analyser will sort it all out
68 dsForeigns :: [LForeignDecl Id]
69 -> DsM (ForeignStubs, [Binding])
71 = return (NoStubs, [])
73 fives <- mapM do_ldecl fos
75 (hs, cs, idss, bindss) = unzip4 fives
77 fe_init_code = map foreignExportInitialiser fe_ids
81 (vcat cs $$ vcat fe_init_code),
84 do_ldecl (L loc decl) = putSrcSpanDs loc (do_decl decl)
86 do_decl (ForeignImport id _ spec) = do
87 traceIf (text "fi start" <+> ppr id)
88 (bs, h, c) <- dsFImport (unLoc id) spec
89 traceIf (text "fi end" <+> ppr id)
92 do_decl (ForeignExport (L _ id) _ (CExport (CExportStatic ext_nm cconv))) = do
93 (h, c, _, _) <- dsFExport id (idType id) ext_nm cconv False
94 return (h, c, [id], [])
96 do_decl d = pprPanic "dsForeigns/do_decl" (ppr d)
100 %************************************************************************
102 \subsection{Foreign import}
104 %************************************************************************
106 Desugaring foreign imports is just the matter of creating a binding
107 that on its RHS unboxes its arguments, performs the external call
108 (using the @CCallOp@ primop), before boxing the result up and returning it.
110 However, we create a worker/wrapper pair, thus:
112 foreign import f :: Int -> IO Int
114 f x = IO ( \s -> case x of { I# x# ->
115 case fw s x# of { (# s1, y# #) ->
118 fw s x# = ccall f s x#
120 The strictness/CPR analyser won't do this automatically because it doesn't look
121 inside returned tuples; but inlining this wrapper is a Really Good Idea
122 because it exposes the boxing to the call site.
127 -> DsM ([Binding], SDoc, SDoc)
128 dsFImport id (CImport cconv safety _ _ spec) = do
129 (ids, h, c) <- dsCImport id spec cconv safety
132 -- FIXME: the `lib' field is needed for .NET ILX generation when invoking
133 -- routines that are external to the .NET runtime, but GHC doesn't
134 -- support such calls yet; if `nullFastString lib', the value was not given
135 dsFImport id (DNImport spec) = do
136 (ids, h, c) <- dsFCall id (DNCall spec)
143 -> DsM ([Binding], SDoc, SDoc)
144 dsCImport id (CLabel cid) cconv _ = do
146 (resTy, foRhs) <- resultWrapper ty
147 ASSERT(fromJust resTy `coreEqType` addrPrimTy) -- typechecker ensures this
149 rhs = foRhs (Lit (MachLabel cid stdcall_info))
150 stdcall_info = fun_type_arg_stdcall_info cconv ty
152 return ([(id, rhs)], empty, empty)
154 dsCImport id (CFunction target) cconv safety
155 = dsFCall id (CCall (CCallSpec target cconv safety))
156 dsCImport id CWrapper cconv _
157 = dsFExportDynamic id cconv
159 -- For stdcall labels, if the type was a FunPtr or newtype thereof,
160 -- then we need to calculate the size of the arguments in order to add
161 -- the @n suffix to the label.
162 fun_type_arg_stdcall_info :: CCallConv -> Type -> Maybe Int
163 fun_type_arg_stdcall_info StdCallConv ty
164 | Just (tc,[arg_ty]) <- splitTyConApp_maybe (repType ty),
165 tyConUnique tc == funPtrTyConKey
167 (_tvs,sans_foralls) = tcSplitForAllTys arg_ty
168 (fe_arg_tys, _orig_res_ty) = tcSplitFunTys sans_foralls
169 in Just $ sum (map (widthInBytes . typeWidth . typeCmmType . getPrimTyOf) fe_arg_tys)
170 fun_type_arg_stdcall_info _other_conv _
175 %************************************************************************
177 \subsection{Foreign calls}
179 %************************************************************************
182 dsFCall :: Id -> ForeignCall -> DsM ([(Id, Expr TyVar)], SDoc, SDoc)
183 dsFCall fn_id fcall = do
186 (tvs, fun_ty) = tcSplitForAllTys ty
187 (arg_tys, io_res_ty) = tcSplitFunTys fun_ty
188 -- Must use tcSplit* functions because we want to
189 -- see that (IO t) in the corner
191 args <- newSysLocalsDs arg_tys
192 (val_args, arg_wrappers) <- mapAndUnzipM unboxArg (map Var args)
195 work_arg_ids = [v | Var v <- val_args] -- All guaranteed to be vars
203 | forDotnet = Just <$> dsLookupGlobalId checkDotnetResName
204 | otherwise = return Nothing
208 return (\ (mb_res_ty, resWrap) ->
210 Nothing -> (Just (mkTyConApp (tupleTyCon Unboxed 1)
213 Just x -> (Just (mkTyConApp (tupleTyCon Unboxed 2)
216 | otherwise = return id
218 augment <- augmentResultDs
220 (ccall_result_ty, res_wrapper) <- boxResult augment topCon io_res_ty
222 ccall_uniq <- newUnique
223 work_uniq <- newUnique
226 worker_ty = mkForAllTys tvs (mkFunTys (map idType work_arg_ids) ccall_result_ty)
227 the_ccall_app = mkFCall ccall_uniq fcall val_args ccall_result_ty
228 work_rhs = mkLams tvs (mkLams work_arg_ids the_ccall_app)
229 work_id = mkSysLocal (fsLit "$wccall") work_uniq worker_ty
232 work_app = mkApps (mkVarApps (Var work_id) tvs) val_args
233 wrapper_body = foldr ($) (res_wrapper work_app) arg_wrappers
234 wrap_rhs = mkLams (tvs ++ args) wrapper_body
235 fn_id_w_inl = fn_id `setIdUnfolding` mkInlineRule wrap_rhs (length args)
237 return ([(work_id, work_rhs), (fn_id_w_inl, wrap_rhs)], empty, empty)
241 %************************************************************************
243 \subsection{Foreign export}
245 %************************************************************************
247 The function that does most of the work for `@foreign export@' declarations.
248 (see below for the boilerplate code a `@foreign export@' declaration expands
251 For each `@foreign export foo@' in a module M we generate:
253 \item a C function `@foo@', which calls
254 \item a Haskell stub `@M.\$ffoo@', which calls
256 the user-written Haskell function `@M.foo@'.
259 dsFExport :: Id -- Either the exported Id,
260 -- or the foreign-export-dynamic constructor
261 -> Type -- The type of the thing callable from C
262 -> CLabelString -- The name to export to C land
264 -> Bool -- True => foreign export dynamic
265 -- so invoke IO action that's hanging off
266 -- the first argument's stable pointer
267 -> DsM ( SDoc -- contents of Module_stub.h
268 , SDoc -- contents of Module_stub.c
269 , String -- string describing type to pass to createAdj.
270 , Int -- size of args to stub function
273 dsFExport fn_id ty ext_name cconv isDyn= do
275 (_tvs,sans_foralls) = tcSplitForAllTys ty
276 (fe_arg_tys', orig_res_ty) = tcSplitFunTys sans_foralls
277 -- We must use tcSplits here, because we want to see
278 -- the (IO t) in the corner of the type!
279 fe_arg_tys | isDyn = tail fe_arg_tys'
280 | otherwise = fe_arg_tys'
282 -- Look at the result type of the exported function, orig_res_ty
283 -- If it's IO t, return (t, True)
284 -- If it's plain t, return (t, False)
286 is_IO_res_ty) <- -- Bool
287 case tcSplitIOType_maybe orig_res_ty of
288 Just (_ioTyCon, res_ty, _co) -> return (res_ty, True)
289 -- The function already returns IO t
290 -- ToDo: what about the coercion?
291 Nothing -> return (orig_res_ty, False)
292 -- The function returns t
295 mkFExportCBits ext_name
296 (if isDyn then Nothing else Just fn_id)
297 fe_arg_tys res_ty is_IO_res_ty cconv
300 @foreign import "wrapper"@ (previously "foreign export dynamic") lets
301 you dress up Haskell IO actions of some fixed type behind an
302 externally callable interface (i.e., as a C function pointer). Useful
303 for callbacks and stuff.
306 type Fun = Bool -> Int -> IO Int
307 foreign import "wrapper" f :: Fun -> IO (FunPtr Fun)
309 -- Haskell-visible constructor, which is generated from the above:
310 -- SUP: No check for NULL from createAdjustor anymore???
312 f :: Fun -> IO (FunPtr Fun)
314 bindIO (newStablePtr cback)
315 (\StablePtr sp# -> IO (\s1# ->
316 case _ccall_ createAdjustor cconv sp# ``f_helper'' <arg info> s1# of
317 (# s2#, a# #) -> (# s2#, A# a# #)))
319 foreign import "&f_helper" f_helper :: FunPtr (StablePtr Fun -> Fun)
321 -- and the helper in C:
323 f_helper(StablePtr s, HsBool b, HsInt i)
325 rts_evalIO(rts_apply(rts_apply(deRefStablePtr(s),
326 rts_mkBool(b)), rts_mkInt(i)));
331 dsFExportDynamic :: Id
333 -> DsM ([Binding], SDoc, SDoc)
334 dsFExportDynamic id cconv = do
335 fe_id <- newSysLocalDs ty
338 -- hack: need to get at the name of the C stub we're about to generate.
339 fe_nm = mkFastString (unpackFS (zEncodeFS (moduleNameFS (moduleName mod))) ++ "_" ++ toCName fe_id)
341 cback <- newSysLocalDs arg_ty
342 newStablePtrId <- dsLookupGlobalId newStablePtrName
343 stable_ptr_tycon <- dsLookupTyCon stablePtrTyConName
345 stable_ptr_ty = mkTyConApp stable_ptr_tycon [arg_ty]
346 export_ty = mkFunTy stable_ptr_ty arg_ty
347 bindIOId <- dsLookupGlobalId bindIOName
348 stbl_value <- newSysLocalDs stable_ptr_ty
349 (h_code, c_code, typestring, args_size) <- dsFExport id export_ty fe_nm cconv True
352 The arguments to the external function which will
353 create a little bit of (template) code on the fly
354 for allowing the (stable pointed) Haskell closure
355 to be entered using an external calling convention
358 adj_args = [ mkIntLitInt (ccallConvToInt cconv)
360 , Lit (MachLabel fe_nm mb_sz_args)
361 , Lit (mkMachString typestring)
363 -- name of external entry point providing these services.
364 -- (probably in the RTS.)
365 adjustor = fsLit "createAdjustor"
367 -- Determine the number of bytes of arguments to the stub function,
368 -- so that we can attach the '@N' suffix to its label if it is a
369 -- stdcall on Windows.
370 mb_sz_args = case cconv of
371 StdCallConv -> Just args_size
374 ccall_adj <- dsCCall adjustor adj_args PlayRisky (mkTyConApp io_tc [res_ty])
375 -- PlayRisky: the adjustor doesn't allocate in the Haskell heap or do a callback
377 let io_app = mkLams tvs $
379 mkCoerceI (mkSymCoI co) $
380 mkApps (Var bindIOId)
383 , mkApps (Var newStablePtrId) [ Type arg_ty, Var cback ]
384 , Lam stbl_value ccall_adj
387 fed = (id `setInlinePragma` NeverActive, io_app)
388 -- Never inline the f.e.d. function, because the litlit
389 -- might not be in scope in other modules.
391 return ([fed], h_code, c_code)
395 (tvs,sans_foralls) = tcSplitForAllTys ty
396 ([arg_ty], fn_res_ty) = tcSplitFunTys sans_foralls
397 Just (io_tc, res_ty, co) = tcSplitIOType_maybe fn_res_ty
398 -- Must have an IO type; hence Just
399 -- co : fn_res_ty ~ IO res_ty
401 toCName :: Id -> String
402 toCName i = showSDoc (pprCode CStyle (ppr (idName i)))
407 \subsection{Generating @foreign export@ stubs}
411 For each @foreign export@ function, a C stub function is generated.
412 The C stub constructs the application of the exported Haskell function
413 using the hugs/ghc rts invocation API.
416 mkFExportCBits :: FastString
417 -> Maybe Id -- Just==static, Nothing==dynamic
420 -> Bool -- True <=> returns an IO type
424 String, -- the argument reps
425 Int -- total size of arguments
427 mkFExportCBits c_nm maybe_target arg_htys res_hty is_IO_res_ty cc
428 = (header_bits, c_bits, type_string,
429 sum [ widthInBytes (typeWidth rep) | (_,_,_,rep) <- aug_arg_info] -- all the args
430 -- NB. the calculation here isn't strictly speaking correct.
431 -- We have a primitive Haskell type (eg. Int#, Double#), and
432 -- we want to know the size, when passed on the C stack, of
433 -- the associated C type (eg. HsInt, HsDouble). We don't have
434 -- this information to hand, but we know what GHC's conventions
435 -- are for passing around the primitive Haskell types, so we
436 -- use that instead. I hope the two coincide --SDM
439 -- list the arguments to the C function
440 arg_info :: [(SDoc, -- arg name
442 Type, -- Haskell type
443 CmmType)] -- the CmmType
444 arg_info = [ let stg_type = showStgType ty in
445 (arg_cname n stg_type,
448 typeCmmType (getPrimTyOf ty))
449 | (ty,n) <- zip arg_htys [1::Int ..] ]
452 | libffi = char '*' <> parens (stg_ty <> char '*') <>
453 ptext (sLit "args") <> brackets (int (n-1))
454 | otherwise = text ('a':show n)
456 -- generate a libffi-style stub if this is a "wrapper" and libffi is enabled
457 libffi = cLibFFI && isNothing maybe_target
460 -- libffi needs to know the result type too:
461 | libffi = primTyDescChar res_hty : arg_type_string
462 | otherwise = arg_type_string
464 arg_type_string = [primTyDescChar ty | (_,_,ty,_) <- arg_info]
465 -- just the real args
467 -- add some auxiliary args; the stable ptr in the wrapper case, and
468 -- a slot for the dummy return address in the wrapper + ccall case
470 | isNothing maybe_target = stable_ptr_arg : insertRetAddr cc arg_info
471 | otherwise = arg_info
474 (text "the_stableptr", text "StgStablePtr", undefined,
475 typeCmmType (mkStablePtrPrimTy alphaTy))
477 -- stuff to do with the return type of the C function
478 res_hty_is_unit = res_hty `coreEqType` unitTy -- Look through any newtypes
480 cResType | res_hty_is_unit = text "void"
481 | otherwise = showStgType res_hty
483 -- Now we can cook up the prototype for the exported function.
484 pprCconv = case cc of
486 StdCallConv -> text (ccallConvAttribute cc)
487 CmmCallConv -> panic "mkFExportCBits/pprCconv CmmCallConv"
489 header_bits = ptext (sLit "extern") <+> fun_proto <> semi
492 | null aug_arg_info = text "void"
493 | otherwise = hsep $ punctuate comma
494 $ map (\(nm,ty,_,_) -> ty <+> nm) aug_arg_info
498 = ptext (sLit "void") <+> ftext c_nm <>
499 parens (ptext (sLit "void *cif STG_UNUSED, void* resp, void** args, void* the_stableptr"))
501 = cResType <+> pprCconv <+> ftext c_nm <> parens fun_args
503 -- the target which will form the root of what we ask rts_evalIO to run
505 = case maybe_target of
506 Nothing -> text "(StgClosure*)deRefStablePtr(the_stableptr)"
507 Just hs_fn -> char '&' <> ppr hs_fn <> text "_closure"
509 cap = text "cap" <> comma
511 -- the expression we give to rts_evalIO
513 = foldl appArg the_cfun arg_info -- NOT aug_arg_info
515 appArg acc (arg_cname, _, arg_hty, _)
517 <> parens (cap <> acc <> comma <> mkHObj arg_hty <> parens (cap <> arg_cname))
519 -- various other bits for inside the fn
520 declareResult = text "HaskellObj ret;"
521 declareCResult | res_hty_is_unit = empty
522 | otherwise = cResType <+> text "cret;"
524 assignCResult | res_hty_is_unit = empty
526 text "cret=" <> unpackHObj res_hty <> parens (text "ret") <> semi
528 -- an extern decl for the fn being called
530 = case maybe_target of
532 Just hs_fn -> text "extern StgClosure " <> ppr hs_fn <> text "_closure" <> semi
535 -- finally, the whole darn thing
542 , ptext (sLit "Capability *cap;")
545 , text "cap = rts_lock();"
546 -- create the application + perform it.
547 , ptext (sLit "cap=rts_evalIO") <> parens (
549 ptext (sLit "rts_apply") <> parens (
552 <> ptext (if is_IO_res_ty
553 then (sLit "runIO_closure")
554 else (sLit "runNonIO_closure"))
560 , ptext (sLit "rts_checkSchedStatus") <> parens (doubleQuotes (ftext c_nm)
561 <> comma <> text "cap") <> semi
563 , ptext (sLit "rts_unlock(cap);")
564 , if res_hty_is_unit then empty
566 then char '*' <> parens (cResType <> char '*') <>
567 ptext (sLit "resp = cret;")
568 else ptext (sLit "return cret;")
573 foreignExportInitialiser :: Id -> SDoc
574 foreignExportInitialiser hs_fn =
575 -- Initialise foreign exports by registering a stable pointer from an
576 -- __attribute__((constructor)) function.
577 -- The alternative is to do this from stginit functions generated in
578 -- codeGen/CodeGen.lhs; however, stginit functions have a negative impact
579 -- on binary sizes and link times because the static linker will think that
580 -- all modules that are imported directly or indirectly are actually used by
582 -- (this is bad for big umbrella modules like Graphics.Rendering.OpenGL)
584 [ text "static void stginit_export_" <> ppr hs_fn
585 <> text "() __attribute__((constructor));"
586 , text "static void stginit_export_" <> ppr hs_fn <> text "()"
587 , braces (text "getStablePtr"
588 <> parens (text "(StgPtr) &" <> ppr hs_fn <> text "_closure")
593 mkHObj :: Type -> SDoc
594 mkHObj t = text "rts_mk" <> text (showFFIType t)
596 unpackHObj :: Type -> SDoc
597 unpackHObj t = text "rts_get" <> text (showFFIType t)
599 showStgType :: Type -> SDoc
600 showStgType t = text "Hs" <> text (showFFIType t)
602 showFFIType :: Type -> String
603 showFFIType t = getOccString (getName tc)
605 tc = case tcSplitTyConApp_maybe (repType t) of
607 Nothing -> pprPanic "showFFIType" (ppr t)
609 insertRetAddr :: CCallConv -> [(SDoc, SDoc, Type, CmmType)]
610 -> [(SDoc, SDoc, Type, CmmType)]
611 #if !defined(x86_64_TARGET_ARCH)
612 insertRetAddr CCallConv args = ret_addr_arg : args
613 insertRetAddr _ args = args
615 -- On x86_64 we insert the return address after the 6th
616 -- integer argument, because this is the point at which we
617 -- need to flush a register argument to the stack (See rts/Adjustor.c for
619 insertRetAddr CCallConv args = go 0 args
620 where go :: Int -> [(SDoc, SDoc, Type, CmmType)]
621 -> [(SDoc, SDoc, Type, CmmType)]
622 go 6 args = ret_addr_arg : args
623 go n (arg@(_,_,_,rep):args)
624 | cmmEqType_ignoring_ptrhood rep b64 = arg : go (n+1) args
625 | otherwise = arg : go n args
627 insertRetAddr _ args = args
630 ret_addr_arg :: (SDoc, SDoc, Type, CmmType)
631 ret_addr_arg = (text "original_return_addr", text "void*", undefined,
632 typeCmmType addrPrimTy)
634 -- This function returns the primitive type associated with the boxed
635 -- type argument to a foreign export (eg. Int ==> Int#).
636 getPrimTyOf :: Type -> Type
638 | isBoolTy rep_ty = intPrimTy
639 -- Except for Bool, the types we are interested in have a single constructor
640 -- with a single primitive-typed argument (see TcType.legalFEArgTyCon).
642 case splitProductType_maybe rep_ty of
643 Just (_, _, data_con, [prim_ty]) ->
644 ASSERT(dataConSourceArity data_con == 1)
645 ASSERT2(isUnLiftedType prim_ty, ppr prim_ty)
647 _other -> pprPanic "DsForeign.getPrimTyOf" (ppr ty)
651 -- represent a primitive type as a Char, for building a string that
652 -- described the foreign function type. The types are size-dependent,
653 -- e.g. 'W' is a signed 32-bit integer.
654 primTyDescChar :: Type -> Char
656 | ty `coreEqType` unitTy = 'v'
658 = case typePrimRep (getPrimTyOf ty) of
659 IntRep -> signed_word
660 WordRep -> unsigned_word
666 _ -> pprPanic "primTyDescChar" (ppr ty)
668 (signed_word, unsigned_word)
669 | wORD_SIZE == 4 = ('W','w')
670 | wORD_SIZE == 8 = ('L','l')
671 | otherwise = panic "primTyDescChar"