[project @ 2005-03-31 10:16:33 by simonmar]
[ghc-hetmet.git] / ghc / compiler / cmm / PprC.hs
1 -----------------------------------------------------------------------------
2 --
3 -- Pretty-printing of Cmm as C, suitable for feeding gcc
4 --
5 -- (c) The University of Glasgow 2004
6 --
7 -----------------------------------------------------------------------------
8
9 --
10 -- Print Cmm as real C, for -fvia-C
11 --
12 -- This is simpler than the old PprAbsC, because Cmm is "macro-expanded"
13 -- relative to the old AbstractC, and many oddities/decorations have
14 -- disappeared from the data type.
15 --
16
17 -- ToDo: save/restore volatile registers around calls.
18
19 module PprC (
20         writeCs,
21         pprStringInCStyle 
22   ) where
23
24 #include "HsVersions.h"
25
26 -- Cmm stuff
27 import Cmm
28 import CLabel
29 import MachOp
30 import ForeignCall
31
32 -- Utils
33 import DynFlags         ( DynFlags, DynFlag(..), dopt )
34 import Unique           ( getUnique )
35 import UniqSet
36 import FiniteMap
37 import UniqFM           ( eltsUFM )
38 import FastString
39 import Outputable
40 import Constants
41
42 -- The rest
43 import Data.List        ( intersperse, groupBy )
44 import Data.Bits        ( shiftR )
45 import Char             ( ord, chr )
46 import IO               ( Handle )
47 import DATA_BITS
48
49 #ifdef DEBUG
50 import PprCmm           () -- instances only
51 -- import Debug.Trace
52 #endif
53
54 #if __GLASGOW_HASKELL__ >= 504
55 import Data.Array.ST
56 #endif
57 import MONAD_ST
58
59 -- --------------------------------------------------------------------------
60 -- Top level
61
62 pprCs :: DynFlags -> [Cmm] -> SDoc
63 pprCs dflags cmms
64  = pprCode CStyle (vcat $ map (\c -> split_marker $$ pprC c) cmms)
65  where
66    split_marker
67      | dopt Opt_SplitObjs dflags = ptext SLIT("__STG_SPLIT_MARKER")
68      | otherwise                 = empty
69
70 writeCs :: DynFlags -> Handle -> [Cmm] -> IO ()
71 writeCs dflags handle cmms 
72   = printForUser handle alwaysQualify (pprCs dflags cmms)
73         -- ToDo: should be printForC
74
75 -- --------------------------------------------------------------------------
76 -- Now do some real work
77 --
78 -- for fun, we could call cmmToCmm over the tops...
79 --
80
81 pprC :: Cmm -> SDoc
82 pprC (Cmm tops) = vcat $ intersperse (text "") $ map pprTop tops
83
84 --
85 -- top level procs
86 -- 
87 pprTop :: CmmTop -> SDoc
88 pprTop (CmmProc info clbl _params blocks) =
89     (if not (null info)
90         then pprDataExterns info $$
91              pprWordArray (entryLblToInfoLbl clbl) info
92         else empty) $$
93     (case blocks of
94         [] -> empty
95          -- the first block doesn't get a label:
96         (BasicBlock _ stmts : rest) -> vcat [
97            text "",
98            extern_decls,
99            (if (externallyVisibleCLabel clbl)
100                     then mkFN_ else mkIF_) (pprCLabel clbl) <+> lbrace,
101            nest 8 temp_decls,
102            nest 8 mkFB_,
103            nest 8 (vcat (map pprStmt stmts)) $$
104               vcat (map pprBBlock rest),
105            nest 8 mkFE_,
106            rbrace ]
107     )
108   where
109         (temp_decls, extern_decls) = pprTempAndExternDecls blocks 
110
111
112 -- Chunks of static data.
113
114 -- We only handle (a) arrays of word-sized things and (b) strings.
115
116 pprTop (CmmData _section _ds@[CmmDataLabel lbl, CmmString str]) = 
117   hcat [
118     pprLocalness lbl, ptext SLIT("char "), pprCLabel lbl,
119     ptext SLIT("[] = "), pprStringInCStyle str, semi
120   ]
121
122 pprTop (CmmData _section _ds@[CmmDataLabel lbl, CmmUninitialised size]) = 
123   hcat [
124     pprLocalness lbl, ptext SLIT("char "), pprCLabel lbl,
125     brackets (int size), semi
126   ]
127
128 pprTop top@(CmmData _section (CmmDataLabel lbl : lits)) = 
129   pprDataExterns lits $$
130   pprWordArray lbl lits  
131
132 -- these shouldn't appear?
133 pprTop (CmmData _ _) = panic "PprC.pprTop: can't handle this data"
134
135
136 -- --------------------------------------------------------------------------
137 -- BasicBlocks are self-contained entities: they always end in a jump.
138 --
139 -- Like nativeGen/AsmCodeGen, we could probably reorder blocks to turn
140 -- as many jumps as possible into fall throughs.
141 --
142
143 pprBBlock :: CmmBasicBlock -> SDoc
144 pprBBlock (BasicBlock lbl stmts) = 
145     if null stmts then
146         pprTrace "pprC.pprBBlock: curious empty code block for" 
147                         (pprBlockId lbl) empty
148     else 
149         nest 4 (pprBlockId lbl <> colon) $$
150         nest 8 (vcat (map pprStmt stmts))
151
152 -- --------------------------------------------------------------------------
153 -- Info tables. Just arrays of words. 
154 -- See codeGen/ClosureInfo, and nativeGen/PprMach
155
156 pprWordArray :: CLabel -> [CmmStatic] -> SDoc
157 pprWordArray lbl ds
158   = hcat [ pprLocalness lbl, ptext SLIT("StgWord")
159          , space, pprCLabel lbl, ptext SLIT("[] = {") ] 
160     $$ nest 8 (commafy (pprStatics ds))
161     $$ ptext SLIT("};")
162
163 --
164 -- has to be static, if it isn't globally visible
165 --
166 pprLocalness :: CLabel -> SDoc
167 pprLocalness lbl | not $ externallyVisibleCLabel lbl = ptext SLIT("static ")
168                  | otherwise = empty
169
170 -- --------------------------------------------------------------------------
171 -- Statements.
172 --
173
174 pprStmt :: CmmStmt -> SDoc
175
176 pprStmt stmt = case stmt of
177     CmmNop       -> empty
178     CmmComment s -> (hang (ptext SLIT("/*")) 3 (ftext s)) $$ ptext SLIT("*/")
179
180     CmmAssign dest src -> pprAssign dest src
181
182     CmmStore  dest src
183         | rep == I64 && wordRep /= I64
184         -> ptext SLIT("ASSIGN_Word64") <> 
185                 parens (mkP_ <> pprExpr1 dest <> comma <> pprExpr src) <> semi
186
187         | otherwise
188         -> hsep [ pprExpr (CmmLoad dest rep), equals, pprExpr src <> semi ]
189         where
190           rep = cmmExprRep src
191
192     CmmCall (CmmForeignCall fn cconv) results args volatile -> 
193         -- Controversial: leave this out for now.
194         -- pprUndef fn $$
195
196         pprCall ppr_fn cconv results args volatile
197         where
198         ppr_fn = case fn of
199                    CmmLit (CmmLabel lbl) -> pprCLabel lbl
200                    _other -> parens (cCast (pprCFunType cconv results args) fn)
201                         -- for a dynamic call, cast the expression to
202                         -- a function of the right type (we hope).
203
204         -- we #undef a function before calling it: the FFI is supposed to be
205         -- an interface specifically to C, not to C+CPP.  For one thing, this
206         -- makes the via-C route more compatible with the NCG.  If macros
207         -- are being used for optimisation, then inline functions are probably
208         -- better anyway.
209         pprUndef (CmmLit (CmmLabel lbl)) = 
210            ptext SLIT("#undef") <+> pprCLabel lbl
211         pprUndef _ = empty
212
213     CmmCall (CmmPrim op) results args volatile -> 
214         pprCall ppr_fn CCallConv results args volatile
215         where
216         ppr_fn = pprCallishMachOp_for_C op
217
218     CmmBranch ident          -> pprBranch ident
219     CmmCondBranch expr ident -> pprCondBranch expr ident
220     CmmJump lbl _params      -> mkJMP_(pprExpr lbl) <> semi
221     CmmSwitch arg ids        -> pprSwitch arg ids
222
223 pprCFunType :: CCallConv -> [(CmmReg,MachHint)] -> [(CmmExpr,MachHint)] -> SDoc
224 pprCFunType cconv ress args
225   = hcat [
226         res_type ress,
227         parens (text (ccallConvAttribute cconv) <>  char '*'),
228         parens (commafy (map arg_type args))
229    ]
230   where
231         res_type [] = ptext SLIT("void")
232         res_type [(one,hint)] = machRepHintCType (cmmRegRep one) hint
233
234         arg_type (expr,hint) = machRepHintCType (cmmExprRep expr) hint
235
236 -- ---------------------------------------------------------------------
237 -- unconditional branches
238 pprBranch :: BlockId -> SDoc
239 pprBranch ident = ptext SLIT("goto") <+> pprBlockId ident <> semi
240
241
242 -- ---------------------------------------------------------------------
243 -- conditional branches to local labels
244 pprCondBranch :: CmmExpr -> BlockId -> SDoc
245 pprCondBranch expr ident 
246         = hsep [ ptext SLIT("if") , parens(pprExpr expr) ,
247                         ptext SLIT("goto") , (pprBlockId ident) <> semi ]
248
249
250 -- ---------------------------------------------------------------------
251 -- a local table branch
252 --
253 -- we find the fall-through cases
254 --
255 -- N.B. we remove Nothing's from the list of branches, as they are
256 -- 'undefined'. However, they may be defined one day, so we better
257 -- document this behaviour.
258 --
259 pprSwitch :: CmmExpr -> [ Maybe BlockId ] -> SDoc
260 pprSwitch e maybe_ids 
261   = let pairs  = [ (ix, ident) | (ix,Just ident) <- zip [0..] maybe_ids ]
262         pairs2 = [ (map fst as, snd (head as)) | as <- groupBy sndEq pairs ]
263     in 
264         (hang (ptext SLIT("switch") <+> parens ( pprExpr e ) <+> lbrace)
265                 4 (vcat ( map caseify pairs2 )))
266         $$ rbrace
267
268   where
269     sndEq (_,x) (_,y) = x == y
270
271     -- fall through case
272     caseify (ix:ixs, ident) = vcat (map do_fallthrough ixs) $$ final_branch ix
273         where 
274         do_fallthrough ix =
275                  hsep [ ptext SLIT("case") , pprHexVal ix wordRep <> colon ,
276                         ptext SLIT("/* fall through */") ]
277
278         final_branch ix = 
279                 hsep [ ptext SLIT("case") , pprHexVal ix wordRep <> colon ,
280                        ptext SLIT("goto") , (pprBlockId ident) <> semi ]
281
282 -- ---------------------------------------------------------------------
283 -- Expressions.
284 --
285
286 -- C Types: the invariant is that the C expression generated by
287 --
288 --      pprExpr e
289 --
290 -- has a type in C which is also given by
291 --
292 --      machRepCType (cmmExprRep e)
293 --
294 -- (similar invariants apply to the rest of the pretty printer).
295
296 pprExpr :: CmmExpr -> SDoc
297 pprExpr e = case e of
298     CmmLit lit -> pprLit lit
299
300     CmmLoad e I64 | wordRep /= I64
301         -> ptext SLIT("PK_Word64") <> parens (mkP_ <> pprExpr1 e)
302
303     CmmLoad (CmmReg r) rep 
304         | isPtrReg r && rep == wordRep
305         -> char '*' <> pprAsPtrReg r
306
307     CmmLoad (CmmRegOff r 0) rep 
308         | isPtrReg r && rep == wordRep
309         -> char '*' <> pprAsPtrReg r
310
311     CmmLoad (CmmRegOff r off) rep
312         | isPtrReg r && rep == wordRep 
313         -- ToDo: check that the offset is a word multiple?
314         -> pprAsPtrReg r <> brackets (ppr (off `shiftR` wordShift))
315
316     CmmLoad expr rep ->
317         -- the general case:
318         char '*' <> parens (cCast (machRepPtrCType rep) expr)
319
320     CmmReg reg      -> pprCastReg reg
321     CmmRegOff reg 0 -> pprCastReg reg
322
323     CmmRegOff reg i
324         | i >  0    -> pprRegOff (char '+') i
325         | otherwise -> pprRegOff (char '-') (-i)
326       where
327         pprRegOff op i' = pprCastReg reg <> op <> int i'
328
329     CmmMachOp mop args -> pprMachOpApp mop args
330
331 pprExpr1 :: CmmExpr -> SDoc
332 pprExpr1 (CmmLit lit)     = pprLit1 lit
333 pprExpr1 e@(CmmReg _reg)  = pprExpr e
334 pprExpr1 other            = parens (pprExpr other)
335
336 -- --------------------------------------------------------------------------
337 -- MachOp applications
338
339 pprMachOpApp :: MachOp -> [CmmExpr] -> SDoc
340
341 pprMachOpApp op args
342   | isMulMayOfloOp op
343   = ptext SLIT("mulIntMayOflo") <> parens (commafy (map pprExpr args))
344   where isMulMayOfloOp (MO_U_MulMayOflo _) = True
345         isMulMayOfloOp (MO_S_MulMayOflo _) = True
346         isMulMayOfloOp _ = False
347
348 pprMachOpApp mop args
349  = case args of
350     -- dyadic
351     [x,y] -> pprArg x <+> pprMachOp_for_C mop <+> pprArg y
352
353     -- unary
354     [x]   -> pprMachOp_for_C mop <> parens (pprArg x)
355
356     _     -> panic "PprC.pprMachOp : machop with wrong number of args"
357
358   where
359     pprArg e | signedOp mop = cCast (machRepSignedCType (cmmExprRep e)) e
360              | otherwise    = pprExpr1 e
361
362 -- --------------------------------------------------------------------------
363 -- Literals
364
365 pprLit :: CmmLit -> SDoc
366 pprLit lit = case lit of
367     CmmInt i rep      -> pprHexVal i rep
368     CmmFloat f rep     -> parens (machRepCType rep) <> (rational f)
369     CmmLabel clbl      -> mkW_ <> pprCLabel clbl
370     CmmLabelOff clbl i -> mkW_ <> pprCLabel clbl <> char '+' <> int i
371     CmmLabelDiffOff clbl1 clbl2 i
372         -- WARNING:
373         --  * the lit must occur in the info table clbl2
374         --  * clbl1 must be an SRT, a slow entry point or a large bitmap
375         -- The Mangler is expected to convert any reference to an SRT,
376         -- a slow entry point or a large bitmap
377         -- from an info table to an offset.
378         -> mkW_ <> pprCLabel clbl1 <> char '+' <> int i
379
380 pprLit1 :: CmmLit -> SDoc
381 pprLit1 lit@(CmmLabelOff _ _) = parens (pprLit lit)
382 pprLit1 lit@(CmmLabelDiffOff _ _ _) = parens (pprLit lit)
383 pprLit1 lit@(CmmFloat _ _)    = parens (pprLit lit)
384 pprLit1 other = pprLit other
385
386 -- ---------------------------------------------------------------------------
387 -- Static data
388
389 pprStatics :: [CmmStatic] -> [SDoc]
390 pprStatics [] = []
391 pprStatics (CmmStaticLit (CmmFloat f F32) : rest) 
392   = pprLit1 (floatToWord f) : pprStatics rest
393 pprStatics (CmmStaticLit (CmmFloat f F64) : rest)
394   = map pprLit1 (doubleToWords f) ++ pprStatics rest
395 pprStatics (CmmStaticLit (CmmInt i I64) : rest)
396   | machRepByteWidth I32 == wORD_SIZE
397 #ifdef WORDS_BIGENDIAN
398   = pprStatics (CmmStaticLit (CmmInt q I32) : 
399                 CmmStaticLit (CmmInt r I32) : rest)
400 #else
401   = pprStatics (CmmStaticLit (CmmInt r I32) : 
402                 CmmStaticLit (CmmInt q I32) : rest)
403 #endif
404   where r = i .&. 0xffffffff
405         q = i `shiftR` 32
406 pprStatics (CmmStaticLit lit : rest)
407   = pprLit1 lit : pprStatics rest
408 pprStatics (other : rest)
409   = pprPanic "pprWord" (pprStatic other)
410
411 pprStatic :: CmmStatic -> SDoc
412 pprStatic s = case s of
413
414     CmmStaticLit lit   -> nest 4 (pprLit lit)
415     CmmAlign i         -> nest 4 (ptext SLIT("/* align */") <+> int i)
416     CmmDataLabel clbl  -> pprCLabel clbl <> colon
417     CmmUninitialised i -> nest 4 (mkC_ <> brackets (int i))
418
419     -- these should be inlined, like the old .hc
420     CmmString s'       -> nest 4 (mkW_ <> parens(pprStringInCStyle s'))
421
422
423 -- ---------------------------------------------------------------------------
424 -- Block Ids
425
426 pprBlockId :: BlockId -> SDoc
427 pprBlockId b = char '_' <> ppr (getUnique b)
428
429 -- --------------------------------------------------------------------------
430 -- Print a MachOp in a way suitable for emitting via C.
431 --
432
433 pprMachOp_for_C :: MachOp -> SDoc
434
435 pprMachOp_for_C mop = case mop of 
436
437         -- Integer operations
438         MO_Add          _ -> char '+'
439         MO_Sub          _ -> char '-'
440         MO_Eq           _ -> ptext SLIT("==")
441         MO_Ne           _ -> ptext SLIT("!=")
442         MO_Mul          _ -> char '*'
443
444         MO_S_Quot       _ -> char '/'
445         MO_S_Rem        _ -> char '%'
446         MO_S_Neg        _ -> char '-'
447
448         MO_U_Quot       _ -> char '/'
449         MO_U_Rem        _ -> char '%'
450
451         -- Signed comparisons (floating-point comparisons also use these)
452         -- & Unsigned comparisons
453         MO_S_Ge         _ -> ptext SLIT(">=")
454         MO_S_Le         _ -> ptext SLIT("<=")
455         MO_S_Gt         _ -> char '>'
456         MO_S_Lt         _ -> char '<'
457
458         MO_U_Ge         _ -> ptext SLIT(">=")
459         MO_U_Le         _ -> ptext SLIT("<=")
460         MO_U_Gt         _ -> char '>'
461         MO_U_Lt         _ -> char '<'
462
463         -- Bitwise operations.  Not all of these may be supported at all
464         -- sizes, and only integral MachReps are valid.
465         MO_And          _ -> char '&'
466         MO_Or           _ -> char '|'
467         MO_Xor          _ -> char '^'
468         MO_Not          _ -> char '~'
469         MO_Shl          _ -> ptext SLIT("<<")
470         MO_U_Shr        _ -> ptext SLIT(">>") -- unsigned shift right
471         MO_S_Shr        _ -> ptext SLIT(">>") -- signed shift right
472
473 -- Conversions.  Some of these will be NOPs.
474 -- Floating-point conversions use the signed variant.
475 -- We won't know to generate (void*) casts here, but maybe from
476 -- context elsewhere
477
478 -- noop casts
479         MO_U_Conv I8 I8     -> empty
480         MO_U_Conv I16 I16   -> empty
481         MO_U_Conv I32 I32   -> empty
482         MO_U_Conv I64 I64   -> empty
483         MO_U_Conv I128 I128 -> empty
484         MO_S_Conv I8 I8     -> empty
485         MO_S_Conv I16 I16   -> empty
486         MO_S_Conv I32 I32   -> empty
487         MO_S_Conv I64 I64   -> empty
488         MO_S_Conv I128 I128 -> empty
489
490         MO_U_Conv _from to  -> parens (machRepCType to)
491         MO_S_Conv _from to  -> parens (machRepSignedCType to)
492
493         _ -> panic "PprC.pprMachOp_for_C: unknown machop"
494
495 signedOp :: MachOp -> Bool
496 signedOp (MO_S_Quot _)   = True
497 signedOp (MO_S_Rem  _)   = True
498 signedOp (MO_S_Neg  _)   = True
499 signedOp (MO_S_Ge   _)   = True
500 signedOp (MO_S_Le   _)   = True
501 signedOp (MO_S_Gt   _)   = True
502 signedOp (MO_S_Lt   _)   = True
503 signedOp (MO_S_Shr  _)   = True
504 signedOp (MO_S_Conv _ _) = True
505 signedOp _ = False
506
507 -- ---------------------------------------------------------------------
508 -- tend to be implemented by foreign calls
509
510 pprCallishMachOp_for_C :: CallishMachOp -> SDoc
511
512 pprCallishMachOp_for_C mop 
513     = case mop of
514         MO_F64_Pwr  -> ptext SLIT("pow")
515         MO_F64_Sin  -> ptext SLIT("sin")
516         MO_F64_Cos  -> ptext SLIT("cos")
517         MO_F64_Tan  -> ptext SLIT("tan")
518         MO_F64_Sinh -> ptext SLIT("sinh")
519         MO_F64_Cosh -> ptext SLIT("cosh")
520         MO_F64_Tanh -> ptext SLIT("tanh")
521         MO_F64_Asin -> ptext SLIT("asin")
522         MO_F64_Acos -> ptext SLIT("acos")
523         MO_F64_Atan -> ptext SLIT("atan")
524         MO_F64_Log  -> ptext SLIT("log")
525         MO_F64_Exp  -> ptext SLIT("exp")
526         MO_F64_Sqrt -> ptext SLIT("sqrt")
527         MO_F32_Pwr  -> ptext SLIT("pow")
528         MO_F32_Sin  -> ptext SLIT("sin")
529         MO_F32_Cos  -> ptext SLIT("cos")
530         MO_F32_Tan  -> ptext SLIT("tan")
531         MO_F32_Sinh -> ptext SLIT("sinh")
532         MO_F32_Cosh -> ptext SLIT("cosh")
533         MO_F32_Tanh -> ptext SLIT("tanh")
534         MO_F32_Asin -> ptext SLIT("asin")
535         MO_F32_Acos -> ptext SLIT("acos")
536         MO_F32_Atan -> ptext SLIT("atan")
537         MO_F32_Log  -> ptext SLIT("log")
538         MO_F32_Exp  -> ptext SLIT("exp")
539         MO_F32_Sqrt -> ptext SLIT("sqrt")
540
541 -- ---------------------------------------------------------------------
542 -- Useful #defines
543 --
544
545 mkJMP_, mkFN_, mkIF_ :: SDoc -> SDoc
546
547 mkJMP_ i = ptext SLIT("JMP_") <> parens i
548 mkFN_  i = ptext SLIT("FN_")  <> parens i -- externally visible function
549 mkIF_  i = ptext SLIT("IF_")  <> parens i -- locally visible
550
551
552 mkFB_, mkFE_ :: SDoc
553 mkFB_ = ptext SLIT("FB_") -- function code begin
554 mkFE_ = ptext SLIT("FE_") -- function code end
555
556 -- from includes/Stg.h
557 --
558 mkC_,mkW_,mkP_,mkPP_,mkI_,mkA_,mkD_,mkF_,mkB_,mkL_,mkLI_,mkLW_ :: SDoc
559
560 mkC_  = ptext SLIT("(C_)")        -- StgChar
561 mkW_  = ptext SLIT("(W_)")        -- StgWord
562 mkP_  = ptext SLIT("(P_)")        -- StgWord*
563 mkPP_ = ptext SLIT("(PP_)")       -- P_*
564 mkI_  = ptext SLIT("(I_)")        -- StgInt
565 mkA_  = ptext SLIT("(A_)")        -- StgAddr
566 mkD_  = ptext SLIT("(D_)")        -- const StgWord*
567 mkF_  = ptext SLIT("(F_)")        -- StgFunPtr
568 mkB_  = ptext SLIT("(B_)")        -- StgByteArray
569 mkL_  = ptext SLIT("(L_)")        -- StgClosurePtr
570
571 mkLI_ = ptext SLIT("(LI_)")       -- StgInt64
572 mkLW_ = ptext SLIT("(LW_)")       -- StgWord64
573
574
575 -- ---------------------------------------------------------------------
576 --
577 -- Assignments
578 --
579 -- Generating assignments is what we're all about, here
580 --
581 pprAssign :: CmmReg -> CmmExpr -> SDoc
582
583 -- dest is a reg, rhs is a reg
584 pprAssign r1 (CmmReg r2)
585    | not (isStrangeTypeReg r1) && not (isStrangeTypeReg r2)
586    || isPtrReg r1 && isPtrReg r2
587    = hcat [ pprAsPtrReg r1, equals, pprAsPtrReg r2, semi ]
588
589 -- dest is a reg, rhs is a CmmRegOff
590 pprAssign r1 (CmmRegOff r2 off)
591    | not (isStrangeTypeReg r1) && not (isStrangeTypeReg r2)
592    || isPtrReg r1 && isPtrReg r2
593    = hcat [ pprAsPtrReg r1, equals, pprAsPtrReg r2, op, int off', semi ]
594   where
595         off1 | isPtrReg r2 = off `shiftR` wordShift
596              | otherwise   = off
597
598         (op,off') | off >= 0  = (char '+', off1)
599                   | otherwise = (char '-', -off1)
600
601 -- dest is a reg, rhs is anything.
602 -- We can't cast the lvalue, so we have to cast the rhs if necessary.  Casting
603 -- the lvalue elicits a warning from new GCC versions (3.4+).
604 pprAssign r1 r2
605   | isPtrReg r1
606   = pprAsPtrReg r1 <> ptext SLIT(" = ") <> mkP_ <> pprExpr1 r2 <> semi
607   | Just ty <- strangeRegType r1
608   = pprReg r1 <> ptext SLIT(" = ") <> parens ty <> pprExpr1 r2 <> semi
609   | otherwise
610   = pprReg r1 <> ptext SLIT(" = ") <> pprExpr r2 <> semi
611
612 -- ---------------------------------------------------------------------
613 -- Registers
614
615 pprCastReg reg
616    | isStrangeTypeReg reg = mkW_ <> pprReg reg
617    | otherwise            = pprReg reg
618
619 -- True if the register has type StgPtr in C, otherwise it has an
620 -- integer type.  We need to take care with pointer arithmetic on registers
621 -- with type StgPtr.
622 isPtrReg :: CmmReg -> Bool
623 isPtrReg (CmmLocal _) = False
624 isPtrReg (CmmGlobal r) = isPtrGlobalReg r
625
626 isPtrGlobalReg :: GlobalReg -> Bool
627 isPtrGlobalReg (VanillaReg n)   = True
628 isPtrGlobalReg Sp               = True
629 isPtrGlobalReg Hp               = True
630 isPtrGlobalReg HpLim            = True
631 isPtrGlobalReg SpLim            = True
632 isPtrGlobalReg _                = False
633
634 -- True if in C this register doesn't have the type given by 
635 -- (machRepCType (cmmRegRep reg)), so it has to be cast.
636 isStrangeTypeReg :: CmmReg -> Bool
637 isStrangeTypeReg (CmmLocal _)   = False
638 isStrangeTypeReg (CmmGlobal g)  = isStrangeTypeGlobal g
639
640 isStrangeTypeGlobal :: GlobalReg -> Bool
641 isStrangeTypeGlobal CurrentTSO          = True
642 isStrangeTypeGlobal CurrentNursery      = True
643 isStrangeTypeGlobal r                   = isPtrGlobalReg r
644
645 strangeRegType :: CmmReg -> Maybe SDoc
646 strangeRegType (CmmGlobal CurrentTSO) = Just (ptext SLIT("struct StgTSO_ *"))
647 strangeRegType (CmmGlobal CurrentNursery) = Just (ptext SLIT("struct bdescr_ *"))
648 strangeRegType _ = Nothing
649
650 -- pprReg just prints the register name.
651 --
652 pprReg :: CmmReg -> SDoc
653 pprReg r = case r of
654         CmmLocal  local  -> pprLocalReg local
655         CmmGlobal global -> pprGlobalReg global
656                 
657 pprAsPtrReg :: CmmReg -> SDoc
658 pprAsPtrReg (CmmGlobal (VanillaReg n)) = char 'R' <> int n <> ptext SLIT(".p")
659 pprAsPtrReg other_reg = pprReg other_reg
660
661 pprGlobalReg :: GlobalReg -> SDoc
662 pprGlobalReg gr = case gr of
663     VanillaReg n   -> char 'R' <> int n  <> ptext SLIT(".w")
664     FloatReg   n   -> char 'F' <> int n
665     DoubleReg  n   -> char 'D' <> int n
666     LongReg    n   -> char 'L' <> int n
667     Sp             -> ptext SLIT("Sp")
668     SpLim          -> ptext SLIT("SpLim")
669     Hp             -> ptext SLIT("Hp")
670     HpLim          -> ptext SLIT("HpLim")
671     CurrentTSO     -> ptext SLIT("CurrentTSO")
672     CurrentNursery -> ptext SLIT("CurrentNursery")
673     HpAlloc        -> ptext SLIT("HpAlloc")
674     BaseReg        -> ptext SLIT("BaseReg")
675     GCEnter1       -> ptext SLIT("stg_gc_enter_1")
676     GCFun          -> ptext SLIT("stg_gc_fun")
677
678 pprLocalReg :: LocalReg -> SDoc
679 pprLocalReg (LocalReg uniq _rep) = char '_' <> ppr uniq
680
681 -- -----------------------------------------------------------------------------
682 -- Foreign Calls
683
684 pprCall :: SDoc -> CCallConv -> [(CmmReg,MachHint)] -> [(CmmExpr,MachHint)]
685         -> Maybe [GlobalReg] -> SDoc
686
687 pprCall ppr_fn cconv results args vols
688   | not (is_cish cconv)
689   = panic "pprForeignCall: unknown calling convention"
690
691   | otherwise
692   = save vols $$
693     ptext SLIT("CALLER_SAVE_SYSTEM") $$
694     hcat [ ppr_results results, ppr_fn, 
695            parens (commafy (map pprArg args)), semi ] $$
696     ptext SLIT("CALLER_RESTORE_SYSTEM") $$
697     restore vols
698   where 
699      ppr_results []     = empty
700      ppr_results [(one,hint)] 
701          = pprExpr (CmmReg one) <> ptext SLIT(" = ")
702                  <> pprUnHint hint (cmmRegRep one)
703      ppr_results _other = panic "pprCall: multiple results"
704
705      pprArg (expr, PtrHint)
706         = cCast (ptext SLIT("void *")) expr
707         -- see comment by machRepHintCType below
708      pprArg (expr, SignedHint)
709         = cCast (machRepSignedCType (cmmExprRep expr)) expr
710      pprArg (expr, _other)
711         = pprExpr expr
712
713      pprUnHint PtrHint    rep = parens (machRepCType rep)
714      pprUnHint SignedHint rep = parens (machRepCType rep)
715      pprUnHint _          _   = empty
716
717      save    = save_restore SLIT("CALLER_SAVE")
718      restore = save_restore SLIT("CALLER_RESTORE")
719
720         -- Nothing says "I don't know what's live; save everything"
721         -- CALLER_SAVE_USER is defined in ghc/includes/Regs.h
722      save_restore txt Nothing     = ptext txt <> ptext SLIT("_USER")
723      save_restore txt (Just these) = vcat (map saveRestoreGlobal these)
724         where saveRestoreGlobal r = ptext txt <> char '_' <> pprGlobalRegName r
725
726 pprGlobalRegName :: GlobalReg -> SDoc
727 pprGlobalRegName gr = case gr of
728     VanillaReg n   -> char 'R' <> int n  -- without the .w suffix
729     _              -> pprGlobalReg gr
730
731 is_cish CCallConv   = True
732 is_cish StdCallConv = True
733 is_cish _           = False
734
735 -- ---------------------------------------------------------------------
736 -- Find and print local and external declarations for a list of
737 -- Cmm statements.
738 -- 
739 pprTempAndExternDecls :: [CmmBasicBlock] -> (SDoc{-temps-}, SDoc{-externs-})
740 pprTempAndExternDecls stmts 
741   = (vcat (map pprTempDecl (eltsUFM temps)), 
742      vcat (map (pprExternDecl False{-ToDo-}) (keysFM lbls)))
743   where (temps, lbls) = runTE (mapM_ te_BB stmts)
744
745 pprDataExterns :: [CmmStatic] -> SDoc
746 pprDataExterns statics
747   = vcat (map (pprExternDecl False{-ToDo-}) (keysFM lbls))
748   where (_, lbls) = runTE (mapM_ te_Static statics)
749
750 pprTempDecl :: LocalReg -> SDoc
751 pprTempDecl l@(LocalReg _uniq rep)
752   = hcat [ machRepCType rep, space, pprLocalReg l, semi ]
753
754 pprExternDecl :: Bool -> CLabel -> SDoc
755 pprExternDecl in_srt lbl
756   -- do not print anything for "known external" things
757   | not (needsCDecl lbl) = empty
758   | otherwise               = 
759         hcat [ visibility, label_type (labelType lbl), 
760                lparen, dyn_wrapper (pprCLabel lbl), text ");" ]
761  where
762   dyn_wrapper d
763     | in_srt && labelDynamic lbl = text "DLL_IMPORT_DATA_VAR" <> parens d
764     | otherwise                  = d
765
766   label_type CodeLabel = ptext SLIT("F_")
767   label_type DataLabel = ptext SLIT("I_")
768
769   visibility
770      | externallyVisibleCLabel lbl = char 'E'
771      | otherwise                   = char 'I'
772
773
774 type TEState = (UniqSet LocalReg, FiniteMap CLabel ())
775 newtype TE a = TE { unTE :: TEState -> (a, TEState) }
776
777 instance Monad TE where
778    TE m >>= k  = TE $ \s -> case m s of (a, s') -> unTE (k a) s'
779    return a    = TE $ \s -> (a, s)
780
781 te_lbl :: CLabel -> TE ()
782 te_lbl lbl = TE $ \(temps,lbls) -> ((), (temps, addToFM lbls lbl ()))
783
784 te_temp :: LocalReg -> TE ()
785 te_temp r = TE $ \(temps,lbls) -> ((), (addOneToUniqSet temps r, lbls))
786
787 runTE :: TE () -> TEState
788 runTE (TE m) = snd (m (emptyUniqSet, emptyFM))
789
790 te_Static :: CmmStatic -> TE ()
791 te_Static (CmmStaticLit lit) = te_Lit lit
792 te_Static _ = return ()
793
794 te_BB :: CmmBasicBlock -> TE ()
795 te_BB (BasicBlock _ ss)         = mapM_ te_Stmt ss
796
797 te_Lit :: CmmLit -> TE ()
798 te_Lit (CmmLabel l) = te_lbl l
799 te_Lit (CmmLabelOff l _) = te_lbl l
800 te_Lit (CmmLabelDiffOff l1 l2 _) = te_lbl l1
801 te_Lit _ = return ()
802
803 te_Stmt :: CmmStmt -> TE ()
804 te_Stmt (CmmAssign r e)         = te_Reg r >> te_Expr e
805 te_Stmt (CmmStore l r)          = te_Expr l >> te_Expr r
806 te_Stmt (CmmCall _ rs es _)     = mapM_ (te_Reg.fst) rs >>
807                                   mapM_ (te_Expr.fst) es
808 te_Stmt (CmmCondBranch e _)     = te_Expr e
809 te_Stmt (CmmSwitch e _)         = te_Expr e
810 te_Stmt (CmmJump e _)           = te_Expr e
811 te_Stmt _                       = return ()
812
813 te_Expr :: CmmExpr -> TE ()
814 te_Expr (CmmLit lit)            = te_Lit lit
815 te_Expr (CmmReg r)              = te_Reg r
816 te_Expr (CmmLoad e _)           = te_Expr e
817 te_Expr (CmmMachOp _ es)        = mapM_ te_Expr es
818 te_Expr (CmmRegOff r _)         = te_Reg r
819 te_Expr _                       = return ()
820
821 te_Reg :: CmmReg -> TE ()
822 te_Reg (CmmLocal l) = te_temp l
823 te_Reg _            = return ()
824
825
826 -- ---------------------------------------------------------------------
827 -- C types for MachReps
828
829 cCast :: SDoc -> CmmExpr -> SDoc
830 cCast ty expr = parens ty <> pprExpr1 expr
831
832 -- This is for finding the types of foreign call arguments.  For a pointer
833 -- argument, we always cast the argument to (void *), to avoid warnings from
834 -- the C compiler.
835 machRepHintCType :: MachRep -> MachHint -> SDoc
836 machRepHintCType rep PtrHint    = ptext SLIT("void *")
837 machRepHintCType rep SignedHint = machRepSignedCType rep
838 machRepHintCType rep _other     = machRepCType rep
839
840 machRepPtrCType :: MachRep -> SDoc
841 machRepPtrCType r | r == wordRep = ptext SLIT("P_")
842                   | otherwise    = machRepCType r <> char '*'
843
844 machRepCType :: MachRep -> SDoc
845 machRepCType r | r == wordRep = ptext SLIT("W_")
846                | otherwise    = sized_type
847   where sized_type = case r of
848                         I8      -> ptext SLIT("StgWord8")
849                         I16     -> ptext SLIT("StgWord16")
850                         I32     -> ptext SLIT("StgWord32")
851                         I64     -> ptext SLIT("StgWord64")
852                         F32     -> ptext SLIT("StgFloat") -- ToDo: correct?
853                         F64     -> ptext SLIT("StgDouble")
854                         _  -> panic "machRepCType"
855
856 machRepSignedCType :: MachRep -> SDoc
857 machRepSignedCType r | r == wordRep = ptext SLIT("I_")
858                      | otherwise    = sized_type
859   where sized_type = case r of
860                         I8      -> ptext SLIT("StgInt8")
861                         I16     -> ptext SLIT("StgInt16")
862                         I32     -> ptext SLIT("StgInt32")
863                         I64     -> ptext SLIT("StgInt64")
864                         F32     -> ptext SLIT("StgFloat") -- ToDo: correct?
865                         F64     -> ptext SLIT("StgDouble")
866                         _ -> panic "machRepCType"
867
868 -- ---------------------------------------------------------------------
869 -- print strings as valid C strings
870
871 -- Assumes it contains only characters '\0'..'\xFF'!
872 pprFSInCStyle :: FastString -> SDoc
873 pprFSInCStyle fs = pprStringInCStyle (unpackFS fs)
874
875 pprStringInCStyle :: String -> SDoc
876 pprStringInCStyle s = doubleQuotes (text (concatMap charToC s))
877
878 charToC :: Char -> String
879 charToC '\"' = "\\\""
880 charToC '\'' = "\\\'"
881 charToC '\\' = "\\\\"
882 charToC c | c >= ' ' && c <= '~' = [c]
883           | c > '\xFF' = panic ("charToC "++show c)
884           | otherwise = ['\\',
885                          chr (ord '0' + ord c `div` 64),
886                          chr (ord '0' + ord c `div` 8 `mod` 8),
887                          chr (ord '0' + ord c         `mod` 8)]
888
889
890 -- ---------------------------------------------------------------------------
891 -- Initialising static objects with floating-point numbers.  We can't
892 -- just emit the floating point number, because C will cast it to an int
893 -- by rounding it.  We want the actual bit-representation of the float.
894
895 -- This is a hack to turn the floating point numbers into ints that we
896 -- can safely initialise to static locations.
897
898 big_doubles 
899   | machRepByteWidth F64 == 2 * wORD_SIZE  = True
900   | machRepByteWidth F64 == wORD_SIZE      = False
901   | otherwise = panic "big_doubles"
902
903 #if __GLASGOW_HASKELL__ >= 504
904 newFloatArray :: (Int,Int) -> ST s (STUArray s Int Float)
905 newFloatArray = newArray_
906
907 newDoubleArray :: (Int,Int) -> ST s (STUArray s Int Double)
908 newDoubleArray = newArray_
909
910 castFloatToIntArray :: STUArray s Int Float -> ST s (STUArray s Int Int)
911 castFloatToIntArray = castSTUArray
912
913 castDoubleToIntArray :: STUArray s Int Double -> ST s (STUArray s Int Int)
914 castDoubleToIntArray = castSTUArray
915
916 writeFloatArray :: STUArray s Int Float -> Int -> Float -> ST s ()
917 writeFloatArray = writeArray
918
919 writeDoubleArray :: STUArray s Int Double -> Int -> Double -> ST s ()
920 writeDoubleArray = writeArray
921
922 readIntArray :: STUArray s Int Int -> Int -> ST s Int
923 readIntArray = readArray
924
925 #else
926
927 castFloatToIntArray :: MutableByteArray s t -> ST s (MutableByteArray s t)
928 castFloatToIntArray = return
929
930 castDoubleToIntArray :: MutableByteArray s t -> ST s (MutableByteArray s t)
931 castDoubleToIntArray = return
932
933 #endif
934
935 -- floats are always 1 word
936 floatToWord :: Rational -> CmmLit
937 floatToWord r
938   = runST (do
939         arr <- newFloatArray ((0::Int),0)
940         writeFloatArray arr 0 (fromRational r)
941         arr' <- castFloatToIntArray arr
942         i <- readIntArray arr' 0
943         return (CmmInt (toInteger i) wordRep)
944     )
945
946 doubleToWords :: Rational -> [CmmLit]
947 doubleToWords r
948   | big_doubles                         -- doubles are 2 words
949   = runST (do
950         arr <- newDoubleArray ((0::Int),1)
951         writeDoubleArray arr 0 (fromRational r)
952         arr' <- castDoubleToIntArray arr
953         i1 <- readIntArray arr' 0
954         i2 <- readIntArray arr' 1
955         return [ CmmInt (toInteger i1) wordRep
956                , CmmInt (toInteger i2) wordRep
957                ]
958     )
959   | otherwise                           -- doubles are 1 word
960   = runST (do
961         arr <- newDoubleArray ((0::Int),0)
962         writeDoubleArray arr 0 (fromRational r)
963         arr' <- castDoubleToIntArray arr
964         i <- readIntArray arr' 0
965         return [ CmmInt (toInteger i) wordRep ]
966     )
967
968 -- ---------------------------------------------------------------------------
969 -- Utils
970
971 wordShift :: Int
972 wordShift = machRepLogWidth wordRep
973
974 commafy :: [SDoc] -> SDoc
975 commafy xs = hsep $ punctuate comma xs
976
977 -- Print in C hex format: 0x13fa
978 pprHexVal :: Integer -> MachRep -> SDoc
979 pprHexVal 0 _ = ptext SLIT("0x0")
980 pprHexVal w rep
981   | w < 0     = parens (char '-' <> ptext SLIT("0x") <> go (-w) <> repsuffix rep)
982   | otherwise = ptext SLIT("0x") <> go w <> repsuffix rep
983   where
984         -- type suffix for literals:
985         -- on 32-bit platforms, add "LL" to 64-bit literals
986       repsuffix I64 | wORD_SIZE == 4 = ptext SLIT("LL")
987         -- on 64-bit platforms with 32-bit int, add "L" to 64-bit literals
988       repsuffix I64 | cINT_SIZE == 4 = ptext SLIT("L")
989       repsuffix _ = empty
990       
991       go 0 = empty
992       go w' = go q <> dig
993            where
994              (q,r) = w' `quotRem` 16
995              dig | r < 10    = char (chr (fromInteger r + ord '0'))
996                  | otherwise = char (chr (fromInteger r - 10 + ord 'a'))
997