blob: b72fbb07c4192eaf939fb558df0ab7464161c19a [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) {
Artem Serovb47b9782019-12-04 21:02:09 +0000308 // We want an actual add/sub and not the trivial case where {b: 0, c: 0}.
309 if (IsAddOrSub(instruction) && IsAddConst(instruction, a, b, c) && *a != nullptr) {
Nicolas Geoffraya3e23262018-03-28 11:15:12 +0000310 if (*b == nullptr) {
311 // Constant is usually already present, unless accumulated.
312 *b = graph->GetConstant(instruction->GetType(), (*c));
313 *c = 0;
Aart Bik5f805002017-05-16 16:42:41 -0700314 }
Aart Bik5f805002017-05-16 16:42:41 -0700315 return true;
316 }
317 return false;
318}
319
Nicolas Geoffraya3e23262018-03-28 11:15:12 +0000320// Detect a direct a - b or a hidden a - (-c).
321static bool IsSubConst2(HGraph* graph,
322 HInstruction* instruction,
323 /*out*/ HInstruction** a,
324 /*out*/ HInstruction** b) {
325 int64_t c = 0;
326 if (instruction->IsSub()) {
327 *a = instruction->InputAt(0);
328 *b = instruction->InputAt(1);
329 return true;
330 } else if (IsAddConst(instruction, a, b, &c) && *a != nullptr && *b == nullptr) {
331 // Constant for the hidden subtraction.
332 *b = graph->GetConstant(instruction->GetType(), -c);
333 return true;
Aart Bikdf011c32017-09-28 12:53:04 -0700334 }
335 return false;
336}
337
Aart Bikb29f6842017-07-28 15:58:41 -0700338// Detect reductions of the following forms,
Aart Bikb29f6842017-07-28 15:58:41 -0700339// x = x_phi + ..
340// x = x_phi - ..
Aart Bikb29f6842017-07-28 15:58:41 -0700341static bool HasReductionFormat(HInstruction* reduction, HInstruction* phi) {
Aart Bik3f08e9b2018-05-01 13:42:03 -0700342 if (reduction->IsAdd()) {
Aart Bikdbbac8f2017-09-01 13:06:08 -0700343 return (reduction->InputAt(0) == phi && reduction->InputAt(1) != phi) ||
344 (reduction->InputAt(0) != phi && reduction->InputAt(1) == phi);
Aart Bikb29f6842017-07-28 15:58:41 -0700345 } else if (reduction->IsSub()) {
Aart Bikdbbac8f2017-09-01 13:06:08 -0700346 return (reduction->InputAt(0) == phi && reduction->InputAt(1) != phi);
Aart Bikb29f6842017-07-28 15:58:41 -0700347 }
348 return false;
349}
350
Aart Bikdbbac8f2017-09-01 13:06:08 -0700351// Translates vector operation to reduction kind.
352static HVecReduce::ReductionKind GetReductionKind(HVecOperation* reduction) {
Shalini Salomi Bodapati81d15be2019-05-30 11:00:42 +0530353 if (reduction->IsVecAdd() ||
Artem Serovaaac0e32018-08-07 00:52:22 +0100354 reduction->IsVecSub() ||
355 reduction->IsVecSADAccumulate() ||
356 reduction->IsVecDotProd()) {
Aart Bik0148de42017-09-05 09:25:01 -0700357 return HVecReduce::kSum;
Aart Bik0148de42017-09-05 09:25:01 -0700358 }
Aart Bik38a3f212017-10-20 17:02:21 -0700359 LOG(FATAL) << "Unsupported SIMD reduction " << reduction->GetId();
Aart Bik0148de42017-09-05 09:25:01 -0700360 UNREACHABLE();
361}
362
Aart Bikf8f5a162017-02-06 15:35:29 -0800363// Test vector restrictions.
364static bool HasVectorRestrictions(uint64_t restrictions, uint64_t tested) {
365 return (restrictions & tested) != 0;
366}
367
Aart Bikf3e61ee2017-04-12 17:09:20 -0700368// Insert an instruction.
Aart Bikf8f5a162017-02-06 15:35:29 -0800369static HInstruction* Insert(HBasicBlock* block, HInstruction* instruction) {
370 DCHECK(block != nullptr);
371 DCHECK(instruction != nullptr);
372 block->InsertInstructionBefore(instruction, block->GetLastInstruction());
373 return instruction;
374}
375
Artem Serov21c7e6f2017-07-27 16:04:42 +0100376// Check that instructions from the induction sets are fully removed: have no uses
377// and no other instructions use them.
Vladimir Markoca6fff82017-10-03 14:49:14 +0100378static bool CheckInductionSetFullyRemoved(ScopedArenaSet<HInstruction*>* iset) {
Artem Serov21c7e6f2017-07-27 16:04:42 +0100379 for (HInstruction* instr : *iset) {
380 if (instr->GetBlock() != nullptr ||
381 !instr->GetUses().empty() ||
382 !instr->GetEnvUses().empty() ||
383 HasEnvironmentUsedByOthers(instr)) {
384 return false;
385 }
386 }
Artem Serov21c7e6f2017-07-27 16:04:42 +0100387 return true;
388}
389
Artem Serov72411e62017-10-19 16:18:07 +0100390// Tries to statically evaluate condition of the specified "HIf" for other condition checks.
391static void TryToEvaluateIfCondition(HIf* instruction, HGraph* graph) {
392 HInstruction* cond = instruction->InputAt(0);
393
394 // If a condition 'cond' is evaluated in an HIf instruction then in the successors of the
395 // IF_BLOCK we statically know the value of the condition 'cond' (TRUE in TRUE_SUCC, FALSE in
396 // FALSE_SUCC). Using that we can replace another evaluation (use) EVAL of the same 'cond'
397 // with TRUE value (FALSE value) if every path from the ENTRY_BLOCK to EVAL_BLOCK contains the
398 // edge HIF_BLOCK->TRUE_SUCC (HIF_BLOCK->FALSE_SUCC).
399 // if (cond) { if(cond) {
400 // if (cond) {} if (1) {}
401 // } else { =======> } else {
402 // if (cond) {} if (0) {}
403 // } }
404 if (!cond->IsConstant()) {
405 HBasicBlock* true_succ = instruction->IfTrueSuccessor();
406 HBasicBlock* false_succ = instruction->IfFalseSuccessor();
407
408 DCHECK_EQ(true_succ->GetPredecessors().size(), 1u);
409 DCHECK_EQ(false_succ->GetPredecessors().size(), 1u);
410
411 const HUseList<HInstruction*>& uses = cond->GetUses();
412 for (auto it = uses.begin(), end = uses.end(); it != end; /* ++it below */) {
413 HInstruction* user = it->GetUser();
414 size_t index = it->GetIndex();
415 HBasicBlock* user_block = user->GetBlock();
416 // Increment `it` now because `*it` may disappear thanks to user->ReplaceInput().
417 ++it;
418 if (true_succ->Dominates(user_block)) {
419 user->ReplaceInput(graph->GetIntConstant(1), index);
420 } else if (false_succ->Dominates(user_block)) {
421 user->ReplaceInput(graph->GetIntConstant(0), index);
422 }
423 }
424 }
425}
426
Artem Serov18ba1da2018-05-16 19:06:32 +0100427// Peel the first 'count' iterations of the loop.
Nicolas Geoffray256c94b2019-04-29 10:55:09 +0100428static void PeelByCount(HLoopInformation* loop_info,
429 int count,
430 InductionVarRange* induction_range) {
Artem Serov18ba1da2018-05-16 19:06:32 +0100431 for (int i = 0; i < count; i++) {
432 // Perform peeling.
Nicolas Geoffray256c94b2019-04-29 10:55:09 +0100433 PeelUnrollSimpleHelper helper(loop_info, induction_range);
Artem Serov18ba1da2018-05-16 19:06:32 +0100434 helper.DoPeeling();
435 }
436}
437
Artem Serovaaac0e32018-08-07 00:52:22 +0100438// Returns the narrower type out of instructions a and b types.
439static DataType::Type GetNarrowerType(HInstruction* a, HInstruction* b) {
440 DataType::Type type = a->GetType();
441 if (DataType::Size(b->GetType()) < DataType::Size(type)) {
442 type = b->GetType();
443 }
444 if (a->IsTypeConversion() &&
445 DataType::Size(a->InputAt(0)->GetType()) < DataType::Size(type)) {
446 type = a->InputAt(0)->GetType();
447 }
448 if (b->IsTypeConversion() &&
449 DataType::Size(b->InputAt(0)->GetType()) < DataType::Size(type)) {
450 type = b->InputAt(0)->GetType();
451 }
452 return type;
453}
454
Aart Bik281c6812016-08-26 11:31:48 -0700455//
Aart Bikb29f6842017-07-28 15:58:41 -0700456// Public methods.
Aart Bik281c6812016-08-26 11:31:48 -0700457//
458
459HLoopOptimization::HLoopOptimization(HGraph* graph,
Vladimir Markoa0431112018-06-25 09:32:54 +0100460 const CompilerOptions* compiler_options,
Aart Bikb92cc332017-09-06 15:53:17 -0700461 HInductionVarAnalysis* induction_analysis,
Aart Bik2ca10eb2017-11-15 15:17:53 -0800462 OptimizingCompilerStats* stats,
463 const char* name)
464 : HOptimization(graph, name, stats),
Vladimir Markoa0431112018-06-25 09:32:54 +0100465 compiler_options_(compiler_options),
Aart Bik281c6812016-08-26 11:31:48 -0700466 induction_range_(induction_analysis),
Aart Bik96202302016-10-04 17:33:56 -0700467 loop_allocator_(nullptr),
Vladimir Markoca6fff82017-10-03 14:49:14 +0100468 global_allocator_(graph_->GetAllocator()),
Aart Bik281c6812016-08-26 11:31:48 -0700469 top_loop_(nullptr),
Aart Bik8c4a8542016-10-06 11:36:57 -0700470 last_loop_(nullptr),
Aart Bik482095d2016-10-10 15:39:10 -0700471 iset_(nullptr),
Aart Bikb29f6842017-07-28 15:58:41 -0700472 reductions_(nullptr),
Aart Bikf8f5a162017-02-06 15:35:29 -0800473 simplified_(false),
474 vector_length_(0),
475 vector_refs_(nullptr),
Aart Bik38a3f212017-10-20 17:02:21 -0700476 vector_static_peeling_factor_(0),
477 vector_dynamic_peeling_candidate_(nullptr),
Aart Bik14a68b42017-06-08 14:06:58 -0700478 vector_runtime_test_a_(nullptr),
479 vector_runtime_test_b_(nullptr),
Aart Bik0148de42017-09-05 09:25:01 -0700480 vector_map_(nullptr),
Vladimir Markoca6fff82017-10-03 14:49:14 +0100481 vector_permanent_map_(nullptr),
482 vector_mode_(kSequential),
483 vector_preheader_(nullptr),
484 vector_header_(nullptr),
485 vector_body_(nullptr),
Artem Serov121f2032017-10-23 19:19:06 +0100486 vector_index_(nullptr),
Vladimir Markoa0431112018-06-25 09:32:54 +0100487 arch_loop_helper_(ArchNoOptsLoopHelper::Create(compiler_options_ != nullptr
488 ? compiler_options_->GetInstructionSet()
Artem Serov121f2032017-10-23 19:19:06 +0100489 : InstructionSet::kNone,
490 global_allocator_)) {
Aart Bik281c6812016-08-26 11:31:48 -0700491}
492
Aart Bik24773202018-04-26 10:28:51 -0700493bool HLoopOptimization::Run() {
Mingyao Yang01b47b02017-02-03 12:09:57 -0800494 // Skip if there is no loop or the graph has try-catch/irreducible loops.
Aart Bik281c6812016-08-26 11:31:48 -0700495 // TODO: make this less of a sledgehammer.
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800496 if (!graph_->HasLoops() || graph_->HasTryCatch() || graph_->HasIrreducibleLoops()) {
Aart Bik24773202018-04-26 10:28:51 -0700497 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700498 }
499
Vladimir Markoca6fff82017-10-03 14:49:14 +0100500 // Phase-local allocator.
501 ScopedArenaAllocator allocator(graph_->GetArenaStack());
Aart Bik96202302016-10-04 17:33:56 -0700502 loop_allocator_ = &allocator;
Nicolas Geoffrayebe16742016-10-05 09:55:42 +0100503
Aart Bik96202302016-10-04 17:33:56 -0700504 // Perform loop optimizations.
Aart Bik24773202018-04-26 10:28:51 -0700505 bool didLoopOpt = LocalRun();
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800506 if (top_loop_ == nullptr) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800507 graph_->SetHasLoops(false); // no more loops
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800508 }
509
Aart Bik96202302016-10-04 17:33:56 -0700510 // Detach.
511 loop_allocator_ = nullptr;
512 last_loop_ = top_loop_ = nullptr;
Aart Bik24773202018-04-26 10:28:51 -0700513
514 return didLoopOpt;
Aart Bik96202302016-10-04 17:33:56 -0700515}
516
Aart Bikb29f6842017-07-28 15:58:41 -0700517//
518// Loop setup and traversal.
519//
520
Aart Bik24773202018-04-26 10:28:51 -0700521bool HLoopOptimization::LocalRun() {
522 bool didLoopOpt = false;
Aart Bik96202302016-10-04 17:33:56 -0700523 // Build the linear order using the phase-local allocator. This step enables building
524 // a loop hierarchy that properly reflects the outer-inner and previous-next relation.
Vladimir Markoca6fff82017-10-03 14:49:14 +0100525 ScopedArenaVector<HBasicBlock*> linear_order(loop_allocator_->Adapter(kArenaAllocLinearOrder));
526 LinearizeGraph(graph_, &linear_order);
Aart Bik96202302016-10-04 17:33:56 -0700527
Aart Bik281c6812016-08-26 11:31:48 -0700528 // Build the loop hierarchy.
Aart Bik96202302016-10-04 17:33:56 -0700529 for (HBasicBlock* block : linear_order) {
Aart Bik281c6812016-08-26 11:31:48 -0700530 if (block->IsLoopHeader()) {
531 AddLoop(block->GetLoopInformation());
532 }
533 }
Aart Bik96202302016-10-04 17:33:56 -0700534
Aart Bik8c4a8542016-10-06 11:36:57 -0700535 // Traverse the loop hierarchy inner-to-outer and optimize. Traversal can use
Aart Bikf8f5a162017-02-06 15:35:29 -0800536 // temporary data structures using the phase-local allocator. All new HIR
537 // should use the global allocator.
Aart Bik8c4a8542016-10-06 11:36:57 -0700538 if (top_loop_ != nullptr) {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100539 ScopedArenaSet<HInstruction*> iset(loop_allocator_->Adapter(kArenaAllocLoopOptimization));
540 ScopedArenaSafeMap<HInstruction*, HInstruction*> reds(
Aart Bikb29f6842017-07-28 15:58:41 -0700541 std::less<HInstruction*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
Vladimir Markoca6fff82017-10-03 14:49:14 +0100542 ScopedArenaSet<ArrayReference> refs(loop_allocator_->Adapter(kArenaAllocLoopOptimization));
543 ScopedArenaSafeMap<HInstruction*, HInstruction*> map(
Aart Bikf8f5a162017-02-06 15:35:29 -0800544 std::less<HInstruction*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
Vladimir Markoca6fff82017-10-03 14:49:14 +0100545 ScopedArenaSafeMap<HInstruction*, HInstruction*> perm(
Aart Bik0148de42017-09-05 09:25:01 -0700546 std::less<HInstruction*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
Aart Bikf8f5a162017-02-06 15:35:29 -0800547 // Attach.
Aart Bik8c4a8542016-10-06 11:36:57 -0700548 iset_ = &iset;
Aart Bikb29f6842017-07-28 15:58:41 -0700549 reductions_ = &reds;
Aart Bikf8f5a162017-02-06 15:35:29 -0800550 vector_refs_ = &refs;
551 vector_map_ = &map;
Aart Bik0148de42017-09-05 09:25:01 -0700552 vector_permanent_map_ = &perm;
Aart Bikf8f5a162017-02-06 15:35:29 -0800553 // Traverse.
Aart Bik24773202018-04-26 10:28:51 -0700554 didLoopOpt = TraverseLoopsInnerToOuter(top_loop_);
Aart Bikf8f5a162017-02-06 15:35:29 -0800555 // Detach.
556 iset_ = nullptr;
Aart Bikb29f6842017-07-28 15:58:41 -0700557 reductions_ = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800558 vector_refs_ = nullptr;
559 vector_map_ = nullptr;
Aart Bik0148de42017-09-05 09:25:01 -0700560 vector_permanent_map_ = nullptr;
Aart Bik8c4a8542016-10-06 11:36:57 -0700561 }
Aart Bik24773202018-04-26 10:28:51 -0700562 return didLoopOpt;
Aart Bik281c6812016-08-26 11:31:48 -0700563}
564
565void HLoopOptimization::AddLoop(HLoopInformation* loop_info) {
566 DCHECK(loop_info != nullptr);
Aart Bikf8f5a162017-02-06 15:35:29 -0800567 LoopNode* node = new (loop_allocator_) LoopNode(loop_info);
Aart Bik281c6812016-08-26 11:31:48 -0700568 if (last_loop_ == nullptr) {
569 // First loop.
570 DCHECK(top_loop_ == nullptr);
571 last_loop_ = top_loop_ = node;
572 } else if (loop_info->IsIn(*last_loop_->loop_info)) {
573 // Inner loop.
574 node->outer = last_loop_;
575 DCHECK(last_loop_->inner == nullptr);
576 last_loop_ = last_loop_->inner = node;
577 } else {
578 // Subsequent loop.
579 while (last_loop_->outer != nullptr && !loop_info->IsIn(*last_loop_->outer->loop_info)) {
580 last_loop_ = last_loop_->outer;
581 }
582 node->outer = last_loop_->outer;
583 node->previous = last_loop_;
584 DCHECK(last_loop_->next == nullptr);
585 last_loop_ = last_loop_->next = node;
586 }
587}
588
589void HLoopOptimization::RemoveLoop(LoopNode* node) {
590 DCHECK(node != nullptr);
Aart Bik8c4a8542016-10-06 11:36:57 -0700591 DCHECK(node->inner == nullptr);
592 if (node->previous != nullptr) {
593 // Within sequence.
594 node->previous->next = node->next;
595 if (node->next != nullptr) {
596 node->next->previous = node->previous;
597 }
598 } else {
599 // First of sequence.
600 if (node->outer != nullptr) {
601 node->outer->inner = node->next;
602 } else {
603 top_loop_ = node->next;
604 }
605 if (node->next != nullptr) {
606 node->next->outer = node->outer;
607 node->next->previous = nullptr;
608 }
609 }
Aart Bik281c6812016-08-26 11:31:48 -0700610}
611
Aart Bikb29f6842017-07-28 15:58:41 -0700612bool HLoopOptimization::TraverseLoopsInnerToOuter(LoopNode* node) {
613 bool changed = false;
Aart Bik281c6812016-08-26 11:31:48 -0700614 for ( ; node != nullptr; node = node->next) {
Aart Bikb29f6842017-07-28 15:58:41 -0700615 // Visit inner loops first. Recompute induction information for this
616 // loop if the induction of any inner loop has changed.
617 if (TraverseLoopsInnerToOuter(node->inner)) {
Aart Bik482095d2016-10-10 15:39:10 -0700618 induction_range_.ReVisit(node->loop_info);
Aart Bika8360cd2018-05-02 16:07:51 -0700619 changed = true;
Aart Bik482095d2016-10-10 15:39:10 -0700620 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800621 // Repeat simplifications in the loop-body until no more changes occur.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800622 // Note that since each simplification consists of eliminating code (without
623 // introducing new code), this process is always finite.
Aart Bikdf7822e2016-12-06 10:05:30 -0800624 do {
625 simplified_ = false;
Aart Bikdf7822e2016-12-06 10:05:30 -0800626 SimplifyInduction(node);
Aart Bik6b69e0a2017-01-11 10:20:43 -0800627 SimplifyBlocks(node);
Aart Bikb29f6842017-07-28 15:58:41 -0700628 changed = simplified_ || changed;
Aart Bikdf7822e2016-12-06 10:05:30 -0800629 } while (simplified_);
Aart Bikf8f5a162017-02-06 15:35:29 -0800630 // Optimize inner loop.
Aart Bik9abf8942016-10-14 09:49:42 -0700631 if (node->inner == nullptr) {
Aart Bikb29f6842017-07-28 15:58:41 -0700632 changed = OptimizeInnerLoop(node) || changed;
Aart Bik9abf8942016-10-14 09:49:42 -0700633 }
Aart Bik281c6812016-08-26 11:31:48 -0700634 }
Aart Bikb29f6842017-07-28 15:58:41 -0700635 return changed;
Aart Bik281c6812016-08-26 11:31:48 -0700636}
637
Aart Bikf8f5a162017-02-06 15:35:29 -0800638//
639// Optimization.
640//
641
Aart Bik281c6812016-08-26 11:31:48 -0700642void HLoopOptimization::SimplifyInduction(LoopNode* node) {
643 HBasicBlock* header = node->loop_info->GetHeader();
644 HBasicBlock* preheader = node->loop_info->GetPreHeader();
Aart Bik8c4a8542016-10-06 11:36:57 -0700645 // Scan the phis in the header to find opportunities to simplify an induction
646 // cycle that is only used outside the loop. Replace these uses, if any, with
647 // the last value and remove the induction cycle.
648 // Examples: for (int i = 0; x != null; i++) { .... no i .... }
649 // for (int i = 0; i < 10; i++, k++) { .... no k .... } return k;
Aart Bik281c6812016-08-26 11:31:48 -0700650 for (HInstructionIterator it(header->GetPhis()); !it.Done(); it.Advance()) {
651 HPhi* phi = it.Current()->AsPhi();
Aart Bikf8f5a162017-02-06 15:35:29 -0800652 if (TrySetPhiInduction(phi, /*restrict_uses*/ true) &&
653 TryAssignLastValue(node->loop_info, phi, preheader, /*collect_loop_uses*/ false)) {
Aart Bik671e48a2017-08-09 13:16:56 -0700654 // Note that it's ok to have replaced uses after the loop with the last value, without
655 // being able to remove the cycle. Environment uses (which are the reason we may not be
656 // able to remove the cycle) within the loop will still hold the right value. We must
657 // have tried first, however, to replace outside uses.
658 if (CanRemoveCycle()) {
659 simplified_ = true;
660 for (HInstruction* i : *iset_) {
661 RemoveFromCycle(i);
662 }
663 DCHECK(CheckInductionSetFullyRemoved(iset_));
Aart Bik281c6812016-08-26 11:31:48 -0700664 }
Aart Bik482095d2016-10-10 15:39:10 -0700665 }
666 }
667}
668
669void HLoopOptimization::SimplifyBlocks(LoopNode* node) {
Aart Bikdf7822e2016-12-06 10:05:30 -0800670 // Iterate over all basic blocks in the loop-body.
671 for (HBlocksInLoopIterator it(*node->loop_info); !it.Done(); it.Advance()) {
672 HBasicBlock* block = it.Current();
673 // Remove dead instructions from the loop-body.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800674 RemoveDeadInstructions(block->GetPhis());
675 RemoveDeadInstructions(block->GetInstructions());
Aart Bikdf7822e2016-12-06 10:05:30 -0800676 // Remove trivial control flow blocks from the loop-body.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800677 if (block->GetPredecessors().size() == 1 &&
678 block->GetSuccessors().size() == 1 &&
679 block->GetSingleSuccessor()->GetPredecessors().size() == 1) {
Aart Bikdf7822e2016-12-06 10:05:30 -0800680 simplified_ = true;
Aart Bik6b69e0a2017-01-11 10:20:43 -0800681 block->MergeWith(block->GetSingleSuccessor());
Aart Bikdf7822e2016-12-06 10:05:30 -0800682 } else if (block->GetSuccessors().size() == 2) {
683 // Trivial if block can be bypassed to either branch.
684 HBasicBlock* succ0 = block->GetSuccessors()[0];
685 HBasicBlock* succ1 = block->GetSuccessors()[1];
686 HBasicBlock* meet0 = nullptr;
687 HBasicBlock* meet1 = nullptr;
688 if (succ0 != succ1 &&
689 IsGotoBlock(succ0, &meet0) &&
690 IsGotoBlock(succ1, &meet1) &&
691 meet0 == meet1 && // meets again
692 meet0 != block && // no self-loop
693 meet0->GetPhis().IsEmpty()) { // not used for merging
694 simplified_ = true;
695 succ0->DisconnectAndDelete();
696 if (block->Dominates(meet0)) {
697 block->RemoveDominatedBlock(meet0);
698 succ1->AddDominatedBlock(meet0);
699 meet0->SetDominator(succ1);
Aart Bike3dedc52016-11-02 17:50:27 -0700700 }
Aart Bik482095d2016-10-10 15:39:10 -0700701 }
Aart Bik281c6812016-08-26 11:31:48 -0700702 }
Aart Bikdf7822e2016-12-06 10:05:30 -0800703 }
Aart Bik281c6812016-08-26 11:31:48 -0700704}
705
Artem Serov121f2032017-10-23 19:19:06 +0100706bool HLoopOptimization::TryOptimizeInnerLoopFinite(LoopNode* node) {
Aart Bik281c6812016-08-26 11:31:48 -0700707 HBasicBlock* header = node->loop_info->GetHeader();
708 HBasicBlock* preheader = node->loop_info->GetPreHeader();
Aart Bik9abf8942016-10-14 09:49:42 -0700709 // Ensure loop header logic is finite.
Aart Bikf8f5a162017-02-06 15:35:29 -0800710 int64_t trip_count = 0;
711 if (!induction_range_.IsFinite(node->loop_info, &trip_count)) {
Aart Bikb29f6842017-07-28 15:58:41 -0700712 return false;
Aart Bik9abf8942016-10-14 09:49:42 -0700713 }
Aart Bik281c6812016-08-26 11:31:48 -0700714 // Ensure there is only a single loop-body (besides the header).
715 HBasicBlock* body = nullptr;
716 for (HBlocksInLoopIterator it(*node->loop_info); !it.Done(); it.Advance()) {
717 if (it.Current() != header) {
718 if (body != nullptr) {
Aart Bikb29f6842017-07-28 15:58:41 -0700719 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700720 }
721 body = it.Current();
722 }
723 }
Andreas Gampef45d61c2017-06-07 10:29:33 -0700724 CHECK(body != nullptr);
Aart Bik281c6812016-08-26 11:31:48 -0700725 // Ensure there is only a single exit point.
726 if (header->GetSuccessors().size() != 2) {
Aart Bikb29f6842017-07-28 15:58:41 -0700727 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700728 }
729 HBasicBlock* exit = (header->GetSuccessors()[0] == body)
730 ? header->GetSuccessors()[1]
731 : header->GetSuccessors()[0];
Aart Bik8c4a8542016-10-06 11:36:57 -0700732 // Ensure exit can only be reached by exiting loop.
Aart Bik281c6812016-08-26 11:31:48 -0700733 if (exit->GetPredecessors().size() != 1) {
Aart Bikb29f6842017-07-28 15:58:41 -0700734 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700735 }
Aart Bik6b69e0a2017-01-11 10:20:43 -0800736 // Detect either an empty loop (no side effects other than plain iteration) or
737 // a trivial loop (just iterating once). Replace subsequent index uses, if any,
738 // with the last value and remove the loop, possibly after unrolling its body.
Aart Bikb29f6842017-07-28 15:58:41 -0700739 HPhi* main_phi = nullptr;
740 if (TrySetSimpleLoopHeader(header, &main_phi)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -0800741 bool is_empty = IsEmptyBody(body);
Aart Bikb29f6842017-07-28 15:58:41 -0700742 if (reductions_->empty() && // TODO: possible with some effort
743 (is_empty || trip_count == 1) &&
744 TryAssignLastValue(node->loop_info, main_phi, preheader, /*collect_loop_uses*/ true)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -0800745 if (!is_empty) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800746 // Unroll the loop-body, which sees initial value of the index.
Aart Bikb29f6842017-07-28 15:58:41 -0700747 main_phi->ReplaceWith(main_phi->InputAt(0));
Aart Bik6b69e0a2017-01-11 10:20:43 -0800748 preheader->MergeInstructionsWith(body);
749 }
750 body->DisconnectAndDelete();
751 exit->RemovePredecessor(header);
752 header->RemoveSuccessor(exit);
753 header->RemoveDominatedBlock(exit);
754 header->DisconnectAndDelete();
755 preheader->AddSuccessor(exit);
Aart Bikf8f5a162017-02-06 15:35:29 -0800756 preheader->AddInstruction(new (global_allocator_) HGoto());
Aart Bik6b69e0a2017-01-11 10:20:43 -0800757 preheader->AddDominatedBlock(exit);
758 exit->SetDominator(preheader);
759 RemoveLoop(node); // update hierarchy
Aart Bikb29f6842017-07-28 15:58:41 -0700760 return true;
Aart Bikf8f5a162017-02-06 15:35:29 -0800761 }
762 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800763 // Vectorize loop, if possible and valid.
Aart Bikb29f6842017-07-28 15:58:41 -0700764 if (kEnableVectorization &&
Artem Serove65ade72019-07-25 21:04:16 +0100765 // Disable vectorization for debuggable graphs: this is a workaround for the bug
766 // in 'GenerateNewLoop' which caused the SuspendCheck environment to be invalid.
767 // TODO: b/138601207, investigate other possible cases with wrong environment values and
768 // possibly switch back vectorization on for debuggable graphs.
769 !graph_->IsDebuggable() &&
Aart Bikb29f6842017-07-28 15:58:41 -0700770 TrySetSimpleLoopHeader(header, &main_phi) &&
Aart Bikb29f6842017-07-28 15:58:41 -0700771 ShouldVectorize(node, body, trip_count) &&
772 TryAssignLastValue(node->loop_info, main_phi, preheader, /*collect_loop_uses*/ true)) {
773 Vectorize(node, body, exit, trip_count);
774 graph_->SetHasSIMD(true); // flag SIMD usage
Aart Bik21b85922017-09-06 13:29:16 -0700775 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorized);
Aart Bikb29f6842017-07-28 15:58:41 -0700776 return true;
Aart Bikf8f5a162017-02-06 15:35:29 -0800777 }
Aart Bikb29f6842017-07-28 15:58:41 -0700778 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -0800779}
780
Artem Serov121f2032017-10-23 19:19:06 +0100781bool HLoopOptimization::OptimizeInnerLoop(LoopNode* node) {
Artem Serov0e329082018-06-12 10:23:27 +0100782 return TryOptimizeInnerLoopFinite(node) || TryPeelingAndUnrolling(node);
Artem Serov121f2032017-10-23 19:19:06 +0100783}
784
Artem Serov121f2032017-10-23 19:19:06 +0100785
Artem Serov121f2032017-10-23 19:19:06 +0100786
787//
Artem Serov0e329082018-06-12 10:23:27 +0100788// Scalar loop peeling and unrolling: generic part methods.
Artem Serov121f2032017-10-23 19:19:06 +0100789//
790
Artem Serov0e329082018-06-12 10:23:27 +0100791bool HLoopOptimization::TryUnrollingForBranchPenaltyReduction(LoopAnalysisInfo* analysis_info,
792 bool generate_code) {
793 if (analysis_info->GetNumberOfExits() > 1) {
Artem Serov121f2032017-10-23 19:19:06 +0100794 return false;
795 }
796
Artem Serov0e329082018-06-12 10:23:27 +0100797 uint32_t unrolling_factor = arch_loop_helper_->GetScalarUnrollingFactor(analysis_info);
798 if (unrolling_factor == LoopAnalysisInfo::kNoUnrollingFactor) {
Artem Serov121f2032017-10-23 19:19:06 +0100799 return false;
800 }
801
Artem Serov0e329082018-06-12 10:23:27 +0100802 if (generate_code) {
803 // TODO: support other unrolling factors.
804 DCHECK_EQ(unrolling_factor, 2u);
805
806 // Perform unrolling.
807 HLoopInformation* loop_info = analysis_info->GetLoopInfo();
Nicolas Geoffray256c94b2019-04-29 10:55:09 +0100808 PeelUnrollSimpleHelper helper(loop_info, &induction_range_);
Artem Serov0e329082018-06-12 10:23:27 +0100809 helper.DoUnrolling();
810
811 // Remove the redundant loop check after unrolling.
812 HIf* copy_hif =
813 helper.GetBasicBlockMap()->Get(loop_info->GetHeader())->GetLastInstruction()->AsIf();
814 int32_t constant = loop_info->Contains(*copy_hif->IfTrueSuccessor()) ? 1 : 0;
815 copy_hif->ReplaceInput(graph_->GetIntConstant(constant), 0u);
Artem Serov121f2032017-10-23 19:19:06 +0100816 }
Artem Serov121f2032017-10-23 19:19:06 +0100817 return true;
818}
819
Artem Serov0e329082018-06-12 10:23:27 +0100820bool HLoopOptimization::TryPeelingForLoopInvariantExitsElimination(LoopAnalysisInfo* analysis_info,
821 bool generate_code) {
822 HLoopInformation* loop_info = analysis_info->GetLoopInfo();
Artem Serov72411e62017-10-19 16:18:07 +0100823 if (!arch_loop_helper_->IsLoopPeelingEnabled()) {
824 return false;
825 }
826
Artem Serov0e329082018-06-12 10:23:27 +0100827 if (analysis_info->GetNumberOfInvariantExits() == 0) {
Artem Serov72411e62017-10-19 16:18:07 +0100828 return false;
829 }
830
Artem Serov0e329082018-06-12 10:23:27 +0100831 if (generate_code) {
832 // Perform peeling.
Nicolas Geoffray256c94b2019-04-29 10:55:09 +0100833 PeelUnrollSimpleHelper helper(loop_info, &induction_range_);
Artem Serov0e329082018-06-12 10:23:27 +0100834 helper.DoPeeling();
Artem Serov72411e62017-10-19 16:18:07 +0100835
Artem Serov0e329082018-06-12 10:23:27 +0100836 // Statically evaluate loop check after peeling for loop invariant condition.
837 const SuperblockCloner::HInstructionMap* hir_map = helper.GetInstructionMap();
838 for (auto entry : *hir_map) {
839 HInstruction* copy = entry.second;
840 if (copy->IsIf()) {
841 TryToEvaluateIfCondition(copy->AsIf(), graph_);
842 }
Artem Serov72411e62017-10-19 16:18:07 +0100843 }
844 }
845
846 return true;
847}
848
Artem Serov18ba1da2018-05-16 19:06:32 +0100849bool HLoopOptimization::TryFullUnrolling(LoopAnalysisInfo* analysis_info, bool generate_code) {
850 // Fully unroll loops with a known and small trip count.
851 int64_t trip_count = analysis_info->GetTripCount();
852 if (!arch_loop_helper_->IsLoopPeelingEnabled() ||
853 trip_count == LoopAnalysisInfo::kUnknownTripCount ||
854 !arch_loop_helper_->IsFullUnrollingBeneficial(analysis_info)) {
855 return false;
856 }
857
858 if (generate_code) {
859 // Peeling of the N first iterations (where N equals to the trip count) will effectively
860 // eliminate the loop: after peeling we will have N sequential iterations copied into the loop
861 // preheader and the original loop. The trip count of this loop will be 0 as the sequential
862 // iterations are executed first and there are exactly N of them. Thus we can statically
863 // evaluate the loop exit condition to 'false' and fully eliminate it.
864 //
865 // Here is an example of full unrolling of a loop with a trip count 2:
866 //
867 // loop_cond_1
868 // loop_body_1 <- First iteration.
869 // |
870 // \ v
871 // ==\ loop_cond_2
872 // ==/ loop_body_2 <- Second iteration.
873 // / |
874 // <- v <-
875 // loop_cond \ loop_cond \ <- This cond is always false.
876 // loop_body _/ loop_body _/
877 //
878 HLoopInformation* loop_info = analysis_info->GetLoopInfo();
Nicolas Geoffray256c94b2019-04-29 10:55:09 +0100879 PeelByCount(loop_info, trip_count, &induction_range_);
Artem Serov18ba1da2018-05-16 19:06:32 +0100880 HIf* loop_hif = loop_info->GetHeader()->GetLastInstruction()->AsIf();
881 int32_t constant = loop_info->Contains(*loop_hif->IfTrueSuccessor()) ? 0 : 1;
882 loop_hif->ReplaceInput(graph_->GetIntConstant(constant), 0u);
883 }
884
885 return true;
886}
887
Artem Serov0e329082018-06-12 10:23:27 +0100888bool HLoopOptimization::TryPeelingAndUnrolling(LoopNode* node) {
889 // Don't run peeling/unrolling if compiler_options_ is nullptr (i.e., running under tests)
890 // as InstructionSet is needed.
891 if (compiler_options_ == nullptr) {
892 return false;
893 }
894
895 HLoopInformation* loop_info = node->loop_info;
896 int64_t trip_count = LoopAnalysis::GetLoopTripCount(loop_info, &induction_range_);
897 LoopAnalysisInfo analysis_info(loop_info);
898 LoopAnalysis::CalculateLoopBasicProperties(loop_info, &analysis_info, trip_count);
899
900 if (analysis_info.HasInstructionsPreventingScalarOpts() ||
901 arch_loop_helper_->IsLoopNonBeneficialForScalarOpts(&analysis_info)) {
902 return false;
903 }
904
Artem Serov18ba1da2018-05-16 19:06:32 +0100905 if (!TryFullUnrolling(&analysis_info, /*generate_code*/ false) &&
906 !TryPeelingForLoopInvariantExitsElimination(&analysis_info, /*generate_code*/ false) &&
Artem Serov0e329082018-06-12 10:23:27 +0100907 !TryUnrollingForBranchPenaltyReduction(&analysis_info, /*generate_code*/ false)) {
908 return false;
909 }
910
911 // Run 'IsLoopClonable' the last as it might be time-consuming.
912 if (!PeelUnrollHelper::IsLoopClonable(loop_info)) {
913 return false;
914 }
915
Artem Serov18ba1da2018-05-16 19:06:32 +0100916 return TryFullUnrolling(&analysis_info) ||
917 TryPeelingForLoopInvariantExitsElimination(&analysis_info) ||
Artem Serov0e329082018-06-12 10:23:27 +0100918 TryUnrollingForBranchPenaltyReduction(&analysis_info);
919}
920
Aart Bikf8f5a162017-02-06 15:35:29 -0800921//
922// Loop vectorization. The implementation is based on the book by Aart J.C. Bik:
923// "The Software Vectorization Handbook. Applying Multimedia Extensions for Maximum Performance."
924// Intel Press, June, 2004 (http://www.aartbik.com/).
925//
926
Aart Bik14a68b42017-06-08 14:06:58 -0700927bool HLoopOptimization::ShouldVectorize(LoopNode* node, HBasicBlock* block, int64_t trip_count) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800928 // Reset vector bookkeeping.
929 vector_length_ = 0;
930 vector_refs_->clear();
Aart Bik38a3f212017-10-20 17:02:21 -0700931 vector_static_peeling_factor_ = 0;
932 vector_dynamic_peeling_candidate_ = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800933 vector_runtime_test_a_ =
Igor Murashkin2ffb7032017-11-08 13:35:21 -0800934 vector_runtime_test_b_ = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800935
936 // Phis in the loop-body prevent vectorization.
937 if (!block->GetPhis().IsEmpty()) {
938 return false;
939 }
940
941 // Scan the loop-body, starting a right-hand-side tree traversal at each left-hand-side
942 // occurrence, which allows passing down attributes down the use tree.
943 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
944 if (!VectorizeDef(node, it.Current(), /*generate_code*/ false)) {
945 return false; // failure to vectorize a left-hand-side
946 }
947 }
948
Aart Bik38a3f212017-10-20 17:02:21 -0700949 // Prepare alignment analysis:
950 // (1) find desired alignment (SIMD vector size in bytes).
951 // (2) initialize static loop peeling votes (peeling factor that will
952 // make one particular reference aligned), never to exceed (1).
953 // (3) variable to record how many references share same alignment.
954 // (4) variable to record suitable candidate for dynamic loop peeling.
955 uint32_t desired_alignment = GetVectorSizeInBytes();
956 DCHECK_LE(desired_alignment, 16u);
957 uint32_t peeling_votes[16] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
958 uint32_t max_num_same_alignment = 0;
959 const ArrayReference* peeling_candidate = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800960
961 // Data dependence analysis. Find each pair of references with same type, where
962 // at least one is a write. Each such pair denotes a possible data dependence.
963 // This analysis exploits the property that differently typed arrays cannot be
964 // aliased, as well as the property that references either point to the same
965 // array or to two completely disjoint arrays, i.e., no partial aliasing.
966 // Other than a few simply heuristics, no detailed subscript analysis is done.
Aart Bik38a3f212017-10-20 17:02:21 -0700967 // The scan over references also prepares finding a suitable alignment strategy.
Aart Bikf8f5a162017-02-06 15:35:29 -0800968 for (auto i = vector_refs_->begin(); i != vector_refs_->end(); ++i) {
Aart Bik38a3f212017-10-20 17:02:21 -0700969 uint32_t num_same_alignment = 0;
970 // Scan over all next references.
Aart Bikf8f5a162017-02-06 15:35:29 -0800971 for (auto j = i; ++j != vector_refs_->end(); ) {
972 if (i->type == j->type && (i->lhs || j->lhs)) {
973 // Found same-typed a[i+x] vs. b[i+y], where at least one is a write.
974 HInstruction* a = i->base;
975 HInstruction* b = j->base;
976 HInstruction* x = i->offset;
977 HInstruction* y = j->offset;
978 if (a == b) {
979 // Found a[i+x] vs. a[i+y]. Accept if x == y (loop-independent data dependence).
980 // Conservatively assume a loop-carried data dependence otherwise, and reject.
981 if (x != y) {
982 return false;
983 }
Aart Bik38a3f212017-10-20 17:02:21 -0700984 // Count the number of references that have the same alignment (since
985 // base and offset are the same) and where at least one is a write, so
986 // e.g. a[i] = a[i] + b[i] counts a[i] but not b[i]).
987 num_same_alignment++;
Aart Bikf8f5a162017-02-06 15:35:29 -0800988 } else {
989 // Found a[i+x] vs. b[i+y]. Accept if x == y (at worst loop-independent data dependence).
990 // Conservatively assume a potential loop-carried data dependence otherwise, avoided by
991 // generating an explicit a != b disambiguation runtime test on the two references.
992 if (x != y) {
Aart Bik37dc4df2017-06-28 14:08:00 -0700993 // To avoid excessive overhead, we only accept one a != b test.
994 if (vector_runtime_test_a_ == nullptr) {
995 // First test found.
996 vector_runtime_test_a_ = a;
997 vector_runtime_test_b_ = b;
998 } else if ((vector_runtime_test_a_ != a || vector_runtime_test_b_ != b) &&
999 (vector_runtime_test_a_ != b || vector_runtime_test_b_ != a)) {
1000 return false; // second test would be needed
Aart Bikf8f5a162017-02-06 15:35:29 -08001001 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001002 }
1003 }
1004 }
1005 }
Aart Bik38a3f212017-10-20 17:02:21 -07001006 // Update information for finding suitable alignment strategy:
1007 // (1) update votes for static loop peeling,
1008 // (2) update suitable candidate for dynamic loop peeling.
1009 Alignment alignment = ComputeAlignment(i->offset, i->type, i->is_string_char_at);
1010 if (alignment.Base() >= desired_alignment) {
1011 // If the array/string object has a known, sufficient alignment, use the
1012 // initial offset to compute the static loop peeling vote (this always
1013 // works, since elements have natural alignment).
1014 uint32_t offset = alignment.Offset() & (desired_alignment - 1u);
1015 uint32_t vote = (offset == 0)
1016 ? 0
1017 : ((desired_alignment - offset) >> DataType::SizeShift(i->type));
1018 DCHECK_LT(vote, 16u);
1019 ++peeling_votes[vote];
1020 } else if (BaseAlignment() >= desired_alignment &&
1021 num_same_alignment > max_num_same_alignment) {
1022 // Otherwise, if the array/string object has a known, sufficient alignment
1023 // for just the base but with an unknown offset, record the candidate with
1024 // the most occurrences for dynamic loop peeling (again, the peeling always
1025 // works, since elements have natural alignment).
1026 max_num_same_alignment = num_same_alignment;
1027 peeling_candidate = &(*i);
1028 }
1029 } // for i
Aart Bikf8f5a162017-02-06 15:35:29 -08001030
Aart Bik38a3f212017-10-20 17:02:21 -07001031 // Find a suitable alignment strategy.
1032 SetAlignmentStrategy(peeling_votes, peeling_candidate);
1033
1034 // Does vectorization seem profitable?
1035 if (!IsVectorizationProfitable(trip_count)) {
1036 return false;
1037 }
Aart Bik14a68b42017-06-08 14:06:58 -07001038
Aart Bikf8f5a162017-02-06 15:35:29 -08001039 // Success!
1040 return true;
1041}
1042
1043void HLoopOptimization::Vectorize(LoopNode* node,
1044 HBasicBlock* block,
1045 HBasicBlock* exit,
1046 int64_t trip_count) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001047 HBasicBlock* header = node->loop_info->GetHeader();
1048 HBasicBlock* preheader = node->loop_info->GetPreHeader();
1049
Aart Bik14a68b42017-06-08 14:06:58 -07001050 // Pick a loop unrolling factor for the vector loop.
Artem Serov121f2032017-10-23 19:19:06 +01001051 uint32_t unroll = arch_loop_helper_->GetSIMDUnrollingFactor(
1052 block, trip_count, MaxNumberPeeled(), vector_length_);
Aart Bik14a68b42017-06-08 14:06:58 -07001053 uint32_t chunk = vector_length_ * unroll;
1054
Aart Bik38a3f212017-10-20 17:02:21 -07001055 DCHECK(trip_count == 0 || (trip_count >= MaxNumberPeeled() + chunk));
1056
Aart Bik14a68b42017-06-08 14:06:58 -07001057 // A cleanup loop is needed, at least, for any unknown trip count or
1058 // for a known trip count with remainder iterations after vectorization.
Aart Bik38a3f212017-10-20 17:02:21 -07001059 bool needs_cleanup = trip_count == 0 ||
1060 ((trip_count - vector_static_peeling_factor_) % chunk) != 0;
Aart Bikf8f5a162017-02-06 15:35:29 -08001061
1062 // Adjust vector bookkeeping.
Aart Bikb29f6842017-07-28 15:58:41 -07001063 HPhi* main_phi = nullptr;
1064 bool is_simple_loop_header = TrySetSimpleLoopHeader(header, &main_phi); // refills sets
Aart Bikf8f5a162017-02-06 15:35:29 -08001065 DCHECK(is_simple_loop_header);
Aart Bik14a68b42017-06-08 14:06:58 -07001066 vector_header_ = header;
1067 vector_body_ = block;
Aart Bikf8f5a162017-02-06 15:35:29 -08001068
Aart Bikdbbac8f2017-09-01 13:06:08 -07001069 // Loop induction type.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001070 DataType::Type induc_type = main_phi->GetType();
1071 DCHECK(induc_type == DataType::Type::kInt32 || induc_type == DataType::Type::kInt64)
1072 << induc_type;
Aart Bikdbbac8f2017-09-01 13:06:08 -07001073
Aart Bik38a3f212017-10-20 17:02:21 -07001074 // Generate the trip count for static or dynamic loop peeling, if needed:
1075 // ptc = <peeling factor>;
Aart Bik14a68b42017-06-08 14:06:58 -07001076 HInstruction* ptc = nullptr;
Aart Bik38a3f212017-10-20 17:02:21 -07001077 if (vector_static_peeling_factor_ != 0) {
1078 // Static loop peeling for SIMD alignment (using the most suitable
1079 // fixed peeling factor found during prior alignment analysis).
1080 DCHECK(vector_dynamic_peeling_candidate_ == nullptr);
1081 ptc = graph_->GetConstant(induc_type, vector_static_peeling_factor_);
1082 } else if (vector_dynamic_peeling_candidate_ != nullptr) {
1083 // Dynamic loop peeling for SIMD alignment (using the most suitable
1084 // candidate found during prior alignment analysis):
1085 // rem = offset % ALIGN; // adjusted as #elements
1086 // ptc = rem == 0 ? 0 : (ALIGN - rem);
1087 uint32_t shift = DataType::SizeShift(vector_dynamic_peeling_candidate_->type);
1088 uint32_t align = GetVectorSizeInBytes() >> shift;
1089 uint32_t hidden_offset = HiddenOffset(vector_dynamic_peeling_candidate_->type,
1090 vector_dynamic_peeling_candidate_->is_string_char_at);
1091 HInstruction* adjusted_offset = graph_->GetConstant(induc_type, hidden_offset >> shift);
1092 HInstruction* offset = Insert(preheader, new (global_allocator_) HAdd(
1093 induc_type, vector_dynamic_peeling_candidate_->offset, adjusted_offset));
1094 HInstruction* rem = Insert(preheader, new (global_allocator_) HAnd(
1095 induc_type, offset, graph_->GetConstant(induc_type, align - 1u)));
1096 HInstruction* sub = Insert(preheader, new (global_allocator_) HSub(
1097 induc_type, graph_->GetConstant(induc_type, align), rem));
1098 HInstruction* cond = Insert(preheader, new (global_allocator_) HEqual(
1099 rem, graph_->GetConstant(induc_type, 0)));
1100 ptc = Insert(preheader, new (global_allocator_) HSelect(
1101 cond, graph_->GetConstant(induc_type, 0), sub, kNoDexPc));
1102 needs_cleanup = true; // don't know the exact amount
Aart Bik14a68b42017-06-08 14:06:58 -07001103 }
1104
1105 // Generate loop control:
Aart Bikf8f5a162017-02-06 15:35:29 -08001106 // stc = <trip-count>;
Aart Bik38a3f212017-10-20 17:02:21 -07001107 // ptc = min(stc, ptc);
Aart Bik14a68b42017-06-08 14:06:58 -07001108 // vtc = stc - (stc - ptc) % chunk;
1109 // i = 0;
Aart Bikf8f5a162017-02-06 15:35:29 -08001110 HInstruction* stc = induction_range_.GenerateTripCount(node->loop_info, graph_, preheader);
1111 HInstruction* vtc = stc;
1112 if (needs_cleanup) {
Aart Bik14a68b42017-06-08 14:06:58 -07001113 DCHECK(IsPowerOfTwo(chunk));
1114 HInstruction* diff = stc;
1115 if (ptc != nullptr) {
Aart Bik38a3f212017-10-20 17:02:21 -07001116 if (trip_count == 0) {
1117 HInstruction* cond = Insert(preheader, new (global_allocator_) HAboveOrEqual(stc, ptc));
1118 ptc = Insert(preheader, new (global_allocator_) HSelect(cond, ptc, stc, kNoDexPc));
1119 }
Aart Bik14a68b42017-06-08 14:06:58 -07001120 diff = Insert(preheader, new (global_allocator_) HSub(induc_type, stc, ptc));
1121 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001122 HInstruction* rem = Insert(
1123 preheader, new (global_allocator_) HAnd(induc_type,
Aart Bik14a68b42017-06-08 14:06:58 -07001124 diff,
Aart Bikdbbac8f2017-09-01 13:06:08 -07001125 graph_->GetConstant(induc_type, chunk - 1)));
Aart Bikf8f5a162017-02-06 15:35:29 -08001126 vtc = Insert(preheader, new (global_allocator_) HSub(induc_type, stc, rem));
1127 }
Aart Bikdbbac8f2017-09-01 13:06:08 -07001128 vector_index_ = graph_->GetConstant(induc_type, 0);
Aart Bikf8f5a162017-02-06 15:35:29 -08001129
1130 // Generate runtime disambiguation test:
1131 // vtc = a != b ? vtc : 0;
1132 if (vector_runtime_test_a_ != nullptr) {
1133 HInstruction* rt = Insert(
1134 preheader,
1135 new (global_allocator_) HNotEqual(vector_runtime_test_a_, vector_runtime_test_b_));
1136 vtc = Insert(preheader,
Aart Bikdbbac8f2017-09-01 13:06:08 -07001137 new (global_allocator_)
1138 HSelect(rt, vtc, graph_->GetConstant(induc_type, 0), kNoDexPc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001139 needs_cleanup = true;
1140 }
1141
Aart Bik38a3f212017-10-20 17:02:21 -07001142 // Generate alignment peeling loop, if needed:
Aart Bik14a68b42017-06-08 14:06:58 -07001143 // for ( ; i < ptc; i += 1)
1144 // <loop-body>
Aart Bik38a3f212017-10-20 17:02:21 -07001145 //
1146 // NOTE: The alignment forced by the peeling loop is preserved even if data is
1147 // moved around during suspend checks, since all analysis was based on
1148 // nothing more than the Android runtime alignment conventions.
Aart Bik14a68b42017-06-08 14:06:58 -07001149 if (ptc != nullptr) {
1150 vector_mode_ = kSequential;
1151 GenerateNewLoop(node,
1152 block,
1153 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
1154 vector_index_,
1155 ptc,
Aart Bikdbbac8f2017-09-01 13:06:08 -07001156 graph_->GetConstant(induc_type, 1),
Artem Serov0e329082018-06-12 10:23:27 +01001157 LoopAnalysisInfo::kNoUnrollingFactor);
Aart Bik14a68b42017-06-08 14:06:58 -07001158 }
1159
1160 // Generate vector loop, possibly further unrolled:
1161 // for ( ; i < vtc; i += chunk)
Aart Bikf8f5a162017-02-06 15:35:29 -08001162 // <vectorized-loop-body>
1163 vector_mode_ = kVector;
1164 GenerateNewLoop(node,
1165 block,
Aart Bik14a68b42017-06-08 14:06:58 -07001166 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
1167 vector_index_,
Aart Bikf8f5a162017-02-06 15:35:29 -08001168 vtc,
Aart Bikdbbac8f2017-09-01 13:06:08 -07001169 graph_->GetConstant(induc_type, vector_length_), // increment per unroll
Aart Bik14a68b42017-06-08 14:06:58 -07001170 unroll);
Aart Bikf8f5a162017-02-06 15:35:29 -08001171 HLoopInformation* vloop = vector_header_->GetLoopInformation();
1172
1173 // Generate cleanup loop, if needed:
1174 // for ( ; i < stc; i += 1)
1175 // <loop-body>
1176 if (needs_cleanup) {
1177 vector_mode_ = kSequential;
1178 GenerateNewLoop(node,
1179 block,
1180 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
Aart Bik14a68b42017-06-08 14:06:58 -07001181 vector_index_,
Aart Bikf8f5a162017-02-06 15:35:29 -08001182 stc,
Aart Bikdbbac8f2017-09-01 13:06:08 -07001183 graph_->GetConstant(induc_type, 1),
Artem Serov0e329082018-06-12 10:23:27 +01001184 LoopAnalysisInfo::kNoUnrollingFactor);
Aart Bikf8f5a162017-02-06 15:35:29 -08001185 }
1186
Aart Bik0148de42017-09-05 09:25:01 -07001187 // Link reductions to their final uses.
1188 for (auto i = reductions_->begin(); i != reductions_->end(); ++i) {
1189 if (i->first->IsPhi()) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001190 HInstruction* phi = i->first;
1191 HInstruction* repl = ReduceAndExtractIfNeeded(i->second);
1192 // Deal with regular uses.
1193 for (const HUseListNode<HInstruction*>& use : phi->GetUses()) {
1194 induction_range_.Replace(use.GetUser(), phi, repl); // update induction use
1195 }
1196 phi->ReplaceWith(repl);
Aart Bik0148de42017-09-05 09:25:01 -07001197 }
1198 }
1199
Aart Bikf8f5a162017-02-06 15:35:29 -08001200 // Remove the original loop by disconnecting the body block
1201 // and removing all instructions from the header.
1202 block->DisconnectAndDelete();
1203 while (!header->GetFirstInstruction()->IsGoto()) {
1204 header->RemoveInstruction(header->GetFirstInstruction());
1205 }
Aart Bikb29f6842017-07-28 15:58:41 -07001206
Aart Bik14a68b42017-06-08 14:06:58 -07001207 // Update loop hierarchy: the old header now resides in the same outer loop
1208 // as the old preheader. Note that we don't bother putting sequential
1209 // loops back in the hierarchy at this point.
Aart Bikf8f5a162017-02-06 15:35:29 -08001210 header->SetLoopInformation(preheader->GetLoopInformation()); // outward
1211 node->loop_info = vloop;
1212}
1213
1214void HLoopOptimization::GenerateNewLoop(LoopNode* node,
1215 HBasicBlock* block,
1216 HBasicBlock* new_preheader,
1217 HInstruction* lo,
1218 HInstruction* hi,
Aart Bik14a68b42017-06-08 14:06:58 -07001219 HInstruction* step,
1220 uint32_t unroll) {
1221 DCHECK(unroll == 1 || vector_mode_ == kVector);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001222 DataType::Type induc_type = lo->GetType();
Aart Bikf8f5a162017-02-06 15:35:29 -08001223 // Prepare new loop.
Aart Bikf8f5a162017-02-06 15:35:29 -08001224 vector_preheader_ = new_preheader,
1225 vector_header_ = vector_preheader_->GetSingleSuccessor();
1226 vector_body_ = vector_header_->GetSuccessors()[1];
Aart Bik14a68b42017-06-08 14:06:58 -07001227 HPhi* phi = new (global_allocator_) HPhi(global_allocator_,
1228 kNoRegNumber,
1229 0,
1230 HPhi::ToPhiType(induc_type));
Aart Bikb07d1bc2017-04-05 10:03:15 -07001231 // Generate header and prepare body.
Aart Bikf8f5a162017-02-06 15:35:29 -08001232 // for (i = lo; i < hi; i += step)
1233 // <loop-body>
Aart Bik14a68b42017-06-08 14:06:58 -07001234 HInstruction* cond = new (global_allocator_) HAboveOrEqual(phi, hi);
1235 vector_header_->AddPhi(phi);
Aart Bikf8f5a162017-02-06 15:35:29 -08001236 vector_header_->AddInstruction(cond);
1237 vector_header_->AddInstruction(new (global_allocator_) HIf(cond));
Aart Bik14a68b42017-06-08 14:06:58 -07001238 vector_index_ = phi;
Aart Bik0148de42017-09-05 09:25:01 -07001239 vector_permanent_map_->clear(); // preserved over unrolling
Aart Bik14a68b42017-06-08 14:06:58 -07001240 for (uint32_t u = 0; u < unroll; u++) {
Aart Bik14a68b42017-06-08 14:06:58 -07001241 // Generate instruction map.
Aart Bik0148de42017-09-05 09:25:01 -07001242 vector_map_->clear();
Aart Bik14a68b42017-06-08 14:06:58 -07001243 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
1244 bool vectorized_def = VectorizeDef(node, it.Current(), /*generate_code*/ true);
1245 DCHECK(vectorized_def);
1246 }
1247 // Generate body from the instruction map, but in original program order.
1248 HEnvironment* env = vector_header_->GetFirstInstruction()->GetEnvironment();
1249 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
1250 auto i = vector_map_->find(it.Current());
1251 if (i != vector_map_->end() && !i->second->IsInBlock()) {
1252 Insert(vector_body_, i->second);
1253 // Deal with instructions that need an environment, such as the scalar intrinsics.
1254 if (i->second->NeedsEnvironment()) {
1255 i->second->CopyEnvironmentFromWithLoopPhiAdjustment(env, vector_header_);
1256 }
1257 }
1258 }
Aart Bik0148de42017-09-05 09:25:01 -07001259 // Generate the induction.
Aart Bik14a68b42017-06-08 14:06:58 -07001260 vector_index_ = new (global_allocator_) HAdd(induc_type, vector_index_, step);
1261 Insert(vector_body_, vector_index_);
Aart Bikf8f5a162017-02-06 15:35:29 -08001262 }
Aart Bik0148de42017-09-05 09:25:01 -07001263 // Finalize phi inputs for the reductions (if any).
1264 for (auto i = reductions_->begin(); i != reductions_->end(); ++i) {
1265 if (!i->first->IsPhi()) {
1266 DCHECK(i->second->IsPhi());
1267 GenerateVecReductionPhiInputs(i->second->AsPhi(), i->first);
1268 }
1269 }
Aart Bikb29f6842017-07-28 15:58:41 -07001270 // Finalize phi inputs for the loop index.
Aart Bik14a68b42017-06-08 14:06:58 -07001271 phi->AddInput(lo);
1272 phi->AddInput(vector_index_);
1273 vector_index_ = phi;
Aart Bikf8f5a162017-02-06 15:35:29 -08001274}
1275
Aart Bikf8f5a162017-02-06 15:35:29 -08001276bool HLoopOptimization::VectorizeDef(LoopNode* node,
1277 HInstruction* instruction,
1278 bool generate_code) {
1279 // Accept a left-hand-side array base[index] for
1280 // (1) supported vector type,
1281 // (2) loop-invariant base,
1282 // (3) unit stride index,
1283 // (4) vectorizable right-hand-side value.
1284 uint64_t restrictions = kNone;
Georgia Kouvelibac080b2019-01-31 16:12:16 +00001285 // Don't accept expressions that can throw.
1286 if (instruction->CanThrow()) {
1287 return false;
1288 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001289 if (instruction->IsArraySet()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001290 DataType::Type type = instruction->AsArraySet()->GetComponentType();
Aart Bikf8f5a162017-02-06 15:35:29 -08001291 HInstruction* base = instruction->InputAt(0);
1292 HInstruction* index = instruction->InputAt(1);
1293 HInstruction* value = instruction->InputAt(2);
1294 HInstruction* offset = nullptr;
Aart Bik6d057002018-04-09 15:39:58 -07001295 // For narrow types, explicit type conversion may have been
1296 // optimized way, so set the no hi bits restriction here.
1297 if (DataType::Size(type) <= 2) {
1298 restrictions |= kNoHiBits;
1299 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001300 if (TrySetVectorType(type, &restrictions) &&
1301 node->loop_info->IsDefinedOutOfTheLoop(base) &&
Aart Bik37dc4df2017-06-28 14:08:00 -07001302 induction_range_.IsUnitStride(instruction, index, graph_, &offset) &&
Aart Bikf8f5a162017-02-06 15:35:29 -08001303 VectorizeUse(node, value, generate_code, type, restrictions)) {
1304 if (generate_code) {
1305 GenerateVecSub(index, offset);
Aart Bik14a68b42017-06-08 14:06:58 -07001306 GenerateVecMem(instruction, vector_map_->Get(index), vector_map_->Get(value), offset, type);
Aart Bikf8f5a162017-02-06 15:35:29 -08001307 } else {
1308 vector_refs_->insert(ArrayReference(base, offset, type, /*lhs*/ true));
1309 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08001310 return true;
1311 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001312 return false;
1313 }
Aart Bik0148de42017-09-05 09:25:01 -07001314 // Accept a left-hand-side reduction for
1315 // (1) supported vector type,
1316 // (2) vectorizable right-hand-side value.
1317 auto redit = reductions_->find(instruction);
1318 if (redit != reductions_->end()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001319 DataType::Type type = instruction->GetType();
Aart Bikdbbac8f2017-09-01 13:06:08 -07001320 // Recognize SAD idiom or direct reduction.
1321 if (VectorizeSADIdiom(node, instruction, generate_code, type, restrictions) ||
Artem Serovaaac0e32018-08-07 00:52:22 +01001322 VectorizeDotProdIdiom(node, instruction, generate_code, type, restrictions) ||
Aart Bikdbbac8f2017-09-01 13:06:08 -07001323 (TrySetVectorType(type, &restrictions) &&
1324 VectorizeUse(node, instruction, generate_code, type, restrictions))) {
Aart Bik0148de42017-09-05 09:25:01 -07001325 if (generate_code) {
1326 HInstruction* new_red = vector_map_->Get(instruction);
1327 vector_permanent_map_->Put(new_red, vector_map_->Get(redit->second));
1328 vector_permanent_map_->Overwrite(redit->second, new_red);
1329 }
1330 return true;
1331 }
1332 return false;
1333 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001334 // Branch back okay.
1335 if (instruction->IsGoto()) {
1336 return true;
1337 }
1338 // Otherwise accept only expressions with no effects outside the immediate loop-body.
1339 // Note that actual uses are inspected during right-hand-side tree traversal.
Georgia Kouvelibac080b2019-01-31 16:12:16 +00001340 return !IsUsedOutsideLoop(node->loop_info, instruction)
1341 && !instruction->DoesAnyWrite();
Aart Bikf8f5a162017-02-06 15:35:29 -08001342}
1343
Aart Bikf8f5a162017-02-06 15:35:29 -08001344bool HLoopOptimization::VectorizeUse(LoopNode* node,
1345 HInstruction* instruction,
1346 bool generate_code,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001347 DataType::Type type,
Aart Bikf8f5a162017-02-06 15:35:29 -08001348 uint64_t restrictions) {
1349 // Accept anything for which code has already been generated.
1350 if (generate_code) {
1351 if (vector_map_->find(instruction) != vector_map_->end()) {
1352 return true;
1353 }
1354 }
1355 // Continue the right-hand-side tree traversal, passing in proper
1356 // types and vector restrictions along the way. During code generation,
1357 // all new nodes are drawn from the global allocator.
1358 if (node->loop_info->IsDefinedOutOfTheLoop(instruction)) {
1359 // Accept invariant use, using scalar expansion.
1360 if (generate_code) {
1361 GenerateVecInv(instruction, type);
1362 }
1363 return true;
1364 } else if (instruction->IsArrayGet()) {
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001365 // Deal with vector restrictions.
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001366 bool is_string_char_at = instruction->AsArrayGet()->IsStringCharAt();
1367 if (is_string_char_at && HasVectorRestrictions(restrictions, kNoStringCharAt)) {
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001368 return false;
1369 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001370 // Accept a right-hand-side array base[index] for
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001371 // (1) matching vector type (exact match or signed/unsigned integral type of the same size),
Aart Bikf8f5a162017-02-06 15:35:29 -08001372 // (2) loop-invariant base,
1373 // (3) unit stride index,
1374 // (4) vectorizable right-hand-side value.
1375 HInstruction* base = instruction->InputAt(0);
1376 HInstruction* index = instruction->InputAt(1);
1377 HInstruction* offset = nullptr;
Aart Bik46b6dbc2017-10-03 11:37:37 -07001378 if (HVecOperation::ToSignedType(type) == HVecOperation::ToSignedType(instruction->GetType()) &&
Aart Bikf8f5a162017-02-06 15:35:29 -08001379 node->loop_info->IsDefinedOutOfTheLoop(base) &&
Aart Bik37dc4df2017-06-28 14:08:00 -07001380 induction_range_.IsUnitStride(instruction, index, graph_, &offset)) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001381 if (generate_code) {
1382 GenerateVecSub(index, offset);
Aart Bik14a68b42017-06-08 14:06:58 -07001383 GenerateVecMem(instruction, vector_map_->Get(index), nullptr, offset, type);
Aart Bikf8f5a162017-02-06 15:35:29 -08001384 } else {
Aart Bik38a3f212017-10-20 17:02:21 -07001385 vector_refs_->insert(ArrayReference(base, offset, type, /*lhs*/ false, is_string_char_at));
Aart Bikf8f5a162017-02-06 15:35:29 -08001386 }
1387 return true;
1388 }
Aart Bik0148de42017-09-05 09:25:01 -07001389 } else if (instruction->IsPhi()) {
1390 // Accept particular phi operations.
1391 if (reductions_->find(instruction) != reductions_->end()) {
1392 // Deal with vector restrictions.
1393 if (HasVectorRestrictions(restrictions, kNoReduction)) {
1394 return false;
1395 }
1396 // Accept a reduction.
1397 if (generate_code) {
1398 GenerateVecReductionPhi(instruction->AsPhi());
1399 }
1400 return true;
1401 }
1402 // TODO: accept right-hand-side induction?
1403 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001404 } else if (instruction->IsTypeConversion()) {
1405 // Accept particular type conversions.
1406 HTypeConversion* conversion = instruction->AsTypeConversion();
1407 HInstruction* opa = conversion->InputAt(0);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001408 DataType::Type from = conversion->GetInputType();
1409 DataType::Type to = conversion->GetResultType();
1410 if (DataType::IsIntegralType(from) && DataType::IsIntegralType(to)) {
Aart Bik38a3f212017-10-20 17:02:21 -07001411 uint32_t size_vec = DataType::Size(type);
1412 uint32_t size_from = DataType::Size(from);
1413 uint32_t size_to = DataType::Size(to);
Aart Bikdbbac8f2017-09-01 13:06:08 -07001414 // Accept an integral conversion
1415 // (1a) narrowing into vector type, "wider" operations cannot bring in higher order bits, or
1416 // (1b) widening from at least vector type, and
1417 // (2) vectorizable operand.
1418 if ((size_to < size_from &&
1419 size_to == size_vec &&
1420 VectorizeUse(node, opa, generate_code, type, restrictions | kNoHiBits)) ||
1421 (size_to >= size_from &&
1422 size_from >= size_vec &&
Aart Bik4d1a9d42017-10-19 14:40:55 -07001423 VectorizeUse(node, opa, generate_code, type, restrictions))) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001424 if (generate_code) {
1425 if (vector_mode_ == kVector) {
1426 vector_map_->Put(instruction, vector_map_->Get(opa)); // operand pass-through
1427 } else {
1428 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1429 }
1430 }
1431 return true;
1432 }
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001433 } else if (to == DataType::Type::kFloat32 && from == DataType::Type::kInt32) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001434 DCHECK_EQ(to, type);
1435 // Accept int to float conversion for
1436 // (1) supported int,
1437 // (2) vectorizable operand.
1438 if (TrySetVectorType(from, &restrictions) &&
1439 VectorizeUse(node, opa, generate_code, from, restrictions)) {
1440 if (generate_code) {
1441 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1442 }
1443 return true;
1444 }
1445 }
1446 return false;
1447 } else if (instruction->IsNeg() || instruction->IsNot() || instruction->IsBooleanNot()) {
1448 // Accept unary operator for vectorizable operand.
1449 HInstruction* opa = instruction->InputAt(0);
1450 if (VectorizeUse(node, opa, generate_code, type, restrictions)) {
1451 if (generate_code) {
1452 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1453 }
1454 return true;
1455 }
1456 } else if (instruction->IsAdd() || instruction->IsSub() ||
1457 instruction->IsMul() || instruction->IsDiv() ||
1458 instruction->IsAnd() || instruction->IsOr() || instruction->IsXor()) {
1459 // Deal with vector restrictions.
1460 if ((instruction->IsMul() && HasVectorRestrictions(restrictions, kNoMul)) ||
1461 (instruction->IsDiv() && HasVectorRestrictions(restrictions, kNoDiv))) {
1462 return false;
1463 }
1464 // Accept binary operator for vectorizable operands.
1465 HInstruction* opa = instruction->InputAt(0);
1466 HInstruction* opb = instruction->InputAt(1);
1467 if (VectorizeUse(node, opa, generate_code, type, restrictions) &&
1468 VectorizeUse(node, opb, generate_code, type, restrictions)) {
1469 if (generate_code) {
1470 GenerateVecOp(instruction, vector_map_->Get(opa), vector_map_->Get(opb), type);
1471 }
1472 return true;
1473 }
1474 } else if (instruction->IsShl() || instruction->IsShr() || instruction->IsUShr()) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001475 // Recognize halving add idiom.
Aart Bikf3e61ee2017-04-12 17:09:20 -07001476 if (VectorizeHalvingAddIdiom(node, instruction, generate_code, type, restrictions)) {
1477 return true;
1478 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001479 // Deal with vector restrictions.
Aart Bik304c8a52017-05-23 11:01:13 -07001480 HInstruction* opa = instruction->InputAt(0);
1481 HInstruction* opb = instruction->InputAt(1);
1482 HInstruction* r = opa;
1483 bool is_unsigned = false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001484 if ((HasVectorRestrictions(restrictions, kNoShift)) ||
1485 (instruction->IsShr() && HasVectorRestrictions(restrictions, kNoShr))) {
1486 return false; // unsupported instruction
Aart Bik304c8a52017-05-23 11:01:13 -07001487 } else if (HasVectorRestrictions(restrictions, kNoHiBits)) {
1488 // Shifts right need extra care to account for higher order bits.
1489 // TODO: less likely shr/unsigned and ushr/signed can by flipping signess.
1490 if (instruction->IsShr() &&
1491 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || is_unsigned)) {
1492 return false; // reject, unless all operands are sign-extension narrower
1493 } else if (instruction->IsUShr() &&
1494 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || !is_unsigned)) {
1495 return false; // reject, unless all operands are zero-extension narrower
1496 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001497 }
1498 // Accept shift operator for vectorizable/invariant operands.
1499 // TODO: accept symbolic, albeit loop invariant shift factors.
Aart Bik304c8a52017-05-23 11:01:13 -07001500 DCHECK(r != nullptr);
1501 if (generate_code && vector_mode_ != kVector) { // de-idiom
1502 r = opa;
1503 }
Aart Bik50e20d52017-05-05 14:07:29 -07001504 int64_t distance = 0;
Aart Bik304c8a52017-05-23 11:01:13 -07001505 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
Aart Bik50e20d52017-05-05 14:07:29 -07001506 IsInt64AndGet(opb, /*out*/ &distance)) {
Aart Bik65ffd8e2017-05-01 16:50:45 -07001507 // Restrict shift distance to packed data type width.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001508 int64_t max_distance = DataType::Size(type) * 8;
Aart Bik65ffd8e2017-05-01 16:50:45 -07001509 if (0 <= distance && distance < max_distance) {
1510 if (generate_code) {
Aart Bik304c8a52017-05-23 11:01:13 -07001511 GenerateVecOp(instruction, vector_map_->Get(r), opb, type);
Aart Bik65ffd8e2017-05-01 16:50:45 -07001512 }
1513 return true;
Aart Bikf8f5a162017-02-06 15:35:29 -08001514 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001515 }
Aart Bik3b2a5952018-03-05 13:55:28 -08001516 } else if (instruction->IsAbs()) {
1517 // Deal with vector restrictions.
1518 HInstruction* opa = instruction->InputAt(0);
1519 HInstruction* r = opa;
1520 bool is_unsigned = false;
1521 if (HasVectorRestrictions(restrictions, kNoAbs)) {
1522 return false;
1523 } else if (HasVectorRestrictions(restrictions, kNoHiBits) &&
1524 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || is_unsigned)) {
1525 return false; // reject, unless operand is sign-extension narrower
1526 }
1527 // Accept ABS(x) for vectorizable operand.
1528 DCHECK(r != nullptr);
1529 if (generate_code && vector_mode_ != kVector) { // de-idiom
1530 r = opa;
1531 }
1532 if (VectorizeUse(node, r, generate_code, type, restrictions)) {
1533 if (generate_code) {
1534 GenerateVecOp(instruction,
1535 vector_map_->Get(r),
1536 nullptr,
1537 HVecOperation::ToProperType(type, is_unsigned));
1538 }
1539 return true;
1540 }
Aart Bik281c6812016-08-26 11:31:48 -07001541 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08001542 return false;
Aart Bik281c6812016-08-26 11:31:48 -07001543}
1544
Aart Bik38a3f212017-10-20 17:02:21 -07001545uint32_t HLoopOptimization::GetVectorSizeInBytes() {
Vladimir Markoa0431112018-06-25 09:32:54 +01001546 switch (compiler_options_->GetInstructionSet()) {
Vladimir Marko33bff252017-11-01 14:35:42 +00001547 case InstructionSet::kArm:
1548 case InstructionSet::kThumb2:
Aart Bik38a3f212017-10-20 17:02:21 -07001549 return 8; // 64-bit SIMD
1550 default:
1551 return 16; // 128-bit SIMD
1552 }
1553}
1554
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001555bool HLoopOptimization::TrySetVectorType(DataType::Type type, uint64_t* restrictions) {
Vladimir Markoa0431112018-06-25 09:32:54 +01001556 const InstructionSetFeatures* features = compiler_options_->GetInstructionSetFeatures();
1557 switch (compiler_options_->GetInstructionSet()) {
Vladimir Marko33bff252017-11-01 14:35:42 +00001558 case InstructionSet::kArm:
1559 case InstructionSet::kThumb2:
Artem Serov8f7c4102017-06-21 11:21:37 +01001560 // Allow vectorization for all ARM devices, because Android assumes that
Aart Bikb29f6842017-07-28 15:58:41 -07001561 // ARM 32-bit always supports advanced SIMD (64-bit SIMD).
Artem Serov8f7c4102017-06-21 11:21:37 +01001562 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001563 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001564 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001565 case DataType::Type::kInt8:
Artem Serovaaac0e32018-08-07 00:52:22 +01001566 *restrictions |= kNoDiv | kNoReduction | kNoDotProd;
Artem Serov8f7c4102017-06-21 11:21:37 +01001567 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001568 case DataType::Type::kUint16:
1569 case DataType::Type::kInt16:
Artem Serovaaac0e32018-08-07 00:52:22 +01001570 *restrictions |= kNoDiv | kNoStringCharAt | kNoReduction | kNoDotProd;
Artem Serov8f7c4102017-06-21 11:21:37 +01001571 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001572 case DataType::Type::kInt32:
Artem Serov6e9b1372017-10-05 16:48:30 +01001573 *restrictions |= kNoDiv | kNoWideSAD;
Artem Serov8f7c4102017-06-21 11:21:37 +01001574 return TrySetVectorLength(2);
1575 default:
1576 break;
1577 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001578 return false;
Vladimir Marko33bff252017-11-01 14:35:42 +00001579 case InstructionSet::kArm64:
Aart Bikf8f5a162017-02-06 15:35:29 -08001580 // Allow vectorization for all ARM devices, because Android assumes that
Aart Bikb29f6842017-07-28 15:58:41 -07001581 // ARMv8 AArch64 always supports advanced SIMD (128-bit SIMD).
Aart Bikf8f5a162017-02-06 15:35:29 -08001582 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001583 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001584 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001585 case DataType::Type::kInt8:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001586 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +01001587 return TrySetVectorLength(16);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001588 case DataType::Type::kUint16:
1589 case DataType::Type::kInt16:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001590 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +01001591 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001592 case DataType::Type::kInt32:
Aart Bikf8f5a162017-02-06 15:35:29 -08001593 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +01001594 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001595 case DataType::Type::kInt64:
Aart Bik3f08e9b2018-05-01 13:42:03 -07001596 *restrictions |= kNoDiv | kNoMul;
Aart Bikf8f5a162017-02-06 15:35:29 -08001597 return TrySetVectorLength(2);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001598 case DataType::Type::kFloat32:
Aart Bik0148de42017-09-05 09:25:01 -07001599 *restrictions |= kNoReduction;
Artem Serovd4bccf12017-04-03 18:47:32 +01001600 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001601 case DataType::Type::kFloat64:
Aart Bik0148de42017-09-05 09:25:01 -07001602 *restrictions |= kNoReduction;
Aart Bikf8f5a162017-02-06 15:35:29 -08001603 return TrySetVectorLength(2);
1604 default:
1605 return false;
1606 }
Vladimir Marko33bff252017-11-01 14:35:42 +00001607 case InstructionSet::kX86:
1608 case InstructionSet::kX86_64:
Aart Bikb29f6842017-07-28 15:58:41 -07001609 // Allow vectorization for SSE4.1-enabled X86 devices only (128-bit SIMD).
Aart Bikf8f5a162017-02-06 15:35:29 -08001610 if (features->AsX86InstructionSetFeatures()->HasSSE4_1()) {
1611 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001612 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001613 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001614 case DataType::Type::kInt8:
Artem Serovaaac0e32018-08-07 00:52:22 +01001615 *restrictions |= kNoMul |
1616 kNoDiv |
1617 kNoShift |
1618 kNoAbs |
1619 kNoSignedHAdd |
1620 kNoUnroundedHAdd |
1621 kNoSAD |
1622 kNoDotProd;
Aart Bikf8f5a162017-02-06 15:35:29 -08001623 return TrySetVectorLength(16);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001624 case DataType::Type::kUint16:
Alex Light43f2f752019-12-04 17:48:45 +00001625 *restrictions |= kNoDiv |
1626 kNoAbs |
1627 kNoSignedHAdd |
1628 kNoUnroundedHAdd |
1629 kNoSAD |
1630 kNoDotProd;
1631 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001632 case DataType::Type::kInt16:
Artem Serovaaac0e32018-08-07 00:52:22 +01001633 *restrictions |= kNoDiv |
1634 kNoAbs |
1635 kNoSignedHAdd |
1636 kNoUnroundedHAdd |
Alex Light43f2f752019-12-04 17:48:45 +00001637 kNoSAD;
Aart Bikf8f5a162017-02-06 15:35:29 -08001638 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001639 case DataType::Type::kInt32:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001640 *restrictions |= kNoDiv | kNoSAD;
Aart Bikf8f5a162017-02-06 15:35:29 -08001641 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001642 case DataType::Type::kInt64:
Aart Bik3f08e9b2018-05-01 13:42:03 -07001643 *restrictions |= kNoMul | kNoDiv | kNoShr | kNoAbs | kNoSAD;
Aart Bikf8f5a162017-02-06 15:35:29 -08001644 return TrySetVectorLength(2);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001645 case DataType::Type::kFloat32:
Aart Bik3f08e9b2018-05-01 13:42:03 -07001646 *restrictions |= kNoReduction;
Aart Bikf8f5a162017-02-06 15:35:29 -08001647 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001648 case DataType::Type::kFloat64:
Aart Bik3f08e9b2018-05-01 13:42:03 -07001649 *restrictions |= kNoReduction;
Aart Bikf8f5a162017-02-06 15:35:29 -08001650 return TrySetVectorLength(2);
1651 default:
1652 break;
1653 } // switch type
1654 }
1655 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001656 default:
1657 return false;
1658 } // switch instruction set
1659}
1660
1661bool HLoopOptimization::TrySetVectorLength(uint32_t length) {
1662 DCHECK(IsPowerOfTwo(length) && length >= 2u);
1663 // First time set?
1664 if (vector_length_ == 0) {
1665 vector_length_ = length;
1666 }
1667 // Different types are acceptable within a loop-body, as long as all the corresponding vector
1668 // lengths match exactly to obtain a uniform traversal through the vector iteration space
1669 // (idiomatic exceptions to this rule can be handled by further unrolling sub-expressions).
1670 return vector_length_ == length;
1671}
1672
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001673void HLoopOptimization::GenerateVecInv(HInstruction* org, DataType::Type type) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001674 if (vector_map_->find(org) == vector_map_->end()) {
1675 // In scalar code, just use a self pass-through for scalar invariants
1676 // (viz. expression remains itself).
1677 if (vector_mode_ == kSequential) {
1678 vector_map_->Put(org, org);
1679 return;
1680 }
1681 // In vector code, explicit scalar expansion is needed.
Aart Bik0148de42017-09-05 09:25:01 -07001682 HInstruction* vector = nullptr;
1683 auto it = vector_permanent_map_->find(org);
1684 if (it != vector_permanent_map_->end()) {
1685 vector = it->second; // reuse during unrolling
1686 } else {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001687 // Generates ReplicateScalar( (optional_type_conv) org ).
1688 HInstruction* input = org;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001689 DataType::Type input_type = input->GetType();
1690 if (type != input_type && (type == DataType::Type::kInt64 ||
1691 input_type == DataType::Type::kInt64)) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001692 input = Insert(vector_preheader_,
1693 new (global_allocator_) HTypeConversion(type, input, kNoDexPc));
1694 }
1695 vector = new (global_allocator_)
Aart Bik46b6dbc2017-10-03 11:37:37 -07001696 HVecReplicateScalar(global_allocator_, input, type, vector_length_, kNoDexPc);
Aart Bik0148de42017-09-05 09:25:01 -07001697 vector_permanent_map_->Put(org, Insert(vector_preheader_, vector));
1698 }
1699 vector_map_->Put(org, vector);
Aart Bikf8f5a162017-02-06 15:35:29 -08001700 }
1701}
1702
1703void HLoopOptimization::GenerateVecSub(HInstruction* org, HInstruction* offset) {
1704 if (vector_map_->find(org) == vector_map_->end()) {
Aart Bik14a68b42017-06-08 14:06:58 -07001705 HInstruction* subscript = vector_index_;
Aart Bik37dc4df2017-06-28 14:08:00 -07001706 int64_t value = 0;
1707 if (!IsInt64AndGet(offset, &value) || value != 0) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001708 subscript = new (global_allocator_) HAdd(DataType::Type::kInt32, subscript, offset);
Aart Bikf8f5a162017-02-06 15:35:29 -08001709 if (org->IsPhi()) {
1710 Insert(vector_body_, subscript); // lacks layout placeholder
1711 }
1712 }
1713 vector_map_->Put(org, subscript);
1714 }
1715}
1716
1717void HLoopOptimization::GenerateVecMem(HInstruction* org,
1718 HInstruction* opa,
1719 HInstruction* opb,
Aart Bik14a68b42017-06-08 14:06:58 -07001720 HInstruction* offset,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001721 DataType::Type type) {
Aart Bik46b6dbc2017-10-03 11:37:37 -07001722 uint32_t dex_pc = org->GetDexPc();
Aart Bikf8f5a162017-02-06 15:35:29 -08001723 HInstruction* vector = nullptr;
1724 if (vector_mode_ == kVector) {
1725 // Vector store or load.
Aart Bik38a3f212017-10-20 17:02:21 -07001726 bool is_string_char_at = false;
Aart Bik14a68b42017-06-08 14:06:58 -07001727 HInstruction* base = org->InputAt(0);
Aart Bikf8f5a162017-02-06 15:35:29 -08001728 if (opb != nullptr) {
1729 vector = new (global_allocator_) HVecStore(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001730 global_allocator_, base, opa, opb, type, org->GetSideEffects(), vector_length_, dex_pc);
Aart Bikf8f5a162017-02-06 15:35:29 -08001731 } else {
Aart Bik38a3f212017-10-20 17:02:21 -07001732 is_string_char_at = org->AsArrayGet()->IsStringCharAt();
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001733 vector = new (global_allocator_) HVecLoad(global_allocator_,
1734 base,
1735 opa,
1736 type,
1737 org->GetSideEffects(),
1738 vector_length_,
Aart Bik46b6dbc2017-10-03 11:37:37 -07001739 is_string_char_at,
1740 dex_pc);
Aart Bik14a68b42017-06-08 14:06:58 -07001741 }
Aart Bik38a3f212017-10-20 17:02:21 -07001742 // Known (forced/adjusted/original) alignment?
1743 if (vector_dynamic_peeling_candidate_ != nullptr) {
1744 if (vector_dynamic_peeling_candidate_->offset == offset && // TODO: diffs too?
1745 DataType::Size(vector_dynamic_peeling_candidate_->type) == DataType::Size(type) &&
1746 vector_dynamic_peeling_candidate_->is_string_char_at == is_string_char_at) {
1747 vector->AsVecMemoryOperation()->SetAlignment( // forced
1748 Alignment(GetVectorSizeInBytes(), 0));
1749 }
1750 } else {
1751 vector->AsVecMemoryOperation()->SetAlignment( // adjusted/original
1752 ComputeAlignment(offset, type, is_string_char_at, vector_static_peeling_factor_));
Aart Bikf8f5a162017-02-06 15:35:29 -08001753 }
1754 } else {
1755 // Scalar store or load.
1756 DCHECK(vector_mode_ == kSequential);
1757 if (opb != nullptr) {
Aart Bik4d1a9d42017-10-19 14:40:55 -07001758 DataType::Type component_type = org->AsArraySet()->GetComponentType();
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001759 vector = new (global_allocator_) HArraySet(
Aart Bik4d1a9d42017-10-19 14:40:55 -07001760 org->InputAt(0), opa, opb, component_type, org->GetSideEffects(), dex_pc);
Aart Bikf8f5a162017-02-06 15:35:29 -08001761 } else {
Aart Bikdb14fcf2017-04-25 15:53:58 -07001762 bool is_string_char_at = org->AsArrayGet()->IsStringCharAt();
1763 vector = new (global_allocator_) HArrayGet(
Aart Bik4d1a9d42017-10-19 14:40:55 -07001764 org->InputAt(0), opa, org->GetType(), org->GetSideEffects(), dex_pc, is_string_char_at);
Aart Bikf8f5a162017-02-06 15:35:29 -08001765 }
1766 }
1767 vector_map_->Put(org, vector);
1768}
1769
Aart Bik0148de42017-09-05 09:25:01 -07001770void HLoopOptimization::GenerateVecReductionPhi(HPhi* phi) {
1771 DCHECK(reductions_->find(phi) != reductions_->end());
1772 DCHECK(reductions_->Get(phi->InputAt(1)) == phi);
1773 HInstruction* vector = nullptr;
1774 if (vector_mode_ == kSequential) {
1775 HPhi* new_phi = new (global_allocator_) HPhi(
1776 global_allocator_, kNoRegNumber, 0, phi->GetType());
1777 vector_header_->AddPhi(new_phi);
1778 vector = new_phi;
1779 } else {
1780 // Link vector reduction back to prior unrolled update, or a first phi.
1781 auto it = vector_permanent_map_->find(phi);
1782 if (it != vector_permanent_map_->end()) {
1783 vector = it->second;
1784 } else {
1785 HPhi* new_phi = new (global_allocator_) HPhi(
1786 global_allocator_, kNoRegNumber, 0, HVecOperation::kSIMDType);
1787 vector_header_->AddPhi(new_phi);
1788 vector = new_phi;
1789 }
1790 }
1791 vector_map_->Put(phi, vector);
1792}
1793
1794void HLoopOptimization::GenerateVecReductionPhiInputs(HPhi* phi, HInstruction* reduction) {
1795 HInstruction* new_phi = vector_map_->Get(phi);
1796 HInstruction* new_init = reductions_->Get(phi);
1797 HInstruction* new_red = vector_map_->Get(reduction);
1798 // Link unrolled vector loop back to new phi.
1799 for (; !new_phi->IsPhi(); new_phi = vector_permanent_map_->Get(new_phi)) {
1800 DCHECK(new_phi->IsVecOperation());
1801 }
1802 // Prepare the new initialization.
1803 if (vector_mode_ == kVector) {
Goran Jakovljevic89b8df02017-10-13 08:33:17 +02001804 // Generate a [initial, 0, .., 0] vector for add or
1805 // a [initial, initial, .., initial] vector for min/max.
Aart Bikdbbac8f2017-09-01 13:06:08 -07001806 HVecOperation* red_vector = new_red->AsVecOperation();
Goran Jakovljevic89b8df02017-10-13 08:33:17 +02001807 HVecReduce::ReductionKind kind = GetReductionKind(red_vector);
Aart Bik38a3f212017-10-20 17:02:21 -07001808 uint32_t vector_length = red_vector->GetVectorLength();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001809 DataType::Type type = red_vector->GetPackedType();
Goran Jakovljevic89b8df02017-10-13 08:33:17 +02001810 if (kind == HVecReduce::ReductionKind::kSum) {
1811 new_init = Insert(vector_preheader_,
1812 new (global_allocator_) HVecSetScalars(global_allocator_,
1813 &new_init,
1814 type,
1815 vector_length,
1816 1,
1817 kNoDexPc));
1818 } else {
1819 new_init = Insert(vector_preheader_,
1820 new (global_allocator_) HVecReplicateScalar(global_allocator_,
1821 new_init,
1822 type,
1823 vector_length,
1824 kNoDexPc));
1825 }
Aart Bik0148de42017-09-05 09:25:01 -07001826 } else {
1827 new_init = ReduceAndExtractIfNeeded(new_init);
1828 }
1829 // Set the phi inputs.
1830 DCHECK(new_phi->IsPhi());
1831 new_phi->AsPhi()->AddInput(new_init);
1832 new_phi->AsPhi()->AddInput(new_red);
1833 // New feed value for next phi (safe mutation in iteration).
1834 reductions_->find(phi)->second = new_phi;
1835}
1836
1837HInstruction* HLoopOptimization::ReduceAndExtractIfNeeded(HInstruction* instruction) {
1838 if (instruction->IsPhi()) {
1839 HInstruction* input = instruction->InputAt(1);
Aart Bik2dd7b672017-12-07 11:11:22 -08001840 if (HVecOperation::ReturnsSIMDValue(input)) {
1841 DCHECK(!input->IsPhi());
Aart Bikdbbac8f2017-09-01 13:06:08 -07001842 HVecOperation* input_vector = input->AsVecOperation();
Aart Bik38a3f212017-10-20 17:02:21 -07001843 uint32_t vector_length = input_vector->GetVectorLength();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001844 DataType::Type type = input_vector->GetPackedType();
Aart Bikdbbac8f2017-09-01 13:06:08 -07001845 HVecReduce::ReductionKind kind = GetReductionKind(input_vector);
Aart Bik0148de42017-09-05 09:25:01 -07001846 HBasicBlock* exit = instruction->GetBlock()->GetSuccessors()[0];
1847 // Generate a vector reduction and scalar extract
1848 // x = REDUCE( [x_1, .., x_n] )
1849 // y = x_1
1850 // along the exit of the defining loop.
Aart Bik0148de42017-09-05 09:25:01 -07001851 HInstruction* reduce = new (global_allocator_) HVecReduce(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001852 global_allocator_, instruction, type, vector_length, kind, kNoDexPc);
Aart Bik0148de42017-09-05 09:25:01 -07001853 exit->InsertInstructionBefore(reduce, exit->GetFirstInstruction());
1854 instruction = new (global_allocator_) HVecExtractScalar(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001855 global_allocator_, reduce, type, vector_length, 0, kNoDexPc);
Aart Bik0148de42017-09-05 09:25:01 -07001856 exit->InsertInstructionAfter(instruction, reduce);
1857 }
1858 }
1859 return instruction;
1860}
1861
Aart Bikf8f5a162017-02-06 15:35:29 -08001862#define GENERATE_VEC(x, y) \
1863 if (vector_mode_ == kVector) { \
1864 vector = (x); \
1865 } else { \
1866 DCHECK(vector_mode_ == kSequential); \
1867 vector = (y); \
1868 } \
1869 break;
1870
1871void HLoopOptimization::GenerateVecOp(HInstruction* org,
1872 HInstruction* opa,
1873 HInstruction* opb,
Aart Bik3f08e9b2018-05-01 13:42:03 -07001874 DataType::Type type) {
Aart Bik46b6dbc2017-10-03 11:37:37 -07001875 uint32_t dex_pc = org->GetDexPc();
Aart Bikf8f5a162017-02-06 15:35:29 -08001876 HInstruction* vector = nullptr;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001877 DataType::Type org_type = org->GetType();
Aart Bikf8f5a162017-02-06 15:35:29 -08001878 switch (org->GetKind()) {
1879 case HInstruction::kNeg:
1880 DCHECK(opb == nullptr);
1881 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001882 new (global_allocator_) HVecNeg(global_allocator_, opa, type, vector_length_, dex_pc),
1883 new (global_allocator_) HNeg(org_type, opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001884 case HInstruction::kNot:
1885 DCHECK(opb == nullptr);
1886 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001887 new (global_allocator_) HVecNot(global_allocator_, opa, type, vector_length_, dex_pc),
1888 new (global_allocator_) HNot(org_type, opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001889 case HInstruction::kBooleanNot:
1890 DCHECK(opb == nullptr);
1891 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001892 new (global_allocator_) HVecNot(global_allocator_, opa, type, vector_length_, dex_pc),
1893 new (global_allocator_) HBooleanNot(opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001894 case HInstruction::kTypeConversion:
1895 DCHECK(opb == nullptr);
1896 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001897 new (global_allocator_) HVecCnv(global_allocator_, opa, type, vector_length_, dex_pc),
1898 new (global_allocator_) HTypeConversion(org_type, opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001899 case HInstruction::kAdd:
1900 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001901 new (global_allocator_) HVecAdd(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1902 new (global_allocator_) HAdd(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001903 case HInstruction::kSub:
1904 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001905 new (global_allocator_) HVecSub(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1906 new (global_allocator_) HSub(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001907 case HInstruction::kMul:
1908 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001909 new (global_allocator_) HVecMul(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1910 new (global_allocator_) HMul(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001911 case HInstruction::kDiv:
1912 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001913 new (global_allocator_) HVecDiv(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1914 new (global_allocator_) HDiv(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001915 case HInstruction::kAnd:
1916 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001917 new (global_allocator_) HVecAnd(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1918 new (global_allocator_) HAnd(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001919 case HInstruction::kOr:
1920 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001921 new (global_allocator_) HVecOr(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1922 new (global_allocator_) HOr(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001923 case HInstruction::kXor:
1924 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001925 new (global_allocator_) HVecXor(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1926 new (global_allocator_) HXor(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001927 case HInstruction::kShl:
1928 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001929 new (global_allocator_) HVecShl(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1930 new (global_allocator_) HShl(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001931 case HInstruction::kShr:
1932 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001933 new (global_allocator_) HVecShr(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1934 new (global_allocator_) HShr(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001935 case HInstruction::kUShr:
1936 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001937 new (global_allocator_) HVecUShr(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1938 new (global_allocator_) HUShr(org_type, opa, opb, dex_pc));
Aart Bik3b2a5952018-03-05 13:55:28 -08001939 case HInstruction::kAbs:
1940 DCHECK(opb == nullptr);
1941 GENERATE_VEC(
1942 new (global_allocator_) HVecAbs(global_allocator_, opa, type, vector_length_, dex_pc),
1943 new (global_allocator_) HAbs(org_type, opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001944 default:
1945 break;
1946 } // switch
1947 CHECK(vector != nullptr) << "Unsupported SIMD operator";
1948 vector_map_->Put(org, vector);
1949}
1950
1951#undef GENERATE_VEC
1952
1953//
Aart Bikf3e61ee2017-04-12 17:09:20 -07001954// Vectorization idioms.
1955//
1956
1957// Method recognizes the following idioms:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001958// rounding halving add (a + b + 1) >> 1 for unsigned/signed operands a, b
1959// truncated halving add (a + b) >> 1 for unsigned/signed operands a, b
Aart Bikf3e61ee2017-04-12 17:09:20 -07001960// Provided that the operands are promoted to a wider form to do the arithmetic and
1961// then cast back to narrower form, the idioms can be mapped into efficient SIMD
1962// implementation that operates directly in narrower form (plus one extra bit).
1963// TODO: current version recognizes implicit byte/short/char widening only;
1964// explicit widening from int to long could be added later.
1965bool HLoopOptimization::VectorizeHalvingAddIdiom(LoopNode* node,
1966 HInstruction* instruction,
1967 bool generate_code,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001968 DataType::Type type,
Aart Bikf3e61ee2017-04-12 17:09:20 -07001969 uint64_t restrictions) {
1970 // Test for top level arithmetic shift right x >> 1 or logical shift right x >>> 1
Aart Bik304c8a52017-05-23 11:01:13 -07001971 // (note whether the sign bit in wider precision is shifted in has no effect
Aart Bikf3e61ee2017-04-12 17:09:20 -07001972 // on the narrow precision computed by the idiom).
Aart Bikf3e61ee2017-04-12 17:09:20 -07001973 if ((instruction->IsShr() ||
1974 instruction->IsUShr()) &&
Aart Bik0148de42017-09-05 09:25:01 -07001975 IsInt64Value(instruction->InputAt(1), 1)) {
Aart Bik5f805002017-05-16 16:42:41 -07001976 // Test for (a + b + c) >> 1 for optional constant c.
1977 HInstruction* a = nullptr;
1978 HInstruction* b = nullptr;
1979 int64_t c = 0;
Nicolas Geoffraya3e23262018-03-28 11:15:12 +00001980 if (IsAddConst2(graph_, instruction->InputAt(0), /*out*/ &a, /*out*/ &b, /*out*/ &c)) {
Aart Bik5f805002017-05-16 16:42:41 -07001981 // Accept c == 1 (rounded) or c == 0 (not rounded).
1982 bool is_rounded = false;
1983 if (c == 1) {
1984 is_rounded = true;
1985 } else if (c != 0) {
1986 return false;
1987 }
1988 // Accept consistent zero or sign extension on operands a and b.
Aart Bikf3e61ee2017-04-12 17:09:20 -07001989 HInstruction* r = nullptr;
1990 HInstruction* s = nullptr;
1991 bool is_unsigned = false;
Aart Bik304c8a52017-05-23 11:01:13 -07001992 if (!IsNarrowerOperands(a, b, type, &r, &s, &is_unsigned)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -07001993 return false;
1994 }
1995 // Deal with vector restrictions.
1996 if ((!is_unsigned && HasVectorRestrictions(restrictions, kNoSignedHAdd)) ||
1997 (!is_rounded && HasVectorRestrictions(restrictions, kNoUnroundedHAdd))) {
1998 return false;
1999 }
2000 // Accept recognized halving add for vectorizable operands. Vectorized code uses the
2001 // shorthand idiomatic operation. Sequential code uses the original scalar expressions.
Nicolas Geoffraya3e23262018-03-28 11:15:12 +00002002 DCHECK(r != nullptr && s != nullptr);
Aart Bik304c8a52017-05-23 11:01:13 -07002003 if (generate_code && vector_mode_ != kVector) { // de-idiom
2004 r = instruction->InputAt(0);
2005 s = instruction->InputAt(1);
2006 }
Aart Bikf3e61ee2017-04-12 17:09:20 -07002007 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
2008 VectorizeUse(node, s, generate_code, type, restrictions)) {
2009 if (generate_code) {
2010 if (vector_mode_ == kVector) {
2011 vector_map_->Put(instruction, new (global_allocator_) HVecHalvingAdd(
2012 global_allocator_,
2013 vector_map_->Get(r),
2014 vector_map_->Get(s),
Aart Bik66c158e2018-01-31 12:55:04 -08002015 HVecOperation::ToProperType(type, is_unsigned),
Aart Bikf3e61ee2017-04-12 17:09:20 -07002016 vector_length_,
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01002017 is_rounded,
Aart Bik46b6dbc2017-10-03 11:37:37 -07002018 kNoDexPc));
Aart Bik21b85922017-09-06 13:29:16 -07002019 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorizedIdiom);
Aart Bikf3e61ee2017-04-12 17:09:20 -07002020 } else {
Aart Bik304c8a52017-05-23 11:01:13 -07002021 GenerateVecOp(instruction, vector_map_->Get(r), vector_map_->Get(s), type);
Aart Bikf3e61ee2017-04-12 17:09:20 -07002022 }
2023 }
2024 return true;
2025 }
2026 }
2027 }
2028 return false;
2029}
2030
Aart Bikdbbac8f2017-09-01 13:06:08 -07002031// Method recognizes the following idiom:
2032// q += ABS(a - b) for signed operands a, b
2033// Provided that the operands have the same type or are promoted to a wider form.
2034// Since this may involve a vector length change, the idiom is handled by going directly
2035// to a sad-accumulate node (rather than relying combining finer grained nodes later).
2036// TODO: unsigned SAD too?
2037bool HLoopOptimization::VectorizeSADIdiom(LoopNode* node,
2038 HInstruction* instruction,
2039 bool generate_code,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002040 DataType::Type reduction_type,
Aart Bikdbbac8f2017-09-01 13:06:08 -07002041 uint64_t restrictions) {
2042 // Filter integral "q += ABS(a - b);" reduction, where ABS and SUB
2043 // are done in the same precision (either int or long).
2044 if (!instruction->IsAdd() ||
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002045 (reduction_type != DataType::Type::kInt32 && reduction_type != DataType::Type::kInt64)) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07002046 return false;
2047 }
Artem Serove521eb02020-02-27 18:51:24 +00002048 HInstruction* acc = instruction->InputAt(0);
2049 HInstruction* abs = instruction->InputAt(1);
Aart Bikdbbac8f2017-09-01 13:06:08 -07002050 HInstruction* a = nullptr;
2051 HInstruction* b = nullptr;
Artem Serove521eb02020-02-27 18:51:24 +00002052 if (abs->IsAbs() &&
2053 abs->GetType() == reduction_type &&
2054 IsSubConst2(graph_, abs->InputAt(0), /*out*/ &a, /*out*/ &b)) {
Nicolas Geoffraya3e23262018-03-28 11:15:12 +00002055 DCHECK(a != nullptr && b != nullptr);
2056 } else {
Aart Bikdbbac8f2017-09-01 13:06:08 -07002057 return false;
2058 }
2059 // Accept same-type or consistent sign extension for narrower-type on operands a and b.
2060 // The same-type or narrower operands are called r (a or lower) and s (b or lower).
Aart Bikdf011c32017-09-28 12:53:04 -07002061 // We inspect the operands carefully to pick the most suited type.
Aart Bikdbbac8f2017-09-01 13:06:08 -07002062 HInstruction* r = a;
2063 HInstruction* s = b;
2064 bool is_unsigned = false;
Artem Serovaaac0e32018-08-07 00:52:22 +01002065 DataType::Type sub_type = GetNarrowerType(a, b);
Aart Bikdbbac8f2017-09-01 13:06:08 -07002066 if (reduction_type != sub_type &&
2067 (!IsNarrowerOperands(a, b, sub_type, &r, &s, &is_unsigned) || is_unsigned)) {
2068 return false;
2069 }
2070 // Try same/narrower type and deal with vector restrictions.
Artem Serov6e9b1372017-10-05 16:48:30 +01002071 if (!TrySetVectorType(sub_type, &restrictions) ||
2072 HasVectorRestrictions(restrictions, kNoSAD) ||
2073 (reduction_type != sub_type && HasVectorRestrictions(restrictions, kNoWideSAD))) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07002074 return false;
2075 }
2076 // Accept SAD idiom for vectorizable operands. Vectorized code uses the shorthand
2077 // idiomatic operation. Sequential code uses the original scalar expressions.
Nicolas Geoffraya3e23262018-03-28 11:15:12 +00002078 DCHECK(r != nullptr && s != nullptr);
Aart Bikdbbac8f2017-09-01 13:06:08 -07002079 if (generate_code && vector_mode_ != kVector) { // de-idiom
Artem Serove521eb02020-02-27 18:51:24 +00002080 r = s = abs->InputAt(0);
Aart Bikdbbac8f2017-09-01 13:06:08 -07002081 }
Artem Serove521eb02020-02-27 18:51:24 +00002082 if (VectorizeUse(node, acc, generate_code, sub_type, restrictions) &&
Aart Bikdbbac8f2017-09-01 13:06:08 -07002083 VectorizeUse(node, r, generate_code, sub_type, restrictions) &&
2084 VectorizeUse(node, s, generate_code, sub_type, restrictions)) {
2085 if (generate_code) {
2086 if (vector_mode_ == kVector) {
2087 vector_map_->Put(instruction, new (global_allocator_) HVecSADAccumulate(
2088 global_allocator_,
Artem Serove521eb02020-02-27 18:51:24 +00002089 vector_map_->Get(acc),
Aart Bikdbbac8f2017-09-01 13:06:08 -07002090 vector_map_->Get(r),
2091 vector_map_->Get(s),
Aart Bik3b2a5952018-03-05 13:55:28 -08002092 HVecOperation::ToProperType(reduction_type, is_unsigned),
Aart Bik46b6dbc2017-10-03 11:37:37 -07002093 GetOtherVL(reduction_type, sub_type, vector_length_),
2094 kNoDexPc));
Aart Bikdbbac8f2017-09-01 13:06:08 -07002095 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorizedIdiom);
2096 } else {
Artem Serove521eb02020-02-27 18:51:24 +00002097 // "GenerateVecOp()" must not be called more than once for each original loop body
2098 // instruction. As the SAD idiom processes both "current" instruction ("instruction")
2099 // and its ABS input in one go, we must check that for the scalar case the ABS instruction
2100 // has not yet been processed.
2101 if (vector_map_->find(abs) == vector_map_->end()) {
2102 GenerateVecOp(abs, vector_map_->Get(r), nullptr, reduction_type);
2103 }
2104 GenerateVecOp(instruction, vector_map_->Get(acc), vector_map_->Get(abs), reduction_type);
Aart Bikdbbac8f2017-09-01 13:06:08 -07002105 }
2106 }
2107 return true;
2108 }
2109 return false;
2110}
2111
Artem Serovaaac0e32018-08-07 00:52:22 +01002112// Method recognises the following dot product idiom:
2113// q += a * b for operands a, b whose type is narrower than the reduction one.
2114// Provided that the operands have the same type or are promoted to a wider form.
2115// Since this may involve a vector length change, the idiom is handled by going directly
2116// to a dot product node (rather than relying combining finer grained nodes later).
2117bool HLoopOptimization::VectorizeDotProdIdiom(LoopNode* node,
2118 HInstruction* instruction,
2119 bool generate_code,
2120 DataType::Type reduction_type,
2121 uint64_t restrictions) {
Alex Light43f2f752019-12-04 17:48:45 +00002122 if (!instruction->IsAdd() || reduction_type != DataType::Type::kInt32) {
Artem Serovaaac0e32018-08-07 00:52:22 +01002123 return false;
2124 }
2125
Artem Serove521eb02020-02-27 18:51:24 +00002126 HInstruction* const acc = instruction->InputAt(0);
2127 HInstruction* const mul = instruction->InputAt(1);
2128 if (!mul->IsMul() || mul->GetType() != reduction_type) {
Artem Serovaaac0e32018-08-07 00:52:22 +01002129 return false;
2130 }
2131
Artem Serove521eb02020-02-27 18:51:24 +00002132 HInstruction* const mul_left = mul->InputAt(0);
2133 HInstruction* const mul_right = mul->InputAt(1);
2134 HInstruction* r = mul_left;
2135 HInstruction* s = mul_right;
2136 DataType::Type op_type = GetNarrowerType(mul_left, mul_right);
Artem Serovaaac0e32018-08-07 00:52:22 +01002137 bool is_unsigned = false;
2138
Artem Serove521eb02020-02-27 18:51:24 +00002139 if (!IsNarrowerOperands(mul_left, mul_right, op_type, &r, &s, &is_unsigned)) {
Artem Serovaaac0e32018-08-07 00:52:22 +01002140 return false;
2141 }
2142 op_type = HVecOperation::ToProperType(op_type, is_unsigned);
2143
2144 if (!TrySetVectorType(op_type, &restrictions) ||
2145 HasVectorRestrictions(restrictions, kNoDotProd)) {
2146 return false;
2147 }
2148
2149 DCHECK(r != nullptr && s != nullptr);
2150 // Accept dot product idiom for vectorizable operands. Vectorized code uses the shorthand
2151 // idiomatic operation. Sequential code uses the original scalar expressions.
2152 if (generate_code && vector_mode_ != kVector) { // de-idiom
Artem Serove521eb02020-02-27 18:51:24 +00002153 r = mul_left;
2154 s = mul_right;
Artem Serovaaac0e32018-08-07 00:52:22 +01002155 }
Artem Serove521eb02020-02-27 18:51:24 +00002156 if (VectorizeUse(node, acc, generate_code, op_type, restrictions) &&
Artem Serovaaac0e32018-08-07 00:52:22 +01002157 VectorizeUse(node, r, generate_code, op_type, restrictions) &&
2158 VectorizeUse(node, s, generate_code, op_type, restrictions)) {
2159 if (generate_code) {
2160 if (vector_mode_ == kVector) {
2161 vector_map_->Put(instruction, new (global_allocator_) HVecDotProd(
2162 global_allocator_,
Artem Serove521eb02020-02-27 18:51:24 +00002163 vector_map_->Get(acc),
Artem Serovaaac0e32018-08-07 00:52:22 +01002164 vector_map_->Get(r),
2165 vector_map_->Get(s),
2166 reduction_type,
2167 is_unsigned,
2168 GetOtherVL(reduction_type, op_type, vector_length_),
2169 kNoDexPc));
2170 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorizedIdiom);
2171 } else {
Artem Serove521eb02020-02-27 18:51:24 +00002172 // "GenerateVecOp()" must not be called more than once for each original loop body
2173 // instruction. As the DotProd idiom processes both "current" instruction ("instruction")
2174 // and its MUL input in one go, we must check that for the scalar case the MUL instruction
2175 // has not yet been processed.
2176 if (vector_map_->find(mul) == vector_map_->end()) {
2177 GenerateVecOp(mul, vector_map_->Get(r), vector_map_->Get(s), reduction_type);
2178 }
2179 GenerateVecOp(instruction, vector_map_->Get(acc), vector_map_->Get(mul), reduction_type);
Artem Serovaaac0e32018-08-07 00:52:22 +01002180 }
2181 }
2182 return true;
2183 }
2184 return false;
2185}
2186
Aart Bikf3e61ee2017-04-12 17:09:20 -07002187//
Aart Bik14a68b42017-06-08 14:06:58 -07002188// Vectorization heuristics.
2189//
2190
Aart Bik38a3f212017-10-20 17:02:21 -07002191Alignment HLoopOptimization::ComputeAlignment(HInstruction* offset,
2192 DataType::Type type,
2193 bool is_string_char_at,
2194 uint32_t peeling) {
2195 // Combine the alignment and hidden offset that is guaranteed by
2196 // the Android runtime with a known starting index adjusted as bytes.
2197 int64_t value = 0;
2198 if (IsInt64AndGet(offset, /*out*/ &value)) {
2199 uint32_t start_offset =
2200 HiddenOffset(type, is_string_char_at) + (value + peeling) * DataType::Size(type);
2201 return Alignment(BaseAlignment(), start_offset & (BaseAlignment() - 1u));
2202 }
2203 // Otherwise, the Android runtime guarantees at least natural alignment.
2204 return Alignment(DataType::Size(type), 0);
2205}
2206
2207void HLoopOptimization::SetAlignmentStrategy(uint32_t peeling_votes[],
2208 const ArrayReference* peeling_candidate) {
2209 // Current heuristic: pick the best static loop peeling factor, if any,
2210 // or otherwise use dynamic loop peeling on suggested peeling candidate.
2211 uint32_t max_vote = 0;
2212 for (int32_t i = 0; i < 16; i++) {
2213 if (peeling_votes[i] > max_vote) {
2214 max_vote = peeling_votes[i];
2215 vector_static_peeling_factor_ = i;
2216 }
2217 }
2218 if (max_vote == 0) {
2219 vector_dynamic_peeling_candidate_ = peeling_candidate;
2220 }
2221}
2222
2223uint32_t HLoopOptimization::MaxNumberPeeled() {
2224 if (vector_dynamic_peeling_candidate_ != nullptr) {
2225 return vector_length_ - 1u; // worst-case
2226 }
2227 return vector_static_peeling_factor_; // known exactly
2228}
2229
Aart Bik14a68b42017-06-08 14:06:58 -07002230bool HLoopOptimization::IsVectorizationProfitable(int64_t trip_count) {
Aart Bik38a3f212017-10-20 17:02:21 -07002231 // Current heuristic: non-empty body with sufficient number of iterations (if known).
Aart Bik14a68b42017-06-08 14:06:58 -07002232 // TODO: refine by looking at e.g. operation count, alignment, etc.
Aart Bik38a3f212017-10-20 17:02:21 -07002233 // TODO: trip count is really unsigned entity, provided the guarding test
2234 // is satisfied; deal with this more carefully later
2235 uint32_t max_peel = MaxNumberPeeled();
Aart Bik14a68b42017-06-08 14:06:58 -07002236 if (vector_length_ == 0) {
2237 return false; // nothing found
Aart Bik38a3f212017-10-20 17:02:21 -07002238 } else if (trip_count < 0) {
2239 return false; // guard against non-taken/large
2240 } else if ((0 < trip_count) && (trip_count < (vector_length_ + max_peel))) {
Aart Bik14a68b42017-06-08 14:06:58 -07002241 return false; // insufficient iterations
2242 }
2243 return true;
2244}
2245
Aart Bik14a68b42017-06-08 14:06:58 -07002246//
Aart Bikf8f5a162017-02-06 15:35:29 -08002247// Helpers.
2248//
2249
2250bool HLoopOptimization::TrySetPhiInduction(HPhi* phi, bool restrict_uses) {
Aart Bikb29f6842017-07-28 15:58:41 -07002251 // Start with empty phi induction.
2252 iset_->clear();
2253
Nicolas Geoffrayf57c1ae2017-06-28 17:40:18 +01002254 // Special case Phis that have equivalent in a debuggable setup. Our graph checker isn't
2255 // smart enough to follow strongly connected components (and it's probably not worth
2256 // it to make it so). See b/33775412.
2257 if (graph_->IsDebuggable() && phi->HasEquivalentPhi()) {
2258 return false;
2259 }
Aart Bikb29f6842017-07-28 15:58:41 -07002260
2261 // Lookup phi induction cycle.
Aart Bikcc42be02016-10-20 16:14:16 -07002262 ArenaSet<HInstruction*>* set = induction_range_.LookupCycle(phi);
2263 if (set != nullptr) {
2264 for (HInstruction* i : *set) {
Aart Bike3dedc52016-11-02 17:50:27 -07002265 // Check that, other than instructions that are no longer in the graph (removed earlier)
Aart Bikf8f5a162017-02-06 15:35:29 -08002266 // each instruction is removable and, when restrict uses are requested, other than for phi,
2267 // all uses are contained within the cycle.
Aart Bike3dedc52016-11-02 17:50:27 -07002268 if (!i->IsInBlock()) {
2269 continue;
2270 } else if (!i->IsRemovable()) {
2271 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08002272 } else if (i != phi && restrict_uses) {
Aart Bikb29f6842017-07-28 15:58:41 -07002273 // Deal with regular uses.
Aart Bikcc42be02016-10-20 16:14:16 -07002274 for (const HUseListNode<HInstruction*>& use : i->GetUses()) {
2275 if (set->find(use.GetUser()) == set->end()) {
2276 return false;
2277 }
2278 }
2279 }
Aart Bike3dedc52016-11-02 17:50:27 -07002280 iset_->insert(i); // copy
Aart Bikcc42be02016-10-20 16:14:16 -07002281 }
Aart Bikcc42be02016-10-20 16:14:16 -07002282 return true;
2283 }
2284 return false;
2285}
2286
Aart Bikb29f6842017-07-28 15:58:41 -07002287bool HLoopOptimization::TrySetPhiReduction(HPhi* phi) {
Aart Bikcc42be02016-10-20 16:14:16 -07002288 DCHECK(iset_->empty());
Aart Bikb29f6842017-07-28 15:58:41 -07002289 // Only unclassified phi cycles are candidates for reductions.
2290 if (induction_range_.IsClassified(phi)) {
2291 return false;
2292 }
2293 // Accept operations like x = x + .., provided that the phi and the reduction are
2294 // used exactly once inside the loop, and by each other.
2295 HInputsRef inputs = phi->GetInputs();
2296 if (inputs.size() == 2) {
2297 HInstruction* reduction = inputs[1];
2298 if (HasReductionFormat(reduction, phi)) {
2299 HLoopInformation* loop_info = phi->GetBlock()->GetLoopInformation();
Aart Bik38a3f212017-10-20 17:02:21 -07002300 uint32_t use_count = 0;
Aart Bikb29f6842017-07-28 15:58:41 -07002301 bool single_use_inside_loop =
2302 // Reduction update only used by phi.
2303 reduction->GetUses().HasExactlyOneElement() &&
2304 !reduction->HasEnvironmentUses() &&
2305 // Reduction update is only use of phi inside the loop.
2306 IsOnlyUsedAfterLoop(loop_info, phi, /*collect_loop_uses*/ true, &use_count) &&
2307 iset_->size() == 1;
2308 iset_->clear(); // leave the way you found it
2309 if (single_use_inside_loop) {
2310 // Link reduction back, and start recording feed value.
2311 reductions_->Put(reduction, phi);
2312 reductions_->Put(phi, phi->InputAt(0));
2313 return true;
2314 }
2315 }
2316 }
2317 return false;
2318}
2319
2320bool HLoopOptimization::TrySetSimpleLoopHeader(HBasicBlock* block, /*out*/ HPhi** main_phi) {
2321 // Start with empty phi induction and reductions.
2322 iset_->clear();
2323 reductions_->clear();
2324
2325 // Scan the phis to find the following (the induction structure has already
2326 // been optimized, so we don't need to worry about trivial cases):
2327 // (1) optional reductions in loop,
2328 // (2) the main induction, used in loop control.
2329 HPhi* phi = nullptr;
2330 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
2331 if (TrySetPhiReduction(it.Current()->AsPhi())) {
2332 continue;
2333 } else if (phi == nullptr) {
2334 // Found the first candidate for main induction.
2335 phi = it.Current()->AsPhi();
2336 } else {
2337 return false;
2338 }
2339 }
2340
2341 // Then test for a typical loopheader:
2342 // s: SuspendCheck
2343 // c: Condition(phi, bound)
2344 // i: If(c)
2345 if (phi != nullptr && TrySetPhiInduction(phi, /*restrict_uses*/ false)) {
Aart Bikcc42be02016-10-20 16:14:16 -07002346 HInstruction* s = block->GetFirstInstruction();
2347 if (s != nullptr && s->IsSuspendCheck()) {
2348 HInstruction* c = s->GetNext();
Aart Bikd86c0852017-04-14 12:00:15 -07002349 if (c != nullptr &&
2350 c->IsCondition() &&
2351 c->GetUses().HasExactlyOneElement() && // only used for termination
2352 !c->HasEnvironmentUses()) { // unlikely, but not impossible
Aart Bikcc42be02016-10-20 16:14:16 -07002353 HInstruction* i = c->GetNext();
2354 if (i != nullptr && i->IsIf() && i->InputAt(0) == c) {
2355 iset_->insert(c);
2356 iset_->insert(s);
Aart Bikb29f6842017-07-28 15:58:41 -07002357 *main_phi = phi;
Aart Bikcc42be02016-10-20 16:14:16 -07002358 return true;
2359 }
2360 }
2361 }
2362 }
2363 return false;
2364}
2365
2366bool HLoopOptimization::IsEmptyBody(HBasicBlock* block) {
Aart Bikf8f5a162017-02-06 15:35:29 -08002367 if (!block->GetPhis().IsEmpty()) {
2368 return false;
2369 }
2370 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
2371 HInstruction* instruction = it.Current();
2372 if (!instruction->IsGoto() && iset_->find(instruction) == iset_->end()) {
2373 return false;
Aart Bikcc42be02016-10-20 16:14:16 -07002374 }
Aart Bikf8f5a162017-02-06 15:35:29 -08002375 }
2376 return true;
2377}
2378
2379bool HLoopOptimization::IsUsedOutsideLoop(HLoopInformation* loop_info,
2380 HInstruction* instruction) {
Aart Bikb29f6842017-07-28 15:58:41 -07002381 // Deal with regular uses.
Aart Bikf8f5a162017-02-06 15:35:29 -08002382 for (const HUseListNode<HInstruction*>& use : instruction->GetUses()) {
2383 if (use.GetUser()->GetBlock()->GetLoopInformation() != loop_info) {
2384 return true;
2385 }
Aart Bikcc42be02016-10-20 16:14:16 -07002386 }
2387 return false;
2388}
2389
Aart Bik482095d2016-10-10 15:39:10 -07002390bool HLoopOptimization::IsOnlyUsedAfterLoop(HLoopInformation* loop_info,
Aart Bik8c4a8542016-10-06 11:36:57 -07002391 HInstruction* instruction,
Aart Bik6b69e0a2017-01-11 10:20:43 -08002392 bool collect_loop_uses,
Aart Bik38a3f212017-10-20 17:02:21 -07002393 /*out*/ uint32_t* use_count) {
Aart Bikb29f6842017-07-28 15:58:41 -07002394 // Deal with regular uses.
Aart Bik8c4a8542016-10-06 11:36:57 -07002395 for (const HUseListNode<HInstruction*>& use : instruction->GetUses()) {
2396 HInstruction* user = use.GetUser();
2397 if (iset_->find(user) == iset_->end()) { // not excluded?
2398 HLoopInformation* other_loop_info = user->GetBlock()->GetLoopInformation();
Aart Bik482095d2016-10-10 15:39:10 -07002399 if (other_loop_info != nullptr && other_loop_info->IsIn(*loop_info)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -08002400 // If collect_loop_uses is set, simply keep adding those uses to the set.
2401 // Otherwise, reject uses inside the loop that were not already in the set.
2402 if (collect_loop_uses) {
2403 iset_->insert(user);
2404 continue;
2405 }
Aart Bik8c4a8542016-10-06 11:36:57 -07002406 return false;
2407 }
2408 ++*use_count;
2409 }
2410 }
2411 return true;
2412}
2413
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002414bool HLoopOptimization::TryReplaceWithLastValue(HLoopInformation* loop_info,
2415 HInstruction* instruction,
2416 HBasicBlock* block) {
2417 // Try to replace outside uses with the last value.
Aart Bik807868e2016-11-03 17:51:43 -07002418 if (induction_range_.CanGenerateLastValue(instruction)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -08002419 HInstruction* replacement = induction_range_.GenerateLastValue(instruction, graph_, block);
Aart Bikb29f6842017-07-28 15:58:41 -07002420 // Deal with regular uses.
Aart Bik6b69e0a2017-01-11 10:20:43 -08002421 const HUseList<HInstruction*>& uses = instruction->GetUses();
2422 for (auto it = uses.begin(), end = uses.end(); it != end;) {
2423 HInstruction* user = it->GetUser();
2424 size_t index = it->GetIndex();
2425 ++it; // increment before replacing
2426 if (iset_->find(user) == iset_->end()) { // not excluded?
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002427 if (kIsDebugBuild) {
2428 // We have checked earlier in 'IsOnlyUsedAfterLoop' that the use is after the loop.
2429 HLoopInformation* other_loop_info = user->GetBlock()->GetLoopInformation();
2430 CHECK(other_loop_info == nullptr || !other_loop_info->IsIn(*loop_info));
2431 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08002432 user->ReplaceInput(replacement, index);
2433 induction_range_.Replace(user, instruction, replacement); // update induction
2434 }
2435 }
Aart Bikb29f6842017-07-28 15:58:41 -07002436 // Deal with environment uses.
Aart Bik6b69e0a2017-01-11 10:20:43 -08002437 const HUseList<HEnvironment*>& env_uses = instruction->GetEnvUses();
2438 for (auto it = env_uses.begin(), end = env_uses.end(); it != end;) {
2439 HEnvironment* user = it->GetUser();
2440 size_t index = it->GetIndex();
2441 ++it; // increment before replacing
2442 if (iset_->find(user->GetHolder()) == iset_->end()) { // not excluded?
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002443 // Only update environment uses after the loop.
Aart Bik14a68b42017-06-08 14:06:58 -07002444 HLoopInformation* other_loop_info = user->GetHolder()->GetBlock()->GetLoopInformation();
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002445 if (other_loop_info == nullptr || !other_loop_info->IsIn(*loop_info)) {
2446 user->RemoveAsUserOfInput(index);
2447 user->SetRawEnvAt(index, replacement);
2448 replacement->AddEnvUseAt(user, index);
2449 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08002450 }
2451 }
Aart Bik807868e2016-11-03 17:51:43 -07002452 return true;
Aart Bik8c4a8542016-10-06 11:36:57 -07002453 }
Aart Bik807868e2016-11-03 17:51:43 -07002454 return false;
Aart Bik8c4a8542016-10-06 11:36:57 -07002455}
2456
Aart Bikf8f5a162017-02-06 15:35:29 -08002457bool HLoopOptimization::TryAssignLastValue(HLoopInformation* loop_info,
2458 HInstruction* instruction,
2459 HBasicBlock* block,
2460 bool collect_loop_uses) {
2461 // Assigning the last value is always successful if there are no uses.
2462 // Otherwise, it succeeds in a no early-exit loop by generating the
2463 // proper last value assignment.
Aart Bik38a3f212017-10-20 17:02:21 -07002464 uint32_t use_count = 0;
Aart Bikf8f5a162017-02-06 15:35:29 -08002465 return IsOnlyUsedAfterLoop(loop_info, instruction, collect_loop_uses, &use_count) &&
2466 (use_count == 0 ||
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002467 (!IsEarlyExit(loop_info) && TryReplaceWithLastValue(loop_info, instruction, block)));
Aart Bikf8f5a162017-02-06 15:35:29 -08002468}
2469
Aart Bik6b69e0a2017-01-11 10:20:43 -08002470void HLoopOptimization::RemoveDeadInstructions(const HInstructionList& list) {
2471 for (HBackwardInstructionIterator i(list); !i.Done(); i.Advance()) {
2472 HInstruction* instruction = i.Current();
2473 if (instruction->IsDeadAndRemovable()) {
2474 simplified_ = true;
2475 instruction->GetBlock()->RemoveInstructionOrPhi(instruction);
2476 }
2477 }
2478}
2479
Aart Bik14a68b42017-06-08 14:06:58 -07002480bool HLoopOptimization::CanRemoveCycle() {
2481 for (HInstruction* i : *iset_) {
2482 // We can never remove instructions that have environment
2483 // uses when we compile 'debuggable'.
2484 if (i->HasEnvironmentUses() && graph_->IsDebuggable()) {
2485 return false;
2486 }
2487 // A deoptimization should never have an environment input removed.
2488 for (const HUseListNode<HEnvironment*>& use : i->GetEnvUses()) {
2489 if (use.GetUser()->GetHolder()->IsDeoptimize()) {
2490 return false;
2491 }
2492 }
2493 }
2494 return true;
2495}
2496
Aart Bik281c6812016-08-26 11:31:48 -07002497} // namespace art