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