1// RUN: mlir-opt %s \
2// RUN:   --sparsification --sparse-tensor-conversion \
3// RUN:   --convert-linalg-to-loops --convert-vector-to-scf --convert-scf-to-std \
4// RUN:   --func-bufferize --tensor-constant-bufferize --tensor-bufferize \
5// RUN:   --std-bufferize --finalizing-bufferize  \
6// RUN:   --convert-vector-to-llvm --convert-std-to-llvm | \
7// RUN: TENSOR0="%mlir_integration_test_dir/data/test.mtx" \
8// RUN: mlir-cpu-runner \
9// RUN:  -e entry -entry-point-result=void  \
10// RUN:  -shared-libs=%mlir_integration_test_dir/libmlir_c_runner_utils%shlibext | \
11// RUN: FileCheck %s
12
13!Filename = type !llvm.ptr<i8>
14
15#DCSR = #sparse_tensor.encoding<{
16  dimLevelType = [ "compressed", "compressed" ],
17  dimOrdering = affine_map<(i,j) -> (i,j)>
18}>
19
20#eltwise_mult = {
21  indexing_maps = [
22    affine_map<(i,j) -> (i,j)>  // X (out)
23  ],
24  iterator_types = ["parallel", "parallel"],
25  doc = "X(i,j) += X(i,j) * X(i,j)"
26}
27
28//
29// Integration test that lowers a kernel annotated as sparse to
30// actual sparse code, initializes a matching sparse storage scheme
31// from file, and runs the resulting code with the JIT compiler.
32//
33module {
34  //
35  // A kernel that multiplies a sparse matrix A with itself
36  // in an element-wise fashion. In this operation, we have
37  // a sparse tensor as output, but although the values of the
38  // sparse tensor change, its nonzero structure remains the same.
39  //
40  func @kernel_eltwise_mult(%argx: tensor<?x?xf64, #DCSR> {linalg.inplaceable = true})
41    -> tensor<?x?xf64, #DCSR> {
42    %0 = linalg.generic #eltwise_mult
43      outs(%argx: tensor<?x?xf64, #DCSR>) {
44      ^bb(%x: f64):
45        %0 = mulf %x, %x : f64
46        linalg.yield %0 : f64
47    } -> tensor<?x?xf64, #DCSR>
48    return %0 : tensor<?x?xf64, #DCSR>
49  }
50
51  func private @getTensorFilename(index) -> (!Filename)
52
53  //
54  // Main driver that reads matrix from file and calls the sparse kernel.
55  //
56  func @entry() {
57    %d0 = constant 0.0 : f64
58    %c0 = constant 0 : index
59
60    // Read the sparse matrix from file, construct sparse storage.
61    %fileName = call @getTensorFilename(%c0) : (index) -> (!Filename)
62    %x = sparse_tensor.new %fileName : !llvm.ptr<i8> to tensor<?x?xf64, #DCSR>
63
64    // Call kernel.
65    %0 = call @kernel_eltwise_mult(%x) : (tensor<?x?xf64, #DCSR>) -> tensor<?x?xf64, #DCSR>
66
67    // Print the result for verification.
68    //
69    // CHECK: ( 1, 1.96, 4, 6.25, 9, 16.81, 16, 27.04, 25 )
70    //
71    %m = sparse_tensor.values %0 : tensor<?x?xf64, #DCSR> to memref<?xf64>
72    %v = vector.transfer_read %m[%c0], %d0: memref<?xf64>, vector<9xf64>
73    vector.print %v : vector<9xf64>
74
75    return
76  }
77}
78