mlir-script.js 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713
  1. import * as child_process from 'child_process';
  2. import * as fs from 'fs/promises';
  3. import * as os from 'os';
  4. import * as path from 'path';
  5. import * as process from 'process';
  6. import * as readline from 'readline';
  7. import * as tablegen from './tablegen.js';
  8. import * as url from 'url';
  9. const write = (message) => {
  10. if (process.stdout.write) {
  11. process.stdout.write(message);
  12. }
  13. };
  14. const writeLine = (message) => {
  15. write(message + os.EOL);
  16. };
  17. class Operator {
  18. constructor(def) {
  19. this.def = def;
  20. // With template parameter substitution, opDialect and opName fields
  21. // from the Op base class now contain the actual substituted values
  22. this.opName = def.getValueAsString('opName');
  23. const dialectDef = this.def.getValueAsDef('opDialect');
  24. if (dialectDef) {
  25. this.dialectName = dialectDef.getValueAsString('name');
  26. }
  27. }
  28. getDialectName() {
  29. return this.dialectName || '';
  30. }
  31. getOperationName() {
  32. return this.dialectName && this.opName ? `${this.dialectName}.${this.opName}` : null;
  33. }
  34. }
  35. const access = async (path) => {
  36. try {
  37. await fs.access(path);
  38. return true;
  39. } catch {
  40. return false;
  41. }
  42. };
  43. const schema = async () => {
  44. const dirname = path.dirname(url.fileURLToPath(import.meta.url));
  45. const source = path.join(dirname, '..', 'third_party', 'source', 'mlir');
  46. const paths = [
  47. source, // Add base source directory for cross-repository includes
  48. path.join(source, 'llvm-project', 'mlir', 'include'),
  49. path.join(source, 'llvm-project', 'mlir', 'test', 'lib', 'Dialect', 'Transform'),
  50. path.join(source, 'llvm-project', 'mlir', 'include', 'mlir', 'Dialect', 'ArmNeon'),
  51. path.join(source, 'llvm-project', 'mlir', 'include', 'mlir', 'Dialect', 'ArmSME', 'IR'),
  52. path.join(source, 'llvm-project', 'mlir', 'include', 'mlir', 'Dialect', 'ArmSVE', 'IR'),
  53. path.join(source, 'llvm-project', 'mlir', 'examples', 'toy', 'Ch7', 'include'),
  54. path.join(source, 'stablehlo'),
  55. path.join(source, 'xla', 'xla', 'mlir_hlo'),
  56. path.join(source, 'onnx-mlir'),
  57. path.join(source, 'torch-mlir', 'include'),
  58. path.join(source, 'triton', 'include'),
  59. path.join(source, 'triton', 'third_party'),
  60. path.join(source, 'triton', 'third_party', 'amd', 'include', 'Dialect', 'TritonAMDGPU', 'IR'),
  61. path.join(source, 'iree', 'compiler', 'src'),
  62. path.join(source, 'FlashTensor', 'include'),
  63. path.join(source, 'tpu-mlir', 'include'),
  64. path.join(source, 'tensorflow'),
  65. path.join(source, 'tensorflow', 'tensorflow', 'compiler', 'mlir', 'tfrt', 'ir'),
  66. path.join(source, 'runtime', 'include'),
  67. path.join(source, 'plaidml'),
  68. path.join(source, 'plaidml', 'pmlc', 'dialect', 'pxa', 'ir'),
  69. path.join(source, 'mlir-dace', 'include'),
  70. path.join(source, 'lltz', 'mlir', 'dialect', 'include', 'Michelson'),
  71. path.join(source, 'lagrad', 'include', 'LAGrad'),
  72. path.join(source, 'TensorRT-Incubator', 'mlir-tensorrt', 'tensorrt', 'include'),
  73. path.join(source, 'TensorRT-Incubator', 'mlir-tensorrt', 'executor', 'include'),
  74. ];
  75. const dialects = [
  76. 'mlir/IR/BuiltinAttributeInterfaces.td',
  77. 'mlir/IR/BuiltinTypeInterfaces.td',
  78. 'mlir/IR/BuiltinLocationAttributes.td',
  79. 'mlir/IR/BuiltinDialect.td',
  80. 'mlir/IR/BuiltinOps.td',
  81. 'mlir/IR/BuiltinDialectBytecode.td',
  82. 'mlir/IR/BuiltinAttributes.td',
  83. 'mlir/IR/BuiltinTypes.td',
  84. 'mlir/Dialect/Async/IR/AsyncOps.td',
  85. 'mlir/Dialect/Affine/IR/AffineOps.td',
  86. 'mlir/Dialect/Affine/IR/AffineOps.td',
  87. 'mlir/Dialect/Arith/IR/ArithOps.td',
  88. 'mlir/Dialect/ControlFlow/IR/ControlFlowOps.td',
  89. 'mlir/Dialect/Func/IR/FuncOps.td',
  90. 'mlir/Dialect/GPU/IR/GPUOps.td',
  91. 'mlir/Dialect/SCF/IR/SCFOps.td',
  92. 'mlir/Dialect/Linalg/IR/LinalgOps.td',
  93. // 'mlir/Dialect/Linalg/IR/LinalgStructuredOps.td', // File not found 'mlir/Dialect/Linalg/IR/LinalgNamedStructuredOps.yamlgen.td'
  94. 'mlir/Dialect/Linalg/IR/LinalgRelayoutOps.td',
  95. 'mlir/Dialect/MemRef/IR/MemRefOps.td',
  96. 'mlir/Dialect/Bufferization/IR/BufferizationOps.td',
  97. 'mlir/Dialect/Quant/IR/QuantOps.td',
  98. 'mlir/Dialect/Shape/IR/ShapeOps.td',
  99. 'mlir/Dialect/SparseTensor/IR/SparseTensorOps.td',
  100. 'mlir/Dialect/Tensor/IR/TensorOps.td',
  101. 'mlir/Dialect/Tosa/IR/TosaOps.td',
  102. 'mlir/Dialect/Vector/IR/VectorOps.td',
  103. 'mlir/Dialect/X86Vector/X86Vector.td',
  104. 'mlir/Dialect/XeGPU/IR/XeGPUOps.td',
  105. 'mlir/Dialect/Transform/IR/TransformOps.td',
  106. 'mlir/Dialect/Transform/DebugExtension/DebugExtensionOps.td',
  107. 'mlir/Dialect/Transform/IRDLExtension/IRDLExtensionOps.td',
  108. 'mlir/Dialect/Transform/LoopExtension/LoopExtensionOps.td',
  109. 'mlir/Dialect/Transform/PDLExtension/PDLExtensionOps.td',
  110. 'mlir/Dialect/Transform/SMTExtension/SMTExtensionOps.td',
  111. 'mlir/Dialect/Transform/TuneExtension/TuneExtensionOps.td',
  112. 'TestTransformDialectExtension.td',
  113. 'iree/compiler/Dialect/Util/TransformOps/UtilTransformOps.td',
  114. 'mlir/Dialect/Linalg/TransformOps/LinalgTransformOps.td',
  115. 'mlir/Dialect/Linalg/TransformOps/LinalgMatchOps.td',
  116. 'mlir/Dialect/SCF/TransformOps/SCFTransformOps.td',
  117. 'mlir/Dialect/Bufferization/TransformOps/BufferizationTransformOps.td',
  118. 'mlir/Dialect/GPU/TransformOps/GPUTransformOps.td',
  119. 'mlir/Dialect/NVGPU/TransformOps/NVGPUTransformOps.td',
  120. 'mlir/Dialect/Affine/TransformOps/AffineTransformOps.td',
  121. 'mlir/Dialect/SparseTensor/TransformOps/SparseTensorTransformOps.td',
  122. 'mlir/Dialect/Tensor/TransformOps/TensorTransformOps.td',
  123. 'mlir/Dialect/Vector/TransformOps/VectorTransformOps.td',
  124. 'mlir/Dialect/MemRef/TransformOps/MemRefTransformOps.td',
  125. 'mlir/Dialect/Func/TransformOps/FuncTransformOps.td',
  126. 'mlir/Dialect/ArmNeon/TransformOps/ArmNeonVectorTransformOps.td',
  127. 'mlir/Dialect/ArmSVE/TransformOps/ArmSVEVectorTransformOps.td',
  128. 'mlir/Dialect/XeGPU/TransformOps/XeGPUTransformOps.td',
  129. 'mlir/Dialect/DLTI/TransformOps/DLTITransformOps.td',
  130. 'mlir/Dialect/WasmSSA/IR/WasmSSAOps.td',
  131. 'mlir/Dialect/IRDL/IR/IRDLOps.td',
  132. 'mlir/Dialect/LLVMIR/LLVMOps.td',
  133. 'mlir/Dialect/LLVMIR/LLVMIntrinsicOps.td',
  134. 'mlir/Dialect/LLVMIR/NVVMOps.td',
  135. 'mlir/Dialect/LLVMIR/ROCDLOps.td',
  136. // 'mlir/Dialect/OpenMP/OpenMPOps.td', // File not found 'mlir/Dialect/OpenMP/OmpCommon.td'
  137. 'mlir/Dialect/ArmSME/IR/ArmSMEOps.td',
  138. 'mlir/Dialect/ArmNeon/ArmNeon.td',
  139. 'mlir/Dialect/ArmSVE/IR/ArmSVE.td',
  140. 'mlir/Dialect/Math/IR/MathOps.td',
  141. 'mlir/Dialect/MLProgram/IR/MLProgramOps.td',
  142. 'mlir/Dialect/SPIRV/IR/SPIRVStructureOps.td',
  143. 'mlir/Dialect/SPIRV/IR/SPIRVControlFlowOps.td',
  144. 'mlir/Dialect/SPIRV/IR/SPIRVArithmeticOps.td',
  145. 'mlir/Dialect/SPIRV/IR/SPIRVLogicalOps.td',
  146. 'mlir/Dialect/SPIRV/IR/SPIRVBitOps.td',
  147. 'mlir/Dialect/SPIRV/IR/SPIRVCastOps.td',
  148. 'mlir/Dialect/SPIRV/IR/SPIRVCompositeOps.td',
  149. 'mlir/Dialect/SPIRV/IR/SPIRVAtomicOps.td',
  150. 'mlir/Dialect/SPIRV/IR/SPIRVBarrierOps.td',
  151. 'mlir/Dialect/SPIRV/IR/SPIRVGroupOps.td',
  152. 'mlir/Dialect/SPIRV/IR/SPIRVMemoryOps.td',
  153. 'mlir/Dialect/SPIRV/IR/SPIRVMiscOps.td',
  154. 'mlir/Dialect/SPIRV/IR/SPIRVMatrixOps.td',
  155. 'mlir/Dialect/SPIRV/IR/SPIRVImageOps.td',
  156. 'mlir/Dialect/SPIRV/IR/SPIRVGLOps.td',
  157. 'mlir/Dialect/SPIRV/IR/SPIRVCLOps.td',
  158. 'mlir/Dialect/SPIRV/IR/SPIRVNonUniformOps.td',
  159. 'mlir/Dialect/SPIRV/IR/SPIRVCooperativeMatrixOps.td',
  160. 'mlir/Dialect/SPIRV/IR/SPIRVIntegerDotProductOps.td',
  161. 'mlir/Dialect/SPIRV/IR/SPIRVIntelExtOps.td',
  162. 'mlir/Dialect/SPIRV/IR/SPIRVGraphOps.td',
  163. 'mlir/Dialect/SPIRV/IR/SPIRVMeshOps.td',
  164. 'mlir/Dialect/SPIRV/IR/SPIRVPrimitiveOps.td',
  165. 'mlir/Dialect/EmitC/IR/EmitC.td',
  166. 'mlir/Dialect/Complex/IR/ComplexOps.td',
  167. 'mlir/Dialect/Index/IR/IndexOps.td',
  168. 'mlir/Dialect/PDL/IR/PDLOps.td',
  169. 'mlir/Dialect/Ptr/IR/PtrOps.td',
  170. 'mlir/Dialect/UB/IR/UBOps.td',
  171. 'mlir/Dialect/AMDGPU/IR/AMDGPU.td',
  172. 'mlir/Dialect/NVGPU/IR/NVGPUOps.td',
  173. 'mlir/Dialect/Shard/IR/ShardOps.td',
  174. 'mlir/Dialect/AMX/AMX.td',
  175. 'mlir/Dialect/SMT/IR/SMTOps.td',
  176. 'mlir/Dialect/SMT/IR/SMTArrayOps.td',
  177. 'mlir/Dialect/SMT/IR/SMTBitVectorOps.td',
  178. 'mlir/Dialect/SMT/IR/SMTIntOps.td',
  179. // 'mlir/Dialect/OpenACC/OpenACCOps.td', // File not found 'mlir/Dialect/OpenACC/AccCommon.td'
  180. 'mlir/Dialect/LLVMIR/XeVMOps.td',
  181. 'toy/Ops.td',
  182. 'stablehlo/dialect/StablehloOps.td',
  183. 'stablehlo/dialect/ChloOps.td',
  184. 'stablehlo/dialect/VhloOps.td',
  185. 'stablehlo/reference/InterpreterOps.td',
  186. 'stablehlo/tests/CheckOps.td',
  187. 'mhlo/IR/hlo_ops.td',
  188. 'src/Dialect/ONNX/ONNX.td',
  189. 'src/Dialect/ONNX/ONNXOps.td.inc',
  190. 'src/Dialect/ONNX/AdditionalONNXOps.td',
  191. 'src/Dialect/Krnl/Krnl.td',
  192. 'torch-mlir/Dialect/Torch/IR/TorchOps.td',
  193. 'torch-mlir/Dialect/TorchConversion/IR/TorchConversionOps.td',
  194. 'torch-mlir-dialects/Dialect/TMTensor/IR/TMTensorOps.td',
  195. 'tensorflow/compiler/mlir/lite/ir/tfl_ops.td',
  196. 'tensorflow/compiler/mlir/tensorflow/ir/tf_ops.td',
  197. 'tensorflow/compiler/mlir/tensorflow/ir/tf_saved_model_ops.td',
  198. 'tensorflow/compiler/mlir/tensorflow/ir/tf_device_ops.td',
  199. 'tensorflow/compiler/mlir/tensorflow/ir/tf_executor_ops.td',
  200. 'tensorflow/compiler/mlir/tools/kernel_gen/ir/tf_framework_ops.td',
  201. 'tensorflow/compiler/mlir/tfr/ir/tfr_ops.td',
  202. 'tensorflow/compiler/mlir/tfrt/ir/tfrt_fallback.td',
  203. 'tensorflow/compiler/mlir/tfrt/ir/tfrt_fallback_async.td',
  204. 'tensorflow/compiler/mlir/tfrt/ir/tfrt_fallback_sync.td',
  205. 'tensorflow/compiler/mlir/tensorflow/ir/host_runtime/tfrt_ops.td',
  206. 'tensorflow/compiler/mlir/tfrt/runtime_fallback/runtime_fallback_ops.td',
  207. 'tensorflow/compiler/mlir/tfrt/ir/mlrt/mlrt_ops.td',
  208. 'tfrt/core_runtime/opdefs/core_runtime.td',
  209. 'tfrt/basic_kernels/opdefs/basic_kernels.td',
  210. 'tfrt/test_kernels/opdefs/test_kernels.td',
  211. 'tfrt/tensor/opdefs/tensor.td',
  212. 'tfrt/tensor/opdefs/dense_host_tensor.td',
  213. 'iree/compiler/Dialect/HAL/IR/HALOps.td',
  214. 'iree/compiler/Dialect/HAL/IR/HALTypes.td',
  215. 'iree/compiler/Modules/HAL/Loader/IR/HALLoaderOps.td',
  216. 'iree/compiler/Modules/HAL/Inline/IR/HALInlineOps.td',
  217. 'iree/compiler/Dialect/Flow/IR/FlowOps.td',
  218. 'iree/compiler/Dialect/Stream/IR/StreamOps.td',
  219. 'iree/compiler/Codegen/Dialect/VectorExt/IR/VectorExtOps.td',
  220. 'iree/compiler/Dialect/LinalgExt/IR/LinalgExtOps.td',
  221. 'iree/compiler/Dialect/LinalgExt/IR/LinalgExtPureOps.td',
  222. 'iree/compiler/Dialect/TensorExt/IR/TensorExtOps.td',
  223. 'iree/compiler/Dialect/Util/IR/UtilOps.td',
  224. 'iree/compiler/Dialect/VM/IR/VMOps.td',
  225. 'iree/compiler/Dialect/VMVX/IR/VMVXOps.td',
  226. 'iree/compiler/Codegen/Dialect/GPU/IR/IREEGPUOps.td',
  227. 'iree/compiler/Codegen/Dialect/Codegen/IR/IREECodegenOps.td',
  228. 'iree/compiler/Codegen/Dialect/Codegen/IR/UKernelOps.td',
  229. 'iree/compiler/Dialect/Encoding/IR/EncodingOps.td',
  230. 'asuka/Dialect/Asuka/IR/AsukaOps.td',
  231. 'tpu_mlir/Dialect/Top/IR/TopOps.td',
  232. 'tpu_mlir/Dialect/Tpu/IR/TpuOps.td',
  233. 'pmlc/dialect/tile/ir/ops.td',
  234. 'pmlc/dialect/stdx/ir/ops.td',
  235. // 'pmlc/dialect/pxa/ir/ops.td', // File not found 'mlir/Dialect/Arithmetic/IR/ArithmeticBase.td'
  236. 'SDFG/Dialect/Ops.td',
  237. 'MichelsonOps.td',
  238. 'triton/Dialect/Triton/IR/TritonOps.td',
  239. 'triton/Dialect/TritonGPU/IR/TritonGPUOps.td',
  240. 'triton/Dialect/Gluon/IR/GluonOps.td',
  241. 'triton/Dialect/TritonNvidiaGPU/IR/TritonNvidiaGPUOps.td',
  242. 'amd/include/Dialect/TritonAMDGPU/IR/TritonAMDGPUOps.td',
  243. 'proton/Dialect/include/Dialect/Proton/IR/ProtonOps.td',
  244. 'LAGradOps.td',
  245. 'mlir-tensorrt-dialect/TensorRT/IR/TensorRTOps.td',
  246. 'mlir-executor/Executor/IR/ExecutorOps.td',
  247. ];
  248. const file = path.join(dirname, '..', 'source', 'mlir-metadata.json');
  249. const operations = new Map();
  250. const exists = await access(file);
  251. if (exists) {
  252. const content = await fs.readFile(file, 'utf-8');
  253. const json = JSON.parse(content);
  254. for (const op of json) {
  255. if (op.name.endsWith('.') || op.name.includes('..') || op.name.includes('#')) {
  256. throw new Error(`Invalid operation name '${op.name}'.`);
  257. }
  258. if (op.name && !op.name.endsWith('.')) {
  259. operations.set(op.name, op);
  260. }
  261. }
  262. }
  263. let count = 0;
  264. const parser = new tablegen.Reader();
  265. await parser.parse(dialects, paths);
  266. for (const def of parser.defs) {
  267. const op = new Operator(def);
  268. const operationName = op.getOperationName();
  269. if (!operationName) {
  270. continue;
  271. }
  272. if (operationName.endsWith('.') || operationName.includes('..') || operationName.includes('#')) {
  273. throw new Error(`Invalid operation name '${operationName}'.`);
  274. }
  275. const operation = {
  276. name: operationName
  277. };
  278. if (operations.has(operationName)) {
  279. const existing = operations.get(operationName);
  280. if (existing.category) {
  281. operation.category = existing.category;
  282. }
  283. }
  284. let args = def.getValueAsDag('arguments');
  285. if (!args || !args.operands || args.operands.length === 0) {
  286. // Try to get from parent Arguments class
  287. for (const parent of def.parents) {
  288. if (parent.name === 'Arguments' && parent.args && parent.args.length > 0) {
  289. const [dagValue] = parent.args;
  290. if (dagValue && dagValue.type === 'dag') {
  291. args = dagValue.value;
  292. }
  293. break;
  294. }
  295. }
  296. }
  297. const name = operation.name.replace(/^(asuka|stablehlo|chlo|affine|linalg|memref|quant|vector|tosa|tfl|tf|onnx|torch\.aten|gpu)\./, '');
  298. if (['reshape', 'broadcast_in_dim', 'dynamic_reshape', 'Reshape', 'Shape', 'Size', 'ConstantOfShape'].indexOf(name) !== -1) {
  299. operation.category = 'Shape';
  300. } else if (['transpose', 'reverse', 'pad', 'Transpose', 'Pad'].indexOf(name) !== -1) {
  301. operation.category = 'Transform';
  302. } else if (['slice', 'split', 'dynamic_slice', 'gather', 'scatter', 'Slice', 'Gather', 'Scatter', 'concatenate'].indexOf(name) !== -1) {
  303. operation.category = 'Tensor';
  304. } else if (['tanh', 'Sigmoid', 'Tanh', 'Relu', 'Softmax', 'softmax', 'sigmoid', 'relu'].indexOf(name) !== -1) {
  305. operation.category = 'Activation';
  306. } else if (['convolution', 'Conv', 'matmul', 'batch_matmul', 'conv2d', 'conv3d', 'fully_connected', 'conv_2d'].indexOf(name) !== -1) {
  307. operation.category = 'Layer';
  308. } else if (['batch_norm_inference'].includes(name)) {
  309. operation.category = 'Normalization';
  310. }
  311. if (def.getValue('summary')) {
  312. const summary = def.getValueAsString('summary').trim();
  313. if (summary) {
  314. operation.summary = summary;
  315. }
  316. }
  317. if (def.getValue('description')) {
  318. const description = def.getValueAsString('description');
  319. if (description) {
  320. operation.description = description;
  321. }
  322. }
  323. // Convert TableGen value to constraint string
  324. const toConstraintString = (value) => {
  325. if (!value) {
  326. return null;
  327. }
  328. if (value.type === 'def') {
  329. const defName = value.value;
  330. // Check if this is an enum attribute or property and add enum cases
  331. let attrDef = parser.getDef(defName) || parser.getClass(defName);
  332. // If this is a ConfinedAttr, unwrap to get the underlying attribute type
  333. if (attrDef) {
  334. const checkIfConfinedAttr = (def) => {
  335. for (const parent of def.parents) {
  336. if (parent.name === 'ConfinedAttr' && parent.args && parent.args.length > 0) {
  337. // First arg is the underlying attr type
  338. const [underlyingAttr] = parent.args;
  339. if (underlyingAttr && underlyingAttr.type === 'def') {
  340. return parser.getDef(underlyingAttr.value) || parser.getClass(underlyingAttr.value);
  341. }
  342. }
  343. }
  344. return null;
  345. };
  346. const underlyingAttr = checkIfConfinedAttr(attrDef);
  347. if (underlyingAttr) {
  348. attrDef = underlyingAttr;
  349. }
  350. }
  351. // Resolve type aliases that inherit from Variadic/Optional - expand to full form
  352. if (attrDef) {
  353. for (const parent of attrDef.parents) {
  354. if (parent.name === 'Variadic' && parent.args && parent.args.length > 0) {
  355. const innerType = toConstraintString(parent.args[0]);
  356. return innerType ? `Variadic<${innerType}>` : 'Variadic';
  357. }
  358. if (parent.name === 'Optional' && parent.args && parent.args.length > 0) {
  359. const innerType = toConstraintString(parent.args[0]);
  360. return innerType ? `Optional<${innerType}>` : 'Optional';
  361. }
  362. }
  363. }
  364. if (attrDef && (attrDef.isEnumAttr() || attrDef.isEnumProp())) {
  365. const cases = attrDef.getEnumCases();
  366. if (cases && cases.length > 0) {
  367. return `${defName}{${cases.join('|')}}`;
  368. }
  369. }
  370. return defName;
  371. }
  372. if (value.type === 'string' || value.type === 'code') {
  373. return value.value;
  374. }
  375. if (value.type === 'int') {
  376. return String(value.value);
  377. }
  378. if (value.type === 'list') {
  379. const items = value.value.map((item) => toConstraintString(item)).filter((x) => x !== null);
  380. return items.length > 0 ? `[${items.join(', ')}]` : null;
  381. }
  382. if (value.type === 'dag' && value.value) {
  383. const dag = value.value;
  384. // Unwrap Arg/Res wrappers - they just hold the type constraint plus metadata
  385. // The first operand is the actual type constraint
  386. if ((dag.operator === 'Arg' || dag.operator === 'Res') && dag.operands.length > 0) {
  387. return toConstraintString(dag.operands[0].value);
  388. }
  389. const args = dag.operands.map((op) => toConstraintString(op.value)).filter((x) => x !== null);
  390. if (args.length > 0) {
  391. return `${dag.operator}<${args.join(', ')}>`;
  392. }
  393. return dag.operator;
  394. }
  395. return null;
  396. };
  397. const attributes = [];
  398. const inputs = [];
  399. const outputs = [];
  400. if (args && args.operator === 'ins') {
  401. for (const operand of args.operands) {
  402. if (operand.value && operand.name) {
  403. const type = toConstraintString(operand.value);
  404. // Check if this is an actual attribute/property constraint by looking up the def
  405. // and checking if it inherits from Attr or Property class (matches LLVM reference)
  406. const checkIsAttr = (record, visited = new Set()) => {
  407. if (!record || visited.has(record.name)) {
  408. return false;
  409. }
  410. visited.add(record.name);
  411. // Check for attribute base classes - both constraint and bytecode encoding types
  412. if (record.name === 'Attr' || record.name === 'AttributeKind' || record.name === 'DialectAttribute') {
  413. return true;
  414. }
  415. // Check for property base classes - properties are also attributes (compile-time metadata)
  416. if (record.name === 'Property' || record.name === 'PropConstraint' || record.name === 'EnumProp') {
  417. return true;
  418. }
  419. for (const parent of record.parents) {
  420. const parentClass = parser.getClass(parent.name);
  421. if (parentClass && checkIsAttr(parentClass, visited)) {
  422. return true;
  423. }
  424. }
  425. return false;
  426. };
  427. let isAttribute = false;
  428. if (operand.value) {
  429. if (operand.value.type === 'def') {
  430. // Simple def reference like StrAttr
  431. const constraintDef = parser.getDef(operand.value.value) || parser.getClass(operand.value.value);
  432. if (constraintDef) {
  433. isAttribute = checkIsAttr(constraintDef);
  434. }
  435. } else if (operand.value.type === 'dag' && operand.value.value) {
  436. // DAG constraint like OptionalAttr<StrAttr>
  437. const dag = operand.value.value;
  438. // Check the operator (e.g., OptionalAttr, DefaultValuedAttr)
  439. const operatorDef = parser.getDef(dag.operator) || parser.getClass(dag.operator);
  440. if (operatorDef && checkIsAttr(operatorDef)) {
  441. isAttribute = true;
  442. } else if (dag.operands && dag.operands.length > 0) {
  443. // Check the first operand (the wrapped type)
  444. const innerValue = dag.operands[0].value;
  445. if (innerValue && innerValue.type === 'def') {
  446. const innerDef = parser.getDef(innerValue.value) || parser.getClass(innerValue.value);
  447. if (innerDef && checkIsAttr(innerDef)) {
  448. isAttribute = true;
  449. }
  450. }
  451. }
  452. }
  453. }
  454. if (isAttribute) {
  455. attributes.push({ name: operand.name, type });
  456. } else {
  457. inputs.push({ name: operand.name, type });
  458. }
  459. }
  460. }
  461. }
  462. let results = def.getValueAsDag('results');
  463. if (!results || !results.operands || results.operands.length === 0) {
  464. // Try to get from parent Results class
  465. for (const parent of def.parents) {
  466. if (parent.name === 'Results' && parent.args && parent.args.length > 0) {
  467. const [dagValue] = parent.args;
  468. if (dagValue && dagValue.type === 'dag') {
  469. results = dagValue.value;
  470. }
  471. break;
  472. }
  473. }
  474. }
  475. if (results && results.operator === 'outs') {
  476. for (const operand of results.operands) {
  477. if (operand.value && operand.name) {
  478. const type = toConstraintString(operand.value);
  479. outputs.push({ name: operand.name, type });
  480. }
  481. }
  482. }
  483. if (inputs.length > 0) {
  484. operation.inputs = inputs;
  485. }
  486. if (outputs.length > 0) {
  487. operation.outputs = outputs;
  488. }
  489. if (attributes.length > 0) {
  490. operation.attributes = attributes;
  491. }
  492. const successors = def.getValueAsDag('successors');
  493. if (successors && successors.operator === 'successor') {
  494. const list = [];
  495. for (const operand of successors.operands) {
  496. if (operand.name) {
  497. list.push({ name: operand.name });
  498. }
  499. }
  500. if (list.length > 0) {
  501. operation.successors = list;
  502. }
  503. }
  504. const regions = def.getValueAsDag('regions');
  505. if (regions && regions.operator === 'region') {
  506. const list = [];
  507. for (const operand of regions.operands) {
  508. if (operand.name) {
  509. const type = toConstraintString(operand.value);
  510. list.push({ name: operand.name, type });
  511. }
  512. }
  513. if (list.length > 0) {
  514. operation.regions = list;
  515. }
  516. }
  517. if (def.getValue('assemblyFormat')) {
  518. const assemblyFormat = def.getValueAsString('assemblyFormat');
  519. if (assemblyFormat) {
  520. operation.assemblyFormat = assemblyFormat.trim();
  521. }
  522. }
  523. if (def.getValue('hasCustomAssemblyFormat') && def.getValueAsBit('hasCustomAssemblyFormat')) {
  524. operation.hasCustomAssemblyFormat = true;
  525. }
  526. if (def.getValue('parser')) {
  527. operation.parser = def.getValueAsString('parser');
  528. }
  529. // Extract defaultDialect from OpAsmOpInterface
  530. for (const parent of def.parents) {
  531. const possibleTraitArgs = parent.args && parent.args.length >= 2 ? [parent.args[1], parent.args[2]] : [];
  532. for (const traitsArg of possibleTraitArgs) {
  533. if (traitsArg && traitsArg.type === 'list' && traitsArg.value) {
  534. for (const trait of traitsArg.value) {
  535. const traitName = trait.type === 'def' ? trait.value : null;
  536. const traitDag = trait.type === 'dag' && trait.value?.operator ? trait.value.operator : null;
  537. if (traitName === 'OpAsmOpInterface' || traitDag === 'DeclareOpInterfaceMethods') {
  538. if (traitDag === 'DeclareOpInterfaceMethods' && trait.value?.operands) {
  539. if (trait.value.operands.some((operand) => operand.value && operand.value.type === 'list' && operand.value.value.some((method) => method.type === 'string' && method.value === 'getDefaultDialect'))) {
  540. const [dialectName] = operationName.split('.');
  541. operation.defaultDialect = dialectName;
  542. break;
  543. }
  544. }
  545. const extraClass = def.getValueAsString('extraClassDeclaration');
  546. if (extraClass) {
  547. const match = extraClass.match(/getDefaultDialect\(\)\s*\{\s*return\s+"(\w+)"/);
  548. if (match) {
  549. [, operation.defaultDialect] = match;
  550. break;
  551. }
  552. }
  553. }
  554. }
  555. if (operation.defaultDialect) {
  556. break;
  557. }
  558. }
  559. }
  560. if (operation.defaultDialect) {
  561. break;
  562. }
  563. }
  564. if (Object.keys(operation).length > 1) {
  565. operations.set(operationName, operation);
  566. count++;
  567. }
  568. }
  569. const sorted = Array.from(operations.values()).sort((a, b) => a.name.localeCompare(b.name));
  570. const output = JSON.stringify(sorted, null, 2);
  571. const formatted = output.replace(/\{\s+"name":\s+"([^"]+)",\s+"type":\s+"([^"]+)"\s+\}/g, '{ "name": "$1", "type": "$2" }');
  572. await fs.writeFile(file, formatted, 'utf-8');
  573. if (count < 6300) {
  574. throw new Error(`Unexpected operation count '${count}'.`);
  575. }
  576. };
  577. const test = async (pattern) => {
  578. pattern = pattern || './third_party/source/mlir/**/*.mlir';
  579. const errorTotals = new Map();
  580. const filesByError = new Map();
  581. const fileErrorDetails = new Map();
  582. let currentFile = null;
  583. const validFiles = new Set();
  584. const invalidFiles = new Set([
  585. 'third_party/source/mlir/stablehlo/stablehlo/tests/ops_stablehlo.mlir',
  586. 'third_party/source/mlir/stablehlo/stablehlo/tests/print_types_invalid.mlir',
  587. 'third_party/source/mlir/stablehlo/stablehlo/tests/vhlo/invalid_vhlo_future.mlir',
  588. 'third_party/source/mlir/torch-mlir/test/Dialect/Torch/verify-backend-contract-error.mlir'
  589. ]);
  590. return new Promise((resolve, reject) => {
  591. const cmd = 'npm';
  592. const args = ['run', 'test', 'continue', pattern];
  593. const process = child_process.spawn(cmd, args, { stdio: ['ignore', 'pipe', 'pipe'] });
  594. const stdout = readline.createInterface({ input: process.stdout, crlfDelay: Infinity });
  595. const stderr = readline.createInterface({ input: process.stderr, crlfDelay: Infinity });
  596. const processLine = (line) => {
  597. writeLine(line);
  598. const stripped = line.trim();
  599. if (!stripped) {
  600. return;
  601. }
  602. if (stripped.startsWith('third_party/')) {
  603. currentFile = stripped;
  604. if (stripped.toLowerCase().includes('invalid')) {
  605. invalidFiles.add(currentFile);
  606. } else {
  607. validFiles.add(currentFile);
  608. }
  609. return;
  610. }
  611. if (currentFile && invalidFiles.has(currentFile)) {
  612. return;
  613. }
  614. if (currentFile && !invalidFiles.has(currentFile)) {
  615. // Skip summary lines (e.g., "123 / 456 = 78.9%")
  616. if (/^\s*\d+\s*\/\s*\d+\s*=\s*[\d.]+%\s*$/.test(stripped)) {
  617. return;
  618. }
  619. // Normalize error message
  620. const key = stripped.split(' at ', 1)[0].trim().replace(/\.$/, '').trim();
  621. if (key) {
  622. errorTotals.set(key, (errorTotals.get(key) || 0) + 1);
  623. if (!filesByError.has(key)) {
  624. filesByError.set(key, new Map());
  625. }
  626. const fileCounts = filesByError.get(key);
  627. fileCounts.set(currentFile, (fileCounts.get(currentFile) || 0) + 1);
  628. if (!fileErrorDetails.has(key)) {
  629. fileErrorDetails.set(key, new Map());
  630. }
  631. const details = fileErrorDetails.get(key);
  632. if (!details.has(currentFile)) {
  633. details.set(currentFile, []);
  634. }
  635. details.get(currentFile).push(stripped);
  636. }
  637. }
  638. };
  639. stdout.on('line', processLine);
  640. stderr.on('line', processLine);
  641. process.on('error', (error) => {
  642. reject(new Error(`Failed to start process: ${error.message}`));
  643. });
  644. process.on('close', (/* code */) => {
  645. const totalValid = validFiles.size;
  646. const totalInvalid = invalidFiles.size;
  647. const filesWithErrors = new Set();
  648. for (const [, fileCounts] of filesByError) {
  649. for (const file of fileCounts.keys()) {
  650. filesWithErrors.add(file);
  651. }
  652. }
  653. const succeeded = totalValid - filesWithErrors.size;
  654. writeLine('');
  655. writeLine('-'.repeat(75));
  656. if (errorTotals.size > 0) {
  657. const sortedErrors = Array.from(errorTotals.entries()).sort((a, b) => b[1] - a[1]).slice(0, 10);
  658. for (const [err, cnt] of sortedErrors) {
  659. const fileCounts = filesByError.get(err);
  660. const topFiles = Array.from(fileCounts.entries())
  661. .sort((a, b) => b[1] - a[1])
  662. .slice(0, 100);
  663. writeLine(`${cnt} | ${err}`);
  664. for (const [file,] of topFiles) {
  665. writeLine(` ${file}`);
  666. const details = fileErrorDetails.get(err).get(file);
  667. for (const specificError of details) {
  668. writeLine(` ${specificError}`);
  669. }
  670. }
  671. writeLine('');
  672. }
  673. }
  674. if (totalValid > 0) {
  675. const percentage = (succeeded * 100.0) / totalValid;
  676. writeLine(` ${succeeded} / ${totalValid} = ${percentage.toPrecision(6)}% - skipped ${totalInvalid} files`);
  677. } else {
  678. writeLine(' No valid files processed');
  679. }
  680. writeLine();
  681. resolve();
  682. });
  683. });
  684. };
  685. const main = async () => {
  686. const command = process.argv.length >= 3 ? process.argv[2] : 'schema';
  687. switch (command) {
  688. case 'test': {
  689. writeLine(process.argv);
  690. await test(process.argv.slice(3).join(' '));
  691. break;
  692. }
  693. case 'schema':
  694. default: {
  695. await schema();
  696. break;
  697. }
  698. }
  699. };
  700. await main();