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