blob: c0c721de63ee3b05dc0e520f6027c8c87b28ef7c [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;
1356 if (TrySetVectorType(type, &restrictions) &&
1357 node->loop_info->IsDefinedOutOfTheLoop(base) &&
Aart Bik37dc4df2017-06-28 14:08:00 -07001358 induction_range_.IsUnitStride(instruction, index, graph_, &offset) &&
Aart Bikf8f5a162017-02-06 15:35:29 -08001359 VectorizeUse(node, value, generate_code, type, restrictions)) {
1360 if (generate_code) {
1361 GenerateVecSub(index, offset);
Aart Bik14a68b42017-06-08 14:06:58 -07001362 GenerateVecMem(instruction, vector_map_->Get(index), vector_map_->Get(value), offset, type);
Aart Bikf8f5a162017-02-06 15:35:29 -08001363 } else {
1364 vector_refs_->insert(ArrayReference(base, offset, type, /*lhs*/ true));
1365 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08001366 return true;
1367 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001368 return false;
1369 }
Aart Bik0148de42017-09-05 09:25:01 -07001370 // Accept a left-hand-side reduction for
1371 // (1) supported vector type,
1372 // (2) vectorizable right-hand-side value.
1373 auto redit = reductions_->find(instruction);
1374 if (redit != reductions_->end()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001375 DataType::Type type = instruction->GetType();
Aart Bikdbbac8f2017-09-01 13:06:08 -07001376 // Recognize SAD idiom or direct reduction.
1377 if (VectorizeSADIdiom(node, instruction, generate_code, type, restrictions) ||
1378 (TrySetVectorType(type, &restrictions) &&
1379 VectorizeUse(node, instruction, generate_code, type, restrictions))) {
Aart Bik0148de42017-09-05 09:25:01 -07001380 if (generate_code) {
1381 HInstruction* new_red = vector_map_->Get(instruction);
1382 vector_permanent_map_->Put(new_red, vector_map_->Get(redit->second));
1383 vector_permanent_map_->Overwrite(redit->second, new_red);
1384 }
1385 return true;
1386 }
1387 return false;
1388 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001389 // Branch back okay.
1390 if (instruction->IsGoto()) {
1391 return true;
1392 }
1393 // Otherwise accept only expressions with no effects outside the immediate loop-body.
1394 // Note that actual uses are inspected during right-hand-side tree traversal.
1395 return !IsUsedOutsideLoop(node->loop_info, instruction) && !instruction->DoesAnyWrite();
1396}
1397
Aart Bikf8f5a162017-02-06 15:35:29 -08001398bool HLoopOptimization::VectorizeUse(LoopNode* node,
1399 HInstruction* instruction,
1400 bool generate_code,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001401 DataType::Type type,
Aart Bikf8f5a162017-02-06 15:35:29 -08001402 uint64_t restrictions) {
1403 // Accept anything for which code has already been generated.
1404 if (generate_code) {
1405 if (vector_map_->find(instruction) != vector_map_->end()) {
1406 return true;
1407 }
1408 }
1409 // Continue the right-hand-side tree traversal, passing in proper
1410 // types and vector restrictions along the way. During code generation,
1411 // all new nodes are drawn from the global allocator.
1412 if (node->loop_info->IsDefinedOutOfTheLoop(instruction)) {
1413 // Accept invariant use, using scalar expansion.
1414 if (generate_code) {
1415 GenerateVecInv(instruction, type);
1416 }
1417 return true;
1418 } else if (instruction->IsArrayGet()) {
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001419 // Deal with vector restrictions.
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001420 bool is_string_char_at = instruction->AsArrayGet()->IsStringCharAt();
1421 if (is_string_char_at && HasVectorRestrictions(restrictions, kNoStringCharAt)) {
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001422 return false;
1423 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001424 // Accept a right-hand-side array base[index] for
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001425 // (1) matching vector type (exact match or signed/unsigned integral type of the same size),
Aart Bikf8f5a162017-02-06 15:35:29 -08001426 // (2) loop-invariant base,
1427 // (3) unit stride index,
1428 // (4) vectorizable right-hand-side value.
1429 HInstruction* base = instruction->InputAt(0);
1430 HInstruction* index = instruction->InputAt(1);
1431 HInstruction* offset = nullptr;
Aart Bik46b6dbc2017-10-03 11:37:37 -07001432 if (HVecOperation::ToSignedType(type) == HVecOperation::ToSignedType(instruction->GetType()) &&
Aart Bikf8f5a162017-02-06 15:35:29 -08001433 node->loop_info->IsDefinedOutOfTheLoop(base) &&
Aart Bik37dc4df2017-06-28 14:08:00 -07001434 induction_range_.IsUnitStride(instruction, index, graph_, &offset)) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001435 if (generate_code) {
1436 GenerateVecSub(index, offset);
Aart Bik14a68b42017-06-08 14:06:58 -07001437 GenerateVecMem(instruction, vector_map_->Get(index), nullptr, offset, type);
Aart Bikf8f5a162017-02-06 15:35:29 -08001438 } else {
Aart Bik38a3f212017-10-20 17:02:21 -07001439 vector_refs_->insert(ArrayReference(base, offset, type, /*lhs*/ false, is_string_char_at));
Aart Bikf8f5a162017-02-06 15:35:29 -08001440 }
1441 return true;
1442 }
Aart Bik0148de42017-09-05 09:25:01 -07001443 } else if (instruction->IsPhi()) {
1444 // Accept particular phi operations.
1445 if (reductions_->find(instruction) != reductions_->end()) {
1446 // Deal with vector restrictions.
1447 if (HasVectorRestrictions(restrictions, kNoReduction)) {
1448 return false;
1449 }
1450 // Accept a reduction.
1451 if (generate_code) {
1452 GenerateVecReductionPhi(instruction->AsPhi());
1453 }
1454 return true;
1455 }
1456 // TODO: accept right-hand-side induction?
1457 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001458 } else if (instruction->IsTypeConversion()) {
1459 // Accept particular type conversions.
1460 HTypeConversion* conversion = instruction->AsTypeConversion();
1461 HInstruction* opa = conversion->InputAt(0);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001462 DataType::Type from = conversion->GetInputType();
1463 DataType::Type to = conversion->GetResultType();
1464 if (DataType::IsIntegralType(from) && DataType::IsIntegralType(to)) {
Aart Bik38a3f212017-10-20 17:02:21 -07001465 uint32_t size_vec = DataType::Size(type);
1466 uint32_t size_from = DataType::Size(from);
1467 uint32_t size_to = DataType::Size(to);
Aart Bikdbbac8f2017-09-01 13:06:08 -07001468 // Accept an integral conversion
1469 // (1a) narrowing into vector type, "wider" operations cannot bring in higher order bits, or
1470 // (1b) widening from at least vector type, and
1471 // (2) vectorizable operand.
1472 if ((size_to < size_from &&
1473 size_to == size_vec &&
1474 VectorizeUse(node, opa, generate_code, type, restrictions | kNoHiBits)) ||
1475 (size_to >= size_from &&
1476 size_from >= size_vec &&
Aart Bik4d1a9d42017-10-19 14:40:55 -07001477 VectorizeUse(node, opa, generate_code, type, restrictions))) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001478 if (generate_code) {
1479 if (vector_mode_ == kVector) {
1480 vector_map_->Put(instruction, vector_map_->Get(opa)); // operand pass-through
1481 } else {
1482 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1483 }
1484 }
1485 return true;
1486 }
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001487 } else if (to == DataType::Type::kFloat32 && from == DataType::Type::kInt32) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001488 DCHECK_EQ(to, type);
1489 // Accept int to float conversion for
1490 // (1) supported int,
1491 // (2) vectorizable operand.
1492 if (TrySetVectorType(from, &restrictions) &&
1493 VectorizeUse(node, opa, generate_code, from, restrictions)) {
1494 if (generate_code) {
1495 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1496 }
1497 return true;
1498 }
1499 }
1500 return false;
1501 } else if (instruction->IsNeg() || instruction->IsNot() || instruction->IsBooleanNot()) {
1502 // Accept unary operator for vectorizable operand.
1503 HInstruction* opa = instruction->InputAt(0);
1504 if (VectorizeUse(node, opa, generate_code, type, restrictions)) {
1505 if (generate_code) {
1506 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1507 }
1508 return true;
1509 }
1510 } else if (instruction->IsAdd() || instruction->IsSub() ||
1511 instruction->IsMul() || instruction->IsDiv() ||
1512 instruction->IsAnd() || instruction->IsOr() || instruction->IsXor()) {
1513 // Deal with vector restrictions.
1514 if ((instruction->IsMul() && HasVectorRestrictions(restrictions, kNoMul)) ||
1515 (instruction->IsDiv() && HasVectorRestrictions(restrictions, kNoDiv))) {
1516 return false;
1517 }
1518 // Accept binary operator for vectorizable operands.
1519 HInstruction* opa = instruction->InputAt(0);
1520 HInstruction* opb = instruction->InputAt(1);
1521 if (VectorizeUse(node, opa, generate_code, type, restrictions) &&
1522 VectorizeUse(node, opb, generate_code, type, restrictions)) {
1523 if (generate_code) {
1524 GenerateVecOp(instruction, vector_map_->Get(opa), vector_map_->Get(opb), type);
1525 }
1526 return true;
1527 }
1528 } else if (instruction->IsShl() || instruction->IsShr() || instruction->IsUShr()) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001529 // Recognize halving add idiom.
Aart Bikf3e61ee2017-04-12 17:09:20 -07001530 if (VectorizeHalvingAddIdiom(node, instruction, generate_code, type, restrictions)) {
1531 return true;
1532 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001533 // Deal with vector restrictions.
Aart Bik304c8a52017-05-23 11:01:13 -07001534 HInstruction* opa = instruction->InputAt(0);
1535 HInstruction* opb = instruction->InputAt(1);
1536 HInstruction* r = opa;
1537 bool is_unsigned = false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001538 if ((HasVectorRestrictions(restrictions, kNoShift)) ||
1539 (instruction->IsShr() && HasVectorRestrictions(restrictions, kNoShr))) {
1540 return false; // unsupported instruction
Aart Bik304c8a52017-05-23 11:01:13 -07001541 } else if (HasVectorRestrictions(restrictions, kNoHiBits)) {
1542 // Shifts right need extra care to account for higher order bits.
1543 // TODO: less likely shr/unsigned and ushr/signed can by flipping signess.
1544 if (instruction->IsShr() &&
1545 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || is_unsigned)) {
1546 return false; // reject, unless all operands are sign-extension narrower
1547 } else if (instruction->IsUShr() &&
1548 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || !is_unsigned)) {
1549 return false; // reject, unless all operands are zero-extension narrower
1550 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001551 }
1552 // Accept shift operator for vectorizable/invariant operands.
1553 // TODO: accept symbolic, albeit loop invariant shift factors.
Aart Bik304c8a52017-05-23 11:01:13 -07001554 DCHECK(r != nullptr);
1555 if (generate_code && vector_mode_ != kVector) { // de-idiom
1556 r = opa;
1557 }
Aart Bik50e20d52017-05-05 14:07:29 -07001558 int64_t distance = 0;
Aart Bik304c8a52017-05-23 11:01:13 -07001559 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
Aart Bik50e20d52017-05-05 14:07:29 -07001560 IsInt64AndGet(opb, /*out*/ &distance)) {
Aart Bik65ffd8e2017-05-01 16:50:45 -07001561 // Restrict shift distance to packed data type width.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001562 int64_t max_distance = DataType::Size(type) * 8;
Aart Bik65ffd8e2017-05-01 16:50:45 -07001563 if (0 <= distance && distance < max_distance) {
1564 if (generate_code) {
Aart Bik304c8a52017-05-23 11:01:13 -07001565 GenerateVecOp(instruction, vector_map_->Get(r), opb, type);
Aart Bik65ffd8e2017-05-01 16:50:45 -07001566 }
1567 return true;
Aart Bikf8f5a162017-02-06 15:35:29 -08001568 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001569 }
Aart Bik3b2a5952018-03-05 13:55:28 -08001570 } else if (instruction->IsAbs()) {
1571 // Deal with vector restrictions.
1572 HInstruction* opa = instruction->InputAt(0);
1573 HInstruction* r = opa;
1574 bool is_unsigned = false;
1575 if (HasVectorRestrictions(restrictions, kNoAbs)) {
1576 return false;
1577 } else if (HasVectorRestrictions(restrictions, kNoHiBits) &&
1578 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || is_unsigned)) {
1579 return false; // reject, unless operand is sign-extension narrower
1580 }
1581 // Accept ABS(x) for vectorizable operand.
1582 DCHECK(r != nullptr);
1583 if (generate_code && vector_mode_ != kVector) { // de-idiom
1584 r = opa;
1585 }
1586 if (VectorizeUse(node, r, generate_code, type, restrictions)) {
1587 if (generate_code) {
1588 GenerateVecOp(instruction,
1589 vector_map_->Get(r),
1590 nullptr,
1591 HVecOperation::ToProperType(type, is_unsigned));
1592 }
1593 return true;
1594 }
Aart Bik1f8d51b2018-02-15 10:42:37 -08001595 } else if (instruction->IsMin() || instruction->IsMax()) {
Aart Bik29aa0822018-03-08 11:28:00 -08001596 // Recognize saturation arithmetic.
1597 if (VectorizeSaturationIdiom(node, instruction, generate_code, type, restrictions)) {
1598 return true;
1599 }
Aart Bik1f8d51b2018-02-15 10:42:37 -08001600 // Deal with vector restrictions.
1601 HInstruction* opa = instruction->InputAt(0);
1602 HInstruction* opb = instruction->InputAt(1);
1603 HInstruction* r = opa;
1604 HInstruction* s = opb;
1605 bool is_unsigned = false;
1606 if (HasVectorRestrictions(restrictions, kNoMinMax)) {
1607 return false;
1608 } else if (HasVectorRestrictions(restrictions, kNoHiBits) &&
1609 !IsNarrowerOperands(opa, opb, type, &r, &s, &is_unsigned)) {
1610 return false; // reject, unless all operands are same-extension narrower
1611 }
1612 // Accept MIN/MAX(x, y) for vectorizable operands.
Nicolas Geoffraya3e23262018-03-28 11:15:12 +00001613 DCHECK(r != nullptr && s != nullptr);
Aart Bik1f8d51b2018-02-15 10:42:37 -08001614 if (generate_code && vector_mode_ != kVector) { // de-idiom
1615 r = opa;
1616 s = opb;
1617 }
1618 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
1619 VectorizeUse(node, s, generate_code, type, restrictions)) {
1620 if (generate_code) {
1621 GenerateVecOp(
1622 instruction, vector_map_->Get(r), vector_map_->Get(s), type, is_unsigned);
Aart Bikc8e93c72017-05-10 10:49:22 -07001623 }
Aart Bik1f8d51b2018-02-15 10:42:37 -08001624 return true;
1625 }
Aart Bik281c6812016-08-26 11:31:48 -07001626 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08001627 return false;
Aart Bik281c6812016-08-26 11:31:48 -07001628}
1629
Aart Bik38a3f212017-10-20 17:02:21 -07001630uint32_t HLoopOptimization::GetVectorSizeInBytes() {
1631 switch (compiler_driver_->GetInstructionSet()) {
Vladimir Marko33bff252017-11-01 14:35:42 +00001632 case InstructionSet::kArm:
1633 case InstructionSet::kThumb2:
Aart Bik38a3f212017-10-20 17:02:21 -07001634 return 8; // 64-bit SIMD
1635 default:
1636 return 16; // 128-bit SIMD
1637 }
1638}
1639
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001640bool HLoopOptimization::TrySetVectorType(DataType::Type type, uint64_t* restrictions) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001641 const InstructionSetFeatures* features = compiler_driver_->GetInstructionSetFeatures();
1642 switch (compiler_driver_->GetInstructionSet()) {
Vladimir Marko33bff252017-11-01 14:35:42 +00001643 case InstructionSet::kArm:
1644 case InstructionSet::kThumb2:
Artem Serov8f7c4102017-06-21 11:21:37 +01001645 // Allow vectorization for all ARM devices, because Android assumes that
Aart Bikb29f6842017-07-28 15:58:41 -07001646 // ARM 32-bit always supports advanced SIMD (64-bit SIMD).
Artem Serov8f7c4102017-06-21 11:21:37 +01001647 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001648 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001649 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001650 case DataType::Type::kInt8:
Aart Bik0148de42017-09-05 09:25:01 -07001651 *restrictions |= kNoDiv | kNoReduction;
Artem Serov8f7c4102017-06-21 11:21:37 +01001652 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001653 case DataType::Type::kUint16:
1654 case DataType::Type::kInt16:
Aart Bik0148de42017-09-05 09:25:01 -07001655 *restrictions |= kNoDiv | kNoStringCharAt | kNoReduction;
Artem Serov8f7c4102017-06-21 11:21:37 +01001656 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001657 case DataType::Type::kInt32:
Artem Serov6e9b1372017-10-05 16:48:30 +01001658 *restrictions |= kNoDiv | kNoWideSAD;
Artem Serov8f7c4102017-06-21 11:21:37 +01001659 return TrySetVectorLength(2);
1660 default:
1661 break;
1662 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001663 return false;
Vladimir Marko33bff252017-11-01 14:35:42 +00001664 case InstructionSet::kArm64:
Aart Bikf8f5a162017-02-06 15:35:29 -08001665 // Allow vectorization for all ARM devices, because Android assumes that
Aart Bikb29f6842017-07-28 15:58:41 -07001666 // ARMv8 AArch64 always supports advanced SIMD (128-bit SIMD).
Aart Bikf8f5a162017-02-06 15:35:29 -08001667 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001668 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001669 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001670 case DataType::Type::kInt8:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001671 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +01001672 return TrySetVectorLength(16);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001673 case DataType::Type::kUint16:
1674 case DataType::Type::kInt16:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001675 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +01001676 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001677 case DataType::Type::kInt32:
Aart Bikf8f5a162017-02-06 15:35:29 -08001678 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +01001679 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001680 case DataType::Type::kInt64:
Aart Bikc8e93c72017-05-10 10:49:22 -07001681 *restrictions |= kNoDiv | kNoMul | kNoMinMax;
Aart Bikf8f5a162017-02-06 15:35:29 -08001682 return TrySetVectorLength(2);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001683 case DataType::Type::kFloat32:
Aart Bik0148de42017-09-05 09:25:01 -07001684 *restrictions |= kNoReduction;
Artem Serovd4bccf12017-04-03 18:47:32 +01001685 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001686 case DataType::Type::kFloat64:
Aart Bik0148de42017-09-05 09:25:01 -07001687 *restrictions |= kNoReduction;
Aart Bikf8f5a162017-02-06 15:35:29 -08001688 return TrySetVectorLength(2);
1689 default:
1690 return false;
1691 }
Vladimir Marko33bff252017-11-01 14:35:42 +00001692 case InstructionSet::kX86:
1693 case InstructionSet::kX86_64:
Aart Bikb29f6842017-07-28 15:58:41 -07001694 // Allow vectorization for SSE4.1-enabled X86 devices only (128-bit SIMD).
Aart Bikf8f5a162017-02-06 15:35:29 -08001695 if (features->AsX86InstructionSetFeatures()->HasSSE4_1()) {
1696 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001697 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001698 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001699 case DataType::Type::kInt8:
Aart Bik0148de42017-09-05 09:25:01 -07001700 *restrictions |=
Aart Bikdbbac8f2017-09-01 13:06:08 -07001701 kNoMul | kNoDiv | kNoShift | kNoAbs | kNoSignedHAdd | kNoUnroundedHAdd | kNoSAD;
Aart Bikf8f5a162017-02-06 15:35:29 -08001702 return TrySetVectorLength(16);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001703 case DataType::Type::kUint16:
1704 case DataType::Type::kInt16:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001705 *restrictions |= kNoDiv | kNoAbs | kNoSignedHAdd | kNoUnroundedHAdd | kNoSAD;
Aart Bikf8f5a162017-02-06 15:35:29 -08001706 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001707 case DataType::Type::kInt32:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001708 *restrictions |= kNoDiv | kNoSAD;
Aart Bikf8f5a162017-02-06 15:35:29 -08001709 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001710 case DataType::Type::kInt64:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001711 *restrictions |= kNoMul | kNoDiv | kNoShr | kNoAbs | kNoMinMax | kNoSAD;
Aart Bikf8f5a162017-02-06 15:35:29 -08001712 return TrySetVectorLength(2);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001713 case DataType::Type::kFloat32:
Aart Bik0148de42017-09-05 09:25:01 -07001714 *restrictions |= kNoMinMax | kNoReduction; // minmax: -0.0 vs +0.0
Aart Bikf8f5a162017-02-06 15:35:29 -08001715 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001716 case DataType::Type::kFloat64:
Aart Bik0148de42017-09-05 09:25:01 -07001717 *restrictions |= kNoMinMax | kNoReduction; // minmax: -0.0 vs +0.0
Aart Bikf8f5a162017-02-06 15:35:29 -08001718 return TrySetVectorLength(2);
1719 default:
1720 break;
1721 } // switch type
1722 }
1723 return false;
Vladimir Marko33bff252017-11-01 14:35:42 +00001724 case InstructionSet::kMips:
Lena Djokic51765b02017-06-22 13:49:59 +02001725 if (features->AsMipsInstructionSetFeatures()->HasMsa()) {
1726 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001727 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001728 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001729 case DataType::Type::kInt8:
Aart Bik29aa0822018-03-08 11:28:00 -08001730 *restrictions |= kNoDiv | kNoSaturation;
Lena Djokic51765b02017-06-22 13:49:59 +02001731 return TrySetVectorLength(16);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001732 case DataType::Type::kUint16:
1733 case DataType::Type::kInt16:
Aart Bik29aa0822018-03-08 11:28:00 -08001734 *restrictions |= kNoDiv | kNoSaturation | kNoStringCharAt;
Lena Djokic51765b02017-06-22 13:49:59 +02001735 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001736 case DataType::Type::kInt32:
Lena Djokic38e380b2017-10-30 16:17:10 +01001737 *restrictions |= kNoDiv;
Lena Djokic51765b02017-06-22 13:49:59 +02001738 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001739 case DataType::Type::kInt64:
Lena Djokic38e380b2017-10-30 16:17:10 +01001740 *restrictions |= kNoDiv;
Lena Djokic51765b02017-06-22 13:49:59 +02001741 return TrySetVectorLength(2);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001742 case DataType::Type::kFloat32:
Aart Bik0148de42017-09-05 09:25:01 -07001743 *restrictions |= kNoMinMax | kNoReduction; // min/max(x, NaN)
Lena Djokic51765b02017-06-22 13:49:59 +02001744 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001745 case DataType::Type::kFloat64:
Aart Bik0148de42017-09-05 09:25:01 -07001746 *restrictions |= kNoMinMax | kNoReduction; // min/max(x, NaN)
Lena Djokic51765b02017-06-22 13:49:59 +02001747 return TrySetVectorLength(2);
1748 default:
1749 break;
1750 } // switch type
1751 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001752 return false;
Vladimir Marko33bff252017-11-01 14:35:42 +00001753 case InstructionSet::kMips64:
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001754 if (features->AsMips64InstructionSetFeatures()->HasMsa()) {
1755 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001756 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001757 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001758 case DataType::Type::kInt8:
Aart Bik29aa0822018-03-08 11:28:00 -08001759 *restrictions |= kNoDiv | kNoSaturation;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001760 return TrySetVectorLength(16);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001761 case DataType::Type::kUint16:
1762 case DataType::Type::kInt16:
Aart Bik29aa0822018-03-08 11:28:00 -08001763 *restrictions |= kNoDiv | kNoSaturation | kNoStringCharAt;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001764 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001765 case DataType::Type::kInt32:
Lena Djokic38e380b2017-10-30 16:17:10 +01001766 *restrictions |= kNoDiv;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001767 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001768 case DataType::Type::kInt64:
Lena Djokic38e380b2017-10-30 16:17:10 +01001769 *restrictions |= kNoDiv;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001770 return TrySetVectorLength(2);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001771 case DataType::Type::kFloat32:
Aart Bik0148de42017-09-05 09:25:01 -07001772 *restrictions |= kNoMinMax | kNoReduction; // min/max(x, NaN)
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001773 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001774 case DataType::Type::kFloat64:
Aart Bik0148de42017-09-05 09:25:01 -07001775 *restrictions |= kNoMinMax | kNoReduction; // min/max(x, NaN)
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001776 return TrySetVectorLength(2);
1777 default:
1778 break;
1779 } // switch type
1780 }
1781 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001782 default:
1783 return false;
1784 } // switch instruction set
1785}
1786
1787bool HLoopOptimization::TrySetVectorLength(uint32_t length) {
1788 DCHECK(IsPowerOfTwo(length) && length >= 2u);
1789 // First time set?
1790 if (vector_length_ == 0) {
1791 vector_length_ = length;
1792 }
1793 // Different types are acceptable within a loop-body, as long as all the corresponding vector
1794 // lengths match exactly to obtain a uniform traversal through the vector iteration space
1795 // (idiomatic exceptions to this rule can be handled by further unrolling sub-expressions).
1796 return vector_length_ == length;
1797}
1798
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001799void HLoopOptimization::GenerateVecInv(HInstruction* org, DataType::Type type) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001800 if (vector_map_->find(org) == vector_map_->end()) {
1801 // In scalar code, just use a self pass-through for scalar invariants
1802 // (viz. expression remains itself).
1803 if (vector_mode_ == kSequential) {
1804 vector_map_->Put(org, org);
1805 return;
1806 }
1807 // In vector code, explicit scalar expansion is needed.
Aart Bik0148de42017-09-05 09:25:01 -07001808 HInstruction* vector = nullptr;
1809 auto it = vector_permanent_map_->find(org);
1810 if (it != vector_permanent_map_->end()) {
1811 vector = it->second; // reuse during unrolling
1812 } else {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001813 // Generates ReplicateScalar( (optional_type_conv) org ).
1814 HInstruction* input = org;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001815 DataType::Type input_type = input->GetType();
1816 if (type != input_type && (type == DataType::Type::kInt64 ||
1817 input_type == DataType::Type::kInt64)) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001818 input = Insert(vector_preheader_,
1819 new (global_allocator_) HTypeConversion(type, input, kNoDexPc));
1820 }
1821 vector = new (global_allocator_)
Aart Bik46b6dbc2017-10-03 11:37:37 -07001822 HVecReplicateScalar(global_allocator_, input, type, vector_length_, kNoDexPc);
Aart Bik0148de42017-09-05 09:25:01 -07001823 vector_permanent_map_->Put(org, Insert(vector_preheader_, vector));
1824 }
1825 vector_map_->Put(org, vector);
Aart Bikf8f5a162017-02-06 15:35:29 -08001826 }
1827}
1828
1829void HLoopOptimization::GenerateVecSub(HInstruction* org, HInstruction* offset) {
1830 if (vector_map_->find(org) == vector_map_->end()) {
Aart Bik14a68b42017-06-08 14:06:58 -07001831 HInstruction* subscript = vector_index_;
Aart Bik37dc4df2017-06-28 14:08:00 -07001832 int64_t value = 0;
1833 if (!IsInt64AndGet(offset, &value) || value != 0) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001834 subscript = new (global_allocator_) HAdd(DataType::Type::kInt32, subscript, offset);
Aart Bikf8f5a162017-02-06 15:35:29 -08001835 if (org->IsPhi()) {
1836 Insert(vector_body_, subscript); // lacks layout placeholder
1837 }
1838 }
1839 vector_map_->Put(org, subscript);
1840 }
1841}
1842
1843void HLoopOptimization::GenerateVecMem(HInstruction* org,
1844 HInstruction* opa,
1845 HInstruction* opb,
Aart Bik14a68b42017-06-08 14:06:58 -07001846 HInstruction* offset,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001847 DataType::Type type) {
Aart Bik46b6dbc2017-10-03 11:37:37 -07001848 uint32_t dex_pc = org->GetDexPc();
Aart Bikf8f5a162017-02-06 15:35:29 -08001849 HInstruction* vector = nullptr;
1850 if (vector_mode_ == kVector) {
1851 // Vector store or load.
Aart Bik38a3f212017-10-20 17:02:21 -07001852 bool is_string_char_at = false;
Aart Bik14a68b42017-06-08 14:06:58 -07001853 HInstruction* base = org->InputAt(0);
Aart Bikf8f5a162017-02-06 15:35:29 -08001854 if (opb != nullptr) {
1855 vector = new (global_allocator_) HVecStore(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001856 global_allocator_, base, opa, opb, type, org->GetSideEffects(), vector_length_, dex_pc);
Aart Bikf8f5a162017-02-06 15:35:29 -08001857 } else {
Aart Bik38a3f212017-10-20 17:02:21 -07001858 is_string_char_at = org->AsArrayGet()->IsStringCharAt();
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001859 vector = new (global_allocator_) HVecLoad(global_allocator_,
1860 base,
1861 opa,
1862 type,
1863 org->GetSideEffects(),
1864 vector_length_,
Aart Bik46b6dbc2017-10-03 11:37:37 -07001865 is_string_char_at,
1866 dex_pc);
Aart Bik14a68b42017-06-08 14:06:58 -07001867 }
Aart Bik38a3f212017-10-20 17:02:21 -07001868 // Known (forced/adjusted/original) alignment?
1869 if (vector_dynamic_peeling_candidate_ != nullptr) {
1870 if (vector_dynamic_peeling_candidate_->offset == offset && // TODO: diffs too?
1871 DataType::Size(vector_dynamic_peeling_candidate_->type) == DataType::Size(type) &&
1872 vector_dynamic_peeling_candidate_->is_string_char_at == is_string_char_at) {
1873 vector->AsVecMemoryOperation()->SetAlignment( // forced
1874 Alignment(GetVectorSizeInBytes(), 0));
1875 }
1876 } else {
1877 vector->AsVecMemoryOperation()->SetAlignment( // adjusted/original
1878 ComputeAlignment(offset, type, is_string_char_at, vector_static_peeling_factor_));
Aart Bikf8f5a162017-02-06 15:35:29 -08001879 }
1880 } else {
1881 // Scalar store or load.
1882 DCHECK(vector_mode_ == kSequential);
1883 if (opb != nullptr) {
Aart Bik4d1a9d42017-10-19 14:40:55 -07001884 DataType::Type component_type = org->AsArraySet()->GetComponentType();
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001885 vector = new (global_allocator_) HArraySet(
Aart Bik4d1a9d42017-10-19 14:40:55 -07001886 org->InputAt(0), opa, opb, component_type, org->GetSideEffects(), dex_pc);
Aart Bikf8f5a162017-02-06 15:35:29 -08001887 } else {
Aart Bikdb14fcf2017-04-25 15:53:58 -07001888 bool is_string_char_at = org->AsArrayGet()->IsStringCharAt();
1889 vector = new (global_allocator_) HArrayGet(
Aart Bik4d1a9d42017-10-19 14:40:55 -07001890 org->InputAt(0), opa, org->GetType(), org->GetSideEffects(), dex_pc, is_string_char_at);
Aart Bikf8f5a162017-02-06 15:35:29 -08001891 }
1892 }
1893 vector_map_->Put(org, vector);
1894}
1895
Aart Bik0148de42017-09-05 09:25:01 -07001896void HLoopOptimization::GenerateVecReductionPhi(HPhi* phi) {
1897 DCHECK(reductions_->find(phi) != reductions_->end());
1898 DCHECK(reductions_->Get(phi->InputAt(1)) == phi);
1899 HInstruction* vector = nullptr;
1900 if (vector_mode_ == kSequential) {
1901 HPhi* new_phi = new (global_allocator_) HPhi(
1902 global_allocator_, kNoRegNumber, 0, phi->GetType());
1903 vector_header_->AddPhi(new_phi);
1904 vector = new_phi;
1905 } else {
1906 // Link vector reduction back to prior unrolled update, or a first phi.
1907 auto it = vector_permanent_map_->find(phi);
1908 if (it != vector_permanent_map_->end()) {
1909 vector = it->second;
1910 } else {
1911 HPhi* new_phi = new (global_allocator_) HPhi(
1912 global_allocator_, kNoRegNumber, 0, HVecOperation::kSIMDType);
1913 vector_header_->AddPhi(new_phi);
1914 vector = new_phi;
1915 }
1916 }
1917 vector_map_->Put(phi, vector);
1918}
1919
1920void HLoopOptimization::GenerateVecReductionPhiInputs(HPhi* phi, HInstruction* reduction) {
1921 HInstruction* new_phi = vector_map_->Get(phi);
1922 HInstruction* new_init = reductions_->Get(phi);
1923 HInstruction* new_red = vector_map_->Get(reduction);
1924 // Link unrolled vector loop back to new phi.
1925 for (; !new_phi->IsPhi(); new_phi = vector_permanent_map_->Get(new_phi)) {
1926 DCHECK(new_phi->IsVecOperation());
1927 }
1928 // Prepare the new initialization.
1929 if (vector_mode_ == kVector) {
Goran Jakovljevic89b8df02017-10-13 08:33:17 +02001930 // Generate a [initial, 0, .., 0] vector for add or
1931 // a [initial, initial, .., initial] vector for min/max.
Aart Bikdbbac8f2017-09-01 13:06:08 -07001932 HVecOperation* red_vector = new_red->AsVecOperation();
Goran Jakovljevic89b8df02017-10-13 08:33:17 +02001933 HVecReduce::ReductionKind kind = GetReductionKind(red_vector);
Aart Bik38a3f212017-10-20 17:02:21 -07001934 uint32_t vector_length = red_vector->GetVectorLength();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001935 DataType::Type type = red_vector->GetPackedType();
Goran Jakovljevic89b8df02017-10-13 08:33:17 +02001936 if (kind == HVecReduce::ReductionKind::kSum) {
1937 new_init = Insert(vector_preheader_,
1938 new (global_allocator_) HVecSetScalars(global_allocator_,
1939 &new_init,
1940 type,
1941 vector_length,
1942 1,
1943 kNoDexPc));
1944 } else {
1945 new_init = Insert(vector_preheader_,
1946 new (global_allocator_) HVecReplicateScalar(global_allocator_,
1947 new_init,
1948 type,
1949 vector_length,
1950 kNoDexPc));
1951 }
Aart Bik0148de42017-09-05 09:25:01 -07001952 } else {
1953 new_init = ReduceAndExtractIfNeeded(new_init);
1954 }
1955 // Set the phi inputs.
1956 DCHECK(new_phi->IsPhi());
1957 new_phi->AsPhi()->AddInput(new_init);
1958 new_phi->AsPhi()->AddInput(new_red);
1959 // New feed value for next phi (safe mutation in iteration).
1960 reductions_->find(phi)->second = new_phi;
1961}
1962
1963HInstruction* HLoopOptimization::ReduceAndExtractIfNeeded(HInstruction* instruction) {
1964 if (instruction->IsPhi()) {
1965 HInstruction* input = instruction->InputAt(1);
Aart Bik2dd7b672017-12-07 11:11:22 -08001966 if (HVecOperation::ReturnsSIMDValue(input)) {
1967 DCHECK(!input->IsPhi());
Aart Bikdbbac8f2017-09-01 13:06:08 -07001968 HVecOperation* input_vector = input->AsVecOperation();
Aart Bik38a3f212017-10-20 17:02:21 -07001969 uint32_t vector_length = input_vector->GetVectorLength();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001970 DataType::Type type = input_vector->GetPackedType();
Aart Bikdbbac8f2017-09-01 13:06:08 -07001971 HVecReduce::ReductionKind kind = GetReductionKind(input_vector);
Aart Bik0148de42017-09-05 09:25:01 -07001972 HBasicBlock* exit = instruction->GetBlock()->GetSuccessors()[0];
1973 // Generate a vector reduction and scalar extract
1974 // x = REDUCE( [x_1, .., x_n] )
1975 // y = x_1
1976 // along the exit of the defining loop.
Aart Bik0148de42017-09-05 09:25:01 -07001977 HInstruction* reduce = new (global_allocator_) HVecReduce(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001978 global_allocator_, instruction, type, vector_length, kind, kNoDexPc);
Aart Bik0148de42017-09-05 09:25:01 -07001979 exit->InsertInstructionBefore(reduce, exit->GetFirstInstruction());
1980 instruction = new (global_allocator_) HVecExtractScalar(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001981 global_allocator_, reduce, type, vector_length, 0, kNoDexPc);
Aart Bik0148de42017-09-05 09:25:01 -07001982 exit->InsertInstructionAfter(instruction, reduce);
1983 }
1984 }
1985 return instruction;
1986}
1987
Aart Bikf8f5a162017-02-06 15:35:29 -08001988#define GENERATE_VEC(x, y) \
1989 if (vector_mode_ == kVector) { \
1990 vector = (x); \
1991 } else { \
1992 DCHECK(vector_mode_ == kSequential); \
1993 vector = (y); \
1994 } \
1995 break;
1996
1997void HLoopOptimization::GenerateVecOp(HInstruction* org,
1998 HInstruction* opa,
1999 HInstruction* opb,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002000 DataType::Type type,
Aart Bik304c8a52017-05-23 11:01:13 -07002001 bool is_unsigned) {
Aart Bik46b6dbc2017-10-03 11:37:37 -07002002 uint32_t dex_pc = org->GetDexPc();
Aart Bikf8f5a162017-02-06 15:35:29 -08002003 HInstruction* vector = nullptr;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002004 DataType::Type org_type = org->GetType();
Aart Bikf8f5a162017-02-06 15:35:29 -08002005 switch (org->GetKind()) {
2006 case HInstruction::kNeg:
2007 DCHECK(opb == nullptr);
2008 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07002009 new (global_allocator_) HVecNeg(global_allocator_, opa, type, vector_length_, dex_pc),
2010 new (global_allocator_) HNeg(org_type, opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08002011 case HInstruction::kNot:
2012 DCHECK(opb == nullptr);
2013 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07002014 new (global_allocator_) HVecNot(global_allocator_, opa, type, vector_length_, dex_pc),
2015 new (global_allocator_) HNot(org_type, opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08002016 case HInstruction::kBooleanNot:
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_) HBooleanNot(opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08002021 case HInstruction::kTypeConversion:
2022 DCHECK(opb == nullptr);
2023 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07002024 new (global_allocator_) HVecCnv(global_allocator_, opa, type, vector_length_, dex_pc),
2025 new (global_allocator_) HTypeConversion(org_type, opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08002026 case HInstruction::kAdd:
2027 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07002028 new (global_allocator_) HVecAdd(global_allocator_, opa, opb, type, vector_length_, dex_pc),
2029 new (global_allocator_) HAdd(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08002030 case HInstruction::kSub:
2031 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07002032 new (global_allocator_) HVecSub(global_allocator_, opa, opb, type, vector_length_, dex_pc),
2033 new (global_allocator_) HSub(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08002034 case HInstruction::kMul:
2035 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07002036 new (global_allocator_) HVecMul(global_allocator_, opa, opb, type, vector_length_, dex_pc),
2037 new (global_allocator_) HMul(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08002038 case HInstruction::kDiv:
2039 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07002040 new (global_allocator_) HVecDiv(global_allocator_, opa, opb, type, vector_length_, dex_pc),
2041 new (global_allocator_) HDiv(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08002042 case HInstruction::kAnd:
2043 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07002044 new (global_allocator_) HVecAnd(global_allocator_, opa, opb, type, vector_length_, dex_pc),
2045 new (global_allocator_) HAnd(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08002046 case HInstruction::kOr:
2047 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07002048 new (global_allocator_) HVecOr(global_allocator_, opa, opb, type, vector_length_, dex_pc),
2049 new (global_allocator_) HOr(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08002050 case HInstruction::kXor:
2051 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07002052 new (global_allocator_) HVecXor(global_allocator_, opa, opb, type, vector_length_, dex_pc),
2053 new (global_allocator_) HXor(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08002054 case HInstruction::kShl:
2055 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07002056 new (global_allocator_) HVecShl(global_allocator_, opa, opb, type, vector_length_, dex_pc),
2057 new (global_allocator_) HShl(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08002058 case HInstruction::kShr:
2059 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07002060 new (global_allocator_) HVecShr(global_allocator_, opa, opb, type, vector_length_, dex_pc),
2061 new (global_allocator_) HShr(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08002062 case HInstruction::kUShr:
2063 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07002064 new (global_allocator_) HVecUShr(global_allocator_, opa, opb, type, vector_length_, dex_pc),
2065 new (global_allocator_) HUShr(org_type, opa, opb, dex_pc));
Aart Bik1f8d51b2018-02-15 10:42:37 -08002066 case HInstruction::kMin:
2067 GENERATE_VEC(
2068 new (global_allocator_) HVecMin(global_allocator_,
2069 opa,
2070 opb,
2071 HVecOperation::ToProperType(type, is_unsigned),
2072 vector_length_,
2073 dex_pc),
2074 new (global_allocator_) HMin(org_type, opa, opb, dex_pc));
2075 case HInstruction::kMax:
2076 GENERATE_VEC(
2077 new (global_allocator_) HVecMax(global_allocator_,
2078 opa,
2079 opb,
2080 HVecOperation::ToProperType(type, is_unsigned),
2081 vector_length_,
2082 dex_pc),
2083 new (global_allocator_) HMax(org_type, opa, opb, dex_pc));
Aart Bik3b2a5952018-03-05 13:55:28 -08002084 case HInstruction::kAbs:
2085 DCHECK(opb == nullptr);
2086 GENERATE_VEC(
2087 new (global_allocator_) HVecAbs(global_allocator_, opa, type, vector_length_, dex_pc),
2088 new (global_allocator_) HAbs(org_type, opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08002089 default:
2090 break;
2091 } // switch
2092 CHECK(vector != nullptr) << "Unsupported SIMD operator";
2093 vector_map_->Put(org, vector);
2094}
2095
2096#undef GENERATE_VEC
2097
2098//
Aart Bikf3e61ee2017-04-12 17:09:20 -07002099// Vectorization idioms.
2100//
2101
Aart Bik29aa0822018-03-08 11:28:00 -08002102// Method recognizes single and double clipping saturation arithmetic.
2103bool HLoopOptimization::VectorizeSaturationIdiom(LoopNode* node,
2104 HInstruction* instruction,
2105 bool generate_code,
2106 DataType::Type type,
2107 uint64_t restrictions) {
2108 // Deal with vector restrictions.
2109 if (HasVectorRestrictions(restrictions, kNoSaturation)) {
2110 return false;
2111 }
Aart Bik1a381022018-03-15 15:51:37 -07002112 // Restrict type (generalize if one day we generalize allowed MIN/MAX integral types).
2113 if (instruction->GetType() != DataType::Type::kInt32 &&
2114 instruction->GetType() != DataType::Type::kInt64) {
Aart Bik29aa0822018-03-08 11:28:00 -08002115 return false;
2116 }
Nicolas Geoffraya3e23262018-03-28 11:15:12 +00002117 // Clipped addition or subtraction on narrower operands? We will try both
2118 // formats since, e.g., x+c can be interpreted as x+c and x-(-c), depending
2119 // on what clipping values are used, to get most benefits.
Aart Bik1a381022018-03-15 15:51:37 -07002120 int64_t lo = std::numeric_limits<int64_t>::min();
2121 int64_t hi = std::numeric_limits<int64_t>::max();
2122 HInstruction* clippee = FindClippee(instruction, &lo, &hi);
Nicolas Geoffraya3e23262018-03-28 11:15:12 +00002123 HInstruction* a = nullptr;
2124 HInstruction* b = nullptr;
Aart Bik29aa0822018-03-08 11:28:00 -08002125 HInstruction* r = nullptr;
2126 HInstruction* s = nullptr;
2127 bool is_unsigned = false;
Nicolas Geoffraya3e23262018-03-28 11:15:12 +00002128 bool is_add = true;
2129 int64_t c = 0;
2130 // First try for saturated addition.
2131 if (IsAddConst2(graph_, clippee, /*out*/ &a, /*out*/ &b, /*out*/ &c) && c == 0 &&
2132 IsNarrowerOperands(a, b, type, &r, &s, &is_unsigned) &&
2133 IsSaturatedAdd(r, s, type, lo, hi, is_unsigned)) {
2134 is_add = true;
Aart Bik29aa0822018-03-08 11:28:00 -08002135 } else {
Nicolas Geoffraya3e23262018-03-28 11:15:12 +00002136 // Then try again for saturated subtraction.
2137 a = b = r = s = nullptr;
2138 if (IsSubConst2(graph_, clippee, /*out*/ &a, /*out*/ &b) &&
2139 IsNarrowerOperands(a, b, type, &r, &s, &is_unsigned) &&
2140 IsSaturatedSub(r, type, lo, hi, is_unsigned)) {
2141 is_add = false;
2142 } else {
2143 return false;
2144 }
Aart Bik29aa0822018-03-08 11:28:00 -08002145 }
2146 // Accept saturation idiom for vectorizable operands.
Nicolas Geoffraya3e23262018-03-28 11:15:12 +00002147 DCHECK(r != nullptr && s != nullptr);
Aart Bik29aa0822018-03-08 11:28:00 -08002148 if (generate_code && vector_mode_ != kVector) { // de-idiom
2149 r = instruction->InputAt(0);
2150 s = instruction->InputAt(1);
2151 restrictions &= ~(kNoHiBits | kNoMinMax); // allow narrow MIN/MAX in seq
2152 }
2153 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
2154 VectorizeUse(node, s, generate_code, type, restrictions)) {
2155 if (generate_code) {
2156 if (vector_mode_ == kVector) {
2157 DataType::Type vtype = HVecOperation::ToProperType(type, is_unsigned);
2158 HInstruction* op1 = vector_map_->Get(r);
2159 HInstruction* op2 = vector_map_->Get(s);
2160 vector_map_->Put(instruction, is_add
2161 ? reinterpret_cast<HInstruction*>(new (global_allocator_) HVecSaturationAdd(
2162 global_allocator_, op1, op2, vtype, vector_length_, kNoDexPc))
2163 : reinterpret_cast<HInstruction*>(new (global_allocator_) HVecSaturationSub(
2164 global_allocator_, op1, op2, vtype, vector_length_, kNoDexPc)));
2165 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorizedIdiom);
2166 } else {
2167 GenerateVecOp(instruction, vector_map_->Get(r), vector_map_->Get(s), type);
2168 }
2169 }
2170 return true;
2171 }
2172 return false;
2173}
2174
Aart Bikf3e61ee2017-04-12 17:09:20 -07002175// Method recognizes the following idioms:
Aart Bikdbbac8f2017-09-01 13:06:08 -07002176// rounding halving add (a + b + 1) >> 1 for unsigned/signed operands a, b
2177// truncated halving add (a + b) >> 1 for unsigned/signed operands a, b
Aart Bikf3e61ee2017-04-12 17:09:20 -07002178// Provided that the operands are promoted to a wider form to do the arithmetic and
2179// then cast back to narrower form, the idioms can be mapped into efficient SIMD
2180// implementation that operates directly in narrower form (plus one extra bit).
2181// TODO: current version recognizes implicit byte/short/char widening only;
2182// explicit widening from int to long could be added later.
2183bool HLoopOptimization::VectorizeHalvingAddIdiom(LoopNode* node,
2184 HInstruction* instruction,
2185 bool generate_code,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002186 DataType::Type type,
Aart Bikf3e61ee2017-04-12 17:09:20 -07002187 uint64_t restrictions) {
2188 // Test for top level arithmetic shift right x >> 1 or logical shift right x >>> 1
Aart Bik304c8a52017-05-23 11:01:13 -07002189 // (note whether the sign bit in wider precision is shifted in has no effect
Aart Bikf3e61ee2017-04-12 17:09:20 -07002190 // on the narrow precision computed by the idiom).
Aart Bikf3e61ee2017-04-12 17:09:20 -07002191 if ((instruction->IsShr() ||
2192 instruction->IsUShr()) &&
Aart Bik0148de42017-09-05 09:25:01 -07002193 IsInt64Value(instruction->InputAt(1), 1)) {
Aart Bik5f805002017-05-16 16:42:41 -07002194 // Test for (a + b + c) >> 1 for optional constant c.
2195 HInstruction* a = nullptr;
2196 HInstruction* b = nullptr;
2197 int64_t c = 0;
Nicolas Geoffraya3e23262018-03-28 11:15:12 +00002198 if (IsAddConst2(graph_, instruction->InputAt(0), /*out*/ &a, /*out*/ &b, /*out*/ &c)) {
Aart Bik5f805002017-05-16 16:42:41 -07002199 // Accept c == 1 (rounded) or c == 0 (not rounded).
2200 bool is_rounded = false;
2201 if (c == 1) {
2202 is_rounded = true;
2203 } else if (c != 0) {
2204 return false;
2205 }
2206 // Accept consistent zero or sign extension on operands a and b.
Aart Bikf3e61ee2017-04-12 17:09:20 -07002207 HInstruction* r = nullptr;
2208 HInstruction* s = nullptr;
2209 bool is_unsigned = false;
Aart Bik304c8a52017-05-23 11:01:13 -07002210 if (!IsNarrowerOperands(a, b, type, &r, &s, &is_unsigned)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -07002211 return false;
2212 }
2213 // Deal with vector restrictions.
2214 if ((!is_unsigned && HasVectorRestrictions(restrictions, kNoSignedHAdd)) ||
2215 (!is_rounded && HasVectorRestrictions(restrictions, kNoUnroundedHAdd))) {
2216 return false;
2217 }
2218 // Accept recognized halving add for vectorizable operands. Vectorized code uses the
2219 // shorthand idiomatic operation. Sequential code uses the original scalar expressions.
Nicolas Geoffraya3e23262018-03-28 11:15:12 +00002220 DCHECK(r != nullptr && s != nullptr);
Aart Bik304c8a52017-05-23 11:01:13 -07002221 if (generate_code && vector_mode_ != kVector) { // de-idiom
2222 r = instruction->InputAt(0);
2223 s = instruction->InputAt(1);
2224 }
Aart Bikf3e61ee2017-04-12 17:09:20 -07002225 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
2226 VectorizeUse(node, s, generate_code, type, restrictions)) {
2227 if (generate_code) {
2228 if (vector_mode_ == kVector) {
2229 vector_map_->Put(instruction, new (global_allocator_) HVecHalvingAdd(
2230 global_allocator_,
2231 vector_map_->Get(r),
2232 vector_map_->Get(s),
Aart Bik66c158e2018-01-31 12:55:04 -08002233 HVecOperation::ToProperType(type, is_unsigned),
Aart Bikf3e61ee2017-04-12 17:09:20 -07002234 vector_length_,
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01002235 is_rounded,
Aart Bik46b6dbc2017-10-03 11:37:37 -07002236 kNoDexPc));
Aart Bik21b85922017-09-06 13:29:16 -07002237 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorizedIdiom);
Aart Bikf3e61ee2017-04-12 17:09:20 -07002238 } else {
Aart Bik304c8a52017-05-23 11:01:13 -07002239 GenerateVecOp(instruction, vector_map_->Get(r), vector_map_->Get(s), type);
Aart Bikf3e61ee2017-04-12 17:09:20 -07002240 }
2241 }
2242 return true;
2243 }
2244 }
2245 }
2246 return false;
2247}
2248
Aart Bikdbbac8f2017-09-01 13:06:08 -07002249// Method recognizes the following idiom:
2250// q += ABS(a - b) for signed operands a, b
2251// Provided that the operands have the same type or are promoted to a wider form.
2252// Since this may involve a vector length change, the idiom is handled by going directly
2253// to a sad-accumulate node (rather than relying combining finer grained nodes later).
2254// TODO: unsigned SAD too?
2255bool HLoopOptimization::VectorizeSADIdiom(LoopNode* node,
2256 HInstruction* instruction,
2257 bool generate_code,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002258 DataType::Type reduction_type,
Aart Bikdbbac8f2017-09-01 13:06:08 -07002259 uint64_t restrictions) {
2260 // Filter integral "q += ABS(a - b);" reduction, where ABS and SUB
2261 // are done in the same precision (either int or long).
2262 if (!instruction->IsAdd() ||
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002263 (reduction_type != DataType::Type::kInt32 && reduction_type != DataType::Type::kInt64)) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07002264 return false;
2265 }
2266 HInstruction* q = instruction->InputAt(0);
2267 HInstruction* v = instruction->InputAt(1);
2268 HInstruction* a = nullptr;
2269 HInstruction* b = nullptr;
Nicolas Geoffraya3e23262018-03-28 11:15:12 +00002270 if (v->IsAbs() &&
2271 v->GetType() == reduction_type &&
2272 IsSubConst2(graph_, v->InputAt(0), /*out*/ &a, /*out*/ &b)) {
2273 DCHECK(a != nullptr && b != nullptr);
2274 } else {
Aart Bikdbbac8f2017-09-01 13:06:08 -07002275 return false;
2276 }
2277 // Accept same-type or consistent sign extension for narrower-type on operands a and b.
2278 // The same-type or narrower operands are called r (a or lower) and s (b or lower).
Aart Bikdf011c32017-09-28 12:53:04 -07002279 // We inspect the operands carefully to pick the most suited type.
Aart Bikdbbac8f2017-09-01 13:06:08 -07002280 HInstruction* r = a;
2281 HInstruction* s = b;
2282 bool is_unsigned = false;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002283 DataType::Type sub_type = a->GetType();
Aart Bikdf011c32017-09-28 12:53:04 -07002284 if (DataType::Size(b->GetType()) < DataType::Size(sub_type)) {
2285 sub_type = b->GetType();
2286 }
2287 if (a->IsTypeConversion() &&
2288 DataType::Size(a->InputAt(0)->GetType()) < DataType::Size(sub_type)) {
2289 sub_type = a->InputAt(0)->GetType();
2290 }
2291 if (b->IsTypeConversion() &&
2292 DataType::Size(b->InputAt(0)->GetType()) < DataType::Size(sub_type)) {
2293 sub_type = b->InputAt(0)->GetType();
Aart Bikdbbac8f2017-09-01 13:06:08 -07002294 }
2295 if (reduction_type != sub_type &&
2296 (!IsNarrowerOperands(a, b, sub_type, &r, &s, &is_unsigned) || is_unsigned)) {
2297 return false;
2298 }
2299 // Try same/narrower type and deal with vector restrictions.
Artem Serov6e9b1372017-10-05 16:48:30 +01002300 if (!TrySetVectorType(sub_type, &restrictions) ||
2301 HasVectorRestrictions(restrictions, kNoSAD) ||
2302 (reduction_type != sub_type && HasVectorRestrictions(restrictions, kNoWideSAD))) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07002303 return false;
2304 }
2305 // Accept SAD idiom for vectorizable operands. Vectorized code uses the shorthand
2306 // idiomatic operation. Sequential code uses the original scalar expressions.
Nicolas Geoffraya3e23262018-03-28 11:15:12 +00002307 DCHECK(r != nullptr && s != nullptr);
Aart Bikdbbac8f2017-09-01 13:06:08 -07002308 if (generate_code && vector_mode_ != kVector) { // de-idiom
2309 r = s = v->InputAt(0);
2310 }
2311 if (VectorizeUse(node, q, generate_code, sub_type, restrictions) &&
2312 VectorizeUse(node, r, generate_code, sub_type, restrictions) &&
2313 VectorizeUse(node, s, generate_code, sub_type, restrictions)) {
2314 if (generate_code) {
2315 if (vector_mode_ == kVector) {
2316 vector_map_->Put(instruction, new (global_allocator_) HVecSADAccumulate(
2317 global_allocator_,
2318 vector_map_->Get(q),
2319 vector_map_->Get(r),
2320 vector_map_->Get(s),
Aart Bik3b2a5952018-03-05 13:55:28 -08002321 HVecOperation::ToProperType(reduction_type, is_unsigned),
Aart Bik46b6dbc2017-10-03 11:37:37 -07002322 GetOtherVL(reduction_type, sub_type, vector_length_),
2323 kNoDexPc));
Aart Bikdbbac8f2017-09-01 13:06:08 -07002324 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorizedIdiom);
2325 } else {
2326 GenerateVecOp(v, vector_map_->Get(r), nullptr, reduction_type);
2327 GenerateVecOp(instruction, vector_map_->Get(q), vector_map_->Get(v), reduction_type);
2328 }
2329 }
2330 return true;
2331 }
2332 return false;
2333}
2334
Aart Bikf3e61ee2017-04-12 17:09:20 -07002335//
Aart Bik14a68b42017-06-08 14:06:58 -07002336// Vectorization heuristics.
2337//
2338
Aart Bik38a3f212017-10-20 17:02:21 -07002339Alignment HLoopOptimization::ComputeAlignment(HInstruction* offset,
2340 DataType::Type type,
2341 bool is_string_char_at,
2342 uint32_t peeling) {
2343 // Combine the alignment and hidden offset that is guaranteed by
2344 // the Android runtime with a known starting index adjusted as bytes.
2345 int64_t value = 0;
2346 if (IsInt64AndGet(offset, /*out*/ &value)) {
2347 uint32_t start_offset =
2348 HiddenOffset(type, is_string_char_at) + (value + peeling) * DataType::Size(type);
2349 return Alignment(BaseAlignment(), start_offset & (BaseAlignment() - 1u));
2350 }
2351 // Otherwise, the Android runtime guarantees at least natural alignment.
2352 return Alignment(DataType::Size(type), 0);
2353}
2354
2355void HLoopOptimization::SetAlignmentStrategy(uint32_t peeling_votes[],
2356 const ArrayReference* peeling_candidate) {
2357 // Current heuristic: pick the best static loop peeling factor, if any,
2358 // or otherwise use dynamic loop peeling on suggested peeling candidate.
2359 uint32_t max_vote = 0;
2360 for (int32_t i = 0; i < 16; i++) {
2361 if (peeling_votes[i] > max_vote) {
2362 max_vote = peeling_votes[i];
2363 vector_static_peeling_factor_ = i;
2364 }
2365 }
2366 if (max_vote == 0) {
2367 vector_dynamic_peeling_candidate_ = peeling_candidate;
2368 }
2369}
2370
2371uint32_t HLoopOptimization::MaxNumberPeeled() {
2372 if (vector_dynamic_peeling_candidate_ != nullptr) {
2373 return vector_length_ - 1u; // worst-case
2374 }
2375 return vector_static_peeling_factor_; // known exactly
2376}
2377
Aart Bik14a68b42017-06-08 14:06:58 -07002378bool HLoopOptimization::IsVectorizationProfitable(int64_t trip_count) {
Aart Bik38a3f212017-10-20 17:02:21 -07002379 // Current heuristic: non-empty body with sufficient number of iterations (if known).
Aart Bik14a68b42017-06-08 14:06:58 -07002380 // TODO: refine by looking at e.g. operation count, alignment, etc.
Aart Bik38a3f212017-10-20 17:02:21 -07002381 // TODO: trip count is really unsigned entity, provided the guarding test
2382 // is satisfied; deal with this more carefully later
2383 uint32_t max_peel = MaxNumberPeeled();
Aart Bik14a68b42017-06-08 14:06:58 -07002384 if (vector_length_ == 0) {
2385 return false; // nothing found
Aart Bik38a3f212017-10-20 17:02:21 -07002386 } else if (trip_count < 0) {
2387 return false; // guard against non-taken/large
2388 } else if ((0 < trip_count) && (trip_count < (vector_length_ + max_peel))) {
Aart Bik14a68b42017-06-08 14:06:58 -07002389 return false; // insufficient iterations
2390 }
2391 return true;
2392}
2393
Aart Bik14a68b42017-06-08 14:06:58 -07002394//
Aart Bikf8f5a162017-02-06 15:35:29 -08002395// Helpers.
2396//
2397
2398bool HLoopOptimization::TrySetPhiInduction(HPhi* phi, bool restrict_uses) {
Aart Bikb29f6842017-07-28 15:58:41 -07002399 // Start with empty phi induction.
2400 iset_->clear();
2401
Nicolas Geoffrayf57c1ae2017-06-28 17:40:18 +01002402 // Special case Phis that have equivalent in a debuggable setup. Our graph checker isn't
2403 // smart enough to follow strongly connected components (and it's probably not worth
2404 // it to make it so). See b/33775412.
2405 if (graph_->IsDebuggable() && phi->HasEquivalentPhi()) {
2406 return false;
2407 }
Aart Bikb29f6842017-07-28 15:58:41 -07002408
2409 // Lookup phi induction cycle.
Aart Bikcc42be02016-10-20 16:14:16 -07002410 ArenaSet<HInstruction*>* set = induction_range_.LookupCycle(phi);
2411 if (set != nullptr) {
2412 for (HInstruction* i : *set) {
Aart Bike3dedc52016-11-02 17:50:27 -07002413 // Check that, other than instructions that are no longer in the graph (removed earlier)
Aart Bikf8f5a162017-02-06 15:35:29 -08002414 // each instruction is removable and, when restrict uses are requested, other than for phi,
2415 // all uses are contained within the cycle.
Aart Bike3dedc52016-11-02 17:50:27 -07002416 if (!i->IsInBlock()) {
2417 continue;
2418 } else if (!i->IsRemovable()) {
2419 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08002420 } else if (i != phi && restrict_uses) {
Aart Bikb29f6842017-07-28 15:58:41 -07002421 // Deal with regular uses.
Aart Bikcc42be02016-10-20 16:14:16 -07002422 for (const HUseListNode<HInstruction*>& use : i->GetUses()) {
2423 if (set->find(use.GetUser()) == set->end()) {
2424 return false;
2425 }
2426 }
2427 }
Aart Bike3dedc52016-11-02 17:50:27 -07002428 iset_->insert(i); // copy
Aart Bikcc42be02016-10-20 16:14:16 -07002429 }
Aart Bikcc42be02016-10-20 16:14:16 -07002430 return true;
2431 }
2432 return false;
2433}
2434
Aart Bikb29f6842017-07-28 15:58:41 -07002435bool HLoopOptimization::TrySetPhiReduction(HPhi* phi) {
Aart Bikcc42be02016-10-20 16:14:16 -07002436 DCHECK(iset_->empty());
Aart Bikb29f6842017-07-28 15:58:41 -07002437 // Only unclassified phi cycles are candidates for reductions.
2438 if (induction_range_.IsClassified(phi)) {
2439 return false;
2440 }
2441 // Accept operations like x = x + .., provided that the phi and the reduction are
2442 // used exactly once inside the loop, and by each other.
2443 HInputsRef inputs = phi->GetInputs();
2444 if (inputs.size() == 2) {
2445 HInstruction* reduction = inputs[1];
2446 if (HasReductionFormat(reduction, phi)) {
2447 HLoopInformation* loop_info = phi->GetBlock()->GetLoopInformation();
Aart Bik38a3f212017-10-20 17:02:21 -07002448 uint32_t use_count = 0;
Aart Bikb29f6842017-07-28 15:58:41 -07002449 bool single_use_inside_loop =
2450 // Reduction update only used by phi.
2451 reduction->GetUses().HasExactlyOneElement() &&
2452 !reduction->HasEnvironmentUses() &&
2453 // Reduction update is only use of phi inside the loop.
2454 IsOnlyUsedAfterLoop(loop_info, phi, /*collect_loop_uses*/ true, &use_count) &&
2455 iset_->size() == 1;
2456 iset_->clear(); // leave the way you found it
2457 if (single_use_inside_loop) {
2458 // Link reduction back, and start recording feed value.
2459 reductions_->Put(reduction, phi);
2460 reductions_->Put(phi, phi->InputAt(0));
2461 return true;
2462 }
2463 }
2464 }
2465 return false;
2466}
2467
2468bool HLoopOptimization::TrySetSimpleLoopHeader(HBasicBlock* block, /*out*/ HPhi** main_phi) {
2469 // Start with empty phi induction and reductions.
2470 iset_->clear();
2471 reductions_->clear();
2472
2473 // Scan the phis to find the following (the induction structure has already
2474 // been optimized, so we don't need to worry about trivial cases):
2475 // (1) optional reductions in loop,
2476 // (2) the main induction, used in loop control.
2477 HPhi* phi = nullptr;
2478 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
2479 if (TrySetPhiReduction(it.Current()->AsPhi())) {
2480 continue;
2481 } else if (phi == nullptr) {
2482 // Found the first candidate for main induction.
2483 phi = it.Current()->AsPhi();
2484 } else {
2485 return false;
2486 }
2487 }
2488
2489 // Then test for a typical loopheader:
2490 // s: SuspendCheck
2491 // c: Condition(phi, bound)
2492 // i: If(c)
2493 if (phi != nullptr && TrySetPhiInduction(phi, /*restrict_uses*/ false)) {
Aart Bikcc42be02016-10-20 16:14:16 -07002494 HInstruction* s = block->GetFirstInstruction();
2495 if (s != nullptr && s->IsSuspendCheck()) {
2496 HInstruction* c = s->GetNext();
Aart Bikd86c0852017-04-14 12:00:15 -07002497 if (c != nullptr &&
2498 c->IsCondition() &&
2499 c->GetUses().HasExactlyOneElement() && // only used for termination
2500 !c->HasEnvironmentUses()) { // unlikely, but not impossible
Aart Bikcc42be02016-10-20 16:14:16 -07002501 HInstruction* i = c->GetNext();
2502 if (i != nullptr && i->IsIf() && i->InputAt(0) == c) {
2503 iset_->insert(c);
2504 iset_->insert(s);
Aart Bikb29f6842017-07-28 15:58:41 -07002505 *main_phi = phi;
Aart Bikcc42be02016-10-20 16:14:16 -07002506 return true;
2507 }
2508 }
2509 }
2510 }
2511 return false;
2512}
2513
2514bool HLoopOptimization::IsEmptyBody(HBasicBlock* block) {
Aart Bikf8f5a162017-02-06 15:35:29 -08002515 if (!block->GetPhis().IsEmpty()) {
2516 return false;
2517 }
2518 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
2519 HInstruction* instruction = it.Current();
2520 if (!instruction->IsGoto() && iset_->find(instruction) == iset_->end()) {
2521 return false;
Aart Bikcc42be02016-10-20 16:14:16 -07002522 }
Aart Bikf8f5a162017-02-06 15:35:29 -08002523 }
2524 return true;
2525}
2526
2527bool HLoopOptimization::IsUsedOutsideLoop(HLoopInformation* loop_info,
2528 HInstruction* instruction) {
Aart Bikb29f6842017-07-28 15:58:41 -07002529 // Deal with regular uses.
Aart Bikf8f5a162017-02-06 15:35:29 -08002530 for (const HUseListNode<HInstruction*>& use : instruction->GetUses()) {
2531 if (use.GetUser()->GetBlock()->GetLoopInformation() != loop_info) {
2532 return true;
2533 }
Aart Bikcc42be02016-10-20 16:14:16 -07002534 }
2535 return false;
2536}
2537
Aart Bik482095d2016-10-10 15:39:10 -07002538bool HLoopOptimization::IsOnlyUsedAfterLoop(HLoopInformation* loop_info,
Aart Bik8c4a8542016-10-06 11:36:57 -07002539 HInstruction* instruction,
Aart Bik6b69e0a2017-01-11 10:20:43 -08002540 bool collect_loop_uses,
Aart Bik38a3f212017-10-20 17:02:21 -07002541 /*out*/ uint32_t* use_count) {
Aart Bikb29f6842017-07-28 15:58:41 -07002542 // Deal with regular uses.
Aart Bik8c4a8542016-10-06 11:36:57 -07002543 for (const HUseListNode<HInstruction*>& use : instruction->GetUses()) {
2544 HInstruction* user = use.GetUser();
2545 if (iset_->find(user) == iset_->end()) { // not excluded?
2546 HLoopInformation* other_loop_info = user->GetBlock()->GetLoopInformation();
Aart Bik482095d2016-10-10 15:39:10 -07002547 if (other_loop_info != nullptr && other_loop_info->IsIn(*loop_info)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -08002548 // If collect_loop_uses is set, simply keep adding those uses to the set.
2549 // Otherwise, reject uses inside the loop that were not already in the set.
2550 if (collect_loop_uses) {
2551 iset_->insert(user);
2552 continue;
2553 }
Aart Bik8c4a8542016-10-06 11:36:57 -07002554 return false;
2555 }
2556 ++*use_count;
2557 }
2558 }
2559 return true;
2560}
2561
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002562bool HLoopOptimization::TryReplaceWithLastValue(HLoopInformation* loop_info,
2563 HInstruction* instruction,
2564 HBasicBlock* block) {
2565 // Try to replace outside uses with the last value.
Aart Bik807868e2016-11-03 17:51:43 -07002566 if (induction_range_.CanGenerateLastValue(instruction)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -08002567 HInstruction* replacement = induction_range_.GenerateLastValue(instruction, graph_, block);
Aart Bikb29f6842017-07-28 15:58:41 -07002568 // Deal with regular uses.
Aart Bik6b69e0a2017-01-11 10:20:43 -08002569 const HUseList<HInstruction*>& uses = instruction->GetUses();
2570 for (auto it = uses.begin(), end = uses.end(); it != end;) {
2571 HInstruction* user = it->GetUser();
2572 size_t index = it->GetIndex();
2573 ++it; // increment before replacing
2574 if (iset_->find(user) == iset_->end()) { // not excluded?
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002575 if (kIsDebugBuild) {
2576 // We have checked earlier in 'IsOnlyUsedAfterLoop' that the use is after the loop.
2577 HLoopInformation* other_loop_info = user->GetBlock()->GetLoopInformation();
2578 CHECK(other_loop_info == nullptr || !other_loop_info->IsIn(*loop_info));
2579 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08002580 user->ReplaceInput(replacement, index);
2581 induction_range_.Replace(user, instruction, replacement); // update induction
2582 }
2583 }
Aart Bikb29f6842017-07-28 15:58:41 -07002584 // Deal with environment uses.
Aart Bik6b69e0a2017-01-11 10:20:43 -08002585 const HUseList<HEnvironment*>& env_uses = instruction->GetEnvUses();
2586 for (auto it = env_uses.begin(), end = env_uses.end(); it != end;) {
2587 HEnvironment* user = it->GetUser();
2588 size_t index = it->GetIndex();
2589 ++it; // increment before replacing
2590 if (iset_->find(user->GetHolder()) == iset_->end()) { // not excluded?
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002591 // Only update environment uses after the loop.
Aart Bik14a68b42017-06-08 14:06:58 -07002592 HLoopInformation* other_loop_info = user->GetHolder()->GetBlock()->GetLoopInformation();
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002593 if (other_loop_info == nullptr || !other_loop_info->IsIn(*loop_info)) {
2594 user->RemoveAsUserOfInput(index);
2595 user->SetRawEnvAt(index, replacement);
2596 replacement->AddEnvUseAt(user, index);
2597 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08002598 }
2599 }
Aart Bik807868e2016-11-03 17:51:43 -07002600 return true;
Aart Bik8c4a8542016-10-06 11:36:57 -07002601 }
Aart Bik807868e2016-11-03 17:51:43 -07002602 return false;
Aart Bik8c4a8542016-10-06 11:36:57 -07002603}
2604
Aart Bikf8f5a162017-02-06 15:35:29 -08002605bool HLoopOptimization::TryAssignLastValue(HLoopInformation* loop_info,
2606 HInstruction* instruction,
2607 HBasicBlock* block,
2608 bool collect_loop_uses) {
2609 // Assigning the last value is always successful if there are no uses.
2610 // Otherwise, it succeeds in a no early-exit loop by generating the
2611 // proper last value assignment.
Aart Bik38a3f212017-10-20 17:02:21 -07002612 uint32_t use_count = 0;
Aart Bikf8f5a162017-02-06 15:35:29 -08002613 return IsOnlyUsedAfterLoop(loop_info, instruction, collect_loop_uses, &use_count) &&
2614 (use_count == 0 ||
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002615 (!IsEarlyExit(loop_info) && TryReplaceWithLastValue(loop_info, instruction, block)));
Aart Bikf8f5a162017-02-06 15:35:29 -08002616}
2617
Aart Bik6b69e0a2017-01-11 10:20:43 -08002618void HLoopOptimization::RemoveDeadInstructions(const HInstructionList& list) {
2619 for (HBackwardInstructionIterator i(list); !i.Done(); i.Advance()) {
2620 HInstruction* instruction = i.Current();
2621 if (instruction->IsDeadAndRemovable()) {
2622 simplified_ = true;
2623 instruction->GetBlock()->RemoveInstructionOrPhi(instruction);
2624 }
2625 }
2626}
2627
Aart Bik14a68b42017-06-08 14:06:58 -07002628bool HLoopOptimization::CanRemoveCycle() {
2629 for (HInstruction* i : *iset_) {
2630 // We can never remove instructions that have environment
2631 // uses when we compile 'debuggable'.
2632 if (i->HasEnvironmentUses() && graph_->IsDebuggable()) {
2633 return false;
2634 }
2635 // A deoptimization should never have an environment input removed.
2636 for (const HUseListNode<HEnvironment*>& use : i->GetEnvUses()) {
2637 if (use.GetUser()->GetHolder()->IsDeoptimize()) {
2638 return false;
2639 }
2640 }
2641 }
2642 return true;
2643}
2644
Aart Bik281c6812016-08-26 11:31:48 -07002645} // namespace art