blob: 9c8a632d4087ec2f91f64fb53a84d386c306198e [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
Aart Bik281c6812016-08-26 11:31:48 -0700425void HLoopOptimization::SimplifyInduction(LoopNode* node) {
426 HBasicBlock* header = node->loop_info->GetHeader();
427 HBasicBlock* preheader = node->loop_info->GetPreHeader();
Aart Bik8c4a8542016-10-06 11:36:57 -0700428 // Scan the phis in the header to find opportunities to simplify an induction
429 // cycle that is only used outside the loop. Replace these uses, if any, with
430 // the last value and remove the induction cycle.
431 // Examples: for (int i = 0; x != null; i++) { .... no i .... }
432 // for (int i = 0; i < 10; i++, k++) { .... no k .... } return k;
Aart Bik281c6812016-08-26 11:31:48 -0700433 for (HInstructionIterator it(header->GetPhis()); !it.Done(); it.Advance()) {
434 HPhi* phi = it.Current()->AsPhi();
Aart Bikf8f5a162017-02-06 15:35:29 -0800435 iset_->clear(); // prepare phi induction
436 if (TrySetPhiInduction(phi, /*restrict_uses*/ true) &&
437 TryAssignLastValue(node->loop_info, phi, preheader, /*collect_loop_uses*/ false)) {
Aart Bik8c4a8542016-10-06 11:36:57 -0700438 for (HInstruction* i : *iset_) {
439 RemoveFromCycle(i);
Aart Bik281c6812016-08-26 11:31:48 -0700440 }
Aart Bikdf7822e2016-12-06 10:05:30 -0800441 simplified_ = true;
Aart Bik482095d2016-10-10 15:39:10 -0700442 }
443 }
444}
445
446void HLoopOptimization::SimplifyBlocks(LoopNode* node) {
Aart Bikdf7822e2016-12-06 10:05:30 -0800447 // Iterate over all basic blocks in the loop-body.
448 for (HBlocksInLoopIterator it(*node->loop_info); !it.Done(); it.Advance()) {
449 HBasicBlock* block = it.Current();
450 // Remove dead instructions from the loop-body.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800451 RemoveDeadInstructions(block->GetPhis());
452 RemoveDeadInstructions(block->GetInstructions());
Aart Bikdf7822e2016-12-06 10:05:30 -0800453 // Remove trivial control flow blocks from the loop-body.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800454 if (block->GetPredecessors().size() == 1 &&
455 block->GetSuccessors().size() == 1 &&
456 block->GetSingleSuccessor()->GetPredecessors().size() == 1) {
Aart Bikdf7822e2016-12-06 10:05:30 -0800457 simplified_ = true;
Aart Bik6b69e0a2017-01-11 10:20:43 -0800458 block->MergeWith(block->GetSingleSuccessor());
Aart Bikdf7822e2016-12-06 10:05:30 -0800459 } else if (block->GetSuccessors().size() == 2) {
460 // Trivial if block can be bypassed to either branch.
461 HBasicBlock* succ0 = block->GetSuccessors()[0];
462 HBasicBlock* succ1 = block->GetSuccessors()[1];
463 HBasicBlock* meet0 = nullptr;
464 HBasicBlock* meet1 = nullptr;
465 if (succ0 != succ1 &&
466 IsGotoBlock(succ0, &meet0) &&
467 IsGotoBlock(succ1, &meet1) &&
468 meet0 == meet1 && // meets again
469 meet0 != block && // no self-loop
470 meet0->GetPhis().IsEmpty()) { // not used for merging
471 simplified_ = true;
472 succ0->DisconnectAndDelete();
473 if (block->Dominates(meet0)) {
474 block->RemoveDominatedBlock(meet0);
475 succ1->AddDominatedBlock(meet0);
476 meet0->SetDominator(succ1);
Aart Bike3dedc52016-11-02 17:50:27 -0700477 }
Aart Bik482095d2016-10-10 15:39:10 -0700478 }
Aart Bik281c6812016-08-26 11:31:48 -0700479 }
Aart Bikdf7822e2016-12-06 10:05:30 -0800480 }
Aart Bik281c6812016-08-26 11:31:48 -0700481}
482
Aart Bikf8f5a162017-02-06 15:35:29 -0800483void HLoopOptimization::OptimizeInnerLoop(LoopNode* node) {
Aart Bik281c6812016-08-26 11:31:48 -0700484 HBasicBlock* header = node->loop_info->GetHeader();
485 HBasicBlock* preheader = node->loop_info->GetPreHeader();
Aart Bik9abf8942016-10-14 09:49:42 -0700486 // Ensure loop header logic is finite.
Aart Bikf8f5a162017-02-06 15:35:29 -0800487 int64_t trip_count = 0;
488 if (!induction_range_.IsFinite(node->loop_info, &trip_count)) {
489 return;
Aart Bik9abf8942016-10-14 09:49:42 -0700490 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800491
Aart Bik281c6812016-08-26 11:31:48 -0700492 // Ensure there is only a single loop-body (besides the header).
493 HBasicBlock* body = nullptr;
494 for (HBlocksInLoopIterator it(*node->loop_info); !it.Done(); it.Advance()) {
495 if (it.Current() != header) {
496 if (body != nullptr) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800497 return;
Aart Bik281c6812016-08-26 11:31:48 -0700498 }
499 body = it.Current();
500 }
501 }
Andreas Gampef45d61c2017-06-07 10:29:33 -0700502 CHECK(body != nullptr);
Aart Bik281c6812016-08-26 11:31:48 -0700503 // Ensure there is only a single exit point.
504 if (header->GetSuccessors().size() != 2) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800505 return;
Aart Bik281c6812016-08-26 11:31:48 -0700506 }
507 HBasicBlock* exit = (header->GetSuccessors()[0] == body)
508 ? header->GetSuccessors()[1]
509 : header->GetSuccessors()[0];
Aart Bik8c4a8542016-10-06 11:36:57 -0700510 // Ensure exit can only be reached by exiting loop.
Aart Bik281c6812016-08-26 11:31:48 -0700511 if (exit->GetPredecessors().size() != 1) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800512 return;
Aart Bik281c6812016-08-26 11:31:48 -0700513 }
Aart Bik6b69e0a2017-01-11 10:20:43 -0800514 // Detect either an empty loop (no side effects other than plain iteration) or
515 // a trivial loop (just iterating once). Replace subsequent index uses, if any,
516 // with the last value and remove the loop, possibly after unrolling its body.
517 HInstruction* phi = header->GetFirstPhi();
Aart Bikf8f5a162017-02-06 15:35:29 -0800518 iset_->clear(); // prepare phi induction
519 if (TrySetSimpleLoopHeader(header)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -0800520 bool is_empty = IsEmptyBody(body);
Aart Bikf8f5a162017-02-06 15:35:29 -0800521 if ((is_empty || trip_count == 1) &&
522 TryAssignLastValue(node->loop_info, phi, preheader, /*collect_loop_uses*/ true)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -0800523 if (!is_empty) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800524 // Unroll the loop-body, which sees initial value of the index.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800525 phi->ReplaceWith(phi->InputAt(0));
526 preheader->MergeInstructionsWith(body);
527 }
528 body->DisconnectAndDelete();
529 exit->RemovePredecessor(header);
530 header->RemoveSuccessor(exit);
531 header->RemoveDominatedBlock(exit);
532 header->DisconnectAndDelete();
533 preheader->AddSuccessor(exit);
Aart Bikf8f5a162017-02-06 15:35:29 -0800534 preheader->AddInstruction(new (global_allocator_) HGoto());
Aart Bik6b69e0a2017-01-11 10:20:43 -0800535 preheader->AddDominatedBlock(exit);
536 exit->SetDominator(preheader);
537 RemoveLoop(node); // update hierarchy
Aart Bikf8f5a162017-02-06 15:35:29 -0800538 return;
539 }
540 }
541
542 // Vectorize loop, if possible and valid.
543 if (kEnableVectorization) {
544 iset_->clear(); // prepare phi induction
545 if (TrySetSimpleLoopHeader(header) &&
546 CanVectorize(node, body, trip_count) &&
547 TryAssignLastValue(node->loop_info, phi, preheader, /*collect_loop_uses*/ true)) {
548 Vectorize(node, body, exit, trip_count);
549 graph_->SetHasSIMD(true); // flag SIMD usage
550 return;
551 }
552 }
553}
554
555//
556// Loop vectorization. The implementation is based on the book by Aart J.C. Bik:
557// "The Software Vectorization Handbook. Applying Multimedia Extensions for Maximum Performance."
558// Intel Press, June, 2004 (http://www.aartbik.com/).
559//
560
561bool HLoopOptimization::CanVectorize(LoopNode* node, HBasicBlock* block, int64_t trip_count) {
562 // Reset vector bookkeeping.
563 vector_length_ = 0;
564 vector_refs_->clear();
565 vector_runtime_test_a_ =
566 vector_runtime_test_b_= nullptr;
567
568 // Phis in the loop-body prevent vectorization.
569 if (!block->GetPhis().IsEmpty()) {
570 return false;
571 }
572
573 // Scan the loop-body, starting a right-hand-side tree traversal at each left-hand-side
574 // occurrence, which allows passing down attributes down the use tree.
575 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
576 if (!VectorizeDef(node, it.Current(), /*generate_code*/ false)) {
577 return false; // failure to vectorize a left-hand-side
578 }
579 }
580
581 // Heuristics. Does vectorization seem profitable?
582 // TODO: refine
583 if (vector_length_ == 0) {
584 return false; // nothing found
585 } else if (0 < trip_count && trip_count < vector_length_) {
586 return false; // insufficient iterations
587 }
588
589 // Data dependence analysis. Find each pair of references with same type, where
590 // at least one is a write. Each such pair denotes a possible data dependence.
591 // This analysis exploits the property that differently typed arrays cannot be
592 // aliased, as well as the property that references either point to the same
593 // array or to two completely disjoint arrays, i.e., no partial aliasing.
594 // Other than a few simply heuristics, no detailed subscript analysis is done.
595 for (auto i = vector_refs_->begin(); i != vector_refs_->end(); ++i) {
596 for (auto j = i; ++j != vector_refs_->end(); ) {
597 if (i->type == j->type && (i->lhs || j->lhs)) {
598 // Found same-typed a[i+x] vs. b[i+y], where at least one is a write.
599 HInstruction* a = i->base;
600 HInstruction* b = j->base;
601 HInstruction* x = i->offset;
602 HInstruction* y = j->offset;
603 if (a == b) {
604 // Found a[i+x] vs. a[i+y]. Accept if x == y (loop-independent data dependence).
605 // Conservatively assume a loop-carried data dependence otherwise, and reject.
606 if (x != y) {
607 return false;
608 }
609 } else {
610 // Found a[i+x] vs. b[i+y]. Accept if x == y (at worst loop-independent data dependence).
611 // Conservatively assume a potential loop-carried data dependence otherwise, avoided by
612 // generating an explicit a != b disambiguation runtime test on the two references.
613 if (x != y) {
614 // For now, we reject after one test to avoid excessive overhead.
615 if (vector_runtime_test_a_ != nullptr) {
616 return false;
617 }
618 vector_runtime_test_a_ = a;
619 vector_runtime_test_b_ = b;
620 }
621 }
622 }
623 }
624 }
625
626 // Success!
627 return true;
628}
629
630void HLoopOptimization::Vectorize(LoopNode* node,
631 HBasicBlock* block,
632 HBasicBlock* exit,
633 int64_t trip_count) {
634 Primitive::Type induc_type = Primitive::kPrimInt;
635 HBasicBlock* header = node->loop_info->GetHeader();
636 HBasicBlock* preheader = node->loop_info->GetPreHeader();
637
638 // A cleanup is needed for any unknown trip count or for a known trip count
639 // with remainder iterations after vectorization.
640 bool needs_cleanup = trip_count == 0 || (trip_count % vector_length_) != 0;
641
642 // Adjust vector bookkeeping.
643 iset_->clear(); // prepare phi induction
644 bool is_simple_loop_header = TrySetSimpleLoopHeader(header); // fills iset_
645 DCHECK(is_simple_loop_header);
646
647 // Generate preheader:
648 // stc = <trip-count>;
649 // vtc = stc - stc % VL;
650 HInstruction* stc = induction_range_.GenerateTripCount(node->loop_info, graph_, preheader);
651 HInstruction* vtc = stc;
652 if (needs_cleanup) {
653 DCHECK(IsPowerOfTwo(vector_length_));
654 HInstruction* rem = Insert(
655 preheader, new (global_allocator_) HAnd(induc_type,
656 stc,
657 graph_->GetIntConstant(vector_length_ - 1)));
658 vtc = Insert(preheader, new (global_allocator_) HSub(induc_type, stc, rem));
659 }
660
661 // Generate runtime disambiguation test:
662 // vtc = a != b ? vtc : 0;
663 if (vector_runtime_test_a_ != nullptr) {
664 HInstruction* rt = Insert(
665 preheader,
666 new (global_allocator_) HNotEqual(vector_runtime_test_a_, vector_runtime_test_b_));
667 vtc = Insert(preheader,
668 new (global_allocator_) HSelect(rt, vtc, graph_->GetIntConstant(0), kNoDexPc));
669 needs_cleanup = true;
670 }
671
672 // Generate vector loop:
673 // for (i = 0; i < vtc; i += VL)
674 // <vectorized-loop-body>
675 vector_mode_ = kVector;
676 GenerateNewLoop(node,
677 block,
678 graph_->TransformLoopForVectorization(header, block, exit),
679 graph_->GetIntConstant(0),
680 vtc,
681 graph_->GetIntConstant(vector_length_));
682 HLoopInformation* vloop = vector_header_->GetLoopInformation();
683
684 // Generate cleanup loop, if needed:
685 // for ( ; i < stc; i += 1)
686 // <loop-body>
687 if (needs_cleanup) {
688 vector_mode_ = kSequential;
689 GenerateNewLoop(node,
690 block,
691 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
692 vector_phi_,
693 stc,
694 graph_->GetIntConstant(1));
695 }
696
697 // Remove the original loop by disconnecting the body block
698 // and removing all instructions from the header.
699 block->DisconnectAndDelete();
700 while (!header->GetFirstInstruction()->IsGoto()) {
701 header->RemoveInstruction(header->GetFirstInstruction());
702 }
703 // Update loop hierarchy: the old header now resides in the
704 // same outer loop as the old preheader.
705 header->SetLoopInformation(preheader->GetLoopInformation()); // outward
706 node->loop_info = vloop;
707}
708
709void HLoopOptimization::GenerateNewLoop(LoopNode* node,
710 HBasicBlock* block,
711 HBasicBlock* new_preheader,
712 HInstruction* lo,
713 HInstruction* hi,
714 HInstruction* step) {
715 Primitive::Type induc_type = Primitive::kPrimInt;
716 // Prepare new loop.
717 vector_map_->clear();
718 vector_preheader_ = new_preheader,
719 vector_header_ = vector_preheader_->GetSingleSuccessor();
720 vector_body_ = vector_header_->GetSuccessors()[1];
721 vector_phi_ = new (global_allocator_) HPhi(global_allocator_,
722 kNoRegNumber,
723 0,
724 HPhi::ToPhiType(induc_type));
Aart Bikb07d1bc2017-04-05 10:03:15 -0700725 // Generate header and prepare body.
Aart Bikf8f5a162017-02-06 15:35:29 -0800726 // for (i = lo; i < hi; i += step)
727 // <loop-body>
728 HInstruction* cond = new (global_allocator_) HAboveOrEqual(vector_phi_, hi);
729 vector_header_->AddPhi(vector_phi_);
730 vector_header_->AddInstruction(cond);
731 vector_header_->AddInstruction(new (global_allocator_) HIf(cond));
Aart Bikf8f5a162017-02-06 15:35:29 -0800732 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
733 bool vectorized_def = VectorizeDef(node, it.Current(), /*generate_code*/ true);
734 DCHECK(vectorized_def);
735 }
Aart Bik24b905f2017-04-06 09:59:06 -0700736 // Generate body from the instruction map, but in original program order.
Aart Bikb07d1bc2017-04-05 10:03:15 -0700737 HEnvironment* env = vector_header_->GetFirstInstruction()->GetEnvironment();
Aart Bikf8f5a162017-02-06 15:35:29 -0800738 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
739 auto i = vector_map_->find(it.Current());
740 if (i != vector_map_->end() && !i->second->IsInBlock()) {
Aart Bik24b905f2017-04-06 09:59:06 -0700741 Insert(vector_body_, i->second);
742 // Deal with instructions that need an environment, such as the scalar intrinsics.
Aart Bikf8f5a162017-02-06 15:35:29 -0800743 if (i->second->NeedsEnvironment()) {
Aart Bikb07d1bc2017-04-05 10:03:15 -0700744 i->second->CopyEnvironmentFromWithLoopPhiAdjustment(env, vector_header_);
Aart Bikf8f5a162017-02-06 15:35:29 -0800745 }
746 }
747 }
748 // Finalize increment and phi.
749 HInstruction* inc = new (global_allocator_) HAdd(induc_type, vector_phi_, step);
750 vector_phi_->AddInput(lo);
751 vector_phi_->AddInput(Insert(vector_body_, inc));
752}
753
754// TODO: accept reductions at left-hand-side, mixed-type store idioms, etc.
755bool HLoopOptimization::VectorizeDef(LoopNode* node,
756 HInstruction* instruction,
757 bool generate_code) {
758 // Accept a left-hand-side array base[index] for
759 // (1) supported vector type,
760 // (2) loop-invariant base,
761 // (3) unit stride index,
762 // (4) vectorizable right-hand-side value.
763 uint64_t restrictions = kNone;
764 if (instruction->IsArraySet()) {
765 Primitive::Type type = instruction->AsArraySet()->GetComponentType();
766 HInstruction* base = instruction->InputAt(0);
767 HInstruction* index = instruction->InputAt(1);
768 HInstruction* value = instruction->InputAt(2);
769 HInstruction* offset = nullptr;
770 if (TrySetVectorType(type, &restrictions) &&
771 node->loop_info->IsDefinedOutOfTheLoop(base) &&
Aart Bikfa762962017-04-07 11:33:37 -0700772 induction_range_.IsUnitStride(instruction, index, &offset) &&
Aart Bikf8f5a162017-02-06 15:35:29 -0800773 VectorizeUse(node, value, generate_code, type, restrictions)) {
774 if (generate_code) {
775 GenerateVecSub(index, offset);
776 GenerateVecMem(instruction, vector_map_->Get(index), vector_map_->Get(value), type);
777 } else {
778 vector_refs_->insert(ArrayReference(base, offset, type, /*lhs*/ true));
779 }
Aart Bik6b69e0a2017-01-11 10:20:43 -0800780 return true;
781 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800782 return false;
783 }
784 // Branch back okay.
785 if (instruction->IsGoto()) {
786 return true;
787 }
788 // Otherwise accept only expressions with no effects outside the immediate loop-body.
789 // Note that actual uses are inspected during right-hand-side tree traversal.
790 return !IsUsedOutsideLoop(node->loop_info, instruction) && !instruction->DoesAnyWrite();
791}
792
Aart Bik304c8a52017-05-23 11:01:13 -0700793// TODO: saturation arithmetic.
Aart Bikf8f5a162017-02-06 15:35:29 -0800794bool HLoopOptimization::VectorizeUse(LoopNode* node,
795 HInstruction* instruction,
796 bool generate_code,
797 Primitive::Type type,
798 uint64_t restrictions) {
799 // Accept anything for which code has already been generated.
800 if (generate_code) {
801 if (vector_map_->find(instruction) != vector_map_->end()) {
802 return true;
803 }
804 }
805 // Continue the right-hand-side tree traversal, passing in proper
806 // types and vector restrictions along the way. During code generation,
807 // all new nodes are drawn from the global allocator.
808 if (node->loop_info->IsDefinedOutOfTheLoop(instruction)) {
809 // Accept invariant use, using scalar expansion.
810 if (generate_code) {
811 GenerateVecInv(instruction, type);
812 }
813 return true;
814 } else if (instruction->IsArrayGet()) {
Goran Jakovljevic19680d32017-05-11 10:38:36 +0200815 // Deal with vector restrictions.
816 if (instruction->AsArrayGet()->IsStringCharAt() &&
817 HasVectorRestrictions(restrictions, kNoStringCharAt)) {
818 return false;
819 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800820 // Accept a right-hand-side array base[index] for
821 // (1) exact matching vector type,
822 // (2) loop-invariant base,
823 // (3) unit stride index,
824 // (4) vectorizable right-hand-side value.
825 HInstruction* base = instruction->InputAt(0);
826 HInstruction* index = instruction->InputAt(1);
827 HInstruction* offset = nullptr;
828 if (type == instruction->GetType() &&
829 node->loop_info->IsDefinedOutOfTheLoop(base) &&
Aart Bikfa762962017-04-07 11:33:37 -0700830 induction_range_.IsUnitStride(instruction, index, &offset)) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800831 if (generate_code) {
832 GenerateVecSub(index, offset);
833 GenerateVecMem(instruction, vector_map_->Get(index), nullptr, type);
834 } else {
835 vector_refs_->insert(ArrayReference(base, offset, type, /*lhs*/ false));
836 }
837 return true;
838 }
839 } else if (instruction->IsTypeConversion()) {
840 // Accept particular type conversions.
841 HTypeConversion* conversion = instruction->AsTypeConversion();
842 HInstruction* opa = conversion->InputAt(0);
843 Primitive::Type from = conversion->GetInputType();
844 Primitive::Type to = conversion->GetResultType();
845 if ((to == Primitive::kPrimByte ||
846 to == Primitive::kPrimChar ||
847 to == Primitive::kPrimShort) && from == Primitive::kPrimInt) {
848 // Accept a "narrowing" type conversion from a "wider" computation for
849 // (1) conversion into final required type,
850 // (2) vectorizable operand,
851 // (3) "wider" operations cannot bring in higher order bits.
852 if (to == type && VectorizeUse(node, opa, generate_code, type, restrictions | kNoHiBits)) {
853 if (generate_code) {
854 if (vector_mode_ == kVector) {
855 vector_map_->Put(instruction, vector_map_->Get(opa)); // operand pass-through
856 } else {
857 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
858 }
859 }
860 return true;
861 }
862 } else if (to == Primitive::kPrimFloat && from == Primitive::kPrimInt) {
863 DCHECK_EQ(to, type);
864 // Accept int to float conversion for
865 // (1) supported int,
866 // (2) vectorizable operand.
867 if (TrySetVectorType(from, &restrictions) &&
868 VectorizeUse(node, opa, generate_code, from, restrictions)) {
869 if (generate_code) {
870 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
871 }
872 return true;
873 }
874 }
875 return false;
876 } else if (instruction->IsNeg() || instruction->IsNot() || instruction->IsBooleanNot()) {
877 // Accept unary operator for vectorizable operand.
878 HInstruction* opa = instruction->InputAt(0);
879 if (VectorizeUse(node, opa, generate_code, type, restrictions)) {
880 if (generate_code) {
881 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
882 }
883 return true;
884 }
885 } else if (instruction->IsAdd() || instruction->IsSub() ||
886 instruction->IsMul() || instruction->IsDiv() ||
887 instruction->IsAnd() || instruction->IsOr() || instruction->IsXor()) {
888 // Deal with vector restrictions.
889 if ((instruction->IsMul() && HasVectorRestrictions(restrictions, kNoMul)) ||
890 (instruction->IsDiv() && HasVectorRestrictions(restrictions, kNoDiv))) {
891 return false;
892 }
893 // Accept binary operator for vectorizable operands.
894 HInstruction* opa = instruction->InputAt(0);
895 HInstruction* opb = instruction->InputAt(1);
896 if (VectorizeUse(node, opa, generate_code, type, restrictions) &&
897 VectorizeUse(node, opb, generate_code, type, restrictions)) {
898 if (generate_code) {
899 GenerateVecOp(instruction, vector_map_->Get(opa), vector_map_->Get(opb), type);
900 }
901 return true;
902 }
903 } else if (instruction->IsShl() || instruction->IsShr() || instruction->IsUShr()) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700904 // Recognize vectorization idioms.
905 if (VectorizeHalvingAddIdiom(node, instruction, generate_code, type, restrictions)) {
906 return true;
907 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800908 // Deal with vector restrictions.
Aart Bik304c8a52017-05-23 11:01:13 -0700909 HInstruction* opa = instruction->InputAt(0);
910 HInstruction* opb = instruction->InputAt(1);
911 HInstruction* r = opa;
912 bool is_unsigned = false;
Aart Bikf8f5a162017-02-06 15:35:29 -0800913 if ((HasVectorRestrictions(restrictions, kNoShift)) ||
914 (instruction->IsShr() && HasVectorRestrictions(restrictions, kNoShr))) {
915 return false; // unsupported instruction
Aart Bik304c8a52017-05-23 11:01:13 -0700916 } else if (HasVectorRestrictions(restrictions, kNoHiBits)) {
917 // Shifts right need extra care to account for higher order bits.
918 // TODO: less likely shr/unsigned and ushr/signed can by flipping signess.
919 if (instruction->IsShr() &&
920 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || is_unsigned)) {
921 return false; // reject, unless all operands are sign-extension narrower
922 } else if (instruction->IsUShr() &&
923 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || !is_unsigned)) {
924 return false; // reject, unless all operands are zero-extension narrower
925 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800926 }
927 // Accept shift operator for vectorizable/invariant operands.
928 // TODO: accept symbolic, albeit loop invariant shift factors.
Aart Bik304c8a52017-05-23 11:01:13 -0700929 DCHECK(r != nullptr);
930 if (generate_code && vector_mode_ != kVector) { // de-idiom
931 r = opa;
932 }
Aart Bik50e20d52017-05-05 14:07:29 -0700933 int64_t distance = 0;
Aart Bik304c8a52017-05-23 11:01:13 -0700934 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
Aart Bik50e20d52017-05-05 14:07:29 -0700935 IsInt64AndGet(opb, /*out*/ &distance)) {
Aart Bik65ffd8e2017-05-01 16:50:45 -0700936 // Restrict shift distance to packed data type width.
937 int64_t max_distance = Primitive::ComponentSize(type) * 8;
938 if (0 <= distance && distance < max_distance) {
939 if (generate_code) {
Aart Bik304c8a52017-05-23 11:01:13 -0700940 GenerateVecOp(instruction, vector_map_->Get(r), opb, type);
Aart Bik65ffd8e2017-05-01 16:50:45 -0700941 }
942 return true;
Aart Bikf8f5a162017-02-06 15:35:29 -0800943 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800944 }
945 } else if (instruction->IsInvokeStaticOrDirect()) {
Aart Bik6daebeb2017-04-03 14:35:41 -0700946 // Accept particular intrinsics.
947 HInvokeStaticOrDirect* invoke = instruction->AsInvokeStaticOrDirect();
948 switch (invoke->GetIntrinsic()) {
949 case Intrinsics::kMathAbsInt:
950 case Intrinsics::kMathAbsLong:
951 case Intrinsics::kMathAbsFloat:
952 case Intrinsics::kMathAbsDouble: {
953 // Deal with vector restrictions.
Aart Bik304c8a52017-05-23 11:01:13 -0700954 HInstruction* opa = instruction->InputAt(0);
955 HInstruction* r = opa;
956 bool is_unsigned = false;
957 if (HasVectorRestrictions(restrictions, kNoAbs)) {
Aart Bik6daebeb2017-04-03 14:35:41 -0700958 return false;
Aart Bik304c8a52017-05-23 11:01:13 -0700959 } else if (HasVectorRestrictions(restrictions, kNoHiBits) &&
960 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || is_unsigned)) {
961 return false; // reject, unless operand is sign-extension narrower
Aart Bik6daebeb2017-04-03 14:35:41 -0700962 }
963 // Accept ABS(x) for vectorizable operand.
Aart Bik304c8a52017-05-23 11:01:13 -0700964 DCHECK(r != nullptr);
965 if (generate_code && vector_mode_ != kVector) { // de-idiom
966 r = opa;
967 }
968 if (VectorizeUse(node, r, generate_code, type, restrictions)) {
Aart Bik6daebeb2017-04-03 14:35:41 -0700969 if (generate_code) {
Aart Bik304c8a52017-05-23 11:01:13 -0700970 GenerateVecOp(instruction, vector_map_->Get(r), nullptr, type);
Aart Bik6daebeb2017-04-03 14:35:41 -0700971 }
972 return true;
973 }
974 return false;
975 }
Aart Bikc8e93c72017-05-10 10:49:22 -0700976 case Intrinsics::kMathMinIntInt:
977 case Intrinsics::kMathMinLongLong:
978 case Intrinsics::kMathMinFloatFloat:
979 case Intrinsics::kMathMinDoubleDouble:
980 case Intrinsics::kMathMaxIntInt:
981 case Intrinsics::kMathMaxLongLong:
982 case Intrinsics::kMathMaxFloatFloat:
983 case Intrinsics::kMathMaxDoubleDouble: {
984 // Deal with vector restrictions.
Nicolas Geoffray92316902017-05-23 08:06:07 +0000985 HInstruction* opa = instruction->InputAt(0);
986 HInstruction* opb = instruction->InputAt(1);
Aart Bik304c8a52017-05-23 11:01:13 -0700987 HInstruction* r = opa;
988 HInstruction* s = opb;
989 bool is_unsigned = false;
990 if (HasVectorRestrictions(restrictions, kNoMinMax)) {
991 return false;
992 } else if (HasVectorRestrictions(restrictions, kNoHiBits) &&
993 !IsNarrowerOperands(opa, opb, type, &r, &s, &is_unsigned)) {
994 return false; // reject, unless all operands are same-extension narrower
995 }
996 // Accept MIN/MAX(x, y) for vectorizable operands.
997 DCHECK(r != nullptr && s != nullptr);
998 if (generate_code && vector_mode_ != kVector) { // de-idiom
999 r = opa;
1000 s = opb;
1001 }
1002 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
1003 VectorizeUse(node, s, generate_code, type, restrictions)) {
Aart Bikc8e93c72017-05-10 10:49:22 -07001004 if (generate_code) {
Aart Bik304c8a52017-05-23 11:01:13 -07001005 GenerateVecOp(
1006 instruction, vector_map_->Get(r), vector_map_->Get(s), type, is_unsigned);
Aart Bikc8e93c72017-05-10 10:49:22 -07001007 }
1008 return true;
1009 }
1010 return false;
1011 }
Aart Bik6daebeb2017-04-03 14:35:41 -07001012 default:
1013 return false;
1014 } // switch
Aart Bik281c6812016-08-26 11:31:48 -07001015 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08001016 return false;
Aart Bik281c6812016-08-26 11:31:48 -07001017}
1018
Aart Bikf8f5a162017-02-06 15:35:29 -08001019bool HLoopOptimization::TrySetVectorType(Primitive::Type type, uint64_t* restrictions) {
1020 const InstructionSetFeatures* features = compiler_driver_->GetInstructionSetFeatures();
1021 switch (compiler_driver_->GetInstructionSet()) {
1022 case kArm:
1023 case kThumb2:
1024 return false;
1025 case kArm64:
1026 // Allow vectorization for all ARM devices, because Android assumes that
Artem Serovd4bccf12017-04-03 18:47:32 +01001027 // ARMv8 AArch64 always supports advanced SIMD.
Aart Bikf8f5a162017-02-06 15:35:29 -08001028 switch (type) {
1029 case Primitive::kPrimBoolean:
1030 case Primitive::kPrimByte:
Aart Bik304c8a52017-05-23 11:01:13 -07001031 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +01001032 return TrySetVectorLength(16);
Aart Bikf8f5a162017-02-06 15:35:29 -08001033 case Primitive::kPrimChar:
1034 case Primitive::kPrimShort:
Aart Bik304c8a52017-05-23 11:01:13 -07001035 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +01001036 return TrySetVectorLength(8);
Aart Bikf8f5a162017-02-06 15:35:29 -08001037 case Primitive::kPrimInt:
1038 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +01001039 return TrySetVectorLength(4);
Artem Serovb31f91f2017-04-05 11:31:19 +01001040 case Primitive::kPrimLong:
Aart Bikc8e93c72017-05-10 10:49:22 -07001041 *restrictions |= kNoDiv | kNoMul | kNoMinMax;
Aart Bikf8f5a162017-02-06 15:35:29 -08001042 return TrySetVectorLength(2);
1043 case Primitive::kPrimFloat:
Artem Serovd4bccf12017-04-03 18:47:32 +01001044 return TrySetVectorLength(4);
Artem Serovb31f91f2017-04-05 11:31:19 +01001045 case Primitive::kPrimDouble:
Aart Bikf8f5a162017-02-06 15:35:29 -08001046 return TrySetVectorLength(2);
1047 default:
1048 return false;
1049 }
1050 case kX86:
1051 case kX86_64:
1052 // Allow vectorization for SSE4-enabled X86 devices only (128-bit vectors).
1053 if (features->AsX86InstructionSetFeatures()->HasSSE4_1()) {
1054 switch (type) {
1055 case Primitive::kPrimBoolean:
1056 case Primitive::kPrimByte:
Aart Bikf3e61ee2017-04-12 17:09:20 -07001057 *restrictions |= kNoMul | kNoDiv | kNoShift | kNoAbs | kNoSignedHAdd | kNoUnroundedHAdd;
Aart Bikf8f5a162017-02-06 15:35:29 -08001058 return TrySetVectorLength(16);
1059 case Primitive::kPrimChar:
1060 case Primitive::kPrimShort:
Aart Bikf3e61ee2017-04-12 17:09:20 -07001061 *restrictions |= kNoDiv | kNoAbs | kNoSignedHAdd | kNoUnroundedHAdd;
Aart Bikf8f5a162017-02-06 15:35:29 -08001062 return TrySetVectorLength(8);
1063 case Primitive::kPrimInt:
1064 *restrictions |= kNoDiv;
1065 return TrySetVectorLength(4);
1066 case Primitive::kPrimLong:
Aart Bikc8e93c72017-05-10 10:49:22 -07001067 *restrictions |= kNoMul | kNoDiv | kNoShr | kNoAbs | kNoMinMax;
Aart Bikf8f5a162017-02-06 15:35:29 -08001068 return TrySetVectorLength(2);
1069 case Primitive::kPrimFloat:
Aart Bikc8e93c72017-05-10 10:49:22 -07001070 *restrictions |= kNoMinMax; // -0.0 vs +0.0
Aart Bikf8f5a162017-02-06 15:35:29 -08001071 return TrySetVectorLength(4);
1072 case Primitive::kPrimDouble:
Aart Bikc8e93c72017-05-10 10:49:22 -07001073 *restrictions |= kNoMinMax; // -0.0 vs +0.0
Aart Bikf8f5a162017-02-06 15:35:29 -08001074 return TrySetVectorLength(2);
1075 default:
1076 break;
1077 } // switch type
1078 }
1079 return false;
1080 case kMips:
Aart Bikf8f5a162017-02-06 15:35:29 -08001081 // TODO: implement MIPS SIMD.
1082 return false;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001083 case kMips64:
1084 if (features->AsMips64InstructionSetFeatures()->HasMsa()) {
1085 switch (type) {
1086 case Primitive::kPrimBoolean:
1087 case Primitive::kPrimByte:
Goran Jakovljevic8fea1e12017-06-06 13:28:42 +02001088 *restrictions |= kNoDiv;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001089 return TrySetVectorLength(16);
1090 case Primitive::kPrimChar:
1091 case Primitive::kPrimShort:
Goran Jakovljevic8fea1e12017-06-06 13:28:42 +02001092 *restrictions |= kNoDiv | kNoStringCharAt;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001093 return TrySetVectorLength(8);
1094 case Primitive::kPrimInt:
Goran Jakovljevic8fea1e12017-06-06 13:28:42 +02001095 *restrictions |= kNoDiv;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001096 return TrySetVectorLength(4);
1097 case Primitive::kPrimLong:
Goran Jakovljevic8fea1e12017-06-06 13:28:42 +02001098 *restrictions |= kNoDiv;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001099 return TrySetVectorLength(2);
1100 case Primitive::kPrimFloat:
Goran Jakovljevic8fea1e12017-06-06 13:28:42 +02001101 *restrictions |= kNoMinMax; // min/max(x, NaN)
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001102 return TrySetVectorLength(4);
1103 case Primitive::kPrimDouble:
Goran Jakovljevic8fea1e12017-06-06 13:28:42 +02001104 *restrictions |= kNoMinMax; // min/max(x, NaN)
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001105 return TrySetVectorLength(2);
1106 default:
1107 break;
1108 } // switch type
1109 }
1110 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001111 default:
1112 return false;
1113 } // switch instruction set
1114}
1115
1116bool HLoopOptimization::TrySetVectorLength(uint32_t length) {
1117 DCHECK(IsPowerOfTwo(length) && length >= 2u);
1118 // First time set?
1119 if (vector_length_ == 0) {
1120 vector_length_ = length;
1121 }
1122 // Different types are acceptable within a loop-body, as long as all the corresponding vector
1123 // lengths match exactly to obtain a uniform traversal through the vector iteration space
1124 // (idiomatic exceptions to this rule can be handled by further unrolling sub-expressions).
1125 return vector_length_ == length;
1126}
1127
1128void HLoopOptimization::GenerateVecInv(HInstruction* org, Primitive::Type type) {
1129 if (vector_map_->find(org) == vector_map_->end()) {
1130 // In scalar code, just use a self pass-through for scalar invariants
1131 // (viz. expression remains itself).
1132 if (vector_mode_ == kSequential) {
1133 vector_map_->Put(org, org);
1134 return;
1135 }
1136 // In vector code, explicit scalar expansion is needed.
1137 HInstruction* vector = new (global_allocator_) HVecReplicateScalar(
1138 global_allocator_, org, type, vector_length_);
1139 vector_map_->Put(org, Insert(vector_preheader_, vector));
1140 }
1141}
1142
1143void HLoopOptimization::GenerateVecSub(HInstruction* org, HInstruction* offset) {
1144 if (vector_map_->find(org) == vector_map_->end()) {
1145 HInstruction* subscript = vector_phi_;
1146 if (offset != nullptr) {
1147 subscript = new (global_allocator_) HAdd(Primitive::kPrimInt, subscript, offset);
1148 if (org->IsPhi()) {
1149 Insert(vector_body_, subscript); // lacks layout placeholder
1150 }
1151 }
1152 vector_map_->Put(org, subscript);
1153 }
1154}
1155
1156void HLoopOptimization::GenerateVecMem(HInstruction* org,
1157 HInstruction* opa,
1158 HInstruction* opb,
1159 Primitive::Type type) {
1160 HInstruction* vector = nullptr;
1161 if (vector_mode_ == kVector) {
1162 // Vector store or load.
1163 if (opb != nullptr) {
1164 vector = new (global_allocator_) HVecStore(
1165 global_allocator_, org->InputAt(0), opa, opb, type, vector_length_);
1166 } else {
Aart Bikdb14fcf2017-04-25 15:53:58 -07001167 bool is_string_char_at = org->AsArrayGet()->IsStringCharAt();
Aart Bikf8f5a162017-02-06 15:35:29 -08001168 vector = new (global_allocator_) HVecLoad(
Aart Bikdb14fcf2017-04-25 15:53:58 -07001169 global_allocator_, org->InputAt(0), opa, type, vector_length_, is_string_char_at);
Aart Bikf8f5a162017-02-06 15:35:29 -08001170 }
1171 } else {
1172 // Scalar store or load.
1173 DCHECK(vector_mode_ == kSequential);
1174 if (opb != nullptr) {
1175 vector = new (global_allocator_) HArraySet(org->InputAt(0), opa, opb, type, kNoDexPc);
1176 } else {
Aart Bikdb14fcf2017-04-25 15:53:58 -07001177 bool is_string_char_at = org->AsArrayGet()->IsStringCharAt();
1178 vector = new (global_allocator_) HArrayGet(
1179 org->InputAt(0), opa, type, kNoDexPc, is_string_char_at);
Aart Bikf8f5a162017-02-06 15:35:29 -08001180 }
1181 }
1182 vector_map_->Put(org, vector);
1183}
1184
1185#define GENERATE_VEC(x, y) \
1186 if (vector_mode_ == kVector) { \
1187 vector = (x); \
1188 } else { \
1189 DCHECK(vector_mode_ == kSequential); \
1190 vector = (y); \
1191 } \
1192 break;
1193
1194void HLoopOptimization::GenerateVecOp(HInstruction* org,
1195 HInstruction* opa,
1196 HInstruction* opb,
Aart Bik304c8a52017-05-23 11:01:13 -07001197 Primitive::Type type,
1198 bool is_unsigned) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001199 if (vector_mode_ == kSequential) {
Aart Bik304c8a52017-05-23 11:01:13 -07001200 // Non-converting scalar code follows implicit integral promotion.
1201 if (!org->IsTypeConversion() && (type == Primitive::kPrimBoolean ||
1202 type == Primitive::kPrimByte ||
1203 type == Primitive::kPrimChar ||
1204 type == Primitive::kPrimShort)) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001205 type = Primitive::kPrimInt;
1206 }
1207 }
1208 HInstruction* vector = nullptr;
1209 switch (org->GetKind()) {
1210 case HInstruction::kNeg:
1211 DCHECK(opb == nullptr);
1212 GENERATE_VEC(
1213 new (global_allocator_) HVecNeg(global_allocator_, opa, type, vector_length_),
1214 new (global_allocator_) HNeg(type, opa));
1215 case HInstruction::kNot:
1216 DCHECK(opb == nullptr);
1217 GENERATE_VEC(
1218 new (global_allocator_) HVecNot(global_allocator_, opa, type, vector_length_),
1219 new (global_allocator_) HNot(type, opa));
1220 case HInstruction::kBooleanNot:
1221 DCHECK(opb == nullptr);
1222 GENERATE_VEC(
1223 new (global_allocator_) HVecNot(global_allocator_, opa, type, vector_length_),
1224 new (global_allocator_) HBooleanNot(opa));
1225 case HInstruction::kTypeConversion:
1226 DCHECK(opb == nullptr);
1227 GENERATE_VEC(
1228 new (global_allocator_) HVecCnv(global_allocator_, opa, type, vector_length_),
1229 new (global_allocator_) HTypeConversion(type, opa, kNoDexPc));
1230 case HInstruction::kAdd:
1231 GENERATE_VEC(
1232 new (global_allocator_) HVecAdd(global_allocator_, opa, opb, type, vector_length_),
1233 new (global_allocator_) HAdd(type, opa, opb));
1234 case HInstruction::kSub:
1235 GENERATE_VEC(
1236 new (global_allocator_) HVecSub(global_allocator_, opa, opb, type, vector_length_),
1237 new (global_allocator_) HSub(type, opa, opb));
1238 case HInstruction::kMul:
1239 GENERATE_VEC(
1240 new (global_allocator_) HVecMul(global_allocator_, opa, opb, type, vector_length_),
1241 new (global_allocator_) HMul(type, opa, opb));
1242 case HInstruction::kDiv:
1243 GENERATE_VEC(
1244 new (global_allocator_) HVecDiv(global_allocator_, opa, opb, type, vector_length_),
1245 new (global_allocator_) HDiv(type, opa, opb, kNoDexPc));
1246 case HInstruction::kAnd:
1247 GENERATE_VEC(
1248 new (global_allocator_) HVecAnd(global_allocator_, opa, opb, type, vector_length_),
1249 new (global_allocator_) HAnd(type, opa, opb));
1250 case HInstruction::kOr:
1251 GENERATE_VEC(
1252 new (global_allocator_) HVecOr(global_allocator_, opa, opb, type, vector_length_),
1253 new (global_allocator_) HOr(type, opa, opb));
1254 case HInstruction::kXor:
1255 GENERATE_VEC(
1256 new (global_allocator_) HVecXor(global_allocator_, opa, opb, type, vector_length_),
1257 new (global_allocator_) HXor(type, opa, opb));
1258 case HInstruction::kShl:
1259 GENERATE_VEC(
1260 new (global_allocator_) HVecShl(global_allocator_, opa, opb, type, vector_length_),
1261 new (global_allocator_) HShl(type, opa, opb));
1262 case HInstruction::kShr:
1263 GENERATE_VEC(
1264 new (global_allocator_) HVecShr(global_allocator_, opa, opb, type, vector_length_),
1265 new (global_allocator_) HShr(type, opa, opb));
1266 case HInstruction::kUShr:
1267 GENERATE_VEC(
1268 new (global_allocator_) HVecUShr(global_allocator_, opa, opb, type, vector_length_),
1269 new (global_allocator_) HUShr(type, opa, opb));
1270 case HInstruction::kInvokeStaticOrDirect: {
Aart Bik6daebeb2017-04-03 14:35:41 -07001271 HInvokeStaticOrDirect* invoke = org->AsInvokeStaticOrDirect();
1272 if (vector_mode_ == kVector) {
1273 switch (invoke->GetIntrinsic()) {
1274 case Intrinsics::kMathAbsInt:
1275 case Intrinsics::kMathAbsLong:
1276 case Intrinsics::kMathAbsFloat:
1277 case Intrinsics::kMathAbsDouble:
1278 DCHECK(opb == nullptr);
1279 vector = new (global_allocator_) HVecAbs(global_allocator_, opa, type, vector_length_);
1280 break;
Aart Bikc8e93c72017-05-10 10:49:22 -07001281 case Intrinsics::kMathMinIntInt:
1282 case Intrinsics::kMathMinLongLong:
1283 case Intrinsics::kMathMinFloatFloat:
1284 case Intrinsics::kMathMinDoubleDouble: {
Aart Bikc8e93c72017-05-10 10:49:22 -07001285 vector = new (global_allocator_)
1286 HVecMin(global_allocator_, opa, opb, type, vector_length_, is_unsigned);
1287 break;
1288 }
1289 case Intrinsics::kMathMaxIntInt:
1290 case Intrinsics::kMathMaxLongLong:
1291 case Intrinsics::kMathMaxFloatFloat:
1292 case Intrinsics::kMathMaxDoubleDouble: {
Aart Bikc8e93c72017-05-10 10:49:22 -07001293 vector = new (global_allocator_)
1294 HVecMax(global_allocator_, opa, opb, type, vector_length_, is_unsigned);
1295 break;
1296 }
Aart Bik6daebeb2017-04-03 14:35:41 -07001297 default:
1298 LOG(FATAL) << "Unsupported SIMD intrinsic";
1299 UNREACHABLE();
1300 } // switch invoke
1301 } else {
Aart Bik24b905f2017-04-06 09:59:06 -07001302 // In scalar code, simply clone the method invoke, and replace its operands with the
1303 // corresponding new scalar instructions in the loop. The instruction will get an
1304 // environment while being inserted from the instruction map in original program order.
Aart Bik6daebeb2017-04-03 14:35:41 -07001305 DCHECK(vector_mode_ == kSequential);
Aart Bik6e92fb32017-06-05 14:05:09 -07001306 size_t num_args = invoke->GetNumberOfArguments();
Aart Bik6daebeb2017-04-03 14:35:41 -07001307 HInvokeStaticOrDirect* new_invoke = new (global_allocator_) HInvokeStaticOrDirect(
1308 global_allocator_,
Aart Bik6e92fb32017-06-05 14:05:09 -07001309 num_args,
Aart Bik6daebeb2017-04-03 14:35:41 -07001310 invoke->GetType(),
1311 invoke->GetDexPc(),
1312 invoke->GetDexMethodIndex(),
1313 invoke->GetResolvedMethod(),
1314 invoke->GetDispatchInfo(),
1315 invoke->GetInvokeType(),
1316 invoke->GetTargetMethod(),
1317 invoke->GetClinitCheckRequirement());
1318 HInputsRef inputs = invoke->GetInputs();
Aart Bik6e92fb32017-06-05 14:05:09 -07001319 size_t num_inputs = inputs.size();
1320 DCHECK_LE(num_args, num_inputs);
1321 DCHECK_EQ(num_inputs, new_invoke->GetInputs().size()); // both invokes agree
1322 for (size_t index = 0; index < num_inputs; ++index) {
1323 HInstruction* new_input = index < num_args
1324 ? vector_map_->Get(inputs[index])
1325 : inputs[index]; // beyond arguments: just pass through
1326 new_invoke->SetArgumentAt(index, new_input);
Aart Bik6daebeb2017-04-03 14:35:41 -07001327 }
Aart Bik98990262017-04-10 13:15:57 -07001328 new_invoke->SetIntrinsic(invoke->GetIntrinsic(),
1329 kNeedsEnvironmentOrCache,
1330 kNoSideEffects,
1331 kNoThrow);
Aart Bik6daebeb2017-04-03 14:35:41 -07001332 vector = new_invoke;
1333 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001334 break;
1335 }
1336 default:
1337 break;
1338 } // switch
1339 CHECK(vector != nullptr) << "Unsupported SIMD operator";
1340 vector_map_->Put(org, vector);
1341}
1342
1343#undef GENERATE_VEC
1344
1345//
Aart Bikf3e61ee2017-04-12 17:09:20 -07001346// Vectorization idioms.
1347//
1348
1349// Method recognizes the following idioms:
1350// rounding halving add (a + b + 1) >> 1 for unsigned/signed operands a, b
1351// regular halving add (a + b) >> 1 for unsigned/signed operands a, b
1352// Provided that the operands are promoted to a wider form to do the arithmetic and
1353// then cast back to narrower form, the idioms can be mapped into efficient SIMD
1354// implementation that operates directly in narrower form (plus one extra bit).
1355// TODO: current version recognizes implicit byte/short/char widening only;
1356// explicit widening from int to long could be added later.
1357bool HLoopOptimization::VectorizeHalvingAddIdiom(LoopNode* node,
1358 HInstruction* instruction,
1359 bool generate_code,
1360 Primitive::Type type,
1361 uint64_t restrictions) {
1362 // Test for top level arithmetic shift right x >> 1 or logical shift right x >>> 1
Aart Bik304c8a52017-05-23 11:01:13 -07001363 // (note whether the sign bit in wider precision is shifted in has no effect
Aart Bikf3e61ee2017-04-12 17:09:20 -07001364 // on the narrow precision computed by the idiom).
Aart Bik5f805002017-05-16 16:42:41 -07001365 int64_t distance = 0;
Aart Bikf3e61ee2017-04-12 17:09:20 -07001366 if ((instruction->IsShr() ||
1367 instruction->IsUShr()) &&
Aart Bik5f805002017-05-16 16:42:41 -07001368 IsInt64AndGet(instruction->InputAt(1), /*out*/ &distance) && distance == 1) {
1369 // Test for (a + b + c) >> 1 for optional constant c.
1370 HInstruction* a = nullptr;
1371 HInstruction* b = nullptr;
1372 int64_t c = 0;
1373 if (IsAddConst(instruction->InputAt(0), /*out*/ &a, /*out*/ &b, /*out*/ &c)) {
Aart Bik304c8a52017-05-23 11:01:13 -07001374 DCHECK(a != nullptr && b != nullptr);
Aart Bik5f805002017-05-16 16:42:41 -07001375 // Accept c == 1 (rounded) or c == 0 (not rounded).
1376 bool is_rounded = false;
1377 if (c == 1) {
1378 is_rounded = true;
1379 } else if (c != 0) {
1380 return false;
1381 }
1382 // Accept consistent zero or sign extension on operands a and b.
Aart Bikf3e61ee2017-04-12 17:09:20 -07001383 HInstruction* r = nullptr;
1384 HInstruction* s = nullptr;
1385 bool is_unsigned = false;
Aart Bik304c8a52017-05-23 11:01:13 -07001386 if (!IsNarrowerOperands(a, b, type, &r, &s, &is_unsigned)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -07001387 return false;
1388 }
1389 // Deal with vector restrictions.
1390 if ((!is_unsigned && HasVectorRestrictions(restrictions, kNoSignedHAdd)) ||
1391 (!is_rounded && HasVectorRestrictions(restrictions, kNoUnroundedHAdd))) {
1392 return false;
1393 }
1394 // Accept recognized halving add for vectorizable operands. Vectorized code uses the
1395 // shorthand idiomatic operation. Sequential code uses the original scalar expressions.
1396 DCHECK(r != nullptr && s != nullptr);
Aart Bik304c8a52017-05-23 11:01:13 -07001397 if (generate_code && vector_mode_ != kVector) { // de-idiom
1398 r = instruction->InputAt(0);
1399 s = instruction->InputAt(1);
1400 }
Aart Bikf3e61ee2017-04-12 17:09:20 -07001401 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
1402 VectorizeUse(node, s, generate_code, type, restrictions)) {
1403 if (generate_code) {
1404 if (vector_mode_ == kVector) {
1405 vector_map_->Put(instruction, new (global_allocator_) HVecHalvingAdd(
1406 global_allocator_,
1407 vector_map_->Get(r),
1408 vector_map_->Get(s),
1409 type,
1410 vector_length_,
1411 is_unsigned,
1412 is_rounded));
1413 } else {
Aart Bik304c8a52017-05-23 11:01:13 -07001414 GenerateVecOp(instruction, vector_map_->Get(r), vector_map_->Get(s), type);
Aart Bikf3e61ee2017-04-12 17:09:20 -07001415 }
1416 }
1417 return true;
1418 }
1419 }
1420 }
1421 return false;
1422}
1423
1424//
Aart Bikf8f5a162017-02-06 15:35:29 -08001425// Helpers.
1426//
1427
1428bool HLoopOptimization::TrySetPhiInduction(HPhi* phi, bool restrict_uses) {
1429 DCHECK(iset_->empty());
Aart Bikcc42be02016-10-20 16:14:16 -07001430 ArenaSet<HInstruction*>* set = induction_range_.LookupCycle(phi);
1431 if (set != nullptr) {
1432 for (HInstruction* i : *set) {
Aart Bike3dedc52016-11-02 17:50:27 -07001433 // Check that, other than instructions that are no longer in the graph (removed earlier)
Aart Bikf8f5a162017-02-06 15:35:29 -08001434 // each instruction is removable and, when restrict uses are requested, other than for phi,
1435 // all uses are contained within the cycle.
Aart Bike3dedc52016-11-02 17:50:27 -07001436 if (!i->IsInBlock()) {
1437 continue;
1438 } else if (!i->IsRemovable()) {
1439 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001440 } else if (i != phi && restrict_uses) {
Aart Bikcc42be02016-10-20 16:14:16 -07001441 for (const HUseListNode<HInstruction*>& use : i->GetUses()) {
1442 if (set->find(use.GetUser()) == set->end()) {
1443 return false;
1444 }
1445 }
1446 }
Aart Bike3dedc52016-11-02 17:50:27 -07001447 iset_->insert(i); // copy
Aart Bikcc42be02016-10-20 16:14:16 -07001448 }
Aart Bikcc42be02016-10-20 16:14:16 -07001449 return true;
1450 }
1451 return false;
1452}
1453
1454// Find: phi: Phi(init, addsub)
1455// s: SuspendCheck
1456// c: Condition(phi, bound)
1457// i: If(c)
1458// TODO: Find a less pattern matching approach?
Aart Bikf8f5a162017-02-06 15:35:29 -08001459bool HLoopOptimization::TrySetSimpleLoopHeader(HBasicBlock* block) {
Aart Bikcc42be02016-10-20 16:14:16 -07001460 DCHECK(iset_->empty());
1461 HInstruction* phi = block->GetFirstPhi();
Aart Bikf8f5a162017-02-06 15:35:29 -08001462 if (phi != nullptr &&
1463 phi->GetNext() == nullptr &&
1464 TrySetPhiInduction(phi->AsPhi(), /*restrict_uses*/ false)) {
Aart Bikcc42be02016-10-20 16:14:16 -07001465 HInstruction* s = block->GetFirstInstruction();
1466 if (s != nullptr && s->IsSuspendCheck()) {
1467 HInstruction* c = s->GetNext();
Aart Bikd86c0852017-04-14 12:00:15 -07001468 if (c != nullptr &&
1469 c->IsCondition() &&
1470 c->GetUses().HasExactlyOneElement() && // only used for termination
1471 !c->HasEnvironmentUses()) { // unlikely, but not impossible
Aart Bikcc42be02016-10-20 16:14:16 -07001472 HInstruction* i = c->GetNext();
1473 if (i != nullptr && i->IsIf() && i->InputAt(0) == c) {
1474 iset_->insert(c);
1475 iset_->insert(s);
1476 return true;
1477 }
1478 }
1479 }
1480 }
1481 return false;
1482}
1483
1484bool HLoopOptimization::IsEmptyBody(HBasicBlock* block) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001485 if (!block->GetPhis().IsEmpty()) {
1486 return false;
1487 }
1488 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
1489 HInstruction* instruction = it.Current();
1490 if (!instruction->IsGoto() && iset_->find(instruction) == iset_->end()) {
1491 return false;
Aart Bikcc42be02016-10-20 16:14:16 -07001492 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001493 }
1494 return true;
1495}
1496
1497bool HLoopOptimization::IsUsedOutsideLoop(HLoopInformation* loop_info,
1498 HInstruction* instruction) {
1499 for (const HUseListNode<HInstruction*>& use : instruction->GetUses()) {
1500 if (use.GetUser()->GetBlock()->GetLoopInformation() != loop_info) {
1501 return true;
1502 }
Aart Bikcc42be02016-10-20 16:14:16 -07001503 }
1504 return false;
1505}
1506
Aart Bik482095d2016-10-10 15:39:10 -07001507bool HLoopOptimization::IsOnlyUsedAfterLoop(HLoopInformation* loop_info,
Aart Bik8c4a8542016-10-06 11:36:57 -07001508 HInstruction* instruction,
Aart Bik6b69e0a2017-01-11 10:20:43 -08001509 bool collect_loop_uses,
Aart Bik8c4a8542016-10-06 11:36:57 -07001510 /*out*/ int32_t* use_count) {
1511 for (const HUseListNode<HInstruction*>& use : instruction->GetUses()) {
1512 HInstruction* user = use.GetUser();
1513 if (iset_->find(user) == iset_->end()) { // not excluded?
1514 HLoopInformation* other_loop_info = user->GetBlock()->GetLoopInformation();
Aart Bik482095d2016-10-10 15:39:10 -07001515 if (other_loop_info != nullptr && other_loop_info->IsIn(*loop_info)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -08001516 // If collect_loop_uses is set, simply keep adding those uses to the set.
1517 // Otherwise, reject uses inside the loop that were not already in the set.
1518 if (collect_loop_uses) {
1519 iset_->insert(user);
1520 continue;
1521 }
Aart Bik8c4a8542016-10-06 11:36:57 -07001522 return false;
1523 }
1524 ++*use_count;
1525 }
1526 }
1527 return true;
1528}
1529
Aart Bik807868e2016-11-03 17:51:43 -07001530bool HLoopOptimization::TryReplaceWithLastValue(HInstruction* instruction, HBasicBlock* block) {
1531 // Try to replace outside uses with the last value. Environment uses can consume this
1532 // value too, since any first true use is outside the loop (although this may imply
1533 // that de-opting may look "ahead" a bit on the phi value). If there are only environment
1534 // uses, the value is dropped altogether, since the computations have no effect.
1535 if (induction_range_.CanGenerateLastValue(instruction)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -08001536 HInstruction* replacement = induction_range_.GenerateLastValue(instruction, graph_, block);
1537 const HUseList<HInstruction*>& uses = instruction->GetUses();
1538 for (auto it = uses.begin(), end = uses.end(); it != end;) {
1539 HInstruction* user = it->GetUser();
1540 size_t index = it->GetIndex();
1541 ++it; // increment before replacing
1542 if (iset_->find(user) == iset_->end()) { // not excluded?
1543 user->ReplaceInput(replacement, index);
1544 induction_range_.Replace(user, instruction, replacement); // update induction
1545 }
1546 }
1547 const HUseList<HEnvironment*>& env_uses = instruction->GetEnvUses();
1548 for (auto it = env_uses.begin(), end = env_uses.end(); it != end;) {
1549 HEnvironment* user = it->GetUser();
1550 size_t index = it->GetIndex();
1551 ++it; // increment before replacing
1552 if (iset_->find(user->GetHolder()) == iset_->end()) { // not excluded?
1553 user->RemoveAsUserOfInput(index);
1554 user->SetRawEnvAt(index, replacement);
1555 replacement->AddEnvUseAt(user, index);
1556 }
1557 }
1558 induction_simplication_count_++;
Aart Bik807868e2016-11-03 17:51:43 -07001559 return true;
Aart Bik8c4a8542016-10-06 11:36:57 -07001560 }
Aart Bik807868e2016-11-03 17:51:43 -07001561 return false;
Aart Bik8c4a8542016-10-06 11:36:57 -07001562}
1563
Aart Bikf8f5a162017-02-06 15:35:29 -08001564bool HLoopOptimization::TryAssignLastValue(HLoopInformation* loop_info,
1565 HInstruction* instruction,
1566 HBasicBlock* block,
1567 bool collect_loop_uses) {
1568 // Assigning the last value is always successful if there are no uses.
1569 // Otherwise, it succeeds in a no early-exit loop by generating the
1570 // proper last value assignment.
1571 int32_t use_count = 0;
1572 return IsOnlyUsedAfterLoop(loop_info, instruction, collect_loop_uses, &use_count) &&
1573 (use_count == 0 ||
1574 (!IsEarlyExit(loop_info) && TryReplaceWithLastValue(instruction, block)));
1575}
1576
Aart Bik6b69e0a2017-01-11 10:20:43 -08001577void HLoopOptimization::RemoveDeadInstructions(const HInstructionList& list) {
1578 for (HBackwardInstructionIterator i(list); !i.Done(); i.Advance()) {
1579 HInstruction* instruction = i.Current();
1580 if (instruction->IsDeadAndRemovable()) {
1581 simplified_ = true;
1582 instruction->GetBlock()->RemoveInstructionOrPhi(instruction);
1583 }
1584 }
1585}
1586
Aart Bik281c6812016-08-26 11:31:48 -07001587} // namespace art