bea6d67193c51ec188431908615c00712bf7cb01
[ghc-hetmet.git] / ghc / compiler / absCSyn / PprAbsC.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 %
4 %************************************************************************
5 %*                                                                      *
6 \section[PprAbsC]{Pretty-printing Abstract~C}
7 %*                                                                      *
8 %************************************************************************
9
10 \begin{code}
11 module PprAbsC (
12         writeRealC,
13         dumpRealC,
14         pprAmode,
15         pprMagicId
16     ) where
17
18 #include "HsVersions.h"
19
20 import IO       ( Handle )
21
22 import PrimRep 
23 import AbsCSyn
24 import ClosureInfo
25 import AbsCUtils        ( getAmodeRep, nonemptyAbsC,
26                           mixedPtrLocn, mixedTypeLocn
27                         )
28
29 import ForeignCall      ( CCallSpec(..), CCallTarget(..), playSafe,
30                           playThreadSafe, ccallConvAttribute,
31                           ForeignCall(..), DNCallSpec(..),
32                           DNType(..), DNKind(..) )
33 import CLabel           ( externallyVisibleCLabel,
34                           needsCDecl, pprCLabel, mkClosureLabel,
35                           mkReturnInfoLabel, mkReturnPtLabel, mkClosureTblLabel,
36                           CLabel, CLabelType(..), labelType, labelDynamic
37                         )
38
39 import CmdLineOpts      ( opt_SccProfilingOn, opt_GranMacros )
40 import CostCentre       ( pprCostCentreDecl, pprCostCentreStackDecl )
41
42 import Costs            ( costs, addrModeCosts, CostRes(..), Side(..) )
43 import CStrings         ( pprCLabelString )
44 import FiniteMap        ( addToFM, emptyFM, lookupFM, FiniteMap )
45 import Literal          ( Literal(..) )
46 import TyCon            ( tyConDataCons )
47 import Name             ( NamedThing(..) )
48 import Maybes           ( catMaybes )
49 import PrimOp           ( primOpNeedsWrapper )
50 import MachOp           ( MachOp(..) )
51 import PrimRep          ( isFloatingRep, PrimRep(..), getPrimRepSize )
52 import Unique           ( pprUnique, Unique{-instance NamedThing-} )
53 import UniqSet          ( emptyUniqSet, elementOfUniqSet,
54                           addOneToUniqSet, UniqSet
55                         )
56 import StgSyn           ( StgOp(..) )
57 import Outputable
58 import FastString
59 import Util             ( lengthExceeds )
60
61 #if __GLASGOW_HASKELL__ >= 504
62 import Data.Array.ST
63 #endif
64
65 #ifdef DEBUG
66 import Util             ( listLengthCmp )
67 #endif
68
69 import Maybe            ( isJust )
70 import GLAEXTS
71 import MONAD_ST
72
73 infixr 9 `thenTE`
74 \end{code}
75
76 For spitting out the costs of an abstract~C expression, @writeRealC@
77 now not only prints the C~code of the @absC@ arg but also adds a macro
78 call to a cost evaluation function @GRAN_EXEC@. For that,
79 @pprAbsC@ has a new ``costs'' argument.  %% HWL
80
81 \begin{code}
82 {-
83 writeRealC :: Handle -> AbstractC -> IO ()
84 writeRealC handle absC
85      -- avoid holding on to the whole of absC in the !Gransim case.
86      if opt_GranMacros
87         then printForCFast fp (pprAbsC absC (costs absC))
88         else printForCFast fp (pprAbsC absC (panic "costs"))
89              --printForC handle (pprAbsC absC (panic "costs"))
90 dumpRealC :: AbstractC -> SDoc
91 dumpRealC absC = pprAbsC absC (costs absC)
92 -}
93
94 writeRealC :: Handle -> AbstractC -> IO ()
95 --writeRealC handle absC = 
96 -- _scc_ "writeRealC" 
97 -- printDoc LeftMode handle (pprAbsC absC (costs absC))
98
99 writeRealC handle absC
100  | opt_GranMacros = _scc_ "writeRealC" printForC handle $ 
101                                        pprCode CStyle (pprAbsC absC (costs absC))
102  | otherwise      = _scc_ "writeRealC" printForC handle $
103                                        pprCode CStyle (pprAbsC absC (panic "costs"))
104
105 dumpRealC :: AbstractC -> SDoc
106 dumpRealC absC
107  | opt_GranMacros = pprCode CStyle (pprAbsC absC (costs absC))
108  | otherwise      = pprCode CStyle (pprAbsC absC (panic "costs"))
109
110 \end{code}
111
112 This emits the macro,  which is used in GrAnSim  to compute the total costs
113 from a cost 5 tuple. %%  HWL
114
115 \begin{code}
116 emitMacro :: CostRes -> SDoc
117
118 emitMacro _ | not opt_GranMacros = empty
119
120 emitMacro (Cost (i,b,l,s,f))
121   = hcat [ ptext SLIT("GRAN_EXEC"), char '(',
122                           int i, comma, int b, comma, int l, comma,
123                           int s, comma, int f, pp_paren_semi ]
124
125 pp_paren_semi = text ");"
126 \end{code}
127
128 New type: Now pprAbsC also takes the costs for evaluating the Abstract C
129 code as an argument (that's needed when spitting out the GRAN_EXEC macro
130 which must be done before the return i.e. inside absC code)   HWL
131
132 \begin{code}
133 pprAbsC :: AbstractC -> CostRes -> SDoc
134 pprAbsC AbsCNop _ = empty
135 pprAbsC (AbsCStmts s1 s2) c = ($$) (pprAbsC s1 c) (pprAbsC s2 c)
136
137 pprAbsC (CAssign dest src) _ = pprAssign (getAmodeRep dest) dest src
138
139 pprAbsC (CJump target) c
140   = ($$) (hcat [emitMacro c {-WDP:, text "/* <--++  CJump */"-} ])
141              (hcat [ text jmp_lit, pprAmode target, pp_paren_semi ])
142
143 pprAbsC (CFallThrough target) c
144   = ($$) (hcat [emitMacro c {-WDP:, text "/* <--++  CFallThrough */"-} ])
145              (hcat [ text jmp_lit, pprAmode target, pp_paren_semi ])
146
147 -- --------------------------------------------------------------------------
148 -- Spit out GRAN_EXEC macro immediately before the return                 HWL
149
150 pprAbsC (CReturn am return_info)  c
151   = ($$) (hcat [emitMacro c {-WDP:, text "/* <----  CReturn */"-} ])
152              (hcat [text jmp_lit, target, pp_paren_semi ])
153   where
154    target = case return_info of
155         DirectReturn -> hcat [ptext SLIT("ENTRY_CODE"), lparen,
156                               pprAmode am, rparen]
157         DynamicVectoredReturn am' -> mk_vector (pprAmode am')
158         StaticVectoredReturn n -> mk_vector (int n)     -- Always positive
159    mk_vector x = hcat [ptext SLIT("RET_VEC"), char '(', pprAmode am, comma,
160                        x, rparen ]
161
162 pprAbsC (CSplitMarker) _ = ptext SLIT("__STG_SPLIT_MARKER")
163
164 -- we optimise various degenerate cases of CSwitches.
165
166 -- --------------------------------------------------------------------------
167 -- Assume: CSwitch is also end of basic block
168 --         costs function yields nullCosts for whole switch
169 --         ==> inherited costs c are those of basic block up to switch
170 --         ==> inherit c + costs for the corresponding branch
171 --                                                                       HWL
172 -- --------------------------------------------------------------------------
173
174 pprAbsC (CSwitch discrim [] deflt) c
175   = pprAbsC deflt (c + costs deflt)
176     -- Empty alternative list => no costs for discrim as nothing cond. here HWL
177
178 pprAbsC (CSwitch discrim [(tag,alt_code)] deflt) c -- only one alt
179   = case (nonemptyAbsC deflt) of
180       Nothing ->                -- one alt and no default
181                  pprAbsC alt_code (c + costs alt_code)
182                  -- Nothing conditional in here either  HWL
183
184       Just dc ->                -- make it an "if"
185                  do_if_stmt discrim tag alt_code dc c
186
187 -- What problem is the re-ordering trying to solve ?
188 pprAbsC (CSwitch discrim [(tag1@(MachInt i1), alt_code1),
189                           (tag2@(MachInt i2), alt_code2)] deflt) c
190   | empty_deflt && ((i1 == 0 && i2 == 1) || (i1 == 1 && i2 == 0))
191   = if (i1 == 0) then
192         do_if_stmt discrim tag1 alt_code1 alt_code2 c
193     else
194         do_if_stmt discrim tag2 alt_code2 alt_code1 c
195   where
196     empty_deflt = not (isJust (nonemptyAbsC deflt))
197
198 pprAbsC (CSwitch discrim alts deflt) c -- general case
199   | isFloatingRep (getAmodeRep discrim)
200     = pprAbsC (foldr ( \ a -> CSwitch discrim [a]) deflt alts) c
201   | otherwise
202     = vcat [
203         hcat [text "switch (", pp_discrim, text ") {"],
204         nest 2 (vcat (map ppr_alt alts)),
205         (case (nonemptyAbsC deflt) of
206            Nothing -> empty
207            Just dc ->
208             nest 2 (vcat [ptext SLIT("default:"),
209                                   pprAbsC dc (c + switch_head_cost
210                                                     + costs dc),
211                                   ptext SLIT("break;")])),
212         char '}' ]
213   where
214     pp_discrim
215       = pprAmode discrim
216
217     ppr_alt (lit, absC)
218       = vcat [ hcat [ptext SLIT("case "), pprBasicLit lit, char ':'],
219                    nest 2 (($$) (pprAbsC absC (c + switch_head_cost + costs absC))
220                                        (ptext SLIT("break;"))) ]
221
222     -- Costs for addressing header of switch and cond. branching        -- HWL
223     switch_head_cost = addrModeCosts discrim Rhs + (Cost (0, 1, 0, 0, 0))
224
225 pprAbsC stmt@(COpStmt results (StgFCallOp fcall uniq) args vol_regs) _
226   = pprFCall fcall uniq args results vol_regs
227
228 pprAbsC stmt@(COpStmt results (StgPrimOp op) args vol_regs) _
229   = let
230         non_void_args = grab_non_void_amodes args
231         non_void_results = grab_non_void_amodes results
232         -- if just one result, we print in the obvious "assignment" style;
233         -- if 0 or many results, we emit a macro call, w/ the results
234         -- followed by the arguments.  The macro presumably knows which
235         -- are which :-)
236
237         the_op = ppr_op_call non_void_results non_void_args
238                 -- liveness mask is *in* the non_void_args
239     in
240     if primOpNeedsWrapper op then
241         case (ppr_vol_regs vol_regs) of { (pp_saves, pp_restores) ->
242         vcat [  pp_saves,
243                 the_op,
244                 pp_restores
245              ]
246         }
247     else
248         the_op
249   where
250     ppr_op_call results args
251       = hcat [ ppr op, lparen,
252         hcat (punctuate comma (map ppr_op_result results)),
253         if null results || null args then empty else comma,
254         hcat (punctuate comma (map pprAmode args)),
255         pp_paren_semi ]
256
257     ppr_op_result r = ppr_amode r
258       -- primop macros do their own casting of result;
259       -- hence we can toss the provided cast...
260
261 -- NEW CASES FOR EXPANDED PRIMOPS
262
263 pprAbsC stmt@(CMachOpStmt res mop [arg1,arg2] maybe_vols) _
264   = let prefix_fn = mop `elem` [MO_Dbl_Pwr, MO_Flt_Pwr, MO_NatS_MulMayOflo]
265     in
266     case ppr_maybe_vol_regs maybe_vols of {(saves,restores) ->
267     saves $$
268     hcat (
269        [ppr_amode res, equals]
270        ++ (if prefix_fn 
271            then [pprMachOp_for_C mop, parens (pprAmode arg1 <> comma <> pprAmode arg2)]
272            else [pprAmode arg1, pprMachOp_for_C mop, pprAmode arg2])
273        ++ [semi]
274     )
275     $$ restores
276     }
277
278 pprAbsC stmt@(CMachOpStmt res mop [arg1] maybe_vols) _
279   = case ppr_maybe_vol_regs maybe_vols of {(saves,restores) ->
280     saves $$
281     hcat [ppr_amode res, equals, 
282           pprMachOp_for_C mop, parens (pprAmode arg1),
283           semi]
284     $$ restores
285     }
286
287 pprAbsC stmt@(CSequential stuff) c
288   = vcat (map (flip pprAbsC c) stuff)
289
290 -- end of NEW CASES FOR EXPANDED PRIMOPS
291
292 pprAbsC stmt@(CSRT lbl closures) c
293   = case (pprTempAndExternDecls stmt) of { (_, pp_exts) ->
294          pp_exts
295       $$ ptext SLIT("SRT") <> lparen <> pprCLabel lbl <> rparen
296       $$ nest 2 (hcat (punctuate comma (map pp_closure_lbl closures)))
297          <> ptext SLIT("};")
298   }
299
300 pprAbsC stmt@(CBitmap liveness@(Liveness lbl size mask)) c
301   = pprWordArray lbl (mkWordCLit (fromIntegral size) : bitmapAddrModes mask)
302
303 pprAbsC stmt@(CSRTDesc desc_lbl srt_lbl off len bitmap) c
304   = pprWordArray desc_lbl (
305         CAddr (CIndex (CLbl srt_lbl DataPtrRep) (mkIntCLit off) WordRep) :
306         mkWordCLit (fromIntegral len) :
307         bitmapAddrModes bitmap
308      )
309
310 pprAbsC (CSimultaneous abs_c) c
311   = hcat [ptext SLIT("{{"), pprAbsC abs_c c, ptext SLIT("}}")]
312
313 pprAbsC (CCheck macro as code) c
314   = hcat [ptext (cCheckMacroText macro), lparen,
315        hcat (punctuate comma (map ppr_amode as)), comma,
316        pprAbsC code c, pp_paren_semi
317     ]
318 pprAbsC (CMacroStmt macro as) _
319   = hcat [ptext (cStmtMacroText macro), lparen,
320         hcat (punctuate comma (map ppr_amode as)),pp_paren_semi] -- no casting
321 pprAbsC (CCallProfCtrMacro op as) _
322   = hcat [ftext op, lparen,
323         hcat (punctuate comma (map ppr_amode as)),pp_paren_semi]
324 pprAbsC (CCallProfCCMacro op as) _
325   = hcat [ftext op, lparen,
326         hcat (punctuate comma (map ppr_amode as)),pp_paren_semi]
327 pprAbsC stmt@(CCallTypedef is_tdef (CCallSpec op_str cconv _) uniq results args) _
328   =  hsep [ ptext (if is_tdef then SLIT("typedef") else SLIT("extern"))
329           , ccall_res_ty
330           , fun_nm
331           , parens (hsep (punctuate comma ccall_decl_ty_args))
332           ] <> semi
333     where
334     {-
335       In the non-casm case, to ensure that we're entering the given external
336       entry point using the correct calling convention, we have to do the following:
337
338         - When entering via a function pointer (the `dynamic' case) using the specified
339           calling convention, we emit a typedefn declaration attributed with the
340           calling convention to use together with the result and parameter types we're
341           assuming. Coerce the function pointer to this type and go.
342
343         - to enter the function at a given code label, we emit an extern declaration
344           for the label here, stating the calling convention together with result and
345           argument types we're assuming. 
346
347           The C compiler will hopefully use this extern declaration to good effect,
348           reporting any discrepancies between our extern decl and any other that
349           may be in scope.
350     
351           Re: calling convention, notice that gcc (2.8.1 and egcs-1.0.2) will for
352           the external function `foo' use the calling convention of the first `foo'
353           prototype it encounters (nor does it complain about conflicting attribute
354           declarations). The consequence of this is that you cannot override the
355           calling convention of `foo' using an extern declaration (you'd have to use
356           a typedef), but why you would want to do such a thing in the first place
357           is totally beyond me.
358           
359           ToDo: petition the gcc folks to add code to warn about conflicting attribute
360           declarations.
361
362     -}
363
364      fun_nm
365        | is_tdef   = parens (text (ccallConvAttribute cconv) <+> char '*' <> ccall_fun_ty)
366        | otherwise = text (ccallConvAttribute cconv) <+> ccall_fun_ty
367
368      ccall_fun_ty = 
369         case op_str of
370           DynamicTarget  -> ptext SLIT("_ccall_fun_ty") <> ppr uniq
371           StaticTarget x -> pprCLabelString x
372
373      ccall_res_ty = 
374        case non_void_results of
375           []       -> ptext SLIT("void")
376           [amode]  -> ppr (getAmodeRep amode)
377           _        -> panic "pprAbsC{CCallTypedef}: ccall_res_ty"
378
379      ccall_decl_ty_args 
380        | is_tdef   = tail ccall_arg_tys
381        | otherwise = ccall_arg_tys
382
383      ccall_arg_tys      = map (ppr . getAmodeRep) non_void_args
384
385       -- the first argument will be the "I/O world" token (a VoidRep)
386       -- all others should be non-void
387      non_void_args =
388         let nvas = init args
389         in ASSERT (all non_void nvas) nvas
390
391       -- there will usually be two results: a (void) state which we
392       -- should ignore and a (possibly void) result.
393      non_void_results =
394         let nvrs = grab_non_void_amodes results
395         in ASSERT (listLengthCmp nvrs 1 /= GT) nvrs
396
397 pprAbsC (CCodeBlock lbl abs_C) _
398   = if not (isJust(nonemptyAbsC abs_C)) then
399         pprTrace "pprAbsC: curious empty code block for" (pprCLabel lbl) empty
400     else
401     case (pprTempAndExternDecls abs_C) of { (pp_temps, pp_exts) ->
402     vcat [
403         empty,
404         pp_exts, 
405         hcat [text (if (externallyVisibleCLabel lbl)
406                           then "FN_("   -- abbreviations to save on output
407                           else "IF_("),
408                    pprCLabel lbl, text ") {"],
409
410         pp_temps,
411
412         nest 8 (ptext SLIT("FB_")),
413         nest 8 (pprAbsC abs_C (costs abs_C)),
414         nest 8 (ptext SLIT("FE_")),
415         char '}',
416         char ' ' ]
417     }
418
419
420 pprAbsC (CInitHdr cl_info amode cost_centre size) _
421   = hcat [ ptext SLIT("SET_HDR_"), char '(',
422                 ppr_amode amode, comma,
423                 pprCLabelAddr info_lbl, comma,
424                 if_profiling (pprAmode cost_centre), comma,
425                 if_profiling (int size),
426                 pp_paren_semi ]
427   where
428     info_lbl    = infoTableLabelFromCI cl_info
429
430
431 pprAbsC stmt@(CStaticClosure closure_lbl cl_info cost_centre amodes) _
432   = case (pprTempAndExternDecls stmt) of { (_, pp_exts) ->
433     vcat [
434         pp_exts,
435         hcat [
436                 ptext SLIT("SET_STATIC_HDR"), char '(',
437                 pprCLabel closure_lbl,                          comma,
438                 pprCLabel info_lbl,                             comma,
439                 if_profiling (pprAmode cost_centre),            comma,
440                 ppLocalness closure_lbl,                        comma,
441                 ppLocalnessMacro True{-include dyn-} info_lbl,
442                 char ')'
443                 ],
444         nest 2 (ppr_payload amodes),
445         ptext SLIT("};") ]
446     }
447   where
448     info_lbl    = infoTableLabelFromCI cl_info
449
450     ppr_payload [] = empty
451     ppr_payload ls = 
452         comma <+> 
453           (braces $ hsep $ punctuate comma $
454            map (text "(L_)" <>) (foldr ppr_item [] ls))
455
456     ppr_item item rest
457       | rep == VoidRep   = rest
458       | rep == FloatRep  = ppr_amode (floatToWord item) : rest
459       | rep == DoubleRep = map ppr_amode (doubleToWords item) ++ rest
460       | otherwise        = ppr_amode item : rest
461       where 
462         rep  = getAmodeRep item
463
464 pprAbsC stmt@(CClosureInfoAndCode cl_info entry) _
465   =  pprWordArray info_lbl (mkInfoTable cl_info)
466   $$ let stuff = CCodeBlock entry_lbl entry in
467      pprAbsC stuff (costs stuff)
468   where
469         entry_lbl = entryLabelFromCI cl_info
470         info_lbl  = infoTableLabelFromCI cl_info
471
472 pprAbsC stmt@(CClosureTbl tycon) _
473   = vcat (
474         ptext SLIT("CLOSURE_TBL") <> 
475            lparen <> pprCLabel (mkClosureTblLabel tycon) <> rparen :
476         punctuate comma (
477            map (pp_closure_lbl . mkClosureLabel . getName) (tyConDataCons tycon)
478         )
479    ) $$ ptext SLIT("};")
480
481 pprAbsC stmt@(CRetDirect uniq code srt liveness) _
482   =  pprWordArray info_lbl (mkRetInfoTable entry_lbl srt liveness)
483   $$ let stuff = CCodeBlock entry_lbl code in
484      pprAbsC stuff (costs stuff)
485   where
486      info_lbl  = mkReturnInfoLabel uniq
487      entry_lbl = mkReturnPtLabel uniq
488
489 pprAbsC stmt@(CRetVector lbl amodes srt liveness) _
490   = pprWordArray lbl (mkVecInfoTable amodes srt liveness)
491
492 pprAbsC stmt@(CModuleInitBlock plain_lbl lbl code) _
493   = vcat [
494         ptext SLIT("START_MOD_INIT") <> 
495             parens (pprCLabel plain_lbl <> comma <> pprCLabel lbl),
496         case (pprTempAndExternDecls stmt) of { (_, pp_exts) -> pp_exts },
497         pprAbsC code (costs code),
498         hcat [ptext SLIT("END_MOD_INIT"), lparen, rparen]
499     ]
500
501 pprAbsC (CCostCentreDecl is_local cc) _ = pprCostCentreDecl is_local cc
502 pprAbsC (CCostCentreStackDecl ccs)    _ = pprCostCentreStackDecl ccs
503 \end{code}
504
505 Info tables... just arrays of words (the translation is done in
506 ClosureInfo).
507
508 \begin{code}
509 pprWordArray lbl amodes
510   = (case snd (initTE (ppr_decls_Amodes amodes)) of
511         Just pp -> pp
512         Nothing -> empty)
513   $$ hcat [ ppLocalness lbl, ptext SLIT("StgWord "), 
514             pprCLabel lbl, ptext SLIT("[] = {") ]
515   $$ hcat (punctuate comma (map (castToWord.pprAmode) amodes))
516   $$ ptext SLIT("};")
517
518 castToWord s = text "(W_)(" <> s <> char ')'
519 \end{code}
520
521 \begin{code}
522 -- Print a CMachOp in a way suitable for emitting via C.
523 pprMachOp_for_C MO_Nat_Add       = char '+'
524 pprMachOp_for_C MO_Nat_Sub       = char '-'
525 pprMachOp_for_C MO_Nat_Eq        = text "==" 
526 pprMachOp_for_C MO_Nat_Ne        = text "!="
527
528 pprMachOp_for_C MO_NatS_Ge       = text ">="
529 pprMachOp_for_C MO_NatS_Le       = text "<="
530 pprMachOp_for_C MO_NatS_Gt       = text ">"
531 pprMachOp_for_C MO_NatS_Lt       = text "<"
532
533 pprMachOp_for_C MO_NatU_Ge       = text ">="
534 pprMachOp_for_C MO_NatU_Le       = text "<="
535 pprMachOp_for_C MO_NatU_Gt       = text ">"
536 pprMachOp_for_C MO_NatU_Lt       = text "<"
537
538 pprMachOp_for_C MO_NatS_Mul      = char '*'
539 pprMachOp_for_C MO_NatS_MulMayOflo = text "mulIntMayOflo"
540 pprMachOp_for_C MO_NatS_Quot     = char '/'
541 pprMachOp_for_C MO_NatS_Rem      = char '%'
542 pprMachOp_for_C MO_NatS_Neg      = char '-'
543
544 pprMachOp_for_C MO_NatU_Mul      = char '*'
545 pprMachOp_for_C MO_NatU_Quot     = char '/'
546 pprMachOp_for_C MO_NatU_Rem      = char '%'
547
548 pprMachOp_for_C MO_Nat_And       = text "&"
549 pprMachOp_for_C MO_Nat_Or        = text "|"
550 pprMachOp_for_C MO_Nat_Xor       = text "^"
551 pprMachOp_for_C MO_Nat_Not       = text "~"
552 pprMachOp_for_C MO_Nat_Shl       = text "<<"
553 pprMachOp_for_C MO_Nat_Shr       = text ">>"
554 pprMachOp_for_C MO_Nat_Sar       = text ">>"
555
556 pprMachOp_for_C MO_32U_Eq        = text "=="
557 pprMachOp_for_C MO_32U_Ne        = text "!="
558 pprMachOp_for_C MO_32U_Ge        = text ">="
559 pprMachOp_for_C MO_32U_Le        = text "<="
560 pprMachOp_for_C MO_32U_Gt        = text ">"
561 pprMachOp_for_C MO_32U_Lt        = text "<"
562
563 pprMachOp_for_C MO_Dbl_Eq        = text "=="
564 pprMachOp_for_C MO_Dbl_Ne        = text "!="
565 pprMachOp_for_C MO_Dbl_Ge        = text ">="
566 pprMachOp_for_C MO_Dbl_Le        = text "<="
567 pprMachOp_for_C MO_Dbl_Gt        = text ">"
568 pprMachOp_for_C MO_Dbl_Lt        = text "<"
569
570 pprMachOp_for_C MO_Dbl_Add       = text "+"
571 pprMachOp_for_C MO_Dbl_Sub       = text "-"
572 pprMachOp_for_C MO_Dbl_Mul       = text "*"
573 pprMachOp_for_C MO_Dbl_Div       = text "/"
574 pprMachOp_for_C MO_Dbl_Pwr       = text "pow"
575
576 pprMachOp_for_C MO_Dbl_Sin       = text "sin"
577 pprMachOp_for_C MO_Dbl_Cos       = text "cos"
578 pprMachOp_for_C MO_Dbl_Tan       = text "tan"
579 pprMachOp_for_C MO_Dbl_Sinh      = text "sinh"
580 pprMachOp_for_C MO_Dbl_Cosh      = text "cosh"
581 pprMachOp_for_C MO_Dbl_Tanh      = text "tanh"
582 pprMachOp_for_C MO_Dbl_Asin      = text "asin"
583 pprMachOp_for_C MO_Dbl_Acos      = text "acos"
584 pprMachOp_for_C MO_Dbl_Atan      = text "atan"
585 pprMachOp_for_C MO_Dbl_Log       = text "log"
586 pprMachOp_for_C MO_Dbl_Exp       = text "exp"
587 pprMachOp_for_C MO_Dbl_Sqrt      = text "sqrt"
588 pprMachOp_for_C MO_Dbl_Neg       = text "-"
589
590 pprMachOp_for_C MO_Flt_Add       = text "+"
591 pprMachOp_for_C MO_Flt_Sub       = text "-"
592 pprMachOp_for_C MO_Flt_Mul       = text "*"
593 pprMachOp_for_C MO_Flt_Div       = text "/"
594 pprMachOp_for_C MO_Flt_Pwr       = text "pow"
595
596 pprMachOp_for_C MO_Flt_Eq        = text "=="
597 pprMachOp_for_C MO_Flt_Ne        = text "!="
598 pprMachOp_for_C MO_Flt_Ge        = text ">="
599 pprMachOp_for_C MO_Flt_Le        = text "<="
600 pprMachOp_for_C MO_Flt_Gt        = text ">"
601 pprMachOp_for_C MO_Flt_Lt        = text "<"
602
603 pprMachOp_for_C MO_Flt_Sin       = text "sin"
604 pprMachOp_for_C MO_Flt_Cos       = text "cos"
605 pprMachOp_for_C MO_Flt_Tan       = text "tan"
606 pprMachOp_for_C MO_Flt_Sinh      = text "sinh"
607 pprMachOp_for_C MO_Flt_Cosh      = text "cosh"
608 pprMachOp_for_C MO_Flt_Tanh      = text "tanh"
609 pprMachOp_for_C MO_Flt_Asin      = text "asin"
610 pprMachOp_for_C MO_Flt_Acos      = text "acos"
611 pprMachOp_for_C MO_Flt_Atan      = text "atan"
612 pprMachOp_for_C MO_Flt_Log       = text "log"
613 pprMachOp_for_C MO_Flt_Exp       = text "exp"
614 pprMachOp_for_C MO_Flt_Sqrt      = text "sqrt"
615 pprMachOp_for_C MO_Flt_Neg       = text "-"
616
617 pprMachOp_for_C MO_32U_to_NatS   = text "(StgInt)"
618 pprMachOp_for_C MO_NatS_to_32U   = text "(StgWord32)"
619
620 pprMachOp_for_C MO_NatS_to_Dbl   = text "(StgDouble)"
621 pprMachOp_for_C MO_Dbl_to_NatS   = text "(StgInt)"
622
623 pprMachOp_for_C MO_NatS_to_Flt   = text "(StgFloat)"
624 pprMachOp_for_C MO_Flt_to_NatS   = text "(StgInt)"
625
626 pprMachOp_for_C MO_NatS_to_NatU  = text "(StgWord)"
627 pprMachOp_for_C MO_NatU_to_NatS  = text "(StgInt)"
628
629 pprMachOp_for_C MO_NatS_to_NatP  = text "(void*)"
630 pprMachOp_for_C MO_NatP_to_NatS  = text "(StgInt)"
631 pprMachOp_for_C MO_NatU_to_NatP  = text "(void*)"
632 pprMachOp_for_C MO_NatP_to_NatU  = text "(StgWord)"
633
634 pprMachOp_for_C MO_Dbl_to_Flt    = text "(StgFloat)"
635 pprMachOp_for_C MO_Flt_to_Dbl    = text "(StgDouble)"
636
637 pprMachOp_for_C MO_8S_to_NatS    = text "(StgInt8)(StgInt)"
638 pprMachOp_for_C MO_16S_to_NatS   = text "(StgInt16)(StgInt)"
639 pprMachOp_for_C MO_32S_to_NatS   = text "(StgInt32)(StgInt)"
640
641 pprMachOp_for_C MO_8U_to_NatU    = text "(StgWord8)(StgWord)"
642 pprMachOp_for_C MO_16U_to_NatU   = text "(StgWord16)(StgWord)"
643 pprMachOp_for_C MO_32U_to_NatU   = text "(StgWord32)(StgWord)"
644
645 pprMachOp_for_C MO_8U_to_32U     = text "(StgWord32)"
646 pprMachOp_for_C MO_32U_to_8U     = text "(StgWord8)"
647
648
649 ppLocalness lbl
650   = if (externallyVisibleCLabel lbl) 
651                 then empty 
652                 else ptext SLIT("static ")
653
654 -- Horrible macros for declaring the types and locality of labels (see
655 -- StgMacros.h).
656
657 ppLocalnessMacro include_dyn_prefix clabel =
658      hcat [
659         visiblity_prefix,
660         dyn_prefix,
661         case label_type of
662           ClosureType        -> ptext SLIT("C_")
663           CodeType           -> ptext SLIT("F_")
664           InfoTblType        -> ptext SLIT("I_")
665           RetInfoTblType     -> ptext SLIT("RI_")
666           ClosureTblType     -> ptext SLIT("CP_")
667           DataType           -> ptext SLIT("D_")
668      ]
669   where
670    is_visible = externallyVisibleCLabel clabel
671    label_type = labelType clabel
672
673    visiblity_prefix
674      | is_visible = char 'E'
675      | otherwise  = char 'I'
676
677    dyn_prefix
678      | include_dyn_prefix && labelDynamic clabel = char 'D'
679      | otherwise                                 = empty
680
681 \end{code}
682
683 \begin{code}
684 jmp_lit = "JMP_("
685
686 grab_non_void_amodes amodes
687   = filter non_void amodes
688
689 non_void amode
690   = case (getAmodeRep amode) of
691       VoidRep -> False
692       k -> True
693 \end{code}
694
695 \begin{code}
696 ppr_maybe_vol_regs :: Maybe [MagicId] -> (SDoc, SDoc)
697 ppr_maybe_vol_regs Nothing
698    = (empty, empty)
699 ppr_maybe_vol_regs (Just vrs)
700    = case ppr_vol_regs vrs of
701         (saves, restores) 
702            -> (pp_basic_saves $$ saves,
703                pp_basic_restores $$ restores)
704
705 ppr_vol_regs :: [MagicId] -> (SDoc, SDoc)
706
707 ppr_vol_regs [] = (empty, empty)
708 ppr_vol_regs (VoidReg:rs) = ppr_vol_regs rs
709 ppr_vol_regs (r:rs)
710   = let pp_reg = case r of
711                     VanillaReg pk n -> pprVanillaReg n
712                     _ -> pprMagicId r
713         (more_saves, more_restores) = ppr_vol_regs rs
714     in
715     (($$) ((<>) (ptext SLIT("CALLER_SAVE_"))    pp_reg) more_saves,
716      ($$) ((<>) (ptext SLIT("CALLER_RESTORE_")) pp_reg) more_restores)
717
718 -- pp_basic_{saves,restores}: The BaseReg, Sp, Hp and
719 -- HpLim (see StgRegs.lh) may need to be saved/restored around CCalls,
720 -- depending on the platform.  (The "volatile regs" stuff handles all
721 -- other registers.)  Just be *sure* BaseReg is OK before trying to do
722 -- anything else. The correct sequence of saves&restores are
723 -- encoded by the CALLER_*_SYSTEM macros.
724 pp_basic_saves    = ptext SLIT("CALLER_SAVE_SYSTEM")
725 pp_basic_restores = ptext SLIT("CALLER_RESTORE_SYSTEM")
726 \end{code}
727
728 \begin{code}
729 pp_closure_lbl lbl
730       | labelDynamic lbl = text "DLL_SRT_ENTRY" <> parens (pprCLabel lbl)
731       | otherwise        = char '&' <> pprCLabel lbl
732 \end{code}
733
734 \begin{code}
735 if_profiling pretty
736   = if  opt_SccProfilingOn
737     then pretty
738     else char '0' -- leave it out!
739 -- ---------------------------------------------------------------------------
740 -- Changes for GrAnSim:
741 --  draw costs for computation in head of if into both branches;
742 --  as no abstractC data structure is given for the head, one is constructed
743 --  guessing unknown values and fed into the costs function
744 -- ---------------------------------------------------------------------------
745
746 do_if_stmt discrim tag alt_code deflt c
747    = let
748        cond = hcat [ pprAmode discrim
749                    , ptext SLIT(" == ")
750                    , tcast
751                    , pprAmode (CLit tag)
752                    ]
753         -- to be absolutely sure that none of the 
754         -- conversion rules hit, e.g.,
755         --
756         --     minInt is different to (int)minInt
757         --
758         -- in C (when minInt is a number not a constant
759         --  expression which evaluates to it.)
760         -- 
761        tcast = case tag of
762                    MachInt _  -> ptext SLIT("(I_)")
763                    _          -> empty
764      in
765      ppr_if_stmt cond
766                  alt_code deflt
767                  (addrModeCosts discrim Rhs) c
768
769 ppr_if_stmt pp_pred then_part else_part discrim_costs c
770   = vcat [
771       hcat [text "if (", pp_pred, text ") {"],
772       nest 8 (pprAbsC then_part         (c + discrim_costs +
773                                         (Cost (0, 2, 0, 0, 0)) +
774                                         costs then_part)),
775       (case nonemptyAbsC else_part of Nothing -> empty; Just _ -> text "} else {"),
776       nest 8 (pprAbsC else_part  (c + discrim_costs +
777                                         (Cost (0, 1, 0, 0, 0)) +
778                                         costs else_part)),
779       char '}' ]
780     {- Total costs = inherited costs (before if) + costs for accessing discrim
781                      + costs for cond branch ( = (0, 1, 0, 0, 0) )
782                      + costs for that alternative
783     -}
784 \end{code}
785
786 Historical note: this used to be two separate cases -- one for `ccall'
787 and one for `casm'.  To get round a potential limitation to only 10
788 arguments, the numbering of arguments in @process_casm@ was beefed up a
789 bit. ADR
790
791 Some rough notes on generating code for @CCallOp@:
792
793 1) Evaluate all arguments and stuff them into registers. (done elsewhere)
794 2) Save any essential registers (heap, stack, etc).
795
796    ToDo: If stable pointers are in use, these must be saved in a place
797    where the runtime system can get at them so that the Stg world can
798    be restarted during the call.
799
800 3) Save any temporary registers that are currently in use.
801 4) Do the call, putting result into a local variable
802 5) Restore essential registers
803 6) Restore temporaries
804
805    (This happens after restoration of essential registers because we
806    might need the @Base@ register to access all the others correctly.)
807
808    Otherwise, copy local variable into result register.
809
810 8) If ccall (not casm), declare the function being called as extern so
811    that C knows if it returns anything other than an int.
812
813 \begin{pseudocode}
814 { ResultType _ccall_result;
815   basic_saves;
816   saves;
817   _ccall_result = f( args );
818   basic_restores;
819   restores;
820
821   return_reg = _ccall_result;
822 }
823 \end{pseudocode}
824
825 Amendment to the above: if we can GC, we have to:
826
827 * make sure we save all our registers away where the garbage collector
828   can get at them.
829 * be sure that there are no live registers or we're in trouble.
830   (This can cause problems if you try something foolish like passing
831    an array or a foreign obj to a _ccall_GC_ thing.)
832 * increment/decrement the @inCCallGC@ counter before/after the call so
833   that the runtime check that PerformGC is being used sensibly will work.
834
835 \begin{code}
836 pprFCall call uniq args results vol_regs
837   = case call of
838       CCall (CCallSpec target _cconv safety) ->
839         vcat [ char '{',
840                 declare_local_vars,   -- local var for *result*
841                 vcat local_arg_decls,
842                 makeCall target safety 
843                          (process_casm local_vars pp_non_void_args (call_str target)),
844                 assign_results,
845               char '}'
846              ]
847       DNCall (DNCallSpec isStatic kind assem nm argTys resTy) ->
848          let
849           target    = StaticTarget (mkFastString nm)
850           resultVar = "_ccall_result"
851           
852           hasAssemArg = isStatic || kind == DNConstructor
853           invokeOp  = 
854             case kind of
855               DNMethod 
856                 | isStatic  -> "DN_invokeStatic"
857                 | otherwise -> "DN_invokeMethod"
858               DNField
859                 | isStatic ->
860                    if resTy == DNUnit 
861                     then "DN_setStatic"
862                     else "DN_getStatic"
863                 | otherwise ->
864                    if resTy == DNUnit 
865                     then "DN_setField"
866                     else "DN_getField"
867               DNConstructor -> "DN_createObject"
868
869           (methArrDecl, methArrInit, methArrName, methArrLen) 
870             | null argTys = (empty, empty, text "NULL", text "0")
871             | otherwise   = 
872               ( text "DotnetArg __meth_args[" <> int (length argTys) <> text "];"
873               , vcat (zipWith3 (\ idx arg argTy -> 
874                                  text "__meth_args[" <> int idx <> text "].arg." <> text (toDotnetArgField argTy) <> equals <> ppr_amode arg <> semi $$
875                                  text "__meth_args[" <> int idx <> text "].arg_type=" <> text (toDotnetTy argTy) <> semi)
876                                [0..]
877                                non_void_args
878                                argTys)
879               , text "__meth_args"
880               , int (length non_void_args)
881               )
882          in
883          vcat [ char '{',
884                   declare_local_vars,
885                   vcat local_arg_decls,
886                   vcat [ methArrDecl
887                        , methArrInit
888                        , text "_ccall_result1 =" <+> text invokeOp <> parens (
889                           hcat (punctuate comma $
890                                      (if hasAssemArg then
891                                         ((if null assem then 
892                                             text "NULL" 
893                                          else 
894                                             doubleQuotes (text assem)):)
895                                       else
896                                          id) $
897                                      [ doubleQuotes $ text nm
898                                      , methArrName
899                                      , methArrLen
900                                      , text (toDotnetTy resTy)
901                                      , text "(void*)&" <> text resultVar 
902                                      ])) <> semi
903                         ],
904                   assign_results,
905                 char '}'
906                ]
907   where
908     (pp_saves, pp_restores) = ppr_vol_regs vol_regs
909     
910     makeCall target safety theCall = 
911         vcat [ pp_save_context, theCall, pp_restore_context ]
912      where
913       (pp_save_context, pp_restore_context)
914         | playSafe safety = ( text "{ I_" <+> ppr_uniq_token <> 
915                                 text "; SUSPEND_THREAD" <> parens thread_macro_args <> semi
916                             , text "RESUME_THREAD" <> parens thread_macro_args <> text ";}"
917                             )
918         | otherwise = ( pp_basic_saves $$ pp_saves,
919                         pp_basic_restores $$ pp_restores)
920            where
921             thread_macro_args = ppr_uniq_token <> comma <+> 
922                                 text "rts" <> ppr (playThreadSafe safety)
923             ppr_uniq_token = text "tok_" <> ppr uniq
924
925
926     non_void_args = 
927         let nvas = init args
928         in ASSERT2 ( all non_void nvas, ppr call <+> hsep (map pprAmode args) )
929         nvas
930     -- the last argument will be the "I/O world" token (a VoidRep)
931     -- all others should be non-void
932
933     non_void_results =
934         let nvrs = grab_non_void_amodes results
935         in ASSERT (forDotnet || listLengthCmp nvrs 1 /= GT) nvrs
936     -- there will usually be two results: a (void) state which we
937     -- should ignore and a (possibly void) result.
938
939     (local_arg_decls, pp_non_void_args)
940       = unzip [ ppr_casm_arg a i | (a,i) <- non_void_args `zip` [1..] ]
941
942     (declare_local_vars, local_vars, assign_results)
943       = ppr_casm_results non_void_results forDotnet
944
945     forDotnet
946       = case call of
947           DNCall{} -> True
948           _ -> False
949
950     call_str tgt 
951       = case tgt of
952           StaticTarget fn -> mk_ccall_str (pprCLabelString fn) ccall_args
953           DynamicTarget   -> mk_ccall_str dyn_fun              (tail ccall_args)
954
955     ccall_args = zipWith (\ _ i -> char '%' <> int i) non_void_args [0..]
956     dyn_fun    = parens (parens (ptext SLIT("_ccall_fun_ty") <> ppr uniq) <> text "%0")
957                                                  
958
959     -- Remainder only used for ccall
960     mk_ccall_str fun_name ccall_fun_args = showSDoc
961         (hcat [
962                 if null non_void_results
963                   then empty
964                   else text "%r = ",
965                 lparen, fun_name, lparen,
966                   hcat (punctuate comma ccall_fun_args),
967                 text "));"
968         ])
969
970 toDotnetTy :: DNType -> String
971 toDotnetTy x = 
972   case x of 
973     DNByte -> "Dotnet_Byte"
974     DNBool -> "Dotnet_Bool"
975     DNChar -> "Dotnet_Char"
976     DNDouble -> "Dotnet_Double"
977     DNFloat  -> "Dotnet_Float"
978     DNInt    -> "Dotnet_Int"
979     DNInt8   -> "Dotnet_Int8"
980     DNInt16  -> "Dotnet_Int16"
981     DNInt32  -> "Dotnet_Int32"
982     DNInt64  -> "Dotnet_Int64"
983     DNWord8  -> "Dotnet_Word8"
984     DNWord16 -> "Dotnet_Word16"
985     DNWord32 -> "Dotnet_Word32"
986     DNWord64 -> "Dotnet_Word64"
987     DNPtr    -> "Dotnet_Ptr"
988     DNUnit   -> "Dotnet_Unit"
989     DNObject -> "Dotnet_Object"
990     DNString -> "Dotnet_String"
991
992 toDotnetArgField :: DNType -> String
993 toDotnetArgField x = 
994   case x of 
995     DNByte -> "arg_byte"
996     DNBool -> "arg_bool"
997     DNChar -> "arg_char"
998     DNDouble -> "arg_double"
999     DNFloat  -> "arg_float"
1000     DNInt    -> "arg_int"
1001     DNInt8   -> "arg_int8"
1002     DNInt16  -> "arg_int16"
1003     DNInt32  -> "arg_int32"
1004     DNInt64  -> "arg_int64"
1005     DNWord8  -> "arg_word8"
1006     DNWord16 -> "arg_word16"
1007     DNWord32 -> "arg_word32"
1008     DNWord64 -> "arg_word64"
1009     DNPtr    -> "arg_ptr"
1010     DNUnit   -> "arg_ptr" -- can't happen
1011     DNObject -> "arg_obj"
1012     DNString -> "arg_str"
1013
1014 ppr_casm_arg :: CAddrMode -> Int -> (SDoc, SDoc)
1015     -- (a) decl and assignment, (b) local var to be used later
1016
1017 ppr_casm_arg amode a_num
1018   = let
1019         a_kind   = getAmodeRep amode
1020         pp_amode = pprAmode amode
1021         pp_kind  = pprPrimKind a_kind
1022
1023         local_var  = (<>) (ptext SLIT("_ccall_arg")) (int a_num)
1024
1025         declare_local_var
1026           = hcat [ pp_kind, space, local_var, equals, pp_amode, semi ]
1027     in
1028     (declare_local_var, local_var)
1029 \end{code}
1030
1031 For l-values, the critical questions are:
1032
1033 1) Are there any results at all?
1034
1035    We only allow zero or one results.
1036
1037 \begin{code}
1038 ppr_casm_results
1039         :: [CAddrMode]  -- list of results (length <= 1)
1040         -> Bool         -- True => multiple results OK.
1041         ->
1042         ( SDoc,         -- declaration of any local vars
1043           [SDoc],       -- list of result vars (same length as results)
1044           SDoc )        -- assignment (if any) of results in local var to registers
1045
1046 ppr_casm_results [] _
1047   = (empty, [], empty)  -- no results
1048
1049 ppr_casm_results (r:rs) multiResultsOK
1050   | not multiResultsOK && not (null rs) = panic "ppr_casm_results: ccall/casm with many results"
1051   | otherwise
1052   = foldr (\ (a,b,c) (as,bs,cs) -> (a $$ as, b ++ bs, c $$ cs))
1053           (empty,[],empty)
1054           (zipWith pprRes (r:rs) ("" : map show [(1::Int)..]))
1055     where
1056       pprRes r suf = (declare_local_var, [local_var], assign_result)
1057        where
1058         result_reg = ppr_amode r
1059         r_kind     = getAmodeRep r
1060
1061         local_var  = ptext SLIT("_ccall_result") <> text suf
1062
1063         (result_type, assign_result)
1064           = (pprPrimKind r_kind,
1065              hcat [ result_reg, equals, local_var, semi ])
1066
1067         declare_local_var = hcat [ result_type, space, local_var, semi ]
1068
1069 \end{code}
1070
1071
1072 Note the sneaky way _the_ result is represented by a list so that we
1073 can complain if it's used twice.
1074
1075 ToDo: Any chance of giving line numbers when process-casm fails?
1076       Or maybe we should do a check _much earlier_ in compiler. ADR
1077
1078 \begin{code}
1079 process_casm :: [SDoc]          -- results (length <= 1)
1080              -> [SDoc]          -- arguments
1081              -> String          -- format string (with embedded %'s)
1082              -> SDoc            -- code being generated
1083
1084 process_casm results args string = process results args string
1085  where
1086   process []    _ "" = empty
1087   process (_:_) _ "" = error ("process_casm: non-void result not assigned while processing _casm_ \"" ++ 
1088                               string ++ 
1089                               "\"\n(Try changing result type to IO ()\n")
1090
1091   process ress args ('%':cs)
1092     = case cs of
1093         [] ->
1094             error ("process_casm: lonely % while processing _casm_ \"" ++ string ++ "\".\n")
1095
1096         ('%':css) ->
1097             char '%' <> process ress args css
1098
1099         ('r':css)  ->
1100           case ress of
1101             []  -> error ("process_casm: no result to match %r while processing _casm_ \"" ++ string ++ "\".\nTry deleting %r or changing result type from PrimIO ()\n")
1102             [r] -> r <> (process [] args css)
1103             _   -> panic ("process_casm: casm with many results while processing _casm_ \"" ++ string ++ "\".\n")
1104
1105         other ->
1106           let
1107                 read_int :: ReadS Int
1108                 read_int = reads
1109           in
1110           case (read_int other) of
1111             [(num,css)] ->
1112                   if num >= 0 && args `lengthExceeds` num
1113                   then parens (args !! num) <> process ress args css
1114                   else error ("process_casm: no such arg #:"++(show num)++" while processing \"" ++ string ++ "\".\n")
1115             _ -> error ("process_casm: not %<num> while processing _casm_ \"" ++ string ++ "\".\n")
1116
1117   process ress args (other_c:cs)
1118     = char other_c <> process ress args cs
1119 \end{code}
1120
1121 %************************************************************************
1122 %*                                                                      *
1123 \subsection[a2r-assignments]{Assignments}
1124 %*                                                                      *
1125 %************************************************************************
1126
1127 Printing assignments is a little tricky because of type coercion.
1128
1129 First of all, the kind of the thing being assigned can be gotten from
1130 the destination addressing mode.  (It should be the same as the kind
1131 of the source addressing mode.)  If the kind of the assignment is of
1132 @VoidRep@, then don't generate any code at all.
1133
1134 \begin{code}
1135 pprAssign :: PrimRep -> CAddrMode -> CAddrMode -> SDoc
1136
1137 pprAssign VoidRep dest src = empty
1138 \end{code}
1139
1140 Special treatment for floats and doubles, to avoid unwanted conversions.
1141
1142 \begin{code}
1143 pprAssign FloatRep dest@(CVal reg_rel _) src
1144   = hcat [ ptext SLIT("ASSIGN_FLT((W_*)"), parens (ppr_amode (CAddr reg_rel)), comma, pprAmode src, pp_paren_semi ]
1145
1146 pprAssign DoubleRep dest@(CVal reg_rel _) src
1147   = hcat [ ptext SLIT("ASSIGN_DBL((W_*)"), parens (ppr_amode (CAddr reg_rel)), comma, pprAmode src, pp_paren_semi ]
1148
1149 pprAssign Int64Rep dest@(CVal reg_rel _) src
1150   = hcat [ ptext SLIT("ASSIGN_Int64((W_*)"), parens (ppr_amode (CAddr reg_rel)), comma, pprAmode src, pp_paren_semi ]
1151 pprAssign Word64Rep dest@(CVal reg_rel _) src
1152   = hcat [ ptext SLIT("ASSIGN_Word64((W_*)"), parens (ppr_amode (CAddr reg_rel)), comma, pprAmode src, pp_paren_semi ]
1153 \end{code}
1154
1155 Lastly, the question is: will the C compiler think the types of the
1156 two sides of the assignment match?
1157
1158         We assume that the types will match if neither side is a
1159         @CVal@ addressing mode for any register which can point into
1160         the heap or stack.
1161
1162 Why?  Because the heap and stack are used to store miscellaneous
1163 things, whereas the temporaries, registers, etc., are only used for
1164 things of fixed type.
1165
1166 \begin{code}
1167 pprAssign kind (CReg (VanillaReg _ dest)) (CReg (VanillaReg _ src))
1168   = hcat [ pprVanillaReg dest, equals,
1169                 pprVanillaReg src, semi ]
1170
1171 pprAssign kind dest src
1172   | mixedTypeLocn dest
1173     -- Add in a cast to StgWord (a.k.a. W_) iff the destination is mixed
1174   = hcat [ ppr_amode dest, equals,
1175                 text "(W_)(",   -- Here is the cast
1176                 ppr_amode src, pp_paren_semi ]
1177
1178 pprAssign kind dest src
1179   | mixedPtrLocn dest && getAmodeRep src /= PtrRep
1180     -- Add in a cast to StgPtr (a.k.a. P_) iff the destination is mixed
1181   = hcat [ ppr_amode dest, equals,
1182                 text "(P_)(",   -- Here is the cast
1183                 ppr_amode src, pp_paren_semi ]
1184
1185 pprAssign kind other_dest src
1186   = hcat [ ppr_amode other_dest, equals,
1187                 pprAmode  src, semi ]
1188 \end{code}
1189
1190
1191 %************************************************************************
1192 %*                                                                      *
1193 \subsection[a2r-CAddrModes]{Addressing modes}
1194 %*                                                                      *
1195 %************************************************************************
1196
1197 @pprAmode@ is used to print r-values (which may need casts), whereas
1198 @ppr_amode@ is used for l-values {\em and} as a help function for
1199 @pprAmode@.
1200
1201 \begin{code}
1202 pprAmode, ppr_amode :: CAddrMode -> SDoc
1203 \end{code}
1204
1205 For reasons discussed above under assignments, @CVal@ modes need
1206 to be treated carefully.  First come special cases for floats and doubles,
1207 similar to those in @pprAssign@:
1208
1209 (NB: @PK_FLT@ and @PK_DBL@ require the {\em address} of the value in
1210 question.)
1211
1212 \begin{code}
1213 pprAmode (CVal reg_rel FloatRep)
1214   = hcat [ text "PK_FLT((W_*)", parens (ppr_amode (CAddr reg_rel)), rparen ]
1215 pprAmode (CVal reg_rel DoubleRep)
1216   = hcat [ text "PK_DBL((W_*)", parens (ppr_amode (CAddr reg_rel)), rparen ]
1217 pprAmode (CVal reg_rel Int64Rep)
1218   = hcat [ text "PK_Int64((W_*)", parens (ppr_amode (CAddr reg_rel)), rparen ]
1219 pprAmode (CVal reg_rel Word64Rep)
1220   = hcat [ text "PK_Word64((W_*)", parens (ppr_amode (CAddr reg_rel)), rparen ]
1221 \end{code}
1222
1223 Next comes the case where there is some other cast need, and the
1224 no-cast case:
1225
1226 \begin{code}
1227 pprAmode amode
1228   | mixedTypeLocn amode
1229   = parens (hcat [ pprPrimKind (getAmodeRep amode), ptext SLIT(")("),
1230                 ppr_amode amode ])
1231   | otherwise   -- No cast needed
1232   = ppr_amode amode
1233 \end{code}
1234
1235 When we have an indirection through a CIndex, we have to be careful to
1236 get the type casts right.  
1237
1238 this amode:
1239
1240         CVal (CIndex kind1 base offset) kind2
1241
1242 means (in C speak): 
1243         
1244         *(kind2 *)((kind1 *)base + offset)
1245
1246 That is, the indexing is done in units of kind1, but the resulting
1247 amode has kind2.
1248
1249 \begin{code}
1250 ppr_amode (CVal reg_rel@(CIndex _ _ _) kind)
1251   = case (pprRegRelative False{-no sign wanted-} reg_rel) of
1252         (pp_reg, Nothing)     -> panic "ppr_amode: CIndex"
1253         (pp_reg, Just offset) -> 
1254            hcat [ char '*', parens (pprPrimKind kind <> char '*'),
1255                   parens (pp_reg <> char '+' <> offset) ]
1256 \end{code}
1257
1258 Now the rest of the cases for ``workhorse'' @ppr_amode@:
1259
1260 \begin{code}
1261 ppr_amode (CVal reg_rel _)
1262   = case (pprRegRelative False{-no sign wanted-} reg_rel) of
1263         (pp_reg, Nothing)     -> (<>)  (char '*') pp_reg
1264         (pp_reg, Just offset) -> hcat [ pp_reg, brackets offset ]
1265
1266 ppr_amode (CAddr reg_rel)
1267   = case (pprRegRelative True{-sign wanted-} reg_rel) of
1268         (pp_reg, Nothing)     -> pp_reg
1269         (pp_reg, Just offset) -> pp_reg <> offset
1270
1271 ppr_amode (CReg magic_id) = pprMagicId magic_id
1272
1273 ppr_amode (CTemp uniq kind) = char '_' <> pprUnique uniq <> char '_'
1274
1275 ppr_amode (CLbl lbl kind) = pprCLabelAddr lbl 
1276
1277 ppr_amode (CCharLike ch)
1278   = hcat [ptext SLIT("CHARLIKE_CLOSURE"), char '(', pprAmode ch, rparen ]
1279 ppr_amode (CIntLike int)
1280   = hcat [ptext SLIT("INTLIKE_CLOSURE"), char '(', pprAmode int, rparen ]
1281
1282 ppr_amode (CLit lit) = pprBasicLit lit
1283
1284 ppr_amode (CJoinPoint _)
1285   = panic "ppr_amode: CJoinPoint"
1286
1287 ppr_amode (CMacroExpr pk macro as)
1288   = parens (ptext (cExprMacroText macro) <> 
1289             parens (hcat (punctuate comma (map pprAmode as))))
1290 \end{code}
1291
1292 \begin{code}
1293 cExprMacroText ENTRY_CODE               = SLIT("ENTRY_CODE")
1294 cExprMacroText ARG_TAG                  = SLIT("ARG_TAG")
1295 cExprMacroText GET_TAG                  = SLIT("GET_TAG")
1296 cExprMacroText CCS_HDR                  = SLIT("CCS_HDR")
1297 cExprMacroText BYTE_ARR_CTS             = SLIT("BYTE_ARR_CTS")
1298 cExprMacroText PTRS_ARR_CTS             = SLIT("PTRS_ARR_CTS")
1299 cExprMacroText ForeignObj_CLOSURE_DATA  = SLIT("ForeignObj_CLOSURE_DATA")
1300
1301 cStmtMacroText UPD_CAF                  = SLIT("UPD_CAF")
1302 cStmtMacroText UPD_BH_UPDATABLE         = SLIT("UPD_BH_UPDATABLE")
1303 cStmtMacroText UPD_BH_SINGLE_ENTRY      = SLIT("UPD_BH_SINGLE_ENTRY")
1304 cStmtMacroText PUSH_UPD_FRAME           = SLIT("PUSH_UPD_FRAME")
1305 cStmtMacroText SET_TAG                  = SLIT("SET_TAG")
1306 cStmtMacroText DATA_TO_TAGZH            = SLIT("dataToTagzh")
1307 cStmtMacroText REGISTER_FOREIGN_EXPORT  = SLIT("REGISTER_FOREIGN_EXPORT")
1308 cStmtMacroText REGISTER_IMPORT          = SLIT("REGISTER_IMPORT")
1309 cStmtMacroText REGISTER_DIMPORT         = SLIT("REGISTER_DIMPORT")
1310 cStmtMacroText GRAN_FETCH               = SLIT("GRAN_FETCH")
1311 cStmtMacroText GRAN_RESCHEDULE          = SLIT("GRAN_RESCHEDULE")
1312 cStmtMacroText GRAN_FETCH_AND_RESCHEDULE= SLIT("GRAN_FETCH_AND_RESCHEDULE")
1313 cStmtMacroText THREAD_CONTEXT_SWITCH    = SLIT("THREAD_CONTEXT_SWITCH")
1314 cStmtMacroText GRAN_YIELD               = SLIT("GRAN_YIELD")
1315
1316 cCheckMacroText HP_CHK_NP               = SLIT("HP_CHK_NP")
1317 cCheckMacroText STK_CHK_NP              = SLIT("STK_CHK_NP")
1318 cCheckMacroText HP_STK_CHK_NP           = SLIT("HP_STK_CHK_NP")
1319 cCheckMacroText HP_CHK_FUN              = SLIT("HP_CHK_FUN")
1320 cCheckMacroText STK_CHK_FUN             = SLIT("STK_CHK_FUN")
1321 cCheckMacroText HP_STK_CHK_FUN          = SLIT("HP_STK_CHK_FUN")
1322 cCheckMacroText HP_CHK_NOREGS           = SLIT("HP_CHK_NOREGS")
1323 cCheckMacroText HP_CHK_UNPT_R1          = SLIT("HP_CHK_UNPT_R1")
1324 cCheckMacroText HP_CHK_UNBX_R1          = SLIT("HP_CHK_UNBX_R1")
1325 cCheckMacroText HP_CHK_F1               = SLIT("HP_CHK_F1")
1326 cCheckMacroText HP_CHK_D1               = SLIT("HP_CHK_D1")
1327 cCheckMacroText HP_CHK_L1               = SLIT("HP_CHK_L1")
1328 cCheckMacroText HP_CHK_UNBX_TUPLE       = SLIT("HP_CHK_UNBX_TUPLE")
1329 \end{code}
1330
1331 %************************************************************************
1332 %*                                                                      *
1333 \subsection[ppr-liveness-masks]{Liveness Masks}
1334 %*                                                                      *
1335 %************************************************************************
1336
1337 \begin{code}
1338 bitmapAddrModes [] = [mkWordCLit 0]
1339 bitmapAddrModes xs = map mkWordCLit xs
1340 \end{code}
1341
1342 %************************************************************************
1343 %*                                                                      *
1344 \subsection[a2r-MagicIds]{Magic ids}
1345 %*                                                                      *
1346 %************************************************************************
1347
1348 @pprRegRelative@ returns a pair of the @Doc@ for the register
1349 (some casting may be required), and a @Maybe Doc@ for the offset
1350 (zero offset gives a @Nothing@).
1351
1352 \begin{code}
1353 addPlusSign :: Bool -> SDoc -> SDoc
1354 addPlusSign False p = p
1355 addPlusSign True  p = (<>) (char '+') p
1356
1357 pprSignedInt :: Bool -> Int -> Maybe SDoc       -- Nothing => 0
1358 pprSignedInt sign_wanted n
1359  = if n == 0 then Nothing else
1360    if n > 0  then Just (addPlusSign sign_wanted (int n))
1361    else           Just (int n)
1362
1363 pprRegRelative :: Bool          -- True <=> Print leading plus sign (if +ve)
1364                -> RegRelative
1365                -> (SDoc, Maybe SDoc)
1366
1367 pprRegRelative sign_wanted (SpRel off)
1368   = (pprMagicId Sp, pprSignedInt sign_wanted (I# off))
1369
1370 pprRegRelative sign_wanted r@(HpRel o)
1371   = let pp_Hp    = pprMagicId Hp; off = I# o
1372     in
1373     if off == 0 then
1374         (pp_Hp, Nothing)
1375     else
1376         (pp_Hp, Just ((<>) (char '-') (int off)))
1377
1378 pprRegRelative sign_wanted (NodeRel o)
1379   = let pp_Node = pprMagicId node; off = I# o
1380     in
1381     if off == 0 then
1382         (pp_Node, Nothing)
1383     else
1384         (pp_Node, Just (addPlusSign sign_wanted (int off)))
1385
1386 pprRegRelative sign_wanted (CIndex base offset kind)
1387   = ( hcat [text "((", pprPrimKind kind, text " *)(", ppr_amode base, text "))"]
1388     , Just (hcat [if sign_wanted then char '+' else empty,
1389             text "(I_)(", ppr_amode offset, ptext SLIT(")")])
1390     )
1391 \end{code}
1392
1393 @pprMagicId@ just prints the register name.  @VanillaReg@ registers are
1394 represented by a discriminated union (@StgUnion@), so we use the @PrimRep@
1395 to select the union tag.
1396
1397 \begin{code}
1398 pprMagicId :: MagicId -> SDoc
1399
1400 pprMagicId BaseReg                  = ptext SLIT("BaseReg")
1401 pprMagicId (VanillaReg pk n)
1402                                     = hcat [ pprVanillaReg n, char '.',
1403                                                   pprUnionTag pk ]
1404 pprMagicId (FloatReg  n)            = ptext SLIT("F") <> int (I# n)
1405 pprMagicId (DoubleReg n)            = ptext SLIT("D") <> int (I# n)
1406 pprMagicId (LongReg _ n)            = ptext SLIT("L") <> int (I# n)
1407 pprMagicId Sp                       = ptext SLIT("Sp")
1408 pprMagicId SpLim                    = ptext SLIT("SpLim")
1409 pprMagicId Hp                       = ptext SLIT("Hp")
1410 pprMagicId HpLim                    = ptext SLIT("HpLim")
1411 pprMagicId CurCostCentre            = ptext SLIT("CCCS")
1412 pprMagicId VoidReg                  = ptext SLIT("VoidReg")
1413
1414 pprVanillaReg :: Int# -> SDoc
1415 pprVanillaReg n = char 'R' <> int (I# n)
1416
1417 pprUnionTag :: PrimRep -> SDoc
1418
1419 pprUnionTag PtrRep              = char 'p'
1420 pprUnionTag CodePtrRep          = ptext SLIT("fp")
1421 pprUnionTag DataPtrRep          = char 'd'
1422 pprUnionTag RetRep              = char 'p'
1423 pprUnionTag CostCentreRep       = panic "pprUnionTag:CostCentre?"
1424
1425 pprUnionTag CharRep             = char 'c'
1426 pprUnionTag Int8Rep             = ptext SLIT("i8")
1427 pprUnionTag IntRep              = char 'i'
1428 pprUnionTag WordRep             = char 'w'
1429 pprUnionTag Int32Rep            = char 'i'
1430 pprUnionTag Word32Rep           = char 'w'
1431 pprUnionTag AddrRep             = char 'a'
1432 pprUnionTag FloatRep            = char 'f'
1433 pprUnionTag DoubleRep           = panic "pprUnionTag:Double?"
1434
1435 pprUnionTag StablePtrRep        = char 'p'
1436
1437 pprUnionTag _                   = panic "pprUnionTag:Odd kind"
1438 \end{code}
1439
1440
1441 Find and print local and external declarations for a list of
1442 Abstract~C statements.
1443 \begin{code}
1444 pprTempAndExternDecls :: AbstractC -> (SDoc{-temps-}, SDoc{-externs-})
1445 pprTempAndExternDecls AbsCNop = (empty, empty)
1446
1447 pprTempAndExternDecls (AbsCStmts stmt1 stmt2)
1448   = initTE (ppr_decls_AbsC stmt1        `thenTE` \ (t_p1, e_p1) ->
1449             ppr_decls_AbsC stmt2        `thenTE` \ (t_p2, e_p2) ->
1450             case (catMaybes [t_p1, t_p2])        of { real_temps ->
1451             case (catMaybes [e_p1, e_p2])        of { real_exts ->
1452             returnTE (vcat real_temps, vcat real_exts) }}
1453            )
1454
1455 pprTempAndExternDecls other_stmt
1456   = initTE (ppr_decls_AbsC other_stmt `thenTE` \ (maybe_t, maybe_e) ->
1457             returnTE (
1458                 case maybe_t of
1459                   Nothing -> empty
1460                   Just pp -> pp,
1461
1462                 case maybe_e of
1463                   Nothing -> empty
1464                   Just pp -> pp )
1465            )
1466
1467 pprBasicLit :: Literal -> SDoc
1468 pprPrimKind :: PrimRep -> SDoc
1469
1470 pprBasicLit  lit = ppr lit
1471 pprPrimKind  k   = ppr k
1472 \end{code}
1473
1474
1475 %************************************************************************
1476 %*                                                                      *
1477 \subsection[a2r-monad]{Monadery}
1478 %*                                                                      *
1479 %************************************************************************
1480
1481 We need some monadery to keep track of temps and externs we have already
1482 printed.  This info must be threaded right through the Abstract~C, so
1483 it's most convenient to hide it in this monad.
1484
1485 WDP 95/02: Switched from \tr{([Unique], [CLabel])} to
1486 \tr{(UniqSet, CLabelSet)}.  Allegedly for efficiency.
1487
1488 \begin{code}
1489 type CLabelSet = FiniteMap CLabel (){-any type will do-}
1490 emptyCLabelSet = emptyFM
1491 x `elementOfCLabelSet` labs
1492   = case (lookupFM labs x) of { Just _ -> True; Nothing -> False }
1493
1494 addToCLabelSet set x = addToFM set x ()
1495
1496 type TEenv = (UniqSet Unique, CLabelSet)
1497
1498 type TeM result =  TEenv -> (TEenv, result)
1499
1500 initTE :: TeM a -> a
1501 initTE sa
1502   = case sa (emptyUniqSet, emptyCLabelSet) of { (_, result) ->
1503     result }
1504
1505 {-# INLINE thenTE #-}
1506 {-# INLINE returnTE #-}
1507
1508 thenTE :: TeM a -> (a -> TeM b) -> TeM b
1509 thenTE a b u
1510   = case a u        of { (u_1, result_of_a) ->
1511     b result_of_a u_1 }
1512
1513 mapTE :: (a -> TeM b) -> [a] -> TeM [b]
1514 mapTE f []     = returnTE []
1515 mapTE f (x:xs)
1516   = f x         `thenTE` \ r  ->
1517     mapTE f xs  `thenTE` \ rs ->
1518     returnTE (r : rs)
1519
1520 returnTE :: a -> TeM a
1521 returnTE result env = (env, result)
1522
1523 -- these next two check whether the thing is already
1524 -- recorded, and THEN THEY RECORD IT
1525 -- (subsequent calls will return False for the same uniq/label)
1526
1527 tempSeenTE :: Unique -> TeM Bool
1528 tempSeenTE uniq env@(seen_uniqs, seen_labels)
1529   = if (uniq `elementOfUniqSet` seen_uniqs)
1530     then (env, True)
1531     else ((addOneToUniqSet seen_uniqs uniq,
1532           seen_labels),
1533           False)
1534
1535 labelSeenTE :: CLabel -> TeM Bool
1536 labelSeenTE lbl env@(seen_uniqs, seen_labels)
1537   = if (lbl `elementOfCLabelSet` seen_labels)
1538     then (env, True)
1539     else ((seen_uniqs,
1540           addToCLabelSet seen_labels lbl),
1541           False)
1542 \end{code}
1543
1544 \begin{code}
1545 pprTempDecl :: Unique -> PrimRep -> SDoc
1546 pprTempDecl uniq kind
1547   = hcat [ pprPrimKind kind, space, char '_', pprUnique uniq, ptext SLIT("_;") ]
1548
1549 pprExternDecl :: Bool -> CLabel -> SDoc
1550 pprExternDecl in_srt clabel
1551   | not (needsCDecl clabel) = empty -- do not print anything for "known external" things
1552   | otherwise               = 
1553         hcat [ ppLocalnessMacro (not in_srt) clabel, 
1554                lparen, dyn_wrapper (pprCLabel clabel), pp_paren_semi ]
1555  where
1556   dyn_wrapper d
1557     | in_srt && labelDynamic clabel = text "DLL_IMPORT_DATA_VAR" <> parens d
1558     | otherwise                     = d
1559
1560 \end{code}
1561
1562 \begin{code}
1563 ppr_decls_AbsC :: AbstractC -> TeM (Maybe SDoc{-temps-}, Maybe SDoc{-externs-})
1564
1565 ppr_decls_AbsC AbsCNop          = returnTE (Nothing, Nothing)
1566
1567 ppr_decls_AbsC (AbsCStmts stmts_1 stmts_2)
1568   = ppr_decls_AbsC stmts_1  `thenTE` \ p1 ->
1569     ppr_decls_AbsC stmts_2  `thenTE` \ p2 ->
1570     returnTE (maybe_vcat [p1, p2])
1571
1572 ppr_decls_AbsC (CSplitMarker) = returnTE (Nothing, Nothing)
1573
1574 ppr_decls_AbsC (CAssign dest source)
1575   = ppr_decls_Amode dest    `thenTE` \ p1 ->
1576     ppr_decls_Amode source  `thenTE` \ p2 ->
1577     returnTE (maybe_vcat [p1, p2])
1578
1579 ppr_decls_AbsC (CJump target) = ppr_decls_Amode target
1580
1581 ppr_decls_AbsC (CFallThrough target) = ppr_decls_Amode target
1582
1583 ppr_decls_AbsC (CReturn target _) = ppr_decls_Amode target
1584
1585 ppr_decls_AbsC (CSwitch discrim alts deflt)
1586   = ppr_decls_Amode discrim     `thenTE` \ pdisc ->
1587     mapTE ppr_alt_stuff alts    `thenTE` \ palts  ->
1588     ppr_decls_AbsC deflt        `thenTE` \ pdeflt ->
1589     returnTE (maybe_vcat (pdisc:pdeflt:palts))
1590   where
1591     ppr_alt_stuff (_, absC) = ppr_decls_AbsC absC
1592
1593 ppr_decls_AbsC (CCodeBlock lbl absC)
1594   = ppr_decls_AbsC absC
1595
1596 ppr_decls_AbsC (CInitHdr cl_info reg_rel cost_centre _)
1597         -- ToDo: strictly speaking, should chk "cost_centre" amode
1598   = labelSeenTE info_lbl     `thenTE` \  label_seen ->
1599     returnTE (Nothing,
1600               if label_seen then
1601                   Nothing
1602               else
1603                   Just (pprExternDecl False{-not in an SRT decl-} info_lbl))
1604   where
1605     info_lbl = infoTableLabelFromCI cl_info
1606
1607 ppr_decls_AbsC (CMachOpStmt res _ args _) = ppr_decls_Amodes (res : args)
1608 ppr_decls_AbsC (COpStmt results _ args _) = ppr_decls_Amodes (results ++ args)
1609
1610 ppr_decls_AbsC (CSimultaneous abc)        = ppr_decls_AbsC abc
1611
1612 ppr_decls_AbsC (CSequential abcs) 
1613   = mapTE ppr_decls_AbsC abcs   `thenTE` \ t_and_e_s ->
1614     returnTE (maybe_vcat t_and_e_s)
1615
1616 ppr_decls_AbsC (CCheck              _ amodes code) = 
1617      ppr_decls_Amodes amodes `thenTE` \p1 ->
1618      ppr_decls_AbsC code     `thenTE` \p2 ->
1619      returnTE (maybe_vcat [p1,p2])
1620
1621 ppr_decls_AbsC (CMacroStmt          _ amodes)   = ppr_decls_Amodes amodes
1622
1623 ppr_decls_AbsC (CCallProfCtrMacro   _ amodes)   = ppr_decls_Amodes [] -- *****!!!
1624   -- you get some nasty re-decls of stdio.h if you compile
1625   -- the prelude while looking inside those amodes;
1626   -- no real reason to, anyway.
1627 ppr_decls_AbsC (CCallProfCCMacro    _ amodes)   = ppr_decls_Amodes amodes
1628
1629 ppr_decls_AbsC (CStaticClosure _ closure_info cost_centre amodes)
1630         -- ToDo: strictly speaking, should chk "cost_centre" amode
1631   = ppr_decls_Amodes amodes
1632
1633 ppr_decls_AbsC (CClosureInfoAndCode cl_info entry)
1634   = ppr_decls_Amodes [entry_lbl]                `thenTE` \ p1 ->
1635     ppr_decls_AbsC entry                        `thenTE` \ p2 ->
1636     returnTE (maybe_vcat [p1, p2])
1637   where
1638     entry_lbl = CLbl (entryLabelFromCI cl_info) CodePtrRep
1639
1640 ppr_decls_AbsC (CSRT _ closure_lbls)
1641   = mapTE labelSeenTE closure_lbls              `thenTE` \ seen ->
1642     returnTE (Nothing, 
1643               if and seen then Nothing
1644                 else Just (vcat [ pprExternDecl True{-in SRT decl-} l
1645                                 | (l,False) <- zip closure_lbls seen ]))
1646
1647 ppr_decls_AbsC (CRetDirect     _ code _ _)   = ppr_decls_AbsC code
1648 ppr_decls_AbsC (CRetVector _ amodes _ _)     = ppr_decls_Amodes amodes
1649 ppr_decls_AbsC (CModuleInitBlock _ _ code)   = ppr_decls_AbsC code
1650
1651 ppr_decls_AbsC (_) = returnTE (Nothing, Nothing)
1652 \end{code}
1653
1654 \begin{code}
1655 ppr_decls_Amode :: CAddrMode -> TeM (Maybe SDoc, Maybe SDoc)
1656 ppr_decls_Amode (CVal  (CIndex base offset _) _) = ppr_decls_Amodes [base,offset]
1657 ppr_decls_Amode (CAddr (CIndex base offset _))   = ppr_decls_Amodes [base,offset]
1658 ppr_decls_Amode (CVal _ _)      = returnTE (Nothing, Nothing)
1659 ppr_decls_Amode (CAddr _)       = returnTE (Nothing, Nothing)
1660 ppr_decls_Amode (CReg _)        = returnTE (Nothing, Nothing)
1661 ppr_decls_Amode (CLit _)        = returnTE (Nothing, Nothing)
1662
1663 -- CIntLike must be a literal -- no decls
1664 ppr_decls_Amode (CIntLike int)  = returnTE (Nothing, Nothing)
1665
1666 -- CCharLike too
1667 ppr_decls_Amode (CCharLike char) = returnTE (Nothing, Nothing)
1668
1669 -- now, the only place where we actually print temps/externs...
1670 ppr_decls_Amode (CTemp uniq kind)
1671   = case kind of
1672       VoidRep -> returnTE (Nothing, Nothing)
1673       other ->
1674         tempSeenTE uniq `thenTE` \ temp_seen ->
1675         returnTE
1676           (if temp_seen then Nothing else Just (pprTempDecl uniq kind), Nothing)
1677
1678 ppr_decls_Amode (CLbl lbl VoidRep)
1679   = returnTE (Nothing, Nothing)
1680
1681 ppr_decls_Amode (CLbl lbl kind)
1682   = labelSeenTE lbl `thenTE` \ label_seen ->
1683     returnTE (Nothing,
1684               if label_seen then Nothing else Just (pprExternDecl False{-not in an SRT decl-} lbl))
1685
1686 ppr_decls_Amode (CMacroExpr _ _ amodes)
1687   = ppr_decls_Amodes amodes
1688
1689 ppr_decls_Amode other = returnTE (Nothing, Nothing)
1690
1691
1692 maybe_vcat :: [(Maybe SDoc, Maybe SDoc)] -> (Maybe SDoc, Maybe SDoc)
1693 maybe_vcat ps
1694   = case (unzip ps)     of { (ts, es) ->
1695     case (catMaybes ts) of { real_ts  ->
1696     case (catMaybes es) of { real_es  ->
1697     (if (null real_ts) then Nothing else Just (vcat real_ts),
1698      if (null real_es) then Nothing else Just (vcat real_es))
1699     } } }
1700 \end{code}
1701
1702 \begin{code}
1703 ppr_decls_Amodes :: [CAddrMode] -> TeM (Maybe SDoc, Maybe SDoc)
1704 ppr_decls_Amodes amodes
1705   = mapTE ppr_decls_Amode amodes `thenTE` \ ps ->
1706     returnTE ( maybe_vcat ps )
1707 \end{code}
1708
1709 Print out a C Label where you want the *address* of the label, not the
1710 object it refers to.  The distinction is important when the label may
1711 refer to a C structure (info tables and closures, for instance).
1712
1713 When just generating a declaration for the label, use pprCLabel.
1714
1715 \begin{code}
1716 pprCLabelAddr :: CLabel -> SDoc
1717 pprCLabelAddr clabel =
1718   case labelType clabel of
1719      InfoTblType    -> addr_of_label
1720      RetInfoTblType -> addr_of_label
1721      ClosureType    -> addr_of_label
1722      VecTblType     -> addr_of_label
1723      DataType       -> addr_of_label
1724
1725      _              -> pp_label
1726   where
1727     addr_of_label = ptext SLIT("(P_)&") <> pp_label
1728     pp_label = pprCLabel clabel
1729 \end{code}
1730
1731 -----------------------------------------------------------------------------
1732 Initialising static objects with floating-point numbers.  We can't
1733 just emit the floating point number, because C will cast it to an int
1734 by rounding it.  We want the actual bit-representation of the float.
1735
1736 This is a hack to turn the floating point numbers into ints that we
1737 can safely initialise to static locations.
1738
1739 \begin{code}
1740 big_doubles = (getPrimRepSize DoubleRep) /= 1
1741
1742 #if __GLASGOW_HASKELL__ >= 504
1743 newFloatArray :: (Int,Int) -> ST s (STUArray s Int Float)
1744 newFloatArray = newArray_
1745
1746 newDoubleArray :: (Int,Int) -> ST s (STUArray s Int Double)
1747 newDoubleArray = newArray_
1748
1749 castFloatToIntArray :: STUArray s Int Float -> ST s (STUArray s Int Int)
1750 castFloatToIntArray = castSTUArray
1751
1752 castDoubleToIntArray :: STUArray s Int Double -> ST s (STUArray s Int Int)
1753 castDoubleToIntArray = castSTUArray
1754
1755 writeFloatArray :: STUArray s Int Float -> Int -> Float -> ST s ()
1756 writeFloatArray = writeArray
1757
1758 writeDoubleArray :: STUArray s Int Double -> Int -> Double -> ST s ()
1759 writeDoubleArray = writeArray
1760
1761 readIntArray :: STUArray s Int Int -> Int -> ST s Int
1762 readIntArray = readArray
1763
1764 #else
1765
1766 castFloatToIntArray :: MutableByteArray s t -> ST s (MutableByteArray s t)
1767 castFloatToIntArray = return
1768
1769 castDoubleToIntArray :: MutableByteArray s t -> ST s (MutableByteArray s t)
1770 castDoubleToIntArray = return
1771
1772 #endif
1773
1774 -- floats are always 1 word
1775 floatToWord :: CAddrMode -> CAddrMode
1776 floatToWord (CLit (MachFloat r))
1777   = runST (do
1778         arr <- newFloatArray ((0::Int),0)
1779         writeFloatArray arr 0 (fromRational r)
1780         arr' <- castFloatToIntArray arr
1781         i <- readIntArray arr' 0
1782         return (CLit (MachInt (toInteger i)))
1783     )
1784
1785 doubleToWords :: CAddrMode -> [CAddrMode]
1786 doubleToWords (CLit (MachDouble r))
1787   | big_doubles                         -- doubles are 2 words
1788   = runST (do
1789         arr <- newDoubleArray ((0::Int),1)
1790         writeDoubleArray arr 0 (fromRational r)
1791         arr' <- castDoubleToIntArray arr
1792         i1 <- readIntArray arr' 0
1793         i2 <- readIntArray arr' 1
1794         return [ CLit (MachInt (toInteger i1))
1795                , CLit (MachInt (toInteger i2))
1796                ]
1797     )
1798   | otherwise                           -- doubles are 1 word
1799   = runST (do
1800         arr <- newDoubleArray ((0::Int),0)
1801         writeDoubleArray arr 0 (fromRational r)
1802         arr' <- castDoubleToIntArray arr
1803         i <- readIntArray arr' 0
1804         return [ CLit (MachInt (toInteger i)) ]
1805     )
1806 \end{code}