blob: a249cacc9384c78b0bc42d5811ebae139987bf33 [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 Bikb92cc332017-09-06 15:53:17 -0700334 HInductionVarAnalysis* induction_analysis,
335 OptimizingCompilerStats* stats)
336 : HOptimization(graph, kLoopOptimizationPassName, stats),
Aart Bik92685a82017-03-06 11:13:43 -0800337 compiler_driver_(compiler_driver),
Aart Bik281c6812016-08-26 11:31:48 -0700338 induction_range_(induction_analysis),
Aart Bik96202302016-10-04 17:33:56 -0700339 loop_allocator_(nullptr),
Aart Bikf8f5a162017-02-06 15:35:29 -0800340 global_allocator_(graph_->GetArena()),
Aart Bik281c6812016-08-26 11:31:48 -0700341 top_loop_(nullptr),
Aart Bik8c4a8542016-10-06 11:36:57 -0700342 last_loop_(nullptr),
Aart Bik482095d2016-10-10 15:39:10 -0700343 iset_(nullptr),
Aart Bikb29f6842017-07-28 15:58:41 -0700344 reductions_(nullptr),
Aart Bikf8f5a162017-02-06 15:35:29 -0800345 simplified_(false),
346 vector_length_(0),
347 vector_refs_(nullptr),
Aart Bik14a68b42017-06-08 14:06:58 -0700348 vector_peeling_candidate_(nullptr),
349 vector_runtime_test_a_(nullptr),
350 vector_runtime_test_b_(nullptr),
Aart Bik0148de42017-09-05 09:25:01 -0700351 vector_map_(nullptr),
352 vector_permanent_map_(nullptr) {
Aart Bik281c6812016-08-26 11:31:48 -0700353}
354
355void HLoopOptimization::Run() {
Mingyao Yang01b47b02017-02-03 12:09:57 -0800356 // Skip if there is no loop or the graph has try-catch/irreducible loops.
Aart Bik281c6812016-08-26 11:31:48 -0700357 // TODO: make this less of a sledgehammer.
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800358 if (!graph_->HasLoops() || graph_->HasTryCatch() || graph_->HasIrreducibleLoops()) {
Aart Bik281c6812016-08-26 11:31:48 -0700359 return;
360 }
361
Aart Bik96202302016-10-04 17:33:56 -0700362 // Phase-local allocator that draws from the global pool. Since the allocator
363 // itself resides on the stack, it is destructed on exiting Run(), which
364 // implies its underlying memory is released immediately.
Aart Bikf8f5a162017-02-06 15:35:29 -0800365 ArenaAllocator allocator(global_allocator_->GetArenaPool());
Aart Bik96202302016-10-04 17:33:56 -0700366 loop_allocator_ = &allocator;
Nicolas Geoffrayebe16742016-10-05 09:55:42 +0100367
Aart Bik96202302016-10-04 17:33:56 -0700368 // Perform loop optimizations.
369 LocalRun();
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800370 if (top_loop_ == nullptr) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800371 graph_->SetHasLoops(false); // no more loops
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800372 }
373
Aart Bik96202302016-10-04 17:33:56 -0700374 // Detach.
375 loop_allocator_ = nullptr;
376 last_loop_ = top_loop_ = nullptr;
377}
378
Aart Bikb29f6842017-07-28 15:58:41 -0700379//
380// Loop setup and traversal.
381//
382
Aart Bik96202302016-10-04 17:33:56 -0700383void HLoopOptimization::LocalRun() {
384 // Build the linear order using the phase-local allocator. This step enables building
385 // a loop hierarchy that properly reflects the outer-inner and previous-next relation.
386 ArenaVector<HBasicBlock*> linear_order(loop_allocator_->Adapter(kArenaAllocLinearOrder));
387 LinearizeGraph(graph_, loop_allocator_, &linear_order);
388
Aart Bik281c6812016-08-26 11:31:48 -0700389 // Build the loop hierarchy.
Aart Bik96202302016-10-04 17:33:56 -0700390 for (HBasicBlock* block : linear_order) {
Aart Bik281c6812016-08-26 11:31:48 -0700391 if (block->IsLoopHeader()) {
392 AddLoop(block->GetLoopInformation());
393 }
394 }
Aart Bik96202302016-10-04 17:33:56 -0700395
Aart Bik8c4a8542016-10-06 11:36:57 -0700396 // Traverse the loop hierarchy inner-to-outer and optimize. Traversal can use
Aart Bikf8f5a162017-02-06 15:35:29 -0800397 // temporary data structures using the phase-local allocator. All new HIR
398 // should use the global allocator.
Aart Bik8c4a8542016-10-06 11:36:57 -0700399 if (top_loop_ != nullptr) {
400 ArenaSet<HInstruction*> iset(loop_allocator_->Adapter(kArenaAllocLoopOptimization));
Aart Bikb29f6842017-07-28 15:58:41 -0700401 ArenaSafeMap<HInstruction*, HInstruction*> reds(
402 std::less<HInstruction*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
Aart Bikf8f5a162017-02-06 15:35:29 -0800403 ArenaSet<ArrayReference> refs(loop_allocator_->Adapter(kArenaAllocLoopOptimization));
404 ArenaSafeMap<HInstruction*, HInstruction*> map(
405 std::less<HInstruction*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
Aart Bik0148de42017-09-05 09:25:01 -0700406 ArenaSafeMap<HInstruction*, HInstruction*> perm(
407 std::less<HInstruction*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
Aart Bikf8f5a162017-02-06 15:35:29 -0800408 // Attach.
Aart Bik8c4a8542016-10-06 11:36:57 -0700409 iset_ = &iset;
Aart Bikb29f6842017-07-28 15:58:41 -0700410 reductions_ = &reds;
Aart Bikf8f5a162017-02-06 15:35:29 -0800411 vector_refs_ = &refs;
412 vector_map_ = &map;
Aart Bik0148de42017-09-05 09:25:01 -0700413 vector_permanent_map_ = &perm;
Aart Bikf8f5a162017-02-06 15:35:29 -0800414 // Traverse.
Aart Bik8c4a8542016-10-06 11:36:57 -0700415 TraverseLoopsInnerToOuter(top_loop_);
Aart Bikf8f5a162017-02-06 15:35:29 -0800416 // Detach.
417 iset_ = nullptr;
Aart Bikb29f6842017-07-28 15:58:41 -0700418 reductions_ = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800419 vector_refs_ = nullptr;
420 vector_map_ = nullptr;
Aart Bik0148de42017-09-05 09:25:01 -0700421 vector_permanent_map_ = nullptr;
Aart Bik8c4a8542016-10-06 11:36:57 -0700422 }
Aart Bik281c6812016-08-26 11:31:48 -0700423}
424
425void HLoopOptimization::AddLoop(HLoopInformation* loop_info) {
426 DCHECK(loop_info != nullptr);
Aart Bikf8f5a162017-02-06 15:35:29 -0800427 LoopNode* node = new (loop_allocator_) LoopNode(loop_info);
Aart Bik281c6812016-08-26 11:31:48 -0700428 if (last_loop_ == nullptr) {
429 // First loop.
430 DCHECK(top_loop_ == nullptr);
431 last_loop_ = top_loop_ = node;
432 } else if (loop_info->IsIn(*last_loop_->loop_info)) {
433 // Inner loop.
434 node->outer = last_loop_;
435 DCHECK(last_loop_->inner == nullptr);
436 last_loop_ = last_loop_->inner = node;
437 } else {
438 // Subsequent loop.
439 while (last_loop_->outer != nullptr && !loop_info->IsIn(*last_loop_->outer->loop_info)) {
440 last_loop_ = last_loop_->outer;
441 }
442 node->outer = last_loop_->outer;
443 node->previous = last_loop_;
444 DCHECK(last_loop_->next == nullptr);
445 last_loop_ = last_loop_->next = node;
446 }
447}
448
449void HLoopOptimization::RemoveLoop(LoopNode* node) {
450 DCHECK(node != nullptr);
Aart Bik8c4a8542016-10-06 11:36:57 -0700451 DCHECK(node->inner == nullptr);
452 if (node->previous != nullptr) {
453 // Within sequence.
454 node->previous->next = node->next;
455 if (node->next != nullptr) {
456 node->next->previous = node->previous;
457 }
458 } else {
459 // First of sequence.
460 if (node->outer != nullptr) {
461 node->outer->inner = node->next;
462 } else {
463 top_loop_ = node->next;
464 }
465 if (node->next != nullptr) {
466 node->next->outer = node->outer;
467 node->next->previous = nullptr;
468 }
469 }
Aart Bik281c6812016-08-26 11:31:48 -0700470}
471
Aart Bikb29f6842017-07-28 15:58:41 -0700472bool HLoopOptimization::TraverseLoopsInnerToOuter(LoopNode* node) {
473 bool changed = false;
Aart Bik281c6812016-08-26 11:31:48 -0700474 for ( ; node != nullptr; node = node->next) {
Aart Bikb29f6842017-07-28 15:58:41 -0700475 // Visit inner loops first. Recompute induction information for this
476 // loop if the induction of any inner loop has changed.
477 if (TraverseLoopsInnerToOuter(node->inner)) {
Aart Bik482095d2016-10-10 15:39:10 -0700478 induction_range_.ReVisit(node->loop_info);
479 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800480 // Repeat simplifications in the loop-body until no more changes occur.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800481 // Note that since each simplification consists of eliminating code (without
482 // introducing new code), this process is always finite.
Aart Bikdf7822e2016-12-06 10:05:30 -0800483 do {
484 simplified_ = false;
Aart Bikdf7822e2016-12-06 10:05:30 -0800485 SimplifyInduction(node);
Aart Bik6b69e0a2017-01-11 10:20:43 -0800486 SimplifyBlocks(node);
Aart Bikb29f6842017-07-28 15:58:41 -0700487 changed = simplified_ || changed;
Aart Bikdf7822e2016-12-06 10:05:30 -0800488 } while (simplified_);
Aart Bikf8f5a162017-02-06 15:35:29 -0800489 // Optimize inner loop.
Aart Bik9abf8942016-10-14 09:49:42 -0700490 if (node->inner == nullptr) {
Aart Bikb29f6842017-07-28 15:58:41 -0700491 changed = OptimizeInnerLoop(node) || changed;
Aart Bik9abf8942016-10-14 09:49:42 -0700492 }
Aart Bik281c6812016-08-26 11:31:48 -0700493 }
Aart Bikb29f6842017-07-28 15:58:41 -0700494 return changed;
Aart Bik281c6812016-08-26 11:31:48 -0700495}
496
Aart Bikf8f5a162017-02-06 15:35:29 -0800497//
498// Optimization.
499//
500
Aart Bik281c6812016-08-26 11:31:48 -0700501void HLoopOptimization::SimplifyInduction(LoopNode* node) {
502 HBasicBlock* header = node->loop_info->GetHeader();
503 HBasicBlock* preheader = node->loop_info->GetPreHeader();
Aart Bik8c4a8542016-10-06 11:36:57 -0700504 // Scan the phis in the header to find opportunities to simplify an induction
505 // cycle that is only used outside the loop. Replace these uses, if any, with
506 // the last value and remove the induction cycle.
507 // Examples: for (int i = 0; x != null; i++) { .... no i .... }
508 // for (int i = 0; i < 10; i++, k++) { .... no k .... } return k;
Aart Bik281c6812016-08-26 11:31:48 -0700509 for (HInstructionIterator it(header->GetPhis()); !it.Done(); it.Advance()) {
510 HPhi* phi = it.Current()->AsPhi();
Aart Bikf8f5a162017-02-06 15:35:29 -0800511 if (TrySetPhiInduction(phi, /*restrict_uses*/ true) &&
512 TryAssignLastValue(node->loop_info, phi, preheader, /*collect_loop_uses*/ false)) {
Aart Bik671e48a2017-08-09 13:16:56 -0700513 // Note that it's ok to have replaced uses after the loop with the last value, without
514 // being able to remove the cycle. Environment uses (which are the reason we may not be
515 // able to remove the cycle) within the loop will still hold the right value. We must
516 // have tried first, however, to replace outside uses.
517 if (CanRemoveCycle()) {
518 simplified_ = true;
519 for (HInstruction* i : *iset_) {
520 RemoveFromCycle(i);
521 }
522 DCHECK(CheckInductionSetFullyRemoved(iset_));
Aart Bik281c6812016-08-26 11:31:48 -0700523 }
Aart Bik482095d2016-10-10 15:39:10 -0700524 }
525 }
526}
527
528void HLoopOptimization::SimplifyBlocks(LoopNode* node) {
Aart Bikdf7822e2016-12-06 10:05:30 -0800529 // Iterate over all basic blocks in the loop-body.
530 for (HBlocksInLoopIterator it(*node->loop_info); !it.Done(); it.Advance()) {
531 HBasicBlock* block = it.Current();
532 // Remove dead instructions from the loop-body.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800533 RemoveDeadInstructions(block->GetPhis());
534 RemoveDeadInstructions(block->GetInstructions());
Aart Bikdf7822e2016-12-06 10:05:30 -0800535 // Remove trivial control flow blocks from the loop-body.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800536 if (block->GetPredecessors().size() == 1 &&
537 block->GetSuccessors().size() == 1 &&
538 block->GetSingleSuccessor()->GetPredecessors().size() == 1) {
Aart Bikdf7822e2016-12-06 10:05:30 -0800539 simplified_ = true;
Aart Bik6b69e0a2017-01-11 10:20:43 -0800540 block->MergeWith(block->GetSingleSuccessor());
Aart Bikdf7822e2016-12-06 10:05:30 -0800541 } else if (block->GetSuccessors().size() == 2) {
542 // Trivial if block can be bypassed to either branch.
543 HBasicBlock* succ0 = block->GetSuccessors()[0];
544 HBasicBlock* succ1 = block->GetSuccessors()[1];
545 HBasicBlock* meet0 = nullptr;
546 HBasicBlock* meet1 = nullptr;
547 if (succ0 != succ1 &&
548 IsGotoBlock(succ0, &meet0) &&
549 IsGotoBlock(succ1, &meet1) &&
550 meet0 == meet1 && // meets again
551 meet0 != block && // no self-loop
552 meet0->GetPhis().IsEmpty()) { // not used for merging
553 simplified_ = true;
554 succ0->DisconnectAndDelete();
555 if (block->Dominates(meet0)) {
556 block->RemoveDominatedBlock(meet0);
557 succ1->AddDominatedBlock(meet0);
558 meet0->SetDominator(succ1);
Aart Bike3dedc52016-11-02 17:50:27 -0700559 }
Aart Bik482095d2016-10-10 15:39:10 -0700560 }
Aart Bik281c6812016-08-26 11:31:48 -0700561 }
Aart Bikdf7822e2016-12-06 10:05:30 -0800562 }
Aart Bik281c6812016-08-26 11:31:48 -0700563}
564
Aart Bikb29f6842017-07-28 15:58:41 -0700565bool HLoopOptimization::OptimizeInnerLoop(LoopNode* node) {
Aart Bik281c6812016-08-26 11:31:48 -0700566 HBasicBlock* header = node->loop_info->GetHeader();
567 HBasicBlock* preheader = node->loop_info->GetPreHeader();
Aart Bik9abf8942016-10-14 09:49:42 -0700568 // Ensure loop header logic is finite.
Aart Bikf8f5a162017-02-06 15:35:29 -0800569 int64_t trip_count = 0;
570 if (!induction_range_.IsFinite(node->loop_info, &trip_count)) {
Aart Bikb29f6842017-07-28 15:58:41 -0700571 return false;
Aart Bik9abf8942016-10-14 09:49:42 -0700572 }
Aart Bik281c6812016-08-26 11:31:48 -0700573 // Ensure there is only a single loop-body (besides the header).
574 HBasicBlock* body = nullptr;
575 for (HBlocksInLoopIterator it(*node->loop_info); !it.Done(); it.Advance()) {
576 if (it.Current() != header) {
577 if (body != nullptr) {
Aart Bikb29f6842017-07-28 15:58:41 -0700578 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700579 }
580 body = it.Current();
581 }
582 }
Andreas Gampef45d61c2017-06-07 10:29:33 -0700583 CHECK(body != nullptr);
Aart Bik281c6812016-08-26 11:31:48 -0700584 // Ensure there is only a single exit point.
585 if (header->GetSuccessors().size() != 2) {
Aart Bikb29f6842017-07-28 15:58:41 -0700586 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700587 }
588 HBasicBlock* exit = (header->GetSuccessors()[0] == body)
589 ? header->GetSuccessors()[1]
590 : header->GetSuccessors()[0];
Aart Bik8c4a8542016-10-06 11:36:57 -0700591 // Ensure exit can only be reached by exiting loop.
Aart Bik281c6812016-08-26 11:31:48 -0700592 if (exit->GetPredecessors().size() != 1) {
Aart Bikb29f6842017-07-28 15:58:41 -0700593 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700594 }
Aart Bik6b69e0a2017-01-11 10:20:43 -0800595 // Detect either an empty loop (no side effects other than plain iteration) or
596 // a trivial loop (just iterating once). Replace subsequent index uses, if any,
597 // with the last value and remove the loop, possibly after unrolling its body.
Aart Bikb29f6842017-07-28 15:58:41 -0700598 HPhi* main_phi = nullptr;
599 if (TrySetSimpleLoopHeader(header, &main_phi)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -0800600 bool is_empty = IsEmptyBody(body);
Aart Bikb29f6842017-07-28 15:58:41 -0700601 if (reductions_->empty() && // TODO: possible with some effort
602 (is_empty || trip_count == 1) &&
603 TryAssignLastValue(node->loop_info, main_phi, preheader, /*collect_loop_uses*/ true)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -0800604 if (!is_empty) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800605 // Unroll the loop-body, which sees initial value of the index.
Aart Bikb29f6842017-07-28 15:58:41 -0700606 main_phi->ReplaceWith(main_phi->InputAt(0));
Aart Bik6b69e0a2017-01-11 10:20:43 -0800607 preheader->MergeInstructionsWith(body);
608 }
609 body->DisconnectAndDelete();
610 exit->RemovePredecessor(header);
611 header->RemoveSuccessor(exit);
612 header->RemoveDominatedBlock(exit);
613 header->DisconnectAndDelete();
614 preheader->AddSuccessor(exit);
Aart Bikf8f5a162017-02-06 15:35:29 -0800615 preheader->AddInstruction(new (global_allocator_) HGoto());
Aart Bik6b69e0a2017-01-11 10:20:43 -0800616 preheader->AddDominatedBlock(exit);
617 exit->SetDominator(preheader);
618 RemoveLoop(node); // update hierarchy
Aart Bikb29f6842017-07-28 15:58:41 -0700619 return true;
Aart Bikf8f5a162017-02-06 15:35:29 -0800620 }
621 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800622 // Vectorize loop, if possible and valid.
Aart Bikb29f6842017-07-28 15:58:41 -0700623 if (kEnableVectorization &&
624 TrySetSimpleLoopHeader(header, &main_phi) &&
Aart Bikb29f6842017-07-28 15:58:41 -0700625 ShouldVectorize(node, body, trip_count) &&
626 TryAssignLastValue(node->loop_info, main_phi, preheader, /*collect_loop_uses*/ true)) {
627 Vectorize(node, body, exit, trip_count);
628 graph_->SetHasSIMD(true); // flag SIMD usage
Aart Bik21b85922017-09-06 13:29:16 -0700629 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorized);
Aart Bikb29f6842017-07-28 15:58:41 -0700630 return true;
Aart Bikf8f5a162017-02-06 15:35:29 -0800631 }
Aart Bikb29f6842017-07-28 15:58:41 -0700632 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -0800633}
634
635//
636// Loop vectorization. The implementation is based on the book by Aart J.C. Bik:
637// "The Software Vectorization Handbook. Applying Multimedia Extensions for Maximum Performance."
638// Intel Press, June, 2004 (http://www.aartbik.com/).
639//
640
Aart Bik14a68b42017-06-08 14:06:58 -0700641bool HLoopOptimization::ShouldVectorize(LoopNode* node, HBasicBlock* block, int64_t trip_count) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800642 // Reset vector bookkeeping.
643 vector_length_ = 0;
644 vector_refs_->clear();
Aart Bik14a68b42017-06-08 14:06:58 -0700645 vector_peeling_candidate_ = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800646 vector_runtime_test_a_ =
647 vector_runtime_test_b_= nullptr;
648
649 // Phis in the loop-body prevent vectorization.
650 if (!block->GetPhis().IsEmpty()) {
651 return false;
652 }
653
654 // Scan the loop-body, starting a right-hand-side tree traversal at each left-hand-side
655 // occurrence, which allows passing down attributes down the use tree.
656 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
657 if (!VectorizeDef(node, it.Current(), /*generate_code*/ false)) {
658 return false; // failure to vectorize a left-hand-side
659 }
660 }
661
Aart Bik14a68b42017-06-08 14:06:58 -0700662 // Does vectorization seem profitable?
663 if (!IsVectorizationProfitable(trip_count)) {
664 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -0800665 }
666
667 // Data dependence analysis. Find each pair of references with same type, where
668 // at least one is a write. Each such pair denotes a possible data dependence.
669 // This analysis exploits the property that differently typed arrays cannot be
670 // aliased, as well as the property that references either point to the same
671 // array or to two completely disjoint arrays, i.e., no partial aliasing.
672 // Other than a few simply heuristics, no detailed subscript analysis is done.
Aart Bikb29f6842017-07-28 15:58:41 -0700673 // The scan over references also finds a suitable dynamic loop peeling candidate.
674 const ArrayReference* candidate = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800675 for (auto i = vector_refs_->begin(); i != vector_refs_->end(); ++i) {
676 for (auto j = i; ++j != vector_refs_->end(); ) {
677 if (i->type == j->type && (i->lhs || j->lhs)) {
678 // Found same-typed a[i+x] vs. b[i+y], where at least one is a write.
679 HInstruction* a = i->base;
680 HInstruction* b = j->base;
681 HInstruction* x = i->offset;
682 HInstruction* y = j->offset;
683 if (a == b) {
684 // Found a[i+x] vs. a[i+y]. Accept if x == y (loop-independent data dependence).
685 // Conservatively assume a loop-carried data dependence otherwise, and reject.
686 if (x != y) {
687 return false;
688 }
689 } else {
690 // Found a[i+x] vs. b[i+y]. Accept if x == y (at worst loop-independent data dependence).
691 // Conservatively assume a potential loop-carried data dependence otherwise, avoided by
692 // generating an explicit a != b disambiguation runtime test on the two references.
693 if (x != y) {
Aart Bik37dc4df2017-06-28 14:08:00 -0700694 // To avoid excessive overhead, we only accept one a != b test.
695 if (vector_runtime_test_a_ == nullptr) {
696 // First test found.
697 vector_runtime_test_a_ = a;
698 vector_runtime_test_b_ = b;
699 } else if ((vector_runtime_test_a_ != a || vector_runtime_test_b_ != b) &&
700 (vector_runtime_test_a_ != b || vector_runtime_test_b_ != a)) {
701 return false; // second test would be needed
Aart Bikf8f5a162017-02-06 15:35:29 -0800702 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800703 }
704 }
705 }
706 }
707 }
708
Aart Bik14a68b42017-06-08 14:06:58 -0700709 // Consider dynamic loop peeling for alignment.
Aart Bikb29f6842017-07-28 15:58:41 -0700710 SetPeelingCandidate(candidate, trip_count);
Aart Bik14a68b42017-06-08 14:06:58 -0700711
Aart Bikf8f5a162017-02-06 15:35:29 -0800712 // Success!
713 return true;
714}
715
716void HLoopOptimization::Vectorize(LoopNode* node,
717 HBasicBlock* block,
718 HBasicBlock* exit,
719 int64_t trip_count) {
720 Primitive::Type induc_type = Primitive::kPrimInt;
721 HBasicBlock* header = node->loop_info->GetHeader();
722 HBasicBlock* preheader = node->loop_info->GetPreHeader();
723
Aart Bik14a68b42017-06-08 14:06:58 -0700724 // Pick a loop unrolling factor for the vector loop.
725 uint32_t unroll = GetUnrollingFactor(block, trip_count);
726 uint32_t chunk = vector_length_ * unroll;
727
728 // A cleanup loop is needed, at least, for any unknown trip count or
729 // for a known trip count with remainder iterations after vectorization.
730 bool needs_cleanup = trip_count == 0 || (trip_count % chunk) != 0;
Aart Bikf8f5a162017-02-06 15:35:29 -0800731
732 // Adjust vector bookkeeping.
Aart Bikb29f6842017-07-28 15:58:41 -0700733 HPhi* main_phi = nullptr;
734 bool is_simple_loop_header = TrySetSimpleLoopHeader(header, &main_phi); // refills sets
Aart Bikf8f5a162017-02-06 15:35:29 -0800735 DCHECK(is_simple_loop_header);
Aart Bik14a68b42017-06-08 14:06:58 -0700736 vector_header_ = header;
737 vector_body_ = block;
Aart Bikf8f5a162017-02-06 15:35:29 -0800738
Aart Bikb29f6842017-07-28 15:58:41 -0700739 // Generate dynamic loop peeling trip count, if needed, under the assumption
740 // that the Android runtime guarantees at least "component size" alignment:
741 // ptc = (ALIGN - (&a[initial] % ALIGN)) / type-size
Aart Bik14a68b42017-06-08 14:06:58 -0700742 HInstruction* ptc = nullptr;
743 if (vector_peeling_candidate_ != nullptr) {
744 DCHECK_LT(vector_length_, trip_count) << "dynamic peeling currently requires known trip count";
745 //
746 // TODO: Implement this. Compute address of first access memory location and
747 // compute peeling factor to obtain kAlignedBase alignment.
748 //
749 needs_cleanup = true;
750 }
751
752 // Generate loop control:
Aart Bikf8f5a162017-02-06 15:35:29 -0800753 // stc = <trip-count>;
Aart Bik14a68b42017-06-08 14:06:58 -0700754 // vtc = stc - (stc - ptc) % chunk;
755 // i = 0;
Aart Bikf8f5a162017-02-06 15:35:29 -0800756 HInstruction* stc = induction_range_.GenerateTripCount(node->loop_info, graph_, preheader);
757 HInstruction* vtc = stc;
758 if (needs_cleanup) {
Aart Bik14a68b42017-06-08 14:06:58 -0700759 DCHECK(IsPowerOfTwo(chunk));
760 HInstruction* diff = stc;
761 if (ptc != nullptr) {
762 diff = Insert(preheader, new (global_allocator_) HSub(induc_type, stc, ptc));
763 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800764 HInstruction* rem = Insert(
765 preheader, new (global_allocator_) HAnd(induc_type,
Aart Bik14a68b42017-06-08 14:06:58 -0700766 diff,
767 graph_->GetIntConstant(chunk - 1)));
Aart Bikf8f5a162017-02-06 15:35:29 -0800768 vtc = Insert(preheader, new (global_allocator_) HSub(induc_type, stc, rem));
769 }
Aart Bik14a68b42017-06-08 14:06:58 -0700770 vector_index_ = graph_->GetIntConstant(0);
Aart Bikf8f5a162017-02-06 15:35:29 -0800771
772 // Generate runtime disambiguation test:
773 // vtc = a != b ? vtc : 0;
774 if (vector_runtime_test_a_ != nullptr) {
775 HInstruction* rt = Insert(
776 preheader,
777 new (global_allocator_) HNotEqual(vector_runtime_test_a_, vector_runtime_test_b_));
778 vtc = Insert(preheader,
779 new (global_allocator_) HSelect(rt, vtc, graph_->GetIntConstant(0), kNoDexPc));
780 needs_cleanup = true;
781 }
782
Aart Bik14a68b42017-06-08 14:06:58 -0700783 // Generate dynamic peeling loop for alignment, if needed:
784 // for ( ; i < ptc; i += 1)
785 // <loop-body>
786 if (ptc != nullptr) {
787 vector_mode_ = kSequential;
788 GenerateNewLoop(node,
789 block,
790 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
791 vector_index_,
792 ptc,
793 graph_->GetIntConstant(1),
794 /*unroll*/ 1);
795 }
796
797 // Generate vector loop, possibly further unrolled:
798 // for ( ; i < vtc; i += chunk)
Aart Bikf8f5a162017-02-06 15:35:29 -0800799 // <vectorized-loop-body>
800 vector_mode_ = kVector;
801 GenerateNewLoop(node,
802 block,
Aart Bik14a68b42017-06-08 14:06:58 -0700803 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
804 vector_index_,
Aart Bikf8f5a162017-02-06 15:35:29 -0800805 vtc,
Aart Bik14a68b42017-06-08 14:06:58 -0700806 graph_->GetIntConstant(vector_length_), // increment per unroll
807 unroll);
Aart Bikf8f5a162017-02-06 15:35:29 -0800808 HLoopInformation* vloop = vector_header_->GetLoopInformation();
809
810 // Generate cleanup loop, if needed:
811 // for ( ; i < stc; i += 1)
812 // <loop-body>
813 if (needs_cleanup) {
814 vector_mode_ = kSequential;
815 GenerateNewLoop(node,
816 block,
817 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
Aart Bik14a68b42017-06-08 14:06:58 -0700818 vector_index_,
Aart Bikf8f5a162017-02-06 15:35:29 -0800819 stc,
Aart Bik14a68b42017-06-08 14:06:58 -0700820 graph_->GetIntConstant(1),
821 /*unroll*/ 1);
Aart Bikf8f5a162017-02-06 15:35:29 -0800822 }
823
Aart Bik0148de42017-09-05 09:25:01 -0700824 // Link reductions to their final uses.
825 for (auto i = reductions_->begin(); i != reductions_->end(); ++i) {
826 if (i->first->IsPhi()) {
827 i->first->ReplaceWith(ReduceAndExtractIfNeeded(i->second));
828 }
829 }
830
Aart Bikf8f5a162017-02-06 15:35:29 -0800831 // Remove the original loop by disconnecting the body block
832 // and removing all instructions from the header.
833 block->DisconnectAndDelete();
834 while (!header->GetFirstInstruction()->IsGoto()) {
835 header->RemoveInstruction(header->GetFirstInstruction());
836 }
Aart Bikb29f6842017-07-28 15:58:41 -0700837
Aart Bik14a68b42017-06-08 14:06:58 -0700838 // Update loop hierarchy: the old header now resides in the same outer loop
839 // as the old preheader. Note that we don't bother putting sequential
840 // loops back in the hierarchy at this point.
Aart Bikf8f5a162017-02-06 15:35:29 -0800841 header->SetLoopInformation(preheader->GetLoopInformation()); // outward
842 node->loop_info = vloop;
843}
844
845void HLoopOptimization::GenerateNewLoop(LoopNode* node,
846 HBasicBlock* block,
847 HBasicBlock* new_preheader,
848 HInstruction* lo,
849 HInstruction* hi,
Aart Bik14a68b42017-06-08 14:06:58 -0700850 HInstruction* step,
851 uint32_t unroll) {
852 DCHECK(unroll == 1 || vector_mode_ == kVector);
Aart Bikf8f5a162017-02-06 15:35:29 -0800853 Primitive::Type induc_type = Primitive::kPrimInt;
854 // Prepare new loop.
Aart Bikf8f5a162017-02-06 15:35:29 -0800855 vector_preheader_ = new_preheader,
856 vector_header_ = vector_preheader_->GetSingleSuccessor();
857 vector_body_ = vector_header_->GetSuccessors()[1];
Aart Bik14a68b42017-06-08 14:06:58 -0700858 HPhi* phi = new (global_allocator_) HPhi(global_allocator_,
859 kNoRegNumber,
860 0,
861 HPhi::ToPhiType(induc_type));
Aart Bikb07d1bc2017-04-05 10:03:15 -0700862 // Generate header and prepare body.
Aart Bikf8f5a162017-02-06 15:35:29 -0800863 // for (i = lo; i < hi; i += step)
864 // <loop-body>
Aart Bik14a68b42017-06-08 14:06:58 -0700865 HInstruction* cond = new (global_allocator_) HAboveOrEqual(phi, hi);
866 vector_header_->AddPhi(phi);
Aart Bikf8f5a162017-02-06 15:35:29 -0800867 vector_header_->AddInstruction(cond);
868 vector_header_->AddInstruction(new (global_allocator_) HIf(cond));
Aart Bik14a68b42017-06-08 14:06:58 -0700869 vector_index_ = phi;
Aart Bik0148de42017-09-05 09:25:01 -0700870 vector_permanent_map_->clear(); // preserved over unrolling
Aart Bik14a68b42017-06-08 14:06:58 -0700871 for (uint32_t u = 0; u < unroll; u++) {
Aart Bik14a68b42017-06-08 14:06:58 -0700872 // Generate instruction map.
Aart Bik0148de42017-09-05 09:25:01 -0700873 vector_map_->clear();
Aart Bik14a68b42017-06-08 14:06:58 -0700874 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
875 bool vectorized_def = VectorizeDef(node, it.Current(), /*generate_code*/ true);
876 DCHECK(vectorized_def);
877 }
878 // Generate body from the instruction map, but in original program order.
879 HEnvironment* env = vector_header_->GetFirstInstruction()->GetEnvironment();
880 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
881 auto i = vector_map_->find(it.Current());
882 if (i != vector_map_->end() && !i->second->IsInBlock()) {
883 Insert(vector_body_, i->second);
884 // Deal with instructions that need an environment, such as the scalar intrinsics.
885 if (i->second->NeedsEnvironment()) {
886 i->second->CopyEnvironmentFromWithLoopPhiAdjustment(env, vector_header_);
887 }
888 }
889 }
Aart Bik0148de42017-09-05 09:25:01 -0700890 // Generate the induction.
Aart Bik14a68b42017-06-08 14:06:58 -0700891 vector_index_ = new (global_allocator_) HAdd(induc_type, vector_index_, step);
892 Insert(vector_body_, vector_index_);
Aart Bikf8f5a162017-02-06 15:35:29 -0800893 }
Aart Bik0148de42017-09-05 09:25:01 -0700894 // Finalize phi inputs for the reductions (if any).
895 for (auto i = reductions_->begin(); i != reductions_->end(); ++i) {
896 if (!i->first->IsPhi()) {
897 DCHECK(i->second->IsPhi());
898 GenerateVecReductionPhiInputs(i->second->AsPhi(), i->first);
899 }
900 }
Aart Bikb29f6842017-07-28 15:58:41 -0700901 // Finalize phi inputs for the loop index.
Aart Bik14a68b42017-06-08 14:06:58 -0700902 phi->AddInput(lo);
903 phi->AddInput(vector_index_);
904 vector_index_ = phi;
Aart Bikf8f5a162017-02-06 15:35:29 -0800905}
906
Aart Bikf8f5a162017-02-06 15:35:29 -0800907bool HLoopOptimization::VectorizeDef(LoopNode* node,
908 HInstruction* instruction,
909 bool generate_code) {
910 // Accept a left-hand-side array base[index] for
911 // (1) supported vector type,
912 // (2) loop-invariant base,
913 // (3) unit stride index,
914 // (4) vectorizable right-hand-side value.
915 uint64_t restrictions = kNone;
916 if (instruction->IsArraySet()) {
917 Primitive::Type type = instruction->AsArraySet()->GetComponentType();
918 HInstruction* base = instruction->InputAt(0);
919 HInstruction* index = instruction->InputAt(1);
920 HInstruction* value = instruction->InputAt(2);
921 HInstruction* offset = nullptr;
922 if (TrySetVectorType(type, &restrictions) &&
923 node->loop_info->IsDefinedOutOfTheLoop(base) &&
Aart Bik37dc4df2017-06-28 14:08:00 -0700924 induction_range_.IsUnitStride(instruction, index, graph_, &offset) &&
Aart Bikf8f5a162017-02-06 15:35:29 -0800925 VectorizeUse(node, value, generate_code, type, restrictions)) {
926 if (generate_code) {
927 GenerateVecSub(index, offset);
Aart Bik14a68b42017-06-08 14:06:58 -0700928 GenerateVecMem(instruction, vector_map_->Get(index), vector_map_->Get(value), offset, type);
Aart Bikf8f5a162017-02-06 15:35:29 -0800929 } else {
930 vector_refs_->insert(ArrayReference(base, offset, type, /*lhs*/ true));
931 }
Aart Bik6b69e0a2017-01-11 10:20:43 -0800932 return true;
933 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800934 return false;
935 }
Aart Bik0148de42017-09-05 09:25:01 -0700936 // Accept a left-hand-side reduction for
937 // (1) supported vector type,
938 // (2) vectorizable right-hand-side value.
939 auto redit = reductions_->find(instruction);
940 if (redit != reductions_->end()) {
941 Primitive::Type type = instruction->GetType();
942 if (TrySetVectorType(type, &restrictions) &&
943 VectorizeUse(node, instruction, generate_code, type, restrictions)) {
944 if (generate_code) {
945 HInstruction* new_red = vector_map_->Get(instruction);
946 vector_permanent_map_->Put(new_red, vector_map_->Get(redit->second));
947 vector_permanent_map_->Overwrite(redit->second, new_red);
948 }
949 return true;
950 }
951 return false;
952 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800953 // Branch back okay.
954 if (instruction->IsGoto()) {
955 return true;
956 }
957 // Otherwise accept only expressions with no effects outside the immediate loop-body.
958 // Note that actual uses are inspected during right-hand-side tree traversal.
959 return !IsUsedOutsideLoop(node->loop_info, instruction) && !instruction->DoesAnyWrite();
960}
961
Aart Bik304c8a52017-05-23 11:01:13 -0700962// TODO: saturation arithmetic.
Aart Bikf8f5a162017-02-06 15:35:29 -0800963bool HLoopOptimization::VectorizeUse(LoopNode* node,
964 HInstruction* instruction,
965 bool generate_code,
966 Primitive::Type type,
967 uint64_t restrictions) {
968 // Accept anything for which code has already been generated.
969 if (generate_code) {
970 if (vector_map_->find(instruction) != vector_map_->end()) {
971 return true;
972 }
973 }
974 // Continue the right-hand-side tree traversal, passing in proper
975 // types and vector restrictions along the way. During code generation,
976 // all new nodes are drawn from the global allocator.
977 if (node->loop_info->IsDefinedOutOfTheLoop(instruction)) {
978 // Accept invariant use, using scalar expansion.
979 if (generate_code) {
980 GenerateVecInv(instruction, type);
981 }
982 return true;
983 } else if (instruction->IsArrayGet()) {
Goran Jakovljevic19680d32017-05-11 10:38:36 +0200984 // Deal with vector restrictions.
985 if (instruction->AsArrayGet()->IsStringCharAt() &&
986 HasVectorRestrictions(restrictions, kNoStringCharAt)) {
987 return false;
988 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800989 // Accept a right-hand-side array base[index] for
990 // (1) exact matching vector type,
991 // (2) loop-invariant base,
992 // (3) unit stride index,
993 // (4) vectorizable right-hand-side value.
994 HInstruction* base = instruction->InputAt(0);
995 HInstruction* index = instruction->InputAt(1);
996 HInstruction* offset = nullptr;
997 if (type == instruction->GetType() &&
998 node->loop_info->IsDefinedOutOfTheLoop(base) &&
Aart Bik37dc4df2017-06-28 14:08:00 -0700999 induction_range_.IsUnitStride(instruction, index, graph_, &offset)) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001000 if (generate_code) {
1001 GenerateVecSub(index, offset);
Aart Bik14a68b42017-06-08 14:06:58 -07001002 GenerateVecMem(instruction, vector_map_->Get(index), nullptr, offset, type);
Aart Bikf8f5a162017-02-06 15:35:29 -08001003 } else {
1004 vector_refs_->insert(ArrayReference(base, offset, type, /*lhs*/ false));
1005 }
1006 return true;
1007 }
Aart Bik0148de42017-09-05 09:25:01 -07001008 } else if (instruction->IsPhi()) {
1009 // Accept particular phi operations.
1010 if (reductions_->find(instruction) != reductions_->end()) {
1011 // Deal with vector restrictions.
1012 if (HasVectorRestrictions(restrictions, kNoReduction)) {
1013 return false;
1014 }
1015 // Accept a reduction.
1016 if (generate_code) {
1017 GenerateVecReductionPhi(instruction->AsPhi());
1018 }
1019 return true;
1020 }
1021 // TODO: accept right-hand-side induction?
1022 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001023 } else if (instruction->IsTypeConversion()) {
1024 // Accept particular type conversions.
1025 HTypeConversion* conversion = instruction->AsTypeConversion();
1026 HInstruction* opa = conversion->InputAt(0);
1027 Primitive::Type from = conversion->GetInputType();
1028 Primitive::Type to = conversion->GetResultType();
1029 if ((to == Primitive::kPrimByte ||
1030 to == Primitive::kPrimChar ||
1031 to == Primitive::kPrimShort) && from == Primitive::kPrimInt) {
1032 // Accept a "narrowing" type conversion from a "wider" computation for
1033 // (1) conversion into final required type,
1034 // (2) vectorizable operand,
1035 // (3) "wider" operations cannot bring in higher order bits.
1036 if (to == type && VectorizeUse(node, opa, generate_code, type, restrictions | kNoHiBits)) {
1037 if (generate_code) {
1038 if (vector_mode_ == kVector) {
1039 vector_map_->Put(instruction, vector_map_->Get(opa)); // operand pass-through
1040 } else {
1041 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1042 }
1043 }
1044 return true;
1045 }
1046 } else if (to == Primitive::kPrimFloat && from == Primitive::kPrimInt) {
1047 DCHECK_EQ(to, type);
1048 // Accept int to float conversion for
1049 // (1) supported int,
1050 // (2) vectorizable operand.
1051 if (TrySetVectorType(from, &restrictions) &&
1052 VectorizeUse(node, opa, generate_code, from, restrictions)) {
1053 if (generate_code) {
1054 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1055 }
1056 return true;
1057 }
1058 }
1059 return false;
1060 } else if (instruction->IsNeg() || instruction->IsNot() || instruction->IsBooleanNot()) {
1061 // Accept unary operator for vectorizable operand.
1062 HInstruction* opa = instruction->InputAt(0);
1063 if (VectorizeUse(node, opa, generate_code, type, restrictions)) {
1064 if (generate_code) {
1065 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1066 }
1067 return true;
1068 }
1069 } else if (instruction->IsAdd() || instruction->IsSub() ||
1070 instruction->IsMul() || instruction->IsDiv() ||
1071 instruction->IsAnd() || instruction->IsOr() || instruction->IsXor()) {
1072 // Deal with vector restrictions.
1073 if ((instruction->IsMul() && HasVectorRestrictions(restrictions, kNoMul)) ||
1074 (instruction->IsDiv() && HasVectorRestrictions(restrictions, kNoDiv))) {
1075 return false;
1076 }
1077 // Accept binary operator for vectorizable operands.
1078 HInstruction* opa = instruction->InputAt(0);
1079 HInstruction* opb = instruction->InputAt(1);
1080 if (VectorizeUse(node, opa, generate_code, type, restrictions) &&
1081 VectorizeUse(node, opb, generate_code, type, restrictions)) {
1082 if (generate_code) {
1083 GenerateVecOp(instruction, vector_map_->Get(opa), vector_map_->Get(opb), type);
1084 }
1085 return true;
1086 }
1087 } else if (instruction->IsShl() || instruction->IsShr() || instruction->IsUShr()) {
Aart Bikf3e61ee2017-04-12 17:09:20 -07001088 // Recognize vectorization idioms.
1089 if (VectorizeHalvingAddIdiom(node, instruction, generate_code, type, restrictions)) {
1090 return true;
1091 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001092 // Deal with vector restrictions.
Aart Bik304c8a52017-05-23 11:01:13 -07001093 HInstruction* opa = instruction->InputAt(0);
1094 HInstruction* opb = instruction->InputAt(1);
1095 HInstruction* r = opa;
1096 bool is_unsigned = false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001097 if ((HasVectorRestrictions(restrictions, kNoShift)) ||
1098 (instruction->IsShr() && HasVectorRestrictions(restrictions, kNoShr))) {
1099 return false; // unsupported instruction
Aart Bik304c8a52017-05-23 11:01:13 -07001100 } else if (HasVectorRestrictions(restrictions, kNoHiBits)) {
1101 // Shifts right need extra care to account for higher order bits.
1102 // TODO: less likely shr/unsigned and ushr/signed can by flipping signess.
1103 if (instruction->IsShr() &&
1104 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || is_unsigned)) {
1105 return false; // reject, unless all operands are sign-extension narrower
1106 } else if (instruction->IsUShr() &&
1107 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || !is_unsigned)) {
1108 return false; // reject, unless all operands are zero-extension narrower
1109 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001110 }
1111 // Accept shift operator for vectorizable/invariant operands.
1112 // TODO: accept symbolic, albeit loop invariant shift factors.
Aart Bik304c8a52017-05-23 11:01:13 -07001113 DCHECK(r != nullptr);
1114 if (generate_code && vector_mode_ != kVector) { // de-idiom
1115 r = opa;
1116 }
Aart Bik50e20d52017-05-05 14:07:29 -07001117 int64_t distance = 0;
Aart Bik304c8a52017-05-23 11:01:13 -07001118 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
Aart Bik50e20d52017-05-05 14:07:29 -07001119 IsInt64AndGet(opb, /*out*/ &distance)) {
Aart Bik65ffd8e2017-05-01 16:50:45 -07001120 // Restrict shift distance to packed data type width.
1121 int64_t max_distance = Primitive::ComponentSize(type) * 8;
1122 if (0 <= distance && distance < max_distance) {
1123 if (generate_code) {
Aart Bik304c8a52017-05-23 11:01:13 -07001124 GenerateVecOp(instruction, vector_map_->Get(r), opb, type);
Aart Bik65ffd8e2017-05-01 16:50:45 -07001125 }
1126 return true;
Aart Bikf8f5a162017-02-06 15:35:29 -08001127 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001128 }
1129 } else if (instruction->IsInvokeStaticOrDirect()) {
Aart Bik6daebeb2017-04-03 14:35:41 -07001130 // Accept particular intrinsics.
1131 HInvokeStaticOrDirect* invoke = instruction->AsInvokeStaticOrDirect();
1132 switch (invoke->GetIntrinsic()) {
1133 case Intrinsics::kMathAbsInt:
1134 case Intrinsics::kMathAbsLong:
1135 case Intrinsics::kMathAbsFloat:
1136 case Intrinsics::kMathAbsDouble: {
1137 // Deal with vector restrictions.
Aart Bik304c8a52017-05-23 11:01:13 -07001138 HInstruction* opa = instruction->InputAt(0);
1139 HInstruction* r = opa;
1140 bool is_unsigned = false;
1141 if (HasVectorRestrictions(restrictions, kNoAbs)) {
Aart Bik6daebeb2017-04-03 14:35:41 -07001142 return false;
Aart Bik304c8a52017-05-23 11:01:13 -07001143 } else if (HasVectorRestrictions(restrictions, kNoHiBits) &&
1144 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || is_unsigned)) {
1145 return false; // reject, unless operand is sign-extension narrower
Aart Bik6daebeb2017-04-03 14:35:41 -07001146 }
1147 // Accept ABS(x) for vectorizable operand.
Aart Bik304c8a52017-05-23 11:01:13 -07001148 DCHECK(r != nullptr);
1149 if (generate_code && vector_mode_ != kVector) { // de-idiom
1150 r = opa;
1151 }
1152 if (VectorizeUse(node, r, generate_code, type, restrictions)) {
Aart Bik6daebeb2017-04-03 14:35:41 -07001153 if (generate_code) {
Aart Bik304c8a52017-05-23 11:01:13 -07001154 GenerateVecOp(instruction, vector_map_->Get(r), nullptr, type);
Aart Bik6daebeb2017-04-03 14:35:41 -07001155 }
1156 return true;
1157 }
1158 return false;
1159 }
Aart Bikc8e93c72017-05-10 10:49:22 -07001160 case Intrinsics::kMathMinIntInt:
1161 case Intrinsics::kMathMinLongLong:
1162 case Intrinsics::kMathMinFloatFloat:
1163 case Intrinsics::kMathMinDoubleDouble:
1164 case Intrinsics::kMathMaxIntInt:
1165 case Intrinsics::kMathMaxLongLong:
1166 case Intrinsics::kMathMaxFloatFloat:
1167 case Intrinsics::kMathMaxDoubleDouble: {
1168 // Deal with vector restrictions.
Nicolas Geoffray92316902017-05-23 08:06:07 +00001169 HInstruction* opa = instruction->InputAt(0);
1170 HInstruction* opb = instruction->InputAt(1);
Aart Bik304c8a52017-05-23 11:01:13 -07001171 HInstruction* r = opa;
1172 HInstruction* s = opb;
1173 bool is_unsigned = false;
1174 if (HasVectorRestrictions(restrictions, kNoMinMax)) {
1175 return false;
1176 } else if (HasVectorRestrictions(restrictions, kNoHiBits) &&
1177 !IsNarrowerOperands(opa, opb, type, &r, &s, &is_unsigned)) {
1178 return false; // reject, unless all operands are same-extension narrower
1179 }
1180 // Accept MIN/MAX(x, y) for vectorizable operands.
1181 DCHECK(r != nullptr && s != nullptr);
1182 if (generate_code && vector_mode_ != kVector) { // de-idiom
1183 r = opa;
1184 s = opb;
1185 }
1186 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
1187 VectorizeUse(node, s, generate_code, type, restrictions)) {
Aart Bikc8e93c72017-05-10 10:49:22 -07001188 if (generate_code) {
Aart Bik304c8a52017-05-23 11:01:13 -07001189 GenerateVecOp(
1190 instruction, vector_map_->Get(r), vector_map_->Get(s), type, is_unsigned);
Aart Bikc8e93c72017-05-10 10:49:22 -07001191 }
1192 return true;
1193 }
1194 return false;
1195 }
Aart Bik6daebeb2017-04-03 14:35:41 -07001196 default:
1197 return false;
1198 } // switch
Aart Bik281c6812016-08-26 11:31:48 -07001199 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08001200 return false;
Aart Bik281c6812016-08-26 11:31:48 -07001201}
1202
Aart Bikf8f5a162017-02-06 15:35:29 -08001203bool HLoopOptimization::TrySetVectorType(Primitive::Type type, uint64_t* restrictions) {
1204 const InstructionSetFeatures* features = compiler_driver_->GetInstructionSetFeatures();
1205 switch (compiler_driver_->GetInstructionSet()) {
1206 case kArm:
1207 case kThumb2:
Artem Serov8f7c4102017-06-21 11:21:37 +01001208 // Allow vectorization for all ARM devices, because Android assumes that
Aart Bikb29f6842017-07-28 15:58:41 -07001209 // ARM 32-bit always supports advanced SIMD (64-bit SIMD).
Artem Serov8f7c4102017-06-21 11:21:37 +01001210 switch (type) {
1211 case Primitive::kPrimBoolean:
1212 case Primitive::kPrimByte:
Aart Bik0148de42017-09-05 09:25:01 -07001213 *restrictions |= kNoDiv | kNoReduction;
Artem Serov8f7c4102017-06-21 11:21:37 +01001214 return TrySetVectorLength(8);
1215 case Primitive::kPrimChar:
1216 case Primitive::kPrimShort:
Aart Bik0148de42017-09-05 09:25:01 -07001217 *restrictions |= kNoDiv | kNoStringCharAt | kNoReduction;
Artem Serov8f7c4102017-06-21 11:21:37 +01001218 return TrySetVectorLength(4);
1219 case Primitive::kPrimInt:
Aart Bik0148de42017-09-05 09:25:01 -07001220 *restrictions |= kNoDiv | kNoReduction;
Artem Serov8f7c4102017-06-21 11:21:37 +01001221 return TrySetVectorLength(2);
1222 default:
1223 break;
1224 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001225 return false;
1226 case kArm64:
1227 // Allow vectorization for all ARM devices, because Android assumes that
Aart Bikb29f6842017-07-28 15:58:41 -07001228 // ARMv8 AArch64 always supports advanced SIMD (128-bit SIMD).
Aart Bikf8f5a162017-02-06 15:35:29 -08001229 switch (type) {
1230 case Primitive::kPrimBoolean:
1231 case Primitive::kPrimByte:
Aart Bik0148de42017-09-05 09:25:01 -07001232 *restrictions |= kNoDiv | kNoReduction;
Artem Serovd4bccf12017-04-03 18:47:32 +01001233 return TrySetVectorLength(16);
Aart Bikf8f5a162017-02-06 15:35:29 -08001234 case Primitive::kPrimChar:
1235 case Primitive::kPrimShort:
Aart Bik0148de42017-09-05 09:25:01 -07001236 *restrictions |= kNoDiv | kNoReduction;
Artem Serovd4bccf12017-04-03 18:47:32 +01001237 return TrySetVectorLength(8);
Aart Bikf8f5a162017-02-06 15:35:29 -08001238 case Primitive::kPrimInt:
1239 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +01001240 return TrySetVectorLength(4);
Artem Serovb31f91f2017-04-05 11:31:19 +01001241 case Primitive::kPrimLong:
Aart Bikc8e93c72017-05-10 10:49:22 -07001242 *restrictions |= kNoDiv | kNoMul | kNoMinMax;
Aart Bikf8f5a162017-02-06 15:35:29 -08001243 return TrySetVectorLength(2);
1244 case Primitive::kPrimFloat:
Aart Bik0148de42017-09-05 09:25:01 -07001245 *restrictions |= kNoReduction;
Artem Serovd4bccf12017-04-03 18:47:32 +01001246 return TrySetVectorLength(4);
Artem Serovb31f91f2017-04-05 11:31:19 +01001247 case Primitive::kPrimDouble:
Aart Bik0148de42017-09-05 09:25:01 -07001248 *restrictions |= kNoReduction;
Aart Bikf8f5a162017-02-06 15:35:29 -08001249 return TrySetVectorLength(2);
1250 default:
1251 return false;
1252 }
1253 case kX86:
1254 case kX86_64:
Aart Bikb29f6842017-07-28 15:58:41 -07001255 // Allow vectorization for SSE4.1-enabled X86 devices only (128-bit SIMD).
Aart Bikf8f5a162017-02-06 15:35:29 -08001256 if (features->AsX86InstructionSetFeatures()->HasSSE4_1()) {
1257 switch (type) {
1258 case Primitive::kPrimBoolean:
1259 case Primitive::kPrimByte:
Aart Bik0148de42017-09-05 09:25:01 -07001260 *restrictions |=
1261 kNoMul | kNoDiv | kNoShift | kNoAbs | kNoSignedHAdd | kNoUnroundedHAdd | kNoReduction;
Aart Bikf8f5a162017-02-06 15:35:29 -08001262 return TrySetVectorLength(16);
1263 case Primitive::kPrimChar:
1264 case Primitive::kPrimShort:
Aart Bik0148de42017-09-05 09:25:01 -07001265 *restrictions |= kNoDiv | kNoAbs | kNoSignedHAdd | kNoUnroundedHAdd | kNoReduction;
Aart Bikf8f5a162017-02-06 15:35:29 -08001266 return TrySetVectorLength(8);
1267 case Primitive::kPrimInt:
1268 *restrictions |= kNoDiv;
1269 return TrySetVectorLength(4);
1270 case Primitive::kPrimLong:
Aart Bikc8e93c72017-05-10 10:49:22 -07001271 *restrictions |= kNoMul | kNoDiv | kNoShr | kNoAbs | kNoMinMax;
Aart Bikf8f5a162017-02-06 15:35:29 -08001272 return TrySetVectorLength(2);
1273 case Primitive::kPrimFloat:
Aart Bik0148de42017-09-05 09:25:01 -07001274 *restrictions |= kNoMinMax | kNoReduction; // minmax: -0.0 vs +0.0
Aart Bikf8f5a162017-02-06 15:35:29 -08001275 return TrySetVectorLength(4);
1276 case Primitive::kPrimDouble:
Aart Bik0148de42017-09-05 09:25:01 -07001277 *restrictions |= kNoMinMax | kNoReduction; // minmax: -0.0 vs +0.0
Aart Bikf8f5a162017-02-06 15:35:29 -08001278 return TrySetVectorLength(2);
1279 default:
1280 break;
1281 } // switch type
1282 }
1283 return false;
1284 case kMips:
Lena Djokic51765b02017-06-22 13:49:59 +02001285 if (features->AsMipsInstructionSetFeatures()->HasMsa()) {
1286 switch (type) {
1287 case Primitive::kPrimBoolean:
1288 case Primitive::kPrimByte:
Aart Bik0148de42017-09-05 09:25:01 -07001289 *restrictions |= kNoDiv | kNoReduction;
Lena Djokic51765b02017-06-22 13:49:59 +02001290 return TrySetVectorLength(16);
1291 case Primitive::kPrimChar:
1292 case Primitive::kPrimShort:
Aart Bik0148de42017-09-05 09:25:01 -07001293 *restrictions |= kNoDiv | kNoStringCharAt | kNoReduction;
Lena Djokic51765b02017-06-22 13:49:59 +02001294 return TrySetVectorLength(8);
1295 case Primitive::kPrimInt:
Aart Bik0148de42017-09-05 09:25:01 -07001296 *restrictions |= kNoDiv | kNoReduction;
Lena Djokic51765b02017-06-22 13:49:59 +02001297 return TrySetVectorLength(4);
1298 case Primitive::kPrimLong:
Aart Bik0148de42017-09-05 09:25:01 -07001299 *restrictions |= kNoDiv | kNoReduction;
Lena Djokic51765b02017-06-22 13:49:59 +02001300 return TrySetVectorLength(2);
1301 case Primitive::kPrimFloat:
Aart Bik0148de42017-09-05 09:25:01 -07001302 *restrictions |= kNoMinMax | kNoReduction; // min/max(x, NaN)
Lena Djokic51765b02017-06-22 13:49:59 +02001303 return TrySetVectorLength(4);
1304 case Primitive::kPrimDouble:
Aart Bik0148de42017-09-05 09:25:01 -07001305 *restrictions |= kNoMinMax | kNoReduction; // min/max(x, NaN)
Lena Djokic51765b02017-06-22 13:49:59 +02001306 return TrySetVectorLength(2);
1307 default:
1308 break;
1309 } // switch type
1310 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001311 return false;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001312 case kMips64:
1313 if (features->AsMips64InstructionSetFeatures()->HasMsa()) {
1314 switch (type) {
1315 case Primitive::kPrimBoolean:
1316 case Primitive::kPrimByte:
Aart Bik0148de42017-09-05 09:25:01 -07001317 *restrictions |= kNoDiv | kNoReduction;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001318 return TrySetVectorLength(16);
1319 case Primitive::kPrimChar:
1320 case Primitive::kPrimShort:
Aart Bik0148de42017-09-05 09:25:01 -07001321 *restrictions |= kNoDiv | kNoStringCharAt | kNoReduction;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001322 return TrySetVectorLength(8);
1323 case Primitive::kPrimInt:
Aart Bik0148de42017-09-05 09:25:01 -07001324 *restrictions |= kNoDiv | kNoReduction;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001325 return TrySetVectorLength(4);
1326 case Primitive::kPrimLong:
Aart Bik0148de42017-09-05 09:25:01 -07001327 *restrictions |= kNoDiv | kNoReduction;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001328 return TrySetVectorLength(2);
1329 case Primitive::kPrimFloat:
Aart Bik0148de42017-09-05 09:25:01 -07001330 *restrictions |= kNoMinMax | kNoReduction; // min/max(x, NaN)
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001331 return TrySetVectorLength(4);
1332 case Primitive::kPrimDouble:
Aart Bik0148de42017-09-05 09:25:01 -07001333 *restrictions |= kNoMinMax | kNoReduction; // min/max(x, NaN)
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001334 return TrySetVectorLength(2);
1335 default:
1336 break;
1337 } // switch type
1338 }
1339 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001340 default:
1341 return false;
1342 } // switch instruction set
1343}
1344
1345bool HLoopOptimization::TrySetVectorLength(uint32_t length) {
1346 DCHECK(IsPowerOfTwo(length) && length >= 2u);
1347 // First time set?
1348 if (vector_length_ == 0) {
1349 vector_length_ = length;
1350 }
1351 // Different types are acceptable within a loop-body, as long as all the corresponding vector
1352 // lengths match exactly to obtain a uniform traversal through the vector iteration space
1353 // (idiomatic exceptions to this rule can be handled by further unrolling sub-expressions).
1354 return vector_length_ == length;
1355}
1356
1357void HLoopOptimization::GenerateVecInv(HInstruction* org, Primitive::Type type) {
1358 if (vector_map_->find(org) == vector_map_->end()) {
1359 // In scalar code, just use a self pass-through for scalar invariants
1360 // (viz. expression remains itself).
1361 if (vector_mode_ == kSequential) {
1362 vector_map_->Put(org, org);
1363 return;
1364 }
1365 // In vector code, explicit scalar expansion is needed.
Aart Bik0148de42017-09-05 09:25:01 -07001366 HInstruction* vector = nullptr;
1367 auto it = vector_permanent_map_->find(org);
1368 if (it != vector_permanent_map_->end()) {
1369 vector = it->second; // reuse during unrolling
1370 } else {
1371 vector = new (global_allocator_) HVecReplicateScalar(
1372 global_allocator_, org, type, vector_length_);
1373 vector_permanent_map_->Put(org, Insert(vector_preheader_, vector));
1374 }
1375 vector_map_->Put(org, vector);
Aart Bikf8f5a162017-02-06 15:35:29 -08001376 }
1377}
1378
1379void HLoopOptimization::GenerateVecSub(HInstruction* org, HInstruction* offset) {
1380 if (vector_map_->find(org) == vector_map_->end()) {
Aart Bik14a68b42017-06-08 14:06:58 -07001381 HInstruction* subscript = vector_index_;
Aart Bik37dc4df2017-06-28 14:08:00 -07001382 int64_t value = 0;
1383 if (!IsInt64AndGet(offset, &value) || value != 0) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001384 subscript = new (global_allocator_) HAdd(Primitive::kPrimInt, subscript, offset);
1385 if (org->IsPhi()) {
1386 Insert(vector_body_, subscript); // lacks layout placeholder
1387 }
1388 }
1389 vector_map_->Put(org, subscript);
1390 }
1391}
1392
1393void HLoopOptimization::GenerateVecMem(HInstruction* org,
1394 HInstruction* opa,
1395 HInstruction* opb,
Aart Bik14a68b42017-06-08 14:06:58 -07001396 HInstruction* offset,
Aart Bikf8f5a162017-02-06 15:35:29 -08001397 Primitive::Type type) {
1398 HInstruction* vector = nullptr;
1399 if (vector_mode_ == kVector) {
1400 // Vector store or load.
Aart Bik14a68b42017-06-08 14:06:58 -07001401 HInstruction* base = org->InputAt(0);
Aart Bikf8f5a162017-02-06 15:35:29 -08001402 if (opb != nullptr) {
1403 vector = new (global_allocator_) HVecStore(
Aart Bik14a68b42017-06-08 14:06:58 -07001404 global_allocator_, base, opa, opb, type, vector_length_);
Aart Bikf8f5a162017-02-06 15:35:29 -08001405 } else {
Aart Bikdb14fcf2017-04-25 15:53:58 -07001406 bool is_string_char_at = org->AsArrayGet()->IsStringCharAt();
Aart Bikf8f5a162017-02-06 15:35:29 -08001407 vector = new (global_allocator_) HVecLoad(
Aart Bik14a68b42017-06-08 14:06:58 -07001408 global_allocator_, base, opa, type, vector_length_, is_string_char_at);
1409 }
1410 // Known dynamically enforced alignment?
Aart Bik14a68b42017-06-08 14:06:58 -07001411 if (vector_peeling_candidate_ != nullptr &&
1412 vector_peeling_candidate_->base == base &&
1413 vector_peeling_candidate_->offset == offset) {
1414 vector->AsVecMemoryOperation()->SetAlignment(Alignment(kAlignedBase, 0));
Aart Bikf8f5a162017-02-06 15:35:29 -08001415 }
1416 } else {
1417 // Scalar store or load.
1418 DCHECK(vector_mode_ == kSequential);
1419 if (opb != nullptr) {
1420 vector = new (global_allocator_) HArraySet(org->InputAt(0), opa, opb, type, kNoDexPc);
1421 } else {
Aart Bikdb14fcf2017-04-25 15:53:58 -07001422 bool is_string_char_at = org->AsArrayGet()->IsStringCharAt();
1423 vector = new (global_allocator_) HArrayGet(
1424 org->InputAt(0), opa, type, kNoDexPc, is_string_char_at);
Aart Bikf8f5a162017-02-06 15:35:29 -08001425 }
1426 }
1427 vector_map_->Put(org, vector);
1428}
1429
Aart Bik0148de42017-09-05 09:25:01 -07001430void HLoopOptimization::GenerateVecReductionPhi(HPhi* phi) {
1431 DCHECK(reductions_->find(phi) != reductions_->end());
1432 DCHECK(reductions_->Get(phi->InputAt(1)) == phi);
1433 HInstruction* vector = nullptr;
1434 if (vector_mode_ == kSequential) {
1435 HPhi* new_phi = new (global_allocator_) HPhi(
1436 global_allocator_, kNoRegNumber, 0, phi->GetType());
1437 vector_header_->AddPhi(new_phi);
1438 vector = new_phi;
1439 } else {
1440 // Link vector reduction back to prior unrolled update, or a first phi.
1441 auto it = vector_permanent_map_->find(phi);
1442 if (it != vector_permanent_map_->end()) {
1443 vector = it->second;
1444 } else {
1445 HPhi* new_phi = new (global_allocator_) HPhi(
1446 global_allocator_, kNoRegNumber, 0, HVecOperation::kSIMDType);
1447 vector_header_->AddPhi(new_phi);
1448 vector = new_phi;
1449 }
1450 }
1451 vector_map_->Put(phi, vector);
1452}
1453
1454void HLoopOptimization::GenerateVecReductionPhiInputs(HPhi* phi, HInstruction* reduction) {
1455 HInstruction* new_phi = vector_map_->Get(phi);
1456 HInstruction* new_init = reductions_->Get(phi);
1457 HInstruction* new_red = vector_map_->Get(reduction);
1458 // Link unrolled vector loop back to new phi.
1459 for (; !new_phi->IsPhi(); new_phi = vector_permanent_map_->Get(new_phi)) {
1460 DCHECK(new_phi->IsVecOperation());
1461 }
1462 // Prepare the new initialization.
1463 if (vector_mode_ == kVector) {
1464 // Generate a [initial, 0, .., 0] vector.
1465 new_init = Insert(
1466 vector_preheader_,
1467 new (global_allocator_) HVecSetScalars(
1468 global_allocator_, &new_init, phi->GetType(), vector_length_, 1));
1469 } else {
1470 new_init = ReduceAndExtractIfNeeded(new_init);
1471 }
1472 // Set the phi inputs.
1473 DCHECK(new_phi->IsPhi());
1474 new_phi->AsPhi()->AddInput(new_init);
1475 new_phi->AsPhi()->AddInput(new_red);
1476 // New feed value for next phi (safe mutation in iteration).
1477 reductions_->find(phi)->second = new_phi;
1478}
1479
1480HInstruction* HLoopOptimization::ReduceAndExtractIfNeeded(HInstruction* instruction) {
1481 if (instruction->IsPhi()) {
1482 HInstruction* input = instruction->InputAt(1);
1483 if (input->IsVecOperation()) {
1484 Primitive::Type type = input->AsVecOperation()->GetPackedType();
1485 HBasicBlock* exit = instruction->GetBlock()->GetSuccessors()[0];
1486 // Generate a vector reduction and scalar extract
1487 // x = REDUCE( [x_1, .., x_n] )
1488 // y = x_1
1489 // along the exit of the defining loop.
1490 HVecReduce::ReductionKind kind = GetReductionKind(input);
1491 HInstruction* reduce = new (global_allocator_) HVecReduce(
1492 global_allocator_, instruction, type, vector_length_, kind);
1493 exit->InsertInstructionBefore(reduce, exit->GetFirstInstruction());
1494 instruction = new (global_allocator_) HVecExtractScalar(
1495 global_allocator_, reduce, type, vector_length_, 0);
1496 exit->InsertInstructionAfter(instruction, reduce);
1497 }
1498 }
1499 return instruction;
1500}
1501
Aart Bikf8f5a162017-02-06 15:35:29 -08001502#define GENERATE_VEC(x, y) \
1503 if (vector_mode_ == kVector) { \
1504 vector = (x); \
1505 } else { \
1506 DCHECK(vector_mode_ == kSequential); \
1507 vector = (y); \
1508 } \
1509 break;
1510
1511void HLoopOptimization::GenerateVecOp(HInstruction* org,
1512 HInstruction* opa,
1513 HInstruction* opb,
Aart Bik304c8a52017-05-23 11:01:13 -07001514 Primitive::Type type,
1515 bool is_unsigned) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001516 if (vector_mode_ == kSequential) {
Aart Bik304c8a52017-05-23 11:01:13 -07001517 // Non-converting scalar code follows implicit integral promotion.
1518 if (!org->IsTypeConversion() && (type == Primitive::kPrimBoolean ||
1519 type == Primitive::kPrimByte ||
1520 type == Primitive::kPrimChar ||
1521 type == Primitive::kPrimShort)) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001522 type = Primitive::kPrimInt;
1523 }
1524 }
1525 HInstruction* vector = nullptr;
1526 switch (org->GetKind()) {
1527 case HInstruction::kNeg:
1528 DCHECK(opb == nullptr);
1529 GENERATE_VEC(
1530 new (global_allocator_) HVecNeg(global_allocator_, opa, type, vector_length_),
1531 new (global_allocator_) HNeg(type, opa));
1532 case HInstruction::kNot:
1533 DCHECK(opb == nullptr);
1534 GENERATE_VEC(
1535 new (global_allocator_) HVecNot(global_allocator_, opa, type, vector_length_),
1536 new (global_allocator_) HNot(type, opa));
1537 case HInstruction::kBooleanNot:
1538 DCHECK(opb == nullptr);
1539 GENERATE_VEC(
1540 new (global_allocator_) HVecNot(global_allocator_, opa, type, vector_length_),
1541 new (global_allocator_) HBooleanNot(opa));
1542 case HInstruction::kTypeConversion:
1543 DCHECK(opb == nullptr);
1544 GENERATE_VEC(
1545 new (global_allocator_) HVecCnv(global_allocator_, opa, type, vector_length_),
1546 new (global_allocator_) HTypeConversion(type, opa, kNoDexPc));
1547 case HInstruction::kAdd:
1548 GENERATE_VEC(
1549 new (global_allocator_) HVecAdd(global_allocator_, opa, opb, type, vector_length_),
1550 new (global_allocator_) HAdd(type, opa, opb));
1551 case HInstruction::kSub:
1552 GENERATE_VEC(
1553 new (global_allocator_) HVecSub(global_allocator_, opa, opb, type, vector_length_),
1554 new (global_allocator_) HSub(type, opa, opb));
1555 case HInstruction::kMul:
1556 GENERATE_VEC(
1557 new (global_allocator_) HVecMul(global_allocator_, opa, opb, type, vector_length_),
1558 new (global_allocator_) HMul(type, opa, opb));
1559 case HInstruction::kDiv:
1560 GENERATE_VEC(
1561 new (global_allocator_) HVecDiv(global_allocator_, opa, opb, type, vector_length_),
1562 new (global_allocator_) HDiv(type, opa, opb, kNoDexPc));
1563 case HInstruction::kAnd:
1564 GENERATE_VEC(
1565 new (global_allocator_) HVecAnd(global_allocator_, opa, opb, type, vector_length_),
1566 new (global_allocator_) HAnd(type, opa, opb));
1567 case HInstruction::kOr:
1568 GENERATE_VEC(
1569 new (global_allocator_) HVecOr(global_allocator_, opa, opb, type, vector_length_),
1570 new (global_allocator_) HOr(type, opa, opb));
1571 case HInstruction::kXor:
1572 GENERATE_VEC(
1573 new (global_allocator_) HVecXor(global_allocator_, opa, opb, type, vector_length_),
1574 new (global_allocator_) HXor(type, opa, opb));
1575 case HInstruction::kShl:
1576 GENERATE_VEC(
1577 new (global_allocator_) HVecShl(global_allocator_, opa, opb, type, vector_length_),
1578 new (global_allocator_) HShl(type, opa, opb));
1579 case HInstruction::kShr:
1580 GENERATE_VEC(
1581 new (global_allocator_) HVecShr(global_allocator_, opa, opb, type, vector_length_),
1582 new (global_allocator_) HShr(type, opa, opb));
1583 case HInstruction::kUShr:
1584 GENERATE_VEC(
1585 new (global_allocator_) HVecUShr(global_allocator_, opa, opb, type, vector_length_),
1586 new (global_allocator_) HUShr(type, opa, opb));
1587 case HInstruction::kInvokeStaticOrDirect: {
Aart Bik6daebeb2017-04-03 14:35:41 -07001588 HInvokeStaticOrDirect* invoke = org->AsInvokeStaticOrDirect();
1589 if (vector_mode_ == kVector) {
1590 switch (invoke->GetIntrinsic()) {
1591 case Intrinsics::kMathAbsInt:
1592 case Intrinsics::kMathAbsLong:
1593 case Intrinsics::kMathAbsFloat:
1594 case Intrinsics::kMathAbsDouble:
1595 DCHECK(opb == nullptr);
1596 vector = new (global_allocator_) HVecAbs(global_allocator_, opa, type, vector_length_);
1597 break;
Aart Bikc8e93c72017-05-10 10:49:22 -07001598 case Intrinsics::kMathMinIntInt:
1599 case Intrinsics::kMathMinLongLong:
1600 case Intrinsics::kMathMinFloatFloat:
1601 case Intrinsics::kMathMinDoubleDouble: {
Aart Bikc8e93c72017-05-10 10:49:22 -07001602 vector = new (global_allocator_)
1603 HVecMin(global_allocator_, opa, opb, type, vector_length_, is_unsigned);
1604 break;
1605 }
1606 case Intrinsics::kMathMaxIntInt:
1607 case Intrinsics::kMathMaxLongLong:
1608 case Intrinsics::kMathMaxFloatFloat:
1609 case Intrinsics::kMathMaxDoubleDouble: {
Aart Bikc8e93c72017-05-10 10:49:22 -07001610 vector = new (global_allocator_)
1611 HVecMax(global_allocator_, opa, opb, type, vector_length_, is_unsigned);
1612 break;
1613 }
Aart Bik6daebeb2017-04-03 14:35:41 -07001614 default:
1615 LOG(FATAL) << "Unsupported SIMD intrinsic";
1616 UNREACHABLE();
1617 } // switch invoke
1618 } else {
Aart Bik24b905f2017-04-06 09:59:06 -07001619 // In scalar code, simply clone the method invoke, and replace its operands with the
1620 // corresponding new scalar instructions in the loop. The instruction will get an
1621 // environment while being inserted from the instruction map in original program order.
Aart Bik6daebeb2017-04-03 14:35:41 -07001622 DCHECK(vector_mode_ == kSequential);
Aart Bik6e92fb32017-06-05 14:05:09 -07001623 size_t num_args = invoke->GetNumberOfArguments();
Aart Bik6daebeb2017-04-03 14:35:41 -07001624 HInvokeStaticOrDirect* new_invoke = new (global_allocator_) HInvokeStaticOrDirect(
1625 global_allocator_,
Aart Bik6e92fb32017-06-05 14:05:09 -07001626 num_args,
Aart Bik6daebeb2017-04-03 14:35:41 -07001627 invoke->GetType(),
1628 invoke->GetDexPc(),
1629 invoke->GetDexMethodIndex(),
1630 invoke->GetResolvedMethod(),
1631 invoke->GetDispatchInfo(),
1632 invoke->GetInvokeType(),
1633 invoke->GetTargetMethod(),
1634 invoke->GetClinitCheckRequirement());
1635 HInputsRef inputs = invoke->GetInputs();
Aart Bik6e92fb32017-06-05 14:05:09 -07001636 size_t num_inputs = inputs.size();
1637 DCHECK_LE(num_args, num_inputs);
1638 DCHECK_EQ(num_inputs, new_invoke->GetInputs().size()); // both invokes agree
1639 for (size_t index = 0; index < num_inputs; ++index) {
1640 HInstruction* new_input = index < num_args
1641 ? vector_map_->Get(inputs[index])
1642 : inputs[index]; // beyond arguments: just pass through
1643 new_invoke->SetArgumentAt(index, new_input);
Aart Bik6daebeb2017-04-03 14:35:41 -07001644 }
Aart Bik98990262017-04-10 13:15:57 -07001645 new_invoke->SetIntrinsic(invoke->GetIntrinsic(),
1646 kNeedsEnvironmentOrCache,
1647 kNoSideEffects,
1648 kNoThrow);
Aart Bik6daebeb2017-04-03 14:35:41 -07001649 vector = new_invoke;
1650 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001651 break;
1652 }
1653 default:
1654 break;
1655 } // switch
1656 CHECK(vector != nullptr) << "Unsupported SIMD operator";
1657 vector_map_->Put(org, vector);
1658}
1659
1660#undef GENERATE_VEC
1661
1662//
Aart Bikf3e61ee2017-04-12 17:09:20 -07001663// Vectorization idioms.
1664//
1665
1666// Method recognizes the following idioms:
1667// rounding halving add (a + b + 1) >> 1 for unsigned/signed operands a, b
1668// regular halving add (a + b) >> 1 for unsigned/signed operands a, b
1669// Provided that the operands are promoted to a wider form to do the arithmetic and
1670// then cast back to narrower form, the idioms can be mapped into efficient SIMD
1671// implementation that operates directly in narrower form (plus one extra bit).
1672// TODO: current version recognizes implicit byte/short/char widening only;
1673// explicit widening from int to long could be added later.
1674bool HLoopOptimization::VectorizeHalvingAddIdiom(LoopNode* node,
1675 HInstruction* instruction,
1676 bool generate_code,
1677 Primitive::Type type,
1678 uint64_t restrictions) {
1679 // Test for top level arithmetic shift right x >> 1 or logical shift right x >>> 1
Aart Bik304c8a52017-05-23 11:01:13 -07001680 // (note whether the sign bit in wider precision is shifted in has no effect
Aart Bikf3e61ee2017-04-12 17:09:20 -07001681 // on the narrow precision computed by the idiom).
Aart Bikf3e61ee2017-04-12 17:09:20 -07001682 if ((instruction->IsShr() ||
1683 instruction->IsUShr()) &&
Aart Bik0148de42017-09-05 09:25:01 -07001684 IsInt64Value(instruction->InputAt(1), 1)) {
Aart Bik5f805002017-05-16 16:42:41 -07001685 // Test for (a + b + c) >> 1 for optional constant c.
1686 HInstruction* a = nullptr;
1687 HInstruction* b = nullptr;
1688 int64_t c = 0;
1689 if (IsAddConst(instruction->InputAt(0), /*out*/ &a, /*out*/ &b, /*out*/ &c)) {
Aart Bik304c8a52017-05-23 11:01:13 -07001690 DCHECK(a != nullptr && b != nullptr);
Aart Bik5f805002017-05-16 16:42:41 -07001691 // Accept c == 1 (rounded) or c == 0 (not rounded).
1692 bool is_rounded = false;
1693 if (c == 1) {
1694 is_rounded = true;
1695 } else if (c != 0) {
1696 return false;
1697 }
1698 // Accept consistent zero or sign extension on operands a and b.
Aart Bikf3e61ee2017-04-12 17:09:20 -07001699 HInstruction* r = nullptr;
1700 HInstruction* s = nullptr;
1701 bool is_unsigned = false;
Aart Bik304c8a52017-05-23 11:01:13 -07001702 if (!IsNarrowerOperands(a, b, type, &r, &s, &is_unsigned)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -07001703 return false;
1704 }
1705 // Deal with vector restrictions.
1706 if ((!is_unsigned && HasVectorRestrictions(restrictions, kNoSignedHAdd)) ||
1707 (!is_rounded && HasVectorRestrictions(restrictions, kNoUnroundedHAdd))) {
1708 return false;
1709 }
1710 // Accept recognized halving add for vectorizable operands. Vectorized code uses the
1711 // shorthand idiomatic operation. Sequential code uses the original scalar expressions.
1712 DCHECK(r != nullptr && s != nullptr);
Aart Bik304c8a52017-05-23 11:01:13 -07001713 if (generate_code && vector_mode_ != kVector) { // de-idiom
1714 r = instruction->InputAt(0);
1715 s = instruction->InputAt(1);
1716 }
Aart Bikf3e61ee2017-04-12 17:09:20 -07001717 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
1718 VectorizeUse(node, s, generate_code, type, restrictions)) {
1719 if (generate_code) {
1720 if (vector_mode_ == kVector) {
1721 vector_map_->Put(instruction, new (global_allocator_) HVecHalvingAdd(
1722 global_allocator_,
1723 vector_map_->Get(r),
1724 vector_map_->Get(s),
1725 type,
1726 vector_length_,
1727 is_unsigned,
1728 is_rounded));
Aart Bik21b85922017-09-06 13:29:16 -07001729 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorizedIdiom);
Aart Bikf3e61ee2017-04-12 17:09:20 -07001730 } else {
Aart Bik304c8a52017-05-23 11:01:13 -07001731 GenerateVecOp(instruction, vector_map_->Get(r), vector_map_->Get(s), type);
Aart Bikf3e61ee2017-04-12 17:09:20 -07001732 }
1733 }
1734 return true;
1735 }
1736 }
1737 }
1738 return false;
1739}
1740
1741//
Aart Bik14a68b42017-06-08 14:06:58 -07001742// Vectorization heuristics.
1743//
1744
1745bool HLoopOptimization::IsVectorizationProfitable(int64_t trip_count) {
1746 // Current heuristic: non-empty body with sufficient number
1747 // of iterations (if known).
1748 // TODO: refine by looking at e.g. operation count, alignment, etc.
1749 if (vector_length_ == 0) {
1750 return false; // nothing found
1751 } else if (0 < trip_count && trip_count < vector_length_) {
1752 return false; // insufficient iterations
1753 }
1754 return true;
1755}
1756
Aart Bikb29f6842017-07-28 15:58:41 -07001757void HLoopOptimization::SetPeelingCandidate(const ArrayReference* candidate,
1758 int64_t trip_count ATTRIBUTE_UNUSED) {
Aart Bik14a68b42017-06-08 14:06:58 -07001759 // Current heuristic: none.
1760 // TODO: implement
Aart Bikb29f6842017-07-28 15:58:41 -07001761 vector_peeling_candidate_ = candidate;
Aart Bik14a68b42017-06-08 14:06:58 -07001762}
1763
1764uint32_t HLoopOptimization::GetUnrollingFactor(HBasicBlock* block, int64_t trip_count) {
1765 // Current heuristic: unroll by 2 on ARM64/X86 for large known trip
1766 // counts and small loop bodies.
1767 // TODO: refine with operation count, remaining iterations, etc.
1768 // Artem had some really cool ideas for this already.
1769 switch (compiler_driver_->GetInstructionSet()) {
1770 case kArm64:
1771 case kX86:
1772 case kX86_64: {
1773 size_t num_instructions = block->GetInstructions().CountSize();
1774 if (num_instructions <= 10 && trip_count >= 4 * vector_length_) {
1775 return 2;
1776 }
1777 return 1;
1778 }
1779 default:
1780 return 1;
1781 }
1782}
1783
1784//
Aart Bikf8f5a162017-02-06 15:35:29 -08001785// Helpers.
1786//
1787
1788bool HLoopOptimization::TrySetPhiInduction(HPhi* phi, bool restrict_uses) {
Aart Bikb29f6842017-07-28 15:58:41 -07001789 // Start with empty phi induction.
1790 iset_->clear();
1791
Nicolas Geoffrayf57c1ae2017-06-28 17:40:18 +01001792 // Special case Phis that have equivalent in a debuggable setup. Our graph checker isn't
1793 // smart enough to follow strongly connected components (and it's probably not worth
1794 // it to make it so). See b/33775412.
1795 if (graph_->IsDebuggable() && phi->HasEquivalentPhi()) {
1796 return false;
1797 }
Aart Bikb29f6842017-07-28 15:58:41 -07001798
1799 // Lookup phi induction cycle.
Aart Bikcc42be02016-10-20 16:14:16 -07001800 ArenaSet<HInstruction*>* set = induction_range_.LookupCycle(phi);
1801 if (set != nullptr) {
1802 for (HInstruction* i : *set) {
Aart Bike3dedc52016-11-02 17:50:27 -07001803 // Check that, other than instructions that are no longer in the graph (removed earlier)
Aart Bikf8f5a162017-02-06 15:35:29 -08001804 // each instruction is removable and, when restrict uses are requested, other than for phi,
1805 // all uses are contained within the cycle.
Aart Bike3dedc52016-11-02 17:50:27 -07001806 if (!i->IsInBlock()) {
1807 continue;
1808 } else if (!i->IsRemovable()) {
1809 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001810 } else if (i != phi && restrict_uses) {
Aart Bikb29f6842017-07-28 15:58:41 -07001811 // Deal with regular uses.
Aart Bikcc42be02016-10-20 16:14:16 -07001812 for (const HUseListNode<HInstruction*>& use : i->GetUses()) {
1813 if (set->find(use.GetUser()) == set->end()) {
1814 return false;
1815 }
1816 }
1817 }
Aart Bike3dedc52016-11-02 17:50:27 -07001818 iset_->insert(i); // copy
Aart Bikcc42be02016-10-20 16:14:16 -07001819 }
Aart Bikcc42be02016-10-20 16:14:16 -07001820 return true;
1821 }
1822 return false;
1823}
1824
Aart Bikb29f6842017-07-28 15:58:41 -07001825bool HLoopOptimization::TrySetPhiReduction(HPhi* phi) {
Aart Bikcc42be02016-10-20 16:14:16 -07001826 DCHECK(iset_->empty());
Aart Bikb29f6842017-07-28 15:58:41 -07001827 // Only unclassified phi cycles are candidates for reductions.
1828 if (induction_range_.IsClassified(phi)) {
1829 return false;
1830 }
1831 // Accept operations like x = x + .., provided that the phi and the reduction are
1832 // used exactly once inside the loop, and by each other.
1833 HInputsRef inputs = phi->GetInputs();
1834 if (inputs.size() == 2) {
1835 HInstruction* reduction = inputs[1];
1836 if (HasReductionFormat(reduction, phi)) {
1837 HLoopInformation* loop_info = phi->GetBlock()->GetLoopInformation();
1838 int32_t use_count = 0;
1839 bool single_use_inside_loop =
1840 // Reduction update only used by phi.
1841 reduction->GetUses().HasExactlyOneElement() &&
1842 !reduction->HasEnvironmentUses() &&
1843 // Reduction update is only use of phi inside the loop.
1844 IsOnlyUsedAfterLoop(loop_info, phi, /*collect_loop_uses*/ true, &use_count) &&
1845 iset_->size() == 1;
1846 iset_->clear(); // leave the way you found it
1847 if (single_use_inside_loop) {
1848 // Link reduction back, and start recording feed value.
1849 reductions_->Put(reduction, phi);
1850 reductions_->Put(phi, phi->InputAt(0));
1851 return true;
1852 }
1853 }
1854 }
1855 return false;
1856}
1857
1858bool HLoopOptimization::TrySetSimpleLoopHeader(HBasicBlock* block, /*out*/ HPhi** main_phi) {
1859 // Start with empty phi induction and reductions.
1860 iset_->clear();
1861 reductions_->clear();
1862
1863 // Scan the phis to find the following (the induction structure has already
1864 // been optimized, so we don't need to worry about trivial cases):
1865 // (1) optional reductions in loop,
1866 // (2) the main induction, used in loop control.
1867 HPhi* phi = nullptr;
1868 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
1869 if (TrySetPhiReduction(it.Current()->AsPhi())) {
1870 continue;
1871 } else if (phi == nullptr) {
1872 // Found the first candidate for main induction.
1873 phi = it.Current()->AsPhi();
1874 } else {
1875 return false;
1876 }
1877 }
1878
1879 // Then test for a typical loopheader:
1880 // s: SuspendCheck
1881 // c: Condition(phi, bound)
1882 // i: If(c)
1883 if (phi != nullptr && TrySetPhiInduction(phi, /*restrict_uses*/ false)) {
Aart Bikcc42be02016-10-20 16:14:16 -07001884 HInstruction* s = block->GetFirstInstruction();
1885 if (s != nullptr && s->IsSuspendCheck()) {
1886 HInstruction* c = s->GetNext();
Aart Bikd86c0852017-04-14 12:00:15 -07001887 if (c != nullptr &&
1888 c->IsCondition() &&
1889 c->GetUses().HasExactlyOneElement() && // only used for termination
1890 !c->HasEnvironmentUses()) { // unlikely, but not impossible
Aart Bikcc42be02016-10-20 16:14:16 -07001891 HInstruction* i = c->GetNext();
1892 if (i != nullptr && i->IsIf() && i->InputAt(0) == c) {
1893 iset_->insert(c);
1894 iset_->insert(s);
Aart Bikb29f6842017-07-28 15:58:41 -07001895 *main_phi = phi;
Aart Bikcc42be02016-10-20 16:14:16 -07001896 return true;
1897 }
1898 }
1899 }
1900 }
1901 return false;
1902}
1903
1904bool HLoopOptimization::IsEmptyBody(HBasicBlock* block) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001905 if (!block->GetPhis().IsEmpty()) {
1906 return false;
1907 }
1908 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
1909 HInstruction* instruction = it.Current();
1910 if (!instruction->IsGoto() && iset_->find(instruction) == iset_->end()) {
1911 return false;
Aart Bikcc42be02016-10-20 16:14:16 -07001912 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001913 }
1914 return true;
1915}
1916
1917bool HLoopOptimization::IsUsedOutsideLoop(HLoopInformation* loop_info,
1918 HInstruction* instruction) {
Aart Bikb29f6842017-07-28 15:58:41 -07001919 // Deal with regular uses.
Aart Bikf8f5a162017-02-06 15:35:29 -08001920 for (const HUseListNode<HInstruction*>& use : instruction->GetUses()) {
1921 if (use.GetUser()->GetBlock()->GetLoopInformation() != loop_info) {
1922 return true;
1923 }
Aart Bikcc42be02016-10-20 16:14:16 -07001924 }
1925 return false;
1926}
1927
Aart Bik482095d2016-10-10 15:39:10 -07001928bool HLoopOptimization::IsOnlyUsedAfterLoop(HLoopInformation* loop_info,
Aart Bik8c4a8542016-10-06 11:36:57 -07001929 HInstruction* instruction,
Aart Bik6b69e0a2017-01-11 10:20:43 -08001930 bool collect_loop_uses,
Aart Bik8c4a8542016-10-06 11:36:57 -07001931 /*out*/ int32_t* use_count) {
Aart Bikb29f6842017-07-28 15:58:41 -07001932 // Deal with regular uses.
Aart Bik8c4a8542016-10-06 11:36:57 -07001933 for (const HUseListNode<HInstruction*>& use : instruction->GetUses()) {
1934 HInstruction* user = use.GetUser();
1935 if (iset_->find(user) == iset_->end()) { // not excluded?
1936 HLoopInformation* other_loop_info = user->GetBlock()->GetLoopInformation();
Aart Bik482095d2016-10-10 15:39:10 -07001937 if (other_loop_info != nullptr && other_loop_info->IsIn(*loop_info)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -08001938 // If collect_loop_uses is set, simply keep adding those uses to the set.
1939 // Otherwise, reject uses inside the loop that were not already in the set.
1940 if (collect_loop_uses) {
1941 iset_->insert(user);
1942 continue;
1943 }
Aart Bik8c4a8542016-10-06 11:36:57 -07001944 return false;
1945 }
1946 ++*use_count;
1947 }
1948 }
1949 return true;
1950}
1951
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01001952bool HLoopOptimization::TryReplaceWithLastValue(HLoopInformation* loop_info,
1953 HInstruction* instruction,
1954 HBasicBlock* block) {
1955 // Try to replace outside uses with the last value.
Aart Bik807868e2016-11-03 17:51:43 -07001956 if (induction_range_.CanGenerateLastValue(instruction)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -08001957 HInstruction* replacement = induction_range_.GenerateLastValue(instruction, graph_, block);
Aart Bikb29f6842017-07-28 15:58:41 -07001958 // Deal with regular uses.
Aart Bik6b69e0a2017-01-11 10:20:43 -08001959 const HUseList<HInstruction*>& uses = instruction->GetUses();
1960 for (auto it = uses.begin(), end = uses.end(); it != end;) {
1961 HInstruction* user = it->GetUser();
1962 size_t index = it->GetIndex();
1963 ++it; // increment before replacing
1964 if (iset_->find(user) == iset_->end()) { // not excluded?
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01001965 if (kIsDebugBuild) {
1966 // We have checked earlier in 'IsOnlyUsedAfterLoop' that the use is after the loop.
1967 HLoopInformation* other_loop_info = user->GetBlock()->GetLoopInformation();
1968 CHECK(other_loop_info == nullptr || !other_loop_info->IsIn(*loop_info));
1969 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08001970 user->ReplaceInput(replacement, index);
1971 induction_range_.Replace(user, instruction, replacement); // update induction
1972 }
1973 }
Aart Bikb29f6842017-07-28 15:58:41 -07001974 // Deal with environment uses.
Aart Bik6b69e0a2017-01-11 10:20:43 -08001975 const HUseList<HEnvironment*>& env_uses = instruction->GetEnvUses();
1976 for (auto it = env_uses.begin(), end = env_uses.end(); it != end;) {
1977 HEnvironment* user = it->GetUser();
1978 size_t index = it->GetIndex();
1979 ++it; // increment before replacing
1980 if (iset_->find(user->GetHolder()) == iset_->end()) { // not excluded?
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01001981 // Only update environment uses after the loop.
Aart Bik14a68b42017-06-08 14:06:58 -07001982 HLoopInformation* other_loop_info = user->GetHolder()->GetBlock()->GetLoopInformation();
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01001983 if (other_loop_info == nullptr || !other_loop_info->IsIn(*loop_info)) {
1984 user->RemoveAsUserOfInput(index);
1985 user->SetRawEnvAt(index, replacement);
1986 replacement->AddEnvUseAt(user, index);
1987 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08001988 }
1989 }
Aart Bik807868e2016-11-03 17:51:43 -07001990 return true;
Aart Bik8c4a8542016-10-06 11:36:57 -07001991 }
Aart Bik807868e2016-11-03 17:51:43 -07001992 return false;
Aart Bik8c4a8542016-10-06 11:36:57 -07001993}
1994
Aart Bikf8f5a162017-02-06 15:35:29 -08001995bool HLoopOptimization::TryAssignLastValue(HLoopInformation* loop_info,
1996 HInstruction* instruction,
1997 HBasicBlock* block,
1998 bool collect_loop_uses) {
1999 // Assigning the last value is always successful if there are no uses.
2000 // Otherwise, it succeeds in a no early-exit loop by generating the
2001 // proper last value assignment.
2002 int32_t use_count = 0;
2003 return IsOnlyUsedAfterLoop(loop_info, instruction, collect_loop_uses, &use_count) &&
2004 (use_count == 0 ||
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002005 (!IsEarlyExit(loop_info) && TryReplaceWithLastValue(loop_info, instruction, block)));
Aart Bikf8f5a162017-02-06 15:35:29 -08002006}
2007
Aart Bik6b69e0a2017-01-11 10:20:43 -08002008void HLoopOptimization::RemoveDeadInstructions(const HInstructionList& list) {
2009 for (HBackwardInstructionIterator i(list); !i.Done(); i.Advance()) {
2010 HInstruction* instruction = i.Current();
2011 if (instruction->IsDeadAndRemovable()) {
2012 simplified_ = true;
2013 instruction->GetBlock()->RemoveInstructionOrPhi(instruction);
2014 }
2015 }
2016}
2017
Aart Bik14a68b42017-06-08 14:06:58 -07002018bool HLoopOptimization::CanRemoveCycle() {
2019 for (HInstruction* i : *iset_) {
2020 // We can never remove instructions that have environment
2021 // uses when we compile 'debuggable'.
2022 if (i->HasEnvironmentUses() && graph_->IsDebuggable()) {
2023 return false;
2024 }
2025 // A deoptimization should never have an environment input removed.
2026 for (const HUseListNode<HEnvironment*>& use : i->GetEnvUses()) {
2027 if (use.GetUser()->GetHolder()->IsDeoptimize()) {
2028 return false;
2029 }
2030 }
2031 }
2032 return true;
2033}
2034
Aart Bik281c6812016-08-26 11:31:48 -07002035} // namespace art