blob: 2090a12929dbc01300386656bd7c7d14fb39c7b8 [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.
432static bool CheckInductionSetFullyRemoved(ArenaSet<HInstruction*>* iset) {
433 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),
Aart Bikf8f5a162017-02-06 15:35:29 -0800456 global_allocator_(graph_->GetArena()),
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),
468 vector_permanent_map_(nullptr) {
Aart Bik281c6812016-08-26 11:31:48 -0700469}
470
471void HLoopOptimization::Run() {
Mingyao Yang01b47b02017-02-03 12:09:57 -0800472 // Skip if there is no loop or the graph has try-catch/irreducible loops.
Aart Bik281c6812016-08-26 11:31:48 -0700473 // TODO: make this less of a sledgehammer.
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800474 if (!graph_->HasLoops() || graph_->HasTryCatch() || graph_->HasIrreducibleLoops()) {
Aart Bik281c6812016-08-26 11:31:48 -0700475 return;
476 }
477
Aart Bik96202302016-10-04 17:33:56 -0700478 // Phase-local allocator that draws from the global pool. Since the allocator
479 // itself resides on the stack, it is destructed on exiting Run(), which
480 // implies its underlying memory is released immediately.
Aart Bikf8f5a162017-02-06 15:35:29 -0800481 ArenaAllocator allocator(global_allocator_->GetArenaPool());
Aart Bik96202302016-10-04 17:33:56 -0700482 loop_allocator_ = &allocator;
Nicolas Geoffrayebe16742016-10-05 09:55:42 +0100483
Aart Bik96202302016-10-04 17:33:56 -0700484 // Perform loop optimizations.
485 LocalRun();
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800486 if (top_loop_ == nullptr) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800487 graph_->SetHasLoops(false); // no more loops
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800488 }
489
Aart Bik96202302016-10-04 17:33:56 -0700490 // Detach.
491 loop_allocator_ = nullptr;
492 last_loop_ = top_loop_ = nullptr;
493}
494
Aart Bikb29f6842017-07-28 15:58:41 -0700495//
496// Loop setup and traversal.
497//
498
Aart Bik96202302016-10-04 17:33:56 -0700499void HLoopOptimization::LocalRun() {
500 // Build the linear order using the phase-local allocator. This step enables building
501 // a loop hierarchy that properly reflects the outer-inner and previous-next relation.
502 ArenaVector<HBasicBlock*> linear_order(loop_allocator_->Adapter(kArenaAllocLinearOrder));
503 LinearizeGraph(graph_, loop_allocator_, &linear_order);
504
Aart Bik281c6812016-08-26 11:31:48 -0700505 // Build the loop hierarchy.
Aart Bik96202302016-10-04 17:33:56 -0700506 for (HBasicBlock* block : linear_order) {
Aart Bik281c6812016-08-26 11:31:48 -0700507 if (block->IsLoopHeader()) {
508 AddLoop(block->GetLoopInformation());
509 }
510 }
Aart Bik96202302016-10-04 17:33:56 -0700511
Aart Bik8c4a8542016-10-06 11:36:57 -0700512 // Traverse the loop hierarchy inner-to-outer and optimize. Traversal can use
Aart Bikf8f5a162017-02-06 15:35:29 -0800513 // temporary data structures using the phase-local allocator. All new HIR
514 // should use the global allocator.
Aart Bik8c4a8542016-10-06 11:36:57 -0700515 if (top_loop_ != nullptr) {
516 ArenaSet<HInstruction*> iset(loop_allocator_->Adapter(kArenaAllocLoopOptimization));
Aart Bikb29f6842017-07-28 15:58:41 -0700517 ArenaSafeMap<HInstruction*, HInstruction*> reds(
518 std::less<HInstruction*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
Aart Bikf8f5a162017-02-06 15:35:29 -0800519 ArenaSet<ArrayReference> refs(loop_allocator_->Adapter(kArenaAllocLoopOptimization));
520 ArenaSafeMap<HInstruction*, HInstruction*> map(
521 std::less<HInstruction*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
Aart Bik0148de42017-09-05 09:25:01 -0700522 ArenaSafeMap<HInstruction*, HInstruction*> perm(
523 std::less<HInstruction*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
Aart Bikf8f5a162017-02-06 15:35:29 -0800524 // Attach.
Aart Bik8c4a8542016-10-06 11:36:57 -0700525 iset_ = &iset;
Aart Bikb29f6842017-07-28 15:58:41 -0700526 reductions_ = &reds;
Aart Bikf8f5a162017-02-06 15:35:29 -0800527 vector_refs_ = &refs;
528 vector_map_ = &map;
Aart Bik0148de42017-09-05 09:25:01 -0700529 vector_permanent_map_ = &perm;
Aart Bikf8f5a162017-02-06 15:35:29 -0800530 // Traverse.
Aart Bik8c4a8542016-10-06 11:36:57 -0700531 TraverseLoopsInnerToOuter(top_loop_);
Aart Bikf8f5a162017-02-06 15:35:29 -0800532 // Detach.
533 iset_ = nullptr;
Aart Bikb29f6842017-07-28 15:58:41 -0700534 reductions_ = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800535 vector_refs_ = nullptr;
536 vector_map_ = nullptr;
Aart Bik0148de42017-09-05 09:25:01 -0700537 vector_permanent_map_ = nullptr;
Aart Bik8c4a8542016-10-06 11:36:57 -0700538 }
Aart Bik281c6812016-08-26 11:31:48 -0700539}
540
541void HLoopOptimization::AddLoop(HLoopInformation* loop_info) {
542 DCHECK(loop_info != nullptr);
Aart Bikf8f5a162017-02-06 15:35:29 -0800543 LoopNode* node = new (loop_allocator_) LoopNode(loop_info);
Aart Bik281c6812016-08-26 11:31:48 -0700544 if (last_loop_ == nullptr) {
545 // First loop.
546 DCHECK(top_loop_ == nullptr);
547 last_loop_ = top_loop_ = node;
548 } else if (loop_info->IsIn(*last_loop_->loop_info)) {
549 // Inner loop.
550 node->outer = last_loop_;
551 DCHECK(last_loop_->inner == nullptr);
552 last_loop_ = last_loop_->inner = node;
553 } else {
554 // Subsequent loop.
555 while (last_loop_->outer != nullptr && !loop_info->IsIn(*last_loop_->outer->loop_info)) {
556 last_loop_ = last_loop_->outer;
557 }
558 node->outer = last_loop_->outer;
559 node->previous = last_loop_;
560 DCHECK(last_loop_->next == nullptr);
561 last_loop_ = last_loop_->next = node;
562 }
563}
564
565void HLoopOptimization::RemoveLoop(LoopNode* node) {
566 DCHECK(node != nullptr);
Aart Bik8c4a8542016-10-06 11:36:57 -0700567 DCHECK(node->inner == nullptr);
568 if (node->previous != nullptr) {
569 // Within sequence.
570 node->previous->next = node->next;
571 if (node->next != nullptr) {
572 node->next->previous = node->previous;
573 }
574 } else {
575 // First of sequence.
576 if (node->outer != nullptr) {
577 node->outer->inner = node->next;
578 } else {
579 top_loop_ = node->next;
580 }
581 if (node->next != nullptr) {
582 node->next->outer = node->outer;
583 node->next->previous = nullptr;
584 }
585 }
Aart Bik281c6812016-08-26 11:31:48 -0700586}
587
Aart Bikb29f6842017-07-28 15:58:41 -0700588bool HLoopOptimization::TraverseLoopsInnerToOuter(LoopNode* node) {
589 bool changed = false;
Aart Bik281c6812016-08-26 11:31:48 -0700590 for ( ; node != nullptr; node = node->next) {
Aart Bikb29f6842017-07-28 15:58:41 -0700591 // Visit inner loops first. Recompute induction information for this
592 // loop if the induction of any inner loop has changed.
593 if (TraverseLoopsInnerToOuter(node->inner)) {
Aart Bik482095d2016-10-10 15:39:10 -0700594 induction_range_.ReVisit(node->loop_info);
595 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800596 // Repeat simplifications in the loop-body until no more changes occur.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800597 // Note that since each simplification consists of eliminating code (without
598 // introducing new code), this process is always finite.
Aart Bikdf7822e2016-12-06 10:05:30 -0800599 do {
600 simplified_ = false;
Aart Bikdf7822e2016-12-06 10:05:30 -0800601 SimplifyInduction(node);
Aart Bik6b69e0a2017-01-11 10:20:43 -0800602 SimplifyBlocks(node);
Aart Bikb29f6842017-07-28 15:58:41 -0700603 changed = simplified_ || changed;
Aart Bikdf7822e2016-12-06 10:05:30 -0800604 } while (simplified_);
Aart Bikf8f5a162017-02-06 15:35:29 -0800605 // Optimize inner loop.
Aart Bik9abf8942016-10-14 09:49:42 -0700606 if (node->inner == nullptr) {
Aart Bikb29f6842017-07-28 15:58:41 -0700607 changed = OptimizeInnerLoop(node) || changed;
Aart Bik9abf8942016-10-14 09:49:42 -0700608 }
Aart Bik281c6812016-08-26 11:31:48 -0700609 }
Aart Bikb29f6842017-07-28 15:58:41 -0700610 return changed;
Aart Bik281c6812016-08-26 11:31:48 -0700611}
612
Aart Bikf8f5a162017-02-06 15:35:29 -0800613//
614// Optimization.
615//
616
Aart Bik281c6812016-08-26 11:31:48 -0700617void HLoopOptimization::SimplifyInduction(LoopNode* node) {
618 HBasicBlock* header = node->loop_info->GetHeader();
619 HBasicBlock* preheader = node->loop_info->GetPreHeader();
Aart Bik8c4a8542016-10-06 11:36:57 -0700620 // Scan the phis in the header to find opportunities to simplify an induction
621 // cycle that is only used outside the loop. Replace these uses, if any, with
622 // the last value and remove the induction cycle.
623 // Examples: for (int i = 0; x != null; i++) { .... no i .... }
624 // for (int i = 0; i < 10; i++, k++) { .... no k .... } return k;
Aart Bik281c6812016-08-26 11:31:48 -0700625 for (HInstructionIterator it(header->GetPhis()); !it.Done(); it.Advance()) {
626 HPhi* phi = it.Current()->AsPhi();
Aart Bikf8f5a162017-02-06 15:35:29 -0800627 if (TrySetPhiInduction(phi, /*restrict_uses*/ true) &&
628 TryAssignLastValue(node->loop_info, phi, preheader, /*collect_loop_uses*/ false)) {
Aart Bik671e48a2017-08-09 13:16:56 -0700629 // Note that it's ok to have replaced uses after the loop with the last value, without
630 // being able to remove the cycle. Environment uses (which are the reason we may not be
631 // able to remove the cycle) within the loop will still hold the right value. We must
632 // have tried first, however, to replace outside uses.
633 if (CanRemoveCycle()) {
634 simplified_ = true;
635 for (HInstruction* i : *iset_) {
636 RemoveFromCycle(i);
637 }
638 DCHECK(CheckInductionSetFullyRemoved(iset_));
Aart Bik281c6812016-08-26 11:31:48 -0700639 }
Aart Bik482095d2016-10-10 15:39:10 -0700640 }
641 }
642}
643
644void HLoopOptimization::SimplifyBlocks(LoopNode* node) {
Aart Bikdf7822e2016-12-06 10:05:30 -0800645 // Iterate over all basic blocks in the loop-body.
646 for (HBlocksInLoopIterator it(*node->loop_info); !it.Done(); it.Advance()) {
647 HBasicBlock* block = it.Current();
648 // Remove dead instructions from the loop-body.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800649 RemoveDeadInstructions(block->GetPhis());
650 RemoveDeadInstructions(block->GetInstructions());
Aart Bikdf7822e2016-12-06 10:05:30 -0800651 // Remove trivial control flow blocks from the loop-body.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800652 if (block->GetPredecessors().size() == 1 &&
653 block->GetSuccessors().size() == 1 &&
654 block->GetSingleSuccessor()->GetPredecessors().size() == 1) {
Aart Bikdf7822e2016-12-06 10:05:30 -0800655 simplified_ = true;
Aart Bik6b69e0a2017-01-11 10:20:43 -0800656 block->MergeWith(block->GetSingleSuccessor());
Aart Bikdf7822e2016-12-06 10:05:30 -0800657 } else if (block->GetSuccessors().size() == 2) {
658 // Trivial if block can be bypassed to either branch.
659 HBasicBlock* succ0 = block->GetSuccessors()[0];
660 HBasicBlock* succ1 = block->GetSuccessors()[1];
661 HBasicBlock* meet0 = nullptr;
662 HBasicBlock* meet1 = nullptr;
663 if (succ0 != succ1 &&
664 IsGotoBlock(succ0, &meet0) &&
665 IsGotoBlock(succ1, &meet1) &&
666 meet0 == meet1 && // meets again
667 meet0 != block && // no self-loop
668 meet0->GetPhis().IsEmpty()) { // not used for merging
669 simplified_ = true;
670 succ0->DisconnectAndDelete();
671 if (block->Dominates(meet0)) {
672 block->RemoveDominatedBlock(meet0);
673 succ1->AddDominatedBlock(meet0);
674 meet0->SetDominator(succ1);
Aart Bike3dedc52016-11-02 17:50:27 -0700675 }
Aart Bik482095d2016-10-10 15:39:10 -0700676 }
Aart Bik281c6812016-08-26 11:31:48 -0700677 }
Aart Bikdf7822e2016-12-06 10:05:30 -0800678 }
Aart Bik281c6812016-08-26 11:31:48 -0700679}
680
Aart Bikb29f6842017-07-28 15:58:41 -0700681bool HLoopOptimization::OptimizeInnerLoop(LoopNode* node) {
Aart Bik281c6812016-08-26 11:31:48 -0700682 HBasicBlock* header = node->loop_info->GetHeader();
683 HBasicBlock* preheader = node->loop_info->GetPreHeader();
Aart Bik9abf8942016-10-14 09:49:42 -0700684 // Ensure loop header logic is finite.
Aart Bikf8f5a162017-02-06 15:35:29 -0800685 int64_t trip_count = 0;
686 if (!induction_range_.IsFinite(node->loop_info, &trip_count)) {
Aart Bikb29f6842017-07-28 15:58:41 -0700687 return false;
Aart Bik9abf8942016-10-14 09:49:42 -0700688 }
Aart Bik281c6812016-08-26 11:31:48 -0700689 // Ensure there is only a single loop-body (besides the header).
690 HBasicBlock* body = nullptr;
691 for (HBlocksInLoopIterator it(*node->loop_info); !it.Done(); it.Advance()) {
692 if (it.Current() != header) {
693 if (body != nullptr) {
Aart Bikb29f6842017-07-28 15:58:41 -0700694 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700695 }
696 body = it.Current();
697 }
698 }
Andreas Gampef45d61c2017-06-07 10:29:33 -0700699 CHECK(body != nullptr);
Aart Bik281c6812016-08-26 11:31:48 -0700700 // Ensure there is only a single exit point.
701 if (header->GetSuccessors().size() != 2) {
Aart Bikb29f6842017-07-28 15:58:41 -0700702 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700703 }
704 HBasicBlock* exit = (header->GetSuccessors()[0] == body)
705 ? header->GetSuccessors()[1]
706 : header->GetSuccessors()[0];
Aart Bik8c4a8542016-10-06 11:36:57 -0700707 // Ensure exit can only be reached by exiting loop.
Aart Bik281c6812016-08-26 11:31:48 -0700708 if (exit->GetPredecessors().size() != 1) {
Aart Bikb29f6842017-07-28 15:58:41 -0700709 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700710 }
Aart Bik6b69e0a2017-01-11 10:20:43 -0800711 // Detect either an empty loop (no side effects other than plain iteration) or
712 // a trivial loop (just iterating once). Replace subsequent index uses, if any,
713 // with the last value and remove the loop, possibly after unrolling its body.
Aart Bikb29f6842017-07-28 15:58:41 -0700714 HPhi* main_phi = nullptr;
715 if (TrySetSimpleLoopHeader(header, &main_phi)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -0800716 bool is_empty = IsEmptyBody(body);
Aart Bikb29f6842017-07-28 15:58:41 -0700717 if (reductions_->empty() && // TODO: possible with some effort
718 (is_empty || trip_count == 1) &&
719 TryAssignLastValue(node->loop_info, main_phi, preheader, /*collect_loop_uses*/ true)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -0800720 if (!is_empty) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800721 // Unroll the loop-body, which sees initial value of the index.
Aart Bikb29f6842017-07-28 15:58:41 -0700722 main_phi->ReplaceWith(main_phi->InputAt(0));
Aart Bik6b69e0a2017-01-11 10:20:43 -0800723 preheader->MergeInstructionsWith(body);
724 }
725 body->DisconnectAndDelete();
726 exit->RemovePredecessor(header);
727 header->RemoveSuccessor(exit);
728 header->RemoveDominatedBlock(exit);
729 header->DisconnectAndDelete();
730 preheader->AddSuccessor(exit);
Aart Bikf8f5a162017-02-06 15:35:29 -0800731 preheader->AddInstruction(new (global_allocator_) HGoto());
Aart Bik6b69e0a2017-01-11 10:20:43 -0800732 preheader->AddDominatedBlock(exit);
733 exit->SetDominator(preheader);
734 RemoveLoop(node); // update hierarchy
Aart Bikb29f6842017-07-28 15:58:41 -0700735 return true;
Aart Bikf8f5a162017-02-06 15:35:29 -0800736 }
737 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800738 // Vectorize loop, if possible and valid.
Aart Bikb29f6842017-07-28 15:58:41 -0700739 if (kEnableVectorization &&
740 TrySetSimpleLoopHeader(header, &main_phi) &&
Aart Bikb29f6842017-07-28 15:58:41 -0700741 ShouldVectorize(node, body, trip_count) &&
742 TryAssignLastValue(node->loop_info, main_phi, preheader, /*collect_loop_uses*/ true)) {
743 Vectorize(node, body, exit, trip_count);
744 graph_->SetHasSIMD(true); // flag SIMD usage
Aart Bik21b85922017-09-06 13:29:16 -0700745 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorized);
Aart Bikb29f6842017-07-28 15:58:41 -0700746 return true;
Aart Bikf8f5a162017-02-06 15:35:29 -0800747 }
Aart Bikb29f6842017-07-28 15:58:41 -0700748 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -0800749}
750
751//
752// Loop vectorization. The implementation is based on the book by Aart J.C. Bik:
753// "The Software Vectorization Handbook. Applying Multimedia Extensions for Maximum Performance."
754// Intel Press, June, 2004 (http://www.aartbik.com/).
755//
756
Aart Bik14a68b42017-06-08 14:06:58 -0700757bool HLoopOptimization::ShouldVectorize(LoopNode* node, HBasicBlock* block, int64_t trip_count) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800758 // Reset vector bookkeeping.
759 vector_length_ = 0;
760 vector_refs_->clear();
Aart Bik14a68b42017-06-08 14:06:58 -0700761 vector_peeling_candidate_ = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800762 vector_runtime_test_a_ =
763 vector_runtime_test_b_= nullptr;
764
765 // Phis in the loop-body prevent vectorization.
766 if (!block->GetPhis().IsEmpty()) {
767 return false;
768 }
769
770 // Scan the loop-body, starting a right-hand-side tree traversal at each left-hand-side
771 // occurrence, which allows passing down attributes down the use tree.
772 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
773 if (!VectorizeDef(node, it.Current(), /*generate_code*/ false)) {
774 return false; // failure to vectorize a left-hand-side
775 }
776 }
777
Aart Bik14a68b42017-06-08 14:06:58 -0700778 // Does vectorization seem profitable?
779 if (!IsVectorizationProfitable(trip_count)) {
780 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -0800781 }
782
783 // Data dependence analysis. Find each pair of references with same type, where
784 // at least one is a write. Each such pair denotes a possible data dependence.
785 // This analysis exploits the property that differently typed arrays cannot be
786 // aliased, as well as the property that references either point to the same
787 // array or to two completely disjoint arrays, i.e., no partial aliasing.
788 // Other than a few simply heuristics, no detailed subscript analysis is done.
Aart Bikb29f6842017-07-28 15:58:41 -0700789 // The scan over references also finds a suitable dynamic loop peeling candidate.
790 const ArrayReference* candidate = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800791 for (auto i = vector_refs_->begin(); i != vector_refs_->end(); ++i) {
792 for (auto j = i; ++j != vector_refs_->end(); ) {
793 if (i->type == j->type && (i->lhs || j->lhs)) {
794 // Found same-typed a[i+x] vs. b[i+y], where at least one is a write.
795 HInstruction* a = i->base;
796 HInstruction* b = j->base;
797 HInstruction* x = i->offset;
798 HInstruction* y = j->offset;
799 if (a == b) {
800 // Found a[i+x] vs. a[i+y]. Accept if x == y (loop-independent data dependence).
801 // Conservatively assume a loop-carried data dependence otherwise, and reject.
802 if (x != y) {
803 return false;
804 }
805 } else {
806 // Found a[i+x] vs. b[i+y]. Accept if x == y (at worst loop-independent data dependence).
807 // Conservatively assume a potential loop-carried data dependence otherwise, avoided by
808 // generating an explicit a != b disambiguation runtime test on the two references.
809 if (x != y) {
Aart Bik37dc4df2017-06-28 14:08:00 -0700810 // To avoid excessive overhead, we only accept one a != b test.
811 if (vector_runtime_test_a_ == nullptr) {
812 // First test found.
813 vector_runtime_test_a_ = a;
814 vector_runtime_test_b_ = b;
815 } else if ((vector_runtime_test_a_ != a || vector_runtime_test_b_ != b) &&
816 (vector_runtime_test_a_ != b || vector_runtime_test_b_ != a)) {
817 return false; // second test would be needed
Aart Bikf8f5a162017-02-06 15:35:29 -0800818 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800819 }
820 }
821 }
822 }
823 }
824
Aart Bik14a68b42017-06-08 14:06:58 -0700825 // Consider dynamic loop peeling for alignment.
Aart Bikb29f6842017-07-28 15:58:41 -0700826 SetPeelingCandidate(candidate, trip_count);
Aart Bik14a68b42017-06-08 14:06:58 -0700827
Aart Bikf8f5a162017-02-06 15:35:29 -0800828 // Success!
829 return true;
830}
831
832void HLoopOptimization::Vectorize(LoopNode* node,
833 HBasicBlock* block,
834 HBasicBlock* exit,
835 int64_t trip_count) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800836 HBasicBlock* header = node->loop_info->GetHeader();
837 HBasicBlock* preheader = node->loop_info->GetPreHeader();
838
Aart Bik14a68b42017-06-08 14:06:58 -0700839 // Pick a loop unrolling factor for the vector loop.
840 uint32_t unroll = GetUnrollingFactor(block, trip_count);
841 uint32_t chunk = vector_length_ * unroll;
842
843 // A cleanup loop is needed, at least, for any unknown trip count or
844 // for a known trip count with remainder iterations after vectorization.
845 bool needs_cleanup = trip_count == 0 || (trip_count % chunk) != 0;
Aart Bikf8f5a162017-02-06 15:35:29 -0800846
847 // Adjust vector bookkeeping.
Aart Bikb29f6842017-07-28 15:58:41 -0700848 HPhi* main_phi = nullptr;
849 bool is_simple_loop_header = TrySetSimpleLoopHeader(header, &main_phi); // refills sets
Aart Bikf8f5a162017-02-06 15:35:29 -0800850 DCHECK(is_simple_loop_header);
Aart Bik14a68b42017-06-08 14:06:58 -0700851 vector_header_ = header;
852 vector_body_ = block;
Aart Bikf8f5a162017-02-06 15:35:29 -0800853
Aart Bikdbbac8f2017-09-01 13:06:08 -0700854 // Loop induction type.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100855 DataType::Type induc_type = main_phi->GetType();
856 DCHECK(induc_type == DataType::Type::kInt32 || induc_type == DataType::Type::kInt64)
857 << induc_type;
Aart Bikdbbac8f2017-09-01 13:06:08 -0700858
Aart Bikb29f6842017-07-28 15:58:41 -0700859 // Generate dynamic loop peeling trip count, if needed, under the assumption
860 // that the Android runtime guarantees at least "component size" alignment:
861 // ptc = (ALIGN - (&a[initial] % ALIGN)) / type-size
Aart Bik14a68b42017-06-08 14:06:58 -0700862 HInstruction* ptc = nullptr;
863 if (vector_peeling_candidate_ != nullptr) {
864 DCHECK_LT(vector_length_, trip_count) << "dynamic peeling currently requires known trip count";
865 //
866 // TODO: Implement this. Compute address of first access memory location and
867 // compute peeling factor to obtain kAlignedBase alignment.
868 //
869 needs_cleanup = true;
870 }
871
872 // Generate loop control:
Aart Bikf8f5a162017-02-06 15:35:29 -0800873 // stc = <trip-count>;
Aart Bik14a68b42017-06-08 14:06:58 -0700874 // vtc = stc - (stc - ptc) % chunk;
875 // i = 0;
Aart Bikf8f5a162017-02-06 15:35:29 -0800876 HInstruction* stc = induction_range_.GenerateTripCount(node->loop_info, graph_, preheader);
877 HInstruction* vtc = stc;
878 if (needs_cleanup) {
Aart Bik14a68b42017-06-08 14:06:58 -0700879 DCHECK(IsPowerOfTwo(chunk));
880 HInstruction* diff = stc;
881 if (ptc != nullptr) {
882 diff = Insert(preheader, new (global_allocator_) HSub(induc_type, stc, ptc));
883 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800884 HInstruction* rem = Insert(
885 preheader, new (global_allocator_) HAnd(induc_type,
Aart Bik14a68b42017-06-08 14:06:58 -0700886 diff,
Aart Bikdbbac8f2017-09-01 13:06:08 -0700887 graph_->GetConstant(induc_type, chunk - 1)));
Aart Bikf8f5a162017-02-06 15:35:29 -0800888 vtc = Insert(preheader, new (global_allocator_) HSub(induc_type, stc, rem));
889 }
Aart Bikdbbac8f2017-09-01 13:06:08 -0700890 vector_index_ = graph_->GetConstant(induc_type, 0);
Aart Bikf8f5a162017-02-06 15:35:29 -0800891
892 // Generate runtime disambiguation test:
893 // vtc = a != b ? vtc : 0;
894 if (vector_runtime_test_a_ != nullptr) {
895 HInstruction* rt = Insert(
896 preheader,
897 new (global_allocator_) HNotEqual(vector_runtime_test_a_, vector_runtime_test_b_));
898 vtc = Insert(preheader,
Aart Bikdbbac8f2017-09-01 13:06:08 -0700899 new (global_allocator_)
900 HSelect(rt, vtc, graph_->GetConstant(induc_type, 0), kNoDexPc));
Aart Bikf8f5a162017-02-06 15:35:29 -0800901 needs_cleanup = true;
902 }
903
Aart Bik14a68b42017-06-08 14:06:58 -0700904 // Generate dynamic peeling loop for alignment, if needed:
905 // for ( ; i < ptc; i += 1)
906 // <loop-body>
907 if (ptc != nullptr) {
908 vector_mode_ = kSequential;
909 GenerateNewLoop(node,
910 block,
911 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
912 vector_index_,
913 ptc,
Aart Bikdbbac8f2017-09-01 13:06:08 -0700914 graph_->GetConstant(induc_type, 1),
Aart Bik521b50f2017-09-09 10:44:45 -0700915 kNoUnrollingFactor);
Aart Bik14a68b42017-06-08 14:06:58 -0700916 }
917
918 // Generate vector loop, possibly further unrolled:
919 // for ( ; i < vtc; i += chunk)
Aart Bikf8f5a162017-02-06 15:35:29 -0800920 // <vectorized-loop-body>
921 vector_mode_ = kVector;
922 GenerateNewLoop(node,
923 block,
Aart Bik14a68b42017-06-08 14:06:58 -0700924 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
925 vector_index_,
Aart Bikf8f5a162017-02-06 15:35:29 -0800926 vtc,
Aart Bikdbbac8f2017-09-01 13:06:08 -0700927 graph_->GetConstant(induc_type, vector_length_), // increment per unroll
Aart Bik14a68b42017-06-08 14:06:58 -0700928 unroll);
Aart Bikf8f5a162017-02-06 15:35:29 -0800929 HLoopInformation* vloop = vector_header_->GetLoopInformation();
930
931 // Generate cleanup loop, if needed:
932 // for ( ; i < stc; i += 1)
933 // <loop-body>
934 if (needs_cleanup) {
935 vector_mode_ = kSequential;
936 GenerateNewLoop(node,
937 block,
938 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
Aart Bik14a68b42017-06-08 14:06:58 -0700939 vector_index_,
Aart Bikf8f5a162017-02-06 15:35:29 -0800940 stc,
Aart Bikdbbac8f2017-09-01 13:06:08 -0700941 graph_->GetConstant(induc_type, 1),
Aart Bik521b50f2017-09-09 10:44:45 -0700942 kNoUnrollingFactor);
Aart Bikf8f5a162017-02-06 15:35:29 -0800943 }
944
Aart Bik0148de42017-09-05 09:25:01 -0700945 // Link reductions to their final uses.
946 for (auto i = reductions_->begin(); i != reductions_->end(); ++i) {
947 if (i->first->IsPhi()) {
Aart Bikdbbac8f2017-09-01 13:06:08 -0700948 HInstruction* phi = i->first;
949 HInstruction* repl = ReduceAndExtractIfNeeded(i->second);
950 // Deal with regular uses.
951 for (const HUseListNode<HInstruction*>& use : phi->GetUses()) {
952 induction_range_.Replace(use.GetUser(), phi, repl); // update induction use
953 }
954 phi->ReplaceWith(repl);
Aart Bik0148de42017-09-05 09:25:01 -0700955 }
956 }
957
Aart Bikf8f5a162017-02-06 15:35:29 -0800958 // Remove the original loop by disconnecting the body block
959 // and removing all instructions from the header.
960 block->DisconnectAndDelete();
961 while (!header->GetFirstInstruction()->IsGoto()) {
962 header->RemoveInstruction(header->GetFirstInstruction());
963 }
Aart Bikb29f6842017-07-28 15:58:41 -0700964
Aart Bik14a68b42017-06-08 14:06:58 -0700965 // Update loop hierarchy: the old header now resides in the same outer loop
966 // as the old preheader. Note that we don't bother putting sequential
967 // loops back in the hierarchy at this point.
Aart Bikf8f5a162017-02-06 15:35:29 -0800968 header->SetLoopInformation(preheader->GetLoopInformation()); // outward
969 node->loop_info = vloop;
970}
971
972void HLoopOptimization::GenerateNewLoop(LoopNode* node,
973 HBasicBlock* block,
974 HBasicBlock* new_preheader,
975 HInstruction* lo,
976 HInstruction* hi,
Aart Bik14a68b42017-06-08 14:06:58 -0700977 HInstruction* step,
978 uint32_t unroll) {
979 DCHECK(unroll == 1 || vector_mode_ == kVector);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100980 DataType::Type induc_type = lo->GetType();
Aart Bikf8f5a162017-02-06 15:35:29 -0800981 // Prepare new loop.
Aart Bikf8f5a162017-02-06 15:35:29 -0800982 vector_preheader_ = new_preheader,
983 vector_header_ = vector_preheader_->GetSingleSuccessor();
984 vector_body_ = vector_header_->GetSuccessors()[1];
Aart Bik14a68b42017-06-08 14:06:58 -0700985 HPhi* phi = new (global_allocator_) HPhi(global_allocator_,
986 kNoRegNumber,
987 0,
988 HPhi::ToPhiType(induc_type));
Aart Bikb07d1bc2017-04-05 10:03:15 -0700989 // Generate header and prepare body.
Aart Bikf8f5a162017-02-06 15:35:29 -0800990 // for (i = lo; i < hi; i += step)
991 // <loop-body>
Aart Bik14a68b42017-06-08 14:06:58 -0700992 HInstruction* cond = new (global_allocator_) HAboveOrEqual(phi, hi);
993 vector_header_->AddPhi(phi);
Aart Bikf8f5a162017-02-06 15:35:29 -0800994 vector_header_->AddInstruction(cond);
995 vector_header_->AddInstruction(new (global_allocator_) HIf(cond));
Aart Bik14a68b42017-06-08 14:06:58 -0700996 vector_index_ = phi;
Aart Bik0148de42017-09-05 09:25:01 -0700997 vector_permanent_map_->clear(); // preserved over unrolling
Aart Bik14a68b42017-06-08 14:06:58 -0700998 for (uint32_t u = 0; u < unroll; u++) {
Aart Bik14a68b42017-06-08 14:06:58 -0700999 // Generate instruction map.
Aart Bik0148de42017-09-05 09:25:01 -07001000 vector_map_->clear();
Aart Bik14a68b42017-06-08 14:06:58 -07001001 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
1002 bool vectorized_def = VectorizeDef(node, it.Current(), /*generate_code*/ true);
1003 DCHECK(vectorized_def);
1004 }
1005 // Generate body from the instruction map, but in original program order.
1006 HEnvironment* env = vector_header_->GetFirstInstruction()->GetEnvironment();
1007 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
1008 auto i = vector_map_->find(it.Current());
1009 if (i != vector_map_->end() && !i->second->IsInBlock()) {
1010 Insert(vector_body_, i->second);
1011 // Deal with instructions that need an environment, such as the scalar intrinsics.
1012 if (i->second->NeedsEnvironment()) {
1013 i->second->CopyEnvironmentFromWithLoopPhiAdjustment(env, vector_header_);
1014 }
1015 }
1016 }
Aart Bik0148de42017-09-05 09:25:01 -07001017 // Generate the induction.
Aart Bik14a68b42017-06-08 14:06:58 -07001018 vector_index_ = new (global_allocator_) HAdd(induc_type, vector_index_, step);
1019 Insert(vector_body_, vector_index_);
Aart Bikf8f5a162017-02-06 15:35:29 -08001020 }
Aart Bik0148de42017-09-05 09:25:01 -07001021 // Finalize phi inputs for the reductions (if any).
1022 for (auto i = reductions_->begin(); i != reductions_->end(); ++i) {
1023 if (!i->first->IsPhi()) {
1024 DCHECK(i->second->IsPhi());
1025 GenerateVecReductionPhiInputs(i->second->AsPhi(), i->first);
1026 }
1027 }
Aart Bikb29f6842017-07-28 15:58:41 -07001028 // Finalize phi inputs for the loop index.
Aart Bik14a68b42017-06-08 14:06:58 -07001029 phi->AddInput(lo);
1030 phi->AddInput(vector_index_);
1031 vector_index_ = phi;
Aart Bikf8f5a162017-02-06 15:35:29 -08001032}
1033
Aart Bikf8f5a162017-02-06 15:35:29 -08001034bool HLoopOptimization::VectorizeDef(LoopNode* node,
1035 HInstruction* instruction,
1036 bool generate_code) {
1037 // Accept a left-hand-side array base[index] for
1038 // (1) supported vector type,
1039 // (2) loop-invariant base,
1040 // (3) unit stride index,
1041 // (4) vectorizable right-hand-side value.
1042 uint64_t restrictions = kNone;
1043 if (instruction->IsArraySet()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001044 DataType::Type type = instruction->AsArraySet()->GetComponentType();
Aart Bikf8f5a162017-02-06 15:35:29 -08001045 HInstruction* base = instruction->InputAt(0);
1046 HInstruction* index = instruction->InputAt(1);
1047 HInstruction* value = instruction->InputAt(2);
1048 HInstruction* offset = nullptr;
1049 if (TrySetVectorType(type, &restrictions) &&
1050 node->loop_info->IsDefinedOutOfTheLoop(base) &&
Aart Bik37dc4df2017-06-28 14:08:00 -07001051 induction_range_.IsUnitStride(instruction, index, graph_, &offset) &&
Aart Bikf8f5a162017-02-06 15:35:29 -08001052 VectorizeUse(node, value, generate_code, type, restrictions)) {
1053 if (generate_code) {
1054 GenerateVecSub(index, offset);
Aart Bik14a68b42017-06-08 14:06:58 -07001055 GenerateVecMem(instruction, vector_map_->Get(index), vector_map_->Get(value), offset, type);
Aart Bikf8f5a162017-02-06 15:35:29 -08001056 } else {
1057 vector_refs_->insert(ArrayReference(base, offset, type, /*lhs*/ true));
1058 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08001059 return true;
1060 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001061 return false;
1062 }
Aart Bik0148de42017-09-05 09:25:01 -07001063 // Accept a left-hand-side reduction for
1064 // (1) supported vector type,
1065 // (2) vectorizable right-hand-side value.
1066 auto redit = reductions_->find(instruction);
1067 if (redit != reductions_->end()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001068 DataType::Type type = instruction->GetType();
Aart Bikdbbac8f2017-09-01 13:06:08 -07001069 // Recognize SAD idiom or direct reduction.
1070 if (VectorizeSADIdiom(node, instruction, generate_code, type, restrictions) ||
1071 (TrySetVectorType(type, &restrictions) &&
1072 VectorizeUse(node, instruction, generate_code, type, restrictions))) {
Aart Bik0148de42017-09-05 09:25:01 -07001073 if (generate_code) {
1074 HInstruction* new_red = vector_map_->Get(instruction);
1075 vector_permanent_map_->Put(new_red, vector_map_->Get(redit->second));
1076 vector_permanent_map_->Overwrite(redit->second, new_red);
1077 }
1078 return true;
1079 }
1080 return false;
1081 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001082 // Branch back okay.
1083 if (instruction->IsGoto()) {
1084 return true;
1085 }
1086 // Otherwise accept only expressions with no effects outside the immediate loop-body.
1087 // Note that actual uses are inspected during right-hand-side tree traversal.
1088 return !IsUsedOutsideLoop(node->loop_info, instruction) && !instruction->DoesAnyWrite();
1089}
1090
Aart Bik304c8a52017-05-23 11:01:13 -07001091// TODO: saturation arithmetic.
Aart Bikf8f5a162017-02-06 15:35:29 -08001092bool HLoopOptimization::VectorizeUse(LoopNode* node,
1093 HInstruction* instruction,
1094 bool generate_code,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001095 DataType::Type type,
Aart Bikf8f5a162017-02-06 15:35:29 -08001096 uint64_t restrictions) {
1097 // Accept anything for which code has already been generated.
1098 if (generate_code) {
1099 if (vector_map_->find(instruction) != vector_map_->end()) {
1100 return true;
1101 }
1102 }
1103 // Continue the right-hand-side tree traversal, passing in proper
1104 // types and vector restrictions along the way. During code generation,
1105 // all new nodes are drawn from the global allocator.
1106 if (node->loop_info->IsDefinedOutOfTheLoop(instruction)) {
1107 // Accept invariant use, using scalar expansion.
1108 if (generate_code) {
1109 GenerateVecInv(instruction, type);
1110 }
1111 return true;
1112 } else if (instruction->IsArrayGet()) {
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001113 // Deal with vector restrictions.
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001114 bool is_string_char_at = instruction->AsArrayGet()->IsStringCharAt();
1115 if (is_string_char_at && HasVectorRestrictions(restrictions, kNoStringCharAt)) {
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001116 return false;
1117 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001118 // Accept a right-hand-side array base[index] for
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001119 // (1) matching vector type (exact match or signed/unsigned integral type of the same size),
Aart Bikf8f5a162017-02-06 15:35:29 -08001120 // (2) loop-invariant base,
1121 // (3) unit stride index,
1122 // (4) vectorizable right-hand-side value.
1123 HInstruction* base = instruction->InputAt(0);
1124 HInstruction* index = instruction->InputAt(1);
1125 HInstruction* offset = nullptr;
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001126 if (DataType::ToSignedType(type) == DataType::ToSignedType(instruction->GetType()) &&
Aart Bikf8f5a162017-02-06 15:35:29 -08001127 node->loop_info->IsDefinedOutOfTheLoop(base) &&
Aart Bik37dc4df2017-06-28 14:08:00 -07001128 induction_range_.IsUnitStride(instruction, index, graph_, &offset)) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001129 if (generate_code) {
1130 GenerateVecSub(index, offset);
Aart Bik14a68b42017-06-08 14:06:58 -07001131 GenerateVecMem(instruction, vector_map_->Get(index), nullptr, offset, type);
Aart Bikf8f5a162017-02-06 15:35:29 -08001132 } else {
1133 vector_refs_->insert(ArrayReference(base, offset, type, /*lhs*/ false));
1134 }
1135 return true;
1136 }
Aart Bik0148de42017-09-05 09:25:01 -07001137 } else if (instruction->IsPhi()) {
1138 // Accept particular phi operations.
1139 if (reductions_->find(instruction) != reductions_->end()) {
1140 // Deal with vector restrictions.
1141 if (HasVectorRestrictions(restrictions, kNoReduction)) {
1142 return false;
1143 }
1144 // Accept a reduction.
1145 if (generate_code) {
1146 GenerateVecReductionPhi(instruction->AsPhi());
1147 }
1148 return true;
1149 }
1150 // TODO: accept right-hand-side induction?
1151 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001152 } else if (instruction->IsTypeConversion()) {
1153 // Accept particular type conversions.
1154 HTypeConversion* conversion = instruction->AsTypeConversion();
1155 HInstruction* opa = conversion->InputAt(0);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001156 DataType::Type from = conversion->GetInputType();
1157 DataType::Type to = conversion->GetResultType();
1158 if (DataType::IsIntegralType(from) && DataType::IsIntegralType(to)) {
1159 size_t size_vec = DataType::Size(type);
1160 size_t size_from = DataType::Size(from);
1161 size_t size_to = DataType::Size(to);
Aart Bikdf011c32017-09-28 12:53:04 -07001162 DataType::Type ctype = size_from == size_vec ? from : type;
Aart Bikdbbac8f2017-09-01 13:06:08 -07001163 // Accept an integral conversion
1164 // (1a) narrowing into vector type, "wider" operations cannot bring in higher order bits, or
1165 // (1b) widening from at least vector type, and
1166 // (2) vectorizable operand.
1167 if ((size_to < size_from &&
1168 size_to == size_vec &&
1169 VectorizeUse(node, opa, generate_code, type, restrictions | kNoHiBits)) ||
1170 (size_to >= size_from &&
1171 size_from >= size_vec &&
Aart Bikdf011c32017-09-28 12:53:04 -07001172 VectorizeUse(node, opa, generate_code, ctype, restrictions))) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001173 if (generate_code) {
1174 if (vector_mode_ == kVector) {
1175 vector_map_->Put(instruction, vector_map_->Get(opa)); // operand pass-through
1176 } else {
1177 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1178 }
1179 }
1180 return true;
1181 }
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001182 } else if (to == DataType::Type::kFloat32 && from == DataType::Type::kInt32) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001183 DCHECK_EQ(to, type);
1184 // Accept int to float conversion for
1185 // (1) supported int,
1186 // (2) vectorizable operand.
1187 if (TrySetVectorType(from, &restrictions) &&
1188 VectorizeUse(node, opa, generate_code, from, restrictions)) {
1189 if (generate_code) {
1190 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1191 }
1192 return true;
1193 }
1194 }
1195 return false;
1196 } else if (instruction->IsNeg() || instruction->IsNot() || instruction->IsBooleanNot()) {
1197 // Accept unary operator for vectorizable operand.
1198 HInstruction* opa = instruction->InputAt(0);
1199 if (VectorizeUse(node, opa, generate_code, type, restrictions)) {
1200 if (generate_code) {
1201 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1202 }
1203 return true;
1204 }
1205 } else if (instruction->IsAdd() || instruction->IsSub() ||
1206 instruction->IsMul() || instruction->IsDiv() ||
1207 instruction->IsAnd() || instruction->IsOr() || instruction->IsXor()) {
1208 // Deal with vector restrictions.
1209 if ((instruction->IsMul() && HasVectorRestrictions(restrictions, kNoMul)) ||
1210 (instruction->IsDiv() && HasVectorRestrictions(restrictions, kNoDiv))) {
1211 return false;
1212 }
1213 // Accept binary operator for vectorizable operands.
1214 HInstruction* opa = instruction->InputAt(0);
1215 HInstruction* opb = instruction->InputAt(1);
1216 if (VectorizeUse(node, opa, generate_code, type, restrictions) &&
1217 VectorizeUse(node, opb, generate_code, type, restrictions)) {
1218 if (generate_code) {
1219 GenerateVecOp(instruction, vector_map_->Get(opa), vector_map_->Get(opb), type);
1220 }
1221 return true;
1222 }
1223 } else if (instruction->IsShl() || instruction->IsShr() || instruction->IsUShr()) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001224 // Recognize halving add idiom.
Aart Bikf3e61ee2017-04-12 17:09:20 -07001225 if (VectorizeHalvingAddIdiom(node, instruction, generate_code, type, restrictions)) {
1226 return true;
1227 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001228 // Deal with vector restrictions.
Aart Bik304c8a52017-05-23 11:01:13 -07001229 HInstruction* opa = instruction->InputAt(0);
1230 HInstruction* opb = instruction->InputAt(1);
1231 HInstruction* r = opa;
1232 bool is_unsigned = false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001233 if ((HasVectorRestrictions(restrictions, kNoShift)) ||
1234 (instruction->IsShr() && HasVectorRestrictions(restrictions, kNoShr))) {
1235 return false; // unsupported instruction
Aart Bik304c8a52017-05-23 11:01:13 -07001236 } else if (HasVectorRestrictions(restrictions, kNoHiBits)) {
1237 // Shifts right need extra care to account for higher order bits.
1238 // TODO: less likely shr/unsigned and ushr/signed can by flipping signess.
1239 if (instruction->IsShr() &&
1240 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || is_unsigned)) {
1241 return false; // reject, unless all operands are sign-extension narrower
1242 } else if (instruction->IsUShr() &&
1243 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || !is_unsigned)) {
1244 return false; // reject, unless all operands are zero-extension narrower
1245 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001246 }
1247 // Accept shift operator for vectorizable/invariant operands.
1248 // TODO: accept symbolic, albeit loop invariant shift factors.
Aart Bik304c8a52017-05-23 11:01:13 -07001249 DCHECK(r != nullptr);
1250 if (generate_code && vector_mode_ != kVector) { // de-idiom
1251 r = opa;
1252 }
Aart Bik50e20d52017-05-05 14:07:29 -07001253 int64_t distance = 0;
Aart Bik304c8a52017-05-23 11:01:13 -07001254 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
Aart Bik50e20d52017-05-05 14:07:29 -07001255 IsInt64AndGet(opb, /*out*/ &distance)) {
Aart Bik65ffd8e2017-05-01 16:50:45 -07001256 // Restrict shift distance to packed data type width.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001257 int64_t max_distance = DataType::Size(type) * 8;
Aart Bik65ffd8e2017-05-01 16:50:45 -07001258 if (0 <= distance && distance < max_distance) {
1259 if (generate_code) {
Aart Bik304c8a52017-05-23 11:01:13 -07001260 GenerateVecOp(instruction, vector_map_->Get(r), opb, type);
Aart Bik65ffd8e2017-05-01 16:50:45 -07001261 }
1262 return true;
Aart Bikf8f5a162017-02-06 15:35:29 -08001263 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001264 }
1265 } else if (instruction->IsInvokeStaticOrDirect()) {
Aart Bik6daebeb2017-04-03 14:35:41 -07001266 // Accept particular intrinsics.
1267 HInvokeStaticOrDirect* invoke = instruction->AsInvokeStaticOrDirect();
1268 switch (invoke->GetIntrinsic()) {
1269 case Intrinsics::kMathAbsInt:
1270 case Intrinsics::kMathAbsLong:
1271 case Intrinsics::kMathAbsFloat:
1272 case Intrinsics::kMathAbsDouble: {
1273 // Deal with vector restrictions.
Aart Bik304c8a52017-05-23 11:01:13 -07001274 HInstruction* opa = instruction->InputAt(0);
1275 HInstruction* r = opa;
1276 bool is_unsigned = false;
1277 if (HasVectorRestrictions(restrictions, kNoAbs)) {
Aart Bik6daebeb2017-04-03 14:35:41 -07001278 return false;
Aart Bik304c8a52017-05-23 11:01:13 -07001279 } else if (HasVectorRestrictions(restrictions, kNoHiBits) &&
1280 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || is_unsigned)) {
1281 return false; // reject, unless operand is sign-extension narrower
Aart Bik6daebeb2017-04-03 14:35:41 -07001282 }
1283 // Accept ABS(x) for vectorizable operand.
Aart Bik304c8a52017-05-23 11:01:13 -07001284 DCHECK(r != nullptr);
1285 if (generate_code && vector_mode_ != kVector) { // de-idiom
1286 r = opa;
1287 }
1288 if (VectorizeUse(node, r, generate_code, type, restrictions)) {
Aart Bik6daebeb2017-04-03 14:35:41 -07001289 if (generate_code) {
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001290 NormalizePackedType(&type, &is_unsigned);
Aart Bik304c8a52017-05-23 11:01:13 -07001291 GenerateVecOp(instruction, vector_map_->Get(r), nullptr, type);
Aart Bik6daebeb2017-04-03 14:35:41 -07001292 }
1293 return true;
1294 }
1295 return false;
1296 }
Aart Bikc8e93c72017-05-10 10:49:22 -07001297 case Intrinsics::kMathMinIntInt:
1298 case Intrinsics::kMathMinLongLong:
1299 case Intrinsics::kMathMinFloatFloat:
1300 case Intrinsics::kMathMinDoubleDouble:
1301 case Intrinsics::kMathMaxIntInt:
1302 case Intrinsics::kMathMaxLongLong:
1303 case Intrinsics::kMathMaxFloatFloat:
1304 case Intrinsics::kMathMaxDoubleDouble: {
1305 // Deal with vector restrictions.
Nicolas Geoffray92316902017-05-23 08:06:07 +00001306 HInstruction* opa = instruction->InputAt(0);
1307 HInstruction* opb = instruction->InputAt(1);
Aart Bik304c8a52017-05-23 11:01:13 -07001308 HInstruction* r = opa;
1309 HInstruction* s = opb;
1310 bool is_unsigned = false;
1311 if (HasVectorRestrictions(restrictions, kNoMinMax)) {
1312 return false;
1313 } else if (HasVectorRestrictions(restrictions, kNoHiBits) &&
1314 !IsNarrowerOperands(opa, opb, type, &r, &s, &is_unsigned)) {
1315 return false; // reject, unless all operands are same-extension narrower
1316 }
1317 // Accept MIN/MAX(x, y) for vectorizable operands.
Aart Bikdbbac8f2017-09-01 13:06:08 -07001318 DCHECK(r != nullptr);
1319 DCHECK(s != nullptr);
Aart Bik304c8a52017-05-23 11:01:13 -07001320 if (generate_code && vector_mode_ != kVector) { // de-idiom
1321 r = opa;
1322 s = opb;
1323 }
1324 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
1325 VectorizeUse(node, s, generate_code, type, restrictions)) {
Aart Bikc8e93c72017-05-10 10:49:22 -07001326 if (generate_code) {
Aart Bik304c8a52017-05-23 11:01:13 -07001327 GenerateVecOp(
1328 instruction, vector_map_->Get(r), vector_map_->Get(s), type, is_unsigned);
Aart Bikc8e93c72017-05-10 10:49:22 -07001329 }
1330 return true;
1331 }
1332 return false;
1333 }
Aart Bik6daebeb2017-04-03 14:35:41 -07001334 default:
1335 return false;
1336 } // switch
Aart Bik281c6812016-08-26 11:31:48 -07001337 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08001338 return false;
Aart Bik281c6812016-08-26 11:31:48 -07001339}
1340
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001341bool HLoopOptimization::TrySetVectorType(DataType::Type type, uint64_t* restrictions) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001342 const InstructionSetFeatures* features = compiler_driver_->GetInstructionSetFeatures();
1343 switch (compiler_driver_->GetInstructionSet()) {
1344 case kArm:
1345 case kThumb2:
Artem Serov8f7c4102017-06-21 11:21:37 +01001346 // Allow vectorization for all ARM devices, because Android assumes that
Aart Bikb29f6842017-07-28 15:58:41 -07001347 // ARM 32-bit always supports advanced SIMD (64-bit SIMD).
Artem Serov8f7c4102017-06-21 11:21:37 +01001348 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001349 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001350 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001351 case DataType::Type::kInt8:
Aart Bik0148de42017-09-05 09:25:01 -07001352 *restrictions |= kNoDiv | kNoReduction;
Artem Serov8f7c4102017-06-21 11:21:37 +01001353 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001354 case DataType::Type::kUint16:
1355 case DataType::Type::kInt16:
Aart Bik0148de42017-09-05 09:25:01 -07001356 *restrictions |= kNoDiv | kNoStringCharAt | kNoReduction;
Artem Serov8f7c4102017-06-21 11:21:37 +01001357 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001358 case DataType::Type::kInt32:
Aart Bik0148de42017-09-05 09:25:01 -07001359 *restrictions |= kNoDiv | kNoReduction;
Artem Serov8f7c4102017-06-21 11:21:37 +01001360 return TrySetVectorLength(2);
1361 default:
1362 break;
1363 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001364 return false;
1365 case kArm64:
1366 // Allow vectorization for all ARM devices, because Android assumes that
Aart Bikb29f6842017-07-28 15:58:41 -07001367 // ARMv8 AArch64 always supports advanced SIMD (128-bit SIMD).
Aart Bikf8f5a162017-02-06 15:35:29 -08001368 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001369 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001370 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001371 case DataType::Type::kInt8:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001372 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +01001373 return TrySetVectorLength(16);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001374 case DataType::Type::kUint16:
1375 case DataType::Type::kInt16:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001376 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +01001377 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001378 case DataType::Type::kInt32:
Aart Bikf8f5a162017-02-06 15:35:29 -08001379 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +01001380 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001381 case DataType::Type::kInt64:
Aart Bikc8e93c72017-05-10 10:49:22 -07001382 *restrictions |= kNoDiv | kNoMul | kNoMinMax;
Aart Bikf8f5a162017-02-06 15:35:29 -08001383 return TrySetVectorLength(2);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001384 case DataType::Type::kFloat32:
Aart Bik0148de42017-09-05 09:25:01 -07001385 *restrictions |= kNoReduction;
Artem Serovd4bccf12017-04-03 18:47:32 +01001386 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001387 case DataType::Type::kFloat64:
Aart Bik0148de42017-09-05 09:25:01 -07001388 *restrictions |= kNoReduction;
Aart Bikf8f5a162017-02-06 15:35:29 -08001389 return TrySetVectorLength(2);
1390 default:
1391 return false;
1392 }
1393 case kX86:
1394 case kX86_64:
Aart Bikb29f6842017-07-28 15:58:41 -07001395 // Allow vectorization for SSE4.1-enabled X86 devices only (128-bit SIMD).
Aart Bikf8f5a162017-02-06 15:35:29 -08001396 if (features->AsX86InstructionSetFeatures()->HasSSE4_1()) {
1397 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001398 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001399 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001400 case DataType::Type::kInt8:
Aart Bik0148de42017-09-05 09:25:01 -07001401 *restrictions |=
Aart Bikdbbac8f2017-09-01 13:06:08 -07001402 kNoMul | kNoDiv | kNoShift | kNoAbs | kNoSignedHAdd | kNoUnroundedHAdd | kNoSAD;
Aart Bikf8f5a162017-02-06 15:35:29 -08001403 return TrySetVectorLength(16);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001404 case DataType::Type::kUint16:
1405 case DataType::Type::kInt16:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001406 *restrictions |= kNoDiv | kNoAbs | kNoSignedHAdd | kNoUnroundedHAdd | kNoSAD;
Aart Bikf8f5a162017-02-06 15:35:29 -08001407 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001408 case DataType::Type::kInt32:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001409 *restrictions |= kNoDiv | kNoSAD;
Aart Bikf8f5a162017-02-06 15:35:29 -08001410 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001411 case DataType::Type::kInt64:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001412 *restrictions |= kNoMul | kNoDiv | kNoShr | kNoAbs | kNoMinMax | kNoSAD;
Aart Bikf8f5a162017-02-06 15:35:29 -08001413 return TrySetVectorLength(2);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001414 case DataType::Type::kFloat32:
Aart Bik0148de42017-09-05 09:25:01 -07001415 *restrictions |= kNoMinMax | kNoReduction; // minmax: -0.0 vs +0.0
Aart Bikf8f5a162017-02-06 15:35:29 -08001416 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001417 case DataType::Type::kFloat64:
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(2);
1420 default:
1421 break;
1422 } // switch type
1423 }
1424 return false;
1425 case kMips:
Lena Djokic51765b02017-06-22 13:49:59 +02001426 if (features->AsMipsInstructionSetFeatures()->HasMsa()) {
1427 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001428 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001429 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001430 case DataType::Type::kInt8:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001431 *restrictions |= kNoDiv | kNoReduction | kNoSAD;
Lena Djokic51765b02017-06-22 13:49:59 +02001432 return TrySetVectorLength(16);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001433 case DataType::Type::kUint16:
1434 case DataType::Type::kInt16:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001435 *restrictions |= kNoDiv | kNoStringCharAt | kNoReduction | kNoSAD;
Lena Djokic51765b02017-06-22 13:49:59 +02001436 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001437 case DataType::Type::kInt32:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001438 *restrictions |= kNoDiv | kNoReduction | kNoSAD;
Lena Djokic51765b02017-06-22 13:49:59 +02001439 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001440 case DataType::Type::kInt64:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001441 *restrictions |= kNoDiv | kNoReduction | kNoSAD;
Lena Djokic51765b02017-06-22 13:49:59 +02001442 return TrySetVectorLength(2);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001443 case DataType::Type::kFloat32:
Aart Bik0148de42017-09-05 09:25:01 -07001444 *restrictions |= kNoMinMax | kNoReduction; // min/max(x, NaN)
Lena Djokic51765b02017-06-22 13:49:59 +02001445 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001446 case DataType::Type::kFloat64:
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(2);
1449 default:
1450 break;
1451 } // switch type
1452 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001453 return false;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001454 case kMips64:
1455 if (features->AsMips64InstructionSetFeatures()->HasMsa()) {
1456 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001457 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001458 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001459 case DataType::Type::kInt8:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001460 *restrictions |= kNoDiv | kNoReduction | kNoSAD;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001461 return TrySetVectorLength(16);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001462 case DataType::Type::kUint16:
1463 case DataType::Type::kInt16:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001464 *restrictions |= kNoDiv | kNoStringCharAt | kNoReduction | kNoSAD;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001465 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001466 case DataType::Type::kInt32:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001467 *restrictions |= kNoDiv | kNoReduction | kNoSAD;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001468 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001469 case DataType::Type::kInt64:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001470 *restrictions |= kNoDiv | kNoReduction | kNoSAD;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001471 return TrySetVectorLength(2);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001472 case DataType::Type::kFloat32:
Aart Bik0148de42017-09-05 09:25:01 -07001473 *restrictions |= kNoMinMax | kNoReduction; // min/max(x, NaN)
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001474 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001475 case DataType::Type::kFloat64:
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(2);
1478 default:
1479 break;
1480 } // switch type
1481 }
1482 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001483 default:
1484 return false;
1485 } // switch instruction set
1486}
1487
1488bool HLoopOptimization::TrySetVectorLength(uint32_t length) {
1489 DCHECK(IsPowerOfTwo(length) && length >= 2u);
1490 // First time set?
1491 if (vector_length_ == 0) {
1492 vector_length_ = length;
1493 }
1494 // Different types are acceptable within a loop-body, as long as all the corresponding vector
1495 // lengths match exactly to obtain a uniform traversal through the vector iteration space
1496 // (idiomatic exceptions to this rule can be handled by further unrolling sub-expressions).
1497 return vector_length_ == length;
1498}
1499
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001500void HLoopOptimization::GenerateVecInv(HInstruction* org, DataType::Type type) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001501 if (vector_map_->find(org) == vector_map_->end()) {
1502 // In scalar code, just use a self pass-through for scalar invariants
1503 // (viz. expression remains itself).
1504 if (vector_mode_ == kSequential) {
1505 vector_map_->Put(org, org);
1506 return;
1507 }
1508 // In vector code, explicit scalar expansion is needed.
Aart Bik0148de42017-09-05 09:25:01 -07001509 HInstruction* vector = nullptr;
1510 auto it = vector_permanent_map_->find(org);
1511 if (it != vector_permanent_map_->end()) {
1512 vector = it->second; // reuse during unrolling
1513 } else {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001514 // Generates ReplicateScalar( (optional_type_conv) org ).
1515 HInstruction* input = org;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001516 DataType::Type input_type = input->GetType();
1517 if (type != input_type && (type == DataType::Type::kInt64 ||
1518 input_type == DataType::Type::kInt64)) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001519 input = Insert(vector_preheader_,
1520 new (global_allocator_) HTypeConversion(type, input, kNoDexPc));
1521 }
1522 vector = new (global_allocator_)
1523 HVecReplicateScalar(global_allocator_, input, type, vector_length_);
Aart Bik0148de42017-09-05 09:25:01 -07001524 vector_permanent_map_->Put(org, Insert(vector_preheader_, vector));
1525 }
1526 vector_map_->Put(org, vector);
Aart Bikf8f5a162017-02-06 15:35:29 -08001527 }
1528}
1529
1530void HLoopOptimization::GenerateVecSub(HInstruction* org, HInstruction* offset) {
1531 if (vector_map_->find(org) == vector_map_->end()) {
Aart Bik14a68b42017-06-08 14:06:58 -07001532 HInstruction* subscript = vector_index_;
Aart Bik37dc4df2017-06-28 14:08:00 -07001533 int64_t value = 0;
1534 if (!IsInt64AndGet(offset, &value) || value != 0) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001535 subscript = new (global_allocator_) HAdd(DataType::Type::kInt32, subscript, offset);
Aart Bikf8f5a162017-02-06 15:35:29 -08001536 if (org->IsPhi()) {
1537 Insert(vector_body_, subscript); // lacks layout placeholder
1538 }
1539 }
1540 vector_map_->Put(org, subscript);
1541 }
1542}
1543
1544void HLoopOptimization::GenerateVecMem(HInstruction* org,
1545 HInstruction* opa,
1546 HInstruction* opb,
Aart Bik14a68b42017-06-08 14:06:58 -07001547 HInstruction* offset,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001548 DataType::Type type) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001549 HInstruction* vector = nullptr;
1550 if (vector_mode_ == kVector) {
1551 // Vector store or load.
Aart Bik14a68b42017-06-08 14:06:58 -07001552 HInstruction* base = org->InputAt(0);
Aart Bikf8f5a162017-02-06 15:35:29 -08001553 if (opb != nullptr) {
1554 vector = new (global_allocator_) HVecStore(
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001555 global_allocator_, base, opa, opb, type, org->GetSideEffects(), vector_length_);
Aart Bikf8f5a162017-02-06 15:35:29 -08001556 } else {
Aart Bikdb14fcf2017-04-25 15:53:58 -07001557 bool is_string_char_at = org->AsArrayGet()->IsStringCharAt();
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001558 vector = new (global_allocator_) HVecLoad(global_allocator_,
1559 base,
1560 opa,
1561 type,
1562 org->GetSideEffects(),
1563 vector_length_,
1564 is_string_char_at);
Aart Bik14a68b42017-06-08 14:06:58 -07001565 }
1566 // Known dynamically enforced alignment?
Aart Bik14a68b42017-06-08 14:06:58 -07001567 if (vector_peeling_candidate_ != nullptr &&
1568 vector_peeling_candidate_->base == base &&
1569 vector_peeling_candidate_->offset == offset) {
1570 vector->AsVecMemoryOperation()->SetAlignment(Alignment(kAlignedBase, 0));
Aart Bikf8f5a162017-02-06 15:35:29 -08001571 }
1572 } else {
1573 // Scalar store or load.
1574 DCHECK(vector_mode_ == kSequential);
1575 if (opb != nullptr) {
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001576 vector = new (global_allocator_) HArraySet(
1577 org->InputAt(0), opa, opb, type, org->GetSideEffects(), kNoDexPc);
Aart Bikf8f5a162017-02-06 15:35:29 -08001578 } else {
Aart Bikdb14fcf2017-04-25 15:53:58 -07001579 bool is_string_char_at = org->AsArrayGet()->IsStringCharAt();
1580 vector = new (global_allocator_) HArrayGet(
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001581 org->InputAt(0), opa, type, org->GetSideEffects(), kNoDexPc, is_string_char_at);
Aart Bikf8f5a162017-02-06 15:35:29 -08001582 }
1583 }
1584 vector_map_->Put(org, vector);
1585}
1586
Aart Bik0148de42017-09-05 09:25:01 -07001587void HLoopOptimization::GenerateVecReductionPhi(HPhi* phi) {
1588 DCHECK(reductions_->find(phi) != reductions_->end());
1589 DCHECK(reductions_->Get(phi->InputAt(1)) == phi);
1590 HInstruction* vector = nullptr;
1591 if (vector_mode_ == kSequential) {
1592 HPhi* new_phi = new (global_allocator_) HPhi(
1593 global_allocator_, kNoRegNumber, 0, phi->GetType());
1594 vector_header_->AddPhi(new_phi);
1595 vector = new_phi;
1596 } else {
1597 // Link vector reduction back to prior unrolled update, or a first phi.
1598 auto it = vector_permanent_map_->find(phi);
1599 if (it != vector_permanent_map_->end()) {
1600 vector = it->second;
1601 } else {
1602 HPhi* new_phi = new (global_allocator_) HPhi(
1603 global_allocator_, kNoRegNumber, 0, HVecOperation::kSIMDType);
1604 vector_header_->AddPhi(new_phi);
1605 vector = new_phi;
1606 }
1607 }
1608 vector_map_->Put(phi, vector);
1609}
1610
1611void HLoopOptimization::GenerateVecReductionPhiInputs(HPhi* phi, HInstruction* reduction) {
1612 HInstruction* new_phi = vector_map_->Get(phi);
1613 HInstruction* new_init = reductions_->Get(phi);
1614 HInstruction* new_red = vector_map_->Get(reduction);
1615 // Link unrolled vector loop back to new phi.
1616 for (; !new_phi->IsPhi(); new_phi = vector_permanent_map_->Get(new_phi)) {
1617 DCHECK(new_phi->IsVecOperation());
1618 }
1619 // Prepare the new initialization.
1620 if (vector_mode_ == kVector) {
1621 // Generate a [initial, 0, .., 0] vector.
Aart Bikdbbac8f2017-09-01 13:06:08 -07001622 HVecOperation* red_vector = new_red->AsVecOperation();
1623 size_t vector_length = red_vector->GetVectorLength();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001624 DataType::Type type = red_vector->GetPackedType();
Aart Bikdbbac8f2017-09-01 13:06:08 -07001625 new_init = Insert(vector_preheader_,
1626 new (global_allocator_) HVecSetScalars(global_allocator_,
1627 &new_init,
1628 type,
1629 vector_length,
1630 1));
Aart Bik0148de42017-09-05 09:25:01 -07001631 } else {
1632 new_init = ReduceAndExtractIfNeeded(new_init);
1633 }
1634 // Set the phi inputs.
1635 DCHECK(new_phi->IsPhi());
1636 new_phi->AsPhi()->AddInput(new_init);
1637 new_phi->AsPhi()->AddInput(new_red);
1638 // New feed value for next phi (safe mutation in iteration).
1639 reductions_->find(phi)->second = new_phi;
1640}
1641
1642HInstruction* HLoopOptimization::ReduceAndExtractIfNeeded(HInstruction* instruction) {
1643 if (instruction->IsPhi()) {
1644 HInstruction* input = instruction->InputAt(1);
1645 if (input->IsVecOperation()) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001646 HVecOperation* input_vector = input->AsVecOperation();
1647 size_t vector_length = input_vector->GetVectorLength();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001648 DataType::Type type = input_vector->GetPackedType();
Aart Bikdbbac8f2017-09-01 13:06:08 -07001649 HVecReduce::ReductionKind kind = GetReductionKind(input_vector);
Aart Bik0148de42017-09-05 09:25:01 -07001650 HBasicBlock* exit = instruction->GetBlock()->GetSuccessors()[0];
1651 // Generate a vector reduction and scalar extract
1652 // x = REDUCE( [x_1, .., x_n] )
1653 // y = x_1
1654 // along the exit of the defining loop.
Aart Bik0148de42017-09-05 09:25:01 -07001655 HInstruction* reduce = new (global_allocator_) HVecReduce(
Aart Bikdbbac8f2017-09-01 13:06:08 -07001656 global_allocator_, instruction, type, vector_length, kind);
Aart Bik0148de42017-09-05 09:25:01 -07001657 exit->InsertInstructionBefore(reduce, exit->GetFirstInstruction());
1658 instruction = new (global_allocator_) HVecExtractScalar(
Aart Bikdbbac8f2017-09-01 13:06:08 -07001659 global_allocator_, reduce, type, vector_length, 0);
Aart Bik0148de42017-09-05 09:25:01 -07001660 exit->InsertInstructionAfter(instruction, reduce);
1661 }
1662 }
1663 return instruction;
1664}
1665
Aart Bikf8f5a162017-02-06 15:35:29 -08001666#define GENERATE_VEC(x, y) \
1667 if (vector_mode_ == kVector) { \
1668 vector = (x); \
1669 } else { \
1670 DCHECK(vector_mode_ == kSequential); \
1671 vector = (y); \
1672 } \
1673 break;
1674
1675void HLoopOptimization::GenerateVecOp(HInstruction* org,
1676 HInstruction* opa,
1677 HInstruction* opb,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001678 DataType::Type type,
Aart Bik304c8a52017-05-23 11:01:13 -07001679 bool is_unsigned) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001680 HInstruction* vector = nullptr;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001681 DataType::Type org_type = org->GetType();
Aart Bikf8f5a162017-02-06 15:35:29 -08001682 switch (org->GetKind()) {
1683 case HInstruction::kNeg:
1684 DCHECK(opb == nullptr);
1685 GENERATE_VEC(
1686 new (global_allocator_) HVecNeg(global_allocator_, opa, type, vector_length_),
Aart Bikdbbac8f2017-09-01 13:06:08 -07001687 new (global_allocator_) HNeg(org_type, opa));
Aart Bikf8f5a162017-02-06 15:35:29 -08001688 case HInstruction::kNot:
1689 DCHECK(opb == nullptr);
1690 GENERATE_VEC(
1691 new (global_allocator_) HVecNot(global_allocator_, opa, type, vector_length_),
Aart Bikdbbac8f2017-09-01 13:06:08 -07001692 new (global_allocator_) HNot(org_type, opa));
Aart Bikf8f5a162017-02-06 15:35:29 -08001693 case HInstruction::kBooleanNot:
1694 DCHECK(opb == nullptr);
1695 GENERATE_VEC(
1696 new (global_allocator_) HVecNot(global_allocator_, opa, type, vector_length_),
1697 new (global_allocator_) HBooleanNot(opa));
1698 case HInstruction::kTypeConversion:
1699 DCHECK(opb == nullptr);
1700 GENERATE_VEC(
1701 new (global_allocator_) HVecCnv(global_allocator_, opa, type, vector_length_),
Aart Bikdbbac8f2017-09-01 13:06:08 -07001702 new (global_allocator_) HTypeConversion(org_type, opa, kNoDexPc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001703 case HInstruction::kAdd:
1704 GENERATE_VEC(
1705 new (global_allocator_) HVecAdd(global_allocator_, opa, opb, type, vector_length_),
Aart Bikdbbac8f2017-09-01 13:06:08 -07001706 new (global_allocator_) HAdd(org_type, opa, opb));
Aart Bikf8f5a162017-02-06 15:35:29 -08001707 case HInstruction::kSub:
1708 GENERATE_VEC(
1709 new (global_allocator_) HVecSub(global_allocator_, opa, opb, type, vector_length_),
Aart Bikdbbac8f2017-09-01 13:06:08 -07001710 new (global_allocator_) HSub(org_type, opa, opb));
Aart Bikf8f5a162017-02-06 15:35:29 -08001711 case HInstruction::kMul:
1712 GENERATE_VEC(
1713 new (global_allocator_) HVecMul(global_allocator_, opa, opb, type, vector_length_),
Aart Bikdbbac8f2017-09-01 13:06:08 -07001714 new (global_allocator_) HMul(org_type, opa, opb));
Aart Bikf8f5a162017-02-06 15:35:29 -08001715 case HInstruction::kDiv:
1716 GENERATE_VEC(
1717 new (global_allocator_) HVecDiv(global_allocator_, opa, opb, type, vector_length_),
Aart Bikdbbac8f2017-09-01 13:06:08 -07001718 new (global_allocator_) HDiv(org_type, opa, opb, kNoDexPc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001719 case HInstruction::kAnd:
1720 GENERATE_VEC(
1721 new (global_allocator_) HVecAnd(global_allocator_, opa, opb, type, vector_length_),
Aart Bikdbbac8f2017-09-01 13:06:08 -07001722 new (global_allocator_) HAnd(org_type, opa, opb));
Aart Bikf8f5a162017-02-06 15:35:29 -08001723 case HInstruction::kOr:
1724 GENERATE_VEC(
1725 new (global_allocator_) HVecOr(global_allocator_, opa, opb, type, vector_length_),
Aart Bikdbbac8f2017-09-01 13:06:08 -07001726 new (global_allocator_) HOr(org_type, opa, opb));
Aart Bikf8f5a162017-02-06 15:35:29 -08001727 case HInstruction::kXor:
1728 GENERATE_VEC(
1729 new (global_allocator_) HVecXor(global_allocator_, opa, opb, type, vector_length_),
Aart Bikdbbac8f2017-09-01 13:06:08 -07001730 new (global_allocator_) HXor(org_type, opa, opb));
Aart Bikf8f5a162017-02-06 15:35:29 -08001731 case HInstruction::kShl:
1732 GENERATE_VEC(
1733 new (global_allocator_) HVecShl(global_allocator_, opa, opb, type, vector_length_),
Aart Bikdbbac8f2017-09-01 13:06:08 -07001734 new (global_allocator_) HShl(org_type, opa, opb));
Aart Bikf8f5a162017-02-06 15:35:29 -08001735 case HInstruction::kShr:
1736 GENERATE_VEC(
1737 new (global_allocator_) HVecShr(global_allocator_, opa, opb, type, vector_length_),
Aart Bikdbbac8f2017-09-01 13:06:08 -07001738 new (global_allocator_) HShr(org_type, opa, opb));
Aart Bikf8f5a162017-02-06 15:35:29 -08001739 case HInstruction::kUShr:
1740 GENERATE_VEC(
1741 new (global_allocator_) HVecUShr(global_allocator_, opa, opb, type, vector_length_),
Aart Bikdbbac8f2017-09-01 13:06:08 -07001742 new (global_allocator_) HUShr(org_type, opa, opb));
Aart Bikf8f5a162017-02-06 15:35:29 -08001743 case HInstruction::kInvokeStaticOrDirect: {
Aart Bik6daebeb2017-04-03 14:35:41 -07001744 HInvokeStaticOrDirect* invoke = org->AsInvokeStaticOrDirect();
1745 if (vector_mode_ == kVector) {
1746 switch (invoke->GetIntrinsic()) {
1747 case Intrinsics::kMathAbsInt:
1748 case Intrinsics::kMathAbsLong:
1749 case Intrinsics::kMathAbsFloat:
1750 case Intrinsics::kMathAbsDouble:
1751 DCHECK(opb == nullptr);
1752 vector = new (global_allocator_) HVecAbs(global_allocator_, opa, type, vector_length_);
1753 break;
Aart Bikc8e93c72017-05-10 10:49:22 -07001754 case Intrinsics::kMathMinIntInt:
1755 case Intrinsics::kMathMinLongLong:
1756 case Intrinsics::kMathMinFloatFloat:
1757 case Intrinsics::kMathMinDoubleDouble: {
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001758 NormalizePackedType(&type, &is_unsigned);
Aart Bikc8e93c72017-05-10 10:49:22 -07001759 vector = new (global_allocator_)
1760 HVecMin(global_allocator_, opa, opb, type, vector_length_, is_unsigned);
1761 break;
1762 }
1763 case Intrinsics::kMathMaxIntInt:
1764 case Intrinsics::kMathMaxLongLong:
1765 case Intrinsics::kMathMaxFloatFloat:
1766 case Intrinsics::kMathMaxDoubleDouble: {
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001767 NormalizePackedType(&type, &is_unsigned);
Aart Bikc8e93c72017-05-10 10:49:22 -07001768 vector = new (global_allocator_)
1769 HVecMax(global_allocator_, opa, opb, type, vector_length_, is_unsigned);
1770 break;
1771 }
Aart Bik6daebeb2017-04-03 14:35:41 -07001772 default:
1773 LOG(FATAL) << "Unsupported SIMD intrinsic";
1774 UNREACHABLE();
1775 } // switch invoke
1776 } else {
Aart Bik24b905f2017-04-06 09:59:06 -07001777 // In scalar code, simply clone the method invoke, and replace its operands with the
1778 // corresponding new scalar instructions in the loop. The instruction will get an
1779 // environment while being inserted from the instruction map in original program order.
Aart Bik6daebeb2017-04-03 14:35:41 -07001780 DCHECK(vector_mode_ == kSequential);
Aart Bik6e92fb32017-06-05 14:05:09 -07001781 size_t num_args = invoke->GetNumberOfArguments();
Aart Bik6daebeb2017-04-03 14:35:41 -07001782 HInvokeStaticOrDirect* new_invoke = new (global_allocator_) HInvokeStaticOrDirect(
1783 global_allocator_,
Aart Bik6e92fb32017-06-05 14:05:09 -07001784 num_args,
Aart Bik6daebeb2017-04-03 14:35:41 -07001785 invoke->GetType(),
1786 invoke->GetDexPc(),
1787 invoke->GetDexMethodIndex(),
1788 invoke->GetResolvedMethod(),
1789 invoke->GetDispatchInfo(),
1790 invoke->GetInvokeType(),
1791 invoke->GetTargetMethod(),
1792 invoke->GetClinitCheckRequirement());
1793 HInputsRef inputs = invoke->GetInputs();
Aart Bik6e92fb32017-06-05 14:05:09 -07001794 size_t num_inputs = inputs.size();
1795 DCHECK_LE(num_args, num_inputs);
1796 DCHECK_EQ(num_inputs, new_invoke->GetInputs().size()); // both invokes agree
1797 for (size_t index = 0; index < num_inputs; ++index) {
1798 HInstruction* new_input = index < num_args
1799 ? vector_map_->Get(inputs[index])
1800 : inputs[index]; // beyond arguments: just pass through
1801 new_invoke->SetArgumentAt(index, new_input);
Aart Bik6daebeb2017-04-03 14:35:41 -07001802 }
Aart Bik98990262017-04-10 13:15:57 -07001803 new_invoke->SetIntrinsic(invoke->GetIntrinsic(),
1804 kNeedsEnvironmentOrCache,
1805 kNoSideEffects,
1806 kNoThrow);
Aart Bik6daebeb2017-04-03 14:35:41 -07001807 vector = new_invoke;
1808 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001809 break;
1810 }
1811 default:
1812 break;
1813 } // switch
1814 CHECK(vector != nullptr) << "Unsupported SIMD operator";
1815 vector_map_->Put(org, vector);
1816}
1817
1818#undef GENERATE_VEC
1819
1820//
Aart Bikf3e61ee2017-04-12 17:09:20 -07001821// Vectorization idioms.
1822//
1823
1824// Method recognizes the following idioms:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001825// rounding halving add (a + b + 1) >> 1 for unsigned/signed operands a, b
1826// truncated halving add (a + b) >> 1 for unsigned/signed operands a, b
Aart Bikf3e61ee2017-04-12 17:09:20 -07001827// Provided that the operands are promoted to a wider form to do the arithmetic and
1828// then cast back to narrower form, the idioms can be mapped into efficient SIMD
1829// implementation that operates directly in narrower form (plus one extra bit).
1830// TODO: current version recognizes implicit byte/short/char widening only;
1831// explicit widening from int to long could be added later.
1832bool HLoopOptimization::VectorizeHalvingAddIdiom(LoopNode* node,
1833 HInstruction* instruction,
1834 bool generate_code,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001835 DataType::Type type,
Aart Bikf3e61ee2017-04-12 17:09:20 -07001836 uint64_t restrictions) {
1837 // Test for top level arithmetic shift right x >> 1 or logical shift right x >>> 1
Aart Bik304c8a52017-05-23 11:01:13 -07001838 // (note whether the sign bit in wider precision is shifted in has no effect
Aart Bikf3e61ee2017-04-12 17:09:20 -07001839 // on the narrow precision computed by the idiom).
Aart Bikf3e61ee2017-04-12 17:09:20 -07001840 if ((instruction->IsShr() ||
1841 instruction->IsUShr()) &&
Aart Bik0148de42017-09-05 09:25:01 -07001842 IsInt64Value(instruction->InputAt(1), 1)) {
Aart Bik5f805002017-05-16 16:42:41 -07001843 // Test for (a + b + c) >> 1 for optional constant c.
1844 HInstruction* a = nullptr;
1845 HInstruction* b = nullptr;
1846 int64_t c = 0;
1847 if (IsAddConst(instruction->InputAt(0), /*out*/ &a, /*out*/ &b, /*out*/ &c)) {
Aart Bik304c8a52017-05-23 11:01:13 -07001848 DCHECK(a != nullptr && b != nullptr);
Aart Bik5f805002017-05-16 16:42:41 -07001849 // Accept c == 1 (rounded) or c == 0 (not rounded).
1850 bool is_rounded = false;
1851 if (c == 1) {
1852 is_rounded = true;
1853 } else if (c != 0) {
1854 return false;
1855 }
1856 // Accept consistent zero or sign extension on operands a and b.
Aart Bikf3e61ee2017-04-12 17:09:20 -07001857 HInstruction* r = nullptr;
1858 HInstruction* s = nullptr;
1859 bool is_unsigned = false;
Aart Bik304c8a52017-05-23 11:01:13 -07001860 if (!IsNarrowerOperands(a, b, type, &r, &s, &is_unsigned)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -07001861 return false;
1862 }
1863 // Deal with vector restrictions.
1864 if ((!is_unsigned && HasVectorRestrictions(restrictions, kNoSignedHAdd)) ||
1865 (!is_rounded && HasVectorRestrictions(restrictions, kNoUnroundedHAdd))) {
1866 return false;
1867 }
1868 // Accept recognized halving add for vectorizable operands. Vectorized code uses the
1869 // shorthand idiomatic operation. Sequential code uses the original scalar expressions.
Aart Bikdbbac8f2017-09-01 13:06:08 -07001870 DCHECK(r != nullptr);
1871 DCHECK(s != nullptr);
Aart Bik304c8a52017-05-23 11:01:13 -07001872 if (generate_code && vector_mode_ != kVector) { // de-idiom
1873 r = instruction->InputAt(0);
1874 s = instruction->InputAt(1);
1875 }
Aart Bikf3e61ee2017-04-12 17:09:20 -07001876 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
1877 VectorizeUse(node, s, generate_code, type, restrictions)) {
1878 if (generate_code) {
1879 if (vector_mode_ == kVector) {
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001880 NormalizePackedType(&type, &is_unsigned);
Aart Bikf3e61ee2017-04-12 17:09:20 -07001881 vector_map_->Put(instruction, new (global_allocator_) HVecHalvingAdd(
1882 global_allocator_,
1883 vector_map_->Get(r),
1884 vector_map_->Get(s),
1885 type,
1886 vector_length_,
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001887 is_rounded,
1888 is_unsigned));
Aart Bik21b85922017-09-06 13:29:16 -07001889 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorizedIdiom);
Aart Bikf3e61ee2017-04-12 17:09:20 -07001890 } else {
Aart Bik304c8a52017-05-23 11:01:13 -07001891 GenerateVecOp(instruction, vector_map_->Get(r), vector_map_->Get(s), type);
Aart Bikf3e61ee2017-04-12 17:09:20 -07001892 }
1893 }
1894 return true;
1895 }
1896 }
1897 }
1898 return false;
1899}
1900
Aart Bikdbbac8f2017-09-01 13:06:08 -07001901// Method recognizes the following idiom:
1902// q += ABS(a - b) for signed operands a, b
1903// Provided that the operands have the same type or are promoted to a wider form.
1904// Since this may involve a vector length change, the idiom is handled by going directly
1905// to a sad-accumulate node (rather than relying combining finer grained nodes later).
1906// TODO: unsigned SAD too?
1907bool HLoopOptimization::VectorizeSADIdiom(LoopNode* node,
1908 HInstruction* instruction,
1909 bool generate_code,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001910 DataType::Type reduction_type,
Aart Bikdbbac8f2017-09-01 13:06:08 -07001911 uint64_t restrictions) {
1912 // Filter integral "q += ABS(a - b);" reduction, where ABS and SUB
1913 // are done in the same precision (either int or long).
1914 if (!instruction->IsAdd() ||
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001915 (reduction_type != DataType::Type::kInt32 && reduction_type != DataType::Type::kInt64)) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001916 return false;
1917 }
1918 HInstruction* q = instruction->InputAt(0);
1919 HInstruction* v = instruction->InputAt(1);
1920 HInstruction* a = nullptr;
1921 HInstruction* b = nullptr;
1922 if (v->IsInvokeStaticOrDirect() &&
1923 (v->AsInvokeStaticOrDirect()->GetIntrinsic() == Intrinsics::kMathAbsInt ||
1924 v->AsInvokeStaticOrDirect()->GetIntrinsic() == Intrinsics::kMathAbsLong)) {
1925 HInstruction* x = v->InputAt(0);
Aart Bikdf011c32017-09-28 12:53:04 -07001926 if (x->GetType() == reduction_type) {
1927 int64_t c = 0;
1928 if (x->IsSub()) {
1929 a = x->InputAt(0);
1930 b = x->InputAt(1);
1931 } else if (IsAddConst(x, /*out*/ &a, /*out*/ &c)) {
1932 b = graph_->GetConstant(reduction_type, -c); // hidden SUB!
1933 }
Aart Bikdbbac8f2017-09-01 13:06:08 -07001934 }
1935 }
1936 if (a == nullptr || b == nullptr) {
1937 return false;
1938 }
1939 // Accept same-type or consistent sign extension for narrower-type on operands a and b.
1940 // The same-type or narrower operands are called r (a or lower) and s (b or lower).
Aart Bikdf011c32017-09-28 12:53:04 -07001941 // We inspect the operands carefully to pick the most suited type.
Aart Bikdbbac8f2017-09-01 13:06:08 -07001942 HInstruction* r = a;
1943 HInstruction* s = b;
1944 bool is_unsigned = false;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001945 DataType::Type sub_type = a->GetType();
Aart Bikdf011c32017-09-28 12:53:04 -07001946 if (DataType::Size(b->GetType()) < DataType::Size(sub_type)) {
1947 sub_type = b->GetType();
1948 }
1949 if (a->IsTypeConversion() &&
1950 DataType::Size(a->InputAt(0)->GetType()) < DataType::Size(sub_type)) {
1951 sub_type = a->InputAt(0)->GetType();
1952 }
1953 if (b->IsTypeConversion() &&
1954 DataType::Size(b->InputAt(0)->GetType()) < DataType::Size(sub_type)) {
1955 sub_type = b->InputAt(0)->GetType();
Aart Bikdbbac8f2017-09-01 13:06:08 -07001956 }
1957 if (reduction_type != sub_type &&
1958 (!IsNarrowerOperands(a, b, sub_type, &r, &s, &is_unsigned) || is_unsigned)) {
1959 return false;
1960 }
1961 // Try same/narrower type and deal with vector restrictions.
1962 if (!TrySetVectorType(sub_type, &restrictions) || HasVectorRestrictions(restrictions, kNoSAD)) {
1963 return false;
1964 }
1965 // Accept SAD idiom for vectorizable operands. Vectorized code uses the shorthand
1966 // idiomatic operation. Sequential code uses the original scalar expressions.
1967 DCHECK(r != nullptr);
1968 DCHECK(s != nullptr);
1969 if (generate_code && vector_mode_ != kVector) { // de-idiom
1970 r = s = v->InputAt(0);
1971 }
1972 if (VectorizeUse(node, q, generate_code, sub_type, restrictions) &&
1973 VectorizeUse(node, r, generate_code, sub_type, restrictions) &&
1974 VectorizeUse(node, s, generate_code, sub_type, restrictions)) {
1975 if (generate_code) {
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001976 NormalizePackedType(&reduction_type, &is_unsigned);
Aart Bikdbbac8f2017-09-01 13:06:08 -07001977 if (vector_mode_ == kVector) {
1978 vector_map_->Put(instruction, new (global_allocator_) HVecSADAccumulate(
1979 global_allocator_,
1980 vector_map_->Get(q),
1981 vector_map_->Get(r),
1982 vector_map_->Get(s),
1983 reduction_type,
1984 GetOtherVL(reduction_type, sub_type, vector_length_)));
1985 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorizedIdiom);
1986 } else {
1987 GenerateVecOp(v, vector_map_->Get(r), nullptr, reduction_type);
1988 GenerateVecOp(instruction, vector_map_->Get(q), vector_map_->Get(v), reduction_type);
1989 }
1990 }
1991 return true;
1992 }
1993 return false;
1994}
1995
Aart Bikf3e61ee2017-04-12 17:09:20 -07001996//
Aart Bik14a68b42017-06-08 14:06:58 -07001997// Vectorization heuristics.
1998//
1999
2000bool HLoopOptimization::IsVectorizationProfitable(int64_t trip_count) {
2001 // Current heuristic: non-empty body with sufficient number
2002 // of iterations (if known).
2003 // TODO: refine by looking at e.g. operation count, alignment, etc.
2004 if (vector_length_ == 0) {
2005 return false; // nothing found
2006 } else if (0 < trip_count && trip_count < vector_length_) {
2007 return false; // insufficient iterations
2008 }
2009 return true;
2010}
2011
Aart Bikb29f6842017-07-28 15:58:41 -07002012void HLoopOptimization::SetPeelingCandidate(const ArrayReference* candidate,
2013 int64_t trip_count ATTRIBUTE_UNUSED) {
Aart Bik14a68b42017-06-08 14:06:58 -07002014 // Current heuristic: none.
2015 // TODO: implement
Aart Bikb29f6842017-07-28 15:58:41 -07002016 vector_peeling_candidate_ = candidate;
Aart Bik14a68b42017-06-08 14:06:58 -07002017}
2018
Artem Serovf26bb6c2017-09-01 10:59:03 +01002019static constexpr uint32_t ARM64_SIMD_MAXIMUM_UNROLL_FACTOR = 8;
2020static constexpr uint32_t ARM64_SIMD_HEURISTIC_MAX_BODY_SIZE = 50;
2021
Aart Bik14a68b42017-06-08 14:06:58 -07002022uint32_t HLoopOptimization::GetUnrollingFactor(HBasicBlock* block, int64_t trip_count) {
Aart Bik14a68b42017-06-08 14:06:58 -07002023 switch (compiler_driver_->GetInstructionSet()) {
Artem Serovf26bb6c2017-09-01 10:59:03 +01002024 case kArm64: {
Aart Bik521b50f2017-09-09 10:44:45 -07002025 // Don't unroll with insufficient iterations.
Artem Serovf26bb6c2017-09-01 10:59:03 +01002026 // TODO: Unroll loops with unknown trip count.
Aart Bik521b50f2017-09-09 10:44:45 -07002027 DCHECK_NE(vector_length_, 0u);
Artem Serovf26bb6c2017-09-01 10:59:03 +01002028 if (trip_count < 2 * vector_length_) {
Aart Bik521b50f2017-09-09 10:44:45 -07002029 return kNoUnrollingFactor;
Aart Bik14a68b42017-06-08 14:06:58 -07002030 }
Aart Bik521b50f2017-09-09 10:44:45 -07002031 // Don't unroll for large loop body size.
Artem Serovf26bb6c2017-09-01 10:59:03 +01002032 uint32_t instruction_count = block->GetInstructions().CountSize();
Aart Bik521b50f2017-09-09 10:44:45 -07002033 if (instruction_count >= ARM64_SIMD_HEURISTIC_MAX_BODY_SIZE) {
2034 return kNoUnrollingFactor;
2035 }
Artem Serovf26bb6c2017-09-01 10:59:03 +01002036 // Find a beneficial unroll factor with the following restrictions:
2037 // - At least one iteration of the transformed loop should be executed.
2038 // - The loop body shouldn't be "too big" (heuristic).
2039 uint32_t uf1 = ARM64_SIMD_HEURISTIC_MAX_BODY_SIZE / instruction_count;
2040 uint32_t uf2 = trip_count / vector_length_;
2041 uint32_t unroll_factor =
2042 TruncToPowerOfTwo(std::min({uf1, uf2, ARM64_SIMD_MAXIMUM_UNROLL_FACTOR}));
2043 DCHECK_GE(unroll_factor, 1u);
Artem Serovf26bb6c2017-09-01 10:59:03 +01002044 return unroll_factor;
Aart Bik14a68b42017-06-08 14:06:58 -07002045 }
Artem Serovf26bb6c2017-09-01 10:59:03 +01002046 case kX86:
2047 case kX86_64:
Aart Bik14a68b42017-06-08 14:06:58 -07002048 default:
Aart Bik521b50f2017-09-09 10:44:45 -07002049 return kNoUnrollingFactor;
Aart Bik14a68b42017-06-08 14:06:58 -07002050 }
2051}
2052
2053//
Aart Bikf8f5a162017-02-06 15:35:29 -08002054// Helpers.
2055//
2056
2057bool HLoopOptimization::TrySetPhiInduction(HPhi* phi, bool restrict_uses) {
Aart Bikb29f6842017-07-28 15:58:41 -07002058 // Start with empty phi induction.
2059 iset_->clear();
2060
Nicolas Geoffrayf57c1ae2017-06-28 17:40:18 +01002061 // Special case Phis that have equivalent in a debuggable setup. Our graph checker isn't
2062 // smart enough to follow strongly connected components (and it's probably not worth
2063 // it to make it so). See b/33775412.
2064 if (graph_->IsDebuggable() && phi->HasEquivalentPhi()) {
2065 return false;
2066 }
Aart Bikb29f6842017-07-28 15:58:41 -07002067
2068 // Lookup phi induction cycle.
Aart Bikcc42be02016-10-20 16:14:16 -07002069 ArenaSet<HInstruction*>* set = induction_range_.LookupCycle(phi);
2070 if (set != nullptr) {
2071 for (HInstruction* i : *set) {
Aart Bike3dedc52016-11-02 17:50:27 -07002072 // Check that, other than instructions that are no longer in the graph (removed earlier)
Aart Bikf8f5a162017-02-06 15:35:29 -08002073 // each instruction is removable and, when restrict uses are requested, other than for phi,
2074 // all uses are contained within the cycle.
Aart Bike3dedc52016-11-02 17:50:27 -07002075 if (!i->IsInBlock()) {
2076 continue;
2077 } else if (!i->IsRemovable()) {
2078 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08002079 } else if (i != phi && restrict_uses) {
Aart Bikb29f6842017-07-28 15:58:41 -07002080 // Deal with regular uses.
Aart Bikcc42be02016-10-20 16:14:16 -07002081 for (const HUseListNode<HInstruction*>& use : i->GetUses()) {
2082 if (set->find(use.GetUser()) == set->end()) {
2083 return false;
2084 }
2085 }
2086 }
Aart Bike3dedc52016-11-02 17:50:27 -07002087 iset_->insert(i); // copy
Aart Bikcc42be02016-10-20 16:14:16 -07002088 }
Aart Bikcc42be02016-10-20 16:14:16 -07002089 return true;
2090 }
2091 return false;
2092}
2093
Aart Bikb29f6842017-07-28 15:58:41 -07002094bool HLoopOptimization::TrySetPhiReduction(HPhi* phi) {
Aart Bikcc42be02016-10-20 16:14:16 -07002095 DCHECK(iset_->empty());
Aart Bikb29f6842017-07-28 15:58:41 -07002096 // Only unclassified phi cycles are candidates for reductions.
2097 if (induction_range_.IsClassified(phi)) {
2098 return false;
2099 }
2100 // Accept operations like x = x + .., provided that the phi and the reduction are
2101 // used exactly once inside the loop, and by each other.
2102 HInputsRef inputs = phi->GetInputs();
2103 if (inputs.size() == 2) {
2104 HInstruction* reduction = inputs[1];
2105 if (HasReductionFormat(reduction, phi)) {
2106 HLoopInformation* loop_info = phi->GetBlock()->GetLoopInformation();
2107 int32_t use_count = 0;
2108 bool single_use_inside_loop =
2109 // Reduction update only used by phi.
2110 reduction->GetUses().HasExactlyOneElement() &&
2111 !reduction->HasEnvironmentUses() &&
2112 // Reduction update is only use of phi inside the loop.
2113 IsOnlyUsedAfterLoop(loop_info, phi, /*collect_loop_uses*/ true, &use_count) &&
2114 iset_->size() == 1;
2115 iset_->clear(); // leave the way you found it
2116 if (single_use_inside_loop) {
2117 // Link reduction back, and start recording feed value.
2118 reductions_->Put(reduction, phi);
2119 reductions_->Put(phi, phi->InputAt(0));
2120 return true;
2121 }
2122 }
2123 }
2124 return false;
2125}
2126
2127bool HLoopOptimization::TrySetSimpleLoopHeader(HBasicBlock* block, /*out*/ HPhi** main_phi) {
2128 // Start with empty phi induction and reductions.
2129 iset_->clear();
2130 reductions_->clear();
2131
2132 // Scan the phis to find the following (the induction structure has already
2133 // been optimized, so we don't need to worry about trivial cases):
2134 // (1) optional reductions in loop,
2135 // (2) the main induction, used in loop control.
2136 HPhi* phi = nullptr;
2137 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
2138 if (TrySetPhiReduction(it.Current()->AsPhi())) {
2139 continue;
2140 } else if (phi == nullptr) {
2141 // Found the first candidate for main induction.
2142 phi = it.Current()->AsPhi();
2143 } else {
2144 return false;
2145 }
2146 }
2147
2148 // Then test for a typical loopheader:
2149 // s: SuspendCheck
2150 // c: Condition(phi, bound)
2151 // i: If(c)
2152 if (phi != nullptr && TrySetPhiInduction(phi, /*restrict_uses*/ false)) {
Aart Bikcc42be02016-10-20 16:14:16 -07002153 HInstruction* s = block->GetFirstInstruction();
2154 if (s != nullptr && s->IsSuspendCheck()) {
2155 HInstruction* c = s->GetNext();
Aart Bikd86c0852017-04-14 12:00:15 -07002156 if (c != nullptr &&
2157 c->IsCondition() &&
2158 c->GetUses().HasExactlyOneElement() && // only used for termination
2159 !c->HasEnvironmentUses()) { // unlikely, but not impossible
Aart Bikcc42be02016-10-20 16:14:16 -07002160 HInstruction* i = c->GetNext();
2161 if (i != nullptr && i->IsIf() && i->InputAt(0) == c) {
2162 iset_->insert(c);
2163 iset_->insert(s);
Aart Bikb29f6842017-07-28 15:58:41 -07002164 *main_phi = phi;
Aart Bikcc42be02016-10-20 16:14:16 -07002165 return true;
2166 }
2167 }
2168 }
2169 }
2170 return false;
2171}
2172
2173bool HLoopOptimization::IsEmptyBody(HBasicBlock* block) {
Aart Bikf8f5a162017-02-06 15:35:29 -08002174 if (!block->GetPhis().IsEmpty()) {
2175 return false;
2176 }
2177 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
2178 HInstruction* instruction = it.Current();
2179 if (!instruction->IsGoto() && iset_->find(instruction) == iset_->end()) {
2180 return false;
Aart Bikcc42be02016-10-20 16:14:16 -07002181 }
Aart Bikf8f5a162017-02-06 15:35:29 -08002182 }
2183 return true;
2184}
2185
2186bool HLoopOptimization::IsUsedOutsideLoop(HLoopInformation* loop_info,
2187 HInstruction* instruction) {
Aart Bikb29f6842017-07-28 15:58:41 -07002188 // Deal with regular uses.
Aart Bikf8f5a162017-02-06 15:35:29 -08002189 for (const HUseListNode<HInstruction*>& use : instruction->GetUses()) {
2190 if (use.GetUser()->GetBlock()->GetLoopInformation() != loop_info) {
2191 return true;
2192 }
Aart Bikcc42be02016-10-20 16:14:16 -07002193 }
2194 return false;
2195}
2196
Aart Bik482095d2016-10-10 15:39:10 -07002197bool HLoopOptimization::IsOnlyUsedAfterLoop(HLoopInformation* loop_info,
Aart Bik8c4a8542016-10-06 11:36:57 -07002198 HInstruction* instruction,
Aart Bik6b69e0a2017-01-11 10:20:43 -08002199 bool collect_loop_uses,
Aart Bik8c4a8542016-10-06 11:36:57 -07002200 /*out*/ int32_t* use_count) {
Aart Bikb29f6842017-07-28 15:58:41 -07002201 // Deal with regular uses.
Aart Bik8c4a8542016-10-06 11:36:57 -07002202 for (const HUseListNode<HInstruction*>& use : instruction->GetUses()) {
2203 HInstruction* user = use.GetUser();
2204 if (iset_->find(user) == iset_->end()) { // not excluded?
2205 HLoopInformation* other_loop_info = user->GetBlock()->GetLoopInformation();
Aart Bik482095d2016-10-10 15:39:10 -07002206 if (other_loop_info != nullptr && other_loop_info->IsIn(*loop_info)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -08002207 // If collect_loop_uses is set, simply keep adding those uses to the set.
2208 // Otherwise, reject uses inside the loop that were not already in the set.
2209 if (collect_loop_uses) {
2210 iset_->insert(user);
2211 continue;
2212 }
Aart Bik8c4a8542016-10-06 11:36:57 -07002213 return false;
2214 }
2215 ++*use_count;
2216 }
2217 }
2218 return true;
2219}
2220
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002221bool HLoopOptimization::TryReplaceWithLastValue(HLoopInformation* loop_info,
2222 HInstruction* instruction,
2223 HBasicBlock* block) {
2224 // Try to replace outside uses with the last value.
Aart Bik807868e2016-11-03 17:51:43 -07002225 if (induction_range_.CanGenerateLastValue(instruction)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -08002226 HInstruction* replacement = induction_range_.GenerateLastValue(instruction, graph_, block);
Aart Bikb29f6842017-07-28 15:58:41 -07002227 // Deal with regular uses.
Aart Bik6b69e0a2017-01-11 10:20:43 -08002228 const HUseList<HInstruction*>& uses = instruction->GetUses();
2229 for (auto it = uses.begin(), end = uses.end(); it != end;) {
2230 HInstruction* user = it->GetUser();
2231 size_t index = it->GetIndex();
2232 ++it; // increment before replacing
2233 if (iset_->find(user) == iset_->end()) { // not excluded?
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002234 if (kIsDebugBuild) {
2235 // We have checked earlier in 'IsOnlyUsedAfterLoop' that the use is after the loop.
2236 HLoopInformation* other_loop_info = user->GetBlock()->GetLoopInformation();
2237 CHECK(other_loop_info == nullptr || !other_loop_info->IsIn(*loop_info));
2238 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08002239 user->ReplaceInput(replacement, index);
2240 induction_range_.Replace(user, instruction, replacement); // update induction
2241 }
2242 }
Aart Bikb29f6842017-07-28 15:58:41 -07002243 // Deal with environment uses.
Aart Bik6b69e0a2017-01-11 10:20:43 -08002244 const HUseList<HEnvironment*>& env_uses = instruction->GetEnvUses();
2245 for (auto it = env_uses.begin(), end = env_uses.end(); it != end;) {
2246 HEnvironment* user = it->GetUser();
2247 size_t index = it->GetIndex();
2248 ++it; // increment before replacing
2249 if (iset_->find(user->GetHolder()) == iset_->end()) { // not excluded?
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002250 // Only update environment uses after the loop.
Aart Bik14a68b42017-06-08 14:06:58 -07002251 HLoopInformation* other_loop_info = user->GetHolder()->GetBlock()->GetLoopInformation();
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002252 if (other_loop_info == nullptr || !other_loop_info->IsIn(*loop_info)) {
2253 user->RemoveAsUserOfInput(index);
2254 user->SetRawEnvAt(index, replacement);
2255 replacement->AddEnvUseAt(user, index);
2256 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08002257 }
2258 }
Aart Bik807868e2016-11-03 17:51:43 -07002259 return true;
Aart Bik8c4a8542016-10-06 11:36:57 -07002260 }
Aart Bik807868e2016-11-03 17:51:43 -07002261 return false;
Aart Bik8c4a8542016-10-06 11:36:57 -07002262}
2263
Aart Bikf8f5a162017-02-06 15:35:29 -08002264bool HLoopOptimization::TryAssignLastValue(HLoopInformation* loop_info,
2265 HInstruction* instruction,
2266 HBasicBlock* block,
2267 bool collect_loop_uses) {
2268 // Assigning the last value is always successful if there are no uses.
2269 // Otherwise, it succeeds in a no early-exit loop by generating the
2270 // proper last value assignment.
2271 int32_t use_count = 0;
2272 return IsOnlyUsedAfterLoop(loop_info, instruction, collect_loop_uses, &use_count) &&
2273 (use_count == 0 ||
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002274 (!IsEarlyExit(loop_info) && TryReplaceWithLastValue(loop_info, instruction, block)));
Aart Bikf8f5a162017-02-06 15:35:29 -08002275}
2276
Aart Bik6b69e0a2017-01-11 10:20:43 -08002277void HLoopOptimization::RemoveDeadInstructions(const HInstructionList& list) {
2278 for (HBackwardInstructionIterator i(list); !i.Done(); i.Advance()) {
2279 HInstruction* instruction = i.Current();
2280 if (instruction->IsDeadAndRemovable()) {
2281 simplified_ = true;
2282 instruction->GetBlock()->RemoveInstructionOrPhi(instruction);
2283 }
2284 }
2285}
2286
Aart Bik14a68b42017-06-08 14:06:58 -07002287bool HLoopOptimization::CanRemoveCycle() {
2288 for (HInstruction* i : *iset_) {
2289 // We can never remove instructions that have environment
2290 // uses when we compile 'debuggable'.
2291 if (i->HasEnvironmentUses() && graph_->IsDebuggable()) {
2292 return false;
2293 }
2294 // A deoptimization should never have an environment input removed.
2295 for (const HUseListNode<HEnvironment*>& use : i->GetEnvUses()) {
2296 if (use.GetUser()->GetHolder()->IsDeoptimize()) {
2297 return false;
2298 }
2299 }
2300 }
2301 return true;
2302}
2303
Aart Bik281c6812016-08-26 11:31:48 -07002304} // namespace art