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