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