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