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