Merged
feat(pypto_pro):unified error codes #6508
huanyongbenAdd on Sep 18
feat(pypto_pro):unified error codes #6508
Merged
huanyongbenAdd on Sep 18
Total: 143 files changed+5435-2926
@@ -36,10 +36,12 @@
36#include "ir/pipe.h"36#include "ir/pipe.h"
37#include "ir/span.h"37#include "ir/span.h"
38#include "ir/type.h"38#include "ir/type.h"
39+#include "pypto_pro/error.h"
39#include "tilefwk/error.h"40#include "tilefwk/error.h"
40 41 
41namespace pypto {42namespace pypto {
42namespace ir {43namespace ir {
44+using npu::tile_fwk::ExternalError;
43 45 
44// Forward declaration46// Forward declaration
45class Call;47class Call;
@@ -87,24 +89,25 @@ public:
87 [[nodiscard]] inline const OpPtr& GetOp() const89 [[nodiscard]] inline const OpPtr& GetOp() const
88 {90 {
89 // Check operator instance91 // Check operator instance
90- CHECK(op_) << "Operator '" + name_ + "' has no operator instance";92+ PRO_IR_CHECK(npu::tile_fwk::InternalError::COMMON_INNER_ERROR, op_)
93+ << "Operator '" + name_ + "' has no operator instance";
91 94 
92 // Check description is set95 // Check description is set
93- CHECK(description_.has_value()) << "Operator '" + name_ +96+ PRO_IR_CHECK(npu::tile_fwk::InternalError::COMMON_INNER_ERROR, description_.has_value())
94- "' has no description. Use .set_description() to provide one.";97+ << "Operator '" + name_ + "' has no description. Use .set_description() to provide one.";
95 98 
96 // Check op_category is set99 // Check op_category is set
97- CHECK(op_category_.has_value()) << "Operator '" + name_ +100+ PRO_IR_CHECK(npu::tile_fwk::InternalError::COMMON_INNER_ERROR, op_category_.has_value())
98- "' has no category. Use .set_op_category() to provide one.";101+ << "Operator '" + name_ + "' has no category. Use .set_op_category() to provide one.";
99 102 
100 // Check arguments are defined (either with arguments or marked as no_argument)103 // Check arguments are defined (either with arguments or marked as no_argument)
101- CHECK(arguments_.has_value())104+ PRO_IR_CHECK(ExternalError::INVALID_ARGUMENT, arguments_.has_value())
102 << "Operator '" + name_ +105 << "Operator '" + name_ +
103 "' has no argument definition. Use .add_argument() or .no_argument() to define arguments.";106 "' has no argument definition. Use .add_argument() or .no_argument() to define arguments.";
104 107 
105 // Check deduce_type is set108 // Check deduce_type is set
106- CHECK(deduce_type_.has_value()) << "Operator '" + name_ +109+ PRO_IR_CHECK(npu::tile_fwk::InternalError::COMMON_INNER_ERROR, deduce_type_.has_value())
107- "' has no type deduction function. Use .f_deduce_type() to provide one.";110+ << "Operator '" + name_ + "' has no type deduction function. Use .f_deduce_type() to provide one.";
108 111 
109 return op_;112 return op_;
110 }113 }
@@ -124,7 +127,8 @@ public:
124 */127 */
125 [[nodiscard]] inline const std::string& GetDescription() const128 [[nodiscard]] inline const std::string& GetDescription() const
126 {129 {
127- CHECK(description_.has_value()) << "Operator '" + name_ + "' has no description";130+ PRO_IR_CHECK(npu::tile_fwk::InternalError::COMMON_INNER_ERROR, description_.has_value())
131+ << "Operator '" + name_ + "' has no description";
128 return *description_;132 return *description_;
129 }133 }
130 134 
@@ -136,7 +140,8 @@ public:
136 */140 */
137 [[nodiscard]] inline const std::string& GetOpCategory() const141 [[nodiscard]] inline const std::string& GetOpCategory() const
138 {142 {
139- CHECK(op_category_.has_value()) << "Operator '" + name_ + "' has no category";143+ PRO_IR_CHECK(npu::tile_fwk::InternalError::COMMON_INNER_ERROR, op_category_.has_value())
144+ << "Operator '" + name_ + "' has no category";
140 return *op_category_;145 return *op_category_;
141 }146 }
142 147 
@@ -152,7 +157,8 @@ public:
152 const std::vector<std::pair<std::string, std::any>>&)>&157 const std::vector<std::pair<std::string, std::any>>&)>&
153 GetDeduceType() const158 GetDeduceType() const
154 {159 {
155- CHECK(deduce_type_.has_value()) << "Operator '" + name_ + "' has no type deduction function";160+ PRO_IR_CHECK(npu::tile_fwk::InternalError::COMMON_INNER_ERROR, deduce_type_.has_value())
161+ << "Operator '" + name_ + "' has no type deduction function";
156 return *deduce_type_;162 return *deduce_type_;
157 }163 }
158 164 
@@ -167,7 +173,8 @@ public:
167 */173 */
168 inline OpRegistryEntry& set_description(std::string description)174 inline OpRegistryEntry& set_description(std::string description)
169 {175 {
170- CHECK(!description_.has_value()) << "Operator '" + name_ + "' description is already set";176+ PRO_IR_CHECK(ExternalError::INVALID_OPERATION, !description_.has_value())
177+ << "Operator '" + name_ + "' description is already set";
171 description_ = std::move(description);178 description_ = std::move(description);
172 return *this;179 return *this;
173 }180 }
@@ -183,7 +190,8 @@ public:
183 */190 */
184 inline OpRegistryEntry& set_op_category(std::string category)191 inline OpRegistryEntry& set_op_category(std::string category)
185 {192 {
186- CHECK(!op_category_.has_value()) << "Operator '" + name_ + "' category is already set";193+ PRO_IR_CHECK(ExternalError::INVALID_OPERATION, !op_category_.has_value())
194+ << "Operator '" + name_ + "' category is already set";
187 op_category_ = std::move(category);195 op_category_ = std::move(category);
188 return *this;196 return *this;
189 }197 }
@@ -220,9 +228,10 @@ public:
220 */228 */
221 inline OpRegistryEntry& no_argument()229 inline OpRegistryEntry& no_argument()
222 {230 {
223- CHECK(!arguments_.has_value()) << "Operator '" + name_ +231+ PRO_IR_CHECK(ExternalError::INVALID_OPERATION, !arguments_.has_value())
224- "' already has arguments defined. Cannot call no_argument() after "232+ << "Operator '" + name_ +
225- "add_argument().";233+ "' already has arguments defined. Cannot call no_argument() after "
234+ "add_argument().";
226 arguments_ = std::vector<std::pair<std::string, std::string>>();235 arguments_ = std::vector<std::pair<std::string, std::string>>();
227 return *this;236 return *this;
228 }237 }
@@ -246,7 +255,8 @@ public:
246 inline OpRegistryEntry& f_deduce_type(255 inline OpRegistryEntry& f_deduce_type(
247 std::function<TypePtr(const std::vector<ExprPtr>&, const std::vector<std::pair<std::string, std::any>>&)> dt)256 std::function<TypePtr(const std::vector<ExprPtr>&, const std::vector<std::pair<std::string, std::any>>&)> dt)
248 {257 {
249- CHECK(!deduce_type_.has_value()) << "Operator '" + name_ + "' type deduction function is already set";258+ PRO_IR_CHECK(ExternalError::INVALID_OPERATION, !deduce_type_.has_value())
259+ << "Operator '" + name_ + "' type deduction function is already set";
250 deduce_type_ = std::move(dt);260 deduce_type_ = std::move(dt);
251 return *this;261 return *this;
252 }262 }
@@ -284,7 +294,8 @@ public:
284 template <typename T>294 template <typename T>
285 inline OpRegistryEntry& set_attr(const std::string& key)295 inline OpRegistryEntry& set_attr(const std::string& key)
286 {296 {
287- CHECK(op_) << "Operator '" + name_ + "' has no operator instance";297+ PRO_IR_CHECK(npu::tile_fwk::InternalError::COMMON_INNER_ERROR, op_)
298+ << "Operator '" + name_ + "' has no operator instance";
288 op_->SetAttrType<T>(key); // Delegate to Op::SetAttrType (compile-time check happens there)299 op_->SetAttrType<T>(key); // Delegate to Op::SetAttrType (compile-time check happens there)
289 return *this;300 return *this;
290 }301 }
@@ -297,7 +308,8 @@ public:
297 */308 */
298 inline OpRegistryEntry& set_pipe(PipeType pipe)309 inline OpRegistryEntry& set_pipe(PipeType pipe)
299 {310 {
300- CHECK(op_) << "Operator '" + name_ + "' has no operator instance";311+ PRO_IR_CHECK(npu::tile_fwk::InternalError::COMMON_INNER_ERROR, op_)
312+ << "Operator '" + name_ + "' has no operator instance";
301 op_->SetPipe(pipe);313 op_->SetPipe(pipe);
302 return *this;314 return *this;
303 }315 }
@@ -33,6 +33,7 @@
33#include "core/error.h"33#include "core/error.h"
34#include "ir/expr.h"34#include "ir/expr.h"
35#include "ir/type.h"35#include "ir/type.h"
36+#include "pypto_pro/error.h"
36 37 
37namespace pypto {38namespace pypto {
38namespace ir {39namespace ir {
@@ -173,7 +174,8 @@ T GetOpKwarg(const std::vector<std::pair<std::string, std::any>>& kwargs, const
173 if (default_value) {174 if (default_value) {
174 return *default_value;175 return *default_value;
175 }176 }
176- throw ValueError("Missing kwarg: " + key);177+ using npu::tile_fwk::ExternalError; // Block-scoped: short enum names without leaking to includers
178+ PRO_IR_THROW(::pypto::ir::ValueError, ExternalError::INVALID_ARGUMENT) << "Missing kwarg: " << key;
177}179}
178 180 
179/**181/**
@@ -17,6 +17,7 @@
17#include "core/dtype.h"17#include "core/dtype.h"
18#include "core/error.h"18#include "core/error.h"
19#include "ir/expr.h"19#include "ir/expr.h"
20+#include "pypto_pro/error.h"
20#include "ir/transforms/base/visitor.h"21#include "ir/transforms/base/visitor.h"
21#include "ir/type.h"22#include "ir/type.h"
22 23 
@@ -103,7 +104,9 @@ protected:
103 */104 */
104 [[noreturn]] void ThrowNoCodegenForCall(const std::string& op_name) const105 [[noreturn]] void ThrowNoCodegenForCall(const std::string& op_name) const
105 {106 {
106- throw ir::ValueError("No codegen registered for operation: " + op_name);107+ using npu::tile_fwk::ExternalError;
108+ PRO_CODEGEN_THROW(::pypto::ir::ValueError, ExternalError::KEY_ERROR)
109+ << "No codegen registered for operation: " << op_name;
107 }110 }
108 111 
109 /**112 /**
@@ -0,0 +1,221 @@
1+/**
2+ * Copyright (c) 2026 Huawei Technologies Co., Ltd.
3+ * This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4+ * CANN Open Software License Agreement Version 2.0 (the "License").
5+ * Please refer to the License for details. You may not use this file except in compliance with the License.
6+ * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7+ * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8+ * See LICENSE in the root of the software repository for the full text of the License.
9+ */
10+ 
11+/*!
12+ * \file error.h
13+ * \brief pypto_pro error macros: spec first line plus the user's DSL location.
14+ *
15+ * They differ from core/logging.h's IRCHECK / INTERNAL_CHECK in two ways: they
16+ * render the mandatory first line (error code and module) and append the DSL
17+ * location. The exception type each site throws is unchanged.
18+ *
19+ * \code
20+ * PRO_IR_CHECK(ExternalError::INVALID_ARGUMENT, op->args_.size() == 3)
21+ * << "block.load requires 3 args (out_tile, tensor, offsets)";
22+ * \endcode
23+ */
24+ 
25+#ifndef PYPTO_PRO_ERROR_H_
26+#define PYPTO_PRO_ERROR_H_
27+ 
28+#include <sstream>
29+#include <string>
30+#include <utility>
31+ 
32+#include "core/error.h"
33+#include "ir/span.h"
34+#include "tilefwk/error.h"
35+#include "tilefwk/error_code.h"
36+ 
37+namespace pypto {
38+namespace pro {
39+ 
40+/**
41+ * \brief The DSL location in effect, or Span::Unknown() when none was published.
42+ *
43+ * Separate from ir::Span::Current(), which pypto owns and which is not
44+ * thread-local.
45+ */
46+const ir::Span& CurrentSpan();
47+ 
48+/**
49+ * \brief Publish the DSL location for a scope, restoring the previous one.
50+ *
51+ * Published at two gates: OpRegistry::Create and CCECodegen's VisitStmt /
52+ * VisitExpr. An invalid span is a no-op, so synthesised nodes -- which have no
53+ * source of their own -- cannot erase the enclosing statement's location.
54+ */
55+class SpanScope {
56+public:
57+ explicit SpanScope(const ir::Span& span);
58+ ~SpanScope();
59+ 
60+ SpanScope(const SpanScope&) = delete;
61+ SpanScope& operator=(const SpanScope&) = delete;
62+ SpanScope(SpanScope&&) = delete;
63+ SpanScope& operator=(SpanScope&&) = delete;
64+ 
65+private:
66+ ir::Span prev_;
67+};
68+ 
69+/**
70+ * \brief The first-line prefix: [file:line][MODULE]:ErrCode: FXXXXX! Enum: NAME.
71+ *
72+ * \a file is passed \c __FILE__ directly; the build already redefines it to the
73+ * translation unit's basename.
74+ */
75+std::string ErrHead(const char* file, int line, const char* module, unsigned code, const char* codeName);
76+ 
77+/**
78+ * \brief The location line "\n --> <dsl_file>:<line>:<col>", empty for an
79+ * invalid span. The source preview around it is rendered on the Python side.
80+ */
81+std::string LocLine(const ir::Span& span);
82+ 
83+/**
84+ * \brief How to throw. Specialisations keep each site's exception type and
85+ * behaviour unchanged.
86+ */
87+template <typename ExceptionType>
88+struct Thrower {
89+ [[noreturn]] static void Throw(const char*, const char*, int, const std::string& text)
90+ {
91+ throw ExceptionType(text);
92+ }
93+};
94+ 
95+/**
96+ * \brief npu::tile_fwk::Error keeps its operator=, so backtrace, slog and
97+ * ErrorManager behave as before.
98+ */
99+template <>
100+struct Thrower<npu::tile_fwk::Error> {
101+ [[noreturn]] static void Throw(const char* func, const char* file, int line, const std::string& text)
102+ {
103+ npu::tile_fwk::ErrorMessage message;
104+ message << text;
105+ npu::tile_fwk::Error error(func, file, static_cast<size_t>(line),
106+ npu::tile_fwk::GetBacktrace(0, /* 64 is maxFrames */ 64));
107+ error = message;
108+ // operator= throws only when std::uncaught_exceptions() == 0; this fallback
109+ // is unreachable in practice and exists to satisfy [[noreturn]].
110+ throw npu::tile_fwk::Error(func, file, static_cast<size_t>(line), text, nullptr);
111+ }
112+};
113+ 
114+/**
115+ * \brief Collects the streamed message and throws it on destruction, ordered as
116+ * first line, the caller's message, then the location line.
117+ */
118+template <typename ExceptionType>
119+class ErrLogger {
120+public:
121+ ErrLogger(const char* func, const char* file, int line, const char* module, unsigned code, const char* codeName,
122+ const ir::Span& span)
123+ : func_(func), file_(file), line_(line), head_(ErrHead(file, line, module, code, codeName)), loc_(LocLine(span))
124+ {}
125+ 
126+ [[noreturn]] ~ErrLogger() noexcept(false)
127+ {
128+ Thrower<ExceptionType>::Throw(func_, file_, line_, head_ + ss_.str() + loc_);
129+ }
130+ 
131+ template <typename T>
132+ ErrLogger& operator<<(T&& value)
133+ {
134+ ss_ << std::forward<T>(value);
135+ return *this;
136+ }
137+ 
138+ ErrLogger(const ErrLogger&) = delete;
139+ ErrLogger& operator=(const ErrLogger&) = delete;
140+ ErrLogger(ErrLogger&&) = delete;
141+ ErrLogger& operator=(ErrLogger&&) = delete;
142+ 
143+private:
144+ std::stringstream ss_;
145+ const char* func_;
146+ const char* file_;
147+ int line_;
148+ std::string head_;
149+ std::string loc_;
150+};
151+ 
152+} // namespace pro
153+} // namespace pypto
154+ 
155+/*
156+ * Error macros are named `PRO_<MODULE>_<MECHANISM>`.
157+ *
158+ * The module is part of the macro name, as in pypto's PASS_LOGE / CODEGEN_LOGE:
159+ * picking the macro picks the module. This is what lets a check inside a header
160+ * report its own module rather than that of the including .cpp. pypto_pro needs
161+ * the tag because its external codes are all F0XXXX and carry no stage.
162+ *
163+ * The mechanism selects the exception type, one per existing macro:
164+ * _CHECK -> npu::tile_fwk::Error (= CHECK)
165+ * _IRCHECK -> pypto::ir::ValueError (= IRCHECK)
166+ * _INTERNAL_CHECK -> pypto::ir::InternalError (= INTERNAL_CHECK)
167+ * _THROW -> named at the call site (= throw exc(...))
168+ *
169+ * The location defaults to the ambient span. Use _WITH_SPAN only when the call
170+ * chain does not pass a gate, or to point at a subexpression rather than the
171+ * whole statement.
172+ */
173+ 
174+/** \brief Builds an ErrLogger. Call sites use the PRO_* macros below. */
175+#define PRO_ERR_(exc, module, errcode, span) \
176+ ::pypto::pro::ErrLogger<exc>(__func__, __FILE__, __LINE__, module, static_cast<unsigned>(errcode), #errcode, span)
177+ 
178+/**
179+ * \brief Shared shape of a conditional check.
180+ *
181+ * `if (!!(cond)) ; else` rather than `if (!(cond))`, which would swallow an
182+ * else at the call site.
183+ */
184+#define PRO_CHECK_IMPL_(exc, module, errcode, cond, span) \
185+ if (!!(cond)) \
186+ ; \
187+ else \
188+ PRO_ERR_(exc, module, errcode, span)
189+ 
190+#define PRO_CHECK_M_(module, errcode, cond) \
191+ PRO_CHECK_IMPL_(::npu::tile_fwk::Error, module, errcode, cond, ::pypto::pro::CurrentSpan())
192+#define PRO_IRCHECK_M_(module, errcode, cond) \
193+ PRO_CHECK_IMPL_(::pypto::ir::ValueError, module, errcode, cond, ::pypto::pro::CurrentSpan())
194+#define PRO_INTERNAL_CHECK_M_(module, errcode, cond) \
195+ PRO_CHECK_IMPL_(::pypto::ir::InternalError, module, errcode, cond, ::pypto::pro::CurrentSpan())
196+#define PRO_INTERNAL_CHECK_SPAN_M_(module, errcode, cond, span) \
197+ PRO_CHECK_IMPL_(::pypto::ir::InternalError, module, errcode, cond, span)
198+#define PRO_THROW_M_(exc, module, errcode) PRO_ERR_(exc, module, errcode, ::pypto::pro::CurrentSpan())
199+ 
200+// PRO_IR: IR construction and operator definition.
201+#define PRO_IR_CHECK(errcode, cond) PRO_CHECK_M_("PRO_IR", errcode, cond)
202+#define PRO_IR_IRCHECK(errcode, cond) PRO_IRCHECK_M_("PRO_IR", errcode, cond)
203+#define PRO_IR_INTERNAL_CHECK(errcode, cond) PRO_INTERNAL_CHECK_M_("PRO_IR", errcode, cond)
204+#define PRO_IR_INTERNAL_CHECK_WITH_SPAN(errcode, cond, span) PRO_INTERNAL_CHECK_SPAN_M_("PRO_IR", errcode, cond, span)
205+#define PRO_IR_THROW(exc, errcode) PRO_THROW_M_(exc, "PRO_IR", errcode)
206+ 
207+// PRO_CODEGEN: code generation, including operator emit and VF.
208+#define PRO_CODEGEN_CHECK(errcode, cond) PRO_CHECK_M_("PRO_CODEGEN", errcode, cond)
209+#define PRO_CODEGEN_IRCHECK(errcode, cond) PRO_IRCHECK_M_("PRO_CODEGEN", errcode, cond)
210+#define PRO_CODEGEN_INTERNAL_CHECK(errcode, cond) PRO_INTERNAL_CHECK_M_("PRO_CODEGEN", errcode, cond)
211+#define PRO_CODEGEN_INTERNAL_CHECK_WITH_SPAN(errcode, cond, span) \
212+ PRO_INTERNAL_CHECK_SPAN_M_("PRO_CODEGEN", errcode, cond, span)
213+#define PRO_CODEGEN_THROW(exc, errcode) PRO_THROW_M_(exc, "PRO_CODEGEN", errcode)
214+ 
215+// PRO_PASS: IR transforms. Internal errors only -- a pass consumes the previous
216+// stage's output, not what the user wrote, so its failures are framework bugs.
217+#define PRO_PASS_INTERNAL_CHECK(errcode, cond) PRO_INTERNAL_CHECK_M_("PRO_PASS", errcode, cond)
218+#define PRO_PASS_INTERNAL_CHECK_WITH_SPAN(errcode, cond, span) \
219+ PRO_INTERNAL_CHECK_SPAN_M_("PRO_PASS", errcode, cond, span)
220+ 
221+#endif // PYPTO_PRO_ERROR_H_
@@ -43,6 +43,7 @@ enum class ExternalError : uint32_t {
43 INVALID_SHAPE = 0x0000BU,43 INVALID_SHAPE = 0x0000BU,
44 INVALID_TILE = 0x0000CU,44 INVALID_TILE = 0x0000CU,
45 INVALID_FORMAT = 0x0000DU,45 INVALID_FORMAT = 0x0000DU,
46+ INVALID_ARGUMENT = 0x0000EU,
46 UNKNOWN = 0x0FFFFU47 UNKNOWN = 0x0FFFFU
47};48};
48 49 
@@ -44,8 +44,7 @@ file(GLOB _Interface_Srcs
44)44)
45# pypto_pro 含嵌套子目录, 需 GLOB_RECURSE 递归收集45# pypto_pro 含嵌套子目录, 需 GLOB_RECURSE 递归收集
46file(GLOB_RECURSE _PyptoPro_Srcs46file(GLOB_RECURSE _PyptoPro_Srcs
47- pypto_pro/backend/*.cpp47+ pypto_pro/*.cpp
48- pypto_pro/codegen/*.cpp
49)48)
50list(APPEND _Interface_Srcs ${_PyptoPro_Srcs})49list(APPEND _Interface_Srcs ${_PyptoPro_Srcs})
51#PTO_Fwk_Debug_Source_List(NAME "_Interface_Srcs" LIST ${_Interface_Srcs} DETAIL OFF)50#PTO_Fwk_Debug_Source_List(NAME "_Interface_Srcs" LIST ${_Interface_Srcs} DETAIL OFF)
@@ -36,9 +36,11 @@
36#include "ir/span.h"36#include "ir/span.h"
37#include "ir/type.h"37#include "ir/type.h"
38#include "ir/type_inference.h"38#include "ir/type_inference.h"
39+#include "pypto_pro/error.h"
39 40 
40namespace pypto {41namespace pypto {
41namespace ir {42namespace ir {
43+using npu::tile_fwk::ExternalError;
42 44 
43namespace {45namespace {
44 46 
@@ -56,7 +58,8 @@ TypePtr DeduceBlockGetBlockIdxType([[maybe_unused]] const std::vector<ExprPtr>&
56 [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs,58 [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs,
57 const std::string& op_name)59 const std::string& op_name)
58{60{
59- CHECK(args.size() == 0) << "The operator " << op_name << " requires no arguments, but got " << args.size();61+ PRO_IR_CHECK(ExternalError::INVALID_ARGUMENT, args.size() == 0)
62+ << "The operator " << op_name << " requires no arguments, but got " << args.size();
60 63 
61 return std::make_shared<ScalarType>(DataType::INT64);64 return std::make_shared<ScalarType>(DataType::INT64);
62}65}
@@ -67,17 +70,19 @@ TypePtr DeduceBlockCreateTileType([[maybe_unused]] const std::vector<ExprPtr>& a
67{70{
68 // make_tile signature: (shape)71 // make_tile signature: (shape)
69 // TileType requires static compile-time constant shapes72 // TileType requires static compile-time constant shapes
70- CHECK(args.size() == 0x2) << "The operator " << op_name << " requires exactly 2 arguments, but got " << args.size();73+ PRO_IR_CHECK(ExternalError::INVALID_ARGUMENT, args.size() == 0x2)
74+ << "The operator " << op_name << " requires exactly 2 arguments, but got " << args.size();
71 75 
72 // Extract dtype attribute76 // Extract dtype attribute
73 DataType dtype = GetOpKwarg<DataType>(kwargs, "dtype");77 DataType dtype = GetOpKwarg<DataType>(kwargs, "dtype");
74 78 
75 // First argument must be MakeTuple with static ConstInt elements79 // First argument must be MakeTuple with static ConstInt elements
76 auto shape_tuple = As<MakeTuple>(args[0]);80 auto shape_tuple = As<MakeTuple>(args[0]);
77- CHECK(shape_tuple) << "The operator " << op_name81+ PRO_IR_CHECK(ExternalError::DYNAMIC_SHAPE_COMPUTE_UNSUPPORTED, shape_tuple)
78- << " requires first argument to be a MakeTuple expression with static shape values, but got "82+ << "The operator " << op_name
79- << args[0]->TypeName();83+ << " requires first argument to be a MakeTuple expression with static shape values, but got "
80- CHECK(shape_tuple->elements_.size() == 0x2)84+ << args[0]->TypeName();
85+ PRO_IR_CHECK(ExternalError::NOT_IMPLEMENTED_ERROR, shape_tuple->elements_.size() == 0x2)
81 << "TileType only supports rank-2 shape; "86 << "TileType only supports rank-2 shape; "
82 << "for a 1-D tensor with shape [N], use TileType shape [N, 1] or [1, N], "87 << "for a 1-D tensor with shape [N], use TileType shape [N, 1] or [1, N], "
83 << "and keep the same convention for all tile shapes of that tensor";88 << "and keep the same convention for all tile shapes of that tensor";
@@ -88,11 +93,11 @@ TypePtr DeduceBlockCreateTileType([[maybe_unused]] const std::vector<ExprPtr>& a
88 93 
89 for (size_t i = 0; i < shape_tuple->elements_.size(); ++i) {94 for (size_t i = 0; i < shape_tuple->elements_.size(); ++i) {
90 auto const_int = As<ConstInt>(shape_tuple->elements_[i]);95 auto const_int = As<ConstInt>(shape_tuple->elements_[i]);
91- CHECK(const_int) << "The operator " << op_name << " shape element " << i96+ PRO_IR_CHECK(ExternalError::DYNAMIC_SHAPE_COMPUTE_UNSUPPORTED, const_int)
92- << " must be a compile-time constant (ConstInt), but got "97+ << "The operator " << op_name << " shape element " << i
93- << shape_tuple->elements_[i]->TypeName();98+ << " must be a compile-time constant (ConstInt), but got " << shape_tuple->elements_[i]->TypeName();
94- CHECK(const_int->value_ > 0) << "The operator " << op_name << " shape element " << i99+ PRO_IR_CHECK(ExternalError::INVALID_SHAPE, const_int->value_ > 0)
95- << " must be positive, got " << const_int->value_;100+ << "The operator " << op_name << " shape element " << i << " must be positive, got " << const_int->value_;
96 tile_shape.push_back(shape_tuple->elements_[i]);101 tile_shape.push_back(shape_tuple->elements_[i]);
97 }102 }
98 103 
@@ -156,51 +161,58 @@ TypePtr DeduceBlockCreateTileType([[maybe_unused]] const std::vector<ExprPtr>& a
156TypePtr DeduceGetValType([[maybe_unused]] const std::vector<ExprPtr>& args,161TypePtr DeduceGetValType([[maybe_unused]] const std::vector<ExprPtr>& args,
157 [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs)162 [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs)
158{163{
159- CHECK(args.size() == 0x2) << "getval requires exactly 2 arguments, but got " << args.size();164+ PRO_IR_CHECK(ExternalError::INVALID_ARGUMENT, args.size() == 0x2)
165+ << "getval requires exactly 2 arguments, but got " << args.size();
160 166 
161 auto first_type = args[0]->GetType();167 auto first_type = args[0]->GetType();
162 auto offset_type = As<ScalarType>(args[1]->GetType());168 auto offset_type = As<ScalarType>(args[1]->GetType());
163- CHECK(offset_type) << "getval requires offset to be ScalarType, but got " << args[1]->GetType()->TypeName();169+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, offset_type)
164- CHECK(offset_type->dtype_.IsInt()) << "getval offset must have integer dtype, but got "170+ << "getval requires offset to be ScalarType, but got " << args[1]->GetType()->TypeName();
165- << offset_type->dtype_.ToString();171+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, offset_type->dtype_.IsInt())
172+ << "getval offset must have integer dtype, but got " << offset_type->dtype_.ToString();
166 173 
167 if (auto tile_type = As<TileType>(first_type)) {174 if (auto tile_type = As<TileType>(first_type)) {
168 return std::make_shared<ScalarType>(GetValResultDtype(tile_type->dtype_));175 return std::make_shared<ScalarType>(GetValResultDtype(tile_type->dtype_));
169 }176 }
170 auto tensor_type = As<TensorType>(first_type);177 auto tensor_type = As<TensorType>(first_type);
171- CHECK(tensor_type) << "getval requires first argument to be TileType or TensorType, but got "178+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, tensor_type)
172- << first_type->TypeName();179+ << "getval requires first argument to be TileType or TensorType, but got " << first_type->TypeName();
173 return std::make_shared<ScalarType>(GetValResultDtype(tensor_type->dtype_));180 return std::make_shared<ScalarType>(GetValResultDtype(tensor_type->dtype_));
174}181}
175 182 
176TypePtr DeduceTileValidShapeType(const std::vector<ExprPtr>& args,183TypePtr DeduceTileValidShapeType(const std::vector<ExprPtr>& args,
177 const std::vector<std::pair<std::string, std::any>>& kwargs)184 const std::vector<std::pair<std::string, std::any>>& kwargs)
178{185{
179- CHECK(args.size() == 1 && As<TileType>(args[0]->GetType())) << "block.tile_valid_shape requires one Tile argument";186+ PRO_IR_CHECK(ExternalError::INVALID_ARGUMENT, args.size() == 1 && As<TileType>(args[0]->GetType()))
187+ << "block.tile_valid_shape requires one Tile argument";
180 int axis = GetOpKwarg<int>(kwargs, "axis", 0);188 int axis = GetOpKwarg<int>(kwargs, "axis", 0);
181- CHECK(axis >= 0 && axis <= 1) << "block.tile_valid_shape axis must be in [0, 1], got axis=" << axis;189+ PRO_IR_CHECK(ExternalError::INVALID_SHAPE, axis >= 0 && axis <= 1)
190+ << "block.tile_valid_shape axis must be in [0, 1], got axis=" << axis;
182 return std::make_shared<ScalarType>(DataType::INT64);191 return std::make_shared<ScalarType>(DataType::INT64);
183}192}
184 193 
185TypePtr DeduceSetValType([[maybe_unused]] const std::vector<ExprPtr>& args,194TypePtr DeduceSetValType([[maybe_unused]] const std::vector<ExprPtr>& args,
186 [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs)195 [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs)
187{196{
188- CHECK(args.size() == 0x3) << "setval requires exactly 3 arguments, but got " << args.size();197+ PRO_IR_CHECK(ExternalError::INVALID_ARGUMENT, args.size() == 0x3)
198+ << "setval requires exactly 3 arguments, but got " << args.size();
189 199 
190 auto first_type = args[0]->GetType();200 auto first_type = args[0]->GetType();
191 auto offset_type = As<ScalarType>(args[1]->GetType());201 auto offset_type = As<ScalarType>(args[1]->GetType());
192- CHECK(offset_type) << "setval requires offset to be ScalarType, but got " << args[1]->GetType()->TypeName();202+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, offset_type)
193- CHECK(offset_type->dtype_.IsInt()) << "setval offset must have integer dtype, but got "203+ << "setval requires offset to be ScalarType, but got " << args[1]->GetType()->TypeName();
194- << offset_type->dtype_.ToString();204+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, offset_type->dtype_.IsInt())
205+ << "setval offset must have integer dtype, but got " << offset_type->dtype_.ToString();
195 auto value_type = As<ScalarType>(args[2]->GetType());206 auto value_type = As<ScalarType>(args[2]->GetType());
196- CHECK(value_type) << "setval requires value to be ScalarType, but got " << args[2]->GetType()->TypeName();207+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, value_type)
208+ << "setval requires value to be ScalarType, but got " << args[2]->GetType()->TypeName();
197 209 
198 if (auto tile_type = As<TileType>(first_type)) {210 if (auto tile_type = As<TileType>(first_type)) {
199 return std::make_shared<TileType>(tile_type->shape_, tile_type->dtype_, tile_type->memref_);211 return std::make_shared<TileType>(tile_type->shape_, tile_type->dtype_, tile_type->memref_);
200 }212 }
201 auto tensor_type = As<TensorType>(first_type);213 auto tensor_type = As<TensorType>(first_type);
202- CHECK(tensor_type) << "setval requires first argument to be TileType or TensorType, but got "214+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, tensor_type)
203- << first_type->TypeName();215+ << "setval requires first argument to be TileType or TensorType, but got " << first_type->TypeName();
204 return std::make_shared<TensorType>(tensor_type->shape_, tensor_type->dtype_);216 return std::make_shared<TensorType>(tensor_type->shape_, tensor_type->dtype_);
205}217}
206 218 
@@ -251,7 +263,7 @@ REGISTER_OP("get_spr")
251 .no_argument()263 .no_argument()
252 .f_deduce_type([]([[maybe_unused]] const std::vector<ExprPtr>& args,264 .f_deduce_type([]([[maybe_unused]] const std::vector<ExprPtr>& args,
253 [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs) {265 [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs) {
254- CHECK(args.size() == 0) << "get_spr requires no arguments";266+ PRO_IR_CHECK(ExternalError::INVALID_ARGUMENT, args.size() == 0) << "get_spr requires no arguments";
255 return std::make_shared<ScalarType>(DataType::INT64);267 return std::make_shared<ScalarType>(DataType::INT64);
256 });268 });
257 269 
@@ -284,8 +296,8 @@ REGISTER_OP("set_ctrl_spr")
284 .add_argument("value", "Value to write into the bit range")296 .add_argument("value", "Value to write into the bit range")
285 .f_deduce_type([](const std::vector<ExprPtr>& args,297 .f_deduce_type([](const std::vector<ExprPtr>& args,
286 [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs) {298 [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs) {
287- CHECK(args.size() == 3) << "set_ctrl_spr requires 3 arguments (start_bit, end_bit, value), but got "299+ PRO_IR_CHECK(ExternalError::INVALID_ARGUMENT, args.size() == 3)
288- << args.size();300+ << "set_ctrl_spr requires 3 arguments (start_bit, end_bit, value), but got " << args.size();
289 return GetUnknownType();301 return GetUnknownType();
290 });302 });
291 303 
@@ -296,7 +308,8 @@ REGISTER_OP("get_ctrl_spr")
296 .add_argument("end_bit", "End bit index (0-63)")308 .add_argument("end_bit", "End bit index (0-63)")
297 .f_deduce_type([](const std::vector<ExprPtr>& args,309 .f_deduce_type([](const std::vector<ExprPtr>& args,
298 [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs) {310 [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs) {
299- CHECK(args.size() == 2) << "get_ctrl_spr requires 2 arguments (start_bit, end_bit), but got " << args.size();311+ PRO_IR_CHECK(ExternalError::INVALID_ARGUMENT, args.size() == 2)
312+ << "get_ctrl_spr requires 2 arguments (start_bit, end_bit), but got " << args.size();
300 return std::make_shared<ScalarType>(DataType::INT64);313 return std::make_shared<ScalarType>(DataType::INT64);
301 });314 });
302 315 
@@ -307,7 +320,8 @@ REGISTER_OP("reset_ctrl_spr")
307 .add_argument("end_bit", "End bit index (0-63)")320 .add_argument("end_bit", "End bit index (0-63)")
308 .f_deduce_type([](const std::vector<ExprPtr>& args,321 .f_deduce_type([](const std::vector<ExprPtr>& args,
309 [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs) {322 [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs) {
310- CHECK(args.size() == 2) << "reset_ctrl_spr requires 2 arguments (start_bit, end_bit), but got " << args.size();323+ PRO_IR_CHECK(ExternalError::INVALID_ARGUMENT, args.size() == 2)
324+ << "reset_ctrl_spr requires 2 arguments (start_bit, end_bit), but got " << args.size();
311 return GetUnknownType();325 return GetUnknownType();
312 });326 });
313 327 
@@ -369,15 +383,16 @@ TypePtr DeduceSubViewType([[maybe_unused]] const std::vector<ExprPtr>& args,
369 // args: [container, offset, valid_shape]383 // args: [container, offset, valid_shape]
370 // Type deduction uses the container's original shape (preserving row_stride).384 // Type deduction uses the container's original shape (preserving row_stride).
371 // The valid_shape argument is consumed by codegen to auto-emit SetValidShape.385 // The valid_shape argument is consumed by codegen to auto-emit SetValidShape.
372- CHECK(args.size() == 0x3) << "block.subview requires exactly 3 arguments (container, offset, valid_shape), but got "386+ PRO_IR_CHECK(ExternalError::INVALID_ARGUMENT, args.size() == 0x3)
373- << args.size();387+ << "block.subview requires exactly 3 arguments (container, offset, valid_shape), but got " << args.size();
374 auto container_type = args[0]->GetType();388 auto container_type = args[0]->GetType();
375 389 
376 if (auto tile_type = As<TileType>(container_type)) {390 if (auto tile_type = As<TileType>(container_type)) {
377 return tile_type;391 return tile_type;
378 }392 }
379 393 
380- CHECK(false) << "block.subview requires first argument to be TileType, but got " << container_type->TypeName();394+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, false)
395+ << "block.subview requires first argument to be TileType, but got " << container_type->TypeName();
381 return nullptr;396 return nullptr;
382}397}
383 398 
@@ -31,6 +31,7 @@
31#include <vector>31#include <vector>
32 32 
33#include "core/logging.h"33#include "core/logging.h"
34+#include "pypto_pro/error.h"
34#include "ir/kind_traits.h"35#include "ir/kind_traits.h"
35#include "ir/op_registry.h"36#include "ir/op_registry.h"
36#include "ir/type.h"37#include "ir/type.h"
@@ -38,6 +39,7 @@
38 39 
39namespace pypto {40namespace pypto {
40namespace ir {41namespace ir {
42+using npu::tile_fwk::ExternalError;
41 43 
42// ---------------------------------------------------------------------------44// ---------------------------------------------------------------------------
43// Shared type deduction helpers45// Shared type deduction helpers
@@ -46,15 +48,17 @@ namespace ir {
46// Validate that args[idx] is TileType.48// Validate that args[idx] is TileType.
47static void CheckTileArg([[maybe_unused]] const std::vector<ExprPtr>& args, size_t idx, const std::string& op_name)49static void CheckTileArg([[maybe_unused]] const std::vector<ExprPtr>& args, size_t idx, const std::string& op_name)
48{50{
49- CHECK(As<TileType>(args[idx]->GetType())) << "The operator " << op_name << " requires argument " << idx51+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, As<TileType>(args[idx]->GetType()))
50- << " to be TileType, but got " << args[idx]->GetType()->TypeName();52+ << "The operator " << op_name << " requires argument " << idx << " to be TileType, but got "
53+ << args[idx]->GetType()->TypeName();
51}54}
52 55 
53// Validate that args[idx] is ScalarType.56// Validate that args[idx] is ScalarType.
54static void CheckScalarArg([[maybe_unused]] const std::vector<ExprPtr>& args, size_t idx, const std::string& op_name)57static void CheckScalarArg([[maybe_unused]] const std::vector<ExprPtr>& args, size_t idx, const std::string& op_name)
55{58{
56- CHECK(As<ScalarType>(args[idx]->GetType())) << "The operator " << op_name << " requires argument " << idx59+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, As<ScalarType>(args[idx]->GetType()))
57- << " to be ScalarType, but got " << args[idx]->GetType()->TypeName();60+ << "The operator " << op_name << " requires argument " << idx << " to be ScalarType, but got "
61+ << args[idx]->GetType()->TypeName();
58}62}
59 63 
60// Type deduction for (out:TileType, TileType, TileType) -> out.64// Type deduction for (out:TileType, TileType, TileType) -> out.
@@ -62,7 +66,8 @@ static TypePtr DeduceBlockOutBinaryTile([[maybe_unused]] const std::vector<ExprP
62 [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs,66 [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs,
63 const std::string& op_name)67 const std::string& op_name)
64{68{
65- CHECK(args.size() == 0x3) << op_name << " requires 3 arguments (out, lhs, rhs)";69+ PRO_IR_CHECK(ExternalError::INVALID_ARGUMENT, args.size() == 0x3)
70+ << op_name << " requires 3 arguments (out, lhs, rhs)";
66 CheckTileArg(args, 1, op_name); // NOLINT: lhs index71 CheckTileArg(args, 1, op_name); // NOLINT: lhs index
67 CheckTileArg(args, 2, op_name); // NOLINT: rhs index72 CheckTileArg(args, 2, op_name); // NOLINT: rhs index
68 return DeduceBlockOutTileType(args, kwargs, op_name, 0x3);73 return DeduceBlockOutTileType(args, kwargs, op_name, 0x3);
@@ -73,7 +78,8 @@ static TypePtr DeduceBlockOutBinaryScalar([[maybe_unused]] const std::vector<Exp
73 [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs,78 [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs,
74 const std::string& op_name)79 const std::string& op_name)
75{80{
76- CHECK(args.size() == 0x3) << op_name << " requires 3 arguments (out, tile, scalar)";81+ PRO_IR_CHECK(ExternalError::INVALID_ARGUMENT, args.size() == 0x3)
82+ << op_name << " requires 3 arguments (out, tile, scalar)";
77 CheckTileArg(args, 1, op_name); // NOLINT: lhs index83 CheckTileArg(args, 1, op_name); // NOLINT: lhs index
78 CheckScalarArg(args, 2, op_name); // NOLINT: rhs index84 CheckScalarArg(args, 2, op_name); // NOLINT: rhs index
79 return DeduceBlockOutTileType(args, kwargs, op_name, 0x3);85 return DeduceBlockOutTileType(args, kwargs, op_name, 0x3);
@@ -84,7 +90,7 @@ static TypePtr DeduceBlockOutUnary([[maybe_unused]] const std::vector<ExprPtr>&
84 [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs,90 [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs,
85 const std::string& op_name)91 const std::string& op_name)
86{92{
87- CHECK(args.size() == 0x2) << op_name << " requires 2 arguments (out, src)";93+ PRO_IR_CHECK(ExternalError::INVALID_ARGUMENT, args.size() == 0x2) << op_name << " requires 2 arguments (out, src)";
88 CheckTileArg(args, 1, op_name);94 CheckTileArg(args, 1, op_name);
89 return DeduceBlockOutTileType(args, kwargs, op_name, 0x2);95 return DeduceBlockOutTileType(args, kwargs, op_name, 0x2);
90}96}
@@ -236,7 +242,8 @@ REGISTER_OP("block.gather")
236 if (args.size() == 5) {242 if (args.size() == 5) {
237 return DeduceBlockOutTileType(args, kwargs, "block.gather", 5);243 return DeduceBlockOutTileType(args, kwargs, "block.gather", 5);
238 }244 }
239- throw std::runtime_error("block.gather: expected index form (3-4 args) or compare form (5 args + cmp_mode)");245+ PRO_IR_THROW(std::runtime_error, ExternalError::INVALID_ARGUMENT)
246+ << "block.gather: expected index form (3-4 args) or compare form (5 args + cmp_mode)";
240 });247 });
241 248 
242// block.gatherb: (out, src_tile, offsets_tile) -> out's type249// block.gatherb: (out, src_tile, offsets_tile) -> out's type
@@ -473,10 +480,10 @@ REGISTER_OP("block.quant")
473 .set_attr<int>("mode")480 .set_attr<int>("mode")
474 .f_deduce_type([]([[maybe_unused]] const std::vector<ExprPtr>& args,481 .f_deduce_type([]([[maybe_unused]] const std::vector<ExprPtr>& args,
475 [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs) {482 [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs) {
476- CHECK(args.size() == 3 || args.size() == 4)483+ PRO_IR_CHECK(ExternalError::INVALID_ARGUMENT, args.size() == 3 || args.size() == 4)
477 << "block.quant requires 3 args (sym) or 4 args (asym), got " << args.size();484 << "block.quant requires 3 args (sym) or 4 args (asym), got " << args.size();
478 auto out_type = As<TileType>(args.front()->GetType());485 auto out_type = As<TileType>(args.front()->GetType());
479- CHECK(out_type) << "block.quant: first argument (out) must be TileType";486+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, out_type) << "block.quant: first argument (out) must be TileType";
480 return out_type;487 return out_type;
481 });488 });
482 489 
@@ -36,9 +36,11 @@
36#include "ir/transforms/structural_comparison.h"36#include "ir/transforms/structural_comparison.h"
37#include "ir/type.h"37#include "ir/type.h"
38#include "ir/type_inference.h"38#include "ir/type_inference.h"
39+#include "pypto_pro/error.h"
39 40 
40namespace pypto {41namespace pypto {
41namespace ir {42namespace ir {
43+using npu::tile_fwk::ExternalError;
42 44 
43// ---------------------------------------------------------------------------45// ---------------------------------------------------------------------------
44// Common helpers46// Common helpers
@@ -50,48 +52,54 @@ static TypePtr DeduceBlockOutFillPadType([[maybe_unused]] const std::vector<Expr
50 bool require_shared_backing_storage = false)52 bool require_shared_backing_storage = false)
51{53{
52 auto out_type = As<TileType>(DeduceBlockOutTileType(args, kwargs, op_name, 2));54 auto out_type = As<TileType>(DeduceBlockOutTileType(args, kwargs, op_name, 2));
53- CHECK(out_type) << op_name << ": out must be TileType";55+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, out_type) << op_name << ": out must be TileType";
54 auto src_type = As<TileType>(args[1]->GetType());56 auto src_type = As<TileType>(args[1]->GetType());
55- CHECK(src_type) << op_name << ": src must be TileType";57+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, src_type) << op_name << ": src must be TileType";
56- CHECK(out_type->hardwareInfo_.has_value()) << op_name << ": out tile must carry hardware_info metadata";58+ PRO_IR_CHECK(ExternalError::INVALID_VAL, out_type->hardwareInfo_.has_value())
59+ << op_name << ": out tile must carry hardware_info metadata";
57 60 
58 HardwareInfo hw = out_type->hardwareInfo_.value();61 HardwareInfo hw = out_type->hardwareInfo_.value();
59 int pad_value = static_cast<int>(hw.pad);62 int pad_value = static_cast<int>(hw.pad);
60- CHECK(pad_value >= static_cast<int>(TilePad::null) && pad_value <= static_cast<int>(TilePad::min))63+ PRO_IR_CHECK(ExternalError::INVALID_ARGUMENT,
64+ pad_value >= static_cast<int>(TilePad::null) && pad_value <= static_cast<int>(TilePad::min))
61 << op_name << ": out.hardware_info.pad must be one of TilePad.null/zero/max/min";65 << op_name << ": out.hardware_info.pad must be one of TilePad.null/zero/max/min";
62- CHECK(pad_value != static_cast<int>(TilePad::null))66+ PRO_IR_CHECK(ExternalError::INVALID_ARGUMENT, pad_value != static_cast<int>(TilePad::null))
63 << op_name << ": out.hardware_info.pad must not be TilePad.null";67 << op_name << ": out.hardware_info.pad must not be TilePad.null";
64 68 
65 if (require_shared_backing_storage) {69 if (require_shared_backing_storage) {
66- CHECK(src_type->memref_.has_value() && out_type->memref_.has_value())70+ PRO_IR_CHECK(ExternalError::INVALID_OPERATION, src_type->memref_.has_value() && out_type->memref_.has_value())
67 << op_name << ": src and out must share backing storage";71 << op_name << ": src and out must share backing storage";
68 auto src_memref = src_type->memref_.value();72 auto src_memref = src_type->memref_.value();
69 auto out_memref = out_type->memref_.value();73 auto out_memref = out_type->memref_.value();
70- CHECK(src_memref->memorySpace_ == out_memref->memorySpace_ &&74+ PRO_IR_CHECK(ExternalError::INVALID_OPERATION, src_memref->memorySpace_ == out_memref->memorySpace_ &&
71- structural_equal(src_memref->addr_, out_memref->addr_))75+ structural_equal(src_memref->addr_, out_memref->addr_))
72 << op_name << ": src and out must share backing storage";76 << op_name << ": src and out must share backing storage";
73 77 
74- CHECK(src_type->shape_.size() == 0x2 && out_type->shape_.size() == 0x2)78+ PRO_IR_CHECK(ExternalError::INVALID_SHAPE, src_type->shape_.size() == 0x2 && out_type->shape_.size() == 0x2)
75 << op_name << ": src/out tile shapes must be rank-2";79 << op_name << ": src/out tile shapes must be rank-2";
76 auto src_rows = As<ConstInt>(src_type->shape_[0]);80 auto src_rows = As<ConstInt>(src_type->shape_[0]);
77 auto src_cols = As<ConstInt>(src_type->shape_[1]);81 auto src_cols = As<ConstInt>(src_type->shape_[1]);
78 auto out_rows = As<ConstInt>(out_type->shape_[0]);82 auto out_rows = As<ConstInt>(out_type->shape_[0]);
79 auto out_cols = As<ConstInt>(out_type->shape_[1]);83 auto out_cols = As<ConstInt>(out_type->shape_[1]);
80- CHECK(src_rows && src_cols && out_rows && out_cols) << op_name << ": src/out tile shapes must be static";84+ PRO_IR_CHECK(ExternalError::DYNAMIC_SHAPE_COMPUTE_UNSUPPORTED, src_rows && src_cols && out_rows && out_cols)
81- CHECK(out_rows->value_ == src_rows->value_ && out_cols->value_ == src_cols->value_)85+ << op_name << ": src/out tile shapes must be static";
86+ PRO_IR_CHECK(ExternalError::INVALID_SHAPE,
87+ out_rows->value_ == src_rows->value_ && out_cols->value_ == src_cols->value_)
82 << op_name << ": src and out tile rows/cols must match";88 << op_name << ": src and out tile rows/cols must match";
83 }89 }
84 90 
85 if (allow_expand) {91 if (allow_expand) {
86- CHECK(src_type->shape_.size() == 0x2 && out_type->shape_.size() == 0x2)92+ PRO_IR_CHECK(ExternalError::INVALID_SHAPE, src_type->shape_.size() == 0x2 && out_type->shape_.size() == 0x2)
87 << op_name << ": src/out tile shapes must be rank-2";93 << op_name << ": src/out tile shapes must be rank-2";
88 94 
89 auto src_rows = As<ConstInt>(src_type->shape_[0]);95 auto src_rows = As<ConstInt>(src_type->shape_[0]);
90 auto src_cols = As<ConstInt>(src_type->shape_[1]);96 auto src_cols = As<ConstInt>(src_type->shape_[1]);
91 auto out_rows = As<ConstInt>(out_type->shape_[0]);97 auto out_rows = As<ConstInt>(out_type->shape_[0]);
92 auto out_cols = As<ConstInt>(out_type->shape_[1]);98 auto out_cols = As<ConstInt>(out_type->shape_[1]);
93- CHECK(src_rows && src_cols && out_rows && out_cols) << op_name << ": src/out tile shapes must be static";99+ PRO_IR_CHECK(ExternalError::DYNAMIC_SHAPE_COMPUTE_UNSUPPORTED, src_rows && src_cols && out_rows && out_cols)
94- CHECK(out_rows->value_ >= src_rows->value_ && out_cols->value_ >= src_cols->value_)100+ << op_name << ": src/out tile shapes must be static";
101+ PRO_IR_CHECK(ExternalError::INVALID_SHAPE,
102+ out_rows->value_ >= src_rows->value_ && out_cols->value_ >= src_cols->value_)
95 << op_name << ": out tile rows/cols must be >= src tile rows/cols";103 << op_name << ": out tile rows/cols must be >= src tile rows/cols";
96 }104 }
97 return out_type;105 return out_type;
@@ -114,11 +122,14 @@ REGISTER_OP("block.load")
114 .set_attr<std::vector<int>>("tile_dims")122 .set_attr<std::vector<int>>("tile_dims")
115 .f_deduce_type([]([[maybe_unused]] const std::vector<ExprPtr>& args,123 .f_deduce_type([]([[maybe_unused]] const std::vector<ExprPtr>& args,
116 [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs) {124 [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs) {
117- CHECK(args.size() == 3) << "block.load requires 3 arguments, got " << args.size();125+ PRO_IR_CHECK(ExternalError::INVALID_ARGUMENT, args.size() == 3)
118- CHECK(As<TileType>(args[0]->GetType())) << "block.load: arg 0 must be TileType";126+ << "block.load requires 3 arguments, got " << args.size();
119- CHECK(As<TensorType>(args[1]->GetType())) << "block.load: arg 1 must be TensorType";127+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, As<TileType>(args[0]->GetType()))
128+ << "block.load: arg 0 must be TileType";
129+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, As<TensorType>(args[1]->GetType()))
130+ << "block.load: arg 1 must be TensorType";
120 auto offsets = As<MakeTuple>(args[2]);131 auto offsets = As<MakeTuple>(args[2]);
121- CHECK(offsets) << "block.load: arg 2 must be MakeTuple (offsets)";132+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, offsets) << "block.load: arg 2 must be MakeTuple (offsets)";
122 return args[0]->GetType();133 return args[0]->GetType();
123 });134 });
124 135 
@@ -136,14 +147,17 @@ REGISTER_OP("block.store")
136 .set_attr<int>("phase")147 .set_attr<int>("phase")
137 .f_deduce_type([]([[maybe_unused]] const std::vector<ExprPtr>& args,148 .f_deduce_type([]([[maybe_unused]] const std::vector<ExprPtr>& args,
138 [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs) {149 [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs) {
139- CHECK(args.size() == 3 || args.size() == 4) << "block.store requires 3 or 4 arguments, got " << args.size();150+ PRO_IR_CHECK(ExternalError::INVALID_ARGUMENT, args.size() == 3 || args.size() == 4)
151+ << "block.store requires 3 or 4 arguments, got " << args.size();
140 auto out_type = As<TensorType>(args[0]->GetType());152 auto out_type = As<TensorType>(args[0]->GetType());
141- CHECK(out_type) << "block.store: arg 0 must be TensorType";153+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, out_type) << "block.store: arg 0 must be TensorType";
142- CHECK(As<TileType>(args[1]->GetType())) << "block.store: arg 1 must be TileType";154+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, As<TileType>(args[1]->GetType()))
155+ << "block.store: arg 1 must be TileType";
143 auto offsets = As<MakeTuple>(args[2]);156 auto offsets = As<MakeTuple>(args[2]);
144- CHECK(offsets) << "block.store: arg 2 must be MakeTuple (offsets)";157+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, offsets) << "block.store: arg 2 must be MakeTuple (offsets)";
145 if (args.size() == 4) {158 if (args.size() == 4) {
146- CHECK(As<ScalarType>(args[3]->GetType()) || As<TileType>(args[3]->GetType()))159+ PRO_IR_CHECK(ExternalError::INVALID_TYPE,
160+ As<ScalarType>(args[3]->GetType()) || As<TileType>(args[3]->GetType()))
147 << "block.store: arg 3 (scale) must be ScalarType or TileType";161 << "block.store: arg 3 (scale) must be ScalarType or TileType";
148 }162 }
149 return out_type;163 return out_type;
@@ -163,14 +177,15 @@ REGISTER_OP("block.move")
163 .set_attr<int>("phase")177 .set_attr<int>("phase")
164 .f_deduce_type([]([[maybe_unused]] const std::vector<ExprPtr>& args,178 .f_deduce_type([]([[maybe_unused]] const std::vector<ExprPtr>& args,
165 [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs) {179 [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs) {
166- CHECK(args.size() >= 2 && args.size() <= 4)180+ PRO_IR_CHECK(ExternalError::INVALID_ARGUMENT, args.size() >= 2 && args.size() <= 4)
167 << "The operator block.move requires 2 to 4 arguments, but got " << args.size();181 << "The operator block.move requires 2 to 4 arguments, but got " << args.size();
168 auto out_type = As<TileType>(args[0]->GetType());182 auto out_type = As<TileType>(args[0]->GetType());
169- CHECK(out_type) << "block.move: first argument (out) must be TileType";183+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, out_type) << "block.move: first argument (out) must be TileType";
170 // Optional trailing operands (args[2], args[3]) are distinguished by TYPE, not position:184 // Optional trailing operands (args[2], args[3]) are distinguished by TYPE, not position:
171 // a TupleType is the 2D sub-tile offset; a ScalarType is the pre_quant_scalar quant scale.185 // a TupleType is the 2D sub-tile offset; a ScalarType is the pre_quant_scalar quant scale.
172 for (size_t i = 2; i < args.size(); ++i) {186 for (size_t i = 2; i < args.size(); ++i) {
173- CHECK(As<TupleType>(args[i]->GetType()) || As<ScalarType>(args[i]->GetType()))187+ PRO_IR_CHECK(ExternalError::INVALID_TYPE,
188+ As<TupleType>(args[i]->GetType()) || As<ScalarType>(args[i]->GetType()))
174 << "block.move: optional arg " << i << " must be TupleType (offset) or ScalarType (pre_quant_scalar)";189 << "block.move: optional arg " << i << " must be TupleType (offset) or ScalarType (pre_quant_scalar)";
175 }190 }
176 return out_type;191 return out_type;
@@ -188,11 +203,14 @@ REGISTER_OP("block.move_fp")
188 .set_attr<int>("phase")203 .set_attr<int>("phase")
189 .f_deduce_type([]([[maybe_unused]] const std::vector<ExprPtr>& args,204 .f_deduce_type([]([[maybe_unused]] const std::vector<ExprPtr>& args,
190 [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs) {205 [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs) {
191- CHECK(args.size() == 3) << "The operator block.move_fp requires 3 arguments, but got " << args.size();206+ PRO_IR_CHECK(ExternalError::INVALID_ARGUMENT, args.size() == 3)
207+ << "The operator block.move_fp requires 3 arguments, but got " << args.size();
192 auto out_type = As<TileType>(args[0]->GetType());208 auto out_type = As<TileType>(args[0]->GetType());
193- CHECK(out_type) << "block.move_fp: first argument (out) must be TileType";209+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, out_type) << "block.move_fp: first argument (out) must be TileType";
194- CHECK(As<TileType>(args[1]->GetType())) << "block.move_fp: arg 1 must be TileType";210+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, As<TileType>(args[1]->GetType()))
195- CHECK(As<TileType>(args[2]->GetType())) << "block.move_fp: arg 2 must be TileType";211+ << "block.move_fp: arg 1 must be TileType";
212+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, As<TileType>(args[2]->GetType()))
213+ << "block.move_fp: arg 2 must be TileType";
196 return out_type;214 return out_type;
197 });215 });
198 216 
@@ -207,9 +225,10 @@ REGISTER_OP("block.insert")
207 .add_argument("col", "Column offset where insertion begins")225 .add_argument("col", "Column offset where insertion begins")
208 .f_deduce_type([]([[maybe_unused]] const std::vector<ExprPtr>& args,226 .f_deduce_type([]([[maybe_unused]] const std::vector<ExprPtr>& args,
209 [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs) {227 [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs) {
210- CHECK(args.size() == 4) << "The operator block.insert requires 4 arguments, but got " << args.size();228+ PRO_IR_CHECK(ExternalError::INVALID_ARGUMENT, args.size() == 4)
229+ << "The operator block.insert requires 4 arguments, but got " << args.size();
211 auto out_type = As<TileType>(args[0]->GetType());230 auto out_type = As<TileType>(args[0]->GetType());
212- CHECK(out_type) << "block.insert: first argument (out) must be TileType";231+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, out_type) << "block.insert: first argument (out) must be TileType";
213 return out_type;232 return out_type;
214 });233 });
215 234 
@@ -235,7 +254,8 @@ REGISTER_OP("block.ssbuf_store")
235 .add_argument("offset", "SSBUF byte address offset")254 .add_argument("offset", "SSBUF byte address offset")
236 .f_deduce_type([]([[maybe_unused]] const std::vector<ExprPtr>& args,255 .f_deduce_type([]([[maybe_unused]] const std::vector<ExprPtr>& args,
237 [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs) {256 [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs) {
238- CHECK(args.size() == 2) << "The operator block.ssbuf_store requires 2 arguments (struct_var, offset)";257+ PRO_IR_CHECK(ExternalError::INVALID_ARGUMENT, args.size() == 2)
258+ << "The operator block.ssbuf_store requires 2 arguments (struct_var, offset)";
239 return GetNoneType();259 return GetNoneType();
240 });260 });
241 261 
@@ -248,7 +268,8 @@ REGISTER_OP("block.ssbuf_load")
248 .add_argument("offset", "SSBUF byte address offset")268 .add_argument("offset", "SSBUF byte address offset")
249 .f_deduce_type([]([[maybe_unused]] const std::vector<ExprPtr>& args,269 .f_deduce_type([]([[maybe_unused]] const std::vector<ExprPtr>& args,
250 [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs) {270 [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs) {
251- CHECK(args.size() == 2) << "The operator block.ssbuf_load requires 2 arguments (struct_var, offset)";271+ PRO_IR_CHECK(ExternalError::INVALID_ARGUMENT, args.size() == 2)
272+ << "The operator block.ssbuf_load requires 2 arguments (struct_var, offset)";
252 return GetNoneType();273 return GetNoneType();
253 });274 });
254 275 
@@ -22,9 +22,11 @@
22#include "ir/kind_traits.h"22#include "ir/kind_traits.h"
23#include "ir/op_registry.h"23#include "ir/op_registry.h"
24#include "ir/type.h"24#include "ir/type.h"
25+#include "pypto_pro/error.h"
25 26 
26namespace pypto {27namespace pypto {
27namespace ir {28namespace ir {
29+using npu::tile_fwk::ExternalError;
28 30 
29// ---------------------------------------------------------------------------31// ---------------------------------------------------------------------------
30// sort3232// sort32
@@ -40,10 +42,11 @@ REGISTER_OP("block.sort32")
40 .add_argument("tmp", "Optional scratch tile (TileType)")42 .add_argument("tmp", "Optional scratch tile (TileType)")
41 .f_deduce_type([]([[maybe_unused]] const std::vector<ExprPtr>& args,43 .f_deduce_type([]([[maybe_unused]] const std::vector<ExprPtr>& args,
42 [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs) {44 [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs) {
43- CHECK(args.size() == 3 || args.size() == 4)45+ PRO_IR_CHECK(ExternalError::INVALID_ARGUMENT, args.size() == 3 || args.size() == 4)
44 << "block.sort32 requires 3 or 4 arguments (dst, src, idx[, tmp]), but got " << args.size();46 << "block.sort32 requires 3 or 4 arguments (dst, src, idx[, tmp]), but got " << args.size();
45 auto dst_type = As<TileType>(args[0]->GetType());47 auto dst_type = As<TileType>(args[0]->GetType());
46- CHECK(dst_type) << "block.sort32: dst must be TileType, but got " << args[0]->GetType()->TypeName();48+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, dst_type)
49+ << "block.sort32: dst must be TileType, but got " << args[0]->GetType()->TypeName();
47 return dst_type;50 return dst_type;
48 });51 });
49 52 
@@ -60,9 +63,11 @@ REGISTER_OP("block.mrgsort")
60 .set_attr<int>("block_len")63 .set_attr<int>("block_len")
61 .f_deduce_type([]([[maybe_unused]] const std::vector<ExprPtr>& args,64 .f_deduce_type([]([[maybe_unused]] const std::vector<ExprPtr>& args,
62 [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs) {65 [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs) {
63- CHECK(args.size() == 2) << "block.mrgsort requires 2 arguments (dst, src) for format1, but got " << args.size();66+ PRO_IR_CHECK(ExternalError::INVALID_ARGUMENT, args.size() == 2)
67+ << "block.mrgsort requires 2 arguments (dst, src) for format1, but got " << args.size();
64 auto dst_type = As<TileType>(args[0]->GetType());68 auto dst_type = As<TileType>(args[0]->GetType());
65- CHECK(dst_type) << "block.mrgsort: dst must be TileType, but got " << args[0]->GetType()->TypeName();69+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, dst_type)
70+ << "block.mrgsort: dst must be TileType, but got " << args[0]->GetType()->TypeName();
66 return dst_type;71 return dst_type;
67 });72 });
68 73 
@@ -81,10 +86,11 @@ REGISTER_OP("block.mrgsort2")
81 .set_attr<bool>("exhausted")86 .set_attr<bool>("exhausted")
82 .f_deduce_type([]([[maybe_unused]] const std::vector<ExprPtr>& args,87 .f_deduce_type([]([[maybe_unused]] const std::vector<ExprPtr>& args,
83 [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs) {88 [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs) {
84- CHECK(args.size() >= 4 && args.size() <= 6)89+ PRO_IR_CHECK(ExternalError::INVALID_ARGUMENT, args.size() >= 4 && args.size() <= 6)
85 << "block.mrgsort2 requires 4-6 arguments (dst, src0, tmp, src1, [src2, src3]), but got " << args.size();90 << "block.mrgsort2 requires 4-6 arguments (dst, src0, tmp, src1, [src2, src3]), but got " << args.size();
86 auto dst_type = As<TileType>(args[0]->GetType());91 auto dst_type = As<TileType>(args[0]->GetType());
87- CHECK(dst_type) << "block.mrgsort2: dst must be TileType, but got " << args[0]->GetType()->TypeName();92+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, dst_type)
93+ << "block.mrgsort2: dst must be TileType, but got " << args[0]->GetType()->TypeName();
88 return dst_type;94 return dst_type;
89 });95 });
90 96 
@@ -98,9 +104,11 @@ REGISTER_OP("block.histogram")
98 .set_attr<bool>("is_msb")104 .set_attr<bool>("is_msb")
99 .f_deduce_type([]([[maybe_unused]] const std::vector<ExprPtr>& args,105 .f_deduce_type([]([[maybe_unused]] const std::vector<ExprPtr>& args,
100 [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs) {106 [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs) {
101- CHECK(args.size() == 3) << "block.histogram requires 3 arguments (dst, src, idx), but got " << args.size();107+ PRO_IR_CHECK(ExternalError::INVALID_ARGUMENT, args.size() == 3)
108+ << "block.histogram requires 3 arguments (dst, src, idx), but got " << args.size();
102 auto dst_type = As<TileType>(args[0]->GetType());109 auto dst_type = As<TileType>(args[0]->GetType());
103- CHECK(dst_type) << "block.histogram: dst must be TileType, but got " << args[0]->GetType()->TypeName();110+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, dst_type)
111+ << "block.histogram: dst must be TileType, but got " << args[0]->GetType()->TypeName();
104 return dst_type;112 return dst_type;
105 });113 });
106 114 
@@ -29,10 +29,12 @@
29#include "ir/identifier.h"29#include "ir/identifier.h"
30#include "ir/op_registry.h"30#include "ir/op_registry.h"
31#include "ir/type.h"31#include "ir/type.h"
32+#include "pypto_pro/error.h"
32#include "tilefwk/error.h"33#include "tilefwk/error.h"
33 34 
34namespace pypto {35namespace pypto {
35namespace ir {36namespace ir {
37+using npu::tile_fwk::ExternalError;
36 38 
37REGISTER_OP("struct.create")39REGISTER_OP("struct.create")
38 .set_op_category("StructOp")40 .set_op_category("StructOp")
@@ -58,21 +60,26 @@ REGISTER_OP("struct.create")
58 has_fields = true;60 has_fields = true;
59 }61 }
60 }62 }
61- CHECK(has_name) << "struct.create requires kwarg 'name' (C++ struct type name)";63+ PRO_IR_CHECK(ExternalError::INVALID_ARGUMENT, has_name)
62- CHECK(has_fields) << "struct.create requires kwarg 'fields' (list of field names)";64+ << "struct.create requires kwarg 'name' (C++ struct type name)";
63- CHECK(IsValidIdentifier(struct_name))65+ PRO_IR_CHECK(ExternalError::INVALID_ARGUMENT, has_fields)
66+ << "struct.create requires kwarg 'fields' (list of field names)";
67+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, IsValidIdentifier(struct_name))
64 << "struct.create 'name' must be a valid C identifier, got '" << struct_name << "'";68 << "struct.create 'name' must be a valid C identifier, got '" << struct_name << "'";
65- CHECK(fields.size() == args.size())69+ PRO_IR_CHECK(ExternalError::INVALID_ARGUMENT, fields.size() == args.size())
66 << "struct.create: fields count (" << fields.size() << ") must match args count (" << args.size() << ")";70 << "struct.create: fields count (" << fields.size() << ") must match args count (" << args.size() << ")";
67 std::set<std::string> seen;71 std::set<std::string> seen;
68 for (const auto& f : fields) {72 for (const auto& f : fields) {
69- CHECK(IsValidIdentifier(f)) << "struct.create field name '" << f << "' is not a valid identifier";73+ PRO_IR_CHECK(ExternalError::INVALID_ARGUMENT, IsValidIdentifier(f))
70- CHECK(seen.insert(f).second) << "struct.create field name '" << f << "' is duplicated";74+ << "struct.create field name '" << f << "' is not a valid identifier";
75+ PRO_IR_CHECK(ExternalError::INVALID_OPERATION, seen.insert(f).second)
76+ << "struct.create field name '" << f << "' is duplicated";
71 }77 }
72 std::vector<TypePtr> field_types;78 std::vector<TypePtr> field_types;
73 field_types.reserve(args.size());79 field_types.reserve(args.size());
74 for (size_t i = 0; i < args.size(); ++i) {80 for (size_t i = 0; i < args.size(); ++i) {
75- CHECK(args[i]) << "struct.create arg #" << i << " is null";81+ PRO_IR_CHECK(npu::tile_fwk::InternalError::COMMON_INNER_ERROR, args[i])
82+ << "struct.create arg #" << i << " is null";
76 field_types.push_back(args[i]->GetType());83 field_types.push_back(args[i]->GetType());
77 }84 }
78 // Positional TupleType: field names live in IRDebugInfo (registered by the85 // Positional TupleType: field names live in IRDebugInfo (registered by the
@@ -93,23 +100,25 @@ REGISTER_OP("struct.set")
93 .set_attr<std::string>("field")100 .set_attr<std::string>("field")
94 .f_deduce_type([](const std::vector<ExprPtr>& args,101 .f_deduce_type([](const std::vector<ExprPtr>& args,
95 const std::vector<std::pair<std::string, std::any>>& kwargs) -> TypePtr {102 const std::vector<std::pair<std::string, std::any>>& kwargs) -> TypePtr {
96- CHECK(args.size() == 2 || args.size() == 3)103+ PRO_IR_CHECK(ExternalError::INVALID_ARGUMENT, args.size() == 2 || args.size() == 3)
97 << "struct.set requires 2 args (base, value) or 3 args (base, index, value), got " << args.size();104 << "struct.set requires 2 args (base, value) or 3 args (base, index, value), got " << args.size();
98- CHECK(args[0]) << "struct.set: base arg is null";105+ PRO_IR_CHECK(npu::tile_fwk::InternalError::COMMON_INNER_ERROR, args[0]) << "struct.set: base arg is null";
99 if (args.size() == 3) {106 if (args.size() == 3) {
100- CHECK(args[1]) << "struct.set: index arg is null";107+ PRO_IR_CHECK(npu::tile_fwk::InternalError::COMMON_INNER_ERROR, args[1]) << "struct.set: index arg is null";
101 }108 }
102- CHECK(args.back()) << "struct.set: value arg is null";109+ PRO_IR_CHECK(npu::tile_fwk::InternalError::COMMON_INNER_ERROR, args.back()) << "struct.set: value arg is null";
103 bool has_field = false;110 bool has_field = false;
104 for (const auto& [key, value] : kwargs) {111 for (const auto& [key, value] : kwargs) {
105 if (key == "field") {112 if (key == "field") {
106- CHECK(IsValidIdentifier(std::any_cast<std::string>(value)))113+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, IsValidIdentifier(std::any_cast<std::string>(value)))
107 << "struct.set 'field' must be a valid identifier";114 << "struct.set 'field' must be a valid identifier";
108 has_field = true;115 has_field = true;
109 }116 }
110 }117 }
111- CHECK(has_field) << "struct.set requires kwarg 'field' (the C++ field name to write)";118+ PRO_IR_CHECK(ExternalError::INVALID_ARGUMENT, has_field)
112- CHECK(args[0]->GetType()->GetKind() == ObjectKind::TupleType) << "struct.set: base must have TupleType";119+ << "struct.set requires kwarg 'field' (the C++ field name to write)";
120+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, args[0]->GetType()->GetKind() == ObjectKind::TupleType)
121+ << "struct.set: base must have TupleType";
113 // Statement side effect; the discarded result type mirrors the struct being written.122 // Statement side effect; the discarded result type mirrors the struct being written.
114 return args[0]->GetType();123 return args[0]->GetType();
115 });124 });
@@ -25,9 +25,11 @@
25#include "ir/op_registry.h"25#include "ir/op_registry.h"
26#include "ir/scalar_expr.h"26#include "ir/scalar_expr.h"
27#include "ir/type.h"27#include "ir/type.h"
28+#include "pypto_pro/error.h"
28 29 
29namespace pypto {30namespace pypto {
30namespace ir {31namespace ir {
32+using npu::tile_fwk::ExternalError;
31 33 
32namespace {34namespace {
33 35 
@@ -47,7 +49,7 @@ std::vector<char> ParsePrintfConversions(const std::string& format)
47 continue;49 continue;
48 }50 }
49 if (i + 1 < format.size() && format[i + 1] == '%') {51 if (i + 1 < format.size() && format[i + 1] == '%') {
50- CHECK(false) << "debug.printf does not support literal '%%'";52+ PRO_IR_CHECK(ExternalError::NOT_IMPLEMENTED_ERROR, false) << "debug.printf does not support literal '%%'";
51 }53 }
52 54 
53 size_t j = i + 1;55 size_t j = i + 1;
@@ -64,16 +66,18 @@ std::vector<char> ParsePrintfConversions(const std::string& format)
64 }66 }
65 if (j < format.size() && format[j] == '.') {67 if (j < format.size() && format[j] == '.') {
66 ++j;68 ++j;
67- CHECK(j < format.size() && std::isdigit(static_cast<unsigned char>(format[j])))69+ PRO_IR_CHECK(ExternalError::INVALID_VAL,
70+ j < format.size() && std::isdigit(static_cast<unsigned char>(format[j])))
68 << "debug.printf precision must be followed by digits";71 << "debug.printf precision must be followed by digits";
69 while (j < format.size() && std::isdigit(static_cast<unsigned char>(format[j]))) {72 while (j < format.size() && std::isdigit(static_cast<unsigned char>(format[j]))) {
70 ++j;73 ++j;
71 }74 }
72 }75 }
73 76 
74- CHECK(j < format.size()) << "debug.printf format ends with an incomplete conversion";77+ PRO_IR_CHECK(ExternalError::INVALID_VAL, j < format.size())
78+ << "debug.printf format ends with an incomplete conversion";
75 char conversion = format[j];79 char conversion = format[j];
76- CHECK(IsSupportedPrintfConversion(conversion))80+ PRO_IR_CHECK(ExternalError::NOT_IMPLEMENTED_ERROR, IsSupportedPrintfConversion(conversion))
77 << "debug.printf does not support conversion '%" << conversion << "'";81 << "debug.printf does not support conversion '%" << conversion << "'";
78 conversions.push_back(conversion);82 conversions.push_back(conversion);
79 i = j + 1;83 i = j + 1;
@@ -107,27 +111,30 @@ bool IsPrintfBoolType(const DataType& dtype) { return dtype == DataType::BOOL; }
107TypePtr DeduceDebugDumpTensorType([[maybe_unused]] const std::vector<ExprPtr>& args,111TypePtr DeduceDebugDumpTensorType([[maybe_unused]] const std::vector<ExprPtr>& args,
108 [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs)112 [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs)
109{113{
110- CHECK(args.size() == 0x3) << "debug.dump_tensor requires exactly 3 arguments (tensor, offsets, shapes), but got "114+ PRO_IR_CHECK(ExternalError::INVALID_ARGUMENT, args.size() == 0x3)
111- << args.size();115+ << "debug.dump_tensor requires exactly 3 arguments (tensor, offsets, shapes), but got " << args.size();
112 116 
113 auto tensor_type = As<TensorType>(args[0]->GetType());117 auto tensor_type = As<TensorType>(args[0]->GetType());
114- CHECK(tensor_type) << "debug.dump_tensor requires first argument to be a TensorType, but got "118+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, tensor_type)
115- << args[0]->GetType()->TypeName();119+ << "debug.dump_tensor requires first argument to be a TensorType, but got " << args[0]->GetType()->TypeName();
116- CHECK(tensor_type->dtype_ != DataType::FP4 && tensor_type->dtype_ != DataType::FP4E2M1 &&120+ PRO_IR_CHECK(ExternalError::NOT_IMPLEMENTED_ERROR, tensor_type->dtype_ != DataType::FP4 &&
117- tensor_type->dtype_ != DataType::FP4E1M2)121+ tensor_type->dtype_ != DataType::FP4E2M1 &&
122+ tensor_type->dtype_ != DataType::FP4E1M2)
118 << "debug.dump_tensor does not support FP4 dtype " << tensor_type->dtype_.ToString();123 << "debug.dump_tensor does not support FP4 dtype " << tensor_type->dtype_.ToString();
119 124 
120 auto offsets = As<MakeTuple>(args[1]);125 auto offsets = As<MakeTuple>(args[1]);
121- CHECK(offsets) << "debug.dump_tensor requires offsets to be a MakeTuple";126+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, offsets) << "debug.dump_tensor requires offsets to be a MakeTuple";
122 127 
123 auto shapes = As<MakeTuple>(args[2]);128 auto shapes = As<MakeTuple>(args[2]);
124- CHECK(shapes) << "debug.dump_tensor requires shapes to be a MakeTuple";129+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, shapes) << "debug.dump_tensor requires shapes to be a MakeTuple";
125 130 
126 const size_t rank = tensor_type->shape_.size();131 const size_t rank = tensor_type->shape_.size();
127- CHECK(offsets->elements_.size() == rank) << "debug.dump_tensor offsets count (" << offsets->elements_.size()132+ PRO_IR_CHECK(ExternalError::INVALID_SHAPE, offsets->elements_.size() == rank)
128- << ") must match tensor rank (" << rank << ")";133+ << "debug.dump_tensor offsets count (" << offsets->elements_.size() << ") must match tensor rank (" << rank
129- CHECK(shapes->elements_.size() == rank) << "debug.dump_tensor shapes count (" << shapes->elements_.size()134+ << ")";
130- << ") must match tensor rank (" << rank << ")";135+ PRO_IR_CHECK(ExternalError::INVALID_SHAPE, shapes->elements_.size() == rank)
136+ << "debug.dump_tensor shapes count (" << shapes->elements_.size() << ") must match tensor rank (" << rank
137+ << ")";
131 138 
132 bool is_full_tensor_window = true;139 bool is_full_tensor_window = true;
133 for (size_t i = 0; i < rank; ++i) {140 for (size_t i = 0; i < rank; ++i) {
@@ -147,27 +154,31 @@ TypePtr DeduceDebugDumpTensorType([[maybe_unused]] const std::vector<ExprPtr>& a
147 if (!is_full_tensor_window && tensor_type->tensor_view_.has_value() && !tensor_type->tensor_view_->stride.empty()) {154 if (!is_full_tensor_window && tensor_type->tensor_view_.has_value() && !tensor_type->tensor_view_->stride.empty()) {
148 const auto& last_stride = tensor_type->tensor_view_->stride.back();155 const auto& last_stride = tensor_type->tensor_view_->stride.back();
149 auto last_stride_const = As<ConstInt>(last_stride);156 auto last_stride_const = As<ConstInt>(last_stride);
150- CHECK(last_stride_const) << "debug.dump_tensor windowed mode requires the innermost stride to be statically 1";157+ PRO_IR_CHECK(ExternalError::INVALID_SHAPE, last_stride_const)
151- CHECK(last_stride_const->value_ == 1)158+ << "debug.dump_tensor windowed mode requires the innermost stride to be statically 1";
159+ PRO_IR_CHECK(ExternalError::INVALID_SHAPE, last_stride_const->value_ == 1)
152 << "debug.dump_tensor windowed mode requires innermost stride == 1, got " << last_stride_const->value_;160 << "debug.dump_tensor windowed mode requires innermost stride == 1, got " << last_stride_const->value_;
153 }161 }
154 162 
155 for (size_t i = 0; i < rank; ++i) {163 for (size_t i = 0; i < rank; ++i) {
156 auto offset_scalar = As<ScalarType>(offsets->elements_[i]->GetType());164 auto offset_scalar = As<ScalarType>(offsets->elements_[i]->GetType());
157- CHECK(offset_scalar) << "debug.dump_tensor offset element " << i << " must be ScalarType, but got "165+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, offset_scalar)
158- << offsets->elements_[i]->GetType()->TypeName();166+ << "debug.dump_tensor offset element " << i << " must be ScalarType, but got "
159- CHECK(offset_scalar->dtype_.IsInt())167+ << offsets->elements_[i]->GetType()->TypeName();
168+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, offset_scalar->dtype_.IsInt())
160 << "debug.dump_tensor offset element " << i << " must have integer dtype, but got "169 << "debug.dump_tensor offset element " << i << " must have integer dtype, but got "
161 << offset_scalar->dtype_.ToString();170 << offset_scalar->dtype_.ToString();
162 171 
163 auto shape_scalar = As<ScalarType>(shapes->elements_[i]->GetType());172 auto shape_scalar = As<ScalarType>(shapes->elements_[i]->GetType());
164- CHECK(shape_scalar) << "debug.dump_tensor shape element " << i << " must be ScalarType, but got "173+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, shape_scalar)
165- << shapes->elements_[i]->GetType()->TypeName();174+ << "debug.dump_tensor shape element " << i << " must be ScalarType, but got "
166- CHECK(shape_scalar->dtype_.IsInt()) << "debug.dump_tensor shape element " << i175+ << shapes->elements_[i]->GetType()->TypeName();
167- << " must have integer dtype, but got " << shape_scalar->dtype_.ToString();176+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, shape_scalar->dtype_.IsInt())
177+ << "debug.dump_tensor shape element " << i << " must have integer dtype, but got "
178+ << shape_scalar->dtype_.ToString();
168 auto shape_const = As<ConstInt>(shapes->elements_[i]);179 auto shape_const = As<ConstInt>(shapes->elements_[i]);
169 if (shape_const) {180 if (shape_const) {
170- CHECK(shape_const->value_ > 0)181+ PRO_IR_CHECK(ExternalError::INVALID_SHAPE, shape_const->value_ > 0)
171 << "debug.dump_tensor shape element " << i << " must be positive, got " << shape_const->value_;182 << "debug.dump_tensor shape element " << i << " must be positive, got " << shape_const->value_;
172 }183 }
173 }184 }
@@ -178,44 +189,51 @@ TypePtr DeduceDebugDumpTensorType([[maybe_unused]] const std::vector<ExprPtr>& a
178TypePtr DeduceDebugDumpTileType([[maybe_unused]] const std::vector<ExprPtr>& args,189TypePtr DeduceDebugDumpTileType([[maybe_unused]] const std::vector<ExprPtr>& args,
179 [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs)190 [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs)
180{191{
181- CHECK(args.size() == 1 || args.size() == 0x3 || args.size() == 0x4)192+ PRO_IR_CHECK(ExternalError::INVALID_ARGUMENT, args.size() == 1 || args.size() == 0x3 || args.size() == 0x4)
182 << "debug.dump_tile requires 1 argument (tile), 3 arguments (tile, offsets, shapes), "193 << "debug.dump_tile requires 1 argument (tile), 3 arguments (tile, offsets, shapes), "
183 << "or 4 arguments (tile, offsets, shapes, workspace), but got " << args.size();194 << "or 4 arguments (tile, offsets, shapes, workspace), but got " << args.size();
184 195 
185 auto tile_type = As<TileType>(args[0]->GetType());196 auto tile_type = As<TileType>(args[0]->GetType());
186- CHECK(tile_type) << "debug.dump_tile requires first argument to be a TileType, but got "197+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, tile_type)
187- << args[0]->GetType()->TypeName();198+ << "debug.dump_tile requires first argument to be a TileType, but got " << args[0]->GetType()->TypeName();
188 199 
189 if (args.size() == 0x3 || args.size() == 0x4) {200 if (args.size() == 0x3 || args.size() == 0x4) {
190 auto offsets = As<MakeTuple>(args[1]);201 auto offsets = As<MakeTuple>(args[1]);
191- CHECK(offsets) << "debug.dump_tile requires second argument to be a MakeTuple (offsets)";202+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, offsets)
203+ << "debug.dump_tile requires second argument to be a MakeTuple (offsets)";
192 204 
193 auto shapes = As<MakeTuple>(args[2]);205 auto shapes = As<MakeTuple>(args[2]);
194- CHECK(shapes) << "debug.dump_tile requires third argument to be a MakeTuple (shapes)";206+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, shapes)
207+ << "debug.dump_tile requires third argument to be a MakeTuple (shapes)";
195 208 
196 const size_t rank = tile_type->shape_.size();209 const size_t rank = tile_type->shape_.size();
197- CHECK(rank == 0x2) << "debug.dump_tile currently only supports 2D tile windows, but got rank " << rank;210+ PRO_IR_CHECK(ExternalError::NOT_IMPLEMENTED_ERROR, rank == 0x2)
198- CHECK(offsets->elements_.size() == rank) << "debug.dump_tile offsets count (" << offsets->elements_.size()211+ << "debug.dump_tile currently only supports 2D tile windows, but got rank " << rank;
199- << ") must match tile rank (" << rank << ")";212+ PRO_IR_CHECK(ExternalError::INVALID_SHAPE, offsets->elements_.size() == rank)
200- CHECK(shapes->elements_.size() == rank) << "debug.dump_tile shapes count (" << shapes->elements_.size()213+ << "debug.dump_tile offsets count (" << offsets->elements_.size() << ") must match tile rank (" << rank
201- << ") must match tile rank (" << rank << ")";214+ << ")";
215+ PRO_IR_CHECK(ExternalError::INVALID_SHAPE, shapes->elements_.size() == rank)
216+ << "debug.dump_tile shapes count (" << shapes->elements_.size() << ") must match tile rank (" << rank
217+ << ")";
202 218 
203 for (size_t i = 0; i < rank; ++i) {219 for (size_t i = 0; i < rank; ++i) {
204 auto offset_scalar = As<ScalarType>(offsets->elements_[i]->GetType());220 auto offset_scalar = As<ScalarType>(offsets->elements_[i]->GetType());
205- CHECK(offset_scalar) << "debug.dump_tile offset element " << i << " must be ScalarType, but got "221+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, offset_scalar)
206- << offsets->elements_[i]->GetType()->TypeName();222+ << "debug.dump_tile offset element " << i << " must be ScalarType, but got "
207- CHECK(offset_scalar->dtype_.IsInt())223+ << offsets->elements_[i]->GetType()->TypeName();
224+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, offset_scalar->dtype_.IsInt())
208 << "debug.dump_tile offset element " << i << " must have integer dtype, but got "225 << "debug.dump_tile offset element " << i << " must have integer dtype, but got "
209 << offset_scalar->dtype_.ToString();226 << offset_scalar->dtype_.ToString();
210 227 
211 auto shape_scalar = As<ScalarType>(shapes->elements_[i]->GetType());228 auto shape_scalar = As<ScalarType>(shapes->elements_[i]->GetType());
212- CHECK(shape_scalar) << "debug.dump_tile shape element " << i << " must be ScalarType, but got "229+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, shape_scalar)
213- << shapes->elements_[i]->GetType()->TypeName();230+ << "debug.dump_tile shape element " << i << " must be ScalarType, but got "
214- CHECK(shape_scalar->dtype_.IsInt())231+ << shapes->elements_[i]->GetType()->TypeName();
232+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, shape_scalar->dtype_.IsInt())
215 << "debug.dump_tile shape element " << i << " must have integer dtype, but got "233 << "debug.dump_tile shape element " << i << " must have integer dtype, but got "
216 << shape_scalar->dtype_.ToString();234 << shape_scalar->dtype_.ToString();
217 if (auto shape_const = As<ConstInt>(shapes->elements_[i])) {235 if (auto shape_const = As<ConstInt>(shapes->elements_[i])) {
218- CHECK(shape_const->value_ > 0)236+ PRO_IR_CHECK(ExternalError::INVALID_SHAPE, shape_const->value_ > 0)
219 << "debug.dump_tile shape element " << i << " must be positive, got " << shape_const->value_;237 << "debug.dump_tile shape element " << i << " must be positive, got " << shape_const->value_;
220 }238 }
221 }239 }
@@ -223,14 +241,16 @@ TypePtr DeduceDebugDumpTileType([[maybe_unused]] const std::vector<ExprPtr>& arg
223 241 
224 if (args.size() == 0x4) {242 if (args.size() == 0x4) {
225 auto workspace_type = As<TensorType>(args[3]->GetType());243 auto workspace_type = As<TensorType>(args[3]->GetType());
226- CHECK(workspace_type) << "debug.dump_tile workspace (4th argument) must be a TensorType, but got "244+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, workspace_type)
227- << args[3]->GetType()->TypeName();245+ << "debug.dump_tile workspace (4th argument) must be a TensorType, but got "
228- CHECK(workspace_type->dtype_ == tile_type->dtype_)246+ << args[3]->GetType()->TypeName();
247+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, workspace_type->dtype_ == tile_type->dtype_)
229 << "debug.dump_tile workspace dtype must match tile dtype (tile: " << tile_type->dtype_.ToString()248 << "debug.dump_tile workspace dtype must match tile dtype (tile: " << tile_type->dtype_.ToString()
230 << ", workspace: " << workspace_type->dtype_.ToString() << ")";249 << ", workspace: " << workspace_type->dtype_.ToString() << ")";
231- CHECK(tile_type->memref_.has_value()) << "debug.dump_tile workspace requires tile to have a memref";250+ PRO_IR_CHECK(ExternalError::INVALID_ARGUMENT, tile_type->memref_.has_value())
251+ << "debug.dump_tile workspace requires tile to have a memref";
232 auto tile_space = (*tile_type->memref_)->memorySpace_;252 auto tile_space = (*tile_type->memref_)->memorySpace_;
233- CHECK(tile_space == MemorySpace::Acc)253+ PRO_IR_CHECK(ExternalError::NOT_IMPLEMENTED_ERROR, tile_space == MemorySpace::Acc)
234 << "debug.dump_tile workspace is only supported for Acc tiles, but got tile in "254 << "debug.dump_tile workspace is only supported for Acc tiles, but got tile in "
235 << MemorySpaceToString(tile_space);255 << MemorySpaceToString(tile_space);
236 }256 }
@@ -250,38 +270,41 @@ TypePtr DeduceDebugPrintfType([[maybe_unused]] const std::vector<ExprPtr>& args,
250 break;270 break;
251 }271 }
252 }272 }
253- CHECK(found_format) << "debug.printf requires 'format' kwarg";273+ PRO_IR_CHECK(ExternalError::INVALID_ARGUMENT, found_format) << "debug.printf requires 'format' kwarg";
254 274 
255 auto conversions = ParsePrintfConversions(format);275 auto conversions = ParsePrintfConversions(format);
256- CHECK(conversions.size() == args.size())276+ PRO_IR_CHECK(ExternalError::INVALID_ARGUMENT, conversions.size() == args.size())
257 << "debug.printf format expects " << conversions.size() << " scalar arguments, but got " << args.size();277 << "debug.printf format expects " << conversions.size() << " scalar arguments, but got " << args.size();
258 278 
259 for (size_t i = 0; i < args.size(); ++i) {279 for (size_t i = 0; i < args.size(); ++i) {
260 char conversion = conversions[i];280 char conversion = conversions[i];
261 if (conversion == 'p') {281 if (conversion == 'p') {
262 auto ptr_type = As<PtrType>(args[i]->GetType());282 auto ptr_type = As<PtrType>(args[i]->GetType());
263- CHECK(ptr_type) << "debug.printf argument " << i << " with '%p' must be PtrType, but got "283+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, ptr_type)
264- << args[i]->GetType()->TypeName();284+ << "debug.printf argument " << i << " with '%p' must be PtrType, but got "
285+ << args[i]->GetType()->TypeName();
265 continue;286 continue;
266 }287 }
267 auto scalar_type = As<ScalarType>(args[i]->GetType());288 auto scalar_type = As<ScalarType>(args[i]->GetType());
268- CHECK(scalar_type) << "debug.printf argument " << i << " must be ScalarType, but got "289+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, scalar_type)
269- << args[i]->GetType()->TypeName();290+ << "debug.printf argument " << i << " must be ScalarType, but got " << args[i]->GetType()->TypeName();
270 291 
271 const DataType& dtype = scalar_type->dtype_;292 const DataType& dtype = scalar_type->dtype_;
272 if (conversion == 'f') {293 if (conversion == 'f') {
273- CHECK(dtype == DataType::FP32)294+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, dtype == DataType::FP32)
274 << "debug.printf conversion '%f' requires FP32 scalar, but got " << dtype.ToString();295 << "debug.printf conversion '%f' requires FP32 scalar, but got " << dtype.ToString();
275 } else if (conversion == 'x') {296 } else if (conversion == 'x') {
276- CHECK(IsPrintfUnsignedIntegerType(dtype) || IsPrintfIndexType(dtype))297+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, IsPrintfUnsignedIntegerType(dtype) || IsPrintfIndexType(dtype))
277 << "debug.printf conversion '%" << conversion << "' requires unsigned integer or index scalar, but got "298 << "debug.printf conversion '%" << conversion << "' requires unsigned integer or index scalar, but got "
278 << dtype.ToString();299 << dtype.ToString();
279 } else if (conversion == 'u') {300 } else if (conversion == 'u') {
280- CHECK(IsPrintfUnsignedIntegerType(dtype) || IsPrintfBoolType(dtype) || IsPrintfIndexType(dtype))301+ PRO_IR_CHECK(ExternalError::INVALID_TYPE,
302+ IsPrintfUnsignedIntegerType(dtype) || IsPrintfBoolType(dtype) || IsPrintfIndexType(dtype))
281 << "debug.printf conversion '%" << conversion303 << "debug.printf conversion '%" << conversion
282 << "' requires unsigned integer, bool, or index scalar, but got " << dtype.ToString();304 << "' requires unsigned integer, bool, or index scalar, but got " << dtype.ToString();
283 } else {305 } else {
284- CHECK(IsPrintfSignedIntegerType(dtype) || IsPrintfBoolType(dtype) || IsPrintfIndexType(dtype))306+ PRO_IR_CHECK(ExternalError::INVALID_TYPE,
307+ IsPrintfSignedIntegerType(dtype) || IsPrintfBoolType(dtype) || IsPrintfIndexType(dtype))
285 << "debug.printf conversion '%" << conversion308 << "debug.printf conversion '%" << conversion
286 << "' requires signed integer, bool, or index scalar, but got " << dtype.ToString();309 << "' requires signed integer, bool, or index scalar, but got " << dtype.ToString();
287 }310 }
@@ -293,7 +316,8 @@ TypePtr DeduceDebugPrintfType([[maybe_unused]] const std::vector<ExprPtr>& args,
293TypePtr DeduceDebugAssertType([[maybe_unused]] const std::vector<ExprPtr>& args,316TypePtr DeduceDebugAssertType([[maybe_unused]] const std::vector<ExprPtr>& args,
294 [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs)317 [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs)
295{318{
296- CHECK(args.size() >= 1) << "debug.assert requires at least 1 argument (condition), but got " << args.size();319+ PRO_IR_CHECK(ExternalError::INVALID_ARGUMENT, args.size() >= 1)
320+ << "debug.assert requires at least 1 argument (condition), but got " << args.size();
297 321 
298 bool found_condition_text = false;322 bool found_condition_text = false;
299 bool found_format = false;323 bool found_format = false;
@@ -308,40 +332,44 @@ TypePtr DeduceDebugAssertType([[maybe_unused]] const std::vector<ExprPtr>& args,
308 found_format = true;332 found_format = true;
309 }333 }
310 }334 }
311- CHECK(found_condition_text) << "debug.assert requires 'condition_text' kwarg";335+ PRO_IR_CHECK(ExternalError::INVALID_ARGUMENT, found_condition_text)
312- CHECK(found_format) << "debug.assert requires 'format' kwarg";336+ << "debug.assert requires 'condition_text' kwarg";
313- CHECK(!condition_text.empty()) << "debug.assert requires non-empty condition_text";337+ PRO_IR_CHECK(ExternalError::INVALID_ARGUMENT, found_format) << "debug.assert requires 'format' kwarg";
338+ PRO_IR_CHECK(ExternalError::INVALID_ARGUMENT, !condition_text.empty())
339+ << "debug.assert requires non-empty condition_text";
314 340 
315 auto scalar_type = As<ScalarType>(args[0]->GetType());341 auto scalar_type = As<ScalarType>(args[0]->GetType());
316- CHECK(scalar_type) << "debug.assert requires condition to be ScalarType, but got "342+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, scalar_type)
317- << args[0]->GetType()->TypeName();343+ << "debug.assert requires condition to be ScalarType, but got " << args[0]->GetType()->TypeName();
318- CHECK(scalar_type->dtype_ == DataType::BOOL)344+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, scalar_type->dtype_ == DataType::BOOL)
319 << "debug.assert requires bool scalar condition, but got " << scalar_type->dtype_.ToString();345 << "debug.assert requires bool scalar condition, but got " << scalar_type->dtype_.ToString();
320 346 
321 auto conversions = ParsePrintfConversions(format);347 auto conversions = ParsePrintfConversions(format);
322- CHECK(conversions.size() == args.size() - 1)348+ PRO_IR_CHECK(ExternalError::INVALID_ARGUMENT, conversions.size() == args.size() - 1)
323 << "debug.assert format expects " << conversions.size() << " scalar arguments, but got " << (args.size() - 1);349 << "debug.assert format expects " << conversions.size() << " scalar arguments, but got " << (args.size() - 1);
324 350 
325 for (size_t i = 1; i < args.size(); ++i) {351 for (size_t i = 1; i < args.size(); ++i) {
326 auto printf_arg = As<ScalarType>(args[i]->GetType());352 auto printf_arg = As<ScalarType>(args[i]->GetType());
327- CHECK(printf_arg) << "debug.assert argument " << (i - 1) << " must be ScalarType, but got "353+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, printf_arg)
328- << args[i]->GetType()->TypeName();354+ << "debug.assert argument " << (i - 1) << " must be ScalarType, but got " << args[i]->GetType()->TypeName();
329 355 
330 const DataType& dtype = printf_arg->dtype_;356 const DataType& dtype = printf_arg->dtype_;
331 char conversion = conversions[i - 1];357 char conversion = conversions[i - 1];
332 if (conversion == 'f') {358 if (conversion == 'f') {
333- CHECK(dtype == DataType::FP32)359+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, dtype == DataType::FP32)
334 << "debug.assert conversion '%f' requires FP32 scalar, but got " << dtype.ToString();360 << "debug.assert conversion '%f' requires FP32 scalar, but got " << dtype.ToString();
335 } else if (conversion == 'x') {361 } else if (conversion == 'x') {
336- CHECK(IsPrintfUnsignedIntegerType(dtype) || IsPrintfIndexType(dtype))362+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, IsPrintfUnsignedIntegerType(dtype) || IsPrintfIndexType(dtype))
337 << "debug.assert conversion '%" << conversion << "' requires unsigned integer or index scalar, but got "363 << "debug.assert conversion '%" << conversion << "' requires unsigned integer or index scalar, but got "
338 << dtype.ToString();364 << dtype.ToString();
339 } else if (conversion == 'u') {365 } else if (conversion == 'u') {
340- CHECK(IsPrintfUnsignedIntegerType(dtype) || IsPrintfBoolType(dtype) || IsPrintfIndexType(dtype))366+ PRO_IR_CHECK(ExternalError::INVALID_TYPE,
367+ IsPrintfUnsignedIntegerType(dtype) || IsPrintfBoolType(dtype) || IsPrintfIndexType(dtype))
341 << "debug.assert conversion '%" << conversion368 << "debug.assert conversion '%" << conversion
342 << "' requires unsigned integer, bool, or index scalar, but got " << dtype.ToString();369 << "' requires unsigned integer, bool, or index scalar, but got " << dtype.ToString();
343 } else {370 } else {
344- CHECK(IsPrintfSignedIntegerType(dtype) || IsPrintfBoolType(dtype) || IsPrintfIndexType(dtype))371+ PRO_IR_CHECK(ExternalError::INVALID_TYPE,
372+ IsPrintfSignedIntegerType(dtype) || IsPrintfBoolType(dtype) || IsPrintfIndexType(dtype))
345 << "debug.assert conversion '%" << conversion373 << "debug.assert conversion '%" << conversion
346 << "' requires signed integer, bool, or index scalar, but got " << dtype.ToString();374 << "' requires signed integer, bool, or index scalar, but got " << dtype.ToString();
347 }375 }
@@ -30,9 +30,11 @@
30#include "ir/scalar_expr.h"30#include "ir/scalar_expr.h"
31#include "ir/type.h"31#include "ir/type.h"
32#include "ir/type_inference.h"32#include "ir/type_inference.h"
33+#include "pypto_pro/error.h"
33 34 
34namespace pypto {35namespace pypto {
35namespace ir {36namespace ir {
37+using npu::tile_fwk::ExternalError;
36 38 
37TypePtr DeduceAddPtrType([[maybe_unused]] const std::vector<ExprPtr>& args,39TypePtr DeduceAddPtrType([[maybe_unused]] const std::vector<ExprPtr>& args,
38 [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs)40 [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs)
@@ -40,18 +42,22 @@ TypePtr DeduceAddPtrType([[maybe_unused]] const std::vector<ExprPtr>& args,
40 // ptr.addptr: Advance a pointer by an integer offset42 // ptr.addptr: Advance a pointer by an integer offset
41 // Args: (ptr, offset)43 // Args: (ptr, offset)
42 // Returns: same PtrType as input (pointer bumped but same element dtype)44 // Returns: same PtrType as input (pointer bumped but same element dtype)
43- CHECK(args.size() == 0x2) << "ptr.addptr requires exactly 2 arguments (ptr, offset), but got " << args.size();45+ PRO_IR_CHECK(ExternalError::INVALID_ARGUMENT, args.size() == 0x2)
46+ << "ptr.addptr requires exactly 2 arguments (ptr, offset), but got " << args.size();
44 47 
45 // First argument must be PtrType48 // First argument must be PtrType
46 auto ptr_type = As<PtrType>(args[0]->GetType());49 auto ptr_type = As<PtrType>(args[0]->GetType());
47- CHECK(ptr_type) << "ptr.addptr requires first argument to be a PtrType, but got " << args[0]->GetType()->TypeName()50+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, ptr_type)
48- << ". Use pl.Ptr[dtype] to annotate pointer parameters.";51+ << "ptr.addptr requires first argument to be a PtrType, but got " << args[0]->GetType()->TypeName()
52+ << ". Use pl.Ptr[dtype] to annotate pointer parameters.";
49 53 
50 // Second argument must be ScalarType with integer or index dtype54 // Second argument must be ScalarType with integer or index dtype
51 auto offset_type = As<ScalarType>(args[1]->GetType());55 auto offset_type = As<ScalarType>(args[1]->GetType());
52- CHECK(offset_type) << "ptr.addptr requires second argument (offset) to be a ScalarType, but got "56+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, offset_type)
53- << args[1]->GetType()->TypeName();57+ << "ptr.addptr requires second argument (offset) to be a ScalarType, but got "
54- CHECK(offset_type->dtype_.IsInt() || offset_type->dtype_ == DataType(DataType::INDEX))58+ << args[1]->GetType()->TypeName();
59+ PRO_IR_CHECK(ExternalError::INVALID_TYPE,
60+ offset_type->dtype_.IsInt() || offset_type->dtype_ == DataType(DataType::INDEX))
55 << "ptr.addptr offset must have integer or index dtype, but got " << offset_type->dtype_.ToString();61 << "ptr.addptr offset must have integer or index dtype, but got " << offset_type->dtype_.ToString();
56 62 
57 // Return the same PtrType (pointer is advanced but still points to same element type),63 // Return the same PtrType (pointer is advanced but still points to same element type),
@@ -96,11 +102,12 @@ TypePtr DeduceMakePtrType([[maybe_unused]] const std::vector<ExprPtr>& args,
96 // ptr.make_ptr: Reinterpret a pointer as a (usually different) element dtype, or extract102 // ptr.make_ptr: Reinterpret a pointer as a (usually different) element dtype, or extract
97 // a raw pointer from a tensor. Args: (ptr_or_tensor); kwarg: dtype.103 // a raw pointer from a tensor. Args: (ptr_or_tensor); kwarg: dtype.
98 // Returns: a PtrType with the new element dtype, reusing the same underlying address.104 // Returns: a PtrType with the new element dtype, reusing the same underlying address.
99- CHECK(args.size() == 1) << "ptr.make_ptr requires exactly 1 argument (ptr), but got " << args.size();105+ PRO_IR_CHECK(ExternalError::INVALID_ARGUMENT, args.size() == 1)
106+ << "ptr.make_ptr requires exactly 1 argument (ptr), but got " << args.size();
100 107 
101 auto ptr_type = As<PtrType>(args[0]->GetType());108 auto ptr_type = As<PtrType>(args[0]->GetType());
102 auto tensor_type = As<TensorType>(args[0]->GetType());109 auto tensor_type = As<TensorType>(args[0]->GetType());
103- CHECK(ptr_type || tensor_type)110+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, ptr_type || tensor_type)
104 << "ptr.make_ptr requires first argument to be a PtrType or TensorType, but got "111 << "ptr.make_ptr requires first argument to be a PtrType or TensorType, but got "
105 << args[0]->GetType()->TypeName()112 << args[0]->GetType()->TypeName()
106 << ". Use pl.Ptr[dtype] for pointer params or pl.Tensor[[shape], dtype] for tensor params.";113 << ". Use pl.Ptr[dtype] for pointer params or pl.Tensor[[shape], dtype] for tensor params.";
@@ -134,8 +141,8 @@ TypePtr DeduceMakeTensorType([[maybe_unused]] const std::vector<ExprPtr>& args,
134 // ptr.make_tensor: Create a tensor view from a pointer (or an existing tensor) with141 // ptr.make_tensor: Create a tensor view from a pointer (or an existing tensor) with
135 // shape and optional strides. An empty stride tuple means an implicit contiguous142 // shape and optional strides. An empty stride tuple means an implicit contiguous
136 // row-major layout. Args: (ptr_or_tensor, shape_tuple, stride_tuple)143 // row-major layout. Args: (ptr_or_tensor, shape_tuple, stride_tuple)
137- CHECK(args.size() == 0x3) << "ptr.make_tensor requires exactly 3 arguments (ptr, shape, stride), but got "144+ PRO_IR_CHECK(ExternalError::INVALID_ARGUMENT, args.size() == 0x3)
138- << args.size();145+ << "ptr.make_tensor requires exactly 3 arguments (ptr, shape, stride), but got " << args.size();
139 146 
140 // First argument is either:147 // First argument is either:
141 // - a PtrType: a raw pointer to typed global memory, or148 // - a PtrType: a raw pointer to typed global memory, or
@@ -148,22 +155,23 @@ TypePtr DeduceMakeTensorType([[maybe_unused]] const std::vector<ExprPtr>& args,
148 } else if (auto src_tensor_type = As<TensorType>(args[0]->GetType())) {155 } else if (auto src_tensor_type = As<TensorType>(args[0]->GetType())) {
149 source_dtype = src_tensor_type->dtype_;156 source_dtype = src_tensor_type->dtype_;
150 } else {157 } else {
151- CHECK(false) << "ptr.make_tensor requires first argument to be a PtrType or TensorType, but got "158+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, false)
152- << args[0]->GetType()->TypeName()159+ << "ptr.make_tensor requires first argument to be a PtrType or TensorType, but got "
153- << ". Use pl.Ptr[dtype] to annotate pointer parameters, or pass an existing pl.Tensor.";160+ << args[0]->GetType()->TypeName()
161+ << ". Use pl.Ptr[dtype] to annotate pointer parameters, or pass an existing pl.Tensor.";
154 }162 }
155 163 
156 // Second argument must be MakeTuple (shape)164 // Second argument must be MakeTuple (shape)
157 auto shape_tuple = As<MakeTuple>(args[1]);165 auto shape_tuple = As<MakeTuple>(args[1]);
158- CHECK(shape_tuple) << "ptr.make_tensor requires shape to be a MakeTuple";166+ PRO_IR_CHECK(ExternalError::INVALID_SHAPE, shape_tuple) << "ptr.make_tensor requires shape to be a MakeTuple";
159 167 
160 // Third argument must be MakeTuple (stride); an empty tuple means implicit contiguous stride.168 // Third argument must be MakeTuple (stride); an empty tuple means implicit contiguous stride.
161 auto stride_tuple = As<MakeTuple>(args[2]);169 auto stride_tuple = As<MakeTuple>(args[2]);
162- CHECK(stride_tuple) << "ptr.make_tensor requires stride to be a MakeTuple";170+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, stride_tuple) << "ptr.make_tensor requires stride to be a MakeTuple";
163 171 
164 const auto& stride = stride_tuple->elements_;172 const auto& stride = stride_tuple->elements_;
165 if (!stride.empty()) {173 if (!stride.empty()) {
166- CHECK(shape_tuple->elements_.size() == stride.size())174+ PRO_IR_CHECK(ExternalError::INVALID_SHAPE, shape_tuple->elements_.size() == stride.size())
167 << "ptr.make_tensor shape rank (" << shape_tuple->elements_.size() << ") must match stride rank ("175 << "ptr.make_tensor shape rank (" << shape_tuple->elements_.size() << ") must match stride rank ("
168 << stride.size() << ")";176 << stride.size() << ")";
169 }177 }
@@ -181,7 +189,7 @@ TypePtr DeduceMakeTensorType([[maybe_unused]] const std::vector<ExprPtr>& args,
181 constexpr size_t kBitsPerByte = 8;189 constexpr size_t kBitsPerByte = 8;
182 if (!stride.empty() && result_dtype.GetBit() < kBitsPerByte) {190 if (!stride.empty() && result_dtype.GetBit() < kBitsPerByte) {
183 auto innermost = As<ConstInt>(stride.back());191 auto innermost = As<ConstInt>(stride.back());
184- CHECK(innermost != nullptr && innermost->value_ == 1)192+ PRO_IR_CHECK(ExternalError::INVALID_ARGUMENT, innermost != nullptr && innermost->value_ == 1)
185 << "ptr.make_tensor: a " << result_dtype.ToString()193 << "ptr.make_tensor: a " << result_dtype.ToString()
186 << " view must be contiguous along its innermost axis (stride 1), because two elements "194 << " view must be contiguous along its innermost axis (stride 1), because two elements "
187 << "share a byte there and a half-byte cannot be addressed; got "195 << "share a byte there and a half-byte cannot be addressed; got "
@@ -33,42 +33,49 @@
33#include "ir/scalar_expr.h"33#include "ir/scalar_expr.h"
34#include "ir/type.h"34#include "ir/type.h"
35#include "ir/type_inference.h"35#include "ir/type_inference.h"
36+#include "pypto_pro/error.h"
36 37 
37namespace pypto {38namespace pypto {
38namespace ir {39namespace ir {
40+using npu::tile_fwk::ExternalError;
39 41 
40namespace {42namespace {
41 43 
42TypePtr DeduceSimtContextComponentType(const std::vector<ExprPtr>& args,44TypePtr DeduceSimtContextComponentType(const std::vector<ExprPtr>& args,
43 const std::vector<std::pair<std::string, std::any>>& kwargs)45 const std::vector<std::pair<std::string, std::any>>& kwargs)
44{46{
45- CHECK(args.empty()) << "SIMT context operations do not accept positional arguments";47+ PRO_IR_CHECK(ExternalError::INVALID_ARGUMENT, args.empty())
48+ << "SIMT context operations do not accept positional arguments";
46 int axis = GetOpKwarg<int>(kwargs, "axis", 0);49 int axis = GetOpKwarg<int>(kwargs, "axis", 0);
47- CHECK(axis >= 0 && axis <= 2) << "SIMT context axis must be in [0, 2], got axis=" << axis;50+ PRO_IR_CHECK(ExternalError::INVALID_SHAPE, axis >= 0 && axis <= 2)
51+ << "SIMT context axis must be in [0, 2], got axis=" << axis;
48 return std::make_shared<ScalarType>(DataType(DataType::UINT32));52 return std::make_shared<ScalarType>(DataType(DataType::UINT32));
49}53}
50 54 
51TypePtr DeduceSimtLinearThreadIdxType(const std::vector<ExprPtr>& args,55TypePtr DeduceSimtLinearThreadIdxType(const std::vector<ExprPtr>& args,
52 const std::vector<std::pair<std::string, std::any>>& kwargs)56 const std::vector<std::pair<std::string, std::any>>& kwargs)
53{57{
54- CHECK(args.empty()) << "SIMT builtin scalar operations do not accept positional arguments";58+ PRO_IR_CHECK(ExternalError::INVALID_ARGUMENT, args.empty())
55- CHECK(kwargs.empty()) << "SIMT builtin scalar operations do not accept keyword arguments";59+ << "SIMT builtin scalar operations do not accept positional arguments";
60+ PRO_IR_CHECK(ExternalError::INVALID_ARGUMENT, kwargs.empty())
61+ << "SIMT builtin scalar operations do not accept keyword arguments";
56 return std::make_shared<ScalarType>(DataType(DataType::UINT32));62 return std::make_shared<ScalarType>(DataType(DataType::UINT32));
57}63}
58 64 
59TypePtr DeduceSimtWarpSizeType(const std::vector<ExprPtr>& args,65TypePtr DeduceSimtWarpSizeType(const std::vector<ExprPtr>& args,
60 const std::vector<std::pair<std::string, std::any>>& kwargs)66 const std::vector<std::pair<std::string, std::any>>& kwargs)
61{67{
62- CHECK(args.empty()) << "simt.warp_size does not accept positional arguments";68+ PRO_IR_CHECK(ExternalError::INVALID_ARGUMENT, args.empty())
63- CHECK(kwargs.empty()) << "simt.warp_size does not accept keyword arguments";69+ << "simt.warp_size does not accept positional arguments";
70+ PRO_IR_CHECK(ExternalError::INVALID_ARGUMENT, kwargs.empty()) << "simt.warp_size does not accept keyword arguments";
64 return std::make_shared<ScalarType>(DataType(DataType::INT32));71 return std::make_shared<ScalarType>(DataType(DataType::INT32));
65}72}
66 73 
67TypePtr DeduceSimtSyncType(const std::string& op_name, const std::vector<ExprPtr>& args,74TypePtr DeduceSimtSyncType(const std::string& op_name, const std::vector<ExprPtr>& args,
68 const std::vector<std::pair<std::string, std::any>>& kwargs)75 const std::vector<std::pair<std::string, std::any>>& kwargs)
69{76{
70- CHECK(args.empty()) << op_name << " does not accept positional arguments";77+ PRO_IR_CHECK(ExternalError::INVALID_ARGUMENT, args.empty()) << op_name << " does not accept positional arguments";
71- CHECK(kwargs.empty()) << op_name << " does not accept keyword arguments";78+ PRO_IR_CHECK(ExternalError::INVALID_ARGUMENT, kwargs.empty()) << op_name << " does not accept keyword arguments";
72 return GetNoneType();79 return GetNoneType();
73}80}
74 81 
@@ -190,13 +197,13 @@ bool IsSimtCastSupported(DataType source_dtype, DataType target_dtype, RoundMode
190TypePtr DeduceSimtCastType(const std::vector<ExprPtr>& args,197TypePtr DeduceSimtCastType(const std::vector<ExprPtr>& args,
191 const std::vector<std::pair<std::string, std::any>>& kwargs)198 const std::vector<std::pair<std::string, std::any>>& kwargs)
192{199{
193- CHECK(args.size() == 1) << "simt.cast requires one scalar argument";200+ PRO_IR_CHECK(ExternalError::INVALID_ARGUMENT, args.size() == 1) << "simt.cast requires one scalar argument";
194 auto source_type = As<ScalarType>(args[0]->GetType());201 auto source_type = As<ScalarType>(args[0]->GetType());
195- CHECK(source_type) << "simt.cast value must be a scalar";202+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, source_type) << "simt.cast value must be a scalar";
196 203 
197 DataType target_dtype = GetOpKwarg<DataType>(kwargs, "target_type");204 DataType target_dtype = GetOpKwarg<DataType>(kwargs, "target_type");
198 auto mode = static_cast<RoundMode>(GetOpKwarg<int>(kwargs, "mode"));205 auto mode = static_cast<RoundMode>(GetOpKwarg<int>(kwargs, "mode"));
199- CHECK(IsSimtCastSupported(source_type->dtype_, target_dtype, mode))206+ PRO_IR_CHECK(ExternalError::NOT_IMPLEMENTED_ERROR, IsSimtCastSupported(source_type->dtype_, target_dtype, mode))
200 << "simt.cast does not support " << source_type->dtype_.ToString() << " -> " << target_dtype.ToString()207 << "simt.cast does not support " << source_type->dtype_.ToString() << " -> " << target_dtype.ToString()
201 << " with mode " << EnumToString(mode);208 << " with mode " << EnumToString(mode);
202 return std::make_shared<ScalarType>(target_dtype);209 return std::make_shared<ScalarType>(target_dtype);
@@ -222,16 +229,16 @@ bool IsSimtBitcastSupported(DataType source_dtype, DataType target_dtype)
222TypePtr DeduceSimtBitcastType(const std::vector<ExprPtr>& args,229TypePtr DeduceSimtBitcastType(const std::vector<ExprPtr>& args,
223 const std::vector<std::pair<std::string, std::any>>& kwargs)230 const std::vector<std::pair<std::string, std::any>>& kwargs)
224{231{
225- CHECK(args.size() == 1) << "simt.bitcast requires one scalar argument";232+ PRO_IR_CHECK(ExternalError::INVALID_ARGUMENT, args.size() == 1) << "simt.bitcast requires one scalar argument";
226 auto source_type = As<ScalarType>(args[0]->GetType());233 auto source_type = As<ScalarType>(args[0]->GetType());
227- CHECK(source_type) << "simt.bitcast value must be a scalar";234+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, source_type) << "simt.bitcast value must be a scalar";
228 235 
229 DataType target_dtype = GetOpKwarg<DataType>(kwargs, "target_type");236 DataType target_dtype = GetOpKwarg<DataType>(kwargs, "target_type");
230- CHECK(source_type->dtype_.GetBit() == target_dtype.GetBit())237+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, source_type->dtype_.GetBit() == target_dtype.GetBit())
231 << "simt.bitcast requires source and target dtypes to have the same bit width, got "238 << "simt.bitcast requires source and target dtypes to have the same bit width, got "
232 << source_type->dtype_.ToString() << " (" << source_type->dtype_.GetBit() << " bits) -> "239 << source_type->dtype_.ToString() << " (" << source_type->dtype_.GetBit() << " bits) -> "
233 << target_dtype.ToString() << " (" << target_dtype.GetBit() << " bits)";240 << target_dtype.ToString() << " (" << target_dtype.GetBit() << " bits)";
234- CHECK(IsSimtBitcastSupported(source_type->dtype_, target_dtype))241+ PRO_IR_CHECK(ExternalError::NOT_IMPLEMENTED_ERROR, IsSimtBitcastSupported(source_type->dtype_, target_dtype))
235 << "simt.bitcast does not support " << source_type->dtype_.ToString() << " -> " << target_dtype.ToString();242 << "simt.bitcast does not support " << source_type->dtype_.ToString() << " -> " << target_dtype.ToString();
236 return std::make_shared<ScalarType>(target_dtype);243 return std::make_shared<ScalarType>(target_dtype);
237}244}
@@ -252,27 +259,30 @@ TypePtr DeduceSimtAtomicType(const std::string& op_name, size_t operand_count,
252 const std::vector<std::pair<std::string, std::any>>& kwargs,259 const std::vector<std::pair<std::string, std::any>>& kwargs,
253 std::initializer_list<DataType> no_result_dtypes = {})260 std::initializer_list<DataType> no_result_dtypes = {})
254{261{
255- CHECK(args.size() == operand_count + 2)262+ PRO_IR_CHECK(ExternalError::INVALID_ARGUMENT, args.size() == operand_count + 2)
256 << op_name << " requires container, offset, and " << operand_count << " scalar operand(s)";263 << op_name << " requires container, offset, and " << operand_count << " scalar operand(s)";
257- CHECK(kwargs.empty()) << op_name << " does not accept keyword arguments";264+ PRO_IR_CHECK(ExternalError::INVALID_ARGUMENT, kwargs.empty()) << op_name << " does not accept keyword arguments";
258 265 
259 auto tile_type = As<TileType>(args[0]->GetType());266 auto tile_type = As<TileType>(args[0]->GetType());
260 auto tensor_type = As<TensorType>(args[0]->GetType());267 auto tensor_type = As<TensorType>(args[0]->GetType());
261- CHECK(tile_type || tensor_type) << op_name << " container must be a Tile or Tensor";268+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, tile_type || tensor_type)
269+ << op_name << " container must be a Tile or Tensor";
262 DataType dtype = tile_type ? tile_type->dtype_ : tensor_type->dtype_;270 DataType dtype = tile_type ? tile_type->dtype_ : tensor_type->dtype_;
263- CHECK(IsSimtAtomicDtype(dtype, tile_type ? ub_dtypes : gm_dtypes))271+ PRO_IR_CHECK(ExternalError::NOT_IMPLEMENTED_ERROR, IsSimtAtomicDtype(dtype, tile_type ? ub_dtypes : gm_dtypes))
264 << op_name << " does not support dtype " << dtype.ToString() << " on " << (tile_type ? "UB Tile" : "GM Tensor");272 << op_name << " does not support dtype " << dtype.ToString() << " on " << (tile_type ? "UB Tile" : "GM Tensor");
265 273 
266 auto offset_type = As<ScalarType>(args[1]->GetType());274 auto offset_type = As<ScalarType>(args[1]->GetType());
267- CHECK(offset_type && offset_type->dtype_ != DataType::BOOL &&275+ PRO_IR_CHECK(ExternalError::INVALID_TYPE,
268- (offset_type->dtype_.IsInt() || offset_type->dtype_ == DataType::INDEX))276+ offset_type && offset_type->dtype_ != DataType::BOOL &&
277+ (offset_type->dtype_.IsInt() || offset_type->dtype_ == DataType::INDEX))
269 << op_name << " offset must be a non-bool integer scalar";278 << op_name << " offset must be a non-bool integer scalar";
270 279 
271 for (size_t i = 0; i < operand_count; ++i) {280 for (size_t i = 0; i < operand_count; ++i) {
272 auto operand_type = As<ScalarType>(args[i + 2]->GetType());281 auto operand_type = As<ScalarType>(args[i + 2]->GetType());
273- CHECK(operand_type) << op_name << " operand " << i << " must be a scalar";282+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, operand_type) << op_name << " operand " << i << " must be a scalar";
274- CHECK(operand_type->dtype_ == dtype) << op_name << " operand " << i << " dtype must match target dtype "283+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, operand_type->dtype_ == dtype)
275- << dtype.ToString() << ", but got " << operand_type->dtype_.ToString();284+ << op_name << " operand " << i << " dtype must match target dtype " << dtype.ToString() << ", but got "
285+ << operand_type->dtype_.ToString();
276 }286 }
277 if (IsSimtAtomicDtype(dtype, no_result_dtypes)) {287 if (IsSimtAtomicDtype(dtype, no_result_dtypes)) {
278 return GetNoneType();288 return GetNoneType();
@@ -297,21 +307,23 @@ TypePtr DeduceSimtMathType(const std::string& op_name, size_t operand_count,
297 const std::vector<std::pair<std::string, std::any>>& kwargs,307 const std::vector<std::pair<std::string, std::any>>& kwargs,
298 std::optional<DataType> result_dtype = std::nullopt)308 std::optional<DataType> result_dtype = std::nullopt)
299{309{
300- CHECK(args.size() == operand_count) << op_name << " requires exactly " << operand_count << " scalar operand(s)";310+ PRO_IR_CHECK(ExternalError::INVALID_ARGUMENT, args.size() == operand_count)
301- CHECK(kwargs.empty()) << op_name << " does not accept keyword arguments";311+ << op_name << " requires exactly " << operand_count << " scalar operand(s)";
312+ PRO_IR_CHECK(ExternalError::INVALID_ARGUMENT, kwargs.empty()) << op_name << " does not accept keyword arguments";
302 313 
303 DataType dtype = DataType::BOOL;314 DataType dtype = DataType::BOOL;
304 for (size_t i = 0; i < args.size(); ++i) {315 for (size_t i = 0; i < args.size(); ++i) {
305 auto scalar_type = As<ScalarType>(args[i]->GetType());316 auto scalar_type = As<ScalarType>(args[i]->GetType());
306- CHECK(scalar_type) << op_name << " operand " << i << " must be a scalar";317+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, scalar_type) << op_name << " operand " << i << " must be a scalar";
307 if (i == 0) {318 if (i == 0) {
308 dtype = scalar_type->dtype_;319 dtype = scalar_type->dtype_;
309- CHECK(IsSimtAtomicDtype(dtype, supported_dtypes))320+ PRO_IR_CHECK(ExternalError::NOT_IMPLEMENTED_ERROR, IsSimtAtomicDtype(dtype, supported_dtypes))
310 << op_name << " supports only " << FormatSupportedDtypes(supported_dtypes) << ", got "321 << op_name << " supports only " << FormatSupportedDtypes(supported_dtypes) << ", got "
311 << dtype.ToString();322 << dtype.ToString();
312 } else {323 } else {
313- CHECK(scalar_type->dtype_ == dtype) << op_name << " requires operands with the same dtype, got "324+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, scalar_type->dtype_ == dtype)
314- << dtype.ToString() << " and " << scalar_type->dtype_.ToString();325+ << op_name << " requires operands with the same dtype, got " << dtype.ToString() << " and "
326+ << scalar_type->dtype_.ToString();
315 }327 }
316 }328 }
317 return std::make_shared<ScalarType>(result_dtype.value_or(dtype));329 return std::make_shared<ScalarType>(result_dtype.value_or(dtype));
@@ -320,50 +332,65 @@ TypePtr DeduceSimtMathType(const std::string& op_name, size_t operand_count,
320TypePtr DeduceSimtLaunchType(const std::vector<ExprPtr>& args,332TypePtr DeduceSimtLaunchType(const std::vector<ExprPtr>& args,
321 const std::vector<std::pair<std::string, std::any>>& kwargs)333 const std::vector<std::pair<std::string, std::any>>& kwargs)
322{334{
323- CHECK(args.size() >= 3) << "simt.launch requires three launch dimensions";335+ PRO_IR_CHECK(ExternalError::INVALID_SHAPE, args.size() >= 3) << "simt.launch requires three launch dimensions";
324 int64_t total_threads = 1;336 int64_t total_threads = 1;
325 for (std::size_t i = 0; i < 3; ++i) {337 for (std::size_t i = 0; i < 3; ++i) {
326 auto dim_type = As<ScalarType>(args[i]->GetType());338 auto dim_type = As<ScalarType>(args[i]->GetType());
327- CHECK(dim_type && dim_type->dtype_.IsInt() && dim_type->dtype_ != DataType(DataType::BOOL))339+ PRO_IR_CHECK(ExternalError::INVALID_SHAPE,
340+ dim_type && dim_type->dtype_.IsInt() && dim_type->dtype_ != DataType(DataType::BOOL))
328 << "simt.launch dimensions must be non-bool integer scalars";341 << "simt.launch dimensions must be non-bool integer scalars";
329 auto dim = As<ConstInt>(args[i]);342 auto dim = As<ConstInt>(args[i]);
330- CHECK(dim && dim->value_ > 0 && dim->value_ <= 2048)343+ PRO_IR_CHECK(ExternalError::INVALID_SHAPE, dim && dim->value_ > 0 && dim->value_ <= 2048)
331 << "simt.launch dimensions must be compile-time integers in [1, 2048], got dim[" << i344 << "simt.launch dimensions must be compile-time integers in [1, 2048], got dim[" << i
332 << "]=" << (dim ? dim->value_ : -1);345 << "]=" << (dim ? dim->value_ : -1);
333 total_threads *= dim->value_;346 total_threads *= dim->value_;
334 }347 }
335- CHECK(total_threads <= 2048) << "simt.launch total thread count must not exceed 2048, got total_threads="348+ PRO_IR_CHECK(ExternalError::OUT_OF_RANGE, total_threads <= 2048)
336- << total_threads;349+ << "simt.launch total thread count must not exceed 2048, got total_threads=" << total_threads;
337 int max_threads = GetOpKwarg<int>(kwargs, "max_threads");350 int max_threads = GetOpKwarg<int>(kwargs, "max_threads");
338- CHECK(max_threads >= 1 && max_threads <= 2048) << "simt.launch max_threads must be in [1, 2048]";351+ PRO_IR_CHECK(ExternalError::OUT_OF_RANGE, max_threads >= 1 && max_threads <= 2048)
339- CHECK(total_threads <= max_threads) << "simt.launch threads " << total_threads << " exceed callee max_threads "352+ << "simt.launch max_threads must be in [1, 2048]";
340- << max_threads;353+ PRO_IR_CHECK(ExternalError::OUT_OF_RANGE, total_threads <= max_threads)
354+ << "simt.launch threads " << total_threads << " exceed callee max_threads " << max_threads;
341 for (std::size_t i = 3; i < args.size(); ++i) {355 for (std::size_t i = 3; i < args.size(); ++i) {
342 auto arg_type = args[i]->GetType();356 auto arg_type = args[i]->GetType();
343 if (auto tile_type = As<TileType>(arg_type)) {357 if (auto tile_type = As<TileType>(arg_type)) {
344- CHECK(tile_type->shape_.size() == 2) << "simt.launch Tile argument must have a two-dimensional shape";358+ PRO_IR_CHECK(ExternalError::INVALID_SHAPE, tile_type->shape_.size() == 2)
345- CHECK(As<Var>(args[i]) != nullptr) << "simt.launch Tile argument must be a Var";359+ << "simt.launch Tile argument must have a two-dimensional shape";
360+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, As<Var>(args[i]) != nullptr)
361+ << "simt.launch Tile argument must be a Var";
346 for (const auto& dim : tile_type->shape_) {362 for (const auto& dim : tile_type->shape_) {
347- CHECK(As<ConstInt>(dim) != nullptr) << "simt.launch Tile argument must have a static shape";363+ PRO_IR_CHECK(ExternalError::DYNAMIC_SHAPE_COMPUTE_UNSUPPORTED, As<ConstInt>(dim) != nullptr)
364+ << "simt.launch Tile argument must have a static shape";
348 }365 }
349- CHECK(tile_type->dtype_.GetBit() >= 8) << "simt.launch Tile argument has a sub-byte element dtype";366+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, tile_type->dtype_.GetBit() >= 8)
350- CHECK(tile_type->memref_.has_value()) << "simt.launch Tile argument has no memory reference";367+ << "simt.launch Tile argument has a sub-byte element dtype";
351- CHECK((*tile_type->memref_)->memorySpace_ == MemorySpace::Vec)368+ PRO_IR_CHECK(ExternalError::INVALID_ARGUMENT, tile_type->memref_.has_value())
369+ << "simt.launch Tile argument has no memory reference";
370+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, (*tile_type->memref_)->memorySpace_ == MemorySpace::Vec)
352 << "simt.launch Tile argument must be a Vec-memory Tile";371 << "simt.launch Tile argument must be a Vec-memory Tile";
353- CHECK(tile_type->hardwareInfo_.has_value() && tile_type->hardwareInfo_->blayout == TileLayout::row_major &&372+ PRO_IR_CHECK(ExternalError::INVALID_FORMAT,
354- tile_type->hardwareInfo_->slayout == TileLayout::none_box)373+ tile_type->hardwareInfo_.has_value() &&
374+ tile_type->hardwareInfo_->blayout == TileLayout::row_major &&
375+ tile_type->hardwareInfo_->slayout == TileLayout::none_box)
355 << "simt.launch Tile argument must be an ND Vec Tile";376 << "simt.launch Tile argument must be an ND Vec Tile";
356 } else if (auto tensor_type = As<TensorType>(arg_type)) {377 } else if (auto tensor_type = As<TensorType>(arg_type)) {
357- CHECK(!tensor_type->shape_.empty()) << "simt.launch Tensor argument must have a non-empty shape";378+ PRO_IR_CHECK(ExternalError::INVALID_SHAPE, !tensor_type->shape_.empty())
379+ << "simt.launch Tensor argument must have a non-empty shape";
358 for (const auto& dim : tensor_type->shape_) {380 for (const auto& dim : tensor_type->shape_) {
359- CHECK(As<ConstInt>(dim) != nullptr) << "simt.launch Tensor argument must have a static shape";381+ PRO_IR_CHECK(ExternalError::DYNAMIC_SHAPE_COMPUTE_UNSUPPORTED, As<ConstInt>(dim) != nullptr)
382+ << "simt.launch Tensor argument must have a static shape";
360 }383 }
361- CHECK(tensor_type->dtype_.GetBit() >= 8) << "simt.launch Tensor argument has a sub-byte element dtype";384+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, tensor_type->dtype_.GetBit() >= 8)
362- CHECK(tensor_type->tensor_view_.has_value() && tensor_type->tensor_view_->layout == TensorLayout::ND)385+ << "simt.launch Tensor argument has a sub-byte element dtype";
386+ PRO_IR_CHECK(ExternalError::INVALID_FORMAT,
387+ tensor_type->tensor_view_.has_value() && tensor_type->tensor_view_->layout == TensorLayout::ND)
363 << "simt.launch Tensor argument must use ND layout";388 << "simt.launch Tensor argument must use ND layout";
364- CHECK(As<Var>(args[i]) != nullptr) << "simt.launch Tensor argument must be a Var";389+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, As<Var>(args[i]) != nullptr)
390+ << "simt.launch Tensor argument must be a Var";
365 } else {391 } else {
366- CHECK(As<ScalarType>(arg_type)) << "simt.launch supports only Tile, Tensor, and scalar arguments";392+ PRO_IR_CHECK(ExternalError::NOT_IMPLEMENTED_ERROR, As<ScalarType>(arg_type))
393+ << "simt.launch supports only Tile, Tensor, and scalar arguments";
367 }394 }
368 }395 }
369 return GetUnknownType();396 return GetUnknownType();
@@ -18,9 +18,11 @@
18#include "ir/memref.h"18#include "ir/memref.h"
19#include "ir/op_registry.h"19#include "ir/op_registry.h"
20#include "ir/type.h"20#include "ir/type.h"
21+#include "pypto_pro/error.h"
21 22 
22namespace pypto {23namespace pypto {
23namespace ir {24namespace ir {
25+using npu::tile_fwk::ExternalError;
24 26 
25namespace {27namespace {
26 28 
@@ -71,61 +73,75 @@ TypePtr DeduceSyncAllType(const std::vector<ExprPtr>& args, const std::vector<st
71 // args[0] is an empty MakeTuple for hard mode73 // args[0] is an empty MakeTuple for hard mode
72 if (!args.empty()) {74 if (!args.empty()) {
73 auto tuple = As<MakeTuple>(args[0]);75 auto tuple = As<MakeTuple>(args[0]);
74- CHECK(!tuple || tuple->elements_.empty())76+ PRO_IR_CHECK(ExternalError::NOT_IMPLEMENTED_ERROR, !tuple || tuple->elements_.empty())
75 << "system.sync_all hard mode does not accept workspace arguments";77 << "system.sync_all hard mode does not accept workspace arguments";
76 }78 }
77 } else if (mode == 1) { // SOFT79 } else if (mode == 1) { // SOFT
78- CHECK(core_type == 0 || core_type == 1 || core_type == 2)80+ PRO_IR_CHECK(ExternalError::INVALID_ARGUMENT, core_type == 0 || core_type == 1 || core_type == 2)
79 << "system.sync_all soft mode core_type must be AIV_ONLY(0), AIC_ONLY(1), or MIX(2), got " << core_type;81 << "system.sync_all soft mode core_type must be AIV_ONLY(0), AIC_ONLY(1), or MIX(2), got " << core_type;
80- CHECK(args.size() == 1) << "system.sync_all soft mode requires exactly 1 argument (workspaces list), got "82+ PRO_IR_CHECK(ExternalError::INVALID_ARGUMENT, args.size() == 1)
81- << args.size();83+ << "system.sync_all soft mode requires exactly 1 argument (workspaces list), got " << args.size();
82 84 
83 // Unpack MakeTuple elements and classify by type85 // Unpack MakeTuple elements and classify by type
84 auto tuple = As<MakeTuple>(args[0]);86 auto tuple = As<MakeTuple>(args[0]);
85- CHECK(tuple) << "system.sync_all soft mode: workspaces argument must be a list/tuple";87+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, tuple)
88+ << "system.sync_all soft mode: workspaces argument must be a list/tuple";
86 89 
87 bool has_gm = false, has_ub = false, has_l1 = false, has_used_cores = false;90 bool has_gm = false, has_ub = false, has_l1 = false, has_used_cores = false;
88 for (const auto& elem : tuple->elements_) {91 for (const auto& elem : tuple->elements_) {
89 auto elem_type = elem->GetType();92 auto elem_type = elem->GetType();
90 if (As<TensorType>(elem_type)) {93 if (As<TensorType>(elem_type)) {
91- CHECK(!has_gm) << "system.sync_all: duplicate gm_workspace (TensorType) in workspaces list";94+ PRO_IR_CHECK(ExternalError::INVALID_OPERATION, !has_gm)
95+ << "system.sync_all: duplicate gm_workspace (TensorType) in workspaces list";
92 has_gm = true;96 has_gm = true;
93 } else if (auto tile_type = As<TileType>(elem_type)) {97 } else if (auto tile_type = As<TileType>(elem_type)) {
94- CHECK(tile_type->memref_.has_value()) << "system.sync_all: workspace tile must have memref";98+ PRO_IR_CHECK(ExternalError::INVALID_ARGUMENT, tile_type->memref_.has_value())
99+ << "system.sync_all: workspace tile must have memref";
95 auto space = tile_type->memref_.value()->memorySpace_;100 auto space = tile_type->memref_.value()->memorySpace_;
96 if (space == MemorySpace::Vec) {101 if (space == MemorySpace::Vec) {
97- CHECK(!has_ub) << "system.sync_all: duplicate ub_workspace (Vec TileType) in workspaces list";102+ PRO_IR_CHECK(ExternalError::INVALID_OPERATION, !has_ub)
103+ << "system.sync_all: duplicate ub_workspace (Vec TileType) in workspaces list";
98 has_ub = true;104 has_ub = true;
99 } else if (space == MemorySpace::Mat) {105 } else if (space == MemorySpace::Mat) {
100- CHECK(!has_l1) << "system.sync_all: duplicate l1_workspace (Mat TileType) in workspaces list";106+ PRO_IR_CHECK(ExternalError::INVALID_OPERATION, !has_l1)
107+ << "system.sync_all: duplicate l1_workspace (Mat TileType) in workspaces list";
101 has_l1 = true;108 has_l1 = true;
102 } else {109 } else {
103- CHECK(false) << "system.sync_all: workspace tile must be Vec or Mat, got "110+ PRO_IR_CHECK(ExternalError::INVALID_OPERATION, false)
104- << static_cast<int>(space);111+ << "system.sync_all: workspace tile must be Vec or Mat, got " << static_cast<int>(space);
105 }112 }
106 } else if (IsIntScalar(elem)) {113 } else if (IsIntScalar(elem)) {
107- CHECK(!has_used_cores) << "system.sync_all: duplicate used_cores (int scalar) in workspaces list";114+ PRO_IR_CHECK(ExternalError::INVALID_OPERATION, !has_used_cores)
115+ << "system.sync_all: duplicate used_cores (int scalar) in workspaces list";
108 has_used_cores = true;116 has_used_cores = true;
109 } else {117 } else {
110- CHECK(false) << "system.sync_all: unrecognized element type in workspaces list: "118+ PRO_IR_CHECK(ExternalError::INVALID_ARGUMENT, false)
111- << elem_type->TypeName();119+ << "system.sync_all: unrecognized element type in workspaces list: " << elem_type->TypeName();
112 }120 }
113 }121 }
114 122 
115 // Validate required workspaces per core_type123 // Validate required workspaces per core_type
116- CHECK(has_gm) << "system.sync_all soft mode: workspaces list must contain a gm_workspace (TensorType)";124+ PRO_IR_CHECK(ExternalError::INVALID_ARGUMENT, has_gm)
125+ << "system.sync_all soft mode: workspaces list must contain a gm_workspace (TensorType)";
117 if (core_type == 0) { // AIV_ONLY126 if (core_type == 0) { // AIV_ONLY
118- CHECK(has_ub) << "system.sync_all soft aiv_only: workspaces list must contain ub_workspace (Vec TileType)";127+ PRO_IR_CHECK(ExternalError::INVALID_ARGUMENT, has_ub)
119- CHECK(!has_l1) << "system.sync_all soft aiv_only: l1_workspace (Mat TileType) is not allowed";128+ << "system.sync_all soft aiv_only: workspaces list must contain ub_workspace (Vec TileType)";
129+ PRO_IR_CHECK(ExternalError::NOT_IMPLEMENTED_ERROR, !has_l1)
130+ << "system.sync_all soft aiv_only: l1_workspace (Mat TileType) is not allowed";
120 } else if (core_type == 1) { // AIC_ONLY131 } else if (core_type == 1) { // AIC_ONLY
121- CHECK(has_l1) << "system.sync_all soft aic_only: workspaces list must contain l1_workspace (Mat TileType)";132+ PRO_IR_CHECK(ExternalError::INVALID_ARGUMENT, has_l1)
122- CHECK(!has_ub) << "system.sync_all soft aic_only: ub_workspace (Vec TileType) is not allowed";133+ << "system.sync_all soft aic_only: workspaces list must contain l1_workspace (Mat TileType)";
134+ PRO_IR_CHECK(ExternalError::NOT_IMPLEMENTED_ERROR, !has_ub)
135+ << "system.sync_all soft aic_only: ub_workspace (Vec TileType) is not allowed";
123 } else { // MIX136 } else { // MIX
124- CHECK(has_ub) << "system.sync_all soft mix: workspaces list must contain ub_workspace (Vec TileType)";137+ PRO_IR_CHECK(ExternalError::INVALID_ARGUMENT, has_ub)
125- CHECK(has_l1) << "system.sync_all soft mix: workspaces list must contain l1_workspace (Mat TileType)";138+ << "system.sync_all soft mix: workspaces list must contain ub_workspace (Vec TileType)";
139+ PRO_IR_CHECK(ExternalError::INVALID_ARGUMENT, has_l1)
140+ << "system.sync_all soft mix: workspaces list must contain l1_workspace (Mat TileType)";
126 }141 }
127 } else {142 } else {
128- CHECK(false) << "system.sync_all: mode must be HARD(0) or SOFT(1), got " << mode;143+ PRO_IR_CHECK(ExternalError::INVALID_ARGUMENT, false)
144+ << "system.sync_all: mode must be HARD(0) or SOFT(1), got " << mode;
129 }145 }
130 146 
131 return GetUnknownType();147 return GetUnknownType();
@@ -273,20 +289,21 @@ REGISTER_OP("system.dcci")
273 .set_attr<int>("dst")289 .set_attr<int>("dst")
274 .f_deduce_type([](const std::vector<ExprPtr>& args, const std::vector<std::pair<std::string, std::any>>& kwargs) {290 .f_deduce_type([](const std::vector<ExprPtr>& args, const std::vector<std::pair<std::string, std::any>>& kwargs) {
275 (void)kwargs;291 (void)kwargs;
276- CHECK(args.size() == 1 || args.size() == 2) << "system.dcci requires 1 or 2 arguments, got " << args.size();292+ PRO_IR_CHECK(ExternalError::INVALID_ARGUMENT, args.size() == 1 || args.size() == 2)
293+ << "system.dcci requires 1 or 2 arguments, got " << args.size();
277 auto target_type = args[0]->GetType();294 auto target_type = args[0]->GetType();
278- CHECK(As<TensorType>(target_type) || As<TileType>(target_type))295+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, As<TensorType>(target_type) || As<TileType>(target_type))
279 << "system.dcci: target must be TensorType or TileType, but got " << target_type->TypeName();296 << "system.dcci: target must be TensorType or TileType, but got " << target_type->TypeName();
280 if (As<TensorType>(target_type) && args.size() == 2) {297 if (As<TensorType>(target_type) && args.size() == 2) {
281- CHECK(IsDcciTensorOffset(args[1]))298+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, IsDcciTensorOffset(args[1]))
282 << "system.dcci: tensor target offset must be a per-dimension list/tuple "299 << "system.dcci: tensor target offset must be a per-dimension list/tuple "
283 << "or a scalar integer element offset";300 << "or a scalar integer element offset";
284 }301 }
285 if (As<TileType>(target_type) && args.size() == 2) {302 if (As<TileType>(target_type) && args.size() == 2) {
286- CHECK(IsIntScalar(args[1]))303+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, IsIntScalar(args[1]))
287 << "system.dcci: tile target offset must be a scalar integer element offset (int or index Expr).\n"304 << "system.dcci: tile target offset must be a scalar integer element offset (int or index Expr).\n"
288- << " Example: dcci(tile, 0) - cache invalidation starting at element offset 0\n"305+ << " Example: dcci(tile, 0) - cache invalidation starting at element offset 0\n"
289- << " Note: Use list/tuple offset only for tensor targets";306+ << " Note: Use list/tuple offset only for tensor targets";
290 }307 }
291 return GetUnknownType();308 return GetUnknownType();
292 });309 });
@@ -27,33 +27,39 @@
27#include "ir/op_registry.h"27#include "ir/op_registry.h"
28#include "ir/type.h"28#include "ir/type.h"
29#include "ir/type_inference.h"29#include "ir/type_inference.h"
30+#include "pypto_pro/error.h"
30 31 
31namespace pypto {32namespace pypto {
32namespace ir {33namespace ir {
34+using npu::tile_fwk::ExternalError;
33 35 
34TypePtr DeduceTensorOpElementwiseBinaryType(36TypePtr DeduceTensorOpElementwiseBinaryType(
35 [[maybe_unused]] const std::vector<ExprPtr>& args,37 [[maybe_unused]] const std::vector<ExprPtr>& args,
36 [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs, const std::string& op_name)38 [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs, const std::string& op_name)
37{39{
38- CHECK(args.size() == 0x2) << "The operator " << op_name << " requires exactly 2 arguments, but got " << args.size();40+ PRO_IR_CHECK(ExternalError::INVALID_ARGUMENT, args.size() == 0x2)
41+ << "The operator " << op_name << " requires exactly 2 arguments, but got " << args.size();
39 42 
40 // Try TensorType first43 // Try TensorType first
41 auto tensor_type1 = As<TensorType>(args[0]->GetType());44 auto tensor_type1 = As<TensorType>(args[0]->GetType());
42 auto tensor_type2 = As<TensorType>(args[1]->GetType());45 auto tensor_type2 = As<TensorType>(args[1]->GetType());
43 46 
44- CHECK(tensor_type1) << "The operator " << op_name << " requires first argument to be a TensorType, but got "47+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, tensor_type1)
45- << args[0]->GetType()->TypeName();48+ << "The operator " << op_name << " requires first argument to be a TensorType, but got "
46- CHECK(tensor_type2) << "The operator " << op_name << " requires second argument to be a TensorType, but got "49+ << args[0]->GetType()->TypeName();
47- << args[1]->GetType()->TypeName();50+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, tensor_type2)
51+ << "The operator " << op_name << " requires second argument to be a TensorType, but got "
52+ << args[1]->GetType()->TypeName();
48 53 
49 auto result_dtype = PromoteDataTypes(tensor_type1->dtype_, tensor_type2->dtype_);54 auto result_dtype = PromoteDataTypes(tensor_type1->dtype_, tensor_type2->dtype_);
50- CHECK(result_dtype) << "The operator " << op_name << " requires compatible data types, but got "55+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, result_dtype)
51- << args[0]->GetType()->TypeName() << " and " << args[1]->GetType()->TypeName();56+ << "The operator " << op_name << " requires compatible data types, but got " << args[0]->GetType()->TypeName()
57+ << " and " << args[1]->GetType()->TypeName();
52 58 
53 auto broadcast_result = BroadcastShapes(tensor_type1->shape_, tensor_type2->shape_);59 auto broadcast_result = BroadcastShapes(tensor_type1->shape_, tensor_type2->shape_);
54- CHECK(broadcast_result.success) << "The operator " << op_name << " requires compatible shapes, but got "60+ PRO_IR_CHECK(ExternalError::INVALID_SHAPE, broadcast_result.success)
55- << FormatShape(tensor_type1->shape_) << " and "61+ << "The operator " << op_name << " requires compatible shapes, but got " << FormatShape(tensor_type1->shape_)
56- << FormatShape(tensor_type2->shape_);62+ << " and " << FormatShape(tensor_type2->shape_);
57 63 
58 return std::make_shared<TensorType>(broadcast_result.shape, *result_dtype);64 return std::make_shared<TensorType>(broadcast_result.shape, *result_dtype);
59}65}
@@ -62,20 +68,24 @@ TypePtr DeduceTensorOpElementwiseScalarType(
62 [[maybe_unused]] const std::vector<ExprPtr>& args,68 [[maybe_unused]] const std::vector<ExprPtr>& args,
63 [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs, const std::string& op_name)69 [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs, const std::string& op_name)
64{70{
65- CHECK(args.size() == 0x2) << "The operator " << op_name << " requires exactly 2 arguments, but got " << args.size();71+ PRO_IR_CHECK(ExternalError::INVALID_ARGUMENT, args.size() == 0x2)
72+ << "The operator " << op_name << " requires exactly 2 arguments, but got " << args.size();
66 73 
67 auto tensor_type1 = As<TensorType>(args[0]->GetType());74 auto tensor_type1 = As<TensorType>(args[0]->GetType());
68 auto scalar_type2 = As<ScalarType>(args[1]->GetType());75 auto scalar_type2 = As<ScalarType>(args[1]->GetType());
69 76 
70- CHECK(tensor_type1) << "The operator " << op_name << " requires first argument to be a TensorType, but got "77+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, tensor_type1)
71- << args[0]->GetType()->TypeName();78+ << "The operator " << op_name << " requires first argument to be a TensorType, but got "
72- CHECK(scalar_type2) << "The operator " << op_name << " requires second argument to be a ScalarType, but got "79+ << args[0]->GetType()->TypeName();
73- << args[1]->GetType()->TypeName();80+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, scalar_type2)
81+ << "The operator " << op_name << " requires second argument to be a ScalarType, but got "
82+ << args[1]->GetType()->TypeName();
74 83 
75 // TensorType + ScalarType - result is TensorType with same shape as first argument84 // TensorType + ScalarType - result is TensorType with same shape as first argument
76 auto result_dtype = PromoteDataTypes(tensor_type1->dtype_, scalar_type2->dtype_);85 auto result_dtype = PromoteDataTypes(tensor_type1->dtype_, scalar_type2->dtype_);
77- CHECK(result_dtype) << "The operator " << op_name << " requires compatible data types, but got "86+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, result_dtype)
78- << args[0]->GetType()->TypeName() << " and " << args[1]->GetType()->TypeName();87+ << "The operator " << op_name << " requires compatible data types, but got " << args[0]->GetType()->TypeName()
88+ << " and " << args[1]->GetType()->TypeName();
79 89 
80 return std::make_shared<TensorType>(tensor_type1->shape_, *result_dtype);90 return std::make_shared<TensorType>(tensor_type1->shape_, *result_dtype);
81}91}
@@ -28,6 +28,7 @@
28#include "core/dtype.h"28#include "core/dtype.h"
29#include "core/error.h"29#include "core/error.h"
30#include "core/logging.h"30#include "core/logging.h"
31+#include "pypto_pro/error.h"
31#include "ir/kind_traits.h"32#include "ir/kind_traits.h"
32#include "ir/op_registry.h"33#include "ir/op_registry.h"
33#include "ir/type.h"34#include "ir/type.h"
@@ -35,6 +36,7 @@
35 36 
36namespace pypto {37namespace pypto {
37namespace ir {38namespace ir {
39+using npu::tile_fwk::ExternalError;
38 40 
39// Helper to get kwargs value with default (uses vector to preserve order)41// Helper to get kwargs value with default (uses vector to preserve order)
40template <typename T>42template <typename T>
@@ -49,30 +51,33 @@ T GetKwarg([[maybe_unused]] const std::vector<std::pair<std::string, std::any>>&
49 if (default_value) {51 if (default_value) {
50 return *default_value;52 return *default_value;
51 }53 }
52- throw ValueError("Missing kwarg: " + key);54+ PRO_IR_THROW(::pypto::ir::ValueError, ExternalError::INVALID_ARGUMENT) << "Missing kwarg: " << key;
53}55}
54 56 
55TypePtr DeduceTensorMatMulType([[maybe_unused]] const std::vector<ExprPtr>& args,57TypePtr DeduceTensorMatMulType([[maybe_unused]] const std::vector<ExprPtr>& args,
56 [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs)58 [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs)
57{59{
58 // tensor.matmul requires exactly 2 Expr arguments (lhs, rhs)60 // tensor.matmul requires exactly 2 Expr arguments (lhs, rhs)
59- CHECK(args.size() == 0x2) << "tensor.matmul requires exactly 2 arguments (lhs, rhs), but got " << args.size();61+ PRO_IR_CHECK(ExternalError::INVALID_ARGUMENT, args.size() == 0x2)
62+ << "tensor.matmul requires exactly 2 arguments (lhs, rhs), but got " << args.size();
60 63 
61 // First two arguments must be TensorType64 // First two arguments must be TensorType
62 auto lhs_type = As<TensorType>(args[0]->GetType());65 auto lhs_type = As<TensorType>(args[0]->GetType());
63 auto rhs_type = As<TensorType>(args[1]->GetType());66 auto rhs_type = As<TensorType>(args[1]->GetType());
64 67 
65- CHECK(lhs_type) << "tensor.matmul requires first argument to be a TensorType, but got "68+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, lhs_type)
66- << args[0]->GetType()->TypeName();69+ << "tensor.matmul requires first argument to be a TensorType, but got " << args[0]->GetType()->TypeName();
67- CHECK(rhs_type) << "tensor.matmul requires second argument to be a TensorType, but got "70+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, rhs_type)
68- << args[1]->GetType()->TypeName();71+ << "tensor.matmul requires second argument to be a TensorType, but got " << args[1]->GetType()->TypeName();
69 72 
70 // Extract shapes73 // Extract shapes
71 const auto& lhs_shape = lhs_type->shape_;74 const auto& lhs_shape = lhs_type->shape_;
72 const auto& rhs_shape = rhs_type->shape_;75 const auto& rhs_shape = rhs_type->shape_;
73 76 
74- CHECK(lhs_shape.size() >= 1) << "tensor.matmul requires lhs to have at least 1 dimension";77+ PRO_IR_CHECK(ExternalError::INVALID_SHAPE, lhs_shape.size() >= 1)
75- CHECK(rhs_shape.size() >= 1) << "tensor.matmul requires rhs to have at least 1 dimension";78+ << "tensor.matmul requires lhs to have at least 1 dimension";
79+ PRO_IR_CHECK(ExternalError::INVALID_SHAPE, rhs_shape.size() >= 1)
80+ << "tensor.matmul requires rhs to have at least 1 dimension";
76 81 
77 // Read kwargs (with defaults)82 // Read kwargs (with defaults)
78 DataType out_dtype;83 DataType out_dtype;
@@ -80,10 +85,10 @@ TypePtr DeduceTensorMatMulType([[maybe_unused]] const std::vector<ExprPtr>& args
80 out_dtype = GetKwarg<DataType>(kwargs, "out_dtype");85 out_dtype = GetKwarg<DataType>(kwargs, "out_dtype");
81 } catch (const ValueError& e) {86 } catch (const ValueError& e) {
82 auto promoted = PromoteDataTypes(lhs_type->dtype_, rhs_type->dtype_);87 auto promoted = PromoteDataTypes(lhs_type->dtype_, rhs_type->dtype_);
83- CHECK(promoted) << "Cannot promote data types for tensor.matmul";88+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, promoted) << "Cannot promote data types for tensor.matmul";
84 out_dtype = *promoted;89 out_dtype = *promoted;
85 } catch (const TypeError& e) {90 } catch (const TypeError& e) {
86- CHECK(false) << "Invalid kwarg type for out_dtype: " << e.what();91+ PRO_IR_CHECK(ExternalError::INVALID_ARGUMENT, false) << "Invalid kwarg type for out_dtype: " << e.what();
87 out_dtype = lhs_type->dtype_;92 out_dtype = lhs_type->dtype_;
88 }93 }
89 94 
@@ -117,7 +122,7 @@ TypePtr DeduceTensorMatMulType([[maybe_unused]] const std::vector<ExprPtr>& args
117 size_t rhs_ndim = rhs_shape.size();122 size_t rhs_ndim = rhs_shape.size();
118 123 
119 // Ensure both tensors have at least 2 dimensions for batched matmul124 // Ensure both tensors have at least 2 dimensions for batched matmul
120- CHECK(lhs_ndim >= 0x2 && rhs_ndim >= 0x2)125+ PRO_IR_CHECK(ExternalError::INVALID_SHAPE, lhs_ndim >= 0x2 && rhs_ndim >= 0x2)
121 << "tensor.matmul requires both tensors to have at least 2 dimensions "126 << "tensor.matmul requires both tensors to have at least 2 dimensions "
122 << "for batched matmul, but got lhs shape size " << lhs_ndim << " and rhs shape size " << rhs_ndim;127 << "for batched matmul, but got lhs shape size " << lhs_ndim << " and rhs shape size " << rhs_ndim;
123 128 
@@ -127,7 +132,8 @@ TypePtr DeduceTensorMatMulType([[maybe_unused]] const std::vector<ExprPtr>& args
127 132 
128 // Broadcast batch dimensions133 // Broadcast batch dimensions
129 auto broadcast_result = BroadcastShapes(lhs_batch, rhs_batch);134 auto broadcast_result = BroadcastShapes(lhs_batch, rhs_batch);
130- CHECK(broadcast_result.success) << "Cannot broadcast batch dimensions for tensor.matmul";135+ PRO_IR_CHECK(ExternalError::INVALID_SHAPE, broadcast_result.success)
136+ << "Cannot broadcast batch dimensions for tensor.matmul";
131 137 
132 output_shape = broadcast_result.shape;138 output_shape = broadcast_result.shape;
133 139 
@@ -32,16 +32,19 @@
32#include "ir/op_registry.h"32#include "ir/op_registry.h"
33#include "ir/scalar_expr.h"33#include "ir/scalar_expr.h"
34#include "ir/type.h"34#include "ir/type.h"
35+#include "pypto_pro/error.h"
35 36 
36namespace pypto {37namespace pypto {
37namespace ir {38namespace ir {
39+using npu::tile_fwk::ExternalError;
38 40 
39TypePtr DeduceTensorCreateType([[maybe_unused]] const std::vector<ExprPtr>& args,41TypePtr DeduceTensorCreateType([[maybe_unused]] const std::vector<ExprPtr>& args,
40 [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs)42 [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs)
41{43{
42 // tensor.create: shape is a single TupleType argument44 // tensor.create: shape is a single TupleType argument
43 // dtype comes from kwargs45 // dtype comes from kwargs
44- CHECK(args.size() == 1) << "tensor.create requires exactly 1 argument (shape tuple), but got " << args.size();46+ PRO_IR_CHECK(ExternalError::INVALID_ARGUMENT, args.size() == 1)
47+ << "tensor.create requires exactly 1 argument (shape tuple), but got " << args.size();
45 48 
46 // Extract dtype from kwargs49 // Extract dtype from kwargs
47 bool found_dtype = false;50 bool found_dtype = false;
@@ -53,20 +56,22 @@ TypePtr DeduceTensorCreateType([[maybe_unused]] const std::vector<ExprPtr>& args
53 break;56 break;
54 }57 }
55 }58 }
56- CHECK(found_dtype) << "tensor.create requires 'dtype' kwarg";59+ PRO_IR_CHECK(ExternalError::INVALID_ARGUMENT, found_dtype) << "tensor.create requires 'dtype' kwarg";
57 60 
58 // First argument must be TupleType (shape)61 // First argument must be TupleType (shape)
59 auto shape_tuple_type = As<TupleType>(args[0]->GetType());62 auto shape_tuple_type = As<TupleType>(args[0]->GetType());
60- CHECK(shape_tuple_type) << "tensor.create requires shape to be TupleType, but got "63+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, shape_tuple_type)
61- << args[0]->GetType()->TypeName();64+ << "tensor.create requires shape to be TupleType, but got " << args[0]->GetType()->TypeName();
62 65 
63 // Validate all shape elements are ScalarType with integer dtype66 // Validate all shape elements are ScalarType with integer dtype
64 for (size_t i = 0; i < shape_tuple_type->types_.size(); ++i) {67 for (size_t i = 0; i < shape_tuple_type->types_.size(); ++i) {
65 auto scalar_type = As<ScalarType>(shape_tuple_type->types_[i]);68 auto scalar_type = As<ScalarType>(shape_tuple_type->types_[i]);
66- CHECK(scalar_type) << "tensor.create shape tuple element " << i << " must be ScalarType, but got "69+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, scalar_type)
67- << shape_tuple_type->types_[i]->TypeName();70+ << "tensor.create shape tuple element " << i << " must be ScalarType, but got "
68- CHECK(scalar_type->dtype_.IsInt()) << "tensor.create shape tuple element " << i71+ << shape_tuple_type->types_[i]->TypeName();
69- << " must have integer dtype, but got " << scalar_type->dtype_.ToString();72+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, scalar_type->dtype_.IsInt())
73+ << "tensor.create shape tuple element " << i << " must have integer dtype, but got "
74+ << scalar_type->dtype_.ToString();
70 }75 }
71 76 
72 // Extract shape dimensions77 // Extract shape dimensions
@@ -93,39 +98,44 @@ TypePtr DeduceTensorViewType([[maybe_unused]] const std::vector<ExprPtr>& args,
93 [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs)98 [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs)
94{99{
95 // tensor.view requires exactly 3 arguments: input tensor, shape tuple, and offset tuple100 // tensor.view requires exactly 3 arguments: input tensor, shape tuple, and offset tuple
96- CHECK(args.size() == 3) << "tensor.view requires exactly 3 arguments (input, shape, offset), but got "101+ PRO_IR_CHECK(ExternalError::INVALID_ARGUMENT, args.size() == 3)
97- << args.size();102+ << "tensor.view requires exactly 3 arguments (input, shape, offset), but got " << args.size();
98 103 
99 // First argument must be TensorType104 // First argument must be TensorType
100 auto tensor_type = As<TensorType>(args[0]->GetType());105 auto tensor_type = As<TensorType>(args[0]->GetType());
101- CHECK(tensor_type) << "tensor.view requires first argument to be a TensorType, but got "106+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, tensor_type)
102- << args[0]->GetType()->TypeName();107+ << "tensor.view requires first argument to be a TensorType, but got " << args[0]->GetType()->TypeName();
103 108 
104 // Second argument must be TupleType (shape)109 // Second argument must be TupleType (shape)
105 auto shape_tuple_type = As<TupleType>(args[1]->GetType());110 auto shape_tuple_type = As<TupleType>(args[1]->GetType());
106- CHECK(shape_tuple_type) << "tensor.view requires shape to be TupleType, but got " << args[1]->GetType()->TypeName();111+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, shape_tuple_type)
112+ << "tensor.view requires shape to be TupleType, but got " << args[1]->GetType()->TypeName();
107 113 
108 // Validate all shape elements are ScalarType with integer dtype114 // Validate all shape elements are ScalarType with integer dtype
109 for (size_t i = 0; i < shape_tuple_type->types_.size(); ++i) {115 for (size_t i = 0; i < shape_tuple_type->types_.size(); ++i) {
110 auto scalar_type = As<ScalarType>(shape_tuple_type->types_[i]);116 auto scalar_type = As<ScalarType>(shape_tuple_type->types_[i]);
111- CHECK(scalar_type) << "tensor.view shape tuple element " << i << " must be ScalarType, but got "117+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, scalar_type)
112- << shape_tuple_type->types_[i]->TypeName();118+ << "tensor.view shape tuple element " << i << " must be ScalarType, but got "
113- CHECK(scalar_type->dtype_.IsInt()) << "tensor.view shape tuple element " << i119+ << shape_tuple_type->types_[i]->TypeName();
114- << " must have integer dtype, but got " << scalar_type->dtype_.ToString();120+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, scalar_type->dtype_.IsInt())
121+ << "tensor.view shape tuple element " << i << " must have integer dtype, but got "
122+ << scalar_type->dtype_.ToString();
115 }123 }
116 124 
117 // Third argument must be TupleType (offset)125 // Third argument must be TupleType (offset)
118 auto offset_tuple_type = As<TupleType>(args[2]->GetType());126 auto offset_tuple_type = As<TupleType>(args[2]->GetType());
119- CHECK(offset_tuple_type) << "tensor.view requires offset to be TupleType, but got "127+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, offset_tuple_type)
120- << args[2]->GetType()->TypeName();128+ << "tensor.view requires offset to be TupleType, but got " << args[2]->GetType()->TypeName();
121 129 
122 // Validate all offset elements are ScalarType with integer dtype130 // Validate all offset elements are ScalarType with integer dtype
123 for (size_t i = 0; i < offset_tuple_type->types_.size(); ++i) {131 for (size_t i = 0; i < offset_tuple_type->types_.size(); ++i) {
124 auto scalar_type = As<ScalarType>(offset_tuple_type->types_[i]);132 auto scalar_type = As<ScalarType>(offset_tuple_type->types_[i]);
125- CHECK(scalar_type) << "tensor.view offset tuple element " << i << " must be ScalarType, but got "133+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, scalar_type)
126- << offset_tuple_type->types_[i]->TypeName();134+ << "tensor.view offset tuple element " << i << " must be ScalarType, but got "
127- CHECK(scalar_type->dtype_.IsInt()) << "tensor.view offset tuple element " << i135+ << offset_tuple_type->types_[i]->TypeName();
128- << " must have integer dtype, but got " << scalar_type->dtype_.ToString();136+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, scalar_type->dtype_.IsInt())
137+ << "tensor.view offset tuple element " << i << " must have integer dtype, but got "
138+ << scalar_type->dtype_.ToString();
129 }139 }
130 140 
131 // Extract shape dimensions141 // Extract shape dimensions
@@ -153,31 +163,33 @@ TypePtr DeduceTensorAssembleType([[maybe_unused]] const std::vector<ExprPtr>& ar
153 [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs)163 [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs)
154{164{
155 // tensor.assemble requires exactly 3 arguments: target, source, and offset tuple165 // tensor.assemble requires exactly 3 arguments: target, source, and offset tuple
156- CHECK(args.size() == 3) << "tensor.assemble requires exactly 3 arguments (target, source, offset), but got "166+ PRO_IR_CHECK(ExternalError::INVALID_ARGUMENT, args.size() == 3)
157- << args.size();167+ << "tensor.assemble requires exactly 3 arguments (target, source, offset), but got " << args.size();
158 168 
159 // First argument (target) must be TensorType169 // First argument (target) must be TensorType
160 auto target_type = As<TensorType>(args[0]->GetType());170 auto target_type = As<TensorType>(args[0]->GetType());
161- CHECK(target_type) << "tensor.assemble requires first argument to be a TensorType, but got "171+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, target_type)
162- << args[0]->GetType()->TypeName();172+ << "tensor.assemble requires first argument to be a TensorType, but got " << args[0]->GetType()->TypeName();
163 173 
164 // Second argument (source) must be TensorType174 // Second argument (source) must be TensorType
165 auto source_type = As<TensorType>(args[1]->GetType());175 auto source_type = As<TensorType>(args[1]->GetType());
166- CHECK(source_type) << "tensor.assemble requires second argument to be a TensorType, but got "176+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, source_type)
167- << args[1]->GetType()->TypeName();177+ << "tensor.assemble requires second argument to be a TensorType, but got " << args[1]->GetType()->TypeName();
168 178 
169 // Third argument must be TupleType (offset)179 // Third argument must be TupleType (offset)
170 auto offset_tuple_type = As<TupleType>(args[2]->GetType());180 auto offset_tuple_type = As<TupleType>(args[2]->GetType());
171- CHECK(offset_tuple_type) << "tensor.assemble requires offset to be TupleType, but got "181+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, offset_tuple_type)
172- << args[2]->GetType()->TypeName();182+ << "tensor.assemble requires offset to be TupleType, but got " << args[2]->GetType()->TypeName();
173 183 
174 // Validate all offset elements are ScalarType with integer dtype184 // Validate all offset elements are ScalarType with integer dtype
175 for (size_t i = 0; i < offset_tuple_type->types_.size(); ++i) {185 for (size_t i = 0; i < offset_tuple_type->types_.size(); ++i) {
176 auto scalar_type = As<ScalarType>(offset_tuple_type->types_[i]);186 auto scalar_type = As<ScalarType>(offset_tuple_type->types_[i]);
177- CHECK(scalar_type) << "tensor.assemble offset tuple element " << i << " must be ScalarType, but got "187+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, scalar_type)
178- << offset_tuple_type->types_[i]->TypeName();188+ << "tensor.assemble offset tuple element " << i << " must be ScalarType, but got "
179- CHECK(scalar_type->dtype_.IsInt()) << "tensor.assemble offset tuple element " << i189+ << offset_tuple_type->types_[i]->TypeName();
180- << " must have integer dtype, but got " << scalar_type->dtype_.ToString();190+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, scalar_type->dtype_.IsInt())
191+ << "tensor.assemble offset tuple element " << i << " must have integer dtype, but got "
192+ << scalar_type->dtype_.ToString();
181 }193 }
182 194 
183 // Assemble returns a new TensorType with the same shape and dtype as target195 // Assemble returns a new TensorType with the same shape and dtype as target
@@ -31,21 +31,25 @@
31#include "ir/span.h"31#include "ir/span.h"
32#include "ir/type.h"32#include "ir/type.h"
33#include "ir/type_inference.h"33#include "ir/type_inference.h"
34+#include "pypto_pro/error.h"
34 35 
35namespace pypto {36namespace pypto {
36namespace ir {37namespace ir {
38+using npu::tile_fwk::ExternalError;
37 39 
38TypePtr DeduceTensorReductionType([[maybe_unused]] const std::vector<ExprPtr>& args,40TypePtr DeduceTensorReductionType([[maybe_unused]] const std::vector<ExprPtr>& args,
39 [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs,41 [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs,
40 const std::string& op_name)42 const std::string& op_name)
41{43{
42 // Reduction operations require exactly 1 argument (input tensor)44 // Reduction operations require exactly 1 argument (input tensor)
43- CHECK(args.size() == 1) << "The operator " << op_name << " requires exactly 1 argument, but got " << args.size();45+ PRO_IR_CHECK(ExternalError::INVALID_ARGUMENT, args.size() == 1)
46+ << "The operator " << op_name << " requires exactly 1 argument, but got " << args.size();
44 47 
45 // First argument must be TensorType48 // First argument must be TensorType
46 auto tensor_type = As<TensorType>(args[0]->GetType());49 auto tensor_type = As<TensorType>(args[0]->GetType());
47- CHECK(tensor_type) << "The operator " << op_name << " requires first argument to be a TensorType, but got "50+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, tensor_type)
48- << args[0]->GetType()->TypeName();51+ << "The operator " << op_name << " requires first argument to be a TensorType, but got "
52+ << args[0]->GetType()->TypeName();
49 53 
50 const auto& input_shape = tensor_type->shape_;54 const auto& input_shape = tensor_type->shape_;
51 int64_t input_ndim = static_cast<int64_t>(input_shape.size());55 int64_t input_ndim = static_cast<int64_t>(input_shape.size());
@@ -56,7 +60,7 @@ TypePtr DeduceTensorReductionType([[maybe_unused]] const std::vector<ExprPtr>& a
56 if (axis < 0) {60 if (axis < 0) {
57 axis = static_cast<int>(input_ndim) + axis;61 axis = static_cast<int>(input_ndim) + axis;
58 }62 }
59- CHECK(axis >= 0 && static_cast<int64_t>(axis) < input_ndim)63+ PRO_IR_CHECK(ExternalError::INVALID_SHAPE, axis >= 0 && static_cast<int64_t>(axis) < input_ndim)
60 << "The operator " << op_name << " axis " << axis << " is out of range for shape with " << input_ndim64 << "The operator " << op_name << " axis " << axis << " is out of range for shape with " << input_ndim
61 << " dimensions";65 << " dimensions";
62 66 
@@ -32,9 +32,11 @@
32#include "ir/scalar_expr.h"32#include "ir/scalar_expr.h"
33#include "ir/type.h"33#include "ir/type.h"
34#include "ir/type_inference.h"34#include "ir/type_inference.h"
35+#include "pypto_pro/error.h"
35 36 
36namespace pypto {37namespace pypto {
37namespace ir {38namespace ir {
39+using npu::tile_fwk::ExternalError;
38 40 
39namespace {41namespace {
40// ============================================================================42// ============================================================================
@@ -53,7 +55,7 @@ int NormalizeAxis(int axis, size_t ndim)
53 if (axis < 0) {55 if (axis < 0) {
54 axis += static_cast<int>(ndim);56 axis += static_cast<int>(ndim);
55 }57 }
56- CHECK(axis >= 0 && axis < static_cast<int>(ndim))58+ PRO_IR_CHECK(ExternalError::INVALID_SHAPE, axis >= 0 && axis < static_cast<int>(ndim))
57 << "Axis " << axis << " is out of range for " << ndim << "D tensor";59 << "Axis " << axis << " is out of range for " << ndim << "D tensor";
58 return axis;60 return axis;
59}61}
@@ -68,25 +70,28 @@ TypePtr DeduceTensorReshapeType([[maybe_unused]] const std::vector<ExprPtr>& arg
68 [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs)70 [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs)
69{71{
70 // tensor.reshape requires exactly 2 arguments: input tensor and shape tuple72 // tensor.reshape requires exactly 2 arguments: input tensor and shape tuple
71- CHECK(args.size() == 2) << "tensor.reshape requires exactly 2 arguments (input, shape), but got " << args.size();73+ PRO_IR_CHECK(ExternalError::INVALID_ARGUMENT, args.size() == 2)
74+ << "tensor.reshape requires exactly 2 arguments (input, shape), but got " << args.size();
72 75 
73 // First argument must be TensorType76 // First argument must be TensorType
74 auto tensor_type = As<TensorType>(args[0]->GetType());77 auto tensor_type = As<TensorType>(args[0]->GetType());
75- CHECK(tensor_type) << "tensor.reshape requires first argument to be a TensorType, but got "78+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, tensor_type)
76- << args[0]->GetType()->TypeName();79+ << "tensor.reshape requires first argument to be a TensorType, but got " << args[0]->GetType()->TypeName();
77 80 
78 // Second argument must be TupleType (shape)81 // Second argument must be TupleType (shape)
79 auto shape_tuple_type = As<TupleType>(args[1]->GetType());82 auto shape_tuple_type = As<TupleType>(args[1]->GetType());
80- CHECK(shape_tuple_type) << "tensor.reshape requires shape to be TupleType, but got "83+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, shape_tuple_type)
81- << args[1]->GetType()->TypeName();84+ << "tensor.reshape requires shape to be TupleType, but got " << args[1]->GetType()->TypeName();
82 85 
83 // Validate all shape elements are ScalarType with integer dtype86 // Validate all shape elements are ScalarType with integer dtype
84 for (size_t i = 0; i < shape_tuple_type->types_.size(); ++i) {87 for (size_t i = 0; i < shape_tuple_type->types_.size(); ++i) {
85 auto scalar_type = As<ScalarType>(shape_tuple_type->types_[i]);88 auto scalar_type = As<ScalarType>(shape_tuple_type->types_[i]);
86- CHECK(scalar_type) << "tensor.reshape shape tuple element " << i << " must be ScalarType, but got "89+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, scalar_type)
87- << shape_tuple_type->types_[i]->TypeName();90+ << "tensor.reshape shape tuple element " << i << " must be ScalarType, but got "
88- CHECK(scalar_type->dtype_.IsInt()) << "tensor.reshape shape tuple element " << i91+ << shape_tuple_type->types_[i]->TypeName();
89- << " must have integer dtype, but got " << scalar_type->dtype_.ToString();92+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, scalar_type->dtype_.IsInt())
93+ << "tensor.reshape shape tuple element " << i << " must have integer dtype, but got "
94+ << scalar_type->dtype_.ToString();
90 }95 }
91 96 
92 // Extract new shape dimensions97 // Extract new shape dimensions
@@ -110,8 +115,9 @@ TypePtr DeduceTensorReshapeType([[maybe_unused]] const std::vector<ExprPtr>& arg
110 int64_t old_product = ComputeStaticShapeProduct(tensor_type->shape_);115 int64_t old_product = ComputeStaticShapeProduct(tensor_type->shape_);
111 int64_t new_product = ComputeStaticShapeProduct(new_shape);116 int64_t new_product = ComputeStaticShapeProduct(new_shape);
112 if (old_product > 0 && new_product > 0) {117 if (old_product > 0 && new_product > 0) {
113- CHECK(old_product == new_product) << "tensor.reshape: cannot reshape tensor of size " << old_product118+ PRO_IR_CHECK(ExternalError::INVALID_SHAPE, old_product == new_product)
114- << " into shape with size " << new_product;119+ << "tensor.reshape: cannot reshape tensor of size " << old_product << " into shape with size "
120+ << new_product;
115 }121 }
116 122 
117 // Return new TensorType with reshaped dimensions and same dtype123 // Return new TensorType with reshaped dimensions and same dtype
@@ -122,32 +128,35 @@ TypePtr DeduceTensorTransposeType([[maybe_unused]] const std::vector<ExprPtr>& a
122 [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs)128 [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs)
123{129{
124 // tensor.transpose requires exactly 3 arguments: input tensor, axis1, axis2130 // tensor.transpose requires exactly 3 arguments: input tensor, axis1, axis2
125- CHECK(args.size() == 0x3) << "tensor.transpose requires exactly 3 arguments (input, axis1, axis2), but got "131+ PRO_IR_CHECK(ExternalError::INVALID_ARGUMENT, args.size() == 0x3)
126- << args.size();132+ << "tensor.transpose requires exactly 3 arguments (input, axis1, axis2), but got " << args.size();
127 133 
128 // First argument must be TensorType134 // First argument must be TensorType
129 auto tensor_type = As<TensorType>(args[0]->GetType());135 auto tensor_type = As<TensorType>(args[0]->GetType());
130- CHECK(tensor_type) << "tensor.transpose requires first argument to be a TensorType, but got "136+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, tensor_type)
131- << args[0]->GetType()->TypeName();137+ << "tensor.transpose requires first argument to be a TensorType, but got " << args[0]->GetType()->TypeName();
132 138 
133 const auto& input_shape = tensor_type->shape_;139 const auto& input_shape = tensor_type->shape_;
134 size_t ndim = input_shape.size();140 size_t ndim = input_shape.size();
135- CHECK(ndim >= 0x2) << "tensor.transpose requires at least 2 dimensions, but got " << ndim;141+ PRO_IR_CHECK(ExternalError::INVALID_SHAPE, ndim >= 0x2)
142+ << "tensor.transpose requires at least 2 dimensions, but got " << ndim;
136 143 
137 // Second argument is axis1 (ConstInt)144 // Second argument is axis1 (ConstInt)
138 auto axis1_const = As<ConstInt>(args[1]);145 auto axis1_const = As<ConstInt>(args[1]);
139- CHECK(axis1_const) << "tensor.transpose requires second argument (axis1) to be a ConstInt";146+ PRO_IR_CHECK(ExternalError::INVALID_SHAPE, axis1_const)
147+ << "tensor.transpose requires second argument (axis1) to be a ConstInt";
140 148 
141 // Third argument is axis2 (ConstInt)149 // Third argument is axis2 (ConstInt)
142 auto axis2_const = As<ConstInt>(args[2]);150 auto axis2_const = As<ConstInt>(args[2]);
143- CHECK(axis2_const) << "tensor.transpose requires third argument (axis2) to be a ConstInt";151+ PRO_IR_CHECK(ExternalError::INVALID_SHAPE, axis2_const)
152+ << "tensor.transpose requires third argument (axis2) to be a ConstInt";
144 153 
145 // Normalize axes (handle negative indexing)154 // Normalize axes (handle negative indexing)
146 int axis1 = NormalizeAxis(static_cast<int>(axis1_const->value_), ndim);155 int axis1 = NormalizeAxis(static_cast<int>(axis1_const->value_), ndim);
147 int axis2 = NormalizeAxis(static_cast<int>(axis2_const->value_), ndim);156 int axis2 = NormalizeAxis(static_cast<int>(axis2_const->value_), ndim);
148 157 
149- CHECK(axis1 != axis2) << "tensor.transpose: axis1 and axis2 must be different, but got axis1=" << axis1158+ PRO_IR_CHECK(ExternalError::INVALID_SHAPE, axis1 != axis2)
150- << ", axis2=" << axis2;159+ << "tensor.transpose: axis1 and axis2 must be different, but got axis1=" << axis1 << ", axis2=" << axis2;
151 160 
152 // Create new shape by swapping the specified dimensions161 // Create new shape by swapping the specified dimensions
153 std::vector<ExprPtr> new_shape = input_shape;162 std::vector<ExprPtr> new_shape = input_shape;
@@ -28,17 +28,20 @@
28#include "ir/kind_traits.h"28#include "ir/kind_traits.h"
29#include "ir/op_registry.h"29#include "ir/op_registry.h"
30#include "ir/type.h"30#include "ir/type.h"
31+#include "pypto_pro/error.h"
31namespace pypto {32namespace pypto {
32namespace ir {33namespace ir {
34+using npu::tile_fwk::ExternalError;
33 35 
34TypePtr DeduceTensorExpType([[maybe_unused]] const std::vector<ExprPtr>& args,36TypePtr DeduceTensorExpType([[maybe_unused]] const std::vector<ExprPtr>& args,
35 [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs)37 [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs)
36{38{
37- CHECK(args.size() == 1) << "tensor.exp requires exactly 1 argument, but got " << args.size();39+ PRO_IR_CHECK(ExternalError::INVALID_ARGUMENT, args.size() == 1)
40+ << "tensor.exp requires exactly 1 argument, but got " << args.size();
38 41 
39 auto tensor_type = As<TensorType>(args[0]->GetType());42 auto tensor_type = As<TensorType>(args[0]->GetType());
40- CHECK(tensor_type) << "tensor.exp requires first argument to be a TensorType, but got "43+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, tensor_type)
41- << args[0]->GetType()->TypeName();44+ << "tensor.exp requires first argument to be a TensorType, but got " << args[0]->GetType()->TypeName();
42 45 
43 // exp should promote to float type if input is integer46 // exp should promote to float type if input is integer
44 // Exponential always produces floating-point output (e.g., exp(1) = 2.718...)47 // Exponential always produces floating-point output (e.g., exp(1) = 2.718...)
@@ -54,11 +57,12 @@ TypePtr DeduceTensorExpType([[maybe_unused]] const std::vector<ExprPtr>& args,
54TypePtr DeduceTensorCastType([[maybe_unused]] const std::vector<ExprPtr>& args,57TypePtr DeduceTensorCastType([[maybe_unused]] const std::vector<ExprPtr>& args,
55 [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs)58 [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs)
56{59{
57- CHECK(args.size() == 1) << "tensor.cast requires exactly 1 argument (input), but got " << args.size();60+ PRO_IR_CHECK(ExternalError::INVALID_ARGUMENT, args.size() == 1)
61+ << "tensor.cast requires exactly 1 argument (input), but got " << args.size();
58 62 
59 auto tensor_type = As<TensorType>(args[0]->GetType());63 auto tensor_type = As<TensorType>(args[0]->GetType());
60- CHECK(tensor_type) << "tensor.cast requires first argument to be a TensorType, but got "64+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, tensor_type)
61- << args[0]->GetType()->TypeName();65+ << "tensor.cast requires first argument to be a TensorType, but got " << args[0]->GetType()->TypeName();
62 66 
63 // Read target_type from kwargs67 // Read target_type from kwargs
64 bool found_target_type = false;68 bool found_target_type = false;
@@ -71,13 +75,14 @@ TypePtr DeduceTensorCastType([[maybe_unused]] const std::vector<ExprPtr>& args,
71 } else if (value.type() == typeid(int)) {75 } else if (value.type() == typeid(int)) {
72 target_dtype = static_cast<DataType>(AnyCast<int>(value, "kwarg key: target_type"));76 target_dtype = static_cast<DataType>(AnyCast<int>(value, "kwarg key: target_type"));
73 } else {77 } else {
74- CHECK(false) << "target_type must be a DataType or int, but got " << value.type().name();78+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, false)
79+ << "target_type must be a DataType or int, but got " << value.type().name();
75 }80 }
76 found_target_type = true;81 found_target_type = true;
77 break;82 break;
78 }83 }
79 }84 }
80- CHECK(found_target_type) << "tensor.cast requires 'target_type' kwarg";85+ PRO_IR_CHECK(ExternalError::INVALID_ARGUMENT, found_target_type) << "tensor.cast requires 'target_type' kwarg";
81 86 
82 // mode kwarg is optional, not used in type deduction87 // mode kwarg is optional, not used in type deduction
83 88 
@@ -23,9 +23,11 @@
23#include "ir/kind_traits.h"23#include "ir/kind_traits.h"
24#include "ir/scalar_expr.h"24#include "ir/scalar_expr.h"
25#include "ir/type.h"25#include "ir/type.h"
26+#include "pypto_pro/error.h"
26 27 
27namespace pypto {28namespace pypto {
28namespace ir {29namespace ir {
30+using npu::tile_fwk::ExternalError;
29 31 
30BroadcastResult BroadcastShapes(const std::vector<ExprPtr>& shape1, const std::vector<ExprPtr>& shape2)32BroadcastResult BroadcastShapes(const std::vector<ExprPtr>& shape1, const std::vector<ExprPtr>& shape2)
31{33{
@@ -199,16 +201,18 @@ std::vector<ExprPtr> ExtractShape(const TypePtr& type)
199TileScalarTypes RequireTileScalarArgs(const std::vector<ExprPtr>& args, const std::string& op_name,201TileScalarTypes RequireTileScalarArgs(const std::vector<ExprPtr>& args, const std::string& op_name,
200 size_t expected_args)202 size_t expected_args)
201{203{
202- CHECK(args.size() == expected_args) << "The operator " << op_name << " requires exactly " << expected_args204+ PRO_IR_CHECK(ExternalError::INVALID_ARGUMENT, args.size() == expected_args)
203- << " arguments, but got " << args.size();205+ << "The operator " << op_name << " requires exactly " << expected_args << " arguments, but got " << args.size();
204 206 
205 auto tile_type = As<TileType>(args[0]->GetType());207 auto tile_type = As<TileType>(args[0]->GetType());
206- CHECK(tile_type) << "The operator " << op_name << " requires first argument to be a TileType, but got "208+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, tile_type)
207- << args[0]->GetType()->TypeName();209+ << "The operator " << op_name << " requires first argument to be a TileType, but got "
210+ << args[0]->GetType()->TypeName();
208 211 
209 auto scalar_type = As<ScalarType>(args[1]->GetType());212 auto scalar_type = As<ScalarType>(args[1]->GetType());
210- CHECK(scalar_type) << "The operator " << op_name << " requires second argument to be a ScalarType, but got "213+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, scalar_type)
211- << args[1]->GetType()->TypeName();214+ << "The operator " << op_name << " requires second argument to be a ScalarType, but got "
215+ << args[1]->GetType()->TypeName();
212 216 
213 return {tile_type, scalar_type};217 return {tile_type, scalar_type};
214}218}
@@ -217,11 +221,12 @@ TypePtr DeduceBlockOutTileType(const std::vector<ExprPtr>& args,
217 [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs,221 [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs,
218 const std::string& op_name, size_t expected_args)222 const std::string& op_name, size_t expected_args)
219{223{
220- CHECK(args.size() == expected_args) << "The operator " << op_name << " requires exactly " << expected_args224+ PRO_IR_CHECK(ExternalError::INVALID_ARGUMENT, args.size() == expected_args)
221- << " arguments, but got " << args.size();225+ << "The operator " << op_name << " requires exactly " << expected_args << " arguments, but got " << args.size();
222 auto out_type = As<TileType>(args.front()->GetType());226 auto out_type = As<TileType>(args.front()->GetType());
223- CHECK(out_type) << "The operator " << op_name << " requires first argument (out) to be TileType, but got "227+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, out_type)
224- << args.front()->GetType()->TypeName();228+ << "The operator " << op_name << " requires first argument (out) to be TileType, but got "
229+ << args.front()->GetType()->TypeName();
225 return out_type;230 return out_type;
226}231}
227 232 
@@ -25,9 +25,11 @@
25#include "ir/memref.h"25#include "ir/memref.h"
26#include "ir/span.h"26#include "ir/span.h"
27#include "ir/type.h"27#include "ir/type.h"
28+#include "pypto_pro/error.h"
28 29 
29namespace pypto {30namespace pypto {
30namespace ir {31namespace ir {
32+using npu::tile_fwk::ExternalError;
31 33 
32void ValidateKwargs(const std::vector<std::pair<std::string, std::any>>& kwargs,34void ValidateKwargs(const std::vector<std::pair<std::string, std::any>>& kwargs,
33 const std::unordered_map<std::string, std::type_index>& allowed_kwargs, const std::string& op_name)35 const std::unordered_map<std::string, std::type_index>& allowed_kwargs, const std::string& op_name)
@@ -35,35 +37,42 @@ void ValidateKwargs(const std::vector<std::pair<std::string, std::any>>& kwargs,
35 for (const auto& [key, value] : kwargs) {37 for (const auto& [key, value] : kwargs) {
36 auto it = allowed_kwargs.find(key);38 auto it = allowed_kwargs.find(key);
37 if (it == allowed_kwargs.end()) {39 if (it == allowed_kwargs.end()) {
38- throw ValueError("Unknown kwarg '" + key + "' for operator '" + op_name + "'");40+ PRO_IR_THROW(::pypto::ir::ValueError, ExternalError::INVALID_ARGUMENT)
41+ << "Unknown kwarg '" << key << "' for operator '" << op_name << "'";
39 }42 }
40 43 
41 // For DataType, accept both DataType and int (since Python may pass as int for backward compatibility)44 // For DataType, accept both DataType and int (since Python may pass as int for backward compatibility)
42 if (it->second == std::type_index(typeid(DataType))) {45 if (it->second == std::type_index(typeid(DataType))) {
43 std::type_index value_type(value.type());46 std::type_index value_type(value.type());
44- CHECK(value_type == std::type_index(typeid(DataType)) || value_type == std::type_index(typeid(int)))47+ PRO_IR_CHECK(ExternalError::INVALID_TYPE,
48+ value_type == std::type_index(typeid(DataType)) || value_type == std::type_index(typeid(int)))
45 << "Kwarg '" << key << "' for operator '" << op_name49 << "Kwarg '" << key << "' for operator '" << op_name
46 << "' expects DataType or int, but got incompatible type";50 << "' expects DataType or int, but got incompatible type";
47 } else if (it->second == std::type_index(typeid(int))) {51 } else if (it->second == std::type_index(typeid(int))) {
48 std::type_index value_type(value.type());52 std::type_index value_type(value.type());
49- CHECK(value_type == std::type_index(typeid(int)) || value_type == std::type_index(typeid(int64_t)) ||53+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, value_type == std::type_index(typeid(int)) ||
50- value_type == std::type_index(typeid(TilePad)))54+ value_type == std::type_index(typeid(int64_t)) ||
55+ value_type == std::type_index(typeid(TilePad)))
51 << "Kwarg '" << key << "' for operator '" << op_name56 << "Kwarg '" << key << "' for operator '" << op_name
52 << "' expects int/int64/TilePad, but got incompatible type";57 << "' expects int/int64/TilePad, but got incompatible type";
53 } else if (it->second == std::type_index(typeid(MemorySpace))) {58 } else if (it->second == std::type_index(typeid(MemorySpace))) {
54- CHECK(std::type_index(value.type()) == std::type_index(typeid(MemorySpace)))59+ PRO_IR_CHECK(ExternalError::INVALID_VAL,
60+ std::type_index(value.type()) == std::type_index(typeid(MemorySpace)))
55 << "Kwarg '" << key << "' for operator '" << op_name61 << "Kwarg '" << key << "' for operator '" << op_name
56 << "' expects MemorySpace, but got incompatible type" << value.type().name();62 << "' expects MemorySpace, but got incompatible type" << value.type().name();
57 } else if (it->second == std::type_index(typeid(std::vector<int>))) {63 } else if (it->second == std::type_index(typeid(std::vector<int>))) {
58- CHECK(std::type_index(value.type()) == std::type_index(typeid(std::vector<int>)))64+ PRO_IR_CHECK(ExternalError::INVALID_TYPE,
65+ std::type_index(value.type()) == std::type_index(typeid(std::vector<int>)))
59 << "Kwarg '" << key << "' for operator '" << op_name66 << "Kwarg '" << key << "' for operator '" << op_name
60 << "' expects std::vector<int>, but got incompatible type";67 << "' expects std::vector<int>, but got incompatible type";
61 } else if (it->second == std::type_index(typeid(std::vector<std::string>))) {68 } else if (it->second == std::type_index(typeid(std::vector<std::string>))) {
62- CHECK(std::type_index(value.type()) == std::type_index(typeid(std::vector<std::string>)))69+ PRO_IR_CHECK(ExternalError::INVALID_TYPE,
70+ std::type_index(value.type()) == std::type_index(typeid(std::vector<std::string>)))
63 << "Kwarg '" << key << "' for operator '" << op_name71 << "Kwarg '" << key << "' for operator '" << op_name
64 << "' expects std::vector<std::string>, but got incompatible type";72 << "' expects std::vector<std::string>, but got incompatible type";
65 } else if (std::type_index(value.type()) != it->second) {73 } else if (std::type_index(value.type()) != it->second) {
66- CHECK(false) << "Kwarg '" << key << "' for operator '" << op_name << "' has incompatible type";74+ PRO_IR_CHECK(ExternalError::INVALID_TYPE, false)
75+ << "Kwarg '" << key << "' for operator '" << op_name << "' has incompatible type";
67 }76 }
68 }77 }
69}78}
@@ -77,7 +86,8 @@ OpRegistry& OpRegistry::GetInstance()
77OpRegistryEntry& OpRegistry::Register(const std::string& op_name)86OpRegistryEntry& OpRegistry::Register(const std::string& op_name)
78{87{
79 // Check if operator is already registered88 // Check if operator is already registered
80- CHECK(registry_.find(op_name) == registry_.end()) << "Operator '" + op_name + "' is already registered";89+ PRO_IR_CHECK(ExternalError::INVALID_OPERATION, registry_.find(op_name) == registry_.end())
90+ << "Operator '" + op_name + "' is already registered";
81 91 
82 // Create and insert the entry into the registry92 // Create and insert the entry into the registry
83 auto result = registry_.emplace(op_name, OpRegistryEntry());93 auto result = registry_.emplace(op_name, OpRegistryEntry());
@@ -103,9 +113,13 @@ CallPtr OpRegistry::Create(const std::string& op_name, const std::vector<ExprPtr
103CallPtr OpRegistry::Create(const std::string& op_name, const std::vector<ExprPtr>& args,113CallPtr OpRegistry::Create(const std::string& op_name, const std::vector<ExprPtr>& args,
104 const std::vector<std::pair<std::string, std::any>>& kwargs, Span span) const114 const std::vector<std::pair<std::string, std::any>>& kwargs, Span span) const
105{115{
116+ // Publish the DSL location for the whole of Create(): ValidateKwargs and the
117+ // deduce callbacks take no span, so their errors rely on the ambient one.
118+ const pro::SpanScope spanScope(span);
119+ 
106 // Look up operator in registry120 // Look up operator in registry
107 auto it = registry_.find(op_name);121 auto it = registry_.find(op_name);
108- CHECK(it != registry_.end()) << "Operator '" + op_name + "' not found in registry";122+ PRO_IR_CHECK(ExternalError::KEY_ERROR, it != registry_.end()) << "Operator '" + op_name + "' not found in registry";
109 123 
110 const auto& entry = it->second;124 const auto& entry = it->second;
111 125 
@@ -122,7 +136,8 @@ CallPtr OpRegistry::Create(const std::string& op_name, const std::vector<ExprPtr
122 136 
123 // Deduce result type (pass args and kwargs separately)137 // Deduce result type (pass args and kwargs separately)
124 TypePtr result_type = deduce_type_fn(args, kwargs);138 TypePtr result_type = deduce_type_fn(args, kwargs);
125- INTERNAL_CHECK(result_type) << "Type deduction failed for '" + op_name + "'";139+ PRO_IR_INTERNAL_CHECK(npu::tile_fwk::InternalError::COMMON_INNER_ERROR, result_type)
140+ << "Type deduction failed for '" + op_name + "'";
126 141 
127 // Create Call with deduced type142 // Create Call with deduced type
128 return std::make_shared<Call>(op_name, args, kwargs, result_type, std::move(span));143 return std::make_shared<Call>(op_name, args, kwargs, result_type, std::move(span));
@@ -131,14 +146,14 @@ CallPtr OpRegistry::Create(const std::string& op_name, const std::vector<ExprPtr
131const OpRegistryEntry& OpRegistry::GetEntry(const std::string& op_name) const146const OpRegistryEntry& OpRegistry::GetEntry(const std::string& op_name) const
132{147{
133 auto it = registry_.find(op_name);148 auto it = registry_.find(op_name);
134- CHECK(it != registry_.end()) << "Operator '" + op_name + "' not found in registry";149+ PRO_IR_CHECK(ExternalError::KEY_ERROR, it != registry_.end()) << "Operator '" + op_name + "' not found in registry";
135 return it->second;150 return it->second;
136}151}
137 152 
138OpPtr OpRegistry::GetOp(const std::string& op_name) const153OpPtr OpRegistry::GetOp(const std::string& op_name) const
139{154{
140 auto it = registry_.find(op_name);155 auto it = registry_.find(op_name);
141- CHECK(it != registry_.end()) << "Operator '" + op_name + "' not found in registry";156+ PRO_IR_CHECK(ExternalError::KEY_ERROR, it != registry_.end()) << "Operator '" + op_name + "' not found in registry";
142 return it->second.GetOp();157 return it->second.GetOp();
143}158}
144 159 
@@ -19,6 +19,7 @@
19#include "ir/transforms/base/mutator.h"19#include "ir/transforms/base/mutator.h"
20#include "ir/transforms/base/visitor.h"20#include "ir/transforms/base/visitor.h"
21#include "ir/transforms/passes.h"21#include "ir/transforms/passes.h"
22+#include "pypto_pro/error.h"
22 23 
23namespace pypto {24namespace pypto {
24namespace ir {25namespace ir {
@@ -219,7 +220,8 @@ std::pair<int64_t, int64_t> SanitizerInstrumenter::TileDims(const ExprPtr& tile)
219 return {-1, -1};220 return {-1, -1};
220 auto dim0 = As<ConstInt>(tile_type->shape_[0]);221 auto dim0 = As<ConstInt>(tile_type->shape_[0]);
221 auto dim1 = As<ConstInt>(tile_type->shape_[1]);222 auto dim1 = As<ConstInt>(tile_type->shape_[1]);
222- CHECK(dim0 != nullptr && dim1 != nullptr) << "sanitizer: tile shape dims must be static";223+ PRO_PASS_INTERNAL_CHECK(npu::tile_fwk::InternalError::PASS_INNER_ERROR, dim0 != nullptr && dim1 != nullptr)
224+ << "sanitizer: tile shape dims must be static";
223 return {dim0->value_, dim1->value_};225 return {dim0->value_, dim1->value_};
224}226}
225 227 
@@ -252,7 +254,8 @@ StmtPtr SanitizerInstrumenter::MakeLogStmt(uint32_t det_id, std::vector<ExprPtr>
252// tile-count record.254// tile-count record.
253StmtPtr SanitizerInstrumenter::RecordScalarAccess(const CallPtr& call)255StmtPtr SanitizerInstrumenter::RecordScalarAccess(const CallPtr& call)
254{256{
255- CHECK(call->args_.size() >= 0x2) << "sanitizer: " << call->name_ << " requires (container, offset)";257+ PRO_PASS_INTERNAL_CHECK(npu::tile_fwk::InternalError::PASS_INNER_ERROR, call->args_.size() >= 0x2)
258+ << "sanitizer: " << call->name_ << " requires (container, offset)";
256 const auto& container = call->args_[0];259 const auto& container = call->args_[0];
257 auto [tile_dim0, tile_dim1] = TileDims(container);260 auto [tile_dim0, tile_dim1] = TileDims(container);
258 if (tile_dim0 >= 0) {261 if (tile_dim0 >= 0) {
@@ -289,7 +292,8 @@ StmtPtr SanitizerInstrumenter::RecordValidShape(const CallPtr& call)
289 if (call->args_.size() != 0x3)292 if (call->args_.size() != 0x3)
290 return nullptr;293 return nullptr;
291 auto [dim0, dim1] = TileDims(call->args_[0]);294 auto [dim0, dim1] = TileDims(call->args_[0]);
292- CHECK(dim0 >= 0) << "sanitizer: set_validshape target must be a Tile";295+ PRO_PASS_INTERNAL_CHECK(npu::tile_fwk::InternalError::PASS_INNER_ERROR, dim0 >= 0)
296+ << "sanitizer: set_validshape target must be a Tile";
293 std::vector<ExprPtr> fields;297 std::vector<ExprPtr> fields;
294 fields.push_back(Int64Const(dim0));298 fields.push_back(Int64Const(dim0));
295 fields.push_back(Int64Const(dim1));299 fields.push_back(Int64Const(dim1));
@@ -305,12 +309,14 @@ StmtPtr SanitizerInstrumenter::RecordGmAccess(const CallPtr& call)
305 // Operand positions follow the shared access-op contract; the offsets are309 // Operand positions follow the shared access-op contract; the offsets are
306 // always a MakeTuple (frontend normalizes, CCE codegen CHECKs the same).310 // always a MakeTuple (frontend normalizes, CCE codegen CHECKs the same).
307 auto indices = backend::cce::ResolveAccessArgIndices(call->name_);311 auto indices = backend::cce::ResolveAccessArgIndices(call->name_);
308- CHECK(indices.tensor_arg_idx >= 0 && indices.tile_arg_idx >= 0 && indices.offsets_arg_idx >= 0)312+ PRO_PASS_INTERNAL_CHECK(npu::tile_fwk::InternalError::PASS_INNER_ERROR,
313+ indices.tensor_arg_idx >= 0 && indices.tile_arg_idx >= 0 && indices.offsets_arg_idx >= 0)
309 << "sanitizer: no access-arg contract for op " << call->name_;314 << "sanitizer: no access-arg contract for op " << call->name_;
310 ExprPtr tensor = call->args_[indices.tensor_arg_idx];315 ExprPtr tensor = call->args_[indices.tensor_arg_idx];
311 ExprPtr tile = call->args_[indices.tile_arg_idx];316 ExprPtr tile = call->args_[indices.tile_arg_idx];
312 auto off_tuple = As<MakeTuple>(call->args_[indices.offsets_arg_idx]);317 auto off_tuple = As<MakeTuple>(call->args_[indices.offsets_arg_idx]);
313- CHECK(off_tuple != nullptr) << "sanitizer: " << call->name_ << " offsets must be a MakeTuple";318+ PRO_PASS_INTERNAL_CHECK(npu::tile_fwk::InternalError::PASS_INNER_ERROR, off_tuple != nullptr)
319+ << "sanitizer: " << call->name_ << " offsets must be a MakeTuple";
314 320 
315 // Fields: ndim, off[5] (padded), shape[5] (padded), acc_row/acc_col.321 // Fields: ndim, off[5] (padded), shape[5] (padded), acc_row/acc_col.
316 // The tensor shape comes from the access-site TensorType -- static dims322 // The tensor shape comes from the access-site TensorType -- static dims
@@ -318,7 +324,8 @@ StmtPtr SanitizerInstrumenter::RecordGmAccess(const CallPtr& call)
318 // the ABI scalars, so the record carries the runtime truth with no host324 // the ABI scalars, so the record carries the runtime truth with no host
319 // id<->shape mapping (aliases and dynamic dims included).325 // id<->shape mapping (aliases and dynamic dims included).
320 auto tensor_type = As<TensorType>(tensor->GetType());326 auto tensor_type = As<TensorType>(tensor->GetType());
321- CHECK(tensor_type != nullptr) << "sanitizer: " << call->name_ << " tensor operand must be a Tensor";327+ PRO_PASS_INTERNAL_CHECK(npu::tile_fwk::InternalError::PASS_INNER_ERROR, tensor_type != nullptr)
328+ << "sanitizer: " << call->name_ << " tensor operand must be a Tensor";
322 uint32_t ndim = std::min<uint32_t>(static_cast<uint32_t>(off_tuple->elements_.size()), kSanitizerMaxTensorDims);329 uint32_t ndim = std::min<uint32_t>(static_cast<uint32_t>(off_tuple->elements_.size()), kSanitizerMaxTensorDims);
323 std::vector<ExprPtr> fields;330 std::vector<ExprPtr> fields;
324 fields.push_back(Int64Const(ndim));331 fields.push_back(Int64Const(ndim));
@@ -364,13 +371,15 @@ StmtPtr SanitizerInstrumenter::RecordGmAccess(const CallPtr& call)
364StmtPtr SanitizerInstrumenter::RecordTileAccess(const CallPtr& call, uint32_t tile_arg_idx, const ExprPtr& off_row,371StmtPtr SanitizerInstrumenter::RecordTileAccess(const CallPtr& call, uint32_t tile_arg_idx, const ExprPtr& off_row,
365 const ExprPtr& off_col, const ExprPtr& win_row, const ExprPtr& win_col)372 const ExprPtr& off_col, const ExprPtr& win_row, const ExprPtr& win_col)
366{373{
367- CHECK(tile_arg_idx < call->args_.size()) << "sanitizer: missing tile operand at " << tile_arg_idx;374+ PRO_PASS_INTERNAL_CHECK(npu::tile_fwk::InternalError::PASS_INNER_ERROR, tile_arg_idx < call->args_.size())
375+ << "sanitizer: missing tile operand at " << tile_arg_idx;
368 // Dims come from the access-site tile type -- what the codegen376 // Dims come from the access-site tile type -- what the codegen
369 // instantiates the transfer with, i.e. the runtime truth of the access.377 // instantiates the transfer with, i.e. the runtime truth of the access.
370 // This keeps the bound check independent of the tile table (overlap-scan378 // This keeps the bound check independent of the tile table (overlap-scan
371 // only) and lets group cursors record: unresolvable name, known type.379 // only) and lets group cursors record: unresolvable name, known type.
372 auto [dim0, dim1] = TileDims(call->args_[tile_arg_idx]);380 auto [dim0, dim1] = TileDims(call->args_[tile_arg_idx]);
373- CHECK(dim0 >= 0) << "sanitizer: tile operand must be a Tile";381+ PRO_PASS_INTERNAL_CHECK(npu::tile_fwk::InternalError::PASS_INNER_ERROR, dim0 >= 0)
382+ << "sanitizer: tile operand must be a Tile";
374 std::vector<ExprPtr> fields;383 std::vector<ExprPtr> fields;
375 fields.push_back(Int64Const(dim0));384 fields.push_back(Int64Const(dim0));
376 fields.push_back(Int64Const(dim1));385 fields.push_back(Int64Const(dim1));
@@ -414,15 +423,18 @@ StmtPtr SanitizerInstrumenter::CollectMakeTile(const CallPtr& call)
414 // copies share the span, distinct same-range tiles keep both records and423 // copies share the span, distinct same-range tiles keep both records and
415 // are exactly what the scan must report.424 // are exactly what the scan must report.
416 auto tile_type = As<TileType>(target_type_);425 auto tile_type = As<TileType>(target_type_);
417- CHECK(tile_type != nullptr && tile_type->shape_.size() >= 0x2)426+ PRO_PASS_INTERNAL_CHECK(npu::tile_fwk::InternalError::PASS_INNER_ERROR,
427+ tile_type != nullptr && tile_type->shape_.size() >= 0x2)
418 << "sanitizer: make_tile value must be a 2-D TileType";428 << "sanitizer: make_tile value must be a 2-D TileType";
419- CHECK(tile_type->memref_.has_value() && *tile_type->memref_ != nullptr)429+ PRO_PASS_INTERNAL_CHECK(npu::tile_fwk::InternalError::PASS_INNER_ERROR,
430+ tile_type->memref_.has_value() && *tile_type->memref_ != nullptr)
420 << "sanitizer: make_tile requires a resolved MemRef (frontend enforces addr)";431 << "sanitizer: make_tile requires a resolved MemRef (frontend enforces addr)";
421 int64_t dtype_bytes = std::max<int64_t>(1, tile_type->dtype_.GetBit() / 8);432 int64_t dtype_bytes = std::max<int64_t>(1, tile_type->dtype_.GetBit() / 8);
422 int64_t sz = 1;433 int64_t sz = 1;
423 for (const auto& d : tile_type->shape_) {434 for (const auto& d : tile_type->shape_) {
424 auto c = As<ConstInt>(d);435 auto c = As<ConstInt>(d);
425- CHECK(c != nullptr) << "sanitizer: tile shape dims must be static";436+ PRO_PASS_INTERNAL_CHECK(npu::tile_fwk::InternalError::PASS_INNER_ERROR, c != nullptr)
437+ << "sanitizer: tile shape dims must be static";
426 sz *= c->value_;438 sz *= c->value_;
427 }439 }
428 int64_t addr = -1;440 int64_t addr = -1;
@@ -457,12 +469,17 @@ StmtPtr SanitizerInstrumenter::CollectMakeTensor(const CallPtr& call)
457 // the source's byte capacity (a raw-pointer source records -1: no known469 // the source's byte capacity (a raw-pointer source records -1: no known
458 // bound). Nothing is registered -- the replay needs no host-side view470 // bound). Nothing is registered -- the replay needs no host-side view
459 // table.471 // table.
460- CHECK(call->args_.size() >= 0x2) << "sanitizer: ptr.make_tensor requires (ptr, shape)";472+ PRO_PASS_INTERNAL_CHECK(npu::tile_fwk::InternalError::PASS_INNER_ERROR, call->args_.size() >= 0x2)
473+ << "sanitizer: ptr.make_tensor requires (ptr, shape)";
461 auto shape_tuple = As<MakeTuple>(call->args_[1]);474 auto shape_tuple = As<MakeTuple>(call->args_[1]);
462- CHECK(shape_tuple != nullptr) << "sanitizer: ptr.make_tensor shape must be a MakeTuple";475+ PRO_PASS_INTERNAL_CHECK(npu::tile_fwk::InternalError::PASS_INNER_ERROR, shape_tuple != nullptr)
476+ << "sanitizer: ptr.make_tensor shape must be a MakeTuple";
463 auto stride_tuple = As<MakeTuple>(call->args_[2]);477 auto stride_tuple = As<MakeTuple>(call->args_[2]);
464- CHECK(stride_tuple != nullptr) << "sanitizer: ptr.make_tensor stride must be a MakeTuple";478+ PRO_PASS_INTERNAL_CHECK(npu::tile_fwk::InternalError::PASS_INNER_ERROR, stride_tuple != nullptr)
465- CHECK(stride_tuple->elements_.empty() || stride_tuple->elements_.size() == shape_tuple->elements_.size())479+ << "sanitizer: ptr.make_tensor stride must be a MakeTuple";
480+ PRO_PASS_INTERNAL_CHECK(
481+ npu::tile_fwk::InternalError::PASS_INNER_ERROR,
482+ stride_tuple->elements_.empty() || stride_tuple->elements_.size() == shape_tuple->elements_.size())
466 << "sanitizer: ptr.make_tensor stride rank must match the shape";483 << "sanitizer: ptr.make_tensor stride rank must match the shape";
467 484 
468 // Byte footprint expression: (sum((dim-1)*stride) + 1) * elem_bytes, with485 // Byte footprint expression: (sum((dim-1)*stride) + 1) * elem_bytes, with
@@ -474,7 +491,8 @@ StmtPtr SanitizerInstrumenter::CollectMakeTensor(const CallPtr& call)
474 view_dtype = src_shaped->dtype_;491 view_dtype = src_shaped->dtype_;
475 } else {492 } else {
476 auto src_ptr = As<PtrType>(call->args_[0]->GetType());493 auto src_ptr = As<PtrType>(call->args_[0]->GetType());
477- CHECK(src_ptr != nullptr) << "sanitizer: ptr.make_tensor source must be a Ptr or Tensor";494+ PRO_PASS_INTERNAL_CHECK(npu::tile_fwk::InternalError::PASS_INNER_ERROR, src_ptr != nullptr)
495+ << "sanitizer: ptr.make_tensor source must be a Ptr or Tensor";
478 view_dtype = src_ptr->dtype_;496 view_dtype = src_ptr->dtype_;
479 }497 }
480 int64_t elem_bytes = std::max<int64_t>(1, static_cast<int64_t>(view_dtype.GetBit()) / 8);498 int64_t elem_bytes = std::max<int64_t>(1, static_cast<int64_t>(view_dtype.GetBit()) / 8);
@@ -557,7 +575,8 @@ Pass pass::Sanitizer()
557{575{
558 return CreateProgramPass(576 return CreateProgramPass(
559 [](const ProgramPtr& program) -> ProgramPtr {577 [](const ProgramPtr& program) -> ProgramPtr {
560- INTERNAL_CHECK(program) << "Sanitizer pass cannot run on a null program";578+ PRO_PASS_INTERNAL_CHECK(npu::tile_fwk::InternalError::PASS_INNER_ERROR, program)
579+ << "Sanitizer pass cannot run on a null program";
561 SanitizerInstrumenter instrumenter;580 SanitizerInstrumenter instrumenter;
562 return instrumenter.Instrument(program);581 return instrumenter.Instrument(program);
563 },582 },
@@ -38,11 +38,13 @@
38#include "ir/pipe.h"38#include "ir/pipe.h"
39#include "ir/type.h"39#include "ir/type.h"
40#include "ir/type_inference.h"40#include "ir/type_inference.h"
41+#include "pypto_pro/error.h"
41#include "tilefwk/error.h"42#include "tilefwk/error.h"
42 43 
43namespace pypto {44namespace pypto {
44namespace backend {45namespace backend {
45using ir::DataType;46using ir::DataType;
47+using npu::tile_fwk::ExternalError;
46 48 
47// ============================================================================49// ============================================================================
48// Helper Functions for CCE Code Generation50// Helper Functions for CCE Code Generation
@@ -29,9 +29,11 @@
29#include "ir/op_attr_types.h"29#include "ir/op_attr_types.h"
30#include "ir/pipe.h"30#include "ir/pipe.h"
31#include "ir/scalar_expr.h"31#include "ir/scalar_expr.h"
32+#include "pypto_pro/error.h"
32 33 
33namespace pypto {34namespace pypto {
34namespace backend {35namespace backend {
36+using npu::tile_fwk::ExternalError;
35 37 
36namespace {38namespace {
37 39 
@@ -45,7 +47,8 @@ std::string MakeSimtContextComponentCodegenCCE(const ir::CallPtr& op, codegen::C
45 const char* op_name, const char* context_name)47 const char* op_name, const char* context_name)
46{48{
47 auto& codegen = dynamic_cast<codegen::CCECodegen&>(codegen_base);49 auto& codegen = dynamic_cast<codegen::CCECodegen&>(codegen_base);
48- CHECK(codegen.IsInSimtContext()) << op_name << " reached CCE codegen outside a SIMT function";50+ PRO_CODEGEN_CHECK(ExternalError::INVALID_OPERATION, codegen.IsInSimtContext())
51+ << op_name << " reached CCE codegen outside a SIMT function";
49 return std::string(context_name) + "." + GetSimtAxisName(op->GetKwarg<int>("axis"));52 return std::string(context_name) + "." + GetSimtAxisName(op->GetKwarg<int>("axis"));
50}53}
51 54 
@@ -73,22 +76,26 @@ std::string MakeSimtLinearThreadIdxCodegenCCE([[maybe_unused]] const ir::CallPtr
73 codegen::CodegenBase& codegen_base)76 codegen::CodegenBase& codegen_base)
74{77{
75 auto& codegen = dynamic_cast<codegen::CCECodegen&>(codegen_base);78 auto& codegen = dynamic_cast<codegen::CCECodegen&>(codegen_base);
76- CHECK(codegen.IsInSimtContext()) << "simt.linear_thread_idx reached CCE codegen outside a SIMT function";79+ PRO_CODEGEN_CHECK(ExternalError::INVALID_OPERATION, codegen.IsInSimtContext())
80+ << "simt.linear_thread_idx reached CCE codegen outside a SIMT function";
77 return "(threadIdx.x + threadIdx.y * blockDim.x + threadIdx.z * blockDim.x * blockDim.y)";81 return "(threadIdx.x + threadIdx.y * blockDim.x + threadIdx.z * blockDim.x * blockDim.y)";
78}82}
79 83 
80std::string MakeSimtWarpSizeCodegenCCE([[maybe_unused]] const ir::CallPtr& op, codegen::CodegenBase& codegen_base)84std::string MakeSimtWarpSizeCodegenCCE([[maybe_unused]] const ir::CallPtr& op, codegen::CodegenBase& codegen_base)
81{85{
82 auto& codegen = dynamic_cast<codegen::CCECodegen&>(codegen_base);86 auto& codegen = dynamic_cast<codegen::CCECodegen&>(codegen_base);
83- CHECK(codegen.IsInSimtContext()) << "simt.warp_size reached CCE codegen outside a SIMT function";87+ PRO_CODEGEN_CHECK(ExternalError::INVALID_OPERATION, codegen.IsInSimtContext())
88+ << "simt.warp_size reached CCE codegen outside a SIMT function";
84 return "warpSize";89 return "warpSize";
85}90}
86 91 
87std::string MakeSimtSyncthreadsCodegenCCE(const ir::CallPtr& op, codegen::CodegenBase& codegen_base)92std::string MakeSimtSyncthreadsCodegenCCE(const ir::CallPtr& op, codegen::CodegenBase& codegen_base)
88{93{
89 auto& codegen = dynamic_cast<codegen::CCECodegen&>(codegen_base);94 auto& codegen = dynamic_cast<codegen::CCECodegen&>(codegen_base);
90- CHECK(codegen.IsInSimtContext()) << "simt.syncthreads reached CCE codegen outside a SIMT function";95+ PRO_CODEGEN_CHECK(ExternalError::INVALID_OPERATION, codegen.IsInSimtContext())
91- CHECK(op->args_.empty() && op->kwargs_.empty()) << "simt.syncthreads does not accept arguments";96+ << "simt.syncthreads reached CCE codegen outside a SIMT function";
97+ PRO_CODEGEN_CHECK(ExternalError::NOT_IMPLEMENTED_ERROR, op->args_.empty() && op->kwargs_.empty())
98+ << "simt.syncthreads does not accept arguments";
92 codegen.Emit("__sync_workitems();");99 codegen.Emit("__sync_workitems();");
93 return "";100 return "";
94}101}
@@ -96,8 +103,10 @@ std::string MakeSimtSyncthreadsCodegenCCE(const ir::CallPtr& op, codegen::Codege
96std::string MakeSimtThreadfenceBlockCodegenCCE(const ir::CallPtr& op, codegen::CodegenBase& codegen_base)103std::string MakeSimtThreadfenceBlockCodegenCCE(const ir::CallPtr& op, codegen::CodegenBase& codegen_base)
97{104{
98 auto& codegen = dynamic_cast<codegen::CCECodegen&>(codegen_base);105 auto& codegen = dynamic_cast<codegen::CCECodegen&>(codegen_base);
99- CHECK(codegen.IsInSimtContext()) << "simt.threadfence_block reached CCE codegen outside a SIMT function";106+ PRO_CODEGEN_CHECK(ExternalError::INVALID_OPERATION, codegen.IsInSimtContext())
100- CHECK(op->args_.empty() && op->kwargs_.empty()) << "simt.threadfence_block does not accept arguments";107+ << "simt.threadfence_block reached CCE codegen outside a SIMT function";
108+ PRO_CODEGEN_CHECK(ExternalError::NOT_IMPLEMENTED_ERROR, op->args_.empty() && op->kwargs_.empty())
109+ << "simt.threadfence_block does not accept arguments";
101 codegen.Emit("__threadfence_block();");110 codegen.Emit("__threadfence_block();");
102 return "";111 return "";
103}112}
@@ -105,8 +114,10 @@ std::string MakeSimtThreadfenceBlockCodegenCCE(const ir::CallPtr& op, codegen::C
105std::string MakeSimtThreadfenceCodegenCCE(const ir::CallPtr& op, codegen::CodegenBase& codegen_base)114std::string MakeSimtThreadfenceCodegenCCE(const ir::CallPtr& op, codegen::CodegenBase& codegen_base)
106{115{
107 auto& codegen = dynamic_cast<codegen::CCECodegen&>(codegen_base);116 auto& codegen = dynamic_cast<codegen::CCECodegen&>(codegen_base);
108- CHECK(codegen.IsInSimtContext()) << "simt.threadfence reached CCE codegen outside a SIMT function";117+ PRO_CODEGEN_CHECK(ExternalError::INVALID_OPERATION, codegen.IsInSimtContext())
109- CHECK(op->args_.empty() && op->kwargs_.empty()) << "simt.threadfence does not accept arguments";118+ << "simt.threadfence reached CCE codegen outside a SIMT function";
119+ PRO_CODEGEN_CHECK(ExternalError::NOT_IMPLEMENTED_ERROR, op->args_.empty() && op->kwargs_.empty())
120+ << "simt.threadfence does not accept arguments";
110 codegen.Emit("__threadfence();");121 codegen.Emit("__threadfence();");
111 return "";122 return "";
112}123}
@@ -128,7 +139,7 @@ const char* GetSimtCastRoundModeCCE(ir::RoundMode mode)
128 case ir::RoundMode::CAST_ODD:139 case ir::RoundMode::CAST_ODD:
129 return "ROUND::O";140 return "ROUND::O";
130 default:141 default:
131- CHECK(false) << "Unsupported simt.cast round mode";142+ PRO_CODEGEN_CHECK(ExternalError::NOT_IMPLEMENTED_ERROR, false) << "Unsupported simt.cast round mode";
132 return "";143 return "";
133 }144 }
134}145}
@@ -163,7 +174,8 @@ std::string MakeSimtCastIntrinsicCallCCE(ir::DataType target_dtype, ir::RoundMod
163 const std::string& operand)174 const std::string& operand)
164{175{
165 const char* intrinsic = GetSimtCastIntrinsicCCE(target_dtype);176 const char* intrinsic = GetSimtCastIntrinsicCCE(target_dtype);
166- CHECK(intrinsic != nullptr) << "No A5 scalar conversion intrinsic for " << target_dtype.ToString();177+ PRO_CODEGEN_CHECK(ExternalError::NOT_IMPLEMENTED_ERROR, intrinsic != nullptr)
178+ << "No A5 scalar conversion intrinsic for " << target_dtype.ToString();
167 return std::string(intrinsic) + "<" + GetSimtCastRoundModeCCE(mode) + ", " + saturation + ">(" + operand + ")";179 return std::string(intrinsic) + "<" + GetSimtCastRoundModeCCE(mode) + ", " + saturation + ">(" + operand + ")";
168}180}
169 181 
@@ -189,7 +201,8 @@ std::string MakeSimtCastNarrowIntegerCCE(ir::DataType target_dtype, ir::RoundMod
189 } else if (target_dtype == ir::DataType::UINT16) {201 } else if (target_dtype == ir::DataType::UINT16) {
190 upper_bound = "65535U";202 upper_bound = "65535U";
191 } else {203 } else {
192- CHECK(false) << "Unsupported narrow simt.cast target " << target_dtype.ToString();204+ PRO_CODEGEN_CHECK(ExternalError::NOT_IMPLEMENTED_ERROR, false)
205+ << "Unsupported narrow simt.cast target " << target_dtype.ToString();
193 }206 }
194 207 
195 const std::string target_type = target_dtype.ToCTypeString();208 const std::string target_type = target_dtype.ToCTypeString();
@@ -209,7 +222,8 @@ std::string MakeSimtCastNarrowIntegerCCE(ir::DataType target_dtype, ir::RoundMod
209 222 
210std::string MakeSimtCastPlainCCE(ir::DataType target_dtype, ir::RoundMode mode, const std::string& operand)223std::string MakeSimtCastPlainCCE(ir::DataType target_dtype, ir::RoundMode mode, const std::string& operand)
211{224{
212- CHECK(mode == ir::RoundMode::CAST_NONE) << "Explicit simt.cast rounding requires an A5 scalar conversion intrinsic";225+ PRO_CODEGEN_CHECK(ExternalError::NOT_IMPLEMENTED_ERROR, mode == ir::RoundMode::CAST_NONE)
226+ << "Explicit simt.cast rounding requires an A5 scalar conversion intrinsic";
213 return "((" + target_dtype.ToCTypeString() + ")" + operand + ")";227 return "((" + target_dtype.ToCTypeString() + ")" + operand + ")";
214}228}
215 229 
@@ -294,14 +308,17 @@ std::string MakeSimtCastFromInt64OrUint64CCE(ir::DataType source_dtype, ir::Data
294std::string MakeSimtCastCodegenCCE(const ir::CallPtr& op, codegen::CodegenBase& codegen_base)308std::string MakeSimtCastCodegenCCE(const ir::CallPtr& op, codegen::CodegenBase& codegen_base)
295{309{
296 auto& codegen = dynamic_cast<codegen::CCECodegen&>(codegen_base);310 auto& codegen = dynamic_cast<codegen::CCECodegen&>(codegen_base);
297- CHECK(codegen.IsInSimtContext()) << "simt.cast reached CCE codegen outside a SIMT function";311+ PRO_CODEGEN_CHECK(ExternalError::INVALID_OPERATION, codegen.IsInSimtContext())
298- CHECK(codegen.GetArch() == "a5") << "simt.cast currently requires arch='a5'";312+ << "simt.cast reached CCE codegen outside a SIMT function";
299- CHECK(op->args_.size() == 1) << "simt.cast requires one scalar argument";313+ PRO_CODEGEN_CHECK(ExternalError::NOT_IMPLEMENTED_ERROR, codegen.GetArch() == "a5")
314+ << "simt.cast currently requires arch='a5'";
315+ PRO_CODEGEN_CHECK(ExternalError::INVALID_ARGUMENT, op->args_.size() == 1)
316+ << "simt.cast requires one scalar argument";
300 317 
301 auto source_type = ir::As<ir::ScalarType>(op->args_[0]->GetType());318 auto source_type = ir::As<ir::ScalarType>(op->args_[0]->GetType());
302 auto target_type = ir::As<ir::ScalarType>(op->GetType());319 auto target_type = ir::As<ir::ScalarType>(op->GetType());
303- CHECK(source_type) << "simt.cast source must be ScalarType";320+ PRO_CODEGEN_CHECK(ExternalError::INVALID_TYPE, source_type) << "simt.cast source must be ScalarType";
304- CHECK(target_type) << "simt.cast target must be ScalarType";321+ PRO_CODEGEN_CHECK(ExternalError::INVALID_TYPE, target_type) << "simt.cast target must be ScalarType";
305 322 
306 const auto source_dtype = source_type->dtype_;323 const auto source_dtype = source_type->dtype_;
307 const auto target_dtype = target_type->dtype_;324 const auto target_dtype = target_type->dtype_;
@@ -332,14 +349,17 @@ std::string MakeSimtCastCodegenCCE(const ir::CallPtr& op, codegen::CodegenBase&
332std::string MakeSimtBitcastCodegenCCE(const ir::CallPtr& op, codegen::CodegenBase& codegen_base)349std::string MakeSimtBitcastCodegenCCE(const ir::CallPtr& op, codegen::CodegenBase& codegen_base)
333{350{
334 auto& codegen = dynamic_cast<codegen::CCECodegen&>(codegen_base);351 auto& codegen = dynamic_cast<codegen::CCECodegen&>(codegen_base);
335- CHECK(codegen.IsInSimtContext()) << "simt.bitcast reached CCE codegen outside a SIMT function";352+ PRO_CODEGEN_CHECK(ExternalError::INVALID_OPERATION, codegen.IsInSimtContext())
336- CHECK(codegen.GetArch() == "a5") << "simt.bitcast currently requires arch='a5'";353+ << "simt.bitcast reached CCE codegen outside a SIMT function";
337- CHECK(op->args_.size() == 1) << "simt.bitcast requires one scalar argument";354+ PRO_CODEGEN_CHECK(ExternalError::NOT_IMPLEMENTED_ERROR, codegen.GetArch() == "a5")
355+ << "simt.bitcast currently requires arch='a5'";
356+ PRO_CODEGEN_CHECK(ExternalError::INVALID_ARGUMENT, op->args_.size() == 1)
357+ << "simt.bitcast requires one scalar argument";
338 358 
339 auto source_type = ir::As<ir::ScalarType>(op->args_[0]->GetType());359 auto source_type = ir::As<ir::ScalarType>(op->args_[0]->GetType());
340 auto target_type = ir::As<ir::ScalarType>(op->GetType());360 auto target_type = ir::As<ir::ScalarType>(op->GetType());
341- CHECK(source_type) << "simt.bitcast source must be ScalarType";361+ PRO_CODEGEN_CHECK(ExternalError::INVALID_TYPE, source_type) << "simt.bitcast source must be ScalarType";
342- CHECK(target_type) << "simt.bitcast target must be ScalarType";362+ PRO_CODEGEN_CHECK(ExternalError::INVALID_TYPE, target_type) << "simt.bitcast target must be ScalarType";
343 363 
344 const std::string operand = codegen.GetExprAsCode(op->args_[0]);364 const std::string operand = codegen.GetExprAsCode(op->args_[0]);
345 std::ostringstream s;365 std::ostringstream s;
@@ -426,10 +446,12 @@ struct SimtUnaryCodegenInput {
426SimtUnaryCodegenInput GetSimtUnaryCodegenInput(const ir::CallPtr& op, codegen::CodegenBase& codegen_base)446SimtUnaryCodegenInput GetSimtUnaryCodegenInput(const ir::CallPtr& op, codegen::CodegenBase& codegen_base)
427{447{
428 auto& codegen = dynamic_cast<codegen::CCECodegen&>(codegen_base);448 auto& codegen = dynamic_cast<codegen::CCECodegen&>(codegen_base);
429- CHECK(codegen.IsInSimtContext()) << op->name_ << " reached CCE codegen outside a SIMT function";449+ PRO_CODEGEN_CHECK(ExternalError::INVALID_OPERATION, codegen.IsInSimtContext())
430- CHECK(codegen.GetArch() == "a5") << op->name_ << " currently requires arch='a5'";450+ << op->name_ << " reached CCE codegen outside a SIMT function";
451+ PRO_CODEGEN_CHECK(ExternalError::NOT_IMPLEMENTED_ERROR, codegen.GetArch() == "a5")
452+ << op->name_ << " currently requires arch='a5'";
431 auto scalar_type = ir::As<ir::ScalarType>(op->args_[0]->GetType());453 auto scalar_type = ir::As<ir::ScalarType>(op->args_[0]->GetType());
432- CHECK(scalar_type != nullptr) << op->name_ << " operand must be a scalar";454+ PRO_CODEGEN_CHECK(ExternalError::INVALID_TYPE, scalar_type != nullptr) << op->name_ << " operand must be a scalar";
433 return {scalar_type->dtype_, codegen.GetExprAsCode(op->args_[0])};455 return {scalar_type->dtype_, codegen.GetExprAsCode(op->args_[0])};
434}456}
435 457 
@@ -450,7 +472,7 @@ std::string MakeSimtAbsCodegenCCE(const ir::CallPtr& op, codegen::CodegenBase& c
450 const std::string cvt_in = "__cvt_float<ROUND::R, RoundingSaturation::RS_DISABLE_VALUE>(" + a + ")";472 const std::string cvt_in = "__cvt_float<ROUND::R, RoundingSaturation::RS_DISABLE_VALUE>(" + a + ")";
451 return "__cvt_bfloat16_t<ROUND::R, RoundingSaturation::RS_DISABLE_VALUE>(__fabsf(" + cvt_in + "))";473 return "__cvt_bfloat16_t<ROUND::R, RoundingSaturation::RS_DISABLE_VALUE>(__fabsf(" + cvt_in + "))";
452 }474 }
453- CHECK(false) << "Unsupported simt.abs dtype " << dtype.ToString();475+ PRO_CODEGEN_CHECK(ExternalError::INVALID_TYPE, false) << "Unsupported simt.abs dtype " << dtype.ToString();
454 return "";476 return "";
455}477}
456 478 
@@ -467,7 +489,7 @@ std::string MakeSimtSqrtCodegenCCE(const ir::CallPtr& op, codegen::CodegenBase&
467 const std::string cvt_in = "__cvt_float<ROUND::R, RoundingSaturation::RS_DISABLE_VALUE>(" + a + ")";489 const std::string cvt_in = "__cvt_float<ROUND::R, RoundingSaturation::RS_DISABLE_VALUE>(" + a + ")";
468 return "__cvt_bfloat16_t<ROUND::R, RoundingSaturation::RS_DISABLE_VALUE>(__sqrtf(" + cvt_in + "))";490 return "__cvt_bfloat16_t<ROUND::R, RoundingSaturation::RS_DISABLE_VALUE>(__sqrtf(" + cvt_in + "))";
469 }491 }
470- CHECK(false) << "Unsupported simt.sqrt dtype " << dtype.ToString();492+ PRO_CODEGEN_CHECK(ExternalError::INVALID_TYPE, false) << "Unsupported simt.sqrt dtype " << dtype.ToString();
471 return "";493 return "";
472}494}
473 495 
@@ -484,7 +506,7 @@ std::string MakeSimtRsqrtCodegenCCE(const ir::CallPtr& op, codegen::CodegenBase&
484 const std::string cvt_in = "__cvt_float<ROUND::R, RoundingSaturation::RS_DISABLE_VALUE>(" + a + ")";506 const std::string cvt_in = "__cvt_float<ROUND::R, RoundingSaturation::RS_DISABLE_VALUE>(" + a + ")";
485 return "__cvt_bfloat16_t<ROUND::R, RoundingSaturation::RS_DISABLE_VALUE>(1.0f / __sqrtf(" + cvt_in + "))";507 return "__cvt_bfloat16_t<ROUND::R, RoundingSaturation::RS_DISABLE_VALUE>(1.0f / __sqrtf(" + cvt_in + "))";
486 }508 }
487- CHECK(false) << "Unsupported simt.rsqrt dtype " << dtype.ToString();509+ PRO_CODEGEN_CHECK(ExternalError::INVALID_TYPE, false) << "Unsupported simt.rsqrt dtype " << dtype.ToString();
488 return "";510 return "";
489}511}
490 512 
@@ -501,7 +523,7 @@ std::string MakeSimtExpCodegenCCE(const ir::CallPtr& op, codegen::CodegenBase& c
501 const std::string cvt_in = "__cvt_float<ROUND::R, RoundingSaturation::RS_DISABLE_VALUE>(" + a + ")";523 const std::string cvt_in = "__cvt_float<ROUND::R, RoundingSaturation::RS_DISABLE_VALUE>(" + a + ")";
502 return "__cvt_bfloat16_t<ROUND::R, RoundingSaturation::RS_DISABLE_VALUE>(__expf(" + cvt_in + "))";524 return "__cvt_bfloat16_t<ROUND::R, RoundingSaturation::RS_DISABLE_VALUE>(__expf(" + cvt_in + "))";
503 }525 }
504- CHECK(false) << "Unsupported simt.exp dtype " << dtype.ToString();526+ PRO_CODEGEN_CHECK(ExternalError::INVALID_TYPE, false) << "Unsupported simt.exp dtype " << dtype.ToString();
505 return "";527 return "";
506}528}
507 529 
@@ -522,7 +544,7 @@ std::string MakeSimtExp2CodegenCCE(const ir::CallPtr& op, codegen::CodegenBase&
522 return "__cvt_bfloat16_t<ROUND::R, RoundingSaturation::RS_DISABLE_VALUE>(__expf(" + cvt_in +544 return "__cvt_bfloat16_t<ROUND::R, RoundingSaturation::RS_DISABLE_VALUE>(__expf(" + cvt_in +
523 " * 0.6931471805599453f))";545 " * 0.6931471805599453f))";
524 }546 }
525- CHECK(false) << "Unsupported simt.exp2 dtype " << dtype.ToString();547+ PRO_CODEGEN_CHECK(ExternalError::INVALID_TYPE, false) << "Unsupported simt.exp2 dtype " << dtype.ToString();
526 return "";548 return "";
527}549}
528 550 
@@ -543,7 +565,7 @@ std::string MakeSimtLogCodegenCCE(const ir::CallPtr& op, codegen::CodegenBase& c
543 const std::string cvt_in = "__cvt_float<ROUND::R, RoundingSaturation::RS_DISABLE_VALUE>(" + a + ")";565 const std::string cvt_in = "__cvt_float<ROUND::R, RoundingSaturation::RS_DISABLE_VALUE>(" + a + ")";
544 return "__cvt_bfloat16_t<ROUND::R, RoundingSaturation::RS_DISABLE_VALUE>(__logf(" + cvt_in + "))";566 return "__cvt_bfloat16_t<ROUND::R, RoundingSaturation::RS_DISABLE_VALUE>(__logf(" + cvt_in + "))";
545 }567 }
546- CHECK(false) << "Unsupported simt.log dtype " << dtype.ToString();568+ PRO_CODEGEN_CHECK(ExternalError::INVALID_TYPE, false) << "Unsupported simt.log dtype " << dtype.ToString();
547 return "";569 return "";
548}570}
549 571 
@@ -567,7 +589,7 @@ std::string MakeSimtLog2CodegenCCE(const ir::CallPtr& op, codegen::CodegenBase&
567 return "__cvt_bfloat16_t<ROUND::R, RoundingSaturation::RS_DISABLE_VALUE>(__logf(" + cvt_in +589 return "__cvt_bfloat16_t<ROUND::R, RoundingSaturation::RS_DISABLE_VALUE>(__logf(" + cvt_in +
568 ") / __logf(2.0f))";590 ") / __logf(2.0f))";
569 }591 }
570- CHECK(false) << "Unsupported simt.log2 dtype " << dtype.ToString();592+ PRO_CODEGEN_CHECK(ExternalError::INVALID_TYPE, false) << "Unsupported simt.log2 dtype " << dtype.ToString();
571 return "";593 return "";
572}594}
573 595 
@@ -578,7 +600,7 @@ std::string MakeSimtLog1pCodegenCCE(const ir::CallPtr& op, codegen::CodegenBase&
578 const auto& a = input.operand;600 const auto& a = input.operand;
579 if (dtype == ir::DataType::FP32)601 if (dtype == ir::DataType::FP32)
580 return "__logf(1.0f + " + a + ")";602 return "__logf(1.0f + " + a + ")";
581- CHECK(false) << "Unsupported simt.log1p dtype " << dtype.ToString();603+ PRO_CODEGEN_CHECK(ExternalError::INVALID_TYPE, false) << "Unsupported simt.log1p dtype " << dtype.ToString();
582 return "";604 return "";
583}605}
584 606 
@@ -599,7 +621,7 @@ std::string MakeSimtTanhCodegenCCE(const ir::CallPtr& op, codegen::CodegenBase&
599 return "__cvt_bfloat16_t<ROUND::R, RoundingSaturation::RS_DISABLE_VALUE>(1.0f - (2.0f / (__expf(2.0f * " +621 return "__cvt_bfloat16_t<ROUND::R, RoundingSaturation::RS_DISABLE_VALUE>(1.0f - (2.0f / (__expf(2.0f * " +
600 cvt_in + ") + 1.0f)))";622 cvt_in + ") + 1.0f)))";
601 }623 }
602- CHECK(false) << "Unsupported simt.tanh dtype " << dtype.ToString();624+ PRO_CODEGEN_CHECK(ExternalError::INVALID_TYPE, false) << "Unsupported simt.tanh dtype " << dtype.ToString();
603 return "";625 return "";
604}626}
605 627 
@@ -611,7 +633,7 @@ std::string MakeSimtRintCodegenCCE(const ir::CallPtr& op, codegen::CodegenBase&
611 if (dtype == ir::DataType::FP32 || dtype == ir::DataType::FP16 || dtype == ir::DataType::BF16) {633 if (dtype == ir::DataType::FP32 || dtype == ir::DataType::FP16 || dtype == ir::DataType::BF16) {
612 return "__rintf(" + a + ")";634 return "__rintf(" + a + ")";
613 }635 }
614- CHECK(false) << "Unsupported simt.rint dtype " << dtype.ToString();636+ PRO_CODEGEN_CHECK(ExternalError::INVALID_TYPE, false) << "Unsupported simt.rint dtype " << dtype.ToString();
615 return "";637 return "";
616}638}
617 639 
@@ -628,7 +650,7 @@ std::string MakeSimtRoundCodegenCCE(const ir::CallPtr& op, codegen::CodegenBase&
628 if (dtype == ir::DataType::BF16) {650 if (dtype == ir::DataType::BF16) {
629 return "__cvt_bfloat16_t<ROUND::A, RoundingSaturation::RS_DISABLE_VALUE>(" + a + ")";651 return "__cvt_bfloat16_t<ROUND::A, RoundingSaturation::RS_DISABLE_VALUE>(" + a + ")";
630 }652 }
631- CHECK(false) << "Unsupported simt.round dtype " << dtype.ToString();653+ PRO_CODEGEN_CHECK(ExternalError::INVALID_TYPE, false) << "Unsupported simt.round dtype " << dtype.ToString();
632 return "";654 return "";
633}655}
634 656 
@@ -640,7 +662,7 @@ std::string MakeSimtFloorCodegenCCE(const ir::CallPtr& op, codegen::CodegenBase&
640 if (dtype == ir::DataType::FP32 || dtype == ir::DataType::FP16 || dtype == ir::DataType::BF16) {662 if (dtype == ir::DataType::FP32 || dtype == ir::DataType::FP16 || dtype == ir::DataType::BF16) {
641 return "__floorf(" + a + ")";663 return "__floorf(" + a + ")";
642 }664 }
643- CHECK(false) << "Unsupported simt.floor dtype " << dtype.ToString();665+ PRO_CODEGEN_CHECK(ExternalError::INVALID_TYPE, false) << "Unsupported simt.floor dtype " << dtype.ToString();
644 return "";666 return "";
645}667}
646 668 
@@ -652,7 +674,7 @@ std::string MakeSimtCeilCodegenCCE(const ir::CallPtr& op, codegen::CodegenBase&
652 if (dtype == ir::DataType::FP32 || dtype == ir::DataType::FP16 || dtype == ir::DataType::BF16) {674 if (dtype == ir::DataType::FP32 || dtype == ir::DataType::FP16 || dtype == ir::DataType::BF16) {
653 return "__ceilf(" + a + ")";675 return "__ceilf(" + a + ")";
654 }676 }
655- CHECK(false) << "Unsupported simt.ceil dtype " << dtype.ToString();677+ PRO_CODEGEN_CHECK(ExternalError::INVALID_TYPE, false) << "Unsupported simt.ceil dtype " << dtype.ToString();
656 return "";678 return "";
657}679}
658 680 
@@ -668,7 +690,7 @@ std::string MakeSimtTruncCodegenCCE(const ir::CallPtr& op, codegen::CodegenBase&
668 if (dtype == ir::DataType::BF16) {690 if (dtype == ir::DataType::BF16) {
669 return "((" + a + " > (bfloat16_t)0) ? __floorf(" + a + ") : __ceilf(" + a + "))";691 return "((" + a + " > (bfloat16_t)0) ? __floorf(" + a + ") : __ceilf(" + a + "))";
670 }692 }
671- CHECK(false) << "Unsupported simt.trunc dtype " << dtype.ToString();693+ PRO_CODEGEN_CHECK(ExternalError::INVALID_TYPE, false) << "Unsupported simt.trunc dtype " << dtype.ToString();
672 return "";694 return "";
673}695}
674 696 
@@ -680,7 +702,7 @@ std::string MakeSimtIsnanCodegenCCE(const ir::CallPtr& op, codegen::CodegenBase&
680 if (dtype == ir::DataType::FP32 || dtype == ir::DataType::FP16 || dtype == ir::DataType::BF16) {702 if (dtype == ir::DataType::FP32 || dtype == ir::DataType::FP16 || dtype == ir::DataType::BF16) {
681 return "__isnan(" + a + ")";703 return "__isnan(" + a + ")";
682 }704 }
683- CHECK(false) << "Unsupported simt.isnan dtype " << dtype.ToString();705+ PRO_CODEGEN_CHECK(ExternalError::INVALID_TYPE, false) << "Unsupported simt.isnan dtype " << dtype.ToString();
684 return "";706 return "";
685}707}
686 708 
@@ -692,14 +714,15 @@ std::string MakeSimtIsinfCodegenCCE(const ir::CallPtr& op, codegen::CodegenBase&
692 if (dtype == ir::DataType::FP32 || dtype == ir::DataType::FP16 || dtype == ir::DataType::BF16) {714 if (dtype == ir::DataType::FP32 || dtype == ir::DataType::FP16 || dtype == ir::DataType::BF16) {
693 return "__isinf(" + a + ")";715 return "__isinf(" + a + ")";
694 }716 }
695- CHECK(false) << "Unsupported simt.isinf dtype " << dtype.ToString();717+ PRO_CODEGEN_CHECK(ExternalError::INVALID_TYPE, false) << "Unsupported simt.isinf dtype " << dtype.ToString();
696 return "";718 return "";
697}719}
698 720 
699std::string MakeSimtIsfiniteCodegenCCE(const ir::CallPtr& op, codegen::CodegenBase& codegen_base)721std::string MakeSimtIsfiniteCodegenCCE(const ir::CallPtr& op, codegen::CodegenBase& codegen_base)
700{722{
701 const auto input = GetSimtUnaryCodegenInput(op, codegen_base);723 const auto input = GetSimtUnaryCodegenInput(op, codegen_base);
702- CHECK(input.dtype == ir::DataType::FP16 || input.dtype == ir::DataType::FP32)724+ PRO_CODEGEN_CHECK(ExternalError::INVALID_TYPE,
725+ input.dtype == ir::DataType::FP16 || input.dtype == ir::DataType::FP32)
703 << "simt.isfinite requires FP16 or FP32";726 << "simt.isfinite requires FP16 or FP32";
704 return "__isfinite(" + input.operand + ")";727 return "__isfinite(" + input.operand + ")";
705}728}
@@ -710,7 +733,8 @@ std::string MakeSimtPopcountCodegenCCE(const ir::CallPtr& op, codegen::CodegenBa
710 if (input.dtype == ir::DataType::UINT32) {733 if (input.dtype == ir::DataType::UINT32) {
711 return "__popc((unsigned int)(" + input.operand + "))";734 return "__popc((unsigned int)(" + input.operand + "))";
712 }735 }
713- CHECK(input.dtype == ir::DataType::UINT64) << "simt.popcount requires UINT32 or UINT64";736+ PRO_CODEGEN_CHECK(ExternalError::INVALID_TYPE, input.dtype == ir::DataType::UINT64)
737+ << "simt.popcount requires UINT32 or UINT64";
714 return "__popc((unsigned long long)(" + input.operand + "))";738 return "__popc((unsigned long long)(" + input.operand + "))";
715}739}
716 740 
@@ -734,7 +758,8 @@ std::string MakeSimtMulHiCodegenCCE(const ir::CallPtr& op, codegen::CodegenBase&
734 intrinsic = "__umul64hi";758 intrinsic = "__umul64hi";
735 operand_type = "unsigned long long";759 operand_type = "unsigned long long";
736 } else {760 } else {
737- CHECK(false) << "Unsupported simt.mul_hi dtype " << input.dtype.ToString();761+ PRO_CODEGEN_CHECK(ExternalError::INVALID_TYPE, false)
762+ << "Unsupported simt.mul_hi dtype " << input.dtype.ToString();
738 return "";763 return "";
739 }764 }
740 return "((" + input.dtype.ToCTypeString() + ")" + intrinsic + "((" + operand_type + ")(" + input.operand + "), (" +765 return "((" + input.dtype.ToCTypeString() + ")" + intrinsic + "((" + operand_type + ")(" + input.operand + "), (" +
@@ -744,7 +769,7 @@ std::string MakeSimtMulHiCodegenCCE(const ir::CallPtr& op, codegen::CodegenBase&
744std::string MakeSimtFmodCodegenCCE(const ir::CallPtr& op, codegen::CodegenBase& codegen_base)769std::string MakeSimtFmodCodegenCCE(const ir::CallPtr& op, codegen::CodegenBase& codegen_base)
745{770{
746 const auto input = GetSimtUnaryCodegenInput(op, codegen_base);771 const auto input = GetSimtUnaryCodegenInput(op, codegen_base);
747- CHECK(input.dtype == ir::DataType::FP32) << "simt.fmod requires FP32";772+ PRO_CODEGEN_CHECK(ExternalError::INVALID_TYPE, input.dtype == ir::DataType::FP32) << "simt.fmod requires FP32";
748 auto& codegen = dynamic_cast<codegen::CCECodegen&>(codegen_base);773 auto& codegen = dynamic_cast<codegen::CCECodegen&>(codegen_base);
749 const std::string rhs = codegen.GetExprAsCode(op->args_[1]);774 const std::string rhs = codegen.GetExprAsCode(op->args_[1]);
750 return pypto::codegen::BuildFP32FmodExpression(input.operand, rhs);775 return pypto::codegen::BuildFP32FmodExpression(input.operand, rhs);
@@ -767,7 +792,7 @@ std::string MakeSimtSinCodegenCCE(const ir::CallPtr& op, codegen::CodegenBase& c
767 return "__cvt_bfloat16_t<ROUND::R, RoundingSaturation::RS_DISABLE_VALUE>(" +792 return "__cvt_bfloat16_t<ROUND::R, RoundingSaturation::RS_DISABLE_VALUE>(" +
768 MakeSimtTrigFP32Codegen(cvt_in, true) + ")";793 MakeSimtTrigFP32Codegen(cvt_in, true) + ")";
769 }794 }
770- CHECK(false) << "Unsupported simt.sin dtype " << dtype.ToString();795+ PRO_CODEGEN_CHECK(ExternalError::INVALID_TYPE, false) << "Unsupported simt.sin dtype " << dtype.ToString();
771 return "";796 return "";
772}797}
773 798 
@@ -788,17 +813,19 @@ std::string MakeSimtCosCodegenCCE(const ir::CallPtr& op, codegen::CodegenBase& c
788 return "__cvt_bfloat16_t<ROUND::R, RoundingSaturation::RS_DISABLE_VALUE>(" +813 return "__cvt_bfloat16_t<ROUND::R, RoundingSaturation::RS_DISABLE_VALUE>(" +
789 MakeSimtTrigFP32Codegen(cvt_in, false) + ")";814 MakeSimtTrigFP32Codegen(cvt_in, false) + ")";
790 }815 }
791- CHECK(false) << "Unsupported simt.cos dtype " << dtype.ToString();816+ PRO_CODEGEN_CHECK(ExternalError::INVALID_TYPE, false) << "Unsupported simt.cos dtype " << dtype.ToString();
792 return "";817 return "";
793}818}
794 819 
795std::string MakeSimtMinCodegenCCE(const ir::CallPtr& op, codegen::CodegenBase& codegen_base)820std::string MakeSimtMinCodegenCCE(const ir::CallPtr& op, codegen::CodegenBase& codegen_base)
796{821{
797 auto& codegen = dynamic_cast<codegen::CCECodegen&>(codegen_base);822 auto& codegen = dynamic_cast<codegen::CCECodegen&>(codegen_base);
798- CHECK(codegen.IsInSimtContext()) << "simt.min reached CCE codegen outside a SIMT function";823+ PRO_CODEGEN_CHECK(ExternalError::INVALID_OPERATION, codegen.IsInSimtContext())
799- CHECK(codegen.GetArch() == "a5") << "simt.min currently requires arch='a5'";824+ << "simt.min reached CCE codegen outside a SIMT function";
825+ PRO_CODEGEN_CHECK(ExternalError::NOT_IMPLEMENTED_ERROR, codegen.GetArch() == "a5")
826+ << "simt.min currently requires arch='a5'";
800 auto scalar_type = ir::As<ir::ScalarType>(op->args_[0]->GetType());827 auto scalar_type = ir::As<ir::ScalarType>(op->args_[0]->GetType());
801- CHECK(scalar_type != nullptr) << "simt.min operand must be a scalar";828+ PRO_CODEGEN_CHECK(ExternalError::INVALID_TYPE, scalar_type != nullptr) << "simt.min operand must be a scalar";
802 const auto& dtype = scalar_type->dtype_;829 const auto& dtype = scalar_type->dtype_;
803 const std::string a = codegen.GetExprAsCode(op->args_[0]);830 const std::string a = codegen.GetExprAsCode(op->args_[0]);
804 const std::string b = codegen.GetExprAsCode(op->args_[1]);831 const std::string b = codegen.GetExprAsCode(op->args_[1]);
@@ -815,17 +842,19 @@ std::string MakeSimtMinCodegenCCE(const ir::CallPtr& op, codegen::CodegenBase& c
815 if (dtype == ir::DataType::BF16) {842 if (dtype == ir::DataType::BF16) {
816 return "(__isnan(" + a + ") ? " + b + " : (__isnan(" + b + ") ? " + a + " : __min(" + a + ", " + b + ")))";843 return "(__isnan(" + a + ") ? " + b + " : (__isnan(" + b + ") ? " + a + " : __min(" + a + ", " + b + ")))";
817 }844 }
818- CHECK(false) << "Unsupported simt.min dtype " << dtype.ToString();845+ PRO_CODEGEN_CHECK(ExternalError::INVALID_TYPE, false) << "Unsupported simt.min dtype " << dtype.ToString();
819 return "";846 return "";
820}847}
821 848 
822std::string MakeSimtMaxCodegenCCE(const ir::CallPtr& op, codegen::CodegenBase& codegen_base)849std::string MakeSimtMaxCodegenCCE(const ir::CallPtr& op, codegen::CodegenBase& codegen_base)
823{850{
824 auto& codegen = dynamic_cast<codegen::CCECodegen&>(codegen_base);851 auto& codegen = dynamic_cast<codegen::CCECodegen&>(codegen_base);
825- CHECK(codegen.IsInSimtContext()) << "simt.max reached CCE codegen outside a SIMT function";852+ PRO_CODEGEN_CHECK(ExternalError::INVALID_OPERATION, codegen.IsInSimtContext())
826- CHECK(codegen.GetArch() == "a5") << "simt.max currently requires arch='a5'";853+ << "simt.max reached CCE codegen outside a SIMT function";
854+ PRO_CODEGEN_CHECK(ExternalError::NOT_IMPLEMENTED_ERROR, codegen.GetArch() == "a5")
855+ << "simt.max currently requires arch='a5'";
827 auto scalar_type = ir::As<ir::ScalarType>(op->args_[0]->GetType());856 auto scalar_type = ir::As<ir::ScalarType>(op->args_[0]->GetType());
828- CHECK(scalar_type != nullptr) << "simt.max operand must be a scalar";857+ PRO_CODEGEN_CHECK(ExternalError::INVALID_TYPE, scalar_type != nullptr) << "simt.max operand must be a scalar";
829 const auto& dtype = scalar_type->dtype_;858 const auto& dtype = scalar_type->dtype_;
830 const std::string a = codegen.GetExprAsCode(op->args_[0]);859 const std::string a = codegen.GetExprAsCode(op->args_[0]);
831 const std::string b = codegen.GetExprAsCode(op->args_[1]);860 const std::string b = codegen.GetExprAsCode(op->args_[1]);
@@ -842,15 +871,17 @@ std::string MakeSimtMaxCodegenCCE(const ir::CallPtr& op, codegen::CodegenBase& c
842 if (dtype == ir::DataType::BF16) {871 if (dtype == ir::DataType::BF16) {
843 return "(__isnan(" + a + ") ? " + b + " : (__isnan(" + b + ") ? " + a + " : __max(" + a + ", " + b + ")))";872 return "(__isnan(" + a + ") ? " + b + " : (__isnan(" + b + ") ? " + a + " : __max(" + a + ", " + b + ")))";
844 }873 }
845- CHECK(false) << "Unsupported simt.max dtype " << dtype.ToString();874+ PRO_CODEGEN_CHECK(ExternalError::INVALID_TYPE, false) << "Unsupported simt.max dtype " << dtype.ToString();
846 return "";875 return "";
847}876}
848 877 
849std::string MakeSimtFmaCodegenCCE(const ir::CallPtr& op, codegen::CodegenBase& codegen_base)878std::string MakeSimtFmaCodegenCCE(const ir::CallPtr& op, codegen::CodegenBase& codegen_base)
850{879{
851 auto& codegen = dynamic_cast<codegen::CCECodegen&>(codegen_base);880 auto& codegen = dynamic_cast<codegen::CCECodegen&>(codegen_base);
852- CHECK(codegen.IsInSimtContext()) << "simt.fma reached CCE codegen outside a SIMT function";881+ PRO_CODEGEN_CHECK(ExternalError::INVALID_OPERATION, codegen.IsInSimtContext())
853- CHECK(codegen.GetArch() == "a5") << "simt.fma currently requires arch='a5'";882+ << "simt.fma reached CCE codegen outside a SIMT function";
883+ PRO_CODEGEN_CHECK(ExternalError::NOT_IMPLEMENTED_ERROR, codegen.GetArch() == "a5")
884+ << "simt.fma currently requires arch='a5'";
854 return "__fma(" + codegen.GetExprAsCode(op->args_[0]) + ", " + codegen.GetExprAsCode(op->args_[1]) + ", " +885 return "__fma(" + codegen.GetExprAsCode(op->args_[0]) + ", " + codegen.GetExprAsCode(op->args_[1]) + ", " +
855 codegen.GetExprAsCode(op->args_[2]) + ")";886 codegen.GetExprAsCode(op->args_[2]) + ")";
856}887}
@@ -895,7 +926,7 @@ SimtAtomicSpec GetSimtAtomicSpec(const std::string& op_name)
895 if (op_name == "simt.atomic_xor") {926 if (op_name == "simt.atomic_xor") {
896 return {"atomicXOr", 1};927 return {"atomicXOr", 1};
897 }928 }
898- CHECK(false) << "Unsupported SIMT atomic operation " << op_name;929+ PRO_CODEGEN_CHECK(ExternalError::NOT_IMPLEMENTED_ERROR, false) << "Unsupported SIMT atomic operation " << op_name;
899 return {"", 0};930 return {"", 0};
900}931}
901 932 
@@ -903,23 +934,28 @@ std::string MakeSimtAtomicCodegenCCE(const ir::CallPtr& op, codegen::CodegenBase
903{934{
904 auto& codegen = dynamic_cast<codegen::CCECodegen&>(codegen_base);935 auto& codegen = dynamic_cast<codegen::CCECodegen&>(codegen_base);
905 SimtAtomicSpec spec = GetSimtAtomicSpec(op->name_);936 SimtAtomicSpec spec = GetSimtAtomicSpec(op->name_);
906- CHECK(codegen.IsInSimtContext()) << op->name_ << " reached CCE codegen outside a SIMT function";937+ PRO_CODEGEN_CHECK(ExternalError::INVALID_OPERATION, codegen.IsInSimtContext())
907- CHECK(codegen.GetArch() == "a5") << op->name_ << " currently requires arch='a5'";938+ << op->name_ << " reached CCE codegen outside a SIMT function";
908- CHECK(op->args_.size() == spec.operand_count + 2)939+ PRO_CODEGEN_CHECK(ExternalError::NOT_IMPLEMENTED_ERROR, codegen.GetArch() == "a5")
940+ << op->name_ << " currently requires arch='a5'";
941+ PRO_CODEGEN_CHECK(ExternalError::INVALID_ARGUMENT, op->args_.size() == spec.operand_count + 2)
909 << op->name_ << " requires container, offset, and " << spec.operand_count << " scalar operand(s)";942 << op->name_ << " requires container, offset, and " << spec.operand_count << " scalar operand(s)";
910 943 
911 auto tile_type = ir::As<ir::TileType>(op->args_[0]->GetType());944 auto tile_type = ir::As<ir::TileType>(op->args_[0]->GetType());
912 auto tensor_type = ir::As<ir::TensorType>(op->args_[0]->GetType());945 auto tensor_type = ir::As<ir::TensorType>(op->args_[0]->GetType());
913- CHECK(tile_type || tensor_type) << op->name_ << " container must be a Tile or Tensor";946+ PRO_CODEGEN_CHECK(ExternalError::INVALID_TYPE, tile_type || tensor_type)
947+ << op->name_ << " container must be a Tile or Tensor";
914 948 
915 std::string base;949 std::string base;
916 if (tile_type) {950 if (tile_type) {
917 auto tile_var = ir::As<ir::Var>(op->args_[0]);951 auto tile_var = ir::As<ir::Var>(op->args_[0]);
918- CHECK(tile_var != nullptr) << op->name_ << " Tile container must be a Var";952+ PRO_CODEGEN_CHECK(ExternalError::INVALID_TYPE, tile_var != nullptr)
953+ << op->name_ << " Tile container must be a Var";
919 base = codegen.GetExprAsCode(op->args_[0]);954 base = codegen.GetExprAsCode(op->args_[0]);
920 } else {955 } else {
921 auto tensor_var = ir::As<ir::Var>(op->args_[0]);956 auto tensor_var = ir::As<ir::Var>(op->args_[0]);
922- CHECK(tensor_var != nullptr) << op->name_ << " Tensor container must be a Var";957+ PRO_CODEGEN_CHECK(ExternalError::INVALID_TYPE, tensor_var != nullptr)
958+ << op->name_ << " Tensor container must be a Var";
923 base = codegen.GetPointer(codegen.GetVarName(tensor_var));959 base = codegen.GetPointer(codegen.GetVarName(tensor_var));
924 }960 }
925 std::string offset = codegen.GetExprAsCode(op->args_[1]);961 std::string offset = codegen.GetExprAsCode(op->args_[1]);
@@ -941,9 +977,12 @@ std::string MakeSimtAtomicCodegenCCE(const ir::CallPtr& op, codegen::CodegenBase
941std::string MakeSimtLaunchCodegenCCE(const ir::CallPtr& op, codegen::CodegenBase& codegen_base)977std::string MakeSimtLaunchCodegenCCE(const ir::CallPtr& op, codegen::CodegenBase& codegen_base)
942{978{
943 auto& codegen = dynamic_cast<codegen::CCECodegen&>(codegen_base);979 auto& codegen = dynamic_cast<codegen::CCECodegen&>(codegen_base);
944- CHECK(!codegen.IsInSimtContext()) << "Nested simt.launch is not supported";980+ PRO_CODEGEN_CHECK(ExternalError::NOT_IMPLEMENTED_ERROR, !codegen.IsInSimtContext())
945- CHECK(codegen.GetTarget() == ir::SectionKind::Vector) << "simt.launch requires the Vector target";981+ << "Nested simt.launch is not supported";
946- CHECK(codegen.GetArch() == "a5") << "simt.launch currently requires arch='a5'";982+ PRO_CODEGEN_CHECK(ExternalError::INVALID_OPERATION, codegen.GetTarget() == ir::SectionKind::Vector)
983+ << "simt.launch requires the Vector target";
984+ PRO_CODEGEN_CHECK(ExternalError::NOT_IMPLEMENTED_ERROR, codegen.GetArch() == "a5")
985+ << "simt.launch currently requires arch='a5'";
947 int64_t thread_dims[3] = {};986 int64_t thread_dims[3] = {};
948 for (size_t i = 0; i < 3; ++i) {987 for (size_t i = 0; i < 3; ++i) {
949 auto dim = ir::As<ir::ConstInt>(op->args_[i]);988 auto dim = ir::As<ir::ConstInt>(op->args_[i]);
@@ -25,10 +25,12 @@
25#include "tilefwk/error.h"25#include "tilefwk/error.h"
26#include "ir/memref.h"26#include "ir/memref.h"
27#include "ir/pipe.h"27#include "ir/pipe.h"
28+#include "pypto_pro/error.h"
28#include "tilefwk/error.h"29#include "tilefwk/error.h"
29 30 
30namespace pypto {31namespace pypto {
31namespace backend {32namespace backend {
33+using npu::tile_fwk::ExternalError;
32 34 
33namespace {35namespace {
34 36 
@@ -110,7 +112,8 @@ std::vector<ir::MemorySpace> Backend::FindMemPath(ir::MemorySpace from, ir::Memo
110 }112 }
111 }113 }
112 114 
113- CHECK(found) << "No path found from " << static_cast<int>(from) << " to " << static_cast<int>(to);115+ PRO_CODEGEN_CHECK(ExternalError::NOT_IMPLEMENTED_ERROR, found)
116+ << "No path found from " << static_cast<int>(from) << " to " << static_cast<int>(to);
114 117 
115 // Reconstruct path118 // Reconstruct path
116 std::vector<ir::MemorySpace> path;119 std::vector<ir::MemorySpace> path;
@@ -160,14 +163,16 @@ const Backend::BackendOpInfo* Backend::GetOpInfo(const std::string& op_name) con
160 163 
161BackendOpRegistryEntry& BackendOpRegistryEntry::set_pipe(ir::PipeType pipe)164BackendOpRegistryEntry& BackendOpRegistryEntry::set_pipe(ir::PipeType pipe)
162{165{
163- CHECK(!pipe_.has_value()) << "Pipe type already set for op '" << op_name_ << "'";166+ PRO_CODEGEN_CHECK(ExternalError::INVALID_OPERATION, !pipe_.has_value())
167+ << "Pipe type already set for op '" << op_name_ << "'";
164 pipe_ = pipe;168 pipe_ = pipe;
165 return *this;169 return *this;
166}170}
167 171 
168BackendOpRegistryEntry& BackendOpRegistryEntry::f_codegen(BackendCodegenFunc func)172BackendOpRegistryEntry& BackendOpRegistryEntry::f_codegen(BackendCodegenFunc func)
169{173{
170- CHECK(!codegen_func_.has_value()) << "Codegen function already set for op '" << op_name_ << "'";174+ PRO_CODEGEN_CHECK(ExternalError::INVALID_OPERATION, !codegen_func_.has_value())
175+ << "Codegen function already set for op '" << op_name_ << "'";
171 codegen_func_ = std::move(func);176 codegen_func_ = std::move(func);
172 return *this;177 return *this;
173}178}
@@ -18,10 +18,12 @@
18#include "backend/common/soc.h"18#include "backend/common/soc.h"
19#include "core/error.h"19#include "core/error.h"
20#include "core/logging.h"20#include "core/logging.h"
21+#include "pypto_pro/error.h"
21#include "tilefwk/error.h"22#include "tilefwk/error.h"
22 23 
23namespace pypto {24namespace pypto {
24namespace backend {25namespace backend {
26+using npu::tile_fwk::ExternalError;
25 27 
26BackendRegistry& BackendRegistry::Instance()28BackendRegistry& BackendRegistry::Instance()
27{29{
@@ -31,7 +33,8 @@ BackendRegistry& BackendRegistry::Instance()
31 33 
32void BackendRegistry::Register(const std::string& type_name, CreateFunc func)34void BackendRegistry::Register(const std::string& type_name, CreateFunc func)
33{35{
34- CHECK(registry_.find(type_name) == registry_.end()) << "Backend type already registered: " << type_name;36+ PRO_CODEGEN_CHECK(ExternalError::INVALID_OPERATION, registry_.find(type_name) == registry_.end())
37+ << "Backend type already registered: " << type_name;
35 registry_[type_name] = std::move(func);38 registry_[type_name] = std::move(func);
36}39}
37 40 
@@ -39,8 +42,9 @@ std::unique_ptr<Backend> BackendRegistry::Create(const std::string& type_name, c
39{42{
40 (void)type_name;43 (void)type_name;
41 (void)soc;44 (void)soc;
42- throw ir::ValueError("Cannot create backend instances via registry - backends are singletons. "45+ PRO_CODEGEN_THROW(::pypto::ir::ValueError, npu::tile_fwk::InternalError::CODEGEN_INNER_ERROR)
43- "Use BackendCCE::Instance() instead.");46+ << "Cannot create backend instances via registry - backends are singletons. "
47+ << "Use BackendCCE::Instance() instead.";
44}48}
45 49 
46bool BackendRegistry::IsRegistered(const std::string& type_name) const50bool BackendRegistry::IsRegistered(const std::string& type_name) const
@@ -52,15 +56,17 @@ std::unique_ptr<Backend> CreateBackendFromRegistry(const std::string& type_name,
52{56{
53 (void)type_name;57 (void)type_name;
54 (void)soc;58 (void)soc;
55- throw ir::ValueError("Cannot create backend instances via registry - backends are singletons. "59+ PRO_CODEGEN_THROW(::pypto::ir::ValueError, npu::tile_fwk::InternalError::CODEGEN_INNER_ERROR)
56- "Use BackendCCE::Instance() instead.");60+ << "Cannot create backend instances via registry - backends are singletons. "
61+ << "Use BackendCCE::Instance() instead.";
57}62}
58 63 
59namespace {64namespace {
60bool RegisterBackendCCE()65bool RegisterBackendCCE()
61{66{
62 BackendRegistry::Instance().Register("CCE", [](const std::shared_ptr<const SoC>& /*unused*/) {67 BackendRegistry::Instance().Register("CCE", [](const std::shared_ptr<const SoC>& /*unused*/) {
63- throw ir::ValueError("Cannot create BackendCCE via registry - use BackendCCE::Instance()");68+ PRO_CODEGEN_THROW(::pypto::ir::ValueError, npu::tile_fwk::InternalError::CODEGEN_INNER_ERROR)
69+ << "Cannot create BackendCCE via registry - use BackendCCE::Instance()";
64 return std::unique_ptr<Backend>(nullptr);70 return std::unique_ptr<Backend>(nullptr);
65 });71 });
66 return true;72 return true;
@@ -20,10 +20,12 @@
20#include "ir/memref.h"20#include "ir/memref.h"
21#include "ir/scalar_expr.h"21#include "ir/scalar_expr.h"
22#include "ir/type_inference.h"22#include "ir/type_inference.h"
23+#include "pypto_pro/error.h"
23#include "tilefwk/error.h"24#include "tilefwk/error.h"
24 25 
25namespace pypto {26namespace pypto {
26namespace backend {27namespace backend {
28+using npu::tile_fwk::ExternalError;
27namespace round_mode {29namespace round_mode {
28 30 
29int FindIndex(const std::string& mode, const std::string& op_name)31int FindIndex(const std::string& mode, const std::string& op_name)
@@ -35,7 +37,7 @@ int FindIndex(const std::string& mode, const std::string& op_name)
35 return static_cast<int>(i);37 return static_cast<int>(i);
36 }38 }
37 }39 }
38- CHECK(false) << op_name << ": unknown round mode '" << mode << "'";40+ PRO_CODEGEN_CHECK(ExternalError::INVALID_ARGUMENT, false) << op_name << ": unknown round mode '" << mode << "'";
39 return -1;41 return -1;
40}42}
41 43 
@@ -111,14 +113,14 @@ std::vector<int> MXLoadTileDims(const ir::CallPtr& op, const ir::TensorTypePtr&
111{113{
112 const int rank = static_cast<int>(tensor_type->shape_.size());114 const int rank = static_cast<int>(tensor_type->shape_.size());
113 // MX scale tensors carry a trailing physical phase axis of size 2.115 // MX scale tensors carry a trailing physical phase axis of size 2.
114- IRCHECK(rank >= 3) << "MX scale load requires at least two matrix axes and one physical phase axis at "116+ PRO_CODEGEN_IRCHECK(ExternalError::INVALID_SHAPE, rank >= 3)
115- << op->span_.ToString();117+ << "MX scale load requires at least two matrix axes and one physical phase axis at " << op->span_.ToString();
116 const auto phase_dim = ir::As<ir::ConstInt>(tensor_type->shape_.back());118 const auto phase_dim = ir::As<ir::ConstInt>(tensor_type->shape_.back());
117- IRCHECK(phase_dim != nullptr && phase_dim->value_ == 2)119+ PRO_CODEGEN_IRCHECK(ExternalError::INVALID_SHAPE, phase_dim != nullptr && phase_dim->value_ == 2)
118 << "MX scale load trailing physical phase axis must be statically equal to 2 at " << op->span_.ToString();120 << "MX scale load trailing physical phase axis must be statically equal to 2 at " << op->span_.ToString();
119 const std::vector<int> tile_dims = op->HasKwarg("tile_dims") ? op->GetKwarg<std::vector<int>>("tile_dims") :121 const std::vector<int> tile_dims = op->HasKwarg("tile_dims") ? op->GetKwarg<std::vector<int>>("tile_dims") :
120 std::vector<int>{rank - 3, rank - 2};122 std::vector<int>{rank - 3, rank - 2};
121- IRCHECK(tile_dims[0] != rank - 1 && tile_dims[1] != rank - 1)123+ PRO_CODEGEN_IRCHECK(ExternalError::INVALID_SHAPE, tile_dims[0] != rank - 1 && tile_dims[1] != rank - 1)
122 << "MX scale load order cannot select the trailing physical phase axis at " << op->span_.ToString();124 << "MX scale load order cannot select the trailing physical phase axis at " << op->span_.ToString();
123 return tile_dims;125 return tile_dims;
124}126}
@@ -151,22 +153,26 @@ void ValidateNZTransfer(const std::string& op_name, const ir::CallPtr& op, const
151 auto tile_type = ir::As<ir::TileType>(tile_expr->GetType());153 auto tile_type = ir::As<ir::TileType>(tile_expr->GetType());
152 const auto& hw = tile_type->hardwareInfo_.value();154 const auto& hw = tile_type->hardwareInfo_.value();
153 const bool is_nz_tile = hw.blayout == ir::TileLayout::col_major && hw.slayout == ir::TileLayout::row_major;155 const bool is_nz_tile = hw.blayout == ir::TileLayout::col_major && hw.slayout == ir::TileLayout::row_major;
154- CHECK(is_nz_tile) << op_name << ": GM NZ transfer requires an NZ Tile layout";156+ PRO_CODEGEN_CHECK(ExternalError::INVALID_FORMAT, is_nz_tile)
157+ << op_name << ": GM NZ transfer requires an NZ Tile layout";
155 158 
156 const size_t ndim = tensor_type->shape_.size();159 const size_t ndim = tensor_type->shape_.size();
157- CHECK(offsets->elements_.size() == ndim) << op_name << ": offset rank must match GM NZ tensor rank";160+ PRO_CODEGEN_CHECK(ExternalError::INVALID_SHAPE, offsets->elements_.size() == ndim)
161+ << op_name << ": offset rank must match GM NZ tensor rank";
158 const bool is_transpose = op->HasKwarg("is_transpose") && op->GetKwarg<bool>("is_transpose");162 const bool is_transpose = op->HasKwarg("is_transpose") && op->GetKwarg<bool>("is_transpose");
159- CHECK(!is_transpose) << op_name << ": CCE NZ transfer does not support order transpose";163+ PRO_CODEGEN_CHECK(ExternalError::INVALID_FORMAT, !is_transpose)
164+ << op_name << ": CCE NZ transfer does not support order transpose";
160 165 
161 const int64_t c0 = GetNZInnerCols(tensor_type->dtype_);166 const int64_t c0 = GetNZInnerCols(tensor_type->dtype_);
162 const auto tile_rows = ir::GetConstantDimension(tile_type->shape_[0]);167 const auto tile_rows = ir::GetConstantDimension(tile_type->shape_[0]);
163 const auto tile_cols = ir::GetConstantDimension(tile_type->shape_[1]);168 const auto tile_cols = ir::GetConstantDimension(tile_type->shape_[1]);
164 const auto col_offset = ir::GetConstantDimension(offsets->elements_[ndim - 1]);169 const auto col_offset = ir::GetConstantDimension(offsets->elements_[ndim - 1]);
165 170 
166- CHECK(!tile_rows.has_value() || tile_rows.value() % 16 == 0) << op_name << ": NZ tile rows must be divisible by 16";171+ PRO_CODEGEN_CHECK(ExternalError::INVALID_FORMAT, !tile_rows.has_value() || tile_rows.value() % 16 == 0)
167- CHECK(!tile_cols.has_value() || tile_cols.value() % c0 == 0)172+ << op_name << ": NZ tile rows must be divisible by 16";
173+ PRO_CODEGEN_CHECK(ExternalError::INVALID_FORMAT, !tile_cols.has_value() || tile_cols.value() % c0 == 0)
168 << op_name << ": NZ tile columns must be divisible by C0";174 << op_name << ": NZ tile columns must be divisible by C0";
169- CHECK(!col_offset.has_value() || col_offset.value() % c0 == 0)175+ PRO_CODEGEN_CHECK(ExternalError::INVALID_FORMAT, !col_offset.has_value() || col_offset.value() % c0 == 0)
170 << op_name << ": NZ column offset must be divisible by C0";176 << op_name << ": NZ column offset must be divisible by C0";
171 177 
172 // In a GM transfer, an Acc tile can only appear as the source of store.178 // In a GM transfer, an Acc tile can only appear as the source of store.
@@ -178,8 +184,9 @@ void ValidateNZTransfer(const std::string& op_name, const ir::CallPtr& op, const
178 const auto full_rows = ir::GetConstantDimension(tensor_type->shape_[ndim - 2]);184 const auto full_rows = ir::GetConstantDimension(tensor_type->shape_[ndim - 2]);
179 const auto padded_full_rows = full_rows.has_value() ? std::optional<int64_t>((full_rows.value() + 15) / 16 * 16) :185 const auto padded_full_rows = full_rows.has_value() ? std::optional<int64_t>((full_rows.value() + 15) / 16 * 16) :
180 std::nullopt;186 std::nullopt;
181- CHECK(!padded_full_rows.has_value() || !tile_rows.has_value() || !tile_cols.has_value() ||187+ PRO_CODEGEN_CHECK(ExternalError::INVALID_FORMAT,
182- tile_rows.value() == padded_full_rows.value() || tile_cols.value() <= c0)188+ !padded_full_rows.has_value() || !tile_rows.has_value() || !tile_cols.has_value() ||
189+ tile_rows.value() == padded_full_rows.value() || tile_cols.value() <= c0)
183 << op_name << ": Acc NZ partial-M store spanning multiple N fractals is not supported by direct TSTORE";190 << op_name << ": Acc NZ partial-M store spanning multiple N fractals is not supported by direct TSTORE";
184}191}
185 192 
@@ -254,20 +261,24 @@ size_t FindPrintfConversionIndex(const std::string& format_segment)
254 ++i;261 ++i;
255 continue;262 continue;
256 }263 }
257- CHECK(!(i + 1 < format_segment.size() && format_segment[i + 1] == '%'))264+ PRO_CODEGEN_CHECK(ExternalError::NOT_IMPLEMENTED_ERROR,
265+ !(i + 1 < format_segment.size() && format_segment[i + 1] == '%'))
258 << "debug.printf does not support literal '%%'";266 << "debug.printf does not support literal '%%'";
259 267 
260 size_t j = i + 1;268 size_t j = i + 1;
261- CHECK(j < format_segment.size()) << "debug.printf format ends with an incomplete conversion";269+ PRO_CODEGEN_CHECK(ExternalError::INVALID_VAL, j < format_segment.size())
262- CHECK(format_segment[j] != '-' && format_segment[j] != '+' && format_segment[j] != ' ' &&270+ << "debug.printf format ends with an incomplete conversion";
263- format_segment[j] != '#' && format_segment[j] != '0' && format_segment[j] != '.' &&271+ PRO_CODEGEN_CHECK(ExternalError::NOT_IMPLEMENTED_ERROR,
264- !std::isdigit(static_cast<unsigned char>(format_segment[j])))272+ format_segment[j] != '-' && format_segment[j] != '+' && format_segment[j] != ' ' &&
273+ format_segment[j] != '#' && format_segment[j] != '0' && format_segment[j] != '.' &&
274+ !std::isdigit(static_cast<unsigned char>(format_segment[j])))
265 << "debug.printf does not support flags, width, or precision";275 << "debug.printf does not support flags, width, or precision";
266- CHECK(IsSupportedPrintfConversion(format_segment[j]))276+ PRO_CODEGEN_CHECK(ExternalError::NOT_IMPLEMENTED_ERROR, IsSupportedPrintfConversion(format_segment[j]))
267 << "debug.printf does not support conversion '%" << format_segment[j] << "'";277 << "debug.printf does not support conversion '%" << format_segment[j] << "'";
268 return j;278 return j;
269 }279 }
270- CHECK(false) << "debug.printf format segment must contain a supported conversion";280+ PRO_CODEGEN_CHECK(ExternalError::INVALID_VAL, false)
281+ << "debug.printf format segment must contain a supported conversion";
271 return std::string::npos;282 return std::string::npos;
272}283}
273 284 
@@ -283,7 +294,8 @@ std::vector<PrintfSegment> ParsePrintfSegments(const std::string& format)
283 continue;294 continue;
284 }295 }
285 if (i + 1 < format.size() && format[i + 1] == '%') {296 if (i + 1 < format.size() && format[i + 1] == '%') {
286- CHECK(false) << "debug.printf does not support literal '%%'";297+ PRO_CODEGEN_CHECK(ExternalError::NOT_IMPLEMENTED_ERROR, false)
298+ << "debug.printf does not support literal '%%'";
287 }299 }
288 300 
289 size_t j = FindPrintfConversionIndex(format.substr(i)) + i;301 size_t j = FindPrintfConversionIndex(format.substr(i)) + i;
@@ -17,6 +17,7 @@
17#include "core/logging.h"17#include "core/logging.h"
18#include "tilefwk/error.h"18#include "tilefwk/error.h"
19#include "ir/expr.h"19#include "ir/expr.h"
20+#include "pypto_pro/error.h"
20 21 
21namespace pypto {22namespace pypto {
22 23 
@@ -24,7 +25,8 @@ namespace codegen {
24 25 
25std::string CodeContext::GetVarName(const ir::VarPtr& var)26std::string CodeContext::GetVarName(const ir::VarPtr& var)
26{27{
27- CHECK(var != nullptr) << "Cannot get name for null variable";28+ PRO_CODEGEN_CHECK(npu::tile_fwk::InternalError::CODEGEN_INNER_ERROR, var != nullptr)
29+ << "Cannot get name for null variable";
28 auto it = name_to_cpp_.find(var->name_);30 auto it = name_to_cpp_.find(var->name_);
29 if (it != name_to_cpp_.end()) {31 if (it != name_to_cpp_.end()) {
30 return it->second;32 return it->second;
@@ -77,8 +79,10 @@ bool CodeContext::IsAutoRegistered(const std::string& cpp_name) const { return a
77 79 
78void CodeContext::RegisterVar(const ir::VarPtr& var, const std::string& cpp_name)80void CodeContext::RegisterVar(const ir::VarPtr& var, const std::string& cpp_name)
79{81{
80- CHECK(var != nullptr) << "Cannot register null variable";82+ PRO_CODEGEN_CHECK(npu::tile_fwk::InternalError::CODEGEN_INNER_ERROR, var != nullptr)
81- CHECK(!cpp_name.empty()) << "Cannot register variable with empty name";83+ << "Cannot register null variable";
84+ PRO_CODEGEN_CHECK(npu::tile_fwk::InternalError::CODEGEN_INNER_ERROR, !cpp_name.empty())
85+ << "Cannot register variable with empty name";
82 86 
83 // Check if this name is already registered (suppress for array access and alias optimizations)87 // Check if this name is already registered (suppress for array access and alias optimizations)
84 auto it = name_to_cpp_.find(var->name_);88 auto it = name_to_cpp_.find(var->name_);
@@ -95,7 +99,8 @@ void CodeContext::Clear() { name_to_cpp_.clear(); }
95 99 
96std::string CodeContext::SanitizeName(const ir::VarPtr& var) const100std::string CodeContext::SanitizeName(const ir::VarPtr& var) const
97{101{
98- CHECK(var != nullptr) << "Cannot sanitize null variable";102+ PRO_CODEGEN_CHECK(npu::tile_fwk::InternalError::CODEGEN_INNER_ERROR, var != nullptr)
103+ << "Cannot sanitize null variable";
99 auto ir_name = var->name_;104 auto ir_name = var->name_;
100 if (ir_name.empty()) {105 if (ir_name.empty()) {
101 return "var";106 return "var";
@@ -14,6 +14,7 @@
14#include <string>14#include <string>
15 15 
16#include "core/logging.h"16#include "core/logging.h"
17+#include "pypto_pro/error.h"
17 18 
18namespace pypto {19namespace pypto {
19 20 
@@ -31,7 +32,8 @@ void CodeEmitter::IncreaseIndent() { indent_level_++; }
31 32 
32void CodeEmitter::DecreaseIndent()33void CodeEmitter::DecreaseIndent()
33{34{
34- INTERNAL_CHECK(indent_level_ > 0) << "Internal error: cannot decrease indent level below 0";35+ PRO_CODEGEN_INTERNAL_CHECK(npu::tile_fwk::InternalError::CODEGEN_INNER_ERROR, indent_level_ > 0)
36+ << "Internal error: cannot decrease indent level below 0";
35 indent_level_--;37 indent_level_--;
36}38}
37 39 
@@ -26,11 +26,13 @@
26#include "ir/scalar_expr.h"26#include "ir/scalar_expr.h"
27#include "ir/scalar_expr_ops.h"27#include "ir/scalar_expr_ops.h"
28#include "ir/type.h"28#include "ir/type.h"
29+#include "pypto_pro/error.h"
29#include "tilefwk/error.h"30#include "tilefwk/error.h"
30 31 
31namespace pypto {32namespace pypto {
32 33 
33namespace codegen {34namespace codegen {
35+using npu::tile_fwk::ExternalError; // Short enum names in the Enum field (log spec 4.4)
34 36 
35namespace {37namespace {
36 38 
@@ -61,7 +63,7 @@ std::string ConvertTilePadToPTOValue(ir::TilePad pad)
61 case ir::TilePad::min:63 case ir::TilePad::min:
62 return "PadValue::Min";64 return "PadValue::Min";
63 default:65 default:
64- throw pypto::ir::ValueError("Invalid TilePad value");66+ PRO_CODEGEN_THROW(::pypto::ir::ValueError, ExternalError::INVALID_ARGUMENT) << "Invalid TilePad value";
65 }67 }
66}68}
67 69 
@@ -75,7 +77,7 @@ std::string ConvertCompactModeToPTOValue(ir::CompactMode compact)
75 case ir::CompactMode::row_plus_one:77 case ir::CompactMode::row_plus_one:
76 return "CompactMode::RowPlusOne";78 return "CompactMode::RowPlusOne";
77 default:79 default:
78- throw pypto::ir::ValueError("Invalid CompactMode value");80+ PRO_CODEGEN_THROW(::pypto::ir::ValueError, ExternalError::INVALID_ARGUMENT) << "Invalid CompactMode value";
79 }81 }
80}82}
81 83 
@@ -213,9 +215,10 @@ std::string TypeConverter::ConvertMemorySpaceToTileType(ir::MemorySpace space) c
213 return "TileType::ScaleRight";215 return "TileType::ScaleRight";
214 case ir::MemorySpace::DDR:216 case ir::MemorySpace::DDR:
215 // DDR is for GlobalTensor, not Tile - should not reach here217 // DDR is for GlobalTensor, not Tile - should not reach here
216- throw pypto::ir::ValueError("DDR is for GlobalTensor, not Tile");218+ PRO_CODEGEN_THROW(::pypto::ir::ValueError, ExternalError::INVALID_VAL)
219+ << "DDR is for GlobalTensor, not Tile";
217 default:220 default:
218- throw pypto::ir::ValueError("Invalid MemorySpace value");221+ PRO_CODEGEN_THROW(::pypto::ir::ValueError, ExternalError::INVALID_ARGUMENT) << "Invalid MemorySpace value";
219 }222 }
220}223}
221 224 
@@ -245,12 +248,13 @@ std::string TypeConverter::ConvertPipeType(ir::PipeType pipe) const
245 if (pipe == ir::PipeType::ALL) {248 if (pipe == ir::PipeType::ALL) {
246 return "PIPE_ALL";249 return "PIPE_ALL";
247 }250 }
248- throw pypto::ir::ValueError("Invalid PipeType value");251+ PRO_CODEGEN_THROW(::pypto::ir::ValueError, ExternalError::INVALID_ARGUMENT) << "Invalid PipeType value";
249}252}
250 253 
251std::string TypeConverter::ConvertEventId(int event_id) const254std::string TypeConverter::ConvertEventId(int event_id) const
252{255{
253- CHECK(event_id >= 0 && event_id <= 7) << "Event ID must be in range [0, 7], got " << event_id;256+ PRO_CODEGEN_CHECK(ExternalError::OUT_OF_RANGE, event_id >= 0 && event_id <= 7)
257+ << "Event ID must be in range [0, 7], got " << event_id;
254 return "EVENT_ID" + std::to_string(event_id);258 return "EVENT_ID" + std::to_string(event_id);
255}259}
256 260 
@@ -270,21 +274,21 @@ std::string TypeConverter::ConvertTileLayout(ir::TileLayout layout) const
270 case ir::TileLayout::col_major:274 case ir::TileLayout::col_major:
271 return "ColMajor";275 return "ColMajor";
272 default:276 default:
273- throw pypto::ir::ValueError("Invalid TileLayout value");277+ PRO_CODEGEN_THROW(::pypto::ir::ValueError, ExternalError::INVALID_FORMAT) << "Invalid TileLayout value";
274 }278 }
275}279}
276 280 
277std::string TypeConverter::GenerateShapeType(const std::vector<int64_t>& dims) const281std::string TypeConverter::GenerateShapeType(const std::vector<int64_t>& dims) const
278{282{
279- CHECK(!dims.empty()) << "Cannot generate Shape type for empty dimensions";283+ PRO_CODEGEN_CHECK(ExternalError::INVALID_SHAPE, !dims.empty()) << "Cannot generate Shape type for empty dimensions";
280 284 
281 std::ostringstream oss;285 std::ostringstream oss;
282 oss << "pto::Shape<";286 oss << "pto::Shape<";
283 287 
284 // Pad to 5 dimensions with leading 1s288 // Pad to 5 dimensions with leading 1s
285 const size_t target_dims = 5;289 const size_t target_dims = 5;
286- CHECK(dims.size() <= target_dims) << "Cannot generate Shape with more than " << target_dims << " dimensions, got "290+ PRO_CODEGEN_CHECK(ExternalError::INVALID_SHAPE, dims.size() <= target_dims)
287- << dims.size();291+ << "Cannot generate Shape with more than " << target_dims << " dimensions, got " << dims.size();
288 292 
289 // Add leading 1s for padding293 // Add leading 1s for padding
290 for (size_t i = 0; i < target_dims - dims.size(); ++i) {294 for (size_t i = 0; i < target_dims - dims.size(); ++i) {
@@ -305,15 +309,15 @@ std::string TypeConverter::GenerateShapeType(const std::vector<int64_t>& dims) c
305 309 
306std::string TypeConverter::GenerateStrideType(const std::vector<int64_t>& shape) const310std::string TypeConverter::GenerateStrideType(const std::vector<int64_t>& shape) const
307{311{
308- CHECK(!shape.empty()) << "Cannot generate Stride type for empty shape";312+ PRO_CODEGEN_CHECK(ExternalError::INVALID_SHAPE, !shape.empty()) << "Cannot generate Stride type for empty shape";
309 313 
310 std::ostringstream oss;314 std::ostringstream oss;
311 oss << "pto::Stride<";315 oss << "pto::Stride<";
312 316 
313 // Pad to 5 dimensions with leading 1s317 // Pad to 5 dimensions with leading 1s
314 const size_t target_dims = 5;318 const size_t target_dims = 5;
315- CHECK(shape.size() <= target_dims) << "Cannot generate Stride with more than " << target_dims << " dimensions, got "319+ PRO_CODEGEN_CHECK(ExternalError::INVALID_SHAPE, shape.size() <= target_dims)
316- << shape.size();320+ << "Cannot generate Stride with more than " << target_dims << " dimensions, got " << shape.size();
317 321 
318 // Add leading 1s for padding322 // Add leading 1s for padding
319 for (size_t i = 0; i < target_dims - shape.size(); ++i) {323 for (size_t i = 0; i < target_dims - shape.size(); ++i) {
@@ -0,0 +1,71 @@
1+/**
2+ * Copyright (c) 2026 Huawei Technologies Co., Ltd.
3+ * This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4+ * CANN Open Software License Agreement Version 2.0 (the "License").
5+ * Please refer to the License for details. You may not use this file except in compliance with the License.
6+ * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7+ * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8+ * See LICENSE in the root of the software repository for the full text of the License.
9+ */
10+ 
11+/*!
12+ * \file error.cpp
13+ * \brief First-line rendering and the ambient DSL location.
14+ */
15+ 
16+#include "pypto_pro/error.h"
17+ 
18+#include <iomanip>
19+#include <sstream>
20+ 
21+namespace pypto {
22+namespace pro {
23+namespace {
24+ 
25+/**
26+ * \brief The DSL location in effect on this thread.
27+ *
28+ * thread_local because compilation may run on several threads and a span names
29+ * one kernel statement.
30+ */
31+thread_local ir::Span g_currentSpan;
32+ 
33+constexpr unsigned CODE_MASK = 0xFFFFFU;
34+constexpr int CODE_WIDTH = 5;
35+ 
36+} // namespace
37+ 
38+const ir::Span& CurrentSpan() { return g_currentSpan; }
39+ 
40+SpanScope::SpanScope(const ir::Span& span) : prev_(g_currentSpan)
41+{
42+ // An invalid span would erase the enclosing statement's location: synthesised
43+ // nodes have no source of their own.
44+ if (!span.IsUnknown() && span.IsValid()) {
45+ g_currentSpan = span;
46+ }
47+}
48+ 
49+SpanScope::~SpanScope() { g_currentSpan = prev_; }
50+ 
51+std::string ErrHead(const char* file, int line, const char* module, unsigned code, const char* codeName)
52+{
53+ std::ostringstream oss;
54+ oss << "[" << file << ":" << line << "][" << module << "]:"
55+ << "ErrCode: F" << std::uppercase << std::hex << std::setw(CODE_WIDTH) << std::setfill('0')
56+ << (code & CODE_MASK) << std::dec << "! Enum: " << codeName << ". ";
57+ return oss.str();
58+}
59+ 
60+std::string LocLine(const ir::Span& span)
61+{
62+ if (span.IsUnknown() || !span.IsValid()) {
63+ return "";
64+ }
65+ std::ostringstream oss;
66+ oss << "\n --> " << span.Filename() << ":" << span.BeginLine() << ":" << span.BeginColumn();
67+ return oss.str();
68+}
69+ 
70+} // namespace pro
71+} // namespace pypto
@@ -236,7 +236,10 @@ TEST_F(WrapManagerTest, ResolveDepForOneMix_CoreAvailable_SendsTasks)
236 int sendCount = 0;236 int sendCount = 0;
237 wm_.SendTaskToAiCore = [&sendCount](SchDeviceTaskContext*, CoreType, int, uint64_t) { sendCount++; };237 wm_.SendTaskToAiCore = [&sendCount](SchDeviceTaskContext*, CoreType, int, uint64_t) { sendCount++; };
238 238 
239- uint32_t taskIds[MAX_WRAP_TASK_NUM] = {0x100, 0x200, 0x300};239+ // ResolveDepForOneMix decodes taskIds into (funcId, opIndex) to look up
240+ // opWrapList, so they have to be built with MakeTaskID: a raw 0x100 carries
241+ // opIndex 256 and would index past the four-element list below.
242+ uint32_t taskIds[MAX_WRAP_TASK_NUM] = {MakeTaskID(0, 0), MakeTaskID(0, 1), MakeTaskID(0, 2)};
240 wm_.ResolveDepForOneMix(taskIds, static_cast<uint8_t>(MixResourceType::MIX_1C2V), 0);243 wm_.ResolveDepForOneMix(taskIds, static_cast<uint8_t>(MixResourceType::MIX_1C2V), 0);
241 244 
242 EXPECT_EQ(sendCount, 3);245 EXPECT_EQ(sendCount, 3);
@@ -257,7 +260,10 @@ TEST_F(WrapManagerTest, ResolveDepForOneMix_CoreNotAvailable_PushesToQueue)
257 pendingIds_[aivIdx0] = 0x999;260 pendingIds_[aivIdx0] = 0x999;
258 pendingIds_[aivIdx1] = 0x999;261 pendingIds_[aivIdx1] = 0x999;
259 262 
260- uint32_t taskIds[MAX_WRAP_TASK_NUM] = {0x100, 0x200, 0x300};263+ // ResolveDepForOneMix decodes taskIds into (funcId, opIndex) to look up
264+ // opWrapList, so they have to be built with MakeTaskID: a raw 0x100 carries
265+ // opIndex 256 and would index past the four-element list below.
266+ uint32_t taskIds[MAX_WRAP_TASK_NUM] = {MakeTaskID(0, 0), MakeTaskID(0, 1), MakeTaskID(0, 2)};
261 wm_.ResolveDepForOneMix(taskIds, static_cast<uint8_t>(MixResourceType::MIX_1C2V), 0);267 wm_.ResolveDepForOneMix(taskIds, static_cast<uint8_t>(MixResourceType::MIX_1C2V), 0);
262 268 
263 EXPECT_EQ(sendCount, 0);269 EXPECT_EQ(sendCount, 0);
Rpython/pypto_pro/language/parser/diagnostics/_error_codes.py→python/pypto_pro/_error_codes.py+25-4
@@ -18,24 +18,45 @@ __all__ = ["ErrorCode", "get_error_code"]
18 18 
19from enum import IntEnum19from enum import IntEnum
20 20 
21-from pypto.pypto_impl import ExternalError21+from pypto.pypto_impl import ExternalError, InternalErrorCode
22 22 
23_PYPTO_ERROR_CODE_PREFIX = 0xF0000023_PYPTO_ERROR_CODE_PREFIX = 0xF00000
24 24 
25 25 
26-def _to_pypto_error_code(error: ExternalError) -> int:26+def _to_pypto_error_code(error: ExternalError | InternalErrorCode) -> int:
27- """Convert a centrally allocated external error to its PyPTO error number."""27+ """Convert a centrally allocated error to its PyPTO error number."""
28 return _PYPTO_ERROR_CODE_PREFIX | int(error)28 return _PYPTO_ERROR_CODE_PREFIX | int(error)
29 29 
30 30 
31class ErrorCode(IntEnum):31class ErrorCode(IntEnum):
32- """Parser error codes backed by the centrally allocated PyPTO codes."""32+ """PyPTO error codes, backed by the centrally allocated codes in error_code.h.
33 33 
34+ The values are shared with pypto.
35+ """
36+ 
37+ # External: the user wrote something the framework cannot accept.
34 INVALID_TYPE = _to_pypto_error_code(ExternalError.INVALID_TYPE)38 INVALID_TYPE = _to_pypto_error_code(ExternalError.INVALID_TYPE)
35 INVALID_VAL = _to_pypto_error_code(ExternalError.INVALID_VAL)39 INVALID_VAL = _to_pypto_error_code(ExternalError.INVALID_VAL)
40+ RUNTIME_ERROR = _to_pypto_error_code(ExternalError.RUNTIME_ERROR)
36 NAME_ERROR = _to_pypto_error_code(ExternalError.NAME_ERROR)41 NAME_ERROR = _to_pypto_error_code(ExternalError.NAME_ERROR)
37 NOT_IMPLEMENTED_ERROR = _to_pypto_error_code(ExternalError.NOT_IMPLEMENTED_ERROR)42 NOT_IMPLEMENTED_ERROR = _to_pypto_error_code(ExternalError.NOT_IMPLEMENTED_ERROR)
43+ KEY_ERROR = _to_pypto_error_code(ExternalError.KEY_ERROR)
38 INVALID_OPERATION = _to_pypto_error_code(ExternalError.INVALID_OPERATION)44 INVALID_OPERATION = _to_pypto_error_code(ExternalError.INVALID_OPERATION)
45+ OUT_OF_RANGE = _to_pypto_error_code(ExternalError.OUT_OF_RANGE)
46+ BAD_FD = _to_pypto_error_code(ExternalError.BAD_FD)
47+ DYNAMIC_SHAPE_COMPUTE_UNSUPPORTED = _to_pypto_error_code(ExternalError.DYNAMIC_SHAPE_COMPUTE_UNSUPPORTED)
48+ INVALID_SHAPE = _to_pypto_error_code(ExternalError.INVALID_SHAPE)
49+ INVALID_TILE = _to_pypto_error_code(ExternalError.INVALID_TILE)
50+ INVALID_FORMAT = _to_pypto_error_code(ExternalError.INVALID_FORMAT)
51+ INVALID_ARGUMENT = _to_pypto_error_code(ExternalError.INVALID_ARGUMENT)
52+ COMMON_EXTERNAL_ERROR = _to_pypto_error_code(ExternalError.COMMON_EXTERNAL_ERROR)
53+ 
54+ # Internal: the framework broke its own invariant. Only three stages exist
55+ # in pypto_pro; everything outside pass and codegen uses COMMON.
56+ COMMON_INNER_ERROR = _to_pypto_error_code(InternalErrorCode.COMMON_INNER_ERROR)
57+ PASS_INNER_ERROR = _to_pypto_error_code(InternalErrorCode.PASS_INNER_ERROR)
58+ CODEGEN_INNER_ERROR = _to_pypto_error_code(InternalErrorCode.CODEGEN_INNER_ERROR)
59+ 
39 UNKNOWN = _to_pypto_error_code(ExternalError.UNKNOWN)60 UNKNOWN = _to_pypto_error_code(ExternalError.UNKNOWN)
40 61 
41 62 
@@ -0,0 +1,616 @@
1+#!/usr/bin/env python3
2+# coding: utf-8
3+# Copyright (c) 2026 Huawei Technologies Co., Ltd.
4+# This program is free software, 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+# Please refer to the License for details. You may not use this file except in compliance with the License.
7+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
8+# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 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+"""PyPTO-Pro exceptions: one class per error code.
13+ 
14+The class *is* the error code. Each class also inherits the builtin exception
15+that matches its semantics, so ``except ValueError`` keeps working for callers
16+that do not know about this hierarchy.
17+ 
18+Raising::
19+ 
20+ raise InvalidArgument(f"block.load requires 3 args, got {n}", span=span)
21+ 
22+The error code needs no argument (the class carries it), the module tag is
23+derived from the caller's file, and the DSL location comes from the ambient
24+``current_span``, so a call site states only what went wrong.
25+"""
26+ 
27+from __future__ import annotations
28+ 
29+__all__ = [
30+ "PyptoProError",
31+ "argument_span",
32+ "remembered_span",
33+ "span_of",
34+ "span_source",
35+ "current_span",
36+ "error_class_of_spec_message",
37+ "message_of",
38+ # One class per error code
39+ "InvalidType",
40+ "InvalidVal",
41+ "RuntimeFailure",
42+ "NameNotFound",
43+ "NotSupported",
44+ "KeyNotFound",
45+ "InvalidOperation",
46+ "OutOfRange",
47+ "BadFd",
48+ "DynamicShapeUnsupported",
49+ "InvalidShape",
50+ "InvalidTile",
51+ "InvalidFormat",
52+ "InvalidArgument",
53+ "CommonExternal",
54+ "CommonInner",
55+ "PassInner",
56+ "CodegenInner",
57+]
58+ 
59+import contextlib
60+import contextvars
61+import os
62+import re
63+import sys
64+ 
65+from pypto.error import PyptoError
66+from pypto.pypto_impl import ir
67+ 
68+from ._error_codes import ErrorCode
69+ 
70+# ---------------------------------------------------------------------------
71+# Module tag: the compile stage a message came from (log spec 4.2)
72+# ---------------------------------------------------------------------------
73+ 
74+# Longest path fragment wins, so nested packages override their parent.
75+_MODULE_BY_PATH = (
76+ ("pypto_pro/runtime/pipeline", "PRO_PIPELINE"),
77+ ("pypto_pro/runtime/opc", "PRO_COMPILE"),
78+ ("pypto_pro/runtime", "PRO_RUNTIME"),
79+ ("pypto_pro/language", "PRO_PARSER"),
80+ ("pypto_pro/ir", "PRO_IR"),
81+)
82+_DEFAULT_MODULE = "PRO_COMMON"
83+ 
84+ 
85+def _module_of(filename: str) -> str:
86+ """Map a source path to its ``PRO_*`` module tag."""
87+ normalized = filename.replace(os.sep, "/")
88+ for fragment, module in _MODULE_BY_PATH:
89+ if fragment in normalized:
90+ return module
91+ return _DEFAULT_MODULE
92+ 
93+ 
94+def _origin_of_caller(depth: int) -> tuple[str, str]:
95+ """Module tag and ``basename:lineno`` of the frame ``depth`` levels up.
96+ 
97+ Both come from the same frame -- the one that raised -- so the first line can
98+ name the framework source the C++ side names with ``__FILE__``/``__LINE__``.
99+ """
100+ try:
@@ -22,6 +22,8 @@ import inspect
22from pypto.pypto_impl import ir as _ir22from pypto.pypto_impl import ir as _ir
23from pypto.pypto_impl.ir import DataType23from pypto.pypto_impl.ir import DataType
24 24 
25+from .._errors import InvalidType
26+ 
25 27 
26def _get_span_or_capture(span: _ir.Span | None = None, frame_offset: int = 1) -> _ir.Span:28def _get_span_or_capture(span: _ir.Span | None = None, frame_offset: int = 1) -> _ir.Span:
27 """Get explicit span or capture from caller.29 """Get explicit span or capture from caller.
@@ -76,8 +78,8 @@ def _normalize_expr(
76 IR expression node78 IR expression node
77 79 
78 Raises:80 Raises:
79- TypeError: If value is not int, float, or ir.Expr81+ InvalidType: If value is not int, float, or ir.Expr
80- FinalRejectionError: If an integer is outside the range the IR can carry82+ OutOfRange: If an integer is outside the range the IR can carry
81 """83 """
82 if isinstance(value, _ir.Expr):84 if isinstance(value, _ir.Expr):
83 return value85 return value
@@ -91,7 +93,7 @@ def _normalize_expr(
91 elif isinstance(value, float):93 elif isinstance(value, float):
92 return _ir.ConstFloat(value, float_dtype, actual_span)94 return _ir.ConstFloat(value, float_dtype, actual_span)
93 else:95 else:
94- raise TypeError(f"Cannot convert {type(value)} to IR expression")96+ raise InvalidType(f"Cannot convert {type(value)} to IR expression")
95 97 
96 98 
97def _normalize_shape(99def _normalize_shape(
@@ -142,7 +144,7 @@ def _to_make_tuple(
142 for i in range(len(value_type.types))144 for i in range(len(value_type.types))
143 ]145 ]
144 return _ir.MakeTuple(elements, actual_span)146 return _ir.MakeTuple(elements, actual_span)
145- raise TypeError(147+ raise InvalidType(
146 f"Cannot convert Expr of type {value_type} to an offset tuple; expected a MakeTuple or a tuple-typed value"148 f"Cannot convert Expr of type {value_type} to an offset tuple; expected a MakeTuple or a tuple-typed value"
147 )149 )
148 elements = [_normalize_expr(v, actual_span) for v in value]150 elements = [_normalize_expr(v, actual_span) for v in value]
@@ -37,6 +37,7 @@ from pypto.pypto_impl import ir
37from pypto.pypto_impl.ir import DataType37from pypto.pypto_impl.ir import DataType
38from pypto.pypto_impl.ir import IRBuilder as CppIRBuilder38from pypto.pypto_impl.ir import IRBuilder as CppIRBuilder
39 39 
40+from .._errors import CommonInner, InvalidOperation, InvalidShape, InvalidType, OutOfRange
40from ._utils import _normalize_expr41from ._utils import _normalize_expr
41 42 
42 43 
@@ -437,7 +438,7 @@ class IRBuilder:
437 # Recreate the Call with the correct return type438 # Recreate the Call with the correct return type
438 value_expr = ir.Call(value_expr.name, value_expr.args, return_types[0], actual_span)439 value_expr = ir.Call(value_expr.name, value_expr.args, return_types[0], actual_span)
439 elif len(return_types) > 1:440 elif len(return_types) > 1:
440- raise ValueError(441+ raise InvalidShape(
441 f"Function '{value_expr.name}' returns {len(return_types)} values, "442 f"Function '{value_expr.name}' returns {len(return_types)} values, "
442 f"but let() can only assign single return values. "443 f"but let() can only assign single return values. "
443 f"Use explicit tuple unpacking or multiple let() statements."444 f"Use explicit tuple unpacking or multiple let() statements."
@@ -455,7 +456,7 @@ class IRBuilder:
455 if not isinstance(inferred_type, ir.UnknownType) and builtins.type(var_type) is not builtins.type(456 if not isinstance(inferred_type, ir.UnknownType) and builtins.type(var_type) is not builtins.type(
456 inferred_type457 inferred_type
457 ):458 ):
458- raise TypeError(459+ raise InvalidType(
459 f"Type override for '{name}' is incompatible: "460 f"Type override for '{name}' is incompatible: "
460 f"inferred {builtins.type(inferred_type).__name__} "461 f"inferred {builtins.type(inferred_type).__name__} "
461 f"but override is {builtins.type(var_type).__name__}"462 f"but override is {builtins.type(var_type).__name__}"
@@ -792,7 +793,7 @@ class FunctionBuilder:
792 Function: The completed function IR node (or None if not yet finalized)793 Function: The completed function IR node (or None if not yet finalized)
793 """794 """
794 if self.result is None:795 if self.result is None:
795- raise RuntimeError("Builder result is not available")796+ raise CommonInner("Builder result is not available")
796 return self.result797 return self.result
797 798 
798 799 
@@ -844,7 +845,7 @@ class _LoopBuilderBase:
844 inferred_type = init_expr.type845 inferred_type = init_expr.type
845 846 
846 if iter_type is not None and iter_type != inferred_type:847 if iter_type is not None and iter_type != inferred_type:
847- raise ValueError(848+ raise InvalidType(
848 f"Type mismatch in iter_arg for '{name}':\n"849 f"Type mismatch in iter_arg for '{name}':\n"
849 f" Inferred type: {inferred_type}\n"850 f" Inferred type: {inferred_type}\n"
850 f" Provided type: {iter_type}"851 f" Provided type: {iter_type}"
@@ -887,14 +888,14 @@ class _LoopBuilderBase:
887 888 
888 if var_type is None:889 if var_type is None:
889 if inferred_type is None:890 if inferred_type is None:
890- raise ValueError(891+ raise CommonInner(
891 f"Cannot infer type for return_var '{name}': "892 f"Cannot infer type for return_var '{name}': "
892 f"no corresponding iter_arg found. Please provide explicit type."893 f"no corresponding iter_arg found. Please provide explicit type."
893 )894 )
894 final_type = inferred_type895 final_type = inferred_type
895 else:896 else:
896 if inferred_type is not None and var_type != inferred_type:897 if inferred_type is not None and var_type != inferred_type:
897- raise ValueError(898+ raise InvalidType(
898 f"Type mismatch in return_var '{name}':\n"899 f"Type mismatch in return_var '{name}':\n"
899 f" Inferred type (from iter_arg): {inferred_type}\n"900 f" Inferred type (from iter_arg): {inferred_type}\n"
900 f" Provided type: {var_type}"901 f" Provided type: {var_type}"
@@ -947,9 +948,9 @@ class ForLoopBuilder(_LoopBuilderBase):
947 >>> result2 = loop.output(1)948 >>> result2 = loop.output(1)
948 """949 """
949 if self.result is None:950 if self.result is None:
950- raise RuntimeError("For loop not yet complete")951+ raise InvalidOperation("For loop not yet complete")
951 if index >= len(self.result.return_vars):952 if index >= len(self.result.return_vars):
952- raise IndexError(953+ raise OutOfRange(
953 f"Return variable index {index} out of range (for loop has {len(self.result.return_vars)} return vars)"954 f"Return variable index {index} out of range (for loop has {len(self.result.return_vars)} return vars)"
954 )955 )
955 return self.result.return_vars[index]956 return self.result.return_vars[index]
@@ -976,7 +977,7 @@ class ForLoopBuilder(_LoopBuilderBase):
976 >>> sum_result, prod_result = loop.outputs() # Get all return variables977 >>> sum_result, prod_result = loop.outputs() # Get all return variables
977 """978 """
978 if self.result is None:979 if self.result is None:
979- raise RuntimeError("For loop not yet complete")980+ raise InvalidOperation("For loop not yet complete")
980 return list(self.result.return_vars)981 return list(self.result.return_vars)
981 982 
982 def get_result(self) -> ir.ForStmt:983 def get_result(self) -> ir.ForStmt:
@@ -986,7 +987,7 @@ class ForLoopBuilder(_LoopBuilderBase):
986 ForStmt: The completed for loop IR node987 ForStmt: The completed for loop IR node
987 """988 """
988 if self.result is None:989 if self.result is None:
989- raise RuntimeError("Builder result is not available")990+ raise CommonInner("Builder result is not available")
990 return self.result991 return self.result
991 992 
992 def _add_iter_arg(self, iter_arg: ir.IterArg) -> None:993 def _add_iter_arg(self, iter_arg: ir.IterArg) -> None:
@@ -1045,9 +1046,9 @@ class WhileLoopBuilder(_LoopBuilderBase):
1045 >>> result = loop.output() # Get the first return variable1046 >>> result = loop.output() # Get the first return variable
1046 """1047 """
1047 if self.result is None:1048 if self.result is None:
1048- raise RuntimeError("While loop not yet complete")1049+ raise InvalidOperation("While loop not yet complete")
1049 if index >= len(self.result.return_vars):1050 if index >= len(self.result.return_vars):
1050- raise IndexError(1051+ raise OutOfRange(
1051 f"Return variable index {index} out of range "1052 f"Return variable index {index} out of range "
1052 f"(while loop has {len(self.result.return_vars)} return vars)"1053 f"(while loop has {len(self.result.return_vars)} return vars)"
1053 )1054 )
@@ -1075,7 +1076,7 @@ class WhileLoopBuilder(_LoopBuilderBase):
1075 >>> x_result, y_result = loop.outputs() # Get all return variables1076 >>> x_result, y_result = loop.outputs() # Get all return variables
1076 """1077 """
1077 if self.result is None:1078 if self.result is None:
1078- raise RuntimeError("While loop not yet complete")1079+ raise InvalidOperation("While loop not yet complete")
1079 return list(self.result.return_vars)1080 return list(self.result.return_vars)
1080 1081 
1081 def get_result(self) -> ir.WhileStmt:1082 def get_result(self) -> ir.WhileStmt:
@@ -1085,7 +1086,7 @@ class WhileLoopBuilder(_LoopBuilderBase):
1085 WhileStmt: The completed while loop IR node1086 WhileStmt: The completed while loop IR node
1086 """1087 """
1087 if self.result is None:1088 if self.result is None:
1088- raise RuntimeError("Builder result is not available")1089+ raise CommonInner("Builder result is not available")
1089 return self.result1090 return self.result
1090 1091 
1091 def _add_iter_arg(self, iter_arg: ir.IterArg) -> None:1092 def _add_iter_arg(self, iter_arg: ir.IterArg) -> None:
@@ -1114,7 +1115,7 @@ class SectionBuilder:
1114 SectionStmt: The completed section statement IR node1115 SectionStmt: The completed section statement IR node
1115 """1116 """
1116 if self.result is None:1117 if self.result is None:
1117- raise RuntimeError("Builder result is not available")1118+ raise CommonInner("Builder result is not available")
1118 return self.result1119 return self.result
1119 1120 
1120 1121 
@@ -1190,9 +1191,9 @@ class IfStmtBuilder:
1190 >>> result2 = if_builder.output(1)1191 >>> result2 = if_builder.output(1)
1191 """1192 """
1192 if self.result is None:1193 if self.result is None:
1193- raise RuntimeError("If statement not yet complete")1194+ raise CommonInner("If statement not yet complete")
1194 if index >= len(self.result.return_vars):1195 if index >= len(self.result.return_vars):
1195- raise IndexError(1196+ raise OutOfRange(
1196 f"Return variable index {index} out of range "1197 f"Return variable index {index} out of range "
1197 f"(if statement has {len(self.result.return_vars)} return vars)"1198 f"(if statement has {len(self.result.return_vars)} return vars)"
1198 )1199 )
@@ -1218,7 +1219,7 @@ class IfStmtBuilder:
1218 >>> x, y = if_builder.outputs() # Get all return variables1219 >>> x, y = if_builder.outputs() # Get all return variables
1219 """1220 """
1220 if self.result is None:1221 if self.result is None:
1221- raise RuntimeError("If statement not yet complete")1222+ raise CommonInner("If statement not yet complete")
1222 return list(self.result.return_vars)1223 return list(self.result.return_vars)
1223 1224 
1224 def get_result(self) -> ir.IfStmt:1225 def get_result(self) -> ir.IfStmt:
@@ -1228,7 +1229,7 @@ class IfStmtBuilder:
1228 IfStmt: The completed if statement IR node1229 IfStmt: The completed if statement IR node
1229 """1230 """
1230 if self.result is None:1231 if self.result is None:
1231- raise RuntimeError("Builder result is not available")1232+ raise CommonInner("Builder result is not available")
1232 return self.result1233 return self.result
1233 1234 
1234 1235 
@@ -1262,5 +1263,5 @@ class ProgramBuilder:
1262 AssertionError: If called before program is complete1263 AssertionError: If called before program is complete
1263 """1264 """
1264 if self.result is None:1265 if self.result is None:
1265- raise RuntimeError("Program not yet complete")1266+ raise CommonInner("Program not yet complete")
1266 return self.result1267 return self.result
@@ -25,6 +25,8 @@ from dataclasses import dataclass, field
25 25 
26from pypto.pypto_impl import ir as _ir_core26from pypto.pypto_impl import ir as _ir_core
27 27 
28+from ..._errors import InvalidOperation, current_span
29+ 
28_OP_REGISTRY: dict[str, Callable] = {}30_OP_REGISTRY: dict[str, Callable] = {}
29 31 
30 32 
@@ -37,7 +39,7 @@ def op_impl(name: str) -> Callable:
37 39 
38 def decorator(func: Callable) -> Callable:40 def decorator(func: Callable) -> Callable:
39 if name in _OP_REGISTRY:41 if name in _OP_REGISTRY:
40- raise ValueError(f"Duplicate op_impl registration: '{name}'")42+ raise InvalidOperation(f"Duplicate op_impl registration: '{name}'")
41 _OP_REGISTRY[name] = func43 _OP_REGISTRY[name] = func
42 return func44 return func
43 45 
@@ -74,9 +76,13 @@ def _make_handler(spec: OpSpec) -> Callable:
74 kwargs = self.parse_op_kwargs(call) if spec.parse_kwargs else {}76 kwargs = self.parse_op_kwargs(call) if spec.parse_kwargs else {}
75 for hook in spec.pre_hooks:77 for hook in spec.pre_hooks:
76 hook(self, call, kwargs)78 hook(self, call, kwargs)
77- if spec.builder is not None:79+ # Publish where the caller wrote each argument, so a builder that rejects
78- return spec.builder(*args, **kwargs, span=span)80+ # one can point at that argument rather than at the whole call. Every
79- return _ir_core.create_op_call(spec.ir_name, args, kwargs, span)81+ # @op_impl operator is dispatched here, so this one site covers them all.
82+ with current_span(span, self.span_tracker.argument_spans(call)):
83+ if spec.builder is not None:
84+ return spec.builder(*args, **kwargs, span=span)
85+ return _ir_core.create_op_call(spec.ir_name, args, kwargs, span)
80 86 
81 return handler87 return handler
82 88 
@@ -85,5 +91,5 @@ def register_table(specs: dict[str, OpSpec]) -> None:
85 """Batch-register declarative op specs into _OP_REGISTRY."""91 """Batch-register declarative op specs into _OP_REGISTRY."""
86 for op_name, spec in specs.items():92 for op_name, spec in specs.items():
87 if op_name in _OP_REGISTRY:93 if op_name in _OP_REGISTRY:
88- raise ValueError(f"Duplicate op_impl registration: '{op_name}'")94+ raise InvalidOperation(f"Duplicate op_impl registration: '{op_name}'")
89 _OP_REGISTRY[op_name] = _make_handler(spec)95 _OP_REGISTRY[op_name] = _make_handler(spec)
@@ -20,6 +20,7 @@ from typing import Any
20from pypto.pypto_impl import ir as _ir_core20from pypto.pypto_impl import ir as _ir_core
21from pypto.pypto_impl.ir import Call, ConstBool, ConstInt, DataType, Expr, ScalarType, Span, TensorType, TileType21from pypto.pypto_impl.ir import Call, ConstBool, ConstInt, DataType, Expr, ScalarType, Span, TensorType, TileType
22 22 
23+from ..._errors import InvalidArgument, InvalidShape, InvalidType, InvalidVal, NotSupported
23from .._utils import _get_span_or_capture, _normalize_expr, _to_make_tuple24from .._utils import _get_span_or_capture, _normalize_expr, _to_make_tuple
24from ._op_registry import OpSpec, op_impl, register_table25from ._op_registry import OpSpec, op_impl, register_table
25 26 
@@ -69,7 +70,7 @@ def _is_bool_dtype(dtype: DataType) -> bool:
69 70 
70def _normalize_location_flag(loc: bool, op_name: str) -> bool:71def _normalize_location_flag(loc: bool, op_name: str) -> bool:
71 if not isinstance(loc, bool):72 if not isinstance(loc, bool):
72- raise TypeError(f"debug.{op_name} requires bool loc flag, but got {type(loc).__name__}")73+ raise InvalidType(f"debug.{op_name} requires bool loc flag, but got {type(loc).__name__}")
73 return loc74 return loc
74 75 
75 76 
@@ -81,17 +82,17 @@ def _scan_printf_format(format_str: str) -> list[str]:
81 i += 182 i += 1
82 continue83 continue
83 if i + 1 < len(format_str) and format_str[i + 1] == "%":84 if i + 1 < len(format_str) and format_str[i + 1] == "%":
84- raise ValueError("printf does not support literal '%%'")85+ raise NotSupported("printf does not support literal '%%'")
85 86 
86 j = i + 187 j = i + 1
87 if j >= len(format_str):88 if j >= len(format_str):
88- raise ValueError("printf format string ends with an incomplete conversion")89+ raise InvalidVal("printf format string ends with an incomplete conversion")
89 90 
90 conversion = format_str[j]91 conversion = format_str[j]
91 if conversion not in _SUPPORTED_CONVERSIONS:92 if conversion not in _SUPPORTED_CONVERSIONS:
92 if conversion in "-+ #0." or conversion.isdigit():93 if conversion in "-+ #0." or conversion.isdigit():
93- raise ValueError("printf does not support flags, width, or precision")94+ raise NotSupported("printf does not support flags, width, or precision")
94- raise ValueError(f"printf does not support conversion '%{conversion}'")95+ raise NotSupported(f"printf does not support conversion '%{conversion}'")
95 96 
96 specs.append(format_str[i:j + 1])97 specs.append(format_str[i:j + 1])
97 i = j + 198 i = j + 1
@@ -125,7 +126,7 @@ def _validate_printf_arguments(
125) -> None:126) -> None:
126 specs = _scan_printf_format(format_str)127 specs = _scan_printf_format(format_str)
127 if len(specs) != len(normalized_args):128 if len(specs) != len(normalized_args):
128- raise ValueError(f"{op_name} format expects {len(specs)} scalar arguments, but got {len(normalized_args)}")129+ raise InvalidArgument(f"{op_name} format expects {len(specs)} scalar arguments, but got {len(normalized_args)}")
129 130 
130 for idx, (spec, arg, is_raw_bool) in enumerate(zip(specs, normalized_args, raw_bool_args)):131 for idx, (spec, arg, is_raw_bool) in enumerate(zip(specs, normalized_args, raw_bool_args)):
131 arg_type = arg.type132 arg_type = arg.type
@@ -134,13 +135,13 @@ def _validate_printf_arguments(
134 # %p accepts pointer types (PtrType)135 # %p accepts pointer types (PtrType)
135 if conversion == "p":136 if conversion == "p":
136 if not isinstance(arg_type, _ir_core.PtrType):137 if not isinstance(arg_type, _ir_core.PtrType):
137- raise TypeError(138+ raise InvalidVal(
138 f"debug.{op_name} conversion '{spec}' requires pointer, but got {type(arg_type).__name__}"139 f"debug.{op_name} conversion '{spec}' requires pointer, but got {type(arg_type).__name__}"
139 )140 )
140 continue141 continue
141 142 
142 if not isinstance(arg_type, ScalarType):143 if not isinstance(arg_type, ScalarType):
143- raise TypeError(144+ raise InvalidType(
144 f"debug.{op_name} argument {idx} requires ScalarType input, but got {type(arg_type).__name__}"145 f"debug.{op_name} argument {idx} requires ScalarType input, but got {type(arg_type).__name__}"
145 )146 )
146 scalar_type = arg_type147 scalar_type = arg_type
@@ -150,7 +151,7 @@ def _validate_printf_arguments(
150 or _is_bool_dtype(scalar_type.dtype)151 or _is_bool_dtype(scalar_type.dtype)
151 or _is_index_dtype(scalar_type.dtype)152 or _is_index_dtype(scalar_type.dtype)
152 ):153 ):
153- raise TypeError(154+ raise InvalidVal(
154 f"debug.{op_name} conversion '{spec}' requires signed integer, bool, or index scalar, "155 f"debug.{op_name} conversion '{spec}' requires signed integer, bool, or index scalar, "
155 f"but got {scalar_type.dtype}"156 f"but got {scalar_type.dtype}"
156 )157 )
@@ -160,21 +161,21 @@ def _validate_printf_arguments(
160 or _is_index_dtype(scalar_type.dtype)161 or _is_index_dtype(scalar_type.dtype)
161 or is_raw_bool162 or is_raw_bool
162 ):163 ):
163- raise TypeError(164+ raise InvalidVal(
164 f"debug.{op_name} conversion '{spec}' requires unsigned integer, bool, or index scalar, "165 f"debug.{op_name} conversion '{spec}' requires unsigned integer, bool, or index scalar, "
165 f"but got {scalar_type.dtype}"166 f"but got {scalar_type.dtype}"
166 )167 )
167 if conversion == "x" and not (168 if conversion == "x" and not (
168 _is_unsigned_integer_dtype(scalar_type.dtype) or _is_index_dtype(scalar_type.dtype)169 _is_unsigned_integer_dtype(scalar_type.dtype) or _is_index_dtype(scalar_type.dtype)
169 ):170 ):
170- raise TypeError(171+ raise InvalidVal(
171 f"debug.{op_name} conversion '{spec}' requires unsigned integer or index scalar, "172 f"debug.{op_name} conversion '{spec}' requires unsigned integer or index scalar, "
172 f"but got {scalar_type.dtype}"173 f"but got {scalar_type.dtype}"
173 )174 )
174 if conversion == "x" and is_raw_bool:175 if conversion == "x" and is_raw_bool:
175- raise TypeError(f"debug.{op_name} conversion '{spec}' does not support bool scalars")176+ raise NotSupported(f"debug.{op_name} conversion '{spec}' does not support bool scalars")
176 if conversion in _FLOAT_CONVERSIONS and scalar_type.dtype != DataType.FP32:177 if conversion in _FLOAT_CONVERSIONS and scalar_type.dtype != DataType.FP32:
177- raise TypeError(f"debug.{op_name} conversion '{spec}' requires FP32 scalar, but got {scalar_type.dtype}")178+ raise InvalidVal(f"debug.{op_name} conversion '{spec}' requires FP32 scalar, but got {scalar_type.dtype}")
178 179 
179 180 
180def dump_tensor(181def dump_tensor(
@@ -206,15 +207,15 @@ def dump_tensor(
206 actual_span = _get_span_or_capture(span)207 actual_span = _get_span_or_capture(span)
207 show_location = _normalize_location_flag(loc, "dump_tensor")208 show_location = _normalize_location_flag(loc, "dump_tensor")
208 if flag is not None and not isinstance(flag, str):209 if flag is not None and not isinstance(flag, str):
209- raise TypeError(f"debug.dump_tensor requires str flag, but got {type(flag).__name__}")210+ raise InvalidType(f"debug.dump_tensor requires str flag, but got {type(flag).__name__}")
210 tensor_type = tensor.type211 tensor_type = tensor.type
211 if not isinstance(tensor_type, TensorType):212 if not isinstance(tensor_type, TensorType):
212- raise TypeError(f"debug.dump_tensor requires TensorType input, but got {type(tensor_type).__name__}")213+ raise InvalidType(f"debug.dump_tensor requires TensorType input, but got {type(tensor_type).__name__}")
213 if tensor_type.dtype in (DataType.FP4, DataType.FP4E2M1, DataType.FP4E1M2):214 if tensor_type.dtype in (DataType.FP4, DataType.FP4E2M1, DataType.FP4E1M2):
214- raise ValueError(f"debug.dump_tensor does not support FP4 dtype {tensor_type.dtype}")215+ raise NotSupported(f"debug.dump_tensor does not support FP4 dtype {tensor_type.dtype}")
215 216 
216 if (offsets is None) != (shapes is None):217 if (offsets is None) != (shapes is None):
217- raise ValueError("debug.dump_tensor offsets and shapes must be provided together")218+ raise InvalidArgument("debug.dump_tensor offsets and shapes must be provided together")
218 219 
219 rank = len(tensor_type.shape)220 rank = len(tensor_type.shape)
220 if offsets is None and shapes is None:221 if offsets is None and shapes is None:
@@ -224,25 +225,25 @@ def dump_tensor(
224 if tensor_type.tensor_view is not None and tensor_type.tensor_view.stride:225 if tensor_type.tensor_view is not None and tensor_type.tensor_view.stride:
225 last_stride = tensor_type.tensor_view.stride[-1]226 last_stride = tensor_type.tensor_view.stride[-1]
226 if not isinstance(last_stride, ConstInt):227 if not isinstance(last_stride, ConstInt):
227- raise NotImplementedError(228+ raise InvalidShape(
228 "debug.dump_tensor windowed mode requires the innermost stride to be statically 1"229 "debug.dump_tensor windowed mode requires the innermost stride to be statically 1"
229 )230 )
230 if last_stride.value != 1:231 if last_stride.value != 1:
231- raise ValueError(232+ raise InvalidShape(
232 f"debug.dump_tensor windowed mode requires innermost stride == 1, got {last_stride.value}"233 f"debug.dump_tensor windowed mode requires innermost stride == 1, got {last_stride.value}"
233 )234 )
234 offsets_tuple = _to_make_tuple(offsets, actual_span)235 offsets_tuple = _to_make_tuple(offsets, actual_span)
235 shapes_tuple = _to_make_tuple(shapes, actual_span)236 shapes_tuple = _to_make_tuple(shapes, actual_span)
236 237 
237 if len(offsets_tuple.elements) != rank or len(shapes_tuple.elements) != rank:238 if len(offsets_tuple.elements) != rank or len(shapes_tuple.elements) != rank:
238- raise ValueError(239+ raise InvalidShape(
239 f"debug.dump_tensor offsets/shapes must match tensor rank {rank}, got "240 f"debug.dump_tensor offsets/shapes must match tensor rank {rank}, got "
240 f"{len(offsets_tuple.elements)} offsets and {len(shapes_tuple.elements)} shapes"241 f"{len(offsets_tuple.elements)} offsets and {len(shapes_tuple.elements)} shapes"
241 )242 )
242 243 
243 for idx, shape_expr in enumerate(shapes_tuple.elements):244 for idx, shape_expr in enumerate(shapes_tuple.elements):
244 if isinstance(shape_expr, ConstInt) and shape_expr.value <= 0:245 if isinstance(shape_expr, ConstInt) and shape_expr.value <= 0:
245- raise ValueError(f"debug.dump_tensor shape at axis {idx} must be positive, got {shape_expr.value}")246+ raise InvalidShape(f"debug.dump_tensor shape at axis {idx} must be positive, got {shape_expr.value}")
246 247 
247 dump_kwargs: dict[str, Any] = {"show_location": show_location}248 dump_kwargs: dict[str, Any] = {"show_location": show_location}
248 if flag:249 if flag:
@@ -262,13 +263,13 @@ def _validate_dump_offsets_shapes(
262 op_name: str,263 op_name: str,
263) -> None:264) -> None:
264 if len(offsets_tuple.elements) != rank or len(shapes_tuple.elements) != rank:265 if len(offsets_tuple.elements) != rank or len(shapes_tuple.elements) != rank:
265- raise ValueError(266+ raise InvalidShape(
266 f"debug.{op_name} offsets/shapes must match tile rank {rank}, got "267 f"debug.{op_name} offsets/shapes must match tile rank {rank}, got "
267 f"{len(offsets_tuple.elements)} offsets and {len(shapes_tuple.elements)} shapes"268 f"{len(offsets_tuple.elements)} offsets and {len(shapes_tuple.elements)} shapes"
268 )269 )
269 for idx, shape_expr in enumerate(shapes_tuple.elements):270 for idx, shape_expr in enumerate(shapes_tuple.elements):
270 if isinstance(shape_expr, ConstInt) and shape_expr.value <= 0:271 if isinstance(shape_expr, ConstInt) and shape_expr.value <= 0:
271- raise ValueError(f"debug.{op_name} shape at axis {idx} must be positive, got {shape_expr.value}")272+ raise InvalidShape(f"debug.{op_name} shape at axis {idx} must be positive, got {shape_expr.value}")
272 273 
273 274 
274def dump_tile(275def dump_tile(
@@ -303,19 +304,19 @@ def dump_tile(
303 actual_span = _get_span_or_capture(span)304 actual_span = _get_span_or_capture(span)
304 show_location = _normalize_location_flag(loc, "dump_tile")305 show_location = _normalize_location_flag(loc, "dump_tile")
305 if flag is not None and not isinstance(flag, str):306 if flag is not None and not isinstance(flag, str):
306- raise TypeError(f"debug.dump_tile requires str flag, but got {type(flag).__name__}")307+ raise InvalidType(f"debug.dump_tile requires str flag, but got {type(flag).__name__}")
307 tile_type = tile.type308 tile_type = tile.type
308 if not isinstance(tile_type, TileType):309 if not isinstance(tile_type, TileType):
309- raise TypeError(f"debug.dump_tile requires TileType input, but got {type(tile_type).__name__}")310+ raise InvalidType(f"debug.dump_tile requires TileType input, but got {type(tile_type).__name__}")
310 if section is not None:311 if section is not None:
311 _validate_dump_memory_section(tile_type, section, actual_span)312 _validate_dump_memory_section(tile_type, section, actual_span)
312 if (offsets is None) != (shapes is None):313 if (offsets is None) != (shapes is None):
313- raise ValueError("debug.dump_tile offsets and shapes must be provided together")314+ raise InvalidArgument("debug.dump_tile offsets and shapes must be provided together")
314 315 
315 if workspace is not None:316 if workspace is not None:
316 ws_type = workspace.type317 ws_type = workspace.type
317 if not isinstance(ws_type, TensorType):318 if not isinstance(ws_type, TensorType):
318- raise TypeError(f"debug.dump_tile workspace must be TensorType, but got {type(ws_type).__name__}")319+ raise InvalidType(f"debug.dump_tile workspace must be TensorType, but got {type(ws_type).__name__}")
319 320 
320 rank = len(tile_type.shape)321 rank = len(tile_type.shape)
321 dump_kwargs: dict[str, Any] = {"show_location": show_location}322 dump_kwargs: dict[str, Any] = {"show_location": show_location}
@@ -369,9 +370,8 @@ def _validate_dump_memory_section(data_type, section, span: Span | None = None)
369 if section == _ir_core.SectionKind.Vector:370 if section == _ir_core.SectionKind.Vector:
370 if mem == _ir_core.MemorySpace.Vec:371 if mem == _ir_core.MemorySpace.Vec:
371 return372 return
372- from pypto_pro.language.parser.diagnostics import ParserSyntaxError
373 373 
374- raise ParserSyntaxError(374+ raise NotSupported(
375 f"pl.dump_data of a {mem.name} tile is not allowed in a Vector section; "375 f"pl.dump_data of a {mem.name} tile is not allowed in a Vector section; "
376 "only Vec (UB) tiles (and GM tensors) can be dumped there",376 "only Vec (UB) tiles (and GM tensors) can be dumped there",
377 span=span,377 span=span,
@@ -380,9 +380,8 @@ def _validate_dump_memory_section(data_type, section, span: Span | None = None)
380 if section == _ir_core.SectionKind.Cube:380 if section == _ir_core.SectionKind.Cube:
381 if mem == _ir_core.MemorySpace.Acc:381 if mem == _ir_core.MemorySpace.Acc:
382 return382 return
383- from pypto_pro.language.parser.diagnostics import ParserSyntaxError
384 383 
385- raise ParserSyntaxError(384+ raise NotSupported(
386 f"pl.dump_data of a {mem.name} tile is not allowed in a Cube section; "385 f"pl.dump_data of a {mem.name} tile is not allowed in a Cube section; "
387 "only Acc (L0C) tiles (and GM tensors) can be dumped there",386 "only Acc (L0C) tiles (and GM tensors) can be dumped there",
388 span=span,387 span=span,
@@ -409,15 +408,15 @@ def dump_data(
409 """408 """
410 data_type = data.type409 data_type = data.type
411 if flag is not None and not isinstance(flag, str):410 if flag is not None and not isinstance(flag, str):
412- raise TypeError(f"debug.dump_data requires str flag, but got {type(flag).__name__}")411+ raise InvalidType(f"debug.dump_data requires str flag, but got {type(flag).__name__}")
413 if isinstance(data_type, TensorType):412 if isinstance(data_type, TensorType):
414 if workspace is not None:413 if workspace is not None:
415- raise ValueError("debug.dump_data: workspace is only valid for Tile inputs, not Tensor")414+ raise NotSupported("debug.dump_data: workspace is only valid for Tile inputs, not Tensor")
416 return dump_tensor(data, offsets, shapes, loc=loc, span=span, flag=flag)415 return dump_tensor(data, offsets, shapes, loc=loc, span=span, flag=flag)
417 elif isinstance(data_type, TileType):416 elif isinstance(data_type, TileType):
418 return dump_tile(data, offsets, shapes, workspace=workspace, loc=loc, span=span, section=section, flag=flag)417 return dump_tile(data, offsets, shapes, workspace=workspace, loc=loc, span=span, section=section, flag=flag)
419 else:418 else:
420- raise TypeError(f"debug.dump_data requires Tensor or Tile input, but got {type(data_type).__name__}")419+ raise InvalidType(f"debug.dump_data requires Tensor or Tile input, but got {type(data_type).__name__}")
421 420 
422 421 
423def printf(format_str: str, *args: int | float | Expr, loc: bool = False, span: Span | None = None) -> Call:422def printf(format_str: str, *args: int | float | Expr, loc: bool = False, span: Span | None = None) -> Call:
@@ -425,7 +424,7 @@ def printf(format_str: str, *args: int | float | Expr, loc: bool = False, span:
425 actual_span = _get_span_or_capture(span)424 actual_span = _get_span_or_capture(span)
426 show_location = _normalize_location_flag(loc, "printf")425 show_location = _normalize_location_flag(loc, "printf")
427 if not isinstance(format_str, str):426 if not isinstance(format_str, str):
428- raise TypeError(f"debug.printf requires string format literal, but got {type(format_str).__name__}")427+ raise InvalidType(f"debug.printf requires string format literal, but got {type(format_str).__name__}")
429 428 
430 normalized_args, raw_bool_args = _normalize_printf_args(args, actual_span)429 normalized_args, raw_bool_args = _normalize_printf_args(args, actual_span)
431 _validate_printf_arguments(format_str, normalized_args, raw_bool_args, op_name="printf")430 _validate_printf_arguments(format_str, normalized_args, raw_bool_args, op_name="printf")
@@ -450,11 +449,11 @@ def pto_assert(
450 elif isinstance(condition, bool):449 elif isinstance(condition, bool):
451 condition_expr = ConstBool(condition, actual_span)450 condition_expr = ConstBool(condition, actual_span)
452 else:451 else:
453- raise TypeError(f"debug.pto_assert requires a scalar bool condition, but got {type(condition).__name__}")452+ raise InvalidType(f"debug.pto_assert requires a scalar bool condition, but got {type(condition).__name__}")
454 453 
455 condition_type = condition_expr.type454 condition_type = condition_expr.type
456 if not isinstance(condition_type, ScalarType) or condition_type.dtype != DataType.BOOL:455 if not isinstance(condition_type, ScalarType) or condition_type.dtype != DataType.BOOL:
457- raise TypeError(456+ raise InvalidType(
458 "debug.pto_assert requires a scalar bool condition, "457 "debug.pto_assert requires a scalar bool condition, "
459 f"but got {type(condition_type).__name__}({getattr(condition_type, 'dtype', condition_type)})"458 f"but got {type(condition_type).__name__}({getattr(condition_type, 'dtype', condition_type)})"
460 )459 )
@@ -462,7 +461,7 @@ def pto_assert(
462 if condition_text is None:461 if condition_text is None:
463 condition_text = "condition"462 condition_text = "condition"
464 if not isinstance(condition_text, str):463 if not isinstance(condition_text, str):
465- raise TypeError(464+ raise InvalidType(
466 f"debug.pto_assert requires string condition_text metadata, but got {type(condition_text).__name__}"465 f"debug.pto_assert requires string condition_text metadata, but got {type(condition_text).__name__}"
467 )466 )
468 467 
@@ -471,7 +470,7 @@ def pto_assert(
471 format_value = ""470 format_value = ""
472 else:471 else:
473 if not isinstance(format_str, str):472 if not isinstance(format_str, str):
474- raise TypeError(f"debug.pto_assert requires string literal format, but got {type(format_str).__name__}")473+ raise InvalidType(f"debug.pto_assert requires string literal format, but got {type(format_str).__name__}")
475 normalized_args, raw_bool_args = _normalize_printf_args(args, actual_span)474 normalized_args, raw_bool_args = _normalize_printf_args(args, actual_span)
476 _validate_printf_arguments(format_str, normalized_args, raw_bool_args, op_name="pto_assert")475 _validate_printf_arguments(format_str, normalized_args, raw_bool_args, op_name="pto_assert")
477 format_value = format_str476 format_value = format_str
@@ -22,6 +22,7 @@ from typing import Any
22from pypto.pypto_impl import ir as _ir_core22from pypto.pypto_impl import ir as _ir_core
23from pypto.pypto_impl.ir import Call, DataType, Expr, Span23from pypto.pypto_impl.ir import Call, DataType, Expr, Span
24 24 
25+from ..._errors import InvalidType
25from .._utils import _get_span_or_capture, _normalize_expr, _to_make_tuple26from .._utils import _get_span_or_capture, _normalize_expr, _to_make_tuple
26from ._op_registry import OpSpec, register_table27from ._op_registry import OpSpec, register_table
27 28 
@@ -113,7 +114,7 @@ def _check_addptr_dtype(ptr: Expr) -> None:
113 """114 """
114 ptr_type = ptr.type115 ptr_type = ptr.type
115 if isinstance(ptr_type, _ir_core.PtrType) and ptr_type.dtype.get_bit() < 8:116 if isinstance(ptr_type, _ir_core.PtrType) and ptr_type.dtype.get_bit() < 8:
116- raise ValueError(117+ raise InvalidType(
117 f"pl.addptr / pointer arithmetic is not supported on sub-byte element type "118 f"pl.addptr / pointer arithmetic is not supported on sub-byte element type "
118 f"'{ptr_type.dtype.to_string()}': offsetting by elements cannot address a "119 f"'{ptr_type.dtype.to_string()}': offsetting by elements cannot address a "
119 f"half-byte. Reinterpret the pointer as a byte-addressable dtype via "120 f"half-byte. Reinterpret the pointer as a byte-addressable dtype via "
@@ -16,18 +16,18 @@ import ast
16from pypto.pypto_impl import ir as _ir_core16from pypto.pypto_impl import ir as _ir_core
17from pypto.pypto_impl.ir import Expr, Span17from pypto.pypto_impl.ir import Expr, Span
18 18 
19+from ..._errors import InvalidArgument, InvalidType, InvalidVal
19from ._op_registry import OpSpec, op_impl, register_table20from ._op_registry import OpSpec, op_impl, register_table
20 21 
21 22 
22@op_impl("min")23@op_impl("min")
23def _parse_min(self, call: ast.Call):24def _parse_min(self, call: ast.Call):
24- from pypto_pro.language.parser.diagnostics import InvalidOperationError
25 25 
26 call_span = self.span_tracker.get_span(call)26 call_span = self.span_tracker.get_span(call)
27 if call.keywords:27 if call.keywords:
28- raise InvalidOperationError("Scalar operation 'min' does not accept keyword arguments", span=call_span)28+ raise InvalidArgument("Scalar operation 'min' does not accept keyword arguments", span=call_span)
29 if len(call.args) != 2:29 if len(call.args) != 2:
30- raise InvalidOperationError(30+ raise InvalidArgument(
31 f"Scalar binary operation 'min' requires exactly 2 arguments, got {len(call.args)}",31 f"Scalar binary operation 'min' requires exactly 2 arguments, got {len(call.args)}",
32 span=call_span,32 span=call_span,
33 )33 )
@@ -40,13 +40,12 @@ def _parse_min(self, call: ast.Call):
40 40 
41@op_impl("max")41@op_impl("max")
42def _parse_max(self, call: ast.Call):42def _parse_max(self, call: ast.Call):
43- from pypto_pro.language.parser.diagnostics import InvalidOperationError
44 43 
45 call_span = self.span_tracker.get_span(call)44 call_span = self.span_tracker.get_span(call)
46 if call.keywords:45 if call.keywords:
47- raise InvalidOperationError("Scalar operation 'max' does not accept keyword arguments", span=call_span)46+ raise InvalidArgument("Scalar operation 'max' does not accept keyword arguments", span=call_span)
48 if len(call.args) != 2:47 if len(call.args) != 2:
49- raise InvalidOperationError(48+ raise InvalidArgument(
50 f"Scalar binary operation 'max' requires exactly 2 arguments, got {len(call.args)}",49 f"Scalar binary operation 'max' requires exactly 2 arguments, got {len(call.args)}",
51 span=call_span,50 span=call_span,
52 )51 )
@@ -194,12 +193,12 @@ register_table(
194 193 
195@op_impl("const")194@op_impl("const")
196def _parse_typed_constant(self, call: ast.Call):195def _parse_typed_constant(self, call: ast.Call):
197- from pypto_pro.language.parser.diagnostics import ParserSyntaxError, check_fits_dtype, make_const_int196+ from pypto_pro.language.parser.diagnostics import check_fits_dtype, make_const_int
198 197 
199 span = self.span_tracker.get_span(call)198 span = self.span_tracker.get_span(call)
200 199 
201 if len(call.args) != 2:200 if len(call.args) != 2:
202- raise ParserSyntaxError(201+ raise InvalidArgument(
203 "pl.const() requires exactly 2 arguments: value and dtype",202 "pl.const() requires exactly 2 arguments: value and dtype",
204 span=span,203 span=span,
205 hint="Use pl.const(42, pl.DT_INT32) or pl.const(1.0, pl.DT_FP16)",204 hint="Use pl.const(42, pl.DT_INT32) or pl.const(1.0, pl.DT_FP16)",
@@ -212,9 +211,9 @@ def _parse_typed_constant(self, call: ast.Call):
212 value_node = value_node.operand211 value_node = value_node.operand
213 212 
214 if not isinstance(value_node, ast.Constant) or not isinstance(value_node.value, (int, float)):213 if not isinstance(value_node, ast.Constant) or not isinstance(value_node.value, (int, float)):
215- raise ParserSyntaxError(214+ raise InvalidType(
216 "pl.const() first argument must be a numeric literal",215 "pl.const() first argument must be a numeric literal",
217- span=span,216+ span=self.span_tracker.call_argument_span(call, 0, span),
218 hint="Use an int or float literal: pl.const(42, pl.DT_INT32)",217 hint="Use an int or float literal: pl.const(42, pl.DT_INT32)",
219 )218 )
220 219 
@@ -224,10 +223,10 @@ def _parse_typed_constant(self, call: ast.Call):
224 223 
225 dtype = self.parse_expression(call.args[1])224 dtype = self.parse_expression(call.args[1])
226 if not isinstance(dtype, _ir_core.DataType):225 if not isinstance(dtype, _ir_core.DataType):
227- raise ParserSyntaxError(226+ raise InvalidType(
228 f"pl.const() second argument must be a dtype (pl.DT_*), "227 f"pl.const() second argument must be a dtype (pl.DT_*), "
229 f"got {type(dtype).__name__}",228 f"got {type(dtype).__name__}",
230- span=span,229+ span=self.span_tracker.call_argument_span(call, 1, span),
231 hint="Use a dtype: pl.DT_FP32, pl.DT_INT32, etc.",230 hint="Use a dtype: pl.DT_FP32, pl.DT_INT32, etc.",
232 )231 )
233 232 
@@ -242,11 +241,10 @@ def _parse_typed_constant(self, call: ast.Call):
242 241 
243@op_impl("astype")242@op_impl("astype")
244def _parse_scalar_astype(self, call: ast.Call):243def _parse_scalar_astype(self, call: ast.Call):
245- from pypto_pro.language.parser.diagnostics import ParserSyntaxError, ParserTypeError
246 244 
247 span = self.span_tracker.get_span(call)245 span = self.span_tracker.get_span(call)
248 if call.keywords or len(call.args) != 2:246 if call.keywords or len(call.args) != 2:
249- raise ParserSyntaxError(247+ raise InvalidType(
250 "pl.astype() requires exactly 2 positional arguments: value and dtype",248 "pl.astype() requires exactly 2 positional arguments: value and dtype",
251 span=span,249 span=span,
252 hint="Use pl.astype(value, pl.DT_INT32)",250 hint="Use pl.astype(value, pl.DT_INT32)",
@@ -255,15 +253,17 @@ def _parse_scalar_astype(self, call: ast.Call):
255 value = self.parse_expression(call.args[0])253 value = self.parse_expression(call.args[0])
256 if not isinstance(value, _ir_core.Expr) or not isinstance(value.type, _ir_core.ScalarType):254 if not isinstance(value, _ir_core.Expr) or not isinstance(value.type, _ir_core.ScalarType):
257 value_type = getattr(value, "type", type(value).__name__)255 value_type = getattr(value, "type", type(value).__name__)
258- raise ParserTypeError(256+ raise InvalidVal(
259 f"pl.astype() first argument must be a Scalar, got {value_type}",257 f"pl.astype() first argument must be a Scalar, got {value_type}",
260- span=span,258+ span=self.span_tracker.call_argument_span(call, 0, span),
259+ parser_retry=True,
261 )260 )
262 261 
263 dtype = self.parse_expression(call.args[1])262 dtype = self.parse_expression(call.args[1])
264 if not isinstance(dtype, _ir_core.DataType):263 if not isinstance(dtype, _ir_core.DataType):
265- raise ParserTypeError(264+ raise InvalidType(
266 f"pl.astype() second argument must be a dtype (pl.DT_*), got {type(dtype).__name__}",265 f"pl.astype() second argument must be a dtype (pl.DT_*), got {type(dtype).__name__}",
267- span=span,266+ span=self.span_tracker.call_argument_span(call, 1, span),
267+ parser_retry=True,
268 )268 )
269 return _ir_core.cast(value, dtype, span)269 return _ir_core.cast(value, dtype, span)
@@ -20,6 +20,16 @@ from typing import Any
20from pypto.pypto_impl import ir as _ir_core20from pypto.pypto_impl import ir as _ir_core
21from pypto.pypto_impl.ir import Call, Expr, Function, Span21from pypto.pypto_impl.ir import Call, Expr, Function, Span
22 22 
23+from ..._errors import (
24+ CommonExternal,
25+ InvalidArgument,
26+ InvalidOperation,
27+ InvalidShape,
28+ InvalidType,
29+ InvalidVal,
30+ NotSupported,
31+ message_of,
32+)
23from .._utils import _get_span_or_capture, _normalize_expr33from .._utils import _get_span_or_capture, _normalize_expr
24from ._op_registry import op_impl34from ._op_registry import op_impl
25 35 
@@ -318,7 +328,7 @@ def launch(
318 actual_span = _get_span_or_capture(span)328 actual_span = _get_span_or_capture(span)
319 thread_dims = list(threads) if isinstance(threads, tuple) else [threads]329 thread_dims = list(threads) if isinstance(threads, tuple) else [threads]
320 if not 1 <= len(thread_dims) <= 3:330 if not 1 <= len(thread_dims) <= 3:
321- raise ValueError("SIMT launch threads must contain one to three dimensions")331+ raise InvalidShape("SIMT launch threads must contain one to three dimensions")
322 thread_dims.extend([1] * (3 - len(thread_dims)))332 thread_dims.extend([1] * (3 - len(thread_dims)))
323 normalized_dims = [_normalize_expr(dim, actual_span) for dim in thread_dims]333 normalized_dims = [_normalize_expr(dim, actual_span) for dim in thread_dims]
324 return _ir_core.create_op_call(334 return _ir_core.create_op_call(
@@ -331,20 +341,19 @@ def launch(
331 341 
332def _validate_simt_body_op(parser: Any, call: ast.Call, _kwargs: dict[str, Any]) -> None:342def _validate_simt_body_op(parser: Any, call: ast.Call, _kwargs: dict[str, Any]) -> None:
333 """Validate the common source constraints of a SIMT body operation."""343 """Validate the common source constraints of a SIMT body operation."""
334- from pypto_pro.language.parser.diagnostics import ParserSyntaxError
335 344 
336 span = parser.span_tracker.get_span(call)345 span = parser.span_tracker.get_span(call)
337 op_name = parser._extract_op_name(call.func)346 op_name = parser._extract_op_name(call.func)
338 if parser._current_func_type not in (_ir_core.FunctionType.SimtVF, _ir_core.FunctionType.SimtCallee):347 if parser._current_func_type not in (_ir_core.FunctionType.SimtVF, _ir_core.FunctionType.SimtCallee):
339- raise ParserSyntaxError(348+ raise InvalidOperation(
340 f"pl.{op_name}() can only be used inside a SIMT function",349 f"pl.{op_name}() can only be used inside a SIMT function",
341 span=span,350 span=span,
342 hint="Move SIMT-context-dependent logic into @pl.vector_function(mode=\"simt\").",351 hint="Move SIMT-context-dependent logic into @pl.vector_function(mode=\"simt\").",
343 )352 )
344 if call.args:353 if call.args:
345- raise ParserSyntaxError(f"pl.{op_name}() does not accept positional arguments", span=span)354+ raise InvalidArgument(f"pl.{op_name}() does not accept positional arguments", span=span)
346 if call.keywords:355 if call.keywords:
347- raise ParserSyntaxError(f"pl.{op_name}() does not accept keyword arguments", span=span)356+ raise InvalidArgument(f"pl.{op_name}() does not accept keyword arguments", span=span)
348 357 
349 358 
350def _parse_dim3_context(parser: Any, call: ast.Call, op_name: str) -> Expr:359def _parse_dim3_context(parser: Any, call: ast.Call, op_name: str) -> Expr:
@@ -417,36 +426,36 @@ def _parse_threadfence(parser: Any, call: ast.Call) -> Expr:
417def _parse_simt_launch(parser: Any, call: ast.Call, local_name: str, callee_template: Callable) -> Expr:426def _parse_simt_launch(parser: Any, call: ast.Call, local_name: str, callee_template: Callable) -> Expr:
418 """Parse ``simt_func[threads](args...)`` and lower it to ``simt.launch`` IR."""427 """Parse ``simt_func[threads](args...)`` and lower it to ``simt.launch`` IR."""
419 from pypto_pro.language.parser.decorator import get_simt_max_threads428 from pypto_pro.language.parser.decorator import get_simt_max_threads
420- from pypto_pro.language.parser.diagnostics import ParserSyntaxError, ParserTypeError
421 429 
422 span = parser.span_tracker.get_span(call)430 span = parser.span_tracker.get_span(call)
423 if parser._current_func_type in (_ir_core.FunctionType.SimtVF, _ir_core.FunctionType.SimtCallee):431 if parser._current_func_type in (_ir_core.FunctionType.SimtVF, _ir_core.FunctionType.SimtCallee):
424- raise ParserSyntaxError("Nested SIMT vector-function invocation is not supported", span=span)432+ raise NotSupported("Nested SIMT vector-function invocation is not supported", span=span)
425 if parser.target != _ir_core.SectionKind.Vector:433 if parser.target != _ir_core.SectionKind.Vector:
426- raise ParserSyntaxError(434+ raise InvalidOperation(
427 "SIMT vector functions must be invoked inside 'with pl.section_vector():'",435 "SIMT vector functions must be invoked inside 'with pl.section_vector():'",
428 span=span,436 span=span,
429 hint="SIMT vector functions execute on AIV and cannot be invoked from Cube or shared kernel code.",437 hint="SIMT vector functions execute on AIV and cannot be invoked from Cube or shared kernel code.",
430 )438 )
431 439 
432 if call.keywords or any(isinstance(arg, ast.Starred) for arg in call.args):440 if call.keywords or any(isinstance(arg, ast.Starred) for arg in call.args):
433- raise ParserSyntaxError(441+ raise InvalidArgument(
434 "SIMT vector-function invocation accepts positional arguments only",442 "SIMT vector-function invocation accepts positional arguments only",
435 span=span,443 span=span,
436 hint="Use: simt_func[threads](arg0, arg1, ...)",444 hint="Use: simt_func[threads](arg0, arg1, ...)",
437 )445 )
438 446 
439 if get_simt_max_threads(callee_template) is None:447 if get_simt_max_threads(callee_template) is None:
440- raise ParserTypeError(448+ raise InvalidVal(
441 f"'{local_name}' is not a launchable "449 f"'{local_name}' is not a launchable "
442 '@pl.vector_function(mode="simt", max_threads=...)',450 '@pl.vector_function(mode="simt", max_threads=...)',
443 span=parser.span_tracker.get_span(call.func.value),451 span=parser.span_tracker.get_span(call.func.value),
452+ parser_retry=True,
444 )453 )
445 454 
446 threads_node = call.func.slice455 threads_node = call.func.slice
447 if isinstance(threads_node, ast.Tuple):456 if isinstance(threads_node, ast.Tuple):
448 if not 1 <= len(threads_node.elts) <= 3:457 if not 1 <= len(threads_node.elts) <= 3:
449- raise ParserSyntaxError(458+ raise InvalidShape(
450 "SIMT thread configuration must contain one to three dimensions",459 "SIMT thread configuration must contain one to three dimensions",
451 span=parser.span_tracker.get_span(threads_node),460 span=parser.span_tracker.get_span(threads_node),
452 hint="Use simt_func[N](...), simt_func[x, y](...), or simt_func[x, y, z](...).",461 hint="Use simt_func[N](...), simt_func[x, y](...), or simt_func[x, y, z](...).",
@@ -462,7 +471,7 @@ def _parse_simt_launch(parser: Any, call: ast.Call, local_name: str, callee_temp
462 try:471 try:
463 return launch(callee, threads=tuple(thread_dims), args=launch_args, span=span)472 return launch(callee, threads=tuple(thread_dims), args=launch_args, span=span)
464 except RuntimeError as error:473 except RuntimeError as error:
465- raise ParserTypeError(str(error), span=span) from error474+ raise CommonExternal(message_of(error), span=span, parser_retry=True) from error
466 475 
467def _numeric_literal_value(node: ast.expr) -> int | float | None:476def _numeric_literal_value(node: ast.expr) -> int | float | None:
468 if isinstance(node, ast.Constant) and type(node.value) in (int, float):477 if isinstance(node, ast.Constant) and type(node.value) in (int, float):
@@ -485,16 +494,16 @@ def _parse_atomic_operand(
485 dtype: _ir_core.DataType,494 dtype: _ir_core.DataType,
486) -> Expr:495) -> Expr:
487 """Parse one atomic operand, contextually typing numeric literals."""496 """Parse one atomic operand, contextually typing numeric literals."""
488- from pypto_pro.language.parser.diagnostics import ParserTypeError
489 497 
490 operand_span = parser.span_tracker.get_span(operand_node)498 operand_span = parser.span_tracker.get_span(operand_node)
491 literal_value = _numeric_literal_value(operand_node)499 literal_value = _numeric_literal_value(operand_node)
492 if literal_value is not None:500 if literal_value is not None:
493 if dtype.is_int() and type(literal_value) is not int:501 if dtype.is_int() and type(literal_value) is not int:
494- raise ParserTypeError(502+ raise InvalidType(
495 f"pl.{op_name}() requires an integer {operand_name} for target dtype {dtype}",503 f"pl.{op_name}() requires an integer {operand_name} for target dtype {dtype}",
496 span=operand_span,504 span=operand_span,
497 hint=f"Use an integer literal or a Scalar with dtype {dtype}.",505 hint=f"Use an integer literal or a Scalar with dtype {dtype}.",
506+ parser_retry=True,
498 )507 )
499 return parser._make_scalar_constant(literal_value, dtype, operand_span)508 return parser._make_scalar_constant(literal_value, dtype, operand_span)
500 509 
@@ -509,11 +518,10 @@ def _parse_atomic_call(
509 call: ast.Call,518 call: ast.Call,
510) -> Expr:519) -> Expr:
511 """Parse one ``pl.simt.atomic_*`` call without loading its target."""520 """Parse one ``pl.simt.atomic_*`` call without loading its target."""
512- from pypto_pro.language.parser.diagnostics import ParserSyntaxError, ParserTypeError
513 521 
514 span = parser.span_tracker.get_span(call)522 span = parser.span_tracker.get_span(call)
515 if parser._current_func_type not in (_ir_core.FunctionType.SimtVF, _ir_core.FunctionType.SimtCallee):523 if parser._current_func_type not in (_ir_core.FunctionType.SimtVF, _ir_core.FunctionType.SimtCallee):
516- raise ParserSyntaxError(524+ raise InvalidOperation(
517 f"pl.{op_name}() can only be used inside a SIMT function",525 f"pl.{op_name}() can only be used inside a SIMT function",
518 span=span,526 span=span,
519 hint="Move SIMT-context-dependent logic into @pl.vector_function(mode=\"simt\").",527 hint="Move SIMT-context-dependent logic into @pl.vector_function(mode=\"simt\").",
@@ -523,7 +531,7 @@ def _parse_atomic_call(
523 expected_args = 1 + len(operand_names)531 expected_args = 1 + len(operand_names)
524 if len(call.args) != expected_args or call.keywords:532 if len(call.args) != expected_args or call.keywords:
525 signature = ", ".join(("target", *operand_names))533 signature = ", ".join(("target", *operand_names))
526- raise ParserSyntaxError(534+ raise InvalidArgument(
527 f"pl.simt.{short_name}() requires exactly {expected_args} positional arguments",535 f"pl.simt.{short_name}() requires exactly {expected_args} positional arguments",
528 span=span,536 span=span,
529 hint=f"Use pl.simt.{short_name}({signature}).",537 hint=f"Use pl.simt.{short_name}({signature}).",
@@ -531,7 +539,7 @@ def _parse_atomic_call(
531 539 
532 target_node = call.args[0]540 target_node = call.args[0]
533 if not isinstance(target_node, ast.Subscript):541 if not isinstance(target_node, ast.Subscript):
534- raise ParserSyntaxError(542+ raise InvalidVal(
535 f"pl.simt.{short_name}() target must be a direct Tile or Tensor subscript",543 f"pl.simt.{short_name}() target must be a direct Tile or Tensor subscript",
536 span=parser.span_tracker.get_span(target_node),544 span=parser.span_tracker.get_span(target_node),
537 hint=f"Use pl.simt.{short_name}(tile[row, col], ...), not a previously loaded Scalar.",545 hint=f"Use pl.simt.{short_name}(tile[row, col], ...), not a previously loaded Scalar.",
@@ -540,7 +548,7 @@ def _parse_atomic_call(
540 isinstance(target_node.slice, ast.Tuple)548 isinstance(target_node.slice, ast.Tuple)
541 and any(isinstance(index, ast.Slice) for index in target_node.slice.elts)549 and any(isinstance(index, ast.Slice) for index in target_node.slice.elts)
542 ):550 ):
543- raise ParserSyntaxError(551+ raise NotSupported(
544 f"pl.simt.{short_name}() target does not support slices",552 f"pl.simt.{short_name}() target does not support slices",
545 span=parser.span_tracker.get_span(target_node),553 span=parser.span_tracker.get_span(target_node),
546 hint="Select exactly one element with integer indices.",554 hint="Select exactly one element with integer indices.",
@@ -549,9 +557,10 @@ def _parse_atomic_call(
549 container = parser.parse_expression(target_node.value)557 container = parser.parse_expression(target_node.value)
550 container_type = container.type if isinstance(container, Expr) else None558 container_type = container.type if isinstance(container, Expr) else None
551 if not isinstance(container_type, (_ir_core.TileType, _ir_core.TensorType)):559 if not isinstance(container_type, (_ir_core.TileType, _ir_core.TensorType)):
552- raise ParserTypeError(560+ raise InvalidType(
553 f"pl.simt.{short_name}() target container must be a Tile or Tensor",561 f"pl.simt.{short_name}() target container must be a Tile or Tensor",
554 span=parser.span_tracker.get_span(target_node.value),562 span=parser.span_tracker.get_span(target_node.value),
563+ parser_retry=True,
555 )564 )
556 565 
557 dtype = container_type.dtype566 dtype = container_type.dtype
@@ -564,24 +573,23 @@ def _parse_atomic_call(
564 try:573 try:
565 return builder(container, offset, *operands, span=span)574 return builder(container, offset, *operands, span=span)
566 except RuntimeError as exc:575 except RuntimeError as exc:
567- raise ParserTypeError(str(exc), span=span) from exc576+ raise CommonExternal(message_of(exc), span=span, parser_retry=True) from exc
568 577 
569 578 
570@op_impl("simt.cast")579@op_impl("simt.cast")
571def _parse_simt_cast(parser: Any, call: ast.Call) -> Expr:580def _parse_simt_cast(parser: Any, call: ast.Call) -> Expr:
572 """Parse ``pl.simt.cast`` while preserving its scalar-specific diagnostics."""581 """Parse ``pl.simt.cast`` while preserving its scalar-specific diagnostics."""
573- from pypto_pro.language.parser.diagnostics import ParserSyntaxError, ParserTypeError
574 582 
575 span = parser.span_tracker.get_span(call)583 span = parser.span_tracker.get_span(call)
576 if parser._current_func_type not in (_ir_core.FunctionType.SimtVF, _ir_core.FunctionType.SimtCallee):584 if parser._current_func_type not in (_ir_core.FunctionType.SimtVF, _ir_core.FunctionType.SimtCallee):
577- raise ParserSyntaxError(585+ raise InvalidOperation(
578 "pl.simt.cast() can only be used inside a SIMT function",586 "pl.simt.cast() can only be used inside a SIMT function",
579 span=span,587 span=span,
580 hint="Move SIMT-context-dependent logic into @pl.vector_function(mode=\"simt\").",588 hint="Move SIMT-context-dependent logic into @pl.vector_function(mode=\"simt\").",
581 )589 )
582 590 
583 if len(call.args) != 2:591 if len(call.args) != 2:
584- raise ParserSyntaxError(592+ raise InvalidArgument(
585 f"pl.simt.cast() requires exactly 2 positional arguments, got {len(call.args)}",593 f"pl.simt.cast() requires exactly 2 positional arguments, got {len(call.args)}",
586 span=span,594 span=span,
587 hint="Use pl.simt.cast(value, pl.DT_FP32, mode=pl.RoundMode.CAST_RINT).",595 hint="Use pl.simt.cast(value, pl.DT_FP32, mode=pl.RoundMode.CAST_RINT).",
@@ -589,61 +597,63 @@ def _parse_simt_cast(parser: Any, call: ast.Call) -> Expr:
589 597 
590 mode_keywords = [kw for kw in call.keywords if kw.arg == "mode"]598 mode_keywords = [kw for kw in call.keywords if kw.arg == "mode"]
591 if len(mode_keywords) != len(call.keywords) or len(mode_keywords) > 1:599 if len(mode_keywords) != len(call.keywords) or len(mode_keywords) > 1:
592- raise ParserSyntaxError(600+ raise InvalidArgument(
593 "pl.simt.cast() only accepts one optional keyword argument: mode",601 "pl.simt.cast() only accepts one optional keyword argument: mode",
594 span=span,602 span=span,
595 )603 )
596 604 
597 value = parser.parse_expression(call.args[0])605 value = parser.parse_expression(call.args[0])
598 if not isinstance(value, Expr) or not isinstance(value.type, _ir_core.ScalarType):606 if not isinstance(value, Expr) or not isinstance(value.type, _ir_core.ScalarType):
599- raise ParserTypeError(607+ raise InvalidType(
600 "pl.simt.cast() value must be a scalar expression",608 "pl.simt.cast() value must be a scalar expression",
601 span=parser.span_tracker.get_span(call.args[0]),609 span=parser.span_tracker.get_span(call.args[0]),
610+ parser_retry=True,
602 )611 )
603 612 
604 dtype = parser.parse_expression(call.args[1])613 dtype = parser.parse_expression(call.args[1])
605 if not isinstance(dtype, _ir_core.DataType):614 if not isinstance(dtype, _ir_core.DataType):
606- raise ParserTypeError(615+ raise InvalidType(
607 "pl.simt.cast() dtype must be a pl.DT_* value",616 "pl.simt.cast() dtype must be a pl.DT_* value",
608 span=parser.span_tracker.get_span(call.args[1]),617 span=parser.span_tracker.get_span(call.args[1]),
618+ parser_retry=True,
609 )619 )
610 620 
611 mode = _ir_core.RoundMode.CAST_NONE621 mode = _ir_core.RoundMode.CAST_NONE
612 if mode_keywords:622 if mode_keywords:
613 mode = parser.resolve_single_kwarg("mode", mode_keywords[0].value)623 mode = parser.resolve_single_kwarg("mode", mode_keywords[0].value)
614 if not isinstance(mode, _ir_core.RoundMode):624 if not isinstance(mode, _ir_core.RoundMode):
615- raise ParserTypeError(625+ raise InvalidType(
616 "pl.simt.cast() mode must be a pl.RoundMode value",626 "pl.simt.cast() mode must be a pl.RoundMode value",
617 span=parser.span_tracker.get_span(mode_keywords[0].value),627 span=parser.span_tracker.get_span(mode_keywords[0].value),
628+ parser_retry=True,
618 )629 )
619 630 
620 try:631 try:
621 return cast(value, dtype, mode, span)632 return cast(value, dtype, mode, span)
622 except (ValueError, RuntimeError) as err:633 except (ValueError, RuntimeError) as err:
623 message = str(err).replace("simt.cast", "pl.simt.cast()")634 message = str(err).replace("simt.cast", "pl.simt.cast()")
624- raise ParserTypeError(message, span=span) from err635+ raise CommonExternal(message, span=span, parser_retry=True) from err
625 636 
626 637 
627@op_impl("simt.bitcast")638@op_impl("simt.bitcast")
628def _parse_simt_bitcast(parser: Any, call: ast.Call) -> Expr:639def _parse_simt_bitcast(parser: Any, call: ast.Call) -> Expr:
629 """Parse ``pl.simt.bitcast`` with scalar and dtype validation."""640 """Parse ``pl.simt.bitcast`` with scalar and dtype validation."""
630- from pypto_pro.language.parser.diagnostics import ParserSyntaxError, ParserTypeError
631 641 
632 span = parser.span_tracker.get_span(call)642 span = parser.span_tracker.get_span(call)
633 if parser._current_func_type not in (643 if parser._current_func_type not in (
634 _ir_core.FunctionType.SimtVF,644 _ir_core.FunctionType.SimtVF,
635 _ir_core.FunctionType.SimtCallee,645 _ir_core.FunctionType.SimtCallee,
636 ):646 ):
637- raise ParserSyntaxError(647+ raise InvalidOperation(
638 "pl.simt.bitcast() can only be used inside a SIMT function",648 "pl.simt.bitcast() can only be used inside a SIMT function",
639 span=span,649 span=span,
640 hint="Move SIMT-context-dependent logic into @pl.vector_function(mode=\"simt\").",650 hint="Move SIMT-context-dependent logic into @pl.vector_function(mode=\"simt\").",
641 )651 )
642 652 
643 if call.keywords:653 if call.keywords:
644- raise ParserSyntaxError("pl.simt.bitcast() does not accept keyword arguments", span=span)654+ raise InvalidArgument("pl.simt.bitcast() does not accept keyword arguments", span=span)
645 if len(call.args) != 2:655 if len(call.args) != 2:
646- raise ParserSyntaxError(656+ raise InvalidArgument(
647 f"pl.simt.bitcast() requires exactly 2 positional arguments, got {len(call.args)}",657 f"pl.simt.bitcast() requires exactly 2 positional arguments, got {len(call.args)}",
648 span=span,658 span=span,
649 hint="Use pl.simt.bitcast(value, pl.DT_UINT32).",659 hint="Use pl.simt.bitcast(value, pl.DT_UINT32).",
@@ -651,23 +661,25 @@ def _parse_simt_bitcast(parser: Any, call: ast.Call) -> Expr:
651 661 
652 value = parser.parse_expression(call.args[0])662 value = parser.parse_expression(call.args[0])
653 if not isinstance(value, Expr) or not isinstance(value.type, _ir_core.ScalarType):663 if not isinstance(value, Expr) or not isinstance(value.type, _ir_core.ScalarType):
654- raise ParserTypeError(664+ raise InvalidType(
655 "pl.simt.bitcast() value must be a scalar expression",665 "pl.simt.bitcast() value must be a scalar expression",
656 span=parser.span_tracker.get_span(call.args[0]),666 span=parser.span_tracker.get_span(call.args[0]),
667+ parser_retry=True,
657 )668 )
658 669 
659 dtype = parser.parse_expression(call.args[1])670 dtype = parser.parse_expression(call.args[1])
660 if not isinstance(dtype, _ir_core.DataType):671 if not isinstance(dtype, _ir_core.DataType):
661- raise ParserTypeError(672+ raise InvalidType(
662 "pl.simt.bitcast() dtype must be a pl.DT_* value",673 "pl.simt.bitcast() dtype must be a pl.DT_* value",
663 span=parser.span_tracker.get_span(call.args[1]),674 span=parser.span_tracker.get_span(call.args[1]),
675+ parser_retry=True,
664 )676 )
665 677 
666 try:678 try:
667 return bitcast(value, dtype, span)679 return bitcast(value, dtype, span)
668 except (ValueError, RuntimeError) as err:680 except (ValueError, RuntimeError) as err:
669 message = str(err).replace("simt.bitcast", "pl.simt.bitcast()")681 message = str(err).replace("simt.bitcast", "pl.simt.bitcast()")
670- raise ParserTypeError(message, span=span) from err682+ raise CommonExternal(message, span=span, parser_retry=True) from err
671 683 
672 684 
673def _parse_scalar_math(685def _parse_scalar_math(
@@ -677,18 +689,17 @@ def _parse_scalar_math(
677 expected_args: int,689 expected_args: int,
678 builder: Callable[..., Call],690 builder: Callable[..., Call],
679) -> Expr:691) -> Expr:
680- from pypto_pro.language.parser.diagnostics import ParserSyntaxError, ParserTypeError
681 692 
682 short_name = op_name[len("simt."):]693 short_name = op_name[len("simt."):]
683 span = parser.span_tracker.get_span(call)694 span = parser.span_tracker.get_span(call)
684 if parser._current_func_type not in (_ir_core.FunctionType.SimtVF, _ir_core.FunctionType.SimtCallee):695 if parser._current_func_type not in (_ir_core.FunctionType.SimtVF, _ir_core.FunctionType.SimtCallee):
685- raise ParserSyntaxError(696+ raise InvalidOperation(
686 f"pl.{op_name}() can only be used inside a SIMT function",697 f"pl.{op_name}() can only be used inside a SIMT function",
687 span=span,698 span=span,
688 hint="Move SIMT-context-dependent logic into @pl.vector_function(mode=\"simt\").",699 hint="Move SIMT-context-dependent logic into @pl.vector_function(mode=\"simt\").",
689 )700 )
690 if len(call.args) != expected_args or call.keywords:701 if len(call.args) != expected_args or call.keywords:
691- raise ParserSyntaxError(702+ raise InvalidArgument(
692 f"pl.simt.{short_name}() requires exactly {expected_args} positional argument"703 f"pl.simt.{short_name}() requires exactly {expected_args} positional argument"
693 f"{'s' if expected_args != 1 else ''}",704 f"{'s' if expected_args != 1 else ''}",
694 span=span,705 span=span,
@@ -696,15 +707,16 @@ def _parse_scalar_math(
696 args = [parser.parse_expression(arg) for arg in call.args]707 args = [parser.parse_expression(arg) for arg in call.args]
697 for index, (arg, arg_node) in enumerate(zip(args, call.args)):708 for index, (arg, arg_node) in enumerate(zip(args, call.args)):
698 if not isinstance(arg, Expr) or not isinstance(arg.type, _ir_core.ScalarType):709 if not isinstance(arg, Expr) or not isinstance(arg.type, _ir_core.ScalarType):
699- raise ParserTypeError(710+ raise InvalidVal(
700 f"pl.simt.{short_name}() argument {index + 1} must be a scalar expression",711 f"pl.simt.{short_name}() argument {index + 1} must be a scalar expression",
701 span=parser.span_tracker.get_span(arg_node),712 span=parser.span_tracker.get_span(arg_node),
702 hint="Subscript a Tile or Tensor first to obtain one scalar element.",713 hint="Subscript a Tile or Tensor first to obtain one scalar element.",
714+ parser_retry=True,
703 )715 )
704 try:716 try:
705 return builder(*args, span=span)717 return builder(*args, span=span)
706 except (ValueError, RuntimeError) as err:718 except (ValueError, RuntimeError) as err:
707- raise ParserTypeError(str(err), span=span) from err719+ raise CommonExternal(message_of(err), span=span, parser_retry=True) from err
708 720 
709 721 
710def _register_scalar_math_parser(op_name: str, expected_args: int, builder: Callable[..., Call]) -> None:722def _register_scalar_math_parser(op_name: str, expected_args: int, builder: Callable[..., Call]) -> None:
@@ -31,6 +31,7 @@ from pypto.pypto_impl.ir import (
31 SyncCoreType,31 SyncCoreType,
32)32)
33 33 
34+from ..._errors import InvalidArgument, InvalidOperation, InvalidShape, InvalidType, InvalidVal, 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 
@@ -79,54 +80,55 @@ def _is_integer_scalar_expr(value: Expr) -> bool:
79def _normalize_integer_id_expr(value: int | Expr, span: Span, *, name: str, max_id: int) -> Expr:80def _normalize_integer_id_expr(value: int | Expr, span: Span, *, name: str, max_id: int) -> Expr:
80 """Normalize an integer ID to an IR operand and validate statically known values."""81 """Normalize an integer ID to an IR operand and validate statically known values."""
81 if not isinstance(value, Expr) and not _is_int(value):82 if not isinstance(value, Expr) and not _is_int(value):
82- raise TypeError(f"{name} must be a Python int or an integer scalar expression")83+ raise InvalidType(f"{name} must be a Python int or an integer scalar expression", span=span)
83 expr = _normalize_expr(value, span)84 expr = _normalize_expr(value, span)
84 if not _is_integer_scalar_expr(expr):85 if not _is_integer_scalar_expr(expr):
85- raise TypeError(f"{name} must be an integer scalar expression")86+ raise InvalidType(f"{name} must be an integer scalar expression", span=span)
86 if isinstance(expr, _ir_core.ConstInt):87 if isinstance(expr, _ir_core.ConstInt):
87- _check_id_range(expr.value, max_id, name)88+ _check_id_range(expr.value, max_id, name, span=span)
88 return expr89 return expr
89 90 
90 91 
91-def _normalize_mutex_ids(mutex_ids: tuple | list | None) -> list[int] | None:92+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 """Validate candidate IDs before they are converted to vector<int>."""
93 if mutex_ids is None:94 if mutex_ids is None:
94 return None95 return None
95 if not isinstance(mutex_ids, (list, tuple)):96 if not isinstance(mutex_ids, (list, tuple)):
96- raise TypeError("mutex_ids must be a list, tuple, or None")97+ raise InvalidType("mutex_ids must be a list, tuple, or None", span=span)
97 normalized_mutex_ids = list(mutex_ids)98 normalized_mutex_ids = list(mutex_ids)
98 if not normalized_mutex_ids:99 if not normalized_mutex_ids:
99- raise ValueError("mutex_ids must not be empty")100+ raise InvalidVal("mutex_ids must not be empty", span=span)
100 for index, mutex_id in enumerate(normalized_mutex_ids):101 for index, mutex_id in enumerate(normalized_mutex_ids):
101 if not _is_int(mutex_id):102 if not _is_int(mutex_id):
102- raise TypeError(f"mutex_ids[{index}] must be a Python int")103+ 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")104+ _check_id_range(mutex_id, MAX_MUTEX_ID, "mutex_ids element", span=span)
104 return normalized_mutex_ids105 return normalized_mutex_ids
105 106 
106 107 
107-def _validate_concrete_pipe(pipe: PipeType, name: str) -> None:108+def _validate_concrete_pipe(pipe: PipeType, name: str, span: Span | None = None) -> None:
108 if not isinstance(pipe, PipeType):109 if not isinstance(pipe, PipeType):
109- raise TypeError(f"{name} must be a PipeType, got {type(pipe).__name__}")110+ raise InvalidType(f"{name} must be a PipeType, got {type(pipe).__name__}", span=span)
110 if pipe == PipeType.ALL:111 if pipe == PipeType.ALL:
111- raise ValueError(f"{name} must identify one concrete pipe, got PipeType.ALL")112+ raise InvalidArgument(f"{name} must identify one concrete pipe, got PipeType.ALL", span=span)
112 113 
113 114 
114-def _check_id_range(value: int, max_id: int, name: str, *, min_id: int = 0) -> None:115+def _check_id_range(value: int, max_id: int, name: str, *, min_id: int = 0, span: Span | None = None) -> None:
115 """Reject a hardware resource id outside its inclusive range."""116 """Reject a hardware resource id outside its inclusive range."""
116 from pypto_pro.language.parser.diagnostics import check_in_range117 from pypto_pro.language.parser.diagnostics import check_in_range
117 118 
118- check_in_range(value, min_id, max_id, subject=name, error=ValueError)119+ check_in_range(value, min_id, max_id, subject=name, span=span)
119 120 
120 121 
121def _validate_sync_pipes(122def _validate_sync_pipes(
122 set_pipe: PipeType,123 set_pipe: PipeType,
123 wait_pipe: PipeType,124 wait_pipe: PipeType,
124 target: _ir_core.SectionKind,125 target: _ir_core.SectionKind,
126+ span: Span | None = None,
125) -> None:127) -> None:
126- _validate_concrete_pipe(set_pipe, "set_pipe")128+ _validate_concrete_pipe(set_pipe, "set_pipe", span)
127- _validate_concrete_pipe(wait_pipe, "wait_pipe")129+ _validate_concrete_pipe(wait_pipe, "wait_pipe", span)
128 if set_pipe == wait_pipe:130 if set_pipe == wait_pipe:
129- raise ValueError(f"set_pipe and wait_pipe must differ, got {set_pipe}")131+ raise InvalidOperation(f"set_pipe and wait_pipe must differ, got {set_pipe}")
130 132 
131 is_cube = target == _ir_core.SectionKind.Cube133 is_cube = target == _ir_core.SectionKind.Cube
132 sync_wait_pipes = _A5_AIC_SYNC_WAIT_PIPES if is_cube else _A5_AIV_SYNC_WAIT_PIPES134 sync_wait_pipes = _A5_AIC_SYNC_WAIT_PIPES if is_cube else _A5_AIV_SYNC_WAIT_PIPES
@@ -135,7 +137,7 @@ def _validate_sync_pipes(
135 137 
136 if wait_pipe not in supported_wait_pipes:138 if wait_pipe not in supported_wait_pipes:
137 supported = ", ".join(str(pipe) for pipe in supported_wait_pipes)139 supported = ", ".join(str(pipe) for pipe in supported_wait_pipes)
138- raise ValueError(140+ raise NotSupported(
139 f"unsupported A5 synchronization path{side}: {set_pipe} -> {wait_pipe}; "141 f"unsupported A5 synchronization path{side}: {set_pipe} -> {wait_pipe}; "
140 f"supported wait_pipe values for {set_pipe}: {supported}"142 f"supported wait_pipe values for {set_pipe}: {supported}"
141 )143 )
@@ -349,18 +351,21 @@ def sync_all(
349 workspaces = []351 workspaces = []
350 352 
351 kwargs: dict[str, object] = {"mode": mode, "core_type": core_type}353 kwargs: dict[str, object] = {"mode": mode, "core_type": core_type}
354+ # Resolved before the checks below so their errors can report a location.
355+ actual_span = _get_span_or_capture(span)
352 356 
353 if mode == SyncAllMode.HARD:357 if mode == SyncAllMode.HARD:
354 if workspaces:358 if workspaces:
355- raise ValueError("Hard mode sync_all does not accept workspace arguments")359+ raise NotSupported("Hard mode sync_all does not accept workspace arguments", span=actual_span)
356 elif mode == SyncAllMode.SOFT:360 elif mode == SyncAllMode.SOFT:
357 if not workspaces:361 if not workspaces:
358- raise ValueError("Soft mode sync_all requires workspaces list (e.g. [gm, ub])")362+ raise InvalidArgument(
363+ "Soft mode sync_all requires workspaces list (e.g. [gm, ub])", span=actual_span
364+ )
359 365 
360 # Build args[0]: always a MakeTuple (empty for hard, populated for soft)366 # Build args[0]: always a MakeTuple (empty for hard, populated for soft)
361 ws_tuple = _to_make_tuple(workspaces)367 ws_tuple = _to_make_tuple(workspaces)
362 368 
363- actual_span = _get_span_or_capture(span)
364 return _ir_core.create_op_call("system.sync_all", [ws_tuple], kwargs, actual_span)369 return _ir_core.create_op_call("system.sync_all", [ws_tuple], kwargs, actual_span)
365 370 
366 371 
@@ -395,7 +400,7 @@ def dcci(
395 elif isinstance(offset, (int, Expr)):400 elif isinstance(offset, (int, Expr)):
396 args.append(_normalize_expr(offset, actual_span))401 args.append(_normalize_expr(offset, actual_span))
397 else:402 else:
398- raise TypeError("dcci offset must be an int, Expr, list, tuple, or None")403+ raise InvalidType("dcci offset must be an int, Expr, list, tuple, or None")
399 kwargs = {"cache_line": cache_line, "dst": dst}404 kwargs = {"cache_line": cache_line, "dst": dst}
400 return _ir_core.create_op_call("system.dcci", args, kwargs, actual_span)405 return _ir_core.create_op_call("system.dcci", args, kwargs, actual_span)
401 406 
@@ -417,7 +422,7 @@ def _create_mutex_op(
417 actual_span: Span,422 actual_span: Span,
418) -> Call:423) -> Call:
419 """Create one user-requested manual mutex operation."""424 """Create one user-requested manual mutex operation."""
420- _validate_concrete_pipe(pipe, "pipe")425+ _validate_concrete_pipe(pipe, "pipe", actual_span)
421 mutex_id_expr = _normalize_integer_id_expr(426 mutex_id_expr = _normalize_integer_id_expr(
422 mutex_id, actual_span, name="mutex_id", max_id=MAX_MUTEX_ID427 mutex_id, actual_span, name="mutex_id", max_id=MAX_MUTEX_ID
423 )428 )
@@ -453,9 +458,9 @@ def _create_mutex_dedup_op(
453 span: Source span.458 span: Source span.
454 """459 """
455 actual_span = span if span is not None else _get_span_or_capture(span, frame_offset=3)460 actual_span = span if span is not None else _get_span_or_capture(span, frame_offset=3)
456- _validate_concrete_pipe(pipe, "pipe")461+ _validate_concrete_pipe(pipe, "pipe", actual_span)
457 if not mutex_id_exprs:462 if not mutex_id_exprs:
458- raise ValueError("mutex_id requires at least one expression")463+ raise InvalidArgument("mutex_id requires at least one expression")
459 normalized_mutex_id_exprs = [464 normalized_mutex_id_exprs = [
460 _normalize_integer_id_expr(mutex_id, actual_span, name="mutex_id", max_id=MAX_MUTEX_ID)465 _normalize_integer_id_expr(mutex_id, actual_span, name="mutex_id", max_id=MAX_MUTEX_ID)
461 for mutex_id in mutex_id_exprs466 for mutex_id in mutex_id_exprs
@@ -463,9 +468,9 @@ def _create_mutex_dedup_op(
463 kwargs: dict = {"pipe": pipe}468 kwargs: dict = {"pipe": pipe}
464 if mutex_id_owner_indices is not None:469 if mutex_id_owner_indices is not None:
465 if len(mutex_id_owner_indices) != len(mutex_id_exprs):470 if len(mutex_id_owner_indices) != len(mutex_id_exprs):
466- raise ValueError("mutex_id_owner_indices length must match mutex_id_exprs length")471+ raise InvalidShape("mutex_id_owner_indices length must match mutex_id_exprs length")
467 kwargs["mutex_id_owner_indices"] = list(mutex_id_owner_indices)472 kwargs["mutex_id_owner_indices"] = list(mutex_id_owner_indices)
468- normalized_mutex_ids = _normalize_mutex_ids(mutex_ids_union)473+ normalized_mutex_ids = _normalize_mutex_ids(mutex_ids_union, actual_span)
469 if normalized_mutex_ids is not None:474 if normalized_mutex_ids is not None:
470 kwargs["mutex_ids"] = normalized_mutex_ids475 kwargs["mutex_ids"] = normalized_mutex_ids
471 return _ir_core.create_op_call(f"{op_name}_dyn", normalized_mutex_id_exprs, kwargs, actual_span)476 return _ir_core.create_op_call(f"{op_name}_dyn", normalized_mutex_id_exprs, kwargs, actual_span)
@@ -594,7 +599,7 @@ register_table(
594def _parse_system_sync(self, call: ast.Call, op_name: str):599def _parse_system_sync(self, call: ast.Call, op_name: str):
595 span = self.span_tracker.get_span(call)600 span = self.span_tracker.get_span(call)
596 kwargs = self.parse_op_kwargs(call)601 kwargs = self.parse_op_kwargs(call)
597- _validate_sync_pipes(kwargs["set_pipe"], kwargs["wait_pipe"], self.target)602+ _validate_sync_pipes(kwargs["set_pipe"], kwargs["wait_pipe"], self.target, span)
598 return _create_sync_op(op_name, **kwargs, span=span)603 return _create_sync_op(op_name, **kwargs, span=span)
599 604 
600 605 
@@ -621,9 +626,8 @@ def _parse_system_set_mm_layout_transform(self, call: ast.Call):
621 call_span = self.span_tracker.get_span(call)626 call_span = self.span_tracker.get_span(call)
622 kwargs = self.parse_op_kwargs(call)627 kwargs = self.parse_op_kwargs(call)
623 if "enabled" not in kwargs:628 if "enabled" not in kwargs:
624- from pypto_pro.language.parser.diagnostics import ParserSyntaxError
625 629 
626- raise ParserSyntaxError(630+ raise InvalidArgument(
627 "set_mm_layout_transform requires keyword argument 'enabled'",631 "set_mm_layout_transform requires keyword argument 'enabled'",
628 span=call_span,632 span=call_span,
629 )633 )
@@ -20,6 +20,7 @@ from collections.abc import Sequence
20 20 
21from pypto.pypto_impl.ir import DataType, Expr, HardwareInfo, MemRef, TensorType, TensorView, TileType, TileView21from pypto.pypto_impl.ir import DataType, Expr, HardwareInfo, MemRef, TensorType, TensorView, TileType, TileView
22 22 
23+from .._errors import InvalidArgument
23from ._utils import _normalize_shape24from ._utils import _normalize_shape
24 25 
25# Store the original native __init__26# Store the original native __init__
@@ -68,7 +69,7 @@ def _tile_type_init_wrapper(
68 """69 """
69 shape_exprs = _normalize_shape(shape)70 shape_exprs = _normalize_shape(shape)
70 if tile_view is not None and memref is None:71 if tile_view is not None and memref is None:
71- raise ValueError("tile_view requires memref to be specified")72+ raise InvalidArgument("tile_view requires memref to be specified")
72 _native_tile_type_init(self, shape_exprs, dtype, memref, tile_view, hardware_info)73 _native_tile_type_init(self, shape_exprs, dtype, memref, tile_view, hardware_info)
73 74 
74 75 
@@ -43,6 +43,7 @@ from pypto.ir import (
43)43)
44from pypto_pro.ir.op.block_ops import FillPadMode44from pypto_pro.ir.op.block_ops import FillPadMode
45 45 
46+from .._errors import InvalidOperation
46from . import TensorLayout47from . import TensorLayout
47 48 
48# ---------------------------------------------------------------------------49# ---------------------------------------------------------------------------
@@ -68,7 +69,7 @@ def _api_decl(func):
68 @functools.wraps(func)69 @functools.wraps(func)
69 def wrapper(*args, **kwargs):70 def wrapper(*args, **kwargs):
70 sig.bind(*args, **kwargs)71 sig.bind(*args, **kwargs)
71- raise RuntimeError(_API_MSG)72+ raise InvalidOperation(_API_MSG)
72 73 
73 wrapper.__wrapped__ = func74 wrapper.__wrapped__ = func
74 return wrapper75 return wrapper
@@ -33,4 +33,4 @@ __all__ = [
33 33 
34from ..typing import Scalar, Tensor34from ..typing import Scalar, Tensor
35from .decorator import inline35from .decorator import inline
36-from .diagnostics import ParserError # noqa: F40136+from .diagnostics import PyptoProError # noqa: F401