Merged
feat(pypto_pro): add tile_group auto mutex-id #6209
独吾Add on Sep 12
feat(pypto_pro): add tile_group auto mutex-id #6209
Merged
独吾Add on Sep 12
Total: 33 files changed+4167-1193
@@ -0,0 +1,60 @@
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_IR_TRANSFORMS_AUTO_MUTEX_ID_MANAGER_H_
12+#define PYPTO_IR_TRANSFORMS_AUTO_MUTEX_ID_MANAGER_H_
13+ 
14+#include <memory>
15+#include <string>
16+#include <vector>
17+ 
18+#include "ir/expr.h"
19+#include "ir/program.h"
20+#include "ir/span.h"
21+ 
22+namespace pypto {
23+namespace ir {
24+ 
25+/**
26+ * \brief Collect TileGroup memory ranges, allocate AUTO mutex IDs, and resolve placeholders.
27+ *
28+ * One manager belongs to one target Program, so Cube and Vector keep independent
29+ * 0-31 mutex-ID pools. Logical Tiles are identified by their IR expression
30+ * pointers; physical aliasing is determined from the TileType MemRef range.
31+ */
32+class AutoMutexIdManager {
33+public:
34+ AutoMutexIdManager();
35+ ~AutoMutexIdManager();
36+ 
37+ AutoMutexIdManager(const AutoMutexIdManager&) = delete;
38+ AutoMutexIdManager& operator=(const AutoMutexIdManager&) = delete;
39+ 
40+ /** Collect a TileGroup using the mutex-ID expressions created by the frontend. */
41+ void CollectGroup(const std::vector<ExprPtr>& tiles, const MakeTuplePtr& mutexIds, const std::string& groupName);
42+ 
43+ /** Record the effective mutex-ID candidates for each Tile operand of one operation. */
44+ void RecordOpConstraints(const std::vector<MakeTuplePtr>& tileIdGroups,
45+ const std::vector<MakeTuplePtr>& candidateGroups);
46+ 
47+ ProgramPtr AssignMutexIds(const ProgramPtr& program);
48+ 
49+ /** Source span associated with the most recent user-facing planning failure. */
50+ [[nodiscard]] Span DiagnosticSpan() const;
51+ 
52+private:
53+ class Impl;
54+ std::unique_ptr<Impl> impl_;
55+};
56+ 
57+} // namespace ir
58+} // namespace pypto
59+ 
60+#endif // PYPTO_IR_TRANSFORMS_AUTO_MUTEX_ID_MANAGER_H_
@@ -41,6 +41,49 @@ bool IsIntScalar(const ExprPtr& expr)
41 return scalar_type && (scalar_type->dtype_.IsInt() || scalar_type->dtype_ == DataType::INDEX);41 return scalar_type && (scalar_type->dtype_.IsInt() || scalar_type->dtype_ == DataType::INDEX);
42}42}
43 43 
44+TypePtr DeduceMutexDynType(const std::vector<ExprPtr>& args,
45+ [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs)
46+{
47+ PRO_IR_CHECK(ExternalError::INVALID_ARGUMENT, args.size() == 1 || args.size() == 2)
48+ << "dynamic mutex requires either mutex_id, or mutex_id and candidate_group arguments";
49+ if (args.size() == 1) {
50+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, IsIntScalar(args[0]))
51+ << "manual mutex_id must be an integer scalar expression";
52+ return GetUnknownType();
53+ }
54+ 
55+ auto mutexId = As<MakeTuple>(args[0]);
56+ auto candidateGroups = As<MakeTuple>(args[1]);
57+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, mutexId != nullptr && candidateGroups != nullptr)
58+ << "dynamic mutex arguments must be tuples";
59+ PRO_IR_CHECK(ExternalError::INVALID_SHAPE, !mutexId->elements_.empty())
60+ << "mutex_id must contain at least one Tile group";
61+ 
62+ for (const auto& tileMutexIdExpr : mutexId->elements_) {
63+ auto tileMutexId = As<MakeTuple>(tileMutexIdExpr);
64+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, tileMutexId != nullptr && !tileMutexId->elements_.empty())
65+ << "each mutex_id Tile group must be a non-empty tuple";
66+ for (const auto& mutexIdExpr : tileMutexId->elements_) {
67+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, IsIntScalar(mutexIdExpr))
68+ << "mutex_id elements must be integer scalar expressions";
69+ }
70+ }
71+ 
72+ PRO_IR_CHECK(ExternalError::INVALID_SHAPE,
73+ !candidateGroups->elements_.empty() && candidateGroups->elements_.size() == mutexId->elements_.size())
74+ << "candidate_group must contain one group per mutex_id Tile";
75+ for (const auto& groupExpr : candidateGroups->elements_) {
76+ auto group = As<MakeTuple>(groupExpr);
77+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, group != nullptr && !group->elements_.empty())
78+ << "each candidate_group Tile group must be a non-empty tuple";
79+ for (const auto& candidate : group->elements_) {
80+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, IsIntScalar(candidate))
81+ << "candidate_group elements must be integer scalar expressions";
82+ }
83+ }
84+ return GetUnknownType();
85+}
86+ 
44bool IsDcciTensorOffset(const ExprPtr& offset)87bool IsDcciTensorOffset(const ExprPtr& offset)
45{88{
46 if (IsIntScalar(offset)) {89 if (IsIntScalar(offset)) {
@@ -230,23 +273,21 @@ REGISTER_OP("system.dcci")
230 273 
231// Register system.mutex_lock_dyn (Mutex::Lock, A5)274// Register system.mutex_lock_dyn (Mutex::Lock, A5)
232REGISTER_OP("system.mutex_lock_dyn")275REGISTER_OP("system.mutex_lock_dyn")
233- .set_description("Acquire Mutex buffer-id token with a mutex_id expression (A5)")276+ .set_description("Acquire per-Tile Mutex buffer-id tokens with codegen-side deduplication (A5)")
234 .set_op_category("SyncOp")277 .set_op_category("SyncOp")
235- .add_argument("mutex_id", "Mutex ID expression (integer ScalarType)")278+ .add_argument("mutex_id", "Integer scalar for manual mutex, or two-dimensional tuple grouped by Tile")
279+ .add_argument("candidate_group", "Optional two-dimensional tuple of candidate IDs for automatic mutex")
236 .set_attr<int>("pipe")280 .set_attr<int>("pipe")
237- .set_attr<std::vector<int>>("mutex_ids")281+ .f_deduce_type(DeduceMutexDynType);
238- .set_attr<std::vector<int>>("mutex_id_owner_indices")
239- .f_deduce_type(DeduceUnknownType);
240 282 
241// Register system.mutex_unlock_dyn (Mutex::Unlock, A5)283// Register system.mutex_unlock_dyn (Mutex::Unlock, A5)
242REGISTER_OP("system.mutex_unlock_dyn")284REGISTER_OP("system.mutex_unlock_dyn")
243- .set_description("Release Mutex buffer-id token with a mutex_id expression (A5)")285+ .set_description("Release per-Tile Mutex buffer-id tokens with codegen-side deduplication (A5)")
244 .set_op_category("SyncOp")286 .set_op_category("SyncOp")
245- .add_argument("mutex_id", "Mutex ID expression (integer ScalarType)")287+ .add_argument("mutex_id", "Integer scalar for manual mutex, or two-dimensional tuple grouped by Tile")
288+ .add_argument("candidate_group", "Optional two-dimensional tuple of candidate IDs for automatic mutex")
246 .set_attr<int>("pipe")289 .set_attr<int>("pipe")
247- .set_attr<std::vector<int>>("mutex_ids")290+ .f_deduce_type(DeduceMutexDynType);
248- .set_attr<std::vector<int>>("mutex_id_owner_indices")
249- .f_deduce_type(DeduceUnknownType);
250 291 
251// ============================================================================292// ============================================================================
252// Mask Control Ops — CCE-mode only293// Mask Control Ops — CCE-mode only
@@ -0,0 +1,678 @@
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 "ir/transforms/auto_mutex_id_manager.h"
12+ 
13+#include <algorithm>
14+#include <array>
15+#include <cstdint>
16+#include <limits>
17+#include <numeric>
18+#include <optional>
19+#include <set>
20+#include <sstream>
21+#include <tuple>
22+#include <unordered_map>
23+#include <utility>
24+ 
25+#include "ir/kind_traits.h"
26+#include "ir/memref.h"
27+#include "ir/transforms/base/mutator.h"
28+#include "ir/type.h"
29+#include "pypto_pro/error.h"
30+ 
31+namespace pypto {
32+namespace ir {
33+ 
34+using npu::tile_fwk::ExternalError;
35+ 
36+namespace {
37+ 
38+constexpr int kMutexIdCount = 32;
39+ 
40+class PlaceholderResolver final : public IRMutator {
41+public:
42+ explicit PlaceholderResolver(const std::vector<std::pair<VarPtr, int>>& replacements)
43+ {
44+ for (const auto& [placeholder, value] : replacements) {
45+ placeholderValues_[placeholder.get()] = value;
46+ }
47+ }
48+ 
49+protected:
50+ using IRMutator::VisitExpr_;
51+ 
52+ ExprPtr VisitExpr_(const VarPtr& op) override
53+ {
54+ auto it = placeholderValues_.find(op.get());
55+ if (it == placeholderValues_.end()) {
56+ // Ordinary SSA Vars are not mutex placeholders and must remain unchanged.
57+ return IRMutator::VisitExpr_(op);
58+ }
59+ return std::make_shared<const ConstInt>(it->second, DataType::INT64, op->span_);
60+ }
61+ 
62+private:
63+ std::unordered_map<const Var*, int> placeholderValues_;
64+};
65+ 
66+std::string HexRange(int64_t start, int64_t end)
67+{
68+ std::ostringstream os;
69+ os << "[0x" << std::hex << start << ", 0x" << end << ")";
70+ return os.str();
71+}
72+ 
73+} // namespace
74+ 
75+class AutoMutexIdManager::Impl {
76+public:
77+ struct TileMutexId {
78+ VarPtr placeholder;
79+ std::vector<int> manualIds;
80+ 
81+ bool IsAuto() const { return placeholder != nullptr; }
82+ };
83+ 
84+ struct TileRecord {
85+ MemorySpace memorySpace;
86+ int64_t start;
87+ int64_t end;
88+ std::vector<int> manualIds;
89+ VarPtr placeholder;
90+ std::string groupName;
91+ Span span;
92+ 
93+ bool IsAuto() const { return placeholder != nullptr; }
94+ };
95+ 
96+ struct CandidateGroup {
97+ std::vector<VarPtr> autoPlaceholders;
98+ std::vector<int> manualIds;
99+ };
100+ 
@@ -396,19 +396,31 @@ StmtPtr SanitizerInstrumenter::RecordMutex(const CallPtr& call)
396{396{
397 bool is_lock = (call->name_ == "system.mutex_lock_dyn");397 bool is_lock = (call->name_ == "system.mutex_lock_dyn");
398 int pipe = call->GetKwarg<int>("pipe", 0);398 int pipe = call->GetKwarg<int>("pipe", 0);
399- // One record per mutex_id argument (a deduped auto_mutex call carries
400- // one id per tile group); single-id calls keep the one-statement shape.
401 std::vector<StmtPtr> logs;399 std::vector<StmtPtr> logs;
402- for (const auto& mutex_id : call->args_) {400+ auto recordMutexId = [&](const ExprPtr& mutexId) {
403 std::vector<ExprPtr> fields;401 std::vector<ExprPtr> fields;
404- fields.push_back(mutex_id);402+ fields.push_back(mutexId);
405 fields.push_back(Int64Const(pipe));403 fields.push_back(Int64Const(pipe));
406 fields.push_back(Int64Const(is_lock ? 1 : 0));404 fields.push_back(Int64Const(is_lock ? 1 : 0));
407 logs.push_back(405 logs.push_back(
408 MakeLogStmt(static_cast<uint32_t>(SanitizerDetection::MutexAccess), std::move(fields), call->span_));406 MakeLogStmt(static_cast<uint32_t>(SanitizerDetection::MutexAccess), std::move(fields), call->span_));
407+ };
408+ 
409+ if (call->args_.size() == 1) {
410+ recordMutexId(call->args_[0]);
411+ return SeqStmts::Flatten(std::move(logs), call->span_);
412+ }
413+ 
414+ auto mutexId = As<MakeTuple>(call->args_[0]);
415+ 
416+ // candidate_group is compile-time metadata. Emit one record for every
417+ // actual mutex ID while preserving each Tile's required-ID ordering.
418+ for (const auto& tileMutexIdExpr : mutexId->elements_) {
419+ auto tileMutexId = As<MakeTuple>(tileMutexIdExpr);
420+ for (const auto& mutexIdExpr : tileMutexId->elements_) {
421+ recordMutexId(mutexIdExpr);
422+ }
409 }423 }
410- if (logs.empty())
411- return nullptr;
412 return SeqStmts::Flatten(std::move(logs), call->span_);424 return SeqStmts::Flatten(std::move(logs), call->span_);
413}425}
414 426 
@@ -16,6 +16,7 @@
16 * Each registration specifies the pipe type and CCE codegen function.16 * Each registration specifies the pipe type and CCE codegen function.
17 */17 */
18 18 
19+#include <algorithm>
19#include <any>20#include <any>
20#include <cstddef>21#include <cstddef>
21#include <cstdint>22#include <cstdint>
@@ -1974,69 +1975,127 @@ REGISTER_BACKEND_OP(BackendCCE, "block.subview")
1974// API: get_buf(PIPE_MTE2, mutexId, 0); rls_buf(PIPE_MTE2, mutexId, 0);1975// API: get_buf(PIPE_MTE2, mutexId, 0); rls_buf(PIPE_MTE2, mutexId, 0);
1975// ============================================================================1976// ============================================================================
1976 1977 
1978+using MutexIdExprs = std::vector<std::vector<ir::ExprPtr>>;
1979+ 
1980+static std::vector<int> GetEffectiveCandidateIds(const ir::ExprPtr& mutexId, const std::vector<int>& tileCandidates)
1981+{
1982+ auto staticId = ir::As<ir::ConstInt>(mutexId);
1983+ if (staticId != nullptr) {
1984+ return {static_cast<int>(staticId->value_)};
1985+ }
1986+ return tileCandidates;
1987+}
1988+ 
1989+static bool CandidateGroupsOverlap(const std::vector<int>& left, const std::vector<int>& right)
1990+{
1991+ return std::any_of(left.begin(), left.end(),
1992+ [&](int value) { return std::find(right.begin(), right.end(), value) != right.end(); });
1993+}
1994+ 
1995+static std::vector<int> MergeCandidateGroups(const std::vector<std::vector<int>>& groups)
1996+{
1997+ std::vector<int> result;
1998+ for (const auto& group : groups) {
1999+ for (int value : group) {
2000+ if (std::find(result.begin(), result.end(), value) == result.end()) {
2001+ result.push_back(value);
2002+ }
2003+ }
2004+ }
2005+ return result;
2006+}
2007+ 
1977static std::string MakeMutexBufCodegenCCE(const ir::CallPtr& op, codegen::CodegenBase& codegen_base,2008static std::string MakeMutexBufCodegenCCE(const ir::CallPtr& op, codegen::CodegenBase& codegen_base,
1978 const std::string& intrinsic)2009 const std::string& intrinsic)
1979{2010{
1980 auto& codegen = dynamic_cast<codegen::CCECodegen&>(codegen_base);2011 auto& codegen = dynamic_cast<codegen::CCECodegen&>(codegen_base);
1981 auto pipe = static_cast<ir::PipeType>(op->GetKwarg<int>("pipe"));2012 auto pipe = static_cast<ir::PipeType>(op->GetKwarg<int>("pipe"));
2013+ PRO_CODEGEN_CHECK(ExternalError::INVALID_ARGUMENT, op->args_.size() == 1 || op->args_.size() == 2)
2014+ << "dynamic mutex requires either mutex_id, or mutex_id and candidate_group arguments";
1982 2015 
1983- std::vector<int> mutex_ids = op->GetKwarg<std::vector<int>>("mutex_ids");2016+ std::string pipeStr = PipeTypeToCCEString(pipe);
1984- // Candidate IDs are attached only by the auto-mutex path. A manual mutex op2017+ if (op->args_.size() == 1) {
1985- // has no candidate set and must always be emitted, including on PIPE_V.2018+ std::string mutexIdCode = codegen.GetExprAsCode(op->args_[0]);
1986- if (!mutex_ids.empty() && codegen.ShouldSkipVPipeMutex(pipe, mutex_ids))2019+ codegen.Emit(intrinsic + "(" + pipeStr + ", " + mutexIdCode + ", 0);");
1987- return "";
1988- 
1989- std::string pipe_str = PipeTypeToCCEString(pipe);
1990- 
1991- // N-way cross-Tile dedup: mutex IDs owned by one Tile are already known distinct.
1992- // Compare only across Tiles so each unique mutex_id is acquired and released once.
1993- // Without cross-Tile dedup, two get_buf(pipe, same_id) on the same pipe hang the hardware.
1994- if (op->args_.size() >= 2) {
1995- std::vector<std::string> id_exprs;
1996- id_exprs.reserve(op->args_.size());
1997- for (const auto& arg : op->args_) {
1998- id_exprs.push_back(codegen.GetExprAsCode(arg));
1999- }
2000- // Backward-compatible default: without owner metadata every expression
2001- // has a separate owner, preserving the original all-pairs dedup.
2002- std::vector<int> mutex_id_owner_indices(id_exprs.size());
2003- for (size_t i = 0; i < mutex_id_owner_indices.size(); ++i) {
2004- mutex_id_owner_indices[i] = static_cast<int>(i);
2005- }
2006- for (const auto& [key, value] : op->kwargs_) {
2007- if (key == "mutex_id_owner_indices") {
2008- mutex_id_owner_indices = std::any_cast<std::vector<int>>(value);
2009- break;
2010- }
2011- }
2012- PRO_CODEGEN_CHECK(ExternalError::INVALID_ARGUMENT, mutex_id_owner_indices.size() == id_exprs.size())
2013- << "mutex_id_owner_indices size must match dynamic mutex args size";
2014- 
2015- auto emit_id = [&](size_t i) {
2016- std::string condition;
2017- for (size_t j = 0; j < i; ++j) {
2018- // IDs owned by one Tile are guaranteed distinct by the frontend.
2019- if (mutex_id_owner_indices[i] == mutex_id_owner_indices[j])
2020- continue;
2021- if (!condition.empty())
2022- condition += " && ";
2023- condition += "(" + id_exprs[i] + " != " + id_exprs[j] + ")";
2024- }
2025- if (condition.empty()) {
2026- codegen.Emit(intrinsic + "(" + pipe_str + ", " + id_exprs[i] + ", 0);");
2027- return;
2028- }
2029- codegen.Emit("if (" + condition + ") {");
2030- codegen.Emit(" " + intrinsic + "(" + pipe_str + ", " + id_exprs[i] + ", 0);");
2031- codegen.Emit("}");
2032- };
2033- for (size_t i = 0; i < id_exprs.size(); ++i)
2034- emit_id(i);
2035 return "";2020 return "";
2036 }2021 }
2037 2022 
2038- std::string mutex_id_expr = codegen.GetExprAsCode(op->args_[0]);2023+ auto mutexIdTuple = ir::As<ir::MakeTuple>(op->args_[0]);
2039- codegen.Emit(intrinsic + "(" + pipe_str + ", " + mutex_id_expr + ", 0);");2024+ auto candidateTuple = ir::As<ir::MakeTuple>(op->args_[1]);
2025+ 
2026+ MutexIdExprs mutexId;
2027+ std::vector<std::vector<int>> candidateGroups;
2028+ mutexId.reserve(mutexIdTuple->elements_.size());
2029+ candidateGroups.reserve(mutexIdTuple->elements_.size());
2030+ for (size_t tile = 0; tile < mutexIdTuple->elements_.size(); ++tile) {
2031+ auto tileIds = ir::As<ir::MakeTuple>(mutexIdTuple->elements_[tile]);
2032+ auto tileCandidates = ir::As<ir::MakeTuple>(candidateTuple->elements_[tile]);
2033+ std::vector<int> candidate;
2034+ candidate.reserve(tileCandidates->elements_.size());
2035+ for (const auto& candidateExpr : tileCandidates->elements_) {
2036+ int value = static_cast<int>(ir::As<ir::ConstInt>(candidateExpr)->value_);
2037+ if (std::find(candidate.begin(), candidate.end(), value) == candidate.end()) {
2038+ candidate.push_back(value);
2039+ }
2040+ }
2041+ mutexId.push_back(tileIds->elements_);
2042+ candidateGroups.push_back(std::move(candidate));
2043+ }
2044+ 
2045+ auto candidateIds = MergeCandidateGroups(candidateGroups);
2046+ if (codegen.ShouldSkipVPipeMutex(pipe, candidateIds)) {
2047+ return "";
2048+ }
2049+ 
2050+ std::vector<std::vector<std::string>> idExprs;
2051+ idExprs.reserve(mutexId.size());
2052+ for (const auto& tileMutexId : mutexId) {
2053+ std::vector<std::string> expressions;
2054+ expressions.reserve(tileMutexId.size());
2055+ for (const auto& mutexIdExpr : tileMutexId) {
2056+ expressions.push_back(codegen.GetExprAsCode(mutexIdExpr));
2057+ }
2058+ idExprs.push_back(std::move(expressions));
2059+ }
2060+ 
2061+ for (size_t tile = 0; tile < mutexId.size(); ++tile) {
2062+ for (size_t id = 0; id < mutexId[tile].size(); ++id) {
2063+ const auto& currentExpr = mutexId[tile][id];
2064+ const auto& currentCode = idExprs[tile][id];
2065+ bool duplicate = false;
2066+ std::string condition;
poorwill
poorwillpoorwillSep 26

effective candidate应该在这里调用,如果是常量id,candidate为自身,否则为所在group的candidate,前面candidate修正的逻辑可以删了

likedislike
2067+ auto currentCandidates = GetEffectiveCandidateIds(currentExpr, candidateGroups[tile]);
2068+ for (size_t priorTile = 0; priorTile < tile && !duplicate; ++priorTile) {
2069+ for (size_t priorId = 0; priorId < mutexId[priorTile].size(); ++priorId) {
2070+ const auto& priorCode = idExprs[priorTile][priorId];
2071+ if (currentCode == priorCode) {
2072+ duplicate = true;
2073+ break;
2074+ }
2075+ auto priorCandidates = GetEffectiveCandidateIds(mutexId[priorTile][priorId],
2076+ candidateGroups[priorTile]);
2077+ bool candidatesOverlap = CandidateGroupsOverlap(currentCandidates, priorCandidates);
2078+ if (!candidatesOverlap) {
2079+ continue;
2080+ }
2081+ if (!condition.empty()) {
2082+ condition += " && ";
2083+ }
2084+ condition += "(" + currentCode + " != " + priorCode + ")";
2085+ }
2086+ }
2087+ if (duplicate) {
2088+ continue;
2089+ }
2090+ if (condition.empty()) {
2091+ codegen.Emit(intrinsic + "(" + pipeStr + ", " + currentCode + ", 0);");
2092+ continue;
2093+ }
2094+ codegen.Emit("if (" + condition + ") {");
2095+ codegen.Emit(" " + intrinsic + "(" + pipeStr + ", " + currentCode + ", 0);");
2096+ codegen.Emit("}");
2097+ }
2098+ }
2040 return "";2099 return "";
2041}2100}
2042 2101 
@@ -10,6 +10,7 @@
10 10 
11#include "codegen/cce/cce_codegen.h"11#include "codegen/cce/cce_codegen.h"
12 12 
13+#include <algorithm>
13#include <cctype>14#include <cctype>
14#include <cmath>15#include <cmath>
15#include <cstddef>16#include <cstddef>
@@ -2798,13 +2799,41 @@ public:
2798 {2799 {
2799 const std::string& name = op->name_;2800 const std::string& name = op->name_;
2800 bool is_mutex = (name == "system.mutex_lock_dyn" || name == "system.mutex_unlock_dyn");2801 bool is_mutex = (name == "system.mutex_lock_dyn" || name == "system.mutex_unlock_dyn");
2801- if (!is_mutex) {2802+ // One-argument manual mutexes do not participate in automatic V-pipe elision.
2803+ if (!is_mutex || op->args_.size() != 2) {
2802 return;2804 return;
2803 }2805 }
2804 auto pipe = static_cast<ir::PipeType>(op->GetKwarg<int>("pipe"));2806 auto pipe = static_cast<ir::PipeType>(op->GetKwarg<int>("pipe"));
2805- const auto mutex_ids = op->GetKwarg<std::vector<int>>("mutex_ids");2807+ auto candidateGroups = ir::As<ir::MakeTuple>(op->args_[1]);
2806- for (int bid : mutex_ids)2808+ auto mutexIds = ir::As<ir::MakeTuple>(op->args_[0]);
2807- mutex_pipes[bid].insert(pipe);2809+ 
2810+ std::set<int> effectiveIds;
2811+ for (size_t tile = 0; tile < mutexIds->elements_.size(); ++tile) {
2812+ auto tileMutexIds = ir::As<ir::MakeTuple>(mutexIds->elements_[tile]);
2813+ bool hasDynamicId = false;
2814+ for (const auto& mutexIdExpr : tileMutexIds->elements_) {
2815+ auto mutexId = ir::As<ir::ConstInt>(mutexIdExpr);
2816+ if (mutexId != nullptr) {
2817+ effectiveIds.insert(static_cast<int>(mutexId->value_));
2818+ } else {
2819+ hasDynamicId = true;
2820+ }
2821+ }
2822+ if (!hasDynamicId) {
2823+ continue;
2824+ }
2825+ auto candidate = ir::As<ir::MakeTuple>(candidateGroups->elements_[tile]);
2826+ for (const auto& candidateExpr : candidate->elements_) {
2827+ auto candidateId = ir::As<ir::ConstInt>(candidateExpr);
2828+ if (candidateId == nullptr) {
2829+ return;
2830+ }
2831+ effectiveIds.insert(static_cast<int>(candidateId->value_));
2832+ }
2833+ }
2834+ for (int mutexId : effectiveIds) {
2835+ mutex_pipes[mutexId].insert(pipe);
2836+ }
2808 }2837 }
2809};2838};
2810 2839 
@@ -10,7 +10,7 @@
10 10 
11/*!11/*!
12 * \file test_sync_ops.cpp12 * \file test_sync_ops.cpp
13- * \brief Coverage tests for sync_ops/sync.cpp — system.dcci type deduction13+ * \brief Coverage tests for sync_ops/sync.cpp type deduction
14 */14 */
15 15 
16#include "gtest/gtest.h"16#include "gtest/gtest.h"
@@ -42,26 +42,79 @@ using namespace test_helpers;
42// system.mutex_lock_dyn / system.mutex_unlock_dyn42// system.mutex_lock_dyn / system.mutex_unlock_dyn
43// ============================================================================43// ============================================================================
44 44 
45-TEST(SyncOpsMutexTest, DynamicMutexAcceptsMutexIdOwnerIndices)45+TEST(SyncOpsMutexTest, DynamicMutexAcceptsPerTileGroups)
46{46{
47 auto& reg = OpRegistry::GetInstance();47 auto& reg = OpRegistry::GetInstance();
48 auto id0 = MakeScalarVar("id0", DataType::INDEX);48 auto id0 = MakeScalarVar("id0", DataType::INDEX);
49 auto id1 = MakeScalarVar("id1", DataType::INDEX);49 auto id1 = MakeScalarVar("id1", DataType::INDEX);
50- const std::vector<int> mutex_id_owner_indices = {0, 0};50+ auto firstIds = std::make_shared<const MakeTuple>(std::vector<ExprPtr>{id0}, Sp());
51- std::vector<std::pair<std::string, std::any>> kwargs = {51+ auto secondIds = std::make_shared<const MakeTuple>(std::vector<ExprPtr>{id1}, Sp());
52- {"pipe", 5},52+ auto mutexId = std::make_shared<const MakeTuple>(std::vector<ExprPtr>{firstIds, secondIds}, Sp());
53- {"mutex_ids", std::vector<int>{0, 1, 2, 3}},53+ auto firstCandidates = MakeIntTuple({0});
54- {"mutex_id_owner_indices", mutex_id_owner_indices},54+ auto secondCandidates = MakeIntTuple({1});
55- };55+ auto candidateGroups = std::make_shared<const MakeTuple>(std::vector<ExprPtr>{firstCandidates, secondCandidates},
56+ Sp());
57+ std::vector<std::pair<std::string, std::any>> kwargs = {{"pipe", 5}};
56 58 
57 for (const char* op_name : {"system.mutex_lock_dyn", "system.mutex_unlock_dyn"}) {59 for (const char* op_name : {"system.mutex_lock_dyn", "system.mutex_unlock_dyn"}) {
58- auto call = reg.Create(op_name, {id0, id1}, kwargs, Sp());60+ auto call = reg.Create(op_name, {mutexId, candidateGroups}, kwargs, Sp());
59 ASSERT_NE(call, nullptr);61 ASSERT_NE(call, nullptr);
60 EXPECT_NE(As<UnknownType>(call->GetType()), nullptr);62 EXPECT_NE(As<UnknownType>(call->GetType()), nullptr);
61- EXPECT_EQ(call->GetKwarg<std::vector<int>>("mutex_id_owner_indices"), mutex_id_owner_indices);63+ EXPECT_EQ(call->args_[0], mutexId);
64+ EXPECT_EQ(call->args_[1], candidateGroups);
62 }65 }
63}66}
64 67 
68+TEST(SyncOpsMutexTest, DynamicMutexAcceptsManualScalarId)
69+{
70+ auto& reg = OpRegistry::GetInstance();
71+ auto id0 = MakeScalarVar("id0", DataType::INDEX);
72+ std::vector<std::pair<std::string, std::any>> kwargs = {{"pipe", 5}};
73+ 
74+ for (const char* op_name : {"system.mutex_lock_dyn", "system.mutex_unlock_dyn"}) {
75+ auto call = reg.Create(op_name, {id0}, kwargs, Sp());
76+ ASSERT_NE(call, nullptr);
77+ ASSERT_EQ(call->args_.size(), 1);
78+ EXPECT_EQ(call->args_[0], id0);
79+ }
80+}
81+ 
82+TEST(SyncOpsMutexTest, DynamicMutexRejectsEmptyCandidateGroups)
83+{
84+ auto& reg = OpRegistry::GetInstance();
85+ auto idGroup = MakeIntTuple({0});
86+ auto mutexId = std::make_shared<const MakeTuple>(std::vector<ExprPtr>{idGroup}, Sp());
87+ auto candidateGroups = std::make_shared<const MakeTuple>(std::vector<ExprPtr>{}, Sp());
88+ std::vector<std::pair<std::string, std::any>> kwargs = {{"pipe", 5}};
89+ 
90+ EXPECT_THROW((void)reg.Create("system.mutex_lock_dyn", {mutexId, candidateGroups}, kwargs, Sp()),
91+ npu::tile_fwk::Error);
92+}
93+ 
94+TEST(SyncOpsMutexTest, DynamicMutexRejectsInvalidArgumentCounts)
95+{
96+ auto& reg = OpRegistry::GetInstance();
97+ auto id = MakeScalarVar("id", DataType::INDEX);
98+ std::vector<std::pair<std::string, std::any>> kwargs = {{"pipe", 5}};
99+ 
100+ EXPECT_THROW((void)reg.Create("system.mutex_lock_dyn", {}, kwargs, Sp()), npu::tile_fwk::Error);
101+ EXPECT_THROW((void)reg.Create("system.mutex_lock_dyn", {id, id, id}, kwargs, Sp()), npu::tile_fwk::Error);
102+}
103+ 
104+TEST(SyncOpsMutexTest, DynamicMutexRejectsMisalignedCandidateGroups)
105+{
106+ auto& reg = OpRegistry::GetInstance();
107+ auto firstIds = MakeIntTuple({0});
108+ auto secondIds = MakeIntTuple({1});
109+ auto mutexId = std::make_shared<const MakeTuple>(std::vector<ExprPtr>{firstIds, secondIds}, Sp());
110+ auto candidates = MakeIntTuple({0});
111+ auto candidateGroups = std::make_shared<const MakeTuple>(std::vector<ExprPtr>{candidates}, Sp());
112+ std::vector<std::pair<std::string, std::any>> kwargs = {{"pipe", 5}};
113+ 
114+ EXPECT_THROW((void)reg.Create("system.mutex_lock_dyn", {mutexId, candidateGroups}, kwargs, Sp()),
115+ npu::tile_fwk::Error);
116+}
117+ 
65// ============================================================================118// ============================================================================
66// system.dcci119// system.dcci
67// ============================================================================120// ============================================================================
@@ -60,6 +60,40 @@ ir::MakeTuplePtr MakeTuple(std::vector<ir::ExprPtr> elements)
60 return std::make_shared<const ir::MakeTuple>(std::move(elements), ir::Span::Unknown());60 return std::make_shared<const ir::MakeTuple>(std::move(elements), ir::Span::Unknown());
61}61}
62 62 
63+ir::MakeTuplePtr MakeNestedTuple(const std::vector<std::vector<ir::ExprPtr>>& groups)
64+{
65+ std::vector<ir::ExprPtr> elements;
66+ elements.reserve(groups.size());
67+ for (const auto& group : groups) {
68+ elements.push_back(MakeTuple(group));
69+ }
70+ return MakeTuple(std::move(elements));
71+}
72+ 
73+ir::CallPtr MakeMutexCall(const std::string& name, const std::vector<std::vector<ir::ExprPtr>>& mutexId,
74+ const std::vector<std::vector<int>>& candidateGroups, ir::PipeType pipe)
75+{
76+ std::vector<std::vector<ir::ExprPtr>> candidateExprGroups;
77+ candidateExprGroups.reserve(candidateGroups.size());
78+ for (const auto& group : candidateGroups) {
79+ std::vector<ir::ExprPtr> candidates;
80+ candidates.reserve(group.size());
81+ for (int candidate : group) {
82+ candidates.push_back(MakeConstInt(candidate));
83+ }
84+ candidateExprGroups.push_back(std::move(candidates));
85+ }
86+ return std::make_shared<const ir::Call>(
87+ name, std::vector<ir::ExprPtr>{MakeNestedTuple(mutexId), MakeNestedTuple(candidateExprGroups)},
88+ Kwargs{{"pipe", static_cast<int>(pipe)}}, ir::Span::Unknown());
89+}
90+ 
91+ir::CallPtr MakeManualMutexCall(const std::string& name, const ir::ExprPtr& mutexId, ir::PipeType pipe)
92+{
93+ return std::make_shared<const ir::Call>(name, std::vector<ir::ExprPtr>{mutexId},
94+ Kwargs{{"pipe", static_cast<int>(pipe)}}, ir::Span::Unknown());
95+}
96+ 
63ir::VarPtr MakeTensorVar(const std::string& name, const std::vector<int64_t>& shape, ir::DataType dtype,97ir::VarPtr MakeTensorVar(const std::string& name, const std::vector<int64_t>& shape, ir::DataType dtype,
64 ir::TensorLayout layout = ir::TensorLayout::ND, std::vector<ir::ExprPtr> strides = {})98 ir::TensorLayout layout = ir::TensorLayout::ND, std::vector<ir::ExprPtr> strides = {})
65{99{
@@ -567,9 +601,7 @@ TEST(BackendCceOpsTest, CubeCrossCoreDynamicA5IntraBlockSignalsBothVectorSubcore
567 601 
568TEST(BackendCceOpsTest, MutexLock)602TEST(BackendCceOpsTest, MutexLock)
569{603{
570- Kwargs kwargs = {{"pipe", 5}};604+ auto call = MakeManualMutexCall("system.mutex_lock_dyn", MakeConstInt(1), ir::PipeType::S);
571- auto call = std::make_shared<const ir::Call>("system.mutex_lock_dyn", std::vector<ir::ExprPtr>{MakeConstInt(1)},
572- kwargs, ir::Span::Unknown());
573 auto body = std::make_shared<const ir::EvalStmt>(call, ir::Span::Unknown());605 auto body = std::make_shared<const ir::EvalStmt>(call, ir::Span::Unknown());
574 606 
575 codegen::CCECodegen codegen(ir::SectionKind::Vector);607 codegen::CCECodegen codegen(ir::SectionKind::Vector);
@@ -579,9 +611,7 @@ TEST(BackendCceOpsTest, MutexLock)
579 611 
580TEST(BackendCceOpsTest, MutexUnlock)612TEST(BackendCceOpsTest, MutexUnlock)
581{613{
582- Kwargs kwargs = {{"pipe", 5}};614+ auto call = MakeManualMutexCall("system.mutex_unlock_dyn", MakeConstInt(1), ir::PipeType::S);
583- auto call = std::make_shared<const ir::Call>("system.mutex_unlock_dyn", std::vector<ir::ExprPtr>{MakeConstInt(1)},
584- kwargs, ir::Span::Unknown());
585 auto body = std::make_shared<const ir::EvalStmt>(call, ir::Span::Unknown());615 auto body = std::make_shared<const ir::EvalStmt>(call, ir::Span::Unknown());
586 616 
587 codegen::CCECodegen codegen(ir::SectionKind::Vector);617 codegen::CCECodegen codegen(ir::SectionKind::Vector);
@@ -591,9 +621,7 @@ TEST(BackendCceOpsTest, MutexUnlock)
591 621 
592TEST(BackendCceOpsTest, MutexLockDyn)622TEST(BackendCceOpsTest, MutexLockDyn)
593{623{
594- Kwargs kwargs = {{"pipe", 5}};624+ auto call = MakeManualMutexCall("system.mutex_lock_dyn", MakeConstInt(2), ir::PipeType::S);
595- auto call = std::make_shared<const ir::Call>("system.mutex_lock_dyn", std::vector<ir::ExprPtr>{MakeConstInt(2)},
596- kwargs, ir::Span::Unknown());
597 auto body = std::make_shared<const ir::EvalStmt>(call, ir::Span::Unknown());625 auto body = std::make_shared<const ir::EvalStmt>(call, ir::Span::Unknown());
598 626 
599 codegen::CCECodegen codegen(ir::SectionKind::Vector);627 codegen::CCECodegen codegen(ir::SectionKind::Vector);
@@ -603,9 +631,7 @@ TEST(BackendCceOpsTest, MutexLockDyn)
603 631 
604TEST(BackendCceOpsTest, MutexUnlockDyn)632TEST(BackendCceOpsTest, MutexUnlockDyn)
605{633{
606- Kwargs kwargs = {{"pipe", 5}};634+ auto call = MakeManualMutexCall("system.mutex_unlock_dyn", MakeConstInt(2), ir::PipeType::S);
607- auto call = std::make_shared<const ir::Call>("system.mutex_unlock_dyn", std::vector<ir::ExprPtr>{MakeConstInt(2)},
608- kwargs, ir::Span::Unknown());
609 auto body = std::make_shared<const ir::EvalStmt>(call, ir::Span::Unknown());635 auto body = std::make_shared<const ir::EvalStmt>(call, ir::Span::Unknown());
610 636 
611 codegen::CCECodegen codegen(ir::SectionKind::Vector);637 codegen::CCECodegen codegen(ir::SectionKind::Vector);
@@ -615,12 +641,8 @@ TEST(BackendCceOpsTest, MutexUnlockDyn)
615 641 
616TEST(BackendCceOpsTest, VMutexWithoutCandidateIdsIsNotSkipped)642TEST(BackendCceOpsTest, VMutexWithoutCandidateIdsIsNotSkipped)
617{643{
618- auto lock = std::make_shared<const ir::Call>("system.mutex_lock_dyn", std::vector<ir::ExprPtr>{MakeConstInt(6)},644+ auto lock = MakeManualMutexCall("system.mutex_lock_dyn", MakeConstInt(6), ir::PipeType::V);
619- Kwargs{{"pipe", static_cast<int>(ir::PipeType::V)}},645+ auto unlock = MakeManualMutexCall("system.mutex_unlock_dyn", MakeConstInt(7), ir::PipeType::V);
620- ir::Span::Unknown());
621- auto unlock = std::make_shared<const ir::Call>("system.mutex_unlock_dyn", std::vector<ir::ExprPtr>{MakeConstInt(7)},
622- Kwargs{{"pipe", static_cast<int>(ir::PipeType::V)}},
623- ir::Span::Unknown());
624 auto body = std::make_shared<const ir::SeqStmts>(646 auto body = std::make_shared<const ir::SeqStmts>(
625 std::vector<ir::StmtPtr>{std::make_shared<const ir::EvalStmt>(lock, ir::Span::Unknown()),647 std::vector<ir::StmtPtr>{std::make_shared<const ir::EvalStmt>(lock, ir::Span::Unknown()),
626 std::make_shared<const ir::EvalStmt>(unlock, ir::Span::Unknown())},648 std::make_shared<const ir::EvalStmt>(unlock, ir::Span::Unknown())},
@@ -634,10 +656,7 @@ TEST(BackendCceOpsTest, VMutexWithoutCandidateIdsIsNotSkipped)
634 656 
635TEST(BackendCceOpsTest, AutoVMutexIsSkippedWhenAllCandidatesAreVOnly)657TEST(BackendCceOpsTest, AutoVMutexIsSkippedWhenAllCandidatesAreVOnly)
636{658{
637- auto call = std::make_shared<const ir::Call>(659+ auto call = MakeMutexCall("system.mutex_lock_dyn", {{MakeConstInt(6)}}, {{6, 7}}, ir::PipeType::V);
638- "system.mutex_lock_dyn", std::vector<ir::ExprPtr>{MakeConstInt(6)},
639- Kwargs{{"pipe", static_cast<int>(ir::PipeType::V)}, {"mutex_ids", std::vector<int>{6, 7}}},
640- ir::Span::Unknown());
641 auto body = std::make_shared<const ir::EvalStmt>(call, ir::Span::Unknown());660 auto body = std::make_shared<const ir::EvalStmt>(call, ir::Span::Unknown());
642 661 
643 codegen::CCECodegen codegen(ir::SectionKind::Vector);662 codegen::CCECodegen codegen(ir::SectionKind::Vector);
@@ -647,14 +666,24 @@ TEST(BackendCceOpsTest, AutoVMutexIsSkippedWhenAllCandidatesAreVOnly)
647 666 
648TEST(BackendCceOpsTest, AutoVMutexUsesTheWholeCandidateSetBeforeSkipping)667TEST(BackendCceOpsTest, AutoVMutexUsesTheWholeCandidateSetBeforeSkipping)
649{668{
650- auto vector_call = std::make_shared<const ir::Call>(669+ auto dynamic_id = MakeVar("dynamic_id", std::make_shared<const ir::ScalarType>(ir::DataType::INT32));
651- "system.mutex_lock_dyn", std::vector<ir::ExprPtr>{MakeConstInt(6)},670+ auto vector_call = MakeMutexCall("system.mutex_lock_dyn", {{dynamic_id}}, {{6, 7}}, ir::PipeType::V);
652- Kwargs{{"pipe", static_cast<int>(ir::PipeType::V)}, {"mutex_ids", std::vector<int>{6, 7}}},671+ auto mte2_call = MakeMutexCall("system.mutex_lock_dyn", {{MakeConstInt(7)}}, {{7}}, ir::PipeType::MTE2);
653- ir::Span::Unknown());672+ auto body = std::make_shared<const ir::SeqStmts>(
654- auto mte2_call = std::make_shared<const ir::Call>(673+ std::vector<ir::StmtPtr>{std::make_shared<const ir::EvalStmt>(vector_call, ir::Span::Unknown()),
655- "system.mutex_lock_dyn", std::vector<ir::ExprPtr>{MakeConstInt(7)},674+ std::make_shared<const ir::EvalStmt>(mte2_call, ir::Span::Unknown())},
656- Kwargs{{"pipe", static_cast<int>(ir::PipeType::MTE2)}, {"mutex_ids", std::vector<int>{7}}},
657 ir::Span::Unknown());675 ir::Span::Unknown());
676+ 
677+ codegen::CCECodegen codegen(ir::SectionKind::Vector);
678+ auto generated = codegen.GenerateSingle(MakeProgram(body, {dynamic_id}), "a5");
679+ EXPECT_NE(generated.find("get_buf(PIPE_V, dynamic_id, 0);"), std::string::npos);
680+ EXPECT_NE(generated.find("get_buf(PIPE_MTE2, 7, 0);"), std::string::npos);
681+}
682+ 
683+TEST(BackendCceOpsTest, StaticVMutexConservativelyKeepsBroadCandidates)
684+{
685+ auto vector_call = MakeMutexCall("system.mutex_lock_dyn", {{MakeConstInt(6)}}, {{6, 7}}, ir::PipeType::V);
686+ auto mte2_call = MakeMutexCall("system.mutex_lock_dyn", {{MakeConstInt(7)}}, {{6, 7}}, ir::PipeType::MTE2);
658 auto body = std::make_shared<const ir::SeqStmts>(687 auto body = std::make_shared<const ir::SeqStmts>(
659 std::vector<ir::StmtPtr>{std::make_shared<const ir::EvalStmt>(vector_call, ir::Span::Unknown()),688 std::vector<ir::StmtPtr>{std::make_shared<const ir::EvalStmt>(vector_call, ir::Span::Unknown()),
660 std::make_shared<const ir::EvalStmt>(mte2_call, ir::Span::Unknown())},689 std::make_shared<const ir::EvalStmt>(mte2_call, ir::Span::Unknown())},
@@ -668,12 +697,8 @@ TEST(BackendCceOpsTest, AutoVMutexUsesTheWholeCandidateSetBeforeSkipping)
668 697 
669TEST(BackendCceOpsTest, ManualConstantMutexDoesNotAffectAutoVMutexSkipForSameId)698TEST(BackendCceOpsTest, ManualConstantMutexDoesNotAffectAutoVMutexSkipForSameId)
670{699{
671- auto auto_v = std::make_shared<const ir::Call>(700+ auto auto_v = MakeMutexCall("system.mutex_lock_dyn", {{MakeConstInt(6)}}, {{6}}, ir::PipeType::V);
672- "system.mutex_lock_dyn", std::vector<ir::ExprPtr>{MakeConstInt(6)},701+ auto manual_mte2 = MakeManualMutexCall("system.mutex_lock_dyn", MakeConstInt(6), ir::PipeType::MTE2);
673- Kwargs{{"pipe", static_cast<int>(ir::PipeType::V)}, {"mutex_ids", std::vector<int>{6}}}, ir::Span::Unknown());
674- auto manual_mte2 = std::make_shared<const ir::Call>(
675- "system.mutex_lock_dyn", std::vector<ir::ExprPtr>{MakeConstInt(6)},
676- Kwargs{{"pipe", static_cast<int>(ir::PipeType::MTE2)}}, ir::Span::Unknown());
677 auto body = std::make_shared<const ir::SeqStmts>(702 auto body = std::make_shared<const ir::SeqStmts>(
678 std::vector<ir::StmtPtr>{std::make_shared<const ir::EvalStmt>(auto_v, ir::Span::Unknown()),703 std::vector<ir::StmtPtr>{std::make_shared<const ir::EvalStmt>(auto_v, ir::Span::Unknown()),
679 std::make_shared<const ir::EvalStmt>(manual_mte2, ir::Span::Unknown())},704 std::make_shared<const ir::EvalStmt>(manual_mte2, ir::Span::Unknown())},
@@ -687,12 +712,8 @@ TEST(BackendCceOpsTest, ManualConstantMutexDoesNotAffectAutoVMutexSkipForSameId)
687 712 
688TEST(BackendCceOpsTest, ManualConstantMutexOnAnotherPipeDoesNotBlockAutoVMutexSkipForDifferentId)713TEST(BackendCceOpsTest, ManualConstantMutexOnAnotherPipeDoesNotBlockAutoVMutexSkipForDifferentId)
689{714{
690- auto auto_v = std::make_shared<const ir::Call>(715+ auto auto_v = MakeMutexCall("system.mutex_lock_dyn", {{MakeConstInt(6)}}, {{6}}, ir::PipeType::V);
691- "system.mutex_lock_dyn", std::vector<ir::ExprPtr>{MakeConstInt(6)},716+ auto manual_mte2 = MakeManualMutexCall("system.mutex_lock_dyn", MakeConstInt(7), ir::PipeType::MTE2);
692- Kwargs{{"pipe", static_cast<int>(ir::PipeType::V)}, {"mutex_ids", std::vector<int>{6}}}, ir::Span::Unknown());
693- auto manual_mte2 = std::make_shared<const ir::Call>(
694- "system.mutex_lock_dyn", std::vector<ir::ExprPtr>{MakeConstInt(7)},
695- Kwargs{{"pipe", static_cast<int>(ir::PipeType::MTE2)}}, ir::Span::Unknown());
696 auto body = std::make_shared<const ir::SeqStmts>(717 auto body = std::make_shared<const ir::SeqStmts>(
697 std::vector<ir::StmtPtr>{std::make_shared<const ir::EvalStmt>(auto_v, ir::Span::Unknown()),718 std::vector<ir::StmtPtr>{std::make_shared<const ir::EvalStmt>(auto_v, ir::Span::Unknown()),
698 std::make_shared<const ir::EvalStmt>(manual_mte2, ir::Span::Unknown())},719 std::make_shared<const ir::EvalStmt>(manual_mte2, ir::Span::Unknown())},
@@ -707,12 +728,8 @@ TEST(BackendCceOpsTest, ManualConstantMutexOnAnotherPipeDoesNotBlockAutoVMutexSk
707TEST(BackendCceOpsTest, ManualDynamicMutexDoesNotGloballyDisableAutoVMutexSkip)728TEST(BackendCceOpsTest, ManualDynamicMutexDoesNotGloballyDisableAutoVMutexSkip)
708{729{
709 auto dynamic_id = MakeVar("manual_id", std::make_shared<const ir::ScalarType>(ir::DataType::INDEX));730 auto dynamic_id = MakeVar("manual_id", std::make_shared<const ir::ScalarType>(ir::DataType::INDEX));
710- auto auto_v = std::make_shared<const ir::Call>(731+ auto auto_v = MakeMutexCall("system.mutex_lock_dyn", {{MakeConstInt(6)}}, {{6}}, ir::PipeType::V);
711- "system.mutex_lock_dyn", std::vector<ir::ExprPtr>{MakeConstInt(6)},732+ auto manual_mte2 = MakeManualMutexCall("system.mutex_lock_dyn", dynamic_id, ir::PipeType::MTE2);
712- Kwargs{{"pipe", static_cast<int>(ir::PipeType::V)}, {"mutex_ids", std::vector<int>{6}}}, ir::Span::Unknown());
713- auto manual_mte2 = std::make_shared<const ir::Call>("system.mutex_lock_dyn", std::vector<ir::ExprPtr>{dynamic_id},
714- Kwargs{{"pipe", static_cast<int>(ir::PipeType::MTE2)}},
715- ir::Span::Unknown());
716 auto body = std::make_shared<const ir::SeqStmts>(733 auto body = std::make_shared<const ir::SeqStmts>(
717 std::vector<ir::StmtPtr>{std::make_shared<const ir::EvalStmt>(auto_v, ir::Span::Unknown()),734 std::vector<ir::StmtPtr>{std::make_shared<const ir::EvalStmt>(auto_v, ir::Span::Unknown()),
718 std::make_shared<const ir::EvalStmt>(manual_mte2, ir::Span::Unknown())},735 std::make_shared<const ir::EvalStmt>(manual_mte2, ir::Span::Unknown())},
@@ -724,14 +741,14 @@ TEST(BackendCceOpsTest, ManualDynamicMutexDoesNotGloballyDisableAutoVMutexSkip)
724 EXPECT_NE(generated.find("get_buf(PIPE_MTE2, manual_id, 0);"), std::string::npos);741 EXPECT_NE(generated.find("get_buf(PIPE_MTE2, manual_id, 0);"), std::string::npos);
725}742}
726 743 
727-TEST(BackendCceOpsTest, MutexDynDedupUnlocksFirstOccurrencesInInputOrder)744+TEST(BackendCceOpsTest, MutexDynDedupSkipsRepeatedDynamicExpression)
728{745{
729- Kwargs kwargs = {{"pipe", 5}};
730 auto id0 = MakeVar("id0", std::make_shared<const ir::ScalarType>(ir::DataType::INT32));746 auto id0 = MakeVar("id0", std::make_shared<const ir::ScalarType>(ir::DataType::INT32));
731 auto id1 = MakeVar("id1", std::make_shared<const ir::ScalarType>(ir::DataType::INT32));747 auto id1 = MakeVar("id1", std::make_shared<const ir::ScalarType>(ir::DataType::INT32));
732- std::vector<ir::ExprPtr> ids = {id0, id1, id0};748+ std::vector<std::vector<ir::ExprPtr>> ids = {{id0}, {id1}, {id0}};
733- auto lock = std::make_shared<const ir::Call>("system.mutex_lock_dyn", ids, kwargs, ir::Span::Unknown());749+ std::vector<std::vector<int>> candidates = {{0, 1}, {0, 1}, {0, 1}};
734- auto unlock = std::make_shared<const ir::Call>("system.mutex_unlock_dyn", ids, kwargs, ir::Span::Unknown());750+ auto lock = MakeMutexCall("system.mutex_lock_dyn", ids, candidates, ir::PipeType::S);
751+ auto unlock = MakeMutexCall("system.mutex_unlock_dyn", ids, candidates, ir::PipeType::S);
735 auto body = std::make_shared<const ir::SeqStmts>(752 auto body = std::make_shared<const ir::SeqStmts>(
736 std::vector<ir::StmtPtr>{std::make_shared<const ir::EvalStmt>(lock, ir::Span::Unknown()),753 std::vector<ir::StmtPtr>{std::make_shared<const ir::EvalStmt>(lock, ir::Span::Unknown()),
737 std::make_shared<const ir::EvalStmt>(unlock, ir::Span::Unknown())},754 std::make_shared<const ir::EvalStmt>(unlock, ir::Span::Unknown())},
@@ -739,28 +756,100 @@ TEST(BackendCceOpsTest, MutexDynDedupUnlocksFirstOccurrencesInInputOrder)
739 756 
740 codegen::CCECodegen codegen(ir::SectionKind::Vector);757 codegen::CCECodegen codegen(ir::SectionKind::Vector);
741 auto generated = codegen.GenerateSingle(MakeProgram(body, {id0, id1}), "a5");758 auto generated = codegen.GenerateSingle(MakeProgram(body, {id0, id1}), "a5");
742- auto release_id0 = generated.find("rls_buf(PIPE_S, id0, 0);");759+ const std::string acquire_id0 = "get_buf(PIPE_S, id0, 0);";
743- auto release_id1 = generated.find("rls_buf(PIPE_S, id1, 0);", release_id0);760+ const std::string acquire_id1 = "get_buf(PIPE_S, id1, 0);";
744- auto duplicate_guard = generated.find("if ((id0 != id0) && (id0 != id1)) {", release_id1);761+ const std::string release_id0 = "rls_buf(PIPE_S, id0, 0);";
745- auto duplicate_release = generated.find("rls_buf(PIPE_S, id0, 0);", duplicate_guard);762+ const std::string release_id1 = "rls_buf(PIPE_S, id1, 0);";
746- EXPECT_NE(release_id0, std::string::npos);763+ auto first_acquire_id0 = generated.find(acquire_id0);
747- EXPECT_NE(release_id1, std::string::npos);764+ auto first_release_id0 = generated.find(release_id0);
748- EXPECT_NE(duplicate_guard, std::string::npos);765+ ASSERT_NE(first_acquire_id0, std::string::npos);
749- EXPECT_NE(duplicate_release, std::string::npos);766+ ASSERT_NE(first_release_id0, std::string::npos);
750- EXPECT_LT(release_id0, release_id1);767+ EXPECT_NE(generated.find(acquire_id1), std::string::npos);
751- EXPECT_LT(release_id1, duplicate_guard);768+ EXPECT_NE(generated.find(release_id1), std::string::npos);
752- EXPECT_LT(duplicate_guard, duplicate_release);769+ EXPECT_EQ(generated.find(acquire_id0, first_acquire_id0 + acquire_id0.size()), std::string::npos);
770+ EXPECT_EQ(generated.find(release_id0, first_release_id0 + release_id0.size()), std::string::npos);
771+ EXPECT_EQ(generated.find("id0 != id0"), std::string::npos);
753}772}
754 773 
755-TEST(BackendCceOpsTest, MutexDynSkipsDedupWithinOneTile)774+TEST(BackendCceOpsTest, MutexDynFoldsConstantDedup)
775+{
776+ std::vector<std::vector<ir::ExprPtr>> ids = {{MakeConstInt(3)}, {MakeConstInt(7)}, {MakeConstInt(7)}};
777+ std::vector<std::vector<int>> candidates = {{3}, {7}, {7}};
778+ auto lock = MakeMutexCall("system.mutex_lock_dyn", ids, candidates, ir::PipeType::S);
779+ auto unlock = MakeMutexCall("system.mutex_unlock_dyn", ids, candidates, ir::PipeType::S);
780+ auto body = std::make_shared<const ir::SeqStmts>(
781+ std::vector<ir::StmtPtr>{std::make_shared<const ir::EvalStmt>(lock, ir::Span::Unknown()),
782+ std::make_shared<const ir::EvalStmt>(unlock, ir::Span::Unknown())},
783+ ir::Span::Unknown());
784+ 
785+ codegen::CCECodegen codegen(ir::SectionKind::Vector);
786+ auto generated = codegen.GenerateSingle(MakeProgram(body), "a5");
787+ const std::string acquire7 = "get_buf(PIPE_S, 7, 0);";
788+ const std::string release7 = "rls_buf(PIPE_S, 7, 0);";
789+ auto first_acquire7 = generated.find(acquire7);
790+ auto first_release7 = generated.find(release7);
791+ ASSERT_NE(first_acquire7, std::string::npos);
792+ ASSERT_NE(first_release7, std::string::npos);
793+ EXPECT_EQ(generated.find(acquire7, first_acquire7 + acquire7.size()), std::string::npos);
794+ EXPECT_EQ(generated.find(release7, first_release7 + release7.size()), std::string::npos);
795+ EXPECT_EQ(generated.find("7 != 3"), std::string::npos);
796+ EXPECT_EQ(generated.find("7 != 7"), std::string::npos);
797+}
798+ 
799+TEST(BackendCceOpsTest, MutexDynKeepsOnlyDynamicGuardTerms)
800+{
801+ auto dynamic_id = MakeVar("dynamic_id", std::make_shared<const ir::ScalarType>(ir::DataType::INT32));
802+ std::vector<std::vector<ir::ExprPtr>> ids = {{MakeConstInt(5)}, {dynamic_id}, {MakeConstInt(7)}};
803+ std::vector<std::vector<int>> candidates = {{5}, {5, 7}, {7}};
804+ auto call = MakeMutexCall("system.mutex_lock_dyn", ids, candidates, ir::PipeType::S);
805+ auto body = std::make_shared<const ir::EvalStmt>(call, ir::Span::Unknown());
806+ 
807+ codegen::CCECodegen codegen(ir::SectionKind::Vector);
808+ auto generated = codegen.GenerateSingle(MakeProgram(body, {dynamic_id}), "a5");
809+ EXPECT_NE(generated.find("if ((dynamic_id != 5)) {"), std::string::npos);
810+ EXPECT_NE(generated.find("if ((7 != dynamic_id)) {"), std::string::npos);
811+ EXPECT_EQ(generated.find("7 != 5"), std::string::npos);
812+}
813+ 
814+TEST(BackendCceOpsTest, MutexDynStaticIdsOverrideBroadCandidates)
815+{
816+ auto dynamic_id = MakeVar("dynamic_id", std::make_shared<const ir::ScalarType>(ir::DataType::INT32));
817+ std::vector<std::vector<ir::ExprPtr>> ids = {{MakeConstInt(5)}, {dynamic_id}};
818+ std::vector<std::vector<int>> candidates = {{5, 7}, {7}};
819+ auto call = MakeMutexCall("system.mutex_lock_dyn", ids, candidates, ir::PipeType::S);
820+ auto body = std::make_shared<const ir::EvalStmt>(call, ir::Span::Unknown());
821+ 
822+ codegen::CCECodegen codegen(ir::SectionKind::Vector);
823+ auto generated = codegen.GenerateSingle(MakeProgram(body, {dynamic_id}), "a5");
824+ EXPECT_NE(generated.find("get_buf(PIPE_S, 5, 0);"), std::string::npos);
825+ EXPECT_NE(generated.find("get_buf(PIPE_S, dynamic_id, 0);"), std::string::npos);
826+ EXPECT_EQ(generated.find("dynamic_id != 5"), std::string::npos);
827+}
828+ 
829+TEST(BackendCceOpsTest, MutexDynUsesPerIdCandidatesInMixedTile)
830+{
831+ auto prior_id = MakeVar("prior_id", std::make_shared<const ir::ScalarType>(ir::DataType::INT32));
832+ auto current_id = MakeVar("current_id", std::make_shared<const ir::ScalarType>(ir::DataType::INT32));
833+ std::vector<std::vector<ir::ExprPtr>> ids = {{prior_id}, {MakeConstInt(0), current_id}};
834+ auto call = MakeMutexCall("system.mutex_lock_dyn", ids, {{1}, {0, 1}}, ir::PipeType::S);
835+ auto body = std::make_shared<const ir::EvalStmt>(call, ir::Span::Unknown());
836+ 
837+ codegen::CCECodegen codegen(ir::SectionKind::Vector);
838+ auto generated = codegen.GenerateSingle(MakeProgram(body, {prior_id, current_id}), "a5");
839+ EXPECT_NE(generated.find("get_buf(PIPE_S, 0, 0);"), std::string::npos);
840+ EXPECT_NE(generated.find("if ((current_id != prior_id)) {"), std::string::npos);
841+ EXPECT_EQ(generated.find("0 != prior_id"), std::string::npos);
842+}
843+ 
844+TEST(BackendCceOpsTest, MutexDynGuardPairsSkipDedupWithinOneTile)
756{845{
757- Kwargs kwargs = {{"pipe", 5}, {"mutex_id_owner_indices", std::vector<int>{0, 0, 1}}};
758 auto output0 = MakeVar("output0", std::make_shared<const ir::ScalarType>(ir::DataType::INT32));846 auto output0 = MakeVar("output0", std::make_shared<const ir::ScalarType>(ir::DataType::INT32));
759 auto output1 = MakeVar("output1", std::make_shared<const ir::ScalarType>(ir::DataType::INT32));847 auto output1 = MakeVar("output1", std::make_shared<const ir::ScalarType>(ir::DataType::INT32));
760 auto source = MakeVar("source", std::make_shared<const ir::ScalarType>(ir::DataType::INT32));848 auto source = MakeVar("source", std::make_shared<const ir::ScalarType>(ir::DataType::INT32));
761- std::vector<ir::ExprPtr> ids = {output0, output1, source};849+ std::vector<std::vector<ir::ExprPtr>> ids = {{output0, output1}, {source}};
762- auto lock = std::make_shared<const ir::Call>("system.mutex_lock_dyn", ids, kwargs, ir::Span::Unknown());850+ std::vector<std::vector<int>> candidates = {{0, 1}, {0, 1}};
763- auto unlock = std::make_shared<const ir::Call>("system.mutex_unlock_dyn", ids, kwargs, ir::Span::Unknown());851+ auto lock = MakeMutexCall("system.mutex_lock_dyn", ids, candidates, ir::PipeType::S);
852+ auto unlock = MakeMutexCall("system.mutex_unlock_dyn", ids, candidates, ir::PipeType::S);
764 auto body = std::make_shared<const ir::SeqStmts>(853 auto body = std::make_shared<const ir::SeqStmts>(
765 std::vector<ir::StmtPtr>{std::make_shared<const ir::EvalStmt>(lock, ir::Span::Unknown()),854 std::vector<ir::StmtPtr>{std::make_shared<const ir::EvalStmt>(lock, ir::Span::Unknown()),
766 std::make_shared<const ir::EvalStmt>(unlock, ir::Span::Unknown())},855 std::make_shared<const ir::EvalStmt>(unlock, ir::Span::Unknown())},
@@ -789,6 +878,35 @@ TEST(BackendCceOpsTest, MutexDynSkipsDedupWithinOneTile)
789 EXPECT_LT(release_output1, release_source_guard);878 EXPECT_LT(release_output1, release_source_guard);
790}879}
791 880 
881+TEST(BackendCceOpsTest, MutexDynDisjointCandidateGroupsEmitWithoutIf)
882+{
883+ auto id0 = MakeVar("id0", std::make_shared<const ir::ScalarType>(ir::DataType::INT32));
884+ auto id1 = MakeVar("id1", std::make_shared<const ir::ScalarType>(ir::DataType::INT32));
885+ auto call = MakeMutexCall("system.mutex_lock_dyn", {{id0}, {id1}}, {{0}, {1}}, ir::PipeType::S);
886+ auto body = std::make_shared<const ir::EvalStmt>(call, ir::Span::Unknown());
887+ 
888+ codegen::CCECodegen codegen(ir::SectionKind::Vector);
889+ auto generated = codegen.GenerateSingle(MakeProgram(body, {id0, id1}), "a5");
890+ EXPECT_NE(generated.find("get_buf(PIPE_S, id0, 0);"), std::string::npos);
891+ EXPECT_NE(generated.find("get_buf(PIPE_S, id1, 0);"), std::string::npos);
892+ EXPECT_EQ(generated.find("if ((id1 != id0)) {"), std::string::npos);
893+}
894+ 
895+TEST(BackendCceOpsTest, MutexDynChecksOnlyOverlappingCandidateGroups)
896+{
897+ auto output0 = MakeVar("output0", std::make_shared<const ir::ScalarType>(ir::DataType::INT32));
898+ auto output1 = MakeVar("output1", std::make_shared<const ir::ScalarType>(ir::DataType::INT32));
899+ auto source = MakeVar("source", std::make_shared<const ir::ScalarType>(ir::DataType::INT32));
900+ std::vector<std::vector<ir::ExprPtr>> ids = {{output0}, {output1}, {source}};
901+ auto call = MakeMutexCall("system.mutex_lock_dyn", ids, {{0}, {1}, {0}}, ir::PipeType::S);
902+ auto body = std::make_shared<const ir::EvalStmt>(call, ir::Span::Unknown());
903+ 
904+ codegen::CCECodegen codegen(ir::SectionKind::Vector);
905+ auto generated = codegen.GenerateSingle(MakeProgram(body, {output0, output1, source}), "a5");
906+ EXPECT_NE(generated.find("if ((source != output0)) {"), std::string::npos);
907+ EXPECT_EQ(generated.find("source != output1"), std::string::npos);
908+}
909+ 
792// ============================================================================910// ============================================================================
793// A5-specific: set_mm_layout_transform911// A5-specific: set_mm_layout_transform
794// ============================================================================912// ============================================================================
@@ -12,6 +12,30 @@ from .. import pypto_impl
12from .. import SymbolicScalar12from .. import SymbolicScalar
13 13 
14 14 
15+class _AutoMutexIdManager:
16+ """Collect TileGroups, allocate automatic mutex IDs, and resolve placeholders."""
17+ 
18+ def __init__(self) -> None: ...
19+ 
20+ def collect_group(
21+ self,
22+ tiles: Sequence[Expr],
23+ mutex_ids: MakeTuple,
24+ group_name: str,
25+ ) -> None: ...
26+ 
27+ def record_op_constraints(
28+ self,
29+ tile_id_groups: Sequence[MakeTuple],
30+ candidate_groups: Sequence[MakeTuple],
31+ ) -> None: ...
32+ 
33+ def assign_mutex_ids(self, program: Program) -> Program: ...
34+ 
35+ @property
36+ def diagnostic_span(self) -> Span: ...
37+ 
38+ 
15class DataType:39class DataType:
16 """Data type representation for PyPTO tensors and operations"""40 """Data type representation for PyPTO tensors and operations"""
17 41 
@@ -25,12 +25,13 @@ from pypto.pypto_impl.ir import (
25 CrossCoreSyncMode,25 CrossCoreSyncMode,
26 DcciDst,26 DcciDst,
27 Expr,27 Expr,
28+ MakeTuple,
28 PipeType,29 PipeType,
29 Span,30 Span,
30 SyncCoreType,31 SyncCoreType,
31)32)
32 33 
33-from ..._errors import InvalidArgument, InvalidOperation, InvalidShape, InvalidType, InvalidVal, NotSupported34+from ..._errors import InvalidArgument, InvalidOperation, InvalidShape, InvalidType, NotSupported
34from .._utils import _get_span_or_capture, _is_int, _normalize_expr, _to_make_tuple35from .._utils import _get_span_or_capture, _is_int, _normalize_expr, _to_make_tuple
35from ._op_registry import OpSpec, op_impl, register_table36from ._op_registry import OpSpec, op_impl, register_table
36 37 
@@ -88,22 +89,6 @@ def _normalize_integer_id_expr(value: int | Expr, span: Span, *, name: str, max_
88 return expr89 return expr
89 90 
90 91 
91-def _normalize_mutex_ids(mutex_ids: tuple | list | None, span: Span | None = None) -> list[int] | None:
92- """Validate candidate IDs before they are converted to vector<int>."""
93- if mutex_ids is None:
94- return None
95- if not isinstance(mutex_ids, (list, tuple)):
96- raise InvalidType("mutex_ids must be a list, tuple, or None", span=span)
97- normalized_mutex_ids = list(mutex_ids)
98- if not normalized_mutex_ids:
99- raise InvalidVal("mutex_ids must not be empty", span=span)
100- for index, mutex_id in enumerate(normalized_mutex_ids):
101- if not _is_int(mutex_id):
102- raise InvalidType(f"mutex_ids[{index}] must be a Python int", span=span)
103- _check_id_range(mutex_id, MAX_MUTEX_ID, "mutex_ids element", span=span)
104- return normalized_mutex_ids
105- 
106- 
107def _validate_concrete_pipe(pipe: PipeType, name: str, span: Span | None = None) -> None:92def _validate_concrete_pipe(pipe: PipeType, name: str, span: Span | None = None) -> None:
108 if not isinstance(pipe, PipeType):93 if not isinstance(pipe, PipeType):
109 raise InvalidType(f"{name} must be a PipeType, got {type(pipe).__name__}", span=span)94 raise InvalidType(f"{name} must be a PipeType, got {type(pipe).__name__}", span=span)
@@ -397,53 +382,87 @@ def _create_mutex_op(
397 mutex_id, actual_span, name="mutex_id", max_id=MAX_MUTEX_ID382 mutex_id, actual_span, name="mutex_id", max_id=MAX_MUTEX_ID
398 )383 )
399 384 
400- kwargs: dict = {"pipe": pipe}385+ return _ir_core.create_op_call(
401- return _ir_core.create_op_call(f"{op_name}_dyn", [mutex_id_expr], kwargs, actual_span)386+ f"{op_name}_dyn",
387+ [mutex_id_expr],
388+ {"pipe": pipe},
389+ actual_span,
390+ )
402 391 
403 392 
404def _create_mutex_dedup_op(393def _create_mutex_dedup_op(
405 op_name: str,394 op_name: str,
406 *,395 *,
407 pipe: PipeType,396 pipe: PipeType,
408- mutex_id_exprs: list[Expr],397+ mutex_id: MakeTuple,
409- mutex_id_owner_indices: list[int] | None = None,398+ candidate_groups: MakeTuple,
410- mutex_ids_union: list | None = None,
411 span: Span | None = None,399 span: Span | None = None,
412) -> Call:400) -> Call:
413- """Create a dedup mutex lock/unlock for N runtime mutex-id expressions.401+ """Create a mutex lock/unlock with per-Tile ID and candidate groups.
414 402 
415- Emits a single ``system.mutex_lock_dyn`` / ``system.mutex_unlock_dyn`` IR Call403+ The first argument is a two-dimensional tuple containing the IDs required by
416- with multiple mutex_id expressions in args. Expressions with the same owner404+ each Tile. The second argument is the matching two-dimensional candidate
417- index in ``mutex_id_owner_indices`` are known distinct; CCE only generates405+ tuple used by codegen for cross-Tile deduplication.
418- runtime if-guards across different Tiles. Lock and unlock both use
419- first-occurrence order.
420 406 
421 Args:407 Args:
422 op_name: Base operation name ("system.mutex_lock" or "system.mutex_unlock").408 op_name: Base operation name ("system.mutex_lock" or "system.mutex_unlock").
423 pipe: Pipe to lock on.409 pipe: Pipe to lock on.
424- mutex_id_exprs: List of N mutex_id IR expressions (already normalized to Expr).410+ mutex_id: One non-empty mutex ID sequence per Tile.
425- mutex_id_owner_indices: Owner index for every expression. Expressions with411+ candidate_groups: One non-empty candidate sequence per Tile.
426- the same index come from one Tile and are guaranteed distinct.
427- mutex_ids_union: Union of all TileGroup candidate mutex_id values.
428 span: Source span.412 span: Source span.
429 """413 """
430 actual_span = span if span is not None else _get_span_or_capture(span, frame_offset=3)414 actual_span = span if span is not None else _get_span_or_capture(span, frame_offset=3)
431 _validate_concrete_pipe(pipe, "pipe", actual_span)415 _validate_concrete_pipe(pipe, "pipe", actual_span)
432- if not mutex_id_exprs:416+ if not mutex_id.elements or any(
433- raise InvalidArgument("mutex_id requires at least one expression")417+ not isinstance(tile_mutex_id, MakeTuple) or not tile_mutex_id.elements
434- normalized_mutex_id_exprs = [418+ for tile_mutex_id in mutex_id.elements
435- _normalize_integer_id_expr(mutex_id, actual_span, name="mutex_id", max_id=MAX_MUTEX_ID)419+ ):
436- for mutex_id in mutex_id_exprs420+ raise InvalidArgument("mutex_id requires at least one expression per Tile", span=actual_span)
437- ]421+ 
438- kwargs: dict = {"pipe": pipe}422+ mutex_id_tuple = _to_make_tuple(
439- if mutex_id_owner_indices is not None:423+ [
440- if len(mutex_id_owner_indices) != len(mutex_id_exprs):424+ _to_make_tuple(
441- raise InvalidShape("mutex_id_owner_indices length must match mutex_id_exprs length")425+ [
442- kwargs["mutex_id_owner_indices"] = list(mutex_id_owner_indices)426+ _normalize_integer_id_expr(value, actual_span, name="mutex_id", max_id=MAX_MUTEX_ID)
443- normalized_mutex_ids = _normalize_mutex_ids(mutex_ids_union, actual_span)427+ for value in tile_mutex_id.elements
444- if normalized_mutex_ids is not None:428+ ],
445- kwargs["mutex_ids"] = normalized_mutex_ids429+ actual_span,
446- return _ir_core.create_op_call(f"{op_name}_dyn", normalized_mutex_id_exprs, kwargs, actual_span)430+ )
431+ for tile_mutex_id in mutex_id.elements
432+ ],
433+ actual_span,
434+ )
435+ 
436+ if len(candidate_groups.elements) != len(mutex_id.elements) or any(
437+ not isinstance(group, MakeTuple) or not group.elements
438+ for group in candidate_groups.elements
439+ ):
440+ raise InvalidShape(
441+ "candidate_group must contain one non-empty group per mutex_id Tile",
442+ span=actual_span,
443+ )
444+ candidate_group_tuple = _to_make_tuple(
445+ [
446+ _to_make_tuple(
447+ [
448+ _normalize_integer_id_expr(
449+ candidate, actual_span, name="candidate_group", max_id=MAX_MUTEX_ID
450+ )
451+ for candidate in group.elements
452+ ],
453+ actual_span,
454+ )
455+ for group in candidate_groups.elements
456+ ],
457+ actual_span,
458+ )
459+ 
460+ return _ir_core.create_op_call(
461+ f"{op_name}_dyn",
462+ [mutex_id_tuple, candidate_group_tuple],
463+ {"pipe": pipe},
464+ actual_span,
465+ )
447 466 
448 467 
449def _mutex_op(468def _mutex_op(
@@ -1486,7 +1486,7 @@ def make_tile(
1486 1486 
1487@_api_decl1487@_api_decl
1488def make_tile_group(*, type: TileType, addrs: int | list,1488def make_tile_group(*, type: TileType, addrs: int | list,
1489- mutex_ids: list[int | list[int] | tuple[int, ...]] | tuple | None = None,1489+ mutex_ids: str | list[int | list[int] | tuple[int, ...]] | tuple | None = None,
1490 depth: int | None = None,1490 depth: int | None = None,
1491 fwd_ids: list[int] | tuple[int, ...] | None = None,1491 fwd_ids: list[int] | tuple[int, ...] | None = None,
1492 bwd_ids: list[int] | tuple[int, ...] | None = None,1492 bwd_ids: list[int] | tuple[int, ...] | None = None,
@@ -1500,11 +1500,13 @@ def make_tile_group(*, type: TileType, addrs: int | list,
1500 Args:1500 Args:
1501 type: ``pl.TileType`` descriptor1501 type: ``pl.TileType`` descriptor
1502 addrs: Base address for contiguous Tiles, or one address per Tile1502 addrs: Base address for contiguous Tiles, or one address per Tile
1503- mutex_ids: Optional mutex IDs for synchronization. Each Tile may use1503+ mutex_ids: ``"auto"`` for whole-group automatic allocation, a manual
1504- one int or a non-empty list/tuple. Every Tile must use the same1504+ sequence, or None/empty for user-managed synchronization. Each
1505- mutex ID count, with no duplicates for one Tile1505+ manually configured Tile may use one int or a non-empty list/tuple.
1506- depth: Number of Tiles. Required when ``mutex_ids`` is None or empty;1506+ Every Tile must use the same mutex ID count, with no duplicates for
1507- otherwise inferred from ``len(mutex_ids)``1507+ one Tile
1508+ depth: Number of Tiles. Required when ``mutex_ids`` is ``"auto"``, None,
1509+ or empty; otherwise inferred from ``len(mutex_ids)``
1508 fwd_ids: Optional cross-core event IDs (0..15) marking this group as a1510 fwd_ids: Optional cross-core event IDs (0..15) marking this group as a
1509 producer->consumer channel for the automatic pipeline transform. One1511 producer->consumer channel for the automatic pipeline transform. One
1510 per Tile; the transform picks ``fwd_ids[i % N]`` per iteration1512 per Tile; the transform picks ``fwd_ids[i % N]`` per iteration
@@ -48,6 +48,8 @@ from ._type_resolver import TypeResolver
48# publishing it as the ambient location would underline the entire block.48# publishing it as the ambient location would underline the entire block.
49_COMPOUND_STATEMENTS = (ast.For, ast.While, ast.If, ast.With, ast.Try, ast.FunctionDef)49_COMPOUND_STATEMENTS = (ast.For, ast.While, ast.If, ast.With, ast.Try, ast.FunctionDef)
50 50 
51+AutoMutexIdManager = ir._AutoMutexIdManager
52+ 
51 53 
52def _snake_visit_name(node: ast.AST) -> str:54def _snake_visit_name(node: ast.AST) -> str:
53 """Return the snake_case visitor handler for an AST node type."""55 """Return the snake_case visitor handler for an AST node type."""
@@ -112,6 +114,7 @@ class ASTParser(
112 void_return_only: bool = False,114 void_return_only: bool = False,
113 void_return_context: str = "this function",115 void_return_context: str = "this function",
114 allow_early_return: bool = False,116 allow_early_return: bool = False,
117+ mutex_id_manager: AutoMutexIdManager | None = None,
115 ):118 ):
116 """Initialize AST parser.119 """Initialize AST parser.
117 120 
@@ -132,9 +135,13 @@ class ASTParser(
132 are void-only but allow early/multiple returns, while @pl.vector_function135 are void-only but allow early/multiple returns, while @pl.vector_function
133 and @pl.pipeline.stage are void-only and still require a single tail return.136 and @pl.pipeline.stage are void-only and still require a single tail return.
134 target: Required Cube/Vector target for target-specific parsing.137 target: Required Cube/Vector target for target-specific parsing.
138+ mutex_id_manager: Manager for mutex-ID planning and IR resolution in
139+ this target parse.
135 """140 """
136 if target not in (ir.SectionKind.Cube, ir.SectionKind.Vector):141 if target not in (ir.SectionKind.Cube, ir.SectionKind.Vector):
137 raise NotSupported(f"Unsupported parser target: {target}")142 raise NotSupported(f"Unsupported parser target: {target}")
143+ if auto_mutex and mutex_id_manager is None:
144+ raise CommonInner("auto_mutex=True requires a mutex ID manager")
138 self._target = target145 self._target = target
139 self.matched_target = False146 self.matched_target = False
140 # Launch facts collected while this target Program is parsed. Tile147 # Launch facts collected while this target Program is parsed. Tile
@@ -143,12 +150,12 @@ class ASTParser(
143 self.max_vec_tile_end: int = 0150 self.max_vec_tile_end: int = 0
144 self.requires_simt: bool = False151 self.requires_simt: bool = False
145 self.span_tracker = SpanTracker(source_file, source_lines, line_offset, col_offset)152 self.span_tracker = SpanTracker(source_file, source_lines, line_offset, col_offset)
146- # Maps tile Expr objects -> (tuple[buf_id_ir, ...], mutex_ids) for tiles returned by153+ # Maps tile Expr objects -> (tile_id MakeTuple, candidate MakeTuple) for tiles returned by
147 # group.next()/current()/previous()/group[i]; consumed by auto_mutex and154 # group.next()/current()/previous()/group[i]; consumed by auto_mutex and
148 # shared with ScopeManager for control-flow candidate-id merging.155 # shared with ScopeManager for control-flow candidate-id merging.
149 # Keep the Expr itself as the key. A bare id(expr) does not retain the156 # Keep the Expr itself as the key. A bare id(expr) does not retain the
150 # Python IR wrapper and can be reused by an unrelated expression.157 # Python IR wrapper and can be reused by an unrelated expression.
151- self._tile_mutex_meta: dict[ir.Expr, tuple] = {}158+ self._tile_mutex_meta: dict[ir.Expr, tuple[ir.MakeTuple, ir.MakeTuple]] = {}
152 self.scope_manager = ScopeManager(strict_ssa=strict_ssa)159 self.scope_manager = ScopeManager(strict_ssa=strict_ssa)
153 self._tilingkey_consts = tilingkey_consts160 self._tilingkey_consts = tilingkey_consts
154 self._datatype_consts = datatype_consts161 self._datatype_consts = datatype_consts
@@ -205,9 +212,10 @@ class ASTParser(
205 self._buf_tile_counter: int = 0212 self._buf_tile_counter: int = 0
206 # Counter for let-bound buf_idx variables in tile-group cursor selection.213 # Counter for let-bound buf_idx variables in tile-group cursor selection.
207 self._tuple_idx_counter: int = 0214 self._tuple_idx_counter: int = 0
215+ self._auto_mutex_placeholder_counter: int = 0
208 self._expr_tmp_counter: int = 0216 self._expr_tmp_counter: int = 0
209 self._ifexpr_tmp_counter: int = 0217 self._ifexpr_tmp_counter: int = 0
210- # Maps group Expr objects -> (depth, per-tile mutex IDs, memory).218+ # Maps group Expr objects -> (depth, group mutex IDs, memory).
211 self.tile_group_meta: dict[ir.Expr, tuple] = {}219 self.tile_group_meta: dict[ir.Expr, tuple] = {}
212 # Parser-only constant environment. Runtime bindings remain exclusively in220 # Parser-only constant environment. Runtime bindings remain exclusively in
213 # ScopeManager as Vars; this map records constants by physical SSA name.221 # ScopeManager as Vars; this map records constants by physical SSA name.
@@ -242,6 +250,7 @@ class ASTParser(
242 self._tuple_select_cache: dict[tuple[str, int], ir.Var] = {}250 self._tuple_select_cache: dict[tuple[str, int], ir.Var] = {}
243 251 
244 self._auto_mutex = auto_mutex252 self._auto_mutex = auto_mutex
253+ self._mutex_id_manager = mutex_id_manager
245 self._parsed_expr_cache: dict[ast.expr, Any] = {}254 self._parsed_expr_cache: dict[ast.expr, Any] = {}
246 self._current_func_type = ir.FunctionType.Opaque255 self._current_func_type = ir.FunctionType.Opaque
247 self._void_return_only = void_return_only256 self._void_return_only = void_return_only
@@ -30,7 +30,7 @@ import ast
30 30 
31from pypto.pypto_impl import ir31from pypto.pypto_impl import ir
32from pypto.pypto_impl.ir import DataType32from pypto.pypto_impl.ir import DataType
33-from pypto_pro.ir._utils import _is_int33+from pypto_pro.ir._utils import _is_int, _to_make_tuple
34from pypto_pro.ir.op._op_registry import op_impl34from pypto_pro.ir.op._op_registry import op_impl
35from pypto_pro.ir.op.block_ops import TileType as _TileType35from pypto_pro.ir.op.block_ops import TileType as _TileType
36from pypto_pro.ir.op.block_ops import _ir_reinterpret, _static_shape_ints36from pypto_pro.ir.op.block_ops import _ir_reinterpret, _static_shape_ints
@@ -38,7 +38,16 @@ from pypto_pro.ir.op.block_ops import make_tile_expr as _make_tile_expr
38from pypto_pro.ir.op.block_ops import tile_slot_size as _tile_slot_size38from pypto_pro.ir.op.block_ops import tile_slot_size as _tile_slot_size
39from pypto_pro.ir.op.system_ops import MAX_MUTEX_ID39from pypto_pro.ir.op.system_ops import MAX_MUTEX_ID
40 40 
41-from ..._errors import InvalidArgument, InvalidShape, InvalidType, InvalidVal, OutOfRange, PyptoProError, message_of41+from ..._errors import (
42+ InvalidArgument,
43+ InvalidOperation,
44+ InvalidShape,
45+ InvalidType,
46+ InvalidVal,
47+ OutOfRange,
48+ PyptoProError,
49+ message_of,
50+)
42from ._tuple_type_registry import TupleTypeKind51from ._tuple_type_registry import TupleTypeKind
43from .diagnostics import check_in_range52from .diagnostics import check_in_range
44 53 
@@ -58,7 +67,7 @@ class BufferParserMixin:
58 @staticmethod67 @staticmethod
59 def _normalize_mutex_ids(mutex_ids, span: ir.Span) -> tuple[tuple[int, ...], ...]:68 def _normalize_mutex_ids(mutex_ids, span: ir.Span) -> tuple[tuple[int, ...], ...]:
60 """Normalize mutex IDs to one fixed-size tuple per tile slot."""69 """Normalize mutex IDs to one fixed-size tuple per tile slot."""
61- per_tile_mutex_ids = []70+ normalized_mutex_ids = []
62 for mutex_id in mutex_ids:71 for mutex_id in mutex_ids:
63 if isinstance(mutex_id, (list, tuple)):72 if isinstance(mutex_id, (list, tuple)):
64 tile_mutex_ids = tuple(mutex_id)73 tile_mutex_ids = tuple(mutex_id)
@@ -80,10 +89,10 @@ class BufferParserMixin:
80 span=span,89 span=span,
81 parser_retry=True,90 parser_retry=True,
82 )91 )
83- per_tile_mutex_ids.append(tile_mutex_ids)92+ normalized_mutex_ids.append(tile_mutex_ids)
84 93 
85- expected_mutex_id_count = len(per_tile_mutex_ids[0])94+ expected_mutex_id_count = len(normalized_mutex_ids[0])
86- for tile_mutex_ids in per_tile_mutex_ids[1:]:95+ for tile_mutex_ids in normalized_mutex_ids[1:]:
87 if len(tile_mutex_ids) != expected_mutex_id_count:96 if len(tile_mutex_ids) != expected_mutex_id_count:
88 raise InvalidArgument(97 raise InvalidArgument(
89 f"all tiles in a tile group must have the same mutex ID count: "98 f"all tiles in a tile group must have the same mutex ID count: "
@@ -91,7 +100,7 @@ class BufferParserMixin:
91 span=span,100 span=span,
92 parser_retry=True,101 parser_retry=True,
93 )102 )
94- return tuple(per_tile_mutex_ids)103+ return tuple(normalized_mutex_ids)
95 104 
96 @staticmethod105 @staticmethod
97 def _validate_depth(depth, span: ir.Span) -> None:106 def _validate_depth(depth, span: ir.Span) -> None:
@@ -102,6 +111,84 @@ class BufferParserMixin:
102 parser_retry=True,111 parser_retry=True,
103 )112 )
104 113 
114+ def _parse_mutex_ids_and_depth(
115+ self,
116+ raw_mutex_ids,
117+ depth: int | None,
118+ mutex_ids_span: ir.Span,
119+ depth_span: ir.Span,
120+ span: ir.Span,
121+ ) -> tuple[ir.MakeTuple | None, int]:
122+ """Validate and lower one tile group's mutex IDs, inferring depth when omitted."""
123+ if depth is not None:
124+ self._validate_depth(depth, depth_span)
125+ 
126+ if isinstance(raw_mutex_ids, str):
127+ if raw_mutex_ids != "auto":
128+ raise InvalidArgument(
129+ 'make_tile_group() string mutex_ids only supports "auto", '
130+ f"got {raw_mutex_ids!r}",
131+ span=mutex_ids_span,
132+ parser_retry=True,
133+ )
134+ if not self._auto_mutex:
135+ raise InvalidOperation(
136+ 'mutex_ids="auto" requires @pl.jit(auto_mutex=True)',
137+ span=mutex_ids_span,
138+ parser_retry=True,
139+ )
140+ if depth is None:
141+ raise InvalidArgument(
142+ 'make_tile_group() depth is required when mutex_ids is "auto", None, or empty',
143+ span=mutex_ids_span,
144+ parser_retry=True,
145+ )
146+ auto_mutex_ids = []
147+ for _ in range(depth):
148+ placeholder = ir.Var(
149+ f"__pypto_auto_mutex_id_{self._auto_mutex_placeholder_counter}",
150+ ir.ScalarType(DataType.INT64),
151+ span,
152+ )
153+ self._auto_mutex_placeholder_counter += 1
154+ auto_mutex_ids.append(_to_make_tuple([placeholder], span))
155+ return _to_make_tuple(auto_mutex_ids, span), depth
156+ 
157+ if raw_mutex_ids is None or (
158+ isinstance(raw_mutex_ids, (list, tuple)) and not raw_mutex_ids
159+ ):
160+ if depth is None:
161+ raise InvalidArgument(
162+ 'make_tile_group() depth is required when mutex_ids is "auto", None, or empty',
163+ span=mutex_ids_span,
164+ parser_retry=True,
165+ )
166+ return None, depth
167+ 
168+ if not isinstance(raw_mutex_ids, (list, tuple)):
169+ raise InvalidType(
170+ 'make_tile_group() mutex_ids must be "auto", a list, tuple, or None',
171+ span=mutex_ids_span,
172+ parser_retry=True,
173+ )
174+ 
175+ normalized_mutex_ids = self._normalize_mutex_ids(raw_mutex_ids, mutex_ids_span)
176+ if depth is None:
177+ depth = len(normalized_mutex_ids)
178+ elif len(normalized_mutex_ids) != depth:
179+ raise InvalidShape(
180+ f"make_tile_group() mutex_ids length {len(normalized_mutex_ids)} must equal depth {depth}",
181+ span=mutex_ids_span,
182+ parser_retry=True,
183+ )
184+ return (
185+ _to_make_tuple(
186+ [_to_make_tuple(tile_mutex_ids, span) for tile_mutex_ids in normalized_mutex_ids],
187+ span,
188+ ),
189+ depth,
190+ )
191+ 
105 @staticmethod192 @staticmethod
106 def _tile_type_slot_size(tile_type: _TileType) -> int:193 def _tile_type_slot_size(tile_type: _TileType) -> int:
107 """Per-tile byte size derived from the TileType static shape and dtype.194 """Per-tile byte size derived from the TileType static shape and dtype.
@@ -166,36 +253,43 @@ class BufferParserMixin:
166 span=self.span_tracker.keyword_span(kw, "type", span),253 span=self.span_tracker.keyword_span(kw, "type", span),
167 parser_retry=True,254 parser_retry=True,
168 )255 )
256+ group_target = (
257+ ir.SectionKind.Vector
258+ if tile_type.target_memory == ir.MemorySpace.Vec
259+ else ir.SectionKind.Cube
260+ )
169 261 
170 mutex_ids_span = self.span_tracker.keyword_span(kw, "mutex_ids", span)262 mutex_ids_span = self.span_tracker.keyword_span(kw, "mutex_ids", span)
171 raw_mutex_ids = self.expr_evaluator.eval_expr(kw["mutex_ids"].value) if "mutex_ids" in kw else None263 raw_mutex_ids = self.expr_evaluator.eval_expr(kw["mutex_ids"].value) if "mutex_ids" in kw else None
172- if raw_mutex_ids is not None and not isinstance(raw_mutex_ids, (list, tuple)):264+ depth_span = self.span_tracker.keyword_span(kw, "depth", span)
173- raise InvalidType(
174- "make_tile_group() mutex_ids must be a list, tuple, or None",
175- span=mutex_ids_span,
176- parser_retry=True,
177- )
178- mutex_ids = self._normalize_mutex_ids(raw_mutex_ids, mutex_ids_span) if raw_mutex_ids else None
179- 
180 depth = self.expr_evaluator.eval_expr(kw["depth"].value) if "depth" in kw else None265 depth = self.expr_evaluator.eval_expr(kw["depth"].value) if "depth" in kw else None
181- if depth is not None:
182- self._validate_depth(depth, self.span_tracker.keyword_span(kw, "depth", span))
183 266 
184- if mutex_ids is None:267+ if group_target == self.target:
185- if depth is None:268+ mutex_id_irs, depth = self._parse_mutex_ids_and_depth(
269+ raw_mutex_ids,
270+ depth,
271+ mutex_ids_span,
272+ depth_span,
273+ span,
274+ )
275+ else:
276+ mutex_id_irs = None
277+ if depth is not None:
278+ self._validate_depth(depth, depth_span)
279+ if isinstance(raw_mutex_ids, (list, tuple)) and raw_mutex_ids and len(raw_mutex_ids) != depth:
280+ raise InvalidShape(
281+ f"make_tile_group() mutex_ids length {len(raw_mutex_ids)} must equal depth {depth}",
282+ span=mutex_ids_span,
283+ parser_retry=True,
284+ )
285+ elif isinstance(raw_mutex_ids, (list, tuple)) and raw_mutex_ids:
286+ depth = len(raw_mutex_ids)
287+ else:
186 raise InvalidArgument(288 raise InvalidArgument(
187- "make_tile_group() depth is required when mutex_ids is None or empty",289+ 'make_tile_group() depth is required when mutex_ids is "auto", None, or empty',
188 span=mutex_ids_span,290 span=mutex_ids_span,
189 parser_retry=True,291 parser_retry=True,
190 )292 )
191- elif depth is None:
192- depth = len(mutex_ids)
193- elif len(mutex_ids) != depth:
194- raise InvalidShape(
195- f"make_tile_group() mutex_ids length {len(mutex_ids)} must equal depth {depth}",
196- span=mutex_ids_span,
197- parser_retry=True,
198- )
199 293 
200 slot_size = self._tile_type_slot_size(tile_type)294 slot_size = self._tile_type_slot_size(tile_type)
201 # addrs: a single base address -> contiguous tiles (base + i*slot_size);295 # addrs: a single base address -> contiguous tiles (base + i*slot_size);
@@ -229,10 +323,23 @@ class BufferParserMixin:
229 else:323 else:
230 tile_addrs = [addrs + i * slot_size for i in range(depth)]324 tile_addrs = [addrs + i * slot_size for i in range(depth)]
231 325 
232- return self._build_tile_group_ir(tile_type, tile_addrs, depth, mutex_ids, slot_size, span)326+ return self._build_tile_group_ir(
327+ tile_type,
328+ tile_addrs,
329+ depth,
330+ mutex_id_irs,
331+ slot_size,
332+ span,
333+ )
233 334 
234 def _build_tile_group_ir(335 def _build_tile_group_ir(
235- self, tile_type, tile_addrs, depth, mutex_ids, slot_size, span: ir.Span336+ self,
337+ tile_type,
338+ tile_addrs,
339+ depth,
340+ mutex_id_irs,
341+ slot_size,
342+ span: ir.Span,
236 ) -> ir.Expr:343 ) -> ir.Expr:
237 """Build the IR named-tuple handle for a tile group.344 """Build the IR named-tuple handle for a tile group.
238 345 
@@ -246,7 +353,6 @@ class BufferParserMixin:
246 the assigned variable after SSA binding creation.353 the assigned variable after SSA binding creation.
247 """354 """
248 var_name = self.current_target_name355 var_name = self.current_target_name
249- per_tile_mutex_ids = mutex_ids or ()
250 tile_vars = []356 tile_vars = []
251 for i, addr in enumerate(tile_addrs):357 for i, addr in enumerate(tile_addrs):
252 t = _make_tile_expr(358 t = _make_tile_expr(
@@ -264,8 +370,17 @@ class BufferParserMixin:
264 )370 )
265 self._record_tile_high_water(t)371 self._record_tile_high_water(t)
266 tile_vars.append(self.builder.let(f"_tg_{var_name}_tiles_{i}", t, span=span))372 tile_vars.append(self.builder.let(f"_tg_{var_name}_tiles_{i}", t, span=span))
373+ 
374+ if self._auto_mutex and mutex_id_irs is not None:
375+ self._mutex_id_manager.collect_group(tile_vars, mutex_id_irs, var_name)
376+ 
267 tiles_tuple = self.builder.let(f"_tg_{var_name}_tiles", ir.MakeTuple(tile_vars, span), span=span)377 tiles_tuple = self.builder.let(f"_tg_{var_name}_tiles", ir.MakeTuple(tile_vars, span), span=span)
268- mutex_columns = tuple(zip(*per_tile_mutex_ids)) if per_tile_mutex_ids else ((),)378+ mutex_rows = (
379+ [tile_mutex_ids.elements for tile_mutex_ids in mutex_id_irs.elements]
380+ if mutex_id_irs is not None
381+ else []
382+ )
383+ mutex_columns = tuple(zip(*mutex_rows)) if mutex_rows else ((),)
269 mut_tuples = []384 mut_tuples = []
270 mut_fields = []385 mut_fields = []
271 for column, values in enumerate(mutex_columns):386 for column, values in enumerate(mutex_columns):
@@ -273,7 +388,7 @@ class BufferParserMixin:
273 mut_tuples.append(388 mut_tuples.append(
274 self.builder.let(389 self.builder.let(
275 f"_tg_{var_name}_mutex_ids{suffix}",390 f"_tg_{var_name}_mutex_ids{suffix}",
276- ir.MakeTuple([ir.ConstInt(m, DataType.INT64, span) for m in values], span),391+ _to_make_tuple(values, span),
277 span=span,392 span=span,
278 )393 )
279 )394 )
@@ -285,7 +400,7 @@ class BufferParserMixin:
285 span,400 span,
286 name=_TILE_GROUP_TYPE_NAME,401 name=_TILE_GROUP_TYPE_NAME,
287 )402 )
288- self.tile_group_meta[result] = (depth, mutex_ids, tile_type.target_memory)403+ self.tile_group_meta[result] = (depth, mutex_id_irs, tile_type.target_memory)
289 return result404 return result
290 cursor_call = ir.create_op_call(405 cursor_call = ir.create_op_call(
291 "struct.create",406 "struct.create",
@@ -301,7 +416,7 @@ class BufferParserMixin:
301 span,416 span,
302 name=_TILE_GROUP_TYPE_NAME,417 name=_TILE_GROUP_TYPE_NAME,
303 )418 )
304- self.tile_group_meta[result] = (depth, mutex_ids, tile_type.target_memory)419+ self.tile_group_meta[result] = (depth, mutex_id_irs, tile_type.target_memory)
305 return result420 return result
306 421 
307 def _build_reinterpreted_group(self, group, kwargs: dict, span: ir.Span) -> ir.Expr:422 def _build_reinterpreted_group(self, group, kwargs: dict, span: ir.Span) -> ir.Expr:
@@ -312,7 +427,7 @@ class BufferParserMixin:
312 semantics keep the "same buffer" identity) and runs the same validation as427 semantics keep the "same buffer" identity) and runs the same validation as
313 standalone tiles (compile-time shape, element alignment, footprint bound).428 standalone tiles (compile-time shape, element alignment, footprint bound).
314 429 
315- depth and per-tile mutex_ids are inherited verbatim (mutex_id430+ depth and group mutex_ids are inherited verbatim (mutex_id
316 inheritance); the mutex columns and the rotating cursor are reused from431 inheritance); the mutex columns and the rotating cursor are reused from
317 the original group handle. The group handle shape mirrors what432 the original group handle. The group handle shape mirrors what
318 ``_build_tile_group_ir`` produces (tiles tuple, mutex_id columns,433 ``_build_tile_group_ir`` produces (tiles tuple, mutex_id columns,
@@ -328,7 +443,7 @@ class BufferParserMixin:
328 hint="Pass the handle itself rather than a copy stored in a struct or container",443 hint="Pass the handle itself rather than a copy stored in a struct or container",
329 parser_retry=True,444 parser_retry=True,
330 )445 )
331- n_slots, per_tile_mutex_ids, _memory = meta446+ depth, mutex_ids, _memory = meta
332 tiles = self.lower_attr_access(group, "tiles", span)447 tiles = self.lower_attr_access(group, "tiles", span)
333 448 
334 slot0 = ir.GetItemExpr(tiles, ir.ConstInt(0, DataType.INT64, span), span)449 slot0 = ir.GetItemExpr(tiles, ir.ConstInt(0, DataType.INT64, span), span)
@@ -349,7 +464,7 @@ class BufferParserMixin:
349 # size (fresh MemRef inside _ir_reinterpret) and identical validation.464 # size (fresh MemRef inside _ir_reinterpret) and identical validation.
350 var_name = self.current_target_name465 var_name = self.current_target_name
351 tile_vars = []466 tile_vars = []
352- for i in range(n_slots):467+ for i in range(depth):
353 slot = ir.GetItemExpr(tiles, ir.ConstInt(i, DataType.INT64, span), span)468 slot = ir.GetItemExpr(tiles, ir.ConstInt(i, DataType.INT64, span), span)
354 slot_tile = _ir_reinterpret(slot, shape=new_shape if kwargs.get("shape") is not None else None,469 slot_tile = _ir_reinterpret(slot, shape=new_shape if kwargs.get("shape") is not None else None,
355 dtype=kwargs.get("dtype"), layout=kwargs.get("layout"), span=span)470 dtype=kwargs.get("dtype"), layout=kwargs.get("layout"), span=span)
@@ -357,8 +472,7 @@ class BufferParserMixin:
357 tiles_tuple = self.builder.let(f"_tg_{var_name}_tiles", ir.MakeTuple(tile_vars, span), span=span)472 tiles_tuple = self.builder.let(f"_tg_{var_name}_tiles", ir.MakeTuple(tile_vars, span), span=span)
358 473 
359 # ② mutex columns: reuse the original group's own column expressions.474 # ② mutex columns: reuse the original group's own column expressions.
360- per_tile = per_tile_mutex_ids or ()475+ n_columns = len(mutex_ids.elements[0].elements) if mutex_ids is not None else 0
361- n_columns = len(per_tile[0]) if per_tile else 0
362 mut_tuples = []476 mut_tuples = []
363 mut_fields = []477 mut_fields = []
364 for column in range(n_columns):478 for column in range(n_columns):
@@ -368,14 +482,14 @@ class BufferParserMixin:
368 482 
369 # ③ cursor: reused from the original handle so the rotation position483 # ③ cursor: reused from the original handle so the rotation position
370 # (the original group keeps its own independent cursor) is preserved.484 # (the original group keeps its own independent cursor) is preserved.
371- if n_slots == 1:485+ if depth == 1:
372 result = self.make_named_tuple(486 result = self.make_named_tuple(
373 [tiles_tuple, *mut_tuples],487 [tiles_tuple, *mut_tuples],
374 ["tiles", *mut_fields],488 ["tiles", *mut_fields],
375 span,489 span,
376 name=_TILE_GROUP_TYPE_NAME,490 name=_TILE_GROUP_TYPE_NAME,
377 )491 )
378- self.tile_group_meta[result] = (n_slots, per_tile_mutex_ids, memref.memory_space)492+ self.tile_group_meta[result] = (depth, mutex_ids, memref.memory_space)
379 return result493 return result
380 cursor = self.lower_attr_access(group, "cursor", span)494 cursor = self.lower_attr_access(group, "cursor", span)
381 result = self.make_named_tuple(495 result = self.make_named_tuple(
@@ -384,7 +498,7 @@ class BufferParserMixin:
384 span,498 span,
385 name=_TILE_GROUP_TYPE_NAME,499 name=_TILE_GROUP_TYPE_NAME,
386 )500 )
387- self.tile_group_meta[result] = (n_slots, per_tile_mutex_ids, memref.memory_space)501+ self.tile_group_meta[result] = (depth, mutex_ids, memref.memory_space)
388 return result502 return result
389 503 
390 # --- accessors ------------------------------------------------------------504 # --- accessors ------------------------------------------------------------
@@ -395,7 +509,7 @@ class BufferParserMixin:
395 )509 )
396 510 
397 def _group_meta(self, group_var, span: ir.Span) -> tuple:511 def _group_meta(self, group_var, span: ir.Span) -> tuple:
398- """Return the slot count, per-tile mutex IDs, and candidate IDs."""512+ """Return the group depth, mutex IDs, and candidate IDs."""
399 meta = self.tile_group_meta.get(group_var)513 meta = self.tile_group_meta.get(group_var)
400 if meta is None:514 if meta is None:
401 raise InvalidType(515 raise InvalidType(
@@ -405,14 +519,21 @@ class BufferParserMixin:
405 hint="Pass the handle itself rather than a copy stored in a struct or container",519 hint="Pass the handle itself rather than a copy stored in a struct or container",
406 parser_retry=True,520 parser_retry=True,
407 )521 )
408- per_tile_mutex_ids = meta[1]522+ depth, mutex_ids, _memory = meta
409- candidate_ids = tuple(523+ candidate_ids = _to_make_tuple(
410- dict.fromkeys(value for tile_mutex_ids in (per_tile_mutex_ids or ()) for value in tile_mutex_ids)524+ list(
525+ dict.fromkeys(
526+ value
527+ for tile_mutex_ids in (mutex_ids.elements if mutex_ids is not None else ())
528+ for value in tile_mutex_ids.elements
529+ )
530+ ),
531+ span,
411 )532 )
412- return meta[0], per_tile_mutex_ids, candidate_ids533+ return depth, mutex_ids, candidate_ids
413 534 
414 def _select_static_slot(535 def _select_static_slot(
415- self, tiles, slot: int, per_tile_mutex_ids, candidate_ids, span: ir.Span536+ self, tiles, slot: int, mutex_ids, candidate_ids, span: ir.Span
416 ) -> ir.Expr:537 ) -> ir.Expr:
417 """Select tiles[slot] with a compile-time index.538 """Select tiles[slot] with a compile-time index.
418 539 
@@ -420,11 +541,9 @@ class BufferParserMixin:
420 ``% n`` and no dynamic lock at lock time.541 ``% n`` and no dynamic lock at lock time.
421 """542 """
422 tile_ir = ir.GetItemExpr(tiles, ir.ConstInt(slot, DataType.INT64, span), span)543 tile_ir = ir.GetItemExpr(tiles, ir.ConstInt(slot, DataType.INT64, span), span)
423- if per_tile_mutex_ids is not None:544+ if mutex_ids is not None:
424- mutex_id_irs = tuple(545+ tile_id_irs = mutex_ids.elements[slot]
425- ir.ConstInt(value, DataType.INT64, span) for value in per_tile_mutex_ids[slot]546+ self._tile_mutex_meta[tile_ir] = (tile_id_irs, candidate_ids)
poorwill
poorwillpoorwillSep 26

这个尝试把candidate修正后会有啥问题?

likedislike
426- )
427- self._tile_mutex_meta[tile_ir] = (mutex_id_irs, candidate_ids)
428 return tile_ir547 return tile_ir
429 548 
430 def _select_dynamic_slot(549 def _select_dynamic_slot(
@@ -432,15 +551,15 @@ class BufferParserMixin:
432 group_var,551 group_var,
433 tiles,552 tiles,
434 raw_index,553 raw_index,
435- per_tile_mutex_ids,554+ mutex_ids,
436 candidate_ids,555 candidate_ids,
437 span: ir.Span,556 span: ir.Span,
438 ):557 ):
439 """Select a slot with one materialized runtime index.558 """Select a slot with one materialized runtime index.
440 559 
441 The supplied index is used unchanged. When mutex metadata exists, the560 The supplied index is used unchanged. When mutex metadata exists, the
442- buf_id is ``mutex_ids[idx]``, an Expr, so auto_mutex takes the dynamic561+ Tile IDs are selected from the mutex-ID columns by ``idx``, so
443- lock path.562+ auto_mutex takes the dynamic lock path.
444 """563 """
445 idx = self.builder.let(564 idx = self.builder.let(
446 f"_bufidx_{self._tuple_idx_counter}",565 f"_bufidx_{self._tuple_idx_counter}",
@@ -449,13 +568,13 @@ class BufferParserMixin:
449 )568 )
450 self._tuple_idx_counter += 1569 self._tuple_idx_counter += 1
451 tile_ir = ir.GetItemExpr(tiles, idx, span)570 tile_ir = ir.GetItemExpr(tiles, idx, span)
452- if per_tile_mutex_ids is not None:571+ if mutex_ids is not None:
453- mutex_id_irs = []572+ tile_id_irs = []
454- for column in range(len(per_tile_mutex_ids[0])):573+ for column in range(len(mutex_ids.elements[0].elements)):
455 suffix = "" if column == 0 else f"_{column}"574 suffix = "" if column == 0 else f"_{column}"
456 mut = self.lower_attr_access(group_var, f"mutex_ids{suffix}", span)575 mut = self.lower_attr_access(group_var, f"mutex_ids{suffix}", span)
457- mutex_id_irs.append(ir.GetItemExpr(mut, idx, span))576+ tile_id_irs.append(ir.GetItemExpr(mut, idx, span))
458- self._tile_mutex_meta[tile_ir] = (tuple(mutex_id_irs), candidate_ids)577+ self._tile_mutex_meta[tile_ir] = (_to_make_tuple(tile_id_irs, span), candidate_ids)
459 return tile_ir578 return tile_ir
460 579 
461 def _lower_group_accessor(self, group_var, method_name: str, span: ir.Span):580 def _lower_group_accessor(self, group_var, method_name: str, span: ir.Span):
@@ -465,11 +584,11 @@ class BufferParserMixin:
465 current()/previous() leave the cursor unchanged. When configured, records584 current()/previous() leave the cursor unchanged. When configured, records
466 the selected tile's mutex id via _tile_mutex_meta for auto_mutex.585 the selected tile's mutex id via _tile_mutex_meta for auto_mutex.
467 """586 """
468- n_slots, per_tile_mutex_ids, candidate_ids = self._group_meta(group_var, span)587+ depth, mutex_ids, candidate_ids = self._group_meta(group_var, span)
469 tiles = self.lower_attr_access(group_var, "tiles", span)588 tiles = self.lower_attr_access(group_var, "tiles", span)
470- if n_slots == 1:589+ if depth == 1:
471 # Single tile: no cursor or modulo; optional mutex metadata stays static.590 # Single tile: no cursor or modulo; optional mutex metadata stays static.
472- return self._select_static_slot(tiles, 0, per_tile_mutex_ids, candidate_ids, span)591+ return self._select_static_slot(tiles, 0, mutex_ids, candidate_ids, span)
473 cursor_struct = self.lower_attr_access(group_var, "cursor", span)592 cursor_struct = self.lower_attr_access(group_var, "cursor", span)
474 cur_read = self.lower_attr_access(cursor_struct, "cursor", span)593 cur_read = self.lower_attr_access(cursor_struct, "cursor", span)
475 if method_name == "next":594 if method_name == "next":
@@ -479,13 +598,13 @@ class BufferParserMixin:
479 elif method_name == "current":598 elif method_name == "current":
480 raw = cur_read599 raw = cur_read
481 else: # previous600 else: # previous
482- raw = cur_read + ir.ConstInt(n_slots - 1, DataType.INT64, span)601+ raw = cur_read + ir.ConstInt(depth - 1, DataType.INT64, span)
483- wrapped = raw % ir.ConstInt(n_slots, DataType.INT64, span)602+ wrapped = raw % ir.ConstInt(depth, DataType.INT64, span)
484 return self._select_dynamic_slot(603 return self._select_dynamic_slot(
485 group_var,604 group_var,
486 tiles,605 tiles,
487 wrapped,606 wrapped,
488- per_tile_mutex_ids,607+ mutex_ids,
489 candidate_ids,608 candidate_ids,
490 span,609 span,
491 )610 )
@@ -502,27 +621,27 @@ class BufferParserMixin:
502 access, so interleaving it with next()/previous() leaves the rotation621 access, so interleaving it with next()/previous() leaves the rotation
503 sequence exactly where the last next() put it.622 sequence exactly where the last next() put it.
504 """623 """
505- n_slots, per_tile_mutex_ids, candidate_ids = self._group_meta(group_var, span)624+ depth, mutex_ids, candidate_ids = self._group_meta(group_var, span)
506 tiles = self.lower_attr_access(group_var, "tiles", span)625 tiles = self.lower_attr_access(group_var, "tiles", span)
507 index_expr = self._reject_non_index_subscript(slice_node, span)626 index_expr = self._reject_non_index_subscript(slice_node, span)
508 627 
509 if isinstance(index_expr, ir.ConstInt):628 if isinstance(index_expr, ir.ConstInt):
510 slot = int(index_expr.value)629 slot = int(index_expr.value)
511- if not 0 <= slot < n_slots:630+ if not 0 <= slot < depth:
512 raise OutOfRange(631 raise OutOfRange(
513 f"tile group index {index_expr.value} is out of range for a "632 f"tile group index {index_expr.value} is out of range for a "
514- f"{n_slots}-tile group",633+ f"{depth}-tile group",
515 span=span,634 span=span,
516- hint=f"Valid indices are in [0, {n_slots})",635+ hint=f"Valid indices are in [0, {depth})",
517 parser_retry=True,636 parser_retry=True,
518 )637 )
519- return self._select_static_slot(tiles, slot, per_tile_mutex_ids, candidate_ids, span)638+ return self._select_static_slot(tiles, slot, mutex_ids, candidate_ids, span)
520 639 
521 return self._select_dynamic_slot(640 return self._select_dynamic_slot(
522 group_var,641 group_var,
523 tiles,642 tiles,
524 index_expr,643 index_expr,
525- per_tile_mutex_ids,644+ mutex_ids,
526 candidate_ids,645 candidate_ids,
527 span,646 span,
528 )647 )
@@ -22,7 +22,7 @@ import sys
22from typing import Any, Callable22from typing import Any, Callable
23 23 
24from pypto.pypto_impl import ir24from pypto.pypto_impl import ir
25-from pypto_pro.ir._utils import _is_int25+from pypto_pro.ir._utils import _is_int, _to_make_tuple
26from pypto_pro.ir.op._op_registry import _OP_REGISTRY26from pypto_pro.ir.op._op_registry import _OP_REGISTRY
27from pypto_pro.ir.op.block_ops import block_ir_op27from pypto_pro.ir.op.block_ops import block_ir_op
28 28 
@@ -223,8 +223,8 @@ def _get_source_info(entity: Callable | type, entity_type: str) -> tuple[str, li
223 )223 )
224 224 
225 225 
226-# Mutex carrier for tile-group tiles (buf_id IR expr tuple, candidate values, memory, dedup id).226+# Mutex carrier for one selected Tile (runtime IDs, possible values, memory, dedup id).
227-_MutexRef = namedtuple("_MutexRef", "buf_ids mutex_ids memory slot_id")227+_MutexRef = namedtuple("_MutexRef", "tile_ids candidate_ids memory slot_id")
228 228 
229 229 
230@dataclass(frozen=True)230@dataclass(frozen=True)
@@ -734,46 +734,25 @@ class CallParserMixin:
734 return True734 return True
735 return bool(args.kw_defaults)735 return bool(args.kw_defaults)
736 736 
737- # -------------------------------------------------------------------------737+ def _record_mutex_op_constraints(self, refs: list) -> None:
738- # Mutex dedup helpers (shared by _emit_auto_mutex and _emit_vf_func_mutex_lock)738+ """Record same-operation ID preferences before grouped Calls are built."""
739- # -------------------------------------------------------------------------739+ tile_id_groups = []
740+ candidate_groups = []
741+ for tile_ref in refs:
742+ target = (
743+ ir.SectionKind.Vector
744+ if tile_ref.memory == ir.MemorySpace.Vec
745+ else ir.SectionKind.Cube
746+ )
747+ # MTE3 may expose both Cube and Vector TileGroups to both target parses. Only pass
748+ # candidates owned by this target to its independent mutex-ID manager.
749+ if target != self.target:
750+ continue
740 751 
741- @staticmethod752+ tile_id_groups.append(tile_ref.tile_ids)
742- def _group_refs_by_mutex_overlap(refs: list) -> list:753+ candidate_groups.append(tile_ref.candidate_ids)
743- """Group tilerefs by mutex_ids overlap (connected components via union-find).
744 754 
745- Two refs whose mutex_ids lists have any common value are in the same group.755+ self._mutex_id_manager.record_op_constraints(tile_id_groups, candidate_groups)
746- Returns a list of groups, each group is a list of _MutexRef.
747- """
748- n = len(refs)
749- parent = list(range(n))
750- 
751- def find(x):
752- while parent[x] != x:
753- parent[x] = parent[parent[x]]
754- x = parent[x]
755- return x
756- 
757- def union(x, y):
758- px, py = find(x), find(y)
759- if px != py:
760- parent[px] = py
761- 
762- # Build mutex_id sets for each ref
763- id_sets = [set(ref.mutex_ids) if ref.mutex_ids else set() for ref in refs]
764- 
765- # Union refs that have overlapping mutex_ids
766- for i in range(n):
767- for j in range(i + 1, n):
768- if id_sets[i] & id_sets[j]:
769- union(i, j)
770- 
771- # Collect groups
772- groups: dict[int, list] = {}
773- for i in range(n):
774- root = find(i)
775- groups.setdefault(root, []).append(refs[i])
776- return list(groups.values())
777 756 
778 @classmethod757 @classmethod
779 def _make_call_with_return_type(758 def _make_call_with_return_type(
@@ -1560,8 +1539,8 @@ class CallParserMixin:
1560 )1539 )
1561 if self._auto_mutex:1540 if self._auto_mutex:
1562 self._tile_mutex_meta[undefined_return] = (1541 self._tile_mutex_meta[undefined_return] = (
1563- (ir.ConstInt(-1, ir.DataType.INT64, span),),1542+ _to_make_tuple([ir.ConstInt(-1, ir.DataType.INT64, span)], span),
1564- [],1543+ _to_make_tuple([], span),
1565 )1544 )
1566 1545 
1567 if is_outermost_vf:1546 if is_outermost_vf:
@@ -1655,8 +1634,8 @@ class CallParserMixin:
1655 def _try_resolve_tileref(self, node: ast.expr):1634 def _try_resolve_tileref(self, node: ast.expr):
1656 """Resolve a tile argument to its memory and optional mutex metadata.1635 """Resolve a tile argument to its memory and optional mutex metadata.
1657 1636 
1658- Returns _MutexRef(buf_ids, mutex_ids, memory, tile_id) for tile1637+ Returns _MutexRef(tile_ids, candidate_ids, memory, tile_id) for tile
1659- arguments. Ordinary tiles have empty ``buf_ids`` and ``mutex_ids``;1638+ arguments. Ordinary tiles have empty ``tile_ids`` and ``candidate_ids``;
1660 their memory is still needed to infer the move pipe when paired with a1639 their memory is still needed to infer the move pipe when paired with a
1661 tile-group tile.1640 tile-group tile.
1662 1641 
@@ -1673,9 +1652,9 @@ class CallParserMixin:
1673 mem = expr.type.memref.memory_space_1652 mem = expr.type.memref.memory_space_
1674 meta = self.tile_mutex_lock_meta(expr)1653 meta = self.tile_mutex_lock_meta(expr)
1675 if meta is None:1654 if meta is None:
1676- return _MutexRef((), (), mem, id(expr))1655+ return _MutexRef(_to_make_tuple([], expr.span), _to_make_tuple([], expr.span), mem, id(expr))
1677- buf_id_irs, mutex_ids = meta1656+ tile_ids, candidate_ids = meta
1678- return _MutexRef(buf_id_irs, mutex_ids, mem, id(expr))1657+ return _MutexRef(tile_ids, candidate_ids, mem, id(expr))
1679 1658 
1680 def _emit_auto_mutex(self, op_name: str, call: ast.Call, span: ir.Span):1659 def _emit_auto_mutex(self, op_name: str, call: ast.Call, span: ir.Span):
1681 """Emit mutex_lock before and mutex_unlock after a block DSL op.1660 """Emit mutex_lock before and mutex_unlock after a block DSL op.
@@ -1714,7 +1693,7 @@ class CallParserMixin:
1714 unique_refs = []1693 unique_refs = []
1715 seen = set()1694 seen = set()
1716 for tref in tilerefs:1695 for tref in tilerefs:
1717- if tref is None or not tref.buf_ids:1696+ if tref is None or not tref.tile_ids.elements:
1718 continue1697 continue
1719 if tref.slot_id in seen:1698 if tref.slot_id in seen:
1720 continue1699 continue
@@ -1758,20 +1737,18 @@ class CallParserMixin:
1758 if pipe is None:1737 if pipe is None:
1759 return1738 return
1760 1739 
1761- # 3. Emit lock for each unique _TileRef, with dedup for aliasing tiles.1740+ self._record_mutex_op_constraints(unique_refs)
1762- # Group once here and reuse the grouping at unlock time.
1763- groups = self._group_refs_by_mutex_overlap(unique_refs)
1764- self._emit_mutex_for_groups(groups, pipe, span, is_lock=True)
1765 1741 
1766- # Store grouping for post-op unlock emission (avoids re-grouping)1742+ # 3. Preserve Tile boundaries and ordering for codegen-side deduplication.
1767- self._pending_mutex_unlocks = (groups, pipe, span)1743+ self._emit_mutex_for_refs(unique_refs, pipe, span, is_lock=True)
1744+ self._pending_mutex_unlocks = (unique_refs, pipe, span)
1768 1745 
1769 def _emit_auto_mutex_unlocks(self):1746 def _emit_auto_mutex_unlocks(self):
1770 """Emit mutex_unlock calls queued by _emit_auto_mutex or _parse_func_call."""1747 """Emit mutex_unlock calls queued by _emit_auto_mutex or _parse_func_call."""
1771 if not hasattr(self, "_pending_mutex_unlocks") or self._pending_mutex_unlocks is None:1748 if not hasattr(self, "_pending_mutex_unlocks") or self._pending_mutex_unlocks is None:
1772 return1749 return
1773- groups, pipe, span = self._pending_mutex_unlocks1750+ refs, pipe, span = self._pending_mutex_unlocks
1774- self._emit_mutex_for_groups(groups, pipe, span, is_lock=False)1751+ self._emit_mutex_for_refs(refs, pipe, span, is_lock=False)
1775 self._pending_mutex_unlocks = None1752 self._pending_mutex_unlocks = None
1776 1753 
1777 def _emit_mutex_for_tile(self, tile: ir.Expr, pipe, span: ir.Span, *, is_lock: bool) -> bool:1754 def _emit_mutex_for_tile(self, tile: ir.Expr, pipe, span: ir.Span, *, is_lock: bool) -> bool:
@@ -1779,11 +1756,10 @@ class CallParserMixin:
1779 meta = self.tile_mutex_lock_meta(tile)1756 meta = self.tile_mutex_lock_meta(tile)
1780 if meta is None:1757 if meta is None:
1781 return False1758 return False
1782- buf_ids, mutex_ids = meta1759+ tile_id_irs, candidate_ids = meta
1783 self._emit_mutex_op(1760 self._emit_mutex_op(
1784- buf_ids,1761+ _to_make_tuple([tile_id_irs], span),
1785- mutex_ids,1762+ _to_make_tuple([candidate_ids], span),
1786- [0] * len(buf_ids),
1787 pipe,1763 pipe,
1788 span,1764 span,
1789 is_lock=is_lock,1765 is_lock=is_lock,
@@ -1792,65 +1768,40 @@ class CallParserMixin:
1792 1768 
1793 def _emit_mutex_op(1769 def _emit_mutex_op(
1794 self,1770 self,
1795- buf_ids,1771+ mutex_id,
1796- mutex_ids,1772+ candidate_groups,
1797- mutex_id_owner_indices,
1798 pipe,1773 pipe,
1799 span: ir.Span,1774 span: ir.Span,
1800 *,1775 *,
1801 is_lock: bool,1776 is_lock: bool,
1802 ) -> None:1777 ) -> None:
1803- """Emit a per-tile-aware mutex dedup operation."""1778+ """Emit per-Tile mutex IDs and candidates for codegen-side deduplication."""
1804 from pypto_pro.ir.op.system_ops import _create_mutex_dedup_op1779 from pypto_pro.ir.op.system_ops import _create_mutex_dedup_op
1805 1780 
1806 op_name = "system.mutex_lock" if is_lock else "system.mutex_unlock"1781 op_name = "system.mutex_lock" if is_lock else "system.mutex_unlock"
1807- id_exprs = list(buf_ids)
1808 expr = _create_mutex_dedup_op(1782 expr = _create_mutex_dedup_op(
1809 op_name,1783 op_name,
1810 pipe=pipe,1784 pipe=pipe,
1811- mutex_id_exprs=id_exprs,1785+ mutex_id=mutex_id,
1812- mutex_id_owner_indices=mutex_id_owner_indices,1786+ candidate_groups=candidate_groups,
1813- mutex_ids_union=list(mutex_ids or ()),
1814 span=span,1787 span=span,
1815 )1788 )
1816 self.builder.emit(ir.EvalStmt(expr, span))1789 self.builder.emit(ir.EvalStmt(expr, span))
1817 1790 
1818- def _emit_mutex_for_groups(self, groups: list, pipe, span: ir.Span, *, is_lock: bool):1791+ def _emit_mutex_for_refs(self, refs: list, pipe, span: ir.Span, *, is_lock: bool) -> None:
1819- """Emit mutex lock/unlock calls for pre-grouped refs, with dedup if-guards.1792+ """Emit one mutex call containing all Tile references of the operation."""
1820- 1793+ if not refs:
1821- ``groups`` is the output of _group_refs_by_mutex_overlap (computed once at1794+ return
1822- lock time and reused at unlock time). Shared by lock (is_lock=True) and unlock1795+ self._emit_mutex_op(
1823- (is_lock=False). Each group uses one mutex_(un)lock_dyn whose CCE codegen1796+ _to_make_tuple([tile_ref.tile_ids for tile_ref in refs], span),
1824- guards possible aliases across Tiles while trusting the frontend's per-tile1797+ _to_make_tuple(
1825- uniqueness validation. Lock and unlock visit independent groups and IDs in1798+ [tile_ref.candidate_ids for tile_ref in refs],
1826- the same order.
1827- """
1828- for group in groups:
1829- id_exprs = [
1830- buf_id
1831- for tref in group
1832- for buf_id in tref.buf_ids
1833- ]
1834- mutex_id_owner_indices = [
1835- owner_index
1836- for owner_index, tref in enumerate(group)
1837- for _ in tref.buf_ids
1838- ]
1839- ids_union = list(
1840- dict.fromkeys(
1841- mutex_id
1842- for tref in group
1843- for mutex_id in (tref.mutex_ids or ())
1844- )
1845- )
1846- self._emit_mutex_op(
1847- id_exprs,
1848- ids_union,
1849- mutex_id_owner_indices,
1850- pipe,
1851 span,1799 span,
1852- is_lock=is_lock,1800+ ),
1853- )1801+ pipe,
1802+ span,
1803+ is_lock=is_lock,
1804+ )
1854 1805 
1855 def _emit_vf_func_mutex_lock(1806 def _emit_vf_func_mutex_lock(
1856 self,1807 self,
@@ -1859,17 +1810,17 @@ class CallParserMixin:
1859 used_params: set,1810 used_params: set,
1860 span: ir.Span,1811 span: ir.Span,
1861 ) -> list:1812 ) -> list:
1862- """Emit mutex_lock(V, buf_id) for tile-valued args whose matching1813+ """Emit mutex_lock(V, mutex_id) for tile-valued args whose matching
1863 parameter is referenced inside a ``@pl.vector_function`` body.1814 parameter is referenced inside a ``@pl.vector_function`` body.
1864 1815 
1865 Called before a VF func.call is emitted (i.e., before the VEC_SCOPE1816 Called before a VF func.call is emitted (i.e., before the VEC_SCOPE
1866- is generated). Returns the ref grouping (from _group_refs_by_mutex_overlap)1817+ is generated). Returns the reference grouping so the caller can emit
1867- so the caller can emit matching unlocks after the call without re-grouping.1818+ matching unlocks after the call without rebuilding it.
1868 """1819 """
1869 unique_refs = []1820 unique_refs = []
1870 seen = set()1821 seen = set()
1871 for param_name, tref in zip(param_names, arg_tilerefs):1822 for param_name, tref in zip(param_names, arg_tilerefs):
1872- if tref is None or not tref.buf_ids:1823+ if tref is None or not tref.tile_ids.elements:
1873 continue1824 continue
1874 if param_name not in used_params:1825 if param_name not in used_params:
1875 continue1826 continue
@@ -1878,13 +1829,13 @@ class CallParserMixin:
1878 seen.add(tref.slot_id)1829 seen.add(tref.slot_id)
1879 unique_refs.append(tref)1830 unique_refs.append(tref)
1880 1831 
1881- groups = self._group_refs_by_mutex_overlap(unique_refs)1832+ self._record_mutex_op_constraints(unique_refs)
1882- self._emit_mutex_for_groups(groups, ir.PipeType.V, span, is_lock=True)1833+ self._emit_mutex_for_refs(unique_refs, ir.PipeType.V, span, is_lock=True)
1883- return groups1834+ return unique_refs
1884 1835 
1885- def _emit_inline_vf_mutex_unlock(self, groups: list, span: ir.Span) -> None:1836+ def _emit_inline_vf_mutex_unlock(self, refs: list, span: ir.Span) -> None:
1886- """Emit mutex_unlock(V, buf_id) for each group from _emit_vf_func_mutex_lock."""1837+ """Emit mutex_unlock(V, mutex_id) for refs from _emit_vf_func_mutex_lock."""
1887- self._emit_mutex_for_groups(groups, ir.PipeType.V, span, is_lock=False)1838+ self._emit_mutex_for_refs(refs, ir.PipeType.V, span, is_lock=False)
1888 1839 
1889 # -------------------------------------------------------------------------1840 # -------------------------------------------------------------------------
1890 # Block default handler and helpers1841 # Block default handler and helpers
@@ -18,6 +18,7 @@ from typing import Any, Callable
18from pypto.pypto_impl import ir18from pypto.pypto_impl import ir
19from pypto.pypto_impl.ir import DataType19from pypto.pypto_impl.ir import DataType
20from pypto_pro.ir._limits import INT64_MAX, INT64_MIN, from_storage_int20from pypto_pro.ir._limits import INT64_MAX, INT64_MIN, from_storage_int
21+from pypto_pro.ir._utils import _to_make_tuple
21 22 
22from ..._errors import InvalidArgument, InvalidOperation, InvalidType, InvalidVal, NotSupported, OutOfRange23from ..._errors import InvalidArgument, InvalidOperation, InvalidType, InvalidVal, NotSupported, OutOfRange
23from ._expr_evaluator import ExprEvaluator24from ._expr_evaluator import ExprEvaluator
@@ -106,7 +107,7 @@ class _LoopMergeSlot:
106 init_value: ir.Expr107 init_value: ir.Expr
107 iter_var: ir.Var108 iter_var: ir.Var
108 state: LoopVarState109 state: LoopVarState
109- mutex_iter_vars: tuple[ir.Var, ...] = ()110+ tile_id_iter_vars: ir.MakeTuple | None = None
110 111 
111 112 
112def validate_single_tail_return(func_def: ast.FunctionDef, context: str) -> tuple[ast.Return, str, str] | None:113def validate_single_tail_return(func_def: ast.FunctionDef, context: str) -> tuple[ast.Return, str, str] | None:
@@ -161,7 +162,7 @@ class ControlFlowParserMixin:
161 162 
162 def _merge_tile_mutex_meta_pair(163 def _merge_tile_mutex_meta_pair(
163 self, first_value: ir.Expr, second_value: ir.Expr, span: ir.Span164 self, first_value: ir.Expr, second_value: ir.Expr, span: ir.Span
164- ) -> tuple[tuple[ir.Expr, ...], tuple[ir.Expr, ...], list[Any]] | None:165+ ) -> tuple[ir.MakeTuple, ir.MakeTuple, ir.MakeTuple] | None:
165 """Align two runtime mutex-id lists and union their static candidates."""166 """Align two runtime mutex-id lists and union their static candidates."""
166 if not self._auto_mutex:167 if not self._auto_mutex:
167 return None168 return None
@@ -171,7 +172,7 @@ class ControlFlowParserMixin:
171 return None172 return None
172 if first_meta is None or second_meta is None:173 if first_meta is None or second_meta is None:
173 present_meta = first_meta if first_meta is not None else second_meta174 present_meta = first_meta if first_meta is not None else second_meta
174- if not present_meta[1]:175+ if not present_meta[1].elements:
175 return None176 return None
176 raise InvalidOperation(177 raise InvalidOperation(
177 "Cannot merge Tile values when only one input carries mutex metadata",178 "Cannot merge Tile values when only one input carries mutex metadata",
@@ -179,28 +180,33 @@ class ControlFlowParserMixin:
179 hint="Ensure all values come from the same auto-mutex tile-group flow",180 hint="Ensure all values come from the same auto-mutex tile-group flow",
180 parser_retry=True,181 parser_retry=True,
181 )182 )
182- first_mutex_ids, first_candidates = first_meta183+ first_tile_ids, first_candidates = first_meta
183- second_mutex_ids, second_candidates = second_meta184+ second_tile_ids, second_candidates = second_meta
184- if len(first_mutex_ids) != len(second_mutex_ids):185+ if len(first_tile_ids.elements) != len(second_tile_ids.elements):
185- if not first_candidates and len(first_mutex_ids) == 1:186+ if not first_candidates.elements and len(first_tile_ids.elements) == 1:
186- first_mutex_ids = tuple(first_mutex_ids) * len(second_mutex_ids)187+ first_tile_ids = _to_make_tuple(
187- elif not second_candidates and len(second_mutex_ids) == 1:188+ first_tile_ids.elements * len(second_tile_ids.elements), span
188- second_mutex_ids = tuple(second_mutex_ids) * len(first_mutex_ids)189+ )
190+ elif not second_candidates.elements and len(second_tile_ids.elements) == 1:
191+ second_tile_ids = _to_make_tuple(
192+ second_tile_ids.elements * len(first_tile_ids.elements), span
193+ )
189 else:194 else:
190 raise InvalidOperation(195 raise InvalidOperation(
191 "cannot merge tile mutex metadata with different ID counts: "196 "cannot merge tile mutex metadata with different ID counts: "
192- f"{len(first_mutex_ids)} and {len(second_mutex_ids)}",197+ f"{len(first_tile_ids.elements)} and {len(second_tile_ids.elements)}",
193 span=span,198 span=span,
194 parser_retry=True,199 parser_retry=True,
195 )200 )
196- candidates = list(201+ candidates = _to_make_tuple(
197- dict.fromkeys(list(first_candidates or ()) + list(second_candidates or ()))202+ list(dict.fromkeys([*first_candidates.elements, *second_candidates.elements])),
203+ span,
198 )204 )
199- return tuple(first_mutex_ids), tuple(second_mutex_ids), candidates205+ return first_tile_ids, second_tile_ids, candidates
200 206 
201 def _merge_control_flow_mutex_ids(207 def _merge_control_flow_mutex_ids(
202 self, values: list[ir.Expr], span: ir.Span208 self, values: list[ir.Expr], span: ir.Span
203- ) -> tuple[list[tuple[ir.Expr, ...]], list[Any]] | None:209+ ) -> tuple[list[ir.MakeTuple], ir.MakeTuple] | None:
204 """Align one explicit Tile slot's mutex ids across its CFG inputs."""210 """Align one explicit Tile slot's mutex ids across its CFG inputs."""
205 if not self._auto_mutex or not values:211 if not self._auto_mutex or not values:
206 return None212 return None
@@ -208,47 +214,48 @@ class ControlFlowParserMixin:
208 mutex_meta = self._tile_mutex_meta.get(values[0])214 mutex_meta = self._tile_mutex_meta.get(values[0])
209 if mutex_meta is None:215 if mutex_meta is None:
210 return None216 return None
211- mutex_ids, candidates = mutex_meta217+ tile_ids, candidates = mutex_meta
212- return [tuple(mutex_ids)], list(candidates or ())218+ return [tile_ids], candidates
213 if len(values) == 2:219 if len(values) == 2:
214 merged = self._merge_tile_mutex_meta_pair(values[0], values[1], span)220 merged = self._merge_tile_mutex_meta_pair(values[0], values[1], span)
215 if merged is None:221 if merged is None:
216 return None222 return None
217- first_mutex_ids, second_mutex_ids, candidates = merged223+ first_tile_ids, second_tile_ids, candidates = merged
218- return [tuple(first_mutex_ids), tuple(second_mutex_ids)], candidates224+ return [first_tile_ids, second_tile_ids], candidates
219 225 
220 exemplar = next(226 exemplar = next(
221 (227 (
222 value228 value
223 for value in values229 for value in values
224- if (meta := self._tile_mutex_meta.get(value)) is not None and meta[1]230+ if (meta := self._tile_mutex_meta.get(value)) is not None and meta[1].elements
225 ),231 ),
226 None,232 None,
227 )233 )
228 if exemplar is None:234 if exemplar is None:
229 return None235 return None
230 236 
231- tile_mutex_id_outputs: list[tuple[ir.Expr, ...]] = []237+ tile_id_outputs: list[ir.MakeTuple] = []
232 candidates: list[Any] = []238 candidates: list[Any] = []
233 for value in values:239 for value in values:
234 merged = self._merge_tile_mutex_meta_pair(value, exemplar, span)240 merged = self._merge_tile_mutex_meta_pair(value, exemplar, span)
235 if merged is None:241 if merged is None:
236 raise InvalidOperation("Cannot merge Tile values without mutex metadata", span=span, parser_retry=True)242 raise InvalidOperation("Cannot merge Tile values without mutex metadata", span=span, parser_retry=True)
237- value_mutex_ids, _, value_candidates = merged243+ value_tile_ids, _, value_candidates = merged
238- tile_mutex_id_outputs.append(tuple(value_mutex_ids))244+ tile_id_outputs.append(value_tile_ids)
239- candidates.extend(value_candidates)245+ candidates.extend(value_candidates.elements)
240- return tile_mutex_id_outputs, list(dict.fromkeys(candidates))246+ return tile_id_outputs, _to_make_tuple(list(dict.fromkeys(candidates)), span)
241 247 
242- def _create_mutex_id_vars(248+ def _create_tile_id_vars(self, name: str, count: int, span: ir.Span) -> ir.MakeTuple:
243- self, name: str, count: int, span: ir.Span249+ return _to_make_tuple(
244- ) -> tuple[ir.Var, ...]:250+ [
245- return tuple(251+ self.builder.var(
246- self.builder.var(252+ f"{name}__mutexid" if index == 0 else f"{name}__mutexid_{index}",
247- f"{name}__mutexid" if index == 0 else f"{name}__mutexid_{index}",253+ ir.ScalarType(DataType.INT64),
248- ir.ScalarType(DataType.INT64),254+ span,
249- span,255+ )
250- )256+ for index in range(count)
251- for index in range(count)257+ ],
258+ span,
252 )259 )
253 260 
254 def _parse_statement_list(self, statements: list[ast.stmt]) -> JumpKind | None:261 def _parse_statement_list(self, statements: list[ast.stmt]) -> JumpKind | None:
@@ -480,10 +487,10 @@ class ControlFlowParserMixin:
480 )487 )
481 return slots488 return slots
482 489 
483- def _prepare_loop_mutex_iter_vars(490+ def _prepare_loop_tile_id_iter_vars(
484 self, slots: list[_LoopMergeSlot], span: ir.Span491 self, slots: list[_LoopMergeSlot], span: ir.Span
485 ) -> None:492 ) -> None:
486- """Expose provisional mutex iter vars while parsing the loop body."""493+ """Expose provisional Tile-ID iter vars while parsing the loop body."""
487 if not self._auto_mutex:494 if not self._auto_mutex:
488 return495 return
489 for slot in slots:496 for slot in slots:
@@ -492,14 +499,11 @@ class ControlFlowParserMixin:
492 mutex_meta = self._tile_mutex_meta.get(slot.init_value)499 mutex_meta = self._tile_mutex_meta.get(slot.init_value)
493 if mutex_meta is None:500 if mutex_meta is None:
494 continue501 continue
495- mutex_ids, candidates = mutex_meta502+ tile_ids, candidates = mutex_meta
496- slot.mutex_iter_vars = self._create_mutex_id_vars(503+ slot.tile_id_iter_vars = self._create_tile_id_vars(
497- slot.name, len(mutex_ids), span504+ slot.name, len(tile_ids.elements), span
498- )
499- self._tile_mutex_meta[slot.iter_var] = (
500- slot.mutex_iter_vars,
501- list(candidates or ()),
502 )505 )
506+ self._tile_mutex_meta[slot.iter_var] = (slot.tile_id_iter_vars, candidates)
503 507 
504 def _parse_loop_region(508 def _parse_loop_region(
505 self,509 self,
@@ -591,31 +595,31 @@ class ControlFlowParserMixin:
591 mutex_merge = self._merge_control_flow_mutex_ids(values, span)595 mutex_merge = self._merge_control_flow_mutex_ids(values, span)
592 if mutex_merge is None:596 if mutex_merge is None:
593 continue597 continue
594- mutex_ids_by_source, candidates = mutex_merge598+ tile_ids_by_source, candidates = mutex_merge
595- init_mutex_ids, *mutex_ids_by_jump = mutex_ids_by_source599+ init_tile_ids, *tile_ids_by_jump = tile_ids_by_source
596- if not slot.mutex_iter_vars:600+ if slot.tile_id_iter_vars is None:
597- slot.mutex_iter_vars = self._create_mutex_id_vars(601+ slot.tile_id_iter_vars = self._create_tile_id_vars(
598- slot.name, len(init_mutex_ids), span602+ slot.name, len(init_tile_ids.elements), span
599 )603 )
600- mutex_return_vars = self._create_mutex_id_vars(604+ tile_id_return_vars = self._create_tile_id_vars(
601- slot.name, len(init_mutex_ids), span605+ slot.name, len(init_tile_ids.elements), span
602 )606 )
603- for mutex_iter_var, mutex_init_value in zip(607+ for mutex_iter_var, tile_init_value in zip(
604- slot.mutex_iter_vars, init_mutex_ids, strict=True608+ slot.tile_id_iter_vars.elements, init_tile_ids.elements, strict=True
605 ):609 ):
606 iter_args.append(610 iter_args.append(
607 self.builder.builder.create_iter_arg(611 self.builder.builder.create_iter_arg(
608- mutex_iter_var, mutex_init_value612+ mutex_iter_var, tile_init_value
609 )613 )
610 )614 )
611- return_vars.extend(mutex_return_vars)615+ return_vars.extend(tile_id_return_vars.elements)
612- for jump_mutex_ids, tile_mutex_ids in zip(616+ for jump_mutex_ids, tile_ids in zip(
613- mutex_outputs_by_jump, mutex_ids_by_jump, strict=True617+ mutex_outputs_by_jump, tile_ids_by_jump, strict=True
614 ):618 ):
615- jump_mutex_ids.extend(tile_mutex_ids)619+ jump_mutex_ids.extend(tile_ids.elements)
616 620 
617 if isinstance(return_var.type, ir.TileType):621 if isinstance(return_var.type, ir.TileType):
618- self._tile_mutex_meta[return_var] = (mutex_return_vars, candidates)622+ self._tile_mutex_meta[return_var] = (tile_id_return_vars, candidates)
619 623 
620 for jump, jump_mutex_ids in zip(info.jumps, mutex_outputs_by_jump, strict=True):624 for jump, jump_mutex_ids in zip(info.jumps, mutex_outputs_by_jump, strict=True):
621 if jump.jump_op is None:625 if jump.jump_op is None:
@@ -640,7 +644,7 @@ class ControlFlowParserMixin:
640 if not self._is_empty_control_flow_value(slot.init_value):644 if not self._is_empty_control_flow_value(slot.init_value):
641 slot.state.result_phi.propagate(slot.init_value)645 slot.state.result_phi.propagate(slot.init_value)
642 info = ControlFlowInfo(merge_names)646 info = ControlFlowInfo(merge_names)
643- self._prepare_loop_mutex_iter_vars(slots, span)647+ self._prepare_loop_tile_id_iter_vars(slots, span)
644 loop_var = self.builder.var(loop_var_name, ir.ScalarType(DataType.INT64), span)648 loop_var = self.builder.var(loop_var_name, ir.ScalarType(DataType.INT64), span)
645 with self.scope_manager.change_loop_info(info):649 with self.scope_manager.change_loop_info(info):
646 body = self._parse_loop_region(650 body = self._parse_loop_region(
@@ -720,7 +724,7 @@ class ControlFlowParserMixin:
720 merge_names = tuple(name for name, _ in merge_inputs)724 merge_names = tuple(name for name, _ in merge_inputs)
721 slots = self._create_loop_slots(merge_inputs, span)725 slots = self._create_loop_slots(merge_inputs, span)
722 info = ControlFlowInfo(merge_names)726 info = ControlFlowInfo(merge_names)
723- self._prepare_loop_mutex_iter_vars(slots, span)727+ self._prepare_loop_tile_id_iter_vars(slots, span)
724 with self.scope_manager.change_loop_info(info):728 with self.scope_manager.change_loop_info(info):
725 body = self._parse_loop_region(loop_body, "while", span, slots)729 body = self._parse_loop_region(loop_body, "while", span, slots)
726 iter_args, return_vars, merged_bindings = self._finalize_loop_slots(730 iter_args, return_vars, merged_bindings = self._finalize_loop_slots(
@@ -795,16 +799,16 @@ class ControlFlowParserMixin:
795 mutex_merge = self._merge_control_flow_mutex_ids(values, span)799 mutex_merge = self._merge_control_flow_mutex_ids(values, span)
796 if mutex_merge is None:800 if mutex_merge is None:
797 continue801 continue
798- tile_mutex_id_outputs, candidates = mutex_merge802+ tile_id_outputs, candidates = mutex_merge
799- mutex_vars = self._create_mutex_id_vars(803+ tile_id_vars = self._create_tile_id_vars(
800- name, len(tile_mutex_id_outputs[0]), span804+ name, len(tile_id_outputs[0].elements), span
801 )805 )
802- return_vars.extend(mutex_vars)806+ return_vars.extend(tile_id_vars.elements)
803- for jump_mutex_ids, tile_mutex_ids in zip(807+ for jump_mutex_ids, tile_ids in zip(
804- jump_mutex_id_outputs, tile_mutex_id_outputs, strict=True808+ jump_mutex_id_outputs, tile_id_outputs, strict=True
805 ):809 ):
806- jump_mutex_ids.extend(tile_mutex_ids)810+ jump_mutex_ids.extend(tile_ids.elements)
807- self._tile_mutex_meta[merged_var] = (mutex_vars, candidates)811+ self._tile_mutex_meta[merged_var] = (tile_id_vars, candidates)
808 812 
809 for jump, jump_mutex_ids in zip(info.jumps, jump_mutex_id_outputs, strict=True):813 for jump, jump_mutex_ids in zip(info.jumps, jump_mutex_id_outputs, strict=True):
810 if jump.jump_op is None:814 if jump.jump_op is None:
@@ -18,7 +18,7 @@ from pypto.pypto_impl import ir
18from pypto.pypto_impl.ir import DataType18from pypto.pypto_impl.ir import DataType
19from pypto_pro.ir import op as ir_op19from pypto_pro.ir import op as ir_op
20from pypto_pro.ir._operators import make_binary as _make_binary20from pypto_pro.ir._operators import make_binary as _make_binary
21-from pypto_pro.ir._utils import _normalize_expr21+from pypto_pro.ir._utils import _normalize_expr, _to_make_tuple
22 22 
23from ..._errors import (23from ..._errors import (
24 InvalidFormat,24 InvalidFormat,
@@ -323,7 +323,10 @@ class ExpressionParserMixin:
323 """323 """
324 none_expr = self.builder.builder.none()324 none_expr = self.builder.builder.none()
325 if self._auto_mutex and none_expr not in self._tile_mutex_meta:325 if self._auto_mutex and none_expr not in self._tile_mutex_meta:
326- self._tile_mutex_meta[none_expr] = ((ir.ConstInt(-1, DataType.INT64, span),), [])326+ self._tile_mutex_meta[none_expr] = (
327+ _to_make_tuple([ir.ConstInt(-1, DataType.INT64, span)], span),
328+ _to_make_tuple([], span),
329+ )
327 return none_expr330 return none_expr
328 331 
329 def tile_mutex_lock_meta(self, expr):332 def tile_mutex_lock_meta(self, expr):
@@ -333,7 +336,7 @@ class ExpressionParserMixin:
333 candidate ids, so the ``None`` seed (which carries none) never turns into a lock.336 candidate ids, so the ``None`` seed (which carries none) never turns into a lock.
334 """337 """
335 meta = self._tile_mutex_meta.get(expr)338 meta = self._tile_mutex_meta.get(expr)
336- return meta if meta is not None and meta[1] else None339+ return meta if meta is not None and meta[1].elements else None
337 340 
338 def parse_constant(self, const: ast.Constant) -> ir.Expr:341 def parse_constant(self, const: ast.Constant) -> ir.Expr:
339 """Parse constant value.342 """Parse constant value.
@@ -942,7 +945,7 @@ class ExpressionParserMixin:
942 item_expr = ir.GetItemExpr(value_expr, index_expr, span)945 item_expr = ir.GetItemExpr(value_expr, index_expr, span)
943 # A subscript aliases the base's buffer, so carry the base's mutex946 # A subscript aliases the base's buffer, so carry the base's mutex
944 # metadata onto the item. auto_mutex then locks accesses to the item on947 # metadata onto the item. auto_mutex then locks accesses to the item on
945- # the base's buf_id; it is consumed when the item is bound to a var (see948+ # the base's Tile-ID metadata; it is consumed when the item is bound to a var (see
946 # _transfer_tile_sync_metadata).949 # _transfer_tile_sync_metadata).
947 meta = self._tile_mutex_meta.get(value_expr)950 meta = self._tile_mutex_meta.get(value_expr)
948 if meta is not None:951 if meta is not None:
@@ -54,6 +54,7 @@ def get_op_pipe(op_name: str) -> PipeType | None:
54# OP_VIEW / OP_VIEW_TYPE / OP_RESHAPE / OP_ASSEMBLE from synchronisation.54# OP_VIEW / OP_VIEW_TYPE / OP_RESHAPE / OP_ASSEMBLE from synchronisation.
55_DESCRIPTOR_ONLY_OPS: frozenset[str] = frozenset(55_DESCRIPTOR_ONLY_OPS: frozenset[str] = frozenset(
56 {56 {
57+ "make_tile_group", # Declares storage metadata; does not access tile data.
57 "set_validshape",58 "set_validshape",
58 }59 }
59)60)
@@ -32,6 +32,7 @@ from pypto_pro.language.parser._ast_parser import ASTParser
32from pypto_pro.language.typing.direction import TensorDirection32from pypto_pro.language.typing.direction import TensorDirection
33 33 
34from .._errors import (34from .._errors import (
35+ CommonInner,
35 NameNotFound,36 NameNotFound,
36 PyptoProError,37 PyptoProError,
37 RuntimeFailure,38 RuntimeFailure,
@@ -42,6 +43,8 @@ from .._errors import (
42 spec_head_of,43 spec_head_of,
43)44)
44 45 
46+AutoMutexIdManager = ir._AutoMutexIdManager
47+ 
45 48 
46def _calculate_col_offset(source_lines: list[str]) -> int:49def _calculate_col_offset(source_lines: list[str]) -> int:
47 """Calculate the column offset (indentation) of the first non-empty line.50 """Calculate the column offset (indentation) of the first non-empty line.
@@ -257,6 +260,9 @@ class KernelDef:
257 program_name = self._name if self._name is not None else self._func.__name__260 program_name = self._name if self._name is not None else self._func.__name__
258 261 
259 try:262 try:
263+ # Each target parse owns one mutex ID manager, so Cube and Vector both use
264+ # their own independent 0-31 mutex ID pool.
265+ mutex_id_manager = AutoMutexIdManager() if self._auto_mutex else None
260 # The Program owns one IRDebugInfo; share it with the parser so all266 # The Program owns one IRDebugInfo; share it with the parser so all
261 # semantic tuple metadata lands in the table the Program carries.267 # semantic tuple metadata lands in the table the Program carries.
262 debug_info = ir.IRDebugInfo()268 debug_info = ir.IRDebugInfo()
@@ -277,6 +283,7 @@ class KernelDef:
277 void_return_only=True,283 void_return_only=True,
278 void_return_context="@pl.jit",284 void_return_context="@pl.jit",
279 allow_early_return=True,285 allow_early_return=True,
286+ mutex_id_manager=mutex_id_manager,
280 )287 )
281 288 
282 try:289 try:
@@ -337,6 +344,15 @@ class KernelDef:
337 self._last_param_directions = dict(parser.type_resolver.param_directions)344 self._last_param_directions = dict(parser.type_resolver.param_directions)
338 self._max_vec_tile_end = parser.max_vec_tile_end345 self._max_vec_tile_end = parser.max_vec_tile_end
339 self._requires_simt = parser.requires_simt346 self._requires_simt = parser.requires_simt
347+ if mutex_id_manager is not None:
348+ try:
349+ program = mutex_id_manager.assign_mutex_ids(program)
350+ except Exception as exc:
351+ wrapper = error_class_of_spec_message(str(exc)) or CommonInner
352+ raise wrapper(
353+ str(exc),
354+ span=span_of_spec_message(str(exc)) or mutex_id_manager.diagnostic_span,
355+ ) from None
340 return program, parser.matched_target356 return program, parser.matched_target
341 357 
342 except PyptoProError as e:358 except PyptoProError as e:
@@ -34,6 +34,7 @@ from ._cross_core_scanner import (
34 scan_all_tile_group_names,34 scan_all_tile_group_names,
35 scan_buffer_addr_ranges,35 scan_buffer_addr_ranges,
36 scan_buffer_mutex_ids,36 scan_buffer_mutex_ids,
37+ scan_buffer_slot_counts,
37 scan_cross_core_buffers,38 scan_cross_core_buffers,
38 scan_kernel_slot_to_buffer,39 scan_kernel_slot_to_buffer,
39 scan_stage_accesses,40 scan_stage_accesses,
@@ -277,9 +278,11 @@ def _scan_kernel_buffers(
277 scans below is the order their errors surface in, so it is deliberate: the cross-core278 scans below is the order their errors surface in, so it is deliberate: the cross-core
278 scan raises on an unusable declaration, the rest only collect what they can resolve.279 scan raises on an unusable declaration, the rest only collect what they can resolve.
279 """280 """
280- # Filled before the early return below: _collect_outer_slots needs a slot count for local281+ # Filled before the early return below: _collect_outer_slots needs a slot count for
281- # groups too. This scan raises on nothing, so its position affects no diagnostic.282+ # local groups too. These scans raise on nothing — they skip declarations whose layout
283+ # will not resolve — so their position decides nothing about which error a user sees.
282 sync.mutex_ids = scan_buffer_mutex_ids(decls, closure_vars)284 sync.mutex_ids = scan_buffer_mutex_ids(decls, closure_vars)
285+ sync.slot_counts = scan_buffer_slot_counts(decls, closure_vars)
283 286 
284 cross_buffers, lifted_ids = scan_cross_core_buffers(decls, closure_vars)287 cross_buffers, lifted_ids = scan_cross_core_buffers(decls, closure_vars)
285 sync.buffers = cross_buffers288 sync.buffers = cross_buffers
@@ -631,15 +634,15 @@ def _collect_outer_slots(info: PipelineInfo) -> dict:
631 task stream, so the variable never moves and the argument passes through; and two634 task stream, so the variable never moves and the argument passes through; and two
632 pipelines' outer loops are disjoint, which keeps their same-named picks apart.635 pipelines' outer loops are disjoint, which keeps their same-named picks apart.
633 636 
634- Only slots a stage consumes are kept. A group whose mutex_ids do not resolve statically is637+ Only slots a stage actually consumes are kept; pure bookkeeping slots are left alone.
635- an error rather than a skip: the rewrite needs the count as its modulus.638+ The rewrite needs the slot count as its modulus, so a group whose depth or mutex_ids do
639+ not resolve statically is reported as an error rather than silently skipped — skipping
640+ it would leave the delayed stage reading the wrong slot with no diagnostic.
636 """641 """
637 groups = info.group_names642 groups = info.group_names
638 if not groups or info.pipeline_loop is None or info.outer_loop is None:643 if not groups or info.pipeline_loop is None or info.outer_loop is None:
639 return {}644 return {}
640- # One lock per slot. No fall-back to addr_ranges (which _sync_graph._slot_count has): they645+ slot_counts = info.sync.slot_counts
641- # are not scanned yet here, and an outer slot needs an EXACT count.
642- slot_counts = {name: len(ids) for name, ids in info.sync.mutex_ids.items()}
643 646 
644 consumed = {647 consumed = {
645 arg.id for stage in info.stages for arg in stage.args if isinstance(arg, ast.Name)648 arg.id for stage in info.stages for arg in stage.args if isinstance(arg, ast.Name)
@@ -669,7 +672,7 @@ def _collect_outer_slots(info: PipelineInfo) -> dict:
669 if group not in slot_counts:672 if group not in slot_counts:
670 raise InvalidOperation(673 raise InvalidOperation(
671 f"pipeline: slot '{target.id}' is taken from tile group '{group}' outside "674 f"pipeline: slot '{target.id}' is taken from tile group '{group}' outside "
672- f"the pipeline loop, but '{group}'s mutex_ids could not be resolved "675+ f"the pipeline loop, but '{group}'s depth or mutex_ids could not be resolved "
673 f"statically, so the number of slots is unknown. The transform needs it to "676 f"statically, so the number of slots is unknown. The transform needs it to "
674 f"give each stage the slot from its own iteration."677 f"give each stage the slot from its own iteration."
675 )678 )
@@ -897,6 +900,7 @@ def probe_kernel_facts(kernel_def, bound_signature=None) -> tuple[dict, dict]:
897 if_const: dict = {}900 if_const: dict = {}
898 var_types: dict = {}901 var_types: dict = {}
899 for target in (ir.SectionKind.Cube, ir.SectionKind.Vector):902 for target in (ir.SectionKind.Cube, ir.SectionKind.Vector):
903+ # The probe discards parsed IR, so AUTO placeholders do not need resolution.
900 parser = ASTParser(904 parser = ASTParser(
901 kernel_def._source_file,905 kernel_def._source_file,
902 kernel_def._source_lines,906 kernel_def._source_lines,
@@ -913,6 +917,7 @@ def probe_kernel_facts(kernel_def, bound_signature=None) -> tuple[dict, dict]:
913 void_return_only=True,917 void_return_only=True,
914 void_return_context="@pl.jit",918 void_return_context="@pl.jit",
915 allow_early_return=True,919 allow_early_return=True,
920+ mutex_id_manager=ir._AutoMutexIdManager() if kernel_def._auto_mutex else None,
916 )921 )
917 parser.collect_if_const = True922 parser.collect_if_const = True
918 # define_var is the single point where every name gets bound, so wrapping it here923 # define_var is the single point where every name gets bound, so wrapping it here
@@ -120,6 +120,8 @@ class CrossCoreSyncContext:
120 # buffer name -> tuple of mutex ids. Used to check that co-located buffers hold the120 # buffer name -> tuple of mutex ids. Used to check that co-located buffers hold the
121 # same locks (a mutex locks the address, not the variable).121 # same locks (a mutex locks the address, not the variable).
122 mutex_ids: dict = field(default_factory=dict)122 mutex_ids: dict = field(default_factory=dict)
123+ # buffer name -> static TileGroup depth. AUTO uses this before IDs are planned.
124+ slot_counts: dict = field(default_factory=dict)
123 # Address-overlapping buffer pairs: [(buf_a, buf_b), ...] (same memory, ranges intersect)125 # Address-overlapping buffer pairs: [(buf_a, buf_b), ...] (same memory, ranges intersect)
124 addr_overlaps: list = field(default_factory=list)126 addr_overlaps: list = field(default_factory=list)
125 # Address-reuse sync is derived from the graph on demand, not stored here — see127 # Address-reuse sync is derived from the graph on demand, not stored here — see
@@ -271,6 +273,29 @@ def _eval_const(node: ast.expr, closure_vars: dict):
271 return None273 return None
272 274 
273 275 
276+def scan_buffer_slot_counts(decls: list[TileGroupDecl], closure_vars: dict) -> dict[str, int]:
277+ """Return each structurally valid TileGroup's static slot count."""
278+ result: dict[str, int] = {}
279+ for decl in decls:
280+ mutex_node = decl.mutex_ids_node
281+ depth_node = decl.depth_node
282+ mutex_ids = _eval_const(mutex_node, closure_vars) if mutex_node is not None else None
283+ depth = _eval_const(depth_node, closure_vars) if depth_node is not None else None
284+ if depth_node is not None:
285+ if isinstance(depth, bool) or not isinstance(depth, int) or depth <= 0:
286+ continue
287+ count = depth
288+ elif isinstance(mutex_ids, (list, tuple)) and mutex_ids:
289+ count = len(mutex_ids)
290+ else:
291+ continue
292+ if isinstance(mutex_ids, (list, tuple)) and mutex_ids and len(mutex_ids) != count:
293+ continue
294+ for name in decl.names:
295+ result[name] = count
296+ return result
297+ 
298+ 
274def _tile_type_slot_size(type_call: ast.Call, closure_vars: dict) -> int | None:299def _tile_type_slot_size(type_call: ast.Call, closure_vars: dict) -> int | None:
275 """Compute per-slot byte size from a pl.TileType(shape=..., dtype=...) call.300 """Compute per-slot byte size from a pl.TileType(shape=..., dtype=...) call.
276 Returns None if shape/dtype cannot be resolved.301 Returns None if shape/dtype cannot be resolved.
@@ -330,7 +355,7 @@ def scan_buffer_addr_ranges(decls: list[TileGroupDecl], closure_vars: dict) -> d
330 addrs = _eval_const(addrs_node, closure_vars)355 addrs = _eval_const(addrs_node, closure_vars)
331 if slot_size is None or addrs is None:356 if slot_size is None or addrs is None:
332 continue357 continue
333- if mutex_ids is not None and not isinstance(mutex_ids, (list, tuple)):358+ if mutex_ids != "auto" and mutex_ids is not None and not isinstance(mutex_ids, (list, tuple)):
334 continue359 continue
335 if depth_node is not None:360 if depth_node is not None:
336 if isinstance(depth, bool) or not isinstance(depth, int) or depth <= 0:361 if isinstance(depth, bool) or not isinstance(depth, int) or depth <= 0:
@@ -135,19 +135,19 @@ class SyncGraph:
135def _slot_count(info, buffer: str) -> int:135def _slot_count(info, buffer: str) -> int:
136 """How many slots a buffer rotates through, i.e. the modulus of ``task % slot_count``.136 """How many slots a buffer rotates through, i.e. the modulus of ``task % slot_count``.
137 137 
138- Read from the buffer's mutex_ids — one lock per slot — rather than from its address138+ Read from the declaration's normalized depth/ID-list length. AUTO groups have no IDs
139- ranges: both give the same number, but scan_buffer_addr_ranges is allowed to skip a139+ yet during pipeline transformation, so depth is the authoritative structural count.
140- buffer it cannot size, while every buffer in the graph needs a slot count.140+ Address ranges remain only a fallback for older analysis inputs.
141 """141 """
142- ids = info.sync.mutex_ids.get(buffer)142+ count = info.sync.slot_counts.get(buffer)
143- if ids:143+ if count:
144- return len(ids)144+ return count
145 ranges = info.sync.addr_ranges.get(buffer)145 ranges = info.sync.addr_ranges.get(buffer)
146 if ranges:146 if ranges:
147 return len(ranges[1])147 return len(ranges[1])
148 raise InvalidOperation(148 raise InvalidOperation(
149 f"pipeline: cannot determine the slot count of buffer '{buffer}'. Its "149 f"pipeline: cannot determine the slot count of buffer '{buffer}'. Its "
150- f"make_tile_group needs a statically resolvable mutex_ids list."150+ f"make_tile_group needs a statically resolvable depth or mutex_ids list."
151 )151 )
152 152 
153 153 
@@ -14,6 +14,7 @@
14 14 
15#include "bindings/ir/bindings.h"15#include "bindings/ir/bindings.h"
16#include "core/error.h"16#include "core/error.h"
17+#include "ir/transforms/auto_mutex_id_manager.h"
17#include "ir/transforms/ir_property.h"18#include "ir/transforms/ir_property.h"
18#include "ir/transforms/pass_context.h"19#include "ir/transforms/pass_context.h"
19#include "ir/transforms/passes.h"20#include "ir/transforms/passes.h"
@@ -25,6 +26,15 @@ namespace ir {
25 26 
26void BindPasses(py::module_& m)27void BindPasses(py::module_& m)
27{28{
29+ py::class_<AutoMutexIdManager>(m, "_AutoMutexIdManager", "Internal whole-program automatic mutex-ID manager")
30+ .def(py::init<>())
31+ .def("collect_group", &AutoMutexIdManager::CollectGroup, py::arg("tiles"), py::arg("mutex_ids"),
32+ py::arg("group_name"))
33+ .def("record_op_constraints", &AutoMutexIdManager::RecordOpConstraints, py::arg("tile_id_groups"),
34+ py::arg("candidate_groups"))
35+ .def("assign_mutex_ids", &AutoMutexIdManager::AssignMutexIds, py::arg("program"))
36+ .def_property_readonly("diagnostic_span", &AutoMutexIdManager::DiagnosticSpan);
37+ 
28 py::enum_<IRProperty>(m, "IRProperty", "Verifiable IR properties")38 py::enum_<IRProperty>(m, "IRProperty", "Verifiable IR properties")
29 .value("SSAForm", IRProperty::SSAForm, "IR is in SSA form")39 .value("SSAForm", IRProperty::SSAForm, "IR is in SSA form")
30 .value("TypeChecked", IRProperty::TypeChecked, "IR has passed type checking")40 .value("TypeChecked", IRProperty::TypeChecked, "IR has passed type checking")
@@ -0,0 +1,664 @@
1+#!/usr/bin/env python3
2+# coding: utf-8
3+# Copyright (c) 2026 Huawei Technologies Co., Ltd.
4+# This program is free software and you can redistribute it and/or modify it under the terms and conditions of
5+# CANN Open Software License Agreement Version 2.0 (the "License").
6+# You may refer to the License for details. You should not use this file except in compliance with the License.
7+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR ANY KIND, EITHER EXPRESS OR IMPLIED,
8+# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
9+# See LICENSE in the root of the software repository for the full text of the License.
10+# -----------------------------------------------------------------------------------------------------------
11+ 
12+"""System tests for whole-kernel ``mutex_ids="auto"`` allocation.
13+ 
14+The cases cover balanced reuse once a single group exceeds the 32-ID pool,
15+AUTO groups coexisting with exhausted manual IDs and a manual candidate chain
16+in one compilation, per-slot manual-ID inheritance through address aliasing,
17+three AUTO groups overlapping in every Vec address pattern, non-contiguous
18+addresses visited out of order, groups created inside nested or branching
19+Python helpers, and independent Cube/Vector ID pools exercised by a combined
20+Cube+Vector kernel.
21+"""
22+ 
23+import os
24+ 
25+import pypto_pro.language as pl
26+import pytest
27+import torch
28+ 
29+import pypto
30+ 
31+ST_DEVICE_ID = int(os.environ.get("TILE_FWK_DEVICE_ID", 0))
32+ST_DEVICE = f"npu:{ST_DEVICE_ID}"
33+ 
34+ 
35+def _require_a5(device):
36+ try:
37+ torch.npu.set_device(device)
38+ except RuntimeError as exc:
39+ pytest.skip(f"NPU unavailable: {exc}")
40+ name = torch.npu.get_device_name()
41+ if "Ascend950" not in name:
42+ pytest.skip(f"Current device is {name}, not A5 (Ascend950). Skip.")
43+ 
44+ 
45+# ===========================================================================
46+# Pool pressure: more AUTO slots than the 32 available mutex IDs
47+# ===========================================================================
48+ 
49+OVER_32_ROWS = 16
50+OVER_32_COLS = 32
51+OVER_32_DEPTH = 33
52+OVER_32_FULL_ROWS = OVER_32_ROWS * OVER_32_DEPTH
53+ 
54+ 
55+@pl.jit(arch="a5", auto_mutex=True)
56+def auto_over_32_kernel(
57+ source: pl.Tensor[[OVER_32_FULL_ROWS, OVER_32_COLS], pl.DT_FP16],
58+ output: pl.Tensor[[OVER_32_FULL_ROWS, OVER_32_COLS], pl.DT_FP16],
59+):
60+ tile_type = pl.TileType(
61+ shape=[OVER_32_ROWS, OVER_32_COLS],
62+ dtype=pl.DT_FP16,
63+ target_memory=pl.MemorySpace.Vec,
64+ )
65+ group = pl.make_tile_group(
66+ type=tile_type,
67+ addrs=0,
68+ mutex_ids="auto",
69+ depth=OVER_32_DEPTH,
70+ )
71+ with pl.section_vector():
72+ for index in pl.range(0, OVER_32_DEPTH):
73+ tile = group[index]
74+ row = index * OVER_32_ROWS
75+ pl.load(tile, source, [row, 0])
76+ pl.add(tile, tile, tile)
77+ pl.store(output, tile, [row, 0])
78+ 
79+ 
80+@pytest.mark.soc("950")
81+@pypto.options(pass_options={"enable_slice": False})
82+def test_auto_more_than_32_tiles_runs_with_balanced_id_reuse():
83+ """A single AUTO group with 33 slots forces balanced reuse across the 32-ID pool."""
84+ _require_a5(ST_DEVICE)
85+ torch.manual_seed(4)
86+ source = torch.rand([OVER_32_FULL_ROWS, OVER_32_COLS], device=ST_DEVICE, dtype=torch.float16) * 2.0 - 1.0
87+ output = torch.zeros_like(source)
88+ 
89+ auto_over_32_kernel(source, output)
90+ torch.npu.synchronize()
91+ 
92+ torch.testing.assert_close(output.cpu().float(), source.cpu().float() * 2.0, rtol=3e-3, atol=3e-3)
93+ 
94+ 
95+# ===========================================================================
96+# Manual-ID coexistence and address aliasing
97+# ===========================================================================
98+ 
99+GUARD_ROWS = 16
100+GUARD_COLS = 32