xref: /aosp_15_r20/external/tensorflow/tensorflow/compiler/mlir/xla/transforms/utils.h (revision b6fb3261f9314811a0f4371741dbb8839866f948)
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 #ifndef TENSORFLOW_COMPILER_MLIR_XLA_TRANSFORMS_UTILS_H_
17 #define TENSORFLOW_COMPILER_MLIR_XLA_TRANSFORMS_UTILS_H_
18 
19 #include "llvm/ADT/ArrayRef.h"
20 #include "mlir/IR/Builders.h"  // from @llvm-project
21 #include "mlir/IR/BuiltinAttributes.h"  // from @llvm-project
22 #include "mlir/IR/BuiltinTypes.h"  // from @llvm-project
23 #include "mlir/IR/Location.h"  // from @llvm-project
24 #include "mlir/IR/Types.h"  // from @llvm-project
25 #include "tensorflow/compiler/xla/mlir_hlo/include/mlir-hlo/Dialect/mhlo/IR/hlo_ops.h"
26 
27 namespace mlir {
28 namespace mhlo {
29 
30 // Builds body for reduce op by using the template binary op as the
31 // reducer op.
32 template <typename Op>
BuildReduceBody(Type element_type,Region * body,OpBuilder * builder)33 void BuildReduceBody(Type element_type, Region* body, OpBuilder* builder) {
34   OpBuilder::InsertionGuard guard(*builder);
35   Block* block = builder->createBlock(body);
36 
37   // Block arguments are scalars of the given element type.
38   Type type = RankedTensorType::get(/*shape=*/{}, element_type);
39   Location loc = body->getLoc();
40   block->addArguments({type, type}, SmallVector<Location, 2>(2, loc));
41 
42   auto reducer =
43       builder->create<Op>(loc, block->getArgument(0), block->getArgument(1));
44   builder->create<ReturnOp>(loc, reducer.getResult());
45 }
46 
47 ConstantOp GetScalarConstOfType(Type ty, Location loc, int64_t raw_value,
48                                 OpBuilder* builder);
49 
50 ConstantOp GetScalarNegZeroOfType(Type ty, Location loc, OpBuilder* builder);
51 
52 // Converts an ArrayAttr to a 1D 64-bit dense elements attribute.
53 DenseIntElementsAttr GetI64ElementsAttr(ArrayAttr attr);
54 DenseIntElementsAttr GetI64ElementsAttr(llvm::ArrayRef<int64_t> values,
55                                         Builder* builder);
56 
57 }  // namespace mhlo
58 }  // namespace mlir
59 
60 #endif  // TENSORFLOW_COMPILER_MLIR_XLA_TRANSFORMS_UTILS_H_
61