[project @ 2005-03-18 13:37:27 by simonmar]
[ghc-hetmet.git] / ghc / compiler / cmm / CmmParse.y
1 -----------------------------------------------------------------------------
2 --
3 -- (c) The University of Glasgow, 2004
4 --
5 -- Parser for concrete Cmm.
6 --
7 -----------------------------------------------------------------------------
8
9 {
10 module CmmParse ( parseCmmFile ) where
11
12 import CgMonad
13 import CgHeapery
14 import CgUtils
15 import CgProf
16 import CgTicky
17 import CgInfoTbls
18 import CgForeignCall
19 import CgTailCall       ( pushUnboxedTuple )
20 import CgStackery       ( emitPushUpdateFrame )
21 import ClosureInfo      ( C_SRT(..) )
22 import CgCallConv       ( smallLiveness )
23 import CgClosure        ( emitBlackHoleCode )
24 import CostCentre       ( dontCareCCS )
25
26 import Cmm
27 import PprCmm
28 import CmmUtils         ( mkIntCLit )
29 import CmmLex
30 import CLabel
31 import MachOp
32 import SMRep            ( fixedHdrSize, CgRep(..) )
33 import Lexer
34
35 import ForeignCall      ( CCallConv(..) )
36 import Literal          ( mkMachInt )
37 import Unique
38 import UniqFM
39 import SrcLoc
40 import DynFlags         ( DynFlags, DynFlag(..) )
41 import StaticFlags      ( opt_SccProfilingOn )
42 import ErrUtils         ( printError, dumpIfSet_dyn, showPass )
43 import StringBuffer     ( hGetStringBuffer )
44 import FastString
45 import Panic            ( panic )
46 import Constants        ( wORD_SIZE )
47 import Outputable
48
49 import Monad            ( when )
50
51 #include "HsVersions.h"
52 }
53
54 %token
55         ':'     { L _ (CmmT_SpecChar ':') }
56         ';'     { L _ (CmmT_SpecChar ';') }
57         '{'     { L _ (CmmT_SpecChar '{') }
58         '}'     { L _ (CmmT_SpecChar '}') }
59         '['     { L _ (CmmT_SpecChar '[') }
60         ']'     { L _ (CmmT_SpecChar ']') }
61         '('     { L _ (CmmT_SpecChar '(') }
62         ')'     { L _ (CmmT_SpecChar ')') }
63         '='     { L _ (CmmT_SpecChar '=') }
64         '`'     { L _ (CmmT_SpecChar '`') }
65         '~'     { L _ (CmmT_SpecChar '~') }
66         '/'     { L _ (CmmT_SpecChar '/') }
67         '*'     { L _ (CmmT_SpecChar '*') }
68         '%'     { L _ (CmmT_SpecChar '%') }
69         '-'     { L _ (CmmT_SpecChar '-') }
70         '+'     { L _ (CmmT_SpecChar '+') }
71         '&'     { L _ (CmmT_SpecChar '&') }
72         '^'     { L _ (CmmT_SpecChar '^') }
73         '|'     { L _ (CmmT_SpecChar '|') }
74         '>'     { L _ (CmmT_SpecChar '>') }
75         '<'     { L _ (CmmT_SpecChar '<') }
76         ','     { L _ (CmmT_SpecChar ',') }
77         '!'     { L _ (CmmT_SpecChar '!') }
78
79         '..'    { L _ (CmmT_DotDot) }
80         '::'    { L _ (CmmT_DoubleColon) }
81         '>>'    { L _ (CmmT_Shr) }
82         '<<'    { L _ (CmmT_Shl) }
83         '>='    { L _ (CmmT_Ge) }
84         '<='    { L _ (CmmT_Le) }
85         '=='    { L _ (CmmT_Eq) }
86         '!='    { L _ (CmmT_Ne) }
87         '&&'    { L _ (CmmT_BoolAnd) }
88         '||'    { L _ (CmmT_BoolOr) }
89
90         'CLOSURE'       { L _ (CmmT_CLOSURE) }
91         'INFO_TABLE'    { L _ (CmmT_INFO_TABLE) }
92         'INFO_TABLE_RET'{ L _ (CmmT_INFO_TABLE_RET) }
93         'INFO_TABLE_FUN'{ L _ (CmmT_INFO_TABLE_FUN) }
94         'INFO_TABLE_CONSTR'{ L _ (CmmT_INFO_TABLE_CONSTR) }
95         'INFO_TABLE_SELECTOR'{ L _ (CmmT_INFO_TABLE_SELECTOR) }
96         'else'          { L _ (CmmT_else) }
97         'export'        { L _ (CmmT_export) }
98         'section'       { L _ (CmmT_section) }
99         'align'         { L _ (CmmT_align) }
100         'goto'          { L _ (CmmT_goto) }
101         'if'            { L _ (CmmT_if) }
102         'jump'          { L _ (CmmT_jump) }
103         'foreign'       { L _ (CmmT_foreign) }
104         'import'        { L _ (CmmT_import) }
105         'switch'        { L _ (CmmT_switch) }
106         'case'          { L _ (CmmT_case) }
107         'default'       { L _ (CmmT_default) }
108         'bits8'         { L _ (CmmT_bits8) }
109         'bits16'        { L _ (CmmT_bits16) }
110         'bits32'        { L _ (CmmT_bits32) }
111         'bits64'        { L _ (CmmT_bits64) }
112         'float32'       { L _ (CmmT_float32) }
113         'float64'       { L _ (CmmT_float64) }
114
115         GLOBALREG       { L _ (CmmT_GlobalReg   $$) }
116         NAME            { L _ (CmmT_Name        $$) }
117         STRING          { L _ (CmmT_String      $$) }
118         INT             { L _ (CmmT_Int         $$) }
119         FLOAT           { L _ (CmmT_Float       $$) }
120
121 %monad { P } { >>= } { return }
122 %lexer { cmmlex } { L _ CmmT_EOF }
123 %name cmmParse cmm
124 %tokentype { Located CmmToken }
125
126 -- C-- operator precedences, taken from the C-- spec
127 %right '||'     -- non-std extension, called %disjoin in C--
128 %right '&&'     -- non-std extension, called %conjoin in C--
129 %right '!'
130 %nonassoc '>=' '>' '<=' '<' '!=' '=='
131 %left '|'
132 %left '^'
133 %left '&'
134 %left '>>' '<<'
135 %left '-' '+'
136 %left '/' '*' '%'
137 %right '~'
138
139 %%
140
141 cmm     :: { ExtCode }
142         : {- empty -}                   { return () }
143         | cmmtop cmm                    { do $1; $2 }
144
145 cmmtop  :: { ExtCode }
146         : cmmproc                       { $1 }
147         | cmmdata                       { $1 }
148         | decl                          { $1 } 
149         | 'CLOSURE' '(' NAME ',' NAME lits ')' ';'  
150                 { do lits <- sequence $6;
151                      staticClosure $3 $5 (map getLit lits) }
152
153 -- The only static closures in the RTS are dummy closures like
154 -- stg_END_TSO_QUEUE_closure and stg_dummy_ret.  We don't need
155 -- to provide the full generality of static closures here.
156 -- In particular:
157 --      * CCS can always be CCS_DONT_CARE
158 --      * closure is always extern
159 --      * payload is always empty
160 --      * we can derive closure and info table labels from a single NAME
161
162 cmmdata :: { ExtCode }
163         : 'section' STRING '{' statics '}' 
164                 { do ss <- sequence $4;
165                      code (emitData (section $2) (concat ss)) }
166
167 statics :: { [ExtFCode [CmmStatic]] }
168         : {- empty -}                   { [] }
169         | static statics                { $1 : $2 }
170
171 -- Strings aren't used much in the RTS HC code, so it doesn't seem
172 -- worth allowing inline strings.  C-- doesn't allow them anyway.
173 static  :: { ExtFCode [CmmStatic] }
174         : NAME ':'      { return [CmmDataLabel (mkRtsDataLabelFS $1)] }
175         | type expr ';' { do e <- $2;
176                              return [CmmStaticLit (getLit e)] }
177         | type ';'                      { return [CmmUninitialised
178                                                         (machRepByteWidth $1)] }
179         | 'bits8' '[' ']' STRING ';'    { return [CmmString $4] }
180         | 'bits8' '[' INT ']' ';'       { return [CmmUninitialised 
181                                                         (fromIntegral $3)] }
182         | typenot8 '[' INT ']' ';'      { return [CmmUninitialised 
183                                                 (machRepByteWidth $1 * 
184                                                         fromIntegral $3)] }
185         | 'align' INT ';'               { return [CmmAlign (fromIntegral $2)] }
186         | 'CLOSURE' '(' NAME lits ')'
187                 { do lits <- sequence $4;
188                      return $ map CmmStaticLit $
189                        mkStaticClosure (mkRtsInfoLabelFS $3) 
190                          dontCareCCS (map getLit lits) [] [] [] }
191         -- arrays of closures required for the CHARLIKE & INTLIKE arrays
192
193 lits    :: { [ExtFCode CmmExpr] }
194         : {- empty -}           { [] }
195         | ',' expr lits         { $2 : $3 }
196
197 cmmproc :: { ExtCode }
198         : info '{' body '}'
199                 { do  (info_lbl, info1, info2) <- $1;
200                       stmts <- getCgStmtsEC (loopDecls $3)
201                       blks <- code (cgStmtsToBlocks stmts)
202                       code (emitInfoTableAndCode info_lbl info1 info2 [] blks) }
203
204         | info ';'
205                 { do (info_lbl, info1, info2) <- $1;
206                      code (emitInfoTableAndCode info_lbl info1 info2 [] []) }
207
208         | NAME '{' body '}'
209                 { do stmts <- getCgStmtsEC (loopDecls $3);
210                      blks <- code (cgStmtsToBlocks stmts)
211                      code (emitProc [] (mkRtsCodeLabelFS $1) [] blks) }
212
213 info    :: { ExtFCode (CLabel, [CmmLit],[CmmLit]) }
214         : 'INFO_TABLE' '(' NAME ',' INT ',' INT ',' INT ',' STRING ',' STRING ')'
215                 -- ptrs, nptrs, closure type, description, type
216                 { stdInfo $3 $5 $7 0 $9 $11 $13 }
217         
218         | 'INFO_TABLE_FUN' '(' NAME ',' INT ',' INT ',' INT ',' STRING ',' STRING ',' INT ')'
219                 -- ptrs, nptrs, closure type, description, type, fun type
220                 { funInfo $3 $5 $7 $9 $11 $13 $15 }
221         
222         | 'INFO_TABLE_CONSTR' '(' NAME ',' INT ',' INT ',' INT ',' INT ',' STRING ',' STRING ')'
223                 -- ptrs, nptrs, tag, closure type, description, type
224                 { stdInfo $3 $5 $7 $9 $11 $13 $15 }
225         
226         | 'INFO_TABLE_SELECTOR' '(' NAME ',' INT ',' INT ',' STRING ',' STRING ')'
227                 -- selector, closure type, description, type
228                 { basicInfo $3 (mkIntCLit (fromIntegral $5)) 0 $7 $9 $11 }
229
230         | 'INFO_TABLE_RET' '(' NAME ',' INT ',' INT ',' INT maybe_vec ')'
231                 { retInfo $3 $5 $7 $9 $10 }
232
233 maybe_vec :: { [CmmLit] }
234         : {- empty -}                   { [] }
235         | ',' NAME maybe_vec            { CmmLabel (mkRtsCodeLabelFS $2) : $3 }
236
237 body    :: { ExtCode }
238         : {- empty -}                   { return () }
239         | decl body                     { do $1; $2 }
240         | stmt body                     { do $1; $2 }
241
242 decl    :: { ExtCode }
243         : type names ';'                { mapM_ (newLocal $1) $2 }
244         | 'import' names ';'            { return () }  -- ignore imports
245         | 'export' names ';'            { return () }  -- ignore exports
246
247 names   :: { [FastString] }
248         : NAME                  { [$1] }
249         | NAME ',' names        { $1 : $3 }
250
251 stmt    :: { ExtCode }
252         : ';'                                   { nopEC }
253
254         | block_id ':'                          { code (labelC $1) }
255
256         | lreg '=' expr ';'                     
257                 { do reg <- $1; e <- $3; stmtEC (CmmAssign reg e) }
258         | type '[' expr ']' '=' expr ';'
259                 { doStore $1 $3 $6 }
260         | 'foreign' STRING expr '(' hint_exprs0 ')' vols ';'
261                 {% foreignCall $2 [] $3 $5 $7 }
262         | lreg '=' 'foreign' STRING expr '(' hint_exprs0 ')' vols ';'
263                 {% let result = do r <- $1; return (r,NoHint) in
264                    foreignCall $4 [result] $5 $7 $9 }
265         | STRING lreg '=' 'foreign' STRING expr '(' hint_exprs0 ')' vols ';'
266                 {% do h <- parseHint $1;
267                       let result = do r <- $2; return (r,h) in
268                       foreignCall $5 [result] $6 $8 $10 }
269         -- stmt-level macros, stealing syntax from ordinary C-- function calls.
270         -- Perhaps we ought to use the %%-form?
271         | NAME '(' exprs0 ')' ';'
272                 {% stmtMacro $1 $3  }
273         | 'switch' maybe_range expr '{' arms default '}'
274                 { doSwitch $2 $3 $5 $6 }
275         | 'goto' block_id ';'
276                 { stmtEC (CmmBranch $2) }
277         | 'jump' expr {-maybe_actuals-} ';'
278                 { do e <- $2; stmtEC (CmmJump e []) }
279         | 'if' bool_expr '{' body '}' else      
280                 { ifThenElse $2 $4 $6 }
281
282 bool_expr :: { ExtFCode BoolExpr }
283         : bool_op                       { $1 }
284         | expr                          { do e <- $1; return (BoolTest e) }
285
286 bool_op :: { ExtFCode BoolExpr }
287         : bool_expr '&&' bool_expr      { do e1 <- $1; e2 <- $3; 
288                                           return (BoolAnd e1 e2) }
289         | bool_expr '||' bool_expr      { do e1 <- $1; e2 <- $3; 
290                                           return (BoolOr e1 e2)  }
291         | '!' bool_expr                 { do e <- $2; return (BoolNot e) }
292         | '(' bool_op ')'               { $2 }
293
294 -- This is not C-- syntax.  What to do?
295 vols    :: { Maybe [GlobalReg] }
296         : {- empty -}                   { Nothing }
297         | '[' globals ']'               { Just $2 }
298
299 globals :: { [GlobalReg] }
300         : GLOBALREG                     { [$1] }
301         | GLOBALREG ',' globals         { $1 : $3 }
302
303 maybe_range :: { Maybe (Int,Int) }
304         : '[' INT '..' INT ']'  { Just (fromIntegral $2, fromIntegral $4) }
305         | {- empty -}           { Nothing }
306
307 arms    :: { [([Int],ExtCode)] }
308         : {- empty -}                   { [] }
309         | arm arms                      { $1 : $2 }
310
311 arm     :: { ([Int],ExtCode) }
312         : 'case' ints ':' '{' body '}'  { ($2, $5) }
313
314 ints    :: { [Int] }
315         : INT                           { [ fromIntegral $1 ] }
316         | INT ',' ints                  { fromIntegral $1 : $3 }
317
318 default :: { Maybe ExtCode }
319         : 'default' ':' '{' body '}'    { Just $4 }
320         -- taking a few liberties with the C-- syntax here; C-- doesn't have
321         -- 'default' branches
322         | {- empty -}                   { Nothing }
323
324 else    :: { ExtCode }
325         : {- empty -}                   { nopEC }
326         | 'else' '{' body '}'           { $3 }
327
328 -- we have to write this out longhand so that Happy's precedence rules
329 -- can kick in.
330 expr    :: { ExtFCode CmmExpr } 
331         : expr '/' expr                 { mkMachOp MO_U_Quot [$1,$3] }
332         | expr '*' expr                 { mkMachOp MO_Mul [$1,$3] }
333         | expr '%' expr                 { mkMachOp MO_U_Rem [$1,$3] }
334         | expr '-' expr                 { mkMachOp MO_Sub [$1,$3] }
335         | expr '+' expr                 { mkMachOp MO_Add [$1,$3] }
336         | expr '>>' expr                { mkMachOp MO_U_Shr [$1,$3] }
337         | expr '<<' expr                { mkMachOp MO_Shl [$1,$3] }
338         | expr '&' expr                 { mkMachOp MO_And [$1,$3] }
339         | expr '^' expr                 { mkMachOp MO_Xor [$1,$3] }
340         | expr '|' expr                 { mkMachOp MO_Or [$1,$3] }
341         | expr '>=' expr                { mkMachOp MO_U_Ge [$1,$3] }
342         | expr '>' expr                 { mkMachOp MO_U_Gt [$1,$3] }
343         | expr '<=' expr                { mkMachOp MO_U_Le [$1,$3] }
344         | expr '<' expr                 { mkMachOp MO_U_Lt [$1,$3] }
345         | expr '!=' expr                { mkMachOp MO_Ne [$1,$3] }
346         | expr '==' expr                { mkMachOp MO_Eq [$1,$3] }
347         | '~' expr                      { mkMachOp MO_Not [$2] }
348         | '-' expr                      { mkMachOp MO_S_Neg [$2] }
349         | expr0 '`' NAME '`' expr0      {% do { mo <- nameToMachOp $3 ;
350                                                 return (mkMachOp mo [$1,$5]) } }
351         | expr0                         { $1 }
352
353 expr0   :: { ExtFCode CmmExpr }
354         : INT   maybe_ty         { return (CmmLit (CmmInt $1 $2)) }
355         | FLOAT maybe_ty         { return (CmmLit (CmmFloat $1 $2)) }
356         | STRING                 { do s <- code (mkStringCLit $1); 
357                                       return (CmmLit s) }
358         | reg                    { $1 }
359         | type '[' expr ']'      { do e <- $3; return (CmmLoad e $1) }
360         | '%' NAME '(' exprs0 ')' {% exprOp $2 $4 }
361         | '(' expr ')'           { $2 }
362
363
364 -- leaving out the type of a literal gives you the native word size in C--
365 maybe_ty :: { MachRep }
366         : {- empty -}                   { wordRep }
367         | '::' type                     { $2 }
368
369 hint_exprs0 :: { [ExtFCode (CmmExpr, MachHint)] }
370         : {- empty -}                   { [] }
371         | hint_exprs                    { $1 }
372
373 hint_exprs :: { [ExtFCode (CmmExpr, MachHint)] }
374         : hint_expr                     { [$1] }
375         | hint_expr ',' hint_exprs      { $1 : $3 }
376
377 hint_expr :: { ExtFCode (CmmExpr, MachHint) }
378         : expr                          { do e <- $1; return (e, inferHint e) }
379         | expr STRING                   {% do h <- parseHint $2;
380                                               return $ do
381                                                 e <- $1; return (e,h) }
382
383 exprs0  :: { [ExtFCode CmmExpr] }
384         : {- empty -}                   { [] }
385         | exprs                         { $1 }
386
387 exprs   :: { [ExtFCode CmmExpr] }
388         : expr                          { [ $1 ] }
389         | expr ',' exprs                { $1 : $3 }
390
391 reg     :: { ExtFCode CmmExpr }
392         : NAME                  { lookupName $1 }
393         | GLOBALREG             { return (CmmReg (CmmGlobal $1)) }
394
395 lreg    :: { ExtFCode CmmReg }
396         : NAME                  { do e <- lookupName $1;
397                                      return $
398                                        case e of 
399                                         CmmReg r -> r
400                                         other -> pprPanic "CmmParse:" (ftext $1 <> text " not a register") }
401         | GLOBALREG             { return (CmmGlobal $1) }
402
403 block_id :: { BlockId }
404         : NAME                  { BlockId (newTagUnique (getUnique $1) 'L') }
405                         -- TODO: ugh.  The unique of a FastString has a null
406                         -- tag, so we have to put our own tag on.  We should
407                         -- really make a new unique for every label, and keep
408                         -- them in an environment.
409
410 type    :: { MachRep }
411         : 'bits8'               { I8 }
412         | typenot8              { $1 }
413
414 typenot8 :: { MachRep }
415         : 'bits16'              { I16 }
416         | 'bits32'              { I32 }
417         | 'bits64'              { I64 }
418         | 'float32'             { F32 }
419         | 'float64'             { F64 }
420 {
421 section :: String -> Section
422 section "text"   = Text
423 section "data"   = Data
424 section "rodata" = ReadOnlyData
425 section "bss"    = UninitialisedData
426 section s        = OtherSection s
427
428 -- mkMachOp infers the type of the MachOp from the type of its first
429 -- argument.  We assume that this is correct: for MachOps that don't have
430 -- symmetrical args (e.g. shift ops), the first arg determines the type of
431 -- the op.
432 mkMachOp :: (MachRep -> MachOp) -> [ExtFCode CmmExpr] -> ExtFCode CmmExpr
433 mkMachOp fn args = do
434   arg_exprs <- sequence args
435   return (CmmMachOp (fn (cmmExprRep (head arg_exprs))) arg_exprs)
436
437 getLit :: CmmExpr -> CmmLit
438 getLit (CmmLit l) = l
439 getLit (CmmMachOp (MO_S_Neg _) [CmmLit (CmmInt i r)])  = CmmInt (negate i) r
440 getLit _ = panic "invalid literal" -- TODO messy failure
441
442 nameToMachOp :: FastString -> P (MachRep -> MachOp)
443 nameToMachOp name = 
444   case lookupUFM machOps name of
445         Nothing -> fail ("unknown primitive " ++ unpackFS name)
446         Just m  -> return m
447
448 exprOp :: FastString -> [ExtFCode CmmExpr] -> P (ExtFCode CmmExpr)
449 exprOp name args_code =
450   case lookupUFM exprMacros name of
451      Just f  -> return $ do
452         args <- sequence args_code
453         return (f args)
454      Nothing -> do
455         mo <- nameToMachOp name
456         return $ mkMachOp mo args_code
457
458 exprMacros :: UniqFM ([CmmExpr] -> CmmExpr)
459 exprMacros = listToUFM [
460   ( FSLIT("ENTRY_CODE"),   \ [x] -> entryCode x ),
461   ( FSLIT("GET_ENTRY"),    \ [x] -> entryCode (closureInfoPtr x) ),
462   ( FSLIT("STD_INFO"),     \ [x] -> infoTable x ),
463   ( FSLIT("GET_STD_INFO"), \ [x] -> infoTable (closureInfoPtr x) ),
464   ( FSLIT("GET_FUN_INFO"), \ [x] -> funInfoTable (closureInfoPtr x) ),
465   ( FSLIT("INFO_TYPE"),    \ [x] -> infoTableClosureType x ),
466   ( FSLIT("INFO_PTRS"),    \ [x] -> infoTablePtrs x ),
467   ( FSLIT("INFO_NPTRS"),   \ [x] -> infoTableNonPtrs x ),
468   ( FSLIT("RET_VEC"),      \ [info, conZ] -> retVec info conZ )
469   ]
470
471 -- we understand a subset of C-- primitives:
472 machOps = listToUFM $
473         map (\(x, y) -> (mkFastString x, y)) [
474         ( "add",        MO_Add ),
475         ( "sub",        MO_Sub ),
476         ( "eq",         MO_Eq ),
477         ( "ne",         MO_Ne ),
478         ( "mul",        MO_Mul ),
479         ( "neg",        MO_S_Neg ),
480         ( "quot",       MO_S_Quot ),
481         ( "rem",        MO_S_Rem ),
482         ( "divu",       MO_U_Quot ),
483         ( "modu",       MO_U_Rem ),
484
485         ( "ge",         MO_S_Ge ),
486         ( "le",         MO_S_Le ),
487         ( "gt",         MO_S_Gt ),
488         ( "lt",         MO_S_Lt ),
489
490         ( "geu",        MO_U_Ge ),
491         ( "leu",        MO_U_Le ),
492         ( "gtu",        MO_U_Gt ),
493         ( "ltu",        MO_U_Lt ),
494
495         ( "flt",        MO_S_Lt ),
496         ( "fle",        MO_S_Le ),
497         ( "feq",        MO_Eq ),
498         ( "fne",        MO_Ne ),
499         ( "fgt",        MO_S_Gt ),
500         ( "fge",        MO_S_Ge ),
501         ( "fneg",       MO_S_Neg ),
502
503         ( "and",        MO_And ),
504         ( "or",         MO_Or ),
505         ( "xor",        MO_Xor ),
506         ( "com",        MO_Not ),
507         ( "shl",        MO_Shl ),
508         ( "shrl",       MO_U_Shr ),
509         ( "shra",       MO_S_Shr ),
510
511         ( "lobits8",  flip MO_U_Conv I8  ),
512         ( "lobits16", flip MO_U_Conv I16 ),
513         ( "lobits32", flip MO_U_Conv I32 ),
514         ( "lobits64", flip MO_U_Conv I64 ),
515         ( "sx16",     flip MO_S_Conv I16 ),
516         ( "sx32",     flip MO_S_Conv I32 ),
517         ( "sx64",     flip MO_S_Conv I64 ),
518         ( "zx16",     flip MO_U_Conv I16 ),
519         ( "zx32",     flip MO_U_Conv I32 ),
520         ( "zx64",     flip MO_U_Conv I64 ),
521         ( "f2f32",    flip MO_S_Conv F32 ),  -- TODO; rounding mode
522         ( "f2f64",    flip MO_S_Conv F64 ),  -- TODO; rounding mode
523         ( "f2i8",     flip MO_S_Conv I8 ),
524         ( "f2i16",    flip MO_S_Conv I8 ),
525         ( "f2i32",    flip MO_S_Conv I8 ),
526         ( "f2i64",    flip MO_S_Conv I8 ),
527         ( "i2f32",    flip MO_S_Conv F32 ),
528         ( "i2f64",    flip MO_S_Conv F64 )
529         ]
530
531 parseHint :: String -> P MachHint
532 parseHint "ptr"    = return PtrHint
533 parseHint "signed" = return SignedHint
534 parseHint "float"  = return FloatHint
535 parseHint str      = fail ("unrecognised hint: " ++ str)
536
537 -- labels are always pointers, so we might as well infer the hint
538 inferHint :: CmmExpr -> MachHint
539 inferHint (CmmLit (CmmLabel _)) = PtrHint
540 inferHint (CmmReg (CmmGlobal g)) | isPtrGlobalReg g = PtrHint
541 inferHint _ = NoHint
542
543 isPtrGlobalReg Sp               = True
544 isPtrGlobalReg SpLim            = True
545 isPtrGlobalReg Hp               = True
546 isPtrGlobalReg HpLim            = True
547 isPtrGlobalReg CurrentTSO       = True
548 isPtrGlobalReg CurrentNursery   = True
549 isPtrGlobalReg _                = False
550
551 happyError :: P a
552 happyError = srcParseFail
553
554 -- -----------------------------------------------------------------------------
555 -- Statement-level macros
556
557 stmtMacro :: FastString -> [ExtFCode CmmExpr] -> P ExtCode
558 stmtMacro fun args_code = do
559   case lookupUFM stmtMacros fun of
560     Nothing -> fail ("unknown macro: " ++ unpackFS fun)
561     Just fcode -> return $ do
562         args <- sequence args_code
563         code (fcode args)
564
565 stmtMacros :: UniqFM ([CmmExpr] -> Code)
566 stmtMacros = listToUFM [
567   ( FSLIT("CCS_ALLOC"),            \[words,ccs]  -> profAlloc words ccs ),
568   ( FSLIT("CLOSE_NURSERY"),        \[]  -> emitCloseNursery ),
569   ( FSLIT("ENTER_CCS_PAP_CL"),     \[e] -> enterCostCentrePAP e ),
570   ( FSLIT("ENTER_CCS_THUNK"),      \[e] -> enterCostCentreThunk e ),
571   ( FSLIT("HP_CHK_GEN"),           \[words,liveness,reentry] -> 
572                                       hpChkGen words liveness reentry ),
573   ( FSLIT("HP_CHK_NP_ASSIGN_SP0"), \[e,f] -> hpChkNodePointsAssignSp0 e f ),
574   ( FSLIT("LOAD_THREAD_STATE"),    \[] -> emitLoadThreadState ),
575   ( FSLIT("LDV_ENTER"),            \[e] -> ldvEnter e ),
576   ( FSLIT("LDV_RECORD_CREATE"),    \[e] -> ldvRecordCreate e ),
577   ( FSLIT("OPEN_NURSERY"),         \[]  -> emitOpenNursery ),
578   ( FSLIT("PUSH_UPD_FRAME"),       \[sp,e] -> emitPushUpdateFrame sp e ),
579   ( FSLIT("SAVE_THREAD_STATE"),    \[] -> emitSaveThreadState ),
580   ( FSLIT("SET_HDR"),              \[ptr,info,ccs] -> 
581                                         emitSetDynHdr ptr info ccs ),
582   ( FSLIT("STK_CHK_GEN"),          \[words,liveness,reentry] -> 
583                                       stkChkGen words liveness reentry ),
584   ( FSLIT("STK_CHK_NP"),           \[e] -> stkChkNodePoints e ),
585   ( FSLIT("TICK_ALLOC_PRIM"),      \[hdr,goods,slop] -> 
586                                         tickyAllocPrim hdr goods slop ),
587   ( FSLIT("TICK_ALLOC_PAP"),       \[goods,slop] -> 
588                                         tickyAllocPAP goods slop ),
589   ( FSLIT("TICK_ALLOC_UP_THK"),    \[goods,slop] -> 
590                                         tickyAllocThunk goods slop ),
591   ( FSLIT("UPD_BH_UPDATABLE"),       \[] -> emitBlackHoleCode False ),
592   ( FSLIT("UPD_BH_SINGLE_ENTRY"),    \[] -> emitBlackHoleCode True ),
593
594   ( FSLIT("RET_P"),     \[a] ->       emitRetUT [(PtrArg,a)]),
595   ( FSLIT("RET_N"),     \[a] ->       emitRetUT [(NonPtrArg,a)]),
596   ( FSLIT("RET_PP"),    \[a,b] ->     emitRetUT [(PtrArg,a),(PtrArg,b)]),
597   ( FSLIT("RET_NN"),    \[a,b] ->     emitRetUT [(NonPtrArg,a),(NonPtrArg,b)]),
598   ( FSLIT("RET_NP"),    \[a,b] ->     emitRetUT [(NonPtrArg,a),(PtrArg,b)]),
599   ( FSLIT("RET_PPP"),   \[a,b,c] ->   emitRetUT [(PtrArg,a),(PtrArg,b),(PtrArg,c)]),
600   ( FSLIT("RET_NNP"),   \[a,b,c] ->   emitRetUT [(NonPtrArg,a),(NonPtrArg,b),(PtrArg,c)]),
601   ( FSLIT("RET_NNNP"),  \[a,b,c,d] -> emitRetUT [(NonPtrArg,a),(NonPtrArg,b),(NonPtrArg,c),(PtrArg,d)]),
602   ( FSLIT("RET_NPNP"),  \[a,b,c,d] -> emitRetUT [(NonPtrArg,a),(PtrArg,b),(NonPtrArg,c),(PtrArg,d)])
603
604  ]
605
606 -- -----------------------------------------------------------------------------
607 -- Our extended FCode monad.
608
609 -- We add a mapping from names to CmmExpr, to support local variable names in
610 -- the concrete C-- code.  The unique supply of the underlying FCode monad
611 -- is used to grab a new unique for each local variable.
612
613 -- In C--, a local variable can be declared anywhere within a proc,
614 -- and it scopes from the beginning of the proc to the end.  Hence, we have
615 -- to collect declarations as we parse the proc, and feed the environment
616 -- back in circularly (to avoid a two-pass algorithm).
617
618 type Decls = [(FastString,CmmExpr)]
619 type Env   = UniqFM CmmExpr
620
621 newtype ExtFCode a = EC { unEC :: Env -> Decls -> FCode (Decls, a) }
622
623 type ExtCode = ExtFCode ()
624
625 returnExtFC a = EC $ \e s -> return (s, a)
626 thenExtFC (EC m) k = EC $ \e s -> do (s',r) <- m e s; unEC (k r) e s'
627
628 instance Monad ExtFCode where
629   (>>=) = thenExtFC
630   return = returnExtFC
631
632 -- This function takes the variable decarations and imports and makes 
633 -- an environment, which is looped back into the computation.  In this
634 -- way, we can have embedded declarations that scope over the whole
635 -- procedure, and imports that scope over the entire module.
636 loopDecls :: ExtFCode a -> ExtFCode a
637 loopDecls (EC fcode) = 
638    EC $ \e s -> fixC (\ ~(decls,a) -> fcode (addListToUFM e decls) [])
639
640 getEnv :: ExtFCode Env
641 getEnv = EC $ \e s -> return (s, e)
642
643 addVarDecl :: FastString -> CmmExpr -> ExtCode
644 addVarDecl var expr = EC $ \e s -> return ((var,expr):s, ())
645
646 newLocal :: MachRep -> FastString -> ExtCode
647 newLocal ty name  = do
648    u <- code newUnique
649    addVarDecl name (CmmReg (CmmLocal (LocalReg u ty)))
650
651 -- Unknown names are treated as if they had been 'import'ed.
652 -- This saves us a lot of bother in the RTS sources, at the expense of
653 -- deferring some errors to link time.
654 lookupName :: FastString -> ExtFCode CmmExpr
655 lookupName name = do
656   env <- getEnv
657   return $ 
658      case lookupUFM env name of
659         Nothing -> CmmLit (CmmLabel (mkRtsCodeLabelFS name))
660         Just e  -> e
661
662 -- Lifting FCode computations into the ExtFCode monad:
663 code :: FCode a -> ExtFCode a
664 code fc = EC $ \e s -> do r <- fc; return (s, r)
665
666 code2 :: (FCode (Decls,b) -> FCode ((Decls,b),c))
667          -> ExtFCode b -> ExtFCode c
668 code2 f (EC ec) = EC $ \e s -> do ((s',b),c) <- f (ec e s); return (s',c)
669
670 nopEC = code nopC
671 stmtEC stmt = code (stmtC stmt)
672 stmtsEC stmts = code (stmtsC stmts)
673 getCgStmtsEC = code2 getCgStmts'
674
675 forkLabelledCodeEC ec = do
676   stmts <- getCgStmtsEC ec
677   code (forkCgStmts stmts)
678
679 retInfo name size live_bits cl_type vector = do
680   let liveness = smallLiveness (fromIntegral size) (fromIntegral live_bits)
681       info_lbl = mkRtsRetInfoLabelFS name
682       (info1,info2) = mkRetInfoTable info_lbl liveness NoC_SRT 
683                                 (fromIntegral cl_type) vector
684   return (info_lbl, info1, info2)
685
686 stdInfo name ptrs nptrs srt_bitmap cl_type desc_str ty_str =
687   basicInfo name (packHalfWordsCLit ptrs nptrs) 
688         srt_bitmap cl_type desc_str ty_str
689
690 basicInfo name layout srt_bitmap cl_type desc_str ty_str = do
691   lit1 <- if opt_SccProfilingOn 
692                    then code $ mkStringCLit desc_str
693                    else return (mkIntCLit 0)
694   lit2 <- if opt_SccProfilingOn 
695                    then code $ mkStringCLit ty_str
696                    else return (mkIntCLit 0)
697   let info1 = mkStdInfoTable lit1 lit2 (fromIntegral cl_type) 
698                         (fromIntegral srt_bitmap)
699                         layout
700   return (mkRtsInfoLabelFS name, info1, [])
701
702 funInfo name ptrs nptrs cl_type desc_str ty_str fun_type = do
703   (label,info1,_) <- stdInfo name ptrs nptrs 0{-srt_bitmap-}
704                          cl_type desc_str ty_str 
705   let info2 = mkFunGenInfoExtraBits (fromIntegral fun_type) 0 zero zero zero
706                 -- we leave most of the fields zero here.  This is only used
707                 -- to generate the BCO info table in the RTS at the moment.
708   return (label,info1,info2)
709  where
710    zero = mkIntCLit 0
711
712
713 staticClosure :: FastString -> FastString -> [CmmLit] -> ExtCode
714 staticClosure cl_label info payload
715   = code $ emitDataLits (mkRtsDataLabelFS cl_label) lits
716   where  lits = mkStaticClosure (mkRtsInfoLabelFS info) dontCareCCS payload [] [] []
717
718 foreignCall
719         :: String
720         -> [ExtFCode (CmmReg,MachHint)]
721         -> ExtFCode CmmExpr
722         -> [ExtFCode (CmmExpr,MachHint)]
723         -> Maybe [GlobalReg] -> P ExtCode
724 foreignCall "C" results_code expr_code args_code vols
725   = return $ do
726         results <- sequence results_code
727         expr <- expr_code
728         args <- sequence args_code
729         stmtEC (CmmCall (CmmForeignCall expr CCallConv) results args vols)
730 foreignCall conv _ _ _ _
731   = fail ("unknown calling convention: " ++ conv)
732
733 doStore :: MachRep -> ExtFCode CmmExpr  -> ExtFCode CmmExpr -> ExtCode
734 doStore rep addr_code val_code
735   = do addr <- addr_code
736        val <- val_code
737         -- if the specified store type does not match the type of the expr
738         -- on the rhs, then we insert a coercion that will cause the type
739         -- mismatch to be flagged by cmm-lint.  If we don't do this, then
740         -- the store will happen at the wrong type, and the error will not
741         -- be noticed.
742        let coerce_val 
743                 | cmmExprRep val /= rep = CmmMachOp (MO_U_Conv rep rep) [val]
744                 | otherwise             = val
745        stmtEC (CmmStore addr coerce_val)
746
747 -- Return an unboxed tuple.
748 emitRetUT :: [(CgRep,CmmExpr)] -> Code
749 emitRetUT args = do
750   tickyUnboxedTupleReturn (length args)  -- TICK
751   (sp, stmts) <- pushUnboxedTuple 0 args
752   emitStmts stmts
753   when (sp /= 0) $ stmtC (CmmAssign spReg (cmmRegOffW spReg (-sp)))
754   stmtC (CmmJump (entryCode (CmmLoad (cmmRegOffW spReg sp) wordRep)) [])
755
756 -- -----------------------------------------------------------------------------
757 -- If-then-else and boolean expressions
758
759 data BoolExpr
760   = BoolExpr `BoolAnd` BoolExpr
761   | BoolExpr `BoolOr`  BoolExpr
762   | BoolNot BoolExpr
763   | BoolTest CmmExpr
764
765 -- ToDo: smart constructors which simplify the boolean expression.
766
767 ifThenElse cond then_part else_part = do
768      then_id <- code newLabelC
769      join_id <- code newLabelC
770      c <- cond
771      emitCond c then_id
772      else_part
773      stmtEC (CmmBranch join_id)
774      code (labelC then_id)
775      then_part
776      -- fall through to join
777      code (labelC join_id)
778
779 -- 'emitCond cond true_id'  emits code to test whether the cond is true,
780 -- branching to true_id if so, and falling through otherwise.
781 emitCond (BoolTest e) then_id = do
782   stmtEC (CmmCondBranch e then_id)
783 emitCond (BoolNot (BoolTest (CmmMachOp op args))) then_id
784   | Just op' <- maybeInvertComparison op
785   = emitCond (BoolTest (CmmMachOp op' args)) then_id
786 emitCond (BoolNot e) then_id = do
787   else_id <- code newLabelC
788   emitCond e else_id
789   stmtEC (CmmBranch then_id)
790   code (labelC else_id)
791 emitCond (e1 `BoolOr` e2) then_id = do
792   emitCond e1 then_id
793   emitCond e2 then_id
794 emitCond (e1 `BoolAnd` e2) then_id = do
795         -- we'd like to invert one of the conditionals here to avoid an
796         -- extra branch instruction, but we can't use maybeInvertComparison
797         -- here because we can't look too closely at the expression since
798         -- we're in a loop.
799   and_id <- code newLabelC
800   else_id <- code newLabelC
801   emitCond e1 and_id
802   stmtEC (CmmBranch else_id)
803   code (labelC and_id)
804   emitCond e2 then_id
805   code (labelC else_id)
806
807
808 -- -----------------------------------------------------------------------------
809 -- Table jumps
810
811 -- We use a simplified form of C-- switch statements for now.  A
812 -- switch statement always compiles to a table jump.  Each arm can
813 -- specify a list of values (not ranges), and there can be a single
814 -- default branch.  The range of the table is given either by the
815 -- optional range on the switch (eg. switch [0..7] {...}), or by
816 -- the minimum/maximum values from the branches.
817
818 doSwitch :: Maybe (Int,Int) -> ExtFCode CmmExpr -> [([Int],ExtCode)]
819          -> Maybe ExtCode -> ExtCode
820 doSwitch mb_range scrut arms deflt
821    = do 
822         -- Compile code for the default branch
823         dflt_entry <- 
824                 case deflt of
825                   Nothing -> return Nothing
826                   Just e  -> do b <- forkLabelledCodeEC e; return (Just b)
827
828         -- Compile each case branch
829         table_entries <- mapM emitArm arms
830
831         -- Construct the table
832         let
833             all_entries = concat table_entries
834             ixs = map fst all_entries
835             (min,max) 
836                 | Just (l,u) <- mb_range = (l,u)
837                 | otherwise              = (minimum ixs, maximum ixs)
838
839             entries = elems (accumArray (\_ a -> Just a) dflt_entry (min,max)
840                                 all_entries)
841         expr <- scrut
842         -- ToDo: check for out of range and jump to default if necessary
843         stmtEC (CmmSwitch expr entries)
844    where
845         emitArm :: ([Int],ExtCode) -> ExtFCode [(Int,BlockId)]
846         emitArm (ints,code) = do
847            blockid <- forkLabelledCodeEC code
848            return [ (i,blockid) | i <- ints ]
849
850
851 -- -----------------------------------------------------------------------------
852 -- Putting it all together
853
854 -- The initial environment: we define some constants that the compiler
855 -- knows about here.
856 initEnv :: Env
857 initEnv = listToUFM [
858   ( FSLIT("SIZEOF_StgHeader"), 
859         CmmLit (CmmInt (fromIntegral (fixedHdrSize * wORD_SIZE)) wordRep) ),
860   ( FSLIT("SIZEOF_StgInfoTable"),
861         CmmLit (CmmInt (fromIntegral stdInfoTableSizeB) wordRep) )
862   ]
863
864 parseCmmFile :: DynFlags -> FilePath -> IO (Maybe Cmm)
865 parseCmmFile dflags filename = do
866   showPass dflags "ParseCmm"
867   buf <- hGetStringBuffer filename
868   let
869         init_loc = mkSrcLoc (mkFastString filename) 1 0
870         init_state = (mkPState buf init_loc dflags) { lex_state = [0] }
871                 -- reset the lex_state: the Lexer monad leaves some stuff
872                 -- in there we don't want.
873   case unP cmmParse init_state of
874     PFailed span err -> do printError span err; return Nothing
875     POk _ code -> do
876         cmm <- initC dflags no_module (getCmm (unEC code initEnv [] >> return ()))
877         dumpIfSet_dyn dflags Opt_D_dump_cmm "Cmm" (pprCmms [cmm])
878         return (Just cmm)
879   where
880         no_module = panic "parseCmmFile: no module"
881
882 }