blob: da2acd1fd3bb2467a8d6e2aa16d2b4777cb5434d [file] [log] [blame]
Aart Bik281c6812016-08-26 11:31:48 -07001/*
2 * Copyright (C) 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "loop_optimization.h"
18
Aart Bikf8f5a162017-02-06 15:35:29 -080019#include "arch/instruction_set.h"
20#include "arch/arm/instruction_set_features_arm.h"
21#include "arch/arm64/instruction_set_features_arm64.h"
22#include "arch/mips/instruction_set_features_mips.h"
23#include "arch/mips64/instruction_set_features_mips64.h"
24#include "arch/x86/instruction_set_features_x86.h"
25#include "arch/x86_64/instruction_set_features_x86_64.h"
Aart Bik92685a82017-03-06 11:13:43 -080026#include "driver/compiler_driver.h"
Aart Bik96202302016-10-04 17:33:56 -070027#include "linear_order.h"
Aart Bik281c6812016-08-26 11:31:48 -070028
29namespace art {
30
Aart Bikf8f5a162017-02-06 15:35:29 -080031// Enables vectorization (SIMDization) in the loop optimizer.
32static constexpr bool kEnableVectorization = true;
33
Aart Bik9abf8942016-10-14 09:49:42 -070034// Remove the instruction from the graph. A bit more elaborate than the usual
35// instruction removal, since there may be a cycle in the use structure.
Aart Bik281c6812016-08-26 11:31:48 -070036static void RemoveFromCycle(HInstruction* instruction) {
Aart Bik281c6812016-08-26 11:31:48 -070037 instruction->RemoveAsUserOfAllInputs();
38 instruction->RemoveEnvironmentUsers();
39 instruction->GetBlock()->RemoveInstructionOrPhi(instruction, /*ensure_safety=*/ false);
40}
41
Aart Bik807868e2016-11-03 17:51:43 -070042// Detect a goto block and sets succ to the single successor.
Aart Bike3dedc52016-11-02 17:50:27 -070043static bool IsGotoBlock(HBasicBlock* block, /*out*/ HBasicBlock** succ) {
44 if (block->GetPredecessors().size() == 1 &&
45 block->GetSuccessors().size() == 1 &&
46 block->IsSingleGoto()) {
47 *succ = block->GetSingleSuccessor();
48 return true;
49 }
50 return false;
51}
52
Aart Bik807868e2016-11-03 17:51:43 -070053// Detect an early exit loop.
54static bool IsEarlyExit(HLoopInformation* loop_info) {
55 HBlocksInLoopReversePostOrderIterator it_loop(*loop_info);
56 for (it_loop.Advance(); !it_loop.Done(); it_loop.Advance()) {
57 for (HBasicBlock* successor : it_loop.Current()->GetSuccessors()) {
58 if (!loop_info->Contains(*successor)) {
59 return true;
60 }
61 }
62 }
63 return false;
64}
65
Aart Bikf3e61ee2017-04-12 17:09:20 -070066// Detect a sign extension from the given type. Returns the promoted operand on success.
67static bool IsSignExtensionAndGet(HInstruction* instruction,
68 Primitive::Type type,
69 /*out*/ HInstruction** operand) {
70 // Accept any already wider constant that would be handled properly by sign
71 // extension when represented in the *width* of the given narrower data type
72 // (the fact that char normally zero extends does not matter here).
73 int64_t value = 0;
74 if (IsInt64AndGet(instruction, &value)) {
75 switch (type) {
76 case Primitive::kPrimByte:
77 if (std::numeric_limits<int8_t>::min() <= value &&
78 std::numeric_limits<int8_t>::max() >= value) {
79 *operand = instruction;
80 return true;
81 }
82 return false;
83 case Primitive::kPrimChar:
84 case Primitive::kPrimShort:
85 if (std::numeric_limits<int16_t>::min() <= value &&
86 std::numeric_limits<int16_t>::max() <= value) {
87 *operand = instruction;
88 return true;
89 }
90 return false;
91 default:
92 return false;
93 }
94 }
95 // An implicit widening conversion of a signed integer to an integral type sign-extends
96 // the two's-complement representation of the integer value to fill the wider format.
97 if (instruction->GetType() == type && (instruction->IsArrayGet() ||
98 instruction->IsStaticFieldGet() ||
99 instruction->IsInstanceFieldGet())) {
100 switch (type) {
101 case Primitive::kPrimByte:
102 case Primitive::kPrimShort:
103 *operand = instruction;
104 return true;
105 default:
106 return false;
107 }
108 }
109 // TODO: perhaps explicit conversions later too?
110 // (this may return something different from instruction)
111 return false;
112}
113
114// Detect a zero extension from the given type. Returns the promoted operand on success.
115static bool IsZeroExtensionAndGet(HInstruction* instruction,
116 Primitive::Type type,
117 /*out*/ HInstruction** operand) {
118 // Accept any already wider constant that would be handled properly by zero
119 // extension when represented in the *width* of the given narrower data type
120 // (the fact that byte/short normally sign extend does not matter here).
121 int64_t value = 0;
122 if (IsInt64AndGet(instruction, &value)) {
123 switch (type) {
124 case Primitive::kPrimByte:
125 if (std::numeric_limits<uint8_t>::min() <= value &&
126 std::numeric_limits<uint8_t>::max() >= value) {
127 *operand = instruction;
128 return true;
129 }
130 return false;
131 case Primitive::kPrimChar:
132 case Primitive::kPrimShort:
133 if (std::numeric_limits<uint16_t>::min() <= value &&
134 std::numeric_limits<uint16_t>::max() <= value) {
135 *operand = instruction;
136 return true;
137 }
138 return false;
139 default:
140 return false;
141 }
142 }
143 // An implicit widening conversion of a char to an integral type zero-extends
144 // the representation of the char value to fill the wider format.
145 if (instruction->GetType() == type && (instruction->IsArrayGet() ||
146 instruction->IsStaticFieldGet() ||
147 instruction->IsInstanceFieldGet())) {
148 if (type == Primitive::kPrimChar) {
149 *operand = instruction;
150 return true;
151 }
152 }
153 // A sign (or zero) extension followed by an explicit removal of just the
154 // higher sign bits is equivalent to a zero extension of the underlying operand.
155 if (instruction->IsAnd()) {
156 int64_t mask = 0;
157 HInstruction* a = instruction->InputAt(0);
158 HInstruction* b = instruction->InputAt(1);
159 // In (a & b) find (mask & b) or (a & mask) with sign or zero extension on the non-mask.
160 if ((IsInt64AndGet(a, /*out*/ &mask) && (IsSignExtensionAndGet(b, type, /*out*/ operand) ||
161 IsZeroExtensionAndGet(b, type, /*out*/ operand))) ||
162 (IsInt64AndGet(b, /*out*/ &mask) && (IsSignExtensionAndGet(a, type, /*out*/ operand) ||
163 IsZeroExtensionAndGet(a, type, /*out*/ operand)))) {
164 switch ((*operand)->GetType()) {
165 case Primitive::kPrimByte: return mask == std::numeric_limits<uint8_t>::max();
166 case Primitive::kPrimChar:
167 case Primitive::kPrimShort: return mask == std::numeric_limits<uint16_t>::max();
168 default: return false;
169 }
170 }
171 }
172 // TODO: perhaps explicit conversions later too?
173 return false;
174}
175
Aart Bikf8f5a162017-02-06 15:35:29 -0800176// Test vector restrictions.
177static bool HasVectorRestrictions(uint64_t restrictions, uint64_t tested) {
178 return (restrictions & tested) != 0;
179}
180
Aart Bikf3e61ee2017-04-12 17:09:20 -0700181// Insert an instruction.
Aart Bikf8f5a162017-02-06 15:35:29 -0800182static HInstruction* Insert(HBasicBlock* block, HInstruction* instruction) {
183 DCHECK(block != nullptr);
184 DCHECK(instruction != nullptr);
185 block->InsertInstructionBefore(instruction, block->GetLastInstruction());
186 return instruction;
187}
188
Aart Bik281c6812016-08-26 11:31:48 -0700189//
190// Class methods.
191//
192
193HLoopOptimization::HLoopOptimization(HGraph* graph,
Aart Bik92685a82017-03-06 11:13:43 -0800194 CompilerDriver* compiler_driver,
Aart Bik281c6812016-08-26 11:31:48 -0700195 HInductionVarAnalysis* induction_analysis)
196 : HOptimization(graph, kLoopOptimizationPassName),
Aart Bik92685a82017-03-06 11:13:43 -0800197 compiler_driver_(compiler_driver),
Aart Bik281c6812016-08-26 11:31:48 -0700198 induction_range_(induction_analysis),
Aart Bik96202302016-10-04 17:33:56 -0700199 loop_allocator_(nullptr),
Aart Bikf8f5a162017-02-06 15:35:29 -0800200 global_allocator_(graph_->GetArena()),
Aart Bik281c6812016-08-26 11:31:48 -0700201 top_loop_(nullptr),
Aart Bik8c4a8542016-10-06 11:36:57 -0700202 last_loop_(nullptr),
Aart Bik482095d2016-10-10 15:39:10 -0700203 iset_(nullptr),
Aart Bikdf7822e2016-12-06 10:05:30 -0800204 induction_simplication_count_(0),
Aart Bikf8f5a162017-02-06 15:35:29 -0800205 simplified_(false),
206 vector_length_(0),
207 vector_refs_(nullptr),
208 vector_map_(nullptr) {
Aart Bik281c6812016-08-26 11:31:48 -0700209}
210
211void HLoopOptimization::Run() {
Mingyao Yang01b47b02017-02-03 12:09:57 -0800212 // Skip if there is no loop or the graph has try-catch/irreducible loops.
Aart Bik281c6812016-08-26 11:31:48 -0700213 // TODO: make this less of a sledgehammer.
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800214 if (!graph_->HasLoops() || graph_->HasTryCatch() || graph_->HasIrreducibleLoops()) {
Aart Bik281c6812016-08-26 11:31:48 -0700215 return;
216 }
217
Aart Bik96202302016-10-04 17:33:56 -0700218 // Phase-local allocator that draws from the global pool. Since the allocator
219 // itself resides on the stack, it is destructed on exiting Run(), which
220 // implies its underlying memory is released immediately.
Aart Bikf8f5a162017-02-06 15:35:29 -0800221 ArenaAllocator allocator(global_allocator_->GetArenaPool());
Aart Bik96202302016-10-04 17:33:56 -0700222 loop_allocator_ = &allocator;
Nicolas Geoffrayebe16742016-10-05 09:55:42 +0100223
Aart Bik96202302016-10-04 17:33:56 -0700224 // Perform loop optimizations.
225 LocalRun();
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800226 if (top_loop_ == nullptr) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800227 graph_->SetHasLoops(false); // no more loops
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800228 }
229
Aart Bik96202302016-10-04 17:33:56 -0700230 // Detach.
231 loop_allocator_ = nullptr;
232 last_loop_ = top_loop_ = nullptr;
233}
234
235void HLoopOptimization::LocalRun() {
236 // Build the linear order using the phase-local allocator. This step enables building
237 // a loop hierarchy that properly reflects the outer-inner and previous-next relation.
238 ArenaVector<HBasicBlock*> linear_order(loop_allocator_->Adapter(kArenaAllocLinearOrder));
239 LinearizeGraph(graph_, loop_allocator_, &linear_order);
240
Aart Bik281c6812016-08-26 11:31:48 -0700241 // Build the loop hierarchy.
Aart Bik96202302016-10-04 17:33:56 -0700242 for (HBasicBlock* block : linear_order) {
Aart Bik281c6812016-08-26 11:31:48 -0700243 if (block->IsLoopHeader()) {
244 AddLoop(block->GetLoopInformation());
245 }
246 }
Aart Bik96202302016-10-04 17:33:56 -0700247
Aart Bik8c4a8542016-10-06 11:36:57 -0700248 // Traverse the loop hierarchy inner-to-outer and optimize. Traversal can use
Aart Bikf8f5a162017-02-06 15:35:29 -0800249 // temporary data structures using the phase-local allocator. All new HIR
250 // should use the global allocator.
Aart Bik8c4a8542016-10-06 11:36:57 -0700251 if (top_loop_ != nullptr) {
252 ArenaSet<HInstruction*> iset(loop_allocator_->Adapter(kArenaAllocLoopOptimization));
Aart Bikf8f5a162017-02-06 15:35:29 -0800253 ArenaSet<ArrayReference> refs(loop_allocator_->Adapter(kArenaAllocLoopOptimization));
254 ArenaSafeMap<HInstruction*, HInstruction*> map(
255 std::less<HInstruction*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
256 // Attach.
Aart Bik8c4a8542016-10-06 11:36:57 -0700257 iset_ = &iset;
Aart Bikf8f5a162017-02-06 15:35:29 -0800258 vector_refs_ = &refs;
259 vector_map_ = &map;
260 // Traverse.
Aart Bik8c4a8542016-10-06 11:36:57 -0700261 TraverseLoopsInnerToOuter(top_loop_);
Aart Bikf8f5a162017-02-06 15:35:29 -0800262 // Detach.
263 iset_ = nullptr;
264 vector_refs_ = nullptr;
265 vector_map_ = nullptr;
Aart Bik8c4a8542016-10-06 11:36:57 -0700266 }
Aart Bik281c6812016-08-26 11:31:48 -0700267}
268
269void HLoopOptimization::AddLoop(HLoopInformation* loop_info) {
270 DCHECK(loop_info != nullptr);
Aart Bikf8f5a162017-02-06 15:35:29 -0800271 LoopNode* node = new (loop_allocator_) LoopNode(loop_info);
Aart Bik281c6812016-08-26 11:31:48 -0700272 if (last_loop_ == nullptr) {
273 // First loop.
274 DCHECK(top_loop_ == nullptr);
275 last_loop_ = top_loop_ = node;
276 } else if (loop_info->IsIn(*last_loop_->loop_info)) {
277 // Inner loop.
278 node->outer = last_loop_;
279 DCHECK(last_loop_->inner == nullptr);
280 last_loop_ = last_loop_->inner = node;
281 } else {
282 // Subsequent loop.
283 while (last_loop_->outer != nullptr && !loop_info->IsIn(*last_loop_->outer->loop_info)) {
284 last_loop_ = last_loop_->outer;
285 }
286 node->outer = last_loop_->outer;
287 node->previous = last_loop_;
288 DCHECK(last_loop_->next == nullptr);
289 last_loop_ = last_loop_->next = node;
290 }
291}
292
293void HLoopOptimization::RemoveLoop(LoopNode* node) {
294 DCHECK(node != nullptr);
Aart Bik8c4a8542016-10-06 11:36:57 -0700295 DCHECK(node->inner == nullptr);
296 if (node->previous != nullptr) {
297 // Within sequence.
298 node->previous->next = node->next;
299 if (node->next != nullptr) {
300 node->next->previous = node->previous;
301 }
302 } else {
303 // First of sequence.
304 if (node->outer != nullptr) {
305 node->outer->inner = node->next;
306 } else {
307 top_loop_ = node->next;
308 }
309 if (node->next != nullptr) {
310 node->next->outer = node->outer;
311 node->next->previous = nullptr;
312 }
313 }
Aart Bik281c6812016-08-26 11:31:48 -0700314}
315
316void HLoopOptimization::TraverseLoopsInnerToOuter(LoopNode* node) {
317 for ( ; node != nullptr; node = node->next) {
Aart Bik6b69e0a2017-01-11 10:20:43 -0800318 // Visit inner loops first.
Aart Bikf8f5a162017-02-06 15:35:29 -0800319 uint32_t current_induction_simplification_count = induction_simplication_count_;
Aart Bik281c6812016-08-26 11:31:48 -0700320 if (node->inner != nullptr) {
321 TraverseLoopsInnerToOuter(node->inner);
322 }
Aart Bik6b69e0a2017-01-11 10:20:43 -0800323 // Recompute induction information of this loop if the induction
324 // of any inner loop has been simplified.
Aart Bik482095d2016-10-10 15:39:10 -0700325 if (current_induction_simplification_count != induction_simplication_count_) {
326 induction_range_.ReVisit(node->loop_info);
327 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800328 // Repeat simplifications in the loop-body until no more changes occur.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800329 // Note that since each simplification consists of eliminating code (without
330 // introducing new code), this process is always finite.
Aart Bikdf7822e2016-12-06 10:05:30 -0800331 do {
332 simplified_ = false;
Aart Bikdf7822e2016-12-06 10:05:30 -0800333 SimplifyInduction(node);
Aart Bik6b69e0a2017-01-11 10:20:43 -0800334 SimplifyBlocks(node);
Aart Bikdf7822e2016-12-06 10:05:30 -0800335 } while (simplified_);
Aart Bikf8f5a162017-02-06 15:35:29 -0800336 // Optimize inner loop.
Aart Bik9abf8942016-10-14 09:49:42 -0700337 if (node->inner == nullptr) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800338 OptimizeInnerLoop(node);
Aart Bik9abf8942016-10-14 09:49:42 -0700339 }
Aart Bik281c6812016-08-26 11:31:48 -0700340 }
341}
342
Aart Bikf8f5a162017-02-06 15:35:29 -0800343//
344// Optimization.
345//
346
Aart Bik281c6812016-08-26 11:31:48 -0700347void HLoopOptimization::SimplifyInduction(LoopNode* node) {
348 HBasicBlock* header = node->loop_info->GetHeader();
349 HBasicBlock* preheader = node->loop_info->GetPreHeader();
Aart Bik8c4a8542016-10-06 11:36:57 -0700350 // Scan the phis in the header to find opportunities to simplify an induction
351 // cycle that is only used outside the loop. Replace these uses, if any, with
352 // the last value and remove the induction cycle.
353 // Examples: for (int i = 0; x != null; i++) { .... no i .... }
354 // for (int i = 0; i < 10; i++, k++) { .... no k .... } return k;
Aart Bik281c6812016-08-26 11:31:48 -0700355 for (HInstructionIterator it(header->GetPhis()); !it.Done(); it.Advance()) {
356 HPhi* phi = it.Current()->AsPhi();
Aart Bikf8f5a162017-02-06 15:35:29 -0800357 iset_->clear(); // prepare phi induction
358 if (TrySetPhiInduction(phi, /*restrict_uses*/ true) &&
359 TryAssignLastValue(node->loop_info, phi, preheader, /*collect_loop_uses*/ false)) {
Aart Bik8c4a8542016-10-06 11:36:57 -0700360 for (HInstruction* i : *iset_) {
361 RemoveFromCycle(i);
Aart Bik281c6812016-08-26 11:31:48 -0700362 }
Aart Bikdf7822e2016-12-06 10:05:30 -0800363 simplified_ = true;
Aart Bik482095d2016-10-10 15:39:10 -0700364 }
365 }
366}
367
368void HLoopOptimization::SimplifyBlocks(LoopNode* node) {
Aart Bikdf7822e2016-12-06 10:05:30 -0800369 // Iterate over all basic blocks in the loop-body.
370 for (HBlocksInLoopIterator it(*node->loop_info); !it.Done(); it.Advance()) {
371 HBasicBlock* block = it.Current();
372 // Remove dead instructions from the loop-body.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800373 RemoveDeadInstructions(block->GetPhis());
374 RemoveDeadInstructions(block->GetInstructions());
Aart Bikdf7822e2016-12-06 10:05:30 -0800375 // Remove trivial control flow blocks from the loop-body.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800376 if (block->GetPredecessors().size() == 1 &&
377 block->GetSuccessors().size() == 1 &&
378 block->GetSingleSuccessor()->GetPredecessors().size() == 1) {
Aart Bikdf7822e2016-12-06 10:05:30 -0800379 simplified_ = true;
Aart Bik6b69e0a2017-01-11 10:20:43 -0800380 block->MergeWith(block->GetSingleSuccessor());
Aart Bikdf7822e2016-12-06 10:05:30 -0800381 } else if (block->GetSuccessors().size() == 2) {
382 // Trivial if block can be bypassed to either branch.
383 HBasicBlock* succ0 = block->GetSuccessors()[0];
384 HBasicBlock* succ1 = block->GetSuccessors()[1];
385 HBasicBlock* meet0 = nullptr;
386 HBasicBlock* meet1 = nullptr;
387 if (succ0 != succ1 &&
388 IsGotoBlock(succ0, &meet0) &&
389 IsGotoBlock(succ1, &meet1) &&
390 meet0 == meet1 && // meets again
391 meet0 != block && // no self-loop
392 meet0->GetPhis().IsEmpty()) { // not used for merging
393 simplified_ = true;
394 succ0->DisconnectAndDelete();
395 if (block->Dominates(meet0)) {
396 block->RemoveDominatedBlock(meet0);
397 succ1->AddDominatedBlock(meet0);
398 meet0->SetDominator(succ1);
Aart Bike3dedc52016-11-02 17:50:27 -0700399 }
Aart Bik482095d2016-10-10 15:39:10 -0700400 }
Aart Bik281c6812016-08-26 11:31:48 -0700401 }
Aart Bikdf7822e2016-12-06 10:05:30 -0800402 }
Aart Bik281c6812016-08-26 11:31:48 -0700403}
404
Aart Bikf8f5a162017-02-06 15:35:29 -0800405void HLoopOptimization::OptimizeInnerLoop(LoopNode* node) {
Aart Bik281c6812016-08-26 11:31:48 -0700406 HBasicBlock* header = node->loop_info->GetHeader();
407 HBasicBlock* preheader = node->loop_info->GetPreHeader();
Aart Bik9abf8942016-10-14 09:49:42 -0700408 // Ensure loop header logic is finite.
Aart Bikf8f5a162017-02-06 15:35:29 -0800409 int64_t trip_count = 0;
410 if (!induction_range_.IsFinite(node->loop_info, &trip_count)) {
411 return;
Aart Bik9abf8942016-10-14 09:49:42 -0700412 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800413
Aart Bik281c6812016-08-26 11:31:48 -0700414 // Ensure there is only a single loop-body (besides the header).
415 HBasicBlock* body = nullptr;
416 for (HBlocksInLoopIterator it(*node->loop_info); !it.Done(); it.Advance()) {
417 if (it.Current() != header) {
418 if (body != nullptr) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800419 return;
Aart Bik281c6812016-08-26 11:31:48 -0700420 }
421 body = it.Current();
422 }
423 }
424 // Ensure there is only a single exit point.
425 if (header->GetSuccessors().size() != 2) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800426 return;
Aart Bik281c6812016-08-26 11:31:48 -0700427 }
428 HBasicBlock* exit = (header->GetSuccessors()[0] == body)
429 ? header->GetSuccessors()[1]
430 : header->GetSuccessors()[0];
Aart Bik8c4a8542016-10-06 11:36:57 -0700431 // Ensure exit can only be reached by exiting loop.
Aart Bik281c6812016-08-26 11:31:48 -0700432 if (exit->GetPredecessors().size() != 1) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800433 return;
Aart Bik281c6812016-08-26 11:31:48 -0700434 }
Aart Bik6b69e0a2017-01-11 10:20:43 -0800435 // Detect either an empty loop (no side effects other than plain iteration) or
436 // a trivial loop (just iterating once). Replace subsequent index uses, if any,
437 // with the last value and remove the loop, possibly after unrolling its body.
438 HInstruction* phi = header->GetFirstPhi();
Aart Bikf8f5a162017-02-06 15:35:29 -0800439 iset_->clear(); // prepare phi induction
440 if (TrySetSimpleLoopHeader(header)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -0800441 bool is_empty = IsEmptyBody(body);
Aart Bikf8f5a162017-02-06 15:35:29 -0800442 if ((is_empty || trip_count == 1) &&
443 TryAssignLastValue(node->loop_info, phi, preheader, /*collect_loop_uses*/ true)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -0800444 if (!is_empty) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800445 // Unroll the loop-body, which sees initial value of the index.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800446 phi->ReplaceWith(phi->InputAt(0));
447 preheader->MergeInstructionsWith(body);
448 }
449 body->DisconnectAndDelete();
450 exit->RemovePredecessor(header);
451 header->RemoveSuccessor(exit);
452 header->RemoveDominatedBlock(exit);
453 header->DisconnectAndDelete();
454 preheader->AddSuccessor(exit);
Aart Bikf8f5a162017-02-06 15:35:29 -0800455 preheader->AddInstruction(new (global_allocator_) HGoto());
Aart Bik6b69e0a2017-01-11 10:20:43 -0800456 preheader->AddDominatedBlock(exit);
457 exit->SetDominator(preheader);
458 RemoveLoop(node); // update hierarchy
Aart Bikf8f5a162017-02-06 15:35:29 -0800459 return;
460 }
461 }
462
463 // Vectorize loop, if possible and valid.
464 if (kEnableVectorization) {
465 iset_->clear(); // prepare phi induction
466 if (TrySetSimpleLoopHeader(header) &&
467 CanVectorize(node, body, trip_count) &&
468 TryAssignLastValue(node->loop_info, phi, preheader, /*collect_loop_uses*/ true)) {
469 Vectorize(node, body, exit, trip_count);
470 graph_->SetHasSIMD(true); // flag SIMD usage
471 return;
472 }
473 }
474}
475
476//
477// Loop vectorization. The implementation is based on the book by Aart J.C. Bik:
478// "The Software Vectorization Handbook. Applying Multimedia Extensions for Maximum Performance."
479// Intel Press, June, 2004 (http://www.aartbik.com/).
480//
481
482bool HLoopOptimization::CanVectorize(LoopNode* node, HBasicBlock* block, int64_t trip_count) {
483 // Reset vector bookkeeping.
484 vector_length_ = 0;
485 vector_refs_->clear();
486 vector_runtime_test_a_ =
487 vector_runtime_test_b_= nullptr;
488
489 // Phis in the loop-body prevent vectorization.
490 if (!block->GetPhis().IsEmpty()) {
491 return false;
492 }
493
494 // Scan the loop-body, starting a right-hand-side tree traversal at each left-hand-side
495 // occurrence, which allows passing down attributes down the use tree.
496 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
497 if (!VectorizeDef(node, it.Current(), /*generate_code*/ false)) {
498 return false; // failure to vectorize a left-hand-side
499 }
500 }
501
502 // Heuristics. Does vectorization seem profitable?
503 // TODO: refine
504 if (vector_length_ == 0) {
505 return false; // nothing found
506 } else if (0 < trip_count && trip_count < vector_length_) {
507 return false; // insufficient iterations
508 }
509
510 // Data dependence analysis. Find each pair of references with same type, where
511 // at least one is a write. Each such pair denotes a possible data dependence.
512 // This analysis exploits the property that differently typed arrays cannot be
513 // aliased, as well as the property that references either point to the same
514 // array or to two completely disjoint arrays, i.e., no partial aliasing.
515 // Other than a few simply heuristics, no detailed subscript analysis is done.
516 for (auto i = vector_refs_->begin(); i != vector_refs_->end(); ++i) {
517 for (auto j = i; ++j != vector_refs_->end(); ) {
518 if (i->type == j->type && (i->lhs || j->lhs)) {
519 // Found same-typed a[i+x] vs. b[i+y], where at least one is a write.
520 HInstruction* a = i->base;
521 HInstruction* b = j->base;
522 HInstruction* x = i->offset;
523 HInstruction* y = j->offset;
524 if (a == b) {
525 // Found a[i+x] vs. a[i+y]. Accept if x == y (loop-independent data dependence).
526 // Conservatively assume a loop-carried data dependence otherwise, and reject.
527 if (x != y) {
528 return false;
529 }
530 } else {
531 // Found a[i+x] vs. b[i+y]. Accept if x == y (at worst loop-independent data dependence).
532 // Conservatively assume a potential loop-carried data dependence otherwise, avoided by
533 // generating an explicit a != b disambiguation runtime test on the two references.
534 if (x != y) {
535 // For now, we reject after one test to avoid excessive overhead.
536 if (vector_runtime_test_a_ != nullptr) {
537 return false;
538 }
539 vector_runtime_test_a_ = a;
540 vector_runtime_test_b_ = b;
541 }
542 }
543 }
544 }
545 }
546
547 // Success!
548 return true;
549}
550
551void HLoopOptimization::Vectorize(LoopNode* node,
552 HBasicBlock* block,
553 HBasicBlock* exit,
554 int64_t trip_count) {
555 Primitive::Type induc_type = Primitive::kPrimInt;
556 HBasicBlock* header = node->loop_info->GetHeader();
557 HBasicBlock* preheader = node->loop_info->GetPreHeader();
558
559 // A cleanup is needed for any unknown trip count or for a known trip count
560 // with remainder iterations after vectorization.
561 bool needs_cleanup = trip_count == 0 || (trip_count % vector_length_) != 0;
562
563 // Adjust vector bookkeeping.
564 iset_->clear(); // prepare phi induction
565 bool is_simple_loop_header = TrySetSimpleLoopHeader(header); // fills iset_
566 DCHECK(is_simple_loop_header);
567
568 // Generate preheader:
569 // stc = <trip-count>;
570 // vtc = stc - stc % VL;
571 HInstruction* stc = induction_range_.GenerateTripCount(node->loop_info, graph_, preheader);
572 HInstruction* vtc = stc;
573 if (needs_cleanup) {
574 DCHECK(IsPowerOfTwo(vector_length_));
575 HInstruction* rem = Insert(
576 preheader, new (global_allocator_) HAnd(induc_type,
577 stc,
578 graph_->GetIntConstant(vector_length_ - 1)));
579 vtc = Insert(preheader, new (global_allocator_) HSub(induc_type, stc, rem));
580 }
581
582 // Generate runtime disambiguation test:
583 // vtc = a != b ? vtc : 0;
584 if (vector_runtime_test_a_ != nullptr) {
585 HInstruction* rt = Insert(
586 preheader,
587 new (global_allocator_) HNotEqual(vector_runtime_test_a_, vector_runtime_test_b_));
588 vtc = Insert(preheader,
589 new (global_allocator_) HSelect(rt, vtc, graph_->GetIntConstant(0), kNoDexPc));
590 needs_cleanup = true;
591 }
592
593 // Generate vector loop:
594 // for (i = 0; i < vtc; i += VL)
595 // <vectorized-loop-body>
596 vector_mode_ = kVector;
597 GenerateNewLoop(node,
598 block,
599 graph_->TransformLoopForVectorization(header, block, exit),
600 graph_->GetIntConstant(0),
601 vtc,
602 graph_->GetIntConstant(vector_length_));
603 HLoopInformation* vloop = vector_header_->GetLoopInformation();
604
605 // Generate cleanup loop, if needed:
606 // for ( ; i < stc; i += 1)
607 // <loop-body>
608 if (needs_cleanup) {
609 vector_mode_ = kSequential;
610 GenerateNewLoop(node,
611 block,
612 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
613 vector_phi_,
614 stc,
615 graph_->GetIntConstant(1));
616 }
617
618 // Remove the original loop by disconnecting the body block
619 // and removing all instructions from the header.
620 block->DisconnectAndDelete();
621 while (!header->GetFirstInstruction()->IsGoto()) {
622 header->RemoveInstruction(header->GetFirstInstruction());
623 }
624 // Update loop hierarchy: the old header now resides in the
625 // same outer loop as the old preheader.
626 header->SetLoopInformation(preheader->GetLoopInformation()); // outward
627 node->loop_info = vloop;
628}
629
630void HLoopOptimization::GenerateNewLoop(LoopNode* node,
631 HBasicBlock* block,
632 HBasicBlock* new_preheader,
633 HInstruction* lo,
634 HInstruction* hi,
635 HInstruction* step) {
636 Primitive::Type induc_type = Primitive::kPrimInt;
637 // Prepare new loop.
638 vector_map_->clear();
639 vector_preheader_ = new_preheader,
640 vector_header_ = vector_preheader_->GetSingleSuccessor();
641 vector_body_ = vector_header_->GetSuccessors()[1];
642 vector_phi_ = new (global_allocator_) HPhi(global_allocator_,
643 kNoRegNumber,
644 0,
645 HPhi::ToPhiType(induc_type));
Aart Bikb07d1bc2017-04-05 10:03:15 -0700646 // Generate header and prepare body.
Aart Bikf8f5a162017-02-06 15:35:29 -0800647 // for (i = lo; i < hi; i += step)
648 // <loop-body>
649 HInstruction* cond = new (global_allocator_) HAboveOrEqual(vector_phi_, hi);
650 vector_header_->AddPhi(vector_phi_);
651 vector_header_->AddInstruction(cond);
652 vector_header_->AddInstruction(new (global_allocator_) HIf(cond));
Aart Bikf8f5a162017-02-06 15:35:29 -0800653 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
654 bool vectorized_def = VectorizeDef(node, it.Current(), /*generate_code*/ true);
655 DCHECK(vectorized_def);
656 }
Aart Bik24b905f2017-04-06 09:59:06 -0700657 // Generate body from the instruction map, but in original program order.
Aart Bikb07d1bc2017-04-05 10:03:15 -0700658 HEnvironment* env = vector_header_->GetFirstInstruction()->GetEnvironment();
Aart Bikf8f5a162017-02-06 15:35:29 -0800659 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
660 auto i = vector_map_->find(it.Current());
661 if (i != vector_map_->end() && !i->second->IsInBlock()) {
Aart Bik24b905f2017-04-06 09:59:06 -0700662 Insert(vector_body_, i->second);
663 // Deal with instructions that need an environment, such as the scalar intrinsics.
Aart Bikf8f5a162017-02-06 15:35:29 -0800664 if (i->second->NeedsEnvironment()) {
Aart Bikb07d1bc2017-04-05 10:03:15 -0700665 i->second->CopyEnvironmentFromWithLoopPhiAdjustment(env, vector_header_);
Aart Bikf8f5a162017-02-06 15:35:29 -0800666 }
667 }
668 }
669 // Finalize increment and phi.
670 HInstruction* inc = new (global_allocator_) HAdd(induc_type, vector_phi_, step);
671 vector_phi_->AddInput(lo);
672 vector_phi_->AddInput(Insert(vector_body_, inc));
673}
674
675// TODO: accept reductions at left-hand-side, mixed-type store idioms, etc.
676bool HLoopOptimization::VectorizeDef(LoopNode* node,
677 HInstruction* instruction,
678 bool generate_code) {
679 // Accept a left-hand-side array base[index] for
680 // (1) supported vector type,
681 // (2) loop-invariant base,
682 // (3) unit stride index,
683 // (4) vectorizable right-hand-side value.
684 uint64_t restrictions = kNone;
685 if (instruction->IsArraySet()) {
686 Primitive::Type type = instruction->AsArraySet()->GetComponentType();
687 HInstruction* base = instruction->InputAt(0);
688 HInstruction* index = instruction->InputAt(1);
689 HInstruction* value = instruction->InputAt(2);
690 HInstruction* offset = nullptr;
691 if (TrySetVectorType(type, &restrictions) &&
692 node->loop_info->IsDefinedOutOfTheLoop(base) &&
Aart Bikfa762962017-04-07 11:33:37 -0700693 induction_range_.IsUnitStride(instruction, index, &offset) &&
Aart Bikf8f5a162017-02-06 15:35:29 -0800694 VectorizeUse(node, value, generate_code, type, restrictions)) {
695 if (generate_code) {
696 GenerateVecSub(index, offset);
697 GenerateVecMem(instruction, vector_map_->Get(index), vector_map_->Get(value), type);
698 } else {
699 vector_refs_->insert(ArrayReference(base, offset, type, /*lhs*/ true));
700 }
Aart Bik6b69e0a2017-01-11 10:20:43 -0800701 return true;
702 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800703 return false;
704 }
705 // Branch back okay.
706 if (instruction->IsGoto()) {
707 return true;
708 }
709 // Otherwise accept only expressions with no effects outside the immediate loop-body.
710 // Note that actual uses are inspected during right-hand-side tree traversal.
711 return !IsUsedOutsideLoop(node->loop_info, instruction) && !instruction->DoesAnyWrite();
712}
713
714// TODO: more operations and intrinsics, detect saturation arithmetic, etc.
715bool HLoopOptimization::VectorizeUse(LoopNode* node,
716 HInstruction* instruction,
717 bool generate_code,
718 Primitive::Type type,
719 uint64_t restrictions) {
720 // Accept anything for which code has already been generated.
721 if (generate_code) {
722 if (vector_map_->find(instruction) != vector_map_->end()) {
723 return true;
724 }
725 }
726 // Continue the right-hand-side tree traversal, passing in proper
727 // types and vector restrictions along the way. During code generation,
728 // all new nodes are drawn from the global allocator.
729 if (node->loop_info->IsDefinedOutOfTheLoop(instruction)) {
730 // Accept invariant use, using scalar expansion.
731 if (generate_code) {
732 GenerateVecInv(instruction, type);
733 }
734 return true;
735 } else if (instruction->IsArrayGet()) {
Aart Bik3101e582017-04-11 10:15:44 -0700736 // Strings are different, with a different offset to the actual data
737 // and some compressed to save memory. For now, all cases are rejected
738 // to avoid the complexity.
739 if (instruction->AsArrayGet()->IsStringCharAt()) {
740 return false;
741 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800742 // Accept a right-hand-side array base[index] for
743 // (1) exact matching vector type,
744 // (2) loop-invariant base,
745 // (3) unit stride index,
746 // (4) vectorizable right-hand-side value.
747 HInstruction* base = instruction->InputAt(0);
748 HInstruction* index = instruction->InputAt(1);
749 HInstruction* offset = nullptr;
750 if (type == instruction->GetType() &&
751 node->loop_info->IsDefinedOutOfTheLoop(base) &&
Aart Bikfa762962017-04-07 11:33:37 -0700752 induction_range_.IsUnitStride(instruction, index, &offset)) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800753 if (generate_code) {
754 GenerateVecSub(index, offset);
755 GenerateVecMem(instruction, vector_map_->Get(index), nullptr, type);
756 } else {
757 vector_refs_->insert(ArrayReference(base, offset, type, /*lhs*/ false));
758 }
759 return true;
760 }
761 } else if (instruction->IsTypeConversion()) {
762 // Accept particular type conversions.
763 HTypeConversion* conversion = instruction->AsTypeConversion();
764 HInstruction* opa = conversion->InputAt(0);
765 Primitive::Type from = conversion->GetInputType();
766 Primitive::Type to = conversion->GetResultType();
767 if ((to == Primitive::kPrimByte ||
768 to == Primitive::kPrimChar ||
769 to == Primitive::kPrimShort) && from == Primitive::kPrimInt) {
770 // Accept a "narrowing" type conversion from a "wider" computation for
771 // (1) conversion into final required type,
772 // (2) vectorizable operand,
773 // (3) "wider" operations cannot bring in higher order bits.
774 if (to == type && VectorizeUse(node, opa, generate_code, type, restrictions | kNoHiBits)) {
775 if (generate_code) {
776 if (vector_mode_ == kVector) {
777 vector_map_->Put(instruction, vector_map_->Get(opa)); // operand pass-through
778 } else {
779 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
780 }
781 }
782 return true;
783 }
784 } else if (to == Primitive::kPrimFloat && from == Primitive::kPrimInt) {
785 DCHECK_EQ(to, type);
786 // Accept int to float conversion for
787 // (1) supported int,
788 // (2) vectorizable operand.
789 if (TrySetVectorType(from, &restrictions) &&
790 VectorizeUse(node, opa, generate_code, from, restrictions)) {
791 if (generate_code) {
792 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
793 }
794 return true;
795 }
796 }
797 return false;
798 } else if (instruction->IsNeg() || instruction->IsNot() || instruction->IsBooleanNot()) {
799 // Accept unary operator for vectorizable operand.
800 HInstruction* opa = instruction->InputAt(0);
801 if (VectorizeUse(node, opa, generate_code, type, restrictions)) {
802 if (generate_code) {
803 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
804 }
805 return true;
806 }
807 } else if (instruction->IsAdd() || instruction->IsSub() ||
808 instruction->IsMul() || instruction->IsDiv() ||
809 instruction->IsAnd() || instruction->IsOr() || instruction->IsXor()) {
810 // Deal with vector restrictions.
811 if ((instruction->IsMul() && HasVectorRestrictions(restrictions, kNoMul)) ||
812 (instruction->IsDiv() && HasVectorRestrictions(restrictions, kNoDiv))) {
813 return false;
814 }
815 // Accept binary operator for vectorizable operands.
816 HInstruction* opa = instruction->InputAt(0);
817 HInstruction* opb = instruction->InputAt(1);
818 if (VectorizeUse(node, opa, generate_code, type, restrictions) &&
819 VectorizeUse(node, opb, generate_code, type, restrictions)) {
820 if (generate_code) {
821 GenerateVecOp(instruction, vector_map_->Get(opa), vector_map_->Get(opb), type);
822 }
823 return true;
824 }
825 } else if (instruction->IsShl() || instruction->IsShr() || instruction->IsUShr()) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700826 // Recognize vectorization idioms.
827 if (VectorizeHalvingAddIdiom(node, instruction, generate_code, type, restrictions)) {
828 return true;
829 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800830 // Deal with vector restrictions.
831 if ((HasVectorRestrictions(restrictions, kNoShift)) ||
832 (instruction->IsShr() && HasVectorRestrictions(restrictions, kNoShr))) {
833 return false; // unsupported instruction
834 } else if ((instruction->IsShr() || instruction->IsUShr()) &&
835 HasVectorRestrictions(restrictions, kNoHiBits)) {
836 return false; // hibits may impact lobits; TODO: we can do better!
837 }
838 // Accept shift operator for vectorizable/invariant operands.
839 // TODO: accept symbolic, albeit loop invariant shift factors.
840 HInstruction* opa = instruction->InputAt(0);
841 HInstruction* opb = instruction->InputAt(1);
842 if (VectorizeUse(node, opa, generate_code, type, restrictions) && opb->IsIntConstant()) {
843 if (generate_code) {
844 // Make sure shift factor only looks at lower bits, as defined for sequential shifts.
845 // Note that even the narrower SIMD shifts do the right thing after that.
846 int32_t mask = (instruction->GetType() == Primitive::kPrimLong)
847 ? kMaxLongShiftDistance
848 : kMaxIntShiftDistance;
849 HInstruction* s = graph_->GetIntConstant(opb->AsIntConstant()->GetValue() & mask);
850 GenerateVecOp(instruction, vector_map_->Get(opa), s, type);
851 }
852 return true;
853 }
854 } else if (instruction->IsInvokeStaticOrDirect()) {
Aart Bik6daebeb2017-04-03 14:35:41 -0700855 // Accept particular intrinsics.
856 HInvokeStaticOrDirect* invoke = instruction->AsInvokeStaticOrDirect();
857 switch (invoke->GetIntrinsic()) {
858 case Intrinsics::kMathAbsInt:
859 case Intrinsics::kMathAbsLong:
860 case Intrinsics::kMathAbsFloat:
861 case Intrinsics::kMathAbsDouble: {
862 // Deal with vector restrictions.
863 if (HasVectorRestrictions(restrictions, kNoAbs) ||
864 HasVectorRestrictions(restrictions, kNoHiBits)) {
865 // TODO: we can do better for some hibits cases.
866 return false;
867 }
868 // Accept ABS(x) for vectorizable operand.
869 HInstruction* opa = instruction->InputAt(0);
870 if (VectorizeUse(node, opa, generate_code, type, restrictions)) {
871 if (generate_code) {
872 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
873 }
874 return true;
875 }
876 return false;
877 }
878 default:
879 return false;
880 } // switch
Aart Bik281c6812016-08-26 11:31:48 -0700881 }
Aart Bik6b69e0a2017-01-11 10:20:43 -0800882 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700883}
884
Aart Bikf8f5a162017-02-06 15:35:29 -0800885bool HLoopOptimization::TrySetVectorType(Primitive::Type type, uint64_t* restrictions) {
886 const InstructionSetFeatures* features = compiler_driver_->GetInstructionSetFeatures();
887 switch (compiler_driver_->GetInstructionSet()) {
888 case kArm:
889 case kThumb2:
890 return false;
891 case kArm64:
892 // Allow vectorization for all ARM devices, because Android assumes that
Artem Serovd4bccf12017-04-03 18:47:32 +0100893 // ARMv8 AArch64 always supports advanced SIMD.
Aart Bikf8f5a162017-02-06 15:35:29 -0800894 switch (type) {
895 case Primitive::kPrimBoolean:
896 case Primitive::kPrimByte:
Aart Bik6daebeb2017-04-03 14:35:41 -0700897 *restrictions |= kNoDiv | kNoAbs;
Artem Serovd4bccf12017-04-03 18:47:32 +0100898 return TrySetVectorLength(16);
Aart Bikf8f5a162017-02-06 15:35:29 -0800899 case Primitive::kPrimChar:
900 case Primitive::kPrimShort:
Aart Bik6daebeb2017-04-03 14:35:41 -0700901 *restrictions |= kNoDiv | kNoAbs;
Artem Serovd4bccf12017-04-03 18:47:32 +0100902 return TrySetVectorLength(8);
Aart Bikf8f5a162017-02-06 15:35:29 -0800903 case Primitive::kPrimInt:
904 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +0100905 return TrySetVectorLength(4);
Artem Serovb31f91f2017-04-05 11:31:19 +0100906 case Primitive::kPrimLong:
907 *restrictions |= kNoDiv | kNoMul;
Aart Bikf8f5a162017-02-06 15:35:29 -0800908 return TrySetVectorLength(2);
909 case Primitive::kPrimFloat:
Artem Serovd4bccf12017-04-03 18:47:32 +0100910 return TrySetVectorLength(4);
Artem Serovb31f91f2017-04-05 11:31:19 +0100911 case Primitive::kPrimDouble:
Aart Bikf8f5a162017-02-06 15:35:29 -0800912 return TrySetVectorLength(2);
913 default:
914 return false;
915 }
916 case kX86:
917 case kX86_64:
918 // Allow vectorization for SSE4-enabled X86 devices only (128-bit vectors).
919 if (features->AsX86InstructionSetFeatures()->HasSSE4_1()) {
920 switch (type) {
921 case Primitive::kPrimBoolean:
922 case Primitive::kPrimByte:
Aart Bikf3e61ee2017-04-12 17:09:20 -0700923 *restrictions |= kNoMul | kNoDiv | kNoShift | kNoAbs | kNoSignedHAdd | kNoUnroundedHAdd;
Aart Bikf8f5a162017-02-06 15:35:29 -0800924 return TrySetVectorLength(16);
925 case Primitive::kPrimChar:
926 case Primitive::kPrimShort:
Aart Bikf3e61ee2017-04-12 17:09:20 -0700927 *restrictions |= kNoDiv | kNoAbs | kNoSignedHAdd | kNoUnroundedHAdd;
Aart Bikf8f5a162017-02-06 15:35:29 -0800928 return TrySetVectorLength(8);
929 case Primitive::kPrimInt:
930 *restrictions |= kNoDiv;
931 return TrySetVectorLength(4);
932 case Primitive::kPrimLong:
Aart Bik6daebeb2017-04-03 14:35:41 -0700933 *restrictions |= kNoMul | kNoDiv | kNoShr | kNoAbs;
Aart Bikf8f5a162017-02-06 15:35:29 -0800934 return TrySetVectorLength(2);
935 case Primitive::kPrimFloat:
936 return TrySetVectorLength(4);
937 case Primitive::kPrimDouble:
938 return TrySetVectorLength(2);
939 default:
940 break;
941 } // switch type
942 }
943 return false;
944 case kMips:
945 case kMips64:
946 // TODO: implement MIPS SIMD.
947 return false;
948 default:
949 return false;
950 } // switch instruction set
951}
952
953bool HLoopOptimization::TrySetVectorLength(uint32_t length) {
954 DCHECK(IsPowerOfTwo(length) && length >= 2u);
955 // First time set?
956 if (vector_length_ == 0) {
957 vector_length_ = length;
958 }
959 // Different types are acceptable within a loop-body, as long as all the corresponding vector
960 // lengths match exactly to obtain a uniform traversal through the vector iteration space
961 // (idiomatic exceptions to this rule can be handled by further unrolling sub-expressions).
962 return vector_length_ == length;
963}
964
965void HLoopOptimization::GenerateVecInv(HInstruction* org, Primitive::Type type) {
966 if (vector_map_->find(org) == vector_map_->end()) {
967 // In scalar code, just use a self pass-through for scalar invariants
968 // (viz. expression remains itself).
969 if (vector_mode_ == kSequential) {
970 vector_map_->Put(org, org);
971 return;
972 }
973 // In vector code, explicit scalar expansion is needed.
974 HInstruction* vector = new (global_allocator_) HVecReplicateScalar(
975 global_allocator_, org, type, vector_length_);
976 vector_map_->Put(org, Insert(vector_preheader_, vector));
977 }
978}
979
980void HLoopOptimization::GenerateVecSub(HInstruction* org, HInstruction* offset) {
981 if (vector_map_->find(org) == vector_map_->end()) {
982 HInstruction* subscript = vector_phi_;
983 if (offset != nullptr) {
984 subscript = new (global_allocator_) HAdd(Primitive::kPrimInt, subscript, offset);
985 if (org->IsPhi()) {
986 Insert(vector_body_, subscript); // lacks layout placeholder
987 }
988 }
989 vector_map_->Put(org, subscript);
990 }
991}
992
993void HLoopOptimization::GenerateVecMem(HInstruction* org,
994 HInstruction* opa,
995 HInstruction* opb,
996 Primitive::Type type) {
997 HInstruction* vector = nullptr;
998 if (vector_mode_ == kVector) {
999 // Vector store or load.
1000 if (opb != nullptr) {
1001 vector = new (global_allocator_) HVecStore(
1002 global_allocator_, org->InputAt(0), opa, opb, type, vector_length_);
1003 } else {
Aart Bikdb14fcf2017-04-25 15:53:58 -07001004 bool is_string_char_at = org->AsArrayGet()->IsStringCharAt();
Aart Bikf8f5a162017-02-06 15:35:29 -08001005 vector = new (global_allocator_) HVecLoad(
Aart Bikdb14fcf2017-04-25 15:53:58 -07001006 global_allocator_, org->InputAt(0), opa, type, vector_length_, is_string_char_at);
Aart Bikf8f5a162017-02-06 15:35:29 -08001007 }
1008 } else {
1009 // Scalar store or load.
1010 DCHECK(vector_mode_ == kSequential);
1011 if (opb != nullptr) {
1012 vector = new (global_allocator_) HArraySet(org->InputAt(0), opa, opb, type, kNoDexPc);
1013 } else {
Aart Bikdb14fcf2017-04-25 15:53:58 -07001014 bool is_string_char_at = org->AsArrayGet()->IsStringCharAt();
1015 vector = new (global_allocator_) HArrayGet(
1016 org->InputAt(0), opa, type, kNoDexPc, is_string_char_at);
Aart Bikf8f5a162017-02-06 15:35:29 -08001017 }
1018 }
1019 vector_map_->Put(org, vector);
1020}
1021
1022#define GENERATE_VEC(x, y) \
1023 if (vector_mode_ == kVector) { \
1024 vector = (x); \
1025 } else { \
1026 DCHECK(vector_mode_ == kSequential); \
1027 vector = (y); \
1028 } \
1029 break;
1030
1031void HLoopOptimization::GenerateVecOp(HInstruction* org,
1032 HInstruction* opa,
1033 HInstruction* opb,
1034 Primitive::Type type) {
1035 if (vector_mode_ == kSequential) {
1036 // Scalar code follows implicit integral promotion.
1037 if (type == Primitive::kPrimBoolean ||
1038 type == Primitive::kPrimByte ||
1039 type == Primitive::kPrimChar ||
1040 type == Primitive::kPrimShort) {
1041 type = Primitive::kPrimInt;
1042 }
1043 }
1044 HInstruction* vector = nullptr;
1045 switch (org->GetKind()) {
1046 case HInstruction::kNeg:
1047 DCHECK(opb == nullptr);
1048 GENERATE_VEC(
1049 new (global_allocator_) HVecNeg(global_allocator_, opa, type, vector_length_),
1050 new (global_allocator_) HNeg(type, opa));
1051 case HInstruction::kNot:
1052 DCHECK(opb == nullptr);
1053 GENERATE_VEC(
1054 new (global_allocator_) HVecNot(global_allocator_, opa, type, vector_length_),
1055 new (global_allocator_) HNot(type, opa));
1056 case HInstruction::kBooleanNot:
1057 DCHECK(opb == nullptr);
1058 GENERATE_VEC(
1059 new (global_allocator_) HVecNot(global_allocator_, opa, type, vector_length_),
1060 new (global_allocator_) HBooleanNot(opa));
1061 case HInstruction::kTypeConversion:
1062 DCHECK(opb == nullptr);
1063 GENERATE_VEC(
1064 new (global_allocator_) HVecCnv(global_allocator_, opa, type, vector_length_),
1065 new (global_allocator_) HTypeConversion(type, opa, kNoDexPc));
1066 case HInstruction::kAdd:
1067 GENERATE_VEC(
1068 new (global_allocator_) HVecAdd(global_allocator_, opa, opb, type, vector_length_),
1069 new (global_allocator_) HAdd(type, opa, opb));
1070 case HInstruction::kSub:
1071 GENERATE_VEC(
1072 new (global_allocator_) HVecSub(global_allocator_, opa, opb, type, vector_length_),
1073 new (global_allocator_) HSub(type, opa, opb));
1074 case HInstruction::kMul:
1075 GENERATE_VEC(
1076 new (global_allocator_) HVecMul(global_allocator_, opa, opb, type, vector_length_),
1077 new (global_allocator_) HMul(type, opa, opb));
1078 case HInstruction::kDiv:
1079 GENERATE_VEC(
1080 new (global_allocator_) HVecDiv(global_allocator_, opa, opb, type, vector_length_),
1081 new (global_allocator_) HDiv(type, opa, opb, kNoDexPc));
1082 case HInstruction::kAnd:
1083 GENERATE_VEC(
1084 new (global_allocator_) HVecAnd(global_allocator_, opa, opb, type, vector_length_),
1085 new (global_allocator_) HAnd(type, opa, opb));
1086 case HInstruction::kOr:
1087 GENERATE_VEC(
1088 new (global_allocator_) HVecOr(global_allocator_, opa, opb, type, vector_length_),
1089 new (global_allocator_) HOr(type, opa, opb));
1090 case HInstruction::kXor:
1091 GENERATE_VEC(
1092 new (global_allocator_) HVecXor(global_allocator_, opa, opb, type, vector_length_),
1093 new (global_allocator_) HXor(type, opa, opb));
1094 case HInstruction::kShl:
1095 GENERATE_VEC(
1096 new (global_allocator_) HVecShl(global_allocator_, opa, opb, type, vector_length_),
1097 new (global_allocator_) HShl(type, opa, opb));
1098 case HInstruction::kShr:
1099 GENERATE_VEC(
1100 new (global_allocator_) HVecShr(global_allocator_, opa, opb, type, vector_length_),
1101 new (global_allocator_) HShr(type, opa, opb));
1102 case HInstruction::kUShr:
1103 GENERATE_VEC(
1104 new (global_allocator_) HVecUShr(global_allocator_, opa, opb, type, vector_length_),
1105 new (global_allocator_) HUShr(type, opa, opb));
1106 case HInstruction::kInvokeStaticOrDirect: {
Aart Bik6daebeb2017-04-03 14:35:41 -07001107 HInvokeStaticOrDirect* invoke = org->AsInvokeStaticOrDirect();
1108 if (vector_mode_ == kVector) {
1109 switch (invoke->GetIntrinsic()) {
1110 case Intrinsics::kMathAbsInt:
1111 case Intrinsics::kMathAbsLong:
1112 case Intrinsics::kMathAbsFloat:
1113 case Intrinsics::kMathAbsDouble:
1114 DCHECK(opb == nullptr);
1115 vector = new (global_allocator_) HVecAbs(global_allocator_, opa, type, vector_length_);
1116 break;
1117 default:
1118 LOG(FATAL) << "Unsupported SIMD intrinsic";
1119 UNREACHABLE();
1120 } // switch invoke
1121 } else {
Aart Bik24b905f2017-04-06 09:59:06 -07001122 // In scalar code, simply clone the method invoke, and replace its operands with the
1123 // corresponding new scalar instructions in the loop. The instruction will get an
1124 // environment while being inserted from the instruction map in original program order.
Aart Bik6daebeb2017-04-03 14:35:41 -07001125 DCHECK(vector_mode_ == kSequential);
1126 HInvokeStaticOrDirect* new_invoke = new (global_allocator_) HInvokeStaticOrDirect(
1127 global_allocator_,
1128 invoke->GetNumberOfArguments(),
1129 invoke->GetType(),
1130 invoke->GetDexPc(),
1131 invoke->GetDexMethodIndex(),
1132 invoke->GetResolvedMethod(),
1133 invoke->GetDispatchInfo(),
1134 invoke->GetInvokeType(),
1135 invoke->GetTargetMethod(),
1136 invoke->GetClinitCheckRequirement());
1137 HInputsRef inputs = invoke->GetInputs();
1138 for (size_t index = 0; index < inputs.size(); ++index) {
1139 new_invoke->SetArgumentAt(index, vector_map_->Get(inputs[index]));
1140 }
Aart Bik98990262017-04-10 13:15:57 -07001141 new_invoke->SetIntrinsic(invoke->GetIntrinsic(),
1142 kNeedsEnvironmentOrCache,
1143 kNoSideEffects,
1144 kNoThrow);
Aart Bik6daebeb2017-04-03 14:35:41 -07001145 vector = new_invoke;
1146 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001147 break;
1148 }
1149 default:
1150 break;
1151 } // switch
1152 CHECK(vector != nullptr) << "Unsupported SIMD operator";
1153 vector_map_->Put(org, vector);
1154}
1155
1156#undef GENERATE_VEC
1157
1158//
Aart Bikf3e61ee2017-04-12 17:09:20 -07001159// Vectorization idioms.
1160//
1161
1162// Method recognizes the following idioms:
1163// rounding halving add (a + b + 1) >> 1 for unsigned/signed operands a, b
1164// regular halving add (a + b) >> 1 for unsigned/signed operands a, b
1165// Provided that the operands are promoted to a wider form to do the arithmetic and
1166// then cast back to narrower form, the idioms can be mapped into efficient SIMD
1167// implementation that operates directly in narrower form (plus one extra bit).
1168// TODO: current version recognizes implicit byte/short/char widening only;
1169// explicit widening from int to long could be added later.
1170bool HLoopOptimization::VectorizeHalvingAddIdiom(LoopNode* node,
1171 HInstruction* instruction,
1172 bool generate_code,
1173 Primitive::Type type,
1174 uint64_t restrictions) {
1175 // Test for top level arithmetic shift right x >> 1 or logical shift right x >>> 1
1176 // (note whether the sign bit in higher precision is shifted in has no effect
1177 // on the narrow precision computed by the idiom).
1178 int64_t value = 0;
1179 if ((instruction->IsShr() ||
1180 instruction->IsUShr()) &&
1181 IsInt64AndGet(instruction->InputAt(1), &value) && value == 1) {
1182 //
1183 // TODO: make following code less sensitive to associativity and commutativity differences.
1184 //
1185 HInstruction* x = instruction->InputAt(0);
1186 // Test for an optional rounding part (x + 1) >> 1.
1187 bool is_rounded = false;
1188 if (x->IsAdd() && IsInt64AndGet(x->InputAt(1), &value) && value == 1) {
1189 x = x->InputAt(0);
1190 is_rounded = true;
1191 }
1192 // Test for a core addition (a + b) >> 1 (possibly rounded), either unsigned or signed.
1193 if (x->IsAdd()) {
1194 HInstruction* a = x->InputAt(0);
1195 HInstruction* b = x->InputAt(1);
1196 HInstruction* r = nullptr;
1197 HInstruction* s = nullptr;
1198 bool is_unsigned = false;
1199 if (IsZeroExtensionAndGet(a, type, &r) && IsZeroExtensionAndGet(b, type, &s)) {
1200 is_unsigned = true;
1201 } else if (IsSignExtensionAndGet(a, type, &r) && IsSignExtensionAndGet(b, type, &s)) {
1202 is_unsigned = false;
1203 } else {
1204 return false;
1205 }
1206 // Deal with vector restrictions.
1207 if ((!is_unsigned && HasVectorRestrictions(restrictions, kNoSignedHAdd)) ||
1208 (!is_rounded && HasVectorRestrictions(restrictions, kNoUnroundedHAdd))) {
1209 return false;
1210 }
1211 // Accept recognized halving add for vectorizable operands. Vectorized code uses the
1212 // shorthand idiomatic operation. Sequential code uses the original scalar expressions.
1213 DCHECK(r != nullptr && s != nullptr);
1214 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
1215 VectorizeUse(node, s, generate_code, type, restrictions)) {
1216 if (generate_code) {
1217 if (vector_mode_ == kVector) {
1218 vector_map_->Put(instruction, new (global_allocator_) HVecHalvingAdd(
1219 global_allocator_,
1220 vector_map_->Get(r),
1221 vector_map_->Get(s),
1222 type,
1223 vector_length_,
1224 is_unsigned,
1225 is_rounded));
1226 } else {
1227 VectorizeUse(node, instruction->InputAt(0), generate_code, type, restrictions);
1228 VectorizeUse(node, instruction->InputAt(1), generate_code, type, restrictions);
1229 GenerateVecOp(instruction,
1230 vector_map_->Get(instruction->InputAt(0)),
1231 vector_map_->Get(instruction->InputAt(1)),
1232 type);
1233 }
1234 }
1235 return true;
1236 }
1237 }
1238 }
1239 return false;
1240}
1241
1242//
Aart Bikf8f5a162017-02-06 15:35:29 -08001243// Helpers.
1244//
1245
1246bool HLoopOptimization::TrySetPhiInduction(HPhi* phi, bool restrict_uses) {
1247 DCHECK(iset_->empty());
Aart Bikcc42be02016-10-20 16:14:16 -07001248 ArenaSet<HInstruction*>* set = induction_range_.LookupCycle(phi);
1249 if (set != nullptr) {
1250 for (HInstruction* i : *set) {
Aart Bike3dedc52016-11-02 17:50:27 -07001251 // Check that, other than instructions that are no longer in the graph (removed earlier)
Aart Bikf8f5a162017-02-06 15:35:29 -08001252 // each instruction is removable and, when restrict uses are requested, other than for phi,
1253 // all uses are contained within the cycle.
Aart Bike3dedc52016-11-02 17:50:27 -07001254 if (!i->IsInBlock()) {
1255 continue;
1256 } else if (!i->IsRemovable()) {
1257 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001258 } else if (i != phi && restrict_uses) {
Aart Bikcc42be02016-10-20 16:14:16 -07001259 for (const HUseListNode<HInstruction*>& use : i->GetUses()) {
1260 if (set->find(use.GetUser()) == set->end()) {
1261 return false;
1262 }
1263 }
1264 }
Aart Bike3dedc52016-11-02 17:50:27 -07001265 iset_->insert(i); // copy
Aart Bikcc42be02016-10-20 16:14:16 -07001266 }
Aart Bikcc42be02016-10-20 16:14:16 -07001267 return true;
1268 }
1269 return false;
1270}
1271
1272// Find: phi: Phi(init, addsub)
1273// s: SuspendCheck
1274// c: Condition(phi, bound)
1275// i: If(c)
1276// TODO: Find a less pattern matching approach?
Aart Bikf8f5a162017-02-06 15:35:29 -08001277bool HLoopOptimization::TrySetSimpleLoopHeader(HBasicBlock* block) {
Aart Bikcc42be02016-10-20 16:14:16 -07001278 DCHECK(iset_->empty());
1279 HInstruction* phi = block->GetFirstPhi();
Aart Bikf8f5a162017-02-06 15:35:29 -08001280 if (phi != nullptr &&
1281 phi->GetNext() == nullptr &&
1282 TrySetPhiInduction(phi->AsPhi(), /*restrict_uses*/ false)) {
Aart Bikcc42be02016-10-20 16:14:16 -07001283 HInstruction* s = block->GetFirstInstruction();
1284 if (s != nullptr && s->IsSuspendCheck()) {
1285 HInstruction* c = s->GetNext();
Aart Bikd86c0852017-04-14 12:00:15 -07001286 if (c != nullptr &&
1287 c->IsCondition() &&
1288 c->GetUses().HasExactlyOneElement() && // only used for termination
1289 !c->HasEnvironmentUses()) { // unlikely, but not impossible
Aart Bikcc42be02016-10-20 16:14:16 -07001290 HInstruction* i = c->GetNext();
1291 if (i != nullptr && i->IsIf() && i->InputAt(0) == c) {
1292 iset_->insert(c);
1293 iset_->insert(s);
1294 return true;
1295 }
1296 }
1297 }
1298 }
1299 return false;
1300}
1301
1302bool HLoopOptimization::IsEmptyBody(HBasicBlock* block) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001303 if (!block->GetPhis().IsEmpty()) {
1304 return false;
1305 }
1306 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
1307 HInstruction* instruction = it.Current();
1308 if (!instruction->IsGoto() && iset_->find(instruction) == iset_->end()) {
1309 return false;
Aart Bikcc42be02016-10-20 16:14:16 -07001310 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001311 }
1312 return true;
1313}
1314
1315bool HLoopOptimization::IsUsedOutsideLoop(HLoopInformation* loop_info,
1316 HInstruction* instruction) {
1317 for (const HUseListNode<HInstruction*>& use : instruction->GetUses()) {
1318 if (use.GetUser()->GetBlock()->GetLoopInformation() != loop_info) {
1319 return true;
1320 }
Aart Bikcc42be02016-10-20 16:14:16 -07001321 }
1322 return false;
1323}
1324
Aart Bik482095d2016-10-10 15:39:10 -07001325bool HLoopOptimization::IsOnlyUsedAfterLoop(HLoopInformation* loop_info,
Aart Bik8c4a8542016-10-06 11:36:57 -07001326 HInstruction* instruction,
Aart Bik6b69e0a2017-01-11 10:20:43 -08001327 bool collect_loop_uses,
Aart Bik8c4a8542016-10-06 11:36:57 -07001328 /*out*/ int32_t* use_count) {
1329 for (const HUseListNode<HInstruction*>& use : instruction->GetUses()) {
1330 HInstruction* user = use.GetUser();
1331 if (iset_->find(user) == iset_->end()) { // not excluded?
1332 HLoopInformation* other_loop_info = user->GetBlock()->GetLoopInformation();
Aart Bik482095d2016-10-10 15:39:10 -07001333 if (other_loop_info != nullptr && other_loop_info->IsIn(*loop_info)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -08001334 // If collect_loop_uses is set, simply keep adding those uses to the set.
1335 // Otherwise, reject uses inside the loop that were not already in the set.
1336 if (collect_loop_uses) {
1337 iset_->insert(user);
1338 continue;
1339 }
Aart Bik8c4a8542016-10-06 11:36:57 -07001340 return false;
1341 }
1342 ++*use_count;
1343 }
1344 }
1345 return true;
1346}
1347
Aart Bik807868e2016-11-03 17:51:43 -07001348bool HLoopOptimization::TryReplaceWithLastValue(HInstruction* instruction, HBasicBlock* block) {
1349 // Try to replace outside uses with the last value. Environment uses can consume this
1350 // value too, since any first true use is outside the loop (although this may imply
1351 // that de-opting may look "ahead" a bit on the phi value). If there are only environment
1352 // uses, the value is dropped altogether, since the computations have no effect.
1353 if (induction_range_.CanGenerateLastValue(instruction)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -08001354 HInstruction* replacement = induction_range_.GenerateLastValue(instruction, graph_, block);
1355 const HUseList<HInstruction*>& uses = instruction->GetUses();
1356 for (auto it = uses.begin(), end = uses.end(); it != end;) {
1357 HInstruction* user = it->GetUser();
1358 size_t index = it->GetIndex();
1359 ++it; // increment before replacing
1360 if (iset_->find(user) == iset_->end()) { // not excluded?
1361 user->ReplaceInput(replacement, index);
1362 induction_range_.Replace(user, instruction, replacement); // update induction
1363 }
1364 }
1365 const HUseList<HEnvironment*>& env_uses = instruction->GetEnvUses();
1366 for (auto it = env_uses.begin(), end = env_uses.end(); it != end;) {
1367 HEnvironment* user = it->GetUser();
1368 size_t index = it->GetIndex();
1369 ++it; // increment before replacing
1370 if (iset_->find(user->GetHolder()) == iset_->end()) { // not excluded?
1371 user->RemoveAsUserOfInput(index);
1372 user->SetRawEnvAt(index, replacement);
1373 replacement->AddEnvUseAt(user, index);
1374 }
1375 }
1376 induction_simplication_count_++;
Aart Bik807868e2016-11-03 17:51:43 -07001377 return true;
Aart Bik8c4a8542016-10-06 11:36:57 -07001378 }
Aart Bik807868e2016-11-03 17:51:43 -07001379 return false;
Aart Bik8c4a8542016-10-06 11:36:57 -07001380}
1381
Aart Bikf8f5a162017-02-06 15:35:29 -08001382bool HLoopOptimization::TryAssignLastValue(HLoopInformation* loop_info,
1383 HInstruction* instruction,
1384 HBasicBlock* block,
1385 bool collect_loop_uses) {
1386 // Assigning the last value is always successful if there are no uses.
1387 // Otherwise, it succeeds in a no early-exit loop by generating the
1388 // proper last value assignment.
1389 int32_t use_count = 0;
1390 return IsOnlyUsedAfterLoop(loop_info, instruction, collect_loop_uses, &use_count) &&
1391 (use_count == 0 ||
1392 (!IsEarlyExit(loop_info) && TryReplaceWithLastValue(instruction, block)));
1393}
1394
Aart Bik6b69e0a2017-01-11 10:20:43 -08001395void HLoopOptimization::RemoveDeadInstructions(const HInstructionList& list) {
1396 for (HBackwardInstructionIterator i(list); !i.Done(); i.Advance()) {
1397 HInstruction* instruction = i.Current();
1398 if (instruction->IsDeadAndRemovable()) {
1399 simplified_ = true;
1400 instruction->GetBlock()->RemoveInstructionOrPhi(instruction);
1401 }
1402 }
1403}
1404
Aart Bik281c6812016-08-26 11:31:48 -07001405} // namespace art