blob: d3b081e005129bfedf4c1c44981ab52d3c7c41e3 [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 - ..
Aart Bikb29f6842017-07-28 15:58:41 -0700337// x = min(x_phi, ..)
Aart Bik1f8d51b2018-02-15 10:42:37 -0800338// x = max(x_phi, ..)
Aart Bikb29f6842017-07-28 15:58:41 -0700339static bool HasReductionFormat(HInstruction* reduction, HInstruction* phi) {
Aart Bik1f8d51b2018-02-15 10:42:37 -0800340 if (reduction->IsAdd() || reduction->IsMin() || reduction->IsMax()) {
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 }
346 return false;
347}
348
Aart Bikdbbac8f2017-09-01 13:06:08 -0700349// Translates vector operation to reduction kind.
350static HVecReduce::ReductionKind GetReductionKind(HVecOperation* reduction) {
351 if (reduction->IsVecAdd() || reduction->IsVecSub() || reduction->IsVecSADAccumulate()) {
Aart Bik0148de42017-09-05 09:25:01 -0700352 return HVecReduce::kSum;
353 } else if (reduction->IsVecMin()) {
354 return HVecReduce::kMin;
355 } else if (reduction->IsVecMax()) {
356 return HVecReduce::kMax;
357 }
Aart Bik38a3f212017-10-20 17:02:21 -0700358 LOG(FATAL) << "Unsupported SIMD reduction " << reduction->GetId();
Aart Bik0148de42017-09-05 09:25:01 -0700359 UNREACHABLE();
360}
361
Aart Bikf8f5a162017-02-06 15:35:29 -0800362// Test vector restrictions.
363static bool HasVectorRestrictions(uint64_t restrictions, uint64_t tested) {
364 return (restrictions & tested) != 0;
365}
366
Aart Bikf3e61ee2017-04-12 17:09:20 -0700367// Insert an instruction.
Aart Bikf8f5a162017-02-06 15:35:29 -0800368static HInstruction* Insert(HBasicBlock* block, HInstruction* instruction) {
369 DCHECK(block != nullptr);
370 DCHECK(instruction != nullptr);
371 block->InsertInstructionBefore(instruction, block->GetLastInstruction());
372 return instruction;
373}
374
Artem Serov21c7e6f2017-07-27 16:04:42 +0100375// Check that instructions from the induction sets are fully removed: have no uses
376// and no other instructions use them.
Vladimir Markoca6fff82017-10-03 14:49:14 +0100377static bool CheckInductionSetFullyRemoved(ScopedArenaSet<HInstruction*>* iset) {
Artem Serov21c7e6f2017-07-27 16:04:42 +0100378 for (HInstruction* instr : *iset) {
379 if (instr->GetBlock() != nullptr ||
380 !instr->GetUses().empty() ||
381 !instr->GetEnvUses().empty() ||
382 HasEnvironmentUsedByOthers(instr)) {
383 return false;
384 }
385 }
Artem Serov21c7e6f2017-07-27 16:04:42 +0100386 return true;
387}
388
Aart Bik281c6812016-08-26 11:31:48 -0700389//
Aart Bikb29f6842017-07-28 15:58:41 -0700390// Public methods.
Aart Bik281c6812016-08-26 11:31:48 -0700391//
392
393HLoopOptimization::HLoopOptimization(HGraph* graph,
Aart Bik92685a82017-03-06 11:13:43 -0800394 CompilerDriver* compiler_driver,
Aart Bikb92cc332017-09-06 15:53:17 -0700395 HInductionVarAnalysis* induction_analysis,
Aart Bik2ca10eb2017-11-15 15:17:53 -0800396 OptimizingCompilerStats* stats,
397 const char* name)
398 : HOptimization(graph, name, stats),
Aart Bik92685a82017-03-06 11:13:43 -0800399 compiler_driver_(compiler_driver),
Aart Bik281c6812016-08-26 11:31:48 -0700400 induction_range_(induction_analysis),
Aart Bik96202302016-10-04 17:33:56 -0700401 loop_allocator_(nullptr),
Vladimir Markoca6fff82017-10-03 14:49:14 +0100402 global_allocator_(graph_->GetAllocator()),
Aart Bik281c6812016-08-26 11:31:48 -0700403 top_loop_(nullptr),
Aart Bik8c4a8542016-10-06 11:36:57 -0700404 last_loop_(nullptr),
Aart Bik482095d2016-10-10 15:39:10 -0700405 iset_(nullptr),
Aart Bikb29f6842017-07-28 15:58:41 -0700406 reductions_(nullptr),
Aart Bikf8f5a162017-02-06 15:35:29 -0800407 simplified_(false),
408 vector_length_(0),
409 vector_refs_(nullptr),
Aart Bik38a3f212017-10-20 17:02:21 -0700410 vector_static_peeling_factor_(0),
411 vector_dynamic_peeling_candidate_(nullptr),
Aart Bik14a68b42017-06-08 14:06:58 -0700412 vector_runtime_test_a_(nullptr),
413 vector_runtime_test_b_(nullptr),
Aart Bik0148de42017-09-05 09:25:01 -0700414 vector_map_(nullptr),
Vladimir Markoca6fff82017-10-03 14:49:14 +0100415 vector_permanent_map_(nullptr),
416 vector_mode_(kSequential),
417 vector_preheader_(nullptr),
418 vector_header_(nullptr),
419 vector_body_(nullptr),
420 vector_index_(nullptr) {
Aart Bik281c6812016-08-26 11:31:48 -0700421}
422
423void HLoopOptimization::Run() {
Mingyao Yang01b47b02017-02-03 12:09:57 -0800424 // Skip if there is no loop or the graph has try-catch/irreducible loops.
Aart Bik281c6812016-08-26 11:31:48 -0700425 // TODO: make this less of a sledgehammer.
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800426 if (!graph_->HasLoops() || graph_->HasTryCatch() || graph_->HasIrreducibleLoops()) {
Aart Bik281c6812016-08-26 11:31:48 -0700427 return;
428 }
429
Vladimir Markoca6fff82017-10-03 14:49:14 +0100430 // Phase-local allocator.
431 ScopedArenaAllocator allocator(graph_->GetArenaStack());
Aart Bik96202302016-10-04 17:33:56 -0700432 loop_allocator_ = &allocator;
Nicolas Geoffrayebe16742016-10-05 09:55:42 +0100433
Aart Bik96202302016-10-04 17:33:56 -0700434 // Perform loop optimizations.
435 LocalRun();
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800436 if (top_loop_ == nullptr) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800437 graph_->SetHasLoops(false); // no more loops
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800438 }
439
Aart Bik96202302016-10-04 17:33:56 -0700440 // Detach.
441 loop_allocator_ = nullptr;
442 last_loop_ = top_loop_ = nullptr;
443}
444
Aart Bikb29f6842017-07-28 15:58:41 -0700445//
446// Loop setup and traversal.
447//
448
Aart Bik96202302016-10-04 17:33:56 -0700449void HLoopOptimization::LocalRun() {
450 // Build the linear order using the phase-local allocator. This step enables building
451 // a loop hierarchy that properly reflects the outer-inner and previous-next relation.
Vladimir Markoca6fff82017-10-03 14:49:14 +0100452 ScopedArenaVector<HBasicBlock*> linear_order(loop_allocator_->Adapter(kArenaAllocLinearOrder));
453 LinearizeGraph(graph_, &linear_order);
Aart Bik96202302016-10-04 17:33:56 -0700454
Aart Bik281c6812016-08-26 11:31:48 -0700455 // Build the loop hierarchy.
Aart Bik96202302016-10-04 17:33:56 -0700456 for (HBasicBlock* block : linear_order) {
Aart Bik281c6812016-08-26 11:31:48 -0700457 if (block->IsLoopHeader()) {
458 AddLoop(block->GetLoopInformation());
459 }
460 }
Aart Bik96202302016-10-04 17:33:56 -0700461
Aart Bik8c4a8542016-10-06 11:36:57 -0700462 // Traverse the loop hierarchy inner-to-outer and optimize. Traversal can use
Aart Bikf8f5a162017-02-06 15:35:29 -0800463 // temporary data structures using the phase-local allocator. All new HIR
464 // should use the global allocator.
Aart Bik8c4a8542016-10-06 11:36:57 -0700465 if (top_loop_ != nullptr) {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100466 ScopedArenaSet<HInstruction*> iset(loop_allocator_->Adapter(kArenaAllocLoopOptimization));
467 ScopedArenaSafeMap<HInstruction*, HInstruction*> reds(
Aart Bikb29f6842017-07-28 15:58:41 -0700468 std::less<HInstruction*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
Vladimir Markoca6fff82017-10-03 14:49:14 +0100469 ScopedArenaSet<ArrayReference> refs(loop_allocator_->Adapter(kArenaAllocLoopOptimization));
470 ScopedArenaSafeMap<HInstruction*, HInstruction*> map(
Aart Bikf8f5a162017-02-06 15:35:29 -0800471 std::less<HInstruction*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
Vladimir Markoca6fff82017-10-03 14:49:14 +0100472 ScopedArenaSafeMap<HInstruction*, HInstruction*> perm(
Aart Bik0148de42017-09-05 09:25:01 -0700473 std::less<HInstruction*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
Aart Bikf8f5a162017-02-06 15:35:29 -0800474 // Attach.
Aart Bik8c4a8542016-10-06 11:36:57 -0700475 iset_ = &iset;
Aart Bikb29f6842017-07-28 15:58:41 -0700476 reductions_ = &reds;
Aart Bikf8f5a162017-02-06 15:35:29 -0800477 vector_refs_ = &refs;
478 vector_map_ = &map;
Aart Bik0148de42017-09-05 09:25:01 -0700479 vector_permanent_map_ = &perm;
Aart Bikf8f5a162017-02-06 15:35:29 -0800480 // Traverse.
Aart Bik8c4a8542016-10-06 11:36:57 -0700481 TraverseLoopsInnerToOuter(top_loop_);
Aart Bikf8f5a162017-02-06 15:35:29 -0800482 // Detach.
483 iset_ = nullptr;
Aart Bikb29f6842017-07-28 15:58:41 -0700484 reductions_ = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800485 vector_refs_ = nullptr;
486 vector_map_ = nullptr;
Aart Bik0148de42017-09-05 09:25:01 -0700487 vector_permanent_map_ = nullptr;
Aart Bik8c4a8542016-10-06 11:36:57 -0700488 }
Aart Bik281c6812016-08-26 11:31:48 -0700489}
490
491void HLoopOptimization::AddLoop(HLoopInformation* loop_info) {
492 DCHECK(loop_info != nullptr);
Aart Bikf8f5a162017-02-06 15:35:29 -0800493 LoopNode* node = new (loop_allocator_) LoopNode(loop_info);
Aart Bik281c6812016-08-26 11:31:48 -0700494 if (last_loop_ == nullptr) {
495 // First loop.
496 DCHECK(top_loop_ == nullptr);
497 last_loop_ = top_loop_ = node;
498 } else if (loop_info->IsIn(*last_loop_->loop_info)) {
499 // Inner loop.
500 node->outer = last_loop_;
501 DCHECK(last_loop_->inner == nullptr);
502 last_loop_ = last_loop_->inner = node;
503 } else {
504 // Subsequent loop.
505 while (last_loop_->outer != nullptr && !loop_info->IsIn(*last_loop_->outer->loop_info)) {
506 last_loop_ = last_loop_->outer;
507 }
508 node->outer = last_loop_->outer;
509 node->previous = last_loop_;
510 DCHECK(last_loop_->next == nullptr);
511 last_loop_ = last_loop_->next = node;
512 }
513}
514
515void HLoopOptimization::RemoveLoop(LoopNode* node) {
516 DCHECK(node != nullptr);
Aart Bik8c4a8542016-10-06 11:36:57 -0700517 DCHECK(node->inner == nullptr);
518 if (node->previous != nullptr) {
519 // Within sequence.
520 node->previous->next = node->next;
521 if (node->next != nullptr) {
522 node->next->previous = node->previous;
523 }
524 } else {
525 // First of sequence.
526 if (node->outer != nullptr) {
527 node->outer->inner = node->next;
528 } else {
529 top_loop_ = node->next;
530 }
531 if (node->next != nullptr) {
532 node->next->outer = node->outer;
533 node->next->previous = nullptr;
534 }
535 }
Aart Bik281c6812016-08-26 11:31:48 -0700536}
537
Aart Bikb29f6842017-07-28 15:58:41 -0700538bool HLoopOptimization::TraverseLoopsInnerToOuter(LoopNode* node) {
539 bool changed = false;
Aart Bik281c6812016-08-26 11:31:48 -0700540 for ( ; node != nullptr; node = node->next) {
Aart Bikb29f6842017-07-28 15:58:41 -0700541 // Visit inner loops first. Recompute induction information for this
542 // loop if the induction of any inner loop has changed.
543 if (TraverseLoopsInnerToOuter(node->inner)) {
Aart Bik482095d2016-10-10 15:39:10 -0700544 induction_range_.ReVisit(node->loop_info);
545 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800546 // Repeat simplifications in the loop-body until no more changes occur.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800547 // Note that since each simplification consists of eliminating code (without
548 // introducing new code), this process is always finite.
Aart Bikdf7822e2016-12-06 10:05:30 -0800549 do {
550 simplified_ = false;
Aart Bikdf7822e2016-12-06 10:05:30 -0800551 SimplifyInduction(node);
Aart Bik6b69e0a2017-01-11 10:20:43 -0800552 SimplifyBlocks(node);
Aart Bikb29f6842017-07-28 15:58:41 -0700553 changed = simplified_ || changed;
Aart Bikdf7822e2016-12-06 10:05:30 -0800554 } while (simplified_);
Aart Bikf8f5a162017-02-06 15:35:29 -0800555 // Optimize inner loop.
Aart Bik9abf8942016-10-14 09:49:42 -0700556 if (node->inner == nullptr) {
Aart Bikb29f6842017-07-28 15:58:41 -0700557 changed = OptimizeInnerLoop(node) || changed;
Aart Bik9abf8942016-10-14 09:49:42 -0700558 }
Aart Bik281c6812016-08-26 11:31:48 -0700559 }
Aart Bikb29f6842017-07-28 15:58:41 -0700560 return changed;
Aart Bik281c6812016-08-26 11:31:48 -0700561}
562
Aart Bikf8f5a162017-02-06 15:35:29 -0800563//
564// Optimization.
565//
566
Aart Bik281c6812016-08-26 11:31:48 -0700567void HLoopOptimization::SimplifyInduction(LoopNode* node) {
568 HBasicBlock* header = node->loop_info->GetHeader();
569 HBasicBlock* preheader = node->loop_info->GetPreHeader();
Aart Bik8c4a8542016-10-06 11:36:57 -0700570 // Scan the phis in the header to find opportunities to simplify an induction
571 // cycle that is only used outside the loop. Replace these uses, if any, with
572 // the last value and remove the induction cycle.
573 // Examples: for (int i = 0; x != null; i++) { .... no i .... }
574 // for (int i = 0; i < 10; i++, k++) { .... no k .... } return k;
Aart Bik281c6812016-08-26 11:31:48 -0700575 for (HInstructionIterator it(header->GetPhis()); !it.Done(); it.Advance()) {
576 HPhi* phi = it.Current()->AsPhi();
Aart Bikf8f5a162017-02-06 15:35:29 -0800577 if (TrySetPhiInduction(phi, /*restrict_uses*/ true) &&
578 TryAssignLastValue(node->loop_info, phi, preheader, /*collect_loop_uses*/ false)) {
Aart Bik671e48a2017-08-09 13:16:56 -0700579 // Note that it's ok to have replaced uses after the loop with the last value, without
580 // being able to remove the cycle. Environment uses (which are the reason we may not be
581 // able to remove the cycle) within the loop will still hold the right value. We must
582 // have tried first, however, to replace outside uses.
583 if (CanRemoveCycle()) {
584 simplified_ = true;
585 for (HInstruction* i : *iset_) {
586 RemoveFromCycle(i);
587 }
588 DCHECK(CheckInductionSetFullyRemoved(iset_));
Aart Bik281c6812016-08-26 11:31:48 -0700589 }
Aart Bik482095d2016-10-10 15:39:10 -0700590 }
591 }
592}
593
594void HLoopOptimization::SimplifyBlocks(LoopNode* node) {
Aart Bikdf7822e2016-12-06 10:05:30 -0800595 // Iterate over all basic blocks in the loop-body.
596 for (HBlocksInLoopIterator it(*node->loop_info); !it.Done(); it.Advance()) {
597 HBasicBlock* block = it.Current();
598 // Remove dead instructions from the loop-body.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800599 RemoveDeadInstructions(block->GetPhis());
600 RemoveDeadInstructions(block->GetInstructions());
Aart Bikdf7822e2016-12-06 10:05:30 -0800601 // Remove trivial control flow blocks from the loop-body.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800602 if (block->GetPredecessors().size() == 1 &&
603 block->GetSuccessors().size() == 1 &&
604 block->GetSingleSuccessor()->GetPredecessors().size() == 1) {
Aart Bikdf7822e2016-12-06 10:05:30 -0800605 simplified_ = true;
Aart Bik6b69e0a2017-01-11 10:20:43 -0800606 block->MergeWith(block->GetSingleSuccessor());
Aart Bikdf7822e2016-12-06 10:05:30 -0800607 } else if (block->GetSuccessors().size() == 2) {
608 // Trivial if block can be bypassed to either branch.
609 HBasicBlock* succ0 = block->GetSuccessors()[0];
610 HBasicBlock* succ1 = block->GetSuccessors()[1];
611 HBasicBlock* meet0 = nullptr;
612 HBasicBlock* meet1 = nullptr;
613 if (succ0 != succ1 &&
614 IsGotoBlock(succ0, &meet0) &&
615 IsGotoBlock(succ1, &meet1) &&
616 meet0 == meet1 && // meets again
617 meet0 != block && // no self-loop
618 meet0->GetPhis().IsEmpty()) { // not used for merging
619 simplified_ = true;
620 succ0->DisconnectAndDelete();
621 if (block->Dominates(meet0)) {
622 block->RemoveDominatedBlock(meet0);
623 succ1->AddDominatedBlock(meet0);
624 meet0->SetDominator(succ1);
Aart Bike3dedc52016-11-02 17:50:27 -0700625 }
Aart Bik482095d2016-10-10 15:39:10 -0700626 }
Aart Bik281c6812016-08-26 11:31:48 -0700627 }
Aart Bikdf7822e2016-12-06 10:05:30 -0800628 }
Aart Bik281c6812016-08-26 11:31:48 -0700629}
630
Aart Bikb29f6842017-07-28 15:58:41 -0700631bool HLoopOptimization::OptimizeInnerLoop(LoopNode* node) {
Aart Bik281c6812016-08-26 11:31:48 -0700632 HBasicBlock* header = node->loop_info->GetHeader();
633 HBasicBlock* preheader = node->loop_info->GetPreHeader();
Aart Bik9abf8942016-10-14 09:49:42 -0700634 // Ensure loop header logic is finite.
Aart Bikf8f5a162017-02-06 15:35:29 -0800635 int64_t trip_count = 0;
636 if (!induction_range_.IsFinite(node->loop_info, &trip_count)) {
Aart Bikb29f6842017-07-28 15:58:41 -0700637 return false;
Aart Bik9abf8942016-10-14 09:49:42 -0700638 }
Aart Bik281c6812016-08-26 11:31:48 -0700639 // Ensure there is only a single loop-body (besides the header).
640 HBasicBlock* body = nullptr;
641 for (HBlocksInLoopIterator it(*node->loop_info); !it.Done(); it.Advance()) {
642 if (it.Current() != header) {
643 if (body != nullptr) {
Aart Bikb29f6842017-07-28 15:58:41 -0700644 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700645 }
646 body = it.Current();
647 }
648 }
Andreas Gampef45d61c2017-06-07 10:29:33 -0700649 CHECK(body != nullptr);
Aart Bik281c6812016-08-26 11:31:48 -0700650 // Ensure there is only a single exit point.
651 if (header->GetSuccessors().size() != 2) {
Aart Bikb29f6842017-07-28 15:58:41 -0700652 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700653 }
654 HBasicBlock* exit = (header->GetSuccessors()[0] == body)
655 ? header->GetSuccessors()[1]
656 : header->GetSuccessors()[0];
Aart Bik8c4a8542016-10-06 11:36:57 -0700657 // Ensure exit can only be reached by exiting loop.
Aart Bik281c6812016-08-26 11:31:48 -0700658 if (exit->GetPredecessors().size() != 1) {
Aart Bikb29f6842017-07-28 15:58:41 -0700659 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700660 }
Aart Bik6b69e0a2017-01-11 10:20:43 -0800661 // Detect either an empty loop (no side effects other than plain iteration) or
662 // a trivial loop (just iterating once). Replace subsequent index uses, if any,
663 // with the last value and remove the loop, possibly after unrolling its body.
Aart Bikb29f6842017-07-28 15:58:41 -0700664 HPhi* main_phi = nullptr;
665 if (TrySetSimpleLoopHeader(header, &main_phi)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -0800666 bool is_empty = IsEmptyBody(body);
Aart Bikb29f6842017-07-28 15:58:41 -0700667 if (reductions_->empty() && // TODO: possible with some effort
668 (is_empty || trip_count == 1) &&
669 TryAssignLastValue(node->loop_info, main_phi, preheader, /*collect_loop_uses*/ true)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -0800670 if (!is_empty) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800671 // Unroll the loop-body, which sees initial value of the index.
Aart Bikb29f6842017-07-28 15:58:41 -0700672 main_phi->ReplaceWith(main_phi->InputAt(0));
Aart Bik6b69e0a2017-01-11 10:20:43 -0800673 preheader->MergeInstructionsWith(body);
674 }
675 body->DisconnectAndDelete();
676 exit->RemovePredecessor(header);
677 header->RemoveSuccessor(exit);
678 header->RemoveDominatedBlock(exit);
679 header->DisconnectAndDelete();
680 preheader->AddSuccessor(exit);
Aart Bikf8f5a162017-02-06 15:35:29 -0800681 preheader->AddInstruction(new (global_allocator_) HGoto());
Aart Bik6b69e0a2017-01-11 10:20:43 -0800682 preheader->AddDominatedBlock(exit);
683 exit->SetDominator(preheader);
684 RemoveLoop(node); // update hierarchy
Aart Bikb29f6842017-07-28 15:58:41 -0700685 return true;
Aart Bikf8f5a162017-02-06 15:35:29 -0800686 }
687 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800688 // Vectorize loop, if possible and valid.
Aart Bikb29f6842017-07-28 15:58:41 -0700689 if (kEnableVectorization &&
690 TrySetSimpleLoopHeader(header, &main_phi) &&
Aart Bikb29f6842017-07-28 15:58:41 -0700691 ShouldVectorize(node, body, trip_count) &&
692 TryAssignLastValue(node->loop_info, main_phi, preheader, /*collect_loop_uses*/ true)) {
693 Vectorize(node, body, exit, trip_count);
694 graph_->SetHasSIMD(true); // flag SIMD usage
Aart Bik21b85922017-09-06 13:29:16 -0700695 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorized);
Aart Bikb29f6842017-07-28 15:58:41 -0700696 return true;
Aart Bikf8f5a162017-02-06 15:35:29 -0800697 }
Aart Bikb29f6842017-07-28 15:58:41 -0700698 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -0800699}
700
701//
702// Loop vectorization. The implementation is based on the book by Aart J.C. Bik:
703// "The Software Vectorization Handbook. Applying Multimedia Extensions for Maximum Performance."
704// Intel Press, June, 2004 (http://www.aartbik.com/).
705//
706
Aart Bik14a68b42017-06-08 14:06:58 -0700707bool HLoopOptimization::ShouldVectorize(LoopNode* node, HBasicBlock* block, int64_t trip_count) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800708 // Reset vector bookkeeping.
709 vector_length_ = 0;
710 vector_refs_->clear();
Aart Bik38a3f212017-10-20 17:02:21 -0700711 vector_static_peeling_factor_ = 0;
712 vector_dynamic_peeling_candidate_ = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800713 vector_runtime_test_a_ =
Igor Murashkin2ffb7032017-11-08 13:35:21 -0800714 vector_runtime_test_b_ = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800715
716 // Phis in the loop-body prevent vectorization.
717 if (!block->GetPhis().IsEmpty()) {
718 return false;
719 }
720
721 // Scan the loop-body, starting a right-hand-side tree traversal at each left-hand-side
722 // occurrence, which allows passing down attributes down the use tree.
723 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
724 if (!VectorizeDef(node, it.Current(), /*generate_code*/ false)) {
725 return false; // failure to vectorize a left-hand-side
726 }
727 }
728
Aart Bik38a3f212017-10-20 17:02:21 -0700729 // Prepare alignment analysis:
730 // (1) find desired alignment (SIMD vector size in bytes).
731 // (2) initialize static loop peeling votes (peeling factor that will
732 // make one particular reference aligned), never to exceed (1).
733 // (3) variable to record how many references share same alignment.
734 // (4) variable to record suitable candidate for dynamic loop peeling.
735 uint32_t desired_alignment = GetVectorSizeInBytes();
736 DCHECK_LE(desired_alignment, 16u);
737 uint32_t peeling_votes[16] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
738 uint32_t max_num_same_alignment = 0;
739 const ArrayReference* peeling_candidate = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800740
741 // Data dependence analysis. Find each pair of references with same type, where
742 // at least one is a write. Each such pair denotes a possible data dependence.
743 // This analysis exploits the property that differently typed arrays cannot be
744 // aliased, as well as the property that references either point to the same
745 // array or to two completely disjoint arrays, i.e., no partial aliasing.
746 // Other than a few simply heuristics, no detailed subscript analysis is done.
Aart Bik38a3f212017-10-20 17:02:21 -0700747 // The scan over references also prepares finding a suitable alignment strategy.
Aart Bikf8f5a162017-02-06 15:35:29 -0800748 for (auto i = vector_refs_->begin(); i != vector_refs_->end(); ++i) {
Aart Bik38a3f212017-10-20 17:02:21 -0700749 uint32_t num_same_alignment = 0;
750 // Scan over all next references.
Aart Bikf8f5a162017-02-06 15:35:29 -0800751 for (auto j = i; ++j != vector_refs_->end(); ) {
752 if (i->type == j->type && (i->lhs || j->lhs)) {
753 // Found same-typed a[i+x] vs. b[i+y], where at least one is a write.
754 HInstruction* a = i->base;
755 HInstruction* b = j->base;
756 HInstruction* x = i->offset;
757 HInstruction* y = j->offset;
758 if (a == b) {
759 // Found a[i+x] vs. a[i+y]. Accept if x == y (loop-independent data dependence).
760 // Conservatively assume a loop-carried data dependence otherwise, and reject.
761 if (x != y) {
762 return false;
763 }
Aart Bik38a3f212017-10-20 17:02:21 -0700764 // Count the number of references that have the same alignment (since
765 // base and offset are the same) and where at least one is a write, so
766 // e.g. a[i] = a[i] + b[i] counts a[i] but not b[i]).
767 num_same_alignment++;
Aart Bikf8f5a162017-02-06 15:35:29 -0800768 } else {
769 // Found a[i+x] vs. b[i+y]. Accept if x == y (at worst loop-independent data dependence).
770 // Conservatively assume a potential loop-carried data dependence otherwise, avoided by
771 // generating an explicit a != b disambiguation runtime test on the two references.
772 if (x != y) {
Aart Bik37dc4df2017-06-28 14:08:00 -0700773 // To avoid excessive overhead, we only accept one a != b test.
774 if (vector_runtime_test_a_ == nullptr) {
775 // First test found.
776 vector_runtime_test_a_ = a;
777 vector_runtime_test_b_ = b;
778 } else if ((vector_runtime_test_a_ != a || vector_runtime_test_b_ != b) &&
779 (vector_runtime_test_a_ != b || vector_runtime_test_b_ != a)) {
780 return false; // second test would be needed
Aart Bikf8f5a162017-02-06 15:35:29 -0800781 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800782 }
783 }
784 }
785 }
Aart Bik38a3f212017-10-20 17:02:21 -0700786 // Update information for finding suitable alignment strategy:
787 // (1) update votes for static loop peeling,
788 // (2) update suitable candidate for dynamic loop peeling.
789 Alignment alignment = ComputeAlignment(i->offset, i->type, i->is_string_char_at);
790 if (alignment.Base() >= desired_alignment) {
791 // If the array/string object has a known, sufficient alignment, use the
792 // initial offset to compute the static loop peeling vote (this always
793 // works, since elements have natural alignment).
794 uint32_t offset = alignment.Offset() & (desired_alignment - 1u);
795 uint32_t vote = (offset == 0)
796 ? 0
797 : ((desired_alignment - offset) >> DataType::SizeShift(i->type));
798 DCHECK_LT(vote, 16u);
799 ++peeling_votes[vote];
800 } else if (BaseAlignment() >= desired_alignment &&
801 num_same_alignment > max_num_same_alignment) {
802 // Otherwise, if the array/string object has a known, sufficient alignment
803 // for just the base but with an unknown offset, record the candidate with
804 // the most occurrences for dynamic loop peeling (again, the peeling always
805 // works, since elements have natural alignment).
806 max_num_same_alignment = num_same_alignment;
807 peeling_candidate = &(*i);
808 }
809 } // for i
Aart Bikf8f5a162017-02-06 15:35:29 -0800810
Aart Bik38a3f212017-10-20 17:02:21 -0700811 // Find a suitable alignment strategy.
812 SetAlignmentStrategy(peeling_votes, peeling_candidate);
813
814 // Does vectorization seem profitable?
815 if (!IsVectorizationProfitable(trip_count)) {
816 return false;
817 }
Aart Bik14a68b42017-06-08 14:06:58 -0700818
Aart Bikf8f5a162017-02-06 15:35:29 -0800819 // Success!
820 return true;
821}
822
823void HLoopOptimization::Vectorize(LoopNode* node,
824 HBasicBlock* block,
825 HBasicBlock* exit,
826 int64_t trip_count) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800827 HBasicBlock* header = node->loop_info->GetHeader();
828 HBasicBlock* preheader = node->loop_info->GetPreHeader();
829
Aart Bik14a68b42017-06-08 14:06:58 -0700830 // Pick a loop unrolling factor for the vector loop.
831 uint32_t unroll = GetUnrollingFactor(block, trip_count);
832 uint32_t chunk = vector_length_ * unroll;
833
Aart Bik38a3f212017-10-20 17:02:21 -0700834 DCHECK(trip_count == 0 || (trip_count >= MaxNumberPeeled() + chunk));
835
Aart Bik14a68b42017-06-08 14:06:58 -0700836 // A cleanup loop is needed, at least, for any unknown trip count or
837 // for a known trip count with remainder iterations after vectorization.
Aart Bik38a3f212017-10-20 17:02:21 -0700838 bool needs_cleanup = trip_count == 0 ||
839 ((trip_count - vector_static_peeling_factor_) % chunk) != 0;
Aart Bikf8f5a162017-02-06 15:35:29 -0800840
841 // Adjust vector bookkeeping.
Aart Bikb29f6842017-07-28 15:58:41 -0700842 HPhi* main_phi = nullptr;
843 bool is_simple_loop_header = TrySetSimpleLoopHeader(header, &main_phi); // refills sets
Aart Bikf8f5a162017-02-06 15:35:29 -0800844 DCHECK(is_simple_loop_header);
Aart Bik14a68b42017-06-08 14:06:58 -0700845 vector_header_ = header;
846 vector_body_ = block;
Aart Bikf8f5a162017-02-06 15:35:29 -0800847
Aart Bikdbbac8f2017-09-01 13:06:08 -0700848 // Loop induction type.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100849 DataType::Type induc_type = main_phi->GetType();
850 DCHECK(induc_type == DataType::Type::kInt32 || induc_type == DataType::Type::kInt64)
851 << induc_type;
Aart Bikdbbac8f2017-09-01 13:06:08 -0700852
Aart Bik38a3f212017-10-20 17:02:21 -0700853 // Generate the trip count for static or dynamic loop peeling, if needed:
854 // ptc = <peeling factor>;
Aart Bik14a68b42017-06-08 14:06:58 -0700855 HInstruction* ptc = nullptr;
Aart Bik38a3f212017-10-20 17:02:21 -0700856 if (vector_static_peeling_factor_ != 0) {
857 // Static loop peeling for SIMD alignment (using the most suitable
858 // fixed peeling factor found during prior alignment analysis).
859 DCHECK(vector_dynamic_peeling_candidate_ == nullptr);
860 ptc = graph_->GetConstant(induc_type, vector_static_peeling_factor_);
861 } else if (vector_dynamic_peeling_candidate_ != nullptr) {
862 // Dynamic loop peeling for SIMD alignment (using the most suitable
863 // candidate found during prior alignment analysis):
864 // rem = offset % ALIGN; // adjusted as #elements
865 // ptc = rem == 0 ? 0 : (ALIGN - rem);
866 uint32_t shift = DataType::SizeShift(vector_dynamic_peeling_candidate_->type);
867 uint32_t align = GetVectorSizeInBytes() >> shift;
868 uint32_t hidden_offset = HiddenOffset(vector_dynamic_peeling_candidate_->type,
869 vector_dynamic_peeling_candidate_->is_string_char_at);
870 HInstruction* adjusted_offset = graph_->GetConstant(induc_type, hidden_offset >> shift);
871 HInstruction* offset = Insert(preheader, new (global_allocator_) HAdd(
872 induc_type, vector_dynamic_peeling_candidate_->offset, adjusted_offset));
873 HInstruction* rem = Insert(preheader, new (global_allocator_) HAnd(
874 induc_type, offset, graph_->GetConstant(induc_type, align - 1u)));
875 HInstruction* sub = Insert(preheader, new (global_allocator_) HSub(
876 induc_type, graph_->GetConstant(induc_type, align), rem));
877 HInstruction* cond = Insert(preheader, new (global_allocator_) HEqual(
878 rem, graph_->GetConstant(induc_type, 0)));
879 ptc = Insert(preheader, new (global_allocator_) HSelect(
880 cond, graph_->GetConstant(induc_type, 0), sub, kNoDexPc));
881 needs_cleanup = true; // don't know the exact amount
Aart Bik14a68b42017-06-08 14:06:58 -0700882 }
883
884 // Generate loop control:
Aart Bikf8f5a162017-02-06 15:35:29 -0800885 // stc = <trip-count>;
Aart Bik38a3f212017-10-20 17:02:21 -0700886 // ptc = min(stc, ptc);
Aart Bik14a68b42017-06-08 14:06:58 -0700887 // vtc = stc - (stc - ptc) % chunk;
888 // i = 0;
Aart Bikf8f5a162017-02-06 15:35:29 -0800889 HInstruction* stc = induction_range_.GenerateTripCount(node->loop_info, graph_, preheader);
890 HInstruction* vtc = stc;
891 if (needs_cleanup) {
Aart Bik14a68b42017-06-08 14:06:58 -0700892 DCHECK(IsPowerOfTwo(chunk));
893 HInstruction* diff = stc;
894 if (ptc != nullptr) {
Aart Bik38a3f212017-10-20 17:02:21 -0700895 if (trip_count == 0) {
896 HInstruction* cond = Insert(preheader, new (global_allocator_) HAboveOrEqual(stc, ptc));
897 ptc = Insert(preheader, new (global_allocator_) HSelect(cond, ptc, stc, kNoDexPc));
898 }
Aart Bik14a68b42017-06-08 14:06:58 -0700899 diff = Insert(preheader, new (global_allocator_) HSub(induc_type, stc, ptc));
900 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800901 HInstruction* rem = Insert(
902 preheader, new (global_allocator_) HAnd(induc_type,
Aart Bik14a68b42017-06-08 14:06:58 -0700903 diff,
Aart Bikdbbac8f2017-09-01 13:06:08 -0700904 graph_->GetConstant(induc_type, chunk - 1)));
Aart Bikf8f5a162017-02-06 15:35:29 -0800905 vtc = Insert(preheader, new (global_allocator_) HSub(induc_type, stc, rem));
906 }
Aart Bikdbbac8f2017-09-01 13:06:08 -0700907 vector_index_ = graph_->GetConstant(induc_type, 0);
Aart Bikf8f5a162017-02-06 15:35:29 -0800908
909 // Generate runtime disambiguation test:
910 // vtc = a != b ? vtc : 0;
911 if (vector_runtime_test_a_ != nullptr) {
912 HInstruction* rt = Insert(
913 preheader,
914 new (global_allocator_) HNotEqual(vector_runtime_test_a_, vector_runtime_test_b_));
915 vtc = Insert(preheader,
Aart Bikdbbac8f2017-09-01 13:06:08 -0700916 new (global_allocator_)
917 HSelect(rt, vtc, graph_->GetConstant(induc_type, 0), kNoDexPc));
Aart Bikf8f5a162017-02-06 15:35:29 -0800918 needs_cleanup = true;
919 }
920
Aart Bik38a3f212017-10-20 17:02:21 -0700921 // Generate alignment peeling loop, if needed:
Aart Bik14a68b42017-06-08 14:06:58 -0700922 // for ( ; i < ptc; i += 1)
923 // <loop-body>
Aart Bik38a3f212017-10-20 17:02:21 -0700924 //
925 // NOTE: The alignment forced by the peeling loop is preserved even if data is
926 // moved around during suspend checks, since all analysis was based on
927 // nothing more than the Android runtime alignment conventions.
Aart Bik14a68b42017-06-08 14:06:58 -0700928 if (ptc != nullptr) {
929 vector_mode_ = kSequential;
930 GenerateNewLoop(node,
931 block,
932 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
933 vector_index_,
934 ptc,
Aart Bikdbbac8f2017-09-01 13:06:08 -0700935 graph_->GetConstant(induc_type, 1),
Aart Bik521b50f2017-09-09 10:44:45 -0700936 kNoUnrollingFactor);
Aart Bik14a68b42017-06-08 14:06:58 -0700937 }
938
939 // Generate vector loop, possibly further unrolled:
940 // for ( ; i < vtc; i += chunk)
Aart Bikf8f5a162017-02-06 15:35:29 -0800941 // <vectorized-loop-body>
942 vector_mode_ = kVector;
943 GenerateNewLoop(node,
944 block,
Aart Bik14a68b42017-06-08 14:06:58 -0700945 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
946 vector_index_,
Aart Bikf8f5a162017-02-06 15:35:29 -0800947 vtc,
Aart Bikdbbac8f2017-09-01 13:06:08 -0700948 graph_->GetConstant(induc_type, vector_length_), // increment per unroll
Aart Bik14a68b42017-06-08 14:06:58 -0700949 unroll);
Aart Bikf8f5a162017-02-06 15:35:29 -0800950 HLoopInformation* vloop = vector_header_->GetLoopInformation();
951
952 // Generate cleanup loop, if needed:
953 // for ( ; i < stc; i += 1)
954 // <loop-body>
955 if (needs_cleanup) {
956 vector_mode_ = kSequential;
957 GenerateNewLoop(node,
958 block,
959 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
Aart Bik14a68b42017-06-08 14:06:58 -0700960 vector_index_,
Aart Bikf8f5a162017-02-06 15:35:29 -0800961 stc,
Aart Bikdbbac8f2017-09-01 13:06:08 -0700962 graph_->GetConstant(induc_type, 1),
Aart Bik521b50f2017-09-09 10:44:45 -0700963 kNoUnrollingFactor);
Aart Bikf8f5a162017-02-06 15:35:29 -0800964 }
965
Aart Bik0148de42017-09-05 09:25:01 -0700966 // Link reductions to their final uses.
967 for (auto i = reductions_->begin(); i != reductions_->end(); ++i) {
968 if (i->first->IsPhi()) {
Aart Bikdbbac8f2017-09-01 13:06:08 -0700969 HInstruction* phi = i->first;
970 HInstruction* repl = ReduceAndExtractIfNeeded(i->second);
971 // Deal with regular uses.
972 for (const HUseListNode<HInstruction*>& use : phi->GetUses()) {
973 induction_range_.Replace(use.GetUser(), phi, repl); // update induction use
974 }
975 phi->ReplaceWith(repl);
Aart Bik0148de42017-09-05 09:25:01 -0700976 }
977 }
978
Aart Bikf8f5a162017-02-06 15:35:29 -0800979 // Remove the original loop by disconnecting the body block
980 // and removing all instructions from the header.
981 block->DisconnectAndDelete();
982 while (!header->GetFirstInstruction()->IsGoto()) {
983 header->RemoveInstruction(header->GetFirstInstruction());
984 }
Aart Bikb29f6842017-07-28 15:58:41 -0700985
Aart Bik14a68b42017-06-08 14:06:58 -0700986 // Update loop hierarchy: the old header now resides in the same outer loop
987 // as the old preheader. Note that we don't bother putting sequential
988 // loops back in the hierarchy at this point.
Aart Bikf8f5a162017-02-06 15:35:29 -0800989 header->SetLoopInformation(preheader->GetLoopInformation()); // outward
990 node->loop_info = vloop;
991}
992
993void HLoopOptimization::GenerateNewLoop(LoopNode* node,
994 HBasicBlock* block,
995 HBasicBlock* new_preheader,
996 HInstruction* lo,
997 HInstruction* hi,
Aart Bik14a68b42017-06-08 14:06:58 -0700998 HInstruction* step,
999 uint32_t unroll) {
1000 DCHECK(unroll == 1 || vector_mode_ == kVector);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001001 DataType::Type induc_type = lo->GetType();
Aart Bikf8f5a162017-02-06 15:35:29 -08001002 // Prepare new loop.
Aart Bikf8f5a162017-02-06 15:35:29 -08001003 vector_preheader_ = new_preheader,
1004 vector_header_ = vector_preheader_->GetSingleSuccessor();
1005 vector_body_ = vector_header_->GetSuccessors()[1];
Aart Bik14a68b42017-06-08 14:06:58 -07001006 HPhi* phi = new (global_allocator_) HPhi(global_allocator_,
1007 kNoRegNumber,
1008 0,
1009 HPhi::ToPhiType(induc_type));
Aart Bikb07d1bc2017-04-05 10:03:15 -07001010 // Generate header and prepare body.
Aart Bikf8f5a162017-02-06 15:35:29 -08001011 // for (i = lo; i < hi; i += step)
1012 // <loop-body>
Aart Bik14a68b42017-06-08 14:06:58 -07001013 HInstruction* cond = new (global_allocator_) HAboveOrEqual(phi, hi);
1014 vector_header_->AddPhi(phi);
Aart Bikf8f5a162017-02-06 15:35:29 -08001015 vector_header_->AddInstruction(cond);
1016 vector_header_->AddInstruction(new (global_allocator_) HIf(cond));
Aart Bik14a68b42017-06-08 14:06:58 -07001017 vector_index_ = phi;
Aart Bik0148de42017-09-05 09:25:01 -07001018 vector_permanent_map_->clear(); // preserved over unrolling
Aart Bik14a68b42017-06-08 14:06:58 -07001019 for (uint32_t u = 0; u < unroll; u++) {
Aart Bik14a68b42017-06-08 14:06:58 -07001020 // Generate instruction map.
Aart Bik0148de42017-09-05 09:25:01 -07001021 vector_map_->clear();
Aart Bik14a68b42017-06-08 14:06:58 -07001022 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
1023 bool vectorized_def = VectorizeDef(node, it.Current(), /*generate_code*/ true);
1024 DCHECK(vectorized_def);
1025 }
1026 // Generate body from the instruction map, but in original program order.
1027 HEnvironment* env = vector_header_->GetFirstInstruction()->GetEnvironment();
1028 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
1029 auto i = vector_map_->find(it.Current());
1030 if (i != vector_map_->end() && !i->second->IsInBlock()) {
1031 Insert(vector_body_, i->second);
1032 // Deal with instructions that need an environment, such as the scalar intrinsics.
1033 if (i->second->NeedsEnvironment()) {
1034 i->second->CopyEnvironmentFromWithLoopPhiAdjustment(env, vector_header_);
1035 }
1036 }
1037 }
Aart Bik0148de42017-09-05 09:25:01 -07001038 // Generate the induction.
Aart Bik14a68b42017-06-08 14:06:58 -07001039 vector_index_ = new (global_allocator_) HAdd(induc_type, vector_index_, step);
1040 Insert(vector_body_, vector_index_);
Aart Bikf8f5a162017-02-06 15:35:29 -08001041 }
Aart Bik0148de42017-09-05 09:25:01 -07001042 // Finalize phi inputs for the reductions (if any).
1043 for (auto i = reductions_->begin(); i != reductions_->end(); ++i) {
1044 if (!i->first->IsPhi()) {
1045 DCHECK(i->second->IsPhi());
1046 GenerateVecReductionPhiInputs(i->second->AsPhi(), i->first);
1047 }
1048 }
Aart Bikb29f6842017-07-28 15:58:41 -07001049 // Finalize phi inputs for the loop index.
Aart Bik14a68b42017-06-08 14:06:58 -07001050 phi->AddInput(lo);
1051 phi->AddInput(vector_index_);
1052 vector_index_ = phi;
Aart Bikf8f5a162017-02-06 15:35:29 -08001053}
1054
Aart Bikf8f5a162017-02-06 15:35:29 -08001055bool HLoopOptimization::VectorizeDef(LoopNode* node,
1056 HInstruction* instruction,
1057 bool generate_code) {
1058 // Accept a left-hand-side array base[index] for
1059 // (1) supported vector type,
1060 // (2) loop-invariant base,
1061 // (3) unit stride index,
1062 // (4) vectorizable right-hand-side value.
1063 uint64_t restrictions = kNone;
1064 if (instruction->IsArraySet()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001065 DataType::Type type = instruction->AsArraySet()->GetComponentType();
Aart Bikf8f5a162017-02-06 15:35:29 -08001066 HInstruction* base = instruction->InputAt(0);
1067 HInstruction* index = instruction->InputAt(1);
1068 HInstruction* value = instruction->InputAt(2);
1069 HInstruction* offset = nullptr;
1070 if (TrySetVectorType(type, &restrictions) &&
1071 node->loop_info->IsDefinedOutOfTheLoop(base) &&
Aart Bik37dc4df2017-06-28 14:08:00 -07001072 induction_range_.IsUnitStride(instruction, index, graph_, &offset) &&
Aart Bikf8f5a162017-02-06 15:35:29 -08001073 VectorizeUse(node, value, generate_code, type, restrictions)) {
1074 if (generate_code) {
1075 GenerateVecSub(index, offset);
Aart Bik14a68b42017-06-08 14:06:58 -07001076 GenerateVecMem(instruction, vector_map_->Get(index), vector_map_->Get(value), offset, type);
Aart Bikf8f5a162017-02-06 15:35:29 -08001077 } else {
1078 vector_refs_->insert(ArrayReference(base, offset, type, /*lhs*/ true));
1079 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08001080 return true;
1081 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001082 return false;
1083 }
Aart Bik0148de42017-09-05 09:25:01 -07001084 // Accept a left-hand-side reduction for
1085 // (1) supported vector type,
1086 // (2) vectorizable right-hand-side value.
1087 auto redit = reductions_->find(instruction);
1088 if (redit != reductions_->end()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001089 DataType::Type type = instruction->GetType();
Aart Bikdbbac8f2017-09-01 13:06:08 -07001090 // Recognize SAD idiom or direct reduction.
1091 if (VectorizeSADIdiom(node, instruction, generate_code, type, restrictions) ||
1092 (TrySetVectorType(type, &restrictions) &&
1093 VectorizeUse(node, instruction, generate_code, type, restrictions))) {
Aart Bik0148de42017-09-05 09:25:01 -07001094 if (generate_code) {
1095 HInstruction* new_red = vector_map_->Get(instruction);
1096 vector_permanent_map_->Put(new_red, vector_map_->Get(redit->second));
1097 vector_permanent_map_->Overwrite(redit->second, new_red);
1098 }
1099 return true;
1100 }
1101 return false;
1102 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001103 // Branch back okay.
1104 if (instruction->IsGoto()) {
1105 return true;
1106 }
1107 // Otherwise accept only expressions with no effects outside the immediate loop-body.
1108 // Note that actual uses are inspected during right-hand-side tree traversal.
1109 return !IsUsedOutsideLoop(node->loop_info, instruction) && !instruction->DoesAnyWrite();
1110}
1111
Aart Bik304c8a52017-05-23 11:01:13 -07001112// TODO: saturation arithmetic.
Aart Bikf8f5a162017-02-06 15:35:29 -08001113bool HLoopOptimization::VectorizeUse(LoopNode* node,
1114 HInstruction* instruction,
1115 bool generate_code,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001116 DataType::Type type,
Aart Bikf8f5a162017-02-06 15:35:29 -08001117 uint64_t restrictions) {
1118 // Accept anything for which code has already been generated.
1119 if (generate_code) {
1120 if (vector_map_->find(instruction) != vector_map_->end()) {
1121 return true;
1122 }
1123 }
1124 // Continue the right-hand-side tree traversal, passing in proper
1125 // types and vector restrictions along the way. During code generation,
1126 // all new nodes are drawn from the global allocator.
1127 if (node->loop_info->IsDefinedOutOfTheLoop(instruction)) {
1128 // Accept invariant use, using scalar expansion.
1129 if (generate_code) {
1130 GenerateVecInv(instruction, type);
1131 }
1132 return true;
1133 } else if (instruction->IsArrayGet()) {
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001134 // Deal with vector restrictions.
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001135 bool is_string_char_at = instruction->AsArrayGet()->IsStringCharAt();
1136 if (is_string_char_at && HasVectorRestrictions(restrictions, kNoStringCharAt)) {
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001137 return false;
1138 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001139 // Accept a right-hand-side array base[index] for
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001140 // (1) matching vector type (exact match or signed/unsigned integral type of the same size),
Aart Bikf8f5a162017-02-06 15:35:29 -08001141 // (2) loop-invariant base,
1142 // (3) unit stride index,
1143 // (4) vectorizable right-hand-side value.
1144 HInstruction* base = instruction->InputAt(0);
1145 HInstruction* index = instruction->InputAt(1);
1146 HInstruction* offset = nullptr;
Aart Bik46b6dbc2017-10-03 11:37:37 -07001147 if (HVecOperation::ToSignedType(type) == HVecOperation::ToSignedType(instruction->GetType()) &&
Aart Bikf8f5a162017-02-06 15:35:29 -08001148 node->loop_info->IsDefinedOutOfTheLoop(base) &&
Aart Bik37dc4df2017-06-28 14:08:00 -07001149 induction_range_.IsUnitStride(instruction, index, graph_, &offset)) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001150 if (generate_code) {
1151 GenerateVecSub(index, offset);
Aart Bik14a68b42017-06-08 14:06:58 -07001152 GenerateVecMem(instruction, vector_map_->Get(index), nullptr, offset, type);
Aart Bikf8f5a162017-02-06 15:35:29 -08001153 } else {
Aart Bik38a3f212017-10-20 17:02:21 -07001154 vector_refs_->insert(ArrayReference(base, offset, type, /*lhs*/ false, is_string_char_at));
Aart Bikf8f5a162017-02-06 15:35:29 -08001155 }
1156 return true;
1157 }
Aart Bik0148de42017-09-05 09:25:01 -07001158 } else if (instruction->IsPhi()) {
1159 // Accept particular phi operations.
1160 if (reductions_->find(instruction) != reductions_->end()) {
1161 // Deal with vector restrictions.
1162 if (HasVectorRestrictions(restrictions, kNoReduction)) {
1163 return false;
1164 }
1165 // Accept a reduction.
1166 if (generate_code) {
1167 GenerateVecReductionPhi(instruction->AsPhi());
1168 }
1169 return true;
1170 }
1171 // TODO: accept right-hand-side induction?
1172 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001173 } else if (instruction->IsTypeConversion()) {
1174 // Accept particular type conversions.
1175 HTypeConversion* conversion = instruction->AsTypeConversion();
1176 HInstruction* opa = conversion->InputAt(0);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001177 DataType::Type from = conversion->GetInputType();
1178 DataType::Type to = conversion->GetResultType();
1179 if (DataType::IsIntegralType(from) && DataType::IsIntegralType(to)) {
Aart Bik38a3f212017-10-20 17:02:21 -07001180 uint32_t size_vec = DataType::Size(type);
1181 uint32_t size_from = DataType::Size(from);
1182 uint32_t size_to = DataType::Size(to);
Aart Bikdbbac8f2017-09-01 13:06:08 -07001183 // Accept an integral conversion
1184 // (1a) narrowing into vector type, "wider" operations cannot bring in higher order bits, or
1185 // (1b) widening from at least vector type, and
1186 // (2) vectorizable operand.
1187 if ((size_to < size_from &&
1188 size_to == size_vec &&
1189 VectorizeUse(node, opa, generate_code, type, restrictions | kNoHiBits)) ||
1190 (size_to >= size_from &&
1191 size_from >= size_vec &&
Aart Bik4d1a9d42017-10-19 14:40:55 -07001192 VectorizeUse(node, opa, generate_code, type, restrictions))) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001193 if (generate_code) {
1194 if (vector_mode_ == kVector) {
1195 vector_map_->Put(instruction, vector_map_->Get(opa)); // operand pass-through
1196 } else {
1197 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1198 }
1199 }
1200 return true;
1201 }
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001202 } else if (to == DataType::Type::kFloat32 && from == DataType::Type::kInt32) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001203 DCHECK_EQ(to, type);
1204 // Accept int to float conversion for
1205 // (1) supported int,
1206 // (2) vectorizable operand.
1207 if (TrySetVectorType(from, &restrictions) &&
1208 VectorizeUse(node, opa, generate_code, from, restrictions)) {
1209 if (generate_code) {
1210 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1211 }
1212 return true;
1213 }
1214 }
1215 return false;
1216 } else if (instruction->IsNeg() || instruction->IsNot() || instruction->IsBooleanNot()) {
1217 // Accept unary operator for vectorizable operand.
1218 HInstruction* opa = instruction->InputAt(0);
1219 if (VectorizeUse(node, opa, generate_code, type, restrictions)) {
1220 if (generate_code) {
1221 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1222 }
1223 return true;
1224 }
1225 } else if (instruction->IsAdd() || instruction->IsSub() ||
1226 instruction->IsMul() || instruction->IsDiv() ||
1227 instruction->IsAnd() || instruction->IsOr() || instruction->IsXor()) {
1228 // Deal with vector restrictions.
1229 if ((instruction->IsMul() && HasVectorRestrictions(restrictions, kNoMul)) ||
1230 (instruction->IsDiv() && HasVectorRestrictions(restrictions, kNoDiv))) {
1231 return false;
1232 }
1233 // Accept binary operator for vectorizable operands.
1234 HInstruction* opa = instruction->InputAt(0);
1235 HInstruction* opb = instruction->InputAt(1);
1236 if (VectorizeUse(node, opa, generate_code, type, restrictions) &&
1237 VectorizeUse(node, opb, generate_code, type, restrictions)) {
1238 if (generate_code) {
1239 GenerateVecOp(instruction, vector_map_->Get(opa), vector_map_->Get(opb), type);
1240 }
1241 return true;
1242 }
1243 } else if (instruction->IsShl() || instruction->IsShr() || instruction->IsUShr()) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001244 // Recognize halving add idiom.
Aart Bikf3e61ee2017-04-12 17:09:20 -07001245 if (VectorizeHalvingAddIdiom(node, instruction, generate_code, type, restrictions)) {
1246 return true;
1247 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001248 // Deal with vector restrictions.
Aart Bik304c8a52017-05-23 11:01:13 -07001249 HInstruction* opa = instruction->InputAt(0);
1250 HInstruction* opb = instruction->InputAt(1);
1251 HInstruction* r = opa;
1252 bool is_unsigned = false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001253 if ((HasVectorRestrictions(restrictions, kNoShift)) ||
1254 (instruction->IsShr() && HasVectorRestrictions(restrictions, kNoShr))) {
1255 return false; // unsupported instruction
Aart Bik304c8a52017-05-23 11:01:13 -07001256 } else if (HasVectorRestrictions(restrictions, kNoHiBits)) {
1257 // Shifts right need extra care to account for higher order bits.
1258 // TODO: less likely shr/unsigned and ushr/signed can by flipping signess.
1259 if (instruction->IsShr() &&
1260 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || is_unsigned)) {
1261 return false; // reject, unless all operands are sign-extension narrower
1262 } else if (instruction->IsUShr() &&
1263 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || !is_unsigned)) {
1264 return false; // reject, unless all operands are zero-extension narrower
1265 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001266 }
1267 // Accept shift operator for vectorizable/invariant operands.
1268 // TODO: accept symbolic, albeit loop invariant shift factors.
Aart Bik304c8a52017-05-23 11:01:13 -07001269 DCHECK(r != nullptr);
1270 if (generate_code && vector_mode_ != kVector) { // de-idiom
1271 r = opa;
1272 }
Aart Bik50e20d52017-05-05 14:07:29 -07001273 int64_t distance = 0;
Aart Bik304c8a52017-05-23 11:01:13 -07001274 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
Aart Bik50e20d52017-05-05 14:07:29 -07001275 IsInt64AndGet(opb, /*out*/ &distance)) {
Aart Bik65ffd8e2017-05-01 16:50:45 -07001276 // Restrict shift distance to packed data type width.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001277 int64_t max_distance = DataType::Size(type) * 8;
Aart Bik65ffd8e2017-05-01 16:50:45 -07001278 if (0 <= distance && distance < max_distance) {
1279 if (generate_code) {
Aart Bik304c8a52017-05-23 11:01:13 -07001280 GenerateVecOp(instruction, vector_map_->Get(r), opb, type);
Aart Bik65ffd8e2017-05-01 16:50:45 -07001281 }
1282 return true;
Aart Bikf8f5a162017-02-06 15:35:29 -08001283 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001284 }
Aart Bik3b2a5952018-03-05 13:55:28 -08001285 } else if (instruction->IsAbs()) {
1286 // Deal with vector restrictions.
1287 HInstruction* opa = instruction->InputAt(0);
1288 HInstruction* r = opa;
1289 bool is_unsigned = false;
1290 if (HasVectorRestrictions(restrictions, kNoAbs)) {
1291 return false;
1292 } else if (HasVectorRestrictions(restrictions, kNoHiBits) &&
1293 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || is_unsigned)) {
1294 return false; // reject, unless operand is sign-extension narrower
1295 }
1296 // Accept ABS(x) for vectorizable operand.
1297 DCHECK(r != nullptr);
1298 if (generate_code && vector_mode_ != kVector) { // de-idiom
1299 r = opa;
1300 }
1301 if (VectorizeUse(node, r, generate_code, type, restrictions)) {
1302 if (generate_code) {
1303 GenerateVecOp(instruction,
1304 vector_map_->Get(r),
1305 nullptr,
1306 HVecOperation::ToProperType(type, is_unsigned));
1307 }
1308 return true;
1309 }
Aart Bik1f8d51b2018-02-15 10:42:37 -08001310 } else if (instruction->IsMin() || instruction->IsMax()) {
1311 // Deal with vector restrictions.
1312 HInstruction* opa = instruction->InputAt(0);
1313 HInstruction* opb = instruction->InputAt(1);
1314 HInstruction* r = opa;
1315 HInstruction* s = opb;
1316 bool is_unsigned = false;
1317 if (HasVectorRestrictions(restrictions, kNoMinMax)) {
1318 return false;
1319 } else if (HasVectorRestrictions(restrictions, kNoHiBits) &&
1320 !IsNarrowerOperands(opa, opb, type, &r, &s, &is_unsigned)) {
1321 return false; // reject, unless all operands are same-extension narrower
1322 }
1323 // Accept MIN/MAX(x, y) for vectorizable operands.
1324 DCHECK(r != nullptr);
1325 DCHECK(s != nullptr);
1326 if (generate_code && vector_mode_ != kVector) { // de-idiom
1327 r = opa;
1328 s = opb;
1329 }
1330 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
1331 VectorizeUse(node, s, generate_code, type, restrictions)) {
1332 if (generate_code) {
1333 GenerateVecOp(
1334 instruction, vector_map_->Get(r), vector_map_->Get(s), type, is_unsigned);
Aart Bikc8e93c72017-05-10 10:49:22 -07001335 }
Aart Bik1f8d51b2018-02-15 10:42:37 -08001336 return true;
1337 }
Aart Bik281c6812016-08-26 11:31:48 -07001338 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08001339 return false;
Aart Bik281c6812016-08-26 11:31:48 -07001340}
1341
Aart Bik38a3f212017-10-20 17:02:21 -07001342uint32_t HLoopOptimization::GetVectorSizeInBytes() {
1343 switch (compiler_driver_->GetInstructionSet()) {
Vladimir Marko33bff252017-11-01 14:35:42 +00001344 case InstructionSet::kArm:
1345 case InstructionSet::kThumb2:
Aart Bik38a3f212017-10-20 17:02:21 -07001346 return 8; // 64-bit SIMD
1347 default:
1348 return 16; // 128-bit SIMD
1349 }
1350}
1351
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001352bool HLoopOptimization::TrySetVectorType(DataType::Type type, uint64_t* restrictions) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001353 const InstructionSetFeatures* features = compiler_driver_->GetInstructionSetFeatures();
1354 switch (compiler_driver_->GetInstructionSet()) {
Vladimir Marko33bff252017-11-01 14:35:42 +00001355 case InstructionSet::kArm:
1356 case InstructionSet::kThumb2:
Artem Serov8f7c4102017-06-21 11:21:37 +01001357 // Allow vectorization for all ARM devices, because Android assumes that
Aart Bikb29f6842017-07-28 15:58:41 -07001358 // ARM 32-bit always supports advanced SIMD (64-bit SIMD).
Artem Serov8f7c4102017-06-21 11:21:37 +01001359 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001360 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001361 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001362 case DataType::Type::kInt8:
Aart Bik0148de42017-09-05 09:25:01 -07001363 *restrictions |= kNoDiv | kNoReduction;
Artem Serov8f7c4102017-06-21 11:21:37 +01001364 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001365 case DataType::Type::kUint16:
1366 case DataType::Type::kInt16:
Aart Bik0148de42017-09-05 09:25:01 -07001367 *restrictions |= kNoDiv | kNoStringCharAt | kNoReduction;
Artem Serov8f7c4102017-06-21 11:21:37 +01001368 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001369 case DataType::Type::kInt32:
Artem Serov6e9b1372017-10-05 16:48:30 +01001370 *restrictions |= kNoDiv | kNoWideSAD;
Artem Serov8f7c4102017-06-21 11:21:37 +01001371 return TrySetVectorLength(2);
1372 default:
1373 break;
1374 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001375 return false;
Vladimir Marko33bff252017-11-01 14:35:42 +00001376 case InstructionSet::kArm64:
Aart Bikf8f5a162017-02-06 15:35:29 -08001377 // Allow vectorization for all ARM devices, because Android assumes that
Aart Bikb29f6842017-07-28 15:58:41 -07001378 // ARMv8 AArch64 always supports advanced SIMD (128-bit SIMD).
Aart Bikf8f5a162017-02-06 15:35:29 -08001379 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001380 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001381 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001382 case DataType::Type::kInt8:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001383 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +01001384 return TrySetVectorLength(16);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001385 case DataType::Type::kUint16:
1386 case DataType::Type::kInt16:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001387 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +01001388 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001389 case DataType::Type::kInt32:
Aart Bikf8f5a162017-02-06 15:35:29 -08001390 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +01001391 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001392 case DataType::Type::kInt64:
Aart Bikc8e93c72017-05-10 10:49:22 -07001393 *restrictions |= kNoDiv | kNoMul | kNoMinMax;
Aart Bikf8f5a162017-02-06 15:35:29 -08001394 return TrySetVectorLength(2);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001395 case DataType::Type::kFloat32:
Aart Bik0148de42017-09-05 09:25:01 -07001396 *restrictions |= kNoReduction;
Artem Serovd4bccf12017-04-03 18:47:32 +01001397 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001398 case DataType::Type::kFloat64:
Aart Bik0148de42017-09-05 09:25:01 -07001399 *restrictions |= kNoReduction;
Aart Bikf8f5a162017-02-06 15:35:29 -08001400 return TrySetVectorLength(2);
1401 default:
1402 return false;
1403 }
Vladimir Marko33bff252017-11-01 14:35:42 +00001404 case InstructionSet::kX86:
1405 case InstructionSet::kX86_64:
Aart Bikb29f6842017-07-28 15:58:41 -07001406 // Allow vectorization for SSE4.1-enabled X86 devices only (128-bit SIMD).
Aart Bikf8f5a162017-02-06 15:35:29 -08001407 if (features->AsX86InstructionSetFeatures()->HasSSE4_1()) {
1408 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001409 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001410 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001411 case DataType::Type::kInt8:
Aart Bik0148de42017-09-05 09:25:01 -07001412 *restrictions |=
Aart Bikdbbac8f2017-09-01 13:06:08 -07001413 kNoMul | kNoDiv | kNoShift | kNoAbs | kNoSignedHAdd | kNoUnroundedHAdd | kNoSAD;
Aart Bikf8f5a162017-02-06 15:35:29 -08001414 return TrySetVectorLength(16);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001415 case DataType::Type::kUint16:
1416 case DataType::Type::kInt16:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001417 *restrictions |= kNoDiv | kNoAbs | kNoSignedHAdd | kNoUnroundedHAdd | kNoSAD;
Aart Bikf8f5a162017-02-06 15:35:29 -08001418 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001419 case DataType::Type::kInt32:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001420 *restrictions |= kNoDiv | kNoSAD;
Aart Bikf8f5a162017-02-06 15:35:29 -08001421 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001422 case DataType::Type::kInt64:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001423 *restrictions |= kNoMul | kNoDiv | kNoShr | kNoAbs | kNoMinMax | kNoSAD;
Aart Bikf8f5a162017-02-06 15:35:29 -08001424 return TrySetVectorLength(2);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001425 case DataType::Type::kFloat32:
Aart Bik0148de42017-09-05 09:25:01 -07001426 *restrictions |= kNoMinMax | kNoReduction; // minmax: -0.0 vs +0.0
Aart Bikf8f5a162017-02-06 15:35:29 -08001427 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001428 case DataType::Type::kFloat64:
Aart Bik0148de42017-09-05 09:25:01 -07001429 *restrictions |= kNoMinMax | kNoReduction; // minmax: -0.0 vs +0.0
Aart Bikf8f5a162017-02-06 15:35:29 -08001430 return TrySetVectorLength(2);
1431 default:
1432 break;
1433 } // switch type
1434 }
1435 return false;
Vladimir Marko33bff252017-11-01 14:35:42 +00001436 case InstructionSet::kMips:
Lena Djokic51765b02017-06-22 13:49:59 +02001437 if (features->AsMipsInstructionSetFeatures()->HasMsa()) {
1438 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001439 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001440 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001441 case DataType::Type::kInt8:
Lena Djokic38e380b2017-10-30 16:17:10 +01001442 *restrictions |= kNoDiv;
Lena Djokic51765b02017-06-22 13:49:59 +02001443 return TrySetVectorLength(16);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001444 case DataType::Type::kUint16:
1445 case DataType::Type::kInt16:
Lena Djokic38e380b2017-10-30 16:17:10 +01001446 *restrictions |= kNoDiv | kNoStringCharAt;
Lena Djokic51765b02017-06-22 13:49:59 +02001447 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001448 case DataType::Type::kInt32:
Lena Djokic38e380b2017-10-30 16:17:10 +01001449 *restrictions |= kNoDiv;
Lena Djokic51765b02017-06-22 13:49:59 +02001450 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001451 case DataType::Type::kInt64:
Lena Djokic38e380b2017-10-30 16:17:10 +01001452 *restrictions |= kNoDiv;
Lena Djokic51765b02017-06-22 13:49:59 +02001453 return TrySetVectorLength(2);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001454 case DataType::Type::kFloat32:
Aart Bik0148de42017-09-05 09:25:01 -07001455 *restrictions |= kNoMinMax | kNoReduction; // min/max(x, NaN)
Lena Djokic51765b02017-06-22 13:49:59 +02001456 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001457 case DataType::Type::kFloat64:
Aart Bik0148de42017-09-05 09:25:01 -07001458 *restrictions |= kNoMinMax | kNoReduction; // min/max(x, NaN)
Lena Djokic51765b02017-06-22 13:49:59 +02001459 return TrySetVectorLength(2);
1460 default:
1461 break;
1462 } // switch type
1463 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001464 return false;
Vladimir Marko33bff252017-11-01 14:35:42 +00001465 case InstructionSet::kMips64:
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001466 if (features->AsMips64InstructionSetFeatures()->HasMsa()) {
1467 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001468 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001469 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001470 case DataType::Type::kInt8:
Lena Djokic38e380b2017-10-30 16:17:10 +01001471 *restrictions |= kNoDiv;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001472 return TrySetVectorLength(16);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001473 case DataType::Type::kUint16:
1474 case DataType::Type::kInt16:
Lena Djokic38e380b2017-10-30 16:17:10 +01001475 *restrictions |= kNoDiv | kNoStringCharAt;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001476 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001477 case DataType::Type::kInt32:
Lena Djokic38e380b2017-10-30 16:17:10 +01001478 *restrictions |= kNoDiv;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001479 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001480 case DataType::Type::kInt64:
Lena Djokic38e380b2017-10-30 16:17:10 +01001481 *restrictions |= kNoDiv;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001482 return TrySetVectorLength(2);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001483 case DataType::Type::kFloat32:
Aart Bik0148de42017-09-05 09:25:01 -07001484 *restrictions |= kNoMinMax | kNoReduction; // min/max(x, NaN)
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001485 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001486 case DataType::Type::kFloat64:
Aart Bik0148de42017-09-05 09:25:01 -07001487 *restrictions |= kNoMinMax | kNoReduction; // min/max(x, NaN)
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001488 return TrySetVectorLength(2);
1489 default:
1490 break;
1491 } // switch type
1492 }
1493 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001494 default:
1495 return false;
1496 } // switch instruction set
1497}
1498
1499bool HLoopOptimization::TrySetVectorLength(uint32_t length) {
1500 DCHECK(IsPowerOfTwo(length) && length >= 2u);
1501 // First time set?
1502 if (vector_length_ == 0) {
1503 vector_length_ = length;
1504 }
1505 // Different types are acceptable within a loop-body, as long as all the corresponding vector
1506 // lengths match exactly to obtain a uniform traversal through the vector iteration space
1507 // (idiomatic exceptions to this rule can be handled by further unrolling sub-expressions).
1508 return vector_length_ == length;
1509}
1510
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001511void HLoopOptimization::GenerateVecInv(HInstruction* org, DataType::Type type) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001512 if (vector_map_->find(org) == vector_map_->end()) {
1513 // In scalar code, just use a self pass-through for scalar invariants
1514 // (viz. expression remains itself).
1515 if (vector_mode_ == kSequential) {
1516 vector_map_->Put(org, org);
1517 return;
1518 }
1519 // In vector code, explicit scalar expansion is needed.
Aart Bik0148de42017-09-05 09:25:01 -07001520 HInstruction* vector = nullptr;
1521 auto it = vector_permanent_map_->find(org);
1522 if (it != vector_permanent_map_->end()) {
1523 vector = it->second; // reuse during unrolling
1524 } else {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001525 // Generates ReplicateScalar( (optional_type_conv) org ).
1526 HInstruction* input = org;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001527 DataType::Type input_type = input->GetType();
1528 if (type != input_type && (type == DataType::Type::kInt64 ||
1529 input_type == DataType::Type::kInt64)) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001530 input = Insert(vector_preheader_,
1531 new (global_allocator_) HTypeConversion(type, input, kNoDexPc));
1532 }
1533 vector = new (global_allocator_)
Aart Bik46b6dbc2017-10-03 11:37:37 -07001534 HVecReplicateScalar(global_allocator_, input, type, vector_length_, kNoDexPc);
Aart Bik0148de42017-09-05 09:25:01 -07001535 vector_permanent_map_->Put(org, Insert(vector_preheader_, vector));
1536 }
1537 vector_map_->Put(org, vector);
Aart Bikf8f5a162017-02-06 15:35:29 -08001538 }
1539}
1540
1541void HLoopOptimization::GenerateVecSub(HInstruction* org, HInstruction* offset) {
1542 if (vector_map_->find(org) == vector_map_->end()) {
Aart Bik14a68b42017-06-08 14:06:58 -07001543 HInstruction* subscript = vector_index_;
Aart Bik37dc4df2017-06-28 14:08:00 -07001544 int64_t value = 0;
1545 if (!IsInt64AndGet(offset, &value) || value != 0) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001546 subscript = new (global_allocator_) HAdd(DataType::Type::kInt32, subscript, offset);
Aart Bikf8f5a162017-02-06 15:35:29 -08001547 if (org->IsPhi()) {
1548 Insert(vector_body_, subscript); // lacks layout placeholder
1549 }
1550 }
1551 vector_map_->Put(org, subscript);
1552 }
1553}
1554
1555void HLoopOptimization::GenerateVecMem(HInstruction* org,
1556 HInstruction* opa,
1557 HInstruction* opb,
Aart Bik14a68b42017-06-08 14:06:58 -07001558 HInstruction* offset,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001559 DataType::Type type) {
Aart Bik46b6dbc2017-10-03 11:37:37 -07001560 uint32_t dex_pc = org->GetDexPc();
Aart Bikf8f5a162017-02-06 15:35:29 -08001561 HInstruction* vector = nullptr;
1562 if (vector_mode_ == kVector) {
1563 // Vector store or load.
Aart Bik38a3f212017-10-20 17:02:21 -07001564 bool is_string_char_at = false;
Aart Bik14a68b42017-06-08 14:06:58 -07001565 HInstruction* base = org->InputAt(0);
Aart Bikf8f5a162017-02-06 15:35:29 -08001566 if (opb != nullptr) {
1567 vector = new (global_allocator_) HVecStore(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001568 global_allocator_, base, opa, opb, type, org->GetSideEffects(), vector_length_, dex_pc);
Aart Bikf8f5a162017-02-06 15:35:29 -08001569 } else {
Aart Bik38a3f212017-10-20 17:02:21 -07001570 is_string_char_at = org->AsArrayGet()->IsStringCharAt();
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001571 vector = new (global_allocator_) HVecLoad(global_allocator_,
1572 base,
1573 opa,
1574 type,
1575 org->GetSideEffects(),
1576 vector_length_,
Aart Bik46b6dbc2017-10-03 11:37:37 -07001577 is_string_char_at,
1578 dex_pc);
Aart Bik14a68b42017-06-08 14:06:58 -07001579 }
Aart Bik38a3f212017-10-20 17:02:21 -07001580 // Known (forced/adjusted/original) alignment?
1581 if (vector_dynamic_peeling_candidate_ != nullptr) {
1582 if (vector_dynamic_peeling_candidate_->offset == offset && // TODO: diffs too?
1583 DataType::Size(vector_dynamic_peeling_candidate_->type) == DataType::Size(type) &&
1584 vector_dynamic_peeling_candidate_->is_string_char_at == is_string_char_at) {
1585 vector->AsVecMemoryOperation()->SetAlignment( // forced
1586 Alignment(GetVectorSizeInBytes(), 0));
1587 }
1588 } else {
1589 vector->AsVecMemoryOperation()->SetAlignment( // adjusted/original
1590 ComputeAlignment(offset, type, is_string_char_at, vector_static_peeling_factor_));
Aart Bikf8f5a162017-02-06 15:35:29 -08001591 }
1592 } else {
1593 // Scalar store or load.
1594 DCHECK(vector_mode_ == kSequential);
1595 if (opb != nullptr) {
Aart Bik4d1a9d42017-10-19 14:40:55 -07001596 DataType::Type component_type = org->AsArraySet()->GetComponentType();
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001597 vector = new (global_allocator_) HArraySet(
Aart Bik4d1a9d42017-10-19 14:40:55 -07001598 org->InputAt(0), opa, opb, component_type, org->GetSideEffects(), dex_pc);
Aart Bikf8f5a162017-02-06 15:35:29 -08001599 } else {
Aart Bikdb14fcf2017-04-25 15:53:58 -07001600 bool is_string_char_at = org->AsArrayGet()->IsStringCharAt();
1601 vector = new (global_allocator_) HArrayGet(
Aart Bik4d1a9d42017-10-19 14:40:55 -07001602 org->InputAt(0), opa, org->GetType(), org->GetSideEffects(), dex_pc, is_string_char_at);
Aart Bikf8f5a162017-02-06 15:35:29 -08001603 }
1604 }
1605 vector_map_->Put(org, vector);
1606}
1607
Aart Bik0148de42017-09-05 09:25:01 -07001608void HLoopOptimization::GenerateVecReductionPhi(HPhi* phi) {
1609 DCHECK(reductions_->find(phi) != reductions_->end());
1610 DCHECK(reductions_->Get(phi->InputAt(1)) == phi);
1611 HInstruction* vector = nullptr;
1612 if (vector_mode_ == kSequential) {
1613 HPhi* new_phi = new (global_allocator_) HPhi(
1614 global_allocator_, kNoRegNumber, 0, phi->GetType());
1615 vector_header_->AddPhi(new_phi);
1616 vector = new_phi;
1617 } else {
1618 // Link vector reduction back to prior unrolled update, or a first phi.
1619 auto it = vector_permanent_map_->find(phi);
1620 if (it != vector_permanent_map_->end()) {
1621 vector = it->second;
1622 } else {
1623 HPhi* new_phi = new (global_allocator_) HPhi(
1624 global_allocator_, kNoRegNumber, 0, HVecOperation::kSIMDType);
1625 vector_header_->AddPhi(new_phi);
1626 vector = new_phi;
1627 }
1628 }
1629 vector_map_->Put(phi, vector);
1630}
1631
1632void HLoopOptimization::GenerateVecReductionPhiInputs(HPhi* phi, HInstruction* reduction) {
1633 HInstruction* new_phi = vector_map_->Get(phi);
1634 HInstruction* new_init = reductions_->Get(phi);
1635 HInstruction* new_red = vector_map_->Get(reduction);
1636 // Link unrolled vector loop back to new phi.
1637 for (; !new_phi->IsPhi(); new_phi = vector_permanent_map_->Get(new_phi)) {
1638 DCHECK(new_phi->IsVecOperation());
1639 }
1640 // Prepare the new initialization.
1641 if (vector_mode_ == kVector) {
Goran Jakovljevic89b8df02017-10-13 08:33:17 +02001642 // Generate a [initial, 0, .., 0] vector for add or
1643 // a [initial, initial, .., initial] vector for min/max.
Aart Bikdbbac8f2017-09-01 13:06:08 -07001644 HVecOperation* red_vector = new_red->AsVecOperation();
Goran Jakovljevic89b8df02017-10-13 08:33:17 +02001645 HVecReduce::ReductionKind kind = GetReductionKind(red_vector);
Aart Bik38a3f212017-10-20 17:02:21 -07001646 uint32_t vector_length = red_vector->GetVectorLength();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001647 DataType::Type type = red_vector->GetPackedType();
Goran Jakovljevic89b8df02017-10-13 08:33:17 +02001648 if (kind == HVecReduce::ReductionKind::kSum) {
1649 new_init = Insert(vector_preheader_,
1650 new (global_allocator_) HVecSetScalars(global_allocator_,
1651 &new_init,
1652 type,
1653 vector_length,
1654 1,
1655 kNoDexPc));
1656 } else {
1657 new_init = Insert(vector_preheader_,
1658 new (global_allocator_) HVecReplicateScalar(global_allocator_,
1659 new_init,
1660 type,
1661 vector_length,
1662 kNoDexPc));
1663 }
Aart Bik0148de42017-09-05 09:25:01 -07001664 } else {
1665 new_init = ReduceAndExtractIfNeeded(new_init);
1666 }
1667 // Set the phi inputs.
1668 DCHECK(new_phi->IsPhi());
1669 new_phi->AsPhi()->AddInput(new_init);
1670 new_phi->AsPhi()->AddInput(new_red);
1671 // New feed value for next phi (safe mutation in iteration).
1672 reductions_->find(phi)->second = new_phi;
1673}
1674
1675HInstruction* HLoopOptimization::ReduceAndExtractIfNeeded(HInstruction* instruction) {
1676 if (instruction->IsPhi()) {
1677 HInstruction* input = instruction->InputAt(1);
Aart Bik2dd7b672017-12-07 11:11:22 -08001678 if (HVecOperation::ReturnsSIMDValue(input)) {
1679 DCHECK(!input->IsPhi());
Aart Bikdbbac8f2017-09-01 13:06:08 -07001680 HVecOperation* input_vector = input->AsVecOperation();
Aart Bik38a3f212017-10-20 17:02:21 -07001681 uint32_t vector_length = input_vector->GetVectorLength();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001682 DataType::Type type = input_vector->GetPackedType();
Aart Bikdbbac8f2017-09-01 13:06:08 -07001683 HVecReduce::ReductionKind kind = GetReductionKind(input_vector);
Aart Bik0148de42017-09-05 09:25:01 -07001684 HBasicBlock* exit = instruction->GetBlock()->GetSuccessors()[0];
1685 // Generate a vector reduction and scalar extract
1686 // x = REDUCE( [x_1, .., x_n] )
1687 // y = x_1
1688 // along the exit of the defining loop.
Aart Bik0148de42017-09-05 09:25:01 -07001689 HInstruction* reduce = new (global_allocator_) HVecReduce(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001690 global_allocator_, instruction, type, vector_length, kind, kNoDexPc);
Aart Bik0148de42017-09-05 09:25:01 -07001691 exit->InsertInstructionBefore(reduce, exit->GetFirstInstruction());
1692 instruction = new (global_allocator_) HVecExtractScalar(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001693 global_allocator_, reduce, type, vector_length, 0, kNoDexPc);
Aart Bik0148de42017-09-05 09:25:01 -07001694 exit->InsertInstructionAfter(instruction, reduce);
1695 }
1696 }
1697 return instruction;
1698}
1699
Aart Bikf8f5a162017-02-06 15:35:29 -08001700#define GENERATE_VEC(x, y) \
1701 if (vector_mode_ == kVector) { \
1702 vector = (x); \
1703 } else { \
1704 DCHECK(vector_mode_ == kSequential); \
1705 vector = (y); \
1706 } \
1707 break;
1708
1709void HLoopOptimization::GenerateVecOp(HInstruction* org,
1710 HInstruction* opa,
1711 HInstruction* opb,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001712 DataType::Type type,
Aart Bik304c8a52017-05-23 11:01:13 -07001713 bool is_unsigned) {
Aart Bik46b6dbc2017-10-03 11:37:37 -07001714 uint32_t dex_pc = org->GetDexPc();
Aart Bikf8f5a162017-02-06 15:35:29 -08001715 HInstruction* vector = nullptr;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001716 DataType::Type org_type = org->GetType();
Aart Bikf8f5a162017-02-06 15:35:29 -08001717 switch (org->GetKind()) {
1718 case HInstruction::kNeg:
1719 DCHECK(opb == nullptr);
1720 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001721 new (global_allocator_) HVecNeg(global_allocator_, opa, type, vector_length_, dex_pc),
1722 new (global_allocator_) HNeg(org_type, opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001723 case HInstruction::kNot:
1724 DCHECK(opb == nullptr);
1725 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001726 new (global_allocator_) HVecNot(global_allocator_, opa, type, vector_length_, dex_pc),
1727 new (global_allocator_) HNot(org_type, opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001728 case HInstruction::kBooleanNot:
1729 DCHECK(opb == nullptr);
1730 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001731 new (global_allocator_) HVecNot(global_allocator_, opa, type, vector_length_, dex_pc),
1732 new (global_allocator_) HBooleanNot(opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001733 case HInstruction::kTypeConversion:
1734 DCHECK(opb == nullptr);
1735 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001736 new (global_allocator_) HVecCnv(global_allocator_, opa, type, vector_length_, dex_pc),
1737 new (global_allocator_) HTypeConversion(org_type, opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001738 case HInstruction::kAdd:
1739 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001740 new (global_allocator_) HVecAdd(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1741 new (global_allocator_) HAdd(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001742 case HInstruction::kSub:
1743 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001744 new (global_allocator_) HVecSub(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1745 new (global_allocator_) HSub(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001746 case HInstruction::kMul:
1747 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001748 new (global_allocator_) HVecMul(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1749 new (global_allocator_) HMul(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001750 case HInstruction::kDiv:
1751 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001752 new (global_allocator_) HVecDiv(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1753 new (global_allocator_) HDiv(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001754 case HInstruction::kAnd:
1755 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001756 new (global_allocator_) HVecAnd(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1757 new (global_allocator_) HAnd(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001758 case HInstruction::kOr:
1759 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001760 new (global_allocator_) HVecOr(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1761 new (global_allocator_) HOr(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001762 case HInstruction::kXor:
1763 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001764 new (global_allocator_) HVecXor(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1765 new (global_allocator_) HXor(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001766 case HInstruction::kShl:
1767 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001768 new (global_allocator_) HVecShl(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1769 new (global_allocator_) HShl(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001770 case HInstruction::kShr:
1771 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001772 new (global_allocator_) HVecShr(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1773 new (global_allocator_) HShr(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001774 case HInstruction::kUShr:
1775 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001776 new (global_allocator_) HVecUShr(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1777 new (global_allocator_) HUShr(org_type, opa, opb, dex_pc));
Aart Bik1f8d51b2018-02-15 10:42:37 -08001778 case HInstruction::kMin:
1779 GENERATE_VEC(
1780 new (global_allocator_) HVecMin(global_allocator_,
1781 opa,
1782 opb,
1783 HVecOperation::ToProperType(type, is_unsigned),
1784 vector_length_,
1785 dex_pc),
1786 new (global_allocator_) HMin(org_type, opa, opb, dex_pc));
1787 case HInstruction::kMax:
1788 GENERATE_VEC(
1789 new (global_allocator_) HVecMax(global_allocator_,
1790 opa,
1791 opb,
1792 HVecOperation::ToProperType(type, is_unsigned),
1793 vector_length_,
1794 dex_pc),
1795 new (global_allocator_) HMax(org_type, opa, opb, dex_pc));
Aart Bik3b2a5952018-03-05 13:55:28 -08001796 case HInstruction::kAbs:
1797 DCHECK(opb == nullptr);
1798 GENERATE_VEC(
1799 new (global_allocator_) HVecAbs(global_allocator_, opa, type, vector_length_, dex_pc),
1800 new (global_allocator_) HAbs(org_type, opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001801 default:
1802 break;
1803 } // switch
1804 CHECK(vector != nullptr) << "Unsupported SIMD operator";
1805 vector_map_->Put(org, vector);
1806}
1807
1808#undef GENERATE_VEC
1809
1810//
Aart Bikf3e61ee2017-04-12 17:09:20 -07001811// Vectorization idioms.
1812//
1813
1814// Method recognizes the following idioms:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001815// rounding halving add (a + b + 1) >> 1 for unsigned/signed operands a, b
1816// truncated halving add (a + b) >> 1 for unsigned/signed operands a, b
Aart Bikf3e61ee2017-04-12 17:09:20 -07001817// Provided that the operands are promoted to a wider form to do the arithmetic and
1818// then cast back to narrower form, the idioms can be mapped into efficient SIMD
1819// implementation that operates directly in narrower form (plus one extra bit).
1820// TODO: current version recognizes implicit byte/short/char widening only;
1821// explicit widening from int to long could be added later.
1822bool HLoopOptimization::VectorizeHalvingAddIdiom(LoopNode* node,
1823 HInstruction* instruction,
1824 bool generate_code,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001825 DataType::Type type,
Aart Bikf3e61ee2017-04-12 17:09:20 -07001826 uint64_t restrictions) {
1827 // Test for top level arithmetic shift right x >> 1 or logical shift right x >>> 1
Aart Bik304c8a52017-05-23 11:01:13 -07001828 // (note whether the sign bit in wider precision is shifted in has no effect
Aart Bikf3e61ee2017-04-12 17:09:20 -07001829 // on the narrow precision computed by the idiom).
Aart Bikf3e61ee2017-04-12 17:09:20 -07001830 if ((instruction->IsShr() ||
1831 instruction->IsUShr()) &&
Aart Bik0148de42017-09-05 09:25:01 -07001832 IsInt64Value(instruction->InputAt(1), 1)) {
Aart Bik5f805002017-05-16 16:42:41 -07001833 // Test for (a + b + c) >> 1 for optional constant c.
1834 HInstruction* a = nullptr;
1835 HInstruction* b = nullptr;
1836 int64_t c = 0;
1837 if (IsAddConst(instruction->InputAt(0), /*out*/ &a, /*out*/ &b, /*out*/ &c)) {
Aart Bik304c8a52017-05-23 11:01:13 -07001838 DCHECK(a != nullptr && b != nullptr);
Aart Bik5f805002017-05-16 16:42:41 -07001839 // Accept c == 1 (rounded) or c == 0 (not rounded).
1840 bool is_rounded = false;
1841 if (c == 1) {
1842 is_rounded = true;
1843 } else if (c != 0) {
1844 return false;
1845 }
1846 // Accept consistent zero or sign extension on operands a and b.
Aart Bikf3e61ee2017-04-12 17:09:20 -07001847 HInstruction* r = nullptr;
1848 HInstruction* s = nullptr;
1849 bool is_unsigned = false;
Aart Bik304c8a52017-05-23 11:01:13 -07001850 if (!IsNarrowerOperands(a, b, type, &r, &s, &is_unsigned)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -07001851 return false;
1852 }
1853 // Deal with vector restrictions.
1854 if ((!is_unsigned && HasVectorRestrictions(restrictions, kNoSignedHAdd)) ||
1855 (!is_rounded && HasVectorRestrictions(restrictions, kNoUnroundedHAdd))) {
1856 return false;
1857 }
1858 // Accept recognized halving add for vectorizable operands. Vectorized code uses the
1859 // shorthand idiomatic operation. Sequential code uses the original scalar expressions.
Aart Bikdbbac8f2017-09-01 13:06:08 -07001860 DCHECK(r != nullptr);
1861 DCHECK(s != nullptr);
Aart Bik304c8a52017-05-23 11:01:13 -07001862 if (generate_code && vector_mode_ != kVector) { // de-idiom
1863 r = instruction->InputAt(0);
1864 s = instruction->InputAt(1);
1865 }
Aart Bikf3e61ee2017-04-12 17:09:20 -07001866 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
1867 VectorizeUse(node, s, generate_code, type, restrictions)) {
1868 if (generate_code) {
1869 if (vector_mode_ == kVector) {
1870 vector_map_->Put(instruction, new (global_allocator_) HVecHalvingAdd(
1871 global_allocator_,
1872 vector_map_->Get(r),
1873 vector_map_->Get(s),
Aart Bik66c158e2018-01-31 12:55:04 -08001874 HVecOperation::ToProperType(type, is_unsigned),
Aart Bikf3e61ee2017-04-12 17:09:20 -07001875 vector_length_,
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001876 is_rounded,
Aart Bik46b6dbc2017-10-03 11:37:37 -07001877 kNoDexPc));
Aart Bik21b85922017-09-06 13:29:16 -07001878 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorizedIdiom);
Aart Bikf3e61ee2017-04-12 17:09:20 -07001879 } else {
Aart Bik304c8a52017-05-23 11:01:13 -07001880 GenerateVecOp(instruction, vector_map_->Get(r), vector_map_->Get(s), type);
Aart Bikf3e61ee2017-04-12 17:09:20 -07001881 }
1882 }
1883 return true;
1884 }
1885 }
1886 }
1887 return false;
1888}
1889
Aart Bikdbbac8f2017-09-01 13:06:08 -07001890// Method recognizes the following idiom:
1891// q += ABS(a - b) for signed operands a, b
1892// Provided that the operands have the same type or are promoted to a wider form.
1893// Since this may involve a vector length change, the idiom is handled by going directly
1894// to a sad-accumulate node (rather than relying combining finer grained nodes later).
1895// TODO: unsigned SAD too?
1896bool HLoopOptimization::VectorizeSADIdiom(LoopNode* node,
1897 HInstruction* instruction,
1898 bool generate_code,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001899 DataType::Type reduction_type,
Aart Bikdbbac8f2017-09-01 13:06:08 -07001900 uint64_t restrictions) {
1901 // Filter integral "q += ABS(a - b);" reduction, where ABS and SUB
1902 // are done in the same precision (either int or long).
1903 if (!instruction->IsAdd() ||
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001904 (reduction_type != DataType::Type::kInt32 && reduction_type != DataType::Type::kInt64)) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001905 return false;
1906 }
1907 HInstruction* q = instruction->InputAt(0);
1908 HInstruction* v = instruction->InputAt(1);
1909 HInstruction* a = nullptr;
1910 HInstruction* b = nullptr;
Aart Bik3b2a5952018-03-05 13:55:28 -08001911 if (v->GetType() == reduction_type && v->IsAbs()) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001912 HInstruction* x = v->InputAt(0);
Aart Bikdf011c32017-09-28 12:53:04 -07001913 if (x->GetType() == reduction_type) {
1914 int64_t c = 0;
1915 if (x->IsSub()) {
1916 a = x->InputAt(0);
1917 b = x->InputAt(1);
1918 } else if (IsAddConst(x, /*out*/ &a, /*out*/ &c)) {
1919 b = graph_->GetConstant(reduction_type, -c); // hidden SUB!
1920 }
Aart Bikdbbac8f2017-09-01 13:06:08 -07001921 }
1922 }
1923 if (a == nullptr || b == nullptr) {
1924 return false;
1925 }
1926 // Accept same-type or consistent sign extension for narrower-type on operands a and b.
1927 // The same-type or narrower operands are called r (a or lower) and s (b or lower).
Aart Bikdf011c32017-09-28 12:53:04 -07001928 // We inspect the operands carefully to pick the most suited type.
Aart Bikdbbac8f2017-09-01 13:06:08 -07001929 HInstruction* r = a;
1930 HInstruction* s = b;
1931 bool is_unsigned = false;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001932 DataType::Type sub_type = a->GetType();
Aart Bikdf011c32017-09-28 12:53:04 -07001933 if (DataType::Size(b->GetType()) < DataType::Size(sub_type)) {
1934 sub_type = b->GetType();
1935 }
1936 if (a->IsTypeConversion() &&
1937 DataType::Size(a->InputAt(0)->GetType()) < DataType::Size(sub_type)) {
1938 sub_type = a->InputAt(0)->GetType();
1939 }
1940 if (b->IsTypeConversion() &&
1941 DataType::Size(b->InputAt(0)->GetType()) < DataType::Size(sub_type)) {
1942 sub_type = b->InputAt(0)->GetType();
Aart Bikdbbac8f2017-09-01 13:06:08 -07001943 }
1944 if (reduction_type != sub_type &&
1945 (!IsNarrowerOperands(a, b, sub_type, &r, &s, &is_unsigned) || is_unsigned)) {
1946 return false;
1947 }
1948 // Try same/narrower type and deal with vector restrictions.
Artem Serov6e9b1372017-10-05 16:48:30 +01001949 if (!TrySetVectorType(sub_type, &restrictions) ||
1950 HasVectorRestrictions(restrictions, kNoSAD) ||
1951 (reduction_type != sub_type && HasVectorRestrictions(restrictions, kNoWideSAD))) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001952 return false;
1953 }
1954 // Accept SAD idiom for vectorizable operands. Vectorized code uses the shorthand
1955 // idiomatic operation. Sequential code uses the original scalar expressions.
1956 DCHECK(r != nullptr);
1957 DCHECK(s != nullptr);
1958 if (generate_code && vector_mode_ != kVector) { // de-idiom
1959 r = s = v->InputAt(0);
1960 }
1961 if (VectorizeUse(node, q, generate_code, sub_type, restrictions) &&
1962 VectorizeUse(node, r, generate_code, sub_type, restrictions) &&
1963 VectorizeUse(node, s, generate_code, sub_type, restrictions)) {
1964 if (generate_code) {
1965 if (vector_mode_ == kVector) {
1966 vector_map_->Put(instruction, new (global_allocator_) HVecSADAccumulate(
1967 global_allocator_,
1968 vector_map_->Get(q),
1969 vector_map_->Get(r),
1970 vector_map_->Get(s),
Aart Bik3b2a5952018-03-05 13:55:28 -08001971 HVecOperation::ToProperType(reduction_type, is_unsigned),
Aart Bik46b6dbc2017-10-03 11:37:37 -07001972 GetOtherVL(reduction_type, sub_type, vector_length_),
1973 kNoDexPc));
Aart Bikdbbac8f2017-09-01 13:06:08 -07001974 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorizedIdiom);
1975 } else {
1976 GenerateVecOp(v, vector_map_->Get(r), nullptr, reduction_type);
1977 GenerateVecOp(instruction, vector_map_->Get(q), vector_map_->Get(v), reduction_type);
1978 }
1979 }
1980 return true;
1981 }
1982 return false;
1983}
1984
Aart Bikf3e61ee2017-04-12 17:09:20 -07001985//
Aart Bik14a68b42017-06-08 14:06:58 -07001986// Vectorization heuristics.
1987//
1988
Aart Bik38a3f212017-10-20 17:02:21 -07001989Alignment HLoopOptimization::ComputeAlignment(HInstruction* offset,
1990 DataType::Type type,
1991 bool is_string_char_at,
1992 uint32_t peeling) {
1993 // Combine the alignment and hidden offset that is guaranteed by
1994 // the Android runtime with a known starting index adjusted as bytes.
1995 int64_t value = 0;
1996 if (IsInt64AndGet(offset, /*out*/ &value)) {
1997 uint32_t start_offset =
1998 HiddenOffset(type, is_string_char_at) + (value + peeling) * DataType::Size(type);
1999 return Alignment(BaseAlignment(), start_offset & (BaseAlignment() - 1u));
2000 }
2001 // Otherwise, the Android runtime guarantees at least natural alignment.
2002 return Alignment(DataType::Size(type), 0);
2003}
2004
2005void HLoopOptimization::SetAlignmentStrategy(uint32_t peeling_votes[],
2006 const ArrayReference* peeling_candidate) {
2007 // Current heuristic: pick the best static loop peeling factor, if any,
2008 // or otherwise use dynamic loop peeling on suggested peeling candidate.
2009 uint32_t max_vote = 0;
2010 for (int32_t i = 0; i < 16; i++) {
2011 if (peeling_votes[i] > max_vote) {
2012 max_vote = peeling_votes[i];
2013 vector_static_peeling_factor_ = i;
2014 }
2015 }
2016 if (max_vote == 0) {
2017 vector_dynamic_peeling_candidate_ = peeling_candidate;
2018 }
2019}
2020
2021uint32_t HLoopOptimization::MaxNumberPeeled() {
2022 if (vector_dynamic_peeling_candidate_ != nullptr) {
2023 return vector_length_ - 1u; // worst-case
2024 }
2025 return vector_static_peeling_factor_; // known exactly
2026}
2027
Aart Bik14a68b42017-06-08 14:06:58 -07002028bool HLoopOptimization::IsVectorizationProfitable(int64_t trip_count) {
Aart Bik38a3f212017-10-20 17:02:21 -07002029 // Current heuristic: non-empty body with sufficient number of iterations (if known).
Aart Bik14a68b42017-06-08 14:06:58 -07002030 // TODO: refine by looking at e.g. operation count, alignment, etc.
Aart Bik38a3f212017-10-20 17:02:21 -07002031 // TODO: trip count is really unsigned entity, provided the guarding test
2032 // is satisfied; deal with this more carefully later
2033 uint32_t max_peel = MaxNumberPeeled();
Aart Bik14a68b42017-06-08 14:06:58 -07002034 if (vector_length_ == 0) {
2035 return false; // nothing found
Aart Bik38a3f212017-10-20 17:02:21 -07002036 } else if (trip_count < 0) {
2037 return false; // guard against non-taken/large
2038 } else if ((0 < trip_count) && (trip_count < (vector_length_ + max_peel))) {
Aart Bik14a68b42017-06-08 14:06:58 -07002039 return false; // insufficient iterations
2040 }
2041 return true;
2042}
2043
Artem Serovf26bb6c2017-09-01 10:59:03 +01002044static constexpr uint32_t ARM64_SIMD_MAXIMUM_UNROLL_FACTOR = 8;
2045static constexpr uint32_t ARM64_SIMD_HEURISTIC_MAX_BODY_SIZE = 50;
2046
Aart Bik14a68b42017-06-08 14:06:58 -07002047uint32_t HLoopOptimization::GetUnrollingFactor(HBasicBlock* block, int64_t trip_count) {
Aart Bik38a3f212017-10-20 17:02:21 -07002048 uint32_t max_peel = MaxNumberPeeled();
Aart Bik14a68b42017-06-08 14:06:58 -07002049 switch (compiler_driver_->GetInstructionSet()) {
Vladimir Marko33bff252017-11-01 14:35:42 +00002050 case InstructionSet::kArm64: {
Aart Bik521b50f2017-09-09 10:44:45 -07002051 // Don't unroll with insufficient iterations.
Artem Serovf26bb6c2017-09-01 10:59:03 +01002052 // TODO: Unroll loops with unknown trip count.
Aart Bik521b50f2017-09-09 10:44:45 -07002053 DCHECK_NE(vector_length_, 0u);
Aart Bik38a3f212017-10-20 17:02:21 -07002054 if (trip_count < (2 * vector_length_ + max_peel)) {
Aart Bik521b50f2017-09-09 10:44:45 -07002055 return kNoUnrollingFactor;
Aart Bik14a68b42017-06-08 14:06:58 -07002056 }
Aart Bik521b50f2017-09-09 10:44:45 -07002057 // Don't unroll for large loop body size.
Artem Serovf26bb6c2017-09-01 10:59:03 +01002058 uint32_t instruction_count = block->GetInstructions().CountSize();
Aart Bik521b50f2017-09-09 10:44:45 -07002059 if (instruction_count >= ARM64_SIMD_HEURISTIC_MAX_BODY_SIZE) {
2060 return kNoUnrollingFactor;
2061 }
Artem Serovf26bb6c2017-09-01 10:59:03 +01002062 // Find a beneficial unroll factor with the following restrictions:
2063 // - At least one iteration of the transformed loop should be executed.
2064 // - The loop body shouldn't be "too big" (heuristic).
2065 uint32_t uf1 = ARM64_SIMD_HEURISTIC_MAX_BODY_SIZE / instruction_count;
Aart Bik38a3f212017-10-20 17:02:21 -07002066 uint32_t uf2 = (trip_count - max_peel) / vector_length_;
Artem Serovf26bb6c2017-09-01 10:59:03 +01002067 uint32_t unroll_factor =
2068 TruncToPowerOfTwo(std::min({uf1, uf2, ARM64_SIMD_MAXIMUM_UNROLL_FACTOR}));
2069 DCHECK_GE(unroll_factor, 1u);
Artem Serovf26bb6c2017-09-01 10:59:03 +01002070 return unroll_factor;
Aart Bik14a68b42017-06-08 14:06:58 -07002071 }
Vladimir Marko33bff252017-11-01 14:35:42 +00002072 case InstructionSet::kX86:
2073 case InstructionSet::kX86_64:
Aart Bik14a68b42017-06-08 14:06:58 -07002074 default:
Aart Bik521b50f2017-09-09 10:44:45 -07002075 return kNoUnrollingFactor;
Aart Bik14a68b42017-06-08 14:06:58 -07002076 }
2077}
2078
2079//
Aart Bikf8f5a162017-02-06 15:35:29 -08002080// Helpers.
2081//
2082
2083bool HLoopOptimization::TrySetPhiInduction(HPhi* phi, bool restrict_uses) {
Aart Bikb29f6842017-07-28 15:58:41 -07002084 // Start with empty phi induction.
2085 iset_->clear();
2086
Nicolas Geoffrayf57c1ae2017-06-28 17:40:18 +01002087 // Special case Phis that have equivalent in a debuggable setup. Our graph checker isn't
2088 // smart enough to follow strongly connected components (and it's probably not worth
2089 // it to make it so). See b/33775412.
2090 if (graph_->IsDebuggable() && phi->HasEquivalentPhi()) {
2091 return false;
2092 }
Aart Bikb29f6842017-07-28 15:58:41 -07002093
2094 // Lookup phi induction cycle.
Aart Bikcc42be02016-10-20 16:14:16 -07002095 ArenaSet<HInstruction*>* set = induction_range_.LookupCycle(phi);
2096 if (set != nullptr) {
2097 for (HInstruction* i : *set) {
Aart Bike3dedc52016-11-02 17:50:27 -07002098 // Check that, other than instructions that are no longer in the graph (removed earlier)
Aart Bikf8f5a162017-02-06 15:35:29 -08002099 // each instruction is removable and, when restrict uses are requested, other than for phi,
2100 // all uses are contained within the cycle.
Aart Bike3dedc52016-11-02 17:50:27 -07002101 if (!i->IsInBlock()) {
2102 continue;
2103 } else if (!i->IsRemovable()) {
2104 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08002105 } else if (i != phi && restrict_uses) {
Aart Bikb29f6842017-07-28 15:58:41 -07002106 // Deal with regular uses.
Aart Bikcc42be02016-10-20 16:14:16 -07002107 for (const HUseListNode<HInstruction*>& use : i->GetUses()) {
2108 if (set->find(use.GetUser()) == set->end()) {
2109 return false;
2110 }
2111 }
2112 }
Aart Bike3dedc52016-11-02 17:50:27 -07002113 iset_->insert(i); // copy
Aart Bikcc42be02016-10-20 16:14:16 -07002114 }
Aart Bikcc42be02016-10-20 16:14:16 -07002115 return true;
2116 }
2117 return false;
2118}
2119
Aart Bikb29f6842017-07-28 15:58:41 -07002120bool HLoopOptimization::TrySetPhiReduction(HPhi* phi) {
Aart Bikcc42be02016-10-20 16:14:16 -07002121 DCHECK(iset_->empty());
Aart Bikb29f6842017-07-28 15:58:41 -07002122 // Only unclassified phi cycles are candidates for reductions.
2123 if (induction_range_.IsClassified(phi)) {
2124 return false;
2125 }
2126 // Accept operations like x = x + .., provided that the phi and the reduction are
2127 // used exactly once inside the loop, and by each other.
2128 HInputsRef inputs = phi->GetInputs();
2129 if (inputs.size() == 2) {
2130 HInstruction* reduction = inputs[1];
2131 if (HasReductionFormat(reduction, phi)) {
2132 HLoopInformation* loop_info = phi->GetBlock()->GetLoopInformation();
Aart Bik38a3f212017-10-20 17:02:21 -07002133 uint32_t use_count = 0;
Aart Bikb29f6842017-07-28 15:58:41 -07002134 bool single_use_inside_loop =
2135 // Reduction update only used by phi.
2136 reduction->GetUses().HasExactlyOneElement() &&
2137 !reduction->HasEnvironmentUses() &&
2138 // Reduction update is only use of phi inside the loop.
2139 IsOnlyUsedAfterLoop(loop_info, phi, /*collect_loop_uses*/ true, &use_count) &&
2140 iset_->size() == 1;
2141 iset_->clear(); // leave the way you found it
2142 if (single_use_inside_loop) {
2143 // Link reduction back, and start recording feed value.
2144 reductions_->Put(reduction, phi);
2145 reductions_->Put(phi, phi->InputAt(0));
2146 return true;
2147 }
2148 }
2149 }
2150 return false;
2151}
2152
2153bool HLoopOptimization::TrySetSimpleLoopHeader(HBasicBlock* block, /*out*/ HPhi** main_phi) {
2154 // Start with empty phi induction and reductions.
2155 iset_->clear();
2156 reductions_->clear();
2157
2158 // Scan the phis to find the following (the induction structure has already
2159 // been optimized, so we don't need to worry about trivial cases):
2160 // (1) optional reductions in loop,
2161 // (2) the main induction, used in loop control.
2162 HPhi* phi = nullptr;
2163 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
2164 if (TrySetPhiReduction(it.Current()->AsPhi())) {
2165 continue;
2166 } else if (phi == nullptr) {
2167 // Found the first candidate for main induction.
2168 phi = it.Current()->AsPhi();
2169 } else {
2170 return false;
2171 }
2172 }
2173
2174 // Then test for a typical loopheader:
2175 // s: SuspendCheck
2176 // c: Condition(phi, bound)
2177 // i: If(c)
2178 if (phi != nullptr && TrySetPhiInduction(phi, /*restrict_uses*/ false)) {
Aart Bikcc42be02016-10-20 16:14:16 -07002179 HInstruction* s = block->GetFirstInstruction();
2180 if (s != nullptr && s->IsSuspendCheck()) {
2181 HInstruction* c = s->GetNext();
Aart Bikd86c0852017-04-14 12:00:15 -07002182 if (c != nullptr &&
2183 c->IsCondition() &&
2184 c->GetUses().HasExactlyOneElement() && // only used for termination
2185 !c->HasEnvironmentUses()) { // unlikely, but not impossible
Aart Bikcc42be02016-10-20 16:14:16 -07002186 HInstruction* i = c->GetNext();
2187 if (i != nullptr && i->IsIf() && i->InputAt(0) == c) {
2188 iset_->insert(c);
2189 iset_->insert(s);
Aart Bikb29f6842017-07-28 15:58:41 -07002190 *main_phi = phi;
Aart Bikcc42be02016-10-20 16:14:16 -07002191 return true;
2192 }
2193 }
2194 }
2195 }
2196 return false;
2197}
2198
2199bool HLoopOptimization::IsEmptyBody(HBasicBlock* block) {
Aart Bikf8f5a162017-02-06 15:35:29 -08002200 if (!block->GetPhis().IsEmpty()) {
2201 return false;
2202 }
2203 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
2204 HInstruction* instruction = it.Current();
2205 if (!instruction->IsGoto() && iset_->find(instruction) == iset_->end()) {
2206 return false;
Aart Bikcc42be02016-10-20 16:14:16 -07002207 }
Aart Bikf8f5a162017-02-06 15:35:29 -08002208 }
2209 return true;
2210}
2211
2212bool HLoopOptimization::IsUsedOutsideLoop(HLoopInformation* loop_info,
2213 HInstruction* instruction) {
Aart Bikb29f6842017-07-28 15:58:41 -07002214 // Deal with regular uses.
Aart Bikf8f5a162017-02-06 15:35:29 -08002215 for (const HUseListNode<HInstruction*>& use : instruction->GetUses()) {
2216 if (use.GetUser()->GetBlock()->GetLoopInformation() != loop_info) {
2217 return true;
2218 }
Aart Bikcc42be02016-10-20 16:14:16 -07002219 }
2220 return false;
2221}
2222
Aart Bik482095d2016-10-10 15:39:10 -07002223bool HLoopOptimization::IsOnlyUsedAfterLoop(HLoopInformation* loop_info,
Aart Bik8c4a8542016-10-06 11:36:57 -07002224 HInstruction* instruction,
Aart Bik6b69e0a2017-01-11 10:20:43 -08002225 bool collect_loop_uses,
Aart Bik38a3f212017-10-20 17:02:21 -07002226 /*out*/ uint32_t* use_count) {
Aart Bikb29f6842017-07-28 15:58:41 -07002227 // Deal with regular uses.
Aart Bik8c4a8542016-10-06 11:36:57 -07002228 for (const HUseListNode<HInstruction*>& use : instruction->GetUses()) {
2229 HInstruction* user = use.GetUser();
2230 if (iset_->find(user) == iset_->end()) { // not excluded?
2231 HLoopInformation* other_loop_info = user->GetBlock()->GetLoopInformation();
Aart Bik482095d2016-10-10 15:39:10 -07002232 if (other_loop_info != nullptr && other_loop_info->IsIn(*loop_info)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -08002233 // If collect_loop_uses is set, simply keep adding those uses to the set.
2234 // Otherwise, reject uses inside the loop that were not already in the set.
2235 if (collect_loop_uses) {
2236 iset_->insert(user);
2237 continue;
2238 }
Aart Bik8c4a8542016-10-06 11:36:57 -07002239 return false;
2240 }
2241 ++*use_count;
2242 }
2243 }
2244 return true;
2245}
2246
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002247bool HLoopOptimization::TryReplaceWithLastValue(HLoopInformation* loop_info,
2248 HInstruction* instruction,
2249 HBasicBlock* block) {
2250 // Try to replace outside uses with the last value.
Aart Bik807868e2016-11-03 17:51:43 -07002251 if (induction_range_.CanGenerateLastValue(instruction)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -08002252 HInstruction* replacement = induction_range_.GenerateLastValue(instruction, graph_, block);
Aart Bikb29f6842017-07-28 15:58:41 -07002253 // Deal with regular uses.
Aart Bik6b69e0a2017-01-11 10:20:43 -08002254 const HUseList<HInstruction*>& uses = instruction->GetUses();
2255 for (auto it = uses.begin(), end = uses.end(); it != end;) {
2256 HInstruction* user = it->GetUser();
2257 size_t index = it->GetIndex();
2258 ++it; // increment before replacing
2259 if (iset_->find(user) == iset_->end()) { // not excluded?
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002260 if (kIsDebugBuild) {
2261 // We have checked earlier in 'IsOnlyUsedAfterLoop' that the use is after the loop.
2262 HLoopInformation* other_loop_info = user->GetBlock()->GetLoopInformation();
2263 CHECK(other_loop_info == nullptr || !other_loop_info->IsIn(*loop_info));
2264 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08002265 user->ReplaceInput(replacement, index);
2266 induction_range_.Replace(user, instruction, replacement); // update induction
2267 }
2268 }
Aart Bikb29f6842017-07-28 15:58:41 -07002269 // Deal with environment uses.
Aart Bik6b69e0a2017-01-11 10:20:43 -08002270 const HUseList<HEnvironment*>& env_uses = instruction->GetEnvUses();
2271 for (auto it = env_uses.begin(), end = env_uses.end(); it != end;) {
2272 HEnvironment* user = it->GetUser();
2273 size_t index = it->GetIndex();
2274 ++it; // increment before replacing
2275 if (iset_->find(user->GetHolder()) == iset_->end()) { // not excluded?
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002276 // Only update environment uses after the loop.
Aart Bik14a68b42017-06-08 14:06:58 -07002277 HLoopInformation* other_loop_info = user->GetHolder()->GetBlock()->GetLoopInformation();
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002278 if (other_loop_info == nullptr || !other_loop_info->IsIn(*loop_info)) {
2279 user->RemoveAsUserOfInput(index);
2280 user->SetRawEnvAt(index, replacement);
2281 replacement->AddEnvUseAt(user, index);
2282 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08002283 }
2284 }
Aart Bik807868e2016-11-03 17:51:43 -07002285 return true;
Aart Bik8c4a8542016-10-06 11:36:57 -07002286 }
Aart Bik807868e2016-11-03 17:51:43 -07002287 return false;
Aart Bik8c4a8542016-10-06 11:36:57 -07002288}
2289
Aart Bikf8f5a162017-02-06 15:35:29 -08002290bool HLoopOptimization::TryAssignLastValue(HLoopInformation* loop_info,
2291 HInstruction* instruction,
2292 HBasicBlock* block,
2293 bool collect_loop_uses) {
2294 // Assigning the last value is always successful if there are no uses.
2295 // Otherwise, it succeeds in a no early-exit loop by generating the
2296 // proper last value assignment.
Aart Bik38a3f212017-10-20 17:02:21 -07002297 uint32_t use_count = 0;
Aart Bikf8f5a162017-02-06 15:35:29 -08002298 return IsOnlyUsedAfterLoop(loop_info, instruction, collect_loop_uses, &use_count) &&
2299 (use_count == 0 ||
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002300 (!IsEarlyExit(loop_info) && TryReplaceWithLastValue(loop_info, instruction, block)));
Aart Bikf8f5a162017-02-06 15:35:29 -08002301}
2302
Aart Bik6b69e0a2017-01-11 10:20:43 -08002303void HLoopOptimization::RemoveDeadInstructions(const HInstructionList& list) {
2304 for (HBackwardInstructionIterator i(list); !i.Done(); i.Advance()) {
2305 HInstruction* instruction = i.Current();
2306 if (instruction->IsDeadAndRemovable()) {
2307 simplified_ = true;
2308 instruction->GetBlock()->RemoveInstructionOrPhi(instruction);
2309 }
2310 }
2311}
2312
Aart Bik14a68b42017-06-08 14:06:58 -07002313bool HLoopOptimization::CanRemoveCycle() {
2314 for (HInstruction* i : *iset_) {
2315 // We can never remove instructions that have environment
2316 // uses when we compile 'debuggable'.
2317 if (i->HasEnvironmentUses() && graph_->IsDebuggable()) {
2318 return false;
2319 }
2320 // A deoptimization should never have an environment input removed.
2321 for (const HUseListNode<HEnvironment*>& use : i->GetEnvUses()) {
2322 if (use.GetUser()->GetHolder()->IsDeoptimize()) {
2323 return false;
2324 }
2325 }
2326 }
2327 return true;
2328}
2329
Aart Bik281c6812016-08-26 11:31:48 -07002330} // namespace art