1 /* Copyright 2018 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_XLA_SERVICE_TUPLE_UTIL_H_ 17 #define TENSORFLOW_COMPILER_XLA_SERVICE_TUPLE_UTIL_H_ 18 19 #include "tensorflow/compiler/xla/service/hlo_instruction.h" 20 #include "tensorflow/compiler/xla/service/hlo_value.h" 21 22 namespace xla { 23 class TupleUtil { 24 public: 25 // Generates HLO instructions to get a prefix tuple from `input_tuple` (which 26 // must be of tuple shape) of length `elements`. Returns the root of the 27 // graph of instructions generated. 28 // 29 // The instructions are generated into the computation containing 30 // `input_tuple`. 31 static HloInstruction* ExtractPrefix(HloInstruction* input_tuple, 32 int64_t elements); 33 34 // Generates HLO instructions to create a tuple that consists of the values in 35 // `trailing_values` appended to `input_tuple` (which must be of tuple shape). 36 // Returns the root of the graph of instructions generated. 37 // 38 // The instructions are generated into the computation containing 39 // `input_tuple`. 40 static HloInstruction* AppendSuffix( 41 HloInstruction* input_tuple, 42 absl::Span<HloInstruction* const> trailing_values); 43 44 // Generates HLO instructions that duplicates the tuple by inserting 45 // get-tuple-elements and a new tuple instruction. Returns the root of the 46 // graph of instructions generated. Duplicate(HloInstruction * input_tuple)47 static HloInstruction* Duplicate(HloInstruction* input_tuple) { 48 return ExtractPrefix(input_tuple, input_tuple->shape().tuple_shapes_size()); 49 } 50 51 // Descend to the shape_index element of the tuple and replace that with 52 // new_instruction. If the replacement instruction has a different shape than 53 // the old one, we insert a bitcast if insert_bitcast_if_different_shape is 54 // set to true. 55 static StatusOr<HloInstruction*> ReplaceTupleWith( 56 HloInstruction* new_instruction, HloInstruction* tuple, 57 ShapeIndex shape_index, bool insert_bitcast_if_different_shape = true); 58 59 // Recursively create kGetTupleElement instructions if the defining position 60 // shape is not an array. Returns the new instruction that has array shape. 61 static HloInstruction* AddGetTupleElements(const HloPosition& position); 62 }; 63 } // namespace xla 64 65 #endif // TENSORFLOW_COMPILER_XLA_SERVICE_TUPLE_UTIL_H_ 66