mlir-script.js 63 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147
  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. this.opName = def.getValueAsString('opName');
  21. const dialectDef = this.def.getValueAsDef('opDialect');
  22. if (dialectDef) {
  23. this.dialectName = dialectDef.getValueAsString('name');
  24. }
  25. }
  26. getDialectName() {
  27. return this.dialectName || '';
  28. }
  29. getOperationName() {
  30. return this.dialectName && this.opName ? `${this.dialectName}.${this.opName}` : null;
  31. }
  32. }
  33. const access = async (path) => {
  34. try {
  35. await fs.access(path);
  36. return true;
  37. } catch {
  38. return false;
  39. }
  40. };
  41. const schema = async () => {
  42. const dirname = path.dirname(url.fileURLToPath(import.meta.url));
  43. const paths = [
  44. '',
  45. 'llvm-project',
  46. 'llvm-project/mlir/include',
  47. 'llvm-project/mlir/test/lib/Dialect/Test',
  48. 'llvm-project/mlir/test/lib/Dialect/Transform',
  49. 'llvm-project/mlir/test/lib/Transforms',
  50. 'llvm-project/mlir/include/mlir/Dialect/ArmNeon',
  51. 'llvm-project/mlir/include/mlir/Dialect/ArmSME/IR',
  52. 'llvm-project/mlir/include/mlir/Dialect/ArmSVE/IR',
  53. 'llvm-project/mlir/examples/standalone/include',
  54. 'llvm-project/mlir/examples/toy/Ch7/include',
  55. 'llvm-project/mlir/examples/transform/Ch2/include',
  56. 'llvm-project/mlir/examples/transform/Ch3/include',
  57. 'llvm-project/mlir/examples/transform/Ch4/include',
  58. 'stablehlo',
  59. 'shardy',
  60. 'xla/xla/mlir_hlo',
  61. 'xla',
  62. 'onnx-mlir',
  63. 'torch-mlir/include',
  64. 'triton/include',
  65. 'triton/third_party',
  66. 'triton/third_party/amd/include/Dialect/TritonAMDGPU/IR',
  67. 'iree/compiler/src',
  68. 'iree/compiler/src/iree/compiler/Codegen/Dialect/PCF/IR',
  69. 'iree/compiler/src/iree/compiler/Modules/IO/Parameters/IR',
  70. 'iree/llvm-external-projects/iree-dialects/include',
  71. 'FlashTensor/include',
  72. 'tpu-mlir/include',
  73. 'tensorflow',
  74. 'tensorflow/tensorflow/core/ir',
  75. 'tensorflow/tensorflow/compiler/mlir/tfrt/ir',
  76. 'xla/xla/backends/gpu/codegen/triton/ir',
  77. 'runtime/include',
  78. 'plaidml',
  79. 'plaidml/pmlc/dialect/pxa/ir',
  80. 'mlir-dace/include',
  81. 'lltz/mlir/dialect/include/Michelson',
  82. 'lagrad/include/LAGrad',
  83. 'TensorRT-Incubator/mlir-tensorrt/tensorrt/include',
  84. 'TensorRT-Incubator/mlir-tensorrt/executor/include',
  85. 'TensorRT-Incubator/mlir-tensorrt/compiler/include',
  86. 'TensorRT-Incubator/mlir-tensorrt/kernel/include',
  87. 'TensorRT-Incubator/mlir-tensorrt/common/include',
  88. 'triton/third_party/nvidia/include',
  89. 'triton/third_party/nvidia/include/Dialect/NVGPU/IR',
  90. 'triton/third_party/nvidia/include/Dialect/NVWS/IR',
  91. 'triton/examples/plugins/DialectPlugins/DialectPlugin/include',
  92. 'clangir',
  93. 'clangir/clang/include',
  94. 'rocMLIR',
  95. 'rocMLIR/mlir/include',
  96. 'ensemble-compilation/lib/Dialect/Ensemble',
  97. 'mlir-tutorial/lib/Dialect/Poly',
  98. 'mlir-tutorial/lib/Dialect/Noisy',
  99. 'mlir-xten/include',
  100. 'tt-mlir/include',
  101. 'tt-mlir/include/ttmlir/Dialect/TTCore/IR',
  102. 'tt-mlir/include/ttmlir/Dialect/TTIR/IR',
  103. 'tt-mlir/include/ttmlir/Dialect/TTNN/IR',
  104. 'tt-mlir/include/ttmlir/Dialect/TTKernel/IR',
  105. 'tt-mlir/include/ttmlir/Dialect/TTMetal/IR',
  106. '_/llvm-project/mlir/include',
  107. '_/mlir-hlo',
  108. ];
  109. const dialects = [
  110. 'pmlc/dialect/tile/ir/ops.td',
  111. 'pmlc/dialect/stdx/ir/ops.td',
  112. 'pmlc/dialect/pxa/ir/ops.td',
  113. 'pmlc/dialect/linalgx/ir/ops.td',
  114. 'pmlc/dialect/xsmm/ir/ops.td',
  115. 'pmlc/dialect/layer/ir/ops.td',
  116. 'mlir/include/mlir/IR/BuiltinAttributeInterfaces.td',
  117. 'mlir/include/mlir/IR/BuiltinTypeInterfaces.td',
  118. 'mlir/include/mlir/IR/BuiltinLocationAttributes.td',
  119. 'mlir/include/mlir/IR/BuiltinDialect.td',
  120. 'mlir/include/mlir/IR/BuiltinOps.td',
  121. 'mlir/include/mlir/IR/BuiltinDialectBytecode.td',
  122. 'mlir/include/mlir/IR/BuiltinAttributes.td',
  123. 'mlir/include/mlir/IR/BuiltinTypes.td',
  124. 'mlir/include/mlir/Dialect/Affine/IR/AffineOps.td',
  125. 'mlir/include/mlir/Dialect/Affine/TransformOps/AffineTransformOps.td',
  126. 'mlir/include/mlir/Dialect/AMDGPU/IR/AMDGPU.td',
  127. 'mlir/include/mlir/Dialect/AMX/AMX.td',
  128. 'mlir/include/mlir/Dialect/Arith/IR/ArithOps.td',
  129. 'mlir/include/mlir/Dialect/ArmNeon/ArmNeon.td',
  130. 'mlir/include/mlir/Dialect/ArmNeon/TransformOps/ArmNeonVectorTransformOps.td',
  131. 'mlir/include/mlir/Dialect/ArmSME/IR/ArmSMEOps.td',
  132. 'mlir/include/mlir/Dialect/ArmSVE/IR/ArmSVE.td',
  133. 'mlir/include/mlir/Dialect/ArmSVE/TransformOps/ArmSVEVectorTransformOps.td',
  134. 'mlir/include/mlir/Dialect/Async/IR/AsyncOps.td',
  135. 'mlir/include/mlir/Dialect/Bufferization/IR/BufferizationOps.td',
  136. 'mlir/include/mlir/Dialect/Bufferization/TransformOps/BufferizationTransformOps.td',
  137. 'mlir/include/mlir/Dialect/Complex/IR/ComplexOps.td',
  138. 'mlir/include/mlir/Dialect/ControlFlow/IR/ControlFlowOps.td',
  139. 'mlir/include/mlir/Dialect/DLTI/TransformOps/DLTITransformOps.td',
  140. 'mlir/include/mlir/Dialect/EmitC/IR/EmitC.td',
  141. 'mlir/include/mlir/Dialect/Func/IR/FuncOps.td',
  142. 'mlir/include/mlir/Dialect/Func/TransformOps/FuncTransformOps.td',
  143. 'mlir/include/mlir/Dialect/GPU/IR/GPUOps.td',
  144. 'mlir/include/mlir/Dialect/GPU/TransformOps/GPUTransformOps.td',
  145. 'mlir/include/mlir/Dialect/Index/IR/IndexOps.td',
  146. 'mlir/include/mlir/Dialect/IRDL/IR/IRDLOps.td',
  147. 'mlir/include/mlir/Dialect/Linalg/IR/LinalgOps.td',
  148. 'mlir/include/mlir/Dialect/Linalg/IR/LinalgRelayoutOps.td',
  149. 'mlir/include/mlir/Dialect/Linalg/IR/LinalgStructuredOps.td',
  150. 'mlir/include/mlir/Dialect/Linalg/TransformOps/LinalgMatchOps.td',
  151. 'mlir/include/mlir/Dialect/Linalg/TransformOps/LinalgTransformOps.td',
  152. 'mlir/include/mlir/Dialect/LLVMIR/LLVMIntrinsicOps.td',
  153. 'mlir/include/mlir/Dialect/LLVMIR/LLVMOps.td',
  154. 'mlir/include/mlir/Dialect/LLVMIR/NVVMOps.td',
  155. 'mlir/include/mlir/Dialect/LLVMIR/ROCDLOps.td',
  156. 'mlir/include/mlir/Dialect/LLVMIR/XeVMOps.td',
  157. 'mlir/include/mlir/Dialect/Math/IR/MathOps.td',
  158. 'mlir/include/mlir/Dialect/MemRef/IR/MemRefOps.td',
  159. 'mlir/include/mlir/Dialect/MemRef/TransformOps/MemRefTransformOps.td',
  160. 'mlir/include/mlir/Dialect/MLProgram/IR/MLProgramOps.td',
  161. 'mlir/include/mlir/Dialect/MPI/IR/MPIOps.td',
  162. 'mlir/include/mlir/Dialect/NVGPU/IR/NVGPUOps.td',
  163. 'mlir/include/mlir/Dialect/NVGPU/TransformOps/NVGPUTransformOps.td',
  164. 'mlir/include/mlir/Dialect/OpenACC/OpenACCOps.td',
  165. 'mlir/include/mlir/Dialect/OpenMP/OpenMPOps.td',
  166. 'mlir/include/mlir/Dialect/PDL/IR/PDLOps.td',
  167. 'mlir/include/mlir/Dialect/PDLInterp/IR/PDLInterpOps.td',
  168. 'mlir/include/mlir/Dialect/Ptr/IR/PtrOps.td',
  169. 'mlir/include/mlir/Dialect/Quant/IR/QuantOps.td',
  170. 'mlir/include/mlir/Dialect/SCF/IR/SCFOps.td',
  171. 'mlir/include/mlir/Dialect/SCF/TransformOps/SCFTransformOps.td',
  172. 'mlir/include/mlir/Dialect/Shape/IR/ShapeOps.td',
  173. 'mlir/include/mlir/Dialect/Shard/IR/ShardOps.td',
  174. 'mlir/include/mlir/Dialect/SMT/IR/SMTOps.td',
  175. 'mlir/include/mlir/Dialect/SMT/IR/SMTArrayOps.td',
  176. 'mlir/include/mlir/Dialect/SMT/IR/SMTBitVectorOps.td',
  177. 'mlir/include/mlir/Dialect/SMT/IR/SMTIntOps.td',
  178. 'mlir/include/mlir/Dialect/SparseTensor/IR/SparseTensorOps.td',
  179. 'mlir/include/mlir/Dialect/SparseTensor/TransformOps/SparseTensorTransformOps.td',
  180. 'mlir/include/mlir/Dialect/SPIRV/IR/SPIRVArithmeticOps.td',
  181. 'mlir/include/mlir/Dialect/SPIRV/IR/SPIRVAtomicOps.td',
  182. 'mlir/include/mlir/Dialect/SPIRV/IR/SPIRVBarrierOps.td',
  183. 'mlir/include/mlir/Dialect/SPIRV/IR/SPIRVBitOps.td',
  184. 'mlir/include/mlir/Dialect/SPIRV/IR/SPIRVCastOps.td',
  185. 'mlir/include/mlir/Dialect/SPIRV/IR/SPIRVCLOps.td',
  186. 'mlir/include/mlir/Dialect/SPIRV/IR/SPIRVCompositeOps.td',
  187. 'mlir/include/mlir/Dialect/SPIRV/IR/SPIRVControlFlowOps.td',
  188. 'mlir/include/mlir/Dialect/SPIRV/IR/SPIRVCooperativeMatrixOps.td',
  189. 'mlir/include/mlir/Dialect/SPIRV/IR/SPIRVGLOps.td',
  190. 'mlir/include/mlir/Dialect/SPIRV/IR/SPIRVGraphOps.td',
  191. 'mlir/include/mlir/Dialect/SPIRV/IR/SPIRVGroupOps.td',
  192. 'mlir/include/mlir/Dialect/SPIRV/IR/SPIRVImageOps.td',
  193. 'mlir/include/mlir/Dialect/SPIRV/IR/SPIRVIntegerDotProductOps.td',
  194. 'mlir/include/mlir/Dialect/SPIRV/IR/SPIRVIntelExtOps.td',
  195. 'mlir/include/mlir/Dialect/SPIRV/IR/SPIRVLogicalOps.td',
  196. 'mlir/include/mlir/Dialect/SPIRV/IR/SPIRVMatrixOps.td',
  197. 'mlir/include/mlir/Dialect/SPIRV/IR/SPIRVMemoryOps.td',
  198. 'mlir/include/mlir/Dialect/SPIRV/IR/SPIRVMeshOps.td',
  199. 'mlir/include/mlir/Dialect/SPIRV/IR/SPIRVMiscOps.td',
  200. 'mlir/include/mlir/Dialect/SPIRV/IR/SPIRVNonUniformOps.td',
  201. 'mlir/include/mlir/Dialect/SPIRV/IR/SPIRVPrimitiveOps.td',
  202. 'mlir/include/mlir/Dialect/SPIRV/IR/SPIRVStructureOps.td',
  203. 'mlir/include/mlir/Dialect/SPIRV/IR/SPIRVTosaOps.td',
  204. 'mlir/include/mlir/Dialect/Tensor/IR/TensorOps.td',
  205. 'mlir/include/mlir/Dialect/Tensor/TransformOps/TensorTransformOps.td',
  206. 'mlir/include/mlir/Dialect/Tosa/IR/TosaOps.td',
  207. 'mlir/include/mlir/Dialect/Transform/DebugExtension/DebugExtensionOps.td',
  208. 'mlir/include/mlir/Dialect/Transform/IR/TransformOps.td',
  209. 'mlir/include/mlir/Dialect/Transform/IRDLExtension/IRDLExtensionOps.td',
  210. 'mlir/include/mlir/Dialect/Transform/LoopExtension/LoopExtensionOps.td',
  211. 'mlir/include/mlir/Dialect/Transform/PDLExtension/PDLExtensionOps.td',
  212. 'mlir/include/mlir/Dialect/Transform/SMTExtension/SMTExtensionOps.td',
  213. 'mlir/include/mlir/Dialect/Transform/TuneExtension/TuneExtensionOps.td',
  214. 'mlir/include/mlir/Dialect/UB/IR/UBOps.td',
  215. 'mlir/include/mlir/Dialect/Vector/IR/VectorOps.td',
  216. 'mlir/include/mlir/Dialect/Vector/TransformOps/VectorTransformOps.td',
  217. 'mlir/include/mlir/Dialect/WasmSSA/IR/WasmSSAOps.td',
  218. 'mlir/include/mlir/Dialect/X86Vector/X86Vector.td',
  219. 'mlir/include/mlir/Dialect/X86Vector/TransformOps/X86VectorTransformOps.td',
  220. 'mlir/include/mlir/Dialect/XeGPU/IR/XeGPUOps.td',
  221. 'mlir/include/mlir/Dialect/XeGPU/TransformOps/XeGPUTransformOps.td',
  222. 'mlir/examples/toy/Ch7/include/toy/Ops.td',
  223. 'mlir/examples/transform/Ch2/include/MyExtension.td',
  224. 'mlir/examples/transform/Ch3/include/MyExtension.td',
  225. 'mlir/examples/transform/Ch4/include/MyExtension.td',
  226. 'stablehlo/dialect/StablehloOps.td',
  227. 'stablehlo/dialect/ChloOps.td',
  228. 'stablehlo/dialect/VhloOps.td',
  229. 'stablehlo/reference/InterpreterOps.td',
  230. 'stablehlo/tests/CheckOps.td',
  231. 'shardy/dialect/sdy/ir/ops.td',
  232. 'shardy/dialect/mpmd/ir/ops.td',
  233. 'mhlo/IR/hlo_ops.td',
  234. 'thlo/IR/thlo_ops.td',
  235. 'src/Dialect/ONNX/ONNX.td',
  236. 'src/Dialect/ONNX/ONNXOps.td.inc',
  237. 'src/Dialect/ONNX/AdditionalONNXOps.td',
  238. 'src/Dialect/Krnl/Krnl.td',
  239. 'torch-mlir/Dialect/Torch/IR/TorchOps.td',
  240. 'torch-mlir/Dialect/TorchConversion/IR/TorchConversionOps.td',
  241. 'torch-mlir-dialects/Dialect/TMTensor/IR/TMTensorOps.td',
  242. 'tensorflow/core/ir/ops.td',
  243. 'tensorflow/compiler/mlir/lite/ir/tfl_ops.td',
  244. 'tensorflow/compiler/mlir/tensorflow/ir/tf_ops.td',
  245. 'tensorflow/compiler/mlir/tensorflow/ir/tf_saved_model_ops.td',
  246. 'tensorflow/compiler/mlir/tensorflow/ir/tf_device_ops.td',
  247. 'tensorflow/compiler/mlir/tensorflow/ir/tf_executor_ops.td',
  248. 'tensorflow/compiler/mlir/tools/kernel_gen/ir/tf_framework_ops.td',
  249. 'tensorflow/compiler/mlir/tfr/ir/tfr_ops.td',
  250. 'tensorflow/compiler/mlir/tfrt/ir/tfrt_fallback.td',
  251. 'tensorflow/compiler/mlir/tfrt/ir/tfrt_fallback_async.td',
  252. 'tensorflow/compiler/mlir/tfrt/ir/tfrt_fallback_sync.td',
  253. 'tensorflow/compiler/mlir/tfrt/ir/mlrt/tf_mlrt_ops.td',
  254. 'tensorflow/compiler/mlir/tensorflow/ir/host_runtime/tfrt_ops.td',
  255. 'tensorflow/compiler/mlir/tfrt/runtime_fallback/runtime_fallback_ops.td',
  256. 'tensorflow/compiler/mlir/tfrt/ir/mlrt/mlrt_ops.td',
  257. 'tfrt/core_runtime/opdefs/core_runtime.td',
  258. 'tfrt/core_runtime/opdefs/sync/core_runtime.td',
  259. 'tfrt/basic_kernels/opdefs/basic_kernels.td',
  260. 'tfrt/test_kernels/opdefs/test_kernels.td',
  261. 'tfrt/tensor/opdefs/tensor.td',
  262. 'tfrt/tensor/opdefs/dense_host_tensor.td',
  263. 'tfrt/tensor/opdefs/coo_host_tensor.td',
  264. 'tfrt/tensor/opdefs/tensor_shape.td',
  265. 'mlir/test/lib/Dialect/Test/TestOps.td',
  266. 'mlir/test/lib/Dialect/Test/TestOpsSyntax.td',
  267. 'mlir/test/lib/Dialect/Transform/TestTransformDialectExtension.td',
  268. 'mlir/test/lib/Interfaces/TilingInterface/TestTilingInterfaceTransformOps.td',
  269. 'mlir/test/lib/Transforms/TestTransformsOps.td',
  270. 'iree/compiler/Dialect/HAL/IR/HALOps.td',
  271. 'iree/compiler/Dialect/HAL/IR/HALTypes.td',
  272. 'iree/compiler/Modules/HAL/Loader/IR/HALLoaderOps.td',
  273. 'iree/compiler/Modules/HAL/Inline/IR/HALInlineOps.td',
  274. 'iree/compiler/Modules/IO/Parameters/IR/IOParametersOps.td',
  275. 'iree/compiler/Dialect/Flow/IR/FlowOps.td',
  276. 'iree/compiler/Dialect/Stream/IR/StreamOps.td',
  277. 'iree/compiler/Dialect/Util/TransformOps/UtilTransformOps.td',
  278. 'iree/compiler/Codegen/Dialect/GPU/TransformExtensions/IREEGPUExtensionsOps.td',
  279. 'iree/compiler/Codegen/Common/TransformExtensions/CommonExtensionsOps.td',
  280. 'iree/compiler/Codegen/LLVMGPU/TransformExtensions/LLVMGPUExtensionsOps.td',
  281. 'iree/compiler/Dialect/Flow/TransformExtensions/FlowExtensionsOps.td',
  282. 'iree/compiler/Dialect/LinalgExt/TransformExtensions/LinalgExtExtensionsOps.td',
  283. 'iree/compiler/Preprocessing/TransformExtensions/PreprocessingExtensionsOps.td',
  284. 'iree/compiler/Codegen/Dialect/VectorExt/IR/VectorExtOps.td',
  285. 'iree/compiler/Codegen/Dialect/PCF/IR/PCFOps.td',
  286. 'iree/compiler/Codegen/Dialect/GPU/IR/IREEGPUOps.td',
  287. 'iree/compiler/Codegen/Dialect/Codegen/IR/IREECodegenOps.td',
  288. 'iree/compiler/Codegen/Dialect/Codegen/IR/UKernelOps.td',
  289. 'iree/compiler/Dialect/LinalgExt/IR/LinalgExtOps.td',
  290. 'iree/compiler/Dialect/LinalgExt/IR/LinalgExtPureOps.td',
  291. 'iree/compiler/Dialect/TensorExt/IR/TensorExtOps.td',
  292. 'iree/compiler/Dialect/Util/IR/UtilOps.td',
  293. 'iree/compiler/Dialect/VM/IR/VMOps.td',
  294. 'iree/compiler/Dialect/VMVX/IR/VMVXOps.td',
  295. 'iree/compiler/Dialect/Encoding/IR/EncodingOps.td',
  296. 'iree/compiler/src/iree/compiler/Modules/Check/IR/CheckOps.td',
  297. 'iree-dialects/Dialect/LinalgTransform/StructuredTransformOpsExt.td',
  298. 'asuka/Dialect/Asuka/IR/AsukaOps.td',
  299. 'tpu_mlir/Dialect/Top/IR/TopOps.td',
  300. 'tpu_mlir/Dialect/Tpu/IR/TpuOps.td',
  301. 'SDFG/Dialect/Ops.td',
  302. 'lltz/mlir/dialect/include/Michelson/MichelsonOps.td',
  303. 'triton/Dialect/Triton/IR/TritonOps.td',
  304. 'triton/Dialect/TritonGPU/IR/TritonGPUOps.td',
  305. 'triton/Dialect/TritonInstrument/IR/TritonInstrumentOps.td',
  306. 'triton/Dialect/Gluon/IR/GluonOps.td',
  307. 'triton/Dialect/TritonNvidiaGPU/IR/TritonNvidiaGPUOps.td',
  308. 'triton/third_party/nvidia/include/Dialect/NVWS/IR/NVWSOps.td',
  309. 'triton/examples/plugins/DialectPlugins/DialectPlugin/include/DialectPlugin/DialectPluginOps.td',
  310. 'amd/include/Dialect/TritonAMDGPU/IR/TritonAMDGPUOps.td',
  311. 'proton/Dialect/include/Dialect/Proton/IR/ProtonOps.td',
  312. 'proton/Dialect/include/Dialect/ProtonGPU/IR/ProtonGPUOps.td',
  313. 'lagrad/include/LAGrad/LAGradOps.td',
  314. 'mlir-tensorrt-dialect/TensorRT/IR/TensorRTOps.td',
  315. 'mlir-executor/Executor/IR/ExecutorOps.td',
  316. 'mlir-tensorrt/Dialect/CUDA/IR/CUDAOps.td',
  317. 'mlir-tensorrt/Dialect/TensorRTRuntime/IR/TensorRTRuntimeOps.td',
  318. 'mlir-tensorrt/Dialect/Plan/IR/PlanOps.td',
  319. 'mlir-kernel/Kernel/IR/Ops.td',
  320. 'mlir-kernel/Kernel/TransformOps/KernelTransformOps.td',
  321. 'Dialect/NVGPU/IR/NVGPUOps.td',
  322. 'Standalone/StandaloneOps.td',
  323. 'clang/include/clang/CIR/Dialect/IR/CIROps.td',
  324. 'mlir/include/mlir/Dialect/MIGraphX/IR/MIGraphX.td',
  325. 'xla/backends/cpu/codegen/emitters/ir/xla_cpu_ops.td',
  326. 'xla/backends/gpu/codegen/emitters/ir/xla_gpu_ops.td',
  327. 'xla/backends/gpu/codegen/triton/ir/triton_xla_ops.td',
  328. 'xla/codegen/emitters/ir/xla_ops.td',
  329. 'xla/codegen/xtile/ir/xtile_ops.td',
  330. 'xla/python/ifrt/ir/ifrt_ops.td',
  331. 'xla/python/ifrt/ir/vifrt_ops.td',
  332. 'xla/xla/mlir/framework/ir/xla_framework_ops.td',
  333. 'xten/Dialect/XTenNN/IR/XTenNNOps.td',
  334. 'ensemble-compilation/lib/Dialect/Ensemble/EnsembleOps.td',
  335. 'mlir-tutorial/lib/Dialect/Poly/PolyOps.td',
  336. 'NoisyOps.td',
  337. 'ttmlir/Dialect/TTCore/IR/TTCoreOps.td',
  338. 'ttmlir/Dialect/TTIR/IR/TTIROps.td',
  339. 'ttmlir/Dialect/TTNN/IR/TTNNOps.td',
  340. 'ttmlir/Dialect/TTKernel/IR/TTKernelOps.td',
  341. 'ttmlir/Dialect/TTMetal/IR/TTMetalOps.td',
  342. ];
  343. const file = path.join(dirname, '..', 'source', 'mlir-metadata.json');
  344. const operations = new Map();
  345. const exists = await access(file);
  346. if (exists) {
  347. const content = await fs.readFile(file, 'utf-8');
  348. const json = JSON.parse(content);
  349. for (const op of json) {
  350. if (op.name.endsWith('.') || op.name.includes('..') || op.name.includes('#')) {
  351. throw new Error(`Invalid operation name '${op.name}'.`);
  352. }
  353. if (op.name && !op.name.endsWith('.')) {
  354. operations.set(op.name, op);
  355. }
  356. }
  357. }
  358. let count = 0;
  359. const parser = new tablegen.Reader();
  360. const source = path.join(dirname, '..', 'third_party', 'source', 'mlir');
  361. await parser.parse(dialects, paths.map((p) => path.join(source, ...p.split('/'))));
  362. for (const def of parser.defs) {
  363. const op = new Operator(def);
  364. let operationName = op.getOperationName();
  365. if (!operationName) {
  366. continue;
  367. }
  368. if (operationName.endsWith('.') || operationName.includes('..') || operationName.includes('#')) {
  369. throw new Error(`Invalid operation name '${operationName}'.`);
  370. }
  371. // Workaround: Handle conflicting dialects from stablehlo and iree
  372. if (operationName.startsWith('check.')) {
  373. if (def.location.file.includes('stablehlo')) {
  374. operationName = operationName.replace(/^check./, 'check.<stablehlo>.');
  375. } else if (def.location.file.includes('iree')) {
  376. operationName = operationName.replace(/^check./, 'check.<iree>.');
  377. }
  378. }
  379. const operation = {
  380. name: operationName
  381. };
  382. if (operations.has(operationName)) {
  383. const existing = operations.get(operationName);
  384. if (existing.category) {
  385. operation.category = existing.category;
  386. }
  387. }
  388. let args = def.getValueAsDag('arguments');
  389. if (!args || !args.operands || args.operands.length === 0) {
  390. // Try to get from parent Arguments class
  391. for (const parent of def.parents) {
  392. if (parent.name === 'Arguments' && parent.args && parent.args.length > 0) {
  393. const [dagValue] = parent.args;
  394. if (dagValue && dagValue.type === 'dag') {
  395. args = dagValue.value;
  396. }
  397. break;
  398. }
  399. }
  400. }
  401. const name = operation.name.replace(/^(asuka|stablehlo|chlo|affine|linalg|memref|quant|vector|tosa|tfl|tf|onnx|torch\.aten|gpu)\./, '');
  402. if (['reshape', 'broadcast_in_dim', 'dynamic_reshape', 'Reshape', 'Shape', 'Size', 'ConstantOfShape'].includes(name)) {
  403. operation.category = 'Shape';
  404. } else if (['transpose', 'reverse', 'pad', 'Transpose', 'Pad'].includes(name)) {
  405. operation.category = 'Transform';
  406. } else if (['slice', 'split', 'dynamic_slice', 'gather', 'scatter', 'Slice', 'Gather', 'Scatter', 'concat', 'concatenate'].includes(name)) {
  407. operation.category = 'Tensor';
  408. } else if (['tanh', 'Sigmoid', 'Tanh', 'Relu', 'Softmax', 'softmax', 'sigmoid', 'relu', 'clamp'].includes(name)) {
  409. operation.category = 'Activation';
  410. } else if (['convolution', 'Conv', 'conv2d', 'conv3d', 'fully_connected', 'conv_2d'].includes(name)) {
  411. operation.category = 'Layer';
  412. } else if (['max_pool2d', 'MaxPoolSingleOut'].includes(name)) {
  413. operation.category = 'Pool';
  414. } else if (['batch_norm_inference'].includes(name)) {
  415. operation.category = 'Normalization';
  416. }
  417. if (def.getValue('summary')) {
  418. const summary = def.getValueAsString('summary').trim();
  419. if (summary) {
  420. operation.summary = summary;
  421. }
  422. }
  423. if (def.getValue('description')) {
  424. const description = def.getValueAsString('description');
  425. if (description) {
  426. operation.description = description;
  427. }
  428. }
  429. // Convert TableGen value to constraint string
  430. const toConstraintString = (value) => {
  431. if (!value) {
  432. return null;
  433. }
  434. if (value.type === 'def') {
  435. const defName = value.value;
  436. // Check if this is an enum attribute or property and add enum cases
  437. const attrDef = parser.getDef(defName) || parser.getClass(defName);
  438. // Resolve type aliases to their base forms for proper parser dispatch
  439. if (attrDef) {
  440. for (const parent of attrDef.parents) {
  441. // ConfinedAttr<BaseAttr, Constraints> -> ConfinedAttr<BaseAttr, Constraints>
  442. if (parent.name === 'ConfinedAttr' && parent.args && parent.args.length > 0) {
  443. const args = parent.args.map((arg) => toConstraintString(arg)).filter((x) => x !== null);
  444. return `ConfinedAttr<${args.join(', ')}>`;
  445. }
  446. // TypedArrayAttrBase<ElementType, ...> -> TypedArrayAttrBase<ElementType>
  447. if (parent.name === 'TypedArrayAttrBase' && parent.args && parent.args.length > 0) {
  448. const innerType = toConstraintString(parent.args[0]);
  449. return innerType ? `TypedArrayAttrBase<${innerType}>` : 'ArrayAttr';
  450. }
  451. // Variadic<Type> -> Variadic<Type>
  452. if (parent.name === 'Variadic' && parent.args && parent.args.length > 0) {
  453. const innerType = toConstraintString(parent.args[0]);
  454. return innerType ? `Variadic<${innerType}>` : 'Variadic';
  455. }
  456. // Optional<Type> -> Optional<Type>
  457. if (parent.name === 'Optional' && parent.args && parent.args.length > 0) {
  458. const innerType = toConstraintString(parent.args[0]);
  459. return innerType ? `Optional<${innerType}>` : 'Optional';
  460. }
  461. }
  462. }
  463. if (attrDef && (attrDef.isEnumAttr() || attrDef.isEnumProp())) {
  464. const cases = attrDef.getEnumCases();
  465. if (cases && cases.length > 0) {
  466. return `${defName}{${cases.join('|')}}`;
  467. }
  468. }
  469. return defName;
  470. }
  471. if (value.type === 'string' || value.type === 'code') {
  472. return value.value;
  473. }
  474. if (value.type === 'int') {
  475. return String(value.value);
  476. }
  477. if (value.type === 'list') {
  478. const items = value.value.map((item) => toConstraintString(item)).filter((x) => x !== null);
  479. return items.length > 0 ? `[${items.join(', ')}]` : null;
  480. }
  481. if (value.type === 'dag' && value.value) {
  482. const dag = value.value;
  483. // Unwrap Arg/Res wrappers - they just hold the type constraint plus metadata
  484. // The first operand is the actual type constraint
  485. if ((dag.operator === 'Arg' || dag.operator === 'Res') && dag.operands.length > 0) {
  486. return toConstraintString(dag.operands[0].value);
  487. }
  488. const args = dag.operands.map((op) => toConstraintString(op.value)).filter((x) => x !== null);
  489. if (args.length > 0) {
  490. return `${dag.operator}<${args.join(', ')}>`;
  491. }
  492. return dag.operator;
  493. }
  494. return null;
  495. };
  496. const attributes = [];
  497. const operands = [];
  498. const results = [];
  499. if (args && args.operator === 'ins') {
  500. for (const operand of args.operands) {
  501. if (operand.value && operand.name) {
  502. const type = toConstraintString(operand.value);
  503. // Check if this is an actual attribute/property constraint by looking up the def
  504. // and checking if it inherits from Attr or Property class (matches LLVM reference)
  505. const checkIsAttr = (record, visited = new Set()) => {
  506. if (!record || visited.has(record.name)) {
  507. return false;
  508. }
  509. visited.add(record.name);
  510. // Check for attribute base classes - both constraint and bytecode encoding types
  511. if (record.name === 'Attr' || record.name === 'AttributeKind' || record.name === 'DialectAttribute') {
  512. return true;
  513. }
  514. // Check for property base classes - properties are also attributes (compile-time metadata)
  515. if (record.name === 'Property' || record.name === 'PropConstraint' || record.name === 'EnumProp') {
  516. return true;
  517. }
  518. // Check for enum attribute base classes (e.g., AtomicBinOp, AtomicOrdering)
  519. // Inheritance chain: LLVM_EnumAttr -> I64EnumAttr -> IntEnumAttr -> EnumAttrInfo
  520. if (record.name === 'EnumAttrInfo' || record.name === 'IntEnumAttr' ||
  521. record.name === 'I32EnumAttr' || record.name === 'I64EnumAttr' ||
  522. record.name === 'IntEnumAttrBase' || record.name === 'SignlessIntegerAttrBase' ||
  523. record.name === 'BitEnumAttr' || record.name === 'I32BitEnumAttr' ||
  524. record.name === 'I64BitEnumAttr') {
  525. return true;
  526. }
  527. for (const parent of record.parents || []) {
  528. const parentClass = parser.getClass(parent.name);
  529. if (parentClass && checkIsAttr(parentClass, visited)) {
  530. return true;
  531. }
  532. // Fallback: if parent class not found, check if the parent name itself
  533. // matches known enum attribute base classes (handles cases where the
  534. // base class definition wasn't parsed from included files)
  535. if (!parentClass && parent.name) {
  536. if (parent.name === 'I64EnumAttr' || parent.name === 'I32EnumAttr' ||
  537. parent.name === 'IntEnumAttr' || parent.name === 'EnumAttrInfo' ||
  538. parent.name === 'BitEnumAttr' || parent.name === 'I32BitEnumAttr' ||
  539. parent.name === 'I64BitEnumAttr' || parent.name.endsWith('EnumAttr')) {
  540. return true;
  541. }
  542. }
  543. }
  544. return false;
  545. };
  546. // Recursively check if a value represents an attribute type
  547. const checkValueIsAttr = (value) => {
  548. if (!value) {
  549. return false;
  550. }
  551. if (value.type === 'def') {
  552. // Simple def reference like StrAttr
  553. const constraintDef = parser.getDef(value.value) || parser.getClass(value.value);
  554. if (constraintDef) {
  555. return checkIsAttr(constraintDef);
  556. }
  557. // Fallback: if definition not found but name ends with "Attr", treat as attribute
  558. // This handles cases like CancellationConstructTypeAttr which are generated/external
  559. if (typeof value.value === 'string' && value.value.endsWith('Attr')) {
  560. return true;
  561. }
  562. // Also check for enum predicates (like IntPredicate, CmpIPredicate) which inherit from
  563. // I64EnumAttr but don't end with "Attr" - look for the Predicate suffix pattern
  564. if (typeof value.value === 'string' && value.value.endsWith('Predicate')) {
  565. return true;
  566. }
  567. return false;
  568. }
  569. if (value.type === 'dag' && value.value) {
  570. // DAG constraint like OptionalAttr<StrAttr> or Arg<OptionalAttr<ArrayAttr>, ...>
  571. const dag = value.value;
  572. // Check the operator (e.g., OptionalAttr, DefaultValuedAttr)
  573. const operatorDef = parser.getDef(dag.operator) || parser.getClass(dag.operator);
  574. if (operatorDef && checkIsAttr(operatorDef)) {
  575. return true;
  576. }
  577. // Fallback: if operator name ends with "Attr", treat as attribute
  578. if (typeof dag.operator === 'string' && dag.operator.endsWith('Attr')) {
  579. return true;
  580. }
  581. // For wrappers like Arg<...>, check the first operand recursively
  582. if (dag.operands && dag.operands.length > 0) {
  583. return checkValueIsAttr(dag.operands[0].value);
  584. }
  585. }
  586. return false;
  587. };
  588. const isAttribute = checkValueIsAttr(operand.value);
  589. if (isAttribute) {
  590. attributes.push({ name: operand.name, type });
  591. } else {
  592. operands.push({ name: operand.name, type });
  593. }
  594. }
  595. }
  596. }
  597. // If no attributes were found from 'arguments', try to extract from 'builders'
  598. // Some ops (like krnl.entry_point) define attributes only via builders
  599. if (attributes.length === 0) {
  600. const buildersField = def.getValue('builders');
  601. if (buildersField && buildersField.value && buildersField.value.type === 'list') {
  602. const buildersList = buildersField.value.value;
  603. if (buildersList && buildersList.length > 0) {
  604. // Try to get attribute name mappings from extraClassDeclaration
  605. const attrNameMap = new Map();
  606. const extraDecl = def.getValueAsString('extraClassDeclaration');
  607. if (extraDecl) {
  608. // Match patterns like: static StringRef getXxxAttrName() { return "yyy"; }
  609. const matches = extraDecl.matchAll(/get(\w+)AttrName\(\)\s*\{\s*return\s+"(\w+)"/g);
  610. for (const match of matches) {
  611. // Map parameter name (camelCase) to actual attribute name
  612. const paramName = match[1].charAt(0).toLowerCase() + match[1].slice(1);
  613. attrNameMap.set(paramName, match[2]);
  614. }
  615. }
  616. // Parse first OpBuilder<(ins ...)> to extract attributes
  617. for (const builder of buildersList) {
  618. if (builder.type === 'dag' && builder.value && builder.value.operator === 'OpBuilder') {
  619. const builderOperands = builder.value.operands;
  620. if (builderOperands && builderOperands.length > 0) {
  621. const [insArg] = builderOperands;
  622. if (insArg && insArg.value && insArg.value.type === 'dag' && insArg.value.value.operator === 'ins') {
  623. const insDag = insArg.value.value;
  624. for (const param of insDag.operands) {
  625. // Builder parameters have string types like "SymbolRefAttr":$name
  626. if (param.value && param.value.type === 'string' && param.name) {
  627. const cppType = param.value.value;
  628. // Only include Attr types (not Value or other C++ types)
  629. if (cppType.endsWith('Attr') || cppType.includes('Attr:')) {
  630. // Strip trailing Attr suffix variations and get base attr name
  631. const attrType = cppType.replace(/::$/, '').replace(/:.*$/, '');
  632. // Use the mapped name if available, otherwise derive from param name
  633. let attrName = param.name;
  634. // Remove common suffixes like 'Attr' from the parameter name
  635. const cleanParamName = attrName.replace(/Attr$/, '');
  636. if (attrNameMap.has(cleanParamName)) {
  637. attrName = attrNameMap.get(cleanParamName);
  638. } else if (attrNameMap.has(attrName)) {
  639. attrName = attrNameMap.get(attrName);
  640. } else {
  641. attrName = cleanParamName;
  642. }
  643. attributes.push({ name: attrName, type: attrType });
  644. }
  645. }
  646. }
  647. break; // Only process first builder
  648. }
  649. }
  650. }
  651. }
  652. }
  653. }
  654. }
  655. let resultsDag = def.getValueAsDag('results');
  656. if (!resultsDag || !resultsDag.operands || resultsDag.operands.length === 0) {
  657. // Try to get from parent Results class
  658. for (const parent of def.parents) {
  659. if (parent.name === 'Results' && parent.args && parent.args.length > 0) {
  660. const [dagValue] = parent.args;
  661. if (dagValue && dagValue.type === 'dag') {
  662. resultsDag = dagValue.value;
  663. }
  664. break;
  665. }
  666. }
  667. }
  668. if (resultsDag && resultsDag.operator === 'outs') {
  669. for (let i = 0; i < resultsDag.operands.length; i++) {
  670. const operand = resultsDag.operands[i];
  671. if (operand.value) {
  672. const type = toConstraintString(operand.value);
  673. // Use operand name if present, otherwise generate default name
  674. const name = operand.name || (resultsDag.operands.length === 1 ? 'result' : `result${i}`);
  675. results.push({ name, type });
  676. }
  677. }
  678. }
  679. if (operands.length > 0) {
  680. operation.operands = operands;
  681. }
  682. if (results.length > 0) {
  683. operation.results = results;
  684. }
  685. if (attributes.length > 0) {
  686. operation.attributes = attributes;
  687. }
  688. const successors = def.getValueAsDag('successors');
  689. if (successors && successors.operator === 'successor') {
  690. const list = [];
  691. for (const operand of successors.operands) {
  692. if (operand.name) {
  693. const type = toConstraintString(operand.value);
  694. list.push({ name: operand.name, type });
  695. }
  696. }
  697. if (list.length > 0) {
  698. operation.successors = list;
  699. }
  700. }
  701. const regions = def.getValueAsDag('regions');
  702. if (regions && regions.operator === 'region') {
  703. const list = [];
  704. for (const operand of regions.operands) {
  705. if (operand.name) {
  706. const type = toConstraintString(operand.value);
  707. list.push({ name: operand.name, type });
  708. }
  709. }
  710. if (list.length > 0) {
  711. operation.regions = list;
  712. }
  713. }
  714. // Extract traits (isolation, type inference, operand segments, and interface traits)
  715. const traits = [];
  716. const extractTraitsFromList = (traitsArg) => {
  717. if (!traitsArg) {
  718. return;
  719. }
  720. // Handle concat expressions: traits # [list of traits]
  721. if (traitsArg.type === 'concat' && Array.isArray(traitsArg.value)) {
  722. for (const element of traitsArg.value) {
  723. extractTraitsFromList(element);
  724. }
  725. return;
  726. }
  727. // Handle !listconcat expressions (stored as bang type)
  728. if (traitsArg.type === 'bang' && traitsArg.value) {
  729. const bangOp = traitsArg.value.operator || traitsArg.value.op;
  730. if (bangOp === 'listconcat' && traitsArg.value.args) {
  731. for (const arg of traitsArg.value.args) {
  732. extractTraitsFromList(arg);
  733. }
  734. return;
  735. }
  736. }
  737. // Handle arrays directly (evaluated listconcat results)
  738. if (Array.isArray(traitsArg)) {
  739. for (const element of traitsArg) {
  740. extractTraitsFromList({ type: 'list', value: [element] });
  741. }
  742. return;
  743. }
  744. if (traitsArg.type === 'list' && traitsArg.value) {
  745. for (const trait of traitsArg.value) {
  746. const traitName = trait.type === 'def' ? trait.value : null;
  747. const traitDag = trait.type === 'dag' && trait.value && trait.value.operator ? trait.value.operator : null;
  748. // Extract AllTypesMatch traits as string - parsed on demand in getOperation
  749. if (traitDag === 'AllTypesMatch' && trait.value && trait.value.operands) {
  750. const [namesOperand] = trait.value.operands;
  751. if (namesOperand && namesOperand.value && namesOperand.value.type === 'list') {
  752. const names = namesOperand.value.value.filter((v) => v.type === 'string').map((v) => v.value);
  753. if (names.length > 0) {
  754. const traitType = `AllTypesMatch<[${names.map((n) => `'${n}'`).join(', ')}]>`;
  755. if (traits.every((t) => t.type !== traitType)) {
  756. traits.push({ type: traitType });
  757. }
  758. }
  759. }
  760. }
  761. // Extract TypesMatchWith traits as string - parsed on demand in getOperation
  762. if (traitDag === 'TypesMatchWith' && trait.value && trait.value.operands) {
  763. const operands = trait.value.operands;
  764. if (operands.length >= 4) {
  765. const getStringValue = (op) => op?.value?.value || op?.value;
  766. const from = getStringValue(operands[1]);
  767. const to = getStringValue(operands[2]);
  768. const transformer = getStringValue(operands[3]);
  769. if (from && to && transformer) {
  770. const traitType = `TypesMatchWith<'${from}', '${to}', '${transformer}'>`;
  771. if (traits.every((t) => t.type !== traitType)) {
  772. traits.push({ type: traitType });
  773. }
  774. }
  775. }
  776. }
  777. // Handle classes that inherit from TypesMatchWith (e.g., PointeeTypeMatchTrait)
  778. if (traitDag && traitDag !== 'TypesMatchWith' && trait.value && trait.value.operands) {
  779. const traitClass = parser.getClass(traitDag);
  780. if (traitClass) {
  781. // Check if this class inherits from TypesMatchWith
  782. for (const classParent of traitClass.parents || []) {
  783. if (classParent.name === 'TypesMatchWith' && classParent.args && classParent.args.length >= 4) {
  784. // Build template bindings from trait operands to class template args
  785. const bindings = new Map();
  786. for (let i = 0; i < traitClass.templateArgs.length && i < trait.value.operands.length; i++) {
  787. const paramName = traitClass.templateArgs[i].name;
  788. const argValue = trait.value.operands[i];
  789. if (argValue && argValue.value) {
  790. bindings.set(paramName, argValue.value.type === 'string' ? argValue.value.value : argValue.value);
  791. }
  792. }
  793. // Extract from, to, transformer from TypesMatchWith parent args (indices 1, 2, 3)
  794. const resolveArg = (arg) => {
  795. if (!arg) {
  796. return null;
  797. }
  798. if (arg.type === 'string' || arg.type === 'code') {
  799. return arg.value;
  800. }
  801. if (arg.type === 'def' && typeof arg.value === 'string') {
  802. // Check if it's a template parameter reference
  803. return bindings.has(arg.value) ? bindings.get(arg.value) : arg.value;
  804. }
  805. return null;
  806. };
  807. const from = resolveArg(classParent.args[1]);
  808. const to = resolveArg(classParent.args[2]);
  809. const transformer = resolveArg(classParent.args[3]);
  810. if (from && to && transformer) {
  811. const traitType = `TypesMatchWith<'${from}', '${to}', '${transformer}'>`;
  812. if (traits.every((t) => t.type !== traitType)) {
  813. traits.push({ type: traitType });
  814. }
  815. }
  816. }
  817. }
  818. }
  819. }
  820. if ((traitName === 'AttrSizedOperandSegments' || traitDag === 'AttrSizedOperandSegments') && traits.every((t) => t.type !== 'AttrSizedOperandSegments')) {
  821. traits.push({ type: 'AttrSizedOperandSegments' });
  822. }
  823. if ((traitName === 'SameOperandsAndResultType' || traitDag === 'SameOperandsAndResultType') && traits.every((t) => t.type !== 'SameOperandsAndResultType')) {
  824. traits.push({ type: 'SameOperandsAndResultType' });
  825. }
  826. if (traitName === 'TensorRTInferTensorResultTypes' && traits.every((t) => t.type !== 'SameOperandsAndResultType')) {
  827. traits.push({ type: 'SameOperandsAndResultType' });
  828. }
  829. if (traitName === 'IsolatedFromAbove' && traits.every((trait) => trait.type !== 'IsolatedFromAbove')) {
  830. traits.push({ type: 'IsolatedFromAbove' });
  831. }
  832. if ((traitName === 'FirstAttrDerivedResultType' || traitDag === 'FirstAttrDerivedResultType') && traits.every((t) => t.type !== 'FirstAttrDerivedResultType')) {
  833. traits.push({ type: 'FirstAttrDerivedResultType' });
  834. }
  835. if ((traitName === 'InferTypeOpInterface' || traitName === 'InferTypeOpAdaptor') &&
  836. traits.every((trait) => trait.type !== 'InferTypeOpInterface')) {
  837. traits.push({ type: 'InferTypeOpInterface' });
  838. }
  839. if (traitName === 'OpAsmOpInterface' || traitDag === 'DeclareOpInterfaceMethods') {
  840. if (traitDag === 'DeclareOpInterfaceMethods' && trait.value && trait.value.operands) {
  841. if (trait.value.operands.some((operand) => operand.value && operand.value.type === 'list' && operand.value.value.some((method) => method.type === 'string' && method.value === 'getDefaultDialect'))) {
  842. const [dialectName] = operationName.split('.');
  843. operation.defaultDialect = dialectName;
  844. }
  845. }
  846. if (!operation.defaultDialect) {
  847. const extraClass = def.getValueAsString('extraClassDeclaration');
  848. if (extraClass) {
  849. const match = extraClass.match(/getDefaultDialect\(\)\s*\{\s*return\s+"(\w+)"/);
  850. if (match) {
  851. [, operation.defaultDialect] = match;
  852. }
  853. }
  854. }
  855. }
  856. }
  857. }
  858. };
  859. // Recursively extract traits from parent classes
  860. const extractTraitsFromParents = (parents, visited = new Set()) => {
  861. for (const parent of parents) {
  862. if (visited.has(parent.name)) {
  863. continue;
  864. }
  865. visited.add(parent.name);
  866. // Extract traits from parent args (check all args as traits can be at different positions)
  867. if (parent.args) {
  868. for (const traitsArg of parent.args) {
  869. extractTraitsFromList(traitsArg);
  870. }
  871. }
  872. // Recursively look at parent class definition
  873. const parentClass = parser.getClass(parent.name);
  874. if (parentClass && parentClass.parents) {
  875. // Also extract traits from the parent class's own parent args
  876. // This handles cases like Linalg_RelayoutOp which defines TypesMatchWith
  877. // in its own inheritance from Op, not in args passed by children
  878. for (const classParent of parentClass.parents) {
  879. // Look for Op parent which typically has traits in args[2]
  880. if (classParent.name === 'Op' && classParent.args && classParent.args.length >= 3) {
  881. extractTraitsFromList(classParent.args[2]);
  882. }
  883. // Also check args that might contain traits (e.g., listconcat results)
  884. if (classParent.args) {
  885. for (const arg of classParent.args) {
  886. extractTraitsFromList(arg);
  887. }
  888. }
  889. }
  890. extractTraitsFromParents(parentClass.parents, visited);
  891. }
  892. }
  893. };
  894. extractTraitsFromParents(def.parents);
  895. if (traits.length > 0) {
  896. operation.traits = traits;
  897. }
  898. if (def.getValue('assemblyFormat')) {
  899. const assemblyFormat = def.getValueAsString('assemblyFormat');
  900. if (assemblyFormat) {
  901. operation.assemblyFormat = assemblyFormat.trim();
  902. }
  903. }
  904. if (def.getValue('hasCustomAssemblyFormat') && def.getValueAsBit('hasCustomAssemblyFormat')) {
  905. operation.hasCustomAssemblyFormat = true;
  906. }
  907. if (def.getValue('parser')) {
  908. operation.parser = def.getValueAsString('parser');
  909. }
  910. if (Object.keys(operation).length > 1) {
  911. operations.set(operationName, operation);
  912. count++;
  913. }
  914. }
  915. const sorted = Array.from(operations.values()).sort((a, b) => a.name.localeCompare(b.name));
  916. const output = JSON.stringify(sorted, null, 2);
  917. let formatted = output.replace(/\{\s+"name":\s+"([^"]+)",\s+"type":\s+"((?:[^"\\]|\\.)*)"\s+\}/g, '{ "name": "$1", "type": "$2" }');
  918. formatted = formatted.replace(/\{\s+"type":\s+"((?:[^"\\]|\\.)*)"\s+\}/g, '{ "type": "$1" }');
  919. await fs.writeFile(file, formatted, 'utf-8');
  920. if (count < 6300) {
  921. throw new Error(`Unexpected operation count '${count}'.`);
  922. }
  923. };
  924. const test = async (pattern) => {
  925. pattern = pattern || './**/*.mlir';
  926. const errorTotals = new Map();
  927. let currentFile = null;
  928. const fileErrors = new Map(); // file -> [error lines]
  929. const allFiles = new Set();
  930. await new Promise((resolve, reject) => {
  931. const cmd = 'node';
  932. const args = ['--max-old-space-size=8192', './test/models.js', 'continue', pattern];
  933. const proc = child_process.spawn(cmd, args, { stdio: ['ignore', 'pipe', 'pipe'] });
  934. const stdout = readline.createInterface({ input: proc.stdout, crlfDelay: Infinity });
  935. const stderr = readline.createInterface({ input: proc.stderr, crlfDelay: Infinity });
  936. const processLine = (line) => {
  937. writeLine(line);
  938. const stripped = line.trim();
  939. if (!stripped) {
  940. return;
  941. }
  942. if (stripped.startsWith('third_party/')) {
  943. currentFile = stripped;
  944. allFiles.add(currentFile);
  945. return;
  946. }
  947. if (currentFile) {
  948. if (/^\s*\d+\s*\/\s*\d+\s*=\s*[\d.]+%\s*$/.test(stripped)) {
  949. return;
  950. }
  951. if (!fileErrors.has(currentFile)) {
  952. fileErrors.set(currentFile, []);
  953. }
  954. fileErrors.get(currentFile).push(stripped);
  955. }
  956. };
  957. stdout.on('line', processLine);
  958. stderr.on('line', processLine);
  959. proc.on('error', (error) => reject(new Error(`Failed to start process: ${error.message}`)));
  960. proc.on('close', resolve);
  961. });
  962. const validFiles = new Set();
  963. const invalidFiles = new Set([
  964. 'third_party/source/mlir/ensemble-compilation/tests/benchmarks/quantum_volume.mlir',
  965. 'third_party/source/mlir/ensemble-compilation/tests/ensemble_gate_distribution.mlir',
  966. 'third_party/source/mlir/iree/compiler/src/iree/compiler/Codegen/Dialect/Codegen/IR/test/lowering_config_attr.mlir',
  967. 'third_party/source/mlir/iree/samples/compiler_plugins/simple_io_sample/test/print.mlir',
  968. 'third_party/source/mlir/lltz/mlir/dialect/irdl/michelson.irdl.mlir',
  969. 'third_party/source/mlir/llvm-project/mlir/test/Dialect/Builtin/ops.mlir',
  970. 'third_party/source/mlir/llvm-project/mlir/test/Dialect/IRDL/regions-ops.irdl.mlir',
  971. 'third_party/source/mlir/llvm-project/mlir/test/Dialect/IRDL/testd.irdl.mlir',
  972. 'third_party/source/mlir/llvm-project/mlir/test/Dialect/IRDL/variadics.irdl.mlir',
  973. 'third_party/source/mlir/llvm-project/mlir/test/Dialect/Linalg/tile-to-forall.mlir',
  974. 'third_party/source/mlir/llvm-project/mlir/test/Dialect/LLVMIR/func.mlir',
  975. 'third_party/source/mlir/llvm-project/mlir/test/Dialect/LLVMIR/global.mlir',
  976. 'third_party/source/mlir/llvm-project/mlir/test/Dialect/MemRef/high-rank-overflow.mlir',
  977. 'third_party/source/mlir/llvm-project/mlir/test/Dialect/Quant/parse-uniform-invalid.mlir',
  978. 'third_party/source/mlir/llvm-project/mlir/test/Dialect/SMT/bitvector-errors.mlir',
  979. 'third_party/source/mlir/llvm-project/mlir/test/Dialect/SPIRV/IR/barrier-ops.mlir',
  980. 'third_party/source/mlir/llvm-project/mlir/test/Dialect/SPIRV/IR/composite-ops.mlir',
  981. 'third_party/source/mlir/llvm-project/mlir/test/Dialect/SPIRV/IR/control-flow-ops.mlir',
  982. 'third_party/source/mlir/llvm-project/mlir/test/Dialect/SPIRV/IR/gl-ops.mlir',
  983. 'third_party/source/mlir/llvm-project/mlir/test/Dialect/SPIRV/IR/khr-cooperative-matrix-ops.mlir',
  984. 'third_party/source/mlir/llvm-project/mlir/test/Dialect/SPIRV/IR/logical-ops.mlir',
  985. 'third_party/source/mlir/llvm-project/mlir/test/Dialect/SPIRV/IR/memory-ops.mlir',
  986. 'third_party/source/mlir/llvm-project/mlir/test/Dialect/SPIRV/IR/misc-ops.mlir',
  987. 'third_party/source/mlir/llvm-project/mlir/test/Dialect/SPIRV/IR/ocl-ops.mlir',
  988. 'third_party/source/mlir/llvm-project/mlir/test/Dialect/SPIRV/IR/structure-ops.mlir',
  989. 'third_party/source/mlir/llvm-project/mlir/test/Dialect/SPIRV/IR/types.mlir',
  990. 'third_party/source/mlir/llvm-project/mlir/test/Dialect/Tosa/level_check.mlir',
  991. 'third_party/source/mlir/llvm-project/mlir/test/Dialect/Tosa/verifier.mlir',
  992. 'third_party/source/mlir/llvm-project/mlir/test/Dialect/Transform/test-pass-application.mlir',
  993. 'third_party/source/mlir/llvm-project/mlir/test/Examples/transform-opt/syntax-error.mlir',
  994. 'third_party/source/mlir/llvm-project/mlir/test/IR/attribute.mlir',
  995. 'third_party/source/mlir/llvm-project/mlir/test/IR/dynamic.mlir',
  996. 'third_party/source/mlir/llvm-project/mlir/test/IR/invalid-unregistered.mlir',
  997. 'third_party/source/mlir/llvm-project/mlir/test/IR/parser.mlir',
  998. 'third_party/source/mlir/llvm-project/mlir/test/IR/parser-string-literal-comment.mlir',
  999. 'third_party/source/mlir/llvm-project/mlir/test/IR/zero_whitespace.mlir',
  1000. 'third_party/source/mlir/llvm-project/mlir/test/mlir-tblgen/attr-or-type-format.mlir',
  1001. 'third_party/source/mlir/mlir-dace/design/mlir/map.mlir',
  1002. 'third_party/source/mlir/mlir-dace/design/mlir/simple_sdfg.mlir',
  1003. 'third_party/source/mlir/mlir-dace/design/mlir/symbol.mlir',
  1004. 'third_party/source/mlir/mlir-dace/test/SDFG/Converter/toSDFG/llvm/load.mlir',
  1005. 'third_party/source/mlir/mlir-dace/test/SDFG/Converter/toSDFG/llvm/store.mlir',
  1006. 'third_party/source/mlir/mlir-dace/test/SDFG/Dialect/consume/too_many_params.mlir',
  1007. 'third_party/source/mlir/mlir-dace/test/SDFG/Dialect/memlet/explicit_tile.mlir',
  1008. 'third_party/source/mlir/mlir-dace/test/SDFG/Dialect/state/missing_identifier.mlir',
  1009. 'third_party/source/mlir/mlir-dace/test/SDFG/Dialect/state/missing_region.mlir',
  1010. 'third_party/source/mlir/mlir-dace/test/SDFG/Dialect/tasklet/missing_return_type.mlir',
  1011. 'third_party/source/mlir/runtime/mlir_tests/bef_executor/tutorial.mlir',
  1012. 'third_party/source/mlir/runtime/mlir_tests/core_runtime/basic_ops.mlir',
  1013. 'third_party/source/mlir/shardy/shardy/dialect/mpmd/ir/test/memory_kind_parse_and_print.mlir',
  1014. 'third_party/source/mlir/stablehlo/stablehlo/tests/ops_stablehlo.mlir',
  1015. 'third_party/source/mlir/stablehlo/stablehlo/tests/print_types_invalid.mlir',
  1016. 'third_party/source/mlir/stablehlo/stablehlo/tests/vhlo/invalid_vhlo_future.mlir',
  1017. 'third_party/source/mlir/tensorflow/tensorflow/compiler/mlir/quantization/tensorflow/passes/quantized_function_library_tf_drq.mlir',
  1018. 'third_party/source/mlir/tensorflow/tensorflow/compiler/mlir/quantization/tensorflow/passes/quantized_function_library_uniform_quantized.mlir',
  1019. 'third_party/source/mlir/tensorflow/tensorflow/compiler/mlir/quantization/tensorflow/passes/quantized_function_library_xla_weight_only.mlir',
  1020. 'third_party/source/mlir/tensorflow/tensorflow/compiler/mlir/quantization/tensorflow/passes/quantized_function_library.mlir',
  1021. 'third_party/source/mlir/tensorflow/tensorflow/compiler/mlir/tensorflow/tests/compile_mlir_util/serialized-mlir-module-str-attr.mlir',
  1022. 'third_party/source/mlir/tensorflow/tensorflow/compiler/mlir/tensorflow/tests/tf_executor_ops_invalid.mlir',
  1023. 'third_party/source/mlir/tensorflow/tensorflow/compiler/mlir/tfr/tests/ops.mlir',
  1024. 'third_party/source/mlir/xla/xla/hlo/translate/hlo_to_mhlo/tests/import_bounded_dynamism_stablehlo.mlir',
  1025. 'third_party/source/mlir/xla/xla/mlir_hlo/tests/Dialect/mhlo/ops.mlir',
  1026. 'third_party/source/mlir/xla/xla/mlir_hlo/tests/Dialect/mhlo/verifier_reduce_op.mlir',
  1027. 'third_party/source/tensorflow/tensorflow/compiler/mlir/quantization/tensorflow/passes/quantized_function_library_tf_drq.mlir',
  1028. 'third_party/source/tensorflow/tensorflow/compiler/mlir/quantization/tensorflow/passes/quantized_function_library_uniform_quantized.mlir',
  1029. 'third_party/source/tensorflow/tensorflow/compiler/mlir/quantization/tensorflow/passes/quantized_function_library_xla_weight_only.mlir',
  1030. 'third_party/source/tensorflow/tensorflow/compiler/mlir/quantization/tensorflow/passes/quantized_function_library.mlir',
  1031. 'third_party/source/tensorflow/tensorflow/compiler/mlir/tensorflow/tests/compile_mlir_util/serialized-mlir-module-str-attr.mlir',
  1032. 'third_party/source/tensorflow/tensorflow/compiler/mlir/tensorflow/tests/tf_executor_ops_invalid.mlir',
  1033. 'third_party/source/tensorflow/tensorflow/compiler/mlir/tfr/tests/ops.mlir',
  1034. 'third_party/source/tensorflow/third_party/xla/xla/hlo/translate/hlo_to_mhlo/tests/import_bounded_dynamism_stablehlo.mlir',
  1035. 'third_party/source/tensorflow/third_party/xla/xla/mlir_hlo/tests/Dialect/mhlo/ops.mlir',
  1036. 'third_party/source/tensorflow/third_party/xla/xla/mlir_hlo/tests/Dialect/mhlo/verifier_reduce_op.mlir',
  1037. 'third_party/test/mlir/sample.mlir',
  1038. ]);
  1039. const readRunHeader = async (filePath) => {
  1040. const handle = await fs.open(filePath, 'r');
  1041. const buffer = new Uint8Array(256);
  1042. await handle.read(buffer, 0, 256, 0);
  1043. await handle.close();
  1044. const content = new TextDecoder().decode(buffer).split('\n')[0];
  1045. return content.startsWith('// RUN:') ? content : null;
  1046. };
  1047. for (const file of allFiles) {
  1048. if (file.toLowerCase().includes('invalid')) {
  1049. invalidFiles.add(file);
  1050. } else if (file.startsWith('third_party/source/mlir/mlir-dace/design')) {
  1051. invalidFiles.add(file);
  1052. } else {
  1053. // eslint-disable-next-line no-await-in-loop
  1054. const run = await readRunHeader(file);
  1055. if (run?.includes('mlir-translate --import-wasm')) {
  1056. invalidFiles.add(file);
  1057. } else {
  1058. validFiles.add(file);
  1059. }
  1060. }
  1061. }
  1062. const filesByError = new Map();
  1063. const fileErrorDetails = new Map();
  1064. for (const [file, errors] of fileErrors) {
  1065. if (invalidFiles.has(file)) {
  1066. continue;
  1067. }
  1068. for (const error of errors) {
  1069. const key = error.split(' at ', 1)[0].trim().replace(/\.$/, '').trim();
  1070. if (key) {
  1071. errorTotals.set(key, (errorTotals.get(key) || 0) + 1);
  1072. if (!filesByError.has(key)) {
  1073. filesByError.set(key, new Map());
  1074. }
  1075. filesByError.get(key).set(file, (filesByError.get(key).get(file) || 0) + 1);
  1076. if (!fileErrorDetails.has(key)) {
  1077. fileErrorDetails.set(key, new Map());
  1078. }
  1079. if (!fileErrorDetails.get(key).has(file)) {
  1080. fileErrorDetails.get(key).set(file, []);
  1081. }
  1082. fileErrorDetails.get(key).get(file).push(error);
  1083. }
  1084. }
  1085. }
  1086. const totalValid = validFiles.size;
  1087. const filesWithErrors = new Set();
  1088. for (const [, fileCounts] of filesByError) {
  1089. for (const file of fileCounts.keys()) {
  1090. filesWithErrors.add(file);
  1091. }
  1092. }
  1093. writeLine('');
  1094. writeLine('-'.repeat(75));
  1095. if (errorTotals.size > 0) {
  1096. const sortedErrors = Array.from(errorTotals.entries()).sort((a, b) => b[1] - a[1]).slice(0, 100);
  1097. for (const [err, cnt] of sortedErrors) {
  1098. const fileCounts = filesByError.get(err);
  1099. const topFiles = Array.from(fileCounts.entries()).sort((a, b) => b[1] - a[1]).slice(0, 100);
  1100. writeLine(`${cnt} | ${err}`);
  1101. for (const [file,] of topFiles) {
  1102. writeLine(` ${file}`);
  1103. const details = fileErrorDetails.get(err).get(file);
  1104. for (const specificError of details) {
  1105. writeLine(` ${specificError}`);
  1106. }
  1107. }
  1108. writeLine('');
  1109. }
  1110. }
  1111. if (totalValid > 0) {
  1112. const succeeded = totalValid - filesWithErrors.size;
  1113. const percentage = (succeeded * 100.0) / totalValid;
  1114. writeLine(` ${succeeded} / ${totalValid} = ${percentage.toPrecision(6)}% - skipped ${invalidFiles.size} files`);
  1115. } else {
  1116. writeLine(' No valid files processed');
  1117. }
  1118. writeLine('');
  1119. };
  1120. const main = async () => {
  1121. const command = process.argv.length >= 3 ? process.argv[2] : 'schema';
  1122. switch (command) {
  1123. case 'test': {
  1124. writeLine(process.argv);
  1125. await test(process.argv.slice(3).join(' '));
  1126. break;
  1127. }
  1128. case 'schema':
  1129. default: {
  1130. await schema();
  1131. break;
  1132. }
  1133. }
  1134. };
  1135. await main();