1 /* Copyright 2021 The TensorFlow Authors. All Rights Reserved. 2 3 Licensed under the Apache License, Version 2.0 (the "License"); 4 you may not use this file except in compliance with the License. 5 You may obtain a copy of the License at 6 7 http://www.apache.org/licenses/LICENSE-2.0 8 9 Unless required by applicable law or agreed to in writing, software 10 distributed under the License is distributed on an "AS IS" BASIS, 11 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 See the License for the specific language governing permissions and 13 limitations under the License. 14 ==============================================================================*/ 15 16 // This file implements logic for some optimizations to reduce size on export. 17 18 #include <memory> 19 20 #include "mlir/IR/BuiltinAttributes.h" // from @llvm-project 21 #include "mlir/IR/BuiltinOps.h" // from @llvm-project 22 #include "mlir/IR/BuiltinTypes.h" // from @llvm-project 23 #include "mlir/IR/ImplicitLocOpBuilder.h" // from @llvm-project 24 #include "mlir/IR/Matchers.h" // from @llvm-project 25 #include "mlir/IR/Operation.h" // from @llvm-project 26 #include "mlir/IR/Types.h" // from @llvm-project 27 #include "mlir/Pass/Pass.h" // from @llvm-project 28 #include "tensorflow/compiler/mlir/hlo/include/mlir-hlo/Dialect/mhlo/IR/hlo_ops.h" 29 #include "tensorflow/compiler/mlir/xla/transforms/passes_detail.h" 30 31 #define DEBUG_TYPE "xla-prepare-for-export" 32 33 namespace mlir { 34 namespace mhlo { 35 namespace { 36 37 // Prepare module for export to XLA HLO. 38 struct PrepareForExportPass : PrepareForExportPassBase<PrepareForExportPass> { 39 void runOnFunction() override; 40 }; 41 42 static PassRegistration<PrepareForExportPass> registration( 43 "xla-prepare-for-export", "Prepare for XLA export"); 44 45 } // end namespace 46 runOnFunction()47void PrepareForExportPass::runOnFunction() { 48 getFunction().walk([&](Operation *op) { 49 mlir::SplatElementsAttr attr; 50 if (!matchPattern(op, m_Constant(&attr))) return; 51 // Only consider int or floats for now. 52 if (!attr.getType().getElementType().isIntOrFloat()) return; 53 // Arbitrarialy chosen "small" number. This could be chosen based on the 54 // proto size too. 55 if (attr.getNumElements() < 32) return; 56 ShapedType return_type = op->getResultTypes().front().cast<ShapedType>(); 57 ImplicitLocOpBuilder b(op->getLoc(), op); 58 auto cst = b.create<::mlir::mhlo::ConstOp>(attr.getSplatValue()); 59 auto broadcast = b.create<::mlir::mhlo::BroadcastInDimOp>( 60 return_type, cst, b.getI64TensorAttr({})); 61 op->replaceAllUsesWith(broadcast); 62 op->erase(); 63 }); 64 } 65 CreatePrepareForExport()66std::unique_ptr<OperationPass<FuncOp>> CreatePrepareForExport() { 67 return std::make_unique<PrepareForExportPass>(); 68 } 69 70 } // end namespace mhlo 71 } // end namespace mlir 72