[project @ 2000-04-05 16:25:51 by simonpj]
[ghc-hetmet.git] / ghc / compiler / deSugar / DsForeign.lhs
1 %
2 % (c) The AQUA Project, Glasgow University, 1998
3 %
4 \section[DsCCall]{Desugaring \tr{foreign} declarations}
5
6 Expanding out @foreign import@ and @foreign export@ declarations.
7
8 \begin{code}
9 module DsForeign ( dsForeigns ) where
10
11 #include "HsVersions.h"
12
13 import CoreSyn
14
15 import DsCCall          ( dsCCall, mkCCall, boxResult, unboxArg )
16 import DsMonad
17 import DsUtils
18
19 import HsSyn            ( ExtName(..), ForeignDecl(..), isDynamicExtName, ForKind(..) )
20 import HsDecls          ( extNameStatic )
21 import CallConv
22 import TcHsSyn          ( TypecheckedForeignDecl )
23 import CoreUtils        ( exprType, mkInlineMe, bindNonRec )
24 import DataCon          ( DataCon, dataConWrapId )
25 import Id               ( Id, idType, idName, mkWildId, mkVanillaId )
26 import MkId             ( mkWorkerId )
27 import Literal          ( Literal(..) )
28 import Module           ( Module, moduleUserString )
29 import Name             ( mkGlobalName, nameModule, nameOccName, getOccString, 
30                           mkForeignExportOcc, isLocalName,
31                           NamedThing(..), Provenance(..), ExportFlag(..)
32                         )
33 import PrelInfo         ( deRefStablePtr_NAME, bindIO_NAME, makeStablePtr_NAME )
34 import Type             ( unUsgTy,
35                           splitTyConApp_maybe, splitFunTys, splitForAllTys,
36                           Type, mkFunTys, mkForAllTys, mkTyConApp,
37                           mkTyVarTy, mkFunTy, splitAppTy
38                         )
39 import PrimOp           ( PrimOp(..), CCall(..), CCallTarget(..) )
40 import Var              ( TyVar )
41 import TysPrim          ( realWorldStatePrimTy, addrPrimTy )
42 import TysWiredIn       ( unitTyCon, addrTy, stablePtrTyCon,
43                           unboxedTupleCon, addrDataCon
44                         )
45 import Unique
46 import Maybes           ( maybeToBool )
47 import Outputable
48 \end{code}
49
50 Desugaring of @foreign@ declarations is naturally split up into
51 parts, an @import@ and an @export@  part. A @foreign import@ 
52 declaration
53 \begin{verbatim}
54   foreign import cc nm f :: prim_args -> IO prim_res
55 \end{verbatim}
56 is the same as
57 \begin{verbatim}
58   f :: prim_args -> IO prim_res
59   f a1 ... an = _ccall_ nm cc a1 ... an
60 \end{verbatim}
61 so we reuse the desugaring code in @DsCCall@ to deal with these.
62
63 \begin{code}
64 dsForeigns :: Module
65            -> [TypecheckedForeignDecl] 
66            -> DsM ( [CoreBind]        -- desugared foreign imports
67                   , [CoreBind]        -- helper functions for foreign exports
68                   , SDoc              -- Header file prototypes for
69                                       -- "foreign exported" functions.
70                   , SDoc              -- C stubs to use when calling
71                                       -- "foreign exported" functions.
72                   )
73 dsForeigns mod_name fos = foldlDs combine ([],[],empty,empty) fos
74  where
75   combine (acc_fi, acc_fe, acc_h, acc_c) fo@(ForeignDecl i imp_exp _ ext_nm cconv _) 
76     | isForeignImport =   -- foreign import (dynamic)?
77         dsFImport i (idType i) uns ext_nm cconv  `thenDs` \ bs -> 
78         returnDs (bs ++ acc_fi, acc_fe, acc_h, acc_c)
79     | isForeignLabel = 
80         dsFLabel i ext_nm `thenDs` \ b -> 
81         returnDs (b:acc_fi, acc_fe, acc_h, acc_c)
82     | isDynamicExtName ext_nm =
83         dsFExportDynamic i (idType i) mod_name ext_nm cconv  `thenDs` \ (fi,fe,h,c) -> 
84         returnDs (fi:acc_fi, fe:acc_fe, h $$ acc_h, c $$ acc_c)
85
86     | otherwise        =  -- foreign export
87         dsFExport i (idType i) mod_name ext_nm cconv False   `thenDs` \ (fe,h,c) ->
88         returnDs (acc_fi, fe:acc_fe, h $$ acc_h, c $$ acc_c)
89    where
90     isForeignImport = 
91         case imp_exp of
92           FoImport _ -> True
93           _          -> False
94
95     isForeignLabel = 
96         case imp_exp of
97           FoLabel -> True
98           _       -> False
99
100     (FoImport uns)   = imp_exp
101
102 \end{code}
103
104 Desugaring foreign imports is just the matter of creating a binding
105 that on its RHS unboxes its arguments, performs the external call
106 (using the @CCallOp@ primop), before boxing the result up and returning it.
107
108 However, we create a worker/wrapper pair, thus:
109
110         foreign import f :: Int -> IO Int
111 ==>
112         f x = IO ( \s -> case x of { I# x# ->
113                          case fw s x# of { (# s1, y# #) ->
114                          (# s1, I# y# #)}})
115
116         fw s x# = ccall f s x#
117
118 The strictness/CPR analyser won't do this automatically because it doesn't look
119 inside returned tuples; but inlining this wrapper is a Really Good Idea 
120 because it exposes the boxing to the call site.
121                         
122
123 \begin{code}
124 dsFImport :: Id
125           -> Type               -- Type of foreign import.
126           -> Bool               -- True <=> might cause Haskell GC
127           -> ExtName
128           -> CallConv
129           -> DsM [CoreBind]
130 dsFImport fn_id ty may_not_gc ext_name cconv 
131   = let
132         (tvs, fun_ty)        = splitForAllTys ty
133         (arg_tys, io_res_ty) = splitFunTys fun_ty
134     in
135     newSysLocalsDs arg_tys                      `thenDs` \ args ->
136     mapAndUnzipDs unboxArg (map Var args)       `thenDs` \ (val_args, arg_wrappers) ->
137     boxResult io_res_ty                         `thenDs` \ (ccall_result_ty, res_wrapper) ->
138
139     (case ext_name of
140        Dynamic       -> getUniqueDs `thenDs` \ u -> 
141                         returnDs (DynamicTarget u)
142        ExtName fs _  -> returnDs (StaticTarget fs))     `thenDs` \ lbl ->
143
144     getUniqueDs                                         `thenDs` \ ccall_uniq ->
145     getUniqueDs                                         `thenDs` \ work_uniq ->
146     let
147         -- Build the worker
148         work_arg_ids  = [v | Var v <- val_args]         -- All guaranteed to be vars
149         worker_ty     = mkForAllTys tvs (mkFunTys (map idType work_arg_ids) ccall_result_ty)
150         the_ccall     = CCall lbl False (not may_not_gc) cconv
151         the_ccall_app = mkCCall ccall_uniq the_ccall val_args ccall_result_ty
152         work_rhs      = mkLams tvs (mkLams work_arg_ids the_ccall_app)
153         work_id       = mkWorkerId work_uniq fn_id worker_ty
154
155         -- Build the wrapper
156         work_app     = mkApps (mkVarApps (Var work_id) tvs) val_args
157         wrapper_body = foldr ($) (res_wrapper work_app) arg_wrappers
158         wrap_rhs     = mkInlineMe (mkLams (tvs ++ args) wrapper_body)
159     in
160     returnDs [NonRec fn_id wrap_rhs, NonRec work_id work_rhs]
161 \end{code}
162
163 Foreign labels 
164
165 \begin{code}
166 dsFLabel :: Id -> ExtName -> DsM CoreBind
167 dsFLabel nm ext_name = returnDs (NonRec nm fo_rhs)
168   where
169    fo_rhs = mkConApp addrDataCon [mkLit (MachLitLit enm addrPrimTy)]
170    enm    = extNameStatic ext_name
171 \end{code}
172
173 The function that does most of the work for `@foreign export@' declarations.
174 (see below for the boilerplate code a `@foreign export@' declaration expands
175  into.)
176
177 For each `@foreign export foo@' in a module M we generate:
178 \begin{itemize}
179 \item a C function `@foo@', which calls
180 \item a Haskell stub `@M.$ffoo@', which calls
181 \end{itemize}
182 the user-written Haskell function `@M.foo@'.
183
184 \begin{code}
185 dsFExport :: Id
186           -> Type               -- Type of foreign export.
187           -> Module
188           -> ExtName
189           -> CallConv
190           -> Bool               -- True => invoke IO action that's hanging off 
191                                 -- the first argument's stable pointer
192           -> DsM ( CoreBind
193                  , SDoc
194                  , SDoc
195                  )
196 dsFExport i ty mod_name ext_name cconv isDyn =
197      getUniqueDs                                        `thenDs` \ uniq ->
198      getSrcLocDs                                        `thenDs` \ src_loc ->
199      let
200         f_helper_glob = mkVanillaId helper_name helper_ty
201                       where
202                         name                = idName i
203                         mod     
204                          | isLocalName name = mod_name
205                          | otherwise        = nameModule name
206
207                         occ                 = mkForeignExportOcc (nameOccName name)
208                         prov                = LocalDef src_loc Exported
209                         helper_name         = mkGlobalName uniq mod occ prov
210      in
211      newSysLocalsDs fe_arg_tys                          `thenDs` \ fe_args ->
212      (if isDyn then 
213         newSysLocalDs stbl_ptr_ty                       `thenDs` \ stbl_ptr ->
214         newSysLocalDs stbl_ptr_to_ty                    `thenDs` \ stbl_value ->
215         dsLookupGlobalValue deRefStablePtr_NAME         `thenDs` \ deRefStablePtrId ->
216         let
217          the_deref_app = mkApps (Var deRefStablePtrId)
218                                 [ Type stbl_ptr_to_ty, Var stbl_ptr ]
219         in
220         newSysLocalDs (exprType the_deref_app)   `thenDs` \ x_deref_app ->
221         dsLookupGlobalValue bindIO_NAME                  `thenDs` \ bindIOId ->
222         newSysLocalDs (mkFunTy stbl_ptr_to_ty 
223                                (mkTyConApp ioTyCon [res_ty])) `thenDs` \ x_cont ->
224         let
225          stbl_app      = \ cont -> 
226                 bindNonRec x_cont   (mkLams [stbl_value] cont) $
227                 bindNonRec x_deref_app the_deref_app  
228                            (mkApps (Var bindIOId)
229                                      [ Type stbl_ptr_to_ty
230                                      , Type res_ty
231                                      , Var x_deref_app
232                                      , Var x_cont])
233         in
234         returnDs (stbl_value, stbl_app, stbl_ptr)
235       else
236         returnDs (i, 
237                   \ body -> body,
238                   panic "stbl_ptr"  -- should never be touched.
239                   ))                    `thenDs` \ (i, getFun_wrapper, stbl_ptr) ->
240      let
241       wrapper_args
242        | isDyn      = stbl_ptr:fe_args
243        | otherwise  = fe_args
244
245       wrapper_arg_tys
246        | isDyn      = stbl_ptr_ty:helper_arg_tys
247        | otherwise  = helper_arg_tys
248
249       the_app  = 
250          getFun_wrapper $
251          mkApps (Var i) (map (Type . mkTyVarTy) tvs ++ map Var fe_args)
252      in
253      getModuleDs                        `thenDs` \ mod -> 
254      getUniqueDs                        `thenDs` \ uniq ->
255      let
256       the_body = mkLams (tvs ++ wrapper_args) the_app
257       c_nm     = extNameStatic ext_name
258
259       (h_stub, c_stub) = fexportEntry (moduleUserString mod)
260                                       c_nm f_helper_glob
261                                       wrapper_arg_tys the_result_ty cconv isDyn
262      in
263      returnDs (NonRec f_helper_glob the_body, h_stub, c_stub)
264
265   where
266
267    (tvs,sans_foralls)                   = splitForAllTys ty
268    (fe_arg_tys', io_res)                = splitFunTys sans_foralls
269
270
271    Just (ioTyCon, [res_ty])             = splitTyConApp_maybe io_res
272
273    (_, stbl_ptr_ty')                    = splitForAllTys stbl_ptr_ty
274    (_, stbl_ptr_to_ty)                  = splitAppTy stbl_ptr_ty'
275
276    fe_arg_tys
277      | isDyn        = tail fe_arg_tys'
278      | otherwise    = fe_arg_tys'
279
280    (stbl_ptr_ty, helper_arg_tys) = 
281      case fe_arg_tys' of
282        (x:xs) | isDyn -> (x,xs)
283        ls             -> (error "stbl_ptr_ty", ls)
284
285    helper_ty      =  
286         mkForAllTys tvs $
287         mkFunTys arg_tys io_res
288         where
289           arg_tys
290            | isDyn      = stbl_ptr_ty : helper_arg_tys
291            | otherwise  = helper_arg_tys
292
293    the_result_ty =
294      case splitTyConApp_maybe io_res of
295        Just (_,[res_ty]) ->
296          case splitTyConApp_maybe res_ty of
297            Just (tc,_) | getUnique tc /= getUnique unitTyCon -> Just res_ty
298            _                                                 -> Nothing
299        _                 -> Nothing
300    
301 \end{code}
302
303 @foreign export dynamic@ lets you dress up Haskell IO actions
304 of some fixed type behind an externally callable interface (i.e.,
305 as a C function pointer). Useful for callbacks and stuff.
306
307 \begin{verbatim}
308 foreign export stdcall f :: (Addr -> Int -> IO Int) -> IO Addr
309
310 -- Haskell-visible constructor, which is generated from the
311 -- above:
312
313 f :: (Addr -> Int -> IO Int) -> IO Addr
314 f cback = IO ( \ s1# ->
315   case makeStablePtr# cback s1# of { StateAndStablePtr# s2# sp# ->
316   case _ccall_ "mkAdjustor" sp# ``f_helper'' s2# of
317     StateAndAddr# s3# a# ->
318     case addr2Int# a# of
319       0# -> IOfail s# err
320       _  -> 
321          let
322           a :: Addr
323           a = A# a#
324          in
325          IOok s3# a)
326
327 foreign export "f_helper" f_helper :: StablePtr (Addr -> Int -> IO Int) -> Addr -> Int -> IO Int
328 -- `special' foreign export that invokes the closure pointed to by the
329 -- first argument.
330 \end{verbatim}
331
332 \begin{code}
333 dsFExportDynamic :: Id
334                  -> Type                -- Type of foreign export.
335                  -> Module
336                  -> ExtName
337                  -> CallConv
338                  -> DsM (CoreBind, CoreBind, SDoc, SDoc)
339 dsFExportDynamic i ty mod_name ext_name cconv =
340      newSysLocalDs ty                                    `thenDs` \ fe_id ->
341      let 
342         -- hack: need to get at the name of the C stub we're about to generate.
343        fe_nm       = toCName fe_id
344        fe_ext_name = ExtName (_PK_ fe_nm) Nothing
345      in
346      dsFExport  i export_ty mod_name fe_ext_name cconv True
347      `thenDs` \ (fe@(NonRec fe_helper fe_expr), h_code, c_code) ->
348      newSysLocalDs arg_ty                                   `thenDs` \ cback ->
349      dsLookupGlobalValue makeStablePtr_NAME        `thenDs` \ makeStablePtrId ->
350      let
351         mk_stbl_ptr_app    = mkApps (Var makeStablePtrId) [ Type arg_ty, Var cback ]
352         mk_stbl_ptr_app_ty = exprType mk_stbl_ptr_app
353      in
354      newSysLocalDs mk_stbl_ptr_app_ty                   `thenDs` \ x_mk_stbl_ptr_app ->
355      dsLookupGlobalValue bindIO_NAME                    `thenDs` \ bindIOId ->
356      newSysLocalDs (mkTyConApp stablePtrTyCon [arg_ty]) `thenDs` \ stbl_value ->
357      let
358       stbl_app      = \ x_cont cont ret_ty -> 
359         bindNonRec x_cont            cont            $
360         bindNonRec x_mk_stbl_ptr_app mk_stbl_ptr_app $
361                    (mkApps (Var bindIOId)
362                            [ Type (mkTyConApp stablePtrTyCon [arg_ty])
363                            , Type ret_ty
364                            , Var x_mk_stbl_ptr_app
365                            , Var x_cont
366                            ])
367
368        {-
369         The arguments to the external function which will
370         create a little bit of (template) code on the fly
371         for allowing the (stable pointed) Haskell closure
372         to be entered using an external calling convention
373         (stdcall, ccall).
374        -}
375       adj_args      = [ mkIntLitInt (callConvToInt cconv)
376                       , Var stbl_value
377                       , mkLit (MachLitLit (_PK_ fe_nm) addrPrimTy)
378                       ]
379         -- name of external entry point providing these services.
380         -- (probably in the RTS.) 
381       adjustor      = SLIT("createAdjustor")
382      in
383      dsCCall adjustor adj_args False False addrTy `thenDs` \ ccall_adj ->
384      let ccall_adj_ty = exprType ccall_adj
385      in
386      newSysLocalDs ccall_adj_ty                   `thenDs` \ x_ccall_adj ->
387      let ccall_io_adj = 
388             mkLams [stbl_value]              $
389             bindNonRec x_ccall_adj ccall_adj $
390             Note (Coerce (mkTyConApp ioTyCon [res_ty]) (unUsgTy ccall_adj_ty))
391                  (Var x_ccall_adj)
392      in
393      newSysLocalDs (exprType ccall_io_adj)        `thenDs` \ x_ccall_io_adj ->
394      let io_app = mkLams tvs     $
395                   mkLams [cback] $
396                   stbl_app x_ccall_io_adj ccall_io_adj addrTy
397      in
398      returnDs (NonRec i io_app, fe, h_code, c_code)
399
400  where
401   (tvs,sans_foralls)               = splitForAllTys ty
402   ([arg_ty], io_res)               = splitFunTys sans_foralls
403
404   Just (ioTyCon, [res_ty])         = splitTyConApp_maybe io_res
405
406   export_ty                        = mkFunTy (mkTyConApp stablePtrTyCon [arg_ty]) arg_ty
407
408 toCName :: Id -> String
409 toCName i = showSDoc (pprCode CStyle (ppr (idName i)))
410
411 \end{code}
412
413 %*
414 %
415 \subsection{Generating @foreign export@ stubs}
416 %
417 %*
418
419 For each @foreign export@ function, a C stub function is generated.
420 The C stub constructs the application of the exported Haskell function 
421 using the hugs/ghc rts invocation API.
422
423 \begin{code}
424 fexportEntry :: String
425              -> FAST_STRING
426              -> Id 
427              -> [Type] 
428              -> Maybe Type 
429              -> CallConv 
430              -> Bool
431              -> (SDoc, SDoc)
432 fexportEntry mod_nm c_nm helper args res cc isDyn = (header_bits, c_bits)
433  where
434    -- name of the (Haskell) helper function generated by the desugarer.
435   h_nm      = ppr helper <> text "_closure"
436    -- prototype for the exported function.
437   header_bits = ptext SLIT("extern") <+> fun_proto <> semi
438
439   fun_proto = cResType <+> pprCconv <+> ptext c_nm <>
440               parens (hsep (punctuate comma (zipWith (<+>) cParamTypes proto_args)))
441
442   c_bits =
443     externDecl $$
444     fun_proto  $$
445     vcat 
446      [ lbrace
447      ,   text "SchedulerStatus rc;"
448      ,   declareResult
449           -- create the application + perform it.
450      ,   text "rc=rts_evalIO" <> 
451                   parens (foldl appArg (text "(StgClosure*)&" <> h_nm) (zip args c_args) <> comma <> text "&ret") <> semi
452      ,   returnResult
453      , rbrace
454      ]
455
456   appArg acc (a,c_a) =
457      text "rts_apply" <> parens (acc <> comma <> mkHObj a <> parens c_a)
458
459   cParamTypes  = map showStgType real_args
460
461   cResType = 
462    case res of
463      Nothing -> text "void"
464      Just t  -> showStgType t
465
466   pprCconv
467    | cc == cCallConv = empty
468    | otherwise       = pprCallConv cc
469      
470   declareResult  = text "HaskellObj ret;"
471
472   externDecl     = mkExtern (text "HaskellObj") h_nm
473
474   mkExtern ty nm = text "extern" <+> ty <+> nm <> semi
475
476   returnResult = 
477     text "rts_checkSchedStatus" <> 
478     parens (doubleQuotes (text mod_nm <> char '.' <> ptext c_nm) <> comma <> text "rc") <> semi $$
479     (case res of
480       Nothing -> text "return"
481       Just _  -> text "return" <> parens (res_name)) <> semi
482
483   res_name = 
484     case res of
485       Nothing -> empty
486       Just t  -> unpackHObj t <> parens (text "ret")
487
488   c_args = mkCArgNames 0 args
489
490   {-
491    If we're generating an entry point for a 'foreign export ccall dynamic',
492    then we receive the return address of the C function that wants to
493    invoke a Haskell function as any other C function, as second arg.
494    This arg is unused within the body of the generated C stub, but
495    needed by the Adjustor.c code to get the stack cleanup right.
496   -}
497   (proto_args, real_args)
498     | cc == cCallConv && isDyn = ( text "a0" : text "a_" : mkCArgNames 1 (tail args)
499                                 , head args : addrTy : tail args)
500     | otherwise = (mkCArgNames 0 args, args)
501
502 mkCArgNames :: Int -> [a] -> [SDoc]
503 mkCArgNames n as = zipWith (\ _ n -> text ('a':show n)) as [n..] 
504
505 mkHObj :: Type -> SDoc
506 mkHObj t = text "rts_mk" <> text (showFFIType t)
507
508 unpackHObj :: Type -> SDoc
509 unpackHObj t = text "rts_get" <> text (showFFIType t)
510
511 showStgType :: Type -> SDoc
512 showStgType t = text "Stg" <> text (showFFIType t)
513
514 showFFIType :: Type -> String
515 showFFIType t = getOccString (getName tc)
516  where
517   tc = case splitTyConApp_maybe t of
518             Just (tc,_) -> tc
519             Nothing     -> pprPanic "showFFIType" (ppr t)
520 \end{code}