blob: 69080340e41cf53ccb4e2ddbdf54af5b7c7f8968 [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 Bik38a3f212017-10-20 17:02:21 -070028#include "mirror/array-inl.h"
29#include "mirror/string.h"
Aart Bik281c6812016-08-26 11:31:48 -070030
31namespace art {
32
Aart Bikf8f5a162017-02-06 15:35:29 -080033// Enables vectorization (SIMDization) in the loop optimizer.
34static constexpr bool kEnableVectorization = true;
35
Artem Serov121f2032017-10-23 19:19:06 +010036// Enables scalar loop unrolling in the loop optimizer.
37static constexpr bool kEnableScalarUnrolling = false;
Aart Bik521b50f2017-09-09 10:44:45 -070038
Aart Bik38a3f212017-10-20 17:02:21 -070039//
40// Static helpers.
41//
42
43// Base alignment for arrays/strings guaranteed by the Android runtime.
44static uint32_t BaseAlignment() {
45 return kObjectAlignment;
46}
47
48// Hidden offset for arrays/strings guaranteed by the Android runtime.
49static uint32_t HiddenOffset(DataType::Type type, bool is_string_char_at) {
50 return is_string_char_at
51 ? mirror::String::ValueOffset().Uint32Value()
52 : mirror::Array::DataOffset(DataType::Size(type)).Uint32Value();
53}
54
Aart Bik9abf8942016-10-14 09:49:42 -070055// Remove the instruction from the graph. A bit more elaborate than the usual
56// instruction removal, since there may be a cycle in the use structure.
Aart Bik281c6812016-08-26 11:31:48 -070057static void RemoveFromCycle(HInstruction* instruction) {
Aart Bik281c6812016-08-26 11:31:48 -070058 instruction->RemoveAsUserOfAllInputs();
59 instruction->RemoveEnvironmentUsers();
60 instruction->GetBlock()->RemoveInstructionOrPhi(instruction, /*ensure_safety=*/ false);
Artem Serov21c7e6f2017-07-27 16:04:42 +010061 RemoveEnvironmentUses(instruction);
62 ResetEnvironmentInputRecords(instruction);
Aart Bik281c6812016-08-26 11:31:48 -070063}
64
Aart Bik807868e2016-11-03 17:51:43 -070065// Detect a goto block and sets succ to the single successor.
Aart Bike3dedc52016-11-02 17:50:27 -070066static bool IsGotoBlock(HBasicBlock* block, /*out*/ HBasicBlock** succ) {
67 if (block->GetPredecessors().size() == 1 &&
68 block->GetSuccessors().size() == 1 &&
69 block->IsSingleGoto()) {
70 *succ = block->GetSingleSuccessor();
71 return true;
72 }
73 return false;
74}
75
Aart Bik807868e2016-11-03 17:51:43 -070076// Detect an early exit loop.
77static bool IsEarlyExit(HLoopInformation* loop_info) {
78 HBlocksInLoopReversePostOrderIterator it_loop(*loop_info);
79 for (it_loop.Advance(); !it_loop.Done(); it_loop.Advance()) {
80 for (HBasicBlock* successor : it_loop.Current()->GetSuccessors()) {
81 if (!loop_info->Contains(*successor)) {
82 return true;
83 }
84 }
85 }
86 return false;
87}
88
Aart Bik68ca7022017-09-26 16:44:23 -070089// Forward declaration.
90static bool IsZeroExtensionAndGet(HInstruction* instruction,
91 DataType::Type type,
Aart Bikdf011c32017-09-28 12:53:04 -070092 /*out*/ HInstruction** operand);
Aart Bik68ca7022017-09-26 16:44:23 -070093
Aart Bikdf011c32017-09-28 12:53:04 -070094// Detect a sign extension in instruction from the given type.
Aart Bikdbbac8f2017-09-01 13:06:08 -070095// Returns the promoted operand on success.
Aart Bikf3e61ee2017-04-12 17:09:20 -070096static bool IsSignExtensionAndGet(HInstruction* instruction,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +010097 DataType::Type type,
Aart Bikdf011c32017-09-28 12:53:04 -070098 /*out*/ HInstruction** operand) {
Aart Bikf3e61ee2017-04-12 17:09:20 -070099 // Accept any already wider constant that would be handled properly by sign
100 // extension when represented in the *width* of the given narrower data type
Aart Bik4d1a9d42017-10-19 14:40:55 -0700101 // (the fact that Uint8/Uint16 normally zero extend does not matter here).
Aart Bikf3e61ee2017-04-12 17:09:20 -0700102 int64_t value = 0;
Aart Bik50e20d52017-05-05 14:07:29 -0700103 if (IsInt64AndGet(instruction, /*out*/ &value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700104 switch (type) {
Vladimir Markod5d2f2c2017-09-26 12:37:26 +0100105 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100106 case DataType::Type::kInt8:
Aart Bikdbbac8f2017-09-01 13:06:08 -0700107 if (IsInt<8>(value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700108 *operand = instruction;
109 return true;
110 }
111 return false;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100112 case DataType::Type::kUint16:
113 case DataType::Type::kInt16:
Aart Bikdbbac8f2017-09-01 13:06:08 -0700114 if (IsInt<16>(value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700115 *operand = instruction;
116 return true;
117 }
118 return false;
119 default:
120 return false;
121 }
122 }
Aart Bikdf011c32017-09-28 12:53:04 -0700123 // An implicit widening conversion of any signed expression sign-extends.
124 if (instruction->GetType() == type) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700125 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100126 case DataType::Type::kInt8:
127 case DataType::Type::kInt16:
Aart Bikf3e61ee2017-04-12 17:09:20 -0700128 *operand = instruction;
129 return true;
130 default:
131 return false;
132 }
133 }
Aart Bikdf011c32017-09-28 12:53:04 -0700134 // An explicit widening conversion of a signed expression sign-extends.
Aart Bik68ca7022017-09-26 16:44:23 -0700135 if (instruction->IsTypeConversion()) {
Aart Bikdf011c32017-09-28 12:53:04 -0700136 HInstruction* conv = instruction->InputAt(0);
137 DataType::Type from = conv->GetType();
Aart Bik68ca7022017-09-26 16:44:23 -0700138 switch (instruction->GetType()) {
Aart Bikdf011c32017-09-28 12:53:04 -0700139 case DataType::Type::kInt32:
Aart Bik68ca7022017-09-26 16:44:23 -0700140 case DataType::Type::kInt64:
Aart Bikdf011c32017-09-28 12:53:04 -0700141 if (type == from && (from == DataType::Type::kInt8 ||
142 from == DataType::Type::kInt16 ||
143 from == DataType::Type::kInt32)) {
144 *operand = conv;
145 return true;
146 }
147 return false;
Aart Bik68ca7022017-09-26 16:44:23 -0700148 case DataType::Type::kInt16:
149 return type == DataType::Type::kUint16 &&
150 from == DataType::Type::kUint16 &&
Aart Bikdf011c32017-09-28 12:53:04 -0700151 IsZeroExtensionAndGet(instruction->InputAt(0), type, /*out*/ operand);
Aart Bik68ca7022017-09-26 16:44:23 -0700152 default:
153 return false;
154 }
Aart Bikdbbac8f2017-09-01 13:06:08 -0700155 }
Aart Bikf3e61ee2017-04-12 17:09:20 -0700156 return false;
157}
158
Aart Bikdf011c32017-09-28 12:53:04 -0700159// Detect a zero extension in instruction from the given type.
Aart Bikdbbac8f2017-09-01 13:06:08 -0700160// Returns the promoted operand on success.
Aart Bikf3e61ee2017-04-12 17:09:20 -0700161static bool IsZeroExtensionAndGet(HInstruction* instruction,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100162 DataType::Type type,
Aart Bikdf011c32017-09-28 12:53:04 -0700163 /*out*/ HInstruction** operand) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700164 // Accept any already wider constant that would be handled properly by zero
165 // extension when represented in the *width* of the given narrower data type
Aart Bikdf011c32017-09-28 12:53:04 -0700166 // (the fact that Int8/Int16 normally sign extend does not matter here).
Aart Bikf3e61ee2017-04-12 17:09:20 -0700167 int64_t value = 0;
Aart Bik50e20d52017-05-05 14:07:29 -0700168 if (IsInt64AndGet(instruction, /*out*/ &value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700169 switch (type) {
Vladimir Markod5d2f2c2017-09-26 12:37:26 +0100170 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100171 case DataType::Type::kInt8:
Aart Bikdbbac8f2017-09-01 13:06:08 -0700172 if (IsUint<8>(value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700173 *operand = instruction;
174 return true;
175 }
176 return false;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100177 case DataType::Type::kUint16:
178 case DataType::Type::kInt16:
Aart Bikdbbac8f2017-09-01 13:06:08 -0700179 if (IsUint<16>(value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700180 *operand = instruction;
181 return true;
182 }
183 return false;
184 default:
185 return false;
186 }
187 }
Aart Bikdf011c32017-09-28 12:53:04 -0700188 // An implicit widening conversion of any unsigned expression zero-extends.
189 if (instruction->GetType() == type) {
Vladimir Markod5d2f2c2017-09-26 12:37:26 +0100190 switch (type) {
191 case DataType::Type::kUint8:
192 case DataType::Type::kUint16:
193 *operand = instruction;
194 return true;
195 default:
196 return false;
Aart Bikf3e61ee2017-04-12 17:09:20 -0700197 }
198 }
Aart Bikdf011c32017-09-28 12:53:04 -0700199 // An explicit widening conversion of an unsigned expression zero-extends.
Aart Bik68ca7022017-09-26 16:44:23 -0700200 if (instruction->IsTypeConversion()) {
Aart Bikdf011c32017-09-28 12:53:04 -0700201 HInstruction* conv = instruction->InputAt(0);
202 DataType::Type from = conv->GetType();
Aart Bik68ca7022017-09-26 16:44:23 -0700203 switch (instruction->GetType()) {
Aart Bikdf011c32017-09-28 12:53:04 -0700204 case DataType::Type::kInt32:
Aart Bik68ca7022017-09-26 16:44:23 -0700205 case DataType::Type::kInt64:
Aart Bikdf011c32017-09-28 12:53:04 -0700206 if (type == from && from == DataType::Type::kUint16) {
207 *operand = conv;
208 return true;
209 }
210 return false;
Aart Bik68ca7022017-09-26 16:44:23 -0700211 case DataType::Type::kUint16:
212 return type == DataType::Type::kInt16 &&
213 from == DataType::Type::kInt16 &&
Aart Bikdf011c32017-09-28 12:53:04 -0700214 IsSignExtensionAndGet(instruction->InputAt(0), type, /*out*/ operand);
Aart Bik68ca7022017-09-26 16:44:23 -0700215 default:
216 return false;
217 }
Aart Bikdbbac8f2017-09-01 13:06:08 -0700218 }
Aart Bikf3e61ee2017-04-12 17:09:20 -0700219 return false;
220}
221
Aart Bik304c8a52017-05-23 11:01:13 -0700222// Detect situations with same-extension narrower operands.
223// Returns true on success and sets is_unsigned accordingly.
224static bool IsNarrowerOperands(HInstruction* a,
225 HInstruction* b,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100226 DataType::Type type,
Aart Bik304c8a52017-05-23 11:01:13 -0700227 /*out*/ HInstruction** r,
228 /*out*/ HInstruction** s,
229 /*out*/ bool* is_unsigned) {
Aart Bik4d1a9d42017-10-19 14:40:55 -0700230 // Look for a matching sign extension.
231 DataType::Type stype = HVecOperation::ToSignedType(type);
232 if (IsSignExtensionAndGet(a, stype, r) && IsSignExtensionAndGet(b, stype, s)) {
Aart Bik304c8a52017-05-23 11:01:13 -0700233 *is_unsigned = false;
234 return true;
Aart Bik4d1a9d42017-10-19 14:40:55 -0700235 }
236 // Look for a matching zero extension.
237 DataType::Type utype = HVecOperation::ToUnsignedType(type);
238 if (IsZeroExtensionAndGet(a, utype, r) && IsZeroExtensionAndGet(b, utype, s)) {
Aart Bik304c8a52017-05-23 11:01:13 -0700239 *is_unsigned = true;
240 return true;
241 }
242 return false;
243}
244
245// As above, single operand.
246static bool IsNarrowerOperand(HInstruction* a,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100247 DataType::Type type,
Aart Bik304c8a52017-05-23 11:01:13 -0700248 /*out*/ HInstruction** r,
249 /*out*/ bool* is_unsigned) {
Aart Bik4d1a9d42017-10-19 14:40:55 -0700250 // Look for a matching sign extension.
251 DataType::Type stype = HVecOperation::ToSignedType(type);
252 if (IsSignExtensionAndGet(a, stype, r)) {
Aart Bik304c8a52017-05-23 11:01:13 -0700253 *is_unsigned = false;
254 return true;
Aart Bik4d1a9d42017-10-19 14:40:55 -0700255 }
256 // Look for a matching zero extension.
257 DataType::Type utype = HVecOperation::ToUnsignedType(type);
258 if (IsZeroExtensionAndGet(a, utype, r)) {
Aart Bik304c8a52017-05-23 11:01:13 -0700259 *is_unsigned = true;
260 return true;
261 }
262 return false;
263}
264
Aart Bikdbbac8f2017-09-01 13:06:08 -0700265// Compute relative vector length based on type difference.
Aart Bik38a3f212017-10-20 17:02:21 -0700266static uint32_t GetOtherVL(DataType::Type other_type, DataType::Type vector_type, uint32_t vl) {
Vladimir Markod5d2f2c2017-09-26 12:37:26 +0100267 DCHECK(DataType::IsIntegralType(other_type));
268 DCHECK(DataType::IsIntegralType(vector_type));
269 DCHECK_GE(DataType::SizeShift(other_type), DataType::SizeShift(vector_type));
270 return vl >> (DataType::SizeShift(other_type) - DataType::SizeShift(vector_type));
Aart Bikdbbac8f2017-09-01 13:06:08 -0700271}
272
Aart Bik5f805002017-05-16 16:42:41 -0700273// Detect up to two instructions a and b, and an acccumulated constant c.
274static bool IsAddConstHelper(HInstruction* instruction,
275 /*out*/ HInstruction** a,
276 /*out*/ HInstruction** b,
277 /*out*/ int64_t* c,
278 int32_t depth) {
279 static constexpr int32_t kMaxDepth = 8; // don't search too deep
280 int64_t value = 0;
281 if (IsInt64AndGet(instruction, &value)) {
282 *c += value;
283 return true;
284 } else if (instruction->IsAdd() && depth <= kMaxDepth) {
285 return IsAddConstHelper(instruction->InputAt(0), a, b, c, depth + 1) &&
286 IsAddConstHelper(instruction->InputAt(1), a, b, c, depth + 1);
287 } else if (*a == nullptr) {
288 *a = instruction;
289 return true;
290 } else if (*b == nullptr) {
291 *b = instruction;
292 return true;
293 }
294 return false; // too many non-const operands
295}
296
297// Detect a + b + c for an optional constant c.
298static bool IsAddConst(HInstruction* instruction,
299 /*out*/ HInstruction** a,
300 /*out*/ HInstruction** b,
301 /*out*/ int64_t* c) {
302 if (instruction->IsAdd()) {
303 // Try to find a + b and accumulated c.
304 if (IsAddConstHelper(instruction->InputAt(0), a, b, c, /*depth*/ 0) &&
305 IsAddConstHelper(instruction->InputAt(1), a, b, c, /*depth*/ 0) &&
306 *b != nullptr) {
307 return true;
308 }
309 // Found a + b.
310 *a = instruction->InputAt(0);
311 *b = instruction->InputAt(1);
312 *c = 0;
313 return true;
314 }
315 return false;
316}
317
Aart Bikdf011c32017-09-28 12:53:04 -0700318// Detect a + c for constant c.
319static bool IsAddConst(HInstruction* instruction,
320 /*out*/ HInstruction** a,
321 /*out*/ int64_t* c) {
322 if (instruction->IsAdd()) {
323 if (IsInt64AndGet(instruction->InputAt(0), c)) {
324 *a = instruction->InputAt(1);
325 return true;
326 } else if (IsInt64AndGet(instruction->InputAt(1), c)) {
327 *a = instruction->InputAt(0);
328 return true;
329 }
330 }
331 return false;
332}
333
Aart Bik29aa0822018-03-08 11:28:00 -0800334// Detect clipped [lo, hi] range for nested MIN-MAX operations on a clippee,
335// such as MIN(hi, MAX(lo, clippee)) for an arbitrary clippee expression.
336// Example: MIN(10, MIN(20, MAX(0, x))) yields [0, 10] with clippee x.
Aart Bik1a381022018-03-15 15:51:37 -0700337static HInstruction* FindClippee(HInstruction* instruction,
338 /*out*/ int64_t* lo,
339 /*out*/ int64_t* hi) {
340 // Iterate into MIN(.., c)-MAX(.., c) expressions and 'tighten' the range [lo, hi].
341 while (instruction->IsMin() || instruction->IsMax()) {
342 HBinaryOperation* min_max = instruction->AsBinaryOperation();
343 DCHECK(min_max->GetType() == DataType::Type::kInt32 ||
344 min_max->GetType() == DataType::Type::kInt64);
345 // Process the constant.
346 HConstant* right = min_max->GetConstantRight();
347 if (right == nullptr) {
348 break;
349 } else if (instruction->IsMin()) {
350 *hi = std::min(*hi, Int64FromConstant(right));
351 } else {
352 *lo = std::max(*lo, Int64FromConstant(right));
Aart Bik29aa0822018-03-08 11:28:00 -0800353 }
Aart Bik1a381022018-03-15 15:51:37 -0700354 instruction = min_max->GetLeastConstantLeft();
Aart Bik29aa0822018-03-08 11:28:00 -0800355 }
Aart Bik1a381022018-03-15 15:51:37 -0700356 // Iteration ends in any other expression (possibly MIN/MAX without constant).
357 // This leaf expression is the clippee with range [lo, hi].
358 return instruction;
Aart Bik29aa0822018-03-08 11:28:00 -0800359}
360
361// Accept various saturated addition forms.
362static bool IsSaturatedAdd(DataType::Type type, int64_t lo, int64_t hi, bool is_unsigned) {
363 // MIN(r + s, 255) => SAT_ADD_unsigned
364 // MAX(MIN(r + s, 127), -128) => SAT_ADD_signed etc.
365 if (DataType::Size(type) == 1) {
366 return is_unsigned
367 ? (lo <= 0 && hi == std::numeric_limits<uint8_t>::max())
368 : (lo == std::numeric_limits<int8_t>::min() &&
369 hi == std::numeric_limits<int8_t>::max());
370 } else if (DataType::Size(type) == 2) {
371 return is_unsigned
372 ? (lo <= 0 && hi == std::numeric_limits<uint16_t>::max())
373 : (lo == std::numeric_limits<int16_t>::min() &&
374 hi == std::numeric_limits<int16_t>::max());
375 }
376 return false;
377}
378
379// Accept various saturated subtraction forms.
380static bool IsSaturatedSub(DataType::Type type, int64_t lo, int64_t hi, bool is_unsigned) {
381 // MAX(r - s, 0) => SAT_SUB_unsigned
382 // MIN(MAX(r - s, -128), 127) => SAT_ADD_signed etc.
383 if (DataType::Size(type) == 1) {
384 return is_unsigned
385 ? (lo == 0 && hi >= std::numeric_limits<uint8_t>::max())
386 : (lo == std::numeric_limits<int8_t>::min() &&
387 hi == std::numeric_limits<int8_t>::max());
388 } else if (DataType::Size(type) == 2) {
389 return is_unsigned
390 ? (lo == 0 && hi >= std::numeric_limits<uint16_t>::min())
391 : (lo == std::numeric_limits<int16_t>::min() &&
392 hi == std::numeric_limits<int16_t>::max());
393 }
394 return false;
395}
396
Aart Bikb29f6842017-07-28 15:58:41 -0700397// Detect reductions of the following forms,
Aart Bikb29f6842017-07-28 15:58:41 -0700398// x = x_phi + ..
399// x = x_phi - ..
Aart Bikb29f6842017-07-28 15:58:41 -0700400// x = min(x_phi, ..)
Aart Bik1f8d51b2018-02-15 10:42:37 -0800401// x = max(x_phi, ..)
Aart Bikb29f6842017-07-28 15:58:41 -0700402static bool HasReductionFormat(HInstruction* reduction, HInstruction* phi) {
Aart Bik1f8d51b2018-02-15 10:42:37 -0800403 if (reduction->IsAdd() || reduction->IsMin() || reduction->IsMax()) {
Aart Bikdbbac8f2017-09-01 13:06:08 -0700404 return (reduction->InputAt(0) == phi && reduction->InputAt(1) != phi) ||
405 (reduction->InputAt(0) != phi && reduction->InputAt(1) == phi);
Aart Bikb29f6842017-07-28 15:58:41 -0700406 } else if (reduction->IsSub()) {
Aart Bikdbbac8f2017-09-01 13:06:08 -0700407 return (reduction->InputAt(0) == phi && reduction->InputAt(1) != phi);
Aart Bikb29f6842017-07-28 15:58:41 -0700408 }
409 return false;
410}
411
Aart Bikdbbac8f2017-09-01 13:06:08 -0700412// Translates vector operation to reduction kind.
413static HVecReduce::ReductionKind GetReductionKind(HVecOperation* reduction) {
414 if (reduction->IsVecAdd() || reduction->IsVecSub() || reduction->IsVecSADAccumulate()) {
Aart Bik0148de42017-09-05 09:25:01 -0700415 return HVecReduce::kSum;
416 } else if (reduction->IsVecMin()) {
417 return HVecReduce::kMin;
418 } else if (reduction->IsVecMax()) {
419 return HVecReduce::kMax;
420 }
Aart Bik38a3f212017-10-20 17:02:21 -0700421 LOG(FATAL) << "Unsupported SIMD reduction " << reduction->GetId();
Aart Bik0148de42017-09-05 09:25:01 -0700422 UNREACHABLE();
423}
424
Aart Bikf8f5a162017-02-06 15:35:29 -0800425// Test vector restrictions.
426static bool HasVectorRestrictions(uint64_t restrictions, uint64_t tested) {
427 return (restrictions & tested) != 0;
428}
429
Aart Bikf3e61ee2017-04-12 17:09:20 -0700430// Insert an instruction.
Aart Bikf8f5a162017-02-06 15:35:29 -0800431static HInstruction* Insert(HBasicBlock* block, HInstruction* instruction) {
432 DCHECK(block != nullptr);
433 DCHECK(instruction != nullptr);
434 block->InsertInstructionBefore(instruction, block->GetLastInstruction());
435 return instruction;
436}
437
Artem Serov21c7e6f2017-07-27 16:04:42 +0100438// Check that instructions from the induction sets are fully removed: have no uses
439// and no other instructions use them.
Vladimir Markoca6fff82017-10-03 14:49:14 +0100440static bool CheckInductionSetFullyRemoved(ScopedArenaSet<HInstruction*>* iset) {
Artem Serov21c7e6f2017-07-27 16:04:42 +0100441 for (HInstruction* instr : *iset) {
442 if (instr->GetBlock() != nullptr ||
443 !instr->GetUses().empty() ||
444 !instr->GetEnvUses().empty() ||
445 HasEnvironmentUsedByOthers(instr)) {
446 return false;
447 }
448 }
Artem Serov21c7e6f2017-07-27 16:04:42 +0100449 return true;
450}
451
Aart Bik281c6812016-08-26 11:31:48 -0700452//
Aart Bikb29f6842017-07-28 15:58:41 -0700453// Public methods.
Aart Bik281c6812016-08-26 11:31:48 -0700454//
455
456HLoopOptimization::HLoopOptimization(HGraph* graph,
Aart Bik92685a82017-03-06 11:13:43 -0800457 CompilerDriver* compiler_driver,
Aart Bikb92cc332017-09-06 15:53:17 -0700458 HInductionVarAnalysis* induction_analysis,
Aart Bik2ca10eb2017-11-15 15:17:53 -0800459 OptimizingCompilerStats* stats,
460 const char* name)
461 : HOptimization(graph, name, stats),
Aart Bik92685a82017-03-06 11:13:43 -0800462 compiler_driver_(compiler_driver),
Aart Bik281c6812016-08-26 11:31:48 -0700463 induction_range_(induction_analysis),
Aart Bik96202302016-10-04 17:33:56 -0700464 loop_allocator_(nullptr),
Vladimir Markoca6fff82017-10-03 14:49:14 +0100465 global_allocator_(graph_->GetAllocator()),
Aart Bik281c6812016-08-26 11:31:48 -0700466 top_loop_(nullptr),
Aart Bik8c4a8542016-10-06 11:36:57 -0700467 last_loop_(nullptr),
Aart Bik482095d2016-10-10 15:39:10 -0700468 iset_(nullptr),
Aart Bikb29f6842017-07-28 15:58:41 -0700469 reductions_(nullptr),
Aart Bikf8f5a162017-02-06 15:35:29 -0800470 simplified_(false),
471 vector_length_(0),
472 vector_refs_(nullptr),
Aart Bik38a3f212017-10-20 17:02:21 -0700473 vector_static_peeling_factor_(0),
474 vector_dynamic_peeling_candidate_(nullptr),
Aart Bik14a68b42017-06-08 14:06:58 -0700475 vector_runtime_test_a_(nullptr),
476 vector_runtime_test_b_(nullptr),
Aart Bik0148de42017-09-05 09:25:01 -0700477 vector_map_(nullptr),
Vladimir Markoca6fff82017-10-03 14:49:14 +0100478 vector_permanent_map_(nullptr),
479 vector_mode_(kSequential),
480 vector_preheader_(nullptr),
481 vector_header_(nullptr),
482 vector_body_(nullptr),
Artem Serov121f2032017-10-23 19:19:06 +0100483 vector_index_(nullptr),
484 arch_loop_helper_(ArchDefaultLoopHelper::Create(compiler_driver_ != nullptr
485 ? compiler_driver_->GetInstructionSet()
486 : InstructionSet::kNone,
487 global_allocator_)) {
Aart Bik281c6812016-08-26 11:31:48 -0700488}
489
490void HLoopOptimization::Run() {
Mingyao Yang01b47b02017-02-03 12:09:57 -0800491 // Skip if there is no loop or the graph has try-catch/irreducible loops.
Aart Bik281c6812016-08-26 11:31:48 -0700492 // TODO: make this less of a sledgehammer.
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800493 if (!graph_->HasLoops() || graph_->HasTryCatch() || graph_->HasIrreducibleLoops()) {
Aart Bik281c6812016-08-26 11:31:48 -0700494 return;
495 }
496
Vladimir Markoca6fff82017-10-03 14:49:14 +0100497 // Phase-local allocator.
498 ScopedArenaAllocator allocator(graph_->GetArenaStack());
Aart Bik96202302016-10-04 17:33:56 -0700499 loop_allocator_ = &allocator;
Nicolas Geoffrayebe16742016-10-05 09:55:42 +0100500
Aart Bik96202302016-10-04 17:33:56 -0700501 // Perform loop optimizations.
502 LocalRun();
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800503 if (top_loop_ == nullptr) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800504 graph_->SetHasLoops(false); // no more loops
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800505 }
506
Aart Bik96202302016-10-04 17:33:56 -0700507 // Detach.
508 loop_allocator_ = nullptr;
509 last_loop_ = top_loop_ = nullptr;
510}
511
Aart Bikb29f6842017-07-28 15:58:41 -0700512//
513// Loop setup and traversal.
514//
515
Aart Bik96202302016-10-04 17:33:56 -0700516void HLoopOptimization::LocalRun() {
517 // Build the linear order using the phase-local allocator. This step enables building
518 // a loop hierarchy that properly reflects the outer-inner and previous-next relation.
Vladimir Markoca6fff82017-10-03 14:49:14 +0100519 ScopedArenaVector<HBasicBlock*> linear_order(loop_allocator_->Adapter(kArenaAllocLinearOrder));
520 LinearizeGraph(graph_, &linear_order);
Aart Bik96202302016-10-04 17:33:56 -0700521
Aart Bik281c6812016-08-26 11:31:48 -0700522 // Build the loop hierarchy.
Aart Bik96202302016-10-04 17:33:56 -0700523 for (HBasicBlock* block : linear_order) {
Aart Bik281c6812016-08-26 11:31:48 -0700524 if (block->IsLoopHeader()) {
525 AddLoop(block->GetLoopInformation());
526 }
527 }
Aart Bik96202302016-10-04 17:33:56 -0700528
Aart Bik8c4a8542016-10-06 11:36:57 -0700529 // Traverse the loop hierarchy inner-to-outer and optimize. Traversal can use
Aart Bikf8f5a162017-02-06 15:35:29 -0800530 // temporary data structures using the phase-local allocator. All new HIR
531 // should use the global allocator.
Aart Bik8c4a8542016-10-06 11:36:57 -0700532 if (top_loop_ != nullptr) {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100533 ScopedArenaSet<HInstruction*> iset(loop_allocator_->Adapter(kArenaAllocLoopOptimization));
534 ScopedArenaSafeMap<HInstruction*, HInstruction*> reds(
Aart Bikb29f6842017-07-28 15:58:41 -0700535 std::less<HInstruction*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
Vladimir Markoca6fff82017-10-03 14:49:14 +0100536 ScopedArenaSet<ArrayReference> refs(loop_allocator_->Adapter(kArenaAllocLoopOptimization));
537 ScopedArenaSafeMap<HInstruction*, HInstruction*> map(
Aart Bikf8f5a162017-02-06 15:35:29 -0800538 std::less<HInstruction*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
Vladimir Markoca6fff82017-10-03 14:49:14 +0100539 ScopedArenaSafeMap<HInstruction*, HInstruction*> perm(
Aart Bik0148de42017-09-05 09:25:01 -0700540 std::less<HInstruction*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
Aart Bikf8f5a162017-02-06 15:35:29 -0800541 // Attach.
Aart Bik8c4a8542016-10-06 11:36:57 -0700542 iset_ = &iset;
Aart Bikb29f6842017-07-28 15:58:41 -0700543 reductions_ = &reds;
Aart Bikf8f5a162017-02-06 15:35:29 -0800544 vector_refs_ = &refs;
545 vector_map_ = &map;
Aart Bik0148de42017-09-05 09:25:01 -0700546 vector_permanent_map_ = &perm;
Aart Bikf8f5a162017-02-06 15:35:29 -0800547 // Traverse.
Aart Bik8c4a8542016-10-06 11:36:57 -0700548 TraverseLoopsInnerToOuter(top_loop_);
Aart Bikf8f5a162017-02-06 15:35:29 -0800549 // Detach.
550 iset_ = nullptr;
Aart Bikb29f6842017-07-28 15:58:41 -0700551 reductions_ = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800552 vector_refs_ = nullptr;
553 vector_map_ = nullptr;
Aart Bik0148de42017-09-05 09:25:01 -0700554 vector_permanent_map_ = nullptr;
Aart Bik8c4a8542016-10-06 11:36:57 -0700555 }
Aart Bik281c6812016-08-26 11:31:48 -0700556}
557
558void HLoopOptimization::AddLoop(HLoopInformation* loop_info) {
559 DCHECK(loop_info != nullptr);
Aart Bikf8f5a162017-02-06 15:35:29 -0800560 LoopNode* node = new (loop_allocator_) LoopNode(loop_info);
Aart Bik281c6812016-08-26 11:31:48 -0700561 if (last_loop_ == nullptr) {
562 // First loop.
563 DCHECK(top_loop_ == nullptr);
564 last_loop_ = top_loop_ = node;
565 } else if (loop_info->IsIn(*last_loop_->loop_info)) {
566 // Inner loop.
567 node->outer = last_loop_;
568 DCHECK(last_loop_->inner == nullptr);
569 last_loop_ = last_loop_->inner = node;
570 } else {
571 // Subsequent loop.
572 while (last_loop_->outer != nullptr && !loop_info->IsIn(*last_loop_->outer->loop_info)) {
573 last_loop_ = last_loop_->outer;
574 }
575 node->outer = last_loop_->outer;
576 node->previous = last_loop_;
577 DCHECK(last_loop_->next == nullptr);
578 last_loop_ = last_loop_->next = node;
579 }
580}
581
582void HLoopOptimization::RemoveLoop(LoopNode* node) {
583 DCHECK(node != nullptr);
Aart Bik8c4a8542016-10-06 11:36:57 -0700584 DCHECK(node->inner == nullptr);
585 if (node->previous != nullptr) {
586 // Within sequence.
587 node->previous->next = node->next;
588 if (node->next != nullptr) {
589 node->next->previous = node->previous;
590 }
591 } else {
592 // First of sequence.
593 if (node->outer != nullptr) {
594 node->outer->inner = node->next;
595 } else {
596 top_loop_ = node->next;
597 }
598 if (node->next != nullptr) {
599 node->next->outer = node->outer;
600 node->next->previous = nullptr;
601 }
602 }
Aart Bik281c6812016-08-26 11:31:48 -0700603}
604
Aart Bikb29f6842017-07-28 15:58:41 -0700605bool HLoopOptimization::TraverseLoopsInnerToOuter(LoopNode* node) {
606 bool changed = false;
Aart Bik281c6812016-08-26 11:31:48 -0700607 for ( ; node != nullptr; node = node->next) {
Aart Bikb29f6842017-07-28 15:58:41 -0700608 // Visit inner loops first. Recompute induction information for this
609 // loop if the induction of any inner loop has changed.
610 if (TraverseLoopsInnerToOuter(node->inner)) {
Aart Bik482095d2016-10-10 15:39:10 -0700611 induction_range_.ReVisit(node->loop_info);
612 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800613 // Repeat simplifications in the loop-body until no more changes occur.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800614 // Note that since each simplification consists of eliminating code (without
615 // introducing new code), this process is always finite.
Aart Bikdf7822e2016-12-06 10:05:30 -0800616 do {
617 simplified_ = false;
Aart Bikdf7822e2016-12-06 10:05:30 -0800618 SimplifyInduction(node);
Aart Bik6b69e0a2017-01-11 10:20:43 -0800619 SimplifyBlocks(node);
Aart Bikb29f6842017-07-28 15:58:41 -0700620 changed = simplified_ || changed;
Aart Bikdf7822e2016-12-06 10:05:30 -0800621 } while (simplified_);
Aart Bikf8f5a162017-02-06 15:35:29 -0800622 // Optimize inner loop.
Aart Bik9abf8942016-10-14 09:49:42 -0700623 if (node->inner == nullptr) {
Aart Bikb29f6842017-07-28 15:58:41 -0700624 changed = OptimizeInnerLoop(node) || changed;
Aart Bik9abf8942016-10-14 09:49:42 -0700625 }
Aart Bik281c6812016-08-26 11:31:48 -0700626 }
Aart Bikb29f6842017-07-28 15:58:41 -0700627 return changed;
Aart Bik281c6812016-08-26 11:31:48 -0700628}
629
Aart Bikf8f5a162017-02-06 15:35:29 -0800630//
631// Optimization.
632//
633
Aart Bik281c6812016-08-26 11:31:48 -0700634void HLoopOptimization::SimplifyInduction(LoopNode* node) {
635 HBasicBlock* header = node->loop_info->GetHeader();
636 HBasicBlock* preheader = node->loop_info->GetPreHeader();
Aart Bik8c4a8542016-10-06 11:36:57 -0700637 // Scan the phis in the header to find opportunities to simplify an induction
638 // cycle that is only used outside the loop. Replace these uses, if any, with
639 // the last value and remove the induction cycle.
640 // Examples: for (int i = 0; x != null; i++) { .... no i .... }
641 // for (int i = 0; i < 10; i++, k++) { .... no k .... } return k;
Aart Bik281c6812016-08-26 11:31:48 -0700642 for (HInstructionIterator it(header->GetPhis()); !it.Done(); it.Advance()) {
643 HPhi* phi = it.Current()->AsPhi();
Aart Bikf8f5a162017-02-06 15:35:29 -0800644 if (TrySetPhiInduction(phi, /*restrict_uses*/ true) &&
645 TryAssignLastValue(node->loop_info, phi, preheader, /*collect_loop_uses*/ false)) {
Aart Bik671e48a2017-08-09 13:16:56 -0700646 // Note that it's ok to have replaced uses after the loop with the last value, without
647 // being able to remove the cycle. Environment uses (which are the reason we may not be
648 // able to remove the cycle) within the loop will still hold the right value. We must
649 // have tried first, however, to replace outside uses.
650 if (CanRemoveCycle()) {
651 simplified_ = true;
652 for (HInstruction* i : *iset_) {
653 RemoveFromCycle(i);
654 }
655 DCHECK(CheckInductionSetFullyRemoved(iset_));
Aart Bik281c6812016-08-26 11:31:48 -0700656 }
Aart Bik482095d2016-10-10 15:39:10 -0700657 }
658 }
659}
660
661void HLoopOptimization::SimplifyBlocks(LoopNode* node) {
Aart Bikdf7822e2016-12-06 10:05:30 -0800662 // Iterate over all basic blocks in the loop-body.
663 for (HBlocksInLoopIterator it(*node->loop_info); !it.Done(); it.Advance()) {
664 HBasicBlock* block = it.Current();
665 // Remove dead instructions from the loop-body.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800666 RemoveDeadInstructions(block->GetPhis());
667 RemoveDeadInstructions(block->GetInstructions());
Aart Bikdf7822e2016-12-06 10:05:30 -0800668 // Remove trivial control flow blocks from the loop-body.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800669 if (block->GetPredecessors().size() == 1 &&
670 block->GetSuccessors().size() == 1 &&
671 block->GetSingleSuccessor()->GetPredecessors().size() == 1) {
Aart Bikdf7822e2016-12-06 10:05:30 -0800672 simplified_ = true;
Aart Bik6b69e0a2017-01-11 10:20:43 -0800673 block->MergeWith(block->GetSingleSuccessor());
Aart Bikdf7822e2016-12-06 10:05:30 -0800674 } else if (block->GetSuccessors().size() == 2) {
675 // Trivial if block can be bypassed to either branch.
676 HBasicBlock* succ0 = block->GetSuccessors()[0];
677 HBasicBlock* succ1 = block->GetSuccessors()[1];
678 HBasicBlock* meet0 = nullptr;
679 HBasicBlock* meet1 = nullptr;
680 if (succ0 != succ1 &&
681 IsGotoBlock(succ0, &meet0) &&
682 IsGotoBlock(succ1, &meet1) &&
683 meet0 == meet1 && // meets again
684 meet0 != block && // no self-loop
685 meet0->GetPhis().IsEmpty()) { // not used for merging
686 simplified_ = true;
687 succ0->DisconnectAndDelete();
688 if (block->Dominates(meet0)) {
689 block->RemoveDominatedBlock(meet0);
690 succ1->AddDominatedBlock(meet0);
691 meet0->SetDominator(succ1);
Aart Bike3dedc52016-11-02 17:50:27 -0700692 }
Aart Bik482095d2016-10-10 15:39:10 -0700693 }
Aart Bik281c6812016-08-26 11:31:48 -0700694 }
Aart Bikdf7822e2016-12-06 10:05:30 -0800695 }
Aart Bik281c6812016-08-26 11:31:48 -0700696}
697
Artem Serov121f2032017-10-23 19:19:06 +0100698bool HLoopOptimization::TryOptimizeInnerLoopFinite(LoopNode* node) {
Aart Bik281c6812016-08-26 11:31:48 -0700699 HBasicBlock* header = node->loop_info->GetHeader();
700 HBasicBlock* preheader = node->loop_info->GetPreHeader();
Aart Bik9abf8942016-10-14 09:49:42 -0700701 // Ensure loop header logic is finite.
Aart Bikf8f5a162017-02-06 15:35:29 -0800702 int64_t trip_count = 0;
703 if (!induction_range_.IsFinite(node->loop_info, &trip_count)) {
Aart Bikb29f6842017-07-28 15:58:41 -0700704 return false;
Aart Bik9abf8942016-10-14 09:49:42 -0700705 }
Aart Bik281c6812016-08-26 11:31:48 -0700706 // Ensure there is only a single loop-body (besides the header).
707 HBasicBlock* body = nullptr;
708 for (HBlocksInLoopIterator it(*node->loop_info); !it.Done(); it.Advance()) {
709 if (it.Current() != header) {
710 if (body != nullptr) {
Aart Bikb29f6842017-07-28 15:58:41 -0700711 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700712 }
713 body = it.Current();
714 }
715 }
Andreas Gampef45d61c2017-06-07 10:29:33 -0700716 CHECK(body != nullptr);
Aart Bik281c6812016-08-26 11:31:48 -0700717 // Ensure there is only a single exit point.
718 if (header->GetSuccessors().size() != 2) {
Aart Bikb29f6842017-07-28 15:58:41 -0700719 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700720 }
721 HBasicBlock* exit = (header->GetSuccessors()[0] == body)
722 ? header->GetSuccessors()[1]
723 : header->GetSuccessors()[0];
Aart Bik8c4a8542016-10-06 11:36:57 -0700724 // Ensure exit can only be reached by exiting loop.
Aart Bik281c6812016-08-26 11:31:48 -0700725 if (exit->GetPredecessors().size() != 1) {
Aart Bikb29f6842017-07-28 15:58:41 -0700726 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700727 }
Aart Bik6b69e0a2017-01-11 10:20:43 -0800728 // Detect either an empty loop (no side effects other than plain iteration) or
729 // a trivial loop (just iterating once). Replace subsequent index uses, if any,
730 // with the last value and remove the loop, possibly after unrolling its body.
Aart Bikb29f6842017-07-28 15:58:41 -0700731 HPhi* main_phi = nullptr;
732 if (TrySetSimpleLoopHeader(header, &main_phi)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -0800733 bool is_empty = IsEmptyBody(body);
Aart Bikb29f6842017-07-28 15:58:41 -0700734 if (reductions_->empty() && // TODO: possible with some effort
735 (is_empty || trip_count == 1) &&
736 TryAssignLastValue(node->loop_info, main_phi, preheader, /*collect_loop_uses*/ true)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -0800737 if (!is_empty) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800738 // Unroll the loop-body, which sees initial value of the index.
Aart Bikb29f6842017-07-28 15:58:41 -0700739 main_phi->ReplaceWith(main_phi->InputAt(0));
Aart Bik6b69e0a2017-01-11 10:20:43 -0800740 preheader->MergeInstructionsWith(body);
741 }
742 body->DisconnectAndDelete();
743 exit->RemovePredecessor(header);
744 header->RemoveSuccessor(exit);
745 header->RemoveDominatedBlock(exit);
746 header->DisconnectAndDelete();
747 preheader->AddSuccessor(exit);
Aart Bikf8f5a162017-02-06 15:35:29 -0800748 preheader->AddInstruction(new (global_allocator_) HGoto());
Aart Bik6b69e0a2017-01-11 10:20:43 -0800749 preheader->AddDominatedBlock(exit);
750 exit->SetDominator(preheader);
751 RemoveLoop(node); // update hierarchy
Aart Bikb29f6842017-07-28 15:58:41 -0700752 return true;
Aart Bikf8f5a162017-02-06 15:35:29 -0800753 }
754 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800755 // Vectorize loop, if possible and valid.
Aart Bikb29f6842017-07-28 15:58:41 -0700756 if (kEnableVectorization &&
757 TrySetSimpleLoopHeader(header, &main_phi) &&
Aart Bikb29f6842017-07-28 15:58:41 -0700758 ShouldVectorize(node, body, trip_count) &&
759 TryAssignLastValue(node->loop_info, main_phi, preheader, /*collect_loop_uses*/ true)) {
760 Vectorize(node, body, exit, trip_count);
761 graph_->SetHasSIMD(true); // flag SIMD usage
Aart Bik21b85922017-09-06 13:29:16 -0700762 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorized);
Aart Bikb29f6842017-07-28 15:58:41 -0700763 return true;
Aart Bikf8f5a162017-02-06 15:35:29 -0800764 }
Aart Bikb29f6842017-07-28 15:58:41 -0700765 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -0800766}
767
Artem Serov121f2032017-10-23 19:19:06 +0100768bool HLoopOptimization::OptimizeInnerLoop(LoopNode* node) {
769 return TryOptimizeInnerLoopFinite(node) ||
770 TryUnrollingForBranchPenaltyReduction(node);
771}
772
773void HLoopOptimization::PeelOrUnrollOnce(LoopNode* loop_node,
774 bool do_unrolling,
775 SuperblockCloner::HBasicBlockMap* bb_map,
776 SuperblockCloner::HInstructionMap* hir_map) {
777 // TODO: peel loop nests.
778 DCHECK(loop_node->inner == nullptr);
779
780 // Check that loop info is up-to-date.
781 HLoopInformation* loop_info = loop_node->loop_info;
782 HBasicBlock* header = loop_info->GetHeader();
783 DCHECK(loop_info == header->GetLoopInformation());
784
785 PeelUnrollHelper helper(loop_info, bb_map, hir_map);
786 DCHECK(helper.IsLoopClonable());
787 HBasicBlock* new_header = do_unrolling ? helper.DoUnrolling() : helper.DoPeeling();
788 DCHECK(header == new_header);
789 DCHECK(loop_info == new_header->GetLoopInformation());
790}
791
792//
793// Loop unrolling: generic part methods.
794//
795
796bool HLoopOptimization::TryUnrollingForBranchPenaltyReduction(LoopNode* loop_node) {
797 // Don't run peeling/unrolling if compiler_driver_ is nullptr (i.e., running under tests)
798 // as InstructionSet is needed.
799 if (!kEnableScalarUnrolling || compiler_driver_ == nullptr) {
800 return false;
801 }
802
803 HLoopInformation* loop_info = loop_node->loop_info;
804 int64_t trip_count = 0;
805 // Only unroll loops with a known tripcount.
806 if (!induction_range_.HasKnownTripCount(loop_info, &trip_count)) {
807 return false;
808 }
809
810 uint32_t unrolling_factor = arch_loop_helper_->GetScalarUnrollingFactor(loop_info, trip_count);
811 if (unrolling_factor == kNoUnrollingFactor) {
812 return false;
813 }
814
815 LoopAnalysisInfo loop_analysis_info(loop_info);
816 LoopAnalysis::CalculateLoopBasicProperties(loop_info, &loop_analysis_info);
817
818 // Check "IsLoopClonable" last as it can be time-consuming.
819 if (arch_loop_helper_->IsLoopTooBigForScalarUnrolling(&loop_analysis_info) ||
820 (loop_analysis_info.GetNumberOfExits() > 1) ||
821 loop_analysis_info.HasInstructionsPreventingScalarUnrolling() ||
822 !PeelUnrollHelper::IsLoopClonable(loop_info)) {
823 return false;
824 }
825
826 // TODO: support other unrolling factors.
827 DCHECK_EQ(unrolling_factor, 2u);
828
829 // Perform unrolling.
830 ArenaAllocator* arena = loop_info->GetHeader()->GetGraph()->GetAllocator();
831 SuperblockCloner::HBasicBlockMap bb_map(
832 std::less<HBasicBlock*>(), arena->Adapter(kArenaAllocSuperblockCloner));
833 SuperblockCloner::HInstructionMap hir_map(
834 std::less<HInstruction*>(), arena->Adapter(kArenaAllocSuperblockCloner));
835 PeelOrUnrollOnce(loop_node, /* unrolling */ true, &bb_map, &hir_map);
836
837 // Remove the redundant loop check after unrolling.
838 HIf* copy_hif = bb_map.Get(loop_info->GetHeader())->GetLastInstruction()->AsIf();
839 int32_t constant = loop_info->Contains(*copy_hif->IfTrueSuccessor()) ? 1 : 0;
840 copy_hif->ReplaceInput(graph_->GetIntConstant(constant), 0u);
841
842 return true;
843}
844
Aart Bikf8f5a162017-02-06 15:35:29 -0800845//
846// Loop vectorization. The implementation is based on the book by Aart J.C. Bik:
847// "The Software Vectorization Handbook. Applying Multimedia Extensions for Maximum Performance."
848// Intel Press, June, 2004 (http://www.aartbik.com/).
849//
850
Aart Bik14a68b42017-06-08 14:06:58 -0700851bool HLoopOptimization::ShouldVectorize(LoopNode* node, HBasicBlock* block, int64_t trip_count) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800852 // Reset vector bookkeeping.
853 vector_length_ = 0;
854 vector_refs_->clear();
Aart Bik38a3f212017-10-20 17:02:21 -0700855 vector_static_peeling_factor_ = 0;
856 vector_dynamic_peeling_candidate_ = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800857 vector_runtime_test_a_ =
Igor Murashkin2ffb7032017-11-08 13:35:21 -0800858 vector_runtime_test_b_ = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800859
860 // Phis in the loop-body prevent vectorization.
861 if (!block->GetPhis().IsEmpty()) {
862 return false;
863 }
864
865 // Scan the loop-body, starting a right-hand-side tree traversal at each left-hand-side
866 // occurrence, which allows passing down attributes down the use tree.
867 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
868 if (!VectorizeDef(node, it.Current(), /*generate_code*/ false)) {
869 return false; // failure to vectorize a left-hand-side
870 }
871 }
872
Aart Bik38a3f212017-10-20 17:02:21 -0700873 // Prepare alignment analysis:
874 // (1) find desired alignment (SIMD vector size in bytes).
875 // (2) initialize static loop peeling votes (peeling factor that will
876 // make one particular reference aligned), never to exceed (1).
877 // (3) variable to record how many references share same alignment.
878 // (4) variable to record suitable candidate for dynamic loop peeling.
879 uint32_t desired_alignment = GetVectorSizeInBytes();
880 DCHECK_LE(desired_alignment, 16u);
881 uint32_t peeling_votes[16] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
882 uint32_t max_num_same_alignment = 0;
883 const ArrayReference* peeling_candidate = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800884
885 // Data dependence analysis. Find each pair of references with same type, where
886 // at least one is a write. Each such pair denotes a possible data dependence.
887 // This analysis exploits the property that differently typed arrays cannot be
888 // aliased, as well as the property that references either point to the same
889 // array or to two completely disjoint arrays, i.e., no partial aliasing.
890 // Other than a few simply heuristics, no detailed subscript analysis is done.
Aart Bik38a3f212017-10-20 17:02:21 -0700891 // The scan over references also prepares finding a suitable alignment strategy.
Aart Bikf8f5a162017-02-06 15:35:29 -0800892 for (auto i = vector_refs_->begin(); i != vector_refs_->end(); ++i) {
Aart Bik38a3f212017-10-20 17:02:21 -0700893 uint32_t num_same_alignment = 0;
894 // Scan over all next references.
Aart Bikf8f5a162017-02-06 15:35:29 -0800895 for (auto j = i; ++j != vector_refs_->end(); ) {
896 if (i->type == j->type && (i->lhs || j->lhs)) {
897 // Found same-typed a[i+x] vs. b[i+y], where at least one is a write.
898 HInstruction* a = i->base;
899 HInstruction* b = j->base;
900 HInstruction* x = i->offset;
901 HInstruction* y = j->offset;
902 if (a == b) {
903 // Found a[i+x] vs. a[i+y]. Accept if x == y (loop-independent data dependence).
904 // Conservatively assume a loop-carried data dependence otherwise, and reject.
905 if (x != y) {
906 return false;
907 }
Aart Bik38a3f212017-10-20 17:02:21 -0700908 // Count the number of references that have the same alignment (since
909 // base and offset are the same) and where at least one is a write, so
910 // e.g. a[i] = a[i] + b[i] counts a[i] but not b[i]).
911 num_same_alignment++;
Aart Bikf8f5a162017-02-06 15:35:29 -0800912 } else {
913 // Found a[i+x] vs. b[i+y]. Accept if x == y (at worst loop-independent data dependence).
914 // Conservatively assume a potential loop-carried data dependence otherwise, avoided by
915 // generating an explicit a != b disambiguation runtime test on the two references.
916 if (x != y) {
Aart Bik37dc4df2017-06-28 14:08:00 -0700917 // To avoid excessive overhead, we only accept one a != b test.
918 if (vector_runtime_test_a_ == nullptr) {
919 // First test found.
920 vector_runtime_test_a_ = a;
921 vector_runtime_test_b_ = b;
922 } else if ((vector_runtime_test_a_ != a || vector_runtime_test_b_ != b) &&
923 (vector_runtime_test_a_ != b || vector_runtime_test_b_ != a)) {
924 return false; // second test would be needed
Aart Bikf8f5a162017-02-06 15:35:29 -0800925 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800926 }
927 }
928 }
929 }
Aart Bik38a3f212017-10-20 17:02:21 -0700930 // Update information for finding suitable alignment strategy:
931 // (1) update votes for static loop peeling,
932 // (2) update suitable candidate for dynamic loop peeling.
933 Alignment alignment = ComputeAlignment(i->offset, i->type, i->is_string_char_at);
934 if (alignment.Base() >= desired_alignment) {
935 // If the array/string object has a known, sufficient alignment, use the
936 // initial offset to compute the static loop peeling vote (this always
937 // works, since elements have natural alignment).
938 uint32_t offset = alignment.Offset() & (desired_alignment - 1u);
939 uint32_t vote = (offset == 0)
940 ? 0
941 : ((desired_alignment - offset) >> DataType::SizeShift(i->type));
942 DCHECK_LT(vote, 16u);
943 ++peeling_votes[vote];
944 } else if (BaseAlignment() >= desired_alignment &&
945 num_same_alignment > max_num_same_alignment) {
946 // Otherwise, if the array/string object has a known, sufficient alignment
947 // for just the base but with an unknown offset, record the candidate with
948 // the most occurrences for dynamic loop peeling (again, the peeling always
949 // works, since elements have natural alignment).
950 max_num_same_alignment = num_same_alignment;
951 peeling_candidate = &(*i);
952 }
953 } // for i
Aart Bikf8f5a162017-02-06 15:35:29 -0800954
Aart Bik38a3f212017-10-20 17:02:21 -0700955 // Find a suitable alignment strategy.
956 SetAlignmentStrategy(peeling_votes, peeling_candidate);
957
958 // Does vectorization seem profitable?
959 if (!IsVectorizationProfitable(trip_count)) {
960 return false;
961 }
Aart Bik14a68b42017-06-08 14:06:58 -0700962
Aart Bikf8f5a162017-02-06 15:35:29 -0800963 // Success!
964 return true;
965}
966
967void HLoopOptimization::Vectorize(LoopNode* node,
968 HBasicBlock* block,
969 HBasicBlock* exit,
970 int64_t trip_count) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800971 HBasicBlock* header = node->loop_info->GetHeader();
972 HBasicBlock* preheader = node->loop_info->GetPreHeader();
973
Aart Bik14a68b42017-06-08 14:06:58 -0700974 // Pick a loop unrolling factor for the vector loop.
Artem Serov121f2032017-10-23 19:19:06 +0100975 uint32_t unroll = arch_loop_helper_->GetSIMDUnrollingFactor(
976 block, trip_count, MaxNumberPeeled(), vector_length_);
Aart Bik14a68b42017-06-08 14:06:58 -0700977 uint32_t chunk = vector_length_ * unroll;
978
Aart Bik38a3f212017-10-20 17:02:21 -0700979 DCHECK(trip_count == 0 || (trip_count >= MaxNumberPeeled() + chunk));
980
Aart Bik14a68b42017-06-08 14:06:58 -0700981 // A cleanup loop is needed, at least, for any unknown trip count or
982 // for a known trip count with remainder iterations after vectorization.
Aart Bik38a3f212017-10-20 17:02:21 -0700983 bool needs_cleanup = trip_count == 0 ||
984 ((trip_count - vector_static_peeling_factor_) % chunk) != 0;
Aart Bikf8f5a162017-02-06 15:35:29 -0800985
986 // Adjust vector bookkeeping.
Aart Bikb29f6842017-07-28 15:58:41 -0700987 HPhi* main_phi = nullptr;
988 bool is_simple_loop_header = TrySetSimpleLoopHeader(header, &main_phi); // refills sets
Aart Bikf8f5a162017-02-06 15:35:29 -0800989 DCHECK(is_simple_loop_header);
Aart Bik14a68b42017-06-08 14:06:58 -0700990 vector_header_ = header;
991 vector_body_ = block;
Aart Bikf8f5a162017-02-06 15:35:29 -0800992
Aart Bikdbbac8f2017-09-01 13:06:08 -0700993 // Loop induction type.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100994 DataType::Type induc_type = main_phi->GetType();
995 DCHECK(induc_type == DataType::Type::kInt32 || induc_type == DataType::Type::kInt64)
996 << induc_type;
Aart Bikdbbac8f2017-09-01 13:06:08 -0700997
Aart Bik38a3f212017-10-20 17:02:21 -0700998 // Generate the trip count for static or dynamic loop peeling, if needed:
999 // ptc = <peeling factor>;
Aart Bik14a68b42017-06-08 14:06:58 -07001000 HInstruction* ptc = nullptr;
Aart Bik38a3f212017-10-20 17:02:21 -07001001 if (vector_static_peeling_factor_ != 0) {
1002 // Static loop peeling for SIMD alignment (using the most suitable
1003 // fixed peeling factor found during prior alignment analysis).
1004 DCHECK(vector_dynamic_peeling_candidate_ == nullptr);
1005 ptc = graph_->GetConstant(induc_type, vector_static_peeling_factor_);
1006 } else if (vector_dynamic_peeling_candidate_ != nullptr) {
1007 // Dynamic loop peeling for SIMD alignment (using the most suitable
1008 // candidate found during prior alignment analysis):
1009 // rem = offset % ALIGN; // adjusted as #elements
1010 // ptc = rem == 0 ? 0 : (ALIGN - rem);
1011 uint32_t shift = DataType::SizeShift(vector_dynamic_peeling_candidate_->type);
1012 uint32_t align = GetVectorSizeInBytes() >> shift;
1013 uint32_t hidden_offset = HiddenOffset(vector_dynamic_peeling_candidate_->type,
1014 vector_dynamic_peeling_candidate_->is_string_char_at);
1015 HInstruction* adjusted_offset = graph_->GetConstant(induc_type, hidden_offset >> shift);
1016 HInstruction* offset = Insert(preheader, new (global_allocator_) HAdd(
1017 induc_type, vector_dynamic_peeling_candidate_->offset, adjusted_offset));
1018 HInstruction* rem = Insert(preheader, new (global_allocator_) HAnd(
1019 induc_type, offset, graph_->GetConstant(induc_type, align - 1u)));
1020 HInstruction* sub = Insert(preheader, new (global_allocator_) HSub(
1021 induc_type, graph_->GetConstant(induc_type, align), rem));
1022 HInstruction* cond = Insert(preheader, new (global_allocator_) HEqual(
1023 rem, graph_->GetConstant(induc_type, 0)));
1024 ptc = Insert(preheader, new (global_allocator_) HSelect(
1025 cond, graph_->GetConstant(induc_type, 0), sub, kNoDexPc));
1026 needs_cleanup = true; // don't know the exact amount
Aart Bik14a68b42017-06-08 14:06:58 -07001027 }
1028
1029 // Generate loop control:
Aart Bikf8f5a162017-02-06 15:35:29 -08001030 // stc = <trip-count>;
Aart Bik38a3f212017-10-20 17:02:21 -07001031 // ptc = min(stc, ptc);
Aart Bik14a68b42017-06-08 14:06:58 -07001032 // vtc = stc - (stc - ptc) % chunk;
1033 // i = 0;
Aart Bikf8f5a162017-02-06 15:35:29 -08001034 HInstruction* stc = induction_range_.GenerateTripCount(node->loop_info, graph_, preheader);
1035 HInstruction* vtc = stc;
1036 if (needs_cleanup) {
Aart Bik14a68b42017-06-08 14:06:58 -07001037 DCHECK(IsPowerOfTwo(chunk));
1038 HInstruction* diff = stc;
1039 if (ptc != nullptr) {
Aart Bik38a3f212017-10-20 17:02:21 -07001040 if (trip_count == 0) {
1041 HInstruction* cond = Insert(preheader, new (global_allocator_) HAboveOrEqual(stc, ptc));
1042 ptc = Insert(preheader, new (global_allocator_) HSelect(cond, ptc, stc, kNoDexPc));
1043 }
Aart Bik14a68b42017-06-08 14:06:58 -07001044 diff = Insert(preheader, new (global_allocator_) HSub(induc_type, stc, ptc));
1045 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001046 HInstruction* rem = Insert(
1047 preheader, new (global_allocator_) HAnd(induc_type,
Aart Bik14a68b42017-06-08 14:06:58 -07001048 diff,
Aart Bikdbbac8f2017-09-01 13:06:08 -07001049 graph_->GetConstant(induc_type, chunk - 1)));
Aart Bikf8f5a162017-02-06 15:35:29 -08001050 vtc = Insert(preheader, new (global_allocator_) HSub(induc_type, stc, rem));
1051 }
Aart Bikdbbac8f2017-09-01 13:06:08 -07001052 vector_index_ = graph_->GetConstant(induc_type, 0);
Aart Bikf8f5a162017-02-06 15:35:29 -08001053
1054 // Generate runtime disambiguation test:
1055 // vtc = a != b ? vtc : 0;
1056 if (vector_runtime_test_a_ != nullptr) {
1057 HInstruction* rt = Insert(
1058 preheader,
1059 new (global_allocator_) HNotEqual(vector_runtime_test_a_, vector_runtime_test_b_));
1060 vtc = Insert(preheader,
Aart Bikdbbac8f2017-09-01 13:06:08 -07001061 new (global_allocator_)
1062 HSelect(rt, vtc, graph_->GetConstant(induc_type, 0), kNoDexPc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001063 needs_cleanup = true;
1064 }
1065
Aart Bik38a3f212017-10-20 17:02:21 -07001066 // Generate alignment peeling loop, if needed:
Aart Bik14a68b42017-06-08 14:06:58 -07001067 // for ( ; i < ptc; i += 1)
1068 // <loop-body>
Aart Bik38a3f212017-10-20 17:02:21 -07001069 //
1070 // NOTE: The alignment forced by the peeling loop is preserved even if data is
1071 // moved around during suspend checks, since all analysis was based on
1072 // nothing more than the Android runtime alignment conventions.
Aart Bik14a68b42017-06-08 14:06:58 -07001073 if (ptc != nullptr) {
1074 vector_mode_ = kSequential;
1075 GenerateNewLoop(node,
1076 block,
1077 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
1078 vector_index_,
1079 ptc,
Aart Bikdbbac8f2017-09-01 13:06:08 -07001080 graph_->GetConstant(induc_type, 1),
Aart Bik521b50f2017-09-09 10:44:45 -07001081 kNoUnrollingFactor);
Aart Bik14a68b42017-06-08 14:06:58 -07001082 }
1083
1084 // Generate vector loop, possibly further unrolled:
1085 // for ( ; i < vtc; i += chunk)
Aart Bikf8f5a162017-02-06 15:35:29 -08001086 // <vectorized-loop-body>
1087 vector_mode_ = kVector;
1088 GenerateNewLoop(node,
1089 block,
Aart Bik14a68b42017-06-08 14:06:58 -07001090 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
1091 vector_index_,
Aart Bikf8f5a162017-02-06 15:35:29 -08001092 vtc,
Aart Bikdbbac8f2017-09-01 13:06:08 -07001093 graph_->GetConstant(induc_type, vector_length_), // increment per unroll
Aart Bik14a68b42017-06-08 14:06:58 -07001094 unroll);
Aart Bikf8f5a162017-02-06 15:35:29 -08001095 HLoopInformation* vloop = vector_header_->GetLoopInformation();
1096
1097 // Generate cleanup loop, if needed:
1098 // for ( ; i < stc; i += 1)
1099 // <loop-body>
1100 if (needs_cleanup) {
1101 vector_mode_ = kSequential;
1102 GenerateNewLoop(node,
1103 block,
1104 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
Aart Bik14a68b42017-06-08 14:06:58 -07001105 vector_index_,
Aart Bikf8f5a162017-02-06 15:35:29 -08001106 stc,
Aart Bikdbbac8f2017-09-01 13:06:08 -07001107 graph_->GetConstant(induc_type, 1),
Aart Bik521b50f2017-09-09 10:44:45 -07001108 kNoUnrollingFactor);
Aart Bikf8f5a162017-02-06 15:35:29 -08001109 }
1110
Aart Bik0148de42017-09-05 09:25:01 -07001111 // Link reductions to their final uses.
1112 for (auto i = reductions_->begin(); i != reductions_->end(); ++i) {
1113 if (i->first->IsPhi()) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001114 HInstruction* phi = i->first;
1115 HInstruction* repl = ReduceAndExtractIfNeeded(i->second);
1116 // Deal with regular uses.
1117 for (const HUseListNode<HInstruction*>& use : phi->GetUses()) {
1118 induction_range_.Replace(use.GetUser(), phi, repl); // update induction use
1119 }
1120 phi->ReplaceWith(repl);
Aart Bik0148de42017-09-05 09:25:01 -07001121 }
1122 }
1123
Aart Bikf8f5a162017-02-06 15:35:29 -08001124 // Remove the original loop by disconnecting the body block
1125 // and removing all instructions from the header.
1126 block->DisconnectAndDelete();
1127 while (!header->GetFirstInstruction()->IsGoto()) {
1128 header->RemoveInstruction(header->GetFirstInstruction());
1129 }
Aart Bikb29f6842017-07-28 15:58:41 -07001130
Aart Bik14a68b42017-06-08 14:06:58 -07001131 // Update loop hierarchy: the old header now resides in the same outer loop
1132 // as the old preheader. Note that we don't bother putting sequential
1133 // loops back in the hierarchy at this point.
Aart Bikf8f5a162017-02-06 15:35:29 -08001134 header->SetLoopInformation(preheader->GetLoopInformation()); // outward
1135 node->loop_info = vloop;
1136}
1137
1138void HLoopOptimization::GenerateNewLoop(LoopNode* node,
1139 HBasicBlock* block,
1140 HBasicBlock* new_preheader,
1141 HInstruction* lo,
1142 HInstruction* hi,
Aart Bik14a68b42017-06-08 14:06:58 -07001143 HInstruction* step,
1144 uint32_t unroll) {
1145 DCHECK(unroll == 1 || vector_mode_ == kVector);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001146 DataType::Type induc_type = lo->GetType();
Aart Bikf8f5a162017-02-06 15:35:29 -08001147 // Prepare new loop.
Aart Bikf8f5a162017-02-06 15:35:29 -08001148 vector_preheader_ = new_preheader,
1149 vector_header_ = vector_preheader_->GetSingleSuccessor();
1150 vector_body_ = vector_header_->GetSuccessors()[1];
Aart Bik14a68b42017-06-08 14:06:58 -07001151 HPhi* phi = new (global_allocator_) HPhi(global_allocator_,
1152 kNoRegNumber,
1153 0,
1154 HPhi::ToPhiType(induc_type));
Aart Bikb07d1bc2017-04-05 10:03:15 -07001155 // Generate header and prepare body.
Aart Bikf8f5a162017-02-06 15:35:29 -08001156 // for (i = lo; i < hi; i += step)
1157 // <loop-body>
Aart Bik14a68b42017-06-08 14:06:58 -07001158 HInstruction* cond = new (global_allocator_) HAboveOrEqual(phi, hi);
1159 vector_header_->AddPhi(phi);
Aart Bikf8f5a162017-02-06 15:35:29 -08001160 vector_header_->AddInstruction(cond);
1161 vector_header_->AddInstruction(new (global_allocator_) HIf(cond));
Aart Bik14a68b42017-06-08 14:06:58 -07001162 vector_index_ = phi;
Aart Bik0148de42017-09-05 09:25:01 -07001163 vector_permanent_map_->clear(); // preserved over unrolling
Aart Bik14a68b42017-06-08 14:06:58 -07001164 for (uint32_t u = 0; u < unroll; u++) {
Aart Bik14a68b42017-06-08 14:06:58 -07001165 // Generate instruction map.
Aart Bik0148de42017-09-05 09:25:01 -07001166 vector_map_->clear();
Aart Bik14a68b42017-06-08 14:06:58 -07001167 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
1168 bool vectorized_def = VectorizeDef(node, it.Current(), /*generate_code*/ true);
1169 DCHECK(vectorized_def);
1170 }
1171 // Generate body from the instruction map, but in original program order.
1172 HEnvironment* env = vector_header_->GetFirstInstruction()->GetEnvironment();
1173 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
1174 auto i = vector_map_->find(it.Current());
1175 if (i != vector_map_->end() && !i->second->IsInBlock()) {
1176 Insert(vector_body_, i->second);
1177 // Deal with instructions that need an environment, such as the scalar intrinsics.
1178 if (i->second->NeedsEnvironment()) {
1179 i->second->CopyEnvironmentFromWithLoopPhiAdjustment(env, vector_header_);
1180 }
1181 }
1182 }
Aart Bik0148de42017-09-05 09:25:01 -07001183 // Generate the induction.
Aart Bik14a68b42017-06-08 14:06:58 -07001184 vector_index_ = new (global_allocator_) HAdd(induc_type, vector_index_, step);
1185 Insert(vector_body_, vector_index_);
Aart Bikf8f5a162017-02-06 15:35:29 -08001186 }
Aart Bik0148de42017-09-05 09:25:01 -07001187 // Finalize phi inputs for the reductions (if any).
1188 for (auto i = reductions_->begin(); i != reductions_->end(); ++i) {
1189 if (!i->first->IsPhi()) {
1190 DCHECK(i->second->IsPhi());
1191 GenerateVecReductionPhiInputs(i->second->AsPhi(), i->first);
1192 }
1193 }
Aart Bikb29f6842017-07-28 15:58:41 -07001194 // Finalize phi inputs for the loop index.
Aart Bik14a68b42017-06-08 14:06:58 -07001195 phi->AddInput(lo);
1196 phi->AddInput(vector_index_);
1197 vector_index_ = phi;
Aart Bikf8f5a162017-02-06 15:35:29 -08001198}
1199
Aart Bikf8f5a162017-02-06 15:35:29 -08001200bool HLoopOptimization::VectorizeDef(LoopNode* node,
1201 HInstruction* instruction,
1202 bool generate_code) {
1203 // Accept a left-hand-side array base[index] for
1204 // (1) supported vector type,
1205 // (2) loop-invariant base,
1206 // (3) unit stride index,
1207 // (4) vectorizable right-hand-side value.
1208 uint64_t restrictions = kNone;
1209 if (instruction->IsArraySet()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001210 DataType::Type type = instruction->AsArraySet()->GetComponentType();
Aart Bikf8f5a162017-02-06 15:35:29 -08001211 HInstruction* base = instruction->InputAt(0);
1212 HInstruction* index = instruction->InputAt(1);
1213 HInstruction* value = instruction->InputAt(2);
1214 HInstruction* offset = nullptr;
1215 if (TrySetVectorType(type, &restrictions) &&
1216 node->loop_info->IsDefinedOutOfTheLoop(base) &&
Aart Bik37dc4df2017-06-28 14:08:00 -07001217 induction_range_.IsUnitStride(instruction, index, graph_, &offset) &&
Aart Bikf8f5a162017-02-06 15:35:29 -08001218 VectorizeUse(node, value, generate_code, type, restrictions)) {
1219 if (generate_code) {
1220 GenerateVecSub(index, offset);
Aart Bik14a68b42017-06-08 14:06:58 -07001221 GenerateVecMem(instruction, vector_map_->Get(index), vector_map_->Get(value), offset, type);
Aart Bikf8f5a162017-02-06 15:35:29 -08001222 } else {
1223 vector_refs_->insert(ArrayReference(base, offset, type, /*lhs*/ true));
1224 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08001225 return true;
1226 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001227 return false;
1228 }
Aart Bik0148de42017-09-05 09:25:01 -07001229 // Accept a left-hand-side reduction for
1230 // (1) supported vector type,
1231 // (2) vectorizable right-hand-side value.
1232 auto redit = reductions_->find(instruction);
1233 if (redit != reductions_->end()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001234 DataType::Type type = instruction->GetType();
Aart Bikdbbac8f2017-09-01 13:06:08 -07001235 // Recognize SAD idiom or direct reduction.
1236 if (VectorizeSADIdiom(node, instruction, generate_code, type, restrictions) ||
1237 (TrySetVectorType(type, &restrictions) &&
1238 VectorizeUse(node, instruction, generate_code, type, restrictions))) {
Aart Bik0148de42017-09-05 09:25:01 -07001239 if (generate_code) {
1240 HInstruction* new_red = vector_map_->Get(instruction);
1241 vector_permanent_map_->Put(new_red, vector_map_->Get(redit->second));
1242 vector_permanent_map_->Overwrite(redit->second, new_red);
1243 }
1244 return true;
1245 }
1246 return false;
1247 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001248 // Branch back okay.
1249 if (instruction->IsGoto()) {
1250 return true;
1251 }
1252 // Otherwise accept only expressions with no effects outside the immediate loop-body.
1253 // Note that actual uses are inspected during right-hand-side tree traversal.
1254 return !IsUsedOutsideLoop(node->loop_info, instruction) && !instruction->DoesAnyWrite();
1255}
1256
Aart Bikf8f5a162017-02-06 15:35:29 -08001257bool HLoopOptimization::VectorizeUse(LoopNode* node,
1258 HInstruction* instruction,
1259 bool generate_code,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001260 DataType::Type type,
Aart Bikf8f5a162017-02-06 15:35:29 -08001261 uint64_t restrictions) {
1262 // Accept anything for which code has already been generated.
1263 if (generate_code) {
1264 if (vector_map_->find(instruction) != vector_map_->end()) {
1265 return true;
1266 }
1267 }
1268 // Continue the right-hand-side tree traversal, passing in proper
1269 // types and vector restrictions along the way. During code generation,
1270 // all new nodes are drawn from the global allocator.
1271 if (node->loop_info->IsDefinedOutOfTheLoop(instruction)) {
1272 // Accept invariant use, using scalar expansion.
1273 if (generate_code) {
1274 GenerateVecInv(instruction, type);
1275 }
1276 return true;
1277 } else if (instruction->IsArrayGet()) {
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001278 // Deal with vector restrictions.
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001279 bool is_string_char_at = instruction->AsArrayGet()->IsStringCharAt();
1280 if (is_string_char_at && HasVectorRestrictions(restrictions, kNoStringCharAt)) {
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001281 return false;
1282 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001283 // Accept a right-hand-side array base[index] for
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001284 // (1) matching vector type (exact match or signed/unsigned integral type of the same size),
Aart Bikf8f5a162017-02-06 15:35:29 -08001285 // (2) loop-invariant base,
1286 // (3) unit stride index,
1287 // (4) vectorizable right-hand-side value.
1288 HInstruction* base = instruction->InputAt(0);
1289 HInstruction* index = instruction->InputAt(1);
1290 HInstruction* offset = nullptr;
Aart Bik46b6dbc2017-10-03 11:37:37 -07001291 if (HVecOperation::ToSignedType(type) == HVecOperation::ToSignedType(instruction->GetType()) &&
Aart Bikf8f5a162017-02-06 15:35:29 -08001292 node->loop_info->IsDefinedOutOfTheLoop(base) &&
Aart Bik37dc4df2017-06-28 14:08:00 -07001293 induction_range_.IsUnitStride(instruction, index, graph_, &offset)) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001294 if (generate_code) {
1295 GenerateVecSub(index, offset);
Aart Bik14a68b42017-06-08 14:06:58 -07001296 GenerateVecMem(instruction, vector_map_->Get(index), nullptr, offset, type);
Aart Bikf8f5a162017-02-06 15:35:29 -08001297 } else {
Aart Bik38a3f212017-10-20 17:02:21 -07001298 vector_refs_->insert(ArrayReference(base, offset, type, /*lhs*/ false, is_string_char_at));
Aart Bikf8f5a162017-02-06 15:35:29 -08001299 }
1300 return true;
1301 }
Aart Bik0148de42017-09-05 09:25:01 -07001302 } else if (instruction->IsPhi()) {
1303 // Accept particular phi operations.
1304 if (reductions_->find(instruction) != reductions_->end()) {
1305 // Deal with vector restrictions.
1306 if (HasVectorRestrictions(restrictions, kNoReduction)) {
1307 return false;
1308 }
1309 // Accept a reduction.
1310 if (generate_code) {
1311 GenerateVecReductionPhi(instruction->AsPhi());
1312 }
1313 return true;
1314 }
1315 // TODO: accept right-hand-side induction?
1316 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001317 } else if (instruction->IsTypeConversion()) {
1318 // Accept particular type conversions.
1319 HTypeConversion* conversion = instruction->AsTypeConversion();
1320 HInstruction* opa = conversion->InputAt(0);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001321 DataType::Type from = conversion->GetInputType();
1322 DataType::Type to = conversion->GetResultType();
1323 if (DataType::IsIntegralType(from) && DataType::IsIntegralType(to)) {
Aart Bik38a3f212017-10-20 17:02:21 -07001324 uint32_t size_vec = DataType::Size(type);
1325 uint32_t size_from = DataType::Size(from);
1326 uint32_t size_to = DataType::Size(to);
Aart Bikdbbac8f2017-09-01 13:06:08 -07001327 // Accept an integral conversion
1328 // (1a) narrowing into vector type, "wider" operations cannot bring in higher order bits, or
1329 // (1b) widening from at least vector type, and
1330 // (2) vectorizable operand.
1331 if ((size_to < size_from &&
1332 size_to == size_vec &&
1333 VectorizeUse(node, opa, generate_code, type, restrictions | kNoHiBits)) ||
1334 (size_to >= size_from &&
1335 size_from >= size_vec &&
Aart Bik4d1a9d42017-10-19 14:40:55 -07001336 VectorizeUse(node, opa, generate_code, type, restrictions))) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001337 if (generate_code) {
1338 if (vector_mode_ == kVector) {
1339 vector_map_->Put(instruction, vector_map_->Get(opa)); // operand pass-through
1340 } else {
1341 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1342 }
1343 }
1344 return true;
1345 }
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001346 } else if (to == DataType::Type::kFloat32 && from == DataType::Type::kInt32) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001347 DCHECK_EQ(to, type);
1348 // Accept int to float conversion for
1349 // (1) supported int,
1350 // (2) vectorizable operand.
1351 if (TrySetVectorType(from, &restrictions) &&
1352 VectorizeUse(node, opa, generate_code, from, restrictions)) {
1353 if (generate_code) {
1354 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1355 }
1356 return true;
1357 }
1358 }
1359 return false;
1360 } else if (instruction->IsNeg() || instruction->IsNot() || instruction->IsBooleanNot()) {
1361 // Accept unary operator for vectorizable operand.
1362 HInstruction* opa = instruction->InputAt(0);
1363 if (VectorizeUse(node, opa, generate_code, type, restrictions)) {
1364 if (generate_code) {
1365 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1366 }
1367 return true;
1368 }
1369 } else if (instruction->IsAdd() || instruction->IsSub() ||
1370 instruction->IsMul() || instruction->IsDiv() ||
1371 instruction->IsAnd() || instruction->IsOr() || instruction->IsXor()) {
1372 // Deal with vector restrictions.
1373 if ((instruction->IsMul() && HasVectorRestrictions(restrictions, kNoMul)) ||
1374 (instruction->IsDiv() && HasVectorRestrictions(restrictions, kNoDiv))) {
1375 return false;
1376 }
1377 // Accept binary operator for vectorizable operands.
1378 HInstruction* opa = instruction->InputAt(0);
1379 HInstruction* opb = instruction->InputAt(1);
1380 if (VectorizeUse(node, opa, generate_code, type, restrictions) &&
1381 VectorizeUse(node, opb, generate_code, type, restrictions)) {
1382 if (generate_code) {
1383 GenerateVecOp(instruction, vector_map_->Get(opa), vector_map_->Get(opb), type);
1384 }
1385 return true;
1386 }
1387 } else if (instruction->IsShl() || instruction->IsShr() || instruction->IsUShr()) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001388 // Recognize halving add idiom.
Aart Bikf3e61ee2017-04-12 17:09:20 -07001389 if (VectorizeHalvingAddIdiom(node, instruction, generate_code, type, restrictions)) {
1390 return true;
1391 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001392 // Deal with vector restrictions.
Aart Bik304c8a52017-05-23 11:01:13 -07001393 HInstruction* opa = instruction->InputAt(0);
1394 HInstruction* opb = instruction->InputAt(1);
1395 HInstruction* r = opa;
1396 bool is_unsigned = false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001397 if ((HasVectorRestrictions(restrictions, kNoShift)) ||
1398 (instruction->IsShr() && HasVectorRestrictions(restrictions, kNoShr))) {
1399 return false; // unsupported instruction
Aart Bik304c8a52017-05-23 11:01:13 -07001400 } else if (HasVectorRestrictions(restrictions, kNoHiBits)) {
1401 // Shifts right need extra care to account for higher order bits.
1402 // TODO: less likely shr/unsigned and ushr/signed can by flipping signess.
1403 if (instruction->IsShr() &&
1404 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || is_unsigned)) {
1405 return false; // reject, unless all operands are sign-extension narrower
1406 } else if (instruction->IsUShr() &&
1407 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || !is_unsigned)) {
1408 return false; // reject, unless all operands are zero-extension narrower
1409 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001410 }
1411 // Accept shift operator for vectorizable/invariant operands.
1412 // TODO: accept symbolic, albeit loop invariant shift factors.
Aart Bik304c8a52017-05-23 11:01:13 -07001413 DCHECK(r != nullptr);
1414 if (generate_code && vector_mode_ != kVector) { // de-idiom
1415 r = opa;
1416 }
Aart Bik50e20d52017-05-05 14:07:29 -07001417 int64_t distance = 0;
Aart Bik304c8a52017-05-23 11:01:13 -07001418 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
Aart Bik50e20d52017-05-05 14:07:29 -07001419 IsInt64AndGet(opb, /*out*/ &distance)) {
Aart Bik65ffd8e2017-05-01 16:50:45 -07001420 // Restrict shift distance to packed data type width.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001421 int64_t max_distance = DataType::Size(type) * 8;
Aart Bik65ffd8e2017-05-01 16:50:45 -07001422 if (0 <= distance && distance < max_distance) {
1423 if (generate_code) {
Aart Bik304c8a52017-05-23 11:01:13 -07001424 GenerateVecOp(instruction, vector_map_->Get(r), opb, type);
Aart Bik65ffd8e2017-05-01 16:50:45 -07001425 }
1426 return true;
Aart Bikf8f5a162017-02-06 15:35:29 -08001427 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001428 }
Aart Bik3b2a5952018-03-05 13:55:28 -08001429 } else if (instruction->IsAbs()) {
1430 // Deal with vector restrictions.
1431 HInstruction* opa = instruction->InputAt(0);
1432 HInstruction* r = opa;
1433 bool is_unsigned = false;
1434 if (HasVectorRestrictions(restrictions, kNoAbs)) {
1435 return false;
1436 } else if (HasVectorRestrictions(restrictions, kNoHiBits) &&
1437 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || is_unsigned)) {
1438 return false; // reject, unless operand is sign-extension narrower
1439 }
1440 // Accept ABS(x) for vectorizable operand.
1441 DCHECK(r != nullptr);
1442 if (generate_code && vector_mode_ != kVector) { // de-idiom
1443 r = opa;
1444 }
1445 if (VectorizeUse(node, r, generate_code, type, restrictions)) {
1446 if (generate_code) {
1447 GenerateVecOp(instruction,
1448 vector_map_->Get(r),
1449 nullptr,
1450 HVecOperation::ToProperType(type, is_unsigned));
1451 }
1452 return true;
1453 }
Aart Bik1f8d51b2018-02-15 10:42:37 -08001454 } else if (instruction->IsMin() || instruction->IsMax()) {
Aart Bik29aa0822018-03-08 11:28:00 -08001455 // Recognize saturation arithmetic.
1456 if (VectorizeSaturationIdiom(node, instruction, generate_code, type, restrictions)) {
1457 return true;
1458 }
Aart Bik1f8d51b2018-02-15 10:42:37 -08001459 // Deal with vector restrictions.
1460 HInstruction* opa = instruction->InputAt(0);
1461 HInstruction* opb = instruction->InputAt(1);
1462 HInstruction* r = opa;
1463 HInstruction* s = opb;
1464 bool is_unsigned = false;
1465 if (HasVectorRestrictions(restrictions, kNoMinMax)) {
1466 return false;
1467 } else if (HasVectorRestrictions(restrictions, kNoHiBits) &&
1468 !IsNarrowerOperands(opa, opb, type, &r, &s, &is_unsigned)) {
1469 return false; // reject, unless all operands are same-extension narrower
1470 }
1471 // Accept MIN/MAX(x, y) for vectorizable operands.
1472 DCHECK(r != nullptr);
1473 DCHECK(s != nullptr);
1474 if (generate_code && vector_mode_ != kVector) { // de-idiom
1475 r = opa;
1476 s = opb;
1477 }
1478 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
1479 VectorizeUse(node, s, generate_code, type, restrictions)) {
1480 if (generate_code) {
1481 GenerateVecOp(
1482 instruction, vector_map_->Get(r), vector_map_->Get(s), type, is_unsigned);
Aart Bikc8e93c72017-05-10 10:49:22 -07001483 }
Aart Bik1f8d51b2018-02-15 10:42:37 -08001484 return true;
1485 }
Aart Bik281c6812016-08-26 11:31:48 -07001486 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08001487 return false;
Aart Bik281c6812016-08-26 11:31:48 -07001488}
1489
Aart Bik38a3f212017-10-20 17:02:21 -07001490uint32_t HLoopOptimization::GetVectorSizeInBytes() {
1491 switch (compiler_driver_->GetInstructionSet()) {
Vladimir Marko33bff252017-11-01 14:35:42 +00001492 case InstructionSet::kArm:
1493 case InstructionSet::kThumb2:
Aart Bik38a3f212017-10-20 17:02:21 -07001494 return 8; // 64-bit SIMD
1495 default:
1496 return 16; // 128-bit SIMD
1497 }
1498}
1499
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001500bool HLoopOptimization::TrySetVectorType(DataType::Type type, uint64_t* restrictions) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001501 const InstructionSetFeatures* features = compiler_driver_->GetInstructionSetFeatures();
1502 switch (compiler_driver_->GetInstructionSet()) {
Vladimir Marko33bff252017-11-01 14:35:42 +00001503 case InstructionSet::kArm:
1504 case InstructionSet::kThumb2:
Artem Serov8f7c4102017-06-21 11:21:37 +01001505 // Allow vectorization for all ARM devices, because Android assumes that
Aart Bikb29f6842017-07-28 15:58:41 -07001506 // ARM 32-bit always supports advanced SIMD (64-bit SIMD).
Artem Serov8f7c4102017-06-21 11:21:37 +01001507 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001508 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001509 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001510 case DataType::Type::kInt8:
Aart Bik0148de42017-09-05 09:25:01 -07001511 *restrictions |= kNoDiv | kNoReduction;
Artem Serov8f7c4102017-06-21 11:21:37 +01001512 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001513 case DataType::Type::kUint16:
1514 case DataType::Type::kInt16:
Aart Bik0148de42017-09-05 09:25:01 -07001515 *restrictions |= kNoDiv | kNoStringCharAt | kNoReduction;
Artem Serov8f7c4102017-06-21 11:21:37 +01001516 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001517 case DataType::Type::kInt32:
Artem Serov6e9b1372017-10-05 16:48:30 +01001518 *restrictions |= kNoDiv | kNoWideSAD;
Artem Serov8f7c4102017-06-21 11:21:37 +01001519 return TrySetVectorLength(2);
1520 default:
1521 break;
1522 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001523 return false;
Vladimir Marko33bff252017-11-01 14:35:42 +00001524 case InstructionSet::kArm64:
Aart Bikf8f5a162017-02-06 15:35:29 -08001525 // Allow vectorization for all ARM devices, because Android assumes that
Aart Bikb29f6842017-07-28 15:58:41 -07001526 // ARMv8 AArch64 always supports advanced SIMD (128-bit SIMD).
Aart Bikf8f5a162017-02-06 15:35:29 -08001527 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001528 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001529 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001530 case DataType::Type::kInt8:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001531 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +01001532 return TrySetVectorLength(16);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001533 case DataType::Type::kUint16:
1534 case DataType::Type::kInt16:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001535 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +01001536 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001537 case DataType::Type::kInt32:
Aart Bikf8f5a162017-02-06 15:35:29 -08001538 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +01001539 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001540 case DataType::Type::kInt64:
Aart Bikc8e93c72017-05-10 10:49:22 -07001541 *restrictions |= kNoDiv | kNoMul | kNoMinMax;
Aart Bikf8f5a162017-02-06 15:35:29 -08001542 return TrySetVectorLength(2);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001543 case DataType::Type::kFloat32:
Aart Bik0148de42017-09-05 09:25:01 -07001544 *restrictions |= kNoReduction;
Artem Serovd4bccf12017-04-03 18:47:32 +01001545 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001546 case DataType::Type::kFloat64:
Aart Bik0148de42017-09-05 09:25:01 -07001547 *restrictions |= kNoReduction;
Aart Bikf8f5a162017-02-06 15:35:29 -08001548 return TrySetVectorLength(2);
1549 default:
1550 return false;
1551 }
Vladimir Marko33bff252017-11-01 14:35:42 +00001552 case InstructionSet::kX86:
1553 case InstructionSet::kX86_64:
Aart Bikb29f6842017-07-28 15:58:41 -07001554 // Allow vectorization for SSE4.1-enabled X86 devices only (128-bit SIMD).
Aart Bikf8f5a162017-02-06 15:35:29 -08001555 if (features->AsX86InstructionSetFeatures()->HasSSE4_1()) {
1556 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001557 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001558 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001559 case DataType::Type::kInt8:
Aart Bik0148de42017-09-05 09:25:01 -07001560 *restrictions |=
Aart Bikdbbac8f2017-09-01 13:06:08 -07001561 kNoMul | kNoDiv | kNoShift | kNoAbs | kNoSignedHAdd | kNoUnroundedHAdd | kNoSAD;
Aart Bikf8f5a162017-02-06 15:35:29 -08001562 return TrySetVectorLength(16);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001563 case DataType::Type::kUint16:
1564 case DataType::Type::kInt16:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001565 *restrictions |= kNoDiv | kNoAbs | kNoSignedHAdd | kNoUnroundedHAdd | kNoSAD;
Aart Bikf8f5a162017-02-06 15:35:29 -08001566 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001567 case DataType::Type::kInt32:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001568 *restrictions |= kNoDiv | kNoSAD;
Aart Bikf8f5a162017-02-06 15:35:29 -08001569 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001570 case DataType::Type::kInt64:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001571 *restrictions |= kNoMul | kNoDiv | kNoShr | kNoAbs | kNoMinMax | kNoSAD;
Aart Bikf8f5a162017-02-06 15:35:29 -08001572 return TrySetVectorLength(2);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001573 case DataType::Type::kFloat32:
Aart Bik0148de42017-09-05 09:25:01 -07001574 *restrictions |= kNoMinMax | kNoReduction; // minmax: -0.0 vs +0.0
Aart Bikf8f5a162017-02-06 15:35:29 -08001575 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001576 case DataType::Type::kFloat64:
Aart Bik0148de42017-09-05 09:25:01 -07001577 *restrictions |= kNoMinMax | kNoReduction; // minmax: -0.0 vs +0.0
Aart Bikf8f5a162017-02-06 15:35:29 -08001578 return TrySetVectorLength(2);
1579 default:
1580 break;
1581 } // switch type
1582 }
1583 return false;
Vladimir Marko33bff252017-11-01 14:35:42 +00001584 case InstructionSet::kMips:
Lena Djokic51765b02017-06-22 13:49:59 +02001585 if (features->AsMipsInstructionSetFeatures()->HasMsa()) {
1586 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001587 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001588 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001589 case DataType::Type::kInt8:
Aart Bik29aa0822018-03-08 11:28:00 -08001590 *restrictions |= kNoDiv | kNoSaturation;
Lena Djokic51765b02017-06-22 13:49:59 +02001591 return TrySetVectorLength(16);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001592 case DataType::Type::kUint16:
1593 case DataType::Type::kInt16:
Aart Bik29aa0822018-03-08 11:28:00 -08001594 *restrictions |= kNoDiv | kNoSaturation | kNoStringCharAt;
Lena Djokic51765b02017-06-22 13:49:59 +02001595 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001596 case DataType::Type::kInt32:
Lena Djokic38e380b2017-10-30 16:17:10 +01001597 *restrictions |= kNoDiv;
Lena Djokic51765b02017-06-22 13:49:59 +02001598 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001599 case DataType::Type::kInt64:
Lena Djokic38e380b2017-10-30 16:17:10 +01001600 *restrictions |= kNoDiv;
Lena Djokic51765b02017-06-22 13:49:59 +02001601 return TrySetVectorLength(2);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001602 case DataType::Type::kFloat32:
Aart Bik0148de42017-09-05 09:25:01 -07001603 *restrictions |= kNoMinMax | kNoReduction; // min/max(x, NaN)
Lena Djokic51765b02017-06-22 13:49:59 +02001604 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001605 case DataType::Type::kFloat64:
Aart Bik0148de42017-09-05 09:25:01 -07001606 *restrictions |= kNoMinMax | kNoReduction; // min/max(x, NaN)
Lena Djokic51765b02017-06-22 13:49:59 +02001607 return TrySetVectorLength(2);
1608 default:
1609 break;
1610 } // switch type
1611 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001612 return false;
Vladimir Marko33bff252017-11-01 14:35:42 +00001613 case InstructionSet::kMips64:
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001614 if (features->AsMips64InstructionSetFeatures()->HasMsa()) {
1615 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001616 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001617 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001618 case DataType::Type::kInt8:
Aart Bik29aa0822018-03-08 11:28:00 -08001619 *restrictions |= kNoDiv | kNoSaturation;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001620 return TrySetVectorLength(16);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001621 case DataType::Type::kUint16:
1622 case DataType::Type::kInt16:
Aart Bik29aa0822018-03-08 11:28:00 -08001623 *restrictions |= kNoDiv | kNoSaturation | kNoStringCharAt;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001624 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001625 case DataType::Type::kInt32:
Lena Djokic38e380b2017-10-30 16:17:10 +01001626 *restrictions |= kNoDiv;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001627 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001628 case DataType::Type::kInt64:
Lena Djokic38e380b2017-10-30 16:17:10 +01001629 *restrictions |= kNoDiv;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001630 return TrySetVectorLength(2);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001631 case DataType::Type::kFloat32:
Aart Bik0148de42017-09-05 09:25:01 -07001632 *restrictions |= kNoMinMax | kNoReduction; // min/max(x, NaN)
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001633 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001634 case DataType::Type::kFloat64:
Aart Bik0148de42017-09-05 09:25:01 -07001635 *restrictions |= kNoMinMax | kNoReduction; // min/max(x, NaN)
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001636 return TrySetVectorLength(2);
1637 default:
1638 break;
1639 } // switch type
1640 }
1641 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001642 default:
1643 return false;
1644 } // switch instruction set
1645}
1646
1647bool HLoopOptimization::TrySetVectorLength(uint32_t length) {
1648 DCHECK(IsPowerOfTwo(length) && length >= 2u);
1649 // First time set?
1650 if (vector_length_ == 0) {
1651 vector_length_ = length;
1652 }
1653 // Different types are acceptable within a loop-body, as long as all the corresponding vector
1654 // lengths match exactly to obtain a uniform traversal through the vector iteration space
1655 // (idiomatic exceptions to this rule can be handled by further unrolling sub-expressions).
1656 return vector_length_ == length;
1657}
1658
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001659void HLoopOptimization::GenerateVecInv(HInstruction* org, DataType::Type type) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001660 if (vector_map_->find(org) == vector_map_->end()) {
1661 // In scalar code, just use a self pass-through for scalar invariants
1662 // (viz. expression remains itself).
1663 if (vector_mode_ == kSequential) {
1664 vector_map_->Put(org, org);
1665 return;
1666 }
1667 // In vector code, explicit scalar expansion is needed.
Aart Bik0148de42017-09-05 09:25:01 -07001668 HInstruction* vector = nullptr;
1669 auto it = vector_permanent_map_->find(org);
1670 if (it != vector_permanent_map_->end()) {
1671 vector = it->second; // reuse during unrolling
1672 } else {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001673 // Generates ReplicateScalar( (optional_type_conv) org ).
1674 HInstruction* input = org;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001675 DataType::Type input_type = input->GetType();
1676 if (type != input_type && (type == DataType::Type::kInt64 ||
1677 input_type == DataType::Type::kInt64)) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001678 input = Insert(vector_preheader_,
1679 new (global_allocator_) HTypeConversion(type, input, kNoDexPc));
1680 }
1681 vector = new (global_allocator_)
Aart Bik46b6dbc2017-10-03 11:37:37 -07001682 HVecReplicateScalar(global_allocator_, input, type, vector_length_, kNoDexPc);
Aart Bik0148de42017-09-05 09:25:01 -07001683 vector_permanent_map_->Put(org, Insert(vector_preheader_, vector));
1684 }
1685 vector_map_->Put(org, vector);
Aart Bikf8f5a162017-02-06 15:35:29 -08001686 }
1687}
1688
1689void HLoopOptimization::GenerateVecSub(HInstruction* org, HInstruction* offset) {
1690 if (vector_map_->find(org) == vector_map_->end()) {
Aart Bik14a68b42017-06-08 14:06:58 -07001691 HInstruction* subscript = vector_index_;
Aart Bik37dc4df2017-06-28 14:08:00 -07001692 int64_t value = 0;
1693 if (!IsInt64AndGet(offset, &value) || value != 0) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001694 subscript = new (global_allocator_) HAdd(DataType::Type::kInt32, subscript, offset);
Aart Bikf8f5a162017-02-06 15:35:29 -08001695 if (org->IsPhi()) {
1696 Insert(vector_body_, subscript); // lacks layout placeholder
1697 }
1698 }
1699 vector_map_->Put(org, subscript);
1700 }
1701}
1702
1703void HLoopOptimization::GenerateVecMem(HInstruction* org,
1704 HInstruction* opa,
1705 HInstruction* opb,
Aart Bik14a68b42017-06-08 14:06:58 -07001706 HInstruction* offset,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001707 DataType::Type type) {
Aart Bik46b6dbc2017-10-03 11:37:37 -07001708 uint32_t dex_pc = org->GetDexPc();
Aart Bikf8f5a162017-02-06 15:35:29 -08001709 HInstruction* vector = nullptr;
1710 if (vector_mode_ == kVector) {
1711 // Vector store or load.
Aart Bik38a3f212017-10-20 17:02:21 -07001712 bool is_string_char_at = false;
Aart Bik14a68b42017-06-08 14:06:58 -07001713 HInstruction* base = org->InputAt(0);
Aart Bikf8f5a162017-02-06 15:35:29 -08001714 if (opb != nullptr) {
1715 vector = new (global_allocator_) HVecStore(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001716 global_allocator_, base, opa, opb, type, org->GetSideEffects(), vector_length_, dex_pc);
Aart Bikf8f5a162017-02-06 15:35:29 -08001717 } else {
Aart Bik38a3f212017-10-20 17:02:21 -07001718 is_string_char_at = org->AsArrayGet()->IsStringCharAt();
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001719 vector = new (global_allocator_) HVecLoad(global_allocator_,
1720 base,
1721 opa,
1722 type,
1723 org->GetSideEffects(),
1724 vector_length_,
Aart Bik46b6dbc2017-10-03 11:37:37 -07001725 is_string_char_at,
1726 dex_pc);
Aart Bik14a68b42017-06-08 14:06:58 -07001727 }
Aart Bik38a3f212017-10-20 17:02:21 -07001728 // Known (forced/adjusted/original) alignment?
1729 if (vector_dynamic_peeling_candidate_ != nullptr) {
1730 if (vector_dynamic_peeling_candidate_->offset == offset && // TODO: diffs too?
1731 DataType::Size(vector_dynamic_peeling_candidate_->type) == DataType::Size(type) &&
1732 vector_dynamic_peeling_candidate_->is_string_char_at == is_string_char_at) {
1733 vector->AsVecMemoryOperation()->SetAlignment( // forced
1734 Alignment(GetVectorSizeInBytes(), 0));
1735 }
1736 } else {
1737 vector->AsVecMemoryOperation()->SetAlignment( // adjusted/original
1738 ComputeAlignment(offset, type, is_string_char_at, vector_static_peeling_factor_));
Aart Bikf8f5a162017-02-06 15:35:29 -08001739 }
1740 } else {
1741 // Scalar store or load.
1742 DCHECK(vector_mode_ == kSequential);
1743 if (opb != nullptr) {
Aart Bik4d1a9d42017-10-19 14:40:55 -07001744 DataType::Type component_type = org->AsArraySet()->GetComponentType();
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001745 vector = new (global_allocator_) HArraySet(
Aart Bik4d1a9d42017-10-19 14:40:55 -07001746 org->InputAt(0), opa, opb, component_type, org->GetSideEffects(), dex_pc);
Aart Bikf8f5a162017-02-06 15:35:29 -08001747 } else {
Aart Bikdb14fcf2017-04-25 15:53:58 -07001748 bool is_string_char_at = org->AsArrayGet()->IsStringCharAt();
1749 vector = new (global_allocator_) HArrayGet(
Aart Bik4d1a9d42017-10-19 14:40:55 -07001750 org->InputAt(0), opa, org->GetType(), org->GetSideEffects(), dex_pc, is_string_char_at);
Aart Bikf8f5a162017-02-06 15:35:29 -08001751 }
1752 }
1753 vector_map_->Put(org, vector);
1754}
1755
Aart Bik0148de42017-09-05 09:25:01 -07001756void HLoopOptimization::GenerateVecReductionPhi(HPhi* phi) {
1757 DCHECK(reductions_->find(phi) != reductions_->end());
1758 DCHECK(reductions_->Get(phi->InputAt(1)) == phi);
1759 HInstruction* vector = nullptr;
1760 if (vector_mode_ == kSequential) {
1761 HPhi* new_phi = new (global_allocator_) HPhi(
1762 global_allocator_, kNoRegNumber, 0, phi->GetType());
1763 vector_header_->AddPhi(new_phi);
1764 vector = new_phi;
1765 } else {
1766 // Link vector reduction back to prior unrolled update, or a first phi.
1767 auto it = vector_permanent_map_->find(phi);
1768 if (it != vector_permanent_map_->end()) {
1769 vector = it->second;
1770 } else {
1771 HPhi* new_phi = new (global_allocator_) HPhi(
1772 global_allocator_, kNoRegNumber, 0, HVecOperation::kSIMDType);
1773 vector_header_->AddPhi(new_phi);
1774 vector = new_phi;
1775 }
1776 }
1777 vector_map_->Put(phi, vector);
1778}
1779
1780void HLoopOptimization::GenerateVecReductionPhiInputs(HPhi* phi, HInstruction* reduction) {
1781 HInstruction* new_phi = vector_map_->Get(phi);
1782 HInstruction* new_init = reductions_->Get(phi);
1783 HInstruction* new_red = vector_map_->Get(reduction);
1784 // Link unrolled vector loop back to new phi.
1785 for (; !new_phi->IsPhi(); new_phi = vector_permanent_map_->Get(new_phi)) {
1786 DCHECK(new_phi->IsVecOperation());
1787 }
1788 // Prepare the new initialization.
1789 if (vector_mode_ == kVector) {
Goran Jakovljevic89b8df02017-10-13 08:33:17 +02001790 // Generate a [initial, 0, .., 0] vector for add or
1791 // a [initial, initial, .., initial] vector for min/max.
Aart Bikdbbac8f2017-09-01 13:06:08 -07001792 HVecOperation* red_vector = new_red->AsVecOperation();
Goran Jakovljevic89b8df02017-10-13 08:33:17 +02001793 HVecReduce::ReductionKind kind = GetReductionKind(red_vector);
Aart Bik38a3f212017-10-20 17:02:21 -07001794 uint32_t vector_length = red_vector->GetVectorLength();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001795 DataType::Type type = red_vector->GetPackedType();
Goran Jakovljevic89b8df02017-10-13 08:33:17 +02001796 if (kind == HVecReduce::ReductionKind::kSum) {
1797 new_init = Insert(vector_preheader_,
1798 new (global_allocator_) HVecSetScalars(global_allocator_,
1799 &new_init,
1800 type,
1801 vector_length,
1802 1,
1803 kNoDexPc));
1804 } else {
1805 new_init = Insert(vector_preheader_,
1806 new (global_allocator_) HVecReplicateScalar(global_allocator_,
1807 new_init,
1808 type,
1809 vector_length,
1810 kNoDexPc));
1811 }
Aart Bik0148de42017-09-05 09:25:01 -07001812 } else {
1813 new_init = ReduceAndExtractIfNeeded(new_init);
1814 }
1815 // Set the phi inputs.
1816 DCHECK(new_phi->IsPhi());
1817 new_phi->AsPhi()->AddInput(new_init);
1818 new_phi->AsPhi()->AddInput(new_red);
1819 // New feed value for next phi (safe mutation in iteration).
1820 reductions_->find(phi)->second = new_phi;
1821}
1822
1823HInstruction* HLoopOptimization::ReduceAndExtractIfNeeded(HInstruction* instruction) {
1824 if (instruction->IsPhi()) {
1825 HInstruction* input = instruction->InputAt(1);
Aart Bik2dd7b672017-12-07 11:11:22 -08001826 if (HVecOperation::ReturnsSIMDValue(input)) {
1827 DCHECK(!input->IsPhi());
Aart Bikdbbac8f2017-09-01 13:06:08 -07001828 HVecOperation* input_vector = input->AsVecOperation();
Aart Bik38a3f212017-10-20 17:02:21 -07001829 uint32_t vector_length = input_vector->GetVectorLength();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001830 DataType::Type type = input_vector->GetPackedType();
Aart Bikdbbac8f2017-09-01 13:06:08 -07001831 HVecReduce::ReductionKind kind = GetReductionKind(input_vector);
Aart Bik0148de42017-09-05 09:25:01 -07001832 HBasicBlock* exit = instruction->GetBlock()->GetSuccessors()[0];
1833 // Generate a vector reduction and scalar extract
1834 // x = REDUCE( [x_1, .., x_n] )
1835 // y = x_1
1836 // along the exit of the defining loop.
Aart Bik0148de42017-09-05 09:25:01 -07001837 HInstruction* reduce = new (global_allocator_) HVecReduce(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001838 global_allocator_, instruction, type, vector_length, kind, kNoDexPc);
Aart Bik0148de42017-09-05 09:25:01 -07001839 exit->InsertInstructionBefore(reduce, exit->GetFirstInstruction());
1840 instruction = new (global_allocator_) HVecExtractScalar(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001841 global_allocator_, reduce, type, vector_length, 0, kNoDexPc);
Aart Bik0148de42017-09-05 09:25:01 -07001842 exit->InsertInstructionAfter(instruction, reduce);
1843 }
1844 }
1845 return instruction;
1846}
1847
Aart Bikf8f5a162017-02-06 15:35:29 -08001848#define GENERATE_VEC(x, y) \
1849 if (vector_mode_ == kVector) { \
1850 vector = (x); \
1851 } else { \
1852 DCHECK(vector_mode_ == kSequential); \
1853 vector = (y); \
1854 } \
1855 break;
1856
1857void HLoopOptimization::GenerateVecOp(HInstruction* org,
1858 HInstruction* opa,
1859 HInstruction* opb,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001860 DataType::Type type,
Aart Bik304c8a52017-05-23 11:01:13 -07001861 bool is_unsigned) {
Aart Bik46b6dbc2017-10-03 11:37:37 -07001862 uint32_t dex_pc = org->GetDexPc();
Aart Bikf8f5a162017-02-06 15:35:29 -08001863 HInstruction* vector = nullptr;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001864 DataType::Type org_type = org->GetType();
Aart Bikf8f5a162017-02-06 15:35:29 -08001865 switch (org->GetKind()) {
1866 case HInstruction::kNeg:
1867 DCHECK(opb == nullptr);
1868 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001869 new (global_allocator_) HVecNeg(global_allocator_, opa, type, vector_length_, dex_pc),
1870 new (global_allocator_) HNeg(org_type, opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001871 case HInstruction::kNot:
1872 DCHECK(opb == nullptr);
1873 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001874 new (global_allocator_) HVecNot(global_allocator_, opa, type, vector_length_, dex_pc),
1875 new (global_allocator_) HNot(org_type, opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001876 case HInstruction::kBooleanNot:
1877 DCHECK(opb == nullptr);
1878 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001879 new (global_allocator_) HVecNot(global_allocator_, opa, type, vector_length_, dex_pc),
1880 new (global_allocator_) HBooleanNot(opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001881 case HInstruction::kTypeConversion:
1882 DCHECK(opb == nullptr);
1883 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001884 new (global_allocator_) HVecCnv(global_allocator_, opa, type, vector_length_, dex_pc),
1885 new (global_allocator_) HTypeConversion(org_type, opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001886 case HInstruction::kAdd:
1887 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001888 new (global_allocator_) HVecAdd(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1889 new (global_allocator_) HAdd(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001890 case HInstruction::kSub:
1891 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001892 new (global_allocator_) HVecSub(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1893 new (global_allocator_) HSub(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001894 case HInstruction::kMul:
1895 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001896 new (global_allocator_) HVecMul(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1897 new (global_allocator_) HMul(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001898 case HInstruction::kDiv:
1899 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001900 new (global_allocator_) HVecDiv(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1901 new (global_allocator_) HDiv(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001902 case HInstruction::kAnd:
1903 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001904 new (global_allocator_) HVecAnd(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1905 new (global_allocator_) HAnd(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001906 case HInstruction::kOr:
1907 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001908 new (global_allocator_) HVecOr(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1909 new (global_allocator_) HOr(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001910 case HInstruction::kXor:
1911 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001912 new (global_allocator_) HVecXor(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1913 new (global_allocator_) HXor(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001914 case HInstruction::kShl:
1915 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001916 new (global_allocator_) HVecShl(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1917 new (global_allocator_) HShl(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001918 case HInstruction::kShr:
1919 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001920 new (global_allocator_) HVecShr(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1921 new (global_allocator_) HShr(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001922 case HInstruction::kUShr:
1923 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001924 new (global_allocator_) HVecUShr(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1925 new (global_allocator_) HUShr(org_type, opa, opb, dex_pc));
Aart Bik1f8d51b2018-02-15 10:42:37 -08001926 case HInstruction::kMin:
1927 GENERATE_VEC(
1928 new (global_allocator_) HVecMin(global_allocator_,
1929 opa,
1930 opb,
1931 HVecOperation::ToProperType(type, is_unsigned),
1932 vector_length_,
1933 dex_pc),
1934 new (global_allocator_) HMin(org_type, opa, opb, dex_pc));
1935 case HInstruction::kMax:
1936 GENERATE_VEC(
1937 new (global_allocator_) HVecMax(global_allocator_,
1938 opa,
1939 opb,
1940 HVecOperation::ToProperType(type, is_unsigned),
1941 vector_length_,
1942 dex_pc),
1943 new (global_allocator_) HMax(org_type, opa, opb, dex_pc));
Aart Bik3b2a5952018-03-05 13:55:28 -08001944 case HInstruction::kAbs:
1945 DCHECK(opb == nullptr);
1946 GENERATE_VEC(
1947 new (global_allocator_) HVecAbs(global_allocator_, opa, type, vector_length_, dex_pc),
1948 new (global_allocator_) HAbs(org_type, opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001949 default:
1950 break;
1951 } // switch
1952 CHECK(vector != nullptr) << "Unsupported SIMD operator";
1953 vector_map_->Put(org, vector);
1954}
1955
1956#undef GENERATE_VEC
1957
1958//
Aart Bikf3e61ee2017-04-12 17:09:20 -07001959// Vectorization idioms.
1960//
1961
Aart Bik29aa0822018-03-08 11:28:00 -08001962// Method recognizes single and double clipping saturation arithmetic.
1963bool HLoopOptimization::VectorizeSaturationIdiom(LoopNode* node,
1964 HInstruction* instruction,
1965 bool generate_code,
1966 DataType::Type type,
1967 uint64_t restrictions) {
1968 // Deal with vector restrictions.
1969 if (HasVectorRestrictions(restrictions, kNoSaturation)) {
1970 return false;
1971 }
Aart Bik1a381022018-03-15 15:51:37 -07001972 // Restrict type (generalize if one day we generalize allowed MIN/MAX integral types).
1973 if (instruction->GetType() != DataType::Type::kInt32 &&
1974 instruction->GetType() != DataType::Type::kInt64) {
Aart Bik29aa0822018-03-08 11:28:00 -08001975 return false;
1976 }
Aart Bik29aa0822018-03-08 11:28:00 -08001977 // Clipped addition or subtraction?
Aart Bik1a381022018-03-15 15:51:37 -07001978 int64_t lo = std::numeric_limits<int64_t>::min();
1979 int64_t hi = std::numeric_limits<int64_t>::max();
1980 HInstruction* clippee = FindClippee(instruction, &lo, &hi);
Aart Bik29aa0822018-03-08 11:28:00 -08001981 bool is_add = true;
1982 if (clippee->IsAdd()) {
1983 is_add = true;
1984 } else if (clippee->IsSub()) {
1985 is_add = false;
1986 } else {
1987 return false; // clippee is not add/sub
1988 }
1989 // Addition or subtraction on narrower operands?
1990 HInstruction* r = nullptr;
1991 HInstruction* s = nullptr;
1992 bool is_unsigned = false;
1993 if (IsNarrowerOperands(clippee->InputAt(0), clippee->InputAt(1), type, &r, &s, &is_unsigned) &&
1994 (is_add ? IsSaturatedAdd(type, lo, hi, is_unsigned)
1995 : IsSaturatedSub(type, lo, hi, is_unsigned))) {
1996 DCHECK(r != nullptr);
1997 DCHECK(s != nullptr);
1998 } else {
1999 return false;
2000 }
2001 // Accept saturation idiom for vectorizable operands.
2002 if (generate_code && vector_mode_ != kVector) { // de-idiom
2003 r = instruction->InputAt(0);
2004 s = instruction->InputAt(1);
2005 restrictions &= ~(kNoHiBits | kNoMinMax); // allow narrow MIN/MAX in seq
2006 }
2007 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
2008 VectorizeUse(node, s, generate_code, type, restrictions)) {
2009 if (generate_code) {
2010 if (vector_mode_ == kVector) {
2011 DataType::Type vtype = HVecOperation::ToProperType(type, is_unsigned);
2012 HInstruction* op1 = vector_map_->Get(r);
2013 HInstruction* op2 = vector_map_->Get(s);
2014 vector_map_->Put(instruction, is_add
2015 ? reinterpret_cast<HInstruction*>(new (global_allocator_) HVecSaturationAdd(
2016 global_allocator_, op1, op2, vtype, vector_length_, kNoDexPc))
2017 : reinterpret_cast<HInstruction*>(new (global_allocator_) HVecSaturationSub(
2018 global_allocator_, op1, op2, vtype, vector_length_, kNoDexPc)));
2019 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorizedIdiom);
2020 } else {
2021 GenerateVecOp(instruction, vector_map_->Get(r), vector_map_->Get(s), type);
2022 }
2023 }
2024 return true;
2025 }
2026 return false;
2027}
2028
Aart Bikf3e61ee2017-04-12 17:09:20 -07002029// Method recognizes the following idioms:
Aart Bikdbbac8f2017-09-01 13:06:08 -07002030// rounding halving add (a + b + 1) >> 1 for unsigned/signed operands a, b
2031// truncated halving add (a + b) >> 1 for unsigned/signed operands a, b
Aart Bikf3e61ee2017-04-12 17:09:20 -07002032// Provided that the operands are promoted to a wider form to do the arithmetic and
2033// then cast back to narrower form, the idioms can be mapped into efficient SIMD
2034// implementation that operates directly in narrower form (plus one extra bit).
2035// TODO: current version recognizes implicit byte/short/char widening only;
2036// explicit widening from int to long could be added later.
2037bool HLoopOptimization::VectorizeHalvingAddIdiom(LoopNode* node,
2038 HInstruction* instruction,
2039 bool generate_code,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002040 DataType::Type type,
Aart Bikf3e61ee2017-04-12 17:09:20 -07002041 uint64_t restrictions) {
2042 // Test for top level arithmetic shift right x >> 1 or logical shift right x >>> 1
Aart Bik304c8a52017-05-23 11:01:13 -07002043 // (note whether the sign bit in wider precision is shifted in has no effect
Aart Bikf3e61ee2017-04-12 17:09:20 -07002044 // on the narrow precision computed by the idiom).
Aart Bikf3e61ee2017-04-12 17:09:20 -07002045 if ((instruction->IsShr() ||
2046 instruction->IsUShr()) &&
Aart Bik0148de42017-09-05 09:25:01 -07002047 IsInt64Value(instruction->InputAt(1), 1)) {
Aart Bik5f805002017-05-16 16:42:41 -07002048 // Test for (a + b + c) >> 1 for optional constant c.
2049 HInstruction* a = nullptr;
2050 HInstruction* b = nullptr;
2051 int64_t c = 0;
2052 if (IsAddConst(instruction->InputAt(0), /*out*/ &a, /*out*/ &b, /*out*/ &c)) {
Aart Bik304c8a52017-05-23 11:01:13 -07002053 DCHECK(a != nullptr && b != nullptr);
Aart Bik5f805002017-05-16 16:42:41 -07002054 // Accept c == 1 (rounded) or c == 0 (not rounded).
2055 bool is_rounded = false;
2056 if (c == 1) {
2057 is_rounded = true;
2058 } else if (c != 0) {
2059 return false;
2060 }
2061 // Accept consistent zero or sign extension on operands a and b.
Aart Bikf3e61ee2017-04-12 17:09:20 -07002062 HInstruction* r = nullptr;
2063 HInstruction* s = nullptr;
2064 bool is_unsigned = false;
Aart Bik304c8a52017-05-23 11:01:13 -07002065 if (!IsNarrowerOperands(a, b, type, &r, &s, &is_unsigned)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -07002066 return false;
2067 }
2068 // Deal with vector restrictions.
2069 if ((!is_unsigned && HasVectorRestrictions(restrictions, kNoSignedHAdd)) ||
2070 (!is_rounded && HasVectorRestrictions(restrictions, kNoUnroundedHAdd))) {
2071 return false;
2072 }
2073 // Accept recognized halving add for vectorizable operands. Vectorized code uses the
2074 // shorthand idiomatic operation. Sequential code uses the original scalar expressions.
Aart Bikdbbac8f2017-09-01 13:06:08 -07002075 DCHECK(r != nullptr);
2076 DCHECK(s != nullptr);
Aart Bik304c8a52017-05-23 11:01:13 -07002077 if (generate_code && vector_mode_ != kVector) { // de-idiom
2078 r = instruction->InputAt(0);
2079 s = instruction->InputAt(1);
2080 }
Aart Bikf3e61ee2017-04-12 17:09:20 -07002081 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
2082 VectorizeUse(node, s, generate_code, type, restrictions)) {
2083 if (generate_code) {
2084 if (vector_mode_ == kVector) {
2085 vector_map_->Put(instruction, new (global_allocator_) HVecHalvingAdd(
2086 global_allocator_,
2087 vector_map_->Get(r),
2088 vector_map_->Get(s),
Aart Bik66c158e2018-01-31 12:55:04 -08002089 HVecOperation::ToProperType(type, is_unsigned),
Aart Bikf3e61ee2017-04-12 17:09:20 -07002090 vector_length_,
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01002091 is_rounded,
Aart Bik46b6dbc2017-10-03 11:37:37 -07002092 kNoDexPc));
Aart Bik21b85922017-09-06 13:29:16 -07002093 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorizedIdiom);
Aart Bikf3e61ee2017-04-12 17:09:20 -07002094 } else {
Aart Bik304c8a52017-05-23 11:01:13 -07002095 GenerateVecOp(instruction, vector_map_->Get(r), vector_map_->Get(s), type);
Aart Bikf3e61ee2017-04-12 17:09:20 -07002096 }
2097 }
2098 return true;
2099 }
2100 }
2101 }
2102 return false;
2103}
2104
Aart Bikdbbac8f2017-09-01 13:06:08 -07002105// Method recognizes the following idiom:
2106// q += ABS(a - b) for signed operands a, b
2107// Provided that the operands have the same type or are promoted to a wider form.
2108// Since this may involve a vector length change, the idiom is handled by going directly
2109// to a sad-accumulate node (rather than relying combining finer grained nodes later).
2110// TODO: unsigned SAD too?
2111bool HLoopOptimization::VectorizeSADIdiom(LoopNode* node,
2112 HInstruction* instruction,
2113 bool generate_code,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002114 DataType::Type reduction_type,
Aart Bikdbbac8f2017-09-01 13:06:08 -07002115 uint64_t restrictions) {
2116 // Filter integral "q += ABS(a - b);" reduction, where ABS and SUB
2117 // are done in the same precision (either int or long).
2118 if (!instruction->IsAdd() ||
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002119 (reduction_type != DataType::Type::kInt32 && reduction_type != DataType::Type::kInt64)) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07002120 return false;
2121 }
2122 HInstruction* q = instruction->InputAt(0);
2123 HInstruction* v = instruction->InputAt(1);
2124 HInstruction* a = nullptr;
2125 HInstruction* b = nullptr;
Aart Bik3b2a5952018-03-05 13:55:28 -08002126 if (v->GetType() == reduction_type && v->IsAbs()) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07002127 HInstruction* x = v->InputAt(0);
Aart Bikdf011c32017-09-28 12:53:04 -07002128 if (x->GetType() == reduction_type) {
2129 int64_t c = 0;
2130 if (x->IsSub()) {
2131 a = x->InputAt(0);
2132 b = x->InputAt(1);
2133 } else if (IsAddConst(x, /*out*/ &a, /*out*/ &c)) {
2134 b = graph_->GetConstant(reduction_type, -c); // hidden SUB!
2135 }
Aart Bikdbbac8f2017-09-01 13:06:08 -07002136 }
2137 }
2138 if (a == nullptr || b == nullptr) {
2139 return false;
2140 }
2141 // Accept same-type or consistent sign extension for narrower-type on operands a and b.
2142 // The same-type or narrower operands are called r (a or lower) and s (b or lower).
Aart Bikdf011c32017-09-28 12:53:04 -07002143 // We inspect the operands carefully to pick the most suited type.
Aart Bikdbbac8f2017-09-01 13:06:08 -07002144 HInstruction* r = a;
2145 HInstruction* s = b;
2146 bool is_unsigned = false;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002147 DataType::Type sub_type = a->GetType();
Aart Bikdf011c32017-09-28 12:53:04 -07002148 if (DataType::Size(b->GetType()) < DataType::Size(sub_type)) {
2149 sub_type = b->GetType();
2150 }
2151 if (a->IsTypeConversion() &&
2152 DataType::Size(a->InputAt(0)->GetType()) < DataType::Size(sub_type)) {
2153 sub_type = a->InputAt(0)->GetType();
2154 }
2155 if (b->IsTypeConversion() &&
2156 DataType::Size(b->InputAt(0)->GetType()) < DataType::Size(sub_type)) {
2157 sub_type = b->InputAt(0)->GetType();
Aart Bikdbbac8f2017-09-01 13:06:08 -07002158 }
2159 if (reduction_type != sub_type &&
2160 (!IsNarrowerOperands(a, b, sub_type, &r, &s, &is_unsigned) || is_unsigned)) {
2161 return false;
2162 }
2163 // Try same/narrower type and deal with vector restrictions.
Artem Serov6e9b1372017-10-05 16:48:30 +01002164 if (!TrySetVectorType(sub_type, &restrictions) ||
2165 HasVectorRestrictions(restrictions, kNoSAD) ||
2166 (reduction_type != sub_type && HasVectorRestrictions(restrictions, kNoWideSAD))) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07002167 return false;
2168 }
2169 // Accept SAD idiom for vectorizable operands. Vectorized code uses the shorthand
2170 // idiomatic operation. Sequential code uses the original scalar expressions.
2171 DCHECK(r != nullptr);
2172 DCHECK(s != nullptr);
2173 if (generate_code && vector_mode_ != kVector) { // de-idiom
2174 r = s = v->InputAt(0);
2175 }
2176 if (VectorizeUse(node, q, generate_code, sub_type, restrictions) &&
2177 VectorizeUse(node, r, generate_code, sub_type, restrictions) &&
2178 VectorizeUse(node, s, generate_code, sub_type, restrictions)) {
2179 if (generate_code) {
2180 if (vector_mode_ == kVector) {
2181 vector_map_->Put(instruction, new (global_allocator_) HVecSADAccumulate(
2182 global_allocator_,
2183 vector_map_->Get(q),
2184 vector_map_->Get(r),
2185 vector_map_->Get(s),
Aart Bik3b2a5952018-03-05 13:55:28 -08002186 HVecOperation::ToProperType(reduction_type, is_unsigned),
Aart Bik46b6dbc2017-10-03 11:37:37 -07002187 GetOtherVL(reduction_type, sub_type, vector_length_),
2188 kNoDexPc));
Aart Bikdbbac8f2017-09-01 13:06:08 -07002189 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorizedIdiom);
2190 } else {
2191 GenerateVecOp(v, vector_map_->Get(r), nullptr, reduction_type);
2192 GenerateVecOp(instruction, vector_map_->Get(q), vector_map_->Get(v), reduction_type);
2193 }
2194 }
2195 return true;
2196 }
2197 return false;
2198}
2199
Aart Bikf3e61ee2017-04-12 17:09:20 -07002200//
Aart Bik14a68b42017-06-08 14:06:58 -07002201// Vectorization heuristics.
2202//
2203
Aart Bik38a3f212017-10-20 17:02:21 -07002204Alignment HLoopOptimization::ComputeAlignment(HInstruction* offset,
2205 DataType::Type type,
2206 bool is_string_char_at,
2207 uint32_t peeling) {
2208 // Combine the alignment and hidden offset that is guaranteed by
2209 // the Android runtime with a known starting index adjusted as bytes.
2210 int64_t value = 0;
2211 if (IsInt64AndGet(offset, /*out*/ &value)) {
2212 uint32_t start_offset =
2213 HiddenOffset(type, is_string_char_at) + (value + peeling) * DataType::Size(type);
2214 return Alignment(BaseAlignment(), start_offset & (BaseAlignment() - 1u));
2215 }
2216 // Otherwise, the Android runtime guarantees at least natural alignment.
2217 return Alignment(DataType::Size(type), 0);
2218}
2219
2220void HLoopOptimization::SetAlignmentStrategy(uint32_t peeling_votes[],
2221 const ArrayReference* peeling_candidate) {
2222 // Current heuristic: pick the best static loop peeling factor, if any,
2223 // or otherwise use dynamic loop peeling on suggested peeling candidate.
2224 uint32_t max_vote = 0;
2225 for (int32_t i = 0; i < 16; i++) {
2226 if (peeling_votes[i] > max_vote) {
2227 max_vote = peeling_votes[i];
2228 vector_static_peeling_factor_ = i;
2229 }
2230 }
2231 if (max_vote == 0) {
2232 vector_dynamic_peeling_candidate_ = peeling_candidate;
2233 }
2234}
2235
2236uint32_t HLoopOptimization::MaxNumberPeeled() {
2237 if (vector_dynamic_peeling_candidate_ != nullptr) {
2238 return vector_length_ - 1u; // worst-case
2239 }
2240 return vector_static_peeling_factor_; // known exactly
2241}
2242
Aart Bik14a68b42017-06-08 14:06:58 -07002243bool HLoopOptimization::IsVectorizationProfitable(int64_t trip_count) {
Aart Bik38a3f212017-10-20 17:02:21 -07002244 // Current heuristic: non-empty body with sufficient number of iterations (if known).
Aart Bik14a68b42017-06-08 14:06:58 -07002245 // TODO: refine by looking at e.g. operation count, alignment, etc.
Aart Bik38a3f212017-10-20 17:02:21 -07002246 // TODO: trip count is really unsigned entity, provided the guarding test
2247 // is satisfied; deal with this more carefully later
2248 uint32_t max_peel = MaxNumberPeeled();
Aart Bik14a68b42017-06-08 14:06:58 -07002249 if (vector_length_ == 0) {
2250 return false; // nothing found
Aart Bik38a3f212017-10-20 17:02:21 -07002251 } else if (trip_count < 0) {
2252 return false; // guard against non-taken/large
2253 } else if ((0 < trip_count) && (trip_count < (vector_length_ + max_peel))) {
Aart Bik14a68b42017-06-08 14:06:58 -07002254 return false; // insufficient iterations
2255 }
2256 return true;
2257}
2258
Aart Bik14a68b42017-06-08 14:06:58 -07002259//
Aart Bikf8f5a162017-02-06 15:35:29 -08002260// Helpers.
2261//
2262
2263bool HLoopOptimization::TrySetPhiInduction(HPhi* phi, bool restrict_uses) {
Aart Bikb29f6842017-07-28 15:58:41 -07002264 // Start with empty phi induction.
2265 iset_->clear();
2266
Nicolas Geoffrayf57c1ae2017-06-28 17:40:18 +01002267 // Special case Phis that have equivalent in a debuggable setup. Our graph checker isn't
2268 // smart enough to follow strongly connected components (and it's probably not worth
2269 // it to make it so). See b/33775412.
2270 if (graph_->IsDebuggable() && phi->HasEquivalentPhi()) {
2271 return false;
2272 }
Aart Bikb29f6842017-07-28 15:58:41 -07002273
2274 // Lookup phi induction cycle.
Aart Bikcc42be02016-10-20 16:14:16 -07002275 ArenaSet<HInstruction*>* set = induction_range_.LookupCycle(phi);
2276 if (set != nullptr) {
2277 for (HInstruction* i : *set) {
Aart Bike3dedc52016-11-02 17:50:27 -07002278 // Check that, other than instructions that are no longer in the graph (removed earlier)
Aart Bikf8f5a162017-02-06 15:35:29 -08002279 // each instruction is removable and, when restrict uses are requested, other than for phi,
2280 // all uses are contained within the cycle.
Aart Bike3dedc52016-11-02 17:50:27 -07002281 if (!i->IsInBlock()) {
2282 continue;
2283 } else if (!i->IsRemovable()) {
2284 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08002285 } else if (i != phi && restrict_uses) {
Aart Bikb29f6842017-07-28 15:58:41 -07002286 // Deal with regular uses.
Aart Bikcc42be02016-10-20 16:14:16 -07002287 for (const HUseListNode<HInstruction*>& use : i->GetUses()) {
2288 if (set->find(use.GetUser()) == set->end()) {
2289 return false;
2290 }
2291 }
2292 }
Aart Bike3dedc52016-11-02 17:50:27 -07002293 iset_->insert(i); // copy
Aart Bikcc42be02016-10-20 16:14:16 -07002294 }
Aart Bikcc42be02016-10-20 16:14:16 -07002295 return true;
2296 }
2297 return false;
2298}
2299
Aart Bikb29f6842017-07-28 15:58:41 -07002300bool HLoopOptimization::TrySetPhiReduction(HPhi* phi) {
Aart Bikcc42be02016-10-20 16:14:16 -07002301 DCHECK(iset_->empty());
Aart Bikb29f6842017-07-28 15:58:41 -07002302 // Only unclassified phi cycles are candidates for reductions.
2303 if (induction_range_.IsClassified(phi)) {
2304 return false;
2305 }
2306 // Accept operations like x = x + .., provided that the phi and the reduction are
2307 // used exactly once inside the loop, and by each other.
2308 HInputsRef inputs = phi->GetInputs();
2309 if (inputs.size() == 2) {
2310 HInstruction* reduction = inputs[1];
2311 if (HasReductionFormat(reduction, phi)) {
2312 HLoopInformation* loop_info = phi->GetBlock()->GetLoopInformation();
Aart Bik38a3f212017-10-20 17:02:21 -07002313 uint32_t use_count = 0;
Aart Bikb29f6842017-07-28 15:58:41 -07002314 bool single_use_inside_loop =
2315 // Reduction update only used by phi.
2316 reduction->GetUses().HasExactlyOneElement() &&
2317 !reduction->HasEnvironmentUses() &&
2318 // Reduction update is only use of phi inside the loop.
2319 IsOnlyUsedAfterLoop(loop_info, phi, /*collect_loop_uses*/ true, &use_count) &&
2320 iset_->size() == 1;
2321 iset_->clear(); // leave the way you found it
2322 if (single_use_inside_loop) {
2323 // Link reduction back, and start recording feed value.
2324 reductions_->Put(reduction, phi);
2325 reductions_->Put(phi, phi->InputAt(0));
2326 return true;
2327 }
2328 }
2329 }
2330 return false;
2331}
2332
2333bool HLoopOptimization::TrySetSimpleLoopHeader(HBasicBlock* block, /*out*/ HPhi** main_phi) {
2334 // Start with empty phi induction and reductions.
2335 iset_->clear();
2336 reductions_->clear();
2337
2338 // Scan the phis to find the following (the induction structure has already
2339 // been optimized, so we don't need to worry about trivial cases):
2340 // (1) optional reductions in loop,
2341 // (2) the main induction, used in loop control.
2342 HPhi* phi = nullptr;
2343 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
2344 if (TrySetPhiReduction(it.Current()->AsPhi())) {
2345 continue;
2346 } else if (phi == nullptr) {
2347 // Found the first candidate for main induction.
2348 phi = it.Current()->AsPhi();
2349 } else {
2350 return false;
2351 }
2352 }
2353
2354 // Then test for a typical loopheader:
2355 // s: SuspendCheck
2356 // c: Condition(phi, bound)
2357 // i: If(c)
2358 if (phi != nullptr && TrySetPhiInduction(phi, /*restrict_uses*/ false)) {
Aart Bikcc42be02016-10-20 16:14:16 -07002359 HInstruction* s = block->GetFirstInstruction();
2360 if (s != nullptr && s->IsSuspendCheck()) {
2361 HInstruction* c = s->GetNext();
Aart Bikd86c0852017-04-14 12:00:15 -07002362 if (c != nullptr &&
2363 c->IsCondition() &&
2364 c->GetUses().HasExactlyOneElement() && // only used for termination
2365 !c->HasEnvironmentUses()) { // unlikely, but not impossible
Aart Bikcc42be02016-10-20 16:14:16 -07002366 HInstruction* i = c->GetNext();
2367 if (i != nullptr && i->IsIf() && i->InputAt(0) == c) {
2368 iset_->insert(c);
2369 iset_->insert(s);
Aart Bikb29f6842017-07-28 15:58:41 -07002370 *main_phi = phi;
Aart Bikcc42be02016-10-20 16:14:16 -07002371 return true;
2372 }
2373 }
2374 }
2375 }
2376 return false;
2377}
2378
2379bool HLoopOptimization::IsEmptyBody(HBasicBlock* block) {
Aart Bikf8f5a162017-02-06 15:35:29 -08002380 if (!block->GetPhis().IsEmpty()) {
2381 return false;
2382 }
2383 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
2384 HInstruction* instruction = it.Current();
2385 if (!instruction->IsGoto() && iset_->find(instruction) == iset_->end()) {
2386 return false;
Aart Bikcc42be02016-10-20 16:14:16 -07002387 }
Aart Bikf8f5a162017-02-06 15:35:29 -08002388 }
2389 return true;
2390}
2391
2392bool HLoopOptimization::IsUsedOutsideLoop(HLoopInformation* loop_info,
2393 HInstruction* instruction) {
Aart Bikb29f6842017-07-28 15:58:41 -07002394 // Deal with regular uses.
Aart Bikf8f5a162017-02-06 15:35:29 -08002395 for (const HUseListNode<HInstruction*>& use : instruction->GetUses()) {
2396 if (use.GetUser()->GetBlock()->GetLoopInformation() != loop_info) {
2397 return true;
2398 }
Aart Bikcc42be02016-10-20 16:14:16 -07002399 }
2400 return false;
2401}
2402
Aart Bik482095d2016-10-10 15:39:10 -07002403bool HLoopOptimization::IsOnlyUsedAfterLoop(HLoopInformation* loop_info,
Aart Bik8c4a8542016-10-06 11:36:57 -07002404 HInstruction* instruction,
Aart Bik6b69e0a2017-01-11 10:20:43 -08002405 bool collect_loop_uses,
Aart Bik38a3f212017-10-20 17:02:21 -07002406 /*out*/ uint32_t* use_count) {
Aart Bikb29f6842017-07-28 15:58:41 -07002407 // Deal with regular uses.
Aart Bik8c4a8542016-10-06 11:36:57 -07002408 for (const HUseListNode<HInstruction*>& use : instruction->GetUses()) {
2409 HInstruction* user = use.GetUser();
2410 if (iset_->find(user) == iset_->end()) { // not excluded?
2411 HLoopInformation* other_loop_info = user->GetBlock()->GetLoopInformation();
Aart Bik482095d2016-10-10 15:39:10 -07002412 if (other_loop_info != nullptr && other_loop_info->IsIn(*loop_info)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -08002413 // If collect_loop_uses is set, simply keep adding those uses to the set.
2414 // Otherwise, reject uses inside the loop that were not already in the set.
2415 if (collect_loop_uses) {
2416 iset_->insert(user);
2417 continue;
2418 }
Aart Bik8c4a8542016-10-06 11:36:57 -07002419 return false;
2420 }
2421 ++*use_count;
2422 }
2423 }
2424 return true;
2425}
2426
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002427bool HLoopOptimization::TryReplaceWithLastValue(HLoopInformation* loop_info,
2428 HInstruction* instruction,
2429 HBasicBlock* block) {
2430 // Try to replace outside uses with the last value.
Aart Bik807868e2016-11-03 17:51:43 -07002431 if (induction_range_.CanGenerateLastValue(instruction)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -08002432 HInstruction* replacement = induction_range_.GenerateLastValue(instruction, graph_, block);
Aart Bikb29f6842017-07-28 15:58:41 -07002433 // Deal with regular uses.
Aart Bik6b69e0a2017-01-11 10:20:43 -08002434 const HUseList<HInstruction*>& uses = instruction->GetUses();
2435 for (auto it = uses.begin(), end = uses.end(); it != end;) {
2436 HInstruction* user = it->GetUser();
2437 size_t index = it->GetIndex();
2438 ++it; // increment before replacing
2439 if (iset_->find(user) == iset_->end()) { // not excluded?
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002440 if (kIsDebugBuild) {
2441 // We have checked earlier in 'IsOnlyUsedAfterLoop' that the use is after the loop.
2442 HLoopInformation* other_loop_info = user->GetBlock()->GetLoopInformation();
2443 CHECK(other_loop_info == nullptr || !other_loop_info->IsIn(*loop_info));
2444 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08002445 user->ReplaceInput(replacement, index);
2446 induction_range_.Replace(user, instruction, replacement); // update induction
2447 }
2448 }
Aart Bikb29f6842017-07-28 15:58:41 -07002449 // Deal with environment uses.
Aart Bik6b69e0a2017-01-11 10:20:43 -08002450 const HUseList<HEnvironment*>& env_uses = instruction->GetEnvUses();
2451 for (auto it = env_uses.begin(), end = env_uses.end(); it != end;) {
2452 HEnvironment* user = it->GetUser();
2453 size_t index = it->GetIndex();
2454 ++it; // increment before replacing
2455 if (iset_->find(user->GetHolder()) == iset_->end()) { // not excluded?
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002456 // Only update environment uses after the loop.
Aart Bik14a68b42017-06-08 14:06:58 -07002457 HLoopInformation* other_loop_info = user->GetHolder()->GetBlock()->GetLoopInformation();
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002458 if (other_loop_info == nullptr || !other_loop_info->IsIn(*loop_info)) {
2459 user->RemoveAsUserOfInput(index);
2460 user->SetRawEnvAt(index, replacement);
2461 replacement->AddEnvUseAt(user, index);
2462 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08002463 }
2464 }
Aart Bik807868e2016-11-03 17:51:43 -07002465 return true;
Aart Bik8c4a8542016-10-06 11:36:57 -07002466 }
Aart Bik807868e2016-11-03 17:51:43 -07002467 return false;
Aart Bik8c4a8542016-10-06 11:36:57 -07002468}
2469
Aart Bikf8f5a162017-02-06 15:35:29 -08002470bool HLoopOptimization::TryAssignLastValue(HLoopInformation* loop_info,
2471 HInstruction* instruction,
2472 HBasicBlock* block,
2473 bool collect_loop_uses) {
2474 // Assigning the last value is always successful if there are no uses.
2475 // Otherwise, it succeeds in a no early-exit loop by generating the
2476 // proper last value assignment.
Aart Bik38a3f212017-10-20 17:02:21 -07002477 uint32_t use_count = 0;
Aart Bikf8f5a162017-02-06 15:35:29 -08002478 return IsOnlyUsedAfterLoop(loop_info, instruction, collect_loop_uses, &use_count) &&
2479 (use_count == 0 ||
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002480 (!IsEarlyExit(loop_info) && TryReplaceWithLastValue(loop_info, instruction, block)));
Aart Bikf8f5a162017-02-06 15:35:29 -08002481}
2482
Aart Bik6b69e0a2017-01-11 10:20:43 -08002483void HLoopOptimization::RemoveDeadInstructions(const HInstructionList& list) {
2484 for (HBackwardInstructionIterator i(list); !i.Done(); i.Advance()) {
2485 HInstruction* instruction = i.Current();
2486 if (instruction->IsDeadAndRemovable()) {
2487 simplified_ = true;
2488 instruction->GetBlock()->RemoveInstructionOrPhi(instruction);
2489 }
2490 }
2491}
2492
Aart Bik14a68b42017-06-08 14:06:58 -07002493bool HLoopOptimization::CanRemoveCycle() {
2494 for (HInstruction* i : *iset_) {
2495 // We can never remove instructions that have environment
2496 // uses when we compile 'debuggable'.
2497 if (i->HasEnvironmentUses() && graph_->IsDebuggable()) {
2498 return false;
2499 }
2500 // A deoptimization should never have an environment input removed.
2501 for (const HUseListNode<HEnvironment*>& use : i->GetEnvUses()) {
2502 if (use.GetUser()->GetHolder()->IsDeoptimize()) {
2503 return false;
2504 }
2505 }
2506 }
2507 return true;
2508}
2509
Aart Bik281c6812016-08-26 11:31:48 -07002510} // namespace art