Author Topic: Block copy instructions  (Read 23079 times)

0 Members and 1 Guest are viewing this topic.

Offline DiTBho

  • Super Contributor
  • ***
  • Posts: 5121
  • Country: gb
Re: Block copy instructions
« Reply #25 on: January 14, 2021, 10:34:27 am »
[..] zero copy APIs [..]

That's what is written in the first chapter of "Optimizing MIPS code" Book ;D

The opposite of courage is not cowardice, it is conformity. Even a dead fish can go with the flow
 

Online tggzzz

  • Super Contributor
  • ***
  • Posts: 23122
  • Country: gb
  • Numbers, not adjectives
    • Having fun doing more, with less
Re: Block copy instructions
« Reply #26 on: January 14, 2021, 11:09:39 am »
The general solution if copying is the performance bottleneck, is to completely eliminate the need to copy. AKA Zero-copy.

Most modern OS's have zero copy APIs for things like files and networking.

That solution can easily bring its own problems, e.g. aliasing (and not being able to prove the absence of aliasing), ownership, memory reclamation.

Language support helps, and it absence hinders optimisation and correctness.
There are lies, damned lies, statistics - and ADC/DAC specs.
Glider pilot's aphorism: "there is no substitute for span". Retort: "There is a substitute: skill+imagination. But you can buy span".
Having fun doing more, with less
 

Offline Nominal Animal

  • Super Contributor
  • ***
  • Posts: 8354
  • Country: fi
    • My home page and email address
Re: Block copy instructions
« Reply #27 on: January 14, 2021, 11:15:49 am »
You cannot avoid memory copies completely.

Consider I/O in a general purpose OS with paged virtual memory, where recently used files are cached in otherwise unused ("free") RAM.  Standard I/O involves a minimum of one copy from the page cache to the userspace process buffer; typically two, with the second being within the userspace, copying from its own file buffer to the target.  Memory-mapped I/O can have significant cost in (kernel) metadata structures and setup and teardown costs, and is not possible when the source is a pipe, socket, character device, or any other non-seekable non-file-like object.

(Async I/O directly to userspace buffers would be nice, but their implementation is definitely nontrivial.  The security aspects alone are very hairy: if DMA is used, the target pages need to be locked, and that opens up the risk of denial-of-service.  Per-page DMA and locking may have too much overhead.  And so on.  And even if you do have Async I/O, to have true zero-copy I/O, you need functions that access the data directly in the userspace buffer – interface needed differs a lot from C string functions! – with the way they handle encountering the end of the buffer is critical: they should return inconclusive, so that the buffer can be extended or remapped.  Very, very nontrivial.)

(Personally, I have had to fight several "experts" who claim async I/O, for example MPI async I/O, is "inherently prone to deadlock", simply because they cannot wrap their mind around how it works.  I've basically given up trying to push for true async I/O because of how few actually understand and can use it correctly, and instead nowadays use a thread to handle blocking or non-blocking I/O in an asynchronous manner.)

In a multithreaded system, memory copies are essential for efficient operation (RCU).  In particular, if you have a state object protected by a mutex or a rwlock, you always want to copy the object to local storage for general examination and processing, so that the lock duration can be kept to minimum.

Dense cache-effective data structures – arrays and (binary) heaps in particular – require memory copy operations during insertion and deletion.  Using pointers not only grows the per-item size (often significantly), but also tends to reduce data locality (because consecutive items are not necessarily near each other in memory), which tends to reduce the effectiveness of caching schemes.  A particularly well known example is naïve matrix multiplication on x86/x86-64, where doing an (in-place) transpose to one of the matrices to make the inner loop access memory consecutively gives a significant efficiency boost.

Finally, I personally do not wish to limit to block copy operations, as the block comparison and block examination (zero search in particular) are very similar, and when used, tend to be heavily used (a significant fraction of the CPU time used by a process).
 

Offline RenThraysk

  • Regular Contributor
  • *
  • Posts: 107
  • Country: gb
Re: Block copy instructions
« Reply #28 on: January 14, 2021, 11:35:15 am »
m68k has movem, for block copies above a certain size. Could copy something like 48 bytes in 2 instructions.

On the actual M68000 that is 18 cycles per 4 bytes copied, plus 20 cycles overhead. You can't use all 16 registers (64 bytes), obviously, because you need some for the src and dst pointers, minimum. And whatever registers you do use, you probably have to save them somewhere at the start, and reload them later.

OK, let's say 12 registers. So 12*18+20 = 236 cycles to save them at the start and restore them after. And then 236 cycles plus some loop overhead (dbnz, say, 10 cycles) for each 48 bytes copied.

A simple MOVE.L (An)+,(An)+ is 20 cycles and doesn't use any registers except the src and dst pointers so MOVEM saves very little if you don't mind unrolling the MOVE.L loop a little.

Yes, that's why I said above a certain size. You have to be doing a silly amount of small copies to even care about the cost.
Considerably more loop overhead can be eliminated at some point too with a duff device.

 

Offline RenThraysk

  • Regular Contributor
  • *
  • Posts: 107
  • Country: gb
Re: Block copy instructions
« Reply #29 on: January 14, 2021, 11:41:04 am »
The general solution if copying is the performance bottleneck, is to completely eliminate the need to copy. AKA Zero-copy.

Most modern OS's have zero copy APIs for things like files and networking.

That solution can easily bring its own problems, e.g. aliasing (and not being able to prove the absence of aliasing), ownership, memory reclamation.

Language support helps, and it absence hinders optimisation and correctness.

But you have to have identified that you have a problem with copy performance before you'd even consider attempting to change strategy to a zero copy one.
You certainly shouldn't attempt a zero copy implementation until have written the simpler copy version first, and benchmarked to determine the copy operations are the performance issue.
It's highly unlikely they will be.

Premature optimisation is the root of all evil, and all that.

Or as Dave would put it, a trap for young players.
« Last Edit: January 14, 2021, 11:43:32 am by RenThraysk »
 

Online tggzzz

  • Super Contributor
  • ***
  • Posts: 23122
  • Country: gb
  • Numbers, not adjectives
    • Having fun doing more, with less
Re: Block copy instructions
« Reply #30 on: January 14, 2021, 02:30:22 pm »
You cannot avoid memory copies completely.

Of course.

But I was considering the usual copy-by-accident because people don't understand what the (magic) compiler does. Yes, that is not uncommon :(

Quote
Consider I/O in a general purpose OS with paged virtual memory, where recently used files are cached in otherwise unused ("free") RAM.  Standard I/O involves a minimum of one copy from the page cache to the userspace process buffer; typically two, with the second being within the userspace, copying from its own file buffer to the target.  Memory-mapped I/O can have significant cost in (kernel) metadata structures and setup and teardown costs, and is not possible when the source is a pipe, socket, character device, or any other non-seekable non-file-like object.

ISTR that HP significantly reduced the copies needed during network IO, but that was 25 years ago and I wasn't involved. ISTR one trick was to combine memory traversal for CRC computation with moving a buffer.

Quote
In a multithreaded system, memory copies are essential for efficient operation (RCU).  In particular, if you have a state object protected by a mutex or a rwlock, you always want to copy the object to local storage for general examination and processing, so that the lock duration can be kept to minimum.

Are you sure of that? Have you looked at how modern HotSpot (Java JVM) implementations work?

Quote
Dense cache-effective data structures – arrays and (binary) heaps in particular – require memory copy operations during insertion and deletion.  Using pointers not only grows the per-item size (often significantly), but also tends to reduce data locality (because consecutive items are not necessarily near each other in memory), which tends to reduce the effectiveness of caching schemes.  A particularly well known example is naïve matrix multiplication on x86/x86-64, where doing an (in-place) transpose to one of the matrices to make the inner loop access memory consecutively gives a significant efficiency boost.

Pointers aren't a panacea - far from it!
There are lies, damned lies, statistics - and ADC/DAC specs.
Glider pilot's aphorism: "there is no substitute for span". Retort: "There is a substitute: skill+imagination. But you can buy span".
Having fun doing more, with less
 

Offline radiogeek381

  • Regular Contributor
  • *
  • Posts: 140
  • Country: us
    • SoDaRadio
Re: Block copy instructions
« Reply #31 on: January 14, 2021, 04:03:41 pm »
The VAX instruction set had at least two block copy instructions: MOVC3, MOVC5.  (Depending on how you look at it, add MOVTC and MOVTUC.)

The instructions block move instructions were *all* interruptible, since the transfer link could be much larger than a page.  There had to be a way of handling a page fault that had to go to disk. There were also real-time considerations, as a 64KB+ block could take seconds to complete on a 730, for instance.

MOVC3 and MOVC5 even dealt with *overlapping* source and destination.  Microcode adjusted the order of transfer (front to back, or back to front) in order to get the "right" result.

MOVC5 would fill the destination buffer with a specified character if the source buffer was smaller than the destination buffer.

The interruptibility of the instructions gave rise to quite a few microcoding issues, as the intermediate state was saved in general purpose registers.  Fiddling with the return stack before resuming a MOVCx could produce surprise results.  However, the VAX architecture commitment mandated that it could not cause a system hang.

These instructions were very important in the paging system and, believe it or not, to the BACKUP program.   And it was faster than the "equivalent" series of MOV (Rx)+,(Ry)+,  and AOBLEQ.
 

Offline RenThraysk

  • Regular Contributor
  • *
  • Posts: 107
  • Country: gb
Re: Block copy instructions
« Reply #32 on: January 14, 2021, 04:08:55 pm »
Pointers aren't a panacea - far from it!

Yeah, for example garbage collected languages. If your struct/data is small enough it can be better to copy it around, rather than use pointers and increase pressure on the gc.
 

Offline Nominal Animal

  • Super Contributor
  • ***
  • Posts: 8354
  • Country: fi
    • My home page and email address
Re: Block copy instructions
« Reply #33 on: January 14, 2021, 04:22:40 pm »
Quote
In a multithreaded system, memory copies are essential for efficient operation (RCU).  In particular, if you have a state object protected by a mutex or a rwlock, you always want to copy the object to local storage for general examination and processing, so that the lock duration can be kept to minimum.
Are you sure of that?
I should have phrased that better, now that you point it out!  :-DD

It is true for RCU objects, and these are rather common on the OS kernel side.  I did not mean all state objects protected by a mutex or rwlock need to be copied.  (If you've looked at any example code I've supplied, you'll see that when using mutexes with normal state objects, I don't do copies.)

A typical example would be a set of resource counters for some process or thread.  While e.g. the calculations needed by a scheduler to apply priorities etc. to decide the next process to be run are simple, they are nonneglible, and instead of holding the lock for the duration of the calculation, you only hold the lock for the duration of copying the data. The higher the contention on the state object, the more important it is to minimize the lock hold time, so that you do not end up serializing the operations done using the information in the state object.

Pointers aren't a panacea - far from it!
Exactly.  Many cache-efficient algorithms do need efficient copy operations.
 

Offline SiliconWizardTopic starter

  • Super Contributor
  • ***
  • Posts: 17847
  • Country: fr
Re: Block copy instructions
« Reply #34 on: January 14, 2021, 05:16:39 pm »
The VAX instruction set had at least two block copy instructions: MOVC3, MOVC5.  (Depending on how you look at it, add MOVTC and MOVTUC.)

The instructions block move instructions were *all* interruptible, since the transfer link could be much larger than a page.  There had to be a way of handling a page fault that had to go to disk. There were also real-time considerations, as a 64KB+ block could take seconds to complete on a 730, for instance.

MOVC3 and MOVC5 even dealt with *overlapping* source and destination.  Microcode adjusted the order of transfer (front to back, or back to front) in order to get the "right" result.

MOVC5 would fill the destination buffer with a specified character if the source buffer was smaller than the destination buffer.

The interruptibility of the instructions gave rise to quite a few microcoding issues, as the intermediate state was saved in general purpose registers.  Fiddling with the return stack before resuming a MOVCx could produce surprise results.  However, the VAX architecture commitment mandated that it could not cause a system hang.

These instructions were very important in the paging system and, believe it or not, to the BACKUP program.   And it was faster than the "equivalent" series of MOV (Rx)+,(Ry)+,  and AOBLEQ.

Thanks for this piece of history. I admit I know next to nothing about VAX.
 

Offline SiliconWizardTopic starter

  • Super Contributor
  • ***
  • Posts: 17847
  • Country: fr
Re: Block copy instructions
« Reply #35 on: January 14, 2021, 05:46:52 pm »
Exactly.  Many cache-efficient algorithms do need efficient copy operations.

Absolutely!

Now there is one obvious reason for copying: keeping the original "value" of a given "object". This is a pretty common need.
Sure, doing it if it's not required is wasteful, sure, some languages are better than others to help you avoid that, but still. There are still many, many reasons for doing it for a good reason.

As I said, I'd really like to find (which I have little hope about) or write a tool that could analyze code dynamically (at run time) and extract stats about copy operations. My experience and intuition tell me that they are a significant part of a large range of programs, and since that's just intuition and not facts, a tool would definitely help figure that out. It could also help optimize code to limit copy operations when they are not strictly needed, or even help devise programming languages that are more efficient in that regard. Of course, it would also help determine whether block copy instructions would have a real benefit or not.

 

Offline Nominal Animal

  • Super Contributor
  • ***
  • Posts: 8354
  • Country: fi
    • My home page and email address
Re: Block copy instructions
« Reply #36 on: January 14, 2021, 06:31:15 pm »
As I said, I'd really like to find (which I have little hope about) or write a tool that could analyze code dynamically (at run time) and extract stats about copy operations.
While
    ltrace -o logfile -e memcpy+memmove+memset command
will log all memcpy(), memmove(), and memset() calls to logfile, I suspect one would need to instrument GCC itself to find out.

For example, using GCC 7.5.0 on x86-64 Linux,
Code: [Select]
struct foo {
    double  d;
    float   f;
    long    o;
    int     i;
    char    c;
};

void copy(struct foo *dst, struct foo *src)
{
    *dst = *src;
}
using -O2 will generate an open-coded copy, not a call to memcpy()/memmove().

If you want to see something really funny, create an empty empty.py and run 'ltrace -o log -e memset+memcpy+memmove python3 empty.py'.
On my machine, that yields a log of 57,946 calls to those three functions alone...
 

Offline brucehoult

  • Super Contributor
  • ***
  • Posts: 6464
  • Country: nz
Re: Block copy instructions
« Reply #37 on: January 14, 2021, 09:57:54 pm »
m68k has movem, for block copies above a certain size. Could copy something like 48 bytes in 2 instructions.

On the actual M68000 that is 18 cycles per 4 bytes copied, plus 20 cycles overhead. You can't use all 16 registers (64 bytes), obviously, because you need some for the src and dst pointers, minimum. And whatever registers you do use, you probably have to save them somewhere at the start, and reload them later.

OK, let's say 12 registers. So 12*18+20 = 236 cycles to save them at the start and restore them after. And then 236 cycles plus some loop overhead (dbnz, say, 10 cycles) for each 48 bytes copied.

A simple MOVE.L (An)+,(An)+ is 20 cycles and doesn't use any registers except the src and dst pointers so MOVEM saves very little if you don't mind unrolling the MOVE.L loop a little.

Yes, that's why I said above a certain size. You have to be doing a silly amount of small copies to even care about the cost.
Considerably more loop overhead can be eliminated at some point too with a duff device.

Duff is just a way to do unrolling without having a leftover part at the end by jumping into the middle of the loop the first time. It only works if the pointers are actually updated after every unit copied, not using offset addressing with one big pointer update at the end of the loop -- so it doesn't apply to typical RISC code.

If the unroll factor is small (four, say) then it's questionable whether Duff is even worth it at all as (depending on the ISA) often needs a few instructions and maybe a memory reference to calculate the address of the instruction to jump to.
 

Offline brucehoult

  • Super Contributor
  • ***
  • Posts: 6464
  • Country: nz
Re: Block copy instructions
« Reply #38 on: January 14, 2021, 10:08:58 pm »
The VAX instruction set had at least two block copy instructions: MOVC3, MOVC5.  (Depending on how you look at it, add MOVTC and MOVTUC.)

:

These instructions were very important in the paging system and, believe it or not, to the BACKUP program.   And it was faster than the "equivalent" series of MOV (Rx)+,(Ry)+,  and AOBLEQ.

Are you sure? Maybe on some models.

Dave Patterson's actual measurements of the slowness of VAX 780 instructions such as MOVC3, CALLS/CALLG and the more complicated addressing modes vs doing the same thing using simple instructions was what led him to formulate RISC in the first place.

If you're doing a loop with MOVL (Rx)+,(Ry)+ and AOBLEQ then those may already be too complicated instructions that invoke a slow microcode path.

It's been notorious that throughout the last 42 years REP MOVSB on x86 has been slower than a well written explicit loop on (almost?) every Intel and AMD model.
 

Online tggzzz

  • Super Contributor
  • ***
  • Posts: 23122
  • Country: gb
  • Numbers, not adjectives
    • Having fun doing more, with less
Re: Block copy instructions
« Reply #39 on: January 14, 2021, 10:25:32 pm »
Pointers aren't a panacea - far from it!

Yeah, for example garbage collected languages. If your struct/data is small enough it can be better to copy it around, rather than use pointers and increase pressure on the gc.

Very few people from the C/C++ world (or those who only dimly remember reference counting from university lectures) realise how effective modern garbage collectors are - provided there is appropriate language semantics to support it.

Too many such people think they can manage memory more efficiently manually. (I can manage memory arbitrarily efficiently if I dont have to guarantee correctness :) )
There are lies, damned lies, statistics - and ADC/DAC specs.
Glider pilot's aphorism: "there is no substitute for span". Retort: "There is a substitute: skill+imagination. But you can buy span".
Having fun doing more, with less
 

Offline RenThraysk

  • Regular Contributor
  • *
  • Posts: 107
  • Country: gb
Re: Block copy instructions
« Reply #40 on: January 15, 2021, 12:00:34 am »
m68k has movem, for block copies above a certain size. Could copy something like 48 bytes in 2 instructions.

On the actual M68000 that is 18 cycles per 4 bytes copied, plus 20 cycles overhead. You can't use all 16 registers (64 bytes), obviously, because you need some for the src and dst pointers, minimum. And whatever registers you do use, you probably have to save them somewhere at the start, and reload them later.

OK, let's say 12 registers. So 12*18+20 = 236 cycles to save them at the start and restore them after. And then 236 cycles plus some loop overhead (dbnz, say, 10 cycles) for each 48 bytes copied.

A simple MOVE.L (An)+,(An)+ is 20 cycles and doesn't use any registers except the src and dst pointers so MOVEM saves very little if you don't mind unrolling the MOVE.L loop a little.

Yes, that's why I said above a certain size. You have to be doing a silly amount of small copies to even care about the cost.
Considerably more loop overhead can be eliminated at some point too with a duff device.

Duff is just a way to do unrolling without having a leftover part at the end by jumping into the middle of the loop the first time. It only works if the pointers are actually updated after every unit copied, not using offset addressing with one big pointer update at the end of the loop -- so it doesn't apply to typical RISC code.

Yes, they use a computed goto/jump.
Duff devices work on MIPS/MIPS64 and ARM/ARM64. So not sure what "doesn't apply to typical RISC code means".
« Last Edit: January 15, 2021, 12:08:38 am by RenThraysk »
 

Offline brucehoult

  • Super Contributor
  • ***
  • Posts: 6464
  • Country: nz
Re: Block copy instructions
« Reply #41 on: January 15, 2021, 12:45:29 am »
m68k has movem, for block copies above a certain size. Could copy something like 48 bytes in 2 instructions.

On the actual M68000 that is 18 cycles per 4 bytes copied, plus 20 cycles overhead. You can't use all 16 registers (64 bytes), obviously, because you need some for the src and dst pointers, minimum. And whatever registers you do use, you probably have to save them somewhere at the start, and reload them later.

OK, let's say 12 registers. So 12*18+20 = 236 cycles to save them at the start and restore them after. And then 236 cycles plus some loop overhead (dbnz, say, 10 cycles) for each 48 bytes copied.

A simple MOVE.L (An)+,(An)+ is 20 cycles and doesn't use any registers except the src and dst pointers so MOVEM saves very little if you don't mind unrolling the MOVE.L loop a little.

Yes, that's why I said above a certain size. You have to be doing a silly amount of small copies to even care about the cost.
Considerably more loop overhead can be eliminated at some point too with a duff device.

Duff is just a way to do unrolling without having a leftover part at the end by jumping into the middle of the loop the first time. It only works if the pointers are actually updated after every unit copied, not using offset addressing with one big pointer update at the end of the loop -- so it doesn't apply to typical RISC code.

Yes, they use a computed goto/jump.
Duff devices work on MIPS/MIPS64 and ARM/ARM64. So not sure what "doesn't apply to typical RISC code means".

Let's check.

Code: [Select]
#include <inttypes.h>

typedef uint64_t word;

void foo(word *to, word *from, int count) {
  int n = (count + 7) / 8;
  switch (count % 8) {
  case 0: do { *to++ = *from++;
  case 7:      *to++ = *from++;
  case 6:      *to++ = *from++;
  case 5:      *to++ = *from++;
  case 4:      *to++ = *from++;
  case 3:      *to++ = *from++;
  case 2:      *to++ = *from++;
  case 1:      *to++ = *from++;
    } while (--n > 0);
  }
}


void bar(word *to, word *from, int count) {
  while (count >= 8) {
    *to++ = *from++;
    *to++ = *from++;
    *to++ = *from++;
    *to++ = *from++;
    *to++ = *from++;
    *to++ = *from++;
    *to++ = *from++;
    *to++ = *from++;
    count -= 8;
  }
  while (count > 0) {
    *to++ = *from++;
    count -= 1;
  }
}


Compiled for arm64 with gcc -O2:

Code: [Select]
0000000000000000 <foo>:
   0:   31001c44        adds    w4, w2, #0x7
   4:   11003843        add     w3, w2, #0xe
   8:   1a844063        csel    w3, w3, w4, mi  // mi = first
   c:   6b0203e4        negs    w4, w2
  10:   12000884        and     w4, w4, #0x7
  14:   12000842        and     w2, w2, #0x7
  18:   5a844442        csneg   w2, w2, w4, mi  // mi = first
  1c:   13037c63        asr     w3, w3, #3
  20:   71000c5f        cmp     w2, #0x3
  24:   54000740        b.eq    10c <foo+0x10c>  // b.none
  28:   5400060d        b.le    e8 <foo+0xe8>
  2c:   7100145f        cmp     w2, #0x5
  30:   540006a0        b.eq    104 <foo+0x104>  // b.none
  34:   5400022b        b.lt    78 <foo+0x78>  // b.tstop
  38:   7100185f        cmp     w2, #0x6
  3c:   540000e0        b.eq    58 <foo+0x58>  // b.none
  40:   71001c5f        cmp     w2, #0x7
  44:   540005a1        b.ne    f8 <foo+0xf8>  // b.any
  48:   f9400022        ldr     x2, [x1]
  4c:   91002000        add     x0, x0, #0x8
  50:   f81f8002        stur    x2, [x0, #-8]
  54:   91002021        add     x1, x1, #0x8
  58:   f9400024        ldr     x4, [x1]
  5c:   91002002        add     x2, x0, #0x8
  60:   91002021        add     x1, x1, #0x8
  64:   f9000004        str     x4, [x0]
  68:   f9400024        ldr     x4, [x1]
  6c:   91002040        add     x0, x2, #0x8
  70:   91002021        add     x1, x1, #0x8
  74:   f9000044        str     x4, [x2]
  78:   f9400022        ldr     x2, [x1]
  7c:   91002004        add     x4, x0, #0x8
  80:   91002021        add     x1, x1, #0x8
  84:   f9000002        str     x2, [x0]
  88:   f9400020        ldr     x0, [x1]
  8c:   91002082        add     x2, x4, #0x8
  90:   91002021        add     x1, x1, #0x8
  94:   f9000080        str     x0, [x4]
  98:   f9400024        ldr     x4, [x1]
  9c:   91002040        add     x0, x2, #0x8
  a0:   91002021        add     x1, x1, #0x8
  a4:   f9000044        str     x4, [x2]
  a8:   f9400022        ldr     x2, [x1]
  ac:   51000463        sub     w3, w3, #0x1
  b0:   f9000002        str     x2, [x0]
  b4:   7100007f        cmp     w3, #0x0
  b8:   5400020d        b.le    f8 <foo+0xf8>
  bc:   91002021        add     x1, x1, #0x8
  c0:   91002000        add     x0, x0, #0x8
  c4:   f9400022        ldr     x2, [x1]
  c8:   91002021        add     x1, x1, #0x8
  cc:   f9000002        str     x2, [x0]
  d0:   91002000        add     x0, x0, #0x8
  d4:   f9400022        ldr     x2, [x1]
  d8:   91002021        add     x1, x1, #0x8
  dc:   f9000002        str     x2, [x0]
  e0:   91002000        add     x0, x0, #0x8
  e4:   17ffffdd        b       58 <foo+0x58>
  e8:   7100045f        cmp     w2, #0x1
  ec:   54fffde0        b.eq    a8 <foo+0xa8>  // b.none
  f0:   5400006c        b.gt    fc <foo+0xfc>
  f4:   34fffe82        cbz     w2, c4 <foo+0xc4>
  f8:   d65f03c0        ret
  fc:   aa0003e2        mov     x2, x0
 100:   17ffffe6        b       98 <foo+0x98>
 104:   aa0003e2        mov     x2, x0
 108:   17ffffd8        b       68 <foo+0x68>
 10c:   aa0003e4        mov     x4, x0
 110:   17ffffde        b       88 <foo+0x88>
 114:   d503201f        nop

0000000000000118 <bar>:
 118:   71001c5f        cmp     w2, #0x7
 11c:   5400052d        b.le    1c0 <bar+0xa8>
 120:   51002042        sub     w2, w2, #0x8
 124:   aa0103e3        mov     x3, x1
 128:   53037c47        lsr     w7, w2, #3
 12c:   d37a70e6        ubfiz   x6, x7, #6, #29
 130:   910100c6        add     x6, x6, #0x40
 134:   8b060004        add     x4, x0, x6
 138:   f9400065        ldr     x5, [x3]
 13c:   91010063        add     x3, x3, #0x40
 140:   f9000005        str     x5, [x0]
 144:   91010000        add     x0, x0, #0x40
 148:   eb00009f        cmp     x4, x0
 14c:   f85c8065        ldur    x5, [x3, #-56]
 150:   f81c8005        stur    x5, [x0, #-56]
 154:   f85d0065        ldur    x5, [x3, #-48]
 158:   f81d0005        stur    x5, [x0, #-48]
 15c:   f85d8065        ldur    x5, [x3, #-40]
 160:   f81d8005        stur    x5, [x0, #-40]
 164:   f85e0065        ldur    x5, [x3, #-32]
 168:   f81e0005        stur    x5, [x0, #-32]
 16c:   f85e8065        ldur    x5, [x3, #-24]
 170:   f81e8005        stur    x5, [x0, #-24]
 174:   f85f0065        ldur    x5, [x3, #-16]
 178:   f81f0005        stur    x5, [x0, #-16]
 17c:   f85f8065        ldur    x5, [x3, #-8]
 180:   f81f8005        stur    x5, [x0, #-8]
 184:   54fffda1        b.ne    138 <bar+0x20>  // b.any
 188:   8b060021        add     x1, x1, x6
 18c:   4b070c42        sub     w2, w2, w7, lsl #3
 190:   7100005f        cmp     w2, #0x0
 194:   5400014d        b.le    1bc <bar+0xa4>
 198:   51000442        sub     w2, w2, #0x1
 19c:   d2800000        mov     x0, #0x0                        // #0
 1a0:   91000442        add     x2, x2, #0x1
 1a4:   d503201f        nop
 1a8:   f8607823        ldr     x3, [x1, x0, lsl #3]
 1ac:   f8207883        str     x3, [x4, x0, lsl #3]
 1b0:   91000400        add     x0, x0, #0x1
 1b4:   eb02001f        cmp     x0, x2
 1b8:   54ffff81        b.ne    1a8 <bar+0x90>  // b.any
 1bc:   d65f03c0        ret
 1c0:   aa0003e4        mov     x4, x0
 1c4:   17fffff3        b       190 <bar+0x78>


Let's try MIPS with gcc -O2 -march=mips64

Code: [Select]
00000000 <foo>:
   0:   24c30007        addiu   v1,a2,7
   4:   04610002        bgez    v1,10 <foo+0x10>
   8:   3c028000        lui     v0,0x8000
   c:   24c3000e        addiu   v1,a2,14
  10:   24420007        addiu   v0,v0,7
  14:   00c23024        and     a2,a2,v0
  18:   04c10005        bgez    a2,30 <foo+0x30>
  1c:   000340c3        sra     t0,v1,0x3
  20:   24c6ffff        addiu   a2,a2,-1
  24:   2402fff8        li      v0,-8
  28:   00c23025        or      a2,a2,v0
  2c:   24c60001        addiu   a2,a2,1
  30:   2cc20008        sltiu   v0,a2,8
  34:   10400040        beqz    v0,138 <foo+0x138>
  38:   3c020000        lui     v0,0x0
  3c:   24420000        addiu   v0,v0,0
  40:   00063080        sll     a2,a2,0x2
  44:   00463021        addu    a2,v0,a2
  48:   8cc20000        lw      v0,0(a2)
  4c:   00400008        jr      v0
  50:   00000000        nop
  54:   8ca30004        lw      v1,4(a1)
  58:   8ca20000        lw      v0,0(a1)
  5c:   24840008        addiu   a0,a0,8
  60:   ac83fffc        sw      v1,-4(a0)
  64:   ac82fff8        sw      v0,-8(a0)
  68:   24a50008        addiu   a1,a1,8
  6c:   8ca70004        lw      a3,4(a1)
  70:   8ca60000        lw      a2,0(a1)
  74:   24820008        addiu   v0,a0,8
  78:   24a50008        addiu   a1,a1,8
  7c:   ac870004        sw      a3,4(a0)
  80:   ac860000        sw      a2,0(a0)
  84:   8ca70004        lw      a3,4(a1)
  88:   8ca60000        lw      a2,0(a1)
  8c:   24440008        addiu   a0,v0,8
  90:   24a50008        addiu   a1,a1,8
  94:   ac470004        sw      a3,4(v0)
  98:   ac460000        sw      a2,0(v0)
  9c:   8ca30004        lw      v1,4(a1)
  a0:   8ca20000        lw      v0,0(a1)
  a4:   24860008        addiu   a2,a0,8
  a8:   24a50008        addiu   a1,a1,8
  ac:   ac830004        sw      v1,4(a0)
  b0:   ac820000        sw      v0,0(a0)
  b4:   8cab0004        lw      t3,4(a1)
  b8:   8caa0000        lw      t2,0(a1)
  bc:   24c20008        addiu   v0,a2,8
  c0:   24a50008        addiu   a1,a1,8
  c4:   accb0004        sw      t3,4(a2)
  c8:   acca0000        sw      t2,0(a2)
  cc:   8ca70004        lw      a3,4(a1)
  d0:   8ca60000        lw      a2,0(a1)
  d4:   24440008        addiu   a0,v0,8
  d8:   24a50008        addiu   a1,a1,8
  dc:   ac470004        sw      a3,4(v0)
  e0:   ac460000        sw      a2,0(v0)
  e4:   8ca30004        lw      v1,4(a1)
  e8:   8ca20000        lw      v0,0(a1)
  ec:   2508ffff        addiu   t0,t0,-1
  f0:   ac830004        sw      v1,4(a0)
  f4:   19000010        blez    t0,138 <foo+0x138>
  f8:   ac820000        sw      v0,0(a0)
  fc:   24a50008        addiu   a1,a1,8
 100:   24840008        addiu   a0,a0,8
 104:   8ca30004        lw      v1,4(a1)
 108:   8ca20000        lw      v0,0(a1)
 10c:   ac830004        sw      v1,4(a0)
 110:   ac820000        sw      v0,0(a0)
 114:   24a50008        addiu   a1,a1,8
 118:   8ca30004        lw      v1,4(a1)
 11c:   8ca20000        lw      v0,0(a1)
 120:   24840008        addiu   a0,a0,8
 124:   ac830004        sw      v1,4(a0)
 128:   ac820000        sw      v0,0(a0)
 12c:   24a50008        addiu   a1,a1,8
 130:   1000ffce        b       6c <foo+0x6c>
 134:   24840008        addiu   a0,a0,8
 138:   03e00008        jr      ra
 13c:   00000000        nop
 140:   1000ffd0        b       84 <foo+0x84>
 144:   00801025        move    v0,a0
 148:   1000ffe0        b       cc <foo+0xcc>
 14c:   00801025        move    v0,a0
 150:   1000ffd8        b       b4 <foo+0xb4>
 154:   00803025        move    a2,a0

00000158 <bar>:
 158:   28c20008        slti    v0,a2,8
 15c:   14400030        bnez    v0,220 <bar+0xc8>
 160:   00a01825        move    v1,a1
 164:   00c03825        move    a3,a2
 168:   00801025        move    v0,a0
 16c:   8c690004        lw      t1,4(v1)
 170:   8c680000        lw      t0,0(v1)
 174:   ac490004        sw      t1,4(v0)
 178:   ac480000        sw      t0,0(v0)
 17c:   24630040        addiu   v1,v1,64
 180:   8c69ffcc        lw      t1,-52(v1)
 184:   8c68ffc8        lw      t0,-56(v1)
 188:   ac49000c        sw      t1,12(v0)
 18c:   ac480008        sw      t0,8(v0)
 190:   8c69ffd4        lw      t1,-44(v1)
 194:   8c68ffd0        lw      t0,-48(v1)
 198:   24420040        addiu   v0,v0,64
 19c:   ac49ffd4        sw      t1,-44(v0)
 1a0:   ac48ffd0        sw      t0,-48(v0)
 1a4:   8c69ffdc        lw      t1,-36(v1)
 1a8:   8c68ffd8        lw      t0,-40(v1)
 1ac:   ac49ffdc        sw      t1,-36(v0)
 1b0:   ac48ffd8        sw      t0,-40(v0)
 1b4:   8c69ffe4        lw      t1,-28(v1)
 1b8:   8c68ffe0        lw      t0,-32(v1)
 1bc:   ac49ffe4        sw      t1,-28(v0)
 1c0:   ac48ffe0        sw      t0,-32(v0)
 1c4:   8c69ffec        lw      t1,-20(v1)
 1c8:   8c68ffe8        lw      t0,-24(v1)
 1cc:   ac49ffec        sw      t1,-20(v0)
 1d0:   ac48ffe8        sw      t0,-24(v0)
 1d4:   8c69fff4        lw      t1,-12(v1)
 1d8:   8c68fff0        lw      t0,-16(v1)
 1dc:   ac49fff4        sw      t1,-12(v0)
 1e0:   ac48fff0        sw      t0,-16(v0)
 1e4:   8c69fffc        lw      t1,-4(v1)
 1e8:   8c68fff8        lw      t0,-8(v1)
 1ec:   24e7fff8        addiu   a3,a3,-8
 1f0:   28ea0008        slti    t2,a3,8
 1f4:   ac49fffc        sw      t1,-4(v0)
 1f8:   1140ffdc        beqz    t2,16c <bar+0x14>
 1fc:   ac48fff8        sw      t0,-8(v0)
 200:   24c6fff8        addiu   a2,a2,-8
 204:   000610c2        srl     v0,a2,0x3
 208:   24430001        addiu   v1,v0,1
 20c:   00031980        sll     v1,v1,0x6
 210:   000210c0        sll     v0,v0,0x3
 214:   00832021        addu    a0,a0,v1
 218:   00a32821        addu    a1,a1,v1
 21c:   00c23023        subu    a2,a2,v0
 220:   18c00009        blez    a2,248 <bar+0xf0>
 224:   000630c0        sll     a2,a2,0x3
 228:   00863021        addu    a2,a0,a2
 22c:   24a50008        addiu   a1,a1,8
 230:   8ca3fffc        lw      v1,-4(a1)
 234:   8ca2fff8        lw      v0,-8(a1)
 238:   24840008        addiu   a0,a0,8
 23c:   ac83fffc        sw      v1,-4(a0)
 240:   1486fffa        bne     a0,a2,22c <bar+0xd4>
 244:   ac82fff8        sw      v0,-8(a0)
 248:   03e00008        jr      ra
 24c:   00000000        nop


Any questions?

In both cases, the 2nd version, without Duff, is going to be much preferable.

 

Offline RenThraysk

  • Regular Contributor
  • *
  • Posts: 107
  • Country: gb
Re: Block copy instructions
« Reply #42 on: January 15, 2021, 01:25:00 am »
m68k has movem, for block copies above a certain size. Could copy something like 48 bytes in 2 instructions.

On the actual M68000 that is 18 cycles per 4 bytes copied, plus 20 cycles overhead. You can't use all 16 registers (64 bytes), obviously, because you need some for the src and dst pointers, minimum. And whatever registers you do use, you probably have to save them somewhere at the start, and reload them later.

OK, let's say 12 registers. So 12*18+20 = 236 cycles to save them at the start and restore them after. And then 236 cycles plus some loop overhead (dbnz, say, 10 cycles) for each 48 bytes copied.

A simple MOVE.L (An)+,(An)+ is 20 cycles and doesn't use any registers except the src and dst pointers so MOVEM saves very little if you don't mind unrolling the MOVE.L loop a little.

Yes, that's why I said above a certain size. You have to be doing a silly amount of small copies to even care about the cost.
Considerably more loop overhead can be eliminated at some point too with a duff device.

Duff is just a way to do unrolling without having a leftover part at the end by jumping into the middle of the loop the first time. It only works if the pointers are actually updated after every unit copied, not using offset addressing with one big pointer update at the end of the loop -- so it doesn't apply to typical RISC code.

Yes, they use a computed goto/jump.
Duff devices work on MIPS/MIPS64 and ARM/ARM64. So not sure what "doesn't apply to typical RISC code means".

Let's check.

Any questions?

In both cases, the 2nd version, without Duff, is going to be much preferable.

Questions, yes.. why would you even write another memcpy() function in C? Makes no sense. Existing memcpy() is likely to have all kinds of optimisations already implemented.

Here is Go's assembly duff code generator for various CPUs for duffcopy/zero.
https://golang.org/src/runtime/mkduff.go

 

Offline magic

  • Super Contributor
  • ***
  • Posts: 8072
  • Country: pl
Re: Block copy instructions
« Reply #43 on: January 15, 2021, 03:00:40 am »
I'm not really fluent in ARM assembly and calling conventions so not sure what's happening in your code, but why is the Duff so long?
And what stops you from jumping into the middle of a loop which uses offset addressing? You mean R+constant addressing mode by that, with increasing constant for each unolled iteration?
 

Offline brucehoult

  • Super Contributor
  • ***
  • Posts: 6464
  • Country: nz
Re: Block copy instructions
« Reply #44 on: January 15, 2021, 04:00:32 am »
Questions, yes.. why would you even write another memcpy() function in C? Makes no sense. Existing memcpy() is likely to have all kinds of optimisations already implemented.

Someone has to write the library one.

Quote
Here is Go's assembly duff code generator for various CPUs for duffcopy/zero.
https://golang.org/src/runtime/mkduff.go

If it's assembly language then it's not Duff's device.

Duff specifically means a trick in C interleaving a loop and a switch statement to get an effect similar to what you can trivially do in assembly language.
 

Offline Nominal Animal

  • Super Contributor
  • ***
  • Posts: 8354
  • Country: fi
    • My home page and email address
Re: Block copy instructions
« Reply #45 on: January 15, 2021, 06:02:11 pm »
It's not just memcpy()!

First of all, there are two variants of memcpy(): one that copies in increasing addresses, and one that copies in decreasing addresses.  I call these memcpy_inc() and memcpy_dec(), respectively; with memcpy() itself being arbitrarily either one.

memmove(dst, src, len) uses memcpy_inc() if dst < src, and memcpy_dec() if dst > src.

memrepeat(dest, off, totallen) uses memcpy_inc() with src = dest, dst = dest + off, and len = totallen - off.  It speeds up array initialization significantly, works for any array members including structures, and in several old Fortran-C comparisons (Fortran using something similar internally to initialize arrays, and standard C not having one) was the reason of Fortran being faster than C.  (Fortran as a language is easier to optimize, and array slicing allows some very powerful techniques, but all those can be implemented in C; just is not in the standard C library.  When I started writing MD code, I often had to explain why I was using C and not Fortran, and Fortran users weren't happy when I showed how I could do everything at least as efficiently as anyones Fortran code could.  I seem to have a knack of offending people by showing them facts they really don't like.)

Then we have very often used comparison functions, that are very similar to copies, except they read both sources, and abort at first difference.
This includes memcmp(), memmem(), strcmp(), strncmp(), strstr(), and (rarely implemented strnstr()).

Then we have many of the string functions, that use a single character or a small lookup table to determine when to return.
This includes strspn(), strcspn(), strchr(), strrchr(), memchr(), strsep(), strpbrk().

In assembly, these functions have the same base loop, and really only differ in the loop condition.  The lookup table based ones do an extra load from the lookup table (using a byte from the string as the offset to the table) and test a bit in the result (since in the lookup table, each entry contains a bit mask, with each bit specifying a class to be checked).

(That said, an instruction to test a bit in a possibly large table by bit index alone – so bits 0,1,2 identify the bit, and bits 3-31 (or whatever the native word size is) the byte offset – is something that is not very often needed, but when needed, might make a significant difference.)

My point earlier was that autoincrement and autodecrement speeds up all these, so much so that the inner loops have no other common code than the autoincrement/decrement load from memory.  Looking at ltrace -e str*+mem* output – even for something as simple as the date binary! – shows that these library functions are extremely common; at least as common as memcpy()/memset()/memmove() in typical userspace application code, so picking an approach that makes all these more efficient is a valid strategy in my opinion.

Having watched the x86/x86-64 evolve with respect to its block instructions – rep/repz/repnz cmps/ins/lods/movs/outs/scas/stos –, I do not believe optimizing block operations further than address autoincrement and autodecrement is worth the effort.  Indeed, for a number of x86 processors, these instructions were far from optimal, until Intel/AMD put some effort in the microcode to make them efficient again.

For a RISC-type instruction set, having an extension to enable byte and full register-wide address autoincrement and autodecrement loads and stores yields most of the possible speedups.  Zeroing aligned memory, entire cachelines or pages, is a separate task, and probably something that should be done in cooperation with the memory controller; but only really necessary/useful for general purpose OSes, where privilege separation and avoiding kernel information leaks are important, and often require zeroing memory.

Apologies for any repetition, but this is important.  This does have a measurable impact on many common applications – and a significant one on e.g. the standard Python interpreter (CPython).  Run an application via the aforementioned ltrace command, but do note that current C compilers open-code many memory copies etc., and this only logs the library calls.
« Last Edit: January 15, 2021, 06:06:57 pm by Nominal Animal »
 

Offline gf

  • Super Contributor
  • ***
  • Posts: 1840
  • Country: de
Re: Block copy instructions
« Reply #46 on: January 15, 2021, 07:10:05 pm »
It's been notorious that throughout the last 42 years REP MOVSB on x86 has been slower than a well written explicit loop on (almost?) every Intel and AMD model.

It was rather slow in the past, but starting with Ivy Bridge, Enhanced REP MOVSB did become very fast.

For instance, glibc's memcpy() uses it to copy large blocks.
https://code.woboq.org/userspace/glibc/sysdeps/x86_64/multiarch/memmove-vec-unaligned-erms.S.html

Quote
Threshold to use Enhanced REP MOVSB.  Since there is overhead to set up REP MOVSB operation, REP MOVSB isn't faster on short data.  The memcpy micro benchmark in glibc shows that 2KB is the approximate value above which REP MOVSB becomes faster than SSE2 optimization on processors with Enhanced REP MOVSB.  Since larger register size can move more data with a single load and store, the threshold is higher with larger register size.
 
The following users thanked this post: SiliconWizard

Offline brucehoult

  • Super Contributor
  • ***
  • Posts: 6464
  • Country: nz
Re: Block copy instructions
« Reply #47 on: January 16, 2021, 12:27:57 am »
Quote
Threshold to use Enhanced REP MOVSB.  Since there is overhead to set up REP MOVSB operation, REP MOVSB isn't faster on short data.  The memcpy micro benchmark in glibc shows that 2KB is the approximate value above which REP MOVSB becomes faster than SSE2 optimization on processors with Enhanced REP MOVSB.  Since larger register size can move more data with a single load and store, the threshold is higher with larger register size.

2 KB!!?? That's freaking huge.

Once it hits production I'm sure memcpy() using RISC-V V extension will be optimal for ... I don't know ... maybe 16 bytes and up.

Code: [Select]
    .global memcpy
    # void *memcpy(void* dest, const void* src, size_t n)
    # a0=dest, a1=src, a2=n
    #
  memcpy:
      mv a3, a0 # Copy destination
  loop:
    vsetvli t0, a2, e8,m8,ta,ma   # Vectors of 8b
    vle8.v v0, (a1)               # Load bytes
      add a1, a1, t0              # Bump pointer
      sub a2, a2, t0              # Decrement count
    vse8.v v0, (a3)               # Store bytes
      add a3, a3, t0              # Bump pointer
      bnez a2, loop               # Any more?
      ret                         # Return

For any call copying up to 8 times the vector register size (typically 128 to 512 bits, so 8 * 16 to 64 bytes, or 128-512 bytes) this will execute exactly ten instructions, including the call and return (or 8 if inlined).

If you compare that to the Newlib memcpy() I posted earlier in the thread, for a 1 register memcpy() it actually executes more instructions because it first has to figure out whether this is a big or a small memcpy() and jump to the simple loop -- which still calculates the limit and increments the src and dst in executing the loop once.
 

Offline brucehoult

  • Super Contributor
  • ***
  • Posts: 6464
  • Country: nz
Re: Block copy instructions
« Reply #48 on: January 16, 2021, 12:58:34 am »
For a RISC-type instruction set, having an extension to enable byte and full register-wide address autoincrement and autodecrement loads and stores yields most of the possible speedups.

The hole in your argument is your assumption that a program with fewer instructions is faster.

This is not correct. Adding autoincrement loads to an ISA such as RISC-V suddenly requires that it be possible for an integer instruction to write results to two registers instead of one.

There are two basic implementation choices:

1) build a register file that can take two writes in the same clock cycle. This is expensive, and a huge waste given that no other instruction will make use of this capability.

2) split the autoincrement load into two uops, executing in two clock cycles. The execution time will be the same as using two instructions in the first place, with the only savings being a small amount of program code storage.


OK, there's another option -- make a queue of results waiting for writeback to the register file and do the extra write in a cycle when an instruction is executing that doesn't have a result, such as a conditional branch or a store.

That will work, but it's a lot of complexity added, including the complexity of checking whether the current value for every register read is in the actual register or in the writeback queue. That's getting frighteningly close to full OoO with register renaming.

If you want to implement a register file that can take two result writes every clock cycle then you're probably better off keeping the simple instructions and doing lockstep dual-issue to two pipelines. Then your load and your pointer bump instructions can execute at the same time in the two pipelines -- but so can a whole bunch of other pairs of instructions. Generally experience shows a good implementation will dual-issue about 60% of the time, at a cost of about an extra 15% in core area and power use, making it a very good option for cores intended for maximum energy efficiency such as the ARM A7/A8/A9/A53/A55, SiFive U74 (etc), Western Digital SweRV.
 

Offline SiliconWizardTopic starter

  • Super Contributor
  • ***
  • Posts: 17847
  • Country: fr
Re: Block copy instructions
« Reply #49 on: January 16, 2021, 01:51:19 am »
In my thoughts, I clearly wanted to avoid any of this. No two destination registers. It would not just require a register file that allows two writes per cycle (which is already bad enough), but more importantly, it would drastically increase the complexity of data forwarding (bypassing) in the pipeline. That's way worse IMO. So, basically, nope!

That's why the "accelerator" I have in mind would actually NOT modify any register - it would have its own address registers.
 


Share me

Digg  Facebook  SlashDot  Delicious  Technorati  Twitter  Google  Yahoo
Smf

 

- - -
-->