blob: 770a011550cef31f5c48cf7b9309e721bdb142a8 [file] [log] [blame]
Aart Bik281c6812016-08-26 11:31:48 -07001/*
2 * Copyright (C) 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "loop_optimization.h"
18
Aart Bikf8f5a162017-02-06 15:35:29 -080019#include "arch/arm/instruction_set_features_arm.h"
20#include "arch/arm64/instruction_set_features_arm64.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070021#include "arch/instruction_set.h"
Aart Bikf8f5a162017-02-06 15:35:29 -080022#include "arch/x86/instruction_set_features_x86.h"
23#include "arch/x86_64/instruction_set_features_x86_64.h"
Vladimir Markoa0431112018-06-25 09:32:54 +010024#include "driver/compiler_options.h"
Aart Bik96202302016-10-04 17:33:56 -070025#include "linear_order.h"
Aart Bik38a3f212017-10-20 17:02:21 -070026#include "mirror/array-inl.h"
27#include "mirror/string.h"
Aart Bik281c6812016-08-26 11:31:48 -070028
Vladimir Marko0a516052019-10-14 13:00:44 +000029namespace art {
Aart Bik281c6812016-08-26 11:31:48 -070030
Aart Bikf8f5a162017-02-06 15:35:29 -080031// Enables vectorization (SIMDization) in the loop optimizer.
32static constexpr bool kEnableVectorization = true;
33
Aart Bik38a3f212017-10-20 17:02:21 -070034//
35// Static helpers.
36//
37
38// Base alignment for arrays/strings guaranteed by the Android runtime.
39static uint32_t BaseAlignment() {
40 return kObjectAlignment;
41}
42
43// Hidden offset for arrays/strings guaranteed by the Android runtime.
44static uint32_t HiddenOffset(DataType::Type type, bool is_string_char_at) {
45 return is_string_char_at
46 ? mirror::String::ValueOffset().Uint32Value()
47 : mirror::Array::DataOffset(DataType::Size(type)).Uint32Value();
48}
49
Aart Bik9abf8942016-10-14 09:49:42 -070050// Remove the instruction from the graph. A bit more elaborate than the usual
51// instruction removal, since there may be a cycle in the use structure.
Aart Bik281c6812016-08-26 11:31:48 -070052static void RemoveFromCycle(HInstruction* instruction) {
Aart Bik281c6812016-08-26 11:31:48 -070053 instruction->RemoveAsUserOfAllInputs();
54 instruction->RemoveEnvironmentUsers();
55 instruction->GetBlock()->RemoveInstructionOrPhi(instruction, /*ensure_safety=*/ false);
Artem Serov21c7e6f2017-07-27 16:04:42 +010056 RemoveEnvironmentUses(instruction);
57 ResetEnvironmentInputRecords(instruction);
Aart Bik281c6812016-08-26 11:31:48 -070058}
59
Aart Bik807868e2016-11-03 17:51:43 -070060// Detect a goto block and sets succ to the single successor.
Aart Bike3dedc52016-11-02 17:50:27 -070061static bool IsGotoBlock(HBasicBlock* block, /*out*/ HBasicBlock** succ) {
62 if (block->GetPredecessors().size() == 1 &&
63 block->GetSuccessors().size() == 1 &&
64 block->IsSingleGoto()) {
65 *succ = block->GetSingleSuccessor();
66 return true;
67 }
68 return false;
69}
70
Aart Bik807868e2016-11-03 17:51:43 -070071// Detect an early exit loop.
72static bool IsEarlyExit(HLoopInformation* loop_info) {
73 HBlocksInLoopReversePostOrderIterator it_loop(*loop_info);
74 for (it_loop.Advance(); !it_loop.Done(); it_loop.Advance()) {
75 for (HBasicBlock* successor : it_loop.Current()->GetSuccessors()) {
76 if (!loop_info->Contains(*successor)) {
77 return true;
78 }
79 }
80 }
81 return false;
82}
83
Aart Bik68ca7022017-09-26 16:44:23 -070084// Forward declaration.
85static bool IsZeroExtensionAndGet(HInstruction* instruction,
86 DataType::Type type,
Aart Bikdf011c32017-09-28 12:53:04 -070087 /*out*/ HInstruction** operand);
Aart Bik68ca7022017-09-26 16:44:23 -070088
Aart Bikdf011c32017-09-28 12:53:04 -070089// Detect a sign extension in instruction from the given type.
Aart Bikdbbac8f2017-09-01 13:06:08 -070090// Returns the promoted operand on success.
Aart Bikf3e61ee2017-04-12 17:09:20 -070091static bool IsSignExtensionAndGet(HInstruction* instruction,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +010092 DataType::Type type,
Aart Bikdf011c32017-09-28 12:53:04 -070093 /*out*/ HInstruction** operand) {
Aart Bikf3e61ee2017-04-12 17:09:20 -070094 // Accept any already wider constant that would be handled properly by sign
95 // extension when represented in the *width* of the given narrower data type
Aart Bik4d1a9d42017-10-19 14:40:55 -070096 // (the fact that Uint8/Uint16 normally zero extend does not matter here).
Aart Bikf3e61ee2017-04-12 17:09:20 -070097 int64_t value = 0;
Aart Bik50e20d52017-05-05 14:07:29 -070098 if (IsInt64AndGet(instruction, /*out*/ &value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -070099 switch (type) {
Vladimir Markod5d2f2c2017-09-26 12:37:26 +0100100 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100101 case DataType::Type::kInt8:
Aart Bikdbbac8f2017-09-01 13:06:08 -0700102 if (IsInt<8>(value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700103 *operand = instruction;
104 return true;
105 }
106 return false;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100107 case DataType::Type::kUint16:
108 case DataType::Type::kInt16:
Aart Bikdbbac8f2017-09-01 13:06:08 -0700109 if (IsInt<16>(value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700110 *operand = instruction;
111 return true;
112 }
113 return false;
114 default:
115 return false;
116 }
117 }
Aart Bikdf011c32017-09-28 12:53:04 -0700118 // An implicit widening conversion of any signed expression sign-extends.
119 if (instruction->GetType() == type) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700120 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100121 case DataType::Type::kInt8:
122 case DataType::Type::kInt16:
Aart Bikf3e61ee2017-04-12 17:09:20 -0700123 *operand = instruction;
124 return true;
125 default:
126 return false;
127 }
128 }
Aart Bikdf011c32017-09-28 12:53:04 -0700129 // An explicit widening conversion of a signed expression sign-extends.
Aart Bik68ca7022017-09-26 16:44:23 -0700130 if (instruction->IsTypeConversion()) {
Aart Bikdf011c32017-09-28 12:53:04 -0700131 HInstruction* conv = instruction->InputAt(0);
132 DataType::Type from = conv->GetType();
Aart Bik68ca7022017-09-26 16:44:23 -0700133 switch (instruction->GetType()) {
Aart Bikdf011c32017-09-28 12:53:04 -0700134 case DataType::Type::kInt32:
Aart Bik68ca7022017-09-26 16:44:23 -0700135 case DataType::Type::kInt64:
Aart Bikdf011c32017-09-28 12:53:04 -0700136 if (type == from && (from == DataType::Type::kInt8 ||
137 from == DataType::Type::kInt16 ||
138 from == DataType::Type::kInt32)) {
139 *operand = conv;
140 return true;
141 }
142 return false;
Aart Bik68ca7022017-09-26 16:44:23 -0700143 case DataType::Type::kInt16:
144 return type == DataType::Type::kUint16 &&
145 from == DataType::Type::kUint16 &&
Aart Bikdf011c32017-09-28 12:53:04 -0700146 IsZeroExtensionAndGet(instruction->InputAt(0), type, /*out*/ operand);
Aart Bik68ca7022017-09-26 16:44:23 -0700147 default:
148 return false;
149 }
Aart Bikdbbac8f2017-09-01 13:06:08 -0700150 }
Aart Bikf3e61ee2017-04-12 17:09:20 -0700151 return false;
152}
153
Aart Bikdf011c32017-09-28 12:53:04 -0700154// Detect a zero extension in instruction from the given type.
Aart Bikdbbac8f2017-09-01 13:06:08 -0700155// Returns the promoted operand on success.
Aart Bikf3e61ee2017-04-12 17:09:20 -0700156static bool IsZeroExtensionAndGet(HInstruction* instruction,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100157 DataType::Type type,
Aart Bikdf011c32017-09-28 12:53:04 -0700158 /*out*/ HInstruction** operand) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700159 // Accept any already wider constant that would be handled properly by zero
160 // extension when represented in the *width* of the given narrower data type
Aart Bikdf011c32017-09-28 12:53:04 -0700161 // (the fact that Int8/Int16 normally sign extend does not matter here).
Aart Bikf3e61ee2017-04-12 17:09:20 -0700162 int64_t value = 0;
Aart Bik50e20d52017-05-05 14:07:29 -0700163 if (IsInt64AndGet(instruction, /*out*/ &value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700164 switch (type) {
Vladimir Markod5d2f2c2017-09-26 12:37:26 +0100165 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100166 case DataType::Type::kInt8:
Aart Bikdbbac8f2017-09-01 13:06:08 -0700167 if (IsUint<8>(value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700168 *operand = instruction;
169 return true;
170 }
171 return false;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100172 case DataType::Type::kUint16:
173 case DataType::Type::kInt16:
Aart Bikdbbac8f2017-09-01 13:06:08 -0700174 if (IsUint<16>(value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700175 *operand = instruction;
176 return true;
177 }
178 return false;
179 default:
180 return false;
181 }
182 }
Aart Bikdf011c32017-09-28 12:53:04 -0700183 // An implicit widening conversion of any unsigned expression zero-extends.
184 if (instruction->GetType() == type) {
Vladimir Markod5d2f2c2017-09-26 12:37:26 +0100185 switch (type) {
186 case DataType::Type::kUint8:
187 case DataType::Type::kUint16:
188 *operand = instruction;
189 return true;
190 default:
191 return false;
Aart Bikf3e61ee2017-04-12 17:09:20 -0700192 }
193 }
Aart Bikdf011c32017-09-28 12:53:04 -0700194 // An explicit widening conversion of an unsigned expression zero-extends.
Aart Bik68ca7022017-09-26 16:44:23 -0700195 if (instruction->IsTypeConversion()) {
Aart Bikdf011c32017-09-28 12:53:04 -0700196 HInstruction* conv = instruction->InputAt(0);
197 DataType::Type from = conv->GetType();
Aart Bik68ca7022017-09-26 16:44:23 -0700198 switch (instruction->GetType()) {
Aart Bikdf011c32017-09-28 12:53:04 -0700199 case DataType::Type::kInt32:
Aart Bik68ca7022017-09-26 16:44:23 -0700200 case DataType::Type::kInt64:
Aart Bikdf011c32017-09-28 12:53:04 -0700201 if (type == from && from == DataType::Type::kUint16) {
202 *operand = conv;
203 return true;
204 }
205 return false;
Aart Bik68ca7022017-09-26 16:44:23 -0700206 case DataType::Type::kUint16:
207 return type == DataType::Type::kInt16 &&
208 from == DataType::Type::kInt16 &&
Aart Bikdf011c32017-09-28 12:53:04 -0700209 IsSignExtensionAndGet(instruction->InputAt(0), type, /*out*/ operand);
Aart Bik68ca7022017-09-26 16:44:23 -0700210 default:
211 return false;
212 }
Aart Bikdbbac8f2017-09-01 13:06:08 -0700213 }
Aart Bikf3e61ee2017-04-12 17:09:20 -0700214 return false;
215}
216
Aart Bik304c8a52017-05-23 11:01:13 -0700217// Detect situations with same-extension narrower operands.
218// Returns true on success and sets is_unsigned accordingly.
219static bool IsNarrowerOperands(HInstruction* a,
220 HInstruction* b,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100221 DataType::Type type,
Aart Bik304c8a52017-05-23 11:01:13 -0700222 /*out*/ HInstruction** r,
223 /*out*/ HInstruction** s,
224 /*out*/ bool* is_unsigned) {
Nicolas Geoffraya3e23262018-03-28 11:15:12 +0000225 DCHECK(a != nullptr && b != nullptr);
Aart Bik4d1a9d42017-10-19 14:40:55 -0700226 // Look for a matching sign extension.
227 DataType::Type stype = HVecOperation::ToSignedType(type);
228 if (IsSignExtensionAndGet(a, stype, r) && IsSignExtensionAndGet(b, stype, s)) {
Aart Bik304c8a52017-05-23 11:01:13 -0700229 *is_unsigned = false;
230 return true;
Aart Bik4d1a9d42017-10-19 14:40:55 -0700231 }
232 // Look for a matching zero extension.
233 DataType::Type utype = HVecOperation::ToUnsignedType(type);
234 if (IsZeroExtensionAndGet(a, utype, r) && IsZeroExtensionAndGet(b, utype, s)) {
Aart Bik304c8a52017-05-23 11:01:13 -0700235 *is_unsigned = true;
236 return true;
237 }
238 return false;
239}
240
241// As above, single operand.
242static bool IsNarrowerOperand(HInstruction* a,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100243 DataType::Type type,
Aart Bik304c8a52017-05-23 11:01:13 -0700244 /*out*/ HInstruction** r,
245 /*out*/ bool* is_unsigned) {
Nicolas Geoffraya3e23262018-03-28 11:15:12 +0000246 DCHECK(a != nullptr);
Aart Bik4d1a9d42017-10-19 14:40:55 -0700247 // Look for a matching sign extension.
248 DataType::Type stype = HVecOperation::ToSignedType(type);
249 if (IsSignExtensionAndGet(a, stype, r)) {
Aart Bik304c8a52017-05-23 11:01:13 -0700250 *is_unsigned = false;
251 return true;
Aart Bik4d1a9d42017-10-19 14:40:55 -0700252 }
253 // Look for a matching zero extension.
254 DataType::Type utype = HVecOperation::ToUnsignedType(type);
255 if (IsZeroExtensionAndGet(a, utype, r)) {
Aart Bik304c8a52017-05-23 11:01:13 -0700256 *is_unsigned = true;
257 return true;
258 }
259 return false;
260}
261
Aart Bikdbbac8f2017-09-01 13:06:08 -0700262// Compute relative vector length based on type difference.
Aart Bik38a3f212017-10-20 17:02:21 -0700263static uint32_t GetOtherVL(DataType::Type other_type, DataType::Type vector_type, uint32_t vl) {
Vladimir Markod5d2f2c2017-09-26 12:37:26 +0100264 DCHECK(DataType::IsIntegralType(other_type));
265 DCHECK(DataType::IsIntegralType(vector_type));
266 DCHECK_GE(DataType::SizeShift(other_type), DataType::SizeShift(vector_type));
267 return vl >> (DataType::SizeShift(other_type) - DataType::SizeShift(vector_type));
Aart Bikdbbac8f2017-09-01 13:06:08 -0700268}
269
Nicolas Geoffraya3e23262018-03-28 11:15:12 +0000270// Detect up to two added operands a and b and an acccumulated constant c.
271static bool IsAddConst(HInstruction* instruction,
272 /*out*/ HInstruction** a,
273 /*out*/ HInstruction** b,
274 /*out*/ int64_t* c,
275 int32_t depth = 8) { // don't search too deep
Aart Bik5f805002017-05-16 16:42:41 -0700276 int64_t value = 0;
Nicolas Geoffraya3e23262018-03-28 11:15:12 +0000277 // Enter add/sub while still within reasonable depth.
278 if (depth > 0) {
279 if (instruction->IsAdd()) {
280 return IsAddConst(instruction->InputAt(0), a, b, c, depth - 1) &&
281 IsAddConst(instruction->InputAt(1), a, b, c, depth - 1);
282 } else if (instruction->IsSub() &&
283 IsInt64AndGet(instruction->InputAt(1), &value)) {
284 *c -= value;
285 return IsAddConst(instruction->InputAt(0), a, b, c, depth - 1);
286 }
287 }
288 // Otherwise, deal with leaf nodes.
Aart Bik5f805002017-05-16 16:42:41 -0700289 if (IsInt64AndGet(instruction, &value)) {
290 *c += value;
291 return true;
Aart Bik5f805002017-05-16 16:42:41 -0700292 } else if (*a == nullptr) {
293 *a = instruction;
294 return true;
295 } else if (*b == nullptr) {
296 *b = instruction;
297 return true;
298 }
Nicolas Geoffraya3e23262018-03-28 11:15:12 +0000299 return false; // too many operands
Aart Bik5f805002017-05-16 16:42:41 -0700300}
301
Nicolas Geoffraya3e23262018-03-28 11:15:12 +0000302// Detect a + b + c with optional constant c.
303static bool IsAddConst2(HGraph* graph,
304 HInstruction* instruction,
305 /*out*/ HInstruction** a,
306 /*out*/ HInstruction** b,
307 /*out*/ int64_t* c) {
308 if (IsAddConst(instruction, a, b, c) && *a != nullptr) {
309 if (*b == nullptr) {
310 // Constant is usually already present, unless accumulated.
311 *b = graph->GetConstant(instruction->GetType(), (*c));
312 *c = 0;
Aart Bik5f805002017-05-16 16:42:41 -0700313 }
Aart Bik5f805002017-05-16 16:42:41 -0700314 return true;
315 }
316 return false;
317}
318
Nicolas Geoffraya3e23262018-03-28 11:15:12 +0000319// Detect a direct a - b or a hidden a - (-c).
320static bool IsSubConst2(HGraph* graph,
321 HInstruction* instruction,
322 /*out*/ HInstruction** a,
323 /*out*/ HInstruction** b) {
324 int64_t c = 0;
325 if (instruction->IsSub()) {
326 *a = instruction->InputAt(0);
327 *b = instruction->InputAt(1);
328 return true;
329 } else if (IsAddConst(instruction, a, b, &c) && *a != nullptr && *b == nullptr) {
330 // Constant for the hidden subtraction.
331 *b = graph->GetConstant(instruction->GetType(), -c);
332 return true;
Aart Bikdf011c32017-09-28 12:53:04 -0700333 }
334 return false;
335}
336
Aart Bikb29f6842017-07-28 15:58:41 -0700337// Detect reductions of the following forms,
Aart Bikb29f6842017-07-28 15:58:41 -0700338// x = x_phi + ..
339// x = x_phi - ..
Aart Bikb29f6842017-07-28 15:58:41 -0700340static bool HasReductionFormat(HInstruction* reduction, HInstruction* phi) {
Aart Bik3f08e9b2018-05-01 13:42:03 -0700341 if (reduction->IsAdd()) {
Aart Bikdbbac8f2017-09-01 13:06:08 -0700342 return (reduction->InputAt(0) == phi && reduction->InputAt(1) != phi) ||
343 (reduction->InputAt(0) != phi && reduction->InputAt(1) == phi);
Aart Bikb29f6842017-07-28 15:58:41 -0700344 } else if (reduction->IsSub()) {
Aart Bikdbbac8f2017-09-01 13:06:08 -0700345 return (reduction->InputAt(0) == phi && reduction->InputAt(1) != phi);
Aart Bikb29f6842017-07-28 15:58:41 -0700346 }
347 return false;
348}
349
Aart Bikdbbac8f2017-09-01 13:06:08 -0700350// Translates vector operation to reduction kind.
351static HVecReduce::ReductionKind GetReductionKind(HVecOperation* reduction) {
Shalini Salomi Bodapati81d15be2019-05-30 11:00:42 +0530352 if (reduction->IsVecAdd() ||
Artem Serovaaac0e32018-08-07 00:52:22 +0100353 reduction->IsVecSub() ||
354 reduction->IsVecSADAccumulate() ||
355 reduction->IsVecDotProd()) {
Aart Bik0148de42017-09-05 09:25:01 -0700356 return HVecReduce::kSum;
Aart Bik0148de42017-09-05 09:25:01 -0700357 }
Aart Bik38a3f212017-10-20 17:02:21 -0700358 LOG(FATAL) << "Unsupported SIMD reduction " << reduction->GetId();
Aart Bik0148de42017-09-05 09:25:01 -0700359 UNREACHABLE();
360}
361
Aart Bikf8f5a162017-02-06 15:35:29 -0800362// Test vector restrictions.
363static bool HasVectorRestrictions(uint64_t restrictions, uint64_t tested) {
364 return (restrictions & tested) != 0;
365}
366
Aart Bikf3e61ee2017-04-12 17:09:20 -0700367// Insert an instruction.
Aart Bikf8f5a162017-02-06 15:35:29 -0800368static HInstruction* Insert(HBasicBlock* block, HInstruction* instruction) {
369 DCHECK(block != nullptr);
370 DCHECK(instruction != nullptr);
371 block->InsertInstructionBefore(instruction, block->GetLastInstruction());
372 return instruction;
373}
374
Artem Serov21c7e6f2017-07-27 16:04:42 +0100375// Check that instructions from the induction sets are fully removed: have no uses
376// and no other instructions use them.
Vladimir Markoca6fff82017-10-03 14:49:14 +0100377static bool CheckInductionSetFullyRemoved(ScopedArenaSet<HInstruction*>* iset) {
Artem Serov21c7e6f2017-07-27 16:04:42 +0100378 for (HInstruction* instr : *iset) {
379 if (instr->GetBlock() != nullptr ||
380 !instr->GetUses().empty() ||
381 !instr->GetEnvUses().empty() ||
382 HasEnvironmentUsedByOthers(instr)) {
383 return false;
384 }
385 }
Artem Serov21c7e6f2017-07-27 16:04:42 +0100386 return true;
387}
388
Artem Serov72411e62017-10-19 16:18:07 +0100389// Tries to statically evaluate condition of the specified "HIf" for other condition checks.
390static void TryToEvaluateIfCondition(HIf* instruction, HGraph* graph) {
391 HInstruction* cond = instruction->InputAt(0);
392
393 // If a condition 'cond' is evaluated in an HIf instruction then in the successors of the
394 // IF_BLOCK we statically know the value of the condition 'cond' (TRUE in TRUE_SUCC, FALSE in
395 // FALSE_SUCC). Using that we can replace another evaluation (use) EVAL of the same 'cond'
396 // with TRUE value (FALSE value) if every path from the ENTRY_BLOCK to EVAL_BLOCK contains the
397 // edge HIF_BLOCK->TRUE_SUCC (HIF_BLOCK->FALSE_SUCC).
398 // if (cond) { if(cond) {
399 // if (cond) {} if (1) {}
400 // } else { =======> } else {
401 // if (cond) {} if (0) {}
402 // } }
403 if (!cond->IsConstant()) {
404 HBasicBlock* true_succ = instruction->IfTrueSuccessor();
405 HBasicBlock* false_succ = instruction->IfFalseSuccessor();
406
407 DCHECK_EQ(true_succ->GetPredecessors().size(), 1u);
408 DCHECK_EQ(false_succ->GetPredecessors().size(), 1u);
409
410 const HUseList<HInstruction*>& uses = cond->GetUses();
411 for (auto it = uses.begin(), end = uses.end(); it != end; /* ++it below */) {
412 HInstruction* user = it->GetUser();
413 size_t index = it->GetIndex();
414 HBasicBlock* user_block = user->GetBlock();
415 // Increment `it` now because `*it` may disappear thanks to user->ReplaceInput().
416 ++it;
417 if (true_succ->Dominates(user_block)) {
418 user->ReplaceInput(graph->GetIntConstant(1), index);
419 } else if (false_succ->Dominates(user_block)) {
420 user->ReplaceInput(graph->GetIntConstant(0), index);
421 }
422 }
423 }
424}
425
Artem Serov18ba1da2018-05-16 19:06:32 +0100426// Peel the first 'count' iterations of the loop.
Nicolas Geoffray256c94b2019-04-29 10:55:09 +0100427static void PeelByCount(HLoopInformation* loop_info,
428 int count,
429 InductionVarRange* induction_range) {
Artem Serov18ba1da2018-05-16 19:06:32 +0100430 for (int i = 0; i < count; i++) {
431 // Perform peeling.
Nicolas Geoffray256c94b2019-04-29 10:55:09 +0100432 PeelUnrollSimpleHelper helper(loop_info, induction_range);
Artem Serov18ba1da2018-05-16 19:06:32 +0100433 helper.DoPeeling();
434 }
435}
436
Artem Serovaaac0e32018-08-07 00:52:22 +0100437// Returns the narrower type out of instructions a and b types.
438static DataType::Type GetNarrowerType(HInstruction* a, HInstruction* b) {
439 DataType::Type type = a->GetType();
440 if (DataType::Size(b->GetType()) < DataType::Size(type)) {
441 type = b->GetType();
442 }
443 if (a->IsTypeConversion() &&
444 DataType::Size(a->InputAt(0)->GetType()) < DataType::Size(type)) {
445 type = a->InputAt(0)->GetType();
446 }
447 if (b->IsTypeConversion() &&
448 DataType::Size(b->InputAt(0)->GetType()) < DataType::Size(type)) {
449 type = b->InputAt(0)->GetType();
450 }
451 return type;
452}
453
Aart Bik281c6812016-08-26 11:31:48 -0700454//
Aart Bikb29f6842017-07-28 15:58:41 -0700455// Public methods.
Aart Bik281c6812016-08-26 11:31:48 -0700456//
457
458HLoopOptimization::HLoopOptimization(HGraph* graph,
Vladimir Markoa0431112018-06-25 09:32:54 +0100459 const CompilerOptions* compiler_options,
Aart Bikb92cc332017-09-06 15:53:17 -0700460 HInductionVarAnalysis* induction_analysis,
Aart Bik2ca10eb2017-11-15 15:17:53 -0800461 OptimizingCompilerStats* stats,
462 const char* name)
463 : HOptimization(graph, name, stats),
Vladimir Markoa0431112018-06-25 09:32:54 +0100464 compiler_options_(compiler_options),
Aart Bik281c6812016-08-26 11:31:48 -0700465 induction_range_(induction_analysis),
Aart Bik96202302016-10-04 17:33:56 -0700466 loop_allocator_(nullptr),
Vladimir Markoca6fff82017-10-03 14:49:14 +0100467 global_allocator_(graph_->GetAllocator()),
Aart Bik281c6812016-08-26 11:31:48 -0700468 top_loop_(nullptr),
Aart Bik8c4a8542016-10-06 11:36:57 -0700469 last_loop_(nullptr),
Aart Bik482095d2016-10-10 15:39:10 -0700470 iset_(nullptr),
Aart Bikb29f6842017-07-28 15:58:41 -0700471 reductions_(nullptr),
Aart Bikf8f5a162017-02-06 15:35:29 -0800472 simplified_(false),
473 vector_length_(0),
474 vector_refs_(nullptr),
Aart Bik38a3f212017-10-20 17:02:21 -0700475 vector_static_peeling_factor_(0),
476 vector_dynamic_peeling_candidate_(nullptr),
Aart Bik14a68b42017-06-08 14:06:58 -0700477 vector_runtime_test_a_(nullptr),
478 vector_runtime_test_b_(nullptr),
Aart Bik0148de42017-09-05 09:25:01 -0700479 vector_map_(nullptr),
Vladimir Markoca6fff82017-10-03 14:49:14 +0100480 vector_permanent_map_(nullptr),
481 vector_mode_(kSequential),
482 vector_preheader_(nullptr),
483 vector_header_(nullptr),
484 vector_body_(nullptr),
Artem Serov121f2032017-10-23 19:19:06 +0100485 vector_index_(nullptr),
Vladimir Markoa0431112018-06-25 09:32:54 +0100486 arch_loop_helper_(ArchNoOptsLoopHelper::Create(compiler_options_ != nullptr
487 ? compiler_options_->GetInstructionSet()
Artem Serov121f2032017-10-23 19:19:06 +0100488 : InstructionSet::kNone,
489 global_allocator_)) {
Aart Bik281c6812016-08-26 11:31:48 -0700490}
491
Aart Bik24773202018-04-26 10:28:51 -0700492bool HLoopOptimization::Run() {
Mingyao Yang01b47b02017-02-03 12:09:57 -0800493 // Skip if there is no loop or the graph has try-catch/irreducible loops.
Aart Bik281c6812016-08-26 11:31:48 -0700494 // TODO: make this less of a sledgehammer.
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800495 if (!graph_->HasLoops() || graph_->HasTryCatch() || graph_->HasIrreducibleLoops()) {
Aart Bik24773202018-04-26 10:28:51 -0700496 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700497 }
498
Vladimir Markoca6fff82017-10-03 14:49:14 +0100499 // Phase-local allocator.
500 ScopedArenaAllocator allocator(graph_->GetArenaStack());
Aart Bik96202302016-10-04 17:33:56 -0700501 loop_allocator_ = &allocator;
Nicolas Geoffrayebe16742016-10-05 09:55:42 +0100502
Aart Bik96202302016-10-04 17:33:56 -0700503 // Perform loop optimizations.
Aart Bik24773202018-04-26 10:28:51 -0700504 bool didLoopOpt = LocalRun();
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800505 if (top_loop_ == nullptr) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800506 graph_->SetHasLoops(false); // no more loops
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800507 }
508
Aart Bik96202302016-10-04 17:33:56 -0700509 // Detach.
510 loop_allocator_ = nullptr;
511 last_loop_ = top_loop_ = nullptr;
Aart Bik24773202018-04-26 10:28:51 -0700512
513 return didLoopOpt;
Aart Bik96202302016-10-04 17:33:56 -0700514}
515
Aart Bikb29f6842017-07-28 15:58:41 -0700516//
517// Loop setup and traversal.
518//
519
Aart Bik24773202018-04-26 10:28:51 -0700520bool HLoopOptimization::LocalRun() {
521 bool didLoopOpt = false;
Aart Bik96202302016-10-04 17:33:56 -0700522 // Build the linear order using the phase-local allocator. This step enables building
523 // a loop hierarchy that properly reflects the outer-inner and previous-next relation.
Vladimir Markoca6fff82017-10-03 14:49:14 +0100524 ScopedArenaVector<HBasicBlock*> linear_order(loop_allocator_->Adapter(kArenaAllocLinearOrder));
525 LinearizeGraph(graph_, &linear_order);
Aart Bik96202302016-10-04 17:33:56 -0700526
Aart Bik281c6812016-08-26 11:31:48 -0700527 // Build the loop hierarchy.
Aart Bik96202302016-10-04 17:33:56 -0700528 for (HBasicBlock* block : linear_order) {
Aart Bik281c6812016-08-26 11:31:48 -0700529 if (block->IsLoopHeader()) {
530 AddLoop(block->GetLoopInformation());
531 }
532 }
Aart Bik96202302016-10-04 17:33:56 -0700533
Aart Bik8c4a8542016-10-06 11:36:57 -0700534 // Traverse the loop hierarchy inner-to-outer and optimize. Traversal can use
Aart Bikf8f5a162017-02-06 15:35:29 -0800535 // temporary data structures using the phase-local allocator. All new HIR
536 // should use the global allocator.
Aart Bik8c4a8542016-10-06 11:36:57 -0700537 if (top_loop_ != nullptr) {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100538 ScopedArenaSet<HInstruction*> iset(loop_allocator_->Adapter(kArenaAllocLoopOptimization));
539 ScopedArenaSafeMap<HInstruction*, HInstruction*> reds(
Aart Bikb29f6842017-07-28 15:58:41 -0700540 std::less<HInstruction*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
Vladimir Markoca6fff82017-10-03 14:49:14 +0100541 ScopedArenaSet<ArrayReference> refs(loop_allocator_->Adapter(kArenaAllocLoopOptimization));
542 ScopedArenaSafeMap<HInstruction*, HInstruction*> map(
Aart Bikf8f5a162017-02-06 15:35:29 -0800543 std::less<HInstruction*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
Vladimir Markoca6fff82017-10-03 14:49:14 +0100544 ScopedArenaSafeMap<HInstruction*, HInstruction*> perm(
Aart Bik0148de42017-09-05 09:25:01 -0700545 std::less<HInstruction*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
Aart Bikf8f5a162017-02-06 15:35:29 -0800546 // Attach.
Aart Bik8c4a8542016-10-06 11:36:57 -0700547 iset_ = &iset;
Aart Bikb29f6842017-07-28 15:58:41 -0700548 reductions_ = &reds;
Aart Bikf8f5a162017-02-06 15:35:29 -0800549 vector_refs_ = &refs;
550 vector_map_ = &map;
Aart Bik0148de42017-09-05 09:25:01 -0700551 vector_permanent_map_ = &perm;
Aart Bikf8f5a162017-02-06 15:35:29 -0800552 // Traverse.
Aart Bik24773202018-04-26 10:28:51 -0700553 didLoopOpt = TraverseLoopsInnerToOuter(top_loop_);
Aart Bikf8f5a162017-02-06 15:35:29 -0800554 // Detach.
555 iset_ = nullptr;
Aart Bikb29f6842017-07-28 15:58:41 -0700556 reductions_ = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800557 vector_refs_ = nullptr;
558 vector_map_ = nullptr;
Aart Bik0148de42017-09-05 09:25:01 -0700559 vector_permanent_map_ = nullptr;
Aart Bik8c4a8542016-10-06 11:36:57 -0700560 }
Aart Bik24773202018-04-26 10:28:51 -0700561 return didLoopOpt;
Aart Bik281c6812016-08-26 11:31:48 -0700562}
563
564void HLoopOptimization::AddLoop(HLoopInformation* loop_info) {
565 DCHECK(loop_info != nullptr);
Aart Bikf8f5a162017-02-06 15:35:29 -0800566 LoopNode* node = new (loop_allocator_) LoopNode(loop_info);
Aart Bik281c6812016-08-26 11:31:48 -0700567 if (last_loop_ == nullptr) {
568 // First loop.
569 DCHECK(top_loop_ == nullptr);
570 last_loop_ = top_loop_ = node;
571 } else if (loop_info->IsIn(*last_loop_->loop_info)) {
572 // Inner loop.
573 node->outer = last_loop_;
574 DCHECK(last_loop_->inner == nullptr);
575 last_loop_ = last_loop_->inner = node;
576 } else {
577 // Subsequent loop.
578 while (last_loop_->outer != nullptr && !loop_info->IsIn(*last_loop_->outer->loop_info)) {
579 last_loop_ = last_loop_->outer;
580 }
581 node->outer = last_loop_->outer;
582 node->previous = last_loop_;
583 DCHECK(last_loop_->next == nullptr);
584 last_loop_ = last_loop_->next = node;
585 }
586}
587
588void HLoopOptimization::RemoveLoop(LoopNode* node) {
589 DCHECK(node != nullptr);
Aart Bik8c4a8542016-10-06 11:36:57 -0700590 DCHECK(node->inner == nullptr);
591 if (node->previous != nullptr) {
592 // Within sequence.
593 node->previous->next = node->next;
594 if (node->next != nullptr) {
595 node->next->previous = node->previous;
596 }
597 } else {
598 // First of sequence.
599 if (node->outer != nullptr) {
600 node->outer->inner = node->next;
601 } else {
602 top_loop_ = node->next;
603 }
604 if (node->next != nullptr) {
605 node->next->outer = node->outer;
606 node->next->previous = nullptr;
607 }
608 }
Aart Bik281c6812016-08-26 11:31:48 -0700609}
610
Aart Bikb29f6842017-07-28 15:58:41 -0700611bool HLoopOptimization::TraverseLoopsInnerToOuter(LoopNode* node) {
612 bool changed = false;
Aart Bik281c6812016-08-26 11:31:48 -0700613 for ( ; node != nullptr; node = node->next) {
Aart Bikb29f6842017-07-28 15:58:41 -0700614 // Visit inner loops first. Recompute induction information for this
615 // loop if the induction of any inner loop has changed.
616 if (TraverseLoopsInnerToOuter(node->inner)) {
Aart Bik482095d2016-10-10 15:39:10 -0700617 induction_range_.ReVisit(node->loop_info);
Aart Bika8360cd2018-05-02 16:07:51 -0700618 changed = true;
Aart Bik482095d2016-10-10 15:39:10 -0700619 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800620 // Repeat simplifications in the loop-body until no more changes occur.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800621 // Note that since each simplification consists of eliminating code (without
622 // introducing new code), this process is always finite.
Aart Bikdf7822e2016-12-06 10:05:30 -0800623 do {
624 simplified_ = false;
Aart Bikdf7822e2016-12-06 10:05:30 -0800625 SimplifyInduction(node);
Aart Bik6b69e0a2017-01-11 10:20:43 -0800626 SimplifyBlocks(node);
Aart Bikb29f6842017-07-28 15:58:41 -0700627 changed = simplified_ || changed;
Aart Bikdf7822e2016-12-06 10:05:30 -0800628 } while (simplified_);
Aart Bikf8f5a162017-02-06 15:35:29 -0800629 // Optimize inner loop.
Aart Bik9abf8942016-10-14 09:49:42 -0700630 if (node->inner == nullptr) {
Aart Bikb29f6842017-07-28 15:58:41 -0700631 changed = OptimizeInnerLoop(node) || changed;
Aart Bik9abf8942016-10-14 09:49:42 -0700632 }
Aart Bik281c6812016-08-26 11:31:48 -0700633 }
Aart Bikb29f6842017-07-28 15:58:41 -0700634 return changed;
Aart Bik281c6812016-08-26 11:31:48 -0700635}
636
Aart Bikf8f5a162017-02-06 15:35:29 -0800637//
638// Optimization.
639//
640
Aart Bik281c6812016-08-26 11:31:48 -0700641void HLoopOptimization::SimplifyInduction(LoopNode* node) {
642 HBasicBlock* header = node->loop_info->GetHeader();
643 HBasicBlock* preheader = node->loop_info->GetPreHeader();
Aart Bik8c4a8542016-10-06 11:36:57 -0700644 // Scan the phis in the header to find opportunities to simplify an induction
645 // cycle that is only used outside the loop. Replace these uses, if any, with
646 // the last value and remove the induction cycle.
647 // Examples: for (int i = 0; x != null; i++) { .... no i .... }
648 // for (int i = 0; i < 10; i++, k++) { .... no k .... } return k;
Aart Bik281c6812016-08-26 11:31:48 -0700649 for (HInstructionIterator it(header->GetPhis()); !it.Done(); it.Advance()) {
650 HPhi* phi = it.Current()->AsPhi();
Aart Bikf8f5a162017-02-06 15:35:29 -0800651 if (TrySetPhiInduction(phi, /*restrict_uses*/ true) &&
652 TryAssignLastValue(node->loop_info, phi, preheader, /*collect_loop_uses*/ false)) {
Aart Bik671e48a2017-08-09 13:16:56 -0700653 // Note that it's ok to have replaced uses after the loop with the last value, without
654 // being able to remove the cycle. Environment uses (which are the reason we may not be
655 // able to remove the cycle) within the loop will still hold the right value. We must
656 // have tried first, however, to replace outside uses.
657 if (CanRemoveCycle()) {
658 simplified_ = true;
659 for (HInstruction* i : *iset_) {
660 RemoveFromCycle(i);
661 }
662 DCHECK(CheckInductionSetFullyRemoved(iset_));
Aart Bik281c6812016-08-26 11:31:48 -0700663 }
Aart Bik482095d2016-10-10 15:39:10 -0700664 }
665 }
666}
667
668void HLoopOptimization::SimplifyBlocks(LoopNode* node) {
Aart Bikdf7822e2016-12-06 10:05:30 -0800669 // Iterate over all basic blocks in the loop-body.
670 for (HBlocksInLoopIterator it(*node->loop_info); !it.Done(); it.Advance()) {
671 HBasicBlock* block = it.Current();
672 // Remove dead instructions from the loop-body.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800673 RemoveDeadInstructions(block->GetPhis());
674 RemoveDeadInstructions(block->GetInstructions());
Aart Bikdf7822e2016-12-06 10:05:30 -0800675 // Remove trivial control flow blocks from the loop-body.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800676 if (block->GetPredecessors().size() == 1 &&
677 block->GetSuccessors().size() == 1 &&
678 block->GetSingleSuccessor()->GetPredecessors().size() == 1) {
Aart Bikdf7822e2016-12-06 10:05:30 -0800679 simplified_ = true;
Aart Bik6b69e0a2017-01-11 10:20:43 -0800680 block->MergeWith(block->GetSingleSuccessor());
Aart Bikdf7822e2016-12-06 10:05:30 -0800681 } else if (block->GetSuccessors().size() == 2) {
682 // Trivial if block can be bypassed to either branch.
683 HBasicBlock* succ0 = block->GetSuccessors()[0];
684 HBasicBlock* succ1 = block->GetSuccessors()[1];
685 HBasicBlock* meet0 = nullptr;
686 HBasicBlock* meet1 = nullptr;
687 if (succ0 != succ1 &&
688 IsGotoBlock(succ0, &meet0) &&
689 IsGotoBlock(succ1, &meet1) &&
690 meet0 == meet1 && // meets again
691 meet0 != block && // no self-loop
692 meet0->GetPhis().IsEmpty()) { // not used for merging
693 simplified_ = true;
694 succ0->DisconnectAndDelete();
695 if (block->Dominates(meet0)) {
696 block->RemoveDominatedBlock(meet0);
697 succ1->AddDominatedBlock(meet0);
698 meet0->SetDominator(succ1);
Aart Bike3dedc52016-11-02 17:50:27 -0700699 }
Aart Bik482095d2016-10-10 15:39:10 -0700700 }
Aart Bik281c6812016-08-26 11:31:48 -0700701 }
Aart Bikdf7822e2016-12-06 10:05:30 -0800702 }
Aart Bik281c6812016-08-26 11:31:48 -0700703}
704
Artem Serov121f2032017-10-23 19:19:06 +0100705bool HLoopOptimization::TryOptimizeInnerLoopFinite(LoopNode* node) {
Aart Bik281c6812016-08-26 11:31:48 -0700706 HBasicBlock* header = node->loop_info->GetHeader();
707 HBasicBlock* preheader = node->loop_info->GetPreHeader();
Aart Bik9abf8942016-10-14 09:49:42 -0700708 // Ensure loop header logic is finite.
Aart Bikf8f5a162017-02-06 15:35:29 -0800709 int64_t trip_count = 0;
710 if (!induction_range_.IsFinite(node->loop_info, &trip_count)) {
Aart Bikb29f6842017-07-28 15:58:41 -0700711 return false;
Aart Bik9abf8942016-10-14 09:49:42 -0700712 }
Aart Bik281c6812016-08-26 11:31:48 -0700713 // Ensure there is only a single loop-body (besides the header).
714 HBasicBlock* body = nullptr;
715 for (HBlocksInLoopIterator it(*node->loop_info); !it.Done(); it.Advance()) {
716 if (it.Current() != header) {
717 if (body != nullptr) {
Aart Bikb29f6842017-07-28 15:58:41 -0700718 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700719 }
720 body = it.Current();
721 }
722 }
Andreas Gampef45d61c2017-06-07 10:29:33 -0700723 CHECK(body != nullptr);
Aart Bik281c6812016-08-26 11:31:48 -0700724 // Ensure there is only a single exit point.
725 if (header->GetSuccessors().size() != 2) {
Aart Bikb29f6842017-07-28 15:58:41 -0700726 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700727 }
728 HBasicBlock* exit = (header->GetSuccessors()[0] == body)
729 ? header->GetSuccessors()[1]
730 : header->GetSuccessors()[0];
Aart Bik8c4a8542016-10-06 11:36:57 -0700731 // Ensure exit can only be reached by exiting loop.
Aart Bik281c6812016-08-26 11:31:48 -0700732 if (exit->GetPredecessors().size() != 1) {
Aart Bikb29f6842017-07-28 15:58:41 -0700733 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700734 }
Aart Bik6b69e0a2017-01-11 10:20:43 -0800735 // Detect either an empty loop (no side effects other than plain iteration) or
736 // a trivial loop (just iterating once). Replace subsequent index uses, if any,
737 // with the last value and remove the loop, possibly after unrolling its body.
Aart Bikb29f6842017-07-28 15:58:41 -0700738 HPhi* main_phi = nullptr;
739 if (TrySetSimpleLoopHeader(header, &main_phi)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -0800740 bool is_empty = IsEmptyBody(body);
Aart Bikb29f6842017-07-28 15:58:41 -0700741 if (reductions_->empty() && // TODO: possible with some effort
742 (is_empty || trip_count == 1) &&
743 TryAssignLastValue(node->loop_info, main_phi, preheader, /*collect_loop_uses*/ true)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -0800744 if (!is_empty) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800745 // Unroll the loop-body, which sees initial value of the index.
Aart Bikb29f6842017-07-28 15:58:41 -0700746 main_phi->ReplaceWith(main_phi->InputAt(0));
Aart Bik6b69e0a2017-01-11 10:20:43 -0800747 preheader->MergeInstructionsWith(body);
748 }
749 body->DisconnectAndDelete();
750 exit->RemovePredecessor(header);
751 header->RemoveSuccessor(exit);
752 header->RemoveDominatedBlock(exit);
753 header->DisconnectAndDelete();
754 preheader->AddSuccessor(exit);
Aart Bikf8f5a162017-02-06 15:35:29 -0800755 preheader->AddInstruction(new (global_allocator_) HGoto());
Aart Bik6b69e0a2017-01-11 10:20:43 -0800756 preheader->AddDominatedBlock(exit);
757 exit->SetDominator(preheader);
758 RemoveLoop(node); // update hierarchy
Aart Bikb29f6842017-07-28 15:58:41 -0700759 return true;
Aart Bikf8f5a162017-02-06 15:35:29 -0800760 }
761 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800762 // Vectorize loop, if possible and valid.
Aart Bikb29f6842017-07-28 15:58:41 -0700763 if (kEnableVectorization &&
Artem Serove65ade72019-07-25 21:04:16 +0100764 // Disable vectorization for debuggable graphs: this is a workaround for the bug
765 // in 'GenerateNewLoop' which caused the SuspendCheck environment to be invalid.
766 // TODO: b/138601207, investigate other possible cases with wrong environment values and
767 // possibly switch back vectorization on for debuggable graphs.
768 !graph_->IsDebuggable() &&
Aart Bikb29f6842017-07-28 15:58:41 -0700769 TrySetSimpleLoopHeader(header, &main_phi) &&
Aart Bikb29f6842017-07-28 15:58:41 -0700770 ShouldVectorize(node, body, trip_count) &&
771 TryAssignLastValue(node->loop_info, main_phi, preheader, /*collect_loop_uses*/ true)) {
772 Vectorize(node, body, exit, trip_count);
773 graph_->SetHasSIMD(true); // flag SIMD usage
Aart Bik21b85922017-09-06 13:29:16 -0700774 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorized);
Aart Bikb29f6842017-07-28 15:58:41 -0700775 return true;
Aart Bikf8f5a162017-02-06 15:35:29 -0800776 }
Aart Bikb29f6842017-07-28 15:58:41 -0700777 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -0800778}
779
Artem Serov121f2032017-10-23 19:19:06 +0100780bool HLoopOptimization::OptimizeInnerLoop(LoopNode* node) {
Artem Serov0e329082018-06-12 10:23:27 +0100781 return TryOptimizeInnerLoopFinite(node) || TryPeelingAndUnrolling(node);
Artem Serov121f2032017-10-23 19:19:06 +0100782}
783
Artem Serov121f2032017-10-23 19:19:06 +0100784
Artem Serov121f2032017-10-23 19:19:06 +0100785
786//
Artem Serov0e329082018-06-12 10:23:27 +0100787// Scalar loop peeling and unrolling: generic part methods.
Artem Serov121f2032017-10-23 19:19:06 +0100788//
789
Artem Serov0e329082018-06-12 10:23:27 +0100790bool HLoopOptimization::TryUnrollingForBranchPenaltyReduction(LoopAnalysisInfo* analysis_info,
791 bool generate_code) {
792 if (analysis_info->GetNumberOfExits() > 1) {
Artem Serov121f2032017-10-23 19:19:06 +0100793 return false;
794 }
795
Artem Serov0e329082018-06-12 10:23:27 +0100796 uint32_t unrolling_factor = arch_loop_helper_->GetScalarUnrollingFactor(analysis_info);
797 if (unrolling_factor == LoopAnalysisInfo::kNoUnrollingFactor) {
Artem Serov121f2032017-10-23 19:19:06 +0100798 return false;
799 }
800
Artem Serov0e329082018-06-12 10:23:27 +0100801 if (generate_code) {
802 // TODO: support other unrolling factors.
803 DCHECK_EQ(unrolling_factor, 2u);
804
805 // Perform unrolling.
806 HLoopInformation* loop_info = analysis_info->GetLoopInfo();
Nicolas Geoffray256c94b2019-04-29 10:55:09 +0100807 PeelUnrollSimpleHelper helper(loop_info, &induction_range_);
Artem Serov0e329082018-06-12 10:23:27 +0100808 helper.DoUnrolling();
809
810 // Remove the redundant loop check after unrolling.
811 HIf* copy_hif =
812 helper.GetBasicBlockMap()->Get(loop_info->GetHeader())->GetLastInstruction()->AsIf();
813 int32_t constant = loop_info->Contains(*copy_hif->IfTrueSuccessor()) ? 1 : 0;
814 copy_hif->ReplaceInput(graph_->GetIntConstant(constant), 0u);
Artem Serov121f2032017-10-23 19:19:06 +0100815 }
Artem Serov121f2032017-10-23 19:19:06 +0100816 return true;
817}
818
Artem Serov0e329082018-06-12 10:23:27 +0100819bool HLoopOptimization::TryPeelingForLoopInvariantExitsElimination(LoopAnalysisInfo* analysis_info,
820 bool generate_code) {
821 HLoopInformation* loop_info = analysis_info->GetLoopInfo();
Artem Serov72411e62017-10-19 16:18:07 +0100822 if (!arch_loop_helper_->IsLoopPeelingEnabled()) {
823 return false;
824 }
825
Artem Serov0e329082018-06-12 10:23:27 +0100826 if (analysis_info->GetNumberOfInvariantExits() == 0) {
Artem Serov72411e62017-10-19 16:18:07 +0100827 return false;
828 }
829
Artem Serov0e329082018-06-12 10:23:27 +0100830 if (generate_code) {
831 // Perform peeling.
Nicolas Geoffray256c94b2019-04-29 10:55:09 +0100832 PeelUnrollSimpleHelper helper(loop_info, &induction_range_);
Artem Serov0e329082018-06-12 10:23:27 +0100833 helper.DoPeeling();
Artem Serov72411e62017-10-19 16:18:07 +0100834
Artem Serov0e329082018-06-12 10:23:27 +0100835 // Statically evaluate loop check after peeling for loop invariant condition.
836 const SuperblockCloner::HInstructionMap* hir_map = helper.GetInstructionMap();
837 for (auto entry : *hir_map) {
838 HInstruction* copy = entry.second;
839 if (copy->IsIf()) {
840 TryToEvaluateIfCondition(copy->AsIf(), graph_);
841 }
Artem Serov72411e62017-10-19 16:18:07 +0100842 }
843 }
844
845 return true;
846}
847
Artem Serov18ba1da2018-05-16 19:06:32 +0100848bool HLoopOptimization::TryFullUnrolling(LoopAnalysisInfo* analysis_info, bool generate_code) {
849 // Fully unroll loops with a known and small trip count.
850 int64_t trip_count = analysis_info->GetTripCount();
851 if (!arch_loop_helper_->IsLoopPeelingEnabled() ||
852 trip_count == LoopAnalysisInfo::kUnknownTripCount ||
853 !arch_loop_helper_->IsFullUnrollingBeneficial(analysis_info)) {
854 return false;
855 }
856
857 if (generate_code) {
858 // Peeling of the N first iterations (where N equals to the trip count) will effectively
859 // eliminate the loop: after peeling we will have N sequential iterations copied into the loop
860 // preheader and the original loop. The trip count of this loop will be 0 as the sequential
861 // iterations are executed first and there are exactly N of them. Thus we can statically
862 // evaluate the loop exit condition to 'false' and fully eliminate it.
863 //
864 // Here is an example of full unrolling of a loop with a trip count 2:
865 //
866 // loop_cond_1
867 // loop_body_1 <- First iteration.
868 // |
869 // \ v
870 // ==\ loop_cond_2
871 // ==/ loop_body_2 <- Second iteration.
872 // / |
873 // <- v <-
874 // loop_cond \ loop_cond \ <- This cond is always false.
875 // loop_body _/ loop_body _/
876 //
877 HLoopInformation* loop_info = analysis_info->GetLoopInfo();
Nicolas Geoffray256c94b2019-04-29 10:55:09 +0100878 PeelByCount(loop_info, trip_count, &induction_range_);
Artem Serov18ba1da2018-05-16 19:06:32 +0100879 HIf* loop_hif = loop_info->GetHeader()->GetLastInstruction()->AsIf();
880 int32_t constant = loop_info->Contains(*loop_hif->IfTrueSuccessor()) ? 0 : 1;
881 loop_hif->ReplaceInput(graph_->GetIntConstant(constant), 0u);
882 }
883
884 return true;
885}
886
Artem Serov0e329082018-06-12 10:23:27 +0100887bool HLoopOptimization::TryPeelingAndUnrolling(LoopNode* node) {
888 // Don't run peeling/unrolling if compiler_options_ is nullptr (i.e., running under tests)
889 // as InstructionSet is needed.
890 if (compiler_options_ == nullptr) {
891 return false;
892 }
893
894 HLoopInformation* loop_info = node->loop_info;
895 int64_t trip_count = LoopAnalysis::GetLoopTripCount(loop_info, &induction_range_);
896 LoopAnalysisInfo analysis_info(loop_info);
897 LoopAnalysis::CalculateLoopBasicProperties(loop_info, &analysis_info, trip_count);
898
899 if (analysis_info.HasInstructionsPreventingScalarOpts() ||
900 arch_loop_helper_->IsLoopNonBeneficialForScalarOpts(&analysis_info)) {
901 return false;
902 }
903
Artem Serov18ba1da2018-05-16 19:06:32 +0100904 if (!TryFullUnrolling(&analysis_info, /*generate_code*/ false) &&
905 !TryPeelingForLoopInvariantExitsElimination(&analysis_info, /*generate_code*/ false) &&
Artem Serov0e329082018-06-12 10:23:27 +0100906 !TryUnrollingForBranchPenaltyReduction(&analysis_info, /*generate_code*/ false)) {
907 return false;
908 }
909
910 // Run 'IsLoopClonable' the last as it might be time-consuming.
911 if (!PeelUnrollHelper::IsLoopClonable(loop_info)) {
912 return false;
913 }
914
Artem Serov18ba1da2018-05-16 19:06:32 +0100915 return TryFullUnrolling(&analysis_info) ||
916 TryPeelingForLoopInvariantExitsElimination(&analysis_info) ||
Artem Serov0e329082018-06-12 10:23:27 +0100917 TryUnrollingForBranchPenaltyReduction(&analysis_info);
918}
919
Aart Bikf8f5a162017-02-06 15:35:29 -0800920//
921// Loop vectorization. The implementation is based on the book by Aart J.C. Bik:
922// "The Software Vectorization Handbook. Applying Multimedia Extensions for Maximum Performance."
923// Intel Press, June, 2004 (http://www.aartbik.com/).
924//
925
Aart Bik14a68b42017-06-08 14:06:58 -0700926bool HLoopOptimization::ShouldVectorize(LoopNode* node, HBasicBlock* block, int64_t trip_count) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800927 // Reset vector bookkeeping.
928 vector_length_ = 0;
929 vector_refs_->clear();
Aart Bik38a3f212017-10-20 17:02:21 -0700930 vector_static_peeling_factor_ = 0;
931 vector_dynamic_peeling_candidate_ = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800932 vector_runtime_test_a_ =
Igor Murashkin2ffb7032017-11-08 13:35:21 -0800933 vector_runtime_test_b_ = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800934
935 // Phis in the loop-body prevent vectorization.
936 if (!block->GetPhis().IsEmpty()) {
937 return false;
938 }
939
940 // Scan the loop-body, starting a right-hand-side tree traversal at each left-hand-side
941 // occurrence, which allows passing down attributes down the use tree.
942 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
943 if (!VectorizeDef(node, it.Current(), /*generate_code*/ false)) {
944 return false; // failure to vectorize a left-hand-side
945 }
946 }
947
Aart Bik38a3f212017-10-20 17:02:21 -0700948 // Prepare alignment analysis:
949 // (1) find desired alignment (SIMD vector size in bytes).
950 // (2) initialize static loop peeling votes (peeling factor that will
951 // make one particular reference aligned), never to exceed (1).
952 // (3) variable to record how many references share same alignment.
953 // (4) variable to record suitable candidate for dynamic loop peeling.
954 uint32_t desired_alignment = GetVectorSizeInBytes();
955 DCHECK_LE(desired_alignment, 16u);
956 uint32_t peeling_votes[16] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
957 uint32_t max_num_same_alignment = 0;
958 const ArrayReference* peeling_candidate = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800959
960 // Data dependence analysis. Find each pair of references with same type, where
961 // at least one is a write. Each such pair denotes a possible data dependence.
962 // This analysis exploits the property that differently typed arrays cannot be
963 // aliased, as well as the property that references either point to the same
964 // array or to two completely disjoint arrays, i.e., no partial aliasing.
965 // Other than a few simply heuristics, no detailed subscript analysis is done.
Aart Bik38a3f212017-10-20 17:02:21 -0700966 // The scan over references also prepares finding a suitable alignment strategy.
Aart Bikf8f5a162017-02-06 15:35:29 -0800967 for (auto i = vector_refs_->begin(); i != vector_refs_->end(); ++i) {
Aart Bik38a3f212017-10-20 17:02:21 -0700968 uint32_t num_same_alignment = 0;
969 // Scan over all next references.
Aart Bikf8f5a162017-02-06 15:35:29 -0800970 for (auto j = i; ++j != vector_refs_->end(); ) {
971 if (i->type == j->type && (i->lhs || j->lhs)) {
972 // Found same-typed a[i+x] vs. b[i+y], where at least one is a write.
973 HInstruction* a = i->base;
974 HInstruction* b = j->base;
975 HInstruction* x = i->offset;
976 HInstruction* y = j->offset;
977 if (a == b) {
978 // Found a[i+x] vs. a[i+y]. Accept if x == y (loop-independent data dependence).
979 // Conservatively assume a loop-carried data dependence otherwise, and reject.
980 if (x != y) {
981 return false;
982 }
Aart Bik38a3f212017-10-20 17:02:21 -0700983 // Count the number of references that have the same alignment (since
984 // base and offset are the same) and where at least one is a write, so
985 // e.g. a[i] = a[i] + b[i] counts a[i] but not b[i]).
986 num_same_alignment++;
Aart Bikf8f5a162017-02-06 15:35:29 -0800987 } else {
988 // Found a[i+x] vs. b[i+y]. Accept if x == y (at worst loop-independent data dependence).
989 // Conservatively assume a potential loop-carried data dependence otherwise, avoided by
990 // generating an explicit a != b disambiguation runtime test on the two references.
991 if (x != y) {
Aart Bik37dc4df2017-06-28 14:08:00 -0700992 // To avoid excessive overhead, we only accept one a != b test.
993 if (vector_runtime_test_a_ == nullptr) {
994 // First test found.
995 vector_runtime_test_a_ = a;
996 vector_runtime_test_b_ = b;
997 } else if ((vector_runtime_test_a_ != a || vector_runtime_test_b_ != b) &&
998 (vector_runtime_test_a_ != b || vector_runtime_test_b_ != a)) {
999 return false; // second test would be needed
Aart Bikf8f5a162017-02-06 15:35:29 -08001000 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001001 }
1002 }
1003 }
1004 }
Aart Bik38a3f212017-10-20 17:02:21 -07001005 // Update information for finding suitable alignment strategy:
1006 // (1) update votes for static loop peeling,
1007 // (2) update suitable candidate for dynamic loop peeling.
1008 Alignment alignment = ComputeAlignment(i->offset, i->type, i->is_string_char_at);
1009 if (alignment.Base() >= desired_alignment) {
1010 // If the array/string object has a known, sufficient alignment, use the
1011 // initial offset to compute the static loop peeling vote (this always
1012 // works, since elements have natural alignment).
1013 uint32_t offset = alignment.Offset() & (desired_alignment - 1u);
1014 uint32_t vote = (offset == 0)
1015 ? 0
1016 : ((desired_alignment - offset) >> DataType::SizeShift(i->type));
1017 DCHECK_LT(vote, 16u);
1018 ++peeling_votes[vote];
1019 } else if (BaseAlignment() >= desired_alignment &&
1020 num_same_alignment > max_num_same_alignment) {
1021 // Otherwise, if the array/string object has a known, sufficient alignment
1022 // for just the base but with an unknown offset, record the candidate with
1023 // the most occurrences for dynamic loop peeling (again, the peeling always
1024 // works, since elements have natural alignment).
1025 max_num_same_alignment = num_same_alignment;
1026 peeling_candidate = &(*i);
1027 }
1028 } // for i
Aart Bikf8f5a162017-02-06 15:35:29 -08001029
Aart Bik38a3f212017-10-20 17:02:21 -07001030 // Find a suitable alignment strategy.
1031 SetAlignmentStrategy(peeling_votes, peeling_candidate);
1032
1033 // Does vectorization seem profitable?
1034 if (!IsVectorizationProfitable(trip_count)) {
1035 return false;
1036 }
Aart Bik14a68b42017-06-08 14:06:58 -07001037
Aart Bikf8f5a162017-02-06 15:35:29 -08001038 // Success!
1039 return true;
1040}
1041
1042void HLoopOptimization::Vectorize(LoopNode* node,
1043 HBasicBlock* block,
1044 HBasicBlock* exit,
1045 int64_t trip_count) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001046 HBasicBlock* header = node->loop_info->GetHeader();
1047 HBasicBlock* preheader = node->loop_info->GetPreHeader();
1048
Aart Bik14a68b42017-06-08 14:06:58 -07001049 // Pick a loop unrolling factor for the vector loop.
Artem Serov121f2032017-10-23 19:19:06 +01001050 uint32_t unroll = arch_loop_helper_->GetSIMDUnrollingFactor(
1051 block, trip_count, MaxNumberPeeled(), vector_length_);
Aart Bik14a68b42017-06-08 14:06:58 -07001052 uint32_t chunk = vector_length_ * unroll;
1053
Aart Bik38a3f212017-10-20 17:02:21 -07001054 DCHECK(trip_count == 0 || (trip_count >= MaxNumberPeeled() + chunk));
1055
Aart Bik14a68b42017-06-08 14:06:58 -07001056 // A cleanup loop is needed, at least, for any unknown trip count or
1057 // for a known trip count with remainder iterations after vectorization.
Aart Bik38a3f212017-10-20 17:02:21 -07001058 bool needs_cleanup = trip_count == 0 ||
1059 ((trip_count - vector_static_peeling_factor_) % chunk) != 0;
Aart Bikf8f5a162017-02-06 15:35:29 -08001060
1061 // Adjust vector bookkeeping.
Aart Bikb29f6842017-07-28 15:58:41 -07001062 HPhi* main_phi = nullptr;
1063 bool is_simple_loop_header = TrySetSimpleLoopHeader(header, &main_phi); // refills sets
Aart Bikf8f5a162017-02-06 15:35:29 -08001064 DCHECK(is_simple_loop_header);
Aart Bik14a68b42017-06-08 14:06:58 -07001065 vector_header_ = header;
1066 vector_body_ = block;
Aart Bikf8f5a162017-02-06 15:35:29 -08001067
Aart Bikdbbac8f2017-09-01 13:06:08 -07001068 // Loop induction type.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001069 DataType::Type induc_type = main_phi->GetType();
1070 DCHECK(induc_type == DataType::Type::kInt32 || induc_type == DataType::Type::kInt64)
1071 << induc_type;
Aart Bikdbbac8f2017-09-01 13:06:08 -07001072
Aart Bik38a3f212017-10-20 17:02:21 -07001073 // Generate the trip count for static or dynamic loop peeling, if needed:
1074 // ptc = <peeling factor>;
Aart Bik14a68b42017-06-08 14:06:58 -07001075 HInstruction* ptc = nullptr;
Aart Bik38a3f212017-10-20 17:02:21 -07001076 if (vector_static_peeling_factor_ != 0) {
1077 // Static loop peeling for SIMD alignment (using the most suitable
1078 // fixed peeling factor found during prior alignment analysis).
1079 DCHECK(vector_dynamic_peeling_candidate_ == nullptr);
1080 ptc = graph_->GetConstant(induc_type, vector_static_peeling_factor_);
1081 } else if (vector_dynamic_peeling_candidate_ != nullptr) {
1082 // Dynamic loop peeling for SIMD alignment (using the most suitable
1083 // candidate found during prior alignment analysis):
1084 // rem = offset % ALIGN; // adjusted as #elements
1085 // ptc = rem == 0 ? 0 : (ALIGN - rem);
1086 uint32_t shift = DataType::SizeShift(vector_dynamic_peeling_candidate_->type);
1087 uint32_t align = GetVectorSizeInBytes() >> shift;
1088 uint32_t hidden_offset = HiddenOffset(vector_dynamic_peeling_candidate_->type,
1089 vector_dynamic_peeling_candidate_->is_string_char_at);
1090 HInstruction* adjusted_offset = graph_->GetConstant(induc_type, hidden_offset >> shift);
1091 HInstruction* offset = Insert(preheader, new (global_allocator_) HAdd(
1092 induc_type, vector_dynamic_peeling_candidate_->offset, adjusted_offset));
1093 HInstruction* rem = Insert(preheader, new (global_allocator_) HAnd(
1094 induc_type, offset, graph_->GetConstant(induc_type, align - 1u)));
1095 HInstruction* sub = Insert(preheader, new (global_allocator_) HSub(
1096 induc_type, graph_->GetConstant(induc_type, align), rem));
1097 HInstruction* cond = Insert(preheader, new (global_allocator_) HEqual(
1098 rem, graph_->GetConstant(induc_type, 0)));
1099 ptc = Insert(preheader, new (global_allocator_) HSelect(
1100 cond, graph_->GetConstant(induc_type, 0), sub, kNoDexPc));
1101 needs_cleanup = true; // don't know the exact amount
Aart Bik14a68b42017-06-08 14:06:58 -07001102 }
1103
1104 // Generate loop control:
Aart Bikf8f5a162017-02-06 15:35:29 -08001105 // stc = <trip-count>;
Aart Bik38a3f212017-10-20 17:02:21 -07001106 // ptc = min(stc, ptc);
Aart Bik14a68b42017-06-08 14:06:58 -07001107 // vtc = stc - (stc - ptc) % chunk;
1108 // i = 0;
Aart Bikf8f5a162017-02-06 15:35:29 -08001109 HInstruction* stc = induction_range_.GenerateTripCount(node->loop_info, graph_, preheader);
1110 HInstruction* vtc = stc;
1111 if (needs_cleanup) {
Aart Bik14a68b42017-06-08 14:06:58 -07001112 DCHECK(IsPowerOfTwo(chunk));
1113 HInstruction* diff = stc;
1114 if (ptc != nullptr) {
Aart Bik38a3f212017-10-20 17:02:21 -07001115 if (trip_count == 0) {
1116 HInstruction* cond = Insert(preheader, new (global_allocator_) HAboveOrEqual(stc, ptc));
1117 ptc = Insert(preheader, new (global_allocator_) HSelect(cond, ptc, stc, kNoDexPc));
1118 }
Aart Bik14a68b42017-06-08 14:06:58 -07001119 diff = Insert(preheader, new (global_allocator_) HSub(induc_type, stc, ptc));
1120 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001121 HInstruction* rem = Insert(
1122 preheader, new (global_allocator_) HAnd(induc_type,
Aart Bik14a68b42017-06-08 14:06:58 -07001123 diff,
Aart Bikdbbac8f2017-09-01 13:06:08 -07001124 graph_->GetConstant(induc_type, chunk - 1)));
Aart Bikf8f5a162017-02-06 15:35:29 -08001125 vtc = Insert(preheader, new (global_allocator_) HSub(induc_type, stc, rem));
1126 }
Aart Bikdbbac8f2017-09-01 13:06:08 -07001127 vector_index_ = graph_->GetConstant(induc_type, 0);
Aart Bikf8f5a162017-02-06 15:35:29 -08001128
1129 // Generate runtime disambiguation test:
1130 // vtc = a != b ? vtc : 0;
1131 if (vector_runtime_test_a_ != nullptr) {
1132 HInstruction* rt = Insert(
1133 preheader,
1134 new (global_allocator_) HNotEqual(vector_runtime_test_a_, vector_runtime_test_b_));
1135 vtc = Insert(preheader,
Aart Bikdbbac8f2017-09-01 13:06:08 -07001136 new (global_allocator_)
1137 HSelect(rt, vtc, graph_->GetConstant(induc_type, 0), kNoDexPc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001138 needs_cleanup = true;
1139 }
1140
Aart Bik38a3f212017-10-20 17:02:21 -07001141 // Generate alignment peeling loop, if needed:
Aart Bik14a68b42017-06-08 14:06:58 -07001142 // for ( ; i < ptc; i += 1)
1143 // <loop-body>
Aart Bik38a3f212017-10-20 17:02:21 -07001144 //
1145 // NOTE: The alignment forced by the peeling loop is preserved even if data is
1146 // moved around during suspend checks, since all analysis was based on
1147 // nothing more than the Android runtime alignment conventions.
Aart Bik14a68b42017-06-08 14:06:58 -07001148 if (ptc != nullptr) {
1149 vector_mode_ = kSequential;
1150 GenerateNewLoop(node,
1151 block,
1152 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
1153 vector_index_,
1154 ptc,
Aart Bikdbbac8f2017-09-01 13:06:08 -07001155 graph_->GetConstant(induc_type, 1),
Artem Serov0e329082018-06-12 10:23:27 +01001156 LoopAnalysisInfo::kNoUnrollingFactor);
Aart Bik14a68b42017-06-08 14:06:58 -07001157 }
1158
1159 // Generate vector loop, possibly further unrolled:
1160 // for ( ; i < vtc; i += chunk)
Aart Bikf8f5a162017-02-06 15:35:29 -08001161 // <vectorized-loop-body>
1162 vector_mode_ = kVector;
1163 GenerateNewLoop(node,
1164 block,
Aart Bik14a68b42017-06-08 14:06:58 -07001165 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
1166 vector_index_,
Aart Bikf8f5a162017-02-06 15:35:29 -08001167 vtc,
Aart Bikdbbac8f2017-09-01 13:06:08 -07001168 graph_->GetConstant(induc_type, vector_length_), // increment per unroll
Aart Bik14a68b42017-06-08 14:06:58 -07001169 unroll);
Aart Bikf8f5a162017-02-06 15:35:29 -08001170 HLoopInformation* vloop = vector_header_->GetLoopInformation();
1171
1172 // Generate cleanup loop, if needed:
1173 // for ( ; i < stc; i += 1)
1174 // <loop-body>
1175 if (needs_cleanup) {
1176 vector_mode_ = kSequential;
1177 GenerateNewLoop(node,
1178 block,
1179 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
Aart Bik14a68b42017-06-08 14:06:58 -07001180 vector_index_,
Aart Bikf8f5a162017-02-06 15:35:29 -08001181 stc,
Aart Bikdbbac8f2017-09-01 13:06:08 -07001182 graph_->GetConstant(induc_type, 1),
Artem Serov0e329082018-06-12 10:23:27 +01001183 LoopAnalysisInfo::kNoUnrollingFactor);
Aart Bikf8f5a162017-02-06 15:35:29 -08001184 }
1185
Aart Bik0148de42017-09-05 09:25:01 -07001186 // Link reductions to their final uses.
1187 for (auto i = reductions_->begin(); i != reductions_->end(); ++i) {
1188 if (i->first->IsPhi()) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001189 HInstruction* phi = i->first;
1190 HInstruction* repl = ReduceAndExtractIfNeeded(i->second);
1191 // Deal with regular uses.
1192 for (const HUseListNode<HInstruction*>& use : phi->GetUses()) {
1193 induction_range_.Replace(use.GetUser(), phi, repl); // update induction use
1194 }
1195 phi->ReplaceWith(repl);
Aart Bik0148de42017-09-05 09:25:01 -07001196 }
1197 }
1198
Aart Bikf8f5a162017-02-06 15:35:29 -08001199 // Remove the original loop by disconnecting the body block
1200 // and removing all instructions from the header.
1201 block->DisconnectAndDelete();
1202 while (!header->GetFirstInstruction()->IsGoto()) {
1203 header->RemoveInstruction(header->GetFirstInstruction());
1204 }
Aart Bikb29f6842017-07-28 15:58:41 -07001205
Aart Bik14a68b42017-06-08 14:06:58 -07001206 // Update loop hierarchy: the old header now resides in the same outer loop
1207 // as the old preheader. Note that we don't bother putting sequential
1208 // loops back in the hierarchy at this point.
Aart Bikf8f5a162017-02-06 15:35:29 -08001209 header->SetLoopInformation(preheader->GetLoopInformation()); // outward
1210 node->loop_info = vloop;
1211}
1212
1213void HLoopOptimization::GenerateNewLoop(LoopNode* node,
1214 HBasicBlock* block,
1215 HBasicBlock* new_preheader,
1216 HInstruction* lo,
1217 HInstruction* hi,
Aart Bik14a68b42017-06-08 14:06:58 -07001218 HInstruction* step,
1219 uint32_t unroll) {
1220 DCHECK(unroll == 1 || vector_mode_ == kVector);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001221 DataType::Type induc_type = lo->GetType();
Aart Bikf8f5a162017-02-06 15:35:29 -08001222 // Prepare new loop.
Aart Bikf8f5a162017-02-06 15:35:29 -08001223 vector_preheader_ = new_preheader,
1224 vector_header_ = vector_preheader_->GetSingleSuccessor();
1225 vector_body_ = vector_header_->GetSuccessors()[1];
Aart Bik14a68b42017-06-08 14:06:58 -07001226 HPhi* phi = new (global_allocator_) HPhi(global_allocator_,
1227 kNoRegNumber,
1228 0,
1229 HPhi::ToPhiType(induc_type));
Aart Bikb07d1bc2017-04-05 10:03:15 -07001230 // Generate header and prepare body.
Aart Bikf8f5a162017-02-06 15:35:29 -08001231 // for (i = lo; i < hi; i += step)
1232 // <loop-body>
Aart Bik14a68b42017-06-08 14:06:58 -07001233 HInstruction* cond = new (global_allocator_) HAboveOrEqual(phi, hi);
1234 vector_header_->AddPhi(phi);
Aart Bikf8f5a162017-02-06 15:35:29 -08001235 vector_header_->AddInstruction(cond);
1236 vector_header_->AddInstruction(new (global_allocator_) HIf(cond));
Aart Bik14a68b42017-06-08 14:06:58 -07001237 vector_index_ = phi;
Aart Bik0148de42017-09-05 09:25:01 -07001238 vector_permanent_map_->clear(); // preserved over unrolling
Aart Bik14a68b42017-06-08 14:06:58 -07001239 for (uint32_t u = 0; u < unroll; u++) {
Aart Bik14a68b42017-06-08 14:06:58 -07001240 // Generate instruction map.
Aart Bik0148de42017-09-05 09:25:01 -07001241 vector_map_->clear();
Aart Bik14a68b42017-06-08 14:06:58 -07001242 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
1243 bool vectorized_def = VectorizeDef(node, it.Current(), /*generate_code*/ true);
1244 DCHECK(vectorized_def);
1245 }
1246 // Generate body from the instruction map, but in original program order.
1247 HEnvironment* env = vector_header_->GetFirstInstruction()->GetEnvironment();
1248 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
1249 auto i = vector_map_->find(it.Current());
1250 if (i != vector_map_->end() && !i->second->IsInBlock()) {
1251 Insert(vector_body_, i->second);
1252 // Deal with instructions that need an environment, such as the scalar intrinsics.
1253 if (i->second->NeedsEnvironment()) {
1254 i->second->CopyEnvironmentFromWithLoopPhiAdjustment(env, vector_header_);
1255 }
1256 }
1257 }
Aart Bik0148de42017-09-05 09:25:01 -07001258 // Generate the induction.
Aart Bik14a68b42017-06-08 14:06:58 -07001259 vector_index_ = new (global_allocator_) HAdd(induc_type, vector_index_, step);
1260 Insert(vector_body_, vector_index_);
Aart Bikf8f5a162017-02-06 15:35:29 -08001261 }
Aart Bik0148de42017-09-05 09:25:01 -07001262 // Finalize phi inputs for the reductions (if any).
1263 for (auto i = reductions_->begin(); i != reductions_->end(); ++i) {
1264 if (!i->first->IsPhi()) {
1265 DCHECK(i->second->IsPhi());
1266 GenerateVecReductionPhiInputs(i->second->AsPhi(), i->first);
1267 }
1268 }
Aart Bikb29f6842017-07-28 15:58:41 -07001269 // Finalize phi inputs for the loop index.
Aart Bik14a68b42017-06-08 14:06:58 -07001270 phi->AddInput(lo);
1271 phi->AddInput(vector_index_);
1272 vector_index_ = phi;
Aart Bikf8f5a162017-02-06 15:35:29 -08001273}
1274
Aart Bikf8f5a162017-02-06 15:35:29 -08001275bool HLoopOptimization::VectorizeDef(LoopNode* node,
1276 HInstruction* instruction,
1277 bool generate_code) {
1278 // Accept a left-hand-side array base[index] for
1279 // (1) supported vector type,
1280 // (2) loop-invariant base,
1281 // (3) unit stride index,
1282 // (4) vectorizable right-hand-side value.
1283 uint64_t restrictions = kNone;
Georgia Kouvelibac080b2019-01-31 16:12:16 +00001284 // Don't accept expressions that can throw.
1285 if (instruction->CanThrow()) {
1286 return false;
1287 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001288 if (instruction->IsArraySet()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001289 DataType::Type type = instruction->AsArraySet()->GetComponentType();
Aart Bikf8f5a162017-02-06 15:35:29 -08001290 HInstruction* base = instruction->InputAt(0);
1291 HInstruction* index = instruction->InputAt(1);
1292 HInstruction* value = instruction->InputAt(2);
1293 HInstruction* offset = nullptr;
Aart Bik6d057002018-04-09 15:39:58 -07001294 // For narrow types, explicit type conversion may have been
1295 // optimized way, so set the no hi bits restriction here.
1296 if (DataType::Size(type) <= 2) {
1297 restrictions |= kNoHiBits;
1298 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001299 if (TrySetVectorType(type, &restrictions) &&
1300 node->loop_info->IsDefinedOutOfTheLoop(base) &&
Aart Bik37dc4df2017-06-28 14:08:00 -07001301 induction_range_.IsUnitStride(instruction, index, graph_, &offset) &&
Aart Bikf8f5a162017-02-06 15:35:29 -08001302 VectorizeUse(node, value, generate_code, type, restrictions)) {
1303 if (generate_code) {
1304 GenerateVecSub(index, offset);
Aart Bik14a68b42017-06-08 14:06:58 -07001305 GenerateVecMem(instruction, vector_map_->Get(index), vector_map_->Get(value), offset, type);
Aart Bikf8f5a162017-02-06 15:35:29 -08001306 } else {
1307 vector_refs_->insert(ArrayReference(base, offset, type, /*lhs*/ true));
1308 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08001309 return true;
1310 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001311 return false;
1312 }
Aart Bik0148de42017-09-05 09:25:01 -07001313 // Accept a left-hand-side reduction for
1314 // (1) supported vector type,
1315 // (2) vectorizable right-hand-side value.
1316 auto redit = reductions_->find(instruction);
1317 if (redit != reductions_->end()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001318 DataType::Type type = instruction->GetType();
Aart Bikdbbac8f2017-09-01 13:06:08 -07001319 // Recognize SAD idiom or direct reduction.
1320 if (VectorizeSADIdiom(node, instruction, generate_code, type, restrictions) ||
Artem Serovaaac0e32018-08-07 00:52:22 +01001321 VectorizeDotProdIdiom(node, instruction, generate_code, type, restrictions) ||
Aart Bikdbbac8f2017-09-01 13:06:08 -07001322 (TrySetVectorType(type, &restrictions) &&
1323 VectorizeUse(node, instruction, generate_code, type, restrictions))) {
Aart Bik0148de42017-09-05 09:25:01 -07001324 if (generate_code) {
1325 HInstruction* new_red = vector_map_->Get(instruction);
1326 vector_permanent_map_->Put(new_red, vector_map_->Get(redit->second));
1327 vector_permanent_map_->Overwrite(redit->second, new_red);
1328 }
1329 return true;
1330 }
1331 return false;
1332 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001333 // Branch back okay.
1334 if (instruction->IsGoto()) {
1335 return true;
1336 }
1337 // Otherwise accept only expressions with no effects outside the immediate loop-body.
1338 // Note that actual uses are inspected during right-hand-side tree traversal.
Georgia Kouvelibac080b2019-01-31 16:12:16 +00001339 return !IsUsedOutsideLoop(node->loop_info, instruction)
1340 && !instruction->DoesAnyWrite();
Aart Bikf8f5a162017-02-06 15:35:29 -08001341}
1342
Aart Bikf8f5a162017-02-06 15:35:29 -08001343bool HLoopOptimization::VectorizeUse(LoopNode* node,
1344 HInstruction* instruction,
1345 bool generate_code,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001346 DataType::Type type,
Aart Bikf8f5a162017-02-06 15:35:29 -08001347 uint64_t restrictions) {
1348 // Accept anything for which code has already been generated.
1349 if (generate_code) {
1350 if (vector_map_->find(instruction) != vector_map_->end()) {
1351 return true;
1352 }
1353 }
1354 // Continue the right-hand-side tree traversal, passing in proper
1355 // types and vector restrictions along the way. During code generation,
1356 // all new nodes are drawn from the global allocator.
1357 if (node->loop_info->IsDefinedOutOfTheLoop(instruction)) {
1358 // Accept invariant use, using scalar expansion.
1359 if (generate_code) {
1360 GenerateVecInv(instruction, type);
1361 }
1362 return true;
1363 } else if (instruction->IsArrayGet()) {
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001364 // Deal with vector restrictions.
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001365 bool is_string_char_at = instruction->AsArrayGet()->IsStringCharAt();
1366 if (is_string_char_at && HasVectorRestrictions(restrictions, kNoStringCharAt)) {
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001367 return false;
1368 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001369 // Accept a right-hand-side array base[index] for
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001370 // (1) matching vector type (exact match or signed/unsigned integral type of the same size),
Aart Bikf8f5a162017-02-06 15:35:29 -08001371 // (2) loop-invariant base,
1372 // (3) unit stride index,
1373 // (4) vectorizable right-hand-side value.
1374 HInstruction* base = instruction->InputAt(0);
1375 HInstruction* index = instruction->InputAt(1);
1376 HInstruction* offset = nullptr;
Aart Bik46b6dbc2017-10-03 11:37:37 -07001377 if (HVecOperation::ToSignedType(type) == HVecOperation::ToSignedType(instruction->GetType()) &&
Aart Bikf8f5a162017-02-06 15:35:29 -08001378 node->loop_info->IsDefinedOutOfTheLoop(base) &&
Aart Bik37dc4df2017-06-28 14:08:00 -07001379 induction_range_.IsUnitStride(instruction, index, graph_, &offset)) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001380 if (generate_code) {
1381 GenerateVecSub(index, offset);
Aart Bik14a68b42017-06-08 14:06:58 -07001382 GenerateVecMem(instruction, vector_map_->Get(index), nullptr, offset, type);
Aart Bikf8f5a162017-02-06 15:35:29 -08001383 } else {
Aart Bik38a3f212017-10-20 17:02:21 -07001384 vector_refs_->insert(ArrayReference(base, offset, type, /*lhs*/ false, is_string_char_at));
Aart Bikf8f5a162017-02-06 15:35:29 -08001385 }
1386 return true;
1387 }
Aart Bik0148de42017-09-05 09:25:01 -07001388 } else if (instruction->IsPhi()) {
1389 // Accept particular phi operations.
1390 if (reductions_->find(instruction) != reductions_->end()) {
1391 // Deal with vector restrictions.
1392 if (HasVectorRestrictions(restrictions, kNoReduction)) {
1393 return false;
1394 }
1395 // Accept a reduction.
1396 if (generate_code) {
1397 GenerateVecReductionPhi(instruction->AsPhi());
1398 }
1399 return true;
1400 }
1401 // TODO: accept right-hand-side induction?
1402 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001403 } else if (instruction->IsTypeConversion()) {
1404 // Accept particular type conversions.
1405 HTypeConversion* conversion = instruction->AsTypeConversion();
1406 HInstruction* opa = conversion->InputAt(0);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001407 DataType::Type from = conversion->GetInputType();
1408 DataType::Type to = conversion->GetResultType();
1409 if (DataType::IsIntegralType(from) && DataType::IsIntegralType(to)) {
Aart Bik38a3f212017-10-20 17:02:21 -07001410 uint32_t size_vec = DataType::Size(type);
1411 uint32_t size_from = DataType::Size(from);
1412 uint32_t size_to = DataType::Size(to);
Aart Bikdbbac8f2017-09-01 13:06:08 -07001413 // Accept an integral conversion
1414 // (1a) narrowing into vector type, "wider" operations cannot bring in higher order bits, or
1415 // (1b) widening from at least vector type, and
1416 // (2) vectorizable operand.
1417 if ((size_to < size_from &&
1418 size_to == size_vec &&
1419 VectorizeUse(node, opa, generate_code, type, restrictions | kNoHiBits)) ||
1420 (size_to >= size_from &&
1421 size_from >= size_vec &&
Aart Bik4d1a9d42017-10-19 14:40:55 -07001422 VectorizeUse(node, opa, generate_code, type, restrictions))) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001423 if (generate_code) {
1424 if (vector_mode_ == kVector) {
1425 vector_map_->Put(instruction, vector_map_->Get(opa)); // operand pass-through
1426 } else {
1427 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1428 }
1429 }
1430 return true;
1431 }
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001432 } else if (to == DataType::Type::kFloat32 && from == DataType::Type::kInt32) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001433 DCHECK_EQ(to, type);
1434 // Accept int to float conversion for
1435 // (1) supported int,
1436 // (2) vectorizable operand.
1437 if (TrySetVectorType(from, &restrictions) &&
1438 VectorizeUse(node, opa, generate_code, from, restrictions)) {
1439 if (generate_code) {
1440 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1441 }
1442 return true;
1443 }
1444 }
1445 return false;
1446 } else if (instruction->IsNeg() || instruction->IsNot() || instruction->IsBooleanNot()) {
1447 // Accept unary operator for vectorizable operand.
1448 HInstruction* opa = instruction->InputAt(0);
1449 if (VectorizeUse(node, opa, generate_code, type, restrictions)) {
1450 if (generate_code) {
1451 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1452 }
1453 return true;
1454 }
1455 } else if (instruction->IsAdd() || instruction->IsSub() ||
1456 instruction->IsMul() || instruction->IsDiv() ||
1457 instruction->IsAnd() || instruction->IsOr() || instruction->IsXor()) {
1458 // Deal with vector restrictions.
1459 if ((instruction->IsMul() && HasVectorRestrictions(restrictions, kNoMul)) ||
1460 (instruction->IsDiv() && HasVectorRestrictions(restrictions, kNoDiv))) {
1461 return false;
1462 }
1463 // Accept binary operator for vectorizable operands.
1464 HInstruction* opa = instruction->InputAt(0);
1465 HInstruction* opb = instruction->InputAt(1);
1466 if (VectorizeUse(node, opa, generate_code, type, restrictions) &&
1467 VectorizeUse(node, opb, generate_code, type, restrictions)) {
1468 if (generate_code) {
1469 GenerateVecOp(instruction, vector_map_->Get(opa), vector_map_->Get(opb), type);
1470 }
1471 return true;
1472 }
1473 } else if (instruction->IsShl() || instruction->IsShr() || instruction->IsUShr()) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001474 // Recognize halving add idiom.
Aart Bikf3e61ee2017-04-12 17:09:20 -07001475 if (VectorizeHalvingAddIdiom(node, instruction, generate_code, type, restrictions)) {
1476 return true;
1477 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001478 // Deal with vector restrictions.
Aart Bik304c8a52017-05-23 11:01:13 -07001479 HInstruction* opa = instruction->InputAt(0);
1480 HInstruction* opb = instruction->InputAt(1);
1481 HInstruction* r = opa;
1482 bool is_unsigned = false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001483 if ((HasVectorRestrictions(restrictions, kNoShift)) ||
1484 (instruction->IsShr() && HasVectorRestrictions(restrictions, kNoShr))) {
1485 return false; // unsupported instruction
Aart Bik304c8a52017-05-23 11:01:13 -07001486 } else if (HasVectorRestrictions(restrictions, kNoHiBits)) {
1487 // Shifts right need extra care to account for higher order bits.
1488 // TODO: less likely shr/unsigned and ushr/signed can by flipping signess.
1489 if (instruction->IsShr() &&
1490 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || is_unsigned)) {
1491 return false; // reject, unless all operands are sign-extension narrower
1492 } else if (instruction->IsUShr() &&
1493 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || !is_unsigned)) {
1494 return false; // reject, unless all operands are zero-extension narrower
1495 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001496 }
1497 // Accept shift operator for vectorizable/invariant operands.
1498 // TODO: accept symbolic, albeit loop invariant shift factors.
Aart Bik304c8a52017-05-23 11:01:13 -07001499 DCHECK(r != nullptr);
1500 if (generate_code && vector_mode_ != kVector) { // de-idiom
1501 r = opa;
1502 }
Aart Bik50e20d52017-05-05 14:07:29 -07001503 int64_t distance = 0;
Aart Bik304c8a52017-05-23 11:01:13 -07001504 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
Aart Bik50e20d52017-05-05 14:07:29 -07001505 IsInt64AndGet(opb, /*out*/ &distance)) {
Aart Bik65ffd8e2017-05-01 16:50:45 -07001506 // Restrict shift distance to packed data type width.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001507 int64_t max_distance = DataType::Size(type) * 8;
Aart Bik65ffd8e2017-05-01 16:50:45 -07001508 if (0 <= distance && distance < max_distance) {
1509 if (generate_code) {
Aart Bik304c8a52017-05-23 11:01:13 -07001510 GenerateVecOp(instruction, vector_map_->Get(r), opb, type);
Aart Bik65ffd8e2017-05-01 16:50:45 -07001511 }
1512 return true;
Aart Bikf8f5a162017-02-06 15:35:29 -08001513 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001514 }
Aart Bik3b2a5952018-03-05 13:55:28 -08001515 } else if (instruction->IsAbs()) {
1516 // Deal with vector restrictions.
1517 HInstruction* opa = instruction->InputAt(0);
1518 HInstruction* r = opa;
1519 bool is_unsigned = false;
1520 if (HasVectorRestrictions(restrictions, kNoAbs)) {
1521 return false;
1522 } else if (HasVectorRestrictions(restrictions, kNoHiBits) &&
1523 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || is_unsigned)) {
1524 return false; // reject, unless operand is sign-extension narrower
1525 }
1526 // Accept ABS(x) for vectorizable operand.
1527 DCHECK(r != nullptr);
1528 if (generate_code && vector_mode_ != kVector) { // de-idiom
1529 r = opa;
1530 }
1531 if (VectorizeUse(node, r, generate_code, type, restrictions)) {
1532 if (generate_code) {
1533 GenerateVecOp(instruction,
1534 vector_map_->Get(r),
1535 nullptr,
1536 HVecOperation::ToProperType(type, is_unsigned));
1537 }
1538 return true;
1539 }
Aart Bik281c6812016-08-26 11:31:48 -07001540 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08001541 return false;
Aart Bik281c6812016-08-26 11:31:48 -07001542}
1543
Aart Bik38a3f212017-10-20 17:02:21 -07001544uint32_t HLoopOptimization::GetVectorSizeInBytes() {
Vladimir Markoa0431112018-06-25 09:32:54 +01001545 switch (compiler_options_->GetInstructionSet()) {
Vladimir Marko33bff252017-11-01 14:35:42 +00001546 case InstructionSet::kArm:
1547 case InstructionSet::kThumb2:
Aart Bik38a3f212017-10-20 17:02:21 -07001548 return 8; // 64-bit SIMD
1549 default:
1550 return 16; // 128-bit SIMD
1551 }
1552}
1553
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001554bool HLoopOptimization::TrySetVectorType(DataType::Type type, uint64_t* restrictions) {
Vladimir Markoa0431112018-06-25 09:32:54 +01001555 const InstructionSetFeatures* features = compiler_options_->GetInstructionSetFeatures();
1556 switch (compiler_options_->GetInstructionSet()) {
Vladimir Marko33bff252017-11-01 14:35:42 +00001557 case InstructionSet::kArm:
1558 case InstructionSet::kThumb2:
Artem Serov8f7c4102017-06-21 11:21:37 +01001559 // Allow vectorization for all ARM devices, because Android assumes that
Aart Bikb29f6842017-07-28 15:58:41 -07001560 // ARM 32-bit always supports advanced SIMD (64-bit SIMD).
Artem Serov8f7c4102017-06-21 11:21:37 +01001561 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001562 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001563 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001564 case DataType::Type::kInt8:
Artem Serovaaac0e32018-08-07 00:52:22 +01001565 *restrictions |= kNoDiv | kNoReduction | kNoDotProd;
Artem Serov8f7c4102017-06-21 11:21:37 +01001566 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001567 case DataType::Type::kUint16:
1568 case DataType::Type::kInt16:
Artem Serovaaac0e32018-08-07 00:52:22 +01001569 *restrictions |= kNoDiv | kNoStringCharAt | kNoReduction | kNoDotProd;
Artem Serov8f7c4102017-06-21 11:21:37 +01001570 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001571 case DataType::Type::kInt32:
Artem Serov6e9b1372017-10-05 16:48:30 +01001572 *restrictions |= kNoDiv | kNoWideSAD;
Artem Serov8f7c4102017-06-21 11:21:37 +01001573 return TrySetVectorLength(2);
1574 default:
1575 break;
1576 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001577 return false;
Vladimir Marko33bff252017-11-01 14:35:42 +00001578 case InstructionSet::kArm64:
Aart Bikf8f5a162017-02-06 15:35:29 -08001579 // Allow vectorization for all ARM devices, because Android assumes that
Aart Bikb29f6842017-07-28 15:58:41 -07001580 // ARMv8 AArch64 always supports advanced SIMD (128-bit SIMD).
Aart Bikf8f5a162017-02-06 15:35:29 -08001581 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001582 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001583 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001584 case DataType::Type::kInt8:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001585 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +01001586 return TrySetVectorLength(16);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001587 case DataType::Type::kUint16:
1588 case DataType::Type::kInt16:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001589 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +01001590 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001591 case DataType::Type::kInt32:
Aart Bikf8f5a162017-02-06 15:35:29 -08001592 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +01001593 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001594 case DataType::Type::kInt64:
Aart Bik3f08e9b2018-05-01 13:42:03 -07001595 *restrictions |= kNoDiv | kNoMul;
Aart Bikf8f5a162017-02-06 15:35:29 -08001596 return TrySetVectorLength(2);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001597 case DataType::Type::kFloat32:
Aart Bik0148de42017-09-05 09:25:01 -07001598 *restrictions |= kNoReduction;
Artem Serovd4bccf12017-04-03 18:47:32 +01001599 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001600 case DataType::Type::kFloat64:
Aart Bik0148de42017-09-05 09:25:01 -07001601 *restrictions |= kNoReduction;
Aart Bikf8f5a162017-02-06 15:35:29 -08001602 return TrySetVectorLength(2);
1603 default:
1604 return false;
1605 }
Vladimir Marko33bff252017-11-01 14:35:42 +00001606 case InstructionSet::kX86:
1607 case InstructionSet::kX86_64:
Aart Bikb29f6842017-07-28 15:58:41 -07001608 // Allow vectorization for SSE4.1-enabled X86 devices only (128-bit SIMD).
Aart Bikf8f5a162017-02-06 15:35:29 -08001609 if (features->AsX86InstructionSetFeatures()->HasSSE4_1()) {
1610 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001611 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001612 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001613 case DataType::Type::kInt8:
Artem Serovaaac0e32018-08-07 00:52:22 +01001614 *restrictions |= kNoMul |
1615 kNoDiv |
1616 kNoShift |
1617 kNoAbs |
1618 kNoSignedHAdd |
1619 kNoUnroundedHAdd |
1620 kNoSAD |
1621 kNoDotProd;
Aart Bikf8f5a162017-02-06 15:35:29 -08001622 return TrySetVectorLength(16);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001623 case DataType::Type::kUint16:
Alex Light43f2f752019-12-04 17:48:45 +00001624 *restrictions |= kNoDiv |
1625 kNoAbs |
1626 kNoSignedHAdd |
1627 kNoUnroundedHAdd |
1628 kNoSAD |
1629 kNoDotProd;
1630 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001631 case DataType::Type::kInt16:
Artem Serovaaac0e32018-08-07 00:52:22 +01001632 *restrictions |= kNoDiv |
1633 kNoAbs |
1634 kNoSignedHAdd |
1635 kNoUnroundedHAdd |
Alex Light43f2f752019-12-04 17:48:45 +00001636 kNoSAD;
Aart Bikf8f5a162017-02-06 15:35:29 -08001637 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001638 case DataType::Type::kInt32:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001639 *restrictions |= kNoDiv | kNoSAD;
Aart Bikf8f5a162017-02-06 15:35:29 -08001640 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001641 case DataType::Type::kInt64:
Aart Bik3f08e9b2018-05-01 13:42:03 -07001642 *restrictions |= kNoMul | kNoDiv | kNoShr | kNoAbs | kNoSAD;
Aart Bikf8f5a162017-02-06 15:35:29 -08001643 return TrySetVectorLength(2);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001644 case DataType::Type::kFloat32:
Aart Bik3f08e9b2018-05-01 13:42:03 -07001645 *restrictions |= kNoReduction;
Aart Bikf8f5a162017-02-06 15:35:29 -08001646 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001647 case DataType::Type::kFloat64:
Aart Bik3f08e9b2018-05-01 13:42:03 -07001648 *restrictions |= kNoReduction;
Aart Bikf8f5a162017-02-06 15:35:29 -08001649 return TrySetVectorLength(2);
1650 default:
1651 break;
1652 } // switch type
1653 }
1654 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001655 default:
1656 return false;
1657 } // switch instruction set
1658}
1659
1660bool HLoopOptimization::TrySetVectorLength(uint32_t length) {
1661 DCHECK(IsPowerOfTwo(length) && length >= 2u);
1662 // First time set?
1663 if (vector_length_ == 0) {
1664 vector_length_ = length;
1665 }
1666 // Different types are acceptable within a loop-body, as long as all the corresponding vector
1667 // lengths match exactly to obtain a uniform traversal through the vector iteration space
1668 // (idiomatic exceptions to this rule can be handled by further unrolling sub-expressions).
1669 return vector_length_ == length;
1670}
1671
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001672void HLoopOptimization::GenerateVecInv(HInstruction* org, DataType::Type type) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001673 if (vector_map_->find(org) == vector_map_->end()) {
1674 // In scalar code, just use a self pass-through for scalar invariants
1675 // (viz. expression remains itself).
1676 if (vector_mode_ == kSequential) {
1677 vector_map_->Put(org, org);
1678 return;
1679 }
1680 // In vector code, explicit scalar expansion is needed.
Aart Bik0148de42017-09-05 09:25:01 -07001681 HInstruction* vector = nullptr;
1682 auto it = vector_permanent_map_->find(org);
1683 if (it != vector_permanent_map_->end()) {
1684 vector = it->second; // reuse during unrolling
1685 } else {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001686 // Generates ReplicateScalar( (optional_type_conv) org ).
1687 HInstruction* input = org;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001688 DataType::Type input_type = input->GetType();
1689 if (type != input_type && (type == DataType::Type::kInt64 ||
1690 input_type == DataType::Type::kInt64)) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001691 input = Insert(vector_preheader_,
1692 new (global_allocator_) HTypeConversion(type, input, kNoDexPc));
1693 }
1694 vector = new (global_allocator_)
Aart Bik46b6dbc2017-10-03 11:37:37 -07001695 HVecReplicateScalar(global_allocator_, input, type, vector_length_, kNoDexPc);
Aart Bik0148de42017-09-05 09:25:01 -07001696 vector_permanent_map_->Put(org, Insert(vector_preheader_, vector));
1697 }
1698 vector_map_->Put(org, vector);
Aart Bikf8f5a162017-02-06 15:35:29 -08001699 }
1700}
1701
1702void HLoopOptimization::GenerateVecSub(HInstruction* org, HInstruction* offset) {
1703 if (vector_map_->find(org) == vector_map_->end()) {
Aart Bik14a68b42017-06-08 14:06:58 -07001704 HInstruction* subscript = vector_index_;
Aart Bik37dc4df2017-06-28 14:08:00 -07001705 int64_t value = 0;
1706 if (!IsInt64AndGet(offset, &value) || value != 0) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001707 subscript = new (global_allocator_) HAdd(DataType::Type::kInt32, subscript, offset);
Aart Bikf8f5a162017-02-06 15:35:29 -08001708 if (org->IsPhi()) {
1709 Insert(vector_body_, subscript); // lacks layout placeholder
1710 }
1711 }
1712 vector_map_->Put(org, subscript);
1713 }
1714}
1715
1716void HLoopOptimization::GenerateVecMem(HInstruction* org,
1717 HInstruction* opa,
1718 HInstruction* opb,
Aart Bik14a68b42017-06-08 14:06:58 -07001719 HInstruction* offset,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001720 DataType::Type type) {
Aart Bik46b6dbc2017-10-03 11:37:37 -07001721 uint32_t dex_pc = org->GetDexPc();
Aart Bikf8f5a162017-02-06 15:35:29 -08001722 HInstruction* vector = nullptr;
1723 if (vector_mode_ == kVector) {
1724 // Vector store or load.
Aart Bik38a3f212017-10-20 17:02:21 -07001725 bool is_string_char_at = false;
Aart Bik14a68b42017-06-08 14:06:58 -07001726 HInstruction* base = org->InputAt(0);
Aart Bikf8f5a162017-02-06 15:35:29 -08001727 if (opb != nullptr) {
1728 vector = new (global_allocator_) HVecStore(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001729 global_allocator_, base, opa, opb, type, org->GetSideEffects(), vector_length_, dex_pc);
Aart Bikf8f5a162017-02-06 15:35:29 -08001730 } else {
Aart Bik38a3f212017-10-20 17:02:21 -07001731 is_string_char_at = org->AsArrayGet()->IsStringCharAt();
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001732 vector = new (global_allocator_) HVecLoad(global_allocator_,
1733 base,
1734 opa,
1735 type,
1736 org->GetSideEffects(),
1737 vector_length_,
Aart Bik46b6dbc2017-10-03 11:37:37 -07001738 is_string_char_at,
1739 dex_pc);
Aart Bik14a68b42017-06-08 14:06:58 -07001740 }
Aart Bik38a3f212017-10-20 17:02:21 -07001741 // Known (forced/adjusted/original) alignment?
1742 if (vector_dynamic_peeling_candidate_ != nullptr) {
1743 if (vector_dynamic_peeling_candidate_->offset == offset && // TODO: diffs too?
1744 DataType::Size(vector_dynamic_peeling_candidate_->type) == DataType::Size(type) &&
1745 vector_dynamic_peeling_candidate_->is_string_char_at == is_string_char_at) {
1746 vector->AsVecMemoryOperation()->SetAlignment( // forced
1747 Alignment(GetVectorSizeInBytes(), 0));
1748 }
1749 } else {
1750 vector->AsVecMemoryOperation()->SetAlignment( // adjusted/original
1751 ComputeAlignment(offset, type, is_string_char_at, vector_static_peeling_factor_));
Aart Bikf8f5a162017-02-06 15:35:29 -08001752 }
1753 } else {
1754 // Scalar store or load.
1755 DCHECK(vector_mode_ == kSequential);
1756 if (opb != nullptr) {
Aart Bik4d1a9d42017-10-19 14:40:55 -07001757 DataType::Type component_type = org->AsArraySet()->GetComponentType();
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001758 vector = new (global_allocator_) HArraySet(
Aart Bik4d1a9d42017-10-19 14:40:55 -07001759 org->InputAt(0), opa, opb, component_type, org->GetSideEffects(), dex_pc);
Aart Bikf8f5a162017-02-06 15:35:29 -08001760 } else {
Aart Bikdb14fcf2017-04-25 15:53:58 -07001761 bool is_string_char_at = org->AsArrayGet()->IsStringCharAt();
1762 vector = new (global_allocator_) HArrayGet(
Aart Bik4d1a9d42017-10-19 14:40:55 -07001763 org->InputAt(0), opa, org->GetType(), org->GetSideEffects(), dex_pc, is_string_char_at);
Aart Bikf8f5a162017-02-06 15:35:29 -08001764 }
1765 }
1766 vector_map_->Put(org, vector);
1767}
1768
Aart Bik0148de42017-09-05 09:25:01 -07001769void HLoopOptimization::GenerateVecReductionPhi(HPhi* phi) {
1770 DCHECK(reductions_->find(phi) != reductions_->end());
1771 DCHECK(reductions_->Get(phi->InputAt(1)) == phi);
1772 HInstruction* vector = nullptr;
1773 if (vector_mode_ == kSequential) {
1774 HPhi* new_phi = new (global_allocator_) HPhi(
1775 global_allocator_, kNoRegNumber, 0, phi->GetType());
1776 vector_header_->AddPhi(new_phi);
1777 vector = new_phi;
1778 } else {
1779 // Link vector reduction back to prior unrolled update, or a first phi.
1780 auto it = vector_permanent_map_->find(phi);
1781 if (it != vector_permanent_map_->end()) {
1782 vector = it->second;
1783 } else {
1784 HPhi* new_phi = new (global_allocator_) HPhi(
1785 global_allocator_, kNoRegNumber, 0, HVecOperation::kSIMDType);
1786 vector_header_->AddPhi(new_phi);
1787 vector = new_phi;
1788 }
1789 }
1790 vector_map_->Put(phi, vector);
1791}
1792
1793void HLoopOptimization::GenerateVecReductionPhiInputs(HPhi* phi, HInstruction* reduction) {
1794 HInstruction* new_phi = vector_map_->Get(phi);
1795 HInstruction* new_init = reductions_->Get(phi);
1796 HInstruction* new_red = vector_map_->Get(reduction);
1797 // Link unrolled vector loop back to new phi.
1798 for (; !new_phi->IsPhi(); new_phi = vector_permanent_map_->Get(new_phi)) {
1799 DCHECK(new_phi->IsVecOperation());
1800 }
1801 // Prepare the new initialization.
1802 if (vector_mode_ == kVector) {
Goran Jakovljevic89b8df02017-10-13 08:33:17 +02001803 // Generate a [initial, 0, .., 0] vector for add or
1804 // a [initial, initial, .., initial] vector for min/max.
Aart Bikdbbac8f2017-09-01 13:06:08 -07001805 HVecOperation* red_vector = new_red->AsVecOperation();
Goran Jakovljevic89b8df02017-10-13 08:33:17 +02001806 HVecReduce::ReductionKind kind = GetReductionKind(red_vector);
Aart Bik38a3f212017-10-20 17:02:21 -07001807 uint32_t vector_length = red_vector->GetVectorLength();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001808 DataType::Type type = red_vector->GetPackedType();
Goran Jakovljevic89b8df02017-10-13 08:33:17 +02001809 if (kind == HVecReduce::ReductionKind::kSum) {
1810 new_init = Insert(vector_preheader_,
1811 new (global_allocator_) HVecSetScalars(global_allocator_,
1812 &new_init,
1813 type,
1814 vector_length,
1815 1,
1816 kNoDexPc));
1817 } else {
1818 new_init = Insert(vector_preheader_,
1819 new (global_allocator_) HVecReplicateScalar(global_allocator_,
1820 new_init,
1821 type,
1822 vector_length,
1823 kNoDexPc));
1824 }
Aart Bik0148de42017-09-05 09:25:01 -07001825 } else {
1826 new_init = ReduceAndExtractIfNeeded(new_init);
1827 }
1828 // Set the phi inputs.
1829 DCHECK(new_phi->IsPhi());
1830 new_phi->AsPhi()->AddInput(new_init);
1831 new_phi->AsPhi()->AddInput(new_red);
1832 // New feed value for next phi (safe mutation in iteration).
1833 reductions_->find(phi)->second = new_phi;
1834}
1835
1836HInstruction* HLoopOptimization::ReduceAndExtractIfNeeded(HInstruction* instruction) {
1837 if (instruction->IsPhi()) {
1838 HInstruction* input = instruction->InputAt(1);
Aart Bik2dd7b672017-12-07 11:11:22 -08001839 if (HVecOperation::ReturnsSIMDValue(input)) {
1840 DCHECK(!input->IsPhi());
Aart Bikdbbac8f2017-09-01 13:06:08 -07001841 HVecOperation* input_vector = input->AsVecOperation();
Aart Bik38a3f212017-10-20 17:02:21 -07001842 uint32_t vector_length = input_vector->GetVectorLength();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001843 DataType::Type type = input_vector->GetPackedType();
Aart Bikdbbac8f2017-09-01 13:06:08 -07001844 HVecReduce::ReductionKind kind = GetReductionKind(input_vector);
Aart Bik0148de42017-09-05 09:25:01 -07001845 HBasicBlock* exit = instruction->GetBlock()->GetSuccessors()[0];
1846 // Generate a vector reduction and scalar extract
1847 // x = REDUCE( [x_1, .., x_n] )
1848 // y = x_1
1849 // along the exit of the defining loop.
Aart Bik0148de42017-09-05 09:25:01 -07001850 HInstruction* reduce = new (global_allocator_) HVecReduce(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001851 global_allocator_, instruction, type, vector_length, kind, kNoDexPc);
Aart Bik0148de42017-09-05 09:25:01 -07001852 exit->InsertInstructionBefore(reduce, exit->GetFirstInstruction());
1853 instruction = new (global_allocator_) HVecExtractScalar(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001854 global_allocator_, reduce, type, vector_length, 0, kNoDexPc);
Aart Bik0148de42017-09-05 09:25:01 -07001855 exit->InsertInstructionAfter(instruction, reduce);
1856 }
1857 }
1858 return instruction;
1859}
1860
Aart Bikf8f5a162017-02-06 15:35:29 -08001861#define GENERATE_VEC(x, y) \
1862 if (vector_mode_ == kVector) { \
1863 vector = (x); \
1864 } else { \
1865 DCHECK(vector_mode_ == kSequential); \
1866 vector = (y); \
1867 } \
1868 break;
1869
1870void HLoopOptimization::GenerateVecOp(HInstruction* org,
1871 HInstruction* opa,
1872 HInstruction* opb,
Aart Bik3f08e9b2018-05-01 13:42:03 -07001873 DataType::Type type) {
Aart Bik46b6dbc2017-10-03 11:37:37 -07001874 uint32_t dex_pc = org->GetDexPc();
Aart Bikf8f5a162017-02-06 15:35:29 -08001875 HInstruction* vector = nullptr;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001876 DataType::Type org_type = org->GetType();
Aart Bikf8f5a162017-02-06 15:35:29 -08001877 switch (org->GetKind()) {
1878 case HInstruction::kNeg:
1879 DCHECK(opb == nullptr);
1880 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001881 new (global_allocator_) HVecNeg(global_allocator_, opa, type, vector_length_, dex_pc),
1882 new (global_allocator_) HNeg(org_type, opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001883 case HInstruction::kNot:
1884 DCHECK(opb == nullptr);
1885 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001886 new (global_allocator_) HVecNot(global_allocator_, opa, type, vector_length_, dex_pc),
1887 new (global_allocator_) HNot(org_type, opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001888 case HInstruction::kBooleanNot:
1889 DCHECK(opb == nullptr);
1890 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001891 new (global_allocator_) HVecNot(global_allocator_, opa, type, vector_length_, dex_pc),
1892 new (global_allocator_) HBooleanNot(opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001893 case HInstruction::kTypeConversion:
1894 DCHECK(opb == nullptr);
1895 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001896 new (global_allocator_) HVecCnv(global_allocator_, opa, type, vector_length_, dex_pc),
1897 new (global_allocator_) HTypeConversion(org_type, opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001898 case HInstruction::kAdd:
1899 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001900 new (global_allocator_) HVecAdd(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1901 new (global_allocator_) HAdd(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001902 case HInstruction::kSub:
1903 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001904 new (global_allocator_) HVecSub(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1905 new (global_allocator_) HSub(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001906 case HInstruction::kMul:
1907 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001908 new (global_allocator_) HVecMul(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1909 new (global_allocator_) HMul(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001910 case HInstruction::kDiv:
1911 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001912 new (global_allocator_) HVecDiv(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1913 new (global_allocator_) HDiv(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001914 case HInstruction::kAnd:
1915 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001916 new (global_allocator_) HVecAnd(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1917 new (global_allocator_) HAnd(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001918 case HInstruction::kOr:
1919 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001920 new (global_allocator_) HVecOr(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1921 new (global_allocator_) HOr(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001922 case HInstruction::kXor:
1923 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001924 new (global_allocator_) HVecXor(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1925 new (global_allocator_) HXor(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001926 case HInstruction::kShl:
1927 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001928 new (global_allocator_) HVecShl(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1929 new (global_allocator_) HShl(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001930 case HInstruction::kShr:
1931 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001932 new (global_allocator_) HVecShr(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1933 new (global_allocator_) HShr(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001934 case HInstruction::kUShr:
1935 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001936 new (global_allocator_) HVecUShr(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1937 new (global_allocator_) HUShr(org_type, opa, opb, dex_pc));
Aart Bik3b2a5952018-03-05 13:55:28 -08001938 case HInstruction::kAbs:
1939 DCHECK(opb == nullptr);
1940 GENERATE_VEC(
1941 new (global_allocator_) HVecAbs(global_allocator_, opa, type, vector_length_, dex_pc),
1942 new (global_allocator_) HAbs(org_type, opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001943 default:
1944 break;
1945 } // switch
1946 CHECK(vector != nullptr) << "Unsupported SIMD operator";
1947 vector_map_->Put(org, vector);
1948}
1949
1950#undef GENERATE_VEC
1951
1952//
Aart Bikf3e61ee2017-04-12 17:09:20 -07001953// Vectorization idioms.
1954//
1955
1956// Method recognizes the following idioms:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001957// rounding halving add (a + b + 1) >> 1 for unsigned/signed operands a, b
1958// truncated halving add (a + b) >> 1 for unsigned/signed operands a, b
Aart Bikf3e61ee2017-04-12 17:09:20 -07001959// Provided that the operands are promoted to a wider form to do the arithmetic and
1960// then cast back to narrower form, the idioms can be mapped into efficient SIMD
1961// implementation that operates directly in narrower form (plus one extra bit).
1962// TODO: current version recognizes implicit byte/short/char widening only;
1963// explicit widening from int to long could be added later.
1964bool HLoopOptimization::VectorizeHalvingAddIdiom(LoopNode* node,
1965 HInstruction* instruction,
1966 bool generate_code,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001967 DataType::Type type,
Aart Bikf3e61ee2017-04-12 17:09:20 -07001968 uint64_t restrictions) {
1969 // Test for top level arithmetic shift right x >> 1 or logical shift right x >>> 1
Aart Bik304c8a52017-05-23 11:01:13 -07001970 // (note whether the sign bit in wider precision is shifted in has no effect
Aart Bikf3e61ee2017-04-12 17:09:20 -07001971 // on the narrow precision computed by the idiom).
Aart Bikf3e61ee2017-04-12 17:09:20 -07001972 if ((instruction->IsShr() ||
1973 instruction->IsUShr()) &&
Aart Bik0148de42017-09-05 09:25:01 -07001974 IsInt64Value(instruction->InputAt(1), 1)) {
Aart Bik5f805002017-05-16 16:42:41 -07001975 // Test for (a + b + c) >> 1 for optional constant c.
1976 HInstruction* a = nullptr;
1977 HInstruction* b = nullptr;
1978 int64_t c = 0;
Nicolas Geoffraya3e23262018-03-28 11:15:12 +00001979 if (IsAddConst2(graph_, instruction->InputAt(0), /*out*/ &a, /*out*/ &b, /*out*/ &c)) {
Aart Bik5f805002017-05-16 16:42:41 -07001980 // Accept c == 1 (rounded) or c == 0 (not rounded).
1981 bool is_rounded = false;
1982 if (c == 1) {
1983 is_rounded = true;
1984 } else if (c != 0) {
1985 return false;
1986 }
1987 // Accept consistent zero or sign extension on operands a and b.
Aart Bikf3e61ee2017-04-12 17:09:20 -07001988 HInstruction* r = nullptr;
1989 HInstruction* s = nullptr;
1990 bool is_unsigned = false;
Aart Bik304c8a52017-05-23 11:01:13 -07001991 if (!IsNarrowerOperands(a, b, type, &r, &s, &is_unsigned)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -07001992 return false;
1993 }
1994 // Deal with vector restrictions.
1995 if ((!is_unsigned && HasVectorRestrictions(restrictions, kNoSignedHAdd)) ||
1996 (!is_rounded && HasVectorRestrictions(restrictions, kNoUnroundedHAdd))) {
1997 return false;
1998 }
1999 // Accept recognized halving add for vectorizable operands. Vectorized code uses the
2000 // shorthand idiomatic operation. Sequential code uses the original scalar expressions.
Nicolas Geoffraya3e23262018-03-28 11:15:12 +00002001 DCHECK(r != nullptr && s != nullptr);
Aart Bik304c8a52017-05-23 11:01:13 -07002002 if (generate_code && vector_mode_ != kVector) { // de-idiom
2003 r = instruction->InputAt(0);
2004 s = instruction->InputAt(1);
2005 }
Aart Bikf3e61ee2017-04-12 17:09:20 -07002006 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
2007 VectorizeUse(node, s, generate_code, type, restrictions)) {
2008 if (generate_code) {
2009 if (vector_mode_ == kVector) {
2010 vector_map_->Put(instruction, new (global_allocator_) HVecHalvingAdd(
2011 global_allocator_,
2012 vector_map_->Get(r),
2013 vector_map_->Get(s),
Aart Bik66c158e2018-01-31 12:55:04 -08002014 HVecOperation::ToProperType(type, is_unsigned),
Aart Bikf3e61ee2017-04-12 17:09:20 -07002015 vector_length_,
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01002016 is_rounded,
Aart Bik46b6dbc2017-10-03 11:37:37 -07002017 kNoDexPc));
Aart Bik21b85922017-09-06 13:29:16 -07002018 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorizedIdiom);
Aart Bikf3e61ee2017-04-12 17:09:20 -07002019 } else {
Aart Bik304c8a52017-05-23 11:01:13 -07002020 GenerateVecOp(instruction, vector_map_->Get(r), vector_map_->Get(s), type);
Aart Bikf3e61ee2017-04-12 17:09:20 -07002021 }
2022 }
2023 return true;
2024 }
2025 }
2026 }
2027 return false;
2028}
2029
Aart Bikdbbac8f2017-09-01 13:06:08 -07002030// Method recognizes the following idiom:
2031// q += ABS(a - b) for signed operands a, b
2032// Provided that the operands have the same type or are promoted to a wider form.
2033// Since this may involve a vector length change, the idiom is handled by going directly
2034// to a sad-accumulate node (rather than relying combining finer grained nodes later).
2035// TODO: unsigned SAD too?
2036bool HLoopOptimization::VectorizeSADIdiom(LoopNode* node,
2037 HInstruction* instruction,
2038 bool generate_code,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002039 DataType::Type reduction_type,
Aart Bikdbbac8f2017-09-01 13:06:08 -07002040 uint64_t restrictions) {
2041 // Filter integral "q += ABS(a - b);" reduction, where ABS and SUB
2042 // are done in the same precision (either int or long).
2043 if (!instruction->IsAdd() ||
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002044 (reduction_type != DataType::Type::kInt32 && reduction_type != DataType::Type::kInt64)) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07002045 return false;
2046 }
Artem Serove521eb02020-02-27 18:51:24 +00002047 HInstruction* acc = instruction->InputAt(0);
2048 HInstruction* abs = instruction->InputAt(1);
Aart Bikdbbac8f2017-09-01 13:06:08 -07002049 HInstruction* a = nullptr;
2050 HInstruction* b = nullptr;
Artem Serove521eb02020-02-27 18:51:24 +00002051 if (abs->IsAbs() &&
2052 abs->GetType() == reduction_type &&
2053 IsSubConst2(graph_, abs->InputAt(0), /*out*/ &a, /*out*/ &b)) {
Nicolas Geoffraya3e23262018-03-28 11:15:12 +00002054 DCHECK(a != nullptr && b != nullptr);
2055 } else {
Aart Bikdbbac8f2017-09-01 13:06:08 -07002056 return false;
2057 }
2058 // Accept same-type or consistent sign extension for narrower-type on operands a and b.
2059 // The same-type or narrower operands are called r (a or lower) and s (b or lower).
Aart Bikdf011c32017-09-28 12:53:04 -07002060 // We inspect the operands carefully to pick the most suited type.
Aart Bikdbbac8f2017-09-01 13:06:08 -07002061 HInstruction* r = a;
2062 HInstruction* s = b;
2063 bool is_unsigned = false;
Artem Serovaaac0e32018-08-07 00:52:22 +01002064 DataType::Type sub_type = GetNarrowerType(a, b);
Aart Bikdbbac8f2017-09-01 13:06:08 -07002065 if (reduction_type != sub_type &&
2066 (!IsNarrowerOperands(a, b, sub_type, &r, &s, &is_unsigned) || is_unsigned)) {
2067 return false;
2068 }
2069 // Try same/narrower type and deal with vector restrictions.
Artem Serov6e9b1372017-10-05 16:48:30 +01002070 if (!TrySetVectorType(sub_type, &restrictions) ||
2071 HasVectorRestrictions(restrictions, kNoSAD) ||
2072 (reduction_type != sub_type && HasVectorRestrictions(restrictions, kNoWideSAD))) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07002073 return false;
2074 }
2075 // Accept SAD idiom for vectorizable operands. Vectorized code uses the shorthand
2076 // idiomatic operation. Sequential code uses the original scalar expressions.
Nicolas Geoffraya3e23262018-03-28 11:15:12 +00002077 DCHECK(r != nullptr && s != nullptr);
Aart Bikdbbac8f2017-09-01 13:06:08 -07002078 if (generate_code && vector_mode_ != kVector) { // de-idiom
Artem Serove521eb02020-02-27 18:51:24 +00002079 r = s = abs->InputAt(0);
Aart Bikdbbac8f2017-09-01 13:06:08 -07002080 }
Artem Serove521eb02020-02-27 18:51:24 +00002081 if (VectorizeUse(node, acc, generate_code, sub_type, restrictions) &&
Aart Bikdbbac8f2017-09-01 13:06:08 -07002082 VectorizeUse(node, r, generate_code, sub_type, restrictions) &&
2083 VectorizeUse(node, s, generate_code, sub_type, restrictions)) {
2084 if (generate_code) {
2085 if (vector_mode_ == kVector) {
2086 vector_map_->Put(instruction, new (global_allocator_) HVecSADAccumulate(
2087 global_allocator_,
Artem Serove521eb02020-02-27 18:51:24 +00002088 vector_map_->Get(acc),
Aart Bikdbbac8f2017-09-01 13:06:08 -07002089 vector_map_->Get(r),
2090 vector_map_->Get(s),
Aart Bik3b2a5952018-03-05 13:55:28 -08002091 HVecOperation::ToProperType(reduction_type, is_unsigned),
Aart Bik46b6dbc2017-10-03 11:37:37 -07002092 GetOtherVL(reduction_type, sub_type, vector_length_),
2093 kNoDexPc));
Aart Bikdbbac8f2017-09-01 13:06:08 -07002094 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorizedIdiom);
2095 } else {
Artem Serove521eb02020-02-27 18:51:24 +00002096 // "GenerateVecOp()" must not be called more than once for each original loop body
2097 // instruction. As the SAD idiom processes both "current" instruction ("instruction")
2098 // and its ABS input in one go, we must check that for the scalar case the ABS instruction
2099 // has not yet been processed.
2100 if (vector_map_->find(abs) == vector_map_->end()) {
2101 GenerateVecOp(abs, vector_map_->Get(r), nullptr, reduction_type);
2102 }
2103 GenerateVecOp(instruction, vector_map_->Get(acc), vector_map_->Get(abs), reduction_type);
Aart Bikdbbac8f2017-09-01 13:06:08 -07002104 }
2105 }
2106 return true;
2107 }
2108 return false;
2109}
2110
Artem Serovaaac0e32018-08-07 00:52:22 +01002111// Method recognises the following dot product idiom:
2112// q += a * b for operands a, b whose type is narrower than the reduction one.
2113// Provided that the operands have the same type or are promoted to a wider form.
2114// Since this may involve a vector length change, the idiom is handled by going directly
2115// to a dot product node (rather than relying combining finer grained nodes later).
2116bool HLoopOptimization::VectorizeDotProdIdiom(LoopNode* node,
2117 HInstruction* instruction,
2118 bool generate_code,
2119 DataType::Type reduction_type,
2120 uint64_t restrictions) {
Alex Light43f2f752019-12-04 17:48:45 +00002121 if (!instruction->IsAdd() || reduction_type != DataType::Type::kInt32) {
Artem Serovaaac0e32018-08-07 00:52:22 +01002122 return false;
2123 }
2124
Artem Serove521eb02020-02-27 18:51:24 +00002125 HInstruction* const acc = instruction->InputAt(0);
2126 HInstruction* const mul = instruction->InputAt(1);
2127 if (!mul->IsMul() || mul->GetType() != reduction_type) {
Artem Serovaaac0e32018-08-07 00:52:22 +01002128 return false;
2129 }
2130
Artem Serove521eb02020-02-27 18:51:24 +00002131 HInstruction* const mul_left = mul->InputAt(0);
2132 HInstruction* const mul_right = mul->InputAt(1);
2133 HInstruction* r = mul_left;
2134 HInstruction* s = mul_right;
2135 DataType::Type op_type = GetNarrowerType(mul_left, mul_right);
Artem Serovaaac0e32018-08-07 00:52:22 +01002136 bool is_unsigned = false;
2137
Artem Serove521eb02020-02-27 18:51:24 +00002138 if (!IsNarrowerOperands(mul_left, mul_right, op_type, &r, &s, &is_unsigned)) {
Artem Serovaaac0e32018-08-07 00:52:22 +01002139 return false;
2140 }
2141 op_type = HVecOperation::ToProperType(op_type, is_unsigned);
2142
2143 if (!TrySetVectorType(op_type, &restrictions) ||
2144 HasVectorRestrictions(restrictions, kNoDotProd)) {
2145 return false;
2146 }
2147
2148 DCHECK(r != nullptr && s != nullptr);
2149 // Accept dot product idiom for vectorizable operands. Vectorized code uses the shorthand
2150 // idiomatic operation. Sequential code uses the original scalar expressions.
2151 if (generate_code && vector_mode_ != kVector) { // de-idiom
Artem Serove521eb02020-02-27 18:51:24 +00002152 r = mul_left;
2153 s = mul_right;
Artem Serovaaac0e32018-08-07 00:52:22 +01002154 }
Artem Serove521eb02020-02-27 18:51:24 +00002155 if (VectorizeUse(node, acc, generate_code, op_type, restrictions) &&
Artem Serovaaac0e32018-08-07 00:52:22 +01002156 VectorizeUse(node, r, generate_code, op_type, restrictions) &&
2157 VectorizeUse(node, s, generate_code, op_type, restrictions)) {
2158 if (generate_code) {
2159 if (vector_mode_ == kVector) {
2160 vector_map_->Put(instruction, new (global_allocator_) HVecDotProd(
2161 global_allocator_,
Artem Serove521eb02020-02-27 18:51:24 +00002162 vector_map_->Get(acc),
Artem Serovaaac0e32018-08-07 00:52:22 +01002163 vector_map_->Get(r),
2164 vector_map_->Get(s),
2165 reduction_type,
2166 is_unsigned,
2167 GetOtherVL(reduction_type, op_type, vector_length_),
2168 kNoDexPc));
2169 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorizedIdiom);
2170 } else {
Artem Serove521eb02020-02-27 18:51:24 +00002171 // "GenerateVecOp()" must not be called more than once for each original loop body
2172 // instruction. As the DotProd idiom processes both "current" instruction ("instruction")
2173 // and its MUL input in one go, we must check that for the scalar case the MUL instruction
2174 // has not yet been processed.
2175 if (vector_map_->find(mul) == vector_map_->end()) {
2176 GenerateVecOp(mul, vector_map_->Get(r), vector_map_->Get(s), reduction_type);
2177 }
2178 GenerateVecOp(instruction, vector_map_->Get(acc), vector_map_->Get(mul), reduction_type);
Artem Serovaaac0e32018-08-07 00:52:22 +01002179 }
2180 }
2181 return true;
2182 }
2183 return false;
2184}
2185
Aart Bikf3e61ee2017-04-12 17:09:20 -07002186//
Aart Bik14a68b42017-06-08 14:06:58 -07002187// Vectorization heuristics.
2188//
2189
Aart Bik38a3f212017-10-20 17:02:21 -07002190Alignment HLoopOptimization::ComputeAlignment(HInstruction* offset,
2191 DataType::Type type,
2192 bool is_string_char_at,
2193 uint32_t peeling) {
2194 // Combine the alignment and hidden offset that is guaranteed by
2195 // the Android runtime with a known starting index adjusted as bytes.
2196 int64_t value = 0;
2197 if (IsInt64AndGet(offset, /*out*/ &value)) {
2198 uint32_t start_offset =
2199 HiddenOffset(type, is_string_char_at) + (value + peeling) * DataType::Size(type);
2200 return Alignment(BaseAlignment(), start_offset & (BaseAlignment() - 1u));
2201 }
2202 // Otherwise, the Android runtime guarantees at least natural alignment.
2203 return Alignment(DataType::Size(type), 0);
2204}
2205
2206void HLoopOptimization::SetAlignmentStrategy(uint32_t peeling_votes[],
2207 const ArrayReference* peeling_candidate) {
2208 // Current heuristic: pick the best static loop peeling factor, if any,
2209 // or otherwise use dynamic loop peeling on suggested peeling candidate.
2210 uint32_t max_vote = 0;
2211 for (int32_t i = 0; i < 16; i++) {
2212 if (peeling_votes[i] > max_vote) {
2213 max_vote = peeling_votes[i];
2214 vector_static_peeling_factor_ = i;
2215 }
2216 }
2217 if (max_vote == 0) {
2218 vector_dynamic_peeling_candidate_ = peeling_candidate;
2219 }
2220}
2221
2222uint32_t HLoopOptimization::MaxNumberPeeled() {
2223 if (vector_dynamic_peeling_candidate_ != nullptr) {
2224 return vector_length_ - 1u; // worst-case
2225 }
2226 return vector_static_peeling_factor_; // known exactly
2227}
2228
Aart Bik14a68b42017-06-08 14:06:58 -07002229bool HLoopOptimization::IsVectorizationProfitable(int64_t trip_count) {
Aart Bik38a3f212017-10-20 17:02:21 -07002230 // Current heuristic: non-empty body with sufficient number of iterations (if known).
Aart Bik14a68b42017-06-08 14:06:58 -07002231 // TODO: refine by looking at e.g. operation count, alignment, etc.
Aart Bik38a3f212017-10-20 17:02:21 -07002232 // TODO: trip count is really unsigned entity, provided the guarding test
2233 // is satisfied; deal with this more carefully later
2234 uint32_t max_peel = MaxNumberPeeled();
Aart Bik14a68b42017-06-08 14:06:58 -07002235 if (vector_length_ == 0) {
2236 return false; // nothing found
Aart Bik38a3f212017-10-20 17:02:21 -07002237 } else if (trip_count < 0) {
2238 return false; // guard against non-taken/large
2239 } else if ((0 < trip_count) && (trip_count < (vector_length_ + max_peel))) {
Aart Bik14a68b42017-06-08 14:06:58 -07002240 return false; // insufficient iterations
2241 }
2242 return true;
2243}
2244
Aart Bik14a68b42017-06-08 14:06:58 -07002245//
Aart Bikf8f5a162017-02-06 15:35:29 -08002246// Helpers.
2247//
2248
2249bool HLoopOptimization::TrySetPhiInduction(HPhi* phi, bool restrict_uses) {
Aart Bikb29f6842017-07-28 15:58:41 -07002250 // Start with empty phi induction.
2251 iset_->clear();
2252
Nicolas Geoffrayf57c1ae2017-06-28 17:40:18 +01002253 // Special case Phis that have equivalent in a debuggable setup. Our graph checker isn't
2254 // smart enough to follow strongly connected components (and it's probably not worth
2255 // it to make it so). See b/33775412.
2256 if (graph_->IsDebuggable() && phi->HasEquivalentPhi()) {
2257 return false;
2258 }
Aart Bikb29f6842017-07-28 15:58:41 -07002259
2260 // Lookup phi induction cycle.
Aart Bikcc42be02016-10-20 16:14:16 -07002261 ArenaSet<HInstruction*>* set = induction_range_.LookupCycle(phi);
2262 if (set != nullptr) {
2263 for (HInstruction* i : *set) {
Aart Bike3dedc52016-11-02 17:50:27 -07002264 // Check that, other than instructions that are no longer in the graph (removed earlier)
Aart Bikf8f5a162017-02-06 15:35:29 -08002265 // each instruction is removable and, when restrict uses are requested, other than for phi,
2266 // all uses are contained within the cycle.
Aart Bike3dedc52016-11-02 17:50:27 -07002267 if (!i->IsInBlock()) {
2268 continue;
2269 } else if (!i->IsRemovable()) {
2270 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08002271 } else if (i != phi && restrict_uses) {
Aart Bikb29f6842017-07-28 15:58:41 -07002272 // Deal with regular uses.
Aart Bikcc42be02016-10-20 16:14:16 -07002273 for (const HUseListNode<HInstruction*>& use : i->GetUses()) {
2274 if (set->find(use.GetUser()) == set->end()) {
2275 return false;
2276 }
2277 }
2278 }
Aart Bike3dedc52016-11-02 17:50:27 -07002279 iset_->insert(i); // copy
Aart Bikcc42be02016-10-20 16:14:16 -07002280 }
Aart Bikcc42be02016-10-20 16:14:16 -07002281 return true;
2282 }
2283 return false;
2284}
2285
Aart Bikb29f6842017-07-28 15:58:41 -07002286bool HLoopOptimization::TrySetPhiReduction(HPhi* phi) {
Aart Bikcc42be02016-10-20 16:14:16 -07002287 DCHECK(iset_->empty());
Aart Bikb29f6842017-07-28 15:58:41 -07002288 // Only unclassified phi cycles are candidates for reductions.
2289 if (induction_range_.IsClassified(phi)) {
2290 return false;
2291 }
2292 // Accept operations like x = x + .., provided that the phi and the reduction are
2293 // used exactly once inside the loop, and by each other.
2294 HInputsRef inputs = phi->GetInputs();
2295 if (inputs.size() == 2) {
2296 HInstruction* reduction = inputs[1];
2297 if (HasReductionFormat(reduction, phi)) {
2298 HLoopInformation* loop_info = phi->GetBlock()->GetLoopInformation();
Aart Bik38a3f212017-10-20 17:02:21 -07002299 uint32_t use_count = 0;
Aart Bikb29f6842017-07-28 15:58:41 -07002300 bool single_use_inside_loop =
2301 // Reduction update only used by phi.
2302 reduction->GetUses().HasExactlyOneElement() &&
2303 !reduction->HasEnvironmentUses() &&
2304 // Reduction update is only use of phi inside the loop.
2305 IsOnlyUsedAfterLoop(loop_info, phi, /*collect_loop_uses*/ true, &use_count) &&
2306 iset_->size() == 1;
2307 iset_->clear(); // leave the way you found it
2308 if (single_use_inside_loop) {
2309 // Link reduction back, and start recording feed value.
2310 reductions_->Put(reduction, phi);
2311 reductions_->Put(phi, phi->InputAt(0));
2312 return true;
2313 }
2314 }
2315 }
2316 return false;
2317}
2318
2319bool HLoopOptimization::TrySetSimpleLoopHeader(HBasicBlock* block, /*out*/ HPhi** main_phi) {
2320 // Start with empty phi induction and reductions.
2321 iset_->clear();
2322 reductions_->clear();
2323
2324 // Scan the phis to find the following (the induction structure has already
2325 // been optimized, so we don't need to worry about trivial cases):
2326 // (1) optional reductions in loop,
2327 // (2) the main induction, used in loop control.
2328 HPhi* phi = nullptr;
2329 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
2330 if (TrySetPhiReduction(it.Current()->AsPhi())) {
2331 continue;
2332 } else if (phi == nullptr) {
2333 // Found the first candidate for main induction.
2334 phi = it.Current()->AsPhi();
2335 } else {
2336 return false;
2337 }
2338 }
2339
2340 // Then test for a typical loopheader:
2341 // s: SuspendCheck
2342 // c: Condition(phi, bound)
2343 // i: If(c)
2344 if (phi != nullptr && TrySetPhiInduction(phi, /*restrict_uses*/ false)) {
Aart Bikcc42be02016-10-20 16:14:16 -07002345 HInstruction* s = block->GetFirstInstruction();
2346 if (s != nullptr && s->IsSuspendCheck()) {
2347 HInstruction* c = s->GetNext();
Aart Bikd86c0852017-04-14 12:00:15 -07002348 if (c != nullptr &&
2349 c->IsCondition() &&
2350 c->GetUses().HasExactlyOneElement() && // only used for termination
2351 !c->HasEnvironmentUses()) { // unlikely, but not impossible
Aart Bikcc42be02016-10-20 16:14:16 -07002352 HInstruction* i = c->GetNext();
2353 if (i != nullptr && i->IsIf() && i->InputAt(0) == c) {
2354 iset_->insert(c);
2355 iset_->insert(s);
Aart Bikb29f6842017-07-28 15:58:41 -07002356 *main_phi = phi;
Aart Bikcc42be02016-10-20 16:14:16 -07002357 return true;
2358 }
2359 }
2360 }
2361 }
2362 return false;
2363}
2364
2365bool HLoopOptimization::IsEmptyBody(HBasicBlock* block) {
Aart Bikf8f5a162017-02-06 15:35:29 -08002366 if (!block->GetPhis().IsEmpty()) {
2367 return false;
2368 }
2369 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
2370 HInstruction* instruction = it.Current();
2371 if (!instruction->IsGoto() && iset_->find(instruction) == iset_->end()) {
2372 return false;
Aart Bikcc42be02016-10-20 16:14:16 -07002373 }
Aart Bikf8f5a162017-02-06 15:35:29 -08002374 }
2375 return true;
2376}
2377
2378bool HLoopOptimization::IsUsedOutsideLoop(HLoopInformation* loop_info,
2379 HInstruction* instruction) {
Aart Bikb29f6842017-07-28 15:58:41 -07002380 // Deal with regular uses.
Aart Bikf8f5a162017-02-06 15:35:29 -08002381 for (const HUseListNode<HInstruction*>& use : instruction->GetUses()) {
2382 if (use.GetUser()->GetBlock()->GetLoopInformation() != loop_info) {
2383 return true;
2384 }
Aart Bikcc42be02016-10-20 16:14:16 -07002385 }
2386 return false;
2387}
2388
Aart Bik482095d2016-10-10 15:39:10 -07002389bool HLoopOptimization::IsOnlyUsedAfterLoop(HLoopInformation* loop_info,
Aart Bik8c4a8542016-10-06 11:36:57 -07002390 HInstruction* instruction,
Aart Bik6b69e0a2017-01-11 10:20:43 -08002391 bool collect_loop_uses,
Aart Bik38a3f212017-10-20 17:02:21 -07002392 /*out*/ uint32_t* use_count) {
Aart Bikb29f6842017-07-28 15:58:41 -07002393 // Deal with regular uses.
Aart Bik8c4a8542016-10-06 11:36:57 -07002394 for (const HUseListNode<HInstruction*>& use : instruction->GetUses()) {
2395 HInstruction* user = use.GetUser();
2396 if (iset_->find(user) == iset_->end()) { // not excluded?
2397 HLoopInformation* other_loop_info = user->GetBlock()->GetLoopInformation();
Aart Bik482095d2016-10-10 15:39:10 -07002398 if (other_loop_info != nullptr && other_loop_info->IsIn(*loop_info)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -08002399 // If collect_loop_uses is set, simply keep adding those uses to the set.
2400 // Otherwise, reject uses inside the loop that were not already in the set.
2401 if (collect_loop_uses) {
2402 iset_->insert(user);
2403 continue;
2404 }
Aart Bik8c4a8542016-10-06 11:36:57 -07002405 return false;
2406 }
2407 ++*use_count;
2408 }
2409 }
2410 return true;
2411}
2412
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002413bool HLoopOptimization::TryReplaceWithLastValue(HLoopInformation* loop_info,
2414 HInstruction* instruction,
2415 HBasicBlock* block) {
2416 // Try to replace outside uses with the last value.
Aart Bik807868e2016-11-03 17:51:43 -07002417 if (induction_range_.CanGenerateLastValue(instruction)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -08002418 HInstruction* replacement = induction_range_.GenerateLastValue(instruction, graph_, block);
Aart Bikb29f6842017-07-28 15:58:41 -07002419 // Deal with regular uses.
Aart Bik6b69e0a2017-01-11 10:20:43 -08002420 const HUseList<HInstruction*>& uses = instruction->GetUses();
2421 for (auto it = uses.begin(), end = uses.end(); it != end;) {
2422 HInstruction* user = it->GetUser();
2423 size_t index = it->GetIndex();
2424 ++it; // increment before replacing
2425 if (iset_->find(user) == iset_->end()) { // not excluded?
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002426 if (kIsDebugBuild) {
2427 // We have checked earlier in 'IsOnlyUsedAfterLoop' that the use is after the loop.
2428 HLoopInformation* other_loop_info = user->GetBlock()->GetLoopInformation();
2429 CHECK(other_loop_info == nullptr || !other_loop_info->IsIn(*loop_info));
2430 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08002431 user->ReplaceInput(replacement, index);
2432 induction_range_.Replace(user, instruction, replacement); // update induction
2433 }
2434 }
Aart Bikb29f6842017-07-28 15:58:41 -07002435 // Deal with environment uses.
Aart Bik6b69e0a2017-01-11 10:20:43 -08002436 const HUseList<HEnvironment*>& env_uses = instruction->GetEnvUses();
2437 for (auto it = env_uses.begin(), end = env_uses.end(); it != end;) {
2438 HEnvironment* user = it->GetUser();
2439 size_t index = it->GetIndex();
2440 ++it; // increment before replacing
2441 if (iset_->find(user->GetHolder()) == iset_->end()) { // not excluded?
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002442 // Only update environment uses after the loop.
Aart Bik14a68b42017-06-08 14:06:58 -07002443 HLoopInformation* other_loop_info = user->GetHolder()->GetBlock()->GetLoopInformation();
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002444 if (other_loop_info == nullptr || !other_loop_info->IsIn(*loop_info)) {
2445 user->RemoveAsUserOfInput(index);
2446 user->SetRawEnvAt(index, replacement);
2447 replacement->AddEnvUseAt(user, index);
2448 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08002449 }
2450 }
Aart Bik807868e2016-11-03 17:51:43 -07002451 return true;
Aart Bik8c4a8542016-10-06 11:36:57 -07002452 }
Aart Bik807868e2016-11-03 17:51:43 -07002453 return false;
Aart Bik8c4a8542016-10-06 11:36:57 -07002454}
2455
Aart Bikf8f5a162017-02-06 15:35:29 -08002456bool HLoopOptimization::TryAssignLastValue(HLoopInformation* loop_info,
2457 HInstruction* instruction,
2458 HBasicBlock* block,
2459 bool collect_loop_uses) {
2460 // Assigning the last value is always successful if there are no uses.
2461 // Otherwise, it succeeds in a no early-exit loop by generating the
2462 // proper last value assignment.
Aart Bik38a3f212017-10-20 17:02:21 -07002463 uint32_t use_count = 0;
Aart Bikf8f5a162017-02-06 15:35:29 -08002464 return IsOnlyUsedAfterLoop(loop_info, instruction, collect_loop_uses, &use_count) &&
2465 (use_count == 0 ||
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002466 (!IsEarlyExit(loop_info) && TryReplaceWithLastValue(loop_info, instruction, block)));
Aart Bikf8f5a162017-02-06 15:35:29 -08002467}
2468
Aart Bik6b69e0a2017-01-11 10:20:43 -08002469void HLoopOptimization::RemoveDeadInstructions(const HInstructionList& list) {
2470 for (HBackwardInstructionIterator i(list); !i.Done(); i.Advance()) {
2471 HInstruction* instruction = i.Current();
2472 if (instruction->IsDeadAndRemovable()) {
2473 simplified_ = true;
2474 instruction->GetBlock()->RemoveInstructionOrPhi(instruction);
2475 }
2476 }
2477}
2478
Aart Bik14a68b42017-06-08 14:06:58 -07002479bool HLoopOptimization::CanRemoveCycle() {
2480 for (HInstruction* i : *iset_) {
2481 // We can never remove instructions that have environment
2482 // uses when we compile 'debuggable'.
2483 if (i->HasEnvironmentUses() && graph_->IsDebuggable()) {
2484 return false;
2485 }
2486 // A deoptimization should never have an environment input removed.
2487 for (const HUseListNode<HEnvironment*>& use : i->GetEnvUses()) {
2488 if (use.GetUser()->GetHolder()->IsDeoptimize()) {
2489 return false;
2490 }
2491 }
2492 }
2493 return true;
2494}
2495
Aart Bik281c6812016-08-26 11:31:48 -07002496} // namespace art