### Rust Quick Start Example Source: https://github.com/mlir-rs/melior/blob/main/_autodocs/README.md This example demonstrates how to create a context, module, parse MLIR text, verify, apply passes, and execute a compiled function using Melior. ```rust use melior::{Context, ExecutionEngine, dialect::arith, dialect::func}; use melior::ir::*; use melior::pass::PassManager; fn main() -> Result<(), Box> { // Create context let context = Context::new(); context.load_all_available_dialects(); let location = Location::unknown(&context); // Create module let module = Module::new(location); // Parse MLIR text for simplicity let module = Module::parse(&context, r#"" module { func.func @add(%arg0: i32, %arg1: i32) -> i32 { %result = arith.addi %arg0, %arg1 : i32 func.return %result : i32 } } "#).unwrap(); // Verify assert!(module.as_operation().verify()); // Apply passes let pass_manager = PassManager::new(&context); pass_manager.add_pass(melior::pass::conversion::create_to_llvm()); pass_manager.run(&mut module.clone())?; // Execute let engine = ExecutionEngine::new(&module, 2, &[], false, false); // Invoke function let mut arg1 = 10; let mut arg2 = 20; let mut result = -1; unsafe { engine.invoke_packed("add", &mut [ &mut arg1 as *mut i32 as *mut (), &mut arg2 as *mut i32 as *mut (), &mut result as *mut i32 as *mut (), ])?; } println!("Result: {}", result); // Prints: Result: 30 Ok(()) } ``` -------------------------------- ### Rust Example Test Case Source: https://github.com/mlir-rs/melior/blob/main/_autodocs/api-reference/utilities.md An example of how to use the test utilities to create a context for testing operations. ```rust #[test] fn test_operation() { use melior::test::create_test_context; let context = create_test_context(); // ... test code } ``` -------------------------------- ### Setup PassManager Source: https://github.com/mlir-rs/melior/blob/main/_autodocs/configuration.md Create a new PassManager instance associated with a context. Add passes to the pipeline and then run them on a module. ```rust let pass_manager = PassManager::new(&context); pass_manager.add_pass(pass::conversion::create_to_llvm()); pass_manager.run(&mut module)?; ``` -------------------------------- ### Setup ExecutionEngine Source: https://github.com/mlir-rs/melior/blob/main/_autodocs/configuration.md Create an ExecutionEngine for compiling and running MLIR modules. Configure optimization level, shared libraries, and object dumping. ```rust let engine = ExecutionEngine::new( &module, 2, // Optimization level &["/usr/local/lib"], // Library paths false, // Don't dump object files false, // Don't use PIC ); ``` -------------------------------- ### Rust Test Utilities Setup Source: https://github.com/mlir-rs/melior/blob/main/_autodocs/api-reference/utilities.md Helper functions for setting up tests with Melior, including creating a test context and loading dialects. ```rust #[cfg(test)] pub mod test { pub fn create_test_context() -> Context { ... } pub fn load_all_dialects(context: &Context) { ... } } ``` -------------------------------- ### Thread Pool Setup Source: https://github.com/mlir-rs/melior/blob/main/_autodocs/configuration.md Configures the context to use a specific thread pool. The thread pool must outlive the context. ```APIDOC ## set_thread_pool ### Description Configures the context to use a specific thread pool. ### Method `unsafe fn set_thread_pool(&self, pool: &ThreadPool)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust let context = Context::new(); let pool = ThreadPool::new(); unsafe { context.set_thread_pool(&pool); } ``` ### Response None ### Safety The thread pool must outlive the context. ``` -------------------------------- ### Module::context Source: https://github.com/mlir-rs/melior/blob/main/_autodocs/api-reference/ir-module.md Gets a reference to the context associated with the module. ```APIDOC ## Module::context ### Description Returns a reference to the module's context. ### Method `pub fn context(&self) -> ContextRef<'c>` ### Parameters #### Path Parameters - **—** (—) - No parameters ### Response #### Success Response - **ContextRef<'c>** - An immutable reference to the module's context. ### Request Example ```rust let ctx = module.context(); ``` ``` -------------------------------- ### DialectRegistry::new() Source: https://github.com/mlir-rs/melior/blob/main/_autodocs/api-reference/dialects.md Creates an empty dialect registry. This is the starting point for managing dialects. ```APIDOC ## `DialectRegistry::new()` ### Description Creates an empty dialect registry. ### Method `new()` ### Parameters No parameters. ### Returns `DialectRegistry` ### Example ```rust let registry = DialectRegistry::new(); ``` ``` -------------------------------- ### Create a new Context with Dialect Registry and Threading Source: https://github.com/mlir-rs/melior/blob/main/_autodocs/api-reference/context.md Initializes a context with a pre-loaded dialect registry and explicit threading configuration. This is useful for setting up specific dialects from the start. ```rust let registry = DialectRegistry::new(); let context = Context::new_with_registry(®istry, true); ``` -------------------------------- ### Install LLVM/MLIR Dependency on macOS Source: https://github.com/mlir-rs/melior/blob/main/README.md Instructions to install LLVM/MLIR version 22 on macOS using Homebrew. This is a prerequisite for using the melior crate. ```sh brew install llvm@22 ``` -------------------------------- ### Create an Empty Dialect Registry Source: https://github.com/mlir-rs/melior/blob/main/_autodocs/api-reference/dialects.md Use `DialectRegistry::new()` to create a new, empty registry. This is the starting point for managing dialects. ```rust let registry = DialectRegistry::new(); ``` -------------------------------- ### Context::new_with_threading() Source: https://github.com/mlir-rs/melior/blob/main/_autodocs/api-reference/context.md Creates a context with explicit multithreading configuration. Allows control over whether multithreading is enabled from the start. ```APIDOC ## Context::new_with_threading() ### Description Creates a context with explicit multithreading configuration. ### Method ```rust pub fn new_with_threading(threading_enabled: bool) -> Self ``` ### Parameters #### Parameters - **threading_enabled** (bool) - Required - Enable or disable multithreading ### Returns `Context` ### Example ```rust let context = Context::new_with_threading(true); ``` ``` -------------------------------- ### Building a Function in Melior Source: https://github.com/mlir-rs/melior/blob/main/_autodocs/INDEX.md Provides a comprehensive example of how to construct a function within an MLIR module using Melior. This includes setting up the context, module, block, and the function operation itself. ```rust use melior::{Context, dialect::func, ir::*}; let context = Context::new(); let location = Location::unknown(&context); // Create module let module = Module::new(location); // Create function body let block = Block::new(&[(Type::index(&context), location)]); // ... add operations to block // Create function let func_op = func::func( &context, StringAttribute::new(&context, "my_func"), TypeAttribute::new(...), { let region = Region::new(); region.append_block(block); region }, &[], location, ); module.body().append_operation(func_op); ``` -------------------------------- ### Applying Passes with PassManager Source: https://github.com/mlir-rs/melior/blob/main/_autodocs/INDEX.md Shows how to apply MLIR passes to a module using Melior's PassManager. This example demonstrates adding a conversion pass to LLVM. ```rust use melior::pass; let pass_manager = pass::PassManager::new(&context); pass_manager.add_pass(pass::conversion::create_to_llvm()); pass_manager.run(&mut module)?; ``` -------------------------------- ### Get or Load a Dialect by Name Source: https://github.com/mlir-rs/melior/blob/main/_autodocs/api-reference/context.md Fetches a dialect by its string name (e.g., "func", "llvm"). If the dialect is not already loaded, it will be loaded into the context. This is the standard way to access specific dialects. ```rust let func_dialect = context.get_or_load_dialect("func"); ``` -------------------------------- ### Load Function Dialect into Context Source: https://github.com/mlir-rs/melior/blob/main/_autodocs/api-reference/dialects.md Use `DialectHandle::func()` to get a handle for the function dialect and then `load_dialect()` to load it into a given `Context`. This makes the function dialect's operations available. ```rust let dialect = DialectHandle::func().load_dialect(&context); ``` -------------------------------- ### Get Dialect Namespace Source: https://github.com/mlir-rs/melior/blob/main/_autodocs/api-reference/dialects.md Obtain the namespace string for a given `Dialect`. This can be used to identify the dialect, for example, checking if it's the LLVM dialect. ```rust assert_eq!(dialect.namespace().unwrap(), "llvm"); ``` -------------------------------- ### Get Module as OperationRef Source: https://github.com/mlir-rs/melior/blob/main/_autodocs/api-reference/ir-module.md Use `Module::as_operation()` to get an immutable reference to the module as an `OperationRef`. This allows treating the module itself as an operation. ```rust let op = module.as_operation(); println!("{}", op); ``` -------------------------------- ### Typical Execution Engine Usage Pattern Source: https://github.com/mlir-rs/melior/blob/main/_autodocs/api-reference/execution-engine.md Demonstrates the standard workflow for using the execution engine: creating a module, applying conversion passes to LLVM, initializing the engine, and invoking a compiled function. Ensure proper unsafe block usage for function invocation. ```rust use melior:: { Context, ExecutionEngine, ir::{Module, Location}, pass::PassManager, dialect::func, }; // 1. Create module with IR let context = Context::new(); let location = Location::unknown(&context); let mut module = Module::new(location); // ... add operations to module // 2. Convert to LLVM let pass_manager = PassManager::new(&context); pass_manager.add_pass(melior::pass::conversion::create_to_llvm()); pass_manager.run(&mut module)?; // 3. Create execution engine let engine = ExecutionEngine::new(&module, 2, &[], false, false); // 4. Invoke function let mut arg = 42; let mut result = -1; unsafe { engine.invoke_packed( "my_function", &mut [ &mut arg as *mut i32 as *mut (), &mut result as *mut i32 as *mut (), ], )?; } ``` -------------------------------- ### Create Location with File, Line, and Column Source: https://github.com/mlir-rs/melior/blob/main/_autodocs/api-reference/ir-blocks-regions.md Creates a location with specific file, line, and column information. Requires a context. ```rust let loc = Location::new(&context, "main.mlir", 42, 10); ``` -------------------------------- ### Get Module as mutable OperationRef Source: https://github.com/mlir-rs/melior/blob/main/_autodocs/api-reference/ir-module.md Use `Module::as_operation_mut()` to get a mutable reference to the module as an `OperationRefMut`. This is useful for modifying the module's structure. ```rust let op_mut = module.as_operation_mut(); ``` -------------------------------- ### Context::new_with_registry() Source: https://github.com/mlir-rs/melior/blob/main/_autodocs/api-reference/context.md Creates a context with a pre-loaded dialect registry and explicit threading configuration. Useful for setting up a context with specific dialects from the beginning. ```APIDOC ## Context::new_with_registry() ### Description Creates a context with a pre-loaded dialect registry and explicit threading configuration. ### Method ```rust pub fn new_with_registry(registry: &DialectRegistry, threading_enabled: bool) -> Self ``` ### Parameters #### Parameters - **registry** (&DialectRegistry) - Required - Dialect registry to load - **threading_enabled** (bool) - Required - Enable or disable multithreading ### Returns `Context` ### Example ```rust let registry = DialectRegistry::new(); let context = Context::new_with_registry(®istry, true); ``` ``` -------------------------------- ### Get Context from a Dialect Source: https://github.com/mlir-rs/melior/blob/main/_autodocs/api-reference/dialects.md Retrieve the `ContextRef` associated with a loaded `Dialect`. This is useful for further operations within that context. ```rust let ctx = dialect.context(); ``` -------------------------------- ### Context::new() Source: https://github.com/mlir-rs/melior/blob/main/_autodocs/api-reference/context.md Creates a new context with default settings. This is the most basic way to initialize a Melior context. ```APIDOC ## Context::new() ### Description Creates a new context with default settings. ### Method ```rust pub fn new() -> Self ``` ### Parameters No parameters. ### Returns `Context` ### Example ```rust use melior::Context; let context = Context::new(); ``` ``` -------------------------------- ### Get Operation Result by Index Source: https://github.com/mlir-rs/melior/blob/main/_autodocs/api-reference/ir-operations.md Retrieves an `OperationResult` from an `OperationRef` at a specified index. This operation can fail if the index is out of bounds. ```rust pub fn result(self, index: usize) -> Result, Error> ``` ```rust let result = op_ref.result(0)?; ``` -------------------------------- ### Get Module's Context Source: https://github.com/mlir-rs/melior/blob/main/_autodocs/api-reference/ir-module.md Use `Module::context()` to retrieve an immutable reference to the `Context` associated with the module. ```rust let ctx = module.context(); ``` -------------------------------- ### Create Execution Engine with Optimization Level Source: https://github.com/mlir-rs/melior/blob/main/_autodocs/configuration.md Instantiate an ExecutionEngine with a specified optimization level. Level 2 is suitable for most cases, while level 3 is for production. ```rust ExecutionEngine::new(&module, 2, &[], false, false) ``` -------------------------------- ### Location::new() Source: https://github.com/mlir-rs/melior/blob/main/_autodocs/api-reference/ir-blocks-regions.md Creates a location with file, line, and column information. ```APIDOC ## Location::new() ### Description Creates a location with file, line, and column information. ### Method `new(context: &'c Context, filename: &str, line: usize, column: usize) -> Self` ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Request Example ```rust let loc = Location::new(&context, "main.mlir", 42, 10); ``` ### Response #### Success Response (200) - `Location<'c>`: The created location with file, line, and column info. ### Response Example ```json // No JSON example provided for this Rust struct creation. ``` ``` -------------------------------- ### JIT Execution of a Function Source: https://github.com/mlir-rs/melior/blob/main/_autodocs/INDEX.md Demonstrates how to execute a compiled MLIR function using Melior's ExecutionEngine. This involves setting up the engine and invoking the function with packed arguments. ```rust let engine = ExecutionEngine::new(&module, 2, &[], false, false); let mut arg = 42; let mut result = -1; unsafe { engine.invoke_packed( "my_function", &mut [ &mut arg as *mut i32 as *mut (), &mut result as *mut i32 as *mut (), ], )?; } ``` -------------------------------- ### Get Diagnostic Severity Level Source: https://github.com/mlir-rs/melior/blob/main/_autodocs/api-reference/utilities.md Retrieves the severity level of a diagnostic. Supported levels include Error, Warning, Note, and Remark. ```rust pub fn severity(&self) -> Severity ``` -------------------------------- ### Context::load_all_available_dialects() Source: https://github.com/mlir-rs/melior/blob/main/_autodocs/api-reference/context.md Loads all dialects that have been registered with the context. This ensures all potential dialects are ready for use. ```APIDOC ## Context::load_all_available_dialects() ### Description Loads all available dialects into the context. ### Method ```rust pub fn load_all_available_dialects(&self) ``` ### Parameters No parameters. ### Returns `()` ### Example ```rust context.load_all_available_dialects(); ``` ``` -------------------------------- ### OperationPrintingFlags::new() Source: https://github.com/mlir-rs/melior/blob/main/_autodocs/api-reference/ir-operations.md Creates a new instance of `OperationPrintingFlags` with default settings. This is the primary way to initialize the configuration for printing MLIR operations. ```APIDOC ## Function OperationPrintingFlags::new() ### Description Creates default printing flags for configuring operation output. ### Method `new()` ### Returns - `OperationPrintingFlags`: An instance of `OperationPrintingFlags` with default values. ``` -------------------------------- ### Get Operation Result Type Source: https://github.com/mlir-rs/melior/blob/main/_autodocs/api-reference/ir-operations.md Retrieves the type of an operation's result. This is useful for understanding the data type produced by an operation. ```rust let result = op.result(0)?; let result_type = result.r#type(); ``` -------------------------------- ### ExecutionEngine::new() Source: https://github.com/mlir-rs/melior/blob/main/_autodocs/api-reference/execution-engine.md Creates a new ExecutionEngine for a given MLIR module with specified optimization level and shared library paths. ```APIDOC ## ExecutionEngine::new() ### Description Creates an execution engine for a module. ### Method `ExecutionEngine::new()` ### Parameters #### Path Parameters - **module** (*&Module*) - Required - Module to compile - **optimization_level** (*usize*) - Required - Optimization level (0-3) - **shared_library_paths** (*&[&str]*) - Required - Paths to shared libraries to link - **enable_object_dump** (*bool*) - Required - Whether to dump object files - **enable_pic** (*bool*) - Required - Enable position-independent code ### Request Example ```rust let engine = ExecutionEngine::new(&module, 2, &[], false, false); ``` ### Response #### Success Response (ExecutionEngine) - Returns an instance of `ExecutionEngine`. ### Source `melior/src/execution_engine.rs:15` ``` -------------------------------- ### Create an empty Region Source: https://github.com/mlir-rs/melior/blob/main/_autodocs/api-reference/ir-blocks-regions.md Use `Region::new()` to create a new, empty region. This is the simplest way to initialize a region. ```rust let region = Region::new(); ``` -------------------------------- ### BlockArgument Struct Source: https://github.com/mlir-rs/melior/blob/main/_autodocs/types.md The `BlockArgument` struct represents an argument to a block in MLIR. It provides methods to get the argument's type and the block that owns it. ```APIDOC ## BlockArgument Struct ### Description Represents an argument to an MLIR block. ### Methods - `r#type(&self) -> Type` - Get the argument's type. - `owner(&self) -> BlockRef` - Get the block that owns this argument. ``` -------------------------------- ### Module::new Source: https://github.com/mlir-rs/melior/blob/main/_autodocs/api-reference/ir-module.md Creates a new, empty MLIR module associated with a given location. ```APIDOC ## Module::new ### Description Creates an empty module at the given location. ### Method `pub fn new(location: Location) -> Self` ### Parameters #### Path Parameters - **location** (Location) - Required - Location to associate with the module ### Response #### Success Response - **Self** (`Module<'c>`) - The newly created module. ### Request Example ```rust use melior::ir::{Module, Location}; use melior::Context; let context = Context::new(); let location = Location::unknown(&context); let module = Module::new(location); ``` ``` -------------------------------- ### Get Float Type Bit Width Source: https://github.com/mlir-rs/melior/blob/main/_autodocs/api-reference/ir-types.md Use `float_width()` to retrieve the bit width of a float type. This method is only valid for float types. ```rust let f32 = Type::float32(&context); assert_eq!(f32.float_width(), 32); ``` -------------------------------- ### Get Context Thread Count Source: https://github.com/mlir-rs/melior/blob/main/_autodocs/api-reference/context.md Retrieve the number of threads currently configured for the context. This value indicates the level of parallelism the context can utilize. ```rust let num_threads = context.thread_count(); ``` -------------------------------- ### Get Loaded Dialect Count Source: https://github.com/mlir-rs/melior/blob/main/_autodocs/api-reference/context.md Returns the number of dialects that are currently loaded and active in the context. This count reflects dialects that are ready for use. ```rust let count = context.loaded_dialect_count(); ``` -------------------------------- ### pass::conversion::create_to_llvm() Source: https://github.com/mlir-rs/melior/blob/main/_autodocs/api-reference/passes.md Creates a conversion pass that converts dialects to LLVM. This pass takes no parameters and returns a Pass object. ```APIDOC ## pass::conversion::create_to_llvm() ### Description Creates a conversion pass that converts dialects to LLVM. ### Method Rust function call ### Parameters No parameters ### Returns `Pass` ### Example ```rust let to_llvm = pass::conversion::create_to_llvm(); pass_manager.add_pass(to_llvm); ``` ``` -------------------------------- ### Load All Available Dialects Source: https://github.com/mlir-rs/melior/blob/main/_autodocs/api-reference/context.md Instructs the context to load all dialects that are available in the current environment. Use this when you need access to a wide range of dialects without specifying them individually. ```rust context.load_all_available_dialects(); ``` -------------------------------- ### Get Registered Dialect Count Source: https://github.com/mlir-rs/melior/blob/main/_autodocs/api-reference/context.md Retrieves the total number of dialects that have been registered within the context. This count includes dialects that may not have been loaded yet. ```rust let count = context.registered_dialect_count(); ``` -------------------------------- ### Create Melior Context with Dialect Registry and Threading Source: https://github.com/mlir-rs/melior/blob/main/_autodocs/configuration.md Initialize a Melior context with a pre-defined dialect registry and explicit control over multi-threading. ```rust pub fn new_with_registry(registry: &DialectRegistry, threading_enabled: bool) -> Context ``` -------------------------------- ### Access Module's Body Block Source: https://github.com/mlir-rs/melior/blob/main/_autodocs/api-reference/ir-module.md Use `Module::body()` to get a reference to the module's body `BlockRef`. Operations can be appended to this block. ```rust let body = module.body(); body.append_operation(my_operation); ``` -------------------------------- ### Create an empty MLIR Module Source: https://github.com/mlir-rs/melior/blob/main/_autodocs/api-reference/ir-module.md Use `Module::new()` to create an empty module. It requires a `Location` to associate with the module. ```rust use melior::ir::{Module, Location}; use melior::Context; let context = Context::new(); let location = Location::unknown(&context); let module = Module::new(location); ``` -------------------------------- ### Value Structure Source: https://github.com/mlir-rs/melior/blob/main/_autodocs/types.md The `Value` struct represents a value produced by an operation or a block argument. It provides methods to get the value's type and iterate over its uses. ```rust pub struct Value<'c, 'a> { // ... } ``` -------------------------------- ### Create Melior Context with Default Settings Source: https://github.com/mlir-rs/melior/blob/main/_autodocs/configuration.md Use this method to create a new Melior context with default configurations, including multi-threading enabled and no pre-loaded dialects. ```rust pub fn new() -> Context ``` -------------------------------- ### MLIR Value Lifetime Constraints Example Source: https://github.com/mlir-rs/melior/blob/main/_autodocs/api-reference/ir-values.md Illustrates the lifetime constraints of MLIR values in Rust. Values are non-owning references whose lifetimes are tied to their parent operation, block, and context. ```rust fn process_value<'c, 'a>(value: Value<'c, 'a>) -> Value<'c, 'a> { // value cannot be stored outside this function // because 'a is tied to the parent's lifetime value } // This won't compile: // let saved_value = ...; // let parent = block; // parent goes out of scope // use_value(saved_value); // Error: lifetime mismatch ``` -------------------------------- ### Load All Available Dialects Source: https://github.com/mlir-rs/melior/blob/main/_autodocs/configuration.md This command loads all dialects that have been registered with the Melior environment into the current context. ```rust // Load all available dialects context.load_all_available_dialects(); ``` -------------------------------- ### Create a new Melior Context Source: https://github.com/mlir-rs/melior/blob/main/_autodocs/api-reference/context.md Creates a new context with default settings. This is the most basic way to initialize Melior. ```rust use melior::Context; let context = Context::new(); ``` -------------------------------- ### Create Location with Line and Column Range Source: https://github.com/mlir-rs/melior/blob/main/_autodocs/api-reference/ir-blocks-regions.md Creates a location spanning a range of lines and columns within a file. Requires a context. ```rust let range_loc = Location::file_line_col_range(&context, "main.mlir", 1, 0, 10, 20); ``` -------------------------------- ### Create New Operation Builder Source: https://github.com/mlir-rs/melior/blob/main/_autodocs/api-reference/ir-operations.md Use `OperationBuilder::new` to initialize a builder with an operation name and source location. ```rust pub fn new(name: &str, location: Location) -> Self ``` ```rust let builder = OperationBuilder::new("arith.addi", location); ``` -------------------------------- ### Build MLIR Function to Add Integers in Rust Source: https://github.com/mlir-rs/melior/blob/main/README.md Demonstrates how to construct an MLIR module containing a function that adds two integers. Requires setting up the MLIR context, dialects, and IR objects. ```rust use melior:: Context, dialect::{DialectRegistry, arith, func}, ir::{ attribute::{StringAttribute, TypeAttribute}, operation::OperationLike, r#type::FunctionType, *, }, utility::register_all_dialects, ; let registry = DialectRegistry::new(); register_all_dialects(®istry); let context = Context::new(); context.append_dialect_registry(®istry); context.load_all_available_dialects(); let location = Location::unknown(&context); let module = Module::new(location); let index_type = Type::index(&context); module.body().append_operation(func::func( &context, StringAttribute::new(&context, "add"), TypeAttribute::new( FunctionType::new(&context, &[index_type, index_type], &[index_type]).into(), ), { let block = Block::new(&[(index_type, location), (index_type, location)]); let sum = block .append_operation(arith::addi( block.argument(0).unwrap().into(), block.argument(1).unwrap().into(), location, )) .result(0) .unwrap(); block.append_operation(func::r#return(&[sum.into()], location)); let region = Region::new(); region.append_block(block); region }, &[], location, )); assert!(module.as_operation().verify()); ``` -------------------------------- ### Operation Construction with Builder Pattern Source: https://github.com/mlir-rs/melior/blob/main/_autodocs/INDEX.md Illustrates the builder pattern for constructing MLIR operations in Melior. This pattern allows for fluent configuration and validation before building the operation. ```rust OperationBuilder::new("arith.addi", location) .add_operands(&[lhs, rhs]) .enable_result_type_inference() .build()?; ``` -------------------------------- ### Location::call_site() Source: https://github.com/mlir-rs/melior/blob/main/_autodocs/api-reference/ir-blocks-regions.md Creates a call site location. ```APIDOC ## Location::call_site() ### Description Creates a call site location. ### Method `call_site(callee: Location, caller: Location) -> Self` ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Request Example ```rust let callsite = Location::call_site(callee_loc, caller_loc); ``` ### Response #### Success Response (200) - `Location<'c>`: The created call site location. ### Response Example ```json // No JSON example provided for this Rust struct creation. ``` ``` -------------------------------- ### Module::from_raw Source: https://github.com/mlir-rs/melior/blob/main/_autodocs/api-reference/ir-module.md Creates a module from a raw C API object. This is an unsafe operation. ```APIDOC ## Module::from_raw ### Description Creates a module from a raw C API object. ### Safety A raw object must be valid. ### Method `pub unsafe fn from_raw(raw: MlirModule) -> Self` ### Parameters #### Path Parameters - **raw** (MlirModule) - Required - Raw MLIR module ### Response #### Success Response - **Self** (`Module<'c>`) - The module created from the raw object. ### Source `melior/src/ir/module.rs:65` ``` -------------------------------- ### Create MLIR Module with Location Source: https://github.com/mlir-rs/melior/blob/main/_autodocs/configuration.md Create a new MLIR module. Modules can be created with an unknown location or a specific file, line, and column. ```rust let location = Location::unknown(&context); let module = Module::new(location); ``` ```rust let location = Location::new(&context, "main.mlir", 1, 0); let module = Module::new(location); ``` -------------------------------- ### Create Module from Raw C API Object Source: https://github.com/mlir-rs/melior/blob/main/_autodocs/api-reference/ir-module.md Use the unsafe function `Module::from_raw()` to create a `Module` from a raw `MlirModule` C API object. Ensure the provided raw object is valid. ```rust let module = Module::from_raw(raw); ``` -------------------------------- ### Create a New PassManager Source: https://github.com/mlir-rs/melior/blob/main/_autodocs/api-reference/passes.md Instantiate a new PassManager for a given MLIR context. This is the entry point for managing passes. ```rust let pass_manager = PassManager::new(&context); ``` -------------------------------- ### ExecutionEngine::dump_to_object_file() Source: https://github.com/mlir-rs/melior/blob/main/_autodocs/api-reference/execution-engine.md Dumps the compiled module into an object file at the specified path. ```APIDOC ## ExecutionEngine::dump_to_object_file() ### Description Dumps the compiled module as an object file to the given path. ### Method `ExecutionEngine::dump_to_object_file()` ### Parameters #### Path Parameters - **path** (*&str*) - Required - File path to write object file to ### Request Example ```rust engine.dump_to_object_file("/tmp/module.o"); ``` ### Response #### Success Response () - This function does not return a value. ### Source `melior/src/execution_engine.rs:83` ``` -------------------------------- ### Location::file_line_col_range() Source: https://github.com/mlir-rs/melior/blob/main/_autodocs/api-reference/ir-blocks-regions.md Creates a location with a range of lines and columns. ```APIDOC ## Location::file_line_col_range() ### Description Creates a location with a range of lines and columns. ### Method `file_line_col_range(context: &'c Context, filename: &str, start_line: usize, start_col: usize, end_line: usize, end_col: usize) -> Self` ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Request Example ```rust let range_loc = Location::file_line_col_range(&context, "main.mlir", 1, 0, 10, 20); ``` ### Response #### Success Response (200) - `Location<'c>`: The created location with a range of lines and columns. ### Response Example ```json // No JSON example provided for this Rust struct creation. ``` ``` -------------------------------- ### Create Transform Dialect Interpreter Source: https://github.com/mlir-rs/melior/blob/main/_autodocs/api-reference/passes.md Creates a transform dialect interpreter. This function takes no parameters. ```rust pub fn create_interpreter() -> Pass ``` -------------------------------- ### Module::to_raw Source: https://github.com/mlir-rs/melior/blob/main/_autodocs/api-reference/ir-module.md Converts the module into its raw C API object representation. ```APIDOC ## Module::to_raw ### Description Converts the module into a raw C API object. ### Method `pub const fn to_raw(&self) -> MlirModule` ### Parameters #### Path Parameters - **—** (—) - No parameters ### Response #### Success Response - **MlirModule** - The raw C API module object. ### Request Example ```rust let raw = module.to_raw(); ``` ``` -------------------------------- ### Load a Specific Dialect by Name Source: https://github.com/mlir-rs/melior/blob/main/_autodocs/configuration.md This snippet demonstrates how to load a specific dialect, such as the 'func' dialect, by its name from the context. The dialect will be loaded if it's not already available. ```rust // Load a specific dialect by name let dialect = context.get_or_load_dialect("func"); ``` -------------------------------- ### Convert Module to Raw C API Object Source: https://github.com/mlir-rs/melior/blob/main/_autodocs/api-reference/ir-module.md Use `Module::to_raw()` to convert the `Module` into its underlying raw `MlirModule` C API object. ```rust let raw = module.to_raw(); ``` -------------------------------- ### Use Values as Operands in Operations Source: https://github.com/mlir-rs/melior/blob/main/_autodocs/api-reference/ir-values.md Demonstrates how to use existing values (from block arguments) as operands when building new MLIR operations. ```rust use melior::{ Context, ir::{Location, Block, Type}, dialect::arith, }; let context = Context::new(); let location = Location::unknown(&context); let i32_type = Type::parse(&context, "i32").unwrap(); let block = Block::new(&[(i32_type, location), (i32_type, location)]); // Get block arguments as values let arg0 = block.argument(0).unwrap().into(); let arg1 = block.argument(1).unwrap().into(); // Use values in operations let add = block.append_operation(arith::addi(arg0, arg1, location)); let result: Value = add.result(0).unwrap().into(); // Use result in another operation let doubled = block.append_operation(arith::addi(result, result, location)); ``` -------------------------------- ### Create Execution Engine Source: https://github.com/mlir-rs/melior/blob/main/_autodocs/api-reference/execution-engine.md Instantiates an execution engine for a given MLIR module with specified optimization level and library paths. Configure object file dumping and position-independent code generation. ```rust let engine = ExecutionEngine::new(&module, 2, &[], false, false); ``` -------------------------------- ### Integrate MLIR Values with Type System Source: https://github.com/mlir-rs/melior/blob/main/_autodocs/api-reference/ir-values.md Demonstrates how MLIR values interact with Melior's type system. Values correctly report their types, and type matching is enforced by the IR verifier. ```rust let i32_type = IntegerType::new(&context, 32); let arg: Value = block.argument(0).unwrap().into(); // Values know their types assert_eq!(arg.r#type(), i32_type.into()); // Type matching is enforced by the IR verifier assert!(module.as_operation().verify()); ``` -------------------------------- ### PassIrPrintingOptions::new() Source: https://github.com/mlir-rs/melior/blob/main/_autodocs/api-reference/passes.md Creates default printing options for IR printing during passes. This function initializes `PassIrPrintingOptions` with default values. ```APIDOC ## PassIrPrintingOptions::new() ### Description Creates default printing options for IR printing during passes. ### Method `new()` ### Parameters No parameters. ### Returns `PassIrPrintingOptions` ``` -------------------------------- ### Create a new Context with Threading Enabled Source: https://github.com/mlir-rs/melior/blob/main/_autodocs/api-reference/context.md Creates a context and allows explicit configuration of multithreading. Set `threading_enabled` to `true` to enable, or `false` to disable. ```rust let context = Context::new_with_threading(true); ``` -------------------------------- ### Create StringAttribute Source: https://github.com/mlir-rs/melior/blob/main/_autodocs/api-reference/attributes.md Use `StringAttribute::new` to create a string attribute. It requires a context and the string value. ```rust let str_attr = StringAttribute::new(&context, "my_function"); ``` -------------------------------- ### Compare MLIR Values for Equality Source: https://github.com/mlir-rs/melior/blob/main/_autodocs/api-reference/ir-values.md Demonstrates how to compare two MLIR values for equality. Equality is determined by the underlying MLIR value, not its type. ```rust let result1 = op1.result(0).unwrap(); let result2 = op2.result(0).unwrap(); if result1 == result2 { println!("Same value"); } ``` -------------------------------- ### OperationBuilder::new Source: https://github.com/mlir-rs/melior/blob/main/_autodocs/api-reference/ir-operations.md Creates a new operation builder with a specified name and source code location. ```APIDOC ## OperationBuilder::new() ### Description Creates a new operation builder with a name and location. ### Method `OperationBuilder::new(name: &str, location: Location) -> Self` ### Parameters #### Path Parameters - **name** (string) - Required - Operation name (e.g., "arith.addi") - **location** (Location) - Required - Location in source code ### Returns `OperationBuilder` ### Example ```rust let builder = OperationBuilder::new("arith.addi", location); ``` ``` -------------------------------- ### Operation::from_raw() Source: https://github.com/mlir-rs/melior/blob/main/_autodocs/api-reference/ir-operations.md Creates an `Operation` instance from a raw C API object. This method is unsafe and requires a valid raw MLIR operation. ```APIDOC ## Operation::from_raw() ### Description Creates an operation from a raw C API object. This is an unsafe operation that requires the provided raw object to be valid. ### Method `Operation::from_raw(raw: MlirOperation) -> Self` ### Parameters #### Path Parameters - **raw** (MlirOperation) - Required - Raw MLIR operation ### Returns - `Operation<'c>` ### Safety A raw object must be valid. ``` -------------------------------- ### Run Pass Manager and Verify Module Source: https://github.com/mlir-rs/melior/blob/main/_autodocs/configuration.md Execute a pass manager on a module and assert that the module verification succeeds. Always check pass results and operation verification. ```rust pass_manager.run(&mut module)?; assert!(module.as_operation().verify()); ``` -------------------------------- ### ExecutionEngine::lookup() Source: https://github.com/mlir-rs/melior/blob/main/_autodocs/api-reference/execution-engine.md Searches for a symbol within the compiled module and returns a raw pointer to it. ```APIDOC ## ExecutionEngine::lookup() ### Description Searches for a symbol in the compiled module and returns a pointer to it. ### Method `ExecutionEngine::lookup()` ### Parameters #### Path Parameters - **name** (*&str*) - Required - Symbol name to look up ### Request Example ```rust let func_ptr = engine.lookup("add"); if !func_ptr.is_null() { println!("Found function at {:p}", func_ptr); } ``` ### Response #### Success Response (*mut ()) - A raw pointer to the symbol (null if not found). ### Source `melior/src/execution_engine.rs:41` ``` -------------------------------- ### Print MLIR Values for Debugging Source: https://github.com/mlir-rs/melior/blob/main/_autodocs/api-reference/ir-values.md Shows how to print MLIR values for debugging purposes using the standard `println!` and `{:?}` formatters. The output format depends on the value's location in the IR. ```rust let value = op.result(0).unwrap().into(); println!("Value: {}", value); println!("Debug: {:?}", value); ``` -------------------------------- ### utility::register_all_dialects() Source: https://github.com/mlir-rs/melior/blob/main/_autodocs/api-reference/utilities.md Registers all standard MLIR dialects in a provided registry. This is a crucial step before creating MLIR contexts that require dialect support. ```APIDOC ## utility::register_all_dialects(registry: &DialectRegistry) ### Description Registers all standard MLIR dialects in a registry. ### Parameters #### Path Parameters - **registry** (DialectRegistry) - Required - Registry to populate ### Example ```rust use melior::{utility, dialect::DialectRegistry}; let registry = DialectRegistry::new(); utility::register_all_dialects(®istry); let context = Context::new_with_registry(®istry, true); ``` ``` -------------------------------- ### DialectHandle Methods Source: https://github.com/mlir-rs/melior/blob/main/_autodocs/api-reference/dialects.md Provides handles for various core dialects, allowing them to be loaded into a context. ```APIDOC ## Dialect Handles Each major dialect has a handle method: - `DialectHandle::func()` - Function dialect - `DialectHandle::llvm()` - LLVM dialect - `DialectHandle::arith()` - Arithmetic dialect - `DialectHandle::memref()` - Memref dialect - `DialectHandle::scf()` - Structured control flow dialect - `DialectHandle::cf()` - Control flow dialect - `DialectHandle::index()` - Index dialect ``` -------------------------------- ### Custom Error Handling Pattern in Melior Source: https://github.com/mlir-rs/melior/blob/main/_autodocs/errors.md Demonstrates a standard pattern for error handling in Melior, involving building and verifying MLIR modules. It shows how to return a Result and handle potential verification failures. ```rust use melior::{Context, Error}; use melior::ir::{Module, Location}; fn build_and_verify_module() -> Result { let context = Context::new(); let location = Location::unknown(&context); let module = Module::new(location); // Build IR... // Verify module if !module.as_operation().verify() { return Err(Error::OperationVerificationFailed); } Ok(module) } // Usage: match build_and_verify_module() { Ok(module) => println!("Module valid"), Err(e) => eprintln!("Error: {:?}", e), } ``` -------------------------------- ### ContextRef::from_raw() Source: https://github.com/mlir-rs/melior/blob/main/_autodocs/api-reference/context.md Creates a ContextRef from a raw MLIR context pointer. This is an unsafe operation that requires the provided raw pointer to be valid. ```APIDOC ## `ContextRef::from_raw()` ### Description Creates a context reference from a raw C API object. This is an unsafe operation and requires the raw object to be valid. ### Method Rust function ### Parameters #### Path Parameters - **raw** (MlirContext) - Required - Raw MLIR context ### Returns - `ContextRef<'c>` - A borrowed reference to a context with lifetime tracking. ### Safety A raw object must be valid. ``` -------------------------------- ### StringAttribute::new() Source: https://github.com/mlir-rs/melior/blob/main/_autodocs/api-reference/attributes.md Creates a new StringAttribute with the given context and string value. ```APIDOC ## StringAttribute::new() ### Description Creates a string attribute. ### Method `StringAttribute::new(context: &'c Context, value: &str) -> Self` ### Parameters #### Path Parameters - **context** ( &'c Context ) - Required - Context - **value** ( &str ) - Required - String value ### Request Example ```rust let str_attr = StringAttribute::new(&context, "my_function"); ``` ### Response #### Success Response (StringAttribute<'c>) - **StringAttribute<'c>** - The created string attribute. ### Source `melior/src/ir/attribute/string.rs` ``` -------------------------------- ### Region::into_raw() Source: https://github.com/mlir-rs/melior/blob/main/_autodocs/api-reference/ir-blocks-regions.md Consumes an owned Region and converts it into its raw MLIR C API representation. ```APIDOC ## `Region::into_raw()` ### Description Converts an owned `Region` into a raw C API object (`MlirRegion`), consuming the region in the process. ### Method `into_raw()` ### Parameters No parameters. ### Returns `MlirRegion` - The raw MLIR region object. ### Source `melior/src/ir/region.rs:29` ``` -------------------------------- ### Rust BytecodeWriterConfig Configuration Source: https://github.com/mlir-rs/melior/blob/main/_autodocs/api-reference/utilities.md Configuration options for the BytecodeWriter, allowing enabling debug info and compression. ```rust pub struct BytecodeWriterConfig { // ... } ``` ```rust pub impl BytecodeWriterConfig { pub fn enable_debug_info(&mut self, enabled: bool) -> &mut Self; pub fn enable_compression(&mut self, enabled: bool) -> &mut Self; } ``` -------------------------------- ### Build MLIR Operations in Rust Source: https://github.com/mlir-rs/melior/blob/main/_autodocs/INDEX.md Shows how to construct an MLIR operation using OperationBuilder, adding operands, results, attributes, and regions, with support for result type inference. ```rust OperationBuilder::new(name, location) .add_operands(&[...]) .add_results(&[...]) .add_attributes(&[(id, attr)]) .add_regions([region1, region2]) .enable_result_type_inference() .build()? ``` -------------------------------- ### Create Expand Strided Metadata Pass Source: https://github.com/mlir-rs/melior/blob/main/_autodocs/api-reference/passes.md Creates a pass to expand strided metadata for memory references. This pass requires no parameters. ```rust pub fn create_expand_strided_metadata() -> Pass ``` -------------------------------- ### Create to LLVM Conversion Pass Source: https://github.com/mlir-rs/melior/blob/main/_autodocs/api-reference/passes.md Creates a pass that converts MLIR dialects to LLVM IR. Add this pass to your pass manager to enable LLVM conversion. ```rust let to_llvm = pass::conversion::create_to_llvm(); pass_manager.add_pass(to_llvm); ``` -------------------------------- ### Using Values in Operations Source: https://github.com/mlir-rs/melior/blob/main/_autodocs/api-reference/ir-values.md Illustrates how to use `Value` types as operands when building new operations within a block. ```APIDOC ## Using Values in Operations Values are used as operands when building operations: ```rust use melior::{ Context, ir::{Location, Block, Type}, dialect::arith, }; let context = Context::new(); let location = Location::unknown(&context); let i32_type = Type::parse(&context, "i32").unwrap(); let block = Block::new(&[(i32_type, location), (i32_type, location)]); // Get block arguments as values let arg0 = block.argument(0).unwrap().into(); let arg1 = block.argument(1).unwrap().into(); // Use values in operations let add = block.append_operation(arith::addi(arg0, arg1, location)); let result: Value = add.result(0).unwrap().into(); // Use result in another operation let doubled = block.append_operation(arith::addi(result, result, location)); ``` ``` -------------------------------- ### PassManager::new() Source: https://github.com/mlir-rs/melior/blob/main/_autodocs/api-reference/passes.md Creates a new PassManager instance associated with a given MLIR Context. This is the entry point for setting up a sequence of passes. ```APIDOC ## PassManager::new() ### Description Creates a new pass manager for the given context. ### Method `PassManager::new(context: &Context) -> Self` ### Parameters #### Path Parameters - **context** (Reference to Context) - Required - The MLIR context to associate with this pass manager. ### Returns - `PassManager` - A new instance of PassManager. ### Request Example ```rust let pass_manager = PassManager::new(&context); ``` ``` -------------------------------- ### Create a Function Type Source: https://github.com/mlir-rs/melior/blob/main/_autodocs/api-reference/ir-types.md Use `FunctionType::new` to construct a function type by specifying its input and output types. Ensure you have a valid `Context` and `Type` instances for inputs and outputs. ```rust let i32 = IntegerType::new(&context, 32).into(); let func_type = FunctionType::new(&context, &[i32, i32], &[i32]); ``` -------------------------------- ### Access Block Argument Type Source: https://github.com/mlir-rs/melior/blob/main/_autodocs/api-reference/ir-values.md Demonstrates how to create a block with an argument and then access the type of that argument. This is useful for type checking or further operations on block inputs. ```rust let index_type = Type::index(&context); let location = Location::unknown(&context); let block = Block::new(&[(index_type, location)]); // Access the argument let arg = block.argument(0).unwrap(); let arg_type = arg.r#type(); ``` -------------------------------- ### Create 64-bit Float Type Source: https://github.com/mlir-rs/melior/blob/main/_autodocs/api-reference/ir-types.md Use `Type::float64` to create a 64-bit floating-point type. Requires a `Context`. ```rust let f64 = Type::float64(&context); ``` -------------------------------- ### Create Custom Rewrite Pattern Source: https://github.com/mlir-rs/melior/blob/main/_autodocs/api-reference/utilities.md Enables the creation of custom rewrite patterns by implementing the `RewritePattern` trait. This is the foundation for IR transformation. ```rust pub fn create_op_rewrite_pattern( pattern: P, ) -> Box ``` -------------------------------- ### Create Unknown Location Source: https://github.com/mlir-rs/melior/blob/main/_autodocs/api-reference/ir-blocks-regions.md Creates an unknown location. Requires a context. ```rust let loc = Location::unknown(&context); ``` -------------------------------- ### Value::from_raw() Source: https://github.com/mlir-rs/melior/blob/main/_autodocs/api-reference/ir-values.md Creates a `Value` instance from a raw MLIR C API object. This is an unsafe operation and requires a valid MLIR value. ```APIDOC ## Value::from_raw() ### Description Creates a value from a raw C API object. ### Safety A raw object must be valid. ### Parameters #### Path Parameters - **value** (MlirValue) - Required - Raw MLIR value ### Returns - **Value<'c, 'a>** - A new `Value` instance. ``` -------------------------------- ### Operation::into_raw() Source: https://github.com/mlir-rs/melior/blob/main/_autodocs/api-reference/ir-operations.md Converts an `Operation` into its raw C API representation, consuming the operation in the process. ```APIDOC ## Operation::into_raw() ### Description Converts an operation into a raw C API object, consuming the operation. ### Method `const fn into_raw(self) -> MlirOperation` ### Returns - `MlirOperation` ### Example ```rust let raw = operation.into_raw(); ``` ``` -------------------------------- ### func::func() Source: https://github.com/mlir-rs/melior/blob/main/_autodocs/api-reference/dialects.md Creates a function definition with the specified name, type, region, attributes, and location. ```APIDOC ## func::func() ### Description Creates a function definition. ### Method Rust Function ### Signature ```rust pub fn func<'c>( context: &'c Context, name: StringAttribute<'c>, function_type: TypeAttribute<'c>, region: Region<'c>, attributes: &[(Identifier<'c>, Attribute<'c>)], location: Location<'c>, ) -> Operation<'c> ``` ### Parameters #### Path Parameters - **context** (&'c Context) - Required - Context - **name** (StringAttribute) - Required - Function name - **function_type** (TypeAttribute) - Required - Function type attribute - **region** (Region) - Required - Function body region - **attributes** (&[(Identifier, Attribute)]) - Required - Additional attributes - **location** (Location) - Required - Location ### Request Example ```rust let func_op = func::func( &context, StringAttribute::new(&context, "add"), TypeAttribute::new(func_type), region, &[], location, ); ``` ### Response #### Success Response - **Operation<'c>** - The created function operation. ``` -------------------------------- ### Block::from_raw() Source: https://github.com/mlir-rs/melior/blob/main/_autodocs/api-reference/ir-blocks-regions.md Creates a Block instance from a raw MLIRBlock C API object. This is an unsafe operation. ```APIDOC ## Block::from_raw() ### Description Creates a block from a raw C API object. ### Safety A raw object must be valid. ### Signature ```rust pub unsafe fn from_raw(raw: MlirBlock) -> Self ``` ### Parameters #### Path Parameters - **raw** (*MlirBlock*) - Required - Raw MLIR block ### Returns - **Block<'c>** - The block created from the raw object. ```