blob: f8f4eb2ae303ccbb8ba3eebd407fe6a1c973dc56 [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 Bik9abf8942016-10-14 09:49:42 -070037// Remove the instruction from the graph. A bit more elaborate than the usual
38// instruction removal, since there may be a cycle in the use structure.
Aart Bik281c6812016-08-26 11:31:48 -070039static void RemoveFromCycle(HInstruction* instruction) {
Aart Bik281c6812016-08-26 11:31:48 -070040 instruction->RemoveAsUserOfAllInputs();
41 instruction->RemoveEnvironmentUsers();
42 instruction->GetBlock()->RemoveInstructionOrPhi(instruction, /*ensure_safety=*/ false);
Artem Serov21c7e6f2017-07-27 16:04:42 +010043 RemoveEnvironmentUses(instruction);
44 ResetEnvironmentInputRecords(instruction);
Aart Bik281c6812016-08-26 11:31:48 -070045}
46
Aart Bik807868e2016-11-03 17:51:43 -070047// Detect a goto block and sets succ to the single successor.
Aart Bike3dedc52016-11-02 17:50:27 -070048static bool IsGotoBlock(HBasicBlock* block, /*out*/ HBasicBlock** succ) {
49 if (block->GetPredecessors().size() == 1 &&
50 block->GetSuccessors().size() == 1 &&
51 block->IsSingleGoto()) {
52 *succ = block->GetSingleSuccessor();
53 return true;
54 }
55 return false;
56}
57
Aart Bik807868e2016-11-03 17:51:43 -070058// Detect an early exit loop.
59static bool IsEarlyExit(HLoopInformation* loop_info) {
60 HBlocksInLoopReversePostOrderIterator it_loop(*loop_info);
61 for (it_loop.Advance(); !it_loop.Done(); it_loop.Advance()) {
62 for (HBasicBlock* successor : it_loop.Current()->GetSuccessors()) {
63 if (!loop_info->Contains(*successor)) {
64 return true;
65 }
66 }
67 }
68 return false;
69}
70
Aart Bikf3e61ee2017-04-12 17:09:20 -070071// Detect a sign extension from the given type. Returns the promoted operand on success.
72static bool IsSignExtensionAndGet(HInstruction* instruction,
73 Primitive::Type type,
74 /*out*/ HInstruction** operand) {
75 // Accept any already wider constant that would be handled properly by sign
76 // extension when represented in the *width* of the given narrower data type
77 // (the fact that char normally zero extends does not matter here).
78 int64_t value = 0;
Aart Bik50e20d52017-05-05 14:07:29 -070079 if (IsInt64AndGet(instruction, /*out*/ &value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -070080 switch (type) {
81 case Primitive::kPrimByte:
82 if (std::numeric_limits<int8_t>::min() <= value &&
83 std::numeric_limits<int8_t>::max() >= value) {
84 *operand = instruction;
85 return true;
86 }
87 return false;
88 case Primitive::kPrimChar:
89 case Primitive::kPrimShort:
90 if (std::numeric_limits<int16_t>::min() <= value &&
91 std::numeric_limits<int16_t>::max() <= value) {
92 *operand = instruction;
93 return true;
94 }
95 return false;
96 default:
97 return false;
98 }
99 }
100 // An implicit widening conversion of a signed integer to an integral type sign-extends
101 // the two's-complement representation of the integer value to fill the wider format.
102 if (instruction->GetType() == type && (instruction->IsArrayGet() ||
103 instruction->IsStaticFieldGet() ||
104 instruction->IsInstanceFieldGet())) {
105 switch (type) {
106 case Primitive::kPrimByte:
107 case Primitive::kPrimShort:
108 *operand = instruction;
109 return true;
110 default:
111 return false;
112 }
113 }
114 // TODO: perhaps explicit conversions later too?
115 // (this may return something different from instruction)
116 return false;
117}
118
119// Detect a zero extension from the given type. Returns the promoted operand on success.
120static bool IsZeroExtensionAndGet(HInstruction* instruction,
121 Primitive::Type type,
122 /*out*/ HInstruction** operand) {
123 // Accept any already wider constant that would be handled properly by zero
124 // extension when represented in the *width* of the given narrower data type
125 // (the fact that byte/short normally sign extend does not matter here).
126 int64_t value = 0;
Aart Bik50e20d52017-05-05 14:07:29 -0700127 if (IsInt64AndGet(instruction, /*out*/ &value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700128 switch (type) {
129 case Primitive::kPrimByte:
130 if (std::numeric_limits<uint8_t>::min() <= value &&
131 std::numeric_limits<uint8_t>::max() >= value) {
132 *operand = instruction;
133 return true;
134 }
135 return false;
136 case Primitive::kPrimChar:
137 case Primitive::kPrimShort:
138 if (std::numeric_limits<uint16_t>::min() <= value &&
139 std::numeric_limits<uint16_t>::max() <= value) {
140 *operand = instruction;
141 return true;
142 }
143 return false;
144 default:
145 return false;
146 }
147 }
148 // An implicit widening conversion of a char to an integral type zero-extends
149 // the representation of the char value to fill the wider format.
150 if (instruction->GetType() == type && (instruction->IsArrayGet() ||
151 instruction->IsStaticFieldGet() ||
152 instruction->IsInstanceFieldGet())) {
153 if (type == Primitive::kPrimChar) {
154 *operand = instruction;
155 return true;
156 }
157 }
158 // A sign (or zero) extension followed by an explicit removal of just the
159 // higher sign bits is equivalent to a zero extension of the underlying operand.
160 if (instruction->IsAnd()) {
161 int64_t mask = 0;
162 HInstruction* a = instruction->InputAt(0);
163 HInstruction* b = instruction->InputAt(1);
164 // In (a & b) find (mask & b) or (a & mask) with sign or zero extension on the non-mask.
165 if ((IsInt64AndGet(a, /*out*/ &mask) && (IsSignExtensionAndGet(b, type, /*out*/ operand) ||
166 IsZeroExtensionAndGet(b, type, /*out*/ operand))) ||
167 (IsInt64AndGet(b, /*out*/ &mask) && (IsSignExtensionAndGet(a, type, /*out*/ operand) ||
168 IsZeroExtensionAndGet(a, type, /*out*/ operand)))) {
169 switch ((*operand)->GetType()) {
170 case Primitive::kPrimByte: return mask == std::numeric_limits<uint8_t>::max();
171 case Primitive::kPrimChar:
172 case Primitive::kPrimShort: return mask == std::numeric_limits<uint16_t>::max();
173 default: return false;
174 }
175 }
176 }
177 // TODO: perhaps explicit conversions later too?
178 return false;
179}
180
Aart Bik304c8a52017-05-23 11:01:13 -0700181// Detect situations with same-extension narrower operands.
182// Returns true on success and sets is_unsigned accordingly.
183static bool IsNarrowerOperands(HInstruction* a,
184 HInstruction* b,
185 Primitive::Type type,
186 /*out*/ HInstruction** r,
187 /*out*/ HInstruction** s,
188 /*out*/ bool* is_unsigned) {
189 if (IsSignExtensionAndGet(a, type, r) && IsSignExtensionAndGet(b, type, s)) {
190 *is_unsigned = false;
191 return true;
192 } else if (IsZeroExtensionAndGet(a, type, r) && IsZeroExtensionAndGet(b, type, s)) {
193 *is_unsigned = true;
194 return true;
195 }
196 return false;
197}
198
199// As above, single operand.
200static bool IsNarrowerOperand(HInstruction* a,
201 Primitive::Type type,
202 /*out*/ HInstruction** r,
203 /*out*/ bool* is_unsigned) {
204 if (IsSignExtensionAndGet(a, type, r)) {
205 *is_unsigned = false;
206 return true;
207 } else if (IsZeroExtensionAndGet(a, type, r)) {
208 *is_unsigned = true;
209 return true;
210 }
211 return false;
212}
213
Aart Bik5f805002017-05-16 16:42:41 -0700214// Detect up to two instructions a and b, and an acccumulated constant c.
215static bool IsAddConstHelper(HInstruction* instruction,
216 /*out*/ HInstruction** a,
217 /*out*/ HInstruction** b,
218 /*out*/ int64_t* c,
219 int32_t depth) {
220 static constexpr int32_t kMaxDepth = 8; // don't search too deep
221 int64_t value = 0;
222 if (IsInt64AndGet(instruction, &value)) {
223 *c += value;
224 return true;
225 } else if (instruction->IsAdd() && depth <= kMaxDepth) {
226 return IsAddConstHelper(instruction->InputAt(0), a, b, c, depth + 1) &&
227 IsAddConstHelper(instruction->InputAt(1), a, b, c, depth + 1);
228 } else if (*a == nullptr) {
229 *a = instruction;
230 return true;
231 } else if (*b == nullptr) {
232 *b = instruction;
233 return true;
234 }
235 return false; // too many non-const operands
236}
237
238// Detect a + b + c for an optional constant c.
239static bool IsAddConst(HInstruction* instruction,
240 /*out*/ HInstruction** a,
241 /*out*/ HInstruction** b,
242 /*out*/ int64_t* c) {
243 if (instruction->IsAdd()) {
244 // Try to find a + b and accumulated c.
245 if (IsAddConstHelper(instruction->InputAt(0), a, b, c, /*depth*/ 0) &&
246 IsAddConstHelper(instruction->InputAt(1), a, b, c, /*depth*/ 0) &&
247 *b != nullptr) {
248 return true;
249 }
250 // Found a + b.
251 *a = instruction->InputAt(0);
252 *b = instruction->InputAt(1);
253 *c = 0;
254 return true;
255 }
256 return false;
257}
258
Aart Bikb29f6842017-07-28 15:58:41 -0700259// Detect reductions of the following forms,
260// under assumption phi has only *one* use:
261// x = x_phi + ..
262// x = x_phi - ..
263// x = max(x_phi, ..)
264// x = min(x_phi, ..)
265static bool HasReductionFormat(HInstruction* reduction, HInstruction* phi) {
266 if (reduction->IsAdd()) {
267 return reduction->InputAt(0) == phi || reduction->InputAt(1) == phi;
268 } else if (reduction->IsSub()) {
269 return reduction->InputAt(0) == phi;
270 } else if (reduction->IsInvokeStaticOrDirect()) {
271 switch (reduction->AsInvokeStaticOrDirect()->GetIntrinsic()) {
272 case Intrinsics::kMathMinIntInt:
273 case Intrinsics::kMathMinLongLong:
274 case Intrinsics::kMathMinFloatFloat:
275 case Intrinsics::kMathMinDoubleDouble:
276 case Intrinsics::kMathMaxIntInt:
277 case Intrinsics::kMathMaxLongLong:
278 case Intrinsics::kMathMaxFloatFloat:
279 case Intrinsics::kMathMaxDoubleDouble:
280 return reduction->InputAt(0) == phi || reduction->InputAt(1) == phi;
281 default:
282 return false;
283 }
284 }
285 return false;
286}
287
Aart Bik0148de42017-09-05 09:25:01 -0700288// Translates operation to reduction kind.
289static HVecReduce::ReductionKind GetReductionKind(HInstruction* reduction) {
290 if (reduction->IsVecAdd() || reduction->IsVecSub()) {
291 return HVecReduce::kSum;
292 } else if (reduction->IsVecMin()) {
293 return HVecReduce::kMin;
294 } else if (reduction->IsVecMax()) {
295 return HVecReduce::kMax;
296 }
297 LOG(FATAL) << "Unsupported SIMD reduction";
298 UNREACHABLE();
299}
300
Aart Bikf8f5a162017-02-06 15:35:29 -0800301// Test vector restrictions.
302static bool HasVectorRestrictions(uint64_t restrictions, uint64_t tested) {
303 return (restrictions & tested) != 0;
304}
305
Aart Bikf3e61ee2017-04-12 17:09:20 -0700306// Insert an instruction.
Aart Bikf8f5a162017-02-06 15:35:29 -0800307static HInstruction* Insert(HBasicBlock* block, HInstruction* instruction) {
308 DCHECK(block != nullptr);
309 DCHECK(instruction != nullptr);
310 block->InsertInstructionBefore(instruction, block->GetLastInstruction());
311 return instruction;
312}
313
Artem Serov21c7e6f2017-07-27 16:04:42 +0100314// Check that instructions from the induction sets are fully removed: have no uses
315// and no other instructions use them.
316static bool CheckInductionSetFullyRemoved(ArenaSet<HInstruction*>* iset) {
317 for (HInstruction* instr : *iset) {
318 if (instr->GetBlock() != nullptr ||
319 !instr->GetUses().empty() ||
320 !instr->GetEnvUses().empty() ||
321 HasEnvironmentUsedByOthers(instr)) {
322 return false;
323 }
324 }
Artem Serov21c7e6f2017-07-27 16:04:42 +0100325 return true;
326}
327
Aart Bik281c6812016-08-26 11:31:48 -0700328//
Aart Bikb29f6842017-07-28 15:58:41 -0700329// Public methods.
Aart Bik281c6812016-08-26 11:31:48 -0700330//
331
332HLoopOptimization::HLoopOptimization(HGraph* graph,
Aart Bik92685a82017-03-06 11:13:43 -0800333 CompilerDriver* compiler_driver,
Aart Bik281c6812016-08-26 11:31:48 -0700334 HInductionVarAnalysis* induction_analysis)
335 : HOptimization(graph, kLoopOptimizationPassName),
Aart Bik92685a82017-03-06 11:13:43 -0800336 compiler_driver_(compiler_driver),
Aart Bik281c6812016-08-26 11:31:48 -0700337 induction_range_(induction_analysis),
Aart Bik96202302016-10-04 17:33:56 -0700338 loop_allocator_(nullptr),
Aart Bikf8f5a162017-02-06 15:35:29 -0800339 global_allocator_(graph_->GetArena()),
Aart Bik281c6812016-08-26 11:31:48 -0700340 top_loop_(nullptr),
Aart Bik8c4a8542016-10-06 11:36:57 -0700341 last_loop_(nullptr),
Aart Bik482095d2016-10-10 15:39:10 -0700342 iset_(nullptr),
Aart Bikb29f6842017-07-28 15:58:41 -0700343 reductions_(nullptr),
Aart Bikf8f5a162017-02-06 15:35:29 -0800344 simplified_(false),
345 vector_length_(0),
346 vector_refs_(nullptr),
Aart Bik14a68b42017-06-08 14:06:58 -0700347 vector_peeling_candidate_(nullptr),
348 vector_runtime_test_a_(nullptr),
349 vector_runtime_test_b_(nullptr),
Aart Bik0148de42017-09-05 09:25:01 -0700350 vector_map_(nullptr),
351 vector_permanent_map_(nullptr) {
Aart Bik281c6812016-08-26 11:31:48 -0700352}
353
354void HLoopOptimization::Run() {
Mingyao Yang01b47b02017-02-03 12:09:57 -0800355 // Skip if there is no loop or the graph has try-catch/irreducible loops.
Aart Bik281c6812016-08-26 11:31:48 -0700356 // TODO: make this less of a sledgehammer.
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800357 if (!graph_->HasLoops() || graph_->HasTryCatch() || graph_->HasIrreducibleLoops()) {
Aart Bik281c6812016-08-26 11:31:48 -0700358 return;
359 }
360
Aart Bik96202302016-10-04 17:33:56 -0700361 // Phase-local allocator that draws from the global pool. Since the allocator
362 // itself resides on the stack, it is destructed on exiting Run(), which
363 // implies its underlying memory is released immediately.
Aart Bikf8f5a162017-02-06 15:35:29 -0800364 ArenaAllocator allocator(global_allocator_->GetArenaPool());
Aart Bik96202302016-10-04 17:33:56 -0700365 loop_allocator_ = &allocator;
Nicolas Geoffrayebe16742016-10-05 09:55:42 +0100366
Aart Bik96202302016-10-04 17:33:56 -0700367 // Perform loop optimizations.
368 LocalRun();
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800369 if (top_loop_ == nullptr) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800370 graph_->SetHasLoops(false); // no more loops
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800371 }
372
Aart Bik96202302016-10-04 17:33:56 -0700373 // Detach.
374 loop_allocator_ = nullptr;
375 last_loop_ = top_loop_ = nullptr;
376}
377
Aart Bikb29f6842017-07-28 15:58:41 -0700378//
379// Loop setup and traversal.
380//
381
Aart Bik96202302016-10-04 17:33:56 -0700382void HLoopOptimization::LocalRun() {
383 // Build the linear order using the phase-local allocator. This step enables building
384 // a loop hierarchy that properly reflects the outer-inner and previous-next relation.
385 ArenaVector<HBasicBlock*> linear_order(loop_allocator_->Adapter(kArenaAllocLinearOrder));
386 LinearizeGraph(graph_, loop_allocator_, &linear_order);
387
Aart Bik281c6812016-08-26 11:31:48 -0700388 // Build the loop hierarchy.
Aart Bik96202302016-10-04 17:33:56 -0700389 for (HBasicBlock* block : linear_order) {
Aart Bik281c6812016-08-26 11:31:48 -0700390 if (block->IsLoopHeader()) {
391 AddLoop(block->GetLoopInformation());
392 }
393 }
Aart Bik96202302016-10-04 17:33:56 -0700394
Aart Bik8c4a8542016-10-06 11:36:57 -0700395 // Traverse the loop hierarchy inner-to-outer and optimize. Traversal can use
Aart Bikf8f5a162017-02-06 15:35:29 -0800396 // temporary data structures using the phase-local allocator. All new HIR
397 // should use the global allocator.
Aart Bik8c4a8542016-10-06 11:36:57 -0700398 if (top_loop_ != nullptr) {
399 ArenaSet<HInstruction*> iset(loop_allocator_->Adapter(kArenaAllocLoopOptimization));
Aart Bikb29f6842017-07-28 15:58:41 -0700400 ArenaSafeMap<HInstruction*, HInstruction*> reds(
401 std::less<HInstruction*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
Aart Bikf8f5a162017-02-06 15:35:29 -0800402 ArenaSet<ArrayReference> refs(loop_allocator_->Adapter(kArenaAllocLoopOptimization));
403 ArenaSafeMap<HInstruction*, HInstruction*> map(
404 std::less<HInstruction*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
Aart Bik0148de42017-09-05 09:25:01 -0700405 ArenaSafeMap<HInstruction*, HInstruction*> perm(
406 std::less<HInstruction*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
Aart Bikf8f5a162017-02-06 15:35:29 -0800407 // Attach.
Aart Bik8c4a8542016-10-06 11:36:57 -0700408 iset_ = &iset;
Aart Bikb29f6842017-07-28 15:58:41 -0700409 reductions_ = &reds;
Aart Bikf8f5a162017-02-06 15:35:29 -0800410 vector_refs_ = &refs;
411 vector_map_ = &map;
Aart Bik0148de42017-09-05 09:25:01 -0700412 vector_permanent_map_ = &perm;
Aart Bikf8f5a162017-02-06 15:35:29 -0800413 // Traverse.
Aart Bik8c4a8542016-10-06 11:36:57 -0700414 TraverseLoopsInnerToOuter(top_loop_);
Aart Bikf8f5a162017-02-06 15:35:29 -0800415 // Detach.
416 iset_ = nullptr;
Aart Bikb29f6842017-07-28 15:58:41 -0700417 reductions_ = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800418 vector_refs_ = nullptr;
419 vector_map_ = nullptr;
Aart Bik0148de42017-09-05 09:25:01 -0700420 vector_permanent_map_ = nullptr;
Aart Bik8c4a8542016-10-06 11:36:57 -0700421 }
Aart Bik281c6812016-08-26 11:31:48 -0700422}
423
424void HLoopOptimization::AddLoop(HLoopInformation* loop_info) {
425 DCHECK(loop_info != nullptr);
Aart Bikf8f5a162017-02-06 15:35:29 -0800426 LoopNode* node = new (loop_allocator_) LoopNode(loop_info);
Aart Bik281c6812016-08-26 11:31:48 -0700427 if (last_loop_ == nullptr) {
428 // First loop.
429 DCHECK(top_loop_ == nullptr);
430 last_loop_ = top_loop_ = node;
431 } else if (loop_info->IsIn(*last_loop_->loop_info)) {
432 // Inner loop.
433 node->outer = last_loop_;
434 DCHECK(last_loop_->inner == nullptr);
435 last_loop_ = last_loop_->inner = node;
436 } else {
437 // Subsequent loop.
438 while (last_loop_->outer != nullptr && !loop_info->IsIn(*last_loop_->outer->loop_info)) {
439 last_loop_ = last_loop_->outer;
440 }
441 node->outer = last_loop_->outer;
442 node->previous = last_loop_;
443 DCHECK(last_loop_->next == nullptr);
444 last_loop_ = last_loop_->next = node;
445 }
446}
447
448void HLoopOptimization::RemoveLoop(LoopNode* node) {
449 DCHECK(node != nullptr);
Aart Bik8c4a8542016-10-06 11:36:57 -0700450 DCHECK(node->inner == nullptr);
451 if (node->previous != nullptr) {
452 // Within sequence.
453 node->previous->next = node->next;
454 if (node->next != nullptr) {
455 node->next->previous = node->previous;
456 }
457 } else {
458 // First of sequence.
459 if (node->outer != nullptr) {
460 node->outer->inner = node->next;
461 } else {
462 top_loop_ = node->next;
463 }
464 if (node->next != nullptr) {
465 node->next->outer = node->outer;
466 node->next->previous = nullptr;
467 }
468 }
Aart Bik281c6812016-08-26 11:31:48 -0700469}
470
Aart Bikb29f6842017-07-28 15:58:41 -0700471bool HLoopOptimization::TraverseLoopsInnerToOuter(LoopNode* node) {
472 bool changed = false;
Aart Bik281c6812016-08-26 11:31:48 -0700473 for ( ; node != nullptr; node = node->next) {
Aart Bikb29f6842017-07-28 15:58:41 -0700474 // Visit inner loops first. Recompute induction information for this
475 // loop if the induction of any inner loop has changed.
476 if (TraverseLoopsInnerToOuter(node->inner)) {
Aart Bik482095d2016-10-10 15:39:10 -0700477 induction_range_.ReVisit(node->loop_info);
478 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800479 // Repeat simplifications in the loop-body until no more changes occur.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800480 // Note that since each simplification consists of eliminating code (without
481 // introducing new code), this process is always finite.
Aart Bikdf7822e2016-12-06 10:05:30 -0800482 do {
483 simplified_ = false;
Aart Bikdf7822e2016-12-06 10:05:30 -0800484 SimplifyInduction(node);
Aart Bik6b69e0a2017-01-11 10:20:43 -0800485 SimplifyBlocks(node);
Aart Bikb29f6842017-07-28 15:58:41 -0700486 changed = simplified_ || changed;
Aart Bikdf7822e2016-12-06 10:05:30 -0800487 } while (simplified_);
Aart Bikf8f5a162017-02-06 15:35:29 -0800488 // Optimize inner loop.
Aart Bik9abf8942016-10-14 09:49:42 -0700489 if (node->inner == nullptr) {
Aart Bikb29f6842017-07-28 15:58:41 -0700490 changed = OptimizeInnerLoop(node) || changed;
Aart Bik9abf8942016-10-14 09:49:42 -0700491 }
Aart Bik281c6812016-08-26 11:31:48 -0700492 }
Aart Bikb29f6842017-07-28 15:58:41 -0700493 return changed;
Aart Bik281c6812016-08-26 11:31:48 -0700494}
495
Aart Bikf8f5a162017-02-06 15:35:29 -0800496//
497// Optimization.
498//
499
Aart Bik281c6812016-08-26 11:31:48 -0700500void HLoopOptimization::SimplifyInduction(LoopNode* node) {
501 HBasicBlock* header = node->loop_info->GetHeader();
502 HBasicBlock* preheader = node->loop_info->GetPreHeader();
Aart Bik8c4a8542016-10-06 11:36:57 -0700503 // Scan the phis in the header to find opportunities to simplify an induction
504 // cycle that is only used outside the loop. Replace these uses, if any, with
505 // the last value and remove the induction cycle.
506 // Examples: for (int i = 0; x != null; i++) { .... no i .... }
507 // for (int i = 0; i < 10; i++, k++) { .... no k .... } return k;
Aart Bik281c6812016-08-26 11:31:48 -0700508 for (HInstructionIterator it(header->GetPhis()); !it.Done(); it.Advance()) {
509 HPhi* phi = it.Current()->AsPhi();
Aart Bikf8f5a162017-02-06 15:35:29 -0800510 if (TrySetPhiInduction(phi, /*restrict_uses*/ true) &&
511 TryAssignLastValue(node->loop_info, phi, preheader, /*collect_loop_uses*/ false)) {
Aart Bik671e48a2017-08-09 13:16:56 -0700512 // Note that it's ok to have replaced uses after the loop with the last value, without
513 // being able to remove the cycle. Environment uses (which are the reason we may not be
514 // able to remove the cycle) within the loop will still hold the right value. We must
515 // have tried first, however, to replace outside uses.
516 if (CanRemoveCycle()) {
517 simplified_ = true;
518 for (HInstruction* i : *iset_) {
519 RemoveFromCycle(i);
520 }
521 DCHECK(CheckInductionSetFullyRemoved(iset_));
Aart Bik281c6812016-08-26 11:31:48 -0700522 }
Aart Bik482095d2016-10-10 15:39:10 -0700523 }
524 }
525}
526
527void HLoopOptimization::SimplifyBlocks(LoopNode* node) {
Aart Bikdf7822e2016-12-06 10:05:30 -0800528 // Iterate over all basic blocks in the loop-body.
529 for (HBlocksInLoopIterator it(*node->loop_info); !it.Done(); it.Advance()) {
530 HBasicBlock* block = it.Current();
531 // Remove dead instructions from the loop-body.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800532 RemoveDeadInstructions(block->GetPhis());
533 RemoveDeadInstructions(block->GetInstructions());
Aart Bikdf7822e2016-12-06 10:05:30 -0800534 // Remove trivial control flow blocks from the loop-body.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800535 if (block->GetPredecessors().size() == 1 &&
536 block->GetSuccessors().size() == 1 &&
537 block->GetSingleSuccessor()->GetPredecessors().size() == 1) {
Aart Bikdf7822e2016-12-06 10:05:30 -0800538 simplified_ = true;
Aart Bik6b69e0a2017-01-11 10:20:43 -0800539 block->MergeWith(block->GetSingleSuccessor());
Aart Bikdf7822e2016-12-06 10:05:30 -0800540 } else if (block->GetSuccessors().size() == 2) {
541 // Trivial if block can be bypassed to either branch.
542 HBasicBlock* succ0 = block->GetSuccessors()[0];
543 HBasicBlock* succ1 = block->GetSuccessors()[1];
544 HBasicBlock* meet0 = nullptr;
545 HBasicBlock* meet1 = nullptr;
546 if (succ0 != succ1 &&
547 IsGotoBlock(succ0, &meet0) &&
548 IsGotoBlock(succ1, &meet1) &&
549 meet0 == meet1 && // meets again
550 meet0 != block && // no self-loop
551 meet0->GetPhis().IsEmpty()) { // not used for merging
552 simplified_ = true;
553 succ0->DisconnectAndDelete();
554 if (block->Dominates(meet0)) {
555 block->RemoveDominatedBlock(meet0);
556 succ1->AddDominatedBlock(meet0);
557 meet0->SetDominator(succ1);
Aart Bike3dedc52016-11-02 17:50:27 -0700558 }
Aart Bik482095d2016-10-10 15:39:10 -0700559 }
Aart Bik281c6812016-08-26 11:31:48 -0700560 }
Aart Bikdf7822e2016-12-06 10:05:30 -0800561 }
Aart Bik281c6812016-08-26 11:31:48 -0700562}
563
Aart Bikb29f6842017-07-28 15:58:41 -0700564bool HLoopOptimization::OptimizeInnerLoop(LoopNode* node) {
Aart Bik281c6812016-08-26 11:31:48 -0700565 HBasicBlock* header = node->loop_info->GetHeader();
566 HBasicBlock* preheader = node->loop_info->GetPreHeader();
Aart Bik9abf8942016-10-14 09:49:42 -0700567 // Ensure loop header logic is finite.
Aart Bikf8f5a162017-02-06 15:35:29 -0800568 int64_t trip_count = 0;
569 if (!induction_range_.IsFinite(node->loop_info, &trip_count)) {
Aart Bikb29f6842017-07-28 15:58:41 -0700570 return false;
Aart Bik9abf8942016-10-14 09:49:42 -0700571 }
Aart Bik281c6812016-08-26 11:31:48 -0700572 // Ensure there is only a single loop-body (besides the header).
573 HBasicBlock* body = nullptr;
574 for (HBlocksInLoopIterator it(*node->loop_info); !it.Done(); it.Advance()) {
575 if (it.Current() != header) {
576 if (body != nullptr) {
Aart Bikb29f6842017-07-28 15:58:41 -0700577 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700578 }
579 body = it.Current();
580 }
581 }
Andreas Gampef45d61c2017-06-07 10:29:33 -0700582 CHECK(body != nullptr);
Aart Bik281c6812016-08-26 11:31:48 -0700583 // Ensure there is only a single exit point.
584 if (header->GetSuccessors().size() != 2) {
Aart Bikb29f6842017-07-28 15:58:41 -0700585 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700586 }
587 HBasicBlock* exit = (header->GetSuccessors()[0] == body)
588 ? header->GetSuccessors()[1]
589 : header->GetSuccessors()[0];
Aart Bik8c4a8542016-10-06 11:36:57 -0700590 // Ensure exit can only be reached by exiting loop.
Aart Bik281c6812016-08-26 11:31:48 -0700591 if (exit->GetPredecessors().size() != 1) {
Aart Bikb29f6842017-07-28 15:58:41 -0700592 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700593 }
Aart Bik6b69e0a2017-01-11 10:20:43 -0800594 // Detect either an empty loop (no side effects other than plain iteration) or
595 // a trivial loop (just iterating once). Replace subsequent index uses, if any,
596 // with the last value and remove the loop, possibly after unrolling its body.
Aart Bikb29f6842017-07-28 15:58:41 -0700597 HPhi* main_phi = nullptr;
598 if (TrySetSimpleLoopHeader(header, &main_phi)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -0800599 bool is_empty = IsEmptyBody(body);
Aart Bikb29f6842017-07-28 15:58:41 -0700600 if (reductions_->empty() && // TODO: possible with some effort
601 (is_empty || trip_count == 1) &&
602 TryAssignLastValue(node->loop_info, main_phi, preheader, /*collect_loop_uses*/ true)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -0800603 if (!is_empty) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800604 // Unroll the loop-body, which sees initial value of the index.
Aart Bikb29f6842017-07-28 15:58:41 -0700605 main_phi->ReplaceWith(main_phi->InputAt(0));
Aart Bik6b69e0a2017-01-11 10:20:43 -0800606 preheader->MergeInstructionsWith(body);
607 }
608 body->DisconnectAndDelete();
609 exit->RemovePredecessor(header);
610 header->RemoveSuccessor(exit);
611 header->RemoveDominatedBlock(exit);
612 header->DisconnectAndDelete();
613 preheader->AddSuccessor(exit);
Aart Bikf8f5a162017-02-06 15:35:29 -0800614 preheader->AddInstruction(new (global_allocator_) HGoto());
Aart Bik6b69e0a2017-01-11 10:20:43 -0800615 preheader->AddDominatedBlock(exit);
616 exit->SetDominator(preheader);
617 RemoveLoop(node); // update hierarchy
Aart Bikb29f6842017-07-28 15:58:41 -0700618 return true;
Aart Bikf8f5a162017-02-06 15:35:29 -0800619 }
620 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800621 // Vectorize loop, if possible and valid.
Aart Bikb29f6842017-07-28 15:58:41 -0700622 if (kEnableVectorization &&
623 TrySetSimpleLoopHeader(header, &main_phi) &&
Aart Bikb29f6842017-07-28 15:58:41 -0700624 ShouldVectorize(node, body, trip_count) &&
625 TryAssignLastValue(node->loop_info, main_phi, preheader, /*collect_loop_uses*/ true)) {
626 Vectorize(node, body, exit, trip_count);
627 graph_->SetHasSIMD(true); // flag SIMD usage
628 return true;
Aart Bikf8f5a162017-02-06 15:35:29 -0800629 }
Aart Bikb29f6842017-07-28 15:58:41 -0700630 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -0800631}
632
633//
634// Loop vectorization. The implementation is based on the book by Aart J.C. Bik:
635// "The Software Vectorization Handbook. Applying Multimedia Extensions for Maximum Performance."
636// Intel Press, June, 2004 (http://www.aartbik.com/).
637//
638
Aart Bik14a68b42017-06-08 14:06:58 -0700639bool HLoopOptimization::ShouldVectorize(LoopNode* node, HBasicBlock* block, int64_t trip_count) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800640 // Reset vector bookkeeping.
641 vector_length_ = 0;
642 vector_refs_->clear();
Aart Bik14a68b42017-06-08 14:06:58 -0700643 vector_peeling_candidate_ = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800644 vector_runtime_test_a_ =
645 vector_runtime_test_b_= nullptr;
646
647 // Phis in the loop-body prevent vectorization.
648 if (!block->GetPhis().IsEmpty()) {
649 return false;
650 }
651
652 // Scan the loop-body, starting a right-hand-side tree traversal at each left-hand-side
653 // occurrence, which allows passing down attributes down the use tree.
654 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
655 if (!VectorizeDef(node, it.Current(), /*generate_code*/ false)) {
656 return false; // failure to vectorize a left-hand-side
657 }
658 }
659
Aart Bik14a68b42017-06-08 14:06:58 -0700660 // Does vectorization seem profitable?
661 if (!IsVectorizationProfitable(trip_count)) {
662 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -0800663 }
664
665 // Data dependence analysis. Find each pair of references with same type, where
666 // at least one is a write. Each such pair denotes a possible data dependence.
667 // This analysis exploits the property that differently typed arrays cannot be
668 // aliased, as well as the property that references either point to the same
669 // array or to two completely disjoint arrays, i.e., no partial aliasing.
670 // Other than a few simply heuristics, no detailed subscript analysis is done.
Aart Bikb29f6842017-07-28 15:58:41 -0700671 // The scan over references also finds a suitable dynamic loop peeling candidate.
672 const ArrayReference* candidate = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800673 for (auto i = vector_refs_->begin(); i != vector_refs_->end(); ++i) {
674 for (auto j = i; ++j != vector_refs_->end(); ) {
675 if (i->type == j->type && (i->lhs || j->lhs)) {
676 // Found same-typed a[i+x] vs. b[i+y], where at least one is a write.
677 HInstruction* a = i->base;
678 HInstruction* b = j->base;
679 HInstruction* x = i->offset;
680 HInstruction* y = j->offset;
681 if (a == b) {
682 // Found a[i+x] vs. a[i+y]. Accept if x == y (loop-independent data dependence).
683 // Conservatively assume a loop-carried data dependence otherwise, and reject.
684 if (x != y) {
685 return false;
686 }
687 } else {
688 // Found a[i+x] vs. b[i+y]. Accept if x == y (at worst loop-independent data dependence).
689 // Conservatively assume a potential loop-carried data dependence otherwise, avoided by
690 // generating an explicit a != b disambiguation runtime test on the two references.
691 if (x != y) {
Aart Bik37dc4df2017-06-28 14:08:00 -0700692 // To avoid excessive overhead, we only accept one a != b test.
693 if (vector_runtime_test_a_ == nullptr) {
694 // First test found.
695 vector_runtime_test_a_ = a;
696 vector_runtime_test_b_ = b;
697 } else if ((vector_runtime_test_a_ != a || vector_runtime_test_b_ != b) &&
698 (vector_runtime_test_a_ != b || vector_runtime_test_b_ != a)) {
699 return false; // second test would be needed
Aart Bikf8f5a162017-02-06 15:35:29 -0800700 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800701 }
702 }
703 }
704 }
705 }
706
Aart Bik14a68b42017-06-08 14:06:58 -0700707 // Consider dynamic loop peeling for alignment.
Aart Bikb29f6842017-07-28 15:58:41 -0700708 SetPeelingCandidate(candidate, trip_count);
Aart Bik14a68b42017-06-08 14:06:58 -0700709
Aart Bikf8f5a162017-02-06 15:35:29 -0800710 // Success!
711 return true;
712}
713
714void HLoopOptimization::Vectorize(LoopNode* node,
715 HBasicBlock* block,
716 HBasicBlock* exit,
717 int64_t trip_count) {
718 Primitive::Type induc_type = Primitive::kPrimInt;
719 HBasicBlock* header = node->loop_info->GetHeader();
720 HBasicBlock* preheader = node->loop_info->GetPreHeader();
721
Aart Bik14a68b42017-06-08 14:06:58 -0700722 // Pick a loop unrolling factor for the vector loop.
723 uint32_t unroll = GetUnrollingFactor(block, trip_count);
724 uint32_t chunk = vector_length_ * unroll;
725
726 // A cleanup loop is needed, at least, for any unknown trip count or
727 // for a known trip count with remainder iterations after vectorization.
728 bool needs_cleanup = trip_count == 0 || (trip_count % chunk) != 0;
Aart Bikf8f5a162017-02-06 15:35:29 -0800729
730 // Adjust vector bookkeeping.
Aart Bikb29f6842017-07-28 15:58:41 -0700731 HPhi* main_phi = nullptr;
732 bool is_simple_loop_header = TrySetSimpleLoopHeader(header, &main_phi); // refills sets
Aart Bikf8f5a162017-02-06 15:35:29 -0800733 DCHECK(is_simple_loop_header);
Aart Bik14a68b42017-06-08 14:06:58 -0700734 vector_header_ = header;
735 vector_body_ = block;
Aart Bikf8f5a162017-02-06 15:35:29 -0800736
Aart Bikb29f6842017-07-28 15:58:41 -0700737 // Generate dynamic loop peeling trip count, if needed, under the assumption
738 // that the Android runtime guarantees at least "component size" alignment:
739 // ptc = (ALIGN - (&a[initial] % ALIGN)) / type-size
Aart Bik14a68b42017-06-08 14:06:58 -0700740 HInstruction* ptc = nullptr;
741 if (vector_peeling_candidate_ != nullptr) {
742 DCHECK_LT(vector_length_, trip_count) << "dynamic peeling currently requires known trip count";
743 //
744 // TODO: Implement this. Compute address of first access memory location and
745 // compute peeling factor to obtain kAlignedBase alignment.
746 //
747 needs_cleanup = true;
748 }
749
750 // Generate loop control:
Aart Bikf8f5a162017-02-06 15:35:29 -0800751 // stc = <trip-count>;
Aart Bik14a68b42017-06-08 14:06:58 -0700752 // vtc = stc - (stc - ptc) % chunk;
753 // i = 0;
Aart Bikf8f5a162017-02-06 15:35:29 -0800754 HInstruction* stc = induction_range_.GenerateTripCount(node->loop_info, graph_, preheader);
755 HInstruction* vtc = stc;
756 if (needs_cleanup) {
Aart Bik14a68b42017-06-08 14:06:58 -0700757 DCHECK(IsPowerOfTwo(chunk));
758 HInstruction* diff = stc;
759 if (ptc != nullptr) {
760 diff = Insert(preheader, new (global_allocator_) HSub(induc_type, stc, ptc));
761 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800762 HInstruction* rem = Insert(
763 preheader, new (global_allocator_) HAnd(induc_type,
Aart Bik14a68b42017-06-08 14:06:58 -0700764 diff,
765 graph_->GetIntConstant(chunk - 1)));
Aart Bikf8f5a162017-02-06 15:35:29 -0800766 vtc = Insert(preheader, new (global_allocator_) HSub(induc_type, stc, rem));
767 }
Aart Bik14a68b42017-06-08 14:06:58 -0700768 vector_index_ = graph_->GetIntConstant(0);
Aart Bikf8f5a162017-02-06 15:35:29 -0800769
770 // Generate runtime disambiguation test:
771 // vtc = a != b ? vtc : 0;
772 if (vector_runtime_test_a_ != nullptr) {
773 HInstruction* rt = Insert(
774 preheader,
775 new (global_allocator_) HNotEqual(vector_runtime_test_a_, vector_runtime_test_b_));
776 vtc = Insert(preheader,
777 new (global_allocator_) HSelect(rt, vtc, graph_->GetIntConstant(0), kNoDexPc));
778 needs_cleanup = true;
779 }
780
Aart Bik14a68b42017-06-08 14:06:58 -0700781 // Generate dynamic peeling loop for alignment, if needed:
782 // for ( ; i < ptc; i += 1)
783 // <loop-body>
784 if (ptc != nullptr) {
785 vector_mode_ = kSequential;
786 GenerateNewLoop(node,
787 block,
788 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
789 vector_index_,
790 ptc,
791 graph_->GetIntConstant(1),
792 /*unroll*/ 1);
793 }
794
795 // Generate vector loop, possibly further unrolled:
796 // for ( ; i < vtc; i += chunk)
Aart Bikf8f5a162017-02-06 15:35:29 -0800797 // <vectorized-loop-body>
798 vector_mode_ = kVector;
799 GenerateNewLoop(node,
800 block,
Aart Bik14a68b42017-06-08 14:06:58 -0700801 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
802 vector_index_,
Aart Bikf8f5a162017-02-06 15:35:29 -0800803 vtc,
Aart Bik14a68b42017-06-08 14:06:58 -0700804 graph_->GetIntConstant(vector_length_), // increment per unroll
805 unroll);
Aart Bikf8f5a162017-02-06 15:35:29 -0800806 HLoopInformation* vloop = vector_header_->GetLoopInformation();
807
808 // Generate cleanup loop, if needed:
809 // for ( ; i < stc; i += 1)
810 // <loop-body>
811 if (needs_cleanup) {
812 vector_mode_ = kSequential;
813 GenerateNewLoop(node,
814 block,
815 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
Aart Bik14a68b42017-06-08 14:06:58 -0700816 vector_index_,
Aart Bikf8f5a162017-02-06 15:35:29 -0800817 stc,
Aart Bik14a68b42017-06-08 14:06:58 -0700818 graph_->GetIntConstant(1),
819 /*unroll*/ 1);
Aart Bikf8f5a162017-02-06 15:35:29 -0800820 }
821
Aart Bik0148de42017-09-05 09:25:01 -0700822 // Link reductions to their final uses.
823 for (auto i = reductions_->begin(); i != reductions_->end(); ++i) {
824 if (i->first->IsPhi()) {
825 i->first->ReplaceWith(ReduceAndExtractIfNeeded(i->second));
826 }
827 }
828
Aart Bikf8f5a162017-02-06 15:35:29 -0800829 // Remove the original loop by disconnecting the body block
830 // and removing all instructions from the header.
831 block->DisconnectAndDelete();
832 while (!header->GetFirstInstruction()->IsGoto()) {
833 header->RemoveInstruction(header->GetFirstInstruction());
834 }
Aart Bikb29f6842017-07-28 15:58:41 -0700835
Aart Bik14a68b42017-06-08 14:06:58 -0700836 // Update loop hierarchy: the old header now resides in the same outer loop
837 // as the old preheader. Note that we don't bother putting sequential
838 // loops back in the hierarchy at this point.
Aart Bikf8f5a162017-02-06 15:35:29 -0800839 header->SetLoopInformation(preheader->GetLoopInformation()); // outward
840 node->loop_info = vloop;
841}
842
843void HLoopOptimization::GenerateNewLoop(LoopNode* node,
844 HBasicBlock* block,
845 HBasicBlock* new_preheader,
846 HInstruction* lo,
847 HInstruction* hi,
Aart Bik14a68b42017-06-08 14:06:58 -0700848 HInstruction* step,
849 uint32_t unroll) {
850 DCHECK(unroll == 1 || vector_mode_ == kVector);
Aart Bikf8f5a162017-02-06 15:35:29 -0800851 Primitive::Type induc_type = Primitive::kPrimInt;
852 // Prepare new loop.
Aart Bikf8f5a162017-02-06 15:35:29 -0800853 vector_preheader_ = new_preheader,
854 vector_header_ = vector_preheader_->GetSingleSuccessor();
855 vector_body_ = vector_header_->GetSuccessors()[1];
Aart Bik14a68b42017-06-08 14:06:58 -0700856 HPhi* phi = new (global_allocator_) HPhi(global_allocator_,
857 kNoRegNumber,
858 0,
859 HPhi::ToPhiType(induc_type));
Aart Bikb07d1bc2017-04-05 10:03:15 -0700860 // Generate header and prepare body.
Aart Bikf8f5a162017-02-06 15:35:29 -0800861 // for (i = lo; i < hi; i += step)
862 // <loop-body>
Aart Bik14a68b42017-06-08 14:06:58 -0700863 HInstruction* cond = new (global_allocator_) HAboveOrEqual(phi, hi);
864 vector_header_->AddPhi(phi);
Aart Bikf8f5a162017-02-06 15:35:29 -0800865 vector_header_->AddInstruction(cond);
866 vector_header_->AddInstruction(new (global_allocator_) HIf(cond));
Aart Bik14a68b42017-06-08 14:06:58 -0700867 vector_index_ = phi;
Aart Bik0148de42017-09-05 09:25:01 -0700868 vector_permanent_map_->clear(); // preserved over unrolling
Aart Bik14a68b42017-06-08 14:06:58 -0700869 for (uint32_t u = 0; u < unroll; u++) {
Aart Bik14a68b42017-06-08 14:06:58 -0700870 // Generate instruction map.
Aart Bik0148de42017-09-05 09:25:01 -0700871 vector_map_->clear();
Aart Bik14a68b42017-06-08 14:06:58 -0700872 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
873 bool vectorized_def = VectorizeDef(node, it.Current(), /*generate_code*/ true);
874 DCHECK(vectorized_def);
875 }
876 // Generate body from the instruction map, but in original program order.
877 HEnvironment* env = vector_header_->GetFirstInstruction()->GetEnvironment();
878 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
879 auto i = vector_map_->find(it.Current());
880 if (i != vector_map_->end() && !i->second->IsInBlock()) {
881 Insert(vector_body_, i->second);
882 // Deal with instructions that need an environment, such as the scalar intrinsics.
883 if (i->second->NeedsEnvironment()) {
884 i->second->CopyEnvironmentFromWithLoopPhiAdjustment(env, vector_header_);
885 }
886 }
887 }
Aart Bik0148de42017-09-05 09:25:01 -0700888 // Generate the induction.
Aart Bik14a68b42017-06-08 14:06:58 -0700889 vector_index_ = new (global_allocator_) HAdd(induc_type, vector_index_, step);
890 Insert(vector_body_, vector_index_);
Aart Bikf8f5a162017-02-06 15:35:29 -0800891 }
Aart Bik0148de42017-09-05 09:25:01 -0700892 // Finalize phi inputs for the reductions (if any).
893 for (auto i = reductions_->begin(); i != reductions_->end(); ++i) {
894 if (!i->first->IsPhi()) {
895 DCHECK(i->second->IsPhi());
896 GenerateVecReductionPhiInputs(i->second->AsPhi(), i->first);
897 }
898 }
Aart Bikb29f6842017-07-28 15:58:41 -0700899 // Finalize phi inputs for the loop index.
Aart Bik14a68b42017-06-08 14:06:58 -0700900 phi->AddInput(lo);
901 phi->AddInput(vector_index_);
902 vector_index_ = phi;
Aart Bikf8f5a162017-02-06 15:35:29 -0800903}
904
Aart Bikf8f5a162017-02-06 15:35:29 -0800905bool HLoopOptimization::VectorizeDef(LoopNode* node,
906 HInstruction* instruction,
907 bool generate_code) {
908 // Accept a left-hand-side array base[index] for
909 // (1) supported vector type,
910 // (2) loop-invariant base,
911 // (3) unit stride index,
912 // (4) vectorizable right-hand-side value.
913 uint64_t restrictions = kNone;
914 if (instruction->IsArraySet()) {
915 Primitive::Type type = instruction->AsArraySet()->GetComponentType();
916 HInstruction* base = instruction->InputAt(0);
917 HInstruction* index = instruction->InputAt(1);
918 HInstruction* value = instruction->InputAt(2);
919 HInstruction* offset = nullptr;
920 if (TrySetVectorType(type, &restrictions) &&
921 node->loop_info->IsDefinedOutOfTheLoop(base) &&
Aart Bik37dc4df2017-06-28 14:08:00 -0700922 induction_range_.IsUnitStride(instruction, index, graph_, &offset) &&
Aart Bikf8f5a162017-02-06 15:35:29 -0800923 VectorizeUse(node, value, generate_code, type, restrictions)) {
924 if (generate_code) {
925 GenerateVecSub(index, offset);
Aart Bik14a68b42017-06-08 14:06:58 -0700926 GenerateVecMem(instruction, vector_map_->Get(index), vector_map_->Get(value), offset, type);
Aart Bikf8f5a162017-02-06 15:35:29 -0800927 } else {
928 vector_refs_->insert(ArrayReference(base, offset, type, /*lhs*/ true));
929 }
Aart Bik6b69e0a2017-01-11 10:20:43 -0800930 return true;
931 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800932 return false;
933 }
Aart Bik0148de42017-09-05 09:25:01 -0700934 // Accept a left-hand-side reduction for
935 // (1) supported vector type,
936 // (2) vectorizable right-hand-side value.
937 auto redit = reductions_->find(instruction);
938 if (redit != reductions_->end()) {
939 Primitive::Type type = instruction->GetType();
940 if (TrySetVectorType(type, &restrictions) &&
941 VectorizeUse(node, instruction, generate_code, type, restrictions)) {
942 if (generate_code) {
943 HInstruction* new_red = vector_map_->Get(instruction);
944 vector_permanent_map_->Put(new_red, vector_map_->Get(redit->second));
945 vector_permanent_map_->Overwrite(redit->second, new_red);
946 }
947 return true;
948 }
949 return false;
950 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800951 // Branch back okay.
952 if (instruction->IsGoto()) {
953 return true;
954 }
955 // Otherwise accept only expressions with no effects outside the immediate loop-body.
956 // Note that actual uses are inspected during right-hand-side tree traversal.
957 return !IsUsedOutsideLoop(node->loop_info, instruction) && !instruction->DoesAnyWrite();
958}
959
Aart Bik304c8a52017-05-23 11:01:13 -0700960// TODO: saturation arithmetic.
Aart Bikf8f5a162017-02-06 15:35:29 -0800961bool HLoopOptimization::VectorizeUse(LoopNode* node,
962 HInstruction* instruction,
963 bool generate_code,
964 Primitive::Type type,
965 uint64_t restrictions) {
966 // Accept anything for which code has already been generated.
967 if (generate_code) {
968 if (vector_map_->find(instruction) != vector_map_->end()) {
969 return true;
970 }
971 }
972 // Continue the right-hand-side tree traversal, passing in proper
973 // types and vector restrictions along the way. During code generation,
974 // all new nodes are drawn from the global allocator.
975 if (node->loop_info->IsDefinedOutOfTheLoop(instruction)) {
976 // Accept invariant use, using scalar expansion.
977 if (generate_code) {
978 GenerateVecInv(instruction, type);
979 }
980 return true;
981 } else if (instruction->IsArrayGet()) {
Goran Jakovljevic19680d32017-05-11 10:38:36 +0200982 // Deal with vector restrictions.
983 if (instruction->AsArrayGet()->IsStringCharAt() &&
984 HasVectorRestrictions(restrictions, kNoStringCharAt)) {
985 return false;
986 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800987 // Accept a right-hand-side array base[index] for
988 // (1) exact matching vector type,
989 // (2) loop-invariant base,
990 // (3) unit stride index,
991 // (4) vectorizable right-hand-side value.
992 HInstruction* base = instruction->InputAt(0);
993 HInstruction* index = instruction->InputAt(1);
994 HInstruction* offset = nullptr;
995 if (type == instruction->GetType() &&
996 node->loop_info->IsDefinedOutOfTheLoop(base) &&
Aart Bik37dc4df2017-06-28 14:08:00 -0700997 induction_range_.IsUnitStride(instruction, index, graph_, &offset)) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800998 if (generate_code) {
999 GenerateVecSub(index, offset);
Aart Bik14a68b42017-06-08 14:06:58 -07001000 GenerateVecMem(instruction, vector_map_->Get(index), nullptr, offset, type);
Aart Bikf8f5a162017-02-06 15:35:29 -08001001 } else {
1002 vector_refs_->insert(ArrayReference(base, offset, type, /*lhs*/ false));
1003 }
1004 return true;
1005 }
Aart Bik0148de42017-09-05 09:25:01 -07001006 } else if (instruction->IsPhi()) {
1007 // Accept particular phi operations.
1008 if (reductions_->find(instruction) != reductions_->end()) {
1009 // Deal with vector restrictions.
1010 if (HasVectorRestrictions(restrictions, kNoReduction)) {
1011 return false;
1012 }
1013 // Accept a reduction.
1014 if (generate_code) {
1015 GenerateVecReductionPhi(instruction->AsPhi());
1016 }
1017 return true;
1018 }
1019 // TODO: accept right-hand-side induction?
1020 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001021 } else if (instruction->IsTypeConversion()) {
1022 // Accept particular type conversions.
1023 HTypeConversion* conversion = instruction->AsTypeConversion();
1024 HInstruction* opa = conversion->InputAt(0);
1025 Primitive::Type from = conversion->GetInputType();
1026 Primitive::Type to = conversion->GetResultType();
1027 if ((to == Primitive::kPrimByte ||
1028 to == Primitive::kPrimChar ||
1029 to == Primitive::kPrimShort) && from == Primitive::kPrimInt) {
1030 // Accept a "narrowing" type conversion from a "wider" computation for
1031 // (1) conversion into final required type,
1032 // (2) vectorizable operand,
1033 // (3) "wider" operations cannot bring in higher order bits.
1034 if (to == type && VectorizeUse(node, opa, generate_code, type, restrictions | kNoHiBits)) {
1035 if (generate_code) {
1036 if (vector_mode_ == kVector) {
1037 vector_map_->Put(instruction, vector_map_->Get(opa)); // operand pass-through
1038 } else {
1039 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1040 }
1041 }
1042 return true;
1043 }
1044 } else if (to == Primitive::kPrimFloat && from == Primitive::kPrimInt) {
1045 DCHECK_EQ(to, type);
1046 // Accept int to float conversion for
1047 // (1) supported int,
1048 // (2) vectorizable operand.
1049 if (TrySetVectorType(from, &restrictions) &&
1050 VectorizeUse(node, opa, generate_code, from, restrictions)) {
1051 if (generate_code) {
1052 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1053 }
1054 return true;
1055 }
1056 }
1057 return false;
1058 } else if (instruction->IsNeg() || instruction->IsNot() || instruction->IsBooleanNot()) {
1059 // Accept unary operator for vectorizable operand.
1060 HInstruction* opa = instruction->InputAt(0);
1061 if (VectorizeUse(node, opa, generate_code, type, restrictions)) {
1062 if (generate_code) {
1063 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1064 }
1065 return true;
1066 }
1067 } else if (instruction->IsAdd() || instruction->IsSub() ||
1068 instruction->IsMul() || instruction->IsDiv() ||
1069 instruction->IsAnd() || instruction->IsOr() || instruction->IsXor()) {
1070 // Deal with vector restrictions.
1071 if ((instruction->IsMul() && HasVectorRestrictions(restrictions, kNoMul)) ||
1072 (instruction->IsDiv() && HasVectorRestrictions(restrictions, kNoDiv))) {
1073 return false;
1074 }
1075 // Accept binary operator for vectorizable operands.
1076 HInstruction* opa = instruction->InputAt(0);
1077 HInstruction* opb = instruction->InputAt(1);
1078 if (VectorizeUse(node, opa, generate_code, type, restrictions) &&
1079 VectorizeUse(node, opb, generate_code, type, restrictions)) {
1080 if (generate_code) {
1081 GenerateVecOp(instruction, vector_map_->Get(opa), vector_map_->Get(opb), type);
1082 }
1083 return true;
1084 }
1085 } else if (instruction->IsShl() || instruction->IsShr() || instruction->IsUShr()) {
Aart Bikf3e61ee2017-04-12 17:09:20 -07001086 // Recognize vectorization idioms.
1087 if (VectorizeHalvingAddIdiom(node, instruction, generate_code, type, restrictions)) {
1088 return true;
1089 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001090 // Deal with vector restrictions.
Aart Bik304c8a52017-05-23 11:01:13 -07001091 HInstruction* opa = instruction->InputAt(0);
1092 HInstruction* opb = instruction->InputAt(1);
1093 HInstruction* r = opa;
1094 bool is_unsigned = false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001095 if ((HasVectorRestrictions(restrictions, kNoShift)) ||
1096 (instruction->IsShr() && HasVectorRestrictions(restrictions, kNoShr))) {
1097 return false; // unsupported instruction
Aart Bik304c8a52017-05-23 11:01:13 -07001098 } else if (HasVectorRestrictions(restrictions, kNoHiBits)) {
1099 // Shifts right need extra care to account for higher order bits.
1100 // TODO: less likely shr/unsigned and ushr/signed can by flipping signess.
1101 if (instruction->IsShr() &&
1102 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || is_unsigned)) {
1103 return false; // reject, unless all operands are sign-extension narrower
1104 } else if (instruction->IsUShr() &&
1105 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || !is_unsigned)) {
1106 return false; // reject, unless all operands are zero-extension narrower
1107 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001108 }
1109 // Accept shift operator for vectorizable/invariant operands.
1110 // TODO: accept symbolic, albeit loop invariant shift factors.
Aart Bik304c8a52017-05-23 11:01:13 -07001111 DCHECK(r != nullptr);
1112 if (generate_code && vector_mode_ != kVector) { // de-idiom
1113 r = opa;
1114 }
Aart Bik50e20d52017-05-05 14:07:29 -07001115 int64_t distance = 0;
Aart Bik304c8a52017-05-23 11:01:13 -07001116 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
Aart Bik50e20d52017-05-05 14:07:29 -07001117 IsInt64AndGet(opb, /*out*/ &distance)) {
Aart Bik65ffd8e2017-05-01 16:50:45 -07001118 // Restrict shift distance to packed data type width.
1119 int64_t max_distance = Primitive::ComponentSize(type) * 8;
1120 if (0 <= distance && distance < max_distance) {
1121 if (generate_code) {
Aart Bik304c8a52017-05-23 11:01:13 -07001122 GenerateVecOp(instruction, vector_map_->Get(r), opb, type);
Aart Bik65ffd8e2017-05-01 16:50:45 -07001123 }
1124 return true;
Aart Bikf8f5a162017-02-06 15:35:29 -08001125 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001126 }
1127 } else if (instruction->IsInvokeStaticOrDirect()) {
Aart Bik6daebeb2017-04-03 14:35:41 -07001128 // Accept particular intrinsics.
1129 HInvokeStaticOrDirect* invoke = instruction->AsInvokeStaticOrDirect();
1130 switch (invoke->GetIntrinsic()) {
1131 case Intrinsics::kMathAbsInt:
1132 case Intrinsics::kMathAbsLong:
1133 case Intrinsics::kMathAbsFloat:
1134 case Intrinsics::kMathAbsDouble: {
1135 // Deal with vector restrictions.
Aart Bik304c8a52017-05-23 11:01:13 -07001136 HInstruction* opa = instruction->InputAt(0);
1137 HInstruction* r = opa;
1138 bool is_unsigned = false;
1139 if (HasVectorRestrictions(restrictions, kNoAbs)) {
Aart Bik6daebeb2017-04-03 14:35:41 -07001140 return false;
Aart Bik304c8a52017-05-23 11:01:13 -07001141 } else if (HasVectorRestrictions(restrictions, kNoHiBits) &&
1142 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || is_unsigned)) {
1143 return false; // reject, unless operand is sign-extension narrower
Aart Bik6daebeb2017-04-03 14:35:41 -07001144 }
1145 // Accept ABS(x) for vectorizable operand.
Aart Bik304c8a52017-05-23 11:01:13 -07001146 DCHECK(r != nullptr);
1147 if (generate_code && vector_mode_ != kVector) { // de-idiom
1148 r = opa;
1149 }
1150 if (VectorizeUse(node, r, generate_code, type, restrictions)) {
Aart Bik6daebeb2017-04-03 14:35:41 -07001151 if (generate_code) {
Aart Bik304c8a52017-05-23 11:01:13 -07001152 GenerateVecOp(instruction, vector_map_->Get(r), nullptr, type);
Aart Bik6daebeb2017-04-03 14:35:41 -07001153 }
1154 return true;
1155 }
1156 return false;
1157 }
Aart Bikc8e93c72017-05-10 10:49:22 -07001158 case Intrinsics::kMathMinIntInt:
1159 case Intrinsics::kMathMinLongLong:
1160 case Intrinsics::kMathMinFloatFloat:
1161 case Intrinsics::kMathMinDoubleDouble:
1162 case Intrinsics::kMathMaxIntInt:
1163 case Intrinsics::kMathMaxLongLong:
1164 case Intrinsics::kMathMaxFloatFloat:
1165 case Intrinsics::kMathMaxDoubleDouble: {
1166 // Deal with vector restrictions.
Nicolas Geoffray92316902017-05-23 08:06:07 +00001167 HInstruction* opa = instruction->InputAt(0);
1168 HInstruction* opb = instruction->InputAt(1);
Aart Bik304c8a52017-05-23 11:01:13 -07001169 HInstruction* r = opa;
1170 HInstruction* s = opb;
1171 bool is_unsigned = false;
1172 if (HasVectorRestrictions(restrictions, kNoMinMax)) {
1173 return false;
1174 } else if (HasVectorRestrictions(restrictions, kNoHiBits) &&
1175 !IsNarrowerOperands(opa, opb, type, &r, &s, &is_unsigned)) {
1176 return false; // reject, unless all operands are same-extension narrower
1177 }
1178 // Accept MIN/MAX(x, y) for vectorizable operands.
1179 DCHECK(r != nullptr && s != nullptr);
1180 if (generate_code && vector_mode_ != kVector) { // de-idiom
1181 r = opa;
1182 s = opb;
1183 }
1184 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
1185 VectorizeUse(node, s, generate_code, type, restrictions)) {
Aart Bikc8e93c72017-05-10 10:49:22 -07001186 if (generate_code) {
Aart Bik304c8a52017-05-23 11:01:13 -07001187 GenerateVecOp(
1188 instruction, vector_map_->Get(r), vector_map_->Get(s), type, is_unsigned);
Aart Bikc8e93c72017-05-10 10:49:22 -07001189 }
1190 return true;
1191 }
1192 return false;
1193 }
Aart Bik6daebeb2017-04-03 14:35:41 -07001194 default:
1195 return false;
1196 } // switch
Aart Bik281c6812016-08-26 11:31:48 -07001197 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08001198 return false;
Aart Bik281c6812016-08-26 11:31:48 -07001199}
1200
Aart Bikf8f5a162017-02-06 15:35:29 -08001201bool HLoopOptimization::TrySetVectorType(Primitive::Type type, uint64_t* restrictions) {
1202 const InstructionSetFeatures* features = compiler_driver_->GetInstructionSetFeatures();
1203 switch (compiler_driver_->GetInstructionSet()) {
1204 case kArm:
1205 case kThumb2:
Artem Serov8f7c4102017-06-21 11:21:37 +01001206 // Allow vectorization for all ARM devices, because Android assumes that
Aart Bikb29f6842017-07-28 15:58:41 -07001207 // ARM 32-bit always supports advanced SIMD (64-bit SIMD).
Artem Serov8f7c4102017-06-21 11:21:37 +01001208 switch (type) {
1209 case Primitive::kPrimBoolean:
1210 case Primitive::kPrimByte:
Aart Bik0148de42017-09-05 09:25:01 -07001211 *restrictions |= kNoDiv | kNoReduction;
Artem Serov8f7c4102017-06-21 11:21:37 +01001212 return TrySetVectorLength(8);
1213 case Primitive::kPrimChar:
1214 case Primitive::kPrimShort:
Aart Bik0148de42017-09-05 09:25:01 -07001215 *restrictions |= kNoDiv | kNoStringCharAt | kNoReduction;
Artem Serov8f7c4102017-06-21 11:21:37 +01001216 return TrySetVectorLength(4);
1217 case Primitive::kPrimInt:
Aart Bik0148de42017-09-05 09:25:01 -07001218 *restrictions |= kNoDiv | kNoReduction;
Artem Serov8f7c4102017-06-21 11:21:37 +01001219 return TrySetVectorLength(2);
1220 default:
1221 break;
1222 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001223 return false;
1224 case kArm64:
1225 // Allow vectorization for all ARM devices, because Android assumes that
Aart Bikb29f6842017-07-28 15:58:41 -07001226 // ARMv8 AArch64 always supports advanced SIMD (128-bit SIMD).
Aart Bikf8f5a162017-02-06 15:35:29 -08001227 switch (type) {
1228 case Primitive::kPrimBoolean:
1229 case Primitive::kPrimByte:
Aart Bik0148de42017-09-05 09:25:01 -07001230 *restrictions |= kNoDiv | kNoReduction;
Artem Serovd4bccf12017-04-03 18:47:32 +01001231 return TrySetVectorLength(16);
Aart Bikf8f5a162017-02-06 15:35:29 -08001232 case Primitive::kPrimChar:
1233 case Primitive::kPrimShort:
Aart Bik0148de42017-09-05 09:25:01 -07001234 *restrictions |= kNoDiv | kNoReduction;
Artem Serovd4bccf12017-04-03 18:47:32 +01001235 return TrySetVectorLength(8);
Aart Bikf8f5a162017-02-06 15:35:29 -08001236 case Primitive::kPrimInt:
1237 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +01001238 return TrySetVectorLength(4);
Artem Serovb31f91f2017-04-05 11:31:19 +01001239 case Primitive::kPrimLong:
Aart Bikc8e93c72017-05-10 10:49:22 -07001240 *restrictions |= kNoDiv | kNoMul | kNoMinMax;
Aart Bikf8f5a162017-02-06 15:35:29 -08001241 return TrySetVectorLength(2);
1242 case Primitive::kPrimFloat:
Aart Bik0148de42017-09-05 09:25:01 -07001243 *restrictions |= kNoReduction;
Artem Serovd4bccf12017-04-03 18:47:32 +01001244 return TrySetVectorLength(4);
Artem Serovb31f91f2017-04-05 11:31:19 +01001245 case Primitive::kPrimDouble:
Aart Bik0148de42017-09-05 09:25:01 -07001246 *restrictions |= kNoReduction;
Aart Bikf8f5a162017-02-06 15:35:29 -08001247 return TrySetVectorLength(2);
1248 default:
1249 return false;
1250 }
1251 case kX86:
1252 case kX86_64:
Aart Bikb29f6842017-07-28 15:58:41 -07001253 // Allow vectorization for SSE4.1-enabled X86 devices only (128-bit SIMD).
Aart Bikf8f5a162017-02-06 15:35:29 -08001254 if (features->AsX86InstructionSetFeatures()->HasSSE4_1()) {
1255 switch (type) {
1256 case Primitive::kPrimBoolean:
1257 case Primitive::kPrimByte:
Aart Bik0148de42017-09-05 09:25:01 -07001258 *restrictions |=
1259 kNoMul | kNoDiv | kNoShift | kNoAbs | kNoSignedHAdd | kNoUnroundedHAdd | kNoReduction;
Aart Bikf8f5a162017-02-06 15:35:29 -08001260 return TrySetVectorLength(16);
1261 case Primitive::kPrimChar:
1262 case Primitive::kPrimShort:
Aart Bik0148de42017-09-05 09:25:01 -07001263 *restrictions |= kNoDiv | kNoAbs | kNoSignedHAdd | kNoUnroundedHAdd | kNoReduction;
Aart Bikf8f5a162017-02-06 15:35:29 -08001264 return TrySetVectorLength(8);
1265 case Primitive::kPrimInt:
1266 *restrictions |= kNoDiv;
1267 return TrySetVectorLength(4);
1268 case Primitive::kPrimLong:
Aart Bikc8e93c72017-05-10 10:49:22 -07001269 *restrictions |= kNoMul | kNoDiv | kNoShr | kNoAbs | kNoMinMax;
Aart Bikf8f5a162017-02-06 15:35:29 -08001270 return TrySetVectorLength(2);
1271 case Primitive::kPrimFloat:
Aart Bik0148de42017-09-05 09:25:01 -07001272 *restrictions |= kNoMinMax | kNoReduction; // minmax: -0.0 vs +0.0
Aart Bikf8f5a162017-02-06 15:35:29 -08001273 return TrySetVectorLength(4);
1274 case Primitive::kPrimDouble:
Aart Bik0148de42017-09-05 09:25:01 -07001275 *restrictions |= kNoMinMax | kNoReduction; // minmax: -0.0 vs +0.0
Aart Bikf8f5a162017-02-06 15:35:29 -08001276 return TrySetVectorLength(2);
1277 default:
1278 break;
1279 } // switch type
1280 }
1281 return false;
1282 case kMips:
Lena Djokic51765b02017-06-22 13:49:59 +02001283 if (features->AsMipsInstructionSetFeatures()->HasMsa()) {
1284 switch (type) {
1285 case Primitive::kPrimBoolean:
1286 case Primitive::kPrimByte:
Aart Bik0148de42017-09-05 09:25:01 -07001287 *restrictions |= kNoDiv | kNoReduction;
Lena Djokic51765b02017-06-22 13:49:59 +02001288 return TrySetVectorLength(16);
1289 case Primitive::kPrimChar:
1290 case Primitive::kPrimShort:
Aart Bik0148de42017-09-05 09:25:01 -07001291 *restrictions |= kNoDiv | kNoStringCharAt | kNoReduction;
Lena Djokic51765b02017-06-22 13:49:59 +02001292 return TrySetVectorLength(8);
1293 case Primitive::kPrimInt:
Aart Bik0148de42017-09-05 09:25:01 -07001294 *restrictions |= kNoDiv | kNoReduction;
Lena Djokic51765b02017-06-22 13:49:59 +02001295 return TrySetVectorLength(4);
1296 case Primitive::kPrimLong:
Aart Bik0148de42017-09-05 09:25:01 -07001297 *restrictions |= kNoDiv | kNoReduction;
Lena Djokic51765b02017-06-22 13:49:59 +02001298 return TrySetVectorLength(2);
1299 case Primitive::kPrimFloat:
Aart Bik0148de42017-09-05 09:25:01 -07001300 *restrictions |= kNoMinMax | kNoReduction; // min/max(x, NaN)
Lena Djokic51765b02017-06-22 13:49:59 +02001301 return TrySetVectorLength(4);
1302 case Primitive::kPrimDouble:
Aart Bik0148de42017-09-05 09:25:01 -07001303 *restrictions |= kNoMinMax | kNoReduction; // min/max(x, NaN)
Lena Djokic51765b02017-06-22 13:49:59 +02001304 return TrySetVectorLength(2);
1305 default:
1306 break;
1307 } // switch type
1308 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001309 return false;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001310 case kMips64:
1311 if (features->AsMips64InstructionSetFeatures()->HasMsa()) {
1312 switch (type) {
1313 case Primitive::kPrimBoolean:
1314 case Primitive::kPrimByte:
Aart Bik0148de42017-09-05 09:25:01 -07001315 *restrictions |= kNoDiv | kNoReduction;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001316 return TrySetVectorLength(16);
1317 case Primitive::kPrimChar:
1318 case Primitive::kPrimShort:
Aart Bik0148de42017-09-05 09:25:01 -07001319 *restrictions |= kNoDiv | kNoStringCharAt | kNoReduction;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001320 return TrySetVectorLength(8);
1321 case Primitive::kPrimInt:
Aart Bik0148de42017-09-05 09:25:01 -07001322 *restrictions |= kNoDiv | kNoReduction;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001323 return TrySetVectorLength(4);
1324 case Primitive::kPrimLong:
Aart Bik0148de42017-09-05 09:25:01 -07001325 *restrictions |= kNoDiv | kNoReduction;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001326 return TrySetVectorLength(2);
1327 case Primitive::kPrimFloat:
Aart Bik0148de42017-09-05 09:25:01 -07001328 *restrictions |= kNoMinMax | kNoReduction; // min/max(x, NaN)
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001329 return TrySetVectorLength(4);
1330 case Primitive::kPrimDouble:
Aart Bik0148de42017-09-05 09:25:01 -07001331 *restrictions |= kNoMinMax | kNoReduction; // min/max(x, NaN)
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001332 return TrySetVectorLength(2);
1333 default:
1334 break;
1335 } // switch type
1336 }
1337 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001338 default:
1339 return false;
1340 } // switch instruction set
1341}
1342
1343bool HLoopOptimization::TrySetVectorLength(uint32_t length) {
1344 DCHECK(IsPowerOfTwo(length) && length >= 2u);
1345 // First time set?
1346 if (vector_length_ == 0) {
1347 vector_length_ = length;
1348 }
1349 // Different types are acceptable within a loop-body, as long as all the corresponding vector
1350 // lengths match exactly to obtain a uniform traversal through the vector iteration space
1351 // (idiomatic exceptions to this rule can be handled by further unrolling sub-expressions).
1352 return vector_length_ == length;
1353}
1354
1355void HLoopOptimization::GenerateVecInv(HInstruction* org, Primitive::Type type) {
1356 if (vector_map_->find(org) == vector_map_->end()) {
1357 // In scalar code, just use a self pass-through for scalar invariants
1358 // (viz. expression remains itself).
1359 if (vector_mode_ == kSequential) {
1360 vector_map_->Put(org, org);
1361 return;
1362 }
1363 // In vector code, explicit scalar expansion is needed.
Aart Bik0148de42017-09-05 09:25:01 -07001364 HInstruction* vector = nullptr;
1365 auto it = vector_permanent_map_->find(org);
1366 if (it != vector_permanent_map_->end()) {
1367 vector = it->second; // reuse during unrolling
1368 } else {
1369 vector = new (global_allocator_) HVecReplicateScalar(
1370 global_allocator_, org, type, vector_length_);
1371 vector_permanent_map_->Put(org, Insert(vector_preheader_, vector));
1372 }
1373 vector_map_->Put(org, vector);
Aart Bikf8f5a162017-02-06 15:35:29 -08001374 }
1375}
1376
1377void HLoopOptimization::GenerateVecSub(HInstruction* org, HInstruction* offset) {
1378 if (vector_map_->find(org) == vector_map_->end()) {
Aart Bik14a68b42017-06-08 14:06:58 -07001379 HInstruction* subscript = vector_index_;
Aart Bik37dc4df2017-06-28 14:08:00 -07001380 int64_t value = 0;
1381 if (!IsInt64AndGet(offset, &value) || value != 0) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001382 subscript = new (global_allocator_) HAdd(Primitive::kPrimInt, subscript, offset);
1383 if (org->IsPhi()) {
1384 Insert(vector_body_, subscript); // lacks layout placeholder
1385 }
1386 }
1387 vector_map_->Put(org, subscript);
1388 }
1389}
1390
1391void HLoopOptimization::GenerateVecMem(HInstruction* org,
1392 HInstruction* opa,
1393 HInstruction* opb,
Aart Bik14a68b42017-06-08 14:06:58 -07001394 HInstruction* offset,
Aart Bikf8f5a162017-02-06 15:35:29 -08001395 Primitive::Type type) {
1396 HInstruction* vector = nullptr;
1397 if (vector_mode_ == kVector) {
1398 // Vector store or load.
Aart Bik14a68b42017-06-08 14:06:58 -07001399 HInstruction* base = org->InputAt(0);
Aart Bikf8f5a162017-02-06 15:35:29 -08001400 if (opb != nullptr) {
1401 vector = new (global_allocator_) HVecStore(
Aart Bik14a68b42017-06-08 14:06:58 -07001402 global_allocator_, base, opa, opb, type, vector_length_);
Aart Bikf8f5a162017-02-06 15:35:29 -08001403 } else {
Aart Bikdb14fcf2017-04-25 15:53:58 -07001404 bool is_string_char_at = org->AsArrayGet()->IsStringCharAt();
Aart Bikf8f5a162017-02-06 15:35:29 -08001405 vector = new (global_allocator_) HVecLoad(
Aart Bik14a68b42017-06-08 14:06:58 -07001406 global_allocator_, base, opa, type, vector_length_, is_string_char_at);
1407 }
1408 // Known dynamically enforced alignment?
Aart Bik14a68b42017-06-08 14:06:58 -07001409 if (vector_peeling_candidate_ != nullptr &&
1410 vector_peeling_candidate_->base == base &&
1411 vector_peeling_candidate_->offset == offset) {
1412 vector->AsVecMemoryOperation()->SetAlignment(Alignment(kAlignedBase, 0));
Aart Bikf8f5a162017-02-06 15:35:29 -08001413 }
1414 } else {
1415 // Scalar store or load.
1416 DCHECK(vector_mode_ == kSequential);
1417 if (opb != nullptr) {
1418 vector = new (global_allocator_) HArraySet(org->InputAt(0), opa, opb, type, kNoDexPc);
1419 } else {
Aart Bikdb14fcf2017-04-25 15:53:58 -07001420 bool is_string_char_at = org->AsArrayGet()->IsStringCharAt();
1421 vector = new (global_allocator_) HArrayGet(
1422 org->InputAt(0), opa, type, kNoDexPc, is_string_char_at);
Aart Bikf8f5a162017-02-06 15:35:29 -08001423 }
1424 }
1425 vector_map_->Put(org, vector);
1426}
1427
Aart Bik0148de42017-09-05 09:25:01 -07001428void HLoopOptimization::GenerateVecReductionPhi(HPhi* phi) {
1429 DCHECK(reductions_->find(phi) != reductions_->end());
1430 DCHECK(reductions_->Get(phi->InputAt(1)) == phi);
1431 HInstruction* vector = nullptr;
1432 if (vector_mode_ == kSequential) {
1433 HPhi* new_phi = new (global_allocator_) HPhi(
1434 global_allocator_, kNoRegNumber, 0, phi->GetType());
1435 vector_header_->AddPhi(new_phi);
1436 vector = new_phi;
1437 } else {
1438 // Link vector reduction back to prior unrolled update, or a first phi.
1439 auto it = vector_permanent_map_->find(phi);
1440 if (it != vector_permanent_map_->end()) {
1441 vector = it->second;
1442 } else {
1443 HPhi* new_phi = new (global_allocator_) HPhi(
1444 global_allocator_, kNoRegNumber, 0, HVecOperation::kSIMDType);
1445 vector_header_->AddPhi(new_phi);
1446 vector = new_phi;
1447 }
1448 }
1449 vector_map_->Put(phi, vector);
1450}
1451
1452void HLoopOptimization::GenerateVecReductionPhiInputs(HPhi* phi, HInstruction* reduction) {
1453 HInstruction* new_phi = vector_map_->Get(phi);
1454 HInstruction* new_init = reductions_->Get(phi);
1455 HInstruction* new_red = vector_map_->Get(reduction);
1456 // Link unrolled vector loop back to new phi.
1457 for (; !new_phi->IsPhi(); new_phi = vector_permanent_map_->Get(new_phi)) {
1458 DCHECK(new_phi->IsVecOperation());
1459 }
1460 // Prepare the new initialization.
1461 if (vector_mode_ == kVector) {
1462 // Generate a [initial, 0, .., 0] vector.
1463 new_init = Insert(
1464 vector_preheader_,
1465 new (global_allocator_) HVecSetScalars(
1466 global_allocator_, &new_init, phi->GetType(), vector_length_, 1));
1467 } else {
1468 new_init = ReduceAndExtractIfNeeded(new_init);
1469 }
1470 // Set the phi inputs.
1471 DCHECK(new_phi->IsPhi());
1472 new_phi->AsPhi()->AddInput(new_init);
1473 new_phi->AsPhi()->AddInput(new_red);
1474 // New feed value for next phi (safe mutation in iteration).
1475 reductions_->find(phi)->second = new_phi;
1476}
1477
1478HInstruction* HLoopOptimization::ReduceAndExtractIfNeeded(HInstruction* instruction) {
1479 if (instruction->IsPhi()) {
1480 HInstruction* input = instruction->InputAt(1);
1481 if (input->IsVecOperation()) {
1482 Primitive::Type type = input->AsVecOperation()->GetPackedType();
1483 HBasicBlock* exit = instruction->GetBlock()->GetSuccessors()[0];
1484 // Generate a vector reduction and scalar extract
1485 // x = REDUCE( [x_1, .., x_n] )
1486 // y = x_1
1487 // along the exit of the defining loop.
1488 HVecReduce::ReductionKind kind = GetReductionKind(input);
1489 HInstruction* reduce = new (global_allocator_) HVecReduce(
1490 global_allocator_, instruction, type, vector_length_, kind);
1491 exit->InsertInstructionBefore(reduce, exit->GetFirstInstruction());
1492 instruction = new (global_allocator_) HVecExtractScalar(
1493 global_allocator_, reduce, type, vector_length_, 0);
1494 exit->InsertInstructionAfter(instruction, reduce);
1495 }
1496 }
1497 return instruction;
1498}
1499
Aart Bikf8f5a162017-02-06 15:35:29 -08001500#define GENERATE_VEC(x, y) \
1501 if (vector_mode_ == kVector) { \
1502 vector = (x); \
1503 } else { \
1504 DCHECK(vector_mode_ == kSequential); \
1505 vector = (y); \
1506 } \
1507 break;
1508
1509void HLoopOptimization::GenerateVecOp(HInstruction* org,
1510 HInstruction* opa,
1511 HInstruction* opb,
Aart Bik304c8a52017-05-23 11:01:13 -07001512 Primitive::Type type,
1513 bool is_unsigned) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001514 if (vector_mode_ == kSequential) {
Aart Bik304c8a52017-05-23 11:01:13 -07001515 // Non-converting scalar code follows implicit integral promotion.
1516 if (!org->IsTypeConversion() && (type == Primitive::kPrimBoolean ||
1517 type == Primitive::kPrimByte ||
1518 type == Primitive::kPrimChar ||
1519 type == Primitive::kPrimShort)) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001520 type = Primitive::kPrimInt;
1521 }
1522 }
1523 HInstruction* vector = nullptr;
1524 switch (org->GetKind()) {
1525 case HInstruction::kNeg:
1526 DCHECK(opb == nullptr);
1527 GENERATE_VEC(
1528 new (global_allocator_) HVecNeg(global_allocator_, opa, type, vector_length_),
1529 new (global_allocator_) HNeg(type, opa));
1530 case HInstruction::kNot:
1531 DCHECK(opb == nullptr);
1532 GENERATE_VEC(
1533 new (global_allocator_) HVecNot(global_allocator_, opa, type, vector_length_),
1534 new (global_allocator_) HNot(type, opa));
1535 case HInstruction::kBooleanNot:
1536 DCHECK(opb == nullptr);
1537 GENERATE_VEC(
1538 new (global_allocator_) HVecNot(global_allocator_, opa, type, vector_length_),
1539 new (global_allocator_) HBooleanNot(opa));
1540 case HInstruction::kTypeConversion:
1541 DCHECK(opb == nullptr);
1542 GENERATE_VEC(
1543 new (global_allocator_) HVecCnv(global_allocator_, opa, type, vector_length_),
1544 new (global_allocator_) HTypeConversion(type, opa, kNoDexPc));
1545 case HInstruction::kAdd:
1546 GENERATE_VEC(
1547 new (global_allocator_) HVecAdd(global_allocator_, opa, opb, type, vector_length_),
1548 new (global_allocator_) HAdd(type, opa, opb));
1549 case HInstruction::kSub:
1550 GENERATE_VEC(
1551 new (global_allocator_) HVecSub(global_allocator_, opa, opb, type, vector_length_),
1552 new (global_allocator_) HSub(type, opa, opb));
1553 case HInstruction::kMul:
1554 GENERATE_VEC(
1555 new (global_allocator_) HVecMul(global_allocator_, opa, opb, type, vector_length_),
1556 new (global_allocator_) HMul(type, opa, opb));
1557 case HInstruction::kDiv:
1558 GENERATE_VEC(
1559 new (global_allocator_) HVecDiv(global_allocator_, opa, opb, type, vector_length_),
1560 new (global_allocator_) HDiv(type, opa, opb, kNoDexPc));
1561 case HInstruction::kAnd:
1562 GENERATE_VEC(
1563 new (global_allocator_) HVecAnd(global_allocator_, opa, opb, type, vector_length_),
1564 new (global_allocator_) HAnd(type, opa, opb));
1565 case HInstruction::kOr:
1566 GENERATE_VEC(
1567 new (global_allocator_) HVecOr(global_allocator_, opa, opb, type, vector_length_),
1568 new (global_allocator_) HOr(type, opa, opb));
1569 case HInstruction::kXor:
1570 GENERATE_VEC(
1571 new (global_allocator_) HVecXor(global_allocator_, opa, opb, type, vector_length_),
1572 new (global_allocator_) HXor(type, opa, opb));
1573 case HInstruction::kShl:
1574 GENERATE_VEC(
1575 new (global_allocator_) HVecShl(global_allocator_, opa, opb, type, vector_length_),
1576 new (global_allocator_) HShl(type, opa, opb));
1577 case HInstruction::kShr:
1578 GENERATE_VEC(
1579 new (global_allocator_) HVecShr(global_allocator_, opa, opb, type, vector_length_),
1580 new (global_allocator_) HShr(type, opa, opb));
1581 case HInstruction::kUShr:
1582 GENERATE_VEC(
1583 new (global_allocator_) HVecUShr(global_allocator_, opa, opb, type, vector_length_),
1584 new (global_allocator_) HUShr(type, opa, opb));
1585 case HInstruction::kInvokeStaticOrDirect: {
Aart Bik6daebeb2017-04-03 14:35:41 -07001586 HInvokeStaticOrDirect* invoke = org->AsInvokeStaticOrDirect();
1587 if (vector_mode_ == kVector) {
1588 switch (invoke->GetIntrinsic()) {
1589 case Intrinsics::kMathAbsInt:
1590 case Intrinsics::kMathAbsLong:
1591 case Intrinsics::kMathAbsFloat:
1592 case Intrinsics::kMathAbsDouble:
1593 DCHECK(opb == nullptr);
1594 vector = new (global_allocator_) HVecAbs(global_allocator_, opa, type, vector_length_);
1595 break;
Aart Bikc8e93c72017-05-10 10:49:22 -07001596 case Intrinsics::kMathMinIntInt:
1597 case Intrinsics::kMathMinLongLong:
1598 case Intrinsics::kMathMinFloatFloat:
1599 case Intrinsics::kMathMinDoubleDouble: {
Aart Bikc8e93c72017-05-10 10:49:22 -07001600 vector = new (global_allocator_)
1601 HVecMin(global_allocator_, opa, opb, type, vector_length_, is_unsigned);
1602 break;
1603 }
1604 case Intrinsics::kMathMaxIntInt:
1605 case Intrinsics::kMathMaxLongLong:
1606 case Intrinsics::kMathMaxFloatFloat:
1607 case Intrinsics::kMathMaxDoubleDouble: {
Aart Bikc8e93c72017-05-10 10:49:22 -07001608 vector = new (global_allocator_)
1609 HVecMax(global_allocator_, opa, opb, type, vector_length_, is_unsigned);
1610 break;
1611 }
Aart Bik6daebeb2017-04-03 14:35:41 -07001612 default:
1613 LOG(FATAL) << "Unsupported SIMD intrinsic";
1614 UNREACHABLE();
1615 } // switch invoke
1616 } else {
Aart Bik24b905f2017-04-06 09:59:06 -07001617 // In scalar code, simply clone the method invoke, and replace its operands with the
1618 // corresponding new scalar instructions in the loop. The instruction will get an
1619 // environment while being inserted from the instruction map in original program order.
Aart Bik6daebeb2017-04-03 14:35:41 -07001620 DCHECK(vector_mode_ == kSequential);
Aart Bik6e92fb32017-06-05 14:05:09 -07001621 size_t num_args = invoke->GetNumberOfArguments();
Aart Bik6daebeb2017-04-03 14:35:41 -07001622 HInvokeStaticOrDirect* new_invoke = new (global_allocator_) HInvokeStaticOrDirect(
1623 global_allocator_,
Aart Bik6e92fb32017-06-05 14:05:09 -07001624 num_args,
Aart Bik6daebeb2017-04-03 14:35:41 -07001625 invoke->GetType(),
1626 invoke->GetDexPc(),
1627 invoke->GetDexMethodIndex(),
1628 invoke->GetResolvedMethod(),
1629 invoke->GetDispatchInfo(),
1630 invoke->GetInvokeType(),
1631 invoke->GetTargetMethod(),
1632 invoke->GetClinitCheckRequirement());
1633 HInputsRef inputs = invoke->GetInputs();
Aart Bik6e92fb32017-06-05 14:05:09 -07001634 size_t num_inputs = inputs.size();
1635 DCHECK_LE(num_args, num_inputs);
1636 DCHECK_EQ(num_inputs, new_invoke->GetInputs().size()); // both invokes agree
1637 for (size_t index = 0; index < num_inputs; ++index) {
1638 HInstruction* new_input = index < num_args
1639 ? vector_map_->Get(inputs[index])
1640 : inputs[index]; // beyond arguments: just pass through
1641 new_invoke->SetArgumentAt(index, new_input);
Aart Bik6daebeb2017-04-03 14:35:41 -07001642 }
Aart Bik98990262017-04-10 13:15:57 -07001643 new_invoke->SetIntrinsic(invoke->GetIntrinsic(),
1644 kNeedsEnvironmentOrCache,
1645 kNoSideEffects,
1646 kNoThrow);
Aart Bik6daebeb2017-04-03 14:35:41 -07001647 vector = new_invoke;
1648 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001649 break;
1650 }
1651 default:
1652 break;
1653 } // switch
1654 CHECK(vector != nullptr) << "Unsupported SIMD operator";
1655 vector_map_->Put(org, vector);
1656}
1657
1658#undef GENERATE_VEC
1659
1660//
Aart Bikf3e61ee2017-04-12 17:09:20 -07001661// Vectorization idioms.
1662//
1663
1664// Method recognizes the following idioms:
1665// rounding halving add (a + b + 1) >> 1 for unsigned/signed operands a, b
1666// regular halving add (a + b) >> 1 for unsigned/signed operands a, b
1667// Provided that the operands are promoted to a wider form to do the arithmetic and
1668// then cast back to narrower form, the idioms can be mapped into efficient SIMD
1669// implementation that operates directly in narrower form (plus one extra bit).
1670// TODO: current version recognizes implicit byte/short/char widening only;
1671// explicit widening from int to long could be added later.
1672bool HLoopOptimization::VectorizeHalvingAddIdiom(LoopNode* node,
1673 HInstruction* instruction,
1674 bool generate_code,
1675 Primitive::Type type,
1676 uint64_t restrictions) {
1677 // Test for top level arithmetic shift right x >> 1 or logical shift right x >>> 1
Aart Bik304c8a52017-05-23 11:01:13 -07001678 // (note whether the sign bit in wider precision is shifted in has no effect
Aart Bikf3e61ee2017-04-12 17:09:20 -07001679 // on the narrow precision computed by the idiom).
Aart Bikf3e61ee2017-04-12 17:09:20 -07001680 if ((instruction->IsShr() ||
1681 instruction->IsUShr()) &&
Aart Bik0148de42017-09-05 09:25:01 -07001682 IsInt64Value(instruction->InputAt(1), 1)) {
Aart Bik5f805002017-05-16 16:42:41 -07001683 // Test for (a + b + c) >> 1 for optional constant c.
1684 HInstruction* a = nullptr;
1685 HInstruction* b = nullptr;
1686 int64_t c = 0;
1687 if (IsAddConst(instruction->InputAt(0), /*out*/ &a, /*out*/ &b, /*out*/ &c)) {
Aart Bik304c8a52017-05-23 11:01:13 -07001688 DCHECK(a != nullptr && b != nullptr);
Aart Bik5f805002017-05-16 16:42:41 -07001689 // Accept c == 1 (rounded) or c == 0 (not rounded).
1690 bool is_rounded = false;
1691 if (c == 1) {
1692 is_rounded = true;
1693 } else if (c != 0) {
1694 return false;
1695 }
1696 // Accept consistent zero or sign extension on operands a and b.
Aart Bikf3e61ee2017-04-12 17:09:20 -07001697 HInstruction* r = nullptr;
1698 HInstruction* s = nullptr;
1699 bool is_unsigned = false;
Aart Bik304c8a52017-05-23 11:01:13 -07001700 if (!IsNarrowerOperands(a, b, type, &r, &s, &is_unsigned)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -07001701 return false;
1702 }
1703 // Deal with vector restrictions.
1704 if ((!is_unsigned && HasVectorRestrictions(restrictions, kNoSignedHAdd)) ||
1705 (!is_rounded && HasVectorRestrictions(restrictions, kNoUnroundedHAdd))) {
1706 return false;
1707 }
1708 // Accept recognized halving add for vectorizable operands. Vectorized code uses the
1709 // shorthand idiomatic operation. Sequential code uses the original scalar expressions.
1710 DCHECK(r != nullptr && s != nullptr);
Aart Bik304c8a52017-05-23 11:01:13 -07001711 if (generate_code && vector_mode_ != kVector) { // de-idiom
1712 r = instruction->InputAt(0);
1713 s = instruction->InputAt(1);
1714 }
Aart Bikf3e61ee2017-04-12 17:09:20 -07001715 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
1716 VectorizeUse(node, s, generate_code, type, restrictions)) {
1717 if (generate_code) {
1718 if (vector_mode_ == kVector) {
1719 vector_map_->Put(instruction, new (global_allocator_) HVecHalvingAdd(
1720 global_allocator_,
1721 vector_map_->Get(r),
1722 vector_map_->Get(s),
1723 type,
1724 vector_length_,
1725 is_unsigned,
1726 is_rounded));
1727 } else {
Aart Bik304c8a52017-05-23 11:01:13 -07001728 GenerateVecOp(instruction, vector_map_->Get(r), vector_map_->Get(s), type);
Aart Bikf3e61ee2017-04-12 17:09:20 -07001729 }
1730 }
1731 return true;
1732 }
1733 }
1734 }
1735 return false;
1736}
1737
1738//
Aart Bik14a68b42017-06-08 14:06:58 -07001739// Vectorization heuristics.
1740//
1741
1742bool HLoopOptimization::IsVectorizationProfitable(int64_t trip_count) {
1743 // Current heuristic: non-empty body with sufficient number
1744 // of iterations (if known).
1745 // TODO: refine by looking at e.g. operation count, alignment, etc.
1746 if (vector_length_ == 0) {
1747 return false; // nothing found
1748 } else if (0 < trip_count && trip_count < vector_length_) {
1749 return false; // insufficient iterations
1750 }
1751 return true;
1752}
1753
Aart Bikb29f6842017-07-28 15:58:41 -07001754void HLoopOptimization::SetPeelingCandidate(const ArrayReference* candidate,
1755 int64_t trip_count ATTRIBUTE_UNUSED) {
Aart Bik14a68b42017-06-08 14:06:58 -07001756 // Current heuristic: none.
1757 // TODO: implement
Aart Bikb29f6842017-07-28 15:58:41 -07001758 vector_peeling_candidate_ = candidate;
Aart Bik14a68b42017-06-08 14:06:58 -07001759}
1760
1761uint32_t HLoopOptimization::GetUnrollingFactor(HBasicBlock* block, int64_t trip_count) {
1762 // Current heuristic: unroll by 2 on ARM64/X86 for large known trip
1763 // counts and small loop bodies.
1764 // TODO: refine with operation count, remaining iterations, etc.
1765 // Artem had some really cool ideas for this already.
1766 switch (compiler_driver_->GetInstructionSet()) {
1767 case kArm64:
1768 case kX86:
1769 case kX86_64: {
1770 size_t num_instructions = block->GetInstructions().CountSize();
1771 if (num_instructions <= 10 && trip_count >= 4 * vector_length_) {
1772 return 2;
1773 }
1774 return 1;
1775 }
1776 default:
1777 return 1;
1778 }
1779}
1780
1781//
Aart Bikf8f5a162017-02-06 15:35:29 -08001782// Helpers.
1783//
1784
1785bool HLoopOptimization::TrySetPhiInduction(HPhi* phi, bool restrict_uses) {
Aart Bikb29f6842017-07-28 15:58:41 -07001786 // Start with empty phi induction.
1787 iset_->clear();
1788
Nicolas Geoffrayf57c1ae2017-06-28 17:40:18 +01001789 // Special case Phis that have equivalent in a debuggable setup. Our graph checker isn't
1790 // smart enough to follow strongly connected components (and it's probably not worth
1791 // it to make it so). See b/33775412.
1792 if (graph_->IsDebuggable() && phi->HasEquivalentPhi()) {
1793 return false;
1794 }
Aart Bikb29f6842017-07-28 15:58:41 -07001795
1796 // Lookup phi induction cycle.
Aart Bikcc42be02016-10-20 16:14:16 -07001797 ArenaSet<HInstruction*>* set = induction_range_.LookupCycle(phi);
1798 if (set != nullptr) {
1799 for (HInstruction* i : *set) {
Aart Bike3dedc52016-11-02 17:50:27 -07001800 // Check that, other than instructions that are no longer in the graph (removed earlier)
Aart Bikf8f5a162017-02-06 15:35:29 -08001801 // each instruction is removable and, when restrict uses are requested, other than for phi,
1802 // all uses are contained within the cycle.
Aart Bike3dedc52016-11-02 17:50:27 -07001803 if (!i->IsInBlock()) {
1804 continue;
1805 } else if (!i->IsRemovable()) {
1806 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001807 } else if (i != phi && restrict_uses) {
Aart Bikb29f6842017-07-28 15:58:41 -07001808 // Deal with regular uses.
Aart Bikcc42be02016-10-20 16:14:16 -07001809 for (const HUseListNode<HInstruction*>& use : i->GetUses()) {
1810 if (set->find(use.GetUser()) == set->end()) {
1811 return false;
1812 }
1813 }
1814 }
Aart Bike3dedc52016-11-02 17:50:27 -07001815 iset_->insert(i); // copy
Aart Bikcc42be02016-10-20 16:14:16 -07001816 }
Aart Bikcc42be02016-10-20 16:14:16 -07001817 return true;
1818 }
1819 return false;
1820}
1821
Aart Bikb29f6842017-07-28 15:58:41 -07001822bool HLoopOptimization::TrySetPhiReduction(HPhi* phi) {
Aart Bikcc42be02016-10-20 16:14:16 -07001823 DCHECK(iset_->empty());
Aart Bikb29f6842017-07-28 15:58:41 -07001824 // Only unclassified phi cycles are candidates for reductions.
1825 if (induction_range_.IsClassified(phi)) {
1826 return false;
1827 }
1828 // Accept operations like x = x + .., provided that the phi and the reduction are
1829 // used exactly once inside the loop, and by each other.
1830 HInputsRef inputs = phi->GetInputs();
1831 if (inputs.size() == 2) {
1832 HInstruction* reduction = inputs[1];
1833 if (HasReductionFormat(reduction, phi)) {
1834 HLoopInformation* loop_info = phi->GetBlock()->GetLoopInformation();
1835 int32_t use_count = 0;
1836 bool single_use_inside_loop =
1837 // Reduction update only used by phi.
1838 reduction->GetUses().HasExactlyOneElement() &&
1839 !reduction->HasEnvironmentUses() &&
1840 // Reduction update is only use of phi inside the loop.
1841 IsOnlyUsedAfterLoop(loop_info, phi, /*collect_loop_uses*/ true, &use_count) &&
1842 iset_->size() == 1;
1843 iset_->clear(); // leave the way you found it
1844 if (single_use_inside_loop) {
1845 // Link reduction back, and start recording feed value.
1846 reductions_->Put(reduction, phi);
1847 reductions_->Put(phi, phi->InputAt(0));
1848 return true;
1849 }
1850 }
1851 }
1852 return false;
1853}
1854
1855bool HLoopOptimization::TrySetSimpleLoopHeader(HBasicBlock* block, /*out*/ HPhi** main_phi) {
1856 // Start with empty phi induction and reductions.
1857 iset_->clear();
1858 reductions_->clear();
1859
1860 // Scan the phis to find the following (the induction structure has already
1861 // been optimized, so we don't need to worry about trivial cases):
1862 // (1) optional reductions in loop,
1863 // (2) the main induction, used in loop control.
1864 HPhi* phi = nullptr;
1865 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
1866 if (TrySetPhiReduction(it.Current()->AsPhi())) {
1867 continue;
1868 } else if (phi == nullptr) {
1869 // Found the first candidate for main induction.
1870 phi = it.Current()->AsPhi();
1871 } else {
1872 return false;
1873 }
1874 }
1875
1876 // Then test for a typical loopheader:
1877 // s: SuspendCheck
1878 // c: Condition(phi, bound)
1879 // i: If(c)
1880 if (phi != nullptr && TrySetPhiInduction(phi, /*restrict_uses*/ false)) {
Aart Bikcc42be02016-10-20 16:14:16 -07001881 HInstruction* s = block->GetFirstInstruction();
1882 if (s != nullptr && s->IsSuspendCheck()) {
1883 HInstruction* c = s->GetNext();
Aart Bikd86c0852017-04-14 12:00:15 -07001884 if (c != nullptr &&
1885 c->IsCondition() &&
1886 c->GetUses().HasExactlyOneElement() && // only used for termination
1887 !c->HasEnvironmentUses()) { // unlikely, but not impossible
Aart Bikcc42be02016-10-20 16:14:16 -07001888 HInstruction* i = c->GetNext();
1889 if (i != nullptr && i->IsIf() && i->InputAt(0) == c) {
1890 iset_->insert(c);
1891 iset_->insert(s);
Aart Bikb29f6842017-07-28 15:58:41 -07001892 *main_phi = phi;
Aart Bikcc42be02016-10-20 16:14:16 -07001893 return true;
1894 }
1895 }
1896 }
1897 }
1898 return false;
1899}
1900
1901bool HLoopOptimization::IsEmptyBody(HBasicBlock* block) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001902 if (!block->GetPhis().IsEmpty()) {
1903 return false;
1904 }
1905 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
1906 HInstruction* instruction = it.Current();
1907 if (!instruction->IsGoto() && iset_->find(instruction) == iset_->end()) {
1908 return false;
Aart Bikcc42be02016-10-20 16:14:16 -07001909 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001910 }
1911 return true;
1912}
1913
1914bool HLoopOptimization::IsUsedOutsideLoop(HLoopInformation* loop_info,
1915 HInstruction* instruction) {
Aart Bikb29f6842017-07-28 15:58:41 -07001916 // Deal with regular uses.
Aart Bikf8f5a162017-02-06 15:35:29 -08001917 for (const HUseListNode<HInstruction*>& use : instruction->GetUses()) {
1918 if (use.GetUser()->GetBlock()->GetLoopInformation() != loop_info) {
1919 return true;
1920 }
Aart Bikcc42be02016-10-20 16:14:16 -07001921 }
1922 return false;
1923}
1924
Aart Bik482095d2016-10-10 15:39:10 -07001925bool HLoopOptimization::IsOnlyUsedAfterLoop(HLoopInformation* loop_info,
Aart Bik8c4a8542016-10-06 11:36:57 -07001926 HInstruction* instruction,
Aart Bik6b69e0a2017-01-11 10:20:43 -08001927 bool collect_loop_uses,
Aart Bik8c4a8542016-10-06 11:36:57 -07001928 /*out*/ int32_t* use_count) {
Aart Bikb29f6842017-07-28 15:58:41 -07001929 // Deal with regular uses.
Aart Bik8c4a8542016-10-06 11:36:57 -07001930 for (const HUseListNode<HInstruction*>& use : instruction->GetUses()) {
1931 HInstruction* user = use.GetUser();
1932 if (iset_->find(user) == iset_->end()) { // not excluded?
1933 HLoopInformation* other_loop_info = user->GetBlock()->GetLoopInformation();
Aart Bik482095d2016-10-10 15:39:10 -07001934 if (other_loop_info != nullptr && other_loop_info->IsIn(*loop_info)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -08001935 // If collect_loop_uses is set, simply keep adding those uses to the set.
1936 // Otherwise, reject uses inside the loop that were not already in the set.
1937 if (collect_loop_uses) {
1938 iset_->insert(user);
1939 continue;
1940 }
Aart Bik8c4a8542016-10-06 11:36:57 -07001941 return false;
1942 }
1943 ++*use_count;
1944 }
1945 }
1946 return true;
1947}
1948
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01001949bool HLoopOptimization::TryReplaceWithLastValue(HLoopInformation* loop_info,
1950 HInstruction* instruction,
1951 HBasicBlock* block) {
1952 // Try to replace outside uses with the last value.
Aart Bik807868e2016-11-03 17:51:43 -07001953 if (induction_range_.CanGenerateLastValue(instruction)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -08001954 HInstruction* replacement = induction_range_.GenerateLastValue(instruction, graph_, block);
Aart Bikb29f6842017-07-28 15:58:41 -07001955 // Deal with regular uses.
Aart Bik6b69e0a2017-01-11 10:20:43 -08001956 const HUseList<HInstruction*>& uses = instruction->GetUses();
1957 for (auto it = uses.begin(), end = uses.end(); it != end;) {
1958 HInstruction* user = it->GetUser();
1959 size_t index = it->GetIndex();
1960 ++it; // increment before replacing
1961 if (iset_->find(user) == iset_->end()) { // not excluded?
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01001962 if (kIsDebugBuild) {
1963 // We have checked earlier in 'IsOnlyUsedAfterLoop' that the use is after the loop.
1964 HLoopInformation* other_loop_info = user->GetBlock()->GetLoopInformation();
1965 CHECK(other_loop_info == nullptr || !other_loop_info->IsIn(*loop_info));
1966 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08001967 user->ReplaceInput(replacement, index);
1968 induction_range_.Replace(user, instruction, replacement); // update induction
1969 }
1970 }
Aart Bikb29f6842017-07-28 15:58:41 -07001971 // Deal with environment uses.
Aart Bik6b69e0a2017-01-11 10:20:43 -08001972 const HUseList<HEnvironment*>& env_uses = instruction->GetEnvUses();
1973 for (auto it = env_uses.begin(), end = env_uses.end(); it != end;) {
1974 HEnvironment* user = it->GetUser();
1975 size_t index = it->GetIndex();
1976 ++it; // increment before replacing
1977 if (iset_->find(user->GetHolder()) == iset_->end()) { // not excluded?
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01001978 // Only update environment uses after the loop.
Aart Bik14a68b42017-06-08 14:06:58 -07001979 HLoopInformation* other_loop_info = user->GetHolder()->GetBlock()->GetLoopInformation();
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01001980 if (other_loop_info == nullptr || !other_loop_info->IsIn(*loop_info)) {
1981 user->RemoveAsUserOfInput(index);
1982 user->SetRawEnvAt(index, replacement);
1983 replacement->AddEnvUseAt(user, index);
1984 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08001985 }
1986 }
Aart Bik807868e2016-11-03 17:51:43 -07001987 return true;
Aart Bik8c4a8542016-10-06 11:36:57 -07001988 }
Aart Bik807868e2016-11-03 17:51:43 -07001989 return false;
Aart Bik8c4a8542016-10-06 11:36:57 -07001990}
1991
Aart Bikf8f5a162017-02-06 15:35:29 -08001992bool HLoopOptimization::TryAssignLastValue(HLoopInformation* loop_info,
1993 HInstruction* instruction,
1994 HBasicBlock* block,
1995 bool collect_loop_uses) {
1996 // Assigning the last value is always successful if there are no uses.
1997 // Otherwise, it succeeds in a no early-exit loop by generating the
1998 // proper last value assignment.
1999 int32_t use_count = 0;
2000 return IsOnlyUsedAfterLoop(loop_info, instruction, collect_loop_uses, &use_count) &&
2001 (use_count == 0 ||
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002002 (!IsEarlyExit(loop_info) && TryReplaceWithLastValue(loop_info, instruction, block)));
Aart Bikf8f5a162017-02-06 15:35:29 -08002003}
2004
Aart Bik6b69e0a2017-01-11 10:20:43 -08002005void HLoopOptimization::RemoveDeadInstructions(const HInstructionList& list) {
2006 for (HBackwardInstructionIterator i(list); !i.Done(); i.Advance()) {
2007 HInstruction* instruction = i.Current();
2008 if (instruction->IsDeadAndRemovable()) {
2009 simplified_ = true;
2010 instruction->GetBlock()->RemoveInstructionOrPhi(instruction);
2011 }
2012 }
2013}
2014
Aart Bik14a68b42017-06-08 14:06:58 -07002015bool HLoopOptimization::CanRemoveCycle() {
2016 for (HInstruction* i : *iset_) {
2017 // We can never remove instructions that have environment
2018 // uses when we compile 'debuggable'.
2019 if (i->HasEnvironmentUses() && graph_->IsDebuggable()) {
2020 return false;
2021 }
2022 // A deoptimization should never have an environment input removed.
2023 for (const HUseListNode<HEnvironment*>& use : i->GetEnvUses()) {
2024 if (use.GetUser()->GetHolder()->IsDeoptimize()) {
2025 return false;
2026 }
2027 }
2028 }
2029 return true;
2030}
2031
Aart Bik281c6812016-08-26 11:31:48 -07002032} // namespace art