blob: 567a41e2fdc34239a1adf45562527bb000be500d [file] [log] [blame]
Aart Bik281c6812016-08-26 11:31:48 -07001/*
2 * Copyright (C) 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "loop_optimization.h"
18
Aart Bikf8f5a162017-02-06 15:35:29 -080019#include "arch/arm/instruction_set_features_arm.h"
20#include "arch/arm64/instruction_set_features_arm64.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070021#include "arch/instruction_set.h"
Aart Bikf8f5a162017-02-06 15:35:29 -080022#include "arch/mips/instruction_set_features_mips.h"
23#include "arch/mips64/instruction_set_features_mips64.h"
24#include "arch/x86/instruction_set_features_x86.h"
25#include "arch/x86_64/instruction_set_features_x86_64.h"
Vladimir Markoa0431112018-06-25 09:32:54 +010026#include "driver/compiler_options.h"
Aart Bik96202302016-10-04 17:33:56 -070027#include "linear_order.h"
Aart Bik38a3f212017-10-20 17:02:21 -070028#include "mirror/array-inl.h"
29#include "mirror/string.h"
Aart Bik281c6812016-08-26 11:31:48 -070030
Vladimir Marko0a516052019-10-14 13:00:44 +000031namespace art {
Aart Bik281c6812016-08-26 11:31:48 -070032
Aart Bikf8f5a162017-02-06 15:35:29 -080033// Enables vectorization (SIMDization) in the loop optimizer.
34static constexpr bool kEnableVectorization = true;
35
Aart Bik38a3f212017-10-20 17:02:21 -070036//
37// Static helpers.
38//
39
40// Base alignment for arrays/strings guaranteed by the Android runtime.
41static uint32_t BaseAlignment() {
42 return kObjectAlignment;
43}
44
45// Hidden offset for arrays/strings guaranteed by the Android runtime.
46static uint32_t HiddenOffset(DataType::Type type, bool is_string_char_at) {
47 return is_string_char_at
48 ? mirror::String::ValueOffset().Uint32Value()
49 : mirror::Array::DataOffset(DataType::Size(type)).Uint32Value();
50}
51
Aart Bik9abf8942016-10-14 09:49:42 -070052// Remove the instruction from the graph. A bit more elaborate than the usual
53// instruction removal, since there may be a cycle in the use structure.
Aart Bik281c6812016-08-26 11:31:48 -070054static void RemoveFromCycle(HInstruction* instruction) {
Aart Bik281c6812016-08-26 11:31:48 -070055 instruction->RemoveAsUserOfAllInputs();
56 instruction->RemoveEnvironmentUsers();
57 instruction->GetBlock()->RemoveInstructionOrPhi(instruction, /*ensure_safety=*/ false);
Artem Serov21c7e6f2017-07-27 16:04:42 +010058 RemoveEnvironmentUses(instruction);
59 ResetEnvironmentInputRecords(instruction);
Aart Bik281c6812016-08-26 11:31:48 -070060}
61
Aart Bik807868e2016-11-03 17:51:43 -070062// Detect a goto block and sets succ to the single successor.
Aart Bike3dedc52016-11-02 17:50:27 -070063static bool IsGotoBlock(HBasicBlock* block, /*out*/ HBasicBlock** succ) {
64 if (block->GetPredecessors().size() == 1 &&
65 block->GetSuccessors().size() == 1 &&
66 block->IsSingleGoto()) {
67 *succ = block->GetSingleSuccessor();
68 return true;
69 }
70 return false;
71}
72
Aart Bik807868e2016-11-03 17:51:43 -070073// Detect an early exit loop.
74static bool IsEarlyExit(HLoopInformation* loop_info) {
75 HBlocksInLoopReversePostOrderIterator it_loop(*loop_info);
76 for (it_loop.Advance(); !it_loop.Done(); it_loop.Advance()) {
77 for (HBasicBlock* successor : it_loop.Current()->GetSuccessors()) {
78 if (!loop_info->Contains(*successor)) {
79 return true;
80 }
81 }
82 }
83 return false;
84}
85
Aart Bik68ca7022017-09-26 16:44:23 -070086// Forward declaration.
87static bool IsZeroExtensionAndGet(HInstruction* instruction,
88 DataType::Type type,
Aart Bikdf011c32017-09-28 12:53:04 -070089 /*out*/ HInstruction** operand);
Aart Bik68ca7022017-09-26 16:44:23 -070090
Aart Bikdf011c32017-09-28 12:53:04 -070091// Detect a sign extension in instruction from the given type.
Aart Bikdbbac8f2017-09-01 13:06:08 -070092// Returns the promoted operand on success.
Aart Bikf3e61ee2017-04-12 17:09:20 -070093static bool IsSignExtensionAndGet(HInstruction* instruction,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +010094 DataType::Type type,
Aart Bikdf011c32017-09-28 12:53:04 -070095 /*out*/ HInstruction** operand) {
Aart Bikf3e61ee2017-04-12 17:09:20 -070096 // Accept any already wider constant that would be handled properly by sign
97 // extension when represented in the *width* of the given narrower data type
Aart Bik4d1a9d42017-10-19 14:40:55 -070098 // (the fact that Uint8/Uint16 normally zero extend does not matter here).
Aart Bikf3e61ee2017-04-12 17:09:20 -070099 int64_t value = 0;
Aart Bik50e20d52017-05-05 14:07:29 -0700100 if (IsInt64AndGet(instruction, /*out*/ &value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700101 switch (type) {
Vladimir Markod5d2f2c2017-09-26 12:37:26 +0100102 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100103 case DataType::Type::kInt8:
Aart Bikdbbac8f2017-09-01 13:06:08 -0700104 if (IsInt<8>(value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700105 *operand = instruction;
106 return true;
107 }
108 return false;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100109 case DataType::Type::kUint16:
110 case DataType::Type::kInt16:
Aart Bikdbbac8f2017-09-01 13:06:08 -0700111 if (IsInt<16>(value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700112 *operand = instruction;
113 return true;
114 }
115 return false;
116 default:
117 return false;
118 }
119 }
Aart Bikdf011c32017-09-28 12:53:04 -0700120 // An implicit widening conversion of any signed expression sign-extends.
121 if (instruction->GetType() == type) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700122 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100123 case DataType::Type::kInt8:
124 case DataType::Type::kInt16:
Aart Bikf3e61ee2017-04-12 17:09:20 -0700125 *operand = instruction;
126 return true;
127 default:
128 return false;
129 }
130 }
Aart Bikdf011c32017-09-28 12:53:04 -0700131 // An explicit widening conversion of a signed expression sign-extends.
Aart Bik68ca7022017-09-26 16:44:23 -0700132 if (instruction->IsTypeConversion()) {
Aart Bikdf011c32017-09-28 12:53:04 -0700133 HInstruction* conv = instruction->InputAt(0);
134 DataType::Type from = conv->GetType();
Aart Bik68ca7022017-09-26 16:44:23 -0700135 switch (instruction->GetType()) {
Aart Bikdf011c32017-09-28 12:53:04 -0700136 case DataType::Type::kInt32:
Aart Bik68ca7022017-09-26 16:44:23 -0700137 case DataType::Type::kInt64:
Aart Bikdf011c32017-09-28 12:53:04 -0700138 if (type == from && (from == DataType::Type::kInt8 ||
139 from == DataType::Type::kInt16 ||
140 from == DataType::Type::kInt32)) {
141 *operand = conv;
142 return true;
143 }
144 return false;
Aart Bik68ca7022017-09-26 16:44:23 -0700145 case DataType::Type::kInt16:
146 return type == DataType::Type::kUint16 &&
147 from == DataType::Type::kUint16 &&
Aart Bikdf011c32017-09-28 12:53:04 -0700148 IsZeroExtensionAndGet(instruction->InputAt(0), type, /*out*/ operand);
Aart Bik68ca7022017-09-26 16:44:23 -0700149 default:
150 return false;
151 }
Aart Bikdbbac8f2017-09-01 13:06:08 -0700152 }
Aart Bikf3e61ee2017-04-12 17:09:20 -0700153 return false;
154}
155
Aart Bikdf011c32017-09-28 12:53:04 -0700156// Detect a zero extension in instruction from the given type.
Aart Bikdbbac8f2017-09-01 13:06:08 -0700157// Returns the promoted operand on success.
Aart Bikf3e61ee2017-04-12 17:09:20 -0700158static bool IsZeroExtensionAndGet(HInstruction* instruction,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100159 DataType::Type type,
Aart Bikdf011c32017-09-28 12:53:04 -0700160 /*out*/ HInstruction** operand) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700161 // Accept any already wider constant that would be handled properly by zero
162 // extension when represented in the *width* of the given narrower data type
Aart Bikdf011c32017-09-28 12:53:04 -0700163 // (the fact that Int8/Int16 normally sign extend does not matter here).
Aart Bikf3e61ee2017-04-12 17:09:20 -0700164 int64_t value = 0;
Aart Bik50e20d52017-05-05 14:07:29 -0700165 if (IsInt64AndGet(instruction, /*out*/ &value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700166 switch (type) {
Vladimir Markod5d2f2c2017-09-26 12:37:26 +0100167 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100168 case DataType::Type::kInt8:
Aart Bikdbbac8f2017-09-01 13:06:08 -0700169 if (IsUint<8>(value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700170 *operand = instruction;
171 return true;
172 }
173 return false;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100174 case DataType::Type::kUint16:
175 case DataType::Type::kInt16:
Aart Bikdbbac8f2017-09-01 13:06:08 -0700176 if (IsUint<16>(value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700177 *operand = instruction;
178 return true;
179 }
180 return false;
181 default:
182 return false;
183 }
184 }
Aart Bikdf011c32017-09-28 12:53:04 -0700185 // An implicit widening conversion of any unsigned expression zero-extends.
186 if (instruction->GetType() == type) {
Vladimir Markod5d2f2c2017-09-26 12:37:26 +0100187 switch (type) {
188 case DataType::Type::kUint8:
189 case DataType::Type::kUint16:
190 *operand = instruction;
191 return true;
192 default:
193 return false;
Aart Bikf3e61ee2017-04-12 17:09:20 -0700194 }
195 }
Aart Bikdf011c32017-09-28 12:53:04 -0700196 // An explicit widening conversion of an unsigned expression zero-extends.
Aart Bik68ca7022017-09-26 16:44:23 -0700197 if (instruction->IsTypeConversion()) {
Aart Bikdf011c32017-09-28 12:53:04 -0700198 HInstruction* conv = instruction->InputAt(0);
199 DataType::Type from = conv->GetType();
Aart Bik68ca7022017-09-26 16:44:23 -0700200 switch (instruction->GetType()) {
Aart Bikdf011c32017-09-28 12:53:04 -0700201 case DataType::Type::kInt32:
Aart Bik68ca7022017-09-26 16:44:23 -0700202 case DataType::Type::kInt64:
Aart Bikdf011c32017-09-28 12:53:04 -0700203 if (type == from && from == DataType::Type::kUint16) {
204 *operand = conv;
205 return true;
206 }
207 return false;
Aart Bik68ca7022017-09-26 16:44:23 -0700208 case DataType::Type::kUint16:
209 return type == DataType::Type::kInt16 &&
210 from == DataType::Type::kInt16 &&
Aart Bikdf011c32017-09-28 12:53:04 -0700211 IsSignExtensionAndGet(instruction->InputAt(0), type, /*out*/ operand);
Aart Bik68ca7022017-09-26 16:44:23 -0700212 default:
213 return false;
214 }
Aart Bikdbbac8f2017-09-01 13:06:08 -0700215 }
Aart Bikf3e61ee2017-04-12 17:09:20 -0700216 return false;
217}
218
Aart Bik304c8a52017-05-23 11:01:13 -0700219// Detect situations with same-extension narrower operands.
220// Returns true on success and sets is_unsigned accordingly.
221static bool IsNarrowerOperands(HInstruction* a,
222 HInstruction* b,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100223 DataType::Type type,
Aart Bik304c8a52017-05-23 11:01:13 -0700224 /*out*/ HInstruction** r,
225 /*out*/ HInstruction** s,
226 /*out*/ bool* is_unsigned) {
Nicolas Geoffraya3e23262018-03-28 11:15:12 +0000227 DCHECK(a != nullptr && b != nullptr);
Aart Bik4d1a9d42017-10-19 14:40:55 -0700228 // Look for a matching sign extension.
229 DataType::Type stype = HVecOperation::ToSignedType(type);
230 if (IsSignExtensionAndGet(a, stype, r) && IsSignExtensionAndGet(b, stype, s)) {
Aart Bik304c8a52017-05-23 11:01:13 -0700231 *is_unsigned = false;
232 return true;
Aart Bik4d1a9d42017-10-19 14:40:55 -0700233 }
234 // Look for a matching zero extension.
235 DataType::Type utype = HVecOperation::ToUnsignedType(type);
236 if (IsZeroExtensionAndGet(a, utype, r) && IsZeroExtensionAndGet(b, utype, s)) {
Aart Bik304c8a52017-05-23 11:01:13 -0700237 *is_unsigned = true;
238 return true;
239 }
240 return false;
241}
242
243// As above, single operand.
244static bool IsNarrowerOperand(HInstruction* a,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100245 DataType::Type type,
Aart Bik304c8a52017-05-23 11:01:13 -0700246 /*out*/ HInstruction** r,
247 /*out*/ bool* is_unsigned) {
Nicolas Geoffraya3e23262018-03-28 11:15:12 +0000248 DCHECK(a != nullptr);
Aart Bik4d1a9d42017-10-19 14:40:55 -0700249 // Look for a matching sign extension.
250 DataType::Type stype = HVecOperation::ToSignedType(type);
251 if (IsSignExtensionAndGet(a, stype, r)) {
Aart Bik304c8a52017-05-23 11:01:13 -0700252 *is_unsigned = false;
253 return true;
Aart Bik4d1a9d42017-10-19 14:40:55 -0700254 }
255 // Look for a matching zero extension.
256 DataType::Type utype = HVecOperation::ToUnsignedType(type);
257 if (IsZeroExtensionAndGet(a, utype, r)) {
Aart Bik304c8a52017-05-23 11:01:13 -0700258 *is_unsigned = true;
259 return true;
260 }
261 return false;
262}
263
Aart Bikdbbac8f2017-09-01 13:06:08 -0700264// Compute relative vector length based on type difference.
Aart Bik38a3f212017-10-20 17:02:21 -0700265static uint32_t GetOtherVL(DataType::Type other_type, DataType::Type vector_type, uint32_t vl) {
Vladimir Markod5d2f2c2017-09-26 12:37:26 +0100266 DCHECK(DataType::IsIntegralType(other_type));
267 DCHECK(DataType::IsIntegralType(vector_type));
268 DCHECK_GE(DataType::SizeShift(other_type), DataType::SizeShift(vector_type));
269 return vl >> (DataType::SizeShift(other_type) - DataType::SizeShift(vector_type));
Aart Bikdbbac8f2017-09-01 13:06:08 -0700270}
271
Nicolas Geoffraya3e23262018-03-28 11:15:12 +0000272// Detect up to two added operands a and b and an acccumulated constant c.
273static bool IsAddConst(HInstruction* instruction,
274 /*out*/ HInstruction** a,
275 /*out*/ HInstruction** b,
276 /*out*/ int64_t* c,
277 int32_t depth = 8) { // don't search too deep
Aart Bik5f805002017-05-16 16:42:41 -0700278 int64_t value = 0;
Nicolas Geoffraya3e23262018-03-28 11:15:12 +0000279 // Enter add/sub while still within reasonable depth.
280 if (depth > 0) {
281 if (instruction->IsAdd()) {
282 return IsAddConst(instruction->InputAt(0), a, b, c, depth - 1) &&
283 IsAddConst(instruction->InputAt(1), a, b, c, depth - 1);
284 } else if (instruction->IsSub() &&
285 IsInt64AndGet(instruction->InputAt(1), &value)) {
286 *c -= value;
287 return IsAddConst(instruction->InputAt(0), a, b, c, depth - 1);
288 }
289 }
290 // Otherwise, deal with leaf nodes.
Aart Bik5f805002017-05-16 16:42:41 -0700291 if (IsInt64AndGet(instruction, &value)) {
292 *c += value;
293 return true;
Aart Bik5f805002017-05-16 16:42:41 -0700294 } else if (*a == nullptr) {
295 *a = instruction;
296 return true;
297 } else if (*b == nullptr) {
298 *b = instruction;
299 return true;
300 }
Nicolas Geoffraya3e23262018-03-28 11:15:12 +0000301 return false; // too many operands
Aart Bik5f805002017-05-16 16:42:41 -0700302}
303
Nicolas Geoffraya3e23262018-03-28 11:15:12 +0000304// Detect a + b + c with optional constant c.
305static bool IsAddConst2(HGraph* graph,
306 HInstruction* instruction,
307 /*out*/ HInstruction** a,
308 /*out*/ HInstruction** b,
309 /*out*/ int64_t* c) {
310 if (IsAddConst(instruction, a, b, c) && *a != nullptr) {
311 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.
Nicolas Geoffray256c94b2019-04-29 10:55:09 +0100434 PeelUnrollSimpleHelper 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,
Vladimir Markoa0431112018-06-25 09:32:54 +0100461 const CompilerOptions* compiler_options,
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),
Vladimir Markoa0431112018-06-25 09:32:54 +0100466 compiler_options_(compiler_options),
Aart Bik281c6812016-08-26 11:31:48 -0700467 induction_range_(induction_analysis),
Aart Bik96202302016-10-04 17:33:56 -0700468 loop_allocator_(nullptr),
Vladimir Markoca6fff82017-10-03 14:49:14 +0100469 global_allocator_(graph_->GetAllocator()),
Aart Bik281c6812016-08-26 11:31:48 -0700470 top_loop_(nullptr),
Aart Bik8c4a8542016-10-06 11:36:57 -0700471 last_loop_(nullptr),
Aart Bik482095d2016-10-10 15:39:10 -0700472 iset_(nullptr),
Aart Bikb29f6842017-07-28 15:58:41 -0700473 reductions_(nullptr),
Aart Bikf8f5a162017-02-06 15:35:29 -0800474 simplified_(false),
475 vector_length_(0),
476 vector_refs_(nullptr),
Aart Bik38a3f212017-10-20 17:02:21 -0700477 vector_static_peeling_factor_(0),
478 vector_dynamic_peeling_candidate_(nullptr),
Aart Bik14a68b42017-06-08 14:06:58 -0700479 vector_runtime_test_a_(nullptr),
480 vector_runtime_test_b_(nullptr),
Aart Bik0148de42017-09-05 09:25:01 -0700481 vector_map_(nullptr),
Vladimir Markoca6fff82017-10-03 14:49:14 +0100482 vector_permanent_map_(nullptr),
483 vector_mode_(kSequential),
484 vector_preheader_(nullptr),
485 vector_header_(nullptr),
486 vector_body_(nullptr),
Artem Serov121f2032017-10-23 19:19:06 +0100487 vector_index_(nullptr),
Vladimir Markoa0431112018-06-25 09:32:54 +0100488 arch_loop_helper_(ArchNoOptsLoopHelper::Create(compiler_options_ != nullptr
489 ? compiler_options_->GetInstructionSet()
Artem Serov121f2032017-10-23 19:19:06 +0100490 : InstructionSet::kNone,
491 global_allocator_)) {
Aart Bik281c6812016-08-26 11:31:48 -0700492}
493
Aart Bik24773202018-04-26 10:28:51 -0700494bool HLoopOptimization::Run() {
Mingyao Yang01b47b02017-02-03 12:09:57 -0800495 // Skip if there is no loop or the graph has try-catch/irreducible loops.
Aart Bik281c6812016-08-26 11:31:48 -0700496 // TODO: make this less of a sledgehammer.
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800497 if (!graph_->HasLoops() || graph_->HasTryCatch() || graph_->HasIrreducibleLoops()) {
Aart Bik24773202018-04-26 10:28:51 -0700498 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700499 }
500
Vladimir Markoca6fff82017-10-03 14:49:14 +0100501 // Phase-local allocator.
502 ScopedArenaAllocator allocator(graph_->GetArenaStack());
Aart Bik96202302016-10-04 17:33:56 -0700503 loop_allocator_ = &allocator;
Nicolas Geoffrayebe16742016-10-05 09:55:42 +0100504
Aart Bik96202302016-10-04 17:33:56 -0700505 // Perform loop optimizations.
Aart Bik24773202018-04-26 10:28:51 -0700506 bool didLoopOpt = LocalRun();
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800507 if (top_loop_ == nullptr) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800508 graph_->SetHasLoops(false); // no more loops
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800509 }
510
Aart Bik96202302016-10-04 17:33:56 -0700511 // Detach.
512 loop_allocator_ = nullptr;
513 last_loop_ = top_loop_ = nullptr;
Aart Bik24773202018-04-26 10:28:51 -0700514
515 return didLoopOpt;
Aart Bik96202302016-10-04 17:33:56 -0700516}
517
Aart Bikb29f6842017-07-28 15:58:41 -0700518//
519// Loop setup and traversal.
520//
521
Aart Bik24773202018-04-26 10:28:51 -0700522bool HLoopOptimization::LocalRun() {
523 bool didLoopOpt = false;
Aart Bik96202302016-10-04 17:33:56 -0700524 // Build the linear order using the phase-local allocator. This step enables building
525 // a loop hierarchy that properly reflects the outer-inner and previous-next relation.
Vladimir Markoca6fff82017-10-03 14:49:14 +0100526 ScopedArenaVector<HBasicBlock*> linear_order(loop_allocator_->Adapter(kArenaAllocLinearOrder));
527 LinearizeGraph(graph_, &linear_order);
Aart Bik96202302016-10-04 17:33:56 -0700528
Aart Bik281c6812016-08-26 11:31:48 -0700529 // Build the loop hierarchy.
Aart Bik96202302016-10-04 17:33:56 -0700530 for (HBasicBlock* block : linear_order) {
Aart Bik281c6812016-08-26 11:31:48 -0700531 if (block->IsLoopHeader()) {
532 AddLoop(block->GetLoopInformation());
533 }
534 }
Aart Bik96202302016-10-04 17:33:56 -0700535
Aart Bik8c4a8542016-10-06 11:36:57 -0700536 // Traverse the loop hierarchy inner-to-outer and optimize. Traversal can use
Aart Bikf8f5a162017-02-06 15:35:29 -0800537 // temporary data structures using the phase-local allocator. All new HIR
538 // should use the global allocator.
Aart Bik8c4a8542016-10-06 11:36:57 -0700539 if (top_loop_ != nullptr) {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100540 ScopedArenaSet<HInstruction*> iset(loop_allocator_->Adapter(kArenaAllocLoopOptimization));
541 ScopedArenaSafeMap<HInstruction*, HInstruction*> reds(
Aart Bikb29f6842017-07-28 15:58:41 -0700542 std::less<HInstruction*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
Vladimir Markoca6fff82017-10-03 14:49:14 +0100543 ScopedArenaSet<ArrayReference> refs(loop_allocator_->Adapter(kArenaAllocLoopOptimization));
544 ScopedArenaSafeMap<HInstruction*, HInstruction*> map(
Aart Bikf8f5a162017-02-06 15:35:29 -0800545 std::less<HInstruction*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
Vladimir Markoca6fff82017-10-03 14:49:14 +0100546 ScopedArenaSafeMap<HInstruction*, HInstruction*> perm(
Aart Bik0148de42017-09-05 09:25:01 -0700547 std::less<HInstruction*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
Aart Bikf8f5a162017-02-06 15:35:29 -0800548 // Attach.
Aart Bik8c4a8542016-10-06 11:36:57 -0700549 iset_ = &iset;
Aart Bikb29f6842017-07-28 15:58:41 -0700550 reductions_ = &reds;
Aart Bikf8f5a162017-02-06 15:35:29 -0800551 vector_refs_ = &refs;
552 vector_map_ = &map;
Aart Bik0148de42017-09-05 09:25:01 -0700553 vector_permanent_map_ = &perm;
Aart Bikf8f5a162017-02-06 15:35:29 -0800554 // Traverse.
Aart Bik24773202018-04-26 10:28:51 -0700555 didLoopOpt = TraverseLoopsInnerToOuter(top_loop_);
Aart Bikf8f5a162017-02-06 15:35:29 -0800556 // Detach.
557 iset_ = nullptr;
Aart Bikb29f6842017-07-28 15:58:41 -0700558 reductions_ = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800559 vector_refs_ = nullptr;
560 vector_map_ = nullptr;
Aart Bik0148de42017-09-05 09:25:01 -0700561 vector_permanent_map_ = nullptr;
Aart Bik8c4a8542016-10-06 11:36:57 -0700562 }
Aart Bik24773202018-04-26 10:28:51 -0700563 return didLoopOpt;
Aart Bik281c6812016-08-26 11:31:48 -0700564}
565
566void HLoopOptimization::AddLoop(HLoopInformation* loop_info) {
567 DCHECK(loop_info != nullptr);
Aart Bikf8f5a162017-02-06 15:35:29 -0800568 LoopNode* node = new (loop_allocator_) LoopNode(loop_info);
Aart Bik281c6812016-08-26 11:31:48 -0700569 if (last_loop_ == nullptr) {
570 // First loop.
571 DCHECK(top_loop_ == nullptr);
572 last_loop_ = top_loop_ = node;
573 } else if (loop_info->IsIn(*last_loop_->loop_info)) {
574 // Inner loop.
575 node->outer = last_loop_;
576 DCHECK(last_loop_->inner == nullptr);
577 last_loop_ = last_loop_->inner = node;
578 } else {
579 // Subsequent loop.
580 while (last_loop_->outer != nullptr && !loop_info->IsIn(*last_loop_->outer->loop_info)) {
581 last_loop_ = last_loop_->outer;
582 }
583 node->outer = last_loop_->outer;
584 node->previous = last_loop_;
585 DCHECK(last_loop_->next == nullptr);
586 last_loop_ = last_loop_->next = node;
587 }
588}
589
590void HLoopOptimization::RemoveLoop(LoopNode* node) {
591 DCHECK(node != nullptr);
Aart Bik8c4a8542016-10-06 11:36:57 -0700592 DCHECK(node->inner == nullptr);
593 if (node->previous != nullptr) {
594 // Within sequence.
595 node->previous->next = node->next;
596 if (node->next != nullptr) {
597 node->next->previous = node->previous;
598 }
599 } else {
600 // First of sequence.
601 if (node->outer != nullptr) {
602 node->outer->inner = node->next;
603 } else {
604 top_loop_ = node->next;
605 }
606 if (node->next != nullptr) {
607 node->next->outer = node->outer;
608 node->next->previous = nullptr;
609 }
610 }
Aart Bik281c6812016-08-26 11:31:48 -0700611}
612
Aart Bikb29f6842017-07-28 15:58:41 -0700613bool HLoopOptimization::TraverseLoopsInnerToOuter(LoopNode* node) {
614 bool changed = false;
Aart Bik281c6812016-08-26 11:31:48 -0700615 for ( ; node != nullptr; node = node->next) {
Aart Bikb29f6842017-07-28 15:58:41 -0700616 // Visit inner loops first. Recompute induction information for this
617 // loop if the induction of any inner loop has changed.
618 if (TraverseLoopsInnerToOuter(node->inner)) {
Aart Bik482095d2016-10-10 15:39:10 -0700619 induction_range_.ReVisit(node->loop_info);
Aart Bika8360cd2018-05-02 16:07:51 -0700620 changed = true;
Aart Bik482095d2016-10-10 15:39:10 -0700621 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800622 // Repeat simplifications in the loop-body until no more changes occur.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800623 // Note that since each simplification consists of eliminating code (without
624 // introducing new code), this process is always finite.
Aart Bikdf7822e2016-12-06 10:05:30 -0800625 do {
626 simplified_ = false;
Aart Bikdf7822e2016-12-06 10:05:30 -0800627 SimplifyInduction(node);
Aart Bik6b69e0a2017-01-11 10:20:43 -0800628 SimplifyBlocks(node);
Aart Bikb29f6842017-07-28 15:58:41 -0700629 changed = simplified_ || changed;
Aart Bikdf7822e2016-12-06 10:05:30 -0800630 } while (simplified_);
Aart Bikf8f5a162017-02-06 15:35:29 -0800631 // Optimize inner loop.
Aart Bik9abf8942016-10-14 09:49:42 -0700632 if (node->inner == nullptr) {
Aart Bikb29f6842017-07-28 15:58:41 -0700633 changed = OptimizeInnerLoop(node) || changed;
Aart Bik9abf8942016-10-14 09:49:42 -0700634 }
Aart Bik281c6812016-08-26 11:31:48 -0700635 }
Aart Bikb29f6842017-07-28 15:58:41 -0700636 return changed;
Aart Bik281c6812016-08-26 11:31:48 -0700637}
638
Aart Bikf8f5a162017-02-06 15:35:29 -0800639//
640// Optimization.
641//
642
Aart Bik281c6812016-08-26 11:31:48 -0700643void HLoopOptimization::SimplifyInduction(LoopNode* node) {
644 HBasicBlock* header = node->loop_info->GetHeader();
645 HBasicBlock* preheader = node->loop_info->GetPreHeader();
Aart Bik8c4a8542016-10-06 11:36:57 -0700646 // Scan the phis in the header to find opportunities to simplify an induction
647 // cycle that is only used outside the loop. Replace these uses, if any, with
648 // the last value and remove the induction cycle.
649 // Examples: for (int i = 0; x != null; i++) { .... no i .... }
650 // for (int i = 0; i < 10; i++, k++) { .... no k .... } return k;
Aart Bik281c6812016-08-26 11:31:48 -0700651 for (HInstructionIterator it(header->GetPhis()); !it.Done(); it.Advance()) {
652 HPhi* phi = it.Current()->AsPhi();
Aart Bikf8f5a162017-02-06 15:35:29 -0800653 if (TrySetPhiInduction(phi, /*restrict_uses*/ true) &&
654 TryAssignLastValue(node->loop_info, phi, preheader, /*collect_loop_uses*/ false)) {
Aart Bik671e48a2017-08-09 13:16:56 -0700655 // Note that it's ok to have replaced uses after the loop with the last value, without
656 // being able to remove the cycle. Environment uses (which are the reason we may not be
657 // able to remove the cycle) within the loop will still hold the right value. We must
658 // have tried first, however, to replace outside uses.
659 if (CanRemoveCycle()) {
660 simplified_ = true;
661 for (HInstruction* i : *iset_) {
662 RemoveFromCycle(i);
663 }
664 DCHECK(CheckInductionSetFullyRemoved(iset_));
Aart Bik281c6812016-08-26 11:31:48 -0700665 }
Aart Bik482095d2016-10-10 15:39:10 -0700666 }
667 }
668}
669
670void HLoopOptimization::SimplifyBlocks(LoopNode* node) {
Aart Bikdf7822e2016-12-06 10:05:30 -0800671 // Iterate over all basic blocks in the loop-body.
672 for (HBlocksInLoopIterator it(*node->loop_info); !it.Done(); it.Advance()) {
673 HBasicBlock* block = it.Current();
674 // Remove dead instructions from the loop-body.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800675 RemoveDeadInstructions(block->GetPhis());
676 RemoveDeadInstructions(block->GetInstructions());
Aart Bikdf7822e2016-12-06 10:05:30 -0800677 // Remove trivial control flow blocks from the loop-body.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800678 if (block->GetPredecessors().size() == 1 &&
679 block->GetSuccessors().size() == 1 &&
680 block->GetSingleSuccessor()->GetPredecessors().size() == 1) {
Aart Bikdf7822e2016-12-06 10:05:30 -0800681 simplified_ = true;
Aart Bik6b69e0a2017-01-11 10:20:43 -0800682 block->MergeWith(block->GetSingleSuccessor());
Aart Bikdf7822e2016-12-06 10:05:30 -0800683 } else if (block->GetSuccessors().size() == 2) {
684 // Trivial if block can be bypassed to either branch.
685 HBasicBlock* succ0 = block->GetSuccessors()[0];
686 HBasicBlock* succ1 = block->GetSuccessors()[1];
687 HBasicBlock* meet0 = nullptr;
688 HBasicBlock* meet1 = nullptr;
689 if (succ0 != succ1 &&
690 IsGotoBlock(succ0, &meet0) &&
691 IsGotoBlock(succ1, &meet1) &&
692 meet0 == meet1 && // meets again
693 meet0 != block && // no self-loop
694 meet0->GetPhis().IsEmpty()) { // not used for merging
695 simplified_ = true;
696 succ0->DisconnectAndDelete();
697 if (block->Dominates(meet0)) {
698 block->RemoveDominatedBlock(meet0);
699 succ1->AddDominatedBlock(meet0);
700 meet0->SetDominator(succ1);
Aart Bike3dedc52016-11-02 17:50:27 -0700701 }
Aart Bik482095d2016-10-10 15:39:10 -0700702 }
Aart Bik281c6812016-08-26 11:31:48 -0700703 }
Aart Bikdf7822e2016-12-06 10:05:30 -0800704 }
Aart Bik281c6812016-08-26 11:31:48 -0700705}
706
Artem Serov121f2032017-10-23 19:19:06 +0100707bool HLoopOptimization::TryOptimizeInnerLoopFinite(LoopNode* node) {
Aart Bik281c6812016-08-26 11:31:48 -0700708 HBasicBlock* header = node->loop_info->GetHeader();
709 HBasicBlock* preheader = node->loop_info->GetPreHeader();
Aart Bik9abf8942016-10-14 09:49:42 -0700710 // Ensure loop header logic is finite.
Aart Bikf8f5a162017-02-06 15:35:29 -0800711 int64_t trip_count = 0;
712 if (!induction_range_.IsFinite(node->loop_info, &trip_count)) {
Aart Bikb29f6842017-07-28 15:58:41 -0700713 return false;
Aart Bik9abf8942016-10-14 09:49:42 -0700714 }
Aart Bik281c6812016-08-26 11:31:48 -0700715 // Ensure there is only a single loop-body (besides the header).
716 HBasicBlock* body = nullptr;
717 for (HBlocksInLoopIterator it(*node->loop_info); !it.Done(); it.Advance()) {
718 if (it.Current() != header) {
719 if (body != nullptr) {
Aart Bikb29f6842017-07-28 15:58:41 -0700720 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700721 }
722 body = it.Current();
723 }
724 }
Andreas Gampef45d61c2017-06-07 10:29:33 -0700725 CHECK(body != nullptr);
Aart Bik281c6812016-08-26 11:31:48 -0700726 // Ensure there is only a single exit point.
727 if (header->GetSuccessors().size() != 2) {
Aart Bikb29f6842017-07-28 15:58:41 -0700728 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700729 }
730 HBasicBlock* exit = (header->GetSuccessors()[0] == body)
731 ? header->GetSuccessors()[1]
732 : header->GetSuccessors()[0];
Aart Bik8c4a8542016-10-06 11:36:57 -0700733 // Ensure exit can only be reached by exiting loop.
Aart Bik281c6812016-08-26 11:31:48 -0700734 if (exit->GetPredecessors().size() != 1) {
Aart Bikb29f6842017-07-28 15:58:41 -0700735 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700736 }
Aart Bik6b69e0a2017-01-11 10:20:43 -0800737 // Detect either an empty loop (no side effects other than plain iteration) or
738 // a trivial loop (just iterating once). Replace subsequent index uses, if any,
739 // with the last value and remove the loop, possibly after unrolling its body.
Aart Bikb29f6842017-07-28 15:58:41 -0700740 HPhi* main_phi = nullptr;
741 if (TrySetSimpleLoopHeader(header, &main_phi)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -0800742 bool is_empty = IsEmptyBody(body);
Aart Bikb29f6842017-07-28 15:58:41 -0700743 if (reductions_->empty() && // TODO: possible with some effort
744 (is_empty || trip_count == 1) &&
745 TryAssignLastValue(node->loop_info, main_phi, preheader, /*collect_loop_uses*/ true)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -0800746 if (!is_empty) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800747 // Unroll the loop-body, which sees initial value of the index.
Aart Bikb29f6842017-07-28 15:58:41 -0700748 main_phi->ReplaceWith(main_phi->InputAt(0));
Aart Bik6b69e0a2017-01-11 10:20:43 -0800749 preheader->MergeInstructionsWith(body);
750 }
751 body->DisconnectAndDelete();
752 exit->RemovePredecessor(header);
753 header->RemoveSuccessor(exit);
754 header->RemoveDominatedBlock(exit);
755 header->DisconnectAndDelete();
756 preheader->AddSuccessor(exit);
Aart Bikf8f5a162017-02-06 15:35:29 -0800757 preheader->AddInstruction(new (global_allocator_) HGoto());
Aart Bik6b69e0a2017-01-11 10:20:43 -0800758 preheader->AddDominatedBlock(exit);
759 exit->SetDominator(preheader);
760 RemoveLoop(node); // update hierarchy
Aart Bikb29f6842017-07-28 15:58:41 -0700761 return true;
Aart Bikf8f5a162017-02-06 15:35:29 -0800762 }
763 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800764 // Vectorize loop, if possible and valid.
Aart Bikb29f6842017-07-28 15:58:41 -0700765 if (kEnableVectorization &&
Artem Serove65ade72019-07-25 21:04:16 +0100766 // Disable vectorization for debuggable graphs: this is a workaround for the bug
767 // in 'GenerateNewLoop' which caused the SuspendCheck environment to be invalid.
768 // TODO: b/138601207, investigate other possible cases with wrong environment values and
769 // possibly switch back vectorization on for debuggable graphs.
770 !graph_->IsDebuggable() &&
Aart Bikb29f6842017-07-28 15:58:41 -0700771 TrySetSimpleLoopHeader(header, &main_phi) &&
Aart Bikb29f6842017-07-28 15:58:41 -0700772 ShouldVectorize(node, body, trip_count) &&
773 TryAssignLastValue(node->loop_info, main_phi, preheader, /*collect_loop_uses*/ true)) {
774 Vectorize(node, body, exit, trip_count);
775 graph_->SetHasSIMD(true); // flag SIMD usage
Aart Bik21b85922017-09-06 13:29:16 -0700776 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorized);
Aart Bikb29f6842017-07-28 15:58:41 -0700777 return true;
Aart Bikf8f5a162017-02-06 15:35:29 -0800778 }
Aart Bikb29f6842017-07-28 15:58:41 -0700779 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -0800780}
781
Artem Serov121f2032017-10-23 19:19:06 +0100782bool HLoopOptimization::OptimizeInnerLoop(LoopNode* node) {
Artem Serov0e329082018-06-12 10:23:27 +0100783 return TryOptimizeInnerLoopFinite(node) || TryPeelingAndUnrolling(node);
Artem Serov121f2032017-10-23 19:19:06 +0100784}
785
Artem Serov121f2032017-10-23 19:19:06 +0100786
Artem Serov121f2032017-10-23 19:19:06 +0100787
788//
Artem Serov0e329082018-06-12 10:23:27 +0100789// Scalar loop peeling and unrolling: generic part methods.
Artem Serov121f2032017-10-23 19:19:06 +0100790//
791
Artem Serov0e329082018-06-12 10:23:27 +0100792bool HLoopOptimization::TryUnrollingForBranchPenaltyReduction(LoopAnalysisInfo* analysis_info,
793 bool generate_code) {
794 if (analysis_info->GetNumberOfExits() > 1) {
Artem Serov121f2032017-10-23 19:19:06 +0100795 return false;
796 }
797
Artem Serov0e329082018-06-12 10:23:27 +0100798 uint32_t unrolling_factor = arch_loop_helper_->GetScalarUnrollingFactor(analysis_info);
799 if (unrolling_factor == LoopAnalysisInfo::kNoUnrollingFactor) {
Artem Serov121f2032017-10-23 19:19:06 +0100800 return false;
801 }
802
Artem Serov0e329082018-06-12 10:23:27 +0100803 if (generate_code) {
804 // TODO: support other unrolling factors.
805 DCHECK_EQ(unrolling_factor, 2u);
806
807 // Perform unrolling.
808 HLoopInformation* loop_info = analysis_info->GetLoopInfo();
Nicolas Geoffray256c94b2019-04-29 10:55:09 +0100809 PeelUnrollSimpleHelper helper(loop_info, &induction_range_);
Artem Serov0e329082018-06-12 10:23:27 +0100810 helper.DoUnrolling();
811
812 // Remove the redundant loop check after unrolling.
813 HIf* copy_hif =
814 helper.GetBasicBlockMap()->Get(loop_info->GetHeader())->GetLastInstruction()->AsIf();
815 int32_t constant = loop_info->Contains(*copy_hif->IfTrueSuccessor()) ? 1 : 0;
816 copy_hif->ReplaceInput(graph_->GetIntConstant(constant), 0u);
Artem Serov121f2032017-10-23 19:19:06 +0100817 }
Artem Serov121f2032017-10-23 19:19:06 +0100818 return true;
819}
820
Artem Serov0e329082018-06-12 10:23:27 +0100821bool HLoopOptimization::TryPeelingForLoopInvariantExitsElimination(LoopAnalysisInfo* analysis_info,
822 bool generate_code) {
823 HLoopInformation* loop_info = analysis_info->GetLoopInfo();
Artem Serov72411e62017-10-19 16:18:07 +0100824 if (!arch_loop_helper_->IsLoopPeelingEnabled()) {
825 return false;
826 }
827
Artem Serov0e329082018-06-12 10:23:27 +0100828 if (analysis_info->GetNumberOfInvariantExits() == 0) {
Artem Serov72411e62017-10-19 16:18:07 +0100829 return false;
830 }
831
Artem Serov0e329082018-06-12 10:23:27 +0100832 if (generate_code) {
833 // Perform peeling.
Nicolas Geoffray256c94b2019-04-29 10:55:09 +0100834 PeelUnrollSimpleHelper helper(loop_info, &induction_range_);
Artem Serov0e329082018-06-12 10:23:27 +0100835 helper.DoPeeling();
Artem Serov72411e62017-10-19 16:18:07 +0100836
Artem Serov0e329082018-06-12 10:23:27 +0100837 // Statically evaluate loop check after peeling for loop invariant condition.
838 const SuperblockCloner::HInstructionMap* hir_map = helper.GetInstructionMap();
839 for (auto entry : *hir_map) {
840 HInstruction* copy = entry.second;
841 if (copy->IsIf()) {
842 TryToEvaluateIfCondition(copy->AsIf(), graph_);
843 }
Artem Serov72411e62017-10-19 16:18:07 +0100844 }
845 }
846
847 return true;
848}
849
Artem Serov18ba1da2018-05-16 19:06:32 +0100850bool HLoopOptimization::TryFullUnrolling(LoopAnalysisInfo* analysis_info, bool generate_code) {
851 // Fully unroll loops with a known and small trip count.
852 int64_t trip_count = analysis_info->GetTripCount();
853 if (!arch_loop_helper_->IsLoopPeelingEnabled() ||
854 trip_count == LoopAnalysisInfo::kUnknownTripCount ||
855 !arch_loop_helper_->IsFullUnrollingBeneficial(analysis_info)) {
856 return false;
857 }
858
859 if (generate_code) {
860 // Peeling of the N first iterations (where N equals to the trip count) will effectively
861 // eliminate the loop: after peeling we will have N sequential iterations copied into the loop
862 // preheader and the original loop. The trip count of this loop will be 0 as the sequential
863 // iterations are executed first and there are exactly N of them. Thus we can statically
864 // evaluate the loop exit condition to 'false' and fully eliminate it.
865 //
866 // Here is an example of full unrolling of a loop with a trip count 2:
867 //
868 // loop_cond_1
869 // loop_body_1 <- First iteration.
870 // |
871 // \ v
872 // ==\ loop_cond_2
873 // ==/ loop_body_2 <- Second iteration.
874 // / |
875 // <- v <-
876 // loop_cond \ loop_cond \ <- This cond is always false.
877 // loop_body _/ loop_body _/
878 //
879 HLoopInformation* loop_info = analysis_info->GetLoopInfo();
Nicolas Geoffray256c94b2019-04-29 10:55:09 +0100880 PeelByCount(loop_info, trip_count, &induction_range_);
Artem Serov18ba1da2018-05-16 19:06:32 +0100881 HIf* loop_hif = loop_info->GetHeader()->GetLastInstruction()->AsIf();
882 int32_t constant = loop_info->Contains(*loop_hif->IfTrueSuccessor()) ? 0 : 1;
883 loop_hif->ReplaceInput(graph_->GetIntConstant(constant), 0u);
884 }
885
886 return true;
887}
888
Artem Serov0e329082018-06-12 10:23:27 +0100889bool HLoopOptimization::TryPeelingAndUnrolling(LoopNode* node) {
890 // Don't run peeling/unrolling if compiler_options_ is nullptr (i.e., running under tests)
891 // as InstructionSet is needed.
892 if (compiler_options_ == nullptr) {
893 return false;
894 }
895
896 HLoopInformation* loop_info = node->loop_info;
897 int64_t trip_count = LoopAnalysis::GetLoopTripCount(loop_info, &induction_range_);
898 LoopAnalysisInfo analysis_info(loop_info);
899 LoopAnalysis::CalculateLoopBasicProperties(loop_info, &analysis_info, trip_count);
900
901 if (analysis_info.HasInstructionsPreventingScalarOpts() ||
902 arch_loop_helper_->IsLoopNonBeneficialForScalarOpts(&analysis_info)) {
903 return false;
904 }
905
Artem Serov18ba1da2018-05-16 19:06:32 +0100906 if (!TryFullUnrolling(&analysis_info, /*generate_code*/ false) &&
907 !TryPeelingForLoopInvariantExitsElimination(&analysis_info, /*generate_code*/ false) &&
Artem Serov0e329082018-06-12 10:23:27 +0100908 !TryUnrollingForBranchPenaltyReduction(&analysis_info, /*generate_code*/ false)) {
909 return false;
910 }
911
912 // Run 'IsLoopClonable' the last as it might be time-consuming.
913 if (!PeelUnrollHelper::IsLoopClonable(loop_info)) {
914 return false;
915 }
916
Artem Serov18ba1da2018-05-16 19:06:32 +0100917 return TryFullUnrolling(&analysis_info) ||
918 TryPeelingForLoopInvariantExitsElimination(&analysis_info) ||
Artem Serov0e329082018-06-12 10:23:27 +0100919 TryUnrollingForBranchPenaltyReduction(&analysis_info);
920}
921
Aart Bikf8f5a162017-02-06 15:35:29 -0800922//
923// Loop vectorization. The implementation is based on the book by Aart J.C. Bik:
924// "The Software Vectorization Handbook. Applying Multimedia Extensions for Maximum Performance."
925// Intel Press, June, 2004 (http://www.aartbik.com/).
926//
927
Aart Bik14a68b42017-06-08 14:06:58 -0700928bool HLoopOptimization::ShouldVectorize(LoopNode* node, HBasicBlock* block, int64_t trip_count) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800929 // Reset vector bookkeeping.
930 vector_length_ = 0;
931 vector_refs_->clear();
Aart Bik38a3f212017-10-20 17:02:21 -0700932 vector_static_peeling_factor_ = 0;
933 vector_dynamic_peeling_candidate_ = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800934 vector_runtime_test_a_ =
Igor Murashkin2ffb7032017-11-08 13:35:21 -0800935 vector_runtime_test_b_ = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800936
937 // Phis in the loop-body prevent vectorization.
938 if (!block->GetPhis().IsEmpty()) {
939 return false;
940 }
941
942 // Scan the loop-body, starting a right-hand-side tree traversal at each left-hand-side
943 // occurrence, which allows passing down attributes down the use tree.
944 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
945 if (!VectorizeDef(node, it.Current(), /*generate_code*/ false)) {
946 return false; // failure to vectorize a left-hand-side
947 }
948 }
949
Aart Bik38a3f212017-10-20 17:02:21 -0700950 // Prepare alignment analysis:
951 // (1) find desired alignment (SIMD vector size in bytes).
952 // (2) initialize static loop peeling votes (peeling factor that will
953 // make one particular reference aligned), never to exceed (1).
954 // (3) variable to record how many references share same alignment.
955 // (4) variable to record suitable candidate for dynamic loop peeling.
956 uint32_t desired_alignment = GetVectorSizeInBytes();
957 DCHECK_LE(desired_alignment, 16u);
958 uint32_t peeling_votes[16] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
959 uint32_t max_num_same_alignment = 0;
960 const ArrayReference* peeling_candidate = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800961
962 // Data dependence analysis. Find each pair of references with same type, where
963 // at least one is a write. Each such pair denotes a possible data dependence.
964 // This analysis exploits the property that differently typed arrays cannot be
965 // aliased, as well as the property that references either point to the same
966 // array or to two completely disjoint arrays, i.e., no partial aliasing.
967 // Other than a few simply heuristics, no detailed subscript analysis is done.
Aart Bik38a3f212017-10-20 17:02:21 -0700968 // The scan over references also prepares finding a suitable alignment strategy.
Aart Bikf8f5a162017-02-06 15:35:29 -0800969 for (auto i = vector_refs_->begin(); i != vector_refs_->end(); ++i) {
Aart Bik38a3f212017-10-20 17:02:21 -0700970 uint32_t num_same_alignment = 0;
971 // Scan over all next references.
Aart Bikf8f5a162017-02-06 15:35:29 -0800972 for (auto j = i; ++j != vector_refs_->end(); ) {
973 if (i->type == j->type && (i->lhs || j->lhs)) {
974 // Found same-typed a[i+x] vs. b[i+y], where at least one is a write.
975 HInstruction* a = i->base;
976 HInstruction* b = j->base;
977 HInstruction* x = i->offset;
978 HInstruction* y = j->offset;
979 if (a == b) {
980 // Found a[i+x] vs. a[i+y]. Accept if x == y (loop-independent data dependence).
981 // Conservatively assume a loop-carried data dependence otherwise, and reject.
982 if (x != y) {
983 return false;
984 }
Aart Bik38a3f212017-10-20 17:02:21 -0700985 // Count the number of references that have the same alignment (since
986 // base and offset are the same) and where at least one is a write, so
987 // e.g. a[i] = a[i] + b[i] counts a[i] but not b[i]).
988 num_same_alignment++;
Aart Bikf8f5a162017-02-06 15:35:29 -0800989 } else {
990 // Found a[i+x] vs. b[i+y]. Accept if x == y (at worst loop-independent data dependence).
991 // Conservatively assume a potential loop-carried data dependence otherwise, avoided by
992 // generating an explicit a != b disambiguation runtime test on the two references.
993 if (x != y) {
Aart Bik37dc4df2017-06-28 14:08:00 -0700994 // To avoid excessive overhead, we only accept one a != b test.
995 if (vector_runtime_test_a_ == nullptr) {
996 // First test found.
997 vector_runtime_test_a_ = a;
998 vector_runtime_test_b_ = b;
999 } else if ((vector_runtime_test_a_ != a || vector_runtime_test_b_ != b) &&
1000 (vector_runtime_test_a_ != b || vector_runtime_test_b_ != a)) {
1001 return false; // second test would be needed
Aart Bikf8f5a162017-02-06 15:35:29 -08001002 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001003 }
1004 }
1005 }
1006 }
Aart Bik38a3f212017-10-20 17:02:21 -07001007 // Update information for finding suitable alignment strategy:
1008 // (1) update votes for static loop peeling,
1009 // (2) update suitable candidate for dynamic loop peeling.
1010 Alignment alignment = ComputeAlignment(i->offset, i->type, i->is_string_char_at);
1011 if (alignment.Base() >= desired_alignment) {
1012 // If the array/string object has a known, sufficient alignment, use the
1013 // initial offset to compute the static loop peeling vote (this always
1014 // works, since elements have natural alignment).
1015 uint32_t offset = alignment.Offset() & (desired_alignment - 1u);
1016 uint32_t vote = (offset == 0)
1017 ? 0
1018 : ((desired_alignment - offset) >> DataType::SizeShift(i->type));
1019 DCHECK_LT(vote, 16u);
1020 ++peeling_votes[vote];
1021 } else if (BaseAlignment() >= desired_alignment &&
1022 num_same_alignment > max_num_same_alignment) {
1023 // Otherwise, if the array/string object has a known, sufficient alignment
1024 // for just the base but with an unknown offset, record the candidate with
1025 // the most occurrences for dynamic loop peeling (again, the peeling always
1026 // works, since elements have natural alignment).
1027 max_num_same_alignment = num_same_alignment;
1028 peeling_candidate = &(*i);
1029 }
1030 } // for i
Aart Bikf8f5a162017-02-06 15:35:29 -08001031
Aart Bik38a3f212017-10-20 17:02:21 -07001032 // Find a suitable alignment strategy.
1033 SetAlignmentStrategy(peeling_votes, peeling_candidate);
1034
1035 // Does vectorization seem profitable?
1036 if (!IsVectorizationProfitable(trip_count)) {
1037 return false;
1038 }
Aart Bik14a68b42017-06-08 14:06:58 -07001039
Aart Bikf8f5a162017-02-06 15:35:29 -08001040 // Success!
1041 return true;
1042}
1043
1044void HLoopOptimization::Vectorize(LoopNode* node,
1045 HBasicBlock* block,
1046 HBasicBlock* exit,
1047 int64_t trip_count) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001048 HBasicBlock* header = node->loop_info->GetHeader();
1049 HBasicBlock* preheader = node->loop_info->GetPreHeader();
1050
Aart Bik14a68b42017-06-08 14:06:58 -07001051 // Pick a loop unrolling factor for the vector loop.
Artem Serov121f2032017-10-23 19:19:06 +01001052 uint32_t unroll = arch_loop_helper_->GetSIMDUnrollingFactor(
1053 block, trip_count, MaxNumberPeeled(), vector_length_);
Aart Bik14a68b42017-06-08 14:06:58 -07001054 uint32_t chunk = vector_length_ * unroll;
1055
Aart Bik38a3f212017-10-20 17:02:21 -07001056 DCHECK(trip_count == 0 || (trip_count >= MaxNumberPeeled() + chunk));
1057
Aart Bik14a68b42017-06-08 14:06:58 -07001058 // A cleanup loop is needed, at least, for any unknown trip count or
1059 // for a known trip count with remainder iterations after vectorization.
Aart Bik38a3f212017-10-20 17:02:21 -07001060 bool needs_cleanup = trip_count == 0 ||
1061 ((trip_count - vector_static_peeling_factor_) % chunk) != 0;
Aart Bikf8f5a162017-02-06 15:35:29 -08001062
1063 // Adjust vector bookkeeping.
Aart Bikb29f6842017-07-28 15:58:41 -07001064 HPhi* main_phi = nullptr;
1065 bool is_simple_loop_header = TrySetSimpleLoopHeader(header, &main_phi); // refills sets
Aart Bikf8f5a162017-02-06 15:35:29 -08001066 DCHECK(is_simple_loop_header);
Aart Bik14a68b42017-06-08 14:06:58 -07001067 vector_header_ = header;
1068 vector_body_ = block;
Aart Bikf8f5a162017-02-06 15:35:29 -08001069
Aart Bikdbbac8f2017-09-01 13:06:08 -07001070 // Loop induction type.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001071 DataType::Type induc_type = main_phi->GetType();
1072 DCHECK(induc_type == DataType::Type::kInt32 || induc_type == DataType::Type::kInt64)
1073 << induc_type;
Aart Bikdbbac8f2017-09-01 13:06:08 -07001074
Aart Bik38a3f212017-10-20 17:02:21 -07001075 // Generate the trip count for static or dynamic loop peeling, if needed:
1076 // ptc = <peeling factor>;
Aart Bik14a68b42017-06-08 14:06:58 -07001077 HInstruction* ptc = nullptr;
Aart Bik38a3f212017-10-20 17:02:21 -07001078 if (vector_static_peeling_factor_ != 0) {
1079 // Static loop peeling for SIMD alignment (using the most suitable
1080 // fixed peeling factor found during prior alignment analysis).
1081 DCHECK(vector_dynamic_peeling_candidate_ == nullptr);
1082 ptc = graph_->GetConstant(induc_type, vector_static_peeling_factor_);
1083 } else if (vector_dynamic_peeling_candidate_ != nullptr) {
1084 // Dynamic loop peeling for SIMD alignment (using the most suitable
1085 // candidate found during prior alignment analysis):
1086 // rem = offset % ALIGN; // adjusted as #elements
1087 // ptc = rem == 0 ? 0 : (ALIGN - rem);
1088 uint32_t shift = DataType::SizeShift(vector_dynamic_peeling_candidate_->type);
1089 uint32_t align = GetVectorSizeInBytes() >> shift;
1090 uint32_t hidden_offset = HiddenOffset(vector_dynamic_peeling_candidate_->type,
1091 vector_dynamic_peeling_candidate_->is_string_char_at);
1092 HInstruction* adjusted_offset = graph_->GetConstant(induc_type, hidden_offset >> shift);
1093 HInstruction* offset = Insert(preheader, new (global_allocator_) HAdd(
1094 induc_type, vector_dynamic_peeling_candidate_->offset, adjusted_offset));
1095 HInstruction* rem = Insert(preheader, new (global_allocator_) HAnd(
1096 induc_type, offset, graph_->GetConstant(induc_type, align - 1u)));
1097 HInstruction* sub = Insert(preheader, new (global_allocator_) HSub(
1098 induc_type, graph_->GetConstant(induc_type, align), rem));
1099 HInstruction* cond = Insert(preheader, new (global_allocator_) HEqual(
1100 rem, graph_->GetConstant(induc_type, 0)));
1101 ptc = Insert(preheader, new (global_allocator_) HSelect(
1102 cond, graph_->GetConstant(induc_type, 0), sub, kNoDexPc));
1103 needs_cleanup = true; // don't know the exact amount
Aart Bik14a68b42017-06-08 14:06:58 -07001104 }
1105
1106 // Generate loop control:
Aart Bikf8f5a162017-02-06 15:35:29 -08001107 // stc = <trip-count>;
Aart Bik38a3f212017-10-20 17:02:21 -07001108 // ptc = min(stc, ptc);
Aart Bik14a68b42017-06-08 14:06:58 -07001109 // vtc = stc - (stc - ptc) % chunk;
1110 // i = 0;
Aart Bikf8f5a162017-02-06 15:35:29 -08001111 HInstruction* stc = induction_range_.GenerateTripCount(node->loop_info, graph_, preheader);
1112 HInstruction* vtc = stc;
1113 if (needs_cleanup) {
Aart Bik14a68b42017-06-08 14:06:58 -07001114 DCHECK(IsPowerOfTwo(chunk));
1115 HInstruction* diff = stc;
1116 if (ptc != nullptr) {
Aart Bik38a3f212017-10-20 17:02:21 -07001117 if (trip_count == 0) {
1118 HInstruction* cond = Insert(preheader, new (global_allocator_) HAboveOrEqual(stc, ptc));
1119 ptc = Insert(preheader, new (global_allocator_) HSelect(cond, ptc, stc, kNoDexPc));
1120 }
Aart Bik14a68b42017-06-08 14:06:58 -07001121 diff = Insert(preheader, new (global_allocator_) HSub(induc_type, stc, ptc));
1122 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001123 HInstruction* rem = Insert(
1124 preheader, new (global_allocator_) HAnd(induc_type,
Aart Bik14a68b42017-06-08 14:06:58 -07001125 diff,
Aart Bikdbbac8f2017-09-01 13:06:08 -07001126 graph_->GetConstant(induc_type, chunk - 1)));
Aart Bikf8f5a162017-02-06 15:35:29 -08001127 vtc = Insert(preheader, new (global_allocator_) HSub(induc_type, stc, rem));
1128 }
Aart Bikdbbac8f2017-09-01 13:06:08 -07001129 vector_index_ = graph_->GetConstant(induc_type, 0);
Aart Bikf8f5a162017-02-06 15:35:29 -08001130
1131 // Generate runtime disambiguation test:
1132 // vtc = a != b ? vtc : 0;
1133 if (vector_runtime_test_a_ != nullptr) {
1134 HInstruction* rt = Insert(
1135 preheader,
1136 new (global_allocator_) HNotEqual(vector_runtime_test_a_, vector_runtime_test_b_));
1137 vtc = Insert(preheader,
Aart Bikdbbac8f2017-09-01 13:06:08 -07001138 new (global_allocator_)
1139 HSelect(rt, vtc, graph_->GetConstant(induc_type, 0), kNoDexPc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001140 needs_cleanup = true;
1141 }
1142
Aart Bik38a3f212017-10-20 17:02:21 -07001143 // Generate alignment peeling loop, if needed:
Aart Bik14a68b42017-06-08 14:06:58 -07001144 // for ( ; i < ptc; i += 1)
1145 // <loop-body>
Aart Bik38a3f212017-10-20 17:02:21 -07001146 //
1147 // NOTE: The alignment forced by the peeling loop is preserved even if data is
1148 // moved around during suspend checks, since all analysis was based on
1149 // nothing more than the Android runtime alignment conventions.
Aart Bik14a68b42017-06-08 14:06:58 -07001150 if (ptc != nullptr) {
1151 vector_mode_ = kSequential;
1152 GenerateNewLoop(node,
1153 block,
1154 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
1155 vector_index_,
1156 ptc,
Aart Bikdbbac8f2017-09-01 13:06:08 -07001157 graph_->GetConstant(induc_type, 1),
Artem Serov0e329082018-06-12 10:23:27 +01001158 LoopAnalysisInfo::kNoUnrollingFactor);
Aart Bik14a68b42017-06-08 14:06:58 -07001159 }
1160
1161 // Generate vector loop, possibly further unrolled:
1162 // for ( ; i < vtc; i += chunk)
Aart Bikf8f5a162017-02-06 15:35:29 -08001163 // <vectorized-loop-body>
1164 vector_mode_ = kVector;
1165 GenerateNewLoop(node,
1166 block,
Aart Bik14a68b42017-06-08 14:06:58 -07001167 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
1168 vector_index_,
Aart Bikf8f5a162017-02-06 15:35:29 -08001169 vtc,
Aart Bikdbbac8f2017-09-01 13:06:08 -07001170 graph_->GetConstant(induc_type, vector_length_), // increment per unroll
Aart Bik14a68b42017-06-08 14:06:58 -07001171 unroll);
Aart Bikf8f5a162017-02-06 15:35:29 -08001172 HLoopInformation* vloop = vector_header_->GetLoopInformation();
1173
1174 // Generate cleanup loop, if needed:
1175 // for ( ; i < stc; i += 1)
1176 // <loop-body>
1177 if (needs_cleanup) {
1178 vector_mode_ = kSequential;
1179 GenerateNewLoop(node,
1180 block,
1181 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
Aart Bik14a68b42017-06-08 14:06:58 -07001182 vector_index_,
Aart Bikf8f5a162017-02-06 15:35:29 -08001183 stc,
Aart Bikdbbac8f2017-09-01 13:06:08 -07001184 graph_->GetConstant(induc_type, 1),
Artem Serov0e329082018-06-12 10:23:27 +01001185 LoopAnalysisInfo::kNoUnrollingFactor);
Aart Bikf8f5a162017-02-06 15:35:29 -08001186 }
1187
Aart Bik0148de42017-09-05 09:25:01 -07001188 // Link reductions to their final uses.
1189 for (auto i = reductions_->begin(); i != reductions_->end(); ++i) {
1190 if (i->first->IsPhi()) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001191 HInstruction* phi = i->first;
1192 HInstruction* repl = ReduceAndExtractIfNeeded(i->second);
1193 // Deal with regular uses.
1194 for (const HUseListNode<HInstruction*>& use : phi->GetUses()) {
1195 induction_range_.Replace(use.GetUser(), phi, repl); // update induction use
1196 }
1197 phi->ReplaceWith(repl);
Aart Bik0148de42017-09-05 09:25:01 -07001198 }
1199 }
1200
Aart Bikf8f5a162017-02-06 15:35:29 -08001201 // Remove the original loop by disconnecting the body block
1202 // and removing all instructions from the header.
1203 block->DisconnectAndDelete();
1204 while (!header->GetFirstInstruction()->IsGoto()) {
1205 header->RemoveInstruction(header->GetFirstInstruction());
1206 }
Aart Bikb29f6842017-07-28 15:58:41 -07001207
Aart Bik14a68b42017-06-08 14:06:58 -07001208 // Update loop hierarchy: the old header now resides in the same outer loop
1209 // as the old preheader. Note that we don't bother putting sequential
1210 // loops back in the hierarchy at this point.
Aart Bikf8f5a162017-02-06 15:35:29 -08001211 header->SetLoopInformation(preheader->GetLoopInformation()); // outward
1212 node->loop_info = vloop;
1213}
1214
1215void HLoopOptimization::GenerateNewLoop(LoopNode* node,
1216 HBasicBlock* block,
1217 HBasicBlock* new_preheader,
1218 HInstruction* lo,
1219 HInstruction* hi,
Aart Bik14a68b42017-06-08 14:06:58 -07001220 HInstruction* step,
1221 uint32_t unroll) {
1222 DCHECK(unroll == 1 || vector_mode_ == kVector);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001223 DataType::Type induc_type = lo->GetType();
Aart Bikf8f5a162017-02-06 15:35:29 -08001224 // Prepare new loop.
Aart Bikf8f5a162017-02-06 15:35:29 -08001225 vector_preheader_ = new_preheader,
1226 vector_header_ = vector_preheader_->GetSingleSuccessor();
1227 vector_body_ = vector_header_->GetSuccessors()[1];
Aart Bik14a68b42017-06-08 14:06:58 -07001228 HPhi* phi = new (global_allocator_) HPhi(global_allocator_,
1229 kNoRegNumber,
1230 0,
1231 HPhi::ToPhiType(induc_type));
Aart Bikb07d1bc2017-04-05 10:03:15 -07001232 // Generate header and prepare body.
Aart Bikf8f5a162017-02-06 15:35:29 -08001233 // for (i = lo; i < hi; i += step)
1234 // <loop-body>
Aart Bik14a68b42017-06-08 14:06:58 -07001235 HInstruction* cond = new (global_allocator_) HAboveOrEqual(phi, hi);
1236 vector_header_->AddPhi(phi);
Aart Bikf8f5a162017-02-06 15:35:29 -08001237 vector_header_->AddInstruction(cond);
1238 vector_header_->AddInstruction(new (global_allocator_) HIf(cond));
Aart Bik14a68b42017-06-08 14:06:58 -07001239 vector_index_ = phi;
Aart Bik0148de42017-09-05 09:25:01 -07001240 vector_permanent_map_->clear(); // preserved over unrolling
Aart Bik14a68b42017-06-08 14:06:58 -07001241 for (uint32_t u = 0; u < unroll; u++) {
Aart Bik14a68b42017-06-08 14:06:58 -07001242 // Generate instruction map.
Aart Bik0148de42017-09-05 09:25:01 -07001243 vector_map_->clear();
Aart Bik14a68b42017-06-08 14:06:58 -07001244 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
1245 bool vectorized_def = VectorizeDef(node, it.Current(), /*generate_code*/ true);
1246 DCHECK(vectorized_def);
1247 }
1248 // Generate body from the instruction map, but in original program order.
1249 HEnvironment* env = vector_header_->GetFirstInstruction()->GetEnvironment();
1250 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
1251 auto i = vector_map_->find(it.Current());
1252 if (i != vector_map_->end() && !i->second->IsInBlock()) {
1253 Insert(vector_body_, i->second);
1254 // Deal with instructions that need an environment, such as the scalar intrinsics.
1255 if (i->second->NeedsEnvironment()) {
1256 i->second->CopyEnvironmentFromWithLoopPhiAdjustment(env, vector_header_);
1257 }
1258 }
1259 }
Aart Bik0148de42017-09-05 09:25:01 -07001260 // Generate the induction.
Aart Bik14a68b42017-06-08 14:06:58 -07001261 vector_index_ = new (global_allocator_) HAdd(induc_type, vector_index_, step);
1262 Insert(vector_body_, vector_index_);
Aart Bikf8f5a162017-02-06 15:35:29 -08001263 }
Aart Bik0148de42017-09-05 09:25:01 -07001264 // Finalize phi inputs for the reductions (if any).
1265 for (auto i = reductions_->begin(); i != reductions_->end(); ++i) {
1266 if (!i->first->IsPhi()) {
1267 DCHECK(i->second->IsPhi());
1268 GenerateVecReductionPhiInputs(i->second->AsPhi(), i->first);
1269 }
1270 }
Aart Bikb29f6842017-07-28 15:58:41 -07001271 // Finalize phi inputs for the loop index.
Aart Bik14a68b42017-06-08 14:06:58 -07001272 phi->AddInput(lo);
1273 phi->AddInput(vector_index_);
1274 vector_index_ = phi;
Aart Bikf8f5a162017-02-06 15:35:29 -08001275}
1276
Aart Bikf8f5a162017-02-06 15:35:29 -08001277bool HLoopOptimization::VectorizeDef(LoopNode* node,
1278 HInstruction* instruction,
1279 bool generate_code) {
1280 // Accept a left-hand-side array base[index] for
1281 // (1) supported vector type,
1282 // (2) loop-invariant base,
1283 // (3) unit stride index,
1284 // (4) vectorizable right-hand-side value.
1285 uint64_t restrictions = kNone;
Georgia Kouvelibac080b2019-01-31 16:12:16 +00001286 // Don't accept expressions that can throw.
1287 if (instruction->CanThrow()) {
1288 return false;
1289 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001290 if (instruction->IsArraySet()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001291 DataType::Type type = instruction->AsArraySet()->GetComponentType();
Aart Bikf8f5a162017-02-06 15:35:29 -08001292 HInstruction* base = instruction->InputAt(0);
1293 HInstruction* index = instruction->InputAt(1);
1294 HInstruction* value = instruction->InputAt(2);
1295 HInstruction* offset = nullptr;
Aart Bik6d057002018-04-09 15:39:58 -07001296 // For narrow types, explicit type conversion may have been
1297 // optimized way, so set the no hi bits restriction here.
1298 if (DataType::Size(type) <= 2) {
1299 restrictions |= kNoHiBits;
1300 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001301 if (TrySetVectorType(type, &restrictions) &&
1302 node->loop_info->IsDefinedOutOfTheLoop(base) &&
Aart Bik37dc4df2017-06-28 14:08:00 -07001303 induction_range_.IsUnitStride(instruction, index, graph_, &offset) &&
Aart Bikf8f5a162017-02-06 15:35:29 -08001304 VectorizeUse(node, value, generate_code, type, restrictions)) {
1305 if (generate_code) {
1306 GenerateVecSub(index, offset);
Aart Bik14a68b42017-06-08 14:06:58 -07001307 GenerateVecMem(instruction, vector_map_->Get(index), vector_map_->Get(value), offset, type);
Aart Bikf8f5a162017-02-06 15:35:29 -08001308 } else {
1309 vector_refs_->insert(ArrayReference(base, offset, type, /*lhs*/ true));
1310 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08001311 return true;
1312 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001313 return false;
1314 }
Aart Bik0148de42017-09-05 09:25:01 -07001315 // Accept a left-hand-side reduction for
1316 // (1) supported vector type,
1317 // (2) vectorizable right-hand-side value.
1318 auto redit = reductions_->find(instruction);
1319 if (redit != reductions_->end()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001320 DataType::Type type = instruction->GetType();
Aart Bikdbbac8f2017-09-01 13:06:08 -07001321 // Recognize SAD idiom or direct reduction.
1322 if (VectorizeSADIdiom(node, instruction, generate_code, type, restrictions) ||
Artem Serovaaac0e32018-08-07 00:52:22 +01001323 VectorizeDotProdIdiom(node, instruction, generate_code, type, restrictions) ||
Aart Bikdbbac8f2017-09-01 13:06:08 -07001324 (TrySetVectorType(type, &restrictions) &&
1325 VectorizeUse(node, instruction, generate_code, type, restrictions))) {
Aart Bik0148de42017-09-05 09:25:01 -07001326 if (generate_code) {
1327 HInstruction* new_red = vector_map_->Get(instruction);
1328 vector_permanent_map_->Put(new_red, vector_map_->Get(redit->second));
1329 vector_permanent_map_->Overwrite(redit->second, new_red);
1330 }
1331 return true;
1332 }
1333 return false;
1334 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001335 // Branch back okay.
1336 if (instruction->IsGoto()) {
1337 return true;
1338 }
1339 // Otherwise accept only expressions with no effects outside the immediate loop-body.
1340 // Note that actual uses are inspected during right-hand-side tree traversal.
Georgia Kouvelibac080b2019-01-31 16:12:16 +00001341 return !IsUsedOutsideLoop(node->loop_info, instruction)
1342 && !instruction->DoesAnyWrite();
Aart Bikf8f5a162017-02-06 15:35:29 -08001343}
1344
Aart Bikf8f5a162017-02-06 15:35:29 -08001345bool HLoopOptimization::VectorizeUse(LoopNode* node,
1346 HInstruction* instruction,
1347 bool generate_code,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001348 DataType::Type type,
Aart Bikf8f5a162017-02-06 15:35:29 -08001349 uint64_t restrictions) {
1350 // Accept anything for which code has already been generated.
1351 if (generate_code) {
1352 if (vector_map_->find(instruction) != vector_map_->end()) {
1353 return true;
1354 }
1355 }
1356 // Continue the right-hand-side tree traversal, passing in proper
1357 // types and vector restrictions along the way. During code generation,
1358 // all new nodes are drawn from the global allocator.
1359 if (node->loop_info->IsDefinedOutOfTheLoop(instruction)) {
1360 // Accept invariant use, using scalar expansion.
1361 if (generate_code) {
1362 GenerateVecInv(instruction, type);
1363 }
1364 return true;
1365 } else if (instruction->IsArrayGet()) {
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001366 // Deal with vector restrictions.
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001367 bool is_string_char_at = instruction->AsArrayGet()->IsStringCharAt();
1368 if (is_string_char_at && HasVectorRestrictions(restrictions, kNoStringCharAt)) {
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001369 return false;
1370 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001371 // Accept a right-hand-side array base[index] for
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001372 // (1) matching vector type (exact match or signed/unsigned integral type of the same size),
Aart Bikf8f5a162017-02-06 15:35:29 -08001373 // (2) loop-invariant base,
1374 // (3) unit stride index,
1375 // (4) vectorizable right-hand-side value.
1376 HInstruction* base = instruction->InputAt(0);
1377 HInstruction* index = instruction->InputAt(1);
1378 HInstruction* offset = nullptr;
Aart Bik46b6dbc2017-10-03 11:37:37 -07001379 if (HVecOperation::ToSignedType(type) == HVecOperation::ToSignedType(instruction->GetType()) &&
Aart Bikf8f5a162017-02-06 15:35:29 -08001380 node->loop_info->IsDefinedOutOfTheLoop(base) &&
Aart Bik37dc4df2017-06-28 14:08:00 -07001381 induction_range_.IsUnitStride(instruction, index, graph_, &offset)) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001382 if (generate_code) {
1383 GenerateVecSub(index, offset);
Aart Bik14a68b42017-06-08 14:06:58 -07001384 GenerateVecMem(instruction, vector_map_->Get(index), nullptr, offset, type);
Aart Bikf8f5a162017-02-06 15:35:29 -08001385 } else {
Aart Bik38a3f212017-10-20 17:02:21 -07001386 vector_refs_->insert(ArrayReference(base, offset, type, /*lhs*/ false, is_string_char_at));
Aart Bikf8f5a162017-02-06 15:35:29 -08001387 }
1388 return true;
1389 }
Aart Bik0148de42017-09-05 09:25:01 -07001390 } else if (instruction->IsPhi()) {
1391 // Accept particular phi operations.
1392 if (reductions_->find(instruction) != reductions_->end()) {
1393 // Deal with vector restrictions.
1394 if (HasVectorRestrictions(restrictions, kNoReduction)) {
1395 return false;
1396 }
1397 // Accept a reduction.
1398 if (generate_code) {
1399 GenerateVecReductionPhi(instruction->AsPhi());
1400 }
1401 return true;
1402 }
1403 // TODO: accept right-hand-side induction?
1404 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001405 } else if (instruction->IsTypeConversion()) {
1406 // Accept particular type conversions.
1407 HTypeConversion* conversion = instruction->AsTypeConversion();
1408 HInstruction* opa = conversion->InputAt(0);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001409 DataType::Type from = conversion->GetInputType();
1410 DataType::Type to = conversion->GetResultType();
1411 if (DataType::IsIntegralType(from) && DataType::IsIntegralType(to)) {
Aart Bik38a3f212017-10-20 17:02:21 -07001412 uint32_t size_vec = DataType::Size(type);
1413 uint32_t size_from = DataType::Size(from);
1414 uint32_t size_to = DataType::Size(to);
Aart Bikdbbac8f2017-09-01 13:06:08 -07001415 // Accept an integral conversion
1416 // (1a) narrowing into vector type, "wider" operations cannot bring in higher order bits, or
1417 // (1b) widening from at least vector type, and
1418 // (2) vectorizable operand.
1419 if ((size_to < size_from &&
1420 size_to == size_vec &&
1421 VectorizeUse(node, opa, generate_code, type, restrictions | kNoHiBits)) ||
1422 (size_to >= size_from &&
1423 size_from >= size_vec &&
Aart Bik4d1a9d42017-10-19 14:40:55 -07001424 VectorizeUse(node, opa, generate_code, type, restrictions))) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001425 if (generate_code) {
1426 if (vector_mode_ == kVector) {
1427 vector_map_->Put(instruction, vector_map_->Get(opa)); // operand pass-through
1428 } else {
1429 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1430 }
1431 }
1432 return true;
1433 }
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001434 } else if (to == DataType::Type::kFloat32 && from == DataType::Type::kInt32) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001435 DCHECK_EQ(to, type);
1436 // Accept int to float conversion for
1437 // (1) supported int,
1438 // (2) vectorizable operand.
1439 if (TrySetVectorType(from, &restrictions) &&
1440 VectorizeUse(node, opa, generate_code, from, restrictions)) {
1441 if (generate_code) {
1442 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1443 }
1444 return true;
1445 }
1446 }
1447 return false;
1448 } else if (instruction->IsNeg() || instruction->IsNot() || instruction->IsBooleanNot()) {
1449 // Accept unary operator for vectorizable operand.
1450 HInstruction* opa = instruction->InputAt(0);
1451 if (VectorizeUse(node, opa, generate_code, type, restrictions)) {
1452 if (generate_code) {
1453 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1454 }
1455 return true;
1456 }
1457 } else if (instruction->IsAdd() || instruction->IsSub() ||
1458 instruction->IsMul() || instruction->IsDiv() ||
1459 instruction->IsAnd() || instruction->IsOr() || instruction->IsXor()) {
1460 // Deal with vector restrictions.
1461 if ((instruction->IsMul() && HasVectorRestrictions(restrictions, kNoMul)) ||
1462 (instruction->IsDiv() && HasVectorRestrictions(restrictions, kNoDiv))) {
1463 return false;
1464 }
1465 // Accept binary operator for vectorizable operands.
1466 HInstruction* opa = instruction->InputAt(0);
1467 HInstruction* opb = instruction->InputAt(1);
1468 if (VectorizeUse(node, opa, generate_code, type, restrictions) &&
1469 VectorizeUse(node, opb, generate_code, type, restrictions)) {
1470 if (generate_code) {
1471 GenerateVecOp(instruction, vector_map_->Get(opa), vector_map_->Get(opb), type);
1472 }
1473 return true;
1474 }
1475 } else if (instruction->IsShl() || instruction->IsShr() || instruction->IsUShr()) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001476 // Recognize halving add idiom.
Aart Bikf3e61ee2017-04-12 17:09:20 -07001477 if (VectorizeHalvingAddIdiom(node, instruction, generate_code, type, restrictions)) {
1478 return true;
1479 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001480 // Deal with vector restrictions.
Aart Bik304c8a52017-05-23 11:01:13 -07001481 HInstruction* opa = instruction->InputAt(0);
1482 HInstruction* opb = instruction->InputAt(1);
1483 HInstruction* r = opa;
1484 bool is_unsigned = false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001485 if ((HasVectorRestrictions(restrictions, kNoShift)) ||
1486 (instruction->IsShr() && HasVectorRestrictions(restrictions, kNoShr))) {
1487 return false; // unsupported instruction
Aart Bik304c8a52017-05-23 11:01:13 -07001488 } else if (HasVectorRestrictions(restrictions, kNoHiBits)) {
1489 // Shifts right need extra care to account for higher order bits.
1490 // TODO: less likely shr/unsigned and ushr/signed can by flipping signess.
1491 if (instruction->IsShr() &&
1492 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || is_unsigned)) {
1493 return false; // reject, unless all operands are sign-extension narrower
1494 } else if (instruction->IsUShr() &&
1495 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || !is_unsigned)) {
1496 return false; // reject, unless all operands are zero-extension narrower
1497 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001498 }
1499 // Accept shift operator for vectorizable/invariant operands.
1500 // TODO: accept symbolic, albeit loop invariant shift factors.
Aart Bik304c8a52017-05-23 11:01:13 -07001501 DCHECK(r != nullptr);
1502 if (generate_code && vector_mode_ != kVector) { // de-idiom
1503 r = opa;
1504 }
Aart Bik50e20d52017-05-05 14:07:29 -07001505 int64_t distance = 0;
Aart Bik304c8a52017-05-23 11:01:13 -07001506 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
Aart Bik50e20d52017-05-05 14:07:29 -07001507 IsInt64AndGet(opb, /*out*/ &distance)) {
Aart Bik65ffd8e2017-05-01 16:50:45 -07001508 // Restrict shift distance to packed data type width.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001509 int64_t max_distance = DataType::Size(type) * 8;
Aart Bik65ffd8e2017-05-01 16:50:45 -07001510 if (0 <= distance && distance < max_distance) {
1511 if (generate_code) {
Aart Bik304c8a52017-05-23 11:01:13 -07001512 GenerateVecOp(instruction, vector_map_->Get(r), opb, type);
Aart Bik65ffd8e2017-05-01 16:50:45 -07001513 }
1514 return true;
Aart Bikf8f5a162017-02-06 15:35:29 -08001515 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001516 }
Aart Bik3b2a5952018-03-05 13:55:28 -08001517 } else if (instruction->IsAbs()) {
1518 // Deal with vector restrictions.
1519 HInstruction* opa = instruction->InputAt(0);
1520 HInstruction* r = opa;
1521 bool is_unsigned = false;
1522 if (HasVectorRestrictions(restrictions, kNoAbs)) {
1523 return false;
1524 } else if (HasVectorRestrictions(restrictions, kNoHiBits) &&
1525 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || is_unsigned)) {
1526 return false; // reject, unless operand is sign-extension narrower
1527 }
1528 // Accept ABS(x) for vectorizable operand.
1529 DCHECK(r != nullptr);
1530 if (generate_code && vector_mode_ != kVector) { // de-idiom
1531 r = opa;
1532 }
1533 if (VectorizeUse(node, r, generate_code, type, restrictions)) {
1534 if (generate_code) {
1535 GenerateVecOp(instruction,
1536 vector_map_->Get(r),
1537 nullptr,
1538 HVecOperation::ToProperType(type, is_unsigned));
1539 }
1540 return true;
1541 }
Aart Bik281c6812016-08-26 11:31:48 -07001542 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08001543 return false;
Aart Bik281c6812016-08-26 11:31:48 -07001544}
1545
Aart Bik38a3f212017-10-20 17:02:21 -07001546uint32_t HLoopOptimization::GetVectorSizeInBytes() {
Vladimir Markoa0431112018-06-25 09:32:54 +01001547 switch (compiler_options_->GetInstructionSet()) {
Vladimir Marko33bff252017-11-01 14:35:42 +00001548 case InstructionSet::kArm:
1549 case InstructionSet::kThumb2:
Aart Bik38a3f212017-10-20 17:02:21 -07001550 return 8; // 64-bit SIMD
1551 default:
1552 return 16; // 128-bit SIMD
1553 }
1554}
1555
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001556bool HLoopOptimization::TrySetVectorType(DataType::Type type, uint64_t* restrictions) {
Vladimir Markoa0431112018-06-25 09:32:54 +01001557 const InstructionSetFeatures* features = compiler_options_->GetInstructionSetFeatures();
1558 switch (compiler_options_->GetInstructionSet()) {
Vladimir Marko33bff252017-11-01 14:35:42 +00001559 case InstructionSet::kArm:
1560 case InstructionSet::kThumb2:
Artem Serov8f7c4102017-06-21 11:21:37 +01001561 // Allow vectorization for all ARM devices, because Android assumes that
Aart Bikb29f6842017-07-28 15:58:41 -07001562 // ARM 32-bit always supports advanced SIMD (64-bit SIMD).
Artem Serov8f7c4102017-06-21 11:21:37 +01001563 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001564 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001565 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001566 case DataType::Type::kInt8:
Artem Serovaaac0e32018-08-07 00:52:22 +01001567 *restrictions |= kNoDiv | kNoReduction | kNoDotProd;
Artem Serov8f7c4102017-06-21 11:21:37 +01001568 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001569 case DataType::Type::kUint16:
1570 case DataType::Type::kInt16:
Artem Serovaaac0e32018-08-07 00:52:22 +01001571 *restrictions |= kNoDiv | kNoStringCharAt | kNoReduction | kNoDotProd;
Artem Serov8f7c4102017-06-21 11:21:37 +01001572 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001573 case DataType::Type::kInt32:
Artem Serov6e9b1372017-10-05 16:48:30 +01001574 *restrictions |= kNoDiv | kNoWideSAD;
Artem Serov8f7c4102017-06-21 11:21:37 +01001575 return TrySetVectorLength(2);
1576 default:
1577 break;
1578 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001579 return false;
Vladimir Marko33bff252017-11-01 14:35:42 +00001580 case InstructionSet::kArm64:
Aart Bikf8f5a162017-02-06 15:35:29 -08001581 // Allow vectorization for all ARM devices, because Android assumes that
Aart Bikb29f6842017-07-28 15:58:41 -07001582 // ARMv8 AArch64 always supports advanced SIMD (128-bit SIMD).
Aart Bikf8f5a162017-02-06 15:35:29 -08001583 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001584 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001585 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001586 case DataType::Type::kInt8:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001587 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +01001588 return TrySetVectorLength(16);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001589 case DataType::Type::kUint16:
1590 case DataType::Type::kInt16:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001591 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +01001592 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001593 case DataType::Type::kInt32:
Aart Bikf8f5a162017-02-06 15:35:29 -08001594 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +01001595 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001596 case DataType::Type::kInt64:
Aart Bik3f08e9b2018-05-01 13:42:03 -07001597 *restrictions |= kNoDiv | kNoMul;
Aart Bikf8f5a162017-02-06 15:35:29 -08001598 return TrySetVectorLength(2);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001599 case DataType::Type::kFloat32:
Aart Bik0148de42017-09-05 09:25:01 -07001600 *restrictions |= kNoReduction;
Artem Serovd4bccf12017-04-03 18:47:32 +01001601 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001602 case DataType::Type::kFloat64:
Aart Bik0148de42017-09-05 09:25:01 -07001603 *restrictions |= kNoReduction;
Aart Bikf8f5a162017-02-06 15:35:29 -08001604 return TrySetVectorLength(2);
1605 default:
1606 return false;
1607 }
Vladimir Marko33bff252017-11-01 14:35:42 +00001608 case InstructionSet::kX86:
1609 case InstructionSet::kX86_64:
Aart Bikb29f6842017-07-28 15:58:41 -07001610 // Allow vectorization for SSE4.1-enabled X86 devices only (128-bit SIMD).
Aart Bikf8f5a162017-02-06 15:35:29 -08001611 if (features->AsX86InstructionSetFeatures()->HasSSE4_1()) {
1612 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001613 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001614 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001615 case DataType::Type::kInt8:
Artem Serovaaac0e32018-08-07 00:52:22 +01001616 *restrictions |= kNoMul |
1617 kNoDiv |
1618 kNoShift |
1619 kNoAbs |
1620 kNoSignedHAdd |
1621 kNoUnroundedHAdd |
1622 kNoSAD |
1623 kNoDotProd;
Aart Bikf8f5a162017-02-06 15:35:29 -08001624 return TrySetVectorLength(16);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001625 case DataType::Type::kUint16:
Alex Light43f2f752019-12-04 17:48:45 +00001626 *restrictions |= kNoDiv |
1627 kNoAbs |
1628 kNoSignedHAdd |
1629 kNoUnroundedHAdd |
1630 kNoSAD |
1631 kNoDotProd;
1632 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001633 case DataType::Type::kInt16:
Artem Serovaaac0e32018-08-07 00:52:22 +01001634 *restrictions |= kNoDiv |
1635 kNoAbs |
1636 kNoSignedHAdd |
1637 kNoUnroundedHAdd |
Alex Light43f2f752019-12-04 17:48:45 +00001638 kNoSAD;
Aart Bikf8f5a162017-02-06 15:35:29 -08001639 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001640 case DataType::Type::kInt32:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001641 *restrictions |= kNoDiv | kNoSAD;
Aart Bikf8f5a162017-02-06 15:35:29 -08001642 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001643 case DataType::Type::kInt64:
Aart Bik3f08e9b2018-05-01 13:42:03 -07001644 *restrictions |= kNoMul | kNoDiv | kNoShr | kNoAbs | kNoSAD;
Aart Bikf8f5a162017-02-06 15:35:29 -08001645 return TrySetVectorLength(2);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001646 case DataType::Type::kFloat32:
Aart Bik3f08e9b2018-05-01 13:42:03 -07001647 *restrictions |= kNoReduction;
Aart Bikf8f5a162017-02-06 15:35:29 -08001648 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001649 case DataType::Type::kFloat64:
Aart Bik3f08e9b2018-05-01 13:42:03 -07001650 *restrictions |= kNoReduction;
Aart Bikf8f5a162017-02-06 15:35:29 -08001651 return TrySetVectorLength(2);
1652 default:
1653 break;
1654 } // switch type
1655 }
1656 return false;
Vladimir Marko33bff252017-11-01 14:35:42 +00001657 case InstructionSet::kMips:
Lena Djokic51765b02017-06-22 13:49:59 +02001658 if (features->AsMipsInstructionSetFeatures()->HasMsa()) {
1659 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001660 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001661 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001662 case DataType::Type::kInt8:
Artem Serovaaac0e32018-08-07 00:52:22 +01001663 *restrictions |= kNoDiv | kNoDotProd;
Lena Djokic51765b02017-06-22 13:49:59 +02001664 return TrySetVectorLength(16);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001665 case DataType::Type::kUint16:
1666 case DataType::Type::kInt16:
Artem Serovaaac0e32018-08-07 00:52:22 +01001667 *restrictions |= kNoDiv | kNoStringCharAt | kNoDotProd;
Lena Djokic51765b02017-06-22 13:49:59 +02001668 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001669 case DataType::Type::kInt32:
Lena Djokic38e380b2017-10-30 16:17:10 +01001670 *restrictions |= kNoDiv;
Lena Djokic51765b02017-06-22 13:49:59 +02001671 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001672 case DataType::Type::kInt64:
Lena Djokic38e380b2017-10-30 16:17:10 +01001673 *restrictions |= kNoDiv;
Lena Djokic51765b02017-06-22 13:49:59 +02001674 return TrySetVectorLength(2);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001675 case DataType::Type::kFloat32:
Aart Bik3f08e9b2018-05-01 13:42:03 -07001676 *restrictions |= kNoReduction;
Lena Djokic51765b02017-06-22 13:49:59 +02001677 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001678 case DataType::Type::kFloat64:
Aart Bik3f08e9b2018-05-01 13:42:03 -07001679 *restrictions |= kNoReduction;
Lena Djokic51765b02017-06-22 13:49:59 +02001680 return TrySetVectorLength(2);
1681 default:
1682 break;
1683 } // switch type
1684 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001685 return false;
Vladimir Marko33bff252017-11-01 14:35:42 +00001686 case InstructionSet::kMips64:
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001687 if (features->AsMips64InstructionSetFeatures()->HasMsa()) {
1688 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001689 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001690 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001691 case DataType::Type::kInt8:
Artem Serovaaac0e32018-08-07 00:52:22 +01001692 *restrictions |= kNoDiv | kNoDotProd;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001693 return TrySetVectorLength(16);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001694 case DataType::Type::kUint16:
1695 case DataType::Type::kInt16:
Artem Serovaaac0e32018-08-07 00:52:22 +01001696 *restrictions |= kNoDiv | kNoStringCharAt | kNoDotProd;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001697 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001698 case DataType::Type::kInt32:
Lena Djokic38e380b2017-10-30 16:17:10 +01001699 *restrictions |= kNoDiv;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001700 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001701 case DataType::Type::kInt64:
Lena Djokic38e380b2017-10-30 16:17:10 +01001702 *restrictions |= kNoDiv;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001703 return TrySetVectorLength(2);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001704 case DataType::Type::kFloat32:
Aart Bik3f08e9b2018-05-01 13:42:03 -07001705 *restrictions |= kNoReduction;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001706 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001707 case DataType::Type::kFloat64:
Aart Bik3f08e9b2018-05-01 13:42:03 -07001708 *restrictions |= kNoReduction;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001709 return TrySetVectorLength(2);
1710 default:
1711 break;
1712 } // switch type
1713 }
1714 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001715 default:
1716 return false;
1717 } // switch instruction set
1718}
1719
1720bool HLoopOptimization::TrySetVectorLength(uint32_t length) {
1721 DCHECK(IsPowerOfTwo(length) && length >= 2u);
1722 // First time set?
1723 if (vector_length_ == 0) {
1724 vector_length_ = length;
1725 }
1726 // Different types are acceptable within a loop-body, as long as all the corresponding vector
1727 // lengths match exactly to obtain a uniform traversal through the vector iteration space
1728 // (idiomatic exceptions to this rule can be handled by further unrolling sub-expressions).
1729 return vector_length_ == length;
1730}
1731
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001732void HLoopOptimization::GenerateVecInv(HInstruction* org, DataType::Type type) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001733 if (vector_map_->find(org) == vector_map_->end()) {
1734 // In scalar code, just use a self pass-through for scalar invariants
1735 // (viz. expression remains itself).
1736 if (vector_mode_ == kSequential) {
1737 vector_map_->Put(org, org);
1738 return;
1739 }
1740 // In vector code, explicit scalar expansion is needed.
Aart Bik0148de42017-09-05 09:25:01 -07001741 HInstruction* vector = nullptr;
1742 auto it = vector_permanent_map_->find(org);
1743 if (it != vector_permanent_map_->end()) {
1744 vector = it->second; // reuse during unrolling
1745 } else {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001746 // Generates ReplicateScalar( (optional_type_conv) org ).
1747 HInstruction* input = org;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001748 DataType::Type input_type = input->GetType();
1749 if (type != input_type && (type == DataType::Type::kInt64 ||
1750 input_type == DataType::Type::kInt64)) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001751 input = Insert(vector_preheader_,
1752 new (global_allocator_) HTypeConversion(type, input, kNoDexPc));
1753 }
1754 vector = new (global_allocator_)
Aart Bik46b6dbc2017-10-03 11:37:37 -07001755 HVecReplicateScalar(global_allocator_, input, type, vector_length_, kNoDexPc);
Aart Bik0148de42017-09-05 09:25:01 -07001756 vector_permanent_map_->Put(org, Insert(vector_preheader_, vector));
1757 }
1758 vector_map_->Put(org, vector);
Aart Bikf8f5a162017-02-06 15:35:29 -08001759 }
1760}
1761
1762void HLoopOptimization::GenerateVecSub(HInstruction* org, HInstruction* offset) {
1763 if (vector_map_->find(org) == vector_map_->end()) {
Aart Bik14a68b42017-06-08 14:06:58 -07001764 HInstruction* subscript = vector_index_;
Aart Bik37dc4df2017-06-28 14:08:00 -07001765 int64_t value = 0;
1766 if (!IsInt64AndGet(offset, &value) || value != 0) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001767 subscript = new (global_allocator_) HAdd(DataType::Type::kInt32, subscript, offset);
Aart Bikf8f5a162017-02-06 15:35:29 -08001768 if (org->IsPhi()) {
1769 Insert(vector_body_, subscript); // lacks layout placeholder
1770 }
1771 }
1772 vector_map_->Put(org, subscript);
1773 }
1774}
1775
1776void HLoopOptimization::GenerateVecMem(HInstruction* org,
1777 HInstruction* opa,
1778 HInstruction* opb,
Aart Bik14a68b42017-06-08 14:06:58 -07001779 HInstruction* offset,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001780 DataType::Type type) {
Aart Bik46b6dbc2017-10-03 11:37:37 -07001781 uint32_t dex_pc = org->GetDexPc();
Aart Bikf8f5a162017-02-06 15:35:29 -08001782 HInstruction* vector = nullptr;
1783 if (vector_mode_ == kVector) {
1784 // Vector store or load.
Aart Bik38a3f212017-10-20 17:02:21 -07001785 bool is_string_char_at = false;
Aart Bik14a68b42017-06-08 14:06:58 -07001786 HInstruction* base = org->InputAt(0);
Aart Bikf8f5a162017-02-06 15:35:29 -08001787 if (opb != nullptr) {
1788 vector = new (global_allocator_) HVecStore(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001789 global_allocator_, base, opa, opb, type, org->GetSideEffects(), vector_length_, dex_pc);
Aart Bikf8f5a162017-02-06 15:35:29 -08001790 } else {
Aart Bik38a3f212017-10-20 17:02:21 -07001791 is_string_char_at = org->AsArrayGet()->IsStringCharAt();
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001792 vector = new (global_allocator_) HVecLoad(global_allocator_,
1793 base,
1794 opa,
1795 type,
1796 org->GetSideEffects(),
1797 vector_length_,
Aart Bik46b6dbc2017-10-03 11:37:37 -07001798 is_string_char_at,
1799 dex_pc);
Aart Bik14a68b42017-06-08 14:06:58 -07001800 }
Aart Bik38a3f212017-10-20 17:02:21 -07001801 // Known (forced/adjusted/original) alignment?
1802 if (vector_dynamic_peeling_candidate_ != nullptr) {
1803 if (vector_dynamic_peeling_candidate_->offset == offset && // TODO: diffs too?
1804 DataType::Size(vector_dynamic_peeling_candidate_->type) == DataType::Size(type) &&
1805 vector_dynamic_peeling_candidate_->is_string_char_at == is_string_char_at) {
1806 vector->AsVecMemoryOperation()->SetAlignment( // forced
1807 Alignment(GetVectorSizeInBytes(), 0));
1808 }
1809 } else {
1810 vector->AsVecMemoryOperation()->SetAlignment( // adjusted/original
1811 ComputeAlignment(offset, type, is_string_char_at, vector_static_peeling_factor_));
Aart Bikf8f5a162017-02-06 15:35:29 -08001812 }
1813 } else {
1814 // Scalar store or load.
1815 DCHECK(vector_mode_ == kSequential);
1816 if (opb != nullptr) {
Aart Bik4d1a9d42017-10-19 14:40:55 -07001817 DataType::Type component_type = org->AsArraySet()->GetComponentType();
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001818 vector = new (global_allocator_) HArraySet(
Aart Bik4d1a9d42017-10-19 14:40:55 -07001819 org->InputAt(0), opa, opb, component_type, org->GetSideEffects(), dex_pc);
Aart Bikf8f5a162017-02-06 15:35:29 -08001820 } else {
Aart Bikdb14fcf2017-04-25 15:53:58 -07001821 bool is_string_char_at = org->AsArrayGet()->IsStringCharAt();
1822 vector = new (global_allocator_) HArrayGet(
Aart Bik4d1a9d42017-10-19 14:40:55 -07001823 org->InputAt(0), opa, org->GetType(), org->GetSideEffects(), dex_pc, is_string_char_at);
Aart Bikf8f5a162017-02-06 15:35:29 -08001824 }
1825 }
1826 vector_map_->Put(org, vector);
1827}
1828
Aart Bik0148de42017-09-05 09:25:01 -07001829void HLoopOptimization::GenerateVecReductionPhi(HPhi* phi) {
1830 DCHECK(reductions_->find(phi) != reductions_->end());
1831 DCHECK(reductions_->Get(phi->InputAt(1)) == phi);
1832 HInstruction* vector = nullptr;
1833 if (vector_mode_ == kSequential) {
1834 HPhi* new_phi = new (global_allocator_) HPhi(
1835 global_allocator_, kNoRegNumber, 0, phi->GetType());
1836 vector_header_->AddPhi(new_phi);
1837 vector = new_phi;
1838 } else {
1839 // Link vector reduction back to prior unrolled update, or a first phi.
1840 auto it = vector_permanent_map_->find(phi);
1841 if (it != vector_permanent_map_->end()) {
1842 vector = it->second;
1843 } else {
1844 HPhi* new_phi = new (global_allocator_) HPhi(
1845 global_allocator_, kNoRegNumber, 0, HVecOperation::kSIMDType);
1846 vector_header_->AddPhi(new_phi);
1847 vector = new_phi;
1848 }
1849 }
1850 vector_map_->Put(phi, vector);
1851}
1852
1853void HLoopOptimization::GenerateVecReductionPhiInputs(HPhi* phi, HInstruction* reduction) {
1854 HInstruction* new_phi = vector_map_->Get(phi);
1855 HInstruction* new_init = reductions_->Get(phi);
1856 HInstruction* new_red = vector_map_->Get(reduction);
1857 // Link unrolled vector loop back to new phi.
1858 for (; !new_phi->IsPhi(); new_phi = vector_permanent_map_->Get(new_phi)) {
1859 DCHECK(new_phi->IsVecOperation());
1860 }
1861 // Prepare the new initialization.
1862 if (vector_mode_ == kVector) {
Goran Jakovljevic89b8df02017-10-13 08:33:17 +02001863 // Generate a [initial, 0, .., 0] vector for add or
1864 // a [initial, initial, .., initial] vector for min/max.
Aart Bikdbbac8f2017-09-01 13:06:08 -07001865 HVecOperation* red_vector = new_red->AsVecOperation();
Goran Jakovljevic89b8df02017-10-13 08:33:17 +02001866 HVecReduce::ReductionKind kind = GetReductionKind(red_vector);
Aart Bik38a3f212017-10-20 17:02:21 -07001867 uint32_t vector_length = red_vector->GetVectorLength();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001868 DataType::Type type = red_vector->GetPackedType();
Goran Jakovljevic89b8df02017-10-13 08:33:17 +02001869 if (kind == HVecReduce::ReductionKind::kSum) {
1870 new_init = Insert(vector_preheader_,
1871 new (global_allocator_) HVecSetScalars(global_allocator_,
1872 &new_init,
1873 type,
1874 vector_length,
1875 1,
1876 kNoDexPc));
1877 } else {
1878 new_init = Insert(vector_preheader_,
1879 new (global_allocator_) HVecReplicateScalar(global_allocator_,
1880 new_init,
1881 type,
1882 vector_length,
1883 kNoDexPc));
1884 }
Aart Bik0148de42017-09-05 09:25:01 -07001885 } else {
1886 new_init = ReduceAndExtractIfNeeded(new_init);
1887 }
1888 // Set the phi inputs.
1889 DCHECK(new_phi->IsPhi());
1890 new_phi->AsPhi()->AddInput(new_init);
1891 new_phi->AsPhi()->AddInput(new_red);
1892 // New feed value for next phi (safe mutation in iteration).
1893 reductions_->find(phi)->second = new_phi;
1894}
1895
1896HInstruction* HLoopOptimization::ReduceAndExtractIfNeeded(HInstruction* instruction) {
1897 if (instruction->IsPhi()) {
1898 HInstruction* input = instruction->InputAt(1);
Aart Bik2dd7b672017-12-07 11:11:22 -08001899 if (HVecOperation::ReturnsSIMDValue(input)) {
1900 DCHECK(!input->IsPhi());
Aart Bikdbbac8f2017-09-01 13:06:08 -07001901 HVecOperation* input_vector = input->AsVecOperation();
Aart Bik38a3f212017-10-20 17:02:21 -07001902 uint32_t vector_length = input_vector->GetVectorLength();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001903 DataType::Type type = input_vector->GetPackedType();
Aart Bikdbbac8f2017-09-01 13:06:08 -07001904 HVecReduce::ReductionKind kind = GetReductionKind(input_vector);
Aart Bik0148de42017-09-05 09:25:01 -07001905 HBasicBlock* exit = instruction->GetBlock()->GetSuccessors()[0];
1906 // Generate a vector reduction and scalar extract
1907 // x = REDUCE( [x_1, .., x_n] )
1908 // y = x_1
1909 // along the exit of the defining loop.
Aart Bik0148de42017-09-05 09:25:01 -07001910 HInstruction* reduce = new (global_allocator_) HVecReduce(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001911 global_allocator_, instruction, type, vector_length, kind, kNoDexPc);
Aart Bik0148de42017-09-05 09:25:01 -07001912 exit->InsertInstructionBefore(reduce, exit->GetFirstInstruction());
1913 instruction = new (global_allocator_) HVecExtractScalar(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001914 global_allocator_, reduce, type, vector_length, 0, kNoDexPc);
Aart Bik0148de42017-09-05 09:25:01 -07001915 exit->InsertInstructionAfter(instruction, reduce);
1916 }
1917 }
1918 return instruction;
1919}
1920
Aart Bikf8f5a162017-02-06 15:35:29 -08001921#define GENERATE_VEC(x, y) \
1922 if (vector_mode_ == kVector) { \
1923 vector = (x); \
1924 } else { \
1925 DCHECK(vector_mode_ == kSequential); \
1926 vector = (y); \
1927 } \
1928 break;
1929
1930void HLoopOptimization::GenerateVecOp(HInstruction* org,
1931 HInstruction* opa,
1932 HInstruction* opb,
Aart Bik3f08e9b2018-05-01 13:42:03 -07001933 DataType::Type type) {
Aart Bik46b6dbc2017-10-03 11:37:37 -07001934 uint32_t dex_pc = org->GetDexPc();
Aart Bikf8f5a162017-02-06 15:35:29 -08001935 HInstruction* vector = nullptr;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001936 DataType::Type org_type = org->GetType();
Aart Bikf8f5a162017-02-06 15:35:29 -08001937 switch (org->GetKind()) {
1938 case HInstruction::kNeg:
1939 DCHECK(opb == nullptr);
1940 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001941 new (global_allocator_) HVecNeg(global_allocator_, opa, type, vector_length_, dex_pc),
1942 new (global_allocator_) HNeg(org_type, opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001943 case HInstruction::kNot:
1944 DCHECK(opb == nullptr);
1945 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001946 new (global_allocator_) HVecNot(global_allocator_, opa, type, vector_length_, dex_pc),
1947 new (global_allocator_) HNot(org_type, opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001948 case HInstruction::kBooleanNot:
1949 DCHECK(opb == nullptr);
1950 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001951 new (global_allocator_) HVecNot(global_allocator_, opa, type, vector_length_, dex_pc),
1952 new (global_allocator_) HBooleanNot(opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001953 case HInstruction::kTypeConversion:
1954 DCHECK(opb == nullptr);
1955 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001956 new (global_allocator_) HVecCnv(global_allocator_, opa, type, vector_length_, dex_pc),
1957 new (global_allocator_) HTypeConversion(org_type, opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001958 case HInstruction::kAdd:
1959 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001960 new (global_allocator_) HVecAdd(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1961 new (global_allocator_) HAdd(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001962 case HInstruction::kSub:
1963 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001964 new (global_allocator_) HVecSub(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1965 new (global_allocator_) HSub(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001966 case HInstruction::kMul:
1967 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001968 new (global_allocator_) HVecMul(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1969 new (global_allocator_) HMul(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001970 case HInstruction::kDiv:
1971 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001972 new (global_allocator_) HVecDiv(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1973 new (global_allocator_) HDiv(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001974 case HInstruction::kAnd:
1975 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001976 new (global_allocator_) HVecAnd(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1977 new (global_allocator_) HAnd(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001978 case HInstruction::kOr:
1979 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001980 new (global_allocator_) HVecOr(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1981 new (global_allocator_) HOr(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001982 case HInstruction::kXor:
1983 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001984 new (global_allocator_) HVecXor(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1985 new (global_allocator_) HXor(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001986 case HInstruction::kShl:
1987 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001988 new (global_allocator_) HVecShl(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1989 new (global_allocator_) HShl(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001990 case HInstruction::kShr:
1991 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001992 new (global_allocator_) HVecShr(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1993 new (global_allocator_) HShr(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001994 case HInstruction::kUShr:
1995 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001996 new (global_allocator_) HVecUShr(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1997 new (global_allocator_) HUShr(org_type, opa, opb, dex_pc));
Aart Bik3b2a5952018-03-05 13:55:28 -08001998 case HInstruction::kAbs:
1999 DCHECK(opb == nullptr);
2000 GENERATE_VEC(
2001 new (global_allocator_) HVecAbs(global_allocator_, opa, type, vector_length_, dex_pc),
2002 new (global_allocator_) HAbs(org_type, opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08002003 default:
2004 break;
2005 } // switch
2006 CHECK(vector != nullptr) << "Unsupported SIMD operator";
2007 vector_map_->Put(org, vector);
2008}
2009
2010#undef GENERATE_VEC
2011
2012//
Aart Bikf3e61ee2017-04-12 17:09:20 -07002013// Vectorization idioms.
2014//
2015
2016// Method recognizes the following idioms:
Aart Bikdbbac8f2017-09-01 13:06:08 -07002017// rounding halving add (a + b + 1) >> 1 for unsigned/signed operands a, b
2018// truncated halving add (a + b) >> 1 for unsigned/signed operands a, b
Aart Bikf3e61ee2017-04-12 17:09:20 -07002019// Provided that the operands are promoted to a wider form to do the arithmetic and
2020// then cast back to narrower form, the idioms can be mapped into efficient SIMD
2021// implementation that operates directly in narrower form (plus one extra bit).
2022// TODO: current version recognizes implicit byte/short/char widening only;
2023// explicit widening from int to long could be added later.
2024bool HLoopOptimization::VectorizeHalvingAddIdiom(LoopNode* node,
2025 HInstruction* instruction,
2026 bool generate_code,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002027 DataType::Type type,
Aart Bikf3e61ee2017-04-12 17:09:20 -07002028 uint64_t restrictions) {
2029 // Test for top level arithmetic shift right x >> 1 or logical shift right x >>> 1
Aart Bik304c8a52017-05-23 11:01:13 -07002030 // (note whether the sign bit in wider precision is shifted in has no effect
Aart Bikf3e61ee2017-04-12 17:09:20 -07002031 // on the narrow precision computed by the idiom).
Aart Bikf3e61ee2017-04-12 17:09:20 -07002032 if ((instruction->IsShr() ||
2033 instruction->IsUShr()) &&
Aart Bik0148de42017-09-05 09:25:01 -07002034 IsInt64Value(instruction->InputAt(1), 1)) {
Aart Bik5f805002017-05-16 16:42:41 -07002035 // Test for (a + b + c) >> 1 for optional constant c.
2036 HInstruction* a = nullptr;
2037 HInstruction* b = nullptr;
2038 int64_t c = 0;
Nicolas Geoffraya3e23262018-03-28 11:15:12 +00002039 if (IsAddConst2(graph_, instruction->InputAt(0), /*out*/ &a, /*out*/ &b, /*out*/ &c)) {
Aart Bik5f805002017-05-16 16:42:41 -07002040 // Accept c == 1 (rounded) or c == 0 (not rounded).
2041 bool is_rounded = false;
2042 if (c == 1) {
2043 is_rounded = true;
2044 } else if (c != 0) {
2045 return false;
2046 }
2047 // Accept consistent zero or sign extension on operands a and b.
Aart Bikf3e61ee2017-04-12 17:09:20 -07002048 HInstruction* r = nullptr;
2049 HInstruction* s = nullptr;
2050 bool is_unsigned = false;
Aart Bik304c8a52017-05-23 11:01:13 -07002051 if (!IsNarrowerOperands(a, b, type, &r, &s, &is_unsigned)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -07002052 return false;
2053 }
2054 // Deal with vector restrictions.
2055 if ((!is_unsigned && HasVectorRestrictions(restrictions, kNoSignedHAdd)) ||
2056 (!is_rounded && HasVectorRestrictions(restrictions, kNoUnroundedHAdd))) {
2057 return false;
2058 }
2059 // Accept recognized halving add for vectorizable operands. Vectorized code uses the
2060 // shorthand idiomatic operation. Sequential code uses the original scalar expressions.
Nicolas Geoffraya3e23262018-03-28 11:15:12 +00002061 DCHECK(r != nullptr && s != nullptr);
Aart Bik304c8a52017-05-23 11:01:13 -07002062 if (generate_code && vector_mode_ != kVector) { // de-idiom
2063 r = instruction->InputAt(0);
2064 s = instruction->InputAt(1);
2065 }
Aart Bikf3e61ee2017-04-12 17:09:20 -07002066 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
2067 VectorizeUse(node, s, generate_code, type, restrictions)) {
2068 if (generate_code) {
2069 if (vector_mode_ == kVector) {
2070 vector_map_->Put(instruction, new (global_allocator_) HVecHalvingAdd(
2071 global_allocator_,
2072 vector_map_->Get(r),
2073 vector_map_->Get(s),
Aart Bik66c158e2018-01-31 12:55:04 -08002074 HVecOperation::ToProperType(type, is_unsigned),
Aart Bikf3e61ee2017-04-12 17:09:20 -07002075 vector_length_,
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01002076 is_rounded,
Aart Bik46b6dbc2017-10-03 11:37:37 -07002077 kNoDexPc));
Aart Bik21b85922017-09-06 13:29:16 -07002078 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorizedIdiom);
Aart Bikf3e61ee2017-04-12 17:09:20 -07002079 } else {
Aart Bik304c8a52017-05-23 11:01:13 -07002080 GenerateVecOp(instruction, vector_map_->Get(r), vector_map_->Get(s), type);
Aart Bikf3e61ee2017-04-12 17:09:20 -07002081 }
2082 }
2083 return true;
2084 }
2085 }
2086 }
2087 return false;
2088}
2089
Aart Bikdbbac8f2017-09-01 13:06:08 -07002090// Method recognizes the following idiom:
2091// q += ABS(a - b) for signed operands a, b
2092// Provided that the operands have the same type or are promoted to a wider form.
2093// Since this may involve a vector length change, the idiom is handled by going directly
2094// to a sad-accumulate node (rather than relying combining finer grained nodes later).
2095// TODO: unsigned SAD too?
2096bool HLoopOptimization::VectorizeSADIdiom(LoopNode* node,
2097 HInstruction* instruction,
2098 bool generate_code,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002099 DataType::Type reduction_type,
Aart Bikdbbac8f2017-09-01 13:06:08 -07002100 uint64_t restrictions) {
2101 // Filter integral "q += ABS(a - b);" reduction, where ABS and SUB
2102 // are done in the same precision (either int or long).
2103 if (!instruction->IsAdd() ||
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002104 (reduction_type != DataType::Type::kInt32 && reduction_type != DataType::Type::kInt64)) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07002105 return false;
2106 }
2107 HInstruction* q = instruction->InputAt(0);
2108 HInstruction* v = instruction->InputAt(1);
2109 HInstruction* a = nullptr;
2110 HInstruction* b = nullptr;
Nicolas Geoffraya3e23262018-03-28 11:15:12 +00002111 if (v->IsAbs() &&
2112 v->GetType() == reduction_type &&
2113 IsSubConst2(graph_, v->InputAt(0), /*out*/ &a, /*out*/ &b)) {
2114 DCHECK(a != nullptr && b != nullptr);
2115 } else {
Aart Bikdbbac8f2017-09-01 13:06:08 -07002116 return false;
2117 }
2118 // Accept same-type or consistent sign extension for narrower-type on operands a and b.
2119 // The same-type or narrower operands are called r (a or lower) and s (b or lower).
Aart Bikdf011c32017-09-28 12:53:04 -07002120 // We inspect the operands carefully to pick the most suited type.
Aart Bikdbbac8f2017-09-01 13:06:08 -07002121 HInstruction* r = a;
2122 HInstruction* s = b;
2123 bool is_unsigned = false;
Artem Serovaaac0e32018-08-07 00:52:22 +01002124 DataType::Type sub_type = GetNarrowerType(a, b);
Aart Bikdbbac8f2017-09-01 13:06:08 -07002125 if (reduction_type != sub_type &&
2126 (!IsNarrowerOperands(a, b, sub_type, &r, &s, &is_unsigned) || is_unsigned)) {
2127 return false;
2128 }
2129 // Try same/narrower type and deal with vector restrictions.
Artem Serov6e9b1372017-10-05 16:48:30 +01002130 if (!TrySetVectorType(sub_type, &restrictions) ||
2131 HasVectorRestrictions(restrictions, kNoSAD) ||
2132 (reduction_type != sub_type && HasVectorRestrictions(restrictions, kNoWideSAD))) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07002133 return false;
2134 }
2135 // Accept SAD idiom for vectorizable operands. Vectorized code uses the shorthand
2136 // idiomatic operation. Sequential code uses the original scalar expressions.
Nicolas Geoffraya3e23262018-03-28 11:15:12 +00002137 DCHECK(r != nullptr && s != nullptr);
Aart Bikdbbac8f2017-09-01 13:06:08 -07002138 if (generate_code && vector_mode_ != kVector) { // de-idiom
2139 r = s = v->InputAt(0);
2140 }
2141 if (VectorizeUse(node, q, generate_code, sub_type, restrictions) &&
2142 VectorizeUse(node, r, generate_code, sub_type, restrictions) &&
2143 VectorizeUse(node, s, generate_code, sub_type, restrictions)) {
2144 if (generate_code) {
2145 if (vector_mode_ == kVector) {
2146 vector_map_->Put(instruction, new (global_allocator_) HVecSADAccumulate(
2147 global_allocator_,
2148 vector_map_->Get(q),
2149 vector_map_->Get(r),
2150 vector_map_->Get(s),
Aart Bik3b2a5952018-03-05 13:55:28 -08002151 HVecOperation::ToProperType(reduction_type, is_unsigned),
Aart Bik46b6dbc2017-10-03 11:37:37 -07002152 GetOtherVL(reduction_type, sub_type, vector_length_),
2153 kNoDexPc));
Aart Bikdbbac8f2017-09-01 13:06:08 -07002154 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorizedIdiom);
2155 } else {
2156 GenerateVecOp(v, vector_map_->Get(r), nullptr, reduction_type);
2157 GenerateVecOp(instruction, vector_map_->Get(q), vector_map_->Get(v), reduction_type);
2158 }
2159 }
2160 return true;
2161 }
2162 return false;
2163}
2164
Artem Serovaaac0e32018-08-07 00:52:22 +01002165// Method recognises the following dot product idiom:
2166// q += a * b for operands a, b whose type is narrower than the reduction one.
2167// Provided that the operands have the same type or are promoted to a wider form.
2168// Since this may involve a vector length change, the idiom is handled by going directly
2169// to a dot product node (rather than relying combining finer grained nodes later).
2170bool HLoopOptimization::VectorizeDotProdIdiom(LoopNode* node,
2171 HInstruction* instruction,
2172 bool generate_code,
2173 DataType::Type reduction_type,
2174 uint64_t restrictions) {
Alex Light43f2f752019-12-04 17:48:45 +00002175 if (!instruction->IsAdd() || reduction_type != DataType::Type::kInt32) {
Artem Serovaaac0e32018-08-07 00:52:22 +01002176 return false;
2177 }
2178
2179 HInstruction* q = instruction->InputAt(0);
2180 HInstruction* v = instruction->InputAt(1);
2181 if (!v->IsMul() || v->GetType() != reduction_type) {
2182 return false;
2183 }
2184
2185 HInstruction* a = v->InputAt(0);
2186 HInstruction* b = v->InputAt(1);
2187 HInstruction* r = a;
2188 HInstruction* s = b;
2189 DataType::Type op_type = GetNarrowerType(a, b);
2190 bool is_unsigned = false;
2191
2192 if (!IsNarrowerOperands(a, b, op_type, &r, &s, &is_unsigned)) {
2193 return false;
2194 }
2195 op_type = HVecOperation::ToProperType(op_type, is_unsigned);
2196
2197 if (!TrySetVectorType(op_type, &restrictions) ||
2198 HasVectorRestrictions(restrictions, kNoDotProd)) {
2199 return false;
2200 }
2201
2202 DCHECK(r != nullptr && s != nullptr);
2203 // Accept dot product idiom for vectorizable operands. Vectorized code uses the shorthand
2204 // idiomatic operation. Sequential code uses the original scalar expressions.
2205 if (generate_code && vector_mode_ != kVector) { // de-idiom
2206 r = a;
2207 s = b;
2208 }
2209 if (VectorizeUse(node, q, generate_code, op_type, restrictions) &&
2210 VectorizeUse(node, r, generate_code, op_type, restrictions) &&
2211 VectorizeUse(node, s, generate_code, op_type, restrictions)) {
2212 if (generate_code) {
2213 if (vector_mode_ == kVector) {
2214 vector_map_->Put(instruction, new (global_allocator_) HVecDotProd(
2215 global_allocator_,
2216 vector_map_->Get(q),
2217 vector_map_->Get(r),
2218 vector_map_->Get(s),
2219 reduction_type,
2220 is_unsigned,
2221 GetOtherVL(reduction_type, op_type, vector_length_),
2222 kNoDexPc));
2223 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorizedIdiom);
2224 } else {
2225 GenerateVecOp(v, vector_map_->Get(r), vector_map_->Get(s), reduction_type);
2226 GenerateVecOp(instruction, vector_map_->Get(q), vector_map_->Get(v), reduction_type);
2227 }
2228 }
2229 return true;
2230 }
2231 return false;
2232}
2233
Aart Bikf3e61ee2017-04-12 17:09:20 -07002234//
Aart Bik14a68b42017-06-08 14:06:58 -07002235// Vectorization heuristics.
2236//
2237
Aart Bik38a3f212017-10-20 17:02:21 -07002238Alignment HLoopOptimization::ComputeAlignment(HInstruction* offset,
2239 DataType::Type type,
2240 bool is_string_char_at,
2241 uint32_t peeling) {
2242 // Combine the alignment and hidden offset that is guaranteed by
2243 // the Android runtime with a known starting index adjusted as bytes.
2244 int64_t value = 0;
2245 if (IsInt64AndGet(offset, /*out*/ &value)) {
2246 uint32_t start_offset =
2247 HiddenOffset(type, is_string_char_at) + (value + peeling) * DataType::Size(type);
2248 return Alignment(BaseAlignment(), start_offset & (BaseAlignment() - 1u));
2249 }
2250 // Otherwise, the Android runtime guarantees at least natural alignment.
2251 return Alignment(DataType::Size(type), 0);
2252}
2253
2254void HLoopOptimization::SetAlignmentStrategy(uint32_t peeling_votes[],
2255 const ArrayReference* peeling_candidate) {
2256 // Current heuristic: pick the best static loop peeling factor, if any,
2257 // or otherwise use dynamic loop peeling on suggested peeling candidate.
2258 uint32_t max_vote = 0;
2259 for (int32_t i = 0; i < 16; i++) {
2260 if (peeling_votes[i] > max_vote) {
2261 max_vote = peeling_votes[i];
2262 vector_static_peeling_factor_ = i;
2263 }
2264 }
2265 if (max_vote == 0) {
2266 vector_dynamic_peeling_candidate_ = peeling_candidate;
2267 }
2268}
2269
2270uint32_t HLoopOptimization::MaxNumberPeeled() {
2271 if (vector_dynamic_peeling_candidate_ != nullptr) {
2272 return vector_length_ - 1u; // worst-case
2273 }
2274 return vector_static_peeling_factor_; // known exactly
2275}
2276
Aart Bik14a68b42017-06-08 14:06:58 -07002277bool HLoopOptimization::IsVectorizationProfitable(int64_t trip_count) {
Aart Bik38a3f212017-10-20 17:02:21 -07002278 // Current heuristic: non-empty body with sufficient number of iterations (if known).
Aart Bik14a68b42017-06-08 14:06:58 -07002279 // TODO: refine by looking at e.g. operation count, alignment, etc.
Aart Bik38a3f212017-10-20 17:02:21 -07002280 // TODO: trip count is really unsigned entity, provided the guarding test
2281 // is satisfied; deal with this more carefully later
2282 uint32_t max_peel = MaxNumberPeeled();
Aart Bik14a68b42017-06-08 14:06:58 -07002283 if (vector_length_ == 0) {
2284 return false; // nothing found
Aart Bik38a3f212017-10-20 17:02:21 -07002285 } else if (trip_count < 0) {
2286 return false; // guard against non-taken/large
2287 } else if ((0 < trip_count) && (trip_count < (vector_length_ + max_peel))) {
Aart Bik14a68b42017-06-08 14:06:58 -07002288 return false; // insufficient iterations
2289 }
2290 return true;
2291}
2292
Aart Bik14a68b42017-06-08 14:06:58 -07002293//
Aart Bikf8f5a162017-02-06 15:35:29 -08002294// Helpers.
2295//
2296
2297bool HLoopOptimization::TrySetPhiInduction(HPhi* phi, bool restrict_uses) {
Aart Bikb29f6842017-07-28 15:58:41 -07002298 // Start with empty phi induction.
2299 iset_->clear();
2300
Nicolas Geoffrayf57c1ae2017-06-28 17:40:18 +01002301 // Special case Phis that have equivalent in a debuggable setup. Our graph checker isn't
2302 // smart enough to follow strongly connected components (and it's probably not worth
2303 // it to make it so). See b/33775412.
2304 if (graph_->IsDebuggable() && phi->HasEquivalentPhi()) {
2305 return false;
2306 }
Aart Bikb29f6842017-07-28 15:58:41 -07002307
2308 // Lookup phi induction cycle.
Aart Bikcc42be02016-10-20 16:14:16 -07002309 ArenaSet<HInstruction*>* set = induction_range_.LookupCycle(phi);
2310 if (set != nullptr) {
2311 for (HInstruction* i : *set) {
Aart Bike3dedc52016-11-02 17:50:27 -07002312 // Check that, other than instructions that are no longer in the graph (removed earlier)
Aart Bikf8f5a162017-02-06 15:35:29 -08002313 // each instruction is removable and, when restrict uses are requested, other than for phi,
2314 // all uses are contained within the cycle.
Aart Bike3dedc52016-11-02 17:50:27 -07002315 if (!i->IsInBlock()) {
2316 continue;
2317 } else if (!i->IsRemovable()) {
2318 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08002319 } else if (i != phi && restrict_uses) {
Aart Bikb29f6842017-07-28 15:58:41 -07002320 // Deal with regular uses.
Aart Bikcc42be02016-10-20 16:14:16 -07002321 for (const HUseListNode<HInstruction*>& use : i->GetUses()) {
2322 if (set->find(use.GetUser()) == set->end()) {
2323 return false;
2324 }
2325 }
2326 }
Aart Bike3dedc52016-11-02 17:50:27 -07002327 iset_->insert(i); // copy
Aart Bikcc42be02016-10-20 16:14:16 -07002328 }
Aart Bikcc42be02016-10-20 16:14:16 -07002329 return true;
2330 }
2331 return false;
2332}
2333
Aart Bikb29f6842017-07-28 15:58:41 -07002334bool HLoopOptimization::TrySetPhiReduction(HPhi* phi) {
Aart Bikcc42be02016-10-20 16:14:16 -07002335 DCHECK(iset_->empty());
Aart Bikb29f6842017-07-28 15:58:41 -07002336 // Only unclassified phi cycles are candidates for reductions.
2337 if (induction_range_.IsClassified(phi)) {
2338 return false;
2339 }
2340 // Accept operations like x = x + .., provided that the phi and the reduction are
2341 // used exactly once inside the loop, and by each other.
2342 HInputsRef inputs = phi->GetInputs();
2343 if (inputs.size() == 2) {
2344 HInstruction* reduction = inputs[1];
2345 if (HasReductionFormat(reduction, phi)) {
2346 HLoopInformation* loop_info = phi->GetBlock()->GetLoopInformation();
Aart Bik38a3f212017-10-20 17:02:21 -07002347 uint32_t use_count = 0;
Aart Bikb29f6842017-07-28 15:58:41 -07002348 bool single_use_inside_loop =
2349 // Reduction update only used by phi.
2350 reduction->GetUses().HasExactlyOneElement() &&
2351 !reduction->HasEnvironmentUses() &&
2352 // Reduction update is only use of phi inside the loop.
2353 IsOnlyUsedAfterLoop(loop_info, phi, /*collect_loop_uses*/ true, &use_count) &&
2354 iset_->size() == 1;
2355 iset_->clear(); // leave the way you found it
2356 if (single_use_inside_loop) {
2357 // Link reduction back, and start recording feed value.
2358 reductions_->Put(reduction, phi);
2359 reductions_->Put(phi, phi->InputAt(0));
2360 return true;
2361 }
2362 }
2363 }
2364 return false;
2365}
2366
2367bool HLoopOptimization::TrySetSimpleLoopHeader(HBasicBlock* block, /*out*/ HPhi** main_phi) {
2368 // Start with empty phi induction and reductions.
2369 iset_->clear();
2370 reductions_->clear();
2371
2372 // Scan the phis to find the following (the induction structure has already
2373 // been optimized, so we don't need to worry about trivial cases):
2374 // (1) optional reductions in loop,
2375 // (2) the main induction, used in loop control.
2376 HPhi* phi = nullptr;
2377 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
2378 if (TrySetPhiReduction(it.Current()->AsPhi())) {
2379 continue;
2380 } else if (phi == nullptr) {
2381 // Found the first candidate for main induction.
2382 phi = it.Current()->AsPhi();
2383 } else {
2384 return false;
2385 }
2386 }
2387
2388 // Then test for a typical loopheader:
2389 // s: SuspendCheck
2390 // c: Condition(phi, bound)
2391 // i: If(c)
2392 if (phi != nullptr && TrySetPhiInduction(phi, /*restrict_uses*/ false)) {
Aart Bikcc42be02016-10-20 16:14:16 -07002393 HInstruction* s = block->GetFirstInstruction();
2394 if (s != nullptr && s->IsSuspendCheck()) {
2395 HInstruction* c = s->GetNext();
Aart Bikd86c0852017-04-14 12:00:15 -07002396 if (c != nullptr &&
2397 c->IsCondition() &&
2398 c->GetUses().HasExactlyOneElement() && // only used for termination
2399 !c->HasEnvironmentUses()) { // unlikely, but not impossible
Aart Bikcc42be02016-10-20 16:14:16 -07002400 HInstruction* i = c->GetNext();
2401 if (i != nullptr && i->IsIf() && i->InputAt(0) == c) {
2402 iset_->insert(c);
2403 iset_->insert(s);
Aart Bikb29f6842017-07-28 15:58:41 -07002404 *main_phi = phi;
Aart Bikcc42be02016-10-20 16:14:16 -07002405 return true;
2406 }
2407 }
2408 }
2409 }
2410 return false;
2411}
2412
2413bool HLoopOptimization::IsEmptyBody(HBasicBlock* block) {
Aart Bikf8f5a162017-02-06 15:35:29 -08002414 if (!block->GetPhis().IsEmpty()) {
2415 return false;
2416 }
2417 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
2418 HInstruction* instruction = it.Current();
2419 if (!instruction->IsGoto() && iset_->find(instruction) == iset_->end()) {
2420 return false;
Aart Bikcc42be02016-10-20 16:14:16 -07002421 }
Aart Bikf8f5a162017-02-06 15:35:29 -08002422 }
2423 return true;
2424}
2425
2426bool HLoopOptimization::IsUsedOutsideLoop(HLoopInformation* loop_info,
2427 HInstruction* instruction) {
Aart Bikb29f6842017-07-28 15:58:41 -07002428 // Deal with regular uses.
Aart Bikf8f5a162017-02-06 15:35:29 -08002429 for (const HUseListNode<HInstruction*>& use : instruction->GetUses()) {
2430 if (use.GetUser()->GetBlock()->GetLoopInformation() != loop_info) {
2431 return true;
2432 }
Aart Bikcc42be02016-10-20 16:14:16 -07002433 }
2434 return false;
2435}
2436
Aart Bik482095d2016-10-10 15:39:10 -07002437bool HLoopOptimization::IsOnlyUsedAfterLoop(HLoopInformation* loop_info,
Aart Bik8c4a8542016-10-06 11:36:57 -07002438 HInstruction* instruction,
Aart Bik6b69e0a2017-01-11 10:20:43 -08002439 bool collect_loop_uses,
Aart Bik38a3f212017-10-20 17:02:21 -07002440 /*out*/ uint32_t* use_count) {
Aart Bikb29f6842017-07-28 15:58:41 -07002441 // Deal with regular uses.
Aart Bik8c4a8542016-10-06 11:36:57 -07002442 for (const HUseListNode<HInstruction*>& use : instruction->GetUses()) {
2443 HInstruction* user = use.GetUser();
2444 if (iset_->find(user) == iset_->end()) { // not excluded?
2445 HLoopInformation* other_loop_info = user->GetBlock()->GetLoopInformation();
Aart Bik482095d2016-10-10 15:39:10 -07002446 if (other_loop_info != nullptr && other_loop_info->IsIn(*loop_info)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -08002447 // If collect_loop_uses is set, simply keep adding those uses to the set.
2448 // Otherwise, reject uses inside the loop that were not already in the set.
2449 if (collect_loop_uses) {
2450 iset_->insert(user);
2451 continue;
2452 }
Aart Bik8c4a8542016-10-06 11:36:57 -07002453 return false;
2454 }
2455 ++*use_count;
2456 }
2457 }
2458 return true;
2459}
2460
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002461bool HLoopOptimization::TryReplaceWithLastValue(HLoopInformation* loop_info,
2462 HInstruction* instruction,
2463 HBasicBlock* block) {
2464 // Try to replace outside uses with the last value.
Aart Bik807868e2016-11-03 17:51:43 -07002465 if (induction_range_.CanGenerateLastValue(instruction)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -08002466 HInstruction* replacement = induction_range_.GenerateLastValue(instruction, graph_, block);
Aart Bikb29f6842017-07-28 15:58:41 -07002467 // Deal with regular uses.
Aart Bik6b69e0a2017-01-11 10:20:43 -08002468 const HUseList<HInstruction*>& uses = instruction->GetUses();
2469 for (auto it = uses.begin(), end = uses.end(); it != end;) {
2470 HInstruction* user = it->GetUser();
2471 size_t index = it->GetIndex();
2472 ++it; // increment before replacing
2473 if (iset_->find(user) == iset_->end()) { // not excluded?
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002474 if (kIsDebugBuild) {
2475 // We have checked earlier in 'IsOnlyUsedAfterLoop' that the use is after the loop.
2476 HLoopInformation* other_loop_info = user->GetBlock()->GetLoopInformation();
2477 CHECK(other_loop_info == nullptr || !other_loop_info->IsIn(*loop_info));
2478 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08002479 user->ReplaceInput(replacement, index);
2480 induction_range_.Replace(user, instruction, replacement); // update induction
2481 }
2482 }
Aart Bikb29f6842017-07-28 15:58:41 -07002483 // Deal with environment uses.
Aart Bik6b69e0a2017-01-11 10:20:43 -08002484 const HUseList<HEnvironment*>& env_uses = instruction->GetEnvUses();
2485 for (auto it = env_uses.begin(), end = env_uses.end(); it != end;) {
2486 HEnvironment* user = it->GetUser();
2487 size_t index = it->GetIndex();
2488 ++it; // increment before replacing
2489 if (iset_->find(user->GetHolder()) == iset_->end()) { // not excluded?
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002490 // Only update environment uses after the loop.
Aart Bik14a68b42017-06-08 14:06:58 -07002491 HLoopInformation* other_loop_info = user->GetHolder()->GetBlock()->GetLoopInformation();
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002492 if (other_loop_info == nullptr || !other_loop_info->IsIn(*loop_info)) {
2493 user->RemoveAsUserOfInput(index);
2494 user->SetRawEnvAt(index, replacement);
2495 replacement->AddEnvUseAt(user, index);
2496 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08002497 }
2498 }
Aart Bik807868e2016-11-03 17:51:43 -07002499 return true;
Aart Bik8c4a8542016-10-06 11:36:57 -07002500 }
Aart Bik807868e2016-11-03 17:51:43 -07002501 return false;
Aart Bik8c4a8542016-10-06 11:36:57 -07002502}
2503
Aart Bikf8f5a162017-02-06 15:35:29 -08002504bool HLoopOptimization::TryAssignLastValue(HLoopInformation* loop_info,
2505 HInstruction* instruction,
2506 HBasicBlock* block,
2507 bool collect_loop_uses) {
2508 // Assigning the last value is always successful if there are no uses.
2509 // Otherwise, it succeeds in a no early-exit loop by generating the
2510 // proper last value assignment.
Aart Bik38a3f212017-10-20 17:02:21 -07002511 uint32_t use_count = 0;
Aart Bikf8f5a162017-02-06 15:35:29 -08002512 return IsOnlyUsedAfterLoop(loop_info, instruction, collect_loop_uses, &use_count) &&
2513 (use_count == 0 ||
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002514 (!IsEarlyExit(loop_info) && TryReplaceWithLastValue(loop_info, instruction, block)));
Aart Bikf8f5a162017-02-06 15:35:29 -08002515}
2516
Aart Bik6b69e0a2017-01-11 10:20:43 -08002517void HLoopOptimization::RemoveDeadInstructions(const HInstructionList& list) {
2518 for (HBackwardInstructionIterator i(list); !i.Done(); i.Advance()) {
2519 HInstruction* instruction = i.Current();
2520 if (instruction->IsDeadAndRemovable()) {
2521 simplified_ = true;
2522 instruction->GetBlock()->RemoveInstructionOrPhi(instruction);
2523 }
2524 }
2525}
2526
Aart Bik14a68b42017-06-08 14:06:58 -07002527bool HLoopOptimization::CanRemoveCycle() {
2528 for (HInstruction* i : *iset_) {
2529 // We can never remove instructions that have environment
2530 // uses when we compile 'debuggable'.
2531 if (i->HasEnvironmentUses() && graph_->IsDebuggable()) {
2532 return false;
2533 }
2534 // A deoptimization should never have an environment input removed.
2535 for (const HUseListNode<HEnvironment*>& use : i->GetEnvUses()) {
2536 if (use.GetUser()->GetHolder()->IsDeoptimize()) {
2537 return false;
2538 }
2539 }
2540 }
2541 return true;
2542}
2543
Aart Bik281c6812016-08-26 11:31:48 -07002544} // namespace art