blob: 71e24de141f0d3a249af7bf46f4b64fca4fad358 [file] [log] [blame]
Aart Bik281c6812016-08-26 11:31:48 -07001/*
2 * Copyright (C) 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "loop_optimization.h"
18
Aart Bikf8f5a162017-02-06 15:35:29 -080019#include "arch/arm/instruction_set_features_arm.h"
20#include "arch/arm64/instruction_set_features_arm64.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070021#include "arch/instruction_set.h"
Aart Bikf8f5a162017-02-06 15:35:29 -080022#include "arch/mips/instruction_set_features_mips.h"
23#include "arch/mips64/instruction_set_features_mips64.h"
24#include "arch/x86/instruction_set_features_x86.h"
25#include "arch/x86_64/instruction_set_features_x86_64.h"
Aart Bik92685a82017-03-06 11:13:43 -080026#include "driver/compiler_driver.h"
Aart Bik96202302016-10-04 17:33:56 -070027#include "linear_order.h"
Aart Bik38a3f212017-10-20 17:02:21 -070028#include "mirror/array-inl.h"
29#include "mirror/string.h"
Aart Bik281c6812016-08-26 11:31:48 -070030
31namespace art {
32
Aart Bikf8f5a162017-02-06 15:35:29 -080033// Enables vectorization (SIMDization) in the loop optimizer.
34static constexpr bool kEnableVectorization = true;
35
Artem Serov121f2032017-10-23 19:19:06 +010036// Enables scalar loop unrolling in the loop optimizer.
37static constexpr bool kEnableScalarUnrolling = false;
Aart Bik521b50f2017-09-09 10:44:45 -070038
Aart Bik38a3f212017-10-20 17:02:21 -070039//
40// Static helpers.
41//
42
43// Base alignment for arrays/strings guaranteed by the Android runtime.
44static uint32_t BaseAlignment() {
45 return kObjectAlignment;
46}
47
48// Hidden offset for arrays/strings guaranteed by the Android runtime.
49static uint32_t HiddenOffset(DataType::Type type, bool is_string_char_at) {
50 return is_string_char_at
51 ? mirror::String::ValueOffset().Uint32Value()
52 : mirror::Array::DataOffset(DataType::Size(type)).Uint32Value();
53}
54
Aart Bik9abf8942016-10-14 09:49:42 -070055// Remove the instruction from the graph. A bit more elaborate than the usual
56// instruction removal, since there may be a cycle in the use structure.
Aart Bik281c6812016-08-26 11:31:48 -070057static void RemoveFromCycle(HInstruction* instruction) {
Aart Bik281c6812016-08-26 11:31:48 -070058 instruction->RemoveAsUserOfAllInputs();
59 instruction->RemoveEnvironmentUsers();
60 instruction->GetBlock()->RemoveInstructionOrPhi(instruction, /*ensure_safety=*/ false);
Artem Serov21c7e6f2017-07-27 16:04:42 +010061 RemoveEnvironmentUses(instruction);
62 ResetEnvironmentInputRecords(instruction);
Aart Bik281c6812016-08-26 11:31:48 -070063}
64
Aart Bik807868e2016-11-03 17:51:43 -070065// Detect a goto block and sets succ to the single successor.
Aart Bike3dedc52016-11-02 17:50:27 -070066static bool IsGotoBlock(HBasicBlock* block, /*out*/ HBasicBlock** succ) {
67 if (block->GetPredecessors().size() == 1 &&
68 block->GetSuccessors().size() == 1 &&
69 block->IsSingleGoto()) {
70 *succ = block->GetSingleSuccessor();
71 return true;
72 }
73 return false;
74}
75
Aart Bik807868e2016-11-03 17:51:43 -070076// Detect an early exit loop.
77static bool IsEarlyExit(HLoopInformation* loop_info) {
78 HBlocksInLoopReversePostOrderIterator it_loop(*loop_info);
79 for (it_loop.Advance(); !it_loop.Done(); it_loop.Advance()) {
80 for (HBasicBlock* successor : it_loop.Current()->GetSuccessors()) {
81 if (!loop_info->Contains(*successor)) {
82 return true;
83 }
84 }
85 }
86 return false;
87}
88
Aart Bik68ca7022017-09-26 16:44:23 -070089// Forward declaration.
90static bool IsZeroExtensionAndGet(HInstruction* instruction,
91 DataType::Type type,
Aart Bikdf011c32017-09-28 12:53:04 -070092 /*out*/ HInstruction** operand);
Aart Bik68ca7022017-09-26 16:44:23 -070093
Aart Bikdf011c32017-09-28 12:53:04 -070094// Detect a sign extension in instruction from the given type.
Aart Bikdbbac8f2017-09-01 13:06:08 -070095// Returns the promoted operand on success.
Aart Bikf3e61ee2017-04-12 17:09:20 -070096static bool IsSignExtensionAndGet(HInstruction* instruction,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +010097 DataType::Type type,
Aart Bikdf011c32017-09-28 12:53:04 -070098 /*out*/ HInstruction** operand) {
Aart Bikf3e61ee2017-04-12 17:09:20 -070099 // Accept any already wider constant that would be handled properly by sign
100 // extension when represented in the *width* of the given narrower data type
Aart Bik4d1a9d42017-10-19 14:40:55 -0700101 // (the fact that Uint8/Uint16 normally zero extend does not matter here).
Aart Bikf3e61ee2017-04-12 17:09:20 -0700102 int64_t value = 0;
Aart Bik50e20d52017-05-05 14:07:29 -0700103 if (IsInt64AndGet(instruction, /*out*/ &value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700104 switch (type) {
Vladimir Markod5d2f2c2017-09-26 12:37:26 +0100105 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100106 case DataType::Type::kInt8:
Aart Bikdbbac8f2017-09-01 13:06:08 -0700107 if (IsInt<8>(value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700108 *operand = instruction;
109 return true;
110 }
111 return false;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100112 case DataType::Type::kUint16:
113 case DataType::Type::kInt16:
Aart Bikdbbac8f2017-09-01 13:06:08 -0700114 if (IsInt<16>(value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700115 *operand = instruction;
116 return true;
117 }
118 return false;
119 default:
120 return false;
121 }
122 }
Aart Bikdf011c32017-09-28 12:53:04 -0700123 // An implicit widening conversion of any signed expression sign-extends.
124 if (instruction->GetType() == type) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700125 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100126 case DataType::Type::kInt8:
127 case DataType::Type::kInt16:
Aart Bikf3e61ee2017-04-12 17:09:20 -0700128 *operand = instruction;
129 return true;
130 default:
131 return false;
132 }
133 }
Aart Bikdf011c32017-09-28 12:53:04 -0700134 // An explicit widening conversion of a signed expression sign-extends.
Aart Bik68ca7022017-09-26 16:44:23 -0700135 if (instruction->IsTypeConversion()) {
Aart Bikdf011c32017-09-28 12:53:04 -0700136 HInstruction* conv = instruction->InputAt(0);
137 DataType::Type from = conv->GetType();
Aart Bik68ca7022017-09-26 16:44:23 -0700138 switch (instruction->GetType()) {
Aart Bikdf011c32017-09-28 12:53:04 -0700139 case DataType::Type::kInt32:
Aart Bik68ca7022017-09-26 16:44:23 -0700140 case DataType::Type::kInt64:
Aart Bikdf011c32017-09-28 12:53:04 -0700141 if (type == from && (from == DataType::Type::kInt8 ||
142 from == DataType::Type::kInt16 ||
143 from == DataType::Type::kInt32)) {
144 *operand = conv;
145 return true;
146 }
147 return false;
Aart Bik68ca7022017-09-26 16:44:23 -0700148 case DataType::Type::kInt16:
149 return type == DataType::Type::kUint16 &&
150 from == DataType::Type::kUint16 &&
Aart Bikdf011c32017-09-28 12:53:04 -0700151 IsZeroExtensionAndGet(instruction->InputAt(0), type, /*out*/ operand);
Aart Bik68ca7022017-09-26 16:44:23 -0700152 default:
153 return false;
154 }
Aart Bikdbbac8f2017-09-01 13:06:08 -0700155 }
Aart Bikf3e61ee2017-04-12 17:09:20 -0700156 return false;
157}
158
Aart Bikdf011c32017-09-28 12:53:04 -0700159// Detect a zero extension in instruction from the given type.
Aart Bikdbbac8f2017-09-01 13:06:08 -0700160// Returns the promoted operand on success.
Aart Bikf3e61ee2017-04-12 17:09:20 -0700161static bool IsZeroExtensionAndGet(HInstruction* instruction,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100162 DataType::Type type,
Aart Bikdf011c32017-09-28 12:53:04 -0700163 /*out*/ HInstruction** operand) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700164 // Accept any already wider constant that would be handled properly by zero
165 // extension when represented in the *width* of the given narrower data type
Aart Bikdf011c32017-09-28 12:53:04 -0700166 // (the fact that Int8/Int16 normally sign extend does not matter here).
Aart Bikf3e61ee2017-04-12 17:09:20 -0700167 int64_t value = 0;
Aart Bik50e20d52017-05-05 14:07:29 -0700168 if (IsInt64AndGet(instruction, /*out*/ &value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700169 switch (type) {
Vladimir Markod5d2f2c2017-09-26 12:37:26 +0100170 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100171 case DataType::Type::kInt8:
Aart Bikdbbac8f2017-09-01 13:06:08 -0700172 if (IsUint<8>(value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700173 *operand = instruction;
174 return true;
175 }
176 return false;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100177 case DataType::Type::kUint16:
178 case DataType::Type::kInt16:
Aart Bikdbbac8f2017-09-01 13:06:08 -0700179 if (IsUint<16>(value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700180 *operand = instruction;
181 return true;
182 }
183 return false;
184 default:
185 return false;
186 }
187 }
Aart Bikdf011c32017-09-28 12:53:04 -0700188 // An implicit widening conversion of any unsigned expression zero-extends.
189 if (instruction->GetType() == type) {
Vladimir Markod5d2f2c2017-09-26 12:37:26 +0100190 switch (type) {
191 case DataType::Type::kUint8:
192 case DataType::Type::kUint16:
193 *operand = instruction;
194 return true;
195 default:
196 return false;
Aart Bikf3e61ee2017-04-12 17:09:20 -0700197 }
198 }
Aart Bikdf011c32017-09-28 12:53:04 -0700199 // An explicit widening conversion of an unsigned expression zero-extends.
Aart Bik68ca7022017-09-26 16:44:23 -0700200 if (instruction->IsTypeConversion()) {
Aart Bikdf011c32017-09-28 12:53:04 -0700201 HInstruction* conv = instruction->InputAt(0);
202 DataType::Type from = conv->GetType();
Aart Bik68ca7022017-09-26 16:44:23 -0700203 switch (instruction->GetType()) {
Aart Bikdf011c32017-09-28 12:53:04 -0700204 case DataType::Type::kInt32:
Aart Bik68ca7022017-09-26 16:44:23 -0700205 case DataType::Type::kInt64:
Aart Bikdf011c32017-09-28 12:53:04 -0700206 if (type == from && from == DataType::Type::kUint16) {
207 *operand = conv;
208 return true;
209 }
210 return false;
Aart Bik68ca7022017-09-26 16:44:23 -0700211 case DataType::Type::kUint16:
212 return type == DataType::Type::kInt16 &&
213 from == DataType::Type::kInt16 &&
Aart Bikdf011c32017-09-28 12:53:04 -0700214 IsSignExtensionAndGet(instruction->InputAt(0), type, /*out*/ operand);
Aart Bik68ca7022017-09-26 16:44:23 -0700215 default:
216 return false;
217 }
Aart Bikdbbac8f2017-09-01 13:06:08 -0700218 }
Aart Bikf3e61ee2017-04-12 17:09:20 -0700219 return false;
220}
221
Aart Bik304c8a52017-05-23 11:01:13 -0700222// Detect situations with same-extension narrower operands.
223// Returns true on success and sets is_unsigned accordingly.
224static bool IsNarrowerOperands(HInstruction* a,
225 HInstruction* b,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100226 DataType::Type type,
Aart Bik304c8a52017-05-23 11:01:13 -0700227 /*out*/ HInstruction** r,
228 /*out*/ HInstruction** s,
229 /*out*/ bool* is_unsigned) {
Nicolas Geoffraya3e23262018-03-28 11:15:12 +0000230 DCHECK(a != nullptr && b != nullptr);
Aart Bik4d1a9d42017-10-19 14:40:55 -0700231 // Look for a matching sign extension.
232 DataType::Type stype = HVecOperation::ToSignedType(type);
233 if (IsSignExtensionAndGet(a, stype, r) && IsSignExtensionAndGet(b, stype, s)) {
Aart Bik304c8a52017-05-23 11:01:13 -0700234 *is_unsigned = false;
235 return true;
Aart Bik4d1a9d42017-10-19 14:40:55 -0700236 }
237 // Look for a matching zero extension.
238 DataType::Type utype = HVecOperation::ToUnsignedType(type);
239 if (IsZeroExtensionAndGet(a, utype, r) && IsZeroExtensionAndGet(b, utype, s)) {
Aart Bik304c8a52017-05-23 11:01:13 -0700240 *is_unsigned = true;
241 return true;
242 }
243 return false;
244}
245
246// As above, single operand.
247static bool IsNarrowerOperand(HInstruction* a,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100248 DataType::Type type,
Aart Bik304c8a52017-05-23 11:01:13 -0700249 /*out*/ HInstruction** r,
250 /*out*/ bool* is_unsigned) {
Nicolas Geoffraya3e23262018-03-28 11:15:12 +0000251 DCHECK(a != nullptr);
Aart Bik4d1a9d42017-10-19 14:40:55 -0700252 // Look for a matching sign extension.
253 DataType::Type stype = HVecOperation::ToSignedType(type);
254 if (IsSignExtensionAndGet(a, stype, r)) {
Aart Bik304c8a52017-05-23 11:01:13 -0700255 *is_unsigned = false;
256 return true;
Aart Bik4d1a9d42017-10-19 14:40:55 -0700257 }
258 // Look for a matching zero extension.
259 DataType::Type utype = HVecOperation::ToUnsignedType(type);
260 if (IsZeroExtensionAndGet(a, utype, r)) {
Aart Bik304c8a52017-05-23 11:01:13 -0700261 *is_unsigned = true;
262 return true;
263 }
264 return false;
265}
266
Aart Bikdbbac8f2017-09-01 13:06:08 -0700267// Compute relative vector length based on type difference.
Aart Bik38a3f212017-10-20 17:02:21 -0700268static uint32_t GetOtherVL(DataType::Type other_type, DataType::Type vector_type, uint32_t vl) {
Vladimir Markod5d2f2c2017-09-26 12:37:26 +0100269 DCHECK(DataType::IsIntegralType(other_type));
270 DCHECK(DataType::IsIntegralType(vector_type));
271 DCHECK_GE(DataType::SizeShift(other_type), DataType::SizeShift(vector_type));
272 return vl >> (DataType::SizeShift(other_type) - DataType::SizeShift(vector_type));
Aart Bikdbbac8f2017-09-01 13:06:08 -0700273}
274
Nicolas Geoffraya3e23262018-03-28 11:15:12 +0000275// Detect up to two added operands a and b and an acccumulated constant c.
276static bool IsAddConst(HInstruction* instruction,
277 /*out*/ HInstruction** a,
278 /*out*/ HInstruction** b,
279 /*out*/ int64_t* c,
280 int32_t depth = 8) { // don't search too deep
Aart Bik5f805002017-05-16 16:42:41 -0700281 int64_t value = 0;
Nicolas Geoffraya3e23262018-03-28 11:15:12 +0000282 // Enter add/sub while still within reasonable depth.
283 if (depth > 0) {
284 if (instruction->IsAdd()) {
285 return IsAddConst(instruction->InputAt(0), a, b, c, depth - 1) &&
286 IsAddConst(instruction->InputAt(1), a, b, c, depth - 1);
287 } else if (instruction->IsSub() &&
288 IsInt64AndGet(instruction->InputAt(1), &value)) {
289 *c -= value;
290 return IsAddConst(instruction->InputAt(0), a, b, c, depth - 1);
291 }
292 }
293 // Otherwise, deal with leaf nodes.
Aart Bik5f805002017-05-16 16:42:41 -0700294 if (IsInt64AndGet(instruction, &value)) {
295 *c += value;
296 return true;
Aart Bik5f805002017-05-16 16:42:41 -0700297 } else if (*a == nullptr) {
298 *a = instruction;
299 return true;
300 } else if (*b == nullptr) {
301 *b = instruction;
302 return true;
303 }
Nicolas Geoffraya3e23262018-03-28 11:15:12 +0000304 return false; // too many operands
Aart Bik5f805002017-05-16 16:42:41 -0700305}
306
Nicolas Geoffraya3e23262018-03-28 11:15:12 +0000307// Detect a + b + c with optional constant c.
308static bool IsAddConst2(HGraph* graph,
309 HInstruction* instruction,
310 /*out*/ HInstruction** a,
311 /*out*/ HInstruction** b,
312 /*out*/ int64_t* c) {
313 if (IsAddConst(instruction, a, b, c) && *a != nullptr) {
314 if (*b == nullptr) {
315 // Constant is usually already present, unless accumulated.
316 *b = graph->GetConstant(instruction->GetType(), (*c));
317 *c = 0;
Aart Bik5f805002017-05-16 16:42:41 -0700318 }
Aart Bik5f805002017-05-16 16:42:41 -0700319 return true;
320 }
321 return false;
322}
323
Nicolas Geoffraya3e23262018-03-28 11:15:12 +0000324// Detect a direct a - b or a hidden a - (-c).
325static bool IsSubConst2(HGraph* graph,
326 HInstruction* instruction,
327 /*out*/ HInstruction** a,
328 /*out*/ HInstruction** b) {
329 int64_t c = 0;
330 if (instruction->IsSub()) {
331 *a = instruction->InputAt(0);
332 *b = instruction->InputAt(1);
333 return true;
334 } else if (IsAddConst(instruction, a, b, &c) && *a != nullptr && *b == nullptr) {
335 // Constant for the hidden subtraction.
336 *b = graph->GetConstant(instruction->GetType(), -c);
337 return true;
Aart Bikdf011c32017-09-28 12:53:04 -0700338 }
339 return false;
340}
341
Aart Bik29aa0822018-03-08 11:28:00 -0800342// Detect clipped [lo, hi] range for nested MIN-MAX operations on a clippee,
343// such as MIN(hi, MAX(lo, clippee)) for an arbitrary clippee expression.
344// Example: MIN(10, MIN(20, MAX(0, x))) yields [0, 10] with clippee x.
Aart Bik1a381022018-03-15 15:51:37 -0700345static HInstruction* FindClippee(HInstruction* instruction,
346 /*out*/ int64_t* lo,
347 /*out*/ int64_t* hi) {
348 // Iterate into MIN(.., c)-MAX(.., c) expressions and 'tighten' the range [lo, hi].
349 while (instruction->IsMin() || instruction->IsMax()) {
350 HBinaryOperation* min_max = instruction->AsBinaryOperation();
351 DCHECK(min_max->GetType() == DataType::Type::kInt32 ||
352 min_max->GetType() == DataType::Type::kInt64);
353 // Process the constant.
354 HConstant* right = min_max->GetConstantRight();
355 if (right == nullptr) {
356 break;
357 } else if (instruction->IsMin()) {
358 *hi = std::min(*hi, Int64FromConstant(right));
359 } else {
360 *lo = std::max(*lo, Int64FromConstant(right));
Aart Bik29aa0822018-03-08 11:28:00 -0800361 }
Aart Bik1a381022018-03-15 15:51:37 -0700362 instruction = min_max->GetLeastConstantLeft();
Aart Bik29aa0822018-03-08 11:28:00 -0800363 }
Aart Bik1a381022018-03-15 15:51:37 -0700364 // Iteration ends in any other expression (possibly MIN/MAX without constant).
365 // This leaf expression is the clippee with range [lo, hi].
366 return instruction;
Aart Bik29aa0822018-03-08 11:28:00 -0800367}
368
Aart Bik5a392762018-03-16 10:27:44 -0700369// Set value range for type (or fail).
370static bool CanSetRange(DataType::Type type,
371 /*out*/ int64_t* uhi,
372 /*out*/ int64_t* slo,
373 /*out*/ int64_t* shi) {
Aart Bik29aa0822018-03-08 11:28:00 -0800374 if (DataType::Size(type) == 1) {
Aart Bik5a392762018-03-16 10:27:44 -0700375 *uhi = std::numeric_limits<uint8_t>::max();
376 *slo = std::numeric_limits<int8_t>::min();
377 *shi = std::numeric_limits<int8_t>::max();
378 return true;
Aart Bik29aa0822018-03-08 11:28:00 -0800379 } else if (DataType::Size(type) == 2) {
Aart Bik5a392762018-03-16 10:27:44 -0700380 *uhi = std::numeric_limits<uint16_t>::max();
381 *slo = std::numeric_limits<int16_t>::min();
382 *shi = std::numeric_limits<int16_t>::max();
383 return true;
Aart Bik29aa0822018-03-08 11:28:00 -0800384 }
385 return false;
386}
387
Aart Bik5a392762018-03-16 10:27:44 -0700388// Accept various saturated addition forms.
Nicolas Geoffraya3e23262018-03-28 11:15:12 +0000389static bool IsSaturatedAdd(HInstruction* a,
390 HInstruction* b,
Aart Bik5a392762018-03-16 10:27:44 -0700391 DataType::Type type,
392 int64_t lo,
393 int64_t hi,
394 bool is_unsigned) {
395 int64_t ulo = 0, uhi = 0, slo = 0, shi = 0;
396 if (!CanSetRange(type, &uhi, &slo, &shi)) {
397 return false;
Aart Bik29aa0822018-03-08 11:28:00 -0800398 }
Aart Bik5a392762018-03-16 10:27:44 -0700399 // Tighten the range for signed single clipping on constant.
400 if (!is_unsigned) {
401 int64_t c = 0;
Nicolas Geoffraya3e23262018-03-28 11:15:12 +0000402 if (IsInt64AndGet(a, &c) || IsInt64AndGet(b, &c)) {
Aart Bik5a392762018-03-16 10:27:44 -0700403 // For c in proper range and narrower operand r:
404 // MIN(r + c, 127) c > 0
405 // or MAX(r + c, -128) c < 0 (and possibly redundant bound).
406 if (0 < c && c <= shi && hi == shi) {
407 if (lo <= (slo + c)) {
408 return true;
409 }
410 } else if (slo <= c && c < 0 && lo == slo) {
411 if (hi >= (shi + c)) {
412 return true;
413 }
414 }
415 }
416 }
417 // Detect for narrower operands r and s:
418 // MIN(r + s, 255) => SAT_ADD_unsigned
419 // MAX(MIN(r + s, 127), -128) => SAT_ADD_signed.
420 return is_unsigned ? (lo <= ulo && hi == uhi) : (lo == slo && hi == shi);
421}
422
423// Accept various saturated subtraction forms.
Nicolas Geoffraya3e23262018-03-28 11:15:12 +0000424static bool IsSaturatedSub(HInstruction* a,
Aart Bik5a392762018-03-16 10:27:44 -0700425 DataType::Type type,
426 int64_t lo,
427 int64_t hi,
428 bool is_unsigned) {
429 int64_t ulo = 0, uhi = 0, slo = 0, shi = 0;
430 if (!CanSetRange(type, &uhi, &slo, &shi)) {
431 return false;
432 }
433 // Tighten the range for signed single clipping on constant.
434 if (!is_unsigned) {
435 int64_t c = 0;
Nicolas Geoffraya3e23262018-03-28 11:15:12 +0000436 if (IsInt64AndGet(a, /*out*/ &c)) {
Aart Bik5a392762018-03-16 10:27:44 -0700437 // For c in proper range and narrower operand r:
438 // MIN(c - r, 127) c > 0
439 // or MAX(c - r, -128) c < 0 (and possibly redundant bound).
440 if (0 < c && c <= shi && hi == shi) {
441 if (lo <= (c - shi)) {
442 return true;
443 }
444 } else if (slo <= c && c < 0 && lo == slo) {
445 if (hi >= (c - slo)) {
446 return true;
447 }
448 }
449 }
450 }
451 // Detect for narrower operands r and s:
452 // MAX(r - s, 0) => SAT_SUB_unsigned
453 // MIN(MAX(r - s, -128), 127) => SAT_ADD_signed.
454 return is_unsigned ? (lo == ulo && hi >= uhi) : (lo == slo && hi == shi);
Aart Bik29aa0822018-03-08 11:28:00 -0800455}
456
Aart Bikb29f6842017-07-28 15:58:41 -0700457// Detect reductions of the following forms,
Aart Bikb29f6842017-07-28 15:58:41 -0700458// x = x_phi + ..
459// x = x_phi - ..
Aart Bikb29f6842017-07-28 15:58:41 -0700460// x = min(x_phi, ..)
Aart Bik1f8d51b2018-02-15 10:42:37 -0800461// x = max(x_phi, ..)
Aart Bikb29f6842017-07-28 15:58:41 -0700462static bool HasReductionFormat(HInstruction* reduction, HInstruction* phi) {
Aart Bik1f8d51b2018-02-15 10:42:37 -0800463 if (reduction->IsAdd() || reduction->IsMin() || reduction->IsMax()) {
Aart Bikdbbac8f2017-09-01 13:06:08 -0700464 return (reduction->InputAt(0) == phi && reduction->InputAt(1) != phi) ||
465 (reduction->InputAt(0) != phi && reduction->InputAt(1) == phi);
Aart Bikb29f6842017-07-28 15:58:41 -0700466 } else if (reduction->IsSub()) {
Aart Bikdbbac8f2017-09-01 13:06:08 -0700467 return (reduction->InputAt(0) == phi && reduction->InputAt(1) != phi);
Aart Bikb29f6842017-07-28 15:58:41 -0700468 }
469 return false;
470}
471
Aart Bikdbbac8f2017-09-01 13:06:08 -0700472// Translates vector operation to reduction kind.
473static HVecReduce::ReductionKind GetReductionKind(HVecOperation* reduction) {
474 if (reduction->IsVecAdd() || reduction->IsVecSub() || reduction->IsVecSADAccumulate()) {
Aart Bik0148de42017-09-05 09:25:01 -0700475 return HVecReduce::kSum;
476 } else if (reduction->IsVecMin()) {
477 return HVecReduce::kMin;
478 } else if (reduction->IsVecMax()) {
479 return HVecReduce::kMax;
480 }
Aart Bik38a3f212017-10-20 17:02:21 -0700481 LOG(FATAL) << "Unsupported SIMD reduction " << reduction->GetId();
Aart Bik0148de42017-09-05 09:25:01 -0700482 UNREACHABLE();
483}
484
Aart Bikf8f5a162017-02-06 15:35:29 -0800485// Test vector restrictions.
486static bool HasVectorRestrictions(uint64_t restrictions, uint64_t tested) {
487 return (restrictions & tested) != 0;
488}
489
Aart Bikf3e61ee2017-04-12 17:09:20 -0700490// Insert an instruction.
Aart Bikf8f5a162017-02-06 15:35:29 -0800491static HInstruction* Insert(HBasicBlock* block, HInstruction* instruction) {
492 DCHECK(block != nullptr);
493 DCHECK(instruction != nullptr);
494 block->InsertInstructionBefore(instruction, block->GetLastInstruction());
495 return instruction;
496}
497
Artem Serov21c7e6f2017-07-27 16:04:42 +0100498// Check that instructions from the induction sets are fully removed: have no uses
499// and no other instructions use them.
Vladimir Markoca6fff82017-10-03 14:49:14 +0100500static bool CheckInductionSetFullyRemoved(ScopedArenaSet<HInstruction*>* iset) {
Artem Serov21c7e6f2017-07-27 16:04:42 +0100501 for (HInstruction* instr : *iset) {
502 if (instr->GetBlock() != nullptr ||
503 !instr->GetUses().empty() ||
504 !instr->GetEnvUses().empty() ||
505 HasEnvironmentUsedByOthers(instr)) {
506 return false;
507 }
508 }
Artem Serov21c7e6f2017-07-27 16:04:42 +0100509 return true;
510}
511
Aart Bik281c6812016-08-26 11:31:48 -0700512//
Aart Bikb29f6842017-07-28 15:58:41 -0700513// Public methods.
Aart Bik281c6812016-08-26 11:31:48 -0700514//
515
516HLoopOptimization::HLoopOptimization(HGraph* graph,
Aart Bik92685a82017-03-06 11:13:43 -0800517 CompilerDriver* compiler_driver,
Aart Bikb92cc332017-09-06 15:53:17 -0700518 HInductionVarAnalysis* induction_analysis,
Aart Bik2ca10eb2017-11-15 15:17:53 -0800519 OptimizingCompilerStats* stats,
520 const char* name)
521 : HOptimization(graph, name, stats),
Aart Bik92685a82017-03-06 11:13:43 -0800522 compiler_driver_(compiler_driver),
Aart Bik281c6812016-08-26 11:31:48 -0700523 induction_range_(induction_analysis),
Aart Bik96202302016-10-04 17:33:56 -0700524 loop_allocator_(nullptr),
Vladimir Markoca6fff82017-10-03 14:49:14 +0100525 global_allocator_(graph_->GetAllocator()),
Aart Bik281c6812016-08-26 11:31:48 -0700526 top_loop_(nullptr),
Aart Bik8c4a8542016-10-06 11:36:57 -0700527 last_loop_(nullptr),
Aart Bik482095d2016-10-10 15:39:10 -0700528 iset_(nullptr),
Aart Bikb29f6842017-07-28 15:58:41 -0700529 reductions_(nullptr),
Aart Bikf8f5a162017-02-06 15:35:29 -0800530 simplified_(false),
531 vector_length_(0),
532 vector_refs_(nullptr),
Aart Bik38a3f212017-10-20 17:02:21 -0700533 vector_static_peeling_factor_(0),
534 vector_dynamic_peeling_candidate_(nullptr),
Aart Bik14a68b42017-06-08 14:06:58 -0700535 vector_runtime_test_a_(nullptr),
536 vector_runtime_test_b_(nullptr),
Aart Bik0148de42017-09-05 09:25:01 -0700537 vector_map_(nullptr),
Vladimir Markoca6fff82017-10-03 14:49:14 +0100538 vector_permanent_map_(nullptr),
539 vector_mode_(kSequential),
540 vector_preheader_(nullptr),
541 vector_header_(nullptr),
542 vector_body_(nullptr),
Artem Serov121f2032017-10-23 19:19:06 +0100543 vector_index_(nullptr),
544 arch_loop_helper_(ArchDefaultLoopHelper::Create(compiler_driver_ != nullptr
545 ? compiler_driver_->GetInstructionSet()
546 : InstructionSet::kNone,
547 global_allocator_)) {
Aart Bik281c6812016-08-26 11:31:48 -0700548}
549
550void HLoopOptimization::Run() {
Mingyao Yang01b47b02017-02-03 12:09:57 -0800551 // Skip if there is no loop or the graph has try-catch/irreducible loops.
Aart Bik281c6812016-08-26 11:31:48 -0700552 // TODO: make this less of a sledgehammer.
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800553 if (!graph_->HasLoops() || graph_->HasTryCatch() || graph_->HasIrreducibleLoops()) {
Aart Bik281c6812016-08-26 11:31:48 -0700554 return;
555 }
556
Vladimir Markoca6fff82017-10-03 14:49:14 +0100557 // Phase-local allocator.
558 ScopedArenaAllocator allocator(graph_->GetArenaStack());
Aart Bik96202302016-10-04 17:33:56 -0700559 loop_allocator_ = &allocator;
Nicolas Geoffrayebe16742016-10-05 09:55:42 +0100560
Aart Bik96202302016-10-04 17:33:56 -0700561 // Perform loop optimizations.
562 LocalRun();
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800563 if (top_loop_ == nullptr) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800564 graph_->SetHasLoops(false); // no more loops
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800565 }
566
Aart Bik96202302016-10-04 17:33:56 -0700567 // Detach.
568 loop_allocator_ = nullptr;
569 last_loop_ = top_loop_ = nullptr;
570}
571
Aart Bikb29f6842017-07-28 15:58:41 -0700572//
573// Loop setup and traversal.
574//
575
Aart Bik96202302016-10-04 17:33:56 -0700576void HLoopOptimization::LocalRun() {
577 // Build the linear order using the phase-local allocator. This step enables building
578 // a loop hierarchy that properly reflects the outer-inner and previous-next relation.
Vladimir Markoca6fff82017-10-03 14:49:14 +0100579 ScopedArenaVector<HBasicBlock*> linear_order(loop_allocator_->Adapter(kArenaAllocLinearOrder));
580 LinearizeGraph(graph_, &linear_order);
Aart Bik96202302016-10-04 17:33:56 -0700581
Aart Bik281c6812016-08-26 11:31:48 -0700582 // Build the loop hierarchy.
Aart Bik96202302016-10-04 17:33:56 -0700583 for (HBasicBlock* block : linear_order) {
Aart Bik281c6812016-08-26 11:31:48 -0700584 if (block->IsLoopHeader()) {
585 AddLoop(block->GetLoopInformation());
586 }
587 }
Aart Bik96202302016-10-04 17:33:56 -0700588
Aart Bik8c4a8542016-10-06 11:36:57 -0700589 // Traverse the loop hierarchy inner-to-outer and optimize. Traversal can use
Aart Bikf8f5a162017-02-06 15:35:29 -0800590 // temporary data structures using the phase-local allocator. All new HIR
591 // should use the global allocator.
Aart Bik8c4a8542016-10-06 11:36:57 -0700592 if (top_loop_ != nullptr) {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100593 ScopedArenaSet<HInstruction*> iset(loop_allocator_->Adapter(kArenaAllocLoopOptimization));
594 ScopedArenaSafeMap<HInstruction*, HInstruction*> reds(
Aart Bikb29f6842017-07-28 15:58:41 -0700595 std::less<HInstruction*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
Vladimir Markoca6fff82017-10-03 14:49:14 +0100596 ScopedArenaSet<ArrayReference> refs(loop_allocator_->Adapter(kArenaAllocLoopOptimization));
597 ScopedArenaSafeMap<HInstruction*, HInstruction*> map(
Aart Bikf8f5a162017-02-06 15:35:29 -0800598 std::less<HInstruction*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
Vladimir Markoca6fff82017-10-03 14:49:14 +0100599 ScopedArenaSafeMap<HInstruction*, HInstruction*> perm(
Aart Bik0148de42017-09-05 09:25:01 -0700600 std::less<HInstruction*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
Aart Bikf8f5a162017-02-06 15:35:29 -0800601 // Attach.
Aart Bik8c4a8542016-10-06 11:36:57 -0700602 iset_ = &iset;
Aart Bikb29f6842017-07-28 15:58:41 -0700603 reductions_ = &reds;
Aart Bikf8f5a162017-02-06 15:35:29 -0800604 vector_refs_ = &refs;
605 vector_map_ = &map;
Aart Bik0148de42017-09-05 09:25:01 -0700606 vector_permanent_map_ = &perm;
Aart Bikf8f5a162017-02-06 15:35:29 -0800607 // Traverse.
Aart Bik8c4a8542016-10-06 11:36:57 -0700608 TraverseLoopsInnerToOuter(top_loop_);
Aart Bikf8f5a162017-02-06 15:35:29 -0800609 // Detach.
610 iset_ = nullptr;
Aart Bikb29f6842017-07-28 15:58:41 -0700611 reductions_ = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800612 vector_refs_ = nullptr;
613 vector_map_ = nullptr;
Aart Bik0148de42017-09-05 09:25:01 -0700614 vector_permanent_map_ = nullptr;
Aart Bik8c4a8542016-10-06 11:36:57 -0700615 }
Aart Bik281c6812016-08-26 11:31:48 -0700616}
617
618void HLoopOptimization::AddLoop(HLoopInformation* loop_info) {
619 DCHECK(loop_info != nullptr);
Aart Bikf8f5a162017-02-06 15:35:29 -0800620 LoopNode* node = new (loop_allocator_) LoopNode(loop_info);
Aart Bik281c6812016-08-26 11:31:48 -0700621 if (last_loop_ == nullptr) {
622 // First loop.
623 DCHECK(top_loop_ == nullptr);
624 last_loop_ = top_loop_ = node;
625 } else if (loop_info->IsIn(*last_loop_->loop_info)) {
626 // Inner loop.
627 node->outer = last_loop_;
628 DCHECK(last_loop_->inner == nullptr);
629 last_loop_ = last_loop_->inner = node;
630 } else {
631 // Subsequent loop.
632 while (last_loop_->outer != nullptr && !loop_info->IsIn(*last_loop_->outer->loop_info)) {
633 last_loop_ = last_loop_->outer;
634 }
635 node->outer = last_loop_->outer;
636 node->previous = last_loop_;
637 DCHECK(last_loop_->next == nullptr);
638 last_loop_ = last_loop_->next = node;
639 }
640}
641
642void HLoopOptimization::RemoveLoop(LoopNode* node) {
643 DCHECK(node != nullptr);
Aart Bik8c4a8542016-10-06 11:36:57 -0700644 DCHECK(node->inner == nullptr);
645 if (node->previous != nullptr) {
646 // Within sequence.
647 node->previous->next = node->next;
648 if (node->next != nullptr) {
649 node->next->previous = node->previous;
650 }
651 } else {
652 // First of sequence.
653 if (node->outer != nullptr) {
654 node->outer->inner = node->next;
655 } else {
656 top_loop_ = node->next;
657 }
658 if (node->next != nullptr) {
659 node->next->outer = node->outer;
660 node->next->previous = nullptr;
661 }
662 }
Aart Bik281c6812016-08-26 11:31:48 -0700663}
664
Aart Bikb29f6842017-07-28 15:58:41 -0700665bool HLoopOptimization::TraverseLoopsInnerToOuter(LoopNode* node) {
666 bool changed = false;
Aart Bik281c6812016-08-26 11:31:48 -0700667 for ( ; node != nullptr; node = node->next) {
Aart Bikb29f6842017-07-28 15:58:41 -0700668 // Visit inner loops first. Recompute induction information for this
669 // loop if the induction of any inner loop has changed.
670 if (TraverseLoopsInnerToOuter(node->inner)) {
Aart Bik482095d2016-10-10 15:39:10 -0700671 induction_range_.ReVisit(node->loop_info);
672 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800673 // Repeat simplifications in the loop-body until no more changes occur.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800674 // Note that since each simplification consists of eliminating code (without
675 // introducing new code), this process is always finite.
Aart Bikdf7822e2016-12-06 10:05:30 -0800676 do {
677 simplified_ = false;
Aart Bikdf7822e2016-12-06 10:05:30 -0800678 SimplifyInduction(node);
Aart Bik6b69e0a2017-01-11 10:20:43 -0800679 SimplifyBlocks(node);
Aart Bikb29f6842017-07-28 15:58:41 -0700680 changed = simplified_ || changed;
Aart Bikdf7822e2016-12-06 10:05:30 -0800681 } while (simplified_);
Aart Bikf8f5a162017-02-06 15:35:29 -0800682 // Optimize inner loop.
Aart Bik9abf8942016-10-14 09:49:42 -0700683 if (node->inner == nullptr) {
Aart Bikb29f6842017-07-28 15:58:41 -0700684 changed = OptimizeInnerLoop(node) || changed;
Aart Bik9abf8942016-10-14 09:49:42 -0700685 }
Aart Bik281c6812016-08-26 11:31:48 -0700686 }
Aart Bikb29f6842017-07-28 15:58:41 -0700687 return changed;
Aart Bik281c6812016-08-26 11:31:48 -0700688}
689
Aart Bikf8f5a162017-02-06 15:35:29 -0800690//
691// Optimization.
692//
693
Aart Bik281c6812016-08-26 11:31:48 -0700694void HLoopOptimization::SimplifyInduction(LoopNode* node) {
695 HBasicBlock* header = node->loop_info->GetHeader();
696 HBasicBlock* preheader = node->loop_info->GetPreHeader();
Aart Bik8c4a8542016-10-06 11:36:57 -0700697 // Scan the phis in the header to find opportunities to simplify an induction
698 // cycle that is only used outside the loop. Replace these uses, if any, with
699 // the last value and remove the induction cycle.
700 // Examples: for (int i = 0; x != null; i++) { .... no i .... }
701 // for (int i = 0; i < 10; i++, k++) { .... no k .... } return k;
Aart Bik281c6812016-08-26 11:31:48 -0700702 for (HInstructionIterator it(header->GetPhis()); !it.Done(); it.Advance()) {
703 HPhi* phi = it.Current()->AsPhi();
Aart Bikf8f5a162017-02-06 15:35:29 -0800704 if (TrySetPhiInduction(phi, /*restrict_uses*/ true) &&
705 TryAssignLastValue(node->loop_info, phi, preheader, /*collect_loop_uses*/ false)) {
Aart Bik671e48a2017-08-09 13:16:56 -0700706 // Note that it's ok to have replaced uses after the loop with the last value, without
707 // being able to remove the cycle. Environment uses (which are the reason we may not be
708 // able to remove the cycle) within the loop will still hold the right value. We must
709 // have tried first, however, to replace outside uses.
710 if (CanRemoveCycle()) {
711 simplified_ = true;
712 for (HInstruction* i : *iset_) {
713 RemoveFromCycle(i);
714 }
715 DCHECK(CheckInductionSetFullyRemoved(iset_));
Aart Bik281c6812016-08-26 11:31:48 -0700716 }
Aart Bik482095d2016-10-10 15:39:10 -0700717 }
718 }
719}
720
721void HLoopOptimization::SimplifyBlocks(LoopNode* node) {
Aart Bikdf7822e2016-12-06 10:05:30 -0800722 // Iterate over all basic blocks in the loop-body.
723 for (HBlocksInLoopIterator it(*node->loop_info); !it.Done(); it.Advance()) {
724 HBasicBlock* block = it.Current();
725 // Remove dead instructions from the loop-body.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800726 RemoveDeadInstructions(block->GetPhis());
727 RemoveDeadInstructions(block->GetInstructions());
Aart Bikdf7822e2016-12-06 10:05:30 -0800728 // Remove trivial control flow blocks from the loop-body.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800729 if (block->GetPredecessors().size() == 1 &&
730 block->GetSuccessors().size() == 1 &&
731 block->GetSingleSuccessor()->GetPredecessors().size() == 1) {
Aart Bikdf7822e2016-12-06 10:05:30 -0800732 simplified_ = true;
Aart Bik6b69e0a2017-01-11 10:20:43 -0800733 block->MergeWith(block->GetSingleSuccessor());
Aart Bikdf7822e2016-12-06 10:05:30 -0800734 } else if (block->GetSuccessors().size() == 2) {
735 // Trivial if block can be bypassed to either branch.
736 HBasicBlock* succ0 = block->GetSuccessors()[0];
737 HBasicBlock* succ1 = block->GetSuccessors()[1];
738 HBasicBlock* meet0 = nullptr;
739 HBasicBlock* meet1 = nullptr;
740 if (succ0 != succ1 &&
741 IsGotoBlock(succ0, &meet0) &&
742 IsGotoBlock(succ1, &meet1) &&
743 meet0 == meet1 && // meets again
744 meet0 != block && // no self-loop
745 meet0->GetPhis().IsEmpty()) { // not used for merging
746 simplified_ = true;
747 succ0->DisconnectAndDelete();
748 if (block->Dominates(meet0)) {
749 block->RemoveDominatedBlock(meet0);
750 succ1->AddDominatedBlock(meet0);
751 meet0->SetDominator(succ1);
Aart Bike3dedc52016-11-02 17:50:27 -0700752 }
Aart Bik482095d2016-10-10 15:39:10 -0700753 }
Aart Bik281c6812016-08-26 11:31:48 -0700754 }
Aart Bikdf7822e2016-12-06 10:05:30 -0800755 }
Aart Bik281c6812016-08-26 11:31:48 -0700756}
757
Artem Serov121f2032017-10-23 19:19:06 +0100758bool HLoopOptimization::TryOptimizeInnerLoopFinite(LoopNode* node) {
Aart Bik281c6812016-08-26 11:31:48 -0700759 HBasicBlock* header = node->loop_info->GetHeader();
760 HBasicBlock* preheader = node->loop_info->GetPreHeader();
Aart Bik9abf8942016-10-14 09:49:42 -0700761 // Ensure loop header logic is finite.
Aart Bikf8f5a162017-02-06 15:35:29 -0800762 int64_t trip_count = 0;
763 if (!induction_range_.IsFinite(node->loop_info, &trip_count)) {
Aart Bikb29f6842017-07-28 15:58:41 -0700764 return false;
Aart Bik9abf8942016-10-14 09:49:42 -0700765 }
Aart Bik281c6812016-08-26 11:31:48 -0700766 // Ensure there is only a single loop-body (besides the header).
767 HBasicBlock* body = nullptr;
768 for (HBlocksInLoopIterator it(*node->loop_info); !it.Done(); it.Advance()) {
769 if (it.Current() != header) {
770 if (body != nullptr) {
Aart Bikb29f6842017-07-28 15:58:41 -0700771 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700772 }
773 body = it.Current();
774 }
775 }
Andreas Gampef45d61c2017-06-07 10:29:33 -0700776 CHECK(body != nullptr);
Aart Bik281c6812016-08-26 11:31:48 -0700777 // Ensure there is only a single exit point.
778 if (header->GetSuccessors().size() != 2) {
Aart Bikb29f6842017-07-28 15:58:41 -0700779 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700780 }
781 HBasicBlock* exit = (header->GetSuccessors()[0] == body)
782 ? header->GetSuccessors()[1]
783 : header->GetSuccessors()[0];
Aart Bik8c4a8542016-10-06 11:36:57 -0700784 // Ensure exit can only be reached by exiting loop.
Aart Bik281c6812016-08-26 11:31:48 -0700785 if (exit->GetPredecessors().size() != 1) {
Aart Bikb29f6842017-07-28 15:58:41 -0700786 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700787 }
Aart Bik6b69e0a2017-01-11 10:20:43 -0800788 // Detect either an empty loop (no side effects other than plain iteration) or
789 // a trivial loop (just iterating once). Replace subsequent index uses, if any,
790 // with the last value and remove the loop, possibly after unrolling its body.
Aart Bikb29f6842017-07-28 15:58:41 -0700791 HPhi* main_phi = nullptr;
792 if (TrySetSimpleLoopHeader(header, &main_phi)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -0800793 bool is_empty = IsEmptyBody(body);
Aart Bikb29f6842017-07-28 15:58:41 -0700794 if (reductions_->empty() && // TODO: possible with some effort
795 (is_empty || trip_count == 1) &&
796 TryAssignLastValue(node->loop_info, main_phi, preheader, /*collect_loop_uses*/ true)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -0800797 if (!is_empty) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800798 // Unroll the loop-body, which sees initial value of the index.
Aart Bikb29f6842017-07-28 15:58:41 -0700799 main_phi->ReplaceWith(main_phi->InputAt(0));
Aart Bik6b69e0a2017-01-11 10:20:43 -0800800 preheader->MergeInstructionsWith(body);
801 }
802 body->DisconnectAndDelete();
803 exit->RemovePredecessor(header);
804 header->RemoveSuccessor(exit);
805 header->RemoveDominatedBlock(exit);
806 header->DisconnectAndDelete();
807 preheader->AddSuccessor(exit);
Aart Bikf8f5a162017-02-06 15:35:29 -0800808 preheader->AddInstruction(new (global_allocator_) HGoto());
Aart Bik6b69e0a2017-01-11 10:20:43 -0800809 preheader->AddDominatedBlock(exit);
810 exit->SetDominator(preheader);
811 RemoveLoop(node); // update hierarchy
Aart Bikb29f6842017-07-28 15:58:41 -0700812 return true;
Aart Bikf8f5a162017-02-06 15:35:29 -0800813 }
814 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800815 // Vectorize loop, if possible and valid.
Aart Bikb29f6842017-07-28 15:58:41 -0700816 if (kEnableVectorization &&
817 TrySetSimpleLoopHeader(header, &main_phi) &&
Aart Bikb29f6842017-07-28 15:58:41 -0700818 ShouldVectorize(node, body, trip_count) &&
819 TryAssignLastValue(node->loop_info, main_phi, preheader, /*collect_loop_uses*/ true)) {
820 Vectorize(node, body, exit, trip_count);
821 graph_->SetHasSIMD(true); // flag SIMD usage
Aart Bik21b85922017-09-06 13:29:16 -0700822 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorized);
Aart Bikb29f6842017-07-28 15:58:41 -0700823 return true;
Aart Bikf8f5a162017-02-06 15:35:29 -0800824 }
Aart Bikb29f6842017-07-28 15:58:41 -0700825 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -0800826}
827
Artem Serov121f2032017-10-23 19:19:06 +0100828bool HLoopOptimization::OptimizeInnerLoop(LoopNode* node) {
829 return TryOptimizeInnerLoopFinite(node) ||
830 TryUnrollingForBranchPenaltyReduction(node);
831}
832
833void HLoopOptimization::PeelOrUnrollOnce(LoopNode* loop_node,
834 bool do_unrolling,
835 SuperblockCloner::HBasicBlockMap* bb_map,
836 SuperblockCloner::HInstructionMap* hir_map) {
837 // TODO: peel loop nests.
838 DCHECK(loop_node->inner == nullptr);
839
840 // Check that loop info is up-to-date.
841 HLoopInformation* loop_info = loop_node->loop_info;
842 HBasicBlock* header = loop_info->GetHeader();
843 DCHECK(loop_info == header->GetLoopInformation());
844
845 PeelUnrollHelper helper(loop_info, bb_map, hir_map);
846 DCHECK(helper.IsLoopClonable());
847 HBasicBlock* new_header = do_unrolling ? helper.DoUnrolling() : helper.DoPeeling();
848 DCHECK(header == new_header);
849 DCHECK(loop_info == new_header->GetLoopInformation());
850}
851
852//
853// Loop unrolling: generic part methods.
854//
855
856bool HLoopOptimization::TryUnrollingForBranchPenaltyReduction(LoopNode* loop_node) {
857 // Don't run peeling/unrolling if compiler_driver_ is nullptr (i.e., running under tests)
858 // as InstructionSet is needed.
859 if (!kEnableScalarUnrolling || compiler_driver_ == nullptr) {
860 return false;
861 }
862
863 HLoopInformation* loop_info = loop_node->loop_info;
864 int64_t trip_count = 0;
865 // Only unroll loops with a known tripcount.
866 if (!induction_range_.HasKnownTripCount(loop_info, &trip_count)) {
867 return false;
868 }
869
870 uint32_t unrolling_factor = arch_loop_helper_->GetScalarUnrollingFactor(loop_info, trip_count);
871 if (unrolling_factor == kNoUnrollingFactor) {
872 return false;
873 }
874
875 LoopAnalysisInfo loop_analysis_info(loop_info);
876 LoopAnalysis::CalculateLoopBasicProperties(loop_info, &loop_analysis_info);
877
878 // Check "IsLoopClonable" last as it can be time-consuming.
879 if (arch_loop_helper_->IsLoopTooBigForScalarUnrolling(&loop_analysis_info) ||
880 (loop_analysis_info.GetNumberOfExits() > 1) ||
881 loop_analysis_info.HasInstructionsPreventingScalarUnrolling() ||
882 !PeelUnrollHelper::IsLoopClonable(loop_info)) {
883 return false;
884 }
885
886 // TODO: support other unrolling factors.
887 DCHECK_EQ(unrolling_factor, 2u);
888
889 // Perform unrolling.
890 ArenaAllocator* arena = loop_info->GetHeader()->GetGraph()->GetAllocator();
891 SuperblockCloner::HBasicBlockMap bb_map(
892 std::less<HBasicBlock*>(), arena->Adapter(kArenaAllocSuperblockCloner));
893 SuperblockCloner::HInstructionMap hir_map(
894 std::less<HInstruction*>(), arena->Adapter(kArenaAllocSuperblockCloner));
895 PeelOrUnrollOnce(loop_node, /* unrolling */ true, &bb_map, &hir_map);
896
897 // Remove the redundant loop check after unrolling.
898 HIf* copy_hif = bb_map.Get(loop_info->GetHeader())->GetLastInstruction()->AsIf();
899 int32_t constant = loop_info->Contains(*copy_hif->IfTrueSuccessor()) ? 1 : 0;
900 copy_hif->ReplaceInput(graph_->GetIntConstant(constant), 0u);
901
902 return true;
903}
904
Aart Bikf8f5a162017-02-06 15:35:29 -0800905//
906// Loop vectorization. The implementation is based on the book by Aart J.C. Bik:
907// "The Software Vectorization Handbook. Applying Multimedia Extensions for Maximum Performance."
908// Intel Press, June, 2004 (http://www.aartbik.com/).
909//
910
Aart Bik14a68b42017-06-08 14:06:58 -0700911bool HLoopOptimization::ShouldVectorize(LoopNode* node, HBasicBlock* block, int64_t trip_count) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800912 // Reset vector bookkeeping.
913 vector_length_ = 0;
914 vector_refs_->clear();
Aart Bik38a3f212017-10-20 17:02:21 -0700915 vector_static_peeling_factor_ = 0;
916 vector_dynamic_peeling_candidate_ = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800917 vector_runtime_test_a_ =
Igor Murashkin2ffb7032017-11-08 13:35:21 -0800918 vector_runtime_test_b_ = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800919
920 // Phis in the loop-body prevent vectorization.
921 if (!block->GetPhis().IsEmpty()) {
922 return false;
923 }
924
925 // Scan the loop-body, starting a right-hand-side tree traversal at each left-hand-side
926 // occurrence, which allows passing down attributes down the use tree.
927 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
928 if (!VectorizeDef(node, it.Current(), /*generate_code*/ false)) {
929 return false; // failure to vectorize a left-hand-side
930 }
931 }
932
Aart Bik38a3f212017-10-20 17:02:21 -0700933 // Prepare alignment analysis:
934 // (1) find desired alignment (SIMD vector size in bytes).
935 // (2) initialize static loop peeling votes (peeling factor that will
936 // make one particular reference aligned), never to exceed (1).
937 // (3) variable to record how many references share same alignment.
938 // (4) variable to record suitable candidate for dynamic loop peeling.
939 uint32_t desired_alignment = GetVectorSizeInBytes();
940 DCHECK_LE(desired_alignment, 16u);
941 uint32_t peeling_votes[16] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
942 uint32_t max_num_same_alignment = 0;
943 const ArrayReference* peeling_candidate = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800944
945 // Data dependence analysis. Find each pair of references with same type, where
946 // at least one is a write. Each such pair denotes a possible data dependence.
947 // This analysis exploits the property that differently typed arrays cannot be
948 // aliased, as well as the property that references either point to the same
949 // array or to two completely disjoint arrays, i.e., no partial aliasing.
950 // Other than a few simply heuristics, no detailed subscript analysis is done.
Aart Bik38a3f212017-10-20 17:02:21 -0700951 // The scan over references also prepares finding a suitable alignment strategy.
Aart Bikf8f5a162017-02-06 15:35:29 -0800952 for (auto i = vector_refs_->begin(); i != vector_refs_->end(); ++i) {
Aart Bik38a3f212017-10-20 17:02:21 -0700953 uint32_t num_same_alignment = 0;
954 // Scan over all next references.
Aart Bikf8f5a162017-02-06 15:35:29 -0800955 for (auto j = i; ++j != vector_refs_->end(); ) {
956 if (i->type == j->type && (i->lhs || j->lhs)) {
957 // Found same-typed a[i+x] vs. b[i+y], where at least one is a write.
958 HInstruction* a = i->base;
959 HInstruction* b = j->base;
960 HInstruction* x = i->offset;
961 HInstruction* y = j->offset;
962 if (a == b) {
963 // Found a[i+x] vs. a[i+y]. Accept if x == y (loop-independent data dependence).
964 // Conservatively assume a loop-carried data dependence otherwise, and reject.
965 if (x != y) {
966 return false;
967 }
Aart Bik38a3f212017-10-20 17:02:21 -0700968 // Count the number of references that have the same alignment (since
969 // base and offset are the same) and where at least one is a write, so
970 // e.g. a[i] = a[i] + b[i] counts a[i] but not b[i]).
971 num_same_alignment++;
Aart Bikf8f5a162017-02-06 15:35:29 -0800972 } else {
973 // Found a[i+x] vs. b[i+y]. Accept if x == y (at worst loop-independent data dependence).
974 // Conservatively assume a potential loop-carried data dependence otherwise, avoided by
975 // generating an explicit a != b disambiguation runtime test on the two references.
976 if (x != y) {
Aart Bik37dc4df2017-06-28 14:08:00 -0700977 // To avoid excessive overhead, we only accept one a != b test.
978 if (vector_runtime_test_a_ == nullptr) {
979 // First test found.
980 vector_runtime_test_a_ = a;
981 vector_runtime_test_b_ = b;
982 } else if ((vector_runtime_test_a_ != a || vector_runtime_test_b_ != b) &&
983 (vector_runtime_test_a_ != b || vector_runtime_test_b_ != a)) {
984 return false; // second test would be needed
Aart Bikf8f5a162017-02-06 15:35:29 -0800985 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800986 }
987 }
988 }
989 }
Aart Bik38a3f212017-10-20 17:02:21 -0700990 // Update information for finding suitable alignment strategy:
991 // (1) update votes for static loop peeling,
992 // (2) update suitable candidate for dynamic loop peeling.
993 Alignment alignment = ComputeAlignment(i->offset, i->type, i->is_string_char_at);
994 if (alignment.Base() >= desired_alignment) {
995 // If the array/string object has a known, sufficient alignment, use the
996 // initial offset to compute the static loop peeling vote (this always
997 // works, since elements have natural alignment).
998 uint32_t offset = alignment.Offset() & (desired_alignment - 1u);
999 uint32_t vote = (offset == 0)
1000 ? 0
1001 : ((desired_alignment - offset) >> DataType::SizeShift(i->type));
1002 DCHECK_LT(vote, 16u);
1003 ++peeling_votes[vote];
1004 } else if (BaseAlignment() >= desired_alignment &&
1005 num_same_alignment > max_num_same_alignment) {
1006 // Otherwise, if the array/string object has a known, sufficient alignment
1007 // for just the base but with an unknown offset, record the candidate with
1008 // the most occurrences for dynamic loop peeling (again, the peeling always
1009 // works, since elements have natural alignment).
1010 max_num_same_alignment = num_same_alignment;
1011 peeling_candidate = &(*i);
1012 }
1013 } // for i
Aart Bikf8f5a162017-02-06 15:35:29 -08001014
Aart Bik38a3f212017-10-20 17:02:21 -07001015 // Find a suitable alignment strategy.
1016 SetAlignmentStrategy(peeling_votes, peeling_candidate);
1017
1018 // Does vectorization seem profitable?
1019 if (!IsVectorizationProfitable(trip_count)) {
1020 return false;
1021 }
Aart Bik14a68b42017-06-08 14:06:58 -07001022
Aart Bikf8f5a162017-02-06 15:35:29 -08001023 // Success!
1024 return true;
1025}
1026
1027void HLoopOptimization::Vectorize(LoopNode* node,
1028 HBasicBlock* block,
1029 HBasicBlock* exit,
1030 int64_t trip_count) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001031 HBasicBlock* header = node->loop_info->GetHeader();
1032 HBasicBlock* preheader = node->loop_info->GetPreHeader();
1033
Aart Bik14a68b42017-06-08 14:06:58 -07001034 // Pick a loop unrolling factor for the vector loop.
Artem Serov121f2032017-10-23 19:19:06 +01001035 uint32_t unroll = arch_loop_helper_->GetSIMDUnrollingFactor(
1036 block, trip_count, MaxNumberPeeled(), vector_length_);
Aart Bik14a68b42017-06-08 14:06:58 -07001037 uint32_t chunk = vector_length_ * unroll;
1038
Aart Bik38a3f212017-10-20 17:02:21 -07001039 DCHECK(trip_count == 0 || (trip_count >= MaxNumberPeeled() + chunk));
1040
Aart Bik14a68b42017-06-08 14:06:58 -07001041 // A cleanup loop is needed, at least, for any unknown trip count or
1042 // for a known trip count with remainder iterations after vectorization.
Aart Bik38a3f212017-10-20 17:02:21 -07001043 bool needs_cleanup = trip_count == 0 ||
1044 ((trip_count - vector_static_peeling_factor_) % chunk) != 0;
Aart Bikf8f5a162017-02-06 15:35:29 -08001045
1046 // Adjust vector bookkeeping.
Aart Bikb29f6842017-07-28 15:58:41 -07001047 HPhi* main_phi = nullptr;
1048 bool is_simple_loop_header = TrySetSimpleLoopHeader(header, &main_phi); // refills sets
Aart Bikf8f5a162017-02-06 15:35:29 -08001049 DCHECK(is_simple_loop_header);
Aart Bik14a68b42017-06-08 14:06:58 -07001050 vector_header_ = header;
1051 vector_body_ = block;
Aart Bikf8f5a162017-02-06 15:35:29 -08001052
Aart Bikdbbac8f2017-09-01 13:06:08 -07001053 // Loop induction type.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001054 DataType::Type induc_type = main_phi->GetType();
1055 DCHECK(induc_type == DataType::Type::kInt32 || induc_type == DataType::Type::kInt64)
1056 << induc_type;
Aart Bikdbbac8f2017-09-01 13:06:08 -07001057
Aart Bik38a3f212017-10-20 17:02:21 -07001058 // Generate the trip count for static or dynamic loop peeling, if needed:
1059 // ptc = <peeling factor>;
Aart Bik14a68b42017-06-08 14:06:58 -07001060 HInstruction* ptc = nullptr;
Aart Bik38a3f212017-10-20 17:02:21 -07001061 if (vector_static_peeling_factor_ != 0) {
1062 // Static loop peeling for SIMD alignment (using the most suitable
1063 // fixed peeling factor found during prior alignment analysis).
1064 DCHECK(vector_dynamic_peeling_candidate_ == nullptr);
1065 ptc = graph_->GetConstant(induc_type, vector_static_peeling_factor_);
1066 } else if (vector_dynamic_peeling_candidate_ != nullptr) {
1067 // Dynamic loop peeling for SIMD alignment (using the most suitable
1068 // candidate found during prior alignment analysis):
1069 // rem = offset % ALIGN; // adjusted as #elements
1070 // ptc = rem == 0 ? 0 : (ALIGN - rem);
1071 uint32_t shift = DataType::SizeShift(vector_dynamic_peeling_candidate_->type);
1072 uint32_t align = GetVectorSizeInBytes() >> shift;
1073 uint32_t hidden_offset = HiddenOffset(vector_dynamic_peeling_candidate_->type,
1074 vector_dynamic_peeling_candidate_->is_string_char_at);
1075 HInstruction* adjusted_offset = graph_->GetConstant(induc_type, hidden_offset >> shift);
1076 HInstruction* offset = Insert(preheader, new (global_allocator_) HAdd(
1077 induc_type, vector_dynamic_peeling_candidate_->offset, adjusted_offset));
1078 HInstruction* rem = Insert(preheader, new (global_allocator_) HAnd(
1079 induc_type, offset, graph_->GetConstant(induc_type, align - 1u)));
1080 HInstruction* sub = Insert(preheader, new (global_allocator_) HSub(
1081 induc_type, graph_->GetConstant(induc_type, align), rem));
1082 HInstruction* cond = Insert(preheader, new (global_allocator_) HEqual(
1083 rem, graph_->GetConstant(induc_type, 0)));
1084 ptc = Insert(preheader, new (global_allocator_) HSelect(
1085 cond, graph_->GetConstant(induc_type, 0), sub, kNoDexPc));
1086 needs_cleanup = true; // don't know the exact amount
Aart Bik14a68b42017-06-08 14:06:58 -07001087 }
1088
1089 // Generate loop control:
Aart Bikf8f5a162017-02-06 15:35:29 -08001090 // stc = <trip-count>;
Aart Bik38a3f212017-10-20 17:02:21 -07001091 // ptc = min(stc, ptc);
Aart Bik14a68b42017-06-08 14:06:58 -07001092 // vtc = stc - (stc - ptc) % chunk;
1093 // i = 0;
Aart Bikf8f5a162017-02-06 15:35:29 -08001094 HInstruction* stc = induction_range_.GenerateTripCount(node->loop_info, graph_, preheader);
1095 HInstruction* vtc = stc;
1096 if (needs_cleanup) {
Aart Bik14a68b42017-06-08 14:06:58 -07001097 DCHECK(IsPowerOfTwo(chunk));
1098 HInstruction* diff = stc;
1099 if (ptc != nullptr) {
Aart Bik38a3f212017-10-20 17:02:21 -07001100 if (trip_count == 0) {
1101 HInstruction* cond = Insert(preheader, new (global_allocator_) HAboveOrEqual(stc, ptc));
1102 ptc = Insert(preheader, new (global_allocator_) HSelect(cond, ptc, stc, kNoDexPc));
1103 }
Aart Bik14a68b42017-06-08 14:06:58 -07001104 diff = Insert(preheader, new (global_allocator_) HSub(induc_type, stc, ptc));
1105 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001106 HInstruction* rem = Insert(
1107 preheader, new (global_allocator_) HAnd(induc_type,
Aart Bik14a68b42017-06-08 14:06:58 -07001108 diff,
Aart Bikdbbac8f2017-09-01 13:06:08 -07001109 graph_->GetConstant(induc_type, chunk - 1)));
Aart Bikf8f5a162017-02-06 15:35:29 -08001110 vtc = Insert(preheader, new (global_allocator_) HSub(induc_type, stc, rem));
1111 }
Aart Bikdbbac8f2017-09-01 13:06:08 -07001112 vector_index_ = graph_->GetConstant(induc_type, 0);
Aart Bikf8f5a162017-02-06 15:35:29 -08001113
1114 // Generate runtime disambiguation test:
1115 // vtc = a != b ? vtc : 0;
1116 if (vector_runtime_test_a_ != nullptr) {
1117 HInstruction* rt = Insert(
1118 preheader,
1119 new (global_allocator_) HNotEqual(vector_runtime_test_a_, vector_runtime_test_b_));
1120 vtc = Insert(preheader,
Aart Bikdbbac8f2017-09-01 13:06:08 -07001121 new (global_allocator_)
1122 HSelect(rt, vtc, graph_->GetConstant(induc_type, 0), kNoDexPc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001123 needs_cleanup = true;
1124 }
1125
Aart Bik38a3f212017-10-20 17:02:21 -07001126 // Generate alignment peeling loop, if needed:
Aart Bik14a68b42017-06-08 14:06:58 -07001127 // for ( ; i < ptc; i += 1)
1128 // <loop-body>
Aart Bik38a3f212017-10-20 17:02:21 -07001129 //
1130 // NOTE: The alignment forced by the peeling loop is preserved even if data is
1131 // moved around during suspend checks, since all analysis was based on
1132 // nothing more than the Android runtime alignment conventions.
Aart Bik14a68b42017-06-08 14:06:58 -07001133 if (ptc != nullptr) {
1134 vector_mode_ = kSequential;
1135 GenerateNewLoop(node,
1136 block,
1137 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
1138 vector_index_,
1139 ptc,
Aart Bikdbbac8f2017-09-01 13:06:08 -07001140 graph_->GetConstant(induc_type, 1),
Aart Bik521b50f2017-09-09 10:44:45 -07001141 kNoUnrollingFactor);
Aart Bik14a68b42017-06-08 14:06:58 -07001142 }
1143
1144 // Generate vector loop, possibly further unrolled:
1145 // for ( ; i < vtc; i += chunk)
Aart Bikf8f5a162017-02-06 15:35:29 -08001146 // <vectorized-loop-body>
1147 vector_mode_ = kVector;
1148 GenerateNewLoop(node,
1149 block,
Aart Bik14a68b42017-06-08 14:06:58 -07001150 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
1151 vector_index_,
Aart Bikf8f5a162017-02-06 15:35:29 -08001152 vtc,
Aart Bikdbbac8f2017-09-01 13:06:08 -07001153 graph_->GetConstant(induc_type, vector_length_), // increment per unroll
Aart Bik14a68b42017-06-08 14:06:58 -07001154 unroll);
Aart Bikf8f5a162017-02-06 15:35:29 -08001155 HLoopInformation* vloop = vector_header_->GetLoopInformation();
1156
1157 // Generate cleanup loop, if needed:
1158 // for ( ; i < stc; i += 1)
1159 // <loop-body>
1160 if (needs_cleanup) {
1161 vector_mode_ = kSequential;
1162 GenerateNewLoop(node,
1163 block,
1164 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
Aart Bik14a68b42017-06-08 14:06:58 -07001165 vector_index_,
Aart Bikf8f5a162017-02-06 15:35:29 -08001166 stc,
Aart Bikdbbac8f2017-09-01 13:06:08 -07001167 graph_->GetConstant(induc_type, 1),
Aart Bik521b50f2017-09-09 10:44:45 -07001168 kNoUnrollingFactor);
Aart Bikf8f5a162017-02-06 15:35:29 -08001169 }
1170
Aart Bik0148de42017-09-05 09:25:01 -07001171 // Link reductions to their final uses.
1172 for (auto i = reductions_->begin(); i != reductions_->end(); ++i) {
1173 if (i->first->IsPhi()) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001174 HInstruction* phi = i->first;
1175 HInstruction* repl = ReduceAndExtractIfNeeded(i->second);
1176 // Deal with regular uses.
1177 for (const HUseListNode<HInstruction*>& use : phi->GetUses()) {
1178 induction_range_.Replace(use.GetUser(), phi, repl); // update induction use
1179 }
1180 phi->ReplaceWith(repl);
Aart Bik0148de42017-09-05 09:25:01 -07001181 }
1182 }
1183
Aart Bikf8f5a162017-02-06 15:35:29 -08001184 // Remove the original loop by disconnecting the body block
1185 // and removing all instructions from the header.
1186 block->DisconnectAndDelete();
1187 while (!header->GetFirstInstruction()->IsGoto()) {
1188 header->RemoveInstruction(header->GetFirstInstruction());
1189 }
Aart Bikb29f6842017-07-28 15:58:41 -07001190
Aart Bik14a68b42017-06-08 14:06:58 -07001191 // Update loop hierarchy: the old header now resides in the same outer loop
1192 // as the old preheader. Note that we don't bother putting sequential
1193 // loops back in the hierarchy at this point.
Aart Bikf8f5a162017-02-06 15:35:29 -08001194 header->SetLoopInformation(preheader->GetLoopInformation()); // outward
1195 node->loop_info = vloop;
1196}
1197
1198void HLoopOptimization::GenerateNewLoop(LoopNode* node,
1199 HBasicBlock* block,
1200 HBasicBlock* new_preheader,
1201 HInstruction* lo,
1202 HInstruction* hi,
Aart Bik14a68b42017-06-08 14:06:58 -07001203 HInstruction* step,
1204 uint32_t unroll) {
1205 DCHECK(unroll == 1 || vector_mode_ == kVector);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001206 DataType::Type induc_type = lo->GetType();
Aart Bikf8f5a162017-02-06 15:35:29 -08001207 // Prepare new loop.
Aart Bikf8f5a162017-02-06 15:35:29 -08001208 vector_preheader_ = new_preheader,
1209 vector_header_ = vector_preheader_->GetSingleSuccessor();
1210 vector_body_ = vector_header_->GetSuccessors()[1];
Aart Bik14a68b42017-06-08 14:06:58 -07001211 HPhi* phi = new (global_allocator_) HPhi(global_allocator_,
1212 kNoRegNumber,
1213 0,
1214 HPhi::ToPhiType(induc_type));
Aart Bikb07d1bc2017-04-05 10:03:15 -07001215 // Generate header and prepare body.
Aart Bikf8f5a162017-02-06 15:35:29 -08001216 // for (i = lo; i < hi; i += step)
1217 // <loop-body>
Aart Bik14a68b42017-06-08 14:06:58 -07001218 HInstruction* cond = new (global_allocator_) HAboveOrEqual(phi, hi);
1219 vector_header_->AddPhi(phi);
Aart Bikf8f5a162017-02-06 15:35:29 -08001220 vector_header_->AddInstruction(cond);
1221 vector_header_->AddInstruction(new (global_allocator_) HIf(cond));
Aart Bik14a68b42017-06-08 14:06:58 -07001222 vector_index_ = phi;
Aart Bik0148de42017-09-05 09:25:01 -07001223 vector_permanent_map_->clear(); // preserved over unrolling
Aart Bik14a68b42017-06-08 14:06:58 -07001224 for (uint32_t u = 0; u < unroll; u++) {
Aart Bik14a68b42017-06-08 14:06:58 -07001225 // Generate instruction map.
Aart Bik0148de42017-09-05 09:25:01 -07001226 vector_map_->clear();
Aart Bik14a68b42017-06-08 14:06:58 -07001227 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
1228 bool vectorized_def = VectorizeDef(node, it.Current(), /*generate_code*/ true);
1229 DCHECK(vectorized_def);
1230 }
1231 // Generate body from the instruction map, but in original program order.
1232 HEnvironment* env = vector_header_->GetFirstInstruction()->GetEnvironment();
1233 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
1234 auto i = vector_map_->find(it.Current());
1235 if (i != vector_map_->end() && !i->second->IsInBlock()) {
1236 Insert(vector_body_, i->second);
1237 // Deal with instructions that need an environment, such as the scalar intrinsics.
1238 if (i->second->NeedsEnvironment()) {
1239 i->second->CopyEnvironmentFromWithLoopPhiAdjustment(env, vector_header_);
1240 }
1241 }
1242 }
Aart Bik0148de42017-09-05 09:25:01 -07001243 // Generate the induction.
Aart Bik14a68b42017-06-08 14:06:58 -07001244 vector_index_ = new (global_allocator_) HAdd(induc_type, vector_index_, step);
1245 Insert(vector_body_, vector_index_);
Aart Bikf8f5a162017-02-06 15:35:29 -08001246 }
Aart Bik0148de42017-09-05 09:25:01 -07001247 // Finalize phi inputs for the reductions (if any).
1248 for (auto i = reductions_->begin(); i != reductions_->end(); ++i) {
1249 if (!i->first->IsPhi()) {
1250 DCHECK(i->second->IsPhi());
1251 GenerateVecReductionPhiInputs(i->second->AsPhi(), i->first);
1252 }
1253 }
Aart Bikb29f6842017-07-28 15:58:41 -07001254 // Finalize phi inputs for the loop index.
Aart Bik14a68b42017-06-08 14:06:58 -07001255 phi->AddInput(lo);
1256 phi->AddInput(vector_index_);
1257 vector_index_ = phi;
Aart Bikf8f5a162017-02-06 15:35:29 -08001258}
1259
Aart Bikf8f5a162017-02-06 15:35:29 -08001260bool HLoopOptimization::VectorizeDef(LoopNode* node,
1261 HInstruction* instruction,
1262 bool generate_code) {
1263 // Accept a left-hand-side array base[index] for
1264 // (1) supported vector type,
1265 // (2) loop-invariant base,
1266 // (3) unit stride index,
1267 // (4) vectorizable right-hand-side value.
1268 uint64_t restrictions = kNone;
1269 if (instruction->IsArraySet()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001270 DataType::Type type = instruction->AsArraySet()->GetComponentType();
Aart Bikf8f5a162017-02-06 15:35:29 -08001271 HInstruction* base = instruction->InputAt(0);
1272 HInstruction* index = instruction->InputAt(1);
1273 HInstruction* value = instruction->InputAt(2);
1274 HInstruction* offset = nullptr;
1275 if (TrySetVectorType(type, &restrictions) &&
1276 node->loop_info->IsDefinedOutOfTheLoop(base) &&
Aart Bik37dc4df2017-06-28 14:08:00 -07001277 induction_range_.IsUnitStride(instruction, index, graph_, &offset) &&
Aart Bikf8f5a162017-02-06 15:35:29 -08001278 VectorizeUse(node, value, generate_code, type, restrictions)) {
1279 if (generate_code) {
1280 GenerateVecSub(index, offset);
Aart Bik14a68b42017-06-08 14:06:58 -07001281 GenerateVecMem(instruction, vector_map_->Get(index), vector_map_->Get(value), offset, type);
Aart Bikf8f5a162017-02-06 15:35:29 -08001282 } else {
1283 vector_refs_->insert(ArrayReference(base, offset, type, /*lhs*/ true));
1284 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08001285 return true;
1286 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001287 return false;
1288 }
Aart Bik0148de42017-09-05 09:25:01 -07001289 // Accept a left-hand-side reduction for
1290 // (1) supported vector type,
1291 // (2) vectorizable right-hand-side value.
1292 auto redit = reductions_->find(instruction);
1293 if (redit != reductions_->end()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001294 DataType::Type type = instruction->GetType();
Aart Bikdbbac8f2017-09-01 13:06:08 -07001295 // Recognize SAD idiom or direct reduction.
1296 if (VectorizeSADIdiom(node, instruction, generate_code, type, restrictions) ||
1297 (TrySetVectorType(type, &restrictions) &&
1298 VectorizeUse(node, instruction, generate_code, type, restrictions))) {
Aart Bik0148de42017-09-05 09:25:01 -07001299 if (generate_code) {
1300 HInstruction* new_red = vector_map_->Get(instruction);
1301 vector_permanent_map_->Put(new_red, vector_map_->Get(redit->second));
1302 vector_permanent_map_->Overwrite(redit->second, new_red);
1303 }
1304 return true;
1305 }
1306 return false;
1307 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001308 // Branch back okay.
1309 if (instruction->IsGoto()) {
1310 return true;
1311 }
1312 // Otherwise accept only expressions with no effects outside the immediate loop-body.
1313 // Note that actual uses are inspected during right-hand-side tree traversal.
1314 return !IsUsedOutsideLoop(node->loop_info, instruction) && !instruction->DoesAnyWrite();
1315}
1316
Aart Bikf8f5a162017-02-06 15:35:29 -08001317bool HLoopOptimization::VectorizeUse(LoopNode* node,
1318 HInstruction* instruction,
1319 bool generate_code,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001320 DataType::Type type,
Aart Bikf8f5a162017-02-06 15:35:29 -08001321 uint64_t restrictions) {
1322 // Accept anything for which code has already been generated.
1323 if (generate_code) {
1324 if (vector_map_->find(instruction) != vector_map_->end()) {
1325 return true;
1326 }
1327 }
1328 // Continue the right-hand-side tree traversal, passing in proper
1329 // types and vector restrictions along the way. During code generation,
1330 // all new nodes are drawn from the global allocator.
1331 if (node->loop_info->IsDefinedOutOfTheLoop(instruction)) {
1332 // Accept invariant use, using scalar expansion.
1333 if (generate_code) {
1334 GenerateVecInv(instruction, type);
1335 }
1336 return true;
1337 } else if (instruction->IsArrayGet()) {
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001338 // Deal with vector restrictions.
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001339 bool is_string_char_at = instruction->AsArrayGet()->IsStringCharAt();
1340 if (is_string_char_at && HasVectorRestrictions(restrictions, kNoStringCharAt)) {
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001341 return false;
1342 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001343 // Accept a right-hand-side array base[index] for
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001344 // (1) matching vector type (exact match or signed/unsigned integral type of the same size),
Aart Bikf8f5a162017-02-06 15:35:29 -08001345 // (2) loop-invariant base,
1346 // (3) unit stride index,
1347 // (4) vectorizable right-hand-side value.
1348 HInstruction* base = instruction->InputAt(0);
1349 HInstruction* index = instruction->InputAt(1);
1350 HInstruction* offset = nullptr;
Aart Bik46b6dbc2017-10-03 11:37:37 -07001351 if (HVecOperation::ToSignedType(type) == HVecOperation::ToSignedType(instruction->GetType()) &&
Aart Bikf8f5a162017-02-06 15:35:29 -08001352 node->loop_info->IsDefinedOutOfTheLoop(base) &&
Aart Bik37dc4df2017-06-28 14:08:00 -07001353 induction_range_.IsUnitStride(instruction, index, graph_, &offset)) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001354 if (generate_code) {
1355 GenerateVecSub(index, offset);
Aart Bik14a68b42017-06-08 14:06:58 -07001356 GenerateVecMem(instruction, vector_map_->Get(index), nullptr, offset, type);
Aart Bikf8f5a162017-02-06 15:35:29 -08001357 } else {
Aart Bik38a3f212017-10-20 17:02:21 -07001358 vector_refs_->insert(ArrayReference(base, offset, type, /*lhs*/ false, is_string_char_at));
Aart Bikf8f5a162017-02-06 15:35:29 -08001359 }
1360 return true;
1361 }
Aart Bik0148de42017-09-05 09:25:01 -07001362 } else if (instruction->IsPhi()) {
1363 // Accept particular phi operations.
1364 if (reductions_->find(instruction) != reductions_->end()) {
1365 // Deal with vector restrictions.
1366 if (HasVectorRestrictions(restrictions, kNoReduction)) {
1367 return false;
1368 }
1369 // Accept a reduction.
1370 if (generate_code) {
1371 GenerateVecReductionPhi(instruction->AsPhi());
1372 }
1373 return true;
1374 }
1375 // TODO: accept right-hand-side induction?
1376 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001377 } else if (instruction->IsTypeConversion()) {
1378 // Accept particular type conversions.
1379 HTypeConversion* conversion = instruction->AsTypeConversion();
1380 HInstruction* opa = conversion->InputAt(0);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001381 DataType::Type from = conversion->GetInputType();
1382 DataType::Type to = conversion->GetResultType();
1383 if (DataType::IsIntegralType(from) && DataType::IsIntegralType(to)) {
Aart Bik38a3f212017-10-20 17:02:21 -07001384 uint32_t size_vec = DataType::Size(type);
1385 uint32_t size_from = DataType::Size(from);
1386 uint32_t size_to = DataType::Size(to);
Aart Bikdbbac8f2017-09-01 13:06:08 -07001387 // Accept an integral conversion
1388 // (1a) narrowing into vector type, "wider" operations cannot bring in higher order bits, or
1389 // (1b) widening from at least vector type, and
1390 // (2) vectorizable operand.
1391 if ((size_to < size_from &&
1392 size_to == size_vec &&
1393 VectorizeUse(node, opa, generate_code, type, restrictions | kNoHiBits)) ||
1394 (size_to >= size_from &&
1395 size_from >= size_vec &&
Aart Bik4d1a9d42017-10-19 14:40:55 -07001396 VectorizeUse(node, opa, generate_code, type, restrictions))) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001397 if (generate_code) {
1398 if (vector_mode_ == kVector) {
1399 vector_map_->Put(instruction, vector_map_->Get(opa)); // operand pass-through
1400 } else {
1401 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1402 }
1403 }
1404 return true;
1405 }
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001406 } else if (to == DataType::Type::kFloat32 && from == DataType::Type::kInt32) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001407 DCHECK_EQ(to, type);
1408 // Accept int to float conversion for
1409 // (1) supported int,
1410 // (2) vectorizable operand.
1411 if (TrySetVectorType(from, &restrictions) &&
1412 VectorizeUse(node, opa, generate_code, from, restrictions)) {
1413 if (generate_code) {
1414 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1415 }
1416 return true;
1417 }
1418 }
1419 return false;
1420 } else if (instruction->IsNeg() || instruction->IsNot() || instruction->IsBooleanNot()) {
1421 // Accept unary operator for vectorizable operand.
1422 HInstruction* opa = instruction->InputAt(0);
1423 if (VectorizeUse(node, opa, generate_code, type, restrictions)) {
1424 if (generate_code) {
1425 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1426 }
1427 return true;
1428 }
1429 } else if (instruction->IsAdd() || instruction->IsSub() ||
1430 instruction->IsMul() || instruction->IsDiv() ||
1431 instruction->IsAnd() || instruction->IsOr() || instruction->IsXor()) {
1432 // Deal with vector restrictions.
1433 if ((instruction->IsMul() && HasVectorRestrictions(restrictions, kNoMul)) ||
1434 (instruction->IsDiv() && HasVectorRestrictions(restrictions, kNoDiv))) {
1435 return false;
1436 }
1437 // Accept binary operator for vectorizable operands.
1438 HInstruction* opa = instruction->InputAt(0);
1439 HInstruction* opb = instruction->InputAt(1);
1440 if (VectorizeUse(node, opa, generate_code, type, restrictions) &&
1441 VectorizeUse(node, opb, generate_code, type, restrictions)) {
1442 if (generate_code) {
1443 GenerateVecOp(instruction, vector_map_->Get(opa), vector_map_->Get(opb), type);
1444 }
1445 return true;
1446 }
1447 } else if (instruction->IsShl() || instruction->IsShr() || instruction->IsUShr()) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001448 // Recognize halving add idiom.
Aart Bikf3e61ee2017-04-12 17:09:20 -07001449 if (VectorizeHalvingAddIdiom(node, instruction, generate_code, type, restrictions)) {
1450 return true;
1451 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001452 // Deal with vector restrictions.
Aart Bik304c8a52017-05-23 11:01:13 -07001453 HInstruction* opa = instruction->InputAt(0);
1454 HInstruction* opb = instruction->InputAt(1);
1455 HInstruction* r = opa;
1456 bool is_unsigned = false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001457 if ((HasVectorRestrictions(restrictions, kNoShift)) ||
1458 (instruction->IsShr() && HasVectorRestrictions(restrictions, kNoShr))) {
1459 return false; // unsupported instruction
Aart Bik304c8a52017-05-23 11:01:13 -07001460 } else if (HasVectorRestrictions(restrictions, kNoHiBits)) {
1461 // Shifts right need extra care to account for higher order bits.
1462 // TODO: less likely shr/unsigned and ushr/signed can by flipping signess.
1463 if (instruction->IsShr() &&
1464 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || is_unsigned)) {
1465 return false; // reject, unless all operands are sign-extension narrower
1466 } else if (instruction->IsUShr() &&
1467 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || !is_unsigned)) {
1468 return false; // reject, unless all operands are zero-extension narrower
1469 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001470 }
1471 // Accept shift operator for vectorizable/invariant operands.
1472 // TODO: accept symbolic, albeit loop invariant shift factors.
Aart Bik304c8a52017-05-23 11:01:13 -07001473 DCHECK(r != nullptr);
1474 if (generate_code && vector_mode_ != kVector) { // de-idiom
1475 r = opa;
1476 }
Aart Bik50e20d52017-05-05 14:07:29 -07001477 int64_t distance = 0;
Aart Bik304c8a52017-05-23 11:01:13 -07001478 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
Aart Bik50e20d52017-05-05 14:07:29 -07001479 IsInt64AndGet(opb, /*out*/ &distance)) {
Aart Bik65ffd8e2017-05-01 16:50:45 -07001480 // Restrict shift distance to packed data type width.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001481 int64_t max_distance = DataType::Size(type) * 8;
Aart Bik65ffd8e2017-05-01 16:50:45 -07001482 if (0 <= distance && distance < max_distance) {
1483 if (generate_code) {
Aart Bik304c8a52017-05-23 11:01:13 -07001484 GenerateVecOp(instruction, vector_map_->Get(r), opb, type);
Aart Bik65ffd8e2017-05-01 16:50:45 -07001485 }
1486 return true;
Aart Bikf8f5a162017-02-06 15:35:29 -08001487 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001488 }
Aart Bik3b2a5952018-03-05 13:55:28 -08001489 } else if (instruction->IsAbs()) {
1490 // Deal with vector restrictions.
1491 HInstruction* opa = instruction->InputAt(0);
1492 HInstruction* r = opa;
1493 bool is_unsigned = false;
1494 if (HasVectorRestrictions(restrictions, kNoAbs)) {
1495 return false;
1496 } else if (HasVectorRestrictions(restrictions, kNoHiBits) &&
1497 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || is_unsigned)) {
1498 return false; // reject, unless operand is sign-extension narrower
1499 }
1500 // Accept ABS(x) for vectorizable operand.
1501 DCHECK(r != nullptr);
1502 if (generate_code && vector_mode_ != kVector) { // de-idiom
1503 r = opa;
1504 }
1505 if (VectorizeUse(node, r, generate_code, type, restrictions)) {
1506 if (generate_code) {
1507 GenerateVecOp(instruction,
1508 vector_map_->Get(r),
1509 nullptr,
1510 HVecOperation::ToProperType(type, is_unsigned));
1511 }
1512 return true;
1513 }
Aart Bik1f8d51b2018-02-15 10:42:37 -08001514 } else if (instruction->IsMin() || instruction->IsMax()) {
Aart Bik29aa0822018-03-08 11:28:00 -08001515 // Recognize saturation arithmetic.
1516 if (VectorizeSaturationIdiom(node, instruction, generate_code, type, restrictions)) {
1517 return true;
1518 }
Aart Bik1f8d51b2018-02-15 10:42:37 -08001519 // Deal with vector restrictions.
1520 HInstruction* opa = instruction->InputAt(0);
1521 HInstruction* opb = instruction->InputAt(1);
1522 HInstruction* r = opa;
1523 HInstruction* s = opb;
1524 bool is_unsigned = false;
1525 if (HasVectorRestrictions(restrictions, kNoMinMax)) {
1526 return false;
1527 } else if (HasVectorRestrictions(restrictions, kNoHiBits) &&
1528 !IsNarrowerOperands(opa, opb, type, &r, &s, &is_unsigned)) {
1529 return false; // reject, unless all operands are same-extension narrower
1530 }
1531 // Accept MIN/MAX(x, y) for vectorizable operands.
Nicolas Geoffraya3e23262018-03-28 11:15:12 +00001532 DCHECK(r != nullptr && s != nullptr);
Aart Bik1f8d51b2018-02-15 10:42:37 -08001533 if (generate_code && vector_mode_ != kVector) { // de-idiom
1534 r = opa;
1535 s = opb;
1536 }
1537 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
1538 VectorizeUse(node, s, generate_code, type, restrictions)) {
1539 if (generate_code) {
1540 GenerateVecOp(
1541 instruction, vector_map_->Get(r), vector_map_->Get(s), type, is_unsigned);
Aart Bikc8e93c72017-05-10 10:49:22 -07001542 }
Aart Bik1f8d51b2018-02-15 10:42:37 -08001543 return true;
1544 }
Aart Bik281c6812016-08-26 11:31:48 -07001545 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08001546 return false;
Aart Bik281c6812016-08-26 11:31:48 -07001547}
1548
Aart Bik38a3f212017-10-20 17:02:21 -07001549uint32_t HLoopOptimization::GetVectorSizeInBytes() {
1550 switch (compiler_driver_->GetInstructionSet()) {
Vladimir Marko33bff252017-11-01 14:35:42 +00001551 case InstructionSet::kArm:
1552 case InstructionSet::kThumb2:
Aart Bik38a3f212017-10-20 17:02:21 -07001553 return 8; // 64-bit SIMD
1554 default:
1555 return 16; // 128-bit SIMD
1556 }
1557}
1558
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001559bool HLoopOptimization::TrySetVectorType(DataType::Type type, uint64_t* restrictions) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001560 const InstructionSetFeatures* features = compiler_driver_->GetInstructionSetFeatures();
1561 switch (compiler_driver_->GetInstructionSet()) {
Vladimir Marko33bff252017-11-01 14:35:42 +00001562 case InstructionSet::kArm:
1563 case InstructionSet::kThumb2:
Artem Serov8f7c4102017-06-21 11:21:37 +01001564 // Allow vectorization for all ARM devices, because Android assumes that
Aart Bikb29f6842017-07-28 15:58:41 -07001565 // ARM 32-bit always supports advanced SIMD (64-bit SIMD).
Artem Serov8f7c4102017-06-21 11:21:37 +01001566 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001567 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001568 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001569 case DataType::Type::kInt8:
Aart Bik0148de42017-09-05 09:25:01 -07001570 *restrictions |= kNoDiv | kNoReduction;
Artem Serov8f7c4102017-06-21 11:21:37 +01001571 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001572 case DataType::Type::kUint16:
1573 case DataType::Type::kInt16:
Aart Bik0148de42017-09-05 09:25:01 -07001574 *restrictions |= kNoDiv | kNoStringCharAt | kNoReduction;
Artem Serov8f7c4102017-06-21 11:21:37 +01001575 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001576 case DataType::Type::kInt32:
Artem Serov6e9b1372017-10-05 16:48:30 +01001577 *restrictions |= kNoDiv | kNoWideSAD;
Artem Serov8f7c4102017-06-21 11:21:37 +01001578 return TrySetVectorLength(2);
1579 default:
1580 break;
1581 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001582 return false;
Vladimir Marko33bff252017-11-01 14:35:42 +00001583 case InstructionSet::kArm64:
Aart Bikf8f5a162017-02-06 15:35:29 -08001584 // Allow vectorization for all ARM devices, because Android assumes that
Aart Bikb29f6842017-07-28 15:58:41 -07001585 // ARMv8 AArch64 always supports advanced SIMD (128-bit SIMD).
Aart Bikf8f5a162017-02-06 15:35:29 -08001586 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001587 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001588 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001589 case DataType::Type::kInt8:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001590 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +01001591 return TrySetVectorLength(16);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001592 case DataType::Type::kUint16:
1593 case DataType::Type::kInt16:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001594 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +01001595 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001596 case DataType::Type::kInt32:
Aart Bikf8f5a162017-02-06 15:35:29 -08001597 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +01001598 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001599 case DataType::Type::kInt64:
Aart Bikc8e93c72017-05-10 10:49:22 -07001600 *restrictions |= kNoDiv | kNoMul | kNoMinMax;
Aart Bikf8f5a162017-02-06 15:35:29 -08001601 return TrySetVectorLength(2);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001602 case DataType::Type::kFloat32:
Aart Bik0148de42017-09-05 09:25:01 -07001603 *restrictions |= kNoReduction;
Artem Serovd4bccf12017-04-03 18:47:32 +01001604 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001605 case DataType::Type::kFloat64:
Aart Bik0148de42017-09-05 09:25:01 -07001606 *restrictions |= kNoReduction;
Aart Bikf8f5a162017-02-06 15:35:29 -08001607 return TrySetVectorLength(2);
1608 default:
1609 return false;
1610 }
Vladimir Marko33bff252017-11-01 14:35:42 +00001611 case InstructionSet::kX86:
1612 case InstructionSet::kX86_64:
Aart Bikb29f6842017-07-28 15:58:41 -07001613 // Allow vectorization for SSE4.1-enabled X86 devices only (128-bit SIMD).
Aart Bikf8f5a162017-02-06 15:35:29 -08001614 if (features->AsX86InstructionSetFeatures()->HasSSE4_1()) {
1615 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001616 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001617 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001618 case DataType::Type::kInt8:
Aart Bik0148de42017-09-05 09:25:01 -07001619 *restrictions |=
Aart Bikdbbac8f2017-09-01 13:06:08 -07001620 kNoMul | kNoDiv | kNoShift | kNoAbs | kNoSignedHAdd | kNoUnroundedHAdd | kNoSAD;
Aart Bikf8f5a162017-02-06 15:35:29 -08001621 return TrySetVectorLength(16);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001622 case DataType::Type::kUint16:
1623 case DataType::Type::kInt16:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001624 *restrictions |= kNoDiv | kNoAbs | kNoSignedHAdd | kNoUnroundedHAdd | kNoSAD;
Aart Bikf8f5a162017-02-06 15:35:29 -08001625 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001626 case DataType::Type::kInt32:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001627 *restrictions |= kNoDiv | kNoSAD;
Aart Bikf8f5a162017-02-06 15:35:29 -08001628 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001629 case DataType::Type::kInt64:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001630 *restrictions |= kNoMul | kNoDiv | kNoShr | kNoAbs | kNoMinMax | kNoSAD;
Aart Bikf8f5a162017-02-06 15:35:29 -08001631 return TrySetVectorLength(2);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001632 case DataType::Type::kFloat32:
Aart Bik0148de42017-09-05 09:25:01 -07001633 *restrictions |= kNoMinMax | kNoReduction; // minmax: -0.0 vs +0.0
Aart Bikf8f5a162017-02-06 15:35:29 -08001634 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001635 case DataType::Type::kFloat64:
Aart Bik0148de42017-09-05 09:25:01 -07001636 *restrictions |= kNoMinMax | kNoReduction; // minmax: -0.0 vs +0.0
Aart Bikf8f5a162017-02-06 15:35:29 -08001637 return TrySetVectorLength(2);
1638 default:
1639 break;
1640 } // switch type
1641 }
1642 return false;
Vladimir Marko33bff252017-11-01 14:35:42 +00001643 case InstructionSet::kMips:
Lena Djokic51765b02017-06-22 13:49:59 +02001644 if (features->AsMipsInstructionSetFeatures()->HasMsa()) {
1645 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001646 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001647 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001648 case DataType::Type::kInt8:
Aart Bik29aa0822018-03-08 11:28:00 -08001649 *restrictions |= kNoDiv | kNoSaturation;
Lena Djokic51765b02017-06-22 13:49:59 +02001650 return TrySetVectorLength(16);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001651 case DataType::Type::kUint16:
1652 case DataType::Type::kInt16:
Aart Bik29aa0822018-03-08 11:28:00 -08001653 *restrictions |= kNoDiv | kNoSaturation | kNoStringCharAt;
Lena Djokic51765b02017-06-22 13:49:59 +02001654 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001655 case DataType::Type::kInt32:
Lena Djokic38e380b2017-10-30 16:17:10 +01001656 *restrictions |= kNoDiv;
Lena Djokic51765b02017-06-22 13:49:59 +02001657 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001658 case DataType::Type::kInt64:
Lena Djokic38e380b2017-10-30 16:17:10 +01001659 *restrictions |= kNoDiv;
Lena Djokic51765b02017-06-22 13:49:59 +02001660 return TrySetVectorLength(2);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001661 case DataType::Type::kFloat32:
Aart Bik0148de42017-09-05 09:25:01 -07001662 *restrictions |= kNoMinMax | kNoReduction; // min/max(x, NaN)
Lena Djokic51765b02017-06-22 13:49:59 +02001663 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001664 case DataType::Type::kFloat64:
Aart Bik0148de42017-09-05 09:25:01 -07001665 *restrictions |= kNoMinMax | kNoReduction; // min/max(x, NaN)
Lena Djokic51765b02017-06-22 13:49:59 +02001666 return TrySetVectorLength(2);
1667 default:
1668 break;
1669 } // switch type
1670 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001671 return false;
Vladimir Marko33bff252017-11-01 14:35:42 +00001672 case InstructionSet::kMips64:
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001673 if (features->AsMips64InstructionSetFeatures()->HasMsa()) {
1674 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001675 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001676 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001677 case DataType::Type::kInt8:
Aart Bik29aa0822018-03-08 11:28:00 -08001678 *restrictions |= kNoDiv | kNoSaturation;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001679 return TrySetVectorLength(16);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001680 case DataType::Type::kUint16:
1681 case DataType::Type::kInt16:
Aart Bik29aa0822018-03-08 11:28:00 -08001682 *restrictions |= kNoDiv | kNoSaturation | kNoStringCharAt;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001683 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001684 case DataType::Type::kInt32:
Lena Djokic38e380b2017-10-30 16:17:10 +01001685 *restrictions |= kNoDiv;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001686 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001687 case DataType::Type::kInt64:
Lena Djokic38e380b2017-10-30 16:17:10 +01001688 *restrictions |= kNoDiv;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001689 return TrySetVectorLength(2);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001690 case DataType::Type::kFloat32:
Aart Bik0148de42017-09-05 09:25:01 -07001691 *restrictions |= kNoMinMax | kNoReduction; // min/max(x, NaN)
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001692 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001693 case DataType::Type::kFloat64:
Aart Bik0148de42017-09-05 09:25:01 -07001694 *restrictions |= kNoMinMax | kNoReduction; // min/max(x, NaN)
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001695 return TrySetVectorLength(2);
1696 default:
1697 break;
1698 } // switch type
1699 }
1700 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001701 default:
1702 return false;
1703 } // switch instruction set
1704}
1705
1706bool HLoopOptimization::TrySetVectorLength(uint32_t length) {
1707 DCHECK(IsPowerOfTwo(length) && length >= 2u);
1708 // First time set?
1709 if (vector_length_ == 0) {
1710 vector_length_ = length;
1711 }
1712 // Different types are acceptable within a loop-body, as long as all the corresponding vector
1713 // lengths match exactly to obtain a uniform traversal through the vector iteration space
1714 // (idiomatic exceptions to this rule can be handled by further unrolling sub-expressions).
1715 return vector_length_ == length;
1716}
1717
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001718void HLoopOptimization::GenerateVecInv(HInstruction* org, DataType::Type type) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001719 if (vector_map_->find(org) == vector_map_->end()) {
1720 // In scalar code, just use a self pass-through for scalar invariants
1721 // (viz. expression remains itself).
1722 if (vector_mode_ == kSequential) {
1723 vector_map_->Put(org, org);
1724 return;
1725 }
1726 // In vector code, explicit scalar expansion is needed.
Aart Bik0148de42017-09-05 09:25:01 -07001727 HInstruction* vector = nullptr;
1728 auto it = vector_permanent_map_->find(org);
1729 if (it != vector_permanent_map_->end()) {
1730 vector = it->second; // reuse during unrolling
1731 } else {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001732 // Generates ReplicateScalar( (optional_type_conv) org ).
1733 HInstruction* input = org;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001734 DataType::Type input_type = input->GetType();
1735 if (type != input_type && (type == DataType::Type::kInt64 ||
1736 input_type == DataType::Type::kInt64)) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001737 input = Insert(vector_preheader_,
1738 new (global_allocator_) HTypeConversion(type, input, kNoDexPc));
1739 }
1740 vector = new (global_allocator_)
Aart Bik46b6dbc2017-10-03 11:37:37 -07001741 HVecReplicateScalar(global_allocator_, input, type, vector_length_, kNoDexPc);
Aart Bik0148de42017-09-05 09:25:01 -07001742 vector_permanent_map_->Put(org, Insert(vector_preheader_, vector));
1743 }
1744 vector_map_->Put(org, vector);
Aart Bikf8f5a162017-02-06 15:35:29 -08001745 }
1746}
1747
1748void HLoopOptimization::GenerateVecSub(HInstruction* org, HInstruction* offset) {
1749 if (vector_map_->find(org) == vector_map_->end()) {
Aart Bik14a68b42017-06-08 14:06:58 -07001750 HInstruction* subscript = vector_index_;
Aart Bik37dc4df2017-06-28 14:08:00 -07001751 int64_t value = 0;
1752 if (!IsInt64AndGet(offset, &value) || value != 0) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001753 subscript = new (global_allocator_) HAdd(DataType::Type::kInt32, subscript, offset);
Aart Bikf8f5a162017-02-06 15:35:29 -08001754 if (org->IsPhi()) {
1755 Insert(vector_body_, subscript); // lacks layout placeholder
1756 }
1757 }
1758 vector_map_->Put(org, subscript);
1759 }
1760}
1761
1762void HLoopOptimization::GenerateVecMem(HInstruction* org,
1763 HInstruction* opa,
1764 HInstruction* opb,
Aart Bik14a68b42017-06-08 14:06:58 -07001765 HInstruction* offset,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001766 DataType::Type type) {
Aart Bik46b6dbc2017-10-03 11:37:37 -07001767 uint32_t dex_pc = org->GetDexPc();
Aart Bikf8f5a162017-02-06 15:35:29 -08001768 HInstruction* vector = nullptr;
1769 if (vector_mode_ == kVector) {
1770 // Vector store or load.
Aart Bik38a3f212017-10-20 17:02:21 -07001771 bool is_string_char_at = false;
Aart Bik14a68b42017-06-08 14:06:58 -07001772 HInstruction* base = org->InputAt(0);
Aart Bikf8f5a162017-02-06 15:35:29 -08001773 if (opb != nullptr) {
1774 vector = new (global_allocator_) HVecStore(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001775 global_allocator_, base, opa, opb, type, org->GetSideEffects(), vector_length_, dex_pc);
Aart Bikf8f5a162017-02-06 15:35:29 -08001776 } else {
Aart Bik38a3f212017-10-20 17:02:21 -07001777 is_string_char_at = org->AsArrayGet()->IsStringCharAt();
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001778 vector = new (global_allocator_) HVecLoad(global_allocator_,
1779 base,
1780 opa,
1781 type,
1782 org->GetSideEffects(),
1783 vector_length_,
Aart Bik46b6dbc2017-10-03 11:37:37 -07001784 is_string_char_at,
1785 dex_pc);
Aart Bik14a68b42017-06-08 14:06:58 -07001786 }
Aart Bik38a3f212017-10-20 17:02:21 -07001787 // Known (forced/adjusted/original) alignment?
1788 if (vector_dynamic_peeling_candidate_ != nullptr) {
1789 if (vector_dynamic_peeling_candidate_->offset == offset && // TODO: diffs too?
1790 DataType::Size(vector_dynamic_peeling_candidate_->type) == DataType::Size(type) &&
1791 vector_dynamic_peeling_candidate_->is_string_char_at == is_string_char_at) {
1792 vector->AsVecMemoryOperation()->SetAlignment( // forced
1793 Alignment(GetVectorSizeInBytes(), 0));
1794 }
1795 } else {
1796 vector->AsVecMemoryOperation()->SetAlignment( // adjusted/original
1797 ComputeAlignment(offset, type, is_string_char_at, vector_static_peeling_factor_));
Aart Bikf8f5a162017-02-06 15:35:29 -08001798 }
1799 } else {
1800 // Scalar store or load.
1801 DCHECK(vector_mode_ == kSequential);
1802 if (opb != nullptr) {
Aart Bik4d1a9d42017-10-19 14:40:55 -07001803 DataType::Type component_type = org->AsArraySet()->GetComponentType();
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001804 vector = new (global_allocator_) HArraySet(
Aart Bik4d1a9d42017-10-19 14:40:55 -07001805 org->InputAt(0), opa, opb, component_type, org->GetSideEffects(), dex_pc);
Aart Bikf8f5a162017-02-06 15:35:29 -08001806 } else {
Aart Bikdb14fcf2017-04-25 15:53:58 -07001807 bool is_string_char_at = org->AsArrayGet()->IsStringCharAt();
1808 vector = new (global_allocator_) HArrayGet(
Aart Bik4d1a9d42017-10-19 14:40:55 -07001809 org->InputAt(0), opa, org->GetType(), org->GetSideEffects(), dex_pc, is_string_char_at);
Aart Bikf8f5a162017-02-06 15:35:29 -08001810 }
1811 }
1812 vector_map_->Put(org, vector);
1813}
1814
Aart Bik0148de42017-09-05 09:25:01 -07001815void HLoopOptimization::GenerateVecReductionPhi(HPhi* phi) {
1816 DCHECK(reductions_->find(phi) != reductions_->end());
1817 DCHECK(reductions_->Get(phi->InputAt(1)) == phi);
1818 HInstruction* vector = nullptr;
1819 if (vector_mode_ == kSequential) {
1820 HPhi* new_phi = new (global_allocator_) HPhi(
1821 global_allocator_, kNoRegNumber, 0, phi->GetType());
1822 vector_header_->AddPhi(new_phi);
1823 vector = new_phi;
1824 } else {
1825 // Link vector reduction back to prior unrolled update, or a first phi.
1826 auto it = vector_permanent_map_->find(phi);
1827 if (it != vector_permanent_map_->end()) {
1828 vector = it->second;
1829 } else {
1830 HPhi* new_phi = new (global_allocator_) HPhi(
1831 global_allocator_, kNoRegNumber, 0, HVecOperation::kSIMDType);
1832 vector_header_->AddPhi(new_phi);
1833 vector = new_phi;
1834 }
1835 }
1836 vector_map_->Put(phi, vector);
1837}
1838
1839void HLoopOptimization::GenerateVecReductionPhiInputs(HPhi* phi, HInstruction* reduction) {
1840 HInstruction* new_phi = vector_map_->Get(phi);
1841 HInstruction* new_init = reductions_->Get(phi);
1842 HInstruction* new_red = vector_map_->Get(reduction);
1843 // Link unrolled vector loop back to new phi.
1844 for (; !new_phi->IsPhi(); new_phi = vector_permanent_map_->Get(new_phi)) {
1845 DCHECK(new_phi->IsVecOperation());
1846 }
1847 // Prepare the new initialization.
1848 if (vector_mode_ == kVector) {
Goran Jakovljevic89b8df02017-10-13 08:33:17 +02001849 // Generate a [initial, 0, .., 0] vector for add or
1850 // a [initial, initial, .., initial] vector for min/max.
Aart Bikdbbac8f2017-09-01 13:06:08 -07001851 HVecOperation* red_vector = new_red->AsVecOperation();
Goran Jakovljevic89b8df02017-10-13 08:33:17 +02001852 HVecReduce::ReductionKind kind = GetReductionKind(red_vector);
Aart Bik38a3f212017-10-20 17:02:21 -07001853 uint32_t vector_length = red_vector->GetVectorLength();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001854 DataType::Type type = red_vector->GetPackedType();
Goran Jakovljevic89b8df02017-10-13 08:33:17 +02001855 if (kind == HVecReduce::ReductionKind::kSum) {
1856 new_init = Insert(vector_preheader_,
1857 new (global_allocator_) HVecSetScalars(global_allocator_,
1858 &new_init,
1859 type,
1860 vector_length,
1861 1,
1862 kNoDexPc));
1863 } else {
1864 new_init = Insert(vector_preheader_,
1865 new (global_allocator_) HVecReplicateScalar(global_allocator_,
1866 new_init,
1867 type,
1868 vector_length,
1869 kNoDexPc));
1870 }
Aart Bik0148de42017-09-05 09:25:01 -07001871 } else {
1872 new_init = ReduceAndExtractIfNeeded(new_init);
1873 }
1874 // Set the phi inputs.
1875 DCHECK(new_phi->IsPhi());
1876 new_phi->AsPhi()->AddInput(new_init);
1877 new_phi->AsPhi()->AddInput(new_red);
1878 // New feed value for next phi (safe mutation in iteration).
1879 reductions_->find(phi)->second = new_phi;
1880}
1881
1882HInstruction* HLoopOptimization::ReduceAndExtractIfNeeded(HInstruction* instruction) {
1883 if (instruction->IsPhi()) {
1884 HInstruction* input = instruction->InputAt(1);
Aart Bik2dd7b672017-12-07 11:11:22 -08001885 if (HVecOperation::ReturnsSIMDValue(input)) {
1886 DCHECK(!input->IsPhi());
Aart Bikdbbac8f2017-09-01 13:06:08 -07001887 HVecOperation* input_vector = input->AsVecOperation();
Aart Bik38a3f212017-10-20 17:02:21 -07001888 uint32_t vector_length = input_vector->GetVectorLength();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001889 DataType::Type type = input_vector->GetPackedType();
Aart Bikdbbac8f2017-09-01 13:06:08 -07001890 HVecReduce::ReductionKind kind = GetReductionKind(input_vector);
Aart Bik0148de42017-09-05 09:25:01 -07001891 HBasicBlock* exit = instruction->GetBlock()->GetSuccessors()[0];
1892 // Generate a vector reduction and scalar extract
1893 // x = REDUCE( [x_1, .., x_n] )
1894 // y = x_1
1895 // along the exit of the defining loop.
Aart Bik0148de42017-09-05 09:25:01 -07001896 HInstruction* reduce = new (global_allocator_) HVecReduce(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001897 global_allocator_, instruction, type, vector_length, kind, kNoDexPc);
Aart Bik0148de42017-09-05 09:25:01 -07001898 exit->InsertInstructionBefore(reduce, exit->GetFirstInstruction());
1899 instruction = new (global_allocator_) HVecExtractScalar(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001900 global_allocator_, reduce, type, vector_length, 0, kNoDexPc);
Aart Bik0148de42017-09-05 09:25:01 -07001901 exit->InsertInstructionAfter(instruction, reduce);
1902 }
1903 }
1904 return instruction;
1905}
1906
Aart Bikf8f5a162017-02-06 15:35:29 -08001907#define GENERATE_VEC(x, y) \
1908 if (vector_mode_ == kVector) { \
1909 vector = (x); \
1910 } else { \
1911 DCHECK(vector_mode_ == kSequential); \
1912 vector = (y); \
1913 } \
1914 break;
1915
1916void HLoopOptimization::GenerateVecOp(HInstruction* org,
1917 HInstruction* opa,
1918 HInstruction* opb,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001919 DataType::Type type,
Aart Bik304c8a52017-05-23 11:01:13 -07001920 bool is_unsigned) {
Aart Bik46b6dbc2017-10-03 11:37:37 -07001921 uint32_t dex_pc = org->GetDexPc();
Aart Bikf8f5a162017-02-06 15:35:29 -08001922 HInstruction* vector = nullptr;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001923 DataType::Type org_type = org->GetType();
Aart Bikf8f5a162017-02-06 15:35:29 -08001924 switch (org->GetKind()) {
1925 case HInstruction::kNeg:
1926 DCHECK(opb == nullptr);
1927 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001928 new (global_allocator_) HVecNeg(global_allocator_, opa, type, vector_length_, dex_pc),
1929 new (global_allocator_) HNeg(org_type, opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001930 case HInstruction::kNot:
1931 DCHECK(opb == nullptr);
1932 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001933 new (global_allocator_) HVecNot(global_allocator_, opa, type, vector_length_, dex_pc),
1934 new (global_allocator_) HNot(org_type, opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001935 case HInstruction::kBooleanNot:
1936 DCHECK(opb == nullptr);
1937 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001938 new (global_allocator_) HVecNot(global_allocator_, opa, type, vector_length_, dex_pc),
1939 new (global_allocator_) HBooleanNot(opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001940 case HInstruction::kTypeConversion:
1941 DCHECK(opb == nullptr);
1942 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001943 new (global_allocator_) HVecCnv(global_allocator_, opa, type, vector_length_, dex_pc),
1944 new (global_allocator_) HTypeConversion(org_type, opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001945 case HInstruction::kAdd:
1946 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001947 new (global_allocator_) HVecAdd(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1948 new (global_allocator_) HAdd(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001949 case HInstruction::kSub:
1950 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001951 new (global_allocator_) HVecSub(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1952 new (global_allocator_) HSub(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001953 case HInstruction::kMul:
1954 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001955 new (global_allocator_) HVecMul(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1956 new (global_allocator_) HMul(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001957 case HInstruction::kDiv:
1958 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001959 new (global_allocator_) HVecDiv(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1960 new (global_allocator_) HDiv(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001961 case HInstruction::kAnd:
1962 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001963 new (global_allocator_) HVecAnd(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1964 new (global_allocator_) HAnd(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001965 case HInstruction::kOr:
1966 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001967 new (global_allocator_) HVecOr(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1968 new (global_allocator_) HOr(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001969 case HInstruction::kXor:
1970 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001971 new (global_allocator_) HVecXor(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1972 new (global_allocator_) HXor(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001973 case HInstruction::kShl:
1974 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001975 new (global_allocator_) HVecShl(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1976 new (global_allocator_) HShl(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001977 case HInstruction::kShr:
1978 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001979 new (global_allocator_) HVecShr(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1980 new (global_allocator_) HShr(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001981 case HInstruction::kUShr:
1982 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001983 new (global_allocator_) HVecUShr(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1984 new (global_allocator_) HUShr(org_type, opa, opb, dex_pc));
Aart Bik1f8d51b2018-02-15 10:42:37 -08001985 case HInstruction::kMin:
1986 GENERATE_VEC(
1987 new (global_allocator_) HVecMin(global_allocator_,
1988 opa,
1989 opb,
1990 HVecOperation::ToProperType(type, is_unsigned),
1991 vector_length_,
1992 dex_pc),
1993 new (global_allocator_) HMin(org_type, opa, opb, dex_pc));
1994 case HInstruction::kMax:
1995 GENERATE_VEC(
1996 new (global_allocator_) HVecMax(global_allocator_,
1997 opa,
1998 opb,
1999 HVecOperation::ToProperType(type, is_unsigned),
2000 vector_length_,
2001 dex_pc),
2002 new (global_allocator_) HMax(org_type, opa, opb, dex_pc));
Aart Bik3b2a5952018-03-05 13:55:28 -08002003 case HInstruction::kAbs:
2004 DCHECK(opb == nullptr);
2005 GENERATE_VEC(
2006 new (global_allocator_) HVecAbs(global_allocator_, opa, type, vector_length_, dex_pc),
2007 new (global_allocator_) HAbs(org_type, opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08002008 default:
2009 break;
2010 } // switch
2011 CHECK(vector != nullptr) << "Unsupported SIMD operator";
2012 vector_map_->Put(org, vector);
2013}
2014
2015#undef GENERATE_VEC
2016
2017//
Aart Bikf3e61ee2017-04-12 17:09:20 -07002018// Vectorization idioms.
2019//
2020
Aart Bik29aa0822018-03-08 11:28:00 -08002021// Method recognizes single and double clipping saturation arithmetic.
2022bool HLoopOptimization::VectorizeSaturationIdiom(LoopNode* node,
2023 HInstruction* instruction,
2024 bool generate_code,
2025 DataType::Type type,
2026 uint64_t restrictions) {
2027 // Deal with vector restrictions.
2028 if (HasVectorRestrictions(restrictions, kNoSaturation)) {
2029 return false;
2030 }
Aart Bik1a381022018-03-15 15:51:37 -07002031 // Restrict type (generalize if one day we generalize allowed MIN/MAX integral types).
2032 if (instruction->GetType() != DataType::Type::kInt32 &&
2033 instruction->GetType() != DataType::Type::kInt64) {
Aart Bik29aa0822018-03-08 11:28:00 -08002034 return false;
2035 }
Nicolas Geoffraya3e23262018-03-28 11:15:12 +00002036 // Clipped addition or subtraction on narrower operands? We will try both
2037 // formats since, e.g., x+c can be interpreted as x+c and x-(-c), depending
2038 // on what clipping values are used, to get most benefits.
Aart Bik1a381022018-03-15 15:51:37 -07002039 int64_t lo = std::numeric_limits<int64_t>::min();
2040 int64_t hi = std::numeric_limits<int64_t>::max();
2041 HInstruction* clippee = FindClippee(instruction, &lo, &hi);
Nicolas Geoffraya3e23262018-03-28 11:15:12 +00002042 HInstruction* a = nullptr;
2043 HInstruction* b = nullptr;
Aart Bik29aa0822018-03-08 11:28:00 -08002044 HInstruction* r = nullptr;
2045 HInstruction* s = nullptr;
2046 bool is_unsigned = false;
Nicolas Geoffraya3e23262018-03-28 11:15:12 +00002047 bool is_add = true;
2048 int64_t c = 0;
2049 // First try for saturated addition.
2050 if (IsAddConst2(graph_, clippee, /*out*/ &a, /*out*/ &b, /*out*/ &c) && c == 0 &&
2051 IsNarrowerOperands(a, b, type, &r, &s, &is_unsigned) &&
2052 IsSaturatedAdd(r, s, type, lo, hi, is_unsigned)) {
2053 is_add = true;
Aart Bik29aa0822018-03-08 11:28:00 -08002054 } else {
Nicolas Geoffraya3e23262018-03-28 11:15:12 +00002055 // Then try again for saturated subtraction.
2056 a = b = r = s = nullptr;
2057 if (IsSubConst2(graph_, clippee, /*out*/ &a, /*out*/ &b) &&
2058 IsNarrowerOperands(a, b, type, &r, &s, &is_unsigned) &&
2059 IsSaturatedSub(r, type, lo, hi, is_unsigned)) {
2060 is_add = false;
2061 } else {
2062 return false;
2063 }
Aart Bik29aa0822018-03-08 11:28:00 -08002064 }
2065 // Accept saturation idiom for vectorizable operands.
Nicolas Geoffraya3e23262018-03-28 11:15:12 +00002066 DCHECK(r != nullptr && s != nullptr);
Aart Bik29aa0822018-03-08 11:28:00 -08002067 if (generate_code && vector_mode_ != kVector) { // de-idiom
2068 r = instruction->InputAt(0);
2069 s = instruction->InputAt(1);
2070 restrictions &= ~(kNoHiBits | kNoMinMax); // allow narrow MIN/MAX in seq
2071 }
2072 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
2073 VectorizeUse(node, s, generate_code, type, restrictions)) {
2074 if (generate_code) {
2075 if (vector_mode_ == kVector) {
2076 DataType::Type vtype = HVecOperation::ToProperType(type, is_unsigned);
2077 HInstruction* op1 = vector_map_->Get(r);
2078 HInstruction* op2 = vector_map_->Get(s);
2079 vector_map_->Put(instruction, is_add
2080 ? reinterpret_cast<HInstruction*>(new (global_allocator_) HVecSaturationAdd(
2081 global_allocator_, op1, op2, vtype, vector_length_, kNoDexPc))
2082 : reinterpret_cast<HInstruction*>(new (global_allocator_) HVecSaturationSub(
2083 global_allocator_, op1, op2, vtype, vector_length_, kNoDexPc)));
2084 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorizedIdiom);
2085 } else {
2086 GenerateVecOp(instruction, vector_map_->Get(r), vector_map_->Get(s), type);
2087 }
2088 }
2089 return true;
2090 }
2091 return false;
2092}
2093
Aart Bikf3e61ee2017-04-12 17:09:20 -07002094// Method recognizes the following idioms:
Aart Bikdbbac8f2017-09-01 13:06:08 -07002095// rounding halving add (a + b + 1) >> 1 for unsigned/signed operands a, b
2096// truncated halving add (a + b) >> 1 for unsigned/signed operands a, b
Aart Bikf3e61ee2017-04-12 17:09:20 -07002097// Provided that the operands are promoted to a wider form to do the arithmetic and
2098// then cast back to narrower form, the idioms can be mapped into efficient SIMD
2099// implementation that operates directly in narrower form (plus one extra bit).
2100// TODO: current version recognizes implicit byte/short/char widening only;
2101// explicit widening from int to long could be added later.
2102bool HLoopOptimization::VectorizeHalvingAddIdiom(LoopNode* node,
2103 HInstruction* instruction,
2104 bool generate_code,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002105 DataType::Type type,
Aart Bikf3e61ee2017-04-12 17:09:20 -07002106 uint64_t restrictions) {
2107 // Test for top level arithmetic shift right x >> 1 or logical shift right x >>> 1
Aart Bik304c8a52017-05-23 11:01:13 -07002108 // (note whether the sign bit in wider precision is shifted in has no effect
Aart Bikf3e61ee2017-04-12 17:09:20 -07002109 // on the narrow precision computed by the idiom).
Aart Bikf3e61ee2017-04-12 17:09:20 -07002110 if ((instruction->IsShr() ||
2111 instruction->IsUShr()) &&
Aart Bik0148de42017-09-05 09:25:01 -07002112 IsInt64Value(instruction->InputAt(1), 1)) {
Aart Bik5f805002017-05-16 16:42:41 -07002113 // Test for (a + b + c) >> 1 for optional constant c.
2114 HInstruction* a = nullptr;
2115 HInstruction* b = nullptr;
2116 int64_t c = 0;
Nicolas Geoffraya3e23262018-03-28 11:15:12 +00002117 if (IsAddConst2(graph_, instruction->InputAt(0), /*out*/ &a, /*out*/ &b, /*out*/ &c)) {
Aart Bik5f805002017-05-16 16:42:41 -07002118 // Accept c == 1 (rounded) or c == 0 (not rounded).
2119 bool is_rounded = false;
2120 if (c == 1) {
2121 is_rounded = true;
2122 } else if (c != 0) {
2123 return false;
2124 }
2125 // Accept consistent zero or sign extension on operands a and b.
Aart Bikf3e61ee2017-04-12 17:09:20 -07002126 HInstruction* r = nullptr;
2127 HInstruction* s = nullptr;
2128 bool is_unsigned = false;
Aart Bik304c8a52017-05-23 11:01:13 -07002129 if (!IsNarrowerOperands(a, b, type, &r, &s, &is_unsigned)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -07002130 return false;
2131 }
2132 // Deal with vector restrictions.
2133 if ((!is_unsigned && HasVectorRestrictions(restrictions, kNoSignedHAdd)) ||
2134 (!is_rounded && HasVectorRestrictions(restrictions, kNoUnroundedHAdd))) {
2135 return false;
2136 }
2137 // Accept recognized halving add for vectorizable operands. Vectorized code uses the
2138 // shorthand idiomatic operation. Sequential code uses the original scalar expressions.
Nicolas Geoffraya3e23262018-03-28 11:15:12 +00002139 DCHECK(r != nullptr && s != nullptr);
Aart Bik304c8a52017-05-23 11:01:13 -07002140 if (generate_code && vector_mode_ != kVector) { // de-idiom
2141 r = instruction->InputAt(0);
2142 s = instruction->InputAt(1);
2143 }
Aart Bikf3e61ee2017-04-12 17:09:20 -07002144 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
2145 VectorizeUse(node, s, generate_code, type, restrictions)) {
2146 if (generate_code) {
2147 if (vector_mode_ == kVector) {
2148 vector_map_->Put(instruction, new (global_allocator_) HVecHalvingAdd(
2149 global_allocator_,
2150 vector_map_->Get(r),
2151 vector_map_->Get(s),
Aart Bik66c158e2018-01-31 12:55:04 -08002152 HVecOperation::ToProperType(type, is_unsigned),
Aart Bikf3e61ee2017-04-12 17:09:20 -07002153 vector_length_,
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01002154 is_rounded,
Aart Bik46b6dbc2017-10-03 11:37:37 -07002155 kNoDexPc));
Aart Bik21b85922017-09-06 13:29:16 -07002156 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorizedIdiom);
Aart Bikf3e61ee2017-04-12 17:09:20 -07002157 } else {
Aart Bik304c8a52017-05-23 11:01:13 -07002158 GenerateVecOp(instruction, vector_map_->Get(r), vector_map_->Get(s), type);
Aart Bikf3e61ee2017-04-12 17:09:20 -07002159 }
2160 }
2161 return true;
2162 }
2163 }
2164 }
2165 return false;
2166}
2167
Aart Bikdbbac8f2017-09-01 13:06:08 -07002168// Method recognizes the following idiom:
2169// q += ABS(a - b) for signed operands a, b
2170// Provided that the operands have the same type or are promoted to a wider form.
2171// Since this may involve a vector length change, the idiom is handled by going directly
2172// to a sad-accumulate node (rather than relying combining finer grained nodes later).
2173// TODO: unsigned SAD too?
2174bool HLoopOptimization::VectorizeSADIdiom(LoopNode* node,
2175 HInstruction* instruction,
2176 bool generate_code,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002177 DataType::Type reduction_type,
Aart Bikdbbac8f2017-09-01 13:06:08 -07002178 uint64_t restrictions) {
2179 // Filter integral "q += ABS(a - b);" reduction, where ABS and SUB
2180 // are done in the same precision (either int or long).
2181 if (!instruction->IsAdd() ||
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002182 (reduction_type != DataType::Type::kInt32 && reduction_type != DataType::Type::kInt64)) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07002183 return false;
2184 }
2185 HInstruction* q = instruction->InputAt(0);
2186 HInstruction* v = instruction->InputAt(1);
2187 HInstruction* a = nullptr;
2188 HInstruction* b = nullptr;
Nicolas Geoffraya3e23262018-03-28 11:15:12 +00002189 if (v->IsAbs() &&
2190 v->GetType() == reduction_type &&
2191 IsSubConst2(graph_, v->InputAt(0), /*out*/ &a, /*out*/ &b)) {
2192 DCHECK(a != nullptr && b != nullptr);
2193 } else {
Aart Bikdbbac8f2017-09-01 13:06:08 -07002194 return false;
2195 }
2196 // Accept same-type or consistent sign extension for narrower-type on operands a and b.
2197 // The same-type or narrower operands are called r (a or lower) and s (b or lower).
Aart Bikdf011c32017-09-28 12:53:04 -07002198 // We inspect the operands carefully to pick the most suited type.
Aart Bikdbbac8f2017-09-01 13:06:08 -07002199 HInstruction* r = a;
2200 HInstruction* s = b;
2201 bool is_unsigned = false;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002202 DataType::Type sub_type = a->GetType();
Aart Bikdf011c32017-09-28 12:53:04 -07002203 if (DataType::Size(b->GetType()) < DataType::Size(sub_type)) {
2204 sub_type = b->GetType();
2205 }
2206 if (a->IsTypeConversion() &&
2207 DataType::Size(a->InputAt(0)->GetType()) < DataType::Size(sub_type)) {
2208 sub_type = a->InputAt(0)->GetType();
2209 }
2210 if (b->IsTypeConversion() &&
2211 DataType::Size(b->InputAt(0)->GetType()) < DataType::Size(sub_type)) {
2212 sub_type = b->InputAt(0)->GetType();
Aart Bikdbbac8f2017-09-01 13:06:08 -07002213 }
2214 if (reduction_type != sub_type &&
2215 (!IsNarrowerOperands(a, b, sub_type, &r, &s, &is_unsigned) || is_unsigned)) {
2216 return false;
2217 }
2218 // Try same/narrower type and deal with vector restrictions.
Artem Serov6e9b1372017-10-05 16:48:30 +01002219 if (!TrySetVectorType(sub_type, &restrictions) ||
2220 HasVectorRestrictions(restrictions, kNoSAD) ||
2221 (reduction_type != sub_type && HasVectorRestrictions(restrictions, kNoWideSAD))) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07002222 return false;
2223 }
2224 // Accept SAD idiom for vectorizable operands. Vectorized code uses the shorthand
2225 // idiomatic operation. Sequential code uses the original scalar expressions.
Nicolas Geoffraya3e23262018-03-28 11:15:12 +00002226 DCHECK(r != nullptr && s != nullptr);
Aart Bikdbbac8f2017-09-01 13:06:08 -07002227 if (generate_code && vector_mode_ != kVector) { // de-idiom
2228 r = s = v->InputAt(0);
2229 }
2230 if (VectorizeUse(node, q, generate_code, sub_type, restrictions) &&
2231 VectorizeUse(node, r, generate_code, sub_type, restrictions) &&
2232 VectorizeUse(node, s, generate_code, sub_type, restrictions)) {
2233 if (generate_code) {
2234 if (vector_mode_ == kVector) {
2235 vector_map_->Put(instruction, new (global_allocator_) HVecSADAccumulate(
2236 global_allocator_,
2237 vector_map_->Get(q),
2238 vector_map_->Get(r),
2239 vector_map_->Get(s),
Aart Bik3b2a5952018-03-05 13:55:28 -08002240 HVecOperation::ToProperType(reduction_type, is_unsigned),
Aart Bik46b6dbc2017-10-03 11:37:37 -07002241 GetOtherVL(reduction_type, sub_type, vector_length_),
2242 kNoDexPc));
Aart Bikdbbac8f2017-09-01 13:06:08 -07002243 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorizedIdiom);
2244 } else {
2245 GenerateVecOp(v, vector_map_->Get(r), nullptr, reduction_type);
2246 GenerateVecOp(instruction, vector_map_->Get(q), vector_map_->Get(v), reduction_type);
2247 }
2248 }
2249 return true;
2250 }
2251 return false;
2252}
2253
Aart Bikf3e61ee2017-04-12 17:09:20 -07002254//
Aart Bik14a68b42017-06-08 14:06:58 -07002255// Vectorization heuristics.
2256//
2257
Aart Bik38a3f212017-10-20 17:02:21 -07002258Alignment HLoopOptimization::ComputeAlignment(HInstruction* offset,
2259 DataType::Type type,
2260 bool is_string_char_at,
2261 uint32_t peeling) {
2262 // Combine the alignment and hidden offset that is guaranteed by
2263 // the Android runtime with a known starting index adjusted as bytes.
2264 int64_t value = 0;
2265 if (IsInt64AndGet(offset, /*out*/ &value)) {
2266 uint32_t start_offset =
2267 HiddenOffset(type, is_string_char_at) + (value + peeling) * DataType::Size(type);
2268 return Alignment(BaseAlignment(), start_offset & (BaseAlignment() - 1u));
2269 }
2270 // Otherwise, the Android runtime guarantees at least natural alignment.
2271 return Alignment(DataType::Size(type), 0);
2272}
2273
2274void HLoopOptimization::SetAlignmentStrategy(uint32_t peeling_votes[],
2275 const ArrayReference* peeling_candidate) {
2276 // Current heuristic: pick the best static loop peeling factor, if any,
2277 // or otherwise use dynamic loop peeling on suggested peeling candidate.
2278 uint32_t max_vote = 0;
2279 for (int32_t i = 0; i < 16; i++) {
2280 if (peeling_votes[i] > max_vote) {
2281 max_vote = peeling_votes[i];
2282 vector_static_peeling_factor_ = i;
2283 }
2284 }
2285 if (max_vote == 0) {
2286 vector_dynamic_peeling_candidate_ = peeling_candidate;
2287 }
2288}
2289
2290uint32_t HLoopOptimization::MaxNumberPeeled() {
2291 if (vector_dynamic_peeling_candidate_ != nullptr) {
2292 return vector_length_ - 1u; // worst-case
2293 }
2294 return vector_static_peeling_factor_; // known exactly
2295}
2296
Aart Bik14a68b42017-06-08 14:06:58 -07002297bool HLoopOptimization::IsVectorizationProfitable(int64_t trip_count) {
Aart Bik38a3f212017-10-20 17:02:21 -07002298 // Current heuristic: non-empty body with sufficient number of iterations (if known).
Aart Bik14a68b42017-06-08 14:06:58 -07002299 // TODO: refine by looking at e.g. operation count, alignment, etc.
Aart Bik38a3f212017-10-20 17:02:21 -07002300 // TODO: trip count is really unsigned entity, provided the guarding test
2301 // is satisfied; deal with this more carefully later
2302 uint32_t max_peel = MaxNumberPeeled();
Aart Bik14a68b42017-06-08 14:06:58 -07002303 if (vector_length_ == 0) {
2304 return false; // nothing found
Aart Bik38a3f212017-10-20 17:02:21 -07002305 } else if (trip_count < 0) {
2306 return false; // guard against non-taken/large
2307 } else if ((0 < trip_count) && (trip_count < (vector_length_ + max_peel))) {
Aart Bik14a68b42017-06-08 14:06:58 -07002308 return false; // insufficient iterations
2309 }
2310 return true;
2311}
2312
Aart Bik14a68b42017-06-08 14:06:58 -07002313//
Aart Bikf8f5a162017-02-06 15:35:29 -08002314// Helpers.
2315//
2316
2317bool HLoopOptimization::TrySetPhiInduction(HPhi* phi, bool restrict_uses) {
Aart Bikb29f6842017-07-28 15:58:41 -07002318 // Start with empty phi induction.
2319 iset_->clear();
2320
Nicolas Geoffrayf57c1ae2017-06-28 17:40:18 +01002321 // Special case Phis that have equivalent in a debuggable setup. Our graph checker isn't
2322 // smart enough to follow strongly connected components (and it's probably not worth
2323 // it to make it so). See b/33775412.
2324 if (graph_->IsDebuggable() && phi->HasEquivalentPhi()) {
2325 return false;
2326 }
Aart Bikb29f6842017-07-28 15:58:41 -07002327
2328 // Lookup phi induction cycle.
Aart Bikcc42be02016-10-20 16:14:16 -07002329 ArenaSet<HInstruction*>* set = induction_range_.LookupCycle(phi);
2330 if (set != nullptr) {
2331 for (HInstruction* i : *set) {
Aart Bike3dedc52016-11-02 17:50:27 -07002332 // Check that, other than instructions that are no longer in the graph (removed earlier)
Aart Bikf8f5a162017-02-06 15:35:29 -08002333 // each instruction is removable and, when restrict uses are requested, other than for phi,
2334 // all uses are contained within the cycle.
Aart Bike3dedc52016-11-02 17:50:27 -07002335 if (!i->IsInBlock()) {
2336 continue;
2337 } else if (!i->IsRemovable()) {
2338 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08002339 } else if (i != phi && restrict_uses) {
Aart Bikb29f6842017-07-28 15:58:41 -07002340 // Deal with regular uses.
Aart Bikcc42be02016-10-20 16:14:16 -07002341 for (const HUseListNode<HInstruction*>& use : i->GetUses()) {
2342 if (set->find(use.GetUser()) == set->end()) {
2343 return false;
2344 }
2345 }
2346 }
Aart Bike3dedc52016-11-02 17:50:27 -07002347 iset_->insert(i); // copy
Aart Bikcc42be02016-10-20 16:14:16 -07002348 }
Aart Bikcc42be02016-10-20 16:14:16 -07002349 return true;
2350 }
2351 return false;
2352}
2353
Aart Bikb29f6842017-07-28 15:58:41 -07002354bool HLoopOptimization::TrySetPhiReduction(HPhi* phi) {
Aart Bikcc42be02016-10-20 16:14:16 -07002355 DCHECK(iset_->empty());
Aart Bikb29f6842017-07-28 15:58:41 -07002356 // Only unclassified phi cycles are candidates for reductions.
2357 if (induction_range_.IsClassified(phi)) {
2358 return false;
2359 }
2360 // Accept operations like x = x + .., provided that the phi and the reduction are
2361 // used exactly once inside the loop, and by each other.
2362 HInputsRef inputs = phi->GetInputs();
2363 if (inputs.size() == 2) {
2364 HInstruction* reduction = inputs[1];
2365 if (HasReductionFormat(reduction, phi)) {
2366 HLoopInformation* loop_info = phi->GetBlock()->GetLoopInformation();
Aart Bik38a3f212017-10-20 17:02:21 -07002367 uint32_t use_count = 0;
Aart Bikb29f6842017-07-28 15:58:41 -07002368 bool single_use_inside_loop =
2369 // Reduction update only used by phi.
2370 reduction->GetUses().HasExactlyOneElement() &&
2371 !reduction->HasEnvironmentUses() &&
2372 // Reduction update is only use of phi inside the loop.
2373 IsOnlyUsedAfterLoop(loop_info, phi, /*collect_loop_uses*/ true, &use_count) &&
2374 iset_->size() == 1;
2375 iset_->clear(); // leave the way you found it
2376 if (single_use_inside_loop) {
2377 // Link reduction back, and start recording feed value.
2378 reductions_->Put(reduction, phi);
2379 reductions_->Put(phi, phi->InputAt(0));
2380 return true;
2381 }
2382 }
2383 }
2384 return false;
2385}
2386
2387bool HLoopOptimization::TrySetSimpleLoopHeader(HBasicBlock* block, /*out*/ HPhi** main_phi) {
2388 // Start with empty phi induction and reductions.
2389 iset_->clear();
2390 reductions_->clear();
2391
2392 // Scan the phis to find the following (the induction structure has already
2393 // been optimized, so we don't need to worry about trivial cases):
2394 // (1) optional reductions in loop,
2395 // (2) the main induction, used in loop control.
2396 HPhi* phi = nullptr;
2397 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
2398 if (TrySetPhiReduction(it.Current()->AsPhi())) {
2399 continue;
2400 } else if (phi == nullptr) {
2401 // Found the first candidate for main induction.
2402 phi = it.Current()->AsPhi();
2403 } else {
2404 return false;
2405 }
2406 }
2407
2408 // Then test for a typical loopheader:
2409 // s: SuspendCheck
2410 // c: Condition(phi, bound)
2411 // i: If(c)
2412 if (phi != nullptr && TrySetPhiInduction(phi, /*restrict_uses*/ false)) {
Aart Bikcc42be02016-10-20 16:14:16 -07002413 HInstruction* s = block->GetFirstInstruction();
2414 if (s != nullptr && s->IsSuspendCheck()) {
2415 HInstruction* c = s->GetNext();
Aart Bikd86c0852017-04-14 12:00:15 -07002416 if (c != nullptr &&
2417 c->IsCondition() &&
2418 c->GetUses().HasExactlyOneElement() && // only used for termination
2419 !c->HasEnvironmentUses()) { // unlikely, but not impossible
Aart Bikcc42be02016-10-20 16:14:16 -07002420 HInstruction* i = c->GetNext();
2421 if (i != nullptr && i->IsIf() && i->InputAt(0) == c) {
2422 iset_->insert(c);
2423 iset_->insert(s);
Aart Bikb29f6842017-07-28 15:58:41 -07002424 *main_phi = phi;
Aart Bikcc42be02016-10-20 16:14:16 -07002425 return true;
2426 }
2427 }
2428 }
2429 }
2430 return false;
2431}
2432
2433bool HLoopOptimization::IsEmptyBody(HBasicBlock* block) {
Aart Bikf8f5a162017-02-06 15:35:29 -08002434 if (!block->GetPhis().IsEmpty()) {
2435 return false;
2436 }
2437 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
2438 HInstruction* instruction = it.Current();
2439 if (!instruction->IsGoto() && iset_->find(instruction) == iset_->end()) {
2440 return false;
Aart Bikcc42be02016-10-20 16:14:16 -07002441 }
Aart Bikf8f5a162017-02-06 15:35:29 -08002442 }
2443 return true;
2444}
2445
2446bool HLoopOptimization::IsUsedOutsideLoop(HLoopInformation* loop_info,
2447 HInstruction* instruction) {
Aart Bikb29f6842017-07-28 15:58:41 -07002448 // Deal with regular uses.
Aart Bikf8f5a162017-02-06 15:35:29 -08002449 for (const HUseListNode<HInstruction*>& use : instruction->GetUses()) {
2450 if (use.GetUser()->GetBlock()->GetLoopInformation() != loop_info) {
2451 return true;
2452 }
Aart Bikcc42be02016-10-20 16:14:16 -07002453 }
2454 return false;
2455}
2456
Aart Bik482095d2016-10-10 15:39:10 -07002457bool HLoopOptimization::IsOnlyUsedAfterLoop(HLoopInformation* loop_info,
Aart Bik8c4a8542016-10-06 11:36:57 -07002458 HInstruction* instruction,
Aart Bik6b69e0a2017-01-11 10:20:43 -08002459 bool collect_loop_uses,
Aart Bik38a3f212017-10-20 17:02:21 -07002460 /*out*/ uint32_t* use_count) {
Aart Bikb29f6842017-07-28 15:58:41 -07002461 // Deal with regular uses.
Aart Bik8c4a8542016-10-06 11:36:57 -07002462 for (const HUseListNode<HInstruction*>& use : instruction->GetUses()) {
2463 HInstruction* user = use.GetUser();
2464 if (iset_->find(user) == iset_->end()) { // not excluded?
2465 HLoopInformation* other_loop_info = user->GetBlock()->GetLoopInformation();
Aart Bik482095d2016-10-10 15:39:10 -07002466 if (other_loop_info != nullptr && other_loop_info->IsIn(*loop_info)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -08002467 // If collect_loop_uses is set, simply keep adding those uses to the set.
2468 // Otherwise, reject uses inside the loop that were not already in the set.
2469 if (collect_loop_uses) {
2470 iset_->insert(user);
2471 continue;
2472 }
Aart Bik8c4a8542016-10-06 11:36:57 -07002473 return false;
2474 }
2475 ++*use_count;
2476 }
2477 }
2478 return true;
2479}
2480
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002481bool HLoopOptimization::TryReplaceWithLastValue(HLoopInformation* loop_info,
2482 HInstruction* instruction,
2483 HBasicBlock* block) {
2484 // Try to replace outside uses with the last value.
Aart Bik807868e2016-11-03 17:51:43 -07002485 if (induction_range_.CanGenerateLastValue(instruction)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -08002486 HInstruction* replacement = induction_range_.GenerateLastValue(instruction, graph_, block);
Aart Bikb29f6842017-07-28 15:58:41 -07002487 // Deal with regular uses.
Aart Bik6b69e0a2017-01-11 10:20:43 -08002488 const HUseList<HInstruction*>& uses = instruction->GetUses();
2489 for (auto it = uses.begin(), end = uses.end(); it != end;) {
2490 HInstruction* user = it->GetUser();
2491 size_t index = it->GetIndex();
2492 ++it; // increment before replacing
2493 if (iset_->find(user) == iset_->end()) { // not excluded?
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002494 if (kIsDebugBuild) {
2495 // We have checked earlier in 'IsOnlyUsedAfterLoop' that the use is after the loop.
2496 HLoopInformation* other_loop_info = user->GetBlock()->GetLoopInformation();
2497 CHECK(other_loop_info == nullptr || !other_loop_info->IsIn(*loop_info));
2498 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08002499 user->ReplaceInput(replacement, index);
2500 induction_range_.Replace(user, instruction, replacement); // update induction
2501 }
2502 }
Aart Bikb29f6842017-07-28 15:58:41 -07002503 // Deal with environment uses.
Aart Bik6b69e0a2017-01-11 10:20:43 -08002504 const HUseList<HEnvironment*>& env_uses = instruction->GetEnvUses();
2505 for (auto it = env_uses.begin(), end = env_uses.end(); it != end;) {
2506 HEnvironment* user = it->GetUser();
2507 size_t index = it->GetIndex();
2508 ++it; // increment before replacing
2509 if (iset_->find(user->GetHolder()) == iset_->end()) { // not excluded?
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002510 // Only update environment uses after the loop.
Aart Bik14a68b42017-06-08 14:06:58 -07002511 HLoopInformation* other_loop_info = user->GetHolder()->GetBlock()->GetLoopInformation();
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002512 if (other_loop_info == nullptr || !other_loop_info->IsIn(*loop_info)) {
2513 user->RemoveAsUserOfInput(index);
2514 user->SetRawEnvAt(index, replacement);
2515 replacement->AddEnvUseAt(user, index);
2516 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08002517 }
2518 }
Aart Bik807868e2016-11-03 17:51:43 -07002519 return true;
Aart Bik8c4a8542016-10-06 11:36:57 -07002520 }
Aart Bik807868e2016-11-03 17:51:43 -07002521 return false;
Aart Bik8c4a8542016-10-06 11:36:57 -07002522}
2523
Aart Bikf8f5a162017-02-06 15:35:29 -08002524bool HLoopOptimization::TryAssignLastValue(HLoopInformation* loop_info,
2525 HInstruction* instruction,
2526 HBasicBlock* block,
2527 bool collect_loop_uses) {
2528 // Assigning the last value is always successful if there are no uses.
2529 // Otherwise, it succeeds in a no early-exit loop by generating the
2530 // proper last value assignment.
Aart Bik38a3f212017-10-20 17:02:21 -07002531 uint32_t use_count = 0;
Aart Bikf8f5a162017-02-06 15:35:29 -08002532 return IsOnlyUsedAfterLoop(loop_info, instruction, collect_loop_uses, &use_count) &&
2533 (use_count == 0 ||
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002534 (!IsEarlyExit(loop_info) && TryReplaceWithLastValue(loop_info, instruction, block)));
Aart Bikf8f5a162017-02-06 15:35:29 -08002535}
2536
Aart Bik6b69e0a2017-01-11 10:20:43 -08002537void HLoopOptimization::RemoveDeadInstructions(const HInstructionList& list) {
2538 for (HBackwardInstructionIterator i(list); !i.Done(); i.Advance()) {
2539 HInstruction* instruction = i.Current();
2540 if (instruction->IsDeadAndRemovable()) {
2541 simplified_ = true;
2542 instruction->GetBlock()->RemoveInstructionOrPhi(instruction);
2543 }
2544 }
2545}
2546
Aart Bik14a68b42017-06-08 14:06:58 -07002547bool HLoopOptimization::CanRemoveCycle() {
2548 for (HInstruction* i : *iset_) {
2549 // We can never remove instructions that have environment
2550 // uses when we compile 'debuggable'.
2551 if (i->HasEnvironmentUses() && graph_->IsDebuggable()) {
2552 return false;
2553 }
2554 // A deoptimization should never have an environment input removed.
2555 for (const HUseListNode<HEnvironment*>& use : i->GetEnvUses()) {
2556 if (use.GetUser()->GetHolder()->IsDeoptimize()) {
2557 return false;
2558 }
2559 }
2560 }
2561 return true;
2562}
2563
Aart Bik281c6812016-08-26 11:31:48 -07002564} // namespace art