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