|
| 1 | +from mlir import ir |
| 2 | +from mlir.dialects import ext, transform, func, bufferization |
| 3 | +from mlir.dialects.transform import DiagnosedSilenceableFailure |
| 4 | + |
| 5 | +from lighthouse.dialects.transform.transform_ext import TransformExtensionDialect |
| 6 | +from lighthouse.ingress.mlir_gen.utils import emit_buf_to_tensor |
| 7 | +from lighthouse.utils.mlir import func_cif |
| 8 | + |
| 9 | + |
| 10 | +class ConvertFuncResultsToArgsOp( |
| 11 | + TransformExtensionDialect.Operation, name="convert_func_results_to_args" |
| 12 | +): |
| 13 | + """Converts all function return values to function arguments. |
| 14 | +
|
| 15 | + Function return values are placed in the beginning of the argument list, |
| 16 | + followed by the original function arguments. |
| 17 | +
|
| 18 | + Function arguments are converted to memrefs with appropriate bufferization |
| 19 | + annotations for inputs (bufferization.to_tensor with restrict=True) and |
| 20 | + outputs (bufferization.materialize_in_destination). |
| 21 | +
|
| 22 | + Currently supports only functions with tensor arguments and return values. |
| 23 | + """ |
| 24 | + |
| 25 | + target: ext.Operand[transform.AnyOpType] |
| 26 | + converted_func: ext.Result[transform.AnyOpType[()]] = ext.result(infer_type=True) |
| 27 | + |
| 28 | + @classmethod |
| 29 | + def attach_interface_impls(cls, context=None): |
| 30 | + cls.TransformOpInterfaceModel.attach(cls.OPERATION_NAME, context=context) |
| 31 | + cls.MemoryEffectsOpInterfaceModel.attach(cls.OPERATION_NAME, context=context) |
| 32 | + |
| 33 | + @staticmethod |
| 34 | + def convert_func(target: func.FuncOp) -> func.FuncOp: |
| 35 | + def memref_t(ttype: ir.Type) -> ir.MemRefType: |
| 36 | + return ir.MemRefType.get(ttype.shape, ttype.element_type) |
| 37 | + |
| 38 | + func_name = target.sym_name.value |
| 39 | + func_inputs = list(target.type.inputs) |
| 40 | + func_results = list(target.type.results) |
| 41 | + assert all(isinstance(ty, ir.RankedTensorType) for ty in func_inputs), ( |
| 42 | + "Only tensors are supported as input types" |
| 43 | + ) |
| 44 | + assert all(isinstance(ty, ir.RankedTensorType) for ty in func_results), ( |
| 45 | + "Only tensors are supported as return types" |
| 46 | + ) |
| 47 | + |
| 48 | + nresults = len(func_results) |
| 49 | + new_args = [memref_t(ty) for ty in func_results + func_inputs] |
| 50 | + |
| 51 | + @func_cif(*new_args, name=func_name) |
| 52 | + def f(*args): |
| 53 | + outputs = args[:nresults] |
| 54 | + inputs = args[nresults:] |
| 55 | + # convert input memrefs to tensors |
| 56 | + input_tensors = [] |
| 57 | + for input in inputs: |
| 58 | + t = emit_buf_to_tensor(input, restrict=True) |
| 59 | + input_tensors.append(t) |
| 60 | + |
| 61 | + # clone function body and map args and return values |
| 62 | + cloned_map = {} |
| 63 | + for op in target.regions[0].blocks[0].operations: |
| 64 | + if isinstance(op, func.ReturnOp): |
| 65 | + # emit materialize_in_destination for each return value |
| 66 | + for i, res_val in enumerate(op.operands): |
| 67 | + if res_val.owner not in cloned_map: |
| 68 | + raise NotImplementedError("Unsupported return value") |
| 69 | + iresult = res_val.result_number |
| 70 | + new_val = cloned_map[res_val.owner].results[iresult] |
| 71 | + bufferization.materialize_in_destination( |
| 72 | + None, |
| 73 | + new_val, |
| 74 | + outputs[i], |
| 75 | + restrict=True, |
| 76 | + writable=True, |
| 77 | + ) |
| 78 | + else: |
| 79 | + new_op = op.clone() |
| 80 | + for i, oo in enumerate(op.operands): |
| 81 | + if isinstance(oo, ir.BlockArgument): |
| 82 | + # operand is func argument |
| 83 | + # replace with new input tensors |
| 84 | + new_op.operands[i] = input_tensors[oo.arg_number] |
| 85 | + else: |
| 86 | + # replace operands with cloned values |
| 87 | + if oo.owner in cloned_map: |
| 88 | + iresult = oo.result_number |
| 89 | + new_op.operands[i] = cloned_map[oo.owner].results[ |
| 90 | + iresult |
| 91 | + ] |
| 92 | + cloned_map[op] = new_op |
| 93 | + |
| 94 | + return f.func_op |
| 95 | + |
| 96 | + class TransformOpInterfaceModel(transform.TransformOpInterface): |
| 97 | + @staticmethod |
| 98 | + def apply( |
| 99 | + op: "ConvertFuncResultsToArgsOp", |
| 100 | + _rewriter: transform.TransformRewriter, |
| 101 | + results: transform.TransformResults, |
| 102 | + state: transform.TransformState, |
| 103 | + ) -> DiagnosedSilenceableFailure: |
| 104 | + targets = state.get_payload_ops(op.target) |
| 105 | + converted_funcs = [] |
| 106 | + |
| 107 | + for target in targets: |
| 108 | + if not isinstance(target, func.FuncOp): |
| 109 | + return DiagnosedSilenceableFailure.SilenceableFailure |
| 110 | + |
| 111 | + with ir.InsertionPoint(target), target.location: |
| 112 | + new_func = ConvertFuncResultsToArgsOp.convert_func(target) |
| 113 | + target.erase() |
| 114 | + converted_funcs.append(new_func) |
| 115 | + |
| 116 | + results.set_ops(op.converted_func, converted_funcs) |
| 117 | + |
| 118 | + return DiagnosedSilenceableFailure.Success |
| 119 | + |
| 120 | + @staticmethod |
| 121 | + def allow_repeated_handle_operands(_op: "ConvertFuncResultsToArgsOp") -> bool: |
| 122 | + return False |
| 123 | + |
| 124 | + class MemoryEffectsOpInterfaceModel(ir.MemoryEffectsOpInterface): |
| 125 | + @staticmethod |
| 126 | + def get_effects(op: "ConvertFuncResultsToArgsOp", effects): |
| 127 | + transform.consumes_handle(op.op_operands, effects) |
| 128 | + transform.produces_handle(op.results, effects) |
| 129 | + transform.modifies_payload(effects) |
| 130 | + |
| 131 | + |
| 132 | +def convert_func_results_to_args( |
| 133 | + target: ir.Value[transform.AnyOpType], bench_name: str | None = None |
| 134 | +) -> ir.Value[transform.AnyOpType]: |
| 135 | + """snake_case wrapper to create a ConvertFuncResultsToArgsOp.""" |
| 136 | + op = ConvertFuncResultsToArgsOp(target=target) |
| 137 | + return op.converted_func |
0 commit comments