blob: b41b659083ff0e2bc53edda3e1cdd856db47b83b [file] [log] [blame]
Aart Bik281c6812016-08-26 11:31:48 -07001/*
2 * Copyright (C) 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "loop_optimization.h"
18
Aart Bikf8f5a162017-02-06 15:35:29 -080019#include "arch/arm/instruction_set_features_arm.h"
20#include "arch/arm64/instruction_set_features_arm64.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070021#include "arch/instruction_set.h"
Aart Bikf8f5a162017-02-06 15:35:29 -080022#include "arch/mips/instruction_set_features_mips.h"
23#include "arch/mips64/instruction_set_features_mips64.h"
24#include "arch/x86/instruction_set_features_x86.h"
25#include "arch/x86_64/instruction_set_features_x86_64.h"
Aart Bik92685a82017-03-06 11:13:43 -080026#include "driver/compiler_driver.h"
Aart Bik96202302016-10-04 17:33:56 -070027#include "linear_order.h"
Aart Bik38a3f212017-10-20 17:02:21 -070028#include "mirror/array-inl.h"
29#include "mirror/string.h"
Aart Bik281c6812016-08-26 11:31:48 -070030
31namespace art {
32
Aart Bikf8f5a162017-02-06 15:35:29 -080033// Enables vectorization (SIMDization) in the loop optimizer.
34static constexpr bool kEnableVectorization = true;
35
Artem Serov121f2032017-10-23 19:19:06 +010036// Enables scalar loop unrolling in the loop optimizer.
37static constexpr bool kEnableScalarUnrolling = false;
Aart Bik521b50f2017-09-09 10:44:45 -070038
Aart Bik38a3f212017-10-20 17:02:21 -070039//
40// Static helpers.
41//
42
43// Base alignment for arrays/strings guaranteed by the Android runtime.
44static uint32_t BaseAlignment() {
45 return kObjectAlignment;
46}
47
48// Hidden offset for arrays/strings guaranteed by the Android runtime.
49static uint32_t HiddenOffset(DataType::Type type, bool is_string_char_at) {
50 return is_string_char_at
51 ? mirror::String::ValueOffset().Uint32Value()
52 : mirror::Array::DataOffset(DataType::Size(type)).Uint32Value();
53}
54
Aart Bik9abf8942016-10-14 09:49:42 -070055// Remove the instruction from the graph. A bit more elaborate than the usual
56// instruction removal, since there may be a cycle in the use structure.
Aart Bik281c6812016-08-26 11:31:48 -070057static void RemoveFromCycle(HInstruction* instruction) {
Aart Bik281c6812016-08-26 11:31:48 -070058 instruction->RemoveAsUserOfAllInputs();
59 instruction->RemoveEnvironmentUsers();
60 instruction->GetBlock()->RemoveInstructionOrPhi(instruction, /*ensure_safety=*/ false);
Artem Serov21c7e6f2017-07-27 16:04:42 +010061 RemoveEnvironmentUses(instruction);
62 ResetEnvironmentInputRecords(instruction);
Aart Bik281c6812016-08-26 11:31:48 -070063}
64
Aart Bik807868e2016-11-03 17:51:43 -070065// Detect a goto block and sets succ to the single successor.
Aart Bike3dedc52016-11-02 17:50:27 -070066static bool IsGotoBlock(HBasicBlock* block, /*out*/ HBasicBlock** succ) {
67 if (block->GetPredecessors().size() == 1 &&
68 block->GetSuccessors().size() == 1 &&
69 block->IsSingleGoto()) {
70 *succ = block->GetSingleSuccessor();
71 return true;
72 }
73 return false;
74}
75
Aart Bik807868e2016-11-03 17:51:43 -070076// Detect an early exit loop.
77static bool IsEarlyExit(HLoopInformation* loop_info) {
78 HBlocksInLoopReversePostOrderIterator it_loop(*loop_info);
79 for (it_loop.Advance(); !it_loop.Done(); it_loop.Advance()) {
80 for (HBasicBlock* successor : it_loop.Current()->GetSuccessors()) {
81 if (!loop_info->Contains(*successor)) {
82 return true;
83 }
84 }
85 }
86 return false;
87}
88
Aart Bik68ca7022017-09-26 16:44:23 -070089// Forward declaration.
90static bool IsZeroExtensionAndGet(HInstruction* instruction,
91 DataType::Type type,
Aart Bikdf011c32017-09-28 12:53:04 -070092 /*out*/ HInstruction** operand);
Aart Bik68ca7022017-09-26 16:44:23 -070093
Aart Bikdf011c32017-09-28 12:53:04 -070094// Detect a sign extension in instruction from the given type.
Aart Bikdbbac8f2017-09-01 13:06:08 -070095// Returns the promoted operand on success.
Aart Bikf3e61ee2017-04-12 17:09:20 -070096static bool IsSignExtensionAndGet(HInstruction* instruction,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +010097 DataType::Type type,
Aart Bikdf011c32017-09-28 12:53:04 -070098 /*out*/ HInstruction** operand) {
Aart Bikf3e61ee2017-04-12 17:09:20 -070099 // Accept any already wider constant that would be handled properly by sign
100 // extension when represented in the *width* of the given narrower data type
Aart Bik4d1a9d42017-10-19 14:40:55 -0700101 // (the fact that Uint8/Uint16 normally zero extend does not matter here).
Aart Bikf3e61ee2017-04-12 17:09:20 -0700102 int64_t value = 0;
Aart Bik50e20d52017-05-05 14:07:29 -0700103 if (IsInt64AndGet(instruction, /*out*/ &value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700104 switch (type) {
Vladimir Markod5d2f2c2017-09-26 12:37:26 +0100105 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100106 case DataType::Type::kInt8:
Aart Bikdbbac8f2017-09-01 13:06:08 -0700107 if (IsInt<8>(value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700108 *operand = instruction;
109 return true;
110 }
111 return false;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100112 case DataType::Type::kUint16:
113 case DataType::Type::kInt16:
Aart Bikdbbac8f2017-09-01 13:06:08 -0700114 if (IsInt<16>(value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700115 *operand = instruction;
116 return true;
117 }
118 return false;
119 default:
120 return false;
121 }
122 }
Aart Bikdf011c32017-09-28 12:53:04 -0700123 // An implicit widening conversion of any signed expression sign-extends.
124 if (instruction->GetType() == type) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700125 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100126 case DataType::Type::kInt8:
127 case DataType::Type::kInt16:
Aart Bikf3e61ee2017-04-12 17:09:20 -0700128 *operand = instruction;
129 return true;
130 default:
131 return false;
132 }
133 }
Aart Bikdf011c32017-09-28 12:53:04 -0700134 // An explicit widening conversion of a signed expression sign-extends.
Aart Bik68ca7022017-09-26 16:44:23 -0700135 if (instruction->IsTypeConversion()) {
Aart Bikdf011c32017-09-28 12:53:04 -0700136 HInstruction* conv = instruction->InputAt(0);
137 DataType::Type from = conv->GetType();
Aart Bik68ca7022017-09-26 16:44:23 -0700138 switch (instruction->GetType()) {
Aart Bikdf011c32017-09-28 12:53:04 -0700139 case DataType::Type::kInt32:
Aart Bik68ca7022017-09-26 16:44:23 -0700140 case DataType::Type::kInt64:
Aart Bikdf011c32017-09-28 12:53:04 -0700141 if (type == from && (from == DataType::Type::kInt8 ||
142 from == DataType::Type::kInt16 ||
143 from == DataType::Type::kInt32)) {
144 *operand = conv;
145 return true;
146 }
147 return false;
Aart Bik68ca7022017-09-26 16:44:23 -0700148 case DataType::Type::kInt16:
149 return type == DataType::Type::kUint16 &&
150 from == DataType::Type::kUint16 &&
Aart Bikdf011c32017-09-28 12:53:04 -0700151 IsZeroExtensionAndGet(instruction->InputAt(0), type, /*out*/ operand);
Aart Bik68ca7022017-09-26 16:44:23 -0700152 default:
153 return false;
154 }
Aart Bikdbbac8f2017-09-01 13:06:08 -0700155 }
Aart Bik5aac9212018-04-03 14:06:43 -0700156 // A MIN-MAX on narrower operands qualifies as well
157 // (returning the operator itself).
158 if (instruction->IsMin() || instruction->IsMax()) {
159 HBinaryOperation* min_max = instruction->AsBinaryOperation();
160 DCHECK(min_max->GetType() == DataType::Type::kInt32 ||
161 min_max->GetType() == DataType::Type::kInt64);
162 if (IsSignExtensionAndGet(min_max->InputAt(0), type, operand) &&
163 IsSignExtensionAndGet(min_max->InputAt(1), type, operand)) {
164 *operand = min_max;
165 return true;
166 }
167 }
Aart Bikf3e61ee2017-04-12 17:09:20 -0700168 return false;
169}
170
Aart Bikdf011c32017-09-28 12:53:04 -0700171// Detect a zero extension in instruction from the given type.
Aart Bikdbbac8f2017-09-01 13:06:08 -0700172// Returns the promoted operand on success.
Aart Bikf3e61ee2017-04-12 17:09:20 -0700173static bool IsZeroExtensionAndGet(HInstruction* instruction,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100174 DataType::Type type,
Aart Bikdf011c32017-09-28 12:53:04 -0700175 /*out*/ HInstruction** operand) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700176 // Accept any already wider constant that would be handled properly by zero
177 // extension when represented in the *width* of the given narrower data type
Aart Bikdf011c32017-09-28 12:53:04 -0700178 // (the fact that Int8/Int16 normally sign extend does not matter here).
Aart Bikf3e61ee2017-04-12 17:09:20 -0700179 int64_t value = 0;
Aart Bik50e20d52017-05-05 14:07:29 -0700180 if (IsInt64AndGet(instruction, /*out*/ &value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700181 switch (type) {
Vladimir Markod5d2f2c2017-09-26 12:37:26 +0100182 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100183 case DataType::Type::kInt8:
Aart Bikdbbac8f2017-09-01 13:06:08 -0700184 if (IsUint<8>(value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700185 *operand = instruction;
186 return true;
187 }
188 return false;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100189 case DataType::Type::kUint16:
190 case DataType::Type::kInt16:
Aart Bikdbbac8f2017-09-01 13:06:08 -0700191 if (IsUint<16>(value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700192 *operand = instruction;
193 return true;
194 }
195 return false;
196 default:
197 return false;
198 }
199 }
Aart Bikdf011c32017-09-28 12:53:04 -0700200 // An implicit widening conversion of any unsigned expression zero-extends.
201 if (instruction->GetType() == type) {
Vladimir Markod5d2f2c2017-09-26 12:37:26 +0100202 switch (type) {
203 case DataType::Type::kUint8:
204 case DataType::Type::kUint16:
205 *operand = instruction;
206 return true;
207 default:
208 return false;
Aart Bikf3e61ee2017-04-12 17:09:20 -0700209 }
210 }
Aart Bikdf011c32017-09-28 12:53:04 -0700211 // An explicit widening conversion of an unsigned expression zero-extends.
Aart Bik68ca7022017-09-26 16:44:23 -0700212 if (instruction->IsTypeConversion()) {
Aart Bikdf011c32017-09-28 12:53:04 -0700213 HInstruction* conv = instruction->InputAt(0);
214 DataType::Type from = conv->GetType();
Aart Bik68ca7022017-09-26 16:44:23 -0700215 switch (instruction->GetType()) {
Aart Bikdf011c32017-09-28 12:53:04 -0700216 case DataType::Type::kInt32:
Aart Bik68ca7022017-09-26 16:44:23 -0700217 case DataType::Type::kInt64:
Aart Bikdf011c32017-09-28 12:53:04 -0700218 if (type == from && from == DataType::Type::kUint16) {
219 *operand = conv;
220 return true;
221 }
222 return false;
Aart Bik68ca7022017-09-26 16:44:23 -0700223 case DataType::Type::kUint16:
224 return type == DataType::Type::kInt16 &&
225 from == DataType::Type::kInt16 &&
Aart Bikdf011c32017-09-28 12:53:04 -0700226 IsSignExtensionAndGet(instruction->InputAt(0), type, /*out*/ operand);
Aart Bik68ca7022017-09-26 16:44:23 -0700227 default:
228 return false;
229 }
Aart Bikdbbac8f2017-09-01 13:06:08 -0700230 }
Aart Bik5aac9212018-04-03 14:06:43 -0700231 // A MIN-MAX on narrower operands qualifies as well
232 // (returning the operator itself).
233 if (instruction->IsMin() || instruction->IsMax()) {
234 HBinaryOperation* min_max = instruction->AsBinaryOperation();
235 DCHECK(min_max->GetType() == DataType::Type::kInt32 ||
236 min_max->GetType() == DataType::Type::kInt64);
237 if (IsZeroExtensionAndGet(min_max->InputAt(0), type, operand) &&
238 IsZeroExtensionAndGet(min_max->InputAt(1), type, operand)) {
239 *operand = min_max;
240 return true;
241 }
242 }
Aart Bikf3e61ee2017-04-12 17:09:20 -0700243 return false;
244}
245
Aart Bik304c8a52017-05-23 11:01:13 -0700246// Detect situations with same-extension narrower operands.
247// Returns true on success and sets is_unsigned accordingly.
248static bool IsNarrowerOperands(HInstruction* a,
249 HInstruction* b,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100250 DataType::Type type,
Aart Bik304c8a52017-05-23 11:01:13 -0700251 /*out*/ HInstruction** r,
252 /*out*/ HInstruction** s,
253 /*out*/ bool* is_unsigned) {
Nicolas Geoffraya3e23262018-03-28 11:15:12 +0000254 DCHECK(a != nullptr && b != nullptr);
Aart Bik4d1a9d42017-10-19 14:40:55 -0700255 // Look for a matching sign extension.
256 DataType::Type stype = HVecOperation::ToSignedType(type);
257 if (IsSignExtensionAndGet(a, stype, r) && IsSignExtensionAndGet(b, stype, s)) {
Aart Bik304c8a52017-05-23 11:01:13 -0700258 *is_unsigned = false;
259 return true;
Aart Bik4d1a9d42017-10-19 14:40:55 -0700260 }
261 // Look for a matching zero extension.
262 DataType::Type utype = HVecOperation::ToUnsignedType(type);
263 if (IsZeroExtensionAndGet(a, utype, r) && IsZeroExtensionAndGet(b, utype, s)) {
Aart Bik304c8a52017-05-23 11:01:13 -0700264 *is_unsigned = true;
265 return true;
266 }
267 return false;
268}
269
270// As above, single operand.
271static bool IsNarrowerOperand(HInstruction* a,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100272 DataType::Type type,
Aart Bik304c8a52017-05-23 11:01:13 -0700273 /*out*/ HInstruction** r,
274 /*out*/ bool* is_unsigned) {
Nicolas Geoffraya3e23262018-03-28 11:15:12 +0000275 DCHECK(a != nullptr);
Aart Bik4d1a9d42017-10-19 14:40:55 -0700276 // Look for a matching sign extension.
277 DataType::Type stype = HVecOperation::ToSignedType(type);
278 if (IsSignExtensionAndGet(a, stype, r)) {
Aart Bik304c8a52017-05-23 11:01:13 -0700279 *is_unsigned = false;
280 return true;
Aart Bik4d1a9d42017-10-19 14:40:55 -0700281 }
282 // Look for a matching zero extension.
283 DataType::Type utype = HVecOperation::ToUnsignedType(type);
284 if (IsZeroExtensionAndGet(a, utype, r)) {
Aart Bik304c8a52017-05-23 11:01:13 -0700285 *is_unsigned = true;
286 return true;
287 }
288 return false;
289}
290
Aart Bikdbbac8f2017-09-01 13:06:08 -0700291// Compute relative vector length based on type difference.
Aart Bik38a3f212017-10-20 17:02:21 -0700292static uint32_t GetOtherVL(DataType::Type other_type, DataType::Type vector_type, uint32_t vl) {
Vladimir Markod5d2f2c2017-09-26 12:37:26 +0100293 DCHECK(DataType::IsIntegralType(other_type));
294 DCHECK(DataType::IsIntegralType(vector_type));
295 DCHECK_GE(DataType::SizeShift(other_type), DataType::SizeShift(vector_type));
296 return vl >> (DataType::SizeShift(other_type) - DataType::SizeShift(vector_type));
Aart Bikdbbac8f2017-09-01 13:06:08 -0700297}
298
Nicolas Geoffraya3e23262018-03-28 11:15:12 +0000299// Detect up to two added operands a and b and an acccumulated constant c.
300static bool IsAddConst(HInstruction* instruction,
301 /*out*/ HInstruction** a,
302 /*out*/ HInstruction** b,
303 /*out*/ int64_t* c,
304 int32_t depth = 8) { // don't search too deep
Aart Bik5f805002017-05-16 16:42:41 -0700305 int64_t value = 0;
Nicolas Geoffraya3e23262018-03-28 11:15:12 +0000306 // Enter add/sub while still within reasonable depth.
307 if (depth > 0) {
308 if (instruction->IsAdd()) {
309 return IsAddConst(instruction->InputAt(0), a, b, c, depth - 1) &&
310 IsAddConst(instruction->InputAt(1), a, b, c, depth - 1);
311 } else if (instruction->IsSub() &&
312 IsInt64AndGet(instruction->InputAt(1), &value)) {
313 *c -= value;
314 return IsAddConst(instruction->InputAt(0), a, b, c, depth - 1);
315 }
316 }
317 // Otherwise, deal with leaf nodes.
Aart Bik5f805002017-05-16 16:42:41 -0700318 if (IsInt64AndGet(instruction, &value)) {
319 *c += value;
320 return true;
Aart Bik5f805002017-05-16 16:42:41 -0700321 } else if (*a == nullptr) {
322 *a = instruction;
323 return true;
324 } else if (*b == nullptr) {
325 *b = instruction;
326 return true;
327 }
Nicolas Geoffraya3e23262018-03-28 11:15:12 +0000328 return false; // too many operands
Aart Bik5f805002017-05-16 16:42:41 -0700329}
330
Nicolas Geoffraya3e23262018-03-28 11:15:12 +0000331// Detect a + b + c with optional constant c.
332static bool IsAddConst2(HGraph* graph,
333 HInstruction* instruction,
334 /*out*/ HInstruction** a,
335 /*out*/ HInstruction** b,
336 /*out*/ int64_t* c) {
337 if (IsAddConst(instruction, a, b, c) && *a != nullptr) {
338 if (*b == nullptr) {
339 // Constant is usually already present, unless accumulated.
340 *b = graph->GetConstant(instruction->GetType(), (*c));
341 *c = 0;
Aart Bik5f805002017-05-16 16:42:41 -0700342 }
Aart Bik5f805002017-05-16 16:42:41 -0700343 return true;
344 }
345 return false;
346}
347
Nicolas Geoffraya3e23262018-03-28 11:15:12 +0000348// Detect a direct a - b or a hidden a - (-c).
349static bool IsSubConst2(HGraph* graph,
350 HInstruction* instruction,
351 /*out*/ HInstruction** a,
352 /*out*/ HInstruction** b) {
353 int64_t c = 0;
354 if (instruction->IsSub()) {
355 *a = instruction->InputAt(0);
356 *b = instruction->InputAt(1);
357 return true;
358 } else if (IsAddConst(instruction, a, b, &c) && *a != nullptr && *b == nullptr) {
359 // Constant for the hidden subtraction.
360 *b = graph->GetConstant(instruction->GetType(), -c);
361 return true;
Aart Bikdf011c32017-09-28 12:53:04 -0700362 }
363 return false;
364}
365
Aart Bik29aa0822018-03-08 11:28:00 -0800366// Detect clipped [lo, hi] range for nested MIN-MAX operations on a clippee,
367// such as MIN(hi, MAX(lo, clippee)) for an arbitrary clippee expression.
368// Example: MIN(10, MIN(20, MAX(0, x))) yields [0, 10] with clippee x.
Aart Bik1a381022018-03-15 15:51:37 -0700369static HInstruction* FindClippee(HInstruction* instruction,
370 /*out*/ int64_t* lo,
371 /*out*/ int64_t* hi) {
372 // Iterate into MIN(.., c)-MAX(.., c) expressions and 'tighten' the range [lo, hi].
373 while (instruction->IsMin() || instruction->IsMax()) {
374 HBinaryOperation* min_max = instruction->AsBinaryOperation();
375 DCHECK(min_max->GetType() == DataType::Type::kInt32 ||
376 min_max->GetType() == DataType::Type::kInt64);
377 // Process the constant.
378 HConstant* right = min_max->GetConstantRight();
379 if (right == nullptr) {
380 break;
381 } else if (instruction->IsMin()) {
382 *hi = std::min(*hi, Int64FromConstant(right));
383 } else {
384 *lo = std::max(*lo, Int64FromConstant(right));
Aart Bik29aa0822018-03-08 11:28:00 -0800385 }
Aart Bik1a381022018-03-15 15:51:37 -0700386 instruction = min_max->GetLeastConstantLeft();
Aart Bik29aa0822018-03-08 11:28:00 -0800387 }
Aart Bik1a381022018-03-15 15:51:37 -0700388 // Iteration ends in any other expression (possibly MIN/MAX without constant).
389 // This leaf expression is the clippee with range [lo, hi].
390 return instruction;
Aart Bik29aa0822018-03-08 11:28:00 -0800391}
392
Aart Bik5a392762018-03-16 10:27:44 -0700393// Set value range for type (or fail).
394static bool CanSetRange(DataType::Type type,
395 /*out*/ int64_t* uhi,
396 /*out*/ int64_t* slo,
397 /*out*/ int64_t* shi) {
Aart Bik29aa0822018-03-08 11:28:00 -0800398 if (DataType::Size(type) == 1) {
Aart Bik5a392762018-03-16 10:27:44 -0700399 *uhi = std::numeric_limits<uint8_t>::max();
400 *slo = std::numeric_limits<int8_t>::min();
401 *shi = std::numeric_limits<int8_t>::max();
402 return true;
Aart Bik29aa0822018-03-08 11:28:00 -0800403 } else if (DataType::Size(type) == 2) {
Aart Bik5a392762018-03-16 10:27:44 -0700404 *uhi = std::numeric_limits<uint16_t>::max();
405 *slo = std::numeric_limits<int16_t>::min();
406 *shi = std::numeric_limits<int16_t>::max();
407 return true;
Aart Bik29aa0822018-03-08 11:28:00 -0800408 }
409 return false;
410}
411
Aart Bik5a392762018-03-16 10:27:44 -0700412// Accept various saturated addition forms.
Nicolas Geoffraya3e23262018-03-28 11:15:12 +0000413static bool IsSaturatedAdd(HInstruction* a,
414 HInstruction* b,
Aart Bik5a392762018-03-16 10:27:44 -0700415 DataType::Type type,
416 int64_t lo,
417 int64_t hi,
418 bool is_unsigned) {
419 int64_t ulo = 0, uhi = 0, slo = 0, shi = 0;
420 if (!CanSetRange(type, &uhi, &slo, &shi)) {
421 return false;
Aart Bik29aa0822018-03-08 11:28:00 -0800422 }
Aart Bik5a392762018-03-16 10:27:44 -0700423 // Tighten the range for signed single clipping on constant.
424 if (!is_unsigned) {
425 int64_t c = 0;
Nicolas Geoffraya3e23262018-03-28 11:15:12 +0000426 if (IsInt64AndGet(a, &c) || IsInt64AndGet(b, &c)) {
Aart Bik5a392762018-03-16 10:27:44 -0700427 // For c in proper range and narrower operand r:
428 // MIN(r + c, 127) c > 0
429 // or MAX(r + c, -128) c < 0 (and possibly redundant bound).
430 if (0 < c && c <= shi && hi == shi) {
431 if (lo <= (slo + c)) {
432 return true;
433 }
434 } else if (slo <= c && c < 0 && lo == slo) {
435 if (hi >= (shi + c)) {
436 return true;
437 }
438 }
439 }
440 }
441 // Detect for narrower operands r and s:
442 // MIN(r + s, 255) => SAT_ADD_unsigned
443 // MAX(MIN(r + s, 127), -128) => SAT_ADD_signed.
444 return is_unsigned ? (lo <= ulo && hi == uhi) : (lo == slo && hi == shi);
445}
446
447// Accept various saturated subtraction forms.
Nicolas Geoffraya3e23262018-03-28 11:15:12 +0000448static bool IsSaturatedSub(HInstruction* a,
Aart Bik5a392762018-03-16 10:27:44 -0700449 DataType::Type type,
450 int64_t lo,
451 int64_t hi,
452 bool is_unsigned) {
453 int64_t ulo = 0, uhi = 0, slo = 0, shi = 0;
454 if (!CanSetRange(type, &uhi, &slo, &shi)) {
455 return false;
456 }
457 // Tighten the range for signed single clipping on constant.
458 if (!is_unsigned) {
459 int64_t c = 0;
Nicolas Geoffraya3e23262018-03-28 11:15:12 +0000460 if (IsInt64AndGet(a, /*out*/ &c)) {
Aart Bik5a392762018-03-16 10:27:44 -0700461 // For c in proper range and narrower operand r:
462 // MIN(c - r, 127) c > 0
463 // or MAX(c - r, -128) c < 0 (and possibly redundant bound).
464 if (0 < c && c <= shi && hi == shi) {
465 if (lo <= (c - shi)) {
466 return true;
467 }
468 } else if (slo <= c && c < 0 && lo == slo) {
469 if (hi >= (c - slo)) {
470 return true;
471 }
472 }
473 }
474 }
475 // Detect for narrower operands r and s:
476 // MAX(r - s, 0) => SAT_SUB_unsigned
477 // MIN(MAX(r - s, -128), 127) => SAT_ADD_signed.
478 return is_unsigned ? (lo == ulo && hi >= uhi) : (lo == slo && hi == shi);
Aart Bik29aa0822018-03-08 11:28:00 -0800479}
480
Aart Bikb29f6842017-07-28 15:58:41 -0700481// Detect reductions of the following forms,
Aart Bikb29f6842017-07-28 15:58:41 -0700482// x = x_phi + ..
483// x = x_phi - ..
Aart Bikb29f6842017-07-28 15:58:41 -0700484// x = min(x_phi, ..)
Aart Bik1f8d51b2018-02-15 10:42:37 -0800485// x = max(x_phi, ..)
Aart Bikb29f6842017-07-28 15:58:41 -0700486static bool HasReductionFormat(HInstruction* reduction, HInstruction* phi) {
Aart Bik1f8d51b2018-02-15 10:42:37 -0800487 if (reduction->IsAdd() || reduction->IsMin() || reduction->IsMax()) {
Aart Bikdbbac8f2017-09-01 13:06:08 -0700488 return (reduction->InputAt(0) == phi && reduction->InputAt(1) != phi) ||
489 (reduction->InputAt(0) != phi && reduction->InputAt(1) == phi);
Aart Bikb29f6842017-07-28 15:58:41 -0700490 } else if (reduction->IsSub()) {
Aart Bikdbbac8f2017-09-01 13:06:08 -0700491 return (reduction->InputAt(0) == phi && reduction->InputAt(1) != phi);
Aart Bikb29f6842017-07-28 15:58:41 -0700492 }
493 return false;
494}
495
Aart Bikdbbac8f2017-09-01 13:06:08 -0700496// Translates vector operation to reduction kind.
497static HVecReduce::ReductionKind GetReductionKind(HVecOperation* reduction) {
498 if (reduction->IsVecAdd() || reduction->IsVecSub() || reduction->IsVecSADAccumulate()) {
Aart Bik0148de42017-09-05 09:25:01 -0700499 return HVecReduce::kSum;
500 } else if (reduction->IsVecMin()) {
501 return HVecReduce::kMin;
502 } else if (reduction->IsVecMax()) {
503 return HVecReduce::kMax;
504 }
Aart Bik38a3f212017-10-20 17:02:21 -0700505 LOG(FATAL) << "Unsupported SIMD reduction " << reduction->GetId();
Aart Bik0148de42017-09-05 09:25:01 -0700506 UNREACHABLE();
507}
508
Aart Bikf8f5a162017-02-06 15:35:29 -0800509// Test vector restrictions.
510static bool HasVectorRestrictions(uint64_t restrictions, uint64_t tested) {
511 return (restrictions & tested) != 0;
512}
513
Aart Bikf3e61ee2017-04-12 17:09:20 -0700514// Insert an instruction.
Aart Bikf8f5a162017-02-06 15:35:29 -0800515static HInstruction* Insert(HBasicBlock* block, HInstruction* instruction) {
516 DCHECK(block != nullptr);
517 DCHECK(instruction != nullptr);
518 block->InsertInstructionBefore(instruction, block->GetLastInstruction());
519 return instruction;
520}
521
Artem Serov21c7e6f2017-07-27 16:04:42 +0100522// Check that instructions from the induction sets are fully removed: have no uses
523// and no other instructions use them.
Vladimir Markoca6fff82017-10-03 14:49:14 +0100524static bool CheckInductionSetFullyRemoved(ScopedArenaSet<HInstruction*>* iset) {
Artem Serov21c7e6f2017-07-27 16:04:42 +0100525 for (HInstruction* instr : *iset) {
526 if (instr->GetBlock() != nullptr ||
527 !instr->GetUses().empty() ||
528 !instr->GetEnvUses().empty() ||
529 HasEnvironmentUsedByOthers(instr)) {
530 return false;
531 }
532 }
Artem Serov21c7e6f2017-07-27 16:04:42 +0100533 return true;
534}
535
Aart Bik281c6812016-08-26 11:31:48 -0700536//
Aart Bikb29f6842017-07-28 15:58:41 -0700537// Public methods.
Aart Bik281c6812016-08-26 11:31:48 -0700538//
539
540HLoopOptimization::HLoopOptimization(HGraph* graph,
Aart Bik92685a82017-03-06 11:13:43 -0800541 CompilerDriver* compiler_driver,
Aart Bikb92cc332017-09-06 15:53:17 -0700542 HInductionVarAnalysis* induction_analysis,
Aart Bik2ca10eb2017-11-15 15:17:53 -0800543 OptimizingCompilerStats* stats,
544 const char* name)
545 : HOptimization(graph, name, stats),
Aart Bik92685a82017-03-06 11:13:43 -0800546 compiler_driver_(compiler_driver),
Aart Bik281c6812016-08-26 11:31:48 -0700547 induction_range_(induction_analysis),
Aart Bik96202302016-10-04 17:33:56 -0700548 loop_allocator_(nullptr),
Vladimir Markoca6fff82017-10-03 14:49:14 +0100549 global_allocator_(graph_->GetAllocator()),
Aart Bik281c6812016-08-26 11:31:48 -0700550 top_loop_(nullptr),
Aart Bik8c4a8542016-10-06 11:36:57 -0700551 last_loop_(nullptr),
Aart Bik482095d2016-10-10 15:39:10 -0700552 iset_(nullptr),
Aart Bikb29f6842017-07-28 15:58:41 -0700553 reductions_(nullptr),
Aart Bikf8f5a162017-02-06 15:35:29 -0800554 simplified_(false),
555 vector_length_(0),
556 vector_refs_(nullptr),
Aart Bik38a3f212017-10-20 17:02:21 -0700557 vector_static_peeling_factor_(0),
558 vector_dynamic_peeling_candidate_(nullptr),
Aart Bik14a68b42017-06-08 14:06:58 -0700559 vector_runtime_test_a_(nullptr),
560 vector_runtime_test_b_(nullptr),
Aart Bik0148de42017-09-05 09:25:01 -0700561 vector_map_(nullptr),
Vladimir Markoca6fff82017-10-03 14:49:14 +0100562 vector_permanent_map_(nullptr),
563 vector_mode_(kSequential),
564 vector_preheader_(nullptr),
565 vector_header_(nullptr),
566 vector_body_(nullptr),
Artem Serov121f2032017-10-23 19:19:06 +0100567 vector_index_(nullptr),
568 arch_loop_helper_(ArchDefaultLoopHelper::Create(compiler_driver_ != nullptr
569 ? compiler_driver_->GetInstructionSet()
570 : InstructionSet::kNone,
571 global_allocator_)) {
Aart Bik281c6812016-08-26 11:31:48 -0700572}
573
574void HLoopOptimization::Run() {
Mingyao Yang01b47b02017-02-03 12:09:57 -0800575 // Skip if there is no loop or the graph has try-catch/irreducible loops.
Aart Bik281c6812016-08-26 11:31:48 -0700576 // TODO: make this less of a sledgehammer.
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800577 if (!graph_->HasLoops() || graph_->HasTryCatch() || graph_->HasIrreducibleLoops()) {
Aart Bik281c6812016-08-26 11:31:48 -0700578 return;
579 }
580
Vladimir Markoca6fff82017-10-03 14:49:14 +0100581 // Phase-local allocator.
582 ScopedArenaAllocator allocator(graph_->GetArenaStack());
Aart Bik96202302016-10-04 17:33:56 -0700583 loop_allocator_ = &allocator;
Nicolas Geoffrayebe16742016-10-05 09:55:42 +0100584
Aart Bik96202302016-10-04 17:33:56 -0700585 // Perform loop optimizations.
586 LocalRun();
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800587 if (top_loop_ == nullptr) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800588 graph_->SetHasLoops(false); // no more loops
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800589 }
590
Aart Bik96202302016-10-04 17:33:56 -0700591 // Detach.
592 loop_allocator_ = nullptr;
593 last_loop_ = top_loop_ = nullptr;
594}
595
Aart Bikb29f6842017-07-28 15:58:41 -0700596//
597// Loop setup and traversal.
598//
599
Aart Bik96202302016-10-04 17:33:56 -0700600void HLoopOptimization::LocalRun() {
601 // Build the linear order using the phase-local allocator. This step enables building
602 // a loop hierarchy that properly reflects the outer-inner and previous-next relation.
Vladimir Markoca6fff82017-10-03 14:49:14 +0100603 ScopedArenaVector<HBasicBlock*> linear_order(loop_allocator_->Adapter(kArenaAllocLinearOrder));
604 LinearizeGraph(graph_, &linear_order);
Aart Bik96202302016-10-04 17:33:56 -0700605
Aart Bik281c6812016-08-26 11:31:48 -0700606 // Build the loop hierarchy.
Aart Bik96202302016-10-04 17:33:56 -0700607 for (HBasicBlock* block : linear_order) {
Aart Bik281c6812016-08-26 11:31:48 -0700608 if (block->IsLoopHeader()) {
609 AddLoop(block->GetLoopInformation());
610 }
611 }
Aart Bik96202302016-10-04 17:33:56 -0700612
Aart Bik8c4a8542016-10-06 11:36:57 -0700613 // Traverse the loop hierarchy inner-to-outer and optimize. Traversal can use
Aart Bikf8f5a162017-02-06 15:35:29 -0800614 // temporary data structures using the phase-local allocator. All new HIR
615 // should use the global allocator.
Aart Bik8c4a8542016-10-06 11:36:57 -0700616 if (top_loop_ != nullptr) {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100617 ScopedArenaSet<HInstruction*> iset(loop_allocator_->Adapter(kArenaAllocLoopOptimization));
618 ScopedArenaSafeMap<HInstruction*, HInstruction*> reds(
Aart Bikb29f6842017-07-28 15:58:41 -0700619 std::less<HInstruction*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
Vladimir Markoca6fff82017-10-03 14:49:14 +0100620 ScopedArenaSet<ArrayReference> refs(loop_allocator_->Adapter(kArenaAllocLoopOptimization));
621 ScopedArenaSafeMap<HInstruction*, HInstruction*> map(
Aart Bikf8f5a162017-02-06 15:35:29 -0800622 std::less<HInstruction*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
Vladimir Markoca6fff82017-10-03 14:49:14 +0100623 ScopedArenaSafeMap<HInstruction*, HInstruction*> perm(
Aart Bik0148de42017-09-05 09:25:01 -0700624 std::less<HInstruction*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
Aart Bikf8f5a162017-02-06 15:35:29 -0800625 // Attach.
Aart Bik8c4a8542016-10-06 11:36:57 -0700626 iset_ = &iset;
Aart Bikb29f6842017-07-28 15:58:41 -0700627 reductions_ = &reds;
Aart Bikf8f5a162017-02-06 15:35:29 -0800628 vector_refs_ = &refs;
629 vector_map_ = &map;
Aart Bik0148de42017-09-05 09:25:01 -0700630 vector_permanent_map_ = &perm;
Aart Bikf8f5a162017-02-06 15:35:29 -0800631 // Traverse.
Aart Bik8c4a8542016-10-06 11:36:57 -0700632 TraverseLoopsInnerToOuter(top_loop_);
Aart Bikf8f5a162017-02-06 15:35:29 -0800633 // Detach.
634 iset_ = nullptr;
Aart Bikb29f6842017-07-28 15:58:41 -0700635 reductions_ = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800636 vector_refs_ = nullptr;
637 vector_map_ = nullptr;
Aart Bik0148de42017-09-05 09:25:01 -0700638 vector_permanent_map_ = nullptr;
Aart Bik8c4a8542016-10-06 11:36:57 -0700639 }
Aart Bik281c6812016-08-26 11:31:48 -0700640}
641
642void HLoopOptimization::AddLoop(HLoopInformation* loop_info) {
643 DCHECK(loop_info != nullptr);
Aart Bikf8f5a162017-02-06 15:35:29 -0800644 LoopNode* node = new (loop_allocator_) LoopNode(loop_info);
Aart Bik281c6812016-08-26 11:31:48 -0700645 if (last_loop_ == nullptr) {
646 // First loop.
647 DCHECK(top_loop_ == nullptr);
648 last_loop_ = top_loop_ = node;
649 } else if (loop_info->IsIn(*last_loop_->loop_info)) {
650 // Inner loop.
651 node->outer = last_loop_;
652 DCHECK(last_loop_->inner == nullptr);
653 last_loop_ = last_loop_->inner = node;
654 } else {
655 // Subsequent loop.
656 while (last_loop_->outer != nullptr && !loop_info->IsIn(*last_loop_->outer->loop_info)) {
657 last_loop_ = last_loop_->outer;
658 }
659 node->outer = last_loop_->outer;
660 node->previous = last_loop_;
661 DCHECK(last_loop_->next == nullptr);
662 last_loop_ = last_loop_->next = node;
663 }
664}
665
666void HLoopOptimization::RemoveLoop(LoopNode* node) {
667 DCHECK(node != nullptr);
Aart Bik8c4a8542016-10-06 11:36:57 -0700668 DCHECK(node->inner == nullptr);
669 if (node->previous != nullptr) {
670 // Within sequence.
671 node->previous->next = node->next;
672 if (node->next != nullptr) {
673 node->next->previous = node->previous;
674 }
675 } else {
676 // First of sequence.
677 if (node->outer != nullptr) {
678 node->outer->inner = node->next;
679 } else {
680 top_loop_ = node->next;
681 }
682 if (node->next != nullptr) {
683 node->next->outer = node->outer;
684 node->next->previous = nullptr;
685 }
686 }
Aart Bik281c6812016-08-26 11:31:48 -0700687}
688
Aart Bikb29f6842017-07-28 15:58:41 -0700689bool HLoopOptimization::TraverseLoopsInnerToOuter(LoopNode* node) {
690 bool changed = false;
Aart Bik281c6812016-08-26 11:31:48 -0700691 for ( ; node != nullptr; node = node->next) {
Aart Bikb29f6842017-07-28 15:58:41 -0700692 // Visit inner loops first. Recompute induction information for this
693 // loop if the induction of any inner loop has changed.
694 if (TraverseLoopsInnerToOuter(node->inner)) {
Aart Bik482095d2016-10-10 15:39:10 -0700695 induction_range_.ReVisit(node->loop_info);
696 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800697 // Repeat simplifications in the loop-body until no more changes occur.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800698 // Note that since each simplification consists of eliminating code (without
699 // introducing new code), this process is always finite.
Aart Bikdf7822e2016-12-06 10:05:30 -0800700 do {
701 simplified_ = false;
Aart Bikdf7822e2016-12-06 10:05:30 -0800702 SimplifyInduction(node);
Aart Bik6b69e0a2017-01-11 10:20:43 -0800703 SimplifyBlocks(node);
Aart Bikb29f6842017-07-28 15:58:41 -0700704 changed = simplified_ || changed;
Aart Bikdf7822e2016-12-06 10:05:30 -0800705 } while (simplified_);
Aart Bikf8f5a162017-02-06 15:35:29 -0800706 // Optimize inner loop.
Aart Bik9abf8942016-10-14 09:49:42 -0700707 if (node->inner == nullptr) {
Aart Bikb29f6842017-07-28 15:58:41 -0700708 changed = OptimizeInnerLoop(node) || changed;
Aart Bik9abf8942016-10-14 09:49:42 -0700709 }
Aart Bik281c6812016-08-26 11:31:48 -0700710 }
Aart Bikb29f6842017-07-28 15:58:41 -0700711 return changed;
Aart Bik281c6812016-08-26 11:31:48 -0700712}
713
Aart Bikf8f5a162017-02-06 15:35:29 -0800714//
715// Optimization.
716//
717
Aart Bik281c6812016-08-26 11:31:48 -0700718void HLoopOptimization::SimplifyInduction(LoopNode* node) {
719 HBasicBlock* header = node->loop_info->GetHeader();
720 HBasicBlock* preheader = node->loop_info->GetPreHeader();
Aart Bik8c4a8542016-10-06 11:36:57 -0700721 // Scan the phis in the header to find opportunities to simplify an induction
722 // cycle that is only used outside the loop. Replace these uses, if any, with
723 // the last value and remove the induction cycle.
724 // Examples: for (int i = 0; x != null; i++) { .... no i .... }
725 // for (int i = 0; i < 10; i++, k++) { .... no k .... } return k;
Aart Bik281c6812016-08-26 11:31:48 -0700726 for (HInstructionIterator it(header->GetPhis()); !it.Done(); it.Advance()) {
727 HPhi* phi = it.Current()->AsPhi();
Aart Bikf8f5a162017-02-06 15:35:29 -0800728 if (TrySetPhiInduction(phi, /*restrict_uses*/ true) &&
729 TryAssignLastValue(node->loop_info, phi, preheader, /*collect_loop_uses*/ false)) {
Aart Bik671e48a2017-08-09 13:16:56 -0700730 // Note that it's ok to have replaced uses after the loop with the last value, without
731 // being able to remove the cycle. Environment uses (which are the reason we may not be
732 // able to remove the cycle) within the loop will still hold the right value. We must
733 // have tried first, however, to replace outside uses.
734 if (CanRemoveCycle()) {
735 simplified_ = true;
736 for (HInstruction* i : *iset_) {
737 RemoveFromCycle(i);
738 }
739 DCHECK(CheckInductionSetFullyRemoved(iset_));
Aart Bik281c6812016-08-26 11:31:48 -0700740 }
Aart Bik482095d2016-10-10 15:39:10 -0700741 }
742 }
743}
744
745void HLoopOptimization::SimplifyBlocks(LoopNode* node) {
Aart Bikdf7822e2016-12-06 10:05:30 -0800746 // Iterate over all basic blocks in the loop-body.
747 for (HBlocksInLoopIterator it(*node->loop_info); !it.Done(); it.Advance()) {
748 HBasicBlock* block = it.Current();
749 // Remove dead instructions from the loop-body.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800750 RemoveDeadInstructions(block->GetPhis());
751 RemoveDeadInstructions(block->GetInstructions());
Aart Bikdf7822e2016-12-06 10:05:30 -0800752 // Remove trivial control flow blocks from the loop-body.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800753 if (block->GetPredecessors().size() == 1 &&
754 block->GetSuccessors().size() == 1 &&
755 block->GetSingleSuccessor()->GetPredecessors().size() == 1) {
Aart Bikdf7822e2016-12-06 10:05:30 -0800756 simplified_ = true;
Aart Bik6b69e0a2017-01-11 10:20:43 -0800757 block->MergeWith(block->GetSingleSuccessor());
Aart Bikdf7822e2016-12-06 10:05:30 -0800758 } else if (block->GetSuccessors().size() == 2) {
759 // Trivial if block can be bypassed to either branch.
760 HBasicBlock* succ0 = block->GetSuccessors()[0];
761 HBasicBlock* succ1 = block->GetSuccessors()[1];
762 HBasicBlock* meet0 = nullptr;
763 HBasicBlock* meet1 = nullptr;
764 if (succ0 != succ1 &&
765 IsGotoBlock(succ0, &meet0) &&
766 IsGotoBlock(succ1, &meet1) &&
767 meet0 == meet1 && // meets again
768 meet0 != block && // no self-loop
769 meet0->GetPhis().IsEmpty()) { // not used for merging
770 simplified_ = true;
771 succ0->DisconnectAndDelete();
772 if (block->Dominates(meet0)) {
773 block->RemoveDominatedBlock(meet0);
774 succ1->AddDominatedBlock(meet0);
775 meet0->SetDominator(succ1);
Aart Bike3dedc52016-11-02 17:50:27 -0700776 }
Aart Bik482095d2016-10-10 15:39:10 -0700777 }
Aart Bik281c6812016-08-26 11:31:48 -0700778 }
Aart Bikdf7822e2016-12-06 10:05:30 -0800779 }
Aart Bik281c6812016-08-26 11:31:48 -0700780}
781
Artem Serov121f2032017-10-23 19:19:06 +0100782bool HLoopOptimization::TryOptimizeInnerLoopFinite(LoopNode* node) {
Aart Bik281c6812016-08-26 11:31:48 -0700783 HBasicBlock* header = node->loop_info->GetHeader();
784 HBasicBlock* preheader = node->loop_info->GetPreHeader();
Aart Bik9abf8942016-10-14 09:49:42 -0700785 // Ensure loop header logic is finite.
Aart Bikf8f5a162017-02-06 15:35:29 -0800786 int64_t trip_count = 0;
787 if (!induction_range_.IsFinite(node->loop_info, &trip_count)) {
Aart Bikb29f6842017-07-28 15:58:41 -0700788 return false;
Aart Bik9abf8942016-10-14 09:49:42 -0700789 }
Aart Bik281c6812016-08-26 11:31:48 -0700790 // Ensure there is only a single loop-body (besides the header).
791 HBasicBlock* body = nullptr;
792 for (HBlocksInLoopIterator it(*node->loop_info); !it.Done(); it.Advance()) {
793 if (it.Current() != header) {
794 if (body != nullptr) {
Aart Bikb29f6842017-07-28 15:58:41 -0700795 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700796 }
797 body = it.Current();
798 }
799 }
Andreas Gampef45d61c2017-06-07 10:29:33 -0700800 CHECK(body != nullptr);
Aart Bik281c6812016-08-26 11:31:48 -0700801 // Ensure there is only a single exit point.
802 if (header->GetSuccessors().size() != 2) {
Aart Bikb29f6842017-07-28 15:58:41 -0700803 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700804 }
805 HBasicBlock* exit = (header->GetSuccessors()[0] == body)
806 ? header->GetSuccessors()[1]
807 : header->GetSuccessors()[0];
Aart Bik8c4a8542016-10-06 11:36:57 -0700808 // Ensure exit can only be reached by exiting loop.
Aart Bik281c6812016-08-26 11:31:48 -0700809 if (exit->GetPredecessors().size() != 1) {
Aart Bikb29f6842017-07-28 15:58:41 -0700810 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700811 }
Aart Bik6b69e0a2017-01-11 10:20:43 -0800812 // Detect either an empty loop (no side effects other than plain iteration) or
813 // a trivial loop (just iterating once). Replace subsequent index uses, if any,
814 // with the last value and remove the loop, possibly after unrolling its body.
Aart Bikb29f6842017-07-28 15:58:41 -0700815 HPhi* main_phi = nullptr;
816 if (TrySetSimpleLoopHeader(header, &main_phi)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -0800817 bool is_empty = IsEmptyBody(body);
Aart Bikb29f6842017-07-28 15:58:41 -0700818 if (reductions_->empty() && // TODO: possible with some effort
819 (is_empty || trip_count == 1) &&
820 TryAssignLastValue(node->loop_info, main_phi, preheader, /*collect_loop_uses*/ true)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -0800821 if (!is_empty) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800822 // Unroll the loop-body, which sees initial value of the index.
Aart Bikb29f6842017-07-28 15:58:41 -0700823 main_phi->ReplaceWith(main_phi->InputAt(0));
Aart Bik6b69e0a2017-01-11 10:20:43 -0800824 preheader->MergeInstructionsWith(body);
825 }
826 body->DisconnectAndDelete();
827 exit->RemovePredecessor(header);
828 header->RemoveSuccessor(exit);
829 header->RemoveDominatedBlock(exit);
830 header->DisconnectAndDelete();
831 preheader->AddSuccessor(exit);
Aart Bikf8f5a162017-02-06 15:35:29 -0800832 preheader->AddInstruction(new (global_allocator_) HGoto());
Aart Bik6b69e0a2017-01-11 10:20:43 -0800833 preheader->AddDominatedBlock(exit);
834 exit->SetDominator(preheader);
835 RemoveLoop(node); // update hierarchy
Aart Bikb29f6842017-07-28 15:58:41 -0700836 return true;
Aart Bikf8f5a162017-02-06 15:35:29 -0800837 }
838 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800839 // Vectorize loop, if possible and valid.
Aart Bikb29f6842017-07-28 15:58:41 -0700840 if (kEnableVectorization &&
841 TrySetSimpleLoopHeader(header, &main_phi) &&
Aart Bikb29f6842017-07-28 15:58:41 -0700842 ShouldVectorize(node, body, trip_count) &&
843 TryAssignLastValue(node->loop_info, main_phi, preheader, /*collect_loop_uses*/ true)) {
844 Vectorize(node, body, exit, trip_count);
845 graph_->SetHasSIMD(true); // flag SIMD usage
Aart Bik21b85922017-09-06 13:29:16 -0700846 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorized);
Aart Bikb29f6842017-07-28 15:58:41 -0700847 return true;
Aart Bikf8f5a162017-02-06 15:35:29 -0800848 }
Aart Bikb29f6842017-07-28 15:58:41 -0700849 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -0800850}
851
Artem Serov121f2032017-10-23 19:19:06 +0100852bool HLoopOptimization::OptimizeInnerLoop(LoopNode* node) {
853 return TryOptimizeInnerLoopFinite(node) ||
854 TryUnrollingForBranchPenaltyReduction(node);
855}
856
857void HLoopOptimization::PeelOrUnrollOnce(LoopNode* loop_node,
858 bool do_unrolling,
859 SuperblockCloner::HBasicBlockMap* bb_map,
860 SuperblockCloner::HInstructionMap* hir_map) {
861 // TODO: peel loop nests.
862 DCHECK(loop_node->inner == nullptr);
863
864 // Check that loop info is up-to-date.
865 HLoopInformation* loop_info = loop_node->loop_info;
866 HBasicBlock* header = loop_info->GetHeader();
867 DCHECK(loop_info == header->GetLoopInformation());
868
869 PeelUnrollHelper helper(loop_info, bb_map, hir_map);
870 DCHECK(helper.IsLoopClonable());
871 HBasicBlock* new_header = do_unrolling ? helper.DoUnrolling() : helper.DoPeeling();
872 DCHECK(header == new_header);
873 DCHECK(loop_info == new_header->GetLoopInformation());
874}
875
876//
877// Loop unrolling: generic part methods.
878//
879
880bool HLoopOptimization::TryUnrollingForBranchPenaltyReduction(LoopNode* loop_node) {
881 // Don't run peeling/unrolling if compiler_driver_ is nullptr (i.e., running under tests)
882 // as InstructionSet is needed.
883 if (!kEnableScalarUnrolling || compiler_driver_ == nullptr) {
884 return false;
885 }
886
887 HLoopInformation* loop_info = loop_node->loop_info;
888 int64_t trip_count = 0;
889 // Only unroll loops with a known tripcount.
890 if (!induction_range_.HasKnownTripCount(loop_info, &trip_count)) {
891 return false;
892 }
893
894 uint32_t unrolling_factor = arch_loop_helper_->GetScalarUnrollingFactor(loop_info, trip_count);
895 if (unrolling_factor == kNoUnrollingFactor) {
896 return false;
897 }
898
899 LoopAnalysisInfo loop_analysis_info(loop_info);
900 LoopAnalysis::CalculateLoopBasicProperties(loop_info, &loop_analysis_info);
901
902 // Check "IsLoopClonable" last as it can be time-consuming.
903 if (arch_loop_helper_->IsLoopTooBigForScalarUnrolling(&loop_analysis_info) ||
904 (loop_analysis_info.GetNumberOfExits() > 1) ||
905 loop_analysis_info.HasInstructionsPreventingScalarUnrolling() ||
906 !PeelUnrollHelper::IsLoopClonable(loop_info)) {
907 return false;
908 }
909
910 // TODO: support other unrolling factors.
911 DCHECK_EQ(unrolling_factor, 2u);
912
913 // Perform unrolling.
914 ArenaAllocator* arena = loop_info->GetHeader()->GetGraph()->GetAllocator();
915 SuperblockCloner::HBasicBlockMap bb_map(
916 std::less<HBasicBlock*>(), arena->Adapter(kArenaAllocSuperblockCloner));
917 SuperblockCloner::HInstructionMap hir_map(
918 std::less<HInstruction*>(), arena->Adapter(kArenaAllocSuperblockCloner));
919 PeelOrUnrollOnce(loop_node, /* unrolling */ true, &bb_map, &hir_map);
920
921 // Remove the redundant loop check after unrolling.
922 HIf* copy_hif = bb_map.Get(loop_info->GetHeader())->GetLastInstruction()->AsIf();
923 int32_t constant = loop_info->Contains(*copy_hif->IfTrueSuccessor()) ? 1 : 0;
924 copy_hif->ReplaceInput(graph_->GetIntConstant(constant), 0u);
925
926 return true;
927}
928
Aart Bikf8f5a162017-02-06 15:35:29 -0800929//
930// Loop vectorization. The implementation is based on the book by Aart J.C. Bik:
931// "The Software Vectorization Handbook. Applying Multimedia Extensions for Maximum Performance."
932// Intel Press, June, 2004 (http://www.aartbik.com/).
933//
934
Aart Bik14a68b42017-06-08 14:06:58 -0700935bool HLoopOptimization::ShouldVectorize(LoopNode* node, HBasicBlock* block, int64_t trip_count) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800936 // Reset vector bookkeeping.
937 vector_length_ = 0;
938 vector_refs_->clear();
Aart Bik38a3f212017-10-20 17:02:21 -0700939 vector_static_peeling_factor_ = 0;
940 vector_dynamic_peeling_candidate_ = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800941 vector_runtime_test_a_ =
Igor Murashkin2ffb7032017-11-08 13:35:21 -0800942 vector_runtime_test_b_ = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800943
944 // Phis in the loop-body prevent vectorization.
945 if (!block->GetPhis().IsEmpty()) {
946 return false;
947 }
948
949 // Scan the loop-body, starting a right-hand-side tree traversal at each left-hand-side
950 // occurrence, which allows passing down attributes down the use tree.
951 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
952 if (!VectorizeDef(node, it.Current(), /*generate_code*/ false)) {
953 return false; // failure to vectorize a left-hand-side
954 }
955 }
956
Aart Bik38a3f212017-10-20 17:02:21 -0700957 // Prepare alignment analysis:
958 // (1) find desired alignment (SIMD vector size in bytes).
959 // (2) initialize static loop peeling votes (peeling factor that will
960 // make one particular reference aligned), never to exceed (1).
961 // (3) variable to record how many references share same alignment.
962 // (4) variable to record suitable candidate for dynamic loop peeling.
963 uint32_t desired_alignment = GetVectorSizeInBytes();
964 DCHECK_LE(desired_alignment, 16u);
965 uint32_t peeling_votes[16] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
966 uint32_t max_num_same_alignment = 0;
967 const ArrayReference* peeling_candidate = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800968
969 // Data dependence analysis. Find each pair of references with same type, where
970 // at least one is a write. Each such pair denotes a possible data dependence.
971 // This analysis exploits the property that differently typed arrays cannot be
972 // aliased, as well as the property that references either point to the same
973 // array or to two completely disjoint arrays, i.e., no partial aliasing.
974 // Other than a few simply heuristics, no detailed subscript analysis is done.
Aart Bik38a3f212017-10-20 17:02:21 -0700975 // The scan over references also prepares finding a suitable alignment strategy.
Aart Bikf8f5a162017-02-06 15:35:29 -0800976 for (auto i = vector_refs_->begin(); i != vector_refs_->end(); ++i) {
Aart Bik38a3f212017-10-20 17:02:21 -0700977 uint32_t num_same_alignment = 0;
978 // Scan over all next references.
Aart Bikf8f5a162017-02-06 15:35:29 -0800979 for (auto j = i; ++j != vector_refs_->end(); ) {
980 if (i->type == j->type && (i->lhs || j->lhs)) {
981 // Found same-typed a[i+x] vs. b[i+y], where at least one is a write.
982 HInstruction* a = i->base;
983 HInstruction* b = j->base;
984 HInstruction* x = i->offset;
985 HInstruction* y = j->offset;
986 if (a == b) {
987 // Found a[i+x] vs. a[i+y]. Accept if x == y (loop-independent data dependence).
988 // Conservatively assume a loop-carried data dependence otherwise, and reject.
989 if (x != y) {
990 return false;
991 }
Aart Bik38a3f212017-10-20 17:02:21 -0700992 // Count the number of references that have the same alignment (since
993 // base and offset are the same) and where at least one is a write, so
994 // e.g. a[i] = a[i] + b[i] counts a[i] but not b[i]).
995 num_same_alignment++;
Aart Bikf8f5a162017-02-06 15:35:29 -0800996 } else {
997 // Found a[i+x] vs. b[i+y]. Accept if x == y (at worst loop-independent data dependence).
998 // Conservatively assume a potential loop-carried data dependence otherwise, avoided by
999 // generating an explicit a != b disambiguation runtime test on the two references.
1000 if (x != y) {
Aart Bik37dc4df2017-06-28 14:08:00 -07001001 // To avoid excessive overhead, we only accept one a != b test.
1002 if (vector_runtime_test_a_ == nullptr) {
1003 // First test found.
1004 vector_runtime_test_a_ = a;
1005 vector_runtime_test_b_ = b;
1006 } else if ((vector_runtime_test_a_ != a || vector_runtime_test_b_ != b) &&
1007 (vector_runtime_test_a_ != b || vector_runtime_test_b_ != a)) {
1008 return false; // second test would be needed
Aart Bikf8f5a162017-02-06 15:35:29 -08001009 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001010 }
1011 }
1012 }
1013 }
Aart Bik38a3f212017-10-20 17:02:21 -07001014 // Update information for finding suitable alignment strategy:
1015 // (1) update votes for static loop peeling,
1016 // (2) update suitable candidate for dynamic loop peeling.
1017 Alignment alignment = ComputeAlignment(i->offset, i->type, i->is_string_char_at);
1018 if (alignment.Base() >= desired_alignment) {
1019 // If the array/string object has a known, sufficient alignment, use the
1020 // initial offset to compute the static loop peeling vote (this always
1021 // works, since elements have natural alignment).
1022 uint32_t offset = alignment.Offset() & (desired_alignment - 1u);
1023 uint32_t vote = (offset == 0)
1024 ? 0
1025 : ((desired_alignment - offset) >> DataType::SizeShift(i->type));
1026 DCHECK_LT(vote, 16u);
1027 ++peeling_votes[vote];
1028 } else if (BaseAlignment() >= desired_alignment &&
1029 num_same_alignment > max_num_same_alignment) {
1030 // Otherwise, if the array/string object has a known, sufficient alignment
1031 // for just the base but with an unknown offset, record the candidate with
1032 // the most occurrences for dynamic loop peeling (again, the peeling always
1033 // works, since elements have natural alignment).
1034 max_num_same_alignment = num_same_alignment;
1035 peeling_candidate = &(*i);
1036 }
1037 } // for i
Aart Bikf8f5a162017-02-06 15:35:29 -08001038
Aart Bik38a3f212017-10-20 17:02:21 -07001039 // Find a suitable alignment strategy.
1040 SetAlignmentStrategy(peeling_votes, peeling_candidate);
1041
1042 // Does vectorization seem profitable?
1043 if (!IsVectorizationProfitable(trip_count)) {
1044 return false;
1045 }
Aart Bik14a68b42017-06-08 14:06:58 -07001046
Aart Bikf8f5a162017-02-06 15:35:29 -08001047 // Success!
1048 return true;
1049}
1050
1051void HLoopOptimization::Vectorize(LoopNode* node,
1052 HBasicBlock* block,
1053 HBasicBlock* exit,
1054 int64_t trip_count) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001055 HBasicBlock* header = node->loop_info->GetHeader();
1056 HBasicBlock* preheader = node->loop_info->GetPreHeader();
1057
Aart Bik14a68b42017-06-08 14:06:58 -07001058 // Pick a loop unrolling factor for the vector loop.
Artem Serov121f2032017-10-23 19:19:06 +01001059 uint32_t unroll = arch_loop_helper_->GetSIMDUnrollingFactor(
1060 block, trip_count, MaxNumberPeeled(), vector_length_);
Aart Bik14a68b42017-06-08 14:06:58 -07001061 uint32_t chunk = vector_length_ * unroll;
1062
Aart Bik38a3f212017-10-20 17:02:21 -07001063 DCHECK(trip_count == 0 || (trip_count >= MaxNumberPeeled() + chunk));
1064
Aart Bik14a68b42017-06-08 14:06:58 -07001065 // A cleanup loop is needed, at least, for any unknown trip count or
1066 // for a known trip count with remainder iterations after vectorization.
Aart Bik38a3f212017-10-20 17:02:21 -07001067 bool needs_cleanup = trip_count == 0 ||
1068 ((trip_count - vector_static_peeling_factor_) % chunk) != 0;
Aart Bikf8f5a162017-02-06 15:35:29 -08001069
1070 // Adjust vector bookkeeping.
Aart Bikb29f6842017-07-28 15:58:41 -07001071 HPhi* main_phi = nullptr;
1072 bool is_simple_loop_header = TrySetSimpleLoopHeader(header, &main_phi); // refills sets
Aart Bikf8f5a162017-02-06 15:35:29 -08001073 DCHECK(is_simple_loop_header);
Aart Bik14a68b42017-06-08 14:06:58 -07001074 vector_header_ = header;
1075 vector_body_ = block;
Aart Bikf8f5a162017-02-06 15:35:29 -08001076
Aart Bikdbbac8f2017-09-01 13:06:08 -07001077 // Loop induction type.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001078 DataType::Type induc_type = main_phi->GetType();
1079 DCHECK(induc_type == DataType::Type::kInt32 || induc_type == DataType::Type::kInt64)
1080 << induc_type;
Aart Bikdbbac8f2017-09-01 13:06:08 -07001081
Aart Bik38a3f212017-10-20 17:02:21 -07001082 // Generate the trip count for static or dynamic loop peeling, if needed:
1083 // ptc = <peeling factor>;
Aart Bik14a68b42017-06-08 14:06:58 -07001084 HInstruction* ptc = nullptr;
Aart Bik38a3f212017-10-20 17:02:21 -07001085 if (vector_static_peeling_factor_ != 0) {
1086 // Static loop peeling for SIMD alignment (using the most suitable
1087 // fixed peeling factor found during prior alignment analysis).
1088 DCHECK(vector_dynamic_peeling_candidate_ == nullptr);
1089 ptc = graph_->GetConstant(induc_type, vector_static_peeling_factor_);
1090 } else if (vector_dynamic_peeling_candidate_ != nullptr) {
1091 // Dynamic loop peeling for SIMD alignment (using the most suitable
1092 // candidate found during prior alignment analysis):
1093 // rem = offset % ALIGN; // adjusted as #elements
1094 // ptc = rem == 0 ? 0 : (ALIGN - rem);
1095 uint32_t shift = DataType::SizeShift(vector_dynamic_peeling_candidate_->type);
1096 uint32_t align = GetVectorSizeInBytes() >> shift;
1097 uint32_t hidden_offset = HiddenOffset(vector_dynamic_peeling_candidate_->type,
1098 vector_dynamic_peeling_candidate_->is_string_char_at);
1099 HInstruction* adjusted_offset = graph_->GetConstant(induc_type, hidden_offset >> shift);
1100 HInstruction* offset = Insert(preheader, new (global_allocator_) HAdd(
1101 induc_type, vector_dynamic_peeling_candidate_->offset, adjusted_offset));
1102 HInstruction* rem = Insert(preheader, new (global_allocator_) HAnd(
1103 induc_type, offset, graph_->GetConstant(induc_type, align - 1u)));
1104 HInstruction* sub = Insert(preheader, new (global_allocator_) HSub(
1105 induc_type, graph_->GetConstant(induc_type, align), rem));
1106 HInstruction* cond = Insert(preheader, new (global_allocator_) HEqual(
1107 rem, graph_->GetConstant(induc_type, 0)));
1108 ptc = Insert(preheader, new (global_allocator_) HSelect(
1109 cond, graph_->GetConstant(induc_type, 0), sub, kNoDexPc));
1110 needs_cleanup = true; // don't know the exact amount
Aart Bik14a68b42017-06-08 14:06:58 -07001111 }
1112
1113 // Generate loop control:
Aart Bikf8f5a162017-02-06 15:35:29 -08001114 // stc = <trip-count>;
Aart Bik38a3f212017-10-20 17:02:21 -07001115 // ptc = min(stc, ptc);
Aart Bik14a68b42017-06-08 14:06:58 -07001116 // vtc = stc - (stc - ptc) % chunk;
1117 // i = 0;
Aart Bikf8f5a162017-02-06 15:35:29 -08001118 HInstruction* stc = induction_range_.GenerateTripCount(node->loop_info, graph_, preheader);
1119 HInstruction* vtc = stc;
1120 if (needs_cleanup) {
Aart Bik14a68b42017-06-08 14:06:58 -07001121 DCHECK(IsPowerOfTwo(chunk));
1122 HInstruction* diff = stc;
1123 if (ptc != nullptr) {
Aart Bik38a3f212017-10-20 17:02:21 -07001124 if (trip_count == 0) {
1125 HInstruction* cond = Insert(preheader, new (global_allocator_) HAboveOrEqual(stc, ptc));
1126 ptc = Insert(preheader, new (global_allocator_) HSelect(cond, ptc, stc, kNoDexPc));
1127 }
Aart Bik14a68b42017-06-08 14:06:58 -07001128 diff = Insert(preheader, new (global_allocator_) HSub(induc_type, stc, ptc));
1129 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001130 HInstruction* rem = Insert(
1131 preheader, new (global_allocator_) HAnd(induc_type,
Aart Bik14a68b42017-06-08 14:06:58 -07001132 diff,
Aart Bikdbbac8f2017-09-01 13:06:08 -07001133 graph_->GetConstant(induc_type, chunk - 1)));
Aart Bikf8f5a162017-02-06 15:35:29 -08001134 vtc = Insert(preheader, new (global_allocator_) HSub(induc_type, stc, rem));
1135 }
Aart Bikdbbac8f2017-09-01 13:06:08 -07001136 vector_index_ = graph_->GetConstant(induc_type, 0);
Aart Bikf8f5a162017-02-06 15:35:29 -08001137
1138 // Generate runtime disambiguation test:
1139 // vtc = a != b ? vtc : 0;
1140 if (vector_runtime_test_a_ != nullptr) {
1141 HInstruction* rt = Insert(
1142 preheader,
1143 new (global_allocator_) HNotEqual(vector_runtime_test_a_, vector_runtime_test_b_));
1144 vtc = Insert(preheader,
Aart Bikdbbac8f2017-09-01 13:06:08 -07001145 new (global_allocator_)
1146 HSelect(rt, vtc, graph_->GetConstant(induc_type, 0), kNoDexPc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001147 needs_cleanup = true;
1148 }
1149
Aart Bik38a3f212017-10-20 17:02:21 -07001150 // Generate alignment peeling loop, if needed:
Aart Bik14a68b42017-06-08 14:06:58 -07001151 // for ( ; i < ptc; i += 1)
1152 // <loop-body>
Aart Bik38a3f212017-10-20 17:02:21 -07001153 //
1154 // NOTE: The alignment forced by the peeling loop is preserved even if data is
1155 // moved around during suspend checks, since all analysis was based on
1156 // nothing more than the Android runtime alignment conventions.
Aart Bik14a68b42017-06-08 14:06:58 -07001157 if (ptc != nullptr) {
1158 vector_mode_ = kSequential;
1159 GenerateNewLoop(node,
1160 block,
1161 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
1162 vector_index_,
1163 ptc,
Aart Bikdbbac8f2017-09-01 13:06:08 -07001164 graph_->GetConstant(induc_type, 1),
Aart Bik521b50f2017-09-09 10:44:45 -07001165 kNoUnrollingFactor);
Aart Bik14a68b42017-06-08 14:06:58 -07001166 }
1167
1168 // Generate vector loop, possibly further unrolled:
1169 // for ( ; i < vtc; i += chunk)
Aart Bikf8f5a162017-02-06 15:35:29 -08001170 // <vectorized-loop-body>
1171 vector_mode_ = kVector;
1172 GenerateNewLoop(node,
1173 block,
Aart Bik14a68b42017-06-08 14:06:58 -07001174 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
1175 vector_index_,
Aart Bikf8f5a162017-02-06 15:35:29 -08001176 vtc,
Aart Bikdbbac8f2017-09-01 13:06:08 -07001177 graph_->GetConstant(induc_type, vector_length_), // increment per unroll
Aart Bik14a68b42017-06-08 14:06:58 -07001178 unroll);
Aart Bikf8f5a162017-02-06 15:35:29 -08001179 HLoopInformation* vloop = vector_header_->GetLoopInformation();
1180
1181 // Generate cleanup loop, if needed:
1182 // for ( ; i < stc; i += 1)
1183 // <loop-body>
1184 if (needs_cleanup) {
1185 vector_mode_ = kSequential;
1186 GenerateNewLoop(node,
1187 block,
1188 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
Aart Bik14a68b42017-06-08 14:06:58 -07001189 vector_index_,
Aart Bikf8f5a162017-02-06 15:35:29 -08001190 stc,
Aart Bikdbbac8f2017-09-01 13:06:08 -07001191 graph_->GetConstant(induc_type, 1),
Aart Bik521b50f2017-09-09 10:44:45 -07001192 kNoUnrollingFactor);
Aart Bikf8f5a162017-02-06 15:35:29 -08001193 }
1194
Aart Bik0148de42017-09-05 09:25:01 -07001195 // Link reductions to their final uses.
1196 for (auto i = reductions_->begin(); i != reductions_->end(); ++i) {
1197 if (i->first->IsPhi()) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001198 HInstruction* phi = i->first;
1199 HInstruction* repl = ReduceAndExtractIfNeeded(i->second);
1200 // Deal with regular uses.
1201 for (const HUseListNode<HInstruction*>& use : phi->GetUses()) {
1202 induction_range_.Replace(use.GetUser(), phi, repl); // update induction use
1203 }
1204 phi->ReplaceWith(repl);
Aart Bik0148de42017-09-05 09:25:01 -07001205 }
1206 }
1207
Aart Bikf8f5a162017-02-06 15:35:29 -08001208 // Remove the original loop by disconnecting the body block
1209 // and removing all instructions from the header.
1210 block->DisconnectAndDelete();
1211 while (!header->GetFirstInstruction()->IsGoto()) {
1212 header->RemoveInstruction(header->GetFirstInstruction());
1213 }
Aart Bikb29f6842017-07-28 15:58:41 -07001214
Aart Bik14a68b42017-06-08 14:06:58 -07001215 // Update loop hierarchy: the old header now resides in the same outer loop
1216 // as the old preheader. Note that we don't bother putting sequential
1217 // loops back in the hierarchy at this point.
Aart Bikf8f5a162017-02-06 15:35:29 -08001218 header->SetLoopInformation(preheader->GetLoopInformation()); // outward
1219 node->loop_info = vloop;
1220}
1221
1222void HLoopOptimization::GenerateNewLoop(LoopNode* node,
1223 HBasicBlock* block,
1224 HBasicBlock* new_preheader,
1225 HInstruction* lo,
1226 HInstruction* hi,
Aart Bik14a68b42017-06-08 14:06:58 -07001227 HInstruction* step,
1228 uint32_t unroll) {
1229 DCHECK(unroll == 1 || vector_mode_ == kVector);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001230 DataType::Type induc_type = lo->GetType();
Aart Bikf8f5a162017-02-06 15:35:29 -08001231 // Prepare new loop.
Aart Bikf8f5a162017-02-06 15:35:29 -08001232 vector_preheader_ = new_preheader,
1233 vector_header_ = vector_preheader_->GetSingleSuccessor();
1234 vector_body_ = vector_header_->GetSuccessors()[1];
Aart Bik14a68b42017-06-08 14:06:58 -07001235 HPhi* phi = new (global_allocator_) HPhi(global_allocator_,
1236 kNoRegNumber,
1237 0,
1238 HPhi::ToPhiType(induc_type));
Aart Bikb07d1bc2017-04-05 10:03:15 -07001239 // Generate header and prepare body.
Aart Bikf8f5a162017-02-06 15:35:29 -08001240 // for (i = lo; i < hi; i += step)
1241 // <loop-body>
Aart Bik14a68b42017-06-08 14:06:58 -07001242 HInstruction* cond = new (global_allocator_) HAboveOrEqual(phi, hi);
1243 vector_header_->AddPhi(phi);
Aart Bikf8f5a162017-02-06 15:35:29 -08001244 vector_header_->AddInstruction(cond);
1245 vector_header_->AddInstruction(new (global_allocator_) HIf(cond));
Aart Bik14a68b42017-06-08 14:06:58 -07001246 vector_index_ = phi;
Aart Bik0148de42017-09-05 09:25:01 -07001247 vector_permanent_map_->clear(); // preserved over unrolling
Aart Bik14a68b42017-06-08 14:06:58 -07001248 for (uint32_t u = 0; u < unroll; u++) {
Aart Bik14a68b42017-06-08 14:06:58 -07001249 // Generate instruction map.
Aart Bik0148de42017-09-05 09:25:01 -07001250 vector_map_->clear();
Aart Bik14a68b42017-06-08 14:06:58 -07001251 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
1252 bool vectorized_def = VectorizeDef(node, it.Current(), /*generate_code*/ true);
1253 DCHECK(vectorized_def);
1254 }
1255 // Generate body from the instruction map, but in original program order.
1256 HEnvironment* env = vector_header_->GetFirstInstruction()->GetEnvironment();
1257 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
1258 auto i = vector_map_->find(it.Current());
1259 if (i != vector_map_->end() && !i->second->IsInBlock()) {
1260 Insert(vector_body_, i->second);
1261 // Deal with instructions that need an environment, such as the scalar intrinsics.
1262 if (i->second->NeedsEnvironment()) {
1263 i->second->CopyEnvironmentFromWithLoopPhiAdjustment(env, vector_header_);
1264 }
1265 }
1266 }
Aart Bik0148de42017-09-05 09:25:01 -07001267 // Generate the induction.
Aart Bik14a68b42017-06-08 14:06:58 -07001268 vector_index_ = new (global_allocator_) HAdd(induc_type, vector_index_, step);
1269 Insert(vector_body_, vector_index_);
Aart Bikf8f5a162017-02-06 15:35:29 -08001270 }
Aart Bik0148de42017-09-05 09:25:01 -07001271 // Finalize phi inputs for the reductions (if any).
1272 for (auto i = reductions_->begin(); i != reductions_->end(); ++i) {
1273 if (!i->first->IsPhi()) {
1274 DCHECK(i->second->IsPhi());
1275 GenerateVecReductionPhiInputs(i->second->AsPhi(), i->first);
1276 }
1277 }
Aart Bikb29f6842017-07-28 15:58:41 -07001278 // Finalize phi inputs for the loop index.
Aart Bik14a68b42017-06-08 14:06:58 -07001279 phi->AddInput(lo);
1280 phi->AddInput(vector_index_);
1281 vector_index_ = phi;
Aart Bikf8f5a162017-02-06 15:35:29 -08001282}
1283
Aart Bikf8f5a162017-02-06 15:35:29 -08001284bool HLoopOptimization::VectorizeDef(LoopNode* node,
1285 HInstruction* instruction,
1286 bool generate_code) {
1287 // Accept a left-hand-side array base[index] for
1288 // (1) supported vector type,
1289 // (2) loop-invariant base,
1290 // (3) unit stride index,
1291 // (4) vectorizable right-hand-side value.
1292 uint64_t restrictions = kNone;
1293 if (instruction->IsArraySet()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001294 DataType::Type type = instruction->AsArraySet()->GetComponentType();
Aart Bikf8f5a162017-02-06 15:35:29 -08001295 HInstruction* base = instruction->InputAt(0);
1296 HInstruction* index = instruction->InputAt(1);
1297 HInstruction* value = instruction->InputAt(2);
1298 HInstruction* offset = nullptr;
1299 if (TrySetVectorType(type, &restrictions) &&
1300 node->loop_info->IsDefinedOutOfTheLoop(base) &&
Aart Bik37dc4df2017-06-28 14:08:00 -07001301 induction_range_.IsUnitStride(instruction, index, graph_, &offset) &&
Aart Bikf8f5a162017-02-06 15:35:29 -08001302 VectorizeUse(node, value, generate_code, type, restrictions)) {
1303 if (generate_code) {
1304 GenerateVecSub(index, offset);
Aart Bik14a68b42017-06-08 14:06:58 -07001305 GenerateVecMem(instruction, vector_map_->Get(index), vector_map_->Get(value), offset, type);
Aart Bikf8f5a162017-02-06 15:35:29 -08001306 } else {
1307 vector_refs_->insert(ArrayReference(base, offset, type, /*lhs*/ true));
1308 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08001309 return true;
1310 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001311 return false;
1312 }
Aart Bik0148de42017-09-05 09:25:01 -07001313 // Accept a left-hand-side reduction for
1314 // (1) supported vector type,
1315 // (2) vectorizable right-hand-side value.
1316 auto redit = reductions_->find(instruction);
1317 if (redit != reductions_->end()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001318 DataType::Type type = instruction->GetType();
Aart Bikdbbac8f2017-09-01 13:06:08 -07001319 // Recognize SAD idiom or direct reduction.
1320 if (VectorizeSADIdiom(node, instruction, generate_code, type, restrictions) ||
1321 (TrySetVectorType(type, &restrictions) &&
1322 VectorizeUse(node, instruction, generate_code, type, restrictions))) {
Aart Bik0148de42017-09-05 09:25:01 -07001323 if (generate_code) {
1324 HInstruction* new_red = vector_map_->Get(instruction);
1325 vector_permanent_map_->Put(new_red, vector_map_->Get(redit->second));
1326 vector_permanent_map_->Overwrite(redit->second, new_red);
1327 }
1328 return true;
1329 }
1330 return false;
1331 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001332 // Branch back okay.
1333 if (instruction->IsGoto()) {
1334 return true;
1335 }
1336 // Otherwise accept only expressions with no effects outside the immediate loop-body.
1337 // Note that actual uses are inspected during right-hand-side tree traversal.
1338 return !IsUsedOutsideLoop(node->loop_info, instruction) && !instruction->DoesAnyWrite();
1339}
1340
Aart Bikf8f5a162017-02-06 15:35:29 -08001341bool HLoopOptimization::VectorizeUse(LoopNode* node,
1342 HInstruction* instruction,
1343 bool generate_code,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001344 DataType::Type type,
Aart Bikf8f5a162017-02-06 15:35:29 -08001345 uint64_t restrictions) {
1346 // Accept anything for which code has already been generated.
1347 if (generate_code) {
1348 if (vector_map_->find(instruction) != vector_map_->end()) {
1349 return true;
1350 }
1351 }
1352 // Continue the right-hand-side tree traversal, passing in proper
1353 // types and vector restrictions along the way. During code generation,
1354 // all new nodes are drawn from the global allocator.
1355 if (node->loop_info->IsDefinedOutOfTheLoop(instruction)) {
1356 // Accept invariant use, using scalar expansion.
1357 if (generate_code) {
1358 GenerateVecInv(instruction, type);
1359 }
1360 return true;
1361 } else if (instruction->IsArrayGet()) {
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001362 // Deal with vector restrictions.
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001363 bool is_string_char_at = instruction->AsArrayGet()->IsStringCharAt();
1364 if (is_string_char_at && HasVectorRestrictions(restrictions, kNoStringCharAt)) {
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001365 return false;
1366 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001367 // Accept a right-hand-side array base[index] for
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001368 // (1) matching vector type (exact match or signed/unsigned integral type of the same size),
Aart Bikf8f5a162017-02-06 15:35:29 -08001369 // (2) loop-invariant base,
1370 // (3) unit stride index,
1371 // (4) vectorizable right-hand-side value.
1372 HInstruction* base = instruction->InputAt(0);
1373 HInstruction* index = instruction->InputAt(1);
1374 HInstruction* offset = nullptr;
Aart Bik46b6dbc2017-10-03 11:37:37 -07001375 if (HVecOperation::ToSignedType(type) == HVecOperation::ToSignedType(instruction->GetType()) &&
Aart Bikf8f5a162017-02-06 15:35:29 -08001376 node->loop_info->IsDefinedOutOfTheLoop(base) &&
Aart Bik37dc4df2017-06-28 14:08:00 -07001377 induction_range_.IsUnitStride(instruction, index, graph_, &offset)) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001378 if (generate_code) {
1379 GenerateVecSub(index, offset);
Aart Bik14a68b42017-06-08 14:06:58 -07001380 GenerateVecMem(instruction, vector_map_->Get(index), nullptr, offset, type);
Aart Bikf8f5a162017-02-06 15:35:29 -08001381 } else {
Aart Bik38a3f212017-10-20 17:02:21 -07001382 vector_refs_->insert(ArrayReference(base, offset, type, /*lhs*/ false, is_string_char_at));
Aart Bikf8f5a162017-02-06 15:35:29 -08001383 }
1384 return true;
1385 }
Aart Bik0148de42017-09-05 09:25:01 -07001386 } else if (instruction->IsPhi()) {
1387 // Accept particular phi operations.
1388 if (reductions_->find(instruction) != reductions_->end()) {
1389 // Deal with vector restrictions.
1390 if (HasVectorRestrictions(restrictions, kNoReduction)) {
1391 return false;
1392 }
1393 // Accept a reduction.
1394 if (generate_code) {
1395 GenerateVecReductionPhi(instruction->AsPhi());
1396 }
1397 return true;
1398 }
1399 // TODO: accept right-hand-side induction?
1400 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001401 } else if (instruction->IsTypeConversion()) {
1402 // Accept particular type conversions.
1403 HTypeConversion* conversion = instruction->AsTypeConversion();
1404 HInstruction* opa = conversion->InputAt(0);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001405 DataType::Type from = conversion->GetInputType();
1406 DataType::Type to = conversion->GetResultType();
1407 if (DataType::IsIntegralType(from) && DataType::IsIntegralType(to)) {
Aart Bik38a3f212017-10-20 17:02:21 -07001408 uint32_t size_vec = DataType::Size(type);
1409 uint32_t size_from = DataType::Size(from);
1410 uint32_t size_to = DataType::Size(to);
Aart Bikdbbac8f2017-09-01 13:06:08 -07001411 // Accept an integral conversion
1412 // (1a) narrowing into vector type, "wider" operations cannot bring in higher order bits, or
1413 // (1b) widening from at least vector type, and
1414 // (2) vectorizable operand.
1415 if ((size_to < size_from &&
1416 size_to == size_vec &&
1417 VectorizeUse(node, opa, generate_code, type, restrictions | kNoHiBits)) ||
1418 (size_to >= size_from &&
1419 size_from >= size_vec &&
Aart Bik4d1a9d42017-10-19 14:40:55 -07001420 VectorizeUse(node, opa, generate_code, type, restrictions))) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001421 if (generate_code) {
1422 if (vector_mode_ == kVector) {
1423 vector_map_->Put(instruction, vector_map_->Get(opa)); // operand pass-through
1424 } else {
1425 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1426 }
1427 }
1428 return true;
1429 }
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001430 } else if (to == DataType::Type::kFloat32 && from == DataType::Type::kInt32) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001431 DCHECK_EQ(to, type);
1432 // Accept int to float conversion for
1433 // (1) supported int,
1434 // (2) vectorizable operand.
1435 if (TrySetVectorType(from, &restrictions) &&
1436 VectorizeUse(node, opa, generate_code, from, restrictions)) {
1437 if (generate_code) {
1438 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1439 }
1440 return true;
1441 }
1442 }
1443 return false;
1444 } else if (instruction->IsNeg() || instruction->IsNot() || instruction->IsBooleanNot()) {
1445 // Accept unary operator for vectorizable operand.
1446 HInstruction* opa = instruction->InputAt(0);
1447 if (VectorizeUse(node, opa, generate_code, type, restrictions)) {
1448 if (generate_code) {
1449 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1450 }
1451 return true;
1452 }
1453 } else if (instruction->IsAdd() || instruction->IsSub() ||
1454 instruction->IsMul() || instruction->IsDiv() ||
1455 instruction->IsAnd() || instruction->IsOr() || instruction->IsXor()) {
1456 // Deal with vector restrictions.
1457 if ((instruction->IsMul() && HasVectorRestrictions(restrictions, kNoMul)) ||
1458 (instruction->IsDiv() && HasVectorRestrictions(restrictions, kNoDiv))) {
1459 return false;
1460 }
1461 // Accept binary operator for vectorizable operands.
1462 HInstruction* opa = instruction->InputAt(0);
1463 HInstruction* opb = instruction->InputAt(1);
1464 if (VectorizeUse(node, opa, generate_code, type, restrictions) &&
1465 VectorizeUse(node, opb, generate_code, type, restrictions)) {
1466 if (generate_code) {
1467 GenerateVecOp(instruction, vector_map_->Get(opa), vector_map_->Get(opb), type);
1468 }
1469 return true;
1470 }
1471 } else if (instruction->IsShl() || instruction->IsShr() || instruction->IsUShr()) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001472 // Recognize halving add idiom.
Aart Bikf3e61ee2017-04-12 17:09:20 -07001473 if (VectorizeHalvingAddIdiom(node, instruction, generate_code, type, restrictions)) {
1474 return true;
1475 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001476 // Deal with vector restrictions.
Aart Bik304c8a52017-05-23 11:01:13 -07001477 HInstruction* opa = instruction->InputAt(0);
1478 HInstruction* opb = instruction->InputAt(1);
1479 HInstruction* r = opa;
1480 bool is_unsigned = false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001481 if ((HasVectorRestrictions(restrictions, kNoShift)) ||
1482 (instruction->IsShr() && HasVectorRestrictions(restrictions, kNoShr))) {
1483 return false; // unsupported instruction
Aart Bik304c8a52017-05-23 11:01:13 -07001484 } else if (HasVectorRestrictions(restrictions, kNoHiBits)) {
1485 // Shifts right need extra care to account for higher order bits.
1486 // TODO: less likely shr/unsigned and ushr/signed can by flipping signess.
1487 if (instruction->IsShr() &&
1488 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || is_unsigned)) {
1489 return false; // reject, unless all operands are sign-extension narrower
1490 } else if (instruction->IsUShr() &&
1491 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || !is_unsigned)) {
1492 return false; // reject, unless all operands are zero-extension narrower
1493 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001494 }
1495 // Accept shift operator for vectorizable/invariant operands.
1496 // TODO: accept symbolic, albeit loop invariant shift factors.
Aart Bik304c8a52017-05-23 11:01:13 -07001497 DCHECK(r != nullptr);
1498 if (generate_code && vector_mode_ != kVector) { // de-idiom
1499 r = opa;
1500 }
Aart Bik50e20d52017-05-05 14:07:29 -07001501 int64_t distance = 0;
Aart Bik304c8a52017-05-23 11:01:13 -07001502 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
Aart Bik50e20d52017-05-05 14:07:29 -07001503 IsInt64AndGet(opb, /*out*/ &distance)) {
Aart Bik65ffd8e2017-05-01 16:50:45 -07001504 // Restrict shift distance to packed data type width.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001505 int64_t max_distance = DataType::Size(type) * 8;
Aart Bik65ffd8e2017-05-01 16:50:45 -07001506 if (0 <= distance && distance < max_distance) {
1507 if (generate_code) {
Aart Bik304c8a52017-05-23 11:01:13 -07001508 GenerateVecOp(instruction, vector_map_->Get(r), opb, type);
Aart Bik65ffd8e2017-05-01 16:50:45 -07001509 }
1510 return true;
Aart Bikf8f5a162017-02-06 15:35:29 -08001511 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001512 }
Aart Bik3b2a5952018-03-05 13:55:28 -08001513 } else if (instruction->IsAbs()) {
1514 // Deal with vector restrictions.
1515 HInstruction* opa = instruction->InputAt(0);
1516 HInstruction* r = opa;
1517 bool is_unsigned = false;
1518 if (HasVectorRestrictions(restrictions, kNoAbs)) {
1519 return false;
1520 } else if (HasVectorRestrictions(restrictions, kNoHiBits) &&
1521 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || is_unsigned)) {
1522 return false; // reject, unless operand is sign-extension narrower
1523 }
1524 // Accept ABS(x) for vectorizable operand.
1525 DCHECK(r != nullptr);
1526 if (generate_code && vector_mode_ != kVector) { // de-idiom
1527 r = opa;
1528 }
1529 if (VectorizeUse(node, r, generate_code, type, restrictions)) {
1530 if (generate_code) {
1531 GenerateVecOp(instruction,
1532 vector_map_->Get(r),
1533 nullptr,
1534 HVecOperation::ToProperType(type, is_unsigned));
1535 }
1536 return true;
1537 }
Aart Bik1f8d51b2018-02-15 10:42:37 -08001538 } else if (instruction->IsMin() || instruction->IsMax()) {
Aart Bik29aa0822018-03-08 11:28:00 -08001539 // Recognize saturation arithmetic.
1540 if (VectorizeSaturationIdiom(node, instruction, generate_code, type, restrictions)) {
1541 return true;
1542 }
Aart Bik1f8d51b2018-02-15 10:42:37 -08001543 // Deal with vector restrictions.
1544 HInstruction* opa = instruction->InputAt(0);
1545 HInstruction* opb = instruction->InputAt(1);
1546 HInstruction* r = opa;
1547 HInstruction* s = opb;
1548 bool is_unsigned = false;
1549 if (HasVectorRestrictions(restrictions, kNoMinMax)) {
1550 return false;
1551 } else if (HasVectorRestrictions(restrictions, kNoHiBits) &&
1552 !IsNarrowerOperands(opa, opb, type, &r, &s, &is_unsigned)) {
1553 return false; // reject, unless all operands are same-extension narrower
1554 }
1555 // Accept MIN/MAX(x, y) for vectorizable operands.
Nicolas Geoffraya3e23262018-03-28 11:15:12 +00001556 DCHECK(r != nullptr && s != nullptr);
Aart Bik1f8d51b2018-02-15 10:42:37 -08001557 if (generate_code && vector_mode_ != kVector) { // de-idiom
1558 r = opa;
1559 s = opb;
1560 }
1561 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
1562 VectorizeUse(node, s, generate_code, type, restrictions)) {
1563 if (generate_code) {
1564 GenerateVecOp(
1565 instruction, vector_map_->Get(r), vector_map_->Get(s), type, is_unsigned);
Aart Bikc8e93c72017-05-10 10:49:22 -07001566 }
Aart Bik1f8d51b2018-02-15 10:42:37 -08001567 return true;
1568 }
Aart Bik281c6812016-08-26 11:31:48 -07001569 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08001570 return false;
Aart Bik281c6812016-08-26 11:31:48 -07001571}
1572
Aart Bik38a3f212017-10-20 17:02:21 -07001573uint32_t HLoopOptimization::GetVectorSizeInBytes() {
1574 switch (compiler_driver_->GetInstructionSet()) {
Vladimir Marko33bff252017-11-01 14:35:42 +00001575 case InstructionSet::kArm:
1576 case InstructionSet::kThumb2:
Aart Bik38a3f212017-10-20 17:02:21 -07001577 return 8; // 64-bit SIMD
1578 default:
1579 return 16; // 128-bit SIMD
1580 }
1581}
1582
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001583bool HLoopOptimization::TrySetVectorType(DataType::Type type, uint64_t* restrictions) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001584 const InstructionSetFeatures* features = compiler_driver_->GetInstructionSetFeatures();
1585 switch (compiler_driver_->GetInstructionSet()) {
Vladimir Marko33bff252017-11-01 14:35:42 +00001586 case InstructionSet::kArm:
1587 case InstructionSet::kThumb2:
Artem Serov8f7c4102017-06-21 11:21:37 +01001588 // Allow vectorization for all ARM devices, because Android assumes that
Aart Bikb29f6842017-07-28 15:58:41 -07001589 // ARM 32-bit always supports advanced SIMD (64-bit SIMD).
Artem Serov8f7c4102017-06-21 11:21:37 +01001590 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001591 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001592 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001593 case DataType::Type::kInt8:
Aart Bik0148de42017-09-05 09:25:01 -07001594 *restrictions |= kNoDiv | kNoReduction;
Artem Serov8f7c4102017-06-21 11:21:37 +01001595 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001596 case DataType::Type::kUint16:
1597 case DataType::Type::kInt16:
Aart Bik0148de42017-09-05 09:25:01 -07001598 *restrictions |= kNoDiv | kNoStringCharAt | kNoReduction;
Artem Serov8f7c4102017-06-21 11:21:37 +01001599 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001600 case DataType::Type::kInt32:
Artem Serov6e9b1372017-10-05 16:48:30 +01001601 *restrictions |= kNoDiv | kNoWideSAD;
Artem Serov8f7c4102017-06-21 11:21:37 +01001602 return TrySetVectorLength(2);
1603 default:
1604 break;
1605 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001606 return false;
Vladimir Marko33bff252017-11-01 14:35:42 +00001607 case InstructionSet::kArm64:
Aart Bikf8f5a162017-02-06 15:35:29 -08001608 // Allow vectorization for all ARM devices, because Android assumes that
Aart Bikb29f6842017-07-28 15:58:41 -07001609 // ARMv8 AArch64 always supports advanced SIMD (128-bit SIMD).
Aart Bikf8f5a162017-02-06 15:35:29 -08001610 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001611 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001612 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001613 case DataType::Type::kInt8:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001614 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +01001615 return TrySetVectorLength(16);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001616 case DataType::Type::kUint16:
1617 case DataType::Type::kInt16:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001618 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +01001619 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001620 case DataType::Type::kInt32:
Aart Bikf8f5a162017-02-06 15:35:29 -08001621 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +01001622 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001623 case DataType::Type::kInt64:
Aart Bikc8e93c72017-05-10 10:49:22 -07001624 *restrictions |= kNoDiv | kNoMul | kNoMinMax;
Aart Bikf8f5a162017-02-06 15:35:29 -08001625 return TrySetVectorLength(2);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001626 case DataType::Type::kFloat32:
Aart Bik0148de42017-09-05 09:25:01 -07001627 *restrictions |= kNoReduction;
Artem Serovd4bccf12017-04-03 18:47:32 +01001628 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001629 case DataType::Type::kFloat64:
Aart Bik0148de42017-09-05 09:25:01 -07001630 *restrictions |= kNoReduction;
Aart Bikf8f5a162017-02-06 15:35:29 -08001631 return TrySetVectorLength(2);
1632 default:
1633 return false;
1634 }
Vladimir Marko33bff252017-11-01 14:35:42 +00001635 case InstructionSet::kX86:
1636 case InstructionSet::kX86_64:
Aart Bikb29f6842017-07-28 15:58:41 -07001637 // Allow vectorization for SSE4.1-enabled X86 devices only (128-bit SIMD).
Aart Bikf8f5a162017-02-06 15:35:29 -08001638 if (features->AsX86InstructionSetFeatures()->HasSSE4_1()) {
1639 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001640 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001641 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001642 case DataType::Type::kInt8:
Aart Bik0148de42017-09-05 09:25:01 -07001643 *restrictions |=
Aart Bikdbbac8f2017-09-01 13:06:08 -07001644 kNoMul | kNoDiv | kNoShift | kNoAbs | kNoSignedHAdd | kNoUnroundedHAdd | kNoSAD;
Aart Bikf8f5a162017-02-06 15:35:29 -08001645 return TrySetVectorLength(16);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001646 case DataType::Type::kUint16:
1647 case DataType::Type::kInt16:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001648 *restrictions |= kNoDiv | kNoAbs | kNoSignedHAdd | kNoUnroundedHAdd | kNoSAD;
Aart Bikf8f5a162017-02-06 15:35:29 -08001649 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001650 case DataType::Type::kInt32:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001651 *restrictions |= kNoDiv | kNoSAD;
Aart Bikf8f5a162017-02-06 15:35:29 -08001652 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001653 case DataType::Type::kInt64:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001654 *restrictions |= kNoMul | kNoDiv | kNoShr | kNoAbs | kNoMinMax | kNoSAD;
Aart Bikf8f5a162017-02-06 15:35:29 -08001655 return TrySetVectorLength(2);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001656 case DataType::Type::kFloat32:
Aart Bik0148de42017-09-05 09:25:01 -07001657 *restrictions |= kNoMinMax | kNoReduction; // minmax: -0.0 vs +0.0
Aart Bikf8f5a162017-02-06 15:35:29 -08001658 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001659 case DataType::Type::kFloat64:
Aart Bik0148de42017-09-05 09:25:01 -07001660 *restrictions |= kNoMinMax | kNoReduction; // minmax: -0.0 vs +0.0
Aart Bikf8f5a162017-02-06 15:35:29 -08001661 return TrySetVectorLength(2);
1662 default:
1663 break;
1664 } // switch type
1665 }
1666 return false;
Vladimir Marko33bff252017-11-01 14:35:42 +00001667 case InstructionSet::kMips:
Lena Djokic51765b02017-06-22 13:49:59 +02001668 if (features->AsMipsInstructionSetFeatures()->HasMsa()) {
1669 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001670 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001671 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001672 case DataType::Type::kInt8:
Aart Bik29aa0822018-03-08 11:28:00 -08001673 *restrictions |= kNoDiv | kNoSaturation;
Lena Djokic51765b02017-06-22 13:49:59 +02001674 return TrySetVectorLength(16);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001675 case DataType::Type::kUint16:
1676 case DataType::Type::kInt16:
Aart Bik29aa0822018-03-08 11:28:00 -08001677 *restrictions |= kNoDiv | kNoSaturation | kNoStringCharAt;
Lena Djokic51765b02017-06-22 13:49:59 +02001678 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001679 case DataType::Type::kInt32:
Lena Djokic38e380b2017-10-30 16:17:10 +01001680 *restrictions |= kNoDiv;
Lena Djokic51765b02017-06-22 13:49:59 +02001681 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001682 case DataType::Type::kInt64:
Lena Djokic38e380b2017-10-30 16:17:10 +01001683 *restrictions |= kNoDiv;
Lena Djokic51765b02017-06-22 13:49:59 +02001684 return TrySetVectorLength(2);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001685 case DataType::Type::kFloat32:
Aart Bik0148de42017-09-05 09:25:01 -07001686 *restrictions |= kNoMinMax | kNoReduction; // min/max(x, NaN)
Lena Djokic51765b02017-06-22 13:49:59 +02001687 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001688 case DataType::Type::kFloat64:
Aart Bik0148de42017-09-05 09:25:01 -07001689 *restrictions |= kNoMinMax | kNoReduction; // min/max(x, NaN)
Lena Djokic51765b02017-06-22 13:49:59 +02001690 return TrySetVectorLength(2);
1691 default:
1692 break;
1693 } // switch type
1694 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001695 return false;
Vladimir Marko33bff252017-11-01 14:35:42 +00001696 case InstructionSet::kMips64:
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001697 if (features->AsMips64InstructionSetFeatures()->HasMsa()) {
1698 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001699 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001700 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001701 case DataType::Type::kInt8:
Aart Bik29aa0822018-03-08 11:28:00 -08001702 *restrictions |= kNoDiv | kNoSaturation;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001703 return TrySetVectorLength(16);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001704 case DataType::Type::kUint16:
1705 case DataType::Type::kInt16:
Aart Bik29aa0822018-03-08 11:28:00 -08001706 *restrictions |= kNoDiv | kNoSaturation | kNoStringCharAt;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001707 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001708 case DataType::Type::kInt32:
Lena Djokic38e380b2017-10-30 16:17:10 +01001709 *restrictions |= kNoDiv;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001710 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001711 case DataType::Type::kInt64:
Lena Djokic38e380b2017-10-30 16:17:10 +01001712 *restrictions |= kNoDiv;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001713 return TrySetVectorLength(2);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001714 case DataType::Type::kFloat32:
Aart Bik0148de42017-09-05 09:25:01 -07001715 *restrictions |= kNoMinMax | kNoReduction; // min/max(x, NaN)
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001716 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001717 case DataType::Type::kFloat64:
Aart Bik0148de42017-09-05 09:25:01 -07001718 *restrictions |= kNoMinMax | kNoReduction; // min/max(x, NaN)
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001719 return TrySetVectorLength(2);
1720 default:
1721 break;
1722 } // switch type
1723 }
1724 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001725 default:
1726 return false;
1727 } // switch instruction set
1728}
1729
1730bool HLoopOptimization::TrySetVectorLength(uint32_t length) {
1731 DCHECK(IsPowerOfTwo(length) && length >= 2u);
1732 // First time set?
1733 if (vector_length_ == 0) {
1734 vector_length_ = length;
1735 }
1736 // Different types are acceptable within a loop-body, as long as all the corresponding vector
1737 // lengths match exactly to obtain a uniform traversal through the vector iteration space
1738 // (idiomatic exceptions to this rule can be handled by further unrolling sub-expressions).
1739 return vector_length_ == length;
1740}
1741
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001742void HLoopOptimization::GenerateVecInv(HInstruction* org, DataType::Type type) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001743 if (vector_map_->find(org) == vector_map_->end()) {
1744 // In scalar code, just use a self pass-through for scalar invariants
1745 // (viz. expression remains itself).
1746 if (vector_mode_ == kSequential) {
1747 vector_map_->Put(org, org);
1748 return;
1749 }
1750 // In vector code, explicit scalar expansion is needed.
Aart Bik0148de42017-09-05 09:25:01 -07001751 HInstruction* vector = nullptr;
1752 auto it = vector_permanent_map_->find(org);
1753 if (it != vector_permanent_map_->end()) {
1754 vector = it->second; // reuse during unrolling
1755 } else {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001756 // Generates ReplicateScalar( (optional_type_conv) org ).
1757 HInstruction* input = org;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001758 DataType::Type input_type = input->GetType();
1759 if (type != input_type && (type == DataType::Type::kInt64 ||
1760 input_type == DataType::Type::kInt64)) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001761 input = Insert(vector_preheader_,
1762 new (global_allocator_) HTypeConversion(type, input, kNoDexPc));
1763 }
1764 vector = new (global_allocator_)
Aart Bik46b6dbc2017-10-03 11:37:37 -07001765 HVecReplicateScalar(global_allocator_, input, type, vector_length_, kNoDexPc);
Aart Bik0148de42017-09-05 09:25:01 -07001766 vector_permanent_map_->Put(org, Insert(vector_preheader_, vector));
1767 }
1768 vector_map_->Put(org, vector);
Aart Bikf8f5a162017-02-06 15:35:29 -08001769 }
1770}
1771
1772void HLoopOptimization::GenerateVecSub(HInstruction* org, HInstruction* offset) {
1773 if (vector_map_->find(org) == vector_map_->end()) {
Aart Bik14a68b42017-06-08 14:06:58 -07001774 HInstruction* subscript = vector_index_;
Aart Bik37dc4df2017-06-28 14:08:00 -07001775 int64_t value = 0;
1776 if (!IsInt64AndGet(offset, &value) || value != 0) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001777 subscript = new (global_allocator_) HAdd(DataType::Type::kInt32, subscript, offset);
Aart Bikf8f5a162017-02-06 15:35:29 -08001778 if (org->IsPhi()) {
1779 Insert(vector_body_, subscript); // lacks layout placeholder
1780 }
1781 }
1782 vector_map_->Put(org, subscript);
1783 }
1784}
1785
1786void HLoopOptimization::GenerateVecMem(HInstruction* org,
1787 HInstruction* opa,
1788 HInstruction* opb,
Aart Bik14a68b42017-06-08 14:06:58 -07001789 HInstruction* offset,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001790 DataType::Type type) {
Aart Bik46b6dbc2017-10-03 11:37:37 -07001791 uint32_t dex_pc = org->GetDexPc();
Aart Bikf8f5a162017-02-06 15:35:29 -08001792 HInstruction* vector = nullptr;
1793 if (vector_mode_ == kVector) {
1794 // Vector store or load.
Aart Bik38a3f212017-10-20 17:02:21 -07001795 bool is_string_char_at = false;
Aart Bik14a68b42017-06-08 14:06:58 -07001796 HInstruction* base = org->InputAt(0);
Aart Bikf8f5a162017-02-06 15:35:29 -08001797 if (opb != nullptr) {
1798 vector = new (global_allocator_) HVecStore(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001799 global_allocator_, base, opa, opb, type, org->GetSideEffects(), vector_length_, dex_pc);
Aart Bikf8f5a162017-02-06 15:35:29 -08001800 } else {
Aart Bik38a3f212017-10-20 17:02:21 -07001801 is_string_char_at = org->AsArrayGet()->IsStringCharAt();
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001802 vector = new (global_allocator_) HVecLoad(global_allocator_,
1803 base,
1804 opa,
1805 type,
1806 org->GetSideEffects(),
1807 vector_length_,
Aart Bik46b6dbc2017-10-03 11:37:37 -07001808 is_string_char_at,
1809 dex_pc);
Aart Bik14a68b42017-06-08 14:06:58 -07001810 }
Aart Bik38a3f212017-10-20 17:02:21 -07001811 // Known (forced/adjusted/original) alignment?
1812 if (vector_dynamic_peeling_candidate_ != nullptr) {
1813 if (vector_dynamic_peeling_candidate_->offset == offset && // TODO: diffs too?
1814 DataType::Size(vector_dynamic_peeling_candidate_->type) == DataType::Size(type) &&
1815 vector_dynamic_peeling_candidate_->is_string_char_at == is_string_char_at) {
1816 vector->AsVecMemoryOperation()->SetAlignment( // forced
1817 Alignment(GetVectorSizeInBytes(), 0));
1818 }
1819 } else {
1820 vector->AsVecMemoryOperation()->SetAlignment( // adjusted/original
1821 ComputeAlignment(offset, type, is_string_char_at, vector_static_peeling_factor_));
Aart Bikf8f5a162017-02-06 15:35:29 -08001822 }
1823 } else {
1824 // Scalar store or load.
1825 DCHECK(vector_mode_ == kSequential);
1826 if (opb != nullptr) {
Aart Bik4d1a9d42017-10-19 14:40:55 -07001827 DataType::Type component_type = org->AsArraySet()->GetComponentType();
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001828 vector = new (global_allocator_) HArraySet(
Aart Bik4d1a9d42017-10-19 14:40:55 -07001829 org->InputAt(0), opa, opb, component_type, org->GetSideEffects(), dex_pc);
Aart Bikf8f5a162017-02-06 15:35:29 -08001830 } else {
Aart Bikdb14fcf2017-04-25 15:53:58 -07001831 bool is_string_char_at = org->AsArrayGet()->IsStringCharAt();
1832 vector = new (global_allocator_) HArrayGet(
Aart Bik4d1a9d42017-10-19 14:40:55 -07001833 org->InputAt(0), opa, org->GetType(), org->GetSideEffects(), dex_pc, is_string_char_at);
Aart Bikf8f5a162017-02-06 15:35:29 -08001834 }
1835 }
1836 vector_map_->Put(org, vector);
1837}
1838
Aart Bik0148de42017-09-05 09:25:01 -07001839void HLoopOptimization::GenerateVecReductionPhi(HPhi* phi) {
1840 DCHECK(reductions_->find(phi) != reductions_->end());
1841 DCHECK(reductions_->Get(phi->InputAt(1)) == phi);
1842 HInstruction* vector = nullptr;
1843 if (vector_mode_ == kSequential) {
1844 HPhi* new_phi = new (global_allocator_) HPhi(
1845 global_allocator_, kNoRegNumber, 0, phi->GetType());
1846 vector_header_->AddPhi(new_phi);
1847 vector = new_phi;
1848 } else {
1849 // Link vector reduction back to prior unrolled update, or a first phi.
1850 auto it = vector_permanent_map_->find(phi);
1851 if (it != vector_permanent_map_->end()) {
1852 vector = it->second;
1853 } else {
1854 HPhi* new_phi = new (global_allocator_) HPhi(
1855 global_allocator_, kNoRegNumber, 0, HVecOperation::kSIMDType);
1856 vector_header_->AddPhi(new_phi);
1857 vector = new_phi;
1858 }
1859 }
1860 vector_map_->Put(phi, vector);
1861}
1862
1863void HLoopOptimization::GenerateVecReductionPhiInputs(HPhi* phi, HInstruction* reduction) {
1864 HInstruction* new_phi = vector_map_->Get(phi);
1865 HInstruction* new_init = reductions_->Get(phi);
1866 HInstruction* new_red = vector_map_->Get(reduction);
1867 // Link unrolled vector loop back to new phi.
1868 for (; !new_phi->IsPhi(); new_phi = vector_permanent_map_->Get(new_phi)) {
1869 DCHECK(new_phi->IsVecOperation());
1870 }
1871 // Prepare the new initialization.
1872 if (vector_mode_ == kVector) {
Goran Jakovljevic89b8df02017-10-13 08:33:17 +02001873 // Generate a [initial, 0, .., 0] vector for add or
1874 // a [initial, initial, .., initial] vector for min/max.
Aart Bikdbbac8f2017-09-01 13:06:08 -07001875 HVecOperation* red_vector = new_red->AsVecOperation();
Goran Jakovljevic89b8df02017-10-13 08:33:17 +02001876 HVecReduce::ReductionKind kind = GetReductionKind(red_vector);
Aart Bik38a3f212017-10-20 17:02:21 -07001877 uint32_t vector_length = red_vector->GetVectorLength();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001878 DataType::Type type = red_vector->GetPackedType();
Goran Jakovljevic89b8df02017-10-13 08:33:17 +02001879 if (kind == HVecReduce::ReductionKind::kSum) {
1880 new_init = Insert(vector_preheader_,
1881 new (global_allocator_) HVecSetScalars(global_allocator_,
1882 &new_init,
1883 type,
1884 vector_length,
1885 1,
1886 kNoDexPc));
1887 } else {
1888 new_init = Insert(vector_preheader_,
1889 new (global_allocator_) HVecReplicateScalar(global_allocator_,
1890 new_init,
1891 type,
1892 vector_length,
1893 kNoDexPc));
1894 }
Aart Bik0148de42017-09-05 09:25:01 -07001895 } else {
1896 new_init = ReduceAndExtractIfNeeded(new_init);
1897 }
1898 // Set the phi inputs.
1899 DCHECK(new_phi->IsPhi());
1900 new_phi->AsPhi()->AddInput(new_init);
1901 new_phi->AsPhi()->AddInput(new_red);
1902 // New feed value for next phi (safe mutation in iteration).
1903 reductions_->find(phi)->second = new_phi;
1904}
1905
1906HInstruction* HLoopOptimization::ReduceAndExtractIfNeeded(HInstruction* instruction) {
1907 if (instruction->IsPhi()) {
1908 HInstruction* input = instruction->InputAt(1);
Aart Bik2dd7b672017-12-07 11:11:22 -08001909 if (HVecOperation::ReturnsSIMDValue(input)) {
1910 DCHECK(!input->IsPhi());
Aart Bikdbbac8f2017-09-01 13:06:08 -07001911 HVecOperation* input_vector = input->AsVecOperation();
Aart Bik38a3f212017-10-20 17:02:21 -07001912 uint32_t vector_length = input_vector->GetVectorLength();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001913 DataType::Type type = input_vector->GetPackedType();
Aart Bikdbbac8f2017-09-01 13:06:08 -07001914 HVecReduce::ReductionKind kind = GetReductionKind(input_vector);
Aart Bik0148de42017-09-05 09:25:01 -07001915 HBasicBlock* exit = instruction->GetBlock()->GetSuccessors()[0];
1916 // Generate a vector reduction and scalar extract
1917 // x = REDUCE( [x_1, .., x_n] )
1918 // y = x_1
1919 // along the exit of the defining loop.
Aart Bik0148de42017-09-05 09:25:01 -07001920 HInstruction* reduce = new (global_allocator_) HVecReduce(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001921 global_allocator_, instruction, type, vector_length, kind, kNoDexPc);
Aart Bik0148de42017-09-05 09:25:01 -07001922 exit->InsertInstructionBefore(reduce, exit->GetFirstInstruction());
1923 instruction = new (global_allocator_) HVecExtractScalar(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001924 global_allocator_, reduce, type, vector_length, 0, kNoDexPc);
Aart Bik0148de42017-09-05 09:25:01 -07001925 exit->InsertInstructionAfter(instruction, reduce);
1926 }
1927 }
1928 return instruction;
1929}
1930
Aart Bikf8f5a162017-02-06 15:35:29 -08001931#define GENERATE_VEC(x, y) \
1932 if (vector_mode_ == kVector) { \
1933 vector = (x); \
1934 } else { \
1935 DCHECK(vector_mode_ == kSequential); \
1936 vector = (y); \
1937 } \
1938 break;
1939
1940void HLoopOptimization::GenerateVecOp(HInstruction* org,
1941 HInstruction* opa,
1942 HInstruction* opb,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001943 DataType::Type type,
Aart Bik304c8a52017-05-23 11:01:13 -07001944 bool is_unsigned) {
Aart Bik46b6dbc2017-10-03 11:37:37 -07001945 uint32_t dex_pc = org->GetDexPc();
Aart Bikf8f5a162017-02-06 15:35:29 -08001946 HInstruction* vector = nullptr;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001947 DataType::Type org_type = org->GetType();
Aart Bikf8f5a162017-02-06 15:35:29 -08001948 switch (org->GetKind()) {
1949 case HInstruction::kNeg:
1950 DCHECK(opb == nullptr);
1951 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001952 new (global_allocator_) HVecNeg(global_allocator_, opa, type, vector_length_, dex_pc),
1953 new (global_allocator_) HNeg(org_type, opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001954 case HInstruction::kNot:
1955 DCHECK(opb == nullptr);
1956 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001957 new (global_allocator_) HVecNot(global_allocator_, opa, type, vector_length_, dex_pc),
1958 new (global_allocator_) HNot(org_type, opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001959 case HInstruction::kBooleanNot:
1960 DCHECK(opb == nullptr);
1961 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001962 new (global_allocator_) HVecNot(global_allocator_, opa, type, vector_length_, dex_pc),
1963 new (global_allocator_) HBooleanNot(opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001964 case HInstruction::kTypeConversion:
1965 DCHECK(opb == nullptr);
1966 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001967 new (global_allocator_) HVecCnv(global_allocator_, opa, type, vector_length_, dex_pc),
1968 new (global_allocator_) HTypeConversion(org_type, opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001969 case HInstruction::kAdd:
1970 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001971 new (global_allocator_) HVecAdd(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1972 new (global_allocator_) HAdd(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001973 case HInstruction::kSub:
1974 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001975 new (global_allocator_) HVecSub(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1976 new (global_allocator_) HSub(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001977 case HInstruction::kMul:
1978 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001979 new (global_allocator_) HVecMul(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1980 new (global_allocator_) HMul(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001981 case HInstruction::kDiv:
1982 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001983 new (global_allocator_) HVecDiv(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1984 new (global_allocator_) HDiv(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001985 case HInstruction::kAnd:
1986 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001987 new (global_allocator_) HVecAnd(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1988 new (global_allocator_) HAnd(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001989 case HInstruction::kOr:
1990 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001991 new (global_allocator_) HVecOr(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1992 new (global_allocator_) HOr(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001993 case HInstruction::kXor:
1994 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001995 new (global_allocator_) HVecXor(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1996 new (global_allocator_) HXor(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001997 case HInstruction::kShl:
1998 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001999 new (global_allocator_) HVecShl(global_allocator_, opa, opb, type, vector_length_, dex_pc),
2000 new (global_allocator_) HShl(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08002001 case HInstruction::kShr:
2002 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07002003 new (global_allocator_) HVecShr(global_allocator_, opa, opb, type, vector_length_, dex_pc),
2004 new (global_allocator_) HShr(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08002005 case HInstruction::kUShr:
2006 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07002007 new (global_allocator_) HVecUShr(global_allocator_, opa, opb, type, vector_length_, dex_pc),
2008 new (global_allocator_) HUShr(org_type, opa, opb, dex_pc));
Aart Bik1f8d51b2018-02-15 10:42:37 -08002009 case HInstruction::kMin:
2010 GENERATE_VEC(
2011 new (global_allocator_) HVecMin(global_allocator_,
2012 opa,
2013 opb,
2014 HVecOperation::ToProperType(type, is_unsigned),
2015 vector_length_,
2016 dex_pc),
2017 new (global_allocator_) HMin(org_type, opa, opb, dex_pc));
2018 case HInstruction::kMax:
2019 GENERATE_VEC(
2020 new (global_allocator_) HVecMax(global_allocator_,
2021 opa,
2022 opb,
2023 HVecOperation::ToProperType(type, is_unsigned),
2024 vector_length_,
2025 dex_pc),
2026 new (global_allocator_) HMax(org_type, opa, opb, dex_pc));
Aart Bik3b2a5952018-03-05 13:55:28 -08002027 case HInstruction::kAbs:
2028 DCHECK(opb == nullptr);
2029 GENERATE_VEC(
2030 new (global_allocator_) HVecAbs(global_allocator_, opa, type, vector_length_, dex_pc),
2031 new (global_allocator_) HAbs(org_type, opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08002032 default:
2033 break;
2034 } // switch
2035 CHECK(vector != nullptr) << "Unsupported SIMD operator";
2036 vector_map_->Put(org, vector);
2037}
2038
2039#undef GENERATE_VEC
2040
2041//
Aart Bikf3e61ee2017-04-12 17:09:20 -07002042// Vectorization idioms.
2043//
2044
Aart Bik29aa0822018-03-08 11:28:00 -08002045// Method recognizes single and double clipping saturation arithmetic.
2046bool HLoopOptimization::VectorizeSaturationIdiom(LoopNode* node,
2047 HInstruction* instruction,
2048 bool generate_code,
2049 DataType::Type type,
2050 uint64_t restrictions) {
2051 // Deal with vector restrictions.
2052 if (HasVectorRestrictions(restrictions, kNoSaturation)) {
2053 return false;
2054 }
Aart Bik1a381022018-03-15 15:51:37 -07002055 // Restrict type (generalize if one day we generalize allowed MIN/MAX integral types).
2056 if (instruction->GetType() != DataType::Type::kInt32 &&
2057 instruction->GetType() != DataType::Type::kInt64) {
Aart Bik29aa0822018-03-08 11:28:00 -08002058 return false;
2059 }
Nicolas Geoffraya3e23262018-03-28 11:15:12 +00002060 // Clipped addition or subtraction on narrower operands? We will try both
2061 // formats since, e.g., x+c can be interpreted as x+c and x-(-c), depending
2062 // on what clipping values are used, to get most benefits.
Aart Bik1a381022018-03-15 15:51:37 -07002063 int64_t lo = std::numeric_limits<int64_t>::min();
2064 int64_t hi = std::numeric_limits<int64_t>::max();
2065 HInstruction* clippee = FindClippee(instruction, &lo, &hi);
Nicolas Geoffraya3e23262018-03-28 11:15:12 +00002066 HInstruction* a = nullptr;
2067 HInstruction* b = nullptr;
Aart Bik29aa0822018-03-08 11:28:00 -08002068 HInstruction* r = nullptr;
2069 HInstruction* s = nullptr;
2070 bool is_unsigned = false;
Nicolas Geoffraya3e23262018-03-28 11:15:12 +00002071 bool is_add = true;
2072 int64_t c = 0;
2073 // First try for saturated addition.
2074 if (IsAddConst2(graph_, clippee, /*out*/ &a, /*out*/ &b, /*out*/ &c) && c == 0 &&
2075 IsNarrowerOperands(a, b, type, &r, &s, &is_unsigned) &&
2076 IsSaturatedAdd(r, s, type, lo, hi, is_unsigned)) {
2077 is_add = true;
Aart Bik29aa0822018-03-08 11:28:00 -08002078 } else {
Nicolas Geoffraya3e23262018-03-28 11:15:12 +00002079 // Then try again for saturated subtraction.
2080 a = b = r = s = nullptr;
2081 if (IsSubConst2(graph_, clippee, /*out*/ &a, /*out*/ &b) &&
2082 IsNarrowerOperands(a, b, type, &r, &s, &is_unsigned) &&
2083 IsSaturatedSub(r, type, lo, hi, is_unsigned)) {
2084 is_add = false;
2085 } else {
2086 return false;
2087 }
Aart Bik29aa0822018-03-08 11:28:00 -08002088 }
2089 // Accept saturation idiom for vectorizable operands.
Nicolas Geoffraya3e23262018-03-28 11:15:12 +00002090 DCHECK(r != nullptr && s != nullptr);
Aart Bik29aa0822018-03-08 11:28:00 -08002091 if (generate_code && vector_mode_ != kVector) { // de-idiom
2092 r = instruction->InputAt(0);
2093 s = instruction->InputAt(1);
2094 restrictions &= ~(kNoHiBits | kNoMinMax); // allow narrow MIN/MAX in seq
2095 }
2096 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
2097 VectorizeUse(node, s, generate_code, type, restrictions)) {
2098 if (generate_code) {
2099 if (vector_mode_ == kVector) {
2100 DataType::Type vtype = HVecOperation::ToProperType(type, is_unsigned);
2101 HInstruction* op1 = vector_map_->Get(r);
2102 HInstruction* op2 = vector_map_->Get(s);
2103 vector_map_->Put(instruction, is_add
2104 ? reinterpret_cast<HInstruction*>(new (global_allocator_) HVecSaturationAdd(
2105 global_allocator_, op1, op2, vtype, vector_length_, kNoDexPc))
2106 : reinterpret_cast<HInstruction*>(new (global_allocator_) HVecSaturationSub(
2107 global_allocator_, op1, op2, vtype, vector_length_, kNoDexPc)));
2108 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorizedIdiom);
2109 } else {
2110 GenerateVecOp(instruction, vector_map_->Get(r), vector_map_->Get(s), type);
2111 }
2112 }
2113 return true;
2114 }
2115 return false;
2116}
2117
Aart Bikf3e61ee2017-04-12 17:09:20 -07002118// Method recognizes the following idioms:
Aart Bikdbbac8f2017-09-01 13:06:08 -07002119// rounding halving add (a + b + 1) >> 1 for unsigned/signed operands a, b
2120// truncated halving add (a + b) >> 1 for unsigned/signed operands a, b
Aart Bikf3e61ee2017-04-12 17:09:20 -07002121// Provided that the operands are promoted to a wider form to do the arithmetic and
2122// then cast back to narrower form, the idioms can be mapped into efficient SIMD
2123// implementation that operates directly in narrower form (plus one extra bit).
2124// TODO: current version recognizes implicit byte/short/char widening only;
2125// explicit widening from int to long could be added later.
2126bool HLoopOptimization::VectorizeHalvingAddIdiom(LoopNode* node,
2127 HInstruction* instruction,
2128 bool generate_code,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002129 DataType::Type type,
Aart Bikf3e61ee2017-04-12 17:09:20 -07002130 uint64_t restrictions) {
2131 // Test for top level arithmetic shift right x >> 1 or logical shift right x >>> 1
Aart Bik304c8a52017-05-23 11:01:13 -07002132 // (note whether the sign bit in wider precision is shifted in has no effect
Aart Bikf3e61ee2017-04-12 17:09:20 -07002133 // on the narrow precision computed by the idiom).
Aart Bikf3e61ee2017-04-12 17:09:20 -07002134 if ((instruction->IsShr() ||
2135 instruction->IsUShr()) &&
Aart Bik0148de42017-09-05 09:25:01 -07002136 IsInt64Value(instruction->InputAt(1), 1)) {
Aart Bik5f805002017-05-16 16:42:41 -07002137 // Test for (a + b + c) >> 1 for optional constant c.
2138 HInstruction* a = nullptr;
2139 HInstruction* b = nullptr;
2140 int64_t c = 0;
Nicolas Geoffraya3e23262018-03-28 11:15:12 +00002141 if (IsAddConst2(graph_, instruction->InputAt(0), /*out*/ &a, /*out*/ &b, /*out*/ &c)) {
Aart Bik5f805002017-05-16 16:42:41 -07002142 // Accept c == 1 (rounded) or c == 0 (not rounded).
2143 bool is_rounded = false;
2144 if (c == 1) {
2145 is_rounded = true;
2146 } else if (c != 0) {
2147 return false;
2148 }
2149 // Accept consistent zero or sign extension on operands a and b.
Aart Bikf3e61ee2017-04-12 17:09:20 -07002150 HInstruction* r = nullptr;
2151 HInstruction* s = nullptr;
2152 bool is_unsigned = false;
Aart Bik304c8a52017-05-23 11:01:13 -07002153 if (!IsNarrowerOperands(a, b, type, &r, &s, &is_unsigned)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -07002154 return false;
2155 }
2156 // Deal with vector restrictions.
2157 if ((!is_unsigned && HasVectorRestrictions(restrictions, kNoSignedHAdd)) ||
2158 (!is_rounded && HasVectorRestrictions(restrictions, kNoUnroundedHAdd))) {
2159 return false;
2160 }
2161 // Accept recognized halving add for vectorizable operands. Vectorized code uses the
2162 // shorthand idiomatic operation. Sequential code uses the original scalar expressions.
Nicolas Geoffraya3e23262018-03-28 11:15:12 +00002163 DCHECK(r != nullptr && s != nullptr);
Aart Bik304c8a52017-05-23 11:01:13 -07002164 if (generate_code && vector_mode_ != kVector) { // de-idiom
2165 r = instruction->InputAt(0);
2166 s = instruction->InputAt(1);
2167 }
Aart Bikf3e61ee2017-04-12 17:09:20 -07002168 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
2169 VectorizeUse(node, s, generate_code, type, restrictions)) {
2170 if (generate_code) {
2171 if (vector_mode_ == kVector) {
2172 vector_map_->Put(instruction, new (global_allocator_) HVecHalvingAdd(
2173 global_allocator_,
2174 vector_map_->Get(r),
2175 vector_map_->Get(s),
Aart Bik66c158e2018-01-31 12:55:04 -08002176 HVecOperation::ToProperType(type, is_unsigned),
Aart Bikf3e61ee2017-04-12 17:09:20 -07002177 vector_length_,
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01002178 is_rounded,
Aart Bik46b6dbc2017-10-03 11:37:37 -07002179 kNoDexPc));
Aart Bik21b85922017-09-06 13:29:16 -07002180 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorizedIdiom);
Aart Bikf3e61ee2017-04-12 17:09:20 -07002181 } else {
Aart Bik304c8a52017-05-23 11:01:13 -07002182 GenerateVecOp(instruction, vector_map_->Get(r), vector_map_->Get(s), type);
Aart Bikf3e61ee2017-04-12 17:09:20 -07002183 }
2184 }
2185 return true;
2186 }
2187 }
2188 }
2189 return false;
2190}
2191
Aart Bikdbbac8f2017-09-01 13:06:08 -07002192// Method recognizes the following idiom:
2193// q += ABS(a - b) for signed operands a, b
2194// Provided that the operands have the same type or are promoted to a wider form.
2195// Since this may involve a vector length change, the idiom is handled by going directly
2196// to a sad-accumulate node (rather than relying combining finer grained nodes later).
2197// TODO: unsigned SAD too?
2198bool HLoopOptimization::VectorizeSADIdiom(LoopNode* node,
2199 HInstruction* instruction,
2200 bool generate_code,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002201 DataType::Type reduction_type,
Aart Bikdbbac8f2017-09-01 13:06:08 -07002202 uint64_t restrictions) {
2203 // Filter integral "q += ABS(a - b);" reduction, where ABS and SUB
2204 // are done in the same precision (either int or long).
2205 if (!instruction->IsAdd() ||
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002206 (reduction_type != DataType::Type::kInt32 && reduction_type != DataType::Type::kInt64)) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07002207 return false;
2208 }
2209 HInstruction* q = instruction->InputAt(0);
2210 HInstruction* v = instruction->InputAt(1);
2211 HInstruction* a = nullptr;
2212 HInstruction* b = nullptr;
Nicolas Geoffraya3e23262018-03-28 11:15:12 +00002213 if (v->IsAbs() &&
2214 v->GetType() == reduction_type &&
2215 IsSubConst2(graph_, v->InputAt(0), /*out*/ &a, /*out*/ &b)) {
2216 DCHECK(a != nullptr && b != nullptr);
2217 } else {
Aart Bikdbbac8f2017-09-01 13:06:08 -07002218 return false;
2219 }
2220 // Accept same-type or consistent sign extension for narrower-type on operands a and b.
2221 // The same-type or narrower operands are called r (a or lower) and s (b or lower).
Aart Bikdf011c32017-09-28 12:53:04 -07002222 // We inspect the operands carefully to pick the most suited type.
Aart Bikdbbac8f2017-09-01 13:06:08 -07002223 HInstruction* r = a;
2224 HInstruction* s = b;
2225 bool is_unsigned = false;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002226 DataType::Type sub_type = a->GetType();
Aart Bikdf011c32017-09-28 12:53:04 -07002227 if (DataType::Size(b->GetType()) < DataType::Size(sub_type)) {
2228 sub_type = b->GetType();
2229 }
2230 if (a->IsTypeConversion() &&
2231 DataType::Size(a->InputAt(0)->GetType()) < DataType::Size(sub_type)) {
2232 sub_type = a->InputAt(0)->GetType();
2233 }
2234 if (b->IsTypeConversion() &&
2235 DataType::Size(b->InputAt(0)->GetType()) < DataType::Size(sub_type)) {
2236 sub_type = b->InputAt(0)->GetType();
Aart Bikdbbac8f2017-09-01 13:06:08 -07002237 }
2238 if (reduction_type != sub_type &&
2239 (!IsNarrowerOperands(a, b, sub_type, &r, &s, &is_unsigned) || is_unsigned)) {
2240 return false;
2241 }
2242 // Try same/narrower type and deal with vector restrictions.
Artem Serov6e9b1372017-10-05 16:48:30 +01002243 if (!TrySetVectorType(sub_type, &restrictions) ||
2244 HasVectorRestrictions(restrictions, kNoSAD) ||
2245 (reduction_type != sub_type && HasVectorRestrictions(restrictions, kNoWideSAD))) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07002246 return false;
2247 }
2248 // Accept SAD idiom for vectorizable operands. Vectorized code uses the shorthand
2249 // idiomatic operation. Sequential code uses the original scalar expressions.
Nicolas Geoffraya3e23262018-03-28 11:15:12 +00002250 DCHECK(r != nullptr && s != nullptr);
Aart Bikdbbac8f2017-09-01 13:06:08 -07002251 if (generate_code && vector_mode_ != kVector) { // de-idiom
2252 r = s = v->InputAt(0);
2253 }
2254 if (VectorizeUse(node, q, generate_code, sub_type, restrictions) &&
2255 VectorizeUse(node, r, generate_code, sub_type, restrictions) &&
2256 VectorizeUse(node, s, generate_code, sub_type, restrictions)) {
2257 if (generate_code) {
2258 if (vector_mode_ == kVector) {
2259 vector_map_->Put(instruction, new (global_allocator_) HVecSADAccumulate(
2260 global_allocator_,
2261 vector_map_->Get(q),
2262 vector_map_->Get(r),
2263 vector_map_->Get(s),
Aart Bik3b2a5952018-03-05 13:55:28 -08002264 HVecOperation::ToProperType(reduction_type, is_unsigned),
Aart Bik46b6dbc2017-10-03 11:37:37 -07002265 GetOtherVL(reduction_type, sub_type, vector_length_),
2266 kNoDexPc));
Aart Bikdbbac8f2017-09-01 13:06:08 -07002267 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorizedIdiom);
2268 } else {
2269 GenerateVecOp(v, vector_map_->Get(r), nullptr, reduction_type);
2270 GenerateVecOp(instruction, vector_map_->Get(q), vector_map_->Get(v), reduction_type);
2271 }
2272 }
2273 return true;
2274 }
2275 return false;
2276}
2277
Aart Bikf3e61ee2017-04-12 17:09:20 -07002278//
Aart Bik14a68b42017-06-08 14:06:58 -07002279// Vectorization heuristics.
2280//
2281
Aart Bik38a3f212017-10-20 17:02:21 -07002282Alignment HLoopOptimization::ComputeAlignment(HInstruction* offset,
2283 DataType::Type type,
2284 bool is_string_char_at,
2285 uint32_t peeling) {
2286 // Combine the alignment and hidden offset that is guaranteed by
2287 // the Android runtime with a known starting index adjusted as bytes.
2288 int64_t value = 0;
2289 if (IsInt64AndGet(offset, /*out*/ &value)) {
2290 uint32_t start_offset =
2291 HiddenOffset(type, is_string_char_at) + (value + peeling) * DataType::Size(type);
2292 return Alignment(BaseAlignment(), start_offset & (BaseAlignment() - 1u));
2293 }
2294 // Otherwise, the Android runtime guarantees at least natural alignment.
2295 return Alignment(DataType::Size(type), 0);
2296}
2297
2298void HLoopOptimization::SetAlignmentStrategy(uint32_t peeling_votes[],
2299 const ArrayReference* peeling_candidate) {
2300 // Current heuristic: pick the best static loop peeling factor, if any,
2301 // or otherwise use dynamic loop peeling on suggested peeling candidate.
2302 uint32_t max_vote = 0;
2303 for (int32_t i = 0; i < 16; i++) {
2304 if (peeling_votes[i] > max_vote) {
2305 max_vote = peeling_votes[i];
2306 vector_static_peeling_factor_ = i;
2307 }
2308 }
2309 if (max_vote == 0) {
2310 vector_dynamic_peeling_candidate_ = peeling_candidate;
2311 }
2312}
2313
2314uint32_t HLoopOptimization::MaxNumberPeeled() {
2315 if (vector_dynamic_peeling_candidate_ != nullptr) {
2316 return vector_length_ - 1u; // worst-case
2317 }
2318 return vector_static_peeling_factor_; // known exactly
2319}
2320
Aart Bik14a68b42017-06-08 14:06:58 -07002321bool HLoopOptimization::IsVectorizationProfitable(int64_t trip_count) {
Aart Bik38a3f212017-10-20 17:02:21 -07002322 // Current heuristic: non-empty body with sufficient number of iterations (if known).
Aart Bik14a68b42017-06-08 14:06:58 -07002323 // TODO: refine by looking at e.g. operation count, alignment, etc.
Aart Bik38a3f212017-10-20 17:02:21 -07002324 // TODO: trip count is really unsigned entity, provided the guarding test
2325 // is satisfied; deal with this more carefully later
2326 uint32_t max_peel = MaxNumberPeeled();
Aart Bik14a68b42017-06-08 14:06:58 -07002327 if (vector_length_ == 0) {
2328 return false; // nothing found
Aart Bik38a3f212017-10-20 17:02:21 -07002329 } else if (trip_count < 0) {
2330 return false; // guard against non-taken/large
2331 } else if ((0 < trip_count) && (trip_count < (vector_length_ + max_peel))) {
Aart Bik14a68b42017-06-08 14:06:58 -07002332 return false; // insufficient iterations
2333 }
2334 return true;
2335}
2336
Aart Bik14a68b42017-06-08 14:06:58 -07002337//
Aart Bikf8f5a162017-02-06 15:35:29 -08002338// Helpers.
2339//
2340
2341bool HLoopOptimization::TrySetPhiInduction(HPhi* phi, bool restrict_uses) {
Aart Bikb29f6842017-07-28 15:58:41 -07002342 // Start with empty phi induction.
2343 iset_->clear();
2344
Nicolas Geoffrayf57c1ae2017-06-28 17:40:18 +01002345 // Special case Phis that have equivalent in a debuggable setup. Our graph checker isn't
2346 // smart enough to follow strongly connected components (and it's probably not worth
2347 // it to make it so). See b/33775412.
2348 if (graph_->IsDebuggable() && phi->HasEquivalentPhi()) {
2349 return false;
2350 }
Aart Bikb29f6842017-07-28 15:58:41 -07002351
2352 // Lookup phi induction cycle.
Aart Bikcc42be02016-10-20 16:14:16 -07002353 ArenaSet<HInstruction*>* set = induction_range_.LookupCycle(phi);
2354 if (set != nullptr) {
2355 for (HInstruction* i : *set) {
Aart Bike3dedc52016-11-02 17:50:27 -07002356 // Check that, other than instructions that are no longer in the graph (removed earlier)
Aart Bikf8f5a162017-02-06 15:35:29 -08002357 // each instruction is removable and, when restrict uses are requested, other than for phi,
2358 // all uses are contained within the cycle.
Aart Bike3dedc52016-11-02 17:50:27 -07002359 if (!i->IsInBlock()) {
2360 continue;
2361 } else if (!i->IsRemovable()) {
2362 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08002363 } else if (i != phi && restrict_uses) {
Aart Bikb29f6842017-07-28 15:58:41 -07002364 // Deal with regular uses.
Aart Bikcc42be02016-10-20 16:14:16 -07002365 for (const HUseListNode<HInstruction*>& use : i->GetUses()) {
2366 if (set->find(use.GetUser()) == set->end()) {
2367 return false;
2368 }
2369 }
2370 }
Aart Bike3dedc52016-11-02 17:50:27 -07002371 iset_->insert(i); // copy
Aart Bikcc42be02016-10-20 16:14:16 -07002372 }
Aart Bikcc42be02016-10-20 16:14:16 -07002373 return true;
2374 }
2375 return false;
2376}
2377
Aart Bikb29f6842017-07-28 15:58:41 -07002378bool HLoopOptimization::TrySetPhiReduction(HPhi* phi) {
Aart Bikcc42be02016-10-20 16:14:16 -07002379 DCHECK(iset_->empty());
Aart Bikb29f6842017-07-28 15:58:41 -07002380 // Only unclassified phi cycles are candidates for reductions.
2381 if (induction_range_.IsClassified(phi)) {
2382 return false;
2383 }
2384 // Accept operations like x = x + .., provided that the phi and the reduction are
2385 // used exactly once inside the loop, and by each other.
2386 HInputsRef inputs = phi->GetInputs();
2387 if (inputs.size() == 2) {
2388 HInstruction* reduction = inputs[1];
2389 if (HasReductionFormat(reduction, phi)) {
2390 HLoopInformation* loop_info = phi->GetBlock()->GetLoopInformation();
Aart Bik38a3f212017-10-20 17:02:21 -07002391 uint32_t use_count = 0;
Aart Bikb29f6842017-07-28 15:58:41 -07002392 bool single_use_inside_loop =
2393 // Reduction update only used by phi.
2394 reduction->GetUses().HasExactlyOneElement() &&
2395 !reduction->HasEnvironmentUses() &&
2396 // Reduction update is only use of phi inside the loop.
2397 IsOnlyUsedAfterLoop(loop_info, phi, /*collect_loop_uses*/ true, &use_count) &&
2398 iset_->size() == 1;
2399 iset_->clear(); // leave the way you found it
2400 if (single_use_inside_loop) {
2401 // Link reduction back, and start recording feed value.
2402 reductions_->Put(reduction, phi);
2403 reductions_->Put(phi, phi->InputAt(0));
2404 return true;
2405 }
2406 }
2407 }
2408 return false;
2409}
2410
2411bool HLoopOptimization::TrySetSimpleLoopHeader(HBasicBlock* block, /*out*/ HPhi** main_phi) {
2412 // Start with empty phi induction and reductions.
2413 iset_->clear();
2414 reductions_->clear();
2415
2416 // Scan the phis to find the following (the induction structure has already
2417 // been optimized, so we don't need to worry about trivial cases):
2418 // (1) optional reductions in loop,
2419 // (2) the main induction, used in loop control.
2420 HPhi* phi = nullptr;
2421 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
2422 if (TrySetPhiReduction(it.Current()->AsPhi())) {
2423 continue;
2424 } else if (phi == nullptr) {
2425 // Found the first candidate for main induction.
2426 phi = it.Current()->AsPhi();
2427 } else {
2428 return false;
2429 }
2430 }
2431
2432 // Then test for a typical loopheader:
2433 // s: SuspendCheck
2434 // c: Condition(phi, bound)
2435 // i: If(c)
2436 if (phi != nullptr && TrySetPhiInduction(phi, /*restrict_uses*/ false)) {
Aart Bikcc42be02016-10-20 16:14:16 -07002437 HInstruction* s = block->GetFirstInstruction();
2438 if (s != nullptr && s->IsSuspendCheck()) {
2439 HInstruction* c = s->GetNext();
Aart Bikd86c0852017-04-14 12:00:15 -07002440 if (c != nullptr &&
2441 c->IsCondition() &&
2442 c->GetUses().HasExactlyOneElement() && // only used for termination
2443 !c->HasEnvironmentUses()) { // unlikely, but not impossible
Aart Bikcc42be02016-10-20 16:14:16 -07002444 HInstruction* i = c->GetNext();
2445 if (i != nullptr && i->IsIf() && i->InputAt(0) == c) {
2446 iset_->insert(c);
2447 iset_->insert(s);
Aart Bikb29f6842017-07-28 15:58:41 -07002448 *main_phi = phi;
Aart Bikcc42be02016-10-20 16:14:16 -07002449 return true;
2450 }
2451 }
2452 }
2453 }
2454 return false;
2455}
2456
2457bool HLoopOptimization::IsEmptyBody(HBasicBlock* block) {
Aart Bikf8f5a162017-02-06 15:35:29 -08002458 if (!block->GetPhis().IsEmpty()) {
2459 return false;
2460 }
2461 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
2462 HInstruction* instruction = it.Current();
2463 if (!instruction->IsGoto() && iset_->find(instruction) == iset_->end()) {
2464 return false;
Aart Bikcc42be02016-10-20 16:14:16 -07002465 }
Aart Bikf8f5a162017-02-06 15:35:29 -08002466 }
2467 return true;
2468}
2469
2470bool HLoopOptimization::IsUsedOutsideLoop(HLoopInformation* loop_info,
2471 HInstruction* instruction) {
Aart Bikb29f6842017-07-28 15:58:41 -07002472 // Deal with regular uses.
Aart Bikf8f5a162017-02-06 15:35:29 -08002473 for (const HUseListNode<HInstruction*>& use : instruction->GetUses()) {
2474 if (use.GetUser()->GetBlock()->GetLoopInformation() != loop_info) {
2475 return true;
2476 }
Aart Bikcc42be02016-10-20 16:14:16 -07002477 }
2478 return false;
2479}
2480
Aart Bik482095d2016-10-10 15:39:10 -07002481bool HLoopOptimization::IsOnlyUsedAfterLoop(HLoopInformation* loop_info,
Aart Bik8c4a8542016-10-06 11:36:57 -07002482 HInstruction* instruction,
Aart Bik6b69e0a2017-01-11 10:20:43 -08002483 bool collect_loop_uses,
Aart Bik38a3f212017-10-20 17:02:21 -07002484 /*out*/ uint32_t* use_count) {
Aart Bikb29f6842017-07-28 15:58:41 -07002485 // Deal with regular uses.
Aart Bik8c4a8542016-10-06 11:36:57 -07002486 for (const HUseListNode<HInstruction*>& use : instruction->GetUses()) {
2487 HInstruction* user = use.GetUser();
2488 if (iset_->find(user) == iset_->end()) { // not excluded?
2489 HLoopInformation* other_loop_info = user->GetBlock()->GetLoopInformation();
Aart Bik482095d2016-10-10 15:39:10 -07002490 if (other_loop_info != nullptr && other_loop_info->IsIn(*loop_info)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -08002491 // If collect_loop_uses is set, simply keep adding those uses to the set.
2492 // Otherwise, reject uses inside the loop that were not already in the set.
2493 if (collect_loop_uses) {
2494 iset_->insert(user);
2495 continue;
2496 }
Aart Bik8c4a8542016-10-06 11:36:57 -07002497 return false;
2498 }
2499 ++*use_count;
2500 }
2501 }
2502 return true;
2503}
2504
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002505bool HLoopOptimization::TryReplaceWithLastValue(HLoopInformation* loop_info,
2506 HInstruction* instruction,
2507 HBasicBlock* block) {
2508 // Try to replace outside uses with the last value.
Aart Bik807868e2016-11-03 17:51:43 -07002509 if (induction_range_.CanGenerateLastValue(instruction)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -08002510 HInstruction* replacement = induction_range_.GenerateLastValue(instruction, graph_, block);
Aart Bikb29f6842017-07-28 15:58:41 -07002511 // Deal with regular uses.
Aart Bik6b69e0a2017-01-11 10:20:43 -08002512 const HUseList<HInstruction*>& uses = instruction->GetUses();
2513 for (auto it = uses.begin(), end = uses.end(); it != end;) {
2514 HInstruction* user = it->GetUser();
2515 size_t index = it->GetIndex();
2516 ++it; // increment before replacing
2517 if (iset_->find(user) == iset_->end()) { // not excluded?
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002518 if (kIsDebugBuild) {
2519 // We have checked earlier in 'IsOnlyUsedAfterLoop' that the use is after the loop.
2520 HLoopInformation* other_loop_info = user->GetBlock()->GetLoopInformation();
2521 CHECK(other_loop_info == nullptr || !other_loop_info->IsIn(*loop_info));
2522 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08002523 user->ReplaceInput(replacement, index);
2524 induction_range_.Replace(user, instruction, replacement); // update induction
2525 }
2526 }
Aart Bikb29f6842017-07-28 15:58:41 -07002527 // Deal with environment uses.
Aart Bik6b69e0a2017-01-11 10:20:43 -08002528 const HUseList<HEnvironment*>& env_uses = instruction->GetEnvUses();
2529 for (auto it = env_uses.begin(), end = env_uses.end(); it != end;) {
2530 HEnvironment* user = it->GetUser();
2531 size_t index = it->GetIndex();
2532 ++it; // increment before replacing
2533 if (iset_->find(user->GetHolder()) == iset_->end()) { // not excluded?
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002534 // Only update environment uses after the loop.
Aart Bik14a68b42017-06-08 14:06:58 -07002535 HLoopInformation* other_loop_info = user->GetHolder()->GetBlock()->GetLoopInformation();
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002536 if (other_loop_info == nullptr || !other_loop_info->IsIn(*loop_info)) {
2537 user->RemoveAsUserOfInput(index);
2538 user->SetRawEnvAt(index, replacement);
2539 replacement->AddEnvUseAt(user, index);
2540 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08002541 }
2542 }
Aart Bik807868e2016-11-03 17:51:43 -07002543 return true;
Aart Bik8c4a8542016-10-06 11:36:57 -07002544 }
Aart Bik807868e2016-11-03 17:51:43 -07002545 return false;
Aart Bik8c4a8542016-10-06 11:36:57 -07002546}
2547
Aart Bikf8f5a162017-02-06 15:35:29 -08002548bool HLoopOptimization::TryAssignLastValue(HLoopInformation* loop_info,
2549 HInstruction* instruction,
2550 HBasicBlock* block,
2551 bool collect_loop_uses) {
2552 // Assigning the last value is always successful if there are no uses.
2553 // Otherwise, it succeeds in a no early-exit loop by generating the
2554 // proper last value assignment.
Aart Bik38a3f212017-10-20 17:02:21 -07002555 uint32_t use_count = 0;
Aart Bikf8f5a162017-02-06 15:35:29 -08002556 return IsOnlyUsedAfterLoop(loop_info, instruction, collect_loop_uses, &use_count) &&
2557 (use_count == 0 ||
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002558 (!IsEarlyExit(loop_info) && TryReplaceWithLastValue(loop_info, instruction, block)));
Aart Bikf8f5a162017-02-06 15:35:29 -08002559}
2560
Aart Bik6b69e0a2017-01-11 10:20:43 -08002561void HLoopOptimization::RemoveDeadInstructions(const HInstructionList& list) {
2562 for (HBackwardInstructionIterator i(list); !i.Done(); i.Advance()) {
2563 HInstruction* instruction = i.Current();
2564 if (instruction->IsDeadAndRemovable()) {
2565 simplified_ = true;
2566 instruction->GetBlock()->RemoveInstructionOrPhi(instruction);
2567 }
2568 }
2569}
2570
Aart Bik14a68b42017-06-08 14:06:58 -07002571bool HLoopOptimization::CanRemoveCycle() {
2572 for (HInstruction* i : *iset_) {
2573 // We can never remove instructions that have environment
2574 // uses when we compile 'debuggable'.
2575 if (i->HasEnvironmentUses() && graph_->IsDebuggable()) {
2576 return false;
2577 }
2578 // A deoptimization should never have an environment input removed.
2579 for (const HUseListNode<HEnvironment*>& use : i->GetEnvUses()) {
2580 if (use.GetUser()->GetHolder()->IsDeoptimize()) {
2581 return false;
2582 }
2583 }
2584 }
2585 return true;
2586}
2587
Aart Bik281c6812016-08-26 11:31:48 -07002588} // namespace art