1 /* Copyright 2017 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 #include "tensorflow/compiler/xla/service/llvm_ir/loop_emitter.h"
17
18 #include <memory>
19 #include <utility>
20
21 #include "absl/strings/str_format.h"
22 #include "tensorflow/compiler/xla/service/llvm_ir/llvm_loop.h"
23 #include "tensorflow/compiler/xla/shape_util.h"
24 #include "tensorflow/compiler/xla/status_macros.h"
25 #include "tensorflow/compiler/xla/types.h"
26 #include "tensorflow/core/lib/core/errors.h"
27 #include "tensorflow/core/platform/logging.h"
28 #include "tensorflow/core/platform/protobuf.h"
29 #include "tensorflow/core/platform/types.h"
30
31 namespace xla {
32 namespace llvm_ir {
33
LoopEmitter(const BodyEmitter & body_emitter,const Shape & shape,llvm::IRBuilder<> * b)34 LoopEmitter::LoopEmitter(const BodyEmitter& body_emitter, const Shape& shape,
35 llvm::IRBuilder<>* b)
36 : body_emitter_(body_emitter), shape_(shape), b_(b) {}
37
LoopEmitter(const ElementGenerator & target_element_generator,const IrArray & target_array,llvm::IRBuilder<> * b)38 LoopEmitter::LoopEmitter(const ElementGenerator& target_element_generator,
39 const IrArray& target_array, llvm::IRBuilder<>* b)
40 : body_emitter_([=](const llvm_ir::IrArray::Index array_index) -> Status {
41 // Convert target_element_generator to a BodyEmitter.
42 TF_ASSIGN_OR_RETURN(llvm::Value * target_element,
43 target_element_generator(array_index));
44 target_array.EmitWriteArrayElement(array_index, target_element, b);
45 return Status::OK();
46 }),
47 shape_(target_array.GetShape()),
48 b_(b) {}
49
MakeBodyEmitterForMultiOutputFusion(const ElementGenerator & target_element_generator,const std::vector<IrArray> & target_arrays,llvm::IRBuilder<> * b)50 static LoopEmitter::BodyEmitter MakeBodyEmitterForMultiOutputFusion(
51 const ElementGenerator& target_element_generator,
52 const std::vector<IrArray>& target_arrays, llvm::IRBuilder<>* b) {
53 return [=](const llvm_ir::IrArray::Index array_index) {
54 TF_ASSIGN_OR_RETURN(llvm::Value * target_element,
55 target_element_generator(array_index));
56 CHECK(target_element->getType()->isStructTy())
57 << "This BodyEmitter is for multi-output fusion, but target element "
58 "generator does not produce values of struct type.";
59 CHECK_EQ(target_element->getType()->getStructNumElements(),
60 target_arrays.size());
61
62 for (int64 i = 0; i < target_arrays.size(); ++i) {
63 target_arrays[i].EmitWriteArrayElement(
64 array_index, b->CreateExtractValue(target_element, i), b);
65 }
66 return Status::OK();
67 };
68 }
69
LoopEmitter(const ElementGenerator & target_element_generator,absl::Span<const IrArray> target_arrays,llvm::IRBuilder<> * b)70 LoopEmitter::LoopEmitter(const ElementGenerator& target_element_generator,
71 absl::Span<const IrArray> target_arrays,
72 llvm::IRBuilder<>* b)
73 : body_emitter_(MakeBodyEmitterForMultiOutputFusion(
74 target_element_generator,
75 std::vector<IrArray>(target_arrays.begin(), target_arrays.end()), b)),
76 shape_(target_arrays[0].GetShape()),
77 b_(b) {
78 // Sanity check: In multi-output fusion, all shapes produced must have the
79 // same dimensions.
80 for (const IrArray& array : target_arrays) {
81 CHECK(ShapeUtil::SameDimensions(shape_, array.GetShape()))
82 << ": '" << shape_.ShortDebugString() << "' does not match '"
83 << array.GetShape().ShortDebugString() << "'";
84 }
85 }
86
EmitIndexAndSetExitBasicBlock(absl::string_view loop_name,llvm::Type * index_type)87 std::vector<IrArray::Index> LoopEmitter::EmitIndexAndSetExitBasicBlock(
88 absl::string_view loop_name, llvm::Type* index_type) {
89 CHECK_NE(index_type, nullptr);
90 if (ShapeUtil::IsScalar(shape_)) {
91 // No loop needed, so set exit_bb_ to nullptr.
92 exit_bb_ = nullptr;
93 return {IrArray::Index(index_type)};
94 }
95
96 // Create loop nest with one for-loop for each dimension of the target shape.
97 // Loops are added from outermost to innermost order with the ForLoopNest
98 // class so emit loops in order from most-major dimension down to most-minor
99 // dimension (of the target shape).
100 ForLoopNest loop_nest(loop_name, b_);
101 std::vector<llvm::Value*> array_multi_index(shape_.dimensions_size());
102 for (int i = 0; i < LayoutUtil::MinorToMajor(shape_).size(); ++i) {
103 int64 dimension = LayoutUtil::Major(shape_.layout(), i);
104 std::unique_ptr<ForLoop> loop = loop_nest.AddLoop(
105 /*start_index=*/0,
106 /*end_index=*/shape_.dimensions(dimension),
107 /*suffix=*/absl::StrFormat("dim.%d", dimension));
108 array_multi_index[dimension] = loop->GetIndVarValue();
109 }
110 IrArray::Index array_index(array_multi_index, shape_, index_type);
111
112 // Set IR builder insertion point to the loop body basic block of the
113 // innermost loop.
114 llvm::BasicBlock* innermost_body_bb = loop_nest.GetInnerLoopBodyBasicBlock();
115 b_->SetInsertPoint(innermost_body_bb,
116 innermost_body_bb->getFirstInsertionPt());
117
118 // Set exit_bb_ to the exit block of the loop nest.
119 exit_bb_ = loop_nest.GetOuterLoopExitBasicBlock();
120 CHECK_NOTNULL(exit_bb_);
121
122 return {array_index};
123 }
124
EmitLoop(absl::string_view loop_name,llvm::Type * index_type)125 Status LoopEmitter::EmitLoop(absl::string_view loop_name,
126 llvm::Type* index_type) {
127 if (index_type == nullptr) {
128 index_type = b_->getInt64Ty();
129 }
130
131 for (const IrArray::Index& array_index :
132 EmitIndexAndSetExitBasicBlock(loop_name, index_type)) {
133 TF_RETURN_IF_ERROR(body_emitter_(array_index));
134 }
135
136 // Set the insertion point of b_ to the loop exit, so that
137 // code emitted for later instructions will be correctly placed.
138 if (exit_bb_ != nullptr) {
139 b_->SetInsertPoint(exit_bb_);
140 }
141 return Status::OK();
142 }
143
144 } // namespace llvm_ir
145 } // namespace xla
146