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