blob: 6f8743bd531fd278aa73ba551d97e776c8b24046 [file] [log] [blame]
Aart Bik281c6812016-08-26 11:31:48 -07001/*
2 * Copyright (C) 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "loop_optimization.h"
18
Aart Bikf8f5a162017-02-06 15:35:29 -080019#include "arch/arm/instruction_set_features_arm.h"
20#include "arch/arm64/instruction_set_features_arm64.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070021#include "arch/instruction_set.h"
Aart Bikf8f5a162017-02-06 15:35:29 -080022#include "arch/mips/instruction_set_features_mips.h"
23#include "arch/mips64/instruction_set_features_mips64.h"
24#include "arch/x86/instruction_set_features_x86.h"
25#include "arch/x86_64/instruction_set_features_x86_64.h"
Aart Bik92685a82017-03-06 11:13:43 -080026#include "driver/compiler_driver.h"
Aart Bik96202302016-10-04 17:33:56 -070027#include "linear_order.h"
Aart Bik281c6812016-08-26 11:31:48 -070028
29namespace art {
30
Aart Bikf8f5a162017-02-06 15:35:29 -080031// Enables vectorization (SIMDization) in the loop optimizer.
32static constexpr bool kEnableVectorization = true;
33
Aart Bik14a68b42017-06-08 14:06:58 -070034// All current SIMD targets want 16-byte alignment.
35static constexpr size_t kAlignedBase = 16;
36
Aart Bik521b50f2017-09-09 10:44:45 -070037// No loop unrolling factor (just one copy of the loop-body).
38static constexpr uint32_t kNoUnrollingFactor = 1;
39
Aart Bik9abf8942016-10-14 09:49:42 -070040// Remove the instruction from the graph. A bit more elaborate than the usual
41// instruction removal, since there may be a cycle in the use structure.
Aart Bik281c6812016-08-26 11:31:48 -070042static void RemoveFromCycle(HInstruction* instruction) {
Aart Bik281c6812016-08-26 11:31:48 -070043 instruction->RemoveAsUserOfAllInputs();
44 instruction->RemoveEnvironmentUsers();
45 instruction->GetBlock()->RemoveInstructionOrPhi(instruction, /*ensure_safety=*/ false);
Artem Serov21c7e6f2017-07-27 16:04:42 +010046 RemoveEnvironmentUses(instruction);
47 ResetEnvironmentInputRecords(instruction);
Aart Bik281c6812016-08-26 11:31:48 -070048}
49
Aart Bik807868e2016-11-03 17:51:43 -070050// Detect a goto block and sets succ to the single successor.
Aart Bike3dedc52016-11-02 17:50:27 -070051static bool IsGotoBlock(HBasicBlock* block, /*out*/ HBasicBlock** succ) {
52 if (block->GetPredecessors().size() == 1 &&
53 block->GetSuccessors().size() == 1 &&
54 block->IsSingleGoto()) {
55 *succ = block->GetSingleSuccessor();
56 return true;
57 }
58 return false;
59}
60
Aart Bik807868e2016-11-03 17:51:43 -070061// Detect an early exit loop.
62static bool IsEarlyExit(HLoopInformation* loop_info) {
63 HBlocksInLoopReversePostOrderIterator it_loop(*loop_info);
64 for (it_loop.Advance(); !it_loop.Done(); it_loop.Advance()) {
65 for (HBasicBlock* successor : it_loop.Current()->GetSuccessors()) {
66 if (!loop_info->Contains(*successor)) {
67 return true;
68 }
69 }
70 }
71 return false;
72}
73
Aart Bikdbbac8f2017-09-01 13:06:08 -070074// Detect a sign extension in instruction from the given type. The to64 parameter
75// denotes if result is long, and thus sign extension from int can be included.
76// Returns the promoted operand on success.
Aart Bikf3e61ee2017-04-12 17:09:20 -070077static bool IsSignExtensionAndGet(HInstruction* instruction,
78 Primitive::Type type,
Aart Bikdbbac8f2017-09-01 13:06:08 -070079 /*out*/ HInstruction** operand,
80 bool to64 = false) {
Aart Bikf3e61ee2017-04-12 17:09:20 -070081 // Accept any already wider constant that would be handled properly by sign
82 // extension when represented in the *width* of the given narrower data type
83 // (the fact that char normally zero extends does not matter here).
84 int64_t value = 0;
Aart Bik50e20d52017-05-05 14:07:29 -070085 if (IsInt64AndGet(instruction, /*out*/ &value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -070086 switch (type) {
87 case Primitive::kPrimByte:
Aart Bikdbbac8f2017-09-01 13:06:08 -070088 if (IsInt<8>(value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -070089 *operand = instruction;
90 return true;
91 }
92 return false;
93 case Primitive::kPrimChar:
94 case Primitive::kPrimShort:
Aart Bikdbbac8f2017-09-01 13:06:08 -070095 if (IsInt<16>(value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -070096 *operand = instruction;
97 return true;
98 }
99 return false;
Aart Bikdbbac8f2017-09-01 13:06:08 -0700100 case Primitive::kPrimInt:
101 if (IsInt<32>(value)) {
102 *operand = instruction;
103 return to64;
104 }
105 return false;
Aart Bikf3e61ee2017-04-12 17:09:20 -0700106 default:
107 return false;
108 }
109 }
110 // An implicit widening conversion of a signed integer to an integral type sign-extends
111 // the two's-complement representation of the integer value to fill the wider format.
112 if (instruction->GetType() == type && (instruction->IsArrayGet() ||
113 instruction->IsStaticFieldGet() ||
114 instruction->IsInstanceFieldGet())) {
115 switch (type) {
116 case Primitive::kPrimByte:
117 case Primitive::kPrimShort:
118 *operand = instruction;
119 return true;
Aart Bikdbbac8f2017-09-01 13:06:08 -0700120 case Primitive::kPrimInt:
121 *operand = instruction;
122 return to64;
Aart Bikf3e61ee2017-04-12 17:09:20 -0700123 default:
124 return false;
125 }
126 }
Aart Bikdbbac8f2017-09-01 13:06:08 -0700127 // Explicit type conversion to long.
128 if (instruction->IsTypeConversion() && instruction->GetType() == Primitive::kPrimLong) {
129 return IsSignExtensionAndGet(instruction->InputAt(0), type, /*out*/ operand, /*to64*/ true);
130 }
Aart Bikf3e61ee2017-04-12 17:09:20 -0700131 return false;
132}
133
Aart Bikdbbac8f2017-09-01 13:06:08 -0700134// Detect a zero extension in instruction from the given type. The to64 parameter
135// denotes if result is long, and thus zero extension from int can be included.
136// Returns the promoted operand on success.
Aart Bikf3e61ee2017-04-12 17:09:20 -0700137static bool IsZeroExtensionAndGet(HInstruction* instruction,
138 Primitive::Type type,
Aart Bikdbbac8f2017-09-01 13:06:08 -0700139 /*out*/ HInstruction** operand,
140 bool to64 = false) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700141 // Accept any already wider constant that would be handled properly by zero
142 // extension when represented in the *width* of the given narrower data type
Aart Bikdbbac8f2017-09-01 13:06:08 -0700143 // (the fact that byte/short/int normally sign extend does not matter here).
Aart Bikf3e61ee2017-04-12 17:09:20 -0700144 int64_t value = 0;
Aart Bik50e20d52017-05-05 14:07:29 -0700145 if (IsInt64AndGet(instruction, /*out*/ &value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700146 switch (type) {
147 case Primitive::kPrimByte:
Aart Bikdbbac8f2017-09-01 13:06:08 -0700148 if (IsUint<8>(value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700149 *operand = instruction;
150 return true;
151 }
152 return false;
153 case Primitive::kPrimChar:
154 case Primitive::kPrimShort:
Aart Bikdbbac8f2017-09-01 13:06:08 -0700155 if (IsUint<16>(value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700156 *operand = instruction;
157 return true;
158 }
159 return false;
Aart Bikdbbac8f2017-09-01 13:06:08 -0700160 case Primitive::kPrimInt:
161 if (IsUint<32>(value)) {
162 *operand = instruction;
163 return to64;
164 }
165 return false;
Aart Bikf3e61ee2017-04-12 17:09:20 -0700166 default:
167 return false;
168 }
169 }
170 // An implicit widening conversion of a char to an integral type zero-extends
171 // the representation of the char value to fill the wider format.
172 if (instruction->GetType() == type && (instruction->IsArrayGet() ||
173 instruction->IsStaticFieldGet() ||
174 instruction->IsInstanceFieldGet())) {
175 if (type == Primitive::kPrimChar) {
176 *operand = instruction;
177 return true;
178 }
179 }
180 // A sign (or zero) extension followed by an explicit removal of just the
181 // higher sign bits is equivalent to a zero extension of the underlying operand.
182 if (instruction->IsAnd()) {
183 int64_t mask = 0;
184 HInstruction* a = instruction->InputAt(0);
185 HInstruction* b = instruction->InputAt(1);
186 // In (a & b) find (mask & b) or (a & mask) with sign or zero extension on the non-mask.
187 if ((IsInt64AndGet(a, /*out*/ &mask) && (IsSignExtensionAndGet(b, type, /*out*/ operand) ||
188 IsZeroExtensionAndGet(b, type, /*out*/ operand))) ||
189 (IsInt64AndGet(b, /*out*/ &mask) && (IsSignExtensionAndGet(a, type, /*out*/ operand) ||
190 IsZeroExtensionAndGet(a, type, /*out*/ operand)))) {
191 switch ((*operand)->GetType()) {
Aart Bikdbbac8f2017-09-01 13:06:08 -0700192 case Primitive::kPrimByte:
193 return mask == std::numeric_limits<uint8_t>::max();
Aart Bikf3e61ee2017-04-12 17:09:20 -0700194 case Primitive::kPrimChar:
Aart Bikdbbac8f2017-09-01 13:06:08 -0700195 case Primitive::kPrimShort:
196 return mask == std::numeric_limits<uint16_t>::max();
197 case Primitive::kPrimInt:
198 return mask == std::numeric_limits<uint32_t>::max() && to64;
Aart Bikf3e61ee2017-04-12 17:09:20 -0700199 default: return false;
200 }
201 }
202 }
Aart Bikdbbac8f2017-09-01 13:06:08 -0700203 // Explicit type conversion to long.
204 if (instruction->IsTypeConversion() && instruction->GetType() == Primitive::kPrimLong) {
205 return IsZeroExtensionAndGet(instruction->InputAt(0), type, /*out*/ operand, /*to64*/ true);
206 }
Aart Bikf3e61ee2017-04-12 17:09:20 -0700207 return false;
208}
209
Aart Bik304c8a52017-05-23 11:01:13 -0700210// Detect situations with same-extension narrower operands.
211// Returns true on success and sets is_unsigned accordingly.
212static bool IsNarrowerOperands(HInstruction* a,
213 HInstruction* b,
214 Primitive::Type type,
215 /*out*/ HInstruction** r,
216 /*out*/ HInstruction** s,
217 /*out*/ bool* is_unsigned) {
218 if (IsSignExtensionAndGet(a, type, r) && IsSignExtensionAndGet(b, type, s)) {
219 *is_unsigned = false;
220 return true;
221 } else if (IsZeroExtensionAndGet(a, type, r) && IsZeroExtensionAndGet(b, type, s)) {
222 *is_unsigned = true;
223 return true;
224 }
225 return false;
226}
227
228// As above, single operand.
229static bool IsNarrowerOperand(HInstruction* a,
230 Primitive::Type type,
231 /*out*/ HInstruction** r,
232 /*out*/ bool* is_unsigned) {
233 if (IsSignExtensionAndGet(a, type, r)) {
234 *is_unsigned = false;
235 return true;
236 } else if (IsZeroExtensionAndGet(a, type, r)) {
237 *is_unsigned = true;
238 return true;
239 }
240 return false;
241}
242
Aart Bikdbbac8f2017-09-01 13:06:08 -0700243// Compute relative vector length based on type difference.
244static size_t GetOtherVL(Primitive::Type other_type, Primitive::Type vector_type, size_t vl) {
245 switch (other_type) {
246 case Primitive::kPrimBoolean:
247 case Primitive::kPrimByte:
248 switch (vector_type) {
249 case Primitive::kPrimBoolean:
250 case Primitive::kPrimByte: return vl;
251 default: break;
252 }
253 return vl;
254 case Primitive::kPrimChar:
255 case Primitive::kPrimShort:
256 switch (vector_type) {
257 case Primitive::kPrimBoolean:
258 case Primitive::kPrimByte: return vl >> 1;
259 case Primitive::kPrimChar:
260 case Primitive::kPrimShort: return vl;
261 default: break;
262 }
263 break;
264 case Primitive::kPrimInt:
265 switch (vector_type) {
266 case Primitive::kPrimBoolean:
267 case Primitive::kPrimByte: return vl >> 2;
268 case Primitive::kPrimChar:
269 case Primitive::kPrimShort: return vl >> 1;
270 case Primitive::kPrimInt: return vl;
271 default: break;
272 }
273 break;
274 case Primitive::kPrimLong:
275 switch (vector_type) {
276 case Primitive::kPrimBoolean:
277 case Primitive::kPrimByte: return vl >> 3;
278 case Primitive::kPrimChar:
279 case Primitive::kPrimShort: return vl >> 2;
280 case Primitive::kPrimInt: return vl >> 1;
281 case Primitive::kPrimLong: return vl;
282 default: break;
283 }
284 break;
285 default:
286 break;
287 }
288 LOG(FATAL) << "Unsupported idiom conversion";
289 UNREACHABLE();
290}
291
Aart Bik5f805002017-05-16 16:42:41 -0700292// Detect up to two instructions a and b, and an acccumulated constant c.
293static bool IsAddConstHelper(HInstruction* instruction,
294 /*out*/ HInstruction** a,
295 /*out*/ HInstruction** b,
296 /*out*/ int64_t* c,
297 int32_t depth) {
298 static constexpr int32_t kMaxDepth = 8; // don't search too deep
299 int64_t value = 0;
300 if (IsInt64AndGet(instruction, &value)) {
301 *c += value;
302 return true;
303 } else if (instruction->IsAdd() && depth <= kMaxDepth) {
304 return IsAddConstHelper(instruction->InputAt(0), a, b, c, depth + 1) &&
305 IsAddConstHelper(instruction->InputAt(1), a, b, c, depth + 1);
306 } else if (*a == nullptr) {
307 *a = instruction;
308 return true;
309 } else if (*b == nullptr) {
310 *b = instruction;
311 return true;
312 }
313 return false; // too many non-const operands
314}
315
316// Detect a + b + c for an optional constant c.
317static bool IsAddConst(HInstruction* instruction,
318 /*out*/ HInstruction** a,
319 /*out*/ HInstruction** b,
320 /*out*/ int64_t* c) {
321 if (instruction->IsAdd()) {
322 // Try to find a + b and accumulated c.
323 if (IsAddConstHelper(instruction->InputAt(0), a, b, c, /*depth*/ 0) &&
324 IsAddConstHelper(instruction->InputAt(1), a, b, c, /*depth*/ 0) &&
325 *b != nullptr) {
326 return true;
327 }
328 // Found a + b.
329 *a = instruction->InputAt(0);
330 *b = instruction->InputAt(1);
331 *c = 0;
332 return true;
333 }
334 return false;
335}
336
Aart Bikb29f6842017-07-28 15:58:41 -0700337// Detect reductions of the following forms,
Aart Bikb29f6842017-07-28 15:58:41 -0700338// x = x_phi + ..
339// x = x_phi - ..
340// x = max(x_phi, ..)
341// x = min(x_phi, ..)
342static bool HasReductionFormat(HInstruction* reduction, HInstruction* phi) {
343 if (reduction->IsAdd()) {
Aart Bikdbbac8f2017-09-01 13:06:08 -0700344 return (reduction->InputAt(0) == phi && reduction->InputAt(1) != phi) ||
345 (reduction->InputAt(0) != phi && reduction->InputAt(1) == phi);
Aart Bikb29f6842017-07-28 15:58:41 -0700346 } else if (reduction->IsSub()) {
Aart Bikdbbac8f2017-09-01 13:06:08 -0700347 return (reduction->InputAt(0) == phi && reduction->InputAt(1) != phi);
Aart Bikb29f6842017-07-28 15:58:41 -0700348 } else if (reduction->IsInvokeStaticOrDirect()) {
349 switch (reduction->AsInvokeStaticOrDirect()->GetIntrinsic()) {
350 case Intrinsics::kMathMinIntInt:
351 case Intrinsics::kMathMinLongLong:
352 case Intrinsics::kMathMinFloatFloat:
353 case Intrinsics::kMathMinDoubleDouble:
354 case Intrinsics::kMathMaxIntInt:
355 case Intrinsics::kMathMaxLongLong:
356 case Intrinsics::kMathMaxFloatFloat:
357 case Intrinsics::kMathMaxDoubleDouble:
Aart Bikdbbac8f2017-09-01 13:06:08 -0700358 return (reduction->InputAt(0) == phi && reduction->InputAt(1) != phi) ||
359 (reduction->InputAt(0) != phi && reduction->InputAt(1) == phi);
Aart Bikb29f6842017-07-28 15:58:41 -0700360 default:
361 return false;
362 }
363 }
364 return false;
365}
366
Aart Bikdbbac8f2017-09-01 13:06:08 -0700367// Translates vector operation to reduction kind.
368static HVecReduce::ReductionKind GetReductionKind(HVecOperation* reduction) {
369 if (reduction->IsVecAdd() || reduction->IsVecSub() || reduction->IsVecSADAccumulate()) {
Aart Bik0148de42017-09-05 09:25:01 -0700370 return HVecReduce::kSum;
371 } else if (reduction->IsVecMin()) {
372 return HVecReduce::kMin;
373 } else if (reduction->IsVecMax()) {
374 return HVecReduce::kMax;
375 }
376 LOG(FATAL) << "Unsupported SIMD reduction";
377 UNREACHABLE();
378}
379
Aart Bikf8f5a162017-02-06 15:35:29 -0800380// Test vector restrictions.
381static bool HasVectorRestrictions(uint64_t restrictions, uint64_t tested) {
382 return (restrictions & tested) != 0;
383}
384
Aart Bikf3e61ee2017-04-12 17:09:20 -0700385// Insert an instruction.
Aart Bikf8f5a162017-02-06 15:35:29 -0800386static HInstruction* Insert(HBasicBlock* block, HInstruction* instruction) {
387 DCHECK(block != nullptr);
388 DCHECK(instruction != nullptr);
389 block->InsertInstructionBefore(instruction, block->GetLastInstruction());
390 return instruction;
391}
392
Artem Serov21c7e6f2017-07-27 16:04:42 +0100393// Check that instructions from the induction sets are fully removed: have no uses
394// and no other instructions use them.
395static bool CheckInductionSetFullyRemoved(ArenaSet<HInstruction*>* iset) {
396 for (HInstruction* instr : *iset) {
397 if (instr->GetBlock() != nullptr ||
398 !instr->GetUses().empty() ||
399 !instr->GetEnvUses().empty() ||
400 HasEnvironmentUsedByOthers(instr)) {
401 return false;
402 }
403 }
Artem Serov21c7e6f2017-07-27 16:04:42 +0100404 return true;
405}
406
Aart Bik281c6812016-08-26 11:31:48 -0700407//
Aart Bikb29f6842017-07-28 15:58:41 -0700408// Public methods.
Aart Bik281c6812016-08-26 11:31:48 -0700409//
410
411HLoopOptimization::HLoopOptimization(HGraph* graph,
Aart Bik92685a82017-03-06 11:13:43 -0800412 CompilerDriver* compiler_driver,
Aart Bikb92cc332017-09-06 15:53:17 -0700413 HInductionVarAnalysis* induction_analysis,
414 OptimizingCompilerStats* stats)
415 : HOptimization(graph, kLoopOptimizationPassName, stats),
Aart Bik92685a82017-03-06 11:13:43 -0800416 compiler_driver_(compiler_driver),
Aart Bik281c6812016-08-26 11:31:48 -0700417 induction_range_(induction_analysis),
Aart Bik96202302016-10-04 17:33:56 -0700418 loop_allocator_(nullptr),
Aart Bikf8f5a162017-02-06 15:35:29 -0800419 global_allocator_(graph_->GetArena()),
Aart Bik281c6812016-08-26 11:31:48 -0700420 top_loop_(nullptr),
Aart Bik8c4a8542016-10-06 11:36:57 -0700421 last_loop_(nullptr),
Aart Bik482095d2016-10-10 15:39:10 -0700422 iset_(nullptr),
Aart Bikb29f6842017-07-28 15:58:41 -0700423 reductions_(nullptr),
Aart Bikf8f5a162017-02-06 15:35:29 -0800424 simplified_(false),
425 vector_length_(0),
426 vector_refs_(nullptr),
Aart Bik14a68b42017-06-08 14:06:58 -0700427 vector_peeling_candidate_(nullptr),
428 vector_runtime_test_a_(nullptr),
429 vector_runtime_test_b_(nullptr),
Aart Bik0148de42017-09-05 09:25:01 -0700430 vector_map_(nullptr),
431 vector_permanent_map_(nullptr) {
Aart Bik281c6812016-08-26 11:31:48 -0700432}
433
434void HLoopOptimization::Run() {
Mingyao Yang01b47b02017-02-03 12:09:57 -0800435 // Skip if there is no loop or the graph has try-catch/irreducible loops.
Aart Bik281c6812016-08-26 11:31:48 -0700436 // TODO: make this less of a sledgehammer.
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800437 if (!graph_->HasLoops() || graph_->HasTryCatch() || graph_->HasIrreducibleLoops()) {
Aart Bik281c6812016-08-26 11:31:48 -0700438 return;
439 }
440
Aart Bik96202302016-10-04 17:33:56 -0700441 // Phase-local allocator that draws from the global pool. Since the allocator
442 // itself resides on the stack, it is destructed on exiting Run(), which
443 // implies its underlying memory is released immediately.
Aart Bikf8f5a162017-02-06 15:35:29 -0800444 ArenaAllocator allocator(global_allocator_->GetArenaPool());
Aart Bik96202302016-10-04 17:33:56 -0700445 loop_allocator_ = &allocator;
Nicolas Geoffrayebe16742016-10-05 09:55:42 +0100446
Aart Bik96202302016-10-04 17:33:56 -0700447 // Perform loop optimizations.
448 LocalRun();
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800449 if (top_loop_ == nullptr) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800450 graph_->SetHasLoops(false); // no more loops
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800451 }
452
Aart Bik96202302016-10-04 17:33:56 -0700453 // Detach.
454 loop_allocator_ = nullptr;
455 last_loop_ = top_loop_ = nullptr;
456}
457
Aart Bikb29f6842017-07-28 15:58:41 -0700458//
459// Loop setup and traversal.
460//
461
Aart Bik96202302016-10-04 17:33:56 -0700462void HLoopOptimization::LocalRun() {
463 // Build the linear order using the phase-local allocator. This step enables building
464 // a loop hierarchy that properly reflects the outer-inner and previous-next relation.
465 ArenaVector<HBasicBlock*> linear_order(loop_allocator_->Adapter(kArenaAllocLinearOrder));
466 LinearizeGraph(graph_, loop_allocator_, &linear_order);
467
Aart Bik281c6812016-08-26 11:31:48 -0700468 // Build the loop hierarchy.
Aart Bik96202302016-10-04 17:33:56 -0700469 for (HBasicBlock* block : linear_order) {
Aart Bik281c6812016-08-26 11:31:48 -0700470 if (block->IsLoopHeader()) {
471 AddLoop(block->GetLoopInformation());
472 }
473 }
Aart Bik96202302016-10-04 17:33:56 -0700474
Aart Bik8c4a8542016-10-06 11:36:57 -0700475 // Traverse the loop hierarchy inner-to-outer and optimize. Traversal can use
Aart Bikf8f5a162017-02-06 15:35:29 -0800476 // temporary data structures using the phase-local allocator. All new HIR
477 // should use the global allocator.
Aart Bik8c4a8542016-10-06 11:36:57 -0700478 if (top_loop_ != nullptr) {
479 ArenaSet<HInstruction*> iset(loop_allocator_->Adapter(kArenaAllocLoopOptimization));
Aart Bikb29f6842017-07-28 15:58:41 -0700480 ArenaSafeMap<HInstruction*, HInstruction*> reds(
481 std::less<HInstruction*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
Aart Bikf8f5a162017-02-06 15:35:29 -0800482 ArenaSet<ArrayReference> refs(loop_allocator_->Adapter(kArenaAllocLoopOptimization));
483 ArenaSafeMap<HInstruction*, HInstruction*> map(
484 std::less<HInstruction*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
Aart Bik0148de42017-09-05 09:25:01 -0700485 ArenaSafeMap<HInstruction*, HInstruction*> perm(
486 std::less<HInstruction*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
Aart Bikf8f5a162017-02-06 15:35:29 -0800487 // Attach.
Aart Bik8c4a8542016-10-06 11:36:57 -0700488 iset_ = &iset;
Aart Bikb29f6842017-07-28 15:58:41 -0700489 reductions_ = &reds;
Aart Bikf8f5a162017-02-06 15:35:29 -0800490 vector_refs_ = &refs;
491 vector_map_ = &map;
Aart Bik0148de42017-09-05 09:25:01 -0700492 vector_permanent_map_ = &perm;
Aart Bikf8f5a162017-02-06 15:35:29 -0800493 // Traverse.
Aart Bik8c4a8542016-10-06 11:36:57 -0700494 TraverseLoopsInnerToOuter(top_loop_);
Aart Bikf8f5a162017-02-06 15:35:29 -0800495 // Detach.
496 iset_ = nullptr;
Aart Bikb29f6842017-07-28 15:58:41 -0700497 reductions_ = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800498 vector_refs_ = nullptr;
499 vector_map_ = nullptr;
Aart Bik0148de42017-09-05 09:25:01 -0700500 vector_permanent_map_ = nullptr;
Aart Bik8c4a8542016-10-06 11:36:57 -0700501 }
Aart Bik281c6812016-08-26 11:31:48 -0700502}
503
504void HLoopOptimization::AddLoop(HLoopInformation* loop_info) {
505 DCHECK(loop_info != nullptr);
Aart Bikf8f5a162017-02-06 15:35:29 -0800506 LoopNode* node = new (loop_allocator_) LoopNode(loop_info);
Aart Bik281c6812016-08-26 11:31:48 -0700507 if (last_loop_ == nullptr) {
508 // First loop.
509 DCHECK(top_loop_ == nullptr);
510 last_loop_ = top_loop_ = node;
511 } else if (loop_info->IsIn(*last_loop_->loop_info)) {
512 // Inner loop.
513 node->outer = last_loop_;
514 DCHECK(last_loop_->inner == nullptr);
515 last_loop_ = last_loop_->inner = node;
516 } else {
517 // Subsequent loop.
518 while (last_loop_->outer != nullptr && !loop_info->IsIn(*last_loop_->outer->loop_info)) {
519 last_loop_ = last_loop_->outer;
520 }
521 node->outer = last_loop_->outer;
522 node->previous = last_loop_;
523 DCHECK(last_loop_->next == nullptr);
524 last_loop_ = last_loop_->next = node;
525 }
526}
527
528void HLoopOptimization::RemoveLoop(LoopNode* node) {
529 DCHECK(node != nullptr);
Aart Bik8c4a8542016-10-06 11:36:57 -0700530 DCHECK(node->inner == nullptr);
531 if (node->previous != nullptr) {
532 // Within sequence.
533 node->previous->next = node->next;
534 if (node->next != nullptr) {
535 node->next->previous = node->previous;
536 }
537 } else {
538 // First of sequence.
539 if (node->outer != nullptr) {
540 node->outer->inner = node->next;
541 } else {
542 top_loop_ = node->next;
543 }
544 if (node->next != nullptr) {
545 node->next->outer = node->outer;
546 node->next->previous = nullptr;
547 }
548 }
Aart Bik281c6812016-08-26 11:31:48 -0700549}
550
Aart Bikb29f6842017-07-28 15:58:41 -0700551bool HLoopOptimization::TraverseLoopsInnerToOuter(LoopNode* node) {
552 bool changed = false;
Aart Bik281c6812016-08-26 11:31:48 -0700553 for ( ; node != nullptr; node = node->next) {
Aart Bikb29f6842017-07-28 15:58:41 -0700554 // Visit inner loops first. Recompute induction information for this
555 // loop if the induction of any inner loop has changed.
556 if (TraverseLoopsInnerToOuter(node->inner)) {
Aart Bik482095d2016-10-10 15:39:10 -0700557 induction_range_.ReVisit(node->loop_info);
558 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800559 // Repeat simplifications in the loop-body until no more changes occur.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800560 // Note that since each simplification consists of eliminating code (without
561 // introducing new code), this process is always finite.
Aart Bikdf7822e2016-12-06 10:05:30 -0800562 do {
563 simplified_ = false;
Aart Bikdf7822e2016-12-06 10:05:30 -0800564 SimplifyInduction(node);
Aart Bik6b69e0a2017-01-11 10:20:43 -0800565 SimplifyBlocks(node);
Aart Bikb29f6842017-07-28 15:58:41 -0700566 changed = simplified_ || changed;
Aart Bikdf7822e2016-12-06 10:05:30 -0800567 } while (simplified_);
Aart Bikf8f5a162017-02-06 15:35:29 -0800568 // Optimize inner loop.
Aart Bik9abf8942016-10-14 09:49:42 -0700569 if (node->inner == nullptr) {
Aart Bikb29f6842017-07-28 15:58:41 -0700570 changed = OptimizeInnerLoop(node) || changed;
Aart Bik9abf8942016-10-14 09:49:42 -0700571 }
Aart Bik281c6812016-08-26 11:31:48 -0700572 }
Aart Bikb29f6842017-07-28 15:58:41 -0700573 return changed;
Aart Bik281c6812016-08-26 11:31:48 -0700574}
575
Aart Bikf8f5a162017-02-06 15:35:29 -0800576//
577// Optimization.
578//
579
Aart Bik281c6812016-08-26 11:31:48 -0700580void HLoopOptimization::SimplifyInduction(LoopNode* node) {
581 HBasicBlock* header = node->loop_info->GetHeader();
582 HBasicBlock* preheader = node->loop_info->GetPreHeader();
Aart Bik8c4a8542016-10-06 11:36:57 -0700583 // Scan the phis in the header to find opportunities to simplify an induction
584 // cycle that is only used outside the loop. Replace these uses, if any, with
585 // the last value and remove the induction cycle.
586 // Examples: for (int i = 0; x != null; i++) { .... no i .... }
587 // for (int i = 0; i < 10; i++, k++) { .... no k .... } return k;
Aart Bik281c6812016-08-26 11:31:48 -0700588 for (HInstructionIterator it(header->GetPhis()); !it.Done(); it.Advance()) {
589 HPhi* phi = it.Current()->AsPhi();
Aart Bikf8f5a162017-02-06 15:35:29 -0800590 if (TrySetPhiInduction(phi, /*restrict_uses*/ true) &&
591 TryAssignLastValue(node->loop_info, phi, preheader, /*collect_loop_uses*/ false)) {
Aart Bik671e48a2017-08-09 13:16:56 -0700592 // Note that it's ok to have replaced uses after the loop with the last value, without
593 // being able to remove the cycle. Environment uses (which are the reason we may not be
594 // able to remove the cycle) within the loop will still hold the right value. We must
595 // have tried first, however, to replace outside uses.
596 if (CanRemoveCycle()) {
597 simplified_ = true;
598 for (HInstruction* i : *iset_) {
599 RemoveFromCycle(i);
600 }
601 DCHECK(CheckInductionSetFullyRemoved(iset_));
Aart Bik281c6812016-08-26 11:31:48 -0700602 }
Aart Bik482095d2016-10-10 15:39:10 -0700603 }
604 }
605}
606
607void HLoopOptimization::SimplifyBlocks(LoopNode* node) {
Aart Bikdf7822e2016-12-06 10:05:30 -0800608 // Iterate over all basic blocks in the loop-body.
609 for (HBlocksInLoopIterator it(*node->loop_info); !it.Done(); it.Advance()) {
610 HBasicBlock* block = it.Current();
611 // Remove dead instructions from the loop-body.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800612 RemoveDeadInstructions(block->GetPhis());
613 RemoveDeadInstructions(block->GetInstructions());
Aart Bikdf7822e2016-12-06 10:05:30 -0800614 // Remove trivial control flow blocks from the loop-body.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800615 if (block->GetPredecessors().size() == 1 &&
616 block->GetSuccessors().size() == 1 &&
617 block->GetSingleSuccessor()->GetPredecessors().size() == 1) {
Aart Bikdf7822e2016-12-06 10:05:30 -0800618 simplified_ = true;
Aart Bik6b69e0a2017-01-11 10:20:43 -0800619 block->MergeWith(block->GetSingleSuccessor());
Aart Bikdf7822e2016-12-06 10:05:30 -0800620 } else if (block->GetSuccessors().size() == 2) {
621 // Trivial if block can be bypassed to either branch.
622 HBasicBlock* succ0 = block->GetSuccessors()[0];
623 HBasicBlock* succ1 = block->GetSuccessors()[1];
624 HBasicBlock* meet0 = nullptr;
625 HBasicBlock* meet1 = nullptr;
626 if (succ0 != succ1 &&
627 IsGotoBlock(succ0, &meet0) &&
628 IsGotoBlock(succ1, &meet1) &&
629 meet0 == meet1 && // meets again
630 meet0 != block && // no self-loop
631 meet0->GetPhis().IsEmpty()) { // not used for merging
632 simplified_ = true;
633 succ0->DisconnectAndDelete();
634 if (block->Dominates(meet0)) {
635 block->RemoveDominatedBlock(meet0);
636 succ1->AddDominatedBlock(meet0);
637 meet0->SetDominator(succ1);
Aart Bike3dedc52016-11-02 17:50:27 -0700638 }
Aart Bik482095d2016-10-10 15:39:10 -0700639 }
Aart Bik281c6812016-08-26 11:31:48 -0700640 }
Aart Bikdf7822e2016-12-06 10:05:30 -0800641 }
Aart Bik281c6812016-08-26 11:31:48 -0700642}
643
Aart Bikb29f6842017-07-28 15:58:41 -0700644bool HLoopOptimization::OptimizeInnerLoop(LoopNode* node) {
Aart Bik281c6812016-08-26 11:31:48 -0700645 HBasicBlock* header = node->loop_info->GetHeader();
646 HBasicBlock* preheader = node->loop_info->GetPreHeader();
Aart Bik9abf8942016-10-14 09:49:42 -0700647 // Ensure loop header logic is finite.
Aart Bikf8f5a162017-02-06 15:35:29 -0800648 int64_t trip_count = 0;
649 if (!induction_range_.IsFinite(node->loop_info, &trip_count)) {
Aart Bikb29f6842017-07-28 15:58:41 -0700650 return false;
Aart Bik9abf8942016-10-14 09:49:42 -0700651 }
Aart Bik281c6812016-08-26 11:31:48 -0700652 // Ensure there is only a single loop-body (besides the header).
653 HBasicBlock* body = nullptr;
654 for (HBlocksInLoopIterator it(*node->loop_info); !it.Done(); it.Advance()) {
655 if (it.Current() != header) {
656 if (body != nullptr) {
Aart Bikb29f6842017-07-28 15:58:41 -0700657 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700658 }
659 body = it.Current();
660 }
661 }
Andreas Gampef45d61c2017-06-07 10:29:33 -0700662 CHECK(body != nullptr);
Aart Bik281c6812016-08-26 11:31:48 -0700663 // Ensure there is only a single exit point.
664 if (header->GetSuccessors().size() != 2) {
Aart Bikb29f6842017-07-28 15:58:41 -0700665 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700666 }
667 HBasicBlock* exit = (header->GetSuccessors()[0] == body)
668 ? header->GetSuccessors()[1]
669 : header->GetSuccessors()[0];
Aart Bik8c4a8542016-10-06 11:36:57 -0700670 // Ensure exit can only be reached by exiting loop.
Aart Bik281c6812016-08-26 11:31:48 -0700671 if (exit->GetPredecessors().size() != 1) {
Aart Bikb29f6842017-07-28 15:58:41 -0700672 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700673 }
Aart Bik6b69e0a2017-01-11 10:20:43 -0800674 // Detect either an empty loop (no side effects other than plain iteration) or
675 // a trivial loop (just iterating once). Replace subsequent index uses, if any,
676 // with the last value and remove the loop, possibly after unrolling its body.
Aart Bikb29f6842017-07-28 15:58:41 -0700677 HPhi* main_phi = nullptr;
678 if (TrySetSimpleLoopHeader(header, &main_phi)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -0800679 bool is_empty = IsEmptyBody(body);
Aart Bikb29f6842017-07-28 15:58:41 -0700680 if (reductions_->empty() && // TODO: possible with some effort
681 (is_empty || trip_count == 1) &&
682 TryAssignLastValue(node->loop_info, main_phi, preheader, /*collect_loop_uses*/ true)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -0800683 if (!is_empty) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800684 // Unroll the loop-body, which sees initial value of the index.
Aart Bikb29f6842017-07-28 15:58:41 -0700685 main_phi->ReplaceWith(main_phi->InputAt(0));
Aart Bik6b69e0a2017-01-11 10:20:43 -0800686 preheader->MergeInstructionsWith(body);
687 }
688 body->DisconnectAndDelete();
689 exit->RemovePredecessor(header);
690 header->RemoveSuccessor(exit);
691 header->RemoveDominatedBlock(exit);
692 header->DisconnectAndDelete();
693 preheader->AddSuccessor(exit);
Aart Bikf8f5a162017-02-06 15:35:29 -0800694 preheader->AddInstruction(new (global_allocator_) HGoto());
Aart Bik6b69e0a2017-01-11 10:20:43 -0800695 preheader->AddDominatedBlock(exit);
696 exit->SetDominator(preheader);
697 RemoveLoop(node); // update hierarchy
Aart Bikb29f6842017-07-28 15:58:41 -0700698 return true;
Aart Bikf8f5a162017-02-06 15:35:29 -0800699 }
700 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800701 // Vectorize loop, if possible and valid.
Aart Bikb29f6842017-07-28 15:58:41 -0700702 if (kEnableVectorization &&
703 TrySetSimpleLoopHeader(header, &main_phi) &&
Aart Bikb29f6842017-07-28 15:58:41 -0700704 ShouldVectorize(node, body, trip_count) &&
705 TryAssignLastValue(node->loop_info, main_phi, preheader, /*collect_loop_uses*/ true)) {
706 Vectorize(node, body, exit, trip_count);
707 graph_->SetHasSIMD(true); // flag SIMD usage
Aart Bik21b85922017-09-06 13:29:16 -0700708 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorized);
Aart Bikb29f6842017-07-28 15:58:41 -0700709 return true;
Aart Bikf8f5a162017-02-06 15:35:29 -0800710 }
Aart Bikb29f6842017-07-28 15:58:41 -0700711 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -0800712}
713
714//
715// Loop vectorization. The implementation is based on the book by Aart J.C. Bik:
716// "The Software Vectorization Handbook. Applying Multimedia Extensions for Maximum Performance."
717// Intel Press, June, 2004 (http://www.aartbik.com/).
718//
719
Aart Bik14a68b42017-06-08 14:06:58 -0700720bool HLoopOptimization::ShouldVectorize(LoopNode* node, HBasicBlock* block, int64_t trip_count) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800721 // Reset vector bookkeeping.
722 vector_length_ = 0;
723 vector_refs_->clear();
Aart Bik14a68b42017-06-08 14:06:58 -0700724 vector_peeling_candidate_ = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800725 vector_runtime_test_a_ =
726 vector_runtime_test_b_= nullptr;
727
728 // Phis in the loop-body prevent vectorization.
729 if (!block->GetPhis().IsEmpty()) {
730 return false;
731 }
732
733 // Scan the loop-body, starting a right-hand-side tree traversal at each left-hand-side
734 // occurrence, which allows passing down attributes down the use tree.
735 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
736 if (!VectorizeDef(node, it.Current(), /*generate_code*/ false)) {
737 return false; // failure to vectorize a left-hand-side
738 }
739 }
740
Aart Bik14a68b42017-06-08 14:06:58 -0700741 // Does vectorization seem profitable?
742 if (!IsVectorizationProfitable(trip_count)) {
743 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -0800744 }
745
746 // Data dependence analysis. Find each pair of references with same type, where
747 // at least one is a write. Each such pair denotes a possible data dependence.
748 // This analysis exploits the property that differently typed arrays cannot be
749 // aliased, as well as the property that references either point to the same
750 // array or to two completely disjoint arrays, i.e., no partial aliasing.
751 // Other than a few simply heuristics, no detailed subscript analysis is done.
Aart Bikb29f6842017-07-28 15:58:41 -0700752 // The scan over references also finds a suitable dynamic loop peeling candidate.
753 const ArrayReference* candidate = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800754 for (auto i = vector_refs_->begin(); i != vector_refs_->end(); ++i) {
755 for (auto j = i; ++j != vector_refs_->end(); ) {
756 if (i->type == j->type && (i->lhs || j->lhs)) {
757 // Found same-typed a[i+x] vs. b[i+y], where at least one is a write.
758 HInstruction* a = i->base;
759 HInstruction* b = j->base;
760 HInstruction* x = i->offset;
761 HInstruction* y = j->offset;
762 if (a == b) {
763 // Found a[i+x] vs. a[i+y]. Accept if x == y (loop-independent data dependence).
764 // Conservatively assume a loop-carried data dependence otherwise, and reject.
765 if (x != y) {
766 return false;
767 }
768 } else {
769 // Found a[i+x] vs. b[i+y]. Accept if x == y (at worst loop-independent data dependence).
770 // Conservatively assume a potential loop-carried data dependence otherwise, avoided by
771 // generating an explicit a != b disambiguation runtime test on the two references.
772 if (x != y) {
Aart Bik37dc4df2017-06-28 14:08:00 -0700773 // To avoid excessive overhead, we only accept one a != b test.
774 if (vector_runtime_test_a_ == nullptr) {
775 // First test found.
776 vector_runtime_test_a_ = a;
777 vector_runtime_test_b_ = b;
778 } else if ((vector_runtime_test_a_ != a || vector_runtime_test_b_ != b) &&
779 (vector_runtime_test_a_ != b || vector_runtime_test_b_ != a)) {
780 return false; // second test would be needed
Aart Bikf8f5a162017-02-06 15:35:29 -0800781 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800782 }
783 }
784 }
785 }
786 }
787
Aart Bik14a68b42017-06-08 14:06:58 -0700788 // Consider dynamic loop peeling for alignment.
Aart Bikb29f6842017-07-28 15:58:41 -0700789 SetPeelingCandidate(candidate, trip_count);
Aart Bik14a68b42017-06-08 14:06:58 -0700790
Aart Bikf8f5a162017-02-06 15:35:29 -0800791 // Success!
792 return true;
793}
794
795void HLoopOptimization::Vectorize(LoopNode* node,
796 HBasicBlock* block,
797 HBasicBlock* exit,
798 int64_t trip_count) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800799 HBasicBlock* header = node->loop_info->GetHeader();
800 HBasicBlock* preheader = node->loop_info->GetPreHeader();
801
Aart Bik14a68b42017-06-08 14:06:58 -0700802 // Pick a loop unrolling factor for the vector loop.
803 uint32_t unroll = GetUnrollingFactor(block, trip_count);
804 uint32_t chunk = vector_length_ * unroll;
805
806 // A cleanup loop is needed, at least, for any unknown trip count or
807 // for a known trip count with remainder iterations after vectorization.
808 bool needs_cleanup = trip_count == 0 || (trip_count % chunk) != 0;
Aart Bikf8f5a162017-02-06 15:35:29 -0800809
810 // Adjust vector bookkeeping.
Aart Bikb29f6842017-07-28 15:58:41 -0700811 HPhi* main_phi = nullptr;
812 bool is_simple_loop_header = TrySetSimpleLoopHeader(header, &main_phi); // refills sets
Aart Bikf8f5a162017-02-06 15:35:29 -0800813 DCHECK(is_simple_loop_header);
Aart Bik14a68b42017-06-08 14:06:58 -0700814 vector_header_ = header;
815 vector_body_ = block;
Aart Bikf8f5a162017-02-06 15:35:29 -0800816
Aart Bikdbbac8f2017-09-01 13:06:08 -0700817 // Loop induction type.
818 Primitive::Type induc_type = main_phi->GetType();
819 DCHECK(induc_type == Primitive::kPrimInt || induc_type == Primitive::kPrimLong) << induc_type;
820
Aart Bikb29f6842017-07-28 15:58:41 -0700821 // Generate dynamic loop peeling trip count, if needed, under the assumption
822 // that the Android runtime guarantees at least "component size" alignment:
823 // ptc = (ALIGN - (&a[initial] % ALIGN)) / type-size
Aart Bik14a68b42017-06-08 14:06:58 -0700824 HInstruction* ptc = nullptr;
825 if (vector_peeling_candidate_ != nullptr) {
826 DCHECK_LT(vector_length_, trip_count) << "dynamic peeling currently requires known trip count";
827 //
828 // TODO: Implement this. Compute address of first access memory location and
829 // compute peeling factor to obtain kAlignedBase alignment.
830 //
831 needs_cleanup = true;
832 }
833
834 // Generate loop control:
Aart Bikf8f5a162017-02-06 15:35:29 -0800835 // stc = <trip-count>;
Aart Bik14a68b42017-06-08 14:06:58 -0700836 // vtc = stc - (stc - ptc) % chunk;
837 // i = 0;
Aart Bikf8f5a162017-02-06 15:35:29 -0800838 HInstruction* stc = induction_range_.GenerateTripCount(node->loop_info, graph_, preheader);
839 HInstruction* vtc = stc;
840 if (needs_cleanup) {
Aart Bik14a68b42017-06-08 14:06:58 -0700841 DCHECK(IsPowerOfTwo(chunk));
842 HInstruction* diff = stc;
843 if (ptc != nullptr) {
844 diff = Insert(preheader, new (global_allocator_) HSub(induc_type, stc, ptc));
845 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800846 HInstruction* rem = Insert(
847 preheader, new (global_allocator_) HAnd(induc_type,
Aart Bik14a68b42017-06-08 14:06:58 -0700848 diff,
Aart Bikdbbac8f2017-09-01 13:06:08 -0700849 graph_->GetConstant(induc_type, chunk - 1)));
Aart Bikf8f5a162017-02-06 15:35:29 -0800850 vtc = Insert(preheader, new (global_allocator_) HSub(induc_type, stc, rem));
851 }
Aart Bikdbbac8f2017-09-01 13:06:08 -0700852 vector_index_ = graph_->GetConstant(induc_type, 0);
Aart Bikf8f5a162017-02-06 15:35:29 -0800853
854 // Generate runtime disambiguation test:
855 // vtc = a != b ? vtc : 0;
856 if (vector_runtime_test_a_ != nullptr) {
857 HInstruction* rt = Insert(
858 preheader,
859 new (global_allocator_) HNotEqual(vector_runtime_test_a_, vector_runtime_test_b_));
860 vtc = Insert(preheader,
Aart Bikdbbac8f2017-09-01 13:06:08 -0700861 new (global_allocator_)
862 HSelect(rt, vtc, graph_->GetConstant(induc_type, 0), kNoDexPc));
Aart Bikf8f5a162017-02-06 15:35:29 -0800863 needs_cleanup = true;
864 }
865
Aart Bik14a68b42017-06-08 14:06:58 -0700866 // Generate dynamic peeling loop for alignment, if needed:
867 // for ( ; i < ptc; i += 1)
868 // <loop-body>
869 if (ptc != nullptr) {
870 vector_mode_ = kSequential;
871 GenerateNewLoop(node,
872 block,
873 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
874 vector_index_,
875 ptc,
Aart Bikdbbac8f2017-09-01 13:06:08 -0700876 graph_->GetConstant(induc_type, 1),
Aart Bik521b50f2017-09-09 10:44:45 -0700877 kNoUnrollingFactor);
Aart Bik14a68b42017-06-08 14:06:58 -0700878 }
879
880 // Generate vector loop, possibly further unrolled:
881 // for ( ; i < vtc; i += chunk)
Aart Bikf8f5a162017-02-06 15:35:29 -0800882 // <vectorized-loop-body>
883 vector_mode_ = kVector;
884 GenerateNewLoop(node,
885 block,
Aart Bik14a68b42017-06-08 14:06:58 -0700886 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
887 vector_index_,
Aart Bikf8f5a162017-02-06 15:35:29 -0800888 vtc,
Aart Bikdbbac8f2017-09-01 13:06:08 -0700889 graph_->GetConstant(induc_type, vector_length_), // increment per unroll
Aart Bik14a68b42017-06-08 14:06:58 -0700890 unroll);
Aart Bikf8f5a162017-02-06 15:35:29 -0800891 HLoopInformation* vloop = vector_header_->GetLoopInformation();
892
893 // Generate cleanup loop, if needed:
894 // for ( ; i < stc; i += 1)
895 // <loop-body>
896 if (needs_cleanup) {
897 vector_mode_ = kSequential;
898 GenerateNewLoop(node,
899 block,
900 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
Aart Bik14a68b42017-06-08 14:06:58 -0700901 vector_index_,
Aart Bikf8f5a162017-02-06 15:35:29 -0800902 stc,
Aart Bikdbbac8f2017-09-01 13:06:08 -0700903 graph_->GetConstant(induc_type, 1),
Aart Bik521b50f2017-09-09 10:44:45 -0700904 kNoUnrollingFactor);
Aart Bikf8f5a162017-02-06 15:35:29 -0800905 }
906
Aart Bik0148de42017-09-05 09:25:01 -0700907 // Link reductions to their final uses.
908 for (auto i = reductions_->begin(); i != reductions_->end(); ++i) {
909 if (i->first->IsPhi()) {
Aart Bikdbbac8f2017-09-01 13:06:08 -0700910 HInstruction* phi = i->first;
911 HInstruction* repl = ReduceAndExtractIfNeeded(i->second);
912 // Deal with regular uses.
913 for (const HUseListNode<HInstruction*>& use : phi->GetUses()) {
914 induction_range_.Replace(use.GetUser(), phi, repl); // update induction use
915 }
916 phi->ReplaceWith(repl);
Aart Bik0148de42017-09-05 09:25:01 -0700917 }
918 }
919
Aart Bikf8f5a162017-02-06 15:35:29 -0800920 // Remove the original loop by disconnecting the body block
921 // and removing all instructions from the header.
922 block->DisconnectAndDelete();
923 while (!header->GetFirstInstruction()->IsGoto()) {
924 header->RemoveInstruction(header->GetFirstInstruction());
925 }
Aart Bikb29f6842017-07-28 15:58:41 -0700926
Aart Bik14a68b42017-06-08 14:06:58 -0700927 // Update loop hierarchy: the old header now resides in the same outer loop
928 // as the old preheader. Note that we don't bother putting sequential
929 // loops back in the hierarchy at this point.
Aart Bikf8f5a162017-02-06 15:35:29 -0800930 header->SetLoopInformation(preheader->GetLoopInformation()); // outward
931 node->loop_info = vloop;
932}
933
934void HLoopOptimization::GenerateNewLoop(LoopNode* node,
935 HBasicBlock* block,
936 HBasicBlock* new_preheader,
937 HInstruction* lo,
938 HInstruction* hi,
Aart Bik14a68b42017-06-08 14:06:58 -0700939 HInstruction* step,
940 uint32_t unroll) {
941 DCHECK(unroll == 1 || vector_mode_ == kVector);
Aart Bikdbbac8f2017-09-01 13:06:08 -0700942 Primitive::Type induc_type = lo->GetType();
Aart Bikf8f5a162017-02-06 15:35:29 -0800943 // Prepare new loop.
Aart Bikf8f5a162017-02-06 15:35:29 -0800944 vector_preheader_ = new_preheader,
945 vector_header_ = vector_preheader_->GetSingleSuccessor();
946 vector_body_ = vector_header_->GetSuccessors()[1];
Aart Bik14a68b42017-06-08 14:06:58 -0700947 HPhi* phi = new (global_allocator_) HPhi(global_allocator_,
948 kNoRegNumber,
949 0,
950 HPhi::ToPhiType(induc_type));
Aart Bikb07d1bc2017-04-05 10:03:15 -0700951 // Generate header and prepare body.
Aart Bikf8f5a162017-02-06 15:35:29 -0800952 // for (i = lo; i < hi; i += step)
953 // <loop-body>
Aart Bik14a68b42017-06-08 14:06:58 -0700954 HInstruction* cond = new (global_allocator_) HAboveOrEqual(phi, hi);
955 vector_header_->AddPhi(phi);
Aart Bikf8f5a162017-02-06 15:35:29 -0800956 vector_header_->AddInstruction(cond);
957 vector_header_->AddInstruction(new (global_allocator_) HIf(cond));
Aart Bik14a68b42017-06-08 14:06:58 -0700958 vector_index_ = phi;
Aart Bik0148de42017-09-05 09:25:01 -0700959 vector_permanent_map_->clear(); // preserved over unrolling
Aart Bik14a68b42017-06-08 14:06:58 -0700960 for (uint32_t u = 0; u < unroll; u++) {
Aart Bik14a68b42017-06-08 14:06:58 -0700961 // Generate instruction map.
Aart Bik0148de42017-09-05 09:25:01 -0700962 vector_map_->clear();
Aart Bik14a68b42017-06-08 14:06:58 -0700963 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
964 bool vectorized_def = VectorizeDef(node, it.Current(), /*generate_code*/ true);
965 DCHECK(vectorized_def);
966 }
967 // Generate body from the instruction map, but in original program order.
968 HEnvironment* env = vector_header_->GetFirstInstruction()->GetEnvironment();
969 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
970 auto i = vector_map_->find(it.Current());
971 if (i != vector_map_->end() && !i->second->IsInBlock()) {
972 Insert(vector_body_, i->second);
973 // Deal with instructions that need an environment, such as the scalar intrinsics.
974 if (i->second->NeedsEnvironment()) {
975 i->second->CopyEnvironmentFromWithLoopPhiAdjustment(env, vector_header_);
976 }
977 }
978 }
Aart Bik0148de42017-09-05 09:25:01 -0700979 // Generate the induction.
Aart Bik14a68b42017-06-08 14:06:58 -0700980 vector_index_ = new (global_allocator_) HAdd(induc_type, vector_index_, step);
981 Insert(vector_body_, vector_index_);
Aart Bikf8f5a162017-02-06 15:35:29 -0800982 }
Aart Bik0148de42017-09-05 09:25:01 -0700983 // Finalize phi inputs for the reductions (if any).
984 for (auto i = reductions_->begin(); i != reductions_->end(); ++i) {
985 if (!i->first->IsPhi()) {
986 DCHECK(i->second->IsPhi());
987 GenerateVecReductionPhiInputs(i->second->AsPhi(), i->first);
988 }
989 }
Aart Bikb29f6842017-07-28 15:58:41 -0700990 // Finalize phi inputs for the loop index.
Aart Bik14a68b42017-06-08 14:06:58 -0700991 phi->AddInput(lo);
992 phi->AddInput(vector_index_);
993 vector_index_ = phi;
Aart Bikf8f5a162017-02-06 15:35:29 -0800994}
995
Aart Bikf8f5a162017-02-06 15:35:29 -0800996bool HLoopOptimization::VectorizeDef(LoopNode* node,
997 HInstruction* instruction,
998 bool generate_code) {
999 // Accept a left-hand-side array base[index] for
1000 // (1) supported vector type,
1001 // (2) loop-invariant base,
1002 // (3) unit stride index,
1003 // (4) vectorizable right-hand-side value.
1004 uint64_t restrictions = kNone;
1005 if (instruction->IsArraySet()) {
1006 Primitive::Type type = instruction->AsArraySet()->GetComponentType();
1007 HInstruction* base = instruction->InputAt(0);
1008 HInstruction* index = instruction->InputAt(1);
1009 HInstruction* value = instruction->InputAt(2);
1010 HInstruction* offset = nullptr;
1011 if (TrySetVectorType(type, &restrictions) &&
1012 node->loop_info->IsDefinedOutOfTheLoop(base) &&
Aart Bik37dc4df2017-06-28 14:08:00 -07001013 induction_range_.IsUnitStride(instruction, index, graph_, &offset) &&
Aart Bikf8f5a162017-02-06 15:35:29 -08001014 VectorizeUse(node, value, generate_code, type, restrictions)) {
1015 if (generate_code) {
1016 GenerateVecSub(index, offset);
Aart Bik14a68b42017-06-08 14:06:58 -07001017 GenerateVecMem(instruction, vector_map_->Get(index), vector_map_->Get(value), offset, type);
Aart Bikf8f5a162017-02-06 15:35:29 -08001018 } else {
1019 vector_refs_->insert(ArrayReference(base, offset, type, /*lhs*/ true));
1020 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08001021 return true;
1022 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001023 return false;
1024 }
Aart Bik0148de42017-09-05 09:25:01 -07001025 // Accept a left-hand-side reduction for
1026 // (1) supported vector type,
1027 // (2) vectorizable right-hand-side value.
1028 auto redit = reductions_->find(instruction);
1029 if (redit != reductions_->end()) {
1030 Primitive::Type type = instruction->GetType();
Aart Bikdbbac8f2017-09-01 13:06:08 -07001031 // Recognize SAD idiom or direct reduction.
1032 if (VectorizeSADIdiom(node, instruction, generate_code, type, restrictions) ||
1033 (TrySetVectorType(type, &restrictions) &&
1034 VectorizeUse(node, instruction, generate_code, type, restrictions))) {
Aart Bik0148de42017-09-05 09:25:01 -07001035 if (generate_code) {
1036 HInstruction* new_red = vector_map_->Get(instruction);
1037 vector_permanent_map_->Put(new_red, vector_map_->Get(redit->second));
1038 vector_permanent_map_->Overwrite(redit->second, new_red);
1039 }
1040 return true;
1041 }
1042 return false;
1043 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001044 // Branch back okay.
1045 if (instruction->IsGoto()) {
1046 return true;
1047 }
1048 // Otherwise accept only expressions with no effects outside the immediate loop-body.
1049 // Note that actual uses are inspected during right-hand-side tree traversal.
1050 return !IsUsedOutsideLoop(node->loop_info, instruction) && !instruction->DoesAnyWrite();
1051}
1052
Aart Bik304c8a52017-05-23 11:01:13 -07001053// TODO: saturation arithmetic.
Aart Bikf8f5a162017-02-06 15:35:29 -08001054bool HLoopOptimization::VectorizeUse(LoopNode* node,
1055 HInstruction* instruction,
1056 bool generate_code,
1057 Primitive::Type type,
1058 uint64_t restrictions) {
1059 // Accept anything for which code has already been generated.
1060 if (generate_code) {
1061 if (vector_map_->find(instruction) != vector_map_->end()) {
1062 return true;
1063 }
1064 }
1065 // Continue the right-hand-side tree traversal, passing in proper
1066 // types and vector restrictions along the way. During code generation,
1067 // all new nodes are drawn from the global allocator.
1068 if (node->loop_info->IsDefinedOutOfTheLoop(instruction)) {
1069 // Accept invariant use, using scalar expansion.
1070 if (generate_code) {
1071 GenerateVecInv(instruction, type);
1072 }
1073 return true;
1074 } else if (instruction->IsArrayGet()) {
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001075 // Deal with vector restrictions.
1076 if (instruction->AsArrayGet()->IsStringCharAt() &&
1077 HasVectorRestrictions(restrictions, kNoStringCharAt)) {
1078 return false;
1079 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001080 // Accept a right-hand-side array base[index] for
1081 // (1) exact matching vector type,
1082 // (2) loop-invariant base,
1083 // (3) unit stride index,
1084 // (4) vectorizable right-hand-side value.
1085 HInstruction* base = instruction->InputAt(0);
1086 HInstruction* index = instruction->InputAt(1);
1087 HInstruction* offset = nullptr;
1088 if (type == instruction->GetType() &&
1089 node->loop_info->IsDefinedOutOfTheLoop(base) &&
Aart Bik37dc4df2017-06-28 14:08:00 -07001090 induction_range_.IsUnitStride(instruction, index, graph_, &offset)) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001091 if (generate_code) {
1092 GenerateVecSub(index, offset);
Aart Bik14a68b42017-06-08 14:06:58 -07001093 GenerateVecMem(instruction, vector_map_->Get(index), nullptr, offset, type);
Aart Bikf8f5a162017-02-06 15:35:29 -08001094 } else {
1095 vector_refs_->insert(ArrayReference(base, offset, type, /*lhs*/ false));
1096 }
1097 return true;
1098 }
Aart Bik0148de42017-09-05 09:25:01 -07001099 } else if (instruction->IsPhi()) {
1100 // Accept particular phi operations.
1101 if (reductions_->find(instruction) != reductions_->end()) {
1102 // Deal with vector restrictions.
1103 if (HasVectorRestrictions(restrictions, kNoReduction)) {
1104 return false;
1105 }
1106 // Accept a reduction.
1107 if (generate_code) {
1108 GenerateVecReductionPhi(instruction->AsPhi());
1109 }
1110 return true;
1111 }
1112 // TODO: accept right-hand-side induction?
1113 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001114 } else if (instruction->IsTypeConversion()) {
1115 // Accept particular type conversions.
1116 HTypeConversion* conversion = instruction->AsTypeConversion();
1117 HInstruction* opa = conversion->InputAt(0);
1118 Primitive::Type from = conversion->GetInputType();
1119 Primitive::Type to = conversion->GetResultType();
Aart Bikdbbac8f2017-09-01 13:06:08 -07001120 if (Primitive::IsIntegralType(from) && Primitive::IsIntegralType(to)) {
1121 size_t size_vec = Primitive::ComponentSize(type);
1122 size_t size_from = Primitive::ComponentSize(from);
1123 size_t size_to = Primitive::ComponentSize(to);
1124 // Accept an integral conversion
1125 // (1a) narrowing into vector type, "wider" operations cannot bring in higher order bits, or
1126 // (1b) widening from at least vector type, and
1127 // (2) vectorizable operand.
1128 if ((size_to < size_from &&
1129 size_to == size_vec &&
1130 VectorizeUse(node, opa, generate_code, type, restrictions | kNoHiBits)) ||
1131 (size_to >= size_from &&
1132 size_from >= size_vec &&
1133 VectorizeUse(node, opa, generate_code, type, restrictions))) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001134 if (generate_code) {
1135 if (vector_mode_ == kVector) {
1136 vector_map_->Put(instruction, vector_map_->Get(opa)); // operand pass-through
1137 } else {
1138 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1139 }
1140 }
1141 return true;
1142 }
1143 } else if (to == Primitive::kPrimFloat && from == Primitive::kPrimInt) {
1144 DCHECK_EQ(to, type);
1145 // Accept int to float conversion for
1146 // (1) supported int,
1147 // (2) vectorizable operand.
1148 if (TrySetVectorType(from, &restrictions) &&
1149 VectorizeUse(node, opa, generate_code, from, restrictions)) {
1150 if (generate_code) {
1151 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1152 }
1153 return true;
1154 }
1155 }
1156 return false;
1157 } else if (instruction->IsNeg() || instruction->IsNot() || instruction->IsBooleanNot()) {
1158 // Accept unary operator for vectorizable operand.
1159 HInstruction* opa = instruction->InputAt(0);
1160 if (VectorizeUse(node, opa, generate_code, type, restrictions)) {
1161 if (generate_code) {
1162 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1163 }
1164 return true;
1165 }
1166 } else if (instruction->IsAdd() || instruction->IsSub() ||
1167 instruction->IsMul() || instruction->IsDiv() ||
1168 instruction->IsAnd() || instruction->IsOr() || instruction->IsXor()) {
1169 // Deal with vector restrictions.
1170 if ((instruction->IsMul() && HasVectorRestrictions(restrictions, kNoMul)) ||
1171 (instruction->IsDiv() && HasVectorRestrictions(restrictions, kNoDiv))) {
1172 return false;
1173 }
1174 // Accept binary operator for vectorizable operands.
1175 HInstruction* opa = instruction->InputAt(0);
1176 HInstruction* opb = instruction->InputAt(1);
1177 if (VectorizeUse(node, opa, generate_code, type, restrictions) &&
1178 VectorizeUse(node, opb, generate_code, type, restrictions)) {
1179 if (generate_code) {
1180 GenerateVecOp(instruction, vector_map_->Get(opa), vector_map_->Get(opb), type);
1181 }
1182 return true;
1183 }
1184 } else if (instruction->IsShl() || instruction->IsShr() || instruction->IsUShr()) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001185 // Recognize halving add idiom.
Aart Bikf3e61ee2017-04-12 17:09:20 -07001186 if (VectorizeHalvingAddIdiom(node, instruction, generate_code, type, restrictions)) {
1187 return true;
1188 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001189 // Deal with vector restrictions.
Aart Bik304c8a52017-05-23 11:01:13 -07001190 HInstruction* opa = instruction->InputAt(0);
1191 HInstruction* opb = instruction->InputAt(1);
1192 HInstruction* r = opa;
1193 bool is_unsigned = false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001194 if ((HasVectorRestrictions(restrictions, kNoShift)) ||
1195 (instruction->IsShr() && HasVectorRestrictions(restrictions, kNoShr))) {
1196 return false; // unsupported instruction
Aart Bik304c8a52017-05-23 11:01:13 -07001197 } else if (HasVectorRestrictions(restrictions, kNoHiBits)) {
1198 // Shifts right need extra care to account for higher order bits.
1199 // TODO: less likely shr/unsigned and ushr/signed can by flipping signess.
1200 if (instruction->IsShr() &&
1201 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || is_unsigned)) {
1202 return false; // reject, unless all operands are sign-extension narrower
1203 } else if (instruction->IsUShr() &&
1204 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || !is_unsigned)) {
1205 return false; // reject, unless all operands are zero-extension narrower
1206 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001207 }
1208 // Accept shift operator for vectorizable/invariant operands.
1209 // TODO: accept symbolic, albeit loop invariant shift factors.
Aart Bik304c8a52017-05-23 11:01:13 -07001210 DCHECK(r != nullptr);
1211 if (generate_code && vector_mode_ != kVector) { // de-idiom
1212 r = opa;
1213 }
Aart Bik50e20d52017-05-05 14:07:29 -07001214 int64_t distance = 0;
Aart Bik304c8a52017-05-23 11:01:13 -07001215 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
Aart Bik50e20d52017-05-05 14:07:29 -07001216 IsInt64AndGet(opb, /*out*/ &distance)) {
Aart Bik65ffd8e2017-05-01 16:50:45 -07001217 // Restrict shift distance to packed data type width.
1218 int64_t max_distance = Primitive::ComponentSize(type) * 8;
1219 if (0 <= distance && distance < max_distance) {
1220 if (generate_code) {
Aart Bik304c8a52017-05-23 11:01:13 -07001221 GenerateVecOp(instruction, vector_map_->Get(r), opb, type);
Aart Bik65ffd8e2017-05-01 16:50:45 -07001222 }
1223 return true;
Aart Bikf8f5a162017-02-06 15:35:29 -08001224 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001225 }
1226 } else if (instruction->IsInvokeStaticOrDirect()) {
Aart Bik6daebeb2017-04-03 14:35:41 -07001227 // Accept particular intrinsics.
1228 HInvokeStaticOrDirect* invoke = instruction->AsInvokeStaticOrDirect();
1229 switch (invoke->GetIntrinsic()) {
1230 case Intrinsics::kMathAbsInt:
1231 case Intrinsics::kMathAbsLong:
1232 case Intrinsics::kMathAbsFloat:
1233 case Intrinsics::kMathAbsDouble: {
1234 // Deal with vector restrictions.
Aart Bik304c8a52017-05-23 11:01:13 -07001235 HInstruction* opa = instruction->InputAt(0);
1236 HInstruction* r = opa;
1237 bool is_unsigned = false;
1238 if (HasVectorRestrictions(restrictions, kNoAbs)) {
Aart Bik6daebeb2017-04-03 14:35:41 -07001239 return false;
Aart Bik304c8a52017-05-23 11:01:13 -07001240 } else if (HasVectorRestrictions(restrictions, kNoHiBits) &&
1241 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || is_unsigned)) {
1242 return false; // reject, unless operand is sign-extension narrower
Aart Bik6daebeb2017-04-03 14:35:41 -07001243 }
1244 // Accept ABS(x) for vectorizable operand.
Aart Bik304c8a52017-05-23 11:01:13 -07001245 DCHECK(r != nullptr);
1246 if (generate_code && vector_mode_ != kVector) { // de-idiom
1247 r = opa;
1248 }
1249 if (VectorizeUse(node, r, generate_code, type, restrictions)) {
Aart Bik6daebeb2017-04-03 14:35:41 -07001250 if (generate_code) {
Aart Bik304c8a52017-05-23 11:01:13 -07001251 GenerateVecOp(instruction, vector_map_->Get(r), nullptr, type);
Aart Bik6daebeb2017-04-03 14:35:41 -07001252 }
1253 return true;
1254 }
1255 return false;
1256 }
Aart Bikc8e93c72017-05-10 10:49:22 -07001257 case Intrinsics::kMathMinIntInt:
1258 case Intrinsics::kMathMinLongLong:
1259 case Intrinsics::kMathMinFloatFloat:
1260 case Intrinsics::kMathMinDoubleDouble:
1261 case Intrinsics::kMathMaxIntInt:
1262 case Intrinsics::kMathMaxLongLong:
1263 case Intrinsics::kMathMaxFloatFloat:
1264 case Intrinsics::kMathMaxDoubleDouble: {
1265 // Deal with vector restrictions.
Nicolas Geoffray92316902017-05-23 08:06:07 +00001266 HInstruction* opa = instruction->InputAt(0);
1267 HInstruction* opb = instruction->InputAt(1);
Aart Bik304c8a52017-05-23 11:01:13 -07001268 HInstruction* r = opa;
1269 HInstruction* s = opb;
1270 bool is_unsigned = false;
1271 if (HasVectorRestrictions(restrictions, kNoMinMax)) {
1272 return false;
1273 } else if (HasVectorRestrictions(restrictions, kNoHiBits) &&
1274 !IsNarrowerOperands(opa, opb, type, &r, &s, &is_unsigned)) {
1275 return false; // reject, unless all operands are same-extension narrower
1276 }
1277 // Accept MIN/MAX(x, y) for vectorizable operands.
Aart Bikdbbac8f2017-09-01 13:06:08 -07001278 DCHECK(r != nullptr);
1279 DCHECK(s != nullptr);
Aart Bik304c8a52017-05-23 11:01:13 -07001280 if (generate_code && vector_mode_ != kVector) { // de-idiom
1281 r = opa;
1282 s = opb;
1283 }
1284 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
1285 VectorizeUse(node, s, generate_code, type, restrictions)) {
Aart Bikc8e93c72017-05-10 10:49:22 -07001286 if (generate_code) {
Aart Bik304c8a52017-05-23 11:01:13 -07001287 GenerateVecOp(
1288 instruction, vector_map_->Get(r), vector_map_->Get(s), type, is_unsigned);
Aart Bikc8e93c72017-05-10 10:49:22 -07001289 }
1290 return true;
1291 }
1292 return false;
1293 }
Aart Bik6daebeb2017-04-03 14:35:41 -07001294 default:
1295 return false;
1296 } // switch
Aart Bik281c6812016-08-26 11:31:48 -07001297 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08001298 return false;
Aart Bik281c6812016-08-26 11:31:48 -07001299}
1300
Aart Bikf8f5a162017-02-06 15:35:29 -08001301bool HLoopOptimization::TrySetVectorType(Primitive::Type type, uint64_t* restrictions) {
1302 const InstructionSetFeatures* features = compiler_driver_->GetInstructionSetFeatures();
1303 switch (compiler_driver_->GetInstructionSet()) {
1304 case kArm:
1305 case kThumb2:
Artem Serov8f7c4102017-06-21 11:21:37 +01001306 // Allow vectorization for all ARM devices, because Android assumes that
Aart Bikb29f6842017-07-28 15:58:41 -07001307 // ARM 32-bit always supports advanced SIMD (64-bit SIMD).
Artem Serov8f7c4102017-06-21 11:21:37 +01001308 switch (type) {
1309 case Primitive::kPrimBoolean:
1310 case Primitive::kPrimByte:
Aart Bik0148de42017-09-05 09:25:01 -07001311 *restrictions |= kNoDiv | kNoReduction;
Artem Serov8f7c4102017-06-21 11:21:37 +01001312 return TrySetVectorLength(8);
1313 case Primitive::kPrimChar:
1314 case Primitive::kPrimShort:
Aart Bik0148de42017-09-05 09:25:01 -07001315 *restrictions |= kNoDiv | kNoStringCharAt | kNoReduction;
Artem Serov8f7c4102017-06-21 11:21:37 +01001316 return TrySetVectorLength(4);
1317 case Primitive::kPrimInt:
Aart Bik0148de42017-09-05 09:25:01 -07001318 *restrictions |= kNoDiv | kNoReduction;
Artem Serov8f7c4102017-06-21 11:21:37 +01001319 return TrySetVectorLength(2);
1320 default:
1321 break;
1322 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001323 return false;
1324 case kArm64:
1325 // Allow vectorization for all ARM devices, because Android assumes that
Aart Bikb29f6842017-07-28 15:58:41 -07001326 // ARMv8 AArch64 always supports advanced SIMD (128-bit SIMD).
Aart Bikf8f5a162017-02-06 15:35:29 -08001327 switch (type) {
1328 case Primitive::kPrimBoolean:
1329 case Primitive::kPrimByte:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001330 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +01001331 return TrySetVectorLength(16);
Aart Bikf8f5a162017-02-06 15:35:29 -08001332 case Primitive::kPrimChar:
1333 case Primitive::kPrimShort:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001334 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +01001335 return TrySetVectorLength(8);
Aart Bikf8f5a162017-02-06 15:35:29 -08001336 case Primitive::kPrimInt:
1337 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +01001338 return TrySetVectorLength(4);
Artem Serovb31f91f2017-04-05 11:31:19 +01001339 case Primitive::kPrimLong:
Aart Bikc8e93c72017-05-10 10:49:22 -07001340 *restrictions |= kNoDiv | kNoMul | kNoMinMax;
Aart Bikf8f5a162017-02-06 15:35:29 -08001341 return TrySetVectorLength(2);
1342 case Primitive::kPrimFloat:
Aart Bik0148de42017-09-05 09:25:01 -07001343 *restrictions |= kNoReduction;
Artem Serovd4bccf12017-04-03 18:47:32 +01001344 return TrySetVectorLength(4);
Artem Serovb31f91f2017-04-05 11:31:19 +01001345 case Primitive::kPrimDouble:
Aart Bik0148de42017-09-05 09:25:01 -07001346 *restrictions |= kNoReduction;
Aart Bikf8f5a162017-02-06 15:35:29 -08001347 return TrySetVectorLength(2);
1348 default:
1349 return false;
1350 }
1351 case kX86:
1352 case kX86_64:
Aart Bikb29f6842017-07-28 15:58:41 -07001353 // Allow vectorization for SSE4.1-enabled X86 devices only (128-bit SIMD).
Aart Bikf8f5a162017-02-06 15:35:29 -08001354 if (features->AsX86InstructionSetFeatures()->HasSSE4_1()) {
1355 switch (type) {
1356 case Primitive::kPrimBoolean:
1357 case Primitive::kPrimByte:
Aart Bik0148de42017-09-05 09:25:01 -07001358 *restrictions |=
Aart Bikdbbac8f2017-09-01 13:06:08 -07001359 kNoMul | kNoDiv | kNoShift | kNoAbs | kNoSignedHAdd | kNoUnroundedHAdd | kNoSAD;
Aart Bikf8f5a162017-02-06 15:35:29 -08001360 return TrySetVectorLength(16);
1361 case Primitive::kPrimChar:
1362 case Primitive::kPrimShort:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001363 *restrictions |= kNoDiv | kNoAbs | kNoSignedHAdd | kNoUnroundedHAdd | kNoSAD;
Aart Bikf8f5a162017-02-06 15:35:29 -08001364 return TrySetVectorLength(8);
1365 case Primitive::kPrimInt:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001366 *restrictions |= kNoDiv | kNoSAD;
Aart Bikf8f5a162017-02-06 15:35:29 -08001367 return TrySetVectorLength(4);
1368 case Primitive::kPrimLong:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001369 *restrictions |= kNoMul | kNoDiv | kNoShr | kNoAbs | kNoMinMax | kNoSAD;
Aart Bikf8f5a162017-02-06 15:35:29 -08001370 return TrySetVectorLength(2);
1371 case Primitive::kPrimFloat:
Aart Bik0148de42017-09-05 09:25:01 -07001372 *restrictions |= kNoMinMax | kNoReduction; // minmax: -0.0 vs +0.0
Aart Bikf8f5a162017-02-06 15:35:29 -08001373 return TrySetVectorLength(4);
1374 case Primitive::kPrimDouble:
Aart Bik0148de42017-09-05 09:25:01 -07001375 *restrictions |= kNoMinMax | kNoReduction; // minmax: -0.0 vs +0.0
Aart Bikf8f5a162017-02-06 15:35:29 -08001376 return TrySetVectorLength(2);
1377 default:
1378 break;
1379 } // switch type
1380 }
1381 return false;
1382 case kMips:
Lena Djokic51765b02017-06-22 13:49:59 +02001383 if (features->AsMipsInstructionSetFeatures()->HasMsa()) {
1384 switch (type) {
1385 case Primitive::kPrimBoolean:
1386 case Primitive::kPrimByte:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001387 *restrictions |= kNoDiv | kNoReduction | kNoSAD;
Lena Djokic51765b02017-06-22 13:49:59 +02001388 return TrySetVectorLength(16);
1389 case Primitive::kPrimChar:
1390 case Primitive::kPrimShort:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001391 *restrictions |= kNoDiv | kNoStringCharAt | kNoReduction | kNoSAD;
Lena Djokic51765b02017-06-22 13:49:59 +02001392 return TrySetVectorLength(8);
1393 case Primitive::kPrimInt:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001394 *restrictions |= kNoDiv | kNoReduction | kNoSAD;
Lena Djokic51765b02017-06-22 13:49:59 +02001395 return TrySetVectorLength(4);
1396 case Primitive::kPrimLong:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001397 *restrictions |= kNoDiv | kNoReduction | kNoSAD;
Lena Djokic51765b02017-06-22 13:49:59 +02001398 return TrySetVectorLength(2);
1399 case Primitive::kPrimFloat:
Aart Bik0148de42017-09-05 09:25:01 -07001400 *restrictions |= kNoMinMax | kNoReduction; // min/max(x, NaN)
Lena Djokic51765b02017-06-22 13:49:59 +02001401 return TrySetVectorLength(4);
1402 case Primitive::kPrimDouble:
Aart Bik0148de42017-09-05 09:25:01 -07001403 *restrictions |= kNoMinMax | kNoReduction; // min/max(x, NaN)
Lena Djokic51765b02017-06-22 13:49:59 +02001404 return TrySetVectorLength(2);
1405 default:
1406 break;
1407 } // switch type
1408 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001409 return false;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001410 case kMips64:
1411 if (features->AsMips64InstructionSetFeatures()->HasMsa()) {
1412 switch (type) {
1413 case Primitive::kPrimBoolean:
1414 case Primitive::kPrimByte:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001415 *restrictions |= kNoDiv | kNoReduction | kNoSAD;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001416 return TrySetVectorLength(16);
1417 case Primitive::kPrimChar:
1418 case Primitive::kPrimShort:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001419 *restrictions |= kNoDiv | kNoStringCharAt | kNoReduction | kNoSAD;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001420 return TrySetVectorLength(8);
1421 case Primitive::kPrimInt:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001422 *restrictions |= kNoDiv | kNoReduction | kNoSAD;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001423 return TrySetVectorLength(4);
1424 case Primitive::kPrimLong:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001425 *restrictions |= kNoDiv | kNoReduction | kNoSAD;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001426 return TrySetVectorLength(2);
1427 case Primitive::kPrimFloat:
Aart Bik0148de42017-09-05 09:25:01 -07001428 *restrictions |= kNoMinMax | kNoReduction; // min/max(x, NaN)
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001429 return TrySetVectorLength(4);
1430 case Primitive::kPrimDouble:
Aart Bik0148de42017-09-05 09:25:01 -07001431 *restrictions |= kNoMinMax | kNoReduction; // min/max(x, NaN)
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001432 return TrySetVectorLength(2);
1433 default:
1434 break;
1435 } // switch type
1436 }
1437 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001438 default:
1439 return false;
1440 } // switch instruction set
1441}
1442
1443bool HLoopOptimization::TrySetVectorLength(uint32_t length) {
1444 DCHECK(IsPowerOfTwo(length) && length >= 2u);
1445 // First time set?
1446 if (vector_length_ == 0) {
1447 vector_length_ = length;
1448 }
1449 // Different types are acceptable within a loop-body, as long as all the corresponding vector
1450 // lengths match exactly to obtain a uniform traversal through the vector iteration space
1451 // (idiomatic exceptions to this rule can be handled by further unrolling sub-expressions).
1452 return vector_length_ == length;
1453}
1454
1455void HLoopOptimization::GenerateVecInv(HInstruction* org, Primitive::Type type) {
1456 if (vector_map_->find(org) == vector_map_->end()) {
1457 // In scalar code, just use a self pass-through for scalar invariants
1458 // (viz. expression remains itself).
1459 if (vector_mode_ == kSequential) {
1460 vector_map_->Put(org, org);
1461 return;
1462 }
1463 // In vector code, explicit scalar expansion is needed.
Aart Bik0148de42017-09-05 09:25:01 -07001464 HInstruction* vector = nullptr;
1465 auto it = vector_permanent_map_->find(org);
1466 if (it != vector_permanent_map_->end()) {
1467 vector = it->second; // reuse during unrolling
1468 } else {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001469 // Generates ReplicateScalar( (optional_type_conv) org ).
1470 HInstruction* input = org;
1471 Primitive::Type input_type = input->GetType();
1472 if (type != input_type && (type == Primitive::kPrimLong ||
1473 input_type == Primitive::kPrimLong)) {
1474 input = Insert(vector_preheader_,
1475 new (global_allocator_) HTypeConversion(type, input, kNoDexPc));
1476 }
1477 vector = new (global_allocator_)
1478 HVecReplicateScalar(global_allocator_, input, type, vector_length_);
Aart Bik0148de42017-09-05 09:25:01 -07001479 vector_permanent_map_->Put(org, Insert(vector_preheader_, vector));
1480 }
1481 vector_map_->Put(org, vector);
Aart Bikf8f5a162017-02-06 15:35:29 -08001482 }
1483}
1484
1485void HLoopOptimization::GenerateVecSub(HInstruction* org, HInstruction* offset) {
1486 if (vector_map_->find(org) == vector_map_->end()) {
Aart Bik14a68b42017-06-08 14:06:58 -07001487 HInstruction* subscript = vector_index_;
Aart Bik37dc4df2017-06-28 14:08:00 -07001488 int64_t value = 0;
1489 if (!IsInt64AndGet(offset, &value) || value != 0) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001490 subscript = new (global_allocator_) HAdd(Primitive::kPrimInt, subscript, offset);
1491 if (org->IsPhi()) {
1492 Insert(vector_body_, subscript); // lacks layout placeholder
1493 }
1494 }
1495 vector_map_->Put(org, subscript);
1496 }
1497}
1498
1499void HLoopOptimization::GenerateVecMem(HInstruction* org,
1500 HInstruction* opa,
1501 HInstruction* opb,
Aart Bik14a68b42017-06-08 14:06:58 -07001502 HInstruction* offset,
Aart Bikf8f5a162017-02-06 15:35:29 -08001503 Primitive::Type type) {
1504 HInstruction* vector = nullptr;
1505 if (vector_mode_ == kVector) {
1506 // Vector store or load.
Aart Bik14a68b42017-06-08 14:06:58 -07001507 HInstruction* base = org->InputAt(0);
Aart Bikf8f5a162017-02-06 15:35:29 -08001508 if (opb != nullptr) {
1509 vector = new (global_allocator_) HVecStore(
Aart Bik14a68b42017-06-08 14:06:58 -07001510 global_allocator_, base, opa, opb, type, vector_length_);
Aart Bikf8f5a162017-02-06 15:35:29 -08001511 } else {
Aart Bikdb14fcf2017-04-25 15:53:58 -07001512 bool is_string_char_at = org->AsArrayGet()->IsStringCharAt();
Aart Bikf8f5a162017-02-06 15:35:29 -08001513 vector = new (global_allocator_) HVecLoad(
Aart Bik14a68b42017-06-08 14:06:58 -07001514 global_allocator_, base, opa, type, vector_length_, is_string_char_at);
1515 }
1516 // Known dynamically enforced alignment?
Aart Bik14a68b42017-06-08 14:06:58 -07001517 if (vector_peeling_candidate_ != nullptr &&
1518 vector_peeling_candidate_->base == base &&
1519 vector_peeling_candidate_->offset == offset) {
1520 vector->AsVecMemoryOperation()->SetAlignment(Alignment(kAlignedBase, 0));
Aart Bikf8f5a162017-02-06 15:35:29 -08001521 }
1522 } else {
1523 // Scalar store or load.
1524 DCHECK(vector_mode_ == kSequential);
1525 if (opb != nullptr) {
1526 vector = new (global_allocator_) HArraySet(org->InputAt(0), opa, opb, type, kNoDexPc);
1527 } else {
Aart Bikdb14fcf2017-04-25 15:53:58 -07001528 bool is_string_char_at = org->AsArrayGet()->IsStringCharAt();
1529 vector = new (global_allocator_) HArrayGet(
1530 org->InputAt(0), opa, type, kNoDexPc, is_string_char_at);
Aart Bikf8f5a162017-02-06 15:35:29 -08001531 }
1532 }
1533 vector_map_->Put(org, vector);
1534}
1535
Aart Bik0148de42017-09-05 09:25:01 -07001536void HLoopOptimization::GenerateVecReductionPhi(HPhi* phi) {
1537 DCHECK(reductions_->find(phi) != reductions_->end());
1538 DCHECK(reductions_->Get(phi->InputAt(1)) == phi);
1539 HInstruction* vector = nullptr;
1540 if (vector_mode_ == kSequential) {
1541 HPhi* new_phi = new (global_allocator_) HPhi(
1542 global_allocator_, kNoRegNumber, 0, phi->GetType());
1543 vector_header_->AddPhi(new_phi);
1544 vector = new_phi;
1545 } else {
1546 // Link vector reduction back to prior unrolled update, or a first phi.
1547 auto it = vector_permanent_map_->find(phi);
1548 if (it != vector_permanent_map_->end()) {
1549 vector = it->second;
1550 } else {
1551 HPhi* new_phi = new (global_allocator_) HPhi(
1552 global_allocator_, kNoRegNumber, 0, HVecOperation::kSIMDType);
1553 vector_header_->AddPhi(new_phi);
1554 vector = new_phi;
1555 }
1556 }
1557 vector_map_->Put(phi, vector);
1558}
1559
1560void HLoopOptimization::GenerateVecReductionPhiInputs(HPhi* phi, HInstruction* reduction) {
1561 HInstruction* new_phi = vector_map_->Get(phi);
1562 HInstruction* new_init = reductions_->Get(phi);
1563 HInstruction* new_red = vector_map_->Get(reduction);
1564 // Link unrolled vector loop back to new phi.
1565 for (; !new_phi->IsPhi(); new_phi = vector_permanent_map_->Get(new_phi)) {
1566 DCHECK(new_phi->IsVecOperation());
1567 }
1568 // Prepare the new initialization.
1569 if (vector_mode_ == kVector) {
1570 // Generate a [initial, 0, .., 0] vector.
Aart Bikdbbac8f2017-09-01 13:06:08 -07001571 HVecOperation* red_vector = new_red->AsVecOperation();
1572 size_t vector_length = red_vector->GetVectorLength();
1573 Primitive::Type type = red_vector->GetPackedType();
1574 new_init = Insert(vector_preheader_,
1575 new (global_allocator_) HVecSetScalars(global_allocator_,
1576 &new_init,
1577 type,
1578 vector_length,
1579 1));
Aart Bik0148de42017-09-05 09:25:01 -07001580 } else {
1581 new_init = ReduceAndExtractIfNeeded(new_init);
1582 }
1583 // Set the phi inputs.
1584 DCHECK(new_phi->IsPhi());
1585 new_phi->AsPhi()->AddInput(new_init);
1586 new_phi->AsPhi()->AddInput(new_red);
1587 // New feed value for next phi (safe mutation in iteration).
1588 reductions_->find(phi)->second = new_phi;
1589}
1590
1591HInstruction* HLoopOptimization::ReduceAndExtractIfNeeded(HInstruction* instruction) {
1592 if (instruction->IsPhi()) {
1593 HInstruction* input = instruction->InputAt(1);
1594 if (input->IsVecOperation()) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001595 HVecOperation* input_vector = input->AsVecOperation();
1596 size_t vector_length = input_vector->GetVectorLength();
1597 Primitive::Type type = input_vector->GetPackedType();
1598 HVecReduce::ReductionKind kind = GetReductionKind(input_vector);
Aart Bik0148de42017-09-05 09:25:01 -07001599 HBasicBlock* exit = instruction->GetBlock()->GetSuccessors()[0];
1600 // Generate a vector reduction and scalar extract
1601 // x = REDUCE( [x_1, .., x_n] )
1602 // y = x_1
1603 // along the exit of the defining loop.
Aart Bik0148de42017-09-05 09:25:01 -07001604 HInstruction* reduce = new (global_allocator_) HVecReduce(
Aart Bikdbbac8f2017-09-01 13:06:08 -07001605 global_allocator_, instruction, type, vector_length, kind);
Aart Bik0148de42017-09-05 09:25:01 -07001606 exit->InsertInstructionBefore(reduce, exit->GetFirstInstruction());
1607 instruction = new (global_allocator_) HVecExtractScalar(
Aart Bikdbbac8f2017-09-01 13:06:08 -07001608 global_allocator_, reduce, type, vector_length, 0);
Aart Bik0148de42017-09-05 09:25:01 -07001609 exit->InsertInstructionAfter(instruction, reduce);
1610 }
1611 }
1612 return instruction;
1613}
1614
Aart Bikf8f5a162017-02-06 15:35:29 -08001615#define GENERATE_VEC(x, y) \
1616 if (vector_mode_ == kVector) { \
1617 vector = (x); \
1618 } else { \
1619 DCHECK(vector_mode_ == kSequential); \
1620 vector = (y); \
1621 } \
1622 break;
1623
1624void HLoopOptimization::GenerateVecOp(HInstruction* org,
1625 HInstruction* opa,
1626 HInstruction* opb,
Aart Bik304c8a52017-05-23 11:01:13 -07001627 Primitive::Type type,
1628 bool is_unsigned) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001629 HInstruction* vector = nullptr;
Aart Bikdbbac8f2017-09-01 13:06:08 -07001630 Primitive::Type org_type = org->GetType();
Aart Bikf8f5a162017-02-06 15:35:29 -08001631 switch (org->GetKind()) {
1632 case HInstruction::kNeg:
1633 DCHECK(opb == nullptr);
1634 GENERATE_VEC(
1635 new (global_allocator_) HVecNeg(global_allocator_, opa, type, vector_length_),
Aart Bikdbbac8f2017-09-01 13:06:08 -07001636 new (global_allocator_) HNeg(org_type, opa));
Aart Bikf8f5a162017-02-06 15:35:29 -08001637 case HInstruction::kNot:
1638 DCHECK(opb == nullptr);
1639 GENERATE_VEC(
1640 new (global_allocator_) HVecNot(global_allocator_, opa, type, vector_length_),
Aart Bikdbbac8f2017-09-01 13:06:08 -07001641 new (global_allocator_) HNot(org_type, opa));
Aart Bikf8f5a162017-02-06 15:35:29 -08001642 case HInstruction::kBooleanNot:
1643 DCHECK(opb == nullptr);
1644 GENERATE_VEC(
1645 new (global_allocator_) HVecNot(global_allocator_, opa, type, vector_length_),
1646 new (global_allocator_) HBooleanNot(opa));
1647 case HInstruction::kTypeConversion:
1648 DCHECK(opb == nullptr);
1649 GENERATE_VEC(
1650 new (global_allocator_) HVecCnv(global_allocator_, opa, type, vector_length_),
Aart Bikdbbac8f2017-09-01 13:06:08 -07001651 new (global_allocator_) HTypeConversion(org_type, opa, kNoDexPc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001652 case HInstruction::kAdd:
1653 GENERATE_VEC(
1654 new (global_allocator_) HVecAdd(global_allocator_, opa, opb, type, vector_length_),
Aart Bikdbbac8f2017-09-01 13:06:08 -07001655 new (global_allocator_) HAdd(org_type, opa, opb));
Aart Bikf8f5a162017-02-06 15:35:29 -08001656 case HInstruction::kSub:
1657 GENERATE_VEC(
1658 new (global_allocator_) HVecSub(global_allocator_, opa, opb, type, vector_length_),
Aart Bikdbbac8f2017-09-01 13:06:08 -07001659 new (global_allocator_) HSub(org_type, opa, opb));
Aart Bikf8f5a162017-02-06 15:35:29 -08001660 case HInstruction::kMul:
1661 GENERATE_VEC(
1662 new (global_allocator_) HVecMul(global_allocator_, opa, opb, type, vector_length_),
Aart Bikdbbac8f2017-09-01 13:06:08 -07001663 new (global_allocator_) HMul(org_type, opa, opb));
Aart Bikf8f5a162017-02-06 15:35:29 -08001664 case HInstruction::kDiv:
1665 GENERATE_VEC(
1666 new (global_allocator_) HVecDiv(global_allocator_, opa, opb, type, vector_length_),
Aart Bikdbbac8f2017-09-01 13:06:08 -07001667 new (global_allocator_) HDiv(org_type, opa, opb, kNoDexPc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001668 case HInstruction::kAnd:
1669 GENERATE_VEC(
1670 new (global_allocator_) HVecAnd(global_allocator_, opa, opb, type, vector_length_),
Aart Bikdbbac8f2017-09-01 13:06:08 -07001671 new (global_allocator_) HAnd(org_type, opa, opb));
Aart Bikf8f5a162017-02-06 15:35:29 -08001672 case HInstruction::kOr:
1673 GENERATE_VEC(
1674 new (global_allocator_) HVecOr(global_allocator_, opa, opb, type, vector_length_),
Aart Bikdbbac8f2017-09-01 13:06:08 -07001675 new (global_allocator_) HOr(org_type, opa, opb));
Aart Bikf8f5a162017-02-06 15:35:29 -08001676 case HInstruction::kXor:
1677 GENERATE_VEC(
1678 new (global_allocator_) HVecXor(global_allocator_, opa, opb, type, vector_length_),
Aart Bikdbbac8f2017-09-01 13:06:08 -07001679 new (global_allocator_) HXor(org_type, opa, opb));
Aart Bikf8f5a162017-02-06 15:35:29 -08001680 case HInstruction::kShl:
1681 GENERATE_VEC(
1682 new (global_allocator_) HVecShl(global_allocator_, opa, opb, type, vector_length_),
Aart Bikdbbac8f2017-09-01 13:06:08 -07001683 new (global_allocator_) HShl(org_type, opa, opb));
Aart Bikf8f5a162017-02-06 15:35:29 -08001684 case HInstruction::kShr:
1685 GENERATE_VEC(
1686 new (global_allocator_) HVecShr(global_allocator_, opa, opb, type, vector_length_),
Aart Bikdbbac8f2017-09-01 13:06:08 -07001687 new (global_allocator_) HShr(org_type, opa, opb));
Aart Bikf8f5a162017-02-06 15:35:29 -08001688 case HInstruction::kUShr:
1689 GENERATE_VEC(
1690 new (global_allocator_) HVecUShr(global_allocator_, opa, opb, type, vector_length_),
Aart Bikdbbac8f2017-09-01 13:06:08 -07001691 new (global_allocator_) HUShr(org_type, opa, opb));
Aart Bikf8f5a162017-02-06 15:35:29 -08001692 case HInstruction::kInvokeStaticOrDirect: {
Aart Bik6daebeb2017-04-03 14:35:41 -07001693 HInvokeStaticOrDirect* invoke = org->AsInvokeStaticOrDirect();
1694 if (vector_mode_ == kVector) {
1695 switch (invoke->GetIntrinsic()) {
1696 case Intrinsics::kMathAbsInt:
1697 case Intrinsics::kMathAbsLong:
1698 case Intrinsics::kMathAbsFloat:
1699 case Intrinsics::kMathAbsDouble:
1700 DCHECK(opb == nullptr);
1701 vector = new (global_allocator_) HVecAbs(global_allocator_, opa, type, vector_length_);
1702 break;
Aart Bikc8e93c72017-05-10 10:49:22 -07001703 case Intrinsics::kMathMinIntInt:
1704 case Intrinsics::kMathMinLongLong:
1705 case Intrinsics::kMathMinFloatFloat:
1706 case Intrinsics::kMathMinDoubleDouble: {
Aart Bikc8e93c72017-05-10 10:49:22 -07001707 vector = new (global_allocator_)
1708 HVecMin(global_allocator_, opa, opb, type, vector_length_, is_unsigned);
1709 break;
1710 }
1711 case Intrinsics::kMathMaxIntInt:
1712 case Intrinsics::kMathMaxLongLong:
1713 case Intrinsics::kMathMaxFloatFloat:
1714 case Intrinsics::kMathMaxDoubleDouble: {
Aart Bikc8e93c72017-05-10 10:49:22 -07001715 vector = new (global_allocator_)
1716 HVecMax(global_allocator_, opa, opb, type, vector_length_, is_unsigned);
1717 break;
1718 }
Aart Bik6daebeb2017-04-03 14:35:41 -07001719 default:
1720 LOG(FATAL) << "Unsupported SIMD intrinsic";
1721 UNREACHABLE();
1722 } // switch invoke
1723 } else {
Aart Bik24b905f2017-04-06 09:59:06 -07001724 // In scalar code, simply clone the method invoke, and replace its operands with the
1725 // corresponding new scalar instructions in the loop. The instruction will get an
1726 // environment while being inserted from the instruction map in original program order.
Aart Bik6daebeb2017-04-03 14:35:41 -07001727 DCHECK(vector_mode_ == kSequential);
Aart Bik6e92fb32017-06-05 14:05:09 -07001728 size_t num_args = invoke->GetNumberOfArguments();
Aart Bik6daebeb2017-04-03 14:35:41 -07001729 HInvokeStaticOrDirect* new_invoke = new (global_allocator_) HInvokeStaticOrDirect(
1730 global_allocator_,
Aart Bik6e92fb32017-06-05 14:05:09 -07001731 num_args,
Aart Bik6daebeb2017-04-03 14:35:41 -07001732 invoke->GetType(),
1733 invoke->GetDexPc(),
1734 invoke->GetDexMethodIndex(),
1735 invoke->GetResolvedMethod(),
1736 invoke->GetDispatchInfo(),
1737 invoke->GetInvokeType(),
1738 invoke->GetTargetMethod(),
1739 invoke->GetClinitCheckRequirement());
1740 HInputsRef inputs = invoke->GetInputs();
Aart Bik6e92fb32017-06-05 14:05:09 -07001741 size_t num_inputs = inputs.size();
1742 DCHECK_LE(num_args, num_inputs);
1743 DCHECK_EQ(num_inputs, new_invoke->GetInputs().size()); // both invokes agree
1744 for (size_t index = 0; index < num_inputs; ++index) {
1745 HInstruction* new_input = index < num_args
1746 ? vector_map_->Get(inputs[index])
1747 : inputs[index]; // beyond arguments: just pass through
1748 new_invoke->SetArgumentAt(index, new_input);
Aart Bik6daebeb2017-04-03 14:35:41 -07001749 }
Aart Bik98990262017-04-10 13:15:57 -07001750 new_invoke->SetIntrinsic(invoke->GetIntrinsic(),
1751 kNeedsEnvironmentOrCache,
1752 kNoSideEffects,
1753 kNoThrow);
Aart Bik6daebeb2017-04-03 14:35:41 -07001754 vector = new_invoke;
1755 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001756 break;
1757 }
1758 default:
1759 break;
1760 } // switch
1761 CHECK(vector != nullptr) << "Unsupported SIMD operator";
1762 vector_map_->Put(org, vector);
1763}
1764
1765#undef GENERATE_VEC
1766
1767//
Aart Bikf3e61ee2017-04-12 17:09:20 -07001768// Vectorization idioms.
1769//
1770
1771// Method recognizes the following idioms:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001772// rounding halving add (a + b + 1) >> 1 for unsigned/signed operands a, b
1773// truncated halving add (a + b) >> 1 for unsigned/signed operands a, b
Aart Bikf3e61ee2017-04-12 17:09:20 -07001774// Provided that the operands are promoted to a wider form to do the arithmetic and
1775// then cast back to narrower form, the idioms can be mapped into efficient SIMD
1776// implementation that operates directly in narrower form (plus one extra bit).
1777// TODO: current version recognizes implicit byte/short/char widening only;
1778// explicit widening from int to long could be added later.
1779bool HLoopOptimization::VectorizeHalvingAddIdiom(LoopNode* node,
1780 HInstruction* instruction,
1781 bool generate_code,
1782 Primitive::Type type,
1783 uint64_t restrictions) {
1784 // Test for top level arithmetic shift right x >> 1 or logical shift right x >>> 1
Aart Bik304c8a52017-05-23 11:01:13 -07001785 // (note whether the sign bit in wider precision is shifted in has no effect
Aart Bikf3e61ee2017-04-12 17:09:20 -07001786 // on the narrow precision computed by the idiom).
Aart Bikf3e61ee2017-04-12 17:09:20 -07001787 if ((instruction->IsShr() ||
1788 instruction->IsUShr()) &&
Aart Bik0148de42017-09-05 09:25:01 -07001789 IsInt64Value(instruction->InputAt(1), 1)) {
Aart Bik5f805002017-05-16 16:42:41 -07001790 // Test for (a + b + c) >> 1 for optional constant c.
1791 HInstruction* a = nullptr;
1792 HInstruction* b = nullptr;
1793 int64_t c = 0;
1794 if (IsAddConst(instruction->InputAt(0), /*out*/ &a, /*out*/ &b, /*out*/ &c)) {
Aart Bik304c8a52017-05-23 11:01:13 -07001795 DCHECK(a != nullptr && b != nullptr);
Aart Bik5f805002017-05-16 16:42:41 -07001796 // Accept c == 1 (rounded) or c == 0 (not rounded).
1797 bool is_rounded = false;
1798 if (c == 1) {
1799 is_rounded = true;
1800 } else if (c != 0) {
1801 return false;
1802 }
1803 // Accept consistent zero or sign extension on operands a and b.
Aart Bikf3e61ee2017-04-12 17:09:20 -07001804 HInstruction* r = nullptr;
1805 HInstruction* s = nullptr;
1806 bool is_unsigned = false;
Aart Bik304c8a52017-05-23 11:01:13 -07001807 if (!IsNarrowerOperands(a, b, type, &r, &s, &is_unsigned)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -07001808 return false;
1809 }
1810 // Deal with vector restrictions.
1811 if ((!is_unsigned && HasVectorRestrictions(restrictions, kNoSignedHAdd)) ||
1812 (!is_rounded && HasVectorRestrictions(restrictions, kNoUnroundedHAdd))) {
1813 return false;
1814 }
1815 // Accept recognized halving add for vectorizable operands. Vectorized code uses the
1816 // shorthand idiomatic operation. Sequential code uses the original scalar expressions.
Aart Bikdbbac8f2017-09-01 13:06:08 -07001817 DCHECK(r != nullptr);
1818 DCHECK(s != nullptr);
Aart Bik304c8a52017-05-23 11:01:13 -07001819 if (generate_code && vector_mode_ != kVector) { // de-idiom
1820 r = instruction->InputAt(0);
1821 s = instruction->InputAt(1);
1822 }
Aart Bikf3e61ee2017-04-12 17:09:20 -07001823 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
1824 VectorizeUse(node, s, generate_code, type, restrictions)) {
1825 if (generate_code) {
1826 if (vector_mode_ == kVector) {
1827 vector_map_->Put(instruction, new (global_allocator_) HVecHalvingAdd(
1828 global_allocator_,
1829 vector_map_->Get(r),
1830 vector_map_->Get(s),
1831 type,
1832 vector_length_,
1833 is_unsigned,
1834 is_rounded));
Aart Bik21b85922017-09-06 13:29:16 -07001835 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorizedIdiom);
Aart Bikf3e61ee2017-04-12 17:09:20 -07001836 } else {
Aart Bik304c8a52017-05-23 11:01:13 -07001837 GenerateVecOp(instruction, vector_map_->Get(r), vector_map_->Get(s), type);
Aart Bikf3e61ee2017-04-12 17:09:20 -07001838 }
1839 }
1840 return true;
1841 }
1842 }
1843 }
1844 return false;
1845}
1846
Aart Bikdbbac8f2017-09-01 13:06:08 -07001847// Method recognizes the following idiom:
1848// q += ABS(a - b) for signed operands a, b
1849// Provided that the operands have the same type or are promoted to a wider form.
1850// Since this may involve a vector length change, the idiom is handled by going directly
1851// to a sad-accumulate node (rather than relying combining finer grained nodes later).
1852// TODO: unsigned SAD too?
1853bool HLoopOptimization::VectorizeSADIdiom(LoopNode* node,
1854 HInstruction* instruction,
1855 bool generate_code,
1856 Primitive::Type reduction_type,
1857 uint64_t restrictions) {
1858 // Filter integral "q += ABS(a - b);" reduction, where ABS and SUB
1859 // are done in the same precision (either int or long).
1860 if (!instruction->IsAdd() ||
1861 (reduction_type != Primitive::kPrimInt && reduction_type != Primitive::kPrimLong)) {
1862 return false;
1863 }
1864 HInstruction* q = instruction->InputAt(0);
1865 HInstruction* v = instruction->InputAt(1);
1866 HInstruction* a = nullptr;
1867 HInstruction* b = nullptr;
1868 if (v->IsInvokeStaticOrDirect() &&
1869 (v->AsInvokeStaticOrDirect()->GetIntrinsic() == Intrinsics::kMathAbsInt ||
1870 v->AsInvokeStaticOrDirect()->GetIntrinsic() == Intrinsics::kMathAbsLong)) {
1871 HInstruction* x = v->InputAt(0);
1872 if (x->IsSub() && x->GetType() == reduction_type) {
1873 a = x->InputAt(0);
1874 b = x->InputAt(1);
1875 }
1876 }
1877 if (a == nullptr || b == nullptr) {
1878 return false;
1879 }
1880 // Accept same-type or consistent sign extension for narrower-type on operands a and b.
1881 // The same-type or narrower operands are called r (a or lower) and s (b or lower).
1882 HInstruction* r = a;
1883 HInstruction* s = b;
1884 bool is_unsigned = false;
1885 Primitive::Type sub_type = a->GetType();
1886 if (a->IsTypeConversion()) {
1887 sub_type = a->InputAt(0)->GetType();
1888 } else if (b->IsTypeConversion()) {
1889 sub_type = b->InputAt(0)->GetType();
1890 }
1891 if (reduction_type != sub_type &&
1892 (!IsNarrowerOperands(a, b, sub_type, &r, &s, &is_unsigned) || is_unsigned)) {
1893 return false;
1894 }
1895 // Try same/narrower type and deal with vector restrictions.
1896 if (!TrySetVectorType(sub_type, &restrictions) || HasVectorRestrictions(restrictions, kNoSAD)) {
1897 return false;
1898 }
1899 // Accept SAD idiom for vectorizable operands. Vectorized code uses the shorthand
1900 // idiomatic operation. Sequential code uses the original scalar expressions.
1901 DCHECK(r != nullptr);
1902 DCHECK(s != nullptr);
1903 if (generate_code && vector_mode_ != kVector) { // de-idiom
1904 r = s = v->InputAt(0);
1905 }
1906 if (VectorizeUse(node, q, generate_code, sub_type, restrictions) &&
1907 VectorizeUse(node, r, generate_code, sub_type, restrictions) &&
1908 VectorizeUse(node, s, generate_code, sub_type, restrictions)) {
1909 if (generate_code) {
1910 if (vector_mode_ == kVector) {
1911 vector_map_->Put(instruction, new (global_allocator_) HVecSADAccumulate(
1912 global_allocator_,
1913 vector_map_->Get(q),
1914 vector_map_->Get(r),
1915 vector_map_->Get(s),
1916 reduction_type,
1917 GetOtherVL(reduction_type, sub_type, vector_length_)));
1918 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorizedIdiom);
1919 } else {
1920 GenerateVecOp(v, vector_map_->Get(r), nullptr, reduction_type);
1921 GenerateVecOp(instruction, vector_map_->Get(q), vector_map_->Get(v), reduction_type);
1922 }
1923 }
1924 return true;
1925 }
1926 return false;
1927}
1928
Aart Bikf3e61ee2017-04-12 17:09:20 -07001929//
Aart Bik14a68b42017-06-08 14:06:58 -07001930// Vectorization heuristics.
1931//
1932
1933bool HLoopOptimization::IsVectorizationProfitable(int64_t trip_count) {
1934 // Current heuristic: non-empty body with sufficient number
1935 // of iterations (if known).
1936 // TODO: refine by looking at e.g. operation count, alignment, etc.
1937 if (vector_length_ == 0) {
1938 return false; // nothing found
1939 } else if (0 < trip_count && trip_count < vector_length_) {
1940 return false; // insufficient iterations
1941 }
1942 return true;
1943}
1944
Aart Bikb29f6842017-07-28 15:58:41 -07001945void HLoopOptimization::SetPeelingCandidate(const ArrayReference* candidate,
1946 int64_t trip_count ATTRIBUTE_UNUSED) {
Aart Bik14a68b42017-06-08 14:06:58 -07001947 // Current heuristic: none.
1948 // TODO: implement
Aart Bikb29f6842017-07-28 15:58:41 -07001949 vector_peeling_candidate_ = candidate;
Aart Bik14a68b42017-06-08 14:06:58 -07001950}
1951
Artem Serovf26bb6c2017-09-01 10:59:03 +01001952static constexpr uint32_t ARM64_SIMD_MAXIMUM_UNROLL_FACTOR = 8;
1953static constexpr uint32_t ARM64_SIMD_HEURISTIC_MAX_BODY_SIZE = 50;
1954
Aart Bik14a68b42017-06-08 14:06:58 -07001955uint32_t HLoopOptimization::GetUnrollingFactor(HBasicBlock* block, int64_t trip_count) {
Aart Bik14a68b42017-06-08 14:06:58 -07001956 switch (compiler_driver_->GetInstructionSet()) {
Artem Serovf26bb6c2017-09-01 10:59:03 +01001957 case kArm64: {
Aart Bik521b50f2017-09-09 10:44:45 -07001958 // Don't unroll with insufficient iterations.
Artem Serovf26bb6c2017-09-01 10:59:03 +01001959 // TODO: Unroll loops with unknown trip count.
Aart Bik521b50f2017-09-09 10:44:45 -07001960 DCHECK_NE(vector_length_, 0u);
Artem Serovf26bb6c2017-09-01 10:59:03 +01001961 if (trip_count < 2 * vector_length_) {
Aart Bik521b50f2017-09-09 10:44:45 -07001962 return kNoUnrollingFactor;
Aart Bik14a68b42017-06-08 14:06:58 -07001963 }
Aart Bik521b50f2017-09-09 10:44:45 -07001964 // Don't unroll for large loop body size.
Artem Serovf26bb6c2017-09-01 10:59:03 +01001965 uint32_t instruction_count = block->GetInstructions().CountSize();
Aart Bik521b50f2017-09-09 10:44:45 -07001966 if (instruction_count >= ARM64_SIMD_HEURISTIC_MAX_BODY_SIZE) {
1967 return kNoUnrollingFactor;
1968 }
Artem Serovf26bb6c2017-09-01 10:59:03 +01001969 // Find a beneficial unroll factor with the following restrictions:
1970 // - At least one iteration of the transformed loop should be executed.
1971 // - The loop body shouldn't be "too big" (heuristic).
1972 uint32_t uf1 = ARM64_SIMD_HEURISTIC_MAX_BODY_SIZE / instruction_count;
1973 uint32_t uf2 = trip_count / vector_length_;
1974 uint32_t unroll_factor =
1975 TruncToPowerOfTwo(std::min({uf1, uf2, ARM64_SIMD_MAXIMUM_UNROLL_FACTOR}));
1976 DCHECK_GE(unroll_factor, 1u);
Artem Serovf26bb6c2017-09-01 10:59:03 +01001977 return unroll_factor;
Aart Bik14a68b42017-06-08 14:06:58 -07001978 }
Artem Serovf26bb6c2017-09-01 10:59:03 +01001979 case kX86:
1980 case kX86_64:
Aart Bik14a68b42017-06-08 14:06:58 -07001981 default:
Aart Bik521b50f2017-09-09 10:44:45 -07001982 return kNoUnrollingFactor;
Aart Bik14a68b42017-06-08 14:06:58 -07001983 }
1984}
1985
1986//
Aart Bikf8f5a162017-02-06 15:35:29 -08001987// Helpers.
1988//
1989
1990bool HLoopOptimization::TrySetPhiInduction(HPhi* phi, bool restrict_uses) {
Aart Bikb29f6842017-07-28 15:58:41 -07001991 // Start with empty phi induction.
1992 iset_->clear();
1993
Nicolas Geoffrayf57c1ae2017-06-28 17:40:18 +01001994 // Special case Phis that have equivalent in a debuggable setup. Our graph checker isn't
1995 // smart enough to follow strongly connected components (and it's probably not worth
1996 // it to make it so). See b/33775412.
1997 if (graph_->IsDebuggable() && phi->HasEquivalentPhi()) {
1998 return false;
1999 }
Aart Bikb29f6842017-07-28 15:58:41 -07002000
2001 // Lookup phi induction cycle.
Aart Bikcc42be02016-10-20 16:14:16 -07002002 ArenaSet<HInstruction*>* set = induction_range_.LookupCycle(phi);
2003 if (set != nullptr) {
2004 for (HInstruction* i : *set) {
Aart Bike3dedc52016-11-02 17:50:27 -07002005 // Check that, other than instructions that are no longer in the graph (removed earlier)
Aart Bikf8f5a162017-02-06 15:35:29 -08002006 // each instruction is removable and, when restrict uses are requested, other than for phi,
2007 // all uses are contained within the cycle.
Aart Bike3dedc52016-11-02 17:50:27 -07002008 if (!i->IsInBlock()) {
2009 continue;
2010 } else if (!i->IsRemovable()) {
2011 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08002012 } else if (i != phi && restrict_uses) {
Aart Bikb29f6842017-07-28 15:58:41 -07002013 // Deal with regular uses.
Aart Bikcc42be02016-10-20 16:14:16 -07002014 for (const HUseListNode<HInstruction*>& use : i->GetUses()) {
2015 if (set->find(use.GetUser()) == set->end()) {
2016 return false;
2017 }
2018 }
2019 }
Aart Bike3dedc52016-11-02 17:50:27 -07002020 iset_->insert(i); // copy
Aart Bikcc42be02016-10-20 16:14:16 -07002021 }
Aart Bikcc42be02016-10-20 16:14:16 -07002022 return true;
2023 }
2024 return false;
2025}
2026
Aart Bikb29f6842017-07-28 15:58:41 -07002027bool HLoopOptimization::TrySetPhiReduction(HPhi* phi) {
Aart Bikcc42be02016-10-20 16:14:16 -07002028 DCHECK(iset_->empty());
Aart Bikb29f6842017-07-28 15:58:41 -07002029 // Only unclassified phi cycles are candidates for reductions.
2030 if (induction_range_.IsClassified(phi)) {
2031 return false;
2032 }
2033 // Accept operations like x = x + .., provided that the phi and the reduction are
2034 // used exactly once inside the loop, and by each other.
2035 HInputsRef inputs = phi->GetInputs();
2036 if (inputs.size() == 2) {
2037 HInstruction* reduction = inputs[1];
2038 if (HasReductionFormat(reduction, phi)) {
2039 HLoopInformation* loop_info = phi->GetBlock()->GetLoopInformation();
2040 int32_t use_count = 0;
2041 bool single_use_inside_loop =
2042 // Reduction update only used by phi.
2043 reduction->GetUses().HasExactlyOneElement() &&
2044 !reduction->HasEnvironmentUses() &&
2045 // Reduction update is only use of phi inside the loop.
2046 IsOnlyUsedAfterLoop(loop_info, phi, /*collect_loop_uses*/ true, &use_count) &&
2047 iset_->size() == 1;
2048 iset_->clear(); // leave the way you found it
2049 if (single_use_inside_loop) {
2050 // Link reduction back, and start recording feed value.
2051 reductions_->Put(reduction, phi);
2052 reductions_->Put(phi, phi->InputAt(0));
2053 return true;
2054 }
2055 }
2056 }
2057 return false;
2058}
2059
2060bool HLoopOptimization::TrySetSimpleLoopHeader(HBasicBlock* block, /*out*/ HPhi** main_phi) {
2061 // Start with empty phi induction and reductions.
2062 iset_->clear();
2063 reductions_->clear();
2064
2065 // Scan the phis to find the following (the induction structure has already
2066 // been optimized, so we don't need to worry about trivial cases):
2067 // (1) optional reductions in loop,
2068 // (2) the main induction, used in loop control.
2069 HPhi* phi = nullptr;
2070 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
2071 if (TrySetPhiReduction(it.Current()->AsPhi())) {
2072 continue;
2073 } else if (phi == nullptr) {
2074 // Found the first candidate for main induction.
2075 phi = it.Current()->AsPhi();
2076 } else {
2077 return false;
2078 }
2079 }
2080
2081 // Then test for a typical loopheader:
2082 // s: SuspendCheck
2083 // c: Condition(phi, bound)
2084 // i: If(c)
2085 if (phi != nullptr && TrySetPhiInduction(phi, /*restrict_uses*/ false)) {
Aart Bikcc42be02016-10-20 16:14:16 -07002086 HInstruction* s = block->GetFirstInstruction();
2087 if (s != nullptr && s->IsSuspendCheck()) {
2088 HInstruction* c = s->GetNext();
Aart Bikd86c0852017-04-14 12:00:15 -07002089 if (c != nullptr &&
2090 c->IsCondition() &&
2091 c->GetUses().HasExactlyOneElement() && // only used for termination
2092 !c->HasEnvironmentUses()) { // unlikely, but not impossible
Aart Bikcc42be02016-10-20 16:14:16 -07002093 HInstruction* i = c->GetNext();
2094 if (i != nullptr && i->IsIf() && i->InputAt(0) == c) {
2095 iset_->insert(c);
2096 iset_->insert(s);
Aart Bikb29f6842017-07-28 15:58:41 -07002097 *main_phi = phi;
Aart Bikcc42be02016-10-20 16:14:16 -07002098 return true;
2099 }
2100 }
2101 }
2102 }
2103 return false;
2104}
2105
2106bool HLoopOptimization::IsEmptyBody(HBasicBlock* block) {
Aart Bikf8f5a162017-02-06 15:35:29 -08002107 if (!block->GetPhis().IsEmpty()) {
2108 return false;
2109 }
2110 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
2111 HInstruction* instruction = it.Current();
2112 if (!instruction->IsGoto() && iset_->find(instruction) == iset_->end()) {
2113 return false;
Aart Bikcc42be02016-10-20 16:14:16 -07002114 }
Aart Bikf8f5a162017-02-06 15:35:29 -08002115 }
2116 return true;
2117}
2118
2119bool HLoopOptimization::IsUsedOutsideLoop(HLoopInformation* loop_info,
2120 HInstruction* instruction) {
Aart Bikb29f6842017-07-28 15:58:41 -07002121 // Deal with regular uses.
Aart Bikf8f5a162017-02-06 15:35:29 -08002122 for (const HUseListNode<HInstruction*>& use : instruction->GetUses()) {
2123 if (use.GetUser()->GetBlock()->GetLoopInformation() != loop_info) {
2124 return true;
2125 }
Aart Bikcc42be02016-10-20 16:14:16 -07002126 }
2127 return false;
2128}
2129
Aart Bik482095d2016-10-10 15:39:10 -07002130bool HLoopOptimization::IsOnlyUsedAfterLoop(HLoopInformation* loop_info,
Aart Bik8c4a8542016-10-06 11:36:57 -07002131 HInstruction* instruction,
Aart Bik6b69e0a2017-01-11 10:20:43 -08002132 bool collect_loop_uses,
Aart Bik8c4a8542016-10-06 11:36:57 -07002133 /*out*/ int32_t* use_count) {
Aart Bikb29f6842017-07-28 15:58:41 -07002134 // Deal with regular uses.
Aart Bik8c4a8542016-10-06 11:36:57 -07002135 for (const HUseListNode<HInstruction*>& use : instruction->GetUses()) {
2136 HInstruction* user = use.GetUser();
2137 if (iset_->find(user) == iset_->end()) { // not excluded?
2138 HLoopInformation* other_loop_info = user->GetBlock()->GetLoopInformation();
Aart Bik482095d2016-10-10 15:39:10 -07002139 if (other_loop_info != nullptr && other_loop_info->IsIn(*loop_info)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -08002140 // If collect_loop_uses is set, simply keep adding those uses to the set.
2141 // Otherwise, reject uses inside the loop that were not already in the set.
2142 if (collect_loop_uses) {
2143 iset_->insert(user);
2144 continue;
2145 }
Aart Bik8c4a8542016-10-06 11:36:57 -07002146 return false;
2147 }
2148 ++*use_count;
2149 }
2150 }
2151 return true;
2152}
2153
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002154bool HLoopOptimization::TryReplaceWithLastValue(HLoopInformation* loop_info,
2155 HInstruction* instruction,
2156 HBasicBlock* block) {
2157 // Try to replace outside uses with the last value.
Aart Bik807868e2016-11-03 17:51:43 -07002158 if (induction_range_.CanGenerateLastValue(instruction)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -08002159 HInstruction* replacement = induction_range_.GenerateLastValue(instruction, graph_, block);
Aart Bikb29f6842017-07-28 15:58:41 -07002160 // Deal with regular uses.
Aart Bik6b69e0a2017-01-11 10:20:43 -08002161 const HUseList<HInstruction*>& uses = instruction->GetUses();
2162 for (auto it = uses.begin(), end = uses.end(); it != end;) {
2163 HInstruction* user = it->GetUser();
2164 size_t index = it->GetIndex();
2165 ++it; // increment before replacing
2166 if (iset_->find(user) == iset_->end()) { // not excluded?
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002167 if (kIsDebugBuild) {
2168 // We have checked earlier in 'IsOnlyUsedAfterLoop' that the use is after the loop.
2169 HLoopInformation* other_loop_info = user->GetBlock()->GetLoopInformation();
2170 CHECK(other_loop_info == nullptr || !other_loop_info->IsIn(*loop_info));
2171 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08002172 user->ReplaceInput(replacement, index);
2173 induction_range_.Replace(user, instruction, replacement); // update induction
2174 }
2175 }
Aart Bikb29f6842017-07-28 15:58:41 -07002176 // Deal with environment uses.
Aart Bik6b69e0a2017-01-11 10:20:43 -08002177 const HUseList<HEnvironment*>& env_uses = instruction->GetEnvUses();
2178 for (auto it = env_uses.begin(), end = env_uses.end(); it != end;) {
2179 HEnvironment* user = it->GetUser();
2180 size_t index = it->GetIndex();
2181 ++it; // increment before replacing
2182 if (iset_->find(user->GetHolder()) == iset_->end()) { // not excluded?
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002183 // Only update environment uses after the loop.
Aart Bik14a68b42017-06-08 14:06:58 -07002184 HLoopInformation* other_loop_info = user->GetHolder()->GetBlock()->GetLoopInformation();
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002185 if (other_loop_info == nullptr || !other_loop_info->IsIn(*loop_info)) {
2186 user->RemoveAsUserOfInput(index);
2187 user->SetRawEnvAt(index, replacement);
2188 replacement->AddEnvUseAt(user, index);
2189 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08002190 }
2191 }
Aart Bik807868e2016-11-03 17:51:43 -07002192 return true;
Aart Bik8c4a8542016-10-06 11:36:57 -07002193 }
Aart Bik807868e2016-11-03 17:51:43 -07002194 return false;
Aart Bik8c4a8542016-10-06 11:36:57 -07002195}
2196
Aart Bikf8f5a162017-02-06 15:35:29 -08002197bool HLoopOptimization::TryAssignLastValue(HLoopInformation* loop_info,
2198 HInstruction* instruction,
2199 HBasicBlock* block,
2200 bool collect_loop_uses) {
2201 // Assigning the last value is always successful if there are no uses.
2202 // Otherwise, it succeeds in a no early-exit loop by generating the
2203 // proper last value assignment.
2204 int32_t use_count = 0;
2205 return IsOnlyUsedAfterLoop(loop_info, instruction, collect_loop_uses, &use_count) &&
2206 (use_count == 0 ||
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002207 (!IsEarlyExit(loop_info) && TryReplaceWithLastValue(loop_info, instruction, block)));
Aart Bikf8f5a162017-02-06 15:35:29 -08002208}
2209
Aart Bik6b69e0a2017-01-11 10:20:43 -08002210void HLoopOptimization::RemoveDeadInstructions(const HInstructionList& list) {
2211 for (HBackwardInstructionIterator i(list); !i.Done(); i.Advance()) {
2212 HInstruction* instruction = i.Current();
2213 if (instruction->IsDeadAndRemovable()) {
2214 simplified_ = true;
2215 instruction->GetBlock()->RemoveInstructionOrPhi(instruction);
2216 }
2217 }
2218}
2219
Aart Bik14a68b42017-06-08 14:06:58 -07002220bool HLoopOptimization::CanRemoveCycle() {
2221 for (HInstruction* i : *iset_) {
2222 // We can never remove instructions that have environment
2223 // uses when we compile 'debuggable'.
2224 if (i->HasEnvironmentUses() && graph_->IsDebuggable()) {
2225 return false;
2226 }
2227 // A deoptimization should never have an environment input removed.
2228 for (const HUseListNode<HEnvironment*>& use : i->GetEnvUses()) {
2229 if (use.GetUser()->GetHolder()->IsDeoptimize()) {
2230 return false;
2231 }
2232 }
2233 }
2234 return true;
2235}
2236
Aart Bik281c6812016-08-26 11:31:48 -07002237} // namespace art