blob: 6b2697bf180903e1383f3ba604fc62a78405dc23 [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
Aart Bik21b85922017-09-06 13:29:16 -0700628 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorized);
Aart Bikb29f6842017-07-28 15:58:41 -0700629 return true;
Aart Bikf8f5a162017-02-06 15:35:29 -0800630 }
Aart Bikb29f6842017-07-28 15:58:41 -0700631 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -0800632}
633
634//
635// Loop vectorization. The implementation is based on the book by Aart J.C. Bik:
636// "The Software Vectorization Handbook. Applying Multimedia Extensions for Maximum Performance."
637// Intel Press, June, 2004 (http://www.aartbik.com/).
638//
639
Aart Bik14a68b42017-06-08 14:06:58 -0700640bool HLoopOptimization::ShouldVectorize(LoopNode* node, HBasicBlock* block, int64_t trip_count) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800641 // Reset vector bookkeeping.
642 vector_length_ = 0;
643 vector_refs_->clear();
Aart Bik14a68b42017-06-08 14:06:58 -0700644 vector_peeling_candidate_ = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800645 vector_runtime_test_a_ =
646 vector_runtime_test_b_= nullptr;
647
648 // Phis in the loop-body prevent vectorization.
649 if (!block->GetPhis().IsEmpty()) {
650 return false;
651 }
652
653 // Scan the loop-body, starting a right-hand-side tree traversal at each left-hand-side
654 // occurrence, which allows passing down attributes down the use tree.
655 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
656 if (!VectorizeDef(node, it.Current(), /*generate_code*/ false)) {
657 return false; // failure to vectorize a left-hand-side
658 }
659 }
660
Aart Bik14a68b42017-06-08 14:06:58 -0700661 // Does vectorization seem profitable?
662 if (!IsVectorizationProfitable(trip_count)) {
663 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -0800664 }
665
666 // Data dependence analysis. Find each pair of references with same type, where
667 // at least one is a write. Each such pair denotes a possible data dependence.
668 // This analysis exploits the property that differently typed arrays cannot be
669 // aliased, as well as the property that references either point to the same
670 // array or to two completely disjoint arrays, i.e., no partial aliasing.
671 // Other than a few simply heuristics, no detailed subscript analysis is done.
Aart Bikb29f6842017-07-28 15:58:41 -0700672 // The scan over references also finds a suitable dynamic loop peeling candidate.
673 const ArrayReference* candidate = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800674 for (auto i = vector_refs_->begin(); i != vector_refs_->end(); ++i) {
675 for (auto j = i; ++j != vector_refs_->end(); ) {
676 if (i->type == j->type && (i->lhs || j->lhs)) {
677 // Found same-typed a[i+x] vs. b[i+y], where at least one is a write.
678 HInstruction* a = i->base;
679 HInstruction* b = j->base;
680 HInstruction* x = i->offset;
681 HInstruction* y = j->offset;
682 if (a == b) {
683 // Found a[i+x] vs. a[i+y]. Accept if x == y (loop-independent data dependence).
684 // Conservatively assume a loop-carried data dependence otherwise, and reject.
685 if (x != y) {
686 return false;
687 }
688 } else {
689 // Found a[i+x] vs. b[i+y]. Accept if x == y (at worst loop-independent data dependence).
690 // Conservatively assume a potential loop-carried data dependence otherwise, avoided by
691 // generating an explicit a != b disambiguation runtime test on the two references.
692 if (x != y) {
Aart Bik37dc4df2017-06-28 14:08:00 -0700693 // To avoid excessive overhead, we only accept one a != b test.
694 if (vector_runtime_test_a_ == nullptr) {
695 // First test found.
696 vector_runtime_test_a_ = a;
697 vector_runtime_test_b_ = b;
698 } else if ((vector_runtime_test_a_ != a || vector_runtime_test_b_ != b) &&
699 (vector_runtime_test_a_ != b || vector_runtime_test_b_ != a)) {
700 return false; // second test would be needed
Aart Bikf8f5a162017-02-06 15:35:29 -0800701 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800702 }
703 }
704 }
705 }
706 }
707
Aart Bik14a68b42017-06-08 14:06:58 -0700708 // Consider dynamic loop peeling for alignment.
Aart Bikb29f6842017-07-28 15:58:41 -0700709 SetPeelingCandidate(candidate, trip_count);
Aart Bik14a68b42017-06-08 14:06:58 -0700710
Aart Bikf8f5a162017-02-06 15:35:29 -0800711 // Success!
712 return true;
713}
714
715void HLoopOptimization::Vectorize(LoopNode* node,
716 HBasicBlock* block,
717 HBasicBlock* exit,
718 int64_t trip_count) {
719 Primitive::Type induc_type = Primitive::kPrimInt;
720 HBasicBlock* header = node->loop_info->GetHeader();
721 HBasicBlock* preheader = node->loop_info->GetPreHeader();
722
Aart Bik14a68b42017-06-08 14:06:58 -0700723 // Pick a loop unrolling factor for the vector loop.
724 uint32_t unroll = GetUnrollingFactor(block, trip_count);
725 uint32_t chunk = vector_length_ * unroll;
726
727 // A cleanup loop is needed, at least, for any unknown trip count or
728 // for a known trip count with remainder iterations after vectorization.
729 bool needs_cleanup = trip_count == 0 || (trip_count % chunk) != 0;
Aart Bikf8f5a162017-02-06 15:35:29 -0800730
731 // Adjust vector bookkeeping.
Aart Bikb29f6842017-07-28 15:58:41 -0700732 HPhi* main_phi = nullptr;
733 bool is_simple_loop_header = TrySetSimpleLoopHeader(header, &main_phi); // refills sets
Aart Bikf8f5a162017-02-06 15:35:29 -0800734 DCHECK(is_simple_loop_header);
Aart Bik14a68b42017-06-08 14:06:58 -0700735 vector_header_ = header;
736 vector_body_ = block;
Aart Bikf8f5a162017-02-06 15:35:29 -0800737
Aart Bikb29f6842017-07-28 15:58:41 -0700738 // Generate dynamic loop peeling trip count, if needed, under the assumption
739 // that the Android runtime guarantees at least "component size" alignment:
740 // ptc = (ALIGN - (&a[initial] % ALIGN)) / type-size
Aart Bik14a68b42017-06-08 14:06:58 -0700741 HInstruction* ptc = nullptr;
742 if (vector_peeling_candidate_ != nullptr) {
743 DCHECK_LT(vector_length_, trip_count) << "dynamic peeling currently requires known trip count";
744 //
745 // TODO: Implement this. Compute address of first access memory location and
746 // compute peeling factor to obtain kAlignedBase alignment.
747 //
748 needs_cleanup = true;
749 }
750
751 // Generate loop control:
Aart Bikf8f5a162017-02-06 15:35:29 -0800752 // stc = <trip-count>;
Aart Bik14a68b42017-06-08 14:06:58 -0700753 // vtc = stc - (stc - ptc) % chunk;
754 // i = 0;
Aart Bikf8f5a162017-02-06 15:35:29 -0800755 HInstruction* stc = induction_range_.GenerateTripCount(node->loop_info, graph_, preheader);
756 HInstruction* vtc = stc;
757 if (needs_cleanup) {
Aart Bik14a68b42017-06-08 14:06:58 -0700758 DCHECK(IsPowerOfTwo(chunk));
759 HInstruction* diff = stc;
760 if (ptc != nullptr) {
761 diff = Insert(preheader, new (global_allocator_) HSub(induc_type, stc, ptc));
762 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800763 HInstruction* rem = Insert(
764 preheader, new (global_allocator_) HAnd(induc_type,
Aart Bik14a68b42017-06-08 14:06:58 -0700765 diff,
766 graph_->GetIntConstant(chunk - 1)));
Aart Bikf8f5a162017-02-06 15:35:29 -0800767 vtc = Insert(preheader, new (global_allocator_) HSub(induc_type, stc, rem));
768 }
Aart Bik14a68b42017-06-08 14:06:58 -0700769 vector_index_ = graph_->GetIntConstant(0);
Aart Bikf8f5a162017-02-06 15:35:29 -0800770
771 // Generate runtime disambiguation test:
772 // vtc = a != b ? vtc : 0;
773 if (vector_runtime_test_a_ != nullptr) {
774 HInstruction* rt = Insert(
775 preheader,
776 new (global_allocator_) HNotEqual(vector_runtime_test_a_, vector_runtime_test_b_));
777 vtc = Insert(preheader,
778 new (global_allocator_) HSelect(rt, vtc, graph_->GetIntConstant(0), kNoDexPc));
779 needs_cleanup = true;
780 }
781
Aart Bik14a68b42017-06-08 14:06:58 -0700782 // Generate dynamic peeling loop for alignment, if needed:
783 // for ( ; i < ptc; i += 1)
784 // <loop-body>
785 if (ptc != nullptr) {
786 vector_mode_ = kSequential;
787 GenerateNewLoop(node,
788 block,
789 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
790 vector_index_,
791 ptc,
792 graph_->GetIntConstant(1),
793 /*unroll*/ 1);
794 }
795
796 // Generate vector loop, possibly further unrolled:
797 // for ( ; i < vtc; i += chunk)
Aart Bikf8f5a162017-02-06 15:35:29 -0800798 // <vectorized-loop-body>
799 vector_mode_ = kVector;
800 GenerateNewLoop(node,
801 block,
Aart Bik14a68b42017-06-08 14:06:58 -0700802 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
803 vector_index_,
Aart Bikf8f5a162017-02-06 15:35:29 -0800804 vtc,
Aart Bik14a68b42017-06-08 14:06:58 -0700805 graph_->GetIntConstant(vector_length_), // increment per unroll
806 unroll);
Aart Bikf8f5a162017-02-06 15:35:29 -0800807 HLoopInformation* vloop = vector_header_->GetLoopInformation();
808
809 // Generate cleanup loop, if needed:
810 // for ( ; i < stc; i += 1)
811 // <loop-body>
812 if (needs_cleanup) {
813 vector_mode_ = kSequential;
814 GenerateNewLoop(node,
815 block,
816 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
Aart Bik14a68b42017-06-08 14:06:58 -0700817 vector_index_,
Aart Bikf8f5a162017-02-06 15:35:29 -0800818 stc,
Aart Bik14a68b42017-06-08 14:06:58 -0700819 graph_->GetIntConstant(1),
820 /*unroll*/ 1);
Aart Bikf8f5a162017-02-06 15:35:29 -0800821 }
822
Aart Bik0148de42017-09-05 09:25:01 -0700823 // Link reductions to their final uses.
824 for (auto i = reductions_->begin(); i != reductions_->end(); ++i) {
825 if (i->first->IsPhi()) {
826 i->first->ReplaceWith(ReduceAndExtractIfNeeded(i->second));
827 }
828 }
829
Aart Bikf8f5a162017-02-06 15:35:29 -0800830 // Remove the original loop by disconnecting the body block
831 // and removing all instructions from the header.
832 block->DisconnectAndDelete();
833 while (!header->GetFirstInstruction()->IsGoto()) {
834 header->RemoveInstruction(header->GetFirstInstruction());
835 }
Aart Bikb29f6842017-07-28 15:58:41 -0700836
Aart Bik14a68b42017-06-08 14:06:58 -0700837 // Update loop hierarchy: the old header now resides in the same outer loop
838 // as the old preheader. Note that we don't bother putting sequential
839 // loops back in the hierarchy at this point.
Aart Bikf8f5a162017-02-06 15:35:29 -0800840 header->SetLoopInformation(preheader->GetLoopInformation()); // outward
841 node->loop_info = vloop;
842}
843
844void HLoopOptimization::GenerateNewLoop(LoopNode* node,
845 HBasicBlock* block,
846 HBasicBlock* new_preheader,
847 HInstruction* lo,
848 HInstruction* hi,
Aart Bik14a68b42017-06-08 14:06:58 -0700849 HInstruction* step,
850 uint32_t unroll) {
851 DCHECK(unroll == 1 || vector_mode_ == kVector);
Aart Bikf8f5a162017-02-06 15:35:29 -0800852 Primitive::Type induc_type = Primitive::kPrimInt;
853 // Prepare new loop.
Aart Bikf8f5a162017-02-06 15:35:29 -0800854 vector_preheader_ = new_preheader,
855 vector_header_ = vector_preheader_->GetSingleSuccessor();
856 vector_body_ = vector_header_->GetSuccessors()[1];
Aart Bik14a68b42017-06-08 14:06:58 -0700857 HPhi* phi = new (global_allocator_) HPhi(global_allocator_,
858 kNoRegNumber,
859 0,
860 HPhi::ToPhiType(induc_type));
Aart Bikb07d1bc2017-04-05 10:03:15 -0700861 // Generate header and prepare body.
Aart Bikf8f5a162017-02-06 15:35:29 -0800862 // for (i = lo; i < hi; i += step)
863 // <loop-body>
Aart Bik14a68b42017-06-08 14:06:58 -0700864 HInstruction* cond = new (global_allocator_) HAboveOrEqual(phi, hi);
865 vector_header_->AddPhi(phi);
Aart Bikf8f5a162017-02-06 15:35:29 -0800866 vector_header_->AddInstruction(cond);
867 vector_header_->AddInstruction(new (global_allocator_) HIf(cond));
Aart Bik14a68b42017-06-08 14:06:58 -0700868 vector_index_ = phi;
Aart Bik0148de42017-09-05 09:25:01 -0700869 vector_permanent_map_->clear(); // preserved over unrolling
Aart Bik14a68b42017-06-08 14:06:58 -0700870 for (uint32_t u = 0; u < unroll; u++) {
Aart Bik14a68b42017-06-08 14:06:58 -0700871 // Generate instruction map.
Aart Bik0148de42017-09-05 09:25:01 -0700872 vector_map_->clear();
Aart Bik14a68b42017-06-08 14:06:58 -0700873 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
874 bool vectorized_def = VectorizeDef(node, it.Current(), /*generate_code*/ true);
875 DCHECK(vectorized_def);
876 }
877 // Generate body from the instruction map, but in original program order.
878 HEnvironment* env = vector_header_->GetFirstInstruction()->GetEnvironment();
879 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
880 auto i = vector_map_->find(it.Current());
881 if (i != vector_map_->end() && !i->second->IsInBlock()) {
882 Insert(vector_body_, i->second);
883 // Deal with instructions that need an environment, such as the scalar intrinsics.
884 if (i->second->NeedsEnvironment()) {
885 i->second->CopyEnvironmentFromWithLoopPhiAdjustment(env, vector_header_);
886 }
887 }
888 }
Aart Bik0148de42017-09-05 09:25:01 -0700889 // Generate the induction.
Aart Bik14a68b42017-06-08 14:06:58 -0700890 vector_index_ = new (global_allocator_) HAdd(induc_type, vector_index_, step);
891 Insert(vector_body_, vector_index_);
Aart Bikf8f5a162017-02-06 15:35:29 -0800892 }
Aart Bik0148de42017-09-05 09:25:01 -0700893 // Finalize phi inputs for the reductions (if any).
894 for (auto i = reductions_->begin(); i != reductions_->end(); ++i) {
895 if (!i->first->IsPhi()) {
896 DCHECK(i->second->IsPhi());
897 GenerateVecReductionPhiInputs(i->second->AsPhi(), i->first);
898 }
899 }
Aart Bikb29f6842017-07-28 15:58:41 -0700900 // Finalize phi inputs for the loop index.
Aart Bik14a68b42017-06-08 14:06:58 -0700901 phi->AddInput(lo);
902 phi->AddInput(vector_index_);
903 vector_index_ = phi;
Aart Bikf8f5a162017-02-06 15:35:29 -0800904}
905
Aart Bikf8f5a162017-02-06 15:35:29 -0800906bool HLoopOptimization::VectorizeDef(LoopNode* node,
907 HInstruction* instruction,
908 bool generate_code) {
909 // Accept a left-hand-side array base[index] for
910 // (1) supported vector type,
911 // (2) loop-invariant base,
912 // (3) unit stride index,
913 // (4) vectorizable right-hand-side value.
914 uint64_t restrictions = kNone;
915 if (instruction->IsArraySet()) {
916 Primitive::Type type = instruction->AsArraySet()->GetComponentType();
917 HInstruction* base = instruction->InputAt(0);
918 HInstruction* index = instruction->InputAt(1);
919 HInstruction* value = instruction->InputAt(2);
920 HInstruction* offset = nullptr;
921 if (TrySetVectorType(type, &restrictions) &&
922 node->loop_info->IsDefinedOutOfTheLoop(base) &&
Aart Bik37dc4df2017-06-28 14:08:00 -0700923 induction_range_.IsUnitStride(instruction, index, graph_, &offset) &&
Aart Bikf8f5a162017-02-06 15:35:29 -0800924 VectorizeUse(node, value, generate_code, type, restrictions)) {
925 if (generate_code) {
926 GenerateVecSub(index, offset);
Aart Bik14a68b42017-06-08 14:06:58 -0700927 GenerateVecMem(instruction, vector_map_->Get(index), vector_map_->Get(value), offset, type);
Aart Bikf8f5a162017-02-06 15:35:29 -0800928 } else {
929 vector_refs_->insert(ArrayReference(base, offset, type, /*lhs*/ true));
930 }
Aart Bik6b69e0a2017-01-11 10:20:43 -0800931 return true;
932 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800933 return false;
934 }
Aart Bik0148de42017-09-05 09:25:01 -0700935 // Accept a left-hand-side reduction for
936 // (1) supported vector type,
937 // (2) vectorizable right-hand-side value.
938 auto redit = reductions_->find(instruction);
939 if (redit != reductions_->end()) {
940 Primitive::Type type = instruction->GetType();
941 if (TrySetVectorType(type, &restrictions) &&
942 VectorizeUse(node, instruction, generate_code, type, restrictions)) {
943 if (generate_code) {
944 HInstruction* new_red = vector_map_->Get(instruction);
945 vector_permanent_map_->Put(new_red, vector_map_->Get(redit->second));
946 vector_permanent_map_->Overwrite(redit->second, new_red);
947 }
948 return true;
949 }
950 return false;
951 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800952 // Branch back okay.
953 if (instruction->IsGoto()) {
954 return true;
955 }
956 // Otherwise accept only expressions with no effects outside the immediate loop-body.
957 // Note that actual uses are inspected during right-hand-side tree traversal.
958 return !IsUsedOutsideLoop(node->loop_info, instruction) && !instruction->DoesAnyWrite();
959}
960
Aart Bik304c8a52017-05-23 11:01:13 -0700961// TODO: saturation arithmetic.
Aart Bikf8f5a162017-02-06 15:35:29 -0800962bool HLoopOptimization::VectorizeUse(LoopNode* node,
963 HInstruction* instruction,
964 bool generate_code,
965 Primitive::Type type,
966 uint64_t restrictions) {
967 // Accept anything for which code has already been generated.
968 if (generate_code) {
969 if (vector_map_->find(instruction) != vector_map_->end()) {
970 return true;
971 }
972 }
973 // Continue the right-hand-side tree traversal, passing in proper
974 // types and vector restrictions along the way. During code generation,
975 // all new nodes are drawn from the global allocator.
976 if (node->loop_info->IsDefinedOutOfTheLoop(instruction)) {
977 // Accept invariant use, using scalar expansion.
978 if (generate_code) {
979 GenerateVecInv(instruction, type);
980 }
981 return true;
982 } else if (instruction->IsArrayGet()) {
Goran Jakovljevic19680d32017-05-11 10:38:36 +0200983 // Deal with vector restrictions.
984 if (instruction->AsArrayGet()->IsStringCharAt() &&
985 HasVectorRestrictions(restrictions, kNoStringCharAt)) {
986 return false;
987 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800988 // Accept a right-hand-side array base[index] for
989 // (1) exact matching vector type,
990 // (2) loop-invariant base,
991 // (3) unit stride index,
992 // (4) vectorizable right-hand-side value.
993 HInstruction* base = instruction->InputAt(0);
994 HInstruction* index = instruction->InputAt(1);
995 HInstruction* offset = nullptr;
996 if (type == instruction->GetType() &&
997 node->loop_info->IsDefinedOutOfTheLoop(base) &&
Aart Bik37dc4df2017-06-28 14:08:00 -0700998 induction_range_.IsUnitStride(instruction, index, graph_, &offset)) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800999 if (generate_code) {
1000 GenerateVecSub(index, offset);
Aart Bik14a68b42017-06-08 14:06:58 -07001001 GenerateVecMem(instruction, vector_map_->Get(index), nullptr, offset, type);
Aart Bikf8f5a162017-02-06 15:35:29 -08001002 } else {
1003 vector_refs_->insert(ArrayReference(base, offset, type, /*lhs*/ false));
1004 }
1005 return true;
1006 }
Aart Bik0148de42017-09-05 09:25:01 -07001007 } else if (instruction->IsPhi()) {
1008 // Accept particular phi operations.
1009 if (reductions_->find(instruction) != reductions_->end()) {
1010 // Deal with vector restrictions.
1011 if (HasVectorRestrictions(restrictions, kNoReduction)) {
1012 return false;
1013 }
1014 // Accept a reduction.
1015 if (generate_code) {
1016 GenerateVecReductionPhi(instruction->AsPhi());
1017 }
1018 return true;
1019 }
1020 // TODO: accept right-hand-side induction?
1021 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001022 } else if (instruction->IsTypeConversion()) {
1023 // Accept particular type conversions.
1024 HTypeConversion* conversion = instruction->AsTypeConversion();
1025 HInstruction* opa = conversion->InputAt(0);
1026 Primitive::Type from = conversion->GetInputType();
1027 Primitive::Type to = conversion->GetResultType();
1028 if ((to == Primitive::kPrimByte ||
1029 to == Primitive::kPrimChar ||
1030 to == Primitive::kPrimShort) && from == Primitive::kPrimInt) {
1031 // Accept a "narrowing" type conversion from a "wider" computation for
1032 // (1) conversion into final required type,
1033 // (2) vectorizable operand,
1034 // (3) "wider" operations cannot bring in higher order bits.
1035 if (to == type && VectorizeUse(node, opa, generate_code, type, restrictions | kNoHiBits)) {
1036 if (generate_code) {
1037 if (vector_mode_ == kVector) {
1038 vector_map_->Put(instruction, vector_map_->Get(opa)); // operand pass-through
1039 } else {
1040 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1041 }
1042 }
1043 return true;
1044 }
1045 } else if (to == Primitive::kPrimFloat && from == Primitive::kPrimInt) {
1046 DCHECK_EQ(to, type);
1047 // Accept int to float conversion for
1048 // (1) supported int,
1049 // (2) vectorizable operand.
1050 if (TrySetVectorType(from, &restrictions) &&
1051 VectorizeUse(node, opa, generate_code, from, restrictions)) {
1052 if (generate_code) {
1053 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1054 }
1055 return true;
1056 }
1057 }
1058 return false;
1059 } else if (instruction->IsNeg() || instruction->IsNot() || instruction->IsBooleanNot()) {
1060 // Accept unary operator for vectorizable operand.
1061 HInstruction* opa = instruction->InputAt(0);
1062 if (VectorizeUse(node, opa, generate_code, type, restrictions)) {
1063 if (generate_code) {
1064 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1065 }
1066 return true;
1067 }
1068 } else if (instruction->IsAdd() || instruction->IsSub() ||
1069 instruction->IsMul() || instruction->IsDiv() ||
1070 instruction->IsAnd() || instruction->IsOr() || instruction->IsXor()) {
1071 // Deal with vector restrictions.
1072 if ((instruction->IsMul() && HasVectorRestrictions(restrictions, kNoMul)) ||
1073 (instruction->IsDiv() && HasVectorRestrictions(restrictions, kNoDiv))) {
1074 return false;
1075 }
1076 // Accept binary operator for vectorizable operands.
1077 HInstruction* opa = instruction->InputAt(0);
1078 HInstruction* opb = instruction->InputAt(1);
1079 if (VectorizeUse(node, opa, generate_code, type, restrictions) &&
1080 VectorizeUse(node, opb, generate_code, type, restrictions)) {
1081 if (generate_code) {
1082 GenerateVecOp(instruction, vector_map_->Get(opa), vector_map_->Get(opb), type);
1083 }
1084 return true;
1085 }
1086 } else if (instruction->IsShl() || instruction->IsShr() || instruction->IsUShr()) {
Aart Bikf3e61ee2017-04-12 17:09:20 -07001087 // Recognize vectorization idioms.
1088 if (VectorizeHalvingAddIdiom(node, instruction, generate_code, type, restrictions)) {
1089 return true;
1090 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001091 // Deal with vector restrictions.
Aart Bik304c8a52017-05-23 11:01:13 -07001092 HInstruction* opa = instruction->InputAt(0);
1093 HInstruction* opb = instruction->InputAt(1);
1094 HInstruction* r = opa;
1095 bool is_unsigned = false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001096 if ((HasVectorRestrictions(restrictions, kNoShift)) ||
1097 (instruction->IsShr() && HasVectorRestrictions(restrictions, kNoShr))) {
1098 return false; // unsupported instruction
Aart Bik304c8a52017-05-23 11:01:13 -07001099 } else if (HasVectorRestrictions(restrictions, kNoHiBits)) {
1100 // Shifts right need extra care to account for higher order bits.
1101 // TODO: less likely shr/unsigned and ushr/signed can by flipping signess.
1102 if (instruction->IsShr() &&
1103 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || is_unsigned)) {
1104 return false; // reject, unless all operands are sign-extension narrower
1105 } else if (instruction->IsUShr() &&
1106 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || !is_unsigned)) {
1107 return false; // reject, unless all operands are zero-extension narrower
1108 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001109 }
1110 // Accept shift operator for vectorizable/invariant operands.
1111 // TODO: accept symbolic, albeit loop invariant shift factors.
Aart Bik304c8a52017-05-23 11:01:13 -07001112 DCHECK(r != nullptr);
1113 if (generate_code && vector_mode_ != kVector) { // de-idiom
1114 r = opa;
1115 }
Aart Bik50e20d52017-05-05 14:07:29 -07001116 int64_t distance = 0;
Aart Bik304c8a52017-05-23 11:01:13 -07001117 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
Aart Bik50e20d52017-05-05 14:07:29 -07001118 IsInt64AndGet(opb, /*out*/ &distance)) {
Aart Bik65ffd8e2017-05-01 16:50:45 -07001119 // Restrict shift distance to packed data type width.
1120 int64_t max_distance = Primitive::ComponentSize(type) * 8;
1121 if (0 <= distance && distance < max_distance) {
1122 if (generate_code) {
Aart Bik304c8a52017-05-23 11:01:13 -07001123 GenerateVecOp(instruction, vector_map_->Get(r), opb, type);
Aart Bik65ffd8e2017-05-01 16:50:45 -07001124 }
1125 return true;
Aart Bikf8f5a162017-02-06 15:35:29 -08001126 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001127 }
1128 } else if (instruction->IsInvokeStaticOrDirect()) {
Aart Bik6daebeb2017-04-03 14:35:41 -07001129 // Accept particular intrinsics.
1130 HInvokeStaticOrDirect* invoke = instruction->AsInvokeStaticOrDirect();
1131 switch (invoke->GetIntrinsic()) {
1132 case Intrinsics::kMathAbsInt:
1133 case Intrinsics::kMathAbsLong:
1134 case Intrinsics::kMathAbsFloat:
1135 case Intrinsics::kMathAbsDouble: {
1136 // Deal with vector restrictions.
Aart Bik304c8a52017-05-23 11:01:13 -07001137 HInstruction* opa = instruction->InputAt(0);
1138 HInstruction* r = opa;
1139 bool is_unsigned = false;
1140 if (HasVectorRestrictions(restrictions, kNoAbs)) {
Aart Bik6daebeb2017-04-03 14:35:41 -07001141 return false;
Aart Bik304c8a52017-05-23 11:01:13 -07001142 } else if (HasVectorRestrictions(restrictions, kNoHiBits) &&
1143 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || is_unsigned)) {
1144 return false; // reject, unless operand is sign-extension narrower
Aart Bik6daebeb2017-04-03 14:35:41 -07001145 }
1146 // Accept ABS(x) for vectorizable operand.
Aart Bik304c8a52017-05-23 11:01:13 -07001147 DCHECK(r != nullptr);
1148 if (generate_code && vector_mode_ != kVector) { // de-idiom
1149 r = opa;
1150 }
1151 if (VectorizeUse(node, r, generate_code, type, restrictions)) {
Aart Bik6daebeb2017-04-03 14:35:41 -07001152 if (generate_code) {
Aart Bik304c8a52017-05-23 11:01:13 -07001153 GenerateVecOp(instruction, vector_map_->Get(r), nullptr, type);
Aart Bik6daebeb2017-04-03 14:35:41 -07001154 }
1155 return true;
1156 }
1157 return false;
1158 }
Aart Bikc8e93c72017-05-10 10:49:22 -07001159 case Intrinsics::kMathMinIntInt:
1160 case Intrinsics::kMathMinLongLong:
1161 case Intrinsics::kMathMinFloatFloat:
1162 case Intrinsics::kMathMinDoubleDouble:
1163 case Intrinsics::kMathMaxIntInt:
1164 case Intrinsics::kMathMaxLongLong:
1165 case Intrinsics::kMathMaxFloatFloat:
1166 case Intrinsics::kMathMaxDoubleDouble: {
1167 // Deal with vector restrictions.
Nicolas Geoffray92316902017-05-23 08:06:07 +00001168 HInstruction* opa = instruction->InputAt(0);
1169 HInstruction* opb = instruction->InputAt(1);
Aart Bik304c8a52017-05-23 11:01:13 -07001170 HInstruction* r = opa;
1171 HInstruction* s = opb;
1172 bool is_unsigned = false;
1173 if (HasVectorRestrictions(restrictions, kNoMinMax)) {
1174 return false;
1175 } else if (HasVectorRestrictions(restrictions, kNoHiBits) &&
1176 !IsNarrowerOperands(opa, opb, type, &r, &s, &is_unsigned)) {
1177 return false; // reject, unless all operands are same-extension narrower
1178 }
1179 // Accept MIN/MAX(x, y) for vectorizable operands.
1180 DCHECK(r != nullptr && s != nullptr);
1181 if (generate_code && vector_mode_ != kVector) { // de-idiom
1182 r = opa;
1183 s = opb;
1184 }
1185 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
1186 VectorizeUse(node, s, generate_code, type, restrictions)) {
Aart Bikc8e93c72017-05-10 10:49:22 -07001187 if (generate_code) {
Aart Bik304c8a52017-05-23 11:01:13 -07001188 GenerateVecOp(
1189 instruction, vector_map_->Get(r), vector_map_->Get(s), type, is_unsigned);
Aart Bikc8e93c72017-05-10 10:49:22 -07001190 }
1191 return true;
1192 }
1193 return false;
1194 }
Aart Bik6daebeb2017-04-03 14:35:41 -07001195 default:
1196 return false;
1197 } // switch
Aart Bik281c6812016-08-26 11:31:48 -07001198 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08001199 return false;
Aart Bik281c6812016-08-26 11:31:48 -07001200}
1201
Aart Bikf8f5a162017-02-06 15:35:29 -08001202bool HLoopOptimization::TrySetVectorType(Primitive::Type type, uint64_t* restrictions) {
1203 const InstructionSetFeatures* features = compiler_driver_->GetInstructionSetFeatures();
1204 switch (compiler_driver_->GetInstructionSet()) {
1205 case kArm:
1206 case kThumb2:
Artem Serov8f7c4102017-06-21 11:21:37 +01001207 // Allow vectorization for all ARM devices, because Android assumes that
Aart Bikb29f6842017-07-28 15:58:41 -07001208 // ARM 32-bit always supports advanced SIMD (64-bit SIMD).
Artem Serov8f7c4102017-06-21 11:21:37 +01001209 switch (type) {
1210 case Primitive::kPrimBoolean:
1211 case Primitive::kPrimByte:
Aart Bik0148de42017-09-05 09:25:01 -07001212 *restrictions |= kNoDiv | kNoReduction;
Artem Serov8f7c4102017-06-21 11:21:37 +01001213 return TrySetVectorLength(8);
1214 case Primitive::kPrimChar:
1215 case Primitive::kPrimShort:
Aart Bik0148de42017-09-05 09:25:01 -07001216 *restrictions |= kNoDiv | kNoStringCharAt | kNoReduction;
Artem Serov8f7c4102017-06-21 11:21:37 +01001217 return TrySetVectorLength(4);
1218 case Primitive::kPrimInt:
Aart Bik0148de42017-09-05 09:25:01 -07001219 *restrictions |= kNoDiv | kNoReduction;
Artem Serov8f7c4102017-06-21 11:21:37 +01001220 return TrySetVectorLength(2);
1221 default:
1222 break;
1223 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001224 return false;
1225 case kArm64:
1226 // Allow vectorization for all ARM devices, because Android assumes that
Aart Bikb29f6842017-07-28 15:58:41 -07001227 // ARMv8 AArch64 always supports advanced SIMD (128-bit SIMD).
Aart Bikf8f5a162017-02-06 15:35:29 -08001228 switch (type) {
1229 case Primitive::kPrimBoolean:
1230 case Primitive::kPrimByte:
Aart Bik0148de42017-09-05 09:25:01 -07001231 *restrictions |= kNoDiv | kNoReduction;
Artem Serovd4bccf12017-04-03 18:47:32 +01001232 return TrySetVectorLength(16);
Aart Bikf8f5a162017-02-06 15:35:29 -08001233 case Primitive::kPrimChar:
1234 case Primitive::kPrimShort:
Aart Bik0148de42017-09-05 09:25:01 -07001235 *restrictions |= kNoDiv | kNoReduction;
Artem Serovd4bccf12017-04-03 18:47:32 +01001236 return TrySetVectorLength(8);
Aart Bikf8f5a162017-02-06 15:35:29 -08001237 case Primitive::kPrimInt:
1238 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +01001239 return TrySetVectorLength(4);
Artem Serovb31f91f2017-04-05 11:31:19 +01001240 case Primitive::kPrimLong:
Aart Bikc8e93c72017-05-10 10:49:22 -07001241 *restrictions |= kNoDiv | kNoMul | kNoMinMax;
Aart Bikf8f5a162017-02-06 15:35:29 -08001242 return TrySetVectorLength(2);
1243 case Primitive::kPrimFloat:
Aart Bik0148de42017-09-05 09:25:01 -07001244 *restrictions |= kNoReduction;
Artem Serovd4bccf12017-04-03 18:47:32 +01001245 return TrySetVectorLength(4);
Artem Serovb31f91f2017-04-05 11:31:19 +01001246 case Primitive::kPrimDouble:
Aart Bik0148de42017-09-05 09:25:01 -07001247 *restrictions |= kNoReduction;
Aart Bikf8f5a162017-02-06 15:35:29 -08001248 return TrySetVectorLength(2);
1249 default:
1250 return false;
1251 }
1252 case kX86:
1253 case kX86_64:
Aart Bikb29f6842017-07-28 15:58:41 -07001254 // Allow vectorization for SSE4.1-enabled X86 devices only (128-bit SIMD).
Aart Bikf8f5a162017-02-06 15:35:29 -08001255 if (features->AsX86InstructionSetFeatures()->HasSSE4_1()) {
1256 switch (type) {
1257 case Primitive::kPrimBoolean:
1258 case Primitive::kPrimByte:
Aart Bik0148de42017-09-05 09:25:01 -07001259 *restrictions |=
1260 kNoMul | kNoDiv | kNoShift | kNoAbs | kNoSignedHAdd | kNoUnroundedHAdd | kNoReduction;
Aart Bikf8f5a162017-02-06 15:35:29 -08001261 return TrySetVectorLength(16);
1262 case Primitive::kPrimChar:
1263 case Primitive::kPrimShort:
Aart Bik0148de42017-09-05 09:25:01 -07001264 *restrictions |= kNoDiv | kNoAbs | kNoSignedHAdd | kNoUnroundedHAdd | kNoReduction;
Aart Bikf8f5a162017-02-06 15:35:29 -08001265 return TrySetVectorLength(8);
1266 case Primitive::kPrimInt:
1267 *restrictions |= kNoDiv;
1268 return TrySetVectorLength(4);
1269 case Primitive::kPrimLong:
Aart Bikc8e93c72017-05-10 10:49:22 -07001270 *restrictions |= kNoMul | kNoDiv | kNoShr | kNoAbs | kNoMinMax;
Aart Bikf8f5a162017-02-06 15:35:29 -08001271 return TrySetVectorLength(2);
1272 case Primitive::kPrimFloat:
Aart Bik0148de42017-09-05 09:25:01 -07001273 *restrictions |= kNoMinMax | kNoReduction; // minmax: -0.0 vs +0.0
Aart Bikf8f5a162017-02-06 15:35:29 -08001274 return TrySetVectorLength(4);
1275 case Primitive::kPrimDouble:
Aart Bik0148de42017-09-05 09:25:01 -07001276 *restrictions |= kNoMinMax | kNoReduction; // minmax: -0.0 vs +0.0
Aart Bikf8f5a162017-02-06 15:35:29 -08001277 return TrySetVectorLength(2);
1278 default:
1279 break;
1280 } // switch type
1281 }
1282 return false;
1283 case kMips:
Lena Djokic51765b02017-06-22 13:49:59 +02001284 if (features->AsMipsInstructionSetFeatures()->HasMsa()) {
1285 switch (type) {
1286 case Primitive::kPrimBoolean:
1287 case Primitive::kPrimByte:
Aart Bik0148de42017-09-05 09:25:01 -07001288 *restrictions |= kNoDiv | kNoReduction;
Lena Djokic51765b02017-06-22 13:49:59 +02001289 return TrySetVectorLength(16);
1290 case Primitive::kPrimChar:
1291 case Primitive::kPrimShort:
Aart Bik0148de42017-09-05 09:25:01 -07001292 *restrictions |= kNoDiv | kNoStringCharAt | kNoReduction;
Lena Djokic51765b02017-06-22 13:49:59 +02001293 return TrySetVectorLength(8);
1294 case Primitive::kPrimInt:
Aart Bik0148de42017-09-05 09:25:01 -07001295 *restrictions |= kNoDiv | kNoReduction;
Lena Djokic51765b02017-06-22 13:49:59 +02001296 return TrySetVectorLength(4);
1297 case Primitive::kPrimLong:
Aart Bik0148de42017-09-05 09:25:01 -07001298 *restrictions |= kNoDiv | kNoReduction;
Lena Djokic51765b02017-06-22 13:49:59 +02001299 return TrySetVectorLength(2);
1300 case Primitive::kPrimFloat:
Aart Bik0148de42017-09-05 09:25:01 -07001301 *restrictions |= kNoMinMax | kNoReduction; // min/max(x, NaN)
Lena Djokic51765b02017-06-22 13:49:59 +02001302 return TrySetVectorLength(4);
1303 case Primitive::kPrimDouble:
Aart Bik0148de42017-09-05 09:25:01 -07001304 *restrictions |= kNoMinMax | kNoReduction; // min/max(x, NaN)
Lena Djokic51765b02017-06-22 13:49:59 +02001305 return TrySetVectorLength(2);
1306 default:
1307 break;
1308 } // switch type
1309 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001310 return false;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001311 case kMips64:
1312 if (features->AsMips64InstructionSetFeatures()->HasMsa()) {
1313 switch (type) {
1314 case Primitive::kPrimBoolean:
1315 case Primitive::kPrimByte:
Aart Bik0148de42017-09-05 09:25:01 -07001316 *restrictions |= kNoDiv | kNoReduction;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001317 return TrySetVectorLength(16);
1318 case Primitive::kPrimChar:
1319 case Primitive::kPrimShort:
Aart Bik0148de42017-09-05 09:25:01 -07001320 *restrictions |= kNoDiv | kNoStringCharAt | kNoReduction;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001321 return TrySetVectorLength(8);
1322 case Primitive::kPrimInt:
Aart Bik0148de42017-09-05 09:25:01 -07001323 *restrictions |= kNoDiv | kNoReduction;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001324 return TrySetVectorLength(4);
1325 case Primitive::kPrimLong:
Aart Bik0148de42017-09-05 09:25:01 -07001326 *restrictions |= kNoDiv | kNoReduction;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001327 return TrySetVectorLength(2);
1328 case Primitive::kPrimFloat:
Aart Bik0148de42017-09-05 09:25:01 -07001329 *restrictions |= kNoMinMax | kNoReduction; // min/max(x, NaN)
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001330 return TrySetVectorLength(4);
1331 case Primitive::kPrimDouble:
Aart Bik0148de42017-09-05 09:25:01 -07001332 *restrictions |= kNoMinMax | kNoReduction; // min/max(x, NaN)
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001333 return TrySetVectorLength(2);
1334 default:
1335 break;
1336 } // switch type
1337 }
1338 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001339 default:
1340 return false;
1341 } // switch instruction set
1342}
1343
1344bool HLoopOptimization::TrySetVectorLength(uint32_t length) {
1345 DCHECK(IsPowerOfTwo(length) && length >= 2u);
1346 // First time set?
1347 if (vector_length_ == 0) {
1348 vector_length_ = length;
1349 }
1350 // Different types are acceptable within a loop-body, as long as all the corresponding vector
1351 // lengths match exactly to obtain a uniform traversal through the vector iteration space
1352 // (idiomatic exceptions to this rule can be handled by further unrolling sub-expressions).
1353 return vector_length_ == length;
1354}
1355
1356void HLoopOptimization::GenerateVecInv(HInstruction* org, Primitive::Type type) {
1357 if (vector_map_->find(org) == vector_map_->end()) {
1358 // In scalar code, just use a self pass-through for scalar invariants
1359 // (viz. expression remains itself).
1360 if (vector_mode_ == kSequential) {
1361 vector_map_->Put(org, org);
1362 return;
1363 }
1364 // In vector code, explicit scalar expansion is needed.
Aart Bik0148de42017-09-05 09:25:01 -07001365 HInstruction* vector = nullptr;
1366 auto it = vector_permanent_map_->find(org);
1367 if (it != vector_permanent_map_->end()) {
1368 vector = it->second; // reuse during unrolling
1369 } else {
1370 vector = new (global_allocator_) HVecReplicateScalar(
1371 global_allocator_, org, type, vector_length_);
1372 vector_permanent_map_->Put(org, Insert(vector_preheader_, vector));
1373 }
1374 vector_map_->Put(org, vector);
Aart Bikf8f5a162017-02-06 15:35:29 -08001375 }
1376}
1377
1378void HLoopOptimization::GenerateVecSub(HInstruction* org, HInstruction* offset) {
1379 if (vector_map_->find(org) == vector_map_->end()) {
Aart Bik14a68b42017-06-08 14:06:58 -07001380 HInstruction* subscript = vector_index_;
Aart Bik37dc4df2017-06-28 14:08:00 -07001381 int64_t value = 0;
1382 if (!IsInt64AndGet(offset, &value) || value != 0) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001383 subscript = new (global_allocator_) HAdd(Primitive::kPrimInt, subscript, offset);
1384 if (org->IsPhi()) {
1385 Insert(vector_body_, subscript); // lacks layout placeholder
1386 }
1387 }
1388 vector_map_->Put(org, subscript);
1389 }
1390}
1391
1392void HLoopOptimization::GenerateVecMem(HInstruction* org,
1393 HInstruction* opa,
1394 HInstruction* opb,
Aart Bik14a68b42017-06-08 14:06:58 -07001395 HInstruction* offset,
Aart Bikf8f5a162017-02-06 15:35:29 -08001396 Primitive::Type type) {
1397 HInstruction* vector = nullptr;
1398 if (vector_mode_ == kVector) {
1399 // Vector store or load.
Aart Bik14a68b42017-06-08 14:06:58 -07001400 HInstruction* base = org->InputAt(0);
Aart Bikf8f5a162017-02-06 15:35:29 -08001401 if (opb != nullptr) {
1402 vector = new (global_allocator_) HVecStore(
Aart Bik14a68b42017-06-08 14:06:58 -07001403 global_allocator_, base, opa, opb, type, vector_length_);
Aart Bikf8f5a162017-02-06 15:35:29 -08001404 } else {
Aart Bikdb14fcf2017-04-25 15:53:58 -07001405 bool is_string_char_at = org->AsArrayGet()->IsStringCharAt();
Aart Bikf8f5a162017-02-06 15:35:29 -08001406 vector = new (global_allocator_) HVecLoad(
Aart Bik14a68b42017-06-08 14:06:58 -07001407 global_allocator_, base, opa, type, vector_length_, is_string_char_at);
1408 }
1409 // Known dynamically enforced alignment?
Aart Bik14a68b42017-06-08 14:06:58 -07001410 if (vector_peeling_candidate_ != nullptr &&
1411 vector_peeling_candidate_->base == base &&
1412 vector_peeling_candidate_->offset == offset) {
1413 vector->AsVecMemoryOperation()->SetAlignment(Alignment(kAlignedBase, 0));
Aart Bikf8f5a162017-02-06 15:35:29 -08001414 }
1415 } else {
1416 // Scalar store or load.
1417 DCHECK(vector_mode_ == kSequential);
1418 if (opb != nullptr) {
1419 vector = new (global_allocator_) HArraySet(org->InputAt(0), opa, opb, type, kNoDexPc);
1420 } else {
Aart Bikdb14fcf2017-04-25 15:53:58 -07001421 bool is_string_char_at = org->AsArrayGet()->IsStringCharAt();
1422 vector = new (global_allocator_) HArrayGet(
1423 org->InputAt(0), opa, type, kNoDexPc, is_string_char_at);
Aart Bikf8f5a162017-02-06 15:35:29 -08001424 }
1425 }
1426 vector_map_->Put(org, vector);
1427}
1428
Aart Bik0148de42017-09-05 09:25:01 -07001429void HLoopOptimization::GenerateVecReductionPhi(HPhi* phi) {
1430 DCHECK(reductions_->find(phi) != reductions_->end());
1431 DCHECK(reductions_->Get(phi->InputAt(1)) == phi);
1432 HInstruction* vector = nullptr;
1433 if (vector_mode_ == kSequential) {
1434 HPhi* new_phi = new (global_allocator_) HPhi(
1435 global_allocator_, kNoRegNumber, 0, phi->GetType());
1436 vector_header_->AddPhi(new_phi);
1437 vector = new_phi;
1438 } else {
1439 // Link vector reduction back to prior unrolled update, or a first phi.
1440 auto it = vector_permanent_map_->find(phi);
1441 if (it != vector_permanent_map_->end()) {
1442 vector = it->second;
1443 } else {
1444 HPhi* new_phi = new (global_allocator_) HPhi(
1445 global_allocator_, kNoRegNumber, 0, HVecOperation::kSIMDType);
1446 vector_header_->AddPhi(new_phi);
1447 vector = new_phi;
1448 }
1449 }
1450 vector_map_->Put(phi, vector);
1451}
1452
1453void HLoopOptimization::GenerateVecReductionPhiInputs(HPhi* phi, HInstruction* reduction) {
1454 HInstruction* new_phi = vector_map_->Get(phi);
1455 HInstruction* new_init = reductions_->Get(phi);
1456 HInstruction* new_red = vector_map_->Get(reduction);
1457 // Link unrolled vector loop back to new phi.
1458 for (; !new_phi->IsPhi(); new_phi = vector_permanent_map_->Get(new_phi)) {
1459 DCHECK(new_phi->IsVecOperation());
1460 }
1461 // Prepare the new initialization.
1462 if (vector_mode_ == kVector) {
1463 // Generate a [initial, 0, .., 0] vector.
1464 new_init = Insert(
1465 vector_preheader_,
1466 new (global_allocator_) HVecSetScalars(
1467 global_allocator_, &new_init, phi->GetType(), vector_length_, 1));
1468 } else {
1469 new_init = ReduceAndExtractIfNeeded(new_init);
1470 }
1471 // Set the phi inputs.
1472 DCHECK(new_phi->IsPhi());
1473 new_phi->AsPhi()->AddInput(new_init);
1474 new_phi->AsPhi()->AddInput(new_red);
1475 // New feed value for next phi (safe mutation in iteration).
1476 reductions_->find(phi)->second = new_phi;
1477}
1478
1479HInstruction* HLoopOptimization::ReduceAndExtractIfNeeded(HInstruction* instruction) {
1480 if (instruction->IsPhi()) {
1481 HInstruction* input = instruction->InputAt(1);
1482 if (input->IsVecOperation()) {
1483 Primitive::Type type = input->AsVecOperation()->GetPackedType();
1484 HBasicBlock* exit = instruction->GetBlock()->GetSuccessors()[0];
1485 // Generate a vector reduction and scalar extract
1486 // x = REDUCE( [x_1, .., x_n] )
1487 // y = x_1
1488 // along the exit of the defining loop.
1489 HVecReduce::ReductionKind kind = GetReductionKind(input);
1490 HInstruction* reduce = new (global_allocator_) HVecReduce(
1491 global_allocator_, instruction, type, vector_length_, kind);
1492 exit->InsertInstructionBefore(reduce, exit->GetFirstInstruction());
1493 instruction = new (global_allocator_) HVecExtractScalar(
1494 global_allocator_, reduce, type, vector_length_, 0);
1495 exit->InsertInstructionAfter(instruction, reduce);
1496 }
1497 }
1498 return instruction;
1499}
1500
Aart Bikf8f5a162017-02-06 15:35:29 -08001501#define GENERATE_VEC(x, y) \
1502 if (vector_mode_ == kVector) { \
1503 vector = (x); \
1504 } else { \
1505 DCHECK(vector_mode_ == kSequential); \
1506 vector = (y); \
1507 } \
1508 break;
1509
1510void HLoopOptimization::GenerateVecOp(HInstruction* org,
1511 HInstruction* opa,
1512 HInstruction* opb,
Aart Bik304c8a52017-05-23 11:01:13 -07001513 Primitive::Type type,
1514 bool is_unsigned) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001515 if (vector_mode_ == kSequential) {
Aart Bik304c8a52017-05-23 11:01:13 -07001516 // Non-converting scalar code follows implicit integral promotion.
1517 if (!org->IsTypeConversion() && (type == Primitive::kPrimBoolean ||
1518 type == Primitive::kPrimByte ||
1519 type == Primitive::kPrimChar ||
1520 type == Primitive::kPrimShort)) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001521 type = Primitive::kPrimInt;
1522 }
1523 }
1524 HInstruction* vector = nullptr;
1525 switch (org->GetKind()) {
1526 case HInstruction::kNeg:
1527 DCHECK(opb == nullptr);
1528 GENERATE_VEC(
1529 new (global_allocator_) HVecNeg(global_allocator_, opa, type, vector_length_),
1530 new (global_allocator_) HNeg(type, opa));
1531 case HInstruction::kNot:
1532 DCHECK(opb == nullptr);
1533 GENERATE_VEC(
1534 new (global_allocator_) HVecNot(global_allocator_, opa, type, vector_length_),
1535 new (global_allocator_) HNot(type, opa));
1536 case HInstruction::kBooleanNot:
1537 DCHECK(opb == nullptr);
1538 GENERATE_VEC(
1539 new (global_allocator_) HVecNot(global_allocator_, opa, type, vector_length_),
1540 new (global_allocator_) HBooleanNot(opa));
1541 case HInstruction::kTypeConversion:
1542 DCHECK(opb == nullptr);
1543 GENERATE_VEC(
1544 new (global_allocator_) HVecCnv(global_allocator_, opa, type, vector_length_),
1545 new (global_allocator_) HTypeConversion(type, opa, kNoDexPc));
1546 case HInstruction::kAdd:
1547 GENERATE_VEC(
1548 new (global_allocator_) HVecAdd(global_allocator_, opa, opb, type, vector_length_),
1549 new (global_allocator_) HAdd(type, opa, opb));
1550 case HInstruction::kSub:
1551 GENERATE_VEC(
1552 new (global_allocator_) HVecSub(global_allocator_, opa, opb, type, vector_length_),
1553 new (global_allocator_) HSub(type, opa, opb));
1554 case HInstruction::kMul:
1555 GENERATE_VEC(
1556 new (global_allocator_) HVecMul(global_allocator_, opa, opb, type, vector_length_),
1557 new (global_allocator_) HMul(type, opa, opb));
1558 case HInstruction::kDiv:
1559 GENERATE_VEC(
1560 new (global_allocator_) HVecDiv(global_allocator_, opa, opb, type, vector_length_),
1561 new (global_allocator_) HDiv(type, opa, opb, kNoDexPc));
1562 case HInstruction::kAnd:
1563 GENERATE_VEC(
1564 new (global_allocator_) HVecAnd(global_allocator_, opa, opb, type, vector_length_),
1565 new (global_allocator_) HAnd(type, opa, opb));
1566 case HInstruction::kOr:
1567 GENERATE_VEC(
1568 new (global_allocator_) HVecOr(global_allocator_, opa, opb, type, vector_length_),
1569 new (global_allocator_) HOr(type, opa, opb));
1570 case HInstruction::kXor:
1571 GENERATE_VEC(
1572 new (global_allocator_) HVecXor(global_allocator_, opa, opb, type, vector_length_),
1573 new (global_allocator_) HXor(type, opa, opb));
1574 case HInstruction::kShl:
1575 GENERATE_VEC(
1576 new (global_allocator_) HVecShl(global_allocator_, opa, opb, type, vector_length_),
1577 new (global_allocator_) HShl(type, opa, opb));
1578 case HInstruction::kShr:
1579 GENERATE_VEC(
1580 new (global_allocator_) HVecShr(global_allocator_, opa, opb, type, vector_length_),
1581 new (global_allocator_) HShr(type, opa, opb));
1582 case HInstruction::kUShr:
1583 GENERATE_VEC(
1584 new (global_allocator_) HVecUShr(global_allocator_, opa, opb, type, vector_length_),
1585 new (global_allocator_) HUShr(type, opa, opb));
1586 case HInstruction::kInvokeStaticOrDirect: {
Aart Bik6daebeb2017-04-03 14:35:41 -07001587 HInvokeStaticOrDirect* invoke = org->AsInvokeStaticOrDirect();
1588 if (vector_mode_ == kVector) {
1589 switch (invoke->GetIntrinsic()) {
1590 case Intrinsics::kMathAbsInt:
1591 case Intrinsics::kMathAbsLong:
1592 case Intrinsics::kMathAbsFloat:
1593 case Intrinsics::kMathAbsDouble:
1594 DCHECK(opb == nullptr);
1595 vector = new (global_allocator_) HVecAbs(global_allocator_, opa, type, vector_length_);
1596 break;
Aart Bikc8e93c72017-05-10 10:49:22 -07001597 case Intrinsics::kMathMinIntInt:
1598 case Intrinsics::kMathMinLongLong:
1599 case Intrinsics::kMathMinFloatFloat:
1600 case Intrinsics::kMathMinDoubleDouble: {
Aart Bikc8e93c72017-05-10 10:49:22 -07001601 vector = new (global_allocator_)
1602 HVecMin(global_allocator_, opa, opb, type, vector_length_, is_unsigned);
1603 break;
1604 }
1605 case Intrinsics::kMathMaxIntInt:
1606 case Intrinsics::kMathMaxLongLong:
1607 case Intrinsics::kMathMaxFloatFloat:
1608 case Intrinsics::kMathMaxDoubleDouble: {
Aart Bikc8e93c72017-05-10 10:49:22 -07001609 vector = new (global_allocator_)
1610 HVecMax(global_allocator_, opa, opb, type, vector_length_, is_unsigned);
1611 break;
1612 }
Aart Bik6daebeb2017-04-03 14:35:41 -07001613 default:
1614 LOG(FATAL) << "Unsupported SIMD intrinsic";
1615 UNREACHABLE();
1616 } // switch invoke
1617 } else {
Aart Bik24b905f2017-04-06 09:59:06 -07001618 // In scalar code, simply clone the method invoke, and replace its operands with the
1619 // corresponding new scalar instructions in the loop. The instruction will get an
1620 // environment while being inserted from the instruction map in original program order.
Aart Bik6daebeb2017-04-03 14:35:41 -07001621 DCHECK(vector_mode_ == kSequential);
Aart Bik6e92fb32017-06-05 14:05:09 -07001622 size_t num_args = invoke->GetNumberOfArguments();
Aart Bik6daebeb2017-04-03 14:35:41 -07001623 HInvokeStaticOrDirect* new_invoke = new (global_allocator_) HInvokeStaticOrDirect(
1624 global_allocator_,
Aart Bik6e92fb32017-06-05 14:05:09 -07001625 num_args,
Aart Bik6daebeb2017-04-03 14:35:41 -07001626 invoke->GetType(),
1627 invoke->GetDexPc(),
1628 invoke->GetDexMethodIndex(),
1629 invoke->GetResolvedMethod(),
1630 invoke->GetDispatchInfo(),
1631 invoke->GetInvokeType(),
1632 invoke->GetTargetMethod(),
1633 invoke->GetClinitCheckRequirement());
1634 HInputsRef inputs = invoke->GetInputs();
Aart Bik6e92fb32017-06-05 14:05:09 -07001635 size_t num_inputs = inputs.size();
1636 DCHECK_LE(num_args, num_inputs);
1637 DCHECK_EQ(num_inputs, new_invoke->GetInputs().size()); // both invokes agree
1638 for (size_t index = 0; index < num_inputs; ++index) {
1639 HInstruction* new_input = index < num_args
1640 ? vector_map_->Get(inputs[index])
1641 : inputs[index]; // beyond arguments: just pass through
1642 new_invoke->SetArgumentAt(index, new_input);
Aart Bik6daebeb2017-04-03 14:35:41 -07001643 }
Aart Bik98990262017-04-10 13:15:57 -07001644 new_invoke->SetIntrinsic(invoke->GetIntrinsic(),
1645 kNeedsEnvironmentOrCache,
1646 kNoSideEffects,
1647 kNoThrow);
Aart Bik6daebeb2017-04-03 14:35:41 -07001648 vector = new_invoke;
1649 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001650 break;
1651 }
1652 default:
1653 break;
1654 } // switch
1655 CHECK(vector != nullptr) << "Unsupported SIMD operator";
1656 vector_map_->Put(org, vector);
1657}
1658
1659#undef GENERATE_VEC
1660
1661//
Aart Bikf3e61ee2017-04-12 17:09:20 -07001662// Vectorization idioms.
1663//
1664
1665// Method recognizes the following idioms:
1666// rounding halving add (a + b + 1) >> 1 for unsigned/signed operands a, b
1667// regular halving add (a + b) >> 1 for unsigned/signed operands a, b
1668// Provided that the operands are promoted to a wider form to do the arithmetic and
1669// then cast back to narrower form, the idioms can be mapped into efficient SIMD
1670// implementation that operates directly in narrower form (plus one extra bit).
1671// TODO: current version recognizes implicit byte/short/char widening only;
1672// explicit widening from int to long could be added later.
1673bool HLoopOptimization::VectorizeHalvingAddIdiom(LoopNode* node,
1674 HInstruction* instruction,
1675 bool generate_code,
1676 Primitive::Type type,
1677 uint64_t restrictions) {
1678 // Test for top level arithmetic shift right x >> 1 or logical shift right x >>> 1
Aart Bik304c8a52017-05-23 11:01:13 -07001679 // (note whether the sign bit in wider precision is shifted in has no effect
Aart Bikf3e61ee2017-04-12 17:09:20 -07001680 // on the narrow precision computed by the idiom).
Aart Bikf3e61ee2017-04-12 17:09:20 -07001681 if ((instruction->IsShr() ||
1682 instruction->IsUShr()) &&
Aart Bik0148de42017-09-05 09:25:01 -07001683 IsInt64Value(instruction->InputAt(1), 1)) {
Aart Bik5f805002017-05-16 16:42:41 -07001684 // Test for (a + b + c) >> 1 for optional constant c.
1685 HInstruction* a = nullptr;
1686 HInstruction* b = nullptr;
1687 int64_t c = 0;
1688 if (IsAddConst(instruction->InputAt(0), /*out*/ &a, /*out*/ &b, /*out*/ &c)) {
Aart Bik304c8a52017-05-23 11:01:13 -07001689 DCHECK(a != nullptr && b != nullptr);
Aart Bik5f805002017-05-16 16:42:41 -07001690 // Accept c == 1 (rounded) or c == 0 (not rounded).
1691 bool is_rounded = false;
1692 if (c == 1) {
1693 is_rounded = true;
1694 } else if (c != 0) {
1695 return false;
1696 }
1697 // Accept consistent zero or sign extension on operands a and b.
Aart Bikf3e61ee2017-04-12 17:09:20 -07001698 HInstruction* r = nullptr;
1699 HInstruction* s = nullptr;
1700 bool is_unsigned = false;
Aart Bik304c8a52017-05-23 11:01:13 -07001701 if (!IsNarrowerOperands(a, b, type, &r, &s, &is_unsigned)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -07001702 return false;
1703 }
1704 // Deal with vector restrictions.
1705 if ((!is_unsigned && HasVectorRestrictions(restrictions, kNoSignedHAdd)) ||
1706 (!is_rounded && HasVectorRestrictions(restrictions, kNoUnroundedHAdd))) {
1707 return false;
1708 }
1709 // Accept recognized halving add for vectorizable operands. Vectorized code uses the
1710 // shorthand idiomatic operation. Sequential code uses the original scalar expressions.
1711 DCHECK(r != nullptr && s != nullptr);
Aart Bik304c8a52017-05-23 11:01:13 -07001712 if (generate_code && vector_mode_ != kVector) { // de-idiom
1713 r = instruction->InputAt(0);
1714 s = instruction->InputAt(1);
1715 }
Aart Bikf3e61ee2017-04-12 17:09:20 -07001716 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
1717 VectorizeUse(node, s, generate_code, type, restrictions)) {
1718 if (generate_code) {
1719 if (vector_mode_ == kVector) {
1720 vector_map_->Put(instruction, new (global_allocator_) HVecHalvingAdd(
1721 global_allocator_,
1722 vector_map_->Get(r),
1723 vector_map_->Get(s),
1724 type,
1725 vector_length_,
1726 is_unsigned,
1727 is_rounded));
Aart Bik21b85922017-09-06 13:29:16 -07001728 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorizedIdiom);
Aart Bikf3e61ee2017-04-12 17:09:20 -07001729 } else {
Aart Bik304c8a52017-05-23 11:01:13 -07001730 GenerateVecOp(instruction, vector_map_->Get(r), vector_map_->Get(s), type);
Aart Bikf3e61ee2017-04-12 17:09:20 -07001731 }
1732 }
1733 return true;
1734 }
1735 }
1736 }
1737 return false;
1738}
1739
1740//
Aart Bik14a68b42017-06-08 14:06:58 -07001741// Vectorization heuristics.
1742//
1743
1744bool HLoopOptimization::IsVectorizationProfitable(int64_t trip_count) {
1745 // Current heuristic: non-empty body with sufficient number
1746 // of iterations (if known).
1747 // TODO: refine by looking at e.g. operation count, alignment, etc.
1748 if (vector_length_ == 0) {
1749 return false; // nothing found
1750 } else if (0 < trip_count && trip_count < vector_length_) {
1751 return false; // insufficient iterations
1752 }
1753 return true;
1754}
1755
Aart Bikb29f6842017-07-28 15:58:41 -07001756void HLoopOptimization::SetPeelingCandidate(const ArrayReference* candidate,
1757 int64_t trip_count ATTRIBUTE_UNUSED) {
Aart Bik14a68b42017-06-08 14:06:58 -07001758 // Current heuristic: none.
1759 // TODO: implement
Aart Bikb29f6842017-07-28 15:58:41 -07001760 vector_peeling_candidate_ = candidate;
Aart Bik14a68b42017-06-08 14:06:58 -07001761}
1762
1763uint32_t HLoopOptimization::GetUnrollingFactor(HBasicBlock* block, int64_t trip_count) {
1764 // Current heuristic: unroll by 2 on ARM64/X86 for large known trip
1765 // counts and small loop bodies.
1766 // TODO: refine with operation count, remaining iterations, etc.
1767 // Artem had some really cool ideas for this already.
1768 switch (compiler_driver_->GetInstructionSet()) {
1769 case kArm64:
1770 case kX86:
1771 case kX86_64: {
1772 size_t num_instructions = block->GetInstructions().CountSize();
1773 if (num_instructions <= 10 && trip_count >= 4 * vector_length_) {
1774 return 2;
1775 }
1776 return 1;
1777 }
1778 default:
1779 return 1;
1780 }
1781}
1782
1783//
Aart Bikf8f5a162017-02-06 15:35:29 -08001784// Helpers.
1785//
1786
1787bool HLoopOptimization::TrySetPhiInduction(HPhi* phi, bool restrict_uses) {
Aart Bikb29f6842017-07-28 15:58:41 -07001788 // Start with empty phi induction.
1789 iset_->clear();
1790
Nicolas Geoffrayf57c1ae2017-06-28 17:40:18 +01001791 // Special case Phis that have equivalent in a debuggable setup. Our graph checker isn't
1792 // smart enough to follow strongly connected components (and it's probably not worth
1793 // it to make it so). See b/33775412.
1794 if (graph_->IsDebuggable() && phi->HasEquivalentPhi()) {
1795 return false;
1796 }
Aart Bikb29f6842017-07-28 15:58:41 -07001797
1798 // Lookup phi induction cycle.
Aart Bikcc42be02016-10-20 16:14:16 -07001799 ArenaSet<HInstruction*>* set = induction_range_.LookupCycle(phi);
1800 if (set != nullptr) {
1801 for (HInstruction* i : *set) {
Aart Bike3dedc52016-11-02 17:50:27 -07001802 // Check that, other than instructions that are no longer in the graph (removed earlier)
Aart Bikf8f5a162017-02-06 15:35:29 -08001803 // each instruction is removable and, when restrict uses are requested, other than for phi,
1804 // all uses are contained within the cycle.
Aart Bike3dedc52016-11-02 17:50:27 -07001805 if (!i->IsInBlock()) {
1806 continue;
1807 } else if (!i->IsRemovable()) {
1808 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001809 } else if (i != phi && restrict_uses) {
Aart Bikb29f6842017-07-28 15:58:41 -07001810 // Deal with regular uses.
Aart Bikcc42be02016-10-20 16:14:16 -07001811 for (const HUseListNode<HInstruction*>& use : i->GetUses()) {
1812 if (set->find(use.GetUser()) == set->end()) {
1813 return false;
1814 }
1815 }
1816 }
Aart Bike3dedc52016-11-02 17:50:27 -07001817 iset_->insert(i); // copy
Aart Bikcc42be02016-10-20 16:14:16 -07001818 }
Aart Bikcc42be02016-10-20 16:14:16 -07001819 return true;
1820 }
1821 return false;
1822}
1823
Aart Bikb29f6842017-07-28 15:58:41 -07001824bool HLoopOptimization::TrySetPhiReduction(HPhi* phi) {
Aart Bikcc42be02016-10-20 16:14:16 -07001825 DCHECK(iset_->empty());
Aart Bikb29f6842017-07-28 15:58:41 -07001826 // Only unclassified phi cycles are candidates for reductions.
1827 if (induction_range_.IsClassified(phi)) {
1828 return false;
1829 }
1830 // Accept operations like x = x + .., provided that the phi and the reduction are
1831 // used exactly once inside the loop, and by each other.
1832 HInputsRef inputs = phi->GetInputs();
1833 if (inputs.size() == 2) {
1834 HInstruction* reduction = inputs[1];
1835 if (HasReductionFormat(reduction, phi)) {
1836 HLoopInformation* loop_info = phi->GetBlock()->GetLoopInformation();
1837 int32_t use_count = 0;
1838 bool single_use_inside_loop =
1839 // Reduction update only used by phi.
1840 reduction->GetUses().HasExactlyOneElement() &&
1841 !reduction->HasEnvironmentUses() &&
1842 // Reduction update is only use of phi inside the loop.
1843 IsOnlyUsedAfterLoop(loop_info, phi, /*collect_loop_uses*/ true, &use_count) &&
1844 iset_->size() == 1;
1845 iset_->clear(); // leave the way you found it
1846 if (single_use_inside_loop) {
1847 // Link reduction back, and start recording feed value.
1848 reductions_->Put(reduction, phi);
1849 reductions_->Put(phi, phi->InputAt(0));
1850 return true;
1851 }
1852 }
1853 }
1854 return false;
1855}
1856
1857bool HLoopOptimization::TrySetSimpleLoopHeader(HBasicBlock* block, /*out*/ HPhi** main_phi) {
1858 // Start with empty phi induction and reductions.
1859 iset_->clear();
1860 reductions_->clear();
1861
1862 // Scan the phis to find the following (the induction structure has already
1863 // been optimized, so we don't need to worry about trivial cases):
1864 // (1) optional reductions in loop,
1865 // (2) the main induction, used in loop control.
1866 HPhi* phi = nullptr;
1867 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
1868 if (TrySetPhiReduction(it.Current()->AsPhi())) {
1869 continue;
1870 } else if (phi == nullptr) {
1871 // Found the first candidate for main induction.
1872 phi = it.Current()->AsPhi();
1873 } else {
1874 return false;
1875 }
1876 }
1877
1878 // Then test for a typical loopheader:
1879 // s: SuspendCheck
1880 // c: Condition(phi, bound)
1881 // i: If(c)
1882 if (phi != nullptr && TrySetPhiInduction(phi, /*restrict_uses*/ false)) {
Aart Bikcc42be02016-10-20 16:14:16 -07001883 HInstruction* s = block->GetFirstInstruction();
1884 if (s != nullptr && s->IsSuspendCheck()) {
1885 HInstruction* c = s->GetNext();
Aart Bikd86c0852017-04-14 12:00:15 -07001886 if (c != nullptr &&
1887 c->IsCondition() &&
1888 c->GetUses().HasExactlyOneElement() && // only used for termination
1889 !c->HasEnvironmentUses()) { // unlikely, but not impossible
Aart Bikcc42be02016-10-20 16:14:16 -07001890 HInstruction* i = c->GetNext();
1891 if (i != nullptr && i->IsIf() && i->InputAt(0) == c) {
1892 iset_->insert(c);
1893 iset_->insert(s);
Aart Bikb29f6842017-07-28 15:58:41 -07001894 *main_phi = phi;
Aart Bikcc42be02016-10-20 16:14:16 -07001895 return true;
1896 }
1897 }
1898 }
1899 }
1900 return false;
1901}
1902
1903bool HLoopOptimization::IsEmptyBody(HBasicBlock* block) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001904 if (!block->GetPhis().IsEmpty()) {
1905 return false;
1906 }
1907 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
1908 HInstruction* instruction = it.Current();
1909 if (!instruction->IsGoto() && iset_->find(instruction) == iset_->end()) {
1910 return false;
Aart Bikcc42be02016-10-20 16:14:16 -07001911 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001912 }
1913 return true;
1914}
1915
1916bool HLoopOptimization::IsUsedOutsideLoop(HLoopInformation* loop_info,
1917 HInstruction* instruction) {
Aart Bikb29f6842017-07-28 15:58:41 -07001918 // Deal with regular uses.
Aart Bikf8f5a162017-02-06 15:35:29 -08001919 for (const HUseListNode<HInstruction*>& use : instruction->GetUses()) {
1920 if (use.GetUser()->GetBlock()->GetLoopInformation() != loop_info) {
1921 return true;
1922 }
Aart Bikcc42be02016-10-20 16:14:16 -07001923 }
1924 return false;
1925}
1926
Aart Bik482095d2016-10-10 15:39:10 -07001927bool HLoopOptimization::IsOnlyUsedAfterLoop(HLoopInformation* loop_info,
Aart Bik8c4a8542016-10-06 11:36:57 -07001928 HInstruction* instruction,
Aart Bik6b69e0a2017-01-11 10:20:43 -08001929 bool collect_loop_uses,
Aart Bik8c4a8542016-10-06 11:36:57 -07001930 /*out*/ int32_t* use_count) {
Aart Bikb29f6842017-07-28 15:58:41 -07001931 // Deal with regular uses.
Aart Bik8c4a8542016-10-06 11:36:57 -07001932 for (const HUseListNode<HInstruction*>& use : instruction->GetUses()) {
1933 HInstruction* user = use.GetUser();
1934 if (iset_->find(user) == iset_->end()) { // not excluded?
1935 HLoopInformation* other_loop_info = user->GetBlock()->GetLoopInformation();
Aart Bik482095d2016-10-10 15:39:10 -07001936 if (other_loop_info != nullptr && other_loop_info->IsIn(*loop_info)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -08001937 // If collect_loop_uses is set, simply keep adding those uses to the set.
1938 // Otherwise, reject uses inside the loop that were not already in the set.
1939 if (collect_loop_uses) {
1940 iset_->insert(user);
1941 continue;
1942 }
Aart Bik8c4a8542016-10-06 11:36:57 -07001943 return false;
1944 }
1945 ++*use_count;
1946 }
1947 }
1948 return true;
1949}
1950
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01001951bool HLoopOptimization::TryReplaceWithLastValue(HLoopInformation* loop_info,
1952 HInstruction* instruction,
1953 HBasicBlock* block) {
1954 // Try to replace outside uses with the last value.
Aart Bik807868e2016-11-03 17:51:43 -07001955 if (induction_range_.CanGenerateLastValue(instruction)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -08001956 HInstruction* replacement = induction_range_.GenerateLastValue(instruction, graph_, block);
Aart Bikb29f6842017-07-28 15:58:41 -07001957 // Deal with regular uses.
Aart Bik6b69e0a2017-01-11 10:20:43 -08001958 const HUseList<HInstruction*>& uses = instruction->GetUses();
1959 for (auto it = uses.begin(), end = uses.end(); it != end;) {
1960 HInstruction* user = it->GetUser();
1961 size_t index = it->GetIndex();
1962 ++it; // increment before replacing
1963 if (iset_->find(user) == iset_->end()) { // not excluded?
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01001964 if (kIsDebugBuild) {
1965 // We have checked earlier in 'IsOnlyUsedAfterLoop' that the use is after the loop.
1966 HLoopInformation* other_loop_info = user->GetBlock()->GetLoopInformation();
1967 CHECK(other_loop_info == nullptr || !other_loop_info->IsIn(*loop_info));
1968 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08001969 user->ReplaceInput(replacement, index);
1970 induction_range_.Replace(user, instruction, replacement); // update induction
1971 }
1972 }
Aart Bikb29f6842017-07-28 15:58:41 -07001973 // Deal with environment uses.
Aart Bik6b69e0a2017-01-11 10:20:43 -08001974 const HUseList<HEnvironment*>& env_uses = instruction->GetEnvUses();
1975 for (auto it = env_uses.begin(), end = env_uses.end(); it != end;) {
1976 HEnvironment* user = it->GetUser();
1977 size_t index = it->GetIndex();
1978 ++it; // increment before replacing
1979 if (iset_->find(user->GetHolder()) == iset_->end()) { // not excluded?
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01001980 // Only update environment uses after the loop.
Aart Bik14a68b42017-06-08 14:06:58 -07001981 HLoopInformation* other_loop_info = user->GetHolder()->GetBlock()->GetLoopInformation();
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01001982 if (other_loop_info == nullptr || !other_loop_info->IsIn(*loop_info)) {
1983 user->RemoveAsUserOfInput(index);
1984 user->SetRawEnvAt(index, replacement);
1985 replacement->AddEnvUseAt(user, index);
1986 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08001987 }
1988 }
Aart Bik807868e2016-11-03 17:51:43 -07001989 return true;
Aart Bik8c4a8542016-10-06 11:36:57 -07001990 }
Aart Bik807868e2016-11-03 17:51:43 -07001991 return false;
Aart Bik8c4a8542016-10-06 11:36:57 -07001992}
1993
Aart Bikf8f5a162017-02-06 15:35:29 -08001994bool HLoopOptimization::TryAssignLastValue(HLoopInformation* loop_info,
1995 HInstruction* instruction,
1996 HBasicBlock* block,
1997 bool collect_loop_uses) {
1998 // Assigning the last value is always successful if there are no uses.
1999 // Otherwise, it succeeds in a no early-exit loop by generating the
2000 // proper last value assignment.
2001 int32_t use_count = 0;
2002 return IsOnlyUsedAfterLoop(loop_info, instruction, collect_loop_uses, &use_count) &&
2003 (use_count == 0 ||
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002004 (!IsEarlyExit(loop_info) && TryReplaceWithLastValue(loop_info, instruction, block)));
Aart Bikf8f5a162017-02-06 15:35:29 -08002005}
2006
Aart Bik6b69e0a2017-01-11 10:20:43 -08002007void HLoopOptimization::RemoveDeadInstructions(const HInstructionList& list) {
2008 for (HBackwardInstructionIterator i(list); !i.Done(); i.Advance()) {
2009 HInstruction* instruction = i.Current();
2010 if (instruction->IsDeadAndRemovable()) {
2011 simplified_ = true;
2012 instruction->GetBlock()->RemoveInstructionOrPhi(instruction);
2013 }
2014 }
2015}
2016
Aart Bik14a68b42017-06-08 14:06:58 -07002017bool HLoopOptimization::CanRemoveCycle() {
2018 for (HInstruction* i : *iset_) {
2019 // We can never remove instructions that have environment
2020 // uses when we compile 'debuggable'.
2021 if (i->HasEnvironmentUses() && graph_->IsDebuggable()) {
2022 return false;
2023 }
2024 // A deoptimization should never have an environment input removed.
2025 for (const HUseListNode<HEnvironment*>& use : i->GetEnvUses()) {
2026 if (use.GetUser()->GetHolder()->IsDeoptimize()) {
2027 return false;
2028 }
2029 }
2030 }
2031 return true;
2032}
2033
Aart Bik281c6812016-08-26 11:31:48 -07002034} // namespace art