1 -- -----------------------------------------------------------------------------
3 -- (c) The University of Glasgow 1993-2004
5 -- This is the top-level module in the native code generator.
7 -- -----------------------------------------------------------------------------
10 module AsmCodeGen ( nativeCodeGen ) where
12 #include "HsVersions.h"
20 import RegAllocInfo ( jumpDests )
22 import PositionIndependentCode
25 import PprCmm ( pprStmt, pprCmms )
27 import CLabel ( CLabel, mkSplitMarkerLabel, mkAsmTempLabel )
28 #if powerpc_TARGET_ARCH
29 import CLabel ( mkRtsCodeLabel )
33 import Unique ( Unique, getUnique )
36 import List ( groupBy, sortBy )
37 import CLabel ( pprCLabel )
38 import ErrUtils ( dumpIfSet_dyn )
39 import DynFlags ( DynFlags, DynFlag(..), dopt )
40 import StaticFlags ( opt_Static, opt_PIC )
43 import qualified Pretty
51 import List ( intersperse )
60 The native-code generator has machine-independent and
61 machine-dependent modules.
63 This module ("AsmCodeGen") is the top-level machine-independent
64 module. Before entering machine-dependent land, we do some
65 machine-independent optimisations (defined below) on the
68 We convert to the machine-specific 'Instr' datatype with
69 'cmmCodeGen', assuming an infinite supply of registers. We then use
70 a machine-independent register allocator ('regAlloc') to rejoin
71 reality. Obviously, 'regAlloc' has machine-specific helper
72 functions (see about "RegAllocInfo" below).
74 Finally, we order the basic blocks of the function so as to minimise
75 the number of jumps between blocks, by utilising fallthrough wherever
78 The machine-dependent bits break down as follows:
80 * ["MachRegs"] Everything about the target platform's machine
81 registers (and immediate operands, and addresses, which tend to
82 intermingle/interact with registers).
84 * ["MachInstrs"] Includes the 'Instr' datatype (possibly should
85 have a module of its own), plus a miscellany of other things
86 (e.g., 'targetDoubleSize', 'smStablePtrTable', ...)
88 * ["MachCodeGen"] is where 'Cmm' stuff turns into
91 * ["PprMach"] 'pprInstr' turns an 'Instr' into text (well, really
94 * ["RegAllocInfo"] In the register allocator, we manipulate
95 'MRegsState's, which are 'BitSet's, one bit per machine register.
96 When we want to say something about a specific machine register
97 (e.g., ``it gets clobbered by this instruction''), we set/unset
98 its bit. Obviously, we do this 'BitSet' thing for efficiency
101 The 'RegAllocInfo' module collects together the machine-specific
102 info needed to do register allocation.
104 * ["RegisterAlloc"] The (machine-independent) register allocator.
107 -- -----------------------------------------------------------------------------
108 -- Top-level of the native codegen
110 -- NB. We *lazilly* compile each block of code for space reasons.
112 nativeCodeGen :: DynFlags -> [Cmm] -> UniqSupply -> IO Pretty.Doc
113 nativeCodeGen dflags cmms us
114 = let (res, _) = initUs us $
115 cgCmm (concat (map add_split cmms))
117 cgCmm :: [CmmTop] -> UniqSM (Cmm, Pretty.Doc, [CLabel])
119 lazyMapUs (cmmNativeGen dflags) tops `thenUs` \ results ->
120 case unzip3 results of { (cmms,docs,imps) ->
121 returnUs (Cmm cmms, my_vcat docs, concat imps)
124 case res of { (ppr_cmms, insn_sdoc, imports) -> do
125 dumpIfSet_dyn dflags Opt_D_dump_opt_cmm "Optimised Cmm" (pprCmms [ppr_cmms])
126 return (insn_sdoc Pretty.$$ dyld_stubs imports
127 #if HAVE_SUBSECTIONS_VIA_SYMBOLS
128 -- On recent versions of Darwin, the linker supports
129 -- dead-stripping of code and data on a per-symbol basis.
130 -- There's a hack to make this work in PprMach.pprNatCmmTop.
131 Pretty.$$ Pretty.text ".subsections_via_symbols"
139 | dopt Opt_SplitObjs dflags = split_marker : tops
142 split_marker = CmmProc [] mkSplitMarkerLabel [] []
144 -- Generate "symbol stubs" for all external symbols that might
145 -- come from a dynamic library.
146 {- dyld_stubs imps = Pretty.vcat $ map pprDyldSymbolStub $
147 map head $ group $ sort imps-}
149 -- (Hack) sometimes two Labels pretty-print the same, but have
150 -- different uniques; so we compare their text versions...
152 | needImportedSymbols
154 (pprGotDeclaration :) $
155 map (pprImportedSymbol . fst . head) $
156 groupBy (\(_,a) (_,b) -> a == b) $
157 sortBy (\(_,a) (_,b) -> compare a b) $
163 where doPpr lbl = (lbl, Pretty.render $ pprCLabel lbl astyle)
164 astyle = mkCodeStyle AsmStyle
167 my_vcat sds = Pretty.vcat sds
169 my_vcat sds = Pretty.vcat (
172 Pretty.$$ Pretty.ptext SLIT("# ___ncg_debug_marker")
173 Pretty.$$ Pretty.char ' '
180 -- Complete native code generation phase for a single top-level chunk
183 cmmNativeGen :: DynFlags -> CmmTop -> UniqSM (CmmTop, Pretty.Doc, [CLabel])
184 cmmNativeGen dflags cmm
185 = {-# SCC "fixAssigns" #-}
186 fixAssignsTop cmm `thenUs` \ fixed_cmm ->
187 {-# SCC "genericOpt" #-}
188 cmmToCmm fixed_cmm `bind` \ (cmm, imports) ->
189 (if dopt Opt_D_dump_opt_cmm dflags -- space leak avoidance
191 else CmmData Text []) `bind` \ ppr_cmm ->
192 {-# SCC "genMachCode" #-}
193 genMachCode cmm `thenUs` \ (pre_regalloc, lastMinuteImports) ->
194 {-# SCC "regAlloc" #-}
195 map regAlloc pre_regalloc `bind` \ with_regs ->
196 {-# SCC "sequenceBlocks" #-}
197 map sequenceTop with_regs `bind` \ sequenced ->
198 {-# SCC "x86fp_kludge" #-}
199 map x86fp_kludge sequenced `bind` \ final_mach_code ->
201 Pretty.vcat (map pprNatCmmTop final_mach_code) `bind` \ final_sdoc ->
203 returnUs (ppr_cmm, final_sdoc Pretty.$$ Pretty.text "", lastMinuteImports ++ imports)
205 x86fp_kludge :: NatCmmTop -> NatCmmTop
206 x86fp_kludge top@(CmmData _ _) = top
208 x86fp_kludge top@(CmmProc info lbl params code) =
209 CmmProc info lbl params (map bb_i386_insert_ffrees code)
211 bb_i386_insert_ffrees (BasicBlock id instrs) =
212 BasicBlock id (i386_insert_ffrees instrs)
214 x86fp_kludge top = top
217 -- -----------------------------------------------------------------------------
218 -- Sequencing the basic blocks
220 -- Cmm BasicBlocks are self-contained entities: they always end in a
221 -- jump, either non-local or to another basic block in the same proc.
222 -- In this phase, we attempt to place the basic blocks in a sequence
223 -- such that as many of the local jumps as possible turn into
226 sequenceTop :: NatCmmTop -> NatCmmTop
227 sequenceTop top@(CmmData _ _) = top
228 sequenceTop (CmmProc info lbl params blocks) =
229 CmmProc info lbl params (sequenceBlocks blocks)
231 -- The algorithm is very simple (and stupid): we make a graph out of
232 -- the blocks where there is an edge from one block to another iff the
233 -- first block ends by jumping to the second. Then we topologically
234 -- sort this graph. Then traverse the list: for each block, we first
235 -- output the block, then if it has an out edge, we move the
236 -- destination of the out edge to the front of the list, and continue.
238 sequenceBlocks :: [NatBasicBlock] -> [NatBasicBlock]
239 sequenceBlocks [] = []
240 sequenceBlocks (entry:blocks) =
241 seqBlocks (mkNode entry : reverse (flattenSCCs (sccBlocks blocks)))
242 -- the first block is the entry point ==> it must remain at the start.
244 sccBlocks :: [NatBasicBlock] -> [SCC (NatBasicBlock,Unique,[Unique])]
245 sccBlocks blocks = stronglyConnCompR (map mkNode blocks)
247 getOutEdges :: [Instr] -> [Unique]
248 getOutEdges instrs = case jumpDests (last instrs) [] of
249 [one] -> [getUnique one]
251 -- we're only interested in the last instruction of
252 -- the block, and only if it has a single destination.
254 mkNode block@(BasicBlock id instrs) = (block, getUnique id, getOutEdges instrs)
257 seqBlocks ((block,_,[]) : rest)
258 = block : seqBlocks rest
259 seqBlocks ((block@(BasicBlock id instrs),_,[next]) : rest)
260 | can_fallthrough = BasicBlock id (init instrs) : seqBlocks rest'
261 | otherwise = block : seqBlocks rest'
263 (can_fallthrough, rest') = reorder next [] rest
264 -- TODO: we should do a better job for cycles; try to maximise the
265 -- fallthroughs within a loop.
266 seqBlocks _ = panic "AsmCodegen:seqBlocks"
268 reorder id accum [] = (False, reverse accum)
269 reorder id accum (b@(block,id',out) : rest)
270 | id == id' = (True, (block,id,out) : reverse accum ++ rest)
271 | otherwise = reorder id (b:accum) rest
273 -- -----------------------------------------------------------------------------
274 -- Instruction selection
276 -- Native code instruction selection for a chunk of stix code. For
277 -- this part of the computation, we switch from the UniqSM monad to
278 -- the NatM monad. The latter carries not only a Unique, but also an
279 -- Int denoting the current C stack pointer offset in the generated
280 -- code; this is needed for creating correct spill offsets on
281 -- architectures which don't offer, or for which it would be
282 -- prohibitively expensive to employ, a frame pointer register. Viz,
285 -- The offset is measured in bytes, and indicates the difference
286 -- between the current (simulated) C stack-ptr and the value it was at
287 -- the beginning of the block. For stacks which grow down, this value
288 -- should be either zero or negative.
290 -- Switching between the two monads whilst carrying along the same
291 -- Unique supply breaks abstraction. Is that bad?
293 genMachCode :: CmmTop -> UniqSM ([NatCmmTop], [CLabel])
295 genMachCode cmm_top initial_us
296 = let initial_st = mkNatM_State initial_us 0
297 (new_tops, final_st) = initNat initial_st (cmmTopCodeGen cmm_top)
298 final_us = natm_us final_st
299 final_delta = natm_delta final_st
300 final_imports = natm_imports final_st
303 then ((new_tops, final_imports), final_us)
304 else pprPanic "genMachCode: nonzero final delta"
307 -- -----------------------------------------------------------------------------
308 -- Fixup assignments to global registers so that they assign to
309 -- locations within the RegTable, if appropriate.
311 -- Note that we currently don't fixup reads here: they're done by
312 -- the generic optimiser below, to avoid having two separate passes
315 fixAssignsTop :: CmmTop -> UniqSM CmmTop
316 fixAssignsTop top@(CmmData _ _) = returnUs top
317 fixAssignsTop (CmmProc info lbl params blocks) =
318 mapUs fixAssignsBlock blocks `thenUs` \ blocks' ->
319 returnUs (CmmProc info lbl params blocks')
321 fixAssignsBlock :: CmmBasicBlock -> UniqSM CmmBasicBlock
322 fixAssignsBlock (BasicBlock id stmts) =
323 fixAssigns stmts `thenUs` \ stmts' ->
324 returnUs (BasicBlock id stmts')
326 fixAssigns :: [CmmStmt] -> UniqSM [CmmStmt]
328 mapUs fixAssign stmts `thenUs` \ stmtss ->
329 returnUs (concat stmtss)
331 fixAssign :: CmmStmt -> UniqSM [CmmStmt]
332 fixAssign (CmmAssign (CmmGlobal BaseReg) src)
333 = panic "cmmStmtConFold: assignment to BaseReg";
335 fixAssign (CmmAssign (CmmGlobal reg) src)
336 | Left realreg <- reg_or_addr
337 = returnUs [CmmAssign (CmmGlobal reg) src]
338 | Right baseRegAddr <- reg_or_addr
339 = returnUs [CmmStore baseRegAddr src]
340 -- Replace register leaves with appropriate StixTrees for
341 -- the given target. GlobalRegs which map to a reg on this
342 -- arch are left unchanged. Assigning to BaseReg is always
343 -- illegal, so we check for that.
345 reg_or_addr = get_GlobalReg_reg_or_addr reg
347 fixAssign (CmmCall target results args vols)
348 = mapAndUnzipUs fixResult results `thenUs` \ (results',stores) ->
349 returnUs (CmmCall target results' args vols : concat stores)
351 fixResult g@(CmmGlobal reg,hint) =
352 case get_GlobalReg_reg_or_addr reg of
353 Left realreg -> returnUs (g, [])
355 getUniqueUs `thenUs` \ uq ->
356 let local = CmmLocal (LocalReg uq (globalRegRep reg)) in
357 returnUs ((local,hint),
358 [CmmStore baseRegAddr (CmmReg local)])
362 fixAssign other_stmt = returnUs [other_stmt]
364 -- -----------------------------------------------------------------------------
365 -- Generic Cmm optimiser
371 (b) Simple inlining: a temporary which is assigned to and then
372 used, once, can be shorted.
373 (c) Replacement of references to GlobalRegs which do not have
374 machine registers by the appropriate memory load (eg.
375 Hp ==> *(BaseReg + 34) ).
376 (d) Position independent code and dynamic linking
377 (i) introduce the appropriate indirections
378 and position independent refs
379 (ii) compile a list of imported symbols
381 Ideas for other things we could do (ToDo):
383 - shortcut jumps-to-jumps
384 - eliminate dead code blocks
385 - simple CSE: if an expr is assigned to a temp, then replace later occs of
386 that expr with the temp, until the expr is no longer valid (can push through
387 temp assignments, and certain assigns to mem...)
390 cmmToCmm :: CmmTop -> (CmmTop, [CLabel])
391 cmmToCmm top@(CmmData _ _) = (top, [])
392 cmmToCmm (CmmProc info lbl params blocks) = runCmmOpt $ do
393 blocks' <- mapM cmmBlockConFold (cmmPeep blocks)
394 return $ CmmProc info lbl params blocks'
396 newtype CmmOptM a = CmmOptM ([CLabel] -> (# a, [CLabel] #))
398 instance Monad CmmOptM where
399 return x = CmmOptM $ \imports -> (# x,imports #)
401 CmmOptM $ \imports ->
405 CmmOptM g' -> g' imports'
407 addImportCmmOpt :: CLabel -> CmmOptM ()
408 addImportCmmOpt lbl = CmmOptM $ \imports -> (# (), lbl:imports #)
410 runCmmOpt :: CmmOptM a -> (a, [CLabel])
411 runCmmOpt (CmmOptM f) = case f [] of
412 (# result, imports #) -> (result, imports)
414 cmmBlockConFold :: CmmBasicBlock -> CmmOptM CmmBasicBlock
415 cmmBlockConFold (BasicBlock id stmts) = do
416 stmts' <- mapM cmmStmtConFold stmts
417 return $ BasicBlock id stmts'
422 -> do src' <- cmmExprConFold False src
423 return $ case src' of
424 CmmReg reg' | reg == reg' -> CmmNop
425 new_src -> CmmAssign reg new_src
428 -> do addr' <- cmmExprConFold False addr
429 src' <- cmmExprConFold False src
430 return $ CmmStore addr' src'
433 -> do addr' <- cmmExprConFold True addr
434 return $ CmmJump addr' regs
436 CmmCall target regs args vols
437 -> do target' <- case target of
438 CmmForeignCall e conv -> do
439 e' <- cmmExprConFold True e
440 return $ CmmForeignCall e' conv
441 other -> return other
442 args' <- mapM (\(arg, hint) -> do
443 arg' <- cmmExprConFold False arg
444 return (arg', hint)) args
445 return $ CmmCall target' regs args' vols
447 CmmCondBranch test dest
448 -> do test' <- cmmExprConFold False test
449 return $ case test' of
450 CmmLit (CmmInt 0 _) ->
451 CmmComment (mkFastString ("deleted: " ++
452 showSDoc (pprStmt stmt)))
454 CmmLit (CmmInt n _) -> CmmBranch dest
455 other -> CmmCondBranch test' dest
458 -> do expr' <- cmmExprConFold False expr
459 return $ CmmSwitch expr' ids
465 cmmExprConFold isJumpTarget expr
468 -> do addr' <- cmmExprConFold False addr
469 return $ CmmLoad addr' rep
472 -- For MachOps, we first optimize the children, and then we try
473 -- our hand at some constant-folding.
474 -> do args' <- mapM (cmmExprConFold False) args
475 return $ cmmMachOpFold mop args'
477 CmmLit (CmmLabel lbl)
478 -> cmmMakeDynamicReference addImportCmmOpt isJumpTarget lbl
479 CmmLit (CmmLabelOff lbl off)
480 -> do dynRef <- cmmMakeDynamicReference addImportCmmOpt isJumpTarget lbl
481 return $ cmmMachOpFold (MO_Add wordRep) [
483 (CmmLit $ CmmInt (fromIntegral off) wordRep)
486 #if powerpc_TARGET_ARCH
487 -- On powerpc (non-PIC), it's easier to jump directly to a label than
488 -- to use the register table, so we replace these registers
489 -- with the corresponding labels:
490 CmmReg (CmmGlobal GCEnter1)
492 -> cmmExprConFold isJumpTarget $
493 CmmLit (CmmLabel (mkRtsCodeLabel SLIT( "__stg_gc_enter_1")))
494 CmmReg (CmmGlobal GCFun)
496 -> cmmExprConFold isJumpTarget $
497 CmmLit (CmmLabel (mkRtsCodeLabel SLIT( "__stg_gc_fun")))
500 CmmReg (CmmGlobal mid)
501 -- Replace register leaves with appropriate StixTrees for
502 -- the given target. MagicIds which map to a reg on this
503 -- arch are left unchanged. For the rest, BaseReg is taken
504 -- to mean the address of the reg table in MainCapability,
505 -- and for all others we generate an indirection to its
506 -- location in the register table.
507 -> case get_GlobalReg_reg_or_addr mid of
508 Left realreg -> return expr
511 BaseReg -> cmmExprConFold False baseRegAddr
512 other -> cmmExprConFold False (CmmLoad baseRegAddr
514 -- eliminate zero offsets
516 -> cmmExprConFold False (CmmReg reg)
518 CmmRegOff (CmmGlobal mid) offset
519 -- RegOf leaves are just a shorthand form. If the reg maps
520 -- to a real reg, we keep the shorthand, otherwise, we just
521 -- expand it and defer to the above code.
522 -> case get_GlobalReg_reg_or_addr mid of
523 Left realreg -> return expr
525 -> cmmExprConFold False (CmmMachOp (MO_Add wordRep) [
526 CmmReg (CmmGlobal mid),
527 CmmLit (CmmInt (fromIntegral offset)
533 -- -----------------------------------------------------------------------------
534 -- MachOp constant folder
536 -- Now, try to constant-fold the MachOps. The arguments have already
537 -- been optimized and folded.
540 :: MachOp -- The operation from an CmmMachOp
541 -> [CmmExpr] -- The optimized arguments
544 cmmMachOpFold op arg@[CmmLit (CmmInt x rep)]
546 MO_S_Neg r -> CmmLit (CmmInt (-x) rep)
547 MO_Not r -> CmmLit (CmmInt (complement x) rep)
549 -- these are interesting: we must first narrow to the
550 -- "from" type, in order to truncate to the correct size.
551 -- The final narrow/widen to the destination type
552 -- is implicit in the CmmLit.
554 | isFloatingRep to -> CmmLit (CmmFloat (fromInteger x) to)
555 | otherwise -> CmmLit (CmmInt (narrowS from x) to)
556 MO_U_Conv from to -> CmmLit (CmmInt (narrowU from x) to)
558 _ -> panic "cmmMachOpFold: unknown unary op"
561 -- Eliminate conversion NOPs
562 cmmMachOpFold (MO_S_Conv rep1 rep2) [x] | rep1 == rep2 = x
563 cmmMachOpFold (MO_U_Conv rep1 rep2) [x] | rep1 == rep2 = x
565 -- Eliminate nested conversions where possible
566 cmmMachOpFold conv_outer args@[CmmMachOp conv_inner [x]]
567 | Just (rep1,rep2,signed1) <- isIntConversion conv_inner,
568 Just (_, rep3,signed2) <- isIntConversion conv_outer
570 -- widen then narrow to the same size is a nop
571 _ | rep1 < rep2 && rep1 == rep3 -> x
572 -- Widen then narrow to different size: collapse to single conversion
573 -- but remember to use the signedness from the widening, just in case
574 -- the final conversion is a widen.
575 | rep1 < rep2 && rep2 > rep3 ->
576 cmmMachOpFold (intconv signed1 rep1 rep3) [x]
577 -- Nested widenings: collapse if the signedness is the same
578 | rep1 < rep2 && rep2 < rep3 && signed1 == signed2 ->
579 cmmMachOpFold (intconv signed1 rep1 rep3) [x]
580 -- Nested narrowings: collapse
581 | rep1 > rep2 && rep2 > rep3 ->
582 cmmMachOpFold (MO_U_Conv rep1 rep3) [x]
584 CmmMachOp conv_outer args
586 isIntConversion (MO_U_Conv rep1 rep2)
587 | not (isFloatingRep rep1) && not (isFloatingRep rep2)
588 = Just (rep1,rep2,False)
589 isIntConversion (MO_S_Conv rep1 rep2)
590 | not (isFloatingRep rep1) && not (isFloatingRep rep2)
591 = Just (rep1,rep2,True)
592 isIntConversion _ = Nothing
594 intconv True = MO_S_Conv
595 intconv False = MO_U_Conv
597 -- ToDo: a narrow of a load can be collapsed into a narrow load, right?
598 -- but what if the architecture only supports word-sized loads, should
599 -- we do the transformation anyway?
601 cmmMachOpFold mop args@[CmmLit (CmmInt x xrep), CmmLit (CmmInt y _)]
603 -- for comparisons: don't forget to narrow the arguments before
604 -- comparing, since they might be out of range.
605 MO_Eq r -> CmmLit (CmmInt (if x_u == y_u then 1 else 0) wordRep)
606 MO_Ne r -> CmmLit (CmmInt (if x_u /= y_u then 1 else 0) wordRep)
608 MO_U_Gt r -> CmmLit (CmmInt (if x_u > y_u then 1 else 0) wordRep)
609 MO_U_Ge r -> CmmLit (CmmInt (if x_u >= y_u then 1 else 0) wordRep)
610 MO_U_Lt r -> CmmLit (CmmInt (if x_u < y_u then 1 else 0) wordRep)
611 MO_U_Le r -> CmmLit (CmmInt (if x_u <= y_u then 1 else 0) wordRep)
613 MO_S_Gt r -> CmmLit (CmmInt (if x_s > y_s then 1 else 0) wordRep)
614 MO_S_Ge r -> CmmLit (CmmInt (if x_s >= y_s then 1 else 0) wordRep)
615 MO_S_Lt r -> CmmLit (CmmInt (if x_s < y_s then 1 else 0) wordRep)
616 MO_S_Le r -> CmmLit (CmmInt (if x_s <= y_s then 1 else 0) wordRep)
618 MO_Add r -> CmmLit (CmmInt (x + y) r)
619 MO_Sub r -> CmmLit (CmmInt (x - y) r)
620 MO_Mul r -> CmmLit (CmmInt (x * y) r)
621 MO_S_Quot r | y /= 0 -> CmmLit (CmmInt (x `quot` y) r)
622 MO_S_Rem r | y /= 0 -> CmmLit (CmmInt (x `rem` y) r)
624 MO_And r -> CmmLit (CmmInt (x .&. y) r)
625 MO_Or r -> CmmLit (CmmInt (x .|. y) r)
626 MO_Xor r -> CmmLit (CmmInt (x `xor` y) r)
628 MO_Shl r -> CmmLit (CmmInt (x `shiftL` fromIntegral y) r)
629 MO_U_Shr r -> CmmLit (CmmInt (x_u `shiftR` fromIntegral y) r)
630 MO_S_Shr r -> CmmLit (CmmInt (x `shiftR` fromIntegral y) r)
632 other -> CmmMachOp mop args
641 -- When possible, shift the constants to the right-hand side, so that we
642 -- can match for strength reductions. Note that the code generator will
643 -- also assume that constants have been shifted to the right when
646 cmmMachOpFold op [x@(CmmLit _), y]
647 | not (isLit y) && isCommutableMachOp op
648 = cmmMachOpFold op [y, x]
650 -- Turn (a+b)+c into a+(b+c) where possible. Because literals are
651 -- moved to the right, it is more likely that we will find
652 -- opportunities for constant folding when the expression is
655 -- ToDo: this appears to introduce a quadratic behaviour due to the
656 -- nested cmmMachOpFold. Can we fix this?
658 -- Why do we check isLit arg1? If arg1 is a lit, it means that arg2
659 -- is also a lit (otherwise arg1 would be on the right). If we
660 -- put arg1 on the left of the rearranged expression, we'll get into a
661 -- loop: (x1+x2)+x3 => x1+(x2+x3) => (x2+x3)+x1 => x2+(x3+x1) ...
663 cmmMachOpFold mop1 [CmmMachOp mop2 [arg1,arg2], arg3]
664 | mop1 == mop2 && isAssociativeMachOp mop1 && not (isLit arg1)
665 = cmmMachOpFold mop1 [arg1, cmmMachOpFold mop2 [arg2,arg3]]
667 -- Make a RegOff if we can
668 cmmMachOpFold (MO_Add _) [CmmReg reg, CmmLit (CmmInt n rep)]
669 = CmmRegOff reg (fromIntegral (narrowS rep n))
670 cmmMachOpFold (MO_Add _) [CmmRegOff reg off, CmmLit (CmmInt n rep)]
671 = CmmRegOff reg (off + fromIntegral (narrowS rep n))
672 cmmMachOpFold (MO_Sub _) [CmmReg reg, CmmLit (CmmInt n rep)]
673 = CmmRegOff reg (- fromIntegral (narrowS rep n))
674 cmmMachOpFold (MO_Sub _) [CmmRegOff reg off, CmmLit (CmmInt n rep)]
675 = CmmRegOff reg (off - fromIntegral (narrowS rep n))
677 -- Fold label(+/-)offset into a CmmLit where possible
679 cmmMachOpFold (MO_Add _) [CmmLit (CmmLabel lbl), CmmLit (CmmInt i rep)]
680 = CmmLit (CmmLabelOff lbl (fromIntegral (narrowU rep i)))
681 cmmMachOpFold (MO_Add _) [CmmLit (CmmInt i rep), CmmLit (CmmLabel lbl)]
682 = CmmLit (CmmLabelOff lbl (fromIntegral (narrowU rep i)))
683 cmmMachOpFold (MO_Sub _) [CmmLit (CmmLabel lbl), CmmLit (CmmInt i rep)]
684 = CmmLit (CmmLabelOff lbl (fromIntegral (negate (narrowU rep i))))
686 -- We can often do something with constants of 0 and 1 ...
688 cmmMachOpFold mop args@[x, y@(CmmLit (CmmInt 0 _))]
699 MO_Ne r | isComparisonExpr x -> x
700 MO_Eq r | Just x' <- maybeInvertConditionalExpr x -> x'
701 MO_U_Gt r | isComparisonExpr x -> x
702 MO_S_Gt r | isComparisonExpr x -> x
703 MO_U_Lt r | isComparisonExpr x -> CmmLit (CmmInt 0 wordRep)
704 MO_S_Lt r | isComparisonExpr x -> CmmLit (CmmInt 0 wordRep)
705 MO_U_Ge r | isComparisonExpr x -> CmmLit (CmmInt 1 wordRep)
706 MO_S_Ge r | isComparisonExpr x -> CmmLit (CmmInt 1 wordRep)
707 MO_U_Le r | Just x' <- maybeInvertConditionalExpr x -> x'
708 MO_S_Le r | Just x' <- maybeInvertConditionalExpr x -> x'
709 other -> CmmMachOp mop args
711 cmmMachOpFold mop args@[x, y@(CmmLit (CmmInt 1 rep))]
716 MO_S_Rem r -> CmmLit (CmmInt 0 rep)
717 MO_U_Rem r -> CmmLit (CmmInt 0 rep)
718 MO_Ne r | Just x' <- maybeInvertConditionalExpr x -> x'
719 MO_Eq r | isComparisonExpr x -> x
720 MO_U_Lt r | Just x' <- maybeInvertConditionalExpr x -> x'
721 MO_S_Lt r | Just x' <- maybeInvertConditionalExpr x -> x'
722 MO_U_Gt r | isComparisonExpr x -> CmmLit (CmmInt 0 wordRep)
723 MO_S_Gt r | isComparisonExpr x -> CmmLit (CmmInt 0 wordRep)
724 MO_U_Le r | isComparisonExpr x -> CmmLit (CmmInt 1 wordRep)
725 MO_S_Le r | isComparisonExpr x -> CmmLit (CmmInt 1 wordRep)
726 MO_U_Ge r | isComparisonExpr x -> x
727 MO_S_Ge r | isComparisonExpr x -> x
728 other -> CmmMachOp mop args
730 -- Now look for multiplication/division by powers of 2 (integers).
732 cmmMachOpFold mop args@[x, y@(CmmLit (CmmInt n _))]
735 -> case exactLog2 n of
737 Just p -> CmmMachOp (MO_Shl rep) [x, CmmLit (CmmInt p rep)]
739 -> case exactLog2 n of
741 Just p -> CmmMachOp (MO_S_Shr rep) [x, CmmLit (CmmInt p rep)]
745 unchanged = CmmMachOp mop args
747 -- Anything else is just too hard.
749 cmmMachOpFold mop args = CmmMachOp mop args
751 -- -----------------------------------------------------------------------------
754 -- This algorithm for determining the $\log_2$ of exact powers of 2 comes
755 -- from GCC. It requires bit manipulation primitives, and we use GHC
756 -- extensions. Tough.
758 -- Used to be in MachInstrs --SDM.
759 -- ToDo: remove use of unboxery --SDM.
764 exactLog2 :: Integer -> Maybe Integer
766 = if (x <= 0 || x >= 2147483648) then
769 case iUnbox (fromInteger x) of { x# ->
770 if (w2i ((i2w x#) `and#` (i2w (0# -# x#))) /=# x#) then
773 Just (toInteger (iBox (pow2 x#)))
776 pow2 x# | x# ==# 1# = 0#
777 | otherwise = 1# +# pow2 (w2i (i2w x# `shiftRL#` 1#))
780 -- -----------------------------------------------------------------------------
781 -- widening / narrowing
783 narrowU :: MachRep -> Integer -> Integer
784 narrowU I8 x = fromIntegral (fromIntegral x :: Word8)
785 narrowU I16 x = fromIntegral (fromIntegral x :: Word16)
786 narrowU I32 x = fromIntegral (fromIntegral x :: Word32)
787 narrowU I64 x = fromIntegral (fromIntegral x :: Word64)
788 narrowU _ _ = panic "narrowTo"
790 narrowS :: MachRep -> Integer -> Integer
791 narrowS I8 x = fromIntegral (fromIntegral x :: Int8)
792 narrowS I16 x = fromIntegral (fromIntegral x :: Int16)
793 narrowS I32 x = fromIntegral (fromIntegral x :: Int32)
794 narrowS I64 x = fromIntegral (fromIntegral x :: Int64)
795 narrowS _ _ = panic "narrowTo"
797 -- -----------------------------------------------------------------------------
800 -- This pass inlines assignments to temporaries that are used just
801 -- once in the very next statement only. Generalising this would be
802 -- quite difficult (have to take into account aliasing of memory
803 -- writes, and so on), but at the moment it catches a number of useful
804 -- cases and lets the code generator generate much better code.
806 -- NB. This assumes that temporaries are single-assignment.
808 cmmPeep :: [CmmBasicBlock] -> [CmmBasicBlock]
809 cmmPeep blocks = map do_inline blocks
811 blockUses (BasicBlock _ stmts)
812 = foldr (plusUFM_C (+)) emptyUFM (map getStmtUses stmts)
814 uses = foldr (plusUFM_C (+)) emptyUFM (map blockUses blocks)
816 do_inline (BasicBlock id stmts)
817 = BasicBlock id (cmmMiniInline uses stmts)
820 cmmMiniInline :: UniqFM Int -> [CmmStmt] -> [CmmStmt]
821 cmmMiniInline uses [] = []
822 cmmMiniInline uses (stmt@(CmmAssign (CmmLocal (LocalReg u _)) expr) : stmts)
823 | Just 1 <- lookupUFM uses u,
824 Just stmts' <- lookForInline u expr stmts
827 trace ("nativeGen: inlining " ++ showSDoc (pprStmt stmt)) $
829 cmmMiniInline uses stmts'
831 cmmMiniInline uses (stmt:stmts)
832 = stmt : cmmMiniInline uses stmts
835 -- Try to inline a temporary assignment. We can skip over assignments to
836 -- other tempoararies, because we know that expressions aren't side-effecting
837 -- and temporaries are single-assignment.
838 lookForInline u expr (stmt@(CmmAssign (CmmLocal (LocalReg u' _)) rhs) : rest)
840 = case lookupUFM (getExprUses rhs) u of
841 Just 1 -> Just (inlineStmt u expr stmt : rest)
842 _other -> case lookForInline u expr rest of
844 Just stmts -> Just (stmt:stmts)
846 lookForInline u expr (CmmNop : rest)
847 = lookForInline u expr rest
849 lookForInline u expr (stmt:stmts)
850 = case lookupUFM (getStmtUses stmt) u of
851 Just 1 -> Just (inlineStmt u expr stmt : stmts)
854 -- -----------------------------------------------------------------------------
855 -- Boring Cmm traversals for collecting usage info and substitutions.
857 getStmtUses :: CmmStmt -> UniqFM Int
858 getStmtUses (CmmAssign _ e) = getExprUses e
859 getStmtUses (CmmStore e1 e2) = plusUFM_C (+) (getExprUses e1) (getExprUses e2)
860 getStmtUses (CmmCall target _ es _)
861 = plusUFM_C (+) (uses target) (getExprsUses (map fst es))
862 where uses (CmmForeignCall e _) = getExprUses e
864 getStmtUses (CmmCondBranch e _) = getExprUses e
865 getStmtUses (CmmSwitch e _) = getExprUses e
866 getStmtUses (CmmJump e _) = getExprUses e
867 getStmtUses _ = emptyUFM
869 getExprUses :: CmmExpr -> UniqFM Int
870 getExprUses (CmmReg (CmmLocal (LocalReg u _))) = unitUFM u 1
871 getExprUses (CmmRegOff (CmmLocal (LocalReg u _)) _) = unitUFM u 1
872 getExprUses (CmmLoad e _) = getExprUses e
873 getExprUses (CmmMachOp _ es) = getExprsUses es
874 getExprUses _other = emptyUFM
876 getExprsUses es = foldr (plusUFM_C (+)) emptyUFM (map getExprUses es)
878 inlineStmt :: Unique -> CmmExpr -> CmmStmt -> CmmStmt
879 inlineStmt u a (CmmAssign r e) = CmmAssign r (inlineExpr u a e)
880 inlineStmt u a (CmmStore e1 e2) = CmmStore (inlineExpr u a e1) (inlineExpr u a e2)
881 inlineStmt u a (CmmCall target regs es vols)
882 = CmmCall (infn target) regs es' vols
883 where infn (CmmForeignCall fn cconv) = CmmForeignCall fn cconv
884 infn (CmmPrim p) = CmmPrim p
885 es' = [ (inlineExpr u a e, hint) | (e,hint) <- es ]
886 inlineStmt u a (CmmCondBranch e d) = CmmCondBranch (inlineExpr u a e) d
887 inlineStmt u a (CmmSwitch e d) = CmmSwitch (inlineExpr u a e) d
888 inlineStmt u a (CmmJump e d) = CmmJump (inlineExpr u a e) d
889 inlineStmt u a other_stmt = other_stmt
891 inlineExpr :: Unique -> CmmExpr -> CmmExpr -> CmmExpr
892 inlineExpr u a e@(CmmReg (CmmLocal (LocalReg u' _)))
895 inlineExpr u a e@(CmmRegOff (CmmLocal (LocalReg u' rep)) off)
896 | u == u' = CmmMachOp (MO_Add rep) [a, CmmLit (CmmInt (fromIntegral off) rep)]
898 inlineExpr u a (CmmLoad e rep) = CmmLoad (inlineExpr u a e) rep
899 inlineExpr u a (CmmMachOp op es) = CmmMachOp op (map (inlineExpr u a) es)
900 inlineExpr u a other_expr = other_expr
902 -- -----------------------------------------------------------------------------
907 isLit (CmmLit _) = True
910 isComparisonExpr :: CmmExpr -> Bool
911 isComparisonExpr (CmmMachOp op _) = isComparisonMachOp op
912 isComparisonExpr _other = False
914 maybeInvertConditionalExpr :: CmmExpr -> Maybe CmmExpr
915 maybeInvertConditionalExpr (CmmMachOp op args)
916 | Just op' <- maybeInvertComparison op = Just (CmmMachOp op' args)
917 maybeInvertConditionalExpr _ = Nothing