1 //===- Matrix.cpp - MLIR Matrix Class -------------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 9 #include "mlir/Analysis/Presburger/Matrix.h" 10 11 namespace mlir { 12 13 Matrix::Matrix(unsigned rows, unsigned columns) 14 : nRows(rows), nColumns(columns), data(nRows * nColumns) {} 15 16 Matrix Matrix::identity(unsigned dimension) { 17 Matrix matrix(dimension, dimension); 18 for (unsigned i = 0; i < dimension; ++i) 19 matrix(i, i) = 1; 20 return matrix; 21 } 22 23 int64_t &Matrix::at(unsigned row, unsigned column) { 24 assert(row < getNumRows() && "Row outside of range"); 25 assert(column < getNumColumns() && "Column outside of range"); 26 return data[row * nColumns + column]; 27 } 28 29 int64_t Matrix::at(unsigned row, unsigned column) const { 30 assert(row < getNumRows() && "Row outside of range"); 31 assert(column < getNumColumns() && "Column outside of range"); 32 return data[row * nColumns + column]; 33 } 34 35 int64_t &Matrix::operator()(unsigned row, unsigned column) { 36 return at(row, column); 37 } 38 39 int64_t Matrix::operator()(unsigned row, unsigned column) const { 40 return at(row, column); 41 } 42 43 unsigned Matrix::getNumRows() const { return nRows; } 44 45 unsigned Matrix::getNumColumns() const { return nColumns; } 46 47 void Matrix::resizeVertically(unsigned newNRows) { 48 nRows = newNRows; 49 data.resize(nRows * nColumns); 50 } 51 52 void Matrix::swapRows(unsigned row, unsigned otherRow) { 53 assert((row < getNumRows() && otherRow < getNumRows()) && 54 "Given row out of bounds"); 55 if (row == otherRow) 56 return; 57 for (unsigned col = 0; col < nColumns; col++) 58 std::swap(at(row, col), at(otherRow, col)); 59 } 60 61 void Matrix::swapColumns(unsigned column, unsigned otherColumn) { 62 assert((column < getNumColumns() && otherColumn < getNumColumns()) && 63 "Given column out of bounds"); 64 if (column == otherColumn) 65 return; 66 for (unsigned row = 0; row < nRows; row++) 67 std::swap(at(row, column), at(row, otherColumn)); 68 } 69 70 ArrayRef<int64_t> Matrix::getRow(unsigned row) const { 71 return {&data[row * nColumns], nColumns}; 72 } 73 74 void Matrix::addToRow(unsigned sourceRow, unsigned targetRow, int64_t scale) { 75 if (scale == 0) 76 return; 77 for (unsigned col = 0; col < nColumns; ++col) 78 at(targetRow, col) += scale * at(sourceRow, col); 79 return; 80 } 81 82 void Matrix::print(raw_ostream &os) const { 83 for (unsigned row = 0; row < nRows; ++row) { 84 for (unsigned column = 0; column < nColumns; ++column) 85 os << at(row, column) << ' '; 86 os << '\n'; 87 } 88 } 89 90 void Matrix::dump() const { print(llvm::errs()); } 91 92 } // namespace mlir 93