CmmOpt.hs 27.8 KB
Newer Older
1 2 3 4 5 6 7 8 9
-----------------------------------------------------------------------------
--
-- Cmm optimisation
--
-- (c) The University of Glasgow 2006
--
-----------------------------------------------------------------------------

module CmmOpt (
10 11 12 13 14
        cmmEliminateDeadBlocks,
        cmmMiniInline,
        cmmMachOpFold,
        cmmMachOpFoldM,
        cmmLoopifyForC,
15 16 17 18
 ) where

#include "HsVersions.h"

19
import OldCmm
20
import OldPprCmm
21
import CmmNode (wrapRecExp)
Simon Marlow's avatar
Simon Marlow committed
22
import CmmUtils
23
import StaticFlags
24 25

import UniqFM
Simon Marlow's avatar
Simon Marlow committed
26
import Unique
27
import Util
28
import FastTypes
29
import Outputable
30
import Platform
31
import BlockId
32

Simon Marlow's avatar
Simon Marlow committed
33
import Data.Bits
34
import Data.Maybe
35
import Data.List
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53

-- -----------------------------------------------------------------------------
-- Eliminates dead blocks

{-
We repeatedly expand the set of reachable blocks until we hit a
fixpoint, and then prune any blocks that were not in this set.  This is
actually a required optimization, as dead blocks can cause problems
for invariants in the linear register allocator (and possibly other
places.)
-}

-- Deep fold over statements could probably be abstracted out, but it
-- might not be worth the effort since OldCmm is moribund
cmmEliminateDeadBlocks :: [CmmBasicBlock] -> [CmmBasicBlock]
cmmEliminateDeadBlocks [] = []
cmmEliminateDeadBlocks blocks@(BasicBlock base_id _:_) =
    let -- Calculate what's reachable from what block
54 55 56
        reachableMap = foldl' f emptyUFM blocks -- lazy in values
            where f m (BasicBlock block_id stmts) = addToUFM m block_id (reachableFrom stmts)
        reachableFrom stmts = foldl stmt [] stmts
57 58 59 60 61
            where
                stmt m CmmNop = m
                stmt m (CmmComment _) = m
                stmt m (CmmAssign _ e) = expr m e
                stmt m (CmmStore e1 e2) = expr (expr m e1) e2
62
                stmt m (CmmCall c _ as _) = f (actuals m as) c
63 64
                    where f m (CmmCallee e _) = expr m e
                          f m (CmmPrim _) = m
65 66 67
                stmt m (CmmBranch b) = b:m
                stmt m (CmmCondBranch e b) = b:(expr m e)
                stmt m (CmmSwitch e bs) = catMaybes bs ++ expr m e
68
                stmt m (CmmJump e _) = expr m e
dterei's avatar
dterei committed
69
                stmt m (CmmReturn) = m
70 71 72
                actuals m as = foldl' (\m h -> expr m (hintlessCmm h)) m as
                -- We have to do a deep fold into CmmExpr because
                -- there may be a BlockId in the CmmBlock literal.
73 74 75
                expr m (CmmLit l) = lit m l
                expr m (CmmLoad e _) = expr m e
                expr m (CmmReg _) = m
76
                expr m (CmmMachOp _ es) = foldl' expr m es
77 78
                expr m (CmmStackSlot _ _) = m
                expr m (CmmRegOff _ _) = m
79
                lit m (CmmBlock b) = b:m
80
                lit m _ = m
81 82 83 84 85 86 87 88
        -- go todo done
        reachable = go [base_id] (setEmpty :: BlockSet)
          where go []     m = m
                go (x:xs) m
                    | setMember x m = go xs m
                    | otherwise     = go (add ++ xs) (setInsert x m)
                        where add = fromMaybe (panic "cmmEliminateDeadBlocks: unknown block")
                                              (lookupUFM reachableMap x)
89
    in filter (\(BasicBlock block_id _) -> setMember block_id reachable) blocks
90 91 92 93

-- -----------------------------------------------------------------------------
-- The mini-inliner

Simon Marlow's avatar
Simon Marlow committed
94
{-
95 96 97 98
This pass inlines assignments to temporaries.  Temporaries that are
only used once are unconditionally inlined.  Temporaries that are used
two or more times are only inlined if they are assigned a literal.  It
works as follows:
Simon Marlow's avatar
Simon Marlow committed
99 100

  - count uses of each temporary
101
  - for each temporary:
Ian Lynagh's avatar
Ian Lynagh committed
102
        - attempt to push it forward to the statement that uses it
Simon Marlow's avatar
Simon Marlow committed
103
        - only push forward past assignments to other temporaries
Ian Lynagh's avatar
Ian Lynagh committed
104 105 106
          (assumes that temporaries are single-assignment)
        - if we reach the statement that uses it, inline the rhs
          and delete the original assignment.
Simon Marlow's avatar
Simon Marlow committed
107

108 109 110 111
[N.B. In the Quick C-- compiler, this optimization is achieved by a
 combination of two dataflow passes: forward substitution (peephole
 optimization) and dead-assignment elimination.  ---NR]

Simon Marlow's avatar
Simon Marlow committed
112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
Possible generalisations: here is an example from factorial

Fac_zdwfac_entry:
    cmG:
        _smi = R2;
        if (_smi != 0) goto cmK;
        R1 = R3;
        jump I64[Sp];
    cmK:
        _smn = _smi * R3;
        R2 = _smi + (-1);
        R3 = _smn;
        jump Fac_zdwfac_info;

We want to inline _smi and _smn.  To inline _smn:

   - we must be able to push forward past assignments to global regs.
     We can do this if the rhs of the assignment we are pushing
     forward doesn't refer to the global reg being assigned to; easy
     to test.

To inline _smi:

   - It is a trivial replacement, reg for reg, but it occurs more than
     once.
   - We can inline trivial assignments even if the temporary occurs
     more than once, as long as we don't eliminate the original assignment
     (this doesn't help much on its own).
   - We need to be able to propagate the assignment forward through jumps;
     if we did this, we would find that it can be inlined safely in all
     its occurrences.
-}

145
countUses :: UserOfLocalRegs a => a -> UniqFM Int
Simon Marlow's avatar
Simon Marlow committed
146
countUses a = foldRegsUsed (\m r -> addToUFM_C (+) m r 1) emptyUFM a
147 148
  where count m r = lookupWithDefaultUFM m (0::Int) r

149 150
cmmMiniInline :: Platform -> [CmmBasicBlock] -> [CmmBasicBlock]
cmmMiniInline platform blocks = map do_inline blocks
151
  where do_inline (BasicBlock id stmts)
152
          = BasicBlock id (cmmMiniInlineStmts platform (countUses blocks) stmts)
153

154
cmmMiniInlineStmts :: Platform -> UniqFM Int -> [CmmStmt] -> [CmmStmt]
Ian Lynagh's avatar
Ian Lynagh committed
155
cmmMiniInlineStmts _        _    [] = []
156
cmmMiniInlineStmts platform uses (stmt@(CmmAssign (CmmLocal (LocalReg u _)) expr) : stmts)
157
        -- not used: just discard this assignment
Simon Marlow's avatar
Simon Marlow committed
158
  | 0 <- lookupWithDefaultUFM uses 0 u
159
  = cmmMiniInlineStmts platform uses stmts
160

161
        -- used (foldable to small thing): try to inline at all the use sites
162
  | Just n <- lookupUFM uses u,
163 164
    e <- wrapRecExp foldExp expr,
    isTiny e
165
  =
166
     ncgDebugTrace ("nativeGen: inlining " ++ showSDoc (pprStmt platform stmt)) $
167
     case lookForInlineMany u e stmts of
168
         (m, stmts')
169
             | n == m -> cmmMiniInlineStmts platform (delFromUFM uses u) stmts'
170
             | otherwise ->
171
                 stmt : cmmMiniInlineStmts platform (adjustUFM (\x -> x - m) uses u) stmts'
172

173
        -- used once (non-literal): try to inline at the use site
174 175 176
  | Just 1 <- lookupUFM uses u,
    Just stmts' <- lookForInline u expr stmts
  = 
177 178
     ncgDebugTrace ("nativeGen: inlining " ++ showSDoc (pprStmt platform stmt)) $
     cmmMiniInlineStmts platform uses stmts'
179
 where
180
  isTiny (CmmLit _) = True
181 182
  isTiny (CmmReg (CmmGlobal _)) = True
         -- not CmmLocal: that might invalidate the usage analysis results
183 184
  isTiny _ = False

Ian Lynagh's avatar
Ian Lynagh committed
185
  foldExp (CmmMachOp op args) = cmmMachOpFold platform op args
186
  foldExp e = e
187

188 189 190 191
  ncgDebugTrace str x = if ncgDebugIsOn then trace str x else x

cmmMiniInlineStmts platform uses (stmt:stmts)
  = stmt : cmmMiniInlineStmts platform uses stmts
192

193 194 195 196
-- | Takes a register, a 'CmmLit' expression assigned to that
-- register, and a list of statements.  Inlines the expression at all
-- use sites of the register.  Returns the number of substituations
-- made and the, possibly modified, list of statements.
197 198 199 200 201 202 203
lookForInlineMany :: Unique -> CmmExpr -> [CmmStmt] -> (Int, [CmmStmt])
lookForInlineMany u expr stmts = lookForInlineMany' u expr regset stmts
    where regset = foldRegsUsed extendRegSet emptyRegSet expr

lookForInlineMany' :: Unique -> CmmExpr -> RegSet -> [CmmStmt] -> (Int, [CmmStmt])
lookForInlineMany' _ _ _ [] = (0, [])
lookForInlineMany' u expr regset stmts@(stmt : rest)
204
  | Just n <- lookupUFM (countUses stmt) u, okToInline expr stmt
Simon Marlow's avatar
Simon Marlow committed
205 206 207 208 209 210 211
  = let stmt' = inlineStmt u expr stmt in
    if okToSkip stmt' u expr regset
       then case lookForInlineMany' u expr regset rest of
                       (m, stmts) -> let z = n + m
                                     in z `seq` (z, stmt' : stmts)
       else (n, stmt' : rest)

212 213
  | okToSkip stmt u expr regset
  = case lookForInlineMany' u expr regset rest of
214 215 216 217
      (n, stmts) -> (n, stmt : stmts)

  | otherwise
  = (0, stmts)
218

219

Ian Lynagh's avatar
Ian Lynagh committed
220
lookForInline :: Unique -> CmmExpr -> [CmmStmt] -> Maybe [CmmStmt]
221 222 223
lookForInline u expr stmts = lookForInline' u expr regset stmts
    where regset = foldRegsUsed extendRegSet emptyRegSet expr

Ian Lynagh's avatar
Ian Lynagh committed
224 225
lookForInline' :: Unique -> CmmExpr -> RegSet -> [CmmStmt] -> Maybe [CmmStmt]
lookForInline' _ _    _      [] = panic "lookForInline' []"
226
lookForInline' u expr regset (stmt : rest)
227
  | Just 1 <- lookupUFM (countUses stmt) u, okToInline expr stmt
228 229
  = Just (inlineStmt u expr stmt : rest)

230
  | okToSkip stmt u expr regset
231
  = case lookForInline' u expr regset rest of
232 233 234 235 236
           Nothing    -> Nothing
           Just stmts -> Just (stmt:stmts)

  | otherwise 
  = Nothing
237

238 239 240 241 242 243 244 245 246

-- we don't inline into CmmCall if the expression refers to global
-- registers.  This is a HACK to avoid global registers clashing with
-- C argument-passing registers, really the back-end ought to be able
-- to handle it properly, but currently neither PprC nor the NCG can
-- do it.  See also CgForeignCall:load_args_into_temps.
okToInline :: CmmExpr -> CmmStmt -> Bool
okToInline expr CmmCall{} = hasNoGlobalRegs expr
okToInline _ _ = True
247

248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267
-- Expressions aren't side-effecting.  Temporaries may or may not
-- be single-assignment depending on the source (the old code
-- generator creates single-assignment code, but hand-written Cmm
-- and Cmm from the new code generator is not single-assignment.)
-- So we do an extra check to make sure that the register being
-- changed is not one we were relying on.  I don't know how much of a
-- performance hit this is (we have to create a regset for every
-- instruction.) -- EZY
okToSkip stmt u expr regset
   = case stmt of
         CmmNop -> True
         CmmComment{} -> True
         CmmAssign (CmmLocal r@(LocalReg u' _)) _rhs | u' /= u && not (r `elemRegSet` regset) -> True
         CmmAssign g@(CmmGlobal _) _rhs -> not (g `regUsedIn` expr)
         CmmStore _ _ -> not_a_load expr
         _other -> False
  where
    not_a_load (CmmMachOp _ args) = all not_a_load args
    not_a_load (CmmLoad _ _) = False
    not_a_load _ = True
268

269 270 271
inlineStmt :: Unique -> CmmExpr -> CmmStmt -> CmmStmt
inlineStmt u a (CmmAssign r e) = CmmAssign r (inlineExpr u a e)
inlineStmt u a (CmmStore e1 e2) = CmmStore (inlineExpr u a e1) (inlineExpr u a e2)
272 273
inlineStmt u a (CmmCall target regs es ret)
   = CmmCall (infn target) regs es' ret
274
   where infn (CmmCallee fn cconv) = CmmCallee (inlineExpr u a fn) cconv
Ian Lynagh's avatar
Ian Lynagh committed
275 276
         infn (CmmPrim p) = CmmPrim p
         es' = [ (CmmHinted (inlineExpr u a e) hint) | (CmmHinted e hint) <- es ]
277 278
inlineStmt u a (CmmCondBranch e d) = CmmCondBranch (inlineExpr u a e) d
inlineStmt u a (CmmSwitch e d) = CmmSwitch (inlineExpr u a e) d
279
inlineStmt u a (CmmJump e live) = CmmJump (inlineExpr u a e) live
Ian Lynagh's avatar
Ian Lynagh committed
280
inlineStmt _ _ other_stmt = other_stmt
281 282

inlineExpr :: Unique -> CmmExpr -> CmmExpr -> CmmExpr
283
inlineExpr u a e@(CmmReg (CmmLocal (LocalReg u' _)))
284 285
  | u == u' = a
  | otherwise = e
286 287
inlineExpr u a e@(CmmRegOff (CmmLocal (LocalReg u' rep)) off)
  | u == u' = CmmMachOp (MO_Add width) [a, CmmLit (CmmInt (fromIntegral off) width)]
288
  | otherwise = e
289 290
  where
    width = typeWidth rep
291 292
inlineExpr u a (CmmLoad e rep) = CmmLoad (inlineExpr u a e) rep
inlineExpr u a (CmmMachOp op es) = CmmMachOp op (map (inlineExpr u a) es)
Ian Lynagh's avatar
Ian Lynagh committed
293
inlineExpr _ _ other_expr = other_expr
294 295 296 297 298 299 300 301

-- -----------------------------------------------------------------------------
-- MachOp constant folder

-- Now, try to constant-fold the MachOps.  The arguments have already
-- been optimized and folded.

cmmMachOpFold
Ian Lynagh's avatar
Ian Lynagh committed
302 303
    :: Platform
    -> MachOp       -- The operation from an CmmMachOp
304
    -> [CmmExpr]    -- The optimized arguments
305 306
    -> CmmExpr

Ian Lynagh's avatar
Ian Lynagh committed
307
cmmMachOpFold platform op args = fromMaybe (CmmMachOp op args) (cmmMachOpFoldM platform op args)
308 309 310 311

-- Returns Nothing if no changes, useful for Hoopl, also reduces
-- allocation!
cmmMachOpFoldM
Ian Lynagh's avatar
Ian Lynagh committed
312 313
    :: Platform
    -> MachOp
314 315 316
    -> [CmmExpr]
    -> Maybe CmmExpr

Ian Lynagh's avatar
Ian Lynagh committed
317
cmmMachOpFoldM _ op [CmmLit (CmmInt x rep)]
318
  = Just $ case op of
Ian Lynagh's avatar
Ian Lynagh committed
319 320
      MO_S_Neg _ -> CmmLit (CmmInt (-x) rep)
      MO_Not _   -> CmmLit (CmmInt (complement x) rep)
321

322 323 324 325
        -- these are interesting: we must first narrow to the 
        -- "from" type, in order to truncate to the correct size.
        -- The final narrow/widen to the destination type
        -- is implicit in the CmmLit.
Ian Lynagh's avatar
Ian Lynagh committed
326 327 328
      MO_SF_Conv _from to -> CmmLit (CmmFloat (fromInteger x) to)
      MO_SS_Conv  from to -> CmmLit (CmmInt (narrowS from x) to)
      MO_UU_Conv  from to -> CmmLit (CmmInt (narrowU from x) to)
329

330
      _ -> panic "cmmMachOpFoldM: unknown unary op"
331 332 333


-- Eliminate conversion NOPs
Ian Lynagh's avatar
Ian Lynagh committed
334 335
cmmMachOpFoldM _ (MO_SS_Conv rep1 rep2) [x] | rep1 == rep2 = Just x
cmmMachOpFoldM _ (MO_UU_Conv rep1 rep2) [x] | rep1 == rep2 = Just x
336 337

-- Eliminate nested conversions where possible
Ian Lynagh's avatar
Ian Lynagh committed
338
cmmMachOpFoldM platform conv_outer [CmmMachOp conv_inner [x]]
339 340 341
  | Just (rep1,rep2,signed1) <- isIntConversion conv_inner,
    Just (_,   rep3,signed2) <- isIntConversion conv_outer
  = case () of
342 343 344 345 346 347
        -- widen then narrow to the same size is a nop
      _ | rep1 < rep2 && rep1 == rep3 -> Just x
        -- Widen then narrow to different size: collapse to single conversion
        -- but remember to use the signedness from the widening, just in case
        -- the final conversion is a widen.
        | rep1 < rep2 && rep2 > rep3 ->
Ian Lynagh's avatar
Ian Lynagh committed
348
            Just $ cmmMachOpFold platform (intconv signed1 rep1 rep3) [x]
349 350
        -- Nested widenings: collapse if the signedness is the same
        | rep1 < rep2 && rep2 < rep3 && signed1 == signed2 ->
Ian Lynagh's avatar
Ian Lynagh committed
351
            Just $ cmmMachOpFold platform (intconv signed1 rep1 rep3) [x]
352 353
        -- Nested narrowings: collapse
        | rep1 > rep2 && rep2 > rep3 ->
Ian Lynagh's avatar
Ian Lynagh committed
354
            Just $ cmmMachOpFold platform (MO_UU_Conv rep1 rep3) [x]
355 356
        | otherwise ->
            Nothing
357
  where
358 359 360 361 362
        isIntConversion (MO_UU_Conv rep1 rep2) 
          = Just (rep1,rep2,False)
        isIntConversion (MO_SS_Conv rep1 rep2)
          = Just (rep1,rep2,True)
        isIntConversion _ = Nothing
363

364 365
        intconv True  = MO_SS_Conv
        intconv False = MO_UU_Conv
366 367 368 369 370

-- ToDo: a narrow of a load can be collapsed into a narrow load, right?
-- but what if the architecture only supports word-sized loads, should
-- we do the transformation anyway?

Ian Lynagh's avatar
Ian Lynagh committed
371
cmmMachOpFoldM _ mop [CmmLit (CmmInt x xrep), CmmLit (CmmInt y _)]
372
  = case mop of
373 374
        -- for comparisons: don't forget to narrow the arguments before
        -- comparing, since they might be out of range.
Ian Lynagh's avatar
Ian Lynagh committed
375 376
        MO_Eq _   -> Just $ CmmLit (CmmInt (if x_u == y_u then 1 else 0) wordWidth)
        MO_Ne _   -> Just $ CmmLit (CmmInt (if x_u /= y_u then 1 else 0) wordWidth)
377

Ian Lynagh's avatar
Ian Lynagh committed
378 379 380 381
        MO_U_Gt _ -> Just $ CmmLit (CmmInt (if x_u >  y_u then 1 else 0) wordWidth)
        MO_U_Ge _ -> Just $ CmmLit (CmmInt (if x_u >= y_u then 1 else 0) wordWidth)
        MO_U_Lt _ -> Just $ CmmLit (CmmInt (if x_u <  y_u then 1 else 0) wordWidth)
        MO_U_Le _ -> Just $ CmmLit (CmmInt (if x_u <= y_u then 1 else 0) wordWidth)
382

Ian Lynagh's avatar
Ian Lynagh committed
383 384 385 386
        MO_S_Gt _ -> Just $ CmmLit (CmmInt (if x_s >  y_s then 1 else 0) wordWidth)
        MO_S_Ge _ -> Just $ CmmLit (CmmInt (if x_s >= y_s then 1 else 0) wordWidth)
        MO_S_Lt _ -> Just $ CmmLit (CmmInt (if x_s <  y_s then 1 else 0) wordWidth)
        MO_S_Le _ -> Just $ CmmLit (CmmInt (if x_s <= y_s then 1 else 0) wordWidth)
387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403

        MO_Add r -> Just $ CmmLit (CmmInt (x + y) r)
        MO_Sub r -> Just $ CmmLit (CmmInt (x - y) r)
        MO_Mul r -> Just $ CmmLit (CmmInt (x * y) r)
        MO_U_Quot r | y /= 0 -> Just $ CmmLit (CmmInt (x_u `quot` y_u) r)
        MO_U_Rem  r | y /= 0 -> Just $ CmmLit (CmmInt (x_u `rem`  y_u) r)
        MO_S_Quot r | y /= 0 -> Just $ CmmLit (CmmInt (x `quot` y) r)
        MO_S_Rem  r | y /= 0 -> Just $ CmmLit (CmmInt (x `rem` y) r)

        MO_And   r -> Just $ CmmLit (CmmInt (x .&. y) r)
        MO_Or    r -> Just $ CmmLit (CmmInt (x .|. y) r)
        MO_Xor   r -> Just $ CmmLit (CmmInt (x `xor` y) r)

        MO_Shl   r -> Just $ CmmLit (CmmInt (x `shiftL` fromIntegral y) r)
        MO_U_Shr r -> Just $ CmmLit (CmmInt (x_u `shiftR` fromIntegral y) r)
        MO_S_Shr r -> Just $ CmmLit (CmmInt (x `shiftR` fromIntegral y) r)

Ian Lynagh's avatar
Ian Lynagh committed
404
        _          -> Nothing
405 406

   where
407 408 409 410 411
        x_u = narrowU xrep x
        y_u = narrowU xrep y
        x_s = narrowS xrep x
        y_s = narrowS xrep y

412 413 414 415 416 417

-- When possible, shift the constants to the right-hand side, so that we
-- can match for strength reductions.  Note that the code generator will
-- also assume that constants have been shifted to the right when
-- possible.

Ian Lynagh's avatar
Ian Lynagh committed
418
cmmMachOpFoldM platform op [x@(CmmLit _), y]
419
   | not (isLit y) && isCommutableMachOp op
Ian Lynagh's avatar
Ian Lynagh committed
420
   = Just (cmmMachOpFold platform op [y, x])
421 422 423 424 425 426 427 428 429 430 431 432 433 434

-- Turn (a+b)+c into a+(b+c) where possible.  Because literals are
-- moved to the right, it is more likely that we will find
-- opportunities for constant folding when the expression is
-- right-associated.
--
-- ToDo: this appears to introduce a quadratic behaviour due to the
-- nested cmmMachOpFold.  Can we fix this?
--
-- Why do we check isLit arg1?  If arg1 is a lit, it means that arg2
-- is also a lit (otherwise arg1 would be on the right).  If we
-- put arg1 on the left of the rearranged expression, we'll get into a
-- loop:  (x1+x2)+x3 => x1+(x2+x3)  => (x2+x3)+x1 => x2+(x3+x1) ...
--
435 436 437
-- Also don't do it if arg1 is PicBaseReg, so that we don't separate the
-- PicBaseReg from the corresponding label (or label difference).
--
Ian Lynagh's avatar
Ian Lynagh committed
438
cmmMachOpFoldM platform mop1 [CmmMachOp mop2 [arg1,arg2], arg3]
439
   | mop2 `associates_with` mop1
440
     && not (isLit arg1) && not (isPicReg arg1)
Ian Lynagh's avatar
Ian Lynagh committed
441
   = Just (cmmMachOpFold platform mop2 [arg1, cmmMachOpFold platform mop1 [arg2,arg3]])
442 443 444 445 446 447
   where
     MO_Add{} `associates_with` MO_Sub{} = True
     mop1 `associates_with` mop2 =
        mop1 == mop2 && isAssociativeMachOp mop1

-- special case: (a - b) + c  ==>  a + (c - b)
Ian Lynagh's avatar
Ian Lynagh committed
448
cmmMachOpFoldM platform mop1@(MO_Add{}) [CmmMachOp mop2@(MO_Sub{}) [arg1,arg2], arg3]
449
   | not (isLit arg1) && not (isPicReg arg1)
Ian Lynagh's avatar
Ian Lynagh committed
450
   = Just (cmmMachOpFold platform mop1 [arg1, cmmMachOpFold platform mop2 [arg3,arg2]])
451 452

-- Make a RegOff if we can
Ian Lynagh's avatar
Ian Lynagh committed
453
cmmMachOpFoldM _ (MO_Add _) [CmmReg reg, CmmLit (CmmInt n rep)]
454
  = Just $ CmmRegOff reg (fromIntegral (narrowS rep n))
Ian Lynagh's avatar
Ian Lynagh committed
455
cmmMachOpFoldM _ (MO_Add _) [CmmRegOff reg off, CmmLit (CmmInt n rep)]
456
  = Just $ CmmRegOff reg (off + fromIntegral (narrowS rep n))
Ian Lynagh's avatar
Ian Lynagh committed
457
cmmMachOpFoldM _ (MO_Sub _) [CmmReg reg, CmmLit (CmmInt n rep)]
458
  = Just $ CmmRegOff reg (- fromIntegral (narrowS rep n))
Ian Lynagh's avatar
Ian Lynagh committed
459
cmmMachOpFoldM _ (MO_Sub _) [CmmRegOff reg off, CmmLit (CmmInt n rep)]
460
  = Just $ CmmRegOff reg (off - fromIntegral (narrowS rep n))
461 462 463

-- Fold label(+/-)offset into a CmmLit where possible

Ian Lynagh's avatar
Ian Lynagh committed
464
cmmMachOpFoldM _ (MO_Add _) [CmmLit (CmmLabel lbl), CmmLit (CmmInt i rep)]
465
  = Just $ CmmLit (CmmLabelOff lbl (fromIntegral (narrowU rep i)))
Ian Lynagh's avatar
Ian Lynagh committed
466
cmmMachOpFoldM _ (MO_Add _) [CmmLit (CmmInt i rep), CmmLit (CmmLabel lbl)]
467
  = Just $ CmmLit (CmmLabelOff lbl (fromIntegral (narrowU rep i)))
Ian Lynagh's avatar
Ian Lynagh committed
468
cmmMachOpFoldM _ (MO_Sub _) [CmmLit (CmmLabel lbl), CmmLit (CmmInt i rep)]
469
  = Just $ CmmLit (CmmLabelOff lbl (fromIntegral (negate (narrowU rep i))))
470

471

472 473 474 475 476 477
-- Comparison of literal with widened operand: perform the comparison
-- at the smaller width, as long as the literal is within range.

-- We can't do the reverse trick, when the operand is narrowed:
-- narrowing throws away bits from the operand, there's no way to do
-- the same comparison at the larger size.
478

Ian Lynagh's avatar
Ian Lynagh committed
479 480 481 482
cmmMachOpFoldM platform cmp [CmmMachOp conv [x], CmmLit (CmmInt i _)]
  |     -- powerPC NCG has a TODO for I8/I16 comparisons, so don't try
    platformArch platform `elem` [ArchX86, ArchX86_64],
        -- if the operand is widened:
483 484 485 486 487 488
    Just (rep, signed, narrow_fn) <- maybe_conversion conv,
        -- and this is a comparison operation:
    Just narrow_cmp <- maybe_comparison cmp rep signed,
        -- and the literal fits in the smaller size:
    i == narrow_fn rep i
        -- then we can do the comparison at the smaller size
Ian Lynagh's avatar
Ian Lynagh committed
489
  = Just (cmmMachOpFold platform narrow_cmp [x, CmmLit (CmmInt i rep)])
490
 where
491
    maybe_conversion (MO_UU_Conv from to)
492 493
        | to > from
        = Just (from, False, narrowU)
494 495
    maybe_conversion (MO_SS_Conv from to)
        | to > from
496
        = Just (from, True, narrowS)
497

Simon Marlow's avatar
Simon Marlow committed
498 499
        -- don't attempt to apply this optimisation when the source
        -- is a float; see #1916
500
    maybe_conversion _ = Nothing
501

502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518
        -- careful (#2080): if the original comparison was signed, but
        -- we were doing an unsigned widen, then we must do an
        -- unsigned comparison at the smaller size.
    maybe_comparison (MO_U_Gt _) rep _     = Just (MO_U_Gt rep)
    maybe_comparison (MO_U_Ge _) rep _     = Just (MO_U_Ge rep)
    maybe_comparison (MO_U_Lt _) rep _     = Just (MO_U_Lt rep)
    maybe_comparison (MO_U_Le _) rep _     = Just (MO_U_Le rep)
    maybe_comparison (MO_Eq   _) rep _     = Just (MO_Eq   rep)
    maybe_comparison (MO_S_Gt _) rep True  = Just (MO_S_Gt rep)
    maybe_comparison (MO_S_Ge _) rep True  = Just (MO_S_Ge rep)
    maybe_comparison (MO_S_Lt _) rep True  = Just (MO_S_Lt rep)
    maybe_comparison (MO_S_Le _) rep True  = Just (MO_S_Le rep)
    maybe_comparison (MO_S_Gt _) rep False = Just (MO_U_Gt rep)
    maybe_comparison (MO_S_Ge _) rep False = Just (MO_U_Ge rep)
    maybe_comparison (MO_S_Lt _) rep False = Just (MO_U_Lt rep)
    maybe_comparison (MO_S_Le _) rep False = Just (MO_U_Le rep)
    maybe_comparison _ _ _ = Nothing
519

520 521
-- We can often do something with constants of 0 and 1 ...

Ian Lynagh's avatar
Ian Lynagh committed
522
cmmMachOpFoldM _ mop [x, y@(CmmLit (CmmInt 0 _))]
523
  = case mop of
Ian Lynagh's avatar
Ian Lynagh committed
524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545
        MO_Add   _ -> Just x
        MO_Sub   _ -> Just x
        MO_Mul   _ -> Just y
        MO_And   _ -> Just y
        MO_Or    _ -> Just x
        MO_Xor   _ -> Just x
        MO_Shl   _ -> Just x
        MO_S_Shr _ -> Just x
        MO_U_Shr _ -> Just x
        MO_Ne    _ | isComparisonExpr x -> Just x
        MO_Eq    _ | Just x' <- maybeInvertCmmExpr x -> Just x'
        MO_U_Gt  _ | isComparisonExpr x -> Just x
        MO_S_Gt  _ | isComparisonExpr x -> Just x
        MO_U_Lt  _ | isComparisonExpr x -> Just $ CmmLit (CmmInt 0 wordWidth)
        MO_S_Lt  _ | isComparisonExpr x -> Just $ CmmLit (CmmInt 0 wordWidth)
        MO_U_Ge  _ | isComparisonExpr x -> Just $ CmmLit (CmmInt 1 wordWidth)
        MO_S_Ge  _ | isComparisonExpr x -> Just $ CmmLit (CmmInt 1 wordWidth)
        MO_U_Le  _ | Just x' <- maybeInvertCmmExpr x -> Just x'
        MO_S_Le  _ | Just x' <- maybeInvertCmmExpr x -> Just x'
        _ -> Nothing

cmmMachOpFoldM _ mop [x, (CmmLit (CmmInt 1 rep))]
546
  = case mop of
Ian Lynagh's avatar
Ian Lynagh committed
547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562
        MO_Mul    _ -> Just x
        MO_S_Quot _ -> Just x
        MO_U_Quot _ -> Just x
        MO_S_Rem  _ -> Just $ CmmLit (CmmInt 0 rep)
        MO_U_Rem  _ -> Just $ CmmLit (CmmInt 0 rep)
        MO_Ne    _ | Just x' <- maybeInvertCmmExpr x -> Just x'
        MO_Eq    _ | isComparisonExpr x -> Just x
        MO_U_Lt  _ | Just x' <- maybeInvertCmmExpr x -> Just x'
        MO_S_Lt  _ | Just x' <- maybeInvertCmmExpr x -> Just x'
        MO_U_Gt  _ | isComparisonExpr x -> Just $ CmmLit (CmmInt 0 wordWidth)
        MO_S_Gt  _ | isComparisonExpr x -> Just $ CmmLit (CmmInt 0 wordWidth)
        MO_U_Le  _ | isComparisonExpr x -> Just $ CmmLit (CmmInt 1 wordWidth)
        MO_S_Le  _ | isComparisonExpr x -> Just $ CmmLit (CmmInt 1 wordWidth)
        MO_U_Ge  _ | isComparisonExpr x -> Just x
        MO_S_Ge  _ | isComparisonExpr x -> Just x
        _ -> Nothing
563 564 565

-- Now look for multiplication/division by powers of 2 (integers).

Ian Lynagh's avatar
Ian Lynagh committed
566
cmmMachOpFoldM platform mop [x, (CmmLit (CmmInt n _))]
567
  = case mop of
568 569
        MO_Mul rep
           | Just p <- exactLog2 n ->
Ian Lynagh's avatar
Ian Lynagh committed
570
                 Just (cmmMachOpFold platform (MO_Shl rep) [x, CmmLit (CmmInt p rep)])
571 572
        MO_U_Quot rep
           | Just p <- exactLog2 n ->
Ian Lynagh's avatar
Ian Lynagh committed
573
                 Just (cmmMachOpFold platform (MO_U_Shr rep) [x, CmmLit (CmmInt p rep)])
574 575 576 577 578 579 580 581 582 583
        MO_S_Quot rep
           | Just p <- exactLog2 n, 
             CmmReg _ <- x ->   -- We duplicate x below, hence require
                                -- it is a reg.  FIXME: remove this restriction.
                -- shift right is not the same as quot, because it rounds
                -- to minus infinity, whereasq quot rounds toward zero.
                -- To fix this up, we add one less than the divisor to the
                -- dividend if it is a negative number.
                --
                -- to avoid a test/jump, we use the following sequence:
Ian Lynagh's avatar
Ian Lynagh committed
584
                --      x1 = x >> word_size-1  (all 1s if -ve, all 0s if +ve)
585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600
                --      x2 = y & (divisor-1)
                --      result = (x+x2) >>= log2(divisor)
                -- this could be done a bit more simply using conditional moves,
                -- but we're processor independent here.
                --
                -- we optimise the divide by 2 case slightly, generating
                --      x1 = x >> word_size-1  (unsigned)
                --      return = (x + x1) >>= log2(divisor)
                let
                    bits = fromIntegral (widthInBits rep) - 1
                    shr = if p == 1 then MO_U_Shr rep else MO_S_Shr rep
                    x1 = CmmMachOp shr [x, CmmLit (CmmInt bits rep)]
                    x2 = if p == 1 then x1 else
                         CmmMachOp (MO_And rep) [x1, CmmLit (CmmInt (n-1) rep)]
                    x3 = CmmMachOp (MO_Add rep) [x, x2]
                in
Ian Lynagh's avatar
Ian Lynagh committed
601
                Just (cmmMachOpFold platform (MO_S_Shr rep) [x3, CmmLit (CmmInt p rep)])
Ian Lynagh's avatar
Ian Lynagh committed
602
        _ -> Nothing
603 604 605

-- Anything else is just too hard.

Ian Lynagh's avatar
Ian Lynagh committed
606
cmmMachOpFoldM _ _ _ = Nothing
607 608 609 610 611 612 613 614 615 616 617

-- -----------------------------------------------------------------------------
-- exactLog2

-- This algorithm for determining the $\log_2$ of exact powers of 2 comes
-- from GCC.  It requires bit manipulation primitives, and we use GHC
-- extensions.  Tough.
-- 
-- Used to be in MachInstrs --SDM.
-- ToDo: remove use of unboxery --SDM.

618 619 620 621 622
-- Unboxery removed in favor of FastInt; but is the function supposed to fail
-- on inputs >= 2147483648, or was that just an implementation artifact?
-- And is this speed-critical, or can we just use Integer operations
-- (including Data.Bits)?
--  --Isaac Dupree
623 624

exactLog2 :: Integer -> Maybe Integer
625 626
exactLog2 x_
  = if (x_ <= 0 || x_ >= 2147483648) then
627 628
       Nothing
    else
629 630
       case iUnbox (fromInteger x_) of { x ->
       if (x `bitAndFastInt` negateFastInt x) /=# x then
Ian Lynagh's avatar
Ian Lynagh committed
631
          Nothing
632
       else
Ian Lynagh's avatar
Ian Lynagh committed
633
          Just (toInteger (iBox (pow2 x)))
634 635
       }
  where
636 637
    pow2 x | x ==# _ILIT(1) = _ILIT(0)
           | otherwise = _ILIT(1) +# pow2 (x `shiftR_FastInt` _ILIT(1))
638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665


-- -----------------------------------------------------------------------------
-- Loopify for C

{-
 This is a simple pass that replaces tail-recursive functions like this:

   fac() {
     ...
     jump fac();
   }

 with this:

  fac() {
   L:
     ...
     goto L;
  }

  the latter generates better C code, because the C compiler treats it
  like a loop, and brings full loop optimisation to bear.

  In my measurements this makes little or no difference to anything
  except factorial, but what the hell.
-}

Simon Peyton Jones's avatar
Simon Peyton Jones committed
666
cmmLoopifyForC :: RawCmmDecl -> RawCmmDecl
667
cmmLoopifyForC p@(CmmProc Nothing _ _) = p  -- only if there's an info table, ignore case alts
Ian Lynagh's avatar
Ian Lynagh committed
668
cmmLoopifyForC (CmmProc (Just info@(Statics info_lbl _)) entry_lbl
669
                 (ListGraph blocks@(BasicBlock top_id _ : _))) =
670
--  pprTrace "jump_lbl" (ppr jump_lbl <+> ppr entry_lbl) $
671
  CmmProc (Just info) entry_lbl (ListGraph blocks')
672
  where blocks' = [ BasicBlock id (map do_stmt stmts)
Ian Lynagh's avatar
Ian Lynagh committed
673
                  | BasicBlock id stmts <- blocks ]
674

675
        do_stmt (CmmJump (CmmLit (CmmLabel lbl)) _) | lbl == jump_lbl
Ian Lynagh's avatar
Ian Lynagh committed
676 677
                = CmmBranch top_id
        do_stmt stmt = stmt
678

Ian Lynagh's avatar
Ian Lynagh committed
679 680
        jump_lbl | tablesNextToCode = info_lbl
                 | otherwise        = entry_lbl
681 682 683 684 685 686

cmmLoopifyForC top = top

-- -----------------------------------------------------------------------------
-- Utils

Ian Lynagh's avatar
Ian Lynagh committed
687
isLit :: CmmExpr -> Bool
688 689 690 691 692
isLit (CmmLit _) = True
isLit _          = False

isComparisonExpr :: CmmExpr -> Bool
isComparisonExpr (CmmMachOp op _) = isComparisonMachOp op
Ian Lynagh's avatar
Ian Lynagh committed
693
isComparisonExpr _                  = False
694

Ian Lynagh's avatar
Ian Lynagh committed
695
isPicReg :: CmmExpr -> Bool
696
isPicReg (CmmReg (CmmGlobal PicBaseReg)) = True
697
isPicReg _ = False
698