blob: 6c918a3ac2484ed310570cc6a9219d139f13842b [file] [log] [blame]
Aart Bik281c6812016-08-26 11:31:48 -07001/*
2 * Copyright (C) 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "loop_optimization.h"
18
Aart Bikf8f5a162017-02-06 15:35:29 -080019#include "arch/arm/instruction_set_features_arm.h"
20#include "arch/arm64/instruction_set_features_arm64.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070021#include "arch/instruction_set.h"
Aart Bikf8f5a162017-02-06 15:35:29 -080022#include "arch/mips/instruction_set_features_mips.h"
23#include "arch/mips64/instruction_set_features_mips64.h"
24#include "arch/x86/instruction_set_features_x86.h"
25#include "arch/x86_64/instruction_set_features_x86_64.h"
Aart Bik92685a82017-03-06 11:13:43 -080026#include "driver/compiler_driver.h"
Aart Bik96202302016-10-04 17:33:56 -070027#include "linear_order.h"
Aart Bik281c6812016-08-26 11:31:48 -070028
29namespace art {
30
Aart Bikf8f5a162017-02-06 15:35:29 -080031// Enables vectorization (SIMDization) in the loop optimizer.
32static constexpr bool kEnableVectorization = true;
33
Aart Bik14a68b42017-06-08 14:06:58 -070034// All current SIMD targets want 16-byte alignment.
35static constexpr size_t kAlignedBase = 16;
36
Aart Bik521b50f2017-09-09 10:44:45 -070037// No loop unrolling factor (just one copy of the loop-body).
38static constexpr uint32_t kNoUnrollingFactor = 1;
39
Aart Bik9abf8942016-10-14 09:49:42 -070040// Remove the instruction from the graph. A bit more elaborate than the usual
41// instruction removal, since there may be a cycle in the use structure.
Aart Bik281c6812016-08-26 11:31:48 -070042static void RemoveFromCycle(HInstruction* instruction) {
Aart Bik281c6812016-08-26 11:31:48 -070043 instruction->RemoveAsUserOfAllInputs();
44 instruction->RemoveEnvironmentUsers();
45 instruction->GetBlock()->RemoveInstructionOrPhi(instruction, /*ensure_safety=*/ false);
Artem Serov21c7e6f2017-07-27 16:04:42 +010046 RemoveEnvironmentUses(instruction);
47 ResetEnvironmentInputRecords(instruction);
Aart Bik281c6812016-08-26 11:31:48 -070048}
49
Aart Bik807868e2016-11-03 17:51:43 -070050// Detect a goto block and sets succ to the single successor.
Aart Bike3dedc52016-11-02 17:50:27 -070051static bool IsGotoBlock(HBasicBlock* block, /*out*/ HBasicBlock** succ) {
52 if (block->GetPredecessors().size() == 1 &&
53 block->GetSuccessors().size() == 1 &&
54 block->IsSingleGoto()) {
55 *succ = block->GetSingleSuccessor();
56 return true;
57 }
58 return false;
59}
60
Aart Bik807868e2016-11-03 17:51:43 -070061// Detect an early exit loop.
62static bool IsEarlyExit(HLoopInformation* loop_info) {
63 HBlocksInLoopReversePostOrderIterator it_loop(*loop_info);
64 for (it_loop.Advance(); !it_loop.Done(); it_loop.Advance()) {
65 for (HBasicBlock* successor : it_loop.Current()->GetSuccessors()) {
66 if (!loop_info->Contains(*successor)) {
67 return true;
68 }
69 }
70 }
71 return false;
72}
73
Aart Bikdbbac8f2017-09-01 13:06:08 -070074// Detect a sign extension in instruction from the given type. The to64 parameter
75// denotes if result is long, and thus sign extension from int can be included.
76// Returns the promoted operand on success.
Aart Bikf3e61ee2017-04-12 17:09:20 -070077static bool IsSignExtensionAndGet(HInstruction* instruction,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +010078 DataType::Type type,
Aart Bikdbbac8f2017-09-01 13:06:08 -070079 /*out*/ HInstruction** operand,
80 bool to64 = false) {
Aart Bikf3e61ee2017-04-12 17:09:20 -070081 // Accept any already wider constant that would be handled properly by sign
82 // extension when represented in the *width* of the given narrower data type
83 // (the fact that char normally zero extends does not matter here).
84 int64_t value = 0;
Aart Bik50e20d52017-05-05 14:07:29 -070085 if (IsInt64AndGet(instruction, /*out*/ &value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -070086 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +010087 case DataType::Type::kInt8:
Aart Bikdbbac8f2017-09-01 13:06:08 -070088 if (IsInt<8>(value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -070089 *operand = instruction;
90 return true;
91 }
92 return false;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +010093 case DataType::Type::kUint16:
94 case DataType::Type::kInt16:
Aart Bikdbbac8f2017-09-01 13:06:08 -070095 if (IsInt<16>(value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -070096 *operand = instruction;
97 return true;
98 }
99 return false;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100100 case DataType::Type::kInt32:
Aart Bikdbbac8f2017-09-01 13:06:08 -0700101 if (IsInt<32>(value)) {
102 *operand = instruction;
103 return to64;
104 }
105 return false;
Aart Bikf3e61ee2017-04-12 17:09:20 -0700106 default:
107 return false;
108 }
109 }
110 // An implicit widening conversion of a signed integer to an integral type sign-extends
111 // the two's-complement representation of the integer value to fill the wider format.
112 if (instruction->GetType() == type && (instruction->IsArrayGet() ||
113 instruction->IsStaticFieldGet() ||
114 instruction->IsInstanceFieldGet())) {
115 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100116 case DataType::Type::kInt8:
117 case DataType::Type::kInt16:
Aart Bikf3e61ee2017-04-12 17:09:20 -0700118 *operand = instruction;
119 return true;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100120 case DataType::Type::kInt32:
Aart Bikdbbac8f2017-09-01 13:06:08 -0700121 *operand = instruction;
122 return to64;
Aart Bikf3e61ee2017-04-12 17:09:20 -0700123 default:
124 return false;
125 }
126 }
Aart Bikdbbac8f2017-09-01 13:06:08 -0700127 // Explicit type conversion to long.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100128 if (instruction->IsTypeConversion() && instruction->GetType() == DataType::Type::kInt64) {
Aart Bikdbbac8f2017-09-01 13:06:08 -0700129 return IsSignExtensionAndGet(instruction->InputAt(0), type, /*out*/ operand, /*to64*/ true);
130 }
Aart Bikf3e61ee2017-04-12 17:09:20 -0700131 return false;
132}
133
Aart Bikdbbac8f2017-09-01 13:06:08 -0700134// Detect a zero extension in instruction from the given type. The to64 parameter
135// denotes if result is long, and thus zero extension from int can be included.
136// Returns the promoted operand on success.
Aart Bikf3e61ee2017-04-12 17:09:20 -0700137static bool IsZeroExtensionAndGet(HInstruction* instruction,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100138 DataType::Type type,
Aart Bikdbbac8f2017-09-01 13:06:08 -0700139 /*out*/ HInstruction** operand,
140 bool to64 = false) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700141 // Accept any already wider constant that would be handled properly by zero
142 // extension when represented in the *width* of the given narrower data type
Aart Bikdbbac8f2017-09-01 13:06:08 -0700143 // (the fact that byte/short/int normally sign extend does not matter here).
Aart Bikf3e61ee2017-04-12 17:09:20 -0700144 int64_t value = 0;
Aart Bik50e20d52017-05-05 14:07:29 -0700145 if (IsInt64AndGet(instruction, /*out*/ &value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700146 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100147 case DataType::Type::kInt8:
Aart Bikdbbac8f2017-09-01 13:06:08 -0700148 if (IsUint<8>(value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700149 *operand = instruction;
150 return true;
151 }
152 return false;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100153 case DataType::Type::kUint16:
154 case DataType::Type::kInt16:
Aart Bikdbbac8f2017-09-01 13:06:08 -0700155 if (IsUint<16>(value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700156 *operand = instruction;
157 return true;
158 }
159 return false;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100160 case DataType::Type::kInt32:
Aart Bikdbbac8f2017-09-01 13:06:08 -0700161 if (IsUint<32>(value)) {
162 *operand = instruction;
163 return to64;
164 }
165 return false;
Aart Bikf3e61ee2017-04-12 17:09:20 -0700166 default:
167 return false;
168 }
169 }
170 // An implicit widening conversion of a char to an integral type zero-extends
171 // the representation of the char value to fill the wider format.
172 if (instruction->GetType() == type && (instruction->IsArrayGet() ||
173 instruction->IsStaticFieldGet() ||
174 instruction->IsInstanceFieldGet())) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100175 if (type == DataType::Type::kUint16) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700176 *operand = instruction;
177 return true;
178 }
179 }
180 // A sign (or zero) extension followed by an explicit removal of just the
181 // higher sign bits is equivalent to a zero extension of the underlying operand.
182 if (instruction->IsAnd()) {
183 int64_t mask = 0;
184 HInstruction* a = instruction->InputAt(0);
185 HInstruction* b = instruction->InputAt(1);
186 // In (a & b) find (mask & b) or (a & mask) with sign or zero extension on the non-mask.
187 if ((IsInt64AndGet(a, /*out*/ &mask) && (IsSignExtensionAndGet(b, type, /*out*/ operand) ||
188 IsZeroExtensionAndGet(b, type, /*out*/ operand))) ||
189 (IsInt64AndGet(b, /*out*/ &mask) && (IsSignExtensionAndGet(a, type, /*out*/ operand) ||
190 IsZeroExtensionAndGet(a, type, /*out*/ operand)))) {
191 switch ((*operand)->GetType()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100192 case DataType::Type::kInt8:
Aart Bikdbbac8f2017-09-01 13:06:08 -0700193 return mask == std::numeric_limits<uint8_t>::max();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100194 case DataType::Type::kUint16:
195 case DataType::Type::kInt16:
Aart Bikdbbac8f2017-09-01 13:06:08 -0700196 return mask == std::numeric_limits<uint16_t>::max();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100197 case DataType::Type::kInt32:
Aart Bikdbbac8f2017-09-01 13:06:08 -0700198 return mask == std::numeric_limits<uint32_t>::max() && to64;
Aart Bikf3e61ee2017-04-12 17:09:20 -0700199 default: return false;
200 }
201 }
202 }
Aart Bikdbbac8f2017-09-01 13:06:08 -0700203 // Explicit type conversion to long.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100204 if (instruction->IsTypeConversion() && instruction->GetType() == DataType::Type::kInt64) {
Aart Bikdbbac8f2017-09-01 13:06:08 -0700205 return IsZeroExtensionAndGet(instruction->InputAt(0), type, /*out*/ operand, /*to64*/ true);
206 }
Aart Bikf3e61ee2017-04-12 17:09:20 -0700207 return false;
208}
209
Aart Bik304c8a52017-05-23 11:01:13 -0700210// Detect situations with same-extension narrower operands.
211// Returns true on success and sets is_unsigned accordingly.
212static bool IsNarrowerOperands(HInstruction* a,
213 HInstruction* b,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100214 DataType::Type type,
Aart Bik304c8a52017-05-23 11:01:13 -0700215 /*out*/ HInstruction** r,
216 /*out*/ HInstruction** s,
217 /*out*/ bool* is_unsigned) {
218 if (IsSignExtensionAndGet(a, type, r) && IsSignExtensionAndGet(b, type, s)) {
219 *is_unsigned = false;
220 return true;
221 } else if (IsZeroExtensionAndGet(a, type, r) && IsZeroExtensionAndGet(b, type, s)) {
222 *is_unsigned = true;
223 return true;
224 }
225 return false;
226}
227
228// As above, single operand.
229static bool IsNarrowerOperand(HInstruction* a,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100230 DataType::Type type,
Aart Bik304c8a52017-05-23 11:01:13 -0700231 /*out*/ HInstruction** r,
232 /*out*/ bool* is_unsigned) {
233 if (IsSignExtensionAndGet(a, type, r)) {
234 *is_unsigned = false;
235 return true;
236 } else if (IsZeroExtensionAndGet(a, type, r)) {
237 *is_unsigned = true;
238 return true;
239 }
240 return false;
241}
242
Aart Bikdbbac8f2017-09-01 13:06:08 -0700243// Compute relative vector length based on type difference.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100244static size_t GetOtherVL(DataType::Type other_type, DataType::Type vector_type, size_t vl) {
Aart Bikdbbac8f2017-09-01 13:06:08 -0700245 switch (other_type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100246 case DataType::Type::kBool:
247 case DataType::Type::kInt8:
Aart Bikdbbac8f2017-09-01 13:06:08 -0700248 switch (vector_type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100249 case DataType::Type::kBool:
250 case DataType::Type::kInt8: return vl;
Aart Bikdbbac8f2017-09-01 13:06:08 -0700251 default: break;
252 }
253 return vl;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100254 case DataType::Type::kUint16:
255 case DataType::Type::kInt16:
Aart Bikdbbac8f2017-09-01 13:06:08 -0700256 switch (vector_type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100257 case DataType::Type::kBool:
258 case DataType::Type::kInt8: return vl >> 1;
259 case DataType::Type::kUint16:
260 case DataType::Type::kInt16: return vl;
Aart Bikdbbac8f2017-09-01 13:06:08 -0700261 default: break;
262 }
263 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100264 case DataType::Type::kInt32:
Aart Bikdbbac8f2017-09-01 13:06:08 -0700265 switch (vector_type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100266 case DataType::Type::kBool:
267 case DataType::Type::kInt8: return vl >> 2;
268 case DataType::Type::kUint16:
269 case DataType::Type::kInt16: return vl >> 1;
270 case DataType::Type::kInt32: return vl;
Aart Bikdbbac8f2017-09-01 13:06:08 -0700271 default: break;
272 }
273 break;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100274 case DataType::Type::kInt64:
Aart Bikdbbac8f2017-09-01 13:06:08 -0700275 switch (vector_type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100276 case DataType::Type::kBool:
277 case DataType::Type::kInt8: return vl >> 3;
278 case DataType::Type::kUint16:
279 case DataType::Type::kInt16: return vl >> 2;
280 case DataType::Type::kInt32: return vl >> 1;
281 case DataType::Type::kInt64: return vl;
Aart Bikdbbac8f2017-09-01 13:06:08 -0700282 default: break;
283 }
284 break;
285 default:
286 break;
287 }
288 LOG(FATAL) << "Unsupported idiom conversion";
289 UNREACHABLE();
290}
291
Aart Bik5f805002017-05-16 16:42:41 -0700292// Detect up to two instructions a and b, and an acccumulated constant c.
293static bool IsAddConstHelper(HInstruction* instruction,
294 /*out*/ HInstruction** a,
295 /*out*/ HInstruction** b,
296 /*out*/ int64_t* c,
297 int32_t depth) {
298 static constexpr int32_t kMaxDepth = 8; // don't search too deep
299 int64_t value = 0;
300 if (IsInt64AndGet(instruction, &value)) {
301 *c += value;
302 return true;
303 } else if (instruction->IsAdd() && depth <= kMaxDepth) {
304 return IsAddConstHelper(instruction->InputAt(0), a, b, c, depth + 1) &&
305 IsAddConstHelper(instruction->InputAt(1), a, b, c, depth + 1);
306 } else if (*a == nullptr) {
307 *a = instruction;
308 return true;
309 } else if (*b == nullptr) {
310 *b = instruction;
311 return true;
312 }
313 return false; // too many non-const operands
314}
315
316// Detect a + b + c for an optional constant c.
317static bool IsAddConst(HInstruction* instruction,
318 /*out*/ HInstruction** a,
319 /*out*/ HInstruction** b,
320 /*out*/ int64_t* c) {
321 if (instruction->IsAdd()) {
322 // Try to find a + b and accumulated c.
323 if (IsAddConstHelper(instruction->InputAt(0), a, b, c, /*depth*/ 0) &&
324 IsAddConstHelper(instruction->InputAt(1), a, b, c, /*depth*/ 0) &&
325 *b != nullptr) {
326 return true;
327 }
328 // Found a + b.
329 *a = instruction->InputAt(0);
330 *b = instruction->InputAt(1);
331 *c = 0;
332 return true;
333 }
334 return false;
335}
336
Aart Bikb29f6842017-07-28 15:58:41 -0700337// Detect reductions of the following forms,
Aart Bikb29f6842017-07-28 15:58:41 -0700338// x = x_phi + ..
339// x = x_phi - ..
340// x = max(x_phi, ..)
341// x = min(x_phi, ..)
342static bool HasReductionFormat(HInstruction* reduction, HInstruction* phi) {
343 if (reduction->IsAdd()) {
Aart Bikdbbac8f2017-09-01 13:06:08 -0700344 return (reduction->InputAt(0) == phi && reduction->InputAt(1) != phi) ||
345 (reduction->InputAt(0) != phi && reduction->InputAt(1) == phi);
Aart Bikb29f6842017-07-28 15:58:41 -0700346 } else if (reduction->IsSub()) {
Aart Bikdbbac8f2017-09-01 13:06:08 -0700347 return (reduction->InputAt(0) == phi && reduction->InputAt(1) != phi);
Aart Bikb29f6842017-07-28 15:58:41 -0700348 } else if (reduction->IsInvokeStaticOrDirect()) {
349 switch (reduction->AsInvokeStaticOrDirect()->GetIntrinsic()) {
350 case Intrinsics::kMathMinIntInt:
351 case Intrinsics::kMathMinLongLong:
352 case Intrinsics::kMathMinFloatFloat:
353 case Intrinsics::kMathMinDoubleDouble:
354 case Intrinsics::kMathMaxIntInt:
355 case Intrinsics::kMathMaxLongLong:
356 case Intrinsics::kMathMaxFloatFloat:
357 case Intrinsics::kMathMaxDoubleDouble:
Aart Bikdbbac8f2017-09-01 13:06:08 -0700358 return (reduction->InputAt(0) == phi && reduction->InputAt(1) != phi) ||
359 (reduction->InputAt(0) != phi && reduction->InputAt(1) == phi);
Aart Bikb29f6842017-07-28 15:58:41 -0700360 default:
361 return false;
362 }
363 }
364 return false;
365}
366
Aart Bikdbbac8f2017-09-01 13:06:08 -0700367// Translates vector operation to reduction kind.
368static HVecReduce::ReductionKind GetReductionKind(HVecOperation* reduction) {
369 if (reduction->IsVecAdd() || reduction->IsVecSub() || reduction->IsVecSADAccumulate()) {
Aart Bik0148de42017-09-05 09:25:01 -0700370 return HVecReduce::kSum;
371 } else if (reduction->IsVecMin()) {
372 return HVecReduce::kMin;
373 } else if (reduction->IsVecMax()) {
374 return HVecReduce::kMax;
375 }
376 LOG(FATAL) << "Unsupported SIMD reduction";
377 UNREACHABLE();
378}
379
Aart Bikf8f5a162017-02-06 15:35:29 -0800380// Test vector restrictions.
381static bool HasVectorRestrictions(uint64_t restrictions, uint64_t tested) {
382 return (restrictions & tested) != 0;
383}
384
Aart Bikf3e61ee2017-04-12 17:09:20 -0700385// Insert an instruction.
Aart Bikf8f5a162017-02-06 15:35:29 -0800386static HInstruction* Insert(HBasicBlock* block, HInstruction* instruction) {
387 DCHECK(block != nullptr);
388 DCHECK(instruction != nullptr);
389 block->InsertInstructionBefore(instruction, block->GetLastInstruction());
390 return instruction;
391}
392
Artem Serov21c7e6f2017-07-27 16:04:42 +0100393// Check that instructions from the induction sets are fully removed: have no uses
394// and no other instructions use them.
395static bool CheckInductionSetFullyRemoved(ArenaSet<HInstruction*>* iset) {
396 for (HInstruction* instr : *iset) {
397 if (instr->GetBlock() != nullptr ||
398 !instr->GetUses().empty() ||
399 !instr->GetEnvUses().empty() ||
400 HasEnvironmentUsedByOthers(instr)) {
401 return false;
402 }
403 }
Artem Serov21c7e6f2017-07-27 16:04:42 +0100404 return true;
405}
406
Aart Bik281c6812016-08-26 11:31:48 -0700407//
Aart Bikb29f6842017-07-28 15:58:41 -0700408// Public methods.
Aart Bik281c6812016-08-26 11:31:48 -0700409//
410
411HLoopOptimization::HLoopOptimization(HGraph* graph,
Aart Bik92685a82017-03-06 11:13:43 -0800412 CompilerDriver* compiler_driver,
Aart Bikb92cc332017-09-06 15:53:17 -0700413 HInductionVarAnalysis* induction_analysis,
414 OptimizingCompilerStats* stats)
415 : HOptimization(graph, kLoopOptimizationPassName, stats),
Aart Bik92685a82017-03-06 11:13:43 -0800416 compiler_driver_(compiler_driver),
Aart Bik281c6812016-08-26 11:31:48 -0700417 induction_range_(induction_analysis),
Aart Bik96202302016-10-04 17:33:56 -0700418 loop_allocator_(nullptr),
Aart Bikf8f5a162017-02-06 15:35:29 -0800419 global_allocator_(graph_->GetArena()),
Aart Bik281c6812016-08-26 11:31:48 -0700420 top_loop_(nullptr),
Aart Bik8c4a8542016-10-06 11:36:57 -0700421 last_loop_(nullptr),
Aart Bik482095d2016-10-10 15:39:10 -0700422 iset_(nullptr),
Aart Bikb29f6842017-07-28 15:58:41 -0700423 reductions_(nullptr),
Aart Bikf8f5a162017-02-06 15:35:29 -0800424 simplified_(false),
425 vector_length_(0),
426 vector_refs_(nullptr),
Aart Bik14a68b42017-06-08 14:06:58 -0700427 vector_peeling_candidate_(nullptr),
428 vector_runtime_test_a_(nullptr),
429 vector_runtime_test_b_(nullptr),
Aart Bik0148de42017-09-05 09:25:01 -0700430 vector_map_(nullptr),
431 vector_permanent_map_(nullptr) {
Aart Bik281c6812016-08-26 11:31:48 -0700432}
433
434void HLoopOptimization::Run() {
Mingyao Yang01b47b02017-02-03 12:09:57 -0800435 // Skip if there is no loop or the graph has try-catch/irreducible loops.
Aart Bik281c6812016-08-26 11:31:48 -0700436 // TODO: make this less of a sledgehammer.
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800437 if (!graph_->HasLoops() || graph_->HasTryCatch() || graph_->HasIrreducibleLoops()) {
Aart Bik281c6812016-08-26 11:31:48 -0700438 return;
439 }
440
Aart Bik96202302016-10-04 17:33:56 -0700441 // Phase-local allocator that draws from the global pool. Since the allocator
442 // itself resides on the stack, it is destructed on exiting Run(), which
443 // implies its underlying memory is released immediately.
Aart Bikf8f5a162017-02-06 15:35:29 -0800444 ArenaAllocator allocator(global_allocator_->GetArenaPool());
Aart Bik96202302016-10-04 17:33:56 -0700445 loop_allocator_ = &allocator;
Nicolas Geoffrayebe16742016-10-05 09:55:42 +0100446
Aart Bik96202302016-10-04 17:33:56 -0700447 // Perform loop optimizations.
448 LocalRun();
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800449 if (top_loop_ == nullptr) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800450 graph_->SetHasLoops(false); // no more loops
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800451 }
452
Aart Bik96202302016-10-04 17:33:56 -0700453 // Detach.
454 loop_allocator_ = nullptr;
455 last_loop_ = top_loop_ = nullptr;
456}
457
Aart Bikb29f6842017-07-28 15:58:41 -0700458//
459// Loop setup and traversal.
460//
461
Aart Bik96202302016-10-04 17:33:56 -0700462void HLoopOptimization::LocalRun() {
463 // Build the linear order using the phase-local allocator. This step enables building
464 // a loop hierarchy that properly reflects the outer-inner and previous-next relation.
465 ArenaVector<HBasicBlock*> linear_order(loop_allocator_->Adapter(kArenaAllocLinearOrder));
466 LinearizeGraph(graph_, loop_allocator_, &linear_order);
467
Aart Bik281c6812016-08-26 11:31:48 -0700468 // Build the loop hierarchy.
Aart Bik96202302016-10-04 17:33:56 -0700469 for (HBasicBlock* block : linear_order) {
Aart Bik281c6812016-08-26 11:31:48 -0700470 if (block->IsLoopHeader()) {
471 AddLoop(block->GetLoopInformation());
472 }
473 }
Aart Bik96202302016-10-04 17:33:56 -0700474
Aart Bik8c4a8542016-10-06 11:36:57 -0700475 // Traverse the loop hierarchy inner-to-outer and optimize. Traversal can use
Aart Bikf8f5a162017-02-06 15:35:29 -0800476 // temporary data structures using the phase-local allocator. All new HIR
477 // should use the global allocator.
Aart Bik8c4a8542016-10-06 11:36:57 -0700478 if (top_loop_ != nullptr) {
479 ArenaSet<HInstruction*> iset(loop_allocator_->Adapter(kArenaAllocLoopOptimization));
Aart Bikb29f6842017-07-28 15:58:41 -0700480 ArenaSafeMap<HInstruction*, HInstruction*> reds(
481 std::less<HInstruction*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
Aart Bikf8f5a162017-02-06 15:35:29 -0800482 ArenaSet<ArrayReference> refs(loop_allocator_->Adapter(kArenaAllocLoopOptimization));
483 ArenaSafeMap<HInstruction*, HInstruction*> map(
484 std::less<HInstruction*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
Aart Bik0148de42017-09-05 09:25:01 -0700485 ArenaSafeMap<HInstruction*, HInstruction*> perm(
486 std::less<HInstruction*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
Aart Bikf8f5a162017-02-06 15:35:29 -0800487 // Attach.
Aart Bik8c4a8542016-10-06 11:36:57 -0700488 iset_ = &iset;
Aart Bikb29f6842017-07-28 15:58:41 -0700489 reductions_ = &reds;
Aart Bikf8f5a162017-02-06 15:35:29 -0800490 vector_refs_ = &refs;
491 vector_map_ = &map;
Aart Bik0148de42017-09-05 09:25:01 -0700492 vector_permanent_map_ = &perm;
Aart Bikf8f5a162017-02-06 15:35:29 -0800493 // Traverse.
Aart Bik8c4a8542016-10-06 11:36:57 -0700494 TraverseLoopsInnerToOuter(top_loop_);
Aart Bikf8f5a162017-02-06 15:35:29 -0800495 // Detach.
496 iset_ = nullptr;
Aart Bikb29f6842017-07-28 15:58:41 -0700497 reductions_ = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800498 vector_refs_ = nullptr;
499 vector_map_ = nullptr;
Aart Bik0148de42017-09-05 09:25:01 -0700500 vector_permanent_map_ = nullptr;
Aart Bik8c4a8542016-10-06 11:36:57 -0700501 }
Aart Bik281c6812016-08-26 11:31:48 -0700502}
503
504void HLoopOptimization::AddLoop(HLoopInformation* loop_info) {
505 DCHECK(loop_info != nullptr);
Aart Bikf8f5a162017-02-06 15:35:29 -0800506 LoopNode* node = new (loop_allocator_) LoopNode(loop_info);
Aart Bik281c6812016-08-26 11:31:48 -0700507 if (last_loop_ == nullptr) {
508 // First loop.
509 DCHECK(top_loop_ == nullptr);
510 last_loop_ = top_loop_ = node;
511 } else if (loop_info->IsIn(*last_loop_->loop_info)) {
512 // Inner loop.
513 node->outer = last_loop_;
514 DCHECK(last_loop_->inner == nullptr);
515 last_loop_ = last_loop_->inner = node;
516 } else {
517 // Subsequent loop.
518 while (last_loop_->outer != nullptr && !loop_info->IsIn(*last_loop_->outer->loop_info)) {
519 last_loop_ = last_loop_->outer;
520 }
521 node->outer = last_loop_->outer;
522 node->previous = last_loop_;
523 DCHECK(last_loop_->next == nullptr);
524 last_loop_ = last_loop_->next = node;
525 }
526}
527
528void HLoopOptimization::RemoveLoop(LoopNode* node) {
529 DCHECK(node != nullptr);
Aart Bik8c4a8542016-10-06 11:36:57 -0700530 DCHECK(node->inner == nullptr);
531 if (node->previous != nullptr) {
532 // Within sequence.
533 node->previous->next = node->next;
534 if (node->next != nullptr) {
535 node->next->previous = node->previous;
536 }
537 } else {
538 // First of sequence.
539 if (node->outer != nullptr) {
540 node->outer->inner = node->next;
541 } else {
542 top_loop_ = node->next;
543 }
544 if (node->next != nullptr) {
545 node->next->outer = node->outer;
546 node->next->previous = nullptr;
547 }
548 }
Aart Bik281c6812016-08-26 11:31:48 -0700549}
550
Aart Bikb29f6842017-07-28 15:58:41 -0700551bool HLoopOptimization::TraverseLoopsInnerToOuter(LoopNode* node) {
552 bool changed = false;
Aart Bik281c6812016-08-26 11:31:48 -0700553 for ( ; node != nullptr; node = node->next) {
Aart Bikb29f6842017-07-28 15:58:41 -0700554 // Visit inner loops first. Recompute induction information for this
555 // loop if the induction of any inner loop has changed.
556 if (TraverseLoopsInnerToOuter(node->inner)) {
Aart Bik482095d2016-10-10 15:39:10 -0700557 induction_range_.ReVisit(node->loop_info);
558 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800559 // Repeat simplifications in the loop-body until no more changes occur.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800560 // Note that since each simplification consists of eliminating code (without
561 // introducing new code), this process is always finite.
Aart Bikdf7822e2016-12-06 10:05:30 -0800562 do {
563 simplified_ = false;
Aart Bikdf7822e2016-12-06 10:05:30 -0800564 SimplifyInduction(node);
Aart Bik6b69e0a2017-01-11 10:20:43 -0800565 SimplifyBlocks(node);
Aart Bikb29f6842017-07-28 15:58:41 -0700566 changed = simplified_ || changed;
Aart Bikdf7822e2016-12-06 10:05:30 -0800567 } while (simplified_);
Aart Bikf8f5a162017-02-06 15:35:29 -0800568 // Optimize inner loop.
Aart Bik9abf8942016-10-14 09:49:42 -0700569 if (node->inner == nullptr) {
Aart Bikb29f6842017-07-28 15:58:41 -0700570 changed = OptimizeInnerLoop(node) || changed;
Aart Bik9abf8942016-10-14 09:49:42 -0700571 }
Aart Bik281c6812016-08-26 11:31:48 -0700572 }
Aart Bikb29f6842017-07-28 15:58:41 -0700573 return changed;
Aart Bik281c6812016-08-26 11:31:48 -0700574}
575
Aart Bikf8f5a162017-02-06 15:35:29 -0800576//
577// Optimization.
578//
579
Aart Bik281c6812016-08-26 11:31:48 -0700580void HLoopOptimization::SimplifyInduction(LoopNode* node) {
581 HBasicBlock* header = node->loop_info->GetHeader();
582 HBasicBlock* preheader = node->loop_info->GetPreHeader();
Aart Bik8c4a8542016-10-06 11:36:57 -0700583 // Scan the phis in the header to find opportunities to simplify an induction
584 // cycle that is only used outside the loop. Replace these uses, if any, with
585 // the last value and remove the induction cycle.
586 // Examples: for (int i = 0; x != null; i++) { .... no i .... }
587 // for (int i = 0; i < 10; i++, k++) { .... no k .... } return k;
Aart Bik281c6812016-08-26 11:31:48 -0700588 for (HInstructionIterator it(header->GetPhis()); !it.Done(); it.Advance()) {
589 HPhi* phi = it.Current()->AsPhi();
Aart Bikf8f5a162017-02-06 15:35:29 -0800590 if (TrySetPhiInduction(phi, /*restrict_uses*/ true) &&
591 TryAssignLastValue(node->loop_info, phi, preheader, /*collect_loop_uses*/ false)) {
Aart Bik671e48a2017-08-09 13:16:56 -0700592 // Note that it's ok to have replaced uses after the loop with the last value, without
593 // being able to remove the cycle. Environment uses (which are the reason we may not be
594 // able to remove the cycle) within the loop will still hold the right value. We must
595 // have tried first, however, to replace outside uses.
596 if (CanRemoveCycle()) {
597 simplified_ = true;
598 for (HInstruction* i : *iset_) {
599 RemoveFromCycle(i);
600 }
601 DCHECK(CheckInductionSetFullyRemoved(iset_));
Aart Bik281c6812016-08-26 11:31:48 -0700602 }
Aart Bik482095d2016-10-10 15:39:10 -0700603 }
604 }
605}
606
607void HLoopOptimization::SimplifyBlocks(LoopNode* node) {
Aart Bikdf7822e2016-12-06 10:05:30 -0800608 // Iterate over all basic blocks in the loop-body.
609 for (HBlocksInLoopIterator it(*node->loop_info); !it.Done(); it.Advance()) {
610 HBasicBlock* block = it.Current();
611 // Remove dead instructions from the loop-body.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800612 RemoveDeadInstructions(block->GetPhis());
613 RemoveDeadInstructions(block->GetInstructions());
Aart Bikdf7822e2016-12-06 10:05:30 -0800614 // Remove trivial control flow blocks from the loop-body.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800615 if (block->GetPredecessors().size() == 1 &&
616 block->GetSuccessors().size() == 1 &&
617 block->GetSingleSuccessor()->GetPredecessors().size() == 1) {
Aart Bikdf7822e2016-12-06 10:05:30 -0800618 simplified_ = true;
Aart Bik6b69e0a2017-01-11 10:20:43 -0800619 block->MergeWith(block->GetSingleSuccessor());
Aart Bikdf7822e2016-12-06 10:05:30 -0800620 } else if (block->GetSuccessors().size() == 2) {
621 // Trivial if block can be bypassed to either branch.
622 HBasicBlock* succ0 = block->GetSuccessors()[0];
623 HBasicBlock* succ1 = block->GetSuccessors()[1];
624 HBasicBlock* meet0 = nullptr;
625 HBasicBlock* meet1 = nullptr;
626 if (succ0 != succ1 &&
627 IsGotoBlock(succ0, &meet0) &&
628 IsGotoBlock(succ1, &meet1) &&
629 meet0 == meet1 && // meets again
630 meet0 != block && // no self-loop
631 meet0->GetPhis().IsEmpty()) { // not used for merging
632 simplified_ = true;
633 succ0->DisconnectAndDelete();
634 if (block->Dominates(meet0)) {
635 block->RemoveDominatedBlock(meet0);
636 succ1->AddDominatedBlock(meet0);
637 meet0->SetDominator(succ1);
Aart Bike3dedc52016-11-02 17:50:27 -0700638 }
Aart Bik482095d2016-10-10 15:39:10 -0700639 }
Aart Bik281c6812016-08-26 11:31:48 -0700640 }
Aart Bikdf7822e2016-12-06 10:05:30 -0800641 }
Aart Bik281c6812016-08-26 11:31:48 -0700642}
643
Aart Bikb29f6842017-07-28 15:58:41 -0700644bool HLoopOptimization::OptimizeInnerLoop(LoopNode* node) {
Aart Bik281c6812016-08-26 11:31:48 -0700645 HBasicBlock* header = node->loop_info->GetHeader();
646 HBasicBlock* preheader = node->loop_info->GetPreHeader();
Aart Bik9abf8942016-10-14 09:49:42 -0700647 // Ensure loop header logic is finite.
Aart Bikf8f5a162017-02-06 15:35:29 -0800648 int64_t trip_count = 0;
649 if (!induction_range_.IsFinite(node->loop_info, &trip_count)) {
Aart Bikb29f6842017-07-28 15:58:41 -0700650 return false;
Aart Bik9abf8942016-10-14 09:49:42 -0700651 }
Aart Bik281c6812016-08-26 11:31:48 -0700652 // Ensure there is only a single loop-body (besides the header).
653 HBasicBlock* body = nullptr;
654 for (HBlocksInLoopIterator it(*node->loop_info); !it.Done(); it.Advance()) {
655 if (it.Current() != header) {
656 if (body != nullptr) {
Aart Bikb29f6842017-07-28 15:58:41 -0700657 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700658 }
659 body = it.Current();
660 }
661 }
Andreas Gampef45d61c2017-06-07 10:29:33 -0700662 CHECK(body != nullptr);
Aart Bik281c6812016-08-26 11:31:48 -0700663 // Ensure there is only a single exit point.
664 if (header->GetSuccessors().size() != 2) {
Aart Bikb29f6842017-07-28 15:58:41 -0700665 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700666 }
667 HBasicBlock* exit = (header->GetSuccessors()[0] == body)
668 ? header->GetSuccessors()[1]
669 : header->GetSuccessors()[0];
Aart Bik8c4a8542016-10-06 11:36:57 -0700670 // Ensure exit can only be reached by exiting loop.
Aart Bik281c6812016-08-26 11:31:48 -0700671 if (exit->GetPredecessors().size() != 1) {
Aart Bikb29f6842017-07-28 15:58:41 -0700672 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700673 }
Aart Bik6b69e0a2017-01-11 10:20:43 -0800674 // Detect either an empty loop (no side effects other than plain iteration) or
675 // a trivial loop (just iterating once). Replace subsequent index uses, if any,
676 // with the last value and remove the loop, possibly after unrolling its body.
Aart Bikb29f6842017-07-28 15:58:41 -0700677 HPhi* main_phi = nullptr;
678 if (TrySetSimpleLoopHeader(header, &main_phi)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -0800679 bool is_empty = IsEmptyBody(body);
Aart Bikb29f6842017-07-28 15:58:41 -0700680 if (reductions_->empty() && // TODO: possible with some effort
681 (is_empty || trip_count == 1) &&
682 TryAssignLastValue(node->loop_info, main_phi, preheader, /*collect_loop_uses*/ true)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -0800683 if (!is_empty) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800684 // Unroll the loop-body, which sees initial value of the index.
Aart Bikb29f6842017-07-28 15:58:41 -0700685 main_phi->ReplaceWith(main_phi->InputAt(0));
Aart Bik6b69e0a2017-01-11 10:20:43 -0800686 preheader->MergeInstructionsWith(body);
687 }
688 body->DisconnectAndDelete();
689 exit->RemovePredecessor(header);
690 header->RemoveSuccessor(exit);
691 header->RemoveDominatedBlock(exit);
692 header->DisconnectAndDelete();
693 preheader->AddSuccessor(exit);
Aart Bikf8f5a162017-02-06 15:35:29 -0800694 preheader->AddInstruction(new (global_allocator_) HGoto());
Aart Bik6b69e0a2017-01-11 10:20:43 -0800695 preheader->AddDominatedBlock(exit);
696 exit->SetDominator(preheader);
697 RemoveLoop(node); // update hierarchy
Aart Bikb29f6842017-07-28 15:58:41 -0700698 return true;
Aart Bikf8f5a162017-02-06 15:35:29 -0800699 }
700 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800701 // Vectorize loop, if possible and valid.
Aart Bikb29f6842017-07-28 15:58:41 -0700702 if (kEnableVectorization &&
703 TrySetSimpleLoopHeader(header, &main_phi) &&
Aart Bikb29f6842017-07-28 15:58:41 -0700704 ShouldVectorize(node, body, trip_count) &&
705 TryAssignLastValue(node->loop_info, main_phi, preheader, /*collect_loop_uses*/ true)) {
706 Vectorize(node, body, exit, trip_count);
707 graph_->SetHasSIMD(true); // flag SIMD usage
Aart Bik21b85922017-09-06 13:29:16 -0700708 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorized);
Aart Bikb29f6842017-07-28 15:58:41 -0700709 return true;
Aart Bikf8f5a162017-02-06 15:35:29 -0800710 }
Aart Bikb29f6842017-07-28 15:58:41 -0700711 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -0800712}
713
714//
715// Loop vectorization. The implementation is based on the book by Aart J.C. Bik:
716// "The Software Vectorization Handbook. Applying Multimedia Extensions for Maximum Performance."
717// Intel Press, June, 2004 (http://www.aartbik.com/).
718//
719
Aart Bik14a68b42017-06-08 14:06:58 -0700720bool HLoopOptimization::ShouldVectorize(LoopNode* node, HBasicBlock* block, int64_t trip_count) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800721 // Reset vector bookkeeping.
722 vector_length_ = 0;
723 vector_refs_->clear();
Aart Bik14a68b42017-06-08 14:06:58 -0700724 vector_peeling_candidate_ = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800725 vector_runtime_test_a_ =
726 vector_runtime_test_b_= nullptr;
727
728 // Phis in the loop-body prevent vectorization.
729 if (!block->GetPhis().IsEmpty()) {
730 return false;
731 }
732
733 // Scan the loop-body, starting a right-hand-side tree traversal at each left-hand-side
734 // occurrence, which allows passing down attributes down the use tree.
735 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
736 if (!VectorizeDef(node, it.Current(), /*generate_code*/ false)) {
737 return false; // failure to vectorize a left-hand-side
738 }
739 }
740
Aart Bik14a68b42017-06-08 14:06:58 -0700741 // Does vectorization seem profitable?
742 if (!IsVectorizationProfitable(trip_count)) {
743 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -0800744 }
745
746 // Data dependence analysis. Find each pair of references with same type, where
747 // at least one is a write. Each such pair denotes a possible data dependence.
748 // This analysis exploits the property that differently typed arrays cannot be
749 // aliased, as well as the property that references either point to the same
750 // array or to two completely disjoint arrays, i.e., no partial aliasing.
751 // Other than a few simply heuristics, no detailed subscript analysis is done.
Aart Bikb29f6842017-07-28 15:58:41 -0700752 // The scan over references also finds a suitable dynamic loop peeling candidate.
753 const ArrayReference* candidate = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800754 for (auto i = vector_refs_->begin(); i != vector_refs_->end(); ++i) {
755 for (auto j = i; ++j != vector_refs_->end(); ) {
756 if (i->type == j->type && (i->lhs || j->lhs)) {
757 // Found same-typed a[i+x] vs. b[i+y], where at least one is a write.
758 HInstruction* a = i->base;
759 HInstruction* b = j->base;
760 HInstruction* x = i->offset;
761 HInstruction* y = j->offset;
762 if (a == b) {
763 // Found a[i+x] vs. a[i+y]. Accept if x == y (loop-independent data dependence).
764 // Conservatively assume a loop-carried data dependence otherwise, and reject.
765 if (x != y) {
766 return false;
767 }
768 } else {
769 // Found a[i+x] vs. b[i+y]. Accept if x == y (at worst loop-independent data dependence).
770 // Conservatively assume a potential loop-carried data dependence otherwise, avoided by
771 // generating an explicit a != b disambiguation runtime test on the two references.
772 if (x != y) {
Aart Bik37dc4df2017-06-28 14:08:00 -0700773 // To avoid excessive overhead, we only accept one a != b test.
774 if (vector_runtime_test_a_ == nullptr) {
775 // First test found.
776 vector_runtime_test_a_ = a;
777 vector_runtime_test_b_ = b;
778 } else if ((vector_runtime_test_a_ != a || vector_runtime_test_b_ != b) &&
779 (vector_runtime_test_a_ != b || vector_runtime_test_b_ != a)) {
780 return false; // second test would be needed
Aart Bikf8f5a162017-02-06 15:35:29 -0800781 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800782 }
783 }
784 }
785 }
786 }
787
Aart Bik14a68b42017-06-08 14:06:58 -0700788 // Consider dynamic loop peeling for alignment.
Aart Bikb29f6842017-07-28 15:58:41 -0700789 SetPeelingCandidate(candidate, trip_count);
Aart Bik14a68b42017-06-08 14:06:58 -0700790
Aart Bikf8f5a162017-02-06 15:35:29 -0800791 // Success!
792 return true;
793}
794
795void HLoopOptimization::Vectorize(LoopNode* node,
796 HBasicBlock* block,
797 HBasicBlock* exit,
798 int64_t trip_count) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800799 HBasicBlock* header = node->loop_info->GetHeader();
800 HBasicBlock* preheader = node->loop_info->GetPreHeader();
801
Aart Bik14a68b42017-06-08 14:06:58 -0700802 // Pick a loop unrolling factor for the vector loop.
803 uint32_t unroll = GetUnrollingFactor(block, trip_count);
804 uint32_t chunk = vector_length_ * unroll;
805
806 // A cleanup loop is needed, at least, for any unknown trip count or
807 // for a known trip count with remainder iterations after vectorization.
808 bool needs_cleanup = trip_count == 0 || (trip_count % chunk) != 0;
Aart Bikf8f5a162017-02-06 15:35:29 -0800809
810 // Adjust vector bookkeeping.
Aart Bikb29f6842017-07-28 15:58:41 -0700811 HPhi* main_phi = nullptr;
812 bool is_simple_loop_header = TrySetSimpleLoopHeader(header, &main_phi); // refills sets
Aart Bikf8f5a162017-02-06 15:35:29 -0800813 DCHECK(is_simple_loop_header);
Aart Bik14a68b42017-06-08 14:06:58 -0700814 vector_header_ = header;
815 vector_body_ = block;
Aart Bikf8f5a162017-02-06 15:35:29 -0800816
Aart Bikdbbac8f2017-09-01 13:06:08 -0700817 // Loop induction type.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100818 DataType::Type induc_type = main_phi->GetType();
819 DCHECK(induc_type == DataType::Type::kInt32 || induc_type == DataType::Type::kInt64)
820 << induc_type;
Aart Bikdbbac8f2017-09-01 13:06:08 -0700821
Aart Bikb29f6842017-07-28 15:58:41 -0700822 // Generate dynamic loop peeling trip count, if needed, under the assumption
823 // that the Android runtime guarantees at least "component size" alignment:
824 // ptc = (ALIGN - (&a[initial] % ALIGN)) / type-size
Aart Bik14a68b42017-06-08 14:06:58 -0700825 HInstruction* ptc = nullptr;
826 if (vector_peeling_candidate_ != nullptr) {
827 DCHECK_LT(vector_length_, trip_count) << "dynamic peeling currently requires known trip count";
828 //
829 // TODO: Implement this. Compute address of first access memory location and
830 // compute peeling factor to obtain kAlignedBase alignment.
831 //
832 needs_cleanup = true;
833 }
834
835 // Generate loop control:
Aart Bikf8f5a162017-02-06 15:35:29 -0800836 // stc = <trip-count>;
Aart Bik14a68b42017-06-08 14:06:58 -0700837 // vtc = stc - (stc - ptc) % chunk;
838 // i = 0;
Aart Bikf8f5a162017-02-06 15:35:29 -0800839 HInstruction* stc = induction_range_.GenerateTripCount(node->loop_info, graph_, preheader);
840 HInstruction* vtc = stc;
841 if (needs_cleanup) {
Aart Bik14a68b42017-06-08 14:06:58 -0700842 DCHECK(IsPowerOfTwo(chunk));
843 HInstruction* diff = stc;
844 if (ptc != nullptr) {
845 diff = Insert(preheader, new (global_allocator_) HSub(induc_type, stc, ptc));
846 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800847 HInstruction* rem = Insert(
848 preheader, new (global_allocator_) HAnd(induc_type,
Aart Bik14a68b42017-06-08 14:06:58 -0700849 diff,
Aart Bikdbbac8f2017-09-01 13:06:08 -0700850 graph_->GetConstant(induc_type, chunk - 1)));
Aart Bikf8f5a162017-02-06 15:35:29 -0800851 vtc = Insert(preheader, new (global_allocator_) HSub(induc_type, stc, rem));
852 }
Aart Bikdbbac8f2017-09-01 13:06:08 -0700853 vector_index_ = graph_->GetConstant(induc_type, 0);
Aart Bikf8f5a162017-02-06 15:35:29 -0800854
855 // Generate runtime disambiguation test:
856 // vtc = a != b ? vtc : 0;
857 if (vector_runtime_test_a_ != nullptr) {
858 HInstruction* rt = Insert(
859 preheader,
860 new (global_allocator_) HNotEqual(vector_runtime_test_a_, vector_runtime_test_b_));
861 vtc = Insert(preheader,
Aart Bikdbbac8f2017-09-01 13:06:08 -0700862 new (global_allocator_)
863 HSelect(rt, vtc, graph_->GetConstant(induc_type, 0), kNoDexPc));
Aart Bikf8f5a162017-02-06 15:35:29 -0800864 needs_cleanup = true;
865 }
866
Aart Bik14a68b42017-06-08 14:06:58 -0700867 // Generate dynamic peeling loop for alignment, if needed:
868 // for ( ; i < ptc; i += 1)
869 // <loop-body>
870 if (ptc != nullptr) {
871 vector_mode_ = kSequential;
872 GenerateNewLoop(node,
873 block,
874 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
875 vector_index_,
876 ptc,
Aart Bikdbbac8f2017-09-01 13:06:08 -0700877 graph_->GetConstant(induc_type, 1),
Aart Bik521b50f2017-09-09 10:44:45 -0700878 kNoUnrollingFactor);
Aart Bik14a68b42017-06-08 14:06:58 -0700879 }
880
881 // Generate vector loop, possibly further unrolled:
882 // for ( ; i < vtc; i += chunk)
Aart Bikf8f5a162017-02-06 15:35:29 -0800883 // <vectorized-loop-body>
884 vector_mode_ = kVector;
885 GenerateNewLoop(node,
886 block,
Aart Bik14a68b42017-06-08 14:06:58 -0700887 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
888 vector_index_,
Aart Bikf8f5a162017-02-06 15:35:29 -0800889 vtc,
Aart Bikdbbac8f2017-09-01 13:06:08 -0700890 graph_->GetConstant(induc_type, vector_length_), // increment per unroll
Aart Bik14a68b42017-06-08 14:06:58 -0700891 unroll);
Aart Bikf8f5a162017-02-06 15:35:29 -0800892 HLoopInformation* vloop = vector_header_->GetLoopInformation();
893
894 // Generate cleanup loop, if needed:
895 // for ( ; i < stc; i += 1)
896 // <loop-body>
897 if (needs_cleanup) {
898 vector_mode_ = kSequential;
899 GenerateNewLoop(node,
900 block,
901 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
Aart Bik14a68b42017-06-08 14:06:58 -0700902 vector_index_,
Aart Bikf8f5a162017-02-06 15:35:29 -0800903 stc,
Aart Bikdbbac8f2017-09-01 13:06:08 -0700904 graph_->GetConstant(induc_type, 1),
Aart Bik521b50f2017-09-09 10:44:45 -0700905 kNoUnrollingFactor);
Aart Bikf8f5a162017-02-06 15:35:29 -0800906 }
907
Aart Bik0148de42017-09-05 09:25:01 -0700908 // Link reductions to their final uses.
909 for (auto i = reductions_->begin(); i != reductions_->end(); ++i) {
910 if (i->first->IsPhi()) {
Aart Bikdbbac8f2017-09-01 13:06:08 -0700911 HInstruction* phi = i->first;
912 HInstruction* repl = ReduceAndExtractIfNeeded(i->second);
913 // Deal with regular uses.
914 for (const HUseListNode<HInstruction*>& use : phi->GetUses()) {
915 induction_range_.Replace(use.GetUser(), phi, repl); // update induction use
916 }
917 phi->ReplaceWith(repl);
Aart Bik0148de42017-09-05 09:25:01 -0700918 }
919 }
920
Aart Bikf8f5a162017-02-06 15:35:29 -0800921 // Remove the original loop by disconnecting the body block
922 // and removing all instructions from the header.
923 block->DisconnectAndDelete();
924 while (!header->GetFirstInstruction()->IsGoto()) {
925 header->RemoveInstruction(header->GetFirstInstruction());
926 }
Aart Bikb29f6842017-07-28 15:58:41 -0700927
Aart Bik14a68b42017-06-08 14:06:58 -0700928 // Update loop hierarchy: the old header now resides in the same outer loop
929 // as the old preheader. Note that we don't bother putting sequential
930 // loops back in the hierarchy at this point.
Aart Bikf8f5a162017-02-06 15:35:29 -0800931 header->SetLoopInformation(preheader->GetLoopInformation()); // outward
932 node->loop_info = vloop;
933}
934
935void HLoopOptimization::GenerateNewLoop(LoopNode* node,
936 HBasicBlock* block,
937 HBasicBlock* new_preheader,
938 HInstruction* lo,
939 HInstruction* hi,
Aart Bik14a68b42017-06-08 14:06:58 -0700940 HInstruction* step,
941 uint32_t unroll) {
942 DCHECK(unroll == 1 || vector_mode_ == kVector);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100943 DataType::Type induc_type = lo->GetType();
Aart Bikf8f5a162017-02-06 15:35:29 -0800944 // Prepare new loop.
Aart Bikf8f5a162017-02-06 15:35:29 -0800945 vector_preheader_ = new_preheader,
946 vector_header_ = vector_preheader_->GetSingleSuccessor();
947 vector_body_ = vector_header_->GetSuccessors()[1];
Aart Bik14a68b42017-06-08 14:06:58 -0700948 HPhi* phi = new (global_allocator_) HPhi(global_allocator_,
949 kNoRegNumber,
950 0,
951 HPhi::ToPhiType(induc_type));
Aart Bikb07d1bc2017-04-05 10:03:15 -0700952 // Generate header and prepare body.
Aart Bikf8f5a162017-02-06 15:35:29 -0800953 // for (i = lo; i < hi; i += step)
954 // <loop-body>
Aart Bik14a68b42017-06-08 14:06:58 -0700955 HInstruction* cond = new (global_allocator_) HAboveOrEqual(phi, hi);
956 vector_header_->AddPhi(phi);
Aart Bikf8f5a162017-02-06 15:35:29 -0800957 vector_header_->AddInstruction(cond);
958 vector_header_->AddInstruction(new (global_allocator_) HIf(cond));
Aart Bik14a68b42017-06-08 14:06:58 -0700959 vector_index_ = phi;
Aart Bik0148de42017-09-05 09:25:01 -0700960 vector_permanent_map_->clear(); // preserved over unrolling
Aart Bik14a68b42017-06-08 14:06:58 -0700961 for (uint32_t u = 0; u < unroll; u++) {
Aart Bik14a68b42017-06-08 14:06:58 -0700962 // Generate instruction map.
Aart Bik0148de42017-09-05 09:25:01 -0700963 vector_map_->clear();
Aart Bik14a68b42017-06-08 14:06:58 -0700964 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
965 bool vectorized_def = VectorizeDef(node, it.Current(), /*generate_code*/ true);
966 DCHECK(vectorized_def);
967 }
968 // Generate body from the instruction map, but in original program order.
969 HEnvironment* env = vector_header_->GetFirstInstruction()->GetEnvironment();
970 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
971 auto i = vector_map_->find(it.Current());
972 if (i != vector_map_->end() && !i->second->IsInBlock()) {
973 Insert(vector_body_, i->second);
974 // Deal with instructions that need an environment, such as the scalar intrinsics.
975 if (i->second->NeedsEnvironment()) {
976 i->second->CopyEnvironmentFromWithLoopPhiAdjustment(env, vector_header_);
977 }
978 }
979 }
Aart Bik0148de42017-09-05 09:25:01 -0700980 // Generate the induction.
Aart Bik14a68b42017-06-08 14:06:58 -0700981 vector_index_ = new (global_allocator_) HAdd(induc_type, vector_index_, step);
982 Insert(vector_body_, vector_index_);
Aart Bikf8f5a162017-02-06 15:35:29 -0800983 }
Aart Bik0148de42017-09-05 09:25:01 -0700984 // Finalize phi inputs for the reductions (if any).
985 for (auto i = reductions_->begin(); i != reductions_->end(); ++i) {
986 if (!i->first->IsPhi()) {
987 DCHECK(i->second->IsPhi());
988 GenerateVecReductionPhiInputs(i->second->AsPhi(), i->first);
989 }
990 }
Aart Bikb29f6842017-07-28 15:58:41 -0700991 // Finalize phi inputs for the loop index.
Aart Bik14a68b42017-06-08 14:06:58 -0700992 phi->AddInput(lo);
993 phi->AddInput(vector_index_);
994 vector_index_ = phi;
Aart Bikf8f5a162017-02-06 15:35:29 -0800995}
996
Aart Bikf8f5a162017-02-06 15:35:29 -0800997bool HLoopOptimization::VectorizeDef(LoopNode* node,
998 HInstruction* instruction,
999 bool generate_code) {
1000 // Accept a left-hand-side array base[index] for
1001 // (1) supported vector type,
1002 // (2) loop-invariant base,
1003 // (3) unit stride index,
1004 // (4) vectorizable right-hand-side value.
1005 uint64_t restrictions = kNone;
1006 if (instruction->IsArraySet()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001007 DataType::Type type = instruction->AsArraySet()->GetComponentType();
Aart Bikf8f5a162017-02-06 15:35:29 -08001008 HInstruction* base = instruction->InputAt(0);
1009 HInstruction* index = instruction->InputAt(1);
1010 HInstruction* value = instruction->InputAt(2);
1011 HInstruction* offset = nullptr;
1012 if (TrySetVectorType(type, &restrictions) &&
1013 node->loop_info->IsDefinedOutOfTheLoop(base) &&
Aart Bik37dc4df2017-06-28 14:08:00 -07001014 induction_range_.IsUnitStride(instruction, index, graph_, &offset) &&
Aart Bikf8f5a162017-02-06 15:35:29 -08001015 VectorizeUse(node, value, generate_code, type, restrictions)) {
1016 if (generate_code) {
1017 GenerateVecSub(index, offset);
Aart Bik14a68b42017-06-08 14:06:58 -07001018 GenerateVecMem(instruction, vector_map_->Get(index), vector_map_->Get(value), offset, type);
Aart Bikf8f5a162017-02-06 15:35:29 -08001019 } else {
1020 vector_refs_->insert(ArrayReference(base, offset, type, /*lhs*/ true));
1021 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08001022 return true;
1023 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001024 return false;
1025 }
Aart Bik0148de42017-09-05 09:25:01 -07001026 // Accept a left-hand-side reduction for
1027 // (1) supported vector type,
1028 // (2) vectorizable right-hand-side value.
1029 auto redit = reductions_->find(instruction);
1030 if (redit != reductions_->end()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001031 DataType::Type type = instruction->GetType();
Aart Bikdbbac8f2017-09-01 13:06:08 -07001032 // Recognize SAD idiom or direct reduction.
1033 if (VectorizeSADIdiom(node, instruction, generate_code, type, restrictions) ||
1034 (TrySetVectorType(type, &restrictions) &&
1035 VectorizeUse(node, instruction, generate_code, type, restrictions))) {
Aart Bik0148de42017-09-05 09:25:01 -07001036 if (generate_code) {
1037 HInstruction* new_red = vector_map_->Get(instruction);
1038 vector_permanent_map_->Put(new_red, vector_map_->Get(redit->second));
1039 vector_permanent_map_->Overwrite(redit->second, new_red);
1040 }
1041 return true;
1042 }
1043 return false;
1044 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001045 // Branch back okay.
1046 if (instruction->IsGoto()) {
1047 return true;
1048 }
1049 // Otherwise accept only expressions with no effects outside the immediate loop-body.
1050 // Note that actual uses are inspected during right-hand-side tree traversal.
1051 return !IsUsedOutsideLoop(node->loop_info, instruction) && !instruction->DoesAnyWrite();
1052}
1053
Aart Bik304c8a52017-05-23 11:01:13 -07001054// TODO: saturation arithmetic.
Aart Bikf8f5a162017-02-06 15:35:29 -08001055bool HLoopOptimization::VectorizeUse(LoopNode* node,
1056 HInstruction* instruction,
1057 bool generate_code,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001058 DataType::Type type,
Aart Bikf8f5a162017-02-06 15:35:29 -08001059 uint64_t restrictions) {
1060 // Accept anything for which code has already been generated.
1061 if (generate_code) {
1062 if (vector_map_->find(instruction) != vector_map_->end()) {
1063 return true;
1064 }
1065 }
1066 // Continue the right-hand-side tree traversal, passing in proper
1067 // types and vector restrictions along the way. During code generation,
1068 // all new nodes are drawn from the global allocator.
1069 if (node->loop_info->IsDefinedOutOfTheLoop(instruction)) {
1070 // Accept invariant use, using scalar expansion.
1071 if (generate_code) {
1072 GenerateVecInv(instruction, type);
1073 }
1074 return true;
1075 } else if (instruction->IsArrayGet()) {
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001076 // Deal with vector restrictions.
1077 if (instruction->AsArrayGet()->IsStringCharAt() &&
1078 HasVectorRestrictions(restrictions, kNoStringCharAt)) {
1079 return false;
1080 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001081 // Accept a right-hand-side array base[index] for
1082 // (1) exact matching vector type,
1083 // (2) loop-invariant base,
1084 // (3) unit stride index,
1085 // (4) vectorizable right-hand-side value.
1086 HInstruction* base = instruction->InputAt(0);
1087 HInstruction* index = instruction->InputAt(1);
1088 HInstruction* offset = nullptr;
1089 if (type == instruction->GetType() &&
1090 node->loop_info->IsDefinedOutOfTheLoop(base) &&
Aart Bik37dc4df2017-06-28 14:08:00 -07001091 induction_range_.IsUnitStride(instruction, index, graph_, &offset)) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001092 if (generate_code) {
1093 GenerateVecSub(index, offset);
Aart Bik14a68b42017-06-08 14:06:58 -07001094 GenerateVecMem(instruction, vector_map_->Get(index), nullptr, offset, type);
Aart Bikf8f5a162017-02-06 15:35:29 -08001095 } else {
1096 vector_refs_->insert(ArrayReference(base, offset, type, /*lhs*/ false));
1097 }
1098 return true;
1099 }
Aart Bik0148de42017-09-05 09:25:01 -07001100 } else if (instruction->IsPhi()) {
1101 // Accept particular phi operations.
1102 if (reductions_->find(instruction) != reductions_->end()) {
1103 // Deal with vector restrictions.
1104 if (HasVectorRestrictions(restrictions, kNoReduction)) {
1105 return false;
1106 }
1107 // Accept a reduction.
1108 if (generate_code) {
1109 GenerateVecReductionPhi(instruction->AsPhi());
1110 }
1111 return true;
1112 }
1113 // TODO: accept right-hand-side induction?
1114 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001115 } else if (instruction->IsTypeConversion()) {
1116 // Accept particular type conversions.
1117 HTypeConversion* conversion = instruction->AsTypeConversion();
1118 HInstruction* opa = conversion->InputAt(0);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001119 DataType::Type from = conversion->GetInputType();
1120 DataType::Type to = conversion->GetResultType();
1121 if (DataType::IsIntegralType(from) && DataType::IsIntegralType(to)) {
1122 size_t size_vec = DataType::Size(type);
1123 size_t size_from = DataType::Size(from);
1124 size_t size_to = DataType::Size(to);
Aart Bikdbbac8f2017-09-01 13:06:08 -07001125 // Accept an integral conversion
1126 // (1a) narrowing into vector type, "wider" operations cannot bring in higher order bits, or
1127 // (1b) widening from at least vector type, and
1128 // (2) vectorizable operand.
1129 if ((size_to < size_from &&
1130 size_to == size_vec &&
1131 VectorizeUse(node, opa, generate_code, type, restrictions | kNoHiBits)) ||
1132 (size_to >= size_from &&
1133 size_from >= size_vec &&
1134 VectorizeUse(node, opa, generate_code, type, restrictions))) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001135 if (generate_code) {
1136 if (vector_mode_ == kVector) {
1137 vector_map_->Put(instruction, vector_map_->Get(opa)); // operand pass-through
1138 } else {
1139 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1140 }
1141 }
1142 return true;
1143 }
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001144 } else if (to == DataType::Type::kFloat32 && from == DataType::Type::kInt32) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001145 DCHECK_EQ(to, type);
1146 // Accept int to float conversion for
1147 // (1) supported int,
1148 // (2) vectorizable operand.
1149 if (TrySetVectorType(from, &restrictions) &&
1150 VectorizeUse(node, opa, generate_code, from, restrictions)) {
1151 if (generate_code) {
1152 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1153 }
1154 return true;
1155 }
1156 }
1157 return false;
1158 } else if (instruction->IsNeg() || instruction->IsNot() || instruction->IsBooleanNot()) {
1159 // Accept unary operator for vectorizable operand.
1160 HInstruction* opa = instruction->InputAt(0);
1161 if (VectorizeUse(node, opa, generate_code, type, restrictions)) {
1162 if (generate_code) {
1163 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1164 }
1165 return true;
1166 }
1167 } else if (instruction->IsAdd() || instruction->IsSub() ||
1168 instruction->IsMul() || instruction->IsDiv() ||
1169 instruction->IsAnd() || instruction->IsOr() || instruction->IsXor()) {
1170 // Deal with vector restrictions.
1171 if ((instruction->IsMul() && HasVectorRestrictions(restrictions, kNoMul)) ||
1172 (instruction->IsDiv() && HasVectorRestrictions(restrictions, kNoDiv))) {
1173 return false;
1174 }
1175 // Accept binary operator for vectorizable operands.
1176 HInstruction* opa = instruction->InputAt(0);
1177 HInstruction* opb = instruction->InputAt(1);
1178 if (VectorizeUse(node, opa, generate_code, type, restrictions) &&
1179 VectorizeUse(node, opb, generate_code, type, restrictions)) {
1180 if (generate_code) {
1181 GenerateVecOp(instruction, vector_map_->Get(opa), vector_map_->Get(opb), type);
1182 }
1183 return true;
1184 }
1185 } else if (instruction->IsShl() || instruction->IsShr() || instruction->IsUShr()) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001186 // Recognize halving add idiom.
Aart Bikf3e61ee2017-04-12 17:09:20 -07001187 if (VectorizeHalvingAddIdiom(node, instruction, generate_code, type, restrictions)) {
1188 return true;
1189 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001190 // Deal with vector restrictions.
Aart Bik304c8a52017-05-23 11:01:13 -07001191 HInstruction* opa = instruction->InputAt(0);
1192 HInstruction* opb = instruction->InputAt(1);
1193 HInstruction* r = opa;
1194 bool is_unsigned = false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001195 if ((HasVectorRestrictions(restrictions, kNoShift)) ||
1196 (instruction->IsShr() && HasVectorRestrictions(restrictions, kNoShr))) {
1197 return false; // unsupported instruction
Aart Bik304c8a52017-05-23 11:01:13 -07001198 } else if (HasVectorRestrictions(restrictions, kNoHiBits)) {
1199 // Shifts right need extra care to account for higher order bits.
1200 // TODO: less likely shr/unsigned and ushr/signed can by flipping signess.
1201 if (instruction->IsShr() &&
1202 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || is_unsigned)) {
1203 return false; // reject, unless all operands are sign-extension narrower
1204 } else if (instruction->IsUShr() &&
1205 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || !is_unsigned)) {
1206 return false; // reject, unless all operands are zero-extension narrower
1207 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001208 }
1209 // Accept shift operator for vectorizable/invariant operands.
1210 // TODO: accept symbolic, albeit loop invariant shift factors.
Aart Bik304c8a52017-05-23 11:01:13 -07001211 DCHECK(r != nullptr);
1212 if (generate_code && vector_mode_ != kVector) { // de-idiom
1213 r = opa;
1214 }
Aart Bik50e20d52017-05-05 14:07:29 -07001215 int64_t distance = 0;
Aart Bik304c8a52017-05-23 11:01:13 -07001216 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
Aart Bik50e20d52017-05-05 14:07:29 -07001217 IsInt64AndGet(opb, /*out*/ &distance)) {
Aart Bik65ffd8e2017-05-01 16:50:45 -07001218 // Restrict shift distance to packed data type width.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001219 int64_t max_distance = DataType::Size(type) * 8;
Aart Bik65ffd8e2017-05-01 16:50:45 -07001220 if (0 <= distance && distance < max_distance) {
1221 if (generate_code) {
Aart Bik304c8a52017-05-23 11:01:13 -07001222 GenerateVecOp(instruction, vector_map_->Get(r), opb, type);
Aart Bik65ffd8e2017-05-01 16:50:45 -07001223 }
1224 return true;
Aart Bikf8f5a162017-02-06 15:35:29 -08001225 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001226 }
1227 } else if (instruction->IsInvokeStaticOrDirect()) {
Aart Bik6daebeb2017-04-03 14:35:41 -07001228 // Accept particular intrinsics.
1229 HInvokeStaticOrDirect* invoke = instruction->AsInvokeStaticOrDirect();
1230 switch (invoke->GetIntrinsic()) {
1231 case Intrinsics::kMathAbsInt:
1232 case Intrinsics::kMathAbsLong:
1233 case Intrinsics::kMathAbsFloat:
1234 case Intrinsics::kMathAbsDouble: {
1235 // Deal with vector restrictions.
Aart Bik304c8a52017-05-23 11:01:13 -07001236 HInstruction* opa = instruction->InputAt(0);
1237 HInstruction* r = opa;
1238 bool is_unsigned = false;
1239 if (HasVectorRestrictions(restrictions, kNoAbs)) {
Aart Bik6daebeb2017-04-03 14:35:41 -07001240 return false;
Aart Bik304c8a52017-05-23 11:01:13 -07001241 } else if (HasVectorRestrictions(restrictions, kNoHiBits) &&
1242 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || is_unsigned)) {
1243 return false; // reject, unless operand is sign-extension narrower
Aart Bik6daebeb2017-04-03 14:35:41 -07001244 }
1245 // Accept ABS(x) for vectorizable operand.
Aart Bik304c8a52017-05-23 11:01:13 -07001246 DCHECK(r != nullptr);
1247 if (generate_code && vector_mode_ != kVector) { // de-idiom
1248 r = opa;
1249 }
1250 if (VectorizeUse(node, r, generate_code, type, restrictions)) {
Aart Bik6daebeb2017-04-03 14:35:41 -07001251 if (generate_code) {
Aart Bik304c8a52017-05-23 11:01:13 -07001252 GenerateVecOp(instruction, vector_map_->Get(r), nullptr, type);
Aart Bik6daebeb2017-04-03 14:35:41 -07001253 }
1254 return true;
1255 }
1256 return false;
1257 }
Aart Bikc8e93c72017-05-10 10:49:22 -07001258 case Intrinsics::kMathMinIntInt:
1259 case Intrinsics::kMathMinLongLong:
1260 case Intrinsics::kMathMinFloatFloat:
1261 case Intrinsics::kMathMinDoubleDouble:
1262 case Intrinsics::kMathMaxIntInt:
1263 case Intrinsics::kMathMaxLongLong:
1264 case Intrinsics::kMathMaxFloatFloat:
1265 case Intrinsics::kMathMaxDoubleDouble: {
1266 // Deal with vector restrictions.
Nicolas Geoffray92316902017-05-23 08:06:07 +00001267 HInstruction* opa = instruction->InputAt(0);
1268 HInstruction* opb = instruction->InputAt(1);
Aart Bik304c8a52017-05-23 11:01:13 -07001269 HInstruction* r = opa;
1270 HInstruction* s = opb;
1271 bool is_unsigned = false;
1272 if (HasVectorRestrictions(restrictions, kNoMinMax)) {
1273 return false;
1274 } else if (HasVectorRestrictions(restrictions, kNoHiBits) &&
1275 !IsNarrowerOperands(opa, opb, type, &r, &s, &is_unsigned)) {
1276 return false; // reject, unless all operands are same-extension narrower
1277 }
1278 // Accept MIN/MAX(x, y) for vectorizable operands.
Aart Bikdbbac8f2017-09-01 13:06:08 -07001279 DCHECK(r != nullptr);
1280 DCHECK(s != nullptr);
Aart Bik304c8a52017-05-23 11:01:13 -07001281 if (generate_code && vector_mode_ != kVector) { // de-idiom
1282 r = opa;
1283 s = opb;
1284 }
1285 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
1286 VectorizeUse(node, s, generate_code, type, restrictions)) {
Aart Bikc8e93c72017-05-10 10:49:22 -07001287 if (generate_code) {
Aart Bik304c8a52017-05-23 11:01:13 -07001288 GenerateVecOp(
1289 instruction, vector_map_->Get(r), vector_map_->Get(s), type, is_unsigned);
Aart Bikc8e93c72017-05-10 10:49:22 -07001290 }
1291 return true;
1292 }
1293 return false;
1294 }
Aart Bik6daebeb2017-04-03 14:35:41 -07001295 default:
1296 return false;
1297 } // switch
Aart Bik281c6812016-08-26 11:31:48 -07001298 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08001299 return false;
Aart Bik281c6812016-08-26 11:31:48 -07001300}
1301
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001302bool HLoopOptimization::TrySetVectorType(DataType::Type type, uint64_t* restrictions) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001303 const InstructionSetFeatures* features = compiler_driver_->GetInstructionSetFeatures();
1304 switch (compiler_driver_->GetInstructionSet()) {
1305 case kArm:
1306 case kThumb2:
Artem Serov8f7c4102017-06-21 11:21:37 +01001307 // Allow vectorization for all ARM devices, because Android assumes that
Aart Bikb29f6842017-07-28 15:58:41 -07001308 // ARM 32-bit always supports advanced SIMD (64-bit SIMD).
Artem Serov8f7c4102017-06-21 11:21:37 +01001309 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001310 case DataType::Type::kBool:
1311 case DataType::Type::kInt8:
Aart Bik0148de42017-09-05 09:25:01 -07001312 *restrictions |= kNoDiv | kNoReduction;
Artem Serov8f7c4102017-06-21 11:21:37 +01001313 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001314 case DataType::Type::kUint16:
1315 case DataType::Type::kInt16:
Aart Bik0148de42017-09-05 09:25:01 -07001316 *restrictions |= kNoDiv | kNoStringCharAt | kNoReduction;
Artem Serov8f7c4102017-06-21 11:21:37 +01001317 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001318 case DataType::Type::kInt32:
Aart Bik0148de42017-09-05 09:25:01 -07001319 *restrictions |= kNoDiv | kNoReduction;
Artem Serov8f7c4102017-06-21 11:21:37 +01001320 return TrySetVectorLength(2);
1321 default:
1322 break;
1323 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001324 return false;
1325 case kArm64:
1326 // Allow vectorization for all ARM devices, because Android assumes that
Aart Bikb29f6842017-07-28 15:58:41 -07001327 // ARMv8 AArch64 always supports advanced SIMD (128-bit SIMD).
Aart Bikf8f5a162017-02-06 15:35:29 -08001328 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001329 case DataType::Type::kBool:
1330 case DataType::Type::kInt8:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001331 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +01001332 return TrySetVectorLength(16);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001333 case DataType::Type::kUint16:
1334 case DataType::Type::kInt16:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001335 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +01001336 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001337 case DataType::Type::kInt32:
Aart Bikf8f5a162017-02-06 15:35:29 -08001338 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +01001339 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001340 case DataType::Type::kInt64:
Aart Bikc8e93c72017-05-10 10:49:22 -07001341 *restrictions |= kNoDiv | kNoMul | kNoMinMax;
Aart Bikf8f5a162017-02-06 15:35:29 -08001342 return TrySetVectorLength(2);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001343 case DataType::Type::kFloat32:
Aart Bik0148de42017-09-05 09:25:01 -07001344 *restrictions |= kNoReduction;
Artem Serovd4bccf12017-04-03 18:47:32 +01001345 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001346 case DataType::Type::kFloat64:
Aart Bik0148de42017-09-05 09:25:01 -07001347 *restrictions |= kNoReduction;
Aart Bikf8f5a162017-02-06 15:35:29 -08001348 return TrySetVectorLength(2);
1349 default:
1350 return false;
1351 }
1352 case kX86:
1353 case kX86_64:
Aart Bikb29f6842017-07-28 15:58:41 -07001354 // Allow vectorization for SSE4.1-enabled X86 devices only (128-bit SIMD).
Aart Bikf8f5a162017-02-06 15:35:29 -08001355 if (features->AsX86InstructionSetFeatures()->HasSSE4_1()) {
1356 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001357 case DataType::Type::kBool:
1358 case DataType::Type::kInt8:
Aart Bik0148de42017-09-05 09:25:01 -07001359 *restrictions |=
Aart Bikdbbac8f2017-09-01 13:06:08 -07001360 kNoMul | kNoDiv | kNoShift | kNoAbs | kNoSignedHAdd | kNoUnroundedHAdd | kNoSAD;
Aart Bikf8f5a162017-02-06 15:35:29 -08001361 return TrySetVectorLength(16);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001362 case DataType::Type::kUint16:
1363 case DataType::Type::kInt16:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001364 *restrictions |= kNoDiv | kNoAbs | kNoSignedHAdd | kNoUnroundedHAdd | kNoSAD;
Aart Bikf8f5a162017-02-06 15:35:29 -08001365 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001366 case DataType::Type::kInt32:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001367 *restrictions |= kNoDiv | kNoSAD;
Aart Bikf8f5a162017-02-06 15:35:29 -08001368 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001369 case DataType::Type::kInt64:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001370 *restrictions |= kNoMul | kNoDiv | kNoShr | kNoAbs | kNoMinMax | kNoSAD;
Aart Bikf8f5a162017-02-06 15:35:29 -08001371 return TrySetVectorLength(2);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001372 case DataType::Type::kFloat32:
Aart Bik0148de42017-09-05 09:25:01 -07001373 *restrictions |= kNoMinMax | kNoReduction; // minmax: -0.0 vs +0.0
Aart Bikf8f5a162017-02-06 15:35:29 -08001374 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001375 case DataType::Type::kFloat64:
Aart Bik0148de42017-09-05 09:25:01 -07001376 *restrictions |= kNoMinMax | kNoReduction; // minmax: -0.0 vs +0.0
Aart Bikf8f5a162017-02-06 15:35:29 -08001377 return TrySetVectorLength(2);
1378 default:
1379 break;
1380 } // switch type
1381 }
1382 return false;
1383 case kMips:
Lena Djokic51765b02017-06-22 13:49:59 +02001384 if (features->AsMipsInstructionSetFeatures()->HasMsa()) {
1385 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001386 case DataType::Type::kBool:
1387 case DataType::Type::kInt8:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001388 *restrictions |= kNoDiv | kNoReduction | kNoSAD;
Lena Djokic51765b02017-06-22 13:49:59 +02001389 return TrySetVectorLength(16);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001390 case DataType::Type::kUint16:
1391 case DataType::Type::kInt16:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001392 *restrictions |= kNoDiv | kNoStringCharAt | kNoReduction | kNoSAD;
Lena Djokic51765b02017-06-22 13:49:59 +02001393 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001394 case DataType::Type::kInt32:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001395 *restrictions |= kNoDiv | kNoReduction | kNoSAD;
Lena Djokic51765b02017-06-22 13:49:59 +02001396 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001397 case DataType::Type::kInt64:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001398 *restrictions |= kNoDiv | kNoReduction | kNoSAD;
Lena Djokic51765b02017-06-22 13:49:59 +02001399 return TrySetVectorLength(2);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001400 case DataType::Type::kFloat32:
Aart Bik0148de42017-09-05 09:25:01 -07001401 *restrictions |= kNoMinMax | kNoReduction; // min/max(x, NaN)
Lena Djokic51765b02017-06-22 13:49:59 +02001402 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001403 case DataType::Type::kFloat64:
Aart Bik0148de42017-09-05 09:25:01 -07001404 *restrictions |= kNoMinMax | kNoReduction; // min/max(x, NaN)
Lena Djokic51765b02017-06-22 13:49:59 +02001405 return TrySetVectorLength(2);
1406 default:
1407 break;
1408 } // switch type
1409 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001410 return false;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001411 case kMips64:
1412 if (features->AsMips64InstructionSetFeatures()->HasMsa()) {
1413 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001414 case DataType::Type::kBool:
1415 case DataType::Type::kInt8:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001416 *restrictions |= kNoDiv | kNoReduction | kNoSAD;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001417 return TrySetVectorLength(16);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001418 case DataType::Type::kUint16:
1419 case DataType::Type::kInt16:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001420 *restrictions |= kNoDiv | kNoStringCharAt | kNoReduction | kNoSAD;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001421 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001422 case DataType::Type::kInt32:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001423 *restrictions |= kNoDiv | kNoReduction | kNoSAD;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001424 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001425 case DataType::Type::kInt64:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001426 *restrictions |= kNoDiv | kNoReduction | kNoSAD;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001427 return TrySetVectorLength(2);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001428 case DataType::Type::kFloat32:
Aart Bik0148de42017-09-05 09:25:01 -07001429 *restrictions |= kNoMinMax | kNoReduction; // min/max(x, NaN)
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001430 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001431 case DataType::Type::kFloat64:
Aart Bik0148de42017-09-05 09:25:01 -07001432 *restrictions |= kNoMinMax | kNoReduction; // min/max(x, NaN)
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001433 return TrySetVectorLength(2);
1434 default:
1435 break;
1436 } // switch type
1437 }
1438 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001439 default:
1440 return false;
1441 } // switch instruction set
1442}
1443
1444bool HLoopOptimization::TrySetVectorLength(uint32_t length) {
1445 DCHECK(IsPowerOfTwo(length) && length >= 2u);
1446 // First time set?
1447 if (vector_length_ == 0) {
1448 vector_length_ = length;
1449 }
1450 // Different types are acceptable within a loop-body, as long as all the corresponding vector
1451 // lengths match exactly to obtain a uniform traversal through the vector iteration space
1452 // (idiomatic exceptions to this rule can be handled by further unrolling sub-expressions).
1453 return vector_length_ == length;
1454}
1455
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001456void HLoopOptimization::GenerateVecInv(HInstruction* org, DataType::Type type) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001457 if (vector_map_->find(org) == vector_map_->end()) {
1458 // In scalar code, just use a self pass-through for scalar invariants
1459 // (viz. expression remains itself).
1460 if (vector_mode_ == kSequential) {
1461 vector_map_->Put(org, org);
1462 return;
1463 }
1464 // In vector code, explicit scalar expansion is needed.
Aart Bik0148de42017-09-05 09:25:01 -07001465 HInstruction* vector = nullptr;
1466 auto it = vector_permanent_map_->find(org);
1467 if (it != vector_permanent_map_->end()) {
1468 vector = it->second; // reuse during unrolling
1469 } else {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001470 // Generates ReplicateScalar( (optional_type_conv) org ).
1471 HInstruction* input = org;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001472 DataType::Type input_type = input->GetType();
1473 if (type != input_type && (type == DataType::Type::kInt64 ||
1474 input_type == DataType::Type::kInt64)) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001475 input = Insert(vector_preheader_,
1476 new (global_allocator_) HTypeConversion(type, input, kNoDexPc));
1477 }
1478 vector = new (global_allocator_)
1479 HVecReplicateScalar(global_allocator_, input, type, vector_length_);
Aart Bik0148de42017-09-05 09:25:01 -07001480 vector_permanent_map_->Put(org, Insert(vector_preheader_, vector));
1481 }
1482 vector_map_->Put(org, vector);
Aart Bikf8f5a162017-02-06 15:35:29 -08001483 }
1484}
1485
1486void HLoopOptimization::GenerateVecSub(HInstruction* org, HInstruction* offset) {
1487 if (vector_map_->find(org) == vector_map_->end()) {
Aart Bik14a68b42017-06-08 14:06:58 -07001488 HInstruction* subscript = vector_index_;
Aart Bik37dc4df2017-06-28 14:08:00 -07001489 int64_t value = 0;
1490 if (!IsInt64AndGet(offset, &value) || value != 0) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001491 subscript = new (global_allocator_) HAdd(DataType::Type::kInt32, subscript, offset);
Aart Bikf8f5a162017-02-06 15:35:29 -08001492 if (org->IsPhi()) {
1493 Insert(vector_body_, subscript); // lacks layout placeholder
1494 }
1495 }
1496 vector_map_->Put(org, subscript);
1497 }
1498}
1499
1500void HLoopOptimization::GenerateVecMem(HInstruction* org,
1501 HInstruction* opa,
1502 HInstruction* opb,
Aart Bik14a68b42017-06-08 14:06:58 -07001503 HInstruction* offset,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001504 DataType::Type type) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001505 HInstruction* vector = nullptr;
1506 if (vector_mode_ == kVector) {
1507 // Vector store or load.
Aart Bik14a68b42017-06-08 14:06:58 -07001508 HInstruction* base = org->InputAt(0);
Aart Bikf8f5a162017-02-06 15:35:29 -08001509 if (opb != nullptr) {
1510 vector = new (global_allocator_) HVecStore(
Aart Bik14a68b42017-06-08 14:06:58 -07001511 global_allocator_, base, opa, opb, type, vector_length_);
Aart Bikf8f5a162017-02-06 15:35:29 -08001512 } else {
Aart Bikdb14fcf2017-04-25 15:53:58 -07001513 bool is_string_char_at = org->AsArrayGet()->IsStringCharAt();
Aart Bikf8f5a162017-02-06 15:35:29 -08001514 vector = new (global_allocator_) HVecLoad(
Aart Bik14a68b42017-06-08 14:06:58 -07001515 global_allocator_, base, opa, type, vector_length_, is_string_char_at);
1516 }
1517 // Known dynamically enforced alignment?
Aart Bik14a68b42017-06-08 14:06:58 -07001518 if (vector_peeling_candidate_ != nullptr &&
1519 vector_peeling_candidate_->base == base &&
1520 vector_peeling_candidate_->offset == offset) {
1521 vector->AsVecMemoryOperation()->SetAlignment(Alignment(kAlignedBase, 0));
Aart Bikf8f5a162017-02-06 15:35:29 -08001522 }
1523 } else {
1524 // Scalar store or load.
1525 DCHECK(vector_mode_ == kSequential);
1526 if (opb != nullptr) {
1527 vector = new (global_allocator_) HArraySet(org->InputAt(0), opa, opb, type, kNoDexPc);
1528 } else {
Aart Bikdb14fcf2017-04-25 15:53:58 -07001529 bool is_string_char_at = org->AsArrayGet()->IsStringCharAt();
1530 vector = new (global_allocator_) HArrayGet(
1531 org->InputAt(0), opa, type, kNoDexPc, is_string_char_at);
Aart Bikf8f5a162017-02-06 15:35:29 -08001532 }
1533 }
1534 vector_map_->Put(org, vector);
1535}
1536
Aart Bik0148de42017-09-05 09:25:01 -07001537void HLoopOptimization::GenerateVecReductionPhi(HPhi* phi) {
1538 DCHECK(reductions_->find(phi) != reductions_->end());
1539 DCHECK(reductions_->Get(phi->InputAt(1)) == phi);
1540 HInstruction* vector = nullptr;
1541 if (vector_mode_ == kSequential) {
1542 HPhi* new_phi = new (global_allocator_) HPhi(
1543 global_allocator_, kNoRegNumber, 0, phi->GetType());
1544 vector_header_->AddPhi(new_phi);
1545 vector = new_phi;
1546 } else {
1547 // Link vector reduction back to prior unrolled update, or a first phi.
1548 auto it = vector_permanent_map_->find(phi);
1549 if (it != vector_permanent_map_->end()) {
1550 vector = it->second;
1551 } else {
1552 HPhi* new_phi = new (global_allocator_) HPhi(
1553 global_allocator_, kNoRegNumber, 0, HVecOperation::kSIMDType);
1554 vector_header_->AddPhi(new_phi);
1555 vector = new_phi;
1556 }
1557 }
1558 vector_map_->Put(phi, vector);
1559}
1560
1561void HLoopOptimization::GenerateVecReductionPhiInputs(HPhi* phi, HInstruction* reduction) {
1562 HInstruction* new_phi = vector_map_->Get(phi);
1563 HInstruction* new_init = reductions_->Get(phi);
1564 HInstruction* new_red = vector_map_->Get(reduction);
1565 // Link unrolled vector loop back to new phi.
1566 for (; !new_phi->IsPhi(); new_phi = vector_permanent_map_->Get(new_phi)) {
1567 DCHECK(new_phi->IsVecOperation());
1568 }
1569 // Prepare the new initialization.
1570 if (vector_mode_ == kVector) {
1571 // Generate a [initial, 0, .., 0] vector.
Aart Bikdbbac8f2017-09-01 13:06:08 -07001572 HVecOperation* red_vector = new_red->AsVecOperation();
1573 size_t vector_length = red_vector->GetVectorLength();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001574 DataType::Type type = red_vector->GetPackedType();
Aart Bikdbbac8f2017-09-01 13:06:08 -07001575 new_init = Insert(vector_preheader_,
1576 new (global_allocator_) HVecSetScalars(global_allocator_,
1577 &new_init,
1578 type,
1579 vector_length,
1580 1));
Aart Bik0148de42017-09-05 09:25:01 -07001581 } else {
1582 new_init = ReduceAndExtractIfNeeded(new_init);
1583 }
1584 // Set the phi inputs.
1585 DCHECK(new_phi->IsPhi());
1586 new_phi->AsPhi()->AddInput(new_init);
1587 new_phi->AsPhi()->AddInput(new_red);
1588 // New feed value for next phi (safe mutation in iteration).
1589 reductions_->find(phi)->second = new_phi;
1590}
1591
1592HInstruction* HLoopOptimization::ReduceAndExtractIfNeeded(HInstruction* instruction) {
1593 if (instruction->IsPhi()) {
1594 HInstruction* input = instruction->InputAt(1);
1595 if (input->IsVecOperation()) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001596 HVecOperation* input_vector = input->AsVecOperation();
1597 size_t vector_length = input_vector->GetVectorLength();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001598 DataType::Type type = input_vector->GetPackedType();
Aart Bikdbbac8f2017-09-01 13:06:08 -07001599 HVecReduce::ReductionKind kind = GetReductionKind(input_vector);
Aart Bik0148de42017-09-05 09:25:01 -07001600 HBasicBlock* exit = instruction->GetBlock()->GetSuccessors()[0];
1601 // Generate a vector reduction and scalar extract
1602 // x = REDUCE( [x_1, .., x_n] )
1603 // y = x_1
1604 // along the exit of the defining loop.
Aart Bik0148de42017-09-05 09:25:01 -07001605 HInstruction* reduce = new (global_allocator_) HVecReduce(
Aart Bikdbbac8f2017-09-01 13:06:08 -07001606 global_allocator_, instruction, type, vector_length, kind);
Aart Bik0148de42017-09-05 09:25:01 -07001607 exit->InsertInstructionBefore(reduce, exit->GetFirstInstruction());
1608 instruction = new (global_allocator_) HVecExtractScalar(
Aart Bikdbbac8f2017-09-01 13:06:08 -07001609 global_allocator_, reduce, type, vector_length, 0);
Aart Bik0148de42017-09-05 09:25:01 -07001610 exit->InsertInstructionAfter(instruction, reduce);
1611 }
1612 }
1613 return instruction;
1614}
1615
Aart Bikf8f5a162017-02-06 15:35:29 -08001616#define GENERATE_VEC(x, y) \
1617 if (vector_mode_ == kVector) { \
1618 vector = (x); \
1619 } else { \
1620 DCHECK(vector_mode_ == kSequential); \
1621 vector = (y); \
1622 } \
1623 break;
1624
1625void HLoopOptimization::GenerateVecOp(HInstruction* org,
1626 HInstruction* opa,
1627 HInstruction* opb,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001628 DataType::Type type,
Aart Bik304c8a52017-05-23 11:01:13 -07001629 bool is_unsigned) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001630 HInstruction* vector = nullptr;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001631 DataType::Type org_type = org->GetType();
Aart Bikf8f5a162017-02-06 15:35:29 -08001632 switch (org->GetKind()) {
1633 case HInstruction::kNeg:
1634 DCHECK(opb == nullptr);
1635 GENERATE_VEC(
1636 new (global_allocator_) HVecNeg(global_allocator_, opa, type, vector_length_),
Aart Bikdbbac8f2017-09-01 13:06:08 -07001637 new (global_allocator_) HNeg(org_type, opa));
Aart Bikf8f5a162017-02-06 15:35:29 -08001638 case HInstruction::kNot:
1639 DCHECK(opb == nullptr);
1640 GENERATE_VEC(
1641 new (global_allocator_) HVecNot(global_allocator_, opa, type, vector_length_),
Aart Bikdbbac8f2017-09-01 13:06:08 -07001642 new (global_allocator_) HNot(org_type, opa));
Aart Bikf8f5a162017-02-06 15:35:29 -08001643 case HInstruction::kBooleanNot:
1644 DCHECK(opb == nullptr);
1645 GENERATE_VEC(
1646 new (global_allocator_) HVecNot(global_allocator_, opa, type, vector_length_),
1647 new (global_allocator_) HBooleanNot(opa));
1648 case HInstruction::kTypeConversion:
1649 DCHECK(opb == nullptr);
1650 GENERATE_VEC(
1651 new (global_allocator_) HVecCnv(global_allocator_, opa, type, vector_length_),
Aart Bikdbbac8f2017-09-01 13:06:08 -07001652 new (global_allocator_) HTypeConversion(org_type, opa, kNoDexPc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001653 case HInstruction::kAdd:
1654 GENERATE_VEC(
1655 new (global_allocator_) HVecAdd(global_allocator_, opa, opb, type, vector_length_),
Aart Bikdbbac8f2017-09-01 13:06:08 -07001656 new (global_allocator_) HAdd(org_type, opa, opb));
Aart Bikf8f5a162017-02-06 15:35:29 -08001657 case HInstruction::kSub:
1658 GENERATE_VEC(
1659 new (global_allocator_) HVecSub(global_allocator_, opa, opb, type, vector_length_),
Aart Bikdbbac8f2017-09-01 13:06:08 -07001660 new (global_allocator_) HSub(org_type, opa, opb));
Aart Bikf8f5a162017-02-06 15:35:29 -08001661 case HInstruction::kMul:
1662 GENERATE_VEC(
1663 new (global_allocator_) HVecMul(global_allocator_, opa, opb, type, vector_length_),
Aart Bikdbbac8f2017-09-01 13:06:08 -07001664 new (global_allocator_) HMul(org_type, opa, opb));
Aart Bikf8f5a162017-02-06 15:35:29 -08001665 case HInstruction::kDiv:
1666 GENERATE_VEC(
1667 new (global_allocator_) HVecDiv(global_allocator_, opa, opb, type, vector_length_),
Aart Bikdbbac8f2017-09-01 13:06:08 -07001668 new (global_allocator_) HDiv(org_type, opa, opb, kNoDexPc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001669 case HInstruction::kAnd:
1670 GENERATE_VEC(
1671 new (global_allocator_) HVecAnd(global_allocator_, opa, opb, type, vector_length_),
Aart Bikdbbac8f2017-09-01 13:06:08 -07001672 new (global_allocator_) HAnd(org_type, opa, opb));
Aart Bikf8f5a162017-02-06 15:35:29 -08001673 case HInstruction::kOr:
1674 GENERATE_VEC(
1675 new (global_allocator_) HVecOr(global_allocator_, opa, opb, type, vector_length_),
Aart Bikdbbac8f2017-09-01 13:06:08 -07001676 new (global_allocator_) HOr(org_type, opa, opb));
Aart Bikf8f5a162017-02-06 15:35:29 -08001677 case HInstruction::kXor:
1678 GENERATE_VEC(
1679 new (global_allocator_) HVecXor(global_allocator_, opa, opb, type, vector_length_),
Aart Bikdbbac8f2017-09-01 13:06:08 -07001680 new (global_allocator_) HXor(org_type, opa, opb));
Aart Bikf8f5a162017-02-06 15:35:29 -08001681 case HInstruction::kShl:
1682 GENERATE_VEC(
1683 new (global_allocator_) HVecShl(global_allocator_, opa, opb, type, vector_length_),
Aart Bikdbbac8f2017-09-01 13:06:08 -07001684 new (global_allocator_) HShl(org_type, opa, opb));
Aart Bikf8f5a162017-02-06 15:35:29 -08001685 case HInstruction::kShr:
1686 GENERATE_VEC(
1687 new (global_allocator_) HVecShr(global_allocator_, opa, opb, type, vector_length_),
Aart Bikdbbac8f2017-09-01 13:06:08 -07001688 new (global_allocator_) HShr(org_type, opa, opb));
Aart Bikf8f5a162017-02-06 15:35:29 -08001689 case HInstruction::kUShr:
1690 GENERATE_VEC(
1691 new (global_allocator_) HVecUShr(global_allocator_, opa, opb, type, vector_length_),
Aart Bikdbbac8f2017-09-01 13:06:08 -07001692 new (global_allocator_) HUShr(org_type, opa, opb));
Aart Bikf8f5a162017-02-06 15:35:29 -08001693 case HInstruction::kInvokeStaticOrDirect: {
Aart Bik6daebeb2017-04-03 14:35:41 -07001694 HInvokeStaticOrDirect* invoke = org->AsInvokeStaticOrDirect();
1695 if (vector_mode_ == kVector) {
1696 switch (invoke->GetIntrinsic()) {
1697 case Intrinsics::kMathAbsInt:
1698 case Intrinsics::kMathAbsLong:
1699 case Intrinsics::kMathAbsFloat:
1700 case Intrinsics::kMathAbsDouble:
1701 DCHECK(opb == nullptr);
1702 vector = new (global_allocator_) HVecAbs(global_allocator_, opa, type, vector_length_);
1703 break;
Aart Bikc8e93c72017-05-10 10:49:22 -07001704 case Intrinsics::kMathMinIntInt:
1705 case Intrinsics::kMathMinLongLong:
1706 case Intrinsics::kMathMinFloatFloat:
1707 case Intrinsics::kMathMinDoubleDouble: {
Aart Bikc8e93c72017-05-10 10:49:22 -07001708 vector = new (global_allocator_)
1709 HVecMin(global_allocator_, opa, opb, type, vector_length_, is_unsigned);
1710 break;
1711 }
1712 case Intrinsics::kMathMaxIntInt:
1713 case Intrinsics::kMathMaxLongLong:
1714 case Intrinsics::kMathMaxFloatFloat:
1715 case Intrinsics::kMathMaxDoubleDouble: {
Aart Bikc8e93c72017-05-10 10:49:22 -07001716 vector = new (global_allocator_)
1717 HVecMax(global_allocator_, opa, opb, type, vector_length_, is_unsigned);
1718 break;
1719 }
Aart Bik6daebeb2017-04-03 14:35:41 -07001720 default:
1721 LOG(FATAL) << "Unsupported SIMD intrinsic";
1722 UNREACHABLE();
1723 } // switch invoke
1724 } else {
Aart Bik24b905f2017-04-06 09:59:06 -07001725 // In scalar code, simply clone the method invoke, and replace its operands with the
1726 // corresponding new scalar instructions in the loop. The instruction will get an
1727 // environment while being inserted from the instruction map in original program order.
Aart Bik6daebeb2017-04-03 14:35:41 -07001728 DCHECK(vector_mode_ == kSequential);
Aart Bik6e92fb32017-06-05 14:05:09 -07001729 size_t num_args = invoke->GetNumberOfArguments();
Aart Bik6daebeb2017-04-03 14:35:41 -07001730 HInvokeStaticOrDirect* new_invoke = new (global_allocator_) HInvokeStaticOrDirect(
1731 global_allocator_,
Aart Bik6e92fb32017-06-05 14:05:09 -07001732 num_args,
Aart Bik6daebeb2017-04-03 14:35:41 -07001733 invoke->GetType(),
1734 invoke->GetDexPc(),
1735 invoke->GetDexMethodIndex(),
1736 invoke->GetResolvedMethod(),
1737 invoke->GetDispatchInfo(),
1738 invoke->GetInvokeType(),
1739 invoke->GetTargetMethod(),
1740 invoke->GetClinitCheckRequirement());
1741 HInputsRef inputs = invoke->GetInputs();
Aart Bik6e92fb32017-06-05 14:05:09 -07001742 size_t num_inputs = inputs.size();
1743 DCHECK_LE(num_args, num_inputs);
1744 DCHECK_EQ(num_inputs, new_invoke->GetInputs().size()); // both invokes agree
1745 for (size_t index = 0; index < num_inputs; ++index) {
1746 HInstruction* new_input = index < num_args
1747 ? vector_map_->Get(inputs[index])
1748 : inputs[index]; // beyond arguments: just pass through
1749 new_invoke->SetArgumentAt(index, new_input);
Aart Bik6daebeb2017-04-03 14:35:41 -07001750 }
Aart Bik98990262017-04-10 13:15:57 -07001751 new_invoke->SetIntrinsic(invoke->GetIntrinsic(),
1752 kNeedsEnvironmentOrCache,
1753 kNoSideEffects,
1754 kNoThrow);
Aart Bik6daebeb2017-04-03 14:35:41 -07001755 vector = new_invoke;
1756 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001757 break;
1758 }
1759 default:
1760 break;
1761 } // switch
1762 CHECK(vector != nullptr) << "Unsupported SIMD operator";
1763 vector_map_->Put(org, vector);
1764}
1765
1766#undef GENERATE_VEC
1767
1768//
Aart Bikf3e61ee2017-04-12 17:09:20 -07001769// Vectorization idioms.
1770//
1771
1772// Method recognizes the following idioms:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001773// rounding halving add (a + b + 1) >> 1 for unsigned/signed operands a, b
1774// truncated halving add (a + b) >> 1 for unsigned/signed operands a, b
Aart Bikf3e61ee2017-04-12 17:09:20 -07001775// Provided that the operands are promoted to a wider form to do the arithmetic and
1776// then cast back to narrower form, the idioms can be mapped into efficient SIMD
1777// implementation that operates directly in narrower form (plus one extra bit).
1778// TODO: current version recognizes implicit byte/short/char widening only;
1779// explicit widening from int to long could be added later.
1780bool HLoopOptimization::VectorizeHalvingAddIdiom(LoopNode* node,
1781 HInstruction* instruction,
1782 bool generate_code,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001783 DataType::Type type,
Aart Bikf3e61ee2017-04-12 17:09:20 -07001784 uint64_t restrictions) {
1785 // Test for top level arithmetic shift right x >> 1 or logical shift right x >>> 1
Aart Bik304c8a52017-05-23 11:01:13 -07001786 // (note whether the sign bit in wider precision is shifted in has no effect
Aart Bikf3e61ee2017-04-12 17:09:20 -07001787 // on the narrow precision computed by the idiom).
Aart Bikf3e61ee2017-04-12 17:09:20 -07001788 if ((instruction->IsShr() ||
1789 instruction->IsUShr()) &&
Aart Bik0148de42017-09-05 09:25:01 -07001790 IsInt64Value(instruction->InputAt(1), 1)) {
Aart Bik5f805002017-05-16 16:42:41 -07001791 // Test for (a + b + c) >> 1 for optional constant c.
1792 HInstruction* a = nullptr;
1793 HInstruction* b = nullptr;
1794 int64_t c = 0;
1795 if (IsAddConst(instruction->InputAt(0), /*out*/ &a, /*out*/ &b, /*out*/ &c)) {
Aart Bik304c8a52017-05-23 11:01:13 -07001796 DCHECK(a != nullptr && b != nullptr);
Aart Bik5f805002017-05-16 16:42:41 -07001797 // Accept c == 1 (rounded) or c == 0 (not rounded).
1798 bool is_rounded = false;
1799 if (c == 1) {
1800 is_rounded = true;
1801 } else if (c != 0) {
1802 return false;
1803 }
1804 // Accept consistent zero or sign extension on operands a and b.
Aart Bikf3e61ee2017-04-12 17:09:20 -07001805 HInstruction* r = nullptr;
1806 HInstruction* s = nullptr;
1807 bool is_unsigned = false;
Aart Bik304c8a52017-05-23 11:01:13 -07001808 if (!IsNarrowerOperands(a, b, type, &r, &s, &is_unsigned)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -07001809 return false;
1810 }
1811 // Deal with vector restrictions.
1812 if ((!is_unsigned && HasVectorRestrictions(restrictions, kNoSignedHAdd)) ||
1813 (!is_rounded && HasVectorRestrictions(restrictions, kNoUnroundedHAdd))) {
1814 return false;
1815 }
1816 // Accept recognized halving add for vectorizable operands. Vectorized code uses the
1817 // shorthand idiomatic operation. Sequential code uses the original scalar expressions.
Aart Bikdbbac8f2017-09-01 13:06:08 -07001818 DCHECK(r != nullptr);
1819 DCHECK(s != nullptr);
Aart Bik304c8a52017-05-23 11:01:13 -07001820 if (generate_code && vector_mode_ != kVector) { // de-idiom
1821 r = instruction->InputAt(0);
1822 s = instruction->InputAt(1);
1823 }
Aart Bikf3e61ee2017-04-12 17:09:20 -07001824 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
1825 VectorizeUse(node, s, generate_code, type, restrictions)) {
1826 if (generate_code) {
1827 if (vector_mode_ == kVector) {
1828 vector_map_->Put(instruction, new (global_allocator_) HVecHalvingAdd(
1829 global_allocator_,
1830 vector_map_->Get(r),
1831 vector_map_->Get(s),
1832 type,
1833 vector_length_,
1834 is_unsigned,
1835 is_rounded));
Aart Bik21b85922017-09-06 13:29:16 -07001836 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorizedIdiom);
Aart Bikf3e61ee2017-04-12 17:09:20 -07001837 } else {
Aart Bik304c8a52017-05-23 11:01:13 -07001838 GenerateVecOp(instruction, vector_map_->Get(r), vector_map_->Get(s), type);
Aart Bikf3e61ee2017-04-12 17:09:20 -07001839 }
1840 }
1841 return true;
1842 }
1843 }
1844 }
1845 return false;
1846}
1847
Aart Bikdbbac8f2017-09-01 13:06:08 -07001848// Method recognizes the following idiom:
1849// q += ABS(a - b) for signed operands a, b
1850// Provided that the operands have the same type or are promoted to a wider form.
1851// Since this may involve a vector length change, the idiom is handled by going directly
1852// to a sad-accumulate node (rather than relying combining finer grained nodes later).
1853// TODO: unsigned SAD too?
1854bool HLoopOptimization::VectorizeSADIdiom(LoopNode* node,
1855 HInstruction* instruction,
1856 bool generate_code,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001857 DataType::Type reduction_type,
Aart Bikdbbac8f2017-09-01 13:06:08 -07001858 uint64_t restrictions) {
1859 // Filter integral "q += ABS(a - b);" reduction, where ABS and SUB
1860 // are done in the same precision (either int or long).
1861 if (!instruction->IsAdd() ||
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001862 (reduction_type != DataType::Type::kInt32 && reduction_type != DataType::Type::kInt64)) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001863 return false;
1864 }
1865 HInstruction* q = instruction->InputAt(0);
1866 HInstruction* v = instruction->InputAt(1);
1867 HInstruction* a = nullptr;
1868 HInstruction* b = nullptr;
1869 if (v->IsInvokeStaticOrDirect() &&
1870 (v->AsInvokeStaticOrDirect()->GetIntrinsic() == Intrinsics::kMathAbsInt ||
1871 v->AsInvokeStaticOrDirect()->GetIntrinsic() == Intrinsics::kMathAbsLong)) {
1872 HInstruction* x = v->InputAt(0);
1873 if (x->IsSub() && x->GetType() == reduction_type) {
1874 a = x->InputAt(0);
1875 b = x->InputAt(1);
1876 }
1877 }
1878 if (a == nullptr || b == nullptr) {
1879 return false;
1880 }
1881 // Accept same-type or consistent sign extension for narrower-type on operands a and b.
1882 // The same-type or narrower operands are called r (a or lower) and s (b or lower).
1883 HInstruction* r = a;
1884 HInstruction* s = b;
1885 bool is_unsigned = false;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001886 DataType::Type sub_type = a->GetType();
Aart Bikdbbac8f2017-09-01 13:06:08 -07001887 if (a->IsTypeConversion()) {
1888 sub_type = a->InputAt(0)->GetType();
1889 } else if (b->IsTypeConversion()) {
1890 sub_type = b->InputAt(0)->GetType();
1891 }
1892 if (reduction_type != sub_type &&
1893 (!IsNarrowerOperands(a, b, sub_type, &r, &s, &is_unsigned) || is_unsigned)) {
1894 return false;
1895 }
1896 // Try same/narrower type and deal with vector restrictions.
1897 if (!TrySetVectorType(sub_type, &restrictions) || HasVectorRestrictions(restrictions, kNoSAD)) {
1898 return false;
1899 }
1900 // Accept SAD idiom for vectorizable operands. Vectorized code uses the shorthand
1901 // idiomatic operation. Sequential code uses the original scalar expressions.
1902 DCHECK(r != nullptr);
1903 DCHECK(s != nullptr);
1904 if (generate_code && vector_mode_ != kVector) { // de-idiom
1905 r = s = v->InputAt(0);
1906 }
1907 if (VectorizeUse(node, q, generate_code, sub_type, restrictions) &&
1908 VectorizeUse(node, r, generate_code, sub_type, restrictions) &&
1909 VectorizeUse(node, s, generate_code, sub_type, restrictions)) {
1910 if (generate_code) {
1911 if (vector_mode_ == kVector) {
1912 vector_map_->Put(instruction, new (global_allocator_) HVecSADAccumulate(
1913 global_allocator_,
1914 vector_map_->Get(q),
1915 vector_map_->Get(r),
1916 vector_map_->Get(s),
1917 reduction_type,
1918 GetOtherVL(reduction_type, sub_type, vector_length_)));
1919 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorizedIdiom);
1920 } else {
1921 GenerateVecOp(v, vector_map_->Get(r), nullptr, reduction_type);
1922 GenerateVecOp(instruction, vector_map_->Get(q), vector_map_->Get(v), reduction_type);
1923 }
1924 }
1925 return true;
1926 }
1927 return false;
1928}
1929
Aart Bikf3e61ee2017-04-12 17:09:20 -07001930//
Aart Bik14a68b42017-06-08 14:06:58 -07001931// Vectorization heuristics.
1932//
1933
1934bool HLoopOptimization::IsVectorizationProfitable(int64_t trip_count) {
1935 // Current heuristic: non-empty body with sufficient number
1936 // of iterations (if known).
1937 // TODO: refine by looking at e.g. operation count, alignment, etc.
1938 if (vector_length_ == 0) {
1939 return false; // nothing found
1940 } else if (0 < trip_count && trip_count < vector_length_) {
1941 return false; // insufficient iterations
1942 }
1943 return true;
1944}
1945
Aart Bikb29f6842017-07-28 15:58:41 -07001946void HLoopOptimization::SetPeelingCandidate(const ArrayReference* candidate,
1947 int64_t trip_count ATTRIBUTE_UNUSED) {
Aart Bik14a68b42017-06-08 14:06:58 -07001948 // Current heuristic: none.
1949 // TODO: implement
Aart Bikb29f6842017-07-28 15:58:41 -07001950 vector_peeling_candidate_ = candidate;
Aart Bik14a68b42017-06-08 14:06:58 -07001951}
1952
Artem Serovf26bb6c2017-09-01 10:59:03 +01001953static constexpr uint32_t ARM64_SIMD_MAXIMUM_UNROLL_FACTOR = 8;
1954static constexpr uint32_t ARM64_SIMD_HEURISTIC_MAX_BODY_SIZE = 50;
1955
Aart Bik14a68b42017-06-08 14:06:58 -07001956uint32_t HLoopOptimization::GetUnrollingFactor(HBasicBlock* block, int64_t trip_count) {
Aart Bik14a68b42017-06-08 14:06:58 -07001957 switch (compiler_driver_->GetInstructionSet()) {
Artem Serovf26bb6c2017-09-01 10:59:03 +01001958 case kArm64: {
Aart Bik521b50f2017-09-09 10:44:45 -07001959 // Don't unroll with insufficient iterations.
Artem Serovf26bb6c2017-09-01 10:59:03 +01001960 // TODO: Unroll loops with unknown trip count.
Aart Bik521b50f2017-09-09 10:44:45 -07001961 DCHECK_NE(vector_length_, 0u);
Artem Serovf26bb6c2017-09-01 10:59:03 +01001962 if (trip_count < 2 * vector_length_) {
Aart Bik521b50f2017-09-09 10:44:45 -07001963 return kNoUnrollingFactor;
Aart Bik14a68b42017-06-08 14:06:58 -07001964 }
Aart Bik521b50f2017-09-09 10:44:45 -07001965 // Don't unroll for large loop body size.
Artem Serovf26bb6c2017-09-01 10:59:03 +01001966 uint32_t instruction_count = block->GetInstructions().CountSize();
Aart Bik521b50f2017-09-09 10:44:45 -07001967 if (instruction_count >= ARM64_SIMD_HEURISTIC_MAX_BODY_SIZE) {
1968 return kNoUnrollingFactor;
1969 }
Artem Serovf26bb6c2017-09-01 10:59:03 +01001970 // Find a beneficial unroll factor with the following restrictions:
1971 // - At least one iteration of the transformed loop should be executed.
1972 // - The loop body shouldn't be "too big" (heuristic).
1973 uint32_t uf1 = ARM64_SIMD_HEURISTIC_MAX_BODY_SIZE / instruction_count;
1974 uint32_t uf2 = trip_count / vector_length_;
1975 uint32_t unroll_factor =
1976 TruncToPowerOfTwo(std::min({uf1, uf2, ARM64_SIMD_MAXIMUM_UNROLL_FACTOR}));
1977 DCHECK_GE(unroll_factor, 1u);
Artem Serovf26bb6c2017-09-01 10:59:03 +01001978 return unroll_factor;
Aart Bik14a68b42017-06-08 14:06:58 -07001979 }
Artem Serovf26bb6c2017-09-01 10:59:03 +01001980 case kX86:
1981 case kX86_64:
Aart Bik14a68b42017-06-08 14:06:58 -07001982 default:
Aart Bik521b50f2017-09-09 10:44:45 -07001983 return kNoUnrollingFactor;
Aart Bik14a68b42017-06-08 14:06:58 -07001984 }
1985}
1986
1987//
Aart Bikf8f5a162017-02-06 15:35:29 -08001988// Helpers.
1989//
1990
1991bool HLoopOptimization::TrySetPhiInduction(HPhi* phi, bool restrict_uses) {
Aart Bikb29f6842017-07-28 15:58:41 -07001992 // Start with empty phi induction.
1993 iset_->clear();
1994
Nicolas Geoffrayf57c1ae2017-06-28 17:40:18 +01001995 // Special case Phis that have equivalent in a debuggable setup. Our graph checker isn't
1996 // smart enough to follow strongly connected components (and it's probably not worth
1997 // it to make it so). See b/33775412.
1998 if (graph_->IsDebuggable() && phi->HasEquivalentPhi()) {
1999 return false;
2000 }
Aart Bikb29f6842017-07-28 15:58:41 -07002001
2002 // Lookup phi induction cycle.
Aart Bikcc42be02016-10-20 16:14:16 -07002003 ArenaSet<HInstruction*>* set = induction_range_.LookupCycle(phi);
2004 if (set != nullptr) {
2005 for (HInstruction* i : *set) {
Aart Bike3dedc52016-11-02 17:50:27 -07002006 // Check that, other than instructions that are no longer in the graph (removed earlier)
Aart Bikf8f5a162017-02-06 15:35:29 -08002007 // each instruction is removable and, when restrict uses are requested, other than for phi,
2008 // all uses are contained within the cycle.
Aart Bike3dedc52016-11-02 17:50:27 -07002009 if (!i->IsInBlock()) {
2010 continue;
2011 } else if (!i->IsRemovable()) {
2012 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08002013 } else if (i != phi && restrict_uses) {
Aart Bikb29f6842017-07-28 15:58:41 -07002014 // Deal with regular uses.
Aart Bikcc42be02016-10-20 16:14:16 -07002015 for (const HUseListNode<HInstruction*>& use : i->GetUses()) {
2016 if (set->find(use.GetUser()) == set->end()) {
2017 return false;
2018 }
2019 }
2020 }
Aart Bike3dedc52016-11-02 17:50:27 -07002021 iset_->insert(i); // copy
Aart Bikcc42be02016-10-20 16:14:16 -07002022 }
Aart Bikcc42be02016-10-20 16:14:16 -07002023 return true;
2024 }
2025 return false;
2026}
2027
Aart Bikb29f6842017-07-28 15:58:41 -07002028bool HLoopOptimization::TrySetPhiReduction(HPhi* phi) {
Aart Bikcc42be02016-10-20 16:14:16 -07002029 DCHECK(iset_->empty());
Aart Bikb29f6842017-07-28 15:58:41 -07002030 // Only unclassified phi cycles are candidates for reductions.
2031 if (induction_range_.IsClassified(phi)) {
2032 return false;
2033 }
2034 // Accept operations like x = x + .., provided that the phi and the reduction are
2035 // used exactly once inside the loop, and by each other.
2036 HInputsRef inputs = phi->GetInputs();
2037 if (inputs.size() == 2) {
2038 HInstruction* reduction = inputs[1];
2039 if (HasReductionFormat(reduction, phi)) {
2040 HLoopInformation* loop_info = phi->GetBlock()->GetLoopInformation();
2041 int32_t use_count = 0;
2042 bool single_use_inside_loop =
2043 // Reduction update only used by phi.
2044 reduction->GetUses().HasExactlyOneElement() &&
2045 !reduction->HasEnvironmentUses() &&
2046 // Reduction update is only use of phi inside the loop.
2047 IsOnlyUsedAfterLoop(loop_info, phi, /*collect_loop_uses*/ true, &use_count) &&
2048 iset_->size() == 1;
2049 iset_->clear(); // leave the way you found it
2050 if (single_use_inside_loop) {
2051 // Link reduction back, and start recording feed value.
2052 reductions_->Put(reduction, phi);
2053 reductions_->Put(phi, phi->InputAt(0));
2054 return true;
2055 }
2056 }
2057 }
2058 return false;
2059}
2060
2061bool HLoopOptimization::TrySetSimpleLoopHeader(HBasicBlock* block, /*out*/ HPhi** main_phi) {
2062 // Start with empty phi induction and reductions.
2063 iset_->clear();
2064 reductions_->clear();
2065
2066 // Scan the phis to find the following (the induction structure has already
2067 // been optimized, so we don't need to worry about trivial cases):
2068 // (1) optional reductions in loop,
2069 // (2) the main induction, used in loop control.
2070 HPhi* phi = nullptr;
2071 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
2072 if (TrySetPhiReduction(it.Current()->AsPhi())) {
2073 continue;
2074 } else if (phi == nullptr) {
2075 // Found the first candidate for main induction.
2076 phi = it.Current()->AsPhi();
2077 } else {
2078 return false;
2079 }
2080 }
2081
2082 // Then test for a typical loopheader:
2083 // s: SuspendCheck
2084 // c: Condition(phi, bound)
2085 // i: If(c)
2086 if (phi != nullptr && TrySetPhiInduction(phi, /*restrict_uses*/ false)) {
Aart Bikcc42be02016-10-20 16:14:16 -07002087 HInstruction* s = block->GetFirstInstruction();
2088 if (s != nullptr && s->IsSuspendCheck()) {
2089 HInstruction* c = s->GetNext();
Aart Bikd86c0852017-04-14 12:00:15 -07002090 if (c != nullptr &&
2091 c->IsCondition() &&
2092 c->GetUses().HasExactlyOneElement() && // only used for termination
2093 !c->HasEnvironmentUses()) { // unlikely, but not impossible
Aart Bikcc42be02016-10-20 16:14:16 -07002094 HInstruction* i = c->GetNext();
2095 if (i != nullptr && i->IsIf() && i->InputAt(0) == c) {
2096 iset_->insert(c);
2097 iset_->insert(s);
Aart Bikb29f6842017-07-28 15:58:41 -07002098 *main_phi = phi;
Aart Bikcc42be02016-10-20 16:14:16 -07002099 return true;
2100 }
2101 }
2102 }
2103 }
2104 return false;
2105}
2106
2107bool HLoopOptimization::IsEmptyBody(HBasicBlock* block) {
Aart Bikf8f5a162017-02-06 15:35:29 -08002108 if (!block->GetPhis().IsEmpty()) {
2109 return false;
2110 }
2111 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
2112 HInstruction* instruction = it.Current();
2113 if (!instruction->IsGoto() && iset_->find(instruction) == iset_->end()) {
2114 return false;
Aart Bikcc42be02016-10-20 16:14:16 -07002115 }
Aart Bikf8f5a162017-02-06 15:35:29 -08002116 }
2117 return true;
2118}
2119
2120bool HLoopOptimization::IsUsedOutsideLoop(HLoopInformation* loop_info,
2121 HInstruction* instruction) {
Aart Bikb29f6842017-07-28 15:58:41 -07002122 // Deal with regular uses.
Aart Bikf8f5a162017-02-06 15:35:29 -08002123 for (const HUseListNode<HInstruction*>& use : instruction->GetUses()) {
2124 if (use.GetUser()->GetBlock()->GetLoopInformation() != loop_info) {
2125 return true;
2126 }
Aart Bikcc42be02016-10-20 16:14:16 -07002127 }
2128 return false;
2129}
2130
Aart Bik482095d2016-10-10 15:39:10 -07002131bool HLoopOptimization::IsOnlyUsedAfterLoop(HLoopInformation* loop_info,
Aart Bik8c4a8542016-10-06 11:36:57 -07002132 HInstruction* instruction,
Aart Bik6b69e0a2017-01-11 10:20:43 -08002133 bool collect_loop_uses,
Aart Bik8c4a8542016-10-06 11:36:57 -07002134 /*out*/ int32_t* use_count) {
Aart Bikb29f6842017-07-28 15:58:41 -07002135 // Deal with regular uses.
Aart Bik8c4a8542016-10-06 11:36:57 -07002136 for (const HUseListNode<HInstruction*>& use : instruction->GetUses()) {
2137 HInstruction* user = use.GetUser();
2138 if (iset_->find(user) == iset_->end()) { // not excluded?
2139 HLoopInformation* other_loop_info = user->GetBlock()->GetLoopInformation();
Aart Bik482095d2016-10-10 15:39:10 -07002140 if (other_loop_info != nullptr && other_loop_info->IsIn(*loop_info)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -08002141 // If collect_loop_uses is set, simply keep adding those uses to the set.
2142 // Otherwise, reject uses inside the loop that were not already in the set.
2143 if (collect_loop_uses) {
2144 iset_->insert(user);
2145 continue;
2146 }
Aart Bik8c4a8542016-10-06 11:36:57 -07002147 return false;
2148 }
2149 ++*use_count;
2150 }
2151 }
2152 return true;
2153}
2154
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002155bool HLoopOptimization::TryReplaceWithLastValue(HLoopInformation* loop_info,
2156 HInstruction* instruction,
2157 HBasicBlock* block) {
2158 // Try to replace outside uses with the last value.
Aart Bik807868e2016-11-03 17:51:43 -07002159 if (induction_range_.CanGenerateLastValue(instruction)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -08002160 HInstruction* replacement = induction_range_.GenerateLastValue(instruction, graph_, block);
Aart Bikb29f6842017-07-28 15:58:41 -07002161 // Deal with regular uses.
Aart Bik6b69e0a2017-01-11 10:20:43 -08002162 const HUseList<HInstruction*>& uses = instruction->GetUses();
2163 for (auto it = uses.begin(), end = uses.end(); it != end;) {
2164 HInstruction* user = it->GetUser();
2165 size_t index = it->GetIndex();
2166 ++it; // increment before replacing
2167 if (iset_->find(user) == iset_->end()) { // not excluded?
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002168 if (kIsDebugBuild) {
2169 // We have checked earlier in 'IsOnlyUsedAfterLoop' that the use is after the loop.
2170 HLoopInformation* other_loop_info = user->GetBlock()->GetLoopInformation();
2171 CHECK(other_loop_info == nullptr || !other_loop_info->IsIn(*loop_info));
2172 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08002173 user->ReplaceInput(replacement, index);
2174 induction_range_.Replace(user, instruction, replacement); // update induction
2175 }
2176 }
Aart Bikb29f6842017-07-28 15:58:41 -07002177 // Deal with environment uses.
Aart Bik6b69e0a2017-01-11 10:20:43 -08002178 const HUseList<HEnvironment*>& env_uses = instruction->GetEnvUses();
2179 for (auto it = env_uses.begin(), end = env_uses.end(); it != end;) {
2180 HEnvironment* user = it->GetUser();
2181 size_t index = it->GetIndex();
2182 ++it; // increment before replacing
2183 if (iset_->find(user->GetHolder()) == iset_->end()) { // not excluded?
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002184 // Only update environment uses after the loop.
Aart Bik14a68b42017-06-08 14:06:58 -07002185 HLoopInformation* other_loop_info = user->GetHolder()->GetBlock()->GetLoopInformation();
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002186 if (other_loop_info == nullptr || !other_loop_info->IsIn(*loop_info)) {
2187 user->RemoveAsUserOfInput(index);
2188 user->SetRawEnvAt(index, replacement);
2189 replacement->AddEnvUseAt(user, index);
2190 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08002191 }
2192 }
Aart Bik807868e2016-11-03 17:51:43 -07002193 return true;
Aart Bik8c4a8542016-10-06 11:36:57 -07002194 }
Aart Bik807868e2016-11-03 17:51:43 -07002195 return false;
Aart Bik8c4a8542016-10-06 11:36:57 -07002196}
2197
Aart Bikf8f5a162017-02-06 15:35:29 -08002198bool HLoopOptimization::TryAssignLastValue(HLoopInformation* loop_info,
2199 HInstruction* instruction,
2200 HBasicBlock* block,
2201 bool collect_loop_uses) {
2202 // Assigning the last value is always successful if there are no uses.
2203 // Otherwise, it succeeds in a no early-exit loop by generating the
2204 // proper last value assignment.
2205 int32_t use_count = 0;
2206 return IsOnlyUsedAfterLoop(loop_info, instruction, collect_loop_uses, &use_count) &&
2207 (use_count == 0 ||
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002208 (!IsEarlyExit(loop_info) && TryReplaceWithLastValue(loop_info, instruction, block)));
Aart Bikf8f5a162017-02-06 15:35:29 -08002209}
2210
Aart Bik6b69e0a2017-01-11 10:20:43 -08002211void HLoopOptimization::RemoveDeadInstructions(const HInstructionList& list) {
2212 for (HBackwardInstructionIterator i(list); !i.Done(); i.Advance()) {
2213 HInstruction* instruction = i.Current();
2214 if (instruction->IsDeadAndRemovable()) {
2215 simplified_ = true;
2216 instruction->GetBlock()->RemoveInstructionOrPhi(instruction);
2217 }
2218 }
2219}
2220
Aart Bik14a68b42017-06-08 14:06:58 -07002221bool HLoopOptimization::CanRemoveCycle() {
2222 for (HInstruction* i : *iset_) {
2223 // We can never remove instructions that have environment
2224 // uses when we compile 'debuggable'.
2225 if (i->HasEnvironmentUses() && graph_->IsDebuggable()) {
2226 return false;
2227 }
2228 // A deoptimization should never have an environment input removed.
2229 for (const HUseListNode<HEnvironment*>& use : i->GetEnvUses()) {
2230 if (use.GetUser()->GetHolder()->IsDeoptimize()) {
2231 return false;
2232 }
2233 }
2234 }
2235 return true;
2236}
2237
Aart Bik281c6812016-08-26 11:31:48 -07002238} // namespace art