title: MSVC generating unnecessary complicated instructions
body: <p>While benchmarking code involving <code>std::optional&lt;double&gt;</code>, I noticed that the code MSVC generates runs at roughly half the speed compared to the one produced by clang or gcc. After spending some time reducing the code, I noticed that MSVC apparently has issues generating code for <code>std::optional::operator=</code>. Using <code>std::optional::emplace()</code> does not exhibit the slow down.</p>
  <p>The following function</p>
  <pre><code>void test_assign(std::optional&lt;double&gt; &amp; f){
      f = std::optional{42.0};
  }
  </code></pre>
  <p>produces</p>
  <pre><code>sub     rsp, 24
  vmovsd  xmm0, QWORD PTR __real@4045000000000000
  mov     BYTE PTR $T1[rsp+8], 1
  vmovups xmm1, XMMWORD PTR $T1[rsp]
  vmovsd  xmm1, xmm1, xmm0
  vmovups XMMWORD PTR [rcx], xmm1
  add     rsp, 24
  ret     0
  </code></pre>
  <p>Notice the unaligned mov operations.
  On the contrary, the function</p>
  <pre><code>void test_emplace(std::optional&lt;double&gt; &amp; f){
      f.emplace(42.0);
  }
  </code></pre>
  <p>compiles to</p>
  <pre><code>mov     rax, 4631107791820423168      ; 4045000000000000H
  mov     BYTE PTR [rcx+8], 1
  mov     QWORD PTR [rcx], rax
  ret     0
  </code></pre>
  <p>This version is much simpler and faster.
  These were generated using MSVC 19.32 with <code>/O2 /std:c++17 /DNDEBUG /arch:AVX</code>.</p>
  <p>clang 14 with <code>-O3 -std=c++17 -DNDEBUG -mavx</code> produces</p>
  <pre><code>movabs  rax, 4631107791820423168
  mov     qword ptr [rdi], rax
  mov     byte ptr [rdi + 8], 1
  ret
  </code></pre>
  <p>in both cases.</p>
  <p>Replacing <code>std::optional&lt;double&gt;</code> with</p>
  <pre><code>struct MyOptional {
      double d;
      bool hasValue; // Required to reproduce the problem
      
      MyOptional(double v) {
          d = v;
      }
  
      void emplace(double v){
          d = v;
      }
  };
  </code></pre>
  <p>exhibits the same issue. Apparently MSVC has some troubles with the additional <code>bool</code> member.</p>
  <p>See <a href="https://godbolt.org/z/bj5d6E9Yr" rel="nofollow noreferrer">godbolt</a> for a live example.</p>
  <p>Why is MSVC producing these unaligned moves? I.e. the question is not why they are unaligned rather than aligned (which wouldn't improve things according to <a href="https://stackoverflow.com/a/45466585/3740047">this</a> post). But why does MSVC produce a considerably more expensive set of instructions in the assignment case?
  Is this simply a bug (or missed optimization opportunity) by MSVC? Or am I missing something?</p>