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(..) )
36 import Literal ( mkMachInt )
40 import DynFlags ( DynFlags, DynFlag(..) )
41 import StaticFlags ( opt_SccProfilingOn )
42 import ErrUtils ( printError, dumpIfSet_dyn, showPass )
43 import StringBuffer ( hGetStringBuffer )
45 import Panic ( panic )
46 import Constants ( wORD_SIZE )
51 #include "HsVersions.h"
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 '!') }
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) }
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) }
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 $$) }
121 %monad { P } { >>= } { return }
122 %lexer { cmmlex } { L _ CmmT_EOF }
124 %tokentype { Located CmmToken }
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--
130 %nonassoc '>=' '>' '<=' '<' '!=' '=='
142 : {- empty -} { return () }
143 | cmmtop cmm { do $1; $2 }
145 cmmtop :: { ExtCode }
149 | 'CLOSURE' '(' NAME ',' NAME lits ')' ';'
150 { do lits <- sequence $6;
151 staticClosure $3 $5 (map getLit lits) }
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.
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
162 cmmdata :: { ExtCode }
163 : 'section' STRING '{' statics '}'
164 { do ss <- sequence $4;
165 code (emitData (section $2) (concat ss)) }
167 statics :: { [ExtFCode [CmmStatic]] }
169 | static statics { $1 : $2 }
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
182 | typenot8 '[' INT ']' ';' { return [CmmUninitialised
183 (machRepByteWidth $1 *
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
193 lits :: { [ExtFCode CmmExpr] }
195 | ',' expr lits { $2 : $3 }
197 cmmproc :: { ExtCode }
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) }
205 { do (info_lbl, info1, info2) <- $1;
206 code (emitInfoTableAndCode info_lbl info1 info2 [] []) }
209 { do stmts <- getCgStmtsEC (loopDecls $3);
210 blks <- code (cgStmtsToBlocks stmts)
211 code (emitProc [] (mkRtsCodeLabelFS $1) [] blks) }
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 }
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 }
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 }
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 }
230 | 'INFO_TABLE_RET' '(' NAME ',' INT ',' INT ',' INT maybe_vec ')'
231 { retInfo $3 $5 $7 $9 $10 }
233 maybe_vec :: { [CmmLit] }
235 | ',' NAME maybe_vec { CmmLabel (mkRtsCodeLabelFS $2) : $3 }
238 : {- empty -} { return () }
239 | decl body { do $1; $2 }
240 | stmt body { do $1; $2 }
243 : type names ';' { mapM_ (newLocal $1) $2 }
244 | 'import' names ';' { return () } -- ignore imports
245 | 'export' names ';' { return () } -- ignore exports
247 names :: { [FastString] }
249 | NAME ',' names { $1 : $3 }
254 | block_id ':' { code (labelC $1) }
257 { do reg <- $1; e <- $3; stmtEC (CmmAssign reg e) }
258 | type '[' expr ']' '=' expr ';'
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 ')' ';'
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 }
282 bool_expr :: { ExtFCode BoolExpr }
284 | expr { do e <- $1; return (BoolTest e) }
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 }
294 -- This is not C-- syntax. What to do?
295 vols :: { Maybe [GlobalReg] }
296 : {- empty -} { Nothing }
297 | '[' globals ']' { Just $2 }
299 globals :: { [GlobalReg] }
301 | GLOBALREG ',' globals { $1 : $3 }
303 maybe_range :: { Maybe (Int,Int) }
304 : '[' INT '..' INT ']' { Just (fromIntegral $2, fromIntegral $4) }
305 | {- empty -} { Nothing }
307 arms :: { [([Int],ExtCode)] }
309 | arm arms { $1 : $2 }
311 arm :: { ([Int],ExtCode) }
312 : 'case' ints ':' '{' body '}' { ($2, $5) }
315 : INT { [ fromIntegral $1 ] }
316 | INT ',' ints { fromIntegral $1 : $3 }
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 }
325 : {- empty -} { nopEC }
326 | 'else' '{' body '}' { $3 }
328 -- we have to write this out longhand so that Happy's precedence rules
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]) } }
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);
359 | type '[' expr ']' { do e <- $3; return (CmmLoad e $1) }
360 | '%' NAME '(' exprs0 ')' {% exprOp $2 $4 }
361 | '(' expr ')' { $2 }
364 -- leaving out the type of a literal gives you the native word size in C--
365 maybe_ty :: { MachRep }
366 : {- empty -} { wordRep }
369 hint_exprs0 :: { [ExtFCode (CmmExpr, MachHint)] }
373 hint_exprs :: { [ExtFCode (CmmExpr, MachHint)] }
375 | hint_expr ',' hint_exprs { $1 : $3 }
377 hint_expr :: { ExtFCode (CmmExpr, MachHint) }
378 : expr { do e <- $1; return (e, inferHint e) }
379 | expr STRING {% do h <- parseHint $2;
381 e <- $1; return (e,h) }
383 exprs0 :: { [ExtFCode CmmExpr] }
387 exprs :: { [ExtFCode CmmExpr] }
389 | expr ',' exprs { $1 : $3 }
391 reg :: { ExtFCode CmmExpr }
392 : NAME { lookupName $1 }
393 | GLOBALREG { return (CmmReg (CmmGlobal $1)) }
395 lreg :: { ExtFCode CmmReg }
396 : NAME { do e <- lookupName $1;
400 other -> pprPanic "CmmParse:" (ftext $1 <> text " not a register") }
401 | GLOBALREG { return (CmmGlobal $1) }
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.
414 typenot8 :: { MachRep }
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
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
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)
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
442 nameToMachOp :: FastString -> P (MachRep -> MachOp)
444 case lookupUFM machOps name of
445 Nothing -> fail ("unknown primitive " ++ unpackFS name)
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
455 mo <- nameToMachOp name
456 return $ mkMachOp mo args_code
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 )
471 -- we understand a subset of C-- primitives:
472 machOps = listToUFM $
473 map (\(x, y) -> (mkFastString x, y)) [
480 ( "quot", MO_S_Quot ),
482 ( "divu", MO_U_Quot ),
483 ( "modu", MO_U_Rem ),
501 ( "fneg", MO_S_Neg ),
508 ( "shrl", MO_U_Shr ),
509 ( "shra", MO_S_Shr ),
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 )
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)
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
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
552 happyError = srcParseFail
554 -- -----------------------------------------------------------------------------
555 -- Statement-level macros
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
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 ),
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)])
606 -- -----------------------------------------------------------------------------
607 -- Our extended FCode monad.
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.
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).
618 type Decls = [(FastString,CmmExpr)]
619 type Env = UniqFM CmmExpr
621 newtype ExtFCode a = EC { unEC :: Env -> Decls -> FCode (Decls, a) }
623 type ExtCode = ExtFCode ()
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'
628 instance Monad ExtFCode where
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) [])
640 getEnv :: ExtFCode Env
641 getEnv = EC $ \e s -> return (s, e)
643 addVarDecl :: FastString -> CmmExpr -> ExtCode
644 addVarDecl var expr = EC $ \e s -> return ((var,expr):s, ())
646 newLocal :: MachRep -> FastString -> ExtCode
647 newLocal ty name = do
649 addVarDecl name (CmmReg (CmmLocal (LocalReg u ty)))
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
658 case lookupUFM env name of
659 Nothing -> CmmLit (CmmLabel (mkRtsCodeLabelFS name))
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)
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)
671 stmtEC stmt = code (stmtC stmt)
672 stmtsEC stmts = code (stmtsC stmts)
673 getCgStmtsEC = code2 getCgStmts'
675 forkLabelledCodeEC ec = do
676 stmts <- getCgStmtsEC ec
677 code (forkCgStmts stmts)
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)
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
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)
700 return (mkRtsInfoLabelFS name, info1, [])
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)
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 [] [] []
720 -> [ExtFCode (CmmReg,MachHint)]
722 -> [ExtFCode (CmmExpr,MachHint)]
723 -> Maybe [GlobalReg] -> P ExtCode
724 foreignCall "C" results_code expr_code args_code vols
726 results <- sequence results_code
728 args <- sequence args_code
729 stmtEC (CmmCall (CmmForeignCall expr CCallConv) results args vols)
730 foreignCall conv _ _ _ _
731 = fail ("unknown calling convention: " ++ conv)
733 doStore :: MachRep -> ExtFCode CmmExpr -> ExtFCode CmmExpr -> ExtCode
734 doStore rep addr_code val_code
735 = do addr <- addr_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
743 | cmmExprRep val /= rep = CmmMachOp (MO_U_Conv rep rep) [val]
745 stmtEC (CmmStore addr coerce_val)
747 -- Return an unboxed tuple.
748 emitRetUT :: [(CgRep,CmmExpr)] -> Code
750 tickyUnboxedTupleReturn (length args) -- TICK
751 (sp, stmts) <- pushUnboxedTuple 0 args
753 when (sp /= 0) $ stmtC (CmmAssign spReg (cmmRegOffW spReg (-sp)))
754 stmtC (CmmJump (entryCode (CmmLoad (cmmRegOffW spReg sp) wordRep)) [])
756 -- -----------------------------------------------------------------------------
757 -- If-then-else and boolean expressions
760 = BoolExpr `BoolAnd` BoolExpr
761 | BoolExpr `BoolOr` BoolExpr
765 -- ToDo: smart constructors which simplify the boolean expression.
767 ifThenElse cond then_part else_part = do
768 then_id <- code newLabelC
769 join_id <- code newLabelC
773 stmtEC (CmmBranch join_id)
774 code (labelC then_id)
776 -- fall through to join
777 code (labelC join_id)
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
789 stmtEC (CmmBranch then_id)
790 code (labelC else_id)
791 emitCond (e1 `BoolOr` e2) then_id = do
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
799 and_id <- code newLabelC
800 else_id <- code newLabelC
802 stmtEC (CmmBranch else_id)
805 code (labelC else_id)
808 -- -----------------------------------------------------------------------------
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.
818 doSwitch :: Maybe (Int,Int) -> ExtFCode CmmExpr -> [([Int],ExtCode)]
819 -> Maybe ExtCode -> ExtCode
820 doSwitch mb_range scrut arms deflt
822 -- Compile code for the default branch
825 Nothing -> return Nothing
826 Just e -> do b <- forkLabelledCodeEC e; return (Just b)
828 -- Compile each case branch
829 table_entries <- mapM emitArm arms
831 -- Construct the table
833 all_entries = concat table_entries
834 ixs = map fst all_entries
836 | Just (l,u) <- mb_range = (l,u)
837 | otherwise = (minimum ixs, maximum ixs)
839 entries = elems (accumArray (\_ a -> Just a) dflt_entry (min,max)
842 -- ToDo: check for out of range and jump to default if necessary
843 stmtEC (CmmSwitch expr entries)
845 emitArm :: ([Int],ExtCode) -> ExtFCode [(Int,BlockId)]
846 emitArm (ints,code) = do
847 blockid <- forkLabelledCodeEC code
848 return [ (i,blockid) | i <- ints ]
851 -- -----------------------------------------------------------------------------
852 -- Putting it all together
854 -- The initial environment: we define some constants that the compiler
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) )
864 parseCmmFile :: DynFlags -> FilePath -> IO (Maybe Cmm)
865 parseCmmFile dflags filename = do
866 showPass dflags "ParseCmm"
867 buf <- hGetStringBuffer filename
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
876 cmm <- initC dflags no_module (getCmm (unEC code initEnv [] >> return ()))
877 dumpIfSet_dyn dflags Opt_D_dump_cmm "Cmm" (pprCmms [cmm])
880 no_module = panic "parseCmmFile: no module"