mohitmishra786/low-level-dev-skills

mlir

MLIR skill for multi-level intermediate representation.

Ver código fuente

Cómo usar

  1. Copia el comando y revisa el paquete antes de instalarlo en tu entorno de agente.
  2. Consulta las herramientas, credenciales y entornos necesarios en el documento original.
  3. Describe las entradas y el resultado deseado; contrasta la salida con las fuentes.
npx skills add https://github.com/mohitmishra786/low-level-dev-skills --skill mlir

Antes de empezar

  • La instalación no incluye suscripción al modelo, cuota API ni permisos sobre tus archivos.
  • Las estrellas e instalaciones reflejan actividad, no una prueba independiente de calidad o seguridad.
Documento original del Skill

Contenido del repositorio de origen con títulos, ejemplos, código, tablas, enlaces e imágenes preservados.

MLIR

Purpose

Guide agents through MLIR (Multi-Level IR): ops, regions, blocks, and values; built-in dialects (arith, func, memref, affine, linalg); writing custom dialects with ODS; lowering passes with ConversionPattern; mlir-opt CLI; and ML compiler use cases (Torch-MLIR, IREE).

When to Use

  • Building a domain-specific compiler IR (graphics, ML, hardware DSL)
  • Lowering high-level ops to LLVM or GPU dialects
  • Writing progressive lowering pipelines (linalg → loops → LLVM)
  • Integrating with IREE or Torch-MLIR for ML deployment
  • Creating reusable transformation passes across dialects
  • Prototyping compiler optimizations at the right abstraction level

Workflow

1. MLIR structure

Module
└── func.func @main()
    └── region
        └── block ^bb0:
            └── operations (ops) producing SSA values

Key concepts:

  • Operation — instruction-like node (arith.addi, memref.load)
  • Region — container of blocks (functions, control flow)
  • Block — CFG node with ordered ops
  • Value — SSA result of an op or block argument

2. Built-in dialects

DialectPurpose
arithInteger/float arithmetic
funcFunction definitions and calls
memrefBuffer abstraction with shapes/strides
affineAffine loop nests, map/set constraints
linalgStructured linear algebra ops
scfStructured control flow (for, if)
llvmLLVM IR dialect for final lowering
gpuGPU kernel launches
mlir
// example.mlir
func.func @add(%a: memref<4xf32>, %b: memref<4xf32>, %c: memref<4xf32>) {
  %c0 = arith.constant 0 : index
  %c4 = arith.constant 4 : index
  scf.for %i = %c0 to %c4 step %c1 {
    %av = memref.load %a[%i] : memref<4xf32>
    %bv = memref.load %b[%i] : memref<4xf32>
    %sum = arith.addf %av, %bv : f32
    memref.store %sum, %c[%i] : memref<4xf32>
  }
  return
}

3. mlir-opt CLI

bash
# Parse and print
mlir-opt example.mlir

# Run canonicalization
mlir-opt example.mlir -canonicalize

# Lower affine to scf
mlir-opt affine.mlir -lower-affine

# Full pipeline toward LLVM
mlir-opt input.mlir \
  --linalg-bufferize \
  --convert-linalg-to-loops \
  --convert-scf-to-cf \
  --convert-arith-to-llvm \
  --convert-memref-to-llvm \
  --convert-func-to-llvm \
  -o llvm.mlir

4. ODS — Operation Definition Specification

tablegen
// MyOps.td
include "mlir/IR/OpBase.td"

def My_Dialect : Dialect {
    let name = "my";
    let summary = "My custom dialect";
}

class My_Op<string mnemonic, list<Trait> traits = []> :
    Op<My_Dialect, mnemonic, traits>;

def AddOp : My_Op<"add", [Pure]> {
    let summary = "Add two values";
    let arguments = (ins AnyType:$lhs, AnyType:$rhs);
    let results = (outs AnyType:$result);
    let assemblyFormat = "$lhs `,` $rhs attr-dict `:` type($result)";
}
bash
# Generate C++ from TableGen
mlir-tblgen -gen-op-defs MyOps.td -I include/ -o MyOps.cpp.inc

5. Custom dialect C++ implementation

cpp
#include "mlir/IR/DialectImplementation.h"
#include "MyDialect.h"

#include "MyOps.cpp.inc"

void MyDialect::initialize() {
    addOperations<
#define GET_OP_LIST
#include "MyOps.cpp.inc"
    >();
}

#define GET_OP_CLASSES
#include "MyOps.cpp.inc"

6. Lowering passes

cpp
#include "mlir/Conversion/LLVMCommon/ConversionTarget.h"
#include "mlir/Transforms/DialectConversion.h"

struct AddOpLowering : OpConversionPattern<my::AddOp> {
    using OpConversionPattern::OpConversionPattern;

    LogicalResult matchAndRewrite(my::AddOp op, OpAdaptor adaptor,
                                  ConversionPatternRewriter &rewriter) const override {
        rewriter.replaceOpWithNewOp<arith::AddIOp>(op, adaptor.getLhs(), adaptor.getRhs());
        return success();
    }
};

void populateLoweringPatterns(RewritePatternSet &patterns) {
    patterns.add<AddOpLowering>(patterns.getContext());
}

// In pass:
mlir::ConversionTarget target(*context);
target.addIllegalDialect<my::MyDialect>();
target.addLegalDialect<arith::ArithDialect>();

if (failed(applyPartialConversion(module, target, std::move(patterns))))
    signalPassFailure();

7. linalg for ML compilers

mlir
%0 = linalg.matmul ins(%A, %B : tensor<128x256xf32>, tensor<256x64xf32>)
                   outs(%C : tensor<128x64xf32>) -> tensor<128x64xf32>

Lowering path: linalg → scf loops → affine → llvm

8. Torch-MLIR and IREE

bash
# Torch-MLIR: PyTorch → MLIR
python -m torch_mlir.tools.import-onnx --onnx-model model.onnx -o model.mlir

# IREE: MLIR → GPU/CPU executable
iree-compile --iree-hal-target-backends=llvm-cpu model.mlir -o model.vmfb
iree-run-module --module=model.vmfb --function=main

Common Problems

SymptomCauseFix
Dialect not registeredMissing registerDialectRegister in tool/pass init
ODS build failureTableGen include pathCheck -I for mlir/IR/OpBase.td
Lowering incompleteIllegal ops remainDebug with --mlir-print-ir-after-failure
Type mismatch in patternWrong adaptor typesUse OpAdaptor typed accessors
mlir-opt crashInvalid IRRun -verify-each
Empty function after loweringAll ops illegal, none convertedAdd missing patterns

Related Skills

  • skills/compiler-internals/llvm-passes — LLVM pass equivalents
  • skills/compiler-internals/compiler-frontend — AST to MLIR import
  • skills/compiler-internals/jit-compilation — JIT compiled MLIR→LLVM
  • skills/compilers/llvm — LLVM IR output target
  • skills/gpu/cuda — GPU dialect lowering targets
  • skills/gpu/triton-lang — alternative GPU kernel IR

Relacionados por tarea

del mismo repositorio

Más Skills

Todos los Skills
mohitmishra786
Comunidad

low-power-embedded

Low-power embedded skill for sleep modes and energy optimization. Use when configuring MCU sleep/stop/standby, peripheral clock gating, wake-up sources, or measuring firmware current draw. Activates on queries about WFI, STOP mode, STM32 PWR, nRF sleep, wake-up EXTI, or reducing embedded power consumption.

Instalaciones / 1h
1
GitHub Stars
296
Actualizado
20 nov
mohitmishra786
Comunidad

core-dumps

Core dump analysis skill for production crash triage. Use when loading core files in GDB or LLDB, enabling core dump generation on Linux/macOS, mapping symbols with debuginfo or debuginfod, or extracting backtraces from crashes without re-running the program. Activates on queries about core files, ulimit, coredumpctl, debuginfod, crash triage, or analyzing segfaults from production binaries.

Instalaciones / 1h
2
GitHub Stars
267
Actualizado
27 jun
mohitmishra786
Comunidad

custom-allocators

Custom allocator skill for memory allocation strategies. Use when implementing pool/slab/arena allocators, tuning jemalloc/mimalloc, writing Rust GlobalAlloc, or benchmarking allocator performance. Activates on queries about jemalloc, mimalloc, tcmalloc, arena allocator, GlobalAlloc, or fragmentation.

Instalaciones / 1h
2
GitHub Stars
267
Actualizado
27 jun
mohitmishra786
Comunidad

ebpf

eBPF skill for Linux observability and networking. Use when writing eBPF programs with libbpf or bpftrace, attaching kprobes/tracepoints/XDP hooks, debugging verifier errors, working with eBPF maps, or achieving CO-RE portability across kernel versions. Activates on queries about eBPF, bpftool, bpftrace, XDP programs, libbpf, verifier errors, eBPF maps, or kernel tracing with BPF.

Instalaciones / 1h
2
GitHub Stars
267
Actualizado
27 jun