blob: 3e1c42c8d90db336d328207b184b3203801a6509 [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
31namespace art {
32
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;
1286 if (instruction->IsArraySet()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001287 DataType::Type type = instruction->AsArraySet()->GetComponentType();
Aart Bikf8f5a162017-02-06 15:35:29 -08001288 HInstruction* base = instruction->InputAt(0);
1289 HInstruction* index = instruction->InputAt(1);
1290 HInstruction* value = instruction->InputAt(2);
1291 HInstruction* offset = nullptr;
Aart Bik6d057002018-04-09 15:39:58 -07001292 // For narrow types, explicit type conversion may have been
1293 // optimized way, so set the no hi bits restriction here.
1294 if (DataType::Size(type) <= 2) {
1295 restrictions |= kNoHiBits;
1296 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001297 if (TrySetVectorType(type, &restrictions) &&
1298 node->loop_info->IsDefinedOutOfTheLoop(base) &&
Aart Bik37dc4df2017-06-28 14:08:00 -07001299 induction_range_.IsUnitStride(instruction, index, graph_, &offset) &&
Aart Bikf8f5a162017-02-06 15:35:29 -08001300 VectorizeUse(node, value, generate_code, type, restrictions)) {
1301 if (generate_code) {
1302 GenerateVecSub(index, offset);
Aart Bik14a68b42017-06-08 14:06:58 -07001303 GenerateVecMem(instruction, vector_map_->Get(index), vector_map_->Get(value), offset, type);
Aart Bikf8f5a162017-02-06 15:35:29 -08001304 } else {
1305 vector_refs_->insert(ArrayReference(base, offset, type, /*lhs*/ true));
1306 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08001307 return true;
1308 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001309 return false;
1310 }
Aart Bik0148de42017-09-05 09:25:01 -07001311 // Accept a left-hand-side reduction for
1312 // (1) supported vector type,
1313 // (2) vectorizable right-hand-side value.
1314 auto redit = reductions_->find(instruction);
1315 if (redit != reductions_->end()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001316 DataType::Type type = instruction->GetType();
Aart Bikdbbac8f2017-09-01 13:06:08 -07001317 // Recognize SAD idiom or direct reduction.
1318 if (VectorizeSADIdiom(node, instruction, generate_code, type, restrictions) ||
Artem Serovaaac0e32018-08-07 00:52:22 +01001319 VectorizeDotProdIdiom(node, instruction, generate_code, type, restrictions) ||
Aart Bikdbbac8f2017-09-01 13:06:08 -07001320 (TrySetVectorType(type, &restrictions) &&
1321 VectorizeUse(node, instruction, generate_code, type, restrictions))) {
Aart Bik0148de42017-09-05 09:25:01 -07001322 if (generate_code) {
1323 HInstruction* new_red = vector_map_->Get(instruction);
1324 vector_permanent_map_->Put(new_red, vector_map_->Get(redit->second));
1325 vector_permanent_map_->Overwrite(redit->second, new_red);
1326 }
1327 return true;
1328 }
1329 return false;
1330 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001331 // Branch back okay.
1332 if (instruction->IsGoto()) {
1333 return true;
1334 }
1335 // Otherwise accept only expressions with no effects outside the immediate loop-body.
1336 // Note that actual uses are inspected during right-hand-side tree traversal.
1337 return !IsUsedOutsideLoop(node->loop_info, instruction) && !instruction->DoesAnyWrite();
1338}
1339
Aart Bikf8f5a162017-02-06 15:35:29 -08001340bool HLoopOptimization::VectorizeUse(LoopNode* node,
1341 HInstruction* instruction,
1342 bool generate_code,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001343 DataType::Type type,
Aart Bikf8f5a162017-02-06 15:35:29 -08001344 uint64_t restrictions) {
1345 // Accept anything for which code has already been generated.
1346 if (generate_code) {
1347 if (vector_map_->find(instruction) != vector_map_->end()) {
1348 return true;
1349 }
1350 }
1351 // Continue the right-hand-side tree traversal, passing in proper
1352 // types and vector restrictions along the way. During code generation,
1353 // all new nodes are drawn from the global allocator.
1354 if (node->loop_info->IsDefinedOutOfTheLoop(instruction)) {
1355 // Accept invariant use, using scalar expansion.
1356 if (generate_code) {
1357 GenerateVecInv(instruction, type);
1358 }
1359 return true;
1360 } else if (instruction->IsArrayGet()) {
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001361 // Deal with vector restrictions.
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001362 bool is_string_char_at = instruction->AsArrayGet()->IsStringCharAt();
1363 if (is_string_char_at && HasVectorRestrictions(restrictions, kNoStringCharAt)) {
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001364 return false;
1365 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001366 // Accept a right-hand-side array base[index] for
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001367 // (1) matching vector type (exact match or signed/unsigned integral type of the same size),
Aart Bikf8f5a162017-02-06 15:35:29 -08001368 // (2) loop-invariant base,
1369 // (3) unit stride index,
1370 // (4) vectorizable right-hand-side value.
1371 HInstruction* base = instruction->InputAt(0);
1372 HInstruction* index = instruction->InputAt(1);
1373 HInstruction* offset = nullptr;
Aart Bik46b6dbc2017-10-03 11:37:37 -07001374 if (HVecOperation::ToSignedType(type) == HVecOperation::ToSignedType(instruction->GetType()) &&
Aart Bikf8f5a162017-02-06 15:35:29 -08001375 node->loop_info->IsDefinedOutOfTheLoop(base) &&
Aart Bik37dc4df2017-06-28 14:08:00 -07001376 induction_range_.IsUnitStride(instruction, index, graph_, &offset)) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001377 if (generate_code) {
1378 GenerateVecSub(index, offset);
Aart Bik14a68b42017-06-08 14:06:58 -07001379 GenerateVecMem(instruction, vector_map_->Get(index), nullptr, offset, type);
Aart Bikf8f5a162017-02-06 15:35:29 -08001380 } else {
Aart Bik38a3f212017-10-20 17:02:21 -07001381 vector_refs_->insert(ArrayReference(base, offset, type, /*lhs*/ false, is_string_char_at));
Aart Bikf8f5a162017-02-06 15:35:29 -08001382 }
1383 return true;
1384 }
Aart Bik0148de42017-09-05 09:25:01 -07001385 } else if (instruction->IsPhi()) {
1386 // Accept particular phi operations.
1387 if (reductions_->find(instruction) != reductions_->end()) {
1388 // Deal with vector restrictions.
1389 if (HasVectorRestrictions(restrictions, kNoReduction)) {
1390 return false;
1391 }
1392 // Accept a reduction.
1393 if (generate_code) {
1394 GenerateVecReductionPhi(instruction->AsPhi());
1395 }
1396 return true;
1397 }
1398 // TODO: accept right-hand-side induction?
1399 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001400 } else if (instruction->IsTypeConversion()) {
1401 // Accept particular type conversions.
1402 HTypeConversion* conversion = instruction->AsTypeConversion();
1403 HInstruction* opa = conversion->InputAt(0);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001404 DataType::Type from = conversion->GetInputType();
1405 DataType::Type to = conversion->GetResultType();
1406 if (DataType::IsIntegralType(from) && DataType::IsIntegralType(to)) {
Aart Bik38a3f212017-10-20 17:02:21 -07001407 uint32_t size_vec = DataType::Size(type);
1408 uint32_t size_from = DataType::Size(from);
1409 uint32_t size_to = DataType::Size(to);
Aart Bikdbbac8f2017-09-01 13:06:08 -07001410 // Accept an integral conversion
1411 // (1a) narrowing into vector type, "wider" operations cannot bring in higher order bits, or
1412 // (1b) widening from at least vector type, and
1413 // (2) vectorizable operand.
1414 if ((size_to < size_from &&
1415 size_to == size_vec &&
1416 VectorizeUse(node, opa, generate_code, type, restrictions | kNoHiBits)) ||
1417 (size_to >= size_from &&
1418 size_from >= size_vec &&
Aart Bik4d1a9d42017-10-19 14:40:55 -07001419 VectorizeUse(node, opa, generate_code, type, restrictions))) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001420 if (generate_code) {
1421 if (vector_mode_ == kVector) {
1422 vector_map_->Put(instruction, vector_map_->Get(opa)); // operand pass-through
1423 } else {
1424 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1425 }
1426 }
1427 return true;
1428 }
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001429 } else if (to == DataType::Type::kFloat32 && from == DataType::Type::kInt32) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001430 DCHECK_EQ(to, type);
1431 // Accept int to float conversion for
1432 // (1) supported int,
1433 // (2) vectorizable operand.
1434 if (TrySetVectorType(from, &restrictions) &&
1435 VectorizeUse(node, opa, generate_code, from, restrictions)) {
1436 if (generate_code) {
1437 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1438 }
1439 return true;
1440 }
1441 }
1442 return false;
1443 } else if (instruction->IsNeg() || instruction->IsNot() || instruction->IsBooleanNot()) {
1444 // Accept unary operator for vectorizable operand.
1445 HInstruction* opa = instruction->InputAt(0);
1446 if (VectorizeUse(node, opa, generate_code, type, restrictions)) {
1447 if (generate_code) {
1448 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1449 }
1450 return true;
1451 }
1452 } else if (instruction->IsAdd() || instruction->IsSub() ||
1453 instruction->IsMul() || instruction->IsDiv() ||
1454 instruction->IsAnd() || instruction->IsOr() || instruction->IsXor()) {
1455 // Deal with vector restrictions.
1456 if ((instruction->IsMul() && HasVectorRestrictions(restrictions, kNoMul)) ||
1457 (instruction->IsDiv() && HasVectorRestrictions(restrictions, kNoDiv))) {
1458 return false;
1459 }
1460 // Accept binary operator for vectorizable operands.
1461 HInstruction* opa = instruction->InputAt(0);
1462 HInstruction* opb = instruction->InputAt(1);
1463 if (VectorizeUse(node, opa, generate_code, type, restrictions) &&
1464 VectorizeUse(node, opb, generate_code, type, restrictions)) {
1465 if (generate_code) {
1466 GenerateVecOp(instruction, vector_map_->Get(opa), vector_map_->Get(opb), type);
1467 }
1468 return true;
1469 }
1470 } else if (instruction->IsShl() || instruction->IsShr() || instruction->IsUShr()) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001471 // Recognize halving add idiom.
Aart Bikf3e61ee2017-04-12 17:09:20 -07001472 if (VectorizeHalvingAddIdiom(node, instruction, generate_code, type, restrictions)) {
1473 return true;
1474 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001475 // Deal with vector restrictions.
Aart Bik304c8a52017-05-23 11:01:13 -07001476 HInstruction* opa = instruction->InputAt(0);
1477 HInstruction* opb = instruction->InputAt(1);
1478 HInstruction* r = opa;
1479 bool is_unsigned = false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001480 if ((HasVectorRestrictions(restrictions, kNoShift)) ||
1481 (instruction->IsShr() && HasVectorRestrictions(restrictions, kNoShr))) {
1482 return false; // unsupported instruction
Aart Bik304c8a52017-05-23 11:01:13 -07001483 } else if (HasVectorRestrictions(restrictions, kNoHiBits)) {
1484 // Shifts right need extra care to account for higher order bits.
1485 // TODO: less likely shr/unsigned and ushr/signed can by flipping signess.
1486 if (instruction->IsShr() &&
1487 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || is_unsigned)) {
1488 return false; // reject, unless all operands are sign-extension narrower
1489 } else if (instruction->IsUShr() &&
1490 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || !is_unsigned)) {
1491 return false; // reject, unless all operands are zero-extension narrower
1492 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001493 }
1494 // Accept shift operator for vectorizable/invariant operands.
1495 // TODO: accept symbolic, albeit loop invariant shift factors.
Aart Bik304c8a52017-05-23 11:01:13 -07001496 DCHECK(r != nullptr);
1497 if (generate_code && vector_mode_ != kVector) { // de-idiom
1498 r = opa;
1499 }
Aart Bik50e20d52017-05-05 14:07:29 -07001500 int64_t distance = 0;
Aart Bik304c8a52017-05-23 11:01:13 -07001501 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
Aart Bik50e20d52017-05-05 14:07:29 -07001502 IsInt64AndGet(opb, /*out*/ &distance)) {
Aart Bik65ffd8e2017-05-01 16:50:45 -07001503 // Restrict shift distance to packed data type width.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001504 int64_t max_distance = DataType::Size(type) * 8;
Aart Bik65ffd8e2017-05-01 16:50:45 -07001505 if (0 <= distance && distance < max_distance) {
1506 if (generate_code) {
Aart Bik304c8a52017-05-23 11:01:13 -07001507 GenerateVecOp(instruction, vector_map_->Get(r), opb, type);
Aart Bik65ffd8e2017-05-01 16:50:45 -07001508 }
1509 return true;
Aart Bikf8f5a162017-02-06 15:35:29 -08001510 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001511 }
Aart Bik3b2a5952018-03-05 13:55:28 -08001512 } else if (instruction->IsAbs()) {
1513 // Deal with vector restrictions.
1514 HInstruction* opa = instruction->InputAt(0);
1515 HInstruction* r = opa;
1516 bool is_unsigned = false;
1517 if (HasVectorRestrictions(restrictions, kNoAbs)) {
1518 return false;
1519 } else if (HasVectorRestrictions(restrictions, kNoHiBits) &&
1520 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || is_unsigned)) {
1521 return false; // reject, unless operand is sign-extension narrower
1522 }
1523 // Accept ABS(x) for vectorizable operand.
1524 DCHECK(r != nullptr);
1525 if (generate_code && vector_mode_ != kVector) { // de-idiom
1526 r = opa;
1527 }
1528 if (VectorizeUse(node, r, generate_code, type, restrictions)) {
1529 if (generate_code) {
1530 GenerateVecOp(instruction,
1531 vector_map_->Get(r),
1532 nullptr,
1533 HVecOperation::ToProperType(type, is_unsigned));
1534 }
1535 return true;
1536 }
Aart Bik281c6812016-08-26 11:31:48 -07001537 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08001538 return false;
Aart Bik281c6812016-08-26 11:31:48 -07001539}
1540
Aart Bik38a3f212017-10-20 17:02:21 -07001541uint32_t HLoopOptimization::GetVectorSizeInBytes() {
Vladimir Markoa0431112018-06-25 09:32:54 +01001542 switch (compiler_options_->GetInstructionSet()) {
Vladimir Marko33bff252017-11-01 14:35:42 +00001543 case InstructionSet::kArm:
1544 case InstructionSet::kThumb2:
Aart Bik38a3f212017-10-20 17:02:21 -07001545 return 8; // 64-bit SIMD
1546 default:
1547 return 16; // 128-bit SIMD
1548 }
1549}
1550
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001551bool HLoopOptimization::TrySetVectorType(DataType::Type type, uint64_t* restrictions) {
Vladimir Markoa0431112018-06-25 09:32:54 +01001552 const InstructionSetFeatures* features = compiler_options_->GetInstructionSetFeatures();
1553 switch (compiler_options_->GetInstructionSet()) {
Vladimir Marko33bff252017-11-01 14:35:42 +00001554 case InstructionSet::kArm:
1555 case InstructionSet::kThumb2:
Artem Serov8f7c4102017-06-21 11:21:37 +01001556 // Allow vectorization for all ARM devices, because Android assumes that
Aart Bikb29f6842017-07-28 15:58:41 -07001557 // ARM 32-bit always supports advanced SIMD (64-bit SIMD).
Artem Serov8f7c4102017-06-21 11:21:37 +01001558 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001559 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001560 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001561 case DataType::Type::kInt8:
Artem Serovaaac0e32018-08-07 00:52:22 +01001562 *restrictions |= kNoDiv | kNoReduction | kNoDotProd;
Artem Serov8f7c4102017-06-21 11:21:37 +01001563 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001564 case DataType::Type::kUint16:
1565 case DataType::Type::kInt16:
Artem Serovaaac0e32018-08-07 00:52:22 +01001566 *restrictions |= kNoDiv | kNoStringCharAt | kNoReduction | kNoDotProd;
Artem Serov8f7c4102017-06-21 11:21:37 +01001567 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001568 case DataType::Type::kInt32:
Artem Serov6e9b1372017-10-05 16:48:30 +01001569 *restrictions |= kNoDiv | kNoWideSAD;
Artem Serov8f7c4102017-06-21 11:21:37 +01001570 return TrySetVectorLength(2);
1571 default:
1572 break;
1573 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001574 return false;
Vladimir Marko33bff252017-11-01 14:35:42 +00001575 case InstructionSet::kArm64:
Aart Bikf8f5a162017-02-06 15:35:29 -08001576 // Allow vectorization for all ARM devices, because Android assumes that
Aart Bikb29f6842017-07-28 15:58:41 -07001577 // ARMv8 AArch64 always supports advanced SIMD (128-bit SIMD).
Aart Bikf8f5a162017-02-06 15:35:29 -08001578 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001579 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001580 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001581 case DataType::Type::kInt8:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001582 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +01001583 return TrySetVectorLength(16);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001584 case DataType::Type::kUint16:
1585 case DataType::Type::kInt16:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001586 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +01001587 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001588 case DataType::Type::kInt32:
Aart Bikf8f5a162017-02-06 15:35:29 -08001589 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +01001590 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001591 case DataType::Type::kInt64:
Aart Bik3f08e9b2018-05-01 13:42:03 -07001592 *restrictions |= kNoDiv | kNoMul;
Aart Bikf8f5a162017-02-06 15:35:29 -08001593 return TrySetVectorLength(2);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001594 case DataType::Type::kFloat32:
Aart Bik0148de42017-09-05 09:25:01 -07001595 *restrictions |= kNoReduction;
Artem Serovd4bccf12017-04-03 18:47:32 +01001596 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001597 case DataType::Type::kFloat64:
Aart Bik0148de42017-09-05 09:25:01 -07001598 *restrictions |= kNoReduction;
Aart Bikf8f5a162017-02-06 15:35:29 -08001599 return TrySetVectorLength(2);
1600 default:
1601 return false;
1602 }
Vladimir Marko33bff252017-11-01 14:35:42 +00001603 case InstructionSet::kX86:
1604 case InstructionSet::kX86_64:
Aart Bikb29f6842017-07-28 15:58:41 -07001605 // Allow vectorization for SSE4.1-enabled X86 devices only (128-bit SIMD).
Aart Bikf8f5a162017-02-06 15:35:29 -08001606 if (features->AsX86InstructionSetFeatures()->HasSSE4_1()) {
1607 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001608 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001609 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001610 case DataType::Type::kInt8:
Artem Serovaaac0e32018-08-07 00:52:22 +01001611 *restrictions |= kNoMul |
1612 kNoDiv |
1613 kNoShift |
1614 kNoAbs |
1615 kNoSignedHAdd |
1616 kNoUnroundedHAdd |
1617 kNoSAD |
1618 kNoDotProd;
Aart Bikf8f5a162017-02-06 15:35:29 -08001619 return TrySetVectorLength(16);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001620 case DataType::Type::kUint16:
1621 case DataType::Type::kInt16:
Artem Serovaaac0e32018-08-07 00:52:22 +01001622 *restrictions |= kNoDiv |
1623 kNoAbs |
1624 kNoSignedHAdd |
1625 kNoUnroundedHAdd |
1626 kNoSAD|
1627 kNoDotProd;
Aart Bikf8f5a162017-02-06 15:35:29 -08001628 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001629 case DataType::Type::kInt32:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001630 *restrictions |= kNoDiv | kNoSAD;
Aart Bikf8f5a162017-02-06 15:35:29 -08001631 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001632 case DataType::Type::kInt64:
Aart Bik3f08e9b2018-05-01 13:42:03 -07001633 *restrictions |= kNoMul | kNoDiv | kNoShr | kNoAbs | kNoSAD;
Aart Bikf8f5a162017-02-06 15:35:29 -08001634 return TrySetVectorLength(2);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001635 case DataType::Type::kFloat32:
Aart Bik3f08e9b2018-05-01 13:42:03 -07001636 *restrictions |= kNoReduction;
Aart Bikf8f5a162017-02-06 15:35:29 -08001637 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001638 case DataType::Type::kFloat64:
Aart Bik3f08e9b2018-05-01 13:42:03 -07001639 *restrictions |= kNoReduction;
Aart Bikf8f5a162017-02-06 15:35:29 -08001640 return TrySetVectorLength(2);
1641 default:
1642 break;
1643 } // switch type
1644 }
1645 return false;
Vladimir Marko33bff252017-11-01 14:35:42 +00001646 case InstructionSet::kMips:
Lena Djokic51765b02017-06-22 13:49:59 +02001647 if (features->AsMipsInstructionSetFeatures()->HasMsa()) {
1648 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001649 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001650 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001651 case DataType::Type::kInt8:
Artem Serovaaac0e32018-08-07 00:52:22 +01001652 *restrictions |= kNoDiv | kNoDotProd;
Lena Djokic51765b02017-06-22 13:49:59 +02001653 return TrySetVectorLength(16);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001654 case DataType::Type::kUint16:
1655 case DataType::Type::kInt16:
Artem Serovaaac0e32018-08-07 00:52:22 +01001656 *restrictions |= kNoDiv | kNoStringCharAt | kNoDotProd;
Lena Djokic51765b02017-06-22 13:49:59 +02001657 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001658 case DataType::Type::kInt32:
Lena Djokic38e380b2017-10-30 16:17:10 +01001659 *restrictions |= kNoDiv;
Lena Djokic51765b02017-06-22 13:49:59 +02001660 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001661 case DataType::Type::kInt64:
Lena Djokic38e380b2017-10-30 16:17:10 +01001662 *restrictions |= kNoDiv;
Lena Djokic51765b02017-06-22 13:49:59 +02001663 return TrySetVectorLength(2);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001664 case DataType::Type::kFloat32:
Aart Bik3f08e9b2018-05-01 13:42:03 -07001665 *restrictions |= kNoReduction;
Lena Djokic51765b02017-06-22 13:49:59 +02001666 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001667 case DataType::Type::kFloat64:
Aart Bik3f08e9b2018-05-01 13:42:03 -07001668 *restrictions |= kNoReduction;
Lena Djokic51765b02017-06-22 13:49:59 +02001669 return TrySetVectorLength(2);
1670 default:
1671 break;
1672 } // switch type
1673 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001674 return false;
Vladimir Marko33bff252017-11-01 14:35:42 +00001675 case InstructionSet::kMips64:
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001676 if (features->AsMips64InstructionSetFeatures()->HasMsa()) {
1677 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001678 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001679 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001680 case DataType::Type::kInt8:
Artem Serovaaac0e32018-08-07 00:52:22 +01001681 *restrictions |= kNoDiv | kNoDotProd;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001682 return TrySetVectorLength(16);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001683 case DataType::Type::kUint16:
1684 case DataType::Type::kInt16:
Artem Serovaaac0e32018-08-07 00:52:22 +01001685 *restrictions |= kNoDiv | kNoStringCharAt | kNoDotProd;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001686 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001687 case DataType::Type::kInt32:
Lena Djokic38e380b2017-10-30 16:17:10 +01001688 *restrictions |= kNoDiv;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001689 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001690 case DataType::Type::kInt64:
Lena Djokic38e380b2017-10-30 16:17:10 +01001691 *restrictions |= kNoDiv;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001692 return TrySetVectorLength(2);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001693 case DataType::Type::kFloat32:
Aart Bik3f08e9b2018-05-01 13:42:03 -07001694 *restrictions |= kNoReduction;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001695 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001696 case DataType::Type::kFloat64:
Aart Bik3f08e9b2018-05-01 13:42:03 -07001697 *restrictions |= kNoReduction;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001698 return TrySetVectorLength(2);
1699 default:
1700 break;
1701 } // switch type
1702 }
1703 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001704 default:
1705 return false;
1706 } // switch instruction set
1707}
1708
1709bool HLoopOptimization::TrySetVectorLength(uint32_t length) {
1710 DCHECK(IsPowerOfTwo(length) && length >= 2u);
1711 // First time set?
1712 if (vector_length_ == 0) {
1713 vector_length_ = length;
1714 }
1715 // Different types are acceptable within a loop-body, as long as all the corresponding vector
1716 // lengths match exactly to obtain a uniform traversal through the vector iteration space
1717 // (idiomatic exceptions to this rule can be handled by further unrolling sub-expressions).
1718 return vector_length_ == length;
1719}
1720
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001721void HLoopOptimization::GenerateVecInv(HInstruction* org, DataType::Type type) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001722 if (vector_map_->find(org) == vector_map_->end()) {
1723 // In scalar code, just use a self pass-through for scalar invariants
1724 // (viz. expression remains itself).
1725 if (vector_mode_ == kSequential) {
1726 vector_map_->Put(org, org);
1727 return;
1728 }
1729 // In vector code, explicit scalar expansion is needed.
Aart Bik0148de42017-09-05 09:25:01 -07001730 HInstruction* vector = nullptr;
1731 auto it = vector_permanent_map_->find(org);
1732 if (it != vector_permanent_map_->end()) {
1733 vector = it->second; // reuse during unrolling
1734 } else {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001735 // Generates ReplicateScalar( (optional_type_conv) org ).
1736 HInstruction* input = org;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001737 DataType::Type input_type = input->GetType();
1738 if (type != input_type && (type == DataType::Type::kInt64 ||
1739 input_type == DataType::Type::kInt64)) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001740 input = Insert(vector_preheader_,
1741 new (global_allocator_) HTypeConversion(type, input, kNoDexPc));
1742 }
1743 vector = new (global_allocator_)
Aart Bik46b6dbc2017-10-03 11:37:37 -07001744 HVecReplicateScalar(global_allocator_, input, type, vector_length_, kNoDexPc);
Aart Bik0148de42017-09-05 09:25:01 -07001745 vector_permanent_map_->Put(org, Insert(vector_preheader_, vector));
1746 }
1747 vector_map_->Put(org, vector);
Aart Bikf8f5a162017-02-06 15:35:29 -08001748 }
1749}
1750
1751void HLoopOptimization::GenerateVecSub(HInstruction* org, HInstruction* offset) {
1752 if (vector_map_->find(org) == vector_map_->end()) {
Aart Bik14a68b42017-06-08 14:06:58 -07001753 HInstruction* subscript = vector_index_;
Aart Bik37dc4df2017-06-28 14:08:00 -07001754 int64_t value = 0;
1755 if (!IsInt64AndGet(offset, &value) || value != 0) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001756 subscript = new (global_allocator_) HAdd(DataType::Type::kInt32, subscript, offset);
Aart Bikf8f5a162017-02-06 15:35:29 -08001757 if (org->IsPhi()) {
1758 Insert(vector_body_, subscript); // lacks layout placeholder
1759 }
1760 }
1761 vector_map_->Put(org, subscript);
1762 }
1763}
1764
1765void HLoopOptimization::GenerateVecMem(HInstruction* org,
1766 HInstruction* opa,
1767 HInstruction* opb,
Aart Bik14a68b42017-06-08 14:06:58 -07001768 HInstruction* offset,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001769 DataType::Type type) {
Aart Bik46b6dbc2017-10-03 11:37:37 -07001770 uint32_t dex_pc = org->GetDexPc();
Aart Bikf8f5a162017-02-06 15:35:29 -08001771 HInstruction* vector = nullptr;
1772 if (vector_mode_ == kVector) {
1773 // Vector store or load.
Aart Bik38a3f212017-10-20 17:02:21 -07001774 bool is_string_char_at = false;
Aart Bik14a68b42017-06-08 14:06:58 -07001775 HInstruction* base = org->InputAt(0);
Aart Bikf8f5a162017-02-06 15:35:29 -08001776 if (opb != nullptr) {
1777 vector = new (global_allocator_) HVecStore(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001778 global_allocator_, base, opa, opb, type, org->GetSideEffects(), vector_length_, dex_pc);
Aart Bikf8f5a162017-02-06 15:35:29 -08001779 } else {
Aart Bik38a3f212017-10-20 17:02:21 -07001780 is_string_char_at = org->AsArrayGet()->IsStringCharAt();
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001781 vector = new (global_allocator_) HVecLoad(global_allocator_,
1782 base,
1783 opa,
1784 type,
1785 org->GetSideEffects(),
1786 vector_length_,
Aart Bik46b6dbc2017-10-03 11:37:37 -07001787 is_string_char_at,
1788 dex_pc);
Aart Bik14a68b42017-06-08 14:06:58 -07001789 }
Aart Bik38a3f212017-10-20 17:02:21 -07001790 // Known (forced/adjusted/original) alignment?
1791 if (vector_dynamic_peeling_candidate_ != nullptr) {
1792 if (vector_dynamic_peeling_candidate_->offset == offset && // TODO: diffs too?
1793 DataType::Size(vector_dynamic_peeling_candidate_->type) == DataType::Size(type) &&
1794 vector_dynamic_peeling_candidate_->is_string_char_at == is_string_char_at) {
1795 vector->AsVecMemoryOperation()->SetAlignment( // forced
1796 Alignment(GetVectorSizeInBytes(), 0));
1797 }
1798 } else {
1799 vector->AsVecMemoryOperation()->SetAlignment( // adjusted/original
1800 ComputeAlignment(offset, type, is_string_char_at, vector_static_peeling_factor_));
Aart Bikf8f5a162017-02-06 15:35:29 -08001801 }
1802 } else {
1803 // Scalar store or load.
1804 DCHECK(vector_mode_ == kSequential);
1805 if (opb != nullptr) {
Aart Bik4d1a9d42017-10-19 14:40:55 -07001806 DataType::Type component_type = org->AsArraySet()->GetComponentType();
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001807 vector = new (global_allocator_) HArraySet(
Aart Bik4d1a9d42017-10-19 14:40:55 -07001808 org->InputAt(0), opa, opb, component_type, org->GetSideEffects(), dex_pc);
Aart Bikf8f5a162017-02-06 15:35:29 -08001809 } else {
Aart Bikdb14fcf2017-04-25 15:53:58 -07001810 bool is_string_char_at = org->AsArrayGet()->IsStringCharAt();
1811 vector = new (global_allocator_) HArrayGet(
Aart Bik4d1a9d42017-10-19 14:40:55 -07001812 org->InputAt(0), opa, org->GetType(), org->GetSideEffects(), dex_pc, is_string_char_at);
Aart Bikf8f5a162017-02-06 15:35:29 -08001813 }
1814 }
1815 vector_map_->Put(org, vector);
1816}
1817
Aart Bik0148de42017-09-05 09:25:01 -07001818void HLoopOptimization::GenerateVecReductionPhi(HPhi* phi) {
1819 DCHECK(reductions_->find(phi) != reductions_->end());
1820 DCHECK(reductions_->Get(phi->InputAt(1)) == phi);
1821 HInstruction* vector = nullptr;
1822 if (vector_mode_ == kSequential) {
1823 HPhi* new_phi = new (global_allocator_) HPhi(
1824 global_allocator_, kNoRegNumber, 0, phi->GetType());
1825 vector_header_->AddPhi(new_phi);
1826 vector = new_phi;
1827 } else {
1828 // Link vector reduction back to prior unrolled update, or a first phi.
1829 auto it = vector_permanent_map_->find(phi);
1830 if (it != vector_permanent_map_->end()) {
1831 vector = it->second;
1832 } else {
1833 HPhi* new_phi = new (global_allocator_) HPhi(
1834 global_allocator_, kNoRegNumber, 0, HVecOperation::kSIMDType);
1835 vector_header_->AddPhi(new_phi);
1836 vector = new_phi;
1837 }
1838 }
1839 vector_map_->Put(phi, vector);
1840}
1841
1842void HLoopOptimization::GenerateVecReductionPhiInputs(HPhi* phi, HInstruction* reduction) {
1843 HInstruction* new_phi = vector_map_->Get(phi);
1844 HInstruction* new_init = reductions_->Get(phi);
1845 HInstruction* new_red = vector_map_->Get(reduction);
1846 // Link unrolled vector loop back to new phi.
1847 for (; !new_phi->IsPhi(); new_phi = vector_permanent_map_->Get(new_phi)) {
1848 DCHECK(new_phi->IsVecOperation());
1849 }
1850 // Prepare the new initialization.
1851 if (vector_mode_ == kVector) {
Goran Jakovljevic89b8df02017-10-13 08:33:17 +02001852 // Generate a [initial, 0, .., 0] vector for add or
1853 // a [initial, initial, .., initial] vector for min/max.
Aart Bikdbbac8f2017-09-01 13:06:08 -07001854 HVecOperation* red_vector = new_red->AsVecOperation();
Goran Jakovljevic89b8df02017-10-13 08:33:17 +02001855 HVecReduce::ReductionKind kind = GetReductionKind(red_vector);
Aart Bik38a3f212017-10-20 17:02:21 -07001856 uint32_t vector_length = red_vector->GetVectorLength();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001857 DataType::Type type = red_vector->GetPackedType();
Goran Jakovljevic89b8df02017-10-13 08:33:17 +02001858 if (kind == HVecReduce::ReductionKind::kSum) {
1859 new_init = Insert(vector_preheader_,
1860 new (global_allocator_) HVecSetScalars(global_allocator_,
1861 &new_init,
1862 type,
1863 vector_length,
1864 1,
1865 kNoDexPc));
1866 } else {
1867 new_init = Insert(vector_preheader_,
1868 new (global_allocator_) HVecReplicateScalar(global_allocator_,
1869 new_init,
1870 type,
1871 vector_length,
1872 kNoDexPc));
1873 }
Aart Bik0148de42017-09-05 09:25:01 -07001874 } else {
1875 new_init = ReduceAndExtractIfNeeded(new_init);
1876 }
1877 // Set the phi inputs.
1878 DCHECK(new_phi->IsPhi());
1879 new_phi->AsPhi()->AddInput(new_init);
1880 new_phi->AsPhi()->AddInput(new_red);
1881 // New feed value for next phi (safe mutation in iteration).
1882 reductions_->find(phi)->second = new_phi;
1883}
1884
1885HInstruction* HLoopOptimization::ReduceAndExtractIfNeeded(HInstruction* instruction) {
1886 if (instruction->IsPhi()) {
1887 HInstruction* input = instruction->InputAt(1);
Aart Bik2dd7b672017-12-07 11:11:22 -08001888 if (HVecOperation::ReturnsSIMDValue(input)) {
1889 DCHECK(!input->IsPhi());
Aart Bikdbbac8f2017-09-01 13:06:08 -07001890 HVecOperation* input_vector = input->AsVecOperation();
Aart Bik38a3f212017-10-20 17:02:21 -07001891 uint32_t vector_length = input_vector->GetVectorLength();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001892 DataType::Type type = input_vector->GetPackedType();
Aart Bikdbbac8f2017-09-01 13:06:08 -07001893 HVecReduce::ReductionKind kind = GetReductionKind(input_vector);
Aart Bik0148de42017-09-05 09:25:01 -07001894 HBasicBlock* exit = instruction->GetBlock()->GetSuccessors()[0];
1895 // Generate a vector reduction and scalar extract
1896 // x = REDUCE( [x_1, .., x_n] )
1897 // y = x_1
1898 // along the exit of the defining loop.
Aart Bik0148de42017-09-05 09:25:01 -07001899 HInstruction* reduce = new (global_allocator_) HVecReduce(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001900 global_allocator_, instruction, type, vector_length, kind, kNoDexPc);
Aart Bik0148de42017-09-05 09:25:01 -07001901 exit->InsertInstructionBefore(reduce, exit->GetFirstInstruction());
1902 instruction = new (global_allocator_) HVecExtractScalar(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001903 global_allocator_, reduce, type, vector_length, 0, kNoDexPc);
Aart Bik0148de42017-09-05 09:25:01 -07001904 exit->InsertInstructionAfter(instruction, reduce);
1905 }
1906 }
1907 return instruction;
1908}
1909
Aart Bikf8f5a162017-02-06 15:35:29 -08001910#define GENERATE_VEC(x, y) \
1911 if (vector_mode_ == kVector) { \
1912 vector = (x); \
1913 } else { \
1914 DCHECK(vector_mode_ == kSequential); \
1915 vector = (y); \
1916 } \
1917 break;
1918
1919void HLoopOptimization::GenerateVecOp(HInstruction* org,
1920 HInstruction* opa,
1921 HInstruction* opb,
Aart Bik3f08e9b2018-05-01 13:42:03 -07001922 DataType::Type type) {
Aart Bik46b6dbc2017-10-03 11:37:37 -07001923 uint32_t dex_pc = org->GetDexPc();
Aart Bikf8f5a162017-02-06 15:35:29 -08001924 HInstruction* vector = nullptr;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001925 DataType::Type org_type = org->GetType();
Aart Bikf8f5a162017-02-06 15:35:29 -08001926 switch (org->GetKind()) {
1927 case HInstruction::kNeg:
1928 DCHECK(opb == nullptr);
1929 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001930 new (global_allocator_) HVecNeg(global_allocator_, opa, type, vector_length_, dex_pc),
1931 new (global_allocator_) HNeg(org_type, opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001932 case HInstruction::kNot:
1933 DCHECK(opb == nullptr);
1934 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001935 new (global_allocator_) HVecNot(global_allocator_, opa, type, vector_length_, dex_pc),
1936 new (global_allocator_) HNot(org_type, opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001937 case HInstruction::kBooleanNot:
1938 DCHECK(opb == nullptr);
1939 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001940 new (global_allocator_) HVecNot(global_allocator_, opa, type, vector_length_, dex_pc),
1941 new (global_allocator_) HBooleanNot(opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001942 case HInstruction::kTypeConversion:
1943 DCHECK(opb == nullptr);
1944 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001945 new (global_allocator_) HVecCnv(global_allocator_, opa, type, vector_length_, dex_pc),
1946 new (global_allocator_) HTypeConversion(org_type, opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001947 case HInstruction::kAdd:
1948 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001949 new (global_allocator_) HVecAdd(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1950 new (global_allocator_) HAdd(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001951 case HInstruction::kSub:
1952 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001953 new (global_allocator_) HVecSub(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1954 new (global_allocator_) HSub(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001955 case HInstruction::kMul:
1956 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001957 new (global_allocator_) HVecMul(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1958 new (global_allocator_) HMul(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001959 case HInstruction::kDiv:
1960 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001961 new (global_allocator_) HVecDiv(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1962 new (global_allocator_) HDiv(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001963 case HInstruction::kAnd:
1964 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001965 new (global_allocator_) HVecAnd(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1966 new (global_allocator_) HAnd(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001967 case HInstruction::kOr:
1968 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001969 new (global_allocator_) HVecOr(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1970 new (global_allocator_) HOr(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001971 case HInstruction::kXor:
1972 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001973 new (global_allocator_) HVecXor(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1974 new (global_allocator_) HXor(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001975 case HInstruction::kShl:
1976 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001977 new (global_allocator_) HVecShl(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1978 new (global_allocator_) HShl(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001979 case HInstruction::kShr:
1980 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001981 new (global_allocator_) HVecShr(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1982 new (global_allocator_) HShr(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001983 case HInstruction::kUShr:
1984 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001985 new (global_allocator_) HVecUShr(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1986 new (global_allocator_) HUShr(org_type, opa, opb, dex_pc));
Aart Bik3b2a5952018-03-05 13:55:28 -08001987 case HInstruction::kAbs:
1988 DCHECK(opb == nullptr);
1989 GENERATE_VEC(
1990 new (global_allocator_) HVecAbs(global_allocator_, opa, type, vector_length_, dex_pc),
1991 new (global_allocator_) HAbs(org_type, opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001992 default:
1993 break;
1994 } // switch
1995 CHECK(vector != nullptr) << "Unsupported SIMD operator";
1996 vector_map_->Put(org, vector);
1997}
1998
1999#undef GENERATE_VEC
2000
2001//
Aart Bikf3e61ee2017-04-12 17:09:20 -07002002// Vectorization idioms.
2003//
2004
2005// Method recognizes the following idioms:
Aart Bikdbbac8f2017-09-01 13:06:08 -07002006// rounding halving add (a + b + 1) >> 1 for unsigned/signed operands a, b
2007// truncated halving add (a + b) >> 1 for unsigned/signed operands a, b
Aart Bikf3e61ee2017-04-12 17:09:20 -07002008// Provided that the operands are promoted to a wider form to do the arithmetic and
2009// then cast back to narrower form, the idioms can be mapped into efficient SIMD
2010// implementation that operates directly in narrower form (plus one extra bit).
2011// TODO: current version recognizes implicit byte/short/char widening only;
2012// explicit widening from int to long could be added later.
2013bool HLoopOptimization::VectorizeHalvingAddIdiom(LoopNode* node,
2014 HInstruction* instruction,
2015 bool generate_code,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002016 DataType::Type type,
Aart Bikf3e61ee2017-04-12 17:09:20 -07002017 uint64_t restrictions) {
2018 // Test for top level arithmetic shift right x >> 1 or logical shift right x >>> 1
Aart Bik304c8a52017-05-23 11:01:13 -07002019 // (note whether the sign bit in wider precision is shifted in has no effect
Aart Bikf3e61ee2017-04-12 17:09:20 -07002020 // on the narrow precision computed by the idiom).
Aart Bikf3e61ee2017-04-12 17:09:20 -07002021 if ((instruction->IsShr() ||
2022 instruction->IsUShr()) &&
Aart Bik0148de42017-09-05 09:25:01 -07002023 IsInt64Value(instruction->InputAt(1), 1)) {
Aart Bik5f805002017-05-16 16:42:41 -07002024 // Test for (a + b + c) >> 1 for optional constant c.
2025 HInstruction* a = nullptr;
2026 HInstruction* b = nullptr;
2027 int64_t c = 0;
Nicolas Geoffraya3e23262018-03-28 11:15:12 +00002028 if (IsAddConst2(graph_, instruction->InputAt(0), /*out*/ &a, /*out*/ &b, /*out*/ &c)) {
Aart Bik5f805002017-05-16 16:42:41 -07002029 // Accept c == 1 (rounded) or c == 0 (not rounded).
2030 bool is_rounded = false;
2031 if (c == 1) {
2032 is_rounded = true;
2033 } else if (c != 0) {
2034 return false;
2035 }
2036 // Accept consistent zero or sign extension on operands a and b.
Aart Bikf3e61ee2017-04-12 17:09:20 -07002037 HInstruction* r = nullptr;
2038 HInstruction* s = nullptr;
2039 bool is_unsigned = false;
Aart Bik304c8a52017-05-23 11:01:13 -07002040 if (!IsNarrowerOperands(a, b, type, &r, &s, &is_unsigned)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -07002041 return false;
2042 }
2043 // Deal with vector restrictions.
2044 if ((!is_unsigned && HasVectorRestrictions(restrictions, kNoSignedHAdd)) ||
2045 (!is_rounded && HasVectorRestrictions(restrictions, kNoUnroundedHAdd))) {
2046 return false;
2047 }
2048 // Accept recognized halving add for vectorizable operands. Vectorized code uses the
2049 // shorthand idiomatic operation. Sequential code uses the original scalar expressions.
Nicolas Geoffraya3e23262018-03-28 11:15:12 +00002050 DCHECK(r != nullptr && s != nullptr);
Aart Bik304c8a52017-05-23 11:01:13 -07002051 if (generate_code && vector_mode_ != kVector) { // de-idiom
2052 r = instruction->InputAt(0);
2053 s = instruction->InputAt(1);
2054 }
Aart Bikf3e61ee2017-04-12 17:09:20 -07002055 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
2056 VectorizeUse(node, s, generate_code, type, restrictions)) {
2057 if (generate_code) {
2058 if (vector_mode_ == kVector) {
2059 vector_map_->Put(instruction, new (global_allocator_) HVecHalvingAdd(
2060 global_allocator_,
2061 vector_map_->Get(r),
2062 vector_map_->Get(s),
Aart Bik66c158e2018-01-31 12:55:04 -08002063 HVecOperation::ToProperType(type, is_unsigned),
Aart Bikf3e61ee2017-04-12 17:09:20 -07002064 vector_length_,
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01002065 is_rounded,
Aart Bik46b6dbc2017-10-03 11:37:37 -07002066 kNoDexPc));
Aart Bik21b85922017-09-06 13:29:16 -07002067 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorizedIdiom);
Aart Bikf3e61ee2017-04-12 17:09:20 -07002068 } else {
Aart Bik304c8a52017-05-23 11:01:13 -07002069 GenerateVecOp(instruction, vector_map_->Get(r), vector_map_->Get(s), type);
Aart Bikf3e61ee2017-04-12 17:09:20 -07002070 }
2071 }
2072 return true;
2073 }
2074 }
2075 }
2076 return false;
2077}
2078
Aart Bikdbbac8f2017-09-01 13:06:08 -07002079// Method recognizes the following idiom:
2080// q += ABS(a - b) for signed operands a, b
2081// Provided that the operands have the same type or are promoted to a wider form.
2082// Since this may involve a vector length change, the idiom is handled by going directly
2083// to a sad-accumulate node (rather than relying combining finer grained nodes later).
2084// TODO: unsigned SAD too?
2085bool HLoopOptimization::VectorizeSADIdiom(LoopNode* node,
2086 HInstruction* instruction,
2087 bool generate_code,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002088 DataType::Type reduction_type,
Aart Bikdbbac8f2017-09-01 13:06:08 -07002089 uint64_t restrictions) {
2090 // Filter integral "q += ABS(a - b);" reduction, where ABS and SUB
2091 // are done in the same precision (either int or long).
2092 if (!instruction->IsAdd() ||
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002093 (reduction_type != DataType::Type::kInt32 && reduction_type != DataType::Type::kInt64)) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07002094 return false;
2095 }
2096 HInstruction* q = instruction->InputAt(0);
2097 HInstruction* v = instruction->InputAt(1);
2098 HInstruction* a = nullptr;
2099 HInstruction* b = nullptr;
Nicolas Geoffraya3e23262018-03-28 11:15:12 +00002100 if (v->IsAbs() &&
2101 v->GetType() == reduction_type &&
2102 IsSubConst2(graph_, v->InputAt(0), /*out*/ &a, /*out*/ &b)) {
2103 DCHECK(a != nullptr && b != nullptr);
2104 } else {
Aart Bikdbbac8f2017-09-01 13:06:08 -07002105 return false;
2106 }
2107 // Accept same-type or consistent sign extension for narrower-type on operands a and b.
2108 // The same-type or narrower operands are called r (a or lower) and s (b or lower).
Aart Bikdf011c32017-09-28 12:53:04 -07002109 // We inspect the operands carefully to pick the most suited type.
Aart Bikdbbac8f2017-09-01 13:06:08 -07002110 HInstruction* r = a;
2111 HInstruction* s = b;
2112 bool is_unsigned = false;
Artem Serovaaac0e32018-08-07 00:52:22 +01002113 DataType::Type sub_type = GetNarrowerType(a, b);
Aart Bikdbbac8f2017-09-01 13:06:08 -07002114 if (reduction_type != sub_type &&
2115 (!IsNarrowerOperands(a, b, sub_type, &r, &s, &is_unsigned) || is_unsigned)) {
2116 return false;
2117 }
2118 // Try same/narrower type and deal with vector restrictions.
Artem Serov6e9b1372017-10-05 16:48:30 +01002119 if (!TrySetVectorType(sub_type, &restrictions) ||
2120 HasVectorRestrictions(restrictions, kNoSAD) ||
2121 (reduction_type != sub_type && HasVectorRestrictions(restrictions, kNoWideSAD))) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07002122 return false;
2123 }
2124 // Accept SAD idiom for vectorizable operands. Vectorized code uses the shorthand
2125 // idiomatic operation. Sequential code uses the original scalar expressions.
Nicolas Geoffraya3e23262018-03-28 11:15:12 +00002126 DCHECK(r != nullptr && s != nullptr);
Aart Bikdbbac8f2017-09-01 13:06:08 -07002127 if (generate_code && vector_mode_ != kVector) { // de-idiom
2128 r = s = v->InputAt(0);
2129 }
2130 if (VectorizeUse(node, q, generate_code, sub_type, restrictions) &&
2131 VectorizeUse(node, r, generate_code, sub_type, restrictions) &&
2132 VectorizeUse(node, s, generate_code, sub_type, restrictions)) {
2133 if (generate_code) {
2134 if (vector_mode_ == kVector) {
2135 vector_map_->Put(instruction, new (global_allocator_) HVecSADAccumulate(
2136 global_allocator_,
2137 vector_map_->Get(q),
2138 vector_map_->Get(r),
2139 vector_map_->Get(s),
Aart Bik3b2a5952018-03-05 13:55:28 -08002140 HVecOperation::ToProperType(reduction_type, is_unsigned),
Aart Bik46b6dbc2017-10-03 11:37:37 -07002141 GetOtherVL(reduction_type, sub_type, vector_length_),
2142 kNoDexPc));
Aart Bikdbbac8f2017-09-01 13:06:08 -07002143 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorizedIdiom);
2144 } else {
2145 GenerateVecOp(v, vector_map_->Get(r), nullptr, reduction_type);
2146 GenerateVecOp(instruction, vector_map_->Get(q), vector_map_->Get(v), reduction_type);
2147 }
2148 }
2149 return true;
2150 }
2151 return false;
2152}
2153
Artem Serovaaac0e32018-08-07 00:52:22 +01002154// Method recognises the following dot product idiom:
2155// q += a * b for operands a, b whose type is narrower than the reduction one.
2156// Provided that the operands have the same type or are promoted to a wider form.
2157// Since this may involve a vector length change, the idiom is handled by going directly
2158// to a dot product node (rather than relying combining finer grained nodes later).
2159bool HLoopOptimization::VectorizeDotProdIdiom(LoopNode* node,
2160 HInstruction* instruction,
2161 bool generate_code,
2162 DataType::Type reduction_type,
2163 uint64_t restrictions) {
2164 if (!instruction->IsAdd() || (reduction_type != DataType::Type::kInt32)) {
2165 return false;
2166 }
2167
2168 HInstruction* q = instruction->InputAt(0);
2169 HInstruction* v = instruction->InputAt(1);
2170 if (!v->IsMul() || v->GetType() != reduction_type) {
2171 return false;
2172 }
2173
2174 HInstruction* a = v->InputAt(0);
2175 HInstruction* b = v->InputAt(1);
2176 HInstruction* r = a;
2177 HInstruction* s = b;
2178 DataType::Type op_type = GetNarrowerType(a, b);
2179 bool is_unsigned = false;
2180
2181 if (!IsNarrowerOperands(a, b, op_type, &r, &s, &is_unsigned)) {
2182 return false;
2183 }
2184 op_type = HVecOperation::ToProperType(op_type, is_unsigned);
2185
2186 if (!TrySetVectorType(op_type, &restrictions) ||
2187 HasVectorRestrictions(restrictions, kNoDotProd)) {
2188 return false;
2189 }
2190
2191 DCHECK(r != nullptr && s != nullptr);
2192 // Accept dot product idiom for vectorizable operands. Vectorized code uses the shorthand
2193 // idiomatic operation. Sequential code uses the original scalar expressions.
2194 if (generate_code && vector_mode_ != kVector) { // de-idiom
2195 r = a;
2196 s = b;
2197 }
2198 if (VectorizeUse(node, q, generate_code, op_type, restrictions) &&
2199 VectorizeUse(node, r, generate_code, op_type, restrictions) &&
2200 VectorizeUse(node, s, generate_code, op_type, restrictions)) {
2201 if (generate_code) {
2202 if (vector_mode_ == kVector) {
2203 vector_map_->Put(instruction, new (global_allocator_) HVecDotProd(
2204 global_allocator_,
2205 vector_map_->Get(q),
2206 vector_map_->Get(r),
2207 vector_map_->Get(s),
2208 reduction_type,
2209 is_unsigned,
2210 GetOtherVL(reduction_type, op_type, vector_length_),
2211 kNoDexPc));
2212 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorizedIdiom);
2213 } else {
2214 GenerateVecOp(v, vector_map_->Get(r), vector_map_->Get(s), reduction_type);
2215 GenerateVecOp(instruction, vector_map_->Get(q), vector_map_->Get(v), reduction_type);
2216 }
2217 }
2218 return true;
2219 }
2220 return false;
2221}
2222
Aart Bikf3e61ee2017-04-12 17:09:20 -07002223//
Aart Bik14a68b42017-06-08 14:06:58 -07002224// Vectorization heuristics.
2225//
2226
Aart Bik38a3f212017-10-20 17:02:21 -07002227Alignment HLoopOptimization::ComputeAlignment(HInstruction* offset,
2228 DataType::Type type,
2229 bool is_string_char_at,
2230 uint32_t peeling) {
2231 // Combine the alignment and hidden offset that is guaranteed by
2232 // the Android runtime with a known starting index adjusted as bytes.
2233 int64_t value = 0;
2234 if (IsInt64AndGet(offset, /*out*/ &value)) {
2235 uint32_t start_offset =
2236 HiddenOffset(type, is_string_char_at) + (value + peeling) * DataType::Size(type);
2237 return Alignment(BaseAlignment(), start_offset & (BaseAlignment() - 1u));
2238 }
2239 // Otherwise, the Android runtime guarantees at least natural alignment.
2240 return Alignment(DataType::Size(type), 0);
2241}
2242
2243void HLoopOptimization::SetAlignmentStrategy(uint32_t peeling_votes[],
2244 const ArrayReference* peeling_candidate) {
2245 // Current heuristic: pick the best static loop peeling factor, if any,
2246 // or otherwise use dynamic loop peeling on suggested peeling candidate.
2247 uint32_t max_vote = 0;
2248 for (int32_t i = 0; i < 16; i++) {
2249 if (peeling_votes[i] > max_vote) {
2250 max_vote = peeling_votes[i];
2251 vector_static_peeling_factor_ = i;
2252 }
2253 }
2254 if (max_vote == 0) {
2255 vector_dynamic_peeling_candidate_ = peeling_candidate;
2256 }
2257}
2258
2259uint32_t HLoopOptimization::MaxNumberPeeled() {
2260 if (vector_dynamic_peeling_candidate_ != nullptr) {
2261 return vector_length_ - 1u; // worst-case
2262 }
2263 return vector_static_peeling_factor_; // known exactly
2264}
2265
Aart Bik14a68b42017-06-08 14:06:58 -07002266bool HLoopOptimization::IsVectorizationProfitable(int64_t trip_count) {
Aart Bik38a3f212017-10-20 17:02:21 -07002267 // Current heuristic: non-empty body with sufficient number of iterations (if known).
Aart Bik14a68b42017-06-08 14:06:58 -07002268 // TODO: refine by looking at e.g. operation count, alignment, etc.
Aart Bik38a3f212017-10-20 17:02:21 -07002269 // TODO: trip count is really unsigned entity, provided the guarding test
2270 // is satisfied; deal with this more carefully later
2271 uint32_t max_peel = MaxNumberPeeled();
Aart Bik14a68b42017-06-08 14:06:58 -07002272 if (vector_length_ == 0) {
2273 return false; // nothing found
Aart Bik38a3f212017-10-20 17:02:21 -07002274 } else if (trip_count < 0) {
2275 return false; // guard against non-taken/large
2276 } else if ((0 < trip_count) && (trip_count < (vector_length_ + max_peel))) {
Aart Bik14a68b42017-06-08 14:06:58 -07002277 return false; // insufficient iterations
2278 }
2279 return true;
2280}
2281
Aart Bik14a68b42017-06-08 14:06:58 -07002282//
Aart Bikf8f5a162017-02-06 15:35:29 -08002283// Helpers.
2284//
2285
2286bool HLoopOptimization::TrySetPhiInduction(HPhi* phi, bool restrict_uses) {
Aart Bikb29f6842017-07-28 15:58:41 -07002287 // Start with empty phi induction.
2288 iset_->clear();
2289
Nicolas Geoffrayf57c1ae2017-06-28 17:40:18 +01002290 // Special case Phis that have equivalent in a debuggable setup. Our graph checker isn't
2291 // smart enough to follow strongly connected components (and it's probably not worth
2292 // it to make it so). See b/33775412.
2293 if (graph_->IsDebuggable() && phi->HasEquivalentPhi()) {
2294 return false;
2295 }
Aart Bikb29f6842017-07-28 15:58:41 -07002296
2297 // Lookup phi induction cycle.
Aart Bikcc42be02016-10-20 16:14:16 -07002298 ArenaSet<HInstruction*>* set = induction_range_.LookupCycle(phi);
2299 if (set != nullptr) {
2300 for (HInstruction* i : *set) {
Aart Bike3dedc52016-11-02 17:50:27 -07002301 // Check that, other than instructions that are no longer in the graph (removed earlier)
Aart Bikf8f5a162017-02-06 15:35:29 -08002302 // each instruction is removable and, when restrict uses are requested, other than for phi,
2303 // all uses are contained within the cycle.
Aart Bike3dedc52016-11-02 17:50:27 -07002304 if (!i->IsInBlock()) {
2305 continue;
2306 } else if (!i->IsRemovable()) {
2307 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08002308 } else if (i != phi && restrict_uses) {
Aart Bikb29f6842017-07-28 15:58:41 -07002309 // Deal with regular uses.
Aart Bikcc42be02016-10-20 16:14:16 -07002310 for (const HUseListNode<HInstruction*>& use : i->GetUses()) {
2311 if (set->find(use.GetUser()) == set->end()) {
2312 return false;
2313 }
2314 }
2315 }
Aart Bike3dedc52016-11-02 17:50:27 -07002316 iset_->insert(i); // copy
Aart Bikcc42be02016-10-20 16:14:16 -07002317 }
Aart Bikcc42be02016-10-20 16:14:16 -07002318 return true;
2319 }
2320 return false;
2321}
2322
Aart Bikb29f6842017-07-28 15:58:41 -07002323bool HLoopOptimization::TrySetPhiReduction(HPhi* phi) {
Aart Bikcc42be02016-10-20 16:14:16 -07002324 DCHECK(iset_->empty());
Aart Bikb29f6842017-07-28 15:58:41 -07002325 // Only unclassified phi cycles are candidates for reductions.
2326 if (induction_range_.IsClassified(phi)) {
2327 return false;
2328 }
2329 // Accept operations like x = x + .., provided that the phi and the reduction are
2330 // used exactly once inside the loop, and by each other.
2331 HInputsRef inputs = phi->GetInputs();
2332 if (inputs.size() == 2) {
2333 HInstruction* reduction = inputs[1];
2334 if (HasReductionFormat(reduction, phi)) {
2335 HLoopInformation* loop_info = phi->GetBlock()->GetLoopInformation();
Aart Bik38a3f212017-10-20 17:02:21 -07002336 uint32_t use_count = 0;
Aart Bikb29f6842017-07-28 15:58:41 -07002337 bool single_use_inside_loop =
2338 // Reduction update only used by phi.
2339 reduction->GetUses().HasExactlyOneElement() &&
2340 !reduction->HasEnvironmentUses() &&
2341 // Reduction update is only use of phi inside the loop.
2342 IsOnlyUsedAfterLoop(loop_info, phi, /*collect_loop_uses*/ true, &use_count) &&
2343 iset_->size() == 1;
2344 iset_->clear(); // leave the way you found it
2345 if (single_use_inside_loop) {
2346 // Link reduction back, and start recording feed value.
2347 reductions_->Put(reduction, phi);
2348 reductions_->Put(phi, phi->InputAt(0));
2349 return true;
2350 }
2351 }
2352 }
2353 return false;
2354}
2355
2356bool HLoopOptimization::TrySetSimpleLoopHeader(HBasicBlock* block, /*out*/ HPhi** main_phi) {
2357 // Start with empty phi induction and reductions.
2358 iset_->clear();
2359 reductions_->clear();
2360
2361 // Scan the phis to find the following (the induction structure has already
2362 // been optimized, so we don't need to worry about trivial cases):
2363 // (1) optional reductions in loop,
2364 // (2) the main induction, used in loop control.
2365 HPhi* phi = nullptr;
2366 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
2367 if (TrySetPhiReduction(it.Current()->AsPhi())) {
2368 continue;
2369 } else if (phi == nullptr) {
2370 // Found the first candidate for main induction.
2371 phi = it.Current()->AsPhi();
2372 } else {
2373 return false;
2374 }
2375 }
2376
2377 // Then test for a typical loopheader:
2378 // s: SuspendCheck
2379 // c: Condition(phi, bound)
2380 // i: If(c)
2381 if (phi != nullptr && TrySetPhiInduction(phi, /*restrict_uses*/ false)) {
Aart Bikcc42be02016-10-20 16:14:16 -07002382 HInstruction* s = block->GetFirstInstruction();
2383 if (s != nullptr && s->IsSuspendCheck()) {
2384 HInstruction* c = s->GetNext();
Aart Bikd86c0852017-04-14 12:00:15 -07002385 if (c != nullptr &&
2386 c->IsCondition() &&
2387 c->GetUses().HasExactlyOneElement() && // only used for termination
2388 !c->HasEnvironmentUses()) { // unlikely, but not impossible
Aart Bikcc42be02016-10-20 16:14:16 -07002389 HInstruction* i = c->GetNext();
2390 if (i != nullptr && i->IsIf() && i->InputAt(0) == c) {
2391 iset_->insert(c);
2392 iset_->insert(s);
Aart Bikb29f6842017-07-28 15:58:41 -07002393 *main_phi = phi;
Aart Bikcc42be02016-10-20 16:14:16 -07002394 return true;
2395 }
2396 }
2397 }
2398 }
2399 return false;
2400}
2401
2402bool HLoopOptimization::IsEmptyBody(HBasicBlock* block) {
Aart Bikf8f5a162017-02-06 15:35:29 -08002403 if (!block->GetPhis().IsEmpty()) {
2404 return false;
2405 }
2406 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
2407 HInstruction* instruction = it.Current();
2408 if (!instruction->IsGoto() && iset_->find(instruction) == iset_->end()) {
2409 return false;
Aart Bikcc42be02016-10-20 16:14:16 -07002410 }
Aart Bikf8f5a162017-02-06 15:35:29 -08002411 }
2412 return true;
2413}
2414
2415bool HLoopOptimization::IsUsedOutsideLoop(HLoopInformation* loop_info,
2416 HInstruction* instruction) {
Aart Bikb29f6842017-07-28 15:58:41 -07002417 // Deal with regular uses.
Aart Bikf8f5a162017-02-06 15:35:29 -08002418 for (const HUseListNode<HInstruction*>& use : instruction->GetUses()) {
2419 if (use.GetUser()->GetBlock()->GetLoopInformation() != loop_info) {
2420 return true;
2421 }
Aart Bikcc42be02016-10-20 16:14:16 -07002422 }
2423 return false;
2424}
2425
Aart Bik482095d2016-10-10 15:39:10 -07002426bool HLoopOptimization::IsOnlyUsedAfterLoop(HLoopInformation* loop_info,
Aart Bik8c4a8542016-10-06 11:36:57 -07002427 HInstruction* instruction,
Aart Bik6b69e0a2017-01-11 10:20:43 -08002428 bool collect_loop_uses,
Aart Bik38a3f212017-10-20 17:02:21 -07002429 /*out*/ uint32_t* use_count) {
Aart Bikb29f6842017-07-28 15:58:41 -07002430 // Deal with regular uses.
Aart Bik8c4a8542016-10-06 11:36:57 -07002431 for (const HUseListNode<HInstruction*>& use : instruction->GetUses()) {
2432 HInstruction* user = use.GetUser();
2433 if (iset_->find(user) == iset_->end()) { // not excluded?
2434 HLoopInformation* other_loop_info = user->GetBlock()->GetLoopInformation();
Aart Bik482095d2016-10-10 15:39:10 -07002435 if (other_loop_info != nullptr && other_loop_info->IsIn(*loop_info)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -08002436 // If collect_loop_uses is set, simply keep adding those uses to the set.
2437 // Otherwise, reject uses inside the loop that were not already in the set.
2438 if (collect_loop_uses) {
2439 iset_->insert(user);
2440 continue;
2441 }
Aart Bik8c4a8542016-10-06 11:36:57 -07002442 return false;
2443 }
2444 ++*use_count;
2445 }
2446 }
2447 return true;
2448}
2449
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002450bool HLoopOptimization::TryReplaceWithLastValue(HLoopInformation* loop_info,
2451 HInstruction* instruction,
2452 HBasicBlock* block) {
2453 // Try to replace outside uses with the last value.
Aart Bik807868e2016-11-03 17:51:43 -07002454 if (induction_range_.CanGenerateLastValue(instruction)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -08002455 HInstruction* replacement = induction_range_.GenerateLastValue(instruction, graph_, block);
Aart Bikb29f6842017-07-28 15:58:41 -07002456 // Deal with regular uses.
Aart Bik6b69e0a2017-01-11 10:20:43 -08002457 const HUseList<HInstruction*>& uses = instruction->GetUses();
2458 for (auto it = uses.begin(), end = uses.end(); it != end;) {
2459 HInstruction* user = it->GetUser();
2460 size_t index = it->GetIndex();
2461 ++it; // increment before replacing
2462 if (iset_->find(user) == iset_->end()) { // not excluded?
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002463 if (kIsDebugBuild) {
2464 // We have checked earlier in 'IsOnlyUsedAfterLoop' that the use is after the loop.
2465 HLoopInformation* other_loop_info = user->GetBlock()->GetLoopInformation();
2466 CHECK(other_loop_info == nullptr || !other_loop_info->IsIn(*loop_info));
2467 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08002468 user->ReplaceInput(replacement, index);
2469 induction_range_.Replace(user, instruction, replacement); // update induction
2470 }
2471 }
Aart Bikb29f6842017-07-28 15:58:41 -07002472 // Deal with environment uses.
Aart Bik6b69e0a2017-01-11 10:20:43 -08002473 const HUseList<HEnvironment*>& env_uses = instruction->GetEnvUses();
2474 for (auto it = env_uses.begin(), end = env_uses.end(); it != end;) {
2475 HEnvironment* user = it->GetUser();
2476 size_t index = it->GetIndex();
2477 ++it; // increment before replacing
2478 if (iset_->find(user->GetHolder()) == iset_->end()) { // not excluded?
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002479 // Only update environment uses after the loop.
Aart Bik14a68b42017-06-08 14:06:58 -07002480 HLoopInformation* other_loop_info = user->GetHolder()->GetBlock()->GetLoopInformation();
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002481 if (other_loop_info == nullptr || !other_loop_info->IsIn(*loop_info)) {
2482 user->RemoveAsUserOfInput(index);
2483 user->SetRawEnvAt(index, replacement);
2484 replacement->AddEnvUseAt(user, index);
2485 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08002486 }
2487 }
Aart Bik807868e2016-11-03 17:51:43 -07002488 return true;
Aart Bik8c4a8542016-10-06 11:36:57 -07002489 }
Aart Bik807868e2016-11-03 17:51:43 -07002490 return false;
Aart Bik8c4a8542016-10-06 11:36:57 -07002491}
2492
Aart Bikf8f5a162017-02-06 15:35:29 -08002493bool HLoopOptimization::TryAssignLastValue(HLoopInformation* loop_info,
2494 HInstruction* instruction,
2495 HBasicBlock* block,
2496 bool collect_loop_uses) {
2497 // Assigning the last value is always successful if there are no uses.
2498 // Otherwise, it succeeds in a no early-exit loop by generating the
2499 // proper last value assignment.
Aart Bik38a3f212017-10-20 17:02:21 -07002500 uint32_t use_count = 0;
Aart Bikf8f5a162017-02-06 15:35:29 -08002501 return IsOnlyUsedAfterLoop(loop_info, instruction, collect_loop_uses, &use_count) &&
2502 (use_count == 0 ||
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002503 (!IsEarlyExit(loop_info) && TryReplaceWithLastValue(loop_info, instruction, block)));
Aart Bikf8f5a162017-02-06 15:35:29 -08002504}
2505
Aart Bik6b69e0a2017-01-11 10:20:43 -08002506void HLoopOptimization::RemoveDeadInstructions(const HInstructionList& list) {
2507 for (HBackwardInstructionIterator i(list); !i.Done(); i.Advance()) {
2508 HInstruction* instruction = i.Current();
2509 if (instruction->IsDeadAndRemovable()) {
2510 simplified_ = true;
2511 instruction->GetBlock()->RemoveInstructionOrPhi(instruction);
2512 }
2513 }
2514}
2515
Aart Bik14a68b42017-06-08 14:06:58 -07002516bool HLoopOptimization::CanRemoveCycle() {
2517 for (HInstruction* i : *iset_) {
2518 // We can never remove instructions that have environment
2519 // uses when we compile 'debuggable'.
2520 if (i->HasEnvironmentUses() && graph_->IsDebuggable()) {
2521 return false;
2522 }
2523 // A deoptimization should never have an environment input removed.
2524 for (const HUseListNode<HEnvironment*>& use : i->GetEnvUses()) {
2525 if (use.GetUser()->GetHolder()->IsDeoptimize()) {
2526 return false;
2527 }
2528 }
2529 }
2530 return true;
2531}
2532
Aart Bik281c6812016-08-26 11:31:48 -07002533} // namespace art