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