@@ -343,6 +343,7 @@ def shard_loads(body: Tuple[Stmt, ...], scratch: Callable[[], object], *,
343343 threads : int , fptype : Datatype , static : bool = True ,
344344 stream : bool = False ,
345345 aligns : Optional [Mapping [str , int ]] = None ,
346+ extents : Optional [Mapping [str , int ]] = None ,
346347 report : Optional [List [str ]] = None ) -> Tuple [Stmt , ...]:
347348 """`body` with the shards that fit into `budget` elements of shared
348349 memory read from there.
@@ -357,8 +358,10 @@ def shard_loads(body: Tuple[Stmt, ...], scratch: Callable[[], object], *,
357358 every multiplication of the block takes together. Both are held under
358359 the one budget. `aligns` is what the caller proves of the operands'
359360 bases, in bytes, by the name of their binding: how wide the copies may
360- read them. `report` collects a line per operand: `+` and how much of it
361- is held, `-` and why nothing is.
361+ read them. `extents` is how many elements one of them is stored over,
362+ by the same name, where that is more than its binding's type says
363+ (`_extents`). `report` collects a line per operand: `+` and how much of
364+ it is held, `-` and why nothing is.
362365 """
363366 def note (line : str ) -> None :
364367 if report is not None :
@@ -371,10 +374,11 @@ def note(line: str) -> None:
371374 note (f'- { len (loops )} batch loops in the body, where one is held' )
372375 return body
373376 at = loops [0 ]
374- loads = (_candidates (body , at , threads , mults , fptype , note ) if static
375- else [])
377+ reach = _extents (body , extents or {})
378+ loads = (_candidates (body , at , threads , mults , fptype , reach , note )
379+ if static else [])
376380 if stream :
377- loads += _streamed (body , at , threads , mults , fptype , note )
381+ loads += _streamed (body , at , threads , mults , fptype , reach , note )
378382 shards = _shards (loads )
379383 held = _choose (shards , budget , align )
380384 if not held :
@@ -408,8 +412,49 @@ def _first_reads(stmts: Tuple[Stmt, ...]) -> Dict[int, int]:
408412 return out
409413
410414
415+ def _extents (body : Tuple [Stmt , ...],
416+ extents : Mapping [str , int ]) -> Dict [int , int ]:
417+ """How many elements the buffers in `body` are stored over, by value,
418+ where the caller knows better than their types: an operand bound ahead
419+ of the batch loop by the name of its binding (`extents`), and a pointer
420+ chosen among such operands -- a merged run's member, through its table --
421+ by the largest of them.
422+
423+ A binding is typed when it is bound, from the box, and a multiplication
424+ may store its operand in an order of its own after that
425+ (`storage_order`): two lead slots of a lane as a pair, the rows padded to
426+ the lanes, longer than the box. A shard clamped to the type would leave
427+ out what the loads read past it."""
428+ out : Dict [int , int ] = {}
429+ for s in walk_stmts (body ):
430+ if len (s .target ) != 1 or not isinstance (s .target [0 ].type , BufferType ):
431+ continue
432+ # A merged run's binding has a name of its own as well, the stand-in's,
433+ # whose box the members' orders do not reach the stand-in through.
434+ known = [extents [s .attr ('extern' )]] if s .attr ('extern' ) in extents \
435+ else []
436+ sources = [a for a in s .args if isinstance (a , Value )
437+ and isinstance (a .type , BufferType )]
438+ if (s .op is Op .RAWEXPR and sources
439+ and all (a .id in out for a in sources )):
440+ known .append (max (out [a .id ] for a in sources ))
441+ if known :
442+ out [s .target [0 ].id ] = max (known )
443+ return out
444+
445+
446+ def _within (buffer : Value , span : Tuple [int , int , bool ],
447+ reach : Mapping [int , int ]) -> Optional [Tuple [int , int ]]:
448+ """`span` clamped to what `buffer` is stored over -- the elements a load
449+ reads past it belong to lanes its guard leaves out -- or None where
450+ nothing of it is left."""
451+ last = max (buffer .type .volume , reach .get (buffer .id , 0 )) - 1
452+ lo , hi = max (0 , span [0 ]), min (span [1 ], last )
453+ return (lo , hi ) if lo <= hi else None
454+
455+
411456def _candidates (body , at : int , threads : int , mults : int , fptype : Datatype ,
412- note ) -> List [_Load ]:
457+ reach : Mapping [ int , int ], note ) -> List [_Load ]:
413458 """The loads of the loop at `at` that read a batch-constant operand at
414459 an index known per thread and varying over the lanes, each with the
415460 span it reads."""
@@ -443,13 +488,17 @@ def _candidates(body, at: int, threads: int, mults: int, fptype: Datatype,
443488 continue
444489 if span is None :
445490 continue
491+ held = _within (buffer , span , reach )
492+ if held is None :
493+ why = 'an index past the end of the operand'
494+ refused [why ] = refused .get (why , 0 ) + 1
495+ continue
446496 first = reads .get (id (stmts ))
447497 if first is None :
448498 first = reads [id (stmts )] = _first_reads (stmts )
449499 cover = first .get (stmt .target [0 ].id , len (stmts )) - n - 1
450- out .append (_Load (stmt , buffer , max (0 , span [0 ]),
451- min (span [1 ], buffer .type .volume - 1 ), cover ,
452- position , span [2 ]))
500+ out .append (_Load (stmt , buffer , held [0 ], held [1 ], cover , position ,
501+ span [2 ]))
453502 for why , count in sorted (refused .items ()):
454503 note (f'- { count } load(s): { why } ' )
455504 return out
@@ -492,7 +541,7 @@ def _members(trip: Stmt, bound: Mapping[int, Value],
492541
493542
494543def _streamed (body , at : int , threads : int , mults : int , fptype : Datatype ,
495- note ) -> List [_Load ]:
544+ reach : Mapping [ int , int ], note ) -> List [_Load ]:
496545 """The loads of a merged run's members (`_members`), each with the span
497546 one trip reads -- the same for every trip, since only the member moves.
498547
@@ -547,13 +596,17 @@ def _streamed(body, at: int, threads: int, mults: int, fptype: Datatype,
547596 continue
548597 if span is None :
549598 continue
599+ held = _within (buffer , span , reach )
600+ if held is None :
601+ why = 'an index past the end of the operand'
602+ refused [why ] = refused .get (why , 0 ) + 1
603+ continue
550604 first = reads .get (id (stmts ))
551605 if first is None :
552606 first = reads [id (stmts )] = _first_reads (stmts )
553607 cover = first .get (stmt .target [0 ].id , len (stmts )) - n - 1
554- out .append (_Load (stmt , buffer , max (0 , span [0 ]),
555- min (span [1 ], buffer .type .volume - 1 ), cover ,
556- position , span [2 ], trip = trip ))
608+ out .append (_Load (stmt , buffer , held [0 ], held [1 ], cover , position ,
609+ span [2 ], trip = trip ))
557610 for why , count in sorted (refused .items ()):
558611 note (f'- { count } member load(s): { why } ' )
559612 return out
@@ -744,11 +797,24 @@ def _copies(placed: List[Tuple[_Shard, int]]) -> List[_Copy]:
744797 return out
745798
746799
800+ #: Passes over the block a copy is written out to rather than looped over
801+ #: (`_stage`). The loop runs by lane -- its trips are `flat`'s -- so the
802+ #: compiler cannot count the loads in flight and waits on each one before its
803+ #: store: a round trip to memory a pass, twelve at the head of every trip of
804+ #: SeisSol's order-8 `localFluxAll` on gfx942. Written out, the passes'
805+ #: loads are in flight together. Past this many the loop stays, its code
806+ #: size the bound.
807+ UNROLL = 16
808+
809+
747810def _stage (b , operand : Value , buf : Value , copy : _Copy , flat : Value ,
748811 block : int , width : int = 1 ) -> None :
749812 """`copy` by the threads of the block, `flat` the thread's place among
750813 them: each thread its share of `block` accesses of `width` elements
751- (`_width`), under a guard where the block covers the copy at once."""
814+ (`_width`), under a guard where the block covers the copy at once, and
815+ written out pass by pass where it takes up to `UNROLL` passes -- every
816+ load ahead of the stores, and the lanes past the end of the last pass on
817+ their access of the first."""
752818 def plus (a : Value , c , hint : str ) -> Value :
753819 if isinstance (c , int ) and c == 0 :
754820 return a
@@ -768,29 +834,58 @@ def at(i: Value, k: Optional[Value], start: int, step: int,
768834 elem = operand .type .elem
769835 wide = ScalarType (elem , width ) if width > 1 else None
770836
771- def one (u : Value ) -> None :
837+ nbytes = width * elem .size ()
838+
839+ def place (u : Value ) -> Tuple [Value , Value ]:
772840 # Access `u` moves elements `width * u` on, which never straddle a
773841 # run: `width` divides every run's length.
774842 i = u if width == 1 else b .op ('mul' , INDEX , u , width , hint = 'e' )
775843 k = (b .op ('div' , INDEX , i , copy .count , hint = 'k' )
776844 if copy .times > 1 else None )
777- src = at (i , k , copy .src , copy .src_step , 'g' )
778- dst = at (i , k , copy .dst , copy .dst_step , 'l' )
845+ return (at (i , k , copy .src , copy .src_step , 'g' ),
846+ at (i , k , copy .dst , copy .dst_step , 'l' ))
847+
848+ def fetch (src : Value ) -> Value :
849+ if wide is None :
850+ return b .load (operand , src , hint = 'sh' )
851+ return b .load (operand , src , type_ = wide , align = nbytes , hint = 'sh' )
852+
853+ def put (dst : Value , value : Value ) -> None :
779854 if wide is None :
780- b .store (buf , b .load (operand , src , hint = 'sh' ), dst )
781- return
782- nbytes = width * elem .size ()
783- b .store (buf , b .load (operand , src , type_ = wide , align = nbytes ,
784- hint = 'sh' ), dst , align = nbytes )
855+ b .store (buf , value , dst )
856+ else :
857+ b .store (buf , value , dst , align = nbytes )
858+
859+ def one (u : Value ) -> None :
860+ src , dst = place (u )
861+ put (dst , fetch (src ))
785862
786863 units = copy .total // width
787864 if units <= block :
788865 with b .if_ (b .op ('lt' , BOOL , flat , units , hint = 's' )):
789866 one (flat )
790867 return
791- with b .for_ (flat , units , block , hint = 's' ,
792- uniform = Uniformity .LANE ) as f :
793- one (f .induction )
868+ passes = - (- units // block )
869+ if passes > UNROLL :
870+ with b .for_ (flat , units , block , hint = 's' ,
871+ uniform = Uniformity .LANE ) as f :
872+ one (f .induction )
873+ return
874+ fetched = []
875+ for p in range (passes ):
876+ u = plus (flat , p * block , 's' )
877+ if (p + 1 ) * block > units :
878+ # The last pass, which some lanes are past the end of. They take
879+ # their access of the first pass again -- the same value to the
880+ # same place, by the same lane, so no other lane's write races it
881+ # -- rather than branch: a guard around the store would draw the
882+ # load in behind it and wait on it there.
883+ u = b .op ('select' , INDEX , b .op ('lt' , BOOL , u , units , hint = 's' ),
884+ u , flat , hint = 's' )
885+ src , dst = place (u )
886+ fetched .append ((dst , fetch (src )))
887+ for dst , value in fetched :
888+ put (dst , value )
794889
795890
796891def _alignments (body : Tuple [Stmt , ...], at : int ,
0 commit comments