Merged
feat(pypto_pro): Add pypro_pro codegen and frontend #4925
wuzhongxinAdd on Jul 17
feat(pypto_pro): Add pypro_pro codegen and frontend #4925
Merged
Merged fromwuzhongxin/cann_pyptonewintocann/pyptomaster
Total: 75 files changed+12047-6162
| @@ -33,8 +33,8 @@ using TupleTypePtr = std::shared_ptr<const TupleType>; | |||
| 33 | * each `struct.create` / `MakeTuple` allocates a fresh instance (`make_shared`), | 33 | * each `struct.create` / `MakeTuple` allocates a fresh instance (`make_shared`), |
| 34 | * so same-shape-different-name structs get distinct keys. IR passes copy `TypePtr` | 34 | * so same-shape-different-name structs get distinct keys. IR passes copy `TypePtr` |
| 35 | * by shared_ptr (types are immutable and never rebuilt via reflection), so the | 35 | * by shared_ptr (types are immutable and never rebuilt via reflection), so the |
| 36 | - * pointer stays valid and identical across ConvertToSSA / | 36 | + * pointer stays valid and identical while IR transformation passes rebuild the |
| 37 | - * ConstFoldAndSimplify / InlineHelperCalls. | 37 | + * surrounding nodes. |
| 38 | * | 38 | * |
| 39 | * The parser populates this (via `makeNamedTuple` / struct.create lowering); the | 39 | * The parser populates this (via `makeNamedTuple` / struct.create lowering); the |
| 40 | * instance rides on `Program` so codegen can capture it at its entry point. | 40 | * instance rides on `Program` so codegen can capture it at its entry point. |
| @@ -17,8 +17,6 @@ namespace pypto { | |||
| 17 | namespace ir { | 17 | namespace ir { |
| 18 | namespace pass { | 18 | namespace pass { |
| 19 | 19 | ||
| 20 | -inline const PassProperties kLowerBreakContinueProperties{{IRProperty::TypeChecked}, {IRProperty::TypeChecked}, {}}; | ||
| 21 | - | ||
| 22 | inline const PassProperties kUnrollLoopsProperties{{IRProperty::TypeChecked}, {IRProperty::TypeChecked}, {}}; | 20 | inline const PassProperties kUnrollLoopsProperties{{IRProperty::TypeChecked}, {IRProperty::TypeChecked}, {}}; |
| 23 | 21 | ||
| 24 | inline const PassProperties kSplitChunkedLoopsProperties{ | 22 | inline const PassProperties kSplitChunkedLoopsProperties{ |
| @@ -194,29 +194,6 @@ Pass ConvertTensorToBlockOps(); | |||
| 194 | */ | 194 | */ |
| 195 | Pass RunVerifier(const std::vector<std::string>& disabled_rules = {}); | 195 | Pass RunVerifier(const std::vector<std::string>& disabled_rules = {}); |
| 196 | 196 | ||
| 197 | -/** | ||
| 198 | - * \brief Create a pass that lowers break/continue statements to structured control flow | ||
| 199 | - * | ||
| 200 | - * Transforms BreakStmt and ContinueStmt into nested scf.if blocks suitable for MLIR codegen. | ||
| 201 | - * - continue: wrapped in if(!cond) guard over remaining statements | ||
| 202 | - * - break (for): adds a _can_continue boolean iter_arg; body guarded by scf.if(_can_continue) | ||
| 203 | - * - break (while): adds a _can_continue iter_arg as sole before-region condition; | ||
| 204 | - * original condition checked via scf.if at the start of the do-region (no And/Or/Not) | ||
| 205 | - * | ||
| 206 | - * Must run before ConvertToSSA and before codegen. | ||
| 207 | - */ | ||
| 208 | -Pass LowerBreakContinue(); | ||
| 209 | - | ||
| 210 | -/** | ||
| 211 | - * \brief Create a constant folding and simplification pass | ||
| 212 | - * | ||
| 213 | - * Folds constant arithmetic (ConstInt + ConstInt → ConstInt), simplifies | ||
| 214 | - * if-stmts with constant conditions or identical branches, and removes | ||
| 215 | - * dead comparisons. Reduces scalar instruction count significantly. | ||
| 216 | - * Should run after ConvertToSSA. | ||
| 217 | - */ | ||
| 218 | -Pass ConstFoldAndSimplify(); | ||
| 219 | - | ||
| 220 | /** | 197 | /** |
| 221 | * \brief Create an aggressive dead code elimination pass | 198 | * \brief Create an aggressive dead code elimination pass |
| 222 | * | 199 | * |
| @@ -275,31 +252,6 @@ Pass CreateRootFunctions(); | |||
| 275 | * \brief Finalize dynamic functions built from new IR (post create_root_functions). | 252 | * \brief Finalize dynamic functions built from new IR (post create_root_functions). |
| 276 | */ | 253 | */ |
| 277 | Pass FinalizeDynamicFunction(); | 254 | Pass FinalizeDynamicFunction(); |
| 278 | - | ||
| 279 | -/** | ||
| 280 | - * \brief Normalize "clear-form" Mat matmul operands to the physical layout pto-isa needs. | ||
| 281 | - * | ||
| 282 | - * The L1(Mat)->L0(Left/Right) move (`block.move`) requires the source and destination | ||
| 283 | - * tiles to have the SAME physical [Rows, Cols] (the CANN TMOV tileop static-asserts on it). | ||
| 284 | - * Because `Mat [N,K] NZ` and `Mat [K,N] ZN` are the *same bytes*, a matmul operand that is | ||
| 285 | - * logically transposed on-chip previously had to be declared in the physical form | ||
| 286 | - * `Mat [K,N] ZN`, whose shape does not match the source data it is filled from. | ||
| 287 | - * | ||
| 288 | - * This pass lets the frontend declare such an operand in "clear form" — shape equal to the | ||
| 289 | - * data it holds, layout matching that shape (e.g. `Mat [N,K] NZ` for data `d=[N,K]`) — and | ||
| 290 | - * rewrites it back to the physical form. It detects a `block.move(dst=Left/Right, src=Mat)` | ||
| 291 | - * whose src shape is the reverse of the dst shape (and non-square), then relabels that Mat | ||
| 292 | - * allocation: swap the two shape dims and swap blayout<->slayout (flips NZ<->ZN). The bytes | ||
| 293 | - * are unchanged, so codegen and the hardware behave exactly as with the explicit physical form. | ||
| 294 | - * | ||
| 295 | - * The rewrite follows the allocation by MemRef identity, so every reference Var is updated | ||
| 296 | - * regardless of tile-group assignment or control flow. It is a no-op when src.shape == | ||
| 297 | - * dst.shape (the convention every other kernel uses), so existing kernels are unaffected. | ||
| 298 | - * | ||
| 299 | - * Must run before ConvertToSSA (and after helper inlining so the move and make_tile are in | ||
| 300 | - * the same function). | ||
| 301 | - */ | ||
| 302 | -Pass NormalizeMatTransposeLayout(); | ||
| 303 | } // namespace pass | 255 | } // namespace pass |
| 304 | 256 | ||
| 305 | /** | 257 | /** |
Rframework/include/pypto_pro/backend/910B_CCE/backend_910b_cce.h→framework/include/pypto_pro/backend/backend_cce.h+8-35
| @@ -4,12 +4,12 @@ | |||
| 4 | * CANN Open Software License Agreement Version 2.0 (the "License"). | 4 | * CANN Open Software License Agreement Version 2.0 (the "License"). |
| 5 | * Please refer to the License for details. You may not use this file except in compliance with the License. | 5 | * Please refer to the License for details. You may not use this file except in compliance with the License. |
| 6 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | 6 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, |
| 7 | - * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | 7 | + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. |
| 8 | * See LICENSE in the root of the software repository for the full text of the License. | 8 | * See LICENSE in the root of the software repository for the full text of the License. |
| 9 | */ | 9 | */ |
| 10 | 10 | ||
| 11 | -#ifndef PYPTO_BACKEND_910B_CCE_BACKEND_910B_CCE_H_ | 11 | +#ifndef PYPTO_BACKEND_BACKEND_CCE_H_ |
| 12 | -#define PYPTO_BACKEND_910B_CCE_BACKEND_910B_CCE_H_ | 12 | +#define PYPTO_BACKEND_BACKEND_CCE_H_ |
| 13 | 13 | ||
| 14 | #include <string> | 14 | #include <string> |
| 15 | 15 | ||
| @@ -18,44 +18,17 @@ | |||
| 18 | namespace pypto { | 18 | namespace pypto { |
| 19 | namespace backend { | 19 | namespace backend { |
| 20 | 20 | ||
| 21 | -/** | 21 | +class BackendCCE : public Backend { |
| 22 | - * \brief Backend implementation for 910B hardware with CCE code generation | ||
| 23 | - * | ||
| 24 | - * Provides CCE (C++ pto-isa) code generation for 910B architecture. | ||
| 25 | - * Uses shared 910B SoC configuration created by Create910BSoC(). | ||
| 26 | - * Operators are registered via REGISTER_BACKEND_OP macro in separate | ||
| 27 | - * compilation units. | ||
| 28 | - */ | ||
| 29 | -class Backend910B_CCE : public Backend { | ||
| 30 | public: | 22 | public: |
| 31 | - /** | 23 | + static BackendCCE& Instance(); |
| 32 | - * \brief Get registration instance for static operator registration | ||
| 33 | - * | ||
| 34 | - * Returns a singleton instance used during static initialization | ||
| 35 | - * to register operators via REGISTER_BACKEND_OP macro. | ||
| 36 | - * | ||
| 37 | - * \return Reference to registration instance | ||
| 38 | - */ | ||
| 39 | - static Backend910B_CCE& Instance(); | ||
| 40 | 24 | ||
| 41 | - /** | 25 | + [[nodiscard]] std::string GetTypeName() const override { return "CCE"; } |
| 42 | - * \brief Get backend type name | ||
| 43 | - * | ||
| 44 | - * \return "910B_CCE" | ||
| 45 | - */ | ||
| 46 | - [[nodiscard]] std::string GetTypeName() const override { return "910B_CCE"; } | ||
| 47 | 26 | ||
| 48 | private: | 27 | private: |
| 49 | - /** | 28 | + BackendCCE(); |
| 50 | - * \brief Private constructor (singleton pattern) | ||
| 51 | - * | ||
| 52 | - * Constructor is private to enforce singleton pattern. | ||
| 53 | - * Use Instance() to get the singleton instance. | ||
| 54 | - */ | ||
| 55 | - Backend910B_CCE(); | ||
| 56 | }; | 29 | }; |
| 57 | 30 | ||
| 58 | } // namespace backend | 31 | } // namespace backend |
| 59 | } // namespace pypto | 32 | } // namespace pypto |
| 60 | 33 | ||
| 61 | -#endif // PYPTO_BACKEND_910B_CCE_BACKEND_910B_CCE_H_ | 34 | +#endif // PYPTO_BACKEND_BACKEND_CCE_H_ |
| @@ -39,25 +39,15 @@ using CallPtr = std::shared_ptr<const Call>; | |||
| 39 | 39 | ||
| 40 | namespace backend { | 40 | namespace backend { |
| 41 | 41 | ||
| 42 | -// Forward declaration (required for GetBackendInstance return type) | 42 | +// Forward declaration |
| 43 | class Backend; | 43 | class Backend; |
| 44 | 44 | ||
| 45 | -/** | 45 | +/*! |
| 46 | - * \brief Backend type identifier for selecting backend instance | 46 | + * \brief Get the singleton backend instance |
| 47 | * | 47 | * |
| 48 | - * to obtain the corresponding backend instance via GetBackendInstance(). | ||
| 49 | - */ | ||
| 50 | -enum class BackendType { | ||
| 51 | - CCE ///< 910B CCE backend (C++ codegen) | ||
| 52 | -}; | ||
| 53 | - | ||
| 54 | -/** | ||
| 55 | - * \brief Get the singleton backend instance for the given type | ||
| 56 | - * | ||
| 57 | - * \param type Backend type (CCE) | ||
| 58 | * \return Pointer to the backend instance (never null) | 48 | * \return Pointer to the backend instance (never null) |
| 59 | */ | 49 | */ |
| 60 | -const Backend* GetBackendInstance(BackendType type); | 50 | +const Backend* GetBackend(); |
| 61 | 51 | ||
| 62 | // Backend op code generation function type | 52 | // Backend op code generation function type |
| 63 | using BackendCodegenFunc = std::function<std::string(const ir::CallPtr& op, codegen::CodegenBase& codegen)>; | 53 | using BackendCodegenFunc = std::function<std::string(const ir::CallPtr& op, codegen::CodegenBase& codegen)>; |
| @@ -202,7 +192,7 @@ public: | |||
| 202 | /** | 192 | /** |
| 203 | * \brief Get backend type name | 193 | * \brief Get backend type name |
| 204 | * | 194 | * |
| 205 | - * \return Backend type name (e.g., "910B_CCE") | 195 | + * \return Backend type name (e.g., "CCE") |
| 206 | */ | 196 | */ |
| 207 | [[nodiscard]] virtual std::string GetTypeName() const = 0; | 197 | [[nodiscard]] virtual std::string GetTypeName() const = 0; |
| 208 | 198 | ||
| @@ -1,105 +0,0 @@ | |||
| 1 | -/** | ||
| 2 | - * Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 3 | - * This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 4 | - * CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 5 | - * Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 6 | - * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 7 | - * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 8 | - * See LICENSE in the root of the software repository for the full text of the License. | ||
| 9 | - */ | ||
| 10 | - | ||
| 11 | -#ifndef PYPTO_BACKEND_COMMON_BACKEND_CONFIG_H_ | ||
| 12 | -#define PYPTO_BACKEND_COMMON_BACKEND_CONFIG_H_ | ||
| 13 | - | ||
| 14 | -#include <mutex> | ||
| 15 | -#include <optional> | ||
| 16 | - | ||
| 17 | -#include "backend/common/backend.h" | ||
| 18 | - | ||
| 19 | -namespace pypto { | ||
| 20 | -namespace backend { | ||
| 21 | - | ||
| 22 | -/*! | ||
| 23 | - * \brief Global backend configuration manager | ||
| 24 | - * | ||
| 25 | - * Manages the global backend type selection. The backend type must be | ||
| 26 | - * explicitly configured before use - there is no default value. | ||
| 27 | - * | ||
| 28 | - * Thread-safe singleton pattern with lazy initialization. | ||
| 29 | - */ | ||
| 30 | -class BackendConfig { | ||
| 31 | -public: | ||
| 32 | - /*! | ||
| 33 | - * \brief Set the global backend type | ||
| 34 | - * | ||
| 35 | - * Must be called before any backend operations. Can be called multiple | ||
| 36 | - * times with the same type (idempotent), but will throw an error if | ||
| 37 | - * attempting to change to a different type. | ||
| 38 | - * | ||
| 39 | - * \param type The backend type to use (CCE or PTO) | ||
| 40 | - * \throws pypto::ValueError if attempting to change an already-set type | ||
| 41 | - */ | ||
| 42 | - static void SetBackendType(BackendType type); | ||
| 43 | - | ||
| 44 | - /*! | ||
| 45 | - * \brief Get the configured backend instance | ||
| 46 | - * | ||
| 47 | - * Returns the backend instance corresponding to the configured type. | ||
| 48 | - * | ||
| 49 | - * \return Pointer to the backend instance (never null) | ||
| 50 | - * \throws pypto::ValueError if backend type has not been configured | ||
| 51 | - */ | ||
| 52 | - static const Backend* GetBackend(); | ||
| 53 | - | ||
| 54 | - /*! | ||
| 55 | - * \brief Get the configured backend type | ||
| 56 | - * | ||
| 57 | - * \return The configured backend type | ||
| 58 | - * \throws pypto::ValueError if backend type has not been configured | ||
| 59 | - */ | ||
| 60 | - static BackendType GetBackendType(); | ||
| 61 | - | ||
| 62 | - /*! | ||
| 63 | - * \brief Check if backend type has been configured | ||
| 64 | - * | ||
| 65 | - * \return true if SetBackendType() has been called, false otherwise | ||
| 66 | - */ | ||
| 67 | - static bool IsConfigured(); | ||
| 68 | - | ||
| 69 | - /*! | ||
| 70 | - * \brief Reset backend configuration (for testing only) | ||
| 71 | - * | ||
| 72 | - * WARNING: This function should ONLY be used in tests to reset the | ||
| 73 | - * backend configuration between test cases. Do NOT use in production code. | ||
| 74 | - */ | ||
| 75 | - static void ResetForTesting(); | ||
| 76 | - | ||
| 77 | -private: | ||
| 78 | - static std::optional<BackendType> backend_type_; | ||
| 79 | - static std::mutex mutex_; | ||
| 80 | -}; | ||
| 81 | - | ||
| 82 | -/*! | ||
| 83 | - * \brief Convenience function to get the configured backend | ||
| 84 | - * | ||
| 85 | - * Equivalent to BackendConfig::GetBackend() | ||
| 86 | - * | ||
| 87 | - * \return Pointer to the backend instance | ||
| 88 | - * \throws pypto::ValueError if backend type has not been configured | ||
| 89 | - */ | ||
| 90 | -inline const Backend* GetBackend() { return BackendConfig::GetBackend(); } | ||
| 91 | - | ||
| 92 | -/*! | ||
| 93 | - * \brief Convenience function to get the configured backend type | ||
| 94 | - * | ||
| 95 | - * Equivalent to BackendConfig::GetBackendType() | ||
| 96 | - * | ||
| 97 | - * \return The configured backend type | ||
| 98 | - * \throws pypto::ValueError if backend type has not been configured | ||
| 99 | - */ | ||
| 100 | -inline BackendType GetBackendType() { return BackendConfig::GetBackendType(); } | ||
| 101 | - | ||
| 102 | -} // namespace backend | ||
| 103 | -} // namespace pypto | ||
| 104 | - | ||
| 105 | -#endif // PYPTO_BACKEND_COMMON_BACKEND_CONFIG_H_ | ||
| @@ -41,7 +41,7 @@ public: | |||
| 41 | /** | 41 | /** |
| 42 | * \brief Register a backend type | 42 | * \brief Register a backend type |
| 43 | * | 43 | * |
| 44 | - * \param type_name Backend type name (e.g., "910B_CCE") | 44 | + * \param type_name Backend type name (e.g., "CCE") |
| 45 | * \param func Factory function that creates backend from SoC | 45 | * \param func Factory function that creates backend from SoC |
| 46 | */ | 46 | */ |
| 47 | void Register(const std::string& type_name, CreateFunc func); | 47 | void Register(const std::string& type_name, CreateFunc func); |
| @@ -49,7 +49,7 @@ public: | |||
| 49 | /** | 49 | /** |
| 50 | * \brief Create a backend instance (deprecated for singleton backends) | 50 | * \brief Create a backend instance (deprecated for singleton backends) |
| 51 | * | 51 | * |
| 52 | - * Backends are singletons; this always throws. Use Backend910B_CCE::Instance() instead. | 52 | + * Backends are singletons; this always throws. Use BackendCCE::Instance() instead. |
| 53 | * | 53 | * |
| 54 | * \param type_name Backend type name | 54 | * \param type_name Backend type name |
| 55 | * \param soc SoC structure (includes memory hierarchy) | 55 | * \param soc SoC structure (includes memory hierarchy) |
| @@ -73,7 +73,7 @@ private: | |||
| 73 | /** | 73 | /** |
| 74 | * \brief Create backend from registry (deprecated for singleton backends) | 74 | * \brief Create backend from registry (deprecated for singleton backends) |
| 75 | * | 75 | * |
| 76 | - * Backends are singletons; this always throws. Use Backend910B_CCE::Instance() instead. | 76 | + * Backends are singletons; this always throws. Use BackendCCE::Instance() instead. |
| 77 | * | 77 | * |
| 78 | * \param type_name Backend type name | 78 | * \param type_name Backend type name |
| 79 | * \param soc SoC structure (includes memory hierarchy) | 79 | * \param soc SoC structure (includes memory hierarchy) |
| @@ -235,15 +235,15 @@ private: | |||
| 235 | std::map<ir::MemorySpace, std::vector<ir::MemorySpace>> mem_graph_; | 235 | std::map<ir::MemorySpace, std::vector<ir::MemorySpace>> mem_graph_; |
| 236 | }; | 236 | }; |
| 237 | 237 | ||
| 238 | -/** | 238 | +/*! |
| 239 | - * \brief Create 910B SoC configuration (singleton) | 239 | + * \brief Create SoC configuration (singleton) |
| 240 | * | 240 | * |
| 241 | - * Returns a reference to the singleton 910B SoC instance. | 241 | + * Returns a reference to the singleton SoC instance. |
| 242 | * The instance is created on first call and persists for program lifetime. | 242 | * The instance is created on first call and persists for program lifetime. |
| 243 | * | 243 | * |
| 244 | - * \return Const reference to 910B SoC | 244 | + * \return Const reference to SoC |
| 245 | */ | 245 | */ |
| 246 | -const SoC& Create910BSoC(); | 246 | +const SoC& CreateSoC(); |
| 247 | 247 | ||
| 248 | } // namespace backend | 248 | } // namespace backend |
| 249 | } // namespace pypto | 249 | } // namespace pypto |
| @@ -58,7 +58,7 @@ struct TensorDef { | |||
| 58 | std::vector<ir::ExprPtr> access_shape; ///< access window shape (tile-derived) from load/store | 58 | std::vector<ir::ExprPtr> access_shape; ///< access window shape (tile-derived) from load/store |
| 59 | std::optional<ir::SectionKind> def_section; ///< nullopt = used outside any section (shared) | 59 | std::optional<ir::SectionKind> def_section; ///< nullopt = used outside any section (shared) |
| 60 | std::optional<std::vector<int>> tile_dims; ///< tile_dims kwarg for strided views (if any) | 60 | std::optional<std::vector<int>> tile_dims; ///< tile_dims kwarg for strided views (if any) |
| 61 | - bool is_dn = false; ///< loaded with layout="dn" (needs Layout::DN) | 61 | + bool is_transpose = false; ///< loaded with is_transpose=true (needs Layout::DN) |
| 62 | }; | 62 | }; |
| 63 | 63 | ||
| 64 | /** | 64 | /** |
| @@ -82,7 +82,7 @@ public: | |||
| 82 | /** | 82 | /** |
| 83 | * \brief Generate a single C++ file from a PyPTO IR Program (MIX mode) | 83 | * \brief Generate a single C++ file from a PyPTO IR Program (MIX mode) |
| 84 | * | 84 | * |
| 85 | - * Runs IR passes (LowerBreakContinue ->ConvertToSSA ->ConstFoldAndSimplify), | 85 | + * Runs the ConvertToSSA IR pass, |
| 86 | * then generates a single __global__ AICORE kernel with: | 86 | * then generates a single __global__ AICORE kernel with: |
| 87 | * - PTO-style function signature | 87 | * - PTO-style function signature |
| 88 | * - Section-aware tile declarations (#if __DAV_CUBE__ / __DAV_VEC__) | 88 | * - Section-aware tile declarations (#if __DAV_CUBE__ / __DAV_VEC__) |
| @@ -117,7 +117,9 @@ public: | |||
| 117 | /// Resolve a VF tile expr (plain tile or `tile[offset]`) to its `__ubuf__` pointer, typed as the | 117 | /// Resolve a VF tile expr (plain tile or `tile[offset]`) to its `__ubuf__` pointer, typed as the |
| 118 | /// tile element and hoisted before `__VEC_SCOPE__`. A `tile[offset]` load reuses the rvalue | 118 | /// tile element and hoisted before `__VEC_SCOPE__`. A `tile[offset]` load reuses the rvalue |
| 119 | /// `(vf_tile_ptr_N + off)`; otherwise a `vf_tile_ptr_N` is declared once and cached. With | 119 | /// `(vf_tile_ptr_N + off)`; otherwise a `vf_tile_ptr_N` is declared once and cached. With |
| 120 | - /// `is_post_update`, even a `tile[offset]` materialises a cursor the intrinsic advances in place. | 120 | + /// `is_post_update`, the access gets its own hoisted variable, kept separate from a plain base |
| 121 | + /// pointer to the same tile (e.g. a POST_UPDATE store cursor that must not alias a base load), | ||
| 122 | + /// and even a `tile[offset]` materialises a real lvalue var rather than the shared rvalue. | ||
| 121 | std::string GetOrCreateVFTilePtr(const ir::ExprPtr& expr, bool is_post_update = false); | 123 | std::string GetOrCreateVFTilePtr(const ir::ExprPtr& expr, bool is_post_update = false); |
| 122 | int64_t GetConstIntValue(const ir::ExprPtr& expr) override; | 124 | int64_t GetConstIntValue(const ir::ExprPtr& expr) override; |
| 123 | std::string GetVarName(const ir::VarPtr& var) override; | 125 | std::string GetVarName(const ir::VarPtr& var) override; |
| @@ -158,6 +160,27 @@ public: | |||
| 158 | tile_emit_shape_[tile_cpp_name] = {row_code, col_code}; | 160 | tile_emit_shape_[tile_cpp_name] = {row_code, col_code}; |
| 159 | } | 161 | } |
| 160 | 162 | ||
| 163 | + /** \brief Register a VF RegTensor variable (called from EmitVFRegTensor). */ | ||
| 164 | + void RegisterRegTensorVar(const std::string& cpp_name) { reg_tensor_vars_.insert(cpp_name); } | ||
| 165 | + | ||
| 166 | + /** \brief Push a RegTensor declaration to the hoisting buffer (emitted at __VEC_SCOPE__ top). */ | ||
| 167 | + void HoistRegTensorDecl(const std::string& decl) { vf_reg_hoisted_decls_.push_back(decl); } | ||
| 168 | + | ||
| 169 | + /** \brief Check if a C++ variable name was declared as a VF RegTensor. */ | ||
| 170 | + bool IsRegTensorVar(const std::string& cpp_name) const { return reg_tensor_vars_.count(cpp_name) > 0; } | ||
| 171 | + | ||
| 172 | + /** \brief Register a VF MaskReg variable (called from EmitVFCreateMask/Compare/etc). */ | ||
| 173 | + void RegisterMaskRegVar(const std::string& cpp_name) { mask_reg_vars_.insert(cpp_name); } | ||
| 174 | + | ||
| 175 | + /** \brief Check if a C++ variable name was declared as a VF MaskReg. */ | ||
| 176 | + bool IsMaskRegVar(const std::string& cpp_name) const { return mask_reg_vars_.count(cpp_name) > 0; } | ||
| 177 | + | ||
| 178 | + /** \brief Register a VF AddrReg variable (called from EmitVFCreateAddrReg). */ | ||
| 179 | + void RegisterAddrRegVar(const std::string& cpp_name) { addr_reg_vars_.insert(cpp_name); } | ||
| 180 | + | ||
| 181 | + /** \brief Check if a C++ variable name was declared as a VF AddrReg. */ | ||
| 182 | + bool IsAddrRegVar(const std::string& cpp_name) const { return addr_reg_vars_.count(cpp_name) > 0; } | ||
| 183 | + | ||
| 161 | /** \brief Look up the emit-time valid-shape for a tile (used by load and store). */ | 184 | /** \brief Look up the emit-time valid-shape for a tile (used by load and store). */ |
| 162 | std::optional<std::pair<std::string, std::string>> LookupTileEmitShape(const std::string& tile_cpp_name) const | 185 | std::optional<std::pair<std::string, std::string>> LookupTileEmitShape(const std::string& tile_cpp_name) const |
| 163 | { | 186 | { |
| @@ -175,6 +198,9 @@ public: | |||
| 175 | */ | 198 | */ |
| 176 | std::string ComputeIRBasedOffset(const ir::TensorTypePtr& tensor_type, const ir::MakeTuplePtr& offsets); | 199 | std::string ComputeIRBasedOffset(const ir::TensorTypePtr& tensor_type, const ir::MakeTuplePtr& offsets); |
| 177 | 200 | ||
| 201 | + const ir::Span& GetCurrentStmtSpan() const { return current_stmt_span_; } | ||
| 202 | + const ir::Span& GetCurrentExprSpan() const { return current_expr_span_; } | ||
| 203 | + | ||
| 178 | /** | 204 | /** |
| 179 | * \brief Register a tensor variable's underlying raw pointer (CCE-specific). | 205 | * \brief Register a tensor variable's underlying raw pointer (CCE-specific). |
| 180 | * | 206 | * |
| @@ -244,6 +270,12 @@ protected: | |||
| 244 | void VisitStmt_(const ir::IfStmtPtr& op) override; | 270 | void VisitStmt_(const ir::IfStmtPtr& op) override; |
| 245 | void VisitStmt_(const ir::YieldStmtPtr& op) override; | 271 | void VisitStmt_(const ir::YieldStmtPtr& op) override; |
| 246 | void VisitStmt_(const ir::SectionStmtPtr& op) override; | 272 | void VisitStmt_(const ir::SectionStmtPtr& op) override; |
| 273 | + void VisitStmt_(const ir::SeqStmtsPtr& op) override; | ||
| 274 | + void VisitStmt_(const ir::BreakStmtPtr& op) override; | ||
| 275 | + void VisitStmt_(const ir::ContinueStmtPtr& op) override; | ||
| 276 | + | ||
| 277 | + void VisitStmt(const ir::StmtPtr& stmt) override; | ||
| 278 | + void VisitExpr(const ir::ExprPtr& expr) override; | ||
| 247 | 279 | ||
| 248 | // Override visitor methods for code generation - Expressions | 280 | // Override visitor methods for code generation - Expressions |
| 249 | // Leaf nodes | 281 | // Leaf nodes |
| @@ -423,25 +455,46 @@ private: | |||
| 423 | // --- Phase 5: ForStmt helpers --- | 455 | // --- Phase 5: ForStmt helpers --- |
| 424 | 456 | ||
| 425 | /** | 457 | /** |
| 426 | - * \brief Register iteration arguments for a for-loop and emit their initialization. | 458 | + * \brief Register loop iteration arguments and emit their initialization. |
| 427 | * | 459 | * |
| 428 | * Handles alias propagation, cross-section safety, and pointer/struct inheritance. | 460 | * Handles alias propagation, cross-section safety, and pointer/struct inheritance. |
| 429 | * Returns the sanitized names of each iter-arg for later yield assignment. | 461 | * Returns the sanitized names of each iter-arg for later yield assignment. |
| 462 | + * Shared by ForStmt and WhileStmt. | ||
| 430 | */ | 463 | */ |
| 431 | - std::vector<std::string> RegisterForIterArgs(const ir::ForStmtPtr& op); | 464 | + std::vector<std::string> RegisterLoopIterArgs(const std::vector<ir::IterArgPtr>& iterArgs); |
| 432 | - void PropagateTupleIterArgs(const ir::ForStmtPtr& op); | 465 | + void PropagateTupleIterArgs(const std::vector<ir::IterArgPtr>& iterArgs, const std::vector<ir::VarPtr>& returnVars); |
| 433 | 466 | ||
| 434 | /** | 467 | /** |
| 435 | - * \brief Emit yield-to-iter-arg assignments at the end of a for-loop body. | 468 | + * \brief Emit yield-to-iter-arg assignments at the end of a loop body. |
| 436 | * | 469 | * |
| 437 | * Resolves aliases, detects self-assignments, and uses TASSIGN for tile transfers. | 470 | * Resolves aliases, detects self-assignments, and uses TASSIGN for tile transfers. |
| 438 | */ | 471 | */ |
| 439 | - void EmitForYieldAssignments(const std::vector<std::string>& iter_arg_names); | 472 | + void EmitForYieldAssignments(const std::vector<std::string>& iterArgNames); |
| 440 | - void RegisterForReturnVars(const ir::ForStmtPtr& op, const std::vector<std::string>& iter_arg_names); | ||
| 441 | 473 | ||
| 442 | - void EmitForLoopWithHoisting(const ir::ForStmtPtr& op, const std::string& loop_var_name, | 474 | + /// Emit `targets[i] = sources[i];` (or TASSIGN for tiles/tuples), skipping self-assignments. |
| 443 | - const std::vector<std::string>& iter_arg_names, const std::string& start, | 475 | + /// Shared by the trailing-yield write-back and native break/continue write-back. |
| 444 | - const std::string& stop, const std::string& step); | 476 | + void EmitCarriedAssignments(const std::vector<std::string>& targets, const std::vector<std::string>& sources); |
| 477 | + void RegisterLoopReturnVars(const std::vector<ir::VarPtr>& returnVars, | ||
| 478 | + const std::vector<std::string>& iterArgNames); | ||
| 479 | + | ||
| 480 | + /** | ||
| 481 | + * \brief Emit a C++ loop (for/while) with array-decl hoisting, shared by both loop kinds. | ||
| 482 | + * | ||
| 483 | + * The caller supplies the fully-formed loop header line ("for (...) {" or "while (...) {"); | ||
| 484 | + * everything else — hoisting scaffold, body emission, loop-carried write-back on the trailing | ||
| 485 | + * yield, and return-var registration — is identical. A native break/continue in the body | ||
| 486 | + * carries its own loop-carried values (BreakStmt::value_, populated by ConvertToSSA) and writes | ||
| 487 | + * them back via loop_target_stack_ before jumping. | ||
| 488 | + */ | ||
| 489 | + void EmitLoopWithHoisting(const std::string& header, const ir::StmtPtr& body, | ||
| 490 | + const std::vector<ir::IterArgPtr>& iterArgs, const std::vector<ir::VarPtr>& returnVars, | ||
| 491 | + const std::vector<std::string>& iterArgNames); | ||
| 492 | + | ||
| 493 | + // --- Native break/continue support --- | ||
| 494 | + | ||
| 495 | + /// Write a native jump's self-described carried values to the innermost loop's iter_args | ||
| 496 | + /// (loop_target_stack_.back()) before the jump skips the trailing yield. | ||
| 497 | + void EmitJumpCarriedWriteback(const std::vector<ir::ExprPtr>& values); | ||
| 445 | 498 | ||
| 446 | // --- Phase 6: GenerateSinglePrologue helpers --- | 499 | // --- Phase 6: GenerateSinglePrologue helpers --- |
| 447 | 500 | ||
| @@ -489,8 +542,7 @@ private: | |||
| 489 | 542 | ||
| 490 | void AppendDynamicStrideGlobalTensorArgs(std::ostringstream& global_instance, const std::string& shape_type_name, | 543 | void AppendDynamicStrideGlobalTensorArgs(std::ostringstream& global_instance, const std::string& shape_type_name, |
| 491 | const std::string& stride_type_name, const ir::TensorTypePtr& tensor_type, | 544 | const std::string& stride_type_name, const ir::TensorTypePtr& tensor_type, |
| 492 | - const std::vector<int64_t>& shape_dims, | 545 | + const std::optional<std::vector<int>>& tile_dims, bool is_transpose); |
| 493 | - const std::optional<std::vector<int>>& tile_dims, bool is_dn); | ||
| 494 | 546 | ||
| 495 | void EmitDynamicNZGlobalTensorDeclaration(const std::string& var_name, const ir::TensorTypePtr& tensor_type, | 547 | void EmitDynamicNZGlobalTensorDeclaration(const std::string& var_name, const ir::TensorTypePtr& tensor_type, |
| 496 | const std::optional<std::string>& base_pointer, | 548 | const std::optional<std::string>& base_pointer, |
| @@ -505,15 +557,15 @@ private: | |||
| 505 | const ir::TensorTypePtr& tensor_type); | 557 | const ir::TensorTypePtr& tensor_type); |
| 506 | 558 | ||
| 507 | std::string BuildGlobalTensorLayoutArg(const std::string& stride_type_name, const std::vector<int64_t>& shape_dims, | 559 | std::string BuildGlobalTensorLayoutArg(const std::string& stride_type_name, const std::vector<int64_t>& shape_dims, |
| 508 | - bool is_dn) const; | 560 | + bool is_transpose) const; |
| 509 | 561 | ||
| 510 | /** | 562 | /** |
| 511 | * \brief Emit the GlobalTensor instance declaration and register pointer/struct mappings. | 563 | * \brief Emit the GlobalTensor instance declaration and register pointer/struct mappings. |
| 512 | */ | 564 | */ |
| 513 | void EmitGlobalTensorInstance(const std::string& var_name, const std::string& global_type_name, | 565 | void EmitGlobalTensorInstance(const std::string& var_name, const std::string& global_type_name, |
| 514 | const std::string& shape_type_name, const std::string& stride_type_name, | 566 | const std::string& shape_type_name, const std::string& stride_type_name, |
| 515 | - const ir::TensorTypePtr& tensor_type, const std::vector<int64_t>& shape_dims, | 567 | + const ir::TensorTypePtr& tensor_type, |
| 516 | - const std::optional<std::vector<int>>& tile_dims, bool is_dn, | 568 | + const std::optional<std::vector<int>>& tile_dims, bool is_transpose, |
| 517 | const std::string& base_pointer); | 569 | const std::string& base_pointer); |
| 518 | 570 | ||
| 519 | /** | 571 | /** |
| @@ -548,8 +600,10 @@ private: | |||
| 548 | // Loop tile hoisting: declarations collected during loop body visit, emitted before outermost loop | 600 | // Loop tile hoisting: declarations collected during loop body visit, emitted before outermost loop |
| 549 | int loop_depth_ = 0; ///< Current for-loop nesting depth (0 = not in loop) | 601 | int loop_depth_ = 0; ///< Current for-loop nesting depth (0 = not in loop) |
| 550 | int if_depth_ = 0; ///< Current if-stmt nesting depth (0 = not in if) | 602 | int if_depth_ = 0; ///< Current if-stmt nesting depth (0 = not in if) |
| 551 | - std::map<std::string, std::string> | 603 | + std::map<std::pair<bool, std::string>, std::string> |
| 552 | - vf_tile_ptrs_; ///< VF tile expr code ->hoisted vf_tile_ptr_N var (base + POST_UPDATE cursor) | 604 | + vf_tile_ptrs_; ///< (is_post_update, VF tile expr code) -> hoisted vf_tile_ptr_N var. A dedicated var (e.g. a |
| 605 | + ///< POST_UPDATE store cursor) and a plain base pointer to the same tile are kept separate, so a | ||
| 606 | + ///< cursor store does not corrupt a base load of the same tile. | ||
| 553 | std::vector<std::string> loop_hoisted_decls_; ///< Lines to hoist before outermost loop/if | 607 | std::vector<std::string> loop_hoisted_decls_; ///< Lines to hoist before outermost loop/if |
| 554 | std::vector<std::string> section_hoisted_decls_; ///< VF section decls hoisted before __VEC_SCOPE__ (pre mem_bar) | 608 | std::vector<std::string> section_hoisted_decls_; ///< VF section decls hoisted before __VEC_SCOPE__ (pre mem_bar) |
| 555 | std::set<std::string> var_read_names_; ///< Var names read anywhere in the function body | 609 | std::set<std::string> var_read_names_; ///< Var names read anywhere in the function body |
| @@ -557,6 +611,11 @@ private: | |||
| 557 | std::map<int, std::set<ir::PipeType>> cube_mutex_pipes_; ///< buf_id ->pipes in Cube section | 611 | std::map<int, std::set<ir::PipeType>> cube_mutex_pipes_; ///< buf_id ->pipes in Cube section |
| 558 | std::map<int, std::set<ir::PipeType>> vec_mutex_pipes_; ///< buf_id ->pipes in Vec section | 612 | std::map<int, std::set<ir::PipeType>> vec_mutex_pipes_; ///< buf_id ->pipes in Vec section |
| 559 | 613 | ||
| 614 | + /// Per active loop: the write-back target C++ names (its iter_arg names), pushed while the loop | ||
| 615 | + /// body is emitted. A native break/continue assigns its self-described carried values | ||
| 616 | + /// (BreakStmt::value_) to loop_target_stack_.back() before jumping. Innermost loop = back(). | ||
| 617 | + std::vector<std::vector<std::string>> loop_target_stack_; | ||
| 618 | + | ||
| 560 | /** | 619 | /** |
| 561 | * \brief Pre-scan the IR for mutex_id ->pipe mappings. | 620 | * \brief Pre-scan the IR for mutex_id ->pipe mappings. |
| 562 | * | 621 | * |
| @@ -593,6 +652,18 @@ private: | |||
| 593 | /// Track emitted tile reference aliases to avoid C++ redefinition errors | 652 | /// Track emitted tile reference aliases to avoid C++ redefinition errors |
| 594 | std::set<std::string> emitted_tile_aliases_; | 653 | std::set<std::string> emitted_tile_aliases_; |
| 595 | 654 | ||
| 655 | + /// Track VF RegTensor variable names (C++ names set by EmitVFRegTensor) | ||
| 656 | + std::set<std::string> reg_tensor_vars_; | ||
| 657 | + | ||
| 658 | + /// RegTensor declarations to hoist to the top of __VEC_SCOPE__ (avoid loop-interior placement) | ||
| 659 | + std::vector<std::string> vf_reg_hoisted_decls_; | ||
| 660 | + | ||
| 661 | + /// Track VF MaskReg variable names (C++ names set by EmitVFCreateMask/Compare/etc) | ||
| 662 | + std::set<std::string> mask_reg_vars_; | ||
| 663 | + | ||
| 664 | + /// Track VF AddrReg variable names (C++ names set by EmitVFCreateAddrReg) | ||
| 665 | + std::set<std::string> addr_reg_vars_; | ||
| 666 | + | ||
| 596 | // Tuple Var C++ name -> the MakeTuple that was assigned to it. | 667 | // Tuple Var C++ name -> the MakeTuple that was assigned to it. |
| 597 | // Populated during body codegen by VisitStmt_(AssignStmtPtr) on tuple-typed lhs: | 668 | // Populated during body codegen by VisitStmt_(AssignStmtPtr) on tuple-typed lhs: |
| 598 | // VisitExpr(rhs) drives current_tuple_ through MakeTuple literals, tuple-var aliases, | 669 | // VisitExpr(rhs) drives current_tuple_ through MakeTuple literals, tuple-var aliases, |
| @@ -600,6 +671,11 @@ private: | |||
| 600 | // are propagated in VisitStmt_(ForStmtPtr). | 671 | // are propagated in VisitStmt_(ForStmtPtr). |
| 601 | std::map<std::string, ir::MakeTuplePtr> tuple_var_to_make_tuple_; | 672 | std::map<std::string, ir::MakeTuplePtr> tuple_var_to_make_tuple_; |
| 602 | 673 | ||
| 674 | + // Tuple variable names whose homogeneous MakeTuple assignment emitted a C++ | ||
| 675 | + // backing array. Tuple array identity is scoped to the assignment variable, | ||
| 676 | + // not the MakeTuple expression, which may be shared by multiple inline sites. | ||
| 677 | + std::set<std::string> tuple_vars_with_dyn_array_; | ||
| 678 | + | ||
| 603 | int dyn_arr_counter_ = 0; | 679 | int dyn_arr_counter_ = 0; |
| 604 | 680 | ||
| 605 | /** | 681 | /** |
| @@ -627,21 +703,10 @@ private: | |||
| 627 | /// Emit-time valid-shape map: tile C++ name -> (row code, col code). | 703 | /// Emit-time valid-shape map: tile C++ name -> (row code, col code). |
| 628 | /// Populated when set_validshape is emitted; consumed by the following load or store. | 704 | /// Populated when set_validshape is emitted; consumed by the following load or store. |
| 629 | std::map<std::string, std::pair<std::string, std::string>> tile_emit_shape_; | 705 | std::map<std::string, std::pair<std::string, std::string>> tile_emit_shape_; |
| 630 | -}; | ||
| 631 | 706 | ||
| 632 | -/** | 707 | + ir::Span current_stmt_span_; |
| 633 | - * \brief Inline all HELPER function calls into the kernel function. | 708 | + ir::Span current_expr_span_; |
| 634 | - * | 709 | +}; |
| 635 | - * Walks the kernel body and replaces every Call whose op name matches | ||
| 636 | - * a HELPER function with the helper's body (variables renamed with | ||
| 637 | - * a unique per-call-site prefix, parameters substituted with call-site args, | ||
| 638 | - * ReturnStmt converted to assignment). Returns a new Program containing | ||
| 639 | - * only the inlined kernel (if present) -- helpers are | ||
| 640 | - * removed. | ||
| 641 | - * | ||
| 642 | - * If the program has no helpers, returns it unchanged. | ||
| 643 | - */ | ||
| 644 | -ir::ProgramPtr InlineHelperCalls(const ir::ProgramPtr& program); | ||
| 645 | 710 | ||
| 646 | } // namespace codegen | 711 | } // namespace codegen |
| 647 | } // namespace pypto | 712 | } // namespace pypto |
| @@ -24,6 +24,7 @@ | |||
| 24 | #include "ir/expr.h" | 24 | #include "ir/expr.h" |
| 25 | #include "ir/function.h" | 25 | #include "ir/function.h" |
| 26 | #include "ir/program.h" | 26 | #include "ir/program.h" |
| 27 | +#include "ir/scalar_expr_ops.h" | ||
| 27 | #include "ir/span.h" | 28 | #include "ir/span.h" |
| 28 | #include "ir/stmt.h" | 29 | #include "ir/stmt.h" |
| 29 | #include "ir/type.h" | 30 | #include "ir/type.h" |
| @@ -49,6 +50,77 @@ Span MakeCombinedSpan(const Span& begin_span, const Span& end_span) | |||
| 49 | end_span.EndColumn()); | 50 | end_span.EndColumn()); |
| 50 | } | 51 | } |
| 51 | 52 | ||
| 53 | +/** | ||
| 54 | + * \brief Reconcile the branch value types of an if statement's SSA return vars. | ||
| 55 | + * | ||
| 56 | + * A ternary expression ``a if cond else b`` lowers to an if statement whose then/else | ||
| 57 | + * branches each yield their value into a phi return var. When the two branches produce | ||
| 58 | + * differing but same-category scalar dtypes (e.g. ``INT32`` from a tensor read vs | ||
| 59 | + * ``INDEX`` from a shape access), promote both yielded values to the wider dtype and | ||
| 60 | + * retype the phi return var to match, mirroring the promotion binary operators already | ||
| 61 | + * perform. Non-scalar or cross-category (int vs float) mismatches are left untouched so | ||
| 62 | + * the type verifier still reports them. | ||
| 63 | + * | ||
| 64 | + * \param then_stmts Statements of the then branch (last one is the YieldStmt); mutated in place. | ||
| 65 | + * \param else_stmts Statements of the else branch (last one is the YieldStmt); mutated in place. | ||
| 66 | + * \param return_vars Phi return vars; retyped in place when a branch pair is promoted. | ||
| 67 | + */ | ||
| 68 | +void ReconcileIfReturnVarTypes(std::vector<StmtPtr>& then_stmts, std::vector<StmtPtr>& else_stmts, | ||
| 69 | + std::vector<VarPtr>& return_vars) | ||
| 70 | +{ | ||
| 71 | + if (return_vars.empty() || then_stmts.empty() || else_stmts.empty()) { | ||
| 72 | + return; | ||
| 73 | + } | ||
| 74 | + auto then_yield = std::dynamic_pointer_cast<const YieldStmt>(then_stmts.back()); | ||
| 75 | + auto else_yield = std::dynamic_pointer_cast<const YieldStmt>(else_stmts.back()); | ||
| 76 | + if (!then_yield || !else_yield) { | ||
| 77 | + return; | ||
| 78 | + } | ||
| 79 | + const size_t count = return_vars.size(); | ||
| 80 | + if (then_yield->value_.size() != count || else_yield->value_.size() != count) { | ||
| 81 | + return; | ||
| 82 | + } | ||
| 83 | + | ||
| 84 | + std::vector<ExprPtr> then_values = then_yield->value_; | ||
| 85 | + std::vector<ExprPtr> else_values = else_yield->value_; | ||
| 86 | + bool changed = false; | ||
| 87 | + for (size_t i = 0; i < count; ++i) { | ||
| 88 | + const ExprPtr& then_value = then_values[i]; | ||
| 89 | + const ExprPtr& else_value = else_values[i]; | ||
| 90 | + if (!then_value || !else_value) { | ||
| 91 | + continue; | ||
| 92 | + } | ||
| 93 | + auto then_scalar = std::dynamic_pointer_cast<const ScalarType>(then_value->GetType()); | ||
| 94 | + auto else_scalar = std::dynamic_pointer_cast<const ScalarType>(else_value->GetType()); | ||
| 95 | + if (!then_scalar || !else_scalar) { | ||
| 96 | + continue; | ||
| 97 | + } | ||
| 98 | + DataType then_dtype = then_scalar->dtype_; | ||
| 99 | + DataType else_dtype = else_scalar->dtype_; | ||
| 100 | + if (then_dtype == else_dtype) { | ||
| 101 | + continue; | ||
| 102 | + } | ||
| 103 | + // Only reconcile a matching numeric category (both int or both float); bool and | ||
| 104 | + // int/float mismatches stay errors for the verifier to surface. | ||
| 105 | + bool both_int = then_dtype.IsInt() && else_dtype.IsInt(); | ||
| 106 | + bool both_float = then_dtype.IsFloat() && else_dtype.IsFloat(); | ||
| 107 | + if (!both_int && !both_float) { | ||
| 108 | + continue; | ||
| 109 | + } | ||
| 110 | + DataType promoted = PromoteSameCategoryDtype(then_dtype, else_dtype, "ternary", return_vars[i]->span_); | ||
| 111 | + then_values[i] = MaybeCast(then_value, promoted, then_yield->span_); | ||
| 112 | + else_values[i] = MaybeCast(else_value, promoted, else_yield->span_); | ||
| 113 | + return_vars[i] = std::make_shared<Var>(return_vars[i]->name_, std::make_shared<ScalarType>(promoted), | ||
| 114 | + return_vars[i]->span_); | ||
| 115 | + changed = true; | ||
| 116 | + } | ||
| 117 | + if (!changed) { | ||
| 118 | + return; | ||
| 119 | + } | ||
| 120 | + then_stmts.back() = std::make_shared<YieldStmt>(std::move(then_values), then_yield->span_); | ||
| 121 | + else_stmts.back() = std::make_shared<YieldStmt>(std::move(else_values), else_yield->span_); | ||
| 122 | +} | ||
| 123 | + | ||
| 52 | std::string MakeLoopReturnVarsMismatchMessage(const char* loop_kind, size_t iter_arg_count, size_t return_var_count) | 124 | std::string MakeLoopReturnVarsMismatchMessage(const char* loop_kind, size_t iter_arg_count, size_t return_var_count) |
| 53 | { | 125 | { |
| 54 | std::ostringstream oss; | 126 | std::ostringstream oss; |
| @@ -274,36 +346,30 @@ StmtPtr IRBuilder::EndIf(const Span& end_span) | |||
| 274 | 346 | ||
| 275 | auto* if_ctx = static_cast<IfStmtContext*>(CurrentContext()); | 347 | auto* if_ctx = static_cast<IfStmtContext*>(CurrentContext()); |
| 276 | 348 | ||
| 277 | - // Build then body | 349 | + std::vector<StmtPtr> then_stmts = if_ctx->GetStmts(); |
| 278 | - StmtPtr then_body; | 350 | + std::vector<StmtPtr> else_stmts = if_ctx->GetElseStmts(); |
| 279 | - const auto& then_stmts = if_ctx->GetStmts(); | 351 | + std::vector<VarPtr> return_vars = if_ctx->GetReturnVars(); |
| 280 | - if (then_stmts.empty()) { | 352 | + |
| 281 | - then_body = std::make_shared<SeqStmts>(std::vector<StmtPtr>(), end_span); | 353 | + // Promote differing but same-category scalar branch types (e.g. ``a if c else b`` |
| 282 | - } else if (then_stmts.size() == 1) { | 354 | + // yielding INT32 vs INDEX) to a common dtype before building the phi. |
| 283 | - then_body = then_stmts[0]; | 355 | + if (if_ctx->InElseBranch()) { |
| 284 | - } else { | 356 | + ReconcileIfReturnVarTypes(then_stmts, else_stmts, return_vars); |
| 285 | - then_body = std::make_shared<SeqStmts>(then_stmts, end_span); | ||
| 286 | } | 357 | } |
| 287 | 358 | ||
| 359 | + // Build then body | ||
| 360 | + StmtPtr then_body = MakeStmtBody(then_stmts, end_span); | ||
| 361 | + | ||
| 288 | // Build else body (optional) | 362 | // Build else body (optional) |
| 289 | std::optional<StmtPtr> else_body; | 363 | std::optional<StmtPtr> else_body; |
| 290 | - if (if_ctx->InElseBranch()) { | 364 | + if (if_ctx->InElseBranch() && !else_stmts.empty()) { |
| 291 | - const auto& else_stmts = if_ctx->GetElseStmts(); | 365 | + else_body = MakeStmtBody(else_stmts, end_span); |
| 292 | - if (!else_stmts.empty()) { | ||
| 293 | - if (else_stmts.size() == 1) { | ||
| 294 | - else_body = else_stmts[0]; | ||
| 295 | - } else { | ||
| 296 | - else_body = std::make_shared<SeqStmts>(else_stmts, end_span); | ||
| 297 | - } | ||
| 298 | - } | ||
| 299 | } | 366 | } |
| 300 | 367 | ||
| 301 | // Combine begin and end spans | 368 | // Combine begin and end spans |
| 302 | auto combinedSpan = MakeCombinedSpan(if_ctx->GetBeginSpan(), end_span); | 369 | auto combinedSpan = MakeCombinedSpan(if_ctx->GetBeginSpan(), end_span); |
| 303 | 370 | ||
| 304 | // Create if statement | 371 | // Create if statement |
| 305 | - auto if_stmt = std::make_shared<IfStmt>(if_ctx->GetCondition(), then_body, else_body, if_ctx->GetReturnVars(), | 372 | + auto if_stmt = std::make_shared<IfStmt>(if_ctx->GetCondition(), then_body, else_body, return_vars, combinedSpan); |
| 306 | - combinedSpan); | ||
| 307 | // Pop context | 373 | // Pop context |
| 308 | context_stack_.pop_back(); | 374 | context_stack_.pop_back(); |
| 309 | 375 | ||
| @@ -212,6 +212,17 @@ REGISTER_OP("get_subblock_idx") | |||
| 212 | return DeduceBlockGetBlockIdxType(args, kwargs, "get_subblock_idx"); | 212 | return DeduceBlockGetBlockIdxType(args, kwargs, "get_subblock_idx"); |
| 213 | }); | 213 | }); |
| 214 | 214 | ||
| 215 | +REGISTER_OP("get_spr") | ||
| 216 | + .set_op_category("LanguageOp") | ||
| 217 | + .set_description("Read special purpose register value (get_ar instruction). " | ||
| 218 | + "Currently only AR register is supported.") | ||
| 219 | + .no_argument() | ||
| 220 | + .f_deduce_type([]([[maybe_unused]] const std::vector<ExprPtr>& args, | ||
| 221 | + [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs) { | ||
| 222 | + CHECK(args.size() == 0) << "get_spr requires no arguments"; | ||
| 223 | + return std::make_shared<ScalarType>(DataType::INT64); | ||
| 224 | + }); | ||
| 225 | + | ||
| 215 | REGISTER_OP("block.make_tile") | 226 | REGISTER_OP("block.make_tile") |
| 216 | .set_op_category("BlockOp") | 227 | .set_op_category("BlockOp") |
| 217 | .set_description("Create a tile") | 228 | .set_description("Create a tile") |
| @@ -51,8 +51,13 @@ TypePtr DeduceVFScalarType([[maybe_unused]] const std::vector<ExprPtr>& args, | |||
| 51 | } | 51 | } |
| 52 | 52 | ||
| 53 | TypePtr DeduceVFMaskType([[maybe_unused]] const std::vector<ExprPtr>& args, | 53 | TypePtr DeduceVFMaskType([[maybe_unused]] const std::vector<ExprPtr>& args, |
| 54 | - [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs) | 54 | + const std::vector<std::pair<std::string, std::any>>& kwargs) |
| 55 | { | 55 | { |
| 56 | + for (const auto& [key, value] : kwargs) { | ||
| 57 | + if (key == "dtype") { | ||
| 58 | + return std::make_shared<ScalarType>(AnyCast<DataType>(value, "kwarg: dtype")); | ||
| 59 | + } | ||
| 60 | + } | ||
| 56 | return std::make_shared<ScalarType>(DataType::UINT16); | 61 | return std::make_shared<ScalarType>(DataType::UINT16); |
| 57 | } | 62 | } |
| 58 | 63 | ||
| @@ -74,6 +79,13 @@ REGISTER_OP("vf.reg_tensor") | |||
| 74 | .set_attr<DataType>("dtype") | 79 | .set_attr<DataType>("dtype") |
| 75 | .f_deduce_type(DeduceVFScalarType); | 80 | .f_deduce_type(DeduceVFScalarType); |
| 76 | 81 | ||
| 82 | +REGISTER_OP("vf.mask_reg") | ||
| 83 | + .set_op_category("VFOp") | ||
| 84 | + .set_description("Declare a mask register (without initialization)") | ||
| 85 | + .no_argument() | ||
| 86 | + .set_attr<DataType>("dtype") | ||
| 87 | + .f_deduce_type(DeduceVFMaskType); | ||
| 88 | + | ||
| 77 | // Mask | 89 | // Mask |
| 78 | REGISTER_OP("vf.create_mask") | 90 | REGISTER_OP("vf.create_mask") |
| 79 | .set_op_category("VFOp") | 91 | .set_op_category("VFOp") |
| @@ -531,7 +543,6 @@ REGISTER_OP("vf.exp_sub") | |||
| 531 | .add_argument("src", "Source register") | 543 | .add_argument("src", "Source register") |
| 532 | .add_argument("max", "Max register") | 544 | .add_argument("max", "Max register") |
| 533 | .add_argument("mask", "Mask register") | 545 | .add_argument("mask", "Mask register") |
| 534 | - .set_attr<int>("mode") | ||
| 535 | .set_attr<int>("layout") | 546 | .set_attr<int>("layout") |
| 536 | .f_deduce_type(DeduceVFFromDstArg); | 547 | .f_deduce_type(DeduceVFFromDstArg); |
| 537 | 548 | ||
| @@ -544,7 +555,6 @@ REGISTER_OP("vf.astype") | |||
| 544 | .set_attr<int>("layout") | 555 | .set_attr<int>("layout") |
| 545 | .set_attr<int>("round_mode") | 556 | .set_attr<int>("round_mode") |
| 546 | .set_attr<int>("saturate") | 557 | .set_attr<int>("saturate") |
| 547 | - .set_attr<int>("part") | ||
| 548 | .f_deduce_type(DeduceVFFromDstArg); | 558 | .f_deduce_type(DeduceVFFromDstArg); |
| 549 | 559 | ||
| 550 | REGISTER_OP("vf.de_interleave") | 560 | REGISTER_OP("vf.de_interleave") |
| @@ -588,79 +598,66 @@ REGISTER_OP("vf.histograms") | |||
| 588 | .add_argument("mask", "Mask register") | 598 | .add_argument("mask", "Mask register") |
| 589 | .set_attr<int>("bin_type") | 599 | .set_attr<int>("bin_type") |
| 590 | .set_attr<int>("hist_type") | 600 | .set_attr<int>("hist_type") |
| 591 | - .set_attr<int>("mode") | ||
| 592 | .f_deduce_type(DeduceVFFromDstArg); | 601 | .f_deduce_type(DeduceVFFromDstArg); |
| 593 | REGISTER_OP("vf.eq") | 602 | REGISTER_OP("vf.eq") |
| 594 | .set_op_category("VFOp") | 603 | .set_op_category("VFOp") |
| 595 | .set_description("Equality compare and generate mask") | 604 | .set_description("Equality compare and generate mask") |
| 605 | + .add_argument("dst", "Destination mask register") | ||
| 596 | .add_argument("src0", "First source register") | 606 | .add_argument("src0", "First source register") |
| 597 | .add_argument("src1", "Second source register") | 607 | .add_argument("src1", "Second source register") |
| 598 | .add_argument("mask_src", "Source mask register") | 608 | .add_argument("mask_src", "Source mask register") |
| 599 | .set_attr<DataType>("cmp_dtype") | 609 | .set_attr<DataType>("cmp_dtype") |
| 600 | - .f_deduce_type([]([[maybe_unused]] const std::vector<ExprPtr>& args, | 610 | + .f_deduce_type(DeduceVFMaskType); |
| 601 | - [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs) -> TypePtr { | ||
| 602 | - return std::make_shared<ScalarType>(DataType::UINT16); | ||
| 603 | - }); | ||
| 604 | 611 | ||
| 605 | REGISTER_OP("vf.ne") | 612 | REGISTER_OP("vf.ne") |
| 606 | .set_op_category("VFOp") | 613 | .set_op_category("VFOp") |
| 607 | .set_description("Not-equal compare and generate mask") | 614 | .set_description("Not-equal compare and generate mask") |
| 615 | + .add_argument("dst", "Destination mask register") | ||
| 608 | .add_argument("src0", "First source register") | 616 | .add_argument("src0", "First source register") |
| 609 | .add_argument("src1", "Second source register") | 617 | .add_argument("src1", "Second source register") |
| 610 | .add_argument("mask_src", "Source mask register") | 618 | .add_argument("mask_src", "Source mask register") |
| 611 | .set_attr<DataType>("cmp_dtype") | 619 | .set_attr<DataType>("cmp_dtype") |
| 612 | - .f_deduce_type([]([[maybe_unused]] const std::vector<ExprPtr>& args, | 620 | + .f_deduce_type(DeduceVFMaskType); |
| 613 | - [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs) -> TypePtr { | ||
| 614 | - return std::make_shared<ScalarType>(DataType::UINT16); | ||
| 615 | - }); | ||
| 616 | 621 | ||
| 617 | REGISTER_OP("vf.lt") | 622 | REGISTER_OP("vf.lt") |
| 618 | .set_op_category("VFOp") | 623 | .set_op_category("VFOp") |
| 619 | .set_description("Less-than compare and generate mask") | 624 | .set_description("Less-than compare and generate mask") |
| 625 | + .add_argument("dst", "Destination mask register") | ||
| 620 | .add_argument("src0", "First source register") | 626 | .add_argument("src0", "First source register") |
| 621 | .add_argument("src1", "Second source register") | 627 | .add_argument("src1", "Second source register") |
| 622 | .add_argument("mask_src", "Source mask register") | 628 | .add_argument("mask_src", "Source mask register") |
| 623 | .set_attr<DataType>("cmp_dtype") | 629 | .set_attr<DataType>("cmp_dtype") |
| 624 | - .f_deduce_type([]([[maybe_unused]] const std::vector<ExprPtr>& args, | 630 | + .f_deduce_type(DeduceVFMaskType); |
| 625 | - [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs) -> TypePtr { | ||
| 626 | - return std::make_shared<ScalarType>(DataType::UINT16); | ||
| 627 | - }); | ||
| 628 | 631 | ||
| 629 | REGISTER_OP("vf.gt") | 632 | REGISTER_OP("vf.gt") |
| 630 | .set_op_category("VFOp") | 633 | .set_op_category("VFOp") |
| 631 | .set_description("Greater-than compare and generate mask") | 634 | .set_description("Greater-than compare and generate mask") |
| 635 | + .add_argument("dst", "Destination mask register") | ||
| 632 | .add_argument("src0", "First source register") | 636 | .add_argument("src0", "First source register") |
| 633 | .add_argument("src1", "Second source register") | 637 | .add_argument("src1", "Second source register") |
| 634 | .add_argument("mask_src", "Source mask register") | 638 | .add_argument("mask_src", "Source mask register") |
| 635 | .set_attr<DataType>("cmp_dtype") | 639 | .set_attr<DataType>("cmp_dtype") |
| 636 | - .f_deduce_type([]([[maybe_unused]] const std::vector<ExprPtr>& args, | 640 | + .f_deduce_type(DeduceVFMaskType); |
| 637 | - [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs) -> TypePtr { | ||
| 638 | - return std::make_shared<ScalarType>(DataType::UINT16); | ||
| 639 | - }); | ||
| 640 | 641 | ||
| 641 | REGISTER_OP("vf.le") | 642 | REGISTER_OP("vf.le") |
| 642 | .set_op_category("VFOp") | 643 | .set_op_category("VFOp") |
| 643 | .set_description("Less-or-equal compare and generate mask") | 644 | .set_description("Less-or-equal compare and generate mask") |
| 645 | + .add_argument("dst", "Destination mask register") | ||
| 644 | .add_argument("src0", "First source register") | 646 | .add_argument("src0", "First source register") |
| 645 | .add_argument("src1", "Second source register") | 647 | .add_argument("src1", "Second source register") |
| 646 | .add_argument("mask_src", "Source mask register") | 648 | .add_argument("mask_src", "Source mask register") |
| 647 | .set_attr<DataType>("cmp_dtype") | 649 | .set_attr<DataType>("cmp_dtype") |
| 648 | - .f_deduce_type([]([[maybe_unused]] const std::vector<ExprPtr>& args, | 650 | + .f_deduce_type(DeduceVFMaskType); |
| 649 | - [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs) -> TypePtr { | ||
| 650 | - return std::make_shared<ScalarType>(DataType::UINT16); | ||
| 651 | - }); | ||
| 652 | 651 | ||
| 653 | REGISTER_OP("vf.ge") | 652 | REGISTER_OP("vf.ge") |
| 654 | .set_op_category("VFOp") | 653 | .set_op_category("VFOp") |
| 655 | .set_description("Greater-or-equal compare and generate mask") | 654 | .set_description("Greater-or-equal compare and generate mask") |
| 655 | + .add_argument("dst", "Destination mask register") | ||
| 656 | .add_argument("src0", "First source register") | 656 | .add_argument("src0", "First source register") |
| 657 | .add_argument("src1", "Second source register") | 657 | .add_argument("src1", "Second source register") |
| 658 | .add_argument("mask_src", "Source mask register") | 658 | .add_argument("mask_src", "Source mask register") |
| 659 | .set_attr<DataType>("cmp_dtype") | 659 | .set_attr<DataType>("cmp_dtype") |
| 660 | - .f_deduce_type([]([[maybe_unused]] const std::vector<ExprPtr>& args, | 660 | + .f_deduce_type(DeduceVFMaskType); |
| 661 | - [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs) -> TypePtr { | ||
| 662 | - return std::make_shared<ScalarType>(DataType::UINT16); | ||
| 663 | - }); | ||
| 664 | REGISTER_OP("vf.squeeze") | 661 | REGISTER_OP("vf.squeeze") |
| 665 | 662 | ||
| 666 | .set_op_category("VFOp") | 663 | .set_op_category("VFOp") |
| @@ -668,7 +665,6 @@ REGISTER_OP("vf.squeeze") | |||
| 668 | .add_argument("dst", "Destination register") | 665 | .add_argument("dst", "Destination register") |
| 669 | .add_argument("src", "Source register") | 666 | .add_argument("src", "Source register") |
| 670 | .add_argument("mask", "Mask register") | 667 | .add_argument("mask", "Mask register") |
| 671 | - .set_attr<int>("mode") | ||
| 672 | .set_attr<int>("gather_mode") | 668 | .set_attr<int>("gather_mode") |
| 673 | .f_deduce_type(DeduceVFFromDstArg); | 669 | .f_deduce_type(DeduceVFFromDstArg); |
| 674 | 670 | ||
| @@ -686,7 +682,6 @@ REGISTER_OP("vf.gather") | |||
| 686 | .add_argument("src_ub", "Source UB pointer") | 682 | .add_argument("src_ub", "Source UB pointer") |
| 687 | .add_argument("indices", "Index register") | 683 | .add_argument("indices", "Index register") |
| 688 | .add_argument("mask", "Mask register") | 684 | .add_argument("mask", "Mask register") |
| 689 | - .set_attr<int>("gather_mode") | ||
| 690 | .set_attr<int>("data_copy_mode") | 685 | .set_attr<int>("data_copy_mode") |
| 691 | .f_deduce_type(DeduceVFFromDstArg); | 686 | .f_deduce_type(DeduceVFFromDstArg); |
| 692 | 687 | ||
| @@ -971,12 +966,5 @@ REGISTER_OP("vf.move") | |||
| 971 | .set_attr<int>("mode") | 966 | .set_attr<int>("mode") |
| 972 | .f_deduce_type(DeduceVFFromDstArg); | 967 | .f_deduce_type(DeduceVFFromDstArg); |
| 973 | 968 | ||
| 974 | -REGISTER_OP("vf.get_spr") | ||
| 975 | - .set_op_category("VFOp") | ||
| 976 | - .set_description("Read special purpose register value (get_ar instruction). " | ||
| 977 | - "Currently only AR register is supported.") | ||
| 978 | - .set_attr<int>("spr") | ||
| 979 | - .f_deduce_type(DeduceVFUnknownType); | ||
| 980 | - | ||
| 981 | } // namespace ir | 969 | } // namespace ir |
| 982 | } // namespace pypto | 970 | } // namespace pypto |
| @@ -1,413 +0,0 @@ | |||
| 1 | -/** | ||
| 2 | - * Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 3 | - * This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 4 | - * CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 5 | - * Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 6 | - * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 7 | - * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 8 | - * See LICENSE in the root of the software repository for the full text of the License. | ||
| 9 | - */ | ||
| 10 | - | ||
| 11 | -#include <cstdint> | ||
| 12 | -#include <memory> | ||
| 13 | -#include <optional> | ||
| 14 | -#include <string> | ||
| 15 | -#include <unordered_map> | ||
| 16 | -#include <utility> | ||
| 17 | -#include <vector> | ||
| 18 | - | ||
| 19 | -#include "ir/expr.h" | ||
| 20 | -#include "ir/function.h" | ||
| 21 | -#include "ir/kind_traits.h" | ||
| 22 | -#include "ir/scalar_expr.h" | ||
| 23 | -#include "ir/span.h" | ||
| 24 | -#include "ir/stmt.h" | ||
| 25 | -#include "ir/transforms/base/mutator.h" | ||
| 26 | -#include "ir/transforms/passes.h" | ||
| 27 | -#include "ir/type.h" | ||
| 28 | - | ||
| 29 | -namespace pypto { | ||
| 30 | -namespace ir { | ||
| 31 | - | ||
| 32 | -// --------------------------------------------------------------------------- | ||
| 33 | -// Helper: try to extract compile-time integer value from an Expr | ||
| 34 | -// --------------------------------------------------------------------------- | ||
| 35 | -static std::optional<int64_t> TryGetConstInt(const ExprPtr& expr) | ||
| 36 | -{ | ||
| 37 | - if (!expr) | ||
| 38 | - return std::nullopt; | ||
| 39 | - if (auto ci = As<ConstInt>(expr)) | ||
| 40 | - return ci->value_; | ||
| 41 | - return std::nullopt; | ||
| 42 | -} | ||
| 43 | - | ||
| 44 | -static DataType GetDType(const ExprPtr& expr) | ||
| 45 | -{ | ||
| 46 | - if (auto st = As<ScalarType>(expr->GetType())) | ||
| 47 | - return st->dtype_; | ||
| 48 | - return DataType::INDEX; | ||
| 49 | -} | ||
| 50 | - | ||
| 51 | -// --------------------------------------------------------------------------- | ||
| 52 | -// Helper: resolve Var through a value map to find the underlying ConstInt | ||
| 53 | -// --------------------------------------------------------------------------- | ||
| 54 | -static std::optional<int64_t> ResolveToConst(const ExprPtr& expr, | ||
| 55 | - const std::unordered_map<std::string, ExprPtr>& var_vals) | ||
| 56 | -{ | ||
| 57 | - if (!expr) | ||
| 58 | - return std::nullopt; | ||
| 59 | - if (auto ci = As<ConstInt>(expr)) | ||
| 60 | - return ci->value_; | ||
| 61 | - if (auto cb = As<ConstBool>(expr)) | ||
| 62 | - return cb->value_ ? 1 : 0; | ||
| 63 | - if (auto v = As<Var>(expr)) { | ||
| 64 | - auto it = var_vals.find(v->name_); | ||
| 65 | - if (it != var_vals.end()) | ||
| 66 | - return ResolveToConst(it->second, var_vals); | ||
| 67 | - } | ||
| 68 | - // Resolve tuple-flavored GetItemExpr → MakeTuple element | ||
| 69 | - if (auto gi = As<GetItemExpr>(expr); gi && As<TupleType>(gi->value_->GetType())) { | ||
| 70 | - auto const_idx = As<ConstInt>(gi->slice_); | ||
| 71 | - if (!const_idx) | ||
| 72 | - return std::nullopt; | ||
| 73 | - ExprPtr tuple_expr = gi->value_; | ||
| 74 | - if (auto tv = As<Var>(tuple_expr)) { | ||
| 75 | - auto it = var_vals.find(tv->name_); | ||
| 76 | - if (it != var_vals.end()) | ||
| 77 | - tuple_expr = it->second; | ||
| 78 | - } | ||
| 79 | - if (auto mt = As<MakeTuple>(tuple_expr)) { | ||
| 80 | - int idx = static_cast<int>(const_idx->value_); | ||
| 81 | - if (idx >= 0 && idx < static_cast<int>(mt->elements_.size())) { | ||
| 82 | - return ResolveToConst(mt->elements_[idx], var_vals); | ||
| 83 | - } | ||
| 84 | - } | ||
| 85 | - } | ||
| 86 | - return std::nullopt; | ||
| 87 | -} | ||
| 88 | - | ||
| 89 | -static bool IsSameExpr(const ExprPtr& a, const ExprPtr& b, | ||
| 90 | - const std::unordered_map<std::string, ExprPtr>& var_vals = {}) | ||
| 91 | -{ | ||
| 92 | - if (!a || !b) | ||
| 93 | - return false; | ||
| 94 | - if (a.get() == b.get()) | ||
| 95 | - return true; | ||
| 96 | - // Resolve through value map | ||
| 97 | - auto av = ResolveToConst(a, var_vals); | ||
| 98 | - auto bv = ResolveToConst(b, var_vals); | ||
| 99 | - if (av && bv) | ||
| 100 | - return *av == *bv; | ||
| 101 | - // Both Var with same name | ||
| 102 | - auto va = As<Var>(a); | ||
| 103 | - auto vb = As<Var>(b); | ||
| 104 | - if (va && vb) | ||
| 105 | - return va->name_ == vb->name_; | ||
| 106 | - return false; | ||
| 107 | -} | ||
| 108 | - | ||
| 109 | -// --------------------------------------------------------------------------- | ||
| 110 | -// ConstFoldMutator — IRMutator subclass that folds constants and simplifies ifs | ||
| 111 | -// --------------------------------------------------------------------------- | ||
| 112 | -class ConstFoldMutator : public IRMutator { | ||
| 113 | -public: | ||
| 114 | - using IRMutator::VisitExpr_; | ||
| 115 | - using IRMutator::VisitStmt_; | ||
| 116 | - | ||
| 117 | - // Track Var → assigned Expr for value resolution | ||
| 118 | - std::unordered_map<std::string, ExprPtr> var_vals_; | ||
| 119 | - | ||
| 120 | - // ---- Track assignments for value resolution ---- | ||
| 121 | - StmtPtr VisitStmt_(const AssignStmtPtr& op) override | ||
| 122 | - { | ||
| 123 | - auto new_val = VisitExpr(op->value_); | ||
| 124 | - // Record the assigned value (works for ConstInt, MakeTuple, GetItemExpr, etc.) | ||
| 125 | - var_vals_[op->var_->name_] = new_val; | ||
| 126 | - if (new_val.get() != op->value_.get()) | ||
| 127 | - return std::make_shared<AssignStmt>(op->var_, new_val, op->span_); | ||
| 128 | - return op; | ||
| 129 | - } | ||
| 130 | - | ||
| 131 | - // ---- Constant fold binary expressions ---- | ||
| 132 | - ExprPtr VisitExpr_(const AddPtr& op) override | ||
| 133 | - { | ||
| 134 | - auto l = VisitExpr(op->left_); | ||
| 135 | - auto r = VisitExpr(op->right_); | ||
| 136 | - auto lv = TryGetConstInt(l), rv = TryGetConstInt(r); | ||
| 137 | - if (lv && rv) | ||
| 138 | - return std::make_shared<ConstInt>(*lv + *rv, GetDType(op), op->span_); | ||
| 139 | - // x + 0 → x | ||
| 140 | - if (rv && *rv == 0) | ||
| 141 | - return l; | ||
| 142 | - if (lv && *lv == 0) | ||
| 143 | - return r; | ||
| 144 | - if (l.get() != op->left_.get() || r.get() != op->right_.get()) | ||
| 145 | - return std::make_shared<Add>(l, r, GetDType(op), op->span_); | ||
| 146 | - return op; | ||
| 147 | - } | ||
| 148 | - | ||
| 149 | - ExprPtr VisitExpr_(const SubPtr& op) override | ||
| 150 | - { | ||
| 151 | - auto l = VisitExpr(op->left_); | ||
| 152 | - auto r = VisitExpr(op->right_); | ||
| 153 | - auto lv = TryGetConstInt(l), rv = TryGetConstInt(r); | ||
| 154 | - if (lv && rv) | ||
| 155 | - return std::make_shared<ConstInt>(*lv - *rv, GetDType(op), op->span_); | ||
| 156 | - // x - 0 → x | ||
| 157 | - if (rv && *rv == 0) | ||
| 158 | - return l; | ||
| 159 | - if (l.get() != op->left_.get() || r.get() != op->right_.get()) | ||
| 160 | - return std::make_shared<Sub>(l, r, GetDType(op), op->span_); | ||
| 161 | - return op; | ||
| 162 | - } | ||
| 163 | - | ||
| 164 | - ExprPtr VisitExpr_(const MulPtr& op) override | ||
| 165 | - { | ||
| 166 | - auto l = VisitExpr(op->left_); | ||
| 167 | - auto r = VisitExpr(op->right_); | ||
| 168 | - auto lv = TryGetConstInt(l), rv = TryGetConstInt(r); | ||
| 169 | - if (lv && rv) | ||
| 170 | - return std::make_shared<ConstInt>(*lv * *rv, GetDType(op), op->span_); | ||
| 171 | - // x * 1 → x | ||
| 172 | - if (rv && *rv == 1) | ||
| 173 | - return l; | ||
| 174 | - if (lv && *lv == 1) | ||
| 175 | - return r; | ||
| 176 | - // x * 0 → 0 | ||
| 177 | - if ((rv && *rv == 0) || (lv && *lv == 0)) | ||
| 178 | - return std::make_shared<ConstInt>(0, GetDType(op), op->span_); | ||
| 179 | - if (l.get() != op->left_.get() || r.get() != op->right_.get()) | ||
| 180 | - return std::make_shared<Mul>(l, r, GetDType(op), op->span_); | ||
| 181 | - return op; | ||
| 182 | - } | ||
| 183 | - | ||
| 184 | - ExprPtr VisitExpr_(const FloorDivPtr& op) override | ||
| 185 | - { | ||
| 186 | - auto l = VisitExpr(op->left_); | ||
| 187 | - auto r = VisitExpr(op->right_); | ||
| 188 | - auto lv = TryGetConstInt(l), rv = TryGetConstInt(r); | ||
| 189 | - if (lv && rv && *rv != 0) | ||
| 190 | - return std::make_shared<ConstInt>(*lv / *rv, GetDType(op), op->span_); | ||
| 191 | - if (l.get() != op->left_.get() || r.get() != op->right_.get()) | ||
| 192 | - return std::make_shared<FloorDiv>(l, r, GetDType(op), op->span_); | ||
| 193 | - return op; | ||
| 194 | - } | ||
| 195 | - | ||
| 196 | - ExprPtr VisitExpr_(const FloorModPtr& op) override | ||
| 197 | - { | ||
| 198 | - auto l = VisitExpr(op->left_); | ||
| 199 | - auto r = VisitExpr(op->right_); | ||
| 200 | - auto lv = TryGetConstInt(l), rv = TryGetConstInt(r); | ||
| 201 | - if (lv && rv && *rv != 0) | ||
| 202 | - return std::make_shared<ConstInt>(*lv % *rv, GetDType(op), op->span_); | ||
| 203 | - if (l.get() != op->left_.get() || r.get() != op->right_.get()) | ||
| 204 | - return std::make_shared<FloorMod>(l, r, GetDType(op), op->span_); | ||
| 205 | - return op; | ||
| 206 | - } | ||
| 207 | - | ||
| 208 | - // ---- Constant fold comparisons ---- | ||
| 209 | - ExprPtr VisitExpr_(const EqPtr& op) override | ||
| 210 | - { | ||
| 211 | - auto l = VisitExpr(op->left_); | ||
| 212 | - auto r = VisitExpr(op->right_); | ||
| 213 | - auto lv = TryGetConstInt(l), rv = TryGetConstInt(r); | ||
| 214 | - if (lv && rv) | ||
| 215 | - return std::make_shared<ConstInt>(*lv == *rv ? 1 : 0, DataType::BOOL, op->span_); | ||
| 216 | - if (l.get() != op->left_.get() || r.get() != op->right_.get()) | ||
| 217 | - return std::make_shared<Eq>(l, r, GetDType(op), op->span_); | ||
| 218 | - return op; | ||
| 219 | - } | ||
| 220 | - | ||
| 221 | - ExprPtr VisitExpr_(const LtPtr& op) override | ||
| 222 | - { | ||
| 223 | - auto l = VisitExpr(op->left_); | ||
| 224 | - auto r = VisitExpr(op->right_); | ||
| 225 | - auto lv = TryGetConstInt(l), rv = TryGetConstInt(r); | ||
| 226 | - if (lv && rv) | ||
| 227 | - return std::make_shared<ConstInt>(*lv < *rv ? 1 : 0, DataType::BOOL, op->span_); | ||
| 228 | - if (l.get() != op->left_.get() || r.get() != op->right_.get()) | ||
| 229 | - return std::make_shared<Lt>(l, r, GetDType(op), op->span_); | ||
| 230 | - return op; | ||
| 231 | - } | ||
| 232 | - | ||
| 233 | - ExprPtr VisitExpr_(const LePtr& op) override | ||
| 234 | - { | ||
| 235 | - auto l = VisitExpr(op->left_); | ||
| 236 | - auto r = VisitExpr(op->right_); | ||
| 237 | - auto lv = TryGetConstInt(l), rv = TryGetConstInt(r); | ||
| 238 | - if (lv && rv) | ||
| 239 | - return std::make_shared<ConstInt>(*lv <= *rv ? 1 : 0, DataType::BOOL, op->span_); | ||
| 240 | - if (l.get() != op->left_.get() || r.get() != op->right_.get()) | ||
| 241 | - return std::make_shared<Le>(l, r, GetDType(op), op->span_); | ||
| 242 | - return op; | ||
| 243 | - } | ||
| 244 | - | ||
| 245 | - ExprPtr VisitExpr_(const GtPtr& op) override | ||
| 246 | - { | ||
| 247 | - auto l = VisitExpr(op->left_); | ||
| 248 | - auto r = VisitExpr(op->right_); | ||
| 249 | - auto lv = TryGetConstInt(l), rv = TryGetConstInt(r); | ||
| 250 | - if (lv && rv) | ||
| 251 | - return std::make_shared<ConstInt>(*lv > *rv ? 1 : 0, DataType::BOOL, op->span_); | ||
| 252 | - if (l.get() != op->left_.get() || r.get() != op->right_.get()) | ||
| 253 | - return std::make_shared<Gt>(l, r, GetDType(op), op->span_); | ||
| 254 | - return op; | ||
| 255 | - } | ||
| 256 | - | ||
| 257 | - ExprPtr VisitExpr_(const GePtr& op) override | ||
| 258 | - { | ||
| 259 | - auto l = VisitExpr(op->left_); | ||
| 260 | - auto r = VisitExpr(op->right_); | ||
| 261 | - auto lv = TryGetConstInt(l), rv = TryGetConstInt(r); | ||
| 262 | - if (lv && rv) | ||
| 263 | - return std::make_shared<ConstInt>(*lv >= *rv ? 1 : 0, DataType::BOOL, op->span_); | ||
| 264 | - if (l.get() != op->left_.get() || r.get() != op->right_.get()) | ||
| 265 | - return std::make_shared<Ge>(l, r, GetDType(op), op->span_); | ||
| 266 | - return op; | ||
| 267 | - } | ||
| 268 | - | ||
| 269 | - // ---- Constant fold unary Neg ---- | ||
| 270 | - ExprPtr VisitExpr_(const NegPtr& op) override | ||
| 271 | - { | ||
| 272 | - auto operand = VisitExpr(op->operand_); | ||
| 273 | - auto ov = TryGetConstInt(operand); | ||
| 274 | - if (ov) | ||
| 275 | - return std::make_shared<ConstInt>(-*ov, GetDType(op), op->span_); | ||
| 276 | - if (operand.get() != op->operand_.get()) | ||
| 277 | - return std::make_shared<Neg>(operand, GetDType(op), op->span_); | ||
| 278 | - return op; | ||
| 279 | - } | ||
| 280 | - | ||
| 281 | - StmtPtr MakeEmptySeq(const Span& span) { return std::make_shared<SeqStmts>(std::vector<StmtPtr>{}, span); } | ||
| 282 | - | ||
| 283 | - std::optional<StmtPtr> SimplifyConstCondition(const ExprPtr& cond, const StmtPtr& then_body, | ||
| 284 | - const std::optional<StmtPtr>& else_body, const Span& span) | ||
| 285 | - { | ||
| 286 | - // Resolve through Vars and tuple accesses so a compile-time-constant condition | ||
| 287 | - // (e.g. a bool field of a make_tuple threaded through helpers) prunes the dead | ||
| 288 | - // branch, hoisting the live branch into the parent scope. | ||
| 289 | - auto const_value = ResolveToConst(cond, var_vals_); | ||
| 290 | - if (!const_value) { | ||
| 291 | - return std::nullopt; | ||
| 292 | - } | ||
| 293 | - if (*const_value != 0) { | ||
| 294 | - return then_body; | ||
| 295 | - } | ||
| 296 | - if (else_body) { | ||
| 297 | - return *else_body; | ||
| 298 | - } | ||
| 299 | - return MakeEmptySeq(span); | ||
| 300 | - } | ||
| 301 | - | ||
| 302 | - std::vector<ExprPtr> ExtractYieldValues(const StmtPtr& body) | ||
| 303 | - { | ||
| 304 | - if (auto yield_stmt = As<YieldStmt>(body)) { | ||
| 305 | - return yield_stmt->value_; | ||
| 306 | - } | ||
| 307 | - | ||
| 308 | - auto seq = As<SeqStmts>(body); | ||
| 309 | - if (!seq) { | ||
| 310 | - return {}; | ||
| 311 | - } | ||
| 312 | - if (seq->stmts_.size() == 1) { | ||
| 313 | - if (auto yield_stmt = As<YieldStmt>(seq->stmts_[0])) { | ||
| 314 | - return yield_stmt->value_; | ||
| 315 | - } | ||
| 316 | - } | ||
| 317 | - if (!seq->stmts_.empty()) { | ||
| 318 | - if (auto yield_stmt = As<YieldStmt>(seq->stmts_.back())) { | ||
| 319 | - return yield_stmt->value_; | ||
| 320 | - } | ||
| 321 | - } | ||
| 322 | - return {}; | ||
| 323 | - } | ||
| 324 | - | ||
| 325 | - bool HaveSameYieldValues(const std::vector<ExprPtr>& then_vals, const std::vector<ExprPtr>& else_vals, | ||
| 326 | - size_t expected_count) | ||
| 327 | - { | ||
| 328 | - if (then_vals.size() != expected_count || else_vals.size() != expected_count) { | ||
| 329 | - return false; | ||
| 330 | - } | ||
| 331 | - for (size_t i = 0; i < then_vals.size(); ++i) { | ||
| 332 | - if (!IsSameExpr(then_vals[i], else_vals[i], var_vals_)) { | ||
| 333 | - return false; | ||
| 334 | - } | ||
| 335 | - } | ||
| 336 | - return true; | ||
| 337 | - } | ||
| 338 | - | ||
| 339 | - StmtPtr MakeAssignSeq(const std::vector<VarPtr>& return_vars, const std::vector<ExprPtr>& values, const Span& span) | ||
| 340 | - { | ||
| 341 | - std::vector<StmtPtr> assigns; | ||
| 342 | - assigns.reserve(return_vars.size()); | ||
| 343 | - for (size_t i = 0; i < return_vars.size(); ++i) { | ||
| 344 | - assigns.push_back(std::make_shared<AssignStmt>(return_vars[i], values[i], span)); | ||
| 345 | - } | ||
| 346 | - return std::make_shared<SeqStmts>(std::move(assigns), span); | ||
| 347 | - } | ||
| 348 | - | ||
| 349 | - std::optional<StmtPtr> TryFoldSameYieldBranches(const IfStmtPtr& op, const StmtPtr& then_body, | ||
| 350 | - const std::optional<StmtPtr>& else_body) | ||
| 351 | - { | ||
| 352 | - if (!else_body || op->returnVars_.empty()) { | ||
| 353 | - return std::nullopt; | ||
| 354 | - } | ||
| 355 | - | ||
| 356 | - auto then_vals = ExtractYieldValues(then_body); | ||
| 357 | - auto else_vals = ExtractYieldValues(*else_body); | ||
| 358 | - if (!HaveSameYieldValues(then_vals, else_vals, op->returnVars_.size())) { | ||
| 359 | - return std::nullopt; | ||
| 360 | - } | ||
| 361 | - return MakeAssignSeq(op->returnVars_, then_vals, op->span_); | ||
| 362 | - } | ||
| 363 | - | ||
| 364 | - // ---- If-stmt simplification ---- | ||
| 365 | - StmtPtr VisitStmt_(const IfStmtPtr& op) override | ||
| 366 | - { | ||
| 367 | - auto cond = VisitExpr(op->condition_); | ||
| 368 | - auto then_body = VisitStmt(op->thenBody_); | ||
| 369 | - std::optional<StmtPtr> else_body; | ||
| 370 | - if (op->elseBody_) | ||
| 371 | - else_body = VisitStmt(*op->elseBody_); | ||
| 372 | - | ||
| 373 | - auto const_simplified = SimplifyConstCondition(cond, then_body, else_body, op->span_); | ||
| 374 | - if (const_simplified) { | ||
| 375 | - return *const_simplified; | ||
| 376 | - } | ||
| 377 | - | ||
| 378 | - auto same_yield_folded = TryFoldSameYieldBranches(op, then_body, else_body); | ||
| 379 | - if (same_yield_folded) { | ||
| 380 | - return *same_yield_folded; | ||
| 381 | - } | ||
| 382 | - | ||
| 383 | - // Copy-on-write | ||
| 384 | - if (cond.get() != op->condition_.get() || then_body.get() != op->thenBody_.get() || | ||
| 385 | - (else_body && else_body->get() != op->elseBody_->get())) { | ||
| 386 | - return std::make_shared<IfStmt>(cond, then_body, else_body, op->returnVars_, op->span_); | ||
| 387 | - } | ||
| 388 | - return op; | ||
| 389 | - } | ||
| 390 | -}; | ||
| 391 | - | ||
| 392 | -// --------------------------------------------------------------------------- | ||
| 393 | -// Pass factory | ||
| 394 | -// --------------------------------------------------------------------------- | ||
| 395 | -static FunctionPtr TransformConstFoldAndSimplify(const FunctionPtr& func) | ||
| 396 | -{ | ||
| 397 | - if (!func || !func->body_) | ||
| 398 | - return func; | ||
| 399 | - ConstFoldMutator mutator; | ||
| 400 | - auto new_body = mutator.VisitStmt(func->body_); | ||
| 401 | - if (new_body.get() == func->body_.get()) | ||
| 402 | - return func; | ||
| 403 | - return std::make_shared<Function>(func->name_, func->params_, func->returnTypes_, new_body, func->span_, | ||
| 404 | - func->funcType_, func->entry_); | ||
| 405 | -} | ||
| 406 | - | ||
| 407 | -namespace pass { | ||
| 408 | - | ||
| 409 | -Pass ConstFoldAndSimplify() { return CreateFunctionPass(TransformConstFoldAndSimplify, "ConstFoldAndSimplify"); } | ||
| 410 | - | ||
| 411 | -} // namespace pass | ||
| 412 | -} // namespace ir | ||
| 413 | -} // namespace pypto | ||
| @@ -1,494 +0,0 @@ | |||
| 1 | -/** | ||
| 2 | - * Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 3 | - * This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 4 | - * CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 5 | - * Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 6 | - * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 7 | - * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 8 | - * See LICENSE in the root of the software repository for the full text of the License. | ||
| 9 | - */ | ||
| 10 | - | ||
| 11 | -// NormalizeMatTransposeLayout | ||
| 12 | -// =========================== | ||
| 13 | -// Lets a matmul operand that lives in the L1 (Mat) buffer be declared in "clear form" -- its | ||
| 14 | -// shape/layout describing the data as produced, not the physical fractal the hardware needs -- | ||
| 15 | -// and rewrites it to that physical form. See the pass factory doc in ir/transforms/passes.h. | ||
| 16 | -// | ||
| 17 | -// Background (the hardware constraint) | ||
| 18 | -// ------------------------------------ | ||
| 19 | -// The L1(Mat)->L0(Left/Right) move (`pl.move`, lowered to the CANN TMOV tileop) requires src | ||
| 20 | -// and dst to have the SAME physical [Rows, Cols] (a static_assert in the generated kernel). It | ||
| 21 | -// realizes a *logical transpose* only by the NZ-vs-ZN fractal mismatch, never by changing the | ||
| 22 | -// dims. And because `Mat [N,K] NZ` and `Mat [K,N] ZN` are the *same bytes*, a transposed | ||
| 23 | -// operand physically has to be declared `[K,N] ZN` -- a shape that does not match the [N,K] | ||
| 24 | -// data it is filled from. This pass lets you write the [N,K] shape and fixes it up here. | ||
| 25 | -// | ||
| 26 | -// What the frontend writes vs. what this pass emits | ||
| 27 | -// ------------------------------------------------- | ||
| 28 | -// Example matmul: out[M,N] = A[M,K] @ B[K,N], with the RIGHT operand B transposed on-chip. | ||
| 29 | -// | ||
| 30 | -// (1) ON-CHIP (insert) path -- B is produced by the vector core and inserted into L1: | ||
| 31 | -// | ||
| 32 | -// # clear form: shape [N,K] matches the inserted data d, layout NZ matches the shape | ||
| 33 | -// rhs_mat = pl.make_tile(pl.TileType(shape=[N, K], layout=pl.NZ, | ||
| 34 | -// target_memory=pl.MemorySpace.Mat), ...) | ||
| 35 | -// pl.insert(rhs_mat, tile_nz, [off, 0]) # fill L1 from a Vec NZ tile | ||
| 36 | -// rhs_right = pl.make_tile(... shape=[K, N], Right, layout=pl.ZN) | ||
| 37 | -// pl.move(rhs_right, rhs_mat) # src [N,K] vs dst [K,N] <-- reversed | ||
| 38 | -// | ||
| 39 | -// This pass relabels `rhs_mat` to the physical `shape=[K,N], layout=pl.ZN` (swap dims + | ||
| 40 | -// swap NZ<->ZN, identical bytes), so the move becomes same-shape [K,N]->[K,N] and its | ||
| 41 | -// fractal mismatch performs the transpose. Emitted tile: Tile<Mat,half,K,N,ZN,...>. | ||
| 42 | -// | ||
| 43 | -// (2) GM normal-load path -- B^T is in GM as b_t=[N,K] and loaded straight into L1: | ||
| 44 | -// | ||
| 45 | -// b_mat = pl.make_tile(pl.TileType(shape=[N, K], layout=pl.NZ, Mat), ...) # clear form | ||
| 46 | -// pl.load(b_mat, b_t, [0, 0]) # NORMAL load, no is_transpose | ||
| 47 | -// b_right = pl.make_tile(... shape=[K, N], Right, layout=pl.ZN) | ||
| 48 | -// pl.move(b_right, b_mat) # reversed, same as above | ||
| 49 | -// | ||
| 50 | -// Relabeling alone is not enough here: the load's GM access window is derived from the | ||
| 51 | -// tile shape, so swapping `b_mat` to [K,N] would make the load read the [N,K] GM wrong. | ||
| 52 | -// So the pass ALSO flips this feeding load to `is_transpose=True`, which reads b_t=[N,K] | ||
| 53 | -// transposed into the [K,N] tile -- exactly the code the explicit is_transpose form below | ||
| 54 | -// would have produced. | ||
| 55 | -// | ||
| 56 | -// (3) GM transpose-load path -- already physical, LEFT UNTOUCHED: | ||
| 57 | -// | ||
| 58 | -// b_mat = pl.make_tile(pl.TileType(shape=[K, N], layout=pl.ZN, Mat), ...) # physical | ||
| 59 | -// pl.load(b_mat, b_t, [0, 0], is_transpose=True) # load transposes; Mat holds B | ||
| 60 | -// pl.move(b_right, b_mat) # same-shape [K,N]->[K,N] | ||
| 61 | -// | ||
| 62 | -// The move is same-shape, so this Mat is never a candidate; the is_transpose feed is also | ||
| 63 | -// recorded as a hard exclusion so it can never be relabeled by accident. | ||
| 64 | -// | ||
| 65 | -// Two phases | ||
| 66 | -// ---------- | ||
| 67 | -// 1. Analysis (TransposeMatCollector): find every `block.move(dst=Left/Right, src=Mat)` | ||
| 68 | -// whose src 2D shape is the reverse of the dst shape and not square -> candidate Mat. | ||
| 69 | -// Record Mats fed by an is_transpose load as a hard exclusion. | ||
| 70 | -// 2. Rewrite (TransposeMatRewriter): for every reference to a target allocation swap the two | ||
| 71 | -// shape dims and swap blayout<->slayout (NZ<->ZN) -- a pure byte relabeling applied to the | ||
| 72 | -// make_tile def and every reference Var, so it follows tile assignment / control flow. A | ||
| 73 | -// normal `block.load` feeding a target Mat is additionally flipped to is_transpose. | ||
| 74 | -// | ||
| 75 | -// The pass is a no-op when src.shape == dst.shape (the physical convention every other kernel | ||
| 76 | -// uses) and for square tiles (reverse == itself is ambiguous), so existing kernels are safe. | ||
| 77 | - | ||
| 78 | -#include <any> | ||
| 79 | -#include <memory> | ||
| 80 | -#include <optional> | ||
| 81 | -#include <set> | ||
| 82 | -#include <string> | ||
| 83 | -#include <unordered_map> | ||
| 84 | -#include <utility> | ||
| 85 | -#include <vector> | ||
| 86 | - | ||
| 87 | -#include "ir/expr.h" | ||
| 88 | -#include "ir/function.h" | ||
| 89 | -#include "ir/kind_traits.h" | ||
| 90 | -#include "ir/memory_space.h" | ||
| 91 | -#include "ir/memref.h" | ||
| 92 | -#include "ir/span.h" | ||
| 93 | -#include "ir/stmt.h" | ||
| 94 | -#include "ir/transforms/base/mutator.h" | ||
| 95 | -#include "ir/transforms/base/visitor.h" | ||
| 96 | -#include "ir/transforms/passes.h" | ||
| 97 | -#include "ir/type.h" | ||
| 98 | - | ||
| 99 | -namespace pypto { | ||
| 100 | -namespace ir { | ||
| 101 | - | ||
| 102 | -namespace { | ||
| 103 | - | ||
| 104 | -// Return the two static dimensions of a 2D TileType, or nullopt if it is not a | ||
| 105 | -// rank-2 tile with compile-time-constant dims. | ||
| 106 | -std::optional<std::pair<int64_t, int64_t>> Static2DShape(const TileTypePtr& tt) | ||
| 107 | -{ | ||
| 108 | - if (!tt || tt->shape_.size() != 2) | ||
| 109 | - return std::nullopt; | ||
| 110 | - auto d0 = As<ConstInt>(tt->shape_[0]); | ||
| 111 | - auto d1 = As<ConstInt>(tt->shape_[1]); | ||
| 112 | - if (!d0 || !d1) | ||
| 113 | - return std::nullopt; | ||
| 114 | - return std::make_pair(d0->value_, d1->value_); | ||
| 115 | -} | ||
| 116 | - | ||
| 117 | -std::optional<MemorySpace> SpaceOf(const TileTypePtr& tt) | ||
| 118 | -{ | ||
| 119 | - if (!tt || !tt->memref_.has_value()) | ||
| 120 | - return std::nullopt; | ||
| 121 | - return (*tt->memref_)->memorySpace_; | ||
| 122 | -} | ||
| 123 | - | ||
| 124 | -// A Mat allocation is uniquely named by its MemRef (name is generated from the | ||
| 125 | -// allocation id), so the name identifies the allocation across every reference. | ||
| 126 | -std::optional<std::string> AllocNameOf(const TileTypePtr& tt) | ||
| 127 | -{ | ||
| 128 | - if (!tt || !tt->memref_.has_value()) | ||
| 129 | - return std::nullopt; | ||
| 130 | - return (*tt->memref_)->name_; | ||
| 131 | -} | ||
| 132 | - | ||
| 133 | -// ------------------------------------------------------------------------------------------- | ||
| 134 | -// Phase 1: collect Mat allocations that are clear-form transpose operands. | ||
| 135 | -// | ||
| 136 | -// e.g. for `pl.move(rhs_right[K,N], rhs_mat[N,K])` this records the `rhs_mat` allocation as a | ||
| 137 | -// candidate; a `pl.load(rhs_mat, d, ..., is_transpose=True)` instead records it as excluded. | ||
| 138 | -// ------------------------------------------------------------------------------------------- | ||
| 139 | -class TransposeMatCollector : public IRVisitor { | ||
| 140 | - using IRVisitor::VisitExpr_; | ||
| 141 | - using IRVisitor::VisitStmt_; | ||
| 142 | - | ||
| 143 | -public: | ||
| 144 | - std::set<std::string> candidates; // Mat allocations reached by a reversed Mat->L0 move | ||
| 145 | - std::set<std::string> transpose_loaded; // Mat allocations already filled by an is_transpose load | ||
| 146 | - | ||
| 147 | - // Targets are reversed-move candidates, minus any Mat that is already fed by an | ||
| 148 | - // is_transpose load. An is_transpose load fills the Mat in the physical (transposed) | ||
| 149 | - // form the frontend declared, so relabeling it would double-transpose; such a buffer is | ||
| 150 | - // used with a same-shape move and never appears here anyway, but excluding it is safe. | ||
| 151 | - // | ||
| 152 | - // A Mat fed by a NORMAL load with a reversed move IS a target: it is the clear-form GM | ||
| 153 | - // path (declare the logical shape/NZ matching the GM tensor, transpose on the way to | ||
| 154 | - // L0). For those the rewriter both relabels the Mat and flips the feeding load to | ||
| 155 | - // is_transpose, so the load reads the GM correctly into the relabeled tile -- exactly | ||
| 156 | - // the code an explicit is_transpose load would have produced. | ||
| 157 | - std::set<std::string> Targets() const | ||
| 158 | - { | ||
| 159 | - std::set<std::string> out; | ||
| 160 | - for (const auto& name : candidates) { | ||
| 161 | - if (transpose_loaded.count(name) == 0) | ||
| 162 | - out.insert(name); | ||
| 163 | - } | ||
| 164 | - return out; | ||
| 165 | - } | ||
| 166 | - | ||
| 167 | - // Var name -> the value it is bound to (from AssignStmts). Lets a tile-group slot access | ||
| 168 | - // (a GetItemExpr through the group's named tuple) be resolved back to the MakeTuple of slot | ||
| 169 | - // tiles. Populated while walking; a tile group is always defined before it is used. | ||
| 170 | - std::unordered_map<std::string, ExprPtr> bindings_; | ||
| 171 | - | ||
| 172 | - void VisitStmt_(const AssignStmtPtr& op) override | ||
| 173 | - { | ||
| 174 | - if (op->var_ && op->value_) | ||
| 175 | - bindings_[op->var_->name_] = op->value_; | ||
| 176 | - IRVisitor::VisitStmt_(op); | ||
| 177 | - } | ||
| 178 | - | ||
| 179 | - void VisitExpr_(const CallPtr& op) override | ||
| 180 | - { | ||
| 181 | - IRVisitor::VisitExpr_(op); // keep walking nested exprs | ||
| 182 | - | ||
| 183 | - // A Mat already filled by an is_transpose load carries the physical form; never relabel it. | ||
| 184 | - // (block.load covers both pl.load and pl.load_tile; arg 0 is the destination tile.) | ||
| 185 | - if (op->name_ == "block.load" && !op->args_.empty()) { | ||
| 186 | - if (op->HasKwarg("is_transpose") && op->GetKwarg<bool>("is_transpose")) { | ||
| 187 | - if (auto dst = As<TileType>(op->args_[0]->GetType()); dst && SpaceOf(dst) == MemorySpace::Mat) { | ||
| 188 | - for (const auto& name : MatSlotNames(op->args_[0])) | ||
| 189 | - transpose_loaded.insert(name); | ||
| 190 | - } | ||
| 191 | - } | ||
| 192 | - return; | ||
| 193 | - } | ||
| 194 | - | ||
| 195 | - if (op->name_ != "block.move" || op->args_.size() < 2) | ||
| 196 | - return; | ||
| 197 | - auto dst = As<TileType>(op->args_[0]->GetType()); | ||
| 198 | - auto src = As<TileType>(op->args_[1]->GetType()); | ||
| 199 | - if (!dst || !src) | ||
| 200 | - return; | ||
| 201 | - | ||
| 202 | - auto dst_space = SpaceOf(dst); | ||
| 203 | - auto src_space = SpaceOf(src); | ||
| 204 | - if (src_space != MemorySpace::Mat) | ||
| 205 | - return; | ||
| 206 | - if (dst_space != MemorySpace::Left && dst_space != MemorySpace::Right) | ||
| 207 | - return; | ||
| 208 | - | ||
| 209 | - auto src_shape = Static2DShape(src); | ||
| 210 | - auto dst_shape = Static2DShape(dst); | ||
| 211 | - if (!src_shape || !dst_shape) | ||
| 212 | - return; | ||
| 213 | - | ||
| 214 | - // Clear form: src is the reverse of dst and not square. e.g. src Mat [N,K] -> dst | ||
| 215 | - // Right [K,N] is reversed (a clear-form transpose operand); src [K,N] -> dst [K,N] is | ||
| 216 | - // same-shape (the physical convention every other kernel uses); a square [D,D] tile is | ||
| 217 | - // ambiguous because reverse == itself. Only the reversed, non-square case is rewritten. | ||
| 218 | - bool reversed = src_shape->first == dst_shape->second && src_shape->second == dst_shape->first; | ||
| 219 | - bool square = src_shape->first == src_shape->second; | ||
| 220 | - if (!reversed || square) | ||
| 221 | - return; | ||
| 222 | - | ||
| 223 | - // A plain tile contributes one name; a tile-group slot access contributes every sibling | ||
| 224 | - // slot, since a rotating group shares one TileType and must be relabeled as a whole. | ||
| 225 | - for (const auto& name : MatSlotNames(op->args_[1])) | ||
| 226 | - candidates.insert(name); | ||
| 227 | - } | ||
| 228 | - | ||
| 229 | - // Follow Var bindings and constant tuple indices to the MakeTuple that `e` refers to. | ||
| 230 | - MakeTuplePtr ResolveToMakeTuple(const ExprPtr& e, int depth = 0) const | ||
| 231 | - { | ||
| 232 | - if (!e || depth > 32) | ||
| 233 | - return nullptr; | ||
| 234 | - if (auto mt = As<MakeTuple>(e)) | ||
| 235 | - return mt; | ||
| 236 | - if (auto v = As<Var>(e)) { | ||
| 237 | - auto it = bindings_.find(v->name_); | ||
| 238 | - return it == bindings_.end() ? nullptr : ResolveToMakeTuple(it->second, depth + 1); | ||
| 239 | - } | ||
| 240 | - if (auto gi = As<GetItemExpr>(e)) { | ||
| 241 | - if (auto ci = As<ConstInt>(gi->slice_)) { | ||
| 242 | - auto inner = ResolveToMakeTuple(gi->value_, depth + 1); | ||
| 243 | - if (inner && ci->value_ >= 0 && ci->value_ < static_cast<int64_t>(inner->elements_.size())) | ||
| 244 | - return ResolveToMakeTuple(inner->elements_[ci->value_], depth + 1); | ||
| 245 | - } | ||
| 246 | - } | ||
| 247 | - return nullptr; | ||
| 248 | - } | ||
| 249 | - | ||
| 250 | - // The Mat allocation name(s) a tile operand refers to. For a tile-group slot access | ||
| 251 | - // `GetItemExpr(tiles, idx)` this resolves `tiles` to its MakeTuple and returns every slot's | ||
| 252 | - // name; otherwise it is the single name on the operand's own TileType. | ||
| 253 | - std::set<std::string> MatSlotNames(const ExprPtr& tile_expr) const | ||
| 254 | - { | ||
| 255 | - std::set<std::string> out; | ||
| 256 | - // `b_mat = grp.next()` binds the operand to a Var, so follow the binding chain to the | ||
| 257 | - // underlying slot access before checking whether it is a tile-group GetItemExpr. | ||
| 258 | - ExprPtr e = tile_expr; | ||
| 259 | - for (int depth = 0; depth < 32; ++depth) { | ||
| 260 | - auto v = As<Var>(e); | ||
| 261 | - if (!v) | ||
| 262 | - break; | ||
| 263 | - auto it = bindings_.find(v->name_); | ||
| 264 | - if (it == bindings_.end()) | ||
| 265 | - break; | ||
| 266 | - e = it->second; | ||
| 267 | - } | ||
| 268 | - if (auto gi = As<GetItemExpr>(e)) { | ||
| 269 | - if (auto tiles = ResolveToMakeTuple(gi->value_)) { | ||
| 270 | - for (const auto& elem : tiles->elements_) { | ||
| 271 | - if (auto tt = As<TileType>(elem->GetType())) | ||
| 272 | - if (auto name = AllocNameOf(tt)) | ||
| 273 | - out.insert(*name); | ||
| 274 | - } | ||
| 275 | - if (!out.empty()) | ||
| 276 | - return out; | ||
| 277 | - } | ||
| 278 | - } | ||
| 279 | - if (auto tt = As<TileType>(tile_expr->GetType())) | ||
| 280 | - if (auto name = AllocNameOf(tt)) | ||
| 281 | - out.insert(*name); | ||
| 282 | - return out; | ||
| 283 | - } | ||
| 284 | -}; | ||
| 285 | - | ||
| 286 | -// ------------------------------------------------------------------------------------------- | ||
| 287 | -// Phase 2: relabel every reference to a recorded allocation. | ||
| 288 | -// | ||
| 289 | -// For a target `rhs_mat` declared `TileType(shape=[N,K], layout=pl.NZ)` this rewrites the | ||
| 290 | -// make_tile def, and every Var that refers to it, to `shape=[K,N], layout=pl.ZN` (same bytes), | ||
| 291 | -// and flips any normal `pl.load` into it to is_transpose. Downstream ops (`pl.insert`, | ||
| 292 | -// `pl.move`, `pl.matmul`) then see a Mat whose physical shape matches its L0 destination. | ||
| 293 | -// ------------------------------------------------------------------------------------------- | ||
| 294 | -class TransposeMatRewriter : public IRMutator { | ||
| 295 | - using IRMutator::VisitExpr_; | ||
| 296 | - using IRMutator::VisitStmt_; | ||
| 297 | - | ||
| 298 | -public: | ||
| 299 | - explicit TransposeMatRewriter(std::set<std::string> targets) : targets_(std::move(targets)) {} | ||
| 300 | - | ||
| 301 | - ExprPtr VisitExpr_(const VarPtr& op) override | ||
| 302 | - { | ||
| 303 | - auto swapped = SwapContainedTargets(op->GetType()); | ||
| 304 | - if (swapped.get() != op->GetType().get()) { | ||
| 305 | - auto it = var_cache_.find(op.get()); | ||
| 306 | - if (it != var_cache_.end()) | ||
| 307 | - return it->second; | ||
| 308 | - auto rebuilt = std::make_shared<const Var>(op->name_, swapped, op->span_); | ||
| 309 | - var_cache_[op.get()] = rebuilt; | ||
| 310 | - return rebuilt; | ||
| 311 | - } | ||
| 312 | - return IRMutator::VisitExpr_(op); | ||
| 313 | - } | ||
| 314 | - | ||
| 315 | - // Swap target TileTypes appearing directly in a type: either the type itself (a slot Var) or | ||
| 316 | - // the direct elements of a positional tuple. A tile group's `tiles` tuple is such a tuple, and | ||
| 317 | - // codegen sizes the double-buffer array from that Var's declared element types, so it must be | ||
| 318 | - // swapped too. Nested/named tuples (the group's {tiles, mutex_ids, cursor}) are left intact so | ||
| 319 | - // their pointer-keyed field-name side table stays valid; their `tiles` access resolves to the | ||
| 320 | - // swapped tiles Var directly. | ||
| 321 | - TypePtr SwapContainedTargets(const TypePtr& type) const | ||
| 322 | - { | ||
| 323 | - if (auto tt = As<TileType>(type)) | ||
| 324 | - return IsTarget(tt) ? std::static_pointer_cast<const Type>(SwapTileType(tt)) : type; | ||
| 325 | - if (auto tup = As<TupleType>(type)) { | ||
| 326 | - std::vector<TypePtr> elems; | ||
| 327 | - elems.reserve(tup->types_.size()); | ||
| 328 | - bool changed = false; | ||
| 329 | - for (const auto& e : tup->types_) { | ||
| 330 | - if (auto et = As<TileType>(e); et && IsTarget(et)) { | ||
| 331 | - elems.push_back(SwapTileType(et)); | ||
| 332 | - changed = true; | ||
| 333 | - } else { | ||
| 334 | - elems.push_back(e); | ||
| 335 | - } | ||
| 336 | - } | ||
| 337 | - if (!changed) | ||
| 338 | - return type; | ||
| 339 | - return std::make_shared<const TupleType>(std::move(elems)); | ||
| 340 | - } | ||
| 341 | - return type; | ||
| 342 | - } | ||
| 343 | - | ||
| 344 | - ExprPtr VisitExpr_(const CallPtr& op) override | ||
| 345 | - { | ||
| 346 | - auto base = IRMutator::VisitExpr_(op); | ||
| 347 | - auto call = As<Call>(base); | ||
| 348 | - if (!call) | ||
| 349 | - return base; | ||
| 350 | - | ||
| 351 | - if (call->name_ == "block.make_tile") { | ||
| 352 | - auto tt = As<TileType>(call->GetType()); | ||
| 353 | - // Re-validate 2D-ness here rather than trusting the name alone: SwapTileType indexes | ||
| 354 | - // shape_[0]/[1], so a target must be a rank-2 tile with static dims. | ||
| 355 | - if (!tt || !IsTarget(tt) || !Static2DShape(tt)) | ||
| 356 | - return base; | ||
| 357 | - | ||
| 358 | - // Rewrite the make_tile so its args stay consistent with the relabeled type: | ||
| 359 | - // swap the shape (and valid_shape) tuple dims and swap the blayout/slayout kwargs. | ||
| 360 | - std::vector<ExprPtr> new_args = call->args_; | ||
| 361 | - if (!new_args.empty()) | ||
| 362 | - new_args[0] = SwapTuple(new_args[0]); | ||
| 363 | - if (new_args.size() >= 2) | ||
| 364 | - new_args[1] = SwapTuple(new_args[1]); | ||
| 365 | - | ||
| 366 | - std::vector<std::pair<std::string, std::any>> new_kwargs = SwapLayoutKwargs(call->kwargs_); | ||
| 367 | - | ||
| 368 | - return std::make_shared<const Call>(call->name_, std::move(new_args), std::move(new_kwargs), | ||
| 369 | - SwapTileType(tt), call->span_); | ||
| 370 | - } | ||
| 371 | - | ||
| 372 | - // A normal load feeding a relabeled Mat must become an is_transpose load. The make_tile | ||
| 373 | - // above swapped the Mat to the L0 orientation (e.g. [N,K] -> [K,N]), but the load's GM | ||
| 374 | - // access window is derived from the tile shape, so a plain load would now read the | ||
| 375 | - // [N,K] GM tensor as if it were [K,N]. Flipping is_transpose makes it read the GM | ||
| 376 | - // transposed into the swapped tile -- i.e. `pl.load(b_mat, b_t, [0,0])` becomes the | ||
| 377 | - // equivalent of `pl.load(b_mat, b_t, [0,0], is_transpose=True)`. | ||
| 378 | - if (call->name_ == "block.load" && !call->args_.empty()) { | ||
| 379 | - auto dst = As<TileType>(call->args_[0]->GetType()); | ||
| 380 | - bool already_transpose = call->HasKwarg("is_transpose") && call->GetKwarg<bool>("is_transpose"); | ||
| 381 | - if (dst && IsTarget(dst) && !already_transpose) { | ||
| 382 | - std::vector<std::pair<std::string, std::any>> new_kwargs = call->kwargs_; | ||
| 383 | - new_kwargs.emplace_back("is_transpose", std::any(true)); | ||
| 384 | - return std::make_shared<const Call>(call->name_, call->args_, std::move(new_kwargs), call->GetType(), | ||
| 385 | - call->span_); | ||
| 386 | - } | ||
| 387 | - } | ||
| 388 | - | ||
| 389 | - return base; | ||
| 390 | - } | ||
| 391 | - | ||
| 392 | -private: | ||
| 393 | - bool IsTarget(const TileTypePtr& tt) const | ||
| 394 | - { | ||
| 395 | - auto name = AllocNameOf(tt); | ||
| 396 | - return name && targets_.count(*name) > 0; | ||
| 397 | - } | ||
| 398 | - | ||
| 399 | - // Swap the two dims of a rank-2 shape/valid_shape MakeTuple. Leaves anything | ||
| 400 | - // else (e.g. an empty valid_shape tuple) untouched. | ||
| 401 | - static ExprPtr SwapTuple(const ExprPtr& expr) | ||
| 402 | - { | ||
| 403 | - auto tuple = As<MakeTuple>(expr); | ||
| 404 | - if (!tuple || tuple->elements_.size() != 2) | ||
| 405 | - return expr; | ||
| 406 | - std::vector<ExprPtr> swapped = {tuple->elements_[1], tuple->elements_[0]}; | ||
| 407 | - return std::make_shared<const MakeTuple>(std::move(swapped), tuple->span_); | ||
| 408 | - } | ||
| 409 | - | ||
| 410 | - // NZ is (blayout, slayout) = (col_major, row_major); ZN is the swap. Exchanging the | ||
| 411 | - // two kwargs flips NZ<->ZN, matching the TileType relabeling. | ||
| 412 | - static std::vector<std::pair<std::string, std::any>> SwapLayoutKwargs( | ||
| 413 | - const std::vector<std::pair<std::string, std::any>>& kwargs) | ||
| 414 | - { | ||
| 415 | - std::any blayout; | ||
| 416 | - std::any slayout; | ||
| 417 | - bool has_b = false; | ||
| 418 | - bool has_s = false; | ||
| 419 | - for (const auto& [k, v] : kwargs) { | ||
| 420 | - if (k == "blayout") { | ||
| 421 | - blayout = v; | ||
| 422 | - has_b = true; | ||
| 423 | - } else if (k == "slayout") { | ||
| 424 | - slayout = v; | ||
| 425 | - has_s = true; | ||
| 426 | - } | ||
| 427 | - } | ||
| 428 | - if (!has_b || !has_s) | ||
| 429 | - return kwargs; | ||
| 430 | - std::vector<std::pair<std::string, std::any>> out = kwargs; | ||
| 431 | - for (auto& [k, v] : out) { | ||
| 432 | - if (k == "blayout") | ||
| 433 | - v = slayout; | ||
| 434 | - else if (k == "slayout") | ||
| 435 | - v = blayout; | ||
| 436 | - } | ||
| 437 | - return out; | ||
| 438 | - } | ||
| 439 | - | ||
| 440 | - // Relabel a tile to its byte-identical transpose: swap the shape dims, swap the | ||
| 441 | - // valid_shape dims, and swap blayout<->slayout (flips NZ<->ZN). The MemRef (address/size/ | ||
| 442 | - // space/id) is preserved, so this is a pure relabeling of the same L1 bytes -- e.g. | ||
| 443 | - // `Mat [N,K] NZ` -> `Mat [K,N] ZN`. | ||
| 444 | - TileTypePtr SwapTileType(const TileTypePtr& tt) const | ||
| 445 | - { | ||
| 446 | - std::vector<ExprPtr> new_shape = {tt->shape_[1], tt->shape_[0]}; | ||
| 447 | - | ||
| 448 | - std::optional<TileView> new_view = tt->tileView_; | ||
| 449 | - if (new_view.has_value() && new_view->validShape.size() == 2) | ||
| 450 | - std::swap(new_view->validShape[0], new_view->validShape[1]); | ||
| 451 | - | ||
| 452 | - HardwareInfo hw = tt->hardwareInfo_.value_or(HardwareInfo{}); | ||
| 453 | - std::swap(hw.blayout, hw.slayout); | ||
| 454 | - | ||
| 455 | - return std::make_shared<const TileType>(std::move(new_shape), tt->dtype_, tt->memref_, std::move(new_view), | ||
| 456 | - std::make_optional(hw)); | ||
| 457 | - } | ||
| 458 | - | ||
| 459 | - std::set<std::string> targets_; | ||
| 460 | - std::unordered_map<const Expr*, ExprPtr> var_cache_; | ||
| 461 | -}; | ||
| 462 | - | ||
| 463 | -FunctionPtr TransformNormalizeMatTranspose(const FunctionPtr& func) | ||
| 464 | -{ | ||
| 465 | - if (!func || !func->body_) | ||
| 466 | - return func; | ||
| 467 | - | ||
| 468 | - TransposeMatCollector collector; | ||
| 469 | - collector.VisitStmt(func->body_); | ||
| 470 | - auto targets = collector.Targets(); | ||
| 471 | - if (targets.empty()) | ||
| 472 | - return func; | ||
| 473 | - | ||
| 474 | - TransposeMatRewriter rewriter(std::move(targets)); | ||
| 475 | - auto new_body = rewriter.VisitStmt(func->body_); | ||
| 476 | - if (new_body.get() == func->body_.get()) | ||
| 477 | - return func; | ||
| 478 | - return std::make_shared<Function>(func->name_, func->params_, func->returnTypes_, new_body, func->span_, | ||
| 479 | - func->funcType_); | ||
| 480 | -} | ||
| 481 | - | ||
| 482 | -} // namespace | ||
| 483 | - | ||
| 484 | -namespace pass { | ||
| 485 | - | ||
| 486 | -Pass NormalizeMatTransposeLayout() | ||
| 487 | -{ | ||
| 488 | - return CreateFunctionPass(TransformNormalizeMatTranspose, "NormalizeMatTransposeLayout"); | ||
| 489 | -} | ||
| 490 | - | ||
| 491 | -} // namespace pass | ||
| 492 | - | ||
| 493 | -} // namespace ir | ||
| 494 | -} // namespace pypto | ||
Rframework/src/interface/pypto_pro/backend/910B_CCE/backend_910b_cce.cpp→framework/src/interface/pypto_pro/backend/backend_cce.cpp+12-7
| @@ -4,11 +4,11 @@ | |||
| 4 | * CANN Open Software License Agreement Version 2.0 (the "License"). | 4 | * CANN Open Software License Agreement Version 2.0 (the "License"). |
| 5 | * Please refer to the License for details. You may not use this file except in compliance with the License. | 5 | * Please refer to the License for details. You may not use this file except in compliance with the License. |
| 6 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | 6 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, |
| 7 | - * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | 7 | + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. |
| 8 | * See LICENSE in the root of the software repository for the full text of the License. | 8 | * See LICENSE in the root of the software repository for the full text of the License. |
| 9 | */ | 9 | */ |
| 10 | 10 | ||
| 11 | -#include "backend/910B_CCE/backend_910b_cce.h" | 11 | +#include "backend/backend_cce.h" |
| 12 | 12 | ||
| 13 | #include "backend/common/backend.h" | 13 | #include "backend/common/backend.h" |
| 14 | #include "backend/common/soc.h" | 14 | #include "backend/common/soc.h" |
| @@ -16,15 +16,20 @@ | |||
| 16 | namespace pypto { | 16 | namespace pypto { |
| 17 | namespace backend { | 17 | namespace backend { |
| 18 | 18 | ||
| 19 | -Backend910B_CCE::Backend910B_CCE() : Backend(Create910BSoC()) | 19 | +const Backend* GetBackend() |
| 20 | { | 20 | { |
| 21 | - // Operators are registered via REGISTER_BACKEND_OP macro | 21 | + return &BackendCCE::Instance(); |
| 22 | - // in backend_910b_cce_ops.cpp during static initialization | ||
| 23 | } | 22 | } |
| 24 | 23 | ||
| 25 | -Backend910B_CCE& Backend910B_CCE::Instance() | 24 | +BackendCCE::BackendCCE() : Backend(CreateSoC()) |
| 26 | { | 25 | { |
| 27 | - static Backend910B_CCE instance; | 26 | + // Operators are registered via REGISTER_BACKEND_OP macro |
| 27 | + // in backend_cce_ops.cpp during static initialization | ||
| 28 | +} | ||
| 29 | + | ||
| 30 | +BackendCCE& BackendCCE::Instance() | ||
| 31 | +{ | ||
| 32 | + static BackendCCE instance; | ||
| 28 | return instance; | 33 | return instance; |
| 29 | } | 34 | } |
| 30 | 35 | ||
Rframework/src/interface/pypto_pro/backend/910B_CCE/backend_910b_cce_block_out_ops.cpp→framework/src/interface/pypto_pro/backend/backend_cce_block_out_ops.cpp+546-542
Rframework/src/interface/pypto_pro/backend/910B_CCE/backend_910b_cce_ops.cpp→framework/src/interface/pypto_pro/backend/backend_cce_ops.cpp+432-242
| @@ -20,10 +20,9 @@ | |||
| 20 | #include <utility> | 20 | #include <utility> |
| 21 | #include <vector> | 21 | #include <vector> |
| 22 | 22 | ||
| 23 | -#include "backend/910B_CCE/backend_910b_cce.h" | ||
| 24 | - | ||
| 25 | #include "backend/common/soc.h" | 23 | #include "backend/common/soc.h" |
| 26 | #include "core/logging.h" | 24 | #include "core/logging.h" |
| 25 | +#include "tilefwk/error.h" | ||
| 27 | #include "ir/memref.h" | 26 | #include "ir/memref.h" |
| 28 | #include "ir/pipe.h" | 27 | #include "ir/pipe.h" |
| 29 | #include "tilefwk/error.h" | 28 | #include "tilefwk/error.h" |
| @@ -68,17 +67,6 @@ std::optional<uint64_t> FindMemSizeInDie(const DieT& die, ir::MemorySpace mem_ty | |||
| 68 | 67 | ||
| 69 | } // namespace | 68 | } // namespace |
| 70 | 69 | ||
| 71 | -const Backend* GetBackendInstance(BackendType type) | ||
| 72 | -{ | ||
| 73 | - switch (type) { | ||
| 74 | - case BackendType::CCE: | ||
| 75 | - return &Backend910B_CCE::Instance(); | ||
| 76 | - default: | ||
| 77 | - CHECK(false) << "GetBackendInstance: unexpected BackendType (must be CCE)"; | ||
| 78 | - return nullptr; // unreachable | ||
| 79 | - } | ||
| 80 | -} | ||
| 81 | - | ||
| 82 | // ========== Backend Implementation ========== | 70 | // ========== Backend Implementation ========== |
| 83 | 71 | ||
| 84 | std::vector<ir::MemorySpace> Backend::FindMemPath(ir::MemorySpace from, ir::MemorySpace to) const | 72 | std::vector<ir::MemorySpace> Backend::FindMemPath(ir::MemorySpace from, ir::MemorySpace to) const |
| @@ -1,87 +0,0 @@ | |||
| 1 | -/** | ||
| 2 | - * Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 3 | - * This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 4 | - * CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 5 | - * Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 6 | - * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 7 | - * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 8 | - * See LICENSE in the root of the software repository for the full text of the License. | ||
| 9 | - */ | ||
| 10 | - | ||
| 11 | -#include "backend/common/backend_config.h" | ||
| 12 | - | ||
| 13 | -#include <mutex> | ||
| 14 | -#include <optional> | ||
| 15 | - | ||
| 16 | -#include "backend/common/backend.h" | ||
| 17 | -#include "core/logging.h" | ||
| 18 | -#include "tilefwk/error.h" | ||
| 19 | - | ||
| 20 | -namespace pypto { | ||
| 21 | -namespace backend { | ||
| 22 | - | ||
| 23 | -std::optional<BackendType> BackendConfig::backend_type_; | ||
| 24 | -std::mutex BackendConfig::mutex_; | ||
| 25 | - | ||
| 26 | -namespace { | ||
| 27 | - | ||
| 28 | -const char* BackendTypeName(BackendType type) | ||
| 29 | -{ | ||
| 30 | - switch (type) { | ||
| 31 | - case BackendType::CCE: | ||
| 32 | - return "CCE"; | ||
| 33 | - default: | ||
| 34 | - return "unknown"; | ||
| 35 | - } | ||
| 36 | -} | ||
| 37 | - | ||
| 38 | -} // namespace | ||
| 39 | - | ||
| 40 | -void BackendConfig::SetBackendType(BackendType type) | ||
| 41 | -{ | ||
| 42 | - std::scoped_lock<std::mutex> lock(mutex_); | ||
| 43 | - | ||
| 44 | - if (backend_type_.has_value()) { | ||
| 45 | - // Idempotent: allow setting the same type multiple times | ||
| 46 | - CHECK(*backend_type_ == type) << "Backend type already set to " << BackendTypeName(*backend_type_) | ||
| 47 | - << ", cannot change to " << BackendTypeName(type); | ||
| 48 | - return; | ||
| 49 | - } | ||
| 50 | - | ||
| 51 | - backend_type_ = type; | ||
| 52 | -} | ||
| 53 | - | ||
| 54 | -const Backend* BackendConfig::GetBackend() | ||
| 55 | -{ | ||
| 56 | - std::scoped_lock<std::mutex> lock(mutex_); | ||
| 57 | - | ||
| 58 | - CHECK(backend_type_.has_value()) << "Backend type not configured. " | ||
| 59 | - << "Please call SetBackendType() or use compile() with backend_type parameter."; | ||
| 60 | - | ||
| 61 | - return GetBackendInstance(*backend_type_); | ||
| 62 | -} | ||
| 63 | - | ||
| 64 | -BackendType BackendConfig::GetBackendType() | ||
| 65 | -{ | ||
| 66 | - std::scoped_lock<std::mutex> lock(mutex_); | ||
| 67 | - | ||
| 68 | - CHECK(backend_type_.has_value()) << "Backend type not configured. " | ||
| 69 | - << "Please call SetBackendType() or use compile() with backend_type parameter."; | ||
| 70 | - | ||
| 71 | - return *backend_type_; | ||
| 72 | -} | ||
| 73 | - | ||
| 74 | -bool BackendConfig::IsConfigured() | ||
| 75 | -{ | ||
| 76 | - std::scoped_lock<std::mutex> lock(mutex_); | ||
| 77 | - return backend_type_.has_value(); | ||
| 78 | -} | ||
| 79 | - | ||
| 80 | -void BackendConfig::ResetForTesting() | ||
| 81 | -{ | ||
| 82 | - std::scoped_lock<std::mutex> lock(mutex_); | ||
| 83 | - backend_type_.reset(); | ||
| 84 | -} | ||
| 85 | - | ||
| 86 | -} // namespace backend | ||
| 87 | -} // namespace pypto | ||
| @@ -4,7 +4,7 @@ | |||
| 4 | * CANN Open Software License Agreement Version 2.0 (the "License"). | 4 | * CANN Open Software License Agreement Version 2.0 (the "License"). |
| 5 | * Please refer to the License for details. You may not use this file except in compliance with the License. | 5 | * Please refer to the License for details. You may not use this file except in compliance with the License. |
| 6 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | 6 | * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, |
| 7 | - * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | 7 | + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. |
| 8 | * See LICENSE in the root of the software repository for the full text of the License. | 8 | * See LICENSE in the root of the software repository for the full text of the License. |
| 9 | */ | 9 | */ |
| 10 | 10 | ||
| @@ -37,11 +37,10 @@ void BackendRegistry::Register(const std::string& type_name, CreateFunc func) | |||
| 37 | 37 | ||
| 38 | std::unique_ptr<Backend> BackendRegistry::Create(const std::string& type_name, const std::shared_ptr<const SoC>& soc) | 38 | std::unique_ptr<Backend> BackendRegistry::Create(const std::string& type_name, const std::shared_ptr<const SoC>& soc) |
| 39 | { | 39 | { |
| 40 | - // For singleton backends, we cannot create new instances | ||
| 41 | (void)type_name; | 40 | (void)type_name; |
| 42 | (void)soc; | 41 | (void)soc; |
| 43 | throw ir::ValueError("Cannot create backend instances via registry - backends are singletons. " | 42 | throw ir::ValueError("Cannot create backend instances via registry - backends are singletons. " |
| 44 | - "Use Backend910B_CCE::Instance() instead."); | 43 | + "Use BackendCCE::Instance() instead."); |
| 45 | } | 44 | } |
| 46 | 45 | ||
| 47 | bool BackendRegistry::IsRegistered(const std::string& type_name) const | 46 | bool BackendRegistry::IsRegistered(const std::string& type_name) const |
| @@ -51,27 +50,23 @@ bool BackendRegistry::IsRegistered(const std::string& type_name) const | |||
| 51 | 50 | ||
| 52 | std::unique_ptr<Backend> CreateBackendFromRegistry(const std::string& type_name, const std::shared_ptr<const SoC>& soc) | 51 | std::unique_ptr<Backend> CreateBackendFromRegistry(const std::string& type_name, const std::shared_ptr<const SoC>& soc) |
| 53 | { | 52 | { |
| 54 | - // For singleton backends, we cannot create new instances | ||
| 55 | (void)type_name; | 53 | (void)type_name; |
| 56 | (void)soc; | 54 | (void)soc; |
| 57 | throw ir::ValueError("Cannot create backend instances via registry - backends are singletons. " | 55 | throw ir::ValueError("Cannot create backend instances via registry - backends are singletons. " |
| 58 | - "Use Backend910B_CCE::Instance() instead."); | 56 | + "Use BackendCCE::Instance() instead."); |
| 59 | } | 57 | } |
| 60 | 58 | ||
| 61 | -// Auto-register Backend910B_CCE | ||
| 62 | namespace { | 59 | namespace { |
| 63 | -bool RegisterBackend910B_CCE() | 60 | +bool RegisterBackendCCE() |
| 64 | { | 61 | { |
| 65 | - // Backend910B_CCE is a singleton, no need to register factory function | 62 | + BackendRegistry::Instance().Register("CCE", [](const std::shared_ptr<const SoC>& /*unused*/) { |
| 66 | - // Registration is kept for backward compatibility but Create() will fail | 63 | + throw ir::ValueError("Cannot create BackendCCE via registry - use BackendCCE::Instance()"); |
| 67 | - BackendRegistry::Instance().Register("910B_CCE", [](const std::shared_ptr<const SoC>& /*unused*/) { | 64 | + return std::unique_ptr<Backend>(nullptr); |
| 68 | - throw ir::ValueError("Cannot create Backend910B_CCE via registry - use Backend910B_CCE::Instance()"); | ||
| 69 | - return std::unique_ptr<Backend>(nullptr); // Never reached | ||
| 70 | }); | 65 | }); |
| 71 | return true; | 66 | return true; |
| 72 | } | 67 | } |
| 73 | 68 | ||
| 74 | -static bool backend_910b_cce_registered = RegisterBackend910B_CCE(); | 69 | +static bool backend_cce_registered = RegisterBackendCCE(); |
| 75 | } // namespace | 70 | } // namespace |
| 76 | 71 | ||
| 77 | } // namespace backend | 72 | } // namespace backend |
| @@ -243,7 +243,8 @@ std::string FormatDebugLocationHeader(const ir::Span& span, const std::string& o | |||
| 243 | 243 | ||
| 244 | bool IsSupportedPrintfConversion(char conversion) | 244 | bool IsSupportedPrintfConversion(char conversion) |
| 245 | { | 245 | { |
| 246 | - return conversion == 'd' || conversion == 'i' || conversion == 'u' || conversion == 'x' || conversion == 'f'; | 246 | + return conversion == 'd' || conversion == 'i' || conversion == 'u' || conversion == 'x' || conversion == 'f' || |
| 247 | + conversion == 'p'; | ||
| 247 | } | 248 | } |
| 248 | 249 | ||
| 249 | size_t FindPrintfConversionIndex(const std::string& format_segment) | 250 | size_t FindPrintfConversionIndex(const std::string& format_segment) |
| @@ -123,9 +123,9 @@ int SoC::TotalCoreCount() const | |||
| 123 | [](int sum, const auto& pair) { return sum + pair.first.TotalCoreCount() * pair.second; }); | 123 | [](int sum, const auto& pair) { return sum + pair.first.TotalCoreCount() * pair.second; }); |
| 124 | } | 124 | } |
| 125 | 125 | ||
| 126 | -// ========== 910B SoC Factory ========== | 126 | +// ========== SoC Factory ========== |
| 127 | 127 | ||
| 128 | -const SoC& Create910BSoC() | 128 | +const SoC& CreateSoC() |
| 129 | { | 129 | { |
| 130 | // Singleton instance shared by all backends | 130 | // Singleton instance shared by all backends |
| 131 | static SoC soc = []() { | 131 | static SoC soc = []() { |
| @@ -36,6 +36,35 @@ std::string CodeContext::GetVarName(const ir::VarPtr& var) | |||
| 36 | if (v0 != name_to_cpp_.end()) { | 36 | if (v0 != name_to_cpp_.end()) { |
| 37 | return v0->second; | 37 | return v0->second; |
| 38 | } | 38 | } |
| 39 | + // Fallback: for variables first defined inside a loop body, the post-loop | ||
| 40 | + // reference may use the raw base name while SSA registered a versioned form | ||
| 41 | + // (e.g. 'reg_dst' vs 'reg_dst_1'). Search for the highest-versioned match. | ||
| 42 | + std::string best_match; | ||
| 43 | + int best_version = -1; | ||
| 44 | + std::string prefix = var->name_ + "_"; | ||
| 45 | + for (const auto& [key, value] : name_to_cpp_) { | ||
| 46 | + if (key.size() > prefix.size() && key.compare(0, prefix.size(), prefix) == 0) { | ||
| 47 | + const char* suffix = key.c_str() + prefix.size(); | ||
| 48 | + bool all_digits = true; | ||
| 49 | + for (const char* p = suffix; *p; ++p) { | ||
| 50 | + if (*p < '0' || *p > '9') { | ||
| 51 | + all_digits = false; | ||
| 52 | + break; | ||
| 53 | + } | ||
| 54 | + } | ||
| 55 | + if (all_digits && *suffix != '\0') { | ||
| 56 | + int ver = std::atoi(suffix); | ||
| 57 | + if (ver > best_version) { | ||
| 58 | + best_version = ver; | ||
| 59 | + best_match = value; | ||
| 60 | + } | ||
| 61 | + } | ||
| 62 | + } | ||
| 63 | + } | ||
| 64 | + if (!best_match.empty()) { | ||
| 65 | + name_to_cpp_[var->name_] = best_match; | ||
| 66 | + return best_match; | ||
| 67 | + } | ||
| 39 | // Auto-register: variable may originate from a different section (Cube/Vector) | 68 | // Auto-register: variable may originate from a different section (Cube/Vector) |
| 40 | // that was cleared on section boundary. Use the sanitized IR name. | 69 | // that was cleared on section boundary. Use the sanitized IR name. |
| 41 | std::string cpp_name = SanitizeName(var); | 70 | std::string cpp_name = SanitizeName(var); |
| @@ -18,6 +18,7 @@ | |||
| 18 | 18 | ||
| 19 | #include "core/error.h" | 19 | #include "core/error.h" |
| 20 | #include "core/logging.h" | 20 | #include "core/logging.h" |
| 21 | +#include "ir/op_attr_types.h" | ||
| 21 | #include "ir/expr.h" | 22 | #include "ir/expr.h" |
| 22 | #include "ir/kind_traits.h" | 23 | #include "ir/kind_traits.h" |
| 23 | #include "ir/memref.h" | 24 | #include "ir/memref.h" |
| @@ -243,24 +244,8 @@ std::string TypeConverter::ConvertEventId(int event_id) const | |||
| 243 | 244 | ||
| 244 | std::string TypeConverter::ConvertCastRoundMode(int mode) const | 245 | std::string TypeConverter::ConvertCastRoundMode(int mode) const |
| 245 | { | 246 | { |
| 246 | - switch (mode) { | 247 | + auto m = static_cast<ir::RoundMode>(mode); |
| 247 | - case 0: | 248 | + return ir::EnumToString(m); |
| 248 | - return "RoundMode::CAST_NONE"; | ||
| 249 | - case 1: | ||
| 250 | - return "RoundMode::CAST_RINT"; | ||
| 251 | - case 2: | ||
| 252 | - return "RoundMode::CAST_ROUND"; | ||
| 253 | - case 3: | ||
| 254 | - return "RoundMode::CAST_FLOOR"; | ||
| 255 | - case 4: | ||
| 256 | - return "RoundMode::CAST_CEIL"; | ||
| 257 | - case 5: | ||
| 258 | - return "RoundMode::CAST_TRUNC"; | ||
| 259 | - case 6: | ||
| 260 | - return "RoundMode::CAST_ODD"; | ||
| 261 | - default: | ||
| 262 | - throw pypto::ir::ValueError("Cast round mode must be in range [0, 6], got " + std::to_string(mode)); | ||
| 263 | - } | ||
| 264 | } | 249 | } |
| 265 | 250 | ||
| 266 | std::string TypeConverter::ConvertTileLayout(ir::TileLayout layout) const | 251 | std::string TypeConverter::ConvertTileLayout(ir::TileLayout layout) const |
| @@ -25,5 +25,6 @@ endif () | |||
| 25 | PTO_Fwk_UTest_AddCaseLib( | 25 | PTO_Fwk_UTest_AddCaseLib( |
| 26 | TARGET ${_Target} | 26 | TARGET ${_Target} |
| 27 | SOURCES ${_Sources} | 27 | SOURCES ${_Sources} |
| 28 | + PRIVATE_INCLUDE_DIRECTORIES ${PTO_FWK_SRC_ROOT}/framework/include/pypto_pro | ||
| 28 | LINK_LIBRARIES ${LinkLibraries} | 29 | LINK_LIBRARIES ${LinkLibraries} |
| 29 | ) | 30 | ) |
| @@ -1,520 +0,0 @@ | |||
| 1 | -/** | ||
| 2 | - * Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 3 | - * This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 4 | - * CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 5 | - * Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 6 | - * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 7 | - * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 8 | - * See LICENSE in the root of the software repository for the full text of the License. | ||
| 9 | - */ | ||
| 10 | - | ||
| 11 | -/*! | ||
| 12 | - * \file test_const_fold_simplify_pass.cpp | ||
| 13 | - * \brief Coverage tests for ConstFoldAndSimplify pass (const_fold_simplify_pass.cpp) | ||
| 14 | - */ | ||
| 15 | - | ||
| 16 | -#include "gtest/gtest.h" | ||
| 17 | - | ||
| 18 | -#include <cstdint> | ||
| 19 | -#include <memory> | ||
| 20 | -#include <string> | ||
| 21 | -#include <vector> | ||
| 22 | - | ||
| 23 | -#include "core/dtype.h" | ||
| 24 | -#include "ir/expr.h" | ||
| 25 | -#include "ir/function.h" | ||
| 26 | -#include "ir/program.h" | ||
| 27 | -#include "ir/scalar_expr.h" | ||
| 28 | -#include "ir/stmt.h" | ||
| 29 | -#include "ir/transforms/passes.h" | ||
| 30 | -#include "ir/type.h" | ||
| 31 | -#include "test_ir.h" | ||
| 32 | - | ||
| 33 | -namespace pypto { | ||
| 34 | -namespace ir { | ||
| 35 | - | ||
| 36 | -static TypePtr Scalar(DataType dt) { return std::make_shared<ScalarType>(dt); } | ||
| 37 | -static Span Sp() { return Span("test", 1, 1); } | ||
| 38 | - | ||
| 39 | -class ConstFoldSimplifyPassTest : public testing::Test { | ||
| 40 | -protected: | ||
| 41 | - VarPtr MakeVar(const std::string& name) { return std::make_shared<Var>(name, Scalar(DataType::INT32), Sp()); } | ||
| 42 | - | ||
| 43 | - ExprPtr Int(int64_t value) { return std::make_shared<ConstInt>(value, DataType::INT32, Sp()); } | ||
| 44 | - | ||
| 45 | - FunctionPtr MakeFunc(const std::string& name, const StmtPtr& body) | ||
| 46 | - { | ||
| 47 | - auto x = std::make_shared<Var>("x", Scalar(DataType::INT32), Sp()); | ||
| 48 | - return std::make_shared<Function>(name, std::vector<VarPtr>{x}, std::vector<TypePtr>{Scalar(DataType::INT32)}, | ||
| 49 | - body, Sp()); | ||
| 50 | - } | ||
| 51 | - | ||
| 52 | - ProgramPtr MakeProg(const FunctionPtr& func) | ||
| 53 | - { | ||
| 54 | - return std::make_shared<Program>(std::vector<FunctionPtr>{func}, "prog", Sp()); | ||
| 55 | - } | ||
| 56 | - | ||
| 57 | - ProgramPtr RunPass(const ProgramPtr& prog) | ||
| 58 | - { | ||
| 59 | - auto p = pass::ConstFoldAndSimplify(); | ||
| 60 | - return p(prog); | ||
| 61 | - } | ||
| 62 | - | ||
| 63 | - FunctionPtr RunOnFunc(const FunctionPtr& func) | ||
| 64 | - { | ||
| 65 | - auto result = RunPass(MakeProg(func)); | ||
| 66 | - return result->GetFunction(func->name_); | ||
| 67 | - } | ||
| 68 | - | ||
| 69 | - ExprPtr RunAssignValue(const ExprPtr& value) | ||
| 70 | - { | ||
| 71 | - auto assign = std::make_shared<AssignStmt>(MakeVar("res"), value, Sp()); | ||
| 72 | - auto result_func = RunOnFunc(MakeFunc("f", assign)); | ||
| 73 | - if (!result_func || result_func->body_->stmts_.empty()) { | ||
| 74 | - ADD_FAILURE() << "ConstFoldAndSimplify did not return an assignment"; | ||
| 75 | - return nullptr; | ||
| 76 | - } | ||
| 77 | - auto result_assign = std::dynamic_pointer_cast<const AssignStmt>(result_func->body_->stmts_[0]); | ||
| 78 | - if (!result_assign) { | ||
| 79 | - ADD_FAILURE() << "ConstFoldAndSimplify result is not an AssignStmt"; | ||
| 80 | - return nullptr; | ||
| 81 | - } | ||
| 82 | - return result_assign->value_; | ||
| 83 | - } | ||
| 84 | -}; | ||
| 85 | - | ||
| 86 | -// ============================================================================ | ||
| 87 | -// Constant folding: scalar arithmetic and comparisons | ||
| 88 | -// ============================================================================ | ||
| 89 | - | ||
| 90 | -TEST_F(ConstFoldSimplifyPassTest, TestFoldConstantExpressions) | ||
| 91 | -{ | ||
| 92 | - struct Case { | ||
| 93 | - std::string name; | ||
| 94 | - ExprPtr expr; | ||
| 95 | - int64_t expected; | ||
| 96 | - }; | ||
| 97 | - std::vector<Case> cases{ | ||
| 98 | - {"add", std::make_shared<Add>(Int(3), Int(7), DataType::INT32, Sp()), 10}, | ||
| 99 | - {"sub", std::make_shared<Sub>(Int(10), Int(3), DataType::INT32, Sp()), 7}, | ||
| 100 | - {"mul", std::make_shared<Mul>(Int(4), Int(5), DataType::INT32, Sp()), 20}, | ||
| @@ -1,510 +0,0 @@ | |||
| 1 | -/** | ||
| 2 | - * Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 3 | - * This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 4 | - * CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 5 | - * Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 6 | - * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 7 | - * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 8 | - * See LICENSE in the root of the software repository for the full text of the License. | ||
| 9 | - */ | ||
| 10 | - | ||
| 11 | -/*! | ||
| 12 | - * \file test_lower_break_continue_pass.cpp | ||
| 13 | - * \brief Coverage tests for LowerBreakContinue pass (lower_break_continue_pass.cpp) | ||
| 14 | - */ | ||
| 15 | - | ||
| 16 | -#include "gtest/gtest.h" | ||
| 17 | - | ||
| 18 | -#include <memory> | ||
| 19 | -#include <optional> | ||
| 20 | -#include <string> | ||
| 21 | -#include <vector> | ||
| 22 | - | ||
| 23 | -#include "core/dtype.h" | ||
| 24 | -#include "ir/expr.h" | ||
| 25 | -#include "ir/function.h" | ||
| 26 | -#include "ir/kind_traits.h" | ||
| 27 | -#include "ir/program.h" | ||
| 28 | -#include "ir/scalar_expr.h" | ||
| 29 | -#include "ir/stmt.h" | ||
| 30 | -#include "ir/transforms/passes.h" | ||
| 31 | -#include "ir/type.h" | ||
| 32 | -#include "test_ir.h" | ||
| 33 | - | ||
| 34 | -namespace pypto { | ||
| 35 | -namespace ir { | ||
| 36 | - | ||
| 37 | -static TypePtr Scalar(DataType dt) { return std::make_shared<ScalarType>(dt); } | ||
| 38 | -static Span Sp() { return Span("test", 1, 1); } | ||
| 39 | - | ||
| 40 | -class LowerBreakContinuePassTest : public testing::Test { | ||
| 41 | -protected: | ||
| 42 | - VarPtr MakeVar(const std::string& name, TypePtr type = Scalar(DataType::INT32)) | ||
| 43 | - { | ||
| 44 | - return std::make_shared<Var>(name, type, Sp()); | ||
| 45 | - } | ||
| 46 | - | ||
| 47 | - ExprPtr Int(int64_t value) { return std::make_shared<ConstInt>(value, DataType::INT32, Sp()); } | ||
| 48 | - | ||
| 49 | - ExprPtr Bool(bool value) { return std::make_shared<ConstBool>(value, Sp()); } | ||
| 50 | - | ||
| 51 | - FunctionPtr MakeFunc(const std::string& name, const StmtPtr& body) | ||
| 52 | - { | ||
| 53 | - auto x = std::make_shared<Var>("x", Scalar(DataType::INT32), Sp()); | ||
| 54 | - return std::make_shared<Function>(name, std::vector<VarPtr>{x}, std::vector<TypePtr>{}, body, Sp()); | ||
| 55 | - } | ||
| 56 | - | ||
| 57 | - ProgramPtr MakeProg(const FunctionPtr& func) | ||
| 58 | - { | ||
| 59 | - return std::make_shared<Program>(std::vector<FunctionPtr>{func}, "prog", Sp()); | ||
| 60 | - } | ||
| 61 | - | ||
| 62 | - ProgramPtr RunPass(const ProgramPtr& prog) | ||
| 63 | - { | ||
| 64 | - auto p = pass::LowerBreakContinue(); | ||
| 65 | - return p(prog); | ||
| 66 | - } | ||
| 67 | - | ||
| 68 | - FunctionPtr RunOnFunc(const FunctionPtr& func) | ||
| 69 | - { | ||
| 70 | - auto result = RunPass(MakeProg(func)); | ||
| 71 | - return result->GetFunction(func->name_); | ||
| 72 | - } | ||
| 73 | - | ||
| 74 | - ExprPtr LowerContinueGuardCondition(const ExprPtr& cond) | ||
| 75 | - { | ||
| 76 | - auto i = MakeVar("i"); | ||
| 77 | - auto if_cont = std::make_shared<IfStmt>(cond, std::make_shared<ContinueStmt>(Sp()), std::nullopt, | ||
| 78 | - std::vector<VarPtr>{}, Sp()); | ||
| 79 | - auto assign = std::make_shared<AssignStmt>(MakeVar("y"), i, Sp()); | ||
| 80 | - auto body = std::make_shared<SeqStmts>(std::vector<StmtPtr>{if_cont, assign}, Sp()); | ||
| 81 | - auto for_stmt = std::make_shared<ForStmt>(i, Int(0), Int(4), Int(1), std::vector<IterArgPtr>{}, body, | ||
| 82 | - std::vector<VarPtr>{}, Sp()); | ||
| 83 | - auto result_func = RunOnFunc(MakeFunc("f", for_stmt)); | ||
| 84 | - if (!result_func) { | ||
| 85 | - return nullptr; | ||
| 86 | - } | ||
| 87 | - auto result_for = std::dynamic_pointer_cast<const ForStmt>(result_func->body_->stmts_[0]); | ||
| 88 | - EXPECT_NE(result_for, nullptr); | ||
| 89 | - if (!result_for || result_for->body_->stmts_.empty()) { | ||
| 90 | - return nullptr; | ||
| 91 | - } | ||
| 92 | - auto guard_if = std::dynamic_pointer_cast<const IfStmt>(result_for->body_->stmts_[0]); | ||
| 93 | - EXPECT_NE(guard_if, nullptr); | ||
| 94 | - return guard_if ? guard_if->condition_ : nullptr; | ||
| 95 | - } | ||
| 96 | - | ||
| 97 | - bool ContainsNodeOfKind(const StmtPtr& stmt, const std::string& kind) | ||
| 98 | - { | ||
| 99 | - if (!stmt) | ||
| 100 | - return false; | ||
| @@ -0,0 +1,52 @@ | |||
| 1 | +/** | ||
| 2 | + * Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 3 | + * This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 4 | + * CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 5 | + * Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 6 | + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 7 | + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 8 | + * See LICENSE in the root of the software repository for the full text of the License. | ||
| 9 | + */ | ||
| 10 | + | ||
| 11 | +#include "gtest/gtest.h" | ||
| 12 | + | ||
| 13 | +#include "backend/common/backend_registry.h" | ||
| 14 | +#include "backend/common/backend_utils.h" | ||
| 15 | +#include "backend/common/soc.h" | ||
| 16 | +#include "core/error.h" | ||
| 17 | + | ||
| 18 | +namespace pypto { | ||
| 19 | +namespace backend { | ||
| 20 | + | ||
| 21 | +TEST(BackendCommonTest, RegistersCCEAsSingletonBackend) | ||
| 22 | +{ | ||
| 23 | + auto& registry = BackendRegistry::Instance(); | ||
| 24 | + EXPECT_TRUE(registry.IsRegistered("CCE")); | ||
| 25 | + EXPECT_FALSE(registry.IsRegistered("910B_CCE")); | ||
| 26 | + EXPECT_THROW(registry.Create("CCE", nullptr), ir::ValueError); | ||
| 27 | + EXPECT_THROW(CreateBackendFromRegistry("CCE", nullptr), ir::ValueError); | ||
| 28 | +} | ||
| 29 | + | ||
| 30 | +TEST(BackendCommonTest, CreatesSingletonSoC) | ||
| 31 | +{ | ||
| 32 | + const SoC& first = CreateSoC(); | ||
| 33 | + const SoC& second = CreateSoC(); | ||
| 34 | + | ||
| 35 | + EXPECT_EQ(&first, &second); | ||
| 36 | + EXPECT_GT(first.TotalDieCount(), 0); | ||
| 37 | + EXPECT_GT(first.TotalCoreCount(), 0); | ||
| 38 | +} | ||
| 39 | + | ||
| 40 | +TEST(BackendCommonTest, SupportsPointerPrintfConversion) | ||
| 41 | +{ | ||
| 42 | + EXPECT_TRUE(debug_printf::IsSupportedPrintfConversion('p')); | ||
| 43 | + EXPECT_EQ(debug_printf::FindPrintfConversionIndex("address=%p"), 9); | ||
| 44 | + | ||
| 45 | + auto segments = debug_printf::ParsePrintfSegments("address=%p"); | ||
| 46 | + ASSERT_EQ(segments.size(), 1); | ||
| 47 | + EXPECT_EQ(segments[0].format_segment, "address=%p"); | ||
| 48 | + EXPECT_EQ(segments[0].conversion, 'p'); | ||
| 49 | +} | ||
| 50 | + | ||
| 51 | +} // namespace backend | ||
| 52 | +} // namespace pypto | ||
【openlibing.ci】检测到当前PR中存在代码检查告警抑制 4 处,详情见下表,请Committer检视合理性。 / Detected 4 code check alert suppression(s) in this PR, see table below. Committers please review.
frontend/a5/fa/test_fa_perf_tkv_preload_dn_vf_bufid_dynrank.py
if HasAtten == 1: # noqa: F821frontend/a5/fa/test_fa_perf_tkv_preload_dn_vf_bufid_dynrank.py
if HasAtten == 1: # noqa: F821frontend/a5/fa/test_fa_perf_tkv_preload_dn_vf_bufid_dynrank.py
p_dtype_back_db, p_mat_db, sub_id, tensor_attn_mask, mask_db, HasAtten) # noqa: F821frontend/a5/fa/test_fa_tilingkey_attn_mask.py
p_f16_back_db, p_mat_db, sub_id, attn_mask, mask_db, NeedAttnMask) # noqa: F821