blob: 0ef7dcdb5942f7e02f3f0e4ffd929fe031f3b59b [file] [log] [blame]
Aart Bik281c6812016-08-26 11:31:48 -07001/*
2 * Copyright (C) 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "loop_optimization.h"
18
Aart Bikf8f5a162017-02-06 15:35:29 -080019#include "arch/arm/instruction_set_features_arm.h"
20#include "arch/arm64/instruction_set_features_arm64.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070021#include "arch/instruction_set.h"
Aart Bikf8f5a162017-02-06 15:35:29 -080022#include "arch/mips/instruction_set_features_mips.h"
23#include "arch/mips64/instruction_set_features_mips64.h"
24#include "arch/x86/instruction_set_features_x86.h"
25#include "arch/x86_64/instruction_set_features_x86_64.h"
Aart Bik92685a82017-03-06 11:13:43 -080026#include "driver/compiler_driver.h"
Aart Bik96202302016-10-04 17:33:56 -070027#include "linear_order.h"
Aart Bik281c6812016-08-26 11:31:48 -070028
29namespace art {
30
Aart Bikf8f5a162017-02-06 15:35:29 -080031// Enables vectorization (SIMDization) in the loop optimizer.
32static constexpr bool kEnableVectorization = true;
33
Aart Bik14a68b42017-06-08 14:06:58 -070034// All current SIMD targets want 16-byte alignment.
35static constexpr size_t kAlignedBase = 16;
36
Aart Bik9abf8942016-10-14 09:49:42 -070037// Remove the instruction from the graph. A bit more elaborate than the usual
38// instruction removal, since there may be a cycle in the use structure.
Aart Bik281c6812016-08-26 11:31:48 -070039static void RemoveFromCycle(HInstruction* instruction) {
Aart Bik281c6812016-08-26 11:31:48 -070040 instruction->RemoveAsUserOfAllInputs();
41 instruction->RemoveEnvironmentUsers();
42 instruction->GetBlock()->RemoveInstructionOrPhi(instruction, /*ensure_safety=*/ false);
Artem Serov21c7e6f2017-07-27 16:04:42 +010043 RemoveEnvironmentUses(instruction);
44 ResetEnvironmentInputRecords(instruction);
Aart Bik281c6812016-08-26 11:31:48 -070045}
46
Aart Bik807868e2016-11-03 17:51:43 -070047// Detect a goto block and sets succ to the single successor.
Aart Bike3dedc52016-11-02 17:50:27 -070048static bool IsGotoBlock(HBasicBlock* block, /*out*/ HBasicBlock** succ) {
49 if (block->GetPredecessors().size() == 1 &&
50 block->GetSuccessors().size() == 1 &&
51 block->IsSingleGoto()) {
52 *succ = block->GetSingleSuccessor();
53 return true;
54 }
55 return false;
56}
57
Aart Bik807868e2016-11-03 17:51:43 -070058// Detect an early exit loop.
59static bool IsEarlyExit(HLoopInformation* loop_info) {
60 HBlocksInLoopReversePostOrderIterator it_loop(*loop_info);
61 for (it_loop.Advance(); !it_loop.Done(); it_loop.Advance()) {
62 for (HBasicBlock* successor : it_loop.Current()->GetSuccessors()) {
63 if (!loop_info->Contains(*successor)) {
64 return true;
65 }
66 }
67 }
68 return false;
69}
70
Aart Bikf3e61ee2017-04-12 17:09:20 -070071// Detect a sign extension from the given type. Returns the promoted operand on success.
72static bool IsSignExtensionAndGet(HInstruction* instruction,
73 Primitive::Type type,
74 /*out*/ HInstruction** operand) {
75 // Accept any already wider constant that would be handled properly by sign
76 // extension when represented in the *width* of the given narrower data type
77 // (the fact that char normally zero extends does not matter here).
78 int64_t value = 0;
Aart Bik50e20d52017-05-05 14:07:29 -070079 if (IsInt64AndGet(instruction, /*out*/ &value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -070080 switch (type) {
81 case Primitive::kPrimByte:
82 if (std::numeric_limits<int8_t>::min() <= value &&
83 std::numeric_limits<int8_t>::max() >= value) {
84 *operand = instruction;
85 return true;
86 }
87 return false;
88 case Primitive::kPrimChar:
89 case Primitive::kPrimShort:
90 if (std::numeric_limits<int16_t>::min() <= value &&
91 std::numeric_limits<int16_t>::max() <= value) {
92 *operand = instruction;
93 return true;
94 }
95 return false;
96 default:
97 return false;
98 }
99 }
100 // An implicit widening conversion of a signed integer to an integral type sign-extends
101 // the two's-complement representation of the integer value to fill the wider format.
102 if (instruction->GetType() == type && (instruction->IsArrayGet() ||
103 instruction->IsStaticFieldGet() ||
104 instruction->IsInstanceFieldGet())) {
105 switch (type) {
106 case Primitive::kPrimByte:
107 case Primitive::kPrimShort:
108 *operand = instruction;
109 return true;
110 default:
111 return false;
112 }
113 }
114 // TODO: perhaps explicit conversions later too?
115 // (this may return something different from instruction)
116 return false;
117}
118
119// Detect a zero extension from the given type. Returns the promoted operand on success.
120static bool IsZeroExtensionAndGet(HInstruction* instruction,
121 Primitive::Type type,
122 /*out*/ HInstruction** operand) {
123 // Accept any already wider constant that would be handled properly by zero
124 // extension when represented in the *width* of the given narrower data type
125 // (the fact that byte/short normally sign extend does not matter here).
126 int64_t value = 0;
Aart Bik50e20d52017-05-05 14:07:29 -0700127 if (IsInt64AndGet(instruction, /*out*/ &value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700128 switch (type) {
129 case Primitive::kPrimByte:
130 if (std::numeric_limits<uint8_t>::min() <= value &&
131 std::numeric_limits<uint8_t>::max() >= value) {
132 *operand = instruction;
133 return true;
134 }
135 return false;
136 case Primitive::kPrimChar:
137 case Primitive::kPrimShort:
138 if (std::numeric_limits<uint16_t>::min() <= value &&
139 std::numeric_limits<uint16_t>::max() <= value) {
140 *operand = instruction;
141 return true;
142 }
143 return false;
144 default:
145 return false;
146 }
147 }
148 // An implicit widening conversion of a char to an integral type zero-extends
149 // the representation of the char value to fill the wider format.
150 if (instruction->GetType() == type && (instruction->IsArrayGet() ||
151 instruction->IsStaticFieldGet() ||
152 instruction->IsInstanceFieldGet())) {
153 if (type == Primitive::kPrimChar) {
154 *operand = instruction;
155 return true;
156 }
157 }
158 // A sign (or zero) extension followed by an explicit removal of just the
159 // higher sign bits is equivalent to a zero extension of the underlying operand.
160 if (instruction->IsAnd()) {
161 int64_t mask = 0;
162 HInstruction* a = instruction->InputAt(0);
163 HInstruction* b = instruction->InputAt(1);
164 // In (a & b) find (mask & b) or (a & mask) with sign or zero extension on the non-mask.
165 if ((IsInt64AndGet(a, /*out*/ &mask) && (IsSignExtensionAndGet(b, type, /*out*/ operand) ||
166 IsZeroExtensionAndGet(b, type, /*out*/ operand))) ||
167 (IsInt64AndGet(b, /*out*/ &mask) && (IsSignExtensionAndGet(a, type, /*out*/ operand) ||
168 IsZeroExtensionAndGet(a, type, /*out*/ operand)))) {
169 switch ((*operand)->GetType()) {
170 case Primitive::kPrimByte: return mask == std::numeric_limits<uint8_t>::max();
171 case Primitive::kPrimChar:
172 case Primitive::kPrimShort: return mask == std::numeric_limits<uint16_t>::max();
173 default: return false;
174 }
175 }
176 }
177 // TODO: perhaps explicit conversions later too?
178 return false;
179}
180
Aart Bik304c8a52017-05-23 11:01:13 -0700181// Detect situations with same-extension narrower operands.
182// Returns true on success and sets is_unsigned accordingly.
183static bool IsNarrowerOperands(HInstruction* a,
184 HInstruction* b,
185 Primitive::Type type,
186 /*out*/ HInstruction** r,
187 /*out*/ HInstruction** s,
188 /*out*/ bool* is_unsigned) {
189 if (IsSignExtensionAndGet(a, type, r) && IsSignExtensionAndGet(b, type, s)) {
190 *is_unsigned = false;
191 return true;
192 } else if (IsZeroExtensionAndGet(a, type, r) && IsZeroExtensionAndGet(b, type, s)) {
193 *is_unsigned = true;
194 return true;
195 }
196 return false;
197}
198
199// As above, single operand.
200static bool IsNarrowerOperand(HInstruction* a,
201 Primitive::Type type,
202 /*out*/ HInstruction** r,
203 /*out*/ bool* is_unsigned) {
204 if (IsSignExtensionAndGet(a, type, r)) {
205 *is_unsigned = false;
206 return true;
207 } else if (IsZeroExtensionAndGet(a, type, r)) {
208 *is_unsigned = true;
209 return true;
210 }
211 return false;
212}
213
Aart Bik5f805002017-05-16 16:42:41 -0700214// Detect up to two instructions a and b, and an acccumulated constant c.
215static bool IsAddConstHelper(HInstruction* instruction,
216 /*out*/ HInstruction** a,
217 /*out*/ HInstruction** b,
218 /*out*/ int64_t* c,
219 int32_t depth) {
220 static constexpr int32_t kMaxDepth = 8; // don't search too deep
221 int64_t value = 0;
222 if (IsInt64AndGet(instruction, &value)) {
223 *c += value;
224 return true;
225 } else if (instruction->IsAdd() && depth <= kMaxDepth) {
226 return IsAddConstHelper(instruction->InputAt(0), a, b, c, depth + 1) &&
227 IsAddConstHelper(instruction->InputAt(1), a, b, c, depth + 1);
228 } else if (*a == nullptr) {
229 *a = instruction;
230 return true;
231 } else if (*b == nullptr) {
232 *b = instruction;
233 return true;
234 }
235 return false; // too many non-const operands
236}
237
238// Detect a + b + c for an optional constant c.
239static bool IsAddConst(HInstruction* instruction,
240 /*out*/ HInstruction** a,
241 /*out*/ HInstruction** b,
242 /*out*/ int64_t* c) {
243 if (instruction->IsAdd()) {
244 // Try to find a + b and accumulated c.
245 if (IsAddConstHelper(instruction->InputAt(0), a, b, c, /*depth*/ 0) &&
246 IsAddConstHelper(instruction->InputAt(1), a, b, c, /*depth*/ 0) &&
247 *b != nullptr) {
248 return true;
249 }
250 // Found a + b.
251 *a = instruction->InputAt(0);
252 *b = instruction->InputAt(1);
253 *c = 0;
254 return true;
255 }
256 return false;
257}
258
Aart Bikf8f5a162017-02-06 15:35:29 -0800259// Test vector restrictions.
260static bool HasVectorRestrictions(uint64_t restrictions, uint64_t tested) {
261 return (restrictions & tested) != 0;
262}
263
Aart Bikf3e61ee2017-04-12 17:09:20 -0700264// Insert an instruction.
Aart Bikf8f5a162017-02-06 15:35:29 -0800265static HInstruction* Insert(HBasicBlock* block, HInstruction* instruction) {
266 DCHECK(block != nullptr);
267 DCHECK(instruction != nullptr);
268 block->InsertInstructionBefore(instruction, block->GetLastInstruction());
269 return instruction;
270}
271
Artem Serov21c7e6f2017-07-27 16:04:42 +0100272// Check that instructions from the induction sets are fully removed: have no uses
273// and no other instructions use them.
274static bool CheckInductionSetFullyRemoved(ArenaSet<HInstruction*>* iset) {
275 for (HInstruction* instr : *iset) {
276 if (instr->GetBlock() != nullptr ||
277 !instr->GetUses().empty() ||
278 !instr->GetEnvUses().empty() ||
279 HasEnvironmentUsedByOthers(instr)) {
280 return false;
281 }
282 }
283
284 return true;
285}
286
Aart Bik281c6812016-08-26 11:31:48 -0700287//
288// Class methods.
289//
290
291HLoopOptimization::HLoopOptimization(HGraph* graph,
Aart Bik92685a82017-03-06 11:13:43 -0800292 CompilerDriver* compiler_driver,
Aart Bik281c6812016-08-26 11:31:48 -0700293 HInductionVarAnalysis* induction_analysis)
294 : HOptimization(graph, kLoopOptimizationPassName),
Aart Bik92685a82017-03-06 11:13:43 -0800295 compiler_driver_(compiler_driver),
Aart Bik281c6812016-08-26 11:31:48 -0700296 induction_range_(induction_analysis),
Aart Bik96202302016-10-04 17:33:56 -0700297 loop_allocator_(nullptr),
Aart Bikf8f5a162017-02-06 15:35:29 -0800298 global_allocator_(graph_->GetArena()),
Aart Bik281c6812016-08-26 11:31:48 -0700299 top_loop_(nullptr),
Aart Bik8c4a8542016-10-06 11:36:57 -0700300 last_loop_(nullptr),
Aart Bik482095d2016-10-10 15:39:10 -0700301 iset_(nullptr),
Aart Bikdf7822e2016-12-06 10:05:30 -0800302 induction_simplication_count_(0),
Aart Bikf8f5a162017-02-06 15:35:29 -0800303 simplified_(false),
304 vector_length_(0),
305 vector_refs_(nullptr),
Aart Bik14a68b42017-06-08 14:06:58 -0700306 vector_peeling_candidate_(nullptr),
307 vector_runtime_test_a_(nullptr),
308 vector_runtime_test_b_(nullptr),
Aart Bikf8f5a162017-02-06 15:35:29 -0800309 vector_map_(nullptr) {
Aart Bik281c6812016-08-26 11:31:48 -0700310}
311
312void HLoopOptimization::Run() {
Mingyao Yang01b47b02017-02-03 12:09:57 -0800313 // Skip if there is no loop or the graph has try-catch/irreducible loops.
Aart Bik281c6812016-08-26 11:31:48 -0700314 // TODO: make this less of a sledgehammer.
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800315 if (!graph_->HasLoops() || graph_->HasTryCatch() || graph_->HasIrreducibleLoops()) {
Aart Bik281c6812016-08-26 11:31:48 -0700316 return;
317 }
318
Aart Bik96202302016-10-04 17:33:56 -0700319 // Phase-local allocator that draws from the global pool. Since the allocator
320 // itself resides on the stack, it is destructed on exiting Run(), which
321 // implies its underlying memory is released immediately.
Aart Bikf8f5a162017-02-06 15:35:29 -0800322 ArenaAllocator allocator(global_allocator_->GetArenaPool());
Aart Bik96202302016-10-04 17:33:56 -0700323 loop_allocator_ = &allocator;
Nicolas Geoffrayebe16742016-10-05 09:55:42 +0100324
Aart Bik96202302016-10-04 17:33:56 -0700325 // Perform loop optimizations.
326 LocalRun();
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800327 if (top_loop_ == nullptr) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800328 graph_->SetHasLoops(false); // no more loops
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800329 }
330
Aart Bik96202302016-10-04 17:33:56 -0700331 // Detach.
332 loop_allocator_ = nullptr;
333 last_loop_ = top_loop_ = nullptr;
334}
335
336void HLoopOptimization::LocalRun() {
337 // Build the linear order using the phase-local allocator. This step enables building
338 // a loop hierarchy that properly reflects the outer-inner and previous-next relation.
339 ArenaVector<HBasicBlock*> linear_order(loop_allocator_->Adapter(kArenaAllocLinearOrder));
340 LinearizeGraph(graph_, loop_allocator_, &linear_order);
341
Aart Bik281c6812016-08-26 11:31:48 -0700342 // Build the loop hierarchy.
Aart Bik96202302016-10-04 17:33:56 -0700343 for (HBasicBlock* block : linear_order) {
Aart Bik281c6812016-08-26 11:31:48 -0700344 if (block->IsLoopHeader()) {
345 AddLoop(block->GetLoopInformation());
346 }
347 }
Aart Bik96202302016-10-04 17:33:56 -0700348
Aart Bik8c4a8542016-10-06 11:36:57 -0700349 // Traverse the loop hierarchy inner-to-outer and optimize. Traversal can use
Aart Bikf8f5a162017-02-06 15:35:29 -0800350 // temporary data structures using the phase-local allocator. All new HIR
351 // should use the global allocator.
Aart Bik8c4a8542016-10-06 11:36:57 -0700352 if (top_loop_ != nullptr) {
353 ArenaSet<HInstruction*> iset(loop_allocator_->Adapter(kArenaAllocLoopOptimization));
Aart Bikf8f5a162017-02-06 15:35:29 -0800354 ArenaSet<ArrayReference> refs(loop_allocator_->Adapter(kArenaAllocLoopOptimization));
355 ArenaSafeMap<HInstruction*, HInstruction*> map(
356 std::less<HInstruction*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
357 // Attach.
Aart Bik8c4a8542016-10-06 11:36:57 -0700358 iset_ = &iset;
Aart Bikf8f5a162017-02-06 15:35:29 -0800359 vector_refs_ = &refs;
360 vector_map_ = &map;
361 // Traverse.
Aart Bik8c4a8542016-10-06 11:36:57 -0700362 TraverseLoopsInnerToOuter(top_loop_);
Aart Bikf8f5a162017-02-06 15:35:29 -0800363 // Detach.
364 iset_ = nullptr;
365 vector_refs_ = nullptr;
366 vector_map_ = nullptr;
Aart Bik8c4a8542016-10-06 11:36:57 -0700367 }
Aart Bik281c6812016-08-26 11:31:48 -0700368}
369
370void HLoopOptimization::AddLoop(HLoopInformation* loop_info) {
371 DCHECK(loop_info != nullptr);
Aart Bikf8f5a162017-02-06 15:35:29 -0800372 LoopNode* node = new (loop_allocator_) LoopNode(loop_info);
Aart Bik281c6812016-08-26 11:31:48 -0700373 if (last_loop_ == nullptr) {
374 // First loop.
375 DCHECK(top_loop_ == nullptr);
376 last_loop_ = top_loop_ = node;
377 } else if (loop_info->IsIn(*last_loop_->loop_info)) {
378 // Inner loop.
379 node->outer = last_loop_;
380 DCHECK(last_loop_->inner == nullptr);
381 last_loop_ = last_loop_->inner = node;
382 } else {
383 // Subsequent loop.
384 while (last_loop_->outer != nullptr && !loop_info->IsIn(*last_loop_->outer->loop_info)) {
385 last_loop_ = last_loop_->outer;
386 }
387 node->outer = last_loop_->outer;
388 node->previous = last_loop_;
389 DCHECK(last_loop_->next == nullptr);
390 last_loop_ = last_loop_->next = node;
391 }
392}
393
394void HLoopOptimization::RemoveLoop(LoopNode* node) {
395 DCHECK(node != nullptr);
Aart Bik8c4a8542016-10-06 11:36:57 -0700396 DCHECK(node->inner == nullptr);
397 if (node->previous != nullptr) {
398 // Within sequence.
399 node->previous->next = node->next;
400 if (node->next != nullptr) {
401 node->next->previous = node->previous;
402 }
403 } else {
404 // First of sequence.
405 if (node->outer != nullptr) {
406 node->outer->inner = node->next;
407 } else {
408 top_loop_ = node->next;
409 }
410 if (node->next != nullptr) {
411 node->next->outer = node->outer;
412 node->next->previous = nullptr;
413 }
414 }
Aart Bik281c6812016-08-26 11:31:48 -0700415}
416
417void HLoopOptimization::TraverseLoopsInnerToOuter(LoopNode* node) {
418 for ( ; node != nullptr; node = node->next) {
Aart Bik6b69e0a2017-01-11 10:20:43 -0800419 // Visit inner loops first.
Aart Bikf8f5a162017-02-06 15:35:29 -0800420 uint32_t current_induction_simplification_count = induction_simplication_count_;
Aart Bik281c6812016-08-26 11:31:48 -0700421 if (node->inner != nullptr) {
422 TraverseLoopsInnerToOuter(node->inner);
423 }
Aart Bik6b69e0a2017-01-11 10:20:43 -0800424 // Recompute induction information of this loop if the induction
425 // of any inner loop has been simplified.
Aart Bik482095d2016-10-10 15:39:10 -0700426 if (current_induction_simplification_count != induction_simplication_count_) {
427 induction_range_.ReVisit(node->loop_info);
428 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800429 // Repeat simplifications in the loop-body until no more changes occur.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800430 // Note that since each simplification consists of eliminating code (without
431 // introducing new code), this process is always finite.
Aart Bikdf7822e2016-12-06 10:05:30 -0800432 do {
433 simplified_ = false;
Aart Bikdf7822e2016-12-06 10:05:30 -0800434 SimplifyInduction(node);
Aart Bik6b69e0a2017-01-11 10:20:43 -0800435 SimplifyBlocks(node);
Aart Bikdf7822e2016-12-06 10:05:30 -0800436 } while (simplified_);
Aart Bikf8f5a162017-02-06 15:35:29 -0800437 // Optimize inner loop.
Aart Bik9abf8942016-10-14 09:49:42 -0700438 if (node->inner == nullptr) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800439 OptimizeInnerLoop(node);
Aart Bik9abf8942016-10-14 09:49:42 -0700440 }
Aart Bik281c6812016-08-26 11:31:48 -0700441 }
442}
443
Aart Bikf8f5a162017-02-06 15:35:29 -0800444//
445// Optimization.
446//
447
Aart Bik281c6812016-08-26 11:31:48 -0700448void HLoopOptimization::SimplifyInduction(LoopNode* node) {
449 HBasicBlock* header = node->loop_info->GetHeader();
450 HBasicBlock* preheader = node->loop_info->GetPreHeader();
Aart Bik8c4a8542016-10-06 11:36:57 -0700451 // Scan the phis in the header to find opportunities to simplify an induction
452 // cycle that is only used outside the loop. Replace these uses, if any, with
453 // the last value and remove the induction cycle.
454 // Examples: for (int i = 0; x != null; i++) { .... no i .... }
455 // for (int i = 0; i < 10; i++, k++) { .... no k .... } return k;
Aart Bik281c6812016-08-26 11:31:48 -0700456 for (HInstructionIterator it(header->GetPhis()); !it.Done(); it.Advance()) {
457 HPhi* phi = it.Current()->AsPhi();
Aart Bikf8f5a162017-02-06 15:35:29 -0800458 iset_->clear(); // prepare phi induction
459 if (TrySetPhiInduction(phi, /*restrict_uses*/ true) &&
460 TryAssignLastValue(node->loop_info, phi, preheader, /*collect_loop_uses*/ false)) {
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +0100461 // Note that it's ok to have replaced uses after the loop with the last value, without
462 // being able to remove the cycle. Environment uses (which are the reason we may not be
463 // able to remove the cycle) within the loop will still hold the right value.
464 if (CanRemoveCycle()) {
465 for (HInstruction* i : *iset_) {
466 RemoveFromCycle(i);
467 }
Artem Serov21c7e6f2017-07-27 16:04:42 +0100468
469 // Check that there are no records of the deleted instructions.
470 DCHECK(CheckInductionSetFullyRemoved(iset_));
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +0100471 simplified_ = true;
Aart Bik281c6812016-08-26 11:31:48 -0700472 }
Aart Bik482095d2016-10-10 15:39:10 -0700473 }
474 }
475}
476
477void HLoopOptimization::SimplifyBlocks(LoopNode* node) {
Aart Bikdf7822e2016-12-06 10:05:30 -0800478 // Iterate over all basic blocks in the loop-body.
479 for (HBlocksInLoopIterator it(*node->loop_info); !it.Done(); it.Advance()) {
480 HBasicBlock* block = it.Current();
481 // Remove dead instructions from the loop-body.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800482 RemoveDeadInstructions(block->GetPhis());
483 RemoveDeadInstructions(block->GetInstructions());
Aart Bikdf7822e2016-12-06 10:05:30 -0800484 // Remove trivial control flow blocks from the loop-body.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800485 if (block->GetPredecessors().size() == 1 &&
486 block->GetSuccessors().size() == 1 &&
487 block->GetSingleSuccessor()->GetPredecessors().size() == 1) {
Aart Bikdf7822e2016-12-06 10:05:30 -0800488 simplified_ = true;
Aart Bik6b69e0a2017-01-11 10:20:43 -0800489 block->MergeWith(block->GetSingleSuccessor());
Aart Bikdf7822e2016-12-06 10:05:30 -0800490 } else if (block->GetSuccessors().size() == 2) {
491 // Trivial if block can be bypassed to either branch.
492 HBasicBlock* succ0 = block->GetSuccessors()[0];
493 HBasicBlock* succ1 = block->GetSuccessors()[1];
494 HBasicBlock* meet0 = nullptr;
495 HBasicBlock* meet1 = nullptr;
496 if (succ0 != succ1 &&
497 IsGotoBlock(succ0, &meet0) &&
498 IsGotoBlock(succ1, &meet1) &&
499 meet0 == meet1 && // meets again
500 meet0 != block && // no self-loop
501 meet0->GetPhis().IsEmpty()) { // not used for merging
502 simplified_ = true;
503 succ0->DisconnectAndDelete();
504 if (block->Dominates(meet0)) {
505 block->RemoveDominatedBlock(meet0);
506 succ1->AddDominatedBlock(meet0);
507 meet0->SetDominator(succ1);
Aart Bike3dedc52016-11-02 17:50:27 -0700508 }
Aart Bik482095d2016-10-10 15:39:10 -0700509 }
Aart Bik281c6812016-08-26 11:31:48 -0700510 }
Aart Bikdf7822e2016-12-06 10:05:30 -0800511 }
Aart Bik281c6812016-08-26 11:31:48 -0700512}
513
Aart Bikf8f5a162017-02-06 15:35:29 -0800514void HLoopOptimization::OptimizeInnerLoop(LoopNode* node) {
Aart Bik281c6812016-08-26 11:31:48 -0700515 HBasicBlock* header = node->loop_info->GetHeader();
516 HBasicBlock* preheader = node->loop_info->GetPreHeader();
Aart Bik9abf8942016-10-14 09:49:42 -0700517 // Ensure loop header logic is finite.
Aart Bikf8f5a162017-02-06 15:35:29 -0800518 int64_t trip_count = 0;
519 if (!induction_range_.IsFinite(node->loop_info, &trip_count)) {
520 return;
Aart Bik9abf8942016-10-14 09:49:42 -0700521 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800522
Aart Bik281c6812016-08-26 11:31:48 -0700523 // Ensure there is only a single loop-body (besides the header).
524 HBasicBlock* body = nullptr;
525 for (HBlocksInLoopIterator it(*node->loop_info); !it.Done(); it.Advance()) {
526 if (it.Current() != header) {
527 if (body != nullptr) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800528 return;
Aart Bik281c6812016-08-26 11:31:48 -0700529 }
530 body = it.Current();
531 }
532 }
Andreas Gampef45d61c2017-06-07 10:29:33 -0700533 CHECK(body != nullptr);
Aart Bik281c6812016-08-26 11:31:48 -0700534 // Ensure there is only a single exit point.
535 if (header->GetSuccessors().size() != 2) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800536 return;
Aart Bik281c6812016-08-26 11:31:48 -0700537 }
538 HBasicBlock* exit = (header->GetSuccessors()[0] == body)
539 ? header->GetSuccessors()[1]
540 : header->GetSuccessors()[0];
Aart Bik8c4a8542016-10-06 11:36:57 -0700541 // Ensure exit can only be reached by exiting loop.
Aart Bik281c6812016-08-26 11:31:48 -0700542 if (exit->GetPredecessors().size() != 1) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800543 return;
Aart Bik281c6812016-08-26 11:31:48 -0700544 }
Aart Bik6b69e0a2017-01-11 10:20:43 -0800545 // Detect either an empty loop (no side effects other than plain iteration) or
546 // a trivial loop (just iterating once). Replace subsequent index uses, if any,
547 // with the last value and remove the loop, possibly after unrolling its body.
548 HInstruction* phi = header->GetFirstPhi();
Aart Bikf8f5a162017-02-06 15:35:29 -0800549 iset_->clear(); // prepare phi induction
550 if (TrySetSimpleLoopHeader(header)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -0800551 bool is_empty = IsEmptyBody(body);
Aart Bikf8f5a162017-02-06 15:35:29 -0800552 if ((is_empty || trip_count == 1) &&
553 TryAssignLastValue(node->loop_info, phi, preheader, /*collect_loop_uses*/ true)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -0800554 if (!is_empty) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800555 // Unroll the loop-body, which sees initial value of the index.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800556 phi->ReplaceWith(phi->InputAt(0));
557 preheader->MergeInstructionsWith(body);
558 }
559 body->DisconnectAndDelete();
560 exit->RemovePredecessor(header);
561 header->RemoveSuccessor(exit);
562 header->RemoveDominatedBlock(exit);
563 header->DisconnectAndDelete();
564 preheader->AddSuccessor(exit);
Aart Bikf8f5a162017-02-06 15:35:29 -0800565 preheader->AddInstruction(new (global_allocator_) HGoto());
Aart Bik6b69e0a2017-01-11 10:20:43 -0800566 preheader->AddDominatedBlock(exit);
567 exit->SetDominator(preheader);
568 RemoveLoop(node); // update hierarchy
Aart Bikf8f5a162017-02-06 15:35:29 -0800569 return;
570 }
571 }
572
573 // Vectorize loop, if possible and valid.
574 if (kEnableVectorization) {
575 iset_->clear(); // prepare phi induction
576 if (TrySetSimpleLoopHeader(header) &&
Aart Bik14a68b42017-06-08 14:06:58 -0700577 ShouldVectorize(node, body, trip_count) &&
Aart Bikf8f5a162017-02-06 15:35:29 -0800578 TryAssignLastValue(node->loop_info, phi, preheader, /*collect_loop_uses*/ true)) {
579 Vectorize(node, body, exit, trip_count);
580 graph_->SetHasSIMD(true); // flag SIMD usage
581 return;
582 }
583 }
584}
585
586//
587// Loop vectorization. The implementation is based on the book by Aart J.C. Bik:
588// "The Software Vectorization Handbook. Applying Multimedia Extensions for Maximum Performance."
589// Intel Press, June, 2004 (http://www.aartbik.com/).
590//
591
Aart Bik14a68b42017-06-08 14:06:58 -0700592bool HLoopOptimization::ShouldVectorize(LoopNode* node, HBasicBlock* block, int64_t trip_count) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800593 // Reset vector bookkeeping.
594 vector_length_ = 0;
595 vector_refs_->clear();
Aart Bik14a68b42017-06-08 14:06:58 -0700596 vector_peeling_candidate_ = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800597 vector_runtime_test_a_ =
598 vector_runtime_test_b_= nullptr;
599
600 // Phis in the loop-body prevent vectorization.
601 if (!block->GetPhis().IsEmpty()) {
602 return false;
603 }
604
605 // Scan the loop-body, starting a right-hand-side tree traversal at each left-hand-side
606 // occurrence, which allows passing down attributes down the use tree.
607 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
608 if (!VectorizeDef(node, it.Current(), /*generate_code*/ false)) {
609 return false; // failure to vectorize a left-hand-side
610 }
611 }
612
Aart Bik14a68b42017-06-08 14:06:58 -0700613 // Does vectorization seem profitable?
614 if (!IsVectorizationProfitable(trip_count)) {
615 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -0800616 }
617
618 // Data dependence analysis. Find each pair of references with same type, where
619 // at least one is a write. Each such pair denotes a possible data dependence.
620 // This analysis exploits the property that differently typed arrays cannot be
621 // aliased, as well as the property that references either point to the same
622 // array or to two completely disjoint arrays, i.e., no partial aliasing.
623 // Other than a few simply heuristics, no detailed subscript analysis is done.
624 for (auto i = vector_refs_->begin(); i != vector_refs_->end(); ++i) {
625 for (auto j = i; ++j != vector_refs_->end(); ) {
626 if (i->type == j->type && (i->lhs || j->lhs)) {
627 // Found same-typed a[i+x] vs. b[i+y], where at least one is a write.
628 HInstruction* a = i->base;
629 HInstruction* b = j->base;
630 HInstruction* x = i->offset;
631 HInstruction* y = j->offset;
632 if (a == b) {
633 // Found a[i+x] vs. a[i+y]. Accept if x == y (loop-independent data dependence).
634 // Conservatively assume a loop-carried data dependence otherwise, and reject.
635 if (x != y) {
636 return false;
637 }
638 } else {
639 // Found a[i+x] vs. b[i+y]. Accept if x == y (at worst loop-independent data dependence).
640 // Conservatively assume a potential loop-carried data dependence otherwise, avoided by
641 // generating an explicit a != b disambiguation runtime test on the two references.
642 if (x != y) {
Aart Bik37dc4df2017-06-28 14:08:00 -0700643 // To avoid excessive overhead, we only accept one a != b test.
644 if (vector_runtime_test_a_ == nullptr) {
645 // First test found.
646 vector_runtime_test_a_ = a;
647 vector_runtime_test_b_ = b;
648 } else if ((vector_runtime_test_a_ != a || vector_runtime_test_b_ != b) &&
649 (vector_runtime_test_a_ != b || vector_runtime_test_b_ != a)) {
650 return false; // second test would be needed
Aart Bikf8f5a162017-02-06 15:35:29 -0800651 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800652 }
653 }
654 }
655 }
656 }
657
Aart Bik14a68b42017-06-08 14:06:58 -0700658 // Consider dynamic loop peeling for alignment.
659 SetPeelingCandidate(trip_count);
660
Aart Bikf8f5a162017-02-06 15:35:29 -0800661 // Success!
662 return true;
663}
664
665void HLoopOptimization::Vectorize(LoopNode* node,
666 HBasicBlock* block,
667 HBasicBlock* exit,
668 int64_t trip_count) {
669 Primitive::Type induc_type = Primitive::kPrimInt;
670 HBasicBlock* header = node->loop_info->GetHeader();
671 HBasicBlock* preheader = node->loop_info->GetPreHeader();
672
Aart Bik14a68b42017-06-08 14:06:58 -0700673 // Pick a loop unrolling factor for the vector loop.
674 uint32_t unroll = GetUnrollingFactor(block, trip_count);
675 uint32_t chunk = vector_length_ * unroll;
676
677 // A cleanup loop is needed, at least, for any unknown trip count or
678 // for a known trip count with remainder iterations after vectorization.
679 bool needs_cleanup = trip_count == 0 || (trip_count % chunk) != 0;
Aart Bikf8f5a162017-02-06 15:35:29 -0800680
681 // Adjust vector bookkeeping.
682 iset_->clear(); // prepare phi induction
683 bool is_simple_loop_header = TrySetSimpleLoopHeader(header); // fills iset_
684 DCHECK(is_simple_loop_header);
Aart Bik14a68b42017-06-08 14:06:58 -0700685 vector_header_ = header;
686 vector_body_ = block;
Aart Bikf8f5a162017-02-06 15:35:29 -0800687
Aart Bik14a68b42017-06-08 14:06:58 -0700688 // Generate dynamic loop peeling trip count, if needed:
689 // ptc = <peeling-needed-for-candidate>
690 HInstruction* ptc = nullptr;
691 if (vector_peeling_candidate_ != nullptr) {
692 DCHECK_LT(vector_length_, trip_count) << "dynamic peeling currently requires known trip count";
693 //
694 // TODO: Implement this. Compute address of first access memory location and
695 // compute peeling factor to obtain kAlignedBase alignment.
696 //
697 needs_cleanup = true;
698 }
699
700 // Generate loop control:
Aart Bikf8f5a162017-02-06 15:35:29 -0800701 // stc = <trip-count>;
Aart Bik14a68b42017-06-08 14:06:58 -0700702 // vtc = stc - (stc - ptc) % chunk;
703 // i = 0;
Aart Bikf8f5a162017-02-06 15:35:29 -0800704 HInstruction* stc = induction_range_.GenerateTripCount(node->loop_info, graph_, preheader);
705 HInstruction* vtc = stc;
706 if (needs_cleanup) {
Aart Bik14a68b42017-06-08 14:06:58 -0700707 DCHECK(IsPowerOfTwo(chunk));
708 HInstruction* diff = stc;
709 if (ptc != nullptr) {
710 diff = Insert(preheader, new (global_allocator_) HSub(induc_type, stc, ptc));
711 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800712 HInstruction* rem = Insert(
713 preheader, new (global_allocator_) HAnd(induc_type,
Aart Bik14a68b42017-06-08 14:06:58 -0700714 diff,
715 graph_->GetIntConstant(chunk - 1)));
Aart Bikf8f5a162017-02-06 15:35:29 -0800716 vtc = Insert(preheader, new (global_allocator_) HSub(induc_type, stc, rem));
717 }
Aart Bik14a68b42017-06-08 14:06:58 -0700718 vector_index_ = graph_->GetIntConstant(0);
Aart Bikf8f5a162017-02-06 15:35:29 -0800719
720 // Generate runtime disambiguation test:
721 // vtc = a != b ? vtc : 0;
722 if (vector_runtime_test_a_ != nullptr) {
723 HInstruction* rt = Insert(
724 preheader,
725 new (global_allocator_) HNotEqual(vector_runtime_test_a_, vector_runtime_test_b_));
726 vtc = Insert(preheader,
727 new (global_allocator_) HSelect(rt, vtc, graph_->GetIntConstant(0), kNoDexPc));
728 needs_cleanup = true;
729 }
730
Aart Bik14a68b42017-06-08 14:06:58 -0700731 // Generate dynamic peeling loop for alignment, if needed:
732 // for ( ; i < ptc; i += 1)
733 // <loop-body>
734 if (ptc != nullptr) {
735 vector_mode_ = kSequential;
736 GenerateNewLoop(node,
737 block,
738 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
739 vector_index_,
740 ptc,
741 graph_->GetIntConstant(1),
742 /*unroll*/ 1);
743 }
744
745 // Generate vector loop, possibly further unrolled:
746 // for ( ; i < vtc; i += chunk)
Aart Bikf8f5a162017-02-06 15:35:29 -0800747 // <vectorized-loop-body>
748 vector_mode_ = kVector;
749 GenerateNewLoop(node,
750 block,
Aart Bik14a68b42017-06-08 14:06:58 -0700751 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
752 vector_index_,
Aart Bikf8f5a162017-02-06 15:35:29 -0800753 vtc,
Aart Bik14a68b42017-06-08 14:06:58 -0700754 graph_->GetIntConstant(vector_length_), // increment per unroll
755 unroll);
Aart Bikf8f5a162017-02-06 15:35:29 -0800756 HLoopInformation* vloop = vector_header_->GetLoopInformation();
757
758 // Generate cleanup loop, if needed:
759 // for ( ; i < stc; i += 1)
760 // <loop-body>
761 if (needs_cleanup) {
762 vector_mode_ = kSequential;
763 GenerateNewLoop(node,
764 block,
765 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
Aart Bik14a68b42017-06-08 14:06:58 -0700766 vector_index_,
Aart Bikf8f5a162017-02-06 15:35:29 -0800767 stc,
Aart Bik14a68b42017-06-08 14:06:58 -0700768 graph_->GetIntConstant(1),
769 /*unroll*/ 1);
Aart Bikf8f5a162017-02-06 15:35:29 -0800770 }
771
772 // Remove the original loop by disconnecting the body block
773 // and removing all instructions from the header.
774 block->DisconnectAndDelete();
775 while (!header->GetFirstInstruction()->IsGoto()) {
776 header->RemoveInstruction(header->GetFirstInstruction());
777 }
Aart Bik14a68b42017-06-08 14:06:58 -0700778 // Update loop hierarchy: the old header now resides in the same outer loop
779 // as the old preheader. Note that we don't bother putting sequential
780 // loops back in the hierarchy at this point.
Aart Bikf8f5a162017-02-06 15:35:29 -0800781 header->SetLoopInformation(preheader->GetLoopInformation()); // outward
782 node->loop_info = vloop;
783}
784
785void HLoopOptimization::GenerateNewLoop(LoopNode* node,
786 HBasicBlock* block,
787 HBasicBlock* new_preheader,
788 HInstruction* lo,
789 HInstruction* hi,
Aart Bik14a68b42017-06-08 14:06:58 -0700790 HInstruction* step,
791 uint32_t unroll) {
792 DCHECK(unroll == 1 || vector_mode_ == kVector);
Aart Bikf8f5a162017-02-06 15:35:29 -0800793 Primitive::Type induc_type = Primitive::kPrimInt;
794 // Prepare new loop.
Aart Bikf8f5a162017-02-06 15:35:29 -0800795 vector_preheader_ = new_preheader,
796 vector_header_ = vector_preheader_->GetSingleSuccessor();
797 vector_body_ = vector_header_->GetSuccessors()[1];
Aart Bik14a68b42017-06-08 14:06:58 -0700798 HPhi* phi = new (global_allocator_) HPhi(global_allocator_,
799 kNoRegNumber,
800 0,
801 HPhi::ToPhiType(induc_type));
Aart Bikb07d1bc2017-04-05 10:03:15 -0700802 // Generate header and prepare body.
Aart Bikf8f5a162017-02-06 15:35:29 -0800803 // for (i = lo; i < hi; i += step)
804 // <loop-body>
Aart Bik14a68b42017-06-08 14:06:58 -0700805 HInstruction* cond = new (global_allocator_) HAboveOrEqual(phi, hi);
806 vector_header_->AddPhi(phi);
Aart Bikf8f5a162017-02-06 15:35:29 -0800807 vector_header_->AddInstruction(cond);
808 vector_header_->AddInstruction(new (global_allocator_) HIf(cond));
Aart Bik14a68b42017-06-08 14:06:58 -0700809 vector_index_ = phi;
810 for (uint32_t u = 0; u < unroll; u++) {
811 // Clear map, leaving loop invariants setup during unrolling.
812 if (u == 0) {
813 vector_map_->clear();
814 } else {
815 for (auto i = vector_map_->begin(); i != vector_map_->end(); ) {
816 if (i->second->IsVecReplicateScalar()) {
817 DCHECK(node->loop_info->IsDefinedOutOfTheLoop(i->first));
818 ++i;
819 } else {
820 i = vector_map_->erase(i);
821 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800822 }
823 }
Aart Bik14a68b42017-06-08 14:06:58 -0700824 // Generate instruction map.
825 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
826 bool vectorized_def = VectorizeDef(node, it.Current(), /*generate_code*/ true);
827 DCHECK(vectorized_def);
828 }
829 // Generate body from the instruction map, but in original program order.
830 HEnvironment* env = vector_header_->GetFirstInstruction()->GetEnvironment();
831 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
832 auto i = vector_map_->find(it.Current());
833 if (i != vector_map_->end() && !i->second->IsInBlock()) {
834 Insert(vector_body_, i->second);
835 // Deal with instructions that need an environment, such as the scalar intrinsics.
836 if (i->second->NeedsEnvironment()) {
837 i->second->CopyEnvironmentFromWithLoopPhiAdjustment(env, vector_header_);
838 }
839 }
840 }
841 vector_index_ = new (global_allocator_) HAdd(induc_type, vector_index_, step);
842 Insert(vector_body_, vector_index_);
Aart Bikf8f5a162017-02-06 15:35:29 -0800843 }
Aart Bik14a68b42017-06-08 14:06:58 -0700844 // Finalize phi for the loop index.
845 phi->AddInput(lo);
846 phi->AddInput(vector_index_);
847 vector_index_ = phi;
Aart Bikf8f5a162017-02-06 15:35:29 -0800848}
849
850// TODO: accept reductions at left-hand-side, mixed-type store idioms, etc.
851bool HLoopOptimization::VectorizeDef(LoopNode* node,
852 HInstruction* instruction,
853 bool generate_code) {
854 // Accept a left-hand-side array base[index] for
855 // (1) supported vector type,
856 // (2) loop-invariant base,
857 // (3) unit stride index,
858 // (4) vectorizable right-hand-side value.
859 uint64_t restrictions = kNone;
860 if (instruction->IsArraySet()) {
861 Primitive::Type type = instruction->AsArraySet()->GetComponentType();
862 HInstruction* base = instruction->InputAt(0);
863 HInstruction* index = instruction->InputAt(1);
864 HInstruction* value = instruction->InputAt(2);
865 HInstruction* offset = nullptr;
866 if (TrySetVectorType(type, &restrictions) &&
867 node->loop_info->IsDefinedOutOfTheLoop(base) &&
Aart Bik37dc4df2017-06-28 14:08:00 -0700868 induction_range_.IsUnitStride(instruction, index, graph_, &offset) &&
Aart Bikf8f5a162017-02-06 15:35:29 -0800869 VectorizeUse(node, value, generate_code, type, restrictions)) {
870 if (generate_code) {
871 GenerateVecSub(index, offset);
Aart Bik14a68b42017-06-08 14:06:58 -0700872 GenerateVecMem(instruction, vector_map_->Get(index), vector_map_->Get(value), offset, type);
Aart Bikf8f5a162017-02-06 15:35:29 -0800873 } else {
874 vector_refs_->insert(ArrayReference(base, offset, type, /*lhs*/ true));
875 }
Aart Bik6b69e0a2017-01-11 10:20:43 -0800876 return true;
877 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800878 return false;
879 }
880 // Branch back okay.
881 if (instruction->IsGoto()) {
882 return true;
883 }
884 // Otherwise accept only expressions with no effects outside the immediate loop-body.
885 // Note that actual uses are inspected during right-hand-side tree traversal.
886 return !IsUsedOutsideLoop(node->loop_info, instruction) && !instruction->DoesAnyWrite();
887}
888
Aart Bik304c8a52017-05-23 11:01:13 -0700889// TODO: saturation arithmetic.
Aart Bikf8f5a162017-02-06 15:35:29 -0800890bool HLoopOptimization::VectorizeUse(LoopNode* node,
891 HInstruction* instruction,
892 bool generate_code,
893 Primitive::Type type,
894 uint64_t restrictions) {
895 // Accept anything for which code has already been generated.
896 if (generate_code) {
897 if (vector_map_->find(instruction) != vector_map_->end()) {
898 return true;
899 }
900 }
901 // Continue the right-hand-side tree traversal, passing in proper
902 // types and vector restrictions along the way. During code generation,
903 // all new nodes are drawn from the global allocator.
904 if (node->loop_info->IsDefinedOutOfTheLoop(instruction)) {
905 // Accept invariant use, using scalar expansion.
906 if (generate_code) {
907 GenerateVecInv(instruction, type);
908 }
909 return true;
910 } else if (instruction->IsArrayGet()) {
Goran Jakovljevic19680d32017-05-11 10:38:36 +0200911 // Deal with vector restrictions.
912 if (instruction->AsArrayGet()->IsStringCharAt() &&
913 HasVectorRestrictions(restrictions, kNoStringCharAt)) {
914 return false;
915 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800916 // Accept a right-hand-side array base[index] for
917 // (1) exact matching vector type,
918 // (2) loop-invariant base,
919 // (3) unit stride index,
920 // (4) vectorizable right-hand-side value.
921 HInstruction* base = instruction->InputAt(0);
922 HInstruction* index = instruction->InputAt(1);
923 HInstruction* offset = nullptr;
924 if (type == instruction->GetType() &&
925 node->loop_info->IsDefinedOutOfTheLoop(base) &&
Aart Bik37dc4df2017-06-28 14:08:00 -0700926 induction_range_.IsUnitStride(instruction, index, graph_, &offset)) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800927 if (generate_code) {
928 GenerateVecSub(index, offset);
Aart Bik14a68b42017-06-08 14:06:58 -0700929 GenerateVecMem(instruction, vector_map_->Get(index), nullptr, offset, type);
Aart Bikf8f5a162017-02-06 15:35:29 -0800930 } else {
931 vector_refs_->insert(ArrayReference(base, offset, type, /*lhs*/ false));
932 }
933 return true;
934 }
935 } else if (instruction->IsTypeConversion()) {
936 // Accept particular type conversions.
937 HTypeConversion* conversion = instruction->AsTypeConversion();
938 HInstruction* opa = conversion->InputAt(0);
939 Primitive::Type from = conversion->GetInputType();
940 Primitive::Type to = conversion->GetResultType();
941 if ((to == Primitive::kPrimByte ||
942 to == Primitive::kPrimChar ||
943 to == Primitive::kPrimShort) && from == Primitive::kPrimInt) {
944 // Accept a "narrowing" type conversion from a "wider" computation for
945 // (1) conversion into final required type,
946 // (2) vectorizable operand,
947 // (3) "wider" operations cannot bring in higher order bits.
948 if (to == type && VectorizeUse(node, opa, generate_code, type, restrictions | kNoHiBits)) {
949 if (generate_code) {
950 if (vector_mode_ == kVector) {
951 vector_map_->Put(instruction, vector_map_->Get(opa)); // operand pass-through
952 } else {
953 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
954 }
955 }
956 return true;
957 }
958 } else if (to == Primitive::kPrimFloat && from == Primitive::kPrimInt) {
959 DCHECK_EQ(to, type);
960 // Accept int to float conversion for
961 // (1) supported int,
962 // (2) vectorizable operand.
963 if (TrySetVectorType(from, &restrictions) &&
964 VectorizeUse(node, opa, generate_code, from, restrictions)) {
965 if (generate_code) {
966 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
967 }
968 return true;
969 }
970 }
971 return false;
972 } else if (instruction->IsNeg() || instruction->IsNot() || instruction->IsBooleanNot()) {
973 // Accept unary operator for vectorizable operand.
974 HInstruction* opa = instruction->InputAt(0);
975 if (VectorizeUse(node, opa, generate_code, type, restrictions)) {
976 if (generate_code) {
977 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
978 }
979 return true;
980 }
981 } else if (instruction->IsAdd() || instruction->IsSub() ||
982 instruction->IsMul() || instruction->IsDiv() ||
983 instruction->IsAnd() || instruction->IsOr() || instruction->IsXor()) {
984 // Deal with vector restrictions.
985 if ((instruction->IsMul() && HasVectorRestrictions(restrictions, kNoMul)) ||
986 (instruction->IsDiv() && HasVectorRestrictions(restrictions, kNoDiv))) {
987 return false;
988 }
989 // Accept binary operator for vectorizable operands.
990 HInstruction* opa = instruction->InputAt(0);
991 HInstruction* opb = instruction->InputAt(1);
992 if (VectorizeUse(node, opa, generate_code, type, restrictions) &&
993 VectorizeUse(node, opb, generate_code, type, restrictions)) {
994 if (generate_code) {
995 GenerateVecOp(instruction, vector_map_->Get(opa), vector_map_->Get(opb), type);
996 }
997 return true;
998 }
999 } else if (instruction->IsShl() || instruction->IsShr() || instruction->IsUShr()) {
Aart Bikf3e61ee2017-04-12 17:09:20 -07001000 // Recognize vectorization idioms.
1001 if (VectorizeHalvingAddIdiom(node, instruction, generate_code, type, restrictions)) {
1002 return true;
1003 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001004 // Deal with vector restrictions.
Aart Bik304c8a52017-05-23 11:01:13 -07001005 HInstruction* opa = instruction->InputAt(0);
1006 HInstruction* opb = instruction->InputAt(1);
1007 HInstruction* r = opa;
1008 bool is_unsigned = false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001009 if ((HasVectorRestrictions(restrictions, kNoShift)) ||
1010 (instruction->IsShr() && HasVectorRestrictions(restrictions, kNoShr))) {
1011 return false; // unsupported instruction
Aart Bik304c8a52017-05-23 11:01:13 -07001012 } else if (HasVectorRestrictions(restrictions, kNoHiBits)) {
1013 // Shifts right need extra care to account for higher order bits.
1014 // TODO: less likely shr/unsigned and ushr/signed can by flipping signess.
1015 if (instruction->IsShr() &&
1016 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || is_unsigned)) {
1017 return false; // reject, unless all operands are sign-extension narrower
1018 } else if (instruction->IsUShr() &&
1019 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || !is_unsigned)) {
1020 return false; // reject, unless all operands are zero-extension narrower
1021 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001022 }
1023 // Accept shift operator for vectorizable/invariant operands.
1024 // TODO: accept symbolic, albeit loop invariant shift factors.
Aart Bik304c8a52017-05-23 11:01:13 -07001025 DCHECK(r != nullptr);
1026 if (generate_code && vector_mode_ != kVector) { // de-idiom
1027 r = opa;
1028 }
Aart Bik50e20d52017-05-05 14:07:29 -07001029 int64_t distance = 0;
Aart Bik304c8a52017-05-23 11:01:13 -07001030 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
Aart Bik50e20d52017-05-05 14:07:29 -07001031 IsInt64AndGet(opb, /*out*/ &distance)) {
Aart Bik65ffd8e2017-05-01 16:50:45 -07001032 // Restrict shift distance to packed data type width.
1033 int64_t max_distance = Primitive::ComponentSize(type) * 8;
1034 if (0 <= distance && distance < max_distance) {
1035 if (generate_code) {
Aart Bik304c8a52017-05-23 11:01:13 -07001036 GenerateVecOp(instruction, vector_map_->Get(r), opb, type);
Aart Bik65ffd8e2017-05-01 16:50:45 -07001037 }
1038 return true;
Aart Bikf8f5a162017-02-06 15:35:29 -08001039 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001040 }
1041 } else if (instruction->IsInvokeStaticOrDirect()) {
Aart Bik6daebeb2017-04-03 14:35:41 -07001042 // Accept particular intrinsics.
1043 HInvokeStaticOrDirect* invoke = instruction->AsInvokeStaticOrDirect();
1044 switch (invoke->GetIntrinsic()) {
1045 case Intrinsics::kMathAbsInt:
1046 case Intrinsics::kMathAbsLong:
1047 case Intrinsics::kMathAbsFloat:
1048 case Intrinsics::kMathAbsDouble: {
1049 // Deal with vector restrictions.
Aart Bik304c8a52017-05-23 11:01:13 -07001050 HInstruction* opa = instruction->InputAt(0);
1051 HInstruction* r = opa;
1052 bool is_unsigned = false;
1053 if (HasVectorRestrictions(restrictions, kNoAbs)) {
Aart Bik6daebeb2017-04-03 14:35:41 -07001054 return false;
Aart Bik304c8a52017-05-23 11:01:13 -07001055 } else if (HasVectorRestrictions(restrictions, kNoHiBits) &&
1056 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || is_unsigned)) {
1057 return false; // reject, unless operand is sign-extension narrower
Aart Bik6daebeb2017-04-03 14:35:41 -07001058 }
1059 // Accept ABS(x) for vectorizable operand.
Aart Bik304c8a52017-05-23 11:01:13 -07001060 DCHECK(r != nullptr);
1061 if (generate_code && vector_mode_ != kVector) { // de-idiom
1062 r = opa;
1063 }
1064 if (VectorizeUse(node, r, generate_code, type, restrictions)) {
Aart Bik6daebeb2017-04-03 14:35:41 -07001065 if (generate_code) {
Aart Bik304c8a52017-05-23 11:01:13 -07001066 GenerateVecOp(instruction, vector_map_->Get(r), nullptr, type);
Aart Bik6daebeb2017-04-03 14:35:41 -07001067 }
1068 return true;
1069 }
1070 return false;
1071 }
Aart Bikc8e93c72017-05-10 10:49:22 -07001072 case Intrinsics::kMathMinIntInt:
1073 case Intrinsics::kMathMinLongLong:
1074 case Intrinsics::kMathMinFloatFloat:
1075 case Intrinsics::kMathMinDoubleDouble:
1076 case Intrinsics::kMathMaxIntInt:
1077 case Intrinsics::kMathMaxLongLong:
1078 case Intrinsics::kMathMaxFloatFloat:
1079 case Intrinsics::kMathMaxDoubleDouble: {
1080 // Deal with vector restrictions.
Nicolas Geoffray92316902017-05-23 08:06:07 +00001081 HInstruction* opa = instruction->InputAt(0);
1082 HInstruction* opb = instruction->InputAt(1);
Aart Bik304c8a52017-05-23 11:01:13 -07001083 HInstruction* r = opa;
1084 HInstruction* s = opb;
1085 bool is_unsigned = false;
1086 if (HasVectorRestrictions(restrictions, kNoMinMax)) {
1087 return false;
1088 } else if (HasVectorRestrictions(restrictions, kNoHiBits) &&
1089 !IsNarrowerOperands(opa, opb, type, &r, &s, &is_unsigned)) {
1090 return false; // reject, unless all operands are same-extension narrower
1091 }
1092 // Accept MIN/MAX(x, y) for vectorizable operands.
1093 DCHECK(r != nullptr && s != nullptr);
1094 if (generate_code && vector_mode_ != kVector) { // de-idiom
1095 r = opa;
1096 s = opb;
1097 }
1098 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
1099 VectorizeUse(node, s, generate_code, type, restrictions)) {
Aart Bikc8e93c72017-05-10 10:49:22 -07001100 if (generate_code) {
Aart Bik304c8a52017-05-23 11:01:13 -07001101 GenerateVecOp(
1102 instruction, vector_map_->Get(r), vector_map_->Get(s), type, is_unsigned);
Aart Bikc8e93c72017-05-10 10:49:22 -07001103 }
1104 return true;
1105 }
1106 return false;
1107 }
Aart Bik6daebeb2017-04-03 14:35:41 -07001108 default:
1109 return false;
1110 } // switch
Aart Bik281c6812016-08-26 11:31:48 -07001111 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08001112 return false;
Aart Bik281c6812016-08-26 11:31:48 -07001113}
1114
Aart Bikf8f5a162017-02-06 15:35:29 -08001115bool HLoopOptimization::TrySetVectorType(Primitive::Type type, uint64_t* restrictions) {
1116 const InstructionSetFeatures* features = compiler_driver_->GetInstructionSetFeatures();
1117 switch (compiler_driver_->GetInstructionSet()) {
1118 case kArm:
1119 case kThumb2:
Artem Serov8f7c4102017-06-21 11:21:37 +01001120 // Allow vectorization for all ARM devices, because Android assumes that
1121 // ARM 32-bit always supports advanced SIMD.
1122 switch (type) {
1123 case Primitive::kPrimBoolean:
1124 case Primitive::kPrimByte:
1125 *restrictions |= kNoDiv;
1126 return TrySetVectorLength(8);
1127 case Primitive::kPrimChar:
1128 case Primitive::kPrimShort:
1129 *restrictions |= kNoDiv | kNoStringCharAt;
1130 return TrySetVectorLength(4);
1131 case Primitive::kPrimInt:
1132 *restrictions |= kNoDiv;
1133 return TrySetVectorLength(2);
1134 default:
1135 break;
1136 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001137 return false;
1138 case kArm64:
1139 // Allow vectorization for all ARM devices, because Android assumes that
Artem Serovd4bccf12017-04-03 18:47:32 +01001140 // ARMv8 AArch64 always supports advanced SIMD.
Aart Bikf8f5a162017-02-06 15:35:29 -08001141 switch (type) {
1142 case Primitive::kPrimBoolean:
1143 case Primitive::kPrimByte:
Aart Bik304c8a52017-05-23 11:01:13 -07001144 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +01001145 return TrySetVectorLength(16);
Aart Bikf8f5a162017-02-06 15:35:29 -08001146 case Primitive::kPrimChar:
1147 case Primitive::kPrimShort:
Aart Bik304c8a52017-05-23 11:01:13 -07001148 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +01001149 return TrySetVectorLength(8);
Aart Bikf8f5a162017-02-06 15:35:29 -08001150 case Primitive::kPrimInt:
1151 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +01001152 return TrySetVectorLength(4);
Artem Serovb31f91f2017-04-05 11:31:19 +01001153 case Primitive::kPrimLong:
Aart Bikc8e93c72017-05-10 10:49:22 -07001154 *restrictions |= kNoDiv | kNoMul | kNoMinMax;
Aart Bikf8f5a162017-02-06 15:35:29 -08001155 return TrySetVectorLength(2);
1156 case Primitive::kPrimFloat:
Artem Serovd4bccf12017-04-03 18:47:32 +01001157 return TrySetVectorLength(4);
Artem Serovb31f91f2017-04-05 11:31:19 +01001158 case Primitive::kPrimDouble:
Aart Bikf8f5a162017-02-06 15:35:29 -08001159 return TrySetVectorLength(2);
1160 default:
1161 return false;
1162 }
1163 case kX86:
1164 case kX86_64:
1165 // Allow vectorization for SSE4-enabled X86 devices only (128-bit vectors).
1166 if (features->AsX86InstructionSetFeatures()->HasSSE4_1()) {
1167 switch (type) {
1168 case Primitive::kPrimBoolean:
1169 case Primitive::kPrimByte:
Aart Bikf3e61ee2017-04-12 17:09:20 -07001170 *restrictions |= kNoMul | kNoDiv | kNoShift | kNoAbs | kNoSignedHAdd | kNoUnroundedHAdd;
Aart Bikf8f5a162017-02-06 15:35:29 -08001171 return TrySetVectorLength(16);
1172 case Primitive::kPrimChar:
1173 case Primitive::kPrimShort:
Aart Bikf3e61ee2017-04-12 17:09:20 -07001174 *restrictions |= kNoDiv | kNoAbs | kNoSignedHAdd | kNoUnroundedHAdd;
Aart Bikf8f5a162017-02-06 15:35:29 -08001175 return TrySetVectorLength(8);
1176 case Primitive::kPrimInt:
1177 *restrictions |= kNoDiv;
1178 return TrySetVectorLength(4);
1179 case Primitive::kPrimLong:
Aart Bikc8e93c72017-05-10 10:49:22 -07001180 *restrictions |= kNoMul | kNoDiv | kNoShr | kNoAbs | kNoMinMax;
Aart Bikf8f5a162017-02-06 15:35:29 -08001181 return TrySetVectorLength(2);
1182 case Primitive::kPrimFloat:
Aart Bikc8e93c72017-05-10 10:49:22 -07001183 *restrictions |= kNoMinMax; // -0.0 vs +0.0
Aart Bikf8f5a162017-02-06 15:35:29 -08001184 return TrySetVectorLength(4);
1185 case Primitive::kPrimDouble:
Aart Bikc8e93c72017-05-10 10:49:22 -07001186 *restrictions |= kNoMinMax; // -0.0 vs +0.0
Aart Bikf8f5a162017-02-06 15:35:29 -08001187 return TrySetVectorLength(2);
1188 default:
1189 break;
1190 } // switch type
1191 }
1192 return false;
1193 case kMips:
Lena Djokic51765b02017-06-22 13:49:59 +02001194 if (features->AsMipsInstructionSetFeatures()->HasMsa()) {
1195 switch (type) {
1196 case Primitive::kPrimBoolean:
1197 case Primitive::kPrimByte:
1198 *restrictions |= kNoDiv;
1199 return TrySetVectorLength(16);
1200 case Primitive::kPrimChar:
1201 case Primitive::kPrimShort:
1202 *restrictions |= kNoDiv | kNoStringCharAt;
1203 return TrySetVectorLength(8);
1204 case Primitive::kPrimInt:
1205 *restrictions |= kNoDiv;
1206 return TrySetVectorLength(4);
1207 case Primitive::kPrimLong:
1208 *restrictions |= kNoDiv;
1209 return TrySetVectorLength(2);
1210 case Primitive::kPrimFloat:
1211 *restrictions |= kNoMinMax; // min/max(x, NaN)
1212 return TrySetVectorLength(4);
1213 case Primitive::kPrimDouble:
1214 *restrictions |= kNoMinMax; // min/max(x, NaN)
1215 return TrySetVectorLength(2);
1216 default:
1217 break;
1218 } // switch type
1219 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001220 return false;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001221 case kMips64:
1222 if (features->AsMips64InstructionSetFeatures()->HasMsa()) {
1223 switch (type) {
1224 case Primitive::kPrimBoolean:
1225 case Primitive::kPrimByte:
Goran Jakovljevic8fea1e12017-06-06 13:28:42 +02001226 *restrictions |= kNoDiv;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001227 return TrySetVectorLength(16);
1228 case Primitive::kPrimChar:
1229 case Primitive::kPrimShort:
Goran Jakovljevic8fea1e12017-06-06 13:28:42 +02001230 *restrictions |= kNoDiv | kNoStringCharAt;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001231 return TrySetVectorLength(8);
1232 case Primitive::kPrimInt:
Goran Jakovljevic8fea1e12017-06-06 13:28:42 +02001233 *restrictions |= kNoDiv;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001234 return TrySetVectorLength(4);
1235 case Primitive::kPrimLong:
Goran Jakovljevic8fea1e12017-06-06 13:28:42 +02001236 *restrictions |= kNoDiv;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001237 return TrySetVectorLength(2);
1238 case Primitive::kPrimFloat:
Goran Jakovljevic8fea1e12017-06-06 13:28:42 +02001239 *restrictions |= kNoMinMax; // min/max(x, NaN)
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001240 return TrySetVectorLength(4);
1241 case Primitive::kPrimDouble:
Goran Jakovljevic8fea1e12017-06-06 13:28:42 +02001242 *restrictions |= kNoMinMax; // min/max(x, NaN)
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001243 return TrySetVectorLength(2);
1244 default:
1245 break;
1246 } // switch type
1247 }
1248 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001249 default:
1250 return false;
1251 } // switch instruction set
1252}
1253
1254bool HLoopOptimization::TrySetVectorLength(uint32_t length) {
1255 DCHECK(IsPowerOfTwo(length) && length >= 2u);
1256 // First time set?
1257 if (vector_length_ == 0) {
1258 vector_length_ = length;
1259 }
1260 // Different types are acceptable within a loop-body, as long as all the corresponding vector
1261 // lengths match exactly to obtain a uniform traversal through the vector iteration space
1262 // (idiomatic exceptions to this rule can be handled by further unrolling sub-expressions).
1263 return vector_length_ == length;
1264}
1265
1266void HLoopOptimization::GenerateVecInv(HInstruction* org, Primitive::Type type) {
1267 if (vector_map_->find(org) == vector_map_->end()) {
1268 // In scalar code, just use a self pass-through for scalar invariants
1269 // (viz. expression remains itself).
1270 if (vector_mode_ == kSequential) {
1271 vector_map_->Put(org, org);
1272 return;
1273 }
1274 // In vector code, explicit scalar expansion is needed.
1275 HInstruction* vector = new (global_allocator_) HVecReplicateScalar(
1276 global_allocator_, org, type, vector_length_);
1277 vector_map_->Put(org, Insert(vector_preheader_, vector));
1278 }
1279}
1280
1281void HLoopOptimization::GenerateVecSub(HInstruction* org, HInstruction* offset) {
1282 if (vector_map_->find(org) == vector_map_->end()) {
Aart Bik14a68b42017-06-08 14:06:58 -07001283 HInstruction* subscript = vector_index_;
Aart Bik37dc4df2017-06-28 14:08:00 -07001284 int64_t value = 0;
1285 if (!IsInt64AndGet(offset, &value) || value != 0) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001286 subscript = new (global_allocator_) HAdd(Primitive::kPrimInt, subscript, offset);
1287 if (org->IsPhi()) {
1288 Insert(vector_body_, subscript); // lacks layout placeholder
1289 }
1290 }
1291 vector_map_->Put(org, subscript);
1292 }
1293}
1294
1295void HLoopOptimization::GenerateVecMem(HInstruction* org,
1296 HInstruction* opa,
1297 HInstruction* opb,
Aart Bik14a68b42017-06-08 14:06:58 -07001298 HInstruction* offset,
Aart Bikf8f5a162017-02-06 15:35:29 -08001299 Primitive::Type type) {
1300 HInstruction* vector = nullptr;
1301 if (vector_mode_ == kVector) {
1302 // Vector store or load.
Aart Bik14a68b42017-06-08 14:06:58 -07001303 HInstruction* base = org->InputAt(0);
Aart Bikf8f5a162017-02-06 15:35:29 -08001304 if (opb != nullptr) {
1305 vector = new (global_allocator_) HVecStore(
Aart Bik14a68b42017-06-08 14:06:58 -07001306 global_allocator_, base, opa, opb, type, vector_length_);
Aart Bikf8f5a162017-02-06 15:35:29 -08001307 } else {
Aart Bikdb14fcf2017-04-25 15:53:58 -07001308 bool is_string_char_at = org->AsArrayGet()->IsStringCharAt();
Aart Bikf8f5a162017-02-06 15:35:29 -08001309 vector = new (global_allocator_) HVecLoad(
Aart Bik14a68b42017-06-08 14:06:58 -07001310 global_allocator_, base, opa, type, vector_length_, is_string_char_at);
1311 }
1312 // Known dynamically enforced alignment?
1313 // TODO: detect offset + constant differences.
1314 // TODO: long run, static alignment analysis?
1315 if (vector_peeling_candidate_ != nullptr &&
1316 vector_peeling_candidate_->base == base &&
1317 vector_peeling_candidate_->offset == offset) {
1318 vector->AsVecMemoryOperation()->SetAlignment(Alignment(kAlignedBase, 0));
Aart Bikf8f5a162017-02-06 15:35:29 -08001319 }
1320 } else {
1321 // Scalar store or load.
1322 DCHECK(vector_mode_ == kSequential);
1323 if (opb != nullptr) {
1324 vector = new (global_allocator_) HArraySet(org->InputAt(0), opa, opb, type, kNoDexPc);
1325 } else {
Aart Bikdb14fcf2017-04-25 15:53:58 -07001326 bool is_string_char_at = org->AsArrayGet()->IsStringCharAt();
1327 vector = new (global_allocator_) HArrayGet(
1328 org->InputAt(0), opa, type, kNoDexPc, is_string_char_at);
Aart Bikf8f5a162017-02-06 15:35:29 -08001329 }
1330 }
1331 vector_map_->Put(org, vector);
1332}
1333
1334#define GENERATE_VEC(x, y) \
1335 if (vector_mode_ == kVector) { \
1336 vector = (x); \
1337 } else { \
1338 DCHECK(vector_mode_ == kSequential); \
1339 vector = (y); \
1340 } \
1341 break;
1342
1343void HLoopOptimization::GenerateVecOp(HInstruction* org,
1344 HInstruction* opa,
1345 HInstruction* opb,
Aart Bik304c8a52017-05-23 11:01:13 -07001346 Primitive::Type type,
1347 bool is_unsigned) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001348 if (vector_mode_ == kSequential) {
Aart Bik304c8a52017-05-23 11:01:13 -07001349 // Non-converting scalar code follows implicit integral promotion.
1350 if (!org->IsTypeConversion() && (type == Primitive::kPrimBoolean ||
1351 type == Primitive::kPrimByte ||
1352 type == Primitive::kPrimChar ||
1353 type == Primitive::kPrimShort)) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001354 type = Primitive::kPrimInt;
1355 }
1356 }
1357 HInstruction* vector = nullptr;
1358 switch (org->GetKind()) {
1359 case HInstruction::kNeg:
1360 DCHECK(opb == nullptr);
1361 GENERATE_VEC(
1362 new (global_allocator_) HVecNeg(global_allocator_, opa, type, vector_length_),
1363 new (global_allocator_) HNeg(type, opa));
1364 case HInstruction::kNot:
1365 DCHECK(opb == nullptr);
1366 GENERATE_VEC(
1367 new (global_allocator_) HVecNot(global_allocator_, opa, type, vector_length_),
1368 new (global_allocator_) HNot(type, opa));
1369 case HInstruction::kBooleanNot:
1370 DCHECK(opb == nullptr);
1371 GENERATE_VEC(
1372 new (global_allocator_) HVecNot(global_allocator_, opa, type, vector_length_),
1373 new (global_allocator_) HBooleanNot(opa));
1374 case HInstruction::kTypeConversion:
1375 DCHECK(opb == nullptr);
1376 GENERATE_VEC(
1377 new (global_allocator_) HVecCnv(global_allocator_, opa, type, vector_length_),
1378 new (global_allocator_) HTypeConversion(type, opa, kNoDexPc));
1379 case HInstruction::kAdd:
1380 GENERATE_VEC(
1381 new (global_allocator_) HVecAdd(global_allocator_, opa, opb, type, vector_length_),
1382 new (global_allocator_) HAdd(type, opa, opb));
1383 case HInstruction::kSub:
1384 GENERATE_VEC(
1385 new (global_allocator_) HVecSub(global_allocator_, opa, opb, type, vector_length_),
1386 new (global_allocator_) HSub(type, opa, opb));
1387 case HInstruction::kMul:
1388 GENERATE_VEC(
1389 new (global_allocator_) HVecMul(global_allocator_, opa, opb, type, vector_length_),
1390 new (global_allocator_) HMul(type, opa, opb));
1391 case HInstruction::kDiv:
1392 GENERATE_VEC(
1393 new (global_allocator_) HVecDiv(global_allocator_, opa, opb, type, vector_length_),
1394 new (global_allocator_) HDiv(type, opa, opb, kNoDexPc));
1395 case HInstruction::kAnd:
1396 GENERATE_VEC(
1397 new (global_allocator_) HVecAnd(global_allocator_, opa, opb, type, vector_length_),
1398 new (global_allocator_) HAnd(type, opa, opb));
1399 case HInstruction::kOr:
1400 GENERATE_VEC(
1401 new (global_allocator_) HVecOr(global_allocator_, opa, opb, type, vector_length_),
1402 new (global_allocator_) HOr(type, opa, opb));
1403 case HInstruction::kXor:
1404 GENERATE_VEC(
1405 new (global_allocator_) HVecXor(global_allocator_, opa, opb, type, vector_length_),
1406 new (global_allocator_) HXor(type, opa, opb));
1407 case HInstruction::kShl:
1408 GENERATE_VEC(
1409 new (global_allocator_) HVecShl(global_allocator_, opa, opb, type, vector_length_),
1410 new (global_allocator_) HShl(type, opa, opb));
1411 case HInstruction::kShr:
1412 GENERATE_VEC(
1413 new (global_allocator_) HVecShr(global_allocator_, opa, opb, type, vector_length_),
1414 new (global_allocator_) HShr(type, opa, opb));
1415 case HInstruction::kUShr:
1416 GENERATE_VEC(
1417 new (global_allocator_) HVecUShr(global_allocator_, opa, opb, type, vector_length_),
1418 new (global_allocator_) HUShr(type, opa, opb));
1419 case HInstruction::kInvokeStaticOrDirect: {
Aart Bik6daebeb2017-04-03 14:35:41 -07001420 HInvokeStaticOrDirect* invoke = org->AsInvokeStaticOrDirect();
1421 if (vector_mode_ == kVector) {
1422 switch (invoke->GetIntrinsic()) {
1423 case Intrinsics::kMathAbsInt:
1424 case Intrinsics::kMathAbsLong:
1425 case Intrinsics::kMathAbsFloat:
1426 case Intrinsics::kMathAbsDouble:
1427 DCHECK(opb == nullptr);
1428 vector = new (global_allocator_) HVecAbs(global_allocator_, opa, type, vector_length_);
1429 break;
Aart Bikc8e93c72017-05-10 10:49:22 -07001430 case Intrinsics::kMathMinIntInt:
1431 case Intrinsics::kMathMinLongLong:
1432 case Intrinsics::kMathMinFloatFloat:
1433 case Intrinsics::kMathMinDoubleDouble: {
Aart Bikc8e93c72017-05-10 10:49:22 -07001434 vector = new (global_allocator_)
1435 HVecMin(global_allocator_, opa, opb, type, vector_length_, is_unsigned);
1436 break;
1437 }
1438 case Intrinsics::kMathMaxIntInt:
1439 case Intrinsics::kMathMaxLongLong:
1440 case Intrinsics::kMathMaxFloatFloat:
1441 case Intrinsics::kMathMaxDoubleDouble: {
Aart Bikc8e93c72017-05-10 10:49:22 -07001442 vector = new (global_allocator_)
1443 HVecMax(global_allocator_, opa, opb, type, vector_length_, is_unsigned);
1444 break;
1445 }
Aart Bik6daebeb2017-04-03 14:35:41 -07001446 default:
1447 LOG(FATAL) << "Unsupported SIMD intrinsic";
1448 UNREACHABLE();
1449 } // switch invoke
1450 } else {
Aart Bik24b905f2017-04-06 09:59:06 -07001451 // In scalar code, simply clone the method invoke, and replace its operands with the
1452 // corresponding new scalar instructions in the loop. The instruction will get an
1453 // environment while being inserted from the instruction map in original program order.
Aart Bik6daebeb2017-04-03 14:35:41 -07001454 DCHECK(vector_mode_ == kSequential);
Aart Bik6e92fb32017-06-05 14:05:09 -07001455 size_t num_args = invoke->GetNumberOfArguments();
Aart Bik6daebeb2017-04-03 14:35:41 -07001456 HInvokeStaticOrDirect* new_invoke = new (global_allocator_) HInvokeStaticOrDirect(
1457 global_allocator_,
Aart Bik6e92fb32017-06-05 14:05:09 -07001458 num_args,
Aart Bik6daebeb2017-04-03 14:35:41 -07001459 invoke->GetType(),
1460 invoke->GetDexPc(),
1461 invoke->GetDexMethodIndex(),
1462 invoke->GetResolvedMethod(),
1463 invoke->GetDispatchInfo(),
1464 invoke->GetInvokeType(),
1465 invoke->GetTargetMethod(),
1466 invoke->GetClinitCheckRequirement());
1467 HInputsRef inputs = invoke->GetInputs();
Aart Bik6e92fb32017-06-05 14:05:09 -07001468 size_t num_inputs = inputs.size();
1469 DCHECK_LE(num_args, num_inputs);
1470 DCHECK_EQ(num_inputs, new_invoke->GetInputs().size()); // both invokes agree
1471 for (size_t index = 0; index < num_inputs; ++index) {
1472 HInstruction* new_input = index < num_args
1473 ? vector_map_->Get(inputs[index])
1474 : inputs[index]; // beyond arguments: just pass through
1475 new_invoke->SetArgumentAt(index, new_input);
Aart Bik6daebeb2017-04-03 14:35:41 -07001476 }
Aart Bik98990262017-04-10 13:15:57 -07001477 new_invoke->SetIntrinsic(invoke->GetIntrinsic(),
1478 kNeedsEnvironmentOrCache,
1479 kNoSideEffects,
1480 kNoThrow);
Aart Bik6daebeb2017-04-03 14:35:41 -07001481 vector = new_invoke;
1482 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001483 break;
1484 }
1485 default:
1486 break;
1487 } // switch
1488 CHECK(vector != nullptr) << "Unsupported SIMD operator";
1489 vector_map_->Put(org, vector);
1490}
1491
1492#undef GENERATE_VEC
1493
1494//
Aart Bikf3e61ee2017-04-12 17:09:20 -07001495// Vectorization idioms.
1496//
1497
1498// Method recognizes the following idioms:
1499// rounding halving add (a + b + 1) >> 1 for unsigned/signed operands a, b
1500// regular halving add (a + b) >> 1 for unsigned/signed operands a, b
1501// Provided that the operands are promoted to a wider form to do the arithmetic and
1502// then cast back to narrower form, the idioms can be mapped into efficient SIMD
1503// implementation that operates directly in narrower form (plus one extra bit).
1504// TODO: current version recognizes implicit byte/short/char widening only;
1505// explicit widening from int to long could be added later.
1506bool HLoopOptimization::VectorizeHalvingAddIdiom(LoopNode* node,
1507 HInstruction* instruction,
1508 bool generate_code,
1509 Primitive::Type type,
1510 uint64_t restrictions) {
1511 // Test for top level arithmetic shift right x >> 1 or logical shift right x >>> 1
Aart Bik304c8a52017-05-23 11:01:13 -07001512 // (note whether the sign bit in wider precision is shifted in has no effect
Aart Bikf3e61ee2017-04-12 17:09:20 -07001513 // on the narrow precision computed by the idiom).
Aart Bik5f805002017-05-16 16:42:41 -07001514 int64_t distance = 0;
Aart Bikf3e61ee2017-04-12 17:09:20 -07001515 if ((instruction->IsShr() ||
1516 instruction->IsUShr()) &&
Aart Bik5f805002017-05-16 16:42:41 -07001517 IsInt64AndGet(instruction->InputAt(1), /*out*/ &distance) && distance == 1) {
1518 // Test for (a + b + c) >> 1 for optional constant c.
1519 HInstruction* a = nullptr;
1520 HInstruction* b = nullptr;
1521 int64_t c = 0;
1522 if (IsAddConst(instruction->InputAt(0), /*out*/ &a, /*out*/ &b, /*out*/ &c)) {
Aart Bik304c8a52017-05-23 11:01:13 -07001523 DCHECK(a != nullptr && b != nullptr);
Aart Bik5f805002017-05-16 16:42:41 -07001524 // Accept c == 1 (rounded) or c == 0 (not rounded).
1525 bool is_rounded = false;
1526 if (c == 1) {
1527 is_rounded = true;
1528 } else if (c != 0) {
1529 return false;
1530 }
1531 // Accept consistent zero or sign extension on operands a and b.
Aart Bikf3e61ee2017-04-12 17:09:20 -07001532 HInstruction* r = nullptr;
1533 HInstruction* s = nullptr;
1534 bool is_unsigned = false;
Aart Bik304c8a52017-05-23 11:01:13 -07001535 if (!IsNarrowerOperands(a, b, type, &r, &s, &is_unsigned)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -07001536 return false;
1537 }
1538 // Deal with vector restrictions.
1539 if ((!is_unsigned && HasVectorRestrictions(restrictions, kNoSignedHAdd)) ||
1540 (!is_rounded && HasVectorRestrictions(restrictions, kNoUnroundedHAdd))) {
1541 return false;
1542 }
1543 // Accept recognized halving add for vectorizable operands. Vectorized code uses the
1544 // shorthand idiomatic operation. Sequential code uses the original scalar expressions.
1545 DCHECK(r != nullptr && s != nullptr);
Aart Bik304c8a52017-05-23 11:01:13 -07001546 if (generate_code && vector_mode_ != kVector) { // de-idiom
1547 r = instruction->InputAt(0);
1548 s = instruction->InputAt(1);
1549 }
Aart Bikf3e61ee2017-04-12 17:09:20 -07001550 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
1551 VectorizeUse(node, s, generate_code, type, restrictions)) {
1552 if (generate_code) {
1553 if (vector_mode_ == kVector) {
1554 vector_map_->Put(instruction, new (global_allocator_) HVecHalvingAdd(
1555 global_allocator_,
1556 vector_map_->Get(r),
1557 vector_map_->Get(s),
1558 type,
1559 vector_length_,
1560 is_unsigned,
1561 is_rounded));
1562 } else {
Aart Bik304c8a52017-05-23 11:01:13 -07001563 GenerateVecOp(instruction, vector_map_->Get(r), vector_map_->Get(s), type);
Aart Bikf3e61ee2017-04-12 17:09:20 -07001564 }
1565 }
1566 return true;
1567 }
1568 }
1569 }
1570 return false;
1571}
1572
1573//
Aart Bik14a68b42017-06-08 14:06:58 -07001574// Vectorization heuristics.
1575//
1576
1577bool HLoopOptimization::IsVectorizationProfitable(int64_t trip_count) {
1578 // Current heuristic: non-empty body with sufficient number
1579 // of iterations (if known).
1580 // TODO: refine by looking at e.g. operation count, alignment, etc.
1581 if (vector_length_ == 0) {
1582 return false; // nothing found
1583 } else if (0 < trip_count && trip_count < vector_length_) {
1584 return false; // insufficient iterations
1585 }
1586 return true;
1587}
1588
1589void HLoopOptimization::SetPeelingCandidate(int64_t trip_count ATTRIBUTE_UNUSED) {
1590 // Current heuristic: none.
1591 // TODO: implement
1592}
1593
1594uint32_t HLoopOptimization::GetUnrollingFactor(HBasicBlock* block, int64_t trip_count) {
1595 // Current heuristic: unroll by 2 on ARM64/X86 for large known trip
1596 // counts and small loop bodies.
1597 // TODO: refine with operation count, remaining iterations, etc.
1598 // Artem had some really cool ideas for this already.
1599 switch (compiler_driver_->GetInstructionSet()) {
1600 case kArm64:
1601 case kX86:
1602 case kX86_64: {
1603 size_t num_instructions = block->GetInstructions().CountSize();
1604 if (num_instructions <= 10 && trip_count >= 4 * vector_length_) {
1605 return 2;
1606 }
1607 return 1;
1608 }
1609 default:
1610 return 1;
1611 }
1612}
1613
1614//
Aart Bikf8f5a162017-02-06 15:35:29 -08001615// Helpers.
1616//
1617
1618bool HLoopOptimization::TrySetPhiInduction(HPhi* phi, bool restrict_uses) {
Nicolas Geoffrayf57c1ae2017-06-28 17:40:18 +01001619 // Special case Phis that have equivalent in a debuggable setup. Our graph checker isn't
1620 // smart enough to follow strongly connected components (and it's probably not worth
1621 // it to make it so). See b/33775412.
1622 if (graph_->IsDebuggable() && phi->HasEquivalentPhi()) {
1623 return false;
1624 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001625 DCHECK(iset_->empty());
Aart Bikcc42be02016-10-20 16:14:16 -07001626 ArenaSet<HInstruction*>* set = induction_range_.LookupCycle(phi);
1627 if (set != nullptr) {
1628 for (HInstruction* i : *set) {
Aart Bike3dedc52016-11-02 17:50:27 -07001629 // Check that, other than instructions that are no longer in the graph (removed earlier)
Aart Bikf8f5a162017-02-06 15:35:29 -08001630 // each instruction is removable and, when restrict uses are requested, other than for phi,
1631 // all uses are contained within the cycle.
Aart Bike3dedc52016-11-02 17:50:27 -07001632 if (!i->IsInBlock()) {
1633 continue;
1634 } else if (!i->IsRemovable()) {
1635 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001636 } else if (i != phi && restrict_uses) {
Aart Bikcc42be02016-10-20 16:14:16 -07001637 for (const HUseListNode<HInstruction*>& use : i->GetUses()) {
1638 if (set->find(use.GetUser()) == set->end()) {
1639 return false;
1640 }
1641 }
1642 }
Aart Bike3dedc52016-11-02 17:50:27 -07001643 iset_->insert(i); // copy
Aart Bikcc42be02016-10-20 16:14:16 -07001644 }
Aart Bikcc42be02016-10-20 16:14:16 -07001645 return true;
1646 }
1647 return false;
1648}
1649
1650// Find: phi: Phi(init, addsub)
1651// s: SuspendCheck
1652// c: Condition(phi, bound)
1653// i: If(c)
1654// TODO: Find a less pattern matching approach?
Aart Bikf8f5a162017-02-06 15:35:29 -08001655bool HLoopOptimization::TrySetSimpleLoopHeader(HBasicBlock* block) {
Aart Bikcc42be02016-10-20 16:14:16 -07001656 DCHECK(iset_->empty());
1657 HInstruction* phi = block->GetFirstPhi();
Aart Bikf8f5a162017-02-06 15:35:29 -08001658 if (phi != nullptr &&
1659 phi->GetNext() == nullptr &&
1660 TrySetPhiInduction(phi->AsPhi(), /*restrict_uses*/ false)) {
Aart Bikcc42be02016-10-20 16:14:16 -07001661 HInstruction* s = block->GetFirstInstruction();
1662 if (s != nullptr && s->IsSuspendCheck()) {
1663 HInstruction* c = s->GetNext();
Aart Bikd86c0852017-04-14 12:00:15 -07001664 if (c != nullptr &&
1665 c->IsCondition() &&
1666 c->GetUses().HasExactlyOneElement() && // only used for termination
1667 !c->HasEnvironmentUses()) { // unlikely, but not impossible
Aart Bikcc42be02016-10-20 16:14:16 -07001668 HInstruction* i = c->GetNext();
1669 if (i != nullptr && i->IsIf() && i->InputAt(0) == c) {
1670 iset_->insert(c);
1671 iset_->insert(s);
1672 return true;
1673 }
1674 }
1675 }
1676 }
1677 return false;
1678}
1679
1680bool HLoopOptimization::IsEmptyBody(HBasicBlock* block) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001681 if (!block->GetPhis().IsEmpty()) {
1682 return false;
1683 }
1684 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
1685 HInstruction* instruction = it.Current();
1686 if (!instruction->IsGoto() && iset_->find(instruction) == iset_->end()) {
1687 return false;
Aart Bikcc42be02016-10-20 16:14:16 -07001688 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001689 }
1690 return true;
1691}
1692
1693bool HLoopOptimization::IsUsedOutsideLoop(HLoopInformation* loop_info,
1694 HInstruction* instruction) {
1695 for (const HUseListNode<HInstruction*>& use : instruction->GetUses()) {
1696 if (use.GetUser()->GetBlock()->GetLoopInformation() != loop_info) {
1697 return true;
1698 }
Aart Bikcc42be02016-10-20 16:14:16 -07001699 }
1700 return false;
1701}
1702
Aart Bik482095d2016-10-10 15:39:10 -07001703bool HLoopOptimization::IsOnlyUsedAfterLoop(HLoopInformation* loop_info,
Aart Bik8c4a8542016-10-06 11:36:57 -07001704 HInstruction* instruction,
Aart Bik6b69e0a2017-01-11 10:20:43 -08001705 bool collect_loop_uses,
Aart Bik8c4a8542016-10-06 11:36:57 -07001706 /*out*/ int32_t* use_count) {
1707 for (const HUseListNode<HInstruction*>& use : instruction->GetUses()) {
1708 HInstruction* user = use.GetUser();
1709 if (iset_->find(user) == iset_->end()) { // not excluded?
1710 HLoopInformation* other_loop_info = user->GetBlock()->GetLoopInformation();
Aart Bik482095d2016-10-10 15:39:10 -07001711 if (other_loop_info != nullptr && other_loop_info->IsIn(*loop_info)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -08001712 // If collect_loop_uses is set, simply keep adding those uses to the set.
1713 // Otherwise, reject uses inside the loop that were not already in the set.
1714 if (collect_loop_uses) {
1715 iset_->insert(user);
1716 continue;
1717 }
Aart Bik8c4a8542016-10-06 11:36:57 -07001718 return false;
1719 }
1720 ++*use_count;
1721 }
1722 }
1723 return true;
1724}
1725
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01001726bool HLoopOptimization::TryReplaceWithLastValue(HLoopInformation* loop_info,
1727 HInstruction* instruction,
1728 HBasicBlock* block) {
1729 // Try to replace outside uses with the last value.
Aart Bik807868e2016-11-03 17:51:43 -07001730 if (induction_range_.CanGenerateLastValue(instruction)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -08001731 HInstruction* replacement = induction_range_.GenerateLastValue(instruction, graph_, block);
1732 const HUseList<HInstruction*>& uses = instruction->GetUses();
1733 for (auto it = uses.begin(), end = uses.end(); it != end;) {
1734 HInstruction* user = it->GetUser();
1735 size_t index = it->GetIndex();
1736 ++it; // increment before replacing
1737 if (iset_->find(user) == iset_->end()) { // not excluded?
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01001738 if (kIsDebugBuild) {
1739 // We have checked earlier in 'IsOnlyUsedAfterLoop' that the use is after the loop.
1740 HLoopInformation* other_loop_info = user->GetBlock()->GetLoopInformation();
1741 CHECK(other_loop_info == nullptr || !other_loop_info->IsIn(*loop_info));
1742 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08001743 user->ReplaceInput(replacement, index);
1744 induction_range_.Replace(user, instruction, replacement); // update induction
1745 }
1746 }
1747 const HUseList<HEnvironment*>& env_uses = instruction->GetEnvUses();
1748 for (auto it = env_uses.begin(), end = env_uses.end(); it != end;) {
1749 HEnvironment* user = it->GetUser();
1750 size_t index = it->GetIndex();
1751 ++it; // increment before replacing
1752 if (iset_->find(user->GetHolder()) == iset_->end()) { // not excluded?
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01001753 // Only update environment uses after the loop.
Aart Bik14a68b42017-06-08 14:06:58 -07001754 HLoopInformation* other_loop_info = user->GetHolder()->GetBlock()->GetLoopInformation();
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01001755 if (other_loop_info == nullptr || !other_loop_info->IsIn(*loop_info)) {
1756 user->RemoveAsUserOfInput(index);
1757 user->SetRawEnvAt(index, replacement);
1758 replacement->AddEnvUseAt(user, index);
1759 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08001760 }
1761 }
1762 induction_simplication_count_++;
Aart Bik807868e2016-11-03 17:51:43 -07001763 return true;
Aart Bik8c4a8542016-10-06 11:36:57 -07001764 }
Aart Bik807868e2016-11-03 17:51:43 -07001765 return false;
Aart Bik8c4a8542016-10-06 11:36:57 -07001766}
1767
Aart Bikf8f5a162017-02-06 15:35:29 -08001768bool HLoopOptimization::TryAssignLastValue(HLoopInformation* loop_info,
1769 HInstruction* instruction,
1770 HBasicBlock* block,
1771 bool collect_loop_uses) {
1772 // Assigning the last value is always successful if there are no uses.
1773 // Otherwise, it succeeds in a no early-exit loop by generating the
1774 // proper last value assignment.
1775 int32_t use_count = 0;
1776 return IsOnlyUsedAfterLoop(loop_info, instruction, collect_loop_uses, &use_count) &&
1777 (use_count == 0 ||
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01001778 (!IsEarlyExit(loop_info) && TryReplaceWithLastValue(loop_info, instruction, block)));
Aart Bikf8f5a162017-02-06 15:35:29 -08001779}
1780
Aart Bik6b69e0a2017-01-11 10:20:43 -08001781void HLoopOptimization::RemoveDeadInstructions(const HInstructionList& list) {
1782 for (HBackwardInstructionIterator i(list); !i.Done(); i.Advance()) {
1783 HInstruction* instruction = i.Current();
1784 if (instruction->IsDeadAndRemovable()) {
1785 simplified_ = true;
1786 instruction->GetBlock()->RemoveInstructionOrPhi(instruction);
1787 }
1788 }
1789}
1790
Aart Bik14a68b42017-06-08 14:06:58 -07001791bool HLoopOptimization::CanRemoveCycle() {
1792 for (HInstruction* i : *iset_) {
1793 // We can never remove instructions that have environment
1794 // uses when we compile 'debuggable'.
1795 if (i->HasEnvironmentUses() && graph_->IsDebuggable()) {
1796 return false;
1797 }
1798 // A deoptimization should never have an environment input removed.
1799 for (const HUseListNode<HEnvironment*>& use : i->GetEnvUses()) {
1800 if (use.GetUser()->GetHolder()->IsDeoptimize()) {
1801 return false;
1802 }
1803 }
1804 }
1805 return true;
1806}
1807
Aart Bik281c6812016-08-26 11:31:48 -07001808} // namespace art