blob: 1462404932e48ed1af31c351fc6e818feed1d6b4 [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.
Artem Serov72411e62017-10-19 16:18:07 +010037static constexpr bool kEnableScalarPeelingUnrolling = false;
Aart Bik521b50f2017-09-09 10:44:45 -070038
Aart Bik38a3f212017-10-20 17:02:21 -070039//
40// Static helpers.
41//
42
43// Base alignment for arrays/strings guaranteed by the Android runtime.
44static uint32_t BaseAlignment() {
45 return kObjectAlignment;
46}
47
48// Hidden offset for arrays/strings guaranteed by the Android runtime.
49static uint32_t HiddenOffset(DataType::Type type, bool is_string_char_at) {
50 return is_string_char_at
51 ? mirror::String::ValueOffset().Uint32Value()
52 : mirror::Array::DataOffset(DataType::Size(type)).Uint32Value();
53}
54
Aart Bik9abf8942016-10-14 09:49:42 -070055// Remove the instruction from the graph. A bit more elaborate than the usual
56// instruction removal, since there may be a cycle in the use structure.
Aart Bik281c6812016-08-26 11:31:48 -070057static void RemoveFromCycle(HInstruction* instruction) {
Aart Bik281c6812016-08-26 11:31:48 -070058 instruction->RemoveAsUserOfAllInputs();
59 instruction->RemoveEnvironmentUsers();
60 instruction->GetBlock()->RemoveInstructionOrPhi(instruction, /*ensure_safety=*/ false);
Artem Serov21c7e6f2017-07-27 16:04:42 +010061 RemoveEnvironmentUses(instruction);
62 ResetEnvironmentInputRecords(instruction);
Aart Bik281c6812016-08-26 11:31:48 -070063}
64
Aart Bik807868e2016-11-03 17:51:43 -070065// Detect a goto block and sets succ to the single successor.
Aart Bike3dedc52016-11-02 17:50:27 -070066static bool IsGotoBlock(HBasicBlock* block, /*out*/ HBasicBlock** succ) {
67 if (block->GetPredecessors().size() == 1 &&
68 block->GetSuccessors().size() == 1 &&
69 block->IsSingleGoto()) {
70 *succ = block->GetSingleSuccessor();
71 return true;
72 }
73 return false;
74}
75
Aart Bik807868e2016-11-03 17:51:43 -070076// Detect an early exit loop.
77static bool IsEarlyExit(HLoopInformation* loop_info) {
78 HBlocksInLoopReversePostOrderIterator it_loop(*loop_info);
79 for (it_loop.Advance(); !it_loop.Done(); it_loop.Advance()) {
80 for (HBasicBlock* successor : it_loop.Current()->GetSuccessors()) {
81 if (!loop_info->Contains(*successor)) {
82 return true;
83 }
84 }
85 }
86 return false;
87}
88
Aart Bik68ca7022017-09-26 16:44:23 -070089// Forward declaration.
90static bool IsZeroExtensionAndGet(HInstruction* instruction,
91 DataType::Type type,
Aart Bikdf011c32017-09-28 12:53:04 -070092 /*out*/ HInstruction** operand);
Aart Bik68ca7022017-09-26 16:44:23 -070093
Aart Bikdf011c32017-09-28 12:53:04 -070094// Detect a sign extension in instruction from the given type.
Aart Bikdbbac8f2017-09-01 13:06:08 -070095// Returns the promoted operand on success.
Aart Bikf3e61ee2017-04-12 17:09:20 -070096static bool IsSignExtensionAndGet(HInstruction* instruction,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +010097 DataType::Type type,
Aart Bikdf011c32017-09-28 12:53:04 -070098 /*out*/ HInstruction** operand) {
Aart Bikf3e61ee2017-04-12 17:09:20 -070099 // Accept any already wider constant that would be handled properly by sign
100 // extension when represented in the *width* of the given narrower data type
Aart Bik4d1a9d42017-10-19 14:40:55 -0700101 // (the fact that Uint8/Uint16 normally zero extend does not matter here).
Aart Bikf3e61ee2017-04-12 17:09:20 -0700102 int64_t value = 0;
Aart Bik50e20d52017-05-05 14:07:29 -0700103 if (IsInt64AndGet(instruction, /*out*/ &value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700104 switch (type) {
Vladimir Markod5d2f2c2017-09-26 12:37:26 +0100105 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100106 case DataType::Type::kInt8:
Aart Bikdbbac8f2017-09-01 13:06:08 -0700107 if (IsInt<8>(value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700108 *operand = instruction;
109 return true;
110 }
111 return false;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100112 case DataType::Type::kUint16:
113 case DataType::Type::kInt16:
Aart Bikdbbac8f2017-09-01 13:06:08 -0700114 if (IsInt<16>(value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700115 *operand = instruction;
116 return true;
117 }
118 return false;
119 default:
120 return false;
121 }
122 }
Aart Bikdf011c32017-09-28 12:53:04 -0700123 // An implicit widening conversion of any signed expression sign-extends.
124 if (instruction->GetType() == type) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700125 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100126 case DataType::Type::kInt8:
127 case DataType::Type::kInt16:
Aart Bikf3e61ee2017-04-12 17:09:20 -0700128 *operand = instruction;
129 return true;
130 default:
131 return false;
132 }
133 }
Aart Bikdf011c32017-09-28 12:53:04 -0700134 // An explicit widening conversion of a signed expression sign-extends.
Aart Bik68ca7022017-09-26 16:44:23 -0700135 if (instruction->IsTypeConversion()) {
Aart Bikdf011c32017-09-28 12:53:04 -0700136 HInstruction* conv = instruction->InputAt(0);
137 DataType::Type from = conv->GetType();
Aart Bik68ca7022017-09-26 16:44:23 -0700138 switch (instruction->GetType()) {
Aart Bikdf011c32017-09-28 12:53:04 -0700139 case DataType::Type::kInt32:
Aart Bik68ca7022017-09-26 16:44:23 -0700140 case DataType::Type::kInt64:
Aart Bikdf011c32017-09-28 12:53:04 -0700141 if (type == from && (from == DataType::Type::kInt8 ||
142 from == DataType::Type::kInt16 ||
143 from == DataType::Type::kInt32)) {
144 *operand = conv;
145 return true;
146 }
147 return false;
Aart Bik68ca7022017-09-26 16:44:23 -0700148 case DataType::Type::kInt16:
149 return type == DataType::Type::kUint16 &&
150 from == DataType::Type::kUint16 &&
Aart Bikdf011c32017-09-28 12:53:04 -0700151 IsZeroExtensionAndGet(instruction->InputAt(0), type, /*out*/ operand);
Aart Bik68ca7022017-09-26 16:44:23 -0700152 default:
153 return false;
154 }
Aart Bikdbbac8f2017-09-01 13:06:08 -0700155 }
Aart Bik5aac9212018-04-03 14:06:43 -0700156 // A MIN-MAX on narrower operands qualifies as well
157 // (returning the operator itself).
158 if (instruction->IsMin() || instruction->IsMax()) {
159 HBinaryOperation* min_max = instruction->AsBinaryOperation();
160 DCHECK(min_max->GetType() == DataType::Type::kInt32 ||
161 min_max->GetType() == DataType::Type::kInt64);
162 if (IsSignExtensionAndGet(min_max->InputAt(0), type, operand) &&
163 IsSignExtensionAndGet(min_max->InputAt(1), type, operand)) {
164 *operand = min_max;
165 return true;
166 }
167 }
Aart Bikf3e61ee2017-04-12 17:09:20 -0700168 return false;
169}
170
Aart Bikdf011c32017-09-28 12:53:04 -0700171// Detect a zero extension in instruction from the given type.
Aart Bikdbbac8f2017-09-01 13:06:08 -0700172// Returns the promoted operand on success.
Aart Bikf3e61ee2017-04-12 17:09:20 -0700173static bool IsZeroExtensionAndGet(HInstruction* instruction,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100174 DataType::Type type,
Aart Bikdf011c32017-09-28 12:53:04 -0700175 /*out*/ HInstruction** operand) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700176 // Accept any already wider constant that would be handled properly by zero
177 // extension when represented in the *width* of the given narrower data type
Aart Bikdf011c32017-09-28 12:53:04 -0700178 // (the fact that Int8/Int16 normally sign extend does not matter here).
Aart Bikf3e61ee2017-04-12 17:09:20 -0700179 int64_t value = 0;
Aart Bik50e20d52017-05-05 14:07:29 -0700180 if (IsInt64AndGet(instruction, /*out*/ &value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700181 switch (type) {
Vladimir Markod5d2f2c2017-09-26 12:37:26 +0100182 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100183 case DataType::Type::kInt8:
Aart Bikdbbac8f2017-09-01 13:06:08 -0700184 if (IsUint<8>(value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700185 *operand = instruction;
186 return true;
187 }
188 return false;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100189 case DataType::Type::kUint16:
190 case DataType::Type::kInt16:
Aart Bikdbbac8f2017-09-01 13:06:08 -0700191 if (IsUint<16>(value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700192 *operand = instruction;
193 return true;
194 }
195 return false;
196 default:
197 return false;
198 }
199 }
Aart Bikdf011c32017-09-28 12:53:04 -0700200 // An implicit widening conversion of any unsigned expression zero-extends.
201 if (instruction->GetType() == type) {
Vladimir Markod5d2f2c2017-09-26 12:37:26 +0100202 switch (type) {
203 case DataType::Type::kUint8:
204 case DataType::Type::kUint16:
205 *operand = instruction;
206 return true;
207 default:
208 return false;
Aart Bikf3e61ee2017-04-12 17:09:20 -0700209 }
210 }
Aart Bikdf011c32017-09-28 12:53:04 -0700211 // An explicit widening conversion of an unsigned expression zero-extends.
Aart Bik68ca7022017-09-26 16:44:23 -0700212 if (instruction->IsTypeConversion()) {
Aart Bikdf011c32017-09-28 12:53:04 -0700213 HInstruction* conv = instruction->InputAt(0);
214 DataType::Type from = conv->GetType();
Aart Bik68ca7022017-09-26 16:44:23 -0700215 switch (instruction->GetType()) {
Aart Bikdf011c32017-09-28 12:53:04 -0700216 case DataType::Type::kInt32:
Aart Bik68ca7022017-09-26 16:44:23 -0700217 case DataType::Type::kInt64:
Aart Bikdf011c32017-09-28 12:53:04 -0700218 if (type == from && from == DataType::Type::kUint16) {
219 *operand = conv;
220 return true;
221 }
222 return false;
Aart Bik68ca7022017-09-26 16:44:23 -0700223 case DataType::Type::kUint16:
224 return type == DataType::Type::kInt16 &&
225 from == DataType::Type::kInt16 &&
Aart Bikdf011c32017-09-28 12:53:04 -0700226 IsSignExtensionAndGet(instruction->InputAt(0), type, /*out*/ operand);
Aart Bik68ca7022017-09-26 16:44:23 -0700227 default:
228 return false;
229 }
Aart Bikdbbac8f2017-09-01 13:06:08 -0700230 }
Aart Bik5aac9212018-04-03 14:06:43 -0700231 // A MIN-MAX on narrower operands qualifies as well
232 // (returning the operator itself).
233 if (instruction->IsMin() || instruction->IsMax()) {
234 HBinaryOperation* min_max = instruction->AsBinaryOperation();
235 DCHECK(min_max->GetType() == DataType::Type::kInt32 ||
236 min_max->GetType() == DataType::Type::kInt64);
237 if (IsZeroExtensionAndGet(min_max->InputAt(0), type, operand) &&
238 IsZeroExtensionAndGet(min_max->InputAt(1), type, operand)) {
239 *operand = min_max;
240 return true;
241 }
242 }
Aart Bikf3e61ee2017-04-12 17:09:20 -0700243 return false;
244}
245
Aart Bik304c8a52017-05-23 11:01:13 -0700246// Detect situations with same-extension narrower operands.
247// Returns true on success and sets is_unsigned accordingly.
248static bool IsNarrowerOperands(HInstruction* a,
249 HInstruction* b,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100250 DataType::Type type,
Aart Bik304c8a52017-05-23 11:01:13 -0700251 /*out*/ HInstruction** r,
252 /*out*/ HInstruction** s,
253 /*out*/ bool* is_unsigned) {
Nicolas Geoffraya3e23262018-03-28 11:15:12 +0000254 DCHECK(a != nullptr && b != nullptr);
Aart Bik4d1a9d42017-10-19 14:40:55 -0700255 // Look for a matching sign extension.
256 DataType::Type stype = HVecOperation::ToSignedType(type);
257 if (IsSignExtensionAndGet(a, stype, r) && IsSignExtensionAndGet(b, stype, s)) {
Aart Bik304c8a52017-05-23 11:01:13 -0700258 *is_unsigned = false;
259 return true;
Aart Bik4d1a9d42017-10-19 14:40:55 -0700260 }
261 // Look for a matching zero extension.
262 DataType::Type utype = HVecOperation::ToUnsignedType(type);
263 if (IsZeroExtensionAndGet(a, utype, r) && IsZeroExtensionAndGet(b, utype, s)) {
Aart Bik304c8a52017-05-23 11:01:13 -0700264 *is_unsigned = true;
265 return true;
266 }
267 return false;
268}
269
270// As above, single operand.
271static bool IsNarrowerOperand(HInstruction* a,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100272 DataType::Type type,
Aart Bik304c8a52017-05-23 11:01:13 -0700273 /*out*/ HInstruction** r,
274 /*out*/ bool* is_unsigned) {
Nicolas Geoffraya3e23262018-03-28 11:15:12 +0000275 DCHECK(a != nullptr);
Aart Bik4d1a9d42017-10-19 14:40:55 -0700276 // Look for a matching sign extension.
277 DataType::Type stype = HVecOperation::ToSignedType(type);
278 if (IsSignExtensionAndGet(a, stype, r)) {
Aart Bik304c8a52017-05-23 11:01:13 -0700279 *is_unsigned = false;
280 return true;
Aart Bik4d1a9d42017-10-19 14:40:55 -0700281 }
282 // Look for a matching zero extension.
283 DataType::Type utype = HVecOperation::ToUnsignedType(type);
284 if (IsZeroExtensionAndGet(a, utype, r)) {
Aart Bik304c8a52017-05-23 11:01:13 -0700285 *is_unsigned = true;
286 return true;
287 }
288 return false;
289}
290
Aart Bikdbbac8f2017-09-01 13:06:08 -0700291// Compute relative vector length based on type difference.
Aart Bik38a3f212017-10-20 17:02:21 -0700292static uint32_t GetOtherVL(DataType::Type other_type, DataType::Type vector_type, uint32_t vl) {
Vladimir Markod5d2f2c2017-09-26 12:37:26 +0100293 DCHECK(DataType::IsIntegralType(other_type));
294 DCHECK(DataType::IsIntegralType(vector_type));
295 DCHECK_GE(DataType::SizeShift(other_type), DataType::SizeShift(vector_type));
296 return vl >> (DataType::SizeShift(other_type) - DataType::SizeShift(vector_type));
Aart Bikdbbac8f2017-09-01 13:06:08 -0700297}
298
Nicolas Geoffraya3e23262018-03-28 11:15:12 +0000299// Detect up to two added operands a and b and an acccumulated constant c.
300static bool IsAddConst(HInstruction* instruction,
301 /*out*/ HInstruction** a,
302 /*out*/ HInstruction** b,
303 /*out*/ int64_t* c,
304 int32_t depth = 8) { // don't search too deep
Aart Bik5f805002017-05-16 16:42:41 -0700305 int64_t value = 0;
Nicolas Geoffraya3e23262018-03-28 11:15:12 +0000306 // Enter add/sub while still within reasonable depth.
307 if (depth > 0) {
308 if (instruction->IsAdd()) {
309 return IsAddConst(instruction->InputAt(0), a, b, c, depth - 1) &&
310 IsAddConst(instruction->InputAt(1), a, b, c, depth - 1);
311 } else if (instruction->IsSub() &&
312 IsInt64AndGet(instruction->InputAt(1), &value)) {
313 *c -= value;
314 return IsAddConst(instruction->InputAt(0), a, b, c, depth - 1);
315 }
316 }
317 // Otherwise, deal with leaf nodes.
Aart Bik5f805002017-05-16 16:42:41 -0700318 if (IsInt64AndGet(instruction, &value)) {
319 *c += value;
320 return true;
Aart Bik5f805002017-05-16 16:42:41 -0700321 } else if (*a == nullptr) {
322 *a = instruction;
323 return true;
324 } else if (*b == nullptr) {
325 *b = instruction;
326 return true;
327 }
Nicolas Geoffraya3e23262018-03-28 11:15:12 +0000328 return false; // too many operands
Aart Bik5f805002017-05-16 16:42:41 -0700329}
330
Nicolas Geoffraya3e23262018-03-28 11:15:12 +0000331// Detect a + b + c with optional constant c.
332static bool IsAddConst2(HGraph* graph,
333 HInstruction* instruction,
334 /*out*/ HInstruction** a,
335 /*out*/ HInstruction** b,
336 /*out*/ int64_t* c) {
337 if (IsAddConst(instruction, a, b, c) && *a != nullptr) {
338 if (*b == nullptr) {
339 // Constant is usually already present, unless accumulated.
340 *b = graph->GetConstant(instruction->GetType(), (*c));
341 *c = 0;
Aart Bik5f805002017-05-16 16:42:41 -0700342 }
Aart Bik5f805002017-05-16 16:42:41 -0700343 return true;
344 }
345 return false;
346}
347
Nicolas Geoffraya3e23262018-03-28 11:15:12 +0000348// Detect a direct a - b or a hidden a - (-c).
349static bool IsSubConst2(HGraph* graph,
350 HInstruction* instruction,
351 /*out*/ HInstruction** a,
352 /*out*/ HInstruction** b) {
353 int64_t c = 0;
354 if (instruction->IsSub()) {
355 *a = instruction->InputAt(0);
356 *b = instruction->InputAt(1);
357 return true;
358 } else if (IsAddConst(instruction, a, b, &c) && *a != nullptr && *b == nullptr) {
359 // Constant for the hidden subtraction.
360 *b = graph->GetConstant(instruction->GetType(), -c);
361 return true;
Aart Bikdf011c32017-09-28 12:53:04 -0700362 }
363 return false;
364}
365
Aart Bik29aa0822018-03-08 11:28:00 -0800366// Detect clipped [lo, hi] range for nested MIN-MAX operations on a clippee,
367// such as MIN(hi, MAX(lo, clippee)) for an arbitrary clippee expression.
368// Example: MIN(10, MIN(20, MAX(0, x))) yields [0, 10] with clippee x.
Aart Bik1a381022018-03-15 15:51:37 -0700369static HInstruction* FindClippee(HInstruction* instruction,
370 /*out*/ int64_t* lo,
371 /*out*/ int64_t* hi) {
372 // Iterate into MIN(.., c)-MAX(.., c) expressions and 'tighten' the range [lo, hi].
373 while (instruction->IsMin() || instruction->IsMax()) {
374 HBinaryOperation* min_max = instruction->AsBinaryOperation();
375 DCHECK(min_max->GetType() == DataType::Type::kInt32 ||
376 min_max->GetType() == DataType::Type::kInt64);
377 // Process the constant.
378 HConstant* right = min_max->GetConstantRight();
379 if (right == nullptr) {
380 break;
381 } else if (instruction->IsMin()) {
382 *hi = std::min(*hi, Int64FromConstant(right));
383 } else {
384 *lo = std::max(*lo, Int64FromConstant(right));
Aart Bik29aa0822018-03-08 11:28:00 -0800385 }
Aart Bik1a381022018-03-15 15:51:37 -0700386 instruction = min_max->GetLeastConstantLeft();
Aart Bik29aa0822018-03-08 11:28:00 -0800387 }
Aart Bik1a381022018-03-15 15:51:37 -0700388 // Iteration ends in any other expression (possibly MIN/MAX without constant).
389 // This leaf expression is the clippee with range [lo, hi].
390 return instruction;
Aart Bik29aa0822018-03-08 11:28:00 -0800391}
392
Aart Bik5a392762018-03-16 10:27:44 -0700393// Set value range for type (or fail).
394static bool CanSetRange(DataType::Type type,
395 /*out*/ int64_t* uhi,
396 /*out*/ int64_t* slo,
397 /*out*/ int64_t* shi) {
Aart Bik29aa0822018-03-08 11:28:00 -0800398 if (DataType::Size(type) == 1) {
Aart Bik5a392762018-03-16 10:27:44 -0700399 *uhi = std::numeric_limits<uint8_t>::max();
400 *slo = std::numeric_limits<int8_t>::min();
401 *shi = std::numeric_limits<int8_t>::max();
402 return true;
Aart Bik29aa0822018-03-08 11:28:00 -0800403 } else if (DataType::Size(type) == 2) {
Aart Bik5a392762018-03-16 10:27:44 -0700404 *uhi = std::numeric_limits<uint16_t>::max();
405 *slo = std::numeric_limits<int16_t>::min();
406 *shi = std::numeric_limits<int16_t>::max();
407 return true;
Aart Bik29aa0822018-03-08 11:28:00 -0800408 }
409 return false;
410}
411
Aart Bik5a392762018-03-16 10:27:44 -0700412// Accept various saturated addition forms.
Nicolas Geoffraya3e23262018-03-28 11:15:12 +0000413static bool IsSaturatedAdd(HInstruction* a,
414 HInstruction* b,
Aart Bik5a392762018-03-16 10:27:44 -0700415 DataType::Type type,
416 int64_t lo,
417 int64_t hi,
418 bool is_unsigned) {
419 int64_t ulo = 0, uhi = 0, slo = 0, shi = 0;
420 if (!CanSetRange(type, &uhi, &slo, &shi)) {
421 return false;
Aart Bik29aa0822018-03-08 11:28:00 -0800422 }
Aart Bik5a392762018-03-16 10:27:44 -0700423 // Tighten the range for signed single clipping on constant.
424 if (!is_unsigned) {
425 int64_t c = 0;
Nicolas Geoffraya3e23262018-03-28 11:15:12 +0000426 if (IsInt64AndGet(a, &c) || IsInt64AndGet(b, &c)) {
Aart Bik5a392762018-03-16 10:27:44 -0700427 // For c in proper range and narrower operand r:
428 // MIN(r + c, 127) c > 0
429 // or MAX(r + c, -128) c < 0 (and possibly redundant bound).
430 if (0 < c && c <= shi && hi == shi) {
431 if (lo <= (slo + c)) {
432 return true;
433 }
434 } else if (slo <= c && c < 0 && lo == slo) {
435 if (hi >= (shi + c)) {
436 return true;
437 }
438 }
439 }
440 }
441 // Detect for narrower operands r and s:
442 // MIN(r + s, 255) => SAT_ADD_unsigned
443 // MAX(MIN(r + s, 127), -128) => SAT_ADD_signed.
444 return is_unsigned ? (lo <= ulo && hi == uhi) : (lo == slo && hi == shi);
445}
446
447// Accept various saturated subtraction forms.
Nicolas Geoffraya3e23262018-03-28 11:15:12 +0000448static bool IsSaturatedSub(HInstruction* a,
Aart Bik5a392762018-03-16 10:27:44 -0700449 DataType::Type type,
450 int64_t lo,
451 int64_t hi,
452 bool is_unsigned) {
453 int64_t ulo = 0, uhi = 0, slo = 0, shi = 0;
454 if (!CanSetRange(type, &uhi, &slo, &shi)) {
455 return false;
456 }
457 // Tighten the range for signed single clipping on constant.
458 if (!is_unsigned) {
459 int64_t c = 0;
Nicolas Geoffraya3e23262018-03-28 11:15:12 +0000460 if (IsInt64AndGet(a, /*out*/ &c)) {
Aart Bik5a392762018-03-16 10:27:44 -0700461 // For c in proper range and narrower operand r:
462 // MIN(c - r, 127) c > 0
463 // or MAX(c - r, -128) c < 0 (and possibly redundant bound).
464 if (0 < c && c <= shi && hi == shi) {
465 if (lo <= (c - shi)) {
466 return true;
467 }
468 } else if (slo <= c && c < 0 && lo == slo) {
469 if (hi >= (c - slo)) {
470 return true;
471 }
472 }
473 }
474 }
475 // Detect for narrower operands r and s:
476 // MAX(r - s, 0) => SAT_SUB_unsigned
477 // MIN(MAX(r - s, -128), 127) => SAT_ADD_signed.
478 return is_unsigned ? (lo == ulo && hi >= uhi) : (lo == slo && hi == shi);
Aart Bik29aa0822018-03-08 11:28:00 -0800479}
480
Aart Bikb29f6842017-07-28 15:58:41 -0700481// Detect reductions of the following forms,
Aart Bikb29f6842017-07-28 15:58:41 -0700482// x = x_phi + ..
483// x = x_phi - ..
Aart Bikb29f6842017-07-28 15:58:41 -0700484// x = min(x_phi, ..)
Aart Bik1f8d51b2018-02-15 10:42:37 -0800485// x = max(x_phi, ..)
Aart Bikb29f6842017-07-28 15:58:41 -0700486static bool HasReductionFormat(HInstruction* reduction, HInstruction* phi) {
Aart Bik1f8d51b2018-02-15 10:42:37 -0800487 if (reduction->IsAdd() || reduction->IsMin() || reduction->IsMax()) {
Aart Bikdbbac8f2017-09-01 13:06:08 -0700488 return (reduction->InputAt(0) == phi && reduction->InputAt(1) != phi) ||
489 (reduction->InputAt(0) != phi && reduction->InputAt(1) == phi);
Aart Bikb29f6842017-07-28 15:58:41 -0700490 } else if (reduction->IsSub()) {
Aart Bikdbbac8f2017-09-01 13:06:08 -0700491 return (reduction->InputAt(0) == phi && reduction->InputAt(1) != phi);
Aart Bikb29f6842017-07-28 15:58:41 -0700492 }
493 return false;
494}
495
Aart Bikdbbac8f2017-09-01 13:06:08 -0700496// Translates vector operation to reduction kind.
497static HVecReduce::ReductionKind GetReductionKind(HVecOperation* reduction) {
498 if (reduction->IsVecAdd() || reduction->IsVecSub() || reduction->IsVecSADAccumulate()) {
Aart Bik0148de42017-09-05 09:25:01 -0700499 return HVecReduce::kSum;
500 } else if (reduction->IsVecMin()) {
501 return HVecReduce::kMin;
502 } else if (reduction->IsVecMax()) {
503 return HVecReduce::kMax;
504 }
Aart Bik38a3f212017-10-20 17:02:21 -0700505 LOG(FATAL) << "Unsupported SIMD reduction " << reduction->GetId();
Aart Bik0148de42017-09-05 09:25:01 -0700506 UNREACHABLE();
507}
508
Aart Bikf8f5a162017-02-06 15:35:29 -0800509// Test vector restrictions.
510static bool HasVectorRestrictions(uint64_t restrictions, uint64_t tested) {
511 return (restrictions & tested) != 0;
512}
513
Aart Bikf3e61ee2017-04-12 17:09:20 -0700514// Insert an instruction.
Aart Bikf8f5a162017-02-06 15:35:29 -0800515static HInstruction* Insert(HBasicBlock* block, HInstruction* instruction) {
516 DCHECK(block != nullptr);
517 DCHECK(instruction != nullptr);
518 block->InsertInstructionBefore(instruction, block->GetLastInstruction());
519 return instruction;
520}
521
Artem Serov21c7e6f2017-07-27 16:04:42 +0100522// Check that instructions from the induction sets are fully removed: have no uses
523// and no other instructions use them.
Vladimir Markoca6fff82017-10-03 14:49:14 +0100524static bool CheckInductionSetFullyRemoved(ScopedArenaSet<HInstruction*>* iset) {
Artem Serov21c7e6f2017-07-27 16:04:42 +0100525 for (HInstruction* instr : *iset) {
526 if (instr->GetBlock() != nullptr ||
527 !instr->GetUses().empty() ||
528 !instr->GetEnvUses().empty() ||
529 HasEnvironmentUsedByOthers(instr)) {
530 return false;
531 }
532 }
Artem Serov21c7e6f2017-07-27 16:04:42 +0100533 return true;
534}
535
Artem Serov72411e62017-10-19 16:18:07 +0100536// Tries to statically evaluate condition of the specified "HIf" for other condition checks.
537static void TryToEvaluateIfCondition(HIf* instruction, HGraph* graph) {
538 HInstruction* cond = instruction->InputAt(0);
539
540 // If a condition 'cond' is evaluated in an HIf instruction then in the successors of the
541 // IF_BLOCK we statically know the value of the condition 'cond' (TRUE in TRUE_SUCC, FALSE in
542 // FALSE_SUCC). Using that we can replace another evaluation (use) EVAL of the same 'cond'
543 // with TRUE value (FALSE value) if every path from the ENTRY_BLOCK to EVAL_BLOCK contains the
544 // edge HIF_BLOCK->TRUE_SUCC (HIF_BLOCK->FALSE_SUCC).
545 // if (cond) { if(cond) {
546 // if (cond) {} if (1) {}
547 // } else { =======> } else {
548 // if (cond) {} if (0) {}
549 // } }
550 if (!cond->IsConstant()) {
551 HBasicBlock* true_succ = instruction->IfTrueSuccessor();
552 HBasicBlock* false_succ = instruction->IfFalseSuccessor();
553
554 DCHECK_EQ(true_succ->GetPredecessors().size(), 1u);
555 DCHECK_EQ(false_succ->GetPredecessors().size(), 1u);
556
557 const HUseList<HInstruction*>& uses = cond->GetUses();
558 for (auto it = uses.begin(), end = uses.end(); it != end; /* ++it below */) {
559 HInstruction* user = it->GetUser();
560 size_t index = it->GetIndex();
561 HBasicBlock* user_block = user->GetBlock();
562 // Increment `it` now because `*it` may disappear thanks to user->ReplaceInput().
563 ++it;
564 if (true_succ->Dominates(user_block)) {
565 user->ReplaceInput(graph->GetIntConstant(1), index);
566 } else if (false_succ->Dominates(user_block)) {
567 user->ReplaceInput(graph->GetIntConstant(0), index);
568 }
569 }
570 }
571}
572
Aart Bik281c6812016-08-26 11:31:48 -0700573//
Aart Bikb29f6842017-07-28 15:58:41 -0700574// Public methods.
Aart Bik281c6812016-08-26 11:31:48 -0700575//
576
577HLoopOptimization::HLoopOptimization(HGraph* graph,
Aart Bik92685a82017-03-06 11:13:43 -0800578 CompilerDriver* compiler_driver,
Aart Bikb92cc332017-09-06 15:53:17 -0700579 HInductionVarAnalysis* induction_analysis,
Aart Bik2ca10eb2017-11-15 15:17:53 -0800580 OptimizingCompilerStats* stats,
581 const char* name)
582 : HOptimization(graph, name, stats),
Aart Bik92685a82017-03-06 11:13:43 -0800583 compiler_driver_(compiler_driver),
Aart Bik281c6812016-08-26 11:31:48 -0700584 induction_range_(induction_analysis),
Aart Bik96202302016-10-04 17:33:56 -0700585 loop_allocator_(nullptr),
Vladimir Markoca6fff82017-10-03 14:49:14 +0100586 global_allocator_(graph_->GetAllocator()),
Aart Bik281c6812016-08-26 11:31:48 -0700587 top_loop_(nullptr),
Aart Bik8c4a8542016-10-06 11:36:57 -0700588 last_loop_(nullptr),
Aart Bik482095d2016-10-10 15:39:10 -0700589 iset_(nullptr),
Aart Bikb29f6842017-07-28 15:58:41 -0700590 reductions_(nullptr),
Aart Bikf8f5a162017-02-06 15:35:29 -0800591 simplified_(false),
592 vector_length_(0),
593 vector_refs_(nullptr),
Aart Bik38a3f212017-10-20 17:02:21 -0700594 vector_static_peeling_factor_(0),
595 vector_dynamic_peeling_candidate_(nullptr),
Aart Bik14a68b42017-06-08 14:06:58 -0700596 vector_runtime_test_a_(nullptr),
597 vector_runtime_test_b_(nullptr),
Aart Bik0148de42017-09-05 09:25:01 -0700598 vector_map_(nullptr),
Vladimir Markoca6fff82017-10-03 14:49:14 +0100599 vector_permanent_map_(nullptr),
600 vector_mode_(kSequential),
601 vector_preheader_(nullptr),
602 vector_header_(nullptr),
603 vector_body_(nullptr),
Artem Serov121f2032017-10-23 19:19:06 +0100604 vector_index_(nullptr),
605 arch_loop_helper_(ArchDefaultLoopHelper::Create(compiler_driver_ != nullptr
606 ? compiler_driver_->GetInstructionSet()
607 : InstructionSet::kNone,
608 global_allocator_)) {
Aart Bik281c6812016-08-26 11:31:48 -0700609}
610
611void HLoopOptimization::Run() {
Mingyao Yang01b47b02017-02-03 12:09:57 -0800612 // Skip if there is no loop or the graph has try-catch/irreducible loops.
Aart Bik281c6812016-08-26 11:31:48 -0700613 // TODO: make this less of a sledgehammer.
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800614 if (!graph_->HasLoops() || graph_->HasTryCatch() || graph_->HasIrreducibleLoops()) {
Aart Bik281c6812016-08-26 11:31:48 -0700615 return;
616 }
617
Vladimir Markoca6fff82017-10-03 14:49:14 +0100618 // Phase-local allocator.
619 ScopedArenaAllocator allocator(graph_->GetArenaStack());
Aart Bik96202302016-10-04 17:33:56 -0700620 loop_allocator_ = &allocator;
Nicolas Geoffrayebe16742016-10-05 09:55:42 +0100621
Aart Bik96202302016-10-04 17:33:56 -0700622 // Perform loop optimizations.
623 LocalRun();
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800624 if (top_loop_ == nullptr) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800625 graph_->SetHasLoops(false); // no more loops
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800626 }
627
Aart Bik96202302016-10-04 17:33:56 -0700628 // Detach.
629 loop_allocator_ = nullptr;
630 last_loop_ = top_loop_ = nullptr;
631}
632
Aart Bikb29f6842017-07-28 15:58:41 -0700633//
634// Loop setup and traversal.
635//
636
Aart Bik96202302016-10-04 17:33:56 -0700637void HLoopOptimization::LocalRun() {
638 // Build the linear order using the phase-local allocator. This step enables building
639 // a loop hierarchy that properly reflects the outer-inner and previous-next relation.
Vladimir Markoca6fff82017-10-03 14:49:14 +0100640 ScopedArenaVector<HBasicBlock*> linear_order(loop_allocator_->Adapter(kArenaAllocLinearOrder));
641 LinearizeGraph(graph_, &linear_order);
Aart Bik96202302016-10-04 17:33:56 -0700642
Aart Bik281c6812016-08-26 11:31:48 -0700643 // Build the loop hierarchy.
Aart Bik96202302016-10-04 17:33:56 -0700644 for (HBasicBlock* block : linear_order) {
Aart Bik281c6812016-08-26 11:31:48 -0700645 if (block->IsLoopHeader()) {
646 AddLoop(block->GetLoopInformation());
647 }
648 }
Aart Bik96202302016-10-04 17:33:56 -0700649
Aart Bik8c4a8542016-10-06 11:36:57 -0700650 // Traverse the loop hierarchy inner-to-outer and optimize. Traversal can use
Aart Bikf8f5a162017-02-06 15:35:29 -0800651 // temporary data structures using the phase-local allocator. All new HIR
652 // should use the global allocator.
Aart Bik8c4a8542016-10-06 11:36:57 -0700653 if (top_loop_ != nullptr) {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100654 ScopedArenaSet<HInstruction*> iset(loop_allocator_->Adapter(kArenaAllocLoopOptimization));
655 ScopedArenaSafeMap<HInstruction*, HInstruction*> reds(
Aart Bikb29f6842017-07-28 15:58:41 -0700656 std::less<HInstruction*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
Vladimir Markoca6fff82017-10-03 14:49:14 +0100657 ScopedArenaSet<ArrayReference> refs(loop_allocator_->Adapter(kArenaAllocLoopOptimization));
658 ScopedArenaSafeMap<HInstruction*, HInstruction*> map(
Aart Bikf8f5a162017-02-06 15:35:29 -0800659 std::less<HInstruction*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
Vladimir Markoca6fff82017-10-03 14:49:14 +0100660 ScopedArenaSafeMap<HInstruction*, HInstruction*> perm(
Aart Bik0148de42017-09-05 09:25:01 -0700661 std::less<HInstruction*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
Aart Bikf8f5a162017-02-06 15:35:29 -0800662 // Attach.
Aart Bik8c4a8542016-10-06 11:36:57 -0700663 iset_ = &iset;
Aart Bikb29f6842017-07-28 15:58:41 -0700664 reductions_ = &reds;
Aart Bikf8f5a162017-02-06 15:35:29 -0800665 vector_refs_ = &refs;
666 vector_map_ = &map;
Aart Bik0148de42017-09-05 09:25:01 -0700667 vector_permanent_map_ = &perm;
Aart Bikf8f5a162017-02-06 15:35:29 -0800668 // Traverse.
Aart Bik8c4a8542016-10-06 11:36:57 -0700669 TraverseLoopsInnerToOuter(top_loop_);
Aart Bikf8f5a162017-02-06 15:35:29 -0800670 // Detach.
671 iset_ = nullptr;
Aart Bikb29f6842017-07-28 15:58:41 -0700672 reductions_ = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800673 vector_refs_ = nullptr;
674 vector_map_ = nullptr;
Aart Bik0148de42017-09-05 09:25:01 -0700675 vector_permanent_map_ = nullptr;
Aart Bik8c4a8542016-10-06 11:36:57 -0700676 }
Aart Bik281c6812016-08-26 11:31:48 -0700677}
678
679void HLoopOptimization::AddLoop(HLoopInformation* loop_info) {
680 DCHECK(loop_info != nullptr);
Aart Bikf8f5a162017-02-06 15:35:29 -0800681 LoopNode* node = new (loop_allocator_) LoopNode(loop_info);
Aart Bik281c6812016-08-26 11:31:48 -0700682 if (last_loop_ == nullptr) {
683 // First loop.
684 DCHECK(top_loop_ == nullptr);
685 last_loop_ = top_loop_ = node;
686 } else if (loop_info->IsIn(*last_loop_->loop_info)) {
687 // Inner loop.
688 node->outer = last_loop_;
689 DCHECK(last_loop_->inner == nullptr);
690 last_loop_ = last_loop_->inner = node;
691 } else {
692 // Subsequent loop.
693 while (last_loop_->outer != nullptr && !loop_info->IsIn(*last_loop_->outer->loop_info)) {
694 last_loop_ = last_loop_->outer;
695 }
696 node->outer = last_loop_->outer;
697 node->previous = last_loop_;
698 DCHECK(last_loop_->next == nullptr);
699 last_loop_ = last_loop_->next = node;
700 }
701}
702
703void HLoopOptimization::RemoveLoop(LoopNode* node) {
704 DCHECK(node != nullptr);
Aart Bik8c4a8542016-10-06 11:36:57 -0700705 DCHECK(node->inner == nullptr);
706 if (node->previous != nullptr) {
707 // Within sequence.
708 node->previous->next = node->next;
709 if (node->next != nullptr) {
710 node->next->previous = node->previous;
711 }
712 } else {
713 // First of sequence.
714 if (node->outer != nullptr) {
715 node->outer->inner = node->next;
716 } else {
717 top_loop_ = node->next;
718 }
719 if (node->next != nullptr) {
720 node->next->outer = node->outer;
721 node->next->previous = nullptr;
722 }
723 }
Aart Bik281c6812016-08-26 11:31:48 -0700724}
725
Aart Bikb29f6842017-07-28 15:58:41 -0700726bool HLoopOptimization::TraverseLoopsInnerToOuter(LoopNode* node) {
727 bool changed = false;
Aart Bik281c6812016-08-26 11:31:48 -0700728 for ( ; node != nullptr; node = node->next) {
Aart Bikb29f6842017-07-28 15:58:41 -0700729 // Visit inner loops first. Recompute induction information for this
730 // loop if the induction of any inner loop has changed.
731 if (TraverseLoopsInnerToOuter(node->inner)) {
Aart Bik482095d2016-10-10 15:39:10 -0700732 induction_range_.ReVisit(node->loop_info);
733 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800734 // Repeat simplifications in the loop-body until no more changes occur.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800735 // Note that since each simplification consists of eliminating code (without
736 // introducing new code), this process is always finite.
Aart Bikdf7822e2016-12-06 10:05:30 -0800737 do {
738 simplified_ = false;
Aart Bikdf7822e2016-12-06 10:05:30 -0800739 SimplifyInduction(node);
Aart Bik6b69e0a2017-01-11 10:20:43 -0800740 SimplifyBlocks(node);
Aart Bikb29f6842017-07-28 15:58:41 -0700741 changed = simplified_ || changed;
Aart Bikdf7822e2016-12-06 10:05:30 -0800742 } while (simplified_);
Aart Bikf8f5a162017-02-06 15:35:29 -0800743 // Optimize inner loop.
Aart Bik9abf8942016-10-14 09:49:42 -0700744 if (node->inner == nullptr) {
Aart Bikb29f6842017-07-28 15:58:41 -0700745 changed = OptimizeInnerLoop(node) || changed;
Aart Bik9abf8942016-10-14 09:49:42 -0700746 }
Aart Bik281c6812016-08-26 11:31:48 -0700747 }
Aart Bikb29f6842017-07-28 15:58:41 -0700748 return changed;
Aart Bik281c6812016-08-26 11:31:48 -0700749}
750
Aart Bikf8f5a162017-02-06 15:35:29 -0800751//
752// Optimization.
753//
754
Aart Bik281c6812016-08-26 11:31:48 -0700755void HLoopOptimization::SimplifyInduction(LoopNode* node) {
756 HBasicBlock* header = node->loop_info->GetHeader();
757 HBasicBlock* preheader = node->loop_info->GetPreHeader();
Aart Bik8c4a8542016-10-06 11:36:57 -0700758 // Scan the phis in the header to find opportunities to simplify an induction
759 // cycle that is only used outside the loop. Replace these uses, if any, with
760 // the last value and remove the induction cycle.
761 // Examples: for (int i = 0; x != null; i++) { .... no i .... }
762 // for (int i = 0; i < 10; i++, k++) { .... no k .... } return k;
Aart Bik281c6812016-08-26 11:31:48 -0700763 for (HInstructionIterator it(header->GetPhis()); !it.Done(); it.Advance()) {
764 HPhi* phi = it.Current()->AsPhi();
Aart Bikf8f5a162017-02-06 15:35:29 -0800765 if (TrySetPhiInduction(phi, /*restrict_uses*/ true) &&
766 TryAssignLastValue(node->loop_info, phi, preheader, /*collect_loop_uses*/ false)) {
Aart Bik671e48a2017-08-09 13:16:56 -0700767 // Note that it's ok to have replaced uses after the loop with the last value, without
768 // being able to remove the cycle. Environment uses (which are the reason we may not be
769 // able to remove the cycle) within the loop will still hold the right value. We must
770 // have tried first, however, to replace outside uses.
771 if (CanRemoveCycle()) {
772 simplified_ = true;
773 for (HInstruction* i : *iset_) {
774 RemoveFromCycle(i);
775 }
776 DCHECK(CheckInductionSetFullyRemoved(iset_));
Aart Bik281c6812016-08-26 11:31:48 -0700777 }
Aart Bik482095d2016-10-10 15:39:10 -0700778 }
779 }
780}
781
782void HLoopOptimization::SimplifyBlocks(LoopNode* node) {
Aart Bikdf7822e2016-12-06 10:05:30 -0800783 // Iterate over all basic blocks in the loop-body.
784 for (HBlocksInLoopIterator it(*node->loop_info); !it.Done(); it.Advance()) {
785 HBasicBlock* block = it.Current();
786 // Remove dead instructions from the loop-body.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800787 RemoveDeadInstructions(block->GetPhis());
788 RemoveDeadInstructions(block->GetInstructions());
Aart Bikdf7822e2016-12-06 10:05:30 -0800789 // Remove trivial control flow blocks from the loop-body.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800790 if (block->GetPredecessors().size() == 1 &&
791 block->GetSuccessors().size() == 1 &&
792 block->GetSingleSuccessor()->GetPredecessors().size() == 1) {
Aart Bikdf7822e2016-12-06 10:05:30 -0800793 simplified_ = true;
Aart Bik6b69e0a2017-01-11 10:20:43 -0800794 block->MergeWith(block->GetSingleSuccessor());
Aart Bikdf7822e2016-12-06 10:05:30 -0800795 } else if (block->GetSuccessors().size() == 2) {
796 // Trivial if block can be bypassed to either branch.
797 HBasicBlock* succ0 = block->GetSuccessors()[0];
798 HBasicBlock* succ1 = block->GetSuccessors()[1];
799 HBasicBlock* meet0 = nullptr;
800 HBasicBlock* meet1 = nullptr;
801 if (succ0 != succ1 &&
802 IsGotoBlock(succ0, &meet0) &&
803 IsGotoBlock(succ1, &meet1) &&
804 meet0 == meet1 && // meets again
805 meet0 != block && // no self-loop
806 meet0->GetPhis().IsEmpty()) { // not used for merging
807 simplified_ = true;
808 succ0->DisconnectAndDelete();
809 if (block->Dominates(meet0)) {
810 block->RemoveDominatedBlock(meet0);
811 succ1->AddDominatedBlock(meet0);
812 meet0->SetDominator(succ1);
Aart Bike3dedc52016-11-02 17:50:27 -0700813 }
Aart Bik482095d2016-10-10 15:39:10 -0700814 }
Aart Bik281c6812016-08-26 11:31:48 -0700815 }
Aart Bikdf7822e2016-12-06 10:05:30 -0800816 }
Aart Bik281c6812016-08-26 11:31:48 -0700817}
818
Artem Serov121f2032017-10-23 19:19:06 +0100819bool HLoopOptimization::TryOptimizeInnerLoopFinite(LoopNode* node) {
Aart Bik281c6812016-08-26 11:31:48 -0700820 HBasicBlock* header = node->loop_info->GetHeader();
821 HBasicBlock* preheader = node->loop_info->GetPreHeader();
Aart Bik9abf8942016-10-14 09:49:42 -0700822 // Ensure loop header logic is finite.
Aart Bikf8f5a162017-02-06 15:35:29 -0800823 int64_t trip_count = 0;
824 if (!induction_range_.IsFinite(node->loop_info, &trip_count)) {
Aart Bikb29f6842017-07-28 15:58:41 -0700825 return false;
Aart Bik9abf8942016-10-14 09:49:42 -0700826 }
Aart Bik281c6812016-08-26 11:31:48 -0700827 // Ensure there is only a single loop-body (besides the header).
828 HBasicBlock* body = nullptr;
829 for (HBlocksInLoopIterator it(*node->loop_info); !it.Done(); it.Advance()) {
830 if (it.Current() != header) {
831 if (body != nullptr) {
Aart Bikb29f6842017-07-28 15:58:41 -0700832 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700833 }
834 body = it.Current();
835 }
836 }
Andreas Gampef45d61c2017-06-07 10:29:33 -0700837 CHECK(body != nullptr);
Aart Bik281c6812016-08-26 11:31:48 -0700838 // Ensure there is only a single exit point.
839 if (header->GetSuccessors().size() != 2) {
Aart Bikb29f6842017-07-28 15:58:41 -0700840 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700841 }
842 HBasicBlock* exit = (header->GetSuccessors()[0] == body)
843 ? header->GetSuccessors()[1]
844 : header->GetSuccessors()[0];
Aart Bik8c4a8542016-10-06 11:36:57 -0700845 // Ensure exit can only be reached by exiting loop.
Aart Bik281c6812016-08-26 11:31:48 -0700846 if (exit->GetPredecessors().size() != 1) {
Aart Bikb29f6842017-07-28 15:58:41 -0700847 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700848 }
Aart Bik6b69e0a2017-01-11 10:20:43 -0800849 // Detect either an empty loop (no side effects other than plain iteration) or
850 // a trivial loop (just iterating once). Replace subsequent index uses, if any,
851 // with the last value and remove the loop, possibly after unrolling its body.
Aart Bikb29f6842017-07-28 15:58:41 -0700852 HPhi* main_phi = nullptr;
853 if (TrySetSimpleLoopHeader(header, &main_phi)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -0800854 bool is_empty = IsEmptyBody(body);
Aart Bikb29f6842017-07-28 15:58:41 -0700855 if (reductions_->empty() && // TODO: possible with some effort
856 (is_empty || trip_count == 1) &&
857 TryAssignLastValue(node->loop_info, main_phi, preheader, /*collect_loop_uses*/ true)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -0800858 if (!is_empty) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800859 // Unroll the loop-body, which sees initial value of the index.
Aart Bikb29f6842017-07-28 15:58:41 -0700860 main_phi->ReplaceWith(main_phi->InputAt(0));
Aart Bik6b69e0a2017-01-11 10:20:43 -0800861 preheader->MergeInstructionsWith(body);
862 }
863 body->DisconnectAndDelete();
864 exit->RemovePredecessor(header);
865 header->RemoveSuccessor(exit);
866 header->RemoveDominatedBlock(exit);
867 header->DisconnectAndDelete();
868 preheader->AddSuccessor(exit);
Aart Bikf8f5a162017-02-06 15:35:29 -0800869 preheader->AddInstruction(new (global_allocator_) HGoto());
Aart Bik6b69e0a2017-01-11 10:20:43 -0800870 preheader->AddDominatedBlock(exit);
871 exit->SetDominator(preheader);
872 RemoveLoop(node); // update hierarchy
Aart Bikb29f6842017-07-28 15:58:41 -0700873 return true;
Aart Bikf8f5a162017-02-06 15:35:29 -0800874 }
875 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800876 // Vectorize loop, if possible and valid.
Aart Bikb29f6842017-07-28 15:58:41 -0700877 if (kEnableVectorization &&
878 TrySetSimpleLoopHeader(header, &main_phi) &&
Aart Bikb29f6842017-07-28 15:58:41 -0700879 ShouldVectorize(node, body, trip_count) &&
880 TryAssignLastValue(node->loop_info, main_phi, preheader, /*collect_loop_uses*/ true)) {
881 Vectorize(node, body, exit, trip_count);
882 graph_->SetHasSIMD(true); // flag SIMD usage
Aart Bik21b85922017-09-06 13:29:16 -0700883 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorized);
Aart Bikb29f6842017-07-28 15:58:41 -0700884 return true;
Aart Bikf8f5a162017-02-06 15:35:29 -0800885 }
Aart Bikb29f6842017-07-28 15:58:41 -0700886 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -0800887}
888
Artem Serov121f2032017-10-23 19:19:06 +0100889bool HLoopOptimization::OptimizeInnerLoop(LoopNode* node) {
890 return TryOptimizeInnerLoopFinite(node) ||
Artem Serov72411e62017-10-19 16:18:07 +0100891 TryPeelingForLoopInvariantExitsElimination(node) ||
Artem Serov121f2032017-10-23 19:19:06 +0100892 TryUnrollingForBranchPenaltyReduction(node);
893}
894
Artem Serov121f2032017-10-23 19:19:06 +0100895
Artem Serov121f2032017-10-23 19:19:06 +0100896
897//
898// Loop unrolling: generic part methods.
899//
900
Artem Serov72411e62017-10-19 16:18:07 +0100901bool HLoopOptimization::TryUnrollingForBranchPenaltyReduction(LoopNode* node) {
Artem Serov121f2032017-10-23 19:19:06 +0100902 // Don't run peeling/unrolling if compiler_driver_ is nullptr (i.e., running under tests)
903 // as InstructionSet is needed.
Artem Serov72411e62017-10-19 16:18:07 +0100904 if (!kEnableScalarPeelingUnrolling || compiler_driver_ == nullptr) {
Artem Serov121f2032017-10-23 19:19:06 +0100905 return false;
906 }
907
Artem Serov72411e62017-10-19 16:18:07 +0100908 HLoopInformation* loop_info = node->loop_info;
Artem Serov121f2032017-10-23 19:19:06 +0100909 int64_t trip_count = 0;
910 // Only unroll loops with a known tripcount.
911 if (!induction_range_.HasKnownTripCount(loop_info, &trip_count)) {
912 return false;
913 }
914
915 uint32_t unrolling_factor = arch_loop_helper_->GetScalarUnrollingFactor(loop_info, trip_count);
916 if (unrolling_factor == kNoUnrollingFactor) {
917 return false;
918 }
919
920 LoopAnalysisInfo loop_analysis_info(loop_info);
921 LoopAnalysis::CalculateLoopBasicProperties(loop_info, &loop_analysis_info);
922
923 // Check "IsLoopClonable" last as it can be time-consuming.
Artem Serov72411e62017-10-19 16:18:07 +0100924 if (arch_loop_helper_->IsLoopTooBigForScalarPeelingUnrolling(&loop_analysis_info) ||
Artem Serov121f2032017-10-23 19:19:06 +0100925 (loop_analysis_info.GetNumberOfExits() > 1) ||
926 loop_analysis_info.HasInstructionsPreventingScalarUnrolling() ||
927 !PeelUnrollHelper::IsLoopClonable(loop_info)) {
928 return false;
929 }
930
931 // TODO: support other unrolling factors.
932 DCHECK_EQ(unrolling_factor, 2u);
933
934 // Perform unrolling.
Artem Serov72411e62017-10-19 16:18:07 +0100935 PeelUnrollSimpleHelper helper(loop_info);
936 helper.DoUnrolling();
Artem Serov121f2032017-10-23 19:19:06 +0100937
938 // Remove the redundant loop check after unrolling.
Artem Serov72411e62017-10-19 16:18:07 +0100939 HIf* copy_hif =
940 helper.GetBasicBlockMap()->Get(loop_info->GetHeader())->GetLastInstruction()->AsIf();
Artem Serov121f2032017-10-23 19:19:06 +0100941 int32_t constant = loop_info->Contains(*copy_hif->IfTrueSuccessor()) ? 1 : 0;
942 copy_hif->ReplaceInput(graph_->GetIntConstant(constant), 0u);
943
944 return true;
945}
946
Artem Serov72411e62017-10-19 16:18:07 +0100947bool HLoopOptimization::TryPeelingForLoopInvariantExitsElimination(LoopNode* node) {
948 // Don't run peeling/unrolling if compiler_driver_ is nullptr (i.e., running under tests)
949 // as InstructionSet is needed.
950 if (!kEnableScalarPeelingUnrolling || compiler_driver_ == nullptr) {
951 return false;
952 }
953
954 HLoopInformation* loop_info = node->loop_info;
955 // Check 'IsLoopClonable' the last as it might be time-consuming.
956 if (!arch_loop_helper_->IsLoopPeelingEnabled()) {
957 return false;
958 }
959
960 LoopAnalysisInfo loop_analysis_info(loop_info);
961 LoopAnalysis::CalculateLoopBasicProperties(loop_info, &loop_analysis_info);
962
963 // Check "IsLoopClonable" last as it can be time-consuming.
964 if (arch_loop_helper_->IsLoopTooBigForScalarPeelingUnrolling(&loop_analysis_info) ||
965 loop_analysis_info.HasInstructionsPreventingScalarPeeling() ||
966 !LoopAnalysis::HasLoopAtLeastOneInvariantExit(loop_info) ||
967 !PeelUnrollHelper::IsLoopClonable(loop_info)) {
968 return false;
969 }
970
971 // Perform peeling.
972 PeelUnrollSimpleHelper helper(loop_info);
973 helper.DoPeeling();
974
975 const SuperblockCloner::HInstructionMap* hir_map = helper.GetInstructionMap();
976 for (auto entry : *hir_map) {
977 HInstruction* copy = entry.second;
978 if (copy->IsIf()) {
979 TryToEvaluateIfCondition(copy->AsIf(), graph_);
980 }
981 }
982
983 return true;
984}
985
Aart Bikf8f5a162017-02-06 15:35:29 -0800986//
987// Loop vectorization. The implementation is based on the book by Aart J.C. Bik:
988// "The Software Vectorization Handbook. Applying Multimedia Extensions for Maximum Performance."
989// Intel Press, June, 2004 (http://www.aartbik.com/).
990//
991
Aart Bik14a68b42017-06-08 14:06:58 -0700992bool HLoopOptimization::ShouldVectorize(LoopNode* node, HBasicBlock* block, int64_t trip_count) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800993 // Reset vector bookkeeping.
994 vector_length_ = 0;
995 vector_refs_->clear();
Aart Bik38a3f212017-10-20 17:02:21 -0700996 vector_static_peeling_factor_ = 0;
997 vector_dynamic_peeling_candidate_ = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800998 vector_runtime_test_a_ =
Igor Murashkin2ffb7032017-11-08 13:35:21 -0800999 vector_runtime_test_b_ = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -08001000
1001 // Phis in the loop-body prevent vectorization.
1002 if (!block->GetPhis().IsEmpty()) {
1003 return false;
1004 }
1005
1006 // Scan the loop-body, starting a right-hand-side tree traversal at each left-hand-side
1007 // occurrence, which allows passing down attributes down the use tree.
1008 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
1009 if (!VectorizeDef(node, it.Current(), /*generate_code*/ false)) {
1010 return false; // failure to vectorize a left-hand-side
1011 }
1012 }
1013
Aart Bik38a3f212017-10-20 17:02:21 -07001014 // Prepare alignment analysis:
1015 // (1) find desired alignment (SIMD vector size in bytes).
1016 // (2) initialize static loop peeling votes (peeling factor that will
1017 // make one particular reference aligned), never to exceed (1).
1018 // (3) variable to record how many references share same alignment.
1019 // (4) variable to record suitable candidate for dynamic loop peeling.
1020 uint32_t desired_alignment = GetVectorSizeInBytes();
1021 DCHECK_LE(desired_alignment, 16u);
1022 uint32_t peeling_votes[16] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
1023 uint32_t max_num_same_alignment = 0;
1024 const ArrayReference* peeling_candidate = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -08001025
1026 // Data dependence analysis. Find each pair of references with same type, where
1027 // at least one is a write. Each such pair denotes a possible data dependence.
1028 // This analysis exploits the property that differently typed arrays cannot be
1029 // aliased, as well as the property that references either point to the same
1030 // array or to two completely disjoint arrays, i.e., no partial aliasing.
1031 // Other than a few simply heuristics, no detailed subscript analysis is done.
Aart Bik38a3f212017-10-20 17:02:21 -07001032 // The scan over references also prepares finding a suitable alignment strategy.
Aart Bikf8f5a162017-02-06 15:35:29 -08001033 for (auto i = vector_refs_->begin(); i != vector_refs_->end(); ++i) {
Aart Bik38a3f212017-10-20 17:02:21 -07001034 uint32_t num_same_alignment = 0;
1035 // Scan over all next references.
Aart Bikf8f5a162017-02-06 15:35:29 -08001036 for (auto j = i; ++j != vector_refs_->end(); ) {
1037 if (i->type == j->type && (i->lhs || j->lhs)) {
1038 // Found same-typed a[i+x] vs. b[i+y], where at least one is a write.
1039 HInstruction* a = i->base;
1040 HInstruction* b = j->base;
1041 HInstruction* x = i->offset;
1042 HInstruction* y = j->offset;
1043 if (a == b) {
1044 // Found a[i+x] vs. a[i+y]. Accept if x == y (loop-independent data dependence).
1045 // Conservatively assume a loop-carried data dependence otherwise, and reject.
1046 if (x != y) {
1047 return false;
1048 }
Aart Bik38a3f212017-10-20 17:02:21 -07001049 // Count the number of references that have the same alignment (since
1050 // base and offset are the same) and where at least one is a write, so
1051 // e.g. a[i] = a[i] + b[i] counts a[i] but not b[i]).
1052 num_same_alignment++;
Aart Bikf8f5a162017-02-06 15:35:29 -08001053 } else {
1054 // Found a[i+x] vs. b[i+y]. Accept if x == y (at worst loop-independent data dependence).
1055 // Conservatively assume a potential loop-carried data dependence otherwise, avoided by
1056 // generating an explicit a != b disambiguation runtime test on the two references.
1057 if (x != y) {
Aart Bik37dc4df2017-06-28 14:08:00 -07001058 // To avoid excessive overhead, we only accept one a != b test.
1059 if (vector_runtime_test_a_ == nullptr) {
1060 // First test found.
1061 vector_runtime_test_a_ = a;
1062 vector_runtime_test_b_ = b;
1063 } else if ((vector_runtime_test_a_ != a || vector_runtime_test_b_ != b) &&
1064 (vector_runtime_test_a_ != b || vector_runtime_test_b_ != a)) {
1065 return false; // second test would be needed
Aart Bikf8f5a162017-02-06 15:35:29 -08001066 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001067 }
1068 }
1069 }
1070 }
Aart Bik38a3f212017-10-20 17:02:21 -07001071 // Update information for finding suitable alignment strategy:
1072 // (1) update votes for static loop peeling,
1073 // (2) update suitable candidate for dynamic loop peeling.
1074 Alignment alignment = ComputeAlignment(i->offset, i->type, i->is_string_char_at);
1075 if (alignment.Base() >= desired_alignment) {
1076 // If the array/string object has a known, sufficient alignment, use the
1077 // initial offset to compute the static loop peeling vote (this always
1078 // works, since elements have natural alignment).
1079 uint32_t offset = alignment.Offset() & (desired_alignment - 1u);
1080 uint32_t vote = (offset == 0)
1081 ? 0
1082 : ((desired_alignment - offset) >> DataType::SizeShift(i->type));
1083 DCHECK_LT(vote, 16u);
1084 ++peeling_votes[vote];
1085 } else if (BaseAlignment() >= desired_alignment &&
1086 num_same_alignment > max_num_same_alignment) {
1087 // Otherwise, if the array/string object has a known, sufficient alignment
1088 // for just the base but with an unknown offset, record the candidate with
1089 // the most occurrences for dynamic loop peeling (again, the peeling always
1090 // works, since elements have natural alignment).
1091 max_num_same_alignment = num_same_alignment;
1092 peeling_candidate = &(*i);
1093 }
1094 } // for i
Aart Bikf8f5a162017-02-06 15:35:29 -08001095
Aart Bik38a3f212017-10-20 17:02:21 -07001096 // Find a suitable alignment strategy.
1097 SetAlignmentStrategy(peeling_votes, peeling_candidate);
1098
1099 // Does vectorization seem profitable?
1100 if (!IsVectorizationProfitable(trip_count)) {
1101 return false;
1102 }
Aart Bik14a68b42017-06-08 14:06:58 -07001103
Aart Bikf8f5a162017-02-06 15:35:29 -08001104 // Success!
1105 return true;
1106}
1107
1108void HLoopOptimization::Vectorize(LoopNode* node,
1109 HBasicBlock* block,
1110 HBasicBlock* exit,
1111 int64_t trip_count) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001112 HBasicBlock* header = node->loop_info->GetHeader();
1113 HBasicBlock* preheader = node->loop_info->GetPreHeader();
1114
Aart Bik14a68b42017-06-08 14:06:58 -07001115 // Pick a loop unrolling factor for the vector loop.
Artem Serov121f2032017-10-23 19:19:06 +01001116 uint32_t unroll = arch_loop_helper_->GetSIMDUnrollingFactor(
1117 block, trip_count, MaxNumberPeeled(), vector_length_);
Aart Bik14a68b42017-06-08 14:06:58 -07001118 uint32_t chunk = vector_length_ * unroll;
1119
Aart Bik38a3f212017-10-20 17:02:21 -07001120 DCHECK(trip_count == 0 || (trip_count >= MaxNumberPeeled() + chunk));
1121
Aart Bik14a68b42017-06-08 14:06:58 -07001122 // A cleanup loop is needed, at least, for any unknown trip count or
1123 // for a known trip count with remainder iterations after vectorization.
Aart Bik38a3f212017-10-20 17:02:21 -07001124 bool needs_cleanup = trip_count == 0 ||
1125 ((trip_count - vector_static_peeling_factor_) % chunk) != 0;
Aart Bikf8f5a162017-02-06 15:35:29 -08001126
1127 // Adjust vector bookkeeping.
Aart Bikb29f6842017-07-28 15:58:41 -07001128 HPhi* main_phi = nullptr;
1129 bool is_simple_loop_header = TrySetSimpleLoopHeader(header, &main_phi); // refills sets
Aart Bikf8f5a162017-02-06 15:35:29 -08001130 DCHECK(is_simple_loop_header);
Aart Bik14a68b42017-06-08 14:06:58 -07001131 vector_header_ = header;
1132 vector_body_ = block;
Aart Bikf8f5a162017-02-06 15:35:29 -08001133
Aart Bikdbbac8f2017-09-01 13:06:08 -07001134 // Loop induction type.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001135 DataType::Type induc_type = main_phi->GetType();
1136 DCHECK(induc_type == DataType::Type::kInt32 || induc_type == DataType::Type::kInt64)
1137 << induc_type;
Aart Bikdbbac8f2017-09-01 13:06:08 -07001138
Aart Bik38a3f212017-10-20 17:02:21 -07001139 // Generate the trip count for static or dynamic loop peeling, if needed:
1140 // ptc = <peeling factor>;
Aart Bik14a68b42017-06-08 14:06:58 -07001141 HInstruction* ptc = nullptr;
Aart Bik38a3f212017-10-20 17:02:21 -07001142 if (vector_static_peeling_factor_ != 0) {
1143 // Static loop peeling for SIMD alignment (using the most suitable
1144 // fixed peeling factor found during prior alignment analysis).
1145 DCHECK(vector_dynamic_peeling_candidate_ == nullptr);
1146 ptc = graph_->GetConstant(induc_type, vector_static_peeling_factor_);
1147 } else if (vector_dynamic_peeling_candidate_ != nullptr) {
1148 // Dynamic loop peeling for SIMD alignment (using the most suitable
1149 // candidate found during prior alignment analysis):
1150 // rem = offset % ALIGN; // adjusted as #elements
1151 // ptc = rem == 0 ? 0 : (ALIGN - rem);
1152 uint32_t shift = DataType::SizeShift(vector_dynamic_peeling_candidate_->type);
1153 uint32_t align = GetVectorSizeInBytes() >> shift;
1154 uint32_t hidden_offset = HiddenOffset(vector_dynamic_peeling_candidate_->type,
1155 vector_dynamic_peeling_candidate_->is_string_char_at);
1156 HInstruction* adjusted_offset = graph_->GetConstant(induc_type, hidden_offset >> shift);
1157 HInstruction* offset = Insert(preheader, new (global_allocator_) HAdd(
1158 induc_type, vector_dynamic_peeling_candidate_->offset, adjusted_offset));
1159 HInstruction* rem = Insert(preheader, new (global_allocator_) HAnd(
1160 induc_type, offset, graph_->GetConstant(induc_type, align - 1u)));
1161 HInstruction* sub = Insert(preheader, new (global_allocator_) HSub(
1162 induc_type, graph_->GetConstant(induc_type, align), rem));
1163 HInstruction* cond = Insert(preheader, new (global_allocator_) HEqual(
1164 rem, graph_->GetConstant(induc_type, 0)));
1165 ptc = Insert(preheader, new (global_allocator_) HSelect(
1166 cond, graph_->GetConstant(induc_type, 0), sub, kNoDexPc));
1167 needs_cleanup = true; // don't know the exact amount
Aart Bik14a68b42017-06-08 14:06:58 -07001168 }
1169
1170 // Generate loop control:
Aart Bikf8f5a162017-02-06 15:35:29 -08001171 // stc = <trip-count>;
Aart Bik38a3f212017-10-20 17:02:21 -07001172 // ptc = min(stc, ptc);
Aart Bik14a68b42017-06-08 14:06:58 -07001173 // vtc = stc - (stc - ptc) % chunk;
1174 // i = 0;
Aart Bikf8f5a162017-02-06 15:35:29 -08001175 HInstruction* stc = induction_range_.GenerateTripCount(node->loop_info, graph_, preheader);
1176 HInstruction* vtc = stc;
1177 if (needs_cleanup) {
Aart Bik14a68b42017-06-08 14:06:58 -07001178 DCHECK(IsPowerOfTwo(chunk));
1179 HInstruction* diff = stc;
1180 if (ptc != nullptr) {
Aart Bik38a3f212017-10-20 17:02:21 -07001181 if (trip_count == 0) {
1182 HInstruction* cond = Insert(preheader, new (global_allocator_) HAboveOrEqual(stc, ptc));
1183 ptc = Insert(preheader, new (global_allocator_) HSelect(cond, ptc, stc, kNoDexPc));
1184 }
Aart Bik14a68b42017-06-08 14:06:58 -07001185 diff = Insert(preheader, new (global_allocator_) HSub(induc_type, stc, ptc));
1186 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001187 HInstruction* rem = Insert(
1188 preheader, new (global_allocator_) HAnd(induc_type,
Aart Bik14a68b42017-06-08 14:06:58 -07001189 diff,
Aart Bikdbbac8f2017-09-01 13:06:08 -07001190 graph_->GetConstant(induc_type, chunk - 1)));
Aart Bikf8f5a162017-02-06 15:35:29 -08001191 vtc = Insert(preheader, new (global_allocator_) HSub(induc_type, stc, rem));
1192 }
Aart Bikdbbac8f2017-09-01 13:06:08 -07001193 vector_index_ = graph_->GetConstant(induc_type, 0);
Aart Bikf8f5a162017-02-06 15:35:29 -08001194
1195 // Generate runtime disambiguation test:
1196 // vtc = a != b ? vtc : 0;
1197 if (vector_runtime_test_a_ != nullptr) {
1198 HInstruction* rt = Insert(
1199 preheader,
1200 new (global_allocator_) HNotEqual(vector_runtime_test_a_, vector_runtime_test_b_));
1201 vtc = Insert(preheader,
Aart Bikdbbac8f2017-09-01 13:06:08 -07001202 new (global_allocator_)
1203 HSelect(rt, vtc, graph_->GetConstant(induc_type, 0), kNoDexPc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001204 needs_cleanup = true;
1205 }
1206
Aart Bik38a3f212017-10-20 17:02:21 -07001207 // Generate alignment peeling loop, if needed:
Aart Bik14a68b42017-06-08 14:06:58 -07001208 // for ( ; i < ptc; i += 1)
1209 // <loop-body>
Aart Bik38a3f212017-10-20 17:02:21 -07001210 //
1211 // NOTE: The alignment forced by the peeling loop is preserved even if data is
1212 // moved around during suspend checks, since all analysis was based on
1213 // nothing more than the Android runtime alignment conventions.
Aart Bik14a68b42017-06-08 14:06:58 -07001214 if (ptc != nullptr) {
1215 vector_mode_ = kSequential;
1216 GenerateNewLoop(node,
1217 block,
1218 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
1219 vector_index_,
1220 ptc,
Aart Bikdbbac8f2017-09-01 13:06:08 -07001221 graph_->GetConstant(induc_type, 1),
Aart Bik521b50f2017-09-09 10:44:45 -07001222 kNoUnrollingFactor);
Aart Bik14a68b42017-06-08 14:06:58 -07001223 }
1224
1225 // Generate vector loop, possibly further unrolled:
1226 // for ( ; i < vtc; i += chunk)
Aart Bikf8f5a162017-02-06 15:35:29 -08001227 // <vectorized-loop-body>
1228 vector_mode_ = kVector;
1229 GenerateNewLoop(node,
1230 block,
Aart Bik14a68b42017-06-08 14:06:58 -07001231 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
1232 vector_index_,
Aart Bikf8f5a162017-02-06 15:35:29 -08001233 vtc,
Aart Bikdbbac8f2017-09-01 13:06:08 -07001234 graph_->GetConstant(induc_type, vector_length_), // increment per unroll
Aart Bik14a68b42017-06-08 14:06:58 -07001235 unroll);
Aart Bikf8f5a162017-02-06 15:35:29 -08001236 HLoopInformation* vloop = vector_header_->GetLoopInformation();
1237
1238 // Generate cleanup loop, if needed:
1239 // for ( ; i < stc; i += 1)
1240 // <loop-body>
1241 if (needs_cleanup) {
1242 vector_mode_ = kSequential;
1243 GenerateNewLoop(node,
1244 block,
1245 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
Aart Bik14a68b42017-06-08 14:06:58 -07001246 vector_index_,
Aart Bikf8f5a162017-02-06 15:35:29 -08001247 stc,
Aart Bikdbbac8f2017-09-01 13:06:08 -07001248 graph_->GetConstant(induc_type, 1),
Aart Bik521b50f2017-09-09 10:44:45 -07001249 kNoUnrollingFactor);
Aart Bikf8f5a162017-02-06 15:35:29 -08001250 }
1251
Aart Bik0148de42017-09-05 09:25:01 -07001252 // Link reductions to their final uses.
1253 for (auto i = reductions_->begin(); i != reductions_->end(); ++i) {
1254 if (i->first->IsPhi()) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001255 HInstruction* phi = i->first;
1256 HInstruction* repl = ReduceAndExtractIfNeeded(i->second);
1257 // Deal with regular uses.
1258 for (const HUseListNode<HInstruction*>& use : phi->GetUses()) {
1259 induction_range_.Replace(use.GetUser(), phi, repl); // update induction use
1260 }
1261 phi->ReplaceWith(repl);
Aart Bik0148de42017-09-05 09:25:01 -07001262 }
1263 }
1264
Aart Bikf8f5a162017-02-06 15:35:29 -08001265 // Remove the original loop by disconnecting the body block
1266 // and removing all instructions from the header.
1267 block->DisconnectAndDelete();
1268 while (!header->GetFirstInstruction()->IsGoto()) {
1269 header->RemoveInstruction(header->GetFirstInstruction());
1270 }
Aart Bikb29f6842017-07-28 15:58:41 -07001271
Aart Bik14a68b42017-06-08 14:06:58 -07001272 // Update loop hierarchy: the old header now resides in the same outer loop
1273 // as the old preheader. Note that we don't bother putting sequential
1274 // loops back in the hierarchy at this point.
Aart Bikf8f5a162017-02-06 15:35:29 -08001275 header->SetLoopInformation(preheader->GetLoopInformation()); // outward
1276 node->loop_info = vloop;
1277}
1278
1279void HLoopOptimization::GenerateNewLoop(LoopNode* node,
1280 HBasicBlock* block,
1281 HBasicBlock* new_preheader,
1282 HInstruction* lo,
1283 HInstruction* hi,
Aart Bik14a68b42017-06-08 14:06:58 -07001284 HInstruction* step,
1285 uint32_t unroll) {
1286 DCHECK(unroll == 1 || vector_mode_ == kVector);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001287 DataType::Type induc_type = lo->GetType();
Aart Bikf8f5a162017-02-06 15:35:29 -08001288 // Prepare new loop.
Aart Bikf8f5a162017-02-06 15:35:29 -08001289 vector_preheader_ = new_preheader,
1290 vector_header_ = vector_preheader_->GetSingleSuccessor();
1291 vector_body_ = vector_header_->GetSuccessors()[1];
Aart Bik14a68b42017-06-08 14:06:58 -07001292 HPhi* phi = new (global_allocator_) HPhi(global_allocator_,
1293 kNoRegNumber,
1294 0,
1295 HPhi::ToPhiType(induc_type));
Aart Bikb07d1bc2017-04-05 10:03:15 -07001296 // Generate header and prepare body.
Aart Bikf8f5a162017-02-06 15:35:29 -08001297 // for (i = lo; i < hi; i += step)
1298 // <loop-body>
Aart Bik14a68b42017-06-08 14:06:58 -07001299 HInstruction* cond = new (global_allocator_) HAboveOrEqual(phi, hi);
1300 vector_header_->AddPhi(phi);
Aart Bikf8f5a162017-02-06 15:35:29 -08001301 vector_header_->AddInstruction(cond);
1302 vector_header_->AddInstruction(new (global_allocator_) HIf(cond));
Aart Bik14a68b42017-06-08 14:06:58 -07001303 vector_index_ = phi;
Aart Bik0148de42017-09-05 09:25:01 -07001304 vector_permanent_map_->clear(); // preserved over unrolling
Aart Bik14a68b42017-06-08 14:06:58 -07001305 for (uint32_t u = 0; u < unroll; u++) {
Aart Bik14a68b42017-06-08 14:06:58 -07001306 // Generate instruction map.
Aart Bik0148de42017-09-05 09:25:01 -07001307 vector_map_->clear();
Aart Bik14a68b42017-06-08 14:06:58 -07001308 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
1309 bool vectorized_def = VectorizeDef(node, it.Current(), /*generate_code*/ true);
1310 DCHECK(vectorized_def);
1311 }
1312 // Generate body from the instruction map, but in original program order.
1313 HEnvironment* env = vector_header_->GetFirstInstruction()->GetEnvironment();
1314 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
1315 auto i = vector_map_->find(it.Current());
1316 if (i != vector_map_->end() && !i->second->IsInBlock()) {
1317 Insert(vector_body_, i->second);
1318 // Deal with instructions that need an environment, such as the scalar intrinsics.
1319 if (i->second->NeedsEnvironment()) {
1320 i->second->CopyEnvironmentFromWithLoopPhiAdjustment(env, vector_header_);
1321 }
1322 }
1323 }
Aart Bik0148de42017-09-05 09:25:01 -07001324 // Generate the induction.
Aart Bik14a68b42017-06-08 14:06:58 -07001325 vector_index_ = new (global_allocator_) HAdd(induc_type, vector_index_, step);
1326 Insert(vector_body_, vector_index_);
Aart Bikf8f5a162017-02-06 15:35:29 -08001327 }
Aart Bik0148de42017-09-05 09:25:01 -07001328 // Finalize phi inputs for the reductions (if any).
1329 for (auto i = reductions_->begin(); i != reductions_->end(); ++i) {
1330 if (!i->first->IsPhi()) {
1331 DCHECK(i->second->IsPhi());
1332 GenerateVecReductionPhiInputs(i->second->AsPhi(), i->first);
1333 }
1334 }
Aart Bikb29f6842017-07-28 15:58:41 -07001335 // Finalize phi inputs for the loop index.
Aart Bik14a68b42017-06-08 14:06:58 -07001336 phi->AddInput(lo);
1337 phi->AddInput(vector_index_);
1338 vector_index_ = phi;
Aart Bikf8f5a162017-02-06 15:35:29 -08001339}
1340
Aart Bikf8f5a162017-02-06 15:35:29 -08001341bool HLoopOptimization::VectorizeDef(LoopNode* node,
1342 HInstruction* instruction,
1343 bool generate_code) {
1344 // Accept a left-hand-side array base[index] for
1345 // (1) supported vector type,
1346 // (2) loop-invariant base,
1347 // (3) unit stride index,
1348 // (4) vectorizable right-hand-side value.
1349 uint64_t restrictions = kNone;
1350 if (instruction->IsArraySet()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001351 DataType::Type type = instruction->AsArraySet()->GetComponentType();
Aart Bikf8f5a162017-02-06 15:35:29 -08001352 HInstruction* base = instruction->InputAt(0);
1353 HInstruction* index = instruction->InputAt(1);
1354 HInstruction* value = instruction->InputAt(2);
1355 HInstruction* offset = nullptr;
Aart Bik6d057002018-04-09 15:39:58 -07001356 // For narrow types, explicit type conversion may have been
1357 // optimized way, so set the no hi bits restriction here.
1358 if (DataType::Size(type) <= 2) {
1359 restrictions |= kNoHiBits;
1360 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001361 if (TrySetVectorType(type, &restrictions) &&
1362 node->loop_info->IsDefinedOutOfTheLoop(base) &&
Aart Bik37dc4df2017-06-28 14:08:00 -07001363 induction_range_.IsUnitStride(instruction, index, graph_, &offset) &&
Aart Bikf8f5a162017-02-06 15:35:29 -08001364 VectorizeUse(node, value, generate_code, type, restrictions)) {
1365 if (generate_code) {
1366 GenerateVecSub(index, offset);
Aart Bik14a68b42017-06-08 14:06:58 -07001367 GenerateVecMem(instruction, vector_map_->Get(index), vector_map_->Get(value), offset, type);
Aart Bikf8f5a162017-02-06 15:35:29 -08001368 } else {
1369 vector_refs_->insert(ArrayReference(base, offset, type, /*lhs*/ true));
1370 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08001371 return true;
1372 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001373 return false;
1374 }
Aart Bik0148de42017-09-05 09:25:01 -07001375 // Accept a left-hand-side reduction for
1376 // (1) supported vector type,
1377 // (2) vectorizable right-hand-side value.
1378 auto redit = reductions_->find(instruction);
1379 if (redit != reductions_->end()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001380 DataType::Type type = instruction->GetType();
Aart Bikdbbac8f2017-09-01 13:06:08 -07001381 // Recognize SAD idiom or direct reduction.
1382 if (VectorizeSADIdiom(node, instruction, generate_code, type, restrictions) ||
1383 (TrySetVectorType(type, &restrictions) &&
1384 VectorizeUse(node, instruction, generate_code, type, restrictions))) {
Aart Bik0148de42017-09-05 09:25:01 -07001385 if (generate_code) {
1386 HInstruction* new_red = vector_map_->Get(instruction);
1387 vector_permanent_map_->Put(new_red, vector_map_->Get(redit->second));
1388 vector_permanent_map_->Overwrite(redit->second, new_red);
1389 }
1390 return true;
1391 }
1392 return false;
1393 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001394 // Branch back okay.
1395 if (instruction->IsGoto()) {
1396 return true;
1397 }
1398 // Otherwise accept only expressions with no effects outside the immediate loop-body.
1399 // Note that actual uses are inspected during right-hand-side tree traversal.
1400 return !IsUsedOutsideLoop(node->loop_info, instruction) && !instruction->DoesAnyWrite();
1401}
1402
Aart Bikf8f5a162017-02-06 15:35:29 -08001403bool HLoopOptimization::VectorizeUse(LoopNode* node,
1404 HInstruction* instruction,
1405 bool generate_code,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001406 DataType::Type type,
Aart Bikf8f5a162017-02-06 15:35:29 -08001407 uint64_t restrictions) {
1408 // Accept anything for which code has already been generated.
1409 if (generate_code) {
1410 if (vector_map_->find(instruction) != vector_map_->end()) {
1411 return true;
1412 }
1413 }
1414 // Continue the right-hand-side tree traversal, passing in proper
1415 // types and vector restrictions along the way. During code generation,
1416 // all new nodes are drawn from the global allocator.
1417 if (node->loop_info->IsDefinedOutOfTheLoop(instruction)) {
1418 // Accept invariant use, using scalar expansion.
1419 if (generate_code) {
1420 GenerateVecInv(instruction, type);
1421 }
1422 return true;
1423 } else if (instruction->IsArrayGet()) {
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001424 // Deal with vector restrictions.
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001425 bool is_string_char_at = instruction->AsArrayGet()->IsStringCharAt();
1426 if (is_string_char_at && HasVectorRestrictions(restrictions, kNoStringCharAt)) {
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001427 return false;
1428 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001429 // Accept a right-hand-side array base[index] for
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001430 // (1) matching vector type (exact match or signed/unsigned integral type of the same size),
Aart Bikf8f5a162017-02-06 15:35:29 -08001431 // (2) loop-invariant base,
1432 // (3) unit stride index,
1433 // (4) vectorizable right-hand-side value.
1434 HInstruction* base = instruction->InputAt(0);
1435 HInstruction* index = instruction->InputAt(1);
1436 HInstruction* offset = nullptr;
Aart Bik46b6dbc2017-10-03 11:37:37 -07001437 if (HVecOperation::ToSignedType(type) == HVecOperation::ToSignedType(instruction->GetType()) &&
Aart Bikf8f5a162017-02-06 15:35:29 -08001438 node->loop_info->IsDefinedOutOfTheLoop(base) &&
Aart Bik37dc4df2017-06-28 14:08:00 -07001439 induction_range_.IsUnitStride(instruction, index, graph_, &offset)) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001440 if (generate_code) {
1441 GenerateVecSub(index, offset);
Aart Bik14a68b42017-06-08 14:06:58 -07001442 GenerateVecMem(instruction, vector_map_->Get(index), nullptr, offset, type);
Aart Bikf8f5a162017-02-06 15:35:29 -08001443 } else {
Aart Bik38a3f212017-10-20 17:02:21 -07001444 vector_refs_->insert(ArrayReference(base, offset, type, /*lhs*/ false, is_string_char_at));
Aart Bikf8f5a162017-02-06 15:35:29 -08001445 }
1446 return true;
1447 }
Aart Bik0148de42017-09-05 09:25:01 -07001448 } else if (instruction->IsPhi()) {
1449 // Accept particular phi operations.
1450 if (reductions_->find(instruction) != reductions_->end()) {
1451 // Deal with vector restrictions.
1452 if (HasVectorRestrictions(restrictions, kNoReduction)) {
1453 return false;
1454 }
1455 // Accept a reduction.
1456 if (generate_code) {
1457 GenerateVecReductionPhi(instruction->AsPhi());
1458 }
1459 return true;
1460 }
1461 // TODO: accept right-hand-side induction?
1462 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001463 } else if (instruction->IsTypeConversion()) {
1464 // Accept particular type conversions.
1465 HTypeConversion* conversion = instruction->AsTypeConversion();
1466 HInstruction* opa = conversion->InputAt(0);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001467 DataType::Type from = conversion->GetInputType();
1468 DataType::Type to = conversion->GetResultType();
1469 if (DataType::IsIntegralType(from) && DataType::IsIntegralType(to)) {
Aart Bik38a3f212017-10-20 17:02:21 -07001470 uint32_t size_vec = DataType::Size(type);
1471 uint32_t size_from = DataType::Size(from);
1472 uint32_t size_to = DataType::Size(to);
Aart Bikdbbac8f2017-09-01 13:06:08 -07001473 // Accept an integral conversion
1474 // (1a) narrowing into vector type, "wider" operations cannot bring in higher order bits, or
1475 // (1b) widening from at least vector type, and
1476 // (2) vectorizable operand.
1477 if ((size_to < size_from &&
1478 size_to == size_vec &&
1479 VectorizeUse(node, opa, generate_code, type, restrictions | kNoHiBits)) ||
1480 (size_to >= size_from &&
1481 size_from >= size_vec &&
Aart Bik4d1a9d42017-10-19 14:40:55 -07001482 VectorizeUse(node, opa, generate_code, type, restrictions))) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001483 if (generate_code) {
1484 if (vector_mode_ == kVector) {
1485 vector_map_->Put(instruction, vector_map_->Get(opa)); // operand pass-through
1486 } else {
1487 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1488 }
1489 }
1490 return true;
1491 }
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001492 } else if (to == DataType::Type::kFloat32 && from == DataType::Type::kInt32) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001493 DCHECK_EQ(to, type);
1494 // Accept int to float conversion for
1495 // (1) supported int,
1496 // (2) vectorizable operand.
1497 if (TrySetVectorType(from, &restrictions) &&
1498 VectorizeUse(node, opa, generate_code, from, restrictions)) {
1499 if (generate_code) {
1500 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1501 }
1502 return true;
1503 }
1504 }
1505 return false;
1506 } else if (instruction->IsNeg() || instruction->IsNot() || instruction->IsBooleanNot()) {
1507 // Accept unary operator for vectorizable operand.
1508 HInstruction* opa = instruction->InputAt(0);
1509 if (VectorizeUse(node, opa, generate_code, type, restrictions)) {
1510 if (generate_code) {
1511 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1512 }
1513 return true;
1514 }
1515 } else if (instruction->IsAdd() || instruction->IsSub() ||
1516 instruction->IsMul() || instruction->IsDiv() ||
1517 instruction->IsAnd() || instruction->IsOr() || instruction->IsXor()) {
1518 // Deal with vector restrictions.
1519 if ((instruction->IsMul() && HasVectorRestrictions(restrictions, kNoMul)) ||
1520 (instruction->IsDiv() && HasVectorRestrictions(restrictions, kNoDiv))) {
1521 return false;
1522 }
1523 // Accept binary operator for vectorizable operands.
1524 HInstruction* opa = instruction->InputAt(0);
1525 HInstruction* opb = instruction->InputAt(1);
1526 if (VectorizeUse(node, opa, generate_code, type, restrictions) &&
1527 VectorizeUse(node, opb, generate_code, type, restrictions)) {
1528 if (generate_code) {
1529 GenerateVecOp(instruction, vector_map_->Get(opa), vector_map_->Get(opb), type);
1530 }
1531 return true;
1532 }
1533 } else if (instruction->IsShl() || instruction->IsShr() || instruction->IsUShr()) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001534 // Recognize halving add idiom.
Aart Bikf3e61ee2017-04-12 17:09:20 -07001535 if (VectorizeHalvingAddIdiom(node, instruction, generate_code, type, restrictions)) {
1536 return true;
1537 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001538 // Deal with vector restrictions.
Aart Bik304c8a52017-05-23 11:01:13 -07001539 HInstruction* opa = instruction->InputAt(0);
1540 HInstruction* opb = instruction->InputAt(1);
1541 HInstruction* r = opa;
1542 bool is_unsigned = false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001543 if ((HasVectorRestrictions(restrictions, kNoShift)) ||
1544 (instruction->IsShr() && HasVectorRestrictions(restrictions, kNoShr))) {
1545 return false; // unsupported instruction
Aart Bik304c8a52017-05-23 11:01:13 -07001546 } else if (HasVectorRestrictions(restrictions, kNoHiBits)) {
1547 // Shifts right need extra care to account for higher order bits.
1548 // TODO: less likely shr/unsigned and ushr/signed can by flipping signess.
1549 if (instruction->IsShr() &&
1550 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || is_unsigned)) {
1551 return false; // reject, unless all operands are sign-extension narrower
1552 } else if (instruction->IsUShr() &&
1553 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || !is_unsigned)) {
1554 return false; // reject, unless all operands are zero-extension narrower
1555 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001556 }
1557 // Accept shift operator for vectorizable/invariant operands.
1558 // TODO: accept symbolic, albeit loop invariant shift factors.
Aart Bik304c8a52017-05-23 11:01:13 -07001559 DCHECK(r != nullptr);
1560 if (generate_code && vector_mode_ != kVector) { // de-idiom
1561 r = opa;
1562 }
Aart Bik50e20d52017-05-05 14:07:29 -07001563 int64_t distance = 0;
Aart Bik304c8a52017-05-23 11:01:13 -07001564 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
Aart Bik50e20d52017-05-05 14:07:29 -07001565 IsInt64AndGet(opb, /*out*/ &distance)) {
Aart Bik65ffd8e2017-05-01 16:50:45 -07001566 // Restrict shift distance to packed data type width.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001567 int64_t max_distance = DataType::Size(type) * 8;
Aart Bik65ffd8e2017-05-01 16:50:45 -07001568 if (0 <= distance && distance < max_distance) {
1569 if (generate_code) {
Aart Bik304c8a52017-05-23 11:01:13 -07001570 GenerateVecOp(instruction, vector_map_->Get(r), opb, type);
Aart Bik65ffd8e2017-05-01 16:50:45 -07001571 }
1572 return true;
Aart Bikf8f5a162017-02-06 15:35:29 -08001573 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001574 }
Aart Bik3b2a5952018-03-05 13:55:28 -08001575 } else if (instruction->IsAbs()) {
1576 // Deal with vector restrictions.
1577 HInstruction* opa = instruction->InputAt(0);
1578 HInstruction* r = opa;
1579 bool is_unsigned = false;
1580 if (HasVectorRestrictions(restrictions, kNoAbs)) {
1581 return false;
1582 } else if (HasVectorRestrictions(restrictions, kNoHiBits) &&
1583 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || is_unsigned)) {
1584 return false; // reject, unless operand is sign-extension narrower
1585 }
1586 // Accept ABS(x) for vectorizable operand.
1587 DCHECK(r != nullptr);
1588 if (generate_code && vector_mode_ != kVector) { // de-idiom
1589 r = opa;
1590 }
1591 if (VectorizeUse(node, r, generate_code, type, restrictions)) {
1592 if (generate_code) {
1593 GenerateVecOp(instruction,
1594 vector_map_->Get(r),
1595 nullptr,
1596 HVecOperation::ToProperType(type, is_unsigned));
1597 }
1598 return true;
1599 }
Aart Bik1f8d51b2018-02-15 10:42:37 -08001600 } else if (instruction->IsMin() || instruction->IsMax()) {
Aart Bik29aa0822018-03-08 11:28:00 -08001601 // Recognize saturation arithmetic.
1602 if (VectorizeSaturationIdiom(node, instruction, generate_code, type, restrictions)) {
1603 return true;
1604 }
Aart Bik1f8d51b2018-02-15 10:42:37 -08001605 // Deal with vector restrictions.
1606 HInstruction* opa = instruction->InputAt(0);
1607 HInstruction* opb = instruction->InputAt(1);
1608 HInstruction* r = opa;
1609 HInstruction* s = opb;
1610 bool is_unsigned = false;
1611 if (HasVectorRestrictions(restrictions, kNoMinMax)) {
1612 return false;
1613 } else if (HasVectorRestrictions(restrictions, kNoHiBits) &&
1614 !IsNarrowerOperands(opa, opb, type, &r, &s, &is_unsigned)) {
1615 return false; // reject, unless all operands are same-extension narrower
1616 }
1617 // Accept MIN/MAX(x, y) for vectorizable operands.
Nicolas Geoffraya3e23262018-03-28 11:15:12 +00001618 DCHECK(r != nullptr && s != nullptr);
Aart Bik1f8d51b2018-02-15 10:42:37 -08001619 if (generate_code && vector_mode_ != kVector) { // de-idiom
1620 r = opa;
1621 s = opb;
1622 }
1623 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
1624 VectorizeUse(node, s, generate_code, type, restrictions)) {
1625 if (generate_code) {
1626 GenerateVecOp(
1627 instruction, vector_map_->Get(r), vector_map_->Get(s), type, is_unsigned);
Aart Bikc8e93c72017-05-10 10:49:22 -07001628 }
Aart Bik1f8d51b2018-02-15 10:42:37 -08001629 return true;
1630 }
Aart Bik281c6812016-08-26 11:31:48 -07001631 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08001632 return false;
Aart Bik281c6812016-08-26 11:31:48 -07001633}
1634
Aart Bik38a3f212017-10-20 17:02:21 -07001635uint32_t HLoopOptimization::GetVectorSizeInBytes() {
1636 switch (compiler_driver_->GetInstructionSet()) {
Vladimir Marko33bff252017-11-01 14:35:42 +00001637 case InstructionSet::kArm:
1638 case InstructionSet::kThumb2:
Aart Bik38a3f212017-10-20 17:02:21 -07001639 return 8; // 64-bit SIMD
1640 default:
1641 return 16; // 128-bit SIMD
1642 }
1643}
1644
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001645bool HLoopOptimization::TrySetVectorType(DataType::Type type, uint64_t* restrictions) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001646 const InstructionSetFeatures* features = compiler_driver_->GetInstructionSetFeatures();
1647 switch (compiler_driver_->GetInstructionSet()) {
Vladimir Marko33bff252017-11-01 14:35:42 +00001648 case InstructionSet::kArm:
1649 case InstructionSet::kThumb2:
Artem Serov8f7c4102017-06-21 11:21:37 +01001650 // Allow vectorization for all ARM devices, because Android assumes that
Aart Bikb29f6842017-07-28 15:58:41 -07001651 // ARM 32-bit always supports advanced SIMD (64-bit SIMD).
Artem Serov8f7c4102017-06-21 11:21:37 +01001652 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001653 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001654 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001655 case DataType::Type::kInt8:
Aart Bik0148de42017-09-05 09:25:01 -07001656 *restrictions |= kNoDiv | kNoReduction;
Artem Serov8f7c4102017-06-21 11:21:37 +01001657 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001658 case DataType::Type::kUint16:
1659 case DataType::Type::kInt16:
Aart Bik0148de42017-09-05 09:25:01 -07001660 *restrictions |= kNoDiv | kNoStringCharAt | kNoReduction;
Artem Serov8f7c4102017-06-21 11:21:37 +01001661 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001662 case DataType::Type::kInt32:
Artem Serov6e9b1372017-10-05 16:48:30 +01001663 *restrictions |= kNoDiv | kNoWideSAD;
Artem Serov8f7c4102017-06-21 11:21:37 +01001664 return TrySetVectorLength(2);
1665 default:
1666 break;
1667 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001668 return false;
Vladimir Marko33bff252017-11-01 14:35:42 +00001669 case InstructionSet::kArm64:
Aart Bikf8f5a162017-02-06 15:35:29 -08001670 // Allow vectorization for all ARM devices, because Android assumes that
Aart Bikb29f6842017-07-28 15:58:41 -07001671 // ARMv8 AArch64 always supports advanced SIMD (128-bit SIMD).
Aart Bikf8f5a162017-02-06 15:35:29 -08001672 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001673 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001674 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001675 case DataType::Type::kInt8:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001676 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +01001677 return TrySetVectorLength(16);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001678 case DataType::Type::kUint16:
1679 case DataType::Type::kInt16:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001680 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +01001681 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001682 case DataType::Type::kInt32:
Aart Bikf8f5a162017-02-06 15:35:29 -08001683 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +01001684 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001685 case DataType::Type::kInt64:
Aart Bikc8e93c72017-05-10 10:49:22 -07001686 *restrictions |= kNoDiv | kNoMul | kNoMinMax;
Aart Bikf8f5a162017-02-06 15:35:29 -08001687 return TrySetVectorLength(2);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001688 case DataType::Type::kFloat32:
Aart Bik0148de42017-09-05 09:25:01 -07001689 *restrictions |= kNoReduction;
Artem Serovd4bccf12017-04-03 18:47:32 +01001690 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001691 case DataType::Type::kFloat64:
Aart Bik0148de42017-09-05 09:25:01 -07001692 *restrictions |= kNoReduction;
Aart Bikf8f5a162017-02-06 15:35:29 -08001693 return TrySetVectorLength(2);
1694 default:
1695 return false;
1696 }
Vladimir Marko33bff252017-11-01 14:35:42 +00001697 case InstructionSet::kX86:
1698 case InstructionSet::kX86_64:
Aart Bikb29f6842017-07-28 15:58:41 -07001699 // Allow vectorization for SSE4.1-enabled X86 devices only (128-bit SIMD).
Aart Bikf8f5a162017-02-06 15:35:29 -08001700 if (features->AsX86InstructionSetFeatures()->HasSSE4_1()) {
1701 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001702 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001703 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001704 case DataType::Type::kInt8:
Aart Bik0148de42017-09-05 09:25:01 -07001705 *restrictions |=
Aart Bikdbbac8f2017-09-01 13:06:08 -07001706 kNoMul | kNoDiv | kNoShift | kNoAbs | kNoSignedHAdd | kNoUnroundedHAdd | kNoSAD;
Aart Bikf8f5a162017-02-06 15:35:29 -08001707 return TrySetVectorLength(16);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001708 case DataType::Type::kUint16:
1709 case DataType::Type::kInt16:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001710 *restrictions |= kNoDiv | kNoAbs | kNoSignedHAdd | kNoUnroundedHAdd | kNoSAD;
Aart Bikf8f5a162017-02-06 15:35:29 -08001711 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001712 case DataType::Type::kInt32:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001713 *restrictions |= kNoDiv | kNoSAD;
Aart Bikf8f5a162017-02-06 15:35:29 -08001714 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001715 case DataType::Type::kInt64:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001716 *restrictions |= kNoMul | kNoDiv | kNoShr | kNoAbs | kNoMinMax | kNoSAD;
Aart Bikf8f5a162017-02-06 15:35:29 -08001717 return TrySetVectorLength(2);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001718 case DataType::Type::kFloat32:
Aart Bik0148de42017-09-05 09:25:01 -07001719 *restrictions |= kNoMinMax | kNoReduction; // minmax: -0.0 vs +0.0
Aart Bikf8f5a162017-02-06 15:35:29 -08001720 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001721 case DataType::Type::kFloat64:
Aart Bik0148de42017-09-05 09:25:01 -07001722 *restrictions |= kNoMinMax | kNoReduction; // minmax: -0.0 vs +0.0
Aart Bikf8f5a162017-02-06 15:35:29 -08001723 return TrySetVectorLength(2);
1724 default:
1725 break;
1726 } // switch type
1727 }
1728 return false;
Vladimir Marko33bff252017-11-01 14:35:42 +00001729 case InstructionSet::kMips:
Lena Djokic51765b02017-06-22 13:49:59 +02001730 if (features->AsMipsInstructionSetFeatures()->HasMsa()) {
1731 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001732 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001733 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001734 case DataType::Type::kInt8:
Aart Bik29aa0822018-03-08 11:28:00 -08001735 *restrictions |= kNoDiv | kNoSaturation;
Lena Djokic51765b02017-06-22 13:49:59 +02001736 return TrySetVectorLength(16);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001737 case DataType::Type::kUint16:
1738 case DataType::Type::kInt16:
Aart Bik29aa0822018-03-08 11:28:00 -08001739 *restrictions |= kNoDiv | kNoSaturation | kNoStringCharAt;
Lena Djokic51765b02017-06-22 13:49:59 +02001740 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001741 case DataType::Type::kInt32:
Lena Djokic38e380b2017-10-30 16:17:10 +01001742 *restrictions |= kNoDiv;
Lena Djokic51765b02017-06-22 13:49:59 +02001743 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001744 case DataType::Type::kInt64:
Lena Djokic38e380b2017-10-30 16:17:10 +01001745 *restrictions |= kNoDiv;
Lena Djokic51765b02017-06-22 13:49:59 +02001746 return TrySetVectorLength(2);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001747 case DataType::Type::kFloat32:
Aart Bik0148de42017-09-05 09:25:01 -07001748 *restrictions |= kNoMinMax | kNoReduction; // min/max(x, NaN)
Lena Djokic51765b02017-06-22 13:49:59 +02001749 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001750 case DataType::Type::kFloat64:
Aart Bik0148de42017-09-05 09:25:01 -07001751 *restrictions |= kNoMinMax | kNoReduction; // min/max(x, NaN)
Lena Djokic51765b02017-06-22 13:49:59 +02001752 return TrySetVectorLength(2);
1753 default:
1754 break;
1755 } // switch type
1756 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001757 return false;
Vladimir Marko33bff252017-11-01 14:35:42 +00001758 case InstructionSet::kMips64:
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001759 if (features->AsMips64InstructionSetFeatures()->HasMsa()) {
1760 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001761 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001762 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001763 case DataType::Type::kInt8:
Aart Bik29aa0822018-03-08 11:28:00 -08001764 *restrictions |= kNoDiv | kNoSaturation;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001765 return TrySetVectorLength(16);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001766 case DataType::Type::kUint16:
1767 case DataType::Type::kInt16:
Aart Bik29aa0822018-03-08 11:28:00 -08001768 *restrictions |= kNoDiv | kNoSaturation | kNoStringCharAt;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001769 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001770 case DataType::Type::kInt32:
Lena Djokic38e380b2017-10-30 16:17:10 +01001771 *restrictions |= kNoDiv;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001772 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001773 case DataType::Type::kInt64:
Lena Djokic38e380b2017-10-30 16:17:10 +01001774 *restrictions |= kNoDiv;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001775 return TrySetVectorLength(2);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001776 case DataType::Type::kFloat32:
Aart Bik0148de42017-09-05 09:25:01 -07001777 *restrictions |= kNoMinMax | kNoReduction; // min/max(x, NaN)
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001778 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001779 case DataType::Type::kFloat64:
Aart Bik0148de42017-09-05 09:25:01 -07001780 *restrictions |= kNoMinMax | kNoReduction; // min/max(x, NaN)
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001781 return TrySetVectorLength(2);
1782 default:
1783 break;
1784 } // switch type
1785 }
1786 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001787 default:
1788 return false;
1789 } // switch instruction set
1790}
1791
1792bool HLoopOptimization::TrySetVectorLength(uint32_t length) {
1793 DCHECK(IsPowerOfTwo(length) && length >= 2u);
1794 // First time set?
1795 if (vector_length_ == 0) {
1796 vector_length_ = length;
1797 }
1798 // Different types are acceptable within a loop-body, as long as all the corresponding vector
1799 // lengths match exactly to obtain a uniform traversal through the vector iteration space
1800 // (idiomatic exceptions to this rule can be handled by further unrolling sub-expressions).
1801 return vector_length_ == length;
1802}
1803
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001804void HLoopOptimization::GenerateVecInv(HInstruction* org, DataType::Type type) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001805 if (vector_map_->find(org) == vector_map_->end()) {
1806 // In scalar code, just use a self pass-through for scalar invariants
1807 // (viz. expression remains itself).
1808 if (vector_mode_ == kSequential) {
1809 vector_map_->Put(org, org);
1810 return;
1811 }
1812 // In vector code, explicit scalar expansion is needed.
Aart Bik0148de42017-09-05 09:25:01 -07001813 HInstruction* vector = nullptr;
1814 auto it = vector_permanent_map_->find(org);
1815 if (it != vector_permanent_map_->end()) {
1816 vector = it->second; // reuse during unrolling
1817 } else {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001818 // Generates ReplicateScalar( (optional_type_conv) org ).
1819 HInstruction* input = org;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001820 DataType::Type input_type = input->GetType();
1821 if (type != input_type && (type == DataType::Type::kInt64 ||
1822 input_type == DataType::Type::kInt64)) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001823 input = Insert(vector_preheader_,
1824 new (global_allocator_) HTypeConversion(type, input, kNoDexPc));
1825 }
1826 vector = new (global_allocator_)
Aart Bik46b6dbc2017-10-03 11:37:37 -07001827 HVecReplicateScalar(global_allocator_, input, type, vector_length_, kNoDexPc);
Aart Bik0148de42017-09-05 09:25:01 -07001828 vector_permanent_map_->Put(org, Insert(vector_preheader_, vector));
1829 }
1830 vector_map_->Put(org, vector);
Aart Bikf8f5a162017-02-06 15:35:29 -08001831 }
1832}
1833
1834void HLoopOptimization::GenerateVecSub(HInstruction* org, HInstruction* offset) {
1835 if (vector_map_->find(org) == vector_map_->end()) {
Aart Bik14a68b42017-06-08 14:06:58 -07001836 HInstruction* subscript = vector_index_;
Aart Bik37dc4df2017-06-28 14:08:00 -07001837 int64_t value = 0;
1838 if (!IsInt64AndGet(offset, &value) || value != 0) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001839 subscript = new (global_allocator_) HAdd(DataType::Type::kInt32, subscript, offset);
Aart Bikf8f5a162017-02-06 15:35:29 -08001840 if (org->IsPhi()) {
1841 Insert(vector_body_, subscript); // lacks layout placeholder
1842 }
1843 }
1844 vector_map_->Put(org, subscript);
1845 }
1846}
1847
1848void HLoopOptimization::GenerateVecMem(HInstruction* org,
1849 HInstruction* opa,
1850 HInstruction* opb,
Aart Bik14a68b42017-06-08 14:06:58 -07001851 HInstruction* offset,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001852 DataType::Type type) {
Aart Bik46b6dbc2017-10-03 11:37:37 -07001853 uint32_t dex_pc = org->GetDexPc();
Aart Bikf8f5a162017-02-06 15:35:29 -08001854 HInstruction* vector = nullptr;
1855 if (vector_mode_ == kVector) {
1856 // Vector store or load.
Aart Bik38a3f212017-10-20 17:02:21 -07001857 bool is_string_char_at = false;
Aart Bik14a68b42017-06-08 14:06:58 -07001858 HInstruction* base = org->InputAt(0);
Aart Bikf8f5a162017-02-06 15:35:29 -08001859 if (opb != nullptr) {
1860 vector = new (global_allocator_) HVecStore(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001861 global_allocator_, base, opa, opb, type, org->GetSideEffects(), vector_length_, dex_pc);
Aart Bikf8f5a162017-02-06 15:35:29 -08001862 } else {
Aart Bik38a3f212017-10-20 17:02:21 -07001863 is_string_char_at = org->AsArrayGet()->IsStringCharAt();
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001864 vector = new (global_allocator_) HVecLoad(global_allocator_,
1865 base,
1866 opa,
1867 type,
1868 org->GetSideEffects(),
1869 vector_length_,
Aart Bik46b6dbc2017-10-03 11:37:37 -07001870 is_string_char_at,
1871 dex_pc);
Aart Bik14a68b42017-06-08 14:06:58 -07001872 }
Aart Bik38a3f212017-10-20 17:02:21 -07001873 // Known (forced/adjusted/original) alignment?
1874 if (vector_dynamic_peeling_candidate_ != nullptr) {
1875 if (vector_dynamic_peeling_candidate_->offset == offset && // TODO: diffs too?
1876 DataType::Size(vector_dynamic_peeling_candidate_->type) == DataType::Size(type) &&
1877 vector_dynamic_peeling_candidate_->is_string_char_at == is_string_char_at) {
1878 vector->AsVecMemoryOperation()->SetAlignment( // forced
1879 Alignment(GetVectorSizeInBytes(), 0));
1880 }
1881 } else {
1882 vector->AsVecMemoryOperation()->SetAlignment( // adjusted/original
1883 ComputeAlignment(offset, type, is_string_char_at, vector_static_peeling_factor_));
Aart Bikf8f5a162017-02-06 15:35:29 -08001884 }
1885 } else {
1886 // Scalar store or load.
1887 DCHECK(vector_mode_ == kSequential);
1888 if (opb != nullptr) {
Aart Bik4d1a9d42017-10-19 14:40:55 -07001889 DataType::Type component_type = org->AsArraySet()->GetComponentType();
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001890 vector = new (global_allocator_) HArraySet(
Aart Bik4d1a9d42017-10-19 14:40:55 -07001891 org->InputAt(0), opa, opb, component_type, org->GetSideEffects(), dex_pc);
Aart Bikf8f5a162017-02-06 15:35:29 -08001892 } else {
Aart Bikdb14fcf2017-04-25 15:53:58 -07001893 bool is_string_char_at = org->AsArrayGet()->IsStringCharAt();
1894 vector = new (global_allocator_) HArrayGet(
Aart Bik4d1a9d42017-10-19 14:40:55 -07001895 org->InputAt(0), opa, org->GetType(), org->GetSideEffects(), dex_pc, is_string_char_at);
Aart Bikf8f5a162017-02-06 15:35:29 -08001896 }
1897 }
1898 vector_map_->Put(org, vector);
1899}
1900
Aart Bik0148de42017-09-05 09:25:01 -07001901void HLoopOptimization::GenerateVecReductionPhi(HPhi* phi) {
1902 DCHECK(reductions_->find(phi) != reductions_->end());
1903 DCHECK(reductions_->Get(phi->InputAt(1)) == phi);
1904 HInstruction* vector = nullptr;
1905 if (vector_mode_ == kSequential) {
1906 HPhi* new_phi = new (global_allocator_) HPhi(
1907 global_allocator_, kNoRegNumber, 0, phi->GetType());
1908 vector_header_->AddPhi(new_phi);
1909 vector = new_phi;
1910 } else {
1911 // Link vector reduction back to prior unrolled update, or a first phi.
1912 auto it = vector_permanent_map_->find(phi);
1913 if (it != vector_permanent_map_->end()) {
1914 vector = it->second;
1915 } else {
1916 HPhi* new_phi = new (global_allocator_) HPhi(
1917 global_allocator_, kNoRegNumber, 0, HVecOperation::kSIMDType);
1918 vector_header_->AddPhi(new_phi);
1919 vector = new_phi;
1920 }
1921 }
1922 vector_map_->Put(phi, vector);
1923}
1924
1925void HLoopOptimization::GenerateVecReductionPhiInputs(HPhi* phi, HInstruction* reduction) {
1926 HInstruction* new_phi = vector_map_->Get(phi);
1927 HInstruction* new_init = reductions_->Get(phi);
1928 HInstruction* new_red = vector_map_->Get(reduction);
1929 // Link unrolled vector loop back to new phi.
1930 for (; !new_phi->IsPhi(); new_phi = vector_permanent_map_->Get(new_phi)) {
1931 DCHECK(new_phi->IsVecOperation());
1932 }
1933 // Prepare the new initialization.
1934 if (vector_mode_ == kVector) {
Goran Jakovljevic89b8df02017-10-13 08:33:17 +02001935 // Generate a [initial, 0, .., 0] vector for add or
1936 // a [initial, initial, .., initial] vector for min/max.
Aart Bikdbbac8f2017-09-01 13:06:08 -07001937 HVecOperation* red_vector = new_red->AsVecOperation();
Goran Jakovljevic89b8df02017-10-13 08:33:17 +02001938 HVecReduce::ReductionKind kind = GetReductionKind(red_vector);
Aart Bik38a3f212017-10-20 17:02:21 -07001939 uint32_t vector_length = red_vector->GetVectorLength();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001940 DataType::Type type = red_vector->GetPackedType();
Goran Jakovljevic89b8df02017-10-13 08:33:17 +02001941 if (kind == HVecReduce::ReductionKind::kSum) {
1942 new_init = Insert(vector_preheader_,
1943 new (global_allocator_) HVecSetScalars(global_allocator_,
1944 &new_init,
1945 type,
1946 vector_length,
1947 1,
1948 kNoDexPc));
1949 } else {
1950 new_init = Insert(vector_preheader_,
1951 new (global_allocator_) HVecReplicateScalar(global_allocator_,
1952 new_init,
1953 type,
1954 vector_length,
1955 kNoDexPc));
1956 }
Aart Bik0148de42017-09-05 09:25:01 -07001957 } else {
1958 new_init = ReduceAndExtractIfNeeded(new_init);
1959 }
1960 // Set the phi inputs.
1961 DCHECK(new_phi->IsPhi());
1962 new_phi->AsPhi()->AddInput(new_init);
1963 new_phi->AsPhi()->AddInput(new_red);
1964 // New feed value for next phi (safe mutation in iteration).
1965 reductions_->find(phi)->second = new_phi;
1966}
1967
1968HInstruction* HLoopOptimization::ReduceAndExtractIfNeeded(HInstruction* instruction) {
1969 if (instruction->IsPhi()) {
1970 HInstruction* input = instruction->InputAt(1);
Aart Bik2dd7b672017-12-07 11:11:22 -08001971 if (HVecOperation::ReturnsSIMDValue(input)) {
1972 DCHECK(!input->IsPhi());
Aart Bikdbbac8f2017-09-01 13:06:08 -07001973 HVecOperation* input_vector = input->AsVecOperation();
Aart Bik38a3f212017-10-20 17:02:21 -07001974 uint32_t vector_length = input_vector->GetVectorLength();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001975 DataType::Type type = input_vector->GetPackedType();
Aart Bikdbbac8f2017-09-01 13:06:08 -07001976 HVecReduce::ReductionKind kind = GetReductionKind(input_vector);
Aart Bik0148de42017-09-05 09:25:01 -07001977 HBasicBlock* exit = instruction->GetBlock()->GetSuccessors()[0];
1978 // Generate a vector reduction and scalar extract
1979 // x = REDUCE( [x_1, .., x_n] )
1980 // y = x_1
1981 // along the exit of the defining loop.
Aart Bik0148de42017-09-05 09:25:01 -07001982 HInstruction* reduce = new (global_allocator_) HVecReduce(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001983 global_allocator_, instruction, type, vector_length, kind, kNoDexPc);
Aart Bik0148de42017-09-05 09:25:01 -07001984 exit->InsertInstructionBefore(reduce, exit->GetFirstInstruction());
1985 instruction = new (global_allocator_) HVecExtractScalar(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001986 global_allocator_, reduce, type, vector_length, 0, kNoDexPc);
Aart Bik0148de42017-09-05 09:25:01 -07001987 exit->InsertInstructionAfter(instruction, reduce);
1988 }
1989 }
1990 return instruction;
1991}
1992
Aart Bikf8f5a162017-02-06 15:35:29 -08001993#define GENERATE_VEC(x, y) \
1994 if (vector_mode_ == kVector) { \
1995 vector = (x); \
1996 } else { \
1997 DCHECK(vector_mode_ == kSequential); \
1998 vector = (y); \
1999 } \
2000 break;
2001
2002void HLoopOptimization::GenerateVecOp(HInstruction* org,
2003 HInstruction* opa,
2004 HInstruction* opb,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002005 DataType::Type type,
Aart Bik304c8a52017-05-23 11:01:13 -07002006 bool is_unsigned) {
Aart Bik46b6dbc2017-10-03 11:37:37 -07002007 uint32_t dex_pc = org->GetDexPc();
Aart Bikf8f5a162017-02-06 15:35:29 -08002008 HInstruction* vector = nullptr;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002009 DataType::Type org_type = org->GetType();
Aart Bikf8f5a162017-02-06 15:35:29 -08002010 switch (org->GetKind()) {
2011 case HInstruction::kNeg:
2012 DCHECK(opb == nullptr);
2013 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07002014 new (global_allocator_) HVecNeg(global_allocator_, opa, type, vector_length_, dex_pc),
2015 new (global_allocator_) HNeg(org_type, opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08002016 case HInstruction::kNot:
2017 DCHECK(opb == nullptr);
2018 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07002019 new (global_allocator_) HVecNot(global_allocator_, opa, type, vector_length_, dex_pc),
2020 new (global_allocator_) HNot(org_type, opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08002021 case HInstruction::kBooleanNot:
2022 DCHECK(opb == nullptr);
2023 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07002024 new (global_allocator_) HVecNot(global_allocator_, opa, type, vector_length_, dex_pc),
2025 new (global_allocator_) HBooleanNot(opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08002026 case HInstruction::kTypeConversion:
2027 DCHECK(opb == nullptr);
2028 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07002029 new (global_allocator_) HVecCnv(global_allocator_, opa, type, vector_length_, dex_pc),
2030 new (global_allocator_) HTypeConversion(org_type, opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08002031 case HInstruction::kAdd:
2032 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07002033 new (global_allocator_) HVecAdd(global_allocator_, opa, opb, type, vector_length_, dex_pc),
2034 new (global_allocator_) HAdd(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08002035 case HInstruction::kSub:
2036 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07002037 new (global_allocator_) HVecSub(global_allocator_, opa, opb, type, vector_length_, dex_pc),
2038 new (global_allocator_) HSub(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08002039 case HInstruction::kMul:
2040 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07002041 new (global_allocator_) HVecMul(global_allocator_, opa, opb, type, vector_length_, dex_pc),
2042 new (global_allocator_) HMul(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08002043 case HInstruction::kDiv:
2044 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07002045 new (global_allocator_) HVecDiv(global_allocator_, opa, opb, type, vector_length_, dex_pc),
2046 new (global_allocator_) HDiv(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08002047 case HInstruction::kAnd:
2048 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07002049 new (global_allocator_) HVecAnd(global_allocator_, opa, opb, type, vector_length_, dex_pc),
2050 new (global_allocator_) HAnd(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08002051 case HInstruction::kOr:
2052 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07002053 new (global_allocator_) HVecOr(global_allocator_, opa, opb, type, vector_length_, dex_pc),
2054 new (global_allocator_) HOr(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08002055 case HInstruction::kXor:
2056 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07002057 new (global_allocator_) HVecXor(global_allocator_, opa, opb, type, vector_length_, dex_pc),
2058 new (global_allocator_) HXor(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08002059 case HInstruction::kShl:
2060 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07002061 new (global_allocator_) HVecShl(global_allocator_, opa, opb, type, vector_length_, dex_pc),
2062 new (global_allocator_) HShl(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08002063 case HInstruction::kShr:
2064 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07002065 new (global_allocator_) HVecShr(global_allocator_, opa, opb, type, vector_length_, dex_pc),
2066 new (global_allocator_) HShr(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08002067 case HInstruction::kUShr:
2068 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07002069 new (global_allocator_) HVecUShr(global_allocator_, opa, opb, type, vector_length_, dex_pc),
2070 new (global_allocator_) HUShr(org_type, opa, opb, dex_pc));
Aart Bik1f8d51b2018-02-15 10:42:37 -08002071 case HInstruction::kMin:
2072 GENERATE_VEC(
2073 new (global_allocator_) HVecMin(global_allocator_,
2074 opa,
2075 opb,
2076 HVecOperation::ToProperType(type, is_unsigned),
2077 vector_length_,
2078 dex_pc),
2079 new (global_allocator_) HMin(org_type, opa, opb, dex_pc));
2080 case HInstruction::kMax:
2081 GENERATE_VEC(
2082 new (global_allocator_) HVecMax(global_allocator_,
2083 opa,
2084 opb,
2085 HVecOperation::ToProperType(type, is_unsigned),
2086 vector_length_,
2087 dex_pc),
2088 new (global_allocator_) HMax(org_type, opa, opb, dex_pc));
Aart Bik3b2a5952018-03-05 13:55:28 -08002089 case HInstruction::kAbs:
2090 DCHECK(opb == nullptr);
2091 GENERATE_VEC(
2092 new (global_allocator_) HVecAbs(global_allocator_, opa, type, vector_length_, dex_pc),
2093 new (global_allocator_) HAbs(org_type, opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08002094 default:
2095 break;
2096 } // switch
2097 CHECK(vector != nullptr) << "Unsupported SIMD operator";
2098 vector_map_->Put(org, vector);
2099}
2100
2101#undef GENERATE_VEC
2102
2103//
Aart Bikf3e61ee2017-04-12 17:09:20 -07002104// Vectorization idioms.
2105//
2106
Aart Bik29aa0822018-03-08 11:28:00 -08002107// Method recognizes single and double clipping saturation arithmetic.
2108bool HLoopOptimization::VectorizeSaturationIdiom(LoopNode* node,
2109 HInstruction* instruction,
2110 bool generate_code,
2111 DataType::Type type,
2112 uint64_t restrictions) {
2113 // Deal with vector restrictions.
2114 if (HasVectorRestrictions(restrictions, kNoSaturation)) {
2115 return false;
2116 }
Aart Bik1a381022018-03-15 15:51:37 -07002117 // Restrict type (generalize if one day we generalize allowed MIN/MAX integral types).
2118 if (instruction->GetType() != DataType::Type::kInt32 &&
2119 instruction->GetType() != DataType::Type::kInt64) {
Aart Bik29aa0822018-03-08 11:28:00 -08002120 return false;
2121 }
Nicolas Geoffraya3e23262018-03-28 11:15:12 +00002122 // Clipped addition or subtraction on narrower operands? We will try both
2123 // formats since, e.g., x+c can be interpreted as x+c and x-(-c), depending
2124 // on what clipping values are used, to get most benefits.
Aart Bik1a381022018-03-15 15:51:37 -07002125 int64_t lo = std::numeric_limits<int64_t>::min();
2126 int64_t hi = std::numeric_limits<int64_t>::max();
2127 HInstruction* clippee = FindClippee(instruction, &lo, &hi);
Nicolas Geoffraya3e23262018-03-28 11:15:12 +00002128 HInstruction* a = nullptr;
2129 HInstruction* b = nullptr;
Aart Bik29aa0822018-03-08 11:28:00 -08002130 HInstruction* r = nullptr;
2131 HInstruction* s = nullptr;
2132 bool is_unsigned = false;
Nicolas Geoffraya3e23262018-03-28 11:15:12 +00002133 bool is_add = true;
2134 int64_t c = 0;
2135 // First try for saturated addition.
2136 if (IsAddConst2(graph_, clippee, /*out*/ &a, /*out*/ &b, /*out*/ &c) && c == 0 &&
2137 IsNarrowerOperands(a, b, type, &r, &s, &is_unsigned) &&
2138 IsSaturatedAdd(r, s, type, lo, hi, is_unsigned)) {
2139 is_add = true;
Aart Bik29aa0822018-03-08 11:28:00 -08002140 } else {
Nicolas Geoffraya3e23262018-03-28 11:15:12 +00002141 // Then try again for saturated subtraction.
2142 a = b = r = s = nullptr;
2143 if (IsSubConst2(graph_, clippee, /*out*/ &a, /*out*/ &b) &&
2144 IsNarrowerOperands(a, b, type, &r, &s, &is_unsigned) &&
2145 IsSaturatedSub(r, type, lo, hi, is_unsigned)) {
2146 is_add = false;
2147 } else {
2148 return false;
2149 }
Aart Bik29aa0822018-03-08 11:28:00 -08002150 }
2151 // Accept saturation idiom for vectorizable operands.
Nicolas Geoffraya3e23262018-03-28 11:15:12 +00002152 DCHECK(r != nullptr && s != nullptr);
Aart Bik29aa0822018-03-08 11:28:00 -08002153 if (generate_code && vector_mode_ != kVector) { // de-idiom
2154 r = instruction->InputAt(0);
2155 s = instruction->InputAt(1);
2156 restrictions &= ~(kNoHiBits | kNoMinMax); // allow narrow MIN/MAX in seq
2157 }
2158 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
2159 VectorizeUse(node, s, generate_code, type, restrictions)) {
2160 if (generate_code) {
2161 if (vector_mode_ == kVector) {
2162 DataType::Type vtype = HVecOperation::ToProperType(type, is_unsigned);
2163 HInstruction* op1 = vector_map_->Get(r);
2164 HInstruction* op2 = vector_map_->Get(s);
2165 vector_map_->Put(instruction, is_add
2166 ? reinterpret_cast<HInstruction*>(new (global_allocator_) HVecSaturationAdd(
2167 global_allocator_, op1, op2, vtype, vector_length_, kNoDexPc))
2168 : reinterpret_cast<HInstruction*>(new (global_allocator_) HVecSaturationSub(
2169 global_allocator_, op1, op2, vtype, vector_length_, kNoDexPc)));
2170 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorizedIdiom);
2171 } else {
2172 GenerateVecOp(instruction, vector_map_->Get(r), vector_map_->Get(s), type);
2173 }
2174 }
2175 return true;
2176 }
2177 return false;
2178}
2179
Aart Bikf3e61ee2017-04-12 17:09:20 -07002180// Method recognizes the following idioms:
Aart Bikdbbac8f2017-09-01 13:06:08 -07002181// rounding halving add (a + b + 1) >> 1 for unsigned/signed operands a, b
2182// truncated halving add (a + b) >> 1 for unsigned/signed operands a, b
Aart Bikf3e61ee2017-04-12 17:09:20 -07002183// Provided that the operands are promoted to a wider form to do the arithmetic and
2184// then cast back to narrower form, the idioms can be mapped into efficient SIMD
2185// implementation that operates directly in narrower form (plus one extra bit).
2186// TODO: current version recognizes implicit byte/short/char widening only;
2187// explicit widening from int to long could be added later.
2188bool HLoopOptimization::VectorizeHalvingAddIdiom(LoopNode* node,
2189 HInstruction* instruction,
2190 bool generate_code,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002191 DataType::Type type,
Aart Bikf3e61ee2017-04-12 17:09:20 -07002192 uint64_t restrictions) {
2193 // Test for top level arithmetic shift right x >> 1 or logical shift right x >>> 1
Aart Bik304c8a52017-05-23 11:01:13 -07002194 // (note whether the sign bit in wider precision is shifted in has no effect
Aart Bikf3e61ee2017-04-12 17:09:20 -07002195 // on the narrow precision computed by the idiom).
Aart Bikf3e61ee2017-04-12 17:09:20 -07002196 if ((instruction->IsShr() ||
2197 instruction->IsUShr()) &&
Aart Bik0148de42017-09-05 09:25:01 -07002198 IsInt64Value(instruction->InputAt(1), 1)) {
Aart Bik5f805002017-05-16 16:42:41 -07002199 // Test for (a + b + c) >> 1 for optional constant c.
2200 HInstruction* a = nullptr;
2201 HInstruction* b = nullptr;
2202 int64_t c = 0;
Nicolas Geoffraya3e23262018-03-28 11:15:12 +00002203 if (IsAddConst2(graph_, instruction->InputAt(0), /*out*/ &a, /*out*/ &b, /*out*/ &c)) {
Aart Bik5f805002017-05-16 16:42:41 -07002204 // Accept c == 1 (rounded) or c == 0 (not rounded).
2205 bool is_rounded = false;
2206 if (c == 1) {
2207 is_rounded = true;
2208 } else if (c != 0) {
2209 return false;
2210 }
2211 // Accept consistent zero or sign extension on operands a and b.
Aart Bikf3e61ee2017-04-12 17:09:20 -07002212 HInstruction* r = nullptr;
2213 HInstruction* s = nullptr;
2214 bool is_unsigned = false;
Aart Bik304c8a52017-05-23 11:01:13 -07002215 if (!IsNarrowerOperands(a, b, type, &r, &s, &is_unsigned)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -07002216 return false;
2217 }
2218 // Deal with vector restrictions.
2219 if ((!is_unsigned && HasVectorRestrictions(restrictions, kNoSignedHAdd)) ||
2220 (!is_rounded && HasVectorRestrictions(restrictions, kNoUnroundedHAdd))) {
2221 return false;
2222 }
2223 // Accept recognized halving add for vectorizable operands. Vectorized code uses the
2224 // shorthand idiomatic operation. Sequential code uses the original scalar expressions.
Nicolas Geoffraya3e23262018-03-28 11:15:12 +00002225 DCHECK(r != nullptr && s != nullptr);
Aart Bik304c8a52017-05-23 11:01:13 -07002226 if (generate_code && vector_mode_ != kVector) { // de-idiom
2227 r = instruction->InputAt(0);
2228 s = instruction->InputAt(1);
2229 }
Aart Bikf3e61ee2017-04-12 17:09:20 -07002230 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
2231 VectorizeUse(node, s, generate_code, type, restrictions)) {
2232 if (generate_code) {
2233 if (vector_mode_ == kVector) {
2234 vector_map_->Put(instruction, new (global_allocator_) HVecHalvingAdd(
2235 global_allocator_,
2236 vector_map_->Get(r),
2237 vector_map_->Get(s),
Aart Bik66c158e2018-01-31 12:55:04 -08002238 HVecOperation::ToProperType(type, is_unsigned),
Aart Bikf3e61ee2017-04-12 17:09:20 -07002239 vector_length_,
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01002240 is_rounded,
Aart Bik46b6dbc2017-10-03 11:37:37 -07002241 kNoDexPc));
Aart Bik21b85922017-09-06 13:29:16 -07002242 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorizedIdiom);
Aart Bikf3e61ee2017-04-12 17:09:20 -07002243 } else {
Aart Bik304c8a52017-05-23 11:01:13 -07002244 GenerateVecOp(instruction, vector_map_->Get(r), vector_map_->Get(s), type);
Aart Bikf3e61ee2017-04-12 17:09:20 -07002245 }
2246 }
2247 return true;
2248 }
2249 }
2250 }
2251 return false;
2252}
2253
Aart Bikdbbac8f2017-09-01 13:06:08 -07002254// Method recognizes the following idiom:
2255// q += ABS(a - b) for signed operands a, b
2256// Provided that the operands have the same type or are promoted to a wider form.
2257// Since this may involve a vector length change, the idiom is handled by going directly
2258// to a sad-accumulate node (rather than relying combining finer grained nodes later).
2259// TODO: unsigned SAD too?
2260bool HLoopOptimization::VectorizeSADIdiom(LoopNode* node,
2261 HInstruction* instruction,
2262 bool generate_code,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002263 DataType::Type reduction_type,
Aart Bikdbbac8f2017-09-01 13:06:08 -07002264 uint64_t restrictions) {
2265 // Filter integral "q += ABS(a - b);" reduction, where ABS and SUB
2266 // are done in the same precision (either int or long).
2267 if (!instruction->IsAdd() ||
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002268 (reduction_type != DataType::Type::kInt32 && reduction_type != DataType::Type::kInt64)) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07002269 return false;
2270 }
2271 HInstruction* q = instruction->InputAt(0);
2272 HInstruction* v = instruction->InputAt(1);
2273 HInstruction* a = nullptr;
2274 HInstruction* b = nullptr;
Nicolas Geoffraya3e23262018-03-28 11:15:12 +00002275 if (v->IsAbs() &&
2276 v->GetType() == reduction_type &&
2277 IsSubConst2(graph_, v->InputAt(0), /*out*/ &a, /*out*/ &b)) {
2278 DCHECK(a != nullptr && b != nullptr);
2279 } else {
Aart Bikdbbac8f2017-09-01 13:06:08 -07002280 return false;
2281 }
2282 // Accept same-type or consistent sign extension for narrower-type on operands a and b.
2283 // The same-type or narrower operands are called r (a or lower) and s (b or lower).
Aart Bikdf011c32017-09-28 12:53:04 -07002284 // We inspect the operands carefully to pick the most suited type.
Aart Bikdbbac8f2017-09-01 13:06:08 -07002285 HInstruction* r = a;
2286 HInstruction* s = b;
2287 bool is_unsigned = false;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002288 DataType::Type sub_type = a->GetType();
Aart Bikdf011c32017-09-28 12:53:04 -07002289 if (DataType::Size(b->GetType()) < DataType::Size(sub_type)) {
2290 sub_type = b->GetType();
2291 }
2292 if (a->IsTypeConversion() &&
2293 DataType::Size(a->InputAt(0)->GetType()) < DataType::Size(sub_type)) {
2294 sub_type = a->InputAt(0)->GetType();
2295 }
2296 if (b->IsTypeConversion() &&
2297 DataType::Size(b->InputAt(0)->GetType()) < DataType::Size(sub_type)) {
2298 sub_type = b->InputAt(0)->GetType();
Aart Bikdbbac8f2017-09-01 13:06:08 -07002299 }
2300 if (reduction_type != sub_type &&
2301 (!IsNarrowerOperands(a, b, sub_type, &r, &s, &is_unsigned) || is_unsigned)) {
2302 return false;
2303 }
2304 // Try same/narrower type and deal with vector restrictions.
Artem Serov6e9b1372017-10-05 16:48:30 +01002305 if (!TrySetVectorType(sub_type, &restrictions) ||
2306 HasVectorRestrictions(restrictions, kNoSAD) ||
2307 (reduction_type != sub_type && HasVectorRestrictions(restrictions, kNoWideSAD))) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07002308 return false;
2309 }
2310 // Accept SAD idiom for vectorizable operands. Vectorized code uses the shorthand
2311 // idiomatic operation. Sequential code uses the original scalar expressions.
Nicolas Geoffraya3e23262018-03-28 11:15:12 +00002312 DCHECK(r != nullptr && s != nullptr);
Aart Bikdbbac8f2017-09-01 13:06:08 -07002313 if (generate_code && vector_mode_ != kVector) { // de-idiom
2314 r = s = v->InputAt(0);
2315 }
2316 if (VectorizeUse(node, q, generate_code, sub_type, restrictions) &&
2317 VectorizeUse(node, r, generate_code, sub_type, restrictions) &&
2318 VectorizeUse(node, s, generate_code, sub_type, restrictions)) {
2319 if (generate_code) {
2320 if (vector_mode_ == kVector) {
2321 vector_map_->Put(instruction, new (global_allocator_) HVecSADAccumulate(
2322 global_allocator_,
2323 vector_map_->Get(q),
2324 vector_map_->Get(r),
2325 vector_map_->Get(s),
Aart Bik3b2a5952018-03-05 13:55:28 -08002326 HVecOperation::ToProperType(reduction_type, is_unsigned),
Aart Bik46b6dbc2017-10-03 11:37:37 -07002327 GetOtherVL(reduction_type, sub_type, vector_length_),
2328 kNoDexPc));
Aart Bikdbbac8f2017-09-01 13:06:08 -07002329 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorizedIdiom);
2330 } else {
2331 GenerateVecOp(v, vector_map_->Get(r), nullptr, reduction_type);
2332 GenerateVecOp(instruction, vector_map_->Get(q), vector_map_->Get(v), reduction_type);
2333 }
2334 }
2335 return true;
2336 }
2337 return false;
2338}
2339
Aart Bikf3e61ee2017-04-12 17:09:20 -07002340//
Aart Bik14a68b42017-06-08 14:06:58 -07002341// Vectorization heuristics.
2342//
2343
Aart Bik38a3f212017-10-20 17:02:21 -07002344Alignment HLoopOptimization::ComputeAlignment(HInstruction* offset,
2345 DataType::Type type,
2346 bool is_string_char_at,
2347 uint32_t peeling) {
2348 // Combine the alignment and hidden offset that is guaranteed by
2349 // the Android runtime with a known starting index adjusted as bytes.
2350 int64_t value = 0;
2351 if (IsInt64AndGet(offset, /*out*/ &value)) {
2352 uint32_t start_offset =
2353 HiddenOffset(type, is_string_char_at) + (value + peeling) * DataType::Size(type);
2354 return Alignment(BaseAlignment(), start_offset & (BaseAlignment() - 1u));
2355 }
2356 // Otherwise, the Android runtime guarantees at least natural alignment.
2357 return Alignment(DataType::Size(type), 0);
2358}
2359
2360void HLoopOptimization::SetAlignmentStrategy(uint32_t peeling_votes[],
2361 const ArrayReference* peeling_candidate) {
2362 // Current heuristic: pick the best static loop peeling factor, if any,
2363 // or otherwise use dynamic loop peeling on suggested peeling candidate.
2364 uint32_t max_vote = 0;
2365 for (int32_t i = 0; i < 16; i++) {
2366 if (peeling_votes[i] > max_vote) {
2367 max_vote = peeling_votes[i];
2368 vector_static_peeling_factor_ = i;
2369 }
2370 }
2371 if (max_vote == 0) {
2372 vector_dynamic_peeling_candidate_ = peeling_candidate;
2373 }
2374}
2375
2376uint32_t HLoopOptimization::MaxNumberPeeled() {
2377 if (vector_dynamic_peeling_candidate_ != nullptr) {
2378 return vector_length_ - 1u; // worst-case
2379 }
2380 return vector_static_peeling_factor_; // known exactly
2381}
2382
Aart Bik14a68b42017-06-08 14:06:58 -07002383bool HLoopOptimization::IsVectorizationProfitable(int64_t trip_count) {
Aart Bik38a3f212017-10-20 17:02:21 -07002384 // Current heuristic: non-empty body with sufficient number of iterations (if known).
Aart Bik14a68b42017-06-08 14:06:58 -07002385 // TODO: refine by looking at e.g. operation count, alignment, etc.
Aart Bik38a3f212017-10-20 17:02:21 -07002386 // TODO: trip count is really unsigned entity, provided the guarding test
2387 // is satisfied; deal with this more carefully later
2388 uint32_t max_peel = MaxNumberPeeled();
Aart Bik14a68b42017-06-08 14:06:58 -07002389 if (vector_length_ == 0) {
2390 return false; // nothing found
Aart Bik38a3f212017-10-20 17:02:21 -07002391 } else if (trip_count < 0) {
2392 return false; // guard against non-taken/large
2393 } else if ((0 < trip_count) && (trip_count < (vector_length_ + max_peel))) {
Aart Bik14a68b42017-06-08 14:06:58 -07002394 return false; // insufficient iterations
2395 }
2396 return true;
2397}
2398
Aart Bik14a68b42017-06-08 14:06:58 -07002399//
Aart Bikf8f5a162017-02-06 15:35:29 -08002400// Helpers.
2401//
2402
2403bool HLoopOptimization::TrySetPhiInduction(HPhi* phi, bool restrict_uses) {
Aart Bikb29f6842017-07-28 15:58:41 -07002404 // Start with empty phi induction.
2405 iset_->clear();
2406
Nicolas Geoffrayf57c1ae2017-06-28 17:40:18 +01002407 // Special case Phis that have equivalent in a debuggable setup. Our graph checker isn't
2408 // smart enough to follow strongly connected components (and it's probably not worth
2409 // it to make it so). See b/33775412.
2410 if (graph_->IsDebuggable() && phi->HasEquivalentPhi()) {
2411 return false;
2412 }
Aart Bikb29f6842017-07-28 15:58:41 -07002413
2414 // Lookup phi induction cycle.
Aart Bikcc42be02016-10-20 16:14:16 -07002415 ArenaSet<HInstruction*>* set = induction_range_.LookupCycle(phi);
2416 if (set != nullptr) {
2417 for (HInstruction* i : *set) {
Aart Bike3dedc52016-11-02 17:50:27 -07002418 // Check that, other than instructions that are no longer in the graph (removed earlier)
Aart Bikf8f5a162017-02-06 15:35:29 -08002419 // each instruction is removable and, when restrict uses are requested, other than for phi,
2420 // all uses are contained within the cycle.
Aart Bike3dedc52016-11-02 17:50:27 -07002421 if (!i->IsInBlock()) {
2422 continue;
2423 } else if (!i->IsRemovable()) {
2424 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08002425 } else if (i != phi && restrict_uses) {
Aart Bikb29f6842017-07-28 15:58:41 -07002426 // Deal with regular uses.
Aart Bikcc42be02016-10-20 16:14:16 -07002427 for (const HUseListNode<HInstruction*>& use : i->GetUses()) {
2428 if (set->find(use.GetUser()) == set->end()) {
2429 return false;
2430 }
2431 }
2432 }
Aart Bike3dedc52016-11-02 17:50:27 -07002433 iset_->insert(i); // copy
Aart Bikcc42be02016-10-20 16:14:16 -07002434 }
Aart Bikcc42be02016-10-20 16:14:16 -07002435 return true;
2436 }
2437 return false;
2438}
2439
Aart Bikb29f6842017-07-28 15:58:41 -07002440bool HLoopOptimization::TrySetPhiReduction(HPhi* phi) {
Aart Bikcc42be02016-10-20 16:14:16 -07002441 DCHECK(iset_->empty());
Aart Bikb29f6842017-07-28 15:58:41 -07002442 // Only unclassified phi cycles are candidates for reductions.
2443 if (induction_range_.IsClassified(phi)) {
2444 return false;
2445 }
2446 // Accept operations like x = x + .., provided that the phi and the reduction are
2447 // used exactly once inside the loop, and by each other.
2448 HInputsRef inputs = phi->GetInputs();
2449 if (inputs.size() == 2) {
2450 HInstruction* reduction = inputs[1];
2451 if (HasReductionFormat(reduction, phi)) {
2452 HLoopInformation* loop_info = phi->GetBlock()->GetLoopInformation();
Aart Bik38a3f212017-10-20 17:02:21 -07002453 uint32_t use_count = 0;
Aart Bikb29f6842017-07-28 15:58:41 -07002454 bool single_use_inside_loop =
2455 // Reduction update only used by phi.
2456 reduction->GetUses().HasExactlyOneElement() &&
2457 !reduction->HasEnvironmentUses() &&
2458 // Reduction update is only use of phi inside the loop.
2459 IsOnlyUsedAfterLoop(loop_info, phi, /*collect_loop_uses*/ true, &use_count) &&
2460 iset_->size() == 1;
2461 iset_->clear(); // leave the way you found it
2462 if (single_use_inside_loop) {
2463 // Link reduction back, and start recording feed value.
2464 reductions_->Put(reduction, phi);
2465 reductions_->Put(phi, phi->InputAt(0));
2466 return true;
2467 }
2468 }
2469 }
2470 return false;
2471}
2472
2473bool HLoopOptimization::TrySetSimpleLoopHeader(HBasicBlock* block, /*out*/ HPhi** main_phi) {
2474 // Start with empty phi induction and reductions.
2475 iset_->clear();
2476 reductions_->clear();
2477
2478 // Scan the phis to find the following (the induction structure has already
2479 // been optimized, so we don't need to worry about trivial cases):
2480 // (1) optional reductions in loop,
2481 // (2) the main induction, used in loop control.
2482 HPhi* phi = nullptr;
2483 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
2484 if (TrySetPhiReduction(it.Current()->AsPhi())) {
2485 continue;
2486 } else if (phi == nullptr) {
2487 // Found the first candidate for main induction.
2488 phi = it.Current()->AsPhi();
2489 } else {
2490 return false;
2491 }
2492 }
2493
2494 // Then test for a typical loopheader:
2495 // s: SuspendCheck
2496 // c: Condition(phi, bound)
2497 // i: If(c)
2498 if (phi != nullptr && TrySetPhiInduction(phi, /*restrict_uses*/ false)) {
Aart Bikcc42be02016-10-20 16:14:16 -07002499 HInstruction* s = block->GetFirstInstruction();
2500 if (s != nullptr && s->IsSuspendCheck()) {
2501 HInstruction* c = s->GetNext();
Aart Bikd86c0852017-04-14 12:00:15 -07002502 if (c != nullptr &&
2503 c->IsCondition() &&
2504 c->GetUses().HasExactlyOneElement() && // only used for termination
2505 !c->HasEnvironmentUses()) { // unlikely, but not impossible
Aart Bikcc42be02016-10-20 16:14:16 -07002506 HInstruction* i = c->GetNext();
2507 if (i != nullptr && i->IsIf() && i->InputAt(0) == c) {
2508 iset_->insert(c);
2509 iset_->insert(s);
Aart Bikb29f6842017-07-28 15:58:41 -07002510 *main_phi = phi;
Aart Bikcc42be02016-10-20 16:14:16 -07002511 return true;
2512 }
2513 }
2514 }
2515 }
2516 return false;
2517}
2518
2519bool HLoopOptimization::IsEmptyBody(HBasicBlock* block) {
Aart Bikf8f5a162017-02-06 15:35:29 -08002520 if (!block->GetPhis().IsEmpty()) {
2521 return false;
2522 }
2523 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
2524 HInstruction* instruction = it.Current();
2525 if (!instruction->IsGoto() && iset_->find(instruction) == iset_->end()) {
2526 return false;
Aart Bikcc42be02016-10-20 16:14:16 -07002527 }
Aart Bikf8f5a162017-02-06 15:35:29 -08002528 }
2529 return true;
2530}
2531
2532bool HLoopOptimization::IsUsedOutsideLoop(HLoopInformation* loop_info,
2533 HInstruction* instruction) {
Aart Bikb29f6842017-07-28 15:58:41 -07002534 // Deal with regular uses.
Aart Bikf8f5a162017-02-06 15:35:29 -08002535 for (const HUseListNode<HInstruction*>& use : instruction->GetUses()) {
2536 if (use.GetUser()->GetBlock()->GetLoopInformation() != loop_info) {
2537 return true;
2538 }
Aart Bikcc42be02016-10-20 16:14:16 -07002539 }
2540 return false;
2541}
2542
Aart Bik482095d2016-10-10 15:39:10 -07002543bool HLoopOptimization::IsOnlyUsedAfterLoop(HLoopInformation* loop_info,
Aart Bik8c4a8542016-10-06 11:36:57 -07002544 HInstruction* instruction,
Aart Bik6b69e0a2017-01-11 10:20:43 -08002545 bool collect_loop_uses,
Aart Bik38a3f212017-10-20 17:02:21 -07002546 /*out*/ uint32_t* use_count) {
Aart Bikb29f6842017-07-28 15:58:41 -07002547 // Deal with regular uses.
Aart Bik8c4a8542016-10-06 11:36:57 -07002548 for (const HUseListNode<HInstruction*>& use : instruction->GetUses()) {
2549 HInstruction* user = use.GetUser();
2550 if (iset_->find(user) == iset_->end()) { // not excluded?
2551 HLoopInformation* other_loop_info = user->GetBlock()->GetLoopInformation();
Aart Bik482095d2016-10-10 15:39:10 -07002552 if (other_loop_info != nullptr && other_loop_info->IsIn(*loop_info)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -08002553 // If collect_loop_uses is set, simply keep adding those uses to the set.
2554 // Otherwise, reject uses inside the loop that were not already in the set.
2555 if (collect_loop_uses) {
2556 iset_->insert(user);
2557 continue;
2558 }
Aart Bik8c4a8542016-10-06 11:36:57 -07002559 return false;
2560 }
2561 ++*use_count;
2562 }
2563 }
2564 return true;
2565}
2566
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002567bool HLoopOptimization::TryReplaceWithLastValue(HLoopInformation* loop_info,
2568 HInstruction* instruction,
2569 HBasicBlock* block) {
2570 // Try to replace outside uses with the last value.
Aart Bik807868e2016-11-03 17:51:43 -07002571 if (induction_range_.CanGenerateLastValue(instruction)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -08002572 HInstruction* replacement = induction_range_.GenerateLastValue(instruction, graph_, block);
Aart Bikb29f6842017-07-28 15:58:41 -07002573 // Deal with regular uses.
Aart Bik6b69e0a2017-01-11 10:20:43 -08002574 const HUseList<HInstruction*>& uses = instruction->GetUses();
2575 for (auto it = uses.begin(), end = uses.end(); it != end;) {
2576 HInstruction* user = it->GetUser();
2577 size_t index = it->GetIndex();
2578 ++it; // increment before replacing
2579 if (iset_->find(user) == iset_->end()) { // not excluded?
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002580 if (kIsDebugBuild) {
2581 // We have checked earlier in 'IsOnlyUsedAfterLoop' that the use is after the loop.
2582 HLoopInformation* other_loop_info = user->GetBlock()->GetLoopInformation();
2583 CHECK(other_loop_info == nullptr || !other_loop_info->IsIn(*loop_info));
2584 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08002585 user->ReplaceInput(replacement, index);
2586 induction_range_.Replace(user, instruction, replacement); // update induction
2587 }
2588 }
Aart Bikb29f6842017-07-28 15:58:41 -07002589 // Deal with environment uses.
Aart Bik6b69e0a2017-01-11 10:20:43 -08002590 const HUseList<HEnvironment*>& env_uses = instruction->GetEnvUses();
2591 for (auto it = env_uses.begin(), end = env_uses.end(); it != end;) {
2592 HEnvironment* user = it->GetUser();
2593 size_t index = it->GetIndex();
2594 ++it; // increment before replacing
2595 if (iset_->find(user->GetHolder()) == iset_->end()) { // not excluded?
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002596 // Only update environment uses after the loop.
Aart Bik14a68b42017-06-08 14:06:58 -07002597 HLoopInformation* other_loop_info = user->GetHolder()->GetBlock()->GetLoopInformation();
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002598 if (other_loop_info == nullptr || !other_loop_info->IsIn(*loop_info)) {
2599 user->RemoveAsUserOfInput(index);
2600 user->SetRawEnvAt(index, replacement);
2601 replacement->AddEnvUseAt(user, index);
2602 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08002603 }
2604 }
Aart Bik807868e2016-11-03 17:51:43 -07002605 return true;
Aart Bik8c4a8542016-10-06 11:36:57 -07002606 }
Aart Bik807868e2016-11-03 17:51:43 -07002607 return false;
Aart Bik8c4a8542016-10-06 11:36:57 -07002608}
2609
Aart Bikf8f5a162017-02-06 15:35:29 -08002610bool HLoopOptimization::TryAssignLastValue(HLoopInformation* loop_info,
2611 HInstruction* instruction,
2612 HBasicBlock* block,
2613 bool collect_loop_uses) {
2614 // Assigning the last value is always successful if there are no uses.
2615 // Otherwise, it succeeds in a no early-exit loop by generating the
2616 // proper last value assignment.
Aart Bik38a3f212017-10-20 17:02:21 -07002617 uint32_t use_count = 0;
Aart Bikf8f5a162017-02-06 15:35:29 -08002618 return IsOnlyUsedAfterLoop(loop_info, instruction, collect_loop_uses, &use_count) &&
2619 (use_count == 0 ||
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002620 (!IsEarlyExit(loop_info) && TryReplaceWithLastValue(loop_info, instruction, block)));
Aart Bikf8f5a162017-02-06 15:35:29 -08002621}
2622
Aart Bik6b69e0a2017-01-11 10:20:43 -08002623void HLoopOptimization::RemoveDeadInstructions(const HInstructionList& list) {
2624 for (HBackwardInstructionIterator i(list); !i.Done(); i.Advance()) {
2625 HInstruction* instruction = i.Current();
2626 if (instruction->IsDeadAndRemovable()) {
2627 simplified_ = true;
2628 instruction->GetBlock()->RemoveInstructionOrPhi(instruction);
2629 }
2630 }
2631}
2632
Aart Bik14a68b42017-06-08 14:06:58 -07002633bool HLoopOptimization::CanRemoveCycle() {
2634 for (HInstruction* i : *iset_) {
2635 // We can never remove instructions that have environment
2636 // uses when we compile 'debuggable'.
2637 if (i->HasEnvironmentUses() && graph_->IsDebuggable()) {
2638 return false;
2639 }
2640 // A deoptimization should never have an environment input removed.
2641 for (const HUseListNode<HEnvironment*>& use : i->GetEnvUses()) {
2642 if (use.GetUser()->GetHolder()->IsDeoptimize()) {
2643 return false;
2644 }
2645 }
2646 }
2647 return true;
2648}
2649
Aart Bik281c6812016-08-26 11:31:48 -07002650} // namespace art