1 -----------------------------------------------------------------------------
3 -- Pretty-printing of Cmm as C, suitable for feeding gcc
5 -- (c) The University of Glasgow 2004
7 -----------------------------------------------------------------------------
10 -- Print Cmm as real C, for -fvia-C
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.
17 -- ToDo: save/restore volatile registers around calls.
24 #include "HsVersions.h"
33 import DynFlags ( DynFlags, DynFlag(..), dopt )
34 import Unique ( getUnique )
37 import UniqFM ( eltsUFM )
43 import Data.List ( intersperse, groupBy )
44 import Data.Bits ( shiftR )
45 import Char ( ord, chr )
48 import Data.Word ( Word8 )
51 import PprCmm () -- instances only
55 #if __GLASGOW_HASKELL__ >= 504
60 -- --------------------------------------------------------------------------
63 pprCs :: DynFlags -> [Cmm] -> SDoc
65 = pprCode CStyle (vcat $ map (\c -> split_marker $$ pprC c) cmms)
68 | dopt Opt_SplitObjs dflags = ptext SLIT("__STG_SPLIT_MARKER")
71 writeCs :: DynFlags -> Handle -> [Cmm] -> IO ()
72 writeCs dflags handle cmms
73 = printForC handle (pprCs dflags cmms)
75 -- --------------------------------------------------------------------------
76 -- Now do some real work
78 -- for fun, we could call cmmToCmm over the tops...
82 pprC (Cmm tops) = vcat $ intersperse (text "") $ map pprTop tops
87 pprTop :: CmmTop -> SDoc
88 pprTop (CmmProc info clbl _params blocks) =
90 then pprDataExterns info $$
91 pprWordArray (entryLblToInfoLbl clbl) info
95 -- the first block doesn't get a label:
96 (BasicBlock _ stmts : rest) -> vcat [
99 (if (externallyVisibleCLabel clbl)
100 then mkFN_ else mkIF_) (pprCLabel clbl) <+> lbrace,
103 nest 8 (vcat (map pprStmt stmts)) $$
104 vcat (map pprBBlock rest),
109 (temp_decls, extern_decls) = pprTempAndExternDecls blocks
112 -- Chunks of static data.
114 -- We only handle (a) arrays of word-sized things and (b) strings.
116 pprTop (CmmData _section _ds@[CmmDataLabel lbl, CmmString str]) =
118 pprLocalness lbl, ptext SLIT("char "), pprCLabel lbl,
119 ptext SLIT("[] = "), pprStringInCStyle str, semi
122 pprTop (CmmData _section _ds@[CmmDataLabel lbl, CmmUninitialised size]) =
124 pprLocalness lbl, ptext SLIT("char "), pprCLabel lbl,
125 brackets (int size), semi
128 pprTop top@(CmmData _section (CmmDataLabel lbl : lits)) =
129 pprDataExterns lits $$
130 pprWordArray lbl lits
132 -- these shouldn't appear?
133 pprTop (CmmData _ _) = panic "PprC.pprTop: can't handle this data"
136 -- --------------------------------------------------------------------------
137 -- BasicBlocks are self-contained entities: they always end in a jump.
139 -- Like nativeGen/AsmCodeGen, we could probably reorder blocks to turn
140 -- as many jumps as possible into fall throughs.
143 pprBBlock :: CmmBasicBlock -> SDoc
144 pprBBlock (BasicBlock lbl stmts) =
146 pprTrace "pprC.pprBBlock: curious empty code block for"
147 (pprBlockId lbl) empty
149 nest 4 (pprBlockId lbl <> colon) $$
150 nest 8 (vcat (map pprStmt stmts))
152 -- --------------------------------------------------------------------------
153 -- Info tables. Just arrays of words.
154 -- See codeGen/ClosureInfo, and nativeGen/PprMach
156 pprWordArray :: CLabel -> [CmmStatic] -> SDoc
158 = hcat [ pprLocalness lbl, ptext SLIT("StgWord")
159 , space, pprCLabel lbl, ptext SLIT("[] = {") ]
160 $$ nest 8 (commafy (pprStatics ds))
164 -- has to be static, if it isn't globally visible
166 pprLocalness :: CLabel -> SDoc
167 pprLocalness lbl | not $ externallyVisibleCLabel lbl = ptext SLIT("static ")
170 -- --------------------------------------------------------------------------
174 pprStmt :: CmmStmt -> SDoc
176 pprStmt stmt = case stmt of
178 CmmComment s -> (hang (ptext SLIT("/*")) 3 (ftext s)) $$ ptext SLIT("*/")
180 CmmAssign dest src -> pprAssign dest src
183 | rep == I64 && wordRep /= I64
184 -> ptext SLIT("ASSIGN_Word64") <>
185 parens (mkP_ <> pprExpr1 dest <> comma <> pprExpr src) <> semi
187 | rep == F64 && wordRep /= I64
188 -> ptext SLIT("ASSIGN_DBL") <>
189 parens (mkP_ <> pprExpr1 dest <> comma <> pprExpr src) <> semi
192 -> hsep [ pprExpr (CmmLoad dest rep), equals, pprExpr src <> semi ]
196 CmmCall (CmmForeignCall fn cconv) results args volatile ->
197 -- Controversial: leave this out for now.
200 pprCall ppr_fn cconv results args volatile
203 CmmLit (CmmLabel lbl) -> pprCLabel lbl
204 _other -> parens (cCast (pprCFunType cconv results args) fn)
205 -- for a dynamic call, cast the expression to
206 -- a function of the right type (we hope).
208 -- we #undef a function before calling it: the FFI is supposed to be
209 -- an interface specifically to C, not to C+CPP. For one thing, this
210 -- makes the via-C route more compatible with the NCG. If macros
211 -- are being used for optimisation, then inline functions are probably
213 pprUndef (CmmLit (CmmLabel lbl)) =
214 ptext SLIT("#undef") <+> pprCLabel lbl
217 CmmCall (CmmPrim op) results args volatile ->
218 pprCall ppr_fn CCallConv results args volatile
220 ppr_fn = pprCallishMachOp_for_C op
222 CmmBranch ident -> pprBranch ident
223 CmmCondBranch expr ident -> pprCondBranch expr ident
224 CmmJump lbl _params -> mkJMP_(pprExpr lbl) <> semi
225 CmmSwitch arg ids -> pprSwitch arg ids
227 pprCFunType :: CCallConv -> [(CmmReg,MachHint)] -> [(CmmExpr,MachHint)] -> SDoc
228 pprCFunType cconv ress args
231 parens (text (ccallConvAttribute cconv) <> char '*'),
232 parens (commafy (map arg_type args))
235 res_type [] = ptext SLIT("void")
236 res_type [(one,hint)] = machRepHintCType (cmmRegRep one) hint
238 arg_type (expr,hint) = machRepHintCType (cmmExprRep expr) hint
240 -- ---------------------------------------------------------------------
241 -- unconditional branches
242 pprBranch :: BlockId -> SDoc
243 pprBranch ident = ptext SLIT("goto") <+> pprBlockId ident <> semi
246 -- ---------------------------------------------------------------------
247 -- conditional branches to local labels
248 pprCondBranch :: CmmExpr -> BlockId -> SDoc
249 pprCondBranch expr ident
250 = hsep [ ptext SLIT("if") , parens(pprExpr expr) ,
251 ptext SLIT("goto") , (pprBlockId ident) <> semi ]
254 -- ---------------------------------------------------------------------
255 -- a local table branch
257 -- we find the fall-through cases
259 -- N.B. we remove Nothing's from the list of branches, as they are
260 -- 'undefined'. However, they may be defined one day, so we better
261 -- document this behaviour.
263 pprSwitch :: CmmExpr -> [ Maybe BlockId ] -> SDoc
264 pprSwitch e maybe_ids
265 = let pairs = [ (ix, ident) | (ix,Just ident) <- zip [0..] maybe_ids ]
266 pairs2 = [ (map fst as, snd (head as)) | as <- groupBy sndEq pairs ]
268 (hang (ptext SLIT("switch") <+> parens ( pprExpr e ) <+> lbrace)
269 4 (vcat ( map caseify pairs2 )))
273 sndEq (_,x) (_,y) = x == y
276 caseify (ix:ixs, ident) = vcat (map do_fallthrough ixs) $$ final_branch ix
279 hsep [ ptext SLIT("case") , pprHexVal ix wordRep <> colon ,
280 ptext SLIT("/* fall through */") ]
283 hsep [ ptext SLIT("case") , pprHexVal ix wordRep <> colon ,
284 ptext SLIT("goto") , (pprBlockId ident) <> semi ]
286 -- ---------------------------------------------------------------------
290 -- C Types: the invariant is that the C expression generated by
294 -- has a type in C which is also given by
296 -- machRepCType (cmmExprRep e)
298 -- (similar invariants apply to the rest of the pretty printer).
300 pprExpr :: CmmExpr -> SDoc
301 pprExpr e = case e of
302 CmmLit lit -> pprLit lit
304 CmmLoad e I64 | wordRep /= I64
305 -> ptext SLIT("PK_Word64") <> parens (mkP_ <> pprExpr1 e)
307 CmmLoad e F64 | wordRep /= I64
308 -> ptext SLIT("PK_DBL") <> parens (mkP_ <> pprExpr1 e)
310 CmmLoad (CmmReg r) rep
311 | isPtrReg r && rep == wordRep
312 -> char '*' <> pprAsPtrReg r
314 CmmLoad (CmmRegOff r 0) rep
315 | isPtrReg r && rep == wordRep
316 -> char '*' <> pprAsPtrReg r
318 CmmLoad (CmmRegOff r off) rep
319 | isPtrReg r && rep == wordRep
320 -- ToDo: check that the offset is a word multiple?
321 -> pprAsPtrReg r <> brackets (ppr (off `shiftR` wordShift))
325 char '*' <> parens (cCast (machRepPtrCType rep) expr)
327 CmmReg reg -> pprCastReg reg
328 CmmRegOff reg 0 -> pprCastReg reg
331 | i > 0 -> pprRegOff (char '+') i
332 | otherwise -> pprRegOff (char '-') (-i)
334 pprRegOff op i' = pprCastReg reg <> op <> int i'
336 CmmMachOp mop args -> pprMachOpApp mop args
338 pprExpr1 :: CmmExpr -> SDoc
339 pprExpr1 (CmmLit lit) = pprLit1 lit
340 pprExpr1 e@(CmmReg _reg) = pprExpr e
341 pprExpr1 other = parens (pprExpr other)
343 -- --------------------------------------------------------------------------
344 -- MachOp applications
346 pprMachOpApp :: MachOp -> [CmmExpr] -> SDoc
350 = ptext SLIT("mulIntMayOflo") <> parens (commafy (map pprExpr args))
351 where isMulMayOfloOp (MO_U_MulMayOflo _) = True
352 isMulMayOfloOp (MO_S_MulMayOflo _) = True
353 isMulMayOfloOp _ = False
355 pprMachOpApp mop args
358 [x,y] -> pprArg x <+> pprMachOp_for_C mop <+> pprArg y
361 [x] -> pprMachOp_for_C mop <> parens (pprArg x)
363 _ -> panic "PprC.pprMachOp : machop with wrong number of args"
366 pprArg e | signedOp mop = cCast (machRepSignedCType (cmmExprRep e)) e
367 | otherwise = pprExpr1 e
369 -- --------------------------------------------------------------------------
372 pprLit :: CmmLit -> SDoc
373 pprLit lit = case lit of
374 CmmInt i rep -> pprHexVal i rep
375 CmmFloat f rep -> parens (machRepCType rep) <> (rational f)
376 CmmLabel clbl -> mkW_ <> pprCLabelAddr clbl
377 CmmLabelOff clbl i -> mkW_ <> pprCLabelAddr clbl <> char '+' <> int i
378 CmmLabelDiffOff clbl1 clbl2 i
380 -- * the lit must occur in the info table clbl2
381 -- * clbl1 must be an SRT, a slow entry point or a large bitmap
382 -- The Mangler is expected to convert any reference to an SRT,
383 -- a slow entry point or a large bitmap
384 -- from an info table to an offset.
385 -> mkW_ <> pprCLabelAddr clbl1 <> char '+' <> int i
387 pprCLabelAddr lbl = char '&' <> pprCLabel lbl
389 pprLit1 :: CmmLit -> SDoc
390 pprLit1 lit@(CmmLabelOff _ _) = parens (pprLit lit)
391 pprLit1 lit@(CmmLabelDiffOff _ _ _) = parens (pprLit lit)
392 pprLit1 lit@(CmmFloat _ _) = parens (pprLit lit)
393 pprLit1 other = pprLit other
395 -- ---------------------------------------------------------------------------
398 pprStatics :: [CmmStatic] -> [SDoc]
400 pprStatics (CmmStaticLit (CmmFloat f F32) : rest)
401 = pprLit1 (floatToWord f) : pprStatics rest
402 pprStatics (CmmStaticLit (CmmFloat f F64) : rest)
403 = map pprLit1 (doubleToWords f) ++ pprStatics rest
404 pprStatics (CmmStaticLit (CmmInt i I64) : rest)
405 | machRepByteWidth I32 == wORD_SIZE
406 #ifdef WORDS_BIGENDIAN
407 = pprStatics (CmmStaticLit (CmmInt q I32) :
408 CmmStaticLit (CmmInt r I32) : rest)
410 = pprStatics (CmmStaticLit (CmmInt r I32) :
411 CmmStaticLit (CmmInt q I32) : rest)
413 where r = i .&. 0xffffffff
415 pprStatics (CmmStaticLit lit : rest)
416 = pprLit1 lit : pprStatics rest
417 pprStatics (other : rest)
418 = pprPanic "pprWord" (pprStatic other)
420 pprStatic :: CmmStatic -> SDoc
421 pprStatic s = case s of
423 CmmStaticLit lit -> nest 4 (pprLit lit)
424 CmmAlign i -> nest 4 (ptext SLIT("/* align */") <+> int i)
425 CmmDataLabel clbl -> pprCLabel clbl <> colon
426 CmmUninitialised i -> nest 4 (mkC_ <> brackets (int i))
428 -- these should be inlined, like the old .hc
429 CmmString s' -> nest 4 (mkW_ <> parens(pprStringInCStyle s'))
432 -- ---------------------------------------------------------------------------
435 pprBlockId :: BlockId -> SDoc
436 pprBlockId b = char '_' <> ppr (getUnique b)
438 -- --------------------------------------------------------------------------
439 -- Print a MachOp in a way suitable for emitting via C.
442 pprMachOp_for_C :: MachOp -> SDoc
444 pprMachOp_for_C mop = case mop of
446 -- Integer operations
449 MO_Eq _ -> ptext SLIT("==")
450 MO_Ne _ -> ptext SLIT("!=")
453 MO_S_Quot _ -> char '/'
454 MO_S_Rem _ -> char '%'
455 MO_S_Neg _ -> char '-'
457 MO_U_Quot _ -> char '/'
458 MO_U_Rem _ -> char '%'
460 -- Signed comparisons (floating-point comparisons also use these)
461 -- & Unsigned comparisons
462 MO_S_Ge _ -> ptext SLIT(">=")
463 MO_S_Le _ -> ptext SLIT("<=")
464 MO_S_Gt _ -> char '>'
465 MO_S_Lt _ -> char '<'
467 MO_U_Ge _ -> ptext SLIT(">=")
468 MO_U_Le _ -> ptext SLIT("<=")
469 MO_U_Gt _ -> char '>'
470 MO_U_Lt _ -> char '<'
472 -- Bitwise operations. Not all of these may be supported at all
473 -- sizes, and only integral MachReps are valid.
478 MO_Shl _ -> ptext SLIT("<<")
479 MO_U_Shr _ -> ptext SLIT(">>") -- unsigned shift right
480 MO_S_Shr _ -> ptext SLIT(">>") -- signed shift right
482 -- Conversions. Some of these will be NOPs.
483 -- Floating-point conversions use the signed variant.
484 -- We won't know to generate (void*) casts here, but maybe from
488 MO_U_Conv I8 I8 -> empty
489 MO_U_Conv I16 I16 -> empty
490 MO_U_Conv I32 I32 -> empty
491 MO_U_Conv I64 I64 -> empty
492 MO_U_Conv I128 I128 -> empty
493 MO_S_Conv I8 I8 -> empty
494 MO_S_Conv I16 I16 -> empty
495 MO_S_Conv I32 I32 -> empty
496 MO_S_Conv I64 I64 -> empty
497 MO_S_Conv I128 I128 -> empty
499 MO_U_Conv _from to -> parens (machRepCType to)
500 MO_S_Conv _from to -> parens (machRepSignedCType to)
502 _ -> panic "PprC.pprMachOp_for_C: unknown machop"
504 signedOp :: MachOp -> Bool
505 signedOp (MO_S_Quot _) = True
506 signedOp (MO_S_Rem _) = True
507 signedOp (MO_S_Neg _) = True
508 signedOp (MO_S_Ge _) = True
509 signedOp (MO_S_Le _) = True
510 signedOp (MO_S_Gt _) = True
511 signedOp (MO_S_Lt _) = True
512 signedOp (MO_S_Shr _) = True
513 signedOp (MO_S_Conv _ _) = True
516 -- ---------------------------------------------------------------------
517 -- tend to be implemented by foreign calls
519 pprCallishMachOp_for_C :: CallishMachOp -> SDoc
521 pprCallishMachOp_for_C mop
523 MO_F64_Pwr -> ptext SLIT("pow")
524 MO_F64_Sin -> ptext SLIT("sin")
525 MO_F64_Cos -> ptext SLIT("cos")
526 MO_F64_Tan -> ptext SLIT("tan")
527 MO_F64_Sinh -> ptext SLIT("sinh")
528 MO_F64_Cosh -> ptext SLIT("cosh")
529 MO_F64_Tanh -> ptext SLIT("tanh")
530 MO_F64_Asin -> ptext SLIT("asin")
531 MO_F64_Acos -> ptext SLIT("acos")
532 MO_F64_Atan -> ptext SLIT("atan")
533 MO_F64_Log -> ptext SLIT("log")
534 MO_F64_Exp -> ptext SLIT("exp")
535 MO_F64_Sqrt -> ptext SLIT("sqrt")
536 MO_F32_Pwr -> ptext SLIT("pow")
537 MO_F32_Sin -> ptext SLIT("sin")
538 MO_F32_Cos -> ptext SLIT("cos")
539 MO_F32_Tan -> ptext SLIT("tan")
540 MO_F32_Sinh -> ptext SLIT("sinh")
541 MO_F32_Cosh -> ptext SLIT("cosh")
542 MO_F32_Tanh -> ptext SLIT("tanh")
543 MO_F32_Asin -> ptext SLIT("asin")
544 MO_F32_Acos -> ptext SLIT("acos")
545 MO_F32_Atan -> ptext SLIT("atan")
546 MO_F32_Log -> ptext SLIT("log")
547 MO_F32_Exp -> ptext SLIT("exp")
548 MO_F32_Sqrt -> ptext SLIT("sqrt")
550 -- ---------------------------------------------------------------------
554 mkJMP_, mkFN_, mkIF_ :: SDoc -> SDoc
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
562 mkFB_ = ptext SLIT("FB_") -- function code begin
563 mkFE_ = ptext SLIT("FE_") -- function code end
565 -- from includes/Stg.h
567 mkC_,mkW_,mkP_,mkPP_,mkI_,mkA_,mkD_,mkF_,mkB_,mkL_,mkLI_,mkLW_ :: SDoc
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
580 mkLI_ = ptext SLIT("(LI_)") -- StgInt64
581 mkLW_ = ptext SLIT("(LW_)") -- StgWord64
584 -- ---------------------------------------------------------------------
588 -- Generating assignments is what we're all about, here
590 pprAssign :: CmmReg -> CmmExpr -> SDoc
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 ]
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 ]
604 off1 | isPtrReg r2 = off `shiftR` wordShift
607 (op,off') | off >= 0 = (char '+', off1)
608 | otherwise = (char '-', -off1)
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+).
615 = pprAsPtrReg r1 <> ptext SLIT(" = ") <> mkP_ <> pprExpr1 r2 <> semi
616 | Just ty <- strangeRegType r1
617 = pprReg r1 <> ptext SLIT(" = ") <> parens ty <> pprExpr1 r2 <> semi
619 = pprReg r1 <> ptext SLIT(" = ") <> pprExpr r2 <> semi
621 -- ---------------------------------------------------------------------
625 | isStrangeTypeReg reg = mkW_ <> pprReg reg
626 | otherwise = pprReg reg
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
631 isPtrReg :: CmmReg -> Bool
632 isPtrReg (CmmLocal _) = False
633 isPtrReg (CmmGlobal r) = isPtrGlobalReg r
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
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
649 isStrangeTypeGlobal :: GlobalReg -> Bool
650 isStrangeTypeGlobal CurrentTSO = True
651 isStrangeTypeGlobal CurrentNursery = True
652 isStrangeTypeGlobal BaseReg = True
653 isStrangeTypeGlobal r = isPtrGlobalReg r
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
661 -- pprReg just prints the register name.
663 pprReg :: CmmReg -> SDoc
665 CmmLocal local -> pprLocalReg local
666 CmmGlobal global -> pprGlobalReg global
668 pprAsPtrReg :: CmmReg -> SDoc
669 pprAsPtrReg (CmmGlobal (VanillaReg n)) = char 'R' <> int n <> ptext SLIT(".p")
670 pprAsPtrReg other_reg = pprReg other_reg
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")
689 pprLocalReg :: LocalReg -> SDoc
690 pprLocalReg (LocalReg uniq _rep) = char '_' <> ppr uniq
692 -- -----------------------------------------------------------------------------
695 pprCall :: SDoc -> CCallConv -> [(CmmReg,MachHint)] -> [(CmmExpr,MachHint)]
696 -> Maybe [GlobalReg] -> SDoc
698 pprCall ppr_fn cconv results args vols
699 | not (is_cish cconv)
700 = panic "pprForeignCall: unknown calling convention"
704 ptext SLIT("CALLER_SAVE_SYSTEM") $$
705 hcat [ ppr_results results, ppr_fn,
706 parens (commafy (map pprArg args)), semi ] $$
707 ptext SLIT("CALLER_RESTORE_SYSTEM") $$
710 ppr_results [] = empty
711 ppr_results [(one,hint)]
712 | Just ty <- strangeRegType one
713 = pprReg one <> ptext SLIT(" = ") <> parens ty
715 = pprReg one <> ptext SLIT(" = ")
716 <> pprUnHint hint (cmmRegRep one)
717 ppr_results _other = panic "pprCall: multiple results"
719 pprArg (expr, PtrHint)
720 = cCast (ptext SLIT("void *")) expr
721 -- see comment by machRepHintCType below
722 pprArg (expr, SignedHint)
723 = cCast (machRepSignedCType (cmmExprRep expr)) expr
724 pprArg (expr, _other)
727 pprUnHint PtrHint rep = parens (machRepCType rep)
728 pprUnHint SignedHint rep = parens (machRepCType rep)
729 pprUnHint _ _ = empty
731 save = save_restore SLIT("CALLER_SAVE")
732 restore = save_restore SLIT("CALLER_RESTORE")
734 -- Nothing says "I don't know what's live; save everything"
735 -- CALLER_SAVE_USER is defined in ghc/includes/Regs.h
736 save_restore txt Nothing = ptext txt <> ptext SLIT("_USER")
737 save_restore txt (Just these) = vcat (map saveRestoreGlobal these)
738 where saveRestoreGlobal r = ptext txt <> char '_' <> pprGlobalRegName r
740 pprGlobalRegName :: GlobalReg -> SDoc
741 pprGlobalRegName gr = case gr of
742 VanillaReg n -> char 'R' <> int n -- without the .w suffix
745 -- Currently we only have these two calling conventions, but this might
746 -- change in the future...
747 is_cish CCallConv = True
748 is_cish StdCallConv = True
750 -- ---------------------------------------------------------------------
751 -- Find and print local and external declarations for a list of
754 pprTempAndExternDecls :: [CmmBasicBlock] -> (SDoc{-temps-}, SDoc{-externs-})
755 pprTempAndExternDecls stmts
756 = (vcat (map pprTempDecl (eltsUFM temps)),
757 vcat (map (pprExternDecl False{-ToDo-}) (keysFM lbls)))
758 where (temps, lbls) = runTE (mapM_ te_BB stmts)
760 pprDataExterns :: [CmmStatic] -> SDoc
761 pprDataExterns statics
762 = vcat (map (pprExternDecl False{-ToDo-}) (keysFM lbls))
763 where (_, lbls) = runTE (mapM_ te_Static statics)
765 pprTempDecl :: LocalReg -> SDoc
766 pprTempDecl l@(LocalReg _uniq rep)
767 = hcat [ machRepCType rep, space, pprLocalReg l, semi ]
769 pprExternDecl :: Bool -> CLabel -> SDoc
770 pprExternDecl in_srt lbl
771 -- do not print anything for "known external" things
772 | not (needsCDecl lbl) = empty
774 hcat [ visibility, label_type (labelType lbl),
775 lparen, dyn_wrapper (pprCLabel lbl), text ");" ]
778 | in_srt && labelDynamic lbl = text "DLL_IMPORT_DATA_VAR" <> parens d
781 label_type CodeLabel = ptext SLIT("F_")
782 label_type DataLabel = ptext SLIT("I_")
785 | externallyVisibleCLabel lbl = char 'E'
786 | otherwise = char 'I'
789 type TEState = (UniqSet LocalReg, FiniteMap CLabel ())
790 newtype TE a = TE { unTE :: TEState -> (a, TEState) }
792 instance Monad TE where
793 TE m >>= k = TE $ \s -> case m s of (a, s') -> unTE (k a) s'
794 return a = TE $ \s -> (a, s)
796 te_lbl :: CLabel -> TE ()
797 te_lbl lbl = TE $ \(temps,lbls) -> ((), (temps, addToFM lbls lbl ()))
799 te_temp :: LocalReg -> TE ()
800 te_temp r = TE $ \(temps,lbls) -> ((), (addOneToUniqSet temps r, lbls))
802 runTE :: TE () -> TEState
803 runTE (TE m) = snd (m (emptyUniqSet, emptyFM))
805 te_Static :: CmmStatic -> TE ()
806 te_Static (CmmStaticLit lit) = te_Lit lit
807 te_Static _ = return ()
809 te_BB :: CmmBasicBlock -> TE ()
810 te_BB (BasicBlock _ ss) = mapM_ te_Stmt ss
812 te_Lit :: CmmLit -> TE ()
813 te_Lit (CmmLabel l) = te_lbl l
814 te_Lit (CmmLabelOff l _) = te_lbl l
815 te_Lit (CmmLabelDiffOff l1 l2 _) = te_lbl l1
818 te_Stmt :: CmmStmt -> TE ()
819 te_Stmt (CmmAssign r e) = te_Reg r >> te_Expr e
820 te_Stmt (CmmStore l r) = te_Expr l >> te_Expr r
821 te_Stmt (CmmCall _ rs es _) = mapM_ (te_Reg.fst) rs >>
822 mapM_ (te_Expr.fst) es
823 te_Stmt (CmmCondBranch e _) = te_Expr e
824 te_Stmt (CmmSwitch e _) = te_Expr e
825 te_Stmt (CmmJump e _) = te_Expr e
826 te_Stmt _ = return ()
828 te_Expr :: CmmExpr -> TE ()
829 te_Expr (CmmLit lit) = te_Lit lit
830 te_Expr (CmmLoad e _) = te_Expr e
831 te_Expr (CmmReg r) = te_Reg r
832 te_Expr (CmmMachOp _ es) = mapM_ te_Expr es
833 te_Expr (CmmRegOff r _) = te_Reg r
835 te_Reg :: CmmReg -> TE ()
836 te_Reg (CmmLocal l) = te_temp l
840 -- ---------------------------------------------------------------------
841 -- C types for MachReps
843 cCast :: SDoc -> CmmExpr -> SDoc
844 cCast ty expr = parens ty <> pprExpr1 expr
846 -- This is for finding the types of foreign call arguments. For a pointer
847 -- argument, we always cast the argument to (void *), to avoid warnings from
849 machRepHintCType :: MachRep -> MachHint -> SDoc
850 machRepHintCType rep PtrHint = ptext SLIT("void *")
851 machRepHintCType rep SignedHint = machRepSignedCType rep
852 machRepHintCType rep _other = machRepCType rep
854 machRepPtrCType :: MachRep -> SDoc
855 machRepPtrCType r | r == wordRep = ptext SLIT("P_")
856 | otherwise = machRepCType r <> char '*'
858 machRepCType :: MachRep -> SDoc
859 machRepCType r | r == wordRep = ptext SLIT("W_")
860 | otherwise = sized_type
861 where sized_type = case r of
862 I8 -> ptext SLIT("StgWord8")
863 I16 -> ptext SLIT("StgWord16")
864 I32 -> ptext SLIT("StgWord32")
865 I64 -> ptext SLIT("StgWord64")
866 F32 -> ptext SLIT("StgFloat") -- ToDo: correct?
867 F64 -> ptext SLIT("StgDouble")
868 _ -> panic "machRepCType"
870 machRepSignedCType :: MachRep -> SDoc
871 machRepSignedCType r | r == wordRep = ptext SLIT("I_")
872 | otherwise = sized_type
873 where sized_type = case r of
874 I8 -> ptext SLIT("StgInt8")
875 I16 -> ptext SLIT("StgInt16")
876 I32 -> ptext SLIT("StgInt32")
877 I64 -> ptext SLIT("StgInt64")
878 F32 -> ptext SLIT("StgFloat") -- ToDo: correct?
879 F64 -> ptext SLIT("StgDouble")
880 _ -> panic "machRepCType"
882 -- ---------------------------------------------------------------------
883 -- print strings as valid C strings
885 pprStringInCStyle :: [Word8] -> SDoc
886 pprStringInCStyle s = doubleQuotes (text (concatMap charToC s))
888 charToC :: Word8 -> String
890 case chr (fromIntegral w) of
894 c | c >= ' ' && c <= '~' -> [c]
895 | otherwise -> ['\\',
896 chr (ord '0' + ord c `div` 64),
897 chr (ord '0' + ord c `div` 8 `mod` 8),
898 chr (ord '0' + ord c `mod` 8)]
900 -- ---------------------------------------------------------------------------
901 -- Initialising static objects with floating-point numbers. We can't
902 -- just emit the floating point number, because C will cast it to an int
903 -- by rounding it. We want the actual bit-representation of the float.
905 -- This is a hack to turn the floating point numbers into ints that we
906 -- can safely initialise to static locations.
909 | machRepByteWidth F64 == 2 * wORD_SIZE = True
910 | machRepByteWidth F64 == wORD_SIZE = False
911 | otherwise = panic "big_doubles"
913 #if __GLASGOW_HASKELL__ >= 504
914 newFloatArray :: (Int,Int) -> ST s (STUArray s Int Float)
915 newFloatArray = newArray_
917 newDoubleArray :: (Int,Int) -> ST s (STUArray s Int Double)
918 newDoubleArray = newArray_
920 castFloatToIntArray :: STUArray s Int Float -> ST s (STUArray s Int Int)
921 castFloatToIntArray = castSTUArray
923 castDoubleToIntArray :: STUArray s Int Double -> ST s (STUArray s Int Int)
924 castDoubleToIntArray = castSTUArray
926 writeFloatArray :: STUArray s Int Float -> Int -> Float -> ST s ()
927 writeFloatArray = writeArray
929 writeDoubleArray :: STUArray s Int Double -> Int -> Double -> ST s ()
930 writeDoubleArray = writeArray
932 readIntArray :: STUArray s Int Int -> Int -> ST s Int
933 readIntArray = readArray
937 castFloatToIntArray :: MutableByteArray s t -> ST s (MutableByteArray s t)
938 castFloatToIntArray = return
940 castDoubleToIntArray :: MutableByteArray s t -> ST s (MutableByteArray s t)
941 castDoubleToIntArray = return
945 -- floats are always 1 word
946 floatToWord :: Rational -> CmmLit
949 arr <- newFloatArray ((0::Int),0)
950 writeFloatArray arr 0 (fromRational r)
951 arr' <- castFloatToIntArray arr
952 i <- readIntArray arr' 0
953 return (CmmInt (toInteger i) wordRep)
956 doubleToWords :: Rational -> [CmmLit]
958 | big_doubles -- doubles are 2 words
960 arr <- newDoubleArray ((0::Int),1)
961 writeDoubleArray arr 0 (fromRational r)
962 arr' <- castDoubleToIntArray arr
963 i1 <- readIntArray arr' 0
964 i2 <- readIntArray arr' 1
965 return [ CmmInt (toInteger i1) wordRep
966 , CmmInt (toInteger i2) wordRep
969 | otherwise -- doubles are 1 word
971 arr <- newDoubleArray ((0::Int),0)
972 writeDoubleArray arr 0 (fromRational r)
973 arr' <- castDoubleToIntArray arr
974 i <- readIntArray arr' 0
975 return [ CmmInt (toInteger i) wordRep ]
978 -- ---------------------------------------------------------------------------
982 wordShift = machRepLogWidth wordRep
984 commafy :: [SDoc] -> SDoc
985 commafy xs = hsep $ punctuate comma xs
987 -- Print in C hex format: 0x13fa
988 pprHexVal :: Integer -> MachRep -> SDoc
989 pprHexVal 0 _ = ptext SLIT("0x0")
991 | w < 0 = parens (char '-' <> ptext SLIT("0x") <> go (-w) <> repsuffix rep)
992 | otherwise = ptext SLIT("0x") <> go w <> repsuffix rep
994 -- type suffix for literals:
995 -- Integer literals are unsigned in Cmm/C. We explicitly cast to
996 -- signed values for doing signed operations, but at all other
997 -- times values are unsigned. This also helps eliminate occasional
998 -- warnings about integer overflow from gcc.
1000 -- on 32-bit platforms, add "ULL" to 64-bit literals
1001 repsuffix I64 | wORD_SIZE == 4 = ptext SLIT("ULL")
1002 -- on 64-bit platforms with 32-bit int, add "L" to 64-bit literals
1003 repsuffix I64 | cINT_SIZE == 4 = ptext SLIT("UL")
1004 repsuffix _ = char 'U'
1009 (q,r) = w' `quotRem` 16
1010 dig | r < 10 = char (chr (fromInteger r + ord '0'))
1011 | otherwise = char (chr (fromInteger r - 10 + ord 'a'))