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