Files
concrete/compilers/concrete-compiler/compiler/lib/Dialect/TFHE/Transforms/Optimization.cpp
Andi Drebes c8c969773e Rebase onto llvm-project 465ee9bfb26d with local changes
This commit rebases the compiler onto commit 465ee9bfb26d from
llvm-project with locally maintained patches on top, i.e.:

  * 5d8669d669ee: Fix the element alignment (size) for memrefCopy
  * 4239163ea337: fix: Do not fold the memref.subview if the offset are
                  != 0 and strides != 1
  * 72c5decfcc21: remove github stuff from llvm
  * 8d0ce8f9eca1: Support arbitrary element types in named operations
                  via attributes
  * 94f64805c38c: Copy attributes of scf.for on bufferization and make
                  it an allocation hoisting barrier

Main upstream changes from llvm-project that required modification of
concretecompiler:

  * Switch to C++17
  * Various changes in the interfaces for linalg named operations
  * Transition from `llvm::Optional` to `std::optional`
  * Use of enums instead of string values for iterator types in linalg
  * Changed default naming convention of getter methods in
    ODS-generated operation classes from `some_value()` to
    `getSomeValue()`
  * Renaming of Arithmetic dialect to Arith
  * Refactoring of side effect interfaces (i.e., renaming from
    `NoSideEffect` to `Pure`)
  * Re-design of the data flow analysis framework
  * Refactoring of build targets for Python bindings
  * Refactoring of array attributes with integer values
  * Renaming of `linalg.init_tensor` to `tensor.empty`
  * Emission of `linalg.map` operations in bufferization of the Tensor
    dialect requiring another linalg conversion pass and registration
    of the bufferization op interfaces for linalg operations
  * Refactoring of the one-shot bufferizer
  * Necessity to run the expand-strided-metadata, affine-to-std and
    finalize-memref-to-llvm passes before converson to the LLVM
    dialect
  * Renaming of `BlockAndValueMapping` to `IRMapping`
  * Changes in the build function of `LLVM::CallOp`
  * Refactoring of the construction of `llvm::ArrayRef` and
    `llvm::MutableArrayRef` (direct invocation of constructor instead
    of builder functions for some cases)
  * New naming conventions for generated SSA values requiring rewrite
    of some check tests
  * Refactoring of `mlir::LLVM::lookupOrCreateMallocFn()`
  * Interface changes in generated type parsers
  * New dependencies for to mlir_float16_utils and
    MLIRSparseTensorRuntime for the runtime
  * Overhaul of MLIR-c deleting `mlir-c/Registration.h`
  * Deletion of library MLIRLinalgToSPIRV
  * Deletion of library MLIRLinalgAnalysis
  * Deletion of library MLIRMemRefUtils
  * Deletion of library MLIRQuantTransforms
  * Deletion of library MLIRVectorToROCDL
2023-03-09 17:47:16 +01:00

90 lines
3.0 KiB
C++

// Part of the Concrete Compiler Project, under the BSD3 License with Zama
// Exceptions. See
// https://github.com/zama-ai/concrete-compiler-internal/blob/main/LICENSE.txt
// for license information.
#include <mlir/Dialect/Arith/IR/Arith.h>
#include <mlir/IR/PatternMatch.h>
#include <mlir/Transforms/GreedyPatternRewriteDriver.h>
#include <concretelang/Dialect/TFHE/IR/TFHEOps.h>
#include <concretelang/Dialect/TFHE/Transforms/Optimization.h>
#include <concretelang/Support/Constants.h>
namespace mlir {
namespace concretelang {
namespace {
/// Get the constant integer that the cleartext was created from if it exists.
std::optional<IntegerAttr>
getConstantIntFromCleartextIfExists(mlir::Value cleartext) {
auto constantOp = cleartext.getDefiningOp();
if (constantOp == nullptr)
return {};
if (llvm::isa<arith::ConstantOp>(constantOp)) {
auto constIntToMul = constantOp->getAttrOfType<mlir::IntegerAttr>("value");
if (constIntToMul != nullptr)
return constIntToMul;
}
return {};
}
/// Rewrite a TFHE multiplication with an integer operation as a
/// Zero operation if it's being multiplied with a constant 0, or as
/// a Negate operation if multiplied with a constant -1.
class MulCleartextLweCiphertextOpPattern
: public mlir::OpRewritePattern<mlir::concretelang::TFHE::MulGLWEIntOp> {
public:
MulCleartextLweCiphertextOpPattern(mlir::MLIRContext *context)
: mlir::OpRewritePattern<mlir::concretelang::TFHE::MulGLWEIntOp>(
context, ::mlir::concretelang::DEFAULT_PATTERN_BENEFIT) {}
mlir::LogicalResult
matchAndRewrite(mlir::concretelang::TFHE::MulGLWEIntOp op,
mlir::PatternRewriter &rewriter) const override {
auto cleartext = op.getOperand(1);
auto constIntToMul = getConstantIntFromCleartextIfExists(cleartext);
// Constant integer
if (constIntToMul.has_value()) {
auto toMul = constIntToMul.value().getInt();
if (toMul == 0) {
rewriter.replaceOpWithNewOp<mlir::concretelang::TFHE::ZeroGLWEOp>(
op, op.getResult().getType());
return mlir::success();
}
if (toMul == -1) {
rewriter.replaceOpWithNewOp<mlir::concretelang::TFHE::NegGLWEOp>(
op, op.getResult().getType(), op.getOperand(0));
return mlir::success();
}
}
return mlir::failure();
}
};
/// Optimization pass that should choose more efficient ways of performing
/// crypto operations.
class TFHEOptimizationPass : public TFHEOptimizationBase<TFHEOptimizationPass> {
public:
void runOnOperation() override {
mlir::Operation *op = getOperation();
mlir::RewritePatternSet patterns(op->getContext());
patterns.add<MulCleartextLweCiphertextOpPattern>(op->getContext());
if (mlir::applyPatternsAndFoldGreedily(op, std::move(patterns)).failed()) {
this->signalPassFailure();
}
}
};
} // end anonymous namespace
std::unique_ptr<mlir::OperationPass<>> createTFHEOptimizationPass() {
return std::make_unique<TFHEOptimizationPass>();
}
} // namespace concretelang
} // namespace mlir