blob: 758aca2d0cb23f4962f10833ecd40e08704d2684 [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
Aart Bik521b50f2017-09-09 10:44:45 -070036// No loop unrolling factor (just one copy of the loop-body).
37static constexpr uint32_t kNoUnrollingFactor = 1;
38
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
Aart Bik5a392762018-03-16 10:27:44 -0700361// Set value range for type (or fail).
362static bool CanSetRange(DataType::Type type,
363 /*out*/ int64_t* uhi,
364 /*out*/ int64_t* slo,
365 /*out*/ int64_t* shi) {
Aart Bik29aa0822018-03-08 11:28:00 -0800366 if (DataType::Size(type) == 1) {
Aart Bik5a392762018-03-16 10:27:44 -0700367 *uhi = std::numeric_limits<uint8_t>::max();
368 *slo = std::numeric_limits<int8_t>::min();
369 *shi = std::numeric_limits<int8_t>::max();
370 return true;
Aart Bik29aa0822018-03-08 11:28:00 -0800371 } else if (DataType::Size(type) == 2) {
Aart Bik5a392762018-03-16 10:27:44 -0700372 *uhi = std::numeric_limits<uint16_t>::max();
373 *slo = std::numeric_limits<int16_t>::min();
374 *shi = std::numeric_limits<int16_t>::max();
375 return true;
Aart Bik29aa0822018-03-08 11:28:00 -0800376 }
377 return false;
378}
379
Aart Bik5a392762018-03-16 10:27:44 -0700380// Accept various saturated addition forms.
381static bool IsSaturatedAdd(HInstruction* clippee,
382 DataType::Type type,
383 int64_t lo,
384 int64_t hi,
385 bool is_unsigned) {
386 int64_t ulo = 0, uhi = 0, slo = 0, shi = 0;
387 if (!CanSetRange(type, &uhi, &slo, &shi)) {
388 return false;
Aart Bik29aa0822018-03-08 11:28:00 -0800389 }
Aart Bik5a392762018-03-16 10:27:44 -0700390 // Tighten the range for signed single clipping on constant.
391 if (!is_unsigned) {
392 int64_t c = 0;
393 HInstruction* notused = nullptr;
394 if (IsAddConst(clippee, &notused, &c)) {
395 // For c in proper range and narrower operand r:
396 // MIN(r + c, 127) c > 0
397 // or MAX(r + c, -128) c < 0 (and possibly redundant bound).
398 if (0 < c && c <= shi && hi == shi) {
399 if (lo <= (slo + c)) {
400 return true;
401 }
402 } else if (slo <= c && c < 0 && lo == slo) {
403 if (hi >= (shi + c)) {
404 return true;
405 }
406 }
407 }
408 }
409 // Detect for narrower operands r and s:
410 // MIN(r + s, 255) => SAT_ADD_unsigned
411 // MAX(MIN(r + s, 127), -128) => SAT_ADD_signed.
412 return is_unsigned ? (lo <= ulo && hi == uhi) : (lo == slo && hi == shi);
413}
414
415// Accept various saturated subtraction forms.
416static bool IsSaturatedSub(HInstruction* clippee,
417 DataType::Type type,
418 int64_t lo,
419 int64_t hi,
420 bool is_unsigned) {
421 int64_t ulo = 0, uhi = 0, slo = 0, shi = 0;
422 if (!CanSetRange(type, &uhi, &slo, &shi)) {
423 return false;
424 }
425 // Tighten the range for signed single clipping on constant.
426 if (!is_unsigned) {
427 int64_t c = 0;
428 if (IsInt64AndGet(clippee->InputAt(0), /*out*/ &c)) {
429 // For c in proper range and narrower operand r:
430 // MIN(c - r, 127) c > 0
431 // or MAX(c - r, -128) c < 0 (and possibly redundant bound).
432 if (0 < c && c <= shi && hi == shi) {
433 if (lo <= (c - shi)) {
434 return true;
435 }
436 } else if (slo <= c && c < 0 && lo == slo) {
437 if (hi >= (c - slo)) {
438 return true;
439 }
440 }
441 }
442 }
443 // Detect for narrower operands r and s:
444 // MAX(r - s, 0) => SAT_SUB_unsigned
445 // MIN(MAX(r - s, -128), 127) => SAT_ADD_signed.
446 return is_unsigned ? (lo == ulo && hi >= uhi) : (lo == slo && hi == shi);
Aart Bik29aa0822018-03-08 11:28:00 -0800447}
448
Aart Bikb29f6842017-07-28 15:58:41 -0700449// Detect reductions of the following forms,
Aart Bikb29f6842017-07-28 15:58:41 -0700450// x = x_phi + ..
451// x = x_phi - ..
Aart Bikb29f6842017-07-28 15:58:41 -0700452// x = min(x_phi, ..)
Aart Bik1f8d51b2018-02-15 10:42:37 -0800453// x = max(x_phi, ..)
Aart Bikb29f6842017-07-28 15:58:41 -0700454static bool HasReductionFormat(HInstruction* reduction, HInstruction* phi) {
Aart Bik1f8d51b2018-02-15 10:42:37 -0800455 if (reduction->IsAdd() || reduction->IsMin() || reduction->IsMax()) {
Aart Bikdbbac8f2017-09-01 13:06:08 -0700456 return (reduction->InputAt(0) == phi && reduction->InputAt(1) != phi) ||
457 (reduction->InputAt(0) != phi && reduction->InputAt(1) == phi);
Aart Bikb29f6842017-07-28 15:58:41 -0700458 } else if (reduction->IsSub()) {
Aart Bikdbbac8f2017-09-01 13:06:08 -0700459 return (reduction->InputAt(0) == phi && reduction->InputAt(1) != phi);
Aart Bikb29f6842017-07-28 15:58:41 -0700460 }
461 return false;
462}
463
Aart Bikdbbac8f2017-09-01 13:06:08 -0700464// Translates vector operation to reduction kind.
465static HVecReduce::ReductionKind GetReductionKind(HVecOperation* reduction) {
466 if (reduction->IsVecAdd() || reduction->IsVecSub() || reduction->IsVecSADAccumulate()) {
Aart Bik0148de42017-09-05 09:25:01 -0700467 return HVecReduce::kSum;
468 } else if (reduction->IsVecMin()) {
469 return HVecReduce::kMin;
470 } else if (reduction->IsVecMax()) {
471 return HVecReduce::kMax;
472 }
Aart Bik38a3f212017-10-20 17:02:21 -0700473 LOG(FATAL) << "Unsupported SIMD reduction " << reduction->GetId();
Aart Bik0148de42017-09-05 09:25:01 -0700474 UNREACHABLE();
475}
476
Aart Bikf8f5a162017-02-06 15:35:29 -0800477// Test vector restrictions.
478static bool HasVectorRestrictions(uint64_t restrictions, uint64_t tested) {
479 return (restrictions & tested) != 0;
480}
481
Aart Bikf3e61ee2017-04-12 17:09:20 -0700482// Insert an instruction.
Aart Bikf8f5a162017-02-06 15:35:29 -0800483static HInstruction* Insert(HBasicBlock* block, HInstruction* instruction) {
484 DCHECK(block != nullptr);
485 DCHECK(instruction != nullptr);
486 block->InsertInstructionBefore(instruction, block->GetLastInstruction());
487 return instruction;
488}
489
Artem Serov21c7e6f2017-07-27 16:04:42 +0100490// Check that instructions from the induction sets are fully removed: have no uses
491// and no other instructions use them.
Vladimir Markoca6fff82017-10-03 14:49:14 +0100492static bool CheckInductionSetFullyRemoved(ScopedArenaSet<HInstruction*>* iset) {
Artem Serov21c7e6f2017-07-27 16:04:42 +0100493 for (HInstruction* instr : *iset) {
494 if (instr->GetBlock() != nullptr ||
495 !instr->GetUses().empty() ||
496 !instr->GetEnvUses().empty() ||
497 HasEnvironmentUsedByOthers(instr)) {
498 return false;
499 }
500 }
Artem Serov21c7e6f2017-07-27 16:04:42 +0100501 return true;
502}
503
Aart Bik281c6812016-08-26 11:31:48 -0700504//
Aart Bikb29f6842017-07-28 15:58:41 -0700505// Public methods.
Aart Bik281c6812016-08-26 11:31:48 -0700506//
507
508HLoopOptimization::HLoopOptimization(HGraph* graph,
Aart Bik92685a82017-03-06 11:13:43 -0800509 CompilerDriver* compiler_driver,
Aart Bikb92cc332017-09-06 15:53:17 -0700510 HInductionVarAnalysis* induction_analysis,
Aart Bik2ca10eb2017-11-15 15:17:53 -0800511 OptimizingCompilerStats* stats,
512 const char* name)
513 : HOptimization(graph, name, stats),
Aart Bik92685a82017-03-06 11:13:43 -0800514 compiler_driver_(compiler_driver),
Aart Bik281c6812016-08-26 11:31:48 -0700515 induction_range_(induction_analysis),
Aart Bik96202302016-10-04 17:33:56 -0700516 loop_allocator_(nullptr),
Vladimir Markoca6fff82017-10-03 14:49:14 +0100517 global_allocator_(graph_->GetAllocator()),
Aart Bik281c6812016-08-26 11:31:48 -0700518 top_loop_(nullptr),
Aart Bik8c4a8542016-10-06 11:36:57 -0700519 last_loop_(nullptr),
Aart Bik482095d2016-10-10 15:39:10 -0700520 iset_(nullptr),
Aart Bikb29f6842017-07-28 15:58:41 -0700521 reductions_(nullptr),
Aart Bikf8f5a162017-02-06 15:35:29 -0800522 simplified_(false),
523 vector_length_(0),
524 vector_refs_(nullptr),
Aart Bik38a3f212017-10-20 17:02:21 -0700525 vector_static_peeling_factor_(0),
526 vector_dynamic_peeling_candidate_(nullptr),
Aart Bik14a68b42017-06-08 14:06:58 -0700527 vector_runtime_test_a_(nullptr),
528 vector_runtime_test_b_(nullptr),
Aart Bik0148de42017-09-05 09:25:01 -0700529 vector_map_(nullptr),
Vladimir Markoca6fff82017-10-03 14:49:14 +0100530 vector_permanent_map_(nullptr),
531 vector_mode_(kSequential),
532 vector_preheader_(nullptr),
533 vector_header_(nullptr),
534 vector_body_(nullptr),
535 vector_index_(nullptr) {
Aart Bik281c6812016-08-26 11:31:48 -0700536}
537
538void HLoopOptimization::Run() {
Mingyao Yang01b47b02017-02-03 12:09:57 -0800539 // Skip if there is no loop or the graph has try-catch/irreducible loops.
Aart Bik281c6812016-08-26 11:31:48 -0700540 // TODO: make this less of a sledgehammer.
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800541 if (!graph_->HasLoops() || graph_->HasTryCatch() || graph_->HasIrreducibleLoops()) {
Aart Bik281c6812016-08-26 11:31:48 -0700542 return;
543 }
544
Vladimir Markoca6fff82017-10-03 14:49:14 +0100545 // Phase-local allocator.
546 ScopedArenaAllocator allocator(graph_->GetArenaStack());
Aart Bik96202302016-10-04 17:33:56 -0700547 loop_allocator_ = &allocator;
Nicolas Geoffrayebe16742016-10-05 09:55:42 +0100548
Aart Bik96202302016-10-04 17:33:56 -0700549 // Perform loop optimizations.
550 LocalRun();
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800551 if (top_loop_ == nullptr) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800552 graph_->SetHasLoops(false); // no more loops
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800553 }
554
Aart Bik96202302016-10-04 17:33:56 -0700555 // Detach.
556 loop_allocator_ = nullptr;
557 last_loop_ = top_loop_ = nullptr;
558}
559
Aart Bikb29f6842017-07-28 15:58:41 -0700560//
561// Loop setup and traversal.
562//
563
Aart Bik96202302016-10-04 17:33:56 -0700564void HLoopOptimization::LocalRun() {
565 // Build the linear order using the phase-local allocator. This step enables building
566 // a loop hierarchy that properly reflects the outer-inner and previous-next relation.
Vladimir Markoca6fff82017-10-03 14:49:14 +0100567 ScopedArenaVector<HBasicBlock*> linear_order(loop_allocator_->Adapter(kArenaAllocLinearOrder));
568 LinearizeGraph(graph_, &linear_order);
Aart Bik96202302016-10-04 17:33:56 -0700569
Aart Bik281c6812016-08-26 11:31:48 -0700570 // Build the loop hierarchy.
Aart Bik96202302016-10-04 17:33:56 -0700571 for (HBasicBlock* block : linear_order) {
Aart Bik281c6812016-08-26 11:31:48 -0700572 if (block->IsLoopHeader()) {
573 AddLoop(block->GetLoopInformation());
574 }
575 }
Aart Bik96202302016-10-04 17:33:56 -0700576
Aart Bik8c4a8542016-10-06 11:36:57 -0700577 // Traverse the loop hierarchy inner-to-outer and optimize. Traversal can use
Aart Bikf8f5a162017-02-06 15:35:29 -0800578 // temporary data structures using the phase-local allocator. All new HIR
579 // should use the global allocator.
Aart Bik8c4a8542016-10-06 11:36:57 -0700580 if (top_loop_ != nullptr) {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100581 ScopedArenaSet<HInstruction*> iset(loop_allocator_->Adapter(kArenaAllocLoopOptimization));
582 ScopedArenaSafeMap<HInstruction*, HInstruction*> reds(
Aart Bikb29f6842017-07-28 15:58:41 -0700583 std::less<HInstruction*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
Vladimir Markoca6fff82017-10-03 14:49:14 +0100584 ScopedArenaSet<ArrayReference> refs(loop_allocator_->Adapter(kArenaAllocLoopOptimization));
585 ScopedArenaSafeMap<HInstruction*, HInstruction*> map(
Aart Bikf8f5a162017-02-06 15:35:29 -0800586 std::less<HInstruction*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
Vladimir Markoca6fff82017-10-03 14:49:14 +0100587 ScopedArenaSafeMap<HInstruction*, HInstruction*> perm(
Aart Bik0148de42017-09-05 09:25:01 -0700588 std::less<HInstruction*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
Aart Bikf8f5a162017-02-06 15:35:29 -0800589 // Attach.
Aart Bik8c4a8542016-10-06 11:36:57 -0700590 iset_ = &iset;
Aart Bikb29f6842017-07-28 15:58:41 -0700591 reductions_ = &reds;
Aart Bikf8f5a162017-02-06 15:35:29 -0800592 vector_refs_ = &refs;
593 vector_map_ = &map;
Aart Bik0148de42017-09-05 09:25:01 -0700594 vector_permanent_map_ = &perm;
Aart Bikf8f5a162017-02-06 15:35:29 -0800595 // Traverse.
Aart Bik8c4a8542016-10-06 11:36:57 -0700596 TraverseLoopsInnerToOuter(top_loop_);
Aart Bikf8f5a162017-02-06 15:35:29 -0800597 // Detach.
598 iset_ = nullptr;
Aart Bikb29f6842017-07-28 15:58:41 -0700599 reductions_ = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800600 vector_refs_ = nullptr;
601 vector_map_ = nullptr;
Aart Bik0148de42017-09-05 09:25:01 -0700602 vector_permanent_map_ = nullptr;
Aart Bik8c4a8542016-10-06 11:36:57 -0700603 }
Aart Bik281c6812016-08-26 11:31:48 -0700604}
605
606void HLoopOptimization::AddLoop(HLoopInformation* loop_info) {
607 DCHECK(loop_info != nullptr);
Aart Bikf8f5a162017-02-06 15:35:29 -0800608 LoopNode* node = new (loop_allocator_) LoopNode(loop_info);
Aart Bik281c6812016-08-26 11:31:48 -0700609 if (last_loop_ == nullptr) {
610 // First loop.
611 DCHECK(top_loop_ == nullptr);
612 last_loop_ = top_loop_ = node;
613 } else if (loop_info->IsIn(*last_loop_->loop_info)) {
614 // Inner loop.
615 node->outer = last_loop_;
616 DCHECK(last_loop_->inner == nullptr);
617 last_loop_ = last_loop_->inner = node;
618 } else {
619 // Subsequent loop.
620 while (last_loop_->outer != nullptr && !loop_info->IsIn(*last_loop_->outer->loop_info)) {
621 last_loop_ = last_loop_->outer;
622 }
623 node->outer = last_loop_->outer;
624 node->previous = last_loop_;
625 DCHECK(last_loop_->next == nullptr);
626 last_loop_ = last_loop_->next = node;
627 }
628}
629
630void HLoopOptimization::RemoveLoop(LoopNode* node) {
631 DCHECK(node != nullptr);
Aart Bik8c4a8542016-10-06 11:36:57 -0700632 DCHECK(node->inner == nullptr);
633 if (node->previous != nullptr) {
634 // Within sequence.
635 node->previous->next = node->next;
636 if (node->next != nullptr) {
637 node->next->previous = node->previous;
638 }
639 } else {
640 // First of sequence.
641 if (node->outer != nullptr) {
642 node->outer->inner = node->next;
643 } else {
644 top_loop_ = node->next;
645 }
646 if (node->next != nullptr) {
647 node->next->outer = node->outer;
648 node->next->previous = nullptr;
649 }
650 }
Aart Bik281c6812016-08-26 11:31:48 -0700651}
652
Aart Bikb29f6842017-07-28 15:58:41 -0700653bool HLoopOptimization::TraverseLoopsInnerToOuter(LoopNode* node) {
654 bool changed = false;
Aart Bik281c6812016-08-26 11:31:48 -0700655 for ( ; node != nullptr; node = node->next) {
Aart Bikb29f6842017-07-28 15:58:41 -0700656 // Visit inner loops first. Recompute induction information for this
657 // loop if the induction of any inner loop has changed.
658 if (TraverseLoopsInnerToOuter(node->inner)) {
Aart Bik482095d2016-10-10 15:39:10 -0700659 induction_range_.ReVisit(node->loop_info);
660 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800661 // Repeat simplifications in the loop-body until no more changes occur.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800662 // Note that since each simplification consists of eliminating code (without
663 // introducing new code), this process is always finite.
Aart Bikdf7822e2016-12-06 10:05:30 -0800664 do {
665 simplified_ = false;
Aart Bikdf7822e2016-12-06 10:05:30 -0800666 SimplifyInduction(node);
Aart Bik6b69e0a2017-01-11 10:20:43 -0800667 SimplifyBlocks(node);
Aart Bikb29f6842017-07-28 15:58:41 -0700668 changed = simplified_ || changed;
Aart Bikdf7822e2016-12-06 10:05:30 -0800669 } while (simplified_);
Aart Bikf8f5a162017-02-06 15:35:29 -0800670 // Optimize inner loop.
Aart Bik9abf8942016-10-14 09:49:42 -0700671 if (node->inner == nullptr) {
Aart Bikb29f6842017-07-28 15:58:41 -0700672 changed = OptimizeInnerLoop(node) || changed;
Aart Bik9abf8942016-10-14 09:49:42 -0700673 }
Aart Bik281c6812016-08-26 11:31:48 -0700674 }
Aart Bikb29f6842017-07-28 15:58:41 -0700675 return changed;
Aart Bik281c6812016-08-26 11:31:48 -0700676}
677
Aart Bikf8f5a162017-02-06 15:35:29 -0800678//
679// Optimization.
680//
681
Aart Bik281c6812016-08-26 11:31:48 -0700682void HLoopOptimization::SimplifyInduction(LoopNode* node) {
683 HBasicBlock* header = node->loop_info->GetHeader();
684 HBasicBlock* preheader = node->loop_info->GetPreHeader();
Aart Bik8c4a8542016-10-06 11:36:57 -0700685 // Scan the phis in the header to find opportunities to simplify an induction
686 // cycle that is only used outside the loop. Replace these uses, if any, with
687 // the last value and remove the induction cycle.
688 // Examples: for (int i = 0; x != null; i++) { .... no i .... }
689 // for (int i = 0; i < 10; i++, k++) { .... no k .... } return k;
Aart Bik281c6812016-08-26 11:31:48 -0700690 for (HInstructionIterator it(header->GetPhis()); !it.Done(); it.Advance()) {
691 HPhi* phi = it.Current()->AsPhi();
Aart Bikf8f5a162017-02-06 15:35:29 -0800692 if (TrySetPhiInduction(phi, /*restrict_uses*/ true) &&
693 TryAssignLastValue(node->loop_info, phi, preheader, /*collect_loop_uses*/ false)) {
Aart Bik671e48a2017-08-09 13:16:56 -0700694 // Note that it's ok to have replaced uses after the loop with the last value, without
695 // being able to remove the cycle. Environment uses (which are the reason we may not be
696 // able to remove the cycle) within the loop will still hold the right value. We must
697 // have tried first, however, to replace outside uses.
698 if (CanRemoveCycle()) {
699 simplified_ = true;
700 for (HInstruction* i : *iset_) {
701 RemoveFromCycle(i);
702 }
703 DCHECK(CheckInductionSetFullyRemoved(iset_));
Aart Bik281c6812016-08-26 11:31:48 -0700704 }
Aart Bik482095d2016-10-10 15:39:10 -0700705 }
706 }
707}
708
709void HLoopOptimization::SimplifyBlocks(LoopNode* node) {
Aart Bikdf7822e2016-12-06 10:05:30 -0800710 // Iterate over all basic blocks in the loop-body.
711 for (HBlocksInLoopIterator it(*node->loop_info); !it.Done(); it.Advance()) {
712 HBasicBlock* block = it.Current();
713 // Remove dead instructions from the loop-body.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800714 RemoveDeadInstructions(block->GetPhis());
715 RemoveDeadInstructions(block->GetInstructions());
Aart Bikdf7822e2016-12-06 10:05:30 -0800716 // Remove trivial control flow blocks from the loop-body.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800717 if (block->GetPredecessors().size() == 1 &&
718 block->GetSuccessors().size() == 1 &&
719 block->GetSingleSuccessor()->GetPredecessors().size() == 1) {
Aart Bikdf7822e2016-12-06 10:05:30 -0800720 simplified_ = true;
Aart Bik6b69e0a2017-01-11 10:20:43 -0800721 block->MergeWith(block->GetSingleSuccessor());
Aart Bikdf7822e2016-12-06 10:05:30 -0800722 } else if (block->GetSuccessors().size() == 2) {
723 // Trivial if block can be bypassed to either branch.
724 HBasicBlock* succ0 = block->GetSuccessors()[0];
725 HBasicBlock* succ1 = block->GetSuccessors()[1];
726 HBasicBlock* meet0 = nullptr;
727 HBasicBlock* meet1 = nullptr;
728 if (succ0 != succ1 &&
729 IsGotoBlock(succ0, &meet0) &&
730 IsGotoBlock(succ1, &meet1) &&
731 meet0 == meet1 && // meets again
732 meet0 != block && // no self-loop
733 meet0->GetPhis().IsEmpty()) { // not used for merging
734 simplified_ = true;
735 succ0->DisconnectAndDelete();
736 if (block->Dominates(meet0)) {
737 block->RemoveDominatedBlock(meet0);
738 succ1->AddDominatedBlock(meet0);
739 meet0->SetDominator(succ1);
Aart Bike3dedc52016-11-02 17:50:27 -0700740 }
Aart Bik482095d2016-10-10 15:39:10 -0700741 }
Aart Bik281c6812016-08-26 11:31:48 -0700742 }
Aart Bikdf7822e2016-12-06 10:05:30 -0800743 }
Aart Bik281c6812016-08-26 11:31:48 -0700744}
745
Aart Bikb29f6842017-07-28 15:58:41 -0700746bool HLoopOptimization::OptimizeInnerLoop(LoopNode* node) {
Aart Bik281c6812016-08-26 11:31:48 -0700747 HBasicBlock* header = node->loop_info->GetHeader();
748 HBasicBlock* preheader = node->loop_info->GetPreHeader();
Aart Bik9abf8942016-10-14 09:49:42 -0700749 // Ensure loop header logic is finite.
Aart Bikf8f5a162017-02-06 15:35:29 -0800750 int64_t trip_count = 0;
751 if (!induction_range_.IsFinite(node->loop_info, &trip_count)) {
Aart Bikb29f6842017-07-28 15:58:41 -0700752 return false;
Aart Bik9abf8942016-10-14 09:49:42 -0700753 }
Aart Bik281c6812016-08-26 11:31:48 -0700754 // Ensure there is only a single loop-body (besides the header).
755 HBasicBlock* body = nullptr;
756 for (HBlocksInLoopIterator it(*node->loop_info); !it.Done(); it.Advance()) {
757 if (it.Current() != header) {
758 if (body != nullptr) {
Aart Bikb29f6842017-07-28 15:58:41 -0700759 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700760 }
761 body = it.Current();
762 }
763 }
Andreas Gampef45d61c2017-06-07 10:29:33 -0700764 CHECK(body != nullptr);
Aart Bik281c6812016-08-26 11:31:48 -0700765 // Ensure there is only a single exit point.
766 if (header->GetSuccessors().size() != 2) {
Aart Bikb29f6842017-07-28 15:58:41 -0700767 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700768 }
769 HBasicBlock* exit = (header->GetSuccessors()[0] == body)
770 ? header->GetSuccessors()[1]
771 : header->GetSuccessors()[0];
Aart Bik8c4a8542016-10-06 11:36:57 -0700772 // Ensure exit can only be reached by exiting loop.
Aart Bik281c6812016-08-26 11:31:48 -0700773 if (exit->GetPredecessors().size() != 1) {
Aart Bikb29f6842017-07-28 15:58:41 -0700774 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700775 }
Aart Bik6b69e0a2017-01-11 10:20:43 -0800776 // Detect either an empty loop (no side effects other than plain iteration) or
777 // a trivial loop (just iterating once). Replace subsequent index uses, if any,
778 // with the last value and remove the loop, possibly after unrolling its body.
Aart Bikb29f6842017-07-28 15:58:41 -0700779 HPhi* main_phi = nullptr;
780 if (TrySetSimpleLoopHeader(header, &main_phi)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -0800781 bool is_empty = IsEmptyBody(body);
Aart Bikb29f6842017-07-28 15:58:41 -0700782 if (reductions_->empty() && // TODO: possible with some effort
783 (is_empty || trip_count == 1) &&
784 TryAssignLastValue(node->loop_info, main_phi, preheader, /*collect_loop_uses*/ true)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -0800785 if (!is_empty) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800786 // Unroll the loop-body, which sees initial value of the index.
Aart Bikb29f6842017-07-28 15:58:41 -0700787 main_phi->ReplaceWith(main_phi->InputAt(0));
Aart Bik6b69e0a2017-01-11 10:20:43 -0800788 preheader->MergeInstructionsWith(body);
789 }
790 body->DisconnectAndDelete();
791 exit->RemovePredecessor(header);
792 header->RemoveSuccessor(exit);
793 header->RemoveDominatedBlock(exit);
794 header->DisconnectAndDelete();
795 preheader->AddSuccessor(exit);
Aart Bikf8f5a162017-02-06 15:35:29 -0800796 preheader->AddInstruction(new (global_allocator_) HGoto());
Aart Bik6b69e0a2017-01-11 10:20:43 -0800797 preheader->AddDominatedBlock(exit);
798 exit->SetDominator(preheader);
799 RemoveLoop(node); // update hierarchy
Aart Bikb29f6842017-07-28 15:58:41 -0700800 return true;
Aart Bikf8f5a162017-02-06 15:35:29 -0800801 }
802 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800803 // Vectorize loop, if possible and valid.
Aart Bikb29f6842017-07-28 15:58:41 -0700804 if (kEnableVectorization &&
805 TrySetSimpleLoopHeader(header, &main_phi) &&
Aart Bikb29f6842017-07-28 15:58:41 -0700806 ShouldVectorize(node, body, trip_count) &&
807 TryAssignLastValue(node->loop_info, main_phi, preheader, /*collect_loop_uses*/ true)) {
808 Vectorize(node, body, exit, trip_count);
809 graph_->SetHasSIMD(true); // flag SIMD usage
Aart Bik21b85922017-09-06 13:29:16 -0700810 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorized);
Aart Bikb29f6842017-07-28 15:58:41 -0700811 return true;
Aart Bikf8f5a162017-02-06 15:35:29 -0800812 }
Aart Bikb29f6842017-07-28 15:58:41 -0700813 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -0800814}
815
816//
817// Loop vectorization. The implementation is based on the book by Aart J.C. Bik:
818// "The Software Vectorization Handbook. Applying Multimedia Extensions for Maximum Performance."
819// Intel Press, June, 2004 (http://www.aartbik.com/).
820//
821
Aart Bik14a68b42017-06-08 14:06:58 -0700822bool HLoopOptimization::ShouldVectorize(LoopNode* node, HBasicBlock* block, int64_t trip_count) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800823 // Reset vector bookkeeping.
824 vector_length_ = 0;
825 vector_refs_->clear();
Aart Bik38a3f212017-10-20 17:02:21 -0700826 vector_static_peeling_factor_ = 0;
827 vector_dynamic_peeling_candidate_ = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800828 vector_runtime_test_a_ =
Igor Murashkin2ffb7032017-11-08 13:35:21 -0800829 vector_runtime_test_b_ = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800830
831 // Phis in the loop-body prevent vectorization.
832 if (!block->GetPhis().IsEmpty()) {
833 return false;
834 }
835
836 // Scan the loop-body, starting a right-hand-side tree traversal at each left-hand-side
837 // occurrence, which allows passing down attributes down the use tree.
838 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
839 if (!VectorizeDef(node, it.Current(), /*generate_code*/ false)) {
840 return false; // failure to vectorize a left-hand-side
841 }
842 }
843
Aart Bik38a3f212017-10-20 17:02:21 -0700844 // Prepare alignment analysis:
845 // (1) find desired alignment (SIMD vector size in bytes).
846 // (2) initialize static loop peeling votes (peeling factor that will
847 // make one particular reference aligned), never to exceed (1).
848 // (3) variable to record how many references share same alignment.
849 // (4) variable to record suitable candidate for dynamic loop peeling.
850 uint32_t desired_alignment = GetVectorSizeInBytes();
851 DCHECK_LE(desired_alignment, 16u);
852 uint32_t peeling_votes[16] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
853 uint32_t max_num_same_alignment = 0;
854 const ArrayReference* peeling_candidate = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800855
856 // Data dependence analysis. Find each pair of references with same type, where
857 // at least one is a write. Each such pair denotes a possible data dependence.
858 // This analysis exploits the property that differently typed arrays cannot be
859 // aliased, as well as the property that references either point to the same
860 // array or to two completely disjoint arrays, i.e., no partial aliasing.
861 // Other than a few simply heuristics, no detailed subscript analysis is done.
Aart Bik38a3f212017-10-20 17:02:21 -0700862 // The scan over references also prepares finding a suitable alignment strategy.
Aart Bikf8f5a162017-02-06 15:35:29 -0800863 for (auto i = vector_refs_->begin(); i != vector_refs_->end(); ++i) {
Aart Bik38a3f212017-10-20 17:02:21 -0700864 uint32_t num_same_alignment = 0;
865 // Scan over all next references.
Aart Bikf8f5a162017-02-06 15:35:29 -0800866 for (auto j = i; ++j != vector_refs_->end(); ) {
867 if (i->type == j->type && (i->lhs || j->lhs)) {
868 // Found same-typed a[i+x] vs. b[i+y], where at least one is a write.
869 HInstruction* a = i->base;
870 HInstruction* b = j->base;
871 HInstruction* x = i->offset;
872 HInstruction* y = j->offset;
873 if (a == b) {
874 // Found a[i+x] vs. a[i+y]. Accept if x == y (loop-independent data dependence).
875 // Conservatively assume a loop-carried data dependence otherwise, and reject.
876 if (x != y) {
877 return false;
878 }
Aart Bik38a3f212017-10-20 17:02:21 -0700879 // Count the number of references that have the same alignment (since
880 // base and offset are the same) and where at least one is a write, so
881 // e.g. a[i] = a[i] + b[i] counts a[i] but not b[i]).
882 num_same_alignment++;
Aart Bikf8f5a162017-02-06 15:35:29 -0800883 } else {
884 // Found a[i+x] vs. b[i+y]. Accept if x == y (at worst loop-independent data dependence).
885 // Conservatively assume a potential loop-carried data dependence otherwise, avoided by
886 // generating an explicit a != b disambiguation runtime test on the two references.
887 if (x != y) {
Aart Bik37dc4df2017-06-28 14:08:00 -0700888 // To avoid excessive overhead, we only accept one a != b test.
889 if (vector_runtime_test_a_ == nullptr) {
890 // First test found.
891 vector_runtime_test_a_ = a;
892 vector_runtime_test_b_ = b;
893 } else if ((vector_runtime_test_a_ != a || vector_runtime_test_b_ != b) &&
894 (vector_runtime_test_a_ != b || vector_runtime_test_b_ != a)) {
895 return false; // second test would be needed
Aart Bikf8f5a162017-02-06 15:35:29 -0800896 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800897 }
898 }
899 }
900 }
Aart Bik38a3f212017-10-20 17:02:21 -0700901 // Update information for finding suitable alignment strategy:
902 // (1) update votes for static loop peeling,
903 // (2) update suitable candidate for dynamic loop peeling.
904 Alignment alignment = ComputeAlignment(i->offset, i->type, i->is_string_char_at);
905 if (alignment.Base() >= desired_alignment) {
906 // If the array/string object has a known, sufficient alignment, use the
907 // initial offset to compute the static loop peeling vote (this always
908 // works, since elements have natural alignment).
909 uint32_t offset = alignment.Offset() & (desired_alignment - 1u);
910 uint32_t vote = (offset == 0)
911 ? 0
912 : ((desired_alignment - offset) >> DataType::SizeShift(i->type));
913 DCHECK_LT(vote, 16u);
914 ++peeling_votes[vote];
915 } else if (BaseAlignment() >= desired_alignment &&
916 num_same_alignment > max_num_same_alignment) {
917 // Otherwise, if the array/string object has a known, sufficient alignment
918 // for just the base but with an unknown offset, record the candidate with
919 // the most occurrences for dynamic loop peeling (again, the peeling always
920 // works, since elements have natural alignment).
921 max_num_same_alignment = num_same_alignment;
922 peeling_candidate = &(*i);
923 }
924 } // for i
Aart Bikf8f5a162017-02-06 15:35:29 -0800925
Aart Bik38a3f212017-10-20 17:02:21 -0700926 // Find a suitable alignment strategy.
927 SetAlignmentStrategy(peeling_votes, peeling_candidate);
928
929 // Does vectorization seem profitable?
930 if (!IsVectorizationProfitable(trip_count)) {
931 return false;
932 }
Aart Bik14a68b42017-06-08 14:06:58 -0700933
Aart Bikf8f5a162017-02-06 15:35:29 -0800934 // Success!
935 return true;
936}
937
938void HLoopOptimization::Vectorize(LoopNode* node,
939 HBasicBlock* block,
940 HBasicBlock* exit,
941 int64_t trip_count) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800942 HBasicBlock* header = node->loop_info->GetHeader();
943 HBasicBlock* preheader = node->loop_info->GetPreHeader();
944
Aart Bik14a68b42017-06-08 14:06:58 -0700945 // Pick a loop unrolling factor for the vector loop.
946 uint32_t unroll = GetUnrollingFactor(block, trip_count);
947 uint32_t chunk = vector_length_ * unroll;
948
Aart Bik38a3f212017-10-20 17:02:21 -0700949 DCHECK(trip_count == 0 || (trip_count >= MaxNumberPeeled() + chunk));
950
Aart Bik14a68b42017-06-08 14:06:58 -0700951 // A cleanup loop is needed, at least, for any unknown trip count or
952 // for a known trip count with remainder iterations after vectorization.
Aart Bik38a3f212017-10-20 17:02:21 -0700953 bool needs_cleanup = trip_count == 0 ||
954 ((trip_count - vector_static_peeling_factor_) % chunk) != 0;
Aart Bikf8f5a162017-02-06 15:35:29 -0800955
956 // Adjust vector bookkeeping.
Aart Bikb29f6842017-07-28 15:58:41 -0700957 HPhi* main_phi = nullptr;
958 bool is_simple_loop_header = TrySetSimpleLoopHeader(header, &main_phi); // refills sets
Aart Bikf8f5a162017-02-06 15:35:29 -0800959 DCHECK(is_simple_loop_header);
Aart Bik14a68b42017-06-08 14:06:58 -0700960 vector_header_ = header;
961 vector_body_ = block;
Aart Bikf8f5a162017-02-06 15:35:29 -0800962
Aart Bikdbbac8f2017-09-01 13:06:08 -0700963 // Loop induction type.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100964 DataType::Type induc_type = main_phi->GetType();
965 DCHECK(induc_type == DataType::Type::kInt32 || induc_type == DataType::Type::kInt64)
966 << induc_type;
Aart Bikdbbac8f2017-09-01 13:06:08 -0700967
Aart Bik38a3f212017-10-20 17:02:21 -0700968 // Generate the trip count for static or dynamic loop peeling, if needed:
969 // ptc = <peeling factor>;
Aart Bik14a68b42017-06-08 14:06:58 -0700970 HInstruction* ptc = nullptr;
Aart Bik38a3f212017-10-20 17:02:21 -0700971 if (vector_static_peeling_factor_ != 0) {
972 // Static loop peeling for SIMD alignment (using the most suitable
973 // fixed peeling factor found during prior alignment analysis).
974 DCHECK(vector_dynamic_peeling_candidate_ == nullptr);
975 ptc = graph_->GetConstant(induc_type, vector_static_peeling_factor_);
976 } else if (vector_dynamic_peeling_candidate_ != nullptr) {
977 // Dynamic loop peeling for SIMD alignment (using the most suitable
978 // candidate found during prior alignment analysis):
979 // rem = offset % ALIGN; // adjusted as #elements
980 // ptc = rem == 0 ? 0 : (ALIGN - rem);
981 uint32_t shift = DataType::SizeShift(vector_dynamic_peeling_candidate_->type);
982 uint32_t align = GetVectorSizeInBytes() >> shift;
983 uint32_t hidden_offset = HiddenOffset(vector_dynamic_peeling_candidate_->type,
984 vector_dynamic_peeling_candidate_->is_string_char_at);
985 HInstruction* adjusted_offset = graph_->GetConstant(induc_type, hidden_offset >> shift);
986 HInstruction* offset = Insert(preheader, new (global_allocator_) HAdd(
987 induc_type, vector_dynamic_peeling_candidate_->offset, adjusted_offset));
988 HInstruction* rem = Insert(preheader, new (global_allocator_) HAnd(
989 induc_type, offset, graph_->GetConstant(induc_type, align - 1u)));
990 HInstruction* sub = Insert(preheader, new (global_allocator_) HSub(
991 induc_type, graph_->GetConstant(induc_type, align), rem));
992 HInstruction* cond = Insert(preheader, new (global_allocator_) HEqual(
993 rem, graph_->GetConstant(induc_type, 0)));
994 ptc = Insert(preheader, new (global_allocator_) HSelect(
995 cond, graph_->GetConstant(induc_type, 0), sub, kNoDexPc));
996 needs_cleanup = true; // don't know the exact amount
Aart Bik14a68b42017-06-08 14:06:58 -0700997 }
998
999 // Generate loop control:
Aart Bikf8f5a162017-02-06 15:35:29 -08001000 // stc = <trip-count>;
Aart Bik38a3f212017-10-20 17:02:21 -07001001 // ptc = min(stc, ptc);
Aart Bik14a68b42017-06-08 14:06:58 -07001002 // vtc = stc - (stc - ptc) % chunk;
1003 // i = 0;
Aart Bikf8f5a162017-02-06 15:35:29 -08001004 HInstruction* stc = induction_range_.GenerateTripCount(node->loop_info, graph_, preheader);
1005 HInstruction* vtc = stc;
1006 if (needs_cleanup) {
Aart Bik14a68b42017-06-08 14:06:58 -07001007 DCHECK(IsPowerOfTwo(chunk));
1008 HInstruction* diff = stc;
1009 if (ptc != nullptr) {
Aart Bik38a3f212017-10-20 17:02:21 -07001010 if (trip_count == 0) {
1011 HInstruction* cond = Insert(preheader, new (global_allocator_) HAboveOrEqual(stc, ptc));
1012 ptc = Insert(preheader, new (global_allocator_) HSelect(cond, ptc, stc, kNoDexPc));
1013 }
Aart Bik14a68b42017-06-08 14:06:58 -07001014 diff = Insert(preheader, new (global_allocator_) HSub(induc_type, stc, ptc));
1015 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001016 HInstruction* rem = Insert(
1017 preheader, new (global_allocator_) HAnd(induc_type,
Aart Bik14a68b42017-06-08 14:06:58 -07001018 diff,
Aart Bikdbbac8f2017-09-01 13:06:08 -07001019 graph_->GetConstant(induc_type, chunk - 1)));
Aart Bikf8f5a162017-02-06 15:35:29 -08001020 vtc = Insert(preheader, new (global_allocator_) HSub(induc_type, stc, rem));
1021 }
Aart Bikdbbac8f2017-09-01 13:06:08 -07001022 vector_index_ = graph_->GetConstant(induc_type, 0);
Aart Bikf8f5a162017-02-06 15:35:29 -08001023
1024 // Generate runtime disambiguation test:
1025 // vtc = a != b ? vtc : 0;
1026 if (vector_runtime_test_a_ != nullptr) {
1027 HInstruction* rt = Insert(
1028 preheader,
1029 new (global_allocator_) HNotEqual(vector_runtime_test_a_, vector_runtime_test_b_));
1030 vtc = Insert(preheader,
Aart Bikdbbac8f2017-09-01 13:06:08 -07001031 new (global_allocator_)
1032 HSelect(rt, vtc, graph_->GetConstant(induc_type, 0), kNoDexPc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001033 needs_cleanup = true;
1034 }
1035
Aart Bik38a3f212017-10-20 17:02:21 -07001036 // Generate alignment peeling loop, if needed:
Aart Bik14a68b42017-06-08 14:06:58 -07001037 // for ( ; i < ptc; i += 1)
1038 // <loop-body>
Aart Bik38a3f212017-10-20 17:02:21 -07001039 //
1040 // NOTE: The alignment forced by the peeling loop is preserved even if data is
1041 // moved around during suspend checks, since all analysis was based on
1042 // nothing more than the Android runtime alignment conventions.
Aart Bik14a68b42017-06-08 14:06:58 -07001043 if (ptc != nullptr) {
1044 vector_mode_ = kSequential;
1045 GenerateNewLoop(node,
1046 block,
1047 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
1048 vector_index_,
1049 ptc,
Aart Bikdbbac8f2017-09-01 13:06:08 -07001050 graph_->GetConstant(induc_type, 1),
Aart Bik521b50f2017-09-09 10:44:45 -07001051 kNoUnrollingFactor);
Aart Bik14a68b42017-06-08 14:06:58 -07001052 }
1053
1054 // Generate vector loop, possibly further unrolled:
1055 // for ( ; i < vtc; i += chunk)
Aart Bikf8f5a162017-02-06 15:35:29 -08001056 // <vectorized-loop-body>
1057 vector_mode_ = kVector;
1058 GenerateNewLoop(node,
1059 block,
Aart Bik14a68b42017-06-08 14:06:58 -07001060 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
1061 vector_index_,
Aart Bikf8f5a162017-02-06 15:35:29 -08001062 vtc,
Aart Bikdbbac8f2017-09-01 13:06:08 -07001063 graph_->GetConstant(induc_type, vector_length_), // increment per unroll
Aart Bik14a68b42017-06-08 14:06:58 -07001064 unroll);
Aart Bikf8f5a162017-02-06 15:35:29 -08001065 HLoopInformation* vloop = vector_header_->GetLoopInformation();
1066
1067 // Generate cleanup loop, if needed:
1068 // for ( ; i < stc; i += 1)
1069 // <loop-body>
1070 if (needs_cleanup) {
1071 vector_mode_ = kSequential;
1072 GenerateNewLoop(node,
1073 block,
1074 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
Aart Bik14a68b42017-06-08 14:06:58 -07001075 vector_index_,
Aart Bikf8f5a162017-02-06 15:35:29 -08001076 stc,
Aart Bikdbbac8f2017-09-01 13:06:08 -07001077 graph_->GetConstant(induc_type, 1),
Aart Bik521b50f2017-09-09 10:44:45 -07001078 kNoUnrollingFactor);
Aart Bikf8f5a162017-02-06 15:35:29 -08001079 }
1080
Aart Bik0148de42017-09-05 09:25:01 -07001081 // Link reductions to their final uses.
1082 for (auto i = reductions_->begin(); i != reductions_->end(); ++i) {
1083 if (i->first->IsPhi()) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001084 HInstruction* phi = i->first;
1085 HInstruction* repl = ReduceAndExtractIfNeeded(i->second);
1086 // Deal with regular uses.
1087 for (const HUseListNode<HInstruction*>& use : phi->GetUses()) {
1088 induction_range_.Replace(use.GetUser(), phi, repl); // update induction use
1089 }
1090 phi->ReplaceWith(repl);
Aart Bik0148de42017-09-05 09:25:01 -07001091 }
1092 }
1093
Aart Bikf8f5a162017-02-06 15:35:29 -08001094 // Remove the original loop by disconnecting the body block
1095 // and removing all instructions from the header.
1096 block->DisconnectAndDelete();
1097 while (!header->GetFirstInstruction()->IsGoto()) {
1098 header->RemoveInstruction(header->GetFirstInstruction());
1099 }
Aart Bikb29f6842017-07-28 15:58:41 -07001100
Aart Bik14a68b42017-06-08 14:06:58 -07001101 // Update loop hierarchy: the old header now resides in the same outer loop
1102 // as the old preheader. Note that we don't bother putting sequential
1103 // loops back in the hierarchy at this point.
Aart Bikf8f5a162017-02-06 15:35:29 -08001104 header->SetLoopInformation(preheader->GetLoopInformation()); // outward
1105 node->loop_info = vloop;
1106}
1107
1108void HLoopOptimization::GenerateNewLoop(LoopNode* node,
1109 HBasicBlock* block,
1110 HBasicBlock* new_preheader,
1111 HInstruction* lo,
1112 HInstruction* hi,
Aart Bik14a68b42017-06-08 14:06:58 -07001113 HInstruction* step,
1114 uint32_t unroll) {
1115 DCHECK(unroll == 1 || vector_mode_ == kVector);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001116 DataType::Type induc_type = lo->GetType();
Aart Bikf8f5a162017-02-06 15:35:29 -08001117 // Prepare new loop.
Aart Bikf8f5a162017-02-06 15:35:29 -08001118 vector_preheader_ = new_preheader,
1119 vector_header_ = vector_preheader_->GetSingleSuccessor();
1120 vector_body_ = vector_header_->GetSuccessors()[1];
Aart Bik14a68b42017-06-08 14:06:58 -07001121 HPhi* phi = new (global_allocator_) HPhi(global_allocator_,
1122 kNoRegNumber,
1123 0,
1124 HPhi::ToPhiType(induc_type));
Aart Bikb07d1bc2017-04-05 10:03:15 -07001125 // Generate header and prepare body.
Aart Bikf8f5a162017-02-06 15:35:29 -08001126 // for (i = lo; i < hi; i += step)
1127 // <loop-body>
Aart Bik14a68b42017-06-08 14:06:58 -07001128 HInstruction* cond = new (global_allocator_) HAboveOrEqual(phi, hi);
1129 vector_header_->AddPhi(phi);
Aart Bikf8f5a162017-02-06 15:35:29 -08001130 vector_header_->AddInstruction(cond);
1131 vector_header_->AddInstruction(new (global_allocator_) HIf(cond));
Aart Bik14a68b42017-06-08 14:06:58 -07001132 vector_index_ = phi;
Aart Bik0148de42017-09-05 09:25:01 -07001133 vector_permanent_map_->clear(); // preserved over unrolling
Aart Bik14a68b42017-06-08 14:06:58 -07001134 for (uint32_t u = 0; u < unroll; u++) {
Aart Bik14a68b42017-06-08 14:06:58 -07001135 // Generate instruction map.
Aart Bik0148de42017-09-05 09:25:01 -07001136 vector_map_->clear();
Aart Bik14a68b42017-06-08 14:06:58 -07001137 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
1138 bool vectorized_def = VectorizeDef(node, it.Current(), /*generate_code*/ true);
1139 DCHECK(vectorized_def);
1140 }
1141 // Generate body from the instruction map, but in original program order.
1142 HEnvironment* env = vector_header_->GetFirstInstruction()->GetEnvironment();
1143 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
1144 auto i = vector_map_->find(it.Current());
1145 if (i != vector_map_->end() && !i->second->IsInBlock()) {
1146 Insert(vector_body_, i->second);
1147 // Deal with instructions that need an environment, such as the scalar intrinsics.
1148 if (i->second->NeedsEnvironment()) {
1149 i->second->CopyEnvironmentFromWithLoopPhiAdjustment(env, vector_header_);
1150 }
1151 }
1152 }
Aart Bik0148de42017-09-05 09:25:01 -07001153 // Generate the induction.
Aart Bik14a68b42017-06-08 14:06:58 -07001154 vector_index_ = new (global_allocator_) HAdd(induc_type, vector_index_, step);
1155 Insert(vector_body_, vector_index_);
Aart Bikf8f5a162017-02-06 15:35:29 -08001156 }
Aart Bik0148de42017-09-05 09:25:01 -07001157 // Finalize phi inputs for the reductions (if any).
1158 for (auto i = reductions_->begin(); i != reductions_->end(); ++i) {
1159 if (!i->first->IsPhi()) {
1160 DCHECK(i->second->IsPhi());
1161 GenerateVecReductionPhiInputs(i->second->AsPhi(), i->first);
1162 }
1163 }
Aart Bikb29f6842017-07-28 15:58:41 -07001164 // Finalize phi inputs for the loop index.
Aart Bik14a68b42017-06-08 14:06:58 -07001165 phi->AddInput(lo);
1166 phi->AddInput(vector_index_);
1167 vector_index_ = phi;
Aart Bikf8f5a162017-02-06 15:35:29 -08001168}
1169
Aart Bikf8f5a162017-02-06 15:35:29 -08001170bool HLoopOptimization::VectorizeDef(LoopNode* node,
1171 HInstruction* instruction,
1172 bool generate_code) {
1173 // Accept a left-hand-side array base[index] for
1174 // (1) supported vector type,
1175 // (2) loop-invariant base,
1176 // (3) unit stride index,
1177 // (4) vectorizable right-hand-side value.
1178 uint64_t restrictions = kNone;
1179 if (instruction->IsArraySet()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001180 DataType::Type type = instruction->AsArraySet()->GetComponentType();
Aart Bikf8f5a162017-02-06 15:35:29 -08001181 HInstruction* base = instruction->InputAt(0);
1182 HInstruction* index = instruction->InputAt(1);
1183 HInstruction* value = instruction->InputAt(2);
1184 HInstruction* offset = nullptr;
1185 if (TrySetVectorType(type, &restrictions) &&
1186 node->loop_info->IsDefinedOutOfTheLoop(base) &&
Aart Bik37dc4df2017-06-28 14:08:00 -07001187 induction_range_.IsUnitStride(instruction, index, graph_, &offset) &&
Aart Bikf8f5a162017-02-06 15:35:29 -08001188 VectorizeUse(node, value, generate_code, type, restrictions)) {
1189 if (generate_code) {
1190 GenerateVecSub(index, offset);
Aart Bik14a68b42017-06-08 14:06:58 -07001191 GenerateVecMem(instruction, vector_map_->Get(index), vector_map_->Get(value), offset, type);
Aart Bikf8f5a162017-02-06 15:35:29 -08001192 } else {
1193 vector_refs_->insert(ArrayReference(base, offset, type, /*lhs*/ true));
1194 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08001195 return true;
1196 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001197 return false;
1198 }
Aart Bik0148de42017-09-05 09:25:01 -07001199 // Accept a left-hand-side reduction for
1200 // (1) supported vector type,
1201 // (2) vectorizable right-hand-side value.
1202 auto redit = reductions_->find(instruction);
1203 if (redit != reductions_->end()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001204 DataType::Type type = instruction->GetType();
Aart Bikdbbac8f2017-09-01 13:06:08 -07001205 // Recognize SAD idiom or direct reduction.
1206 if (VectorizeSADIdiom(node, instruction, generate_code, type, restrictions) ||
1207 (TrySetVectorType(type, &restrictions) &&
1208 VectorizeUse(node, instruction, generate_code, type, restrictions))) {
Aart Bik0148de42017-09-05 09:25:01 -07001209 if (generate_code) {
1210 HInstruction* new_red = vector_map_->Get(instruction);
1211 vector_permanent_map_->Put(new_red, vector_map_->Get(redit->second));
1212 vector_permanent_map_->Overwrite(redit->second, new_red);
1213 }
1214 return true;
1215 }
1216 return false;
1217 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001218 // Branch back okay.
1219 if (instruction->IsGoto()) {
1220 return true;
1221 }
1222 // Otherwise accept only expressions with no effects outside the immediate loop-body.
1223 // Note that actual uses are inspected during right-hand-side tree traversal.
1224 return !IsUsedOutsideLoop(node->loop_info, instruction) && !instruction->DoesAnyWrite();
1225}
1226
Aart Bikf8f5a162017-02-06 15:35:29 -08001227bool HLoopOptimization::VectorizeUse(LoopNode* node,
1228 HInstruction* instruction,
1229 bool generate_code,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001230 DataType::Type type,
Aart Bikf8f5a162017-02-06 15:35:29 -08001231 uint64_t restrictions) {
1232 // Accept anything for which code has already been generated.
1233 if (generate_code) {
1234 if (vector_map_->find(instruction) != vector_map_->end()) {
1235 return true;
1236 }
1237 }
1238 // Continue the right-hand-side tree traversal, passing in proper
1239 // types and vector restrictions along the way. During code generation,
1240 // all new nodes are drawn from the global allocator.
1241 if (node->loop_info->IsDefinedOutOfTheLoop(instruction)) {
1242 // Accept invariant use, using scalar expansion.
1243 if (generate_code) {
1244 GenerateVecInv(instruction, type);
1245 }
1246 return true;
1247 } else if (instruction->IsArrayGet()) {
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001248 // Deal with vector restrictions.
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001249 bool is_string_char_at = instruction->AsArrayGet()->IsStringCharAt();
1250 if (is_string_char_at && HasVectorRestrictions(restrictions, kNoStringCharAt)) {
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001251 return false;
1252 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001253 // Accept a right-hand-side array base[index] for
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001254 // (1) matching vector type (exact match or signed/unsigned integral type of the same size),
Aart Bikf8f5a162017-02-06 15:35:29 -08001255 // (2) loop-invariant base,
1256 // (3) unit stride index,
1257 // (4) vectorizable right-hand-side value.
1258 HInstruction* base = instruction->InputAt(0);
1259 HInstruction* index = instruction->InputAt(1);
1260 HInstruction* offset = nullptr;
Aart Bik46b6dbc2017-10-03 11:37:37 -07001261 if (HVecOperation::ToSignedType(type) == HVecOperation::ToSignedType(instruction->GetType()) &&
Aart Bikf8f5a162017-02-06 15:35:29 -08001262 node->loop_info->IsDefinedOutOfTheLoop(base) &&
Aart Bik37dc4df2017-06-28 14:08:00 -07001263 induction_range_.IsUnitStride(instruction, index, graph_, &offset)) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001264 if (generate_code) {
1265 GenerateVecSub(index, offset);
Aart Bik14a68b42017-06-08 14:06:58 -07001266 GenerateVecMem(instruction, vector_map_->Get(index), nullptr, offset, type);
Aart Bikf8f5a162017-02-06 15:35:29 -08001267 } else {
Aart Bik38a3f212017-10-20 17:02:21 -07001268 vector_refs_->insert(ArrayReference(base, offset, type, /*lhs*/ false, is_string_char_at));
Aart Bikf8f5a162017-02-06 15:35:29 -08001269 }
1270 return true;
1271 }
Aart Bik0148de42017-09-05 09:25:01 -07001272 } else if (instruction->IsPhi()) {
1273 // Accept particular phi operations.
1274 if (reductions_->find(instruction) != reductions_->end()) {
1275 // Deal with vector restrictions.
1276 if (HasVectorRestrictions(restrictions, kNoReduction)) {
1277 return false;
1278 }
1279 // Accept a reduction.
1280 if (generate_code) {
1281 GenerateVecReductionPhi(instruction->AsPhi());
1282 }
1283 return true;
1284 }
1285 // TODO: accept right-hand-side induction?
1286 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001287 } else if (instruction->IsTypeConversion()) {
1288 // Accept particular type conversions.
1289 HTypeConversion* conversion = instruction->AsTypeConversion();
1290 HInstruction* opa = conversion->InputAt(0);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001291 DataType::Type from = conversion->GetInputType();
1292 DataType::Type to = conversion->GetResultType();
1293 if (DataType::IsIntegralType(from) && DataType::IsIntegralType(to)) {
Aart Bik38a3f212017-10-20 17:02:21 -07001294 uint32_t size_vec = DataType::Size(type);
1295 uint32_t size_from = DataType::Size(from);
1296 uint32_t size_to = DataType::Size(to);
Aart Bikdbbac8f2017-09-01 13:06:08 -07001297 // Accept an integral conversion
1298 // (1a) narrowing into vector type, "wider" operations cannot bring in higher order bits, or
1299 // (1b) widening from at least vector type, and
1300 // (2) vectorizable operand.
1301 if ((size_to < size_from &&
1302 size_to == size_vec &&
1303 VectorizeUse(node, opa, generate_code, type, restrictions | kNoHiBits)) ||
1304 (size_to >= size_from &&
1305 size_from >= size_vec &&
Aart Bik4d1a9d42017-10-19 14:40:55 -07001306 VectorizeUse(node, opa, generate_code, type, restrictions))) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001307 if (generate_code) {
1308 if (vector_mode_ == kVector) {
1309 vector_map_->Put(instruction, vector_map_->Get(opa)); // operand pass-through
1310 } else {
1311 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1312 }
1313 }
1314 return true;
1315 }
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001316 } else if (to == DataType::Type::kFloat32 && from == DataType::Type::kInt32) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001317 DCHECK_EQ(to, type);
1318 // Accept int to float conversion for
1319 // (1) supported int,
1320 // (2) vectorizable operand.
1321 if (TrySetVectorType(from, &restrictions) &&
1322 VectorizeUse(node, opa, generate_code, from, restrictions)) {
1323 if (generate_code) {
1324 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1325 }
1326 return true;
1327 }
1328 }
1329 return false;
1330 } else if (instruction->IsNeg() || instruction->IsNot() || instruction->IsBooleanNot()) {
1331 // Accept unary operator for vectorizable operand.
1332 HInstruction* opa = instruction->InputAt(0);
1333 if (VectorizeUse(node, opa, generate_code, type, restrictions)) {
1334 if (generate_code) {
1335 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1336 }
1337 return true;
1338 }
1339 } else if (instruction->IsAdd() || instruction->IsSub() ||
1340 instruction->IsMul() || instruction->IsDiv() ||
1341 instruction->IsAnd() || instruction->IsOr() || instruction->IsXor()) {
1342 // Deal with vector restrictions.
1343 if ((instruction->IsMul() && HasVectorRestrictions(restrictions, kNoMul)) ||
1344 (instruction->IsDiv() && HasVectorRestrictions(restrictions, kNoDiv))) {
1345 return false;
1346 }
1347 // Accept binary operator for vectorizable operands.
1348 HInstruction* opa = instruction->InputAt(0);
1349 HInstruction* opb = instruction->InputAt(1);
1350 if (VectorizeUse(node, opa, generate_code, type, restrictions) &&
1351 VectorizeUse(node, opb, generate_code, type, restrictions)) {
1352 if (generate_code) {
1353 GenerateVecOp(instruction, vector_map_->Get(opa), vector_map_->Get(opb), type);
1354 }
1355 return true;
1356 }
1357 } else if (instruction->IsShl() || instruction->IsShr() || instruction->IsUShr()) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001358 // Recognize halving add idiom.
Aart Bikf3e61ee2017-04-12 17:09:20 -07001359 if (VectorizeHalvingAddIdiom(node, instruction, generate_code, type, restrictions)) {
1360 return true;
1361 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001362 // Deal with vector restrictions.
Aart Bik304c8a52017-05-23 11:01:13 -07001363 HInstruction* opa = instruction->InputAt(0);
1364 HInstruction* opb = instruction->InputAt(1);
1365 HInstruction* r = opa;
1366 bool is_unsigned = false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001367 if ((HasVectorRestrictions(restrictions, kNoShift)) ||
1368 (instruction->IsShr() && HasVectorRestrictions(restrictions, kNoShr))) {
1369 return false; // unsupported instruction
Aart Bik304c8a52017-05-23 11:01:13 -07001370 } else if (HasVectorRestrictions(restrictions, kNoHiBits)) {
1371 // Shifts right need extra care to account for higher order bits.
1372 // TODO: less likely shr/unsigned and ushr/signed can by flipping signess.
1373 if (instruction->IsShr() &&
1374 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || is_unsigned)) {
1375 return false; // reject, unless all operands are sign-extension narrower
1376 } else if (instruction->IsUShr() &&
1377 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || !is_unsigned)) {
1378 return false; // reject, unless all operands are zero-extension narrower
1379 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001380 }
1381 // Accept shift operator for vectorizable/invariant operands.
1382 // TODO: accept symbolic, albeit loop invariant shift factors.
Aart Bik304c8a52017-05-23 11:01:13 -07001383 DCHECK(r != nullptr);
1384 if (generate_code && vector_mode_ != kVector) { // de-idiom
1385 r = opa;
1386 }
Aart Bik50e20d52017-05-05 14:07:29 -07001387 int64_t distance = 0;
Aart Bik304c8a52017-05-23 11:01:13 -07001388 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
Aart Bik50e20d52017-05-05 14:07:29 -07001389 IsInt64AndGet(opb, /*out*/ &distance)) {
Aart Bik65ffd8e2017-05-01 16:50:45 -07001390 // Restrict shift distance to packed data type width.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001391 int64_t max_distance = DataType::Size(type) * 8;
Aart Bik65ffd8e2017-05-01 16:50:45 -07001392 if (0 <= distance && distance < max_distance) {
1393 if (generate_code) {
Aart Bik304c8a52017-05-23 11:01:13 -07001394 GenerateVecOp(instruction, vector_map_->Get(r), opb, type);
Aart Bik65ffd8e2017-05-01 16:50:45 -07001395 }
1396 return true;
Aart Bikf8f5a162017-02-06 15:35:29 -08001397 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001398 }
Aart Bik3b2a5952018-03-05 13:55:28 -08001399 } else if (instruction->IsAbs()) {
1400 // Deal with vector restrictions.
1401 HInstruction* opa = instruction->InputAt(0);
1402 HInstruction* r = opa;
1403 bool is_unsigned = false;
1404 if (HasVectorRestrictions(restrictions, kNoAbs)) {
1405 return false;
1406 } else if (HasVectorRestrictions(restrictions, kNoHiBits) &&
1407 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || is_unsigned)) {
1408 return false; // reject, unless operand is sign-extension narrower
1409 }
1410 // Accept ABS(x) for vectorizable operand.
1411 DCHECK(r != nullptr);
1412 if (generate_code && vector_mode_ != kVector) { // de-idiom
1413 r = opa;
1414 }
1415 if (VectorizeUse(node, r, generate_code, type, restrictions)) {
1416 if (generate_code) {
1417 GenerateVecOp(instruction,
1418 vector_map_->Get(r),
1419 nullptr,
1420 HVecOperation::ToProperType(type, is_unsigned));
1421 }
1422 return true;
1423 }
Aart Bik1f8d51b2018-02-15 10:42:37 -08001424 } else if (instruction->IsMin() || instruction->IsMax()) {
Aart Bik29aa0822018-03-08 11:28:00 -08001425 // Recognize saturation arithmetic.
1426 if (VectorizeSaturationIdiom(node, instruction, generate_code, type, restrictions)) {
1427 return true;
1428 }
Aart Bik1f8d51b2018-02-15 10:42:37 -08001429 // Deal with vector restrictions.
1430 HInstruction* opa = instruction->InputAt(0);
1431 HInstruction* opb = instruction->InputAt(1);
1432 HInstruction* r = opa;
1433 HInstruction* s = opb;
1434 bool is_unsigned = false;
1435 if (HasVectorRestrictions(restrictions, kNoMinMax)) {
1436 return false;
1437 } else if (HasVectorRestrictions(restrictions, kNoHiBits) &&
1438 !IsNarrowerOperands(opa, opb, type, &r, &s, &is_unsigned)) {
1439 return false; // reject, unless all operands are same-extension narrower
1440 }
1441 // Accept MIN/MAX(x, y) for vectorizable operands.
1442 DCHECK(r != nullptr);
1443 DCHECK(s != nullptr);
1444 if (generate_code && vector_mode_ != kVector) { // de-idiom
1445 r = opa;
1446 s = opb;
1447 }
1448 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
1449 VectorizeUse(node, s, generate_code, type, restrictions)) {
1450 if (generate_code) {
1451 GenerateVecOp(
1452 instruction, vector_map_->Get(r), vector_map_->Get(s), type, is_unsigned);
Aart Bikc8e93c72017-05-10 10:49:22 -07001453 }
Aart Bik1f8d51b2018-02-15 10:42:37 -08001454 return true;
1455 }
Aart Bik281c6812016-08-26 11:31:48 -07001456 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08001457 return false;
Aart Bik281c6812016-08-26 11:31:48 -07001458}
1459
Aart Bik38a3f212017-10-20 17:02:21 -07001460uint32_t HLoopOptimization::GetVectorSizeInBytes() {
1461 switch (compiler_driver_->GetInstructionSet()) {
Vladimir Marko33bff252017-11-01 14:35:42 +00001462 case InstructionSet::kArm:
1463 case InstructionSet::kThumb2:
Aart Bik38a3f212017-10-20 17:02:21 -07001464 return 8; // 64-bit SIMD
1465 default:
1466 return 16; // 128-bit SIMD
1467 }
1468}
1469
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001470bool HLoopOptimization::TrySetVectorType(DataType::Type type, uint64_t* restrictions) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001471 const InstructionSetFeatures* features = compiler_driver_->GetInstructionSetFeatures();
1472 switch (compiler_driver_->GetInstructionSet()) {
Vladimir Marko33bff252017-11-01 14:35:42 +00001473 case InstructionSet::kArm:
1474 case InstructionSet::kThumb2:
Artem Serov8f7c4102017-06-21 11:21:37 +01001475 // Allow vectorization for all ARM devices, because Android assumes that
Aart Bikb29f6842017-07-28 15:58:41 -07001476 // ARM 32-bit always supports advanced SIMD (64-bit SIMD).
Artem Serov8f7c4102017-06-21 11:21:37 +01001477 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001478 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001479 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001480 case DataType::Type::kInt8:
Aart Bik0148de42017-09-05 09:25:01 -07001481 *restrictions |= kNoDiv | kNoReduction;
Artem Serov8f7c4102017-06-21 11:21:37 +01001482 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001483 case DataType::Type::kUint16:
1484 case DataType::Type::kInt16:
Aart Bik0148de42017-09-05 09:25:01 -07001485 *restrictions |= kNoDiv | kNoStringCharAt | kNoReduction;
Artem Serov8f7c4102017-06-21 11:21:37 +01001486 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001487 case DataType::Type::kInt32:
Artem Serov6e9b1372017-10-05 16:48:30 +01001488 *restrictions |= kNoDiv | kNoWideSAD;
Artem Serov8f7c4102017-06-21 11:21:37 +01001489 return TrySetVectorLength(2);
1490 default:
1491 break;
1492 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001493 return false;
Vladimir Marko33bff252017-11-01 14:35:42 +00001494 case InstructionSet::kArm64:
Aart Bikf8f5a162017-02-06 15:35:29 -08001495 // Allow vectorization for all ARM devices, because Android assumes that
Aart Bikb29f6842017-07-28 15:58:41 -07001496 // ARMv8 AArch64 always supports advanced SIMD (128-bit SIMD).
Aart Bikf8f5a162017-02-06 15:35:29 -08001497 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001498 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001499 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001500 case DataType::Type::kInt8:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001501 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +01001502 return TrySetVectorLength(16);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001503 case DataType::Type::kUint16:
1504 case DataType::Type::kInt16:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001505 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +01001506 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001507 case DataType::Type::kInt32:
Aart Bikf8f5a162017-02-06 15:35:29 -08001508 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +01001509 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001510 case DataType::Type::kInt64:
Aart Bikc8e93c72017-05-10 10:49:22 -07001511 *restrictions |= kNoDiv | kNoMul | kNoMinMax;
Aart Bikf8f5a162017-02-06 15:35:29 -08001512 return TrySetVectorLength(2);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001513 case DataType::Type::kFloat32:
Aart Bik0148de42017-09-05 09:25:01 -07001514 *restrictions |= kNoReduction;
Artem Serovd4bccf12017-04-03 18:47:32 +01001515 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001516 case DataType::Type::kFloat64:
Aart Bik0148de42017-09-05 09:25:01 -07001517 *restrictions |= kNoReduction;
Aart Bikf8f5a162017-02-06 15:35:29 -08001518 return TrySetVectorLength(2);
1519 default:
1520 return false;
1521 }
Vladimir Marko33bff252017-11-01 14:35:42 +00001522 case InstructionSet::kX86:
1523 case InstructionSet::kX86_64:
Aart Bikb29f6842017-07-28 15:58:41 -07001524 // Allow vectorization for SSE4.1-enabled X86 devices only (128-bit SIMD).
Aart Bikf8f5a162017-02-06 15:35:29 -08001525 if (features->AsX86InstructionSetFeatures()->HasSSE4_1()) {
1526 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001527 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001528 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001529 case DataType::Type::kInt8:
Aart Bik0148de42017-09-05 09:25:01 -07001530 *restrictions |=
Aart Bikdbbac8f2017-09-01 13:06:08 -07001531 kNoMul | kNoDiv | kNoShift | kNoAbs | kNoSignedHAdd | kNoUnroundedHAdd | kNoSAD;
Aart Bikf8f5a162017-02-06 15:35:29 -08001532 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 | kNoAbs | kNoSignedHAdd | kNoUnroundedHAdd | kNoSAD;
Aart Bikf8f5a162017-02-06 15:35:29 -08001536 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001537 case DataType::Type::kInt32:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001538 *restrictions |= kNoDiv | kNoSAD;
Aart Bikf8f5a162017-02-06 15:35:29 -08001539 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001540 case DataType::Type::kInt64:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001541 *restrictions |= kNoMul | kNoDiv | kNoShr | kNoAbs | kNoMinMax | kNoSAD;
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 |= kNoMinMax | kNoReduction; // minmax: -0.0 vs +0.0
Aart Bikf8f5a162017-02-06 15:35:29 -08001545 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001546 case DataType::Type::kFloat64:
Aart Bik0148de42017-09-05 09:25:01 -07001547 *restrictions |= kNoMinMax | kNoReduction; // minmax: -0.0 vs +0.0
Aart Bikf8f5a162017-02-06 15:35:29 -08001548 return TrySetVectorLength(2);
1549 default:
1550 break;
1551 } // switch type
1552 }
1553 return false;
Vladimir Marko33bff252017-11-01 14:35:42 +00001554 case InstructionSet::kMips:
Lena Djokic51765b02017-06-22 13:49:59 +02001555 if (features->AsMipsInstructionSetFeatures()->HasMsa()) {
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 Bik29aa0822018-03-08 11:28:00 -08001560 *restrictions |= kNoDiv | kNoSaturation;
Lena Djokic51765b02017-06-22 13:49:59 +02001561 return TrySetVectorLength(16);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001562 case DataType::Type::kUint16:
1563 case DataType::Type::kInt16:
Aart Bik29aa0822018-03-08 11:28:00 -08001564 *restrictions |= kNoDiv | kNoSaturation | kNoStringCharAt;
Lena Djokic51765b02017-06-22 13:49:59 +02001565 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001566 case DataType::Type::kInt32:
Lena Djokic38e380b2017-10-30 16:17:10 +01001567 *restrictions |= kNoDiv;
Lena Djokic51765b02017-06-22 13:49:59 +02001568 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001569 case DataType::Type::kInt64:
Lena Djokic38e380b2017-10-30 16:17:10 +01001570 *restrictions |= kNoDiv;
Lena Djokic51765b02017-06-22 13:49:59 +02001571 return TrySetVectorLength(2);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001572 case DataType::Type::kFloat32:
Aart Bik0148de42017-09-05 09:25:01 -07001573 *restrictions |= kNoMinMax | kNoReduction; // min/max(x, NaN)
Lena Djokic51765b02017-06-22 13:49:59 +02001574 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001575 case DataType::Type::kFloat64:
Aart Bik0148de42017-09-05 09:25:01 -07001576 *restrictions |= kNoMinMax | kNoReduction; // min/max(x, NaN)
Lena Djokic51765b02017-06-22 13:49:59 +02001577 return TrySetVectorLength(2);
1578 default:
1579 break;
1580 } // switch type
1581 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001582 return false;
Vladimir Marko33bff252017-11-01 14:35:42 +00001583 case InstructionSet::kMips64:
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001584 if (features->AsMips64InstructionSetFeatures()->HasMsa()) {
1585 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001586 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001587 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001588 case DataType::Type::kInt8:
Aart Bik29aa0822018-03-08 11:28:00 -08001589 *restrictions |= kNoDiv | kNoSaturation;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001590 return TrySetVectorLength(16);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001591 case DataType::Type::kUint16:
1592 case DataType::Type::kInt16:
Aart Bik29aa0822018-03-08 11:28:00 -08001593 *restrictions |= kNoDiv | kNoSaturation | kNoStringCharAt;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001594 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001595 case DataType::Type::kInt32:
Lena Djokic38e380b2017-10-30 16:17:10 +01001596 *restrictions |= kNoDiv;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001597 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001598 case DataType::Type::kInt64:
Lena Djokic38e380b2017-10-30 16:17:10 +01001599 *restrictions |= kNoDiv;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001600 return TrySetVectorLength(2);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001601 case DataType::Type::kFloat32:
Aart Bik0148de42017-09-05 09:25:01 -07001602 *restrictions |= kNoMinMax | kNoReduction; // min/max(x, NaN)
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001603 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001604 case DataType::Type::kFloat64:
Aart Bik0148de42017-09-05 09:25:01 -07001605 *restrictions |= kNoMinMax | kNoReduction; // min/max(x, NaN)
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001606 return TrySetVectorLength(2);
1607 default:
1608 break;
1609 } // switch type
1610 }
1611 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001612 default:
1613 return false;
1614 } // switch instruction set
1615}
1616
1617bool HLoopOptimization::TrySetVectorLength(uint32_t length) {
1618 DCHECK(IsPowerOfTwo(length) && length >= 2u);
1619 // First time set?
1620 if (vector_length_ == 0) {
1621 vector_length_ = length;
1622 }
1623 // Different types are acceptable within a loop-body, as long as all the corresponding vector
1624 // lengths match exactly to obtain a uniform traversal through the vector iteration space
1625 // (idiomatic exceptions to this rule can be handled by further unrolling sub-expressions).
1626 return vector_length_ == length;
1627}
1628
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001629void HLoopOptimization::GenerateVecInv(HInstruction* org, DataType::Type type) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001630 if (vector_map_->find(org) == vector_map_->end()) {
1631 // In scalar code, just use a self pass-through for scalar invariants
1632 // (viz. expression remains itself).
1633 if (vector_mode_ == kSequential) {
1634 vector_map_->Put(org, org);
1635 return;
1636 }
1637 // In vector code, explicit scalar expansion is needed.
Aart Bik0148de42017-09-05 09:25:01 -07001638 HInstruction* vector = nullptr;
1639 auto it = vector_permanent_map_->find(org);
1640 if (it != vector_permanent_map_->end()) {
1641 vector = it->second; // reuse during unrolling
1642 } else {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001643 // Generates ReplicateScalar( (optional_type_conv) org ).
1644 HInstruction* input = org;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001645 DataType::Type input_type = input->GetType();
1646 if (type != input_type && (type == DataType::Type::kInt64 ||
1647 input_type == DataType::Type::kInt64)) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001648 input = Insert(vector_preheader_,
1649 new (global_allocator_) HTypeConversion(type, input, kNoDexPc));
1650 }
1651 vector = new (global_allocator_)
Aart Bik46b6dbc2017-10-03 11:37:37 -07001652 HVecReplicateScalar(global_allocator_, input, type, vector_length_, kNoDexPc);
Aart Bik0148de42017-09-05 09:25:01 -07001653 vector_permanent_map_->Put(org, Insert(vector_preheader_, vector));
1654 }
1655 vector_map_->Put(org, vector);
Aart Bikf8f5a162017-02-06 15:35:29 -08001656 }
1657}
1658
1659void HLoopOptimization::GenerateVecSub(HInstruction* org, HInstruction* offset) {
1660 if (vector_map_->find(org) == vector_map_->end()) {
Aart Bik14a68b42017-06-08 14:06:58 -07001661 HInstruction* subscript = vector_index_;
Aart Bik37dc4df2017-06-28 14:08:00 -07001662 int64_t value = 0;
1663 if (!IsInt64AndGet(offset, &value) || value != 0) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001664 subscript = new (global_allocator_) HAdd(DataType::Type::kInt32, subscript, offset);
Aart Bikf8f5a162017-02-06 15:35:29 -08001665 if (org->IsPhi()) {
1666 Insert(vector_body_, subscript); // lacks layout placeholder
1667 }
1668 }
1669 vector_map_->Put(org, subscript);
1670 }
1671}
1672
1673void HLoopOptimization::GenerateVecMem(HInstruction* org,
1674 HInstruction* opa,
1675 HInstruction* opb,
Aart Bik14a68b42017-06-08 14:06:58 -07001676 HInstruction* offset,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001677 DataType::Type type) {
Aart Bik46b6dbc2017-10-03 11:37:37 -07001678 uint32_t dex_pc = org->GetDexPc();
Aart Bikf8f5a162017-02-06 15:35:29 -08001679 HInstruction* vector = nullptr;
1680 if (vector_mode_ == kVector) {
1681 // Vector store or load.
Aart Bik38a3f212017-10-20 17:02:21 -07001682 bool is_string_char_at = false;
Aart Bik14a68b42017-06-08 14:06:58 -07001683 HInstruction* base = org->InputAt(0);
Aart Bikf8f5a162017-02-06 15:35:29 -08001684 if (opb != nullptr) {
1685 vector = new (global_allocator_) HVecStore(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001686 global_allocator_, base, opa, opb, type, org->GetSideEffects(), vector_length_, dex_pc);
Aart Bikf8f5a162017-02-06 15:35:29 -08001687 } else {
Aart Bik38a3f212017-10-20 17:02:21 -07001688 is_string_char_at = org->AsArrayGet()->IsStringCharAt();
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001689 vector = new (global_allocator_) HVecLoad(global_allocator_,
1690 base,
1691 opa,
1692 type,
1693 org->GetSideEffects(),
1694 vector_length_,
Aart Bik46b6dbc2017-10-03 11:37:37 -07001695 is_string_char_at,
1696 dex_pc);
Aart Bik14a68b42017-06-08 14:06:58 -07001697 }
Aart Bik38a3f212017-10-20 17:02:21 -07001698 // Known (forced/adjusted/original) alignment?
1699 if (vector_dynamic_peeling_candidate_ != nullptr) {
1700 if (vector_dynamic_peeling_candidate_->offset == offset && // TODO: diffs too?
1701 DataType::Size(vector_dynamic_peeling_candidate_->type) == DataType::Size(type) &&
1702 vector_dynamic_peeling_candidate_->is_string_char_at == is_string_char_at) {
1703 vector->AsVecMemoryOperation()->SetAlignment( // forced
1704 Alignment(GetVectorSizeInBytes(), 0));
1705 }
1706 } else {
1707 vector->AsVecMemoryOperation()->SetAlignment( // adjusted/original
1708 ComputeAlignment(offset, type, is_string_char_at, vector_static_peeling_factor_));
Aart Bikf8f5a162017-02-06 15:35:29 -08001709 }
1710 } else {
1711 // Scalar store or load.
1712 DCHECK(vector_mode_ == kSequential);
1713 if (opb != nullptr) {
Aart Bik4d1a9d42017-10-19 14:40:55 -07001714 DataType::Type component_type = org->AsArraySet()->GetComponentType();
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001715 vector = new (global_allocator_) HArraySet(
Aart Bik4d1a9d42017-10-19 14:40:55 -07001716 org->InputAt(0), opa, opb, component_type, org->GetSideEffects(), dex_pc);
Aart Bikf8f5a162017-02-06 15:35:29 -08001717 } else {
Aart Bikdb14fcf2017-04-25 15:53:58 -07001718 bool is_string_char_at = org->AsArrayGet()->IsStringCharAt();
1719 vector = new (global_allocator_) HArrayGet(
Aart Bik4d1a9d42017-10-19 14:40:55 -07001720 org->InputAt(0), opa, org->GetType(), org->GetSideEffects(), dex_pc, is_string_char_at);
Aart Bikf8f5a162017-02-06 15:35:29 -08001721 }
1722 }
1723 vector_map_->Put(org, vector);
1724}
1725
Aart Bik0148de42017-09-05 09:25:01 -07001726void HLoopOptimization::GenerateVecReductionPhi(HPhi* phi) {
1727 DCHECK(reductions_->find(phi) != reductions_->end());
1728 DCHECK(reductions_->Get(phi->InputAt(1)) == phi);
1729 HInstruction* vector = nullptr;
1730 if (vector_mode_ == kSequential) {
1731 HPhi* new_phi = new (global_allocator_) HPhi(
1732 global_allocator_, kNoRegNumber, 0, phi->GetType());
1733 vector_header_->AddPhi(new_phi);
1734 vector = new_phi;
1735 } else {
1736 // Link vector reduction back to prior unrolled update, or a first phi.
1737 auto it = vector_permanent_map_->find(phi);
1738 if (it != vector_permanent_map_->end()) {
1739 vector = it->second;
1740 } else {
1741 HPhi* new_phi = new (global_allocator_) HPhi(
1742 global_allocator_, kNoRegNumber, 0, HVecOperation::kSIMDType);
1743 vector_header_->AddPhi(new_phi);
1744 vector = new_phi;
1745 }
1746 }
1747 vector_map_->Put(phi, vector);
1748}
1749
1750void HLoopOptimization::GenerateVecReductionPhiInputs(HPhi* phi, HInstruction* reduction) {
1751 HInstruction* new_phi = vector_map_->Get(phi);
1752 HInstruction* new_init = reductions_->Get(phi);
1753 HInstruction* new_red = vector_map_->Get(reduction);
1754 // Link unrolled vector loop back to new phi.
1755 for (; !new_phi->IsPhi(); new_phi = vector_permanent_map_->Get(new_phi)) {
1756 DCHECK(new_phi->IsVecOperation());
1757 }
1758 // Prepare the new initialization.
1759 if (vector_mode_ == kVector) {
Goran Jakovljevic89b8df02017-10-13 08:33:17 +02001760 // Generate a [initial, 0, .., 0] vector for add or
1761 // a [initial, initial, .., initial] vector for min/max.
Aart Bikdbbac8f2017-09-01 13:06:08 -07001762 HVecOperation* red_vector = new_red->AsVecOperation();
Goran Jakovljevic89b8df02017-10-13 08:33:17 +02001763 HVecReduce::ReductionKind kind = GetReductionKind(red_vector);
Aart Bik38a3f212017-10-20 17:02:21 -07001764 uint32_t vector_length = red_vector->GetVectorLength();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001765 DataType::Type type = red_vector->GetPackedType();
Goran Jakovljevic89b8df02017-10-13 08:33:17 +02001766 if (kind == HVecReduce::ReductionKind::kSum) {
1767 new_init = Insert(vector_preheader_,
1768 new (global_allocator_) HVecSetScalars(global_allocator_,
1769 &new_init,
1770 type,
1771 vector_length,
1772 1,
1773 kNoDexPc));
1774 } else {
1775 new_init = Insert(vector_preheader_,
1776 new (global_allocator_) HVecReplicateScalar(global_allocator_,
1777 new_init,
1778 type,
1779 vector_length,
1780 kNoDexPc));
1781 }
Aart Bik0148de42017-09-05 09:25:01 -07001782 } else {
1783 new_init = ReduceAndExtractIfNeeded(new_init);
1784 }
1785 // Set the phi inputs.
1786 DCHECK(new_phi->IsPhi());
1787 new_phi->AsPhi()->AddInput(new_init);
1788 new_phi->AsPhi()->AddInput(new_red);
1789 // New feed value for next phi (safe mutation in iteration).
1790 reductions_->find(phi)->second = new_phi;
1791}
1792
1793HInstruction* HLoopOptimization::ReduceAndExtractIfNeeded(HInstruction* instruction) {
1794 if (instruction->IsPhi()) {
1795 HInstruction* input = instruction->InputAt(1);
Aart Bik2dd7b672017-12-07 11:11:22 -08001796 if (HVecOperation::ReturnsSIMDValue(input)) {
1797 DCHECK(!input->IsPhi());
Aart Bikdbbac8f2017-09-01 13:06:08 -07001798 HVecOperation* input_vector = input->AsVecOperation();
Aart Bik38a3f212017-10-20 17:02:21 -07001799 uint32_t vector_length = input_vector->GetVectorLength();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001800 DataType::Type type = input_vector->GetPackedType();
Aart Bikdbbac8f2017-09-01 13:06:08 -07001801 HVecReduce::ReductionKind kind = GetReductionKind(input_vector);
Aart Bik0148de42017-09-05 09:25:01 -07001802 HBasicBlock* exit = instruction->GetBlock()->GetSuccessors()[0];
1803 // Generate a vector reduction and scalar extract
1804 // x = REDUCE( [x_1, .., x_n] )
1805 // y = x_1
1806 // along the exit of the defining loop.
Aart Bik0148de42017-09-05 09:25:01 -07001807 HInstruction* reduce = new (global_allocator_) HVecReduce(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001808 global_allocator_, instruction, type, vector_length, kind, kNoDexPc);
Aart Bik0148de42017-09-05 09:25:01 -07001809 exit->InsertInstructionBefore(reduce, exit->GetFirstInstruction());
1810 instruction = new (global_allocator_) HVecExtractScalar(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001811 global_allocator_, reduce, type, vector_length, 0, kNoDexPc);
Aart Bik0148de42017-09-05 09:25:01 -07001812 exit->InsertInstructionAfter(instruction, reduce);
1813 }
1814 }
1815 return instruction;
1816}
1817
Aart Bikf8f5a162017-02-06 15:35:29 -08001818#define GENERATE_VEC(x, y) \
1819 if (vector_mode_ == kVector) { \
1820 vector = (x); \
1821 } else { \
1822 DCHECK(vector_mode_ == kSequential); \
1823 vector = (y); \
1824 } \
1825 break;
1826
1827void HLoopOptimization::GenerateVecOp(HInstruction* org,
1828 HInstruction* opa,
1829 HInstruction* opb,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001830 DataType::Type type,
Aart Bik304c8a52017-05-23 11:01:13 -07001831 bool is_unsigned) {
Aart Bik46b6dbc2017-10-03 11:37:37 -07001832 uint32_t dex_pc = org->GetDexPc();
Aart Bikf8f5a162017-02-06 15:35:29 -08001833 HInstruction* vector = nullptr;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001834 DataType::Type org_type = org->GetType();
Aart Bikf8f5a162017-02-06 15:35:29 -08001835 switch (org->GetKind()) {
1836 case HInstruction::kNeg:
1837 DCHECK(opb == nullptr);
1838 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001839 new (global_allocator_) HVecNeg(global_allocator_, opa, type, vector_length_, dex_pc),
1840 new (global_allocator_) HNeg(org_type, opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001841 case HInstruction::kNot:
1842 DCHECK(opb == nullptr);
1843 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001844 new (global_allocator_) HVecNot(global_allocator_, opa, type, vector_length_, dex_pc),
1845 new (global_allocator_) HNot(org_type, opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001846 case HInstruction::kBooleanNot:
1847 DCHECK(opb == nullptr);
1848 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001849 new (global_allocator_) HVecNot(global_allocator_, opa, type, vector_length_, dex_pc),
1850 new (global_allocator_) HBooleanNot(opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001851 case HInstruction::kTypeConversion:
1852 DCHECK(opb == nullptr);
1853 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001854 new (global_allocator_) HVecCnv(global_allocator_, opa, type, vector_length_, dex_pc),
1855 new (global_allocator_) HTypeConversion(org_type, opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001856 case HInstruction::kAdd:
1857 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001858 new (global_allocator_) HVecAdd(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1859 new (global_allocator_) HAdd(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001860 case HInstruction::kSub:
1861 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001862 new (global_allocator_) HVecSub(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1863 new (global_allocator_) HSub(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001864 case HInstruction::kMul:
1865 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001866 new (global_allocator_) HVecMul(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1867 new (global_allocator_) HMul(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001868 case HInstruction::kDiv:
1869 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001870 new (global_allocator_) HVecDiv(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1871 new (global_allocator_) HDiv(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001872 case HInstruction::kAnd:
1873 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001874 new (global_allocator_) HVecAnd(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1875 new (global_allocator_) HAnd(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001876 case HInstruction::kOr:
1877 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001878 new (global_allocator_) HVecOr(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1879 new (global_allocator_) HOr(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001880 case HInstruction::kXor:
1881 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001882 new (global_allocator_) HVecXor(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1883 new (global_allocator_) HXor(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001884 case HInstruction::kShl:
1885 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001886 new (global_allocator_) HVecShl(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1887 new (global_allocator_) HShl(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001888 case HInstruction::kShr:
1889 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001890 new (global_allocator_) HVecShr(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1891 new (global_allocator_) HShr(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001892 case HInstruction::kUShr:
1893 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001894 new (global_allocator_) HVecUShr(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1895 new (global_allocator_) HUShr(org_type, opa, opb, dex_pc));
Aart Bik1f8d51b2018-02-15 10:42:37 -08001896 case HInstruction::kMin:
1897 GENERATE_VEC(
1898 new (global_allocator_) HVecMin(global_allocator_,
1899 opa,
1900 opb,
1901 HVecOperation::ToProperType(type, is_unsigned),
1902 vector_length_,
1903 dex_pc),
1904 new (global_allocator_) HMin(org_type, opa, opb, dex_pc));
1905 case HInstruction::kMax:
1906 GENERATE_VEC(
1907 new (global_allocator_) HVecMax(global_allocator_,
1908 opa,
1909 opb,
1910 HVecOperation::ToProperType(type, is_unsigned),
1911 vector_length_,
1912 dex_pc),
1913 new (global_allocator_) HMax(org_type, opa, opb, dex_pc));
Aart Bik3b2a5952018-03-05 13:55:28 -08001914 case HInstruction::kAbs:
1915 DCHECK(opb == nullptr);
1916 GENERATE_VEC(
1917 new (global_allocator_) HVecAbs(global_allocator_, opa, type, vector_length_, dex_pc),
1918 new (global_allocator_) HAbs(org_type, opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001919 default:
1920 break;
1921 } // switch
1922 CHECK(vector != nullptr) << "Unsupported SIMD operator";
1923 vector_map_->Put(org, vector);
1924}
1925
1926#undef GENERATE_VEC
1927
1928//
Aart Bikf3e61ee2017-04-12 17:09:20 -07001929// Vectorization idioms.
1930//
1931
Aart Bik29aa0822018-03-08 11:28:00 -08001932// Method recognizes single and double clipping saturation arithmetic.
1933bool HLoopOptimization::VectorizeSaturationIdiom(LoopNode* node,
1934 HInstruction* instruction,
1935 bool generate_code,
1936 DataType::Type type,
1937 uint64_t restrictions) {
1938 // Deal with vector restrictions.
1939 if (HasVectorRestrictions(restrictions, kNoSaturation)) {
1940 return false;
1941 }
Aart Bik1a381022018-03-15 15:51:37 -07001942 // Restrict type (generalize if one day we generalize allowed MIN/MAX integral types).
1943 if (instruction->GetType() != DataType::Type::kInt32 &&
1944 instruction->GetType() != DataType::Type::kInt64) {
Aart Bik29aa0822018-03-08 11:28:00 -08001945 return false;
1946 }
Aart Bik29aa0822018-03-08 11:28:00 -08001947 // Clipped addition or subtraction?
Aart Bik1a381022018-03-15 15:51:37 -07001948 int64_t lo = std::numeric_limits<int64_t>::min();
1949 int64_t hi = std::numeric_limits<int64_t>::max();
1950 HInstruction* clippee = FindClippee(instruction, &lo, &hi);
Aart Bik29aa0822018-03-08 11:28:00 -08001951 bool is_add = true;
1952 if (clippee->IsAdd()) {
1953 is_add = true;
1954 } else if (clippee->IsSub()) {
1955 is_add = false;
1956 } else {
1957 return false; // clippee is not add/sub
1958 }
1959 // Addition or subtraction on narrower operands?
1960 HInstruction* r = nullptr;
1961 HInstruction* s = nullptr;
1962 bool is_unsigned = false;
1963 if (IsNarrowerOperands(clippee->InputAt(0), clippee->InputAt(1), type, &r, &s, &is_unsigned) &&
Aart Bik5a392762018-03-16 10:27:44 -07001964 (is_add ? IsSaturatedAdd(clippee, type, lo, hi, is_unsigned)
1965 : IsSaturatedSub(clippee, type, lo, hi, is_unsigned))) {
Aart Bik29aa0822018-03-08 11:28:00 -08001966 DCHECK(r != nullptr);
1967 DCHECK(s != nullptr);
1968 } else {
1969 return false;
1970 }
1971 // Accept saturation idiom for vectorizable operands.
1972 if (generate_code && vector_mode_ != kVector) { // de-idiom
1973 r = instruction->InputAt(0);
1974 s = instruction->InputAt(1);
1975 restrictions &= ~(kNoHiBits | kNoMinMax); // allow narrow MIN/MAX in seq
1976 }
1977 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
1978 VectorizeUse(node, s, generate_code, type, restrictions)) {
1979 if (generate_code) {
1980 if (vector_mode_ == kVector) {
1981 DataType::Type vtype = HVecOperation::ToProperType(type, is_unsigned);
1982 HInstruction* op1 = vector_map_->Get(r);
1983 HInstruction* op2 = vector_map_->Get(s);
1984 vector_map_->Put(instruction, is_add
1985 ? reinterpret_cast<HInstruction*>(new (global_allocator_) HVecSaturationAdd(
1986 global_allocator_, op1, op2, vtype, vector_length_, kNoDexPc))
1987 : reinterpret_cast<HInstruction*>(new (global_allocator_) HVecSaturationSub(
1988 global_allocator_, op1, op2, vtype, vector_length_, kNoDexPc)));
1989 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorizedIdiom);
1990 } else {
1991 GenerateVecOp(instruction, vector_map_->Get(r), vector_map_->Get(s), type);
1992 }
1993 }
1994 return true;
1995 }
1996 return false;
1997}
1998
Aart Bikf3e61ee2017-04-12 17:09:20 -07001999// Method recognizes the following idioms:
Aart Bikdbbac8f2017-09-01 13:06:08 -07002000// rounding halving add (a + b + 1) >> 1 for unsigned/signed operands a, b
2001// truncated halving add (a + b) >> 1 for unsigned/signed operands a, b
Aart Bikf3e61ee2017-04-12 17:09:20 -07002002// Provided that the operands are promoted to a wider form to do the arithmetic and
2003// then cast back to narrower form, the idioms can be mapped into efficient SIMD
2004// implementation that operates directly in narrower form (plus one extra bit).
2005// TODO: current version recognizes implicit byte/short/char widening only;
2006// explicit widening from int to long could be added later.
2007bool HLoopOptimization::VectorizeHalvingAddIdiom(LoopNode* node,
2008 HInstruction* instruction,
2009 bool generate_code,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002010 DataType::Type type,
Aart Bikf3e61ee2017-04-12 17:09:20 -07002011 uint64_t restrictions) {
2012 // Test for top level arithmetic shift right x >> 1 or logical shift right x >>> 1
Aart Bik304c8a52017-05-23 11:01:13 -07002013 // (note whether the sign bit in wider precision is shifted in has no effect
Aart Bikf3e61ee2017-04-12 17:09:20 -07002014 // on the narrow precision computed by the idiom).
Aart Bikf3e61ee2017-04-12 17:09:20 -07002015 if ((instruction->IsShr() ||
2016 instruction->IsUShr()) &&
Aart Bik0148de42017-09-05 09:25:01 -07002017 IsInt64Value(instruction->InputAt(1), 1)) {
Aart Bik5f805002017-05-16 16:42:41 -07002018 // Test for (a + b + c) >> 1 for optional constant c.
2019 HInstruction* a = nullptr;
2020 HInstruction* b = nullptr;
2021 int64_t c = 0;
2022 if (IsAddConst(instruction->InputAt(0), /*out*/ &a, /*out*/ &b, /*out*/ &c)) {
Aart Bik304c8a52017-05-23 11:01:13 -07002023 DCHECK(a != nullptr && b != nullptr);
Aart Bik5f805002017-05-16 16:42:41 -07002024 // Accept c == 1 (rounded) or c == 0 (not rounded).
2025 bool is_rounded = false;
2026 if (c == 1) {
2027 is_rounded = true;
2028 } else if (c != 0) {
2029 return false;
2030 }
2031 // Accept consistent zero or sign extension on operands a and b.
Aart Bikf3e61ee2017-04-12 17:09:20 -07002032 HInstruction* r = nullptr;
2033 HInstruction* s = nullptr;
2034 bool is_unsigned = false;
Aart Bik304c8a52017-05-23 11:01:13 -07002035 if (!IsNarrowerOperands(a, b, type, &r, &s, &is_unsigned)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -07002036 return false;
2037 }
2038 // Deal with vector restrictions.
2039 if ((!is_unsigned && HasVectorRestrictions(restrictions, kNoSignedHAdd)) ||
2040 (!is_rounded && HasVectorRestrictions(restrictions, kNoUnroundedHAdd))) {
2041 return false;
2042 }
2043 // Accept recognized halving add for vectorizable operands. Vectorized code uses the
2044 // shorthand idiomatic operation. Sequential code uses the original scalar expressions.
Aart Bikdbbac8f2017-09-01 13:06:08 -07002045 DCHECK(r != nullptr);
2046 DCHECK(s != nullptr);
Aart Bik304c8a52017-05-23 11:01:13 -07002047 if (generate_code && vector_mode_ != kVector) { // de-idiom
2048 r = instruction->InputAt(0);
2049 s = instruction->InputAt(1);
2050 }
Aart Bikf3e61ee2017-04-12 17:09:20 -07002051 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
2052 VectorizeUse(node, s, generate_code, type, restrictions)) {
2053 if (generate_code) {
2054 if (vector_mode_ == kVector) {
2055 vector_map_->Put(instruction, new (global_allocator_) HVecHalvingAdd(
2056 global_allocator_,
2057 vector_map_->Get(r),
2058 vector_map_->Get(s),
Aart Bik66c158e2018-01-31 12:55:04 -08002059 HVecOperation::ToProperType(type, is_unsigned),
Aart Bikf3e61ee2017-04-12 17:09:20 -07002060 vector_length_,
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01002061 is_rounded,
Aart Bik46b6dbc2017-10-03 11:37:37 -07002062 kNoDexPc));
Aart Bik21b85922017-09-06 13:29:16 -07002063 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorizedIdiom);
Aart Bikf3e61ee2017-04-12 17:09:20 -07002064 } else {
Aart Bik304c8a52017-05-23 11:01:13 -07002065 GenerateVecOp(instruction, vector_map_->Get(r), vector_map_->Get(s), type);
Aart Bikf3e61ee2017-04-12 17:09:20 -07002066 }
2067 }
2068 return true;
2069 }
2070 }
2071 }
2072 return false;
2073}
2074
Aart Bikdbbac8f2017-09-01 13:06:08 -07002075// Method recognizes the following idiom:
2076// q += ABS(a - b) for signed operands a, b
2077// Provided that the operands have the same type or are promoted to a wider form.
2078// Since this may involve a vector length change, the idiom is handled by going directly
2079// to a sad-accumulate node (rather than relying combining finer grained nodes later).
2080// TODO: unsigned SAD too?
2081bool HLoopOptimization::VectorizeSADIdiom(LoopNode* node,
2082 HInstruction* instruction,
2083 bool generate_code,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002084 DataType::Type reduction_type,
Aart Bikdbbac8f2017-09-01 13:06:08 -07002085 uint64_t restrictions) {
2086 // Filter integral "q += ABS(a - b);" reduction, where ABS and SUB
2087 // are done in the same precision (either int or long).
2088 if (!instruction->IsAdd() ||
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002089 (reduction_type != DataType::Type::kInt32 && reduction_type != DataType::Type::kInt64)) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07002090 return false;
2091 }
2092 HInstruction* q = instruction->InputAt(0);
2093 HInstruction* v = instruction->InputAt(1);
2094 HInstruction* a = nullptr;
2095 HInstruction* b = nullptr;
Aart Bik3b2a5952018-03-05 13:55:28 -08002096 if (v->GetType() == reduction_type && v->IsAbs()) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07002097 HInstruction* x = v->InputAt(0);
Aart Bikdf011c32017-09-28 12:53:04 -07002098 if (x->GetType() == reduction_type) {
2099 int64_t c = 0;
2100 if (x->IsSub()) {
2101 a = x->InputAt(0);
2102 b = x->InputAt(1);
2103 } else if (IsAddConst(x, /*out*/ &a, /*out*/ &c)) {
2104 b = graph_->GetConstant(reduction_type, -c); // hidden SUB!
2105 }
Aart Bikdbbac8f2017-09-01 13:06:08 -07002106 }
2107 }
2108 if (a == nullptr || b == nullptr) {
2109 return false;
2110 }
2111 // Accept same-type or consistent sign extension for narrower-type on operands a and b.
2112 // The same-type or narrower operands are called r (a or lower) and s (b or lower).
Aart Bikdf011c32017-09-28 12:53:04 -07002113 // We inspect the operands carefully to pick the most suited type.
Aart Bikdbbac8f2017-09-01 13:06:08 -07002114 HInstruction* r = a;
2115 HInstruction* s = b;
2116 bool is_unsigned = false;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002117 DataType::Type sub_type = a->GetType();
Aart Bikdf011c32017-09-28 12:53:04 -07002118 if (DataType::Size(b->GetType()) < DataType::Size(sub_type)) {
2119 sub_type = b->GetType();
2120 }
2121 if (a->IsTypeConversion() &&
2122 DataType::Size(a->InputAt(0)->GetType()) < DataType::Size(sub_type)) {
2123 sub_type = a->InputAt(0)->GetType();
2124 }
2125 if (b->IsTypeConversion() &&
2126 DataType::Size(b->InputAt(0)->GetType()) < DataType::Size(sub_type)) {
2127 sub_type = b->InputAt(0)->GetType();
Aart Bikdbbac8f2017-09-01 13:06:08 -07002128 }
2129 if (reduction_type != sub_type &&
2130 (!IsNarrowerOperands(a, b, sub_type, &r, &s, &is_unsigned) || is_unsigned)) {
2131 return false;
2132 }
2133 // Try same/narrower type and deal with vector restrictions.
Artem Serov6e9b1372017-10-05 16:48:30 +01002134 if (!TrySetVectorType(sub_type, &restrictions) ||
2135 HasVectorRestrictions(restrictions, kNoSAD) ||
2136 (reduction_type != sub_type && HasVectorRestrictions(restrictions, kNoWideSAD))) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07002137 return false;
2138 }
2139 // Accept SAD idiom for vectorizable operands. Vectorized code uses the shorthand
2140 // idiomatic operation. Sequential code uses the original scalar expressions.
2141 DCHECK(r != nullptr);
2142 DCHECK(s != nullptr);
2143 if (generate_code && vector_mode_ != kVector) { // de-idiom
2144 r = s = v->InputAt(0);
2145 }
2146 if (VectorizeUse(node, q, generate_code, sub_type, restrictions) &&
2147 VectorizeUse(node, r, generate_code, sub_type, restrictions) &&
2148 VectorizeUse(node, s, generate_code, sub_type, restrictions)) {
2149 if (generate_code) {
2150 if (vector_mode_ == kVector) {
2151 vector_map_->Put(instruction, new (global_allocator_) HVecSADAccumulate(
2152 global_allocator_,
2153 vector_map_->Get(q),
2154 vector_map_->Get(r),
2155 vector_map_->Get(s),
Aart Bik3b2a5952018-03-05 13:55:28 -08002156 HVecOperation::ToProperType(reduction_type, is_unsigned),
Aart Bik46b6dbc2017-10-03 11:37:37 -07002157 GetOtherVL(reduction_type, sub_type, vector_length_),
2158 kNoDexPc));
Aart Bikdbbac8f2017-09-01 13:06:08 -07002159 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorizedIdiom);
2160 } else {
2161 GenerateVecOp(v, vector_map_->Get(r), nullptr, reduction_type);
2162 GenerateVecOp(instruction, vector_map_->Get(q), vector_map_->Get(v), reduction_type);
2163 }
2164 }
2165 return true;
2166 }
2167 return false;
2168}
2169
Aart Bikf3e61ee2017-04-12 17:09:20 -07002170//
Aart Bik14a68b42017-06-08 14:06:58 -07002171// Vectorization heuristics.
2172//
2173
Aart Bik38a3f212017-10-20 17:02:21 -07002174Alignment HLoopOptimization::ComputeAlignment(HInstruction* offset,
2175 DataType::Type type,
2176 bool is_string_char_at,
2177 uint32_t peeling) {
2178 // Combine the alignment and hidden offset that is guaranteed by
2179 // the Android runtime with a known starting index adjusted as bytes.
2180 int64_t value = 0;
2181 if (IsInt64AndGet(offset, /*out*/ &value)) {
2182 uint32_t start_offset =
2183 HiddenOffset(type, is_string_char_at) + (value + peeling) * DataType::Size(type);
2184 return Alignment(BaseAlignment(), start_offset & (BaseAlignment() - 1u));
2185 }
2186 // Otherwise, the Android runtime guarantees at least natural alignment.
2187 return Alignment(DataType::Size(type), 0);
2188}
2189
2190void HLoopOptimization::SetAlignmentStrategy(uint32_t peeling_votes[],
2191 const ArrayReference* peeling_candidate) {
2192 // Current heuristic: pick the best static loop peeling factor, if any,
2193 // or otherwise use dynamic loop peeling on suggested peeling candidate.
2194 uint32_t max_vote = 0;
2195 for (int32_t i = 0; i < 16; i++) {
2196 if (peeling_votes[i] > max_vote) {
2197 max_vote = peeling_votes[i];
2198 vector_static_peeling_factor_ = i;
2199 }
2200 }
2201 if (max_vote == 0) {
2202 vector_dynamic_peeling_candidate_ = peeling_candidate;
2203 }
2204}
2205
2206uint32_t HLoopOptimization::MaxNumberPeeled() {
2207 if (vector_dynamic_peeling_candidate_ != nullptr) {
2208 return vector_length_ - 1u; // worst-case
2209 }
2210 return vector_static_peeling_factor_; // known exactly
2211}
2212
Aart Bik14a68b42017-06-08 14:06:58 -07002213bool HLoopOptimization::IsVectorizationProfitable(int64_t trip_count) {
Aart Bik38a3f212017-10-20 17:02:21 -07002214 // Current heuristic: non-empty body with sufficient number of iterations (if known).
Aart Bik14a68b42017-06-08 14:06:58 -07002215 // TODO: refine by looking at e.g. operation count, alignment, etc.
Aart Bik38a3f212017-10-20 17:02:21 -07002216 // TODO: trip count is really unsigned entity, provided the guarding test
2217 // is satisfied; deal with this more carefully later
2218 uint32_t max_peel = MaxNumberPeeled();
Aart Bik14a68b42017-06-08 14:06:58 -07002219 if (vector_length_ == 0) {
2220 return false; // nothing found
Aart Bik38a3f212017-10-20 17:02:21 -07002221 } else if (trip_count < 0) {
2222 return false; // guard against non-taken/large
2223 } else if ((0 < trip_count) && (trip_count < (vector_length_ + max_peel))) {
Aart Bik14a68b42017-06-08 14:06:58 -07002224 return false; // insufficient iterations
2225 }
2226 return true;
2227}
2228
Artem Serovf26bb6c2017-09-01 10:59:03 +01002229static constexpr uint32_t ARM64_SIMD_MAXIMUM_UNROLL_FACTOR = 8;
2230static constexpr uint32_t ARM64_SIMD_HEURISTIC_MAX_BODY_SIZE = 50;
2231
Aart Bik14a68b42017-06-08 14:06:58 -07002232uint32_t HLoopOptimization::GetUnrollingFactor(HBasicBlock* block, int64_t trip_count) {
Aart Bik38a3f212017-10-20 17:02:21 -07002233 uint32_t max_peel = MaxNumberPeeled();
Aart Bik14a68b42017-06-08 14:06:58 -07002234 switch (compiler_driver_->GetInstructionSet()) {
Vladimir Marko33bff252017-11-01 14:35:42 +00002235 case InstructionSet::kArm64: {
Aart Bik521b50f2017-09-09 10:44:45 -07002236 // Don't unroll with insufficient iterations.
Artem Serovf26bb6c2017-09-01 10:59:03 +01002237 // TODO: Unroll loops with unknown trip count.
Aart Bik521b50f2017-09-09 10:44:45 -07002238 DCHECK_NE(vector_length_, 0u);
Aart Bik38a3f212017-10-20 17:02:21 -07002239 if (trip_count < (2 * vector_length_ + max_peel)) {
Aart Bik521b50f2017-09-09 10:44:45 -07002240 return kNoUnrollingFactor;
Aart Bik14a68b42017-06-08 14:06:58 -07002241 }
Aart Bik521b50f2017-09-09 10:44:45 -07002242 // Don't unroll for large loop body size.
Artem Serovf26bb6c2017-09-01 10:59:03 +01002243 uint32_t instruction_count = block->GetInstructions().CountSize();
Aart Bik521b50f2017-09-09 10:44:45 -07002244 if (instruction_count >= ARM64_SIMD_HEURISTIC_MAX_BODY_SIZE) {
2245 return kNoUnrollingFactor;
2246 }
Artem Serovf26bb6c2017-09-01 10:59:03 +01002247 // Find a beneficial unroll factor with the following restrictions:
2248 // - At least one iteration of the transformed loop should be executed.
2249 // - The loop body shouldn't be "too big" (heuristic).
2250 uint32_t uf1 = ARM64_SIMD_HEURISTIC_MAX_BODY_SIZE / instruction_count;
Aart Bik38a3f212017-10-20 17:02:21 -07002251 uint32_t uf2 = (trip_count - max_peel) / vector_length_;
Artem Serovf26bb6c2017-09-01 10:59:03 +01002252 uint32_t unroll_factor =
2253 TruncToPowerOfTwo(std::min({uf1, uf2, ARM64_SIMD_MAXIMUM_UNROLL_FACTOR}));
2254 DCHECK_GE(unroll_factor, 1u);
Artem Serovf26bb6c2017-09-01 10:59:03 +01002255 return unroll_factor;
Aart Bik14a68b42017-06-08 14:06:58 -07002256 }
Vladimir Marko33bff252017-11-01 14:35:42 +00002257 case InstructionSet::kX86:
2258 case InstructionSet::kX86_64:
Aart Bik14a68b42017-06-08 14:06:58 -07002259 default:
Aart Bik521b50f2017-09-09 10:44:45 -07002260 return kNoUnrollingFactor;
Aart Bik14a68b42017-06-08 14:06:58 -07002261 }
2262}
2263
2264//
Aart Bikf8f5a162017-02-06 15:35:29 -08002265// Helpers.
2266//
2267
2268bool HLoopOptimization::TrySetPhiInduction(HPhi* phi, bool restrict_uses) {
Aart Bikb29f6842017-07-28 15:58:41 -07002269 // Start with empty phi induction.
2270 iset_->clear();
2271
Nicolas Geoffrayf57c1ae2017-06-28 17:40:18 +01002272 // Special case Phis that have equivalent in a debuggable setup. Our graph checker isn't
2273 // smart enough to follow strongly connected components (and it's probably not worth
2274 // it to make it so). See b/33775412.
2275 if (graph_->IsDebuggable() && phi->HasEquivalentPhi()) {
2276 return false;
2277 }
Aart Bikb29f6842017-07-28 15:58:41 -07002278
2279 // Lookup phi induction cycle.
Aart Bikcc42be02016-10-20 16:14:16 -07002280 ArenaSet<HInstruction*>* set = induction_range_.LookupCycle(phi);
2281 if (set != nullptr) {
2282 for (HInstruction* i : *set) {
Aart Bike3dedc52016-11-02 17:50:27 -07002283 // Check that, other than instructions that are no longer in the graph (removed earlier)
Aart Bikf8f5a162017-02-06 15:35:29 -08002284 // each instruction is removable and, when restrict uses are requested, other than for phi,
2285 // all uses are contained within the cycle.
Aart Bike3dedc52016-11-02 17:50:27 -07002286 if (!i->IsInBlock()) {
2287 continue;
2288 } else if (!i->IsRemovable()) {
2289 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08002290 } else if (i != phi && restrict_uses) {
Aart Bikb29f6842017-07-28 15:58:41 -07002291 // Deal with regular uses.
Aart Bikcc42be02016-10-20 16:14:16 -07002292 for (const HUseListNode<HInstruction*>& use : i->GetUses()) {
2293 if (set->find(use.GetUser()) == set->end()) {
2294 return false;
2295 }
2296 }
2297 }
Aart Bike3dedc52016-11-02 17:50:27 -07002298 iset_->insert(i); // copy
Aart Bikcc42be02016-10-20 16:14:16 -07002299 }
Aart Bikcc42be02016-10-20 16:14:16 -07002300 return true;
2301 }
2302 return false;
2303}
2304
Aart Bikb29f6842017-07-28 15:58:41 -07002305bool HLoopOptimization::TrySetPhiReduction(HPhi* phi) {
Aart Bikcc42be02016-10-20 16:14:16 -07002306 DCHECK(iset_->empty());
Aart Bikb29f6842017-07-28 15:58:41 -07002307 // Only unclassified phi cycles are candidates for reductions.
2308 if (induction_range_.IsClassified(phi)) {
2309 return false;
2310 }
2311 // Accept operations like x = x + .., provided that the phi and the reduction are
2312 // used exactly once inside the loop, and by each other.
2313 HInputsRef inputs = phi->GetInputs();
2314 if (inputs.size() == 2) {
2315 HInstruction* reduction = inputs[1];
2316 if (HasReductionFormat(reduction, phi)) {
2317 HLoopInformation* loop_info = phi->GetBlock()->GetLoopInformation();
Aart Bik38a3f212017-10-20 17:02:21 -07002318 uint32_t use_count = 0;
Aart Bikb29f6842017-07-28 15:58:41 -07002319 bool single_use_inside_loop =
2320 // Reduction update only used by phi.
2321 reduction->GetUses().HasExactlyOneElement() &&
2322 !reduction->HasEnvironmentUses() &&
2323 // Reduction update is only use of phi inside the loop.
2324 IsOnlyUsedAfterLoop(loop_info, phi, /*collect_loop_uses*/ true, &use_count) &&
2325 iset_->size() == 1;
2326 iset_->clear(); // leave the way you found it
2327 if (single_use_inside_loop) {
2328 // Link reduction back, and start recording feed value.
2329 reductions_->Put(reduction, phi);
2330 reductions_->Put(phi, phi->InputAt(0));
2331 return true;
2332 }
2333 }
2334 }
2335 return false;
2336}
2337
2338bool HLoopOptimization::TrySetSimpleLoopHeader(HBasicBlock* block, /*out*/ HPhi** main_phi) {
2339 // Start with empty phi induction and reductions.
2340 iset_->clear();
2341 reductions_->clear();
2342
2343 // Scan the phis to find the following (the induction structure has already
2344 // been optimized, so we don't need to worry about trivial cases):
2345 // (1) optional reductions in loop,
2346 // (2) the main induction, used in loop control.
2347 HPhi* phi = nullptr;
2348 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
2349 if (TrySetPhiReduction(it.Current()->AsPhi())) {
2350 continue;
2351 } else if (phi == nullptr) {
2352 // Found the first candidate for main induction.
2353 phi = it.Current()->AsPhi();
2354 } else {
2355 return false;
2356 }
2357 }
2358
2359 // Then test for a typical loopheader:
2360 // s: SuspendCheck
2361 // c: Condition(phi, bound)
2362 // i: If(c)
2363 if (phi != nullptr && TrySetPhiInduction(phi, /*restrict_uses*/ false)) {
Aart Bikcc42be02016-10-20 16:14:16 -07002364 HInstruction* s = block->GetFirstInstruction();
2365 if (s != nullptr && s->IsSuspendCheck()) {
2366 HInstruction* c = s->GetNext();
Aart Bikd86c0852017-04-14 12:00:15 -07002367 if (c != nullptr &&
2368 c->IsCondition() &&
2369 c->GetUses().HasExactlyOneElement() && // only used for termination
2370 !c->HasEnvironmentUses()) { // unlikely, but not impossible
Aart Bikcc42be02016-10-20 16:14:16 -07002371 HInstruction* i = c->GetNext();
2372 if (i != nullptr && i->IsIf() && i->InputAt(0) == c) {
2373 iset_->insert(c);
2374 iset_->insert(s);
Aart Bikb29f6842017-07-28 15:58:41 -07002375 *main_phi = phi;
Aart Bikcc42be02016-10-20 16:14:16 -07002376 return true;
2377 }
2378 }
2379 }
2380 }
2381 return false;
2382}
2383
2384bool HLoopOptimization::IsEmptyBody(HBasicBlock* block) {
Aart Bikf8f5a162017-02-06 15:35:29 -08002385 if (!block->GetPhis().IsEmpty()) {
2386 return false;
2387 }
2388 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
2389 HInstruction* instruction = it.Current();
2390 if (!instruction->IsGoto() && iset_->find(instruction) == iset_->end()) {
2391 return false;
Aart Bikcc42be02016-10-20 16:14:16 -07002392 }
Aart Bikf8f5a162017-02-06 15:35:29 -08002393 }
2394 return true;
2395}
2396
2397bool HLoopOptimization::IsUsedOutsideLoop(HLoopInformation* loop_info,
2398 HInstruction* instruction) {
Aart Bikb29f6842017-07-28 15:58:41 -07002399 // Deal with regular uses.
Aart Bikf8f5a162017-02-06 15:35:29 -08002400 for (const HUseListNode<HInstruction*>& use : instruction->GetUses()) {
2401 if (use.GetUser()->GetBlock()->GetLoopInformation() != loop_info) {
2402 return true;
2403 }
Aart Bikcc42be02016-10-20 16:14:16 -07002404 }
2405 return false;
2406}
2407
Aart Bik482095d2016-10-10 15:39:10 -07002408bool HLoopOptimization::IsOnlyUsedAfterLoop(HLoopInformation* loop_info,
Aart Bik8c4a8542016-10-06 11:36:57 -07002409 HInstruction* instruction,
Aart Bik6b69e0a2017-01-11 10:20:43 -08002410 bool collect_loop_uses,
Aart Bik38a3f212017-10-20 17:02:21 -07002411 /*out*/ uint32_t* use_count) {
Aart Bikb29f6842017-07-28 15:58:41 -07002412 // Deal with regular uses.
Aart Bik8c4a8542016-10-06 11:36:57 -07002413 for (const HUseListNode<HInstruction*>& use : instruction->GetUses()) {
2414 HInstruction* user = use.GetUser();
2415 if (iset_->find(user) == iset_->end()) { // not excluded?
2416 HLoopInformation* other_loop_info = user->GetBlock()->GetLoopInformation();
Aart Bik482095d2016-10-10 15:39:10 -07002417 if (other_loop_info != nullptr && other_loop_info->IsIn(*loop_info)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -08002418 // If collect_loop_uses is set, simply keep adding those uses to the set.
2419 // Otherwise, reject uses inside the loop that were not already in the set.
2420 if (collect_loop_uses) {
2421 iset_->insert(user);
2422 continue;
2423 }
Aart Bik8c4a8542016-10-06 11:36:57 -07002424 return false;
2425 }
2426 ++*use_count;
2427 }
2428 }
2429 return true;
2430}
2431
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002432bool HLoopOptimization::TryReplaceWithLastValue(HLoopInformation* loop_info,
2433 HInstruction* instruction,
2434 HBasicBlock* block) {
2435 // Try to replace outside uses with the last value.
Aart Bik807868e2016-11-03 17:51:43 -07002436 if (induction_range_.CanGenerateLastValue(instruction)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -08002437 HInstruction* replacement = induction_range_.GenerateLastValue(instruction, graph_, block);
Aart Bikb29f6842017-07-28 15:58:41 -07002438 // Deal with regular uses.
Aart Bik6b69e0a2017-01-11 10:20:43 -08002439 const HUseList<HInstruction*>& uses = instruction->GetUses();
2440 for (auto it = uses.begin(), end = uses.end(); it != end;) {
2441 HInstruction* user = it->GetUser();
2442 size_t index = it->GetIndex();
2443 ++it; // increment before replacing
2444 if (iset_->find(user) == iset_->end()) { // not excluded?
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002445 if (kIsDebugBuild) {
2446 // We have checked earlier in 'IsOnlyUsedAfterLoop' that the use is after the loop.
2447 HLoopInformation* other_loop_info = user->GetBlock()->GetLoopInformation();
2448 CHECK(other_loop_info == nullptr || !other_loop_info->IsIn(*loop_info));
2449 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08002450 user->ReplaceInput(replacement, index);
2451 induction_range_.Replace(user, instruction, replacement); // update induction
2452 }
2453 }
Aart Bikb29f6842017-07-28 15:58:41 -07002454 // Deal with environment uses.
Aart Bik6b69e0a2017-01-11 10:20:43 -08002455 const HUseList<HEnvironment*>& env_uses = instruction->GetEnvUses();
2456 for (auto it = env_uses.begin(), end = env_uses.end(); it != end;) {
2457 HEnvironment* user = it->GetUser();
2458 size_t index = it->GetIndex();
2459 ++it; // increment before replacing
2460 if (iset_->find(user->GetHolder()) == iset_->end()) { // not excluded?
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002461 // Only update environment uses after the loop.
Aart Bik14a68b42017-06-08 14:06:58 -07002462 HLoopInformation* other_loop_info = user->GetHolder()->GetBlock()->GetLoopInformation();
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002463 if (other_loop_info == nullptr || !other_loop_info->IsIn(*loop_info)) {
2464 user->RemoveAsUserOfInput(index);
2465 user->SetRawEnvAt(index, replacement);
2466 replacement->AddEnvUseAt(user, index);
2467 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08002468 }
2469 }
Aart Bik807868e2016-11-03 17:51:43 -07002470 return true;
Aart Bik8c4a8542016-10-06 11:36:57 -07002471 }
Aart Bik807868e2016-11-03 17:51:43 -07002472 return false;
Aart Bik8c4a8542016-10-06 11:36:57 -07002473}
2474
Aart Bikf8f5a162017-02-06 15:35:29 -08002475bool HLoopOptimization::TryAssignLastValue(HLoopInformation* loop_info,
2476 HInstruction* instruction,
2477 HBasicBlock* block,
2478 bool collect_loop_uses) {
2479 // Assigning the last value is always successful if there are no uses.
2480 // Otherwise, it succeeds in a no early-exit loop by generating the
2481 // proper last value assignment.
Aart Bik38a3f212017-10-20 17:02:21 -07002482 uint32_t use_count = 0;
Aart Bikf8f5a162017-02-06 15:35:29 -08002483 return IsOnlyUsedAfterLoop(loop_info, instruction, collect_loop_uses, &use_count) &&
2484 (use_count == 0 ||
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002485 (!IsEarlyExit(loop_info) && TryReplaceWithLastValue(loop_info, instruction, block)));
Aart Bikf8f5a162017-02-06 15:35:29 -08002486}
2487
Aart Bik6b69e0a2017-01-11 10:20:43 -08002488void HLoopOptimization::RemoveDeadInstructions(const HInstructionList& list) {
2489 for (HBackwardInstructionIterator i(list); !i.Done(); i.Advance()) {
2490 HInstruction* instruction = i.Current();
2491 if (instruction->IsDeadAndRemovable()) {
2492 simplified_ = true;
2493 instruction->GetBlock()->RemoveInstructionOrPhi(instruction);
2494 }
2495 }
2496}
2497
Aart Bik14a68b42017-06-08 14:06:58 -07002498bool HLoopOptimization::CanRemoveCycle() {
2499 for (HInstruction* i : *iset_) {
2500 // We can never remove instructions that have environment
2501 // uses when we compile 'debuggable'.
2502 if (i->HasEnvironmentUses() && graph_->IsDebuggable()) {
2503 return false;
2504 }
2505 // A deoptimization should never have an environment input removed.
2506 for (const HUseListNode<HEnvironment*>& use : i->GetEnvUses()) {
2507 if (use.GetUser()->GetHolder()->IsDeoptimize()) {
2508 return false;
2509 }
2510 }
2511 }
2512 return true;
2513}
2514
Aart Bik281c6812016-08-26 11:31:48 -07002515} // namespace art