1 -----------------------------------------------------------------------------
3 -- Pretty-printing of Cmm as C, suitable for feeding gcc
5 -- (c) The University of Glasgow 2004-2006
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"
50 import PprCmm () -- instances only
54 #if __GLASGOW_HASKELL__ >= 504
57 import Control.Monad.ST
59 #if x86_64_TARGET_ARCH
60 import StaticFlags ( opt_Unregisterised )
63 #if defined(alpha_TARGET_ARCH) || defined(mips_TARGET_ARCH) || defined(mipsel_TARGET_ARCH) || defined(arm_TARGET_ARCH)
64 #define BEWARE_LOAD_STORE_ALIGNMENT
67 -- --------------------------------------------------------------------------
70 pprCs :: DynFlags -> [Cmm] -> SDoc
72 = pprCode CStyle (vcat $ map (\c -> split_marker $$ pprC c) cmms)
75 | dopt Opt_SplitObjs dflags = ptext SLIT("__STG_SPLIT_MARKER")
78 writeCs :: DynFlags -> Handle -> [Cmm] -> IO ()
79 writeCs dflags handle cmms
80 = printForC handle (pprCs dflags cmms)
82 -- --------------------------------------------------------------------------
83 -- Now do some real work
85 -- for fun, we could call cmmToCmm over the tops...
89 pprC (Cmm tops) = vcat $ intersperse (text "") $ map pprTop tops
94 pprTop :: CmmTop -> SDoc
95 pprTop (CmmProc info clbl _params blocks) =
97 then pprDataExterns info $$
98 pprWordArray (entryLblToInfoLbl clbl) info
102 -- the first block doesn't get a label:
103 (BasicBlock _ stmts : rest) -> vcat [
106 (if (externallyVisibleCLabel clbl)
107 then mkFN_ else mkIF_) (pprCLabel clbl) <+> lbrace,
110 nest 8 (vcat (map pprStmt stmts)) $$
111 vcat (map pprBBlock rest),
116 (temp_decls, extern_decls) = pprTempAndExternDecls blocks
119 -- Chunks of static data.
121 -- We only handle (a) arrays of word-sized things and (b) strings.
123 pprTop (CmmData _section _ds@[CmmDataLabel lbl, CmmString str]) =
125 pprLocalness lbl, ptext SLIT("char "), pprCLabel lbl,
126 ptext SLIT("[] = "), pprStringInCStyle str, semi
129 pprTop (CmmData _section _ds@[CmmDataLabel lbl, CmmUninitialised size]) =
131 pprLocalness lbl, ptext SLIT("char "), pprCLabel lbl,
132 brackets (int size), semi
135 pprTop top@(CmmData _section (CmmDataLabel lbl : lits)) =
136 pprDataExterns lits $$
137 pprWordArray lbl lits
139 -- these shouldn't appear?
140 pprTop (CmmData _ _) = panic "PprC.pprTop: can't handle this data"
143 -- --------------------------------------------------------------------------
144 -- BasicBlocks are self-contained entities: they always end in a jump.
146 -- Like nativeGen/AsmCodeGen, we could probably reorder blocks to turn
147 -- as many jumps as possible into fall throughs.
150 pprBBlock :: CmmBasicBlock -> SDoc
151 pprBBlock (BasicBlock lbl stmts) =
153 pprTrace "pprC.pprBBlock: curious empty code block for"
154 (pprBlockId lbl) empty
156 nest 4 (pprBlockId lbl <> colon) $$
157 nest 8 (vcat (map pprStmt stmts))
159 -- --------------------------------------------------------------------------
160 -- Info tables. Just arrays of words.
161 -- See codeGen/ClosureInfo, and nativeGen/PprMach
163 pprWordArray :: CLabel -> [CmmStatic] -> SDoc
165 = hcat [ pprLocalness lbl, ptext SLIT("StgWord")
166 , space, pprCLabel lbl, ptext SLIT("[] = {") ]
167 $$ nest 8 (commafy (pprStatics ds))
171 -- has to be static, if it isn't globally visible
173 pprLocalness :: CLabel -> SDoc
174 pprLocalness lbl | not $ externallyVisibleCLabel lbl = ptext SLIT("static ")
177 -- --------------------------------------------------------------------------
181 pprStmt :: CmmStmt -> SDoc
183 pprStmt stmt = case stmt of
185 CmmComment s -> (hang (ptext SLIT("/*")) 3 (ftext s)) $$ ptext SLIT("*/")
187 CmmAssign dest src -> pprAssign dest src
190 | rep == I64 && wordRep /= I64
191 -> ptext SLIT("ASSIGN_Word64") <>
192 parens (mkP_ <> pprExpr1 dest <> comma <> pprExpr src) <> semi
194 | rep == F64 && wordRep /= I64
195 -> ptext SLIT("ASSIGN_DBL") <>
196 parens (mkP_ <> pprExpr1 dest <> comma <> pprExpr src) <> semi
199 -> hsep [ pprExpr (CmmLoad dest rep), equals, pprExpr src <> semi ]
203 CmmCall (CmmForeignCall fn cconv) results args volatile ->
204 -- Controversial: leave this out for now.
207 pprCall ppr_fn cconv results args volatile
210 CmmLit (CmmLabel lbl) -> pprCLabel lbl
211 _other -> parens (cCast (pprCFunType cconv results args) fn)
212 -- for a dynamic call, cast the expression to
213 -- a function of the right type (we hope).
215 -- we #undef a function before calling it: the FFI is supposed to be
216 -- an interface specifically to C, not to C+CPP. For one thing, this
217 -- makes the via-C route more compatible with the NCG. If macros
218 -- are being used for optimisation, then inline functions are probably
220 pprUndef (CmmLit (CmmLabel lbl)) =
221 ptext SLIT("#undef") <+> pprCLabel lbl
224 CmmCall (CmmPrim op) results args volatile ->
225 pprCall ppr_fn CCallConv results args volatile
227 ppr_fn = pprCallishMachOp_for_C op
229 CmmBranch ident -> pprBranch ident
230 CmmCondBranch expr ident -> pprCondBranch expr ident
231 CmmJump lbl _params -> mkJMP_(pprExpr lbl) <> semi
232 CmmSwitch arg ids -> pprSwitch arg ids
234 pprCFunType :: CCallConv -> [(CmmReg,MachHint)] -> [(CmmExpr,MachHint)] -> SDoc
235 pprCFunType cconv ress args
238 parens (text (ccallConvAttribute cconv) <> char '*'),
239 parens (commafy (map arg_type args))
242 res_type [] = ptext SLIT("void")
243 res_type [(one,hint)] = machRepHintCType (cmmRegRep one) hint
245 arg_type (expr,hint) = machRepHintCType (cmmExprRep expr) hint
247 -- ---------------------------------------------------------------------
248 -- unconditional branches
249 pprBranch :: BlockId -> SDoc
250 pprBranch ident = ptext SLIT("goto") <+> pprBlockId ident <> semi
253 -- ---------------------------------------------------------------------
254 -- conditional branches to local labels
255 pprCondBranch :: CmmExpr -> BlockId -> SDoc
256 pprCondBranch expr ident
257 = hsep [ ptext SLIT("if") , parens(pprExpr expr) ,
258 ptext SLIT("goto") , (pprBlockId ident) <> semi ]
261 -- ---------------------------------------------------------------------
262 -- a local table branch
264 -- we find the fall-through cases
266 -- N.B. we remove Nothing's from the list of branches, as they are
267 -- 'undefined'. However, they may be defined one day, so we better
268 -- document this behaviour.
270 pprSwitch :: CmmExpr -> [ Maybe BlockId ] -> SDoc
271 pprSwitch e maybe_ids
272 = let pairs = [ (ix, ident) | (ix,Just ident) <- zip [0..] maybe_ids ]
273 pairs2 = [ (map fst as, snd (head as)) | as <- groupBy sndEq pairs ]
275 (hang (ptext SLIT("switch") <+> parens ( pprExpr e ) <+> lbrace)
276 4 (vcat ( map caseify pairs2 )))
280 sndEq (_,x) (_,y) = x == y
283 caseify (ix:ixs, ident) = vcat (map do_fallthrough ixs) $$ final_branch ix
286 hsep [ ptext SLIT("case") , pprHexVal ix wordRep <> colon ,
287 ptext SLIT("/* fall through */") ]
290 hsep [ ptext SLIT("case") , pprHexVal ix wordRep <> colon ,
291 ptext SLIT("goto") , (pprBlockId ident) <> semi ]
293 -- ---------------------------------------------------------------------
297 -- C Types: the invariant is that the C expression generated by
301 -- has a type in C which is also given by
303 -- machRepCType (cmmExprRep e)
305 -- (similar invariants apply to the rest of the pretty printer).
307 pprExpr :: CmmExpr -> SDoc
308 pprExpr e = case e of
309 CmmLit lit -> pprLit lit
311 CmmLoad e I64 | wordRep /= I64
312 -> ptext SLIT("PK_Word64") <> parens (mkP_ <> pprExpr1 e)
314 CmmLoad e F64 | wordRep /= I64
315 -> ptext SLIT("PK_DBL") <> parens (mkP_ <> pprExpr1 e)
317 CmmLoad (CmmReg r) rep
318 | isPtrReg r && rep == wordRep
319 -> char '*' <> pprAsPtrReg r
321 CmmLoad (CmmRegOff r 0) rep
322 | isPtrReg r && rep == wordRep
323 -> char '*' <> pprAsPtrReg r
325 CmmLoad (CmmRegOff r off) rep
326 | isPtrReg r && rep == wordRep
327 -- ToDo: check that the offset is a word multiple?
328 -> pprAsPtrReg r <> brackets (ppr (off `shiftR` wordShift))
334 CmmReg reg -> pprCastReg reg
335 CmmRegOff reg 0 -> pprCastReg reg
338 | i > 0 -> pprRegOff (char '+') i
339 | otherwise -> pprRegOff (char '-') (-i)
341 pprRegOff op i' = pprCastReg reg <> op <> int i'
343 CmmMachOp mop args -> pprMachOpApp mop args
345 pprExpr1 :: CmmExpr -> SDoc
346 pprExpr1 (CmmLit lit) = pprLit1 lit
347 pprExpr1 e@(CmmReg _reg) = pprExpr e
348 pprExpr1 other = parens (pprExpr other)
350 -- --------------------------------------------------------------------------
351 -- MachOp applications
353 pprMachOpApp :: MachOp -> [CmmExpr] -> SDoc
357 = ptext SLIT("mulIntMayOflo") <> parens (commafy (map pprExpr args))
358 where isMulMayOfloOp (MO_U_MulMayOflo _) = True
359 isMulMayOfloOp (MO_S_MulMayOflo _) = True
360 isMulMayOfloOp _ = False
362 pprMachOpApp mop args
363 | Just ty <- machOpNeedsCast mop
364 = ty <> parens (pprMachOpApp' mop args)
366 = pprMachOpApp' mop args
368 -- Comparisons in C have type 'int', but we want type W_ (this is what
369 -- resultRepOfMachOp says). The other C operations inherit their type
370 -- from their operands, so no casting is required.
371 machOpNeedsCast :: MachOp -> Maybe SDoc
373 | isComparisonMachOp mop = Just mkW_
374 | otherwise = Nothing
376 pprMachOpApp' mop args
379 [x,y] -> pprArg x <+> pprMachOp_for_C mop <+> pprArg y
382 [x] -> pprMachOp_for_C mop <> parens (pprArg x)
384 _ -> panic "PprC.pprMachOp : machop with wrong number of args"
387 pprArg e | signedOp mop = cCast (machRepSignedCType (cmmExprRep e)) e
388 | otherwise = pprExpr1 e
390 -- --------------------------------------------------------------------------
393 pprLit :: CmmLit -> SDoc
394 pprLit lit = case lit of
395 CmmInt i rep -> pprHexVal i rep
396 CmmFloat f rep -> parens (machRepCType rep) <> (rational f)
397 CmmLabel clbl -> mkW_ <> pprCLabelAddr clbl
398 CmmLabelOff clbl i -> mkW_ <> pprCLabelAddr clbl <> char '+' <> int i
399 CmmLabelDiffOff clbl1 clbl2 i
401 -- * the lit must occur in the info table clbl2
402 -- * clbl1 must be an SRT, a slow entry point or a large bitmap
403 -- The Mangler is expected to convert any reference to an SRT,
404 -- a slow entry point or a large bitmap
405 -- from an info table to an offset.
406 -> mkW_ <> pprCLabelAddr clbl1 <> char '+' <> int i
408 pprCLabelAddr lbl = char '&' <> pprCLabel lbl
410 pprLit1 :: CmmLit -> SDoc
411 pprLit1 lit@(CmmLabelOff _ _) = parens (pprLit lit)
412 pprLit1 lit@(CmmLabelDiffOff _ _ _) = parens (pprLit lit)
413 pprLit1 lit@(CmmFloat _ _) = parens (pprLit lit)
414 pprLit1 other = pprLit other
416 -- ---------------------------------------------------------------------------
419 pprStatics :: [CmmStatic] -> [SDoc]
421 pprStatics (CmmStaticLit (CmmFloat f F32) : rest)
422 = pprLit1 (floatToWord f) : pprStatics rest
423 pprStatics (CmmStaticLit (CmmFloat f F64) : rest)
424 = map pprLit1 (doubleToWords f) ++ pprStatics rest
425 pprStatics (CmmStaticLit (CmmInt i I64) : rest)
426 | machRepByteWidth I32 == wORD_SIZE
427 #ifdef WORDS_BIGENDIAN
428 = pprStatics (CmmStaticLit (CmmInt q I32) :
429 CmmStaticLit (CmmInt r I32) : rest)
431 = pprStatics (CmmStaticLit (CmmInt r I32) :
432 CmmStaticLit (CmmInt q I32) : rest)
434 where r = i .&. 0xffffffff
436 pprStatics (CmmStaticLit lit : rest)
437 = pprLit1 lit : pprStatics rest
438 pprStatics (other : rest)
439 = pprPanic "pprWord" (pprStatic other)
441 pprStatic :: CmmStatic -> SDoc
442 pprStatic s = case s of
444 CmmStaticLit lit -> nest 4 (pprLit lit)
445 CmmAlign i -> nest 4 (ptext SLIT("/* align */") <+> int i)
446 CmmDataLabel clbl -> pprCLabel clbl <> colon
447 CmmUninitialised i -> nest 4 (mkC_ <> brackets (int i))
449 -- these should be inlined, like the old .hc
450 CmmString s' -> nest 4 (mkW_ <> parens(pprStringInCStyle s'))
453 -- ---------------------------------------------------------------------------
456 pprBlockId :: BlockId -> SDoc
457 pprBlockId b = char '_' <> ppr (getUnique b)
459 -- --------------------------------------------------------------------------
460 -- Print a MachOp in a way suitable for emitting via C.
463 pprMachOp_for_C :: MachOp -> SDoc
465 pprMachOp_for_C mop = case mop of
467 -- Integer operations
470 MO_Eq _ -> ptext SLIT("==")
471 MO_Ne _ -> ptext SLIT("!=")
474 MO_S_Quot _ -> char '/'
475 MO_S_Rem _ -> char '%'
476 MO_S_Neg _ -> char '-'
478 MO_U_Quot _ -> char '/'
479 MO_U_Rem _ -> char '%'
481 -- Signed comparisons (floating-point comparisons also use these)
482 -- & Unsigned comparisons
483 MO_S_Ge _ -> ptext SLIT(">=")
484 MO_S_Le _ -> ptext SLIT("<=")
485 MO_S_Gt _ -> char '>'
486 MO_S_Lt _ -> char '<'
488 MO_U_Ge _ -> ptext SLIT(">=")
489 MO_U_Le _ -> ptext SLIT("<=")
490 MO_U_Gt _ -> char '>'
491 MO_U_Lt _ -> char '<'
493 -- Bitwise operations. Not all of these may be supported at all
494 -- sizes, and only integral MachReps are valid.
499 MO_Shl _ -> ptext SLIT("<<")
500 MO_U_Shr _ -> ptext SLIT(">>") -- unsigned shift right
501 MO_S_Shr _ -> ptext SLIT(">>") -- signed shift right
503 -- Conversions. Some of these will be NOPs.
504 -- Floating-point conversions use the signed variant.
505 -- We won't know to generate (void*) casts here, but maybe from
509 MO_U_Conv I8 I8 -> empty
510 MO_U_Conv I16 I16 -> empty
511 MO_U_Conv I32 I32 -> empty
512 MO_U_Conv I64 I64 -> empty
513 MO_U_Conv I128 I128 -> empty
514 MO_S_Conv I8 I8 -> empty
515 MO_S_Conv I16 I16 -> empty
516 MO_S_Conv I32 I32 -> empty
517 MO_S_Conv I64 I64 -> empty
518 MO_S_Conv I128 I128 -> empty
520 MO_U_Conv _from to -> parens (machRepCType to)
521 MO_S_Conv _from to -> parens (machRepSignedCType to)
523 _ -> panic "PprC.pprMachOp_for_C: unknown machop"
525 signedOp :: MachOp -> Bool
526 signedOp (MO_S_Quot _) = True
527 signedOp (MO_S_Rem _) = True
528 signedOp (MO_S_Neg _) = True
529 signedOp (MO_S_Ge _) = True
530 signedOp (MO_S_Le _) = True
531 signedOp (MO_S_Gt _) = True
532 signedOp (MO_S_Lt _) = True
533 signedOp (MO_S_Shr _) = True
534 signedOp (MO_S_Conv _ _) = True
537 -- ---------------------------------------------------------------------
538 -- tend to be implemented by foreign calls
540 pprCallishMachOp_for_C :: CallishMachOp -> SDoc
542 pprCallishMachOp_for_C mop
544 MO_F64_Pwr -> ptext SLIT("pow")
545 MO_F64_Sin -> ptext SLIT("sin")
546 MO_F64_Cos -> ptext SLIT("cos")
547 MO_F64_Tan -> ptext SLIT("tan")
548 MO_F64_Sinh -> ptext SLIT("sinh")
549 MO_F64_Cosh -> ptext SLIT("cosh")
550 MO_F64_Tanh -> ptext SLIT("tanh")
551 MO_F64_Asin -> ptext SLIT("asin")
552 MO_F64_Acos -> ptext SLIT("acos")
553 MO_F64_Atan -> ptext SLIT("atan")
554 MO_F64_Log -> ptext SLIT("log")
555 MO_F64_Exp -> ptext SLIT("exp")
556 MO_F64_Sqrt -> ptext SLIT("sqrt")
557 MO_F32_Pwr -> ptext SLIT("powf")
558 MO_F32_Sin -> ptext SLIT("sinf")
559 MO_F32_Cos -> ptext SLIT("cosf")
560 MO_F32_Tan -> ptext SLIT("tanf")
561 MO_F32_Sinh -> ptext SLIT("sinhf")
562 MO_F32_Cosh -> ptext SLIT("coshf")
563 MO_F32_Tanh -> ptext SLIT("tanhf")
564 MO_F32_Asin -> ptext SLIT("asinf")
565 MO_F32_Acos -> ptext SLIT("acosf")
566 MO_F32_Atan -> ptext SLIT("atanf")
567 MO_F32_Log -> ptext SLIT("logf")
568 MO_F32_Exp -> ptext SLIT("expf")
569 MO_F32_Sqrt -> ptext SLIT("sqrtf")
570 MO_WriteBarrier -> ptext SLIT("write_barrier")
572 -- ---------------------------------------------------------------------
576 mkJMP_, mkFN_, mkIF_ :: SDoc -> SDoc
578 mkJMP_ i = ptext SLIT("JMP_") <> parens i
579 mkFN_ i = ptext SLIT("FN_") <> parens i -- externally visible function
580 mkIF_ i = ptext SLIT("IF_") <> parens i -- locally visible
584 mkFB_ = ptext SLIT("FB_") -- function code begin
585 mkFE_ = ptext SLIT("FE_") -- function code end
587 -- from includes/Stg.h
589 mkC_,mkW_,mkP_,mkPP_,mkI_,mkA_,mkD_,mkF_,mkB_,mkL_,mkLI_,mkLW_ :: SDoc
591 mkC_ = ptext SLIT("(C_)") -- StgChar
592 mkW_ = ptext SLIT("(W_)") -- StgWord
593 mkP_ = ptext SLIT("(P_)") -- StgWord*
594 mkPP_ = ptext SLIT("(PP_)") -- P_*
595 mkI_ = ptext SLIT("(I_)") -- StgInt
596 mkA_ = ptext SLIT("(A_)") -- StgAddr
597 mkD_ = ptext SLIT("(D_)") -- const StgWord*
598 mkF_ = ptext SLIT("(F_)") -- StgFunPtr
599 mkB_ = ptext SLIT("(B_)") -- StgByteArray
600 mkL_ = ptext SLIT("(L_)") -- StgClosurePtr
602 mkLI_ = ptext SLIT("(LI_)") -- StgInt64
603 mkLW_ = ptext SLIT("(LW_)") -- StgWord64
606 -- ---------------------------------------------------------------------
610 -- Generating assignments is what we're all about, here
612 pprAssign :: CmmReg -> CmmExpr -> SDoc
614 -- dest is a reg, rhs is a reg
615 pprAssign r1 (CmmReg r2)
616 | isPtrReg r1 && isPtrReg r2
617 = hcat [ pprAsPtrReg r1, equals, pprAsPtrReg r2, semi ]
619 -- dest is a reg, rhs is a CmmRegOff
620 pprAssign r1 (CmmRegOff r2 off)
621 | isPtrReg r1 && isPtrReg r2 && (off `rem` wORD_SIZE == 0)
622 = hcat [ pprAsPtrReg r1, equals, pprAsPtrReg r2, op, int off', semi ]
624 off1 = off `shiftR` wordShift
626 (op,off') | off >= 0 = (char '+', off1)
627 | otherwise = (char '-', -off1)
629 -- dest is a reg, rhs is anything.
630 -- We can't cast the lvalue, so we have to cast the rhs if necessary. Casting
631 -- the lvalue elicits a warning from new GCC versions (3.4+).
634 = pprReg r1 <> ptext SLIT(" = ") <> mkP_ <> pprExpr1 r2 <> semi
635 | Just ty <- strangeRegType r1
636 = pprReg r1 <> ptext SLIT(" = ") <> parens ty <> pprExpr1 r2 <> semi
638 = pprReg r1 <> ptext SLIT(" = ") <> pprExpr r2 <> semi
640 -- ---------------------------------------------------------------------
644 | isStrangeTypeReg reg = mkW_ <> pprReg reg
645 | otherwise = pprReg reg
647 -- True if (pprReg reg) will give an expression with type StgPtr. We
648 -- need to take care with pointer arithmetic on registers with type
650 isFixedPtrReg :: CmmReg -> Bool
651 isFixedPtrReg (CmmLocal _) = False
652 isFixedPtrReg (CmmGlobal r) = isFixedPtrGlobalReg r
654 -- True if (pprAsPtrReg reg) will give an expression with type StgPtr
655 isPtrReg :: CmmReg -> Bool
656 isPtrReg (CmmLocal _) = False
657 isPtrReg (CmmGlobal (VanillaReg n)) = True -- if we print via pprAsPtrReg
658 isPtrReg (CmmGlobal reg) = isFixedPtrGlobalReg reg
660 -- True if this global reg has type StgPtr
661 isFixedPtrGlobalReg :: GlobalReg -> Bool
662 isFixedPtrGlobalReg Sp = True
663 isFixedPtrGlobalReg Hp = True
664 isFixedPtrGlobalReg HpLim = True
665 isFixedPtrGlobalReg SpLim = True
666 isFixedPtrGlobalReg _ = False
668 -- True if in C this register doesn't have the type given by
669 -- (machRepCType (cmmRegRep reg)), so it has to be cast.
670 isStrangeTypeReg :: CmmReg -> Bool
671 isStrangeTypeReg (CmmLocal _) = False
672 isStrangeTypeReg (CmmGlobal g) = isStrangeTypeGlobal g
674 isStrangeTypeGlobal :: GlobalReg -> Bool
675 isStrangeTypeGlobal CurrentTSO = True
676 isStrangeTypeGlobal CurrentNursery = True
677 isStrangeTypeGlobal BaseReg = True
678 isStrangeTypeGlobal r = isFixedPtrGlobalReg r
680 strangeRegType :: CmmReg -> Maybe SDoc
681 strangeRegType (CmmGlobal CurrentTSO) = Just (ptext SLIT("struct StgTSO_ *"))
682 strangeRegType (CmmGlobal CurrentNursery) = Just (ptext SLIT("struct bdescr_ *"))
683 strangeRegType (CmmGlobal BaseReg) = Just (ptext SLIT("struct StgRegTable_ *"))
684 strangeRegType _ = Nothing
686 -- pprReg just prints the register name.
688 pprReg :: CmmReg -> SDoc
690 CmmLocal local -> pprLocalReg local
691 CmmGlobal global -> pprGlobalReg global
693 pprAsPtrReg :: CmmReg -> SDoc
694 pprAsPtrReg (CmmGlobal (VanillaReg n)) = char 'R' <> int n <> ptext SLIT(".p")
695 pprAsPtrReg other_reg = pprReg other_reg
697 pprGlobalReg :: GlobalReg -> SDoc
698 pprGlobalReg gr = case gr of
699 VanillaReg n -> char 'R' <> int n <> ptext SLIT(".w")
700 FloatReg n -> char 'F' <> int n
701 DoubleReg n -> char 'D' <> int n
702 LongReg n -> char 'L' <> int n
703 Sp -> ptext SLIT("Sp")
704 SpLim -> ptext SLIT("SpLim")
705 Hp -> ptext SLIT("Hp")
706 HpLim -> ptext SLIT("HpLim")
707 CurrentTSO -> ptext SLIT("CurrentTSO")
708 CurrentNursery -> ptext SLIT("CurrentNursery")
709 HpAlloc -> ptext SLIT("HpAlloc")
710 BaseReg -> ptext SLIT("BaseReg")
711 GCEnter1 -> ptext SLIT("stg_gc_enter_1")
712 GCFun -> ptext SLIT("stg_gc_fun")
714 pprLocalReg :: LocalReg -> SDoc
715 pprLocalReg (LocalReg uniq _rep) = char '_' <> ppr uniq
717 -- -----------------------------------------------------------------------------
720 pprCall :: SDoc -> CCallConv -> [(CmmReg,MachHint)] -> [(CmmExpr,MachHint)]
721 -> Maybe [GlobalReg] -> SDoc
723 pprCall ppr_fn cconv results args vols
724 | not (is_cish cconv)
725 = panic "pprCall: unknown calling convention"
729 ptext SLIT("CALLER_SAVE_SYSTEM") $$
730 #if x86_64_TARGET_ARCH
731 -- HACK around gcc optimisations.
732 -- x86_64 needs a __DISCARD__() here, to create a barrier between
733 -- putting the arguments into temporaries and passing the arguments
734 -- to the callee, because the argument expressions may refer to
735 -- machine registers that are also used for passing arguments in the
736 -- C calling convention.
737 (if (not opt_Unregisterised)
738 then ptext SLIT("__DISCARD__();")
741 ppr_assign results (ppr_fn <> parens (commafy (map pprArg args))) <> semi $$
742 ptext SLIT("CALLER_RESTORE_SYSTEM") $$
745 ppr_assign [] rhs = rhs
746 ppr_assign [(reg@(CmmGlobal BaseReg), hint)] rhs
747 | Just ty <- strangeRegType reg
748 = ptext SLIT("ASSIGN_BaseReg") <> parens (parens ty <> rhs)
749 -- BaseReg is special, sometimes it isn't an lvalue and we
750 -- can't assign to it.
751 ppr_assign [(one,hint)] rhs
752 | Just ty <- strangeRegType one
753 = pprReg one <> ptext SLIT(" = ") <> parens ty <> rhs
755 = pprReg one <> ptext SLIT(" = ")
756 <> pprUnHint hint (cmmRegRep one) <> rhs
757 ppr_assign _other _rhs = panic "pprCall: multiple results"
759 pprArg (expr, PtrHint)
760 = cCast (ptext SLIT("void *")) expr
761 -- see comment by machRepHintCType below
762 pprArg (expr, SignedHint)
763 = cCast (machRepSignedCType (cmmExprRep expr)) expr
764 pprArg (expr, _other)
767 pprUnHint PtrHint rep = parens (machRepCType rep)
768 pprUnHint SignedHint rep = parens (machRepCType rep)
769 pprUnHint _ _ = empty
771 save = save_restore SLIT("CALLER_SAVE")
772 restore = save_restore SLIT("CALLER_RESTORE")
774 -- Nothing says "I don't know what's live; save everything"
775 -- CALLER_SAVE_USER is defined in ghc/includes/Regs.h
776 save_restore txt Nothing = ptext txt <> ptext SLIT("_USER")
777 save_restore txt (Just these) = vcat (map saveRestoreGlobal these)
778 where saveRestoreGlobal r = ptext txt <> char '_' <> pprGlobalRegName r
780 pprGlobalRegName :: GlobalReg -> SDoc
781 pprGlobalRegName gr = case gr of
782 VanillaReg n -> char 'R' <> int n -- without the .w suffix
785 -- Currently we only have these two calling conventions, but this might
786 -- change in the future...
787 is_cish CCallConv = True
788 is_cish StdCallConv = True
790 -- ---------------------------------------------------------------------
791 -- Find and print local and external declarations for a list of
794 pprTempAndExternDecls :: [CmmBasicBlock] -> (SDoc{-temps-}, SDoc{-externs-})
795 pprTempAndExternDecls stmts
796 = (vcat (map pprTempDecl (eltsUFM temps)),
797 vcat (map (pprExternDecl False{-ToDo-}) (keysFM lbls)))
798 where (temps, lbls) = runTE (mapM_ te_BB stmts)
800 pprDataExterns :: [CmmStatic] -> SDoc
801 pprDataExterns statics
802 = vcat (map (pprExternDecl False{-ToDo-}) (keysFM lbls))
803 where (_, lbls) = runTE (mapM_ te_Static statics)
805 pprTempDecl :: LocalReg -> SDoc
806 pprTempDecl l@(LocalReg _uniq rep)
807 = hcat [ machRepCType rep, space, pprLocalReg l, semi ]
809 pprExternDecl :: Bool -> CLabel -> SDoc
810 pprExternDecl in_srt lbl
811 -- do not print anything for "known external" things
812 | not (needsCDecl lbl) = empty
814 hcat [ visibility, label_type (labelType lbl),
815 lparen, dyn_wrapper (pprCLabel lbl), text ");" ]
818 | in_srt && labelDynamic lbl = text "DLL_IMPORT_DATA_VAR" <> parens d
821 label_type CodeLabel = ptext SLIT("F_")
822 label_type DataLabel = ptext SLIT("I_")
825 | externallyVisibleCLabel lbl = char 'E'
826 | otherwise = char 'I'
829 type TEState = (UniqSet LocalReg, FiniteMap CLabel ())
830 newtype TE a = TE { unTE :: TEState -> (a, TEState) }
832 instance Monad TE where
833 TE m >>= k = TE $ \s -> case m s of (a, s') -> unTE (k a) s'
834 return a = TE $ \s -> (a, s)
836 te_lbl :: CLabel -> TE ()
837 te_lbl lbl = TE $ \(temps,lbls) -> ((), (temps, addToFM lbls lbl ()))
839 te_temp :: LocalReg -> TE ()
840 te_temp r = TE $ \(temps,lbls) -> ((), (addOneToUniqSet temps r, lbls))
842 runTE :: TE () -> TEState
843 runTE (TE m) = snd (m (emptyUniqSet, emptyFM))
845 te_Static :: CmmStatic -> TE ()
846 te_Static (CmmStaticLit lit) = te_Lit lit
847 te_Static _ = return ()
849 te_BB :: CmmBasicBlock -> TE ()
850 te_BB (BasicBlock _ ss) = mapM_ te_Stmt ss
852 te_Lit :: CmmLit -> TE ()
853 te_Lit (CmmLabel l) = te_lbl l
854 te_Lit (CmmLabelOff l _) = te_lbl l
855 te_Lit (CmmLabelDiffOff l1 l2 _) = te_lbl l1
858 te_Stmt :: CmmStmt -> TE ()
859 te_Stmt (CmmAssign r e) = te_Reg r >> te_Expr e
860 te_Stmt (CmmStore l r) = te_Expr l >> te_Expr r
861 te_Stmt (CmmCall _ rs es _) = mapM_ (te_Reg.fst) rs >>
862 mapM_ (te_Expr.fst) es
863 te_Stmt (CmmCondBranch e _) = te_Expr e
864 te_Stmt (CmmSwitch e _) = te_Expr e
865 te_Stmt (CmmJump e _) = te_Expr e
866 te_Stmt _ = return ()
868 te_Expr :: CmmExpr -> TE ()
869 te_Expr (CmmLit lit) = te_Lit lit
870 te_Expr (CmmLoad e _) = te_Expr e
871 te_Expr (CmmReg r) = te_Reg r
872 te_Expr (CmmMachOp _ es) = mapM_ te_Expr es
873 te_Expr (CmmRegOff r _) = te_Reg r
875 te_Reg :: CmmReg -> TE ()
876 te_Reg (CmmLocal l) = te_temp l
880 -- ---------------------------------------------------------------------
881 -- C types for MachReps
883 cCast :: SDoc -> CmmExpr -> SDoc
884 cCast ty expr = parens ty <> pprExpr1 expr
886 cLoad :: CmmExpr -> MachRep -> SDoc
887 #ifdef BEWARE_LOAD_STORE_ALIGNMENT
889 let decl = machRepCType rep <+> ptext SLIT("x") <> semi
890 struct = ptext SLIT("struct") <+> braces (decl)
891 packed_attr = ptext SLIT("__attribute__((packed))")
892 cast = parens (struct <+> packed_attr <> char '*')
893 in parens (cast <+> pprExpr1 expr) <> ptext SLIT("->x")
895 cLoad expr rep = char '*' <> parens (cCast (machRepPtrCType rep) expr)
898 -- This is for finding the types of foreign call arguments. For a pointer
899 -- argument, we always cast the argument to (void *), to avoid warnings from
901 machRepHintCType :: MachRep -> MachHint -> SDoc
902 machRepHintCType rep PtrHint = ptext SLIT("void *")
903 machRepHintCType rep SignedHint = machRepSignedCType rep
904 machRepHintCType rep _other = machRepCType rep
906 machRepPtrCType :: MachRep -> SDoc
907 machRepPtrCType r | r == wordRep = ptext SLIT("P_")
908 | otherwise = machRepCType r <> char '*'
910 machRepCType :: MachRep -> SDoc
911 machRepCType r | r == wordRep = ptext SLIT("W_")
912 | otherwise = sized_type
913 where sized_type = case r of
914 I8 -> ptext SLIT("StgWord8")
915 I16 -> ptext SLIT("StgWord16")
916 I32 -> ptext SLIT("StgWord32")
917 I64 -> ptext SLIT("StgWord64")
918 F32 -> ptext SLIT("StgFloat") -- ToDo: correct?
919 F64 -> ptext SLIT("StgDouble")
920 _ -> panic "machRepCType"
922 machRepSignedCType :: MachRep -> SDoc
923 machRepSignedCType r | r == wordRep = ptext SLIT("I_")
924 | otherwise = sized_type
925 where sized_type = case r of
926 I8 -> ptext SLIT("StgInt8")
927 I16 -> ptext SLIT("StgInt16")
928 I32 -> ptext SLIT("StgInt32")
929 I64 -> ptext SLIT("StgInt64")
930 F32 -> ptext SLIT("StgFloat") -- ToDo: correct?
931 F64 -> ptext SLIT("StgDouble")
932 _ -> panic "machRepCType"
934 -- ---------------------------------------------------------------------
935 -- print strings as valid C strings
937 pprStringInCStyle :: [Word8] -> SDoc
938 pprStringInCStyle s = doubleQuotes (text (concatMap charToC s))
940 charToC :: Word8 -> String
942 case chr (fromIntegral w) of
946 c | c >= ' ' && c <= '~' -> [c]
947 | otherwise -> ['\\',
948 chr (ord '0' + ord c `div` 64),
949 chr (ord '0' + ord c `div` 8 `mod` 8),
950 chr (ord '0' + ord c `mod` 8)]
952 -- ---------------------------------------------------------------------------
953 -- Initialising static objects with floating-point numbers. We can't
954 -- just emit the floating point number, because C will cast it to an int
955 -- by rounding it. We want the actual bit-representation of the float.
957 -- This is a hack to turn the floating point numbers into ints that we
958 -- can safely initialise to static locations.
961 | machRepByteWidth F64 == 2 * wORD_SIZE = True
962 | machRepByteWidth F64 == wORD_SIZE = False
963 | otherwise = panic "big_doubles"
965 #if __GLASGOW_HASKELL__ >= 504
966 newFloatArray :: (Int,Int) -> ST s (STUArray s Int Float)
967 newFloatArray = newArray_
969 newDoubleArray :: (Int,Int) -> ST s (STUArray s Int Double)
970 newDoubleArray = newArray_
972 castFloatToIntArray :: STUArray s Int Float -> ST s (STUArray s Int Int)
973 castFloatToIntArray = castSTUArray
975 castDoubleToIntArray :: STUArray s Int Double -> ST s (STUArray s Int Int)
976 castDoubleToIntArray = castSTUArray
978 writeFloatArray :: STUArray s Int Float -> Int -> Float -> ST s ()
979 writeFloatArray = writeArray
981 writeDoubleArray :: STUArray s Int Double -> Int -> Double -> ST s ()
982 writeDoubleArray = writeArray
984 readIntArray :: STUArray s Int Int -> Int -> ST s Int
985 readIntArray = readArray
989 castFloatToIntArray :: MutableByteArray s t -> ST s (MutableByteArray s t)
990 castFloatToIntArray = return
992 castDoubleToIntArray :: MutableByteArray s t -> ST s (MutableByteArray s t)
993 castDoubleToIntArray = return
997 -- floats are always 1 word
998 floatToWord :: Rational -> CmmLit
1001 arr <- newFloatArray ((0::Int),0)
1002 writeFloatArray arr 0 (fromRational r)
1003 arr' <- castFloatToIntArray arr
1004 i <- readIntArray arr' 0
1005 return (CmmInt (toInteger i) wordRep)
1008 doubleToWords :: Rational -> [CmmLit]
1010 | big_doubles -- doubles are 2 words
1012 arr <- newDoubleArray ((0::Int),1)
1013 writeDoubleArray arr 0 (fromRational r)
1014 arr' <- castDoubleToIntArray arr
1015 i1 <- readIntArray arr' 0
1016 i2 <- readIntArray arr' 1
1017 return [ CmmInt (toInteger i1) wordRep
1018 , CmmInt (toInteger i2) wordRep
1021 | otherwise -- doubles are 1 word
1023 arr <- newDoubleArray ((0::Int),0)
1024 writeDoubleArray arr 0 (fromRational r)
1025 arr' <- castDoubleToIntArray arr
1026 i <- readIntArray arr' 0
1027 return [ CmmInt (toInteger i) wordRep ]
1030 -- ---------------------------------------------------------------------------
1034 wordShift = machRepLogWidth wordRep
1036 commafy :: [SDoc] -> SDoc
1037 commafy xs = hsep $ punctuate comma xs
1039 -- Print in C hex format: 0x13fa
1040 pprHexVal :: Integer -> MachRep -> SDoc
1041 pprHexVal 0 _ = ptext SLIT("0x0")
1043 | w < 0 = parens (char '-' <> ptext SLIT("0x") <> go (-w) <> repsuffix rep)
1044 | otherwise = ptext SLIT("0x") <> go w <> repsuffix rep
1046 -- type suffix for literals:
1047 -- Integer literals are unsigned in Cmm/C. We explicitly cast to
1048 -- signed values for doing signed operations, but at all other
1049 -- times values are unsigned. This also helps eliminate occasional
1050 -- warnings about integer overflow from gcc.
1052 -- on 32-bit platforms, add "ULL" to 64-bit literals
1053 repsuffix I64 | wORD_SIZE == 4 = ptext SLIT("ULL")
1054 -- on 64-bit platforms with 32-bit int, add "L" to 64-bit literals
1055 repsuffix I64 | cINT_SIZE == 4 = ptext SLIT("UL")
1056 repsuffix _ = char 'U'
1061 (q,r) = w' `quotRem` 16
1062 dig | r < 10 = char (chr (fromInteger r + ord '0'))
1063 | otherwise = char (chr (fromInteger r - 10 + ord 'a'))