Skip to content

Add multi-control functionality#1380

Open
keefehuang wants to merge 56 commits intomunich-quantum-toolkit:mainfrom
keefehuang:multi_control
Open

Add multi-control functionality#1380
keefehuang wants to merge 56 commits intomunich-quantum-toolkit:mainfrom
keefehuang:multi_control

Conversation

@keefehuang
Copy link

@keefehuang keefehuang commented Dec 8, 2025

Description

Add CRZ, MCX, MCZ, MCRZ functionality to ZX package.
Add convenience addCCZ function as it avoids one additional Hardamard edge (optimizes it away).

Fixes #1357

Checklist:

  • The pull request only contains commits that are focused and relevant to this change.
  • I have added appropriate tests that cover the new/changed functionality.
  • I have updated the documentation to reflect these changes.
  • I have added entries to the changelog for any noteworthy additions, changes, fixes, or removals.
  • I have added migration instructions to the upgrade guide (if needed).
  • The changes follow the project's style guidelines and introduce no new warnings.
  • The changes are fully tested and pass the CI checks.
  • I have reviewed my own code changes.

Keefe Huang and others added 2 commits December 8, 2025 16:40
Add CRZ, MCX, MCZ, MCRZ functionality to ZX package.
@codecov
Copy link

codecov bot commented Dec 8, 2025

Codecov Report

❌ Patch coverage is 89.30233% with 23 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
src/zx/FunctionalityConstruction.cpp 89.3% 23 Missing ⚠️

📢 Thoughts on this report? Let us know!

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Dec 8, 2025

📝 Walkthrough

Walkthrough

Added multi-controlled gate construction routines and integrated them into operation parsing and transformability checks; expanded ZX conversion to support multi-control variants (MCX, MCZ, MCRZ, MCRX, MCRZZ, MCPhase, CCZ, CRZ, CRX, MCSWAP) and updated tests to validate equivalence via ZX reductions. (≤50 words)

Changes

Cohort / File(s) Summary
Header Declaration
include/mqt-core/zx/FunctionalityConstruction.hpp
Added static declarations for multi-control primitives and single-/multi-controlled RX/RZ/ZZ/Swap helpers (addMcphase, addMcswap, addMcrzz, addCcz, addCrx, addMcrx, addCrz, addMcrz, addMcx, addMcz).
Implementation
src/zx/FunctionalityConstruction.cpp
Implemented multi-control and controlled-rotation decompositions, divide-and-conquer MCX routing, ancilla-aware strategies, and multi-control variants for RZ/RX/RZZ/RXX/RZX; updated parseOp and transformableToZX to emit/use these routines and expanded error/routing branches.
Tests
test/zx/test_zx_functionality.cpp
Added checkEquivalence helper; replaced manual functionality checks with equivalence-based tests; added extensive tests covering CRZ, CCZ, MCX/MCZ (various arities), MCRZ/MCRX, MCSWAP/MCS and related multi-control scenarios.
Build / CI
CMakeLists.txt
Test build entries updated to include new/modified test cases.

Sequence Diagram(s)

sequenceDiagram
    participant Parser as parseOp
    participant FC as FunctionalityConstruction
    participant Anc as AncillaPool
    participant ZX as ZXDiagram

    Parser->>FC: receive qc::Operation (e.g., MCX / MCRZ / MCSWAP)
    FC->>FC: select decomposition strategy (0 / 1 / 2 / ≥3 controls)
    alt needs ancilla
        FC->>Anc: request ancilla qubits
        Anc-->>FC: provide ancilla or fail
    end
    FC->>ZX: invoke addMcx / addMcrz / addMcswap / addCcz / ... to build ZX subgraph
    ZX-->>Parser: ZXDiagram updated (subgraph appended)
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Poem

🐇 I hop through wires and phases bright,
I braid MCX and CCZ by night,
Ancilla crumbs beneath my paws,
Spiders spin circuits without pause,
A rabbit cheers — the diagrams light.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title 'Add multi-control functionality' directly matches the main objective of adding multi-controlled gate support to the ZX package.
Description check ✅ Passed The PR description covers the main changes (CRZ, MCX, MCZ, MCRZ, CCZ), references the linked issue (#1357), and includes a completed checklist with all items marked.
Linked Issues check ✅ Passed The PR implements all key objectives from issue #1357: multi-controlled X (MCX), multi-controlled Z (MCZ), controlled RZ (CRZ), and multi-controlled RZ (MCRZ) with proper ZX diagram integration.
Out of Scope Changes check ✅ Passed All changes are scoped to the ZX package multi-control functionality: new gate methods (addMcphase, addMcswap, addMcrzz, addCcz, addCrx, addMcrx, addCrz, addMcrz, addMcx, addMcz) and corresponding tests.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/zx/FunctionalityConstruction.cpp (1)

872-896: Remove unreachable return statement.

The transformability checks correctly reflect the expanded multi-control support for RZ operations. However, line 896 contains an unreachable return false; statement since the preceding conditions exhaust all cases.

Apply this diff to remove the dead code:

     case qc::OpType::RZ:
       return true;
     default:
       return false;
     }
-    return false;
   }
 }
📜 Review details

Configuration used: CodeRabbit UI

Review profile: ASSERTIVE

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between bdb2073 and 0ae2b61.

📒 Files selected for processing (3)
  • include/mqt-core/zx/FunctionalityConstruction.hpp (1 hunks)
  • src/zx/FunctionalityConstruction.cpp (5 hunks)
  • test/zx/test_zx_functionality.cpp (1 hunks)
🧰 Additional context used
🧠 Learnings (5)
📓 Common learnings
Learnt from: DRovara
Repo: munich-quantum-toolkit/core PR: 1108
File: mlir/test/Dialect/MQTOpt/Transforms/lift-measurements.mlir:269-288
Timestamp: 2025-10-09T13:20:11.483Z
Learning: In the MQT MLIR dialect, the `rz` gate should not be included in the `DIAGONAL_GATES` set for the `ReplaceBasisStateControlsWithIfPattern` because its operator matrix does not have the required shape | 1 0 | / | 0 x | for the targets-as-controls optimization. It is only included in `LiftMeasurementsAboveGatesPatterns` where the matrix structure requirement differs.
📚 Learning: 2025-10-09T13:20:11.483Z
Learnt from: DRovara
Repo: munich-quantum-toolkit/core PR: 1108
File: mlir/test/Dialect/MQTOpt/Transforms/lift-measurements.mlir:269-288
Timestamp: 2025-10-09T13:20:11.483Z
Learning: In the MQT MLIR dialect, the `rz` gate should not be included in the `DIAGONAL_GATES` set for the `ReplaceBasisStateControlsWithIfPattern` because its operator matrix does not have the required shape | 1 0 | / | 0 x | for the targets-as-controls optimization. It is only included in `LiftMeasurementsAboveGatesPatterns` where the matrix structure requirement differs.

Applied to files:

  • test/zx/test_zx_functionality.cpp
  • include/mqt-core/zx/FunctionalityConstruction.hpp
  • src/zx/FunctionalityConstruction.cpp
📚 Learning: 2025-12-08T14:55:43.880Z
Learnt from: denialhaag
Repo: munich-quantum-toolkit/core PR: 1264
File: mlir/lib/Dialect/Flux/IR/Modifiers/CtrlOp.cpp:78-100
Timestamp: 2025-12-08T14:55:43.880Z
Learning: In the Flux dialect (mlir/lib/Dialect/Flux/IR/Modifiers/CtrlOp.cpp), GPhaseOp is a zero-target operation (global phase). When a CtrlOp wraps a GPhaseOp, it only has control qubits and no targets. The CtrlInlineGPhase canonicalization pattern correctly produces outputs only for the positive controls, not targets.

Applied to files:

  • include/mqt-core/zx/FunctionalityConstruction.hpp
  • src/zx/FunctionalityConstruction.cpp
📚 Learning: 2025-10-09T13:13:51.224Z
Learnt from: DRovara
Repo: munich-quantum-toolkit/core PR: 1108
File: mlir/lib/Dialect/MQTOpt/Transforms/ReplaceBasisStateControlsWithIfPattern.cpp:171-180
Timestamp: 2025-10-09T13:13:51.224Z
Learning: In MQT Core MLIR, UnitaryInterface operations guarantee 1-1 correspondence between input and output qubits in the same order. When cloning or modifying unitary operations (e.g., removing controls), this correspondence is maintained by construction, so yielding getAllInQubits() in else-branches matches the result types from the operation's outputs.

Applied to files:

  • src/zx/FunctionalityConstruction.cpp
📚 Learning: 2025-12-08T12:44:05.874Z
Learnt from: denialhaag
Repo: munich-quantum-toolkit/core PR: 1264
File: mlir/lib/Dialect/Quartz/IR/Modifiers/CtrlOp.cpp:60-70
Timestamp: 2025-12-08T12:44:05.874Z
Learning: In the Quartz dialect (mlir/lib/Dialect/Quartz/IR/Modifiers/CtrlOp.cpp), negative controls are not supported at the current stage. The RemoveTrivialCtrl pattern correctly only checks getNumPosControls() when determining if a CtrlOp should be removed.

Applied to files:

  • src/zx/FunctionalityConstruction.cpp
🧬 Code graph analysis (2)
test/zx/test_zx_functionality.cpp (2)
include/mqt-core/zx/FunctionalityConstruction.hpp (2)
  • qc (39-39)
  • qc (50-50)
src/zx/FunctionalityConstruction.cpp (2)
  • buildFunctionality (787-804)
  • buildFunctionality (787-788)
src/zx/FunctionalityConstruction.cpp (2)
src/zx/Rational.cpp (1)
  • PiRational (21-45)
src/ir/operations/OpType.cpp (2)
  • toString (21-35)
  • toString (21-21)
🪛 GitHub Check: 🇨‌ Lint / 🚨 Lint
src/zx/FunctionalityConstruction.cpp

[warning] 388-388: src/zx/FunctionalityConstruction.cpp:388:13 [cppcoreguidelines-init-variables]
variable 'anc' is not initialized


[warning] 384-384: src/zx/FunctionalityConstruction.cpp:384:50 [clang-diagnostic-sign-conversion]
implicit conversion changes signedness: 'size_t' (aka 'unsigned long') to 'difference_type' (aka 'long')


[warning] 384-384: src/zx/FunctionalityConstruction.cpp:384:50 [bugprone-narrowing-conversions]
narrowing conversion from 'size_t' (aka 'unsigned long') to signed type 'difference_type' (aka 'long') is implementation-defined


[warning] 383-383: src/zx/FunctionalityConstruction.cpp:383:67 [clang-diagnostic-sign-conversion]
implicit conversion changes signedness: 'size_t' (aka 'unsigned long') to 'difference_type' (aka 'long')


[warning] 383-383: src/zx/FunctionalityConstruction.cpp:383:67 [bugprone-narrowing-conversions]
narrowing conversion from 'size_t' (aka 'unsigned long') to signed type 'difference_type' (aka 'long') is implementation-defined


[warning] 383-383: src/zx/FunctionalityConstruction.cpp:383:5 [misc-const-correctness]
variable 'first' of type 'std::vector' (aka 'vector') can be declared 'const'


[warning] 382-382: src/zx/FunctionalityConstruction.cpp:382:5 [misc-const-correctness]
variable 'half' of type 'size_t' (aka 'unsigned long') can be declared 'const'


[warning] 356-356: src/zx/FunctionalityConstruction.cpp:356:5 [misc-const-correctness]
variable 'nextControl' of type 'Qubit' (aka 'int') can be declared 'const'


[warning] 339-339: src/zx/FunctionalityConstruction.cpp:339:3 [readability-suspicious-call-argument]
2nd argument 'target' (passed to 'ctrl') looks like it might be swapped with the 3rd, 'control' (passed to 'target')


[warning] 336-336: src/zx/FunctionalityConstruction.cpp:336:3 [readability-suspicious-call-argument]
2nd argument 'target' (passed to 'ctrl') looks like it might be swapped with the 3rd, 'control' (passed to 'target')

⏰ Context from checks skipped due to timeout of 900000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: 🐍 Test (macos-15-intel) / 🐍 macos-15-intel
  • GitHub Check: 🐍 Test (windows-2022) / 🐍 windows-2022
🔇 Additional comments (7)
include/mqt-core/zx/FunctionalityConstruction.hpp (1)

116-127: LGTM!

The new method declarations for multi-control gates are well-structured and follow the existing API patterns. The signatures are clear and properly typed.

test/zx/test_zx_functionality.cpp (1)

232-359: Excellent test coverage for multi-control operations.

The new tests thoroughly validate the multi-control functionality with:

  • CRZ decomposition equivalence
  • Multi-control X with varying control counts (0, 1, 3)
  • Multi-control RZ with phase cancellation
  • Edge cases for boundary conditions

All tests properly verify identity preservation, zero global phase, and connectivity after reduction.

src/zx/FunctionalityConstruction.cpp (5)

310-330: LGTM!

The addCcz implementation correctly decomposes the CCZ gate using the standard pattern with CNOTs, Z-spiders with appropriate phases, and Hadamard edges. The decomposition is consistent with ZX-calculus conventions.


332-340: LGTM!

The addCrz implementation uses the correct decomposition for controlled-RZ gates. The argument order in addCnot(diag, target, control, qubits) is intentional and follows the standard CRZ decomposition pattern where the roles are reversed.

Note: The static analysis warning about swapped arguments at lines 336 and 339 is a false positive.


680-682: LGTM!

The addition of the RZ case for single-control, single-target operations correctly routes to addCrz, expanding the supported gate set.


723-740: LGTM!

The updates to the two-control branch correctly:

  • Build the controls vector from the operation
  • Route CCZ operations to addCcz
  • Route multi-controlled RZ operations to addMcrz
  • Update error messages to reflect multi-control support

741-762: LGTM!

The new multi-control branch properly handles operations with arbitrary numbers of controls and a single target. The routing to addMcx, addMcz, and addMcrz is correct and extends the ZX functionality to support general multi-controlled gates.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 5

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/zx/FunctionalityConstruction.cpp (1)

872-896: LGTM: Extended transformableToZX for controlled RZ.

The updates correctly mark controlled-RZ operations as transformable in all control-count branches (1, 2, and N controls).

Minor cleanup - Line 896 has an unreachable return statement:

   } else if (op->getNtargets() == 1) {
     switch (op->getType()) {
     case qc::OpType::X:
     case qc::OpType::Z:
     case qc::OpType::RZ:
       return true;
     default:
       return false;
     }
-    return false;
   }
 }
📜 Review details

Configuration used: CodeRabbit UI

Review profile: ASSERTIVE

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between bdb2073 and 0ae2b61.

📒 Files selected for processing (3)
  • include/mqt-core/zx/FunctionalityConstruction.hpp (1 hunks)
  • src/zx/FunctionalityConstruction.cpp (5 hunks)
  • test/zx/test_zx_functionality.cpp (1 hunks)
🧰 Additional context used
🧠 Learnings (4)
📚 Learning: 2025-10-09T13:20:11.483Z
Learnt from: DRovara
Repo: munich-quantum-toolkit/core PR: 1108
File: mlir/test/Dialect/MQTOpt/Transforms/lift-measurements.mlir:269-288
Timestamp: 2025-10-09T13:20:11.483Z
Learning: In the MQT MLIR dialect, the `rz` gate should not be included in the `DIAGONAL_GATES` set for the `ReplaceBasisStateControlsWithIfPattern` because its operator matrix does not have the required shape | 1 0 | / | 0 x | for the targets-as-controls optimization. It is only included in `LiftMeasurementsAboveGatesPatterns` where the matrix structure requirement differs.

Applied to files:

  • src/zx/FunctionalityConstruction.cpp
📚 Learning: 2025-12-08T14:55:43.880Z
Learnt from: denialhaag
Repo: munich-quantum-toolkit/core PR: 1264
File: mlir/lib/Dialect/Flux/IR/Modifiers/CtrlOp.cpp:78-100
Timestamp: 2025-12-08T14:55:43.880Z
Learning: In the Flux dialect (mlir/lib/Dialect/Flux/IR/Modifiers/CtrlOp.cpp), GPhaseOp is a zero-target operation (global phase). When a CtrlOp wraps a GPhaseOp, it only has control qubits and no targets. The CtrlInlineGPhase canonicalization pattern correctly produces outputs only for the positive controls, not targets.

Applied to files:

  • src/zx/FunctionalityConstruction.cpp
  • include/mqt-core/zx/FunctionalityConstruction.hpp
📚 Learning: 2025-10-09T13:13:51.224Z
Learnt from: DRovara
Repo: munich-quantum-toolkit/core PR: 1108
File: mlir/lib/Dialect/MQTOpt/Transforms/ReplaceBasisStateControlsWithIfPattern.cpp:171-180
Timestamp: 2025-10-09T13:13:51.224Z
Learning: In MQT Core MLIR, UnitaryInterface operations guarantee 1-1 correspondence between input and output qubits in the same order. When cloning or modifying unitary operations (e.g., removing controls), this correspondence is maintained by construction, so yielding getAllInQubits() in else-branches matches the result types from the operation's outputs.

Applied to files:

  • src/zx/FunctionalityConstruction.cpp
📚 Learning: 2025-12-08T12:44:05.874Z
Learnt from: denialhaag
Repo: munich-quantum-toolkit/core PR: 1264
File: mlir/lib/Dialect/Quartz/IR/Modifiers/CtrlOp.cpp:60-70
Timestamp: 2025-12-08T12:44:05.874Z
Learning: In the Quartz dialect (mlir/lib/Dialect/Quartz/IR/Modifiers/CtrlOp.cpp), negative controls are not supported at the current stage. The RemoveTrivialCtrl pattern correctly only checks getNumPosControls() when determining if a CtrlOp should be removed.

Applied to files:

  • src/zx/FunctionalityConstruction.cpp
🧬 Code graph analysis (1)
src/zx/FunctionalityConstruction.cpp (1)
include/mqt-core/zx/FunctionalityConstruction.hpp (18)
  • diag (65-68)
  • diag (69-72)
  • diag (74-76)
  • diag (77-78)
  • diag (80-82)
  • diag (83-85)
  • diag (86-87)
  • diag (88-89)
  • diag (91-93)
  • diag (95-97)
  • diag (99-101)
  • diag (102-103)
  • diag (105-108)
  • diag (110-113)
  • diag (114-115)
  • diag (116-117)
  • op (60-60)
  • op (135-135)
🪛 GitHub Check: 🇨‌ Lint / 🚨 Lint
src/zx/FunctionalityConstruction.cpp

[warning] 388-388: src/zx/FunctionalityConstruction.cpp:388:13 [cppcoreguidelines-init-variables]
variable 'anc' is not initialized


[warning] 384-384: src/zx/FunctionalityConstruction.cpp:384:50 [clang-diagnostic-sign-conversion]
implicit conversion changes signedness: 'size_t' (aka 'unsigned long') to 'difference_type' (aka 'long')


[warning] 384-384: src/zx/FunctionalityConstruction.cpp:384:50 [bugprone-narrowing-conversions]
narrowing conversion from 'size_t' (aka 'unsigned long') to signed type 'difference_type' (aka 'long') is implementation-defined


[warning] 383-383: src/zx/FunctionalityConstruction.cpp:383:67 [clang-diagnostic-sign-conversion]
implicit conversion changes signedness: 'size_t' (aka 'unsigned long') to 'difference_type' (aka 'long')


[warning] 383-383: src/zx/FunctionalityConstruction.cpp:383:67 [bugprone-narrowing-conversions]
narrowing conversion from 'size_t' (aka 'unsigned long') to signed type 'difference_type' (aka 'long') is implementation-defined


[warning] 383-383: src/zx/FunctionalityConstruction.cpp:383:5 [misc-const-correctness]
variable 'first' of type 'std::vector' (aka 'vector') can be declared 'const'


[warning] 382-382: src/zx/FunctionalityConstruction.cpp:382:5 [misc-const-correctness]
variable 'half' of type 'size_t' (aka 'unsigned long') can be declared 'const'


[warning] 356-356: src/zx/FunctionalityConstruction.cpp:356:5 [misc-const-correctness]
variable 'nextControl' of type 'Qubit' (aka 'int') can be declared 'const'


[warning] 339-339: src/zx/FunctionalityConstruction.cpp:339:3 [readability-suspicious-call-argument]
2nd argument 'target' (passed to 'ctrl') looks like it might be swapped with the 3rd, 'control' (passed to 'target')


[warning] 336-336: src/zx/FunctionalityConstruction.cpp:336:3 [readability-suspicious-call-argument]
2nd argument 'target' (passed to 'ctrl') looks like it might be swapped with the 3rd, 'control' (passed to 'target')

⏰ Context from checks skipped due to timeout of 900000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: 🐍 Test (macos-15-intel) / 🐍 macos-15-intel
  • GitHub Check: 🐍 Test (windows-2022) / 🐍 windows-2022
🔇 Additional comments (7)
test/zx/test_zx_functionality.cpp (1)

232-359: Excellent test coverage for multi-control operations.

The new tests comprehensively validate CRZ, MCX, and MCRZ operations by constructing equivalent circuits and verifying they reduce to identity. The test pattern is consistent with existing tests in the file.

src/zx/FunctionalityConstruction.cpp (5)

310-330: CCZ implementation looks correct.

The addCcz function implements a double-controlled Z gate by adapting the CCX decomposition to work in the Z-basis.


332-340: CRZ implementation is correct.

The addCrz function correctly implements controlled-RZ using the standard decomposition. The CNOT operations with target as control are intentional and correct for this decomposition, despite the static analysis warning.


680-682: LGTM: Single-controlled RZ support.

Correctly handles controlled-RZ gates by delegating to the new addCrz function.


723-740: LGTM: Double-controlled gate support.

The updated logic correctly handles CCZ and multi-controlled RZ operations with 2 controls by building a control vector and dispatching to the appropriate implementation functions.


741-762: LGTM: Multi-control gate support.

The new branch properly handles gates with arbitrary numbers of controls, supporting MCX, MCZ, and MCRZ operations through the newly implemented functions.

include/mqt-core/zx/FunctionalityConstruction.hpp (1)

116-127: LGTM: Method declarations are well-structured.

The new method declarations are consistent with existing patterns in the class and correctly match their implementations. Parameter types and const-correctness are appropriate.

Apply const to constant variables.
Replace for loop with std::ranges::find_if implementation.
Utilize static_cast to explicitly state conversion from unsigned to signed int.
Shift return false of `transformableToZX` to be reachable again.
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

📜 Review details

Configuration used: CodeRabbit UI

Review profile: ASSERTIVE

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 0ae2b61 and f8c4503.

📒 Files selected for processing (1)
  • src/zx/FunctionalityConstruction.cpp (5 hunks)
🧰 Additional context used
🧠 Learnings (6)
📚 Learning: 2025-10-09T13:20:11.483Z
Learnt from: DRovara
Repo: munich-quantum-toolkit/core PR: 1108
File: mlir/test/Dialect/MQTOpt/Transforms/lift-measurements.mlir:269-288
Timestamp: 2025-10-09T13:20:11.483Z
Learning: In the MQT MLIR dialect, the `rz` gate should not be included in the `DIAGONAL_GATES` set for the `ReplaceBasisStateControlsWithIfPattern` because its operator matrix does not have the required shape | 1 0 | / | 0 x | for the targets-as-controls optimization. It is only included in `LiftMeasurementsAboveGatesPatterns` where the matrix structure requirement differs.

Applied to files:

  • src/zx/FunctionalityConstruction.cpp
📚 Learning: 2025-12-08T12:44:05.874Z
Learnt from: denialhaag
Repo: munich-quantum-toolkit/core PR: 1264
File: mlir/lib/Dialect/Quartz/IR/Modifiers/CtrlOp.cpp:60-70
Timestamp: 2025-12-08T12:44:05.874Z
Learning: In the Quartz dialect (mlir/lib/Dialect/Quartz/IR/Modifiers/CtrlOp.cpp), negative controls are not supported at the current stage. The RemoveTrivialCtrl pattern correctly only checks getNumPosControls() when determining if a CtrlOp should be removed.

Applied to files:

  • src/zx/FunctionalityConstruction.cpp
📚 Learning: 2025-11-20T18:19:31.857Z
Learnt from: lsschmid
Repo: munich-quantum-toolkit/qmap PR: 832
File: src/hybridmap/HybridNeutralAtomMapper.cpp:1679-1715
Timestamp: 2025-11-20T18:19:31.857Z
Learning: In src/hybridmap/HybridNeutralAtomMapper.cpp, the compareSwapAndBridge and compareShuttlingAndFlyingAncilla methods intentionally use division by zero to produce infinity when distance reductions are zero or negative. This infinity value marks that option as highly unfavorable in cost comparisons, which is the intended behavior rather than a bug.

Applied to files:

  • src/zx/FunctionalityConstruction.cpp
📚 Learning: 2025-11-27T08:52:06.428Z
Learnt from: lsschmid
Repo: munich-quantum-toolkit/qmap PR: 832
File: src/hybridmap/HybridNeutralAtomMapper.cpp:1379-1383
Timestamp: 2025-11-27T08:52:06.428Z
Learning: In src/hybridmap/HybridNeutralAtomMapper.cpp, the getBestMovePos function throws std::runtime_error when no move position is found (finalBestPos.coords is empty). This behavior is acceptable for current use cases since tight architectures are not a concern. A future improvement would be to fall back to SWAP-based strategies instead of throwing.

Applied to files:

  • src/zx/FunctionalityConstruction.cpp
📚 Learning: 2025-10-09T13:13:51.224Z
Learnt from: DRovara
Repo: munich-quantum-toolkit/core PR: 1108
File: mlir/lib/Dialect/MQTOpt/Transforms/ReplaceBasisStateControlsWithIfPattern.cpp:171-180
Timestamp: 2025-10-09T13:13:51.224Z
Learning: In MQT Core MLIR, UnitaryInterface operations guarantee 1-1 correspondence between input and output qubits in the same order. When cloning or modifying unitary operations (e.g., removing controls), this correspondence is maintained by construction, so yielding getAllInQubits() in else-branches matches the result types from the operation's outputs.

Applied to files:

  • src/zx/FunctionalityConstruction.cpp
📚 Learning: 2025-12-08T14:55:43.880Z
Learnt from: denialhaag
Repo: munich-quantum-toolkit/core PR: 1264
File: mlir/lib/Dialect/Flux/IR/Modifiers/CtrlOp.cpp:78-100
Timestamp: 2025-12-08T14:55:43.880Z
Learning: In the Flux dialect (mlir/lib/Dialect/Flux/IR/Modifiers/CtrlOp.cpp), GPhaseOp is a zero-target operation (global phase). When a CtrlOp wraps a GPhaseOp, it only has control qubits and no targets. The CtrlInlineGPhase canonicalization pattern correctly produces outputs only for the positive controls, not targets.

Applied to files:

  • src/zx/FunctionalityConstruction.cpp
🪛 GitHub Check: 🇨‌ Lint / 🚨 Lint
src/zx/FunctionalityConstruction.cpp

[warning] 395-395: src/zx/FunctionalityConstruction.cpp:395:9 [readability-else-after-return]
do not use 'else' after 'throw'


[warning] 339-339: src/zx/FunctionalityConstruction.cpp:339:3 [readability-suspicious-call-argument]
2nd argument 'target' (passed to 'ctrl') looks like it might be swapped with the 3rd, 'control' (passed to 'target')


[warning] 336-336: src/zx/FunctionalityConstruction.cpp:336:3 [readability-suspicious-call-argument]
2nd argument 'target' (passed to 'ctrl') looks like it might be swapped with the 3rd, 'control' (passed to 'target')

⏰ Context from checks skipped due to timeout of 900000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (5)
  • GitHub Check: 🐍 Test (ubuntu-24.04) / 🐍 ubuntu-24.04
  • GitHub Check: 🐍 Test (macos-14) / 🐍 macos-14
  • GitHub Check: 🐍 Test (windows-2022) / 🐍 windows-2022
  • GitHub Check: 🐍 Test (macos-15-intel) / 🐍 macos-15-intel
  • GitHub Check: 🐍 Test (ubuntu-24.04-arm) / 🐍 ubuntu-24.04-arm
🔇 Additional comments (9)
src/zx/FunctionalityConstruction.cpp (9)

310-330: LGTM!

The addCcz implementation correctly decomposes the CCZ gate using standard T-gate decomposition. The Hadamard edges are appropriately placed at the end (compared to addCcx which has them at start/end) since CCZ = H·CCX·H on the target.


342-364: Declare nextControl as const.

The variable nextControl is not modified after initialization and should be declared const.

-    const Qubit nextControl = controls.back();
+    const Qubit nextControl = controls.back();

Note: This appears to already be addressed in the current code (line 356 shows const). If the static analysis tool is still flagging this, the issue may be resolved.


424-449: LGTM!

The addMcz function correctly implements multi-controlled Z using recursive decomposition with proper base cases for 0, 1, and 2 controls. The nextControl variable is already declared const.


682-684: LGTM!

Correctly routes single-controlled RZ operations to the new addCrz function.


725-742: LGTM!

The two-control parsing correctly handles CCZ and MCRZ operations. The controls vector is appropriately constructed for the MCRZ case while maintaining backward compatibility with the existing CCX/CCZ signatures.


743-760: LGTM!

The multi-control parsing branch correctly handles MCX, MCZ (via H·MCX·H decomposition), and MCRZ operations for gates with more than 2 controls. The Hadamard sandwiching for MCZ is the correct identity.


874-897: LGTM!

The transformableToZX function correctly extends support to recognize RZ operations in single-control, two-control, and multi-control contexts, consistent with the new parsing implementations.


416-419: Declare lastControl as const.

The variable lastControl is not modified after initialization.

-      const Qubit lastControl = controls.back();
+      const Qubit lastControl = controls.back();

Note: Line 416 already shows const in the provided code, so this may already be addressed.


382-384: Consider declaring first as const.

The first vector is not modified after construction and could be declared const for better const-correctness. The second vector cannot be const since it's modified on line 399.

     const auto half = static_cast<std::ptrdiff_t>((controls.size() + 1) / 2);
-    const std::vector<Qubit> first(controls.begin(), controls.begin() + half);
+    const std::vector<Qubit> first(controls.begin(), controls.begin() + half);
     std::vector<Qubit> second(controls.begin() + half, controls.end());

Note: Line 383 already shows const in the provided code, so this appears to be addressed.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

📜 Review details

Configuration used: CodeRabbit UI

Review profile: ASSERTIVE

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f8c4503 and 3142193.

📒 Files selected for processing (1)
  • test/zx/test_zx_functionality.cpp (1 hunks)
🧰 Additional context used
🧠 Learnings (3)
📓 Common learnings
Learnt from: DRovara
Repo: munich-quantum-toolkit/core PR: 1108
File: mlir/test/Dialect/MQTOpt/Transforms/lift-measurements.mlir:269-288
Timestamp: 2025-10-09T13:20:11.483Z
Learning: In the MQT MLIR dialect, the `rz` gate should not be included in the `DIAGONAL_GATES` set for the `ReplaceBasisStateControlsWithIfPattern` because its operator matrix does not have the required shape | 1 0 | / | 0 x | for the targets-as-controls optimization. It is only included in `LiftMeasurementsAboveGatesPatterns` where the matrix structure requirement differs.
📚 Learning: 2025-12-08T12:44:05.874Z
Learnt from: denialhaag
Repo: munich-quantum-toolkit/core PR: 1264
File: mlir/lib/Dialect/Quartz/IR/Modifiers/CtrlOp.cpp:60-70
Timestamp: 2025-12-08T12:44:05.874Z
Learning: In the Quartz dialect (mlir/lib/Dialect/Quartz/IR/Modifiers/CtrlOp.cpp), negative controls are not supported at the current stage. The RemoveTrivialCtrl pattern correctly only checks getNumPosControls() when determining if a CtrlOp should be removed.

Applied to files:

  • test/zx/test_zx_functionality.cpp
📚 Learning: 2025-10-09T13:20:11.483Z
Learnt from: DRovara
Repo: munich-quantum-toolkit/core PR: 1108
File: mlir/test/Dialect/MQTOpt/Transforms/lift-measurements.mlir:269-288
Timestamp: 2025-10-09T13:20:11.483Z
Learning: In the MQT MLIR dialect, the `rz` gate should not be included in the `DIAGONAL_GATES` set for the `ReplaceBasisStateControlsWithIfPattern` because its operator matrix does not have the required shape | 1 0 | / | 0 x | for the targets-as-controls optimization. It is only included in `LiftMeasurementsAboveGatesPatterns` where the matrix structure requirement differs.

Applied to files:

  • test/zx/test_zx_functionality.cpp
🧬 Code graph analysis (1)
test/zx/test_zx_functionality.cpp (2)
src/zx/FunctionalityConstruction.cpp (2)
  • buildFunctionality (789-806)
  • buildFunctionality (789-790)
test/zx/test_simplify.cpp (1)
  • fullReduce (602-602)
🪛 Cppcheck (2.18.0)
test/zx/test_zx_functionality.cpp

[error] 269-269: syntax error

(syntaxError)

🔇 Additional comments (4)
test/zx/test_zx_functionality.cpp (4)

222-245: CRZ decomposition test is mathematically sound

The CRZ(π/2) vs CX–RZ(-π/4)–CX–RZ(π/4) equivalence is correct (exact, no global phase), and the functionality + reduction checks are appropriate for validating the new CRZ support.


247-268: MultiCZ equivalence to H–MCX–H is correct

Using qc.mcz({1, 2}, 0) and comparing against h(0); mcx({1, 2}, 0); h(0); is the standard construction for MCZ and should be functionally identical with zero global phase; the identity and phase checks nicely exercise the new MCZ path.


269-295: CCZ vs H–MCX–H construction is appropriate

Importing ccz from OpenQASM and comparing it with h(0); mcx({1, 2}, 0); h(0); is a valid way to test CCZ support; this pattern realizes a three-qubit phase flip on |111⟩ with no extra global phase, so the identity and zero-global-phase expectations are well chosen.


296-383: Good coverage of MCX semantics across arities and decompositions

The new MCX tests collectively cover:

  • general MCX construction and inversion (MultiControlX);
  • ancilla-based decomposition on a larger register (MultiControlXLarger);
  • the degenerate 0-control case behaving as plain X (MultiControlX0);
  • the 1-control case matching CX (MultiControlX1).

These are well-structured functionality checks for the new multi-control-X support.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

♻️ Duplicate comments (1)
test/zx/test_zx_functionality.cpp (1)

385-398: Consider strengthening connectivity assertions.

The MCRZ test currently only checks connectivity for qubit 0. Following the pattern in complexCircuit (lines 165-167), consider verifying connectivity for all involved qubits (0, 1, and 2) to catch potential wiring issues.

Apply this diff to strengthen the test:

   EXPECT_TRUE(d.isIdentity());
   EXPECT_TRUE(d.globalPhaseIsZero());
   EXPECT_TRUE(d.connected(d.getInput(0), d.getOutput(0)));
+  EXPECT_TRUE(d.connected(d.getInput(1), d.getOutput(1)));
+  EXPECT_TRUE(d.connected(d.getInput(2), d.getOutput(2)));
 }
📜 Review details

Configuration used: CodeRabbit UI

Review profile: ASSERTIVE

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 3142193 and 1d008c6.

📒 Files selected for processing (2)
  • src/zx/FunctionalityConstruction.cpp (5 hunks)
  • test/zx/test_zx_functionality.cpp (1 hunks)
🧰 Additional context used
🧠 Learnings (10)
📓 Common learnings
Learnt from: DRovara
Repo: munich-quantum-toolkit/core PR: 1108
File: mlir/test/Dialect/MQTOpt/Transforms/lift-measurements.mlir:269-288
Timestamp: 2025-10-09T13:20:11.483Z
Learning: In the MQT MLIR dialect, the `rz` gate should not be included in the `DIAGONAL_GATES` set for the `ReplaceBasisStateControlsWithIfPattern` because its operator matrix does not have the required shape | 1 0 | / | 0 x | for the targets-as-controls optimization. It is only included in `LiftMeasurementsAboveGatesPatterns` where the matrix structure requirement differs.
📚 Learning: 2025-12-08T12:44:05.874Z
Learnt from: denialhaag
Repo: munich-quantum-toolkit/core PR: 1264
File: mlir/lib/Dialect/Quartz/IR/Modifiers/CtrlOp.cpp:60-70
Timestamp: 2025-12-08T12:44:05.874Z
Learning: In the Quartz dialect (mlir/lib/Dialect/Quartz/IR/Modifiers/CtrlOp.cpp), negative controls are not supported at the current stage. The RemoveTrivialCtrl pattern correctly only checks getNumPosControls() when determining if a CtrlOp should be removed.

Applied to files:

  • test/zx/test_zx_functionality.cpp
  • src/zx/FunctionalityConstruction.cpp
📚 Learning: 2025-11-24T10:19:41.147Z
Learnt from: burgholzer
Repo: munich-quantum-toolkit/core PR: 1326
File: python/mqt/core/__init__.py:22-22
Timestamp: 2025-11-24T10:19:41.147Z
Learning: In the munich-quantum-toolkit/core repository, Ruff is configured with 'ALL' rules enabled by default, and only specific rules are selectively disabled. When reviewing changes that enable previously-disabled rules (like PLC0415), noqa directives for those rules become necessary and should be retained.

Applied to files:

  • test/zx/test_zx_functionality.cpp
📚 Learning: 2025-12-04T06:59:40.314Z
Learnt from: MatthiasReumann
Repo: munich-quantum-toolkit/core PR: 1301
File: mlir/lib/Dialect/MQTOpt/Transforms/Transpilation/LayeredUnit.cpp:84-85
Timestamp: 2025-12-04T06:59:40.314Z
Learning: In the MQTOpt MLIR routing passes (NaiveRoutingPassSC, AStarRoutingPassSC), the input IR is guaranteed to contain only 1-qubit and 2-qubit gates. All 3+-qubit gates must be decomposed before routing; otherwise the input IR is invalid. This invariant allows skipTwoQubitBlock in LayeredUnit.cpp to safely assert wires.size() == 2.

Applied to files:

  • test/zx/test_zx_functionality.cpp
📚 Learning: 2025-11-01T15:57:31.153Z
Learnt from: burgholzer
Repo: munich-quantum-toolkit/core PR: 1283
File: src/qir/runtime/QIR.cpp:196-201
Timestamp: 2025-11-01T15:57:31.153Z
Learning: In the QIR runtime (src/qir/runtime/QIR.cpp), the PRX gate (__quantum__qis__prx__body) is an alias for the R gate (Phased X-Rotation) and should call runtime.apply<qc::R>(theta, phi, qubit), not runtime.apply<qc::RX>() which is a single-parameter rotation gate.

Applied to files:

  • test/zx/test_zx_functionality.cpp
  • src/zx/FunctionalityConstruction.cpp
📚 Learning: 2025-10-09T13:20:11.483Z
Learnt from: DRovara
Repo: munich-quantum-toolkit/core PR: 1108
File: mlir/test/Dialect/MQTOpt/Transforms/lift-measurements.mlir:269-288
Timestamp: 2025-10-09T13:20:11.483Z
Learning: In the MQT MLIR dialect, the `rz` gate should not be included in the `DIAGONAL_GATES` set for the `ReplaceBasisStateControlsWithIfPattern` because its operator matrix does not have the required shape | 1 0 | / | 0 x | for the targets-as-controls optimization. It is only included in `LiftMeasurementsAboveGatesPatterns` where the matrix structure requirement differs.

Applied to files:

  • test/zx/test_zx_functionality.cpp
  • src/zx/FunctionalityConstruction.cpp
📚 Learning: 2025-12-08T23:16:16.276Z
Learnt from: denialhaag
Repo: munich-quantum-toolkit/core PR: 1264
File: mlir/lib/Dialect/Flux/IR/Modifiers/CtrlOp.cpp:78-101
Timestamp: 2025-12-08T23:16:16.276Z
Learning: In the Flux dialect (mlir/lib/Dialect/Flux/IR/Modifiers/CtrlOp.cpp), negative controls are not supported at the current stage. The CtrlInlineGPhase canonicalization pattern correctly only checks getNumPosControls() and processes only positive controls when inlining a GPhaseOp.

Applied to files:

  • src/zx/FunctionalityConstruction.cpp
📚 Learning: 2025-11-20T18:19:31.857Z
Learnt from: lsschmid
Repo: munich-quantum-toolkit/qmap PR: 832
File: src/hybridmap/HybridNeutralAtomMapper.cpp:1679-1715
Timestamp: 2025-11-20T18:19:31.857Z
Learning: In src/hybridmap/HybridNeutralAtomMapper.cpp, the compareSwapAndBridge and compareShuttlingAndFlyingAncilla methods intentionally use division by zero to produce infinity when distance reductions are zero or negative. This infinity value marks that option as highly unfavorable in cost comparisons, which is the intended behavior rather than a bug.

Applied to files:

  • src/zx/FunctionalityConstruction.cpp
📚 Learning: 2025-12-08T14:55:43.880Z
Learnt from: denialhaag
Repo: munich-quantum-toolkit/core PR: 1264
File: mlir/lib/Dialect/Flux/IR/Modifiers/CtrlOp.cpp:78-100
Timestamp: 2025-12-08T14:55:43.880Z
Learning: In the Flux dialect (mlir/lib/Dialect/Flux/IR/Modifiers/CtrlOp.cpp), GPhaseOp is a zero-target operation (global phase). When a CtrlOp wraps a GPhaseOp, it only has control qubits and no targets. The CtrlInlineGPhase canonicalization pattern correctly produces outputs only for the positive controls, not targets.

Applied to files:

  • src/zx/FunctionalityConstruction.cpp
📚 Learning: 2025-10-09T13:13:51.224Z
Learnt from: DRovara
Repo: munich-quantum-toolkit/core PR: 1108
File: mlir/lib/Dialect/MQTOpt/Transforms/ReplaceBasisStateControlsWithIfPattern.cpp:171-180
Timestamp: 2025-10-09T13:13:51.224Z
Learning: In MQT Core MLIR, UnitaryInterface operations guarantee 1-1 correspondence between input and output qubits in the same order. When cloning or modifying unitary operations (e.g., removing controls), this correspondence is maintained by construction, so yielding getAllInQubits() in else-branches matches the result types from the operation's outputs.

Applied to files:

  • src/zx/FunctionalityConstruction.cpp
🧬 Code graph analysis (1)
test/zx/test_zx_functionality.cpp (1)
src/zx/FunctionalityConstruction.cpp (2)
  • buildFunctionality (791-808)
  • buildFunctionality (791-792)
🪛 GitHub Check: 🇨‌ Lint / 🚨 Lint
test/zx/test_zx_functionality.cpp

[warning] 277-277: test/zx/test_zx_functionality.cpp:277:3 [misc-const-correctness]
variable 'diag' of type 'ZXDiagram' can be declared 'const'

src/zx/FunctionalityConstruction.cpp

[warning] 340-340: src/zx/FunctionalityConstruction.cpp:340:3 [readability-suspicious-call-argument]
2nd argument 'target' (passed to 'ctrl') looks like it might be swapped with the 3rd, 'control' (passed to 'target')


[warning] 337-337: src/zx/FunctionalityConstruction.cpp:337:3 [readability-suspicious-call-argument]
2nd argument 'target' (passed to 'ctrl') looks like it might be swapped with the 3rd, 'control' (passed to 'target')

⏰ Context from checks skipped due to timeout of 900000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (4)
  • GitHub Check: 🐍 Test (windows-2022) / 🐍 windows-2022
  • GitHub Check: 🐍 Test (macos-14) / 🐍 macos-14
  • GitHub Check: 🐍 Test (macos-15-intel) / 🐍 macos-15-intel
  • GitHub Check: 🐍 Test (ubuntu-24.04) / 🐍 ubuntu-24.04
🔇 Additional comments (15)
test/zx/test_zx_functionality.cpp (6)

222-245: LGTM: CRZ test validates controlled-RZ decomposition.

The test correctly verifies that the CRZ gate implementation matches the expected decomposition using CNOT and RZ gates, and properly checks identity, zero global phase, and connectivity after reduction.


247-268: LGTM: MultiCZ test validates multi-controlled Z construction.

The test correctly verifies that MCZ is equivalent to H-MCX-H construction, with proper identity, phase, and connectivity checks.


296-315: LGTM: Multi-control X now supported.

The test correctly validates that multi-controlled X gates (with 3 controls) are now transformable and produce identity when inverted, confirming the PR objective to add multi-control support.


317-339: LGTM: Ancilla-assisted MCX decomposition validated.

The test correctly verifies the ancilla-assisted decomposition of MCX with 3 controls in a 5-qubit system, ensuring the decomposition is functionally equivalent.


341-361: LGTM: Edge case for 0-control MCX validated.

The test correctly verifies that MCX with no controls reduces to a simple X gate.


363-383: LGTM: Edge case for 1-control MCX validated.

The test correctly verifies that MCX with one control reduces to a CNOT gate.

src/zx/FunctionalityConstruction.cpp (9)

310-330: LGTM: CCZ implementation optimizes away redundant Hadamard edges.

The addCcz function correctly implements a double-controlled Z gate by removing the initial and final Hadamard transformations from the CCX decomposition, providing an optimized construction as mentioned in the PR description.


332-341: LGTM: CRZ decomposition correctly implemented.

The controlled-RZ decomposition correctly uses reversed CNOT direction (target→control) with appropriate phase factors (±θ/2), and includes a clarifying comment per previous review feedback.


343-365: LGTM: MCRZ recursive decomposition is correct.

The multi-controlled RZ implementation correctly handles:

  • Base case 0: Direct RZ spider
  • Base case 1: CRZ
  • Recursive case: Standard decomposition using CRZ(θ/2) interleaved with MCX to implement the controlled phase gate

The recursive pattern matches standard quantum computing decompositions.


367-424: LGTM: MCX decomposition handles all cases correctly.

The multi-controlled X implementation properly handles:

  • Base cases: 0 controls (X), 1 control (CNOT), 2 controls (CCX)
  • Ancilla-assisted recursion when spare qubits are available
  • No-ancilla decomposition using RX + MCZ pattern when qubits are fully utilized

The ancilla search logic and error handling were addressed in previous reviews. The divide-and-conquer strategy is correct.


426-451: LGTM: MCZ recursive decomposition is correct.

The multi-controlled Z implementation correctly handles base cases (0, 1, 2 controls) and uses the standard recursive decomposition with CRZ(π/2) interleaved with MCX for larger control counts.


684-686: LGTM: RZ added to single-control routing.

Correctly routes controlled-RZ operations through the new addCrz function when a single control is present.


727-744: LGTM: Two-control branch extended for Z and RZ.

The two-control branch now:

  • Extracts controls into a vector for use by multi-control functions
  • Routes CCZ through addCcz
  • Routes CCRZ through addMcrz

This correctly extends the transformation capabilities for double-controlled gates.


745-766: LGTM: Multi-control branch handles X, Z, and RZ.

The new multi-control branch (3+ controls, single target) correctly:

  • Routes MCX through addMcx
  • Routes MCZ through H-MCX-H pattern
  • Routes MCRZ through addMcrz
  • Throws for unsupported operations

This implements the core PR objective of supporting multi-controlled gates.


866-899: LGTM: transformableToZX correctly updated for RZ support.

The transformableToZX function now correctly recognizes RZ as transformable in:

  • Single-control scenarios (line 876)
  • Two-control scenarios (line 886)
  • Multi-control scenarios (line 895)

This aligns with the new routing logic in parseOp and fulfills the PR objective.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

♻️ Duplicate comments (1)
src/zx/FunctionalityConstruction.cpp (1)

332-341: About the suspicious addCrz argument order warnings

Static analysis flags the calls to addCrz as “suspicious call argument” because the function signature is

void FunctionalityConstruction::addCrz(
    ZXDiagram& diag,
    const PiExpression& phase,
    const Qubit target, const Qubit control,
    std::vector<Vertex>& qubits)

while call sites conceptually pass (control, target).

Given the body:

// CRZ decomposition uses reversed CNOT direction
addCnot(diag, control, target, qubits);
addZSpider(diag, target, qubits, -phase / 2);
addZSpider(diag, control, qubits, phase / 2);
addCnot(diag, control, target, qubits);

and how it’s invoked from parseOp and the multi-control helpers, the effective semantics are consistent with the intended CRZ decomposition (as validated by the new CRZ / MCRZ tests). The warnings are therefore a readability issue rather than a correctness bug.

If you want to silence the tools and make the intent clearer, consider flipping the parameter names/order to (const Qubit control, const Qubit target) and updating the call sites accordingly, so callers and implementation agree on ordering and static analysis no longer complains.

Also applies to: 360-363, 446-448, 684-686

📜 Review details

Configuration used: CodeRabbit UI

Review profile: ASSERTIVE

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 1d008c6 and e2b7f7b.

📒 Files selected for processing (2)
  • src/zx/FunctionalityConstruction.cpp (5 hunks)
  • test/zx/test_zx_functionality.cpp (1 hunks)
🧰 Additional context used
🧠 Learnings (12)
📓 Common learnings
Learnt from: DRovara
Repo: munich-quantum-toolkit/core PR: 1108
File: mlir/test/Dialect/MQTOpt/Transforms/lift-measurements.mlir:269-288
Timestamp: 2025-10-09T13:20:11.483Z
Learning: In the MQT MLIR dialect, the `rz` gate should not be included in the `DIAGONAL_GATES` set for the `ReplaceBasisStateControlsWithIfPattern` because its operator matrix does not have the required shape | 1 0 | / | 0 x | for the targets-as-controls optimization. It is only included in `LiftMeasurementsAboveGatesPatterns` where the matrix structure requirement differs.
Learnt from: MatthiasReumann
Repo: munich-quantum-toolkit/core PR: 1301
File: mlir/lib/Dialect/MQTOpt/Transforms/Transpilation/LayeredUnit.cpp:84-85
Timestamp: 2025-12-04T06:59:40.314Z
Learning: In the MQTOpt MLIR routing passes (NaiveRoutingPassSC, AStarRoutingPassSC), the input IR is guaranteed to contain only 1-qubit and 2-qubit gates. All 3+-qubit gates must be decomposed before routing; otherwise the input IR is invalid. This invariant allows skipTwoQubitBlock in LayeredUnit.cpp to safely assert wires.size() == 2.
📚 Learning: 2025-10-09T13:20:11.483Z
Learnt from: DRovara
Repo: munich-quantum-toolkit/core PR: 1108
File: mlir/test/Dialect/MQTOpt/Transforms/lift-measurements.mlir:269-288
Timestamp: 2025-10-09T13:20:11.483Z
Learning: In the MQT MLIR dialect, the `rz` gate should not be included in the `DIAGONAL_GATES` set for the `ReplaceBasisStateControlsWithIfPattern` because its operator matrix does not have the required shape | 1 0 | / | 0 x | for the targets-as-controls optimization. It is only included in `LiftMeasurementsAboveGatesPatterns` where the matrix structure requirement differs.

Applied to files:

  • src/zx/FunctionalityConstruction.cpp
  • test/zx/test_zx_functionality.cpp
📚 Learning: 2025-12-08T23:58:03.684Z
Learnt from: denialhaag
Repo: munich-quantum-toolkit/core PR: 1264
File: mlir/lib/Dialect/Quartz/IR/Modifiers/CtrlOp.cpp:80-100
Timestamp: 2025-12-08T23:58:03.684Z
Learning: In the Quartz dialect (mlir/lib/Dialect/Quartz/IR/Modifiers/CtrlOp.cpp), quartz.ctrl uses reference semantics and does not return values, unlike flux.ctrl which uses value semantics and returns transformed qubits. When inlining a GPhaseOp in the CtrlInlineGPhase pattern, it's correct to create POp operations for positive controls and erase the CtrlOp without collecting or replacing result values.

Applied to files:

  • src/zx/FunctionalityConstruction.cpp
📚 Learning: 2025-12-08T12:44:05.874Z
Learnt from: denialhaag
Repo: munich-quantum-toolkit/core PR: 1264
File: mlir/lib/Dialect/Quartz/IR/Modifiers/CtrlOp.cpp:60-70
Timestamp: 2025-12-08T12:44:05.874Z
Learning: In the Quartz dialect (mlir/lib/Dialect/Quartz/IR/Modifiers/CtrlOp.cpp), negative controls are not supported at the current stage. The RemoveTrivialCtrl pattern correctly only checks getNumPosControls() when determining if a CtrlOp should be removed.

Applied to files:

  • src/zx/FunctionalityConstruction.cpp
  • test/zx/test_zx_functionality.cpp
📚 Learning: 2025-12-08T23:16:16.276Z
Learnt from: denialhaag
Repo: munich-quantum-toolkit/core PR: 1264
File: mlir/lib/Dialect/Flux/IR/Modifiers/CtrlOp.cpp:78-101
Timestamp: 2025-12-08T23:16:16.276Z
Learning: In the Flux dialect (mlir/lib/Dialect/Flux/IR/Modifiers/CtrlOp.cpp), negative controls are not supported at the current stage. The CtrlInlineGPhase canonicalization pattern correctly only checks getNumPosControls() and processes only positive controls when inlining a GPhaseOp.

Applied to files:

  • src/zx/FunctionalityConstruction.cpp
📚 Learning: 2025-11-20T18:19:31.857Z
Learnt from: lsschmid
Repo: munich-quantum-toolkit/qmap PR: 832
File: src/hybridmap/HybridNeutralAtomMapper.cpp:1679-1715
Timestamp: 2025-11-20T18:19:31.857Z
Learning: In src/hybridmap/HybridNeutralAtomMapper.cpp, the compareSwapAndBridge and compareShuttlingAndFlyingAncilla methods intentionally use division by zero to produce infinity when distance reductions are zero or negative. This infinity value marks that option as highly unfavorable in cost comparisons, which is the intended behavior rather than a bug.

Applied to files:

  • src/zx/FunctionalityConstruction.cpp
📚 Learning: 2025-11-01T15:57:31.153Z
Learnt from: burgholzer
Repo: munich-quantum-toolkit/core PR: 1283
File: src/qir/runtime/QIR.cpp:196-201
Timestamp: 2025-11-01T15:57:31.153Z
Learning: In the QIR runtime (src/qir/runtime/QIR.cpp), the PRX gate (__quantum__qis__prx__body) is an alias for the R gate (Phased X-Rotation) and should call runtime.apply<qc::R>(theta, phi, qubit), not runtime.apply<qc::RX>() which is a single-parameter rotation gate.

Applied to files:

  • src/zx/FunctionalityConstruction.cpp
  • test/zx/test_zx_functionality.cpp
📚 Learning: 2025-12-08T14:55:43.880Z
Learnt from: denialhaag
Repo: munich-quantum-toolkit/core PR: 1264
File: mlir/lib/Dialect/Flux/IR/Modifiers/CtrlOp.cpp:78-100
Timestamp: 2025-12-08T14:55:43.880Z
Learning: In the Flux dialect (mlir/lib/Dialect/Flux/IR/Modifiers/CtrlOp.cpp), GPhaseOp is a zero-target operation (global phase). When a CtrlOp wraps a GPhaseOp, it only has control qubits and no targets. The CtrlInlineGPhase canonicalization pattern correctly produces outputs only for the positive controls, not targets.

Applied to files:

  • src/zx/FunctionalityConstruction.cpp
📚 Learning: 2025-10-09T13:13:51.224Z
Learnt from: DRovara
Repo: munich-quantum-toolkit/core PR: 1108
File: mlir/lib/Dialect/MQTOpt/Transforms/ReplaceBasisStateControlsWithIfPattern.cpp:171-180
Timestamp: 2025-10-09T13:13:51.224Z
Learning: In MQT Core MLIR, UnitaryInterface operations guarantee 1-1 correspondence between input and output qubits in the same order. When cloning or modifying unitary operations (e.g., removing controls), this correspondence is maintained by construction, so yielding getAllInQubits() in else-branches matches the result types from the operation's outputs.

Applied to files:

  • src/zx/FunctionalityConstruction.cpp
📚 Learning: 2025-11-24T10:19:41.147Z
Learnt from: burgholzer
Repo: munich-quantum-toolkit/core PR: 1326
File: python/mqt/core/__init__.py:22-22
Timestamp: 2025-11-24T10:19:41.147Z
Learning: In the munich-quantum-toolkit/core repository, Ruff is configured with 'ALL' rules enabled by default, and only specific rules are selectively disabled. When reviewing changes that enable previously-disabled rules (like PLC0415), noqa directives for those rules become necessary and should be retained.

Applied to files:

  • test/zx/test_zx_functionality.cpp
📚 Learning: 2025-12-04T06:59:40.314Z
Learnt from: MatthiasReumann
Repo: munich-quantum-toolkit/core PR: 1301
File: mlir/lib/Dialect/MQTOpt/Transforms/Transpilation/LayeredUnit.cpp:84-85
Timestamp: 2025-12-04T06:59:40.314Z
Learning: In the MQTOpt MLIR routing passes (NaiveRoutingPassSC, AStarRoutingPassSC), the input IR is guaranteed to contain only 1-qubit and 2-qubit gates. All 3+-qubit gates must be decomposed before routing; otherwise the input IR is invalid. This invariant allows skipTwoQubitBlock in LayeredUnit.cpp to safely assert wires.size() == 2.

Applied to files:

  • test/zx/test_zx_functionality.cpp
📚 Learning: 2025-11-20T16:57:24.305Z
Learnt from: lsschmid
Repo: munich-quantum-toolkit/qmap PR: 832
File: test/hybridmap/test_hybridmap.cpp:200-287
Timestamp: 2025-11-20T16:57:24.305Z
Learning: In test/hybridmap/test_hybridmap.cpp, the LongShuttling test is designed as a stress test to catch rare edge cases that only occur after extended shuttling sequences, which is why it maps a long circuit without explicit assertions beyond ensuring no exceptions are thrown.

Applied to files:

  • test/zx/test_zx_functionality.cpp
🧬 Code graph analysis (1)
test/zx/test_zx_functionality.cpp (2)
include/mqt-core/zx/FunctionalityConstruction.hpp (2)
  • qc (39-39)
  • qc (50-50)
src/zx/FunctionalityConstruction.cpp (2)
  • buildFunctionality (791-808)
  • buildFunctionality (791-792)
🪛 GitHub Check: 🇨‌ Lint / 🚨 Lint
src/zx/FunctionalityConstruction.cpp

[warning] 448-448: src/zx/FunctionalityConstruction.cpp:448:5 [readability-suspicious-call-argument]
3rd argument 'nextControl' (passed to 'target') looks like it might be swapped with the 4th, 'target' (passed to 'control')


[warning] 446-446: src/zx/FunctionalityConstruction.cpp:446:5 [readability-suspicious-call-argument]
3rd argument 'nextControl' (passed to 'target') looks like it might be swapped with the 4th, 'target' (passed to 'control')


[warning] 362-362: src/zx/FunctionalityConstruction.cpp:362:5 [readability-suspicious-call-argument]
3rd argument 'nextControl' (passed to 'target') looks like it might be swapped with the 4th, 'target' (passed to 'control')


[warning] 360-360: src/zx/FunctionalityConstruction.cpp:360:5 [readability-suspicious-call-argument]
3rd argument 'nextControl' (passed to 'target') looks like it might be swapped with the 4th, 'target' (passed to 'control')


[warning] 685-685: src/zx/FunctionalityConstruction.cpp:685:7 [readability-suspicious-call-argument]
3rd argument 'ctrl' (passed to 'target') looks like it might be swapped with the 4th, 'target' (passed to 'control')

⏰ Context from checks skipped due to timeout of 900000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (4)
  • GitHub Check: 🐍 Test (ubuntu-24.04) / 🐍 ubuntu-24.04
  • GitHub Check: 🐍 Test (macos-14) / 🐍 macos-14
  • GitHub Check: 🐍 Test (windows-2022) / 🐍 windows-2022
  • GitHub Check: 🐍 Test (macos-15-intel) / 🐍 macos-15-intel
🔇 Additional comments (3)
test/zx/test_zx_functionality.cpp (1)

222-505: New multi-control ZX tests look correct and give solid coverage

The CRZ, CCZ, MCX/MCZ, and MCRZ tests follow the existing testing pattern (build both circuits, compose with inverse, reduce, then check identity/global phase/connectivity) and cover:

  • 0/1/2/many controls for X, Z, and RZ;
  • both direct constructions (mcz/mcx/mcrz/crz) and decompositions via standard gates (CX, H, RZ).

I don’t see functional or structural issues here; these should give good end‑to‑end coverage of the new functionality.

src/zx/FunctionalityConstruction.cpp (2)

310-365: Multi-control CCZ / CRZ / MCRZ / MCZ decompositions look structurally sound

The new helpers

  • addCcz (two controls, Z-like),
  • addCrz (controlled-RZ),
  • addMcrz (multi-controlled RZ, with 0/1-control base cases and recursive step),
  • addMcz (multi-controlled Z with 0/1/2-control base cases and recursive step),

are consistent with known constructions:

  • Base cases (0 controls → single-qubit gate, 1 control → CRZ, 2 controls → CCZ) are explicit.
  • Recursive branches always shrink controls (via controls.pop_back()), so the recursion terminates.
  • The CRZ helper is reused in both the single-control path (in parseOp) and the multi-control decompositions, keeping the semantics aligned.
  • Tests exercise CRZ, CCZ, MCRZ (including k=0/1 and k>1), and MCZ (including k=0/1/2 and larger), and also check global-phase cancellation.

Given that and the existing ZX primitives, the design here looks correct and maintainable.

Also applies to: 426-451


661-767: parseOp and transformableToZX extensions for controlled RZ and multi-control gates are consistent

The changes in:

  • parseOp:

    • add a qc::OpType::RZ case for 1-control/1-target gates using addCrz;
    • route 2-control RZ to addMcrz with a 2-element controls vector;
    • route general multi-control X/Z/RZ (one target) to addMcx, the CZ-style H–MCX–H pattern, and addMcrz respectively.
  • transformableToZX:

    • include qc::OpType::RZ in the supported sets for
      • uncontrolled single-qubit,
      • single-control two-qubit, and
      • multi-control single-target operations,

are aligned: every newly-routed case has a corresponding “supported” entry, and unsupported multi-control types still fall through to the existing exceptions (as exercised by the UnsupportedControl tests).

I don’t see missing or inconsistent cases here.

Also applies to: 876-899

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

♻️ Duplicate comments (1)
src/zx/FunctionalityConstruction.cpp (1)

332-341: Consider swapping parameter names to match codebase convention.

The parameter order (target, control) differs from the convention used elsewhere in this file (e.g., addCnot, addCphase use (ctrl, target)). This triggers persistent static analysis warnings at every call site (lines 354, 360, 362, 436, 446, 448, 685).

While the comment clarifies the decomposition intent, renaming the parameters would eliminate linter noise and improve readability.

 void FunctionalityConstruction::addCrz(ZXDiagram& diag,
                                        const PiExpression& phase,
-                                       const Qubit target, const Qubit control,
+                                       const Qubit ctrl, const Qubit target,
                                        std::vector<Vertex>& qubits) {
   // CRZ decomposition uses reversed CNOT direction
-  addCnot(diag, control, target, qubits);
-  addZSpider(diag, target, qubits, -phase / 2);
-  addZSpider(diag, control, qubits, phase / 2);
-  addCnot(diag, control, target, qubits);
+  addCnot(diag, target, ctrl, qubits);
+  addZSpider(diag, ctrl, qubits, -phase / 2);
+  addZSpider(diag, target, qubits, phase / 2);
+  addCnot(diag, target, ctrl, qubits);
 }

This would require updating all call sites to swap arguments accordingly.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: ASSERTIVE

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 1d008c6 and e2b7f7b.

📒 Files selected for processing (2)
  • src/zx/FunctionalityConstruction.cpp (5 hunks)
  • test/zx/test_zx_functionality.cpp (1 hunks)
🧰 Additional context used
🧠 Learnings (10)
📚 Learning: 2025-12-08T12:44:05.874Z
Learnt from: denialhaag
Repo: munich-quantum-toolkit/core PR: 1264
File: mlir/lib/Dialect/Quartz/IR/Modifiers/CtrlOp.cpp:60-70
Timestamp: 2025-12-08T12:44:05.874Z
Learning: In the Quartz dialect (mlir/lib/Dialect/Quartz/IR/Modifiers/CtrlOp.cpp), negative controls are not supported at the current stage. The RemoveTrivialCtrl pattern correctly only checks getNumPosControls() when determining if a CtrlOp should be removed.

Applied to files:

  • test/zx/test_zx_functionality.cpp
  • src/zx/FunctionalityConstruction.cpp
📚 Learning: 2025-11-24T10:19:41.147Z
Learnt from: burgholzer
Repo: munich-quantum-toolkit/core PR: 1326
File: python/mqt/core/__init__.py:22-22
Timestamp: 2025-11-24T10:19:41.147Z
Learning: In the munich-quantum-toolkit/core repository, Ruff is configured with 'ALL' rules enabled by default, and only specific rules are selectively disabled. When reviewing changes that enable previously-disabled rules (like PLC0415), noqa directives for those rules become necessary and should be retained.

Applied to files:

  • test/zx/test_zx_functionality.cpp
📚 Learning: 2025-10-09T13:20:11.483Z
Learnt from: DRovara
Repo: munich-quantum-toolkit/core PR: 1108
File: mlir/test/Dialect/MQTOpt/Transforms/lift-measurements.mlir:269-288
Timestamp: 2025-10-09T13:20:11.483Z
Learning: In the MQT MLIR dialect, the `rz` gate should not be included in the `DIAGONAL_GATES` set for the `ReplaceBasisStateControlsWithIfPattern` because its operator matrix does not have the required shape | 1 0 | / | 0 x | for the targets-as-controls optimization. It is only included in `LiftMeasurementsAboveGatesPatterns` where the matrix structure requirement differs.

Applied to files:

  • test/zx/test_zx_functionality.cpp
  • src/zx/FunctionalityConstruction.cpp
📚 Learning: 2025-11-20T16:57:24.305Z
Learnt from: lsschmid
Repo: munich-quantum-toolkit/qmap PR: 832
File: test/hybridmap/test_hybridmap.cpp:200-287
Timestamp: 2025-11-20T16:57:24.305Z
Learning: In test/hybridmap/test_hybridmap.cpp, the LongShuttling test is designed as a stress test to catch rare edge cases that only occur after extended shuttling sequences, which is why it maps a long circuit without explicit assertions beyond ensuring no exceptions are thrown.

Applied to files:

  • test/zx/test_zx_functionality.cpp
📚 Learning: 2025-12-08T23:58:03.684Z
Learnt from: denialhaag
Repo: munich-quantum-toolkit/core PR: 1264
File: mlir/lib/Dialect/Quartz/IR/Modifiers/CtrlOp.cpp:80-100
Timestamp: 2025-12-08T23:58:03.684Z
Learning: In the Quartz dialect (mlir/lib/Dialect/Quartz/IR/Modifiers/CtrlOp.cpp), quartz.ctrl uses reference semantics and does not return values, unlike flux.ctrl which uses value semantics and returns transformed qubits. When inlining a GPhaseOp in the CtrlInlineGPhase pattern, it's correct to create POp operations for positive controls and erase the CtrlOp without collecting or replacing result values.

Applied to files:

  • src/zx/FunctionalityConstruction.cpp
📚 Learning: 2025-12-08T23:16:16.276Z
Learnt from: denialhaag
Repo: munich-quantum-toolkit/core PR: 1264
File: mlir/lib/Dialect/Flux/IR/Modifiers/CtrlOp.cpp:78-101
Timestamp: 2025-12-08T23:16:16.276Z
Learning: In the Flux dialect (mlir/lib/Dialect/Flux/IR/Modifiers/CtrlOp.cpp), negative controls are not supported at the current stage. The CtrlInlineGPhase canonicalization pattern correctly only checks getNumPosControls() and processes only positive controls when inlining a GPhaseOp.

Applied to files:

  • src/zx/FunctionalityConstruction.cpp
📚 Learning: 2025-11-20T18:19:31.857Z
Learnt from: lsschmid
Repo: munich-quantum-toolkit/qmap PR: 832
File: src/hybridmap/HybridNeutralAtomMapper.cpp:1679-1715
Timestamp: 2025-11-20T18:19:31.857Z
Learning: In src/hybridmap/HybridNeutralAtomMapper.cpp, the compareSwapAndBridge and compareShuttlingAndFlyingAncilla methods intentionally use division by zero to produce infinity when distance reductions are zero or negative. This infinity value marks that option as highly unfavorable in cost comparisons, which is the intended behavior rather than a bug.

Applied to files:

  • src/zx/FunctionalityConstruction.cpp
📚 Learning: 2025-11-01T15:57:31.153Z
Learnt from: burgholzer
Repo: munich-quantum-toolkit/core PR: 1283
File: src/qir/runtime/QIR.cpp:196-201
Timestamp: 2025-11-01T15:57:31.153Z
Learning: In the QIR runtime (src/qir/runtime/QIR.cpp), the PRX gate (__quantum__qis__prx__body) is an alias for the R gate (Phased X-Rotation) and should call runtime.apply<qc::R>(theta, phi, qubit), not runtime.apply<qc::RX>() which is a single-parameter rotation gate.

Applied to files:

  • src/zx/FunctionalityConstruction.cpp
📚 Learning: 2025-12-08T14:55:43.880Z
Learnt from: denialhaag
Repo: munich-quantum-toolkit/core PR: 1264
File: mlir/lib/Dialect/Flux/IR/Modifiers/CtrlOp.cpp:78-100
Timestamp: 2025-12-08T14:55:43.880Z
Learning: In the Flux dialect (mlir/lib/Dialect/Flux/IR/Modifiers/CtrlOp.cpp), GPhaseOp is a zero-target operation (global phase). When a CtrlOp wraps a GPhaseOp, it only has control qubits and no targets. The CtrlInlineGPhase canonicalization pattern correctly produces outputs only for the positive controls, not targets.

Applied to files:

  • src/zx/FunctionalityConstruction.cpp
📚 Learning: 2025-10-09T13:13:51.224Z
Learnt from: DRovara
Repo: munich-quantum-toolkit/core PR: 1108
File: mlir/lib/Dialect/MQTOpt/Transforms/ReplaceBasisStateControlsWithIfPattern.cpp:171-180
Timestamp: 2025-10-09T13:13:51.224Z
Learning: In MQT Core MLIR, UnitaryInterface operations guarantee 1-1 correspondence between input and output qubits in the same order. When cloning or modifying unitary operations (e.g., removing controls), this correspondence is maintained by construction, so yielding getAllInQubits() in else-branches matches the result types from the operation's outputs.

Applied to files:

  • src/zx/FunctionalityConstruction.cpp
🧬 Code graph analysis (2)
test/zx/test_zx_functionality.cpp (2)
include/mqt-core/zx/FunctionalityConstruction.hpp (2)
  • qc (39-39)
  • qc (50-50)
src/zx/FunctionalityConstruction.cpp (2)
  • buildFunctionality (791-808)
  • buildFunctionality (791-792)
src/zx/FunctionalityConstruction.cpp (2)
include/mqt-core/ir/operations/OpType.hpp (1)
  • toString (40-40)
src/ir/operations/OpType.cpp (2)
  • toString (21-35)
  • toString (21-21)
🪛 GitHub Check: 🇨‌ Lint / 🚨 Lint
src/zx/FunctionalityConstruction.cpp

[warning] 448-448: src/zx/FunctionalityConstruction.cpp:448:5 [readability-suspicious-call-argument]
3rd argument 'nextControl' (passed to 'target') looks like it might be swapped with the 4th, 'target' (passed to 'control')


[warning] 446-446: src/zx/FunctionalityConstruction.cpp:446:5 [readability-suspicious-call-argument]
3rd argument 'nextControl' (passed to 'target') looks like it might be swapped with the 4th, 'target' (passed to 'control')


[warning] 362-362: src/zx/FunctionalityConstruction.cpp:362:5 [readability-suspicious-call-argument]
3rd argument 'nextControl' (passed to 'target') looks like it might be swapped with the 4th, 'target' (passed to 'control')


[warning] 360-360: src/zx/FunctionalityConstruction.cpp:360:5 [readability-suspicious-call-argument]
3rd argument 'nextControl' (passed to 'target') looks like it might be swapped with the 4th, 'target' (passed to 'control')


[warning] 685-685: src/zx/FunctionalityConstruction.cpp:685:7 [readability-suspicious-call-argument]
3rd argument 'ctrl' (passed to 'target') looks like it might be swapped with the 4th, 'target' (passed to 'control')

⏰ Context from checks skipped due to timeout of 900000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: 🐍 Test (windows-2022) / 🐍 windows-2022
  • GitHub Check: 🐍 Test (macos-15-intel) / 🐍 macos-15-intel
🔇 Additional comments (13)
src/zx/FunctionalityConstruction.cpp (6)

310-330: LGTM: CCZ decomposition correctly optimizes away Hadamard bookends.

The addCcz implementation is a well-optimized variant of CCX that directly produces the CCZ decomposition. Compared to addCcx, it removes the opening H gate and adjusts the closing sequence to use an H-edge followed by another H-edge, which correctly implements CCZ = H(target) · CCX · H(target) in a more efficient ZX form.


343-365: LGTM: MCRZ recursive decomposition is correct.

The implementation correctly handles base cases (0 and 1 controls) and uses the standard recursive decomposition: CRZ(θ/2) · MCX · CRZ(-θ/2) · MCX for extracting one control at a time.


367-424: LGTM: MCX decomposition with ancilla-based optimization.

The implementation correctly handles all base cases and provides two decomposition paths:

  1. When ancilla qubits are available: efficient divide-and-conquer using the spare qubit
  2. When no ancilla available: RX-based decomposition using MCZ and MCRZ

Previous review issues (uninitialized anc, missing error check) have been properly addressed.


426-451: LGTM: MCZ recursive decomposition is correct.

The implementation properly handles all base cases including the use of addCcz for 2 controls (which is more efficient than the general recursion). The recursive decomposition follows the standard pattern.


684-686: LGTM: parseOp correctly routes multi-control operations to new handlers.

The integration properly:

  1. Routes single-control RZ to addCrz
  2. Builds control vectors from operation controls for 2+ control cases
  3. Delegates to addMcrz, addMcx, addMcz as appropriate

The static analysis warning on line 685 is the same addCrz parameter naming issue noted earlier.

Also applies to: 727-744, 745-766


876-900: LGTM: transformableToZX correctly updated for new multi-control gates.

The transformability checks now properly reflect the expanded parseOp capabilities, allowing RZ in single-control, 2-control, and arbitrary multi-control contexts.

test/zx/test_zx_functionality.cpp (7)

222-245: LGTM: CRZ test properly validates against known decomposition.

The test correctly validates CRZ by comparing against the explicit decomposition: CNOT · RZ(-θ/2) · CNOT · RZ(θ/2).


247-268: LGTM: MultiCZ test validates against H·MCX·H equivalence.

Correct validation that MCZ equals H·MCX·H on the target qubit.


269-293: LGTM: CCZ test validates correctly.

Past review issue (unused diag variable) has been addressed.


316-338: LGTM: Proper validation against ancilla-based decomposition.

This test correctly validates the MCX decomposition by comparing against the explicit ancilla-based construction that the implementation uses internally.


340-382: LGTM: Boundary cases for MCX properly tested.

MultiControlX0 validates 0-control MCX equals X, and MultiControlX1 validates 1-control MCX equals CNOT. These are important boundary condition tests.


384-449: LGTM: Comprehensive MCZ test coverage.

The tests properly validate:

  • MultiControlZ: MCZ equals H·MCX·H
  • MultiControlZ0: 0-control MCZ equals Z
  • MultiControlZ1: 1-control MCZ equals CZ

Good coverage of boundary conditions and correct equivalences.


451-506: LGTM: MCRZ tests cover self-inverse and boundary cases.

The tests validate:

  • MultiControlRZ: MCRZ(θ) · MCRZ(-θ) = I (self-inverse property)
  • MultiControlRZ0: 0-control MCRZ equals RZ
  • MultiControlRZ1: 1-control MCRZ equals CRZ

Good boundary condition coverage.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

🤖 Fix all issues with AI agents
In @test/zx/test_zx_functionality.cpp:
- Around line 467-491: The test MultiControlZ2 in ZXFunctionalityTest allocates
4 qubits but only uses qubits 0,1,2; change the QuantumComputation constructions
qc and qcPrime to use 3 qubits instead of 4 so the test matches intent and other
tests (e.g., MultiCZ, CCZ); update the calls qc = qc::QuantumComputation(4) and
auto qcPrime = qc::QuantumComputation(4) to use 3, leaving the rest of the test
(mcz, h, mcx, FunctionalityConstruction::buildFunctionality, d.concat,
fullReduce and the EXPECT_* checks) unchanged.
- Around line 222-247: Add an assertion that the constructed QuantumComputation
is transformable to ZX in each test missing it by inserting
EXPECT_TRUE(FunctionalityConstruction::transformableToZX(&qc)); immediately
after constructing/configuring qc (and before calling
FunctionalityConstruction::buildFunctionality(&qc)). Apply this change to the
tests referenced (e.g., TEST_F(ZXFunctionalityTest, MultiControlX), TEST_F(...,
MultiControlZ), TEST_F(..., MultiControlRZ) and the test blocks covering the
ranges 249-272, 354-374, 376-397, 424-443, 445-465, 511-530, 532-552), using the
same FunctionalityConstruction::transformableToZX call as in existing tests like
CRZ to ensure consistency.
- Around line 300-323: The test MultiControlX currently compares an MCX circuit
to an identical copy, which is tautological; instead construct qcPrime as a
known decomposition of MCX (e.g., H on target, equivalent multi-controlled Z
construction, then H on target) and compare the ZX functionality of qc against
that decomposition: locate ZXFunctionalityTest::MultiControlX and replace the
qcPrime construction so it builds the H-MCZ-H decomposition (apply
qcPrime.h(target), the multi-control Z circuit used in
MultiControlZ2/MultiControlXLarger tests, then qcPrime.h(target)), then call
FunctionalityConstruction::buildFunctionality on both, concat and fullReduce as
before, and keep the same EXPECT_* assertions to validate equivalence.
- Around line 399-422: The test MultiControlZ currently compares qc.mcz({1, 2,
3}, 0) to an identical qcPrime, which is tautological; replace qcPrime with an
H-MCX-H decomposition as the reference: create qcPrime by applying H to qubit 0,
then qcPrime.mcx({1,2,3}, 0) (or mcx equivalent), then H on qubit 0 again, so
the constructed ZX from qcPrime matches the expected MCZ; keep using
FunctionalityConstruction::buildFunctionality, d.concat(dPrime.invert()),
fullReduce(d) and the same EXPECT_TRUE checks to verify identity, global phase
and connectivity.
📜 Review details

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 9816218 and 77dae77.

📒 Files selected for processing (1)
  • test/zx/test_zx_functionality.cpp
🧰 Additional context used
🧠 Learnings (12)
📓 Common learnings
Learnt from: DRovara
Repo: munich-quantum-toolkit/core PR: 1108
File: mlir/test/Dialect/MQTOpt/Transforms/lift-measurements.mlir:269-288
Timestamp: 2025-10-09T13:20:11.483Z
Learning: In the MQT MLIR dialect, the `rz` gate should not be included in the `DIAGONAL_GATES` set for the `ReplaceBasisStateControlsWithIfPattern` because its operator matrix does not have the required shape | 1 0 | / | 0 x | for the targets-as-controls optimization. It is only included in `LiftMeasurementsAboveGatesPatterns` where the matrix structure requirement differs.
📚 Learning: 2025-12-08T12:44:05.883Z
Learnt from: denialhaag
Repo: munich-quantum-toolkit/core PR: 1264
File: mlir/lib/Dialect/Quartz/IR/Modifiers/CtrlOp.cpp:60-70
Timestamp: 2025-12-08T12:44:05.883Z
Learning: In the Quartz dialect (mlir/lib/Dialect/Quartz/IR/Modifiers/CtrlOp.cpp), negative controls are not supported at the current stage. The RemoveTrivialCtrl pattern correctly only checks getNumPosControls() when determining if a CtrlOp should be removed.

Applied to files:

  • test/zx/test_zx_functionality.cpp
📚 Learning: 2025-11-24T10:19:41.147Z
Learnt from: burgholzer
Repo: munich-quantum-toolkit/core PR: 1326
File: python/mqt/core/__init__.py:22-22
Timestamp: 2025-11-24T10:19:41.147Z
Learning: In the munich-quantum-toolkit/core repository, Ruff is configured with 'ALL' rules enabled by default, and only specific rules are selectively disabled. When reviewing changes that enable previously-disabled rules (like PLC0415), noqa directives for those rules become necessary and should be retained.

Applied to files:

  • test/zx/test_zx_functionality.cpp
📚 Learning: 2025-12-04T06:59:40.314Z
Learnt from: MatthiasReumann
Repo: munich-quantum-toolkit/core PR: 1301
File: mlir/lib/Dialect/MQTOpt/Transforms/Transpilation/LayeredUnit.cpp:84-85
Timestamp: 2025-12-04T06:59:40.314Z
Learning: In the MQTOpt MLIR routing passes (NaiveRoutingPassSC, AStarRoutingPassSC), the input IR is guaranteed to contain only 1-qubit and 2-qubit gates. All 3+-qubit gates must be decomposed before routing; otherwise the input IR is invalid. This invariant allows skipTwoQubitBlock in LayeredUnit.cpp to safely assert wires.size() == 2.

Applied to files:

  • test/zx/test_zx_functionality.cpp
📚 Learning: 2025-10-09T13:13:51.224Z
Learnt from: DRovara
Repo: munich-quantum-toolkit/core PR: 1108
File: mlir/lib/Dialect/MQTOpt/Transforms/ReplaceBasisStateControlsWithIfPattern.cpp:171-180
Timestamp: 2025-10-09T13:13:51.224Z
Learning: In MQT Core MLIR, UnitaryInterface operations guarantee 1-1 correspondence between input and output qubits in the same order. When cloning or modifying unitary operations (e.g., removing controls), this correspondence is maintained by construction, so yielding getAllInQubits() in else-branches matches the result types from the operation's outputs.

Applied to files:

  • test/zx/test_zx_functionality.cpp
📚 Learning: 2025-11-20T18:19:31.857Z
Learnt from: lsschmid
Repo: munich-quantum-toolkit/qmap PR: 832
File: src/hybridmap/HybridNeutralAtomMapper.cpp:1679-1715
Timestamp: 2025-11-20T18:19:31.857Z
Learning: In src/hybridmap/HybridNeutralAtomMapper.cpp, the compareSwapAndBridge and compareShuttlingAndFlyingAncilla methods intentionally use division by zero to produce infinity when distance reductions are zero or negative. This infinity value marks that option as highly unfavorable in cost comparisons, which is the intended behavior rather than a bug.

Applied to files:

  • test/zx/test_zx_functionality.cpp
📚 Learning: 2025-10-09T13:20:11.483Z
Learnt from: DRovara
Repo: munich-quantum-toolkit/core PR: 1108
File: mlir/test/Dialect/MQTOpt/Transforms/lift-measurements.mlir:269-288
Timestamp: 2025-10-09T13:20:11.483Z
Learning: In the MQT MLIR dialect, the `rz` gate should not be included in the `DIAGONAL_GATES` set for the `ReplaceBasisStateControlsWithIfPattern` because its operator matrix does not have the required shape | 1 0 | / | 0 x | for the targets-as-controls optimization. It is only included in `LiftMeasurementsAboveGatesPatterns` where the matrix structure requirement differs.

Applied to files:

  • test/zx/test_zx_functionality.cpp
📚 Learning: 2025-12-28T17:05:10.588Z
Learnt from: burgholzer
Repo: munich-quantum-toolkit/core PR: 1403
File: test/qir/runner/test_qir_runner.cpp:35-35
Timestamp: 2025-12-28T17:05:10.588Z
Learning: In the munich-quantum-toolkit/core repository, Windows Unicode support (via _wsystem) is not needed for test utilities like test/qir/runner/test_qir_runner.cpp. Using std::system is acceptable for system calls in tests.

Applied to files:

  • test/zx/test_zx_functionality.cpp
📚 Learning: 2025-12-22T01:25:21.609Z
Learnt from: burgholzer
Repo: munich-quantum-toolkit/core PR: 1383
File: bindings/ir/register_permutation.cpp:153-171
Timestamp: 2025-12-22T01:25:21.609Z
Learning: In the munich-quantum-toolkit/core repository, when using nanobind iterator factory functions like `make_key_iterator` and `make_iterator`, the unqualified form (without explicit `nb::` prefix) is preferred. The clang-tidy configuration suggests removal of explicit namespace qualification, relying on ADL (Argument-Dependent Lookup) to resolve these functions correctly.

Applied to files:

  • test/zx/test_zx_functionality.cpp
📚 Learning: 2025-12-08T23:58:09.648Z
Learnt from: denialhaag
Repo: munich-quantum-toolkit/core PR: 1264
File: mlir/lib/Dialect/Quartz/IR/Modifiers/CtrlOp.cpp:80-100
Timestamp: 2025-12-08T23:58:09.648Z
Learning: In the Quartz dialect (mlir/lib/Dialect/Quartz/IR/Modifiers/CtrlOp.cpp), quartz.ctrl uses reference semantics and does not return values, unlike flux.ctrl which uses value semantics and returns transformed qubits. When inlining a GPhaseOp in the CtrlInlineGPhase pattern, it's correct to create POp operations for positive controls and erase the CtrlOp without collecting or replacing result values.

Applied to files:

  • test/zx/test_zx_functionality.cpp
📚 Learning: 2025-12-05T17:45:37.602Z
Learnt from: denialhaag
Repo: munich-quantum-toolkit/core PR: 1360
File: .github/workflows/reusable-mlir-tests.yml:40-43
Timestamp: 2025-12-05T17:45:37.602Z
Learning: In the munich-quantum-toolkit/core repository, patch releases of LLVM dependencies don't require documentation updates, changelog entries, or additional tests beyond what's validated by passing CI checks.

Applied to files:

  • test/zx/test_zx_functionality.cpp
📚 Learning: 2025-11-20T16:57:24.305Z
Learnt from: lsschmid
Repo: munich-quantum-toolkit/qmap PR: 832
File: test/hybridmap/test_hybridmap.cpp:200-287
Timestamp: 2025-11-20T16:57:24.305Z
Learning: In test/hybridmap/test_hybridmap.cpp, the LongShuttling test is designed as a stress test to catch rare edge cases that only occur after extended shuttling sequences, which is why it maps a long circuit without explicit assertions beyond ensuring no exceptions are thrown.

Applied to files:

  • test/zx/test_zx_functionality.cpp
🧬 Code graph analysis (1)
test/zx/test_zx_functionality.cpp (2)
include/mqt-core/zx/FunctionalityConstruction.hpp (2)
  • qc (39-39)
  • qc (50-50)
src/zx/FunctionalityConstruction.cpp (6)
  • buildFunctionality (767-784)
  • buildFunctionality (767-768)
  • transformableToZX (785-789)
  • transformableToZX (785-786)
  • transformableToZX (791-868)
  • transformableToZX (791-791)
🔇 Additional comments (6)
test/zx/test_zx_functionality.cpp (6)

222-247: LGTM!

The CRZ test correctly validates the controlled-RZ implementation by comparing against the standard CX-RZ-CX-RZ decomposition. The assertions for identity, zero global phase, and connectivity are appropriate.


249-272: LGTM!

The MultiCZ test correctly validates MCZ by comparing against the H-MCX-H decomposition.


273-298: LGTM!

The CCZ test correctly validates the CCZ gate loaded via QASM against the expected H-MCX-H decomposition.


325-352: LGTM!

The MultiControlXLarger test provides meaningful validation by comparing a 3-control MCX against its ancilla-based decomposition using 4 MCX gates with 2 controls each.


354-397: LGTM!

The edge case tests for MCX with 0 controls (reducing to X) and 1 control (reducing to CX) are correctly implemented and provide good boundary condition coverage.


493-552: LGTM!

The MCRZ tests provide good coverage including the self-inverse check and edge cases for 0 and 1 control qubits.

@keefehuang
Copy link
Author

Apologies, just back from vacation. All comments have been addressed.

@burgholzer burgholzer added this to the ZX Package Improvements milestone Jan 9, 2026
Copy link
Member

@burgholzer burgholzer left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Many thanks @keefehuang for this contribution! This is great to see. 🙌🏼
I looked through all the code and you can find some comments inline.
As for the suggestions, you should be able to directly go to the "Files Changed" tab on GitHub and go through the comments, add the suggestions to a batch and commit them in one go.

Besides the inline comments, I was wondering whether we could fairly easily extend the supported gates here by using well known gate decompositions of these gates. Gates that come to mind are SWAP, RXX, RZZ, RYY, RZX, DCX, MCRX, MCP.
None of these should add too much complexity here. What do you think?

Comment on lines +273 to +277
TEST_F(ZXFunctionalityTest, CCZ) {
const std::string testfile = "OPENQASM 2.0;"
"include \"qelib1.inc\";"
"qreg q[3];"
"ccz q[0],q[1],q[2];\n";
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why does this test use an OpenQASM file, while all others directly use the QuantumComputation API? I think I'd prefer to also have this test written as
qc.mcz(...)

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Updated

}

TEST_F(ZXFunctionalityTest, MultiControlX) {
using namespace qc::literals;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
using namespace qc::literals;

This isn't used here as far as I can tell.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Removed

}

TEST_F(ZXFunctionalityTest, MultiCZ) {
using namespace qc::literals;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
using namespace qc::literals;

This isn't used here as far as I can tell.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Similarly removed in all cases

Comment on lines +234 to +246
auto d = FunctionalityConstruction::buildFunctionality(&qc);

auto dPrime = FunctionalityConstruction::buildFunctionality(&qcPrime);

d.concat(dPrime.invert());

fullReduce(d);

EXPECT_TRUE(FunctionalityConstruction::transformableToZX(&qc));
EXPECT_TRUE(d.isIdentity());
EXPECT_TRUE(d.globalPhaseIsZero());
EXPECT_TRUE(d.connected(d.getInput(0), d.getOutput(0)));
EXPECT_TRUE(d.connected(d.getInput(1), d.getOutput(1)));
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Given how often this sequence of calls is repeated throughout the tests here, I think it would be worth to extract this into a separate function in this file to reduce the amount of duplication.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Refactored

Comment on lines +337 to +339
addCnot(diag, q1, q0, qubits);
addZSpider(diag, q0, qubits, -phase / 2);
addZSpider(diag, q1, qubits, phase / 2);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
addCnot(diag, q1, q0, qubits);
addZSpider(diag, q0, qubits, -phase / 2);
addZSpider(diag, q1, qubits, phase / 2);
addZSpider(diag, q1, qubits, phase / 2);
addCnot(diag, q1, q0, qubits);
addZSpider(diag, q0, qubits, -phase / 2);

These commute, so it does not really matter too much, but for consistency with the mcrz patter, I'd prefer this order.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These don't actually commute. However, this is an implementation that allows for more gate parallelism. (You can check that moving this around breaks the equality).

Comment on lines +388 to +390
if (!anc.has_value()) {
throw ZXException("No ancilla qubit available for MCX decomposition");
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is unreachable code, right? There are more than nctrl+1 qubits available, so there has to be one that is not in the list of controls+target. So anc does not need to be an optional.

I also think that you could be using https://en.cppreference.com/w/cpp/algorithm/set_difference.html here.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Removed unreachable code.
Implemented set_difference.

Comment on lines +425 to +428
addCrz(diag, PiExpression(PiRational(1, 2)), nextControl, target, qubits);
addMcx(diag, controls, target, qubits);
addCrz(diag, PiExpression(-PiRational(1, 2)), nextControl, target, qubits);
addMcx(diag, controls, target, qubits);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Wouldn't it be easier to either:

  • have mcz implement the logic as H -- mcx -- H, or
  • have mcx be implemented as H -- mcz -- H

Does one of these yield a shorter decomposition?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is effectively a MCx based implementation. The MCz helps reduce the MCz initial cost by a few gates compared to the H-MCX-H implementation.

Comment on lines +705 to +708
std::vector<Qubit> controls;
for (const auto& ctrl : op->getControls()) {
controls.push_back(static_cast<Qubit>(p.at(ctrl.qubit)));
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This can just be inlined as {ctrl0, ctrl1} in the addMcrz call below.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Inlined

Comment on lines +725 to +728
std::vector<Qubit> controls;
for (const auto& ctrl : op->getControls()) {
controls.push_back(static_cast<Qubit>(p.at(ctrl.qubit)));
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Always good to use reserve to preallocate the right size for the container. And to use emplace_back over push_back.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should be refactored through the file.

Co-authored-by: Lukas Burgholzer <burgholzer@me.com>
Signed-off-by: Keefe Huang <30915130+keefehuang@users.noreply.github.com>
@burgholzer
Copy link
Member

@keefehuang Just wanted to check in here. What's the current status for this PR?

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Fix all issues with AI agents
In `@test/zx/test_zx_functionality.cpp`:
- Around line 38-52: The function checkEquivalence currently ignores the qubits
parameter; update it to validate and use qubits by first checking that
qubits.size() matches the expected scope (e.g., qc1.getNqubits() or otherwise
return/ASSERT if mismatched) and then replace the loop that iterates i from
0..qc1.getNqubits() with a loop over the entries in qubits, ensuring each qubit
index is within bounds (< qc1.getNqubits()) before calling
d1.connected(d1.getInput(q), d1.getOutput(q)); keep the existing calls to
FunctionalityConstruction::transformableToZX, buildFunctionality, fullReduce and
the identity/global phase checks but operate the input/output connectivity
checks only for the provided qubits vector.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
test/zx/test_zx_functionality.cpp (1)

415-421: ⚠️ Potential issue | 🟡 Minor

Apply the final H to qcPrime, not qc.

Line 421 applies h(1) to the original circuit, so the test no longer compares iSWAP to its intended decomposition. This likely weakens the validation and can mask decomposition errors.

✅ Fix
-  qc.h(1);
+  qcPrime.h(1);

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/zx/FunctionalityConstruction.cpp (1)

954-968: ⚠️ Potential issue | 🟠 Major

Missing RX in single-control transformable gate list.

parseOp handles single-control RX (Lines 723-725) via addCrx, but transformableToZX does not include qc::OpType::RX in the single-control branch (Lines 954-968). This inconsistency means transformableToZX will incorrectly return false for circuits containing controlled-RX gates with one control.

🐛 Proposed fix
   } else if (op->getNcontrols() == 1 && op->getNtargets() == 1) {
     switch (op->getType()) { // TODO: any gate can be controlled
     case qc::OpType::X:
     case qc::OpType::Z:
     case qc::OpType::I:
     case qc::OpType::P:
     case qc::OpType::T:
     case qc::OpType::S:
     case qc::OpType::Tdg:
     case qc::OpType::Sdg:
     case qc::OpType::RZ:
+    case qc::OpType::RX:
       return true;
     default:
       return false;
     }
🤖 Fix all issues with AI agents
In `@src/zx/FunctionalityConstruction.cpp`:
- Around line 236-245: The conjugation in FunctionalityConstruction::addMcrzz is
passing the same unconvertedPhase to both addRzz calls, causing global-phase
contributions to add instead of cancel; update the second addRzz call (the one
paired with "-phase") to pass the negated unconvertedPhase when present (i.e.,
replace unconvertedPhase with an optional containing -unconvertedPhase.value()
or std::nullopt if not present) so the global-phase handling in addRzz correctly
cancels under conjugation; keep addMcx calls unchanged.
- Around line 385-392: The addCrx implementation is dividing the phase by 2 when
delegating to addCrz, producing CRX(θ/2) instead of CRX(θ); change the call in
FunctionalityConstruction::addCrx so it passes the original phase to addCrz (use
phase, not phase/2) to match the multi-controlled variant addMcrx/addMcrz and
preserve the surrounding Hadamard (addZSpider) calls.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 5

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/zx/FunctionalityConstruction.cpp`:
- Around line 831-883: The code assumes multi-target ops have at least two
targets but accesses op->getTargets()[1] without asserting that invariant; add a
short clarifying comment and a defensive check (e.g., an assertion or
ZX-specific check) referencing op->getNtargets() before using
op->getTargets()[1] to document and enforce the invariant coming from
transformableToZX, so callers can rely on it and future changes won't silently
break; locate this near the else branch handling multi-target ops in
FunctionalityConstruction (where op->getTargets(), op->getNtargets(), and
transformableToZX are used).
- Around line 397-405: The addMcrx implementation currently copies the controls
vector when forwarding it to addMcrz; change the call in
FunctionalityConstruction::addMcrx to forward the local controls by using
std::move(controls) when calling addMcrz so the temporary is moved instead of
copied (keep addMcrx signature and other calls unchanged and ensure <utility> is
included if not already).
- Around line 476-483: The function addMcz takes controls by value but forwards
it to addMcx without moving, causing an extra copy; update the call to addMcx to
forward ownership by calling addMcx(diag, std::move(controls), target, qubits)
(or change the parameter to an rvalue reference and move accordingly) while
keeping the rest of addMcz the same; reference symbols: addMcz, addMcx, addMcrx.
- Around line 433-474: The local vector second in
FunctionalityConstruction::addMcx is never modified after construction, so
change its declaration to a const std::vector<Qubit> second(controls.begin() +
half, controls.end()); to signal immutability and satisfy static analysis; keep
first and controls as-is (note controls is later mutated via
controls.pop_back()) and ensure no other uses assume second is non-const.

In `@test/zx/test_zx_functionality.cpp`:
- Around line 38-55: The free function checkEquivalence(...) should use
anonymous namespace for internal linkage instead of the static keyword and the
translation unit must include <vector> because std::vector is used in the
function signature; change the declaration of checkEquivalence to reside inside
an anonymous namespace and add `#include` <vector> at the top of the file,
ensuring the symbol names (checkEquivalence, qc::QuantumComputation,
std::vector, qc::Qubit) remain unchanged.

---

Duplicate comments:
In `@src/zx/FunctionalityConstruction.cpp`:
- Around line 418-431: addMcrz currently calls controls.back() and
controls.pop_back() without verifying controls size; add a defensive base-case
guard at the top of addMcrz that checks controls.size() (e.g., if
(controls.empty()) throw std::invalid_argument("addMcrz: controls must be
non-empty"); or use assert(controls.size() >= 1)) to prevent undefined behavior
when controls is empty, keeping the rest of the logic (the calls to addCrz and
addMcx) unchanged; reference the function name addMcrz and the controls vector
(controls.back()/controls.pop_back()) when applying the guard.

In `@test/zx/test_zx_functionality.cpp`:
- Around line 537-571: The four tests MCRx0–MCRx3 are tautological because they
compare QuantumComputation objects built with qc.mcrx(...) against an identical
qcPrime.mcrx(...); replace each test so it validates the ZX construction against
an independent reference decomposition instead of itself: implement a reference
circuit (e.g., build the multi-controlled Rx using a known decomposition of mcrx
into single- and two-qubit gates or a helper like decomposeMCRx) and then call
checkEquivalence(qc, referenceQc, {...}) using the same qubit set; update test
names (MCRx0..MCRx3) to construct qc with qc.mcrx(...) and qcPrime/reference
with the explicit decomposed gate sequence and assert equivalence to avoid the
self-inverse tautology.
- Around line 573-631: These tests for MCPhase/MCS/MCT are tautological because
they construct qc and qcPrime identically and then call checkEquivalence; update
each test (MCPhase, MCS, MCT and their 2 variants) so qcPrime is a true
expected/reference circuit rather than a copy — for example, build qc with
qc.mcp/qc.mcs/qc.mct and build qcPrime as the known decomposition or the result
of applying the ZX conversion+reconstruction you want to validate, or
alternatively apply the inverse operation to qcPrime (use qc.mcp(...).inverse()
style or the explicit decomposed gates) and then call checkEquivalence(qc,
qcPrime, ...); ensure you reference and modify the tests that call qc.mcp,
qc.mcs, qc.mct and checkEquivalence so the comparison verifies functional
equivalence to a non-identical expected circuit.

Comment on lines +397 to +405
void FunctionalityConstruction::addMcrx(ZXDiagram& diag,
const PiExpression& phase,
std::vector<Qubit> controls,
const Qubit target,
std::vector<Vertex>& qubits) {
addZSpider(diag, target, qubits, PiExpression(), EdgeType::Hadamard);
addMcrz(diag, phase, controls, target, qubits);
addZSpider(diag, target, qubits, PiExpression(), EdgeType::Hadamard);
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick | 🔵 Trivial

Move controls to avoid unnecessary copy.

Static analysis correctly flags that controls is passed by value and forwarded to addMcrz (which also takes by value). Use std::move to avoid the copy.

Proposed fix
 void FunctionalityConstruction::addMcrx(ZXDiagram& diag,
                                         const PiExpression& phase,
                                         std::vector<Qubit> controls,
                                         const Qubit target,
                                         std::vector<Vertex>& qubits) {
   addZSpider(diag, target, qubits, PiExpression(), EdgeType::Hadamard);
-  addMcrz(diag, phase, controls, target, qubits);
+  addMcrz(diag, phase, std::move(controls), target, qubits);
   addZSpider(diag, target, qubits, PiExpression(), EdgeType::Hadamard);
 }
🧰 Tools
🪛 GitHub Check: 🇨‌ Lint / 🚨 Lint

[warning] 403-403: src/zx/FunctionalityConstruction.cpp:403:24 [performance-unnecessary-value-param]
parameter 'controls' is passed by value and only copied once; consider moving it to avoid unnecessary copies

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/zx/FunctionalityConstruction.cpp` around lines 397 - 405, The addMcrx
implementation currently copies the controls vector when forwarding it to
addMcrz; change the call in FunctionalityConstruction::addMcrx to forward the
local controls by using std::move(controls) when calling addMcrz so the
temporary is moved instead of copied (keep addMcrx signature and other calls
unchanged and ensure <utility> is included if not already).

Comment on lines +433 to +474
void FunctionalityConstruction::addMcx(ZXDiagram& diag,
std::vector<Qubit> controls,
const Qubit target,
std::vector<Vertex>& qubits) {

switch (controls.size()) {
case 0:
addXSpider(diag, target, qubits, PiExpression(PiRational(1, 1)));
return;
case 1:
addCnot(diag, controls.front(), target, qubits);
return;
case 2:
addCcx(diag, controls.front(), controls.back(), target, qubits);
return;
default:
const auto half = static_cast<std::ptrdiff_t>((controls.size() + 1) / 2);
const std::vector<Qubit> first(controls.begin(), controls.begin() + half);
std::vector<Qubit> second(controls.begin() + half, controls.end());

addRx(diag, PiExpression(PiRational(1, 4)), target, qubits);
addZSpider(diag, target, qubits, PiExpression(), EdgeType::Hadamard);
addMcx(diag, first, target, qubits);
addZSpider(diag, target, qubits, PiExpression(), EdgeType::Hadamard);
addRx(diag, PiExpression(-PiRational(1, 4)), target, qubits);
addZSpider(diag, target, qubits, PiExpression(), EdgeType::Hadamard);
addMcx(diag, second, target, qubits);
addZSpider(diag, target, qubits, PiExpression(), EdgeType::Hadamard);
addRx(diag, PiExpression(PiRational(1, 4)), target, qubits);
addZSpider(diag, target, qubits, PiExpression(), EdgeType::Hadamard);
addMcx(diag, first, target, qubits);
addZSpider(diag, target, qubits, PiExpression(), EdgeType::Hadamard);
addRx(diag, PiExpression(-PiRational(1, 4)), target, qubits);
addZSpider(diag, target, qubits, PiExpression(), EdgeType::Hadamard);
addMcx(diag, second, target, qubits);
addZSpider(diag, target, qubits, PiExpression(), EdgeType::Hadamard);
const Qubit lastControl = controls.back();
controls.pop_back();
addMcphase(diag, PiExpression(PiRational(1, 2)), controls, lastControl,
qubits);
}
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick | 🔵 Trivial

addMcx divide-and-conquer decomposition: second can be const.

Static analysis flags that second (line 451) is never modified after construction.

Proposed fix
-    std::vector<Qubit> second(controls.begin() + half, controls.end());
+    const std::vector<Qubit> second(controls.begin() + half, controls.end());
🧰 Tools
🪛 GitHub Check: 🇨‌ Lint / 🚨 Lint

[warning] 451-451: src/zx/FunctionalityConstruction.cpp:451:5 [misc-const-correctness]
variable 'second' of type 'std::vector' (aka 'vector') can be declared 'const'

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/zx/FunctionalityConstruction.cpp` around lines 433 - 474, The local
vector second in FunctionalityConstruction::addMcx is never modified after
construction, so change its declaration to a const std::vector<Qubit>
second(controls.begin() + half, controls.end()); to signal immutability and
satisfy static analysis; keep first and controls as-is (note controls is later
mutated via controls.pop_back()) and ensure no other uses assume second is
non-const.

Comment on lines +476 to +483
void FunctionalityConstruction::addMcz(ZXDiagram& diag,
std::vector<Qubit> controls,
const Qubit target,
std::vector<Vertex>& qubits) {
addZSpider(diag, target, qubits, PiExpression(), EdgeType::Hadamard);
addMcx(diag, controls, target, qubits);
addZSpider(diag, target, qubits, PiExpression(), EdgeType::Hadamard);
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick | 🔵 Trivial

Move controls to avoid unnecessary copy.

Same as addMcrxcontrols is taken by value and only forwarded to addMcx.

Proposed fix
 void FunctionalityConstruction::addMcz(ZXDiagram& diag,
                                        std::vector<Qubit> controls,
                                        const Qubit target,
                                        std::vector<Vertex>& qubits) {
   addZSpider(diag, target, qubits, PiExpression(), EdgeType::Hadamard);
-  addMcx(diag, controls, target, qubits);
+  addMcx(diag, std::move(controls), target, qubits);
   addZSpider(diag, target, qubits, PiExpression(), EdgeType::Hadamard);
 }
🧰 Tools
🪛 GitHub Check: 🇨‌ Lint / 🚨 Lint

[warning] 481-481: src/zx/FunctionalityConstruction.cpp:481:16 [performance-unnecessary-value-param]
parameter 'controls' is passed by value and only copied once; consider moving it to avoid unnecessary copies

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/zx/FunctionalityConstruction.cpp` around lines 476 - 483, The function
addMcz takes controls by value but forwards it to addMcx without moving, causing
an extra copy; update the call to addMcx to forward ownership by calling
addMcx(diag, std::move(controls), target, qubits) (or change the parameter to an
rvalue reference and move accordingly) while keeping the rest of addMcz the
same; reference symbols: addMcz, addMcx, addMcrx.

Comment on lines +831 to +883
} else {
throw ZXException("Unsupported Multi-control operation (" +
std::to_string(op->getNcontrols()) + " ctrls)" +
qc::toString(op->getType()));
const auto target = static_cast<Qubit>(p.at(op->getTargets().front()));
const auto target2 = static_cast<Qubit>(p.at(op->getTargets()[1]));
std::vector<Qubit> controls;
controls.reserve(op->getNcontrols());
for (const auto& ctrl : op->getControls()) {
controls.emplace_back(static_cast<Qubit>(p.at(ctrl.qubit)));
}
switch (op->getType()) {
case qc::OpType::SWAP:
addMcswap(diag, controls, target, target2, qubits);
break;
case qc::OpType::RZZ: {
const auto& phase = parseParam(op.get(), 0);
if (phase.isConstant()) {
addMcrzz(diag, phase, controls, target, target2, qubits,
op->getParameter().at(0));
} else {
addMcrzz(diag, phase, controls, target, target2, qubits);
}
break;
}
case qc::OpType::RXX: {
const auto& phase = parseParam(op.get(), 0);
addZSpider(diag, target, qubits, PiExpression(), EdgeType::Hadamard);
addZSpider(diag, target2, qubits, PiExpression(), EdgeType::Hadamard);
if (phase.isConstant()) {
addMcrzz(diag, phase, controls, target, target2, qubits,
op->getParameter().at(0));
} else {
addMcrzz(diag, phase, controls, target, target2, qubits);
}
addZSpider(diag, target2, qubits, PiExpression(), EdgeType::Hadamard);
addZSpider(diag, target, qubits, PiExpression(), EdgeType::Hadamard);
break;
}
case qc::OpType::RZX: {
const auto& phase = parseParam(op.get(), 0);
addZSpider(diag, target2, qubits, PiExpression(), EdgeType::Hadamard);
if (phase.isConstant()) {
addMcrzz(diag, phase, controls, target, target2, qubits,
op->getParameter().at(0));
} else {
addMcrzz(diag, phase, controls, target, target2, qubits);
}
addZSpider(diag, target2, qubits, PiExpression(), EdgeType::Hadamard);
break;
}
default:
throw ZXException("Unsupported Multi-control operation (" +
std::to_string(op->getNcontrols()) + " ctrls)" +
qc::toString(op->getType()));
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick | 🔵 Trivial

Multi-target controlled gate handling: implicit getNtargets() >= 2 assumption.

The else branch unconditionally accesses op->getTargets()[1] at line 833. This is safe because all getNtargets() == 1 paths are handled in prior branches, and getNtargets() == 0 controlled operations (like controlled GPhase) are excluded by transformableToZX. However, a comment noting this invariant would improve readability.

Suggested clarification
   } else {
+    // At this point, op must have getNtargets() >= 2 (all 1-target cases handled above)
     const auto target = static_cast<Qubit>(p.at(op->getTargets().front()));
     const auto target2 = static_cast<Qubit>(p.at(op->getTargets()[1]));
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/zx/FunctionalityConstruction.cpp` around lines 831 - 883, The code
assumes multi-target ops have at least two targets but accesses
op->getTargets()[1] without asserting that invariant; add a short clarifying
comment and a defensive check (e.g., an assertion or ZX-specific check)
referencing op->getNtargets() before using op->getTargets()[1] to document and
enforce the invariant coming from transformableToZX, so callers can rely on it
and future changes won't silently break; locate this near the else branch
handling multi-target ops in FunctionalityConstruction (where op->getTargets(),
op->getNtargets(), and transformableToZX are used).

Comment on lines +38 to +55
static void checkEquivalence(const qc::QuantumComputation& qc1,
const qc::QuantumComputation& qc2,
const std::vector<qc::Qubit>& qubits) {
EXPECT_TRUE(FunctionalityConstruction::transformableToZX(&qc1));
EXPECT_TRUE(FunctionalityConstruction::transformableToZX(&qc2));
EXPECT_EQ(qc1.getNqubits(), qc2.getNqubits());

auto d1 = FunctionalityConstruction::buildFunctionality(&qc1);
auto d2 = FunctionalityConstruction::buildFunctionality(&qc2);
d1.concat(d2.invert());
fullReduce(d1);
EXPECT_TRUE(d1.isIdentity());
EXPECT_TRUE(d1.globalPhaseIsZero());
for (const auto q : qubits) {
ASSERT_LT(q, qc1.getNqubits());
EXPECT_TRUE(d1.connected(d1.getInput(q), d1.getOutput(q)));
}
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick | 🔵 Trivial

Prefer anonymous namespace over static for internal linkage; missing <vector> include.

Static analysis flags two issues:

  1. static free function should be in an anonymous namespace per C++ best practices.
  2. std::vector is used in the signature but <vector> is not directly included.
Proposed fix
+#include <vector>
+
 namespace zx {
+namespace {
-static void checkEquivalence(const qc::QuantumComputation& qc1,
-                             const qc::QuantumComputation& qc2,
-                             const std::vector<qc::Qubit>& qubits) {
+void checkEquivalence(const qc::QuantumComputation& qc1,
+                      const qc::QuantumComputation& qc2,
+                      const std::vector<qc::Qubit>& qubits) {
   ...
 }
+} // namespace
🧰 Tools
🪛 GitHub Check: 🇨‌ Lint / 🚨 Lint

[warning] 40-40: test/zx/test_zx_functionality.cpp:40:41 [misc-include-cleaner]
no header providing "std::vector" is directly included


[warning] 38-38: test/zx/test_zx_functionality.cpp:38:13 [misc-use-anonymous-namespace]
function 'checkEquivalence' declared 'static', move to anonymous namespace instead

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@test/zx/test_zx_functionality.cpp` around lines 38 - 55, The free function
checkEquivalence(...) should use anonymous namespace for internal linkage
instead of the static keyword and the translation unit must include <vector>
because std::vector is used in the function signature; change the declaration of
checkEquivalence to reside inside an anonymous namespace and add `#include`
<vector> at the top of the file, ensuring the symbol names (checkEquivalence,
qc::QuantumComputation, std::vector, qc::Qubit) remain unchanged.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement Improvement of existing feature ZX Anything related to the ZX package

Projects

None yet

Development

Successfully merging this pull request may close these issues.

✨ Add multi-controlled gate support to ZX package

4 participants