diff --git a/.clang-tidy b/.clang-tidy index 3d9e3b1bfd..1f73231b0a 100644 --- a/.clang-tidy +++ b/.clang-tidy @@ -2,6 +2,8 @@ FormatStyle: file Checks: | bugprone-*, + -bugprone-command-processor, + -bugprone-random-generator-seed, -bugprone-easily-swappable-parameters, -bugprone-unchecked-optional-access, clang-analyzer-*, diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 5c86e799e1..3f26999acf 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -160,7 +160,7 @@ jobs: uses: munich-quantum-toolkit/workflows/.github/workflows/reusable-cpp-linter.yml@afe75175d32177a7291bbb7bd11b3276f60fc810 # v1.17.15 with: cmake-args: -DBUILD_MQT_CORE_BENCHMARKS=ON -DBUILD_MQT_CORE_BINDINGS=ON - clang-version: 21 + clang-version: 22 build-project: true files-changed-only: true setup-python: true diff --git a/CHANGELOG.md b/CHANGELOG.md index 0de707dd37..33db26d50f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -20,6 +20,7 @@ This project adheres to [Semantic Versioning], with the exception that minor rel ### Changed +- ⬆️ Update `clang-tidy` to version 22 ([#1564]) ([**@denialhaag**], [**@burgholzer**]) - 👷 Build on `macos-26`/`macos-26-intel` by default and `macos-15`/`macos-15-intel` for extensive tests ([#1571]) ([**@denialhaag**]) - ⬆️ Require LLVM 22.1 for C++ library builds ([#1549]) ([**@burgholzer**], [**@denialhaag**]) - 📦 Build MLIR by default for C++ library builds ([#1356]) ([**@burgholzer**], [**@denialhaag**]) @@ -336,6 +337,7 @@ _📚 Refer to the [GitHub Release Notes](https://github.com/munich-quantum-tool [#1570]: https://github.com/munich-quantum-toolkit/core/pull/1570 [#1568]: https://github.com/munich-quantum-toolkit/core/pull/1568 [#1565]: https://github.com/munich-quantum-toolkit/core/pull/1565 +[#1564]: https://github.com/munich-quantum-toolkit/core/pull/1564 [#1554]: https://github.com/munich-quantum-toolkit/core/pull/1554 [#1550]: https://github.com/munich-quantum-toolkit/core/pull/1550 [#1549]: https://github.com/munich-quantum-toolkit/core/pull/1549 diff --git a/eval/eval_dd_package.cpp b/eval/eval_dd_package.cpp index 9074e024de..234f8a7495 100644 --- a/eval/eval_dd_package.cpp +++ b/eval/eval_dd_package.cpp @@ -40,6 +40,9 @@ #include namespace dd { +namespace { + +constexpr std::size_t SEED = 42U; struct Experiment { std::unique_ptr dd; @@ -73,7 +76,6 @@ struct FunctionalityConstructionExperiment final : Experiment { } }; -namespace { std::unique_ptr benchmarkSimulate(const qc::QuantumComputation& qc) { auto exp = std::make_unique(); @@ -191,9 +193,6 @@ benchmarkFunctionalityConstructionGrover( exp->stats = getStatistics(*exp->dd); return exp; } -} // namespace - -static constexpr std::size_t SEED = 42U; class BenchmarkDDPackage { protected: @@ -407,6 +406,7 @@ class BenchmarkDDPackage { } }; +} // namespace } // namespace dd int main(const int argc, char** argv) { diff --git a/include/mqt-core/dd/DDDefinitions.hpp b/include/mqt-core/dd/DDDefinitions.hpp index c1a7e76ca2..6b3752c4d0 100644 --- a/include/mqt-core/dd/DDDefinitions.hpp +++ b/include/mqt-core/dd/DDDefinitions.hpp @@ -38,9 +38,8 @@ using Qubit = std::uint16_t; * @note Adjusting the precision might lead to unexpected results. */ using fp = double; -static_assert( - std::is_floating_point_v, - "fp should be a floating point type (float, *double*, long double)"); +static_assert(std::is_floating_point_v, + "fp should be a floating point type (float or double)"); // logic radix static constexpr std::uint8_t RADIX = 2; diff --git a/include/mqt-core/ir/operations/Expression.hpp b/include/mqt-core/ir/operations/Expression.hpp index 963f1dbf14..e9a3f4c178 100644 --- a/include/mqt-core/ir/operations/Expression.hpp +++ b/include/mqt-core/ir/operations/Expression.hpp @@ -842,7 +842,7 @@ template struct std::hash> { qc::hashCombine(seed, std::hash{}(expr.getConst())); return seed; } -}; // namespace std +}; namespace qc { using Symbolic = sym::Expression; diff --git a/include/mqt-core/ir/operations/IfElseOperation.hpp b/include/mqt-core/ir/operations/IfElseOperation.hpp index 1626c7add7..e8dabfefaa 100644 --- a/include/mqt-core/ir/operations/IfElseOperation.hpp +++ b/include/mqt-core/ir/operations/IfElseOperation.hpp @@ -164,4 +164,4 @@ class IfElseOperation final : public Operation { template <> struct std::hash { std::size_t operator()(qc::IfElseOperation const& op) const noexcept; -}; // namespace std +}; diff --git a/mlir/.clang-tidy b/mlir/.clang-tidy index 5e7c7353be..a83fa04cb3 100644 --- a/mlir/.clang-tidy +++ b/mlir/.clang-tidy @@ -4,9 +4,12 @@ Checks: | llvm-prefer-isa-or-dyn-cast-in-conditionals, llvm-prefer-register-over-unsigned, llvm-prefer-static-over-anonymous-namespace, - -misc-use-anonymous-namespace, llvm-twine-local, + -bugprone-throwing-static-initialization, + -cppcoreguidelines-avoid-non-const-global-variables, -cppcoreguidelines-pro-bounds-avoid-unchecked-container-access, + -misc-use-anonymous-namespace, + -modernize-type-traits, -*-const-correctness, CheckOptions: diff --git a/mlir/lib/Conversion/JeffToQCO/JeffToQCO.cpp b/mlir/lib/Conversion/JeffToQCO/JeffToQCO.cpp index cd3f1a29d0..5599753f96 100644 --- a/mlir/lib/Conversion/JeffToQCO/JeffToQCO.cpp +++ b/mlir/lib/Conversion/JeffToQCO/JeffToQCO.cpp @@ -39,6 +39,7 @@ #include namespace mlir { + using namespace qco; #define GEN_PASS_DEF_JEFFTOQCO @@ -378,6 +379,8 @@ static LogicalResult cleanUp(Operation* op) { return success(); } +namespace { + /** * @brief Converts jeff.qubit_alloc to qco.alloc * @@ -590,7 +593,7 @@ struct ConvertJeffOneTargetZeroParameterToQCO final using OpConversionPattern::OpConversionPattern; LogicalResult - matchAndRewrite(JeffOpType op, typename JeffOpType::Adaptor adaptor, + matchAndRewrite(JeffOpType op, JeffOpType::Adaptor adaptor, ConversionPatternRewriter& rewriter) const override { if (op.getPower() != 1) { return rewriter.notifyMatchFailure( @@ -626,7 +629,7 @@ struct ConvertJeffOneTargetOneParameterToQCO final using OpConversionPattern::OpConversionPattern; LogicalResult - matchAndRewrite(JeffOpType op, typename JeffOpType::Adaptor adaptor, + matchAndRewrite(JeffOpType op, JeffOpType::Adaptor adaptor, ConversionPatternRewriter& rewriter) const override { if (op.getPower() != 1) { return rewriter.notifyMatchFailure( @@ -963,4 +966,6 @@ struct JeffToQCO final : impl::JeffToQCOBase { } }; +} // namespace + } // namespace mlir diff --git a/mlir/lib/Conversion/QCOToJeff/QCOToJeff.cpp b/mlir/lib/Conversion/QCOToJeff/QCOToJeff.cpp index 8796e834df..124c095060 100644 --- a/mlir/lib/Conversion/QCOToJeff/QCOToJeff.cpp +++ b/mlir/lib/Conversion/QCOToJeff/QCOToJeff.cpp @@ -44,6 +44,7 @@ #include namespace mlir { + using namespace qco; #define GEN_PASS_DEF_QCOTOJEFF @@ -241,6 +242,8 @@ static LogicalResult cleanUp(Operation* op, LoweringState& state) { return success(); } +namespace { + /** * @brief Converts qco.alloc to jeff.qubit_alloc * @@ -400,7 +403,7 @@ struct ConvertQCOOneTargetZeroParameterToJeff final using StatefulOpConversionPattern::StatefulOpConversionPattern; LogicalResult - matchAndRewrite(QCOOpType op, typename QCOOpType::Adaptor adaptor, + matchAndRewrite(QCOOpType op, QCOOpType::Adaptor adaptor, ConversionPatternRewriter& rewriter) const override { auto& state = this->getState(); @@ -516,7 +519,7 @@ struct ConvertQCOOneTargetOneParameterToJeff final using StatefulOpConversionPattern::StatefulOpConversionPattern; LogicalResult - matchAndRewrite(QCOOpType op, typename QCOOpType::Adaptor adaptor, + matchAndRewrite(QCOOpType op, QCOOpType::Adaptor adaptor, ConversionPatternRewriter& rewriter) const override { auto& state = this->getState(); @@ -647,7 +650,7 @@ struct ConvertQCOOneTargetThreeParameterToJeff final using StatefulOpConversionPattern::StatefulOpConversionPattern; LogicalResult - matchAndRewrite(QCOOpType op, typename QCOOpType::Adaptor adaptor, + matchAndRewrite(QCOOpType op, QCOOpType::Adaptor adaptor, ConversionPatternRewriter& rewriter) const override { auto& state = this->getState(); @@ -698,7 +701,7 @@ struct ConvertQCOTwoTargetZeroParameterToJeff final using StatefulOpConversionPattern::StatefulOpConversionPattern; LogicalResult - matchAndRewrite(QCOOpType op, typename QCOOpType::Adaptor adaptor, + matchAndRewrite(QCOOpType op, QCOOpType::Adaptor adaptor, ConversionPatternRewriter& rewriter) const override { auto& state = this->getState(); @@ -1400,4 +1403,6 @@ struct QCOToJeff final : impl::QCOToJeffBase { } }; +} // namespace + } // namespace mlir diff --git a/mlir/lib/Conversion/QCOToQC/QCOToQC.cpp b/mlir/lib/Conversion/QCOToQC/QCOToQC.cpp index 8d8a604ab4..381486b02b 100644 --- a/mlir/lib/Conversion/QCOToQC/QCOToQC.cpp +++ b/mlir/lib/Conversion/QCOToQC/QCOToQC.cpp @@ -29,12 +29,15 @@ #include namespace mlir { + using namespace qco; using namespace qc; #define GEN_PASS_DEF_QCOTOQC #include "mlir/Conversion/QCOToQC/QCOToQC.h.inc" +namespace { + /** * @brief Type converter for QCO-to-QC conversion * @@ -257,7 +260,7 @@ struct ConvertQCOZeroTargetOneParameterToQC final using OpConversionPattern::OpConversionPattern; LogicalResult - matchAndRewrite(QCOOpType op, typename QCOOpType::Adaptor /*adaptor*/, + matchAndRewrite(QCOOpType op, QCOOpType::Adaptor /*adaptor*/, ConversionPatternRewriter& rewriter) const override { QCOpType::create(rewriter, op.getLoc(), op.getParameter(0)); rewriter.eraseOp(op); @@ -286,7 +289,7 @@ struct ConvertQCOOneTargetZeroParameterToQC final using OpConversionPattern::OpConversionPattern; LogicalResult - matchAndRewrite(QCOOpType op, typename QCOOpType::Adaptor adaptor, + matchAndRewrite(QCOOpType op, QCOOpType::Adaptor adaptor, ConversionPatternRewriter& rewriter) const override { // OpAdaptor provides the already type-converted input qubit auto qcQubit = adaptor.getQubitIn(); @@ -322,7 +325,7 @@ struct ConvertQCOOneTargetOneParameterToQC final using OpConversionPattern::OpConversionPattern; LogicalResult - matchAndRewrite(QCOOpType op, typename QCOOpType::Adaptor adaptor, + matchAndRewrite(QCOOpType op, QCOOpType::Adaptor adaptor, ConversionPatternRewriter& rewriter) const override { // OpAdaptor provides the already type-converted input qubit auto qcQubit = adaptor.getQubitIn(); @@ -358,7 +361,7 @@ struct ConvertQCOOneTargetTwoParameterToQC final using OpConversionPattern::OpConversionPattern; LogicalResult - matchAndRewrite(QCOOpType op, typename QCOOpType::Adaptor adaptor, + matchAndRewrite(QCOOpType op, QCOOpType::Adaptor adaptor, ConversionPatternRewriter& rewriter) const override { // OpAdaptor provides the already type-converted input qubit auto qcQubit = adaptor.getQubitIn(); @@ -395,7 +398,7 @@ struct ConvertQCOOneTargetThreeParameterToQC final using OpConversionPattern::OpConversionPattern; LogicalResult - matchAndRewrite(QCOOpType op, typename QCOOpType::Adaptor adaptor, + matchAndRewrite(QCOOpType op, QCOOpType::Adaptor adaptor, ConversionPatternRewriter& rewriter) const override { // OpAdaptor provides the already type-converted input qubit auto qcQubit = adaptor.getQubitIn(); @@ -433,7 +436,7 @@ struct ConvertQCOTwoTargetZeroParameterToQC final using OpConversionPattern::OpConversionPattern; LogicalResult - matchAndRewrite(QCOOpType op, typename QCOOpType::Adaptor adaptor, + matchAndRewrite(QCOOpType op, QCOOpType::Adaptor adaptor, ConversionPatternRewriter& rewriter) const override { // OpAdaptor provides the already type-converted input qubits auto qcQubit0 = adaptor.getQubit0In(); @@ -471,7 +474,7 @@ struct ConvertQCOTwoTargetOneParameterToQC final using OpConversionPattern::OpConversionPattern; LogicalResult - matchAndRewrite(QCOOpType op, typename QCOOpType::Adaptor adaptor, + matchAndRewrite(QCOOpType op, QCOOpType::Adaptor adaptor, ConversionPatternRewriter& rewriter) const override { // OpAdaptor provides the already type-converted input qubits auto qcQubit0 = adaptor.getQubit0In(); @@ -510,7 +513,7 @@ struct ConvertQCOTwoTargetTwoParameterToQC final using OpConversionPattern::OpConversionPattern; LogicalResult - matchAndRewrite(QCOOpType op, typename QCOOpType::Adaptor adaptor, + matchAndRewrite(QCOOpType op, QCOOpType::Adaptor adaptor, ConversionPatternRewriter& rewriter) const override { // OpAdaptor provides the already type-converted input qubits auto qcQubit0 = adaptor.getQubit0In(); @@ -817,4 +820,6 @@ struct QCOToQC final : impl::QCOToQCBase { } }; +} // namespace + } // namespace mlir diff --git a/mlir/lib/Conversion/QCToQCO/QCToQCO.cpp b/mlir/lib/Conversion/QCToQCO/QCToQCO.cpp index ab2c5bad3c..474f80aacf 100644 --- a/mlir/lib/Conversion/QCToQCO/QCToQCO.cpp +++ b/mlir/lib/Conversion/QCToQCO/QCToQCO.cpp @@ -34,6 +34,7 @@ #include namespace mlir { + using namespace qco; using namespace qc; @@ -110,8 +111,6 @@ class StatefulOpConversionPattern : public OpConversionPattern { LoweringState* state_; }; -} // namespace - /** * @brief Type converter for QC-to-QCO conversion * @@ -377,7 +376,7 @@ struct ConvertQCZeroTargetOneParameterToQCO final using StatefulOpConversionPattern::StatefulOpConversionPattern; LogicalResult - matchAndRewrite(QCOpType op, typename QCOpType::Adaptor /*adaptor*/, + matchAndRewrite(QCOpType op, QCOpType::Adaptor /*adaptor*/, ConversionPatternRewriter& rewriter) const override { auto& state = this->getState(); const auto inNestedRegion = state.inNestedRegion; @@ -418,7 +417,7 @@ struct ConvertQCOneTargetZeroParameterToQCO final using StatefulOpConversionPattern::StatefulOpConversionPattern; LogicalResult - matchAndRewrite(QCOpType op, typename QCOpType::Adaptor /*adaptor*/, + matchAndRewrite(QCOpType op, QCOpType::Adaptor /*adaptor*/, ConversionPatternRewriter& rewriter) const override { auto& state = this->getState(); auto& qubitMap = state.qubitMap; @@ -475,7 +474,7 @@ struct ConvertQCOneTargetOneParameterToQCO final using StatefulOpConversionPattern::StatefulOpConversionPattern; LogicalResult - matchAndRewrite(QCOpType op, typename QCOpType::Adaptor /*adaptor*/, + matchAndRewrite(QCOpType op, QCOpType::Adaptor /*adaptor*/, ConversionPatternRewriter& rewriter) const override { auto& state = this->getState(); auto& qubitMap = state.qubitMap; @@ -533,7 +532,7 @@ struct ConvertQCOneTargetTwoParameterToQCO final using StatefulOpConversionPattern::StatefulOpConversionPattern; LogicalResult - matchAndRewrite(QCOpType op, typename QCOpType::Adaptor /*adaptor*/, + matchAndRewrite(QCOpType op, QCOpType::Adaptor /*adaptor*/, ConversionPatternRewriter& rewriter) const override { auto& state = this->getState(); auto& qubitMap = state.qubitMap; @@ -591,7 +590,7 @@ struct ConvertQCOneTargetThreeParameterToQCO final using StatefulOpConversionPattern::StatefulOpConversionPattern; LogicalResult - matchAndRewrite(QCOpType op, typename QCOpType::Adaptor /*adaptor*/, + matchAndRewrite(QCOpType op, QCOpType::Adaptor /*adaptor*/, ConversionPatternRewriter& rewriter) const override { auto& state = this->getState(); auto& qubitMap = state.qubitMap; @@ -651,7 +650,7 @@ struct ConvertQCTwoTargetZeroParameterToQCO final using StatefulOpConversionPattern::StatefulOpConversionPattern; LogicalResult - matchAndRewrite(QCOpType op, typename QCOpType::Adaptor /*adaptor*/, + matchAndRewrite(QCOpType op, QCOpType::Adaptor /*adaptor*/, ConversionPatternRewriter& rewriter) const override { auto& state = this->getState(); auto& qubitMap = state.qubitMap; @@ -717,7 +716,7 @@ struct ConvertQCTwoTargetOneParameterToQCO final using StatefulOpConversionPattern::StatefulOpConversionPattern; LogicalResult - matchAndRewrite(QCOpType op, typename QCOpType::Adaptor /*adaptor*/, + matchAndRewrite(QCOpType op, QCOpType::Adaptor /*adaptor*/, ConversionPatternRewriter& rewriter) const override { auto& state = this->getState(); auto& qubitMap = state.qubitMap; @@ -784,7 +783,7 @@ struct ConvertQCTwoTargetTwoParameterToQCO final using StatefulOpConversionPattern::StatefulOpConversionPattern; LogicalResult - matchAndRewrite(QCOpType op, typename QCOpType::Adaptor /*adaptor*/, + matchAndRewrite(QCOpType op, QCOpType::Adaptor /*adaptor*/, ConversionPatternRewriter& rewriter) const override { auto& state = this->getState(); auto& qubitMap = state.qubitMap; @@ -1178,4 +1177,6 @@ struct QCToQCO final : impl::QCToQCOBase { } }; +} // namespace + } // namespace mlir diff --git a/mlir/lib/Conversion/QCToQIR/QCToQIR.cpp b/mlir/lib/Conversion/QCToQIR/QCToQIR.cpp index 6363fad5a4..cd1d2721b7 100644 --- a/mlir/lib/Conversion/QCToQIR/QCToQIR.cpp +++ b/mlir/lib/Conversion/QCToQIR/QCToQIR.cpp @@ -185,6 +185,8 @@ convertUnitaryToCallOp(QCOpType& op, QCOpAdaptorType& adaptor, return success(); } +namespace { + /** * @brief Type converter for lowering QC dialect types to LLVM types * @@ -202,8 +204,6 @@ struct QCToQIRTypeConverter final : LLVMTypeConverter { } }; -namespace { - /** * @brief Converts qc.alloc operation to static QIR qubit allocations * @@ -873,8 +873,6 @@ struct ConvertQCYieldQIR final : StatefulOpConversionPattern { } }; -} // namespace - /** * @brief Pass for converting QC dialect operations to QIR * @@ -1123,6 +1121,7 @@ struct QCToQIR final : impl::QCToQIRBase { } } +protected: /** * @brief Executes the QC to QIR conversion pass * @@ -1270,4 +1269,6 @@ struct QCToQIR final : impl::QCToQIRBase { } }; +} // namespace + } // namespace mlir diff --git a/mlir/lib/Dialect/QC/IR/Modifiers/CtrlOp.cpp b/mlir/lib/Dialect/QC/IR/Modifiers/CtrlOp.cpp index 921b1421be..064107de7b 100644 --- a/mlir/lib/Dialect/QC/IR/Modifiers/CtrlOp.cpp +++ b/mlir/lib/Dialect/QC/IR/Modifiers/CtrlOp.cpp @@ -154,7 +154,7 @@ LogicalResult CtrlOp::verify() { "last operation in body region must be a yield operation"); } auto iter = ++block.rbegin(); - if (!llvm::isa(*(iter))) { + if (!llvm::isa(*iter)) { return emitOpError( "second to last operation in body region must be a unitary operation"); } diff --git a/mlir/lib/Dialect/QC/IR/Modifiers/InvOp.cpp b/mlir/lib/Dialect/QC/IR/Modifiers/InvOp.cpp index 02b0f67db2..10f3c1d9df 100644 --- a/mlir/lib/Dialect/QC/IR/Modifiers/InvOp.cpp +++ b/mlir/lib/Dialect/QC/IR/Modifiers/InvOp.cpp @@ -285,7 +285,7 @@ LogicalResult InvOp::verify() { "last operation in body region must be a yield operation"); } auto iter = ++block.rbegin(); - if (!llvm::isa(*(iter))) { + if (!llvm::isa(*iter)) { return emitOpError( "second to last operation in body region must be a unitary operation"); } diff --git a/mlir/lib/Dialect/QCO/IR/Modifiers/CtrlOp.cpp b/mlir/lib/Dialect/QCO/IR/Modifiers/CtrlOp.cpp index 7c7e5b7bca..96c811eed8 100644 --- a/mlir/lib/Dialect/QCO/IR/Modifiers/CtrlOp.cpp +++ b/mlir/lib/Dialect/QCO/IR/Modifiers/CtrlOp.cpp @@ -280,7 +280,7 @@ LogicalResult CtrlOp::verify() { << numTargets << " values, but found " << numYieldOperands; } auto iter = ++block.rbegin(); - if (!llvm::isa(*(iter))) { + if (!llvm::isa(*iter)) { return emitOpError( "second to last operation in body region must be a unitary operation"); } diff --git a/mlir/lib/Dialect/QCO/IR/Modifiers/InvOp.cpp b/mlir/lib/Dialect/QCO/IR/Modifiers/InvOp.cpp index a13da2d497..18cc331c5b 100644 --- a/mlir/lib/Dialect/QCO/IR/Modifiers/InvOp.cpp +++ b/mlir/lib/Dialect/QCO/IR/Modifiers/InvOp.cpp @@ -364,7 +364,7 @@ LogicalResult InvOp::verify() { << numTargets << " values, but found " << numYieldOperands; } auto iter = ++block.rbegin(); - if (!llvm::isa(*(iter))) { + if (!llvm::isa(*iter)) { return emitOpError( "second to last operation in body region must be a unitary operation"); } diff --git a/mlir/lib/Dialect/QCO/Transforms/Mapping/Mapping.cpp b/mlir/lib/Dialect/QCO/Transforms/Mapping/Mapping.cpp index c8971abbfc..ebd8fa2cf8 100644 --- a/mlir/lib/Dialect/QCO/Transforms/Mapping/Mapping.cpp +++ b/mlir/lib/Dialect/QCO/Transforms/Mapping/Mapping.cpp @@ -55,6 +55,8 @@ namespace mlir::qco { #define GEN_PASS_DEF_MAPPINGPASS #include "mlir/Dialect/QCO/Transforms/Passes.h.inc" +namespace { + struct MappingPass : impl::MappingPassBase { private: using QubitValue = TypedValue; @@ -271,7 +273,7 @@ struct MappingPass : impl::MappingPassBase { */ [[nodiscard]] bool isGoal(const Layer& front, const Architecture& arch) const { - return all_of(front, [&](const IndexGate gate) { + return all_of(front, [&](const IndexGate& gate) { return arch.areAdjacent(layout.getHardwareIndex(gate.first), layout.getHardwareIndex(gate.second)); }); @@ -322,6 +324,7 @@ struct MappingPass : impl::MappingPassBase { public: using MappingPassBase::MappingPassBase; +protected: void runOnOperation() override { std::mt19937_64 rng{this->seed}; IRRewriter rewriter(&getContext()); @@ -775,4 +778,7 @@ struct MappingPass : impl::MappingPassBase { } } }; + +} // namespace + } // namespace mlir::qco diff --git a/mlir/lib/Dialect/QIR/Builder/QIRProgramBuilder.cpp b/mlir/lib/Dialect/QIR/Builder/QIRProgramBuilder.cpp index 5f72670ee6..5ca6cfd050 100644 --- a/mlir/lib/Dialect/QIR/Builder/QIRProgramBuilder.cpp +++ b/mlir/lib/Dialect/QIR/Builder/QIRProgramBuilder.cpp @@ -495,6 +495,7 @@ DEFINE_ONE_TARGET_THREE_PARAMETER(U, u, theta, phi, lambda) return *this; \ } +// NOLINTNEXTLINE(bugprone-exception-escape) DEFINE_TWO_TARGET_ZERO_PARAMETER(SWAP, swap) DEFINE_TWO_TARGET_ZERO_PARAMETER(ISWAP, iswap) DEFINE_TWO_TARGET_ZERO_PARAMETER(DCX, dcx) diff --git a/mlir/tools/mqt-cc/mqt-cc.cpp b/mlir/tools/mqt-cc/mqt-cc.cpp index 0bfc747341..76848b6594 100644 --- a/mlir/tools/mqt-cc/mqt-cc.cpp +++ b/mlir/tools/mqt-cc/mqt-cc.cpp @@ -40,40 +40,36 @@ using namespace llvm; using namespace mlir; -namespace { - // Command-line options -const cl::opt INPUT_FILENAME(cl::Positional, +static cl::opt inputFilename(cl::Positional, cl::desc(""), cl::init("-")); -const cl::opt OUTPUT_FILENAME("o", cl::desc("Output filename"), +static cl::opt outputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"), cl::init("-")); -const cl::opt CONVERT_TO_QIR("emit-qir", - cl::desc("Convert to QIR at the end"), - cl::init(false)); +static cl::opt convertToQIR("emit-qir", + cl::desc("Convert to QIR at the end"), + cl::init(false)); -const cl::opt RECORD_INTERMEDIATES( +static cl::opt recordIntermediates( "record-intermediates", cl::desc("Record intermediate IR after each compiler stage"), cl::init(false)); -const cl::opt ENABLE_TIMING("mlir-timing", +static cl::opt enableTiming("mlir-timing", cl::desc("Enable pass timing statistics"), cl::init(false)); -const cl::opt ENABLE_STATISTICS("mlir-statistics", +static cl::opt enableStatistics("mlir-statistics", cl::desc("Enable pass statistics"), cl::init(false)); -const cl::opt - PRINT_IR_AFTER_ALL_STAGES("mlir-print-ir-after-all-stages", - cl::desc("Print IR after each compiler stage"), - cl::init(false)); - -} // namespace +static cl::opt + printIRAfterAllStages("mlir-print-ir-after-all-stages", + cl::desc("Print IR after each compiler stage"), + cl::init(false)); /** * @brief Load and parse a .qasm file @@ -153,10 +149,10 @@ int main(int argc, char** argv) { // Load the input .mlir file OwningOpRef module; - if (INPUT_FILENAME.getValue().ends_with(".qasm")) { - module = loadQASMFile(INPUT_FILENAME, &context); + if (inputFilename.getValue().ends_with(".qasm")) { + module = loadQASMFile(inputFilename, &context); } else { - module = loadMLIRFile(INPUT_FILENAME, &context); + module = loadMLIRFile(inputFilename, &context); } if (!module) { return 1; @@ -164,23 +160,23 @@ int main(int argc, char** argv) { // Configure the compiler pipeline QuantumCompilerConfig config; - config.convertToQIR = CONVERT_TO_QIR; - config.recordIntermediates = RECORD_INTERMEDIATES; - config.enableTiming = ENABLE_TIMING; - config.enableStatistics = ENABLE_STATISTICS; - config.printIRAfterAllStages = PRINT_IR_AFTER_ALL_STAGES; + config.convertToQIR = convertToQIR; + config.recordIntermediates = recordIntermediates; + config.enableTiming = enableTiming; + config.enableStatistics = enableStatistics; + config.printIRAfterAllStages = printIRAfterAllStages; // Run the compilation pipeline CompilationRecord record; if (const QuantumCompilerPipeline pipeline(config); pipeline - .runPipeline(module.get(), RECORD_INTERMEDIATES ? &record : nullptr) + .runPipeline(module.get(), recordIntermediates ? &record : nullptr) .failed()) { errs() << "Compilation pipeline failed\n"; return 1; } - if (RECORD_INTERMEDIATES) { + if (recordIntermediates) { outs() << "=== Compilation Record ===\n"; outs() << "After QC Import:\n" << record.afterQCImport << "\n"; outs() << "After Initial QC Canonicalization:\n" @@ -202,8 +198,8 @@ int main(int argc, char** argv) { } // Write the output - if (writeOutput(module.get(), OUTPUT_FILENAME).failed()) { - errs() << "Failed to write output file: " << OUTPUT_FILENAME << "\n"; + if (writeOutput(module.get(), outputFilename).failed()) { + errs() << "Failed to write output file: " << outputFilename << "\n"; return 1; } diff --git a/mlir/unittests/Compiler/test_compiler_pipeline.cpp b/mlir/unittests/Compiler/test_compiler_pipeline.cpp index 1b72a08521..a81f6a7c01 100644 --- a/mlir/unittests/Compiler/test_compiler_pipeline.cpp +++ b/mlir/unittests/Compiler/test_compiler_pipeline.cpp @@ -46,6 +46,8 @@ using QCProgramBuilderFn = NamedBuilder; using QIRProgramBuilderFn = NamedBuilder; using QuantumComputationBuilderFn = NamedBuilder<::qc::QuantumComputation>; +namespace { + struct CompilerPipelineTestCase { std::string name; QuantumComputationBuilderFn quantumComputationBuilder; @@ -56,21 +58,25 @@ struct CompilerPipelineTestCase { bool convertToQIR = true; friend std::ostream& operator<<(std::ostream& os, - const CompilerPipelineTestCase& info) { - os << "CompilerPipeline{" << info.name << ", original="; - if (info.startFromQuantumComputation) { - os << displayName(info.quantumComputationBuilder.name); - } else { - os << displayName(info.qcProgramBuilder.name); - } - os << ", qcReference=" << displayName(info.qcReferenceBuilder.name); - if (info.convertToQIR) { - os << ", qirReference=" << displayName(info.qirReferenceBuilder.name); - } - return os << "}"; - } + const CompilerPipelineTestCase& info); }; +// NOLINTNEXTLINE(llvm-prefer-static-over-anonymous-namespace) +std::ostream& operator<<(std::ostream& os, + const CompilerPipelineTestCase& info) { + os << "CompilerPipeline{" << info.name << ", original="; + if (info.startFromQuantumComputation) { + os << displayName(info.quantumComputationBuilder.name); + } else { + os << displayName(info.qcProgramBuilder.name); + } + os << ", qcReference=" << displayName(info.qcReferenceBuilder.name); + if (info.convertToQIR) { + os << ", qirReference=" << displayName(info.qirReferenceBuilder.name); + } + return os << "}"; +} + class CompilerPipelineTest : public testing::TestWithParam { protected: @@ -128,6 +134,8 @@ class CompilerPipelineTest } }; +} // namespace + TEST_P(CompilerPipelineTest, EndToEndPipeline) { const auto& testCase = GetParam(); const auto name = " (" + testCase.name + ")"; diff --git a/mlir/unittests/Conversion/JeffRoundTrip/test_jeff_round_trip.cpp b/mlir/unittests/Conversion/JeffRoundTrip/test_jeff_round_trip.cpp index f37972128e..48b0b22926 100644 --- a/mlir/unittests/Conversion/JeffRoundTrip/test_jeff_round_trip.cpp +++ b/mlir/unittests/Conversion/JeffRoundTrip/test_jeff_round_trip.cpp @@ -34,6 +34,8 @@ using namespace mlir; +namespace { + struct JeffRoundTripTestCase { std::string name; mqt::test::NamedBuilder programBuilder; @@ -43,6 +45,14 @@ struct JeffRoundTripTestCase { const JeffRoundTripTestCase& info); }; +// NOLINTNEXTLINE(llvm-prefer-static-over-anonymous-namespace) +std::ostream& operator<<(std::ostream& os, const JeffRoundTripTestCase& info) { + return os << "JeffRoundTrip{" << info.name + << ", original=" << mqt::test::displayName(info.programBuilder.name) + << ", reference=" + << mqt::test::displayName(info.referenceBuilder.name) << "}"; +} + class JeffRoundTripTest : public testing::TestWithParam { protected: std::unique_ptr context; @@ -58,12 +68,7 @@ class JeffRoundTripTest : public testing::TestWithParam { } }; -std::ostream& operator<<(std::ostream& os, const JeffRoundTripTestCase& info) { - return os << "JeffRoundTrip{" << info.name - << ", original=" << mqt::test::displayName(info.programBuilder.name) - << ", reference=" - << mqt::test::displayName(info.referenceBuilder.name) << "}"; -} +} // namespace static LogicalResult convertQCOToJeff(ModuleOp module) { PassManager pm(module.getContext()); diff --git a/mlir/unittests/Conversion/QCOToQC/test_qco_to_qc.cpp b/mlir/unittests/Conversion/QCOToQC/test_qco_to_qc.cpp index 579b9f05c3..bb81b94ecc 100644 --- a/mlir/unittests/Conversion/QCOToQC/test_qco_to_qc.cpp +++ b/mlir/unittests/Conversion/QCOToQC/test_qco_to_qc.cpp @@ -34,6 +34,8 @@ using namespace mlir; +namespace { + struct QCOToQCTestCase { std::string name; mqt::test::NamedBuilder programBuilder; @@ -43,6 +45,14 @@ struct QCOToQCTestCase { const QCOToQCTestCase& info); }; +// NOLINTNEXTLINE(llvm-prefer-static-over-anonymous-namespace) +std::ostream& operator<<(std::ostream& os, const QCOToQCTestCase& info) { + return os << "QCOToQC{" << info.name + << ", original=" << mqt::test::displayName(info.programBuilder.name) + << ", reference=" + << mqt::test::displayName(info.referenceBuilder.name) << "}"; +} + class QCOToQCTest : public testing::TestWithParam { protected: std::unique_ptr context; @@ -58,12 +68,7 @@ class QCOToQCTest : public testing::TestWithParam { } }; -std::ostream& operator<<(std::ostream& os, const QCOToQCTestCase& info) { - return os << "QCOToQC{" << info.name - << ", original=" << mqt::test::displayName(info.programBuilder.name) - << ", reference=" - << mqt::test::displayName(info.referenceBuilder.name) << "}"; -} +} // namespace static LogicalResult runQCOToQCConversion(ModuleOp module) { PassManager pm(module.getContext()); diff --git a/mlir/unittests/Conversion/QCToQCO/test_qc_to_qco.cpp b/mlir/unittests/Conversion/QCToQCO/test_qc_to_qco.cpp index 3718329082..98d6c9e012 100644 --- a/mlir/unittests/Conversion/QCToQCO/test_qc_to_qco.cpp +++ b/mlir/unittests/Conversion/QCToQCO/test_qc_to_qco.cpp @@ -34,6 +34,8 @@ using namespace mlir; +namespace { + struct QCToQCOTestCase { std::string name; mqt::test::NamedBuilder programBuilder; @@ -43,6 +45,14 @@ struct QCToQCOTestCase { const QCToQCOTestCase& info); }; +// NOLINTNEXTLINE(llvm-prefer-static-over-anonymous-namespace) +std::ostream& operator<<(std::ostream& os, const QCToQCOTestCase& info) { + return os << "QCToQCO{" << info.name + << ", original=" << mqt::test::displayName(info.programBuilder.name) + << ", reference=" + << mqt::test::displayName(info.referenceBuilder.name) << "}"; +} + class QCToQCOTest : public testing::TestWithParam { protected: std::unique_ptr context; @@ -58,12 +68,7 @@ class QCToQCOTest : public testing::TestWithParam { } }; -std::ostream& operator<<(std::ostream& os, const QCToQCOTestCase& info) { - return os << "QCToQCO{" << info.name - << ", original=" << mqt::test::displayName(info.programBuilder.name) - << ", reference=" - << mqt::test::displayName(info.referenceBuilder.name) << "}"; -} +} // namespace static LogicalResult runQCToQCOConversion(ModuleOp module) { PassManager pm(module.getContext()); diff --git a/mlir/unittests/Conversion/QCToQIR/test_qc_to_qir.cpp b/mlir/unittests/Conversion/QCToQIR/test_qc_to_qir.cpp index f8825c0dc1..82ab251e41 100644 --- a/mlir/unittests/Conversion/QCToQIR/test_qc_to_qir.cpp +++ b/mlir/unittests/Conversion/QCToQIR/test_qc_to_qir.cpp @@ -35,6 +35,8 @@ using namespace mlir; +namespace { + struct QCToQIRTestCase { std::string name; mqt::test::NamedBuilder programBuilder; @@ -44,6 +46,14 @@ struct QCToQIRTestCase { const QCToQIRTestCase& info); }; +// NOLINTNEXTLINE(llvm-prefer-static-over-anonymous-namespace) +std::ostream& operator<<(std::ostream& os, const QCToQIRTestCase& info) { + return os << "QCToQIR{" << info.name + << ", original=" << mqt::test::displayName(info.programBuilder.name) + << ", reference=" + << mqt::test::displayName(info.referenceBuilder.name) << "}"; +} + class QCToQIRTest : public testing::TestWithParam { protected: std::unique_ptr context; @@ -58,12 +68,7 @@ class QCToQIRTest : public testing::TestWithParam { } }; -std::ostream& operator<<(std::ostream& os, const QCToQIRTestCase& info) { - return os << "QCToQIR{" << info.name - << ", original=" << mqt::test::displayName(info.programBuilder.name) - << ", reference=" - << mqt::test::displayName(info.referenceBuilder.name) << "}"; -} +} // namespace static LogicalResult runQCToQIRConversion(ModuleOp module) { PassManager pm(module.getContext()); diff --git a/mlir/unittests/Dialect/QC/IR/test_qc_ir.cpp b/mlir/unittests/Dialect/QC/IR/test_qc_ir.cpp index fe8c0abd7a..221b750f7e 100644 --- a/mlir/unittests/Dialect/QC/IR/test_qc_ir.cpp +++ b/mlir/unittests/Dialect/QC/IR/test_qc_ir.cpp @@ -30,6 +30,8 @@ using namespace mlir; using namespace mlir::qc; +namespace { + struct QCTestCase { std::string name; mqt::test::NamedBuilder programBuilder; @@ -38,6 +40,14 @@ struct QCTestCase { friend std::ostream& operator<<(std::ostream& os, const QCTestCase& info); }; +// NOLINTNEXTLINE(llvm-prefer-static-over-anonymous-namespace) +std::ostream& operator<<(std::ostream& os, const QCTestCase& info) { + return os << "QC{" << info.name + << ", original=" << mqt::test::displayName(info.programBuilder.name) + << ", reference=" + << mqt::test::displayName(info.referenceBuilder.name) << "}"; +} + class QCTest : public testing::TestWithParam { protected: std::unique_ptr context; @@ -45,6 +55,8 @@ class QCTest : public testing::TestWithParam { void SetUp() override; }; +} // namespace + void QCTest::SetUp() { // Register all necessary dialects DialectRegistry registry; @@ -54,13 +66,6 @@ void QCTest::SetUp() { context->loadAllAvailableDialects(); } -std::ostream& operator<<(std::ostream& os, const QCTestCase& info) { - return os << "QC{" << info.name - << ", original=" << mqt::test::displayName(info.programBuilder.name) - << ", reference=" - << mqt::test::displayName(info.referenceBuilder.name) << "}"; -} - TEST_P(QCTest, ProgramEquivalence) { const auto& [_, programBuilder, referenceBuilder] = GetParam(); const auto name = " (" + GetParam().name + ")"; diff --git a/mlir/unittests/Dialect/QC/Translation/test_quantum_computation_translation.cpp b/mlir/unittests/Dialect/QC/Translation/test_quantum_computation_translation.cpp index ed57896cfb..e8850c3706 100644 --- a/mlir/unittests/Dialect/QC/Translation/test_quantum_computation_translation.cpp +++ b/mlir/unittests/Dialect/QC/Translation/test_quantum_computation_translation.cpp @@ -29,6 +29,8 @@ #include #include +namespace { + struct QuantumComputationTranslationTestCase { std::string name; mqt::test::NamedBuilder<::qc::QuantumComputation> programBuilder; @@ -36,14 +38,18 @@ struct QuantumComputationTranslationTestCase { friend std::ostream& operator<<(std::ostream& os, - const QuantumComputationTranslationTestCase& test) { - return os << "QuantumComputationTranslation{" << test.name << ", original=" - << mqt::test::displayName(test.programBuilder.name) - << ", reference=" - << mqt::test::displayName(test.referenceBuilder.name) << "}"; - } + const QuantumComputationTranslationTestCase& test); }; +// NOLINTNEXTLINE(llvm-prefer-static-over-anonymous-namespace) +std::ostream& operator<<(std::ostream& os, + const QuantumComputationTranslationTestCase& test) { + return os << "QuantumComputationTranslation{" << test.name + << ", original=" << mqt::test::displayName(test.programBuilder.name) + << ", reference=" + << mqt::test::displayName(test.referenceBuilder.name) << "}"; +} + class QuantumComputationTranslationTest : public testing::TestWithParam { protected: @@ -59,6 +65,8 @@ class QuantumComputationTranslationTest } }; +} // namespace + TEST_P(QuantumComputationTranslationTest, ProgramEquivalence) { const auto& [_, programBuilder, referenceBuilder] = GetParam(); const auto name = " (" + GetParam().name + ")"; diff --git a/mlir/unittests/Dialect/QCO/IR/test_qco_ir.cpp b/mlir/unittests/Dialect/QCO/IR/test_qco_ir.cpp index 3220aa753c..e7b4853f34 100644 --- a/mlir/unittests/Dialect/QCO/IR/test_qco_ir.cpp +++ b/mlir/unittests/Dialect/QCO/IR/test_qco_ir.cpp @@ -32,6 +32,8 @@ using namespace mlir; using namespace mlir::qco; +namespace { + struct QCOTestCase { std::string name; mqt::test::NamedBuilder programBuilder; @@ -40,6 +42,14 @@ struct QCOTestCase { friend std::ostream& operator<<(std::ostream& os, const QCOTestCase& info); }; +// NOLINTNEXTLINE(llvm-prefer-static-over-anonymous-namespace) +std::ostream& operator<<(std::ostream& os, const QCOTestCase& info) { + return os << "QCO{" << info.name + << ", original=" << mqt::test::displayName(info.programBuilder.name) + << ", reference=" + << mqt::test::displayName(info.referenceBuilder.name) << "}"; +} + class QCOTest : public testing::TestWithParam { protected: std::unique_ptr context; @@ -54,12 +64,7 @@ class QCOTest : public testing::TestWithParam { } }; -std::ostream& operator<<(std::ostream& os, const QCOTestCase& info) { - return os << "QCO{" << info.name - << ", original=" << mqt::test::displayName(info.programBuilder.name) - << ", reference=" - << mqt::test::displayName(info.referenceBuilder.name) << "}"; -} +} // namespace TEST_P(QCOTest, ProgramEquivalence) { const auto& [_, programBuilder, referenceBuilder] = GetParam(); diff --git a/mlir/unittests/Dialect/QCO/IR/test_qco_ir_matrix.cpp b/mlir/unittests/Dialect/QCO/IR/test_qco_ir_matrix.cpp index d10f76c15c..24103da18c 100644 --- a/mlir/unittests/Dialect/QCO/IR/test_qco_ir_matrix.cpp +++ b/mlir/unittests/Dialect/QCO/IR/test_qco_ir_matrix.cpp @@ -27,22 +27,21 @@ #include #include -#include #include #include using namespace mlir; using namespace qco; -struct QCOTestCase { +namespace { + +struct QCOMatrixTestCase { std::string name; mqt::test::NamedBuilder programBuilder; mqt::test::NamedBuilder referenceBuilder; - - friend std::ostream& operator<<(std::ostream& os, const QCOTestCase& info); }; -class QCOTest : public testing::TestWithParam { +class QCOMatrixTest : public testing::TestWithParam { protected: std::unique_ptr context; @@ -55,9 +54,11 @@ class QCOTest : public testing::TestWithParam { } }; +} // namespace + /// \name QCO/Modifiers/CtrlOp.cpp /// @{ -TEST_F(QCOTest, CXOpMatrix) { +TEST_F(QCOMatrixTest, CXOpMatrix) { auto moduleOp = QCOProgramBuilder::build(context.get(), singleControlledX); ASSERT_TRUE(moduleOp); @@ -87,7 +88,7 @@ TEST_F(QCOTest, CXOpMatrix) { /// \name QCO/Modifiers/InvOp.cpp /// @{ -TEST_F(QCOTest, InverseIswapOpMatrix) { +TEST_F(QCOMatrixTest, InverseIswapOpMatrix) { auto moduleOp = QCOProgramBuilder::build(context.get(), inverseIswap); ASSERT_TRUE(moduleOp); @@ -117,7 +118,7 @@ TEST_F(QCOTest, InverseIswapOpMatrix) { /// \name QCO/Operations/StandardGates/DcxOp.cpp /// @{ -TEST_F(QCOTest, DCXOpMatrix) { +TEST_F(QCOMatrixTest, DCXOpMatrix) { // Get the (static) matrix from the operation const auto matrix = DCXOp::getUnitaryMatrix(); @@ -139,7 +140,7 @@ TEST_F(QCOTest, DCXOpMatrix) { /// \name QCO/Operations/StandardGates/EcrOp.cpp /// @{ -TEST_F(QCOTest, ECROpMatrix) { +TEST_F(QCOMatrixTest, ECROpMatrix) { // Get the (static) matrix from the operation const auto matrix = ECROp::getUnitaryMatrix(); @@ -161,7 +162,7 @@ TEST_F(QCOTest, ECROpMatrix) { /// \name QCO/Operations/StandardGates/GphaseOp.cpp /// @{ -TEST_F(QCOTest, GPhaseOpMatrix) { +TEST_F(QCOMatrixTest, GPhaseOpMatrix) { auto moduleOp = QCOProgramBuilder::build(context.get(), globalPhase); ASSERT_TRUE(moduleOp); @@ -184,7 +185,7 @@ TEST_F(QCOTest, GPhaseOpMatrix) { /// \name QCO/Operations/StandardGates/HOp.cpp /// @{ -TEST_F(QCOTest, HOpMatrix) { +TEST_F(QCOMatrixTest, HOpMatrix) { // Get the (static) matrix from the operation const auto matrix = HOp::getUnitaryMatrix(); @@ -202,7 +203,7 @@ TEST_F(QCOTest, HOpMatrix) { /// \name QCO/Operations/StandardGates/IdOp.cpp /// @{ -TEST_F(QCOTest, IdOpMatrix) { +TEST_F(QCOMatrixTest, IdOpMatrix) { // Get the (static) matrix from the operation const auto matrix = IdOp::getUnitaryMatrix(); @@ -220,7 +221,7 @@ TEST_F(QCOTest, IdOpMatrix) { /// \name QCO/Operations/StandardGates/IswapOp.cpp /// @{ -TEST_F(QCOTest, iSWAPOpMatrix) { +TEST_F(QCOMatrixTest, iSWAPOpMatrix) { // Get the (static) matrix from the operation const auto matrix = iSWAPOp::getUnitaryMatrix(); @@ -242,7 +243,7 @@ TEST_F(QCOTest, iSWAPOpMatrix) { /// \name QCO/Operations/StandardGates/POp.cpp /// @{ -TEST_F(QCOTest, POpMatrix) { +TEST_F(QCOMatrixTest, POpMatrix) { auto moduleOp = QCOProgramBuilder::build(context.get(), p); ASSERT_TRUE(moduleOp); @@ -265,7 +266,7 @@ TEST_F(QCOTest, POpMatrix) { /// \name QCO/Operations/StandardGates/ROp.cpp /// @{ -TEST_F(QCOTest, ROpMatrix) { +TEST_F(QCOMatrixTest, ROpMatrix) { auto moduleOp = QCOProgramBuilder::build(context.get(), r); ASSERT_TRUE(moduleOp); @@ -288,7 +289,7 @@ TEST_F(QCOTest, ROpMatrix) { /// \name QCO/Operations/StandardGates/RxOp.cpp /// @{ -TEST_F(QCOTest, RXOpMatrix) { +TEST_F(QCOMatrixTest, RXOpMatrix) { auto moduleOp = QCOProgramBuilder::build(context.get(), rx); ASSERT_TRUE(moduleOp); @@ -312,7 +313,7 @@ TEST_F(QCOTest, RXOpMatrix) { /// \name QCO/Operations/StandardGates/RxxOp.cpp /// @{ -TEST_F(QCOTest, RXXOpMatrix) { +TEST_F(QCOMatrixTest, RXXOpMatrix) { auto moduleOp = QCOProgramBuilder::build(context.get(), rxx); ASSERT_TRUE(moduleOp); @@ -339,7 +340,7 @@ TEST_F(QCOTest, RXXOpMatrix) { /// \name QCO/Operations/StandardGates/RyOp.cpp /// @{ -TEST_F(QCOTest, RYOpMatrix) { +TEST_F(QCOMatrixTest, RYOpMatrix) { auto moduleOp = QCOProgramBuilder::build(context.get(), ry); ASSERT_TRUE(moduleOp); @@ -363,7 +364,7 @@ TEST_F(QCOTest, RYOpMatrix) { /// \name QCO/Operations/StandardGates/RyyOp.cpp /// @{ -TEST_F(QCOTest, RYYOpMatrix) { +TEST_F(QCOMatrixTest, RYYOpMatrix) { auto moduleOp = QCOProgramBuilder::build(context.get(), ryy); ASSERT_TRUE(moduleOp); @@ -390,7 +391,7 @@ TEST_F(QCOTest, RYYOpMatrix) { /// \name QCO/Operations/StandardGates/RzOp.cpp /// @{ -TEST_F(QCOTest, RZOpMatrix) { +TEST_F(QCOMatrixTest, RZOpMatrix) { auto moduleOp = QCOProgramBuilder::build(context.get(), rz); ASSERT_TRUE(moduleOp); @@ -414,7 +415,7 @@ TEST_F(QCOTest, RZOpMatrix) { /// \name QCO/Operations/StandardGates/RzxOp.cpp /// @{ -TEST_F(QCOTest, RZXOpMatrix) { +TEST_F(QCOMatrixTest, RZXOpMatrix) { auto moduleOp = QCOProgramBuilder::build(context.get(), rzx); ASSERT_TRUE(moduleOp); @@ -441,7 +442,7 @@ TEST_F(QCOTest, RZXOpMatrix) { /// \name QCO/Operations/StandardGates/RzzOp.cpp /// @{ -TEST_F(QCOTest, RZZOpMatrix) { +TEST_F(QCOMatrixTest, RZZOpMatrix) { auto moduleOp = QCOProgramBuilder::build(context.get(), rzz); ASSERT_TRUE(moduleOp); @@ -468,7 +469,7 @@ TEST_F(QCOTest, RZZOpMatrix) { /// \name QCO/Operations/StandardGates/SOp.cpp /// @{ -TEST_F(QCOTest, SOpMatrix) { +TEST_F(QCOMatrixTest, SOpMatrix) { // Get the (static) matrix from the operation const auto matrix = SOp::getUnitaryMatrix(); @@ -486,7 +487,7 @@ TEST_F(QCOTest, SOpMatrix) { /// \name QCO/Operations/StandardGates/SdgOp.cpp /// @{ -TEST_F(QCOTest, SdgOpMatrix) { +TEST_F(QCOMatrixTest, SdgOpMatrix) { // Get the (static) matrix from the operation const auto matrix = SdgOp::getUnitaryMatrix(); @@ -504,7 +505,7 @@ TEST_F(QCOTest, SdgOpMatrix) { /// \name QCO/Operations/StandardGates/SwapOp.cpp /// @{ -TEST_F(QCOTest, SWAPOpMatrix) { +TEST_F(QCOMatrixTest, SWAPOpMatrix) { // Get the (static) matrix from the operation const auto matrix = SWAPOp::getUnitaryMatrix(); @@ -526,7 +527,7 @@ TEST_F(QCOTest, SWAPOpMatrix) { /// \name QCO/Operations/StandardGates/SxOp.cpp /// @{ -TEST_F(QCOTest, SXOpMatrix) { +TEST_F(QCOMatrixTest, SXOpMatrix) { // Get the (static) matrix from the operation const auto matrix = SXOp::getUnitaryMatrix(); @@ -544,7 +545,7 @@ TEST_F(QCOTest, SXOpMatrix) { /// \name QCO/Operations/StandardGates/SxdgOp.cpp /// @{ -TEST_F(QCOTest, SXdgOpMatrix) { +TEST_F(QCOMatrixTest, SXdgOpMatrix) { // Get the (static) matrix from the operation const auto matrix = SXdgOp::getUnitaryMatrix(); @@ -562,7 +563,7 @@ TEST_F(QCOTest, SXdgOpMatrix) { /// \name QCO/Operations/StandardGates/TOp.cpp /// @{ -TEST_F(QCOTest, TOpMatrix) { +TEST_F(QCOMatrixTest, TOpMatrix) { // Get the (static) matrix from the operation const auto matrix = TOp::getUnitaryMatrix(); @@ -580,7 +581,7 @@ TEST_F(QCOTest, TOpMatrix) { /// \name QCO/Operations/StandardGates/TdgOp.cpp /// @{ -TEST_F(QCOTest, TdgOpMatrix) { +TEST_F(QCOMatrixTest, TdgOpMatrix) { // Get the (static) matrix from the operation const auto matrix = TdgOp::getUnitaryMatrix(); @@ -598,7 +599,7 @@ TEST_F(QCOTest, TdgOpMatrix) { /// \name QCO/Operations/StandardGates/U2Op.cpp /// @{ -TEST_F(QCOTest, U2OpMatrix) { +TEST_F(QCOMatrixTest, U2OpMatrix) { auto moduleOp = QCOProgramBuilder::build(context.get(), u2); ASSERT_TRUE(moduleOp); @@ -622,7 +623,7 @@ TEST_F(QCOTest, U2OpMatrix) { /// \name QCO/Operations/StandardGates/UOp.cpp /// @{ -TEST_F(QCOTest, UOpMatrix) { +TEST_F(QCOMatrixTest, UOpMatrix) { auto moduleOp = QCOProgramBuilder::build(context.get(), u); ASSERT_TRUE(moduleOp); @@ -646,7 +647,7 @@ TEST_F(QCOTest, UOpMatrix) { /// \name QCO/Operations/StandardGates/XOp.cpp /// @{ -TEST_F(QCOTest, XOpMatrix) { +TEST_F(QCOMatrixTest, XOpMatrix) { // Get the (static) matrix from the operation const auto matrix = XOp::getUnitaryMatrix(); @@ -664,7 +665,7 @@ TEST_F(QCOTest, XOpMatrix) { /// \name QCO/Operations/StandardGates/XxMinusYyOp.cpp /// @{ -TEST_F(QCOTest, XXMinusYYOpMatrix) { +TEST_F(QCOMatrixTest, XXMinusYYOpMatrix) { auto moduleOp = QCOProgramBuilder::build(context.get(), xxMinusYY); ASSERT_TRUE(moduleOp); @@ -692,7 +693,7 @@ TEST_F(QCOTest, XXMinusYYOpMatrix) { /// \name QCO/Operations/StandardGates/XxPlusYyOp.cpp /// @{ -TEST_F(QCOTest, XXPlusYYOp) { +TEST_F(QCOMatrixTest, XXPlusYYOp) { auto moduleOp = QCOProgramBuilder::build(context.get(), xxPlusYY); ASSERT_TRUE(moduleOp); @@ -720,7 +721,7 @@ TEST_F(QCOTest, XXPlusYYOp) { /// \name QCO/Operations/StandardGates/YOp.cpp /// @{ -TEST_F(QCOTest, YOpMatrix) { +TEST_F(QCOMatrixTest, YOpMatrix) { // Get the (static) matrix from the operation const auto matrix = YOp::getUnitaryMatrix(); @@ -738,7 +739,7 @@ TEST_F(QCOTest, YOpMatrix) { /// \name QCO/Operations/StandardGates/ZOp.cpp /// @{ -TEST_F(QCOTest, ZOpMatrix) { +TEST_F(QCOMatrixTest, ZOpMatrix) { // Get the (static) matrix from the operation const auto matrix = ZOp::getUnitaryMatrix(); diff --git a/mlir/unittests/Dialect/QIR/IR/test_qir_ir.cpp b/mlir/unittests/Dialect/QIR/IR/test_qir_ir.cpp index f9fdf94ddb..e177c90329 100644 --- a/mlir/unittests/Dialect/QIR/IR/test_qir_ir.cpp +++ b/mlir/unittests/Dialect/QIR/IR/test_qir_ir.cpp @@ -28,6 +28,8 @@ using namespace mlir; using namespace qir; +namespace { + struct QIRTestCase { std::string name; mqt::test::NamedBuilder programBuilder; @@ -36,6 +38,14 @@ struct QIRTestCase { friend std::ostream& operator<<(std::ostream& os, const QIRTestCase& info); }; +// NOLINTNEXTLINE(llvm-prefer-static-over-anonymous-namespace) +std::ostream& operator<<(std::ostream& os, const QIRTestCase& info) { + return os << "QIR{" << info.name + << ", original=" << mqt::test::displayName(info.programBuilder.name) + << ", reference=" + << mqt::test::displayName(info.referenceBuilder.name) << "}"; +} + class QIRTest : public testing::TestWithParam { protected: std::unique_ptr context; @@ -49,12 +59,7 @@ class QIRTest : public testing::TestWithParam { } }; -std::ostream& operator<<(std::ostream& os, const QIRTestCase& info) { - return os << "QIR{" << info.name - << ", original=" << mqt::test::displayName(info.programBuilder.name) - << ", reference=" - << mqt::test::displayName(info.referenceBuilder.name) << "}"; -} +} // namespace TEST_P(QIRTest, ProgramEquivalence) { const auto& [_, programBuilder, referenceBuilder] = GetParam(); diff --git a/mlir/unittests/Dialect/Utils/test_utils.cpp b/mlir/unittests/Dialect/Utils/test_utils.cpp index 30fb71863e..36bd137673 100644 --- a/mlir/unittests/Dialect/Utils/test_utils.cpp +++ b/mlir/unittests/Dialect/Utils/test_utils.cpp @@ -29,6 +29,8 @@ using namespace mlir; +namespace { + class UtilsTest : public ::testing::Test { protected: MLIRContext context; @@ -53,6 +55,8 @@ class UtilsTest : public ::testing::Test { } }; +} // namespace + TEST_F(UtilsTest, valueToDouble) { constexpr double expectedValue = 1.234; auto op = arith::ConstantOp::create(*builder, diff --git a/src/circuit_optimizer/CircuitOptimizer.cpp b/src/circuit_optimizer/CircuitOptimizer.cpp index fbb9bf8933..544a43519b 100644 --- a/src/circuit_optimizer/CircuitOptimizer.cpp +++ b/src/circuit_optimizer/CircuitOptimizer.cpp @@ -1364,6 +1364,8 @@ void CircuitOptimizer::backpropagateOutputPermutation(QuantumComputation& qc) { qc.initialLayout = permutation; } +namespace { + /** * @brief Disjoint Set Union data structure for qubits * @@ -1471,6 +1473,8 @@ struct DSU { } }; +} // namespace + void CircuitOptimizer::collectBlocks(QuantumComputation& qc, const std::size_t maxBlockSize) { if (qc.size() <= 1) { @@ -1625,6 +1629,8 @@ void CircuitOptimizer::collectBlocks(QuantumComputation& qc, removeIdentities(qc); } +namespace { + /** * @brief Block of Clifford operations * @details This structure is used to collect Clifford operations that can be @@ -1657,8 +1663,8 @@ struct CliffordBlock { * @param maxBlockSize Maximum allowed block size */ [[nodiscard]] bool - checkExceedsMaxBlockSize(const std::set& used, - const std::size_t maxBlockSize) const noexcept { + checkFitsWithinMaxBlockSize(const std::set& used, + const std::size_t maxBlockSize) const noexcept { std::size_t extra = 0; for (const auto q : used) { if (!blockQubits.contains(q)) { @@ -1753,6 +1759,8 @@ struct CliffordBlock { } }; +} // namespace + void CircuitOptimizer::collectCliffordBlocks(QuantumComputation& qc, const std::size_t maxBlockSize) { if (qc.size() <= 1) { @@ -1809,7 +1817,7 @@ void CircuitOptimizer::collectCliffordBlocks(QuantumComputation& qc, if (!block.checkBlocked(used)) { continue; } - if (!block.checkExceedsMaxBlockSize(used, maxBlockSize)) { + if (!block.checkFitsWithinMaxBlockSize(used, maxBlockSize)) { continue; } diff --git a/src/dd/CachedEdge.cpp b/src/dd/CachedEdge.cpp index fa4bd223f6..7abefb20e3 100644 --- a/src/dd/CachedEdge.cpp +++ b/src/dd/CachedEdge.cpp @@ -162,15 +162,15 @@ template struct CachedEdge; } // namespace dd -namespace std { template -auto hash>::operator()( +auto std::hash>::operator()( const dd::CachedEdge& e) const noexcept -> std::size_t { const auto h1 = dd::murmur64(reinterpret_cast(e.p)); const auto h2 = std::hash{}(e.w); return qc::combineHash(h1, h2); } -template struct hash>; -template struct hash>; -} // namespace std +// NOLINTNEXTLINE(bugprone-std-namespace-modification) +template struct std::hash>; +// NOLINTNEXTLINE(bugprone-std-namespace-modification) +template struct std::hash>; diff --git a/src/dd/ComplexValue.cpp b/src/dd/ComplexValue.cpp index bdc1bf7faa..1eb2d12d1c 100644 --- a/src/dd/ComplexValue.cpp +++ b/src/dd/ComplexValue.cpp @@ -300,13 +300,11 @@ std::ostream& operator<<(std::ostream& os, const ComplexValue& c) { } } // namespace dd -namespace std { -std::size_t -hash::operator()(const dd::ComplexValue& c) const noexcept { +std::size_t std::hash::operator()( + const dd::ComplexValue& c) const noexcept { const auto h1 = dd::murmur64( static_cast(std::round(c.r / dd::RealNumber::eps))); const auto h2 = dd::murmur64( static_cast(std::round(c.i / dd::RealNumber::eps))); return qc::combineHash(h1, h2); } -} // namespace std diff --git a/src/dd/Edge.cpp b/src/dd/Edge.cpp index 952056035e..9a52b670e7 100644 --- a/src/dd/Edge.cpp +++ b/src/dd/Edge.cpp @@ -513,15 +513,15 @@ template struct Edge; /// \n Hash related code \n ///----------------------------------------------------------------------------- -namespace std { template -auto hash>::operator()(const dd::Edge& e) const noexcept - -> std::size_t { +auto std::hash>::operator()( + const dd::Edge& e) const noexcept -> std::size_t { const auto h1 = dd::murmur64(reinterpret_cast(e.p)); const auto h2 = std::hash{}(e.w); return qc::combineHash(h1, h2); } -template struct hash>; -template struct hash>; -} // namespace std +// NOLINTNEXTLINE(bugprone-std-namespace-modification) +template struct std::hash>; +// NOLINTNEXTLINE(bugprone-std-namespace-modification) +template struct std::hash>; diff --git a/src/dd/Package.cpp b/src/dd/Package.cpp index b9e01dfe3a..ed34234512 100644 --- a/src/dd/Package.cpp +++ b/src/dd/Package.cpp @@ -177,7 +177,7 @@ mEdge Package::makeGateDD(const GateMatrix& mat, const qc::Controls& controls, if (controls.empty()) { // Single qubit operation const auto e = makeDDNode(static_cast(target), em); - return {e.p, cn.lookup(e.w)}; + return {.p = e.p, .w = cn.lookup(e.w)}; } auto it = controls.begin(); @@ -216,7 +216,7 @@ mEdge Package::makeGateDD(const GateMatrix& mat, const qc::Controls& controls, e = makeDDNode(static_cast(it->qubit), edges); } } - return {e.p, cn.lookup(e.w)}; + return {.p = e.p, .w = cn.lookup(e.w)}; } mEdge Package::makeTwoQubitGateDD(const TwoQubitGateMatrix& mat, const qc::Qubit target0, @@ -339,7 +339,7 @@ mEdge Package::makeTwoQubitGateDD(const TwoQubitGateMatrix& mat, e = makeDDNode(static_cast(it->qubit), edges); } - return {e.p, cn.lookup(e.w)}; + return {.p = e.p, .w = cn.lookup(e.w)}; } mEdge Package::makeDDFromMatrix(const CMat& matrix) { if (matrix.empty()) { @@ -362,7 +362,7 @@ mEdge Package::makeDDFromMatrix(const CMat& matrix) { const auto level = static_cast(std::log2(length) - 1); const auto matrixDD = makeDDFromMatrix(matrix, level, 0, length, 0, width); - return {matrixDD.p, cn.lookup(matrixDD.w)}; + return {.p = matrixDD.p, .w = cn.lookup(matrixDD.w)}; } mCachedEdge Package::makeDDFromMatrix(const CMat& matrix, const Qubit level, const std::size_t rowStart, @@ -426,7 +426,7 @@ std::string Package::measureAll(vEdge& rootEdge, const bool collapse, std::string result(numberOfQubits, '0'); - std::uniform_real_distribution dist(0.0, 1.0L); + std::uniform_real_distribution dist(0.0, 1.0); for (auto i = numberOfQubits; i > 0; --i) { fp p0 = ComplexNumbers::mag2(cur.p->e.at(0).w); @@ -584,7 +584,7 @@ void Package::performCollapsingMeasurement(vEdge& rootEdge, const Qubit index, } vEdge Package::conjugate(const vEdge& a) { const auto r = conjugateRec(a); - return {r.p, cn.lookup(r.w)}; + return {.p = r.p, .w = cn.lookup(r.w)}; } vCachedEdge Package::conjugateRec(const vEdge& a) { if (a.isZeroTerminal()) { @@ -609,7 +609,7 @@ vCachedEdge Package::conjugateRec(const vEdge& a) { } mEdge Package::conjugateTranspose(const mEdge& a) { const auto r = conjugateTransposeRec(a); - return {r.p, cn.lookup(r.w)}; + return {.p = r.p, .w = cn.lookup(r.w)}; } mCachedEdge Package::conjugateTransposeRec(const mEdge& a) { if (a.isTerminal()) { // terminal case @@ -662,7 +662,7 @@ ComplexValue Package::innerProduct(const vEdge& x, const vEdge& y) { const auto w = std::max(x.p->v, y.p->v); // Overall normalization factor needs to be conjugated // before input into recursive private function - auto xCopy = vEdge{x.p, ComplexNumbers::conj(x.w)}; + auto xCopy = vEdge{.p = x.p, .w = ComplexNumbers::conj(x.w)}; return innerProduct(xCopy, y, w + 1U); } fp Package::fidelity(const vEdge& x, const vEdge& y) { @@ -772,7 +772,7 @@ fp Package::expectationValue(const mEdge& x, const vEdge& y) { mEdge Package::partialTrace(const mEdge& a, const std::vector& eliminate) { auto r = trace(a, eliminate, eliminate.size()); - return {r.p, cn.lookup(r.w)}; + return {.p = r.p, .w = cn.lookup(r.w)}; } ComplexValue Package::trace(const mEdge& a, const std::size_t numQubits) { if (a.isIdentity()) { @@ -971,7 +971,7 @@ mEdge Package::reduceAncillae(mEdge e, const std::vector& ancillary, mCachedEdge::zero()}); } } - const auto res = mEdge{g.p, cn.lookup(g.w * e.w)}; + const auto res = mEdge{.p = g.p, .w = cn.lookup(g.w * e.w)}; incRef(res); decRef(e); return res; @@ -1000,7 +1000,7 @@ vEdge Package::reduceGarbage(vEdge& e, const std::vector& garbage, if (normalizeWeights) { weight = weight.mag(); } - const auto res = vEdge{f.p, cn.lookup(weight)}; + const auto res = vEdge{.p = f.p, .w = cn.lookup(weight)}; incRef(res); decRef(e); return res; @@ -1064,7 +1064,7 @@ mEdge Package::reduceGarbage(const mEdge& e, const std::vector& garbage, if (normalizeWeights) { weight = weight.mag(); } - const auto res = mEdge{g.p, cn.lookup(weight)}; + const auto res = mEdge{.p = g.p, .w = cn.lookup(weight)}; incRef(res); decRef(e); diff --git a/src/dd/StateGeneration.cpp b/src/dd/StateGeneration.cpp index 578fde5971..0b63abe4b2 100644 --- a/src/dd/StateGeneration.cpp +++ b/src/dd/StateGeneration.cpp @@ -175,7 +175,7 @@ VectorDD makeBasisState(const std::size_t n, } f = dd.makeDDNode(v, edges); } - const vEdge e{f.p, dd.cn.lookup(f.w)}; + const vEdge e{.p = f.p, .w = dd.cn.lookup(f.w)}; dd.incRef(e); return e; } @@ -260,7 +260,7 @@ VectorDD makeStateFromVector(const CVec& vec, Package& dd) { const vCachedEdge state = makeStateFromVector(vec.begin(), vec.end(), v, dd); - const vEdge ret{state.p, dd.cn.lookup(state.w)}; + const vEdge ret{.p = state.p, .w = dd.cn.lookup(state.w)}; dd.incRef(ret); return ret; } @@ -358,7 +358,7 @@ VectorDD generateRandomState(const std::size_t levels, } // Below only contains one element: the root. - vEdge ret{curr.at(0).p, Complex::one()}; + vEdge ret{.p = curr.at(0).p, .w = Complex::one()}; dd.incRef(ret); return ret; } diff --git a/src/dd/statistics/PackageStatistics.cpp b/src/dd/statistics/PackageStatistics.cpp index 19db2dbf4c..98588dfae3 100644 --- a/src/dd/statistics/PackageStatistics.cpp +++ b/src/dd/statistics/PackageStatistics.cpp @@ -178,50 +178,46 @@ nlohmann::basic_json<> getDataStructureStatistics() { // For every entry, we store the size in bytes and the alignment in bytes auto& ctEntries = j["ComplexTableEntries"]; auto& vectorAdd = ctEntries["vector_add"]; - vectorAdd["size_B"] = sizeof(typename decltype(Package::vectorAdd)::Entry); - vectorAdd["alignment_B"] = - alignof(typename decltype(Package::vectorAdd)::Entry); + vectorAdd["size_B"] = sizeof(decltype(Package::vectorAdd)::Entry); + vectorAdd["alignment_B"] = alignof(decltype(Package::vectorAdd)::Entry); auto& matrixAdd = ctEntries["matrix_add"]; - matrixAdd["size_B"] = sizeof(typename decltype(Package::matrixAdd)::Entry); - matrixAdd["alignment_B"] = - alignof(typename decltype(Package::matrixAdd)::Entry); + matrixAdd["size_B"] = sizeof(decltype(Package::matrixAdd)::Entry); + matrixAdd["alignment_B"] = alignof(decltype(Package::matrixAdd)::Entry); auto& conjugateMatrixTranspose = ctEntries["conjugate_matrix_transpose"]; conjugateMatrixTranspose["size_B"] = - sizeof(typename decltype(Package::conjugateMatrixTranspose)::Entry); + sizeof(decltype(Package::conjugateMatrixTranspose)::Entry); conjugateMatrixTranspose["alignment_B"] = - alignof(typename decltype(Package::conjugateMatrixTranspose)::Entry); + alignof(decltype(Package::conjugateMatrixTranspose)::Entry); auto& matrixVectorMult = ctEntries["matrix_vector_mult"]; matrixVectorMult["size_B"] = - sizeof(typename decltype(Package::matrixVectorMultiplication)::Entry); + sizeof(decltype(Package::matrixVectorMultiplication)::Entry); matrixVectorMult["alignment_B"] = - alignof(typename decltype(Package::matrixVectorMultiplication)::Entry); + alignof(decltype(Package::matrixVectorMultiplication)::Entry); auto& matrixMatrixMult = ctEntries["matrix_matrix_mult"]; matrixMatrixMult["size_B"] = - sizeof(typename decltype(Package::matrixMatrixMultiplication)::Entry); + sizeof(decltype(Package::matrixMatrixMultiplication)::Entry); matrixMatrixMult["alignment_B"] = - alignof(typename decltype(Package::matrixMatrixMultiplication)::Entry); + alignof(decltype(Package::matrixMatrixMultiplication)::Entry); auto& vectorKronecker = ctEntries["vector_kronecker"]; - vectorKronecker["size_B"] = - sizeof(typename decltype(Package::vectorKronecker)::Entry); + vectorKronecker["size_B"] = sizeof(decltype(Package::vectorKronecker)::Entry); vectorKronecker["alignment_B"] = - alignof(typename decltype(Package::vectorKronecker)::Entry); + alignof(decltype(Package::vectorKronecker)::Entry); auto& matrixKronecker = ctEntries["matrix_kronecker"]; - matrixKronecker["size_B"] = - sizeof(typename decltype(Package::matrixKronecker)::Entry); + matrixKronecker["size_B"] = sizeof(decltype(Package::matrixKronecker)::Entry); matrixKronecker["alignment_B"] = - alignof(typename decltype(Package::matrixKronecker)::Entry); + alignof(decltype(Package::matrixKronecker)::Entry); auto& vectorInnerProduct = ctEntries["vector_inner_product"]; vectorInnerProduct["size_B"] = - sizeof(typename decltype(Package::vectorInnerProduct)::Entry); + sizeof(decltype(Package::vectorInnerProduct)::Entry); vectorInnerProduct["alignment_B"] = - alignof(typename decltype(Package::vectorInnerProduct)::Entry); + alignof(decltype(Package::vectorInnerProduct)::Entry); return j; } diff --git a/src/ir/operations/IfElseOperation.cpp b/src/ir/operations/IfElseOperation.cpp index ece89849ee..10ff911b83 100644 --- a/src/ir/operations/IfElseOperation.cpp +++ b/src/ir/operations/IfElseOperation.cpp @@ -304,12 +304,12 @@ std::size_t std::hash::operator()( } if (const auto& reg = op.getControlRegister(); reg.has_value()) { assert(!op.getControlBit().has_value()); - qc::hashCombine(seed, std::hash{}(reg.value())); + qc::hashCombine(seed, std::hash{}(*reg)); qc::hashCombine(seed, op.getExpectedValueRegister()); } if (const auto& bit = op.getControlBit(); bit.has_value()) { assert(!op.getControlRegister().has_value()); - qc::hashCombine(seed, bit.value()); + qc::hashCombine(seed, *bit); qc::hashCombine(seed, static_cast(op.getExpectedValueBit())); } qc::hashCombine(seed, op.getComparisonKind()); diff --git a/src/ir/operations/StandardOperation.cpp b/src/ir/operations/StandardOperation.cpp index dc4bd8ce16..d8a59c1403 100644 --- a/src/ir/operations/StandardOperation.cpp +++ b/src/ir/operations/StandardOperation.cpp @@ -46,7 +46,7 @@ OpType StandardOperation::parseU3(fp& theta, fp& phi, fp& lambda) { } if (std::abs(lambda) < PARAMETER_TOLERANCE) { - lambda = 0.L; + lambda = 0.0; if (std::abs(phi) < PARAMETER_TOLERANCE) { checkInteger(theta); checkFractionPi(theta); @@ -85,7 +85,7 @@ OpType StandardOperation::parseU3(fp& theta, fp& phi, fp& lambda) { if (std::abs(lambda - PI) < PARAMETER_TOLERANCE) { lambda = PI; if (std::abs(phi) < PARAMETER_TOLERANCE) { - phi = 0.L; + phi = 0.0; if (std::abs(theta - PI) < PARAMETER_TOLERANCE) { parameter.clear(); return X; @@ -106,7 +106,7 @@ OpType StandardOperation::parseU3(fp& theta, fp& phi, fp& lambda) { OpType StandardOperation::parseU2(fp& phi, fp& lambda) { if (std::abs(phi) < PARAMETER_TOLERANCE) { - phi = 0.L; + phi = 0.0; if (std::abs(std::abs(lambda) - PI) < PARAMETER_TOLERANCE) { parameter.clear(); return H; diff --git a/src/ir/operations/SymbolicOperation.cpp b/src/ir/operations/SymbolicOperation.cpp index 92c2e6d095..6405babe05 100644 --- a/src/ir/operations/SymbolicOperation.cpp +++ b/src/ir/operations/SymbolicOperation.cpp @@ -32,6 +32,7 @@ namespace qc { // Overload pattern for std::visit namespace { +// NOLINTNEXTLINE(misc-multiple-inheritance) template struct Overload : Ts... { using Ts::operator()...; }; @@ -62,9 +63,9 @@ fp& SymbolicOperation::getNumber(SymbolOrNumber& param) { OpType SymbolicOperation::parseU3([[maybe_unused]] const Symbolic& theta, fp& phi, fp& lambda) { if (std::abs(lambda) < PARAMETER_TOLERANCE) { - lambda = 0.L; + lambda = 0.0; if (std::abs(phi) < PARAMETER_TOLERANCE) { - phi = 0.L; + phi = 0.0; } } @@ -78,7 +79,7 @@ OpType SymbolicOperation::parseU3([[maybe_unused]] const Symbolic& theta, if (std::abs(lambda - PI) < PARAMETER_TOLERANCE) { lambda = PI; if (std::abs(phi) < PARAMETER_TOLERANCE) { - phi = 0.L; + phi = 0.0; } } @@ -97,7 +98,7 @@ OpType SymbolicOperation::parseU3(fp& theta, const Symbolic& phi, fp& lambda) { } if (std::abs(lambda) < PARAMETER_TOLERANCE) { - lambda = 0.L; + lambda = 0.0; } if (std::abs(lambda - PI_2) < PARAMETER_TOLERANCE) { @@ -120,8 +121,8 @@ OpType SymbolicOperation::parseU3(fp& theta, fp& phi, [[maybe_unused]] const Symbolic& lambda) { if (std::abs(theta) < PARAMETER_TOLERANCE && std::abs(phi) < PARAMETER_TOLERANCE) { - phi = 0.L; - theta = 0.L; + phi = 0.0; + theta = 0.0; return SymbolicOperation::parseU1(lambda); } diff --git a/src/qdmi/devices/na/Device.cpp b/src/qdmi/devices/na/Device.cpp index 4fd5fd3020..c0d8a4c8be 100644 --- a/src/qdmi/devices/na/Device.cpp +++ b/src/qdmi/devices/na/Device.cpp @@ -102,7 +102,7 @@ auto Device::queryProperty(const QDMI_Device_Property prop, const size_t size, size, value, sizeRet) ADD_LIST_PROPERTY(QDMI_DEVICE_PROPERTY_OPERATIONS, MQT_NA_QDMI_Operation, operations_, prop, size, value, sizeRet) - if (prop == (QDMI_DEVICE_PROPERTY_SUPPORTEDPROGRAMFORMATS)) { + if (prop == QDMI_DEVICE_PROPERTY_SUPPORTEDPROGRAMFORMATS) { if (value != nullptr && size > 0) { return QDMI_ERROR_INVALIDARGUMENT; } diff --git a/src/qdmi/devices/na/DynDevice.cpp b/src/qdmi/devices/na/DynDevice.cpp index c6fdaf4d9f..34dcea8fa4 100644 --- a/src/qdmi/devices/na/DynDevice.cpp +++ b/src/qdmi/devices/na/DynDevice.cpp @@ -125,7 +125,7 @@ int MQT_NA_DYN_QDMI_device_session_query_device_property( // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic) static_cast(value)[size - 1] = '\0'; } - if ((sizeRet) != nullptr) { + if (sizeRet != nullptr) { *sizeRet = 27; } } diff --git a/src/qdmi/devices/sc/Device.cpp b/src/qdmi/devices/sc/Device.cpp index f5c9448c94..dc398619ab 100644 --- a/src/qdmi/devices/sc/Device.cpp +++ b/src/qdmi/devices/sc/Device.cpp @@ -92,7 +92,7 @@ auto Device::queryProperty(const QDMI_Device_Property prop, const size_t size, couplingMap_, prop, size, value, sizeRet) ADD_LIST_PROPERTY(QDMI_DEVICE_PROPERTY_OPERATIONS, MQT_SC_QDMI_Operation, operations_, prop, size, value, sizeRet) - if (prop == (QDMI_DEVICE_PROPERTY_SUPPORTEDPROGRAMFORMATS)) { + if (prop == QDMI_DEVICE_PROPERTY_SUPPORTEDPROGRAMFORMATS) { if (value != nullptr && size > 0) { return QDMI_ERROR_INVALIDARGUMENT; } diff --git a/src/qdmi/devices/sc/DynDevice.cpp b/src/qdmi/devices/sc/DynDevice.cpp index 0f97bc4b79..020ffc1559 100644 --- a/src/qdmi/devices/sc/DynDevice.cpp +++ b/src/qdmi/devices/sc/DynDevice.cpp @@ -125,7 +125,7 @@ int MQT_SC_DYN_QDMI_device_session_query_device_property( // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic) static_cast(value)[size - 1] = '\0'; } - if ((sizeRet) != nullptr) { + if (sizeRet != nullptr) { *sizeRet = 27; } } diff --git a/src/qir/.clang-tidy b/src/qir/.clang-tidy new file mode 100644 index 0000000000..b7fccb3e0e --- /dev/null +++ b/src/qir/.clang-tidy @@ -0,0 +1,14 @@ +InheritParentConfig: true +Checks: | + llvm-namespace-comment, + llvm-prefer-isa-or-dyn-cast-in-conditionals, + llvm-prefer-register-over-unsigned, + llvm-prefer-static-over-anonymous-namespace, + -bugprone-throwing-static-initialization, + -cppcoreguidelines-avoid-non-const-global-variables, + -cppcoreguidelines-pro-bounds-avoid-unchecked-container-access, + -misc-use-anonymous-namespace, + +CheckOptions: + - key: readability-identifier-naming.VariableCase + value: CamelCase diff --git a/src/qir/runner/Runner.cpp b/src/qir/runner/Runner.cpp index 3aa5d16cfd..9335c0f590 100644 --- a/src/qir/runner/Runner.cpp +++ b/src/qir/runner/Runner.cpp @@ -53,32 +53,20 @@ #define DEBUG_TYPE "mqt-core-qir-runner" -namespace { -// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables,readability-identifier-naming) -llvm::codegen::RegisterCodeGenFlags CGF; +static llvm::codegen::RegisterCodeGenFlags CGF; -const llvm::cl::opt INPUT_FILE(llvm::cl::desc(""), +static llvm::cl::opt InputFile(llvm::cl::desc(""), llvm::cl::Positional, llvm::cl::init("-")); -const llvm::cl::list - INPUT_ARGV(llvm::cl::ConsumeAfter, - llvm::cl::desc("...")); +static llvm::cl::list + InputArgv(llvm::cl::ConsumeAfter, llvm::cl::desc("...")); -// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) -llvm::ExitOnError exitOnErr; +static llvm::ExitOnError ExitOnError; -// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) -std::vector> manualSymbols; +static void exitOnLazyCallThroughFailure() { exit(1); } -#define REGISTER_SYMBOL(name) \ - llvm::sys::DynamicLibrary::AddSymbol(#name, \ - reinterpret_cast(&(name))); \ - manualSymbols.emplace_back(#name, reinterpret_cast(&(name))); - -void exitOnLazyCallThroughFailure() { exit(1); } - -llvm::Expected +static llvm::Expected loadModule(const llvm::StringRef path, llvm::orc::ThreadSafeContext tsCtx) { llvm::SMDiagnostic err; auto m = tsCtx.withContextDo( @@ -96,7 +84,7 @@ loadModule(const llvm::StringRef path, llvm::orc::ThreadSafeContext tsCtx) { return llvm::orc::ThreadSafeModule(std::move(m), std::move(tsCtx)); } -int mingwNoopMain() { +static int mingwNoopMain() { // Cygwin and MinGW insert calls from the main function to the runtime // function __main. The __main function is responsible for setting up main's // environment (e.g. running static constructors), however this is not needed @@ -109,7 +97,7 @@ int mingwNoopMain() { // Try to enable debugger support for the given instance. // This always returns success, but prints a warning if it's not able to enable // debugger support. -llvm::Error tryEnableDebugSupport(llvm::orc::LLJIT& jit) { +static llvm::Error tryEnableDebugSupport(llvm::orc::LLJIT& jit) { if (auto err = enableDebuggerSupport(jit)) { [[maybe_unused]] const std::string errMsg = toString(std::move(err)); // NOLINTNEXTLINE(cppcoreguidelines-avoid-do-while) @@ -118,13 +106,15 @@ llvm::Error tryEnableDebugSupport(llvm::orc::LLJIT& jit) { return llvm::Error::success(); } -int runOrcJIT() { +static std::vector> manualSymbols; + +static int runOrcJIT() { // Start setting up the JIT environment. // Parse the main module. const llvm::orc::ThreadSafeContext tsCtx( std::make_unique()); - auto mainModule = exitOnErr(loadModule(INPUT_FILE, tsCtx)); + auto mainModule = ExitOnError(loadModule(InputFile, tsCtx)); // Get TargetTriple and DataLayout from the main module if they're explicitly // set. @@ -143,7 +133,7 @@ int runOrcJIT() { builder.setJITTargetMachineBuilder( tt ? llvm::orc::JITTargetMachineBuilder(*tt) - : exitOnErr(llvm::orc::JITTargetMachineBuilder::detectHost())); + : ExitOnError(llvm::orc::JITTargetMachineBuilder::detectHost())); tt = builder.getJITTargetMachineBuilder()->getTargetTriple(); if (dl) { @@ -165,7 +155,7 @@ int runOrcJIT() { builder.setLinkProcessSymbolsByDefault(true); auto es = std::make_unique( - exitOnErr(llvm::orc::SelfExecutorProcessControl::Create())); + ExitOnError(llvm::orc::SelfExecutorProcessControl::Create())); builder.setLazyCallthroughManager( std::make_unique( *es, llvm::orc::ExecutorAddr(), nullptr)); @@ -177,7 +167,7 @@ int runOrcJIT() { // Enable debugging of JIT'd code (only works on JITLink for ELF and MachO). builder.setPrePlatformSetup(tryEnableDebugSupport); - const auto jit = exitOnErr(builder.create()); + const auto jit = ExitOnError(builder.create()); auto& jd = jit->getMainJITDylib(); llvm::orc::SymbolMap hostSymbols; @@ -185,10 +175,10 @@ int runOrcJIT() { hostSymbols[jit->mangleAndIntern(name)] = { llvm::orc::ExecutorAddr::fromPtr(ptr), llvm::JITSymbolFlags::Exported}; } - exitOnErr(jd.define(llvm::orc::absoluteSymbols(hostSymbols))); + ExitOnError(jd.define(llvm::orc::absoluteSymbols(hostSymbols))); - jit->getMainJITDylib().addGenerator( - exitOnErr(llvm::orc::DynamicLibrarySearchGenerator::GetForCurrentProcess( + jit->getMainJITDylib().addGenerator(ExitOnError( + llvm::orc::DynamicLibrarySearchGenerator::GetForCurrentProcess( jit->getDataLayout().getGlobalPrefix()))); auto* objLayer = &jit->getObjLinkingLayer(); @@ -204,7 +194,7 @@ int runOrcJIT() { auto& workaroundJD = jit->getProcessSymbolsJITDylib() ? *jit->getProcessSymbolsJITDylib() : jit->getMainJITDylib(); - exitOnErr(workaroundJD.define(llvm::orc::absoluteSymbols( + ExitOnError(workaroundJD.define(llvm::orc::absoluteSymbols( {{jit->mangleAndIntern("__main"), {llvm::orc::ExecutorAddr::fromPtr(mingwNoopMain), llvm::JITSymbolFlags::Exported}}}))); @@ -219,32 +209,36 @@ int runOrcJIT() { }; // Add the main module. - exitOnErr(addModule(jit->getMainJITDylib(), std::move(mainModule))); + ExitOnError(addModule(jit->getMainJITDylib(), std::move(mainModule))); // Run any static constructors. - exitOnErr(jit->initialize(jit->getMainJITDylib())); + ExitOnError(jit->initialize(jit->getMainJITDylib())); // Resolve and run the main function. - const auto mainAddr = exitOnErr(jit->lookup("main")); + const auto mainAddr = ExitOnError(jit->lookup("main")); // Manual in-process execution with RuntimeDyld. using mainFnTy = int(int, char**); auto mainFn = mainAddr.toPtr(); const int result = - llvm::orc::runAsMain(mainFn, INPUT_ARGV, llvm::StringRef(INPUT_FILE)); + llvm::orc::runAsMain(mainFn, InputArgv, llvm::StringRef(InputFile)); // Run destructors. - exitOnErr(jit->deinitialize(jit->getMainJITDylib())); + ExitOnError(jit->deinitialize(jit->getMainJITDylib())); return result; } -} // namespace + +#define REGISTER_SYMBOL(name) \ + llvm::sys::DynamicLibrary::AddSymbol(#name, \ + reinterpret_cast(&(name))); \ + manualSymbols.emplace_back(#name, reinterpret_cast(&(name))); auto main(int argc, char* argv[]) -> int { const llvm::InitLLVM session(argc, argv); if (const std::span args(argv, argc); args.size() > 1) { - exitOnErr.setBanner(std::string(args[0]) + ": "); + ExitOnError.setBanner(std::string(args[0]) + ": "); } // If we have a native target, initialize it to ensure it is linked in and @@ -320,3 +314,5 @@ auto main(int argc, char* argv[]) -> int { return runOrcJIT(); } + +#undef REGISTER_SYMBOL diff --git a/src/qir/runtime/Runtime.cpp b/src/qir/runtime/Runtime.cpp index bff0a7171a..0ca6a70c6b 100644 --- a/src/qir/runtime/Runtime.cpp +++ b/src/qir/runtime/Runtime.cpp @@ -114,6 +114,7 @@ auto Runtime::enlargeState(const std::uint64_t maxQubit) -> void { } } +// NOLINTNEXTLINE(bugprone-exception-escape) auto Runtime::swap(Qubit* qubit1, Qubit* qubit2) -> void { const auto target1 = translateAddresses(std::array{qubit1})[0]; const auto target2 = translateAddresses(std::array{qubit2})[0]; diff --git a/test/algorithms/eval_dynamic_circuits.cpp b/test/algorithms/eval_dynamic_circuits.cpp index 9804c4f6ea..1ce8b4963b 100644 --- a/test/algorithms/eval_dynamic_circuits.cpp +++ b/test/algorithms/eval_dynamic_circuits.cpp @@ -29,6 +29,8 @@ #include #include +namespace { + class DynamicCircuitEvalExactQPE : public testing::TestWithParam { protected: qc::Qubit precision{}; @@ -100,6 +102,8 @@ class DynamicCircuitEvalExactQPE : public testing::TestWithParam { } }; +} // namespace + INSTANTIATE_TEST_SUITE_P( Eval, DynamicCircuitEvalExactQPE, testing::Range(1U, 64U, 5U), [](const testing::TestParamInfo& @@ -184,6 +188,8 @@ TEST_P(DynamicCircuitEvalExactQPE, UnitaryTransformation) { EXPECT_TRUE(e.isIdentity()); } +namespace { + class DynamicCircuitEvalInexactQPE : public testing::TestWithParam { protected: qc::Qubit precision{}; @@ -269,6 +275,8 @@ class DynamicCircuitEvalInexactQPE : public testing::TestWithParam { } }; +} // namespace + INSTANTIATE_TEST_SUITE_P( Eval, DynamicCircuitEvalInexactQPE, testing::Range(1U, 15U, 3U), [](const testing::TestParamInfo& @@ -353,6 +361,8 @@ TEST_P(DynamicCircuitEvalInexactQPE, UnitaryTransformation) { EXPECT_TRUE(e.isIdentity()); } +namespace { + class DynamicCircuitEvalBV : public testing::TestWithParam { protected: qc::Qubit bitwidth{}; @@ -383,6 +393,8 @@ class DynamicCircuitEvalBV : public testing::TestWithParam { } }; +} // namespace + INSTANTIATE_TEST_SUITE_P( Eval, DynamicCircuitEvalBV, testing::Range(1U, 64U, 5U), [](const testing::TestParamInfo& inf) { @@ -466,6 +478,8 @@ TEST_P(DynamicCircuitEvalBV, UnitaryTransformation) { EXPECT_TRUE(e.isIdentity()); } +namespace { + class DynamicCircuitEvalQFT : public testing::TestWithParam { protected: qc::Qubit precision{}; @@ -492,6 +506,8 @@ class DynamicCircuitEvalQFT : public testing::TestWithParam { } }; +} // namespace + INSTANTIATE_TEST_SUITE_P( Eval, DynamicCircuitEvalQFT, testing::Range(1U, 65U, 5U), [](const testing::TestParamInfo& inf) { diff --git a/test/algorithms/test_bernsteinvazirani.cpp b/test/algorithms/test_bernsteinvazirani.cpp index db90e75d1b..868e8f8f20 100644 --- a/test/algorithms/test_bernsteinvazirani.cpp +++ b/test/algorithms/test_bernsteinvazirani.cpp @@ -23,12 +23,16 @@ #include #include +namespace { + class BernsteinVazirani : public testing::TestWithParam { protected: void TearDown() override {} void SetUp() override {} }; +} // namespace + INSTANTIATE_TEST_SUITE_P( BernsteinVazirani, BernsteinVazirani, testing::Values(0ULL, // Zero-Value diff --git a/test/algorithms/test_entanglement.cpp b/test/algorithms/test_entanglement.cpp index 464bb3318a..5fa2d9216a 100644 --- a/test/algorithms/test_entanglement.cpp +++ b/test/algorithms/test_entanglement.cpp @@ -23,6 +23,8 @@ #include #include +namespace { + class Entanglement : public testing::TestWithParam { protected: void TearDown() override {} @@ -34,6 +36,8 @@ class Entanglement : public testing::TestWithParam { std::unique_ptr dd; }; +} // namespace + INSTANTIATE_TEST_SUITE_P( Entanglement, Entanglement, testing::Range(2U, 90U, 7U), [](const testing::TestParamInfo& inf) { diff --git a/test/algorithms/test_grover.cpp b/test/algorithms/test_grover.cpp index 918273a53d..0b1acc1633 100644 --- a/test/algorithms/test_grover.cpp +++ b/test/algorithms/test_grover.cpp @@ -29,6 +29,8 @@ #include #include +namespace { + class Grover : public testing::TestWithParam> { protected: @@ -58,6 +60,8 @@ class Grover qc::GroverBitString targetValue; }; +} // namespace + constexpr qc::Qubit GROVER_MAX_QUBITS = 15; constexpr std::size_t GROVER_NUM_SEEDS = 5; constexpr dd::fp GROVER_ACCURACY = 1e-2; diff --git a/test/algorithms/test_qft.cpp b/test/algorithms/test_qft.cpp index 8684f83cec..e4cd1cd72a 100644 --- a/test/algorithms/test_qft.cpp +++ b/test/algorithms/test_qft.cpp @@ -29,8 +29,11 @@ #include #include #include +#include #include +namespace { + class QFT : public testing::TestWithParam { protected: void TearDown() override {} @@ -47,6 +50,8 @@ class QFT : public testing::TestWithParam { dd::MatrixDD func{}; }; +} // namespace + /// Findings from the QFT Benchmarks: /// The DDpackage has to be able to represent all 2^n different amplitudes in /// order to produce correct results The smallest entry seems to be closely @@ -57,7 +62,6 @@ class QFT : public testing::TestWithParam { /// 10e-13 .. 23 qubits /// The accuracy of double floating points allows for a minimal CN::TOLERANCE /// value of 10e-15 -/// Utilizing more qubits requires the use of fp=long double constexpr qc::Qubit QFT_MAX_QUBITS = 17U; constexpr size_t INITIAL_COMPLEX_COUNT = dd::immortals::size(); @@ -96,22 +100,20 @@ TEST_P(QFT, Functionality) { ASSERT_EQ(dd->cn.realCount(), 1ULL << (std::max(2UL, nqubits) - 2)); - // top edge weight should equal sqrt(0.5)^n - EXPECT_NEAR(dd::RealNumber::val(func.w.r), - static_cast(std::pow(1.L / std::sqrt(2.L), nqubits)), + const auto expectedAmplitude = + static_cast(std::pow(1.0 / std::numbers::sqrt2, nqubits)); + + // top edge weight should equal (1/sqrt(2))^n + EXPECT_NEAR(dd::RealNumber::val(func.w.r), expectedAmplitude, dd::RealNumber::eps); - // first row and first column should consist only of (1/sqrt(2))**nqubits + // first row and first column should consist only of (1/sqrt(2))^n entries for (std::uint64_t i = 0; i < 1ULL << nqubits; ++i) { auto c = func.getValueByIndex(dd->qubits(), 0, i); - EXPECT_NEAR(c.real(), - static_cast(std::pow(1.L / std::sqrt(2.L), nqubits)), - dd::RealNumber::eps); + EXPECT_NEAR(c.real(), expectedAmplitude, dd::RealNumber::eps); EXPECT_NEAR(c.imag(), 0, dd::RealNumber::eps); c = func.getValueByIndex(dd->qubits(), i, 0); - EXPECT_NEAR(c.real(), - static_cast(std::pow(1.L / std::sqrt(2.L), nqubits)), - dd::RealNumber::eps); + EXPECT_NEAR(c.real(), expectedAmplitude, dd::RealNumber::eps); EXPECT_NEAR(c.imag(), 0, dd::RealNumber::eps); } dd->decRef(func); @@ -141,23 +143,20 @@ TEST_P(QFT, FunctionalityRecursive) { ASSERT_EQ(dd->cn.realCount(), 1ULL << (std::max(2UL, nqubits) - 2)); - // top edge weight should equal sqrt(0.5)^n - EXPECT_NEAR(dd::RealNumber::val(func.w.r), - static_cast(std::pow(1.L / std::sqrt(2.L), nqubits)), + const auto expectedAmplitude = + static_cast(std::pow(1.0 / std::numbers::sqrt2, nqubits)); + + // top edge weight should equal (1/sqrt(2))^n + EXPECT_NEAR(dd::RealNumber::val(func.w.r), expectedAmplitude, dd::RealNumber::eps); - // first row and first column should consist only of (1/sqrt(2))**nqubits - for (std::uint64_t i = 0; i < std::pow(static_cast(2), nqubits); - ++i) { + // first row and first column should consist only of (1/sqrt(2))^n entries + for (std::uint64_t i = 0; i < 1ULL << nqubits; ++i) { auto c = func.getValueByIndex(dd->qubits(), 0, i); - EXPECT_NEAR(c.real(), - static_cast(std::pow(1.L / std::sqrt(2.L), nqubits)), - dd::RealNumber::eps); + EXPECT_NEAR(c.real(), expectedAmplitude, dd::RealNumber::eps); EXPECT_NEAR(c.imag(), 0, dd::RealNumber::eps); c = func.getValueByIndex(dd->qubits(), i, 0); - EXPECT_NEAR(c.real(), - static_cast(std::pow(1.L / std::sqrt(2.L), nqubits)), - dd::RealNumber::eps); + EXPECT_NEAR(c.real(), expectedAmplitude, dd::RealNumber::eps); EXPECT_NEAR(c.imag(), 0, dd::RealNumber::eps); } dd->decRef(func); @@ -188,12 +187,13 @@ TEST_P(QFT, Simulation) { EXPECT_NEAR(dd::RealNumber::val(sim.w.r), 1, dd::RealNumber::eps); EXPECT_NEAR(dd::RealNumber::val(sim.w.i), 0, dd::RealNumber::eps); - // first column should consist only of sqrt(0.5)^n's + // first column should consist only of (1/sqrt(2))^n entries for (std::uint64_t i = 0; i < 1ULL << nqubits; ++i) { auto c = sim.getValueByIndex(i); - EXPECT_NEAR(c.real(), - static_cast(std::pow(1.L / std::sqrt(2.L), nqubits)), - dd::RealNumber::eps); + EXPECT_NEAR( + c.real(), + static_cast(std::pow(1.0 / std::numbers::sqrt2, nqubits)), + dd::RealNumber::eps); EXPECT_NEAR(c.imag(), 0, dd::RealNumber::eps); } dd->decRef(sim); diff --git a/test/algorithms/test_qpe.cpp b/test/algorithms/test_qpe.cpp index d45860ff3e..553f3dfac1 100644 --- a/test/algorithms/test_qpe.cpp +++ b/test/algorithms/test_qpe.cpp @@ -32,6 +32,8 @@ #include #include +namespace { + class QPE : public testing::TestWithParam> { protected: qc::fp lambda{}; @@ -116,6 +118,8 @@ class QPE : public testing::TestWithParam> { } }; +} // namespace + INSTANTIATE_TEST_SUITE_P( QPE, QPE, testing::Values(std::pair{1., 1U}, std::pair{0.5, 2U}, std::pair{0.25, 3U}, @@ -198,7 +202,7 @@ TEST_P(QPE, IQPETest) { } else { auto it = ordered.begin(); std::advance(it, 1); - const auto& [secondMostLikelyResult, secondMostLikelyCount] = *(it); + const auto& [secondMostLikelyResult, secondMostLikelyCount] = *it; EXPECT_TRUE( (mostLikelyResult == expectedResultRepresentation && secondMostLikelyResult == secondExpectedResultRepresentation) || diff --git a/test/algorithms/test_random_clifford.cpp b/test/algorithms/test_random_clifford.cpp index cf18527a5d..f58d42e74b 100644 --- a/test/algorithms/test_random_clifford.cpp +++ b/test/algorithms/test_random_clifford.cpp @@ -23,12 +23,16 @@ #include #include +namespace { + class RandomClifford : public testing::TestWithParam { protected: void TearDown() override {} void SetUp() override {} }; +} // namespace + INSTANTIATE_TEST_SUITE_P( RandomClifford, RandomClifford, testing::Range(1U, 9U), [](const testing::TestParamInfo& inf) { diff --git a/test/algorithms/test_statepreparation.cpp b/test/algorithms/test_statepreparation.cpp index ba06c5f138..b35b8350ff 100644 --- a/test/algorithms/test_statepreparation.cpp +++ b/test/algorithms/test_statepreparation.cpp @@ -27,6 +27,8 @@ constexpr double EPS = 1e-10; +namespace { + class StatePreparation : public testing::TestWithParam>> { protected: @@ -36,6 +38,8 @@ class StatePreparation void SetUp() override { amplitudes = GetParam(); } }; +} // namespace + INSTANTIATE_TEST_SUITE_P( StatePreparation, StatePreparation, testing::Values( diff --git a/test/algorithms/test_wstate.cpp b/test/algorithms/test_wstate.cpp index ec7f43053b..7e069f3955 100644 --- a/test/algorithms/test_wstate.cpp +++ b/test/algorithms/test_wstate.cpp @@ -21,9 +21,10 @@ #include #include +namespace { + class WState : public testing::TestWithParam {}; -namespace { std::vector generateWStateStrings(const std::size_t length) { std::vector result; result.reserve(length); @@ -34,6 +35,7 @@ std::vector generateWStateStrings(const std::size_t length) { } return result; } + } // namespace INSTANTIATE_TEST_SUITE_P( diff --git a/test/dd/test_complex.cpp b/test/dd/test_complex.cpp index bd59f81874..ba830f58c0 100644 --- a/test/dd/test_complex.cpp +++ b/test/dd/test_complex.cpp @@ -28,6 +28,8 @@ using namespace dd; +namespace { + class CNTest : public testing::Test { protected: MemoryManager mm{MemoryManager::create()}; @@ -35,6 +37,8 @@ class CNTest : public testing::Test { ComplexNumbers cn{ut}; }; +} // namespace + TEST_F(CNTest, ComplexNumberCreation) { EXPECT_TRUE(cn.lookup(Complex::zero()).exactlyZero()); EXPECT_TRUE(cn.lookup(Complex::one()).exactlyOne()); @@ -150,7 +154,7 @@ TEST_F(CNTest, LookupInNeighbouringBuckets) { auto preHash = [fpMask](const fp val) { return val * fpMask; }; // lower border of a bucket - const fp numBucketBorder = (0.25 * fpMask - 0.5) / (fpMask); + const fp numBucketBorder = ((0.25 * fpMask) - 0.5) / fpMask; const auto hashBucketBorder = RealNumberUniqueTable::hash(numBucketBorder); std::cout.flush(); std::clog << "numBucketBorder = " diff --git a/test/dd/test_dd_functionality.cpp b/test/dd/test_dd_functionality.cpp index accc6c8c43..1cdb4552ec 100644 --- a/test/dd/test_dd_functionality.cpp +++ b/test/dd/test_dd_functionality.cpp @@ -38,6 +38,8 @@ using namespace qc; using namespace dd; +namespace { + class DDFunctionality : public testing::TestWithParam { protected: void TearDown() override {} @@ -56,6 +58,8 @@ class DDFunctionality : public testing::TestWithParam { std::uniform_real_distribution dist; }; +} // namespace + INSTANTIATE_TEST_SUITE_P( Parameters, DDFunctionality, testing::Values(GPhase, I, H, X, Y, Z, S, Sdg, T, Tdg, SX, SXdg, V, Vdg, U, diff --git a/test/fomac/test_fomac.cpp b/test/fomac/test_fomac.cpp index 4a1a925c17..a3166e5f67 100644 --- a/test/fomac/test_fomac.cpp +++ b/test/fomac/test_fomac.cpp @@ -29,6 +29,9 @@ #include namespace fomac { + +namespace { + class DeviceTest : public testing::TestWithParam { protected: Session::Device device; @@ -103,6 +106,8 @@ cx q[0], q[1]; } }; +} // namespace + TEST(FoMaCTest, StatusToString) { EXPECT_STREQ(qdmi::toString(QDMI_WARN_GENERAL), "General warning"); EXPECT_STREQ(qdmi::toString(QDMI_SUCCESS), "Success"); diff --git a/test/ir/test_io.cpp b/test/ir/test_io.cpp index c44f3b6a53..03ab35e81b 100644 --- a/test/ir/test_io.cpp +++ b/test/ir/test_io.cpp @@ -33,6 +33,8 @@ #include #include +namespace { + class IO : public testing::Test { protected: void TearDown() override {} @@ -48,7 +50,6 @@ class IO : public testing::Test { qc::QuantumComputation qc; }; -namespace { void compareFiles(const std::string& file1, const std::string& file2) { std::ifstream fstream1(file1); std::string str1((std::istreambuf_iterator(fstream1)), @@ -60,6 +61,7 @@ void compareFiles(const std::string& file1, const std::string& file2) { std::erase_if(str2, isspace); ASSERT_EQ(str1, str2); } + } // namespace TEST_F(IO, importAndDumpQASM) { diff --git a/test/ir/test_qasm3_parser.cpp b/test/ir/test_qasm3_parser.cpp index fb4e9244c5..623af1be11 100644 --- a/test/ir/test_qasm3_parser.cpp +++ b/test/ir/test_qasm3_parser.cpp @@ -32,8 +32,12 @@ using namespace qc; +namespace { + class Qasm3ParserTest : public testing::TestWithParam {}; +} // namespace + TEST_F(Qasm3ParserTest, ImportQasm3) { const std::string testfile = "OPENQASM 3.0;\n" "include \"stdgates.inc\";\n" diff --git a/test/ir/test_qfr_functionality.cpp b/test/ir/test_qfr_functionality.cpp index 7cf5dd83e5..f6f3e2b51e 100644 --- a/test/ir/test_qfr_functionality.cpp +++ b/test/ir/test_qfr_functionality.cpp @@ -41,6 +41,7 @@ namespace qc { namespace { + void printRegisters(const QuantumComputation& qc) { for (const auto& [name, reg] : qc.getQuantumRegisters()) { std::cout << "QuantumRegister(name=" << name @@ -58,7 +59,6 @@ void printRegisters(const QuantumComputation& qc) { << ")\n"; } } -} // namespace class QFRFunctionality : public testing::TestWithParam { protected: @@ -76,6 +76,8 @@ class QFRFunctionality : public testing::TestWithParam { std::uniform_real_distribution dist; }; +} // namespace + TEST_F(QFRFunctionality, removeTrailingIdleQubits) { const std::size_t nqubits = 4; QuantumComputation qc(nqubits, nqubits); diff --git a/test/ir/test_symbolic.cpp b/test/ir/test_symbolic.cpp index a398dc6abe..298ea5ea02 100644 --- a/test/ir/test_symbolic.cpp +++ b/test/ir/test_symbolic.cpp @@ -23,6 +23,9 @@ using namespace qc; using namespace sym; + +namespace { + class SymbolicTest : public ::testing::Test { public: Variable x = Variable("x"); @@ -37,6 +40,8 @@ class SymbolicTest : public ::testing::Test { QuantumComputation qc = QuantumComputation(4); }; +} // namespace + TEST_F(SymbolicTest, Gates) { auto xVal = PI_4 / 2; auto yVal = PI_4 / 4; diff --git a/test/na/test_nacomputation.cpp b/test/na/test_nacomputation.cpp index 6c2ce3a196..cc44c486e4 100644 --- a/test/na/test_nacomputation.cpp +++ b/test/na/test_nacomputation.cpp @@ -130,6 +130,8 @@ TEST(NAComputation, EmptyPrint) { EXPECT_EQ(ss.str(), ""); } +namespace { + class NAComputationValidateAODConstraints : public ::testing::Test { protected: NAComputation qc; @@ -150,6 +152,8 @@ class NAComputationValidateAODConstraints : public ::testing::Test { } }; +} // namespace + TEST_F(NAComputationValidateAODConstraints, AtomAlreadyLoaded) { qc.emplaceBack( std::vector{atom0, atom2}, diff --git a/test/qdmi/devices/dd/error_handling_test.cpp b/test/qdmi/devices/dd/error_handling_test.cpp index b22836f512..6d9f8fcc72 100644 --- a/test/qdmi/devices/dd/error_handling_test.cpp +++ b/test/qdmi/devices/dd/error_handling_test.cpp @@ -18,12 +18,16 @@ #include #include +namespace { + class ErrorHandling : public ::testing::Test { protected: static auto SetUpTestSuite() -> void { MQT_DDSIM_QDMI_device_initialize(); } static auto TearDownTestSuite() -> void { MQT_DDSIM_QDMI_device_finalize(); } }; +} // namespace + TEST_F(ErrorHandling, NullptrArguments) { EXPECT_EQ(MQT_DDSIM_QDMI_device_session_alloc(nullptr), QDMI_ERROR_INVALIDARGUMENT); diff --git a/test/qdmi/devices/na/test_device.cpp b/test/qdmi/devices/na/test_device.cpp index e32500a460..264df04de4 100644 --- a/test/qdmi/devices/na/test_device.cpp +++ b/test/qdmi/devices/na/test_device.cpp @@ -47,6 +47,7 @@ MATCHER_P2(IsBetween, a, b, } // namespace testing namespace { + /// Hash function for a pair struct PairHash { template @@ -94,7 +95,6 @@ struct PairHash { } return operations; } -} // namespace class NaQDMISpecificationTest : public ::testing::Test { protected: @@ -143,6 +143,8 @@ class NaQDMIJobSpecificationTest : public NaQDMISpecificationTest { } }; +} // namespace + TEST_F(NaQDMISpecificationTest, SessionAlloc) { EXPECT_EQ(MQT_NA_QDMI_device_session_alloc(nullptr), QDMI_ERROR_INVALIDARGUMENT); @@ -477,6 +479,8 @@ TEST_F(NaQDMISpecificationTest, QueryDeviceQubitNum) { QDMI_SUCCESS); } +namespace { + class NADeviceTest : public NaQDMISpecificationTest { protected: // NOLINTNEXTLINE(misc-include-cleaner) @@ -501,6 +505,8 @@ class NADeviceTest : public NaQDMISpecificationTest { void TearDown() override { NaQDMISpecificationTest::TearDown(); } }; +} // namespace + TEST_F(NADeviceTest, QuerySiteData) { std::vector sites; EXPECT_NO_THROW(sites = querySites(session)) diff --git a/test/qdmi/devices/sc/test_device.cpp b/test/qdmi/devices/sc/test_device.cpp index 7d0a647525..66479c9a4a 100644 --- a/test/qdmi/devices/sc/test_device.cpp +++ b/test/qdmi/devices/sc/test_device.cpp @@ -20,6 +20,7 @@ #include namespace { + [[nodiscard]] auto querySites(MQT_SC_QDMI_Device_Session session) -> std::vector { size_t size = 0; @@ -39,7 +40,6 @@ namespace { } return sites; } -} // namespace class ScQDMISpecificationTest : public ::testing::Test { protected: @@ -88,6 +88,8 @@ class ScQDMIJobSpecificationTest : public ScQDMISpecificationTest { } }; +} // namespace + TEST_F(ScQDMISpecificationTest, SessionAlloc) { EXPECT_EQ(MQT_SC_QDMI_device_session_alloc(nullptr), QDMI_ERROR_INVALIDARGUMENT); diff --git a/test/qdmi/driver/test_driver.cpp b/test/qdmi/driver/test_driver.cpp index c3cd05be59..0688c09d34 100644 --- a/test/qdmi/driver/test_driver.cpp +++ b/test/qdmi/driver/test_driver.cpp @@ -44,7 +44,11 @@ MATCHER_P2(IsBetween, a, b, // NOLINTEND(readability-identifier-naming,cppcoreguidelines-avoid-const-or-ref-data-members) } // namespace } // namespace testing + namespace qc { + +namespace { + class DriverTest : public testing::TestWithParam { protected: QDMI_Session session = nullptr; @@ -127,6 +131,8 @@ class DriverJobTest : public DriverTest { } }; +} // namespace + TEST_P(DriverTest, SessionSetParameter) { const std::string authFile = "authfile.txt"; QDMI_Session uninitializedSession = nullptr; diff --git a/test/qir/runner/test_qir_runner.cpp b/test/qir/runner/test_qir_runner.cpp index b86b33a461..bb3de09fba 100644 --- a/test/qir/runner/test_qir_runner.cpp +++ b/test/qir/runner/test_qir_runner.cpp @@ -15,8 +15,13 @@ #include namespace qir { + +namespace { + class QIRRunnerTest : public testing::TestWithParam {}; +} // namespace + // Instantiate the test suite with different parameters INSTANTIATE_TEST_SUITE_P( QIRRunnerTest, //< Custom instantiation name diff --git a/test/qir/runtime/test_qir_runtime.cpp b/test/qir/runtime/test_qir_runtime.cpp index 05e83cf1ef..cc4e733f7f 100644 --- a/test/qir/runtime/test_qir_runtime.cpp +++ b/test/qir/runtime/test_qir_runtime.cpp @@ -30,6 +30,8 @@ namespace qir { +namespace { + class QIRRuntimeTest : public testing::Test { protected: std::stringstream buffer; @@ -38,6 +40,8 @@ class QIRRuntimeTest : public testing::Test { void TearDown() override { std::cout.rdbuf(old); } }; +} // namespace + TEST_F(QIRRuntimeTest, XGate) { auto* q0 = reinterpret_cast(0UL); __quantum__rt__initialize(nullptr); @@ -501,8 +505,12 @@ TEST_F(QIRRuntimeTest, GHZ4Dynamic) { __quantum__rt__array_update_reference_count(rArr, -1); } +namespace { + class QIRFilesTest : public ::testing::TestWithParam {}; +} // namespace + // Instantiate the test suite with different parameters INSTANTIATE_TEST_SUITE_P( QIRExecutablesTest, //< Custom instantiation name diff --git a/test/zx/test_expression.cpp b/test/zx/test_expression.cpp index dc8581efe6..64f9168cee 100644 --- a/test/zx/test_expression.cpp +++ b/test/zx/test_expression.cpp @@ -22,6 +22,8 @@ namespace sym { using namespace zx; +namespace { + class ExpressionTest : public ::testing::Test { public: Term x{Variable("x"), 1.0}; @@ -29,6 +31,8 @@ class ExpressionTest : public ::testing::Test { Term z{Variable("z")}; }; +} // namespace + TEST_F(ExpressionTest, basicOps1) { Expression e(x); diff --git a/test/zx/test_rational.cpp b/test/zx/test_rational.cpp index de29fd643b..837c4e21e2 100644 --- a/test/zx/test_rational.cpp +++ b/test/zx/test_rational.cpp @@ -14,8 +14,13 @@ #include namespace zx { + +namespace { + class RationalTest : public ::testing::Test {}; +} // namespace + TEST_F(RationalTest, normalize) { const PiRational r(-33, 16); EXPECT_EQ(r, PiRational(-1, 16)); diff --git a/test/zx/test_simplify.cpp b/test/zx/test_simplify.cpp index b8f1749136..f01028b221 100644 --- a/test/zx/test_simplify.cpp +++ b/test/zx/test_simplify.cpp @@ -21,9 +21,10 @@ namespace zx { +namespace { + class SimplifyTest : public ::testing::Test {}; -namespace { ZXDiagram makeIdentityDiagram(const std::size_t nqubits, const std::size_t spidersPerQubit) { ZXDiagram diag(nqubits); @@ -56,6 +57,7 @@ ZXDiagram makeEmptyDiagram(const std::size_t nqubits) { } return diag; } + } // namespace TEST_F(SimplifyTest, idSimp) { diff --git a/test/zx/test_zx.cpp b/test/zx/test_zx.cpp index f91529fae6..59ccb9c267 100644 --- a/test/zx/test_zx.cpp +++ b/test/zx/test_zx.cpp @@ -23,6 +23,9 @@ #include namespace zx { + +namespace { + class ZXDiagramTest : public ::testing::Test { public: ZXDiagram diag; @@ -53,6 +56,8 @@ class ZXDiagramTest : public ::testing::Test { } }; +} // namespace + TEST_F(ZXDiagramTest, createDiagram) { EXPECT_EQ(diag.getNVertices(), 7); EXPECT_EQ(diag.getNEdges(), 6); diff --git a/test/zx/test_zx_functionality.cpp b/test/zx/test_zx_functionality.cpp index 2be1a2ad14..79edeec944 100644 --- a/test/zx/test_zx_functionality.cpp +++ b/test/zx/test_zx_functionality.cpp @@ -31,11 +31,16 @@ #include namespace zx { + +namespace { + class ZXFunctionalityTest : public ::testing::Test { public: qc::QuantumComputation qc; }; +} // namespace + TEST_F(ZXFunctionalityTest, parseQasm) { const std::string testfile = "OPENQASM 2.0;" "include \"qelib1.inc\";"