blob: 7f1b319c1248138ea883e0615ca75cc16c9157e2 [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
Aart Bik24773202018-04-26 10:28:51 -0700611bool 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 Bik24773202018-04-26 10:28:51 -0700615 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700616 }
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.
Aart Bik24773202018-04-26 10:28:51 -0700623 bool didLoopOpt = 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;
Aart Bik24773202018-04-26 10:28:51 -0700631
632 return didLoopOpt;
Aart Bik96202302016-10-04 17:33:56 -0700633}
634
Aart Bikb29f6842017-07-28 15:58:41 -0700635//
636// Loop setup and traversal.
637//
638
Aart Bik24773202018-04-26 10:28:51 -0700639bool HLoopOptimization::LocalRun() {
640 bool didLoopOpt = false;
Aart Bik96202302016-10-04 17:33:56 -0700641 // Build the linear order using the phase-local allocator. This step enables building
642 // a loop hierarchy that properly reflects the outer-inner and previous-next relation.
Vladimir Markoca6fff82017-10-03 14:49:14 +0100643 ScopedArenaVector<HBasicBlock*> linear_order(loop_allocator_->Adapter(kArenaAllocLinearOrder));
644 LinearizeGraph(graph_, &linear_order);
Aart Bik96202302016-10-04 17:33:56 -0700645
Aart Bik281c6812016-08-26 11:31:48 -0700646 // Build the loop hierarchy.
Aart Bik96202302016-10-04 17:33:56 -0700647 for (HBasicBlock* block : linear_order) {
Aart Bik281c6812016-08-26 11:31:48 -0700648 if (block->IsLoopHeader()) {
649 AddLoop(block->GetLoopInformation());
650 }
651 }
Aart Bik96202302016-10-04 17:33:56 -0700652
Aart Bik8c4a8542016-10-06 11:36:57 -0700653 // Traverse the loop hierarchy inner-to-outer and optimize. Traversal can use
Aart Bikf8f5a162017-02-06 15:35:29 -0800654 // temporary data structures using the phase-local allocator. All new HIR
655 // should use the global allocator.
Aart Bik8c4a8542016-10-06 11:36:57 -0700656 if (top_loop_ != nullptr) {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100657 ScopedArenaSet<HInstruction*> iset(loop_allocator_->Adapter(kArenaAllocLoopOptimization));
658 ScopedArenaSafeMap<HInstruction*, HInstruction*> reds(
Aart Bikb29f6842017-07-28 15:58:41 -0700659 std::less<HInstruction*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
Vladimir Markoca6fff82017-10-03 14:49:14 +0100660 ScopedArenaSet<ArrayReference> refs(loop_allocator_->Adapter(kArenaAllocLoopOptimization));
661 ScopedArenaSafeMap<HInstruction*, HInstruction*> map(
Aart Bikf8f5a162017-02-06 15:35:29 -0800662 std::less<HInstruction*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
Vladimir Markoca6fff82017-10-03 14:49:14 +0100663 ScopedArenaSafeMap<HInstruction*, HInstruction*> perm(
Aart Bik0148de42017-09-05 09:25:01 -0700664 std::less<HInstruction*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
Aart Bikf8f5a162017-02-06 15:35:29 -0800665 // Attach.
Aart Bik8c4a8542016-10-06 11:36:57 -0700666 iset_ = &iset;
Aart Bikb29f6842017-07-28 15:58:41 -0700667 reductions_ = &reds;
Aart Bikf8f5a162017-02-06 15:35:29 -0800668 vector_refs_ = &refs;
669 vector_map_ = &map;
Aart Bik0148de42017-09-05 09:25:01 -0700670 vector_permanent_map_ = &perm;
Aart Bikf8f5a162017-02-06 15:35:29 -0800671 // Traverse.
Aart Bik24773202018-04-26 10:28:51 -0700672 didLoopOpt = TraverseLoopsInnerToOuter(top_loop_);
Aart Bikf8f5a162017-02-06 15:35:29 -0800673 // Detach.
674 iset_ = nullptr;
Aart Bikb29f6842017-07-28 15:58:41 -0700675 reductions_ = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800676 vector_refs_ = nullptr;
677 vector_map_ = nullptr;
Aart Bik0148de42017-09-05 09:25:01 -0700678 vector_permanent_map_ = nullptr;
Aart Bik8c4a8542016-10-06 11:36:57 -0700679 }
Aart Bik24773202018-04-26 10:28:51 -0700680 return didLoopOpt;
Aart Bik281c6812016-08-26 11:31:48 -0700681}
682
683void HLoopOptimization::AddLoop(HLoopInformation* loop_info) {
684 DCHECK(loop_info != nullptr);
Aart Bikf8f5a162017-02-06 15:35:29 -0800685 LoopNode* node = new (loop_allocator_) LoopNode(loop_info);
Aart Bik281c6812016-08-26 11:31:48 -0700686 if (last_loop_ == nullptr) {
687 // First loop.
688 DCHECK(top_loop_ == nullptr);
689 last_loop_ = top_loop_ = node;
690 } else if (loop_info->IsIn(*last_loop_->loop_info)) {
691 // Inner loop.
692 node->outer = last_loop_;
693 DCHECK(last_loop_->inner == nullptr);
694 last_loop_ = last_loop_->inner = node;
695 } else {
696 // Subsequent loop.
697 while (last_loop_->outer != nullptr && !loop_info->IsIn(*last_loop_->outer->loop_info)) {
698 last_loop_ = last_loop_->outer;
699 }
700 node->outer = last_loop_->outer;
701 node->previous = last_loop_;
702 DCHECK(last_loop_->next == nullptr);
703 last_loop_ = last_loop_->next = node;
704 }
705}
706
707void HLoopOptimization::RemoveLoop(LoopNode* node) {
708 DCHECK(node != nullptr);
Aart Bik8c4a8542016-10-06 11:36:57 -0700709 DCHECK(node->inner == nullptr);
710 if (node->previous != nullptr) {
711 // Within sequence.
712 node->previous->next = node->next;
713 if (node->next != nullptr) {
714 node->next->previous = node->previous;
715 }
716 } else {
717 // First of sequence.
718 if (node->outer != nullptr) {
719 node->outer->inner = node->next;
720 } else {
721 top_loop_ = node->next;
722 }
723 if (node->next != nullptr) {
724 node->next->outer = node->outer;
725 node->next->previous = nullptr;
726 }
727 }
Aart Bik281c6812016-08-26 11:31:48 -0700728}
729
Aart Bikb29f6842017-07-28 15:58:41 -0700730bool HLoopOptimization::TraverseLoopsInnerToOuter(LoopNode* node) {
731 bool changed = false;
Aart Bik281c6812016-08-26 11:31:48 -0700732 for ( ; node != nullptr; node = node->next) {
Aart Bikb29f6842017-07-28 15:58:41 -0700733 // Visit inner loops first. Recompute induction information for this
734 // loop if the induction of any inner loop has changed.
735 if (TraverseLoopsInnerToOuter(node->inner)) {
Aart Bik482095d2016-10-10 15:39:10 -0700736 induction_range_.ReVisit(node->loop_info);
737 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800738 // Repeat simplifications in the loop-body until no more changes occur.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800739 // Note that since each simplification consists of eliminating code (without
740 // introducing new code), this process is always finite.
Aart Bikdf7822e2016-12-06 10:05:30 -0800741 do {
742 simplified_ = false;
Aart Bikdf7822e2016-12-06 10:05:30 -0800743 SimplifyInduction(node);
Aart Bik6b69e0a2017-01-11 10:20:43 -0800744 SimplifyBlocks(node);
Aart Bikb29f6842017-07-28 15:58:41 -0700745 changed = simplified_ || changed;
Aart Bikdf7822e2016-12-06 10:05:30 -0800746 } while (simplified_);
Aart Bikf8f5a162017-02-06 15:35:29 -0800747 // Optimize inner loop.
Aart Bik9abf8942016-10-14 09:49:42 -0700748 if (node->inner == nullptr) {
Aart Bikb29f6842017-07-28 15:58:41 -0700749 changed = OptimizeInnerLoop(node) || changed;
Aart Bik9abf8942016-10-14 09:49:42 -0700750 }
Aart Bik281c6812016-08-26 11:31:48 -0700751 }
Aart Bikb29f6842017-07-28 15:58:41 -0700752 return changed;
Aart Bik281c6812016-08-26 11:31:48 -0700753}
754
Aart Bikf8f5a162017-02-06 15:35:29 -0800755//
756// Optimization.
757//
758
Aart Bik281c6812016-08-26 11:31:48 -0700759void HLoopOptimization::SimplifyInduction(LoopNode* node) {
760 HBasicBlock* header = node->loop_info->GetHeader();
761 HBasicBlock* preheader = node->loop_info->GetPreHeader();
Aart Bik8c4a8542016-10-06 11:36:57 -0700762 // Scan the phis in the header to find opportunities to simplify an induction
763 // cycle that is only used outside the loop. Replace these uses, if any, with
764 // the last value and remove the induction cycle.
765 // Examples: for (int i = 0; x != null; i++) { .... no i .... }
766 // for (int i = 0; i < 10; i++, k++) { .... no k .... } return k;
Aart Bik281c6812016-08-26 11:31:48 -0700767 for (HInstructionIterator it(header->GetPhis()); !it.Done(); it.Advance()) {
768 HPhi* phi = it.Current()->AsPhi();
Aart Bikf8f5a162017-02-06 15:35:29 -0800769 if (TrySetPhiInduction(phi, /*restrict_uses*/ true) &&
770 TryAssignLastValue(node->loop_info, phi, preheader, /*collect_loop_uses*/ false)) {
Aart Bik671e48a2017-08-09 13:16:56 -0700771 // Note that it's ok to have replaced uses after the loop with the last value, without
772 // being able to remove the cycle. Environment uses (which are the reason we may not be
773 // able to remove the cycle) within the loop will still hold the right value. We must
774 // have tried first, however, to replace outside uses.
775 if (CanRemoveCycle()) {
776 simplified_ = true;
777 for (HInstruction* i : *iset_) {
778 RemoveFromCycle(i);
779 }
780 DCHECK(CheckInductionSetFullyRemoved(iset_));
Aart Bik281c6812016-08-26 11:31:48 -0700781 }
Aart Bik482095d2016-10-10 15:39:10 -0700782 }
783 }
784}
785
786void HLoopOptimization::SimplifyBlocks(LoopNode* node) {
Aart Bikdf7822e2016-12-06 10:05:30 -0800787 // Iterate over all basic blocks in the loop-body.
788 for (HBlocksInLoopIterator it(*node->loop_info); !it.Done(); it.Advance()) {
789 HBasicBlock* block = it.Current();
790 // Remove dead instructions from the loop-body.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800791 RemoveDeadInstructions(block->GetPhis());
792 RemoveDeadInstructions(block->GetInstructions());
Aart Bikdf7822e2016-12-06 10:05:30 -0800793 // Remove trivial control flow blocks from the loop-body.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800794 if (block->GetPredecessors().size() == 1 &&
795 block->GetSuccessors().size() == 1 &&
796 block->GetSingleSuccessor()->GetPredecessors().size() == 1) {
Aart Bikdf7822e2016-12-06 10:05:30 -0800797 simplified_ = true;
Aart Bik6b69e0a2017-01-11 10:20:43 -0800798 block->MergeWith(block->GetSingleSuccessor());
Aart Bikdf7822e2016-12-06 10:05:30 -0800799 } else if (block->GetSuccessors().size() == 2) {
800 // Trivial if block can be bypassed to either branch.
801 HBasicBlock* succ0 = block->GetSuccessors()[0];
802 HBasicBlock* succ1 = block->GetSuccessors()[1];
803 HBasicBlock* meet0 = nullptr;
804 HBasicBlock* meet1 = nullptr;
805 if (succ0 != succ1 &&
806 IsGotoBlock(succ0, &meet0) &&
807 IsGotoBlock(succ1, &meet1) &&
808 meet0 == meet1 && // meets again
809 meet0 != block && // no self-loop
810 meet0->GetPhis().IsEmpty()) { // not used for merging
811 simplified_ = true;
812 succ0->DisconnectAndDelete();
813 if (block->Dominates(meet0)) {
814 block->RemoveDominatedBlock(meet0);
815 succ1->AddDominatedBlock(meet0);
816 meet0->SetDominator(succ1);
Aart Bike3dedc52016-11-02 17:50:27 -0700817 }
Aart Bik482095d2016-10-10 15:39:10 -0700818 }
Aart Bik281c6812016-08-26 11:31:48 -0700819 }
Aart Bikdf7822e2016-12-06 10:05:30 -0800820 }
Aart Bik281c6812016-08-26 11:31:48 -0700821}
822
Artem Serov121f2032017-10-23 19:19:06 +0100823bool HLoopOptimization::TryOptimizeInnerLoopFinite(LoopNode* node) {
Aart Bik281c6812016-08-26 11:31:48 -0700824 HBasicBlock* header = node->loop_info->GetHeader();
825 HBasicBlock* preheader = node->loop_info->GetPreHeader();
Aart Bik9abf8942016-10-14 09:49:42 -0700826 // Ensure loop header logic is finite.
Aart Bikf8f5a162017-02-06 15:35:29 -0800827 int64_t trip_count = 0;
828 if (!induction_range_.IsFinite(node->loop_info, &trip_count)) {
Aart Bikb29f6842017-07-28 15:58:41 -0700829 return false;
Aart Bik9abf8942016-10-14 09:49:42 -0700830 }
Aart Bik281c6812016-08-26 11:31:48 -0700831 // Ensure there is only a single loop-body (besides the header).
832 HBasicBlock* body = nullptr;
833 for (HBlocksInLoopIterator it(*node->loop_info); !it.Done(); it.Advance()) {
834 if (it.Current() != header) {
835 if (body != nullptr) {
Aart Bikb29f6842017-07-28 15:58:41 -0700836 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700837 }
838 body = it.Current();
839 }
840 }
Andreas Gampef45d61c2017-06-07 10:29:33 -0700841 CHECK(body != nullptr);
Aart Bik281c6812016-08-26 11:31:48 -0700842 // Ensure there is only a single exit point.
843 if (header->GetSuccessors().size() != 2) {
Aart Bikb29f6842017-07-28 15:58:41 -0700844 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700845 }
846 HBasicBlock* exit = (header->GetSuccessors()[0] == body)
847 ? header->GetSuccessors()[1]
848 : header->GetSuccessors()[0];
Aart Bik8c4a8542016-10-06 11:36:57 -0700849 // Ensure exit can only be reached by exiting loop.
Aart Bik281c6812016-08-26 11:31:48 -0700850 if (exit->GetPredecessors().size() != 1) {
Aart Bikb29f6842017-07-28 15:58:41 -0700851 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700852 }
Aart Bik6b69e0a2017-01-11 10:20:43 -0800853 // Detect either an empty loop (no side effects other than plain iteration) or
854 // a trivial loop (just iterating once). Replace subsequent index uses, if any,
855 // with the last value and remove the loop, possibly after unrolling its body.
Aart Bikb29f6842017-07-28 15:58:41 -0700856 HPhi* main_phi = nullptr;
857 if (TrySetSimpleLoopHeader(header, &main_phi)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -0800858 bool is_empty = IsEmptyBody(body);
Aart Bikb29f6842017-07-28 15:58:41 -0700859 if (reductions_->empty() && // TODO: possible with some effort
860 (is_empty || trip_count == 1) &&
861 TryAssignLastValue(node->loop_info, main_phi, preheader, /*collect_loop_uses*/ true)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -0800862 if (!is_empty) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800863 // Unroll the loop-body, which sees initial value of the index.
Aart Bikb29f6842017-07-28 15:58:41 -0700864 main_phi->ReplaceWith(main_phi->InputAt(0));
Aart Bik6b69e0a2017-01-11 10:20:43 -0800865 preheader->MergeInstructionsWith(body);
866 }
867 body->DisconnectAndDelete();
868 exit->RemovePredecessor(header);
869 header->RemoveSuccessor(exit);
870 header->RemoveDominatedBlock(exit);
871 header->DisconnectAndDelete();
872 preheader->AddSuccessor(exit);
Aart Bikf8f5a162017-02-06 15:35:29 -0800873 preheader->AddInstruction(new (global_allocator_) HGoto());
Aart Bik6b69e0a2017-01-11 10:20:43 -0800874 preheader->AddDominatedBlock(exit);
875 exit->SetDominator(preheader);
876 RemoveLoop(node); // update hierarchy
Aart Bikb29f6842017-07-28 15:58:41 -0700877 return true;
Aart Bikf8f5a162017-02-06 15:35:29 -0800878 }
879 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800880 // Vectorize loop, if possible and valid.
Aart Bikb29f6842017-07-28 15:58:41 -0700881 if (kEnableVectorization &&
882 TrySetSimpleLoopHeader(header, &main_phi) &&
Aart Bikb29f6842017-07-28 15:58:41 -0700883 ShouldVectorize(node, body, trip_count) &&
884 TryAssignLastValue(node->loop_info, main_phi, preheader, /*collect_loop_uses*/ true)) {
885 Vectorize(node, body, exit, trip_count);
886 graph_->SetHasSIMD(true); // flag SIMD usage
Aart Bik21b85922017-09-06 13:29:16 -0700887 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorized);
Aart Bikb29f6842017-07-28 15:58:41 -0700888 return true;
Aart Bikf8f5a162017-02-06 15:35:29 -0800889 }
Aart Bikb29f6842017-07-28 15:58:41 -0700890 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -0800891}
892
Artem Serov121f2032017-10-23 19:19:06 +0100893bool HLoopOptimization::OptimizeInnerLoop(LoopNode* node) {
894 return TryOptimizeInnerLoopFinite(node) ||
Artem Serov72411e62017-10-19 16:18:07 +0100895 TryPeelingForLoopInvariantExitsElimination(node) ||
Artem Serov121f2032017-10-23 19:19:06 +0100896 TryUnrollingForBranchPenaltyReduction(node);
897}
898
Artem Serov121f2032017-10-23 19:19:06 +0100899
Artem Serov121f2032017-10-23 19:19:06 +0100900
901//
902// Loop unrolling: generic part methods.
903//
904
Artem Serov72411e62017-10-19 16:18:07 +0100905bool HLoopOptimization::TryUnrollingForBranchPenaltyReduction(LoopNode* node) {
Artem Serov121f2032017-10-23 19:19:06 +0100906 // Don't run peeling/unrolling if compiler_driver_ is nullptr (i.e., running under tests)
907 // as InstructionSet is needed.
Artem Serov72411e62017-10-19 16:18:07 +0100908 if (!kEnableScalarPeelingUnrolling || compiler_driver_ == nullptr) {
Artem Serov121f2032017-10-23 19:19:06 +0100909 return false;
910 }
911
Artem Serov72411e62017-10-19 16:18:07 +0100912 HLoopInformation* loop_info = node->loop_info;
Artem Serov121f2032017-10-23 19:19:06 +0100913 int64_t trip_count = 0;
914 // Only unroll loops with a known tripcount.
915 if (!induction_range_.HasKnownTripCount(loop_info, &trip_count)) {
916 return false;
917 }
918
919 uint32_t unrolling_factor = arch_loop_helper_->GetScalarUnrollingFactor(loop_info, trip_count);
920 if (unrolling_factor == kNoUnrollingFactor) {
921 return false;
922 }
923
924 LoopAnalysisInfo loop_analysis_info(loop_info);
925 LoopAnalysis::CalculateLoopBasicProperties(loop_info, &loop_analysis_info);
926
927 // Check "IsLoopClonable" last as it can be time-consuming.
Artem Serov72411e62017-10-19 16:18:07 +0100928 if (arch_loop_helper_->IsLoopTooBigForScalarPeelingUnrolling(&loop_analysis_info) ||
Artem Serov121f2032017-10-23 19:19:06 +0100929 (loop_analysis_info.GetNumberOfExits() > 1) ||
930 loop_analysis_info.HasInstructionsPreventingScalarUnrolling() ||
931 !PeelUnrollHelper::IsLoopClonable(loop_info)) {
932 return false;
933 }
934
935 // TODO: support other unrolling factors.
936 DCHECK_EQ(unrolling_factor, 2u);
937
938 // Perform unrolling.
Artem Serov72411e62017-10-19 16:18:07 +0100939 PeelUnrollSimpleHelper helper(loop_info);
940 helper.DoUnrolling();
Artem Serov121f2032017-10-23 19:19:06 +0100941
942 // Remove the redundant loop check after unrolling.
Artem Serov72411e62017-10-19 16:18:07 +0100943 HIf* copy_hif =
944 helper.GetBasicBlockMap()->Get(loop_info->GetHeader())->GetLastInstruction()->AsIf();
Artem Serov121f2032017-10-23 19:19:06 +0100945 int32_t constant = loop_info->Contains(*copy_hif->IfTrueSuccessor()) ? 1 : 0;
946 copy_hif->ReplaceInput(graph_->GetIntConstant(constant), 0u);
947
948 return true;
949}
950
Artem Serov72411e62017-10-19 16:18:07 +0100951bool HLoopOptimization::TryPeelingForLoopInvariantExitsElimination(LoopNode* node) {
952 // Don't run peeling/unrolling if compiler_driver_ is nullptr (i.e., running under tests)
953 // as InstructionSet is needed.
954 if (!kEnableScalarPeelingUnrolling || compiler_driver_ == nullptr) {
955 return false;
956 }
957
958 HLoopInformation* loop_info = node->loop_info;
959 // Check 'IsLoopClonable' the last as it might be time-consuming.
960 if (!arch_loop_helper_->IsLoopPeelingEnabled()) {
961 return false;
962 }
963
964 LoopAnalysisInfo loop_analysis_info(loop_info);
965 LoopAnalysis::CalculateLoopBasicProperties(loop_info, &loop_analysis_info);
966
967 // Check "IsLoopClonable" last as it can be time-consuming.
968 if (arch_loop_helper_->IsLoopTooBigForScalarPeelingUnrolling(&loop_analysis_info) ||
969 loop_analysis_info.HasInstructionsPreventingScalarPeeling() ||
970 !LoopAnalysis::HasLoopAtLeastOneInvariantExit(loop_info) ||
971 !PeelUnrollHelper::IsLoopClonable(loop_info)) {
972 return false;
973 }
974
975 // Perform peeling.
976 PeelUnrollSimpleHelper helper(loop_info);
977 helper.DoPeeling();
978
979 const SuperblockCloner::HInstructionMap* hir_map = helper.GetInstructionMap();
980 for (auto entry : *hir_map) {
981 HInstruction* copy = entry.second;
982 if (copy->IsIf()) {
983 TryToEvaluateIfCondition(copy->AsIf(), graph_);
984 }
985 }
986
987 return true;
988}
989
Aart Bikf8f5a162017-02-06 15:35:29 -0800990//
991// Loop vectorization. The implementation is based on the book by Aart J.C. Bik:
992// "The Software Vectorization Handbook. Applying Multimedia Extensions for Maximum Performance."
993// Intel Press, June, 2004 (http://www.aartbik.com/).
994//
995
Aart Bik14a68b42017-06-08 14:06:58 -0700996bool HLoopOptimization::ShouldVectorize(LoopNode* node, HBasicBlock* block, int64_t trip_count) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800997 // Reset vector bookkeeping.
998 vector_length_ = 0;
999 vector_refs_->clear();
Aart Bik38a3f212017-10-20 17:02:21 -07001000 vector_static_peeling_factor_ = 0;
1001 vector_dynamic_peeling_candidate_ = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -08001002 vector_runtime_test_a_ =
Igor Murashkin2ffb7032017-11-08 13:35:21 -08001003 vector_runtime_test_b_ = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -08001004
1005 // Phis in the loop-body prevent vectorization.
1006 if (!block->GetPhis().IsEmpty()) {
1007 return false;
1008 }
1009
1010 // Scan the loop-body, starting a right-hand-side tree traversal at each left-hand-side
1011 // occurrence, which allows passing down attributes down the use tree.
1012 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
1013 if (!VectorizeDef(node, it.Current(), /*generate_code*/ false)) {
1014 return false; // failure to vectorize a left-hand-side
1015 }
1016 }
1017
Aart Bik38a3f212017-10-20 17:02:21 -07001018 // Prepare alignment analysis:
1019 // (1) find desired alignment (SIMD vector size in bytes).
1020 // (2) initialize static loop peeling votes (peeling factor that will
1021 // make one particular reference aligned), never to exceed (1).
1022 // (3) variable to record how many references share same alignment.
1023 // (4) variable to record suitable candidate for dynamic loop peeling.
1024 uint32_t desired_alignment = GetVectorSizeInBytes();
1025 DCHECK_LE(desired_alignment, 16u);
1026 uint32_t peeling_votes[16] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
1027 uint32_t max_num_same_alignment = 0;
1028 const ArrayReference* peeling_candidate = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -08001029
1030 // Data dependence analysis. Find each pair of references with same type, where
1031 // at least one is a write. Each such pair denotes a possible data dependence.
1032 // This analysis exploits the property that differently typed arrays cannot be
1033 // aliased, as well as the property that references either point to the same
1034 // array or to two completely disjoint arrays, i.e., no partial aliasing.
1035 // Other than a few simply heuristics, no detailed subscript analysis is done.
Aart Bik38a3f212017-10-20 17:02:21 -07001036 // The scan over references also prepares finding a suitable alignment strategy.
Aart Bikf8f5a162017-02-06 15:35:29 -08001037 for (auto i = vector_refs_->begin(); i != vector_refs_->end(); ++i) {
Aart Bik38a3f212017-10-20 17:02:21 -07001038 uint32_t num_same_alignment = 0;
1039 // Scan over all next references.
Aart Bikf8f5a162017-02-06 15:35:29 -08001040 for (auto j = i; ++j != vector_refs_->end(); ) {
1041 if (i->type == j->type && (i->lhs || j->lhs)) {
1042 // Found same-typed a[i+x] vs. b[i+y], where at least one is a write.
1043 HInstruction* a = i->base;
1044 HInstruction* b = j->base;
1045 HInstruction* x = i->offset;
1046 HInstruction* y = j->offset;
1047 if (a == b) {
1048 // Found a[i+x] vs. a[i+y]. Accept if x == y (loop-independent data dependence).
1049 // Conservatively assume a loop-carried data dependence otherwise, and reject.
1050 if (x != y) {
1051 return false;
1052 }
Aart Bik38a3f212017-10-20 17:02:21 -07001053 // Count the number of references that have the same alignment (since
1054 // base and offset are the same) and where at least one is a write, so
1055 // e.g. a[i] = a[i] + b[i] counts a[i] but not b[i]).
1056 num_same_alignment++;
Aart Bikf8f5a162017-02-06 15:35:29 -08001057 } else {
1058 // Found a[i+x] vs. b[i+y]. Accept if x == y (at worst loop-independent data dependence).
1059 // Conservatively assume a potential loop-carried data dependence otherwise, avoided by
1060 // generating an explicit a != b disambiguation runtime test on the two references.
1061 if (x != y) {
Aart Bik37dc4df2017-06-28 14:08:00 -07001062 // To avoid excessive overhead, we only accept one a != b test.
1063 if (vector_runtime_test_a_ == nullptr) {
1064 // First test found.
1065 vector_runtime_test_a_ = a;
1066 vector_runtime_test_b_ = b;
1067 } else if ((vector_runtime_test_a_ != a || vector_runtime_test_b_ != b) &&
1068 (vector_runtime_test_a_ != b || vector_runtime_test_b_ != a)) {
1069 return false; // second test would be needed
Aart Bikf8f5a162017-02-06 15:35:29 -08001070 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001071 }
1072 }
1073 }
1074 }
Aart Bik38a3f212017-10-20 17:02:21 -07001075 // Update information for finding suitable alignment strategy:
1076 // (1) update votes for static loop peeling,
1077 // (2) update suitable candidate for dynamic loop peeling.
1078 Alignment alignment = ComputeAlignment(i->offset, i->type, i->is_string_char_at);
1079 if (alignment.Base() >= desired_alignment) {
1080 // If the array/string object has a known, sufficient alignment, use the
1081 // initial offset to compute the static loop peeling vote (this always
1082 // works, since elements have natural alignment).
1083 uint32_t offset = alignment.Offset() & (desired_alignment - 1u);
1084 uint32_t vote = (offset == 0)
1085 ? 0
1086 : ((desired_alignment - offset) >> DataType::SizeShift(i->type));
1087 DCHECK_LT(vote, 16u);
1088 ++peeling_votes[vote];
1089 } else if (BaseAlignment() >= desired_alignment &&
1090 num_same_alignment > max_num_same_alignment) {
1091 // Otherwise, if the array/string object has a known, sufficient alignment
1092 // for just the base but with an unknown offset, record the candidate with
1093 // the most occurrences for dynamic loop peeling (again, the peeling always
1094 // works, since elements have natural alignment).
1095 max_num_same_alignment = num_same_alignment;
1096 peeling_candidate = &(*i);
1097 }
1098 } // for i
Aart Bikf8f5a162017-02-06 15:35:29 -08001099
Aart Bik38a3f212017-10-20 17:02:21 -07001100 // Find a suitable alignment strategy.
1101 SetAlignmentStrategy(peeling_votes, peeling_candidate);
1102
1103 // Does vectorization seem profitable?
1104 if (!IsVectorizationProfitable(trip_count)) {
1105 return false;
1106 }
Aart Bik14a68b42017-06-08 14:06:58 -07001107
Aart Bikf8f5a162017-02-06 15:35:29 -08001108 // Success!
1109 return true;
1110}
1111
1112void HLoopOptimization::Vectorize(LoopNode* node,
1113 HBasicBlock* block,
1114 HBasicBlock* exit,
1115 int64_t trip_count) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001116 HBasicBlock* header = node->loop_info->GetHeader();
1117 HBasicBlock* preheader = node->loop_info->GetPreHeader();
1118
Aart Bik14a68b42017-06-08 14:06:58 -07001119 // Pick a loop unrolling factor for the vector loop.
Artem Serov121f2032017-10-23 19:19:06 +01001120 uint32_t unroll = arch_loop_helper_->GetSIMDUnrollingFactor(
1121 block, trip_count, MaxNumberPeeled(), vector_length_);
Aart Bik14a68b42017-06-08 14:06:58 -07001122 uint32_t chunk = vector_length_ * unroll;
1123
Aart Bik38a3f212017-10-20 17:02:21 -07001124 DCHECK(trip_count == 0 || (trip_count >= MaxNumberPeeled() + chunk));
1125
Aart Bik14a68b42017-06-08 14:06:58 -07001126 // A cleanup loop is needed, at least, for any unknown trip count or
1127 // for a known trip count with remainder iterations after vectorization.
Aart Bik38a3f212017-10-20 17:02:21 -07001128 bool needs_cleanup = trip_count == 0 ||
1129 ((trip_count - vector_static_peeling_factor_) % chunk) != 0;
Aart Bikf8f5a162017-02-06 15:35:29 -08001130
1131 // Adjust vector bookkeeping.
Aart Bikb29f6842017-07-28 15:58:41 -07001132 HPhi* main_phi = nullptr;
1133 bool is_simple_loop_header = TrySetSimpleLoopHeader(header, &main_phi); // refills sets
Aart Bikf8f5a162017-02-06 15:35:29 -08001134 DCHECK(is_simple_loop_header);
Aart Bik14a68b42017-06-08 14:06:58 -07001135 vector_header_ = header;
1136 vector_body_ = block;
Aart Bikf8f5a162017-02-06 15:35:29 -08001137
Aart Bikdbbac8f2017-09-01 13:06:08 -07001138 // Loop induction type.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001139 DataType::Type induc_type = main_phi->GetType();
1140 DCHECK(induc_type == DataType::Type::kInt32 || induc_type == DataType::Type::kInt64)
1141 << induc_type;
Aart Bikdbbac8f2017-09-01 13:06:08 -07001142
Aart Bik38a3f212017-10-20 17:02:21 -07001143 // Generate the trip count for static or dynamic loop peeling, if needed:
1144 // ptc = <peeling factor>;
Aart Bik14a68b42017-06-08 14:06:58 -07001145 HInstruction* ptc = nullptr;
Aart Bik38a3f212017-10-20 17:02:21 -07001146 if (vector_static_peeling_factor_ != 0) {
1147 // Static loop peeling for SIMD alignment (using the most suitable
1148 // fixed peeling factor found during prior alignment analysis).
1149 DCHECK(vector_dynamic_peeling_candidate_ == nullptr);
1150 ptc = graph_->GetConstant(induc_type, vector_static_peeling_factor_);
1151 } else if (vector_dynamic_peeling_candidate_ != nullptr) {
1152 // Dynamic loop peeling for SIMD alignment (using the most suitable
1153 // candidate found during prior alignment analysis):
1154 // rem = offset % ALIGN; // adjusted as #elements
1155 // ptc = rem == 0 ? 0 : (ALIGN - rem);
1156 uint32_t shift = DataType::SizeShift(vector_dynamic_peeling_candidate_->type);
1157 uint32_t align = GetVectorSizeInBytes() >> shift;
1158 uint32_t hidden_offset = HiddenOffset(vector_dynamic_peeling_candidate_->type,
1159 vector_dynamic_peeling_candidate_->is_string_char_at);
1160 HInstruction* adjusted_offset = graph_->GetConstant(induc_type, hidden_offset >> shift);
1161 HInstruction* offset = Insert(preheader, new (global_allocator_) HAdd(
1162 induc_type, vector_dynamic_peeling_candidate_->offset, adjusted_offset));
1163 HInstruction* rem = Insert(preheader, new (global_allocator_) HAnd(
1164 induc_type, offset, graph_->GetConstant(induc_type, align - 1u)));
1165 HInstruction* sub = Insert(preheader, new (global_allocator_) HSub(
1166 induc_type, graph_->GetConstant(induc_type, align), rem));
1167 HInstruction* cond = Insert(preheader, new (global_allocator_) HEqual(
1168 rem, graph_->GetConstant(induc_type, 0)));
1169 ptc = Insert(preheader, new (global_allocator_) HSelect(
1170 cond, graph_->GetConstant(induc_type, 0), sub, kNoDexPc));
1171 needs_cleanup = true; // don't know the exact amount
Aart Bik14a68b42017-06-08 14:06:58 -07001172 }
1173
1174 // Generate loop control:
Aart Bikf8f5a162017-02-06 15:35:29 -08001175 // stc = <trip-count>;
Aart Bik38a3f212017-10-20 17:02:21 -07001176 // ptc = min(stc, ptc);
Aart Bik14a68b42017-06-08 14:06:58 -07001177 // vtc = stc - (stc - ptc) % chunk;
1178 // i = 0;
Aart Bikf8f5a162017-02-06 15:35:29 -08001179 HInstruction* stc = induction_range_.GenerateTripCount(node->loop_info, graph_, preheader);
1180 HInstruction* vtc = stc;
1181 if (needs_cleanup) {
Aart Bik14a68b42017-06-08 14:06:58 -07001182 DCHECK(IsPowerOfTwo(chunk));
1183 HInstruction* diff = stc;
1184 if (ptc != nullptr) {
Aart Bik38a3f212017-10-20 17:02:21 -07001185 if (trip_count == 0) {
1186 HInstruction* cond = Insert(preheader, new (global_allocator_) HAboveOrEqual(stc, ptc));
1187 ptc = Insert(preheader, new (global_allocator_) HSelect(cond, ptc, stc, kNoDexPc));
1188 }
Aart Bik14a68b42017-06-08 14:06:58 -07001189 diff = Insert(preheader, new (global_allocator_) HSub(induc_type, stc, ptc));
1190 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001191 HInstruction* rem = Insert(
1192 preheader, new (global_allocator_) HAnd(induc_type,
Aart Bik14a68b42017-06-08 14:06:58 -07001193 diff,
Aart Bikdbbac8f2017-09-01 13:06:08 -07001194 graph_->GetConstant(induc_type, chunk - 1)));
Aart Bikf8f5a162017-02-06 15:35:29 -08001195 vtc = Insert(preheader, new (global_allocator_) HSub(induc_type, stc, rem));
1196 }
Aart Bikdbbac8f2017-09-01 13:06:08 -07001197 vector_index_ = graph_->GetConstant(induc_type, 0);
Aart Bikf8f5a162017-02-06 15:35:29 -08001198
1199 // Generate runtime disambiguation test:
1200 // vtc = a != b ? vtc : 0;
1201 if (vector_runtime_test_a_ != nullptr) {
1202 HInstruction* rt = Insert(
1203 preheader,
1204 new (global_allocator_) HNotEqual(vector_runtime_test_a_, vector_runtime_test_b_));
1205 vtc = Insert(preheader,
Aart Bikdbbac8f2017-09-01 13:06:08 -07001206 new (global_allocator_)
1207 HSelect(rt, vtc, graph_->GetConstant(induc_type, 0), kNoDexPc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001208 needs_cleanup = true;
1209 }
1210
Aart Bik38a3f212017-10-20 17:02:21 -07001211 // Generate alignment peeling loop, if needed:
Aart Bik14a68b42017-06-08 14:06:58 -07001212 // for ( ; i < ptc; i += 1)
1213 // <loop-body>
Aart Bik38a3f212017-10-20 17:02:21 -07001214 //
1215 // NOTE: The alignment forced by the peeling loop is preserved even if data is
1216 // moved around during suspend checks, since all analysis was based on
1217 // nothing more than the Android runtime alignment conventions.
Aart Bik14a68b42017-06-08 14:06:58 -07001218 if (ptc != nullptr) {
1219 vector_mode_ = kSequential;
1220 GenerateNewLoop(node,
1221 block,
1222 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
1223 vector_index_,
1224 ptc,
Aart Bikdbbac8f2017-09-01 13:06:08 -07001225 graph_->GetConstant(induc_type, 1),
Aart Bik521b50f2017-09-09 10:44:45 -07001226 kNoUnrollingFactor);
Aart Bik14a68b42017-06-08 14:06:58 -07001227 }
1228
1229 // Generate vector loop, possibly further unrolled:
1230 // for ( ; i < vtc; i += chunk)
Aart Bikf8f5a162017-02-06 15:35:29 -08001231 // <vectorized-loop-body>
1232 vector_mode_ = kVector;
1233 GenerateNewLoop(node,
1234 block,
Aart Bik14a68b42017-06-08 14:06:58 -07001235 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
1236 vector_index_,
Aart Bikf8f5a162017-02-06 15:35:29 -08001237 vtc,
Aart Bikdbbac8f2017-09-01 13:06:08 -07001238 graph_->GetConstant(induc_type, vector_length_), // increment per unroll
Aart Bik14a68b42017-06-08 14:06:58 -07001239 unroll);
Aart Bikf8f5a162017-02-06 15:35:29 -08001240 HLoopInformation* vloop = vector_header_->GetLoopInformation();
1241
1242 // Generate cleanup loop, if needed:
1243 // for ( ; i < stc; i += 1)
1244 // <loop-body>
1245 if (needs_cleanup) {
1246 vector_mode_ = kSequential;
1247 GenerateNewLoop(node,
1248 block,
1249 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
Aart Bik14a68b42017-06-08 14:06:58 -07001250 vector_index_,
Aart Bikf8f5a162017-02-06 15:35:29 -08001251 stc,
Aart Bikdbbac8f2017-09-01 13:06:08 -07001252 graph_->GetConstant(induc_type, 1),
Aart Bik521b50f2017-09-09 10:44:45 -07001253 kNoUnrollingFactor);
Aart Bikf8f5a162017-02-06 15:35:29 -08001254 }
1255
Aart Bik0148de42017-09-05 09:25:01 -07001256 // Link reductions to their final uses.
1257 for (auto i = reductions_->begin(); i != reductions_->end(); ++i) {
1258 if (i->first->IsPhi()) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001259 HInstruction* phi = i->first;
1260 HInstruction* repl = ReduceAndExtractIfNeeded(i->second);
1261 // Deal with regular uses.
1262 for (const HUseListNode<HInstruction*>& use : phi->GetUses()) {
1263 induction_range_.Replace(use.GetUser(), phi, repl); // update induction use
1264 }
1265 phi->ReplaceWith(repl);
Aart Bik0148de42017-09-05 09:25:01 -07001266 }
1267 }
1268
Aart Bikf8f5a162017-02-06 15:35:29 -08001269 // Remove the original loop by disconnecting the body block
1270 // and removing all instructions from the header.
1271 block->DisconnectAndDelete();
1272 while (!header->GetFirstInstruction()->IsGoto()) {
1273 header->RemoveInstruction(header->GetFirstInstruction());
1274 }
Aart Bikb29f6842017-07-28 15:58:41 -07001275
Aart Bik14a68b42017-06-08 14:06:58 -07001276 // Update loop hierarchy: the old header now resides in the same outer loop
1277 // as the old preheader. Note that we don't bother putting sequential
1278 // loops back in the hierarchy at this point.
Aart Bikf8f5a162017-02-06 15:35:29 -08001279 header->SetLoopInformation(preheader->GetLoopInformation()); // outward
1280 node->loop_info = vloop;
1281}
1282
1283void HLoopOptimization::GenerateNewLoop(LoopNode* node,
1284 HBasicBlock* block,
1285 HBasicBlock* new_preheader,
1286 HInstruction* lo,
1287 HInstruction* hi,
Aart Bik14a68b42017-06-08 14:06:58 -07001288 HInstruction* step,
1289 uint32_t unroll) {
1290 DCHECK(unroll == 1 || vector_mode_ == kVector);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001291 DataType::Type induc_type = lo->GetType();
Aart Bikf8f5a162017-02-06 15:35:29 -08001292 // Prepare new loop.
Aart Bikf8f5a162017-02-06 15:35:29 -08001293 vector_preheader_ = new_preheader,
1294 vector_header_ = vector_preheader_->GetSingleSuccessor();
1295 vector_body_ = vector_header_->GetSuccessors()[1];
Aart Bik14a68b42017-06-08 14:06:58 -07001296 HPhi* phi = new (global_allocator_) HPhi(global_allocator_,
1297 kNoRegNumber,
1298 0,
1299 HPhi::ToPhiType(induc_type));
Aart Bikb07d1bc2017-04-05 10:03:15 -07001300 // Generate header and prepare body.
Aart Bikf8f5a162017-02-06 15:35:29 -08001301 // for (i = lo; i < hi; i += step)
1302 // <loop-body>
Aart Bik14a68b42017-06-08 14:06:58 -07001303 HInstruction* cond = new (global_allocator_) HAboveOrEqual(phi, hi);
1304 vector_header_->AddPhi(phi);
Aart Bikf8f5a162017-02-06 15:35:29 -08001305 vector_header_->AddInstruction(cond);
1306 vector_header_->AddInstruction(new (global_allocator_) HIf(cond));
Aart Bik14a68b42017-06-08 14:06:58 -07001307 vector_index_ = phi;
Aart Bik0148de42017-09-05 09:25:01 -07001308 vector_permanent_map_->clear(); // preserved over unrolling
Aart Bik14a68b42017-06-08 14:06:58 -07001309 for (uint32_t u = 0; u < unroll; u++) {
Aart Bik14a68b42017-06-08 14:06:58 -07001310 // Generate instruction map.
Aart Bik0148de42017-09-05 09:25:01 -07001311 vector_map_->clear();
Aart Bik14a68b42017-06-08 14:06:58 -07001312 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
1313 bool vectorized_def = VectorizeDef(node, it.Current(), /*generate_code*/ true);
1314 DCHECK(vectorized_def);
1315 }
1316 // Generate body from the instruction map, but in original program order.
1317 HEnvironment* env = vector_header_->GetFirstInstruction()->GetEnvironment();
1318 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
1319 auto i = vector_map_->find(it.Current());
1320 if (i != vector_map_->end() && !i->second->IsInBlock()) {
1321 Insert(vector_body_, i->second);
1322 // Deal with instructions that need an environment, such as the scalar intrinsics.
1323 if (i->second->NeedsEnvironment()) {
1324 i->second->CopyEnvironmentFromWithLoopPhiAdjustment(env, vector_header_);
1325 }
1326 }
1327 }
Aart Bik0148de42017-09-05 09:25:01 -07001328 // Generate the induction.
Aart Bik14a68b42017-06-08 14:06:58 -07001329 vector_index_ = new (global_allocator_) HAdd(induc_type, vector_index_, step);
1330 Insert(vector_body_, vector_index_);
Aart Bikf8f5a162017-02-06 15:35:29 -08001331 }
Aart Bik0148de42017-09-05 09:25:01 -07001332 // Finalize phi inputs for the reductions (if any).
1333 for (auto i = reductions_->begin(); i != reductions_->end(); ++i) {
1334 if (!i->first->IsPhi()) {
1335 DCHECK(i->second->IsPhi());
1336 GenerateVecReductionPhiInputs(i->second->AsPhi(), i->first);
1337 }
1338 }
Aart Bikb29f6842017-07-28 15:58:41 -07001339 // Finalize phi inputs for the loop index.
Aart Bik14a68b42017-06-08 14:06:58 -07001340 phi->AddInput(lo);
1341 phi->AddInput(vector_index_);
1342 vector_index_ = phi;
Aart Bikf8f5a162017-02-06 15:35:29 -08001343}
1344
Aart Bikf8f5a162017-02-06 15:35:29 -08001345bool HLoopOptimization::VectorizeDef(LoopNode* node,
1346 HInstruction* instruction,
1347 bool generate_code) {
1348 // Accept a left-hand-side array base[index] for
1349 // (1) supported vector type,
1350 // (2) loop-invariant base,
1351 // (3) unit stride index,
1352 // (4) vectorizable right-hand-side value.
1353 uint64_t restrictions = kNone;
1354 if (instruction->IsArraySet()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001355 DataType::Type type = instruction->AsArraySet()->GetComponentType();
Aart Bikf8f5a162017-02-06 15:35:29 -08001356 HInstruction* base = instruction->InputAt(0);
1357 HInstruction* index = instruction->InputAt(1);
1358 HInstruction* value = instruction->InputAt(2);
1359 HInstruction* offset = nullptr;
Aart Bik6d057002018-04-09 15:39:58 -07001360 // For narrow types, explicit type conversion may have been
1361 // optimized way, so set the no hi bits restriction here.
1362 if (DataType::Size(type) <= 2) {
1363 restrictions |= kNoHiBits;
1364 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001365 if (TrySetVectorType(type, &restrictions) &&
1366 node->loop_info->IsDefinedOutOfTheLoop(base) &&
Aart Bik37dc4df2017-06-28 14:08:00 -07001367 induction_range_.IsUnitStride(instruction, index, graph_, &offset) &&
Aart Bikf8f5a162017-02-06 15:35:29 -08001368 VectorizeUse(node, value, generate_code, type, restrictions)) {
1369 if (generate_code) {
1370 GenerateVecSub(index, offset);
Aart Bik14a68b42017-06-08 14:06:58 -07001371 GenerateVecMem(instruction, vector_map_->Get(index), vector_map_->Get(value), offset, type);
Aart Bikf8f5a162017-02-06 15:35:29 -08001372 } else {
1373 vector_refs_->insert(ArrayReference(base, offset, type, /*lhs*/ true));
1374 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08001375 return true;
1376 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001377 return false;
1378 }
Aart Bik0148de42017-09-05 09:25:01 -07001379 // Accept a left-hand-side reduction for
1380 // (1) supported vector type,
1381 // (2) vectorizable right-hand-side value.
1382 auto redit = reductions_->find(instruction);
1383 if (redit != reductions_->end()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001384 DataType::Type type = instruction->GetType();
Aart Bikdbbac8f2017-09-01 13:06:08 -07001385 // Recognize SAD idiom or direct reduction.
1386 if (VectorizeSADIdiom(node, instruction, generate_code, type, restrictions) ||
1387 (TrySetVectorType(type, &restrictions) &&
1388 VectorizeUse(node, instruction, generate_code, type, restrictions))) {
Aart Bik0148de42017-09-05 09:25:01 -07001389 if (generate_code) {
1390 HInstruction* new_red = vector_map_->Get(instruction);
1391 vector_permanent_map_->Put(new_red, vector_map_->Get(redit->second));
1392 vector_permanent_map_->Overwrite(redit->second, new_red);
1393 }
1394 return true;
1395 }
1396 return false;
1397 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001398 // Branch back okay.
1399 if (instruction->IsGoto()) {
1400 return true;
1401 }
1402 // Otherwise accept only expressions with no effects outside the immediate loop-body.
1403 // Note that actual uses are inspected during right-hand-side tree traversal.
1404 return !IsUsedOutsideLoop(node->loop_info, instruction) && !instruction->DoesAnyWrite();
1405}
1406
Aart Bikf8f5a162017-02-06 15:35:29 -08001407bool HLoopOptimization::VectorizeUse(LoopNode* node,
1408 HInstruction* instruction,
1409 bool generate_code,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001410 DataType::Type type,
Aart Bikf8f5a162017-02-06 15:35:29 -08001411 uint64_t restrictions) {
1412 // Accept anything for which code has already been generated.
1413 if (generate_code) {
1414 if (vector_map_->find(instruction) != vector_map_->end()) {
1415 return true;
1416 }
1417 }
1418 // Continue the right-hand-side tree traversal, passing in proper
1419 // types and vector restrictions along the way. During code generation,
1420 // all new nodes are drawn from the global allocator.
1421 if (node->loop_info->IsDefinedOutOfTheLoop(instruction)) {
1422 // Accept invariant use, using scalar expansion.
1423 if (generate_code) {
1424 GenerateVecInv(instruction, type);
1425 }
1426 return true;
1427 } else if (instruction->IsArrayGet()) {
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001428 // Deal with vector restrictions.
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001429 bool is_string_char_at = instruction->AsArrayGet()->IsStringCharAt();
1430 if (is_string_char_at && HasVectorRestrictions(restrictions, kNoStringCharAt)) {
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001431 return false;
1432 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001433 // Accept a right-hand-side array base[index] for
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001434 // (1) matching vector type (exact match or signed/unsigned integral type of the same size),
Aart Bikf8f5a162017-02-06 15:35:29 -08001435 // (2) loop-invariant base,
1436 // (3) unit stride index,
1437 // (4) vectorizable right-hand-side value.
1438 HInstruction* base = instruction->InputAt(0);
1439 HInstruction* index = instruction->InputAt(1);
1440 HInstruction* offset = nullptr;
Aart Bik46b6dbc2017-10-03 11:37:37 -07001441 if (HVecOperation::ToSignedType(type) == HVecOperation::ToSignedType(instruction->GetType()) &&
Aart Bikf8f5a162017-02-06 15:35:29 -08001442 node->loop_info->IsDefinedOutOfTheLoop(base) &&
Aart Bik37dc4df2017-06-28 14:08:00 -07001443 induction_range_.IsUnitStride(instruction, index, graph_, &offset)) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001444 if (generate_code) {
1445 GenerateVecSub(index, offset);
Aart Bik14a68b42017-06-08 14:06:58 -07001446 GenerateVecMem(instruction, vector_map_->Get(index), nullptr, offset, type);
Aart Bikf8f5a162017-02-06 15:35:29 -08001447 } else {
Aart Bik38a3f212017-10-20 17:02:21 -07001448 vector_refs_->insert(ArrayReference(base, offset, type, /*lhs*/ false, is_string_char_at));
Aart Bikf8f5a162017-02-06 15:35:29 -08001449 }
1450 return true;
1451 }
Aart Bik0148de42017-09-05 09:25:01 -07001452 } else if (instruction->IsPhi()) {
1453 // Accept particular phi operations.
1454 if (reductions_->find(instruction) != reductions_->end()) {
1455 // Deal with vector restrictions.
1456 if (HasVectorRestrictions(restrictions, kNoReduction)) {
1457 return false;
1458 }
1459 // Accept a reduction.
1460 if (generate_code) {
1461 GenerateVecReductionPhi(instruction->AsPhi());
1462 }
1463 return true;
1464 }
1465 // TODO: accept right-hand-side induction?
1466 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001467 } else if (instruction->IsTypeConversion()) {
1468 // Accept particular type conversions.
1469 HTypeConversion* conversion = instruction->AsTypeConversion();
1470 HInstruction* opa = conversion->InputAt(0);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001471 DataType::Type from = conversion->GetInputType();
1472 DataType::Type to = conversion->GetResultType();
1473 if (DataType::IsIntegralType(from) && DataType::IsIntegralType(to)) {
Aart Bik38a3f212017-10-20 17:02:21 -07001474 uint32_t size_vec = DataType::Size(type);
1475 uint32_t size_from = DataType::Size(from);
1476 uint32_t size_to = DataType::Size(to);
Aart Bikdbbac8f2017-09-01 13:06:08 -07001477 // Accept an integral conversion
1478 // (1a) narrowing into vector type, "wider" operations cannot bring in higher order bits, or
1479 // (1b) widening from at least vector type, and
1480 // (2) vectorizable operand.
1481 if ((size_to < size_from &&
1482 size_to == size_vec &&
1483 VectorizeUse(node, opa, generate_code, type, restrictions | kNoHiBits)) ||
1484 (size_to >= size_from &&
1485 size_from >= size_vec &&
Aart Bik4d1a9d42017-10-19 14:40:55 -07001486 VectorizeUse(node, opa, generate_code, type, restrictions))) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001487 if (generate_code) {
1488 if (vector_mode_ == kVector) {
1489 vector_map_->Put(instruction, vector_map_->Get(opa)); // operand pass-through
1490 } else {
1491 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1492 }
1493 }
1494 return true;
1495 }
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001496 } else if (to == DataType::Type::kFloat32 && from == DataType::Type::kInt32) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001497 DCHECK_EQ(to, type);
1498 // Accept int to float conversion for
1499 // (1) supported int,
1500 // (2) vectorizable operand.
1501 if (TrySetVectorType(from, &restrictions) &&
1502 VectorizeUse(node, opa, generate_code, from, restrictions)) {
1503 if (generate_code) {
1504 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1505 }
1506 return true;
1507 }
1508 }
1509 return false;
1510 } else if (instruction->IsNeg() || instruction->IsNot() || instruction->IsBooleanNot()) {
1511 // Accept unary operator for vectorizable operand.
1512 HInstruction* opa = instruction->InputAt(0);
1513 if (VectorizeUse(node, opa, generate_code, type, restrictions)) {
1514 if (generate_code) {
1515 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1516 }
1517 return true;
1518 }
1519 } else if (instruction->IsAdd() || instruction->IsSub() ||
1520 instruction->IsMul() || instruction->IsDiv() ||
1521 instruction->IsAnd() || instruction->IsOr() || instruction->IsXor()) {
1522 // Deal with vector restrictions.
1523 if ((instruction->IsMul() && HasVectorRestrictions(restrictions, kNoMul)) ||
1524 (instruction->IsDiv() && HasVectorRestrictions(restrictions, kNoDiv))) {
1525 return false;
1526 }
1527 // Accept binary operator for vectorizable operands.
1528 HInstruction* opa = instruction->InputAt(0);
1529 HInstruction* opb = instruction->InputAt(1);
1530 if (VectorizeUse(node, opa, generate_code, type, restrictions) &&
1531 VectorizeUse(node, opb, generate_code, type, restrictions)) {
1532 if (generate_code) {
1533 GenerateVecOp(instruction, vector_map_->Get(opa), vector_map_->Get(opb), type);
1534 }
1535 return true;
1536 }
1537 } else if (instruction->IsShl() || instruction->IsShr() || instruction->IsUShr()) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001538 // Recognize halving add idiom.
Aart Bikf3e61ee2017-04-12 17:09:20 -07001539 if (VectorizeHalvingAddIdiom(node, instruction, generate_code, type, restrictions)) {
1540 return true;
1541 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001542 // Deal with vector restrictions.
Aart Bik304c8a52017-05-23 11:01:13 -07001543 HInstruction* opa = instruction->InputAt(0);
1544 HInstruction* opb = instruction->InputAt(1);
1545 HInstruction* r = opa;
1546 bool is_unsigned = false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001547 if ((HasVectorRestrictions(restrictions, kNoShift)) ||
1548 (instruction->IsShr() && HasVectorRestrictions(restrictions, kNoShr))) {
1549 return false; // unsupported instruction
Aart Bik304c8a52017-05-23 11:01:13 -07001550 } else if (HasVectorRestrictions(restrictions, kNoHiBits)) {
1551 // Shifts right need extra care to account for higher order bits.
1552 // TODO: less likely shr/unsigned and ushr/signed can by flipping signess.
1553 if (instruction->IsShr() &&
1554 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || is_unsigned)) {
1555 return false; // reject, unless all operands are sign-extension narrower
1556 } else if (instruction->IsUShr() &&
1557 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || !is_unsigned)) {
1558 return false; // reject, unless all operands are zero-extension narrower
1559 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001560 }
1561 // Accept shift operator for vectorizable/invariant operands.
1562 // TODO: accept symbolic, albeit loop invariant shift factors.
Aart Bik304c8a52017-05-23 11:01:13 -07001563 DCHECK(r != nullptr);
1564 if (generate_code && vector_mode_ != kVector) { // de-idiom
1565 r = opa;
1566 }
Aart Bik50e20d52017-05-05 14:07:29 -07001567 int64_t distance = 0;
Aart Bik304c8a52017-05-23 11:01:13 -07001568 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
Aart Bik50e20d52017-05-05 14:07:29 -07001569 IsInt64AndGet(opb, /*out*/ &distance)) {
Aart Bik65ffd8e2017-05-01 16:50:45 -07001570 // Restrict shift distance to packed data type width.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001571 int64_t max_distance = DataType::Size(type) * 8;
Aart Bik65ffd8e2017-05-01 16:50:45 -07001572 if (0 <= distance && distance < max_distance) {
1573 if (generate_code) {
Aart Bik304c8a52017-05-23 11:01:13 -07001574 GenerateVecOp(instruction, vector_map_->Get(r), opb, type);
Aart Bik65ffd8e2017-05-01 16:50:45 -07001575 }
1576 return true;
Aart Bikf8f5a162017-02-06 15:35:29 -08001577 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001578 }
Aart Bik3b2a5952018-03-05 13:55:28 -08001579 } else if (instruction->IsAbs()) {
1580 // Deal with vector restrictions.
1581 HInstruction* opa = instruction->InputAt(0);
1582 HInstruction* r = opa;
1583 bool is_unsigned = false;
1584 if (HasVectorRestrictions(restrictions, kNoAbs)) {
1585 return false;
1586 } else if (HasVectorRestrictions(restrictions, kNoHiBits) &&
1587 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || is_unsigned)) {
1588 return false; // reject, unless operand is sign-extension narrower
1589 }
1590 // Accept ABS(x) for vectorizable operand.
1591 DCHECK(r != nullptr);
1592 if (generate_code && vector_mode_ != kVector) { // de-idiom
1593 r = opa;
1594 }
1595 if (VectorizeUse(node, r, generate_code, type, restrictions)) {
1596 if (generate_code) {
1597 GenerateVecOp(instruction,
1598 vector_map_->Get(r),
1599 nullptr,
1600 HVecOperation::ToProperType(type, is_unsigned));
1601 }
1602 return true;
1603 }
Aart Bik1f8d51b2018-02-15 10:42:37 -08001604 } else if (instruction->IsMin() || instruction->IsMax()) {
Aart Bik29aa0822018-03-08 11:28:00 -08001605 // Recognize saturation arithmetic.
1606 if (VectorizeSaturationIdiom(node, instruction, generate_code, type, restrictions)) {
1607 return true;
1608 }
Aart Bik1f8d51b2018-02-15 10:42:37 -08001609 // Deal with vector restrictions.
1610 HInstruction* opa = instruction->InputAt(0);
1611 HInstruction* opb = instruction->InputAt(1);
1612 HInstruction* r = opa;
1613 HInstruction* s = opb;
1614 bool is_unsigned = false;
1615 if (HasVectorRestrictions(restrictions, kNoMinMax)) {
1616 return false;
1617 } else if (HasVectorRestrictions(restrictions, kNoHiBits) &&
1618 !IsNarrowerOperands(opa, opb, type, &r, &s, &is_unsigned)) {
1619 return false; // reject, unless all operands are same-extension narrower
1620 }
1621 // Accept MIN/MAX(x, y) for vectorizable operands.
Nicolas Geoffraya3e23262018-03-28 11:15:12 +00001622 DCHECK(r != nullptr && s != nullptr);
Aart Bik1f8d51b2018-02-15 10:42:37 -08001623 if (generate_code && vector_mode_ != kVector) { // de-idiom
1624 r = opa;
1625 s = opb;
1626 }
1627 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
1628 VectorizeUse(node, s, generate_code, type, restrictions)) {
1629 if (generate_code) {
1630 GenerateVecOp(
1631 instruction, vector_map_->Get(r), vector_map_->Get(s), type, is_unsigned);
Aart Bikc8e93c72017-05-10 10:49:22 -07001632 }
Aart Bik1f8d51b2018-02-15 10:42:37 -08001633 return true;
1634 }
Aart Bik281c6812016-08-26 11:31:48 -07001635 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08001636 return false;
Aart Bik281c6812016-08-26 11:31:48 -07001637}
1638
Aart Bik38a3f212017-10-20 17:02:21 -07001639uint32_t HLoopOptimization::GetVectorSizeInBytes() {
1640 switch (compiler_driver_->GetInstructionSet()) {
Vladimir Marko33bff252017-11-01 14:35:42 +00001641 case InstructionSet::kArm:
1642 case InstructionSet::kThumb2:
Aart Bik38a3f212017-10-20 17:02:21 -07001643 return 8; // 64-bit SIMD
1644 default:
1645 return 16; // 128-bit SIMD
1646 }
1647}
1648
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001649bool HLoopOptimization::TrySetVectorType(DataType::Type type, uint64_t* restrictions) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001650 const InstructionSetFeatures* features = compiler_driver_->GetInstructionSetFeatures();
1651 switch (compiler_driver_->GetInstructionSet()) {
Vladimir Marko33bff252017-11-01 14:35:42 +00001652 case InstructionSet::kArm:
1653 case InstructionSet::kThumb2:
Artem Serov8f7c4102017-06-21 11:21:37 +01001654 // Allow vectorization for all ARM devices, because Android assumes that
Aart Bikb29f6842017-07-28 15:58:41 -07001655 // ARM 32-bit always supports advanced SIMD (64-bit SIMD).
Artem Serov8f7c4102017-06-21 11:21:37 +01001656 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001657 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001658 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001659 case DataType::Type::kInt8:
Aart Bik0148de42017-09-05 09:25:01 -07001660 *restrictions |= kNoDiv | kNoReduction;
Artem Serov8f7c4102017-06-21 11:21:37 +01001661 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001662 case DataType::Type::kUint16:
1663 case DataType::Type::kInt16:
Aart Bik0148de42017-09-05 09:25:01 -07001664 *restrictions |= kNoDiv | kNoStringCharAt | kNoReduction;
Artem Serov8f7c4102017-06-21 11:21:37 +01001665 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001666 case DataType::Type::kInt32:
Artem Serov6e9b1372017-10-05 16:48:30 +01001667 *restrictions |= kNoDiv | kNoWideSAD;
Artem Serov8f7c4102017-06-21 11:21:37 +01001668 return TrySetVectorLength(2);
1669 default:
1670 break;
1671 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001672 return false;
Vladimir Marko33bff252017-11-01 14:35:42 +00001673 case InstructionSet::kArm64:
Aart Bikf8f5a162017-02-06 15:35:29 -08001674 // Allow vectorization for all ARM devices, because Android assumes that
Aart Bikb29f6842017-07-28 15:58:41 -07001675 // ARMv8 AArch64 always supports advanced SIMD (128-bit SIMD).
Aart Bikf8f5a162017-02-06 15:35:29 -08001676 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001677 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001678 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001679 case DataType::Type::kInt8:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001680 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +01001681 return TrySetVectorLength(16);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001682 case DataType::Type::kUint16:
1683 case DataType::Type::kInt16:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001684 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +01001685 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001686 case DataType::Type::kInt32:
Aart Bikf8f5a162017-02-06 15:35:29 -08001687 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +01001688 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001689 case DataType::Type::kInt64:
Aart Bikc8e93c72017-05-10 10:49:22 -07001690 *restrictions |= kNoDiv | kNoMul | kNoMinMax;
Aart Bikf8f5a162017-02-06 15:35:29 -08001691 return TrySetVectorLength(2);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001692 case DataType::Type::kFloat32:
Aart Bik0148de42017-09-05 09:25:01 -07001693 *restrictions |= kNoReduction;
Artem Serovd4bccf12017-04-03 18:47:32 +01001694 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001695 case DataType::Type::kFloat64:
Aart Bik0148de42017-09-05 09:25:01 -07001696 *restrictions |= kNoReduction;
Aart Bikf8f5a162017-02-06 15:35:29 -08001697 return TrySetVectorLength(2);
1698 default:
1699 return false;
1700 }
Vladimir Marko33bff252017-11-01 14:35:42 +00001701 case InstructionSet::kX86:
1702 case InstructionSet::kX86_64:
Aart Bikb29f6842017-07-28 15:58:41 -07001703 // Allow vectorization for SSE4.1-enabled X86 devices only (128-bit SIMD).
Aart Bikf8f5a162017-02-06 15:35:29 -08001704 if (features->AsX86InstructionSetFeatures()->HasSSE4_1()) {
1705 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001706 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001707 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001708 case DataType::Type::kInt8:
Aart Bik0148de42017-09-05 09:25:01 -07001709 *restrictions |=
Aart Bikdbbac8f2017-09-01 13:06:08 -07001710 kNoMul | kNoDiv | kNoShift | kNoAbs | kNoSignedHAdd | kNoUnroundedHAdd | kNoSAD;
Aart Bikf8f5a162017-02-06 15:35:29 -08001711 return TrySetVectorLength(16);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001712 case DataType::Type::kUint16:
1713 case DataType::Type::kInt16:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001714 *restrictions |= kNoDiv | kNoAbs | kNoSignedHAdd | kNoUnroundedHAdd | kNoSAD;
Aart Bikf8f5a162017-02-06 15:35:29 -08001715 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001716 case DataType::Type::kInt32:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001717 *restrictions |= kNoDiv | kNoSAD;
Aart Bikf8f5a162017-02-06 15:35:29 -08001718 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001719 case DataType::Type::kInt64:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001720 *restrictions |= kNoMul | kNoDiv | kNoShr | kNoAbs | kNoMinMax | kNoSAD;
Aart Bikf8f5a162017-02-06 15:35:29 -08001721 return TrySetVectorLength(2);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001722 case DataType::Type::kFloat32:
Aart Bik0148de42017-09-05 09:25:01 -07001723 *restrictions |= kNoMinMax | kNoReduction; // minmax: -0.0 vs +0.0
Aart Bikf8f5a162017-02-06 15:35:29 -08001724 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001725 case DataType::Type::kFloat64:
Aart Bik0148de42017-09-05 09:25:01 -07001726 *restrictions |= kNoMinMax | kNoReduction; // minmax: -0.0 vs +0.0
Aart Bikf8f5a162017-02-06 15:35:29 -08001727 return TrySetVectorLength(2);
1728 default:
1729 break;
1730 } // switch type
1731 }
1732 return false;
Vladimir Marko33bff252017-11-01 14:35:42 +00001733 case InstructionSet::kMips:
Lena Djokic51765b02017-06-22 13:49:59 +02001734 if (features->AsMipsInstructionSetFeatures()->HasMsa()) {
1735 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001736 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001737 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001738 case DataType::Type::kInt8:
Aart Bik29aa0822018-03-08 11:28:00 -08001739 *restrictions |= kNoDiv | kNoSaturation;
Lena Djokic51765b02017-06-22 13:49:59 +02001740 return TrySetVectorLength(16);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001741 case DataType::Type::kUint16:
1742 case DataType::Type::kInt16:
Aart Bik29aa0822018-03-08 11:28:00 -08001743 *restrictions |= kNoDiv | kNoSaturation | kNoStringCharAt;
Lena Djokic51765b02017-06-22 13:49:59 +02001744 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001745 case DataType::Type::kInt32:
Lena Djokic38e380b2017-10-30 16:17:10 +01001746 *restrictions |= kNoDiv;
Lena Djokic51765b02017-06-22 13:49:59 +02001747 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001748 case DataType::Type::kInt64:
Lena Djokic38e380b2017-10-30 16:17:10 +01001749 *restrictions |= kNoDiv;
Lena Djokic51765b02017-06-22 13:49:59 +02001750 return TrySetVectorLength(2);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001751 case DataType::Type::kFloat32:
Aart Bik0148de42017-09-05 09:25:01 -07001752 *restrictions |= kNoMinMax | kNoReduction; // min/max(x, NaN)
Lena Djokic51765b02017-06-22 13:49:59 +02001753 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001754 case DataType::Type::kFloat64:
Aart Bik0148de42017-09-05 09:25:01 -07001755 *restrictions |= kNoMinMax | kNoReduction; // min/max(x, NaN)
Lena Djokic51765b02017-06-22 13:49:59 +02001756 return TrySetVectorLength(2);
1757 default:
1758 break;
1759 } // switch type
1760 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001761 return false;
Vladimir Marko33bff252017-11-01 14:35:42 +00001762 case InstructionSet::kMips64:
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001763 if (features->AsMips64InstructionSetFeatures()->HasMsa()) {
1764 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001765 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001766 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001767 case DataType::Type::kInt8:
Aart Bik29aa0822018-03-08 11:28:00 -08001768 *restrictions |= kNoDiv | kNoSaturation;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001769 return TrySetVectorLength(16);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001770 case DataType::Type::kUint16:
1771 case DataType::Type::kInt16:
Aart Bik29aa0822018-03-08 11:28:00 -08001772 *restrictions |= kNoDiv | kNoSaturation | kNoStringCharAt;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001773 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001774 case DataType::Type::kInt32:
Lena Djokic38e380b2017-10-30 16:17:10 +01001775 *restrictions |= kNoDiv;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001776 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001777 case DataType::Type::kInt64:
Lena Djokic38e380b2017-10-30 16:17:10 +01001778 *restrictions |= kNoDiv;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001779 return TrySetVectorLength(2);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001780 case DataType::Type::kFloat32:
Aart Bik0148de42017-09-05 09:25:01 -07001781 *restrictions |= kNoMinMax | kNoReduction; // min/max(x, NaN)
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001782 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001783 case DataType::Type::kFloat64:
Aart Bik0148de42017-09-05 09:25:01 -07001784 *restrictions |= kNoMinMax | kNoReduction; // min/max(x, NaN)
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001785 return TrySetVectorLength(2);
1786 default:
1787 break;
1788 } // switch type
1789 }
1790 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001791 default:
1792 return false;
1793 } // switch instruction set
1794}
1795
1796bool HLoopOptimization::TrySetVectorLength(uint32_t length) {
1797 DCHECK(IsPowerOfTwo(length) && length >= 2u);
1798 // First time set?
1799 if (vector_length_ == 0) {
1800 vector_length_ = length;
1801 }
1802 // Different types are acceptable within a loop-body, as long as all the corresponding vector
1803 // lengths match exactly to obtain a uniform traversal through the vector iteration space
1804 // (idiomatic exceptions to this rule can be handled by further unrolling sub-expressions).
1805 return vector_length_ == length;
1806}
1807
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001808void HLoopOptimization::GenerateVecInv(HInstruction* org, DataType::Type type) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001809 if (vector_map_->find(org) == vector_map_->end()) {
1810 // In scalar code, just use a self pass-through for scalar invariants
1811 // (viz. expression remains itself).
1812 if (vector_mode_ == kSequential) {
1813 vector_map_->Put(org, org);
1814 return;
1815 }
1816 // In vector code, explicit scalar expansion is needed.
Aart Bik0148de42017-09-05 09:25:01 -07001817 HInstruction* vector = nullptr;
1818 auto it = vector_permanent_map_->find(org);
1819 if (it != vector_permanent_map_->end()) {
1820 vector = it->second; // reuse during unrolling
1821 } else {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001822 // Generates ReplicateScalar( (optional_type_conv) org ).
1823 HInstruction* input = org;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001824 DataType::Type input_type = input->GetType();
1825 if (type != input_type && (type == DataType::Type::kInt64 ||
1826 input_type == DataType::Type::kInt64)) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001827 input = Insert(vector_preheader_,
1828 new (global_allocator_) HTypeConversion(type, input, kNoDexPc));
1829 }
1830 vector = new (global_allocator_)
Aart Bik46b6dbc2017-10-03 11:37:37 -07001831 HVecReplicateScalar(global_allocator_, input, type, vector_length_, kNoDexPc);
Aart Bik0148de42017-09-05 09:25:01 -07001832 vector_permanent_map_->Put(org, Insert(vector_preheader_, vector));
1833 }
1834 vector_map_->Put(org, vector);
Aart Bikf8f5a162017-02-06 15:35:29 -08001835 }
1836}
1837
1838void HLoopOptimization::GenerateVecSub(HInstruction* org, HInstruction* offset) {
1839 if (vector_map_->find(org) == vector_map_->end()) {
Aart Bik14a68b42017-06-08 14:06:58 -07001840 HInstruction* subscript = vector_index_;
Aart Bik37dc4df2017-06-28 14:08:00 -07001841 int64_t value = 0;
1842 if (!IsInt64AndGet(offset, &value) || value != 0) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001843 subscript = new (global_allocator_) HAdd(DataType::Type::kInt32, subscript, offset);
Aart Bikf8f5a162017-02-06 15:35:29 -08001844 if (org->IsPhi()) {
1845 Insert(vector_body_, subscript); // lacks layout placeholder
1846 }
1847 }
1848 vector_map_->Put(org, subscript);
1849 }
1850}
1851
1852void HLoopOptimization::GenerateVecMem(HInstruction* org,
1853 HInstruction* opa,
1854 HInstruction* opb,
Aart Bik14a68b42017-06-08 14:06:58 -07001855 HInstruction* offset,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001856 DataType::Type type) {
Aart Bik46b6dbc2017-10-03 11:37:37 -07001857 uint32_t dex_pc = org->GetDexPc();
Aart Bikf8f5a162017-02-06 15:35:29 -08001858 HInstruction* vector = nullptr;
1859 if (vector_mode_ == kVector) {
1860 // Vector store or load.
Aart Bik38a3f212017-10-20 17:02:21 -07001861 bool is_string_char_at = false;
Aart Bik14a68b42017-06-08 14:06:58 -07001862 HInstruction* base = org->InputAt(0);
Aart Bikf8f5a162017-02-06 15:35:29 -08001863 if (opb != nullptr) {
1864 vector = new (global_allocator_) HVecStore(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001865 global_allocator_, base, opa, opb, type, org->GetSideEffects(), vector_length_, dex_pc);
Aart Bikf8f5a162017-02-06 15:35:29 -08001866 } else {
Aart Bik38a3f212017-10-20 17:02:21 -07001867 is_string_char_at = org->AsArrayGet()->IsStringCharAt();
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001868 vector = new (global_allocator_) HVecLoad(global_allocator_,
1869 base,
1870 opa,
1871 type,
1872 org->GetSideEffects(),
1873 vector_length_,
Aart Bik46b6dbc2017-10-03 11:37:37 -07001874 is_string_char_at,
1875 dex_pc);
Aart Bik14a68b42017-06-08 14:06:58 -07001876 }
Aart Bik38a3f212017-10-20 17:02:21 -07001877 // Known (forced/adjusted/original) alignment?
1878 if (vector_dynamic_peeling_candidate_ != nullptr) {
1879 if (vector_dynamic_peeling_candidate_->offset == offset && // TODO: diffs too?
1880 DataType::Size(vector_dynamic_peeling_candidate_->type) == DataType::Size(type) &&
1881 vector_dynamic_peeling_candidate_->is_string_char_at == is_string_char_at) {
1882 vector->AsVecMemoryOperation()->SetAlignment( // forced
1883 Alignment(GetVectorSizeInBytes(), 0));
1884 }
1885 } else {
1886 vector->AsVecMemoryOperation()->SetAlignment( // adjusted/original
1887 ComputeAlignment(offset, type, is_string_char_at, vector_static_peeling_factor_));
Aart Bikf8f5a162017-02-06 15:35:29 -08001888 }
1889 } else {
1890 // Scalar store or load.
1891 DCHECK(vector_mode_ == kSequential);
1892 if (opb != nullptr) {
Aart Bik4d1a9d42017-10-19 14:40:55 -07001893 DataType::Type component_type = org->AsArraySet()->GetComponentType();
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001894 vector = new (global_allocator_) HArraySet(
Aart Bik4d1a9d42017-10-19 14:40:55 -07001895 org->InputAt(0), opa, opb, component_type, org->GetSideEffects(), dex_pc);
Aart Bikf8f5a162017-02-06 15:35:29 -08001896 } else {
Aart Bikdb14fcf2017-04-25 15:53:58 -07001897 bool is_string_char_at = org->AsArrayGet()->IsStringCharAt();
1898 vector = new (global_allocator_) HArrayGet(
Aart Bik4d1a9d42017-10-19 14:40:55 -07001899 org->InputAt(0), opa, org->GetType(), org->GetSideEffects(), dex_pc, is_string_char_at);
Aart Bikf8f5a162017-02-06 15:35:29 -08001900 }
1901 }
1902 vector_map_->Put(org, vector);
1903}
1904
Aart Bik0148de42017-09-05 09:25:01 -07001905void HLoopOptimization::GenerateVecReductionPhi(HPhi* phi) {
1906 DCHECK(reductions_->find(phi) != reductions_->end());
1907 DCHECK(reductions_->Get(phi->InputAt(1)) == phi);
1908 HInstruction* vector = nullptr;
1909 if (vector_mode_ == kSequential) {
1910 HPhi* new_phi = new (global_allocator_) HPhi(
1911 global_allocator_, kNoRegNumber, 0, phi->GetType());
1912 vector_header_->AddPhi(new_phi);
1913 vector = new_phi;
1914 } else {
1915 // Link vector reduction back to prior unrolled update, or a first phi.
1916 auto it = vector_permanent_map_->find(phi);
1917 if (it != vector_permanent_map_->end()) {
1918 vector = it->second;
1919 } else {
1920 HPhi* new_phi = new (global_allocator_) HPhi(
1921 global_allocator_, kNoRegNumber, 0, HVecOperation::kSIMDType);
1922 vector_header_->AddPhi(new_phi);
1923 vector = new_phi;
1924 }
1925 }
1926 vector_map_->Put(phi, vector);
1927}
1928
1929void HLoopOptimization::GenerateVecReductionPhiInputs(HPhi* phi, HInstruction* reduction) {
1930 HInstruction* new_phi = vector_map_->Get(phi);
1931 HInstruction* new_init = reductions_->Get(phi);
1932 HInstruction* new_red = vector_map_->Get(reduction);
1933 // Link unrolled vector loop back to new phi.
1934 for (; !new_phi->IsPhi(); new_phi = vector_permanent_map_->Get(new_phi)) {
1935 DCHECK(new_phi->IsVecOperation());
1936 }
1937 // Prepare the new initialization.
1938 if (vector_mode_ == kVector) {
Goran Jakovljevic89b8df02017-10-13 08:33:17 +02001939 // Generate a [initial, 0, .., 0] vector for add or
1940 // a [initial, initial, .., initial] vector for min/max.
Aart Bikdbbac8f2017-09-01 13:06:08 -07001941 HVecOperation* red_vector = new_red->AsVecOperation();
Goran Jakovljevic89b8df02017-10-13 08:33:17 +02001942 HVecReduce::ReductionKind kind = GetReductionKind(red_vector);
Aart Bik38a3f212017-10-20 17:02:21 -07001943 uint32_t vector_length = red_vector->GetVectorLength();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001944 DataType::Type type = red_vector->GetPackedType();
Goran Jakovljevic89b8df02017-10-13 08:33:17 +02001945 if (kind == HVecReduce::ReductionKind::kSum) {
1946 new_init = Insert(vector_preheader_,
1947 new (global_allocator_) HVecSetScalars(global_allocator_,
1948 &new_init,
1949 type,
1950 vector_length,
1951 1,
1952 kNoDexPc));
1953 } else {
1954 new_init = Insert(vector_preheader_,
1955 new (global_allocator_) HVecReplicateScalar(global_allocator_,
1956 new_init,
1957 type,
1958 vector_length,
1959 kNoDexPc));
1960 }
Aart Bik0148de42017-09-05 09:25:01 -07001961 } else {
1962 new_init = ReduceAndExtractIfNeeded(new_init);
1963 }
1964 // Set the phi inputs.
1965 DCHECK(new_phi->IsPhi());
1966 new_phi->AsPhi()->AddInput(new_init);
1967 new_phi->AsPhi()->AddInput(new_red);
1968 // New feed value for next phi (safe mutation in iteration).
1969 reductions_->find(phi)->second = new_phi;
1970}
1971
1972HInstruction* HLoopOptimization::ReduceAndExtractIfNeeded(HInstruction* instruction) {
1973 if (instruction->IsPhi()) {
1974 HInstruction* input = instruction->InputAt(1);
Aart Bik2dd7b672017-12-07 11:11:22 -08001975 if (HVecOperation::ReturnsSIMDValue(input)) {
1976 DCHECK(!input->IsPhi());
Aart Bikdbbac8f2017-09-01 13:06:08 -07001977 HVecOperation* input_vector = input->AsVecOperation();
Aart Bik38a3f212017-10-20 17:02:21 -07001978 uint32_t vector_length = input_vector->GetVectorLength();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001979 DataType::Type type = input_vector->GetPackedType();
Aart Bikdbbac8f2017-09-01 13:06:08 -07001980 HVecReduce::ReductionKind kind = GetReductionKind(input_vector);
Aart Bik0148de42017-09-05 09:25:01 -07001981 HBasicBlock* exit = instruction->GetBlock()->GetSuccessors()[0];
1982 // Generate a vector reduction and scalar extract
1983 // x = REDUCE( [x_1, .., x_n] )
1984 // y = x_1
1985 // along the exit of the defining loop.
Aart Bik0148de42017-09-05 09:25:01 -07001986 HInstruction* reduce = new (global_allocator_) HVecReduce(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001987 global_allocator_, instruction, type, vector_length, kind, kNoDexPc);
Aart Bik0148de42017-09-05 09:25:01 -07001988 exit->InsertInstructionBefore(reduce, exit->GetFirstInstruction());
1989 instruction = new (global_allocator_) HVecExtractScalar(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001990 global_allocator_, reduce, type, vector_length, 0, kNoDexPc);
Aart Bik0148de42017-09-05 09:25:01 -07001991 exit->InsertInstructionAfter(instruction, reduce);
1992 }
1993 }
1994 return instruction;
1995}
1996
Aart Bikf8f5a162017-02-06 15:35:29 -08001997#define GENERATE_VEC(x, y) \
1998 if (vector_mode_ == kVector) { \
1999 vector = (x); \
2000 } else { \
2001 DCHECK(vector_mode_ == kSequential); \
2002 vector = (y); \
2003 } \
2004 break;
2005
2006void HLoopOptimization::GenerateVecOp(HInstruction* org,
2007 HInstruction* opa,
2008 HInstruction* opb,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002009 DataType::Type type,
Aart Bik304c8a52017-05-23 11:01:13 -07002010 bool is_unsigned) {
Aart Bik46b6dbc2017-10-03 11:37:37 -07002011 uint32_t dex_pc = org->GetDexPc();
Aart Bikf8f5a162017-02-06 15:35:29 -08002012 HInstruction* vector = nullptr;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002013 DataType::Type org_type = org->GetType();
Aart Bikf8f5a162017-02-06 15:35:29 -08002014 switch (org->GetKind()) {
2015 case HInstruction::kNeg:
2016 DCHECK(opb == nullptr);
2017 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07002018 new (global_allocator_) HVecNeg(global_allocator_, opa, type, vector_length_, dex_pc),
2019 new (global_allocator_) HNeg(org_type, opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08002020 case HInstruction::kNot:
2021 DCHECK(opb == nullptr);
2022 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07002023 new (global_allocator_) HVecNot(global_allocator_, opa, type, vector_length_, dex_pc),
2024 new (global_allocator_) HNot(org_type, opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08002025 case HInstruction::kBooleanNot:
2026 DCHECK(opb == nullptr);
2027 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07002028 new (global_allocator_) HVecNot(global_allocator_, opa, type, vector_length_, dex_pc),
2029 new (global_allocator_) HBooleanNot(opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08002030 case HInstruction::kTypeConversion:
2031 DCHECK(opb == nullptr);
2032 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07002033 new (global_allocator_) HVecCnv(global_allocator_, opa, type, vector_length_, dex_pc),
2034 new (global_allocator_) HTypeConversion(org_type, opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08002035 case HInstruction::kAdd:
2036 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07002037 new (global_allocator_) HVecAdd(global_allocator_, opa, opb, type, vector_length_, dex_pc),
2038 new (global_allocator_) HAdd(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08002039 case HInstruction::kSub:
2040 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07002041 new (global_allocator_) HVecSub(global_allocator_, opa, opb, type, vector_length_, dex_pc),
2042 new (global_allocator_) HSub(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08002043 case HInstruction::kMul:
2044 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07002045 new (global_allocator_) HVecMul(global_allocator_, opa, opb, type, vector_length_, dex_pc),
2046 new (global_allocator_) HMul(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08002047 case HInstruction::kDiv:
2048 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07002049 new (global_allocator_) HVecDiv(global_allocator_, opa, opb, type, vector_length_, dex_pc),
2050 new (global_allocator_) HDiv(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08002051 case HInstruction::kAnd:
2052 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07002053 new (global_allocator_) HVecAnd(global_allocator_, opa, opb, type, vector_length_, dex_pc),
2054 new (global_allocator_) HAnd(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08002055 case HInstruction::kOr:
2056 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07002057 new (global_allocator_) HVecOr(global_allocator_, opa, opb, type, vector_length_, dex_pc),
2058 new (global_allocator_) HOr(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08002059 case HInstruction::kXor:
2060 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07002061 new (global_allocator_) HVecXor(global_allocator_, opa, opb, type, vector_length_, dex_pc),
2062 new (global_allocator_) HXor(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08002063 case HInstruction::kShl:
2064 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07002065 new (global_allocator_) HVecShl(global_allocator_, opa, opb, type, vector_length_, dex_pc),
2066 new (global_allocator_) HShl(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08002067 case HInstruction::kShr:
2068 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07002069 new (global_allocator_) HVecShr(global_allocator_, opa, opb, type, vector_length_, dex_pc),
2070 new (global_allocator_) HShr(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08002071 case HInstruction::kUShr:
2072 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07002073 new (global_allocator_) HVecUShr(global_allocator_, opa, opb, type, vector_length_, dex_pc),
2074 new (global_allocator_) HUShr(org_type, opa, opb, dex_pc));
Aart Bik1f8d51b2018-02-15 10:42:37 -08002075 case HInstruction::kMin:
2076 GENERATE_VEC(
2077 new (global_allocator_) HVecMin(global_allocator_,
2078 opa,
2079 opb,
2080 HVecOperation::ToProperType(type, is_unsigned),
2081 vector_length_,
2082 dex_pc),
2083 new (global_allocator_) HMin(org_type, opa, opb, dex_pc));
2084 case HInstruction::kMax:
2085 GENERATE_VEC(
2086 new (global_allocator_) HVecMax(global_allocator_,
2087 opa,
2088 opb,
2089 HVecOperation::ToProperType(type, is_unsigned),
2090 vector_length_,
2091 dex_pc),
2092 new (global_allocator_) HMax(org_type, opa, opb, dex_pc));
Aart Bik3b2a5952018-03-05 13:55:28 -08002093 case HInstruction::kAbs:
2094 DCHECK(opb == nullptr);
2095 GENERATE_VEC(
2096 new (global_allocator_) HVecAbs(global_allocator_, opa, type, vector_length_, dex_pc),
2097 new (global_allocator_) HAbs(org_type, opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08002098 default:
2099 break;
2100 } // switch
2101 CHECK(vector != nullptr) << "Unsupported SIMD operator";
2102 vector_map_->Put(org, vector);
2103}
2104
2105#undef GENERATE_VEC
2106
2107//
Aart Bikf3e61ee2017-04-12 17:09:20 -07002108// Vectorization idioms.
2109//
2110
Aart Bik29aa0822018-03-08 11:28:00 -08002111// Method recognizes single and double clipping saturation arithmetic.
2112bool HLoopOptimization::VectorizeSaturationIdiom(LoopNode* node,
2113 HInstruction* instruction,
2114 bool generate_code,
2115 DataType::Type type,
2116 uint64_t restrictions) {
2117 // Deal with vector restrictions.
2118 if (HasVectorRestrictions(restrictions, kNoSaturation)) {
2119 return false;
2120 }
Aart Bik1a381022018-03-15 15:51:37 -07002121 // Restrict type (generalize if one day we generalize allowed MIN/MAX integral types).
2122 if (instruction->GetType() != DataType::Type::kInt32 &&
2123 instruction->GetType() != DataType::Type::kInt64) {
Aart Bik29aa0822018-03-08 11:28:00 -08002124 return false;
2125 }
Nicolas Geoffraya3e23262018-03-28 11:15:12 +00002126 // Clipped addition or subtraction on narrower operands? We will try both
2127 // formats since, e.g., x+c can be interpreted as x+c and x-(-c), depending
2128 // on what clipping values are used, to get most benefits.
Aart Bik1a381022018-03-15 15:51:37 -07002129 int64_t lo = std::numeric_limits<int64_t>::min();
2130 int64_t hi = std::numeric_limits<int64_t>::max();
2131 HInstruction* clippee = FindClippee(instruction, &lo, &hi);
Nicolas Geoffraya3e23262018-03-28 11:15:12 +00002132 HInstruction* a = nullptr;
2133 HInstruction* b = nullptr;
Aart Bik29aa0822018-03-08 11:28:00 -08002134 HInstruction* r = nullptr;
2135 HInstruction* s = nullptr;
2136 bool is_unsigned = false;
Nicolas Geoffraya3e23262018-03-28 11:15:12 +00002137 bool is_add = true;
2138 int64_t c = 0;
2139 // First try for saturated addition.
2140 if (IsAddConst2(graph_, clippee, /*out*/ &a, /*out*/ &b, /*out*/ &c) && c == 0 &&
2141 IsNarrowerOperands(a, b, type, &r, &s, &is_unsigned) &&
2142 IsSaturatedAdd(r, s, type, lo, hi, is_unsigned)) {
2143 is_add = true;
Aart Bik29aa0822018-03-08 11:28:00 -08002144 } else {
Nicolas Geoffraya3e23262018-03-28 11:15:12 +00002145 // Then try again for saturated subtraction.
2146 a = b = r = s = nullptr;
2147 if (IsSubConst2(graph_, clippee, /*out*/ &a, /*out*/ &b) &&
2148 IsNarrowerOperands(a, b, type, &r, &s, &is_unsigned) &&
2149 IsSaturatedSub(r, type, lo, hi, is_unsigned)) {
2150 is_add = false;
2151 } else {
2152 return false;
2153 }
Aart Bik29aa0822018-03-08 11:28:00 -08002154 }
2155 // Accept saturation idiom for vectorizable operands.
Nicolas Geoffraya3e23262018-03-28 11:15:12 +00002156 DCHECK(r != nullptr && s != nullptr);
Aart Bik29aa0822018-03-08 11:28:00 -08002157 if (generate_code && vector_mode_ != kVector) { // de-idiom
2158 r = instruction->InputAt(0);
2159 s = instruction->InputAt(1);
2160 restrictions &= ~(kNoHiBits | kNoMinMax); // allow narrow MIN/MAX in seq
2161 }
2162 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
2163 VectorizeUse(node, s, generate_code, type, restrictions)) {
2164 if (generate_code) {
2165 if (vector_mode_ == kVector) {
2166 DataType::Type vtype = HVecOperation::ToProperType(type, is_unsigned);
2167 HInstruction* op1 = vector_map_->Get(r);
2168 HInstruction* op2 = vector_map_->Get(s);
2169 vector_map_->Put(instruction, is_add
2170 ? reinterpret_cast<HInstruction*>(new (global_allocator_) HVecSaturationAdd(
2171 global_allocator_, op1, op2, vtype, vector_length_, kNoDexPc))
2172 : reinterpret_cast<HInstruction*>(new (global_allocator_) HVecSaturationSub(
2173 global_allocator_, op1, op2, vtype, vector_length_, kNoDexPc)));
2174 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorizedIdiom);
2175 } else {
2176 GenerateVecOp(instruction, vector_map_->Get(r), vector_map_->Get(s), type);
2177 }
2178 }
2179 return true;
2180 }
2181 return false;
2182}
2183
Aart Bikf3e61ee2017-04-12 17:09:20 -07002184// Method recognizes the following idioms:
Aart Bikdbbac8f2017-09-01 13:06:08 -07002185// rounding halving add (a + b + 1) >> 1 for unsigned/signed operands a, b
2186// truncated halving add (a + b) >> 1 for unsigned/signed operands a, b
Aart Bikf3e61ee2017-04-12 17:09:20 -07002187// Provided that the operands are promoted to a wider form to do the arithmetic and
2188// then cast back to narrower form, the idioms can be mapped into efficient SIMD
2189// implementation that operates directly in narrower form (plus one extra bit).
2190// TODO: current version recognizes implicit byte/short/char widening only;
2191// explicit widening from int to long could be added later.
2192bool HLoopOptimization::VectorizeHalvingAddIdiom(LoopNode* node,
2193 HInstruction* instruction,
2194 bool generate_code,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002195 DataType::Type type,
Aart Bikf3e61ee2017-04-12 17:09:20 -07002196 uint64_t restrictions) {
2197 // Test for top level arithmetic shift right x >> 1 or logical shift right x >>> 1
Aart Bik304c8a52017-05-23 11:01:13 -07002198 // (note whether the sign bit in wider precision is shifted in has no effect
Aart Bikf3e61ee2017-04-12 17:09:20 -07002199 // on the narrow precision computed by the idiom).
Aart Bikf3e61ee2017-04-12 17:09:20 -07002200 if ((instruction->IsShr() ||
2201 instruction->IsUShr()) &&
Aart Bik0148de42017-09-05 09:25:01 -07002202 IsInt64Value(instruction->InputAt(1), 1)) {
Aart Bik5f805002017-05-16 16:42:41 -07002203 // Test for (a + b + c) >> 1 for optional constant c.
2204 HInstruction* a = nullptr;
2205 HInstruction* b = nullptr;
2206 int64_t c = 0;
Nicolas Geoffraya3e23262018-03-28 11:15:12 +00002207 if (IsAddConst2(graph_, instruction->InputAt(0), /*out*/ &a, /*out*/ &b, /*out*/ &c)) {
Aart Bik5f805002017-05-16 16:42:41 -07002208 // Accept c == 1 (rounded) or c == 0 (not rounded).
2209 bool is_rounded = false;
2210 if (c == 1) {
2211 is_rounded = true;
2212 } else if (c != 0) {
2213 return false;
2214 }
2215 // Accept consistent zero or sign extension on operands a and b.
Aart Bikf3e61ee2017-04-12 17:09:20 -07002216 HInstruction* r = nullptr;
2217 HInstruction* s = nullptr;
2218 bool is_unsigned = false;
Aart Bik304c8a52017-05-23 11:01:13 -07002219 if (!IsNarrowerOperands(a, b, type, &r, &s, &is_unsigned)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -07002220 return false;
2221 }
2222 // Deal with vector restrictions.
2223 if ((!is_unsigned && HasVectorRestrictions(restrictions, kNoSignedHAdd)) ||
2224 (!is_rounded && HasVectorRestrictions(restrictions, kNoUnroundedHAdd))) {
2225 return false;
2226 }
2227 // Accept recognized halving add for vectorizable operands. Vectorized code uses the
2228 // shorthand idiomatic operation. Sequential code uses the original scalar expressions.
Nicolas Geoffraya3e23262018-03-28 11:15:12 +00002229 DCHECK(r != nullptr && s != nullptr);
Aart Bik304c8a52017-05-23 11:01:13 -07002230 if (generate_code && vector_mode_ != kVector) { // de-idiom
2231 r = instruction->InputAt(0);
2232 s = instruction->InputAt(1);
2233 }
Aart Bikf3e61ee2017-04-12 17:09:20 -07002234 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
2235 VectorizeUse(node, s, generate_code, type, restrictions)) {
2236 if (generate_code) {
2237 if (vector_mode_ == kVector) {
2238 vector_map_->Put(instruction, new (global_allocator_) HVecHalvingAdd(
2239 global_allocator_,
2240 vector_map_->Get(r),
2241 vector_map_->Get(s),
Aart Bik66c158e2018-01-31 12:55:04 -08002242 HVecOperation::ToProperType(type, is_unsigned),
Aart Bikf3e61ee2017-04-12 17:09:20 -07002243 vector_length_,
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01002244 is_rounded,
Aart Bik46b6dbc2017-10-03 11:37:37 -07002245 kNoDexPc));
Aart Bik21b85922017-09-06 13:29:16 -07002246 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorizedIdiom);
Aart Bikf3e61ee2017-04-12 17:09:20 -07002247 } else {
Aart Bik304c8a52017-05-23 11:01:13 -07002248 GenerateVecOp(instruction, vector_map_->Get(r), vector_map_->Get(s), type);
Aart Bikf3e61ee2017-04-12 17:09:20 -07002249 }
2250 }
2251 return true;
2252 }
2253 }
2254 }
2255 return false;
2256}
2257
Aart Bikdbbac8f2017-09-01 13:06:08 -07002258// Method recognizes the following idiom:
2259// q += ABS(a - b) for signed operands a, b
2260// Provided that the operands have the same type or are promoted to a wider form.
2261// Since this may involve a vector length change, the idiom is handled by going directly
2262// to a sad-accumulate node (rather than relying combining finer grained nodes later).
2263// TODO: unsigned SAD too?
2264bool HLoopOptimization::VectorizeSADIdiom(LoopNode* node,
2265 HInstruction* instruction,
2266 bool generate_code,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002267 DataType::Type reduction_type,
Aart Bikdbbac8f2017-09-01 13:06:08 -07002268 uint64_t restrictions) {
2269 // Filter integral "q += ABS(a - b);" reduction, where ABS and SUB
2270 // are done in the same precision (either int or long).
2271 if (!instruction->IsAdd() ||
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002272 (reduction_type != DataType::Type::kInt32 && reduction_type != DataType::Type::kInt64)) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07002273 return false;
2274 }
2275 HInstruction* q = instruction->InputAt(0);
2276 HInstruction* v = instruction->InputAt(1);
2277 HInstruction* a = nullptr;
2278 HInstruction* b = nullptr;
Nicolas Geoffraya3e23262018-03-28 11:15:12 +00002279 if (v->IsAbs() &&
2280 v->GetType() == reduction_type &&
2281 IsSubConst2(graph_, v->InputAt(0), /*out*/ &a, /*out*/ &b)) {
2282 DCHECK(a != nullptr && b != nullptr);
2283 } else {
Aart Bikdbbac8f2017-09-01 13:06:08 -07002284 return false;
2285 }
2286 // Accept same-type or consistent sign extension for narrower-type on operands a and b.
2287 // The same-type or narrower operands are called r (a or lower) and s (b or lower).
Aart Bikdf011c32017-09-28 12:53:04 -07002288 // We inspect the operands carefully to pick the most suited type.
Aart Bikdbbac8f2017-09-01 13:06:08 -07002289 HInstruction* r = a;
2290 HInstruction* s = b;
2291 bool is_unsigned = false;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002292 DataType::Type sub_type = a->GetType();
Aart Bikdf011c32017-09-28 12:53:04 -07002293 if (DataType::Size(b->GetType()) < DataType::Size(sub_type)) {
2294 sub_type = b->GetType();
2295 }
2296 if (a->IsTypeConversion() &&
2297 DataType::Size(a->InputAt(0)->GetType()) < DataType::Size(sub_type)) {
2298 sub_type = a->InputAt(0)->GetType();
2299 }
2300 if (b->IsTypeConversion() &&
2301 DataType::Size(b->InputAt(0)->GetType()) < DataType::Size(sub_type)) {
2302 sub_type = b->InputAt(0)->GetType();
Aart Bikdbbac8f2017-09-01 13:06:08 -07002303 }
2304 if (reduction_type != sub_type &&
2305 (!IsNarrowerOperands(a, b, sub_type, &r, &s, &is_unsigned) || is_unsigned)) {
2306 return false;
2307 }
2308 // Try same/narrower type and deal with vector restrictions.
Artem Serov6e9b1372017-10-05 16:48:30 +01002309 if (!TrySetVectorType(sub_type, &restrictions) ||
2310 HasVectorRestrictions(restrictions, kNoSAD) ||
2311 (reduction_type != sub_type && HasVectorRestrictions(restrictions, kNoWideSAD))) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07002312 return false;
2313 }
2314 // Accept SAD idiom for vectorizable operands. Vectorized code uses the shorthand
2315 // idiomatic operation. Sequential code uses the original scalar expressions.
Nicolas Geoffraya3e23262018-03-28 11:15:12 +00002316 DCHECK(r != nullptr && s != nullptr);
Aart Bikdbbac8f2017-09-01 13:06:08 -07002317 if (generate_code && vector_mode_ != kVector) { // de-idiom
2318 r = s = v->InputAt(0);
2319 }
2320 if (VectorizeUse(node, q, generate_code, sub_type, restrictions) &&
2321 VectorizeUse(node, r, generate_code, sub_type, restrictions) &&
2322 VectorizeUse(node, s, generate_code, sub_type, restrictions)) {
2323 if (generate_code) {
2324 if (vector_mode_ == kVector) {
2325 vector_map_->Put(instruction, new (global_allocator_) HVecSADAccumulate(
2326 global_allocator_,
2327 vector_map_->Get(q),
2328 vector_map_->Get(r),
2329 vector_map_->Get(s),
Aart Bik3b2a5952018-03-05 13:55:28 -08002330 HVecOperation::ToProperType(reduction_type, is_unsigned),
Aart Bik46b6dbc2017-10-03 11:37:37 -07002331 GetOtherVL(reduction_type, sub_type, vector_length_),
2332 kNoDexPc));
Aart Bikdbbac8f2017-09-01 13:06:08 -07002333 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorizedIdiom);
2334 } else {
2335 GenerateVecOp(v, vector_map_->Get(r), nullptr, reduction_type);
2336 GenerateVecOp(instruction, vector_map_->Get(q), vector_map_->Get(v), reduction_type);
2337 }
2338 }
2339 return true;
2340 }
2341 return false;
2342}
2343
Aart Bikf3e61ee2017-04-12 17:09:20 -07002344//
Aart Bik14a68b42017-06-08 14:06:58 -07002345// Vectorization heuristics.
2346//
2347
Aart Bik38a3f212017-10-20 17:02:21 -07002348Alignment HLoopOptimization::ComputeAlignment(HInstruction* offset,
2349 DataType::Type type,
2350 bool is_string_char_at,
2351 uint32_t peeling) {
2352 // Combine the alignment and hidden offset that is guaranteed by
2353 // the Android runtime with a known starting index adjusted as bytes.
2354 int64_t value = 0;
2355 if (IsInt64AndGet(offset, /*out*/ &value)) {
2356 uint32_t start_offset =
2357 HiddenOffset(type, is_string_char_at) + (value + peeling) * DataType::Size(type);
2358 return Alignment(BaseAlignment(), start_offset & (BaseAlignment() - 1u));
2359 }
2360 // Otherwise, the Android runtime guarantees at least natural alignment.
2361 return Alignment(DataType::Size(type), 0);
2362}
2363
2364void HLoopOptimization::SetAlignmentStrategy(uint32_t peeling_votes[],
2365 const ArrayReference* peeling_candidate) {
2366 // Current heuristic: pick the best static loop peeling factor, if any,
2367 // or otherwise use dynamic loop peeling on suggested peeling candidate.
2368 uint32_t max_vote = 0;
2369 for (int32_t i = 0; i < 16; i++) {
2370 if (peeling_votes[i] > max_vote) {
2371 max_vote = peeling_votes[i];
2372 vector_static_peeling_factor_ = i;
2373 }
2374 }
2375 if (max_vote == 0) {
2376 vector_dynamic_peeling_candidate_ = peeling_candidate;
2377 }
2378}
2379
2380uint32_t HLoopOptimization::MaxNumberPeeled() {
2381 if (vector_dynamic_peeling_candidate_ != nullptr) {
2382 return vector_length_ - 1u; // worst-case
2383 }
2384 return vector_static_peeling_factor_; // known exactly
2385}
2386
Aart Bik14a68b42017-06-08 14:06:58 -07002387bool HLoopOptimization::IsVectorizationProfitable(int64_t trip_count) {
Aart Bik38a3f212017-10-20 17:02:21 -07002388 // Current heuristic: non-empty body with sufficient number of iterations (if known).
Aart Bik14a68b42017-06-08 14:06:58 -07002389 // TODO: refine by looking at e.g. operation count, alignment, etc.
Aart Bik38a3f212017-10-20 17:02:21 -07002390 // TODO: trip count is really unsigned entity, provided the guarding test
2391 // is satisfied; deal with this more carefully later
2392 uint32_t max_peel = MaxNumberPeeled();
Aart Bik14a68b42017-06-08 14:06:58 -07002393 if (vector_length_ == 0) {
2394 return false; // nothing found
Aart Bik38a3f212017-10-20 17:02:21 -07002395 } else if (trip_count < 0) {
2396 return false; // guard against non-taken/large
2397 } else if ((0 < trip_count) && (trip_count < (vector_length_ + max_peel))) {
Aart Bik14a68b42017-06-08 14:06:58 -07002398 return false; // insufficient iterations
2399 }
2400 return true;
2401}
2402
Aart Bik14a68b42017-06-08 14:06:58 -07002403//
Aart Bikf8f5a162017-02-06 15:35:29 -08002404// Helpers.
2405//
2406
2407bool HLoopOptimization::TrySetPhiInduction(HPhi* phi, bool restrict_uses) {
Aart Bikb29f6842017-07-28 15:58:41 -07002408 // Start with empty phi induction.
2409 iset_->clear();
2410
Nicolas Geoffrayf57c1ae2017-06-28 17:40:18 +01002411 // Special case Phis that have equivalent in a debuggable setup. Our graph checker isn't
2412 // smart enough to follow strongly connected components (and it's probably not worth
2413 // it to make it so). See b/33775412.
2414 if (graph_->IsDebuggable() && phi->HasEquivalentPhi()) {
2415 return false;
2416 }
Aart Bikb29f6842017-07-28 15:58:41 -07002417
2418 // Lookup phi induction cycle.
Aart Bikcc42be02016-10-20 16:14:16 -07002419 ArenaSet<HInstruction*>* set = induction_range_.LookupCycle(phi);
2420 if (set != nullptr) {
2421 for (HInstruction* i : *set) {
Aart Bike3dedc52016-11-02 17:50:27 -07002422 // Check that, other than instructions that are no longer in the graph (removed earlier)
Aart Bikf8f5a162017-02-06 15:35:29 -08002423 // each instruction is removable and, when restrict uses are requested, other than for phi,
2424 // all uses are contained within the cycle.
Aart Bike3dedc52016-11-02 17:50:27 -07002425 if (!i->IsInBlock()) {
2426 continue;
2427 } else if (!i->IsRemovable()) {
2428 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08002429 } else if (i != phi && restrict_uses) {
Aart Bikb29f6842017-07-28 15:58:41 -07002430 // Deal with regular uses.
Aart Bikcc42be02016-10-20 16:14:16 -07002431 for (const HUseListNode<HInstruction*>& use : i->GetUses()) {
2432 if (set->find(use.GetUser()) == set->end()) {
2433 return false;
2434 }
2435 }
2436 }
Aart Bike3dedc52016-11-02 17:50:27 -07002437 iset_->insert(i); // copy
Aart Bikcc42be02016-10-20 16:14:16 -07002438 }
Aart Bikcc42be02016-10-20 16:14:16 -07002439 return true;
2440 }
2441 return false;
2442}
2443
Aart Bikb29f6842017-07-28 15:58:41 -07002444bool HLoopOptimization::TrySetPhiReduction(HPhi* phi) {
Aart Bikcc42be02016-10-20 16:14:16 -07002445 DCHECK(iset_->empty());
Aart Bikb29f6842017-07-28 15:58:41 -07002446 // Only unclassified phi cycles are candidates for reductions.
2447 if (induction_range_.IsClassified(phi)) {
2448 return false;
2449 }
2450 // Accept operations like x = x + .., provided that the phi and the reduction are
2451 // used exactly once inside the loop, and by each other.
2452 HInputsRef inputs = phi->GetInputs();
2453 if (inputs.size() == 2) {
2454 HInstruction* reduction = inputs[1];
2455 if (HasReductionFormat(reduction, phi)) {
2456 HLoopInformation* loop_info = phi->GetBlock()->GetLoopInformation();
Aart Bik38a3f212017-10-20 17:02:21 -07002457 uint32_t use_count = 0;
Aart Bikb29f6842017-07-28 15:58:41 -07002458 bool single_use_inside_loop =
2459 // Reduction update only used by phi.
2460 reduction->GetUses().HasExactlyOneElement() &&
2461 !reduction->HasEnvironmentUses() &&
2462 // Reduction update is only use of phi inside the loop.
2463 IsOnlyUsedAfterLoop(loop_info, phi, /*collect_loop_uses*/ true, &use_count) &&
2464 iset_->size() == 1;
2465 iset_->clear(); // leave the way you found it
2466 if (single_use_inside_loop) {
2467 // Link reduction back, and start recording feed value.
2468 reductions_->Put(reduction, phi);
2469 reductions_->Put(phi, phi->InputAt(0));
2470 return true;
2471 }
2472 }
2473 }
2474 return false;
2475}
2476
2477bool HLoopOptimization::TrySetSimpleLoopHeader(HBasicBlock* block, /*out*/ HPhi** main_phi) {
2478 // Start with empty phi induction and reductions.
2479 iset_->clear();
2480 reductions_->clear();
2481
2482 // Scan the phis to find the following (the induction structure has already
2483 // been optimized, so we don't need to worry about trivial cases):
2484 // (1) optional reductions in loop,
2485 // (2) the main induction, used in loop control.
2486 HPhi* phi = nullptr;
2487 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
2488 if (TrySetPhiReduction(it.Current()->AsPhi())) {
2489 continue;
2490 } else if (phi == nullptr) {
2491 // Found the first candidate for main induction.
2492 phi = it.Current()->AsPhi();
2493 } else {
2494 return false;
2495 }
2496 }
2497
2498 // Then test for a typical loopheader:
2499 // s: SuspendCheck
2500 // c: Condition(phi, bound)
2501 // i: If(c)
2502 if (phi != nullptr && TrySetPhiInduction(phi, /*restrict_uses*/ false)) {
Aart Bikcc42be02016-10-20 16:14:16 -07002503 HInstruction* s = block->GetFirstInstruction();
2504 if (s != nullptr && s->IsSuspendCheck()) {
2505 HInstruction* c = s->GetNext();
Aart Bikd86c0852017-04-14 12:00:15 -07002506 if (c != nullptr &&
2507 c->IsCondition() &&
2508 c->GetUses().HasExactlyOneElement() && // only used for termination
2509 !c->HasEnvironmentUses()) { // unlikely, but not impossible
Aart Bikcc42be02016-10-20 16:14:16 -07002510 HInstruction* i = c->GetNext();
2511 if (i != nullptr && i->IsIf() && i->InputAt(0) == c) {
2512 iset_->insert(c);
2513 iset_->insert(s);
Aart Bikb29f6842017-07-28 15:58:41 -07002514 *main_phi = phi;
Aart Bikcc42be02016-10-20 16:14:16 -07002515 return true;
2516 }
2517 }
2518 }
2519 }
2520 return false;
2521}
2522
2523bool HLoopOptimization::IsEmptyBody(HBasicBlock* block) {
Aart Bikf8f5a162017-02-06 15:35:29 -08002524 if (!block->GetPhis().IsEmpty()) {
2525 return false;
2526 }
2527 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
2528 HInstruction* instruction = it.Current();
2529 if (!instruction->IsGoto() && iset_->find(instruction) == iset_->end()) {
2530 return false;
Aart Bikcc42be02016-10-20 16:14:16 -07002531 }
Aart Bikf8f5a162017-02-06 15:35:29 -08002532 }
2533 return true;
2534}
2535
2536bool HLoopOptimization::IsUsedOutsideLoop(HLoopInformation* loop_info,
2537 HInstruction* instruction) {
Aart Bikb29f6842017-07-28 15:58:41 -07002538 // Deal with regular uses.
Aart Bikf8f5a162017-02-06 15:35:29 -08002539 for (const HUseListNode<HInstruction*>& use : instruction->GetUses()) {
2540 if (use.GetUser()->GetBlock()->GetLoopInformation() != loop_info) {
2541 return true;
2542 }
Aart Bikcc42be02016-10-20 16:14:16 -07002543 }
2544 return false;
2545}
2546
Aart Bik482095d2016-10-10 15:39:10 -07002547bool HLoopOptimization::IsOnlyUsedAfterLoop(HLoopInformation* loop_info,
Aart Bik8c4a8542016-10-06 11:36:57 -07002548 HInstruction* instruction,
Aart Bik6b69e0a2017-01-11 10:20:43 -08002549 bool collect_loop_uses,
Aart Bik38a3f212017-10-20 17:02:21 -07002550 /*out*/ uint32_t* use_count) {
Aart Bikb29f6842017-07-28 15:58:41 -07002551 // Deal with regular uses.
Aart Bik8c4a8542016-10-06 11:36:57 -07002552 for (const HUseListNode<HInstruction*>& use : instruction->GetUses()) {
2553 HInstruction* user = use.GetUser();
2554 if (iset_->find(user) == iset_->end()) { // not excluded?
2555 HLoopInformation* other_loop_info = user->GetBlock()->GetLoopInformation();
Aart Bik482095d2016-10-10 15:39:10 -07002556 if (other_loop_info != nullptr && other_loop_info->IsIn(*loop_info)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -08002557 // If collect_loop_uses is set, simply keep adding those uses to the set.
2558 // Otherwise, reject uses inside the loop that were not already in the set.
2559 if (collect_loop_uses) {
2560 iset_->insert(user);
2561 continue;
2562 }
Aart Bik8c4a8542016-10-06 11:36:57 -07002563 return false;
2564 }
2565 ++*use_count;
2566 }
2567 }
2568 return true;
2569}
2570
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002571bool HLoopOptimization::TryReplaceWithLastValue(HLoopInformation* loop_info,
2572 HInstruction* instruction,
2573 HBasicBlock* block) {
2574 // Try to replace outside uses with the last value.
Aart Bik807868e2016-11-03 17:51:43 -07002575 if (induction_range_.CanGenerateLastValue(instruction)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -08002576 HInstruction* replacement = induction_range_.GenerateLastValue(instruction, graph_, block);
Aart Bikb29f6842017-07-28 15:58:41 -07002577 // Deal with regular uses.
Aart Bik6b69e0a2017-01-11 10:20:43 -08002578 const HUseList<HInstruction*>& uses = instruction->GetUses();
2579 for (auto it = uses.begin(), end = uses.end(); it != end;) {
2580 HInstruction* user = it->GetUser();
2581 size_t index = it->GetIndex();
2582 ++it; // increment before replacing
2583 if (iset_->find(user) == iset_->end()) { // not excluded?
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002584 if (kIsDebugBuild) {
2585 // We have checked earlier in 'IsOnlyUsedAfterLoop' that the use is after the loop.
2586 HLoopInformation* other_loop_info = user->GetBlock()->GetLoopInformation();
2587 CHECK(other_loop_info == nullptr || !other_loop_info->IsIn(*loop_info));
2588 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08002589 user->ReplaceInput(replacement, index);
2590 induction_range_.Replace(user, instruction, replacement); // update induction
2591 }
2592 }
Aart Bikb29f6842017-07-28 15:58:41 -07002593 // Deal with environment uses.
Aart Bik6b69e0a2017-01-11 10:20:43 -08002594 const HUseList<HEnvironment*>& env_uses = instruction->GetEnvUses();
2595 for (auto it = env_uses.begin(), end = env_uses.end(); it != end;) {
2596 HEnvironment* user = it->GetUser();
2597 size_t index = it->GetIndex();
2598 ++it; // increment before replacing
2599 if (iset_->find(user->GetHolder()) == iset_->end()) { // not excluded?
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002600 // Only update environment uses after the loop.
Aart Bik14a68b42017-06-08 14:06:58 -07002601 HLoopInformation* other_loop_info = user->GetHolder()->GetBlock()->GetLoopInformation();
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002602 if (other_loop_info == nullptr || !other_loop_info->IsIn(*loop_info)) {
2603 user->RemoveAsUserOfInput(index);
2604 user->SetRawEnvAt(index, replacement);
2605 replacement->AddEnvUseAt(user, index);
2606 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08002607 }
2608 }
Aart Bik807868e2016-11-03 17:51:43 -07002609 return true;
Aart Bik8c4a8542016-10-06 11:36:57 -07002610 }
Aart Bik807868e2016-11-03 17:51:43 -07002611 return false;
Aart Bik8c4a8542016-10-06 11:36:57 -07002612}
2613
Aart Bikf8f5a162017-02-06 15:35:29 -08002614bool HLoopOptimization::TryAssignLastValue(HLoopInformation* loop_info,
2615 HInstruction* instruction,
2616 HBasicBlock* block,
2617 bool collect_loop_uses) {
2618 // Assigning the last value is always successful if there are no uses.
2619 // Otherwise, it succeeds in a no early-exit loop by generating the
2620 // proper last value assignment.
Aart Bik38a3f212017-10-20 17:02:21 -07002621 uint32_t use_count = 0;
Aart Bikf8f5a162017-02-06 15:35:29 -08002622 return IsOnlyUsedAfterLoop(loop_info, instruction, collect_loop_uses, &use_count) &&
2623 (use_count == 0 ||
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002624 (!IsEarlyExit(loop_info) && TryReplaceWithLastValue(loop_info, instruction, block)));
Aart Bikf8f5a162017-02-06 15:35:29 -08002625}
2626
Aart Bik6b69e0a2017-01-11 10:20:43 -08002627void HLoopOptimization::RemoveDeadInstructions(const HInstructionList& list) {
2628 for (HBackwardInstructionIterator i(list); !i.Done(); i.Advance()) {
2629 HInstruction* instruction = i.Current();
2630 if (instruction->IsDeadAndRemovable()) {
2631 simplified_ = true;
2632 instruction->GetBlock()->RemoveInstructionOrPhi(instruction);
2633 }
2634 }
2635}
2636
Aart Bik14a68b42017-06-08 14:06:58 -07002637bool HLoopOptimization::CanRemoveCycle() {
2638 for (HInstruction* i : *iset_) {
2639 // We can never remove instructions that have environment
2640 // uses when we compile 'debuggable'.
2641 if (i->HasEnvironmentUses() && graph_->IsDebuggable()) {
2642 return false;
2643 }
2644 // A deoptimization should never have an environment input removed.
2645 for (const HUseListNode<HEnvironment*>& use : i->GetEnvUses()) {
2646 if (use.GetUser()->GetHolder()->IsDeoptimize()) {
2647 return false;
2648 }
2649 }
2650 }
2651 return true;
2652}
2653
Aart Bik281c6812016-08-26 11:31:48 -07002654} // namespace art