blob: 027ba7741c31f4304d935c93bc4f10999ca049f5 [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/arm/instruction_set_features_arm.h"
20#include "arch/arm64/instruction_set_features_arm64.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070021#include "arch/instruction_set.h"
Aart Bikf8f5a162017-02-06 15:35:29 -080022#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 Bik14a68b42017-06-08 14:06:58 -070034// All current SIMD targets want 16-byte alignment.
35static constexpr size_t kAlignedBase = 16;
36
Aart Bik9abf8942016-10-14 09:49:42 -070037// Remove the instruction from the graph. A bit more elaborate than the usual
38// instruction removal, since there may be a cycle in the use structure.
Aart Bik281c6812016-08-26 11:31:48 -070039static void RemoveFromCycle(HInstruction* instruction) {
Aart Bik281c6812016-08-26 11:31:48 -070040 instruction->RemoveAsUserOfAllInputs();
41 instruction->RemoveEnvironmentUsers();
42 instruction->GetBlock()->RemoveInstructionOrPhi(instruction, /*ensure_safety=*/ false);
Artem Serov21c7e6f2017-07-27 16:04:42 +010043 RemoveEnvironmentUses(instruction);
44 ResetEnvironmentInputRecords(instruction);
Aart Bik281c6812016-08-26 11:31:48 -070045}
46
Aart Bik807868e2016-11-03 17:51:43 -070047// Detect a goto block and sets succ to the single successor.
Aart Bike3dedc52016-11-02 17:50:27 -070048static bool IsGotoBlock(HBasicBlock* block, /*out*/ HBasicBlock** succ) {
49 if (block->GetPredecessors().size() == 1 &&
50 block->GetSuccessors().size() == 1 &&
51 block->IsSingleGoto()) {
52 *succ = block->GetSingleSuccessor();
53 return true;
54 }
55 return false;
56}
57
Aart Bik807868e2016-11-03 17:51:43 -070058// Detect an early exit loop.
59static bool IsEarlyExit(HLoopInformation* loop_info) {
60 HBlocksInLoopReversePostOrderIterator it_loop(*loop_info);
61 for (it_loop.Advance(); !it_loop.Done(); it_loop.Advance()) {
62 for (HBasicBlock* successor : it_loop.Current()->GetSuccessors()) {
63 if (!loop_info->Contains(*successor)) {
64 return true;
65 }
66 }
67 }
68 return false;
69}
70
Aart Bikf3e61ee2017-04-12 17:09:20 -070071// Detect a sign extension from the given type. Returns the promoted operand on success.
72static bool IsSignExtensionAndGet(HInstruction* instruction,
73 Primitive::Type type,
74 /*out*/ HInstruction** operand) {
75 // Accept any already wider constant that would be handled properly by sign
76 // extension when represented in the *width* of the given narrower data type
77 // (the fact that char normally zero extends does not matter here).
78 int64_t value = 0;
Aart Bik50e20d52017-05-05 14:07:29 -070079 if (IsInt64AndGet(instruction, /*out*/ &value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -070080 switch (type) {
81 case Primitive::kPrimByte:
82 if (std::numeric_limits<int8_t>::min() <= value &&
83 std::numeric_limits<int8_t>::max() >= value) {
84 *operand = instruction;
85 return true;
86 }
87 return false;
88 case Primitive::kPrimChar:
89 case Primitive::kPrimShort:
90 if (std::numeric_limits<int16_t>::min() <= value &&
91 std::numeric_limits<int16_t>::max() <= value) {
92 *operand = instruction;
93 return true;
94 }
95 return false;
96 default:
97 return false;
98 }
99 }
100 // An implicit widening conversion of a signed integer to an integral type sign-extends
101 // the two's-complement representation of the integer value to fill the wider format.
102 if (instruction->GetType() == type && (instruction->IsArrayGet() ||
103 instruction->IsStaticFieldGet() ||
104 instruction->IsInstanceFieldGet())) {
105 switch (type) {
106 case Primitive::kPrimByte:
107 case Primitive::kPrimShort:
108 *operand = instruction;
109 return true;
110 default:
111 return false;
112 }
113 }
114 // TODO: perhaps explicit conversions later too?
115 // (this may return something different from instruction)
116 return false;
117}
118
119// Detect a zero extension from the given type. Returns the promoted operand on success.
120static bool IsZeroExtensionAndGet(HInstruction* instruction,
121 Primitive::Type type,
122 /*out*/ HInstruction** operand) {
123 // Accept any already wider constant that would be handled properly by zero
124 // extension when represented in the *width* of the given narrower data type
125 // (the fact that byte/short normally sign extend does not matter here).
126 int64_t value = 0;
Aart Bik50e20d52017-05-05 14:07:29 -0700127 if (IsInt64AndGet(instruction, /*out*/ &value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700128 switch (type) {
129 case Primitive::kPrimByte:
130 if (std::numeric_limits<uint8_t>::min() <= value &&
131 std::numeric_limits<uint8_t>::max() >= value) {
132 *operand = instruction;
133 return true;
134 }
135 return false;
136 case Primitive::kPrimChar:
137 case Primitive::kPrimShort:
138 if (std::numeric_limits<uint16_t>::min() <= value &&
139 std::numeric_limits<uint16_t>::max() <= value) {
140 *operand = instruction;
141 return true;
142 }
143 return false;
144 default:
145 return false;
146 }
147 }
148 // An implicit widening conversion of a char to an integral type zero-extends
149 // the representation of the char value to fill the wider format.
150 if (instruction->GetType() == type && (instruction->IsArrayGet() ||
151 instruction->IsStaticFieldGet() ||
152 instruction->IsInstanceFieldGet())) {
153 if (type == Primitive::kPrimChar) {
154 *operand = instruction;
155 return true;
156 }
157 }
158 // A sign (or zero) extension followed by an explicit removal of just the
159 // higher sign bits is equivalent to a zero extension of the underlying operand.
160 if (instruction->IsAnd()) {
161 int64_t mask = 0;
162 HInstruction* a = instruction->InputAt(0);
163 HInstruction* b = instruction->InputAt(1);
164 // In (a & b) find (mask & b) or (a & mask) with sign or zero extension on the non-mask.
165 if ((IsInt64AndGet(a, /*out*/ &mask) && (IsSignExtensionAndGet(b, type, /*out*/ operand) ||
166 IsZeroExtensionAndGet(b, type, /*out*/ operand))) ||
167 (IsInt64AndGet(b, /*out*/ &mask) && (IsSignExtensionAndGet(a, type, /*out*/ operand) ||
168 IsZeroExtensionAndGet(a, type, /*out*/ operand)))) {
169 switch ((*operand)->GetType()) {
170 case Primitive::kPrimByte: return mask == std::numeric_limits<uint8_t>::max();
171 case Primitive::kPrimChar:
172 case Primitive::kPrimShort: return mask == std::numeric_limits<uint16_t>::max();
173 default: return false;
174 }
175 }
176 }
177 // TODO: perhaps explicit conversions later too?
178 return false;
179}
180
Aart Bik304c8a52017-05-23 11:01:13 -0700181// Detect situations with same-extension narrower operands.
182// Returns true on success and sets is_unsigned accordingly.
183static bool IsNarrowerOperands(HInstruction* a,
184 HInstruction* b,
185 Primitive::Type type,
186 /*out*/ HInstruction** r,
187 /*out*/ HInstruction** s,
188 /*out*/ bool* is_unsigned) {
189 if (IsSignExtensionAndGet(a, type, r) && IsSignExtensionAndGet(b, type, s)) {
190 *is_unsigned = false;
191 return true;
192 } else if (IsZeroExtensionAndGet(a, type, r) && IsZeroExtensionAndGet(b, type, s)) {
193 *is_unsigned = true;
194 return true;
195 }
196 return false;
197}
198
199// As above, single operand.
200static bool IsNarrowerOperand(HInstruction* a,
201 Primitive::Type type,
202 /*out*/ HInstruction** r,
203 /*out*/ bool* is_unsigned) {
204 if (IsSignExtensionAndGet(a, type, r)) {
205 *is_unsigned = false;
206 return true;
207 } else if (IsZeroExtensionAndGet(a, type, r)) {
208 *is_unsigned = true;
209 return true;
210 }
211 return false;
212}
213
Aart Bik5f805002017-05-16 16:42:41 -0700214// Detect up to two instructions a and b, and an acccumulated constant c.
215static bool IsAddConstHelper(HInstruction* instruction,
216 /*out*/ HInstruction** a,
217 /*out*/ HInstruction** b,
218 /*out*/ int64_t* c,
219 int32_t depth) {
220 static constexpr int32_t kMaxDepth = 8; // don't search too deep
221 int64_t value = 0;
222 if (IsInt64AndGet(instruction, &value)) {
223 *c += value;
224 return true;
225 } else if (instruction->IsAdd() && depth <= kMaxDepth) {
226 return IsAddConstHelper(instruction->InputAt(0), a, b, c, depth + 1) &&
227 IsAddConstHelper(instruction->InputAt(1), a, b, c, depth + 1);
228 } else if (*a == nullptr) {
229 *a = instruction;
230 return true;
231 } else if (*b == nullptr) {
232 *b = instruction;
233 return true;
234 }
235 return false; // too many non-const operands
236}
237
238// Detect a + b + c for an optional constant c.
239static bool IsAddConst(HInstruction* instruction,
240 /*out*/ HInstruction** a,
241 /*out*/ HInstruction** b,
242 /*out*/ int64_t* c) {
243 if (instruction->IsAdd()) {
244 // Try to find a + b and accumulated c.
245 if (IsAddConstHelper(instruction->InputAt(0), a, b, c, /*depth*/ 0) &&
246 IsAddConstHelper(instruction->InputAt(1), a, b, c, /*depth*/ 0) &&
247 *b != nullptr) {
248 return true;
249 }
250 // Found a + b.
251 *a = instruction->InputAt(0);
252 *b = instruction->InputAt(1);
253 *c = 0;
254 return true;
255 }
256 return false;
257}
258
Aart Bikb29f6842017-07-28 15:58:41 -0700259// Detect reductions of the following forms,
260// under assumption phi has only *one* use:
261// x = x_phi + ..
262// x = x_phi - ..
263// x = max(x_phi, ..)
264// x = min(x_phi, ..)
265static bool HasReductionFormat(HInstruction* reduction, HInstruction* phi) {
266 if (reduction->IsAdd()) {
267 return reduction->InputAt(0) == phi || reduction->InputAt(1) == phi;
268 } else if (reduction->IsSub()) {
269 return reduction->InputAt(0) == phi;
270 } else if (reduction->IsInvokeStaticOrDirect()) {
271 switch (reduction->AsInvokeStaticOrDirect()->GetIntrinsic()) {
272 case Intrinsics::kMathMinIntInt:
273 case Intrinsics::kMathMinLongLong:
274 case Intrinsics::kMathMinFloatFloat:
275 case Intrinsics::kMathMinDoubleDouble:
276 case Intrinsics::kMathMaxIntInt:
277 case Intrinsics::kMathMaxLongLong:
278 case Intrinsics::kMathMaxFloatFloat:
279 case Intrinsics::kMathMaxDoubleDouble:
280 return reduction->InputAt(0) == phi || reduction->InputAt(1) == phi;
281 default:
282 return false;
283 }
284 }
285 return false;
286}
287
Aart Bikf8f5a162017-02-06 15:35:29 -0800288// Test vector restrictions.
289static bool HasVectorRestrictions(uint64_t restrictions, uint64_t tested) {
290 return (restrictions & tested) != 0;
291}
292
Aart Bikf3e61ee2017-04-12 17:09:20 -0700293// Insert an instruction.
Aart Bikf8f5a162017-02-06 15:35:29 -0800294static HInstruction* Insert(HBasicBlock* block, HInstruction* instruction) {
295 DCHECK(block != nullptr);
296 DCHECK(instruction != nullptr);
297 block->InsertInstructionBefore(instruction, block->GetLastInstruction());
298 return instruction;
299}
300
Artem Serov21c7e6f2017-07-27 16:04:42 +0100301// Check that instructions from the induction sets are fully removed: have no uses
302// and no other instructions use them.
303static bool CheckInductionSetFullyRemoved(ArenaSet<HInstruction*>* iset) {
304 for (HInstruction* instr : *iset) {
305 if (instr->GetBlock() != nullptr ||
306 !instr->GetUses().empty() ||
307 !instr->GetEnvUses().empty() ||
308 HasEnvironmentUsedByOthers(instr)) {
309 return false;
310 }
311 }
Artem Serov21c7e6f2017-07-27 16:04:42 +0100312 return true;
313}
314
Aart Bik281c6812016-08-26 11:31:48 -0700315//
Aart Bikb29f6842017-07-28 15:58:41 -0700316// Public methods.
Aart Bik281c6812016-08-26 11:31:48 -0700317//
318
319HLoopOptimization::HLoopOptimization(HGraph* graph,
Aart Bik92685a82017-03-06 11:13:43 -0800320 CompilerDriver* compiler_driver,
Aart Bik281c6812016-08-26 11:31:48 -0700321 HInductionVarAnalysis* induction_analysis)
322 : HOptimization(graph, kLoopOptimizationPassName),
Aart Bik92685a82017-03-06 11:13:43 -0800323 compiler_driver_(compiler_driver),
Aart Bik281c6812016-08-26 11:31:48 -0700324 induction_range_(induction_analysis),
Aart Bik96202302016-10-04 17:33:56 -0700325 loop_allocator_(nullptr),
Aart Bikf8f5a162017-02-06 15:35:29 -0800326 global_allocator_(graph_->GetArena()),
Aart Bik281c6812016-08-26 11:31:48 -0700327 top_loop_(nullptr),
Aart Bik8c4a8542016-10-06 11:36:57 -0700328 last_loop_(nullptr),
Aart Bik482095d2016-10-10 15:39:10 -0700329 iset_(nullptr),
Aart Bikb29f6842017-07-28 15:58:41 -0700330 reductions_(nullptr),
Aart Bikf8f5a162017-02-06 15:35:29 -0800331 simplified_(false),
332 vector_length_(0),
333 vector_refs_(nullptr),
Aart Bik14a68b42017-06-08 14:06:58 -0700334 vector_peeling_candidate_(nullptr),
335 vector_runtime_test_a_(nullptr),
336 vector_runtime_test_b_(nullptr),
Aart Bikf8f5a162017-02-06 15:35:29 -0800337 vector_map_(nullptr) {
Aart Bik281c6812016-08-26 11:31:48 -0700338}
339
340void HLoopOptimization::Run() {
Mingyao Yang01b47b02017-02-03 12:09:57 -0800341 // Skip if there is no loop or the graph has try-catch/irreducible loops.
Aart Bik281c6812016-08-26 11:31:48 -0700342 // TODO: make this less of a sledgehammer.
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800343 if (!graph_->HasLoops() || graph_->HasTryCatch() || graph_->HasIrreducibleLoops()) {
Aart Bik281c6812016-08-26 11:31:48 -0700344 return;
345 }
346
Aart Bik96202302016-10-04 17:33:56 -0700347 // Phase-local allocator that draws from the global pool. Since the allocator
348 // itself resides on the stack, it is destructed on exiting Run(), which
349 // implies its underlying memory is released immediately.
Aart Bikf8f5a162017-02-06 15:35:29 -0800350 ArenaAllocator allocator(global_allocator_->GetArenaPool());
Aart Bik96202302016-10-04 17:33:56 -0700351 loop_allocator_ = &allocator;
Nicolas Geoffrayebe16742016-10-05 09:55:42 +0100352
Aart Bik96202302016-10-04 17:33:56 -0700353 // Perform loop optimizations.
354 LocalRun();
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800355 if (top_loop_ == nullptr) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800356 graph_->SetHasLoops(false); // no more loops
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800357 }
358
Aart Bik96202302016-10-04 17:33:56 -0700359 // Detach.
360 loop_allocator_ = nullptr;
361 last_loop_ = top_loop_ = nullptr;
362}
363
Aart Bikb29f6842017-07-28 15:58:41 -0700364//
365// Loop setup and traversal.
366//
367
Aart Bik96202302016-10-04 17:33:56 -0700368void HLoopOptimization::LocalRun() {
369 // Build the linear order using the phase-local allocator. This step enables building
370 // a loop hierarchy that properly reflects the outer-inner and previous-next relation.
371 ArenaVector<HBasicBlock*> linear_order(loop_allocator_->Adapter(kArenaAllocLinearOrder));
372 LinearizeGraph(graph_, loop_allocator_, &linear_order);
373
Aart Bik281c6812016-08-26 11:31:48 -0700374 // Build the loop hierarchy.
Aart Bik96202302016-10-04 17:33:56 -0700375 for (HBasicBlock* block : linear_order) {
Aart Bik281c6812016-08-26 11:31:48 -0700376 if (block->IsLoopHeader()) {
377 AddLoop(block->GetLoopInformation());
378 }
379 }
Aart Bik96202302016-10-04 17:33:56 -0700380
Aart Bik8c4a8542016-10-06 11:36:57 -0700381 // Traverse the loop hierarchy inner-to-outer and optimize. Traversal can use
Aart Bikf8f5a162017-02-06 15:35:29 -0800382 // temporary data structures using the phase-local allocator. All new HIR
383 // should use the global allocator.
Aart Bik8c4a8542016-10-06 11:36:57 -0700384 if (top_loop_ != nullptr) {
385 ArenaSet<HInstruction*> iset(loop_allocator_->Adapter(kArenaAllocLoopOptimization));
Aart Bikb29f6842017-07-28 15:58:41 -0700386 ArenaSafeMap<HInstruction*, HInstruction*> reds(
387 std::less<HInstruction*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
Aart Bikf8f5a162017-02-06 15:35:29 -0800388 ArenaSet<ArrayReference> refs(loop_allocator_->Adapter(kArenaAllocLoopOptimization));
389 ArenaSafeMap<HInstruction*, HInstruction*> map(
390 std::less<HInstruction*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
391 // Attach.
Aart Bik8c4a8542016-10-06 11:36:57 -0700392 iset_ = &iset;
Aart Bikb29f6842017-07-28 15:58:41 -0700393 reductions_ = &reds;
Aart Bikf8f5a162017-02-06 15:35:29 -0800394 vector_refs_ = &refs;
395 vector_map_ = &map;
396 // Traverse.
Aart Bik8c4a8542016-10-06 11:36:57 -0700397 TraverseLoopsInnerToOuter(top_loop_);
Aart Bikf8f5a162017-02-06 15:35:29 -0800398 // Detach.
399 iset_ = nullptr;
Aart Bikb29f6842017-07-28 15:58:41 -0700400 reductions_ = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800401 vector_refs_ = nullptr;
402 vector_map_ = nullptr;
Aart Bik8c4a8542016-10-06 11:36:57 -0700403 }
Aart Bik281c6812016-08-26 11:31:48 -0700404}
405
406void HLoopOptimization::AddLoop(HLoopInformation* loop_info) {
407 DCHECK(loop_info != nullptr);
Aart Bikf8f5a162017-02-06 15:35:29 -0800408 LoopNode* node = new (loop_allocator_) LoopNode(loop_info);
Aart Bik281c6812016-08-26 11:31:48 -0700409 if (last_loop_ == nullptr) {
410 // First loop.
411 DCHECK(top_loop_ == nullptr);
412 last_loop_ = top_loop_ = node;
413 } else if (loop_info->IsIn(*last_loop_->loop_info)) {
414 // Inner loop.
415 node->outer = last_loop_;
416 DCHECK(last_loop_->inner == nullptr);
417 last_loop_ = last_loop_->inner = node;
418 } else {
419 // Subsequent loop.
420 while (last_loop_->outer != nullptr && !loop_info->IsIn(*last_loop_->outer->loop_info)) {
421 last_loop_ = last_loop_->outer;
422 }
423 node->outer = last_loop_->outer;
424 node->previous = last_loop_;
425 DCHECK(last_loop_->next == nullptr);
426 last_loop_ = last_loop_->next = node;
427 }
428}
429
430void HLoopOptimization::RemoveLoop(LoopNode* node) {
431 DCHECK(node != nullptr);
Aart Bik8c4a8542016-10-06 11:36:57 -0700432 DCHECK(node->inner == nullptr);
433 if (node->previous != nullptr) {
434 // Within sequence.
435 node->previous->next = node->next;
436 if (node->next != nullptr) {
437 node->next->previous = node->previous;
438 }
439 } else {
440 // First of sequence.
441 if (node->outer != nullptr) {
442 node->outer->inner = node->next;
443 } else {
444 top_loop_ = node->next;
445 }
446 if (node->next != nullptr) {
447 node->next->outer = node->outer;
448 node->next->previous = nullptr;
449 }
450 }
Aart Bik281c6812016-08-26 11:31:48 -0700451}
452
Aart Bikb29f6842017-07-28 15:58:41 -0700453bool HLoopOptimization::TraverseLoopsInnerToOuter(LoopNode* node) {
454 bool changed = false;
Aart Bik281c6812016-08-26 11:31:48 -0700455 for ( ; node != nullptr; node = node->next) {
Aart Bikb29f6842017-07-28 15:58:41 -0700456 // Visit inner loops first. Recompute induction information for this
457 // loop if the induction of any inner loop has changed.
458 if (TraverseLoopsInnerToOuter(node->inner)) {
Aart Bik482095d2016-10-10 15:39:10 -0700459 induction_range_.ReVisit(node->loop_info);
460 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800461 // Repeat simplifications in the loop-body until no more changes occur.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800462 // Note that since each simplification consists of eliminating code (without
463 // introducing new code), this process is always finite.
Aart Bikdf7822e2016-12-06 10:05:30 -0800464 do {
465 simplified_ = false;
Aart Bikdf7822e2016-12-06 10:05:30 -0800466 SimplifyInduction(node);
Aart Bik6b69e0a2017-01-11 10:20:43 -0800467 SimplifyBlocks(node);
Aart Bikb29f6842017-07-28 15:58:41 -0700468 changed = simplified_ || changed;
Aart Bikdf7822e2016-12-06 10:05:30 -0800469 } while (simplified_);
Aart Bikf8f5a162017-02-06 15:35:29 -0800470 // Optimize inner loop.
Aart Bik9abf8942016-10-14 09:49:42 -0700471 if (node->inner == nullptr) {
Aart Bikb29f6842017-07-28 15:58:41 -0700472 changed = OptimizeInnerLoop(node) || changed;
Aart Bik9abf8942016-10-14 09:49:42 -0700473 }
Aart Bik281c6812016-08-26 11:31:48 -0700474 }
Aart Bikb29f6842017-07-28 15:58:41 -0700475 return changed;
Aart Bik281c6812016-08-26 11:31:48 -0700476}
477
Aart Bikf8f5a162017-02-06 15:35:29 -0800478//
479// Optimization.
480//
481
Aart Bik281c6812016-08-26 11:31:48 -0700482void HLoopOptimization::SimplifyInduction(LoopNode* node) {
483 HBasicBlock* header = node->loop_info->GetHeader();
484 HBasicBlock* preheader = node->loop_info->GetPreHeader();
Aart Bik8c4a8542016-10-06 11:36:57 -0700485 // Scan the phis in the header to find opportunities to simplify an induction
486 // cycle that is only used outside the loop. Replace these uses, if any, with
487 // the last value and remove the induction cycle.
488 // Examples: for (int i = 0; x != null; i++) { .... no i .... }
489 // for (int i = 0; i < 10; i++, k++) { .... no k .... } return k;
Aart Bik281c6812016-08-26 11:31:48 -0700490 for (HInstructionIterator it(header->GetPhis()); !it.Done(); it.Advance()) {
491 HPhi* phi = it.Current()->AsPhi();
Aart Bikf8f5a162017-02-06 15:35:29 -0800492 if (TrySetPhiInduction(phi, /*restrict_uses*/ true) &&
493 TryAssignLastValue(node->loop_info, phi, preheader, /*collect_loop_uses*/ false)) {
Aart Bik671e48a2017-08-09 13:16:56 -0700494 // Note that it's ok to have replaced uses after the loop with the last value, without
495 // being able to remove the cycle. Environment uses (which are the reason we may not be
496 // able to remove the cycle) within the loop will still hold the right value. We must
497 // have tried first, however, to replace outside uses.
498 if (CanRemoveCycle()) {
499 simplified_ = true;
500 for (HInstruction* i : *iset_) {
501 RemoveFromCycle(i);
502 }
503 DCHECK(CheckInductionSetFullyRemoved(iset_));
Aart Bik281c6812016-08-26 11:31:48 -0700504 }
Aart Bik482095d2016-10-10 15:39:10 -0700505 }
506 }
507}
508
509void HLoopOptimization::SimplifyBlocks(LoopNode* node) {
Aart Bikdf7822e2016-12-06 10:05:30 -0800510 // Iterate over all basic blocks in the loop-body.
511 for (HBlocksInLoopIterator it(*node->loop_info); !it.Done(); it.Advance()) {
512 HBasicBlock* block = it.Current();
513 // Remove dead instructions from the loop-body.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800514 RemoveDeadInstructions(block->GetPhis());
515 RemoveDeadInstructions(block->GetInstructions());
Aart Bikdf7822e2016-12-06 10:05:30 -0800516 // Remove trivial control flow blocks from the loop-body.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800517 if (block->GetPredecessors().size() == 1 &&
518 block->GetSuccessors().size() == 1 &&
519 block->GetSingleSuccessor()->GetPredecessors().size() == 1) {
Aart Bikdf7822e2016-12-06 10:05:30 -0800520 simplified_ = true;
Aart Bik6b69e0a2017-01-11 10:20:43 -0800521 block->MergeWith(block->GetSingleSuccessor());
Aart Bikdf7822e2016-12-06 10:05:30 -0800522 } else if (block->GetSuccessors().size() == 2) {
523 // Trivial if block can be bypassed to either branch.
524 HBasicBlock* succ0 = block->GetSuccessors()[0];
525 HBasicBlock* succ1 = block->GetSuccessors()[1];
526 HBasicBlock* meet0 = nullptr;
527 HBasicBlock* meet1 = nullptr;
528 if (succ0 != succ1 &&
529 IsGotoBlock(succ0, &meet0) &&
530 IsGotoBlock(succ1, &meet1) &&
531 meet0 == meet1 && // meets again
532 meet0 != block && // no self-loop
533 meet0->GetPhis().IsEmpty()) { // not used for merging
534 simplified_ = true;
535 succ0->DisconnectAndDelete();
536 if (block->Dominates(meet0)) {
537 block->RemoveDominatedBlock(meet0);
538 succ1->AddDominatedBlock(meet0);
539 meet0->SetDominator(succ1);
Aart Bike3dedc52016-11-02 17:50:27 -0700540 }
Aart Bik482095d2016-10-10 15:39:10 -0700541 }
Aart Bik281c6812016-08-26 11:31:48 -0700542 }
Aart Bikdf7822e2016-12-06 10:05:30 -0800543 }
Aart Bik281c6812016-08-26 11:31:48 -0700544}
545
Aart Bikb29f6842017-07-28 15:58:41 -0700546bool HLoopOptimization::OptimizeInnerLoop(LoopNode* node) {
Aart Bik281c6812016-08-26 11:31:48 -0700547 HBasicBlock* header = node->loop_info->GetHeader();
548 HBasicBlock* preheader = node->loop_info->GetPreHeader();
Aart Bik9abf8942016-10-14 09:49:42 -0700549 // Ensure loop header logic is finite.
Aart Bikf8f5a162017-02-06 15:35:29 -0800550 int64_t trip_count = 0;
551 if (!induction_range_.IsFinite(node->loop_info, &trip_count)) {
Aart Bikb29f6842017-07-28 15:58:41 -0700552 return false;
Aart Bik9abf8942016-10-14 09:49:42 -0700553 }
Aart Bik281c6812016-08-26 11:31:48 -0700554 // Ensure there is only a single loop-body (besides the header).
555 HBasicBlock* body = nullptr;
556 for (HBlocksInLoopIterator it(*node->loop_info); !it.Done(); it.Advance()) {
557 if (it.Current() != header) {
558 if (body != nullptr) {
Aart Bikb29f6842017-07-28 15:58:41 -0700559 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700560 }
561 body = it.Current();
562 }
563 }
Andreas Gampef45d61c2017-06-07 10:29:33 -0700564 CHECK(body != nullptr);
Aart Bik281c6812016-08-26 11:31:48 -0700565 // Ensure there is only a single exit point.
566 if (header->GetSuccessors().size() != 2) {
Aart Bikb29f6842017-07-28 15:58:41 -0700567 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700568 }
569 HBasicBlock* exit = (header->GetSuccessors()[0] == body)
570 ? header->GetSuccessors()[1]
571 : header->GetSuccessors()[0];
Aart Bik8c4a8542016-10-06 11:36:57 -0700572 // Ensure exit can only be reached by exiting loop.
Aart Bik281c6812016-08-26 11:31:48 -0700573 if (exit->GetPredecessors().size() != 1) {
Aart Bikb29f6842017-07-28 15:58:41 -0700574 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700575 }
Aart Bik6b69e0a2017-01-11 10:20:43 -0800576 // Detect either an empty loop (no side effects other than plain iteration) or
577 // a trivial loop (just iterating once). Replace subsequent index uses, if any,
578 // with the last value and remove the loop, possibly after unrolling its body.
Aart Bikb29f6842017-07-28 15:58:41 -0700579 HPhi* main_phi = nullptr;
580 if (TrySetSimpleLoopHeader(header, &main_phi)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -0800581 bool is_empty = IsEmptyBody(body);
Aart Bikb29f6842017-07-28 15:58:41 -0700582 if (reductions_->empty() && // TODO: possible with some effort
583 (is_empty || trip_count == 1) &&
584 TryAssignLastValue(node->loop_info, main_phi, preheader, /*collect_loop_uses*/ true)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -0800585 if (!is_empty) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800586 // Unroll the loop-body, which sees initial value of the index.
Aart Bikb29f6842017-07-28 15:58:41 -0700587 main_phi->ReplaceWith(main_phi->InputAt(0));
Aart Bik6b69e0a2017-01-11 10:20:43 -0800588 preheader->MergeInstructionsWith(body);
589 }
590 body->DisconnectAndDelete();
591 exit->RemovePredecessor(header);
592 header->RemoveSuccessor(exit);
593 header->RemoveDominatedBlock(exit);
594 header->DisconnectAndDelete();
595 preheader->AddSuccessor(exit);
Aart Bikf8f5a162017-02-06 15:35:29 -0800596 preheader->AddInstruction(new (global_allocator_) HGoto());
Aart Bik6b69e0a2017-01-11 10:20:43 -0800597 preheader->AddDominatedBlock(exit);
598 exit->SetDominator(preheader);
599 RemoveLoop(node); // update hierarchy
Aart Bikb29f6842017-07-28 15:58:41 -0700600 return true;
Aart Bikf8f5a162017-02-06 15:35:29 -0800601 }
602 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800603 // Vectorize loop, if possible and valid.
Aart Bikb29f6842017-07-28 15:58:41 -0700604 if (kEnableVectorization &&
605 TrySetSimpleLoopHeader(header, &main_phi) &&
606 reductions_->empty() && // TODO: possible with some effort
607 ShouldVectorize(node, body, trip_count) &&
608 TryAssignLastValue(node->loop_info, main_phi, preheader, /*collect_loop_uses*/ true)) {
609 Vectorize(node, body, exit, trip_count);
610 graph_->SetHasSIMD(true); // flag SIMD usage
611 return true;
Aart Bikf8f5a162017-02-06 15:35:29 -0800612 }
Aart Bikb29f6842017-07-28 15:58:41 -0700613 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -0800614}
615
616//
617// Loop vectorization. The implementation is based on the book by Aart J.C. Bik:
618// "The Software Vectorization Handbook. Applying Multimedia Extensions for Maximum Performance."
619// Intel Press, June, 2004 (http://www.aartbik.com/).
620//
621
Aart Bik14a68b42017-06-08 14:06:58 -0700622bool HLoopOptimization::ShouldVectorize(LoopNode* node, HBasicBlock* block, int64_t trip_count) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800623 // Reset vector bookkeeping.
624 vector_length_ = 0;
625 vector_refs_->clear();
Aart Bik14a68b42017-06-08 14:06:58 -0700626 vector_peeling_candidate_ = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800627 vector_runtime_test_a_ =
628 vector_runtime_test_b_= nullptr;
629
630 // Phis in the loop-body prevent vectorization.
631 if (!block->GetPhis().IsEmpty()) {
632 return false;
633 }
634
635 // Scan the loop-body, starting a right-hand-side tree traversal at each left-hand-side
636 // occurrence, which allows passing down attributes down the use tree.
637 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
638 if (!VectorizeDef(node, it.Current(), /*generate_code*/ false)) {
639 return false; // failure to vectorize a left-hand-side
640 }
641 }
642
Aart Bik14a68b42017-06-08 14:06:58 -0700643 // Does vectorization seem profitable?
644 if (!IsVectorizationProfitable(trip_count)) {
645 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -0800646 }
647
648 // Data dependence analysis. Find each pair of references with same type, where
649 // at least one is a write. Each such pair denotes a possible data dependence.
650 // This analysis exploits the property that differently typed arrays cannot be
651 // aliased, as well as the property that references either point to the same
652 // array or to two completely disjoint arrays, i.e., no partial aliasing.
653 // Other than a few simply heuristics, no detailed subscript analysis is done.
Aart Bikb29f6842017-07-28 15:58:41 -0700654 // The scan over references also finds a suitable dynamic loop peeling candidate.
655 const ArrayReference* candidate = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800656 for (auto i = vector_refs_->begin(); i != vector_refs_->end(); ++i) {
657 for (auto j = i; ++j != vector_refs_->end(); ) {
658 if (i->type == j->type && (i->lhs || j->lhs)) {
659 // Found same-typed a[i+x] vs. b[i+y], where at least one is a write.
660 HInstruction* a = i->base;
661 HInstruction* b = j->base;
662 HInstruction* x = i->offset;
663 HInstruction* y = j->offset;
664 if (a == b) {
665 // Found a[i+x] vs. a[i+y]. Accept if x == y (loop-independent data dependence).
666 // Conservatively assume a loop-carried data dependence otherwise, and reject.
667 if (x != y) {
668 return false;
669 }
670 } else {
671 // Found a[i+x] vs. b[i+y]. Accept if x == y (at worst loop-independent data dependence).
672 // Conservatively assume a potential loop-carried data dependence otherwise, avoided by
673 // generating an explicit a != b disambiguation runtime test on the two references.
674 if (x != y) {
Aart Bik37dc4df2017-06-28 14:08:00 -0700675 // To avoid excessive overhead, we only accept one a != b test.
676 if (vector_runtime_test_a_ == nullptr) {
677 // First test found.
678 vector_runtime_test_a_ = a;
679 vector_runtime_test_b_ = b;
680 } else if ((vector_runtime_test_a_ != a || vector_runtime_test_b_ != b) &&
681 (vector_runtime_test_a_ != b || vector_runtime_test_b_ != a)) {
682 return false; // second test would be needed
Aart Bikf8f5a162017-02-06 15:35:29 -0800683 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800684 }
685 }
686 }
687 }
688 }
689
Aart Bik14a68b42017-06-08 14:06:58 -0700690 // Consider dynamic loop peeling for alignment.
Aart Bikb29f6842017-07-28 15:58:41 -0700691 SetPeelingCandidate(candidate, trip_count);
Aart Bik14a68b42017-06-08 14:06:58 -0700692
Aart Bikf8f5a162017-02-06 15:35:29 -0800693 // Success!
694 return true;
695}
696
697void HLoopOptimization::Vectorize(LoopNode* node,
698 HBasicBlock* block,
699 HBasicBlock* exit,
700 int64_t trip_count) {
701 Primitive::Type induc_type = Primitive::kPrimInt;
702 HBasicBlock* header = node->loop_info->GetHeader();
703 HBasicBlock* preheader = node->loop_info->GetPreHeader();
704
Aart Bik14a68b42017-06-08 14:06:58 -0700705 // Pick a loop unrolling factor for the vector loop.
706 uint32_t unroll = GetUnrollingFactor(block, trip_count);
707 uint32_t chunk = vector_length_ * unroll;
708
709 // A cleanup loop is needed, at least, for any unknown trip count or
710 // for a known trip count with remainder iterations after vectorization.
711 bool needs_cleanup = trip_count == 0 || (trip_count % chunk) != 0;
Aart Bikf8f5a162017-02-06 15:35:29 -0800712
713 // Adjust vector bookkeeping.
Aart Bikb29f6842017-07-28 15:58:41 -0700714 HPhi* main_phi = nullptr;
715 bool is_simple_loop_header = TrySetSimpleLoopHeader(header, &main_phi); // refills sets
Aart Bikf8f5a162017-02-06 15:35:29 -0800716 DCHECK(is_simple_loop_header);
Aart Bik14a68b42017-06-08 14:06:58 -0700717 vector_header_ = header;
718 vector_body_ = block;
Aart Bikf8f5a162017-02-06 15:35:29 -0800719
Aart Bikb29f6842017-07-28 15:58:41 -0700720 // Generate dynamic loop peeling trip count, if needed, under the assumption
721 // that the Android runtime guarantees at least "component size" alignment:
722 // ptc = (ALIGN - (&a[initial] % ALIGN)) / type-size
Aart Bik14a68b42017-06-08 14:06:58 -0700723 HInstruction* ptc = nullptr;
724 if (vector_peeling_candidate_ != nullptr) {
725 DCHECK_LT(vector_length_, trip_count) << "dynamic peeling currently requires known trip count";
726 //
727 // TODO: Implement this. Compute address of first access memory location and
728 // compute peeling factor to obtain kAlignedBase alignment.
729 //
730 needs_cleanup = true;
731 }
732
733 // Generate loop control:
Aart Bikf8f5a162017-02-06 15:35:29 -0800734 // stc = <trip-count>;
Aart Bik14a68b42017-06-08 14:06:58 -0700735 // vtc = stc - (stc - ptc) % chunk;
736 // i = 0;
Aart Bikf8f5a162017-02-06 15:35:29 -0800737 HInstruction* stc = induction_range_.GenerateTripCount(node->loop_info, graph_, preheader);
738 HInstruction* vtc = stc;
739 if (needs_cleanup) {
Aart Bik14a68b42017-06-08 14:06:58 -0700740 DCHECK(IsPowerOfTwo(chunk));
741 HInstruction* diff = stc;
742 if (ptc != nullptr) {
743 diff = Insert(preheader, new (global_allocator_) HSub(induc_type, stc, ptc));
744 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800745 HInstruction* rem = Insert(
746 preheader, new (global_allocator_) HAnd(induc_type,
Aart Bik14a68b42017-06-08 14:06:58 -0700747 diff,
748 graph_->GetIntConstant(chunk - 1)));
Aart Bikf8f5a162017-02-06 15:35:29 -0800749 vtc = Insert(preheader, new (global_allocator_) HSub(induc_type, stc, rem));
750 }
Aart Bik14a68b42017-06-08 14:06:58 -0700751 vector_index_ = graph_->GetIntConstant(0);
Aart Bikf8f5a162017-02-06 15:35:29 -0800752
753 // Generate runtime disambiguation test:
754 // vtc = a != b ? vtc : 0;
755 if (vector_runtime_test_a_ != nullptr) {
756 HInstruction* rt = Insert(
757 preheader,
758 new (global_allocator_) HNotEqual(vector_runtime_test_a_, vector_runtime_test_b_));
759 vtc = Insert(preheader,
760 new (global_allocator_) HSelect(rt, vtc, graph_->GetIntConstant(0), kNoDexPc));
761 needs_cleanup = true;
762 }
763
Aart Bik14a68b42017-06-08 14:06:58 -0700764 // Generate dynamic peeling loop for alignment, if needed:
765 // for ( ; i < ptc; i += 1)
766 // <loop-body>
767 if (ptc != nullptr) {
768 vector_mode_ = kSequential;
769 GenerateNewLoop(node,
770 block,
771 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
772 vector_index_,
773 ptc,
774 graph_->GetIntConstant(1),
775 /*unroll*/ 1);
776 }
777
778 // Generate vector loop, possibly further unrolled:
779 // for ( ; i < vtc; i += chunk)
Aart Bikf8f5a162017-02-06 15:35:29 -0800780 // <vectorized-loop-body>
781 vector_mode_ = kVector;
782 GenerateNewLoop(node,
783 block,
Aart Bik14a68b42017-06-08 14:06:58 -0700784 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
785 vector_index_,
Aart Bikf8f5a162017-02-06 15:35:29 -0800786 vtc,
Aart Bik14a68b42017-06-08 14:06:58 -0700787 graph_->GetIntConstant(vector_length_), // increment per unroll
788 unroll);
Aart Bikf8f5a162017-02-06 15:35:29 -0800789 HLoopInformation* vloop = vector_header_->GetLoopInformation();
790
791 // Generate cleanup loop, if needed:
792 // for ( ; i < stc; i += 1)
793 // <loop-body>
794 if (needs_cleanup) {
795 vector_mode_ = kSequential;
796 GenerateNewLoop(node,
797 block,
798 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
Aart Bik14a68b42017-06-08 14:06:58 -0700799 vector_index_,
Aart Bikf8f5a162017-02-06 15:35:29 -0800800 stc,
Aart Bik14a68b42017-06-08 14:06:58 -0700801 graph_->GetIntConstant(1),
802 /*unroll*/ 1);
Aart Bikf8f5a162017-02-06 15:35:29 -0800803 }
804
805 // Remove the original loop by disconnecting the body block
806 // and removing all instructions from the header.
807 block->DisconnectAndDelete();
808 while (!header->GetFirstInstruction()->IsGoto()) {
809 header->RemoveInstruction(header->GetFirstInstruction());
810 }
Aart Bikb29f6842017-07-28 15:58:41 -0700811
Aart Bik14a68b42017-06-08 14:06:58 -0700812 // Update loop hierarchy: the old header now resides in the same outer loop
813 // as the old preheader. Note that we don't bother putting sequential
814 // loops back in the hierarchy at this point.
Aart Bikf8f5a162017-02-06 15:35:29 -0800815 header->SetLoopInformation(preheader->GetLoopInformation()); // outward
816 node->loop_info = vloop;
817}
818
819void HLoopOptimization::GenerateNewLoop(LoopNode* node,
820 HBasicBlock* block,
821 HBasicBlock* new_preheader,
822 HInstruction* lo,
823 HInstruction* hi,
Aart Bik14a68b42017-06-08 14:06:58 -0700824 HInstruction* step,
825 uint32_t unroll) {
826 DCHECK(unroll == 1 || vector_mode_ == kVector);
Aart Bikf8f5a162017-02-06 15:35:29 -0800827 Primitive::Type induc_type = Primitive::kPrimInt;
828 // Prepare new loop.
Aart Bikf8f5a162017-02-06 15:35:29 -0800829 vector_preheader_ = new_preheader,
830 vector_header_ = vector_preheader_->GetSingleSuccessor();
831 vector_body_ = vector_header_->GetSuccessors()[1];
Aart Bik14a68b42017-06-08 14:06:58 -0700832 HPhi* phi = new (global_allocator_) HPhi(global_allocator_,
833 kNoRegNumber,
834 0,
835 HPhi::ToPhiType(induc_type));
Aart Bikb07d1bc2017-04-05 10:03:15 -0700836 // Generate header and prepare body.
Aart Bikf8f5a162017-02-06 15:35:29 -0800837 // for (i = lo; i < hi; i += step)
838 // <loop-body>
Aart Bik14a68b42017-06-08 14:06:58 -0700839 HInstruction* cond = new (global_allocator_) HAboveOrEqual(phi, hi);
840 vector_header_->AddPhi(phi);
Aart Bikf8f5a162017-02-06 15:35:29 -0800841 vector_header_->AddInstruction(cond);
842 vector_header_->AddInstruction(new (global_allocator_) HIf(cond));
Aart Bik14a68b42017-06-08 14:06:58 -0700843 vector_index_ = phi;
844 for (uint32_t u = 0; u < unroll; u++) {
845 // Clear map, leaving loop invariants setup during unrolling.
846 if (u == 0) {
847 vector_map_->clear();
848 } else {
849 for (auto i = vector_map_->begin(); i != vector_map_->end(); ) {
850 if (i->second->IsVecReplicateScalar()) {
851 DCHECK(node->loop_info->IsDefinedOutOfTheLoop(i->first));
852 ++i;
853 } else {
854 i = vector_map_->erase(i);
855 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800856 }
857 }
Aart Bik14a68b42017-06-08 14:06:58 -0700858 // Generate instruction map.
859 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
860 bool vectorized_def = VectorizeDef(node, it.Current(), /*generate_code*/ true);
861 DCHECK(vectorized_def);
862 }
863 // Generate body from the instruction map, but in original program order.
864 HEnvironment* env = vector_header_->GetFirstInstruction()->GetEnvironment();
865 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
866 auto i = vector_map_->find(it.Current());
867 if (i != vector_map_->end() && !i->second->IsInBlock()) {
868 Insert(vector_body_, i->second);
869 // Deal with instructions that need an environment, such as the scalar intrinsics.
870 if (i->second->NeedsEnvironment()) {
871 i->second->CopyEnvironmentFromWithLoopPhiAdjustment(env, vector_header_);
872 }
873 }
874 }
875 vector_index_ = new (global_allocator_) HAdd(induc_type, vector_index_, step);
876 Insert(vector_body_, vector_index_);
Aart Bikf8f5a162017-02-06 15:35:29 -0800877 }
Aart Bikb29f6842017-07-28 15:58:41 -0700878 // Finalize phi inputs for the loop index.
Aart Bik14a68b42017-06-08 14:06:58 -0700879 phi->AddInput(lo);
880 phi->AddInput(vector_index_);
881 vector_index_ = phi;
Aart Bikf8f5a162017-02-06 15:35:29 -0800882}
883
Aart Bikf8f5a162017-02-06 15:35:29 -0800884bool HLoopOptimization::VectorizeDef(LoopNode* node,
885 HInstruction* instruction,
886 bool generate_code) {
887 // Accept a left-hand-side array base[index] for
888 // (1) supported vector type,
889 // (2) loop-invariant base,
890 // (3) unit stride index,
891 // (4) vectorizable right-hand-side value.
892 uint64_t restrictions = kNone;
893 if (instruction->IsArraySet()) {
894 Primitive::Type type = instruction->AsArraySet()->GetComponentType();
895 HInstruction* base = instruction->InputAt(0);
896 HInstruction* index = instruction->InputAt(1);
897 HInstruction* value = instruction->InputAt(2);
898 HInstruction* offset = nullptr;
899 if (TrySetVectorType(type, &restrictions) &&
900 node->loop_info->IsDefinedOutOfTheLoop(base) &&
Aart Bik37dc4df2017-06-28 14:08:00 -0700901 induction_range_.IsUnitStride(instruction, index, graph_, &offset) &&
Aart Bikf8f5a162017-02-06 15:35:29 -0800902 VectorizeUse(node, value, generate_code, type, restrictions)) {
903 if (generate_code) {
904 GenerateVecSub(index, offset);
Aart Bik14a68b42017-06-08 14:06:58 -0700905 GenerateVecMem(instruction, vector_map_->Get(index), vector_map_->Get(value), offset, type);
Aart Bikf8f5a162017-02-06 15:35:29 -0800906 } else {
907 vector_refs_->insert(ArrayReference(base, offset, type, /*lhs*/ true));
908 }
Aart Bik6b69e0a2017-01-11 10:20:43 -0800909 return true;
910 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800911 return false;
912 }
913 // Branch back okay.
914 if (instruction->IsGoto()) {
915 return true;
916 }
917 // Otherwise accept only expressions with no effects outside the immediate loop-body.
918 // Note that actual uses are inspected during right-hand-side tree traversal.
919 return !IsUsedOutsideLoop(node->loop_info, instruction) && !instruction->DoesAnyWrite();
920}
921
Aart Bik304c8a52017-05-23 11:01:13 -0700922// TODO: saturation arithmetic.
Aart Bikf8f5a162017-02-06 15:35:29 -0800923bool HLoopOptimization::VectorizeUse(LoopNode* node,
924 HInstruction* instruction,
925 bool generate_code,
926 Primitive::Type type,
927 uint64_t restrictions) {
928 // Accept anything for which code has already been generated.
929 if (generate_code) {
930 if (vector_map_->find(instruction) != vector_map_->end()) {
931 return true;
932 }
933 }
934 // Continue the right-hand-side tree traversal, passing in proper
935 // types and vector restrictions along the way. During code generation,
936 // all new nodes are drawn from the global allocator.
937 if (node->loop_info->IsDefinedOutOfTheLoop(instruction)) {
938 // Accept invariant use, using scalar expansion.
939 if (generate_code) {
940 GenerateVecInv(instruction, type);
941 }
942 return true;
943 } else if (instruction->IsArrayGet()) {
Goran Jakovljevic19680d32017-05-11 10:38:36 +0200944 // Deal with vector restrictions.
945 if (instruction->AsArrayGet()->IsStringCharAt() &&
946 HasVectorRestrictions(restrictions, kNoStringCharAt)) {
947 return false;
948 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800949 // Accept a right-hand-side array base[index] for
950 // (1) exact matching vector type,
951 // (2) loop-invariant base,
952 // (3) unit stride index,
953 // (4) vectorizable right-hand-side value.
954 HInstruction* base = instruction->InputAt(0);
955 HInstruction* index = instruction->InputAt(1);
956 HInstruction* offset = nullptr;
957 if (type == instruction->GetType() &&
958 node->loop_info->IsDefinedOutOfTheLoop(base) &&
Aart Bik37dc4df2017-06-28 14:08:00 -0700959 induction_range_.IsUnitStride(instruction, index, graph_, &offset)) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800960 if (generate_code) {
961 GenerateVecSub(index, offset);
Aart Bik14a68b42017-06-08 14:06:58 -0700962 GenerateVecMem(instruction, vector_map_->Get(index), nullptr, offset, type);
Aart Bikf8f5a162017-02-06 15:35:29 -0800963 } else {
964 vector_refs_->insert(ArrayReference(base, offset, type, /*lhs*/ false));
965 }
966 return true;
967 }
968 } else if (instruction->IsTypeConversion()) {
969 // Accept particular type conversions.
970 HTypeConversion* conversion = instruction->AsTypeConversion();
971 HInstruction* opa = conversion->InputAt(0);
972 Primitive::Type from = conversion->GetInputType();
973 Primitive::Type to = conversion->GetResultType();
974 if ((to == Primitive::kPrimByte ||
975 to == Primitive::kPrimChar ||
976 to == Primitive::kPrimShort) && from == Primitive::kPrimInt) {
977 // Accept a "narrowing" type conversion from a "wider" computation for
978 // (1) conversion into final required type,
979 // (2) vectorizable operand,
980 // (3) "wider" operations cannot bring in higher order bits.
981 if (to == type && VectorizeUse(node, opa, generate_code, type, restrictions | kNoHiBits)) {
982 if (generate_code) {
983 if (vector_mode_ == kVector) {
984 vector_map_->Put(instruction, vector_map_->Get(opa)); // operand pass-through
985 } else {
986 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
987 }
988 }
989 return true;
990 }
991 } else if (to == Primitive::kPrimFloat && from == Primitive::kPrimInt) {
992 DCHECK_EQ(to, type);
993 // Accept int to float conversion for
994 // (1) supported int,
995 // (2) vectorizable operand.
996 if (TrySetVectorType(from, &restrictions) &&
997 VectorizeUse(node, opa, generate_code, from, restrictions)) {
998 if (generate_code) {
999 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1000 }
1001 return true;
1002 }
1003 }
1004 return false;
1005 } else if (instruction->IsNeg() || instruction->IsNot() || instruction->IsBooleanNot()) {
1006 // Accept unary operator for vectorizable operand.
1007 HInstruction* opa = instruction->InputAt(0);
1008 if (VectorizeUse(node, opa, generate_code, type, restrictions)) {
1009 if (generate_code) {
1010 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1011 }
1012 return true;
1013 }
1014 } else if (instruction->IsAdd() || instruction->IsSub() ||
1015 instruction->IsMul() || instruction->IsDiv() ||
1016 instruction->IsAnd() || instruction->IsOr() || instruction->IsXor()) {
1017 // Deal with vector restrictions.
1018 if ((instruction->IsMul() && HasVectorRestrictions(restrictions, kNoMul)) ||
1019 (instruction->IsDiv() && HasVectorRestrictions(restrictions, kNoDiv))) {
1020 return false;
1021 }
1022 // Accept binary operator for vectorizable operands.
1023 HInstruction* opa = instruction->InputAt(0);
1024 HInstruction* opb = instruction->InputAt(1);
1025 if (VectorizeUse(node, opa, generate_code, type, restrictions) &&
1026 VectorizeUse(node, opb, generate_code, type, restrictions)) {
1027 if (generate_code) {
1028 GenerateVecOp(instruction, vector_map_->Get(opa), vector_map_->Get(opb), type);
1029 }
1030 return true;
1031 }
1032 } else if (instruction->IsShl() || instruction->IsShr() || instruction->IsUShr()) {
Aart Bikf3e61ee2017-04-12 17:09:20 -07001033 // Recognize vectorization idioms.
1034 if (VectorizeHalvingAddIdiom(node, instruction, generate_code, type, restrictions)) {
1035 return true;
1036 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001037 // Deal with vector restrictions.
Aart Bik304c8a52017-05-23 11:01:13 -07001038 HInstruction* opa = instruction->InputAt(0);
1039 HInstruction* opb = instruction->InputAt(1);
1040 HInstruction* r = opa;
1041 bool is_unsigned = false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001042 if ((HasVectorRestrictions(restrictions, kNoShift)) ||
1043 (instruction->IsShr() && HasVectorRestrictions(restrictions, kNoShr))) {
1044 return false; // unsupported instruction
Aart Bik304c8a52017-05-23 11:01:13 -07001045 } else if (HasVectorRestrictions(restrictions, kNoHiBits)) {
1046 // Shifts right need extra care to account for higher order bits.
1047 // TODO: less likely shr/unsigned and ushr/signed can by flipping signess.
1048 if (instruction->IsShr() &&
1049 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || is_unsigned)) {
1050 return false; // reject, unless all operands are sign-extension narrower
1051 } else if (instruction->IsUShr() &&
1052 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || !is_unsigned)) {
1053 return false; // reject, unless all operands are zero-extension narrower
1054 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001055 }
1056 // Accept shift operator for vectorizable/invariant operands.
1057 // TODO: accept symbolic, albeit loop invariant shift factors.
Aart Bik304c8a52017-05-23 11:01:13 -07001058 DCHECK(r != nullptr);
1059 if (generate_code && vector_mode_ != kVector) { // de-idiom
1060 r = opa;
1061 }
Aart Bik50e20d52017-05-05 14:07:29 -07001062 int64_t distance = 0;
Aart Bik304c8a52017-05-23 11:01:13 -07001063 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
Aart Bik50e20d52017-05-05 14:07:29 -07001064 IsInt64AndGet(opb, /*out*/ &distance)) {
Aart Bik65ffd8e2017-05-01 16:50:45 -07001065 // Restrict shift distance to packed data type width.
1066 int64_t max_distance = Primitive::ComponentSize(type) * 8;
1067 if (0 <= distance && distance < max_distance) {
1068 if (generate_code) {
Aart Bik304c8a52017-05-23 11:01:13 -07001069 GenerateVecOp(instruction, vector_map_->Get(r), opb, type);
Aart Bik65ffd8e2017-05-01 16:50:45 -07001070 }
1071 return true;
Aart Bikf8f5a162017-02-06 15:35:29 -08001072 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001073 }
1074 } else if (instruction->IsInvokeStaticOrDirect()) {
Aart Bik6daebeb2017-04-03 14:35:41 -07001075 // Accept particular intrinsics.
1076 HInvokeStaticOrDirect* invoke = instruction->AsInvokeStaticOrDirect();
1077 switch (invoke->GetIntrinsic()) {
1078 case Intrinsics::kMathAbsInt:
1079 case Intrinsics::kMathAbsLong:
1080 case Intrinsics::kMathAbsFloat:
1081 case Intrinsics::kMathAbsDouble: {
1082 // Deal with vector restrictions.
Aart Bik304c8a52017-05-23 11:01:13 -07001083 HInstruction* opa = instruction->InputAt(0);
1084 HInstruction* r = opa;
1085 bool is_unsigned = false;
1086 if (HasVectorRestrictions(restrictions, kNoAbs)) {
Aart Bik6daebeb2017-04-03 14:35:41 -07001087 return false;
Aart Bik304c8a52017-05-23 11:01:13 -07001088 } else if (HasVectorRestrictions(restrictions, kNoHiBits) &&
1089 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || is_unsigned)) {
1090 return false; // reject, unless operand is sign-extension narrower
Aart Bik6daebeb2017-04-03 14:35:41 -07001091 }
1092 // Accept ABS(x) for vectorizable operand.
Aart Bik304c8a52017-05-23 11:01:13 -07001093 DCHECK(r != nullptr);
1094 if (generate_code && vector_mode_ != kVector) { // de-idiom
1095 r = opa;
1096 }
1097 if (VectorizeUse(node, r, generate_code, type, restrictions)) {
Aart Bik6daebeb2017-04-03 14:35:41 -07001098 if (generate_code) {
Aart Bik304c8a52017-05-23 11:01:13 -07001099 GenerateVecOp(instruction, vector_map_->Get(r), nullptr, type);
Aart Bik6daebeb2017-04-03 14:35:41 -07001100 }
1101 return true;
1102 }
1103 return false;
1104 }
Aart Bikc8e93c72017-05-10 10:49:22 -07001105 case Intrinsics::kMathMinIntInt:
1106 case Intrinsics::kMathMinLongLong:
1107 case Intrinsics::kMathMinFloatFloat:
1108 case Intrinsics::kMathMinDoubleDouble:
1109 case Intrinsics::kMathMaxIntInt:
1110 case Intrinsics::kMathMaxLongLong:
1111 case Intrinsics::kMathMaxFloatFloat:
1112 case Intrinsics::kMathMaxDoubleDouble: {
1113 // Deal with vector restrictions.
Nicolas Geoffray92316902017-05-23 08:06:07 +00001114 HInstruction* opa = instruction->InputAt(0);
1115 HInstruction* opb = instruction->InputAt(1);
Aart Bik304c8a52017-05-23 11:01:13 -07001116 HInstruction* r = opa;
1117 HInstruction* s = opb;
1118 bool is_unsigned = false;
1119 if (HasVectorRestrictions(restrictions, kNoMinMax)) {
1120 return false;
1121 } else if (HasVectorRestrictions(restrictions, kNoHiBits) &&
1122 !IsNarrowerOperands(opa, opb, type, &r, &s, &is_unsigned)) {
1123 return false; // reject, unless all operands are same-extension narrower
1124 }
1125 // Accept MIN/MAX(x, y) for vectorizable operands.
1126 DCHECK(r != nullptr && s != nullptr);
1127 if (generate_code && vector_mode_ != kVector) { // de-idiom
1128 r = opa;
1129 s = opb;
1130 }
1131 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
1132 VectorizeUse(node, s, generate_code, type, restrictions)) {
Aart Bikc8e93c72017-05-10 10:49:22 -07001133 if (generate_code) {
Aart Bik304c8a52017-05-23 11:01:13 -07001134 GenerateVecOp(
1135 instruction, vector_map_->Get(r), vector_map_->Get(s), type, is_unsigned);
Aart Bikc8e93c72017-05-10 10:49:22 -07001136 }
1137 return true;
1138 }
1139 return false;
1140 }
Aart Bik6daebeb2017-04-03 14:35:41 -07001141 default:
1142 return false;
1143 } // switch
Aart Bik281c6812016-08-26 11:31:48 -07001144 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08001145 return false;
Aart Bik281c6812016-08-26 11:31:48 -07001146}
1147
Aart Bikf8f5a162017-02-06 15:35:29 -08001148bool HLoopOptimization::TrySetVectorType(Primitive::Type type, uint64_t* restrictions) {
1149 const InstructionSetFeatures* features = compiler_driver_->GetInstructionSetFeatures();
1150 switch (compiler_driver_->GetInstructionSet()) {
1151 case kArm:
1152 case kThumb2:
Artem Serov8f7c4102017-06-21 11:21:37 +01001153 // Allow vectorization for all ARM devices, because Android assumes that
Aart Bikb29f6842017-07-28 15:58:41 -07001154 // ARM 32-bit always supports advanced SIMD (64-bit SIMD).
Artem Serov8f7c4102017-06-21 11:21:37 +01001155 switch (type) {
1156 case Primitive::kPrimBoolean:
1157 case Primitive::kPrimByte:
1158 *restrictions |= kNoDiv;
1159 return TrySetVectorLength(8);
1160 case Primitive::kPrimChar:
1161 case Primitive::kPrimShort:
1162 *restrictions |= kNoDiv | kNoStringCharAt;
1163 return TrySetVectorLength(4);
1164 case Primitive::kPrimInt:
1165 *restrictions |= kNoDiv;
1166 return TrySetVectorLength(2);
1167 default:
1168 break;
1169 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001170 return false;
1171 case kArm64:
1172 // Allow vectorization for all ARM devices, because Android assumes that
Aart Bikb29f6842017-07-28 15:58:41 -07001173 // ARMv8 AArch64 always supports advanced SIMD (128-bit SIMD).
Aart Bikf8f5a162017-02-06 15:35:29 -08001174 switch (type) {
1175 case Primitive::kPrimBoolean:
1176 case Primitive::kPrimByte:
Aart Bik304c8a52017-05-23 11:01:13 -07001177 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +01001178 return TrySetVectorLength(16);
Aart Bikf8f5a162017-02-06 15:35:29 -08001179 case Primitive::kPrimChar:
1180 case Primitive::kPrimShort:
Aart Bik304c8a52017-05-23 11:01:13 -07001181 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +01001182 return TrySetVectorLength(8);
Aart Bikf8f5a162017-02-06 15:35:29 -08001183 case Primitive::kPrimInt:
1184 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +01001185 return TrySetVectorLength(4);
Artem Serovb31f91f2017-04-05 11:31:19 +01001186 case Primitive::kPrimLong:
Aart Bikc8e93c72017-05-10 10:49:22 -07001187 *restrictions |= kNoDiv | kNoMul | kNoMinMax;
Aart Bikf8f5a162017-02-06 15:35:29 -08001188 return TrySetVectorLength(2);
1189 case Primitive::kPrimFloat:
Artem Serovd4bccf12017-04-03 18:47:32 +01001190 return TrySetVectorLength(4);
Artem Serovb31f91f2017-04-05 11:31:19 +01001191 case Primitive::kPrimDouble:
Aart Bikf8f5a162017-02-06 15:35:29 -08001192 return TrySetVectorLength(2);
1193 default:
1194 return false;
1195 }
1196 case kX86:
1197 case kX86_64:
Aart Bikb29f6842017-07-28 15:58:41 -07001198 // Allow vectorization for SSE4.1-enabled X86 devices only (128-bit SIMD).
Aart Bikf8f5a162017-02-06 15:35:29 -08001199 if (features->AsX86InstructionSetFeatures()->HasSSE4_1()) {
1200 switch (type) {
1201 case Primitive::kPrimBoolean:
1202 case Primitive::kPrimByte:
Aart Bikf3e61ee2017-04-12 17:09:20 -07001203 *restrictions |= kNoMul | kNoDiv | kNoShift | kNoAbs | kNoSignedHAdd | kNoUnroundedHAdd;
Aart Bikf8f5a162017-02-06 15:35:29 -08001204 return TrySetVectorLength(16);
1205 case Primitive::kPrimChar:
1206 case Primitive::kPrimShort:
Aart Bikf3e61ee2017-04-12 17:09:20 -07001207 *restrictions |= kNoDiv | kNoAbs | kNoSignedHAdd | kNoUnroundedHAdd;
Aart Bikf8f5a162017-02-06 15:35:29 -08001208 return TrySetVectorLength(8);
1209 case Primitive::kPrimInt:
1210 *restrictions |= kNoDiv;
1211 return TrySetVectorLength(4);
1212 case Primitive::kPrimLong:
Aart Bikc8e93c72017-05-10 10:49:22 -07001213 *restrictions |= kNoMul | kNoDiv | kNoShr | kNoAbs | kNoMinMax;
Aart Bikf8f5a162017-02-06 15:35:29 -08001214 return TrySetVectorLength(2);
1215 case Primitive::kPrimFloat:
Aart Bikc8e93c72017-05-10 10:49:22 -07001216 *restrictions |= kNoMinMax; // -0.0 vs +0.0
Aart Bikf8f5a162017-02-06 15:35:29 -08001217 return TrySetVectorLength(4);
1218 case Primitive::kPrimDouble:
Aart Bikc8e93c72017-05-10 10:49:22 -07001219 *restrictions |= kNoMinMax; // -0.0 vs +0.0
Aart Bikf8f5a162017-02-06 15:35:29 -08001220 return TrySetVectorLength(2);
1221 default:
1222 break;
1223 } // switch type
1224 }
1225 return false;
1226 case kMips:
Lena Djokic51765b02017-06-22 13:49:59 +02001227 if (features->AsMipsInstructionSetFeatures()->HasMsa()) {
1228 switch (type) {
1229 case Primitive::kPrimBoolean:
1230 case Primitive::kPrimByte:
1231 *restrictions |= kNoDiv;
1232 return TrySetVectorLength(16);
1233 case Primitive::kPrimChar:
1234 case Primitive::kPrimShort:
1235 *restrictions |= kNoDiv | kNoStringCharAt;
1236 return TrySetVectorLength(8);
1237 case Primitive::kPrimInt:
1238 *restrictions |= kNoDiv;
1239 return TrySetVectorLength(4);
1240 case Primitive::kPrimLong:
1241 *restrictions |= kNoDiv;
1242 return TrySetVectorLength(2);
1243 case Primitive::kPrimFloat:
1244 *restrictions |= kNoMinMax; // min/max(x, NaN)
1245 return TrySetVectorLength(4);
1246 case Primitive::kPrimDouble:
1247 *restrictions |= kNoMinMax; // min/max(x, NaN)
1248 return TrySetVectorLength(2);
1249 default:
1250 break;
1251 } // switch type
1252 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001253 return false;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001254 case kMips64:
1255 if (features->AsMips64InstructionSetFeatures()->HasMsa()) {
1256 switch (type) {
1257 case Primitive::kPrimBoolean:
1258 case Primitive::kPrimByte:
Goran Jakovljevic8fea1e12017-06-06 13:28:42 +02001259 *restrictions |= kNoDiv;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001260 return TrySetVectorLength(16);
1261 case Primitive::kPrimChar:
1262 case Primitive::kPrimShort:
Goran Jakovljevic8fea1e12017-06-06 13:28:42 +02001263 *restrictions |= kNoDiv | kNoStringCharAt;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001264 return TrySetVectorLength(8);
1265 case Primitive::kPrimInt:
Goran Jakovljevic8fea1e12017-06-06 13:28:42 +02001266 *restrictions |= kNoDiv;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001267 return TrySetVectorLength(4);
1268 case Primitive::kPrimLong:
Goran Jakovljevic8fea1e12017-06-06 13:28:42 +02001269 *restrictions |= kNoDiv;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001270 return TrySetVectorLength(2);
1271 case Primitive::kPrimFloat:
Goran Jakovljevic8fea1e12017-06-06 13:28:42 +02001272 *restrictions |= kNoMinMax; // min/max(x, NaN)
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001273 return TrySetVectorLength(4);
1274 case Primitive::kPrimDouble:
Goran Jakovljevic8fea1e12017-06-06 13:28:42 +02001275 *restrictions |= kNoMinMax; // min/max(x, NaN)
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001276 return TrySetVectorLength(2);
1277 default:
1278 break;
1279 } // switch type
1280 }
1281 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001282 default:
1283 return false;
1284 } // switch instruction set
1285}
1286
1287bool HLoopOptimization::TrySetVectorLength(uint32_t length) {
1288 DCHECK(IsPowerOfTwo(length) && length >= 2u);
1289 // First time set?
1290 if (vector_length_ == 0) {
1291 vector_length_ = length;
1292 }
1293 // Different types are acceptable within a loop-body, as long as all the corresponding vector
1294 // lengths match exactly to obtain a uniform traversal through the vector iteration space
1295 // (idiomatic exceptions to this rule can be handled by further unrolling sub-expressions).
1296 return vector_length_ == length;
1297}
1298
1299void HLoopOptimization::GenerateVecInv(HInstruction* org, Primitive::Type type) {
1300 if (vector_map_->find(org) == vector_map_->end()) {
1301 // In scalar code, just use a self pass-through for scalar invariants
1302 // (viz. expression remains itself).
1303 if (vector_mode_ == kSequential) {
1304 vector_map_->Put(org, org);
1305 return;
1306 }
1307 // In vector code, explicit scalar expansion is needed.
1308 HInstruction* vector = new (global_allocator_) HVecReplicateScalar(
1309 global_allocator_, org, type, vector_length_);
1310 vector_map_->Put(org, Insert(vector_preheader_, vector));
1311 }
1312}
1313
1314void HLoopOptimization::GenerateVecSub(HInstruction* org, HInstruction* offset) {
1315 if (vector_map_->find(org) == vector_map_->end()) {
Aart Bik14a68b42017-06-08 14:06:58 -07001316 HInstruction* subscript = vector_index_;
Aart Bik37dc4df2017-06-28 14:08:00 -07001317 int64_t value = 0;
1318 if (!IsInt64AndGet(offset, &value) || value != 0) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001319 subscript = new (global_allocator_) HAdd(Primitive::kPrimInt, subscript, offset);
1320 if (org->IsPhi()) {
1321 Insert(vector_body_, subscript); // lacks layout placeholder
1322 }
1323 }
1324 vector_map_->Put(org, subscript);
1325 }
1326}
1327
1328void HLoopOptimization::GenerateVecMem(HInstruction* org,
1329 HInstruction* opa,
1330 HInstruction* opb,
Aart Bik14a68b42017-06-08 14:06:58 -07001331 HInstruction* offset,
Aart Bikf8f5a162017-02-06 15:35:29 -08001332 Primitive::Type type) {
1333 HInstruction* vector = nullptr;
1334 if (vector_mode_ == kVector) {
1335 // Vector store or load.
Aart Bik14a68b42017-06-08 14:06:58 -07001336 HInstruction* base = org->InputAt(0);
Aart Bikf8f5a162017-02-06 15:35:29 -08001337 if (opb != nullptr) {
1338 vector = new (global_allocator_) HVecStore(
Aart Bik14a68b42017-06-08 14:06:58 -07001339 global_allocator_, base, opa, opb, type, vector_length_);
Aart Bikf8f5a162017-02-06 15:35:29 -08001340 } else {
Aart Bikdb14fcf2017-04-25 15:53:58 -07001341 bool is_string_char_at = org->AsArrayGet()->IsStringCharAt();
Aart Bikf8f5a162017-02-06 15:35:29 -08001342 vector = new (global_allocator_) HVecLoad(
Aart Bik14a68b42017-06-08 14:06:58 -07001343 global_allocator_, base, opa, type, vector_length_, is_string_char_at);
1344 }
1345 // Known dynamically enforced alignment?
Aart Bik14a68b42017-06-08 14:06:58 -07001346 if (vector_peeling_candidate_ != nullptr &&
1347 vector_peeling_candidate_->base == base &&
1348 vector_peeling_candidate_->offset == offset) {
1349 vector->AsVecMemoryOperation()->SetAlignment(Alignment(kAlignedBase, 0));
Aart Bikf8f5a162017-02-06 15:35:29 -08001350 }
1351 } else {
1352 // Scalar store or load.
1353 DCHECK(vector_mode_ == kSequential);
1354 if (opb != nullptr) {
1355 vector = new (global_allocator_) HArraySet(org->InputAt(0), opa, opb, type, kNoDexPc);
1356 } else {
Aart Bikdb14fcf2017-04-25 15:53:58 -07001357 bool is_string_char_at = org->AsArrayGet()->IsStringCharAt();
1358 vector = new (global_allocator_) HArrayGet(
1359 org->InputAt(0), opa, type, kNoDexPc, is_string_char_at);
Aart Bikf8f5a162017-02-06 15:35:29 -08001360 }
1361 }
1362 vector_map_->Put(org, vector);
1363}
1364
1365#define GENERATE_VEC(x, y) \
1366 if (vector_mode_ == kVector) { \
1367 vector = (x); \
1368 } else { \
1369 DCHECK(vector_mode_ == kSequential); \
1370 vector = (y); \
1371 } \
1372 break;
1373
1374void HLoopOptimization::GenerateVecOp(HInstruction* org,
1375 HInstruction* opa,
1376 HInstruction* opb,
Aart Bik304c8a52017-05-23 11:01:13 -07001377 Primitive::Type type,
1378 bool is_unsigned) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001379 if (vector_mode_ == kSequential) {
Aart Bik304c8a52017-05-23 11:01:13 -07001380 // Non-converting scalar code follows implicit integral promotion.
1381 if (!org->IsTypeConversion() && (type == Primitive::kPrimBoolean ||
1382 type == Primitive::kPrimByte ||
1383 type == Primitive::kPrimChar ||
1384 type == Primitive::kPrimShort)) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001385 type = Primitive::kPrimInt;
1386 }
1387 }
1388 HInstruction* vector = nullptr;
1389 switch (org->GetKind()) {
1390 case HInstruction::kNeg:
1391 DCHECK(opb == nullptr);
1392 GENERATE_VEC(
1393 new (global_allocator_) HVecNeg(global_allocator_, opa, type, vector_length_),
1394 new (global_allocator_) HNeg(type, opa));
1395 case HInstruction::kNot:
1396 DCHECK(opb == nullptr);
1397 GENERATE_VEC(
1398 new (global_allocator_) HVecNot(global_allocator_, opa, type, vector_length_),
1399 new (global_allocator_) HNot(type, opa));
1400 case HInstruction::kBooleanNot:
1401 DCHECK(opb == nullptr);
1402 GENERATE_VEC(
1403 new (global_allocator_) HVecNot(global_allocator_, opa, type, vector_length_),
1404 new (global_allocator_) HBooleanNot(opa));
1405 case HInstruction::kTypeConversion:
1406 DCHECK(opb == nullptr);
1407 GENERATE_VEC(
1408 new (global_allocator_) HVecCnv(global_allocator_, opa, type, vector_length_),
1409 new (global_allocator_) HTypeConversion(type, opa, kNoDexPc));
1410 case HInstruction::kAdd:
1411 GENERATE_VEC(
1412 new (global_allocator_) HVecAdd(global_allocator_, opa, opb, type, vector_length_),
1413 new (global_allocator_) HAdd(type, opa, opb));
1414 case HInstruction::kSub:
1415 GENERATE_VEC(
1416 new (global_allocator_) HVecSub(global_allocator_, opa, opb, type, vector_length_),
1417 new (global_allocator_) HSub(type, opa, opb));
1418 case HInstruction::kMul:
1419 GENERATE_VEC(
1420 new (global_allocator_) HVecMul(global_allocator_, opa, opb, type, vector_length_),
1421 new (global_allocator_) HMul(type, opa, opb));
1422 case HInstruction::kDiv:
1423 GENERATE_VEC(
1424 new (global_allocator_) HVecDiv(global_allocator_, opa, opb, type, vector_length_),
1425 new (global_allocator_) HDiv(type, opa, opb, kNoDexPc));
1426 case HInstruction::kAnd:
1427 GENERATE_VEC(
1428 new (global_allocator_) HVecAnd(global_allocator_, opa, opb, type, vector_length_),
1429 new (global_allocator_) HAnd(type, opa, opb));
1430 case HInstruction::kOr:
1431 GENERATE_VEC(
1432 new (global_allocator_) HVecOr(global_allocator_, opa, opb, type, vector_length_),
1433 new (global_allocator_) HOr(type, opa, opb));
1434 case HInstruction::kXor:
1435 GENERATE_VEC(
1436 new (global_allocator_) HVecXor(global_allocator_, opa, opb, type, vector_length_),
1437 new (global_allocator_) HXor(type, opa, opb));
1438 case HInstruction::kShl:
1439 GENERATE_VEC(
1440 new (global_allocator_) HVecShl(global_allocator_, opa, opb, type, vector_length_),
1441 new (global_allocator_) HShl(type, opa, opb));
1442 case HInstruction::kShr:
1443 GENERATE_VEC(
1444 new (global_allocator_) HVecShr(global_allocator_, opa, opb, type, vector_length_),
1445 new (global_allocator_) HShr(type, opa, opb));
1446 case HInstruction::kUShr:
1447 GENERATE_VEC(
1448 new (global_allocator_) HVecUShr(global_allocator_, opa, opb, type, vector_length_),
1449 new (global_allocator_) HUShr(type, opa, opb));
1450 case HInstruction::kInvokeStaticOrDirect: {
Aart Bik6daebeb2017-04-03 14:35:41 -07001451 HInvokeStaticOrDirect* invoke = org->AsInvokeStaticOrDirect();
1452 if (vector_mode_ == kVector) {
1453 switch (invoke->GetIntrinsic()) {
1454 case Intrinsics::kMathAbsInt:
1455 case Intrinsics::kMathAbsLong:
1456 case Intrinsics::kMathAbsFloat:
1457 case Intrinsics::kMathAbsDouble:
1458 DCHECK(opb == nullptr);
1459 vector = new (global_allocator_) HVecAbs(global_allocator_, opa, type, vector_length_);
1460 break;
Aart Bikc8e93c72017-05-10 10:49:22 -07001461 case Intrinsics::kMathMinIntInt:
1462 case Intrinsics::kMathMinLongLong:
1463 case Intrinsics::kMathMinFloatFloat:
1464 case Intrinsics::kMathMinDoubleDouble: {
Aart Bikc8e93c72017-05-10 10:49:22 -07001465 vector = new (global_allocator_)
1466 HVecMin(global_allocator_, opa, opb, type, vector_length_, is_unsigned);
1467 break;
1468 }
1469 case Intrinsics::kMathMaxIntInt:
1470 case Intrinsics::kMathMaxLongLong:
1471 case Intrinsics::kMathMaxFloatFloat:
1472 case Intrinsics::kMathMaxDoubleDouble: {
Aart Bikc8e93c72017-05-10 10:49:22 -07001473 vector = new (global_allocator_)
1474 HVecMax(global_allocator_, opa, opb, type, vector_length_, is_unsigned);
1475 break;
1476 }
Aart Bik6daebeb2017-04-03 14:35:41 -07001477 default:
1478 LOG(FATAL) << "Unsupported SIMD intrinsic";
1479 UNREACHABLE();
1480 } // switch invoke
1481 } else {
Aart Bik24b905f2017-04-06 09:59:06 -07001482 // In scalar code, simply clone the method invoke, and replace its operands with the
1483 // corresponding new scalar instructions in the loop. The instruction will get an
1484 // environment while being inserted from the instruction map in original program order.
Aart Bik6daebeb2017-04-03 14:35:41 -07001485 DCHECK(vector_mode_ == kSequential);
Aart Bik6e92fb32017-06-05 14:05:09 -07001486 size_t num_args = invoke->GetNumberOfArguments();
Aart Bik6daebeb2017-04-03 14:35:41 -07001487 HInvokeStaticOrDirect* new_invoke = new (global_allocator_) HInvokeStaticOrDirect(
1488 global_allocator_,
Aart Bik6e92fb32017-06-05 14:05:09 -07001489 num_args,
Aart Bik6daebeb2017-04-03 14:35:41 -07001490 invoke->GetType(),
1491 invoke->GetDexPc(),
1492 invoke->GetDexMethodIndex(),
1493 invoke->GetResolvedMethod(),
1494 invoke->GetDispatchInfo(),
1495 invoke->GetInvokeType(),
1496 invoke->GetTargetMethod(),
1497 invoke->GetClinitCheckRequirement());
1498 HInputsRef inputs = invoke->GetInputs();
Aart Bik6e92fb32017-06-05 14:05:09 -07001499 size_t num_inputs = inputs.size();
1500 DCHECK_LE(num_args, num_inputs);
1501 DCHECK_EQ(num_inputs, new_invoke->GetInputs().size()); // both invokes agree
1502 for (size_t index = 0; index < num_inputs; ++index) {
1503 HInstruction* new_input = index < num_args
1504 ? vector_map_->Get(inputs[index])
1505 : inputs[index]; // beyond arguments: just pass through
1506 new_invoke->SetArgumentAt(index, new_input);
Aart Bik6daebeb2017-04-03 14:35:41 -07001507 }
Aart Bik98990262017-04-10 13:15:57 -07001508 new_invoke->SetIntrinsic(invoke->GetIntrinsic(),
1509 kNeedsEnvironmentOrCache,
1510 kNoSideEffects,
1511 kNoThrow);
Aart Bik6daebeb2017-04-03 14:35:41 -07001512 vector = new_invoke;
1513 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001514 break;
1515 }
1516 default:
1517 break;
1518 } // switch
1519 CHECK(vector != nullptr) << "Unsupported SIMD operator";
1520 vector_map_->Put(org, vector);
1521}
1522
1523#undef GENERATE_VEC
1524
1525//
Aart Bikf3e61ee2017-04-12 17:09:20 -07001526// Vectorization idioms.
1527//
1528
1529// Method recognizes the following idioms:
1530// rounding halving add (a + b + 1) >> 1 for unsigned/signed operands a, b
1531// regular halving add (a + b) >> 1 for unsigned/signed operands a, b
1532// Provided that the operands are promoted to a wider form to do the arithmetic and
1533// then cast back to narrower form, the idioms can be mapped into efficient SIMD
1534// implementation that operates directly in narrower form (plus one extra bit).
1535// TODO: current version recognizes implicit byte/short/char widening only;
1536// explicit widening from int to long could be added later.
1537bool HLoopOptimization::VectorizeHalvingAddIdiom(LoopNode* node,
1538 HInstruction* instruction,
1539 bool generate_code,
1540 Primitive::Type type,
1541 uint64_t restrictions) {
1542 // Test for top level arithmetic shift right x >> 1 or logical shift right x >>> 1
Aart Bik304c8a52017-05-23 11:01:13 -07001543 // (note whether the sign bit in wider precision is shifted in has no effect
Aart Bikf3e61ee2017-04-12 17:09:20 -07001544 // on the narrow precision computed by the idiom).
Aart Bik5f805002017-05-16 16:42:41 -07001545 int64_t distance = 0;
Aart Bikf3e61ee2017-04-12 17:09:20 -07001546 if ((instruction->IsShr() ||
1547 instruction->IsUShr()) &&
Aart Bik5f805002017-05-16 16:42:41 -07001548 IsInt64AndGet(instruction->InputAt(1), /*out*/ &distance) && distance == 1) {
1549 // Test for (a + b + c) >> 1 for optional constant c.
1550 HInstruction* a = nullptr;
1551 HInstruction* b = nullptr;
1552 int64_t c = 0;
1553 if (IsAddConst(instruction->InputAt(0), /*out*/ &a, /*out*/ &b, /*out*/ &c)) {
Aart Bik304c8a52017-05-23 11:01:13 -07001554 DCHECK(a != nullptr && b != nullptr);
Aart Bik5f805002017-05-16 16:42:41 -07001555 // Accept c == 1 (rounded) or c == 0 (not rounded).
1556 bool is_rounded = false;
1557 if (c == 1) {
1558 is_rounded = true;
1559 } else if (c != 0) {
1560 return false;
1561 }
1562 // Accept consistent zero or sign extension on operands a and b.
Aart Bikf3e61ee2017-04-12 17:09:20 -07001563 HInstruction* r = nullptr;
1564 HInstruction* s = nullptr;
1565 bool is_unsigned = false;
Aart Bik304c8a52017-05-23 11:01:13 -07001566 if (!IsNarrowerOperands(a, b, type, &r, &s, &is_unsigned)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -07001567 return false;
1568 }
1569 // Deal with vector restrictions.
1570 if ((!is_unsigned && HasVectorRestrictions(restrictions, kNoSignedHAdd)) ||
1571 (!is_rounded && HasVectorRestrictions(restrictions, kNoUnroundedHAdd))) {
1572 return false;
1573 }
1574 // Accept recognized halving add for vectorizable operands. Vectorized code uses the
1575 // shorthand idiomatic operation. Sequential code uses the original scalar expressions.
1576 DCHECK(r != nullptr && s != nullptr);
Aart Bik304c8a52017-05-23 11:01:13 -07001577 if (generate_code && vector_mode_ != kVector) { // de-idiom
1578 r = instruction->InputAt(0);
1579 s = instruction->InputAt(1);
1580 }
Aart Bikf3e61ee2017-04-12 17:09:20 -07001581 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
1582 VectorizeUse(node, s, generate_code, type, restrictions)) {
1583 if (generate_code) {
1584 if (vector_mode_ == kVector) {
1585 vector_map_->Put(instruction, new (global_allocator_) HVecHalvingAdd(
1586 global_allocator_,
1587 vector_map_->Get(r),
1588 vector_map_->Get(s),
1589 type,
1590 vector_length_,
1591 is_unsigned,
1592 is_rounded));
1593 } else {
Aart Bik304c8a52017-05-23 11:01:13 -07001594 GenerateVecOp(instruction, vector_map_->Get(r), vector_map_->Get(s), type);
Aart Bikf3e61ee2017-04-12 17:09:20 -07001595 }
1596 }
1597 return true;
1598 }
1599 }
1600 }
1601 return false;
1602}
1603
1604//
Aart Bik14a68b42017-06-08 14:06:58 -07001605// Vectorization heuristics.
1606//
1607
1608bool HLoopOptimization::IsVectorizationProfitable(int64_t trip_count) {
1609 // Current heuristic: non-empty body with sufficient number
1610 // of iterations (if known).
1611 // TODO: refine by looking at e.g. operation count, alignment, etc.
1612 if (vector_length_ == 0) {
1613 return false; // nothing found
1614 } else if (0 < trip_count && trip_count < vector_length_) {
1615 return false; // insufficient iterations
1616 }
1617 return true;
1618}
1619
Aart Bikb29f6842017-07-28 15:58:41 -07001620void HLoopOptimization::SetPeelingCandidate(const ArrayReference* candidate,
1621 int64_t trip_count ATTRIBUTE_UNUSED) {
Aart Bik14a68b42017-06-08 14:06:58 -07001622 // Current heuristic: none.
1623 // TODO: implement
Aart Bikb29f6842017-07-28 15:58:41 -07001624 vector_peeling_candidate_ = candidate;
Aart Bik14a68b42017-06-08 14:06:58 -07001625}
1626
1627uint32_t HLoopOptimization::GetUnrollingFactor(HBasicBlock* block, int64_t trip_count) {
1628 // Current heuristic: unroll by 2 on ARM64/X86 for large known trip
1629 // counts and small loop bodies.
1630 // TODO: refine with operation count, remaining iterations, etc.
1631 // Artem had some really cool ideas for this already.
1632 switch (compiler_driver_->GetInstructionSet()) {
1633 case kArm64:
1634 case kX86:
1635 case kX86_64: {
1636 size_t num_instructions = block->GetInstructions().CountSize();
1637 if (num_instructions <= 10 && trip_count >= 4 * vector_length_) {
1638 return 2;
1639 }
1640 return 1;
1641 }
1642 default:
1643 return 1;
1644 }
1645}
1646
1647//
Aart Bikf8f5a162017-02-06 15:35:29 -08001648// Helpers.
1649//
1650
1651bool HLoopOptimization::TrySetPhiInduction(HPhi* phi, bool restrict_uses) {
Aart Bikb29f6842017-07-28 15:58:41 -07001652 // Start with empty phi induction.
1653 iset_->clear();
1654
Nicolas Geoffrayf57c1ae2017-06-28 17:40:18 +01001655 // Special case Phis that have equivalent in a debuggable setup. Our graph checker isn't
1656 // smart enough to follow strongly connected components (and it's probably not worth
1657 // it to make it so). See b/33775412.
1658 if (graph_->IsDebuggable() && phi->HasEquivalentPhi()) {
1659 return false;
1660 }
Aart Bikb29f6842017-07-28 15:58:41 -07001661
1662 // Lookup phi induction cycle.
Aart Bikcc42be02016-10-20 16:14:16 -07001663 ArenaSet<HInstruction*>* set = induction_range_.LookupCycle(phi);
1664 if (set != nullptr) {
1665 for (HInstruction* i : *set) {
Aart Bike3dedc52016-11-02 17:50:27 -07001666 // Check that, other than instructions that are no longer in the graph (removed earlier)
Aart Bikf8f5a162017-02-06 15:35:29 -08001667 // each instruction is removable and, when restrict uses are requested, other than for phi,
1668 // all uses are contained within the cycle.
Aart Bike3dedc52016-11-02 17:50:27 -07001669 if (!i->IsInBlock()) {
1670 continue;
1671 } else if (!i->IsRemovable()) {
1672 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001673 } else if (i != phi && restrict_uses) {
Aart Bikb29f6842017-07-28 15:58:41 -07001674 // Deal with regular uses.
Aart Bikcc42be02016-10-20 16:14:16 -07001675 for (const HUseListNode<HInstruction*>& use : i->GetUses()) {
1676 if (set->find(use.GetUser()) == set->end()) {
1677 return false;
1678 }
1679 }
1680 }
Aart Bike3dedc52016-11-02 17:50:27 -07001681 iset_->insert(i); // copy
Aart Bikcc42be02016-10-20 16:14:16 -07001682 }
Aart Bikcc42be02016-10-20 16:14:16 -07001683 return true;
1684 }
1685 return false;
1686}
1687
Aart Bikb29f6842017-07-28 15:58:41 -07001688bool HLoopOptimization::TrySetPhiReduction(HPhi* phi) {
Aart Bikcc42be02016-10-20 16:14:16 -07001689 DCHECK(iset_->empty());
Aart Bikb29f6842017-07-28 15:58:41 -07001690 // Only unclassified phi cycles are candidates for reductions.
1691 if (induction_range_.IsClassified(phi)) {
1692 return false;
1693 }
1694 // Accept operations like x = x + .., provided that the phi and the reduction are
1695 // used exactly once inside the loop, and by each other.
1696 HInputsRef inputs = phi->GetInputs();
1697 if (inputs.size() == 2) {
1698 HInstruction* reduction = inputs[1];
1699 if (HasReductionFormat(reduction, phi)) {
1700 HLoopInformation* loop_info = phi->GetBlock()->GetLoopInformation();
1701 int32_t use_count = 0;
1702 bool single_use_inside_loop =
1703 // Reduction update only used by phi.
1704 reduction->GetUses().HasExactlyOneElement() &&
1705 !reduction->HasEnvironmentUses() &&
1706 // Reduction update is only use of phi inside the loop.
1707 IsOnlyUsedAfterLoop(loop_info, phi, /*collect_loop_uses*/ true, &use_count) &&
1708 iset_->size() == 1;
1709 iset_->clear(); // leave the way you found it
1710 if (single_use_inside_loop) {
1711 // Link reduction back, and start recording feed value.
1712 reductions_->Put(reduction, phi);
1713 reductions_->Put(phi, phi->InputAt(0));
1714 return true;
1715 }
1716 }
1717 }
1718 return false;
1719}
1720
1721bool HLoopOptimization::TrySetSimpleLoopHeader(HBasicBlock* block, /*out*/ HPhi** main_phi) {
1722 // Start with empty phi induction and reductions.
1723 iset_->clear();
1724 reductions_->clear();
1725
1726 // Scan the phis to find the following (the induction structure has already
1727 // been optimized, so we don't need to worry about trivial cases):
1728 // (1) optional reductions in loop,
1729 // (2) the main induction, used in loop control.
1730 HPhi* phi = nullptr;
1731 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
1732 if (TrySetPhiReduction(it.Current()->AsPhi())) {
1733 continue;
1734 } else if (phi == nullptr) {
1735 // Found the first candidate for main induction.
1736 phi = it.Current()->AsPhi();
1737 } else {
1738 return false;
1739 }
1740 }
1741
1742 // Then test for a typical loopheader:
1743 // s: SuspendCheck
1744 // c: Condition(phi, bound)
1745 // i: If(c)
1746 if (phi != nullptr && TrySetPhiInduction(phi, /*restrict_uses*/ false)) {
Aart Bikcc42be02016-10-20 16:14:16 -07001747 HInstruction* s = block->GetFirstInstruction();
1748 if (s != nullptr && s->IsSuspendCheck()) {
1749 HInstruction* c = s->GetNext();
Aart Bikd86c0852017-04-14 12:00:15 -07001750 if (c != nullptr &&
1751 c->IsCondition() &&
1752 c->GetUses().HasExactlyOneElement() && // only used for termination
1753 !c->HasEnvironmentUses()) { // unlikely, but not impossible
Aart Bikcc42be02016-10-20 16:14:16 -07001754 HInstruction* i = c->GetNext();
1755 if (i != nullptr && i->IsIf() && i->InputAt(0) == c) {
1756 iset_->insert(c);
1757 iset_->insert(s);
Aart Bikb29f6842017-07-28 15:58:41 -07001758 *main_phi = phi;
Aart Bikcc42be02016-10-20 16:14:16 -07001759 return true;
1760 }
1761 }
1762 }
1763 }
1764 return false;
1765}
1766
1767bool HLoopOptimization::IsEmptyBody(HBasicBlock* block) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001768 if (!block->GetPhis().IsEmpty()) {
1769 return false;
1770 }
1771 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
1772 HInstruction* instruction = it.Current();
1773 if (!instruction->IsGoto() && iset_->find(instruction) == iset_->end()) {
1774 return false;
Aart Bikcc42be02016-10-20 16:14:16 -07001775 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001776 }
1777 return true;
1778}
1779
1780bool HLoopOptimization::IsUsedOutsideLoop(HLoopInformation* loop_info,
1781 HInstruction* instruction) {
Aart Bikb29f6842017-07-28 15:58:41 -07001782 // Deal with regular uses.
Aart Bikf8f5a162017-02-06 15:35:29 -08001783 for (const HUseListNode<HInstruction*>& use : instruction->GetUses()) {
1784 if (use.GetUser()->GetBlock()->GetLoopInformation() != loop_info) {
1785 return true;
1786 }
Aart Bikcc42be02016-10-20 16:14:16 -07001787 }
1788 return false;
1789}
1790
Aart Bik482095d2016-10-10 15:39:10 -07001791bool HLoopOptimization::IsOnlyUsedAfterLoop(HLoopInformation* loop_info,
Aart Bik8c4a8542016-10-06 11:36:57 -07001792 HInstruction* instruction,
Aart Bik6b69e0a2017-01-11 10:20:43 -08001793 bool collect_loop_uses,
Aart Bik8c4a8542016-10-06 11:36:57 -07001794 /*out*/ int32_t* use_count) {
Aart Bikb29f6842017-07-28 15:58:41 -07001795 // Deal with regular uses.
Aart Bik8c4a8542016-10-06 11:36:57 -07001796 for (const HUseListNode<HInstruction*>& use : instruction->GetUses()) {
1797 HInstruction* user = use.GetUser();
1798 if (iset_->find(user) == iset_->end()) { // not excluded?
1799 HLoopInformation* other_loop_info = user->GetBlock()->GetLoopInformation();
Aart Bik482095d2016-10-10 15:39:10 -07001800 if (other_loop_info != nullptr && other_loop_info->IsIn(*loop_info)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -08001801 // If collect_loop_uses is set, simply keep adding those uses to the set.
1802 // Otherwise, reject uses inside the loop that were not already in the set.
1803 if (collect_loop_uses) {
1804 iset_->insert(user);
1805 continue;
1806 }
Aart Bik8c4a8542016-10-06 11:36:57 -07001807 return false;
1808 }
1809 ++*use_count;
1810 }
1811 }
1812 return true;
1813}
1814
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01001815bool HLoopOptimization::TryReplaceWithLastValue(HLoopInformation* loop_info,
1816 HInstruction* instruction,
1817 HBasicBlock* block) {
1818 // Try to replace outside uses with the last value.
Aart Bik807868e2016-11-03 17:51:43 -07001819 if (induction_range_.CanGenerateLastValue(instruction)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -08001820 HInstruction* replacement = induction_range_.GenerateLastValue(instruction, graph_, block);
Aart Bikb29f6842017-07-28 15:58:41 -07001821 // Deal with regular uses.
Aart Bik6b69e0a2017-01-11 10:20:43 -08001822 const HUseList<HInstruction*>& uses = instruction->GetUses();
1823 for (auto it = uses.begin(), end = uses.end(); it != end;) {
1824 HInstruction* user = it->GetUser();
1825 size_t index = it->GetIndex();
1826 ++it; // increment before replacing
1827 if (iset_->find(user) == iset_->end()) { // not excluded?
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01001828 if (kIsDebugBuild) {
1829 // We have checked earlier in 'IsOnlyUsedAfterLoop' that the use is after the loop.
1830 HLoopInformation* other_loop_info = user->GetBlock()->GetLoopInformation();
1831 CHECK(other_loop_info == nullptr || !other_loop_info->IsIn(*loop_info));
1832 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08001833 user->ReplaceInput(replacement, index);
1834 induction_range_.Replace(user, instruction, replacement); // update induction
1835 }
1836 }
Aart Bikb29f6842017-07-28 15:58:41 -07001837 // Deal with environment uses.
Aart Bik6b69e0a2017-01-11 10:20:43 -08001838 const HUseList<HEnvironment*>& env_uses = instruction->GetEnvUses();
1839 for (auto it = env_uses.begin(), end = env_uses.end(); it != end;) {
1840 HEnvironment* user = it->GetUser();
1841 size_t index = it->GetIndex();
1842 ++it; // increment before replacing
1843 if (iset_->find(user->GetHolder()) == iset_->end()) { // not excluded?
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01001844 // Only update environment uses after the loop.
Aart Bik14a68b42017-06-08 14:06:58 -07001845 HLoopInformation* other_loop_info = user->GetHolder()->GetBlock()->GetLoopInformation();
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01001846 if (other_loop_info == nullptr || !other_loop_info->IsIn(*loop_info)) {
1847 user->RemoveAsUserOfInput(index);
1848 user->SetRawEnvAt(index, replacement);
1849 replacement->AddEnvUseAt(user, index);
1850 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08001851 }
1852 }
Aart Bik807868e2016-11-03 17:51:43 -07001853 return true;
Aart Bik8c4a8542016-10-06 11:36:57 -07001854 }
Aart Bik807868e2016-11-03 17:51:43 -07001855 return false;
Aart Bik8c4a8542016-10-06 11:36:57 -07001856}
1857
Aart Bikf8f5a162017-02-06 15:35:29 -08001858bool HLoopOptimization::TryAssignLastValue(HLoopInformation* loop_info,
1859 HInstruction* instruction,
1860 HBasicBlock* block,
1861 bool collect_loop_uses) {
1862 // Assigning the last value is always successful if there are no uses.
1863 // Otherwise, it succeeds in a no early-exit loop by generating the
1864 // proper last value assignment.
1865 int32_t use_count = 0;
1866 return IsOnlyUsedAfterLoop(loop_info, instruction, collect_loop_uses, &use_count) &&
1867 (use_count == 0 ||
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01001868 (!IsEarlyExit(loop_info) && TryReplaceWithLastValue(loop_info, instruction, block)));
Aart Bikf8f5a162017-02-06 15:35:29 -08001869}
1870
Aart Bik6b69e0a2017-01-11 10:20:43 -08001871void HLoopOptimization::RemoveDeadInstructions(const HInstructionList& list) {
1872 for (HBackwardInstructionIterator i(list); !i.Done(); i.Advance()) {
1873 HInstruction* instruction = i.Current();
1874 if (instruction->IsDeadAndRemovable()) {
1875 simplified_ = true;
1876 instruction->GetBlock()->RemoveInstructionOrPhi(instruction);
1877 }
1878 }
1879}
1880
Aart Bik14a68b42017-06-08 14:06:58 -07001881bool HLoopOptimization::CanRemoveCycle() {
1882 for (HInstruction* i : *iset_) {
1883 // We can never remove instructions that have environment
1884 // uses when we compile 'debuggable'.
1885 if (i->HasEnvironmentUses() && graph_->IsDebuggable()) {
1886 return false;
1887 }
1888 // A deoptimization should never have an environment input removed.
1889 for (const HUseListNode<HEnvironment*>& use : i->GetEnvUses()) {
1890 if (use.GetUser()->GetHolder()->IsDeoptimize()) {
1891 return false;
1892 }
1893 }
1894 }
1895 return true;
1896}
1897
Aart Bik281c6812016-08-26 11:31:48 -07001898} // namespace art