[project @ 2001-07-12 12:58:39 by rrt]
[ghc-hetmet.git] / ghc / compiler / ilxGen / IlxGen.lhs
1 %
2 \section{Generate COM+ extended assembler}
3
4 \begin{code}
5 module IlxGen( ilxGen ) where
6
7 #include "HsVersions.h"
8
9 import Char     ( ord, chr )
10 import StgSyn
11 import Id       ( idType, idName, isDeadBinder, idArityInfo )
12 import IdInfo   ( arityLowerBound )
13 import Var      ( Var, Id, TyVar, isId, isTyVar, tyVarKind, tyVarName )
14 import VarEnv
15 import TyCon    ( TyCon,  tyConPrimRep, isUnboxedTupleTyCon, tyConDataCons, 
16                   tyConTyVars, isDataTyCon, isAlgTyCon, tyConArity
17                 )
18 import Type     ( liftedTypeKind, openTypeKind, unliftedTypeKind,
19                   isUnLiftedType, isTyVarTy, mkTyVarTy, sourceTypeRep,
20                   splitForAllTys, splitFunTys, applyTy, applyTys, eqKind
21                 )
22 import TypeRep  ( Type(..) )
23 import DataCon  ( isUnboxedTupleCon, dataConTyCon, dataConRepType, dataConRepArgTys )
24 import Literal  ( Literal(..) )
25 import PrelNames        -- Lots of keys
26 import PrimOp           ( PrimOp(..) )
27 import ForeignCall      ( CCallConv(..), ForeignCall(..), CCallSpec(..), CCallTarget(..), DNCallSpec(..) )
28 import TysWiredIn       ( mkTupleTy, tupleCon )
29 import PrimRep          ( PrimRep(..) )
30 import Name             ( nameModule, nameOccName, isGlobalName, isLocalName, NamedThing(getName) )
31 import Subst            ( substTy, mkTyVarSubst )
32
33 import Module           ( Module, PackageName, ModuleName, moduleName, 
34                           modulePackage, preludePackage,
35                           isHomeModule, isVanillaModule,
36                           pprModuleName, mkHomeModule, mkModuleName
37                         )
38
39 import UniqFM
40 import BasicTypes       ( Boxity(..) )
41 import CStrings         ( CLabelString, pprCLabelString )
42 import Outputable
43 import Char             ( ord )
44 import List             ( partition, elem, insertBy,any  )
45 import UniqSet
46 import PprType          ( pprType )     -- Only called in debug messages
47
48 import TysPrim  ( foreignObjPrimTyCon, weakPrimTyCon, byteArrayPrimTyCon, mutableByteArrayPrimTyCon )
49
50 -- opt_SimplDoEtaReduction is used to help with assembly naming conventions for different
51 -- versions of compiled Haskell code.  We add a ".O" to all assembly and module 
52 -- names when this is set (because that's clue that -O was set).  
53 -- One day this will be configured by the command line.
54 import CmdLineOpts      ( opt_InPackage, opt_SimplDoEtaReduction )
55
56 \end{code}
57
58
59
60 %************************************************************************
61 %*                                                                      *
62 \subsection{Main driver}
63 %*                                                                      *
64 %************************************************************************
65
66 \begin{code}
67 ilxGen :: Module -> [TyCon] -> [(StgBinding,[Id])] -> SDoc
68         -- The TyCons should include those arising from classes
69 ilxGen mod tycons binds_w_srts
70   =  vcat [ text ".assembly extern ilx 'mscorlib' {}",
71             vcat (map (ilxImportPackage topenv) (uniqSetToList import_packages)),
72             vcat (map (ilxImportModule topenv) (uniqSetToList import_modules)),
73             vcat (map (ilxImportTyCon topenv) (uniqSetToList import_tycons)),
74             vcat (map (ilxImportCCall topenv) (map snd (ufmToList import_ccalls))),
75             vcat (map (ilxTyCon topenv) data_tycons),
76             vcat (map (ilxBindClosures topenv) binds),
77             ilxTopBind mod topenv toppairs
78          ]
79     where
80       binds = map fst binds_w_srts
81       toppairs = ilxPairs binds
82       topenv = extendIlxEnvWithTops (emptyIlxEnv False mod) mod toppairs
83         -- Generate info from class decls as well
84       (import_packages,import_modules,import_tycons,import_ccalls) = importsBinds topenv binds (importsPrelude emptyImpInfo)
85       data_tycons = filter isDataTyCon tycons
86 \end{code}
87
88 %************************************************************************
89 %*                                                                      *
90 \subsection{Find Imports}
91 %*                                                                      *
92 %************************************************************************
93
94 \begin{code}
95
96 importsBinds :: IlxEnv -> [StgBinding] -> ImportsInfo-> ImportsInfo
97 importsBinds env binds = foldR (importsBind env) binds
98
99 importsNone :: ImportsInfo -> ImportsInfo
100 importsNone sofar = sofar
101
102 importsBind :: IlxEnv -> StgBinding -> ImportsInfo -> ImportsInfo
103 importsBind env (StgNonRec _ b rhs) = importsRhs env rhs.importsVar env b
104 importsBind env (StgRec _ pairs) = foldR (\(b,rhs) -> importsRhs env rhs . importsVar env b) pairs
105
106 importsRhs :: IlxEnv -> StgRhs -> ImportsInfo -> ImportsInfo
107 importsRhs env (StgRhsCon _ con args) = importsDataCon env con . importsStgArgs env args
108 importsRhs env (StgRhsClosure _ _ _ _ args body) = importsExpr env body. importsVars env args
109
110 importsExpr :: IlxEnv -> StgExpr -> ImportsInfo -> ImportsInfo
111 importsExpr env (StgLit _) = importsNone
112 importsExpr env (StgApp f args) = importsVar env f.importsStgArgs env args
113 importsExpr env (StgConApp con args) = importsDataCon env con.importsStgArgs env args
114 importsExpr env (StgOpApp (StgFCallOp (CCall (CCallSpec (StaticTarget c) cc _)) _) args rty)
115   = addCCallInfo (c,cc, map stgArgType tm_args, rty) . importsStgArgs env args
116   where 
117     (ty_args,tm_args) = splitTyArgs1 args 
118
119 importsExpr env (StgOpApp _ args res_ty) = importsType env res_ty. importsStgArgs env args
120
121
122 importsExpr env (StgSCC _ expr) = importsExpr env expr
123 importsExpr env (StgCase scrut _ _ bndr _ alts)
124   = importsExpr env scrut. imports_alts alts. importsVar env bndr
125    where
126     imports_alts (StgAlgAlts _ alg_alts deflt)  -- The Maybe TyCon part is dealt with 
127                                                 -- by the case-binder's type
128       = foldR imports_alg_alt alg_alts .  imports_deflt deflt
129        where
130         imports_alg_alt (con, bndrs, _, rhs)
131           = importsExpr env rhs . importsDataCon env con. importsVars env bndrs
132
133     imports_alts (StgPrimAlts _ alg_alts deflt)
134       = foldR imports_prim_alt alg_alts . imports_deflt deflt
135        where
136         imports_prim_alt (_, rhs) = importsExpr env rhs
137     imports_deflt StgNoDefault = importsNone
138     imports_deflt (StgBindDefault rhs) = importsExpr env rhs
139
140
141 importsExpr env (StgLetNoEscape _ _ bind body) = importsExpr env (StgLet bind body)
142 importsExpr env (StgLet bind body)
143   = importsBind env bind .  importsExpr env body
144
145 importsApp env v args = importsVar env v.  importsStgArgs env args
146 importsStgArgs env args = foldR (importsStgArg env) args
147
148 importsStgArg :: IlxEnv -> StgArg -> ImportsInfo -> ImportsInfo
149 importsStgArg env (StgTypeArg ty) = importsType env ty
150 importsStgArg env (StgVarArg v) = importsVar env v
151 importsStgArg env _ = importsNone
152
153 importsVars env vs = foldR (importsVar env) vs
154 importsVar env v = importsName env (idName v). importsType env (idType v)
155
156 importsName env n
157    | isLocalName n = importsNone
158    | ilxEnvModule env == nameModule n  = importsNone
159    | isHomeModule (nameModule n) =  addModuleImpInfo (moduleName (nameModule n))
160 -- See HACK below
161    | isVanillaModule (nameModule n)  && not inPrelude =  importsPrelude
162    | isVanillaModule (nameModule n)  && inPrelude =   addModuleImpInfo (moduleName (nameModule n))
163 -- End HACK
164    | otherwise = addPackageImpInfo (modulePackage (nameModule n))
165
166
167 importsType :: IlxEnv -> Type -> ImportsInfo -> ImportsInfo
168 importsType env ty = importsType2 env (deepIlxRepType ty)
169
170 importsType2 :: IlxEnv -> Type -> ImportsInfo -> ImportsInfo
171 importsType2 env (AppTy f x) =  importsType2 env f .  importsType2 env x
172 importsType2 env (TyVarTy _) = importsNone
173 importsType2 env (TyConApp tc args) =importsTyCon env tc . importsTypeArgs2 env args
174 importsType2 env (FunTy arg res) =  importsType env arg .  importsType2 env res
175 importsType2 env (ForAllTy tv body_ty) =  importsType2 env body_ty
176 importsType2 env (NoteTy _ ty) = importsType2 env ty
177 importsType2 _ _ = panic "IlxGen.lhs: importsType2 ty"
178 importsTypeArgs2 env tys = foldR (importsType2 env) tys
179
180 importsDataCon env dcon = importsTyCon env (dataConTyCon dcon)
181
182 importsTyCon env tc | (not (isDataTyCon tc) || 
183                    isLocalName (getName tc) || 
184                    ilxEnvModule env == nameModule (getName tc)) = importsNone
185 importsTyCon env tc | otherwise = importsName env (getName tc) . addTyConImpInfo tc
186
187 importsPrelude | inPrelude = addModuleImpInfo (mkModuleName "PrelGHC")
188                | otherwise = addPackageImpInfo preludePackage
189
190 type StaticCCallInfo = (CLabelString,CCallConv,[Type],Type)
191 type ImportsInfo = (UniqSet PackageName, UniqSet ModuleName, UniqSet TyCon, UniqFM StaticCCallInfo)
192    -- (Packages, Modules, Datatypes, Imported CCalls)
193
194 emptyImpInfo :: ImportsInfo
195 emptyImpInfo = (emptyUniqSet, emptyUniqSet, emptyUniqSet, emptyUFM)
196 addPackageImpInfo p (w,x,y,z) = (addOneToUniqSet w p, x, y,z)
197 addModuleImpInfo m (w,x,y,z) = (w, addOneToUniqSet x m, y,z)
198 addTyConImpInfo tc (w,x,y,z) = (w, x, addOneToUniqSet y tc,z)
199 addCCallInfo info@(nm,a,b,c) (w,x,y,z) = (w, x, y,addToUFM z nm info)
200
201 ilxImportTyCon :: IlxEnv -> TyCon -> SDoc
202 ilxImportTyCon env tycon | isDataTyCon tycon = ilxTyConDef True env tycon
203 ilxImportTyCon _ _ | otherwise =  empty
204
205 ilxImportPackage :: IlxEnv -> PackageName -> SDoc
206 ilxImportPackage _ p = text ".assembly extern ilx" <+> singleQuotes (ppr p <> hscOptionQual) <+> text "{ }"
207
208 ilxImportModule :: IlxEnv -> ModuleName -> SDoc
209 ilxImportModule _ m = text ".module extern ilx" <+> singleQuotes (ppr m  <> hscOptionQual <> text ".dll")
210
211 -- Emit a P/Invoke declaration for the imported C function
212 -- TODO: emit the right DLL name
213 ilxImportCCall :: IlxEnv -> StaticCCallInfo -> SDoc
214 ilxImportCCall env (c,cc,args,ret) = 
215     text ".method static assembly pinvokeimpl" <+> 
216     parens (doubleQuotes (text "HSstd_cbits.dll") <+> text "cdecl") <+> retdoc <+> singleQuotes (pprCLabelString c) <+> 
217     pprCValArgTys ilxTypeL env (map deepIlxRepType (filter (not. isVoidIlxRepType) args)) <+> 
218     text "unmanaged preservesig { }"
219   where 
220     retdoc = 
221           if isVoidIlxRepType ret then text "void" 
222           else ilxTypeR env (deepIlxRepType ret)
223
224
225 \end{code}
226
227 %************************************************************************
228 %*                                                                      *
229 \subsection{Type declarations}
230 %*                                                                      *
231 %************************************************************************
232
233 \begin{code}
234
235
236 ilxTyCon :: IlxEnv -> TyCon -> SDoc
237 ilxTyCon env tycon =  ilxTyConDef False env tycon
238
239 -- filter to get only dataTyCons?
240 ilxTyConDef importing env tycon = 
241         vcat [empty $$ line,
242               text ".classunion" <+> (if importing then text "import" else empty) <+> tycon_ref <+> tyvars_text <+> super_text   <+> alts_text]
243    where
244      tycon_ref =  nameReference env (getName tycon)  <> (ppr tycon)
245      super_text = if importing then empty else text "extends thunk" <> angleBrackets (text "class" <+> tycon_ref)
246      tyvars = tyConTyVars tycon
247      (ilx_tvs, _) = categorizeTyVars tyvars
248      alts_env = extendIlxEnvWithFormalTyVars env ilx_tvs 
249      tyvars_text = pprTyVarBinders alts_env ilx_tvs 
250      alts = vcat (map (pprIlxDataCon alts_env) (tyConDataCons tycon))
251      alts_text = nest 2 (braces alts)
252
253 pprIlxDataCon env dcon =
254         text ".alternative" <+> pprId dcon <+> 
255         parens (pprSepWithCommas (ilxTypeL env) (map deepIlxRepType (filter (not. isVoidIlxRepType) (dataConRepArgTys dcon))))
256 \end{code}
257
258
259 %************************************************************************
260 %*                                                                      *
261 \subsection{Getting the .closures and literals out}                     *
262 %************************************************************************
263
264 \begin{code}
265
266 ilxBindClosures :: IlxEnv -> StgBinding -> SDoc
267 ilxBindClosures env (StgNonRec _ b rhs) = ilxRhsClosures env (b,rhs)
268 ilxBindClosures env (StgRec _ pairs)  
269   = vcat (map (ilxRhsClosures new_env) pairs)
270   where
271      new_env = extendIlxEnvWithBinds env pairs
272
273 ---------------
274 ilxRhsClosures _ (_, StgRhsCon _ _ _)
275   = empty
276
277 ilxRhsClosures env (bndr, StgRhsClosure _ _ fvs upd args rhs)
278   = vcat [ilxExprClosures next_env rhs,
279
280          empty $$ line,
281          kind_text <+> singleQuotes cloname <+>  free_vs_text,
282          nest 2 (braces (
283             nest 2 (vcat [empty,
284                           vcat [text ".apply" <+> closure_sig_text,
285                                 body_text
286                           ],
287                           empty
288                     ])
289                 ))
290     ]
291   where
292     kind_of_thing = case upd of
293                           Updatable -> ASSERT( null args ) ".thunk"
294                           otherwise -> ".closure"
295     kind_text = text kind_of_thing 
296                 
297     cloname = ilxEnvQualifyByModule env (ppr bndr)
298     next_env = ilxPlaceStgRhsClosure env bndr 
299     (free_vs_text,env_with_fvs) = pprFreeBinders next_env fvs
300
301
302     closure_sig_text =     
303       vcat [ text "()",
304              (case args of 
305                []        -> empty
306                otherwise -> args_text),
307              text "-->" <+>  rty_text]
308
309     (args_text,env_with_args) = pprArgBinders env_with_fvs args
310
311         -- Find the type returned, from the no. of args and the type of "bndr"
312     rty_text = 
313       case retType env_with_fvs (idIlxRepType bndr) args of
314        Just (env,ty) -> 
315           if isVoidIlxRepType ty  then  (text "void")
316           else ilxTypeR env ty 
317        Nothing -> trace "WARNING!  IlxGen.trace could not find return type - see generated ILX for context where this occurs." (text "// Could not find return type:" <+> ilxTypeR env_with_fvs (idIlxRepType bndr)<+> text ", non representation: " <+> ilxTypeR env_with_fvs (idType bndr))
318
319     -- strip off leading ForAll and Fun type constructions
320     -- up to the given number of arguments, extending the environment as
321     -- we go.  
322     retType env ty [] = Just (env, ty)
323     retType env (ForAllTy tv ty) (arg:args) = retType (extendIlxEnvWithTyArgs env [tv]) ty args
324     retType env (FunTy l r) (arg:args) = retType env r args
325     retType _ _ _  = Nothing
326
327         -- Code for the local variables
328     locals = ilxExprLocals env_with_args rhs
329
330     env_with_locals = extendIlxEnvWithLocals env_with_args locals
331
332         -- Code for the body of the main apply method
333     body_code = vcat [empty,
334                       pprIlxLocals env_with_args locals,
335                       ilxExpr (IlxEEnv env_with_locals (mkUniqSet (filter (not.isTyVar) args))) rhs Return,
336                       empty
337                 ]
338
339     body_text = nest 2 (braces (text ".maxstack 100" <+> nest 2 body_code))
340
341
342 pprIlxLocals env [] = empty
343 pprIlxLocals env vs 
344    = text ".locals" <+> parens (pprSepWithCommas (pprIlxLocal env) (filter nonVoidLocal vs))
345   where
346     nonVoidLocal (LocalId v,_) = not (isVoidIlxRepId v)
347     nonVoidLocal _ = True
348
349 pprIlxLocal env (LocalId v,_) = ilxTypeL env (idIlxRepType v) <+> pprId v
350 pprIlxLocal env (LocalSDoc (ty,doc,pin),_) = ilxTypeL env (deepIlxRepType ty) <+> (if pin then text "pinned" else empty) <+> doc
351
352
353 pprFreeBinders env fvs 
354     = (ilx_tvs_text <+> vs_text, env2)
355     where   
356        (free_ilx_tvs, _,free_vs) = categorizeVars fvs
357        real_free_vs = filter (not . isVoidIlxRepId) free_vs
358         -- ignore the higher order type parameters for the moment
359        env1 = extendIlxEnvWithFreeTyVars env free_ilx_tvs 
360        ilx_tvs_text = pprTyVarBinders env1 free_ilx_tvs
361        vs_text = parens (pprSepWithCommas ppr_id real_free_vs)
362        ppr_id v = ilxTypeL env1 (idIlxRepType v) <+> pprId v 
363        env2 = extendIlxEnvWithFreeVars env1 real_free_vs 
364
365 pprIdBinder env v = parens (ilxTypeL env (idIlxRepType v) <+> pprId v)
366
367         -- Declarations for the arguments of the main apply method
368 pprArgBinders env [] = (empty,env)
369 pprArgBinders env (arg:args)
370     = (arg_text <+> rest_text, res_env)
371    where 
372      (arg_text,env') = pprArgBinder env arg
373      (rest_text,res_env) = pprArgBinders env' args 
374
375 -- We could probably omit some void argument binders, but
376 -- don't...
377 pprArgBinder env arg 
378   | isVoidIlxRepId arg = (text "()", extendIlxEnvWithArgs env [arg])
379   | otherwise 
380       = if isTyVar arg then 
381          let env' = extendIlxEnvWithTyArgs env [arg] in 
382          (pprTyVarBinder env' arg, env')
383       else (pprIdBinder env arg,extendIlxEnvWithArgs env [arg])
384
385 --------------
386 -- Compute local variables used by generated method.
387 -- The names of some generated locals are recorded as SDocs.
388
389 data LocalSpec = LocalId Id | LocalSDoc (Type, SDoc, Bool)  -- flag is for pinning
390
391 ilxExprLocals :: IlxEnv -> StgExpr -> [(LocalSpec,Maybe (IlxEnv,StgRhs))]
392 ilxExprLocals env (StgLet bind body)              = ilxBindLocals env bind ++ ilxExprLocals env body
393 ilxExprLocals env (StgLetNoEscape _ _ bind body)  = ilxBindLocals env bind ++ ilxExprLocals env body  -- TO DO????
394 ilxExprLocals env (StgCase scrut _ _ bndr _ alts) 
395      = ilxExprLocals (ilxPlaceStgCaseScrut env) scrut ++ 
396        (if isDeadBinder bndr then [] else [(LocalId bndr,Nothing)]) ++ 
397        ilxAltsLocals env alts
398 ilxExprLocals env (StgOpApp (StgFCallOp fcall _) args _) 
399      = concat (ilxMapPlaceArgs 0 ilxCCallArgLocals env args)
400 ilxExprLocals _ _  = []
401
402 -- Generate locals to use for pinning arguments as we cross the boundary
403 -- to C.
404 ilxCCallArgLocals env (StgVarArg v) | pinCCallArg v = 
405    [(LocalSDoc (idType v, ilxEnvQualifyByExact env (ppr v) <> text "pin", True), Nothing)]
406 ilxCCallArgLocals _ _ | otherwise = []
407
408 ilxBindLocals env (StgNonRec _ b rhs) = [(LocalId b,Just (env, rhs))]
409 ilxBindLocals env (StgRec _ pairs)    = map (\(x,y) -> (LocalId x,Just (env, y))) pairs
410
411 ilxAltsLocals env (StgAlgAlts  _ alts deflt) = ilxDefltLocals env deflt ++ concat (ilxMapPlaceAlts ilxAlgAltLocals env alts)
412 ilxAltsLocals env (StgPrimAlts _ alts deflt) = ilxDefltLocals env deflt ++ concat (ilxMapPlaceAlts ilxPrimAltLocals env alts)
413
414 ilxAlgAltLocals env (_, bndrs, _, rhs) = map (\x -> (LocalId x,Nothing)) (filter (\v -> isId v && not (isDeadBinder v)) bndrs) ++ ilxExprLocals env rhs
415 ilxPrimAltLocals env (_, rhs)          = ilxExprLocals env rhs
416
417 ilxDefltLocals _ StgNoDefault   = []
418 ilxDefltLocals env (StgBindDefault rhs) = ilxExprLocals (ilxPlaceStgBindDefault env) rhs
419
420 --------------
421 ilxExprClosures :: IlxEnv -> StgExpr -> SDoc
422 ilxExprClosures env (StgApp _ args)
423   = vcat (ilxMapPlaceArgs 0 (ilxArgClosures) env args)  -- get strings
424 ilxExprClosures env (StgConApp _ args)
425   = vcat (ilxMapPlaceArgs 0 (ilxArgClosures) env args) -- get strings
426 ilxExprClosures env (StgOpApp _ args _)
427   = vcat (ilxMapPlaceArgs 0 (ilxArgClosures) env args) -- get strings
428 ilxExprClosures env (StgLet bind body)
429   = ilxBindClosures env bind $$ ilxExprClosures (extendIlxEnvWithBinds env (ilxPairs1 bind)) body
430 ilxExprClosures env (StgLetNoEscape _ _ bind body)  -- TO DO????
431   = ilxBindClosures env bind $$ ilxExprClosures (extendIlxEnvWithBinds env (ilxPairs1 bind)) body
432 ilxExprClosures env (StgCase scrut _ _ _ _ alts)
433   = ilxExprClosures (ilxPlaceStgCaseScrut env) scrut $$ ilxAltsClosures env alts 
434 ilxExprClosures env (StgLit lit) 
435   = ilxGenLit env lit 
436 ilxExprClosures _ _ 
437   = empty
438
439 ilxAltsClosures env (StgAlgAlts _ alts deflt)
440   = vcat [ilxExprClosures (ilxPlaceAlt env i) rhs | (i,(_, _, _, rhs))  <- [1..] `zip` alts]
441     $$ 
442     ilxDefltClosures env deflt
443
444 ilxAltsClosures env (StgPrimAlts _ alts deflt)
445   = vcat [ilxExprClosures (ilxPlaceAlt env i) rhs | (i,(_, rhs)) <- [1..] `zip` alts]
446     $$ 
447     vcat [ ilxGenLit (ilxPlacePrimAltLit env i) lit | (i,(lit,_)) <- [1..] `zip` alts]
448     $$ 
449     ilxDefltClosures  env deflt
450
451 ilxDefltClosures env (StgBindDefault rhs) = ilxExprClosures (ilxPlaceStgBindDefault env) rhs
452 ilxDefltClosures _ StgNoDefault   = empty
453
454 ilxArgClosures env (StgLitArg lit) = ilxGenLit env lit 
455 ilxArgClosures _ _ = empty
456
457
458
459 ilxGenLit env (MachStr fs) 
460   = vcat [text ".field static assembly char "  <+> singleQuotes nm <+> text "at" <+> nm <> text "L",
461           text ".data" <+> nm <> text "L" <+> text "= char *("  <> pprFSInILStyle fs  <> text ")"
462          ]
463  where
464    nm = ilxEnvQualifyByExact env (text "string")
465
466 ilxGenLit  _ _ = empty
467
468 \end{code}
469
470
471 %************************************************************************
472 %*                                                                      *
473 \subsection{Generating code}
474 %*                                                                      *
475 %************************************************************************
476
477
478 \begin{code}
479
480 -- Environment when generating expressions
481 data IlxEEnv = IlxEEnv IlxEnv (UniqSet Id)
482
483 data Sequel = Return | Jump IlxLabel
484
485 ilxSequel Return     = text "ret"
486 ilxSequel (Jump lbl) = text "br" <+> pprIlxLabel lbl
487
488 isReturn Return = True
489 isReturn (Jump _) = False
490
491
492 ilxExpr :: IlxEEnv -> StgExpr 
493         -> Sequel       -- What to do at the end
494         -> SDoc
495
496 ilxExpr (IlxEEnv env _) (StgApp fun args) sequel
497   = ilxFunApp env fun args (isReturn sequel) $$ ilxSequel sequel
498
499 -- ilxExpr eenv (StgLit lit) sequel
500 ilxExpr (IlxEEnv env _) (StgLit lit) sequel
501   = pushLit env lit $$ ilxSequel sequel
502
503 -- ilxExpr eenv (StgConApp data_con args) sequel
504 ilxExpr (IlxEEnv env _) (StgConApp data_con args) sequel
505   = text " /* ilxExpr:StgConApp */ " <+>  ilxConApp env data_con args $$ ilxSequel sequel
506
507 -- ilxExpr eenv (StgPrimApp primop args _) sequel
508 ilxExpr (IlxEEnv env _) (StgOpApp (StgFCallOp fcall _) args ret_ty) sequel
509   = ilxFCall env fcall args ret_ty $$ ilxSequel sequel
510
511 ilxExpr (IlxEEnv env _) (StgOpApp (StgPrimOp primop) args ret_ty) sequel
512   = ilxPrimOpTable primop args env $$ ilxSequel sequel
513
514 --BEGIN TEMPORARY
515 -- The following are versions of a peephole optimizations for "let t = \[] t2[fvs] in t"
516 -- I think would be subsumed by a general treatmenet of let-no-rec bindings??
517 ilxExpr eenv@(IlxEEnv env _) (StgLet (StgNonRec _ bndr (StgRhsClosure _ _ _ _ [] rhs)) (StgApp fun [])) sequel 
518               | (bndr == fun && null (ilxExprLocals env rhs)) -- TO DO???
519   = ilxExpr eenv rhs sequel
520 ilxExpr eenv@(IlxEEnv env _) (StgLetNoEscape _ _ (StgNonRec _ bndr (StgRhsClosure _ _ _ _ [] rhs)) (StgApp fun [])) sequel 
521               | (bndr == fun && null (ilxExprLocals env rhs)) -- TO DO???
522   = ilxExpr eenv rhs sequel
523 --END TEMPORARY
524
525 ilxExpr eenv (StgLet bind body) sequel
526   = ilxBind eenv bind $$ ilxExpr eenv body sequel
527
528
529 ilxExpr eenv (StgLetNoEscape _ _ bind body) sequel -- TO DO???
530   = ilxBind eenv bind $$ ilxExpr eenv body sequel
531
532 -- StgCase: Special case 1 to avoid spurious branch.
533 ilxExpr eenv@(IlxEEnv env live) (StgCase (StgApp fun args) live_in_case _live_in_alts bndr _ alts) sequel
534   = vcat [ilxWipe env (uniqSetToList (live `minusUniqSet` live_in_case)),
535           ilxFunApp (ilxPlaceStgCaseScrut env) fun args False,
536           --ilxWipe env (uniqSetToList (live_in_case `minusUniqSet` _live_in_alts)),
537           --ilxAlts (IlxEEnv env _live_in_alts) bndr alts sequel
538           ilxAlts (IlxEEnv env live_in_case) bndr alts sequel
539     ]
540
541 -- StgCase: Special case 2 to avoid spurious branch.
542 ilxExpr eenv@(IlxEEnv env live) (StgCase (StgOpApp (StgPrimOp primop) args ret_ty) live_in_case _live_in_alts bndr _ alts) sequel
543   = vcat [ilxWipe env (uniqSetToList (live `minusUniqSet` live_in_case)),
544           ilxPrimOpTable primop args (ilxPlaceStgCaseScrut env),
545           --ilxWipe env (uniqSetToList (live_in_case `minusUniqSet` _live_in_alts)),
546           --ilxAlts (IlxEEnv env _live_in_alts) bndr alts sequel
547           ilxAlts (IlxEEnv env live_in_case) bndr alts sequel
548     ]
549
550 -- StgCase: Normal case.
551 ilxExpr eenv@(IlxEEnv env live) (StgCase scrut live_in_case _live_in_alts bndr _ alts) sequel
552   = vcat [ilxWipe env (uniqSetToList (live `minusUniqSet` live_in_case)),
553           ilxExpr (IlxEEnv (ilxPlaceStgCaseScrut env) live_in_case) scrut (Jump join_lbl),
554           ilxLabel join_lbl,
555           --ilxWipe env (uniqSetToList (live_in_case `minusUniqSet` _live_in_alts)),
556           --ilxAlts (IlxEEnv env _live_in_alts) bndr alts sequel
557           ilxAlts (IlxEEnv env live_in_case) bndr alts sequel
558     ]
559   where
560     join_lbl = mkJoinLabel bndr
561
562 ilxExpr _ _ _ 
563   = panic "ilxExpr:  Patterns not matched:(IlxEEnv _ _) (StgSCC _ _) _ (IlxEEnv _ _) (StgLam _ _ _) _"
564
565
566 -- Wipe out locals and arguments that are no longer in use, to
567 -- prevent space leaks. If the VM is implemented 100% correctly then
568 -- this should probably not be needed, as the live variable analysis
569 -- in the JIT would tell the GC that these locals and arguments are
570 -- no longer live.  However I'm putting it in here so we can
571 -- check out if it helps.
572 --
573 -- Also, in any case this doesn't capture everything we need.  e.g.
574 -- when making a call:
575 --     case f x of ...
576 -- where x is not used in the alternatives, then the variable x
577 -- is no longer live from the point it is transferred to the call
578 -- onwards.  We should expunge "live_in_case - live_in_alts" right
579 -- before making the call, not after returning from the call....
580 --
581 -- Strictly speaking we also don't need to do this for primitive
582 -- values such as integers and addresses, i.e. things not
583 -- mapped down to GC'able objects.
584 ilxWipe env ids 
585    = vcat (map (ilxWipeOne env) (filter (not.isVoidIlxRepId) ids))
586
587 ilxWipeOne env id
588    = case lookupIlxVarEnv env id of
589           Just Local  -> text "ldloca " <+> pprId id <+> text "initobj" <+> (ilxTypeL env (idIlxRepType id))
590           Just Arg   -> text "deadarg " <+> pprId id <+> text "," <+> (ilxTypeL env (idIlxRepType id))
591           Just (CloVar _)  -> ilxComment (text "not yet wiping closure variable" <+> pprId id )
592           _ -> ilxComment (text "cannot wipe non-local/non-argument" <+> pprId id )
593   where 
594       
595
596 ----------------------
597
598 ilxAlts :: IlxEEnv -> Id -> StgCaseAlts -> Sequel -> SDoc
599 ilxAlts (IlxEEnv env live) bndr alts sequel
600         -- At the join label, the result is on top
601         -- of the stack
602   = vcat [store_in_bndr,
603           do_case_analysis alts
604     ]
605   where
606     scrut_rep_ty = deepIlxRepType (idType bndr)
607
608     store_in_bndr | isDeadBinder bndr = empty
609                   | isVoidIlxRepId bndr 
610                         = ilxComment (text "ignoring store of zero-rep value to be analyzed")
611                   | otherwise         = text "dup" $$ (text "stloc" <+> pprId bndr)
612
613     do_case_analysis (StgAlgAlts _ []    deflt)
614         = do_deflt deflt
615
616     do_case_analysis (StgAlgAlts _ args deflt) 
617         = do_alg_alts ([1..] `zip` args) deflt
618
619     do_case_analysis (StgPrimAlts _ alts deflt)
620         = do_prim_alts ([1..] `zip` alts) $$ do_deflt deflt
621
622     do_alg_alts [(i, alt@(data_con,bndrs,used_flags, rhs))] StgNoDefault | isUnboxedTupleCon data_con
623       -- Collapse the analysis of unboxed tuples where 
624       -- some or all elements are zero-sized
625       --
626       -- TO DO: add bndrs to set of live variables
627           = case bndrs' of
628                   [h] -> bind_collapse bndrs used_flags <+> do_rhs_no_pop alt_env rhs
629                   _ -> bind_components alt_env dcon' bndrs 0 used_flags <+> do_rhs alt_env rhs
630            where 
631             bndrs' = filter (not. isVoidIlxRepId) bndrs
632             -- Replacement unboxed tuple type constructor, used if any of the
633             -- arguments have zero-size and more than one remains.
634             dcon'  = tupleCon Unboxed (length bndrs')
635
636             alt_env = IlxEEnv (ilxPlaceAlt env i) live
637             --alt_env = IlxEEnv (ilxPlaceAlt env i) 
638
639             bind_collapse [] _ = panic "bind_collapse: unary element not found"
640             bind_collapse (h:t) (is_used:used_flags) 
641                 | isVoidIlxRepId h = ilxComment (text "zero-rep binding eliminated") <+> (bind_collapse t used_flags)
642                 | not is_used = ilxComment (text "not used") <+> text "pop"
643                 | otherwise = text "stloc" <+> pprId h
644
645
646     do_alg_alts [(i, alt@(data_con,bndrs,used_flags, rhs))] StgNoDefault 
647             = vcat [text "castdata" <+> sep [ilxTypeR env scrut_rep_ty <> comma,
648                                              ilxConRef env data_con],
649                 do_alg_alt (IlxEEnv (ilxPlaceAlt env i) live) alt
650               ]
651
652     do_alg_alts alts deflt
653         = vcat [text "datacase" <+> sep [ilxTypeR env scrut_rep_ty,text ",",
654                                          pprSepWithCommas pp_case labels_w_alts],
655                 do_deflt deflt,
656                 vcat (map do_labelled_alg_alt labels_w_alts)
657           ]
658         where
659           pp_case (i, (lbl, (data_con, _, _, _))) = parens (ilxConRef env data_con <> comma <> pprIlxLabel lbl)
660           labels_w_alts = [(i,(mkAltLabel bndr i, alt)) | (i, alt) <- alts]
661
662     do_prim_alts [] = empty
663     do_prim_alts ((i, (lit,alt)) : alts) 
664         = vcat [text "dup", pushLit (ilxPlacePrimAltLit env i) lit, text "bne.un" <+> pprIlxLabel lbl, 
665                 do_rhs (IlxEEnv (ilxPlaceAlt env i) live) alt, 
666                 ilxLabel lbl, do_prim_alts alts]
667         where
668           lbl = mkAltLabel bndr i
669
670     do_labelled_alg_alt (i,(lbl, alt)) 
671         = ilxLabel lbl $$ do_alg_alt (IlxEEnv (ilxPlaceAlt env i) live) alt
672
673     do_alg_alt alt_eenv (data_con, bndrs, used_flags, rhs) 
674       = vcat [bind_components alt_eenv data_con bndrs 0 used_flags,
675               do_rhs alt_eenv rhs
676              ]
677
678     bind_components alt_eenv data_con [] n _ = empty
679     bind_components alt_eenv data_con (h:t) n (is_used:used_flags) 
680        | isVoidIlxRepId h 
681              -- don't increase the count in this case
682              = ilxComment (text "zero-rep binding eliminated") 
683                <+> bind_components alt_eenv data_con t n used_flags
684        | otherwise 
685              = bind_component alt_eenv data_con h is_used n 
686                <+> bind_components alt_eenv data_con t (n + 1) used_flags
687
688     bind_component alt_eenv@(IlxEEnv alt_env _) data_con bndr is_used reduced_fld_no 
689         | not is_used 
690             = ilxComment (text "not used")
691         | isVoidIlxRepId bndr 
692             = ilxComment (text "ignoring bind of zero-rep variable")
693         | otherwise   = vcat [text "dup",
694                               ld_data alt_env data_con reduced_fld_no bndr,
695                               text "stloc" <+> pprId bndr]
696
697     do_deflt (StgBindDefault rhs) = do_rhs (IlxEEnv (ilxPlaceStgBindDefault env) live) rhs
698     do_deflt StgNoDefault         = empty
699
700     do_rhs alt_eenv rhs  
701         | isVoidIlxRepId bndr = do_rhs_no_pop alt_eenv rhs     -- void on the stack, nothing to pop
702         | otherwise = text "pop" $$ do_rhs_no_pop alt_eenv rhs  -- drop the value
703
704     do_rhs_no_pop alt_env rhs = ilxExpr alt_env rhs sequel
705
706     ld_data alt_env data_con reduced_fld_no bndr
707       | isUnboxedTupleCon data_con
708       = text "ldfld" <+> sep [text "!" <> integer reduced_fld_no,
709                               ilxTypeR alt_env scrut_rep_ty <> text "::fld" <> integer reduced_fld_no]
710       | otherwise 
711       = text "lddata" <+> sep [ilxTypeR alt_env scrut_rep_ty <> comma, 
712                                ilxConRef env data_con <> comma,
713                                integer reduced_fld_no]
714
715
716 -------------------------
717
718 ilxBestTermArity = 3
719 ilxBestTypeArity = 7
720
721
722 -- Constants of unlifted types are represented as
723 -- applications to no arguments.
724 ilxFunApp env fun [] _ | isUnLiftedType (idType fun)
725   = pushId env fun
726
727 ilxFunApp env fun args tail_call 
728   =     -- For example:
729         --      ldloc f         function of type forall a. a->a
730         --      ldloc x         arg of type Int
731         --      .tail callfunc <Int32> (!0) --> !0
732         --
733     vcat [pushId env fun,ilxFunAppAfterPush env fun args tail_call]
734
735 ilxFunAppAfterPush env fun args tail_call 
736   =     -- For example:
737         --      ldloc f         function of type forall a. a->a
738         --      ldloc x         arg of type Int
739         --      .tail callfunc <Int32> (!0) --> !0
740         --
741     vcat [ilxFunAppArgs env 0 (idIlxRepType fun) args tail_call known_clo]
742   where
743     known_clo :: KnownClosure
744     known_clo =
745       case lookupIlxBindEnv env fun of
746           Just (_, StgRhsClosure  _ _ _ Updatable _ _)   -> Nothing 
747           Just (place, StgRhsClosure  _ _ fvs _ args _)  -> Just (place,fun,args,fvs)
748           _ ->  trace (show fun ++ " --> " ++ show (arityLowerBound (idArityInfo fun)))  Nothing 
749
750 type KnownClosure = Maybe (  IlxEnv     -- Of the binding site of the function
751                            , Id         -- The function
752                            , [Var]      -- Binders
753                            , [Var])     -- Free vars of the closure
754
755 -- Push as many arguments as ILX allows us to in one go, and call the function
756 -- Recurse until we're done.
757 -- The function is already on the stack
758 ilxFunAppArgs :: IlxEnv
759               -> Int            -- Number of args already pushed (zero is a special case;
760                                 --      otherwise used only for place generation)
761               -> Type           -- Type of the function
762               -> [StgArg]       -- The arguments
763               -> Bool           -- True <=> tail call please
764               -> KnownClosure   -- Information about the function we're calling
765               -> SDoc
766
767 ilxFunAppArgs env num_sofar funty args tail_call known_clo
768  =   vcat [vcat (ilxMapPlaceArgs num_sofar pushArgWithVoids env now_args),
769            call_instr <+> (if num_sofar == 0 then text "() /* first step in every Haskell app. is to a thunk */ " else empty)
770                      <+> now_args_text
771                      <+> text "-->" 
772                      <+> later_ty_text,
773            later
774           ]
775   where
776     now_args_text = 
777       case now_arg_tys of
778         [] -> empty
779         _ -> hsep (map (pprIlxArgInfo env_after_now_tyvs) now_arg_tys)
780
781     later_ty_text
782         | isVoidIlxRepType later_ty = text "void"
783         | otherwise = ilxTypeR env_after_now_tyvs later_ty
784
785     (now_args,now_arg_tys,env_after_now_tyvs,later_args,later_ty) = 
786         case args of
787           (StgTypeArg v:rest) -> get_type_args ilxBestTypeArity args env funty
788           _ -> get_term_args 0 ilxBestTermArity args env funty
789
790      -- Only apply up to maxArity real (non-type) arguments
791      -- at a time.  ILX should, in principle, allow us to apply
792      -- arbitrary numbers, but you will get more succinct 
793      -- (and perhaps more efficient) IL code
794      -- if you apply in clumps according to its maxArity setting.
795      -- This is because it has to unwind the stack and store it away
796      -- in local variables to do the partial applications.
797      --
798      -- Similarly, ILX only allows one type application at a time, at
799      -- least until we implement unwinding the stack for this case.
800      --
801      -- NB: In the future we may have to be more careful 
802      -- all the way through 
803      -- this file to bind type variables as we move through
804      -- type abstractions and "forall" types.  This would apply
805      -- especially if the type variables were ever bound by expressions
806      -- involving the type variables.  
807
808     -- This part strips off at most "max" term applications or one type application
809     get_type_args 0 args env funty = ([],[],env,args,funty)
810     get_type_args max args env (NoteTy _ ty) = 
811           trace "IlxGen Internal Error: non representation type passed to get_args" (get_type_args max args env ty)
812     get_type_args max ((arg@(StgTypeArg v)):rest) env (ForAllTy tv rem_funty) 
813         = if isIlxTyVar tv then 
814             let env2 = extendIlxEnvWithFormalTyVars env [tv] in 
815             let rest_ty = deepIlxRepType (substTy (mkTyVarSubst [tv] [v]) rem_funty) in 
816             let (now,now_tys,env3,later,later_ty) = get_type_args (max - 1) rest env rest_ty in 
817             let arg_ty = mkTyVarTy tv in 
818             (arg:now,(arg,arg_ty):now_tys,env2, later, later_ty)
819           else 
820              get_type_args max rest env rem_funty  -- ? subst??
821     get_type_args _ (StgTypeArg _:_) _ _ = trace "IlxGen Internal Error: get_type_args could not get ForAllTy for corresponding arg" ([],[],env,[],funty)
822     get_type_args _ args env funty = ([],[],env,args,funty)
823
824     get_term_args n max args env (NoteTy _ ty)
825        -- Skip NoteTy types 
826        = trace "IlxGen Internal Error: non representation type passed to get_term_args" (get_term_args n max args env ty)
827     get_term_args n 0 args env funty
828        -- Stop if we've hit the maximum number of ILX arguments to apply n one hit.
829        = ([],[],env,args,funty)
830     get_term_args n max args env funty
831       | (case known_clo of
832            Just (_,_,needed,_) -> (length needed == n)
833            Nothing -> False)
834        -- Stop if we have the optimal number for a direct call
835        = ([],[],env,args,funty)
836     get_term_args _ _ (args@(StgTypeArg _:_)) env funty 
837        -- Stop if we hit a type arg.
838        = ([],[],env,args,funty)
839     get_term_args n max (h:t) env (FunTy dom ran)
840        -- Take an argument.
841        = let (now,now_tys,env2,later,later_ty) = get_term_args (n+1) (max - 1) t env ran in 
842          (h:now, (h,dom):now_tys,env2,later,later_ty)
843     get_term_args _ max (h:t) env funty = trace "IlxGen Internal Error: get_term_args could not get FunTy or ForAllTy for corresponding arg" ([],[],env,[],funty)
844     get_term_args _ max args env funty = ([],[],env,args,funty)
845
846     -- Are there any remaining arguments?
847     done  = case later_args of
848           [] -> True
849           _ -> False
850
851     -- If so, generate the subsequent calls.
852     later = if done then text "// done"  
853             else ilxFunAppArgs env (num_sofar + length now_args) later_ty later_args tail_call Nothing
854
855     -- Work out whether to issue a direct call a known closure (callclo) or
856     -- an indirect call (callfunc).  Basically, see if the identifier has
857     -- been let-bound, and then check we are applying exactly the right 
858     -- number of arguments.  Also check that it's not a thunk (actually, this
859     -- is done up above).
860     -- 
861     -- The nasty "all" check makes sure that 
862     -- the set of type variables in scope at the callsite is a superset 
863     -- of the set of type variables needed for the direct call.  This is
864     -- is needed because not all of the type variables captured by a 
865     -- let-bound binding will get propogated down to the callsite, and 
866     -- the ILX system of polymorphism demands that the free type variables
867     -- get reapplied when we issue the direct "callclo".  The
868     -- type variables are in reality also "bound up" in the closure that is
869     -- passed as the first argument, so when we do an indirect call
870     -- to that closure we're fine, which is why we don't need them in 
871     -- the "callfunc" case.
872     basic_call_instr =
873       case known_clo of
874         Just (known_env,fun,needed,fvs) | (length needed == length now_args) && 
875                                           all (\x -> elemIlxTyEnv x env) free_ilx_tvs -> 
876            vcat [text "callclo class",
877                  nameReference env (idName fun) <+> singleQuotes (ilxEnvQualifyByModule env (ppr fun)),
878                  pprTypeArgs ilxTypeR env (map mkTyVarTy free_ilx_tvs)]
879            <> text ","
880           where 
881            (free_ilx_tvs, free_non_ilx_tvs,free_vs) = categorizeVars fvs
882         otherwise -> text "callfunc"
883     call_instr =
884            if (tail_call && done) then text "tail." <+> basic_call_instr
885            else basic_call_instr
886
887
888 --------------------------
889 -- Print the arg info at the call site
890 -- For type args we are, at the moment, required to
891 -- give both the actual and the formal (bound).  The formal
892 -- bound is always System.Object at the moment (bounds are
893 -- not properly implemented in ILXASM in any case, and nor do
894 -- we plan on making use og them) For
895 -- non-type args the actuals are on the stack, and we just give the
896 -- formal type.
897 pprIlxArgInfo env (StgTypeArg  arg,ty) =  
898     angleBrackets (ilxTypeR env (deepIlxRepType arg) <+> ilxComment (text "actual for tyvar")) <+> text "<class [mscorlib] System.Object>" 
899 pprIlxArgInfo env (_,ty) =  
900     parens (ilxTypeL env ty)
901
902
903 ----------------------------
904 -- Code for a binding
905 ilxBind :: IlxEEnv -> StgBinding -> SDoc
906 ilxBind eenv@(IlxEEnv env _) bind = 
907     vcat [vcat (map (ilxRhs env rec) pairs), 
908           vcat (map (ilxFixupRec env rec) pairs)]
909        where 
910          rec = ilxRecIds1 bind
911          pairs = ilxPairs1 bind
912
913
914 ----------------------------
915 -- Allocate a closure or constructor.  Fix up recursive definitions.
916 ilxRhs :: IlxEnv -> [Id] -> (Id, StgRhs) -> SDoc
917
918 ilxRhs env rec (bndr, _) | isVoidIlxRepId bndr  
919   = empty
920
921 ilxRhs env rec (bndr, StgRhsCon _ con args)
922   = vcat [text " /* ilxRhs:StgRhsCon */ " <+> ilxConApp env con args,
923            text "stloc" <+> pprId bndr
924           ]
925
926 ilxRhs env rec (bndr, StgRhsClosure _ _ fvs upd args rhs)
927   =     -- Assume .closure v<any A>(int64,!A) { 
928         --              .apply <any B> (int32) (B) { ... }
929         --         }
930         -- Then
931         --    let v = \B (x:int32) (y:B). ... 
932         -- becomes:
933         --    newclo v<int32>(int64,!0)
934         --    stloc v
935     vcat [vcat (map pushFv free_vs),
936           (if null free_non_ilx_tvs then empty else (ilxComment (text "ignored some higher order type arguments in application - code will be non-verifiable"))),
937           text "newclo" <+> clotext,
938           text "stloc" <+> pprId bndr
939     ]
940   where
941     pushFv id = if elem id rec then text "ldnull" else pushId env id
942     (free_ilx_tvs, free_non_ilx_tvs,free_vs) = categorizeVars fvs
943     clotext = pprIlxBoxedTyConApp env (ilxEnvQualifyByModule env (ppr bndr)) (map mkTyVarTy free_ilx_tvs)
944
945 ilxFixupRec env rec (bndr, _) | isVoidIlxRepId bndr = ilxComment (text "no recursive fixup for void-rep-id")
946
947 ilxFixupRec env rec (bndr, StgRhsCon _ con args)
948   = text "// no recursive fixup"
949
950 ilxFixupRec env rec (bndr, StgRhsClosure _ _ fvs upd args rhs)
951      = vcat [vcat (map fixFv rec)]
952   where
953     fixFv recid = if elem recid fvs then 
954                     vcat [pushId env bndr,
955                           pushId env recid,
956                           text "stclofld" <+> clotext <> text "," <+> pprId recid] 
957                 else text "//no fixup needed for" <+> pprId recid
958     (free_ilx_tvs, free_non_ilx_tvs,free_vs) = categorizeVars fvs
959     clotext = pprIlxBoxedTyConApp env (ilxEnvQualifyByModule env (ppr bndr)) (map mkTyVarTy free_ilx_tvs)
960
961
962
963 ---------------------------------------------
964 -- Code for a top-level binding in a module
965 ilxPairs binds = concat (map ilxPairs1 binds)
966
967 ilxPairs1 (StgNonRec _ bndr rhs) = [(bndr,rhs)]
968 ilxPairs1 (StgRec _ pairs)       = pairs
969
970 ilxRecIds1 (StgNonRec _ bndr rhs) = []
971 ilxRecIds1 (StgRec _ pairs)       = map fst pairs
972
973 ---------------------------------------------
974 -- Code for a top-level binding in a module
975 -- TODO: fix up recursions amongst CAF's
976 -- e.g. 
977 --    x = S x
978 -- for infinity...
979 -- 
980 -- For the moment I've put in a completely spurious "reverse"...
981 --
982 -- Consider: make fixing up of CAF's part of ILX?  i.e.
983 -- put static, constant, allocated datastructures into ILX. 
984
985 stableSortBy :: (a -> a -> Ordering) -> [a] -> [a]
986 stableSortBy f (h:t) = insertBy f h (stableSortBy f t)
987 stableSortBy f [] = []
988
989 usedBy :: (Id,StgRhs) -> (Id,StgRhs) -> Ordering
990 usedBy (m,_) (_,StgRhsCon _ data_con args) | any (isArg m) args = LT
991 usedBy (m,_) (n,_) | m == n = EQ
992 usedBy (m,_) (_,_) = GT
993
994 isArg m  (StgVarArg n) = (n == m)
995 isArg m _ = False
996
997
998 ilxTopBind :: Module -> IlxEnv -> [(Id,StgRhs)] -> SDoc
999 --ilxTopBind mod env (StgNonRec _ bndr rhs) = 
1000 --ilxTopRhs env (bndr,rhs)
1001 ilxTopBind mod env pairs       = 
1002    vcat [text ".class" <+> pprId mod,
1003          nest 2 (braces (nest 2 (vcat [empty,cctor, flds, empty])))]
1004      where
1005        cctor = vcat [text ".method static rtspecialname specialname void .cctor()",
1006                      nest 2 (braces 
1007                       (nest 2 (vcat [text ".maxstack 100",
1008                                      text "ldstr \"LOG: initializing module" <+> pprId mod <+> text "\" call void ['mscorlib']System.Console::WriteLine(class [mscorlib]System.String)",
1009                                      vcat (map (ilxTopRhs mod env) (stableSortBy usedBy pairs)), 
1010                                      text "ldstr \"LOG: initialized module" <+> pprId mod <+> text "\" call void ['mscorlib']System.Console::WriteLine(class [mscorlib]System.String)",
1011                                      text "ret",
1012                                      empty])))]
1013        flds =   vcat (map (ilxTopRhsStorage mod env) pairs)
1014
1015 --ilxTopRhs mod env (bndr, _) | isVoidIlxRepId bndr 
1016 --  = empty
1017
1018 ilxTopRhs mod env (bndr, StgRhsClosure _ _ fvs upd args rhs)
1019   = vcat [vcat (map (pushId env) free_vs),
1020          (if null free_non_ilx_tvs then empty else (ilxComment (text "ignored some higher order type arguments in application - code will be non verifiable...."))),
1021           text "newclo" <+> pprIlxBoxedTyConApp env (ilxEnvQualifyByModule env (ppr bndr)) (map mkTyVarTy free_ilx_tvs),
1022           text "stsfld"  <+> pprFieldRef env (mod,bndTy,bndr)
1023     ]
1024   where
1025     (free_ilx_tvs, free_non_ilx_tvs,free_vs) = categorizeVars fvs
1026     bndTy = idIlxRepType bndr
1027
1028 ilxTopRhs mod env (bndr, StgRhsCon _ data_con args)
1029   = vcat [ text " /* ilxTopRhs: StgRhsCon */ " <+> ilxConApp env data_con args, 
1030            text "stsfld" <+> pprFieldRef env (mod,bndTy,bndr)
1031     ]
1032   where
1033     bndTy = idIlxRepType bndr
1034
1035 pprFieldRef env (mod,ty,id) 
1036   =  ilxTypeL env ty <+> moduleReference env mod <+> pprId mod <> text "::" <> pprId id
1037
1038 ilxTopRhsStorage mod env (bndr, StgRhsClosure _ _ _ _ _ _) 
1039   =   text ".field public static " <+> ilxTypeL env bndTy <+> pprId bndr
1040   where
1041     bndTy = idIlxRepType bndr
1042 ilxTopRhsStorage mod env (bndr, StgRhsCon _ _ _) 
1043   =   text ".field public static " <+> ilxTypeL env bndTy <+> pprId bndr
1044   where
1045     bndTy = idIlxRepType bndr
1046
1047 --------------------------------------
1048 -- Push an argument
1049 pushArgWithVoids =  pushArg_aux True
1050 pushArg = pushArg_aux False
1051
1052 pushArg_aux voids env (StgTypeArg ty) = empty
1053 pushArg_aux voids env (StgVarArg var) = pushId_aux voids env var
1054 pushArg_aux voids env (StgLitArg lit) = pushLit env lit
1055
1056
1057 mapi f l = mapi_aux f l 0
1058
1059 mapi_aux f [] n = []
1060 mapi_aux f (h:t) n = f n h : mapi_aux f t (n+1)
1061
1062 --------------------------------------
1063 -- Push an Id
1064 pushId = pushId_aux False
1065
1066 pushId_aux :: Bool -> IlxEnv -> Id -> SDoc
1067 pushId_aux voids _ id | isVoidIlxRepId id =
1068    /* if voids then  text "ldunit" else */ ilxComment (text "pushId: void rep skipped")
1069 pushId_aux _ env var 
1070   = case lookupIlxVarEnv env var of
1071           Just Arg    -> text "ldarg"    <+> pprId var
1072           Just (CloVar n) -> text "ldenv" <+> int n
1073           Just Local  -> text "ldloc"    <+> pprId var
1074           Just (Top m)  -> 
1075              vcat [ilxComment (text "pushId (Top) " <+> pprId m), 
1076                    text "ldsfld" <+> ilxTypeL env (idIlxRepType var)
1077                       <+> moduleReference env m <+> pprId (moduleName m) <> text "::" <> pprId var]
1078
1079           Nothing ->  
1080              vcat [ilxComment (text "pushId (import) " <+> pprIlxTopVar env var), 
1081                    text "ldsfld" <+> ilxTypeL env (idIlxRepType var) 
1082                     <+> pprIlxTopVar env var]
1083
1084 --------------------------------------
1085 -- Push a literal
1086 pushLit env (MachChar c)   = text "ldc.i4" <+> int c
1087 pushLit env (MachStr s)    = text "ldsflda char "  <+> ilxEnvQualifyByExact env (text "string") -- pprFSInILStyle s 
1088 pushLit env (MachInt i)    = text "ldc.i4" <+> integer i
1089 pushLit env (MachInt64 i)  = text "ldc.i8" <+> integer i
1090 pushLit env (MachWord w)   = text "ldc.i4" <+> integer w <+> text "conv.u4"
1091 pushLit env (MachWord64 w) = text "ldc.i8" <+> integer w <+> text "conv.u8"
1092 pushLit env (MachFloat f)  = text "ldc.r4" <+> rational f
1093 pushLit env (MachDouble f) = text "ldc.r8" <+> rational f
1094 pushLit env (MachLitLit _ _) = trace "WARNING: Cannot compile MachLitLit to ILX in IlxGen.lhs" (text "// MachLitLit!!!  Not valid in ILX!!")
1095 pushLit env (MachAddr w) = text "ldc.i4" <+> integer w <+> text "conv.i"
1096 pushLit env (MachLabel l) = trace "WARNING: Cannot compile MachLabel to ILX in IlxGen.lhs" (text "// MachLabel!!!  Not valid in ILX!!")
1097
1098 pprIlxTopVar env v
1099   | isGlobalName n = (nameReference env n) <> pprId (nameModule n) <> text "::" <> singleQuotes (ppr (nameModule n) <> text "_" <> ppr (nameOccName n))
1100   | otherwise      = pprId (nameOccName n)
1101   where
1102     n = idName v
1103
1104 \end{code}
1105
1106
1107 %************************************************************************
1108 %*                                                                      *
1109 \subsection{Printing types}
1110 %*                                                                      *
1111 %************************************************************************
1112
1113
1114 \begin{code}
1115
1116 isVoidIlxRepType (NoteTy   _ ty) = isVoidIlxRepType ty
1117 isVoidIlxRepType (TyConApp tc _) | (tyConPrimRep tc == VoidRep) = True
1118 isVoidIlxRepType (TyConApp tc tys) 
1119   = isUnboxedTupleTyCon tc && null (filter (not. isVoidIlxRepType) tys)
1120 isVoidIlxRepType _ = False
1121
1122 isVoidIlxRepId id = isVoidIlxRepType (idType id)
1123
1124
1125
1126 -- Get rid of all NoteTy and NewTy artifacts
1127 deepIlxRepType :: Type -> Type
1128 deepIlxRepType (FunTy l r)
1129   = FunTy (deepIlxRepType l) (deepIlxRepType r)
1130
1131 deepIlxRepType ty@(TyConApp tc tys) 
1132   =        -- collapse UnboxedTupleTyCon down when it contains VoidRep types.
1133            -- e.g.      (# State#, Int#, Int# #)  ===>   (# Int#, Int# #)
1134             if isUnboxedTupleTyCon tc then 
1135                let tys' = map deepIlxRepType (filter (not. isVoidIlxRepType) tys) in 
1136                case tys' of
1137                   [h] -> h
1138                   _ -> mkTupleTy Unboxed (length tys') tys'
1139             else 
1140               TyConApp tc (map deepIlxRepType tys)
1141 deepIlxRepType (AppTy f x)     = AppTy (deepIlxRepType f) (deepIlxRepType x)
1142 deepIlxRepType (ForAllTy b ty) = ForAllTy b (deepIlxRepType ty)
1143 deepIlxRepType (NoteTy   _ ty) = deepIlxRepType ty
1144 deepIlxRepType (SourceTy p)    = deepIlxRepType (sourceTypeRep p)
1145 deepIlxRepType ty@(TyVarTy tv) = ty
1146
1147 idIlxRepType id = deepIlxRepType (idType id)
1148
1149 --------------------------
1150 -- Some primitive type constructors are not thunkable.
1151 -- Everything else needs to be marked thunkable.
1152 ilxTypeL :: IlxEnv -> Type -> SDoc
1153
1154 ilxTypeL env ty | isUnLiftedType ty ||  isVoidIlxRepType ty = ilxTypeR env ty
1155 ilxTypeL env ty = text "thunk" <> angleBrackets (ilxTypeR env ty)
1156
1157
1158 --------------------------
1159 -- Print non-thunkable version of type.
1160 --
1161
1162 ilxTypeR :: IlxEnv -> Type -> SDoc
1163 ilxTypeR env ty | isVoidIlxRepType ty = text "/* unit skipped */"
1164 ilxTypeR env ty@(AppTy f _) | isTyVarTy f    = ilxComment (text "type app:" <+> pprType ty) <+> (text "class [mscorlib]System.Object")
1165 ilxTypeR env ty@(AppTy f x)     = trace "ilxTypeR: should I be beta reducing types?!" (ilxComment (text "ilxTypeR: should I be beta reducing types...") <+> ilxTypeR env (applyTy f x))
1166 ilxTypeR env (TyVarTy tv)       = ilxTyVar env tv
1167
1168 -- The following is a special rule for types constructed out of 
1169 -- higher kinds, e.g. Monad f or Functor f.  
1170 --
1171 -- The code below is not as general as it should be, but as I
1172 -- have no idea if this approach will even work, I'm going to
1173 -- just try it out on some simple cases arising from the prelude.
1174 ilxTypeR env ty@(TyConApp tc (h:t)) | isAlgTyCon tc && null (tyConTyVars tc)
1175    = ilxComment (text "what on earth? 2") <+> (ilxTypeR env (TyConApp tc t))
1176 ilxTypeR env ty@(TyConApp tc (h:t)) | isAlgTyCon tc && not (isIlxTyVar (hd (tyConTyVars tc)))
1177    = ilxTypeR env (TyConApp tc t)
1178 ilxTypeR env (TyConApp tc args) = ilxTyConApp env tc args
1179
1180   -- nb. the only legitimate place for VoidIlxRepTypes to occur in normalized IlxRepTypes 
1181   -- is on the left of an arrow
1182   --  We could probably eliminate all but a final occurrence of these.
1183 ilxTypeR env (FunTy arg res)| isVoidIlxRepType res 
1184     = pprIlxFunTy (ilxTypeL env arg) (text "void")
1185 ilxTypeR env (FunTy arg res)
1186     = pprIlxFunTy (ilxTypeL env arg) (ilxTypeR env res)
1187
1188 ilxTypeR env ty@(ForAllTy tv body_ty) | isIlxTyVar tv
1189   = parens (text "forall" <+> pprTyVarBinders env' [tv] <+> nest 2 (ilxTypeR env' body_ty))
1190     where
1191        env' = extendIlxEnvWithFormalTyVars env [tv]
1192
1193 ilxTypeR env ty@(ForAllTy tv body_ty) | otherwise
1194   = ilxComment (text "higher order type var " <+> pprId tv) <+>
1195     pprIlxFunTy (text "class [mscorlib]System.Object") (ilxTypeR env body_ty)
1196
1197 ilxTypeR env (NoteTy _ ty)       
1198    = trace "WARNING! non-representation type given to ilxTypeR: see generated ILX for context where this occurs"
1199      (vcat [text "/* WARNING! non-representation type given to ilxTypeR! */",
1200            ilxTypeR env ty ])
1201
1202 pprIlxFunTy dom ran = parens (hsep [text "func",parens dom,text "-->", ran])
1203
1204 ilxTyConApp env tc args =
1205    case lookupUFM tyPrimConTable (getUnique tc) of
1206         Just f  -> f args env
1207         Nothing -> 
1208             (if isUnboxedTupleTyCon tc then pprIlxUnBoxedTyConApp else pprIlxBoxedTyConApp)
1209               env ((nameReference env (getName tc)) <> (ppr tc)) args
1210
1211 pprIlxUnBoxedTyConApp env tcdoc args = text "value class" <+> tcdoc <> pprTypeArgs ilxTypeL env args
1212 pprIlxBoxedTyConApp env tcdoc args = text "class" <+> tcdoc <> pprTypeArgs ilxTypeR env args
1213
1214 -- Returns e.g: <Int32, Bool>
1215 pprTypeArgs f env tys = pprTypeArgs_aux f env (filter (not . isVoidIlxRepType) tys)
1216
1217 pprTypeArgs_aux f env []  = empty
1218 pprTypeArgs_aux f env tys = angleBrackets (pprSepWithCommas (f env) tys)
1219
1220
1221 pprTyVarBinders :: IlxEnv -> [TyVar] -> SDoc
1222 -- Returns e.g: <class [mscorlib]System.Object> <class [mscorlib]System.Object>
1223 -- plus a new environment with the type variables added.
1224 pprTyVarBinders env [] = empty
1225 pprTyVarBinders env tvs = angleBrackets (pprSepWithCommas (pprTyVarBinder_aux env) tvs)
1226
1227 pprTyVarBinder :: IlxEnv -> TyVar -> SDoc
1228 pprTyVarBinder env tv = 
1229     if isIlxTyVar tv then 
1230        angleBrackets (pprTyVarBinder_aux env tv)
1231     else
1232        ilxComment (text "higher order tyvar" <+> pprId tv <+> 
1233                          text ":" <+> ilxTypeR env (tyVarKind tv)) <+>
1234              ilxComment (text "omitted")
1235              -- parens (text "class [mscorlib]System.Object" <+> pprId tv)
1236
1237
1238 pprTyVarBinder_aux env tv = 
1239    ilxComment (text "tyvar" <+> pprId tv <+> text ":" <+> 
1240                         ilxTypeR env (tyVarKind tv)) <+>
1241              (text "class [mscorlib]System.Object")
1242
1243 -- Only a subset of Haskell types can be generalized using the type quantification
1244 -- of ILX
1245 isIlxForAllKind h = 
1246         ( h `eqKind` liftedTypeKind) ||
1247         ( h `eqKind` unliftedTypeKind) ||
1248         ( h `eqKind` openTypeKind)
1249
1250 isIlxTyVar v = isTyVar v && isIlxForAllKind (tyVarKind v)
1251
1252 categorizeVars fvs = (ilx_tvs, non_ilx_tvs, vs)
1253          where
1254            (tvs, vs) = partition isTyVar fvs
1255            (ilx_tvs, non_ilx_tvs) = categorizeTyVars tvs
1256
1257 categorizeTyVars tyvs = partition isIlxTyVar tyvs
1258
1259 pprValArgTys ppr_ty env tys = parens (pprSepWithCommas (ppr_ty env) tys)
1260
1261 pprId id = singleQuotes (ppr id)
1262
1263 \end{code}                      
1264
1265 %************************************************************************
1266 %*                                                                      *
1267 \subsection{IlxEnv}     
1268 %*                                                                      *
1269 %************************************************************************
1270
1271 \begin{code}
1272 type IlxTyEnv = [TyVar]
1273 emptyIlxTyEnv = []
1274
1275 -- Nb. There is currently no distinction between the kinds of type variables.
1276 -- We may need to add this to print out correct numbers, esp. for
1277 -- "forall" types
1278 extendIlxTyEnvWithFreeTyVars env tyvars = env ++ mkIlxTyEnv tyvars -- bound by .closure x<...> in a closure declared with type parameters
1279 extendIlxTyEnvWithFormalTyVars env tyvars = env ++ mkIlxTyEnv tyvars -- bound by "forall <...>" in a type
1280 extendIlxTyEnvWithTyArgs env tyvars = env ++ mkIlxTyEnv tyvars -- bound by "<...>" in a closure implementing a universal type
1281
1282 formalIlxTyEnv tyvars = mkIlxTyEnv tyvars
1283 mkIlxTyEnv tyvars = [ v | v <- tyvars, isIlxTyVar v ]
1284
1285 data HowBound = Top Module      -- Bound in a modules
1286               | Arg     -- Arguments to the enclosing closure
1287               | CloVar Int -- A free variable of the enclosing closure
1288                            -- The int is the index of the field in the 
1289                            -- environment
1290               | Local   -- Local let binding
1291
1292 -- The SDoc prints a unique name for the syntactic block we're currently processing,
1293 -- e.g. Foo_bar_baz when inside closure baz inside closure bar inside module Foo.
1294 data IlxEnv = IlxEnv (Module, IlxTyEnv, IdEnv HowBound,IdEnv (IlxEnv, StgRhs), Place,Bool)
1295 type Place = (SDoc,SDoc)
1296
1297 ilxTyVar  env tv
1298   = go 0 (ilxEnvTyEnv env)
1299   where
1300     go n []                 
1301       = pprTrace "ilxTyVar" (pprId tv <+> text "tv_env = { "
1302            <+> pprSepWithCommas
1303                  (\x -> pprId x <+> text ":" <+> ilxTypeR env (tyVarKind x)) 
1304                (ilxEnvTyEnv env) <+> text "}") 
1305         (char '!' <> pprId tv) 
1306     go n (x:xs)
1307       = {- pprTrace "go" (ppr (tyVarName tv) <+> ppr (tyVarName x)) -}
1308         (if tyVarName x== tyVarName tv then  char '!' <> int n <+> ilxComment (char '!' <> pprId tv) 
1309          else go (n+1) xs)
1310
1311 emptyIlxEnv :: Bool -> Module -> IlxEnv
1312 emptyIlxEnv trace mod = IlxEnv (mod, emptyIlxTyEnv, emptyVarEnv, emptyVarEnv, (ppr mod,empty),trace)
1313
1314 nextPlace place sdoc = place <> sdoc
1315 usePlace  place sdoc = place <> sdoc
1316
1317 ilxEnvModule (IlxEnv (m, _, _,  _, _,_)) = m
1318 ilxEnvSetPlace (IlxEnv (m, tv_env, id_env,  bind_env, (mod,exact),tr)) sdoc 
1319    = IlxEnv (m, tv_env, id_env,  bind_env, (mod, sdoc),tr)
1320 ilxEnvNextPlace (IlxEnv (m, tv_env, id_env,  bind_env, (mod,exact),tr)) sdoc 
1321    = IlxEnv (m, tv_env, id_env,  bind_env, (mod, nextPlace exact sdoc),tr)
1322 ilxEnvQualifyByModule (IlxEnv (_, _, _, _,(mod,_),_)) sdoc = usePlace mod sdoc
1323 ilxEnvQualifyByExact (IlxEnv (_, _, _, _,(mod,exact),_)) sdoc = usePlace mod sdoc <> usePlace exact sdoc
1324
1325 ilxPlaceStgBindDefault env = ilxEnvNextPlace env (text "D")
1326 ilxPlaceStgRhsClosure env bndr = ilxEnvSetPlace env (ppr bndr) -- binders are already unique
1327 ilxPlaceStgCaseScrut env = ilxEnvNextPlace env (text "S")
1328
1329 ilxPlaceAlt :: IlxEnv -> Int -> IlxEnv
1330 ilxPlaceAlt env i = ilxEnvNextPlace env (text "a" <> int i)
1331 ilxPlacePrimAltLit env i = ilxEnvNextPlace env (text "P" <> int i)
1332 ilxMapPlaceArgs start f env args = [ f (ilxEnvNextPlace env (text "A" <> int i)) a | (i,a) <- [start..] `zip` args ]
1333 ilxMapPlaceAlts f env alts = [ f (ilxPlaceAlt env i) alt | (i,alt) <- [1..] `zip` alts ]
1334
1335 extendIlxEnvWithFreeTyVars (IlxEnv (mod, tv_env, id_env,  bind_env, place,tr)) tyvars 
1336   = IlxEnv (mod, extendIlxTyEnvWithFreeTyVars tv_env tyvars,id_env,  bind_env, place,tr)
1337
1338 extendIlxEnvWithFormalTyVars (IlxEnv (mod, tv_env, id_env,  bind_env, place,tr)) tyvars 
1339   = IlxEnv (mod, extendIlxTyEnvWithFormalTyVars tv_env tyvars,id_env,  bind_env, place,tr)
1340
1341 extendIlxEnvWithTyArgs (IlxEnv (mod, tv_env, id_env,  bind_env, place,tr)) tyvars 
1342   = IlxEnv (mod, extendIlxTyEnvWithTyArgs tv_env tyvars,id_env,  bind_env, place,tr)
1343
1344 extendIlxEnvWithArgs :: IlxEnv -> [Var] -> IlxEnv
1345 extendIlxEnvWithArgs (IlxEnv (mod, tv_env, id_env,  bind_env, place,tr)) args
1346   = IlxEnv (mod, extendIlxTyEnvWithTyArgs tv_env [tv      | tv <- args, isIlxTyVar tv],
1347             extendVarEnvList id_env [(v,Arg) | v  <- args, not (isIlxTyVar v)], 
1348              bind_env, place,tr)
1349
1350 extendIlxEnvWithFreeVars (IlxEnv (mod, tv_env, id_env,  bind_env, place,tr)) args
1351   = IlxEnv (mod, 
1352             extendIlxTyEnvWithFreeTyVars tv_env [tv | tv <- args, isIlxTyVar tv],
1353             extendVarEnvList id_env (clovs 0 args), 
1354             bind_env, 
1355             place,tr)
1356    where
1357      clovs _ [] = []
1358      clovs n (x:xs) = if not (isIlxTyVar x) then (x,CloVar n):clovs (n+1) xs else clovs n xs
1359
1360 extendIlxEnvWithBinds env@(IlxEnv (mod, tv_env, id_env, bind_env, place,tr)) bnds
1361   = IlxEnv (mod, tv_env, id_env, 
1362             extendVarEnvList bind_env [(v,(env,rhs)) | (v,rhs) <- bnds], 
1363             place,tr)
1364
1365 extendIlxEnvWithLocals (IlxEnv (m, tv_env, id_env, bind_env, p,tr)) locals
1366   = IlxEnv (m, tv_env, 
1367             extendVarEnvList id_env [(v,Local) | (LocalId v,_) <- locals],
1368             extendVarEnvList bind_env [(v,(env,rhs)) | (LocalId v,Just (env,rhs)) <- locals], 
1369             p,tr)
1370 extendIlxEnvWithTops env@(IlxEnv (m, tv_env, id_env, bind_env, place,tr)) mod binds
1371   = IlxEnv (m, tv_env, 
1372             extendVarEnvList id_env [(bndr,Top mod) | (bndr,rhs) <- binds], 
1373             extendVarEnvList bind_env [(bndr,(env, rhs)) | (bndr,rhs) <- binds], 
1374             place,tr)
1375
1376 formalIlxEnv (IlxEnv (m, tv_env, id_env, bind_env, place, tr)) tyvars 
1377   = IlxEnv (m, formalIlxTyEnv tyvars, id_env, bind_env, place, tr)
1378
1379 ilxEnvTyEnv :: IlxEnv -> IlxTyEnv
1380 ilxEnvTyEnv (IlxEnv (_, tv_env, _,_,_,_)) = tv_env 
1381 elemIlxTyEnv var env = elem var (ilxEnvTyEnv env )
1382 elemIlxVarEnv var (IlxEnv (_, _, id_env,_,_,_)) = elemVarEnv var id_env 
1383 lookupIlxVarEnv (IlxEnv (_, _, id_env,_,_,_)) var = lookupVarEnv id_env var
1384 lookupIlxBindEnv (IlxEnv (_, _, _, bind_env,_,_)) var = lookupVarEnv bind_env var
1385
1386 \end{code}
1387
1388
1389 \begin{code}
1390 type IlxLabel = SDoc
1391
1392 pprIlxLabel lbl = lbl
1393
1394 mkJoinLabel :: Id -> IlxLabel
1395 mkJoinLabel v = text "J_" <> ppr v
1396
1397 mkAltLabel  :: Id -> Int -> IlxLabel
1398 mkAltLabel v n = text "A" <> int n <> ppr v
1399
1400 ilxLabel :: IlxLabel -> SDoc
1401 ilxLabel lbl =  line $$ (pprIlxLabel lbl <> colon)
1402 \end{code}
1403
1404
1405 %************************************************************************
1406 %*                                                                      *
1407 \subsection{Local pretty helper functions}
1408 %*                                                                      *
1409 %************************************************************************
1410
1411 \begin{code}
1412 pprSepWithCommas :: (a -> SDoc) -> [a] -> SDoc
1413 pprSepWithCommas pp xs = sep (punctuate comma (map pp xs))
1414 ilxComment pp   = text "/*" <+> pp <+> text "*/"
1415 singleQuotes pp = char '\'' <> pp <> char '\''
1416
1417 line = text "// ----------------------------------"
1418
1419 hscOptionQual = if opt_SimplDoEtaReduction then text ".ilx-O" else text ".ilx-Onot"
1420
1421 nameReference env n
1422   | isLocalName n = empty
1423   | ilxEnvModule env == nameModule n  = text ""
1424   | isHomeModule (nameModule n)   = moduleNameReference (moduleName (nameModule n))
1425 -- HACK: no Vanilla modules should be around, but they are!!  This
1426 -- gets things working for the scenario "standard library linked as one
1427 -- assembly with multiple modules + a one module program running on top of this"
1428 -- Same applies to all other mentions of Vailla modules in this file
1429   | isVanillaModule (nameModule n)  && not inPrelude =  preludePackageReference
1430   | isVanillaModule (nameModule n)  && inPrelude =   moduleNameReference (moduleName (nameModule n))
1431 -- end hack
1432   | otherwise = packageReference (modulePackage (nameModule n))
1433
1434 packageReference p = brackets (singleQuotes (ppr p  <> hscOptionQual))
1435 moduleNameReference m = brackets ((text ".module") <+> (singleQuotes (pprModuleName m <> hscOptionQual <> text ".dll")))
1436
1437 moduleReference env m
1438   | ilxEnvModule env   == m = text ""
1439   | isHomeModule m = moduleNameReference (moduleName m)
1440   -- See hack above
1441   | isVanillaModule m && not inPrelude =  preludePackageReference
1442   | isVanillaModule m && inPrelude =  moduleNameReference (moduleName m)
1443   -- end hack
1444   | otherwise  =  packageReference (modulePackage m)
1445
1446 preludePackageReference = packageReference preludePackage
1447 inPrelude = preludePackage == opt_InPackage
1448
1449 ------------------------------------------------
1450 -- This code is copied from absCSyn/CString.lhs,
1451 -- and modified to do the correct thing!  It's
1452 -- still a mess though.  Also, still have to do the
1453 -- right thing for embedded nulls.
1454
1455 pprFSInILStyle :: FAST_STRING -> SDoc
1456 pprFSInILStyle fs = doubleQuotes (text (stringToC (_UNPK_ fs)))
1457
1458 stringToC   :: String -> String
1459 -- Convert a string to the form required by C in a C literal string
1460 -- Tthe hassle is what to do w/ strings like "ESC 0"...
1461 stringToC ""  = ""
1462 stringToC [c] = charToC c
1463 stringToC (c:cs)
1464     -- if we have something "octifiable" in "c", we'd better "octify"
1465     -- the rest of the string, too.
1466   = if (c < ' ' || c > '~')
1467     then (charToC c) ++ (concat (map char_to_C cs))
1468     else (charToC c) ++ (stringToC cs)
1469   where
1470     char_to_C c | c == '\n' = "\\n"     -- use C escapes when we can
1471                 | c == '\a' = "\\a"
1472                 | c == '\b' = "\\b"     -- ToDo: chk some of these...
1473                 | c == '\r' = "\\r"
1474                 | c == '\t' = "\\t"
1475                 | c == '\f' = "\\f"
1476                 | c == '\v' = "\\v"
1477                 | otherwise = '\\' : (trigraph (ord c))
1478
1479 charToC :: Char -> String
1480 -- Convert a character to the form reqd in a C character literal
1481 charToC c = if (c >= ' ' && c <= '~')   -- non-portable...
1482             then case c of
1483                   '\'' -> "\\'"
1484                   '\\' -> "\\\\"
1485                   '"'  -> "\\\""
1486                   '\n' -> "\\n"
1487                   '\a' -> "\\a"
1488                   '\b' -> "\\b"
1489                   '\r' -> "\\r"
1490                   '\t' -> "\\t"
1491                   '\f' -> "\\f"
1492                   '\v' -> "\\v"
1493                   _    -> [c]
1494             else '\\' : (trigraph (ord c))
1495
1496 trigraph :: Int -> String
1497 trigraph n
1498   = [chr ((n `div` 100) `rem` 10 + ord '0'),
1499      chr ((n `div` 10) `rem` 10 + ord '0'),
1500      chr (n `rem` 10 + ord '0')]
1501
1502
1503 \end{code}
1504
1505 %************************************************************************
1506 %*                                                                      *
1507 \subsection{PrimOps and Constructors}
1508 %*                                                                      *
1509 %************************************************************************
1510
1511 \begin{code}
1512 ----------------------------
1513 -- Allocate a fresh constructor
1514
1515 ilxConApp env data_con args
1516   | isUnboxedTupleCon data_con
1517      = let tm_args' = filter (not. isVoidIlxRepType . stgArgType) tm_args in 
1518        case tm_args' of
1519         [h] -> 
1520           -- Collapse the construction of an unboxed tuple type where
1521           -- every element is zero-sized
1522             vcat (ilxMapPlaceArgs 0 pushArg env tm_args')
1523         _ -> 
1524           -- Minimize the construction of an unboxed tuple type, which
1525           -- may contain zero-sized elements.  Recompute all the 
1526           -- bits and pieces from the simpler case below for the new data
1527           -- type constructor....
1528            let data_con' = tupleCon Unboxed (length tm_args') in 
1529            let rep_ty_args' = filter (not . isVoidIlxRepType) rep_ty_args in 
1530
1531            let tycon' = dataConTyCon data_con' in
1532            let (formal_tyvars', formal_tau_ty') = splitForAllTys (dataConRepType data_con') in 
1533            let (formal_arg_tys', _)     = splitFunTys formal_tau_ty' in
1534            let formal_env'           = formalIlxEnv env formal_tyvars' in 
1535
1536            vcat [vcat (ilxMapPlaceArgs 0 pushArg env tm_args'),
1537                    sep [text "newobj void ",
1538                         ilxTyConApp env tycon' rep_ty_args',
1539                         text "::.ctor",
1540                         pprValArgTys ilxTypeR formal_env' (map deepIlxRepType formal_arg_tys')
1541                    ]
1542              ]
1543  | otherwise
1544     -- Now all other constructions
1545      =  --  Assume C :: forall a. a -> T a -> T a
1546         --      ldloc x         arg of type Int
1547         --      ldloc y         arg of type T Int
1548         --      newdata classunion T<Int32>, C(!0, T <!0>)
1549         --
1550         let tycon   = dataConTyCon data_con in 
1551         let (formal_tyvars, formal_tau_ty) = splitForAllTys (dataConRepType data_con) in
1552         let (formal_arg_tys, _)     = splitFunTys formal_tau_ty in 
1553
1554        vcat [vcat (ilxMapPlaceArgs 0 pushArg env tm_args),
1555           sep [ text "newdata",
1556                 nest 2 (ilxTyConApp env tycon rep_ty_args <> comma),
1557                 nest 2 (ilxConRef env data_con)
1558           ]
1559         ]
1560  where
1561    tycon   = dataConTyCon data_con 
1562    rep_ty_args = map deepIlxRepType ty_args
1563    (ty_args,tm_args) = if isAlgTyCon tycon then splitTyArgs (tyConTyVars tycon) args  else splitTyArgs1 args
1564
1565 -- Split some type arguments off, throwing away the higher kinded ones for the moment.
1566 -- Base the higher-kinded checks off a corresponding list of formals.
1567 splitTyArgs :: [Var]            -- Formals
1568             -> [StgArg]         -- Actuals
1569             -> ([Type], [StgArg])
1570 splitTyArgs (htv:ttv) (StgTypeArg h:t) 
1571    | isIlxTyVar htv = ((h:l), r) 
1572    | otherwise = trace "splitTyArgs: threw away higher kinded type arg" (l, r) 
1573    where (l,r) = splitTyArgs ttv t 
1574 splitTyArgs _ l = ([],l)
1575  
1576 -- Split some type arguments off, where none should be higher kinded
1577 splitTyArgs1 :: [StgArg] -> ([Type], [StgArg])
1578 splitTyArgs1 (StgTypeArg ty : args) = (ty:tys, args')
1579                                     where
1580                                       (tys, args') = splitTyArgs1 args
1581 splitTyArgs1 args                   = ([], args)
1582
1583 ilxConRef env data_con
1584     = pprId data_con <> pprValArgTys ilxTypeL env' (map deepIlxRepType (filter (not . isVoidIlxRepType) arg_tys))
1585   where
1586     (tyvars, tau_ty) = splitForAllTys (dataConRepType data_con)
1587     (arg_tys, _)     = splitFunTys tau_ty
1588     env'             = formalIlxEnv env tyvars
1589
1590
1591
1592
1593 \end{code}
1594
1595
1596 %************************************************************************
1597 %*                                                                      *
1598 \subsection{PrimOps and Prim Representations}                           *
1599 %************************************************************************
1600
1601 \begin{code}
1602
1603 ilxPrimApp env op              args ret_ty = ilxPrimOpTable op args env
1604
1605
1606 type IlxTyFrag = IlxEnv -> SDoc
1607 ilxType s env = text s
1608
1609 ilxLift ty env = text "thunk" <> angleBrackets (ty env)
1610
1611 ilxTypeSeq :: [IlxTyFrag] -> IlxTyFrag
1612 ilxTypeSeq ops env = hsep (map (\x -> x env) ops)
1613
1614 tyPrimConTable :: UniqFM ([Type] -> IlxTyFrag)
1615 tyPrimConTable = 
1616   listToUFM [(addrPrimTyConKey,         (\_ -> repAddr)),
1617 --           (fileStreamPrimTyConKey,   (\_ -> repFileStream)),
1618              (foreignObjPrimTyConKey,   (\_ -> repForeign)),
1619              (stablePtrPrimTyConKey,    (\[ty] -> repStablePtr {- (ilxTypeL2 ty) -})),
1620              (stableNamePrimTyConKey,   (\[ty] -> repStableName {- (ilxTypeL2 ty) -} )),
1621              (charPrimTyConKey,         (\_ -> repChar)),
1622              (wordPrimTyConKey,         (\_ -> repWord)),
1623              (byteArrayPrimTyConKey,    (\_ -> repByteArray)),
1624              (intPrimTyConKey,          (\_ -> repInt)),
1625              (int64PrimTyConKey,        (\_ -> repInt64)),
1626              (word64PrimTyConKey,       (\_ -> repWord64)),
1627              (floatPrimTyConKey,        (\_ -> repFloat)),
1628              (doublePrimTyConKey,       (\_ -> repDouble)),
1629               -- These can all also accept unlifted parameter types so we explicitly lift.
1630              (arrayPrimTyConKey,        (\[ty] -> repArray (ilxTypeL2 ty))),
1631              (mutableArrayPrimTyConKey,         (\[_, ty] -> repMutArray (ilxTypeL2 ty))),
1632              (weakPrimTyConKey,         (\[ty] -> repWeak (ilxTypeL2 ty))),
1633              (mVarPrimTyConKey,         (\[_, ty] -> repMVar (ilxTypeL2 ty))),
1634              (mutVarPrimTyConKey,       (\[ty1, ty2] -> repMutVar (ilxTypeL2 ty1) (ilxTypeL2 ty2))),
1635              (mutableByteArrayPrimTyConKey,     (\_ -> repByteArray)),
1636              (threadIdPrimTyConKey,     (\_ -> repThread)),
1637              (bcoPrimTyConKey,  (\_ -> repBCO))
1638              ]
1639
1640 ilxTypeL2 :: Type -> IlxTyFrag
1641 ilxTypeL2 ty env = ilxTypeL env ty
1642 ilxTypeR2 :: Type -> IlxTyFrag
1643 ilxTypeR2 ty env = ilxTypeR env ty
1644
1645 ilxMethA = ilxType "!!0"
1646 ilxMethB = ilxType "!!1"
1647 prelGHCReference :: IlxTyFrag
1648 prelGHCReference env =
1649    if ilxEnvModule env == mkHomeModule (mkModuleName "PrelGHC") then empty
1650    else if inPrelude then moduleNameReference (mkModuleName "PrelGHC")
1651    else preludePackageReference
1652
1653 prelBaseReference :: IlxTyFrag
1654 prelBaseReference env =
1655    if ilxEnvModule env == mkHomeModule (mkModuleName "PrelBase") then empty
1656    else if inPrelude then moduleNameReference (mkModuleName "PrelBase")
1657    else preludePackageReference
1658
1659 repThread = ilxType "class [mscorlib]System.Threading.Thread /* ThreadId# */ "
1660 repByteArray = ilxType "unsigned int8[] /* ByteArr# */ "
1661 --repFileStream = text "void * /* FileStream# */ "  -- text "class [mscorlib]System.IO.FileStream"
1662 repInt = ilxType "int32"
1663 repWord = ilxType "unsigned int32"
1664 repAddr =ilxType "/* Addr */ void *"
1665 repInt64 = ilxType "int64"
1666 repWord64 = ilxType "unsigned int64"
1667 repFloat = ilxType "float32"
1668 repDouble = ilxType "float64"
1669 repChar = ilxType "/* Char */ unsigned int8"
1670 repForeign = ilxTypeSeq [ilxType "class ",prelGHCReference,ilxType "PrelGHC_Foreignzh"]
1671 repInteger = ilxUnboxedPairRep repInt repByteArray
1672 repIntegerPair = ilxUnboxedQuadRep repInt repByteArray repInt repByteArray
1673 repArray ty = ilxTypeSeq [ty,ilxType "[]"]
1674 repMutArray ty = ilxTypeSeq [ty,ilxType "[]"]
1675 repMVar ty = ilxTypeSeq [ilxType "class ",prelGHCReference,ilxType "PrelGHC_MVarzh",ilxTyParams [ty]]
1676 repMutVar _ ty2 = ilxTypeSeq [ilxType "class ",prelGHCReference,ilxType "PrelGHC_MutVarzh",ilxTyParams [ty2]]
1677 repWeak ty1 = ilxTypeSeq [ilxType "class ",prelGHCReference,ilxType "PrelGHC_Weakzh",ilxTyParams [ty1]]
1678 repStablePtr {- ty1 -} = ilxTypeSeq [ilxType "class ",prelGHCReference,ilxType "PrelGHC_StablePtrzh" {- ,ilxTyParams [ty1] -} ]
1679 repStableName {- ty1 -}  = ilxTypeSeq [ilxType "class ",prelGHCReference,ilxType "PrelGHC_StableNamezh" {- ,ilxTyParams [ty1] -} ]
1680 classWeak = ilxTypeSeq [ilxType "class ",prelGHCReference,ilxType "PrelGHC_Weakzh"]
1681 repBCO = ilxTypeSeq [ilxType "class ",prelGHCReference,ilxType "PrelGHC_BCOzh"]
1682
1683 ilxTyPair l r = ilxTyParams [l,r]
1684 ilxTyTriple l m r = ilxTyParams [l,m,r]
1685 ilxTyQuad l m1 m2 r = ilxTyParams [l,m1,m2,r]
1686 ilxUnboxedPairRep l r = ilxTypeSeq [ilxType "value class",prelGHCReference,ilxType "PrelGHC_Z1H",ilxTyPair l r]
1687 ilxUnboxedTripleRep l m r = ilxTypeSeq [ilxType "value class",prelGHCReference,ilxType "PrelGHC_Z2H",ilxTyTriple l m r]
1688 ilxUnboxedQuadRep l m1 m2 r = ilxTypeSeq [ilxType "value class",prelGHCReference,ilxType "PrelGHC_Z3H",ilxTyQuad l m1 m2 r]
1689
1690 ilxTyParams :: [IlxTyFrag] -> IlxTyFrag
1691 ilxTyParams [] env = empty
1692 ilxTyParams l env = angleBrackets (ilxTyParamsAux l env)
1693   where
1694    ilxTyParamsAux [] env = empty
1695    ilxTyParamsAux [h] env = h env
1696    ilxTyParamsAux (h:t) env = h env <> text "," <+> ilxTyParamsAux t env
1697    ilxTyParams [] env = empty
1698
1699
1700 type IlxOpFrag = IlxEnv -> SDoc
1701 ilxOp :: String -> IlxOpFrag
1702 ilxOp s env = text s
1703 ilxOpSeq :: [IlxOpFrag] -> IlxOpFrag
1704 ilxOpSeq ops env = hsep (map (\x -> x env) ops)
1705
1706 ilxParams :: [IlxOpFrag] -> IlxOpFrag
1707 ilxParams l env = parens (ilxParamsAux l env)
1708   where
1709    ilxParamsAux [] env = empty
1710    ilxParamsAux [h] env = h env
1711    ilxParamsAux (h:t) env = h env <> text "," <+> ilxParamsAux t env
1712
1713
1714 ilxMethodRef rty cls nm tyargs args = 
1715     ilxOpSeq [rty,cls,ilxOp "::",ilxOp nm,
1716               ilxTyParams tyargs,ilxParams args]
1717
1718 ilxCall m = ilxOpSeq [ilxOp "call", m]
1719
1720 ilxSupportClass = ilxOpSeq [prelGHCReference, ilxOp "'GHC.support'"]
1721 ilxSuppMeth rty nm tyargs args = ilxMethodRef rty ilxSupportClass nm tyargs args
1722
1723 ilxCallSuppMeth rty nm tyargs args  = ilxCall (ilxSuppMeth rty nm tyargs args)
1724
1725 ilxMkBool :: IlxOpFrag
1726 ilxMkBool =  ilxOpSeq [ilxOp "call class",prelBaseReference,
1727                        ilxOp "PrelBase_Bool",
1728                        prelGHCReference,ilxOp "GHC.support::mkBool(bool)"]
1729 ilxCgt = ilxOpSeq [ilxOp "cgt",ilxMkBool]
1730 ilxCge = ilxOpSeq [ilxOp "clt ldc.i4 0 ceq ",ilxMkBool]
1731 ilxClt = ilxOpSeq [ilxOp "clt ",ilxMkBool]
1732 ilxCle = ilxOpSeq [ilxOp "cgt ldc.i4 0 ceq ",ilxMkBool]
1733 ilxCeq = ilxOpSeq [ilxOp "ceq ",ilxMkBool]
1734 ilxCne = ilxOpSeq [ilxOp "ceq ldc.i4 0 ceq " ,ilxMkBool]
1735 ilxCgtUn = ilxOpSeq [ilxOp "cgt.un ",ilxMkBool]
1736 ilxCgeUn  = ilxOpSeq [ilxOp "clt.un ldc.i4 0 ceq ",ilxMkBool]
1737 ilxCltUn = ilxOpSeq [ilxOp "clt.un ",ilxMkBool]
1738 ilxCleUn = ilxOpSeq [ilxOp "cgt.un ldc.i4 0 ceq ",ilxMkBool]
1739
1740 ilxAddrOfForeignOp = ilxOpSeq [ilxOp "ldfld void *" , repForeign, ilxOp "::contents"]
1741 ilxAddrOfByteArrOp = ilxOp "ldc.i4 0 ldelema unsigned int8"
1742
1743 ilxPrimOpTable :: PrimOp -> [StgArg] -> IlxOpFrag
1744 ilxPrimOpTable op
1745   = case op of
1746         CharGtOp    -> simp_op ilxCgt
1747         CharGeOp    -> simp_op ilxCge
1748         CharEqOp    -> simp_op ilxCeq
1749         CharNeOp    -> simp_op ilxCne
1750         CharLtOp    -> simp_op ilxClt
1751         CharLeOp    -> simp_op ilxCle
1752
1753         OrdOp       -> simp_op (ilxOp "conv.i4") -- chars represented by UInt32 (u4)
1754         ChrOp       -> simp_op (ilxOp "conv.u4")
1755
1756         IntGtOp     -> simp_op ilxCgt
1757         IntGeOp     -> simp_op ilxCge
1758         IntEqOp     -> simp_op ilxCeq
1759         IntNeOp     -> simp_op ilxCne
1760         IntLtOp     -> simp_op ilxClt
1761         IntLeOp     -> simp_op ilxCle
1762
1763         IntToInt8Op  -> simp_op  (ilxOp"conv.i1")
1764         IntToInt16Op  -> simp_op (ilxOp "conv.i2")
1765         IntToInt32Op  -> simp_op (ilxOp "conv.i4")
1766         WordToWord8Op  -> simp_op (ilxOp "conv.u1")
1767         WordToWord16Op  -> simp_op (ilxOp "conv.u2")
1768         WordToWord32Op  -> simp_op (ilxOp "conv.u4")
1769
1770         WordGtOp     -> simp_op ilxCgtUn
1771         WordGeOp     -> simp_op ilxCgeUn
1772         WordEqOp     -> simp_op ilxCeq
1773         WordNeOp     -> simp_op ilxCne
1774         WordLtOp     -> simp_op ilxCltUn
1775         WordLeOp     -> simp_op ilxCleUn
1776
1777         AddrGtOp     -> simp_op ilxCgt
1778         AddrGeOp     -> simp_op ilxCge
1779         AddrEqOp     -> simp_op ilxCeq
1780         AddrNeOp     -> simp_op ilxCne
1781         AddrLtOp     -> simp_op ilxClt
1782         AddrLeOp     -> simp_op ilxCle
1783
1784         FloatGtOp     -> simp_op ilxCgt
1785         FloatGeOp     -> simp_op ilxCge
1786         FloatEqOp     -> simp_op ilxCeq
1787         FloatNeOp     -> simp_op ilxCne
1788         FloatLtOp     -> simp_op ilxClt
1789         FloatLeOp     -> simp_op ilxCle
1790
1791         DoubleGtOp     -> simp_op ilxCgt
1792         DoubleGeOp     -> simp_op ilxCge
1793         DoubleEqOp     -> simp_op ilxCeq
1794         DoubleNeOp     -> simp_op ilxCne
1795         DoubleLtOp     -> simp_op ilxClt
1796         DoubleLeOp     -> simp_op ilxCle
1797
1798     -- Int#-related ops:
1799         IntAddOp    -> simp_op (ilxOp "add")
1800         IntSubOp    -> simp_op (ilxOp "sub")
1801         IntMulOp    -> simp_op (ilxOp "mul")
1802         IntQuotOp   -> simp_op (ilxOp "div")
1803         IntNegOp    -> simp_op (ilxOp "neg")
1804         IntRemOp    -> simp_op (ilxOp "rem")
1805
1806     -- Word#-related ops:
1807         WordAddOp    -> simp_op (ilxOp "add")
1808         WordSubOp    -> simp_op (ilxOp "sub")
1809         WordMulOp    -> simp_op (ilxOp "mul")
1810         WordQuotOp   -> simp_op (ilxOp "div")
1811         WordRemOp    -> simp_op (ilxOp "rem")
1812
1813         Addr2IntOp  -> simp_op (ilxOp "conv.i4") -- Addresses are very dodgy for ILX.  They are used for both C-strings and 
1814         Int2AddrOp  -> simp_op (ilxOp "conv.i")  -- the FFI.  This needs more work.
1815         ISllOp      -> simp_op (ilxOp "shl")
1816         ISraOp      -> simp_op (ilxOp "shr")
1817         ISrlOp      -> simp_op (ilxOp "shr.un")
1818         IntAddCOp   -> simp_op (ilxCallSuppMeth (ilxUnboxedPairRep repInt repInt) "IntAddCOp" [] [repInt, repInt])
1819         IntSubCOp   -> simp_op (ilxCallSuppMeth (ilxUnboxedPairRep repInt repInt) "IntSubCOp" [] [repInt, repInt])
1820         IntMulCOp   -> simp_op (ilxCallSuppMeth (ilxUnboxedPairRep repInt repInt) "IntMulCOp" [] [repInt, repInt])
1821         IntGcdOp    -> simp_op (ilxCallSuppMeth repInt "IntGcdOp" [] [repInt, repInt])
1822
1823
1824     -- Word#-related ops:
1825         AndOp       -> simp_op (ilxOp "and") 
1826         OrOp        -> simp_op (ilxOp "or") 
1827         NotOp       -> simp_op (ilxOp "not") 
1828         XorOp       -> simp_op (ilxOp "xor") 
1829         SllOp       -> simp_op (ilxOp "shl") 
1830         SrlOp       -> simp_op (ilxOp "shr") 
1831         Word2IntOp  -> simp_op (ilxOp "conv.i4")
1832         Int2WordOp  -> simp_op (ilxOp "conv.u4")
1833
1834     -- Float#-related ops:
1835         FloatAddOp   -> simp_op (ilxOp "add")
1836         FloatSubOp   -> simp_op (ilxOp "sub")
1837         FloatMulOp   -> simp_op (ilxOp "mul")
1838         FloatDivOp   -> simp_op (ilxOp "div")
1839         FloatNegOp   -> simp_op (ilxOp "neg")
1840         Float2IntOp  -> simp_op (ilxOp "conv.i4")
1841         Int2FloatOp  -> simp_op (ilxOp "conv.r4")
1842
1843         DoubleAddOp     -> simp_op (ilxOp "add")
1844         DoubleSubOp     -> simp_op (ilxOp "sub")
1845         DoubleMulOp     -> simp_op (ilxOp "mul")
1846         DoubleDivOp     -> simp_op (ilxOp "div")
1847         DoubleNegOp     -> simp_op (ilxOp "neg")
1848         Double2IntOp    -> simp_op (ilxOp "conv.i4")
1849         Int2DoubleOp    -> simp_op (ilxOp "conv.r4")
1850         Double2FloatOp  -> simp_op (ilxOp "conv.r4")
1851         Float2DoubleOp  -> simp_op (ilxOp "conv.r8")
1852         DoubleDecodeOp  -> simp_op (ilxCallSuppMeth (ilxUnboxedTripleRep repInt repInt repByteArray) "decodeDouble" [] [ilxType "float64"])
1853         FloatDecodeOp   -> simp_op (ilxCallSuppMeth (ilxUnboxedTripleRep repInt repInt repByteArray) "decodeFloat" [] [ilxType "float32"])
1854
1855         FloatExpOp   -> simp_op (ilxOp "conv.r8 call float64 [mscorlib]System.Math::Exp(float64) conv.r4")
1856         FloatLogOp   -> simp_op (ilxOp "conv.r8 call float64 [mscorlib]System.Math::Log(float64) conv.r4")
1857         FloatSqrtOp  -> simp_op (ilxOp "conv.r8 call float64 [mscorlib]System.Math::Sqrt(float64) conv.r4")
1858         FloatSinOp   -> simp_op (ilxOp "conv.r8 call float64 [mscorlib]System.Math::Sin(float64) conv.r4")
1859         FloatCosOp   -> simp_op (ilxOp "conv.r8 call float64 [mscorlib]System.Math::Cos(float64) conv.r4")
1860         FloatTanOp   -> simp_op (ilxOp "conv.r8 call float64 [mscorlib]System.Math::Tan(float64) conv.r4")
1861         FloatAsinOp  -> simp_op (ilxOp "conv.r8 call float64 [mscorlib]System.Math::Asin(float64) conv.r4")
1862         FloatAcosOp  -> simp_op (ilxOp "conv.r8 call float64 [mscorlib]System.Math::Acos(float64) conv.r4")
1863         FloatAtanOp  -> simp_op (ilxOp "conv.r8 call float64 [mscorlib]System.Math::Atan(float64) conv.r4")
1864         FloatSinhOp  -> simp_op (ilxOp "conv.r8 call float64 [mscorlib]System.Math::Sinh(float64) conv.r4")
1865         FloatCoshOp  -> simp_op (ilxOp "conv.r8 call float64 [mscorlib]System.Math::Cosh(float64) conv.r4")
1866         FloatTanhOp  -> simp_op (ilxOp "conv.r8 call float64 [mscorlib]System.Math::Tanh(float64) conv.r4")
1867         FloatPowerOp -> simp_op (ilxOp "call float64 [mscorlib]System.Math::Pow(float64, float64) conv.r4") -- ** op, make use of implicit cast to r8...
1868
1869         DoubleExpOp   -> simp_op (ilxOp "call float64 [mscorlib]System.Math::Exp(float64)")
1870         DoubleLogOp   -> simp_op (ilxOp "call float64 [mscorlib]System.Math::Log(float64)")
1871         DoubleSqrtOp  -> simp_op (ilxOp "call float64 [mscorlib]System.Math::Sqrt(float64)")
1872           
1873         DoubleSinOp   -> simp_op (ilxOp "call float64 [mscorlib]System.Math::Sin(float64)")
1874         DoubleCosOp   -> simp_op (ilxOp "call float64 [mscorlib]System.Math::Cos(float64)")
1875         DoubleTanOp   -> simp_op (ilxOp "call float64 [mscorlib]System.Math::Tan(float64)")
1876           
1877         DoubleAsinOp   -> simp_op (ilxOp "call float64 [mscorlib]System.Math::Asin(float64)")
1878         DoubleAcosOp   -> simp_op (ilxOp "call float64 [mscorlib]System.Math::Acos(float64)")
1879         DoubleAtanOp   -> simp_op (ilxOp "call float64 [mscorlib]System.Math::Atan(float64)")
1880           
1881         DoubleSinhOp   -> simp_op (ilxOp "call float64 [mscorlib]System.Math::Sinh(float64)")
1882         DoubleCoshOp   -> simp_op (ilxOp "call float64 [mscorlib]System.Math::Cosh(float64)")
1883         DoubleTanhOp   -> simp_op (ilxOp "call float64 [mscorlib]System.Math::Tanh(float64)")
1884           
1885         DoublePowerOp  -> simp_op (ilxOp "call float64 [mscorlib]System.Math::Pow(float64, float64)")
1886
1887     -- Integer (and related...) ops: bail out to support routines
1888         IntegerAndOp       -> simp_op (ilxCallSuppMeth repInteger "IntegerAndOp" [] [repInt, repByteArray, repInt, repByteArray])
1889         IntegerOrOp        -> simp_op (ilxCallSuppMeth repInteger "IntegerOrOp" [] [repInt, repByteArray, repInt, repByteArray])
1890         IntegerXorOp       -> simp_op (ilxCallSuppMeth repInteger "IntegerXorOp" [] [repInt, repByteArray, repInt, repByteArray])
1891         IntegerComplementOp -> simp_op (ilxCallSuppMeth repInteger "IntegerComplementOp" [] [repInt, repByteArray])
1892         IntegerAddOp       -> simp_op (ilxCallSuppMeth repInteger "IntegerAddOp" [] [repInt, repByteArray, repInt, repByteArray])
1893         IntegerSubOp       -> simp_op (ilxCallSuppMeth repInteger "IntegerSubOp" [] [repInt, repByteArray, repInt, repByteArray])
1894         IntegerMulOp       -> simp_op (ilxCallSuppMeth repInteger "IntegerMulOp" [] [repInt, repByteArray, repInt, repByteArray])
1895         IntegerGcdOp       -> simp_op (ilxCallSuppMeth repInteger "IntegerGcdOp" [] [repInt, repByteArray, repInt, repByteArray])
1896         IntegerQuotRemOp   -> simp_op (ilxCallSuppMeth repIntegerPair "IntegerQuotRemOp" [] [repInt, repByteArray, repInt, repByteArray])
1897         IntegerDivModOp    -> simp_op (ilxCallSuppMeth repIntegerPair "IntegerDivModOp" [] [repInt, repByteArray, repInt, repByteArray])
1898         IntegerIntGcdOp    -> simp_op (ilxCallSuppMeth repInt "IntegerIntGcdOp" [] [repInt, repByteArray, repInt])
1899         IntegerDivExactOp  -> simp_op (ilxCallSuppMeth repInteger "IntegerDivExactOp" [] [repInt, repByteArray, repInt, repByteArray])
1900         IntegerQuotOp      -> simp_op (ilxCallSuppMeth repInteger "IntegerQuotOp" [] [repInt, repByteArray, repInt, repByteArray])
1901         IntegerRemOp       -> simp_op (ilxCallSuppMeth repInteger "IntegerRemOp" [] [repInt, repByteArray, repInt, repByteArray])
1902         IntegerCmpOp       -> simp_op (ilxCallSuppMeth repInt "IntegerCmpOp" [] [repInt, repByteArray, repInt, repByteArray])
1903         IntegerCmpIntOp    -> simp_op (ilxCallSuppMeth repInt "IntegerCmpIntOp" [] [repInt, repByteArray, repInt])
1904         Integer2IntOp      -> simp_op (ilxCallSuppMeth repInt "Integer2IntOp" [] [repInt, repByteArray])
1905         Integer2WordOp     -> simp_op (ilxCallSuppMeth repWord "Integer2WordOp" [] [repInt, repByteArray])
1906         Int2IntegerOp      -> simp_op (ilxCallSuppMeth repInteger "Int2IntegerOp" [] [repInt])
1907         Word2IntegerOp     -> simp_op (ilxCallSuppMeth repInteger "Word2IntegerOp" [] [repWord])
1908         IntegerToInt64Op   -> simp_op (ilxCallSuppMeth repInt64 "IntegerToInt64Op" [] [repInt,repByteArray])
1909         Int64ToIntegerOp   -> simp_op (ilxCallSuppMeth repInteger "Int64ToIntegerOp" [] [repInt64])
1910         IntegerToWord64Op  -> simp_op (ilxCallSuppMeth repWord64 "IntegerToWord64Op" [] [repInt,repByteArray])
1911         Word64ToIntegerOp  -> simp_op (ilxCallSuppMeth repInteger "Word64ToIntegerOp" [] [repWord64])
1912
1913
1914
1915         IndexByteArrayOp_Char      -> simp_op (ilxOp "ldelem.u1")
1916         IndexByteArrayOp_WideChar  -> simp_op (ilxOp "ldelem.u4")
1917         IndexByteArrayOp_Int       -> simp_op (ilxOp "ldelem.i4")
1918         IndexByteArrayOp_Word      -> simp_op (ilxOp "ldelem.u4")
1919         IndexByteArrayOp_Addr      -> simp_op (ilxOp "ldelem.u")
1920         IndexByteArrayOp_Float     -> simp_op (ilxOp "ldelem.r4")
1921         IndexByteArrayOp_Double    -> simp_op (ilxOp "ldelem.r8")
1922         IndexByteArrayOp_StablePtr -> simp_op (ilxOp "ldelem.ref")
1923         IndexByteArrayOp_Int8     -> simp_op (ilxOp "ldelem.i1")
1924         IndexByteArrayOp_Int16     -> simp_op (ilxOp "ldelem.i2")
1925         IndexByteArrayOp_Int32     -> simp_op (ilxOp "ldelem.i4")
1926         IndexByteArrayOp_Int64     -> simp_op (ilxOp "ldelem.i8")
1927         IndexByteArrayOp_Word8    -> simp_op (ilxOp "ldelem.u1")
1928         IndexByteArrayOp_Word16    -> simp_op (ilxOp "ldelem.u2")
1929         IndexByteArrayOp_Word32    -> simp_op (ilxOp "ldelem.u4")
1930         IndexByteArrayOp_Word64    -> simp_op (ilxOp "ldelem.u8")
1931
1932             {- should be monadic??? -}
1933         ReadByteArrayOp_Char      -> simp_op (ilxOp "ldelem.u1")
1934         ReadByteArrayOp_WideChar  -> simp_op (ilxOp "ldelem.u4")
1935         ReadByteArrayOp_Int       -> simp_op (ilxOp "ldelem.i4")
1936         ReadByteArrayOp_Word      -> simp_op (ilxOp "ldelem.u4")
1937         ReadByteArrayOp_Addr      -> simp_op (ilxOp "ldelem.u")
1938         ReadByteArrayOp_Float     -> simp_op (ilxOp "ldelem.r4")
1939         ReadByteArrayOp_Double    -> simp_op (ilxOp "ldelem.r8")
1940         ReadByteArrayOp_StablePtr -> simp_op (ilxOp "ldelem.ref")
1941         ReadByteArrayOp_Int8     -> simp_op (ilxOp "ldelem.i1")
1942         ReadByteArrayOp_Int16     -> simp_op (ilxOp "ldelem.i2")
1943         ReadByteArrayOp_Int32     -> simp_op (ilxOp "ldelem.i4")
1944         ReadByteArrayOp_Int64     -> simp_op (ilxOp "ldelem.i8")
1945         ReadByteArrayOp_Word8    -> simp_op (ilxOp "ldelem.u1")
1946         ReadByteArrayOp_Word16    -> simp_op (ilxOp "ldelem.u2")
1947         ReadByteArrayOp_Word32    -> simp_op (ilxOp "ldelem.u4")
1948         ReadByteArrayOp_Word64    -> simp_op (ilxOp "ldelem.u8")
1949                  {-   MutByteArr# s -> Int# -> State# s -> (# State# s, Char# #) -}
1950                  {- ByteArr# -> Int# -> Char# -}
1951
1952
1953         WriteByteArrayOp_Char      -> simp_op (ilxOp "stelem.u1")
1954         WriteByteArrayOp_WideChar   -> simp_op (ilxOp "stelem.u4")
1955         WriteByteArrayOp_Int       -> simp_op (ilxOp "stelem.i4")
1956         WriteByteArrayOp_Word      -> simp_op (ilxOp "stelem.u4")
1957         WriteByteArrayOp_Addr      -> simp_op (ilxOp "stelem.u")
1958         WriteByteArrayOp_Float     -> simp_op (ilxOp "stelem.r4")
1959         WriteByteArrayOp_Double    -> simp_op (ilxOp "stelem.r8")
1960         WriteByteArrayOp_StablePtr -> simp_op (ilxOp "stelem.ref")
1961         WriteByteArrayOp_Int8     -> simp_op (ilxOp "stelem.i1")
1962         WriteByteArrayOp_Int16     -> simp_op (ilxOp "stelem.i2")
1963         WriteByteArrayOp_Int32     -> simp_op (ilxOp "stelem.i4")
1964         WriteByteArrayOp_Int64     -> simp_op (ilxOp "stelem.i8")
1965         WriteByteArrayOp_Word8    -> simp_op (ilxOp "stelem.u1")
1966         WriteByteArrayOp_Word16    -> simp_op (ilxOp "stelem.u2")
1967         WriteByteArrayOp_Word32    -> simp_op (ilxOp "stelem.u4")
1968         WriteByteArrayOp_Word64    -> simp_op (ilxOp "stelem.i8 /* nb. no stelem.u8 */")
1969                  {- MutByteArr# s -> Int# -> Char# -> State# s -> State# s -}
1970
1971         IndexOffAddrOp_Char    -> simp_op (ilxOp "sizeof unsigned int8 mul add ldind.u1")
1972         IndexOffAddrOp_WideChar    -> simp_op (ilxOp "sizeof int32 mul add ldind.u4")
1973         IndexOffAddrOp_Int     -> simp_op (ilxOp "sizeof int32 mul add ldind.i4")
1974         IndexOffAddrOp_Word    -> simp_op (ilxOp "sizeof int32 mul add ldind.u4")
1975         IndexOffAddrOp_Addr    -> simp_op (ilxOp "sizeof unsigned int mul add ldind.i")
1976         IndexOffAddrOp_StablePtr   -> simp_op (ilxOp "sizeof unsigned int mul add ldind.ref")
1977         IndexOffAddrOp_Float   -> simp_op (ilxOp "sizeof float32 mul add ldind.r4")
1978         IndexOffAddrOp_Double  -> simp_op (ilxOp "sizeof float64 mul add ldind.r8")
1979         IndexOffAddrOp_Int8   -> simp_op (ilxOp "sizeof int8 mul add ldind.i1")
1980         IndexOffAddrOp_Int16   -> simp_op (ilxOp "sizeof int16 mul add ldind.i2")
1981         IndexOffAddrOp_Int32   -> simp_op (ilxOp "sizeof int32 mul add ldind.i4")
1982         IndexOffAddrOp_Int64   -> simp_op (ilxOp "sizeof int64 mul add ldind.i8")
1983         IndexOffAddrOp_Word8  -> simp_op (ilxOp "sizeof unsigned int8 mul add ldind.u1")
1984         IndexOffAddrOp_Word16 -> simp_op (ilxOp "sizeof unsigned int16 mul add ldind.u2")
1985         IndexOffAddrOp_Word32  -> simp_op (ilxOp "sizeof unsigned int32 mul add ldind.u4")
1986         IndexOffAddrOp_Word64  -> simp_op (ilxOp "sizeof int64 mul add ldind.u8")
1987
1988         -- ForeignObj: load the address inside the object first
1989         -- TODO: is this remotely right?
1990         IndexOffForeignObjOp_Char    -> arg2_op (\fobj n -> ilxOpSeq [fobj, ilxAddrOfForeignOp, n, ilxOp "sizeof unsigned int8 mul add ldind.u1"])
1991         IndexOffForeignObjOp_WideChar    -> arg2_op (\fobj n -> ilxOpSeq [fobj, ilxAddrOfForeignOp, n, ilxOp "sizeof int32 mul add ldind.u4"])
1992         IndexOffForeignObjOp_Int     -> arg2_op (\fobj n -> ilxOpSeq [fobj, ilxAddrOfForeignOp, n, ilxOp "sizeof int32 mul add ldind.i4"])
1993         IndexOffForeignObjOp_Word    -> arg2_op (\fobj n -> ilxOpSeq [fobj, ilxAddrOfForeignOp, n, ilxOp "sizeof unsigned int32 mul add ldind.u4"])
1994         IndexOffForeignObjOp_Addr    ->  arg2_op (\fobj n -> ilxOpSeq [fobj, ilxAddrOfForeignOp, n, ilxOp "sizeof unsigned int mul add ldind.i  "])
1995         IndexOffForeignObjOp_StablePtr    ->  ty1_arg2_op (\ty fobj n -> ilxOpSeq [fobj, ilxAddrOfForeignOp, n, ilxOp "sizeof unsigned int mul add ldind.ref  "])
1996         IndexOffForeignObjOp_Float   -> arg2_op (\fobj n -> ilxOpSeq [fobj, ilxAddrOfForeignOp, n, ilxOp "sizeof float32 mul add ldind.r4"])
1997         IndexOffForeignObjOp_Double  -> arg2_op (\fobj n -> ilxOpSeq [fobj, ilxAddrOfForeignOp, n, ilxOp "sizeof float64 mul add ldind.r8"])
1998         IndexOffForeignObjOp_Int8   -> arg2_op (\fobj n -> ilxOpSeq [fobj, ilxAddrOfForeignOp, n, ilxOp "sizeof int8 mul add ldind.i1"])
1999         IndexOffForeignObjOp_Int16   -> arg2_op (\fobj n -> ilxOpSeq [fobj, ilxAddrOfForeignOp, n, ilxOp "sizeof int16 mul add ldind.i2"])
2000         IndexOffForeignObjOp_Int32   -> arg2_op (\fobj n -> ilxOpSeq [fobj, ilxAddrOfForeignOp, n, ilxOp "sizeof int32 mul add ldind.i4"])
2001         IndexOffForeignObjOp_Int64   -> arg2_op (\fobj n -> ilxOpSeq [fobj, ilxAddrOfForeignOp, n, ilxOp "sizeof int64 mul add ldind.i8"])
2002         IndexOffForeignObjOp_Word8  -> arg2_op (\fobj n -> ilxOpSeq [fobj, ilxAddrOfForeignOp, n, ilxOp "sizeof unsigned int8 mul add ldind.u1"])
2003         IndexOffForeignObjOp_Word16  -> arg2_op (\fobj n -> ilxOpSeq [fobj, ilxAddrOfForeignOp, n, ilxOp "sizeof unsigned int16 mul add ldind.u2"])
2004         IndexOffForeignObjOp_Word32  -> arg2_op (\fobj n -> ilxOpSeq [fobj, ilxAddrOfForeignOp, n, ilxOp "sizeof unsigned int32 mul add ldind.u4"])
2005         IndexOffForeignObjOp_Word64  -> arg2_op (\fobj n -> ilxOpSeq [fobj, ilxAddrOfForeignOp, n, ilxOp "sizeof unsigned int64 mul add ldind.u8"])
2006
2007         ReadOffAddrOp_Char   -> simp_op (ilxOp "sizeof unsigned int8 mul add ldind.u1")
2008         ReadOffAddrOp_WideChar -> simp_op (ilxOp "sizeof int32 mul add ldind.u4")
2009         ReadOffAddrOp_Int    -> simp_op (ilxOp "sizeof int32 mul add ldind.i4")
2010         ReadOffAddrOp_Word   -> simp_op (ilxOp "sizeof unsigned int32 mul add ldind.u4")
2011         ReadOffAddrOp_Addr   -> simp_op (ilxOp "sizeof unsigned int mul add ldind.i")
2012         ReadOffAddrOp_Float  -> simp_op (ilxOp "sizeof float32 mul add ldind.r4")
2013         ReadOffAddrOp_Double -> simp_op (ilxOp "sizeof float64 mul add ldind.r8")
2014         ReadOffAddrOp_StablePtr  -> simp_op (ilxOp "sizeof unsigned int mul add ldind.ref")
2015         ReadOffAddrOp_Int8  -> simp_op (ilxOp "sizeof int8 mul add ldind.i1")
2016         ReadOffAddrOp_Int16  -> simp_op (ilxOp "sizeof int16 mul add ldind.i2")
2017         ReadOffAddrOp_Int32  -> simp_op (ilxOp "sizeof int32 mul add ldind.i4")
2018         ReadOffAddrOp_Int64  -> simp_op (ilxOp "sizeof int64 mul add ldind.i8")
2019         ReadOffAddrOp_Word8 -> simp_op (ilxOp "sizeof unsigned int8 mul add ldind.u1")
2020         ReadOffAddrOp_Word16 -> simp_op (ilxOp "sizeof unsigned int16 mul add ldind.u2")
2021         ReadOffAddrOp_Word32 -> simp_op (ilxOp "sizeof unsigned int32 mul add ldind.u4")
2022         ReadOffAddrOp_Word64 -> simp_op (ilxOp "sizeof unsigned int64 mul add ldind.u8")
2023                   {-    Addr# -> Int# -> Char# -> State# s -> State# s -} 
2024
2025         WriteOffAddrOp_Char   -> ty1_arg4_op (\sty addr n v s -> ilxOpSeq [addr, n, ilxOp "add", v, ilxOp "stind.u1"])
2026         WriteOffAddrOp_WideChar   -> ty1_arg4_op (\sty addr n v s -> ilxOpSeq [addr, n, ilxOp "sizeof int32 mul add", v, ilxOp "stind.u4"])
2027         WriteOffAddrOp_Int    -> ty1_arg4_op (\sty addr n v s -> ilxOpSeq [addr, n, ilxOp "sizeof int32 mul add", v, ilxOp "stind.i4"])
2028         WriteOffAddrOp_Word   -> ty1_arg4_op (\sty addr n v s -> ilxOpSeq [addr, n, ilxOp "sizeof int32 mul add", v, ilxOp "stind.u4"])
2029         WriteOffAddrOp_Addr   -> ty1_arg4_op (\sty addr n v s -> ilxOpSeq [addr, n, ilxOp "sizeof unsigned int mul add", v, ilxOp "stind.i"])
2030         WriteOffAddrOp_ForeignObj   -> ty1_arg4_op (\sty addr n v s -> ilxOpSeq [addr, n, ilxOp "sizeof unsigned int mul add", v, ilxOp "stind.ref"])
2031         WriteOffAddrOp_Float  -> ty1_arg4_op (\sty addr n v s -> ilxOpSeq [addr, n, ilxOp "sizeof float32 mul add", v,ilxOp "stind.r4"])
2032         WriteOffAddrOp_StablePtr   -> ty2_arg4_op (\ty1 sty addr n v s -> ilxOpSeq [addr, n, ilxOp "sizeof unsigned int mul add", v, ilxOp "stind.ref"])
2033         WriteOffAddrOp_Double -> ty1_arg4_op (\sty addr n v s -> ilxOpSeq [addr,n,ilxOp "sizeof float64 mul add",v,ilxOp "stind.r8"])
2034         WriteOffAddrOp_Int8  -> ty1_arg4_op (\sty addr n v s -> ilxOpSeq [addr,n,ilxOp "sizeof int8 mul add",v,ilxOp "stind.i1"])
2035         WriteOffAddrOp_Int16  -> ty1_arg4_op (\sty addr n v s -> ilxOpSeq [addr,n,ilxOp "sizeof int16 mul add",v,ilxOp "stind.i2"])
2036         WriteOffAddrOp_Int32  -> ty1_arg4_op (\sty addr n v s -> ilxOpSeq [addr,n,ilxOp "sizeof int32 mul add",v,ilxOp "stind.i4"])
2037         WriteOffAddrOp_Int64  -> ty1_arg4_op (\sty addr n v s -> ilxOpSeq [addr,n,ilxOp "sizeof int64 mul add",v,ilxOp "stind.i8"])
2038         WriteOffAddrOp_Word8 -> ty1_arg4_op (\sty addr n v s -> ilxOpSeq [addr,n,ilxOp "sizeof unsigned int8 mul add",v,ilxOp "stind.u1"])
2039         WriteOffAddrOp_Word16 -> ty1_arg4_op (\sty addr n v s -> ilxOpSeq [addr,n,ilxOp "sizeof unsigned int16 mul add",v,ilxOp "stind.u2"])
2040         WriteOffAddrOp_Word32 -> ty1_arg4_op (\sty addr n v s -> ilxOpSeq [addr,n,ilxOp "sizeof unsigned int32 mul add",v,ilxOp "stind.u4"])
2041         WriteOffAddrOp_Word64 -> ty1_arg4_op (\sty addr n v s -> ilxOpSeq [addr,n,ilxOp "sizeof unsigned int64 mul add",v,ilxOp "stind.u8"])
2042                   {-    Addr# -> Int# -> Char# -> State# s -> State# s -} 
2043
2044             {- should be monadic??? -}
2045         NewByteArrayOp_Char      -> simp_op (ilxOp "newarr [mscorlib]System.Byte")
2046 --      NewByteArrayOp_Int       -> simp_op (ilxOp "newarr [mscorlib]System.Int32")
2047 --      NewByteArrayOp_Word      -> simp_op (ilxOp "newarr [mscorlib]System.UInt32")
2048 --      NewByteArrayOp_Addr      -> simp_op (ilxOp "newarr [mscorlib]System.UInt64")
2049 --      NewByteArrayOp_Float     -> simp_op (ilxOp "newarr [mscorlib]System.Single")
2050 --      NewByteArrayOp_Double    -> simp_op (ilxOp "newarr [mscorlib]System.Double")
2051 --      NewByteArrayOp_StablePtr -> simp_op (ilxOp "newarr [mscorlib]System.UInt32")
2052 --      NewByteArrayOp_Int64     -> simp_op (ilxOp "newarr [mscorlib]System.Int64")  TODO: there is no unique for this one -}
2053 --      NewByteArrayOp_Word64    -> simp_op (ilxOp "newarr  [mscorlib]System.UInt64") -}
2054                   {- Int# -> State# s -> (# State# s, MutByteArr# s #) -}
2055
2056         UnsafeFreezeByteArrayOp ->   ty1_op (\ty1  -> ilxOp "nop ")
2057                   {- MutByteArr# s -> State# s -> (# State# s, ByteArr# #) -}
2058         SizeofByteArrayOp  -> simp_op (ilxOp "ldlen")
2059                   {- ByteArr# -> Int# -}
2060
2061         SameMutableByteArrayOp -> ty1_op (\ty1  -> ilxCeq)
2062                  {- MutByteArr# s -> MutByteArr# s -> Bool -}
2063         SizeofMutableByteArrayOp -> ty1_op (\ty1  -> ilxOp "ldlen")
2064                  {- MutByteArr# s -> Int# -}
2065
2066         SameMutVarOp -> ty2_op (\ty1 ty2 -> ilxCeq)
2067                  {- MutVar# s a -> MutVar# s a -> Bool -}
2068         NewMutVarOp -> ty2_op (\ty1 ty2 -> ilxOpSeq [ilxOp "newobj void" , repMutVar ty1 ty2 , ilxOp "::.ctor(!0)"])
2069                  {- a -> State# s -> (# State# s, MutVar# s a #) -}
2070         ReadMutVarOp -> ty2_op (\ty1 ty2 ->  ilxOpSeq [ilxOp "ldfld !0" , repMutVar ty1 ty2 , ilxOp "::contents"])
2071                  {-  MutVar# s a -> State# s -> (# State# s, a #) -}
2072         WriteMutVarOp -> ty2_op (\ty1 ty2 -> ilxOpSeq [ilxOp "stfld !0" , repMutVar ty1 ty2 , ilxOp "::contents"])
2073                  {- MutVar# s a -> a -> State# s -> State# s -}
2074
2075         NewArrayOp -> ty2_op (\ty1 ty2 -> ilxCallSuppMeth (ilxType "!!0[]") "newArray" [ty1] [repInt,ilxMethA])
2076                  {- Int# -> a -> State# s -> (# State# s, MutArr# s a #) -}
2077         IndexArrayOp -> ty1_op (\ty1 -> ilxOp "ldelem.ref")
2078                  {- Array# a -> Int# -> (# a #) -}
2079         WriteArrayOp -> ty2_op (\ty1 ty2 -> ilxOp "stelem.ref")
2080                  {- MutArr# s a -> Int# -> a -> State# s -> State# s -}
2081         ReadArrayOp -> ty2_op (\ty1 ty2 -> ilxOp "ldelem.ref")
2082                  {- MutArr# s a -> Int# -> State# s -> (# State# s, a #) -}
2083         UnsafeFreezeArrayOp -> ty2_op (\ty1 ty2 -> ilxOp "nop")
2084                  {-   MutArr# s a -> State# s -> (# State# s, Array# a #) -}
2085         UnsafeThawArrayOp -> ty2_op (\ty1 ty2 -> ilxOp "nop")
2086                  {-  Array# a -> State# s -> (# State# s, MutArr# s a #) -}
2087
2088         SameMutableArrayOp -> ty2_op (\ty1 ty2 -> ilxCeq)
2089                  {- MutArr# s a -> MutArr# s a -> Bool -}
2090
2091
2092         RaiseOp -> ty2_op (\ty1 ty2 -> ilxOp "throw")
2093         CatchOp -> ty2_op (\ty1 ty2 -> 
2094                 ilxCallSuppMeth ilxMethA "'catch'" [ty1,ty2] [ilxOp "thunk<(func ( /* unit skipped */ ) --> !!0)>", ilxOp "thunk<(func (!!1) --> (func ( /* unit skipped */ ) --> !!0))>"])
2095                             {-        (State# RealWorld -> (# State# RealWorld, a #) )
2096                                    -> (b -> State# RealWorld -> (# State# RealWorld, a #) ) 
2097                                    -> State# RealWorld
2098                                    -> (# State# RealWorld, a #) 
2099                              -} 
2100
2101         BlockAsyncExceptionsOp -> ty1_op (\ty1 -> 
2102                 ilxCallSuppMeth ilxMethA "blockAsyncExceptions" [ty1] [ilxOp "thunk<(func ( /* unit skipped */ ) --> !!0)>"])
2103
2104                 {-     (State# RealWorld -> (# State# RealWorld, a #))
2105                     -> (State# RealWorld -> (# State# RealWorld, a #))
2106                 -}
2107
2108         UnblockAsyncExceptionsOp -> ty1_op (\ty1 -> 
2109                 ilxCallSuppMeth ilxMethA "unblockAsyncExceptions" [ty1] [ilxOp "thunk<(func ( /* unit skipped */ ) --> !!0)>"])
2110
2111                 {-
2112                     State# RealWorld -> (# State# RealWorld, a #))
2113                     -> (State# RealWorld -> (# State# RealWorld, a #))
2114                 -}
2115  
2116         NewMVarOp -> ty2_op (\sty ty -> 
2117                 ilxOpSeq [ilxOp "newobj void " , repMVar ty , ilxOp "::.ctor()"])
2118                  {- State# s -> (# State# s, MVar# s a #) -}
2119
2120         TakeMVarOp -> ty2_op (\sty ty -> 
2121                 ilxCallSuppMeth ilxMethA "takeMVar" [ty] [repMVar ilxMethA])
2122                   {-  MVar# s a -> State# s -> (# State# s, a #) -}
2123
2124         -- These aren't yet right
2125         TryTakeMVarOp -> ty2_op (\sty ty -> 
2126                 ilxCallSuppMeth (ilxUnboxedPairRep repInt ilxMethA) "tryTakeMVar" [ty] [repMVar ilxMethA])
2127                   {-  MVar# s a -> State# s -> (# State# s, a #) -}
2128
2129         TryPutMVarOp -> ty2_op (\sty ty -> 
2130                 ilxCallSuppMeth repInt "tryPutMVar" [ty] [repMVar ilxMethA,ilxMethA])
2131                   {-  MVar# s a -> State# s -> (# State# s, a #) -}
2132
2133         PutMVarOp -> ty2_op (\sty ty -> 
2134                 ilxCallSuppMeth (ilxOp "void") "putMVar" [ty] [repMVar ilxMethA, ilxMethA])
2135                    {- MVar# s a -> a -> State# s -> State# s -}
2136
2137         SameMVarOp -> ty2_op (\sty ty -> ilxCeq)
2138                    {- MVar# s a -> MVar# s a -> Bool -}
2139
2140 --      TakeMaybeMVarOp -> ty2_op (\sty ty -> 
2141 --              (ilxCallSuppMeth (ilxUnboxedPairRep repInt ilxMethA) "tryTakeMVar" [ty] [repMVar ilxMethA]))
2142 --              {- MVar# s a -> State# s -> (# State# s, Int#, a #) -}
2143
2144         IsEmptyMVarOp -> ty2_op (\sty ty -> 
2145                 ilxCallSuppMeth repInt "isEmptyMVar" [ty] [repMVar ilxMethA])
2146                {- MVar# s a -> State# s -> (# State# s, Int# #) -}
2147
2148         TouchOp -> warn_op "touch" (ty1_op (\ty1 -> ilxOp "pop /* PrimOp touch */ "))
2149
2150                {- a -> Int# -}
2151         DataToTagOp -> ty1_op (\ty1 -> 
2152                 ilxCallSuppMeth repInt "dataToTag" [ty1] [ilxMethA])
2153                {- a -> Int# -}
2154
2155         TagToEnumOp -> ty1_op (\ty1 -> 
2156                 ilxCallSuppMeth ilxMethA "tagToEnum" [ty1] [repInt])
2157                {- Int# -> a -}
2158
2159         MakeStablePtrOp -> ty1_op (\ty1 -> ilxOpSeq [ilxOp "box", ty1, ilxOp "newobj void", repStablePtr {- ty1 -}, ilxOp "::.ctor(class [mscorlib]System.Object)"])
2160                  {-   a -> State# RealWorld -> (# State# RealWorld, StablePtr# a #) -}
2161         MakeStableNameOp -> ty1_op (\ty1 -> ilxOpSeq [ilxOp "pop newobj void", repStableName {- ty1 -}, ilxOp "::.ctor()"])
2162                         -- primOpInfo MakeStableNameOp = mkGenPrimOp SLIT("makeStableName#")  [alphaTyVar] [alphaTy, mkStatePrimTy realWorldTy] ((mkTupleTy Unboxed 2 [mkStatePrimTy realWorldTy, mkStableNamePrimTy alphaTy]))
2163
2164         EqStableNameOp -> ty1_op (\ty1 -> ilxOp "ceq")
2165                -- [alphaTyVar] [mkStableNamePrimTy alphaTy, mkStableNamePrimTy alphaTy] (intPrimTy)
2166         StableNameToIntOp -> warn_op "StableNameToIntOp" (ty1_op (\ty1 -> ilxOp "pop ldc.i4 0"))
2167                -- [alphaTyVar] [mkStableNamePrimTy alphaTy] (intPrimTy)
2168
2169         DeRefStablePtrOp -> ty1_op (\ty1 -> ilxOpSeq [ilxOp "ldfld class [mscorlib]System.Object", repStablePtr {- ty1 -}, ilxOp "::contents"])
2170                  {-  StablePtr# a -> State# RealWorld -> (# State# RealWorld, a #) -}
2171
2172         EqStablePtrOp -> ty1_op (\ty1 -> ilxOp "ceq")
2173                  {-  StablePtr# a -> StablePtr# a -> Int# -}
2174
2175         MkWeakOp -> ty3_op (\ty1 ty2 ty3 ->  ilxCall (ilxMethodRef (repWeak ilxMethB) classWeak "bake" [ilxLift ty1,ilxLift ty2,ty3] [ilxMethA, ilxMethB, ilxLift (ilxOp "!!2")]))
2176                  {- o -> b -> c -> State# RealWorld -> (# State# RealWorld, Weak# b #) -}
2177
2178         DeRefWeakOp -> ty1_op (\ty1 ->  ilxCall (ilxMethodRef (ilxUnboxedPairRep repInt ilxMethA) classWeak "deref" [ty1] [repWeak ilxMethA]))
2179         FinalizeWeakOp -> ty1_op (\ty1 ->  ilxCall (ilxMethodRef (ilxUnboxedPairRep repInt (ilxOp "thunk<(func ( /* unit skipped */ ) --> class '()')>")) classWeak "finalizer" [ty1] [repWeak ilxMethA]))
2180                    {-    Weak# a -> State# RealWorld -> (# State# RealWorld, Int#, 
2181         State# RealWorld -> (# State# RealWorld, Unit #)) #) -}
2182
2183         MkForeignObjOp -> simp_op (ilxOpSeq [ilxOp "newobj void", repForeign, ilxOp "::.ctor(void *)"])
2184         WriteForeignObjOp -> ty1_op (\sty -> ilxOpSeq [ilxOp "stfld void *", repForeign, ilxOp "::contents"])
2185         ForeignObjToAddrOp -> simp_op ilxAddrOfForeignOp
2186         YieldOp -> simp_op (ilxOpSeq [ilxOp "call class [mscorlib]System.Threading.Thread class [mscorlib]System.Threading.Thread::get_CurrentThread() 
2187                                 call instance void class [mscorlib]System.Threading.Thread::Suspend()"])
2188         MyThreadIdOp -> simp_op (ilxOpSeq [ilxOp "call default  class [mscorlib]System.Threading.Thread class [mscorlib]System.Threading.Thread::get_CurrentThread() "])
2189         KillThreadOp -> ty1_op (\ty -> ilxOpSeq [ilxOp "box", ty, ilxOp "call instance void class [mscorlib]System.Threading.Thread::Abort(class [mscorlib]System.Object) "])
2190               {-   ThreadId# -> a -> State# RealWorld -> State# RealWorld -}
2191
2192         ForkOp -> warn_op "ForkOp" (simp_op (ilxOp "/* ForkOp skipped... */ newobj void [mscorlib]System.Object::.ctor() throw"))
2193         ParOp ->  warn_op "ParOp" (simp_op (ilxOp "/* ParOp skipped... */ newobj void [mscorlib]System.Object::.ctor() throw"))
2194         DelayOp -> simp_op (ilxOp "call void class [mscorlib]System.Threading.Thread::Sleep(int32) ")
2195                  {-    Int# -> State# s -> State# s -}
2196
2197         WaitReadOp  -> warn_op "WaitReadOp" (simp_op (ilxOp "/* WaitReadOp skipped... */ pop"))
2198         WaitWriteOp -> warn_op "WaitWriteOp" (simp_op (ilxOp " /* WaitWriteOp skipped... */ newobj void [mscorlib]System.Object::.ctor() throw"))
2199         ParAtForNowOp -> warn_op "ParAtForNowOp" (simp_op (ilxOp " /* ParAtForNowOp skipped... */ newobj void [mscorlib]System.Object::.ctor() throw"))
2200         ParAtRelOp -> warn_op "ParAtRelOp" (simp_op (ilxOp " /* ParAtRelOp skipped... */ newobj void [mscorlib]System.Object::.ctor() throw"))
2201         ParAtAbsOp -> warn_op "ParAtAbsOp" (simp_op (ilxOp " /* ParAtAbsOp skipped... */ newobj void [mscorlib]System.Object::.ctor() throw"))
2202         ParAtOp -> warn_op "ParAtOp" (simp_op (ilxOp " /* ParAtOp skipped... */ newobj void [mscorlib]System.Object::.ctor() throw"))
2203         ParLocalOp -> warn_op "ParLocalOp" (simp_op (ilxOp " /* ParLocalOp skipped... */ newobj void [mscorlib]System.Object::.ctor() throw"))
2204         ParGlobalOp -> warn_op "ParGlobalOp" (simp_op (ilxOp " /* ParGlobalOp skipped... */ newobj void [mscorlib]System.Object::.ctor() throw"))
2205         SeqOp -> warn_op "SeqOp" (simp_op (ilxOp " newobj void [mscorlib]System.Object::.ctor() throw "))
2206         AddrToHValueOp -> warn_op "AddrToHValueOp" (simp_op (ilxOp "newobj void [mscorlib]System.Object::.ctor() throw"))
2207         ReallyUnsafePtrEqualityOp -> simp_op (ilxOp "ceq")
2208
2209         MkApUpd0_Op ->  warn_op "MkApUpd0_Op" (simp_op (ilxOp " newobj void [mscorlib]System.Object::.ctor() throw"))
2210         NewBCOOp ->  warn_op "NewBCOOp" (simp_op (ilxOp " newobj void [mscorlib]System.Object::.ctor() throw"))
2211                   -- ("newBCO#")  [alphaTyVar, deltaTyVar] [byteArrayPrimTy, byteArrayPrimTy, mkArrayPrimTy alphaTy, byteArrayPrimTy, mkStatePrimTy deltaTy] ((mkTupleTy Unboxed 2 [mkStatePrimTy deltaTy, bcoPrimTy]))
2212
2213
2214 ty1_op :: (IlxTyFrag -> IlxOpFrag) -> [StgArg] ->  IlxOpFrag 
2215 ty1_op  op ((StgTypeArg ty1):rest)  = 
2216       ilxOpSeq [getArgsStartingAt 1 rest, 
2217                 op (ilxTypeR2 (deepIlxRepType ty1))]
2218
2219 ty2_op :: (IlxTyFrag -> IlxTyFrag -> IlxOpFrag) -> [StgArg] ->  IlxOpFrag 
2220 ty2_op  op ((StgTypeArg ty1):(StgTypeArg ty2):rest)  = 
2221       ilxOpSeq [getArgsStartingAt 2 rest, 
2222                 op (ilxTypeR2 (deepIlxRepType ty1)) 
2223                    (ilxTypeR2 (deepIlxRepType ty2))]
2224
2225 ty3_op :: (IlxTyFrag -> IlxTyFrag -> IlxTyFrag -> IlxOpFrag) -> [StgArg] ->  IlxOpFrag 
2226 ty3_op  op ((StgTypeArg ty1):(StgTypeArg ty2):(StgTypeArg ty3):rest) = 
2227       ilxOpSeq [getArgsStartingAt 3 rest, 
2228                 op (ilxTypeR2 (deepIlxRepType ty1)) 
2229                    (ilxTypeR2 (deepIlxRepType ty2))
2230                    (ilxTypeR2 (deepIlxRepType ty3))]
2231
2232 arg2_op :: (IlxTyFrag -> IlxOpFrag -> IlxOpFrag) -> [StgArg] ->  IlxOpFrag 
2233 arg2_op  op [a1, a2] = 
2234        op (getAsArg 1 a1)
2235           (getAsArg 2 a2)
2236
2237 ty1_arg2_op :: (IlxTyFrag -> IlxOpFrag ->  IlxOpFrag -> IlxOpFrag) -> [StgArg] ->  IlxOpFrag 
2238 ty1_arg2_op  op [(StgTypeArg ty1), a1, a2] = 
2239        op (ilxTypeR2 (deepIlxRepType ty1)) 
2240           (getAsArg 1 a1)
2241           (getAsArg 2 a2)
2242
2243 ty1_arg4_op :: (IlxTyFrag -> IlxOpFrag -> IlxOpFrag -> IlxOpFrag -> IlxOpFrag -> IlxOpFrag) -> [StgArg] ->  IlxOpFrag 
2244 ty1_arg4_op  op [(StgTypeArg ty1), a1, a2, a3, a4] = 
2245        op (ilxTypeR2 (deepIlxRepType ty1)) 
2246           (getAsArg 1 a1)
2247           (getAsArg 2 a2)
2248           (getAsArg 3 a3)
2249           (getAsArg 4 a4)
2250
2251 ty2_arg4_op :: (IlxTyFrag -> IlxTyFrag -> IlxOpFrag -> IlxOpFrag -> IlxOpFrag -> IlxOpFrag -> IlxOpFrag) -> [StgArg] ->  IlxOpFrag 
2252 ty2_arg4_op  op [(StgTypeArg ty1), (StgTypeArg ty2),a1, a2, a3, a4] = 
2253        op (ilxTypeR2 (deepIlxRepType ty1)) 
2254           (ilxTypeR2 (deepIlxRepType ty2)) 
2255           (getAsArg 2 a1)
2256           (getAsArg 3 a2)
2257           (getAsArg 4 a3)
2258           (getAsArg 5 a4)
2259
2260 hd (h:t) = h
2261
2262 getAsArg n a env = hd (ilxMapPlaceArgs n pushArg env [a])
2263 getArgsStartingAt n a env = vcat (ilxMapPlaceArgs n pushArg env a)
2264
2265 simp_op :: IlxOpFrag -> [StgArg] -> IlxOpFrag
2266 simp_op  op args env    = vcat (ilxMapPlaceArgs 0 pushArg env args) $$ op env
2267 warn_op  warning f args = trace ("WARNING! IlxGen cannot translate primop " ++ warning) (f args)
2268 \end{code}
2269
2270 %************************************************************************
2271 %*                                                                      *
2272 \subsection{C Calls}
2273 %*                                                                      *
2274 %************************************************************************
2275
2276 \begin{code}
2277 -- Call the P/Invoke stub wrapper generated in the import section.
2278 -- We eliminate voids in and around an IL C Call.  
2279 -- We also do some type-directed translation for pinning Haskell-managed blobs
2280 -- of data as we throw them across the boundary.
2281 ilxFCall env (CCall (CCallSpec (StaticTarget c) cconv gc)) args ret_ty
2282  = ilxComment (text "C call <+> pprCLabelString c") <+> 
2283         vcat [vcat (ilxMapPlaceArgs 0 pushCArg env args),
2284               text "call" <+> retdoc <+> pprCLabelString c  <+> pprTypeArgs ilxTypeR env ty_args
2285                     <+> pprCValArgTys ilxTypeL env (map deepIlxRepType (filter (not. isVoidIlxRepType) (map stgArgType tm_args))) ]
2286   where 
2287     retdoc | isVoidIlxRepType ret_ty = text "void" 
2288            | otherwise               = ilxTypeR env (deepIlxRepType ret_ty)
2289     (ty_args,tm_args) = splitTyArgs1 args 
2290
2291 ilxFCall env (DNCall (DNCallSpec call_instr)) args ret_ty
2292   = ilxComment (text "IL call") <+> 
2293     vcat [vcat (ilxMapPlaceArgs 0 pushEvalArg env tm_args), 
2294           ptext call_instr
2295                 -- In due course we'll need to pass the type arguments
2296                 -- and to do that we'll need to have more than just a string
2297                 -- for call_instr
2298     ]
2299   where
2300     (ty_args,tm_args) = splitTyArgs1 args 
2301
2302 -- Push and argument and force its evaluation if necessary.
2303 pushEvalArg _ (StgTypeArg _) = empty
2304 pushEvalArg env (StgVarArg arg) = ilxFunApp env arg [] False
2305 pushEvalArg env (StgLitArg lit) = pushLit env lit
2306
2307
2308 hasTyCon (TyConApp tc _) tc2 = tc == tc2
2309 hasTyCon _  _ = False
2310
2311 isByteArrayCArgTy ty = hasTyCon ty byteArrayPrimTyCon || hasTyCon ty mutableByteArrayPrimTyCon
2312 isByteArrayCArg v = isByteArrayCArgTy (deepIlxRepType (idType v))
2313
2314 isForeignObjCArgTy ty = hasTyCon ty foreignObjPrimTyCon
2315 isForeignObjCArg v = isForeignObjCArgTy (deepIlxRepType (idType v))
2316
2317 pinCCallArg v = isByteArrayCArg v || isForeignObjCArg v  
2318
2319 pinCArg  env arg v = pushArg env arg <+> text "dup stloc" <+> singleQuotes (ilxEnvQualifyByExact env (ppr v) <> text "pin") 
2320 pushCArg  env arg@(StgVarArg v) | isByteArrayCArg v = pinCArg env arg v <+> ilxAddrOfByteArrOp env
2321 pushCArg env arg@(StgVarArg v) | isForeignObjCArg v = pinCArg env arg v <+> ilxAddrOfForeignOp env
2322 pushCArg env arg | otherwise = pushArg env arg
2323
2324 pprCValArgTys f env tys = parens (pprSepWithCommas (pprCValArgTy f env) tys)
2325 pprCValArgTy f env ty | isByteArrayCArgTy ty = text "void *" <+> ilxComment (text "interior pointer into ByteArr#")
2326 pprCValArgTy f env ty | isForeignObjCArgTy ty = text "void *" <+> ilxComment (text "foreign object")
2327 pprCValArgTy f env ty | otherwise = f env ty
2328
2329
2330 foldR            :: (a -> b -> b) -> [a] -> b -> b
2331 -- foldR _ [] z     =  z
2332 -- foldR f (x:xs) z =  f x (foldR f xs z) 
2333 {-# INLINE foldR #-}
2334 foldR k xs z = go xs
2335              where
2336                go []     = z
2337                go (y:ys) = y `k` go ys
2338
2339 \end{code}
2340