blob: d2493137fe29afca96eb4358354bfca2fa38bbe2 [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/instruction_set.h"
20#include "arch/arm/instruction_set_features_arm.h"
21#include "arch/arm64/instruction_set_features_arm64.h"
22#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 Bik9abf8942016-10-14 09:49:42 -070034// Remove the instruction from the graph. A bit more elaborate than the usual
35// instruction removal, since there may be a cycle in the use structure.
Aart Bik281c6812016-08-26 11:31:48 -070036static void RemoveFromCycle(HInstruction* instruction) {
Aart Bik281c6812016-08-26 11:31:48 -070037 instruction->RemoveAsUserOfAllInputs();
38 instruction->RemoveEnvironmentUsers();
39 instruction->GetBlock()->RemoveInstructionOrPhi(instruction, /*ensure_safety=*/ false);
40}
41
Aart Bik807868e2016-11-03 17:51:43 -070042// Detect a goto block and sets succ to the single successor.
Aart Bike3dedc52016-11-02 17:50:27 -070043static bool IsGotoBlock(HBasicBlock* block, /*out*/ HBasicBlock** succ) {
44 if (block->GetPredecessors().size() == 1 &&
45 block->GetSuccessors().size() == 1 &&
46 block->IsSingleGoto()) {
47 *succ = block->GetSingleSuccessor();
48 return true;
49 }
50 return false;
51}
52
Aart Bik807868e2016-11-03 17:51:43 -070053// Detect an early exit loop.
54static bool IsEarlyExit(HLoopInformation* loop_info) {
55 HBlocksInLoopReversePostOrderIterator it_loop(*loop_info);
56 for (it_loop.Advance(); !it_loop.Done(); it_loop.Advance()) {
57 for (HBasicBlock* successor : it_loop.Current()->GetSuccessors()) {
58 if (!loop_info->Contains(*successor)) {
59 return true;
60 }
61 }
62 }
63 return false;
64}
65
Aart Bikf3e61ee2017-04-12 17:09:20 -070066// Detect a sign extension from the given type. Returns the promoted operand on success.
67static bool IsSignExtensionAndGet(HInstruction* instruction,
68 Primitive::Type type,
69 /*out*/ HInstruction** operand) {
70 // Accept any already wider constant that would be handled properly by sign
71 // extension when represented in the *width* of the given narrower data type
72 // (the fact that char normally zero extends does not matter here).
73 int64_t value = 0;
Aart Bik50e20d52017-05-05 14:07:29 -070074 if (IsInt64AndGet(instruction, /*out*/ &value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -070075 switch (type) {
76 case Primitive::kPrimByte:
77 if (std::numeric_limits<int8_t>::min() <= value &&
78 std::numeric_limits<int8_t>::max() >= value) {
79 *operand = instruction;
80 return true;
81 }
82 return false;
83 case Primitive::kPrimChar:
84 case Primitive::kPrimShort:
85 if (std::numeric_limits<int16_t>::min() <= value &&
86 std::numeric_limits<int16_t>::max() <= value) {
87 *operand = instruction;
88 return true;
89 }
90 return false;
91 default:
92 return false;
93 }
94 }
95 // An implicit widening conversion of a signed integer to an integral type sign-extends
96 // the two's-complement representation of the integer value to fill the wider format.
97 if (instruction->GetType() == type && (instruction->IsArrayGet() ||
98 instruction->IsStaticFieldGet() ||
99 instruction->IsInstanceFieldGet())) {
100 switch (type) {
101 case Primitive::kPrimByte:
102 case Primitive::kPrimShort:
103 *operand = instruction;
104 return true;
105 default:
106 return false;
107 }
108 }
109 // TODO: perhaps explicit conversions later too?
110 // (this may return something different from instruction)
111 return false;
112}
113
114// Detect a zero extension from the given type. Returns the promoted operand on success.
115static bool IsZeroExtensionAndGet(HInstruction* instruction,
116 Primitive::Type type,
117 /*out*/ HInstruction** operand) {
118 // Accept any already wider constant that would be handled properly by zero
119 // extension when represented in the *width* of the given narrower data type
120 // (the fact that byte/short normally sign extend does not matter here).
121 int64_t value = 0;
Aart Bik50e20d52017-05-05 14:07:29 -0700122 if (IsInt64AndGet(instruction, /*out*/ &value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700123 switch (type) {
124 case Primitive::kPrimByte:
125 if (std::numeric_limits<uint8_t>::min() <= value &&
126 std::numeric_limits<uint8_t>::max() >= value) {
127 *operand = instruction;
128 return true;
129 }
130 return false;
131 case Primitive::kPrimChar:
132 case Primitive::kPrimShort:
133 if (std::numeric_limits<uint16_t>::min() <= value &&
134 std::numeric_limits<uint16_t>::max() <= value) {
135 *operand = instruction;
136 return true;
137 }
138 return false;
139 default:
140 return false;
141 }
142 }
143 // An implicit widening conversion of a char to an integral type zero-extends
144 // the representation of the char value to fill the wider format.
145 if (instruction->GetType() == type && (instruction->IsArrayGet() ||
146 instruction->IsStaticFieldGet() ||
147 instruction->IsInstanceFieldGet())) {
148 if (type == Primitive::kPrimChar) {
149 *operand = instruction;
150 return true;
151 }
152 }
153 // A sign (or zero) extension followed by an explicit removal of just the
154 // higher sign bits is equivalent to a zero extension of the underlying operand.
155 if (instruction->IsAnd()) {
156 int64_t mask = 0;
157 HInstruction* a = instruction->InputAt(0);
158 HInstruction* b = instruction->InputAt(1);
159 // In (a & b) find (mask & b) or (a & mask) with sign or zero extension on the non-mask.
160 if ((IsInt64AndGet(a, /*out*/ &mask) && (IsSignExtensionAndGet(b, type, /*out*/ operand) ||
161 IsZeroExtensionAndGet(b, type, /*out*/ operand))) ||
162 (IsInt64AndGet(b, /*out*/ &mask) && (IsSignExtensionAndGet(a, type, /*out*/ operand) ||
163 IsZeroExtensionAndGet(a, type, /*out*/ operand)))) {
164 switch ((*operand)->GetType()) {
165 case Primitive::kPrimByte: return mask == std::numeric_limits<uint8_t>::max();
166 case Primitive::kPrimChar:
167 case Primitive::kPrimShort: return mask == std::numeric_limits<uint16_t>::max();
168 default: return false;
169 }
170 }
171 }
172 // TODO: perhaps explicit conversions later too?
173 return false;
174}
175
Aart Bik304c8a52017-05-23 11:01:13 -0700176// Detect situations with same-extension narrower operands.
177// Returns true on success and sets is_unsigned accordingly.
178static bool IsNarrowerOperands(HInstruction* a,
179 HInstruction* b,
180 Primitive::Type type,
181 /*out*/ HInstruction** r,
182 /*out*/ HInstruction** s,
183 /*out*/ bool* is_unsigned) {
184 if (IsSignExtensionAndGet(a, type, r) && IsSignExtensionAndGet(b, type, s)) {
185 *is_unsigned = false;
186 return true;
187 } else if (IsZeroExtensionAndGet(a, type, r) && IsZeroExtensionAndGet(b, type, s)) {
188 *is_unsigned = true;
189 return true;
190 }
191 return false;
192}
193
194// As above, single operand.
195static bool IsNarrowerOperand(HInstruction* a,
196 Primitive::Type type,
197 /*out*/ HInstruction** r,
198 /*out*/ bool* is_unsigned) {
199 if (IsSignExtensionAndGet(a, type, r)) {
200 *is_unsigned = false;
201 return true;
202 } else if (IsZeroExtensionAndGet(a, type, r)) {
203 *is_unsigned = true;
204 return true;
205 }
206 return false;
207}
208
Aart Bik5f805002017-05-16 16:42:41 -0700209// Detect up to two instructions a and b, and an acccumulated constant c.
210static bool IsAddConstHelper(HInstruction* instruction,
211 /*out*/ HInstruction** a,
212 /*out*/ HInstruction** b,
213 /*out*/ int64_t* c,
214 int32_t depth) {
215 static constexpr int32_t kMaxDepth = 8; // don't search too deep
216 int64_t value = 0;
217 if (IsInt64AndGet(instruction, &value)) {
218 *c += value;
219 return true;
220 } else if (instruction->IsAdd() && depth <= kMaxDepth) {
221 return IsAddConstHelper(instruction->InputAt(0), a, b, c, depth + 1) &&
222 IsAddConstHelper(instruction->InputAt(1), a, b, c, depth + 1);
223 } else if (*a == nullptr) {
224 *a = instruction;
225 return true;
226 } else if (*b == nullptr) {
227 *b = instruction;
228 return true;
229 }
230 return false; // too many non-const operands
231}
232
233// Detect a + b + c for an optional constant c.
234static bool IsAddConst(HInstruction* instruction,
235 /*out*/ HInstruction** a,
236 /*out*/ HInstruction** b,
237 /*out*/ int64_t* c) {
238 if (instruction->IsAdd()) {
239 // Try to find a + b and accumulated c.
240 if (IsAddConstHelper(instruction->InputAt(0), a, b, c, /*depth*/ 0) &&
241 IsAddConstHelper(instruction->InputAt(1), a, b, c, /*depth*/ 0) &&
242 *b != nullptr) {
243 return true;
244 }
245 // Found a + b.
246 *a = instruction->InputAt(0);
247 *b = instruction->InputAt(1);
248 *c = 0;
249 return true;
250 }
251 return false;
252}
253
Aart Bikf8f5a162017-02-06 15:35:29 -0800254// Test vector restrictions.
255static bool HasVectorRestrictions(uint64_t restrictions, uint64_t tested) {
256 return (restrictions & tested) != 0;
257}
258
Aart Bikf3e61ee2017-04-12 17:09:20 -0700259// Insert an instruction.
Aart Bikf8f5a162017-02-06 15:35:29 -0800260static HInstruction* Insert(HBasicBlock* block, HInstruction* instruction) {
261 DCHECK(block != nullptr);
262 DCHECK(instruction != nullptr);
263 block->InsertInstructionBefore(instruction, block->GetLastInstruction());
264 return instruction;
265}
266
Aart Bik281c6812016-08-26 11:31:48 -0700267//
268// Class methods.
269//
270
271HLoopOptimization::HLoopOptimization(HGraph* graph,
Aart Bik92685a82017-03-06 11:13:43 -0800272 CompilerDriver* compiler_driver,
Aart Bik281c6812016-08-26 11:31:48 -0700273 HInductionVarAnalysis* induction_analysis)
274 : HOptimization(graph, kLoopOptimizationPassName),
Aart Bik92685a82017-03-06 11:13:43 -0800275 compiler_driver_(compiler_driver),
Aart Bik281c6812016-08-26 11:31:48 -0700276 induction_range_(induction_analysis),
Aart Bik96202302016-10-04 17:33:56 -0700277 loop_allocator_(nullptr),
Aart Bikf8f5a162017-02-06 15:35:29 -0800278 global_allocator_(graph_->GetArena()),
Aart Bik281c6812016-08-26 11:31:48 -0700279 top_loop_(nullptr),
Aart Bik8c4a8542016-10-06 11:36:57 -0700280 last_loop_(nullptr),
Aart Bik482095d2016-10-10 15:39:10 -0700281 iset_(nullptr),
Aart Bikdf7822e2016-12-06 10:05:30 -0800282 induction_simplication_count_(0),
Aart Bikf8f5a162017-02-06 15:35:29 -0800283 simplified_(false),
284 vector_length_(0),
285 vector_refs_(nullptr),
286 vector_map_(nullptr) {
Aart Bik281c6812016-08-26 11:31:48 -0700287}
288
289void HLoopOptimization::Run() {
Mingyao Yang01b47b02017-02-03 12:09:57 -0800290 // Skip if there is no loop or the graph has try-catch/irreducible loops.
Aart Bik281c6812016-08-26 11:31:48 -0700291 // TODO: make this less of a sledgehammer.
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800292 if (!graph_->HasLoops() || graph_->HasTryCatch() || graph_->HasIrreducibleLoops()) {
Aart Bik281c6812016-08-26 11:31:48 -0700293 return;
294 }
295
Aart Bik96202302016-10-04 17:33:56 -0700296 // Phase-local allocator that draws from the global pool. Since the allocator
297 // itself resides on the stack, it is destructed on exiting Run(), which
298 // implies its underlying memory is released immediately.
Aart Bikf8f5a162017-02-06 15:35:29 -0800299 ArenaAllocator allocator(global_allocator_->GetArenaPool());
Aart Bik96202302016-10-04 17:33:56 -0700300 loop_allocator_ = &allocator;
Nicolas Geoffrayebe16742016-10-05 09:55:42 +0100301
Aart Bik96202302016-10-04 17:33:56 -0700302 // Perform loop optimizations.
303 LocalRun();
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800304 if (top_loop_ == nullptr) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800305 graph_->SetHasLoops(false); // no more loops
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800306 }
307
Aart Bik96202302016-10-04 17:33:56 -0700308 // Detach.
309 loop_allocator_ = nullptr;
310 last_loop_ = top_loop_ = nullptr;
311}
312
313void HLoopOptimization::LocalRun() {
314 // Build the linear order using the phase-local allocator. This step enables building
315 // a loop hierarchy that properly reflects the outer-inner and previous-next relation.
316 ArenaVector<HBasicBlock*> linear_order(loop_allocator_->Adapter(kArenaAllocLinearOrder));
317 LinearizeGraph(graph_, loop_allocator_, &linear_order);
318
Aart Bik281c6812016-08-26 11:31:48 -0700319 // Build the loop hierarchy.
Aart Bik96202302016-10-04 17:33:56 -0700320 for (HBasicBlock* block : linear_order) {
Aart Bik281c6812016-08-26 11:31:48 -0700321 if (block->IsLoopHeader()) {
322 AddLoop(block->GetLoopInformation());
323 }
324 }
Aart Bik96202302016-10-04 17:33:56 -0700325
Aart Bik8c4a8542016-10-06 11:36:57 -0700326 // Traverse the loop hierarchy inner-to-outer and optimize. Traversal can use
Aart Bikf8f5a162017-02-06 15:35:29 -0800327 // temporary data structures using the phase-local allocator. All new HIR
328 // should use the global allocator.
Aart Bik8c4a8542016-10-06 11:36:57 -0700329 if (top_loop_ != nullptr) {
330 ArenaSet<HInstruction*> iset(loop_allocator_->Adapter(kArenaAllocLoopOptimization));
Aart Bikf8f5a162017-02-06 15:35:29 -0800331 ArenaSet<ArrayReference> refs(loop_allocator_->Adapter(kArenaAllocLoopOptimization));
332 ArenaSafeMap<HInstruction*, HInstruction*> map(
333 std::less<HInstruction*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
334 // Attach.
Aart Bik8c4a8542016-10-06 11:36:57 -0700335 iset_ = &iset;
Aart Bikf8f5a162017-02-06 15:35:29 -0800336 vector_refs_ = &refs;
337 vector_map_ = &map;
338 // Traverse.
Aart Bik8c4a8542016-10-06 11:36:57 -0700339 TraverseLoopsInnerToOuter(top_loop_);
Aart Bikf8f5a162017-02-06 15:35:29 -0800340 // Detach.
341 iset_ = nullptr;
342 vector_refs_ = nullptr;
343 vector_map_ = nullptr;
Aart Bik8c4a8542016-10-06 11:36:57 -0700344 }
Aart Bik281c6812016-08-26 11:31:48 -0700345}
346
347void HLoopOptimization::AddLoop(HLoopInformation* loop_info) {
348 DCHECK(loop_info != nullptr);
Aart Bikf8f5a162017-02-06 15:35:29 -0800349 LoopNode* node = new (loop_allocator_) LoopNode(loop_info);
Aart Bik281c6812016-08-26 11:31:48 -0700350 if (last_loop_ == nullptr) {
351 // First loop.
352 DCHECK(top_loop_ == nullptr);
353 last_loop_ = top_loop_ = node;
354 } else if (loop_info->IsIn(*last_loop_->loop_info)) {
355 // Inner loop.
356 node->outer = last_loop_;
357 DCHECK(last_loop_->inner == nullptr);
358 last_loop_ = last_loop_->inner = node;
359 } else {
360 // Subsequent loop.
361 while (last_loop_->outer != nullptr && !loop_info->IsIn(*last_loop_->outer->loop_info)) {
362 last_loop_ = last_loop_->outer;
363 }
364 node->outer = last_loop_->outer;
365 node->previous = last_loop_;
366 DCHECK(last_loop_->next == nullptr);
367 last_loop_ = last_loop_->next = node;
368 }
369}
370
371void HLoopOptimization::RemoveLoop(LoopNode* node) {
372 DCHECK(node != nullptr);
Aart Bik8c4a8542016-10-06 11:36:57 -0700373 DCHECK(node->inner == nullptr);
374 if (node->previous != nullptr) {
375 // Within sequence.
376 node->previous->next = node->next;
377 if (node->next != nullptr) {
378 node->next->previous = node->previous;
379 }
380 } else {
381 // First of sequence.
382 if (node->outer != nullptr) {
383 node->outer->inner = node->next;
384 } else {
385 top_loop_ = node->next;
386 }
387 if (node->next != nullptr) {
388 node->next->outer = node->outer;
389 node->next->previous = nullptr;
390 }
391 }
Aart Bik281c6812016-08-26 11:31:48 -0700392}
393
394void HLoopOptimization::TraverseLoopsInnerToOuter(LoopNode* node) {
395 for ( ; node != nullptr; node = node->next) {
Aart Bik6b69e0a2017-01-11 10:20:43 -0800396 // Visit inner loops first.
Aart Bikf8f5a162017-02-06 15:35:29 -0800397 uint32_t current_induction_simplification_count = induction_simplication_count_;
Aart Bik281c6812016-08-26 11:31:48 -0700398 if (node->inner != nullptr) {
399 TraverseLoopsInnerToOuter(node->inner);
400 }
Aart Bik6b69e0a2017-01-11 10:20:43 -0800401 // Recompute induction information of this loop if the induction
402 // of any inner loop has been simplified.
Aart Bik482095d2016-10-10 15:39:10 -0700403 if (current_induction_simplification_count != induction_simplication_count_) {
404 induction_range_.ReVisit(node->loop_info);
405 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800406 // Repeat simplifications in the loop-body until no more changes occur.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800407 // Note that since each simplification consists of eliminating code (without
408 // introducing new code), this process is always finite.
Aart Bikdf7822e2016-12-06 10:05:30 -0800409 do {
410 simplified_ = false;
Aart Bikdf7822e2016-12-06 10:05:30 -0800411 SimplifyInduction(node);
Aart Bik6b69e0a2017-01-11 10:20:43 -0800412 SimplifyBlocks(node);
Aart Bikdf7822e2016-12-06 10:05:30 -0800413 } while (simplified_);
Aart Bikf8f5a162017-02-06 15:35:29 -0800414 // Optimize inner loop.
Aart Bik9abf8942016-10-14 09:49:42 -0700415 if (node->inner == nullptr) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800416 OptimizeInnerLoop(node);
Aart Bik9abf8942016-10-14 09:49:42 -0700417 }
Aart Bik281c6812016-08-26 11:31:48 -0700418 }
419}
420
Aart Bikf8f5a162017-02-06 15:35:29 -0800421//
422// Optimization.
423//
424
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +0100425bool HLoopOptimization::CanRemoveCycle() {
426 for (HInstruction* i : *iset_) {
427 // We can never remove instructions that have environment
428 // uses when we compile 'debuggable'.
429 if (i->HasEnvironmentUses() && graph_->IsDebuggable()) {
430 return false;
431 }
432 // A deoptimization should never have an environment input removed.
433 for (const HUseListNode<HEnvironment*>& use : i->GetEnvUses()) {
434 if (use.GetUser()->GetHolder()->IsDeoptimize()) {
435 return false;
436 }
437 }
438 }
439 return true;
440}
441
Aart Bik281c6812016-08-26 11:31:48 -0700442void HLoopOptimization::SimplifyInduction(LoopNode* node) {
443 HBasicBlock* header = node->loop_info->GetHeader();
444 HBasicBlock* preheader = node->loop_info->GetPreHeader();
Aart Bik8c4a8542016-10-06 11:36:57 -0700445 // Scan the phis in the header to find opportunities to simplify an induction
446 // cycle that is only used outside the loop. Replace these uses, if any, with
447 // the last value and remove the induction cycle.
448 // Examples: for (int i = 0; x != null; i++) { .... no i .... }
449 // for (int i = 0; i < 10; i++, k++) { .... no k .... } return k;
Aart Bik281c6812016-08-26 11:31:48 -0700450 for (HInstructionIterator it(header->GetPhis()); !it.Done(); it.Advance()) {
451 HPhi* phi = it.Current()->AsPhi();
Aart Bikf8f5a162017-02-06 15:35:29 -0800452 iset_->clear(); // prepare phi induction
453 if (TrySetPhiInduction(phi, /*restrict_uses*/ true) &&
454 TryAssignLastValue(node->loop_info, phi, preheader, /*collect_loop_uses*/ false)) {
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +0100455 // Note that it's ok to have replaced uses after the loop with the last value, without
456 // being able to remove the cycle. Environment uses (which are the reason we may not be
457 // able to remove the cycle) within the loop will still hold the right value.
458 if (CanRemoveCycle()) {
459 for (HInstruction* i : *iset_) {
460 RemoveFromCycle(i);
461 }
462 simplified_ = true;
Aart Bik281c6812016-08-26 11:31:48 -0700463 }
Aart Bik482095d2016-10-10 15:39:10 -0700464 }
465 }
466}
467
468void HLoopOptimization::SimplifyBlocks(LoopNode* node) {
Aart Bikdf7822e2016-12-06 10:05:30 -0800469 // Iterate over all basic blocks in the loop-body.
470 for (HBlocksInLoopIterator it(*node->loop_info); !it.Done(); it.Advance()) {
471 HBasicBlock* block = it.Current();
472 // Remove dead instructions from the loop-body.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800473 RemoveDeadInstructions(block->GetPhis());
474 RemoveDeadInstructions(block->GetInstructions());
Aart Bikdf7822e2016-12-06 10:05:30 -0800475 // Remove trivial control flow blocks from the loop-body.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800476 if (block->GetPredecessors().size() == 1 &&
477 block->GetSuccessors().size() == 1 &&
478 block->GetSingleSuccessor()->GetPredecessors().size() == 1) {
Aart Bikdf7822e2016-12-06 10:05:30 -0800479 simplified_ = true;
Aart Bik6b69e0a2017-01-11 10:20:43 -0800480 block->MergeWith(block->GetSingleSuccessor());
Aart Bikdf7822e2016-12-06 10:05:30 -0800481 } else if (block->GetSuccessors().size() == 2) {
482 // Trivial if block can be bypassed to either branch.
483 HBasicBlock* succ0 = block->GetSuccessors()[0];
484 HBasicBlock* succ1 = block->GetSuccessors()[1];
485 HBasicBlock* meet0 = nullptr;
486 HBasicBlock* meet1 = nullptr;
487 if (succ0 != succ1 &&
488 IsGotoBlock(succ0, &meet0) &&
489 IsGotoBlock(succ1, &meet1) &&
490 meet0 == meet1 && // meets again
491 meet0 != block && // no self-loop
492 meet0->GetPhis().IsEmpty()) { // not used for merging
493 simplified_ = true;
494 succ0->DisconnectAndDelete();
495 if (block->Dominates(meet0)) {
496 block->RemoveDominatedBlock(meet0);
497 succ1->AddDominatedBlock(meet0);
498 meet0->SetDominator(succ1);
Aart Bike3dedc52016-11-02 17:50:27 -0700499 }
Aart Bik482095d2016-10-10 15:39:10 -0700500 }
Aart Bik281c6812016-08-26 11:31:48 -0700501 }
Aart Bikdf7822e2016-12-06 10:05:30 -0800502 }
Aart Bik281c6812016-08-26 11:31:48 -0700503}
504
Aart Bikf8f5a162017-02-06 15:35:29 -0800505void HLoopOptimization::OptimizeInnerLoop(LoopNode* node) {
Aart Bik281c6812016-08-26 11:31:48 -0700506 HBasicBlock* header = node->loop_info->GetHeader();
507 HBasicBlock* preheader = node->loop_info->GetPreHeader();
Aart Bik9abf8942016-10-14 09:49:42 -0700508 // Ensure loop header logic is finite.
Aart Bikf8f5a162017-02-06 15:35:29 -0800509 int64_t trip_count = 0;
510 if (!induction_range_.IsFinite(node->loop_info, &trip_count)) {
511 return;
Aart Bik9abf8942016-10-14 09:49:42 -0700512 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800513
Aart Bik281c6812016-08-26 11:31:48 -0700514 // Ensure there is only a single loop-body (besides the header).
515 HBasicBlock* body = nullptr;
516 for (HBlocksInLoopIterator it(*node->loop_info); !it.Done(); it.Advance()) {
517 if (it.Current() != header) {
518 if (body != nullptr) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800519 return;
Aart Bik281c6812016-08-26 11:31:48 -0700520 }
521 body = it.Current();
522 }
523 }
Andreas Gampef45d61c2017-06-07 10:29:33 -0700524 CHECK(body != nullptr);
Aart Bik281c6812016-08-26 11:31:48 -0700525 // Ensure there is only a single exit point.
526 if (header->GetSuccessors().size() != 2) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800527 return;
Aart Bik281c6812016-08-26 11:31:48 -0700528 }
529 HBasicBlock* exit = (header->GetSuccessors()[0] == body)
530 ? header->GetSuccessors()[1]
531 : header->GetSuccessors()[0];
Aart Bik8c4a8542016-10-06 11:36:57 -0700532 // Ensure exit can only be reached by exiting loop.
Aart Bik281c6812016-08-26 11:31:48 -0700533 if (exit->GetPredecessors().size() != 1) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800534 return;
Aart Bik281c6812016-08-26 11:31:48 -0700535 }
Aart Bik6b69e0a2017-01-11 10:20:43 -0800536 // Detect either an empty loop (no side effects other than plain iteration) or
537 // a trivial loop (just iterating once). Replace subsequent index uses, if any,
538 // with the last value and remove the loop, possibly after unrolling its body.
539 HInstruction* phi = header->GetFirstPhi();
Aart Bikf8f5a162017-02-06 15:35:29 -0800540 iset_->clear(); // prepare phi induction
541 if (TrySetSimpleLoopHeader(header)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -0800542 bool is_empty = IsEmptyBody(body);
Aart Bikf8f5a162017-02-06 15:35:29 -0800543 if ((is_empty || trip_count == 1) &&
544 TryAssignLastValue(node->loop_info, phi, preheader, /*collect_loop_uses*/ true)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -0800545 if (!is_empty) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800546 // Unroll the loop-body, which sees initial value of the index.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800547 phi->ReplaceWith(phi->InputAt(0));
548 preheader->MergeInstructionsWith(body);
549 }
550 body->DisconnectAndDelete();
551 exit->RemovePredecessor(header);
552 header->RemoveSuccessor(exit);
553 header->RemoveDominatedBlock(exit);
554 header->DisconnectAndDelete();
555 preheader->AddSuccessor(exit);
Aart Bikf8f5a162017-02-06 15:35:29 -0800556 preheader->AddInstruction(new (global_allocator_) HGoto());
Aart Bik6b69e0a2017-01-11 10:20:43 -0800557 preheader->AddDominatedBlock(exit);
558 exit->SetDominator(preheader);
559 RemoveLoop(node); // update hierarchy
Aart Bikf8f5a162017-02-06 15:35:29 -0800560 return;
561 }
562 }
563
564 // Vectorize loop, if possible and valid.
565 if (kEnableVectorization) {
566 iset_->clear(); // prepare phi induction
567 if (TrySetSimpleLoopHeader(header) &&
568 CanVectorize(node, body, trip_count) &&
569 TryAssignLastValue(node->loop_info, phi, preheader, /*collect_loop_uses*/ true)) {
570 Vectorize(node, body, exit, trip_count);
571 graph_->SetHasSIMD(true); // flag SIMD usage
572 return;
573 }
574 }
575}
576
577//
578// Loop vectorization. The implementation is based on the book by Aart J.C. Bik:
579// "The Software Vectorization Handbook. Applying Multimedia Extensions for Maximum Performance."
580// Intel Press, June, 2004 (http://www.aartbik.com/).
581//
582
583bool HLoopOptimization::CanVectorize(LoopNode* node, HBasicBlock* block, int64_t trip_count) {
584 // Reset vector bookkeeping.
585 vector_length_ = 0;
586 vector_refs_->clear();
587 vector_runtime_test_a_ =
588 vector_runtime_test_b_= nullptr;
589
590 // Phis in the loop-body prevent vectorization.
591 if (!block->GetPhis().IsEmpty()) {
592 return false;
593 }
594
595 // Scan the loop-body, starting a right-hand-side tree traversal at each left-hand-side
596 // occurrence, which allows passing down attributes down the use tree.
597 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
598 if (!VectorizeDef(node, it.Current(), /*generate_code*/ false)) {
599 return false; // failure to vectorize a left-hand-side
600 }
601 }
602
603 // Heuristics. Does vectorization seem profitable?
604 // TODO: refine
605 if (vector_length_ == 0) {
606 return false; // nothing found
607 } else if (0 < trip_count && trip_count < vector_length_) {
608 return false; // insufficient iterations
609 }
610
611 // Data dependence analysis. Find each pair of references with same type, where
612 // at least one is a write. Each such pair denotes a possible data dependence.
613 // This analysis exploits the property that differently typed arrays cannot be
614 // aliased, as well as the property that references either point to the same
615 // array or to two completely disjoint arrays, i.e., no partial aliasing.
616 // Other than a few simply heuristics, no detailed subscript analysis is done.
617 for (auto i = vector_refs_->begin(); i != vector_refs_->end(); ++i) {
618 for (auto j = i; ++j != vector_refs_->end(); ) {
619 if (i->type == j->type && (i->lhs || j->lhs)) {
620 // Found same-typed a[i+x] vs. b[i+y], where at least one is a write.
621 HInstruction* a = i->base;
622 HInstruction* b = j->base;
623 HInstruction* x = i->offset;
624 HInstruction* y = j->offset;
625 if (a == b) {
626 // Found a[i+x] vs. a[i+y]. Accept if x == y (loop-independent data dependence).
627 // Conservatively assume a loop-carried data dependence otherwise, and reject.
628 if (x != y) {
629 return false;
630 }
631 } else {
632 // Found a[i+x] vs. b[i+y]. Accept if x == y (at worst loop-independent data dependence).
633 // Conservatively assume a potential loop-carried data dependence otherwise, avoided by
634 // generating an explicit a != b disambiguation runtime test on the two references.
635 if (x != y) {
636 // For now, we reject after one test to avoid excessive overhead.
637 if (vector_runtime_test_a_ != nullptr) {
638 return false;
639 }
640 vector_runtime_test_a_ = a;
641 vector_runtime_test_b_ = b;
642 }
643 }
644 }
645 }
646 }
647
648 // Success!
649 return true;
650}
651
652void HLoopOptimization::Vectorize(LoopNode* node,
653 HBasicBlock* block,
654 HBasicBlock* exit,
655 int64_t trip_count) {
656 Primitive::Type induc_type = Primitive::kPrimInt;
657 HBasicBlock* header = node->loop_info->GetHeader();
658 HBasicBlock* preheader = node->loop_info->GetPreHeader();
659
660 // A cleanup is needed for any unknown trip count or for a known trip count
661 // with remainder iterations after vectorization.
662 bool needs_cleanup = trip_count == 0 || (trip_count % vector_length_) != 0;
663
664 // Adjust vector bookkeeping.
665 iset_->clear(); // prepare phi induction
666 bool is_simple_loop_header = TrySetSimpleLoopHeader(header); // fills iset_
667 DCHECK(is_simple_loop_header);
668
669 // Generate preheader:
670 // stc = <trip-count>;
671 // vtc = stc - stc % VL;
672 HInstruction* stc = induction_range_.GenerateTripCount(node->loop_info, graph_, preheader);
673 HInstruction* vtc = stc;
674 if (needs_cleanup) {
675 DCHECK(IsPowerOfTwo(vector_length_));
676 HInstruction* rem = Insert(
677 preheader, new (global_allocator_) HAnd(induc_type,
678 stc,
679 graph_->GetIntConstant(vector_length_ - 1)));
680 vtc = Insert(preheader, new (global_allocator_) HSub(induc_type, stc, rem));
681 }
682
683 // Generate runtime disambiguation test:
684 // vtc = a != b ? vtc : 0;
685 if (vector_runtime_test_a_ != nullptr) {
686 HInstruction* rt = Insert(
687 preheader,
688 new (global_allocator_) HNotEqual(vector_runtime_test_a_, vector_runtime_test_b_));
689 vtc = Insert(preheader,
690 new (global_allocator_) HSelect(rt, vtc, graph_->GetIntConstant(0), kNoDexPc));
691 needs_cleanup = true;
692 }
693
694 // Generate vector loop:
695 // for (i = 0; i < vtc; i += VL)
696 // <vectorized-loop-body>
697 vector_mode_ = kVector;
698 GenerateNewLoop(node,
699 block,
700 graph_->TransformLoopForVectorization(header, block, exit),
701 graph_->GetIntConstant(0),
702 vtc,
703 graph_->GetIntConstant(vector_length_));
704 HLoopInformation* vloop = vector_header_->GetLoopInformation();
705
706 // Generate cleanup loop, if needed:
707 // for ( ; i < stc; i += 1)
708 // <loop-body>
709 if (needs_cleanup) {
710 vector_mode_ = kSequential;
711 GenerateNewLoop(node,
712 block,
713 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
714 vector_phi_,
715 stc,
716 graph_->GetIntConstant(1));
717 }
718
719 // Remove the original loop by disconnecting the body block
720 // and removing all instructions from the header.
721 block->DisconnectAndDelete();
722 while (!header->GetFirstInstruction()->IsGoto()) {
723 header->RemoveInstruction(header->GetFirstInstruction());
724 }
725 // Update loop hierarchy: the old header now resides in the
726 // same outer loop as the old preheader.
727 header->SetLoopInformation(preheader->GetLoopInformation()); // outward
728 node->loop_info = vloop;
729}
730
731void HLoopOptimization::GenerateNewLoop(LoopNode* node,
732 HBasicBlock* block,
733 HBasicBlock* new_preheader,
734 HInstruction* lo,
735 HInstruction* hi,
736 HInstruction* step) {
737 Primitive::Type induc_type = Primitive::kPrimInt;
738 // Prepare new loop.
739 vector_map_->clear();
740 vector_preheader_ = new_preheader,
741 vector_header_ = vector_preheader_->GetSingleSuccessor();
742 vector_body_ = vector_header_->GetSuccessors()[1];
743 vector_phi_ = new (global_allocator_) HPhi(global_allocator_,
744 kNoRegNumber,
745 0,
746 HPhi::ToPhiType(induc_type));
Aart Bikb07d1bc2017-04-05 10:03:15 -0700747 // Generate header and prepare body.
Aart Bikf8f5a162017-02-06 15:35:29 -0800748 // for (i = lo; i < hi; i += step)
749 // <loop-body>
750 HInstruction* cond = new (global_allocator_) HAboveOrEqual(vector_phi_, hi);
751 vector_header_->AddPhi(vector_phi_);
752 vector_header_->AddInstruction(cond);
753 vector_header_->AddInstruction(new (global_allocator_) HIf(cond));
Aart Bikf8f5a162017-02-06 15:35:29 -0800754 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
755 bool vectorized_def = VectorizeDef(node, it.Current(), /*generate_code*/ true);
756 DCHECK(vectorized_def);
757 }
Aart Bik24b905f2017-04-06 09:59:06 -0700758 // Generate body from the instruction map, but in original program order.
Aart Bikb07d1bc2017-04-05 10:03:15 -0700759 HEnvironment* env = vector_header_->GetFirstInstruction()->GetEnvironment();
Aart Bikf8f5a162017-02-06 15:35:29 -0800760 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
761 auto i = vector_map_->find(it.Current());
762 if (i != vector_map_->end() && !i->second->IsInBlock()) {
Aart Bik24b905f2017-04-06 09:59:06 -0700763 Insert(vector_body_, i->second);
764 // Deal with instructions that need an environment, such as the scalar intrinsics.
Aart Bikf8f5a162017-02-06 15:35:29 -0800765 if (i->second->NeedsEnvironment()) {
Aart Bikb07d1bc2017-04-05 10:03:15 -0700766 i->second->CopyEnvironmentFromWithLoopPhiAdjustment(env, vector_header_);
Aart Bikf8f5a162017-02-06 15:35:29 -0800767 }
768 }
769 }
770 // Finalize increment and phi.
771 HInstruction* inc = new (global_allocator_) HAdd(induc_type, vector_phi_, step);
772 vector_phi_->AddInput(lo);
773 vector_phi_->AddInput(Insert(vector_body_, inc));
774}
775
776// TODO: accept reductions at left-hand-side, mixed-type store idioms, etc.
777bool HLoopOptimization::VectorizeDef(LoopNode* node,
778 HInstruction* instruction,
779 bool generate_code) {
780 // Accept a left-hand-side array base[index] for
781 // (1) supported vector type,
782 // (2) loop-invariant base,
783 // (3) unit stride index,
784 // (4) vectorizable right-hand-side value.
785 uint64_t restrictions = kNone;
786 if (instruction->IsArraySet()) {
787 Primitive::Type type = instruction->AsArraySet()->GetComponentType();
788 HInstruction* base = instruction->InputAt(0);
789 HInstruction* index = instruction->InputAt(1);
790 HInstruction* value = instruction->InputAt(2);
791 HInstruction* offset = nullptr;
792 if (TrySetVectorType(type, &restrictions) &&
793 node->loop_info->IsDefinedOutOfTheLoop(base) &&
Aart Bikfa762962017-04-07 11:33:37 -0700794 induction_range_.IsUnitStride(instruction, index, &offset) &&
Aart Bikf8f5a162017-02-06 15:35:29 -0800795 VectorizeUse(node, value, generate_code, type, restrictions)) {
796 if (generate_code) {
797 GenerateVecSub(index, offset);
798 GenerateVecMem(instruction, vector_map_->Get(index), vector_map_->Get(value), type);
799 } else {
800 vector_refs_->insert(ArrayReference(base, offset, type, /*lhs*/ true));
801 }
Aart Bik6b69e0a2017-01-11 10:20:43 -0800802 return true;
803 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800804 return false;
805 }
806 // Branch back okay.
807 if (instruction->IsGoto()) {
808 return true;
809 }
810 // Otherwise accept only expressions with no effects outside the immediate loop-body.
811 // Note that actual uses are inspected during right-hand-side tree traversal.
812 return !IsUsedOutsideLoop(node->loop_info, instruction) && !instruction->DoesAnyWrite();
813}
814
Aart Bik304c8a52017-05-23 11:01:13 -0700815// TODO: saturation arithmetic.
Aart Bikf8f5a162017-02-06 15:35:29 -0800816bool HLoopOptimization::VectorizeUse(LoopNode* node,
817 HInstruction* instruction,
818 bool generate_code,
819 Primitive::Type type,
820 uint64_t restrictions) {
821 // Accept anything for which code has already been generated.
822 if (generate_code) {
823 if (vector_map_->find(instruction) != vector_map_->end()) {
824 return true;
825 }
826 }
827 // Continue the right-hand-side tree traversal, passing in proper
828 // types and vector restrictions along the way. During code generation,
829 // all new nodes are drawn from the global allocator.
830 if (node->loop_info->IsDefinedOutOfTheLoop(instruction)) {
831 // Accept invariant use, using scalar expansion.
832 if (generate_code) {
833 GenerateVecInv(instruction, type);
834 }
835 return true;
836 } else if (instruction->IsArrayGet()) {
Goran Jakovljevic19680d32017-05-11 10:38:36 +0200837 // Deal with vector restrictions.
838 if (instruction->AsArrayGet()->IsStringCharAt() &&
839 HasVectorRestrictions(restrictions, kNoStringCharAt)) {
840 return false;
841 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800842 // Accept a right-hand-side array base[index] for
843 // (1) exact matching vector type,
844 // (2) loop-invariant base,
845 // (3) unit stride index,
846 // (4) vectorizable right-hand-side value.
847 HInstruction* base = instruction->InputAt(0);
848 HInstruction* index = instruction->InputAt(1);
849 HInstruction* offset = nullptr;
850 if (type == instruction->GetType() &&
851 node->loop_info->IsDefinedOutOfTheLoop(base) &&
Aart Bikfa762962017-04-07 11:33:37 -0700852 induction_range_.IsUnitStride(instruction, index, &offset)) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800853 if (generate_code) {
854 GenerateVecSub(index, offset);
855 GenerateVecMem(instruction, vector_map_->Get(index), nullptr, type);
856 } else {
857 vector_refs_->insert(ArrayReference(base, offset, type, /*lhs*/ false));
858 }
859 return true;
860 }
861 } else if (instruction->IsTypeConversion()) {
862 // Accept particular type conversions.
863 HTypeConversion* conversion = instruction->AsTypeConversion();
864 HInstruction* opa = conversion->InputAt(0);
865 Primitive::Type from = conversion->GetInputType();
866 Primitive::Type to = conversion->GetResultType();
867 if ((to == Primitive::kPrimByte ||
868 to == Primitive::kPrimChar ||
869 to == Primitive::kPrimShort) && from == Primitive::kPrimInt) {
870 // Accept a "narrowing" type conversion from a "wider" computation for
871 // (1) conversion into final required type,
872 // (2) vectorizable operand,
873 // (3) "wider" operations cannot bring in higher order bits.
874 if (to == type && VectorizeUse(node, opa, generate_code, type, restrictions | kNoHiBits)) {
875 if (generate_code) {
876 if (vector_mode_ == kVector) {
877 vector_map_->Put(instruction, vector_map_->Get(opa)); // operand pass-through
878 } else {
879 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
880 }
881 }
882 return true;
883 }
884 } else if (to == Primitive::kPrimFloat && from == Primitive::kPrimInt) {
885 DCHECK_EQ(to, type);
886 // Accept int to float conversion for
887 // (1) supported int,
888 // (2) vectorizable operand.
889 if (TrySetVectorType(from, &restrictions) &&
890 VectorizeUse(node, opa, generate_code, from, restrictions)) {
891 if (generate_code) {
892 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
893 }
894 return true;
895 }
896 }
897 return false;
898 } else if (instruction->IsNeg() || instruction->IsNot() || instruction->IsBooleanNot()) {
899 // Accept unary operator for vectorizable operand.
900 HInstruction* opa = instruction->InputAt(0);
901 if (VectorizeUse(node, opa, generate_code, type, restrictions)) {
902 if (generate_code) {
903 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
904 }
905 return true;
906 }
907 } else if (instruction->IsAdd() || instruction->IsSub() ||
908 instruction->IsMul() || instruction->IsDiv() ||
909 instruction->IsAnd() || instruction->IsOr() || instruction->IsXor()) {
910 // Deal with vector restrictions.
911 if ((instruction->IsMul() && HasVectorRestrictions(restrictions, kNoMul)) ||
912 (instruction->IsDiv() && HasVectorRestrictions(restrictions, kNoDiv))) {
913 return false;
914 }
915 // Accept binary operator for vectorizable operands.
916 HInstruction* opa = instruction->InputAt(0);
917 HInstruction* opb = instruction->InputAt(1);
918 if (VectorizeUse(node, opa, generate_code, type, restrictions) &&
919 VectorizeUse(node, opb, generate_code, type, restrictions)) {
920 if (generate_code) {
921 GenerateVecOp(instruction, vector_map_->Get(opa), vector_map_->Get(opb), type);
922 }
923 return true;
924 }
925 } else if (instruction->IsShl() || instruction->IsShr() || instruction->IsUShr()) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700926 // Recognize vectorization idioms.
927 if (VectorizeHalvingAddIdiom(node, instruction, generate_code, type, restrictions)) {
928 return true;
929 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800930 // Deal with vector restrictions.
Aart Bik304c8a52017-05-23 11:01:13 -0700931 HInstruction* opa = instruction->InputAt(0);
932 HInstruction* opb = instruction->InputAt(1);
933 HInstruction* r = opa;
934 bool is_unsigned = false;
Aart Bikf8f5a162017-02-06 15:35:29 -0800935 if ((HasVectorRestrictions(restrictions, kNoShift)) ||
936 (instruction->IsShr() && HasVectorRestrictions(restrictions, kNoShr))) {
937 return false; // unsupported instruction
Aart Bik304c8a52017-05-23 11:01:13 -0700938 } else if (HasVectorRestrictions(restrictions, kNoHiBits)) {
939 // Shifts right need extra care to account for higher order bits.
940 // TODO: less likely shr/unsigned and ushr/signed can by flipping signess.
941 if (instruction->IsShr() &&
942 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || is_unsigned)) {
943 return false; // reject, unless all operands are sign-extension narrower
944 } else if (instruction->IsUShr() &&
945 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || !is_unsigned)) {
946 return false; // reject, unless all operands are zero-extension narrower
947 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800948 }
949 // Accept shift operator for vectorizable/invariant operands.
950 // TODO: accept symbolic, albeit loop invariant shift factors.
Aart Bik304c8a52017-05-23 11:01:13 -0700951 DCHECK(r != nullptr);
952 if (generate_code && vector_mode_ != kVector) { // de-idiom
953 r = opa;
954 }
Aart Bik50e20d52017-05-05 14:07:29 -0700955 int64_t distance = 0;
Aart Bik304c8a52017-05-23 11:01:13 -0700956 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
Aart Bik50e20d52017-05-05 14:07:29 -0700957 IsInt64AndGet(opb, /*out*/ &distance)) {
Aart Bik65ffd8e2017-05-01 16:50:45 -0700958 // Restrict shift distance to packed data type width.
959 int64_t max_distance = Primitive::ComponentSize(type) * 8;
960 if (0 <= distance && distance < max_distance) {
961 if (generate_code) {
Aart Bik304c8a52017-05-23 11:01:13 -0700962 GenerateVecOp(instruction, vector_map_->Get(r), opb, type);
Aart Bik65ffd8e2017-05-01 16:50:45 -0700963 }
964 return true;
Aart Bikf8f5a162017-02-06 15:35:29 -0800965 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800966 }
967 } else if (instruction->IsInvokeStaticOrDirect()) {
Aart Bik6daebeb2017-04-03 14:35:41 -0700968 // Accept particular intrinsics.
969 HInvokeStaticOrDirect* invoke = instruction->AsInvokeStaticOrDirect();
970 switch (invoke->GetIntrinsic()) {
971 case Intrinsics::kMathAbsInt:
972 case Intrinsics::kMathAbsLong:
973 case Intrinsics::kMathAbsFloat:
974 case Intrinsics::kMathAbsDouble: {
975 // Deal with vector restrictions.
Aart Bik304c8a52017-05-23 11:01:13 -0700976 HInstruction* opa = instruction->InputAt(0);
977 HInstruction* r = opa;
978 bool is_unsigned = false;
979 if (HasVectorRestrictions(restrictions, kNoAbs)) {
Aart Bik6daebeb2017-04-03 14:35:41 -0700980 return false;
Aart Bik304c8a52017-05-23 11:01:13 -0700981 } else if (HasVectorRestrictions(restrictions, kNoHiBits) &&
982 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || is_unsigned)) {
983 return false; // reject, unless operand is sign-extension narrower
Aart Bik6daebeb2017-04-03 14:35:41 -0700984 }
985 // Accept ABS(x) for vectorizable operand.
Aart Bik304c8a52017-05-23 11:01:13 -0700986 DCHECK(r != nullptr);
987 if (generate_code && vector_mode_ != kVector) { // de-idiom
988 r = opa;
989 }
990 if (VectorizeUse(node, r, generate_code, type, restrictions)) {
Aart Bik6daebeb2017-04-03 14:35:41 -0700991 if (generate_code) {
Aart Bik304c8a52017-05-23 11:01:13 -0700992 GenerateVecOp(instruction, vector_map_->Get(r), nullptr, type);
Aart Bik6daebeb2017-04-03 14:35:41 -0700993 }
994 return true;
995 }
996 return false;
997 }
Aart Bikc8e93c72017-05-10 10:49:22 -0700998 case Intrinsics::kMathMinIntInt:
999 case Intrinsics::kMathMinLongLong:
1000 case Intrinsics::kMathMinFloatFloat:
1001 case Intrinsics::kMathMinDoubleDouble:
1002 case Intrinsics::kMathMaxIntInt:
1003 case Intrinsics::kMathMaxLongLong:
1004 case Intrinsics::kMathMaxFloatFloat:
1005 case Intrinsics::kMathMaxDoubleDouble: {
1006 // Deal with vector restrictions.
Nicolas Geoffray92316902017-05-23 08:06:07 +00001007 HInstruction* opa = instruction->InputAt(0);
1008 HInstruction* opb = instruction->InputAt(1);
Aart Bik304c8a52017-05-23 11:01:13 -07001009 HInstruction* r = opa;
1010 HInstruction* s = opb;
1011 bool is_unsigned = false;
1012 if (HasVectorRestrictions(restrictions, kNoMinMax)) {
1013 return false;
1014 } else if (HasVectorRestrictions(restrictions, kNoHiBits) &&
1015 !IsNarrowerOperands(opa, opb, type, &r, &s, &is_unsigned)) {
1016 return false; // reject, unless all operands are same-extension narrower
1017 }
1018 // Accept MIN/MAX(x, y) for vectorizable operands.
1019 DCHECK(r != nullptr && s != nullptr);
1020 if (generate_code && vector_mode_ != kVector) { // de-idiom
1021 r = opa;
1022 s = opb;
1023 }
1024 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
1025 VectorizeUse(node, s, generate_code, type, restrictions)) {
Aart Bikc8e93c72017-05-10 10:49:22 -07001026 if (generate_code) {
Aart Bik304c8a52017-05-23 11:01:13 -07001027 GenerateVecOp(
1028 instruction, vector_map_->Get(r), vector_map_->Get(s), type, is_unsigned);
Aart Bikc8e93c72017-05-10 10:49:22 -07001029 }
1030 return true;
1031 }
1032 return false;
1033 }
Aart Bik6daebeb2017-04-03 14:35:41 -07001034 default:
1035 return false;
1036 } // switch
Aart Bik281c6812016-08-26 11:31:48 -07001037 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08001038 return false;
Aart Bik281c6812016-08-26 11:31:48 -07001039}
1040
Aart Bikf8f5a162017-02-06 15:35:29 -08001041bool HLoopOptimization::TrySetVectorType(Primitive::Type type, uint64_t* restrictions) {
1042 const InstructionSetFeatures* features = compiler_driver_->GetInstructionSetFeatures();
1043 switch (compiler_driver_->GetInstructionSet()) {
1044 case kArm:
1045 case kThumb2:
1046 return false;
1047 case kArm64:
1048 // Allow vectorization for all ARM devices, because Android assumes that
Artem Serovd4bccf12017-04-03 18:47:32 +01001049 // ARMv8 AArch64 always supports advanced SIMD.
Aart Bikf8f5a162017-02-06 15:35:29 -08001050 switch (type) {
1051 case Primitive::kPrimBoolean:
1052 case Primitive::kPrimByte:
Aart Bik304c8a52017-05-23 11:01:13 -07001053 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +01001054 return TrySetVectorLength(16);
Aart Bikf8f5a162017-02-06 15:35:29 -08001055 case Primitive::kPrimChar:
1056 case Primitive::kPrimShort:
Aart Bik304c8a52017-05-23 11:01:13 -07001057 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +01001058 return TrySetVectorLength(8);
Aart Bikf8f5a162017-02-06 15:35:29 -08001059 case Primitive::kPrimInt:
1060 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +01001061 return TrySetVectorLength(4);
Artem Serovb31f91f2017-04-05 11:31:19 +01001062 case Primitive::kPrimLong:
Aart Bikc8e93c72017-05-10 10:49:22 -07001063 *restrictions |= kNoDiv | kNoMul | kNoMinMax;
Aart Bikf8f5a162017-02-06 15:35:29 -08001064 return TrySetVectorLength(2);
1065 case Primitive::kPrimFloat:
Artem Serovd4bccf12017-04-03 18:47:32 +01001066 return TrySetVectorLength(4);
Artem Serovb31f91f2017-04-05 11:31:19 +01001067 case Primitive::kPrimDouble:
Aart Bikf8f5a162017-02-06 15:35:29 -08001068 return TrySetVectorLength(2);
1069 default:
1070 return false;
1071 }
1072 case kX86:
1073 case kX86_64:
1074 // Allow vectorization for SSE4-enabled X86 devices only (128-bit vectors).
1075 if (features->AsX86InstructionSetFeatures()->HasSSE4_1()) {
1076 switch (type) {
1077 case Primitive::kPrimBoolean:
1078 case Primitive::kPrimByte:
Aart Bikf3e61ee2017-04-12 17:09:20 -07001079 *restrictions |= kNoMul | kNoDiv | kNoShift | kNoAbs | kNoSignedHAdd | kNoUnroundedHAdd;
Aart Bikf8f5a162017-02-06 15:35:29 -08001080 return TrySetVectorLength(16);
1081 case Primitive::kPrimChar:
1082 case Primitive::kPrimShort:
Aart Bikf3e61ee2017-04-12 17:09:20 -07001083 *restrictions |= kNoDiv | kNoAbs | kNoSignedHAdd | kNoUnroundedHAdd;
Aart Bikf8f5a162017-02-06 15:35:29 -08001084 return TrySetVectorLength(8);
1085 case Primitive::kPrimInt:
1086 *restrictions |= kNoDiv;
1087 return TrySetVectorLength(4);
1088 case Primitive::kPrimLong:
Aart Bikc8e93c72017-05-10 10:49:22 -07001089 *restrictions |= kNoMul | kNoDiv | kNoShr | kNoAbs | kNoMinMax;
Aart Bikf8f5a162017-02-06 15:35:29 -08001090 return TrySetVectorLength(2);
1091 case Primitive::kPrimFloat:
Aart Bikc8e93c72017-05-10 10:49:22 -07001092 *restrictions |= kNoMinMax; // -0.0 vs +0.0
Aart Bikf8f5a162017-02-06 15:35:29 -08001093 return TrySetVectorLength(4);
1094 case Primitive::kPrimDouble:
Aart Bikc8e93c72017-05-10 10:49:22 -07001095 *restrictions |= kNoMinMax; // -0.0 vs +0.0
Aart Bikf8f5a162017-02-06 15:35:29 -08001096 return TrySetVectorLength(2);
1097 default:
1098 break;
1099 } // switch type
1100 }
1101 return false;
1102 case kMips:
Aart Bikf8f5a162017-02-06 15:35:29 -08001103 // TODO: implement MIPS SIMD.
1104 return false;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001105 case kMips64:
1106 if (features->AsMips64InstructionSetFeatures()->HasMsa()) {
1107 switch (type) {
1108 case Primitive::kPrimBoolean:
1109 case Primitive::kPrimByte:
Goran Jakovljevic8fea1e12017-06-06 13:28:42 +02001110 *restrictions |= kNoDiv;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001111 return TrySetVectorLength(16);
1112 case Primitive::kPrimChar:
1113 case Primitive::kPrimShort:
Goran Jakovljevic8fea1e12017-06-06 13:28:42 +02001114 *restrictions |= kNoDiv | kNoStringCharAt;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001115 return TrySetVectorLength(8);
1116 case Primitive::kPrimInt:
Goran Jakovljevic8fea1e12017-06-06 13:28:42 +02001117 *restrictions |= kNoDiv;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001118 return TrySetVectorLength(4);
1119 case Primitive::kPrimLong:
Goran Jakovljevic8fea1e12017-06-06 13:28:42 +02001120 *restrictions |= kNoDiv;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001121 return TrySetVectorLength(2);
1122 case Primitive::kPrimFloat:
Goran Jakovljevic8fea1e12017-06-06 13:28:42 +02001123 *restrictions |= kNoMinMax; // min/max(x, NaN)
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001124 return TrySetVectorLength(4);
1125 case Primitive::kPrimDouble:
Goran Jakovljevic8fea1e12017-06-06 13:28:42 +02001126 *restrictions |= kNoMinMax; // min/max(x, NaN)
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001127 return TrySetVectorLength(2);
1128 default:
1129 break;
1130 } // switch type
1131 }
1132 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001133 default:
1134 return false;
1135 } // switch instruction set
1136}
1137
1138bool HLoopOptimization::TrySetVectorLength(uint32_t length) {
1139 DCHECK(IsPowerOfTwo(length) && length >= 2u);
1140 // First time set?
1141 if (vector_length_ == 0) {
1142 vector_length_ = length;
1143 }
1144 // Different types are acceptable within a loop-body, as long as all the corresponding vector
1145 // lengths match exactly to obtain a uniform traversal through the vector iteration space
1146 // (idiomatic exceptions to this rule can be handled by further unrolling sub-expressions).
1147 return vector_length_ == length;
1148}
1149
1150void HLoopOptimization::GenerateVecInv(HInstruction* org, Primitive::Type type) {
1151 if (vector_map_->find(org) == vector_map_->end()) {
1152 // In scalar code, just use a self pass-through for scalar invariants
1153 // (viz. expression remains itself).
1154 if (vector_mode_ == kSequential) {
1155 vector_map_->Put(org, org);
1156 return;
1157 }
1158 // In vector code, explicit scalar expansion is needed.
1159 HInstruction* vector = new (global_allocator_) HVecReplicateScalar(
1160 global_allocator_, org, type, vector_length_);
1161 vector_map_->Put(org, Insert(vector_preheader_, vector));
1162 }
1163}
1164
1165void HLoopOptimization::GenerateVecSub(HInstruction* org, HInstruction* offset) {
1166 if (vector_map_->find(org) == vector_map_->end()) {
1167 HInstruction* subscript = vector_phi_;
1168 if (offset != nullptr) {
1169 subscript = new (global_allocator_) HAdd(Primitive::kPrimInt, subscript, offset);
1170 if (org->IsPhi()) {
1171 Insert(vector_body_, subscript); // lacks layout placeholder
1172 }
1173 }
1174 vector_map_->Put(org, subscript);
1175 }
1176}
1177
1178void HLoopOptimization::GenerateVecMem(HInstruction* org,
1179 HInstruction* opa,
1180 HInstruction* opb,
1181 Primitive::Type type) {
1182 HInstruction* vector = nullptr;
1183 if (vector_mode_ == kVector) {
1184 // Vector store or load.
1185 if (opb != nullptr) {
1186 vector = new (global_allocator_) HVecStore(
1187 global_allocator_, org->InputAt(0), opa, opb, type, vector_length_);
1188 } else {
Aart Bikdb14fcf2017-04-25 15:53:58 -07001189 bool is_string_char_at = org->AsArrayGet()->IsStringCharAt();
Aart Bikf8f5a162017-02-06 15:35:29 -08001190 vector = new (global_allocator_) HVecLoad(
Aart Bikdb14fcf2017-04-25 15:53:58 -07001191 global_allocator_, org->InputAt(0), opa, type, vector_length_, is_string_char_at);
Aart Bikf8f5a162017-02-06 15:35:29 -08001192 }
1193 } else {
1194 // Scalar store or load.
1195 DCHECK(vector_mode_ == kSequential);
1196 if (opb != nullptr) {
1197 vector = new (global_allocator_) HArraySet(org->InputAt(0), opa, opb, type, kNoDexPc);
1198 } else {
Aart Bikdb14fcf2017-04-25 15:53:58 -07001199 bool is_string_char_at = org->AsArrayGet()->IsStringCharAt();
1200 vector = new (global_allocator_) HArrayGet(
1201 org->InputAt(0), opa, type, kNoDexPc, is_string_char_at);
Aart Bikf8f5a162017-02-06 15:35:29 -08001202 }
1203 }
1204 vector_map_->Put(org, vector);
1205}
1206
1207#define GENERATE_VEC(x, y) \
1208 if (vector_mode_ == kVector) { \
1209 vector = (x); \
1210 } else { \
1211 DCHECK(vector_mode_ == kSequential); \
1212 vector = (y); \
1213 } \
1214 break;
1215
1216void HLoopOptimization::GenerateVecOp(HInstruction* org,
1217 HInstruction* opa,
1218 HInstruction* opb,
Aart Bik304c8a52017-05-23 11:01:13 -07001219 Primitive::Type type,
1220 bool is_unsigned) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001221 if (vector_mode_ == kSequential) {
Aart Bik304c8a52017-05-23 11:01:13 -07001222 // Non-converting scalar code follows implicit integral promotion.
1223 if (!org->IsTypeConversion() && (type == Primitive::kPrimBoolean ||
1224 type == Primitive::kPrimByte ||
1225 type == Primitive::kPrimChar ||
1226 type == Primitive::kPrimShort)) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001227 type = Primitive::kPrimInt;
1228 }
1229 }
1230 HInstruction* vector = nullptr;
1231 switch (org->GetKind()) {
1232 case HInstruction::kNeg:
1233 DCHECK(opb == nullptr);
1234 GENERATE_VEC(
1235 new (global_allocator_) HVecNeg(global_allocator_, opa, type, vector_length_),
1236 new (global_allocator_) HNeg(type, opa));
1237 case HInstruction::kNot:
1238 DCHECK(opb == nullptr);
1239 GENERATE_VEC(
1240 new (global_allocator_) HVecNot(global_allocator_, opa, type, vector_length_),
1241 new (global_allocator_) HNot(type, opa));
1242 case HInstruction::kBooleanNot:
1243 DCHECK(opb == nullptr);
1244 GENERATE_VEC(
1245 new (global_allocator_) HVecNot(global_allocator_, opa, type, vector_length_),
1246 new (global_allocator_) HBooleanNot(opa));
1247 case HInstruction::kTypeConversion:
1248 DCHECK(opb == nullptr);
1249 GENERATE_VEC(
1250 new (global_allocator_) HVecCnv(global_allocator_, opa, type, vector_length_),
1251 new (global_allocator_) HTypeConversion(type, opa, kNoDexPc));
1252 case HInstruction::kAdd:
1253 GENERATE_VEC(
1254 new (global_allocator_) HVecAdd(global_allocator_, opa, opb, type, vector_length_),
1255 new (global_allocator_) HAdd(type, opa, opb));
1256 case HInstruction::kSub:
1257 GENERATE_VEC(
1258 new (global_allocator_) HVecSub(global_allocator_, opa, opb, type, vector_length_),
1259 new (global_allocator_) HSub(type, opa, opb));
1260 case HInstruction::kMul:
1261 GENERATE_VEC(
1262 new (global_allocator_) HVecMul(global_allocator_, opa, opb, type, vector_length_),
1263 new (global_allocator_) HMul(type, opa, opb));
1264 case HInstruction::kDiv:
1265 GENERATE_VEC(
1266 new (global_allocator_) HVecDiv(global_allocator_, opa, opb, type, vector_length_),
1267 new (global_allocator_) HDiv(type, opa, opb, kNoDexPc));
1268 case HInstruction::kAnd:
1269 GENERATE_VEC(
1270 new (global_allocator_) HVecAnd(global_allocator_, opa, opb, type, vector_length_),
1271 new (global_allocator_) HAnd(type, opa, opb));
1272 case HInstruction::kOr:
1273 GENERATE_VEC(
1274 new (global_allocator_) HVecOr(global_allocator_, opa, opb, type, vector_length_),
1275 new (global_allocator_) HOr(type, opa, opb));
1276 case HInstruction::kXor:
1277 GENERATE_VEC(
1278 new (global_allocator_) HVecXor(global_allocator_, opa, opb, type, vector_length_),
1279 new (global_allocator_) HXor(type, opa, opb));
1280 case HInstruction::kShl:
1281 GENERATE_VEC(
1282 new (global_allocator_) HVecShl(global_allocator_, opa, opb, type, vector_length_),
1283 new (global_allocator_) HShl(type, opa, opb));
1284 case HInstruction::kShr:
1285 GENERATE_VEC(
1286 new (global_allocator_) HVecShr(global_allocator_, opa, opb, type, vector_length_),
1287 new (global_allocator_) HShr(type, opa, opb));
1288 case HInstruction::kUShr:
1289 GENERATE_VEC(
1290 new (global_allocator_) HVecUShr(global_allocator_, opa, opb, type, vector_length_),
1291 new (global_allocator_) HUShr(type, opa, opb));
1292 case HInstruction::kInvokeStaticOrDirect: {
Aart Bik6daebeb2017-04-03 14:35:41 -07001293 HInvokeStaticOrDirect* invoke = org->AsInvokeStaticOrDirect();
1294 if (vector_mode_ == kVector) {
1295 switch (invoke->GetIntrinsic()) {
1296 case Intrinsics::kMathAbsInt:
1297 case Intrinsics::kMathAbsLong:
1298 case Intrinsics::kMathAbsFloat:
1299 case Intrinsics::kMathAbsDouble:
1300 DCHECK(opb == nullptr);
1301 vector = new (global_allocator_) HVecAbs(global_allocator_, opa, type, vector_length_);
1302 break;
Aart Bikc8e93c72017-05-10 10:49:22 -07001303 case Intrinsics::kMathMinIntInt:
1304 case Intrinsics::kMathMinLongLong:
1305 case Intrinsics::kMathMinFloatFloat:
1306 case Intrinsics::kMathMinDoubleDouble: {
Aart Bikc8e93c72017-05-10 10:49:22 -07001307 vector = new (global_allocator_)
1308 HVecMin(global_allocator_, opa, opb, type, vector_length_, is_unsigned);
1309 break;
1310 }
1311 case Intrinsics::kMathMaxIntInt:
1312 case Intrinsics::kMathMaxLongLong:
1313 case Intrinsics::kMathMaxFloatFloat:
1314 case Intrinsics::kMathMaxDoubleDouble: {
Aart Bikc8e93c72017-05-10 10:49:22 -07001315 vector = new (global_allocator_)
1316 HVecMax(global_allocator_, opa, opb, type, vector_length_, is_unsigned);
1317 break;
1318 }
Aart Bik6daebeb2017-04-03 14:35:41 -07001319 default:
1320 LOG(FATAL) << "Unsupported SIMD intrinsic";
1321 UNREACHABLE();
1322 } // switch invoke
1323 } else {
Aart Bik24b905f2017-04-06 09:59:06 -07001324 // In scalar code, simply clone the method invoke, and replace its operands with the
1325 // corresponding new scalar instructions in the loop. The instruction will get an
1326 // environment while being inserted from the instruction map in original program order.
Aart Bik6daebeb2017-04-03 14:35:41 -07001327 DCHECK(vector_mode_ == kSequential);
Aart Bik6e92fb32017-06-05 14:05:09 -07001328 size_t num_args = invoke->GetNumberOfArguments();
Aart Bik6daebeb2017-04-03 14:35:41 -07001329 HInvokeStaticOrDirect* new_invoke = new (global_allocator_) HInvokeStaticOrDirect(
1330 global_allocator_,
Aart Bik6e92fb32017-06-05 14:05:09 -07001331 num_args,
Aart Bik6daebeb2017-04-03 14:35:41 -07001332 invoke->GetType(),
1333 invoke->GetDexPc(),
1334 invoke->GetDexMethodIndex(),
1335 invoke->GetResolvedMethod(),
1336 invoke->GetDispatchInfo(),
1337 invoke->GetInvokeType(),
1338 invoke->GetTargetMethod(),
1339 invoke->GetClinitCheckRequirement());
1340 HInputsRef inputs = invoke->GetInputs();
Aart Bik6e92fb32017-06-05 14:05:09 -07001341 size_t num_inputs = inputs.size();
1342 DCHECK_LE(num_args, num_inputs);
1343 DCHECK_EQ(num_inputs, new_invoke->GetInputs().size()); // both invokes agree
1344 for (size_t index = 0; index < num_inputs; ++index) {
1345 HInstruction* new_input = index < num_args
1346 ? vector_map_->Get(inputs[index])
1347 : inputs[index]; // beyond arguments: just pass through
1348 new_invoke->SetArgumentAt(index, new_input);
Aart Bik6daebeb2017-04-03 14:35:41 -07001349 }
Aart Bik98990262017-04-10 13:15:57 -07001350 new_invoke->SetIntrinsic(invoke->GetIntrinsic(),
1351 kNeedsEnvironmentOrCache,
1352 kNoSideEffects,
1353 kNoThrow);
Aart Bik6daebeb2017-04-03 14:35:41 -07001354 vector = new_invoke;
1355 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001356 break;
1357 }
1358 default:
1359 break;
1360 } // switch
1361 CHECK(vector != nullptr) << "Unsupported SIMD operator";
1362 vector_map_->Put(org, vector);
1363}
1364
1365#undef GENERATE_VEC
1366
1367//
Aart Bikf3e61ee2017-04-12 17:09:20 -07001368// Vectorization idioms.
1369//
1370
1371// Method recognizes the following idioms:
1372// rounding halving add (a + b + 1) >> 1 for unsigned/signed operands a, b
1373// regular halving add (a + b) >> 1 for unsigned/signed operands a, b
1374// Provided that the operands are promoted to a wider form to do the arithmetic and
1375// then cast back to narrower form, the idioms can be mapped into efficient SIMD
1376// implementation that operates directly in narrower form (plus one extra bit).
1377// TODO: current version recognizes implicit byte/short/char widening only;
1378// explicit widening from int to long could be added later.
1379bool HLoopOptimization::VectorizeHalvingAddIdiom(LoopNode* node,
1380 HInstruction* instruction,
1381 bool generate_code,
1382 Primitive::Type type,
1383 uint64_t restrictions) {
1384 // Test for top level arithmetic shift right x >> 1 or logical shift right x >>> 1
Aart Bik304c8a52017-05-23 11:01:13 -07001385 // (note whether the sign bit in wider precision is shifted in has no effect
Aart Bikf3e61ee2017-04-12 17:09:20 -07001386 // on the narrow precision computed by the idiom).
Aart Bik5f805002017-05-16 16:42:41 -07001387 int64_t distance = 0;
Aart Bikf3e61ee2017-04-12 17:09:20 -07001388 if ((instruction->IsShr() ||
1389 instruction->IsUShr()) &&
Aart Bik5f805002017-05-16 16:42:41 -07001390 IsInt64AndGet(instruction->InputAt(1), /*out*/ &distance) && distance == 1) {
1391 // Test for (a + b + c) >> 1 for optional constant c.
1392 HInstruction* a = nullptr;
1393 HInstruction* b = nullptr;
1394 int64_t c = 0;
1395 if (IsAddConst(instruction->InputAt(0), /*out*/ &a, /*out*/ &b, /*out*/ &c)) {
Aart Bik304c8a52017-05-23 11:01:13 -07001396 DCHECK(a != nullptr && b != nullptr);
Aart Bik5f805002017-05-16 16:42:41 -07001397 // Accept c == 1 (rounded) or c == 0 (not rounded).
1398 bool is_rounded = false;
1399 if (c == 1) {
1400 is_rounded = true;
1401 } else if (c != 0) {
1402 return false;
1403 }
1404 // Accept consistent zero or sign extension on operands a and b.
Aart Bikf3e61ee2017-04-12 17:09:20 -07001405 HInstruction* r = nullptr;
1406 HInstruction* s = nullptr;
1407 bool is_unsigned = false;
Aart Bik304c8a52017-05-23 11:01:13 -07001408 if (!IsNarrowerOperands(a, b, type, &r, &s, &is_unsigned)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -07001409 return false;
1410 }
1411 // Deal with vector restrictions.
1412 if ((!is_unsigned && HasVectorRestrictions(restrictions, kNoSignedHAdd)) ||
1413 (!is_rounded && HasVectorRestrictions(restrictions, kNoUnroundedHAdd))) {
1414 return false;
1415 }
1416 // Accept recognized halving add for vectorizable operands. Vectorized code uses the
1417 // shorthand idiomatic operation. Sequential code uses the original scalar expressions.
1418 DCHECK(r != nullptr && s != nullptr);
Aart Bik304c8a52017-05-23 11:01:13 -07001419 if (generate_code && vector_mode_ != kVector) { // de-idiom
1420 r = instruction->InputAt(0);
1421 s = instruction->InputAt(1);
1422 }
Aart Bikf3e61ee2017-04-12 17:09:20 -07001423 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
1424 VectorizeUse(node, s, generate_code, type, restrictions)) {
1425 if (generate_code) {
1426 if (vector_mode_ == kVector) {
1427 vector_map_->Put(instruction, new (global_allocator_) HVecHalvingAdd(
1428 global_allocator_,
1429 vector_map_->Get(r),
1430 vector_map_->Get(s),
1431 type,
1432 vector_length_,
1433 is_unsigned,
1434 is_rounded));
1435 } else {
Aart Bik304c8a52017-05-23 11:01:13 -07001436 GenerateVecOp(instruction, vector_map_->Get(r), vector_map_->Get(s), type);
Aart Bikf3e61ee2017-04-12 17:09:20 -07001437 }
1438 }
1439 return true;
1440 }
1441 }
1442 }
1443 return false;
1444}
1445
1446//
Aart Bikf8f5a162017-02-06 15:35:29 -08001447// Helpers.
1448//
1449
1450bool HLoopOptimization::TrySetPhiInduction(HPhi* phi, bool restrict_uses) {
1451 DCHECK(iset_->empty());
Aart Bikcc42be02016-10-20 16:14:16 -07001452 ArenaSet<HInstruction*>* set = induction_range_.LookupCycle(phi);
1453 if (set != nullptr) {
1454 for (HInstruction* i : *set) {
Aart Bike3dedc52016-11-02 17:50:27 -07001455 // Check that, other than instructions that are no longer in the graph (removed earlier)
Aart Bikf8f5a162017-02-06 15:35:29 -08001456 // each instruction is removable and, when restrict uses are requested, other than for phi,
1457 // all uses are contained within the cycle.
Aart Bike3dedc52016-11-02 17:50:27 -07001458 if (!i->IsInBlock()) {
1459 continue;
1460 } else if (!i->IsRemovable()) {
1461 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001462 } else if (i != phi && restrict_uses) {
Aart Bikcc42be02016-10-20 16:14:16 -07001463 for (const HUseListNode<HInstruction*>& use : i->GetUses()) {
1464 if (set->find(use.GetUser()) == set->end()) {
1465 return false;
1466 }
1467 }
1468 }
Aart Bike3dedc52016-11-02 17:50:27 -07001469 iset_->insert(i); // copy
Aart Bikcc42be02016-10-20 16:14:16 -07001470 }
Aart Bikcc42be02016-10-20 16:14:16 -07001471 return true;
1472 }
1473 return false;
1474}
1475
1476// Find: phi: Phi(init, addsub)
1477// s: SuspendCheck
1478// c: Condition(phi, bound)
1479// i: If(c)
1480// TODO: Find a less pattern matching approach?
Aart Bikf8f5a162017-02-06 15:35:29 -08001481bool HLoopOptimization::TrySetSimpleLoopHeader(HBasicBlock* block) {
Aart Bikcc42be02016-10-20 16:14:16 -07001482 DCHECK(iset_->empty());
1483 HInstruction* phi = block->GetFirstPhi();
Aart Bikf8f5a162017-02-06 15:35:29 -08001484 if (phi != nullptr &&
1485 phi->GetNext() == nullptr &&
1486 TrySetPhiInduction(phi->AsPhi(), /*restrict_uses*/ false)) {
Aart Bikcc42be02016-10-20 16:14:16 -07001487 HInstruction* s = block->GetFirstInstruction();
1488 if (s != nullptr && s->IsSuspendCheck()) {
1489 HInstruction* c = s->GetNext();
Aart Bikd86c0852017-04-14 12:00:15 -07001490 if (c != nullptr &&
1491 c->IsCondition() &&
1492 c->GetUses().HasExactlyOneElement() && // only used for termination
1493 !c->HasEnvironmentUses()) { // unlikely, but not impossible
Aart Bikcc42be02016-10-20 16:14:16 -07001494 HInstruction* i = c->GetNext();
1495 if (i != nullptr && i->IsIf() && i->InputAt(0) == c) {
1496 iset_->insert(c);
1497 iset_->insert(s);
1498 return true;
1499 }
1500 }
1501 }
1502 }
1503 return false;
1504}
1505
1506bool HLoopOptimization::IsEmptyBody(HBasicBlock* block) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001507 if (!block->GetPhis().IsEmpty()) {
1508 return false;
1509 }
1510 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
1511 HInstruction* instruction = it.Current();
1512 if (!instruction->IsGoto() && iset_->find(instruction) == iset_->end()) {
1513 return false;
Aart Bikcc42be02016-10-20 16:14:16 -07001514 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001515 }
1516 return true;
1517}
1518
1519bool HLoopOptimization::IsUsedOutsideLoop(HLoopInformation* loop_info,
1520 HInstruction* instruction) {
1521 for (const HUseListNode<HInstruction*>& use : instruction->GetUses()) {
1522 if (use.GetUser()->GetBlock()->GetLoopInformation() != loop_info) {
1523 return true;
1524 }
Aart Bikcc42be02016-10-20 16:14:16 -07001525 }
1526 return false;
1527}
1528
Aart Bik482095d2016-10-10 15:39:10 -07001529bool HLoopOptimization::IsOnlyUsedAfterLoop(HLoopInformation* loop_info,
Aart Bik8c4a8542016-10-06 11:36:57 -07001530 HInstruction* instruction,
Aart Bik6b69e0a2017-01-11 10:20:43 -08001531 bool collect_loop_uses,
Aart Bik8c4a8542016-10-06 11:36:57 -07001532 /*out*/ int32_t* use_count) {
1533 for (const HUseListNode<HInstruction*>& use : instruction->GetUses()) {
1534 HInstruction* user = use.GetUser();
1535 if (iset_->find(user) == iset_->end()) { // not excluded?
1536 HLoopInformation* other_loop_info = user->GetBlock()->GetLoopInformation();
Aart Bik482095d2016-10-10 15:39:10 -07001537 if (other_loop_info != nullptr && other_loop_info->IsIn(*loop_info)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -08001538 // If collect_loop_uses is set, simply keep adding those uses to the set.
1539 // Otherwise, reject uses inside the loop that were not already in the set.
1540 if (collect_loop_uses) {
1541 iset_->insert(user);
1542 continue;
1543 }
Aart Bik8c4a8542016-10-06 11:36:57 -07001544 return false;
1545 }
1546 ++*use_count;
1547 }
1548 }
1549 return true;
1550}
1551
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01001552bool HLoopOptimization::TryReplaceWithLastValue(HLoopInformation* loop_info,
1553 HInstruction* instruction,
1554 HBasicBlock* block) {
1555 // Try to replace outside uses with the last value.
Aart Bik807868e2016-11-03 17:51:43 -07001556 if (induction_range_.CanGenerateLastValue(instruction)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -08001557 HInstruction* replacement = induction_range_.GenerateLastValue(instruction, graph_, block);
1558 const HUseList<HInstruction*>& uses = instruction->GetUses();
1559 for (auto it = uses.begin(), end = uses.end(); it != end;) {
1560 HInstruction* user = it->GetUser();
1561 size_t index = it->GetIndex();
1562 ++it; // increment before replacing
1563 if (iset_->find(user) == iset_->end()) { // not excluded?
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01001564 if (kIsDebugBuild) {
1565 // We have checked earlier in 'IsOnlyUsedAfterLoop' that the use is after the loop.
1566 HLoopInformation* other_loop_info = user->GetBlock()->GetLoopInformation();
1567 CHECK(other_loop_info == nullptr || !other_loop_info->IsIn(*loop_info));
1568 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08001569 user->ReplaceInput(replacement, index);
1570 induction_range_.Replace(user, instruction, replacement); // update induction
1571 }
1572 }
1573 const HUseList<HEnvironment*>& env_uses = instruction->GetEnvUses();
1574 for (auto it = env_uses.begin(), end = env_uses.end(); it != end;) {
1575 HEnvironment* user = it->GetUser();
1576 size_t index = it->GetIndex();
1577 ++it; // increment before replacing
1578 if (iset_->find(user->GetHolder()) == iset_->end()) { // not excluded?
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01001579 HLoopInformation* other_loop_info = user->GetHolder()->GetBlock()->GetLoopInformation();
1580 // Only update environment uses after the loop.
1581 if (other_loop_info == nullptr || !other_loop_info->IsIn(*loop_info)) {
1582 user->RemoveAsUserOfInput(index);
1583 user->SetRawEnvAt(index, replacement);
1584 replacement->AddEnvUseAt(user, index);
1585 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08001586 }
1587 }
1588 induction_simplication_count_++;
Aart Bik807868e2016-11-03 17:51:43 -07001589 return true;
Aart Bik8c4a8542016-10-06 11:36:57 -07001590 }
Aart Bik807868e2016-11-03 17:51:43 -07001591 return false;
Aart Bik8c4a8542016-10-06 11:36:57 -07001592}
1593
Aart Bikf8f5a162017-02-06 15:35:29 -08001594bool HLoopOptimization::TryAssignLastValue(HLoopInformation* loop_info,
1595 HInstruction* instruction,
1596 HBasicBlock* block,
1597 bool collect_loop_uses) {
1598 // Assigning the last value is always successful if there are no uses.
1599 // Otherwise, it succeeds in a no early-exit loop by generating the
1600 // proper last value assignment.
1601 int32_t use_count = 0;
1602 return IsOnlyUsedAfterLoop(loop_info, instruction, collect_loop_uses, &use_count) &&
1603 (use_count == 0 ||
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01001604 (!IsEarlyExit(loop_info) && TryReplaceWithLastValue(loop_info, instruction, block)));
Aart Bikf8f5a162017-02-06 15:35:29 -08001605}
1606
Aart Bik6b69e0a2017-01-11 10:20:43 -08001607void HLoopOptimization::RemoveDeadInstructions(const HInstructionList& list) {
1608 for (HBackwardInstructionIterator i(list); !i.Done(); i.Advance()) {
1609 HInstruction* instruction = i.Current();
1610 if (instruction->IsDeadAndRemovable()) {
1611 simplified_ = true;
1612 instruction->GetBlock()->RemoveInstructionOrPhi(instruction);
1613 }
1614 }
1615}
1616
Aart Bik281c6812016-08-26 11:31:48 -07001617} // namespace art