blob: 69c6b94c6b11e5b759f940a8536486fd053873b5 [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
Vladimir Markod5d2f2c2017-09-26 12:37:26 +010031// TODO: Clean up the packed type detection so that we have the right type straight away
32// and do not need to go through this normalization.
33static inline void NormalizePackedType(/* inout */ DataType::Type* type,
34 /* inout */ bool* is_unsigned) {
35 switch (*type) {
36 case DataType::Type::kBool:
37 DCHECK(!*is_unsigned);
38 break;
39 case DataType::Type::kUint8:
40 case DataType::Type::kInt8:
41 if (*is_unsigned) {
42 *is_unsigned = false;
43 *type = DataType::Type::kUint8;
44 } else {
45 *type = DataType::Type::kInt8;
46 }
47 break;
48 case DataType::Type::kUint16:
49 case DataType::Type::kInt16:
50 if (*is_unsigned) {
51 *is_unsigned = false;
52 *type = DataType::Type::kUint16;
53 } else {
54 *type = DataType::Type::kInt16;
55 }
56 break;
57 case DataType::Type::kInt32:
58 case DataType::Type::kInt64:
59 // We do not have kUint32 and kUint64 at the moment.
60 break;
61 case DataType::Type::kFloat32:
62 case DataType::Type::kFloat64:
63 DCHECK(!*is_unsigned);
64 break;
65 default:
66 LOG(FATAL) << "Unexpected type " << *type;
67 UNREACHABLE();
68 }
69}
70
Aart Bikf8f5a162017-02-06 15:35:29 -080071// Enables vectorization (SIMDization) in the loop optimizer.
72static constexpr bool kEnableVectorization = true;
73
Aart Bik14a68b42017-06-08 14:06:58 -070074// All current SIMD targets want 16-byte alignment.
75static constexpr size_t kAlignedBase = 16;
76
Aart Bik521b50f2017-09-09 10:44:45 -070077// No loop unrolling factor (just one copy of the loop-body).
78static constexpr uint32_t kNoUnrollingFactor = 1;
79
Aart Bik9abf8942016-10-14 09:49:42 -070080// Remove the instruction from the graph. A bit more elaborate than the usual
81// instruction removal, since there may be a cycle in the use structure.
Aart Bik281c6812016-08-26 11:31:48 -070082static void RemoveFromCycle(HInstruction* instruction) {
Aart Bik281c6812016-08-26 11:31:48 -070083 instruction->RemoveAsUserOfAllInputs();
84 instruction->RemoveEnvironmentUsers();
85 instruction->GetBlock()->RemoveInstructionOrPhi(instruction, /*ensure_safety=*/ false);
Artem Serov21c7e6f2017-07-27 16:04:42 +010086 RemoveEnvironmentUses(instruction);
87 ResetEnvironmentInputRecords(instruction);
Aart Bik281c6812016-08-26 11:31:48 -070088}
89
Aart Bik807868e2016-11-03 17:51:43 -070090// Detect a goto block and sets succ to the single successor.
Aart Bike3dedc52016-11-02 17:50:27 -070091static bool IsGotoBlock(HBasicBlock* block, /*out*/ HBasicBlock** succ) {
92 if (block->GetPredecessors().size() == 1 &&
93 block->GetSuccessors().size() == 1 &&
94 block->IsSingleGoto()) {
95 *succ = block->GetSingleSuccessor();
96 return true;
97 }
98 return false;
99}
100
Aart Bik807868e2016-11-03 17:51:43 -0700101// Detect an early exit loop.
102static bool IsEarlyExit(HLoopInformation* loop_info) {
103 HBlocksInLoopReversePostOrderIterator it_loop(*loop_info);
104 for (it_loop.Advance(); !it_loop.Done(); it_loop.Advance()) {
105 for (HBasicBlock* successor : it_loop.Current()->GetSuccessors()) {
106 if (!loop_info->Contains(*successor)) {
107 return true;
108 }
109 }
110 }
111 return false;
112}
113
Aart Bik68ca7022017-09-26 16:44:23 -0700114// Forward declaration.
115static bool IsZeroExtensionAndGet(HInstruction* instruction,
116 DataType::Type type,
Aart Bikdf011c32017-09-28 12:53:04 -0700117 /*out*/ HInstruction** operand);
Aart Bik68ca7022017-09-26 16:44:23 -0700118
Aart Bikdf011c32017-09-28 12:53:04 -0700119// Detect a sign extension in instruction from the given type.
Aart Bikdbbac8f2017-09-01 13:06:08 -0700120// Returns the promoted operand on success.
Aart Bikf3e61ee2017-04-12 17:09:20 -0700121static bool IsSignExtensionAndGet(HInstruction* instruction,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100122 DataType::Type type,
Aart Bikdf011c32017-09-28 12:53:04 -0700123 /*out*/ HInstruction** operand) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700124 // Accept any already wider constant that would be handled properly by sign
125 // extension when represented in the *width* of the given narrower data type
Aart Bikdf011c32017-09-28 12:53:04 -0700126 // (the fact that Uint16 normally zero extends does not matter here).
Aart Bikf3e61ee2017-04-12 17:09:20 -0700127 int64_t value = 0;
Aart Bik50e20d52017-05-05 14:07:29 -0700128 if (IsInt64AndGet(instruction, /*out*/ &value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700129 switch (type) {
Vladimir Markod5d2f2c2017-09-26 12:37:26 +0100130 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100131 case DataType::Type::kInt8:
Aart Bikdbbac8f2017-09-01 13:06:08 -0700132 if (IsInt<8>(value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700133 *operand = instruction;
134 return true;
135 }
136 return false;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100137 case DataType::Type::kUint16:
138 case DataType::Type::kInt16:
Aart Bikdbbac8f2017-09-01 13:06:08 -0700139 if (IsInt<16>(value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700140 *operand = instruction;
141 return true;
142 }
143 return false;
144 default:
145 return false;
146 }
147 }
Aart Bikdf011c32017-09-28 12:53:04 -0700148 // An implicit widening conversion of any signed expression sign-extends.
149 if (instruction->GetType() == type) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700150 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100151 case DataType::Type::kInt8:
152 case DataType::Type::kInt16:
Aart Bikf3e61ee2017-04-12 17:09:20 -0700153 *operand = instruction;
154 return true;
155 default:
156 return false;
157 }
158 }
Aart Bikdf011c32017-09-28 12:53:04 -0700159 // An explicit widening conversion of a signed expression sign-extends.
Aart Bik68ca7022017-09-26 16:44:23 -0700160 if (instruction->IsTypeConversion()) {
Aart Bikdf011c32017-09-28 12:53:04 -0700161 HInstruction* conv = instruction->InputAt(0);
162 DataType::Type from = conv->GetType();
Aart Bik68ca7022017-09-26 16:44:23 -0700163 switch (instruction->GetType()) {
Aart Bikdf011c32017-09-28 12:53:04 -0700164 case DataType::Type::kInt32:
Aart Bik68ca7022017-09-26 16:44:23 -0700165 case DataType::Type::kInt64:
Aart Bikdf011c32017-09-28 12:53:04 -0700166 if (type == from && (from == DataType::Type::kInt8 ||
167 from == DataType::Type::kInt16 ||
168 from == DataType::Type::kInt32)) {
169 *operand = conv;
170 return true;
171 }
172 return false;
Aart Bik68ca7022017-09-26 16:44:23 -0700173 case DataType::Type::kInt16:
174 return type == DataType::Type::kUint16 &&
175 from == DataType::Type::kUint16 &&
Aart Bikdf011c32017-09-28 12:53:04 -0700176 IsZeroExtensionAndGet(instruction->InputAt(0), type, /*out*/ operand);
Aart Bik68ca7022017-09-26 16:44:23 -0700177 default:
178 return false;
179 }
Aart Bikdbbac8f2017-09-01 13:06:08 -0700180 }
Aart Bikf3e61ee2017-04-12 17:09:20 -0700181 return false;
182}
183
Aart Bikdf011c32017-09-28 12:53:04 -0700184// Detect a zero extension in instruction from the given type.
Aart Bikdbbac8f2017-09-01 13:06:08 -0700185// Returns the promoted operand on success.
Aart Bikf3e61ee2017-04-12 17:09:20 -0700186static bool IsZeroExtensionAndGet(HInstruction* instruction,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100187 DataType::Type type,
Aart Bikdf011c32017-09-28 12:53:04 -0700188 /*out*/ HInstruction** operand) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700189 // Accept any already wider constant that would be handled properly by zero
190 // extension when represented in the *width* of the given narrower data type
Aart Bikdf011c32017-09-28 12:53:04 -0700191 // (the fact that Int8/Int16 normally sign extend does not matter here).
Aart Bikf3e61ee2017-04-12 17:09:20 -0700192 int64_t value = 0;
Aart Bik50e20d52017-05-05 14:07:29 -0700193 if (IsInt64AndGet(instruction, /*out*/ &value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700194 switch (type) {
Vladimir Markod5d2f2c2017-09-26 12:37:26 +0100195 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100196 case DataType::Type::kInt8:
Aart Bikdbbac8f2017-09-01 13:06:08 -0700197 if (IsUint<8>(value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700198 *operand = instruction;
199 return true;
200 }
201 return false;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100202 case DataType::Type::kUint16:
203 case DataType::Type::kInt16:
Aart Bikdbbac8f2017-09-01 13:06:08 -0700204 if (IsUint<16>(value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700205 *operand = instruction;
206 return true;
207 }
208 return false;
209 default:
210 return false;
211 }
212 }
Aart Bikdf011c32017-09-28 12:53:04 -0700213 // An implicit widening conversion of any unsigned expression zero-extends.
214 if (instruction->GetType() == type) {
Vladimir Markod5d2f2c2017-09-26 12:37:26 +0100215 switch (type) {
216 case DataType::Type::kUint8:
217 case DataType::Type::kUint16:
218 *operand = instruction;
219 return true;
220 default:
221 return false;
Aart Bikf3e61ee2017-04-12 17:09:20 -0700222 }
223 }
224 // A sign (or zero) extension followed by an explicit removal of just the
225 // higher sign bits is equivalent to a zero extension of the underlying operand.
Aart Bikdf011c32017-09-28 12:53:04 -0700226 //
227 // TODO: move this into simplifier and use new type system instead.
228 //
Aart Bikf3e61ee2017-04-12 17:09:20 -0700229 if (instruction->IsAnd()) {
230 int64_t mask = 0;
231 HInstruction* a = instruction->InputAt(0);
232 HInstruction* b = instruction->InputAt(1);
233 // In (a & b) find (mask & b) or (a & mask) with sign or zero extension on the non-mask.
234 if ((IsInt64AndGet(a, /*out*/ &mask) && (IsSignExtensionAndGet(b, type, /*out*/ operand) ||
235 IsZeroExtensionAndGet(b, type, /*out*/ operand))) ||
236 (IsInt64AndGet(b, /*out*/ &mask) && (IsSignExtensionAndGet(a, type, /*out*/ operand) ||
237 IsZeroExtensionAndGet(a, type, /*out*/ operand)))) {
238 switch ((*operand)->GetType()) {
Vladimir Markod5d2f2c2017-09-26 12:37:26 +0100239 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100240 case DataType::Type::kInt8:
Aart Bikdbbac8f2017-09-01 13:06:08 -0700241 return mask == std::numeric_limits<uint8_t>::max();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100242 case DataType::Type::kUint16:
243 case DataType::Type::kInt16:
Aart Bikdbbac8f2017-09-01 13:06:08 -0700244 return mask == std::numeric_limits<uint16_t>::max();
Aart Bikf3e61ee2017-04-12 17:09:20 -0700245 default: return false;
246 }
247 }
248 }
Aart Bikdf011c32017-09-28 12:53:04 -0700249 // An explicit widening conversion of an unsigned expression zero-extends.
Aart Bik68ca7022017-09-26 16:44:23 -0700250 if (instruction->IsTypeConversion()) {
Aart Bikdf011c32017-09-28 12:53:04 -0700251 HInstruction* conv = instruction->InputAt(0);
252 DataType::Type from = conv->GetType();
Aart Bik68ca7022017-09-26 16:44:23 -0700253 switch (instruction->GetType()) {
Aart Bikdf011c32017-09-28 12:53:04 -0700254 case DataType::Type::kInt32:
Aart Bik68ca7022017-09-26 16:44:23 -0700255 case DataType::Type::kInt64:
Aart Bikdf011c32017-09-28 12:53:04 -0700256 if (type == from && from == DataType::Type::kUint16) {
257 *operand = conv;
258 return true;
259 }
260 return false;
Aart Bik68ca7022017-09-26 16:44:23 -0700261 case DataType::Type::kUint16:
262 return type == DataType::Type::kInt16 &&
263 from == DataType::Type::kInt16 &&
Aart Bikdf011c32017-09-28 12:53:04 -0700264 IsSignExtensionAndGet(instruction->InputAt(0), type, /*out*/ operand);
Aart Bik68ca7022017-09-26 16:44:23 -0700265 default:
266 return false;
267 }
Aart Bikdbbac8f2017-09-01 13:06:08 -0700268 }
Aart Bikf3e61ee2017-04-12 17:09:20 -0700269 return false;
270}
271
Aart Bik304c8a52017-05-23 11:01:13 -0700272// Detect situations with same-extension narrower operands.
273// Returns true on success and sets is_unsigned accordingly.
274static bool IsNarrowerOperands(HInstruction* a,
275 HInstruction* b,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100276 DataType::Type type,
Aart Bik304c8a52017-05-23 11:01:13 -0700277 /*out*/ HInstruction** r,
278 /*out*/ HInstruction** s,
279 /*out*/ bool* is_unsigned) {
280 if (IsSignExtensionAndGet(a, type, r) && IsSignExtensionAndGet(b, type, s)) {
281 *is_unsigned = false;
282 return true;
283 } else if (IsZeroExtensionAndGet(a, type, r) && IsZeroExtensionAndGet(b, type, s)) {
284 *is_unsigned = true;
285 return true;
286 }
287 return false;
288}
289
290// As above, single operand.
291static bool IsNarrowerOperand(HInstruction* a,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100292 DataType::Type type,
Aart Bik304c8a52017-05-23 11:01:13 -0700293 /*out*/ HInstruction** r,
294 /*out*/ bool* is_unsigned) {
295 if (IsSignExtensionAndGet(a, type, r)) {
296 *is_unsigned = false;
297 return true;
298 } else if (IsZeroExtensionAndGet(a, type, r)) {
299 *is_unsigned = true;
300 return true;
301 }
302 return false;
303}
304
Aart Bikdbbac8f2017-09-01 13:06:08 -0700305// Compute relative vector length based on type difference.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100306static size_t GetOtherVL(DataType::Type other_type, DataType::Type vector_type, size_t vl) {
Vladimir Markod5d2f2c2017-09-26 12:37:26 +0100307 DCHECK(DataType::IsIntegralType(other_type));
308 DCHECK(DataType::IsIntegralType(vector_type));
309 DCHECK_GE(DataType::SizeShift(other_type), DataType::SizeShift(vector_type));
310 return vl >> (DataType::SizeShift(other_type) - DataType::SizeShift(vector_type));
Aart Bikdbbac8f2017-09-01 13:06:08 -0700311}
312
Aart Bik5f805002017-05-16 16:42:41 -0700313// Detect up to two instructions a and b, and an acccumulated constant c.
314static bool IsAddConstHelper(HInstruction* instruction,
315 /*out*/ HInstruction** a,
316 /*out*/ HInstruction** b,
317 /*out*/ int64_t* c,
318 int32_t depth) {
319 static constexpr int32_t kMaxDepth = 8; // don't search too deep
320 int64_t value = 0;
321 if (IsInt64AndGet(instruction, &value)) {
322 *c += value;
323 return true;
324 } else if (instruction->IsAdd() && depth <= kMaxDepth) {
325 return IsAddConstHelper(instruction->InputAt(0), a, b, c, depth + 1) &&
326 IsAddConstHelper(instruction->InputAt(1), a, b, c, depth + 1);
327 } else if (*a == nullptr) {
328 *a = instruction;
329 return true;
330 } else if (*b == nullptr) {
331 *b = instruction;
332 return true;
333 }
334 return false; // too many non-const operands
335}
336
337// Detect a + b + c for an optional constant c.
338static bool IsAddConst(HInstruction* instruction,
339 /*out*/ HInstruction** a,
340 /*out*/ HInstruction** b,
341 /*out*/ int64_t* c) {
342 if (instruction->IsAdd()) {
343 // Try to find a + b and accumulated c.
344 if (IsAddConstHelper(instruction->InputAt(0), a, b, c, /*depth*/ 0) &&
345 IsAddConstHelper(instruction->InputAt(1), a, b, c, /*depth*/ 0) &&
346 *b != nullptr) {
347 return true;
348 }
349 // Found a + b.
350 *a = instruction->InputAt(0);
351 *b = instruction->InputAt(1);
352 *c = 0;
353 return true;
354 }
355 return false;
356}
357
Aart Bikdf011c32017-09-28 12:53:04 -0700358// Detect a + c for constant c.
359static bool IsAddConst(HInstruction* instruction,
360 /*out*/ HInstruction** a,
361 /*out*/ int64_t* c) {
362 if (instruction->IsAdd()) {
363 if (IsInt64AndGet(instruction->InputAt(0), c)) {
364 *a = instruction->InputAt(1);
365 return true;
366 } else if (IsInt64AndGet(instruction->InputAt(1), c)) {
367 *a = instruction->InputAt(0);
368 return true;
369 }
370 }
371 return false;
372}
373
Aart Bikb29f6842017-07-28 15:58:41 -0700374// Detect reductions of the following forms,
Aart Bikb29f6842017-07-28 15:58:41 -0700375// x = x_phi + ..
376// x = x_phi - ..
377// x = max(x_phi, ..)
378// x = min(x_phi, ..)
379static bool HasReductionFormat(HInstruction* reduction, HInstruction* phi) {
380 if (reduction->IsAdd()) {
Aart Bikdbbac8f2017-09-01 13:06:08 -0700381 return (reduction->InputAt(0) == phi && reduction->InputAt(1) != phi) ||
382 (reduction->InputAt(0) != phi && reduction->InputAt(1) == phi);
Aart Bikb29f6842017-07-28 15:58:41 -0700383 } else if (reduction->IsSub()) {
Aart Bikdbbac8f2017-09-01 13:06:08 -0700384 return (reduction->InputAt(0) == phi && reduction->InputAt(1) != phi);
Aart Bikb29f6842017-07-28 15:58:41 -0700385 } else if (reduction->IsInvokeStaticOrDirect()) {
386 switch (reduction->AsInvokeStaticOrDirect()->GetIntrinsic()) {
387 case Intrinsics::kMathMinIntInt:
388 case Intrinsics::kMathMinLongLong:
389 case Intrinsics::kMathMinFloatFloat:
390 case Intrinsics::kMathMinDoubleDouble:
391 case Intrinsics::kMathMaxIntInt:
392 case Intrinsics::kMathMaxLongLong:
393 case Intrinsics::kMathMaxFloatFloat:
394 case Intrinsics::kMathMaxDoubleDouble:
Aart Bikdbbac8f2017-09-01 13:06:08 -0700395 return (reduction->InputAt(0) == phi && reduction->InputAt(1) != phi) ||
396 (reduction->InputAt(0) != phi && reduction->InputAt(1) == phi);
Aart Bikb29f6842017-07-28 15:58:41 -0700397 default:
398 return false;
399 }
400 }
401 return false;
402}
403
Aart Bikdbbac8f2017-09-01 13:06:08 -0700404// Translates vector operation to reduction kind.
405static HVecReduce::ReductionKind GetReductionKind(HVecOperation* reduction) {
406 if (reduction->IsVecAdd() || reduction->IsVecSub() || reduction->IsVecSADAccumulate()) {
Aart Bik0148de42017-09-05 09:25:01 -0700407 return HVecReduce::kSum;
408 } else if (reduction->IsVecMin()) {
409 return HVecReduce::kMin;
410 } else if (reduction->IsVecMax()) {
411 return HVecReduce::kMax;
412 }
413 LOG(FATAL) << "Unsupported SIMD reduction";
414 UNREACHABLE();
415}
416
Aart Bikf8f5a162017-02-06 15:35:29 -0800417// Test vector restrictions.
418static bool HasVectorRestrictions(uint64_t restrictions, uint64_t tested) {
419 return (restrictions & tested) != 0;
420}
421
Aart Bikf3e61ee2017-04-12 17:09:20 -0700422// Insert an instruction.
Aart Bikf8f5a162017-02-06 15:35:29 -0800423static HInstruction* Insert(HBasicBlock* block, HInstruction* instruction) {
424 DCHECK(block != nullptr);
425 DCHECK(instruction != nullptr);
426 block->InsertInstructionBefore(instruction, block->GetLastInstruction());
427 return instruction;
428}
429
Artem Serov21c7e6f2017-07-27 16:04:42 +0100430// Check that instructions from the induction sets are fully removed: have no uses
431// and no other instructions use them.
Vladimir Markoca6fff82017-10-03 14:49:14 +0100432static bool CheckInductionSetFullyRemoved(ScopedArenaSet<HInstruction*>* iset) {
Artem Serov21c7e6f2017-07-27 16:04:42 +0100433 for (HInstruction* instr : *iset) {
434 if (instr->GetBlock() != nullptr ||
435 !instr->GetUses().empty() ||
436 !instr->GetEnvUses().empty() ||
437 HasEnvironmentUsedByOthers(instr)) {
438 return false;
439 }
440 }
Artem Serov21c7e6f2017-07-27 16:04:42 +0100441 return true;
442}
443
Aart Bik281c6812016-08-26 11:31:48 -0700444//
Aart Bikb29f6842017-07-28 15:58:41 -0700445// Public methods.
Aart Bik281c6812016-08-26 11:31:48 -0700446//
447
448HLoopOptimization::HLoopOptimization(HGraph* graph,
Aart Bik92685a82017-03-06 11:13:43 -0800449 CompilerDriver* compiler_driver,
Aart Bikb92cc332017-09-06 15:53:17 -0700450 HInductionVarAnalysis* induction_analysis,
451 OptimizingCompilerStats* stats)
452 : HOptimization(graph, kLoopOptimizationPassName, stats),
Aart Bik92685a82017-03-06 11:13:43 -0800453 compiler_driver_(compiler_driver),
Aart Bik281c6812016-08-26 11:31:48 -0700454 induction_range_(induction_analysis),
Aart Bik96202302016-10-04 17:33:56 -0700455 loop_allocator_(nullptr),
Vladimir Markoca6fff82017-10-03 14:49:14 +0100456 global_allocator_(graph_->GetAllocator()),
Aart Bik281c6812016-08-26 11:31:48 -0700457 top_loop_(nullptr),
Aart Bik8c4a8542016-10-06 11:36:57 -0700458 last_loop_(nullptr),
Aart Bik482095d2016-10-10 15:39:10 -0700459 iset_(nullptr),
Aart Bikb29f6842017-07-28 15:58:41 -0700460 reductions_(nullptr),
Aart Bikf8f5a162017-02-06 15:35:29 -0800461 simplified_(false),
462 vector_length_(0),
463 vector_refs_(nullptr),
Aart Bik14a68b42017-06-08 14:06:58 -0700464 vector_peeling_candidate_(nullptr),
465 vector_runtime_test_a_(nullptr),
466 vector_runtime_test_b_(nullptr),
Aart Bik0148de42017-09-05 09:25:01 -0700467 vector_map_(nullptr),
Vladimir Markoca6fff82017-10-03 14:49:14 +0100468 vector_permanent_map_(nullptr),
469 vector_mode_(kSequential),
470 vector_preheader_(nullptr),
471 vector_header_(nullptr),
472 vector_body_(nullptr),
473 vector_index_(nullptr) {
Aart Bik281c6812016-08-26 11:31:48 -0700474}
475
476void HLoopOptimization::Run() {
Mingyao Yang01b47b02017-02-03 12:09:57 -0800477 // Skip if there is no loop or the graph has try-catch/irreducible loops.
Aart Bik281c6812016-08-26 11:31:48 -0700478 // TODO: make this less of a sledgehammer.
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800479 if (!graph_->HasLoops() || graph_->HasTryCatch() || graph_->HasIrreducibleLoops()) {
Aart Bik281c6812016-08-26 11:31:48 -0700480 return;
481 }
482
Vladimir Markoca6fff82017-10-03 14:49:14 +0100483 // Phase-local allocator.
484 ScopedArenaAllocator allocator(graph_->GetArenaStack());
Aart Bik96202302016-10-04 17:33:56 -0700485 loop_allocator_ = &allocator;
Nicolas Geoffrayebe16742016-10-05 09:55:42 +0100486
Aart Bik96202302016-10-04 17:33:56 -0700487 // Perform loop optimizations.
488 LocalRun();
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800489 if (top_loop_ == nullptr) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800490 graph_->SetHasLoops(false); // no more loops
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800491 }
492
Aart Bik96202302016-10-04 17:33:56 -0700493 // Detach.
494 loop_allocator_ = nullptr;
495 last_loop_ = top_loop_ = nullptr;
496}
497
Aart Bikb29f6842017-07-28 15:58:41 -0700498//
499// Loop setup and traversal.
500//
501
Aart Bik96202302016-10-04 17:33:56 -0700502void HLoopOptimization::LocalRun() {
503 // Build the linear order using the phase-local allocator. This step enables building
504 // a loop hierarchy that properly reflects the outer-inner and previous-next relation.
Vladimir Markoca6fff82017-10-03 14:49:14 +0100505 ScopedArenaVector<HBasicBlock*> linear_order(loop_allocator_->Adapter(kArenaAllocLinearOrder));
506 LinearizeGraph(graph_, &linear_order);
Aart Bik96202302016-10-04 17:33:56 -0700507
Aart Bik281c6812016-08-26 11:31:48 -0700508 // Build the loop hierarchy.
Aart Bik96202302016-10-04 17:33:56 -0700509 for (HBasicBlock* block : linear_order) {
Aart Bik281c6812016-08-26 11:31:48 -0700510 if (block->IsLoopHeader()) {
511 AddLoop(block->GetLoopInformation());
512 }
513 }
Aart Bik96202302016-10-04 17:33:56 -0700514
Aart Bik8c4a8542016-10-06 11:36:57 -0700515 // Traverse the loop hierarchy inner-to-outer and optimize. Traversal can use
Aart Bikf8f5a162017-02-06 15:35:29 -0800516 // temporary data structures using the phase-local allocator. All new HIR
517 // should use the global allocator.
Aart Bik8c4a8542016-10-06 11:36:57 -0700518 if (top_loop_ != nullptr) {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100519 ScopedArenaSet<HInstruction*> iset(loop_allocator_->Adapter(kArenaAllocLoopOptimization));
520 ScopedArenaSafeMap<HInstruction*, HInstruction*> reds(
Aart Bikb29f6842017-07-28 15:58:41 -0700521 std::less<HInstruction*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
Vladimir Markoca6fff82017-10-03 14:49:14 +0100522 ScopedArenaSet<ArrayReference> refs(loop_allocator_->Adapter(kArenaAllocLoopOptimization));
523 ScopedArenaSafeMap<HInstruction*, HInstruction*> map(
Aart Bikf8f5a162017-02-06 15:35:29 -0800524 std::less<HInstruction*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
Vladimir Markoca6fff82017-10-03 14:49:14 +0100525 ScopedArenaSafeMap<HInstruction*, HInstruction*> perm(
Aart Bik0148de42017-09-05 09:25:01 -0700526 std::less<HInstruction*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
Aart Bikf8f5a162017-02-06 15:35:29 -0800527 // Attach.
Aart Bik8c4a8542016-10-06 11:36:57 -0700528 iset_ = &iset;
Aart Bikb29f6842017-07-28 15:58:41 -0700529 reductions_ = &reds;
Aart Bikf8f5a162017-02-06 15:35:29 -0800530 vector_refs_ = &refs;
531 vector_map_ = &map;
Aart Bik0148de42017-09-05 09:25:01 -0700532 vector_permanent_map_ = &perm;
Aart Bikf8f5a162017-02-06 15:35:29 -0800533 // Traverse.
Aart Bik8c4a8542016-10-06 11:36:57 -0700534 TraverseLoopsInnerToOuter(top_loop_);
Aart Bikf8f5a162017-02-06 15:35:29 -0800535 // Detach.
536 iset_ = nullptr;
Aart Bikb29f6842017-07-28 15:58:41 -0700537 reductions_ = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800538 vector_refs_ = nullptr;
539 vector_map_ = nullptr;
Aart Bik0148de42017-09-05 09:25:01 -0700540 vector_permanent_map_ = nullptr;
Aart Bik8c4a8542016-10-06 11:36:57 -0700541 }
Aart Bik281c6812016-08-26 11:31:48 -0700542}
543
544void HLoopOptimization::AddLoop(HLoopInformation* loop_info) {
545 DCHECK(loop_info != nullptr);
Aart Bikf8f5a162017-02-06 15:35:29 -0800546 LoopNode* node = new (loop_allocator_) LoopNode(loop_info);
Aart Bik281c6812016-08-26 11:31:48 -0700547 if (last_loop_ == nullptr) {
548 // First loop.
549 DCHECK(top_loop_ == nullptr);
550 last_loop_ = top_loop_ = node;
551 } else if (loop_info->IsIn(*last_loop_->loop_info)) {
552 // Inner loop.
553 node->outer = last_loop_;
554 DCHECK(last_loop_->inner == nullptr);
555 last_loop_ = last_loop_->inner = node;
556 } else {
557 // Subsequent loop.
558 while (last_loop_->outer != nullptr && !loop_info->IsIn(*last_loop_->outer->loop_info)) {
559 last_loop_ = last_loop_->outer;
560 }
561 node->outer = last_loop_->outer;
562 node->previous = last_loop_;
563 DCHECK(last_loop_->next == nullptr);
564 last_loop_ = last_loop_->next = node;
565 }
566}
567
568void HLoopOptimization::RemoveLoop(LoopNode* node) {
569 DCHECK(node != nullptr);
Aart Bik8c4a8542016-10-06 11:36:57 -0700570 DCHECK(node->inner == nullptr);
571 if (node->previous != nullptr) {
572 // Within sequence.
573 node->previous->next = node->next;
574 if (node->next != nullptr) {
575 node->next->previous = node->previous;
576 }
577 } else {
578 // First of sequence.
579 if (node->outer != nullptr) {
580 node->outer->inner = node->next;
581 } else {
582 top_loop_ = node->next;
583 }
584 if (node->next != nullptr) {
585 node->next->outer = node->outer;
586 node->next->previous = nullptr;
587 }
588 }
Aart Bik281c6812016-08-26 11:31:48 -0700589}
590
Aart Bikb29f6842017-07-28 15:58:41 -0700591bool HLoopOptimization::TraverseLoopsInnerToOuter(LoopNode* node) {
592 bool changed = false;
Aart Bik281c6812016-08-26 11:31:48 -0700593 for ( ; node != nullptr; node = node->next) {
Aart Bikb29f6842017-07-28 15:58:41 -0700594 // Visit inner loops first. Recompute induction information for this
595 // loop if the induction of any inner loop has changed.
596 if (TraverseLoopsInnerToOuter(node->inner)) {
Aart Bik482095d2016-10-10 15:39:10 -0700597 induction_range_.ReVisit(node->loop_info);
598 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800599 // Repeat simplifications in the loop-body until no more changes occur.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800600 // Note that since each simplification consists of eliminating code (without
601 // introducing new code), this process is always finite.
Aart Bikdf7822e2016-12-06 10:05:30 -0800602 do {
603 simplified_ = false;
Aart Bikdf7822e2016-12-06 10:05:30 -0800604 SimplifyInduction(node);
Aart Bik6b69e0a2017-01-11 10:20:43 -0800605 SimplifyBlocks(node);
Aart Bikb29f6842017-07-28 15:58:41 -0700606 changed = simplified_ || changed;
Aart Bikdf7822e2016-12-06 10:05:30 -0800607 } while (simplified_);
Aart Bikf8f5a162017-02-06 15:35:29 -0800608 // Optimize inner loop.
Aart Bik9abf8942016-10-14 09:49:42 -0700609 if (node->inner == nullptr) {
Aart Bikb29f6842017-07-28 15:58:41 -0700610 changed = OptimizeInnerLoop(node) || changed;
Aart Bik9abf8942016-10-14 09:49:42 -0700611 }
Aart Bik281c6812016-08-26 11:31:48 -0700612 }
Aart Bikb29f6842017-07-28 15:58:41 -0700613 return changed;
Aart Bik281c6812016-08-26 11:31:48 -0700614}
615
Aart Bikf8f5a162017-02-06 15:35:29 -0800616//
617// Optimization.
618//
619
Aart Bik281c6812016-08-26 11:31:48 -0700620void HLoopOptimization::SimplifyInduction(LoopNode* node) {
621 HBasicBlock* header = node->loop_info->GetHeader();
622 HBasicBlock* preheader = node->loop_info->GetPreHeader();
Aart Bik8c4a8542016-10-06 11:36:57 -0700623 // Scan the phis in the header to find opportunities to simplify an induction
624 // cycle that is only used outside the loop. Replace these uses, if any, with
625 // the last value and remove the induction cycle.
626 // Examples: for (int i = 0; x != null; i++) { .... no i .... }
627 // for (int i = 0; i < 10; i++, k++) { .... no k .... } return k;
Aart Bik281c6812016-08-26 11:31:48 -0700628 for (HInstructionIterator it(header->GetPhis()); !it.Done(); it.Advance()) {
629 HPhi* phi = it.Current()->AsPhi();
Aart Bikf8f5a162017-02-06 15:35:29 -0800630 if (TrySetPhiInduction(phi, /*restrict_uses*/ true) &&
631 TryAssignLastValue(node->loop_info, phi, preheader, /*collect_loop_uses*/ false)) {
Aart Bik671e48a2017-08-09 13:16:56 -0700632 // Note that it's ok to have replaced uses after the loop with the last value, without
633 // being able to remove the cycle. Environment uses (which are the reason we may not be
634 // able to remove the cycle) within the loop will still hold the right value. We must
635 // have tried first, however, to replace outside uses.
636 if (CanRemoveCycle()) {
637 simplified_ = true;
638 for (HInstruction* i : *iset_) {
639 RemoveFromCycle(i);
640 }
641 DCHECK(CheckInductionSetFullyRemoved(iset_));
Aart Bik281c6812016-08-26 11:31:48 -0700642 }
Aart Bik482095d2016-10-10 15:39:10 -0700643 }
644 }
645}
646
647void HLoopOptimization::SimplifyBlocks(LoopNode* node) {
Aart Bikdf7822e2016-12-06 10:05:30 -0800648 // Iterate over all basic blocks in the loop-body.
649 for (HBlocksInLoopIterator it(*node->loop_info); !it.Done(); it.Advance()) {
650 HBasicBlock* block = it.Current();
651 // Remove dead instructions from the loop-body.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800652 RemoveDeadInstructions(block->GetPhis());
653 RemoveDeadInstructions(block->GetInstructions());
Aart Bikdf7822e2016-12-06 10:05:30 -0800654 // Remove trivial control flow blocks from the loop-body.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800655 if (block->GetPredecessors().size() == 1 &&
656 block->GetSuccessors().size() == 1 &&
657 block->GetSingleSuccessor()->GetPredecessors().size() == 1) {
Aart Bikdf7822e2016-12-06 10:05:30 -0800658 simplified_ = true;
Aart Bik6b69e0a2017-01-11 10:20:43 -0800659 block->MergeWith(block->GetSingleSuccessor());
Aart Bikdf7822e2016-12-06 10:05:30 -0800660 } else if (block->GetSuccessors().size() == 2) {
661 // Trivial if block can be bypassed to either branch.
662 HBasicBlock* succ0 = block->GetSuccessors()[0];
663 HBasicBlock* succ1 = block->GetSuccessors()[1];
664 HBasicBlock* meet0 = nullptr;
665 HBasicBlock* meet1 = nullptr;
666 if (succ0 != succ1 &&
667 IsGotoBlock(succ0, &meet0) &&
668 IsGotoBlock(succ1, &meet1) &&
669 meet0 == meet1 && // meets again
670 meet0 != block && // no self-loop
671 meet0->GetPhis().IsEmpty()) { // not used for merging
672 simplified_ = true;
673 succ0->DisconnectAndDelete();
674 if (block->Dominates(meet0)) {
675 block->RemoveDominatedBlock(meet0);
676 succ1->AddDominatedBlock(meet0);
677 meet0->SetDominator(succ1);
Aart Bike3dedc52016-11-02 17:50:27 -0700678 }
Aart Bik482095d2016-10-10 15:39:10 -0700679 }
Aart Bik281c6812016-08-26 11:31:48 -0700680 }
Aart Bikdf7822e2016-12-06 10:05:30 -0800681 }
Aart Bik281c6812016-08-26 11:31:48 -0700682}
683
Aart Bikb29f6842017-07-28 15:58:41 -0700684bool HLoopOptimization::OptimizeInnerLoop(LoopNode* node) {
Aart Bik281c6812016-08-26 11:31:48 -0700685 HBasicBlock* header = node->loop_info->GetHeader();
686 HBasicBlock* preheader = node->loop_info->GetPreHeader();
Aart Bik9abf8942016-10-14 09:49:42 -0700687 // Ensure loop header logic is finite.
Aart Bikf8f5a162017-02-06 15:35:29 -0800688 int64_t trip_count = 0;
689 if (!induction_range_.IsFinite(node->loop_info, &trip_count)) {
Aart Bikb29f6842017-07-28 15:58:41 -0700690 return false;
Aart Bik9abf8942016-10-14 09:49:42 -0700691 }
Aart Bik281c6812016-08-26 11:31:48 -0700692 // Ensure there is only a single loop-body (besides the header).
693 HBasicBlock* body = nullptr;
694 for (HBlocksInLoopIterator it(*node->loop_info); !it.Done(); it.Advance()) {
695 if (it.Current() != header) {
696 if (body != nullptr) {
Aart Bikb29f6842017-07-28 15:58:41 -0700697 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700698 }
699 body = it.Current();
700 }
701 }
Andreas Gampef45d61c2017-06-07 10:29:33 -0700702 CHECK(body != nullptr);
Aart Bik281c6812016-08-26 11:31:48 -0700703 // Ensure there is only a single exit point.
704 if (header->GetSuccessors().size() != 2) {
Aart Bikb29f6842017-07-28 15:58:41 -0700705 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700706 }
707 HBasicBlock* exit = (header->GetSuccessors()[0] == body)
708 ? header->GetSuccessors()[1]
709 : header->GetSuccessors()[0];
Aart Bik8c4a8542016-10-06 11:36:57 -0700710 // Ensure exit can only be reached by exiting loop.
Aart Bik281c6812016-08-26 11:31:48 -0700711 if (exit->GetPredecessors().size() != 1) {
Aart Bikb29f6842017-07-28 15:58:41 -0700712 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700713 }
Aart Bik6b69e0a2017-01-11 10:20:43 -0800714 // Detect either an empty loop (no side effects other than plain iteration) or
715 // a trivial loop (just iterating once). Replace subsequent index uses, if any,
716 // with the last value and remove the loop, possibly after unrolling its body.
Aart Bikb29f6842017-07-28 15:58:41 -0700717 HPhi* main_phi = nullptr;
718 if (TrySetSimpleLoopHeader(header, &main_phi)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -0800719 bool is_empty = IsEmptyBody(body);
Aart Bikb29f6842017-07-28 15:58:41 -0700720 if (reductions_->empty() && // TODO: possible with some effort
721 (is_empty || trip_count == 1) &&
722 TryAssignLastValue(node->loop_info, main_phi, preheader, /*collect_loop_uses*/ true)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -0800723 if (!is_empty) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800724 // Unroll the loop-body, which sees initial value of the index.
Aart Bikb29f6842017-07-28 15:58:41 -0700725 main_phi->ReplaceWith(main_phi->InputAt(0));
Aart Bik6b69e0a2017-01-11 10:20:43 -0800726 preheader->MergeInstructionsWith(body);
727 }
728 body->DisconnectAndDelete();
729 exit->RemovePredecessor(header);
730 header->RemoveSuccessor(exit);
731 header->RemoveDominatedBlock(exit);
732 header->DisconnectAndDelete();
733 preheader->AddSuccessor(exit);
Aart Bikf8f5a162017-02-06 15:35:29 -0800734 preheader->AddInstruction(new (global_allocator_) HGoto());
Aart Bik6b69e0a2017-01-11 10:20:43 -0800735 preheader->AddDominatedBlock(exit);
736 exit->SetDominator(preheader);
737 RemoveLoop(node); // update hierarchy
Aart Bikb29f6842017-07-28 15:58:41 -0700738 return true;
Aart Bikf8f5a162017-02-06 15:35:29 -0800739 }
740 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800741 // Vectorize loop, if possible and valid.
Aart Bikb29f6842017-07-28 15:58:41 -0700742 if (kEnableVectorization &&
743 TrySetSimpleLoopHeader(header, &main_phi) &&
Aart Bikb29f6842017-07-28 15:58:41 -0700744 ShouldVectorize(node, body, trip_count) &&
745 TryAssignLastValue(node->loop_info, main_phi, preheader, /*collect_loop_uses*/ true)) {
746 Vectorize(node, body, exit, trip_count);
747 graph_->SetHasSIMD(true); // flag SIMD usage
Aart Bik21b85922017-09-06 13:29:16 -0700748 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorized);
Aart Bikb29f6842017-07-28 15:58:41 -0700749 return true;
Aart Bikf8f5a162017-02-06 15:35:29 -0800750 }
Aart Bikb29f6842017-07-28 15:58:41 -0700751 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -0800752}
753
754//
755// Loop vectorization. The implementation is based on the book by Aart J.C. Bik:
756// "The Software Vectorization Handbook. Applying Multimedia Extensions for Maximum Performance."
757// Intel Press, June, 2004 (http://www.aartbik.com/).
758//
759
Aart Bik14a68b42017-06-08 14:06:58 -0700760bool HLoopOptimization::ShouldVectorize(LoopNode* node, HBasicBlock* block, int64_t trip_count) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800761 // Reset vector bookkeeping.
762 vector_length_ = 0;
763 vector_refs_->clear();
Aart Bik14a68b42017-06-08 14:06:58 -0700764 vector_peeling_candidate_ = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800765 vector_runtime_test_a_ =
766 vector_runtime_test_b_= nullptr;
767
768 // Phis in the loop-body prevent vectorization.
769 if (!block->GetPhis().IsEmpty()) {
770 return false;
771 }
772
773 // Scan the loop-body, starting a right-hand-side tree traversal at each left-hand-side
774 // occurrence, which allows passing down attributes down the use tree.
775 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
776 if (!VectorizeDef(node, it.Current(), /*generate_code*/ false)) {
777 return false; // failure to vectorize a left-hand-side
778 }
779 }
780
Aart Bik14a68b42017-06-08 14:06:58 -0700781 // Does vectorization seem profitable?
782 if (!IsVectorizationProfitable(trip_count)) {
783 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -0800784 }
785
786 // Data dependence analysis. Find each pair of references with same type, where
787 // at least one is a write. Each such pair denotes a possible data dependence.
788 // This analysis exploits the property that differently typed arrays cannot be
789 // aliased, as well as the property that references either point to the same
790 // array or to two completely disjoint arrays, i.e., no partial aliasing.
791 // Other than a few simply heuristics, no detailed subscript analysis is done.
Aart Bikb29f6842017-07-28 15:58:41 -0700792 // The scan over references also finds a suitable dynamic loop peeling candidate.
793 const ArrayReference* candidate = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800794 for (auto i = vector_refs_->begin(); i != vector_refs_->end(); ++i) {
795 for (auto j = i; ++j != vector_refs_->end(); ) {
796 if (i->type == j->type && (i->lhs || j->lhs)) {
797 // Found same-typed a[i+x] vs. b[i+y], where at least one is a write.
798 HInstruction* a = i->base;
799 HInstruction* b = j->base;
800 HInstruction* x = i->offset;
801 HInstruction* y = j->offset;
802 if (a == b) {
803 // Found a[i+x] vs. a[i+y]. Accept if x == y (loop-independent data dependence).
804 // Conservatively assume a loop-carried data dependence otherwise, and reject.
805 if (x != y) {
806 return false;
807 }
808 } else {
809 // Found a[i+x] vs. b[i+y]. Accept if x == y (at worst loop-independent data dependence).
810 // Conservatively assume a potential loop-carried data dependence otherwise, avoided by
811 // generating an explicit a != b disambiguation runtime test on the two references.
812 if (x != y) {
Aart Bik37dc4df2017-06-28 14:08:00 -0700813 // To avoid excessive overhead, we only accept one a != b test.
814 if (vector_runtime_test_a_ == nullptr) {
815 // First test found.
816 vector_runtime_test_a_ = a;
817 vector_runtime_test_b_ = b;
818 } else if ((vector_runtime_test_a_ != a || vector_runtime_test_b_ != b) &&
819 (vector_runtime_test_a_ != b || vector_runtime_test_b_ != a)) {
820 return false; // second test would be needed
Aart Bikf8f5a162017-02-06 15:35:29 -0800821 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800822 }
823 }
824 }
825 }
826 }
827
Aart Bik14a68b42017-06-08 14:06:58 -0700828 // Consider dynamic loop peeling for alignment.
Aart Bikb29f6842017-07-28 15:58:41 -0700829 SetPeelingCandidate(candidate, trip_count);
Aart Bik14a68b42017-06-08 14:06:58 -0700830
Aart Bikf8f5a162017-02-06 15:35:29 -0800831 // Success!
832 return true;
833}
834
835void HLoopOptimization::Vectorize(LoopNode* node,
836 HBasicBlock* block,
837 HBasicBlock* exit,
838 int64_t trip_count) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800839 HBasicBlock* header = node->loop_info->GetHeader();
840 HBasicBlock* preheader = node->loop_info->GetPreHeader();
841
Aart Bik14a68b42017-06-08 14:06:58 -0700842 // Pick a loop unrolling factor for the vector loop.
843 uint32_t unroll = GetUnrollingFactor(block, trip_count);
844 uint32_t chunk = vector_length_ * unroll;
845
846 // A cleanup loop is needed, at least, for any unknown trip count or
847 // for a known trip count with remainder iterations after vectorization.
848 bool needs_cleanup = trip_count == 0 || (trip_count % chunk) != 0;
Aart Bikf8f5a162017-02-06 15:35:29 -0800849
850 // Adjust vector bookkeeping.
Aart Bikb29f6842017-07-28 15:58:41 -0700851 HPhi* main_phi = nullptr;
852 bool is_simple_loop_header = TrySetSimpleLoopHeader(header, &main_phi); // refills sets
Aart Bikf8f5a162017-02-06 15:35:29 -0800853 DCHECK(is_simple_loop_header);
Aart Bik14a68b42017-06-08 14:06:58 -0700854 vector_header_ = header;
855 vector_body_ = block;
Aart Bikf8f5a162017-02-06 15:35:29 -0800856
Aart Bikdbbac8f2017-09-01 13:06:08 -0700857 // Loop induction type.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100858 DataType::Type induc_type = main_phi->GetType();
859 DCHECK(induc_type == DataType::Type::kInt32 || induc_type == DataType::Type::kInt64)
860 << induc_type;
Aart Bikdbbac8f2017-09-01 13:06:08 -0700861
Aart Bikb29f6842017-07-28 15:58:41 -0700862 // Generate dynamic loop peeling trip count, if needed, under the assumption
863 // that the Android runtime guarantees at least "component size" alignment:
864 // ptc = (ALIGN - (&a[initial] % ALIGN)) / type-size
Aart Bik14a68b42017-06-08 14:06:58 -0700865 HInstruction* ptc = nullptr;
866 if (vector_peeling_candidate_ != nullptr) {
867 DCHECK_LT(vector_length_, trip_count) << "dynamic peeling currently requires known trip count";
868 //
869 // TODO: Implement this. Compute address of first access memory location and
870 // compute peeling factor to obtain kAlignedBase alignment.
871 //
872 needs_cleanup = true;
873 }
874
875 // Generate loop control:
Aart Bikf8f5a162017-02-06 15:35:29 -0800876 // stc = <trip-count>;
Aart Bik14a68b42017-06-08 14:06:58 -0700877 // vtc = stc - (stc - ptc) % chunk;
878 // i = 0;
Aart Bikf8f5a162017-02-06 15:35:29 -0800879 HInstruction* stc = induction_range_.GenerateTripCount(node->loop_info, graph_, preheader);
880 HInstruction* vtc = stc;
881 if (needs_cleanup) {
Aart Bik14a68b42017-06-08 14:06:58 -0700882 DCHECK(IsPowerOfTwo(chunk));
883 HInstruction* diff = stc;
884 if (ptc != nullptr) {
885 diff = Insert(preheader, new (global_allocator_) HSub(induc_type, stc, ptc));
886 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800887 HInstruction* rem = Insert(
888 preheader, new (global_allocator_) HAnd(induc_type,
Aart Bik14a68b42017-06-08 14:06:58 -0700889 diff,
Aart Bikdbbac8f2017-09-01 13:06:08 -0700890 graph_->GetConstant(induc_type, chunk - 1)));
Aart Bikf8f5a162017-02-06 15:35:29 -0800891 vtc = Insert(preheader, new (global_allocator_) HSub(induc_type, stc, rem));
892 }
Aart Bikdbbac8f2017-09-01 13:06:08 -0700893 vector_index_ = graph_->GetConstant(induc_type, 0);
Aart Bikf8f5a162017-02-06 15:35:29 -0800894
895 // Generate runtime disambiguation test:
896 // vtc = a != b ? vtc : 0;
897 if (vector_runtime_test_a_ != nullptr) {
898 HInstruction* rt = Insert(
899 preheader,
900 new (global_allocator_) HNotEqual(vector_runtime_test_a_, vector_runtime_test_b_));
901 vtc = Insert(preheader,
Aart Bikdbbac8f2017-09-01 13:06:08 -0700902 new (global_allocator_)
903 HSelect(rt, vtc, graph_->GetConstant(induc_type, 0), kNoDexPc));
Aart Bikf8f5a162017-02-06 15:35:29 -0800904 needs_cleanup = true;
905 }
906
Aart Bik14a68b42017-06-08 14:06:58 -0700907 // Generate dynamic peeling loop for alignment, if needed:
908 // for ( ; i < ptc; i += 1)
909 // <loop-body>
910 if (ptc != nullptr) {
911 vector_mode_ = kSequential;
912 GenerateNewLoop(node,
913 block,
914 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
915 vector_index_,
916 ptc,
Aart Bikdbbac8f2017-09-01 13:06:08 -0700917 graph_->GetConstant(induc_type, 1),
Aart Bik521b50f2017-09-09 10:44:45 -0700918 kNoUnrollingFactor);
Aart Bik14a68b42017-06-08 14:06:58 -0700919 }
920
921 // Generate vector loop, possibly further unrolled:
922 // for ( ; i < vtc; i += chunk)
Aart Bikf8f5a162017-02-06 15:35:29 -0800923 // <vectorized-loop-body>
924 vector_mode_ = kVector;
925 GenerateNewLoop(node,
926 block,
Aart Bik14a68b42017-06-08 14:06:58 -0700927 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
928 vector_index_,
Aart Bikf8f5a162017-02-06 15:35:29 -0800929 vtc,
Aart Bikdbbac8f2017-09-01 13:06:08 -0700930 graph_->GetConstant(induc_type, vector_length_), // increment per unroll
Aart Bik14a68b42017-06-08 14:06:58 -0700931 unroll);
Aart Bikf8f5a162017-02-06 15:35:29 -0800932 HLoopInformation* vloop = vector_header_->GetLoopInformation();
933
934 // Generate cleanup loop, if needed:
935 // for ( ; i < stc; i += 1)
936 // <loop-body>
937 if (needs_cleanup) {
938 vector_mode_ = kSequential;
939 GenerateNewLoop(node,
940 block,
941 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
Aart Bik14a68b42017-06-08 14:06:58 -0700942 vector_index_,
Aart Bikf8f5a162017-02-06 15:35:29 -0800943 stc,
Aart Bikdbbac8f2017-09-01 13:06:08 -0700944 graph_->GetConstant(induc_type, 1),
Aart Bik521b50f2017-09-09 10:44:45 -0700945 kNoUnrollingFactor);
Aart Bikf8f5a162017-02-06 15:35:29 -0800946 }
947
Aart Bik0148de42017-09-05 09:25:01 -0700948 // Link reductions to their final uses.
949 for (auto i = reductions_->begin(); i != reductions_->end(); ++i) {
950 if (i->first->IsPhi()) {
Aart Bikdbbac8f2017-09-01 13:06:08 -0700951 HInstruction* phi = i->first;
952 HInstruction* repl = ReduceAndExtractIfNeeded(i->second);
953 // Deal with regular uses.
954 for (const HUseListNode<HInstruction*>& use : phi->GetUses()) {
955 induction_range_.Replace(use.GetUser(), phi, repl); // update induction use
956 }
957 phi->ReplaceWith(repl);
Aart Bik0148de42017-09-05 09:25:01 -0700958 }
959 }
960
Aart Bikf8f5a162017-02-06 15:35:29 -0800961 // Remove the original loop by disconnecting the body block
962 // and removing all instructions from the header.
963 block->DisconnectAndDelete();
964 while (!header->GetFirstInstruction()->IsGoto()) {
965 header->RemoveInstruction(header->GetFirstInstruction());
966 }
Aart Bikb29f6842017-07-28 15:58:41 -0700967
Aart Bik14a68b42017-06-08 14:06:58 -0700968 // Update loop hierarchy: the old header now resides in the same outer loop
969 // as the old preheader. Note that we don't bother putting sequential
970 // loops back in the hierarchy at this point.
Aart Bikf8f5a162017-02-06 15:35:29 -0800971 header->SetLoopInformation(preheader->GetLoopInformation()); // outward
972 node->loop_info = vloop;
973}
974
975void HLoopOptimization::GenerateNewLoop(LoopNode* node,
976 HBasicBlock* block,
977 HBasicBlock* new_preheader,
978 HInstruction* lo,
979 HInstruction* hi,
Aart Bik14a68b42017-06-08 14:06:58 -0700980 HInstruction* step,
981 uint32_t unroll) {
982 DCHECK(unroll == 1 || vector_mode_ == kVector);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100983 DataType::Type induc_type = lo->GetType();
Aart Bikf8f5a162017-02-06 15:35:29 -0800984 // Prepare new loop.
Aart Bikf8f5a162017-02-06 15:35:29 -0800985 vector_preheader_ = new_preheader,
986 vector_header_ = vector_preheader_->GetSingleSuccessor();
987 vector_body_ = vector_header_->GetSuccessors()[1];
Aart Bik14a68b42017-06-08 14:06:58 -0700988 HPhi* phi = new (global_allocator_) HPhi(global_allocator_,
989 kNoRegNumber,
990 0,
991 HPhi::ToPhiType(induc_type));
Aart Bikb07d1bc2017-04-05 10:03:15 -0700992 // Generate header and prepare body.
Aart Bikf8f5a162017-02-06 15:35:29 -0800993 // for (i = lo; i < hi; i += step)
994 // <loop-body>
Aart Bik14a68b42017-06-08 14:06:58 -0700995 HInstruction* cond = new (global_allocator_) HAboveOrEqual(phi, hi);
996 vector_header_->AddPhi(phi);
Aart Bikf8f5a162017-02-06 15:35:29 -0800997 vector_header_->AddInstruction(cond);
998 vector_header_->AddInstruction(new (global_allocator_) HIf(cond));
Aart Bik14a68b42017-06-08 14:06:58 -0700999 vector_index_ = phi;
Aart Bik0148de42017-09-05 09:25:01 -07001000 vector_permanent_map_->clear(); // preserved over unrolling
Aart Bik14a68b42017-06-08 14:06:58 -07001001 for (uint32_t u = 0; u < unroll; u++) {
Aart Bik14a68b42017-06-08 14:06:58 -07001002 // Generate instruction map.
Aart Bik0148de42017-09-05 09:25:01 -07001003 vector_map_->clear();
Aart Bik14a68b42017-06-08 14:06:58 -07001004 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
1005 bool vectorized_def = VectorizeDef(node, it.Current(), /*generate_code*/ true);
1006 DCHECK(vectorized_def);
1007 }
1008 // Generate body from the instruction map, but in original program order.
1009 HEnvironment* env = vector_header_->GetFirstInstruction()->GetEnvironment();
1010 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
1011 auto i = vector_map_->find(it.Current());
1012 if (i != vector_map_->end() && !i->second->IsInBlock()) {
1013 Insert(vector_body_, i->second);
1014 // Deal with instructions that need an environment, such as the scalar intrinsics.
1015 if (i->second->NeedsEnvironment()) {
1016 i->second->CopyEnvironmentFromWithLoopPhiAdjustment(env, vector_header_);
1017 }
1018 }
1019 }
Aart Bik0148de42017-09-05 09:25:01 -07001020 // Generate the induction.
Aart Bik14a68b42017-06-08 14:06:58 -07001021 vector_index_ = new (global_allocator_) HAdd(induc_type, vector_index_, step);
1022 Insert(vector_body_, vector_index_);
Aart Bikf8f5a162017-02-06 15:35:29 -08001023 }
Aart Bik0148de42017-09-05 09:25:01 -07001024 // Finalize phi inputs for the reductions (if any).
1025 for (auto i = reductions_->begin(); i != reductions_->end(); ++i) {
1026 if (!i->first->IsPhi()) {
1027 DCHECK(i->second->IsPhi());
1028 GenerateVecReductionPhiInputs(i->second->AsPhi(), i->first);
1029 }
1030 }
Aart Bikb29f6842017-07-28 15:58:41 -07001031 // Finalize phi inputs for the loop index.
Aart Bik14a68b42017-06-08 14:06:58 -07001032 phi->AddInput(lo);
1033 phi->AddInput(vector_index_);
1034 vector_index_ = phi;
Aart Bikf8f5a162017-02-06 15:35:29 -08001035}
1036
Aart Bikf8f5a162017-02-06 15:35:29 -08001037bool HLoopOptimization::VectorizeDef(LoopNode* node,
1038 HInstruction* instruction,
1039 bool generate_code) {
1040 // Accept a left-hand-side array base[index] for
1041 // (1) supported vector type,
1042 // (2) loop-invariant base,
1043 // (3) unit stride index,
1044 // (4) vectorizable right-hand-side value.
1045 uint64_t restrictions = kNone;
1046 if (instruction->IsArraySet()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001047 DataType::Type type = instruction->AsArraySet()->GetComponentType();
Aart Bikf8f5a162017-02-06 15:35:29 -08001048 HInstruction* base = instruction->InputAt(0);
1049 HInstruction* index = instruction->InputAt(1);
1050 HInstruction* value = instruction->InputAt(2);
1051 HInstruction* offset = nullptr;
1052 if (TrySetVectorType(type, &restrictions) &&
1053 node->loop_info->IsDefinedOutOfTheLoop(base) &&
Aart Bik37dc4df2017-06-28 14:08:00 -07001054 induction_range_.IsUnitStride(instruction, index, graph_, &offset) &&
Aart Bikf8f5a162017-02-06 15:35:29 -08001055 VectorizeUse(node, value, generate_code, type, restrictions)) {
1056 if (generate_code) {
1057 GenerateVecSub(index, offset);
Aart Bik14a68b42017-06-08 14:06:58 -07001058 GenerateVecMem(instruction, vector_map_->Get(index), vector_map_->Get(value), offset, type);
Aart Bikf8f5a162017-02-06 15:35:29 -08001059 } else {
1060 vector_refs_->insert(ArrayReference(base, offset, type, /*lhs*/ true));
1061 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08001062 return true;
1063 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001064 return false;
1065 }
Aart Bik0148de42017-09-05 09:25:01 -07001066 // Accept a left-hand-side reduction for
1067 // (1) supported vector type,
1068 // (2) vectorizable right-hand-side value.
1069 auto redit = reductions_->find(instruction);
1070 if (redit != reductions_->end()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001071 DataType::Type type = instruction->GetType();
Aart Bikdbbac8f2017-09-01 13:06:08 -07001072 // Recognize SAD idiom or direct reduction.
1073 if (VectorizeSADIdiom(node, instruction, generate_code, type, restrictions) ||
1074 (TrySetVectorType(type, &restrictions) &&
1075 VectorizeUse(node, instruction, generate_code, type, restrictions))) {
Aart Bik0148de42017-09-05 09:25:01 -07001076 if (generate_code) {
1077 HInstruction* new_red = vector_map_->Get(instruction);
1078 vector_permanent_map_->Put(new_red, vector_map_->Get(redit->second));
1079 vector_permanent_map_->Overwrite(redit->second, new_red);
1080 }
1081 return true;
1082 }
1083 return false;
1084 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001085 // Branch back okay.
1086 if (instruction->IsGoto()) {
1087 return true;
1088 }
1089 // Otherwise accept only expressions with no effects outside the immediate loop-body.
1090 // Note that actual uses are inspected during right-hand-side tree traversal.
1091 return !IsUsedOutsideLoop(node->loop_info, instruction) && !instruction->DoesAnyWrite();
1092}
1093
Aart Bik304c8a52017-05-23 11:01:13 -07001094// TODO: saturation arithmetic.
Aart Bikf8f5a162017-02-06 15:35:29 -08001095bool HLoopOptimization::VectorizeUse(LoopNode* node,
1096 HInstruction* instruction,
1097 bool generate_code,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001098 DataType::Type type,
Aart Bikf8f5a162017-02-06 15:35:29 -08001099 uint64_t restrictions) {
1100 // Accept anything for which code has already been generated.
1101 if (generate_code) {
1102 if (vector_map_->find(instruction) != vector_map_->end()) {
1103 return true;
1104 }
1105 }
1106 // Continue the right-hand-side tree traversal, passing in proper
1107 // types and vector restrictions along the way. During code generation,
1108 // all new nodes are drawn from the global allocator.
1109 if (node->loop_info->IsDefinedOutOfTheLoop(instruction)) {
1110 // Accept invariant use, using scalar expansion.
1111 if (generate_code) {
1112 GenerateVecInv(instruction, type);
1113 }
1114 return true;
1115 } else if (instruction->IsArrayGet()) {
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001116 // Deal with vector restrictions.
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001117 bool is_string_char_at = instruction->AsArrayGet()->IsStringCharAt();
1118 if (is_string_char_at && HasVectorRestrictions(restrictions, kNoStringCharAt)) {
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001119 return false;
1120 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001121 // Accept a right-hand-side array base[index] for
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001122 // (1) matching vector type (exact match or signed/unsigned integral type of the same size),
Aart Bikf8f5a162017-02-06 15:35:29 -08001123 // (2) loop-invariant base,
1124 // (3) unit stride index,
1125 // (4) vectorizable right-hand-side value.
1126 HInstruction* base = instruction->InputAt(0);
1127 HInstruction* index = instruction->InputAt(1);
1128 HInstruction* offset = nullptr;
Aart Bik46b6dbc2017-10-03 11:37:37 -07001129 if (HVecOperation::ToSignedType(type) == HVecOperation::ToSignedType(instruction->GetType()) &&
Aart Bikf8f5a162017-02-06 15:35:29 -08001130 node->loop_info->IsDefinedOutOfTheLoop(base) &&
Aart Bik37dc4df2017-06-28 14:08:00 -07001131 induction_range_.IsUnitStride(instruction, index, graph_, &offset)) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001132 if (generate_code) {
1133 GenerateVecSub(index, offset);
Aart Bik14a68b42017-06-08 14:06:58 -07001134 GenerateVecMem(instruction, vector_map_->Get(index), nullptr, offset, type);
Aart Bikf8f5a162017-02-06 15:35:29 -08001135 } else {
1136 vector_refs_->insert(ArrayReference(base, offset, type, /*lhs*/ false));
1137 }
1138 return true;
1139 }
Aart Bik0148de42017-09-05 09:25:01 -07001140 } else if (instruction->IsPhi()) {
1141 // Accept particular phi operations.
1142 if (reductions_->find(instruction) != reductions_->end()) {
1143 // Deal with vector restrictions.
1144 if (HasVectorRestrictions(restrictions, kNoReduction)) {
1145 return false;
1146 }
1147 // Accept a reduction.
1148 if (generate_code) {
1149 GenerateVecReductionPhi(instruction->AsPhi());
1150 }
1151 return true;
1152 }
1153 // TODO: accept right-hand-side induction?
1154 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001155 } else if (instruction->IsTypeConversion()) {
1156 // Accept particular type conversions.
1157 HTypeConversion* conversion = instruction->AsTypeConversion();
1158 HInstruction* opa = conversion->InputAt(0);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001159 DataType::Type from = conversion->GetInputType();
1160 DataType::Type to = conversion->GetResultType();
1161 if (DataType::IsIntegralType(from) && DataType::IsIntegralType(to)) {
1162 size_t size_vec = DataType::Size(type);
1163 size_t size_from = DataType::Size(from);
1164 size_t size_to = DataType::Size(to);
Aart Bikdf011c32017-09-28 12:53:04 -07001165 DataType::Type ctype = size_from == size_vec ? from : type;
Aart Bikdbbac8f2017-09-01 13:06:08 -07001166 // Accept an integral conversion
1167 // (1a) narrowing into vector type, "wider" operations cannot bring in higher order bits, or
1168 // (1b) widening from at least vector type, and
1169 // (2) vectorizable operand.
1170 if ((size_to < size_from &&
1171 size_to == size_vec &&
1172 VectorizeUse(node, opa, generate_code, type, restrictions | kNoHiBits)) ||
1173 (size_to >= size_from &&
1174 size_from >= size_vec &&
Aart Bikdf011c32017-09-28 12:53:04 -07001175 VectorizeUse(node, opa, generate_code, ctype, restrictions))) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001176 if (generate_code) {
1177 if (vector_mode_ == kVector) {
1178 vector_map_->Put(instruction, vector_map_->Get(opa)); // operand pass-through
1179 } else {
1180 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1181 }
1182 }
1183 return true;
1184 }
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001185 } else if (to == DataType::Type::kFloat32 && from == DataType::Type::kInt32) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001186 DCHECK_EQ(to, type);
1187 // Accept int to float conversion for
1188 // (1) supported int,
1189 // (2) vectorizable operand.
1190 if (TrySetVectorType(from, &restrictions) &&
1191 VectorizeUse(node, opa, generate_code, from, restrictions)) {
1192 if (generate_code) {
1193 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1194 }
1195 return true;
1196 }
1197 }
1198 return false;
1199 } else if (instruction->IsNeg() || instruction->IsNot() || instruction->IsBooleanNot()) {
1200 // Accept unary operator for vectorizable operand.
1201 HInstruction* opa = instruction->InputAt(0);
1202 if (VectorizeUse(node, opa, generate_code, type, restrictions)) {
1203 if (generate_code) {
1204 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1205 }
1206 return true;
1207 }
1208 } else if (instruction->IsAdd() || instruction->IsSub() ||
1209 instruction->IsMul() || instruction->IsDiv() ||
1210 instruction->IsAnd() || instruction->IsOr() || instruction->IsXor()) {
1211 // Deal with vector restrictions.
1212 if ((instruction->IsMul() && HasVectorRestrictions(restrictions, kNoMul)) ||
1213 (instruction->IsDiv() && HasVectorRestrictions(restrictions, kNoDiv))) {
1214 return false;
1215 }
1216 // Accept binary operator for vectorizable operands.
1217 HInstruction* opa = instruction->InputAt(0);
1218 HInstruction* opb = instruction->InputAt(1);
1219 if (VectorizeUse(node, opa, generate_code, type, restrictions) &&
1220 VectorizeUse(node, opb, generate_code, type, restrictions)) {
1221 if (generate_code) {
1222 GenerateVecOp(instruction, vector_map_->Get(opa), vector_map_->Get(opb), type);
1223 }
1224 return true;
1225 }
1226 } else if (instruction->IsShl() || instruction->IsShr() || instruction->IsUShr()) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001227 // Recognize halving add idiom.
Aart Bikf3e61ee2017-04-12 17:09:20 -07001228 if (VectorizeHalvingAddIdiom(node, instruction, generate_code, type, restrictions)) {
1229 return true;
1230 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001231 // Deal with vector restrictions.
Aart Bik304c8a52017-05-23 11:01:13 -07001232 HInstruction* opa = instruction->InputAt(0);
1233 HInstruction* opb = instruction->InputAt(1);
1234 HInstruction* r = opa;
1235 bool is_unsigned = false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001236 if ((HasVectorRestrictions(restrictions, kNoShift)) ||
1237 (instruction->IsShr() && HasVectorRestrictions(restrictions, kNoShr))) {
1238 return false; // unsupported instruction
Aart Bik304c8a52017-05-23 11:01:13 -07001239 } else if (HasVectorRestrictions(restrictions, kNoHiBits)) {
1240 // Shifts right need extra care to account for higher order bits.
1241 // TODO: less likely shr/unsigned and ushr/signed can by flipping signess.
1242 if (instruction->IsShr() &&
1243 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || is_unsigned)) {
1244 return false; // reject, unless all operands are sign-extension narrower
1245 } else if (instruction->IsUShr() &&
1246 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || !is_unsigned)) {
1247 return false; // reject, unless all operands are zero-extension narrower
1248 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001249 }
1250 // Accept shift operator for vectorizable/invariant operands.
1251 // TODO: accept symbolic, albeit loop invariant shift factors.
Aart Bik304c8a52017-05-23 11:01:13 -07001252 DCHECK(r != nullptr);
1253 if (generate_code && vector_mode_ != kVector) { // de-idiom
1254 r = opa;
1255 }
Aart Bik50e20d52017-05-05 14:07:29 -07001256 int64_t distance = 0;
Aart Bik304c8a52017-05-23 11:01:13 -07001257 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
Aart Bik50e20d52017-05-05 14:07:29 -07001258 IsInt64AndGet(opb, /*out*/ &distance)) {
Aart Bik65ffd8e2017-05-01 16:50:45 -07001259 // Restrict shift distance to packed data type width.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001260 int64_t max_distance = DataType::Size(type) * 8;
Aart Bik65ffd8e2017-05-01 16:50:45 -07001261 if (0 <= distance && distance < max_distance) {
1262 if (generate_code) {
Aart Bik304c8a52017-05-23 11:01:13 -07001263 GenerateVecOp(instruction, vector_map_->Get(r), opb, type);
Aart Bik65ffd8e2017-05-01 16:50:45 -07001264 }
1265 return true;
Aart Bikf8f5a162017-02-06 15:35:29 -08001266 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001267 }
1268 } else if (instruction->IsInvokeStaticOrDirect()) {
Aart Bik6daebeb2017-04-03 14:35:41 -07001269 // Accept particular intrinsics.
1270 HInvokeStaticOrDirect* invoke = instruction->AsInvokeStaticOrDirect();
1271 switch (invoke->GetIntrinsic()) {
1272 case Intrinsics::kMathAbsInt:
1273 case Intrinsics::kMathAbsLong:
1274 case Intrinsics::kMathAbsFloat:
1275 case Intrinsics::kMathAbsDouble: {
1276 // Deal with vector restrictions.
Aart Bik304c8a52017-05-23 11:01:13 -07001277 HInstruction* opa = instruction->InputAt(0);
1278 HInstruction* r = opa;
1279 bool is_unsigned = false;
1280 if (HasVectorRestrictions(restrictions, kNoAbs)) {
Aart Bik6daebeb2017-04-03 14:35:41 -07001281 return false;
Aart Bik304c8a52017-05-23 11:01:13 -07001282 } else if (HasVectorRestrictions(restrictions, kNoHiBits) &&
1283 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || is_unsigned)) {
1284 return false; // reject, unless operand is sign-extension narrower
Aart Bik6daebeb2017-04-03 14:35:41 -07001285 }
1286 // Accept ABS(x) for vectorizable operand.
Aart Bik304c8a52017-05-23 11:01:13 -07001287 DCHECK(r != nullptr);
1288 if (generate_code && vector_mode_ != kVector) { // de-idiom
1289 r = opa;
1290 }
1291 if (VectorizeUse(node, r, generate_code, type, restrictions)) {
Aart Bik6daebeb2017-04-03 14:35:41 -07001292 if (generate_code) {
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001293 NormalizePackedType(&type, &is_unsigned);
Aart Bik304c8a52017-05-23 11:01:13 -07001294 GenerateVecOp(instruction, vector_map_->Get(r), nullptr, type);
Aart Bik6daebeb2017-04-03 14:35:41 -07001295 }
1296 return true;
1297 }
1298 return false;
1299 }
Aart Bikc8e93c72017-05-10 10:49:22 -07001300 case Intrinsics::kMathMinIntInt:
1301 case Intrinsics::kMathMinLongLong:
1302 case Intrinsics::kMathMinFloatFloat:
1303 case Intrinsics::kMathMinDoubleDouble:
1304 case Intrinsics::kMathMaxIntInt:
1305 case Intrinsics::kMathMaxLongLong:
1306 case Intrinsics::kMathMaxFloatFloat:
1307 case Intrinsics::kMathMaxDoubleDouble: {
1308 // Deal with vector restrictions.
Nicolas Geoffray92316902017-05-23 08:06:07 +00001309 HInstruction* opa = instruction->InputAt(0);
1310 HInstruction* opb = instruction->InputAt(1);
Aart Bik304c8a52017-05-23 11:01:13 -07001311 HInstruction* r = opa;
1312 HInstruction* s = opb;
1313 bool is_unsigned = false;
1314 if (HasVectorRestrictions(restrictions, kNoMinMax)) {
1315 return false;
1316 } else if (HasVectorRestrictions(restrictions, kNoHiBits) &&
1317 !IsNarrowerOperands(opa, opb, type, &r, &s, &is_unsigned)) {
1318 return false; // reject, unless all operands are same-extension narrower
1319 }
1320 // Accept MIN/MAX(x, y) for vectorizable operands.
Aart Bikdbbac8f2017-09-01 13:06:08 -07001321 DCHECK(r != nullptr);
1322 DCHECK(s != nullptr);
Aart Bik304c8a52017-05-23 11:01:13 -07001323 if (generate_code && vector_mode_ != kVector) { // de-idiom
1324 r = opa;
1325 s = opb;
1326 }
1327 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
1328 VectorizeUse(node, s, generate_code, type, restrictions)) {
Aart Bikc8e93c72017-05-10 10:49:22 -07001329 if (generate_code) {
Aart Bik304c8a52017-05-23 11:01:13 -07001330 GenerateVecOp(
1331 instruction, vector_map_->Get(r), vector_map_->Get(s), type, is_unsigned);
Aart Bikc8e93c72017-05-10 10:49:22 -07001332 }
1333 return true;
1334 }
1335 return false;
1336 }
Aart Bik6daebeb2017-04-03 14:35:41 -07001337 default:
1338 return false;
1339 } // switch
Aart Bik281c6812016-08-26 11:31:48 -07001340 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08001341 return false;
Aart Bik281c6812016-08-26 11:31:48 -07001342}
1343
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001344bool HLoopOptimization::TrySetVectorType(DataType::Type type, uint64_t* restrictions) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001345 const InstructionSetFeatures* features = compiler_driver_->GetInstructionSetFeatures();
1346 switch (compiler_driver_->GetInstructionSet()) {
1347 case kArm:
1348 case kThumb2:
Artem Serov8f7c4102017-06-21 11:21:37 +01001349 // Allow vectorization for all ARM devices, because Android assumes that
Aart Bikb29f6842017-07-28 15:58:41 -07001350 // ARM 32-bit always supports advanced SIMD (64-bit SIMD).
Artem Serov8f7c4102017-06-21 11:21:37 +01001351 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001352 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001353 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001354 case DataType::Type::kInt8:
Aart Bik0148de42017-09-05 09:25:01 -07001355 *restrictions |= kNoDiv | kNoReduction;
Artem Serov8f7c4102017-06-21 11:21:37 +01001356 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001357 case DataType::Type::kUint16:
1358 case DataType::Type::kInt16:
Aart Bik0148de42017-09-05 09:25:01 -07001359 *restrictions |= kNoDiv | kNoStringCharAt | kNoReduction;
Artem Serov8f7c4102017-06-21 11:21:37 +01001360 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001361 case DataType::Type::kInt32:
Artem Serov6e9b1372017-10-05 16:48:30 +01001362 *restrictions |= kNoDiv | kNoWideSAD;
Artem Serov8f7c4102017-06-21 11:21:37 +01001363 return TrySetVectorLength(2);
1364 default:
1365 break;
1366 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001367 return false;
1368 case kArm64:
1369 // Allow vectorization for all ARM devices, because Android assumes that
Aart Bikb29f6842017-07-28 15:58:41 -07001370 // ARMv8 AArch64 always supports advanced SIMD (128-bit SIMD).
Aart Bikf8f5a162017-02-06 15:35:29 -08001371 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001372 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001373 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001374 case DataType::Type::kInt8:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001375 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +01001376 return TrySetVectorLength(16);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001377 case DataType::Type::kUint16:
1378 case DataType::Type::kInt16:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001379 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +01001380 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001381 case DataType::Type::kInt32:
Aart Bikf8f5a162017-02-06 15:35:29 -08001382 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +01001383 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001384 case DataType::Type::kInt64:
Aart Bikc8e93c72017-05-10 10:49:22 -07001385 *restrictions |= kNoDiv | kNoMul | kNoMinMax;
Aart Bikf8f5a162017-02-06 15:35:29 -08001386 return TrySetVectorLength(2);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001387 case DataType::Type::kFloat32:
Aart Bik0148de42017-09-05 09:25:01 -07001388 *restrictions |= kNoReduction;
Artem Serovd4bccf12017-04-03 18:47:32 +01001389 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001390 case DataType::Type::kFloat64:
Aart Bik0148de42017-09-05 09:25:01 -07001391 *restrictions |= kNoReduction;
Aart Bikf8f5a162017-02-06 15:35:29 -08001392 return TrySetVectorLength(2);
1393 default:
1394 return false;
1395 }
1396 case kX86:
1397 case kX86_64:
Aart Bikb29f6842017-07-28 15:58:41 -07001398 // Allow vectorization for SSE4.1-enabled X86 devices only (128-bit SIMD).
Aart Bikf8f5a162017-02-06 15:35:29 -08001399 if (features->AsX86InstructionSetFeatures()->HasSSE4_1()) {
1400 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001401 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001402 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001403 case DataType::Type::kInt8:
Aart Bik0148de42017-09-05 09:25:01 -07001404 *restrictions |=
Aart Bikdbbac8f2017-09-01 13:06:08 -07001405 kNoMul | kNoDiv | kNoShift | kNoAbs | kNoSignedHAdd | kNoUnroundedHAdd | kNoSAD;
Aart Bikf8f5a162017-02-06 15:35:29 -08001406 return TrySetVectorLength(16);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001407 case DataType::Type::kUint16:
1408 case DataType::Type::kInt16:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001409 *restrictions |= kNoDiv | kNoAbs | kNoSignedHAdd | kNoUnroundedHAdd | kNoSAD;
Aart Bikf8f5a162017-02-06 15:35:29 -08001410 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001411 case DataType::Type::kInt32:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001412 *restrictions |= kNoDiv | kNoSAD;
Aart Bikf8f5a162017-02-06 15:35:29 -08001413 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001414 case DataType::Type::kInt64:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001415 *restrictions |= kNoMul | kNoDiv | kNoShr | kNoAbs | kNoMinMax | kNoSAD;
Aart Bikf8f5a162017-02-06 15:35:29 -08001416 return TrySetVectorLength(2);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001417 case DataType::Type::kFloat32:
Aart Bik0148de42017-09-05 09:25:01 -07001418 *restrictions |= kNoMinMax | kNoReduction; // minmax: -0.0 vs +0.0
Aart Bikf8f5a162017-02-06 15:35:29 -08001419 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001420 case DataType::Type::kFloat64:
Aart Bik0148de42017-09-05 09:25:01 -07001421 *restrictions |= kNoMinMax | kNoReduction; // minmax: -0.0 vs +0.0
Aart Bikf8f5a162017-02-06 15:35:29 -08001422 return TrySetVectorLength(2);
1423 default:
1424 break;
1425 } // switch type
1426 }
1427 return false;
1428 case kMips:
Lena Djokic51765b02017-06-22 13:49:59 +02001429 if (features->AsMipsInstructionSetFeatures()->HasMsa()) {
1430 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001431 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001432 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001433 case DataType::Type::kInt8:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001434 *restrictions |= kNoDiv | kNoReduction | kNoSAD;
Lena Djokic51765b02017-06-22 13:49:59 +02001435 return TrySetVectorLength(16);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001436 case DataType::Type::kUint16:
1437 case DataType::Type::kInt16:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001438 *restrictions |= kNoDiv | kNoStringCharAt | kNoReduction | kNoSAD;
Lena Djokic51765b02017-06-22 13:49:59 +02001439 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001440 case DataType::Type::kInt32:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001441 *restrictions |= kNoDiv | kNoReduction | kNoSAD;
Lena Djokic51765b02017-06-22 13:49:59 +02001442 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001443 case DataType::Type::kInt64:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001444 *restrictions |= kNoDiv | kNoReduction | kNoSAD;
Lena Djokic51765b02017-06-22 13:49:59 +02001445 return TrySetVectorLength(2);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001446 case DataType::Type::kFloat32:
Aart Bik0148de42017-09-05 09:25:01 -07001447 *restrictions |= kNoMinMax | kNoReduction; // min/max(x, NaN)
Lena Djokic51765b02017-06-22 13:49:59 +02001448 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001449 case DataType::Type::kFloat64:
Aart Bik0148de42017-09-05 09:25:01 -07001450 *restrictions |= kNoMinMax | kNoReduction; // min/max(x, NaN)
Lena Djokic51765b02017-06-22 13:49:59 +02001451 return TrySetVectorLength(2);
1452 default:
1453 break;
1454 } // switch type
1455 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001456 return false;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001457 case kMips64:
1458 if (features->AsMips64InstructionSetFeatures()->HasMsa()) {
1459 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001460 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001461 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001462 case DataType::Type::kInt8:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001463 *restrictions |= kNoDiv | kNoReduction | kNoSAD;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001464 return TrySetVectorLength(16);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001465 case DataType::Type::kUint16:
1466 case DataType::Type::kInt16:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001467 *restrictions |= kNoDiv | kNoStringCharAt | kNoReduction | kNoSAD;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001468 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001469 case DataType::Type::kInt32:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001470 *restrictions |= kNoDiv | kNoReduction | kNoSAD;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001471 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001472 case DataType::Type::kInt64:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001473 *restrictions |= kNoDiv | kNoReduction | kNoSAD;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001474 return TrySetVectorLength(2);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001475 case DataType::Type::kFloat32:
Aart Bik0148de42017-09-05 09:25:01 -07001476 *restrictions |= kNoMinMax | kNoReduction; // min/max(x, NaN)
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001477 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001478 case DataType::Type::kFloat64:
Aart Bik0148de42017-09-05 09:25:01 -07001479 *restrictions |= kNoMinMax | kNoReduction; // min/max(x, NaN)
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001480 return TrySetVectorLength(2);
1481 default:
1482 break;
1483 } // switch type
1484 }
1485 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001486 default:
1487 return false;
1488 } // switch instruction set
1489}
1490
1491bool HLoopOptimization::TrySetVectorLength(uint32_t length) {
1492 DCHECK(IsPowerOfTwo(length) && length >= 2u);
1493 // First time set?
1494 if (vector_length_ == 0) {
1495 vector_length_ = length;
1496 }
1497 // Different types are acceptable within a loop-body, as long as all the corresponding vector
1498 // lengths match exactly to obtain a uniform traversal through the vector iteration space
1499 // (idiomatic exceptions to this rule can be handled by further unrolling sub-expressions).
1500 return vector_length_ == length;
1501}
1502
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001503void HLoopOptimization::GenerateVecInv(HInstruction* org, DataType::Type type) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001504 if (vector_map_->find(org) == vector_map_->end()) {
1505 // In scalar code, just use a self pass-through for scalar invariants
1506 // (viz. expression remains itself).
1507 if (vector_mode_ == kSequential) {
1508 vector_map_->Put(org, org);
1509 return;
1510 }
1511 // In vector code, explicit scalar expansion is needed.
Aart Bik0148de42017-09-05 09:25:01 -07001512 HInstruction* vector = nullptr;
1513 auto it = vector_permanent_map_->find(org);
1514 if (it != vector_permanent_map_->end()) {
1515 vector = it->second; // reuse during unrolling
1516 } else {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001517 // Generates ReplicateScalar( (optional_type_conv) org ).
1518 HInstruction* input = org;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001519 DataType::Type input_type = input->GetType();
1520 if (type != input_type && (type == DataType::Type::kInt64 ||
1521 input_type == DataType::Type::kInt64)) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001522 input = Insert(vector_preheader_,
1523 new (global_allocator_) HTypeConversion(type, input, kNoDexPc));
1524 }
1525 vector = new (global_allocator_)
Aart Bik46b6dbc2017-10-03 11:37:37 -07001526 HVecReplicateScalar(global_allocator_, input, type, vector_length_, kNoDexPc);
Aart Bik0148de42017-09-05 09:25:01 -07001527 vector_permanent_map_->Put(org, Insert(vector_preheader_, vector));
1528 }
1529 vector_map_->Put(org, vector);
Aart Bikf8f5a162017-02-06 15:35:29 -08001530 }
1531}
1532
1533void HLoopOptimization::GenerateVecSub(HInstruction* org, HInstruction* offset) {
1534 if (vector_map_->find(org) == vector_map_->end()) {
Aart Bik14a68b42017-06-08 14:06:58 -07001535 HInstruction* subscript = vector_index_;
Aart Bik37dc4df2017-06-28 14:08:00 -07001536 int64_t value = 0;
1537 if (!IsInt64AndGet(offset, &value) || value != 0) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001538 subscript = new (global_allocator_) HAdd(DataType::Type::kInt32, subscript, offset);
Aart Bikf8f5a162017-02-06 15:35:29 -08001539 if (org->IsPhi()) {
1540 Insert(vector_body_, subscript); // lacks layout placeholder
1541 }
1542 }
1543 vector_map_->Put(org, subscript);
1544 }
1545}
1546
1547void HLoopOptimization::GenerateVecMem(HInstruction* org,
1548 HInstruction* opa,
1549 HInstruction* opb,
Aart Bik14a68b42017-06-08 14:06:58 -07001550 HInstruction* offset,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001551 DataType::Type type) {
Aart Bik46b6dbc2017-10-03 11:37:37 -07001552 uint32_t dex_pc = org->GetDexPc();
Aart Bikf8f5a162017-02-06 15:35:29 -08001553 HInstruction* vector = nullptr;
1554 if (vector_mode_ == kVector) {
1555 // Vector store or load.
Aart Bik14a68b42017-06-08 14:06:58 -07001556 HInstruction* base = org->InputAt(0);
Aart Bikf8f5a162017-02-06 15:35:29 -08001557 if (opb != nullptr) {
1558 vector = new (global_allocator_) HVecStore(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001559 global_allocator_, base, opa, opb, type, org->GetSideEffects(), vector_length_, dex_pc);
Aart Bikf8f5a162017-02-06 15:35:29 -08001560 } else {
Aart Bikdb14fcf2017-04-25 15:53:58 -07001561 bool is_string_char_at = org->AsArrayGet()->IsStringCharAt();
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001562 vector = new (global_allocator_) HVecLoad(global_allocator_,
1563 base,
1564 opa,
1565 type,
1566 org->GetSideEffects(),
1567 vector_length_,
Aart Bik46b6dbc2017-10-03 11:37:37 -07001568 is_string_char_at,
1569 dex_pc);
Aart Bik14a68b42017-06-08 14:06:58 -07001570 }
1571 // Known dynamically enforced alignment?
Aart Bik14a68b42017-06-08 14:06:58 -07001572 if (vector_peeling_candidate_ != nullptr &&
1573 vector_peeling_candidate_->base == base &&
1574 vector_peeling_candidate_->offset == offset) {
1575 vector->AsVecMemoryOperation()->SetAlignment(Alignment(kAlignedBase, 0));
Aart Bikf8f5a162017-02-06 15:35:29 -08001576 }
1577 } else {
1578 // Scalar store or load.
1579 DCHECK(vector_mode_ == kSequential);
1580 if (opb != nullptr) {
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001581 vector = new (global_allocator_) HArraySet(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001582 org->InputAt(0), opa, opb, type, org->GetSideEffects(), dex_pc);
Aart Bikf8f5a162017-02-06 15:35:29 -08001583 } else {
Aart Bikdb14fcf2017-04-25 15:53:58 -07001584 bool is_string_char_at = org->AsArrayGet()->IsStringCharAt();
1585 vector = new (global_allocator_) HArrayGet(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001586 org->InputAt(0), opa, type, org->GetSideEffects(), dex_pc, is_string_char_at);
Aart Bikf8f5a162017-02-06 15:35:29 -08001587 }
1588 }
1589 vector_map_->Put(org, vector);
1590}
1591
Aart Bik0148de42017-09-05 09:25:01 -07001592void HLoopOptimization::GenerateVecReductionPhi(HPhi* phi) {
1593 DCHECK(reductions_->find(phi) != reductions_->end());
1594 DCHECK(reductions_->Get(phi->InputAt(1)) == phi);
1595 HInstruction* vector = nullptr;
1596 if (vector_mode_ == kSequential) {
1597 HPhi* new_phi = new (global_allocator_) HPhi(
1598 global_allocator_, kNoRegNumber, 0, phi->GetType());
1599 vector_header_->AddPhi(new_phi);
1600 vector = new_phi;
1601 } else {
1602 // Link vector reduction back to prior unrolled update, or a first phi.
1603 auto it = vector_permanent_map_->find(phi);
1604 if (it != vector_permanent_map_->end()) {
1605 vector = it->second;
1606 } else {
1607 HPhi* new_phi = new (global_allocator_) HPhi(
1608 global_allocator_, kNoRegNumber, 0, HVecOperation::kSIMDType);
1609 vector_header_->AddPhi(new_phi);
1610 vector = new_phi;
1611 }
1612 }
1613 vector_map_->Put(phi, vector);
1614}
1615
1616void HLoopOptimization::GenerateVecReductionPhiInputs(HPhi* phi, HInstruction* reduction) {
1617 HInstruction* new_phi = vector_map_->Get(phi);
1618 HInstruction* new_init = reductions_->Get(phi);
1619 HInstruction* new_red = vector_map_->Get(reduction);
1620 // Link unrolled vector loop back to new phi.
1621 for (; !new_phi->IsPhi(); new_phi = vector_permanent_map_->Get(new_phi)) {
1622 DCHECK(new_phi->IsVecOperation());
1623 }
1624 // Prepare the new initialization.
1625 if (vector_mode_ == kVector) {
Goran Jakovljevic89b8df02017-10-13 08:33:17 +02001626 // Generate a [initial, 0, .., 0] vector for add or
1627 // a [initial, initial, .., initial] vector for min/max.
Aart Bikdbbac8f2017-09-01 13:06:08 -07001628 HVecOperation* red_vector = new_red->AsVecOperation();
Goran Jakovljevic89b8df02017-10-13 08:33:17 +02001629 HVecReduce::ReductionKind kind = GetReductionKind(red_vector);
Aart Bikdbbac8f2017-09-01 13:06:08 -07001630 size_t vector_length = red_vector->GetVectorLength();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001631 DataType::Type type = red_vector->GetPackedType();
Goran Jakovljevic89b8df02017-10-13 08:33:17 +02001632 if (kind == HVecReduce::ReductionKind::kSum) {
1633 new_init = Insert(vector_preheader_,
1634 new (global_allocator_) HVecSetScalars(global_allocator_,
1635 &new_init,
1636 type,
1637 vector_length,
1638 1,
1639 kNoDexPc));
1640 } else {
1641 new_init = Insert(vector_preheader_,
1642 new (global_allocator_) HVecReplicateScalar(global_allocator_,
1643 new_init,
1644 type,
1645 vector_length,
1646 kNoDexPc));
1647 }
Aart Bik0148de42017-09-05 09:25:01 -07001648 } else {
1649 new_init = ReduceAndExtractIfNeeded(new_init);
1650 }
1651 // Set the phi inputs.
1652 DCHECK(new_phi->IsPhi());
1653 new_phi->AsPhi()->AddInput(new_init);
1654 new_phi->AsPhi()->AddInput(new_red);
1655 // New feed value for next phi (safe mutation in iteration).
1656 reductions_->find(phi)->second = new_phi;
1657}
1658
1659HInstruction* HLoopOptimization::ReduceAndExtractIfNeeded(HInstruction* instruction) {
1660 if (instruction->IsPhi()) {
1661 HInstruction* input = instruction->InputAt(1);
1662 if (input->IsVecOperation()) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001663 HVecOperation* input_vector = input->AsVecOperation();
1664 size_t vector_length = input_vector->GetVectorLength();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001665 DataType::Type type = input_vector->GetPackedType();
Aart Bikdbbac8f2017-09-01 13:06:08 -07001666 HVecReduce::ReductionKind kind = GetReductionKind(input_vector);
Aart Bik0148de42017-09-05 09:25:01 -07001667 HBasicBlock* exit = instruction->GetBlock()->GetSuccessors()[0];
1668 // Generate a vector reduction and scalar extract
1669 // x = REDUCE( [x_1, .., x_n] )
1670 // y = x_1
1671 // along the exit of the defining loop.
Aart Bik0148de42017-09-05 09:25:01 -07001672 HInstruction* reduce = new (global_allocator_) HVecReduce(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001673 global_allocator_, instruction, type, vector_length, kind, kNoDexPc);
Aart Bik0148de42017-09-05 09:25:01 -07001674 exit->InsertInstructionBefore(reduce, exit->GetFirstInstruction());
1675 instruction = new (global_allocator_) HVecExtractScalar(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001676 global_allocator_, reduce, type, vector_length, 0, kNoDexPc);
Aart Bik0148de42017-09-05 09:25:01 -07001677 exit->InsertInstructionAfter(instruction, reduce);
1678 }
1679 }
1680 return instruction;
1681}
1682
Aart Bikf8f5a162017-02-06 15:35:29 -08001683#define GENERATE_VEC(x, y) \
1684 if (vector_mode_ == kVector) { \
1685 vector = (x); \
1686 } else { \
1687 DCHECK(vector_mode_ == kSequential); \
1688 vector = (y); \
1689 } \
1690 break;
1691
1692void HLoopOptimization::GenerateVecOp(HInstruction* org,
1693 HInstruction* opa,
1694 HInstruction* opb,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001695 DataType::Type type,
Aart Bik304c8a52017-05-23 11:01:13 -07001696 bool is_unsigned) {
Aart Bik46b6dbc2017-10-03 11:37:37 -07001697 uint32_t dex_pc = org->GetDexPc();
Aart Bikf8f5a162017-02-06 15:35:29 -08001698 HInstruction* vector = nullptr;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001699 DataType::Type org_type = org->GetType();
Aart Bikf8f5a162017-02-06 15:35:29 -08001700 switch (org->GetKind()) {
1701 case HInstruction::kNeg:
1702 DCHECK(opb == nullptr);
1703 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001704 new (global_allocator_) HVecNeg(global_allocator_, opa, type, vector_length_, dex_pc),
1705 new (global_allocator_) HNeg(org_type, opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001706 case HInstruction::kNot:
1707 DCHECK(opb == nullptr);
1708 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001709 new (global_allocator_) HVecNot(global_allocator_, opa, type, vector_length_, dex_pc),
1710 new (global_allocator_) HNot(org_type, opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001711 case HInstruction::kBooleanNot:
1712 DCHECK(opb == nullptr);
1713 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001714 new (global_allocator_) HVecNot(global_allocator_, opa, type, vector_length_, dex_pc),
1715 new (global_allocator_) HBooleanNot(opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001716 case HInstruction::kTypeConversion:
1717 DCHECK(opb == nullptr);
1718 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001719 new (global_allocator_) HVecCnv(global_allocator_, opa, type, vector_length_, dex_pc),
1720 new (global_allocator_) HTypeConversion(org_type, opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001721 case HInstruction::kAdd:
1722 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001723 new (global_allocator_) HVecAdd(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1724 new (global_allocator_) HAdd(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001725 case HInstruction::kSub:
1726 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001727 new (global_allocator_) HVecSub(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1728 new (global_allocator_) HSub(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001729 case HInstruction::kMul:
1730 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001731 new (global_allocator_) HVecMul(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1732 new (global_allocator_) HMul(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001733 case HInstruction::kDiv:
1734 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001735 new (global_allocator_) HVecDiv(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1736 new (global_allocator_) HDiv(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001737 case HInstruction::kAnd:
1738 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001739 new (global_allocator_) HVecAnd(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1740 new (global_allocator_) HAnd(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001741 case HInstruction::kOr:
1742 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001743 new (global_allocator_) HVecOr(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1744 new (global_allocator_) HOr(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001745 case HInstruction::kXor:
1746 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001747 new (global_allocator_) HVecXor(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1748 new (global_allocator_) HXor(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001749 case HInstruction::kShl:
1750 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001751 new (global_allocator_) HVecShl(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1752 new (global_allocator_) HShl(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001753 case HInstruction::kShr:
1754 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001755 new (global_allocator_) HVecShr(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1756 new (global_allocator_) HShr(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001757 case HInstruction::kUShr:
1758 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001759 new (global_allocator_) HVecUShr(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1760 new (global_allocator_) HUShr(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001761 case HInstruction::kInvokeStaticOrDirect: {
Aart Bik6daebeb2017-04-03 14:35:41 -07001762 HInvokeStaticOrDirect* invoke = org->AsInvokeStaticOrDirect();
1763 if (vector_mode_ == kVector) {
1764 switch (invoke->GetIntrinsic()) {
1765 case Intrinsics::kMathAbsInt:
1766 case Intrinsics::kMathAbsLong:
1767 case Intrinsics::kMathAbsFloat:
1768 case Intrinsics::kMathAbsDouble:
1769 DCHECK(opb == nullptr);
Aart Bik46b6dbc2017-10-03 11:37:37 -07001770 vector = new (global_allocator_)
1771 HVecAbs(global_allocator_, opa, type, vector_length_, dex_pc);
Aart Bik6daebeb2017-04-03 14:35:41 -07001772 break;
Aart Bikc8e93c72017-05-10 10:49:22 -07001773 case Intrinsics::kMathMinIntInt:
1774 case Intrinsics::kMathMinLongLong:
1775 case Intrinsics::kMathMinFloatFloat:
1776 case Intrinsics::kMathMinDoubleDouble: {
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001777 NormalizePackedType(&type, &is_unsigned);
Aart Bikc8e93c72017-05-10 10:49:22 -07001778 vector = new (global_allocator_)
Aart Bik46b6dbc2017-10-03 11:37:37 -07001779 HVecMin(global_allocator_, opa, opb, type, vector_length_, is_unsigned, dex_pc);
Aart Bikc8e93c72017-05-10 10:49:22 -07001780 break;
1781 }
1782 case Intrinsics::kMathMaxIntInt:
1783 case Intrinsics::kMathMaxLongLong:
1784 case Intrinsics::kMathMaxFloatFloat:
1785 case Intrinsics::kMathMaxDoubleDouble: {
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001786 NormalizePackedType(&type, &is_unsigned);
Aart Bikc8e93c72017-05-10 10:49:22 -07001787 vector = new (global_allocator_)
Aart Bik46b6dbc2017-10-03 11:37:37 -07001788 HVecMax(global_allocator_, opa, opb, type, vector_length_, is_unsigned, dex_pc);
Aart Bikc8e93c72017-05-10 10:49:22 -07001789 break;
1790 }
Aart Bik6daebeb2017-04-03 14:35:41 -07001791 default:
1792 LOG(FATAL) << "Unsupported SIMD intrinsic";
1793 UNREACHABLE();
1794 } // switch invoke
1795 } else {
Aart Bik24b905f2017-04-06 09:59:06 -07001796 // In scalar code, simply clone the method invoke, and replace its operands with the
1797 // corresponding new scalar instructions in the loop. The instruction will get an
1798 // environment while being inserted from the instruction map in original program order.
Aart Bik6daebeb2017-04-03 14:35:41 -07001799 DCHECK(vector_mode_ == kSequential);
Aart Bik6e92fb32017-06-05 14:05:09 -07001800 size_t num_args = invoke->GetNumberOfArguments();
Aart Bik6daebeb2017-04-03 14:35:41 -07001801 HInvokeStaticOrDirect* new_invoke = new (global_allocator_) HInvokeStaticOrDirect(
1802 global_allocator_,
Aart Bik6e92fb32017-06-05 14:05:09 -07001803 num_args,
Aart Bik6daebeb2017-04-03 14:35:41 -07001804 invoke->GetType(),
1805 invoke->GetDexPc(),
1806 invoke->GetDexMethodIndex(),
1807 invoke->GetResolvedMethod(),
1808 invoke->GetDispatchInfo(),
1809 invoke->GetInvokeType(),
1810 invoke->GetTargetMethod(),
1811 invoke->GetClinitCheckRequirement());
1812 HInputsRef inputs = invoke->GetInputs();
Aart Bik6e92fb32017-06-05 14:05:09 -07001813 size_t num_inputs = inputs.size();
1814 DCHECK_LE(num_args, num_inputs);
1815 DCHECK_EQ(num_inputs, new_invoke->GetInputs().size()); // both invokes agree
1816 for (size_t index = 0; index < num_inputs; ++index) {
1817 HInstruction* new_input = index < num_args
1818 ? vector_map_->Get(inputs[index])
1819 : inputs[index]; // beyond arguments: just pass through
1820 new_invoke->SetArgumentAt(index, new_input);
Aart Bik6daebeb2017-04-03 14:35:41 -07001821 }
Aart Bik98990262017-04-10 13:15:57 -07001822 new_invoke->SetIntrinsic(invoke->GetIntrinsic(),
1823 kNeedsEnvironmentOrCache,
1824 kNoSideEffects,
1825 kNoThrow);
Aart Bik6daebeb2017-04-03 14:35:41 -07001826 vector = new_invoke;
1827 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001828 break;
1829 }
1830 default:
1831 break;
1832 } // switch
1833 CHECK(vector != nullptr) << "Unsupported SIMD operator";
1834 vector_map_->Put(org, vector);
1835}
1836
1837#undef GENERATE_VEC
1838
1839//
Aart Bikf3e61ee2017-04-12 17:09:20 -07001840// Vectorization idioms.
1841//
1842
1843// Method recognizes the following idioms:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001844// rounding halving add (a + b + 1) >> 1 for unsigned/signed operands a, b
1845// truncated halving add (a + b) >> 1 for unsigned/signed operands a, b
Aart Bikf3e61ee2017-04-12 17:09:20 -07001846// Provided that the operands are promoted to a wider form to do the arithmetic and
1847// then cast back to narrower form, the idioms can be mapped into efficient SIMD
1848// implementation that operates directly in narrower form (plus one extra bit).
1849// TODO: current version recognizes implicit byte/short/char widening only;
1850// explicit widening from int to long could be added later.
1851bool HLoopOptimization::VectorizeHalvingAddIdiom(LoopNode* node,
1852 HInstruction* instruction,
1853 bool generate_code,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001854 DataType::Type type,
Aart Bikf3e61ee2017-04-12 17:09:20 -07001855 uint64_t restrictions) {
1856 // Test for top level arithmetic shift right x >> 1 or logical shift right x >>> 1
Aart Bik304c8a52017-05-23 11:01:13 -07001857 // (note whether the sign bit in wider precision is shifted in has no effect
Aart Bikf3e61ee2017-04-12 17:09:20 -07001858 // on the narrow precision computed by the idiom).
Aart Bikf3e61ee2017-04-12 17:09:20 -07001859 if ((instruction->IsShr() ||
1860 instruction->IsUShr()) &&
Aart Bik0148de42017-09-05 09:25:01 -07001861 IsInt64Value(instruction->InputAt(1), 1)) {
Aart Bik5f805002017-05-16 16:42:41 -07001862 // Test for (a + b + c) >> 1 for optional constant c.
1863 HInstruction* a = nullptr;
1864 HInstruction* b = nullptr;
1865 int64_t c = 0;
1866 if (IsAddConst(instruction->InputAt(0), /*out*/ &a, /*out*/ &b, /*out*/ &c)) {
Aart Bik304c8a52017-05-23 11:01:13 -07001867 DCHECK(a != nullptr && b != nullptr);
Aart Bik5f805002017-05-16 16:42:41 -07001868 // Accept c == 1 (rounded) or c == 0 (not rounded).
1869 bool is_rounded = false;
1870 if (c == 1) {
1871 is_rounded = true;
1872 } else if (c != 0) {
1873 return false;
1874 }
1875 // Accept consistent zero or sign extension on operands a and b.
Aart Bikf3e61ee2017-04-12 17:09:20 -07001876 HInstruction* r = nullptr;
1877 HInstruction* s = nullptr;
1878 bool is_unsigned = false;
Aart Bik304c8a52017-05-23 11:01:13 -07001879 if (!IsNarrowerOperands(a, b, type, &r, &s, &is_unsigned)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -07001880 return false;
1881 }
1882 // Deal with vector restrictions.
1883 if ((!is_unsigned && HasVectorRestrictions(restrictions, kNoSignedHAdd)) ||
1884 (!is_rounded && HasVectorRestrictions(restrictions, kNoUnroundedHAdd))) {
1885 return false;
1886 }
1887 // Accept recognized halving add for vectorizable operands. Vectorized code uses the
1888 // shorthand idiomatic operation. Sequential code uses the original scalar expressions.
Aart Bikdbbac8f2017-09-01 13:06:08 -07001889 DCHECK(r != nullptr);
1890 DCHECK(s != nullptr);
Aart Bik304c8a52017-05-23 11:01:13 -07001891 if (generate_code && vector_mode_ != kVector) { // de-idiom
1892 r = instruction->InputAt(0);
1893 s = instruction->InputAt(1);
1894 }
Aart Bikf3e61ee2017-04-12 17:09:20 -07001895 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
1896 VectorizeUse(node, s, generate_code, type, restrictions)) {
1897 if (generate_code) {
1898 if (vector_mode_ == kVector) {
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001899 NormalizePackedType(&type, &is_unsigned);
Aart Bikf3e61ee2017-04-12 17:09:20 -07001900 vector_map_->Put(instruction, new (global_allocator_) HVecHalvingAdd(
1901 global_allocator_,
1902 vector_map_->Get(r),
1903 vector_map_->Get(s),
1904 type,
1905 vector_length_,
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001906 is_rounded,
Aart Bik46b6dbc2017-10-03 11:37:37 -07001907 is_unsigned,
1908 kNoDexPc));
Aart Bik21b85922017-09-06 13:29:16 -07001909 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorizedIdiom);
Aart Bikf3e61ee2017-04-12 17:09:20 -07001910 } else {
Aart Bik304c8a52017-05-23 11:01:13 -07001911 GenerateVecOp(instruction, vector_map_->Get(r), vector_map_->Get(s), type);
Aart Bikf3e61ee2017-04-12 17:09:20 -07001912 }
1913 }
1914 return true;
1915 }
1916 }
1917 }
1918 return false;
1919}
1920
Aart Bikdbbac8f2017-09-01 13:06:08 -07001921// Method recognizes the following idiom:
1922// q += ABS(a - b) for signed operands a, b
1923// Provided that the operands have the same type or are promoted to a wider form.
1924// Since this may involve a vector length change, the idiom is handled by going directly
1925// to a sad-accumulate node (rather than relying combining finer grained nodes later).
1926// TODO: unsigned SAD too?
1927bool HLoopOptimization::VectorizeSADIdiom(LoopNode* node,
1928 HInstruction* instruction,
1929 bool generate_code,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001930 DataType::Type reduction_type,
Aart Bikdbbac8f2017-09-01 13:06:08 -07001931 uint64_t restrictions) {
1932 // Filter integral "q += ABS(a - b);" reduction, where ABS and SUB
1933 // are done in the same precision (either int or long).
1934 if (!instruction->IsAdd() ||
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001935 (reduction_type != DataType::Type::kInt32 && reduction_type != DataType::Type::kInt64)) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001936 return false;
1937 }
1938 HInstruction* q = instruction->InputAt(0);
1939 HInstruction* v = instruction->InputAt(1);
1940 HInstruction* a = nullptr;
1941 HInstruction* b = nullptr;
1942 if (v->IsInvokeStaticOrDirect() &&
1943 (v->AsInvokeStaticOrDirect()->GetIntrinsic() == Intrinsics::kMathAbsInt ||
1944 v->AsInvokeStaticOrDirect()->GetIntrinsic() == Intrinsics::kMathAbsLong)) {
1945 HInstruction* x = v->InputAt(0);
Aart Bikdf011c32017-09-28 12:53:04 -07001946 if (x->GetType() == reduction_type) {
1947 int64_t c = 0;
1948 if (x->IsSub()) {
1949 a = x->InputAt(0);
1950 b = x->InputAt(1);
1951 } else if (IsAddConst(x, /*out*/ &a, /*out*/ &c)) {
1952 b = graph_->GetConstant(reduction_type, -c); // hidden SUB!
1953 }
Aart Bikdbbac8f2017-09-01 13:06:08 -07001954 }
1955 }
1956 if (a == nullptr || b == nullptr) {
1957 return false;
1958 }
1959 // Accept same-type or consistent sign extension for narrower-type on operands a and b.
1960 // The same-type or narrower operands are called r (a or lower) and s (b or lower).
Aart Bikdf011c32017-09-28 12:53:04 -07001961 // We inspect the operands carefully to pick the most suited type.
Aart Bikdbbac8f2017-09-01 13:06:08 -07001962 HInstruction* r = a;
1963 HInstruction* s = b;
1964 bool is_unsigned = false;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001965 DataType::Type sub_type = a->GetType();
Aart Bikdf011c32017-09-28 12:53:04 -07001966 if (DataType::Size(b->GetType()) < DataType::Size(sub_type)) {
1967 sub_type = b->GetType();
1968 }
1969 if (a->IsTypeConversion() &&
1970 DataType::Size(a->InputAt(0)->GetType()) < DataType::Size(sub_type)) {
1971 sub_type = a->InputAt(0)->GetType();
1972 }
1973 if (b->IsTypeConversion() &&
1974 DataType::Size(b->InputAt(0)->GetType()) < DataType::Size(sub_type)) {
1975 sub_type = b->InputAt(0)->GetType();
Aart Bikdbbac8f2017-09-01 13:06:08 -07001976 }
1977 if (reduction_type != sub_type &&
1978 (!IsNarrowerOperands(a, b, sub_type, &r, &s, &is_unsigned) || is_unsigned)) {
1979 return false;
1980 }
1981 // Try same/narrower type and deal with vector restrictions.
Artem Serov6e9b1372017-10-05 16:48:30 +01001982 if (!TrySetVectorType(sub_type, &restrictions) ||
1983 HasVectorRestrictions(restrictions, kNoSAD) ||
1984 (reduction_type != sub_type && HasVectorRestrictions(restrictions, kNoWideSAD))) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001985 return false;
1986 }
1987 // Accept SAD idiom for vectorizable operands. Vectorized code uses the shorthand
1988 // idiomatic operation. Sequential code uses the original scalar expressions.
1989 DCHECK(r != nullptr);
1990 DCHECK(s != nullptr);
1991 if (generate_code && vector_mode_ != kVector) { // de-idiom
1992 r = s = v->InputAt(0);
1993 }
1994 if (VectorizeUse(node, q, generate_code, sub_type, restrictions) &&
1995 VectorizeUse(node, r, generate_code, sub_type, restrictions) &&
1996 VectorizeUse(node, s, generate_code, sub_type, restrictions)) {
1997 if (generate_code) {
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001998 NormalizePackedType(&reduction_type, &is_unsigned);
Aart Bikdbbac8f2017-09-01 13:06:08 -07001999 if (vector_mode_ == kVector) {
2000 vector_map_->Put(instruction, new (global_allocator_) HVecSADAccumulate(
2001 global_allocator_,
2002 vector_map_->Get(q),
2003 vector_map_->Get(r),
2004 vector_map_->Get(s),
2005 reduction_type,
Aart Bik46b6dbc2017-10-03 11:37:37 -07002006 GetOtherVL(reduction_type, sub_type, vector_length_),
2007 kNoDexPc));
Aart Bikdbbac8f2017-09-01 13:06:08 -07002008 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorizedIdiom);
2009 } else {
2010 GenerateVecOp(v, vector_map_->Get(r), nullptr, reduction_type);
2011 GenerateVecOp(instruction, vector_map_->Get(q), vector_map_->Get(v), reduction_type);
2012 }
2013 }
2014 return true;
2015 }
2016 return false;
2017}
2018
Aart Bikf3e61ee2017-04-12 17:09:20 -07002019//
Aart Bik14a68b42017-06-08 14:06:58 -07002020// Vectorization heuristics.
2021//
2022
2023bool HLoopOptimization::IsVectorizationProfitable(int64_t trip_count) {
2024 // Current heuristic: non-empty body with sufficient number
2025 // of iterations (if known).
2026 // TODO: refine by looking at e.g. operation count, alignment, etc.
2027 if (vector_length_ == 0) {
2028 return false; // nothing found
2029 } else if (0 < trip_count && trip_count < vector_length_) {
2030 return false; // insufficient iterations
2031 }
2032 return true;
2033}
2034
Aart Bikb29f6842017-07-28 15:58:41 -07002035void HLoopOptimization::SetPeelingCandidate(const ArrayReference* candidate,
2036 int64_t trip_count ATTRIBUTE_UNUSED) {
Aart Bik14a68b42017-06-08 14:06:58 -07002037 // Current heuristic: none.
2038 // TODO: implement
Aart Bikb29f6842017-07-28 15:58:41 -07002039 vector_peeling_candidate_ = candidate;
Aart Bik14a68b42017-06-08 14:06:58 -07002040}
2041
Artem Serovf26bb6c2017-09-01 10:59:03 +01002042static constexpr uint32_t ARM64_SIMD_MAXIMUM_UNROLL_FACTOR = 8;
2043static constexpr uint32_t ARM64_SIMD_HEURISTIC_MAX_BODY_SIZE = 50;
2044
Aart Bik14a68b42017-06-08 14:06:58 -07002045uint32_t HLoopOptimization::GetUnrollingFactor(HBasicBlock* block, int64_t trip_count) {
Aart Bik14a68b42017-06-08 14:06:58 -07002046 switch (compiler_driver_->GetInstructionSet()) {
Artem Serovf26bb6c2017-09-01 10:59:03 +01002047 case kArm64: {
Aart Bik521b50f2017-09-09 10:44:45 -07002048 // Don't unroll with insufficient iterations.
Artem Serovf26bb6c2017-09-01 10:59:03 +01002049 // TODO: Unroll loops with unknown trip count.
Aart Bik521b50f2017-09-09 10:44:45 -07002050 DCHECK_NE(vector_length_, 0u);
Artem Serovf26bb6c2017-09-01 10:59:03 +01002051 if (trip_count < 2 * vector_length_) {
Aart Bik521b50f2017-09-09 10:44:45 -07002052 return kNoUnrollingFactor;
Aart Bik14a68b42017-06-08 14:06:58 -07002053 }
Aart Bik521b50f2017-09-09 10:44:45 -07002054 // Don't unroll for large loop body size.
Artem Serovf26bb6c2017-09-01 10:59:03 +01002055 uint32_t instruction_count = block->GetInstructions().CountSize();
Aart Bik521b50f2017-09-09 10:44:45 -07002056 if (instruction_count >= ARM64_SIMD_HEURISTIC_MAX_BODY_SIZE) {
2057 return kNoUnrollingFactor;
2058 }
Artem Serovf26bb6c2017-09-01 10:59:03 +01002059 // Find a beneficial unroll factor with the following restrictions:
2060 // - At least one iteration of the transformed loop should be executed.
2061 // - The loop body shouldn't be "too big" (heuristic).
2062 uint32_t uf1 = ARM64_SIMD_HEURISTIC_MAX_BODY_SIZE / instruction_count;
2063 uint32_t uf2 = trip_count / vector_length_;
2064 uint32_t unroll_factor =
2065 TruncToPowerOfTwo(std::min({uf1, uf2, ARM64_SIMD_MAXIMUM_UNROLL_FACTOR}));
2066 DCHECK_GE(unroll_factor, 1u);
Artem Serovf26bb6c2017-09-01 10:59:03 +01002067 return unroll_factor;
Aart Bik14a68b42017-06-08 14:06:58 -07002068 }
Artem Serovf26bb6c2017-09-01 10:59:03 +01002069 case kX86:
2070 case kX86_64:
Aart Bik14a68b42017-06-08 14:06:58 -07002071 default:
Aart Bik521b50f2017-09-09 10:44:45 -07002072 return kNoUnrollingFactor;
Aart Bik14a68b42017-06-08 14:06:58 -07002073 }
2074}
2075
2076//
Aart Bikf8f5a162017-02-06 15:35:29 -08002077// Helpers.
2078//
2079
2080bool HLoopOptimization::TrySetPhiInduction(HPhi* phi, bool restrict_uses) {
Aart Bikb29f6842017-07-28 15:58:41 -07002081 // Start with empty phi induction.
2082 iset_->clear();
2083
Nicolas Geoffrayf57c1ae2017-06-28 17:40:18 +01002084 // Special case Phis that have equivalent in a debuggable setup. Our graph checker isn't
2085 // smart enough to follow strongly connected components (and it's probably not worth
2086 // it to make it so). See b/33775412.
2087 if (graph_->IsDebuggable() && phi->HasEquivalentPhi()) {
2088 return false;
2089 }
Aart Bikb29f6842017-07-28 15:58:41 -07002090
2091 // Lookup phi induction cycle.
Aart Bikcc42be02016-10-20 16:14:16 -07002092 ArenaSet<HInstruction*>* set = induction_range_.LookupCycle(phi);
2093 if (set != nullptr) {
2094 for (HInstruction* i : *set) {
Aart Bike3dedc52016-11-02 17:50:27 -07002095 // Check that, other than instructions that are no longer in the graph (removed earlier)
Aart Bikf8f5a162017-02-06 15:35:29 -08002096 // each instruction is removable and, when restrict uses are requested, other than for phi,
2097 // all uses are contained within the cycle.
Aart Bike3dedc52016-11-02 17:50:27 -07002098 if (!i->IsInBlock()) {
2099 continue;
2100 } else if (!i->IsRemovable()) {
2101 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08002102 } else if (i != phi && restrict_uses) {
Aart Bikb29f6842017-07-28 15:58:41 -07002103 // Deal with regular uses.
Aart Bikcc42be02016-10-20 16:14:16 -07002104 for (const HUseListNode<HInstruction*>& use : i->GetUses()) {
2105 if (set->find(use.GetUser()) == set->end()) {
2106 return false;
2107 }
2108 }
2109 }
Aart Bike3dedc52016-11-02 17:50:27 -07002110 iset_->insert(i); // copy
Aart Bikcc42be02016-10-20 16:14:16 -07002111 }
Aart Bikcc42be02016-10-20 16:14:16 -07002112 return true;
2113 }
2114 return false;
2115}
2116
Aart Bikb29f6842017-07-28 15:58:41 -07002117bool HLoopOptimization::TrySetPhiReduction(HPhi* phi) {
Aart Bikcc42be02016-10-20 16:14:16 -07002118 DCHECK(iset_->empty());
Aart Bikb29f6842017-07-28 15:58:41 -07002119 // Only unclassified phi cycles are candidates for reductions.
2120 if (induction_range_.IsClassified(phi)) {
2121 return false;
2122 }
2123 // Accept operations like x = x + .., provided that the phi and the reduction are
2124 // used exactly once inside the loop, and by each other.
2125 HInputsRef inputs = phi->GetInputs();
2126 if (inputs.size() == 2) {
2127 HInstruction* reduction = inputs[1];
2128 if (HasReductionFormat(reduction, phi)) {
2129 HLoopInformation* loop_info = phi->GetBlock()->GetLoopInformation();
2130 int32_t use_count = 0;
2131 bool single_use_inside_loop =
2132 // Reduction update only used by phi.
2133 reduction->GetUses().HasExactlyOneElement() &&
2134 !reduction->HasEnvironmentUses() &&
2135 // Reduction update is only use of phi inside the loop.
2136 IsOnlyUsedAfterLoop(loop_info, phi, /*collect_loop_uses*/ true, &use_count) &&
2137 iset_->size() == 1;
2138 iset_->clear(); // leave the way you found it
2139 if (single_use_inside_loop) {
2140 // Link reduction back, and start recording feed value.
2141 reductions_->Put(reduction, phi);
2142 reductions_->Put(phi, phi->InputAt(0));
2143 return true;
2144 }
2145 }
2146 }
2147 return false;
2148}
2149
2150bool HLoopOptimization::TrySetSimpleLoopHeader(HBasicBlock* block, /*out*/ HPhi** main_phi) {
2151 // Start with empty phi induction and reductions.
2152 iset_->clear();
2153 reductions_->clear();
2154
2155 // Scan the phis to find the following (the induction structure has already
2156 // been optimized, so we don't need to worry about trivial cases):
2157 // (1) optional reductions in loop,
2158 // (2) the main induction, used in loop control.
2159 HPhi* phi = nullptr;
2160 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
2161 if (TrySetPhiReduction(it.Current()->AsPhi())) {
2162 continue;
2163 } else if (phi == nullptr) {
2164 // Found the first candidate for main induction.
2165 phi = it.Current()->AsPhi();
2166 } else {
2167 return false;
2168 }
2169 }
2170
2171 // Then test for a typical loopheader:
2172 // s: SuspendCheck
2173 // c: Condition(phi, bound)
2174 // i: If(c)
2175 if (phi != nullptr && TrySetPhiInduction(phi, /*restrict_uses*/ false)) {
Aart Bikcc42be02016-10-20 16:14:16 -07002176 HInstruction* s = block->GetFirstInstruction();
2177 if (s != nullptr && s->IsSuspendCheck()) {
2178 HInstruction* c = s->GetNext();
Aart Bikd86c0852017-04-14 12:00:15 -07002179 if (c != nullptr &&
2180 c->IsCondition() &&
2181 c->GetUses().HasExactlyOneElement() && // only used for termination
2182 !c->HasEnvironmentUses()) { // unlikely, but not impossible
Aart Bikcc42be02016-10-20 16:14:16 -07002183 HInstruction* i = c->GetNext();
2184 if (i != nullptr && i->IsIf() && i->InputAt(0) == c) {
2185 iset_->insert(c);
2186 iset_->insert(s);
Aart Bikb29f6842017-07-28 15:58:41 -07002187 *main_phi = phi;
Aart Bikcc42be02016-10-20 16:14:16 -07002188 return true;
2189 }
2190 }
2191 }
2192 }
2193 return false;
2194}
2195
2196bool HLoopOptimization::IsEmptyBody(HBasicBlock* block) {
Aart Bikf8f5a162017-02-06 15:35:29 -08002197 if (!block->GetPhis().IsEmpty()) {
2198 return false;
2199 }
2200 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
2201 HInstruction* instruction = it.Current();
2202 if (!instruction->IsGoto() && iset_->find(instruction) == iset_->end()) {
2203 return false;
Aart Bikcc42be02016-10-20 16:14:16 -07002204 }
Aart Bikf8f5a162017-02-06 15:35:29 -08002205 }
2206 return true;
2207}
2208
2209bool HLoopOptimization::IsUsedOutsideLoop(HLoopInformation* loop_info,
2210 HInstruction* instruction) {
Aart Bikb29f6842017-07-28 15:58:41 -07002211 // Deal with regular uses.
Aart Bikf8f5a162017-02-06 15:35:29 -08002212 for (const HUseListNode<HInstruction*>& use : instruction->GetUses()) {
2213 if (use.GetUser()->GetBlock()->GetLoopInformation() != loop_info) {
2214 return true;
2215 }
Aart Bikcc42be02016-10-20 16:14:16 -07002216 }
2217 return false;
2218}
2219
Aart Bik482095d2016-10-10 15:39:10 -07002220bool HLoopOptimization::IsOnlyUsedAfterLoop(HLoopInformation* loop_info,
Aart Bik8c4a8542016-10-06 11:36:57 -07002221 HInstruction* instruction,
Aart Bik6b69e0a2017-01-11 10:20:43 -08002222 bool collect_loop_uses,
Aart Bik8c4a8542016-10-06 11:36:57 -07002223 /*out*/ int32_t* use_count) {
Aart Bikb29f6842017-07-28 15:58:41 -07002224 // Deal with regular uses.
Aart Bik8c4a8542016-10-06 11:36:57 -07002225 for (const HUseListNode<HInstruction*>& use : instruction->GetUses()) {
2226 HInstruction* user = use.GetUser();
2227 if (iset_->find(user) == iset_->end()) { // not excluded?
2228 HLoopInformation* other_loop_info = user->GetBlock()->GetLoopInformation();
Aart Bik482095d2016-10-10 15:39:10 -07002229 if (other_loop_info != nullptr && other_loop_info->IsIn(*loop_info)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -08002230 // If collect_loop_uses is set, simply keep adding those uses to the set.
2231 // Otherwise, reject uses inside the loop that were not already in the set.
2232 if (collect_loop_uses) {
2233 iset_->insert(user);
2234 continue;
2235 }
Aart Bik8c4a8542016-10-06 11:36:57 -07002236 return false;
2237 }
2238 ++*use_count;
2239 }
2240 }
2241 return true;
2242}
2243
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002244bool HLoopOptimization::TryReplaceWithLastValue(HLoopInformation* loop_info,
2245 HInstruction* instruction,
2246 HBasicBlock* block) {
2247 // Try to replace outside uses with the last value.
Aart Bik807868e2016-11-03 17:51:43 -07002248 if (induction_range_.CanGenerateLastValue(instruction)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -08002249 HInstruction* replacement = induction_range_.GenerateLastValue(instruction, graph_, block);
Aart Bikb29f6842017-07-28 15:58:41 -07002250 // Deal with regular uses.
Aart Bik6b69e0a2017-01-11 10:20:43 -08002251 const HUseList<HInstruction*>& uses = instruction->GetUses();
2252 for (auto it = uses.begin(), end = uses.end(); it != end;) {
2253 HInstruction* user = it->GetUser();
2254 size_t index = it->GetIndex();
2255 ++it; // increment before replacing
2256 if (iset_->find(user) == iset_->end()) { // not excluded?
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002257 if (kIsDebugBuild) {
2258 // We have checked earlier in 'IsOnlyUsedAfterLoop' that the use is after the loop.
2259 HLoopInformation* other_loop_info = user->GetBlock()->GetLoopInformation();
2260 CHECK(other_loop_info == nullptr || !other_loop_info->IsIn(*loop_info));
2261 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08002262 user->ReplaceInput(replacement, index);
2263 induction_range_.Replace(user, instruction, replacement); // update induction
2264 }
2265 }
Aart Bikb29f6842017-07-28 15:58:41 -07002266 // Deal with environment uses.
Aart Bik6b69e0a2017-01-11 10:20:43 -08002267 const HUseList<HEnvironment*>& env_uses = instruction->GetEnvUses();
2268 for (auto it = env_uses.begin(), end = env_uses.end(); it != end;) {
2269 HEnvironment* user = it->GetUser();
2270 size_t index = it->GetIndex();
2271 ++it; // increment before replacing
2272 if (iset_->find(user->GetHolder()) == iset_->end()) { // not excluded?
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002273 // Only update environment uses after the loop.
Aart Bik14a68b42017-06-08 14:06:58 -07002274 HLoopInformation* other_loop_info = user->GetHolder()->GetBlock()->GetLoopInformation();
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002275 if (other_loop_info == nullptr || !other_loop_info->IsIn(*loop_info)) {
2276 user->RemoveAsUserOfInput(index);
2277 user->SetRawEnvAt(index, replacement);
2278 replacement->AddEnvUseAt(user, index);
2279 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08002280 }
2281 }
Aart Bik807868e2016-11-03 17:51:43 -07002282 return true;
Aart Bik8c4a8542016-10-06 11:36:57 -07002283 }
Aart Bik807868e2016-11-03 17:51:43 -07002284 return false;
Aart Bik8c4a8542016-10-06 11:36:57 -07002285}
2286
Aart Bikf8f5a162017-02-06 15:35:29 -08002287bool HLoopOptimization::TryAssignLastValue(HLoopInformation* loop_info,
2288 HInstruction* instruction,
2289 HBasicBlock* block,
2290 bool collect_loop_uses) {
2291 // Assigning the last value is always successful if there are no uses.
2292 // Otherwise, it succeeds in a no early-exit loop by generating the
2293 // proper last value assignment.
2294 int32_t use_count = 0;
2295 return IsOnlyUsedAfterLoop(loop_info, instruction, collect_loop_uses, &use_count) &&
2296 (use_count == 0 ||
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002297 (!IsEarlyExit(loop_info) && TryReplaceWithLastValue(loop_info, instruction, block)));
Aart Bikf8f5a162017-02-06 15:35:29 -08002298}
2299
Aart Bik6b69e0a2017-01-11 10:20:43 -08002300void HLoopOptimization::RemoveDeadInstructions(const HInstructionList& list) {
2301 for (HBackwardInstructionIterator i(list); !i.Done(); i.Advance()) {
2302 HInstruction* instruction = i.Current();
2303 if (instruction->IsDeadAndRemovable()) {
2304 simplified_ = true;
2305 instruction->GetBlock()->RemoveInstructionOrPhi(instruction);
2306 }
2307 }
2308}
2309
Aart Bik14a68b42017-06-08 14:06:58 -07002310bool HLoopOptimization::CanRemoveCycle() {
2311 for (HInstruction* i : *iset_) {
2312 // We can never remove instructions that have environment
2313 // uses when we compile 'debuggable'.
2314 if (i->HasEnvironmentUses() && graph_->IsDebuggable()) {
2315 return false;
2316 }
2317 // A deoptimization should never have an environment input removed.
2318 for (const HUseListNode<HEnvironment*>& use : i->GetEnvUses()) {
2319 if (use.GetUser()->GetHolder()->IsDeoptimize()) {
2320 return false;
2321 }
2322 }
2323 }
2324 return true;
2325}
2326
Aart Bik281c6812016-08-26 11:31:48 -07002327} // namespace art