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