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
55 import Control.Monad.ST
57 #if x86_64_TARGET_ARCH
58 import StaticFlags ( opt_Unregisterised )
61 #if defined(alpha_TARGET_ARCH) || defined(mips_TARGET_ARCH) || defined(mipsel_TARGET_ARCH) || defined(arm_TARGET_ARCH)
62 #define BEWARE_LOAD_STORE_ALIGNMENT
65 -- --------------------------------------------------------------------------
68 pprCs :: DynFlags -> [Cmm] -> SDoc
70 = pprCode CStyle (vcat $ map (\c -> split_marker $$ pprC c) cmms)
73 | dopt Opt_SplitObjs dflags = ptext SLIT("__STG_SPLIT_MARKER")
76 writeCs :: DynFlags -> Handle -> [Cmm] -> IO ()
77 writeCs dflags handle cmms
78 = printForC handle (pprCs dflags cmms)
80 -- --------------------------------------------------------------------------
81 -- Now do some real work
83 -- for fun, we could call cmmToCmm over the tops...
87 pprC (Cmm tops) = vcat $ intersperse (text "") $ map pprTop tops
92 pprTop :: CmmTop -> SDoc
93 pprTop (CmmProc info clbl _params blocks) =
95 then pprDataExterns info $$
96 pprWordArray (entryLblToInfoLbl clbl) info
100 -- the first block doesn't get a label:
101 (BasicBlock _ stmts : rest) -> vcat [
104 (if (externallyVisibleCLabel clbl)
105 then mkFN_ else mkIF_) (pprCLabel clbl) <+> lbrace,
108 nest 8 (vcat (map pprStmt stmts)) $$
109 vcat (map pprBBlock rest),
114 (temp_decls, extern_decls) = pprTempAndExternDecls blocks
117 -- Chunks of static data.
119 -- We only handle (a) arrays of word-sized things and (b) strings.
121 pprTop (CmmData _section _ds@[CmmDataLabel lbl, CmmString str]) =
123 pprLocalness lbl, ptext SLIT("char "), pprCLabel lbl,
124 ptext SLIT("[] = "), pprStringInCStyle str, semi
127 pprTop (CmmData _section _ds@[CmmDataLabel lbl, CmmUninitialised size]) =
129 pprLocalness lbl, ptext SLIT("char "), pprCLabel lbl,
130 brackets (int size), semi
133 pprTop top@(CmmData _section (CmmDataLabel lbl : lits)) =
134 pprDataExterns lits $$
135 pprWordArray lbl lits
137 -- these shouldn't appear?
138 pprTop (CmmData _ _) = panic "PprC.pprTop: can't handle this data"
141 -- --------------------------------------------------------------------------
142 -- BasicBlocks are self-contained entities: they always end in a jump.
144 -- Like nativeGen/AsmCodeGen, we could probably reorder blocks to turn
145 -- as many jumps as possible into fall throughs.
148 pprBBlock :: CmmBasicBlock -> SDoc
149 pprBBlock (BasicBlock lbl stmts) =
151 pprTrace "pprC.pprBBlock: curious empty code block for"
152 (pprBlockId lbl) empty
154 nest 4 (pprBlockId lbl <> colon) $$
155 nest 8 (vcat (map pprStmt stmts))
157 -- --------------------------------------------------------------------------
158 -- Info tables. Just arrays of words.
159 -- See codeGen/ClosureInfo, and nativeGen/PprMach
161 pprWordArray :: CLabel -> [CmmStatic] -> SDoc
163 = hcat [ pprLocalness lbl, ptext SLIT("StgWord")
164 , space, pprCLabel lbl, ptext SLIT("[] = {") ]
165 $$ nest 8 (commafy (pprStatics ds))
169 -- has to be static, if it isn't globally visible
171 pprLocalness :: CLabel -> SDoc
172 pprLocalness lbl | not $ externallyVisibleCLabel lbl = ptext SLIT("static ")
175 -- --------------------------------------------------------------------------
179 pprStmt :: CmmStmt -> SDoc
181 pprStmt stmt = case stmt of
183 CmmComment s -> (hang (ptext SLIT("/*")) 3 (ftext s)) $$ ptext SLIT("*/")
185 CmmAssign dest src -> pprAssign dest src
188 | rep == I64 && wordRep /= I64
189 -> ptext SLIT("ASSIGN_Word64") <>
190 parens (mkP_ <> pprExpr1 dest <> comma <> pprExpr src) <> semi
192 | rep == F64 && wordRep /= I64
193 -> ptext SLIT("ASSIGN_DBL") <>
194 parens (mkP_ <> pprExpr1 dest <> comma <> pprExpr src) <> semi
197 -> hsep [ pprExpr (CmmLoad dest rep), equals, pprExpr src <> semi ]
201 CmmCall (CmmForeignCall fn cconv) results args volatile ->
202 -- Controversial: leave this out for now.
205 pprCall ppr_fn cconv results args volatile
208 CmmLit (CmmLabel lbl) -> pprCLabel lbl
209 _other -> parens (cCast (pprCFunType cconv results args) fn)
210 -- for a dynamic call, cast the expression to
211 -- a function of the right type (we hope).
213 -- we #undef a function before calling it: the FFI is supposed to be
214 -- an interface specifically to C, not to C+CPP. For one thing, this
215 -- makes the via-C route more compatible with the NCG. If macros
216 -- are being used for optimisation, then inline functions are probably
218 pprUndef (CmmLit (CmmLabel lbl)) =
219 ptext SLIT("#undef") <+> pprCLabel lbl
222 CmmCall (CmmPrim op) results args volatile ->
223 pprCall ppr_fn CCallConv results args volatile
225 ppr_fn = pprCallishMachOp_for_C op
227 CmmBranch ident -> pprBranch ident
228 CmmCondBranch expr ident -> pprCondBranch expr ident
229 CmmJump lbl _params -> mkJMP_(pprExpr lbl) <> semi
230 CmmSwitch arg ids -> pprSwitch arg ids
232 pprCFunType :: CCallConv -> [(CmmReg,MachHint)] -> [(CmmExpr,MachHint)] -> SDoc
233 pprCFunType cconv ress args
236 parens (text (ccallConvAttribute cconv) <> char '*'),
237 parens (commafy (map arg_type args))
240 res_type [] = ptext SLIT("void")
241 res_type [(one,hint)] = machRepHintCType (cmmRegRep one) hint
243 arg_type (expr,hint) = machRepHintCType (cmmExprRep expr) hint
245 -- ---------------------------------------------------------------------
246 -- unconditional branches
247 pprBranch :: BlockId -> SDoc
248 pprBranch ident = ptext SLIT("goto") <+> pprBlockId ident <> semi
251 -- ---------------------------------------------------------------------
252 -- conditional branches to local labels
253 pprCondBranch :: CmmExpr -> BlockId -> SDoc
254 pprCondBranch expr ident
255 = hsep [ ptext SLIT("if") , parens(pprExpr expr) ,
256 ptext SLIT("goto") , (pprBlockId ident) <> semi ]
259 -- ---------------------------------------------------------------------
260 -- a local table branch
262 -- we find the fall-through cases
264 -- N.B. we remove Nothing's from the list of branches, as they are
265 -- 'undefined'. However, they may be defined one day, so we better
266 -- document this behaviour.
268 pprSwitch :: CmmExpr -> [ Maybe BlockId ] -> SDoc
269 pprSwitch e maybe_ids
270 = let pairs = [ (ix, ident) | (ix,Just ident) <- zip [0..] maybe_ids ]
271 pairs2 = [ (map fst as, snd (head as)) | as <- groupBy sndEq pairs ]
273 (hang (ptext SLIT("switch") <+> parens ( pprExpr e ) <+> lbrace)
274 4 (vcat ( map caseify pairs2 )))
278 sndEq (_,x) (_,y) = x == y
281 caseify (ix:ixs, ident) = vcat (map do_fallthrough ixs) $$ final_branch ix
284 hsep [ ptext SLIT("case") , pprHexVal ix wordRep <> colon ,
285 ptext SLIT("/* fall through */") ]
288 hsep [ ptext SLIT("case") , pprHexVal ix wordRep <> colon ,
289 ptext SLIT("goto") , (pprBlockId ident) <> semi ]
291 -- ---------------------------------------------------------------------
295 -- C Types: the invariant is that the C expression generated by
299 -- has a type in C which is also given by
301 -- machRepCType (cmmExprRep e)
303 -- (similar invariants apply to the rest of the pretty printer).
305 pprExpr :: CmmExpr -> SDoc
306 pprExpr e = case e of
307 CmmLit lit -> pprLit lit
309 CmmLoad e I64 | wordRep /= I64
310 -> ptext SLIT("PK_Word64") <> parens (mkP_ <> pprExpr1 e)
312 CmmLoad e F64 | wordRep /= I64
313 -> ptext SLIT("PK_DBL") <> parens (mkP_ <> pprExpr1 e)
315 CmmLoad (CmmReg r) rep
316 | isPtrReg r && rep == wordRep
317 -> char '*' <> pprAsPtrReg r
319 CmmLoad (CmmRegOff r 0) rep
320 | isPtrReg r && rep == wordRep
321 -> char '*' <> pprAsPtrReg r
323 CmmLoad (CmmRegOff r off) rep
324 | isPtrReg r && rep == wordRep
325 -- ToDo: check that the offset is a word multiple?
326 -> pprAsPtrReg r <> brackets (ppr (off `shiftR` wordShift))
332 CmmReg reg -> pprCastReg reg
333 CmmRegOff reg 0 -> pprCastReg reg
336 | i > 0 -> pprRegOff (char '+') i
337 | otherwise -> pprRegOff (char '-') (-i)
339 pprRegOff op i' = pprCastReg reg <> op <> int i'
341 CmmMachOp mop args -> pprMachOpApp mop args
343 pprExpr1 :: CmmExpr -> SDoc
344 pprExpr1 (CmmLit lit) = pprLit1 lit
345 pprExpr1 e@(CmmReg _reg) = pprExpr e
346 pprExpr1 other = parens (pprExpr other)
348 -- --------------------------------------------------------------------------
349 -- MachOp applications
351 pprMachOpApp :: MachOp -> [CmmExpr] -> SDoc
355 = ptext SLIT("mulIntMayOflo") <> parens (commafy (map pprExpr args))
356 where isMulMayOfloOp (MO_U_MulMayOflo _) = True
357 isMulMayOfloOp (MO_S_MulMayOflo _) = True
358 isMulMayOfloOp _ = False
360 pprMachOpApp mop args
361 | Just ty <- machOpNeedsCast mop
362 = ty <> parens (pprMachOpApp' mop args)
364 = pprMachOpApp' mop args
366 -- Comparisons in C have type 'int', but we want type W_ (this is what
367 -- resultRepOfMachOp says). The other C operations inherit their type
368 -- from their operands, so no casting is required.
369 machOpNeedsCast :: MachOp -> Maybe SDoc
371 | isComparisonMachOp mop = Just mkW_
372 | otherwise = Nothing
374 pprMachOpApp' mop args
377 [x,y] -> pprArg x <+> pprMachOp_for_C mop <+> pprArg y
380 [x] -> pprMachOp_for_C mop <> parens (pprArg x)
382 _ -> panic "PprC.pprMachOp : machop with wrong number of args"
385 pprArg e | signedOp mop = cCast (machRepSignedCType (cmmExprRep e)) e
386 | otherwise = pprExpr1 e
388 -- --------------------------------------------------------------------------
391 pprLit :: CmmLit -> SDoc
392 pprLit lit = case lit of
393 CmmInt i rep -> pprHexVal i rep
394 CmmFloat f rep -> parens (machRepCType rep) <> (rational f)
395 CmmLabel clbl -> mkW_ <> pprCLabelAddr clbl
396 CmmLabelOff clbl i -> mkW_ <> pprCLabelAddr clbl <> char '+' <> int i
397 CmmLabelDiffOff clbl1 clbl2 i
399 -- * the lit must occur in the info table clbl2
400 -- * clbl1 must be an SRT, a slow entry point or a large bitmap
401 -- The Mangler is expected to convert any reference to an SRT,
402 -- a slow entry point or a large bitmap
403 -- from an info table to an offset.
404 -> mkW_ <> pprCLabelAddr clbl1 <> char '+' <> int i
406 pprCLabelAddr lbl = char '&' <> pprCLabel lbl
408 pprLit1 :: CmmLit -> SDoc
409 pprLit1 lit@(CmmLabelOff _ _) = parens (pprLit lit)
410 pprLit1 lit@(CmmLabelDiffOff _ _ _) = parens (pprLit lit)
411 pprLit1 lit@(CmmFloat _ _) = parens (pprLit lit)
412 pprLit1 other = pprLit other
414 -- ---------------------------------------------------------------------------
417 pprStatics :: [CmmStatic] -> [SDoc]
419 pprStatics (CmmStaticLit (CmmFloat f F32) : rest)
420 = pprLit1 (floatToWord f) : pprStatics rest
421 pprStatics (CmmStaticLit (CmmFloat f F64) : rest)
422 = map pprLit1 (doubleToWords f) ++ pprStatics rest
423 pprStatics (CmmStaticLit (CmmInt i I64) : rest)
424 | machRepByteWidth I32 == wORD_SIZE
425 #ifdef WORDS_BIGENDIAN
426 = pprStatics (CmmStaticLit (CmmInt q I32) :
427 CmmStaticLit (CmmInt r I32) : rest)
429 = pprStatics (CmmStaticLit (CmmInt r I32) :
430 CmmStaticLit (CmmInt q I32) : rest)
432 where r = i .&. 0xffffffff
434 pprStatics (CmmStaticLit (CmmInt i rep) : rest)
435 | machRepByteWidth rep /= wORD_SIZE
436 = panic "pprStatics: cannot emit a non-word-sized static literal"
437 pprStatics (CmmStaticLit lit : rest)
438 = pprLit1 lit : pprStatics rest
439 pprStatics (other : rest)
440 = pprPanic "pprWord" (pprStatic other)
442 pprStatic :: CmmStatic -> SDoc
443 pprStatic s = case s of
445 CmmStaticLit lit -> nest 4 (pprLit lit)
446 CmmAlign i -> nest 4 (ptext SLIT("/* align */") <+> int i)
447 CmmDataLabel clbl -> pprCLabel clbl <> colon
448 CmmUninitialised i -> nest 4 (mkC_ <> brackets (int i))
450 -- these should be inlined, like the old .hc
451 CmmString s' -> nest 4 (mkW_ <> parens(pprStringInCStyle s'))
454 -- ---------------------------------------------------------------------------
457 pprBlockId :: BlockId -> SDoc
458 pprBlockId b = char '_' <> ppr (getUnique b)
460 -- --------------------------------------------------------------------------
461 -- Print a MachOp in a way suitable for emitting via C.
464 pprMachOp_for_C :: MachOp -> SDoc
466 pprMachOp_for_C mop = case mop of
468 -- Integer operations
471 MO_Eq _ -> ptext SLIT("==")
472 MO_Ne _ -> ptext SLIT("!=")
475 MO_S_Quot _ -> char '/'
476 MO_S_Rem _ -> char '%'
477 MO_S_Neg _ -> char '-'
479 MO_U_Quot _ -> char '/'
480 MO_U_Rem _ -> char '%'
482 -- Signed comparisons (floating-point comparisons also use these)
483 -- & Unsigned comparisons
484 MO_S_Ge _ -> ptext SLIT(">=")
485 MO_S_Le _ -> ptext SLIT("<=")
486 MO_S_Gt _ -> char '>'
487 MO_S_Lt _ -> char '<'
489 MO_U_Ge _ -> ptext SLIT(">=")
490 MO_U_Le _ -> ptext SLIT("<=")
491 MO_U_Gt _ -> char '>'
492 MO_U_Lt _ -> char '<'
494 -- Bitwise operations. Not all of these may be supported at all
495 -- sizes, and only integral MachReps are valid.
500 MO_Shl _ -> ptext SLIT("<<")
501 MO_U_Shr _ -> ptext SLIT(">>") -- unsigned shift right
502 MO_S_Shr _ -> ptext SLIT(">>") -- signed shift right
504 -- Conversions. Some of these will be NOPs.
505 -- Floating-point conversions use the signed variant.
506 -- We won't know to generate (void*) casts here, but maybe from
510 MO_U_Conv I8 I8 -> empty
511 MO_U_Conv I16 I16 -> empty
512 MO_U_Conv I32 I32 -> empty
513 MO_U_Conv I64 I64 -> empty
514 MO_U_Conv I128 I128 -> empty
515 MO_S_Conv I8 I8 -> empty
516 MO_S_Conv I16 I16 -> empty
517 MO_S_Conv I32 I32 -> empty
518 MO_S_Conv I64 I64 -> empty
519 MO_S_Conv I128 I128 -> empty
521 MO_U_Conv _from to -> parens (machRepCType to)
522 MO_S_Conv _from to -> parens (machRepSignedCType to)
524 _ -> panic "PprC.pprMachOp_for_C: unknown machop"
526 signedOp :: MachOp -> Bool
527 signedOp (MO_S_Quot _) = True
528 signedOp (MO_S_Rem _) = True
529 signedOp (MO_S_Neg _) = True
530 signedOp (MO_S_Ge _) = True
531 signedOp (MO_S_Le _) = True
532 signedOp (MO_S_Gt _) = True
533 signedOp (MO_S_Lt _) = True
534 signedOp (MO_S_Shr _) = True
535 signedOp (MO_S_Conv _ _) = True
538 -- ---------------------------------------------------------------------
539 -- tend to be implemented by foreign calls
541 pprCallishMachOp_for_C :: CallishMachOp -> SDoc
543 pprCallishMachOp_for_C mop
545 MO_F64_Pwr -> ptext SLIT("pow")
546 MO_F64_Sin -> ptext SLIT("sin")
547 MO_F64_Cos -> ptext SLIT("cos")
548 MO_F64_Tan -> ptext SLIT("tan")
549 MO_F64_Sinh -> ptext SLIT("sinh")
550 MO_F64_Cosh -> ptext SLIT("cosh")
551 MO_F64_Tanh -> ptext SLIT("tanh")
552 MO_F64_Asin -> ptext SLIT("asin")
553 MO_F64_Acos -> ptext SLIT("acos")
554 MO_F64_Atan -> ptext SLIT("atan")
555 MO_F64_Log -> ptext SLIT("log")
556 MO_F64_Exp -> ptext SLIT("exp")
557 MO_F64_Sqrt -> ptext SLIT("sqrt")
558 MO_F32_Pwr -> ptext SLIT("powf")
559 MO_F32_Sin -> ptext SLIT("sinf")
560 MO_F32_Cos -> ptext SLIT("cosf")
561 MO_F32_Tan -> ptext SLIT("tanf")
562 MO_F32_Sinh -> ptext SLIT("sinhf")
563 MO_F32_Cosh -> ptext SLIT("coshf")
564 MO_F32_Tanh -> ptext SLIT("tanhf")
565 MO_F32_Asin -> ptext SLIT("asinf")
566 MO_F32_Acos -> ptext SLIT("acosf")
567 MO_F32_Atan -> ptext SLIT("atanf")
568 MO_F32_Log -> ptext SLIT("logf")
569 MO_F32_Exp -> ptext SLIT("expf")
570 MO_F32_Sqrt -> ptext SLIT("sqrtf")
571 MO_WriteBarrier -> ptext SLIT("write_barrier")
573 -- ---------------------------------------------------------------------
577 mkJMP_, mkFN_, mkIF_ :: SDoc -> SDoc
579 mkJMP_ i = ptext SLIT("JMP_") <> parens i
580 mkFN_ i = ptext SLIT("FN_") <> parens i -- externally visible function
581 mkIF_ i = ptext SLIT("IF_") <> parens i -- locally visible
585 mkFB_ = ptext SLIT("FB_") -- function code begin
586 mkFE_ = ptext SLIT("FE_") -- function code end
588 -- from includes/Stg.h
590 mkC_,mkW_,mkP_,mkPP_,mkI_,mkA_,mkD_,mkF_,mkB_,mkL_,mkLI_,mkLW_ :: SDoc
592 mkC_ = ptext SLIT("(C_)") -- StgChar
593 mkW_ = ptext SLIT("(W_)") -- StgWord
594 mkP_ = ptext SLIT("(P_)") -- StgWord*
595 mkPP_ = ptext SLIT("(PP_)") -- P_*
596 mkI_ = ptext SLIT("(I_)") -- StgInt
597 mkA_ = ptext SLIT("(A_)") -- StgAddr
598 mkD_ = ptext SLIT("(D_)") -- const StgWord*
599 mkF_ = ptext SLIT("(F_)") -- StgFunPtr
600 mkB_ = ptext SLIT("(B_)") -- StgByteArray
601 mkL_ = ptext SLIT("(L_)") -- StgClosurePtr
603 mkLI_ = ptext SLIT("(LI_)") -- StgInt64
604 mkLW_ = ptext SLIT("(LW_)") -- StgWord64
607 -- ---------------------------------------------------------------------
611 -- Generating assignments is what we're all about, here
613 pprAssign :: CmmReg -> CmmExpr -> SDoc
615 -- dest is a reg, rhs is a reg
616 pprAssign r1 (CmmReg r2)
617 | isPtrReg r1 && isPtrReg r2
618 = hcat [ pprAsPtrReg r1, equals, pprAsPtrReg r2, semi ]
620 -- dest is a reg, rhs is a CmmRegOff
621 pprAssign r1 (CmmRegOff r2 off)
622 | isPtrReg r1 && isPtrReg r2 && (off `rem` wORD_SIZE == 0)
623 = hcat [ pprAsPtrReg r1, equals, pprAsPtrReg r2, op, int off', semi ]
625 off1 = off `shiftR` wordShift
627 (op,off') | off >= 0 = (char '+', off1)
628 | otherwise = (char '-', -off1)
630 -- dest is a reg, rhs is anything.
631 -- We can't cast the lvalue, so we have to cast the rhs if necessary. Casting
632 -- the lvalue elicits a warning from new GCC versions (3.4+).
635 = pprReg r1 <> ptext SLIT(" = ") <> mkP_ <> pprExpr1 r2 <> semi
636 | Just ty <- strangeRegType r1
637 = pprReg r1 <> ptext SLIT(" = ") <> parens ty <> pprExpr1 r2 <> semi
639 = pprReg r1 <> ptext SLIT(" = ") <> pprExpr r2 <> semi
641 -- ---------------------------------------------------------------------
645 | isStrangeTypeReg reg = mkW_ <> pprReg reg
646 | otherwise = pprReg reg
648 -- True if (pprReg reg) will give an expression with type StgPtr. We
649 -- need to take care with pointer arithmetic on registers with type
651 isFixedPtrReg :: CmmReg -> Bool
652 isFixedPtrReg (CmmLocal _) = False
653 isFixedPtrReg (CmmGlobal r) = isFixedPtrGlobalReg r
655 -- True if (pprAsPtrReg reg) will give an expression with type StgPtr
656 isPtrReg :: CmmReg -> Bool
657 isPtrReg (CmmLocal _) = False
658 isPtrReg (CmmGlobal (VanillaReg n)) = True -- if we print via pprAsPtrReg
659 isPtrReg (CmmGlobal reg) = isFixedPtrGlobalReg reg
661 -- True if this global reg has type StgPtr
662 isFixedPtrGlobalReg :: GlobalReg -> Bool
663 isFixedPtrGlobalReg Sp = True
664 isFixedPtrGlobalReg Hp = True
665 isFixedPtrGlobalReg HpLim = True
666 isFixedPtrGlobalReg SpLim = True
667 isFixedPtrGlobalReg _ = False
669 -- True if in C this register doesn't have the type given by
670 -- (machRepCType (cmmRegRep reg)), so it has to be cast.
671 isStrangeTypeReg :: CmmReg -> Bool
672 isStrangeTypeReg (CmmLocal _) = False
673 isStrangeTypeReg (CmmGlobal g) = isStrangeTypeGlobal g
675 isStrangeTypeGlobal :: GlobalReg -> Bool
676 isStrangeTypeGlobal CurrentTSO = True
677 isStrangeTypeGlobal CurrentNursery = True
678 isStrangeTypeGlobal BaseReg = True
679 isStrangeTypeGlobal r = isFixedPtrGlobalReg r
681 strangeRegType :: CmmReg -> Maybe SDoc
682 strangeRegType (CmmGlobal CurrentTSO) = Just (ptext SLIT("struct StgTSO_ *"))
683 strangeRegType (CmmGlobal CurrentNursery) = Just (ptext SLIT("struct bdescr_ *"))
684 strangeRegType (CmmGlobal BaseReg) = Just (ptext SLIT("struct StgRegTable_ *"))
685 strangeRegType _ = Nothing
687 -- pprReg just prints the register name.
689 pprReg :: CmmReg -> SDoc
691 CmmLocal local -> pprLocalReg local
692 CmmGlobal global -> pprGlobalReg global
694 pprAsPtrReg :: CmmReg -> SDoc
695 pprAsPtrReg (CmmGlobal (VanillaReg n)) = char 'R' <> int n <> ptext SLIT(".p")
696 pprAsPtrReg other_reg = pprReg other_reg
698 pprGlobalReg :: GlobalReg -> SDoc
699 pprGlobalReg gr = case gr of
700 VanillaReg n -> char 'R' <> int n <> ptext SLIT(".w")
701 FloatReg n -> char 'F' <> int n
702 DoubleReg n -> char 'D' <> int n
703 LongReg n -> char 'L' <> int n
704 Sp -> ptext SLIT("Sp")
705 SpLim -> ptext SLIT("SpLim")
706 Hp -> ptext SLIT("Hp")
707 HpLim -> ptext SLIT("HpLim")
708 CurrentTSO -> ptext SLIT("CurrentTSO")
709 CurrentNursery -> ptext SLIT("CurrentNursery")
710 HpAlloc -> ptext SLIT("HpAlloc")
711 BaseReg -> ptext SLIT("BaseReg")
712 GCEnter1 -> ptext SLIT("stg_gc_enter_1")
713 GCFun -> ptext SLIT("stg_gc_fun")
715 pprLocalReg :: LocalReg -> SDoc
716 pprLocalReg (LocalReg uniq _rep) = char '_' <> ppr uniq
718 -- -----------------------------------------------------------------------------
721 pprCall :: SDoc -> CCallConv -> [(CmmReg,MachHint)] -> [(CmmExpr,MachHint)]
722 -> Maybe [GlobalReg] -> SDoc
724 pprCall ppr_fn cconv results args vols
725 | not (is_cish cconv)
726 = panic "pprCall: unknown calling convention"
730 ptext SLIT("CALLER_SAVE_SYSTEM") $$
731 #if x86_64_TARGET_ARCH
732 -- HACK around gcc optimisations.
733 -- x86_64 needs a __DISCARD__() here, to create a barrier between
734 -- putting the arguments into temporaries and passing the arguments
735 -- to the callee, because the argument expressions may refer to
736 -- machine registers that are also used for passing arguments in the
737 -- C calling convention.
738 (if (not opt_Unregisterised)
739 then ptext SLIT("__DISCARD__();")
742 ppr_assign results (ppr_fn <> parens (commafy (map pprArg args))) <> semi $$
743 ptext SLIT("CALLER_RESTORE_SYSTEM") $$
746 ppr_assign [] rhs = rhs
747 ppr_assign [(reg@(CmmGlobal BaseReg), hint)] rhs
748 | Just ty <- strangeRegType reg
749 = ptext SLIT("ASSIGN_BaseReg") <> parens (parens ty <> rhs)
750 -- BaseReg is special, sometimes it isn't an lvalue and we
751 -- can't assign to it.
752 ppr_assign [(one,hint)] rhs
753 | Just ty <- strangeRegType one
754 = pprReg one <> ptext SLIT(" = ") <> parens ty <> rhs
756 = pprReg one <> ptext SLIT(" = ")
757 <> pprUnHint hint (cmmRegRep one) <> rhs
758 ppr_assign _other _rhs = panic "pprCall: multiple results"
760 pprArg (expr, PtrHint)
761 = cCast (ptext SLIT("void *")) expr
762 -- see comment by machRepHintCType below
763 pprArg (expr, SignedHint)
764 = cCast (machRepSignedCType (cmmExprRep expr)) expr
765 pprArg (expr, _other)
768 pprUnHint PtrHint rep = parens (machRepCType rep)
769 pprUnHint SignedHint rep = parens (machRepCType rep)
770 pprUnHint _ _ = empty
772 save = save_restore SLIT("CALLER_SAVE")
773 restore = save_restore SLIT("CALLER_RESTORE")
775 -- Nothing says "I don't know what's live; save everything"
776 -- CALLER_SAVE_USER is defined in ghc/includes/Regs.h
777 save_restore txt Nothing = ptext txt <> ptext SLIT("_USER")
778 save_restore txt (Just these) = vcat (map saveRestoreGlobal these)
779 where saveRestoreGlobal r = ptext txt <> char '_' <> pprGlobalRegName r
781 pprGlobalRegName :: GlobalReg -> SDoc
782 pprGlobalRegName gr = case gr of
783 VanillaReg n -> char 'R' <> int n -- without the .w suffix
786 -- Currently we only have these two calling conventions, but this might
787 -- change in the future...
788 is_cish CCallConv = True
789 is_cish StdCallConv = True
791 -- ---------------------------------------------------------------------
792 -- Find and print local and external declarations for a list of
795 pprTempAndExternDecls :: [CmmBasicBlock] -> (SDoc{-temps-}, SDoc{-externs-})
796 pprTempAndExternDecls stmts
797 = (vcat (map pprTempDecl (eltsUFM temps)),
798 vcat (map (pprExternDecl False{-ToDo-}) (keysFM lbls)))
799 where (temps, lbls) = runTE (mapM_ te_BB stmts)
801 pprDataExterns :: [CmmStatic] -> SDoc
802 pprDataExterns statics
803 = vcat (map (pprExternDecl False{-ToDo-}) (keysFM lbls))
804 where (_, lbls) = runTE (mapM_ te_Static statics)
806 pprTempDecl :: LocalReg -> SDoc
807 pprTempDecl l@(LocalReg _uniq rep)
808 = hcat [ machRepCType rep, space, pprLocalReg l, semi ]
810 pprExternDecl :: Bool -> CLabel -> SDoc
811 pprExternDecl in_srt lbl
812 -- do not print anything for "known external" things
813 | not (needsCDecl lbl) = empty
815 hcat [ visibility, label_type (labelType lbl),
816 lparen, dyn_wrapper (pprCLabel lbl), text ");" ]
819 | in_srt && labelDynamic lbl = text "DLL_IMPORT_DATA_VAR" <> parens d
822 label_type CodeLabel = ptext SLIT("F_")
823 label_type DataLabel = ptext SLIT("I_")
826 | externallyVisibleCLabel lbl = char 'E'
827 | otherwise = char 'I'
830 type TEState = (UniqSet LocalReg, FiniteMap CLabel ())
831 newtype TE a = TE { unTE :: TEState -> (a, TEState) }
833 instance Monad TE where
834 TE m >>= k = TE $ \s -> case m s of (a, s') -> unTE (k a) s'
835 return a = TE $ \s -> (a, s)
837 te_lbl :: CLabel -> TE ()
838 te_lbl lbl = TE $ \(temps,lbls) -> ((), (temps, addToFM lbls lbl ()))
840 te_temp :: LocalReg -> TE ()
841 te_temp r = TE $ \(temps,lbls) -> ((), (addOneToUniqSet temps r, lbls))
843 runTE :: TE () -> TEState
844 runTE (TE m) = snd (m (emptyUniqSet, emptyFM))
846 te_Static :: CmmStatic -> TE ()
847 te_Static (CmmStaticLit lit) = te_Lit lit
848 te_Static _ = return ()
850 te_BB :: CmmBasicBlock -> TE ()
851 te_BB (BasicBlock _ ss) = mapM_ te_Stmt ss
853 te_Lit :: CmmLit -> TE ()
854 te_Lit (CmmLabel l) = te_lbl l
855 te_Lit (CmmLabelOff l _) = te_lbl l
856 te_Lit (CmmLabelDiffOff l1 l2 _) = te_lbl l1
859 te_Stmt :: CmmStmt -> TE ()
860 te_Stmt (CmmAssign r e) = te_Reg r >> te_Expr e
861 te_Stmt (CmmStore l r) = te_Expr l >> te_Expr r
862 te_Stmt (CmmCall _ rs es _) = mapM_ (te_Reg.fst) rs >>
863 mapM_ (te_Expr.fst) es
864 te_Stmt (CmmCondBranch e _) = te_Expr e
865 te_Stmt (CmmSwitch e _) = te_Expr e
866 te_Stmt (CmmJump e _) = te_Expr e
867 te_Stmt _ = return ()
869 te_Expr :: CmmExpr -> TE ()
870 te_Expr (CmmLit lit) = te_Lit lit
871 te_Expr (CmmLoad e _) = te_Expr e
872 te_Expr (CmmReg r) = te_Reg r
873 te_Expr (CmmMachOp _ es) = mapM_ te_Expr es
874 te_Expr (CmmRegOff r _) = te_Reg r
876 te_Reg :: CmmReg -> TE ()
877 te_Reg (CmmLocal l) = te_temp l
881 -- ---------------------------------------------------------------------
882 -- C types for MachReps
884 cCast :: SDoc -> CmmExpr -> SDoc
885 cCast ty expr = parens ty <> pprExpr1 expr
887 cLoad :: CmmExpr -> MachRep -> SDoc
888 #ifdef BEWARE_LOAD_STORE_ALIGNMENT
890 let decl = machRepCType rep <+> ptext SLIT("x") <> semi
891 struct = ptext SLIT("struct") <+> braces (decl)
892 packed_attr = ptext SLIT("__attribute__((packed))")
893 cast = parens (struct <+> packed_attr <> char '*')
894 in parens (cast <+> pprExpr1 expr) <> ptext SLIT("->x")
896 cLoad expr rep = char '*' <> parens (cCast (machRepPtrCType rep) expr)
899 -- This is for finding the types of foreign call arguments. For a pointer
900 -- argument, we always cast the argument to (void *), to avoid warnings from
902 machRepHintCType :: MachRep -> MachHint -> SDoc
903 machRepHintCType rep PtrHint = ptext SLIT("void *")
904 machRepHintCType rep SignedHint = machRepSignedCType rep
905 machRepHintCType rep _other = machRepCType rep
907 machRepPtrCType :: MachRep -> SDoc
908 machRepPtrCType r | r == wordRep = ptext SLIT("P_")
909 | otherwise = machRepCType r <> char '*'
911 machRepCType :: MachRep -> SDoc
912 machRepCType r | r == wordRep = ptext SLIT("W_")
913 | otherwise = sized_type
914 where sized_type = case r of
915 I8 -> ptext SLIT("StgWord8")
916 I16 -> ptext SLIT("StgWord16")
917 I32 -> ptext SLIT("StgWord32")
918 I64 -> ptext SLIT("StgWord64")
919 F32 -> ptext SLIT("StgFloat") -- ToDo: correct?
920 F64 -> ptext SLIT("StgDouble")
921 _ -> panic "machRepCType"
923 machRepSignedCType :: MachRep -> SDoc
924 machRepSignedCType r | r == wordRep = ptext SLIT("I_")
925 | otherwise = sized_type
926 where sized_type = case r of
927 I8 -> ptext SLIT("StgInt8")
928 I16 -> ptext SLIT("StgInt16")
929 I32 -> ptext SLIT("StgInt32")
930 I64 -> ptext SLIT("StgInt64")
931 F32 -> ptext SLIT("StgFloat") -- ToDo: correct?
932 F64 -> ptext SLIT("StgDouble")
933 _ -> panic "machRepCType"
935 -- ---------------------------------------------------------------------
936 -- print strings as valid C strings
938 pprStringInCStyle :: [Word8] -> SDoc
939 pprStringInCStyle s = doubleQuotes (text (concatMap charToC s))
941 charToC :: Word8 -> String
943 case chr (fromIntegral w) of
947 c | c >= ' ' && c <= '~' -> [c]
948 | otherwise -> ['\\',
949 chr (ord '0' + ord c `div` 64),
950 chr (ord '0' + ord c `div` 8 `mod` 8),
951 chr (ord '0' + ord c `mod` 8)]
953 -- ---------------------------------------------------------------------------
954 -- Initialising static objects with floating-point numbers. We can't
955 -- just emit the floating point number, because C will cast it to an int
956 -- by rounding it. We want the actual bit-representation of the float.
958 -- This is a hack to turn the floating point numbers into ints that we
959 -- can safely initialise to static locations.
962 | machRepByteWidth F64 == 2 * wORD_SIZE = True
963 | machRepByteWidth F64 == wORD_SIZE = False
964 | otherwise = panic "big_doubles"
966 castFloatToIntArray :: STUArray s Int Float -> ST s (STUArray s Int Int)
967 castFloatToIntArray = castSTUArray
969 castDoubleToIntArray :: STUArray s Int Double -> ST s (STUArray s Int Int)
970 castDoubleToIntArray = castSTUArray
972 -- floats are always 1 word
973 floatToWord :: Rational -> CmmLit
976 arr <- newArray_ ((0::Int),0)
977 writeArray arr 0 (fromRational r)
978 arr' <- castFloatToIntArray arr
979 i <- readArray arr' 0
980 return (CmmInt (toInteger i) wordRep)
983 doubleToWords :: Rational -> [CmmLit]
985 | big_doubles -- doubles are 2 words
987 arr <- newArray_ ((0::Int),1)
988 writeArray arr 0 (fromRational r)
989 arr' <- castDoubleToIntArray arr
990 i1 <- readArray arr' 0
991 i2 <- readArray arr' 1
992 return [ CmmInt (toInteger i1) wordRep
993 , CmmInt (toInteger i2) wordRep
996 | otherwise -- doubles are 1 word
998 arr <- newArray_ ((0::Int),0)
999 writeArray arr 0 (fromRational r)
1000 arr' <- castDoubleToIntArray arr
1001 i <- readArray arr' 0
1002 return [ CmmInt (toInteger i) wordRep ]
1005 -- ---------------------------------------------------------------------------
1009 wordShift = machRepLogWidth wordRep
1011 commafy :: [SDoc] -> SDoc
1012 commafy xs = hsep $ punctuate comma xs
1014 -- Print in C hex format: 0x13fa
1015 pprHexVal :: Integer -> MachRep -> SDoc
1016 pprHexVal 0 _ = ptext SLIT("0x0")
1018 | w < 0 = parens (char '-' <> ptext SLIT("0x") <> go (-w) <> repsuffix rep)
1019 | otherwise = ptext SLIT("0x") <> go w <> repsuffix rep
1021 -- type suffix for literals:
1022 -- Integer literals are unsigned in Cmm/C. We explicitly cast to
1023 -- signed values for doing signed operations, but at all other
1024 -- times values are unsigned. This also helps eliminate occasional
1025 -- warnings about integer overflow from gcc.
1027 -- on 32-bit platforms, add "ULL" to 64-bit literals
1028 repsuffix I64 | wORD_SIZE == 4 = ptext SLIT("ULL")
1029 -- on 64-bit platforms with 32-bit int, add "L" to 64-bit literals
1030 repsuffix I64 | cINT_SIZE == 4 = ptext SLIT("UL")
1031 repsuffix _ = char 'U'
1036 (q,r) = w' `quotRem` 16
1037 dig | r < 10 = char (chr (fromInteger r + ord '0'))
1038 | otherwise = char (chr (fromInteger r - 10 + ord 'a'))