blob: 5a483e234b559f3f6379ad2dec29ca4f3db26163 [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 Bik38a3f212017-10-20 17:02:21 -070028#include "mirror/array-inl.h"
29#include "mirror/string.h"
Aart Bik281c6812016-08-26 11:31:48 -070030
31namespace art {
32
Aart Bikf8f5a162017-02-06 15:35:29 -080033// Enables vectorization (SIMDization) in the loop optimizer.
34static constexpr bool kEnableVectorization = true;
35
Aart Bik521b50f2017-09-09 10:44:45 -070036// No loop unrolling factor (just one copy of the loop-body).
37static constexpr uint32_t kNoUnrollingFactor = 1;
38
Aart Bik38a3f212017-10-20 17:02:21 -070039//
40// Static helpers.
41//
42
43// Base alignment for arrays/strings guaranteed by the Android runtime.
44static uint32_t BaseAlignment() {
45 return kObjectAlignment;
46}
47
48// Hidden offset for arrays/strings guaranteed by the Android runtime.
49static uint32_t HiddenOffset(DataType::Type type, bool is_string_char_at) {
50 return is_string_char_at
51 ? mirror::String::ValueOffset().Uint32Value()
52 : mirror::Array::DataOffset(DataType::Size(type)).Uint32Value();
53}
54
Aart Bik9abf8942016-10-14 09:49:42 -070055// Remove the instruction from the graph. A bit more elaborate than the usual
56// instruction removal, since there may be a cycle in the use structure.
Aart Bik281c6812016-08-26 11:31:48 -070057static void RemoveFromCycle(HInstruction* instruction) {
Aart Bik281c6812016-08-26 11:31:48 -070058 instruction->RemoveAsUserOfAllInputs();
59 instruction->RemoveEnvironmentUsers();
60 instruction->GetBlock()->RemoveInstructionOrPhi(instruction, /*ensure_safety=*/ false);
Artem Serov21c7e6f2017-07-27 16:04:42 +010061 RemoveEnvironmentUses(instruction);
62 ResetEnvironmentInputRecords(instruction);
Aart Bik281c6812016-08-26 11:31:48 -070063}
64
Aart Bik807868e2016-11-03 17:51:43 -070065// Detect a goto block and sets succ to the single successor.
Aart Bike3dedc52016-11-02 17:50:27 -070066static bool IsGotoBlock(HBasicBlock* block, /*out*/ HBasicBlock** succ) {
67 if (block->GetPredecessors().size() == 1 &&
68 block->GetSuccessors().size() == 1 &&
69 block->IsSingleGoto()) {
70 *succ = block->GetSingleSuccessor();
71 return true;
72 }
73 return false;
74}
75
Aart Bik807868e2016-11-03 17:51:43 -070076// Detect an early exit loop.
77static bool IsEarlyExit(HLoopInformation* loop_info) {
78 HBlocksInLoopReversePostOrderIterator it_loop(*loop_info);
79 for (it_loop.Advance(); !it_loop.Done(); it_loop.Advance()) {
80 for (HBasicBlock* successor : it_loop.Current()->GetSuccessors()) {
81 if (!loop_info->Contains(*successor)) {
82 return true;
83 }
84 }
85 }
86 return false;
87}
88
Aart Bik68ca7022017-09-26 16:44:23 -070089// Forward declaration.
90static bool IsZeroExtensionAndGet(HInstruction* instruction,
91 DataType::Type type,
Aart Bikdf011c32017-09-28 12:53:04 -070092 /*out*/ HInstruction** operand);
Aart Bik68ca7022017-09-26 16:44:23 -070093
Aart Bikdf011c32017-09-28 12:53:04 -070094// Detect a sign extension in instruction from the given type.
Aart Bikdbbac8f2017-09-01 13:06:08 -070095// Returns the promoted operand on success.
Aart Bikf3e61ee2017-04-12 17:09:20 -070096static bool IsSignExtensionAndGet(HInstruction* instruction,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +010097 DataType::Type type,
Aart Bikdf011c32017-09-28 12:53:04 -070098 /*out*/ HInstruction** operand) {
Aart Bikf3e61ee2017-04-12 17:09:20 -070099 // Accept any already wider constant that would be handled properly by sign
100 // extension when represented in the *width* of the given narrower data type
Aart Bik4d1a9d42017-10-19 14:40:55 -0700101 // (the fact that Uint8/Uint16 normally zero extend does not matter here).
Aart Bikf3e61ee2017-04-12 17:09:20 -0700102 int64_t value = 0;
Aart Bik50e20d52017-05-05 14:07:29 -0700103 if (IsInt64AndGet(instruction, /*out*/ &value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700104 switch (type) {
Vladimir Markod5d2f2c2017-09-26 12:37:26 +0100105 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100106 case DataType::Type::kInt8:
Aart Bikdbbac8f2017-09-01 13:06:08 -0700107 if (IsInt<8>(value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700108 *operand = instruction;
109 return true;
110 }
111 return false;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100112 case DataType::Type::kUint16:
113 case DataType::Type::kInt16:
Aart Bikdbbac8f2017-09-01 13:06:08 -0700114 if (IsInt<16>(value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700115 *operand = instruction;
116 return true;
117 }
118 return false;
119 default:
120 return false;
121 }
122 }
Aart Bikdf011c32017-09-28 12:53:04 -0700123 // An implicit widening conversion of any signed expression sign-extends.
124 if (instruction->GetType() == type) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700125 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100126 case DataType::Type::kInt8:
127 case DataType::Type::kInt16:
Aart Bikf3e61ee2017-04-12 17:09:20 -0700128 *operand = instruction;
129 return true;
130 default:
131 return false;
132 }
133 }
Aart Bikdf011c32017-09-28 12:53:04 -0700134 // An explicit widening conversion of a signed expression sign-extends.
Aart Bik68ca7022017-09-26 16:44:23 -0700135 if (instruction->IsTypeConversion()) {
Aart Bikdf011c32017-09-28 12:53:04 -0700136 HInstruction* conv = instruction->InputAt(0);
137 DataType::Type from = conv->GetType();
Aart Bik68ca7022017-09-26 16:44:23 -0700138 switch (instruction->GetType()) {
Aart Bikdf011c32017-09-28 12:53:04 -0700139 case DataType::Type::kInt32:
Aart Bik68ca7022017-09-26 16:44:23 -0700140 case DataType::Type::kInt64:
Aart Bikdf011c32017-09-28 12:53:04 -0700141 if (type == from && (from == DataType::Type::kInt8 ||
142 from == DataType::Type::kInt16 ||
143 from == DataType::Type::kInt32)) {
144 *operand = conv;
145 return true;
146 }
147 return false;
Aart Bik68ca7022017-09-26 16:44:23 -0700148 case DataType::Type::kInt16:
149 return type == DataType::Type::kUint16 &&
150 from == DataType::Type::kUint16 &&
Aart Bikdf011c32017-09-28 12:53:04 -0700151 IsZeroExtensionAndGet(instruction->InputAt(0), type, /*out*/ operand);
Aart Bik68ca7022017-09-26 16:44:23 -0700152 default:
153 return false;
154 }
Aart Bikdbbac8f2017-09-01 13:06:08 -0700155 }
Aart Bikf3e61ee2017-04-12 17:09:20 -0700156 return false;
157}
158
Aart Bikdf011c32017-09-28 12:53:04 -0700159// Detect a zero extension in instruction from the given type.
Aart Bikdbbac8f2017-09-01 13:06:08 -0700160// Returns the promoted operand on success.
Aart Bikf3e61ee2017-04-12 17:09:20 -0700161static bool IsZeroExtensionAndGet(HInstruction* instruction,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100162 DataType::Type type,
Aart Bikdf011c32017-09-28 12:53:04 -0700163 /*out*/ HInstruction** operand) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700164 // Accept any already wider constant that would be handled properly by zero
165 // extension when represented in the *width* of the given narrower data type
Aart Bikdf011c32017-09-28 12:53:04 -0700166 // (the fact that Int8/Int16 normally sign extend does not matter here).
Aart Bikf3e61ee2017-04-12 17:09:20 -0700167 int64_t value = 0;
Aart Bik50e20d52017-05-05 14:07:29 -0700168 if (IsInt64AndGet(instruction, /*out*/ &value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700169 switch (type) {
Vladimir Markod5d2f2c2017-09-26 12:37:26 +0100170 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100171 case DataType::Type::kInt8:
Aart Bikdbbac8f2017-09-01 13:06:08 -0700172 if (IsUint<8>(value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700173 *operand = instruction;
174 return true;
175 }
176 return false;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100177 case DataType::Type::kUint16:
178 case DataType::Type::kInt16:
Aart Bikdbbac8f2017-09-01 13:06:08 -0700179 if (IsUint<16>(value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700180 *operand = instruction;
181 return true;
182 }
183 return false;
184 default:
185 return false;
186 }
187 }
Aart Bikdf011c32017-09-28 12:53:04 -0700188 // An implicit widening conversion of any unsigned expression zero-extends.
189 if (instruction->GetType() == type) {
Vladimir Markod5d2f2c2017-09-26 12:37:26 +0100190 switch (type) {
191 case DataType::Type::kUint8:
192 case DataType::Type::kUint16:
193 *operand = instruction;
194 return true;
195 default:
196 return false;
Aart Bikf3e61ee2017-04-12 17:09:20 -0700197 }
198 }
Aart Bikdf011c32017-09-28 12:53:04 -0700199 // An explicit widening conversion of an unsigned expression zero-extends.
Aart Bik68ca7022017-09-26 16:44:23 -0700200 if (instruction->IsTypeConversion()) {
Aart Bikdf011c32017-09-28 12:53:04 -0700201 HInstruction* conv = instruction->InputAt(0);
202 DataType::Type from = conv->GetType();
Aart Bik68ca7022017-09-26 16:44:23 -0700203 switch (instruction->GetType()) {
Aart Bikdf011c32017-09-28 12:53:04 -0700204 case DataType::Type::kInt32:
Aart Bik68ca7022017-09-26 16:44:23 -0700205 case DataType::Type::kInt64:
Aart Bikdf011c32017-09-28 12:53:04 -0700206 if (type == from && from == DataType::Type::kUint16) {
207 *operand = conv;
208 return true;
209 }
210 return false;
Aart Bik68ca7022017-09-26 16:44:23 -0700211 case DataType::Type::kUint16:
212 return type == DataType::Type::kInt16 &&
213 from == DataType::Type::kInt16 &&
Aart Bikdf011c32017-09-28 12:53:04 -0700214 IsSignExtensionAndGet(instruction->InputAt(0), type, /*out*/ operand);
Aart Bik68ca7022017-09-26 16:44:23 -0700215 default:
216 return false;
217 }
Aart Bikdbbac8f2017-09-01 13:06:08 -0700218 }
Aart Bikf3e61ee2017-04-12 17:09:20 -0700219 return false;
220}
221
Aart Bik304c8a52017-05-23 11:01:13 -0700222// Detect situations with same-extension narrower operands.
223// Returns true on success and sets is_unsigned accordingly.
224static bool IsNarrowerOperands(HInstruction* a,
225 HInstruction* b,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100226 DataType::Type type,
Aart Bik304c8a52017-05-23 11:01:13 -0700227 /*out*/ HInstruction** r,
228 /*out*/ HInstruction** s,
229 /*out*/ bool* is_unsigned) {
Aart Bik4d1a9d42017-10-19 14:40:55 -0700230 // Look for a matching sign extension.
231 DataType::Type stype = HVecOperation::ToSignedType(type);
232 if (IsSignExtensionAndGet(a, stype, r) && IsSignExtensionAndGet(b, stype, s)) {
Aart Bik304c8a52017-05-23 11:01:13 -0700233 *is_unsigned = false;
234 return true;
Aart Bik4d1a9d42017-10-19 14:40:55 -0700235 }
236 // Look for a matching zero extension.
237 DataType::Type utype = HVecOperation::ToUnsignedType(type);
238 if (IsZeroExtensionAndGet(a, utype, r) && IsZeroExtensionAndGet(b, utype, s)) {
Aart Bik304c8a52017-05-23 11:01:13 -0700239 *is_unsigned = true;
240 return true;
241 }
242 return false;
243}
244
245// As above, single operand.
246static bool IsNarrowerOperand(HInstruction* a,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100247 DataType::Type type,
Aart Bik304c8a52017-05-23 11:01:13 -0700248 /*out*/ HInstruction** r,
249 /*out*/ bool* is_unsigned) {
Aart Bik4d1a9d42017-10-19 14:40:55 -0700250 // Look for a matching sign extension.
251 DataType::Type stype = HVecOperation::ToSignedType(type);
252 if (IsSignExtensionAndGet(a, stype, r)) {
Aart Bik304c8a52017-05-23 11:01:13 -0700253 *is_unsigned = false;
254 return true;
Aart Bik4d1a9d42017-10-19 14:40:55 -0700255 }
256 // Look for a matching zero extension.
257 DataType::Type utype = HVecOperation::ToUnsignedType(type);
258 if (IsZeroExtensionAndGet(a, utype, r)) {
Aart Bik304c8a52017-05-23 11:01:13 -0700259 *is_unsigned = true;
260 return true;
261 }
262 return false;
263}
264
Aart Bikdbbac8f2017-09-01 13:06:08 -0700265// Compute relative vector length based on type difference.
Aart Bik38a3f212017-10-20 17:02:21 -0700266static uint32_t GetOtherVL(DataType::Type other_type, DataType::Type vector_type, uint32_t vl) {
Vladimir Markod5d2f2c2017-09-26 12:37:26 +0100267 DCHECK(DataType::IsIntegralType(other_type));
268 DCHECK(DataType::IsIntegralType(vector_type));
269 DCHECK_GE(DataType::SizeShift(other_type), DataType::SizeShift(vector_type));
270 return vl >> (DataType::SizeShift(other_type) - DataType::SizeShift(vector_type));
Aart Bikdbbac8f2017-09-01 13:06:08 -0700271}
272
Aart Bik5f805002017-05-16 16:42:41 -0700273// Detect up to two instructions a and b, and an acccumulated constant c.
274static bool IsAddConstHelper(HInstruction* instruction,
275 /*out*/ HInstruction** a,
276 /*out*/ HInstruction** b,
277 /*out*/ int64_t* c,
278 int32_t depth) {
279 static constexpr int32_t kMaxDepth = 8; // don't search too deep
280 int64_t value = 0;
281 if (IsInt64AndGet(instruction, &value)) {
282 *c += value;
283 return true;
284 } else if (instruction->IsAdd() && depth <= kMaxDepth) {
285 return IsAddConstHelper(instruction->InputAt(0), a, b, c, depth + 1) &&
286 IsAddConstHelper(instruction->InputAt(1), a, b, c, depth + 1);
287 } else if (*a == nullptr) {
288 *a = instruction;
289 return true;
290 } else if (*b == nullptr) {
291 *b = instruction;
292 return true;
293 }
294 return false; // too many non-const operands
295}
296
297// Detect a + b + c for an optional constant c.
298static bool IsAddConst(HInstruction* instruction,
299 /*out*/ HInstruction** a,
300 /*out*/ HInstruction** b,
301 /*out*/ int64_t* c) {
302 if (instruction->IsAdd()) {
303 // Try to find a + b and accumulated c.
304 if (IsAddConstHelper(instruction->InputAt(0), a, b, c, /*depth*/ 0) &&
305 IsAddConstHelper(instruction->InputAt(1), a, b, c, /*depth*/ 0) &&
306 *b != nullptr) {
307 return true;
308 }
309 // Found a + b.
310 *a = instruction->InputAt(0);
311 *b = instruction->InputAt(1);
312 *c = 0;
313 return true;
314 }
315 return false;
316}
317
Aart Bikdf011c32017-09-28 12:53:04 -0700318// Detect a + c for constant c.
319static bool IsAddConst(HInstruction* instruction,
320 /*out*/ HInstruction** a,
321 /*out*/ int64_t* c) {
322 if (instruction->IsAdd()) {
323 if (IsInt64AndGet(instruction->InputAt(0), c)) {
324 *a = instruction->InputAt(1);
325 return true;
326 } else if (IsInt64AndGet(instruction->InputAt(1), c)) {
327 *a = instruction->InputAt(0);
328 return true;
329 }
330 }
331 return false;
332}
333
Aart Bikb29f6842017-07-28 15:58:41 -0700334// Detect reductions of the following forms,
Aart Bikb29f6842017-07-28 15:58:41 -0700335// x = x_phi + ..
336// x = x_phi - ..
337// x = max(x_phi, ..)
338// x = min(x_phi, ..)
339static bool HasReductionFormat(HInstruction* reduction, HInstruction* phi) {
340 if (reduction->IsAdd()) {
Aart Bikdbbac8f2017-09-01 13:06:08 -0700341 return (reduction->InputAt(0) == phi && reduction->InputAt(1) != phi) ||
342 (reduction->InputAt(0) != phi && reduction->InputAt(1) == phi);
Aart Bikb29f6842017-07-28 15:58:41 -0700343 } else if (reduction->IsSub()) {
Aart Bikdbbac8f2017-09-01 13:06:08 -0700344 return (reduction->InputAt(0) == phi && reduction->InputAt(1) != phi);
Aart Bikb29f6842017-07-28 15:58:41 -0700345 } else if (reduction->IsInvokeStaticOrDirect()) {
346 switch (reduction->AsInvokeStaticOrDirect()->GetIntrinsic()) {
347 case Intrinsics::kMathMinIntInt:
348 case Intrinsics::kMathMinLongLong:
349 case Intrinsics::kMathMinFloatFloat:
350 case Intrinsics::kMathMinDoubleDouble:
351 case Intrinsics::kMathMaxIntInt:
352 case Intrinsics::kMathMaxLongLong:
353 case Intrinsics::kMathMaxFloatFloat:
354 case Intrinsics::kMathMaxDoubleDouble:
Aart Bikdbbac8f2017-09-01 13:06:08 -0700355 return (reduction->InputAt(0) == phi && reduction->InputAt(1) != phi) ||
356 (reduction->InputAt(0) != phi && reduction->InputAt(1) == phi);
Aart Bikb29f6842017-07-28 15:58:41 -0700357 default:
358 return false;
359 }
360 }
361 return false;
362}
363
Aart Bikdbbac8f2017-09-01 13:06:08 -0700364// Translates vector operation to reduction kind.
365static HVecReduce::ReductionKind GetReductionKind(HVecOperation* reduction) {
366 if (reduction->IsVecAdd() || reduction->IsVecSub() || reduction->IsVecSADAccumulate()) {
Aart Bik0148de42017-09-05 09:25:01 -0700367 return HVecReduce::kSum;
368 } else if (reduction->IsVecMin()) {
369 return HVecReduce::kMin;
370 } else if (reduction->IsVecMax()) {
371 return HVecReduce::kMax;
372 }
Aart Bik38a3f212017-10-20 17:02:21 -0700373 LOG(FATAL) << "Unsupported SIMD reduction " << reduction->GetId();
Aart Bik0148de42017-09-05 09:25:01 -0700374 UNREACHABLE();
375}
376
Aart Bikf8f5a162017-02-06 15:35:29 -0800377// Test vector restrictions.
378static bool HasVectorRestrictions(uint64_t restrictions, uint64_t tested) {
379 return (restrictions & tested) != 0;
380}
381
Aart Bikf3e61ee2017-04-12 17:09:20 -0700382// Insert an instruction.
Aart Bikf8f5a162017-02-06 15:35:29 -0800383static HInstruction* Insert(HBasicBlock* block, HInstruction* instruction) {
384 DCHECK(block != nullptr);
385 DCHECK(instruction != nullptr);
386 block->InsertInstructionBefore(instruction, block->GetLastInstruction());
387 return instruction;
388}
389
Artem Serov21c7e6f2017-07-27 16:04:42 +0100390// Check that instructions from the induction sets are fully removed: have no uses
391// and no other instructions use them.
Vladimir Markoca6fff82017-10-03 14:49:14 +0100392static bool CheckInductionSetFullyRemoved(ScopedArenaSet<HInstruction*>* iset) {
Artem Serov21c7e6f2017-07-27 16:04:42 +0100393 for (HInstruction* instr : *iset) {
394 if (instr->GetBlock() != nullptr ||
395 !instr->GetUses().empty() ||
396 !instr->GetEnvUses().empty() ||
397 HasEnvironmentUsedByOthers(instr)) {
398 return false;
399 }
400 }
Artem Serov21c7e6f2017-07-27 16:04:42 +0100401 return true;
402}
403
Aart Bik281c6812016-08-26 11:31:48 -0700404//
Aart Bikb29f6842017-07-28 15:58:41 -0700405// Public methods.
Aart Bik281c6812016-08-26 11:31:48 -0700406//
407
408HLoopOptimization::HLoopOptimization(HGraph* graph,
Aart Bik92685a82017-03-06 11:13:43 -0800409 CompilerDriver* compiler_driver,
Aart Bikb92cc332017-09-06 15:53:17 -0700410 HInductionVarAnalysis* induction_analysis,
Aart Bik2ca10eb2017-11-15 15:17:53 -0800411 OptimizingCompilerStats* stats,
412 const char* name)
413 : HOptimization(graph, name, stats),
Aart Bik92685a82017-03-06 11:13:43 -0800414 compiler_driver_(compiler_driver),
Aart Bik281c6812016-08-26 11:31:48 -0700415 induction_range_(induction_analysis),
Aart Bik96202302016-10-04 17:33:56 -0700416 loop_allocator_(nullptr),
Vladimir Markoca6fff82017-10-03 14:49:14 +0100417 global_allocator_(graph_->GetAllocator()),
Aart Bik281c6812016-08-26 11:31:48 -0700418 top_loop_(nullptr),
Aart Bik8c4a8542016-10-06 11:36:57 -0700419 last_loop_(nullptr),
Aart Bik482095d2016-10-10 15:39:10 -0700420 iset_(nullptr),
Aart Bikb29f6842017-07-28 15:58:41 -0700421 reductions_(nullptr),
Aart Bikf8f5a162017-02-06 15:35:29 -0800422 simplified_(false),
423 vector_length_(0),
424 vector_refs_(nullptr),
Aart Bik38a3f212017-10-20 17:02:21 -0700425 vector_static_peeling_factor_(0),
426 vector_dynamic_peeling_candidate_(nullptr),
Aart Bik14a68b42017-06-08 14:06:58 -0700427 vector_runtime_test_a_(nullptr),
428 vector_runtime_test_b_(nullptr),
Aart Bik0148de42017-09-05 09:25:01 -0700429 vector_map_(nullptr),
Vladimir Markoca6fff82017-10-03 14:49:14 +0100430 vector_permanent_map_(nullptr),
431 vector_mode_(kSequential),
432 vector_preheader_(nullptr),
433 vector_header_(nullptr),
434 vector_body_(nullptr),
435 vector_index_(nullptr) {
Aart Bik281c6812016-08-26 11:31:48 -0700436}
437
438void HLoopOptimization::Run() {
Mingyao Yang01b47b02017-02-03 12:09:57 -0800439 // Skip if there is no loop or the graph has try-catch/irreducible loops.
Aart Bik281c6812016-08-26 11:31:48 -0700440 // TODO: make this less of a sledgehammer.
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800441 if (!graph_->HasLoops() || graph_->HasTryCatch() || graph_->HasIrreducibleLoops()) {
Aart Bik281c6812016-08-26 11:31:48 -0700442 return;
443 }
444
Vladimir Markoca6fff82017-10-03 14:49:14 +0100445 // Phase-local allocator.
446 ScopedArenaAllocator allocator(graph_->GetArenaStack());
Aart Bik96202302016-10-04 17:33:56 -0700447 loop_allocator_ = &allocator;
Nicolas Geoffrayebe16742016-10-05 09:55:42 +0100448
Aart Bik96202302016-10-04 17:33:56 -0700449 // Perform loop optimizations.
450 LocalRun();
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800451 if (top_loop_ == nullptr) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800452 graph_->SetHasLoops(false); // no more loops
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800453 }
454
Aart Bik96202302016-10-04 17:33:56 -0700455 // Detach.
456 loop_allocator_ = nullptr;
457 last_loop_ = top_loop_ = nullptr;
458}
459
Aart Bikb29f6842017-07-28 15:58:41 -0700460//
461// Loop setup and traversal.
462//
463
Aart Bik96202302016-10-04 17:33:56 -0700464void HLoopOptimization::LocalRun() {
465 // Build the linear order using the phase-local allocator. This step enables building
466 // a loop hierarchy that properly reflects the outer-inner and previous-next relation.
Vladimir Markoca6fff82017-10-03 14:49:14 +0100467 ScopedArenaVector<HBasicBlock*> linear_order(loop_allocator_->Adapter(kArenaAllocLinearOrder));
468 LinearizeGraph(graph_, &linear_order);
Aart Bik96202302016-10-04 17:33:56 -0700469
Aart Bik281c6812016-08-26 11:31:48 -0700470 // Build the loop hierarchy.
Aart Bik96202302016-10-04 17:33:56 -0700471 for (HBasicBlock* block : linear_order) {
Aart Bik281c6812016-08-26 11:31:48 -0700472 if (block->IsLoopHeader()) {
473 AddLoop(block->GetLoopInformation());
474 }
475 }
Aart Bik96202302016-10-04 17:33:56 -0700476
Aart Bik8c4a8542016-10-06 11:36:57 -0700477 // Traverse the loop hierarchy inner-to-outer and optimize. Traversal can use
Aart Bikf8f5a162017-02-06 15:35:29 -0800478 // temporary data structures using the phase-local allocator. All new HIR
479 // should use the global allocator.
Aart Bik8c4a8542016-10-06 11:36:57 -0700480 if (top_loop_ != nullptr) {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100481 ScopedArenaSet<HInstruction*> iset(loop_allocator_->Adapter(kArenaAllocLoopOptimization));
482 ScopedArenaSafeMap<HInstruction*, HInstruction*> reds(
Aart Bikb29f6842017-07-28 15:58:41 -0700483 std::less<HInstruction*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
Vladimir Markoca6fff82017-10-03 14:49:14 +0100484 ScopedArenaSet<ArrayReference> refs(loop_allocator_->Adapter(kArenaAllocLoopOptimization));
485 ScopedArenaSafeMap<HInstruction*, HInstruction*> map(
Aart Bikf8f5a162017-02-06 15:35:29 -0800486 std::less<HInstruction*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
Vladimir Markoca6fff82017-10-03 14:49:14 +0100487 ScopedArenaSafeMap<HInstruction*, HInstruction*> perm(
Aart Bik0148de42017-09-05 09:25:01 -0700488 std::less<HInstruction*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
Aart Bikf8f5a162017-02-06 15:35:29 -0800489 // Attach.
Aart Bik8c4a8542016-10-06 11:36:57 -0700490 iset_ = &iset;
Aart Bikb29f6842017-07-28 15:58:41 -0700491 reductions_ = &reds;
Aart Bikf8f5a162017-02-06 15:35:29 -0800492 vector_refs_ = &refs;
493 vector_map_ = &map;
Aart Bik0148de42017-09-05 09:25:01 -0700494 vector_permanent_map_ = &perm;
Aart Bikf8f5a162017-02-06 15:35:29 -0800495 // Traverse.
Aart Bik8c4a8542016-10-06 11:36:57 -0700496 TraverseLoopsInnerToOuter(top_loop_);
Aart Bikf8f5a162017-02-06 15:35:29 -0800497 // Detach.
498 iset_ = nullptr;
Aart Bikb29f6842017-07-28 15:58:41 -0700499 reductions_ = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800500 vector_refs_ = nullptr;
501 vector_map_ = nullptr;
Aart Bik0148de42017-09-05 09:25:01 -0700502 vector_permanent_map_ = nullptr;
Aart Bik8c4a8542016-10-06 11:36:57 -0700503 }
Aart Bik281c6812016-08-26 11:31:48 -0700504}
505
506void HLoopOptimization::AddLoop(HLoopInformation* loop_info) {
507 DCHECK(loop_info != nullptr);
Aart Bikf8f5a162017-02-06 15:35:29 -0800508 LoopNode* node = new (loop_allocator_) LoopNode(loop_info);
Aart Bik281c6812016-08-26 11:31:48 -0700509 if (last_loop_ == nullptr) {
510 // First loop.
511 DCHECK(top_loop_ == nullptr);
512 last_loop_ = top_loop_ = node;
513 } else if (loop_info->IsIn(*last_loop_->loop_info)) {
514 // Inner loop.
515 node->outer = last_loop_;
516 DCHECK(last_loop_->inner == nullptr);
517 last_loop_ = last_loop_->inner = node;
518 } else {
519 // Subsequent loop.
520 while (last_loop_->outer != nullptr && !loop_info->IsIn(*last_loop_->outer->loop_info)) {
521 last_loop_ = last_loop_->outer;
522 }
523 node->outer = last_loop_->outer;
524 node->previous = last_loop_;
525 DCHECK(last_loop_->next == nullptr);
526 last_loop_ = last_loop_->next = node;
527 }
528}
529
530void HLoopOptimization::RemoveLoop(LoopNode* node) {
531 DCHECK(node != nullptr);
Aart Bik8c4a8542016-10-06 11:36:57 -0700532 DCHECK(node->inner == nullptr);
533 if (node->previous != nullptr) {
534 // Within sequence.
535 node->previous->next = node->next;
536 if (node->next != nullptr) {
537 node->next->previous = node->previous;
538 }
539 } else {
540 // First of sequence.
541 if (node->outer != nullptr) {
542 node->outer->inner = node->next;
543 } else {
544 top_loop_ = node->next;
545 }
546 if (node->next != nullptr) {
547 node->next->outer = node->outer;
548 node->next->previous = nullptr;
549 }
550 }
Aart Bik281c6812016-08-26 11:31:48 -0700551}
552
Aart Bikb29f6842017-07-28 15:58:41 -0700553bool HLoopOptimization::TraverseLoopsInnerToOuter(LoopNode* node) {
554 bool changed = false;
Aart Bik281c6812016-08-26 11:31:48 -0700555 for ( ; node != nullptr; node = node->next) {
Aart Bikb29f6842017-07-28 15:58:41 -0700556 // Visit inner loops first. Recompute induction information for this
557 // loop if the induction of any inner loop has changed.
558 if (TraverseLoopsInnerToOuter(node->inner)) {
Aart Bik482095d2016-10-10 15:39:10 -0700559 induction_range_.ReVisit(node->loop_info);
560 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800561 // Repeat simplifications in the loop-body until no more changes occur.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800562 // Note that since each simplification consists of eliminating code (without
563 // introducing new code), this process is always finite.
Aart Bikdf7822e2016-12-06 10:05:30 -0800564 do {
565 simplified_ = false;
Aart Bikdf7822e2016-12-06 10:05:30 -0800566 SimplifyInduction(node);
Aart Bik6b69e0a2017-01-11 10:20:43 -0800567 SimplifyBlocks(node);
Aart Bikb29f6842017-07-28 15:58:41 -0700568 changed = simplified_ || changed;
Aart Bikdf7822e2016-12-06 10:05:30 -0800569 } while (simplified_);
Aart Bikf8f5a162017-02-06 15:35:29 -0800570 // Optimize inner loop.
Aart Bik9abf8942016-10-14 09:49:42 -0700571 if (node->inner == nullptr) {
Aart Bikb29f6842017-07-28 15:58:41 -0700572 changed = OptimizeInnerLoop(node) || changed;
Aart Bik9abf8942016-10-14 09:49:42 -0700573 }
Aart Bik281c6812016-08-26 11:31:48 -0700574 }
Aart Bikb29f6842017-07-28 15:58:41 -0700575 return changed;
Aart Bik281c6812016-08-26 11:31:48 -0700576}
577
Aart Bikf8f5a162017-02-06 15:35:29 -0800578//
579// Optimization.
580//
581
Aart Bik281c6812016-08-26 11:31:48 -0700582void HLoopOptimization::SimplifyInduction(LoopNode* node) {
583 HBasicBlock* header = node->loop_info->GetHeader();
584 HBasicBlock* preheader = node->loop_info->GetPreHeader();
Aart Bik8c4a8542016-10-06 11:36:57 -0700585 // Scan the phis in the header to find opportunities to simplify an induction
586 // cycle that is only used outside the loop. Replace these uses, if any, with
587 // the last value and remove the induction cycle.
588 // Examples: for (int i = 0; x != null; i++) { .... no i .... }
589 // for (int i = 0; i < 10; i++, k++) { .... no k .... } return k;
Aart Bik281c6812016-08-26 11:31:48 -0700590 for (HInstructionIterator it(header->GetPhis()); !it.Done(); it.Advance()) {
591 HPhi* phi = it.Current()->AsPhi();
Aart Bikf8f5a162017-02-06 15:35:29 -0800592 if (TrySetPhiInduction(phi, /*restrict_uses*/ true) &&
593 TryAssignLastValue(node->loop_info, phi, preheader, /*collect_loop_uses*/ false)) {
Aart Bik671e48a2017-08-09 13:16:56 -0700594 // Note that it's ok to have replaced uses after the loop with the last value, without
595 // being able to remove the cycle. Environment uses (which are the reason we may not be
596 // able to remove the cycle) within the loop will still hold the right value. We must
597 // have tried first, however, to replace outside uses.
598 if (CanRemoveCycle()) {
599 simplified_ = true;
600 for (HInstruction* i : *iset_) {
601 RemoveFromCycle(i);
602 }
603 DCHECK(CheckInductionSetFullyRemoved(iset_));
Aart Bik281c6812016-08-26 11:31:48 -0700604 }
Aart Bik482095d2016-10-10 15:39:10 -0700605 }
606 }
607}
608
609void HLoopOptimization::SimplifyBlocks(LoopNode* node) {
Aart Bikdf7822e2016-12-06 10:05:30 -0800610 // Iterate over all basic blocks in the loop-body.
611 for (HBlocksInLoopIterator it(*node->loop_info); !it.Done(); it.Advance()) {
612 HBasicBlock* block = it.Current();
613 // Remove dead instructions from the loop-body.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800614 RemoveDeadInstructions(block->GetPhis());
615 RemoveDeadInstructions(block->GetInstructions());
Aart Bikdf7822e2016-12-06 10:05:30 -0800616 // Remove trivial control flow blocks from the loop-body.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800617 if (block->GetPredecessors().size() == 1 &&
618 block->GetSuccessors().size() == 1 &&
619 block->GetSingleSuccessor()->GetPredecessors().size() == 1) {
Aart Bikdf7822e2016-12-06 10:05:30 -0800620 simplified_ = true;
Aart Bik6b69e0a2017-01-11 10:20:43 -0800621 block->MergeWith(block->GetSingleSuccessor());
Aart Bikdf7822e2016-12-06 10:05:30 -0800622 } else if (block->GetSuccessors().size() == 2) {
623 // Trivial if block can be bypassed to either branch.
624 HBasicBlock* succ0 = block->GetSuccessors()[0];
625 HBasicBlock* succ1 = block->GetSuccessors()[1];
626 HBasicBlock* meet0 = nullptr;
627 HBasicBlock* meet1 = nullptr;
628 if (succ0 != succ1 &&
629 IsGotoBlock(succ0, &meet0) &&
630 IsGotoBlock(succ1, &meet1) &&
631 meet0 == meet1 && // meets again
632 meet0 != block && // no self-loop
633 meet0->GetPhis().IsEmpty()) { // not used for merging
634 simplified_ = true;
635 succ0->DisconnectAndDelete();
636 if (block->Dominates(meet0)) {
637 block->RemoveDominatedBlock(meet0);
638 succ1->AddDominatedBlock(meet0);
639 meet0->SetDominator(succ1);
Aart Bike3dedc52016-11-02 17:50:27 -0700640 }
Aart Bik482095d2016-10-10 15:39:10 -0700641 }
Aart Bik281c6812016-08-26 11:31:48 -0700642 }
Aart Bikdf7822e2016-12-06 10:05:30 -0800643 }
Aart Bik281c6812016-08-26 11:31:48 -0700644}
645
Aart Bikb29f6842017-07-28 15:58:41 -0700646bool HLoopOptimization::OptimizeInnerLoop(LoopNode* node) {
Aart Bik281c6812016-08-26 11:31:48 -0700647 HBasicBlock* header = node->loop_info->GetHeader();
648 HBasicBlock* preheader = node->loop_info->GetPreHeader();
Aart Bik9abf8942016-10-14 09:49:42 -0700649 // Ensure loop header logic is finite.
Aart Bikf8f5a162017-02-06 15:35:29 -0800650 int64_t trip_count = 0;
651 if (!induction_range_.IsFinite(node->loop_info, &trip_count)) {
Aart Bikb29f6842017-07-28 15:58:41 -0700652 return false;
Aart Bik9abf8942016-10-14 09:49:42 -0700653 }
Aart Bik281c6812016-08-26 11:31:48 -0700654 // Ensure there is only a single loop-body (besides the header).
655 HBasicBlock* body = nullptr;
656 for (HBlocksInLoopIterator it(*node->loop_info); !it.Done(); it.Advance()) {
657 if (it.Current() != header) {
658 if (body != nullptr) {
Aart Bikb29f6842017-07-28 15:58:41 -0700659 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700660 }
661 body = it.Current();
662 }
663 }
Andreas Gampef45d61c2017-06-07 10:29:33 -0700664 CHECK(body != nullptr);
Aart Bik281c6812016-08-26 11:31:48 -0700665 // Ensure there is only a single exit point.
666 if (header->GetSuccessors().size() != 2) {
Aart Bikb29f6842017-07-28 15:58:41 -0700667 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700668 }
669 HBasicBlock* exit = (header->GetSuccessors()[0] == body)
670 ? header->GetSuccessors()[1]
671 : header->GetSuccessors()[0];
Aart Bik8c4a8542016-10-06 11:36:57 -0700672 // Ensure exit can only be reached by exiting loop.
Aart Bik281c6812016-08-26 11:31:48 -0700673 if (exit->GetPredecessors().size() != 1) {
Aart Bikb29f6842017-07-28 15:58:41 -0700674 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700675 }
Aart Bik6b69e0a2017-01-11 10:20:43 -0800676 // Detect either an empty loop (no side effects other than plain iteration) or
677 // a trivial loop (just iterating once). Replace subsequent index uses, if any,
678 // with the last value and remove the loop, possibly after unrolling its body.
Aart Bikb29f6842017-07-28 15:58:41 -0700679 HPhi* main_phi = nullptr;
680 if (TrySetSimpleLoopHeader(header, &main_phi)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -0800681 bool is_empty = IsEmptyBody(body);
Aart Bikb29f6842017-07-28 15:58:41 -0700682 if (reductions_->empty() && // TODO: possible with some effort
683 (is_empty || trip_count == 1) &&
684 TryAssignLastValue(node->loop_info, main_phi, preheader, /*collect_loop_uses*/ true)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -0800685 if (!is_empty) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800686 // Unroll the loop-body, which sees initial value of the index.
Aart Bikb29f6842017-07-28 15:58:41 -0700687 main_phi->ReplaceWith(main_phi->InputAt(0));
Aart Bik6b69e0a2017-01-11 10:20:43 -0800688 preheader->MergeInstructionsWith(body);
689 }
690 body->DisconnectAndDelete();
691 exit->RemovePredecessor(header);
692 header->RemoveSuccessor(exit);
693 header->RemoveDominatedBlock(exit);
694 header->DisconnectAndDelete();
695 preheader->AddSuccessor(exit);
Aart Bikf8f5a162017-02-06 15:35:29 -0800696 preheader->AddInstruction(new (global_allocator_) HGoto());
Aart Bik6b69e0a2017-01-11 10:20:43 -0800697 preheader->AddDominatedBlock(exit);
698 exit->SetDominator(preheader);
699 RemoveLoop(node); // update hierarchy
Aart Bikb29f6842017-07-28 15:58:41 -0700700 return true;
Aart Bikf8f5a162017-02-06 15:35:29 -0800701 }
702 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800703 // Vectorize loop, if possible and valid.
Aart Bikb29f6842017-07-28 15:58:41 -0700704 if (kEnableVectorization &&
705 TrySetSimpleLoopHeader(header, &main_phi) &&
Aart Bikb29f6842017-07-28 15:58:41 -0700706 ShouldVectorize(node, body, trip_count) &&
707 TryAssignLastValue(node->loop_info, main_phi, preheader, /*collect_loop_uses*/ true)) {
708 Vectorize(node, body, exit, trip_count);
709 graph_->SetHasSIMD(true); // flag SIMD usage
Aart Bik21b85922017-09-06 13:29:16 -0700710 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorized);
Aart Bikb29f6842017-07-28 15:58:41 -0700711 return true;
Aart Bikf8f5a162017-02-06 15:35:29 -0800712 }
Aart Bikb29f6842017-07-28 15:58:41 -0700713 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -0800714}
715
716//
717// Loop vectorization. The implementation is based on the book by Aart J.C. Bik:
718// "The Software Vectorization Handbook. Applying Multimedia Extensions for Maximum Performance."
719// Intel Press, June, 2004 (http://www.aartbik.com/).
720//
721
Aart Bik14a68b42017-06-08 14:06:58 -0700722bool HLoopOptimization::ShouldVectorize(LoopNode* node, HBasicBlock* block, int64_t trip_count) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800723 // Reset vector bookkeeping.
724 vector_length_ = 0;
725 vector_refs_->clear();
Aart Bik38a3f212017-10-20 17:02:21 -0700726 vector_static_peeling_factor_ = 0;
727 vector_dynamic_peeling_candidate_ = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800728 vector_runtime_test_a_ =
Igor Murashkin2ffb7032017-11-08 13:35:21 -0800729 vector_runtime_test_b_ = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800730
731 // Phis in the loop-body prevent vectorization.
732 if (!block->GetPhis().IsEmpty()) {
733 return false;
734 }
735
736 // Scan the loop-body, starting a right-hand-side tree traversal at each left-hand-side
737 // occurrence, which allows passing down attributes down the use tree.
738 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
739 if (!VectorizeDef(node, it.Current(), /*generate_code*/ false)) {
740 return false; // failure to vectorize a left-hand-side
741 }
742 }
743
Aart Bik38a3f212017-10-20 17:02:21 -0700744 // Prepare alignment analysis:
745 // (1) find desired alignment (SIMD vector size in bytes).
746 // (2) initialize static loop peeling votes (peeling factor that will
747 // make one particular reference aligned), never to exceed (1).
748 // (3) variable to record how many references share same alignment.
749 // (4) variable to record suitable candidate for dynamic loop peeling.
750 uint32_t desired_alignment = GetVectorSizeInBytes();
751 DCHECK_LE(desired_alignment, 16u);
752 uint32_t peeling_votes[16] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
753 uint32_t max_num_same_alignment = 0;
754 const ArrayReference* peeling_candidate = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800755
756 // Data dependence analysis. Find each pair of references with same type, where
757 // at least one is a write. Each such pair denotes a possible data dependence.
758 // This analysis exploits the property that differently typed arrays cannot be
759 // aliased, as well as the property that references either point to the same
760 // array or to two completely disjoint arrays, i.e., no partial aliasing.
761 // Other than a few simply heuristics, no detailed subscript analysis is done.
Aart Bik38a3f212017-10-20 17:02:21 -0700762 // The scan over references also prepares finding a suitable alignment strategy.
Aart Bikf8f5a162017-02-06 15:35:29 -0800763 for (auto i = vector_refs_->begin(); i != vector_refs_->end(); ++i) {
Aart Bik38a3f212017-10-20 17:02:21 -0700764 uint32_t num_same_alignment = 0;
765 // Scan over all next references.
Aart Bikf8f5a162017-02-06 15:35:29 -0800766 for (auto j = i; ++j != vector_refs_->end(); ) {
767 if (i->type == j->type && (i->lhs || j->lhs)) {
768 // Found same-typed a[i+x] vs. b[i+y], where at least one is a write.
769 HInstruction* a = i->base;
770 HInstruction* b = j->base;
771 HInstruction* x = i->offset;
772 HInstruction* y = j->offset;
773 if (a == b) {
774 // Found a[i+x] vs. a[i+y]. Accept if x == y (loop-independent data dependence).
775 // Conservatively assume a loop-carried data dependence otherwise, and reject.
776 if (x != y) {
777 return false;
778 }
Aart Bik38a3f212017-10-20 17:02:21 -0700779 // Count the number of references that have the same alignment (since
780 // base and offset are the same) and where at least one is a write, so
781 // e.g. a[i] = a[i] + b[i] counts a[i] but not b[i]).
782 num_same_alignment++;
Aart Bikf8f5a162017-02-06 15:35:29 -0800783 } else {
784 // Found a[i+x] vs. b[i+y]. Accept if x == y (at worst loop-independent data dependence).
785 // Conservatively assume a potential loop-carried data dependence otherwise, avoided by
786 // generating an explicit a != b disambiguation runtime test on the two references.
787 if (x != y) {
Aart Bik37dc4df2017-06-28 14:08:00 -0700788 // To avoid excessive overhead, we only accept one a != b test.
789 if (vector_runtime_test_a_ == nullptr) {
790 // First test found.
791 vector_runtime_test_a_ = a;
792 vector_runtime_test_b_ = b;
793 } else if ((vector_runtime_test_a_ != a || vector_runtime_test_b_ != b) &&
794 (vector_runtime_test_a_ != b || vector_runtime_test_b_ != a)) {
795 return false; // second test would be needed
Aart Bikf8f5a162017-02-06 15:35:29 -0800796 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800797 }
798 }
799 }
800 }
Aart Bik38a3f212017-10-20 17:02:21 -0700801 // Update information for finding suitable alignment strategy:
802 // (1) update votes for static loop peeling,
803 // (2) update suitable candidate for dynamic loop peeling.
804 Alignment alignment = ComputeAlignment(i->offset, i->type, i->is_string_char_at);
805 if (alignment.Base() >= desired_alignment) {
806 // If the array/string object has a known, sufficient alignment, use the
807 // initial offset to compute the static loop peeling vote (this always
808 // works, since elements have natural alignment).
809 uint32_t offset = alignment.Offset() & (desired_alignment - 1u);
810 uint32_t vote = (offset == 0)
811 ? 0
812 : ((desired_alignment - offset) >> DataType::SizeShift(i->type));
813 DCHECK_LT(vote, 16u);
814 ++peeling_votes[vote];
815 } else if (BaseAlignment() >= desired_alignment &&
816 num_same_alignment > max_num_same_alignment) {
817 // Otherwise, if the array/string object has a known, sufficient alignment
818 // for just the base but with an unknown offset, record the candidate with
819 // the most occurrences for dynamic loop peeling (again, the peeling always
820 // works, since elements have natural alignment).
821 max_num_same_alignment = num_same_alignment;
822 peeling_candidate = &(*i);
823 }
824 } // for i
Aart Bikf8f5a162017-02-06 15:35:29 -0800825
Aart Bik38a3f212017-10-20 17:02:21 -0700826 // Find a suitable alignment strategy.
827 SetAlignmentStrategy(peeling_votes, peeling_candidate);
828
829 // Does vectorization seem profitable?
830 if (!IsVectorizationProfitable(trip_count)) {
831 return false;
832 }
Aart Bik14a68b42017-06-08 14:06:58 -0700833
Aart Bikf8f5a162017-02-06 15:35:29 -0800834 // Success!
835 return true;
836}
837
838void HLoopOptimization::Vectorize(LoopNode* node,
839 HBasicBlock* block,
840 HBasicBlock* exit,
841 int64_t trip_count) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800842 HBasicBlock* header = node->loop_info->GetHeader();
843 HBasicBlock* preheader = node->loop_info->GetPreHeader();
844
Aart Bik14a68b42017-06-08 14:06:58 -0700845 // Pick a loop unrolling factor for the vector loop.
846 uint32_t unroll = GetUnrollingFactor(block, trip_count);
847 uint32_t chunk = vector_length_ * unroll;
848
Aart Bik38a3f212017-10-20 17:02:21 -0700849 DCHECK(trip_count == 0 || (trip_count >= MaxNumberPeeled() + chunk));
850
Aart Bik14a68b42017-06-08 14:06:58 -0700851 // A cleanup loop is needed, at least, for any unknown trip count or
852 // for a known trip count with remainder iterations after vectorization.
Aart Bik38a3f212017-10-20 17:02:21 -0700853 bool needs_cleanup = trip_count == 0 ||
854 ((trip_count - vector_static_peeling_factor_) % chunk) != 0;
Aart Bikf8f5a162017-02-06 15:35:29 -0800855
856 // Adjust vector bookkeeping.
Aart Bikb29f6842017-07-28 15:58:41 -0700857 HPhi* main_phi = nullptr;
858 bool is_simple_loop_header = TrySetSimpleLoopHeader(header, &main_phi); // refills sets
Aart Bikf8f5a162017-02-06 15:35:29 -0800859 DCHECK(is_simple_loop_header);
Aart Bik14a68b42017-06-08 14:06:58 -0700860 vector_header_ = header;
861 vector_body_ = block;
Aart Bikf8f5a162017-02-06 15:35:29 -0800862
Aart Bikdbbac8f2017-09-01 13:06:08 -0700863 // Loop induction type.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100864 DataType::Type induc_type = main_phi->GetType();
865 DCHECK(induc_type == DataType::Type::kInt32 || induc_type == DataType::Type::kInt64)
866 << induc_type;
Aart Bikdbbac8f2017-09-01 13:06:08 -0700867
Aart Bik38a3f212017-10-20 17:02:21 -0700868 // Generate the trip count for static or dynamic loop peeling, if needed:
869 // ptc = <peeling factor>;
Aart Bik14a68b42017-06-08 14:06:58 -0700870 HInstruction* ptc = nullptr;
Aart Bik38a3f212017-10-20 17:02:21 -0700871 if (vector_static_peeling_factor_ != 0) {
872 // Static loop peeling for SIMD alignment (using the most suitable
873 // fixed peeling factor found during prior alignment analysis).
874 DCHECK(vector_dynamic_peeling_candidate_ == nullptr);
875 ptc = graph_->GetConstant(induc_type, vector_static_peeling_factor_);
876 } else if (vector_dynamic_peeling_candidate_ != nullptr) {
877 // Dynamic loop peeling for SIMD alignment (using the most suitable
878 // candidate found during prior alignment analysis):
879 // rem = offset % ALIGN; // adjusted as #elements
880 // ptc = rem == 0 ? 0 : (ALIGN - rem);
881 uint32_t shift = DataType::SizeShift(vector_dynamic_peeling_candidate_->type);
882 uint32_t align = GetVectorSizeInBytes() >> shift;
883 uint32_t hidden_offset = HiddenOffset(vector_dynamic_peeling_candidate_->type,
884 vector_dynamic_peeling_candidate_->is_string_char_at);
885 HInstruction* adjusted_offset = graph_->GetConstant(induc_type, hidden_offset >> shift);
886 HInstruction* offset = Insert(preheader, new (global_allocator_) HAdd(
887 induc_type, vector_dynamic_peeling_candidate_->offset, adjusted_offset));
888 HInstruction* rem = Insert(preheader, new (global_allocator_) HAnd(
889 induc_type, offset, graph_->GetConstant(induc_type, align - 1u)));
890 HInstruction* sub = Insert(preheader, new (global_allocator_) HSub(
891 induc_type, graph_->GetConstant(induc_type, align), rem));
892 HInstruction* cond = Insert(preheader, new (global_allocator_) HEqual(
893 rem, graph_->GetConstant(induc_type, 0)));
894 ptc = Insert(preheader, new (global_allocator_) HSelect(
895 cond, graph_->GetConstant(induc_type, 0), sub, kNoDexPc));
896 needs_cleanup = true; // don't know the exact amount
Aart Bik14a68b42017-06-08 14:06:58 -0700897 }
898
899 // Generate loop control:
Aart Bikf8f5a162017-02-06 15:35:29 -0800900 // stc = <trip-count>;
Aart Bik38a3f212017-10-20 17:02:21 -0700901 // ptc = min(stc, ptc);
Aart Bik14a68b42017-06-08 14:06:58 -0700902 // vtc = stc - (stc - ptc) % chunk;
903 // i = 0;
Aart Bikf8f5a162017-02-06 15:35:29 -0800904 HInstruction* stc = induction_range_.GenerateTripCount(node->loop_info, graph_, preheader);
905 HInstruction* vtc = stc;
906 if (needs_cleanup) {
Aart Bik14a68b42017-06-08 14:06:58 -0700907 DCHECK(IsPowerOfTwo(chunk));
908 HInstruction* diff = stc;
909 if (ptc != nullptr) {
Aart Bik38a3f212017-10-20 17:02:21 -0700910 if (trip_count == 0) {
911 HInstruction* cond = Insert(preheader, new (global_allocator_) HAboveOrEqual(stc, ptc));
912 ptc = Insert(preheader, new (global_allocator_) HSelect(cond, ptc, stc, kNoDexPc));
913 }
Aart Bik14a68b42017-06-08 14:06:58 -0700914 diff = Insert(preheader, new (global_allocator_) HSub(induc_type, stc, ptc));
915 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800916 HInstruction* rem = Insert(
917 preheader, new (global_allocator_) HAnd(induc_type,
Aart Bik14a68b42017-06-08 14:06:58 -0700918 diff,
Aart Bikdbbac8f2017-09-01 13:06:08 -0700919 graph_->GetConstant(induc_type, chunk - 1)));
Aart Bikf8f5a162017-02-06 15:35:29 -0800920 vtc = Insert(preheader, new (global_allocator_) HSub(induc_type, stc, rem));
921 }
Aart Bikdbbac8f2017-09-01 13:06:08 -0700922 vector_index_ = graph_->GetConstant(induc_type, 0);
Aart Bikf8f5a162017-02-06 15:35:29 -0800923
924 // Generate runtime disambiguation test:
925 // vtc = a != b ? vtc : 0;
926 if (vector_runtime_test_a_ != nullptr) {
927 HInstruction* rt = Insert(
928 preheader,
929 new (global_allocator_) HNotEqual(vector_runtime_test_a_, vector_runtime_test_b_));
930 vtc = Insert(preheader,
Aart Bikdbbac8f2017-09-01 13:06:08 -0700931 new (global_allocator_)
932 HSelect(rt, vtc, graph_->GetConstant(induc_type, 0), kNoDexPc));
Aart Bikf8f5a162017-02-06 15:35:29 -0800933 needs_cleanup = true;
934 }
935
Aart Bik38a3f212017-10-20 17:02:21 -0700936 // Generate alignment peeling loop, if needed:
Aart Bik14a68b42017-06-08 14:06:58 -0700937 // for ( ; i < ptc; i += 1)
938 // <loop-body>
Aart Bik38a3f212017-10-20 17:02:21 -0700939 //
940 // NOTE: The alignment forced by the peeling loop is preserved even if data is
941 // moved around during suspend checks, since all analysis was based on
942 // nothing more than the Android runtime alignment conventions.
Aart Bik14a68b42017-06-08 14:06:58 -0700943 if (ptc != nullptr) {
944 vector_mode_ = kSequential;
945 GenerateNewLoop(node,
946 block,
947 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
948 vector_index_,
949 ptc,
Aart Bikdbbac8f2017-09-01 13:06:08 -0700950 graph_->GetConstant(induc_type, 1),
Aart Bik521b50f2017-09-09 10:44:45 -0700951 kNoUnrollingFactor);
Aart Bik14a68b42017-06-08 14:06:58 -0700952 }
953
954 // Generate vector loop, possibly further unrolled:
955 // for ( ; i < vtc; i += chunk)
Aart Bikf8f5a162017-02-06 15:35:29 -0800956 // <vectorized-loop-body>
957 vector_mode_ = kVector;
958 GenerateNewLoop(node,
959 block,
Aart Bik14a68b42017-06-08 14:06:58 -0700960 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
961 vector_index_,
Aart Bikf8f5a162017-02-06 15:35:29 -0800962 vtc,
Aart Bikdbbac8f2017-09-01 13:06:08 -0700963 graph_->GetConstant(induc_type, vector_length_), // increment per unroll
Aart Bik14a68b42017-06-08 14:06:58 -0700964 unroll);
Aart Bikf8f5a162017-02-06 15:35:29 -0800965 HLoopInformation* vloop = vector_header_->GetLoopInformation();
966
967 // Generate cleanup loop, if needed:
968 // for ( ; i < stc; i += 1)
969 // <loop-body>
970 if (needs_cleanup) {
971 vector_mode_ = kSequential;
972 GenerateNewLoop(node,
973 block,
974 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
Aart Bik14a68b42017-06-08 14:06:58 -0700975 vector_index_,
Aart Bikf8f5a162017-02-06 15:35:29 -0800976 stc,
Aart Bikdbbac8f2017-09-01 13:06:08 -0700977 graph_->GetConstant(induc_type, 1),
Aart Bik521b50f2017-09-09 10:44:45 -0700978 kNoUnrollingFactor);
Aart Bikf8f5a162017-02-06 15:35:29 -0800979 }
980
Aart Bik0148de42017-09-05 09:25:01 -0700981 // Link reductions to their final uses.
982 for (auto i = reductions_->begin(); i != reductions_->end(); ++i) {
983 if (i->first->IsPhi()) {
Aart Bikdbbac8f2017-09-01 13:06:08 -0700984 HInstruction* phi = i->first;
985 HInstruction* repl = ReduceAndExtractIfNeeded(i->second);
986 // Deal with regular uses.
987 for (const HUseListNode<HInstruction*>& use : phi->GetUses()) {
988 induction_range_.Replace(use.GetUser(), phi, repl); // update induction use
989 }
990 phi->ReplaceWith(repl);
Aart Bik0148de42017-09-05 09:25:01 -0700991 }
992 }
993
Aart Bikf8f5a162017-02-06 15:35:29 -0800994 // Remove the original loop by disconnecting the body block
995 // and removing all instructions from the header.
996 block->DisconnectAndDelete();
997 while (!header->GetFirstInstruction()->IsGoto()) {
998 header->RemoveInstruction(header->GetFirstInstruction());
999 }
Aart Bikb29f6842017-07-28 15:58:41 -07001000
Aart Bik14a68b42017-06-08 14:06:58 -07001001 // Update loop hierarchy: the old header now resides in the same outer loop
1002 // as the old preheader. Note that we don't bother putting sequential
1003 // loops back in the hierarchy at this point.
Aart Bikf8f5a162017-02-06 15:35:29 -08001004 header->SetLoopInformation(preheader->GetLoopInformation()); // outward
1005 node->loop_info = vloop;
1006}
1007
1008void HLoopOptimization::GenerateNewLoop(LoopNode* node,
1009 HBasicBlock* block,
1010 HBasicBlock* new_preheader,
1011 HInstruction* lo,
1012 HInstruction* hi,
Aart Bik14a68b42017-06-08 14:06:58 -07001013 HInstruction* step,
1014 uint32_t unroll) {
1015 DCHECK(unroll == 1 || vector_mode_ == kVector);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001016 DataType::Type induc_type = lo->GetType();
Aart Bikf8f5a162017-02-06 15:35:29 -08001017 // Prepare new loop.
Aart Bikf8f5a162017-02-06 15:35:29 -08001018 vector_preheader_ = new_preheader,
1019 vector_header_ = vector_preheader_->GetSingleSuccessor();
1020 vector_body_ = vector_header_->GetSuccessors()[1];
Aart Bik14a68b42017-06-08 14:06:58 -07001021 HPhi* phi = new (global_allocator_) HPhi(global_allocator_,
1022 kNoRegNumber,
1023 0,
1024 HPhi::ToPhiType(induc_type));
Aart Bikb07d1bc2017-04-05 10:03:15 -07001025 // Generate header and prepare body.
Aart Bikf8f5a162017-02-06 15:35:29 -08001026 // for (i = lo; i < hi; i += step)
1027 // <loop-body>
Aart Bik14a68b42017-06-08 14:06:58 -07001028 HInstruction* cond = new (global_allocator_) HAboveOrEqual(phi, hi);
1029 vector_header_->AddPhi(phi);
Aart Bikf8f5a162017-02-06 15:35:29 -08001030 vector_header_->AddInstruction(cond);
1031 vector_header_->AddInstruction(new (global_allocator_) HIf(cond));
Aart Bik14a68b42017-06-08 14:06:58 -07001032 vector_index_ = phi;
Aart Bik0148de42017-09-05 09:25:01 -07001033 vector_permanent_map_->clear(); // preserved over unrolling
Aart Bik14a68b42017-06-08 14:06:58 -07001034 for (uint32_t u = 0; u < unroll; u++) {
Aart Bik14a68b42017-06-08 14:06:58 -07001035 // Generate instruction map.
Aart Bik0148de42017-09-05 09:25:01 -07001036 vector_map_->clear();
Aart Bik14a68b42017-06-08 14:06:58 -07001037 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
1038 bool vectorized_def = VectorizeDef(node, it.Current(), /*generate_code*/ true);
1039 DCHECK(vectorized_def);
1040 }
1041 // Generate body from the instruction map, but in original program order.
1042 HEnvironment* env = vector_header_->GetFirstInstruction()->GetEnvironment();
1043 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
1044 auto i = vector_map_->find(it.Current());
1045 if (i != vector_map_->end() && !i->second->IsInBlock()) {
1046 Insert(vector_body_, i->second);
1047 // Deal with instructions that need an environment, such as the scalar intrinsics.
1048 if (i->second->NeedsEnvironment()) {
1049 i->second->CopyEnvironmentFromWithLoopPhiAdjustment(env, vector_header_);
1050 }
1051 }
1052 }
Aart Bik0148de42017-09-05 09:25:01 -07001053 // Generate the induction.
Aart Bik14a68b42017-06-08 14:06:58 -07001054 vector_index_ = new (global_allocator_) HAdd(induc_type, vector_index_, step);
1055 Insert(vector_body_, vector_index_);
Aart Bikf8f5a162017-02-06 15:35:29 -08001056 }
Aart Bik0148de42017-09-05 09:25:01 -07001057 // Finalize phi inputs for the reductions (if any).
1058 for (auto i = reductions_->begin(); i != reductions_->end(); ++i) {
1059 if (!i->first->IsPhi()) {
1060 DCHECK(i->second->IsPhi());
1061 GenerateVecReductionPhiInputs(i->second->AsPhi(), i->first);
1062 }
1063 }
Aart Bikb29f6842017-07-28 15:58:41 -07001064 // Finalize phi inputs for the loop index.
Aart Bik14a68b42017-06-08 14:06:58 -07001065 phi->AddInput(lo);
1066 phi->AddInput(vector_index_);
1067 vector_index_ = phi;
Aart Bikf8f5a162017-02-06 15:35:29 -08001068}
1069
Aart Bikf8f5a162017-02-06 15:35:29 -08001070bool HLoopOptimization::VectorizeDef(LoopNode* node,
1071 HInstruction* instruction,
1072 bool generate_code) {
1073 // Accept a left-hand-side array base[index] for
1074 // (1) supported vector type,
1075 // (2) loop-invariant base,
1076 // (3) unit stride index,
1077 // (4) vectorizable right-hand-side value.
1078 uint64_t restrictions = kNone;
1079 if (instruction->IsArraySet()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001080 DataType::Type type = instruction->AsArraySet()->GetComponentType();
Aart Bikf8f5a162017-02-06 15:35:29 -08001081 HInstruction* base = instruction->InputAt(0);
1082 HInstruction* index = instruction->InputAt(1);
1083 HInstruction* value = instruction->InputAt(2);
1084 HInstruction* offset = nullptr;
1085 if (TrySetVectorType(type, &restrictions) &&
1086 node->loop_info->IsDefinedOutOfTheLoop(base) &&
Aart Bik37dc4df2017-06-28 14:08:00 -07001087 induction_range_.IsUnitStride(instruction, index, graph_, &offset) &&
Aart Bikf8f5a162017-02-06 15:35:29 -08001088 VectorizeUse(node, value, generate_code, type, restrictions)) {
1089 if (generate_code) {
1090 GenerateVecSub(index, offset);
Aart Bik14a68b42017-06-08 14:06:58 -07001091 GenerateVecMem(instruction, vector_map_->Get(index), vector_map_->Get(value), offset, type);
Aart Bikf8f5a162017-02-06 15:35:29 -08001092 } else {
1093 vector_refs_->insert(ArrayReference(base, offset, type, /*lhs*/ true));
1094 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08001095 return true;
1096 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001097 return false;
1098 }
Aart Bik0148de42017-09-05 09:25:01 -07001099 // Accept a left-hand-side reduction for
1100 // (1) supported vector type,
1101 // (2) vectorizable right-hand-side value.
1102 auto redit = reductions_->find(instruction);
1103 if (redit != reductions_->end()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001104 DataType::Type type = instruction->GetType();
Aart Bikdbbac8f2017-09-01 13:06:08 -07001105 // Recognize SAD idiom or direct reduction.
1106 if (VectorizeSADIdiom(node, instruction, generate_code, type, restrictions) ||
1107 (TrySetVectorType(type, &restrictions) &&
1108 VectorizeUse(node, instruction, generate_code, type, restrictions))) {
Aart Bik0148de42017-09-05 09:25:01 -07001109 if (generate_code) {
1110 HInstruction* new_red = vector_map_->Get(instruction);
1111 vector_permanent_map_->Put(new_red, vector_map_->Get(redit->second));
1112 vector_permanent_map_->Overwrite(redit->second, new_red);
1113 }
1114 return true;
1115 }
1116 return false;
1117 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001118 // Branch back okay.
1119 if (instruction->IsGoto()) {
1120 return true;
1121 }
1122 // Otherwise accept only expressions with no effects outside the immediate loop-body.
1123 // Note that actual uses are inspected during right-hand-side tree traversal.
1124 return !IsUsedOutsideLoop(node->loop_info, instruction) && !instruction->DoesAnyWrite();
1125}
1126
Aart Bik304c8a52017-05-23 11:01:13 -07001127// TODO: saturation arithmetic.
Aart Bikf8f5a162017-02-06 15:35:29 -08001128bool HLoopOptimization::VectorizeUse(LoopNode* node,
1129 HInstruction* instruction,
1130 bool generate_code,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001131 DataType::Type type,
Aart Bikf8f5a162017-02-06 15:35:29 -08001132 uint64_t restrictions) {
1133 // Accept anything for which code has already been generated.
1134 if (generate_code) {
1135 if (vector_map_->find(instruction) != vector_map_->end()) {
1136 return true;
1137 }
1138 }
1139 // Continue the right-hand-side tree traversal, passing in proper
1140 // types and vector restrictions along the way. During code generation,
1141 // all new nodes are drawn from the global allocator.
1142 if (node->loop_info->IsDefinedOutOfTheLoop(instruction)) {
1143 // Accept invariant use, using scalar expansion.
1144 if (generate_code) {
1145 GenerateVecInv(instruction, type);
1146 }
1147 return true;
1148 } else if (instruction->IsArrayGet()) {
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001149 // Deal with vector restrictions.
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001150 bool is_string_char_at = instruction->AsArrayGet()->IsStringCharAt();
1151 if (is_string_char_at && HasVectorRestrictions(restrictions, kNoStringCharAt)) {
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001152 return false;
1153 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001154 // Accept a right-hand-side array base[index] for
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001155 // (1) matching vector type (exact match or signed/unsigned integral type of the same size),
Aart Bikf8f5a162017-02-06 15:35:29 -08001156 // (2) loop-invariant base,
1157 // (3) unit stride index,
1158 // (4) vectorizable right-hand-side value.
1159 HInstruction* base = instruction->InputAt(0);
1160 HInstruction* index = instruction->InputAt(1);
1161 HInstruction* offset = nullptr;
Aart Bik46b6dbc2017-10-03 11:37:37 -07001162 if (HVecOperation::ToSignedType(type) == HVecOperation::ToSignedType(instruction->GetType()) &&
Aart Bikf8f5a162017-02-06 15:35:29 -08001163 node->loop_info->IsDefinedOutOfTheLoop(base) &&
Aart Bik37dc4df2017-06-28 14:08:00 -07001164 induction_range_.IsUnitStride(instruction, index, graph_, &offset)) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001165 if (generate_code) {
1166 GenerateVecSub(index, offset);
Aart Bik14a68b42017-06-08 14:06:58 -07001167 GenerateVecMem(instruction, vector_map_->Get(index), nullptr, offset, type);
Aart Bikf8f5a162017-02-06 15:35:29 -08001168 } else {
Aart Bik38a3f212017-10-20 17:02:21 -07001169 vector_refs_->insert(ArrayReference(base, offset, type, /*lhs*/ false, is_string_char_at));
Aart Bikf8f5a162017-02-06 15:35:29 -08001170 }
1171 return true;
1172 }
Aart Bik0148de42017-09-05 09:25:01 -07001173 } else if (instruction->IsPhi()) {
1174 // Accept particular phi operations.
1175 if (reductions_->find(instruction) != reductions_->end()) {
1176 // Deal with vector restrictions.
1177 if (HasVectorRestrictions(restrictions, kNoReduction)) {
1178 return false;
1179 }
1180 // Accept a reduction.
1181 if (generate_code) {
1182 GenerateVecReductionPhi(instruction->AsPhi());
1183 }
1184 return true;
1185 }
1186 // TODO: accept right-hand-side induction?
1187 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001188 } else if (instruction->IsTypeConversion()) {
1189 // Accept particular type conversions.
1190 HTypeConversion* conversion = instruction->AsTypeConversion();
1191 HInstruction* opa = conversion->InputAt(0);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001192 DataType::Type from = conversion->GetInputType();
1193 DataType::Type to = conversion->GetResultType();
1194 if (DataType::IsIntegralType(from) && DataType::IsIntegralType(to)) {
Aart Bik38a3f212017-10-20 17:02:21 -07001195 uint32_t size_vec = DataType::Size(type);
1196 uint32_t size_from = DataType::Size(from);
1197 uint32_t size_to = DataType::Size(to);
Aart Bikdbbac8f2017-09-01 13:06:08 -07001198 // Accept an integral conversion
1199 // (1a) narrowing into vector type, "wider" operations cannot bring in higher order bits, or
1200 // (1b) widening from at least vector type, and
1201 // (2) vectorizable operand.
1202 if ((size_to < size_from &&
1203 size_to == size_vec &&
1204 VectorizeUse(node, opa, generate_code, type, restrictions | kNoHiBits)) ||
1205 (size_to >= size_from &&
1206 size_from >= size_vec &&
Aart Bik4d1a9d42017-10-19 14:40:55 -07001207 VectorizeUse(node, opa, generate_code, type, restrictions))) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001208 if (generate_code) {
1209 if (vector_mode_ == kVector) {
1210 vector_map_->Put(instruction, vector_map_->Get(opa)); // operand pass-through
1211 } else {
1212 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1213 }
1214 }
1215 return true;
1216 }
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001217 } else if (to == DataType::Type::kFloat32 && from == DataType::Type::kInt32) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001218 DCHECK_EQ(to, type);
1219 // Accept int to float conversion for
1220 // (1) supported int,
1221 // (2) vectorizable operand.
1222 if (TrySetVectorType(from, &restrictions) &&
1223 VectorizeUse(node, opa, generate_code, from, restrictions)) {
1224 if (generate_code) {
1225 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1226 }
1227 return true;
1228 }
1229 }
1230 return false;
1231 } else if (instruction->IsNeg() || instruction->IsNot() || instruction->IsBooleanNot()) {
1232 // Accept unary operator for vectorizable operand.
1233 HInstruction* opa = instruction->InputAt(0);
1234 if (VectorizeUse(node, opa, generate_code, type, restrictions)) {
1235 if (generate_code) {
1236 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1237 }
1238 return true;
1239 }
1240 } else if (instruction->IsAdd() || instruction->IsSub() ||
1241 instruction->IsMul() || instruction->IsDiv() ||
1242 instruction->IsAnd() || instruction->IsOr() || instruction->IsXor()) {
1243 // Deal with vector restrictions.
1244 if ((instruction->IsMul() && HasVectorRestrictions(restrictions, kNoMul)) ||
1245 (instruction->IsDiv() && HasVectorRestrictions(restrictions, kNoDiv))) {
1246 return false;
1247 }
1248 // Accept binary operator for vectorizable operands.
1249 HInstruction* opa = instruction->InputAt(0);
1250 HInstruction* opb = instruction->InputAt(1);
1251 if (VectorizeUse(node, opa, generate_code, type, restrictions) &&
1252 VectorizeUse(node, opb, generate_code, type, restrictions)) {
1253 if (generate_code) {
1254 GenerateVecOp(instruction, vector_map_->Get(opa), vector_map_->Get(opb), type);
1255 }
1256 return true;
1257 }
1258 } else if (instruction->IsShl() || instruction->IsShr() || instruction->IsUShr()) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001259 // Recognize halving add idiom.
Aart Bikf3e61ee2017-04-12 17:09:20 -07001260 if (VectorizeHalvingAddIdiom(node, instruction, generate_code, type, restrictions)) {
1261 return true;
1262 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001263 // Deal with vector restrictions.
Aart Bik304c8a52017-05-23 11:01:13 -07001264 HInstruction* opa = instruction->InputAt(0);
1265 HInstruction* opb = instruction->InputAt(1);
1266 HInstruction* r = opa;
1267 bool is_unsigned = false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001268 if ((HasVectorRestrictions(restrictions, kNoShift)) ||
1269 (instruction->IsShr() && HasVectorRestrictions(restrictions, kNoShr))) {
1270 return false; // unsupported instruction
Aart Bik304c8a52017-05-23 11:01:13 -07001271 } else if (HasVectorRestrictions(restrictions, kNoHiBits)) {
1272 // Shifts right need extra care to account for higher order bits.
1273 // TODO: less likely shr/unsigned and ushr/signed can by flipping signess.
1274 if (instruction->IsShr() &&
1275 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || is_unsigned)) {
1276 return false; // reject, unless all operands are sign-extension narrower
1277 } else if (instruction->IsUShr() &&
1278 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || !is_unsigned)) {
1279 return false; // reject, unless all operands are zero-extension narrower
1280 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001281 }
1282 // Accept shift operator for vectorizable/invariant operands.
1283 // TODO: accept symbolic, albeit loop invariant shift factors.
Aart Bik304c8a52017-05-23 11:01:13 -07001284 DCHECK(r != nullptr);
1285 if (generate_code && vector_mode_ != kVector) { // de-idiom
1286 r = opa;
1287 }
Aart Bik50e20d52017-05-05 14:07:29 -07001288 int64_t distance = 0;
Aart Bik304c8a52017-05-23 11:01:13 -07001289 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
Aart Bik50e20d52017-05-05 14:07:29 -07001290 IsInt64AndGet(opb, /*out*/ &distance)) {
Aart Bik65ffd8e2017-05-01 16:50:45 -07001291 // Restrict shift distance to packed data type width.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001292 int64_t max_distance = DataType::Size(type) * 8;
Aart Bik65ffd8e2017-05-01 16:50:45 -07001293 if (0 <= distance && distance < max_distance) {
1294 if (generate_code) {
Aart Bik304c8a52017-05-23 11:01:13 -07001295 GenerateVecOp(instruction, vector_map_->Get(r), opb, type);
Aart Bik65ffd8e2017-05-01 16:50:45 -07001296 }
1297 return true;
Aart Bikf8f5a162017-02-06 15:35:29 -08001298 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001299 }
Aart Bik3b2a5952018-03-05 13:55:28 -08001300 } else if (instruction->IsAbs()) {
1301 // Deal with vector restrictions.
1302 HInstruction* opa = instruction->InputAt(0);
1303 HInstruction* r = opa;
1304 bool is_unsigned = false;
1305 if (HasVectorRestrictions(restrictions, kNoAbs)) {
1306 return false;
1307 } else if (HasVectorRestrictions(restrictions, kNoHiBits) &&
1308 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || is_unsigned)) {
1309 return false; // reject, unless operand is sign-extension narrower
1310 }
1311 // Accept ABS(x) for vectorizable operand.
1312 DCHECK(r != nullptr);
1313 if (generate_code && vector_mode_ != kVector) { // de-idiom
1314 r = opa;
1315 }
1316 if (VectorizeUse(node, r, generate_code, type, restrictions)) {
1317 if (generate_code) {
1318 GenerateVecOp(instruction,
1319 vector_map_->Get(r),
1320 nullptr,
1321 HVecOperation::ToProperType(type, is_unsigned));
1322 }
1323 return true;
1324 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001325 } else if (instruction->IsInvokeStaticOrDirect()) {
Aart Bik6daebeb2017-04-03 14:35:41 -07001326 // Accept particular intrinsics.
1327 HInvokeStaticOrDirect* invoke = instruction->AsInvokeStaticOrDirect();
1328 switch (invoke->GetIntrinsic()) {
Aart Bikc8e93c72017-05-10 10:49:22 -07001329 case Intrinsics::kMathMinIntInt:
1330 case Intrinsics::kMathMinLongLong:
1331 case Intrinsics::kMathMinFloatFloat:
1332 case Intrinsics::kMathMinDoubleDouble:
1333 case Intrinsics::kMathMaxIntInt:
1334 case Intrinsics::kMathMaxLongLong:
1335 case Intrinsics::kMathMaxFloatFloat:
1336 case Intrinsics::kMathMaxDoubleDouble: {
1337 // Deal with vector restrictions.
Nicolas Geoffray92316902017-05-23 08:06:07 +00001338 HInstruction* opa = instruction->InputAt(0);
1339 HInstruction* opb = instruction->InputAt(1);
Aart Bik304c8a52017-05-23 11:01:13 -07001340 HInstruction* r = opa;
1341 HInstruction* s = opb;
1342 bool is_unsigned = false;
1343 if (HasVectorRestrictions(restrictions, kNoMinMax)) {
1344 return false;
1345 } else if (HasVectorRestrictions(restrictions, kNoHiBits) &&
1346 !IsNarrowerOperands(opa, opb, type, &r, &s, &is_unsigned)) {
1347 return false; // reject, unless all operands are same-extension narrower
1348 }
1349 // Accept MIN/MAX(x, y) for vectorizable operands.
Aart Bikdbbac8f2017-09-01 13:06:08 -07001350 DCHECK(r != nullptr);
1351 DCHECK(s != nullptr);
Aart Bik304c8a52017-05-23 11:01:13 -07001352 if (generate_code && vector_mode_ != kVector) { // de-idiom
1353 r = opa;
1354 s = opb;
1355 }
1356 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
1357 VectorizeUse(node, s, generate_code, type, restrictions)) {
Aart Bikc8e93c72017-05-10 10:49:22 -07001358 if (generate_code) {
Aart Bik304c8a52017-05-23 11:01:13 -07001359 GenerateVecOp(
1360 instruction, vector_map_->Get(r), vector_map_->Get(s), type, is_unsigned);
Aart Bikc8e93c72017-05-10 10:49:22 -07001361 }
1362 return true;
1363 }
1364 return false;
1365 }
Aart Bik6daebeb2017-04-03 14:35:41 -07001366 default:
1367 return false;
1368 } // switch
Aart Bik281c6812016-08-26 11:31:48 -07001369 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08001370 return false;
Aart Bik281c6812016-08-26 11:31:48 -07001371}
1372
Aart Bik38a3f212017-10-20 17:02:21 -07001373uint32_t HLoopOptimization::GetVectorSizeInBytes() {
1374 switch (compiler_driver_->GetInstructionSet()) {
Vladimir Marko33bff252017-11-01 14:35:42 +00001375 case InstructionSet::kArm:
1376 case InstructionSet::kThumb2:
Aart Bik38a3f212017-10-20 17:02:21 -07001377 return 8; // 64-bit SIMD
1378 default:
1379 return 16; // 128-bit SIMD
1380 }
1381}
1382
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001383bool HLoopOptimization::TrySetVectorType(DataType::Type type, uint64_t* restrictions) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001384 const InstructionSetFeatures* features = compiler_driver_->GetInstructionSetFeatures();
1385 switch (compiler_driver_->GetInstructionSet()) {
Vladimir Marko33bff252017-11-01 14:35:42 +00001386 case InstructionSet::kArm:
1387 case InstructionSet::kThumb2:
Artem Serov8f7c4102017-06-21 11:21:37 +01001388 // Allow vectorization for all ARM devices, because Android assumes that
Aart Bikb29f6842017-07-28 15:58:41 -07001389 // ARM 32-bit always supports advanced SIMD (64-bit SIMD).
Artem Serov8f7c4102017-06-21 11:21:37 +01001390 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001391 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001392 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001393 case DataType::Type::kInt8:
Aart Bik0148de42017-09-05 09:25:01 -07001394 *restrictions |= kNoDiv | kNoReduction;
Artem Serov8f7c4102017-06-21 11:21:37 +01001395 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001396 case DataType::Type::kUint16:
1397 case DataType::Type::kInt16:
Aart Bik0148de42017-09-05 09:25:01 -07001398 *restrictions |= kNoDiv | kNoStringCharAt | kNoReduction;
Artem Serov8f7c4102017-06-21 11:21:37 +01001399 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001400 case DataType::Type::kInt32:
Artem Serov6e9b1372017-10-05 16:48:30 +01001401 *restrictions |= kNoDiv | kNoWideSAD;
Artem Serov8f7c4102017-06-21 11:21:37 +01001402 return TrySetVectorLength(2);
1403 default:
1404 break;
1405 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001406 return false;
Vladimir Marko33bff252017-11-01 14:35:42 +00001407 case InstructionSet::kArm64:
Aart Bikf8f5a162017-02-06 15:35:29 -08001408 // Allow vectorization for all ARM devices, because Android assumes that
Aart Bikb29f6842017-07-28 15:58:41 -07001409 // ARMv8 AArch64 always supports advanced SIMD (128-bit SIMD).
Aart Bikf8f5a162017-02-06 15:35:29 -08001410 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001411 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001412 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001413 case DataType::Type::kInt8:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001414 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +01001415 return TrySetVectorLength(16);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001416 case DataType::Type::kUint16:
1417 case DataType::Type::kInt16:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001418 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +01001419 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001420 case DataType::Type::kInt32:
Aart Bikf8f5a162017-02-06 15:35:29 -08001421 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +01001422 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001423 case DataType::Type::kInt64:
Aart Bikc8e93c72017-05-10 10:49:22 -07001424 *restrictions |= kNoDiv | kNoMul | kNoMinMax;
Aart Bikf8f5a162017-02-06 15:35:29 -08001425 return TrySetVectorLength(2);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001426 case DataType::Type::kFloat32:
Aart Bik0148de42017-09-05 09:25:01 -07001427 *restrictions |= kNoReduction;
Artem Serovd4bccf12017-04-03 18:47:32 +01001428 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001429 case DataType::Type::kFloat64:
Aart Bik0148de42017-09-05 09:25:01 -07001430 *restrictions |= kNoReduction;
Aart Bikf8f5a162017-02-06 15:35:29 -08001431 return TrySetVectorLength(2);
1432 default:
1433 return false;
1434 }
Vladimir Marko33bff252017-11-01 14:35:42 +00001435 case InstructionSet::kX86:
1436 case InstructionSet::kX86_64:
Aart Bikb29f6842017-07-28 15:58:41 -07001437 // Allow vectorization for SSE4.1-enabled X86 devices only (128-bit SIMD).
Aart Bikf8f5a162017-02-06 15:35:29 -08001438 if (features->AsX86InstructionSetFeatures()->HasSSE4_1()) {
1439 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001440 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001441 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001442 case DataType::Type::kInt8:
Aart Bik0148de42017-09-05 09:25:01 -07001443 *restrictions |=
Aart Bikdbbac8f2017-09-01 13:06:08 -07001444 kNoMul | kNoDiv | kNoShift | kNoAbs | kNoSignedHAdd | kNoUnroundedHAdd | kNoSAD;
Aart Bikf8f5a162017-02-06 15:35:29 -08001445 return TrySetVectorLength(16);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001446 case DataType::Type::kUint16:
1447 case DataType::Type::kInt16:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001448 *restrictions |= kNoDiv | kNoAbs | kNoSignedHAdd | kNoUnroundedHAdd | kNoSAD;
Aart Bikf8f5a162017-02-06 15:35:29 -08001449 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001450 case DataType::Type::kInt32:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001451 *restrictions |= kNoDiv | kNoSAD;
Aart Bikf8f5a162017-02-06 15:35:29 -08001452 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001453 case DataType::Type::kInt64:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001454 *restrictions |= kNoMul | kNoDiv | kNoShr | kNoAbs | kNoMinMax | kNoSAD;
Aart Bikf8f5a162017-02-06 15:35:29 -08001455 return TrySetVectorLength(2);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001456 case DataType::Type::kFloat32:
Aart Bik0148de42017-09-05 09:25:01 -07001457 *restrictions |= kNoMinMax | kNoReduction; // minmax: -0.0 vs +0.0
Aart Bikf8f5a162017-02-06 15:35:29 -08001458 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001459 case DataType::Type::kFloat64:
Aart Bik0148de42017-09-05 09:25:01 -07001460 *restrictions |= kNoMinMax | kNoReduction; // minmax: -0.0 vs +0.0
Aart Bikf8f5a162017-02-06 15:35:29 -08001461 return TrySetVectorLength(2);
1462 default:
1463 break;
1464 } // switch type
1465 }
1466 return false;
Vladimir Marko33bff252017-11-01 14:35:42 +00001467 case InstructionSet::kMips:
Lena Djokic51765b02017-06-22 13:49:59 +02001468 if (features->AsMipsInstructionSetFeatures()->HasMsa()) {
1469 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001470 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001471 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001472 case DataType::Type::kInt8:
Lena Djokic38e380b2017-10-30 16:17:10 +01001473 *restrictions |= kNoDiv;
Lena Djokic51765b02017-06-22 13:49:59 +02001474 return TrySetVectorLength(16);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001475 case DataType::Type::kUint16:
1476 case DataType::Type::kInt16:
Lena Djokic38e380b2017-10-30 16:17:10 +01001477 *restrictions |= kNoDiv | kNoStringCharAt;
Lena Djokic51765b02017-06-22 13:49:59 +02001478 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001479 case DataType::Type::kInt32:
Lena Djokic38e380b2017-10-30 16:17:10 +01001480 *restrictions |= kNoDiv;
Lena Djokic51765b02017-06-22 13:49:59 +02001481 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001482 case DataType::Type::kInt64:
Lena Djokic38e380b2017-10-30 16:17:10 +01001483 *restrictions |= kNoDiv;
Lena Djokic51765b02017-06-22 13:49:59 +02001484 return TrySetVectorLength(2);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001485 case DataType::Type::kFloat32:
Aart Bik0148de42017-09-05 09:25:01 -07001486 *restrictions |= kNoMinMax | kNoReduction; // min/max(x, NaN)
Lena Djokic51765b02017-06-22 13:49:59 +02001487 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001488 case DataType::Type::kFloat64:
Aart Bik0148de42017-09-05 09:25:01 -07001489 *restrictions |= kNoMinMax | kNoReduction; // min/max(x, NaN)
Lena Djokic51765b02017-06-22 13:49:59 +02001490 return TrySetVectorLength(2);
1491 default:
1492 break;
1493 } // switch type
1494 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001495 return false;
Vladimir Marko33bff252017-11-01 14:35:42 +00001496 case InstructionSet::kMips64:
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001497 if (features->AsMips64InstructionSetFeatures()->HasMsa()) {
1498 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001499 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001500 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001501 case DataType::Type::kInt8:
Lena Djokic38e380b2017-10-30 16:17:10 +01001502 *restrictions |= kNoDiv;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001503 return TrySetVectorLength(16);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001504 case DataType::Type::kUint16:
1505 case DataType::Type::kInt16:
Lena Djokic38e380b2017-10-30 16:17:10 +01001506 *restrictions |= kNoDiv | kNoStringCharAt;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001507 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001508 case DataType::Type::kInt32:
Lena Djokic38e380b2017-10-30 16:17:10 +01001509 *restrictions |= kNoDiv;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001510 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001511 case DataType::Type::kInt64:
Lena Djokic38e380b2017-10-30 16:17:10 +01001512 *restrictions |= kNoDiv;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001513 return TrySetVectorLength(2);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001514 case DataType::Type::kFloat32:
Aart Bik0148de42017-09-05 09:25:01 -07001515 *restrictions |= kNoMinMax | kNoReduction; // min/max(x, NaN)
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001516 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001517 case DataType::Type::kFloat64:
Aart Bik0148de42017-09-05 09:25:01 -07001518 *restrictions |= kNoMinMax | kNoReduction; // min/max(x, NaN)
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001519 return TrySetVectorLength(2);
1520 default:
1521 break;
1522 } // switch type
1523 }
1524 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001525 default:
1526 return false;
1527 } // switch instruction set
1528}
1529
1530bool HLoopOptimization::TrySetVectorLength(uint32_t length) {
1531 DCHECK(IsPowerOfTwo(length) && length >= 2u);
1532 // First time set?
1533 if (vector_length_ == 0) {
1534 vector_length_ = length;
1535 }
1536 // Different types are acceptable within a loop-body, as long as all the corresponding vector
1537 // lengths match exactly to obtain a uniform traversal through the vector iteration space
1538 // (idiomatic exceptions to this rule can be handled by further unrolling sub-expressions).
1539 return vector_length_ == length;
1540}
1541
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001542void HLoopOptimization::GenerateVecInv(HInstruction* org, DataType::Type type) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001543 if (vector_map_->find(org) == vector_map_->end()) {
1544 // In scalar code, just use a self pass-through for scalar invariants
1545 // (viz. expression remains itself).
1546 if (vector_mode_ == kSequential) {
1547 vector_map_->Put(org, org);
1548 return;
1549 }
1550 // In vector code, explicit scalar expansion is needed.
Aart Bik0148de42017-09-05 09:25:01 -07001551 HInstruction* vector = nullptr;
1552 auto it = vector_permanent_map_->find(org);
1553 if (it != vector_permanent_map_->end()) {
1554 vector = it->second; // reuse during unrolling
1555 } else {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001556 // Generates ReplicateScalar( (optional_type_conv) org ).
1557 HInstruction* input = org;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001558 DataType::Type input_type = input->GetType();
1559 if (type != input_type && (type == DataType::Type::kInt64 ||
1560 input_type == DataType::Type::kInt64)) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001561 input = Insert(vector_preheader_,
1562 new (global_allocator_) HTypeConversion(type, input, kNoDexPc));
1563 }
1564 vector = new (global_allocator_)
Aart Bik46b6dbc2017-10-03 11:37:37 -07001565 HVecReplicateScalar(global_allocator_, input, type, vector_length_, kNoDexPc);
Aart Bik0148de42017-09-05 09:25:01 -07001566 vector_permanent_map_->Put(org, Insert(vector_preheader_, vector));
1567 }
1568 vector_map_->Put(org, vector);
Aart Bikf8f5a162017-02-06 15:35:29 -08001569 }
1570}
1571
1572void HLoopOptimization::GenerateVecSub(HInstruction* org, HInstruction* offset) {
1573 if (vector_map_->find(org) == vector_map_->end()) {
Aart Bik14a68b42017-06-08 14:06:58 -07001574 HInstruction* subscript = vector_index_;
Aart Bik37dc4df2017-06-28 14:08:00 -07001575 int64_t value = 0;
1576 if (!IsInt64AndGet(offset, &value) || value != 0) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001577 subscript = new (global_allocator_) HAdd(DataType::Type::kInt32, subscript, offset);
Aart Bikf8f5a162017-02-06 15:35:29 -08001578 if (org->IsPhi()) {
1579 Insert(vector_body_, subscript); // lacks layout placeholder
1580 }
1581 }
1582 vector_map_->Put(org, subscript);
1583 }
1584}
1585
1586void HLoopOptimization::GenerateVecMem(HInstruction* org,
1587 HInstruction* opa,
1588 HInstruction* opb,
Aart Bik14a68b42017-06-08 14:06:58 -07001589 HInstruction* offset,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001590 DataType::Type type) {
Aart Bik46b6dbc2017-10-03 11:37:37 -07001591 uint32_t dex_pc = org->GetDexPc();
Aart Bikf8f5a162017-02-06 15:35:29 -08001592 HInstruction* vector = nullptr;
1593 if (vector_mode_ == kVector) {
1594 // Vector store or load.
Aart Bik38a3f212017-10-20 17:02:21 -07001595 bool is_string_char_at = false;
Aart Bik14a68b42017-06-08 14:06:58 -07001596 HInstruction* base = org->InputAt(0);
Aart Bikf8f5a162017-02-06 15:35:29 -08001597 if (opb != nullptr) {
1598 vector = new (global_allocator_) HVecStore(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001599 global_allocator_, base, opa, opb, type, org->GetSideEffects(), vector_length_, dex_pc);
Aart Bikf8f5a162017-02-06 15:35:29 -08001600 } else {
Aart Bik38a3f212017-10-20 17:02:21 -07001601 is_string_char_at = org->AsArrayGet()->IsStringCharAt();
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001602 vector = new (global_allocator_) HVecLoad(global_allocator_,
1603 base,
1604 opa,
1605 type,
1606 org->GetSideEffects(),
1607 vector_length_,
Aart Bik46b6dbc2017-10-03 11:37:37 -07001608 is_string_char_at,
1609 dex_pc);
Aart Bik14a68b42017-06-08 14:06:58 -07001610 }
Aart Bik38a3f212017-10-20 17:02:21 -07001611 // Known (forced/adjusted/original) alignment?
1612 if (vector_dynamic_peeling_candidate_ != nullptr) {
1613 if (vector_dynamic_peeling_candidate_->offset == offset && // TODO: diffs too?
1614 DataType::Size(vector_dynamic_peeling_candidate_->type) == DataType::Size(type) &&
1615 vector_dynamic_peeling_candidate_->is_string_char_at == is_string_char_at) {
1616 vector->AsVecMemoryOperation()->SetAlignment( // forced
1617 Alignment(GetVectorSizeInBytes(), 0));
1618 }
1619 } else {
1620 vector->AsVecMemoryOperation()->SetAlignment( // adjusted/original
1621 ComputeAlignment(offset, type, is_string_char_at, vector_static_peeling_factor_));
Aart Bikf8f5a162017-02-06 15:35:29 -08001622 }
1623 } else {
1624 // Scalar store or load.
1625 DCHECK(vector_mode_ == kSequential);
1626 if (opb != nullptr) {
Aart Bik4d1a9d42017-10-19 14:40:55 -07001627 DataType::Type component_type = org->AsArraySet()->GetComponentType();
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001628 vector = new (global_allocator_) HArraySet(
Aart Bik4d1a9d42017-10-19 14:40:55 -07001629 org->InputAt(0), opa, opb, component_type, org->GetSideEffects(), dex_pc);
Aart Bikf8f5a162017-02-06 15:35:29 -08001630 } else {
Aart Bikdb14fcf2017-04-25 15:53:58 -07001631 bool is_string_char_at = org->AsArrayGet()->IsStringCharAt();
1632 vector = new (global_allocator_) HArrayGet(
Aart Bik4d1a9d42017-10-19 14:40:55 -07001633 org->InputAt(0), opa, org->GetType(), org->GetSideEffects(), dex_pc, is_string_char_at);
Aart Bikf8f5a162017-02-06 15:35:29 -08001634 }
1635 }
1636 vector_map_->Put(org, vector);
1637}
1638
Aart Bik0148de42017-09-05 09:25:01 -07001639void HLoopOptimization::GenerateVecReductionPhi(HPhi* phi) {
1640 DCHECK(reductions_->find(phi) != reductions_->end());
1641 DCHECK(reductions_->Get(phi->InputAt(1)) == phi);
1642 HInstruction* vector = nullptr;
1643 if (vector_mode_ == kSequential) {
1644 HPhi* new_phi = new (global_allocator_) HPhi(
1645 global_allocator_, kNoRegNumber, 0, phi->GetType());
1646 vector_header_->AddPhi(new_phi);
1647 vector = new_phi;
1648 } else {
1649 // Link vector reduction back to prior unrolled update, or a first phi.
1650 auto it = vector_permanent_map_->find(phi);
1651 if (it != vector_permanent_map_->end()) {
1652 vector = it->second;
1653 } else {
1654 HPhi* new_phi = new (global_allocator_) HPhi(
1655 global_allocator_, kNoRegNumber, 0, HVecOperation::kSIMDType);
1656 vector_header_->AddPhi(new_phi);
1657 vector = new_phi;
1658 }
1659 }
1660 vector_map_->Put(phi, vector);
1661}
1662
1663void HLoopOptimization::GenerateVecReductionPhiInputs(HPhi* phi, HInstruction* reduction) {
1664 HInstruction* new_phi = vector_map_->Get(phi);
1665 HInstruction* new_init = reductions_->Get(phi);
1666 HInstruction* new_red = vector_map_->Get(reduction);
1667 // Link unrolled vector loop back to new phi.
1668 for (; !new_phi->IsPhi(); new_phi = vector_permanent_map_->Get(new_phi)) {
1669 DCHECK(new_phi->IsVecOperation());
1670 }
1671 // Prepare the new initialization.
1672 if (vector_mode_ == kVector) {
Goran Jakovljevic89b8df02017-10-13 08:33:17 +02001673 // Generate a [initial, 0, .., 0] vector for add or
1674 // a [initial, initial, .., initial] vector for min/max.
Aart Bikdbbac8f2017-09-01 13:06:08 -07001675 HVecOperation* red_vector = new_red->AsVecOperation();
Goran Jakovljevic89b8df02017-10-13 08:33:17 +02001676 HVecReduce::ReductionKind kind = GetReductionKind(red_vector);
Aart Bik38a3f212017-10-20 17:02:21 -07001677 uint32_t vector_length = red_vector->GetVectorLength();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001678 DataType::Type type = red_vector->GetPackedType();
Goran Jakovljevic89b8df02017-10-13 08:33:17 +02001679 if (kind == HVecReduce::ReductionKind::kSum) {
1680 new_init = Insert(vector_preheader_,
1681 new (global_allocator_) HVecSetScalars(global_allocator_,
1682 &new_init,
1683 type,
1684 vector_length,
1685 1,
1686 kNoDexPc));
1687 } else {
1688 new_init = Insert(vector_preheader_,
1689 new (global_allocator_) HVecReplicateScalar(global_allocator_,
1690 new_init,
1691 type,
1692 vector_length,
1693 kNoDexPc));
1694 }
Aart Bik0148de42017-09-05 09:25:01 -07001695 } else {
1696 new_init = ReduceAndExtractIfNeeded(new_init);
1697 }
1698 // Set the phi inputs.
1699 DCHECK(new_phi->IsPhi());
1700 new_phi->AsPhi()->AddInput(new_init);
1701 new_phi->AsPhi()->AddInput(new_red);
1702 // New feed value for next phi (safe mutation in iteration).
1703 reductions_->find(phi)->second = new_phi;
1704}
1705
1706HInstruction* HLoopOptimization::ReduceAndExtractIfNeeded(HInstruction* instruction) {
1707 if (instruction->IsPhi()) {
1708 HInstruction* input = instruction->InputAt(1);
Aart Bik2dd7b672017-12-07 11:11:22 -08001709 if (HVecOperation::ReturnsSIMDValue(input)) {
1710 DCHECK(!input->IsPhi());
Aart Bikdbbac8f2017-09-01 13:06:08 -07001711 HVecOperation* input_vector = input->AsVecOperation();
Aart Bik38a3f212017-10-20 17:02:21 -07001712 uint32_t vector_length = input_vector->GetVectorLength();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001713 DataType::Type type = input_vector->GetPackedType();
Aart Bikdbbac8f2017-09-01 13:06:08 -07001714 HVecReduce::ReductionKind kind = GetReductionKind(input_vector);
Aart Bik0148de42017-09-05 09:25:01 -07001715 HBasicBlock* exit = instruction->GetBlock()->GetSuccessors()[0];
1716 // Generate a vector reduction and scalar extract
1717 // x = REDUCE( [x_1, .., x_n] )
1718 // y = x_1
1719 // along the exit of the defining loop.
Aart Bik0148de42017-09-05 09:25:01 -07001720 HInstruction* reduce = new (global_allocator_) HVecReduce(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001721 global_allocator_, instruction, type, vector_length, kind, kNoDexPc);
Aart Bik0148de42017-09-05 09:25:01 -07001722 exit->InsertInstructionBefore(reduce, exit->GetFirstInstruction());
1723 instruction = new (global_allocator_) HVecExtractScalar(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001724 global_allocator_, reduce, type, vector_length, 0, kNoDexPc);
Aart Bik0148de42017-09-05 09:25:01 -07001725 exit->InsertInstructionAfter(instruction, reduce);
1726 }
1727 }
1728 return instruction;
1729}
1730
Aart Bikf8f5a162017-02-06 15:35:29 -08001731#define GENERATE_VEC(x, y) \
1732 if (vector_mode_ == kVector) { \
1733 vector = (x); \
1734 } else { \
1735 DCHECK(vector_mode_ == kSequential); \
1736 vector = (y); \
1737 } \
1738 break;
1739
1740void HLoopOptimization::GenerateVecOp(HInstruction* org,
1741 HInstruction* opa,
1742 HInstruction* opb,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001743 DataType::Type type,
Aart Bik304c8a52017-05-23 11:01:13 -07001744 bool is_unsigned) {
Aart Bik46b6dbc2017-10-03 11:37:37 -07001745 uint32_t dex_pc = org->GetDexPc();
Aart Bikf8f5a162017-02-06 15:35:29 -08001746 HInstruction* vector = nullptr;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001747 DataType::Type org_type = org->GetType();
Aart Bikf8f5a162017-02-06 15:35:29 -08001748 switch (org->GetKind()) {
1749 case HInstruction::kNeg:
1750 DCHECK(opb == nullptr);
1751 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001752 new (global_allocator_) HVecNeg(global_allocator_, opa, type, vector_length_, dex_pc),
1753 new (global_allocator_) HNeg(org_type, opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001754 case HInstruction::kNot:
1755 DCHECK(opb == nullptr);
1756 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001757 new (global_allocator_) HVecNot(global_allocator_, opa, type, vector_length_, dex_pc),
1758 new (global_allocator_) HNot(org_type, opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001759 case HInstruction::kBooleanNot:
1760 DCHECK(opb == nullptr);
1761 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001762 new (global_allocator_) HVecNot(global_allocator_, opa, type, vector_length_, dex_pc),
1763 new (global_allocator_) HBooleanNot(opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001764 case HInstruction::kTypeConversion:
1765 DCHECK(opb == nullptr);
1766 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001767 new (global_allocator_) HVecCnv(global_allocator_, opa, type, vector_length_, dex_pc),
1768 new (global_allocator_) HTypeConversion(org_type, opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001769 case HInstruction::kAdd:
1770 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001771 new (global_allocator_) HVecAdd(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1772 new (global_allocator_) HAdd(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001773 case HInstruction::kSub:
1774 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001775 new (global_allocator_) HVecSub(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1776 new (global_allocator_) HSub(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001777 case HInstruction::kMul:
1778 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001779 new (global_allocator_) HVecMul(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1780 new (global_allocator_) HMul(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001781 case HInstruction::kDiv:
1782 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001783 new (global_allocator_) HVecDiv(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1784 new (global_allocator_) HDiv(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001785 case HInstruction::kAnd:
1786 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001787 new (global_allocator_) HVecAnd(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1788 new (global_allocator_) HAnd(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001789 case HInstruction::kOr:
1790 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001791 new (global_allocator_) HVecOr(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1792 new (global_allocator_) HOr(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001793 case HInstruction::kXor:
1794 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001795 new (global_allocator_) HVecXor(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1796 new (global_allocator_) HXor(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001797 case HInstruction::kShl:
1798 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001799 new (global_allocator_) HVecShl(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1800 new (global_allocator_) HShl(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001801 case HInstruction::kShr:
1802 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001803 new (global_allocator_) HVecShr(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1804 new (global_allocator_) HShr(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001805 case HInstruction::kUShr:
1806 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001807 new (global_allocator_) HVecUShr(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1808 new (global_allocator_) HUShr(org_type, opa, opb, dex_pc));
Aart Bik3b2a5952018-03-05 13:55:28 -08001809 case HInstruction::kAbs:
1810 DCHECK(opb == nullptr);
1811 GENERATE_VEC(
1812 new (global_allocator_) HVecAbs(global_allocator_, opa, type, vector_length_, dex_pc),
1813 new (global_allocator_) HAbs(org_type, opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001814 case HInstruction::kInvokeStaticOrDirect: {
Aart Bik6daebeb2017-04-03 14:35:41 -07001815 HInvokeStaticOrDirect* invoke = org->AsInvokeStaticOrDirect();
1816 if (vector_mode_ == kVector) {
1817 switch (invoke->GetIntrinsic()) {
Aart Bikc8e93c72017-05-10 10:49:22 -07001818 case Intrinsics::kMathMinIntInt:
1819 case Intrinsics::kMathMinLongLong:
1820 case Intrinsics::kMathMinFloatFloat:
1821 case Intrinsics::kMathMinDoubleDouble: {
Aart Bikc8e93c72017-05-10 10:49:22 -07001822 vector = new (global_allocator_)
Aart Bik66c158e2018-01-31 12:55:04 -08001823 HVecMin(global_allocator_,
1824 opa,
1825 opb,
1826 HVecOperation::ToProperType(type, is_unsigned),
1827 vector_length_,
1828 dex_pc);
Aart Bikc8e93c72017-05-10 10:49:22 -07001829 break;
1830 }
1831 case Intrinsics::kMathMaxIntInt:
1832 case Intrinsics::kMathMaxLongLong:
1833 case Intrinsics::kMathMaxFloatFloat:
1834 case Intrinsics::kMathMaxDoubleDouble: {
Aart Bikc8e93c72017-05-10 10:49:22 -07001835 vector = new (global_allocator_)
Aart Bik66c158e2018-01-31 12:55:04 -08001836 HVecMax(global_allocator_,
1837 opa,
1838 opb,
1839 HVecOperation::ToProperType(type, is_unsigned),
1840 vector_length_,
1841 dex_pc);
Aart Bikc8e93c72017-05-10 10:49:22 -07001842 break;
1843 }
Aart Bik6daebeb2017-04-03 14:35:41 -07001844 default:
Aart Bik38a3f212017-10-20 17:02:21 -07001845 LOG(FATAL) << "Unsupported SIMD intrinsic " << org->GetId();
Aart Bik6daebeb2017-04-03 14:35:41 -07001846 UNREACHABLE();
1847 } // switch invoke
1848 } else {
Aart Bik24b905f2017-04-06 09:59:06 -07001849 // In scalar code, simply clone the method invoke, and replace its operands with the
1850 // corresponding new scalar instructions in the loop. The instruction will get an
1851 // environment while being inserted from the instruction map in original program order.
Aart Bik6daebeb2017-04-03 14:35:41 -07001852 DCHECK(vector_mode_ == kSequential);
Aart Bik6e92fb32017-06-05 14:05:09 -07001853 size_t num_args = invoke->GetNumberOfArguments();
Aart Bik6daebeb2017-04-03 14:35:41 -07001854 HInvokeStaticOrDirect* new_invoke = new (global_allocator_) HInvokeStaticOrDirect(
1855 global_allocator_,
Aart Bik6e92fb32017-06-05 14:05:09 -07001856 num_args,
Aart Bik6daebeb2017-04-03 14:35:41 -07001857 invoke->GetType(),
1858 invoke->GetDexPc(),
1859 invoke->GetDexMethodIndex(),
1860 invoke->GetResolvedMethod(),
1861 invoke->GetDispatchInfo(),
1862 invoke->GetInvokeType(),
1863 invoke->GetTargetMethod(),
1864 invoke->GetClinitCheckRequirement());
1865 HInputsRef inputs = invoke->GetInputs();
Aart Bik6e92fb32017-06-05 14:05:09 -07001866 size_t num_inputs = inputs.size();
1867 DCHECK_LE(num_args, num_inputs);
1868 DCHECK_EQ(num_inputs, new_invoke->GetInputs().size()); // both invokes agree
1869 for (size_t index = 0; index < num_inputs; ++index) {
1870 HInstruction* new_input = index < num_args
1871 ? vector_map_->Get(inputs[index])
1872 : inputs[index]; // beyond arguments: just pass through
1873 new_invoke->SetArgumentAt(index, new_input);
Aart Bik6daebeb2017-04-03 14:35:41 -07001874 }
Aart Bik98990262017-04-10 13:15:57 -07001875 new_invoke->SetIntrinsic(invoke->GetIntrinsic(),
1876 kNeedsEnvironmentOrCache,
1877 kNoSideEffects,
1878 kNoThrow);
Aart Bik6daebeb2017-04-03 14:35:41 -07001879 vector = new_invoke;
1880 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001881 break;
1882 }
1883 default:
1884 break;
1885 } // switch
1886 CHECK(vector != nullptr) << "Unsupported SIMD operator";
1887 vector_map_->Put(org, vector);
1888}
1889
1890#undef GENERATE_VEC
1891
1892//
Aart Bikf3e61ee2017-04-12 17:09:20 -07001893// Vectorization idioms.
1894//
1895
1896// Method recognizes the following idioms:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001897// rounding halving add (a + b + 1) >> 1 for unsigned/signed operands a, b
1898// truncated halving add (a + b) >> 1 for unsigned/signed operands a, b
Aart Bikf3e61ee2017-04-12 17:09:20 -07001899// Provided that the operands are promoted to a wider form to do the arithmetic and
1900// then cast back to narrower form, the idioms can be mapped into efficient SIMD
1901// implementation that operates directly in narrower form (plus one extra bit).
1902// TODO: current version recognizes implicit byte/short/char widening only;
1903// explicit widening from int to long could be added later.
1904bool HLoopOptimization::VectorizeHalvingAddIdiom(LoopNode* node,
1905 HInstruction* instruction,
1906 bool generate_code,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001907 DataType::Type type,
Aart Bikf3e61ee2017-04-12 17:09:20 -07001908 uint64_t restrictions) {
1909 // Test for top level arithmetic shift right x >> 1 or logical shift right x >>> 1
Aart Bik304c8a52017-05-23 11:01:13 -07001910 // (note whether the sign bit in wider precision is shifted in has no effect
Aart Bikf3e61ee2017-04-12 17:09:20 -07001911 // on the narrow precision computed by the idiom).
Aart Bikf3e61ee2017-04-12 17:09:20 -07001912 if ((instruction->IsShr() ||
1913 instruction->IsUShr()) &&
Aart Bik0148de42017-09-05 09:25:01 -07001914 IsInt64Value(instruction->InputAt(1), 1)) {
Aart Bik5f805002017-05-16 16:42:41 -07001915 // Test for (a + b + c) >> 1 for optional constant c.
1916 HInstruction* a = nullptr;
1917 HInstruction* b = nullptr;
1918 int64_t c = 0;
1919 if (IsAddConst(instruction->InputAt(0), /*out*/ &a, /*out*/ &b, /*out*/ &c)) {
Aart Bik304c8a52017-05-23 11:01:13 -07001920 DCHECK(a != nullptr && b != nullptr);
Aart Bik5f805002017-05-16 16:42:41 -07001921 // Accept c == 1 (rounded) or c == 0 (not rounded).
1922 bool is_rounded = false;
1923 if (c == 1) {
1924 is_rounded = true;
1925 } else if (c != 0) {
1926 return false;
1927 }
1928 // Accept consistent zero or sign extension on operands a and b.
Aart Bikf3e61ee2017-04-12 17:09:20 -07001929 HInstruction* r = nullptr;
1930 HInstruction* s = nullptr;
1931 bool is_unsigned = false;
Aart Bik304c8a52017-05-23 11:01:13 -07001932 if (!IsNarrowerOperands(a, b, type, &r, &s, &is_unsigned)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -07001933 return false;
1934 }
1935 // Deal with vector restrictions.
1936 if ((!is_unsigned && HasVectorRestrictions(restrictions, kNoSignedHAdd)) ||
1937 (!is_rounded && HasVectorRestrictions(restrictions, kNoUnroundedHAdd))) {
1938 return false;
1939 }
1940 // Accept recognized halving add for vectorizable operands. Vectorized code uses the
1941 // shorthand idiomatic operation. Sequential code uses the original scalar expressions.
Aart Bikdbbac8f2017-09-01 13:06:08 -07001942 DCHECK(r != nullptr);
1943 DCHECK(s != nullptr);
Aart Bik304c8a52017-05-23 11:01:13 -07001944 if (generate_code && vector_mode_ != kVector) { // de-idiom
1945 r = instruction->InputAt(0);
1946 s = instruction->InputAt(1);
1947 }
Aart Bikf3e61ee2017-04-12 17:09:20 -07001948 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
1949 VectorizeUse(node, s, generate_code, type, restrictions)) {
1950 if (generate_code) {
1951 if (vector_mode_ == kVector) {
1952 vector_map_->Put(instruction, new (global_allocator_) HVecHalvingAdd(
1953 global_allocator_,
1954 vector_map_->Get(r),
1955 vector_map_->Get(s),
Aart Bik66c158e2018-01-31 12:55:04 -08001956 HVecOperation::ToProperType(type, is_unsigned),
Aart Bikf3e61ee2017-04-12 17:09:20 -07001957 vector_length_,
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001958 is_rounded,
Aart Bik46b6dbc2017-10-03 11:37:37 -07001959 kNoDexPc));
Aart Bik21b85922017-09-06 13:29:16 -07001960 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorizedIdiom);
Aart Bikf3e61ee2017-04-12 17:09:20 -07001961 } else {
Aart Bik304c8a52017-05-23 11:01:13 -07001962 GenerateVecOp(instruction, vector_map_->Get(r), vector_map_->Get(s), type);
Aart Bikf3e61ee2017-04-12 17:09:20 -07001963 }
1964 }
1965 return true;
1966 }
1967 }
1968 }
1969 return false;
1970}
1971
Aart Bikdbbac8f2017-09-01 13:06:08 -07001972// Method recognizes the following idiom:
1973// q += ABS(a - b) for signed operands a, b
1974// Provided that the operands have the same type or are promoted to a wider form.
1975// Since this may involve a vector length change, the idiom is handled by going directly
1976// to a sad-accumulate node (rather than relying combining finer grained nodes later).
1977// TODO: unsigned SAD too?
1978bool HLoopOptimization::VectorizeSADIdiom(LoopNode* node,
1979 HInstruction* instruction,
1980 bool generate_code,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001981 DataType::Type reduction_type,
Aart Bikdbbac8f2017-09-01 13:06:08 -07001982 uint64_t restrictions) {
1983 // Filter integral "q += ABS(a - b);" reduction, where ABS and SUB
1984 // are done in the same precision (either int or long).
1985 if (!instruction->IsAdd() ||
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001986 (reduction_type != DataType::Type::kInt32 && reduction_type != DataType::Type::kInt64)) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001987 return false;
1988 }
1989 HInstruction* q = instruction->InputAt(0);
1990 HInstruction* v = instruction->InputAt(1);
1991 HInstruction* a = nullptr;
1992 HInstruction* b = nullptr;
Aart Bik3b2a5952018-03-05 13:55:28 -08001993 if (v->GetType() == reduction_type && v->IsAbs()) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001994 HInstruction* x = v->InputAt(0);
Aart Bikdf011c32017-09-28 12:53:04 -07001995 if (x->GetType() == reduction_type) {
1996 int64_t c = 0;
1997 if (x->IsSub()) {
1998 a = x->InputAt(0);
1999 b = x->InputAt(1);
2000 } else if (IsAddConst(x, /*out*/ &a, /*out*/ &c)) {
2001 b = graph_->GetConstant(reduction_type, -c); // hidden SUB!
2002 }
Aart Bikdbbac8f2017-09-01 13:06:08 -07002003 }
2004 }
2005 if (a == nullptr || b == nullptr) {
2006 return false;
2007 }
2008 // Accept same-type or consistent sign extension for narrower-type on operands a and b.
2009 // The same-type or narrower operands are called r (a or lower) and s (b or lower).
Aart Bikdf011c32017-09-28 12:53:04 -07002010 // We inspect the operands carefully to pick the most suited type.
Aart Bikdbbac8f2017-09-01 13:06:08 -07002011 HInstruction* r = a;
2012 HInstruction* s = b;
2013 bool is_unsigned = false;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002014 DataType::Type sub_type = a->GetType();
Aart Bikdf011c32017-09-28 12:53:04 -07002015 if (DataType::Size(b->GetType()) < DataType::Size(sub_type)) {
2016 sub_type = b->GetType();
2017 }
2018 if (a->IsTypeConversion() &&
2019 DataType::Size(a->InputAt(0)->GetType()) < DataType::Size(sub_type)) {
2020 sub_type = a->InputAt(0)->GetType();
2021 }
2022 if (b->IsTypeConversion() &&
2023 DataType::Size(b->InputAt(0)->GetType()) < DataType::Size(sub_type)) {
2024 sub_type = b->InputAt(0)->GetType();
Aart Bikdbbac8f2017-09-01 13:06:08 -07002025 }
2026 if (reduction_type != sub_type &&
2027 (!IsNarrowerOperands(a, b, sub_type, &r, &s, &is_unsigned) || is_unsigned)) {
2028 return false;
2029 }
2030 // Try same/narrower type and deal with vector restrictions.
Artem Serov6e9b1372017-10-05 16:48:30 +01002031 if (!TrySetVectorType(sub_type, &restrictions) ||
2032 HasVectorRestrictions(restrictions, kNoSAD) ||
2033 (reduction_type != sub_type && HasVectorRestrictions(restrictions, kNoWideSAD))) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07002034 return false;
2035 }
2036 // Accept SAD idiom for vectorizable operands. Vectorized code uses the shorthand
2037 // idiomatic operation. Sequential code uses the original scalar expressions.
2038 DCHECK(r != nullptr);
2039 DCHECK(s != nullptr);
2040 if (generate_code && vector_mode_ != kVector) { // de-idiom
2041 r = s = v->InputAt(0);
2042 }
2043 if (VectorizeUse(node, q, generate_code, sub_type, restrictions) &&
2044 VectorizeUse(node, r, generate_code, sub_type, restrictions) &&
2045 VectorizeUse(node, s, generate_code, sub_type, restrictions)) {
2046 if (generate_code) {
2047 if (vector_mode_ == kVector) {
2048 vector_map_->Put(instruction, new (global_allocator_) HVecSADAccumulate(
2049 global_allocator_,
2050 vector_map_->Get(q),
2051 vector_map_->Get(r),
2052 vector_map_->Get(s),
Aart Bik3b2a5952018-03-05 13:55:28 -08002053 HVecOperation::ToProperType(reduction_type, is_unsigned),
Aart Bik46b6dbc2017-10-03 11:37:37 -07002054 GetOtherVL(reduction_type, sub_type, vector_length_),
2055 kNoDexPc));
Aart Bikdbbac8f2017-09-01 13:06:08 -07002056 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorizedIdiom);
2057 } else {
2058 GenerateVecOp(v, vector_map_->Get(r), nullptr, reduction_type);
2059 GenerateVecOp(instruction, vector_map_->Get(q), vector_map_->Get(v), reduction_type);
2060 }
2061 }
2062 return true;
2063 }
2064 return false;
2065}
2066
Aart Bikf3e61ee2017-04-12 17:09:20 -07002067//
Aart Bik14a68b42017-06-08 14:06:58 -07002068// Vectorization heuristics.
2069//
2070
Aart Bik38a3f212017-10-20 17:02:21 -07002071Alignment HLoopOptimization::ComputeAlignment(HInstruction* offset,
2072 DataType::Type type,
2073 bool is_string_char_at,
2074 uint32_t peeling) {
2075 // Combine the alignment and hidden offset that is guaranteed by
2076 // the Android runtime with a known starting index adjusted as bytes.
2077 int64_t value = 0;
2078 if (IsInt64AndGet(offset, /*out*/ &value)) {
2079 uint32_t start_offset =
2080 HiddenOffset(type, is_string_char_at) + (value + peeling) * DataType::Size(type);
2081 return Alignment(BaseAlignment(), start_offset & (BaseAlignment() - 1u));
2082 }
2083 // Otherwise, the Android runtime guarantees at least natural alignment.
2084 return Alignment(DataType::Size(type), 0);
2085}
2086
2087void HLoopOptimization::SetAlignmentStrategy(uint32_t peeling_votes[],
2088 const ArrayReference* peeling_candidate) {
2089 // Current heuristic: pick the best static loop peeling factor, if any,
2090 // or otherwise use dynamic loop peeling on suggested peeling candidate.
2091 uint32_t max_vote = 0;
2092 for (int32_t i = 0; i < 16; i++) {
2093 if (peeling_votes[i] > max_vote) {
2094 max_vote = peeling_votes[i];
2095 vector_static_peeling_factor_ = i;
2096 }
2097 }
2098 if (max_vote == 0) {
2099 vector_dynamic_peeling_candidate_ = peeling_candidate;
2100 }
2101}
2102
2103uint32_t HLoopOptimization::MaxNumberPeeled() {
2104 if (vector_dynamic_peeling_candidate_ != nullptr) {
2105 return vector_length_ - 1u; // worst-case
2106 }
2107 return vector_static_peeling_factor_; // known exactly
2108}
2109
Aart Bik14a68b42017-06-08 14:06:58 -07002110bool HLoopOptimization::IsVectorizationProfitable(int64_t trip_count) {
Aart Bik38a3f212017-10-20 17:02:21 -07002111 // Current heuristic: non-empty body with sufficient number of iterations (if known).
Aart Bik14a68b42017-06-08 14:06:58 -07002112 // TODO: refine by looking at e.g. operation count, alignment, etc.
Aart Bik38a3f212017-10-20 17:02:21 -07002113 // TODO: trip count is really unsigned entity, provided the guarding test
2114 // is satisfied; deal with this more carefully later
2115 uint32_t max_peel = MaxNumberPeeled();
Aart Bik14a68b42017-06-08 14:06:58 -07002116 if (vector_length_ == 0) {
2117 return false; // nothing found
Aart Bik38a3f212017-10-20 17:02:21 -07002118 } else if (trip_count < 0) {
2119 return false; // guard against non-taken/large
2120 } else if ((0 < trip_count) && (trip_count < (vector_length_ + max_peel))) {
Aart Bik14a68b42017-06-08 14:06:58 -07002121 return false; // insufficient iterations
2122 }
2123 return true;
2124}
2125
Artem Serovf26bb6c2017-09-01 10:59:03 +01002126static constexpr uint32_t ARM64_SIMD_MAXIMUM_UNROLL_FACTOR = 8;
2127static constexpr uint32_t ARM64_SIMD_HEURISTIC_MAX_BODY_SIZE = 50;
2128
Aart Bik14a68b42017-06-08 14:06:58 -07002129uint32_t HLoopOptimization::GetUnrollingFactor(HBasicBlock* block, int64_t trip_count) {
Aart Bik38a3f212017-10-20 17:02:21 -07002130 uint32_t max_peel = MaxNumberPeeled();
Aart Bik14a68b42017-06-08 14:06:58 -07002131 switch (compiler_driver_->GetInstructionSet()) {
Vladimir Marko33bff252017-11-01 14:35:42 +00002132 case InstructionSet::kArm64: {
Aart Bik521b50f2017-09-09 10:44:45 -07002133 // Don't unroll with insufficient iterations.
Artem Serovf26bb6c2017-09-01 10:59:03 +01002134 // TODO: Unroll loops with unknown trip count.
Aart Bik521b50f2017-09-09 10:44:45 -07002135 DCHECK_NE(vector_length_, 0u);
Aart Bik38a3f212017-10-20 17:02:21 -07002136 if (trip_count < (2 * vector_length_ + max_peel)) {
Aart Bik521b50f2017-09-09 10:44:45 -07002137 return kNoUnrollingFactor;
Aart Bik14a68b42017-06-08 14:06:58 -07002138 }
Aart Bik521b50f2017-09-09 10:44:45 -07002139 // Don't unroll for large loop body size.
Artem Serovf26bb6c2017-09-01 10:59:03 +01002140 uint32_t instruction_count = block->GetInstructions().CountSize();
Aart Bik521b50f2017-09-09 10:44:45 -07002141 if (instruction_count >= ARM64_SIMD_HEURISTIC_MAX_BODY_SIZE) {
2142 return kNoUnrollingFactor;
2143 }
Artem Serovf26bb6c2017-09-01 10:59:03 +01002144 // Find a beneficial unroll factor with the following restrictions:
2145 // - At least one iteration of the transformed loop should be executed.
2146 // - The loop body shouldn't be "too big" (heuristic).
2147 uint32_t uf1 = ARM64_SIMD_HEURISTIC_MAX_BODY_SIZE / instruction_count;
Aart Bik38a3f212017-10-20 17:02:21 -07002148 uint32_t uf2 = (trip_count - max_peel) / vector_length_;
Artem Serovf26bb6c2017-09-01 10:59:03 +01002149 uint32_t unroll_factor =
2150 TruncToPowerOfTwo(std::min({uf1, uf2, ARM64_SIMD_MAXIMUM_UNROLL_FACTOR}));
2151 DCHECK_GE(unroll_factor, 1u);
Artem Serovf26bb6c2017-09-01 10:59:03 +01002152 return unroll_factor;
Aart Bik14a68b42017-06-08 14:06:58 -07002153 }
Vladimir Marko33bff252017-11-01 14:35:42 +00002154 case InstructionSet::kX86:
2155 case InstructionSet::kX86_64:
Aart Bik14a68b42017-06-08 14:06:58 -07002156 default:
Aart Bik521b50f2017-09-09 10:44:45 -07002157 return kNoUnrollingFactor;
Aart Bik14a68b42017-06-08 14:06:58 -07002158 }
2159}
2160
2161//
Aart Bikf8f5a162017-02-06 15:35:29 -08002162// Helpers.
2163//
2164
2165bool HLoopOptimization::TrySetPhiInduction(HPhi* phi, bool restrict_uses) {
Aart Bikb29f6842017-07-28 15:58:41 -07002166 // Start with empty phi induction.
2167 iset_->clear();
2168
Nicolas Geoffrayf57c1ae2017-06-28 17:40:18 +01002169 // Special case Phis that have equivalent in a debuggable setup. Our graph checker isn't
2170 // smart enough to follow strongly connected components (and it's probably not worth
2171 // it to make it so). See b/33775412.
2172 if (graph_->IsDebuggable() && phi->HasEquivalentPhi()) {
2173 return false;
2174 }
Aart Bikb29f6842017-07-28 15:58:41 -07002175
2176 // Lookup phi induction cycle.
Aart Bikcc42be02016-10-20 16:14:16 -07002177 ArenaSet<HInstruction*>* set = induction_range_.LookupCycle(phi);
2178 if (set != nullptr) {
2179 for (HInstruction* i : *set) {
Aart Bike3dedc52016-11-02 17:50:27 -07002180 // Check that, other than instructions that are no longer in the graph (removed earlier)
Aart Bikf8f5a162017-02-06 15:35:29 -08002181 // each instruction is removable and, when restrict uses are requested, other than for phi,
2182 // all uses are contained within the cycle.
Aart Bike3dedc52016-11-02 17:50:27 -07002183 if (!i->IsInBlock()) {
2184 continue;
2185 } else if (!i->IsRemovable()) {
2186 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08002187 } else if (i != phi && restrict_uses) {
Aart Bikb29f6842017-07-28 15:58:41 -07002188 // Deal with regular uses.
Aart Bikcc42be02016-10-20 16:14:16 -07002189 for (const HUseListNode<HInstruction*>& use : i->GetUses()) {
2190 if (set->find(use.GetUser()) == set->end()) {
2191 return false;
2192 }
2193 }
2194 }
Aart Bike3dedc52016-11-02 17:50:27 -07002195 iset_->insert(i); // copy
Aart Bikcc42be02016-10-20 16:14:16 -07002196 }
Aart Bikcc42be02016-10-20 16:14:16 -07002197 return true;
2198 }
2199 return false;
2200}
2201
Aart Bikb29f6842017-07-28 15:58:41 -07002202bool HLoopOptimization::TrySetPhiReduction(HPhi* phi) {
Aart Bikcc42be02016-10-20 16:14:16 -07002203 DCHECK(iset_->empty());
Aart Bikb29f6842017-07-28 15:58:41 -07002204 // Only unclassified phi cycles are candidates for reductions.
2205 if (induction_range_.IsClassified(phi)) {
2206 return false;
2207 }
2208 // Accept operations like x = x + .., provided that the phi and the reduction are
2209 // used exactly once inside the loop, and by each other.
2210 HInputsRef inputs = phi->GetInputs();
2211 if (inputs.size() == 2) {
2212 HInstruction* reduction = inputs[1];
2213 if (HasReductionFormat(reduction, phi)) {
2214 HLoopInformation* loop_info = phi->GetBlock()->GetLoopInformation();
Aart Bik38a3f212017-10-20 17:02:21 -07002215 uint32_t use_count = 0;
Aart Bikb29f6842017-07-28 15:58:41 -07002216 bool single_use_inside_loop =
2217 // Reduction update only used by phi.
2218 reduction->GetUses().HasExactlyOneElement() &&
2219 !reduction->HasEnvironmentUses() &&
2220 // Reduction update is only use of phi inside the loop.
2221 IsOnlyUsedAfterLoop(loop_info, phi, /*collect_loop_uses*/ true, &use_count) &&
2222 iset_->size() == 1;
2223 iset_->clear(); // leave the way you found it
2224 if (single_use_inside_loop) {
2225 // Link reduction back, and start recording feed value.
2226 reductions_->Put(reduction, phi);
2227 reductions_->Put(phi, phi->InputAt(0));
2228 return true;
2229 }
2230 }
2231 }
2232 return false;
2233}
2234
2235bool HLoopOptimization::TrySetSimpleLoopHeader(HBasicBlock* block, /*out*/ HPhi** main_phi) {
2236 // Start with empty phi induction and reductions.
2237 iset_->clear();
2238 reductions_->clear();
2239
2240 // Scan the phis to find the following (the induction structure has already
2241 // been optimized, so we don't need to worry about trivial cases):
2242 // (1) optional reductions in loop,
2243 // (2) the main induction, used in loop control.
2244 HPhi* phi = nullptr;
2245 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
2246 if (TrySetPhiReduction(it.Current()->AsPhi())) {
2247 continue;
2248 } else if (phi == nullptr) {
2249 // Found the first candidate for main induction.
2250 phi = it.Current()->AsPhi();
2251 } else {
2252 return false;
2253 }
2254 }
2255
2256 // Then test for a typical loopheader:
2257 // s: SuspendCheck
2258 // c: Condition(phi, bound)
2259 // i: If(c)
2260 if (phi != nullptr && TrySetPhiInduction(phi, /*restrict_uses*/ false)) {
Aart Bikcc42be02016-10-20 16:14:16 -07002261 HInstruction* s = block->GetFirstInstruction();
2262 if (s != nullptr && s->IsSuspendCheck()) {
2263 HInstruction* c = s->GetNext();
Aart Bikd86c0852017-04-14 12:00:15 -07002264 if (c != nullptr &&
2265 c->IsCondition() &&
2266 c->GetUses().HasExactlyOneElement() && // only used for termination
2267 !c->HasEnvironmentUses()) { // unlikely, but not impossible
Aart Bikcc42be02016-10-20 16:14:16 -07002268 HInstruction* i = c->GetNext();
2269 if (i != nullptr && i->IsIf() && i->InputAt(0) == c) {
2270 iset_->insert(c);
2271 iset_->insert(s);
Aart Bikb29f6842017-07-28 15:58:41 -07002272 *main_phi = phi;
Aart Bikcc42be02016-10-20 16:14:16 -07002273 return true;
2274 }
2275 }
2276 }
2277 }
2278 return false;
2279}
2280
2281bool HLoopOptimization::IsEmptyBody(HBasicBlock* block) {
Aart Bikf8f5a162017-02-06 15:35:29 -08002282 if (!block->GetPhis().IsEmpty()) {
2283 return false;
2284 }
2285 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
2286 HInstruction* instruction = it.Current();
2287 if (!instruction->IsGoto() && iset_->find(instruction) == iset_->end()) {
2288 return false;
Aart Bikcc42be02016-10-20 16:14:16 -07002289 }
Aart Bikf8f5a162017-02-06 15:35:29 -08002290 }
2291 return true;
2292}
2293
2294bool HLoopOptimization::IsUsedOutsideLoop(HLoopInformation* loop_info,
2295 HInstruction* instruction) {
Aart Bikb29f6842017-07-28 15:58:41 -07002296 // Deal with regular uses.
Aart Bikf8f5a162017-02-06 15:35:29 -08002297 for (const HUseListNode<HInstruction*>& use : instruction->GetUses()) {
2298 if (use.GetUser()->GetBlock()->GetLoopInformation() != loop_info) {
2299 return true;
2300 }
Aart Bikcc42be02016-10-20 16:14:16 -07002301 }
2302 return false;
2303}
2304
Aart Bik482095d2016-10-10 15:39:10 -07002305bool HLoopOptimization::IsOnlyUsedAfterLoop(HLoopInformation* loop_info,
Aart Bik8c4a8542016-10-06 11:36:57 -07002306 HInstruction* instruction,
Aart Bik6b69e0a2017-01-11 10:20:43 -08002307 bool collect_loop_uses,
Aart Bik38a3f212017-10-20 17:02:21 -07002308 /*out*/ uint32_t* use_count) {
Aart Bikb29f6842017-07-28 15:58:41 -07002309 // Deal with regular uses.
Aart Bik8c4a8542016-10-06 11:36:57 -07002310 for (const HUseListNode<HInstruction*>& use : instruction->GetUses()) {
2311 HInstruction* user = use.GetUser();
2312 if (iset_->find(user) == iset_->end()) { // not excluded?
2313 HLoopInformation* other_loop_info = user->GetBlock()->GetLoopInformation();
Aart Bik482095d2016-10-10 15:39:10 -07002314 if (other_loop_info != nullptr && other_loop_info->IsIn(*loop_info)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -08002315 // If collect_loop_uses is set, simply keep adding those uses to the set.
2316 // Otherwise, reject uses inside the loop that were not already in the set.
2317 if (collect_loop_uses) {
2318 iset_->insert(user);
2319 continue;
2320 }
Aart Bik8c4a8542016-10-06 11:36:57 -07002321 return false;
2322 }
2323 ++*use_count;
2324 }
2325 }
2326 return true;
2327}
2328
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002329bool HLoopOptimization::TryReplaceWithLastValue(HLoopInformation* loop_info,
2330 HInstruction* instruction,
2331 HBasicBlock* block) {
2332 // Try to replace outside uses with the last value.
Aart Bik807868e2016-11-03 17:51:43 -07002333 if (induction_range_.CanGenerateLastValue(instruction)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -08002334 HInstruction* replacement = induction_range_.GenerateLastValue(instruction, graph_, block);
Aart Bikb29f6842017-07-28 15:58:41 -07002335 // Deal with regular uses.
Aart Bik6b69e0a2017-01-11 10:20:43 -08002336 const HUseList<HInstruction*>& uses = instruction->GetUses();
2337 for (auto it = uses.begin(), end = uses.end(); it != end;) {
2338 HInstruction* user = it->GetUser();
2339 size_t index = it->GetIndex();
2340 ++it; // increment before replacing
2341 if (iset_->find(user) == iset_->end()) { // not excluded?
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002342 if (kIsDebugBuild) {
2343 // We have checked earlier in 'IsOnlyUsedAfterLoop' that the use is after the loop.
2344 HLoopInformation* other_loop_info = user->GetBlock()->GetLoopInformation();
2345 CHECK(other_loop_info == nullptr || !other_loop_info->IsIn(*loop_info));
2346 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08002347 user->ReplaceInput(replacement, index);
2348 induction_range_.Replace(user, instruction, replacement); // update induction
2349 }
2350 }
Aart Bikb29f6842017-07-28 15:58:41 -07002351 // Deal with environment uses.
Aart Bik6b69e0a2017-01-11 10:20:43 -08002352 const HUseList<HEnvironment*>& env_uses = instruction->GetEnvUses();
2353 for (auto it = env_uses.begin(), end = env_uses.end(); it != end;) {
2354 HEnvironment* user = it->GetUser();
2355 size_t index = it->GetIndex();
2356 ++it; // increment before replacing
2357 if (iset_->find(user->GetHolder()) == iset_->end()) { // not excluded?
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002358 // Only update environment uses after the loop.
Aart Bik14a68b42017-06-08 14:06:58 -07002359 HLoopInformation* other_loop_info = user->GetHolder()->GetBlock()->GetLoopInformation();
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002360 if (other_loop_info == nullptr || !other_loop_info->IsIn(*loop_info)) {
2361 user->RemoveAsUserOfInput(index);
2362 user->SetRawEnvAt(index, replacement);
2363 replacement->AddEnvUseAt(user, index);
2364 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08002365 }
2366 }
Aart Bik807868e2016-11-03 17:51:43 -07002367 return true;
Aart Bik8c4a8542016-10-06 11:36:57 -07002368 }
Aart Bik807868e2016-11-03 17:51:43 -07002369 return false;
Aart Bik8c4a8542016-10-06 11:36:57 -07002370}
2371
Aart Bikf8f5a162017-02-06 15:35:29 -08002372bool HLoopOptimization::TryAssignLastValue(HLoopInformation* loop_info,
2373 HInstruction* instruction,
2374 HBasicBlock* block,
2375 bool collect_loop_uses) {
2376 // Assigning the last value is always successful if there are no uses.
2377 // Otherwise, it succeeds in a no early-exit loop by generating the
2378 // proper last value assignment.
Aart Bik38a3f212017-10-20 17:02:21 -07002379 uint32_t use_count = 0;
Aart Bikf8f5a162017-02-06 15:35:29 -08002380 return IsOnlyUsedAfterLoop(loop_info, instruction, collect_loop_uses, &use_count) &&
2381 (use_count == 0 ||
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002382 (!IsEarlyExit(loop_info) && TryReplaceWithLastValue(loop_info, instruction, block)));
Aart Bikf8f5a162017-02-06 15:35:29 -08002383}
2384
Aart Bik6b69e0a2017-01-11 10:20:43 -08002385void HLoopOptimization::RemoveDeadInstructions(const HInstructionList& list) {
2386 for (HBackwardInstructionIterator i(list); !i.Done(); i.Advance()) {
2387 HInstruction* instruction = i.Current();
2388 if (instruction->IsDeadAndRemovable()) {
2389 simplified_ = true;
2390 instruction->GetBlock()->RemoveInstructionOrPhi(instruction);
2391 }
2392 }
2393}
2394
Aart Bik14a68b42017-06-08 14:06:58 -07002395bool HLoopOptimization::CanRemoveCycle() {
2396 for (HInstruction* i : *iset_) {
2397 // We can never remove instructions that have environment
2398 // uses when we compile 'debuggable'.
2399 if (i->HasEnvironmentUses() && graph_->IsDebuggable()) {
2400 return false;
2401 }
2402 // A deoptimization should never have an environment input removed.
2403 for (const HUseListNode<HEnvironment*>& use : i->GetEnvUses()) {
2404 if (use.GetUser()->GetHolder()->IsDeoptimize()) {
2405 return false;
2406 }
2407 }
2408 }
2409 return true;
2410}
2411
Aart Bik281c6812016-08-26 11:31:48 -07002412} // namespace art