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