2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 % $Id: AbsCSyn.lhs,v 1.18 1998/12/02 13:17:16 simonm Exp $
6 \section[AbstractC]{Abstract C: the last stop before machine code}
8 This ``Abstract C'' data type describes the raw Spineless Tagless
9 machine model at a C-ish level; it is ``abstract'' in that it only
10 includes C-like structures that we happen to need. The conversion of
11 programs from @StgSyntax@ (basically a functional language) to
12 @AbstractC@ (basically imperative C) is the heart of code generation.
13 From @AbstractC@, one may convert to real C (for portability) or to
14 raw assembler/machine code.
24 mkAbstractCs, mkAbsCStmts, mkAlgAltsCSwitch,
33 MagicId(..), node, infoptr,
38 #include "HsVersions.h"
40 import {-# SOURCE #-} ClosureInfo ( ClosureInfo )
42 #if ! OMIT_NATIVE_CODEGEN
43 import {-# SOURCE #-} MachMisc
47 import Constants ( mAX_Vanilla_REG, mAX_Float_REG,
48 mAX_Double_REG, spRelToInt )
49 import CostCentre ( CostCentre, CostCentreStack )
50 import Const ( mkMachInt, Literal )
51 import PrimRep ( PrimRep(..) )
52 import PrimOp ( PrimOp )
53 import Unique ( Unique )
54 import StgSyn ( SRT(..) )
55 import BitSet -- for liveness masks
59 @AbstractC@ is a list of Abstract~C statements, but the data structure
60 is tree-ish, for easier and more efficient putting-together.
66 | AbsCStmts AbstractC AbstractC
68 -- and the individual stmts...
71 A note on @CAssign@: In general, the type associated with an assignment
72 is the type of the lhs. However, when the lhs is a pointer to mixed
73 types (e.g. SpB relative), the type of the assignment is the type of
74 the rhs for float types, or the generic StgWord for all other types.
75 (In particular, a CharRep on the rhs is promoted to IntRep when
76 stored in a mixed type location.)
84 CAddrMode -- Put this in the program counter
85 -- eg `CJump (CReg (VanillaReg PtrRep 1))' puts Ret1 in PC
86 -- Enter can be done by:
87 -- CJump (CVal NodeRel zeroOff)
90 CAddrMode -- Fall through into this routine
91 -- (for the benefit of the native code generators)
92 -- Equivalent to CJump in C land
94 | CReturn -- This used to be RetVecRegRel
95 CAddrMode -- Any base address mode
96 ReturnInfo -- How to get the return address from the base address
99 [(Literal, AbstractC)] -- alternatives
100 AbstractC -- default; if there is no real Abstract C in here
101 -- (e.g., all comments; see function "nonemptyAbsC"),
102 -- then that means the default _cannot_ occur.
103 -- If there is only one alternative & no default code,
104 -- then there is no need to check the tag.
106 -- CSwitch m [(tag,code)] AbsCNop == code
108 | CCodeBlock CLabel AbstractC
109 -- A labelled block of code; this "statement" is not
110 -- executed; rather, the labelled code will be hoisted
111 -- out to the top level (out of line) & it can be
114 | CInitHdr -- to initialise the header of a closure (both fixed/var parts)
116 RegRelative -- address of the info ptr
117 CAddrMode -- cost centre to place in closure
118 -- CReg CurCostCentre or CC_HDR(R1.p{-Node-})
121 [CAddrMode] -- Results
123 [CAddrMode] -- Arguments
124 [MagicId] -- Potentially volatile/live registers
125 -- (to save/restore around the call/op)
127 -- INVARIANT: When a PrimOp which can cause GC is used, the
128 -- only live data is tidily on the STG stacks or in the STG
129 -- registers (the code generator ensures this).
131 -- Why this? Because if the arguments were arbitrary
132 -- addressing modes, they might be things like (Hp+6) which
133 -- will get utterly spongled by GC.
135 | CSimultaneous -- Perform simultaneously all the statements
136 AbstractC -- in the nested AbstractC. They are only
137 -- allowed to be CAssigns, COpStmts and AbsCNops, so the
138 -- "simultaneous" part just concerns making
139 -- sure that permutations work.
140 -- For example { a := b, b := a }
141 -- needs to go via (at least one) temporary
143 | CCheck -- heap or stack checks, or both.
144 CCheckMacro -- These might include some code to fill in tags
145 [CAddrMode] -- on the stack, so we can't use CMacroStmt below.
148 | CRetDirect -- Direct return
149 Unique -- for making labels
150 AbstractC -- return code
151 (CLabel,SRT) -- SRT info
152 Liveness -- stack liveness at the return point
154 -- see the notes about these next few; they follow below...
155 | CMacroStmt CStmtMacro [CAddrMode]
156 | CCallProfCtrMacro FAST_STRING [CAddrMode]
157 | CCallProfCCMacro FAST_STRING [CAddrMode]
159 {- The presence of this constructor is a makeshift solution;
160 it being used to work around a gcc-related problem of
161 handling typedefs within statement blocks (or, rather,
162 the inability to do so.)
164 The AbstractC flattener takes care of lifting out these
165 typedefs if needs be (i.e., when generating .hc code and
166 compiling 'foreign import dynamic's)
168 | CCallTypedef PrimOp{-CCallOp-} [CAddrMode] [CAddrMode]
170 -- *** the next three [or so...] are DATA (those above are CODE) ***
173 CLabel -- The (full, not base) label to use for labelling the closure.
175 CAddrMode -- cost centre identifier to place in closure
176 [CAddrMode] -- free vars; ptrs, then non-ptrs.
178 | CSRT CLabel [CLabel] -- SRT declarations: basically an array of
179 -- pointers to static closures.
181 | CBitmap CLabel LivenessMask -- A larger-than-32-bits bitmap.
183 | CClosureInfoAndCode
184 ClosureInfo -- Explains placement and layout of closure
185 AbstractC -- Slow entry point code
187 -- Fast entry point code, if any
188 (CLabel,SRT) -- SRT info
189 String -- Closure description; NB we can't get this
190 -- from ClosureInfo, because the latter refers
191 -- to the *right* hand side of a defn, whereas
192 -- the "description" refers to *left* hand side
194 | CRetVector -- A labelled block of static data
197 (CLabel,SRT) -- SRT info
198 Liveness -- stack liveness at the return point
200 | CCostCentreDecl -- A cost centre *declaration*
201 Bool -- True <=> local => full declaration
202 -- False <=> extern; just say so
205 | CCostCentreStackDecl -- A cost centre stack *declaration*
206 CostCentreStack -- this is the declaration for a
207 -- pre-defined singleton CCS (see
210 | CSplitMarker -- Split into separate object modules here
213 About @CMacroStmt@, etc.: notionally, they all just call some
214 arbitrary C~macro or routine, passing the @CAddrModes@ as arguments.
215 However, we distinguish between various flavours of these things,
216 mostly just to keep things somewhat less wild and wooly.
220 Some {\em essential} bits of the STG execution model are done with C
221 macros. An example is @STK_CHK@, which checks for stack-space
222 overflow. This enumeration type lists all such macros:
225 = ARGS_CHK -- arg satisfaction check
226 | ARGS_CHK_LOAD_NODE -- arg check for top-level functions
227 | UPD_CAF -- update CAF closure with indirection
228 | UPD_BH_UPDATABLE -- eager backholing
229 | UPD_BH_SINGLE_ENTRY -- more eager blackholing
230 | PUSH_UPD_FRAME -- push update frame
231 | PUSH_SEQ_FRAME -- push seq frame
232 | SET_TAG -- set TagReg if it exists
233 | GRAN_FETCH -- for GrAnSim only -- HWL
234 | GRAN_RESCHEDULE -- for GrAnSim only -- HWL
235 | GRAN_FETCH_AND_RESCHEDULE -- for GrAnSim only -- HWL
236 | THREAD_CONTEXT_SWITCH -- for GrAnSim only -- HWL
237 | GRAN_YIELD -- for GrAnSim only -- HWL
241 Heap/Stack checks. There are far too many of these.
246 = HP_CHK_NP -- heap/stack checks when
247 | STK_CHK_NP -- node points to the closure
249 | HP_CHK_SEQ_NP -- for 'seq' style case alternatives
251 | HP_CHK -- heap/stack checks when
252 | STK_CHK -- node doesn't point
254 -- case alternative heap checks:
256 | HP_CHK_NOREGS -- no registers live
257 | HP_CHK_UNPT_R1 -- R1 is boxed/unlifted
258 | HP_CHK_UNBX_R1 -- R1 is unboxed
259 | HP_CHK_F1 -- FloatReg1 (only) is live
260 | HP_CHK_D1 -- DblReg1 (only) is live
261 | HP_CHK_L1 -- LngReg1 (only) is live
262 | HP_CHK_UT_ALT -- unboxed tuple return.
264 | HP_CHK_GEN -- generic heap check
268 \item[@CCallProfCtrMacro@:]
269 The @String@ names a macro that, if \tr{#define}d, will bump one/some
270 of the STG-event profiling counters.
272 \item[@CCallProfCCMacro@:]
273 The @String@ names a macro that, if \tr{#define}d, will perform some
274 cost-centre-profiling-related action.
277 %************************************************************************
279 \subsection[CAddrMode]{C addressing modes}
281 %************************************************************************
285 = CVal RegRelative PrimRep
286 -- On RHS of assign: Contents of Magic[n]
287 -- On LHS of assign: location Magic[n]
288 -- (ie at addr Magic+n)
291 -- On RHS of assign: Address of Magic[n]; ie Magic+n
292 -- n=0 gets the Magic location itself
293 -- (NB: n=0 case superceded by CReg)
294 -- On LHS of assign: only sensible if n=0,
295 -- which gives the magic location itself
296 -- (NB: superceded by CReg)
298 | CReg MagicId -- To replace (CAddr MagicId 0)
300 | CTableEntry -- CVal should be generalized to allow this
303 PrimRep -- For casting
305 | CTemp Unique PrimRep -- Temporary locations
306 -- ``Temporaries'' correspond to local variables in C, and registers in
309 | CLbl CLabel -- Labels in the runtime system, etc.
310 PrimRep -- the kind is so we can generate accurate C decls
312 | CCharLike CAddrMode -- The address of a static char-like closure for
313 -- the specified character. It is guaranteed to be in
316 | CIntLike CAddrMode -- The address of a static int-like closure for the
317 -- specified small integer. It is guaranteed to be in
318 -- the range mIN_INTLIKE..mAX_INTLIKE
320 | CString FAST_STRING -- The address of the null-terminated string
322 | CLitLit FAST_STRING -- completely literal literal: just spit this String
326 | CJoinPoint -- This is used as the amode of a let-no-escape-bound
328 VirtualSpOffset -- Sp value after any volatile free vars
329 -- of the rhs have been saved on stack.
330 -- Just before the code for the thing is jumped to,
331 -- Sp will be set to this value,
332 -- and then any stack-passed args pushed,
333 -- then the code for this thing will be entered
335 !PrimRep -- the kind of the result
336 CExprMacro -- the macro to generate a value
337 [CAddrMode] -- and its arguments
340 Various C macros for values which are dependent on the back-end layout.
346 | ARG_TAG -- stack argument tagging
347 | GET_TAG -- get current constructor tag
352 Convenience functions:
355 mkIntCLit :: Int -> CAddrMode
356 mkIntCLit i = CLit (mkMachInt (toInteger i))
358 mkCCostCentre :: CostCentre -> CAddrMode
359 mkCCostCentre cc = CLbl (mkCC_Label cc) DataPtrRep
361 mkCCostCentreStack :: CostCentreStack -> CAddrMode
362 mkCCostCentreStack ccs = CLbl (mkCCS_Label ccs) DataPtrRep
365 %************************************************************************
367 \subsection[RegRelative]{@RegRelatives@: ???}
369 %************************************************************************
373 = HpRel FAST_INT -- }
374 | SpRel FAST_INT -- }- offsets in StgWords
375 | NodeRel FAST_INT -- }
378 = DirectReturn -- Jump directly, if possible
379 | StaticVectoredReturn Int -- Fixed tag, starting at zero
380 | DynamicVectoredReturn CAddrMode -- Dynamic tag given by amode, starting at zero
382 hpRel :: VirtualHeapOffset -- virtual offset of Hp
383 -> VirtualHeapOffset -- virtual offset of The Thing
384 -> RegRelative -- integer offset
385 hpRel IBOX(hp) IBOX(off) = HpRel (hp _SUB_ off)
387 spRel :: VirtualSpOffset -- virtual offset of Sp
388 -> VirtualSpOffset -- virtual offset of The Thing
389 -> RegRelative -- integer offset
390 spRel sp off = SpRel (case spRelToInt sp off of { IBOX(i) -> i })
392 nodeRel :: VirtualHeapOffset
394 nodeRel IBOX(off) = NodeRel off
398 %************************************************************************
400 \subsection[RegRelative]{@RegRelatives@: ???}
402 %************************************************************************
404 We represent liveness bitmaps as a BitSet (whose internal
405 representation really is a bitmap). These are pinned onto case return
406 vectors to indicate the state of the stack for the garbage collector.
409 type LivenessMask = [BitSet]
411 data Liveness = LvSmall BitSet
415 %************************************************************************
417 \subsection[HeapOffset]{@Heap Offsets@}
419 %************************************************************************
421 This used to be a grotesquely complicated datatype in an attempt to
422 hide the details of header sizes from the compiler itself. Now these
423 constants are imported from the RTS, and we deal in real Ints.
426 type HeapOffset = Int -- ToDo: remove
428 type VirtualHeapOffset = HeapOffset
429 type VirtualSpOffset = Int
431 type HpRelOffset = HeapOffset
432 type SpRelOffset = Int
435 %************************************************************************
437 \subsection[MagicId]{@MagicIds@: registers and such}
439 %************************************************************************
443 = BaseReg -- mentioned only in nativeGen
445 -- Argument and return registers
446 | VanillaReg -- pointers, unboxed ints and chars
448 FAST_INT -- its number (1 .. mAX_Vanilla_REG)
450 | FloatReg -- single-precision floating-point registers
451 FAST_INT -- its number (1 .. mAX_Float_REG)
453 | DoubleReg -- double-precision floating-point registers
454 FAST_INT -- its number (1 .. mAX_Double_REG)
457 | Sp -- Stack ptr; points to last occupied stack location.
458 | Su -- Stack update frame pointer
459 | SpLim -- Stack limit
460 | Hp -- Heap ptr; points to last occupied heap location.
461 | HpLim -- Heap limit register
462 | CurCostCentre -- current cost centre register.
463 | VoidReg -- see "VoidPrim" type; just a placeholder;
464 -- no actual register
465 | LongReg -- long int registers (64-bit, really)
466 PrimRep -- Int64Rep or Word64Rep
467 FAST_INT -- its number (1 .. mAX_Long_REG)
470 node = VanillaReg PtrRep ILIT(1) -- A convenient alias for Node
471 tagreg = VanillaReg WordRep ILIT(2) -- A convenient alias for TagReg
475 We need magical @Eq@ because @VanillaReg@s come in multiple flavors.
478 instance Eq MagicId where
479 reg1 == reg2 = tag reg1 _EQ_ tag reg2
481 tag BaseReg = (ILIT(0) :: FAST_INT)
487 tag CurCostCentre = ILIT(6)
488 tag VoidReg = ILIT(7)
490 tag (VanillaReg _ i) = ILIT(8) _ADD_ i
492 tag (FloatReg i) = ILIT(8) _ADD_ maxv _ADD_ i
493 tag (DoubleReg i) = ILIT(8) _ADD_ maxv _ADD_ maxf _ADD_ i
494 tag (LongReg _ i) = ILIT(8) _ADD_ maxv _ADD_ maxf _ADD_ maxd _ADD_ i
496 maxv = case mAX_Vanilla_REG of { IBOX(x) -> x }
497 maxf = case mAX_Float_REG of { IBOX(x) -> x }
498 maxd = case mAX_Double_REG of { IBOX(x) -> x }
501 Returns True for any register that {\em potentially} dies across
502 C calls (or anything near equivalent). We just say @True@ and
503 let the (machine-specific) registering macros sort things out...
506 isVolatileReg :: MagicId -> Bool
507 isVolatileReg any = True