title: What are the best instruction sequences to generate vector constants on the fly?
body: <p>"Best" means fewest instructions (or fewest uops, if any instructions decode to more than one uop).  Machine-code size in bytes is a tie-breaker for equal insn count.</p>
  
  <p>Constant-generation is by its very nature the start of a fresh dependency chain, so it's unusual for latency to matter.  It's also unusual to generate constants inside a loop, so throughput and execution-port demands are also mostly irrelevant.</p>
  
  <p>Generating constants instead of loading them takes more instructions (except for all-zero or all-one), so it does consume precious uop-cache space.  This can be an even more limited resource than data cache.</p>
  
  <p>Agner Fog's excellent <a href="http://agner.org/optimize/" rel="noreferrer">Optimizing Assembly guide</a> covers this in <code>Section 13.4</code>.  Table 13.10 has sequences for generating vectors where every element is <code>0</code>, <code>1</code>, <code>2</code>, <code>3</code>, <code>4</code>, <code>-1</code>, or <code>-2</code>, with element sizes from 8 to 64 bits.  Table 13.11 has sequences for generating some floating point values (<code>0.0</code>, <code>0.5</code>, <code>1.0</code>, <code>1.5</code>, <code>2.0</code>, <code>-2.0</code>, and bitmasks for the sign bit.)</p>
  
  <p>Agner Fog's sequences only use SSE2, either by design or because it hasn't been updated for a while.</p>
  
  <p><strong>What other constants can be generated with short non-obvious sequences of instructions?</strong>  (Further extensions with different shift counts are obvious and not "interesting".)  Are there better sequences for generating the constants Agner Fog does list?</p>
  
  <p><a href="https://stackoverflow.com/questions/6654099/how-to-move-128-bit-immediates-to-xmm-registers">How to move 128-bit immediates to XMM registers</a> illustrates some ways to put an arbitrary 128b constant into the instruction stream, but that's usually not sensible (it doesn't save any space, and takes up lots of uop-cache space.)</p>