softwareQinc / staq

Full-stack quantum processing toolkit
https://iopscience.iop.org/article/10.1088/2058-9565/ab9359/pdf
MIT License
154 stars 28 forks source link

Transpilation incorrectly removes necessary classical conditions #67

Closed p51lee closed 11 months ago

p51lee commented 11 months ago

Hello, I'm working with the Staq optimizer and it erroneously removes necessary if conditions.

To reproduce this issue, optimize the following bug.qasm:

❯ cat bug.qasm
OPENQASM 2.0;
include "qelib1.inc";
gate cx_o0 q0,q1 { x q0; cx q0,q1; x q0; }
qreg q[2];
creg c[1];
cx_o0 q[1],q[0];
swap q[0],q[1];
if(c==1) cx q[1],q[0];
measure q[0] -> c[0];

Since there are no prior measurements to change the initial state of c, the condition c==1 should be false and the cx gate should not be executed.

❯ staq --version
staq version 3.3
(c) 2019 - 2023 softwareQ Inc. All rights reserved.
❯ staq -O3 bug.qasm
OPENQASM 2.0;
include "qelib1.inc";

qreg q[2];
creg c[1];
x q[1];
cx q[1],q[0];
x q[1];
swap q[0],q[1];
cx q[1],q[0];
measure q[0] -> c[0];

However, Staq optimizer removes the condition if (c==1). It should not be removed because:

  1. cx_o0 q[1],q[0]; flips q[0] to 1, because cx_o0 is a controlled-x gate with condition control qubit == 0.
  2. By swap q[0],q[1]; now q[1] is 1.
  3. if there's no if (c==1), cx q[1],q[0]; will erroneously flip q[0].
meamy commented 11 months ago

I tracked this down, it was a bug with one of the visitor classes from qasmtools. Fixed now. Thanks for the bug report!