blob: 7a525025624182735fff35e828351aa56d46e20e [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/x86/instruction_set_features_x86.h"
23#include "arch/x86_64/instruction_set_features_x86_64.h"
Artem Serovc8150b52019-07-31 18:28:00 +010024#include "code_generator.h"
Vladimir Markoa0431112018-06-25 09:32:54 +010025#include "driver/compiler_options.h"
Aart Bik96202302016-10-04 17:33:56 -070026#include "linear_order.h"
Aart Bik38a3f212017-10-20 17:02:21 -070027#include "mirror/array-inl.h"
28#include "mirror/string.h"
Aart Bik281c6812016-08-26 11:31:48 -070029
VladimĂ­r Marko434d9682022-11-04 14:04:17 +000030namespace art HIDDEN {
Aart Bik281c6812016-08-26 11:31:48 -070031
Aart Bikf8f5a162017-02-06 15:35:29 -080032// Enables vectorization (SIMDization) in the loop optimizer.
33static constexpr bool kEnableVectorization = true;
34
Aart Bik38a3f212017-10-20 17:02:21 -070035//
36// Static helpers.
37//
38
39// Base alignment for arrays/strings guaranteed by the Android runtime.
40static uint32_t BaseAlignment() {
41 return kObjectAlignment;
42}
43
44// Hidden offset for arrays/strings guaranteed by the Android runtime.
45static uint32_t HiddenOffset(DataType::Type type, bool is_string_char_at) {
46 return is_string_char_at
47 ? mirror::String::ValueOffset().Uint32Value()
48 : mirror::Array::DataOffset(DataType::Size(type)).Uint32Value();
49}
50
Aart Bik9abf8942016-10-14 09:49:42 -070051// Remove the instruction from the graph. A bit more elaborate than the usual
52// instruction removal, since there may be a cycle in the use structure.
Aart Bik281c6812016-08-26 11:31:48 -070053static void RemoveFromCycle(HInstruction* instruction) {
Aart Bik281c6812016-08-26 11:31:48 -070054 instruction->RemoveAsUserOfAllInputs();
55 instruction->RemoveEnvironmentUsers();
56 instruction->GetBlock()->RemoveInstructionOrPhi(instruction, /*ensure_safety=*/ false);
Artem Serov21c7e6f2017-07-27 16:04:42 +010057 RemoveEnvironmentUses(instruction);
58 ResetEnvironmentInputRecords(instruction);
Aart Bik281c6812016-08-26 11:31:48 -070059}
60
Aart Bik807868e2016-11-03 17:51:43 -070061// Detect a goto block and sets succ to the single successor.
Aart Bike3dedc52016-11-02 17:50:27 -070062static bool IsGotoBlock(HBasicBlock* block, /*out*/ HBasicBlock** succ) {
63 if (block->GetPredecessors().size() == 1 &&
64 block->GetSuccessors().size() == 1 &&
65 block->IsSingleGoto()) {
66 *succ = block->GetSingleSuccessor();
67 return true;
68 }
69 return false;
70}
71
Aart Bik807868e2016-11-03 17:51:43 -070072// Detect an early exit loop.
73static bool IsEarlyExit(HLoopInformation* loop_info) {
74 HBlocksInLoopReversePostOrderIterator it_loop(*loop_info);
75 for (it_loop.Advance(); !it_loop.Done(); it_loop.Advance()) {
76 for (HBasicBlock* successor : it_loop.Current()->GetSuccessors()) {
77 if (!loop_info->Contains(*successor)) {
78 return true;
79 }
80 }
81 }
82 return false;
83}
84
Aart Bik68ca7022017-09-26 16:44:23 -070085// Forward declaration.
86static bool IsZeroExtensionAndGet(HInstruction* instruction,
87 DataType::Type type,
Aart Bikdf011c32017-09-28 12:53:04 -070088 /*out*/ HInstruction** operand);
Aart Bik68ca7022017-09-26 16:44:23 -070089
Aart Bikdf011c32017-09-28 12:53:04 -070090// Detect a sign extension in instruction from the given type.
Aart Bikdbbac8f2017-09-01 13:06:08 -070091// Returns the promoted operand on success.
Aart Bikf3e61ee2017-04-12 17:09:20 -070092static bool IsSignExtensionAndGet(HInstruction* instruction,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +010093 DataType::Type type,
Aart Bikdf011c32017-09-28 12:53:04 -070094 /*out*/ HInstruction** operand) {
Aart Bikf3e61ee2017-04-12 17:09:20 -070095 // Accept any already wider constant that would be handled properly by sign
96 // extension when represented in the *width* of the given narrower data type
Aart Bik4d1a9d42017-10-19 14:40:55 -070097 // (the fact that Uint8/Uint16 normally zero extend does not matter here).
Aart Bikf3e61ee2017-04-12 17:09:20 -070098 int64_t value = 0;
Aart Bik50e20d52017-05-05 14:07:29 -070099 if (IsInt64AndGet(instruction, /*out*/ &value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700100 switch (type) {
Vladimir Markod5d2f2c2017-09-26 12:37:26 +0100101 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100102 case DataType::Type::kInt8:
Aart Bikdbbac8f2017-09-01 13:06:08 -0700103 if (IsInt<8>(value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700104 *operand = instruction;
105 return true;
106 }
107 return false;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100108 case DataType::Type::kUint16:
109 case DataType::Type::kInt16:
Aart Bikdbbac8f2017-09-01 13:06:08 -0700110 if (IsInt<16>(value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700111 *operand = instruction;
112 return true;
113 }
114 return false;
115 default:
116 return false;
117 }
118 }
Aart Bikdf011c32017-09-28 12:53:04 -0700119 // An implicit widening conversion of any signed expression sign-extends.
120 if (instruction->GetType() == type) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700121 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100122 case DataType::Type::kInt8:
123 case DataType::Type::kInt16:
Aart Bikf3e61ee2017-04-12 17:09:20 -0700124 *operand = instruction;
125 return true;
126 default:
127 return false;
128 }
129 }
Aart Bikdf011c32017-09-28 12:53:04 -0700130 // An explicit widening conversion of a signed expression sign-extends.
Aart Bik68ca7022017-09-26 16:44:23 -0700131 if (instruction->IsTypeConversion()) {
Aart Bikdf011c32017-09-28 12:53:04 -0700132 HInstruction* conv = instruction->InputAt(0);
133 DataType::Type from = conv->GetType();
Aart Bik68ca7022017-09-26 16:44:23 -0700134 switch (instruction->GetType()) {
Aart Bikdf011c32017-09-28 12:53:04 -0700135 case DataType::Type::kInt32:
Aart Bik68ca7022017-09-26 16:44:23 -0700136 case DataType::Type::kInt64:
Aart Bikdf011c32017-09-28 12:53:04 -0700137 if (type == from && (from == DataType::Type::kInt8 ||
138 from == DataType::Type::kInt16 ||
139 from == DataType::Type::kInt32)) {
140 *operand = conv;
141 return true;
142 }
143 return false;
Aart Bik68ca7022017-09-26 16:44:23 -0700144 case DataType::Type::kInt16:
145 return type == DataType::Type::kUint16 &&
146 from == DataType::Type::kUint16 &&
Aart Bikdf011c32017-09-28 12:53:04 -0700147 IsZeroExtensionAndGet(instruction->InputAt(0), type, /*out*/ operand);
Aart Bik68ca7022017-09-26 16:44:23 -0700148 default:
149 return false;
150 }
Aart Bikdbbac8f2017-09-01 13:06:08 -0700151 }
Aart Bikf3e61ee2017-04-12 17:09:20 -0700152 return false;
153}
154
Aart Bikdf011c32017-09-28 12:53:04 -0700155// Detect a zero extension in instruction from the given type.
Aart Bikdbbac8f2017-09-01 13:06:08 -0700156// Returns the promoted operand on success.
Aart Bikf3e61ee2017-04-12 17:09:20 -0700157static bool IsZeroExtensionAndGet(HInstruction* instruction,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100158 DataType::Type type,
Aart Bikdf011c32017-09-28 12:53:04 -0700159 /*out*/ HInstruction** operand) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700160 // Accept any already wider constant that would be handled properly by zero
161 // extension when represented in the *width* of the given narrower data type
Aart Bikdf011c32017-09-28 12:53:04 -0700162 // (the fact that Int8/Int16 normally sign extend does not matter here).
Aart Bikf3e61ee2017-04-12 17:09:20 -0700163 int64_t value = 0;
Aart Bik50e20d52017-05-05 14:07:29 -0700164 if (IsInt64AndGet(instruction, /*out*/ &value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700165 switch (type) {
Vladimir Markod5d2f2c2017-09-26 12:37:26 +0100166 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100167 case DataType::Type::kInt8:
Aart Bikdbbac8f2017-09-01 13:06:08 -0700168 if (IsUint<8>(value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700169 *operand = instruction;
170 return true;
171 }
172 return false;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100173 case DataType::Type::kUint16:
174 case DataType::Type::kInt16:
Aart Bikdbbac8f2017-09-01 13:06:08 -0700175 if (IsUint<16>(value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700176 *operand = instruction;
177 return true;
178 }
179 return false;
180 default:
181 return false;
182 }
183 }
Aart Bikdf011c32017-09-28 12:53:04 -0700184 // An implicit widening conversion of any unsigned expression zero-extends.
185 if (instruction->GetType() == type) {
Vladimir Markod5d2f2c2017-09-26 12:37:26 +0100186 switch (type) {
187 case DataType::Type::kUint8:
188 case DataType::Type::kUint16:
189 *operand = instruction;
190 return true;
191 default:
192 return false;
Aart Bikf3e61ee2017-04-12 17:09:20 -0700193 }
194 }
Aart Bikdf011c32017-09-28 12:53:04 -0700195 // An explicit widening conversion of an unsigned expression zero-extends.
Aart Bik68ca7022017-09-26 16:44:23 -0700196 if (instruction->IsTypeConversion()) {
Aart Bikdf011c32017-09-28 12:53:04 -0700197 HInstruction* conv = instruction->InputAt(0);
198 DataType::Type from = conv->GetType();
Aart Bik68ca7022017-09-26 16:44:23 -0700199 switch (instruction->GetType()) {
Aart Bikdf011c32017-09-28 12:53:04 -0700200 case DataType::Type::kInt32:
Aart Bik68ca7022017-09-26 16:44:23 -0700201 case DataType::Type::kInt64:
Aart Bikdf011c32017-09-28 12:53:04 -0700202 if (type == from && from == DataType::Type::kUint16) {
203 *operand = conv;
204 return true;
205 }
206 return false;
Aart Bik68ca7022017-09-26 16:44:23 -0700207 case DataType::Type::kUint16:
208 return type == DataType::Type::kInt16 &&
209 from == DataType::Type::kInt16 &&
Aart Bikdf011c32017-09-28 12:53:04 -0700210 IsSignExtensionAndGet(instruction->InputAt(0), type, /*out*/ operand);
Aart Bik68ca7022017-09-26 16:44:23 -0700211 default:
212 return false;
213 }
Aart Bikdbbac8f2017-09-01 13:06:08 -0700214 }
Aart Bikf3e61ee2017-04-12 17:09:20 -0700215 return false;
216}
217
Aart Bik304c8a52017-05-23 11:01:13 -0700218// Detect situations with same-extension narrower operands.
219// Returns true on success and sets is_unsigned accordingly.
220static bool IsNarrowerOperands(HInstruction* a,
221 HInstruction* b,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100222 DataType::Type type,
Aart Bik304c8a52017-05-23 11:01:13 -0700223 /*out*/ HInstruction** r,
224 /*out*/ HInstruction** s,
225 /*out*/ bool* is_unsigned) {
Nicolas Geoffraya3e23262018-03-28 11:15:12 +0000226 DCHECK(a != nullptr && b != nullptr);
Aart Bik4d1a9d42017-10-19 14:40:55 -0700227 // Look for a matching sign extension.
228 DataType::Type stype = HVecOperation::ToSignedType(type);
229 if (IsSignExtensionAndGet(a, stype, r) && IsSignExtensionAndGet(b, stype, s)) {
Aart Bik304c8a52017-05-23 11:01:13 -0700230 *is_unsigned = false;
231 return true;
Aart Bik4d1a9d42017-10-19 14:40:55 -0700232 }
233 // Look for a matching zero extension.
234 DataType::Type utype = HVecOperation::ToUnsignedType(type);
235 if (IsZeroExtensionAndGet(a, utype, r) && IsZeroExtensionAndGet(b, utype, s)) {
Aart Bik304c8a52017-05-23 11:01:13 -0700236 *is_unsigned = true;
237 return true;
238 }
239 return false;
240}
241
242// As above, single operand.
243static bool IsNarrowerOperand(HInstruction* a,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100244 DataType::Type type,
Aart Bik304c8a52017-05-23 11:01:13 -0700245 /*out*/ HInstruction** r,
246 /*out*/ bool* is_unsigned) {
Nicolas Geoffraya3e23262018-03-28 11:15:12 +0000247 DCHECK(a != nullptr);
Aart Bik4d1a9d42017-10-19 14:40:55 -0700248 // Look for a matching sign extension.
249 DataType::Type stype = HVecOperation::ToSignedType(type);
250 if (IsSignExtensionAndGet(a, stype, r)) {
Aart Bik304c8a52017-05-23 11:01:13 -0700251 *is_unsigned = false;
252 return true;
Aart Bik4d1a9d42017-10-19 14:40:55 -0700253 }
254 // Look for a matching zero extension.
255 DataType::Type utype = HVecOperation::ToUnsignedType(type);
256 if (IsZeroExtensionAndGet(a, utype, r)) {
Aart Bik304c8a52017-05-23 11:01:13 -0700257 *is_unsigned = true;
258 return true;
259 }
260 return false;
261}
262
Aart Bikdbbac8f2017-09-01 13:06:08 -0700263// Compute relative vector length based on type difference.
Aart Bik38a3f212017-10-20 17:02:21 -0700264static uint32_t GetOtherVL(DataType::Type other_type, DataType::Type vector_type, uint32_t vl) {
Vladimir Markod5d2f2c2017-09-26 12:37:26 +0100265 DCHECK(DataType::IsIntegralType(other_type));
266 DCHECK(DataType::IsIntegralType(vector_type));
267 DCHECK_GE(DataType::SizeShift(other_type), DataType::SizeShift(vector_type));
268 return vl >> (DataType::SizeShift(other_type) - DataType::SizeShift(vector_type));
Aart Bikdbbac8f2017-09-01 13:06:08 -0700269}
270
Nicolas Geoffraya3e23262018-03-28 11:15:12 +0000271// Detect up to two added operands a and b and an acccumulated constant c.
272static bool IsAddConst(HInstruction* instruction,
273 /*out*/ HInstruction** a,
274 /*out*/ HInstruction** b,
275 /*out*/ int64_t* c,
276 int32_t depth = 8) { // don't search too deep
Aart Bik5f805002017-05-16 16:42:41 -0700277 int64_t value = 0;
Nicolas Geoffraya3e23262018-03-28 11:15:12 +0000278 // Enter add/sub while still within reasonable depth.
279 if (depth > 0) {
280 if (instruction->IsAdd()) {
281 return IsAddConst(instruction->InputAt(0), a, b, c, depth - 1) &&
282 IsAddConst(instruction->InputAt(1), a, b, c, depth - 1);
283 } else if (instruction->IsSub() &&
284 IsInt64AndGet(instruction->InputAt(1), &value)) {
285 *c -= value;
286 return IsAddConst(instruction->InputAt(0), a, b, c, depth - 1);
287 }
288 }
289 // Otherwise, deal with leaf nodes.
Aart Bik5f805002017-05-16 16:42:41 -0700290 if (IsInt64AndGet(instruction, &value)) {
291 *c += value;
292 return true;
Aart Bik5f805002017-05-16 16:42:41 -0700293 } else if (*a == nullptr) {
294 *a = instruction;
295 return true;
296 } else if (*b == nullptr) {
297 *b = instruction;
298 return true;
299 }
Nicolas Geoffraya3e23262018-03-28 11:15:12 +0000300 return false; // too many operands
Aart Bik5f805002017-05-16 16:42:41 -0700301}
302
Nicolas Geoffraya3e23262018-03-28 11:15:12 +0000303// Detect a + b + c with optional constant c.
304static bool IsAddConst2(HGraph* graph,
305 HInstruction* instruction,
306 /*out*/ HInstruction** a,
307 /*out*/ HInstruction** b,
308 /*out*/ int64_t* c) {
Artem Serovb47b9782019-12-04 21:02:09 +0000309 // We want an actual add/sub and not the trivial case where {b: 0, c: 0}.
310 if (IsAddOrSub(instruction) && IsAddConst(instruction, a, b, c) && *a != nullptr) {
Nicolas Geoffraya3e23262018-03-28 11:15:12 +0000311 if (*b == nullptr) {
312 // Constant is usually already present, unless accumulated.
313 *b = graph->GetConstant(instruction->GetType(), (*c));
314 *c = 0;
Aart Bik5f805002017-05-16 16:42:41 -0700315 }
Aart Bik5f805002017-05-16 16:42:41 -0700316 return true;
317 }
318 return false;
319}
320
Nicolas Geoffraya3e23262018-03-28 11:15:12 +0000321// Detect a direct a - b or a hidden a - (-c).
322static bool IsSubConst2(HGraph* graph,
323 HInstruction* instruction,
324 /*out*/ HInstruction** a,
325 /*out*/ HInstruction** b) {
326 int64_t c = 0;
327 if (instruction->IsSub()) {
328 *a = instruction->InputAt(0);
329 *b = instruction->InputAt(1);
330 return true;
331 } else if (IsAddConst(instruction, a, b, &c) && *a != nullptr && *b == nullptr) {
332 // Constant for the hidden subtraction.
333 *b = graph->GetConstant(instruction->GetType(), -c);
334 return true;
Aart Bikdf011c32017-09-28 12:53:04 -0700335 }
336 return false;
337}
338
Aart Bikb29f6842017-07-28 15:58:41 -0700339// Detect reductions of the following forms,
Aart Bikb29f6842017-07-28 15:58:41 -0700340// x = x_phi + ..
341// x = x_phi - ..
Aart Bikb29f6842017-07-28 15:58:41 -0700342static bool HasReductionFormat(HInstruction* reduction, HInstruction* phi) {
Aart Bik3f08e9b2018-05-01 13:42:03 -0700343 if (reduction->IsAdd()) {
Aart Bikdbbac8f2017-09-01 13:06:08 -0700344 return (reduction->InputAt(0) == phi && reduction->InputAt(1) != phi) ||
345 (reduction->InputAt(0) != phi && reduction->InputAt(1) == phi);
Aart Bikb29f6842017-07-28 15:58:41 -0700346 } else if (reduction->IsSub()) {
Aart Bikdbbac8f2017-09-01 13:06:08 -0700347 return (reduction->InputAt(0) == phi && reduction->InputAt(1) != phi);
Aart Bikb29f6842017-07-28 15:58:41 -0700348 }
349 return false;
350}
351
Aart Bikdbbac8f2017-09-01 13:06:08 -0700352// Translates vector operation to reduction kind.
353static HVecReduce::ReductionKind GetReductionKind(HVecOperation* reduction) {
Shalini Salomi Bodapati81d15be2019-05-30 11:00:42 +0530354 if (reduction->IsVecAdd() ||
Artem Serovaaac0e32018-08-07 00:52:22 +0100355 reduction->IsVecSub() ||
356 reduction->IsVecSADAccumulate() ||
357 reduction->IsVecDotProd()) {
Aart Bik0148de42017-09-05 09:25:01 -0700358 return HVecReduce::kSum;
Aart Bik0148de42017-09-05 09:25:01 -0700359 }
Aart Bik38a3f212017-10-20 17:02:21 -0700360 LOG(FATAL) << "Unsupported SIMD reduction " << reduction->GetId();
Aart Bik0148de42017-09-05 09:25:01 -0700361 UNREACHABLE();
362}
363
Aart Bikf8f5a162017-02-06 15:35:29 -0800364// Test vector restrictions.
365static bool HasVectorRestrictions(uint64_t restrictions, uint64_t tested) {
366 return (restrictions & tested) != 0;
367}
368
Aart Bikf3e61ee2017-04-12 17:09:20 -0700369// Insert an instruction.
Aart Bikf8f5a162017-02-06 15:35:29 -0800370static HInstruction* Insert(HBasicBlock* block, HInstruction* instruction) {
371 DCHECK(block != nullptr);
372 DCHECK(instruction != nullptr);
373 block->InsertInstructionBefore(instruction, block->GetLastInstruction());
374 return instruction;
375}
376
Artem Serov21c7e6f2017-07-27 16:04:42 +0100377// Check that instructions from the induction sets are fully removed: have no uses
378// and no other instructions use them.
Vladimir Markoca6fff82017-10-03 14:49:14 +0100379static bool CheckInductionSetFullyRemoved(ScopedArenaSet<HInstruction*>* iset) {
Artem Serov21c7e6f2017-07-27 16:04:42 +0100380 for (HInstruction* instr : *iset) {
381 if (instr->GetBlock() != nullptr ||
382 !instr->GetUses().empty() ||
383 !instr->GetEnvUses().empty() ||
384 HasEnvironmentUsedByOthers(instr)) {
385 return false;
386 }
387 }
Artem Serov21c7e6f2017-07-27 16:04:42 +0100388 return true;
389}
390
Artem Serov72411e62017-10-19 16:18:07 +0100391// Tries to statically evaluate condition of the specified "HIf" for other condition checks.
392static void TryToEvaluateIfCondition(HIf* instruction, HGraph* graph) {
393 HInstruction* cond = instruction->InputAt(0);
394
395 // If a condition 'cond' is evaluated in an HIf instruction then in the successors of the
396 // IF_BLOCK we statically know the value of the condition 'cond' (TRUE in TRUE_SUCC, FALSE in
397 // FALSE_SUCC). Using that we can replace another evaluation (use) EVAL of the same 'cond'
398 // with TRUE value (FALSE value) if every path from the ENTRY_BLOCK to EVAL_BLOCK contains the
399 // edge HIF_BLOCK->TRUE_SUCC (HIF_BLOCK->FALSE_SUCC).
400 // if (cond) { if(cond) {
401 // if (cond) {} if (1) {}
402 // } else { =======> } else {
403 // if (cond) {} if (0) {}
404 // } }
405 if (!cond->IsConstant()) {
406 HBasicBlock* true_succ = instruction->IfTrueSuccessor();
407 HBasicBlock* false_succ = instruction->IfFalseSuccessor();
408
409 DCHECK_EQ(true_succ->GetPredecessors().size(), 1u);
410 DCHECK_EQ(false_succ->GetPredecessors().size(), 1u);
411
412 const HUseList<HInstruction*>& uses = cond->GetUses();
413 for (auto it = uses.begin(), end = uses.end(); it != end; /* ++it below */) {
414 HInstruction* user = it->GetUser();
415 size_t index = it->GetIndex();
416 HBasicBlock* user_block = user->GetBlock();
417 // Increment `it` now because `*it` may disappear thanks to user->ReplaceInput().
418 ++it;
419 if (true_succ->Dominates(user_block)) {
420 user->ReplaceInput(graph->GetIntConstant(1), index);
421 } else if (false_succ->Dominates(user_block)) {
422 user->ReplaceInput(graph->GetIntConstant(0), index);
423 }
424 }
425 }
426}
427
Artem Serov18ba1da2018-05-16 19:06:32 +0100428// Peel the first 'count' iterations of the loop.
Nicolas Geoffray256c94b2019-04-29 10:55:09 +0100429static void PeelByCount(HLoopInformation* loop_info,
430 int count,
431 InductionVarRange* induction_range) {
Artem Serov18ba1da2018-05-16 19:06:32 +0100432 for (int i = 0; i < count; i++) {
433 // Perform peeling.
Artem Serov0f5b2bf2019-10-23 14:07:41 +0100434 LoopClonerSimpleHelper helper(loop_info, induction_range);
Artem Serov18ba1da2018-05-16 19:06:32 +0100435 helper.DoPeeling();
436 }
437}
438
Artem Serovaaac0e32018-08-07 00:52:22 +0100439// Returns the narrower type out of instructions a and b types.
440static DataType::Type GetNarrowerType(HInstruction* a, HInstruction* b) {
441 DataType::Type type = a->GetType();
442 if (DataType::Size(b->GetType()) < DataType::Size(type)) {
443 type = b->GetType();
444 }
445 if (a->IsTypeConversion() &&
446 DataType::Size(a->InputAt(0)->GetType()) < DataType::Size(type)) {
447 type = a->InputAt(0)->GetType();
448 }
449 if (b->IsTypeConversion() &&
450 DataType::Size(b->InputAt(0)->GetType()) < DataType::Size(type)) {
451 type = b->InputAt(0)->GetType();
452 }
453 return type;
454}
455
Aart Bik281c6812016-08-26 11:31:48 -0700456//
Aart Bikb29f6842017-07-28 15:58:41 -0700457// Public methods.
Aart Bik281c6812016-08-26 11:31:48 -0700458//
459
460HLoopOptimization::HLoopOptimization(HGraph* graph,
Artem Serovc8150b52019-07-31 18:28:00 +0100461 const CodeGenerator& codegen,
Aart Bikb92cc332017-09-06 15:53:17 -0700462 HInductionVarAnalysis* induction_analysis,
Aart Bik2ca10eb2017-11-15 15:17:53 -0800463 OptimizingCompilerStats* stats,
464 const char* name)
465 : HOptimization(graph, name, stats),
Artem Serovc8150b52019-07-31 18:28:00 +0100466 compiler_options_(&codegen.GetCompilerOptions()),
467 simd_register_size_(codegen.GetSIMDRegisterWidth()),
Aart Bik281c6812016-08-26 11:31:48 -0700468 induction_range_(induction_analysis),
Aart Bik96202302016-10-04 17:33:56 -0700469 loop_allocator_(nullptr),
Vladimir Markoca6fff82017-10-03 14:49:14 +0100470 global_allocator_(graph_->GetAllocator()),
Aart Bik281c6812016-08-26 11:31:48 -0700471 top_loop_(nullptr),
Aart Bik8c4a8542016-10-06 11:36:57 -0700472 last_loop_(nullptr),
Aart Bik482095d2016-10-10 15:39:10 -0700473 iset_(nullptr),
Aart Bikb29f6842017-07-28 15:58:41 -0700474 reductions_(nullptr),
Aart Bikf8f5a162017-02-06 15:35:29 -0800475 simplified_(false),
Artem Serov8ba4de12019-12-04 21:10:23 +0000476 predicated_vectorization_mode_(codegen.SupportsPredicatedSIMD()),
Aart Bikf8f5a162017-02-06 15:35:29 -0800477 vector_length_(0),
478 vector_refs_(nullptr),
Aart Bik38a3f212017-10-20 17:02:21 -0700479 vector_static_peeling_factor_(0),
480 vector_dynamic_peeling_candidate_(nullptr),
Aart Bik14a68b42017-06-08 14:06:58 -0700481 vector_runtime_test_a_(nullptr),
482 vector_runtime_test_b_(nullptr),
Aart Bik0148de42017-09-05 09:25:01 -0700483 vector_map_(nullptr),
Vladimir Markoca6fff82017-10-03 14:49:14 +0100484 vector_permanent_map_(nullptr),
485 vector_mode_(kSequential),
486 vector_preheader_(nullptr),
487 vector_header_(nullptr),
488 vector_body_(nullptr),
Artem Serov121f2032017-10-23 19:19:06 +0100489 vector_index_(nullptr),
Artem Serov8ba4de12019-12-04 21:10:23 +0000490 arch_loop_helper_(ArchNoOptsLoopHelper::Create(codegen, global_allocator_)) {
Aart Bik281c6812016-08-26 11:31:48 -0700491}
492
Aart Bik24773202018-04-26 10:28:51 -0700493bool HLoopOptimization::Run() {
Santiago Aboy Solanes0eca0982022-04-08 18:00:48 +0100494 // Skip if there is no loop or the graph has irreducible loops.
Aart Bik281c6812016-08-26 11:31:48 -0700495 // TODO: make this less of a sledgehammer.
Santiago Aboy Solanes0eca0982022-04-08 18:00:48 +0100496 if (!graph_->HasLoops() || graph_->HasIrreducibleLoops()) {
Aart Bik24773202018-04-26 10:28:51 -0700497 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700498 }
499
Vladimir Markoca6fff82017-10-03 14:49:14 +0100500 // Phase-local allocator.
501 ScopedArenaAllocator allocator(graph_->GetArenaStack());
Aart Bik96202302016-10-04 17:33:56 -0700502 loop_allocator_ = &allocator;
Nicolas Geoffrayebe16742016-10-05 09:55:42 +0100503
Aart Bik96202302016-10-04 17:33:56 -0700504 // Perform loop optimizations.
Santiago Aboy Solanes0eca0982022-04-08 18:00:48 +0100505 const bool did_loop_opt = LocalRun();
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800506 if (top_loop_ == nullptr) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800507 graph_->SetHasLoops(false); // no more loops
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800508 }
509
Santiago Aboy Solanes74da6682022-12-16 19:28:47 +0000510 // Detach allocator.
Aart Bik96202302016-10-04 17:33:56 -0700511 loop_allocator_ = nullptr;
Aart Bik24773202018-04-26 10:28:51 -0700512
Santiago Aboy Solanes0eca0982022-04-08 18:00:48 +0100513 return did_loop_opt;
Aart Bik96202302016-10-04 17:33:56 -0700514}
515
Aart Bikb29f6842017-07-28 15:58:41 -0700516//
517// Loop setup and traversal.
518//
519
Aart Bik24773202018-04-26 10:28:51 -0700520bool HLoopOptimization::LocalRun() {
Aart Bik96202302016-10-04 17:33:56 -0700521 // Build the linear order using the phase-local allocator. This step enables building
522 // a loop hierarchy that properly reflects the outer-inner and previous-next relation.
Vladimir Markoca6fff82017-10-03 14:49:14 +0100523 ScopedArenaVector<HBasicBlock*> linear_order(loop_allocator_->Adapter(kArenaAllocLinearOrder));
524 LinearizeGraph(graph_, &linear_order);
Aart Bik96202302016-10-04 17:33:56 -0700525
Aart Bik281c6812016-08-26 11:31:48 -0700526 // Build the loop hierarchy.
Aart Bik96202302016-10-04 17:33:56 -0700527 for (HBasicBlock* block : linear_order) {
Aart Bik281c6812016-08-26 11:31:48 -0700528 if (block->IsLoopHeader()) {
529 AddLoop(block->GetLoopInformation());
530 }
531 }
Santiago Aboy Solanes74da6682022-12-16 19:28:47 +0000532 DCHECK(top_loop_ != nullptr);
Santiago Aboy Solanes0eca0982022-04-08 18:00:48 +0100533
Aart Bik8c4a8542016-10-06 11:36:57 -0700534 // Traverse the loop hierarchy inner-to-outer and optimize. Traversal can use
Aart Bikf8f5a162017-02-06 15:35:29 -0800535 // temporary data structures using the phase-local allocator. All new HIR
536 // should use the global allocator.
Santiago Aboy Solanes0eca0982022-04-08 18:00:48 +0100537 ScopedArenaSet<HInstruction*> iset(loop_allocator_->Adapter(kArenaAllocLoopOptimization));
538 ScopedArenaSafeMap<HInstruction*, HInstruction*> reds(
539 std::less<HInstruction*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
540 ScopedArenaSet<ArrayReference> refs(loop_allocator_->Adapter(kArenaAllocLoopOptimization));
541 ScopedArenaSafeMap<HInstruction*, HInstruction*> map(
542 std::less<HInstruction*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
543 ScopedArenaSafeMap<HInstruction*, HInstruction*> perm(
544 std::less<HInstruction*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
545 // Attach.
546 iset_ = &iset;
547 reductions_ = &reds;
548 vector_refs_ = &refs;
549 vector_map_ = &map;
550 vector_permanent_map_ = &perm;
551 // Traverse.
552 const bool did_loop_opt = TraverseLoopsInnerToOuter(top_loop_);
553 // Detach.
554 iset_ = nullptr;
555 reductions_ = nullptr;
556 vector_refs_ = nullptr;
557 vector_map_ = nullptr;
558 vector_permanent_map_ = nullptr;
559 return did_loop_opt;
Aart Bik281c6812016-08-26 11:31:48 -0700560}
561
562void HLoopOptimization::AddLoop(HLoopInformation* loop_info) {
563 DCHECK(loop_info != nullptr);
Aart Bikf8f5a162017-02-06 15:35:29 -0800564 LoopNode* node = new (loop_allocator_) LoopNode(loop_info);
Aart Bik281c6812016-08-26 11:31:48 -0700565 if (last_loop_ == nullptr) {
566 // First loop.
567 DCHECK(top_loop_ == nullptr);
568 last_loop_ = top_loop_ = node;
569 } else if (loop_info->IsIn(*last_loop_->loop_info)) {
570 // Inner loop.
571 node->outer = last_loop_;
572 DCHECK(last_loop_->inner == nullptr);
573 last_loop_ = last_loop_->inner = node;
574 } else {
575 // Subsequent loop.
576 while (last_loop_->outer != nullptr && !loop_info->IsIn(*last_loop_->outer->loop_info)) {
577 last_loop_ = last_loop_->outer;
578 }
579 node->outer = last_loop_->outer;
580 node->previous = last_loop_;
581 DCHECK(last_loop_->next == nullptr);
582 last_loop_ = last_loop_->next = node;
583 }
584}
585
586void HLoopOptimization::RemoveLoop(LoopNode* node) {
587 DCHECK(node != nullptr);
Aart Bik8c4a8542016-10-06 11:36:57 -0700588 DCHECK(node->inner == nullptr);
589 if (node->previous != nullptr) {
590 // Within sequence.
591 node->previous->next = node->next;
592 if (node->next != nullptr) {
593 node->next->previous = node->previous;
594 }
595 } else {
596 // First of sequence.
597 if (node->outer != nullptr) {
598 node->outer->inner = node->next;
599 } else {
600 top_loop_ = node->next;
601 }
602 if (node->next != nullptr) {
603 node->next->outer = node->outer;
604 node->next->previous = nullptr;
605 }
606 }
Aart Bik281c6812016-08-26 11:31:48 -0700607}
608
Aart Bikb29f6842017-07-28 15:58:41 -0700609bool HLoopOptimization::TraverseLoopsInnerToOuter(LoopNode* node) {
610 bool changed = false;
Aart Bik281c6812016-08-26 11:31:48 -0700611 for ( ; node != nullptr; node = node->next) {
Aart Bikb29f6842017-07-28 15:58:41 -0700612 // Visit inner loops first. Recompute induction information for this
613 // loop if the induction of any inner loop has changed.
614 if (TraverseLoopsInnerToOuter(node->inner)) {
Aart Bik482095d2016-10-10 15:39:10 -0700615 induction_range_.ReVisit(node->loop_info);
Aart Bika8360cd2018-05-02 16:07:51 -0700616 changed = true;
Aart Bik482095d2016-10-10 15:39:10 -0700617 }
Santiago Aboy Solanes0eca0982022-04-08 18:00:48 +0100618
619 CalculateAndSetTryCatchKind(node);
620 if (node->try_catch_kind == LoopNode::TryCatchKind::kHasTryCatch) {
621 // The current optimizations assume that the loops do not contain try/catches.
622 // TODO(solanes, 227283906): Assess if we can modify them to work with try/catches.
623 continue;
624 }
625
626 DCHECK(node->try_catch_kind == LoopNode::TryCatchKind::kNoTryCatch)
627 << "kind: " << static_cast<int>(node->try_catch_kind)
628 << ". LoopOptimization requires the loops to not have try catches.";
629
Aart Bikf8f5a162017-02-06 15:35:29 -0800630 // Repeat simplifications in the loop-body until no more changes occur.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800631 // Note that since each simplification consists of eliminating code (without
632 // introducing new code), this process is always finite.
Aart Bikdf7822e2016-12-06 10:05:30 -0800633 do {
634 simplified_ = false;
Aart Bikdf7822e2016-12-06 10:05:30 -0800635 SimplifyInduction(node);
Aart Bik6b69e0a2017-01-11 10:20:43 -0800636 SimplifyBlocks(node);
Aart Bikb29f6842017-07-28 15:58:41 -0700637 changed = simplified_ || changed;
Aart Bikdf7822e2016-12-06 10:05:30 -0800638 } while (simplified_);
Aart Bikf8f5a162017-02-06 15:35:29 -0800639 // Optimize inner loop.
Aart Bik9abf8942016-10-14 09:49:42 -0700640 if (node->inner == nullptr) {
Aart Bikb29f6842017-07-28 15:58:41 -0700641 changed = OptimizeInnerLoop(node) || changed;
Aart Bik9abf8942016-10-14 09:49:42 -0700642 }
Aart Bik281c6812016-08-26 11:31:48 -0700643 }
Aart Bikb29f6842017-07-28 15:58:41 -0700644 return changed;
Aart Bik281c6812016-08-26 11:31:48 -0700645}
646
Santiago Aboy Solanes0eca0982022-04-08 18:00:48 +0100647void HLoopOptimization::CalculateAndSetTryCatchKind(LoopNode* node) {
648 DCHECK(node != nullptr);
649 DCHECK(node->try_catch_kind == LoopNode::TryCatchKind::kUnknown)
650 << "kind: " << static_cast<int>(node->try_catch_kind)
651 << ". SetTryCatchKind should be called only once per LoopNode.";
652
653 // If a inner loop has a try catch, then the outer loop has one too (as it contains `inner`).
654 // Knowing this, we could skip iterating through all of the outer loop's parents with a simple
655 // check.
656 for (LoopNode* inner = node->inner; inner != nullptr; inner = inner->next) {
657 DCHECK(inner->try_catch_kind != LoopNode::TryCatchKind::kUnknown)
658 << "kind: " << static_cast<int>(inner->try_catch_kind)
659 << ". Should have updated the inner loop before the outer loop.";
660
661 if (inner->try_catch_kind == LoopNode::TryCatchKind::kHasTryCatch) {
662 node->try_catch_kind = LoopNode::TryCatchKind::kHasTryCatch;
663 return;
664 }
665 }
666
667 for (HBlocksInLoopIterator it_loop(*node->loop_info); !it_loop.Done(); it_loop.Advance()) {
668 HBasicBlock* block = it_loop.Current();
669 if (block->GetTryCatchInformation() != nullptr) {
670 node->try_catch_kind = LoopNode::TryCatchKind::kHasTryCatch;
671 return;
672 }
673 }
674
675 node->try_catch_kind = LoopNode::TryCatchKind::kNoTryCatch;
676}
677
Aart Bikf8f5a162017-02-06 15:35:29 -0800678//
Stelios Ioannouc54cc7c2021-07-09 17:06:03 +0100679// This optimization applies to loops with plain simple operations
680// (I.e. no calls to java code or runtime) with a known small trip_count * instr_count
681// value.
682//
683bool HLoopOptimization::TryToRemoveSuspendCheckFromLoopHeader(LoopAnalysisInfo* analysis_info,
684 bool generate_code) {
685 if (!graph_->SuspendChecksAreAllowedToNoOp()) {
686 return false;
687 }
688
689 int64_t trip_count = analysis_info->GetTripCount();
690
691 if (trip_count == LoopAnalysisInfo::kUnknownTripCount) {
692 return false;
693 }
694
695 int64_t instruction_count = analysis_info->GetNumberOfInstructions();
696 int64_t total_instruction_count = trip_count * instruction_count;
697
698 // The inclusion of the HasInstructionsPreventingScalarOpts() prevents this
699 // optimization from being applied to loops that have calls.
700 bool can_optimize =
701 total_instruction_count <= HLoopOptimization::kMaxTotalInstRemoveSuspendCheck &&
702 !analysis_info->HasInstructionsPreventingScalarOpts();
703
704 if (!can_optimize) {
705 return false;
706 }
707
708 // If we should do the optimization, disable codegen for the SuspendCheck.
709 if (generate_code) {
710 HLoopInformation* loop_info = analysis_info->GetLoopInfo();
711 HBasicBlock* header = loop_info->GetHeader();
712 HSuspendCheck* instruction = header->GetLoopInformation()->GetSuspendCheck();
713 // As other optimizations depend on SuspendCheck
714 // (e.g: CHAGuardVisitor::HoistGuard), disable its codegen instead of
715 // removing the SuspendCheck instruction.
716 instruction->SetIsNoOp(true);
717 }
718
719 return true;
720}
721
722//
Aart Bikf8f5a162017-02-06 15:35:29 -0800723// Optimization.
724//
725
Aart Bik281c6812016-08-26 11:31:48 -0700726void HLoopOptimization::SimplifyInduction(LoopNode* node) {
727 HBasicBlock* header = node->loop_info->GetHeader();
728 HBasicBlock* preheader = node->loop_info->GetPreHeader();
Aart Bik8c4a8542016-10-06 11:36:57 -0700729 // Scan the phis in the header to find opportunities to simplify an induction
730 // cycle that is only used outside the loop. Replace these uses, if any, with
731 // the last value and remove the induction cycle.
732 // Examples: for (int i = 0; x != null; i++) { .... no i .... }
733 // for (int i = 0; i < 10; i++, k++) { .... no k .... } return k;
Aart Bik281c6812016-08-26 11:31:48 -0700734 for (HInstructionIterator it(header->GetPhis()); !it.Done(); it.Advance()) {
735 HPhi* phi = it.Current()->AsPhi();
Aart Bikf8f5a162017-02-06 15:35:29 -0800736 if (TrySetPhiInduction(phi, /*restrict_uses*/ true) &&
737 TryAssignLastValue(node->loop_info, phi, preheader, /*collect_loop_uses*/ false)) {
Aart Bik671e48a2017-08-09 13:16:56 -0700738 // Note that it's ok to have replaced uses after the loop with the last value, without
739 // being able to remove the cycle. Environment uses (which are the reason we may not be
740 // able to remove the cycle) within the loop will still hold the right value. We must
741 // have tried first, however, to replace outside uses.
742 if (CanRemoveCycle()) {
743 simplified_ = true;
744 for (HInstruction* i : *iset_) {
745 RemoveFromCycle(i);
746 }
747 DCHECK(CheckInductionSetFullyRemoved(iset_));
Aart Bik281c6812016-08-26 11:31:48 -0700748 }
Aart Bik482095d2016-10-10 15:39:10 -0700749 }
750 }
751}
752
753void HLoopOptimization::SimplifyBlocks(LoopNode* node) {
Aart Bikdf7822e2016-12-06 10:05:30 -0800754 // Iterate over all basic blocks in the loop-body.
755 for (HBlocksInLoopIterator it(*node->loop_info); !it.Done(); it.Advance()) {
756 HBasicBlock* block = it.Current();
757 // Remove dead instructions from the loop-body.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800758 RemoveDeadInstructions(block->GetPhis());
759 RemoveDeadInstructions(block->GetInstructions());
Aart Bikdf7822e2016-12-06 10:05:30 -0800760 // Remove trivial control flow blocks from the loop-body.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800761 if (block->GetPredecessors().size() == 1 &&
762 block->GetSuccessors().size() == 1 &&
763 block->GetSingleSuccessor()->GetPredecessors().size() == 1) {
Aart Bikdf7822e2016-12-06 10:05:30 -0800764 simplified_ = true;
Aart Bik6b69e0a2017-01-11 10:20:43 -0800765 block->MergeWith(block->GetSingleSuccessor());
Aart Bikdf7822e2016-12-06 10:05:30 -0800766 } else if (block->GetSuccessors().size() == 2) {
767 // Trivial if block can be bypassed to either branch.
768 HBasicBlock* succ0 = block->GetSuccessors()[0];
769 HBasicBlock* succ1 = block->GetSuccessors()[1];
770 HBasicBlock* meet0 = nullptr;
771 HBasicBlock* meet1 = nullptr;
772 if (succ0 != succ1 &&
773 IsGotoBlock(succ0, &meet0) &&
774 IsGotoBlock(succ1, &meet1) &&
775 meet0 == meet1 && // meets again
776 meet0 != block && // no self-loop
777 meet0->GetPhis().IsEmpty()) { // not used for merging
778 simplified_ = true;
779 succ0->DisconnectAndDelete();
780 if (block->Dominates(meet0)) {
781 block->RemoveDominatedBlock(meet0);
782 succ1->AddDominatedBlock(meet0);
783 meet0->SetDominator(succ1);
Aart Bike3dedc52016-11-02 17:50:27 -0700784 }
Aart Bik482095d2016-10-10 15:39:10 -0700785 }
Aart Bik281c6812016-08-26 11:31:48 -0700786 }
Aart Bikdf7822e2016-12-06 10:05:30 -0800787 }
Aart Bik281c6812016-08-26 11:31:48 -0700788}
789
Artem Serov121f2032017-10-23 19:19:06 +0100790bool HLoopOptimization::TryOptimizeInnerLoopFinite(LoopNode* node) {
Aart Bik281c6812016-08-26 11:31:48 -0700791 HBasicBlock* header = node->loop_info->GetHeader();
792 HBasicBlock* preheader = node->loop_info->GetPreHeader();
Aart Bik9abf8942016-10-14 09:49:42 -0700793 // Ensure loop header logic is finite.
Aart Bikf8f5a162017-02-06 15:35:29 -0800794 int64_t trip_count = 0;
795 if (!induction_range_.IsFinite(node->loop_info, &trip_count)) {
Aart Bikb29f6842017-07-28 15:58:41 -0700796 return false;
Aart Bik9abf8942016-10-14 09:49:42 -0700797 }
Aart Bik281c6812016-08-26 11:31:48 -0700798 // Ensure there is only a single loop-body (besides the header).
799 HBasicBlock* body = nullptr;
800 for (HBlocksInLoopIterator it(*node->loop_info); !it.Done(); it.Advance()) {
801 if (it.Current() != header) {
802 if (body != nullptr) {
Aart Bikb29f6842017-07-28 15:58:41 -0700803 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700804 }
805 body = it.Current();
806 }
807 }
Andreas Gampef45d61c2017-06-07 10:29:33 -0700808 CHECK(body != nullptr);
Aart Bik281c6812016-08-26 11:31:48 -0700809 // Ensure there is only a single exit point.
810 if (header->GetSuccessors().size() != 2) {
Aart Bikb29f6842017-07-28 15:58:41 -0700811 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700812 }
813 HBasicBlock* exit = (header->GetSuccessors()[0] == body)
814 ? header->GetSuccessors()[1]
815 : header->GetSuccessors()[0];
Aart Bik8c4a8542016-10-06 11:36:57 -0700816 // Ensure exit can only be reached by exiting loop.
Aart Bik281c6812016-08-26 11:31:48 -0700817 if (exit->GetPredecessors().size() != 1) {
Aart Bikb29f6842017-07-28 15:58:41 -0700818 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700819 }
Aart Bik6b69e0a2017-01-11 10:20:43 -0800820 // Detect either an empty loop (no side effects other than plain iteration) or
821 // a trivial loop (just iterating once). Replace subsequent index uses, if any,
822 // with the last value and remove the loop, possibly after unrolling its body.
Aart Bikb29f6842017-07-28 15:58:41 -0700823 HPhi* main_phi = nullptr;
824 if (TrySetSimpleLoopHeader(header, &main_phi)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -0800825 bool is_empty = IsEmptyBody(body);
Aart Bikb29f6842017-07-28 15:58:41 -0700826 if (reductions_->empty() && // TODO: possible with some effort
827 (is_empty || trip_count == 1) &&
828 TryAssignLastValue(node->loop_info, main_phi, preheader, /*collect_loop_uses*/ true)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -0800829 if (!is_empty) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800830 // Unroll the loop-body, which sees initial value of the index.
Aart Bikb29f6842017-07-28 15:58:41 -0700831 main_phi->ReplaceWith(main_phi->InputAt(0));
Aart Bik6b69e0a2017-01-11 10:20:43 -0800832 preheader->MergeInstructionsWith(body);
833 }
834 body->DisconnectAndDelete();
835 exit->RemovePredecessor(header);
836 header->RemoveSuccessor(exit);
837 header->RemoveDominatedBlock(exit);
838 header->DisconnectAndDelete();
839 preheader->AddSuccessor(exit);
Aart Bikf8f5a162017-02-06 15:35:29 -0800840 preheader->AddInstruction(new (global_allocator_) HGoto());
Aart Bik6b69e0a2017-01-11 10:20:43 -0800841 preheader->AddDominatedBlock(exit);
842 exit->SetDominator(preheader);
843 RemoveLoop(node); // update hierarchy
Aart Bikb29f6842017-07-28 15:58:41 -0700844 return true;
Aart Bikf8f5a162017-02-06 15:35:29 -0800845 }
846 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800847 // Vectorize loop, if possible and valid.
Aart Bikb29f6842017-07-28 15:58:41 -0700848 if (kEnableVectorization &&
Artem Serove65ade72019-07-25 21:04:16 +0100849 // Disable vectorization for debuggable graphs: this is a workaround for the bug
850 // in 'GenerateNewLoop' which caused the SuspendCheck environment to be invalid.
851 // TODO: b/138601207, investigate other possible cases with wrong environment values and
852 // possibly switch back vectorization on for debuggable graphs.
853 !graph_->IsDebuggable() &&
Aart Bikb29f6842017-07-28 15:58:41 -0700854 TrySetSimpleLoopHeader(header, &main_phi) &&
Aart Bikb29f6842017-07-28 15:58:41 -0700855 ShouldVectorize(node, body, trip_count) &&
856 TryAssignLastValue(node->loop_info, main_phi, preheader, /*collect_loop_uses*/ true)) {
857 Vectorize(node, body, exit, trip_count);
858 graph_->SetHasSIMD(true); // flag SIMD usage
Aart Bik21b85922017-09-06 13:29:16 -0700859 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorized);
Aart Bikb29f6842017-07-28 15:58:41 -0700860 return true;
Aart Bikf8f5a162017-02-06 15:35:29 -0800861 }
Aart Bikb29f6842017-07-28 15:58:41 -0700862 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -0800863}
864
Artem Serov121f2032017-10-23 19:19:06 +0100865bool HLoopOptimization::OptimizeInnerLoop(LoopNode* node) {
Stelios Ioannouc54cc7c2021-07-09 17:06:03 +0100866 return TryOptimizeInnerLoopFinite(node) || TryLoopScalarOpts(node);
Artem Serov121f2032017-10-23 19:19:06 +0100867}
868
Artem Serov121f2032017-10-23 19:19:06 +0100869//
Artem Serov0e329082018-06-12 10:23:27 +0100870// Scalar loop peeling and unrolling: generic part methods.
Artem Serov121f2032017-10-23 19:19:06 +0100871//
872
Artem Serov0e329082018-06-12 10:23:27 +0100873bool HLoopOptimization::TryUnrollingForBranchPenaltyReduction(LoopAnalysisInfo* analysis_info,
874 bool generate_code) {
875 if (analysis_info->GetNumberOfExits() > 1) {
Artem Serov121f2032017-10-23 19:19:06 +0100876 return false;
877 }
878
Artem Serov0e329082018-06-12 10:23:27 +0100879 uint32_t unrolling_factor = arch_loop_helper_->GetScalarUnrollingFactor(analysis_info);
880 if (unrolling_factor == LoopAnalysisInfo::kNoUnrollingFactor) {
Artem Serov121f2032017-10-23 19:19:06 +0100881 return false;
882 }
883
Artem Serov0e329082018-06-12 10:23:27 +0100884 if (generate_code) {
885 // TODO: support other unrolling factors.
886 DCHECK_EQ(unrolling_factor, 2u);
887
888 // Perform unrolling.
889 HLoopInformation* loop_info = analysis_info->GetLoopInfo();
Artem Serov0f5b2bf2019-10-23 14:07:41 +0100890 LoopClonerSimpleHelper helper(loop_info, &induction_range_);
Artem Serov0e329082018-06-12 10:23:27 +0100891 helper.DoUnrolling();
892
893 // Remove the redundant loop check after unrolling.
894 HIf* copy_hif =
895 helper.GetBasicBlockMap()->Get(loop_info->GetHeader())->GetLastInstruction()->AsIf();
896 int32_t constant = loop_info->Contains(*copy_hif->IfTrueSuccessor()) ? 1 : 0;
897 copy_hif->ReplaceInput(graph_->GetIntConstant(constant), 0u);
Artem Serov121f2032017-10-23 19:19:06 +0100898 }
Artem Serov121f2032017-10-23 19:19:06 +0100899 return true;
900}
901
Artem Serov0e329082018-06-12 10:23:27 +0100902bool HLoopOptimization::TryPeelingForLoopInvariantExitsElimination(LoopAnalysisInfo* analysis_info,
903 bool generate_code) {
904 HLoopInformation* loop_info = analysis_info->GetLoopInfo();
Artem Serov72411e62017-10-19 16:18:07 +0100905 if (!arch_loop_helper_->IsLoopPeelingEnabled()) {
906 return false;
907 }
908
Artem Serov0e329082018-06-12 10:23:27 +0100909 if (analysis_info->GetNumberOfInvariantExits() == 0) {
Artem Serov72411e62017-10-19 16:18:07 +0100910 return false;
911 }
912
Artem Serov0e329082018-06-12 10:23:27 +0100913 if (generate_code) {
914 // Perform peeling.
Artem Serov0f5b2bf2019-10-23 14:07:41 +0100915 LoopClonerSimpleHelper helper(loop_info, &induction_range_);
Artem Serov0e329082018-06-12 10:23:27 +0100916 helper.DoPeeling();
Artem Serov72411e62017-10-19 16:18:07 +0100917
Artem Serov0e329082018-06-12 10:23:27 +0100918 // Statically evaluate loop check after peeling for loop invariant condition.
919 const SuperblockCloner::HInstructionMap* hir_map = helper.GetInstructionMap();
920 for (auto entry : *hir_map) {
921 HInstruction* copy = entry.second;
922 if (copy->IsIf()) {
923 TryToEvaluateIfCondition(copy->AsIf(), graph_);
924 }
Artem Serov72411e62017-10-19 16:18:07 +0100925 }
926 }
927
928 return true;
929}
930
Artem Serov18ba1da2018-05-16 19:06:32 +0100931bool HLoopOptimization::TryFullUnrolling(LoopAnalysisInfo* analysis_info, bool generate_code) {
932 // Fully unroll loops with a known and small trip count.
933 int64_t trip_count = analysis_info->GetTripCount();
934 if (!arch_loop_helper_->IsLoopPeelingEnabled() ||
935 trip_count == LoopAnalysisInfo::kUnknownTripCount ||
936 !arch_loop_helper_->IsFullUnrollingBeneficial(analysis_info)) {
937 return false;
938 }
939
940 if (generate_code) {
941 // Peeling of the N first iterations (where N equals to the trip count) will effectively
942 // eliminate the loop: after peeling we will have N sequential iterations copied into the loop
943 // preheader and the original loop. The trip count of this loop will be 0 as the sequential
944 // iterations are executed first and there are exactly N of them. Thus we can statically
945 // evaluate the loop exit condition to 'false' and fully eliminate it.
946 //
947 // Here is an example of full unrolling of a loop with a trip count 2:
948 //
949 // loop_cond_1
950 // loop_body_1 <- First iteration.
951 // |
952 // \ v
953 // ==\ loop_cond_2
954 // ==/ loop_body_2 <- Second iteration.
955 // / |
956 // <- v <-
957 // loop_cond \ loop_cond \ <- This cond is always false.
958 // loop_body _/ loop_body _/
959 //
960 HLoopInformation* loop_info = analysis_info->GetLoopInfo();
Nicolas Geoffray256c94b2019-04-29 10:55:09 +0100961 PeelByCount(loop_info, trip_count, &induction_range_);
Artem Serov18ba1da2018-05-16 19:06:32 +0100962 HIf* loop_hif = loop_info->GetHeader()->GetLastInstruction()->AsIf();
963 int32_t constant = loop_info->Contains(*loop_hif->IfTrueSuccessor()) ? 0 : 1;
964 loop_hif->ReplaceInput(graph_->GetIntConstant(constant), 0u);
965 }
966
967 return true;
968}
969
Stelios Ioannouc54cc7c2021-07-09 17:06:03 +0100970bool HLoopOptimization::TryLoopScalarOpts(LoopNode* node) {
Artem Serov0e329082018-06-12 10:23:27 +0100971 HLoopInformation* loop_info = node->loop_info;
972 int64_t trip_count = LoopAnalysis::GetLoopTripCount(loop_info, &induction_range_);
973 LoopAnalysisInfo analysis_info(loop_info);
974 LoopAnalysis::CalculateLoopBasicProperties(loop_info, &analysis_info, trip_count);
975
976 if (analysis_info.HasInstructionsPreventingScalarOpts() ||
977 arch_loop_helper_->IsLoopNonBeneficialForScalarOpts(&analysis_info)) {
978 return false;
979 }
980
Artem Serov18ba1da2018-05-16 19:06:32 +0100981 if (!TryFullUnrolling(&analysis_info, /*generate_code*/ false) &&
982 !TryPeelingForLoopInvariantExitsElimination(&analysis_info, /*generate_code*/ false) &&
Stelios Ioannouc54cc7c2021-07-09 17:06:03 +0100983 !TryUnrollingForBranchPenaltyReduction(&analysis_info, /*generate_code*/ false) &&
984 !TryToRemoveSuspendCheckFromLoopHeader(&analysis_info, /*generate_code*/ false)) {
Artem Serov0e329082018-06-12 10:23:27 +0100985 return false;
986 }
987
Stelios Ioannouc54cc7c2021-07-09 17:06:03 +0100988 // Try the suspend check removal even for non-clonable loops. Also this
989 // optimization doesn't interfere with other scalar loop optimizations so it can
990 // be done prior to them.
991 bool removed_suspend_check = TryToRemoveSuspendCheckFromLoopHeader(&analysis_info);
992
Artem Serov0e329082018-06-12 10:23:27 +0100993 // Run 'IsLoopClonable' the last as it might be time-consuming.
Artem Serov0f5b2bf2019-10-23 14:07:41 +0100994 if (!LoopClonerHelper::IsLoopClonable(loop_info)) {
Artem Serov0e329082018-06-12 10:23:27 +0100995 return false;
996 }
997
Artem Serov18ba1da2018-05-16 19:06:32 +0100998 return TryFullUnrolling(&analysis_info) ||
999 TryPeelingForLoopInvariantExitsElimination(&analysis_info) ||
Stelios Ioannouc54cc7c2021-07-09 17:06:03 +01001000 TryUnrollingForBranchPenaltyReduction(&analysis_info) || removed_suspend_check;
Artem Serov0e329082018-06-12 10:23:27 +01001001}
1002
Aart Bikf8f5a162017-02-06 15:35:29 -08001003//
1004// Loop vectorization. The implementation is based on the book by Aart J.C. Bik:
1005// "The Software Vectorization Handbook. Applying Multimedia Extensions for Maximum Performance."
1006// Intel Press, June, 2004 (http://www.aartbik.com/).
1007//
1008
Aart Bik14a68b42017-06-08 14:06:58 -07001009bool HLoopOptimization::ShouldVectorize(LoopNode* node, HBasicBlock* block, int64_t trip_count) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001010 // Reset vector bookkeeping.
1011 vector_length_ = 0;
1012 vector_refs_->clear();
Aart Bik38a3f212017-10-20 17:02:21 -07001013 vector_static_peeling_factor_ = 0;
1014 vector_dynamic_peeling_candidate_ = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -08001015 vector_runtime_test_a_ =
Igor Murashkin2ffb7032017-11-08 13:35:21 -08001016 vector_runtime_test_b_ = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -08001017
1018 // Phis in the loop-body prevent vectorization.
1019 if (!block->GetPhis().IsEmpty()) {
1020 return false;
1021 }
1022
1023 // Scan the loop-body, starting a right-hand-side tree traversal at each left-hand-side
1024 // occurrence, which allows passing down attributes down the use tree.
1025 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
1026 if (!VectorizeDef(node, it.Current(), /*generate_code*/ false)) {
1027 return false; // failure to vectorize a left-hand-side
1028 }
1029 }
1030
Aart Bik38a3f212017-10-20 17:02:21 -07001031 // Prepare alignment analysis:
1032 // (1) find desired alignment (SIMD vector size in bytes).
1033 // (2) initialize static loop peeling votes (peeling factor that will
1034 // make one particular reference aligned), never to exceed (1).
1035 // (3) variable to record how many references share same alignment.
1036 // (4) variable to record suitable candidate for dynamic loop peeling.
Artem Serov55ab7e82020-04-27 21:02:28 +01001037 size_t desired_alignment = GetVectorSizeInBytes();
1038 ScopedArenaVector<uint32_t> peeling_votes(desired_alignment, 0u,
1039 loop_allocator_->Adapter(kArenaAllocLoopOptimization));
1040
Aart Bik38a3f212017-10-20 17:02:21 -07001041 uint32_t max_num_same_alignment = 0;
1042 const ArrayReference* peeling_candidate = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -08001043
1044 // Data dependence analysis. Find each pair of references with same type, where
1045 // at least one is a write. Each such pair denotes a possible data dependence.
1046 // This analysis exploits the property that differently typed arrays cannot be
1047 // aliased, as well as the property that references either point to the same
1048 // array or to two completely disjoint arrays, i.e., no partial aliasing.
1049 // Other than a few simply heuristics, no detailed subscript analysis is done.
Aart Bik38a3f212017-10-20 17:02:21 -07001050 // The scan over references also prepares finding a suitable alignment strategy.
Aart Bikf8f5a162017-02-06 15:35:29 -08001051 for (auto i = vector_refs_->begin(); i != vector_refs_->end(); ++i) {
Aart Bik38a3f212017-10-20 17:02:21 -07001052 uint32_t num_same_alignment = 0;
1053 // Scan over all next references.
Aart Bikf8f5a162017-02-06 15:35:29 -08001054 for (auto j = i; ++j != vector_refs_->end(); ) {
1055 if (i->type == j->type && (i->lhs || j->lhs)) {
1056 // Found same-typed a[i+x] vs. b[i+y], where at least one is a write.
1057 HInstruction* a = i->base;
1058 HInstruction* b = j->base;
1059 HInstruction* x = i->offset;
1060 HInstruction* y = j->offset;
1061 if (a == b) {
1062 // Found a[i+x] vs. a[i+y]. Accept if x == y (loop-independent data dependence).
1063 // Conservatively assume a loop-carried data dependence otherwise, and reject.
1064 if (x != y) {
1065 return false;
1066 }
Aart Bik38a3f212017-10-20 17:02:21 -07001067 // Count the number of references that have the same alignment (since
1068 // base and offset are the same) and where at least one is a write, so
1069 // e.g. a[i] = a[i] + b[i] counts a[i] but not b[i]).
1070 num_same_alignment++;
Aart Bikf8f5a162017-02-06 15:35:29 -08001071 } else {
1072 // Found a[i+x] vs. b[i+y]. Accept if x == y (at worst loop-independent data dependence).
1073 // Conservatively assume a potential loop-carried data dependence otherwise, avoided by
1074 // generating an explicit a != b disambiguation runtime test on the two references.
1075 if (x != y) {
Aart Bik37dc4df2017-06-28 14:08:00 -07001076 // To avoid excessive overhead, we only accept one a != b test.
1077 if (vector_runtime_test_a_ == nullptr) {
1078 // First test found.
1079 vector_runtime_test_a_ = a;
1080 vector_runtime_test_b_ = b;
1081 } else if ((vector_runtime_test_a_ != a || vector_runtime_test_b_ != b) &&
1082 (vector_runtime_test_a_ != b || vector_runtime_test_b_ != a)) {
1083 return false; // second test would be needed
Aart Bikf8f5a162017-02-06 15:35:29 -08001084 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001085 }
1086 }
1087 }
1088 }
Aart Bik38a3f212017-10-20 17:02:21 -07001089 // Update information for finding suitable alignment strategy:
1090 // (1) update votes for static loop peeling,
1091 // (2) update suitable candidate for dynamic loop peeling.
1092 Alignment alignment = ComputeAlignment(i->offset, i->type, i->is_string_char_at);
1093 if (alignment.Base() >= desired_alignment) {
1094 // If the array/string object has a known, sufficient alignment, use the
1095 // initial offset to compute the static loop peeling vote (this always
1096 // works, since elements have natural alignment).
1097 uint32_t offset = alignment.Offset() & (desired_alignment - 1u);
1098 uint32_t vote = (offset == 0)
1099 ? 0
1100 : ((desired_alignment - offset) >> DataType::SizeShift(i->type));
1101 DCHECK_LT(vote, 16u);
1102 ++peeling_votes[vote];
1103 } else if (BaseAlignment() >= desired_alignment &&
1104 num_same_alignment > max_num_same_alignment) {
1105 // Otherwise, if the array/string object has a known, sufficient alignment
1106 // for just the base but with an unknown offset, record the candidate with
1107 // the most occurrences for dynamic loop peeling (again, the peeling always
1108 // works, since elements have natural alignment).
1109 max_num_same_alignment = num_same_alignment;
1110 peeling_candidate = &(*i);
1111 }
1112 } // for i
Aart Bikf8f5a162017-02-06 15:35:29 -08001113
Artem Serov8ba4de12019-12-04 21:10:23 +00001114 if (!IsInPredicatedVectorizationMode()) {
1115 // Find a suitable alignment strategy.
1116 SetAlignmentStrategy(peeling_votes, peeling_candidate);
1117 }
Aart Bik38a3f212017-10-20 17:02:21 -07001118
1119 // Does vectorization seem profitable?
1120 if (!IsVectorizationProfitable(trip_count)) {
1121 return false;
1122 }
Aart Bik14a68b42017-06-08 14:06:58 -07001123
Aart Bikf8f5a162017-02-06 15:35:29 -08001124 // Success!
1125 return true;
1126}
1127
1128void HLoopOptimization::Vectorize(LoopNode* node,
1129 HBasicBlock* block,
1130 HBasicBlock* exit,
1131 int64_t trip_count) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001132 HBasicBlock* header = node->loop_info->GetHeader();
1133 HBasicBlock* preheader = node->loop_info->GetPreHeader();
1134
Aart Bik14a68b42017-06-08 14:06:58 -07001135 // Pick a loop unrolling factor for the vector loop.
Artem Serov121f2032017-10-23 19:19:06 +01001136 uint32_t unroll = arch_loop_helper_->GetSIMDUnrollingFactor(
1137 block, trip_count, MaxNumberPeeled(), vector_length_);
Aart Bik14a68b42017-06-08 14:06:58 -07001138 uint32_t chunk = vector_length_ * unroll;
1139
Aart Bik38a3f212017-10-20 17:02:21 -07001140 DCHECK(trip_count == 0 || (trip_count >= MaxNumberPeeled() + chunk));
1141
Aart Bik14a68b42017-06-08 14:06:58 -07001142 // A cleanup loop is needed, at least, for any unknown trip count or
1143 // for a known trip count with remainder iterations after vectorization.
Artem Serov8ba4de12019-12-04 21:10:23 +00001144 bool needs_cleanup = !IsInPredicatedVectorizationMode() &&
1145 (trip_count == 0 || ((trip_count - vector_static_peeling_factor_) % chunk) != 0);
Aart Bikf8f5a162017-02-06 15:35:29 -08001146
1147 // Adjust vector bookkeeping.
Aart Bikb29f6842017-07-28 15:58:41 -07001148 HPhi* main_phi = nullptr;
1149 bool is_simple_loop_header = TrySetSimpleLoopHeader(header, &main_phi); // refills sets
Aart Bikf8f5a162017-02-06 15:35:29 -08001150 DCHECK(is_simple_loop_header);
Aart Bik14a68b42017-06-08 14:06:58 -07001151 vector_header_ = header;
1152 vector_body_ = block;
Aart Bikf8f5a162017-02-06 15:35:29 -08001153
Aart Bikdbbac8f2017-09-01 13:06:08 -07001154 // Loop induction type.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001155 DataType::Type induc_type = main_phi->GetType();
1156 DCHECK(induc_type == DataType::Type::kInt32 || induc_type == DataType::Type::kInt64)
1157 << induc_type;
Aart Bikdbbac8f2017-09-01 13:06:08 -07001158
Aart Bik38a3f212017-10-20 17:02:21 -07001159 // Generate the trip count for static or dynamic loop peeling, if needed:
1160 // ptc = <peeling factor>;
Aart Bik14a68b42017-06-08 14:06:58 -07001161 HInstruction* ptc = nullptr;
Aart Bik38a3f212017-10-20 17:02:21 -07001162 if (vector_static_peeling_factor_ != 0) {
Artem Serov8ba4de12019-12-04 21:10:23 +00001163 DCHECK(!IsInPredicatedVectorizationMode());
Aart Bik38a3f212017-10-20 17:02:21 -07001164 // Static loop peeling for SIMD alignment (using the most suitable
1165 // fixed peeling factor found during prior alignment analysis).
1166 DCHECK(vector_dynamic_peeling_candidate_ == nullptr);
1167 ptc = graph_->GetConstant(induc_type, vector_static_peeling_factor_);
1168 } else if (vector_dynamic_peeling_candidate_ != nullptr) {
Artem Serov8ba4de12019-12-04 21:10:23 +00001169 DCHECK(!IsInPredicatedVectorizationMode());
Aart Bik38a3f212017-10-20 17:02:21 -07001170 // Dynamic loop peeling for SIMD alignment (using the most suitable
1171 // candidate found during prior alignment analysis):
1172 // rem = offset % ALIGN; // adjusted as #elements
1173 // ptc = rem == 0 ? 0 : (ALIGN - rem);
1174 uint32_t shift = DataType::SizeShift(vector_dynamic_peeling_candidate_->type);
1175 uint32_t align = GetVectorSizeInBytes() >> shift;
1176 uint32_t hidden_offset = HiddenOffset(vector_dynamic_peeling_candidate_->type,
1177 vector_dynamic_peeling_candidate_->is_string_char_at);
1178 HInstruction* adjusted_offset = graph_->GetConstant(induc_type, hidden_offset >> shift);
1179 HInstruction* offset = Insert(preheader, new (global_allocator_) HAdd(
1180 induc_type, vector_dynamic_peeling_candidate_->offset, adjusted_offset));
1181 HInstruction* rem = Insert(preheader, new (global_allocator_) HAnd(
1182 induc_type, offset, graph_->GetConstant(induc_type, align - 1u)));
1183 HInstruction* sub = Insert(preheader, new (global_allocator_) HSub(
1184 induc_type, graph_->GetConstant(induc_type, align), rem));
1185 HInstruction* cond = Insert(preheader, new (global_allocator_) HEqual(
1186 rem, graph_->GetConstant(induc_type, 0)));
1187 ptc = Insert(preheader, new (global_allocator_) HSelect(
1188 cond, graph_->GetConstant(induc_type, 0), sub, kNoDexPc));
1189 needs_cleanup = true; // don't know the exact amount
Aart Bik14a68b42017-06-08 14:06:58 -07001190 }
1191
1192 // Generate loop control:
Aart Bikf8f5a162017-02-06 15:35:29 -08001193 // stc = <trip-count>;
Aart Bik38a3f212017-10-20 17:02:21 -07001194 // ptc = min(stc, ptc);
Aart Bik14a68b42017-06-08 14:06:58 -07001195 // vtc = stc - (stc - ptc) % chunk;
1196 // i = 0;
Aart Bikf8f5a162017-02-06 15:35:29 -08001197 HInstruction* stc = induction_range_.GenerateTripCount(node->loop_info, graph_, preheader);
1198 HInstruction* vtc = stc;
1199 if (needs_cleanup) {
Artem Serov8ba4de12019-12-04 21:10:23 +00001200 DCHECK(!IsInPredicatedVectorizationMode());
Aart Bik14a68b42017-06-08 14:06:58 -07001201 DCHECK(IsPowerOfTwo(chunk));
1202 HInstruction* diff = stc;
1203 if (ptc != nullptr) {
Aart Bik38a3f212017-10-20 17:02:21 -07001204 if (trip_count == 0) {
1205 HInstruction* cond = Insert(preheader, new (global_allocator_) HAboveOrEqual(stc, ptc));
1206 ptc = Insert(preheader, new (global_allocator_) HSelect(cond, ptc, stc, kNoDexPc));
1207 }
Aart Bik14a68b42017-06-08 14:06:58 -07001208 diff = Insert(preheader, new (global_allocator_) HSub(induc_type, stc, ptc));
1209 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001210 HInstruction* rem = Insert(
1211 preheader, new (global_allocator_) HAnd(induc_type,
Aart Bik14a68b42017-06-08 14:06:58 -07001212 diff,
Aart Bikdbbac8f2017-09-01 13:06:08 -07001213 graph_->GetConstant(induc_type, chunk - 1)));
Aart Bikf8f5a162017-02-06 15:35:29 -08001214 vtc = Insert(preheader, new (global_allocator_) HSub(induc_type, stc, rem));
1215 }
Aart Bikdbbac8f2017-09-01 13:06:08 -07001216 vector_index_ = graph_->GetConstant(induc_type, 0);
Aart Bikf8f5a162017-02-06 15:35:29 -08001217
1218 // Generate runtime disambiguation test:
1219 // vtc = a != b ? vtc : 0;
1220 if (vector_runtime_test_a_ != nullptr) {
1221 HInstruction* rt = Insert(
1222 preheader,
1223 new (global_allocator_) HNotEqual(vector_runtime_test_a_, vector_runtime_test_b_));
1224 vtc = Insert(preheader,
Aart Bikdbbac8f2017-09-01 13:06:08 -07001225 new (global_allocator_)
1226 HSelect(rt, vtc, graph_->GetConstant(induc_type, 0), kNoDexPc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001227 needs_cleanup = true;
1228 }
1229
Aart Bik38a3f212017-10-20 17:02:21 -07001230 // Generate alignment peeling loop, if needed:
Aart Bik14a68b42017-06-08 14:06:58 -07001231 // for ( ; i < ptc; i += 1)
1232 // <loop-body>
Aart Bik38a3f212017-10-20 17:02:21 -07001233 //
1234 // NOTE: The alignment forced by the peeling loop is preserved even if data is
1235 // moved around during suspend checks, since all analysis was based on
1236 // nothing more than the Android runtime alignment conventions.
Aart Bik14a68b42017-06-08 14:06:58 -07001237 if (ptc != nullptr) {
Artem Serov8ba4de12019-12-04 21:10:23 +00001238 DCHECK(!IsInPredicatedVectorizationMode());
Aart Bik14a68b42017-06-08 14:06:58 -07001239 vector_mode_ = kSequential;
1240 GenerateNewLoop(node,
1241 block,
1242 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
1243 vector_index_,
1244 ptc,
Aart Bikdbbac8f2017-09-01 13:06:08 -07001245 graph_->GetConstant(induc_type, 1),
Artem Serov0e329082018-06-12 10:23:27 +01001246 LoopAnalysisInfo::kNoUnrollingFactor);
Aart Bik14a68b42017-06-08 14:06:58 -07001247 }
1248
1249 // Generate vector loop, possibly further unrolled:
1250 // for ( ; i < vtc; i += chunk)
Aart Bikf8f5a162017-02-06 15:35:29 -08001251 // <vectorized-loop-body>
1252 vector_mode_ = kVector;
1253 GenerateNewLoop(node,
1254 block,
Aart Bik14a68b42017-06-08 14:06:58 -07001255 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
1256 vector_index_,
Aart Bikf8f5a162017-02-06 15:35:29 -08001257 vtc,
Aart Bikdbbac8f2017-09-01 13:06:08 -07001258 graph_->GetConstant(induc_type, vector_length_), // increment per unroll
Aart Bik14a68b42017-06-08 14:06:58 -07001259 unroll);
Aart Bikf8f5a162017-02-06 15:35:29 -08001260 HLoopInformation* vloop = vector_header_->GetLoopInformation();
1261
1262 // Generate cleanup loop, if needed:
1263 // for ( ; i < stc; i += 1)
1264 // <loop-body>
1265 if (needs_cleanup) {
Santiago Aboy Solanes872ec722022-02-18 14:10:25 +00001266 DCHECK_IMPLIES(IsInPredicatedVectorizationMode(), vector_runtime_test_a_ != nullptr);
Aart Bikf8f5a162017-02-06 15:35:29 -08001267 vector_mode_ = kSequential;
1268 GenerateNewLoop(node,
1269 block,
1270 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
Aart Bik14a68b42017-06-08 14:06:58 -07001271 vector_index_,
Aart Bikf8f5a162017-02-06 15:35:29 -08001272 stc,
Aart Bikdbbac8f2017-09-01 13:06:08 -07001273 graph_->GetConstant(induc_type, 1),
Artem Serov0e329082018-06-12 10:23:27 +01001274 LoopAnalysisInfo::kNoUnrollingFactor);
Aart Bikf8f5a162017-02-06 15:35:29 -08001275 }
1276
Aart Bik0148de42017-09-05 09:25:01 -07001277 // Link reductions to their final uses.
1278 for (auto i = reductions_->begin(); i != reductions_->end(); ++i) {
1279 if (i->first->IsPhi()) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001280 HInstruction* phi = i->first;
1281 HInstruction* repl = ReduceAndExtractIfNeeded(i->second);
1282 // Deal with regular uses.
1283 for (const HUseListNode<HInstruction*>& use : phi->GetUses()) {
1284 induction_range_.Replace(use.GetUser(), phi, repl); // update induction use
1285 }
1286 phi->ReplaceWith(repl);
Aart Bik0148de42017-09-05 09:25:01 -07001287 }
1288 }
1289
Aart Bikf8f5a162017-02-06 15:35:29 -08001290 // Remove the original loop by disconnecting the body block
1291 // and removing all instructions from the header.
1292 block->DisconnectAndDelete();
1293 while (!header->GetFirstInstruction()->IsGoto()) {
1294 header->RemoveInstruction(header->GetFirstInstruction());
1295 }
Aart Bikb29f6842017-07-28 15:58:41 -07001296
Aart Bik14a68b42017-06-08 14:06:58 -07001297 // Update loop hierarchy: the old header now resides in the same outer loop
1298 // as the old preheader. Note that we don't bother putting sequential
1299 // loops back in the hierarchy at this point.
Aart Bikf8f5a162017-02-06 15:35:29 -08001300 header->SetLoopInformation(preheader->GetLoopInformation()); // outward
1301 node->loop_info = vloop;
1302}
1303
1304void HLoopOptimization::GenerateNewLoop(LoopNode* node,
1305 HBasicBlock* block,
1306 HBasicBlock* new_preheader,
1307 HInstruction* lo,
1308 HInstruction* hi,
Aart Bik14a68b42017-06-08 14:06:58 -07001309 HInstruction* step,
1310 uint32_t unroll) {
1311 DCHECK(unroll == 1 || vector_mode_ == kVector);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001312 DataType::Type induc_type = lo->GetType();
Aart Bikf8f5a162017-02-06 15:35:29 -08001313 // Prepare new loop.
Aart Bikf8f5a162017-02-06 15:35:29 -08001314 vector_preheader_ = new_preheader,
1315 vector_header_ = vector_preheader_->GetSingleSuccessor();
1316 vector_body_ = vector_header_->GetSuccessors()[1];
Aart Bik14a68b42017-06-08 14:06:58 -07001317 HPhi* phi = new (global_allocator_) HPhi(global_allocator_,
1318 kNoRegNumber,
1319 0,
1320 HPhi::ToPhiType(induc_type));
Aart Bikb07d1bc2017-04-05 10:03:15 -07001321 // Generate header and prepare body.
Aart Bikf8f5a162017-02-06 15:35:29 -08001322 // for (i = lo; i < hi; i += step)
1323 // <loop-body>
Artem Serov8ba4de12019-12-04 21:10:23 +00001324 HInstruction* cond = nullptr;
1325 HInstruction* set_pred = nullptr;
1326 if (IsInPredicatedVectorizationMode()) {
1327 HVecPredWhile* pred_while =
1328 new (global_allocator_) HVecPredWhile(global_allocator_,
1329 phi,
1330 hi,
1331 HVecPredWhile::CondKind::kLO,
1332 DataType::Type::kInt32,
1333 vector_length_,
1334 0u);
1335
1336 cond = new (global_allocator_) HVecPredCondition(global_allocator_,
1337 pred_while,
1338 HVecPredCondition::PCondKind::kNFirst,
1339 DataType::Type::kInt32,
1340 vector_length_,
1341 0u);
1342
1343 vector_header_->AddPhi(phi);
1344 vector_header_->AddInstruction(pred_while);
1345 vector_header_->AddInstruction(cond);
1346 set_pred = pred_while;
1347 } else {
1348 cond = new (global_allocator_) HAboveOrEqual(phi, hi);
1349 vector_header_->AddPhi(phi);
1350 vector_header_->AddInstruction(cond);
1351 }
1352
Aart Bikf8f5a162017-02-06 15:35:29 -08001353 vector_header_->AddInstruction(new (global_allocator_) HIf(cond));
Aart Bik14a68b42017-06-08 14:06:58 -07001354 vector_index_ = phi;
Aart Bik0148de42017-09-05 09:25:01 -07001355 vector_permanent_map_->clear(); // preserved over unrolling
Aart Bik14a68b42017-06-08 14:06:58 -07001356 for (uint32_t u = 0; u < unroll; u++) {
Aart Bik14a68b42017-06-08 14:06:58 -07001357 // Generate instruction map.
Aart Bik0148de42017-09-05 09:25:01 -07001358 vector_map_->clear();
Aart Bik14a68b42017-06-08 14:06:58 -07001359 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
1360 bool vectorized_def = VectorizeDef(node, it.Current(), /*generate_code*/ true);
1361 DCHECK(vectorized_def);
1362 }
1363 // Generate body from the instruction map, but in original program order.
1364 HEnvironment* env = vector_header_->GetFirstInstruction()->GetEnvironment();
1365 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
1366 auto i = vector_map_->find(it.Current());
1367 if (i != vector_map_->end() && !i->second->IsInBlock()) {
1368 Insert(vector_body_, i->second);
Artem Serov8ba4de12019-12-04 21:10:23 +00001369 if (IsInPredicatedVectorizationMode() && i->second->IsVecOperation()) {
1370 HVecOperation* op = i->second->AsVecOperation();
1371 op->SetMergingGoverningPredicate(set_pred);
1372 }
Aart Bik14a68b42017-06-08 14:06:58 -07001373 // Deal with instructions that need an environment, such as the scalar intrinsics.
1374 if (i->second->NeedsEnvironment()) {
1375 i->second->CopyEnvironmentFromWithLoopPhiAdjustment(env, vector_header_);
1376 }
1377 }
1378 }
Aart Bik0148de42017-09-05 09:25:01 -07001379 // Generate the induction.
Aart Bik14a68b42017-06-08 14:06:58 -07001380 vector_index_ = new (global_allocator_) HAdd(induc_type, vector_index_, step);
1381 Insert(vector_body_, vector_index_);
Aart Bikf8f5a162017-02-06 15:35:29 -08001382 }
Aart Bik0148de42017-09-05 09:25:01 -07001383 // Finalize phi inputs for the reductions (if any).
1384 for (auto i = reductions_->begin(); i != reductions_->end(); ++i) {
1385 if (!i->first->IsPhi()) {
1386 DCHECK(i->second->IsPhi());
1387 GenerateVecReductionPhiInputs(i->second->AsPhi(), i->first);
1388 }
1389 }
Aart Bikb29f6842017-07-28 15:58:41 -07001390 // Finalize phi inputs for the loop index.
Aart Bik14a68b42017-06-08 14:06:58 -07001391 phi->AddInput(lo);
1392 phi->AddInput(vector_index_);
1393 vector_index_ = phi;
Aart Bikf8f5a162017-02-06 15:35:29 -08001394}
1395
Aart Bikf8f5a162017-02-06 15:35:29 -08001396bool HLoopOptimization::VectorizeDef(LoopNode* node,
1397 HInstruction* instruction,
1398 bool generate_code) {
1399 // Accept a left-hand-side array base[index] for
1400 // (1) supported vector type,
1401 // (2) loop-invariant base,
1402 // (3) unit stride index,
1403 // (4) vectorizable right-hand-side value.
1404 uint64_t restrictions = kNone;
Georgia Kouvelibac080b2019-01-31 16:12:16 +00001405 // Don't accept expressions that can throw.
1406 if (instruction->CanThrow()) {
1407 return false;
1408 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001409 if (instruction->IsArraySet()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001410 DataType::Type type = instruction->AsArraySet()->GetComponentType();
Aart Bikf8f5a162017-02-06 15:35:29 -08001411 HInstruction* base = instruction->InputAt(0);
1412 HInstruction* index = instruction->InputAt(1);
1413 HInstruction* value = instruction->InputAt(2);
1414 HInstruction* offset = nullptr;
Aart Bik6d057002018-04-09 15:39:58 -07001415 // For narrow types, explicit type conversion may have been
1416 // optimized way, so set the no hi bits restriction here.
1417 if (DataType::Size(type) <= 2) {
1418 restrictions |= kNoHiBits;
1419 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001420 if (TrySetVectorType(type, &restrictions) &&
1421 node->loop_info->IsDefinedOutOfTheLoop(base) &&
Vladimir Marko8d100ba2022-03-04 10:13:10 +00001422 induction_range_.IsUnitStride(instruction->GetBlock(), index, graph_, &offset) &&
Aart Bikf8f5a162017-02-06 15:35:29 -08001423 VectorizeUse(node, value, generate_code, type, restrictions)) {
1424 if (generate_code) {
1425 GenerateVecSub(index, offset);
Aart Bik14a68b42017-06-08 14:06:58 -07001426 GenerateVecMem(instruction, vector_map_->Get(index), vector_map_->Get(value), offset, type);
Aart Bikf8f5a162017-02-06 15:35:29 -08001427 } else {
1428 vector_refs_->insert(ArrayReference(base, offset, type, /*lhs*/ true));
1429 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08001430 return true;
1431 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001432 return false;
1433 }
Aart Bik0148de42017-09-05 09:25:01 -07001434 // Accept a left-hand-side reduction for
1435 // (1) supported vector type,
1436 // (2) vectorizable right-hand-side value.
1437 auto redit = reductions_->find(instruction);
1438 if (redit != reductions_->end()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001439 DataType::Type type = instruction->GetType();
Aart Bikdbbac8f2017-09-01 13:06:08 -07001440 // Recognize SAD idiom or direct reduction.
1441 if (VectorizeSADIdiom(node, instruction, generate_code, type, restrictions) ||
Artem Serovaaac0e32018-08-07 00:52:22 +01001442 VectorizeDotProdIdiom(node, instruction, generate_code, type, restrictions) ||
Aart Bikdbbac8f2017-09-01 13:06:08 -07001443 (TrySetVectorType(type, &restrictions) &&
1444 VectorizeUse(node, instruction, generate_code, type, restrictions))) {
Aart Bik0148de42017-09-05 09:25:01 -07001445 if (generate_code) {
1446 HInstruction* new_red = vector_map_->Get(instruction);
1447 vector_permanent_map_->Put(new_red, vector_map_->Get(redit->second));
1448 vector_permanent_map_->Overwrite(redit->second, new_red);
1449 }
1450 return true;
1451 }
1452 return false;
1453 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001454 // Branch back okay.
1455 if (instruction->IsGoto()) {
1456 return true;
1457 }
1458 // Otherwise accept only expressions with no effects outside the immediate loop-body.
1459 // Note that actual uses are inspected during right-hand-side tree traversal.
Georgia Kouvelibac080b2019-01-31 16:12:16 +00001460 return !IsUsedOutsideLoop(node->loop_info, instruction)
1461 && !instruction->DoesAnyWrite();
Aart Bikf8f5a162017-02-06 15:35:29 -08001462}
1463
Aart Bikf8f5a162017-02-06 15:35:29 -08001464bool HLoopOptimization::VectorizeUse(LoopNode* node,
1465 HInstruction* instruction,
1466 bool generate_code,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001467 DataType::Type type,
Aart Bikf8f5a162017-02-06 15:35:29 -08001468 uint64_t restrictions) {
1469 // Accept anything for which code has already been generated.
1470 if (generate_code) {
1471 if (vector_map_->find(instruction) != vector_map_->end()) {
1472 return true;
1473 }
1474 }
1475 // Continue the right-hand-side tree traversal, passing in proper
1476 // types and vector restrictions along the way. During code generation,
1477 // all new nodes are drawn from the global allocator.
1478 if (node->loop_info->IsDefinedOutOfTheLoop(instruction)) {
1479 // Accept invariant use, using scalar expansion.
1480 if (generate_code) {
1481 GenerateVecInv(instruction, type);
1482 }
1483 return true;
1484 } else if (instruction->IsArrayGet()) {
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001485 // Deal with vector restrictions.
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001486 bool is_string_char_at = instruction->AsArrayGet()->IsStringCharAt();
Artem Serov8ba4de12019-12-04 21:10:23 +00001487
1488 if (is_string_char_at && (HasVectorRestrictions(restrictions, kNoStringCharAt) ||
1489 IsInPredicatedVectorizationMode())) {
1490 // TODO: Support CharAt for predicated mode.
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001491 return false;
1492 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001493 // Accept a right-hand-side array base[index] for
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001494 // (1) matching vector type (exact match or signed/unsigned integral type of the same size),
Aart Bikf8f5a162017-02-06 15:35:29 -08001495 // (2) loop-invariant base,
1496 // (3) unit stride index,
1497 // (4) vectorizable right-hand-side value.
1498 HInstruction* base = instruction->InputAt(0);
1499 HInstruction* index = instruction->InputAt(1);
1500 HInstruction* offset = nullptr;
Aart Bik46b6dbc2017-10-03 11:37:37 -07001501 if (HVecOperation::ToSignedType(type) == HVecOperation::ToSignedType(instruction->GetType()) &&
Aart Bikf8f5a162017-02-06 15:35:29 -08001502 node->loop_info->IsDefinedOutOfTheLoop(base) &&
Vladimir Marko8d100ba2022-03-04 10:13:10 +00001503 induction_range_.IsUnitStride(instruction->GetBlock(), index, graph_, &offset)) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001504 if (generate_code) {
1505 GenerateVecSub(index, offset);
Aart Bik14a68b42017-06-08 14:06:58 -07001506 GenerateVecMem(instruction, vector_map_->Get(index), nullptr, offset, type);
Aart Bikf8f5a162017-02-06 15:35:29 -08001507 } else {
Aart Bik38a3f212017-10-20 17:02:21 -07001508 vector_refs_->insert(ArrayReference(base, offset, type, /*lhs*/ false, is_string_char_at));
Aart Bikf8f5a162017-02-06 15:35:29 -08001509 }
1510 return true;
1511 }
Aart Bik0148de42017-09-05 09:25:01 -07001512 } else if (instruction->IsPhi()) {
1513 // Accept particular phi operations.
1514 if (reductions_->find(instruction) != reductions_->end()) {
1515 // Deal with vector restrictions.
1516 if (HasVectorRestrictions(restrictions, kNoReduction)) {
1517 return false;
1518 }
1519 // Accept a reduction.
1520 if (generate_code) {
1521 GenerateVecReductionPhi(instruction->AsPhi());
1522 }
1523 return true;
1524 }
1525 // TODO: accept right-hand-side induction?
1526 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001527 } else if (instruction->IsTypeConversion()) {
1528 // Accept particular type conversions.
1529 HTypeConversion* conversion = instruction->AsTypeConversion();
1530 HInstruction* opa = conversion->InputAt(0);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001531 DataType::Type from = conversion->GetInputType();
1532 DataType::Type to = conversion->GetResultType();
1533 if (DataType::IsIntegralType(from) && DataType::IsIntegralType(to)) {
Aart Bik38a3f212017-10-20 17:02:21 -07001534 uint32_t size_vec = DataType::Size(type);
1535 uint32_t size_from = DataType::Size(from);
1536 uint32_t size_to = DataType::Size(to);
Aart Bikdbbac8f2017-09-01 13:06:08 -07001537 // Accept an integral conversion
1538 // (1a) narrowing into vector type, "wider" operations cannot bring in higher order bits, or
1539 // (1b) widening from at least vector type, and
1540 // (2) vectorizable operand.
1541 if ((size_to < size_from &&
1542 size_to == size_vec &&
1543 VectorizeUse(node, opa, generate_code, type, restrictions | kNoHiBits)) ||
1544 (size_to >= size_from &&
1545 size_from >= size_vec &&
Aart Bik4d1a9d42017-10-19 14:40:55 -07001546 VectorizeUse(node, opa, generate_code, type, restrictions))) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001547 if (generate_code) {
1548 if (vector_mode_ == kVector) {
1549 vector_map_->Put(instruction, vector_map_->Get(opa)); // operand pass-through
1550 } else {
1551 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1552 }
1553 }
1554 return true;
1555 }
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001556 } else if (to == DataType::Type::kFloat32 && from == DataType::Type::kInt32) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001557 DCHECK_EQ(to, type);
1558 // Accept int to float conversion for
1559 // (1) supported int,
1560 // (2) vectorizable operand.
1561 if (TrySetVectorType(from, &restrictions) &&
1562 VectorizeUse(node, opa, generate_code, from, restrictions)) {
1563 if (generate_code) {
1564 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1565 }
1566 return true;
1567 }
1568 }
1569 return false;
1570 } else if (instruction->IsNeg() || instruction->IsNot() || instruction->IsBooleanNot()) {
1571 // Accept unary operator for vectorizable operand.
1572 HInstruction* opa = instruction->InputAt(0);
1573 if (VectorizeUse(node, opa, generate_code, type, restrictions)) {
1574 if (generate_code) {
1575 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1576 }
1577 return true;
1578 }
1579 } else if (instruction->IsAdd() || instruction->IsSub() ||
1580 instruction->IsMul() || instruction->IsDiv() ||
1581 instruction->IsAnd() || instruction->IsOr() || instruction->IsXor()) {
1582 // Deal with vector restrictions.
1583 if ((instruction->IsMul() && HasVectorRestrictions(restrictions, kNoMul)) ||
1584 (instruction->IsDiv() && HasVectorRestrictions(restrictions, kNoDiv))) {
1585 return false;
1586 }
1587 // Accept binary operator for vectorizable operands.
1588 HInstruction* opa = instruction->InputAt(0);
1589 HInstruction* opb = instruction->InputAt(1);
1590 if (VectorizeUse(node, opa, generate_code, type, restrictions) &&
1591 VectorizeUse(node, opb, generate_code, type, restrictions)) {
1592 if (generate_code) {
1593 GenerateVecOp(instruction, vector_map_->Get(opa), vector_map_->Get(opb), type);
1594 }
1595 return true;
1596 }
1597 } else if (instruction->IsShl() || instruction->IsShr() || instruction->IsUShr()) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001598 // Recognize halving add idiom.
Aart Bikf3e61ee2017-04-12 17:09:20 -07001599 if (VectorizeHalvingAddIdiom(node, instruction, generate_code, type, restrictions)) {
1600 return true;
1601 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001602 // Deal with vector restrictions.
Aart Bik304c8a52017-05-23 11:01:13 -07001603 HInstruction* opa = instruction->InputAt(0);
1604 HInstruction* opb = instruction->InputAt(1);
1605 HInstruction* r = opa;
1606 bool is_unsigned = false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001607 if ((HasVectorRestrictions(restrictions, kNoShift)) ||
1608 (instruction->IsShr() && HasVectorRestrictions(restrictions, kNoShr))) {
1609 return false; // unsupported instruction
Aart Bik304c8a52017-05-23 11:01:13 -07001610 } else if (HasVectorRestrictions(restrictions, kNoHiBits)) {
1611 // Shifts right need extra care to account for higher order bits.
1612 // TODO: less likely shr/unsigned and ushr/signed can by flipping signess.
1613 if (instruction->IsShr() &&
1614 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || is_unsigned)) {
1615 return false; // reject, unless all operands are sign-extension narrower
1616 } else if (instruction->IsUShr() &&
1617 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || !is_unsigned)) {
1618 return false; // reject, unless all operands are zero-extension narrower
1619 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001620 }
1621 // Accept shift operator for vectorizable/invariant operands.
1622 // TODO: accept symbolic, albeit loop invariant shift factors.
Aart Bik304c8a52017-05-23 11:01:13 -07001623 DCHECK(r != nullptr);
1624 if (generate_code && vector_mode_ != kVector) { // de-idiom
1625 r = opa;
1626 }
Aart Bik50e20d52017-05-05 14:07:29 -07001627 int64_t distance = 0;
Aart Bik304c8a52017-05-23 11:01:13 -07001628 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
Aart Bik50e20d52017-05-05 14:07:29 -07001629 IsInt64AndGet(opb, /*out*/ &distance)) {
Aart Bik65ffd8e2017-05-01 16:50:45 -07001630 // Restrict shift distance to packed data type width.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001631 int64_t max_distance = DataType::Size(type) * 8;
Aart Bik65ffd8e2017-05-01 16:50:45 -07001632 if (0 <= distance && distance < max_distance) {
1633 if (generate_code) {
Aart Bik304c8a52017-05-23 11:01:13 -07001634 GenerateVecOp(instruction, vector_map_->Get(r), opb, type);
Aart Bik65ffd8e2017-05-01 16:50:45 -07001635 }
1636 return true;
Aart Bikf8f5a162017-02-06 15:35:29 -08001637 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001638 }
Aart Bik3b2a5952018-03-05 13:55:28 -08001639 } else if (instruction->IsAbs()) {
1640 // Deal with vector restrictions.
1641 HInstruction* opa = instruction->InputAt(0);
1642 HInstruction* r = opa;
1643 bool is_unsigned = false;
1644 if (HasVectorRestrictions(restrictions, kNoAbs)) {
1645 return false;
1646 } else if (HasVectorRestrictions(restrictions, kNoHiBits) &&
1647 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || is_unsigned)) {
1648 return false; // reject, unless operand is sign-extension narrower
1649 }
1650 // Accept ABS(x) for vectorizable operand.
1651 DCHECK(r != nullptr);
1652 if (generate_code && vector_mode_ != kVector) { // de-idiom
1653 r = opa;
1654 }
1655 if (VectorizeUse(node, r, generate_code, type, restrictions)) {
1656 if (generate_code) {
1657 GenerateVecOp(instruction,
1658 vector_map_->Get(r),
1659 nullptr,
1660 HVecOperation::ToProperType(type, is_unsigned));
1661 }
1662 return true;
1663 }
Aart Bik281c6812016-08-26 11:31:48 -07001664 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08001665 return false;
Aart Bik281c6812016-08-26 11:31:48 -07001666}
1667
Aart Bik38a3f212017-10-20 17:02:21 -07001668uint32_t HLoopOptimization::GetVectorSizeInBytes() {
Artem Serovc8150b52019-07-31 18:28:00 +01001669 return simd_register_size_;
Aart Bik38a3f212017-10-20 17:02:21 -07001670}
1671
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001672bool HLoopOptimization::TrySetVectorType(DataType::Type type, uint64_t* restrictions) {
Vladimir Markoa0431112018-06-25 09:32:54 +01001673 const InstructionSetFeatures* features = compiler_options_->GetInstructionSetFeatures();
1674 switch (compiler_options_->GetInstructionSet()) {
Vladimir Marko33bff252017-11-01 14:35:42 +00001675 case InstructionSet::kArm:
1676 case InstructionSet::kThumb2:
Artem Serov8f7c4102017-06-21 11:21:37 +01001677 // Allow vectorization for all ARM devices, because Android assumes that
Aart Bikb29f6842017-07-28 15:58:41 -07001678 // ARM 32-bit always supports advanced SIMD (64-bit SIMD).
Artem Serov8f7c4102017-06-21 11:21:37 +01001679 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001680 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001681 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001682 case DataType::Type::kInt8:
Artem Serovaaac0e32018-08-07 00:52:22 +01001683 *restrictions |= kNoDiv | kNoReduction | kNoDotProd;
Artem Serovc8150b52019-07-31 18:28:00 +01001684 return TrySetVectorLength(type, 8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001685 case DataType::Type::kUint16:
1686 case DataType::Type::kInt16:
Artem Serovaaac0e32018-08-07 00:52:22 +01001687 *restrictions |= kNoDiv | kNoStringCharAt | kNoReduction | kNoDotProd;
Artem Serovc8150b52019-07-31 18:28:00 +01001688 return TrySetVectorLength(type, 4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001689 case DataType::Type::kInt32:
Artem Serov6e9b1372017-10-05 16:48:30 +01001690 *restrictions |= kNoDiv | kNoWideSAD;
Artem Serovc8150b52019-07-31 18:28:00 +01001691 return TrySetVectorLength(type, 2);
Artem Serov8f7c4102017-06-21 11:21:37 +01001692 default:
1693 break;
1694 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001695 return false;
Vladimir Marko33bff252017-11-01 14:35:42 +00001696 case InstructionSet::kArm64:
Artem Serov8ba4de12019-12-04 21:10:23 +00001697 if (IsInPredicatedVectorizationMode()) {
1698 // SVE vectorization.
1699 CHECK(features->AsArm64InstructionSetFeatures()->HasSVE());
Artem Serov55ab7e82020-04-27 21:02:28 +01001700 size_t vector_length = simd_register_size_ / DataType::Size(type);
1701 DCHECK_EQ(simd_register_size_ % DataType::Size(type), 0u);
Artem Serov8ba4de12019-12-04 21:10:23 +00001702 switch (type) {
1703 case DataType::Type::kBool:
1704 case DataType::Type::kUint8:
1705 case DataType::Type::kInt8:
1706 *restrictions |= kNoDiv |
1707 kNoSignedHAdd |
1708 kNoUnsignedHAdd |
1709 kNoUnroundedHAdd |
1710 kNoSAD;
Artem Serov55ab7e82020-04-27 21:02:28 +01001711 return TrySetVectorLength(type, vector_length);
Artem Serov8ba4de12019-12-04 21:10:23 +00001712 case DataType::Type::kUint16:
1713 case DataType::Type::kInt16:
1714 *restrictions |= kNoDiv |
1715 kNoSignedHAdd |
1716 kNoUnsignedHAdd |
1717 kNoUnroundedHAdd |
1718 kNoSAD |
1719 kNoDotProd;
Artem Serov55ab7e82020-04-27 21:02:28 +01001720 return TrySetVectorLength(type, vector_length);
Artem Serov8ba4de12019-12-04 21:10:23 +00001721 case DataType::Type::kInt32:
1722 *restrictions |= kNoDiv | kNoSAD;
Artem Serov55ab7e82020-04-27 21:02:28 +01001723 return TrySetVectorLength(type, vector_length);
Artem Serov8ba4de12019-12-04 21:10:23 +00001724 case DataType::Type::kInt64:
1725 *restrictions |= kNoDiv | kNoSAD;
Artem Serov55ab7e82020-04-27 21:02:28 +01001726 return TrySetVectorLength(type, vector_length);
Artem Serov8ba4de12019-12-04 21:10:23 +00001727 case DataType::Type::kFloat32:
1728 *restrictions |= kNoReduction;
Artem Serov55ab7e82020-04-27 21:02:28 +01001729 return TrySetVectorLength(type, vector_length);
Artem Serov8ba4de12019-12-04 21:10:23 +00001730 case DataType::Type::kFloat64:
1731 *restrictions |= kNoReduction;
Artem Serov55ab7e82020-04-27 21:02:28 +01001732 return TrySetVectorLength(type, vector_length);
Artem Serov8ba4de12019-12-04 21:10:23 +00001733 default:
1734 break;
1735 }
1736 return false;
1737 } else {
1738 // Allow vectorization for all ARM devices, because Android assumes that
1739 // ARMv8 AArch64 always supports advanced SIMD (128-bit SIMD).
1740 switch (type) {
1741 case DataType::Type::kBool:
1742 case DataType::Type::kUint8:
1743 case DataType::Type::kInt8:
1744 *restrictions |= kNoDiv;
1745 return TrySetVectorLength(type, 16);
1746 case DataType::Type::kUint16:
1747 case DataType::Type::kInt16:
1748 *restrictions |= kNoDiv;
1749 return TrySetVectorLength(type, 8);
1750 case DataType::Type::kInt32:
1751 *restrictions |= kNoDiv;
1752 return TrySetVectorLength(type, 4);
1753 case DataType::Type::kInt64:
1754 *restrictions |= kNoDiv | kNoMul;
1755 return TrySetVectorLength(type, 2);
1756 case DataType::Type::kFloat32:
1757 *restrictions |= kNoReduction;
1758 return TrySetVectorLength(type, 4);
1759 case DataType::Type::kFloat64:
1760 *restrictions |= kNoReduction;
1761 return TrySetVectorLength(type, 2);
1762 default:
1763 break;
1764 }
1765 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001766 }
Vladimir Marko33bff252017-11-01 14:35:42 +00001767 case InstructionSet::kX86:
1768 case InstructionSet::kX86_64:
Aart Bikb29f6842017-07-28 15:58:41 -07001769 // Allow vectorization for SSE4.1-enabled X86 devices only (128-bit SIMD).
Aart Bikf8f5a162017-02-06 15:35:29 -08001770 if (features->AsX86InstructionSetFeatures()->HasSSE4_1()) {
1771 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001772 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001773 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001774 case DataType::Type::kInt8:
Artem Serovaaac0e32018-08-07 00:52:22 +01001775 *restrictions |= kNoMul |
1776 kNoDiv |
1777 kNoShift |
1778 kNoAbs |
1779 kNoSignedHAdd |
1780 kNoUnroundedHAdd |
1781 kNoSAD |
1782 kNoDotProd;
Artem Serovc8150b52019-07-31 18:28:00 +01001783 return TrySetVectorLength(type, 16);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001784 case DataType::Type::kUint16:
Alex Light43f2f752019-12-04 17:48:45 +00001785 *restrictions |= kNoDiv |
1786 kNoAbs |
1787 kNoSignedHAdd |
1788 kNoUnroundedHAdd |
1789 kNoSAD |
1790 kNoDotProd;
Artem Serovc8150b52019-07-31 18:28:00 +01001791 return TrySetVectorLength(type, 8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001792 case DataType::Type::kInt16:
Artem Serovaaac0e32018-08-07 00:52:22 +01001793 *restrictions |= kNoDiv |
1794 kNoAbs |
1795 kNoSignedHAdd |
1796 kNoUnroundedHAdd |
Alex Light43f2f752019-12-04 17:48:45 +00001797 kNoSAD;
Artem Serovc8150b52019-07-31 18:28:00 +01001798 return TrySetVectorLength(type, 8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001799 case DataType::Type::kInt32:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001800 *restrictions |= kNoDiv | kNoSAD;
Artem Serovc8150b52019-07-31 18:28:00 +01001801 return TrySetVectorLength(type, 4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001802 case DataType::Type::kInt64:
Aart Bik3f08e9b2018-05-01 13:42:03 -07001803 *restrictions |= kNoMul | kNoDiv | kNoShr | kNoAbs | kNoSAD;
Artem Serovc8150b52019-07-31 18:28:00 +01001804 return TrySetVectorLength(type, 2);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001805 case DataType::Type::kFloat32:
Aart Bik3f08e9b2018-05-01 13:42:03 -07001806 *restrictions |= kNoReduction;
Artem Serovc8150b52019-07-31 18:28:00 +01001807 return TrySetVectorLength(type, 4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001808 case DataType::Type::kFloat64:
Aart Bik3f08e9b2018-05-01 13:42:03 -07001809 *restrictions |= kNoReduction;
Artem Serovc8150b52019-07-31 18:28:00 +01001810 return TrySetVectorLength(type, 2);
Aart Bikf8f5a162017-02-06 15:35:29 -08001811 default:
1812 break;
1813 } // switch type
1814 }
1815 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001816 default:
1817 return false;
1818 } // switch instruction set
1819}
1820
Artem Serovc8150b52019-07-31 18:28:00 +01001821bool HLoopOptimization::TrySetVectorLengthImpl(uint32_t length) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001822 DCHECK(IsPowerOfTwo(length) && length >= 2u);
1823 // First time set?
1824 if (vector_length_ == 0) {
1825 vector_length_ = length;
1826 }
1827 // Different types are acceptable within a loop-body, as long as all the corresponding vector
1828 // lengths match exactly to obtain a uniform traversal through the vector iteration space
1829 // (idiomatic exceptions to this rule can be handled by further unrolling sub-expressions).
1830 return vector_length_ == length;
1831}
1832
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001833void HLoopOptimization::GenerateVecInv(HInstruction* org, DataType::Type type) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001834 if (vector_map_->find(org) == vector_map_->end()) {
1835 // In scalar code, just use a self pass-through for scalar invariants
1836 // (viz. expression remains itself).
1837 if (vector_mode_ == kSequential) {
1838 vector_map_->Put(org, org);
1839 return;
1840 }
1841 // In vector code, explicit scalar expansion is needed.
Aart Bik0148de42017-09-05 09:25:01 -07001842 HInstruction* vector = nullptr;
1843 auto it = vector_permanent_map_->find(org);
1844 if (it != vector_permanent_map_->end()) {
1845 vector = it->second; // reuse during unrolling
1846 } else {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001847 // Generates ReplicateScalar( (optional_type_conv) org ).
1848 HInstruction* input = org;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001849 DataType::Type input_type = input->GetType();
1850 if (type != input_type && (type == DataType::Type::kInt64 ||
1851 input_type == DataType::Type::kInt64)) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001852 input = Insert(vector_preheader_,
1853 new (global_allocator_) HTypeConversion(type, input, kNoDexPc));
1854 }
1855 vector = new (global_allocator_)
Aart Bik46b6dbc2017-10-03 11:37:37 -07001856 HVecReplicateScalar(global_allocator_, input, type, vector_length_, kNoDexPc);
Aart Bik0148de42017-09-05 09:25:01 -07001857 vector_permanent_map_->Put(org, Insert(vector_preheader_, vector));
Artem Serov8ba4de12019-12-04 21:10:23 +00001858 if (IsInPredicatedVectorizationMode()) {
1859 HVecPredSetAll* set_pred = new (global_allocator_) HVecPredSetAll(global_allocator_,
1860 graph_->GetIntConstant(1),
1861 type,
1862 vector_length_,
1863 0u);
1864 vector_preheader_->InsertInstructionBefore(set_pred, vector);
1865 vector->AsVecOperation()->SetMergingGoverningPredicate(set_pred);
1866 }
Aart Bik0148de42017-09-05 09:25:01 -07001867 }
1868 vector_map_->Put(org, vector);
Aart Bikf8f5a162017-02-06 15:35:29 -08001869 }
1870}
1871
1872void HLoopOptimization::GenerateVecSub(HInstruction* org, HInstruction* offset) {
1873 if (vector_map_->find(org) == vector_map_->end()) {
Aart Bik14a68b42017-06-08 14:06:58 -07001874 HInstruction* subscript = vector_index_;
Aart Bik37dc4df2017-06-28 14:08:00 -07001875 int64_t value = 0;
1876 if (!IsInt64AndGet(offset, &value) || value != 0) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001877 subscript = new (global_allocator_) HAdd(DataType::Type::kInt32, subscript, offset);
Aart Bikf8f5a162017-02-06 15:35:29 -08001878 if (org->IsPhi()) {
1879 Insert(vector_body_, subscript); // lacks layout placeholder
1880 }
1881 }
1882 vector_map_->Put(org, subscript);
1883 }
1884}
1885
1886void HLoopOptimization::GenerateVecMem(HInstruction* org,
1887 HInstruction* opa,
1888 HInstruction* opb,
Aart Bik14a68b42017-06-08 14:06:58 -07001889 HInstruction* offset,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001890 DataType::Type type) {
Aart Bik46b6dbc2017-10-03 11:37:37 -07001891 uint32_t dex_pc = org->GetDexPc();
Aart Bikf8f5a162017-02-06 15:35:29 -08001892 HInstruction* vector = nullptr;
1893 if (vector_mode_ == kVector) {
1894 // Vector store or load.
Aart Bik38a3f212017-10-20 17:02:21 -07001895 bool is_string_char_at = false;
Aart Bik14a68b42017-06-08 14:06:58 -07001896 HInstruction* base = org->InputAt(0);
Aart Bikf8f5a162017-02-06 15:35:29 -08001897 if (opb != nullptr) {
1898 vector = new (global_allocator_) HVecStore(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001899 global_allocator_, base, opa, opb, type, org->GetSideEffects(), vector_length_, dex_pc);
Aart Bikf8f5a162017-02-06 15:35:29 -08001900 } else {
Aart Bik38a3f212017-10-20 17:02:21 -07001901 is_string_char_at = org->AsArrayGet()->IsStringCharAt();
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001902 vector = new (global_allocator_) HVecLoad(global_allocator_,
1903 base,
1904 opa,
1905 type,
1906 org->GetSideEffects(),
1907 vector_length_,
Aart Bik46b6dbc2017-10-03 11:37:37 -07001908 is_string_char_at,
1909 dex_pc);
Aart Bik14a68b42017-06-08 14:06:58 -07001910 }
Aart Bik38a3f212017-10-20 17:02:21 -07001911 // Known (forced/adjusted/original) alignment?
1912 if (vector_dynamic_peeling_candidate_ != nullptr) {
1913 if (vector_dynamic_peeling_candidate_->offset == offset && // TODO: diffs too?
1914 DataType::Size(vector_dynamic_peeling_candidate_->type) == DataType::Size(type) &&
1915 vector_dynamic_peeling_candidate_->is_string_char_at == is_string_char_at) {
1916 vector->AsVecMemoryOperation()->SetAlignment( // forced
1917 Alignment(GetVectorSizeInBytes(), 0));
1918 }
1919 } else {
1920 vector->AsVecMemoryOperation()->SetAlignment( // adjusted/original
1921 ComputeAlignment(offset, type, is_string_char_at, vector_static_peeling_factor_));
Aart Bikf8f5a162017-02-06 15:35:29 -08001922 }
1923 } else {
1924 // Scalar store or load.
1925 DCHECK(vector_mode_ == kSequential);
1926 if (opb != nullptr) {
Aart Bik4d1a9d42017-10-19 14:40:55 -07001927 DataType::Type component_type = org->AsArraySet()->GetComponentType();
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001928 vector = new (global_allocator_) HArraySet(
Aart Bik4d1a9d42017-10-19 14:40:55 -07001929 org->InputAt(0), opa, opb, component_type, org->GetSideEffects(), dex_pc);
Aart Bikf8f5a162017-02-06 15:35:29 -08001930 } else {
Aart Bikdb14fcf2017-04-25 15:53:58 -07001931 bool is_string_char_at = org->AsArrayGet()->IsStringCharAt();
1932 vector = new (global_allocator_) HArrayGet(
Aart Bik4d1a9d42017-10-19 14:40:55 -07001933 org->InputAt(0), opa, org->GetType(), org->GetSideEffects(), dex_pc, is_string_char_at);
Aart Bikf8f5a162017-02-06 15:35:29 -08001934 }
1935 }
1936 vector_map_->Put(org, vector);
1937}
1938
Aart Bik0148de42017-09-05 09:25:01 -07001939void HLoopOptimization::GenerateVecReductionPhi(HPhi* phi) {
1940 DCHECK(reductions_->find(phi) != reductions_->end());
1941 DCHECK(reductions_->Get(phi->InputAt(1)) == phi);
1942 HInstruction* vector = nullptr;
1943 if (vector_mode_ == kSequential) {
1944 HPhi* new_phi = new (global_allocator_) HPhi(
1945 global_allocator_, kNoRegNumber, 0, phi->GetType());
1946 vector_header_->AddPhi(new_phi);
1947 vector = new_phi;
1948 } else {
1949 // Link vector reduction back to prior unrolled update, or a first phi.
1950 auto it = vector_permanent_map_->find(phi);
1951 if (it != vector_permanent_map_->end()) {
1952 vector = it->second;
1953 } else {
1954 HPhi* new_phi = new (global_allocator_) HPhi(
1955 global_allocator_, kNoRegNumber, 0, HVecOperation::kSIMDType);
1956 vector_header_->AddPhi(new_phi);
1957 vector = new_phi;
1958 }
1959 }
1960 vector_map_->Put(phi, vector);
1961}
1962
1963void HLoopOptimization::GenerateVecReductionPhiInputs(HPhi* phi, HInstruction* reduction) {
1964 HInstruction* new_phi = vector_map_->Get(phi);
1965 HInstruction* new_init = reductions_->Get(phi);
1966 HInstruction* new_red = vector_map_->Get(reduction);
1967 // Link unrolled vector loop back to new phi.
1968 for (; !new_phi->IsPhi(); new_phi = vector_permanent_map_->Get(new_phi)) {
1969 DCHECK(new_phi->IsVecOperation());
1970 }
1971 // Prepare the new initialization.
1972 if (vector_mode_ == kVector) {
Goran Jakovljevic89b8df02017-10-13 08:33:17 +02001973 // Generate a [initial, 0, .., 0] vector for add or
1974 // a [initial, initial, .., initial] vector for min/max.
Aart Bikdbbac8f2017-09-01 13:06:08 -07001975 HVecOperation* red_vector = new_red->AsVecOperation();
Goran Jakovljevic89b8df02017-10-13 08:33:17 +02001976 HVecReduce::ReductionKind kind = GetReductionKind(red_vector);
Aart Bik38a3f212017-10-20 17:02:21 -07001977 uint32_t vector_length = red_vector->GetVectorLength();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001978 DataType::Type type = red_vector->GetPackedType();
Goran Jakovljevic89b8df02017-10-13 08:33:17 +02001979 if (kind == HVecReduce::ReductionKind::kSum) {
1980 new_init = Insert(vector_preheader_,
1981 new (global_allocator_) HVecSetScalars(global_allocator_,
1982 &new_init,
1983 type,
1984 vector_length,
1985 1,
1986 kNoDexPc));
1987 } else {
1988 new_init = Insert(vector_preheader_,
1989 new (global_allocator_) HVecReplicateScalar(global_allocator_,
1990 new_init,
1991 type,
1992 vector_length,
1993 kNoDexPc));
1994 }
Artem Serov8ba4de12019-12-04 21:10:23 +00001995 if (IsInPredicatedVectorizationMode()) {
1996 HVecPredSetAll* set_pred = new (global_allocator_) HVecPredSetAll(global_allocator_,
1997 graph_->GetIntConstant(1),
1998 type,
1999 vector_length,
2000 0u);
2001 vector_preheader_->InsertInstructionBefore(set_pred, new_init);
2002 new_init->AsVecOperation()->SetMergingGoverningPredicate(set_pred);
2003 }
Aart Bik0148de42017-09-05 09:25:01 -07002004 } else {
2005 new_init = ReduceAndExtractIfNeeded(new_init);
2006 }
2007 // Set the phi inputs.
2008 DCHECK(new_phi->IsPhi());
2009 new_phi->AsPhi()->AddInput(new_init);
2010 new_phi->AsPhi()->AddInput(new_red);
2011 // New feed value for next phi (safe mutation in iteration).
2012 reductions_->find(phi)->second = new_phi;
2013}
2014
2015HInstruction* HLoopOptimization::ReduceAndExtractIfNeeded(HInstruction* instruction) {
2016 if (instruction->IsPhi()) {
2017 HInstruction* input = instruction->InputAt(1);
Aart Bik2dd7b672017-12-07 11:11:22 -08002018 if (HVecOperation::ReturnsSIMDValue(input)) {
2019 DCHECK(!input->IsPhi());
Aart Bikdbbac8f2017-09-01 13:06:08 -07002020 HVecOperation* input_vector = input->AsVecOperation();
Aart Bik38a3f212017-10-20 17:02:21 -07002021 uint32_t vector_length = input_vector->GetVectorLength();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002022 DataType::Type type = input_vector->GetPackedType();
Aart Bikdbbac8f2017-09-01 13:06:08 -07002023 HVecReduce::ReductionKind kind = GetReductionKind(input_vector);
Aart Bik0148de42017-09-05 09:25:01 -07002024 HBasicBlock* exit = instruction->GetBlock()->GetSuccessors()[0];
2025 // Generate a vector reduction and scalar extract
2026 // x = REDUCE( [x_1, .., x_n] )
2027 // y = x_1
2028 // along the exit of the defining loop.
Aart Bik0148de42017-09-05 09:25:01 -07002029 HInstruction* reduce = new (global_allocator_) HVecReduce(
Aart Bik46b6dbc2017-10-03 11:37:37 -07002030 global_allocator_, instruction, type, vector_length, kind, kNoDexPc);
Aart Bik0148de42017-09-05 09:25:01 -07002031 exit->InsertInstructionBefore(reduce, exit->GetFirstInstruction());
2032 instruction = new (global_allocator_) HVecExtractScalar(
Aart Bik46b6dbc2017-10-03 11:37:37 -07002033 global_allocator_, reduce, type, vector_length, 0, kNoDexPc);
Aart Bik0148de42017-09-05 09:25:01 -07002034 exit->InsertInstructionAfter(instruction, reduce);
Artem Serov8ba4de12019-12-04 21:10:23 +00002035
2036 if (IsInPredicatedVectorizationMode()) {
2037 HVecPredSetAll* set_pred = new (global_allocator_) HVecPredSetAll(global_allocator_,
2038 graph_->GetIntConstant(1),
2039 type,
2040 vector_length,
2041 0u);
2042 exit->InsertInstructionBefore(set_pred, reduce);
2043 reduce->AsVecOperation()->SetMergingGoverningPredicate(set_pred);
2044 instruction->AsVecOperation()->SetMergingGoverningPredicate(set_pred);
2045 }
Aart Bik0148de42017-09-05 09:25:01 -07002046 }
2047 }
2048 return instruction;
2049}
2050
Aart Bikf8f5a162017-02-06 15:35:29 -08002051#define GENERATE_VEC(x, y) \
2052 if (vector_mode_ == kVector) { \
2053 vector = (x); \
2054 } else { \
2055 DCHECK(vector_mode_ == kSequential); \
2056 vector = (y); \
2057 } \
2058 break;
2059
2060void HLoopOptimization::GenerateVecOp(HInstruction* org,
2061 HInstruction* opa,
2062 HInstruction* opb,
Aart Bik3f08e9b2018-05-01 13:42:03 -07002063 DataType::Type type) {
Aart Bik46b6dbc2017-10-03 11:37:37 -07002064 uint32_t dex_pc = org->GetDexPc();
Aart Bikf8f5a162017-02-06 15:35:29 -08002065 HInstruction* vector = nullptr;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002066 DataType::Type org_type = org->GetType();
Aart Bikf8f5a162017-02-06 15:35:29 -08002067 switch (org->GetKind()) {
2068 case HInstruction::kNeg:
2069 DCHECK(opb == nullptr);
2070 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07002071 new (global_allocator_) HVecNeg(global_allocator_, opa, type, vector_length_, dex_pc),
2072 new (global_allocator_) HNeg(org_type, opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08002073 case HInstruction::kNot:
2074 DCHECK(opb == nullptr);
2075 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07002076 new (global_allocator_) HVecNot(global_allocator_, opa, type, vector_length_, dex_pc),
2077 new (global_allocator_) HNot(org_type, opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08002078 case HInstruction::kBooleanNot:
2079 DCHECK(opb == nullptr);
2080 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07002081 new (global_allocator_) HVecNot(global_allocator_, opa, type, vector_length_, dex_pc),
2082 new (global_allocator_) HBooleanNot(opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08002083 case HInstruction::kTypeConversion:
2084 DCHECK(opb == nullptr);
2085 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07002086 new (global_allocator_) HVecCnv(global_allocator_, opa, type, vector_length_, dex_pc),
2087 new (global_allocator_) HTypeConversion(org_type, opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08002088 case HInstruction::kAdd:
2089 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07002090 new (global_allocator_) HVecAdd(global_allocator_, opa, opb, type, vector_length_, dex_pc),
2091 new (global_allocator_) HAdd(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08002092 case HInstruction::kSub:
2093 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07002094 new (global_allocator_) HVecSub(global_allocator_, opa, opb, type, vector_length_, dex_pc),
2095 new (global_allocator_) HSub(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08002096 case HInstruction::kMul:
2097 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07002098 new (global_allocator_) HVecMul(global_allocator_, opa, opb, type, vector_length_, dex_pc),
2099 new (global_allocator_) HMul(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08002100 case HInstruction::kDiv:
2101 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07002102 new (global_allocator_) HVecDiv(global_allocator_, opa, opb, type, vector_length_, dex_pc),
2103 new (global_allocator_) HDiv(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08002104 case HInstruction::kAnd:
2105 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07002106 new (global_allocator_) HVecAnd(global_allocator_, opa, opb, type, vector_length_, dex_pc),
2107 new (global_allocator_) HAnd(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08002108 case HInstruction::kOr:
2109 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07002110 new (global_allocator_) HVecOr(global_allocator_, opa, opb, type, vector_length_, dex_pc),
2111 new (global_allocator_) HOr(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08002112 case HInstruction::kXor:
2113 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07002114 new (global_allocator_) HVecXor(global_allocator_, opa, opb, type, vector_length_, dex_pc),
2115 new (global_allocator_) HXor(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08002116 case HInstruction::kShl:
2117 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07002118 new (global_allocator_) HVecShl(global_allocator_, opa, opb, type, vector_length_, dex_pc),
2119 new (global_allocator_) HShl(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08002120 case HInstruction::kShr:
2121 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07002122 new (global_allocator_) HVecShr(global_allocator_, opa, opb, type, vector_length_, dex_pc),
2123 new (global_allocator_) HShr(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08002124 case HInstruction::kUShr:
2125 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07002126 new (global_allocator_) HVecUShr(global_allocator_, opa, opb, type, vector_length_, dex_pc),
2127 new (global_allocator_) HUShr(org_type, opa, opb, dex_pc));
Aart Bik3b2a5952018-03-05 13:55:28 -08002128 case HInstruction::kAbs:
2129 DCHECK(opb == nullptr);
2130 GENERATE_VEC(
2131 new (global_allocator_) HVecAbs(global_allocator_, opa, type, vector_length_, dex_pc),
2132 new (global_allocator_) HAbs(org_type, opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08002133 default:
2134 break;
2135 } // switch
2136 CHECK(vector != nullptr) << "Unsupported SIMD operator";
2137 vector_map_->Put(org, vector);
2138}
2139
2140#undef GENERATE_VEC
2141
2142//
Aart Bikf3e61ee2017-04-12 17:09:20 -07002143// Vectorization idioms.
2144//
2145
2146// Method recognizes the following idioms:
Aart Bikdbbac8f2017-09-01 13:06:08 -07002147// rounding halving add (a + b + 1) >> 1 for unsigned/signed operands a, b
2148// truncated halving add (a + b) >> 1 for unsigned/signed operands a, b
Aart Bikf3e61ee2017-04-12 17:09:20 -07002149// Provided that the operands are promoted to a wider form to do the arithmetic and
2150// then cast back to narrower form, the idioms can be mapped into efficient SIMD
2151// implementation that operates directly in narrower form (plus one extra bit).
2152// TODO: current version recognizes implicit byte/short/char widening only;
2153// explicit widening from int to long could be added later.
2154bool HLoopOptimization::VectorizeHalvingAddIdiom(LoopNode* node,
2155 HInstruction* instruction,
2156 bool generate_code,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002157 DataType::Type type,
Aart Bikf3e61ee2017-04-12 17:09:20 -07002158 uint64_t restrictions) {
2159 // Test for top level arithmetic shift right x >> 1 or logical shift right x >>> 1
Aart Bik304c8a52017-05-23 11:01:13 -07002160 // (note whether the sign bit in wider precision is shifted in has no effect
Aart Bikf3e61ee2017-04-12 17:09:20 -07002161 // on the narrow precision computed by the idiom).
Aart Bikf3e61ee2017-04-12 17:09:20 -07002162 if ((instruction->IsShr() ||
2163 instruction->IsUShr()) &&
Aart Bik0148de42017-09-05 09:25:01 -07002164 IsInt64Value(instruction->InputAt(1), 1)) {
Aart Bik5f805002017-05-16 16:42:41 -07002165 // Test for (a + b + c) >> 1 for optional constant c.
2166 HInstruction* a = nullptr;
2167 HInstruction* b = nullptr;
2168 int64_t c = 0;
Nicolas Geoffraya3e23262018-03-28 11:15:12 +00002169 if (IsAddConst2(graph_, instruction->InputAt(0), /*out*/ &a, /*out*/ &b, /*out*/ &c)) {
Aart Bik5f805002017-05-16 16:42:41 -07002170 // Accept c == 1 (rounded) or c == 0 (not rounded).
2171 bool is_rounded = false;
2172 if (c == 1) {
2173 is_rounded = true;
2174 } else if (c != 0) {
2175 return false;
2176 }
2177 // Accept consistent zero or sign extension on operands a and b.
Aart Bikf3e61ee2017-04-12 17:09:20 -07002178 HInstruction* r = nullptr;
2179 HInstruction* s = nullptr;
2180 bool is_unsigned = false;
Aart Bik304c8a52017-05-23 11:01:13 -07002181 if (!IsNarrowerOperands(a, b, type, &r, &s, &is_unsigned)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -07002182 return false;
2183 }
2184 // Deal with vector restrictions.
Artem Serov8ba4de12019-12-04 21:10:23 +00002185 if ((is_unsigned && HasVectorRestrictions(restrictions, kNoUnsignedHAdd)) ||
2186 (!is_unsigned && HasVectorRestrictions(restrictions, kNoSignedHAdd)) ||
Aart Bikf3e61ee2017-04-12 17:09:20 -07002187 (!is_rounded && HasVectorRestrictions(restrictions, kNoUnroundedHAdd))) {
2188 return false;
2189 }
2190 // Accept recognized halving add for vectorizable operands. Vectorized code uses the
2191 // shorthand idiomatic operation. Sequential code uses the original scalar expressions.
Nicolas Geoffraya3e23262018-03-28 11:15:12 +00002192 DCHECK(r != nullptr && s != nullptr);
Aart Bik304c8a52017-05-23 11:01:13 -07002193 if (generate_code && vector_mode_ != kVector) { // de-idiom
2194 r = instruction->InputAt(0);
2195 s = instruction->InputAt(1);
2196 }
Aart Bikf3e61ee2017-04-12 17:09:20 -07002197 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
2198 VectorizeUse(node, s, generate_code, type, restrictions)) {
2199 if (generate_code) {
2200 if (vector_mode_ == kVector) {
2201 vector_map_->Put(instruction, new (global_allocator_) HVecHalvingAdd(
2202 global_allocator_,
2203 vector_map_->Get(r),
2204 vector_map_->Get(s),
Aart Bik66c158e2018-01-31 12:55:04 -08002205 HVecOperation::ToProperType(type, is_unsigned),
Aart Bikf3e61ee2017-04-12 17:09:20 -07002206 vector_length_,
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01002207 is_rounded,
Aart Bik46b6dbc2017-10-03 11:37:37 -07002208 kNoDexPc));
Aart Bik21b85922017-09-06 13:29:16 -07002209 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorizedIdiom);
Aart Bikf3e61ee2017-04-12 17:09:20 -07002210 } else {
Aart Bik304c8a52017-05-23 11:01:13 -07002211 GenerateVecOp(instruction, vector_map_->Get(r), vector_map_->Get(s), type);
Aart Bikf3e61ee2017-04-12 17:09:20 -07002212 }
2213 }
2214 return true;
2215 }
2216 }
2217 }
2218 return false;
2219}
2220
Aart Bikdbbac8f2017-09-01 13:06:08 -07002221// Method recognizes the following idiom:
2222// q += ABS(a - b) for signed operands a, b
2223// Provided that the operands have the same type or are promoted to a wider form.
2224// Since this may involve a vector length change, the idiom is handled by going directly
2225// to a sad-accumulate node (rather than relying combining finer grained nodes later).
2226// TODO: unsigned SAD too?
2227bool HLoopOptimization::VectorizeSADIdiom(LoopNode* node,
2228 HInstruction* instruction,
2229 bool generate_code,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002230 DataType::Type reduction_type,
Aart Bikdbbac8f2017-09-01 13:06:08 -07002231 uint64_t restrictions) {
2232 // Filter integral "q += ABS(a - b);" reduction, where ABS and SUB
2233 // are done in the same precision (either int or long).
2234 if (!instruction->IsAdd() ||
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002235 (reduction_type != DataType::Type::kInt32 && reduction_type != DataType::Type::kInt64)) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07002236 return false;
2237 }
Artem Serove521eb02020-02-27 18:51:24 +00002238 HInstruction* acc = instruction->InputAt(0);
2239 HInstruction* abs = instruction->InputAt(1);
Aart Bikdbbac8f2017-09-01 13:06:08 -07002240 HInstruction* a = nullptr;
2241 HInstruction* b = nullptr;
Artem Serove521eb02020-02-27 18:51:24 +00002242 if (abs->IsAbs() &&
2243 abs->GetType() == reduction_type &&
2244 IsSubConst2(graph_, abs->InputAt(0), /*out*/ &a, /*out*/ &b)) {
Nicolas Geoffraya3e23262018-03-28 11:15:12 +00002245 DCHECK(a != nullptr && b != nullptr);
2246 } else {
Aart Bikdbbac8f2017-09-01 13:06:08 -07002247 return false;
2248 }
2249 // Accept same-type or consistent sign extension for narrower-type on operands a and b.
2250 // The same-type or narrower operands are called r (a or lower) and s (b or lower).
Aart Bikdf011c32017-09-28 12:53:04 -07002251 // We inspect the operands carefully to pick the most suited type.
Aart Bikdbbac8f2017-09-01 13:06:08 -07002252 HInstruction* r = a;
2253 HInstruction* s = b;
2254 bool is_unsigned = false;
Artem Serovaaac0e32018-08-07 00:52:22 +01002255 DataType::Type sub_type = GetNarrowerType(a, b);
Aart Bikdbbac8f2017-09-01 13:06:08 -07002256 if (reduction_type != sub_type &&
2257 (!IsNarrowerOperands(a, b, sub_type, &r, &s, &is_unsigned) || is_unsigned)) {
2258 return false;
2259 }
2260 // Try same/narrower type and deal with vector restrictions.
Artem Serov6e9b1372017-10-05 16:48:30 +01002261 if (!TrySetVectorType(sub_type, &restrictions) ||
2262 HasVectorRestrictions(restrictions, kNoSAD) ||
2263 (reduction_type != sub_type && HasVectorRestrictions(restrictions, kNoWideSAD))) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07002264 return false;
2265 }
2266 // Accept SAD idiom for vectorizable operands. Vectorized code uses the shorthand
2267 // idiomatic operation. Sequential code uses the original scalar expressions.
Nicolas Geoffraya3e23262018-03-28 11:15:12 +00002268 DCHECK(r != nullptr && s != nullptr);
Aart Bikdbbac8f2017-09-01 13:06:08 -07002269 if (generate_code && vector_mode_ != kVector) { // de-idiom
Artem Serove521eb02020-02-27 18:51:24 +00002270 r = s = abs->InputAt(0);
Aart Bikdbbac8f2017-09-01 13:06:08 -07002271 }
Artem Serove521eb02020-02-27 18:51:24 +00002272 if (VectorizeUse(node, acc, generate_code, sub_type, restrictions) &&
Aart Bikdbbac8f2017-09-01 13:06:08 -07002273 VectorizeUse(node, r, generate_code, sub_type, restrictions) &&
2274 VectorizeUse(node, s, generate_code, sub_type, restrictions)) {
2275 if (generate_code) {
2276 if (vector_mode_ == kVector) {
2277 vector_map_->Put(instruction, new (global_allocator_) HVecSADAccumulate(
2278 global_allocator_,
Artem Serove521eb02020-02-27 18:51:24 +00002279 vector_map_->Get(acc),
Aart Bikdbbac8f2017-09-01 13:06:08 -07002280 vector_map_->Get(r),
2281 vector_map_->Get(s),
Aart Bik3b2a5952018-03-05 13:55:28 -08002282 HVecOperation::ToProperType(reduction_type, is_unsigned),
Aart Bik46b6dbc2017-10-03 11:37:37 -07002283 GetOtherVL(reduction_type, sub_type, vector_length_),
2284 kNoDexPc));
Aart Bikdbbac8f2017-09-01 13:06:08 -07002285 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorizedIdiom);
2286 } else {
Artem Serove521eb02020-02-27 18:51:24 +00002287 // "GenerateVecOp()" must not be called more than once for each original loop body
2288 // instruction. As the SAD idiom processes both "current" instruction ("instruction")
2289 // and its ABS input in one go, we must check that for the scalar case the ABS instruction
2290 // has not yet been processed.
2291 if (vector_map_->find(abs) == vector_map_->end()) {
2292 GenerateVecOp(abs, vector_map_->Get(r), nullptr, reduction_type);
2293 }
2294 GenerateVecOp(instruction, vector_map_->Get(acc), vector_map_->Get(abs), reduction_type);
Aart Bikdbbac8f2017-09-01 13:06:08 -07002295 }
2296 }
2297 return true;
2298 }
2299 return false;
2300}
2301
Artem Serovaaac0e32018-08-07 00:52:22 +01002302// Method recognises the following dot product idiom:
2303// q += a * b for operands a, b whose type is narrower than the reduction one.
2304// Provided that the operands have the same type or are promoted to a wider form.
2305// Since this may involve a vector length change, the idiom is handled by going directly
2306// to a dot product node (rather than relying combining finer grained nodes later).
2307bool HLoopOptimization::VectorizeDotProdIdiom(LoopNode* node,
2308 HInstruction* instruction,
2309 bool generate_code,
2310 DataType::Type reduction_type,
2311 uint64_t restrictions) {
Alex Light43f2f752019-12-04 17:48:45 +00002312 if (!instruction->IsAdd() || reduction_type != DataType::Type::kInt32) {
Artem Serovaaac0e32018-08-07 00:52:22 +01002313 return false;
2314 }
2315
Artem Serove521eb02020-02-27 18:51:24 +00002316 HInstruction* const acc = instruction->InputAt(0);
2317 HInstruction* const mul = instruction->InputAt(1);
2318 if (!mul->IsMul() || mul->GetType() != reduction_type) {
Artem Serovaaac0e32018-08-07 00:52:22 +01002319 return false;
2320 }
2321
Artem Serove521eb02020-02-27 18:51:24 +00002322 HInstruction* const mul_left = mul->InputAt(0);
2323 HInstruction* const mul_right = mul->InputAt(1);
2324 HInstruction* r = mul_left;
2325 HInstruction* s = mul_right;
2326 DataType::Type op_type = GetNarrowerType(mul_left, mul_right);
Artem Serovaaac0e32018-08-07 00:52:22 +01002327 bool is_unsigned = false;
2328
Artem Serove521eb02020-02-27 18:51:24 +00002329 if (!IsNarrowerOperands(mul_left, mul_right, op_type, &r, &s, &is_unsigned)) {
Artem Serovaaac0e32018-08-07 00:52:22 +01002330 return false;
2331 }
2332 op_type = HVecOperation::ToProperType(op_type, is_unsigned);
2333
2334 if (!TrySetVectorType(op_type, &restrictions) ||
2335 HasVectorRestrictions(restrictions, kNoDotProd)) {
2336 return false;
2337 }
2338
2339 DCHECK(r != nullptr && s != nullptr);
2340 // Accept dot product idiom for vectorizable operands. Vectorized code uses the shorthand
2341 // idiomatic operation. Sequential code uses the original scalar expressions.
2342 if (generate_code && vector_mode_ != kVector) { // de-idiom
Artem Serove521eb02020-02-27 18:51:24 +00002343 r = mul_left;
2344 s = mul_right;
Artem Serovaaac0e32018-08-07 00:52:22 +01002345 }
Artem Serove521eb02020-02-27 18:51:24 +00002346 if (VectorizeUse(node, acc, generate_code, op_type, restrictions) &&
Artem Serovaaac0e32018-08-07 00:52:22 +01002347 VectorizeUse(node, r, generate_code, op_type, restrictions) &&
2348 VectorizeUse(node, s, generate_code, op_type, restrictions)) {
2349 if (generate_code) {
2350 if (vector_mode_ == kVector) {
2351 vector_map_->Put(instruction, new (global_allocator_) HVecDotProd(
2352 global_allocator_,
Artem Serove521eb02020-02-27 18:51:24 +00002353 vector_map_->Get(acc),
Artem Serovaaac0e32018-08-07 00:52:22 +01002354 vector_map_->Get(r),
2355 vector_map_->Get(s),
2356 reduction_type,
2357 is_unsigned,
2358 GetOtherVL(reduction_type, op_type, vector_length_),
2359 kNoDexPc));
2360 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorizedIdiom);
2361 } else {
Artem Serove521eb02020-02-27 18:51:24 +00002362 // "GenerateVecOp()" must not be called more than once for each original loop body
2363 // instruction. As the DotProd idiom processes both "current" instruction ("instruction")
2364 // and its MUL input in one go, we must check that for the scalar case the MUL instruction
2365 // has not yet been processed.
2366 if (vector_map_->find(mul) == vector_map_->end()) {
2367 GenerateVecOp(mul, vector_map_->Get(r), vector_map_->Get(s), reduction_type);
2368 }
2369 GenerateVecOp(instruction, vector_map_->Get(acc), vector_map_->Get(mul), reduction_type);
Artem Serovaaac0e32018-08-07 00:52:22 +01002370 }
2371 }
2372 return true;
2373 }
2374 return false;
2375}
2376
Aart Bikf3e61ee2017-04-12 17:09:20 -07002377//
Aart Bik14a68b42017-06-08 14:06:58 -07002378// Vectorization heuristics.
2379//
2380
Aart Bik38a3f212017-10-20 17:02:21 -07002381Alignment HLoopOptimization::ComputeAlignment(HInstruction* offset,
2382 DataType::Type type,
2383 bool is_string_char_at,
2384 uint32_t peeling) {
2385 // Combine the alignment and hidden offset that is guaranteed by
2386 // the Android runtime with a known starting index adjusted as bytes.
2387 int64_t value = 0;
2388 if (IsInt64AndGet(offset, /*out*/ &value)) {
2389 uint32_t start_offset =
2390 HiddenOffset(type, is_string_char_at) + (value + peeling) * DataType::Size(type);
2391 return Alignment(BaseAlignment(), start_offset & (BaseAlignment() - 1u));
2392 }
2393 // Otherwise, the Android runtime guarantees at least natural alignment.
2394 return Alignment(DataType::Size(type), 0);
2395}
2396
Artem Serov55ab7e82020-04-27 21:02:28 +01002397void HLoopOptimization::SetAlignmentStrategy(const ScopedArenaVector<uint32_t>& peeling_votes,
Aart Bik38a3f212017-10-20 17:02:21 -07002398 const ArrayReference* peeling_candidate) {
2399 // Current heuristic: pick the best static loop peeling factor, if any,
2400 // or otherwise use dynamic loop peeling on suggested peeling candidate.
2401 uint32_t max_vote = 0;
Artem Serov55ab7e82020-04-27 21:02:28 +01002402 for (size_t i = 0; i < peeling_votes.size(); i++) {
Aart Bik38a3f212017-10-20 17:02:21 -07002403 if (peeling_votes[i] > max_vote) {
2404 max_vote = peeling_votes[i];
2405 vector_static_peeling_factor_ = i;
2406 }
2407 }
2408 if (max_vote == 0) {
2409 vector_dynamic_peeling_candidate_ = peeling_candidate;
2410 }
2411}
2412
2413uint32_t HLoopOptimization::MaxNumberPeeled() {
2414 if (vector_dynamic_peeling_candidate_ != nullptr) {
2415 return vector_length_ - 1u; // worst-case
2416 }
2417 return vector_static_peeling_factor_; // known exactly
2418}
2419
Aart Bik14a68b42017-06-08 14:06:58 -07002420bool HLoopOptimization::IsVectorizationProfitable(int64_t trip_count) {
Aart Bik38a3f212017-10-20 17:02:21 -07002421 // Current heuristic: non-empty body with sufficient number of iterations (if known).
Aart Bik14a68b42017-06-08 14:06:58 -07002422 // TODO: refine by looking at e.g. operation count, alignment, etc.
Aart Bik38a3f212017-10-20 17:02:21 -07002423 // TODO: trip count is really unsigned entity, provided the guarding test
2424 // is satisfied; deal with this more carefully later
2425 uint32_t max_peel = MaxNumberPeeled();
Aart Bik14a68b42017-06-08 14:06:58 -07002426 if (vector_length_ == 0) {
2427 return false; // nothing found
Aart Bik38a3f212017-10-20 17:02:21 -07002428 } else if (trip_count < 0) {
2429 return false; // guard against non-taken/large
2430 } else if ((0 < trip_count) && (trip_count < (vector_length_ + max_peel))) {
Aart Bik14a68b42017-06-08 14:06:58 -07002431 return false; // insufficient iterations
2432 }
2433 return true;
2434}
2435
Aart Bik14a68b42017-06-08 14:06:58 -07002436//
Aart Bikf8f5a162017-02-06 15:35:29 -08002437// Helpers.
2438//
2439
2440bool HLoopOptimization::TrySetPhiInduction(HPhi* phi, bool restrict_uses) {
Aart Bikb29f6842017-07-28 15:58:41 -07002441 // Start with empty phi induction.
2442 iset_->clear();
2443
Nicolas Geoffrayf57c1ae2017-06-28 17:40:18 +01002444 // Special case Phis that have equivalent in a debuggable setup. Our graph checker isn't
2445 // smart enough to follow strongly connected components (and it's probably not worth
2446 // it to make it so). See b/33775412.
2447 if (graph_->IsDebuggable() && phi->HasEquivalentPhi()) {
2448 return false;
2449 }
Aart Bikb29f6842017-07-28 15:58:41 -07002450
2451 // Lookup phi induction cycle.
Aart Bikcc42be02016-10-20 16:14:16 -07002452 ArenaSet<HInstruction*>* set = induction_range_.LookupCycle(phi);
2453 if (set != nullptr) {
2454 for (HInstruction* i : *set) {
Aart Bike3dedc52016-11-02 17:50:27 -07002455 // Check that, other than instructions that are no longer in the graph (removed earlier)
Aart Bikf8f5a162017-02-06 15:35:29 -08002456 // each instruction is removable and, when restrict uses are requested, other than for phi,
2457 // all uses are contained within the cycle.
Aart Bike3dedc52016-11-02 17:50:27 -07002458 if (!i->IsInBlock()) {
2459 continue;
2460 } else if (!i->IsRemovable()) {
2461 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08002462 } else if (i != phi && restrict_uses) {
Aart Bikb29f6842017-07-28 15:58:41 -07002463 // Deal with regular uses.
Aart Bikcc42be02016-10-20 16:14:16 -07002464 for (const HUseListNode<HInstruction*>& use : i->GetUses()) {
2465 if (set->find(use.GetUser()) == set->end()) {
2466 return false;
2467 }
2468 }
2469 }
Aart Bike3dedc52016-11-02 17:50:27 -07002470 iset_->insert(i); // copy
Aart Bikcc42be02016-10-20 16:14:16 -07002471 }
Aart Bikcc42be02016-10-20 16:14:16 -07002472 return true;
2473 }
2474 return false;
2475}
2476
Aart Bikb29f6842017-07-28 15:58:41 -07002477bool HLoopOptimization::TrySetPhiReduction(HPhi* phi) {
Vladimir Markode4d1952022-03-07 09:29:40 +00002478 DCHECK(phi->IsLoopHeaderPhi());
Aart Bikb29f6842017-07-28 15:58:41 -07002479 // Only unclassified phi cycles are candidates for reductions.
2480 if (induction_range_.IsClassified(phi)) {
2481 return false;
2482 }
2483 // Accept operations like x = x + .., provided that the phi and the reduction are
2484 // used exactly once inside the loop, and by each other.
2485 HInputsRef inputs = phi->GetInputs();
2486 if (inputs.size() == 2) {
2487 HInstruction* reduction = inputs[1];
2488 if (HasReductionFormat(reduction, phi)) {
2489 HLoopInformation* loop_info = phi->GetBlock()->GetLoopInformation();
Vladimir Markode4d1952022-03-07 09:29:40 +00002490 DCHECK(loop_info->Contains(*reduction->GetBlock()));
2491 const bool single_use_inside_loop =
Aart Bikb29f6842017-07-28 15:58:41 -07002492 // Reduction update only used by phi.
2493 reduction->GetUses().HasExactlyOneElement() &&
2494 !reduction->HasEnvironmentUses() &&
2495 // Reduction update is only use of phi inside the loop.
Vladimir Markode4d1952022-03-07 09:29:40 +00002496 std::none_of(phi->GetUses().begin(),
2497 phi->GetUses().end(),
2498 [loop_info, reduction](const HUseListNode<HInstruction*>& use) {
2499 HInstruction* user = use.GetUser();
2500 return user != reduction && loop_info->Contains(*user->GetBlock());
2501 });
Aart Bikb29f6842017-07-28 15:58:41 -07002502 if (single_use_inside_loop) {
2503 // Link reduction back, and start recording feed value.
2504 reductions_->Put(reduction, phi);
2505 reductions_->Put(phi, phi->InputAt(0));
2506 return true;
2507 }
2508 }
2509 }
2510 return false;
2511}
2512
2513bool HLoopOptimization::TrySetSimpleLoopHeader(HBasicBlock* block, /*out*/ HPhi** main_phi) {
2514 // Start with empty phi induction and reductions.
2515 iset_->clear();
2516 reductions_->clear();
2517
2518 // Scan the phis to find the following (the induction structure has already
2519 // been optimized, so we don't need to worry about trivial cases):
2520 // (1) optional reductions in loop,
2521 // (2) the main induction, used in loop control.
2522 HPhi* phi = nullptr;
2523 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
2524 if (TrySetPhiReduction(it.Current()->AsPhi())) {
2525 continue;
2526 } else if (phi == nullptr) {
2527 // Found the first candidate for main induction.
2528 phi = it.Current()->AsPhi();
2529 } else {
2530 return false;
2531 }
2532 }
2533
2534 // Then test for a typical loopheader:
2535 // s: SuspendCheck
2536 // c: Condition(phi, bound)
2537 // i: If(c)
2538 if (phi != nullptr && TrySetPhiInduction(phi, /*restrict_uses*/ false)) {
Aart Bikcc42be02016-10-20 16:14:16 -07002539 HInstruction* s = block->GetFirstInstruction();
2540 if (s != nullptr && s->IsSuspendCheck()) {
2541 HInstruction* c = s->GetNext();
Aart Bikd86c0852017-04-14 12:00:15 -07002542 if (c != nullptr &&
2543 c->IsCondition() &&
2544 c->GetUses().HasExactlyOneElement() && // only used for termination
2545 !c->HasEnvironmentUses()) { // unlikely, but not impossible
Aart Bikcc42be02016-10-20 16:14:16 -07002546 HInstruction* i = c->GetNext();
2547 if (i != nullptr && i->IsIf() && i->InputAt(0) == c) {
2548 iset_->insert(c);
2549 iset_->insert(s);
Aart Bikb29f6842017-07-28 15:58:41 -07002550 *main_phi = phi;
Aart Bikcc42be02016-10-20 16:14:16 -07002551 return true;
2552 }
2553 }
2554 }
2555 }
2556 return false;
2557}
2558
2559bool HLoopOptimization::IsEmptyBody(HBasicBlock* block) {
Aart Bikf8f5a162017-02-06 15:35:29 -08002560 if (!block->GetPhis().IsEmpty()) {
2561 return false;
2562 }
2563 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
2564 HInstruction* instruction = it.Current();
2565 if (!instruction->IsGoto() && iset_->find(instruction) == iset_->end()) {
2566 return false;
Aart Bikcc42be02016-10-20 16:14:16 -07002567 }
Aart Bikf8f5a162017-02-06 15:35:29 -08002568 }
2569 return true;
2570}
2571
2572bool HLoopOptimization::IsUsedOutsideLoop(HLoopInformation* loop_info,
2573 HInstruction* instruction) {
Aart Bikb29f6842017-07-28 15:58:41 -07002574 // Deal with regular uses.
Aart Bikf8f5a162017-02-06 15:35:29 -08002575 for (const HUseListNode<HInstruction*>& use : instruction->GetUses()) {
2576 if (use.GetUser()->GetBlock()->GetLoopInformation() != loop_info) {
2577 return true;
2578 }
Aart Bikcc42be02016-10-20 16:14:16 -07002579 }
2580 return false;
2581}
2582
Aart Bik482095d2016-10-10 15:39:10 -07002583bool HLoopOptimization::IsOnlyUsedAfterLoop(HLoopInformation* loop_info,
Aart Bik8c4a8542016-10-06 11:36:57 -07002584 HInstruction* instruction,
Aart Bik6b69e0a2017-01-11 10:20:43 -08002585 bool collect_loop_uses,
Aart Bik38a3f212017-10-20 17:02:21 -07002586 /*out*/ uint32_t* use_count) {
Aart Bikb29f6842017-07-28 15:58:41 -07002587 // Deal with regular uses.
Aart Bik8c4a8542016-10-06 11:36:57 -07002588 for (const HUseListNode<HInstruction*>& use : instruction->GetUses()) {
2589 HInstruction* user = use.GetUser();
2590 if (iset_->find(user) == iset_->end()) { // not excluded?
Vladimir Markode4d1952022-03-07 09:29:40 +00002591 if (loop_info->Contains(*user->GetBlock())) {
Aart Bik6b69e0a2017-01-11 10:20:43 -08002592 // If collect_loop_uses is set, simply keep adding those uses to the set.
2593 // Otherwise, reject uses inside the loop that were not already in the set.
2594 if (collect_loop_uses) {
2595 iset_->insert(user);
2596 continue;
2597 }
Aart Bik8c4a8542016-10-06 11:36:57 -07002598 return false;
2599 }
2600 ++*use_count;
2601 }
2602 }
2603 return true;
2604}
2605
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002606bool HLoopOptimization::TryReplaceWithLastValue(HLoopInformation* loop_info,
2607 HInstruction* instruction,
2608 HBasicBlock* block) {
2609 // Try to replace outside uses with the last value.
Aart Bik807868e2016-11-03 17:51:43 -07002610 if (induction_range_.CanGenerateLastValue(instruction)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -08002611 HInstruction* replacement = induction_range_.GenerateLastValue(instruction, graph_, block);
Aart Bikb29f6842017-07-28 15:58:41 -07002612 // Deal with regular uses.
Aart Bik6b69e0a2017-01-11 10:20:43 -08002613 const HUseList<HInstruction*>& uses = instruction->GetUses();
2614 for (auto it = uses.begin(), end = uses.end(); it != end;) {
2615 HInstruction* user = it->GetUser();
2616 size_t index = it->GetIndex();
2617 ++it; // increment before replacing
2618 if (iset_->find(user) == iset_->end()) { // not excluded?
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002619 if (kIsDebugBuild) {
2620 // We have checked earlier in 'IsOnlyUsedAfterLoop' that the use is after the loop.
2621 HLoopInformation* other_loop_info = user->GetBlock()->GetLoopInformation();
2622 CHECK(other_loop_info == nullptr || !other_loop_info->IsIn(*loop_info));
2623 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08002624 user->ReplaceInput(replacement, index);
2625 induction_range_.Replace(user, instruction, replacement); // update induction
2626 }
2627 }
Aart Bikb29f6842017-07-28 15:58:41 -07002628 // Deal with environment uses.
Aart Bik6b69e0a2017-01-11 10:20:43 -08002629 const HUseList<HEnvironment*>& env_uses = instruction->GetEnvUses();
2630 for (auto it = env_uses.begin(), end = env_uses.end(); it != end;) {
2631 HEnvironment* user = it->GetUser();
2632 size_t index = it->GetIndex();
2633 ++it; // increment before replacing
2634 if (iset_->find(user->GetHolder()) == iset_->end()) { // not excluded?
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002635 // Only update environment uses after the loop.
Aart Bik14a68b42017-06-08 14:06:58 -07002636 HLoopInformation* other_loop_info = user->GetHolder()->GetBlock()->GetLoopInformation();
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002637 if (other_loop_info == nullptr || !other_loop_info->IsIn(*loop_info)) {
2638 user->RemoveAsUserOfInput(index);
2639 user->SetRawEnvAt(index, replacement);
2640 replacement->AddEnvUseAt(user, index);
2641 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08002642 }
2643 }
Aart Bik807868e2016-11-03 17:51:43 -07002644 return true;
Aart Bik8c4a8542016-10-06 11:36:57 -07002645 }
Aart Bik807868e2016-11-03 17:51:43 -07002646 return false;
Aart Bik8c4a8542016-10-06 11:36:57 -07002647}
2648
Aart Bikf8f5a162017-02-06 15:35:29 -08002649bool HLoopOptimization::TryAssignLastValue(HLoopInformation* loop_info,
2650 HInstruction* instruction,
2651 HBasicBlock* block,
2652 bool collect_loop_uses) {
2653 // Assigning the last value is always successful if there are no uses.
2654 // Otherwise, it succeeds in a no early-exit loop by generating the
2655 // proper last value assignment.
Aart Bik38a3f212017-10-20 17:02:21 -07002656 uint32_t use_count = 0;
Aart Bikf8f5a162017-02-06 15:35:29 -08002657 return IsOnlyUsedAfterLoop(loop_info, instruction, collect_loop_uses, &use_count) &&
2658 (use_count == 0 ||
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002659 (!IsEarlyExit(loop_info) && TryReplaceWithLastValue(loop_info, instruction, block)));
Aart Bikf8f5a162017-02-06 15:35:29 -08002660}
2661
Aart Bik6b69e0a2017-01-11 10:20:43 -08002662void HLoopOptimization::RemoveDeadInstructions(const HInstructionList& list) {
2663 for (HBackwardInstructionIterator i(list); !i.Done(); i.Advance()) {
2664 HInstruction* instruction = i.Current();
2665 if (instruction->IsDeadAndRemovable()) {
2666 simplified_ = true;
2667 instruction->GetBlock()->RemoveInstructionOrPhi(instruction);
2668 }
2669 }
2670}
2671
Aart Bik14a68b42017-06-08 14:06:58 -07002672bool HLoopOptimization::CanRemoveCycle() {
2673 for (HInstruction* i : *iset_) {
2674 // We can never remove instructions that have environment
2675 // uses when we compile 'debuggable'.
2676 if (i->HasEnvironmentUses() && graph_->IsDebuggable()) {
2677 return false;
2678 }
2679 // A deoptimization should never have an environment input removed.
2680 for (const HUseListNode<HEnvironment*>& use : i->GetEnvUses()) {
2681 if (use.GetUser()->GetHolder()->IsDeoptimize()) {
2682 return false;
2683 }
2684 }
2685 }
2686 return true;
2687}
2688
Aart Bik281c6812016-08-26 11:31:48 -07002689} // namespace art