Simon Jakobi pushed to branch wip/sjakobi/T27448 at Glasgow Haskell Compiler / GHC

Commits:

10 changed files:

Changes:

  • compiler/GHC/CmmToAsm/CFG.hs
    ... ... @@ -797,7 +797,7 @@ loopLevels cfg root = liLevels loopInfos
    797 797
           loopInfos = loopInfo cfg root
    
    798 798
     
    
    799 799
     data LoopInfo = LoopInfo
    
    800
    -  { liBackEdges :: [(Edge)] -- ^ List of back edges
    
    800
    +  { liBackEdges :: [(Edge)] -- ^ The edges whose target dominates their source
    
    801 801
       , liLevels :: LabelMap Int -- ^ BlockId -> LoopLevel mapping
    
    802 802
       , liLoops :: [(Edge, LabelSet)] -- ^ (backEdge, loopBody), body includes header
    
    803 803
       }
    
    ... ... @@ -840,15 +840,19 @@ loopInfo cfg root = LoopInfo { liBackEdges = backEdges
    840 840
         rooted = coerce (root, graph)
    
    841 841
         tree = coerce (Dom.domTree rooted) :: Tree BlockId
    
    842 842
     
    
    843
    -    -- Map from Nodes to their dominators
    
    843
    +    -- The dominators of each block, including the block itself.
    
    844 844
         domMap :: LabelMap LabelSet
    
    845
    -    domMap = mkDomMap tree
    
    845
    +    domMap = go setEmpty mapEmpty tree
    
    846
    +      where
    
    847
    +        go :: LabelSet -> LabelMap LabelSet -> Tree BlockId -> LabelMap LabelSet
    
    848
    +        go doms acc (Node lbl children)
    
    849
    +          = let !doms' = setInsert lbl doms
    
    850
    +            in  foldl' (go doms') (mapInsert lbl doms' acc) children
    
    846 851
     
    
    847 852
         edges = edgeList cfg :: [(BlockId, BlockId)]
    
    848 853
         -- We can't recompute nodes from edges, there might be blocks not connected via edges.
    
    849 854
         nodes = getCfgNodes cfg :: [BlockId]
    
    850 855
     
    
    851
    -    -- identify back edges
    
    852 856
         isBackEdge (from,to)
    
    853 857
           | Just doms <- mapLookup from domMap
    
    854 858
           , setMember to doms
    
    ... ... @@ -884,19 +888,6 @@ loopInfo cfg root = LoopInfo { liBackEdges = backEdges
    884 888
               loopCount n = length $ nub . map fst . filter (setMember n . snd) $ bodies
    
    885 889
           in  map (\n -> (n, loopCount n)) $ nodes :: [(BlockId, Int)]
    
    886 890
     
    
    887
    -    mkDomMap :: Tree BlockId -> LabelMap LabelSet
    
    888
    -    mkDomMap root = mapFromList $ go setEmpty root
    
    889
    -      where
    
    890
    -        go :: LabelSet -> Tree BlockId -> [(Label,LabelSet)]
    
    891
    -        go parents (Node lbl [])
    
    892
    -          =  [(lbl, parents)]
    
    893
    -        go parents (Node _ leaves)
    
    894
    -          = let nodes = map rootLabel leaves
    
    895
    -                entries = map (\x -> (x,parents)) nodes
    
    896
    -            in  entries ++ concatMap
    
    897
    -                            (\n -> go (setInsert (rootLabel n) parents) n)
    
    898
    -                            leaves
    
    899
    -
    
    900 891
     -- We make the CFG a Hoopl Graph, so we can reuse revPostOrder.
    
    901 892
     newtype BlockNode (e :: Extensibility) (x :: Extensibility) = BN (BlockId,[BlockId])
    
    902 893
     
    
    ... ... @@ -918,6 +909,13 @@ revPostorderFrom cfg root =
    918 909
         toNode bid =
    
    919 910
             BN (bid,getSuccessors cfg $ bid)
    
    920 911
     
    
    912
    +-- | A block's index in the reverse post order of its procedure, starting at
    
    913
    +-- 0 for the entry.
    
    914
    +type Vertex = Int
    
    915
    +
    
    916
    +type VertexMap = IntMap
    
    917
    +
    
    918
    +type VertexSet = IntSet
    
    921 919
     
    
    922 920
     -- | We take in a CFG which has on its edges weights which are
    
    923 921
     --   relative only to other edges originating from the same node.
    
    ... ... @@ -952,7 +950,7 @@ mkGlobalWeights root localCfg
    952 950
         blockFreqs' = mapFromList $ map (first fromVertex) (assocs blockFreqs) :: LabelMap Double
    
    953 951
         edgeFreqs' = fmap fromVertexMap $ fromVertexMap edgeFreqs
    
    954 952
     
    
    955
    -    fromVertexMap :: IM.IntMap x -> LabelMap x
    
    953
    +    fromVertexMap :: VertexMap x -> LabelMap x
    
    956 954
         fromVertexMap m = mapFromList . map (first fromVertex) $ IM.toList m
    
    957 955
     
    
    958 956
         revOrder = revPostorderFrom localCfg root :: [BlockId]
    
    ... ... @@ -972,13 +970,13 @@ mkGlobalWeights root localCfg
    972 970
         calcBody (backedge, blocks) =
    
    973 971
             (toVertex $ snd backedge, sort . map toVertex $ (setElems blocks))
    
    974 972
     
    
    975
    -    vertexMapping = mapFromList $ zip revOrder [0..] :: LabelMap Int
    
    976
    -    blockMapping = listArray (0,mapSize vertexMapping - 1) revOrder :: Array Int BlockId
    
    973
    +    vertexMapping = mapFromList $ zip revOrder [0..] :: LabelMap Vertex
    
    974
    +    blockMapping = listArray (0,mapSize vertexMapping - 1) revOrder :: Array Vertex BlockId
    
    977 975
         -- Map from blockId to indices starting at zero
    
    978
    -    toVertex :: BlockId -> Int
    
    976
    +    toVertex :: BlockId -> Vertex
    
    979 977
         toVertex   blockId  = expectJust $ mapLookup blockId vertexMapping
    
    980 978
         -- Map from indices starting at zero to blockIds
    
    981
    -    fromVertex :: Int -> BlockId
    
    979
    +    fromVertex :: Vertex -> BlockId
    
    982 980
         fromVertex vertex   = blockMapping ! vertex
    
    983 981
     
    
    984 982
     {- Note [Static Branch Prediction]
    
    ... ... @@ -1162,13 +1160,13 @@ staticBranchPrediction _root (LoopInfo l_backEdges loopLevels l_loops) cfg =
    1162 1160
     
    
    1163 1161
     -- We normalize all edge weights as probabilities between 0 and 1.
    
    1164 1162
     -- Ignoring rounding errors all outgoing edges sum up to 1.
    
    1165
    -cfgEdgeProbabilities :: CFG -> (BlockId -> Int) -> IM.IntMap (IM.IntMap Prob)
    
    1163
    +cfgEdgeProbabilities :: CFG -> (BlockId -> Vertex) -> VertexMap (VertexMap Prob)
    
    1166 1164
     cfgEdgeProbabilities cfg toVertex
    
    1167 1165
         = mapFoldlWithKey foldEdges IM.empty cfg
    
    1168 1166
       where
    
    1169 1167
         foldEdges = (\m from toMap -> IM.insert (toVertex from) (normalize toMap) m)
    
    1170 1168
     
    
    1171
    -    normalize :: (LabelMap EdgeInfo) -> (IM.IntMap Prob)
    
    1169
    +    normalize :: (LabelMap EdgeInfo) -> (VertexMap Prob)
    
    1172 1170
         normalize weightMap
    
    1173 1171
             | edgeCount <= 1 = mapFoldlWithKey (\m k _ -> IM.insert (toVertex k) 1.0 m) IM.empty weightMap
    
    1174 1172
             | otherwise = mapFoldlWithKey (\m k _ -> IM.insert (toVertex k) (normalWeight k) m) IM.empty weightMap
    
    ... ... @@ -1189,14 +1187,28 @@ cfgEdgeProbabilities cfg toVertex
    1189 1187
              = w/totalWeight
    
    1190 1188
              | otherwise = panic "impossible"
    
    1191 1189
     
    
    1190
    +-- | Compute how often each block runs and each edge is taken per invocation
    
    1191
    +-- of the procedure, given the probabilities of the edges.
    
    1192
    +--
    
    1192 1193
     -- This is the fixpoint algorithm from
    
    1193 1194
     --   "Static Branch Prediction and Program Profile Analysis" by Y Wu, JR Larus
    
    1194 1195
     -- The adaption to Haskell is my own.
    
    1195
    -calcFreqs :: IM.IntMap (IM.IntMap Prob) -> [(Int,Int)] -> [(Int, [Int])] -> [Int]
    
    1196
    -          -> (Array Int Double, IM.IntMap (IM.IntMap Prob))
    
    1196
    +calcFreqs :: VertexMap (VertexMap Prob)
    
    1197
    +          -- ^ Edge probabilities, by source and target. The probabilities of
    
    1198
    +          -- a block's outgoing edges sum to 1.
    
    1199
    +          -> [(Vertex, Vertex)]
    
    1200
    +          -- ^ The back edges, as (source, target)
    
    1201
    +          -> [(Vertex, [Vertex])]
    
    1202
    +          -- ^ For each back edge, its target (the loop header) and the body
    
    1203
    +          -- of its loop. The body includes the header and is in reverse post
    
    1204
    +          -- order.
    
    1205
    +          -> [Vertex]
    
    1206
    +          -- ^ All blocks in reverse post order, so the entry comes first
    
    1207
    +          -> (Array Vertex Double, VertexMap (VertexMap Prob))
    
    1208
    +          -- ^ Block frequencies, and edge frequencies by source and target
    
    1197 1209
     calcFreqs graph backEdges loops revPostOrder = runST $ do
    
    1198
    -    visitedNodes <- newArray (0,nodeCount-1) False :: ST s (STUArray s Int Bool)
    
    1199
    -    blockFreqs <- newArray (0,nodeCount-1) 0.0 :: ST s (STUArray s Int Double)
    
    1210
    +    (visitedNodes :: STUArray s Vertex Bool) <- newArray (0,nodeCount-1) False
    
    1211
    +    (blockFreqs :: STUArray s Vertex Double) <- newArray (0,nodeCount-1) 0.0
    
    1200 1212
         edgeProbs <- newSTRef graph
    
    1201 1213
         edgeBackProbs <- newSTRef graph
    
    1202 1214
     
    
    ... ... @@ -1207,11 +1219,13 @@ calcFreqs graph backEdges loops revPostOrder = runST $ do
    1207 1219
         let  -- See #1600, we need to inline or unboxing makes perf worse.
    
    1208 1220
             -- {-# INLINE getFreq #-}
    
    1209 1221
             {-# INLINE visited #-}
    
    1222
    +        visited :: Vertex -> ST s Bool
    
    1210 1223
             visited b = unsafeRead visitedNodes b
    
    1224
    +        getFreq :: Vertex -> ST s Double
    
    1211 1225
             getFreq b = unsafeRead blockFreqs b
    
    1212
    -        -- setFreq :: forall s. Int -> Double -> ST s ()
    
    1226
    +        setFreq :: Vertex -> Double -> ST s ()
    
    1213 1227
             setFreq b f = unsafeWrite blockFreqs b f
    
    1214
    -        -- setVisited :: forall s. Node -> ST s ()
    
    1228
    +        setVisited :: Vertex -> ST s ()
    
    1215 1229
             setVisited b = unsafeWrite visitedNodes b True
    
    1216 1230
             -- Frequency/probability that edge is taken.
    
    1217 1231
             getProb' arr b1 b2 = readSTRef arr >>=
    
    ... ... @@ -1238,10 +1252,10 @@ calcFreqs graph backEdges loops revPostOrder = runST $ do
    1238 1252
             setBackProb b1 b2 = setProb' edgeBackProbs b1 b2
    
    1239 1253
     
    
    1240 1254
     
    
    1241
    -    let -- calcOutFreqs :: Node -> ST s ()
    
    1255
    +    let calcOutFreqs :: Vertex -> Vertex -> ST s ()
    
    1242 1256
             calcOutFreqs bhead block = do
    
    1243 1257
               !f <- getFreq block
    
    1244
    -          forM (successors block) $ \bi -> do
    
    1258
    +          forM_ (successors block) $ \bi -> do
    
    1245 1259
                 let !prob = getProb block bi
    
    1246 1260
                 let !succFreq = f * prob
    
    1247 1261
                 setEdgeFreq block bi succFreq
    
    ... ... @@ -1249,7 +1263,8 @@ calcFreqs graph backEdges loops revPostOrder = runST $ do
    1249 1263
                 when (bi == bhead) $ setBackProb block bi succFreq
    
    1250 1264
     
    
    1251 1265
     
    
    1252
    -    let propFreq block head = do
    
    1266
    +    let propFreq :: Vertex -> Vertex -> ST s ()
    
    1267
    +        propFreq block head = do
    
    1253 1268
                 -- traceM ("prop:" ++ show (block,head))
    
    1254 1269
                 -- traceShowM block
    
    1255 1270
     
    
    ... ... @@ -1290,13 +1305,17 @@ calcFreqs graph backEdges loops revPostOrder = runST $ do
    1290 1305
                 setVisited block
    
    1291 1306
                 calcOutFreqs head block
    
    1292 1307
     
    
    1293
    -    -- Loops, by nesting, inner to outer
    
    1308
    +    -- One pass per loop. Each pass sets the probabilities of its loop's back
    
    1309
    +    -- edges, which the passes of the enclosing loops then read.
    
    1310
    +    -- FIXME: 'loops' is not ordered inner first.
    
    1294 1311
         forM_ loops $ \(head, body) -> do
    
    1295 1312
             forM_ [0 .. nodeCount - 1] (\i -> unsafeWrite visitedNodes i True) -- Mark all nodes as visited.
    
    1296 1313
             forM_ body (\i -> unsafeWrite visitedNodes i False) -- Mark all blocks reachable from head as not visited
    
    1297 1314
             forM_ body $ \block -> propFreq block head
    
    1298 1315
     
    
    1299
    -    -- After dealing with all loops, deal with non-looping parts of the CFG
    
    1316
    +    -- The whole procedure, using the back edge probabilities from the loop passes.
    
    1317
    +    -- FIXME: The entry gets frequency 1 even when an edge leads back to it,
    
    1318
    +    -- which makes every frequency too low by the same factor.
    
    1300 1319
         forM_ [0 .. nodeCount - 1] (\i -> unsafeWrite visitedNodes i False) -- Everything in revPostOrder is reachable
    
    1301 1320
         forM_ revPostOrder $ \block -> propFreq block (head revPostOrder)
    
    1302 1321
     
    
    ... ... @@ -1310,14 +1329,14 @@ calcFreqs graph backEdges loops revPostOrder = runST $ do
    1310 1329
         return (freqs', graph')
    
    1311 1330
       where
    
    1312 1331
         -- How can these lookups fail? Consider the CFG [A -> B]
    
    1313
    -    predecessors :: Int -> IS.IntSet
    
    1332
    +    predecessors :: Vertex -> VertexSet
    
    1314 1333
         predecessors b = fromMaybe IS.empty $ IM.lookup b revGraph
    
    1315
    -    successors :: Int -> [Int]
    
    1334
    +    successors :: Vertex -> [Vertex]
    
    1316 1335
         successors b = fromMaybe (lookupError "succ" b graph)$ IM.keys <$> IM.lookup b graph
    
    1317 1336
         lookupError s b g = pprPanic ("Lookup error " ++ s) $
    
    1318 1337
                                 ( text "node" <+> ppr b $$
    
    1319 1338
                                     text "graph" <+>
    
    1320
    -                                vcat (map (\(k,m) -> ppr (k,m :: IM.IntMap Double)) $ IM.toList g)
    
    1339
    +                                vcat (map (\(k,m) -> ppr (k,m :: VertexMap Double)) $ IM.toList g)
    
    1321 1340
                                 )
    
    1322 1341
     
    
    1323 1342
         nodeCount = IM.foldl' (\count toMap -> IM.foldlWithKey' countTargets (count + 1) toMap) 0 graph
    
    ... ... @@ -1328,7 +1347,7 @@ calcFreqs graph backEdges loops revPostOrder = runST $ do
    1328 1347
         isBackEdge from to = S.member (from,to) backEdgeSet
    
    1329 1348
         backEdgeSet = S.fromList backEdges
    
    1330 1349
     
    
    1331
    -    revGraph :: IntMap IntSet
    
    1350
    +    revGraph :: VertexMap VertexSet
    
    1332 1351
         revGraph = IM.foldlWithKey' (\m from toMap -> addEdges m from toMap) IM.empty graph
    
    1333 1352
             where
    
    1334 1353
                 addEdges m0 from toMap = IM.foldlWithKey' (\m k _ -> addEdge m from k) m0 toMap
    

  • testsuite/tests/cmm/should_compile/T28083.cmm
    1
    +#include "Cmm.h"
    
    2
    +
    
    3
    +// The entry is a bare goto, so the Cmm control-flow optimiser makes L the
    
    4
    +// entry, heading the loop L -> B -> L. Expected: L -> B outweighs the exit
    
    5
    +// edge. Without loop detection they tie.
    
    6
    +stg_loop {
    
    7
    +  goto L;
    
    8
    +L:
    
    9
    +  if (R1 > 0) { goto B; }
    
    10
    +  jump stg_loop [R1];
    
    11
    +B:
    
    12
    +  R1 = R1 - 1;
    
    13
    +  goto L;
    
    14
    +}

  • testsuite/tests/cmm/should_compile/T28083.stderr
    1
    +==================== CFG Weights - Final ====================
    
    2
    +stg_loop:
    
    3
    +digraph {
    
    4
    +	c1 -> c4[label="0.25000",weight="0.25000"];
    
    5
    +	c1 -> c2[label="0.75000",weight="0.75000"];
    
    6
    +	c2 -> c1[label="0.75000",weight="0.75000"];
    
    7
    +}

  • testsuite/tests/cmm/should_compile/T28093.cmm
    1
    +#include "Cmm.h"
    
    2
    +
    
    3
    +// S is a self-loop that dominates the exit block, so it is not a leaf of
    
    4
    +// the dominator tree. The entry does work, so it isn't merged into S.
    
    5
    +// Expected: the self edge outweighs the exit edge. Without loop detection
    
    6
    +// both get weight 0.
    
    7
    +stg_self {
    
    8
    +  R1 = R1 + 1;
    
    9
    +  goto S;
    
    10
    +S:
    
    11
    +  R1 = R1 - 1;
    
    12
    +  if (R1 > 0) { goto S; }
    
    13
    +  jump stg_self [R1];
    
    14
    +}

  • testsuite/tests/cmm/should_compile/T28093.stderr
    1
    +==================== CFG Weights - Final ====================
    
    2
    +stg_self:
    
    3
    +digraph {
    
    4
    +	c1 -> c4[label="1.00000",weight="1.00000"];
    
    5
    +	c5 -> c1[label="1.00000",weight="1.00000"];
    
    6
    +	c1 -> c1[label="7.00000",weight="7.00000"];
    
    7
    +}

  • testsuite/tests/cmm/should_compile/T28093_cas.cmm
    1
    +#include "Cmm.h"
    
    2
    +
    
    3
    +// On x86-64 the atomic or is a compare-and-swap loop: a block added by the
    
    4
    +// NCG with a self edge of weight 0. That block dominates the loop L -> B -> L.
    
    5
    +// Expected: the loop's edges outweigh its exit edge. Without the self edge
    
    6
    +// counting as a back edge, every edge after the atomic op gets weight 0.
    
    7
    +stg_cas {
    
    8
    +  W_ old;
    
    9
    +  (old) = prim %fetch_or64(R2, 1 :: I64);
    
    10
    +  goto L;
    
    11
    +L:
    
    12
    +  if (R1 > 0) { goto B; }
    
    13
    +  jump stg_cas [R1, R2];
    
    14
    +B:
    
    15
    +  R1 = R1 - 1;
    
    16
    +  goto L;
    
    17
    +}

  • testsuite/tests/cmm/should_compile/T28093_cas.stderr
    1
    +==================== CFG Weights - Final ====================
    
    2
    +stg_cas:
    
    3
    +digraph {
    
    4
    +	c4 -> c7[label="1.00000",weight="1.00000"];
    
    5
    +	c9 -> n1[label="1.00000",weight="1.00000"];
    
    6
    +	n1 -> n2[label="1.00000",weight="1.00000"];
    
    7
    +	n2 -> c4[label="1.00000",weight="1.00000"];
    
    8
    +	c4 -> c5[label="3.00000",weight="3.00000"];
    
    9
    +	c5 -> c4[label="3.00000",weight="3.00000"];
    
    10
    +	n1 -> n1[label="7.00000",weight="7.00000"];
    
    11
    +}

  • testsuite/tests/cmm/should_compile/all.T
    ... ... @@ -2,6 +2,14 @@ setTestOpts(
    2 2
       [ req_cmm
    
    3 3
       ])
    
    4 4
     
    
    5
    +def final_cfg_weights(s):
    
    6
    +  """
    
    7
    +  The edge weights of the final CFG, without the block labels, which
    
    8
    +  depend on uniques.
    
    9
    +  """
    
    10
    +  final = s.split('CFG Weights - Final')[-1]
    
    11
    +  return '\n'.join(re.findall(r'weight="([^"]*)"', final))
    
    12
    +
    
    5 13
     test('selfloop', [cmm_src], compile, ['-no-hs-main'])
    
    6 14
     test('cmm_sink_sp', [ only_ways(['optasm']),
    
    7 15
                           grep_errmsg(r'(\[Sp.*\]).*(=).*(\[.*R1.*\]).*;',[1,2,3]),
    
    ... ... @@ -11,6 +19,21 @@ test('T16930', normal, makefile_test, ['T16930'])
    11 19
     test('T17442', normal, compile, [''])
    
    12 20
     test('T20725', normal, compile, ['-package ghc'])
    
    13 21
     test('T23610', normal, makefile_test, ['T23610'])
    
    22
    +test('T28083', [cmm_src, only_ways(['optasm']),
    
    23
    +                unless(arch('x86_64'), skip),
    
    24
    +                when(leading_underscore(), skip),
    
    25
    +                normalise_errmsg_fun(final_cfg_weights)],
    
    26
    +     compile, ['-no-hs-main -ddump-cfg-weights'])
    
    27
    +test('T28093', [cmm_src, only_ways(['optasm']),
    
    28
    +                unless(arch('x86_64'), skip),
    
    29
    +                when(leading_underscore(), skip),
    
    30
    +                normalise_errmsg_fun(final_cfg_weights)],
    
    31
    +     compile, ['-no-hs-main -ddump-cfg-weights'])
    
    32
    +test('T28093_cas', [cmm_src, only_ways(['optasm']),
    
    33
    +                    unless(arch('x86_64'), skip),
    
    34
    +                    when(leading_underscore(), skip),
    
    35
    +                    normalise_errmsg_fun(final_cfg_weights)],
    
    36
    +     compile, ['-no-hs-main -ddump-cfg-weights'])
    
    14 37
     test('T24224', [cmm_src, grep_errmsg(r'(F64.*);', [1]), only_ways(['normal'])], compile, ['-no-hs-main -ddump-cmm -dsuppress-all -dsuppress-uniques'])
    
    15 38
     test('T24474', cmm_src, compile, ['-optc-g3'])
    
    16 39
     # Grep for a `... = + .. 42 ..;` occurence from within the dead code block in the cmm dump output.
    

  • testsuite/tests/perf/compiler/all.T
    ... ... @@ -38,6 +38,17 @@ test('T3294',
    38 38
          compile,
    
    39 39
          [''])
    
    40 40
     
    
    41
    +test('CmmDiamondChain',
    
    42
    +     [ only_ways(['optasm']),
    
    43
    +       unless(have_ncg(), skip),
    
    44
    +       cmm_src,
    
    45
    +       collect_compiler_stats('bytes allocated', 2),
    
    46
    +       pre_cmd('./genCmmDiamondChain'),
    
    47
    +       extra_files(['genCmmDiamondChain']),
    
    48
    +     ],
    
    49
    +     compile,
    
    50
    +     ['-O2 -v0'])
    
    51
    +
    
    41 52
     test('T4801',
    
    42 53
          [collect_compiler_runtime(2),
    
    43 54
           only_ways(['normal']),
    

  • testsuite/tests/perf/compiler/genCmmDiamondChain
    1
    +#!/usr/bin/env bash
    
    2
    +set -euo pipefail
    
    3
    +
    
    4
    +# Generate a Cmm source file that is heavy on control flow.
    
    5
    +#
    
    6
    +# It produces thousands of basic blocks in a single Cmm graph,
    
    7
    +# stressing the control-flow handling of the NCG and Wasm backends.
    
    8
    +#
    
    9
    +# With the default knobs, the procedure looks like this:
    
    10
    +#
    
    11
    +#          entry
    
    12
    +#            |
    
    13
    +#            v
    
    14
    +#   .---> split0                    \
    
    15
    +#   |     /    \                     |
    
    16
    +#   |  left0   right0                |  stage 0
    
    17
    +#   |     \    /                     |
    
    18
    +#   |     join0                     /
    
    19
    +#   |       |
    
    20
    +#   |       v
    
    21
    +#   |    split1 ... join15             stages 1 to 15
    
    22
    +#   |       |
    
    23
    +#   |       v
    
    24
    +#   '---- latch0                       trip0 < 2: back to split0
    
    25
    +#           |
    
    26
    +#           v
    
    27
    +#   .---> split16 ... join31           chunk 1, same shape
    
    28
    +#   |       |
    
    29
    +#   '---- latch1
    
    30
    +#           |
    
    31
    +#           v
    
    32
    +#          ...
    
    33
    +#           |
    
    34
    +#           v
    
    35
    +#        latch127                      last chunk returns acc
    
    36
    +#
    
    37
    +# The variables acc and mix stay live through the whole procedure, and
    
    38
    +# every branch condition reads mix, so no stage can be folded away.
    
    39
    +# The two arms of a diamond swap their constants, so that common block
    
    40
    +# elimination cannot merge them.
    
    41
    +#
    
    42
    +# Each trip counter is set in the entry block and read only at its own
    
    43
    +# latch, so all of them start out live and the procedure spills heavily.
    
    44
    +#
    
    45
    +# Tuning knobs:
    
    46
    +#   STAGES       Number of diamond stages to generate. Default: 2048
    
    47
    +#   LOOP_PERIOD  Number of stages per loop chunk. Default: 16
    
    48
    +#   OUT          Output file. Default: CmmDiamondChain.cmm
    
    49
    +#
    
    50
    +# Run with STAGES=2 LOOP_PERIOD=2 for a small example of the output.
    
    51
    +
    
    52
    +: "${STAGES:=2048}"
    
    53
    +: "${LOOP_PERIOD:=16}"
    
    54
    +: "${OUT:=CmmDiamondChain.cmm}"
    
    55
    +
    
    56
    +(( STAGES > 0 && LOOP_PERIOD > 0 )) || {
    
    57
    +  echo "STAGES and LOOP_PERIOD must be positive integers" >&2
    
    58
    +  exit 1
    
    59
    +}
    
    60
    +
    
    61
    +chunk_count=$(( (STAGES + LOOP_PERIOD - 1) / LOOP_PERIOD ))
    
    62
    +block_count=$(( 1 + 4 * STAGES + chunk_count ))
    
    63
    +
    
    64
    +emit() {
    
    65
    +  printf '%s\n' "$*"
    
    66
    +}
    
    67
    +
    
    68
    +{
    
    69
    +  emit "// Generated by genCmmDiamondChain"
    
    70
    +  emit "//"
    
    71
    +  emit "// Parameters:"
    
    72
    +  emit "//   STAGES=${STAGES}"
    
    73
    +  emit "//   LOOP_PERIOD=${LOOP_PERIOD}"
    
    74
    +  emit "//"
    
    75
    +  emit "// Cmm blocks: ${block_count}"
    
    76
    +  emit "#include \"Cmm.h\""
    
    77
    +  emit
    
    78
    +  emit "diamond_chain (W_ seed) {"
    
    79
    +  emit "  W_ acc;"
    
    80
    +  emit "  W_ mix;"
    
    81
    +  for ((chunk = 0; chunk < chunk_count; chunk++)); do
    
    82
    +    emit "  W_ trip${chunk};"
    
    83
    +  done
    
    84
    +  emit
    
    85
    +  emit "entry:"
    
    86
    +  emit "  acc = seed;"
    
    87
    +  emit "  mix = seed + (17 :: W_);"
    
    88
    +  for ((chunk = 0; chunk < chunk_count; chunk++)); do
    
    89
    +    emit "  trip${chunk} = 0;"
    
    90
    +  done
    
    91
    +  emit "  goto split0;"
    
    92
    +  emit
    
    93
    +
    
    94
    +  for ((stage = 0; stage < STAGES; stage++)); do
    
    95
    +    next_stage=$(( stage + 1 ))
    
    96
    +    chunk=$(( stage / LOOP_PERIOD ))
    
    97
    +    k1=$(( 4 * stage + 1 ))
    
    98
    +    k2=$(( 4 * stage + 2 ))
    
    99
    +    k3=$(( 4 * stage + 3 ))
    
    100
    +    k4=$(( 4 * stage + 4 ))
    
    101
    +
    
    102
    +    emit "split${stage}:"
    
    103
    +    emit "  mix = mix + (${k1} :: W_);"
    
    104
    +    emit "  if (((mix + (${k2} :: W_)) % (7 :: W_)) < (3 :: W_)) {"
    
    105
    +    emit "    goto left${stage};"
    
    106
    +    emit "  }"
    
    107
    +    emit "  goto right${stage};"
    
    108
    +    emit
    
    109
    +
    
    110
    +    emit "left${stage}:"
    
    111
    +    emit "  acc = acc + (${k3} :: W_);"
    
    112
    +    emit "  mix = mix + (${k4} :: W_);"
    
    113
    +    emit "  goto join${stage};"
    
    114
    +    emit
    
    115
    +
    
    116
    +    emit "right${stage}:"
    
    117
    +    emit "  acc = acc + (${k4} :: W_);"
    
    118
    +    emit "  mix = mix + (${k3} :: W_);"
    
    119
    +    emit "  goto join${stage};"
    
    120
    +    emit
    
    121
    +
    
    122
    +    emit "join${stage}:"
    
    123
    +    emit "  acc = acc + mix + (${k1} :: W_);"
    
    124
    +    if (( next_stage == STAGES || next_stage % LOOP_PERIOD == 0 )); then
    
    125
    +      emit "  goto latch${chunk};"
    
    126
    +    else
    
    127
    +      emit "  goto split${next_stage};"
    
    128
    +    fi
    
    129
    +    emit
    
    130
    +  done
    
    131
    +
    
    132
    +  for ((chunk = 0; chunk < chunk_count; chunk++)); do
    
    133
    +    loop_start=$(( chunk * LOOP_PERIOD ))
    
    134
    +    next_stage=$(( (chunk + 1) * LOOP_PERIOD ))
    
    135
    +    latch_mix=$(( 1000000 + chunk ))
    
    136
    +    latch_acc=$(( 2000000 + chunk ))
    
    137
    +
    
    138
    +    emit "latch${chunk}:"
    
    139
    +    emit "  trip${chunk} = trip${chunk} + (1 :: W_);"
    
    140
    +    emit "  mix = mix + (${latch_mix} :: W_);"
    
    141
    +    emit "  acc = acc + (${latch_acc} :: W_);"
    
    142
    +    emit "  if (trip${chunk} < (2 :: W_)) {"
    
    143
    +    emit "    goto split${loop_start};"
    
    144
    +    emit "  }"
    
    145
    +    if (( next_stage < STAGES )); then
    
    146
    +      emit "  goto split${next_stage};"
    
    147
    +    else
    
    148
    +      emit "  return (acc);"
    
    149
    +    fi
    
    150
    +    emit
    
    151
    +  done
    
    152
    +
    
    153
    +  emit "}"
    
    154
    +} > "$OUT"