Skip to content

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 78.29457% with 28 lines in your changes missing coverage. Please review.

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

📢 Thoughts on this report? Let us know!

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Dec 8, 2025

📝 Walkthrough

Summary by CodeRabbit

  • New Features
    • Added support for controlled rotation Z (CRZ) and multi-controlled rotation Z (MCRZ) quantum gates
    • Added support for doubly-controlled Z (CCZ) and multi-controlled Z (MCZ) quantum gates
    • Enhanced multi-controlled X (MCX) gate decomposition with improved handling

✏️ Tip: You can customize this high-level summary in your review settings.

Walkthrough

Added multi-control ZX-diagram construction routines (CCZ, CRZ, MCRZ, MCX, MCZ), integrated them into operation parsing and transformability checks, and expanded tests to validate multi-control constructions and reductions. (≤50 words)

Changes

Cohort / File(s) Summary
Header Declaration
include/mqt-core/zx/FunctionalityConstruction.hpp
Added static declarations: addCcz, addCrz, addMcrz, addMcx, addMcz.
Implementation
src/zx/FunctionalityConstruction.cpp
Implemented multi-control helpers (addCcz, addCrz, addMcrz, addMcx, addMcz); extended parseOp to route RZ/CZ/MCX/MCRZ paths; updated transformableToZX overloads to accept RZ in multi-control contexts; added ancilla-aware recursive decompositions and error checks.
Tests
test/zx/test_zx_functionality.cpp
Replaced single unsupported test with a suite covering CRZ, CCZ, MultiCZ, MultiControlX (variants), MultiCRZ; tests assert identity, zero global phase, and preserved connectivity after reduction.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

  • Inspect control ordering and indexing in MCX/MCRZ/CCZ implementations.
  • Verify phase handling and PiExpression usage in addCrz / addMcrz.
  • Review parseOp and transformableToZX branches for all control-count cases.
  • Check ancilla selection, allocation logic, and error/edge-case handling.
  • Run the expanded test suite to confirm expected reductions.

Poem

🐇 I hop through wires and phases bright,
I stitch CCZ and CRZ by night,
My paws arrange each control in line,
MCX and MCZ now shine,
Diagrams hum — a rabbit's delight!

Pre-merge checks and finishing touches

❌ 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%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed Title succinctly captures the primary change: adding multi-control functionality to the ZX package, which is clearly evident from the codebase additions.
Description check ✅ Passed Description includes summary of changes, references the fixed issue (#1357), and mostly completes the checklist. However, changelog entries and CI passing confirmation are missing.
Linked Issues check ✅ Passed PR fulfills the main objective of #1357 by implementing multi-controlled gates (MCX, MCZ, MCRZ) and controlled rotations (CRZ). All code-level requirements from the linked issue have been addressed.
Out of Scope Changes check ✅ Passed All changes are focused on the stated objective of adding multi-control functionality. Header declarations, implementations, and comprehensive test coverage are all directly aligned with extending ZX package capabilities.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 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: 8

📜 Review details

Configuration used: CodeRabbit UI

Review profile: ASSERTIVE

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e2b7f7b and 9915b6a.

📒 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-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
  • 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-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-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:

  • 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
🧬 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 (792-809)
  • buildFunctionality (792-793)
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)
🔇 Additional comments (8)
test/zx/test_zx_functionality.cpp (2)

318-340: LGTM! Strong validation using ancilla decomposition.

This test validates MCX against an ancilla-based decomposition, which is a more robust verification than self-inverse. Consider adding connectivity checks for all 5 qubits for completeness.


342-362: LGTM!

Good edge case coverage testing MCX with zero controls, verifying it reduces to a simple X gate.

src/zx/FunctionalityConstruction.cpp (6)

310-330: LGTM!

The CCZ implementation correctly uses a T-gate decomposition. The structure appropriately omits the initial Hadamard from the CCX decomposition while maintaining the necessary phase structure, with the final Hadamard edges properly placed.


332-341: LGTM!

The CRZ implementation uses the correct decomposition formula with the intentional CNOT direction reversal properly documented.


343-365: LGTM!

The MCRZ implementation correctly uses recursive decomposition with proper base cases. The controls vector is appropriately passed by value to allow modification without affecting the caller.


367-425: LGTM!

The MCX implementation handles base cases correctly and uses two decomposition strategies depending on ancilla availability. The ancilla selection now properly iterates over qubit indices rather than vertex values (addressing the previous critical issue).


427-452: LGTM!

The MCZ implementation correctly uses recursive decomposition with proper base cases for 0, 1, and 2 controls.


877-900: LGTM!

The transformableToZX function is correctly updated to recognize RZ gates in all control configurations (1, 2, and 3+ controls), matching the corresponding parseOp implementations.

Comment on lines +728 to +745
std::vector<Qubit> controls;
for (const auto& ctrl : op->getControls()) {
controls.push_back(static_cast<Qubit>(p.at(ctrl.qubit)));
}
switch (op->getType()) {
case qc::OpType::X:
addCcx(diag, ctrl0, ctrl1, target, qubits);
break;

case qc::OpType::Z:
addCcz(diag, ctrl0, ctrl1, target, qubits);
break;
case qc::OpType::RZ:
addMcrz(diag, parseParam(op.get(), 0), controls, target, qubits);
break;
default:
throw ZXException("Unsupported Multi-control operation: " +
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

Unused controls vector in 2-control branch.

The controls vector is constructed at lines 728-731 but is only used for the RZ case at line 740. For X and Z cases, ctrl0 and ctrl1 are used directly. This is not a bug but introduces slight redundancy.

Consider constructing controls only when needed, or using it consistently for all cases:

+    // Build controls vector for multi-control dispatch
     std::vector<Qubit> controls;
     for (const auto& ctrl : op->getControls()) {
       controls.push_back(static_cast<Qubit>(p.at(ctrl.qubit)));
     }
     switch (op->getType()) {
     case qc::OpType::X:
-      addCcx(diag, ctrl0, ctrl1, target, qubits);
+      addCcx(diag, controls.front(), controls.back(), target, qubits);
       break;
     case qc::OpType::Z:
-      addCcz(diag, ctrl0, ctrl1, target, qubits);
+      addCcz(diag, controls.front(), controls.back(), target, qubits);
       break;
🤖 Prompt for AI Agents
In src/zx/FunctionalityConstruction.cpp around lines 728-745 the vector controls
is populated unconditionally but only used in the RZ branch; avoid the
redundancy by moving the construction into the RZ case (or alternately use the
controls vector for all branches). Update the code so that controls is
declared/filled only inside the qc::OpType::RZ case before calling addMcrz(diag,
parseParam(op.get(), 0), controls, target, qubits), and remove the unused
controls construction from before the switch; ensure no other branches depend on
controls.

Comment on lines +222 to +245
TEST_F(ZXFunctionalityTest, CRZ) {
using namespace qc::literals;
qc = qc::QuantumComputation(2);
qc.crz(PI / 2, 0, 1);

auto qcPrime = qc::QuantumComputation(2);

qcPrime.cx(0, 1);
qcPrime.rz(-PI / 4, 1);
qcPrime.cx(0, 1);
qcPrime.rz(PI / 4, 1);

auto d = FunctionalityConstruction::buildFunctionality(&qc);

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

d.concat(dPrime.invert());

fullReduce(d);

EXPECT_TRUE(d.isIdentity());
EXPECT_TRUE(d.globalPhaseIsZero());
EXPECT_TRUE(d.connected(d.getInput(0), d.getOutput(0)));
}
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

Add connectivity assertion for qubit 1.

The test validates CRZ correctness but only checks connectivity for qubit 0. For completeness, add a connectivity check for qubit 1 to ensure both wires are properly connected after reduction.

   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)));
 }
🤖 Prompt for AI Agents
In test/zx/test_zx_functionality.cpp around lines 222 to 245, the test verifies
CRZ but only asserts connectivity for qubit 0; add an assertion that qubit 1 is
also connected after reduction. Insert a check like
EXPECT_TRUE(d.connected(d.getInput(1), d.getOutput(1))); immediately after the
existing connectivity assertion for qubit 0 so both wires are validated.

Comment on lines +247 to +268
TEST_F(ZXFunctionalityTest, MultiCZ) {
using namespace qc::literals;
qc = qc::QuantumComputation(3);
qc.mcz({1, 2}, 0);

auto qcPrime = qc::QuantumComputation(3);
qcPrime.h(0);
qcPrime.mcx({1, 2}, 0);
qcPrime.h(0);

auto d = FunctionalityConstruction::buildFunctionality(&qc);

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

d.concat(dPrime.invert());

fullReduce(d);

EXPECT_TRUE(d.isIdentity());
EXPECT_TRUE(d.globalPhaseIsZero());
EXPECT_TRUE(d.connected(d.getInput(0), d.getOutput(0)));
}
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

Add connectivity assertions for all qubits.

For a 3-qubit test, only qubit 0's connectivity is verified. Add checks for qubits 1 and 2 for comprehensive validation.

   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)));
 }
🤖 Prompt for AI Agents
In test/zx/test_zx_functionality.cpp around lines 247 to 268, the test currently
only asserts connectivity for qubit 0 after reduction; add analogous
connectivity assertions for qubits 1 and 2 (i.e., call
EXPECT_TRUE(d.connected(d.getInput(1), d.getOutput(1))) and
EXPECT_TRUE(d.connected(d.getInput(2), d.getOutput(2)))) so all three qubits are
validated.

Comment on lines +269 to +293
TEST_F(ZXFunctionalityTest, CCZ) {
using namespace qc::literals;
const std::string testfile = "OPENQASM 2.0;"
"include \"qelib1.inc\";"
"qreg q[3];"
"ccz q[0],q[1],q[2];\n";

qc = qasm3::Importer::imports(testfile);
auto qcPrime = qc::QuantumComputation(3);
qcPrime.h(0);
qcPrime.mcx({1, 2}, 0);
qcPrime.h(0);

auto d = FunctionalityConstruction::buildFunctionality(&qc);

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

d.concat(dPrime.invert());

fullReduce(d);

EXPECT_TRUE(d.isIdentity());
EXPECT_TRUE(d.globalPhaseIsZero());
EXPECT_TRUE(d.connected(d.getInput(0), d.getOutput(0)));
}
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

Add connectivity assertions for all qubits.

Similar to other 3-qubit tests, add connectivity checks for qubits 1 and 2.

   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)));
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
TEST_F(ZXFunctionalityTest, CCZ) {
using namespace qc::literals;
const std::string testfile = "OPENQASM 2.0;"
"include \"qelib1.inc\";"
"qreg q[3];"
"ccz q[0],q[1],q[2];\n";
qc = qasm3::Importer::imports(testfile);
auto qcPrime = qc::QuantumComputation(3);
qcPrime.h(0);
qcPrime.mcx({1, 2}, 0);
qcPrime.h(0);
auto d = FunctionalityConstruction::buildFunctionality(&qc);
auto dPrime = FunctionalityConstruction::buildFunctionality(&qcPrime);
d.concat(dPrime.invert());
fullReduce(d);
EXPECT_TRUE(d.isIdentity());
EXPECT_TRUE(d.globalPhaseIsZero());
EXPECT_TRUE(d.connected(d.getInput(0), d.getOutput(0)));
}
TEST_F(ZXFunctionalityTest, CCZ) {
using namespace qc::literals;
const std::string testfile = "OPENQASM 2.0;"
"include \"qelib1.inc\";"
"qreg q[3];"
"ccz q[0],q[1],q[2];\n";
qc = qasm3::Importer::imports(testfile);
auto qcPrime = qc::QuantumComputation(3);
qcPrime.h(0);
qcPrime.mcx({1, 2}, 0);
qcPrime.h(0);
auto d = FunctionalityConstruction::buildFunctionality(&qc);
auto dPrime = FunctionalityConstruction::buildFunctionality(&qcPrime);
d.concat(dPrime.invert());
fullReduce(d);
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)));
}
🤖 Prompt for AI Agents
In test/zx/test_zx_functionality.cpp around lines 269 to 293, the test only
asserts connectivity for qubit 0; add connectivity assertions for qubits 1 and 2
as well. After the existing EXPECT_TRUE(d.connected(d.getInput(0),
d.getOutput(0))); line, add equivalent assertions for inputs/outputs 1 and 2
(i.e., EXPECT_TRUE(d.connected(d.getInput(1), d.getOutput(1))); and
EXPECT_TRUE(d.connected(d.getInput(2), d.getOutput(2)));) so all three qubits
are checked for connectivity.

Comment on lines +295 to +316
TEST_F(ZXFunctionalityTest, MultiControlX) {
using namespace qc::literals;
qc = qc::QuantumComputation(4);
qc.mcx({1, 2, 3}, 0);
EXPECT_FALSE(FunctionalityConstruction::transformableToZX(&qc));
EXPECT_THROW(const ZXDiagram diag =
FunctionalityConstruction::buildFunctionality(&qc),
ZXException);

auto qcPrime = qc::QuantumComputation(4);
qcPrime.h(0);
qcPrime.mcz({1, 2, 3}, 0);
qcPrime.h(0);

auto d = FunctionalityConstruction::buildFunctionality(&qc);

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

d.concat(dPrime.invert());

fullReduce(d);

EXPECT_TRUE(d.isIdentity());
EXPECT_TRUE(d.globalPhaseIsZero());
EXPECT_TRUE(d.connected(d.getInput(0), d.getOutput(0)));
}
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

Add connectivity assertions for all qubits.

For a 4-qubit test, verify connectivity for all qubits 0-3.

   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)));
+  EXPECT_TRUE(d.connected(d.getInput(3), d.getOutput(3)));
 }
🤖 Prompt for AI Agents
In test/zx/test_zx_functionality.cpp around lines 295-316, the test currently
asserts connectivity only for qubit 0; add assertions that verify connectivity
for all 4 qubits (0–3). Modify the test to check d.connected(d.getInput(i),
d.getOutput(i)) for i in 0..3 (either by adding three additional EXPECT_TRUE
calls for 1,2,3 or a small loop generating those EXPECT_TRUE assertions) so
every input/output qubit pair is asserted connected.

Comment on lines +364 to +384
TEST_F(ZXFunctionalityTest, MultiControlX1) {
using namespace qc::literals;
qc = qc::QuantumComputation(2);
qc.mcx({1}, 0);

auto qcPrime = qc::QuantumComputation(2);

qcPrime.cx(1, 0);

auto d = FunctionalityConstruction::buildFunctionality(&qc);

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

d.concat(dPrime.invert());

fullReduce(d);

EXPECT_TRUE(d.isIdentity());
EXPECT_TRUE(d.globalPhaseIsZero());
EXPECT_TRUE(d.connected(d.getInput(0), d.getOutput(0)));
}
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

Add connectivity assertion for qubit 1.

   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)));
 }
🤖 Prompt for AI Agents
In test/zx/test_zx_functionality.cpp around lines 364 to 384, the test currently
asserts connectivity for qubit 0 only; add an assertion to verify qubit 1 is
also connected after construction, reduction, and concatenation. Insert a line
similar to EXPECT_TRUE(d.connected(d.getInput(1), d.getOutput(1))); immediately
after the existing connectivity check for qubit 0 so the test validates
connectivity for both qubits.

Comment on lines +386 to +409
TEST_F(ZXFunctionalityTest, MultiControlZ) {
using namespace qc::literals;
qc = qc::QuantumComputation(4);
qc.mcz({1, 2, 3}, 0);

auto qcPrime = qc::QuantumComputation(4);
qcPrime.h(0);
qcPrime.mcx({1, 2, 3}, 0);
qcPrime.h(0);

auto d = FunctionalityConstruction::buildFunctionality(&qc);

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

d.concat(dPrime.invert());

fullReduce(d);

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)));
}
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

Add connectivity assertion for qubit 3.

The test correctly checks connectivity for qubits 0-2 but misses qubit 3.

   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)));
+  EXPECT_TRUE(d.connected(d.getInput(3), d.getOutput(3)));
 }
🤖 Prompt for AI Agents
In test/zx/test_zx_functionality.cpp around lines 386 to 409, the test checks
connectivity for qubits 0–2 but omits qubit 3; add an assertion verifying
d.connected(d.getInput(3), d.getOutput(3)) (similar style to the existing
checks) near the other EXPECT_TRUE connectivity assertions so all four qubits
are validated.

Comment on lines +453 to +466
TEST_F(ZXFunctionalityTest, MultiControlRZ) {
using namespace qc::literals;
qc = qc::QuantumComputation(3);
qc.mcrz(PI / 4, {1, 2}, 0);
qc.mcrz(-PI / 4, {1, 2}, 0);

auto d = FunctionalityConstruction::buildFunctionality(&qc);

fullReduce(d);

EXPECT_TRUE(d.isIdentity());
EXPECT_TRUE(d.globalPhaseIsZero());
EXPECT_TRUE(d.connected(d.getInput(0), d.getOutput(0)));
}
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

Add connectivity assertions for qubits 1 and 2.

The MultiControlRZ test uses 3 qubits but only checks qubit 0's connectivity.

   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)));
 }
🤖 Prompt for AI Agents
In test/zx/test_zx_functionality.cpp around lines 453 to 466, the MultiControlRZ
test builds a 3-qubit functionality but only asserts connectivity for qubit 0;
add assertions to verify qubit 1 and qubit 2 are connected similarly to qubit 0
(call d.connected(d.getInput(1), d.getOutput(1)) and d.connected(d.getInput(2),
d.getOutput(2))), keeping them as EXPECT_TRUE checks after the existing
connectivity assertion so the test validates all three qubits.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

✨ Add multi-controlled gate support to ZX package

2 participants