blob: 42ed04dfa3d8b64c923d0b5789291b3404d6cb0c [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 Bikf8f5a162017-02-06 15:35:29 -080066// Test vector restrictions.
67static bool HasVectorRestrictions(uint64_t restrictions, uint64_t tested) {
68 return (restrictions & tested) != 0;
69}
70
71// Inserts an instruction.
72static HInstruction* Insert(HBasicBlock* block, HInstruction* instruction) {
73 DCHECK(block != nullptr);
74 DCHECK(instruction != nullptr);
75 block->InsertInstructionBefore(instruction, block->GetLastInstruction());
76 return instruction;
77}
78
Aart Bik281c6812016-08-26 11:31:48 -070079//
80// Class methods.
81//
82
83HLoopOptimization::HLoopOptimization(HGraph* graph,
Aart Bik92685a82017-03-06 11:13:43 -080084 CompilerDriver* compiler_driver,
Aart Bik281c6812016-08-26 11:31:48 -070085 HInductionVarAnalysis* induction_analysis)
86 : HOptimization(graph, kLoopOptimizationPassName),
Aart Bik92685a82017-03-06 11:13:43 -080087 compiler_driver_(compiler_driver),
Aart Bik281c6812016-08-26 11:31:48 -070088 induction_range_(induction_analysis),
Aart Bik96202302016-10-04 17:33:56 -070089 loop_allocator_(nullptr),
Aart Bikf8f5a162017-02-06 15:35:29 -080090 global_allocator_(graph_->GetArena()),
Aart Bik281c6812016-08-26 11:31:48 -070091 top_loop_(nullptr),
Aart Bik8c4a8542016-10-06 11:36:57 -070092 last_loop_(nullptr),
Aart Bik482095d2016-10-10 15:39:10 -070093 iset_(nullptr),
Aart Bikdf7822e2016-12-06 10:05:30 -080094 induction_simplication_count_(0),
Aart Bikf8f5a162017-02-06 15:35:29 -080095 simplified_(false),
96 vector_length_(0),
97 vector_refs_(nullptr),
98 vector_map_(nullptr) {
Aart Bik281c6812016-08-26 11:31:48 -070099}
100
101void HLoopOptimization::Run() {
Mingyao Yang01b47b02017-02-03 12:09:57 -0800102 // Skip if there is no loop or the graph has try-catch/irreducible loops.
Aart Bik281c6812016-08-26 11:31:48 -0700103 // TODO: make this less of a sledgehammer.
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800104 if (!graph_->HasLoops() || graph_->HasTryCatch() || graph_->HasIrreducibleLoops()) {
Aart Bik281c6812016-08-26 11:31:48 -0700105 return;
106 }
107
Aart Bik96202302016-10-04 17:33:56 -0700108 // Phase-local allocator that draws from the global pool. Since the allocator
109 // itself resides on the stack, it is destructed on exiting Run(), which
110 // implies its underlying memory is released immediately.
Aart Bikf8f5a162017-02-06 15:35:29 -0800111 ArenaAllocator allocator(global_allocator_->GetArenaPool());
Aart Bik96202302016-10-04 17:33:56 -0700112 loop_allocator_ = &allocator;
Nicolas Geoffrayebe16742016-10-05 09:55:42 +0100113
Aart Bik96202302016-10-04 17:33:56 -0700114 // Perform loop optimizations.
115 LocalRun();
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800116 if (top_loop_ == nullptr) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800117 graph_->SetHasLoops(false); // no more loops
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800118 }
119
Aart Bik96202302016-10-04 17:33:56 -0700120 // Detach.
121 loop_allocator_ = nullptr;
122 last_loop_ = top_loop_ = nullptr;
123}
124
125void HLoopOptimization::LocalRun() {
126 // Build the linear order using the phase-local allocator. This step enables building
127 // a loop hierarchy that properly reflects the outer-inner and previous-next relation.
128 ArenaVector<HBasicBlock*> linear_order(loop_allocator_->Adapter(kArenaAllocLinearOrder));
129 LinearizeGraph(graph_, loop_allocator_, &linear_order);
130
Aart Bik281c6812016-08-26 11:31:48 -0700131 // Build the loop hierarchy.
Aart Bik96202302016-10-04 17:33:56 -0700132 for (HBasicBlock* block : linear_order) {
Aart Bik281c6812016-08-26 11:31:48 -0700133 if (block->IsLoopHeader()) {
134 AddLoop(block->GetLoopInformation());
135 }
136 }
Aart Bik96202302016-10-04 17:33:56 -0700137
Aart Bik8c4a8542016-10-06 11:36:57 -0700138 // Traverse the loop hierarchy inner-to-outer and optimize. Traversal can use
Aart Bikf8f5a162017-02-06 15:35:29 -0800139 // temporary data structures using the phase-local allocator. All new HIR
140 // should use the global allocator.
Aart Bik8c4a8542016-10-06 11:36:57 -0700141 if (top_loop_ != nullptr) {
142 ArenaSet<HInstruction*> iset(loop_allocator_->Adapter(kArenaAllocLoopOptimization));
Aart Bikf8f5a162017-02-06 15:35:29 -0800143 ArenaSet<ArrayReference> refs(loop_allocator_->Adapter(kArenaAllocLoopOptimization));
144 ArenaSafeMap<HInstruction*, HInstruction*> map(
145 std::less<HInstruction*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
146 // Attach.
Aart Bik8c4a8542016-10-06 11:36:57 -0700147 iset_ = &iset;
Aart Bikf8f5a162017-02-06 15:35:29 -0800148 vector_refs_ = &refs;
149 vector_map_ = &map;
150 // Traverse.
Aart Bik8c4a8542016-10-06 11:36:57 -0700151 TraverseLoopsInnerToOuter(top_loop_);
Aart Bikf8f5a162017-02-06 15:35:29 -0800152 // Detach.
153 iset_ = nullptr;
154 vector_refs_ = nullptr;
155 vector_map_ = nullptr;
Aart Bik8c4a8542016-10-06 11:36:57 -0700156 }
Aart Bik281c6812016-08-26 11:31:48 -0700157}
158
159void HLoopOptimization::AddLoop(HLoopInformation* loop_info) {
160 DCHECK(loop_info != nullptr);
Aart Bikf8f5a162017-02-06 15:35:29 -0800161 LoopNode* node = new (loop_allocator_) LoopNode(loop_info);
Aart Bik281c6812016-08-26 11:31:48 -0700162 if (last_loop_ == nullptr) {
163 // First loop.
164 DCHECK(top_loop_ == nullptr);
165 last_loop_ = top_loop_ = node;
166 } else if (loop_info->IsIn(*last_loop_->loop_info)) {
167 // Inner loop.
168 node->outer = last_loop_;
169 DCHECK(last_loop_->inner == nullptr);
170 last_loop_ = last_loop_->inner = node;
171 } else {
172 // Subsequent loop.
173 while (last_loop_->outer != nullptr && !loop_info->IsIn(*last_loop_->outer->loop_info)) {
174 last_loop_ = last_loop_->outer;
175 }
176 node->outer = last_loop_->outer;
177 node->previous = last_loop_;
178 DCHECK(last_loop_->next == nullptr);
179 last_loop_ = last_loop_->next = node;
180 }
181}
182
183void HLoopOptimization::RemoveLoop(LoopNode* node) {
184 DCHECK(node != nullptr);
Aart Bik8c4a8542016-10-06 11:36:57 -0700185 DCHECK(node->inner == nullptr);
186 if (node->previous != nullptr) {
187 // Within sequence.
188 node->previous->next = node->next;
189 if (node->next != nullptr) {
190 node->next->previous = node->previous;
191 }
192 } else {
193 // First of sequence.
194 if (node->outer != nullptr) {
195 node->outer->inner = node->next;
196 } else {
197 top_loop_ = node->next;
198 }
199 if (node->next != nullptr) {
200 node->next->outer = node->outer;
201 node->next->previous = nullptr;
202 }
203 }
Aart Bik281c6812016-08-26 11:31:48 -0700204}
205
206void HLoopOptimization::TraverseLoopsInnerToOuter(LoopNode* node) {
207 for ( ; node != nullptr; node = node->next) {
Aart Bik6b69e0a2017-01-11 10:20:43 -0800208 // Visit inner loops first.
Aart Bikf8f5a162017-02-06 15:35:29 -0800209 uint32_t current_induction_simplification_count = induction_simplication_count_;
Aart Bik281c6812016-08-26 11:31:48 -0700210 if (node->inner != nullptr) {
211 TraverseLoopsInnerToOuter(node->inner);
212 }
Aart Bik6b69e0a2017-01-11 10:20:43 -0800213 // Recompute induction information of this loop if the induction
214 // of any inner loop has been simplified.
Aart Bik482095d2016-10-10 15:39:10 -0700215 if (current_induction_simplification_count != induction_simplication_count_) {
216 induction_range_.ReVisit(node->loop_info);
217 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800218 // Repeat simplifications in the loop-body until no more changes occur.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800219 // Note that since each simplification consists of eliminating code (without
220 // introducing new code), this process is always finite.
Aart Bikdf7822e2016-12-06 10:05:30 -0800221 do {
222 simplified_ = false;
Aart Bikdf7822e2016-12-06 10:05:30 -0800223 SimplifyInduction(node);
Aart Bik6b69e0a2017-01-11 10:20:43 -0800224 SimplifyBlocks(node);
Aart Bikdf7822e2016-12-06 10:05:30 -0800225 } while (simplified_);
Aart Bikf8f5a162017-02-06 15:35:29 -0800226 // Optimize inner loop.
Aart Bik9abf8942016-10-14 09:49:42 -0700227 if (node->inner == nullptr) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800228 OptimizeInnerLoop(node);
Aart Bik9abf8942016-10-14 09:49:42 -0700229 }
Aart Bik281c6812016-08-26 11:31:48 -0700230 }
231}
232
Aart Bikf8f5a162017-02-06 15:35:29 -0800233//
234// Optimization.
235//
236
Aart Bik281c6812016-08-26 11:31:48 -0700237void HLoopOptimization::SimplifyInduction(LoopNode* node) {
238 HBasicBlock* header = node->loop_info->GetHeader();
239 HBasicBlock* preheader = node->loop_info->GetPreHeader();
Aart Bik8c4a8542016-10-06 11:36:57 -0700240 // Scan the phis in the header to find opportunities to simplify an induction
241 // cycle that is only used outside the loop. Replace these uses, if any, with
242 // the last value and remove the induction cycle.
243 // Examples: for (int i = 0; x != null; i++) { .... no i .... }
244 // for (int i = 0; i < 10; i++, k++) { .... no k .... } return k;
Aart Bik281c6812016-08-26 11:31:48 -0700245 for (HInstructionIterator it(header->GetPhis()); !it.Done(); it.Advance()) {
246 HPhi* phi = it.Current()->AsPhi();
Aart Bikf8f5a162017-02-06 15:35:29 -0800247 iset_->clear(); // prepare phi induction
248 if (TrySetPhiInduction(phi, /*restrict_uses*/ true) &&
249 TryAssignLastValue(node->loop_info, phi, preheader, /*collect_loop_uses*/ false)) {
Aart Bik8c4a8542016-10-06 11:36:57 -0700250 for (HInstruction* i : *iset_) {
251 RemoveFromCycle(i);
Aart Bik281c6812016-08-26 11:31:48 -0700252 }
Aart Bikdf7822e2016-12-06 10:05:30 -0800253 simplified_ = true;
Aart Bik482095d2016-10-10 15:39:10 -0700254 }
255 }
256}
257
258void HLoopOptimization::SimplifyBlocks(LoopNode* node) {
Aart Bikdf7822e2016-12-06 10:05:30 -0800259 // Iterate over all basic blocks in the loop-body.
260 for (HBlocksInLoopIterator it(*node->loop_info); !it.Done(); it.Advance()) {
261 HBasicBlock* block = it.Current();
262 // Remove dead instructions from the loop-body.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800263 RemoveDeadInstructions(block->GetPhis());
264 RemoveDeadInstructions(block->GetInstructions());
Aart Bikdf7822e2016-12-06 10:05:30 -0800265 // Remove trivial control flow blocks from the loop-body.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800266 if (block->GetPredecessors().size() == 1 &&
267 block->GetSuccessors().size() == 1 &&
268 block->GetSingleSuccessor()->GetPredecessors().size() == 1) {
Aart Bikdf7822e2016-12-06 10:05:30 -0800269 simplified_ = true;
Aart Bik6b69e0a2017-01-11 10:20:43 -0800270 block->MergeWith(block->GetSingleSuccessor());
Aart Bikdf7822e2016-12-06 10:05:30 -0800271 } else if (block->GetSuccessors().size() == 2) {
272 // Trivial if block can be bypassed to either branch.
273 HBasicBlock* succ0 = block->GetSuccessors()[0];
274 HBasicBlock* succ1 = block->GetSuccessors()[1];
275 HBasicBlock* meet0 = nullptr;
276 HBasicBlock* meet1 = nullptr;
277 if (succ0 != succ1 &&
278 IsGotoBlock(succ0, &meet0) &&
279 IsGotoBlock(succ1, &meet1) &&
280 meet0 == meet1 && // meets again
281 meet0 != block && // no self-loop
282 meet0->GetPhis().IsEmpty()) { // not used for merging
283 simplified_ = true;
284 succ0->DisconnectAndDelete();
285 if (block->Dominates(meet0)) {
286 block->RemoveDominatedBlock(meet0);
287 succ1->AddDominatedBlock(meet0);
288 meet0->SetDominator(succ1);
Aart Bike3dedc52016-11-02 17:50:27 -0700289 }
Aart Bik482095d2016-10-10 15:39:10 -0700290 }
Aart Bik281c6812016-08-26 11:31:48 -0700291 }
Aart Bikdf7822e2016-12-06 10:05:30 -0800292 }
Aart Bik281c6812016-08-26 11:31:48 -0700293}
294
Aart Bikf8f5a162017-02-06 15:35:29 -0800295void HLoopOptimization::OptimizeInnerLoop(LoopNode* node) {
Aart Bik281c6812016-08-26 11:31:48 -0700296 HBasicBlock* header = node->loop_info->GetHeader();
297 HBasicBlock* preheader = node->loop_info->GetPreHeader();
Aart Bik9abf8942016-10-14 09:49:42 -0700298 // Ensure loop header logic is finite.
Aart Bikf8f5a162017-02-06 15:35:29 -0800299 int64_t trip_count = 0;
300 if (!induction_range_.IsFinite(node->loop_info, &trip_count)) {
301 return;
Aart Bik9abf8942016-10-14 09:49:42 -0700302 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800303
Aart Bik281c6812016-08-26 11:31:48 -0700304 // Ensure there is only a single loop-body (besides the header).
305 HBasicBlock* body = nullptr;
306 for (HBlocksInLoopIterator it(*node->loop_info); !it.Done(); it.Advance()) {
307 if (it.Current() != header) {
308 if (body != nullptr) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800309 return;
Aart Bik281c6812016-08-26 11:31:48 -0700310 }
311 body = it.Current();
312 }
313 }
314 // Ensure there is only a single exit point.
315 if (header->GetSuccessors().size() != 2) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800316 return;
Aart Bik281c6812016-08-26 11:31:48 -0700317 }
318 HBasicBlock* exit = (header->GetSuccessors()[0] == body)
319 ? header->GetSuccessors()[1]
320 : header->GetSuccessors()[0];
Aart Bik8c4a8542016-10-06 11:36:57 -0700321 // Ensure exit can only be reached by exiting loop.
Aart Bik281c6812016-08-26 11:31:48 -0700322 if (exit->GetPredecessors().size() != 1) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800323 return;
Aart Bik281c6812016-08-26 11:31:48 -0700324 }
Aart Bik6b69e0a2017-01-11 10:20:43 -0800325 // Detect either an empty loop (no side effects other than plain iteration) or
326 // a trivial loop (just iterating once). Replace subsequent index uses, if any,
327 // with the last value and remove the loop, possibly after unrolling its body.
328 HInstruction* phi = header->GetFirstPhi();
Aart Bikf8f5a162017-02-06 15:35:29 -0800329 iset_->clear(); // prepare phi induction
330 if (TrySetSimpleLoopHeader(header)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -0800331 bool is_empty = IsEmptyBody(body);
Aart Bikf8f5a162017-02-06 15:35:29 -0800332 if ((is_empty || trip_count == 1) &&
333 TryAssignLastValue(node->loop_info, phi, preheader, /*collect_loop_uses*/ true)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -0800334 if (!is_empty) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800335 // Unroll the loop-body, which sees initial value of the index.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800336 phi->ReplaceWith(phi->InputAt(0));
337 preheader->MergeInstructionsWith(body);
338 }
339 body->DisconnectAndDelete();
340 exit->RemovePredecessor(header);
341 header->RemoveSuccessor(exit);
342 header->RemoveDominatedBlock(exit);
343 header->DisconnectAndDelete();
344 preheader->AddSuccessor(exit);
Aart Bikf8f5a162017-02-06 15:35:29 -0800345 preheader->AddInstruction(new (global_allocator_) HGoto());
Aart Bik6b69e0a2017-01-11 10:20:43 -0800346 preheader->AddDominatedBlock(exit);
347 exit->SetDominator(preheader);
348 RemoveLoop(node); // update hierarchy
Aart Bikf8f5a162017-02-06 15:35:29 -0800349 return;
350 }
351 }
352
353 // Vectorize loop, if possible and valid.
354 if (kEnableVectorization) {
355 iset_->clear(); // prepare phi induction
356 if (TrySetSimpleLoopHeader(header) &&
357 CanVectorize(node, body, trip_count) &&
358 TryAssignLastValue(node->loop_info, phi, preheader, /*collect_loop_uses*/ true)) {
359 Vectorize(node, body, exit, trip_count);
360 graph_->SetHasSIMD(true); // flag SIMD usage
361 return;
362 }
363 }
364}
365
366//
367// Loop vectorization. The implementation is based on the book by Aart J.C. Bik:
368// "The Software Vectorization Handbook. Applying Multimedia Extensions for Maximum Performance."
369// Intel Press, June, 2004 (http://www.aartbik.com/).
370//
371
372bool HLoopOptimization::CanVectorize(LoopNode* node, HBasicBlock* block, int64_t trip_count) {
373 // Reset vector bookkeeping.
374 vector_length_ = 0;
375 vector_refs_->clear();
376 vector_runtime_test_a_ =
377 vector_runtime_test_b_= nullptr;
378
379 // Phis in the loop-body prevent vectorization.
380 if (!block->GetPhis().IsEmpty()) {
381 return false;
382 }
383
384 // Scan the loop-body, starting a right-hand-side tree traversal at each left-hand-side
385 // occurrence, which allows passing down attributes down the use tree.
386 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
387 if (!VectorizeDef(node, it.Current(), /*generate_code*/ false)) {
388 return false; // failure to vectorize a left-hand-side
389 }
390 }
391
392 // Heuristics. Does vectorization seem profitable?
393 // TODO: refine
394 if (vector_length_ == 0) {
395 return false; // nothing found
396 } else if (0 < trip_count && trip_count < vector_length_) {
397 return false; // insufficient iterations
398 }
399
400 // Data dependence analysis. Find each pair of references with same type, where
401 // at least one is a write. Each such pair denotes a possible data dependence.
402 // This analysis exploits the property that differently typed arrays cannot be
403 // aliased, as well as the property that references either point to the same
404 // array or to two completely disjoint arrays, i.e., no partial aliasing.
405 // Other than a few simply heuristics, no detailed subscript analysis is done.
406 for (auto i = vector_refs_->begin(); i != vector_refs_->end(); ++i) {
407 for (auto j = i; ++j != vector_refs_->end(); ) {
408 if (i->type == j->type && (i->lhs || j->lhs)) {
409 // Found same-typed a[i+x] vs. b[i+y], where at least one is a write.
410 HInstruction* a = i->base;
411 HInstruction* b = j->base;
412 HInstruction* x = i->offset;
413 HInstruction* y = j->offset;
414 if (a == b) {
415 // Found a[i+x] vs. a[i+y]. Accept if x == y (loop-independent data dependence).
416 // Conservatively assume a loop-carried data dependence otherwise, and reject.
417 if (x != y) {
418 return false;
419 }
420 } else {
421 // Found a[i+x] vs. b[i+y]. Accept if x == y (at worst loop-independent data dependence).
422 // Conservatively assume a potential loop-carried data dependence otherwise, avoided by
423 // generating an explicit a != b disambiguation runtime test on the two references.
424 if (x != y) {
425 // For now, we reject after one test to avoid excessive overhead.
426 if (vector_runtime_test_a_ != nullptr) {
427 return false;
428 }
429 vector_runtime_test_a_ = a;
430 vector_runtime_test_b_ = b;
431 }
432 }
433 }
434 }
435 }
436
437 // Success!
438 return true;
439}
440
441void HLoopOptimization::Vectorize(LoopNode* node,
442 HBasicBlock* block,
443 HBasicBlock* exit,
444 int64_t trip_count) {
445 Primitive::Type induc_type = Primitive::kPrimInt;
446 HBasicBlock* header = node->loop_info->GetHeader();
447 HBasicBlock* preheader = node->loop_info->GetPreHeader();
448
449 // A cleanup is needed for any unknown trip count or for a known trip count
450 // with remainder iterations after vectorization.
451 bool needs_cleanup = trip_count == 0 || (trip_count % vector_length_) != 0;
452
453 // Adjust vector bookkeeping.
454 iset_->clear(); // prepare phi induction
455 bool is_simple_loop_header = TrySetSimpleLoopHeader(header); // fills iset_
456 DCHECK(is_simple_loop_header);
457
458 // Generate preheader:
459 // stc = <trip-count>;
460 // vtc = stc - stc % VL;
461 HInstruction* stc = induction_range_.GenerateTripCount(node->loop_info, graph_, preheader);
462 HInstruction* vtc = stc;
463 if (needs_cleanup) {
464 DCHECK(IsPowerOfTwo(vector_length_));
465 HInstruction* rem = Insert(
466 preheader, new (global_allocator_) HAnd(induc_type,
467 stc,
468 graph_->GetIntConstant(vector_length_ - 1)));
469 vtc = Insert(preheader, new (global_allocator_) HSub(induc_type, stc, rem));
470 }
471
472 // Generate runtime disambiguation test:
473 // vtc = a != b ? vtc : 0;
474 if (vector_runtime_test_a_ != nullptr) {
475 HInstruction* rt = Insert(
476 preheader,
477 new (global_allocator_) HNotEqual(vector_runtime_test_a_, vector_runtime_test_b_));
478 vtc = Insert(preheader,
479 new (global_allocator_) HSelect(rt, vtc, graph_->GetIntConstant(0), kNoDexPc));
480 needs_cleanup = true;
481 }
482
483 // Generate vector loop:
484 // for (i = 0; i < vtc; i += VL)
485 // <vectorized-loop-body>
486 vector_mode_ = kVector;
487 GenerateNewLoop(node,
488 block,
489 graph_->TransformLoopForVectorization(header, block, exit),
490 graph_->GetIntConstant(0),
491 vtc,
492 graph_->GetIntConstant(vector_length_));
493 HLoopInformation* vloop = vector_header_->GetLoopInformation();
494
495 // Generate cleanup loop, if needed:
496 // for ( ; i < stc; i += 1)
497 // <loop-body>
498 if (needs_cleanup) {
499 vector_mode_ = kSequential;
500 GenerateNewLoop(node,
501 block,
502 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
503 vector_phi_,
504 stc,
505 graph_->GetIntConstant(1));
506 }
507
508 // Remove the original loop by disconnecting the body block
509 // and removing all instructions from the header.
510 block->DisconnectAndDelete();
511 while (!header->GetFirstInstruction()->IsGoto()) {
512 header->RemoveInstruction(header->GetFirstInstruction());
513 }
514 // Update loop hierarchy: the old header now resides in the
515 // same outer loop as the old preheader.
516 header->SetLoopInformation(preheader->GetLoopInformation()); // outward
517 node->loop_info = vloop;
518}
519
520void HLoopOptimization::GenerateNewLoop(LoopNode* node,
521 HBasicBlock* block,
522 HBasicBlock* new_preheader,
523 HInstruction* lo,
524 HInstruction* hi,
525 HInstruction* step) {
526 Primitive::Type induc_type = Primitive::kPrimInt;
527 // Prepare new loop.
528 vector_map_->clear();
529 vector_preheader_ = new_preheader,
530 vector_header_ = vector_preheader_->GetSingleSuccessor();
531 vector_body_ = vector_header_->GetSuccessors()[1];
532 vector_phi_ = new (global_allocator_) HPhi(global_allocator_,
533 kNoRegNumber,
534 0,
535 HPhi::ToPhiType(induc_type));
536 // Generate header.
537 // for (i = lo; i < hi; i += step)
538 // <loop-body>
539 HInstruction* cond = new (global_allocator_) HAboveOrEqual(vector_phi_, hi);
540 vector_header_->AddPhi(vector_phi_);
541 vector_header_->AddInstruction(cond);
542 vector_header_->AddInstruction(new (global_allocator_) HIf(cond));
543 // Suspend check and environment.
544 HInstruction* suspend = vector_header_->GetFirstInstruction();
545 suspend->CopyEnvironmentFromWithLoopPhiAdjustment(
546 node->loop_info->GetSuspendCheck()->GetEnvironment(), vector_header_);
547 // Generate body.
548 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
549 bool vectorized_def = VectorizeDef(node, it.Current(), /*generate_code*/ true);
550 DCHECK(vectorized_def);
551 }
552 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
553 auto i = vector_map_->find(it.Current());
554 if (i != vector_map_->end() && !i->second->IsInBlock()) {
555 Insert(vector_body_, i->second); // lays out in original order
556 if (i->second->NeedsEnvironment()) {
557 i->second->CopyEnvironmentFromWithLoopPhiAdjustment(
558 suspend->GetEnvironment(), vector_header_);
559 }
560 }
561 }
562 // Finalize increment and phi.
563 HInstruction* inc = new (global_allocator_) HAdd(induc_type, vector_phi_, step);
564 vector_phi_->AddInput(lo);
565 vector_phi_->AddInput(Insert(vector_body_, inc));
566}
567
568// TODO: accept reductions at left-hand-side, mixed-type store idioms, etc.
569bool HLoopOptimization::VectorizeDef(LoopNode* node,
570 HInstruction* instruction,
571 bool generate_code) {
572 // Accept a left-hand-side array base[index] for
573 // (1) supported vector type,
574 // (2) loop-invariant base,
575 // (3) unit stride index,
576 // (4) vectorizable right-hand-side value.
577 uint64_t restrictions = kNone;
578 if (instruction->IsArraySet()) {
579 Primitive::Type type = instruction->AsArraySet()->GetComponentType();
580 HInstruction* base = instruction->InputAt(0);
581 HInstruction* index = instruction->InputAt(1);
582 HInstruction* value = instruction->InputAt(2);
583 HInstruction* offset = nullptr;
584 if (TrySetVectorType(type, &restrictions) &&
585 node->loop_info->IsDefinedOutOfTheLoop(base) &&
586 induction_range_.IsUnitStride(index, &offset) &&
587 VectorizeUse(node, value, generate_code, type, restrictions)) {
588 if (generate_code) {
589 GenerateVecSub(index, offset);
590 GenerateVecMem(instruction, vector_map_->Get(index), vector_map_->Get(value), type);
591 } else {
592 vector_refs_->insert(ArrayReference(base, offset, type, /*lhs*/ true));
593 }
Aart Bik6b69e0a2017-01-11 10:20:43 -0800594 return true;
595 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800596 return false;
597 }
598 // Branch back okay.
599 if (instruction->IsGoto()) {
600 return true;
601 }
602 // Otherwise accept only expressions with no effects outside the immediate loop-body.
603 // Note that actual uses are inspected during right-hand-side tree traversal.
604 return !IsUsedOutsideLoop(node->loop_info, instruction) && !instruction->DoesAnyWrite();
605}
606
607// TODO: more operations and intrinsics, detect saturation arithmetic, etc.
608bool HLoopOptimization::VectorizeUse(LoopNode* node,
609 HInstruction* instruction,
610 bool generate_code,
611 Primitive::Type type,
612 uint64_t restrictions) {
613 // Accept anything for which code has already been generated.
614 if (generate_code) {
615 if (vector_map_->find(instruction) != vector_map_->end()) {
616 return true;
617 }
618 }
619 // Continue the right-hand-side tree traversal, passing in proper
620 // types and vector restrictions along the way. During code generation,
621 // all new nodes are drawn from the global allocator.
622 if (node->loop_info->IsDefinedOutOfTheLoop(instruction)) {
623 // Accept invariant use, using scalar expansion.
624 if (generate_code) {
625 GenerateVecInv(instruction, type);
626 }
627 return true;
628 } else if (instruction->IsArrayGet()) {
629 // Accept a right-hand-side array base[index] for
630 // (1) exact matching vector type,
631 // (2) loop-invariant base,
632 // (3) unit stride index,
633 // (4) vectorizable right-hand-side value.
634 HInstruction* base = instruction->InputAt(0);
635 HInstruction* index = instruction->InputAt(1);
636 HInstruction* offset = nullptr;
637 if (type == instruction->GetType() &&
638 node->loop_info->IsDefinedOutOfTheLoop(base) &&
639 induction_range_.IsUnitStride(index, &offset)) {
640 if (generate_code) {
641 GenerateVecSub(index, offset);
642 GenerateVecMem(instruction, vector_map_->Get(index), nullptr, type);
643 } else {
644 vector_refs_->insert(ArrayReference(base, offset, type, /*lhs*/ false));
645 }
646 return true;
647 }
648 } else if (instruction->IsTypeConversion()) {
649 // Accept particular type conversions.
650 HTypeConversion* conversion = instruction->AsTypeConversion();
651 HInstruction* opa = conversion->InputAt(0);
652 Primitive::Type from = conversion->GetInputType();
653 Primitive::Type to = conversion->GetResultType();
654 if ((to == Primitive::kPrimByte ||
655 to == Primitive::kPrimChar ||
656 to == Primitive::kPrimShort) && from == Primitive::kPrimInt) {
657 // Accept a "narrowing" type conversion from a "wider" computation for
658 // (1) conversion into final required type,
659 // (2) vectorizable operand,
660 // (3) "wider" operations cannot bring in higher order bits.
661 if (to == type && VectorizeUse(node, opa, generate_code, type, restrictions | kNoHiBits)) {
662 if (generate_code) {
663 if (vector_mode_ == kVector) {
664 vector_map_->Put(instruction, vector_map_->Get(opa)); // operand pass-through
665 } else {
666 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
667 }
668 }
669 return true;
670 }
671 } else if (to == Primitive::kPrimFloat && from == Primitive::kPrimInt) {
672 DCHECK_EQ(to, type);
673 // Accept int to float conversion for
674 // (1) supported int,
675 // (2) vectorizable operand.
676 if (TrySetVectorType(from, &restrictions) &&
677 VectorizeUse(node, opa, generate_code, from, restrictions)) {
678 if (generate_code) {
679 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
680 }
681 return true;
682 }
683 }
684 return false;
685 } else if (instruction->IsNeg() || instruction->IsNot() || instruction->IsBooleanNot()) {
686 // Accept unary operator for vectorizable operand.
687 HInstruction* opa = instruction->InputAt(0);
688 if (VectorizeUse(node, opa, generate_code, type, restrictions)) {
689 if (generate_code) {
690 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
691 }
692 return true;
693 }
694 } else if (instruction->IsAdd() || instruction->IsSub() ||
695 instruction->IsMul() || instruction->IsDiv() ||
696 instruction->IsAnd() || instruction->IsOr() || instruction->IsXor()) {
697 // Deal with vector restrictions.
698 if ((instruction->IsMul() && HasVectorRestrictions(restrictions, kNoMul)) ||
699 (instruction->IsDiv() && HasVectorRestrictions(restrictions, kNoDiv))) {
700 return false;
701 }
702 // Accept binary operator for vectorizable operands.
703 HInstruction* opa = instruction->InputAt(0);
704 HInstruction* opb = instruction->InputAt(1);
705 if (VectorizeUse(node, opa, generate_code, type, restrictions) &&
706 VectorizeUse(node, opb, generate_code, type, restrictions)) {
707 if (generate_code) {
708 GenerateVecOp(instruction, vector_map_->Get(opa), vector_map_->Get(opb), type);
709 }
710 return true;
711 }
712 } else if (instruction->IsShl() || instruction->IsShr() || instruction->IsUShr()) {
713 // Deal with vector restrictions.
714 if ((HasVectorRestrictions(restrictions, kNoShift)) ||
715 (instruction->IsShr() && HasVectorRestrictions(restrictions, kNoShr))) {
716 return false; // unsupported instruction
717 } else if ((instruction->IsShr() || instruction->IsUShr()) &&
718 HasVectorRestrictions(restrictions, kNoHiBits)) {
719 return false; // hibits may impact lobits; TODO: we can do better!
720 }
721 // Accept shift operator for vectorizable/invariant operands.
722 // TODO: accept symbolic, albeit loop invariant shift factors.
723 HInstruction* opa = instruction->InputAt(0);
724 HInstruction* opb = instruction->InputAt(1);
725 if (VectorizeUse(node, opa, generate_code, type, restrictions) && opb->IsIntConstant()) {
726 if (generate_code) {
727 // Make sure shift factor only looks at lower bits, as defined for sequential shifts.
728 // Note that even the narrower SIMD shifts do the right thing after that.
729 int32_t mask = (instruction->GetType() == Primitive::kPrimLong)
730 ? kMaxLongShiftDistance
731 : kMaxIntShiftDistance;
732 HInstruction* s = graph_->GetIntConstant(opb->AsIntConstant()->GetValue() & mask);
733 GenerateVecOp(instruction, vector_map_->Get(opa), s, type);
734 }
735 return true;
736 }
737 } else if (instruction->IsInvokeStaticOrDirect()) {
738 // TODO: coming soon.
739 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700740 }
Aart Bik6b69e0a2017-01-11 10:20:43 -0800741 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700742}
743
Aart Bikf8f5a162017-02-06 15:35:29 -0800744bool HLoopOptimization::TrySetVectorType(Primitive::Type type, uint64_t* restrictions) {
745 const InstructionSetFeatures* features = compiler_driver_->GetInstructionSetFeatures();
746 switch (compiler_driver_->GetInstructionSet()) {
747 case kArm:
748 case kThumb2:
749 return false;
750 case kArm64:
751 // Allow vectorization for all ARM devices, because Android assumes that
752 // ARMv8 AArch64 always supports advanced SIMD. For now, only D registers
753 // (64-bit vectors) not Q registers (128-bit vectors).
754 switch (type) {
755 case Primitive::kPrimBoolean:
756 case Primitive::kPrimByte:
757 *restrictions |= kNoDiv;
758 return TrySetVectorLength(8);
759 case Primitive::kPrimChar:
760 case Primitive::kPrimShort:
761 *restrictions |= kNoDiv;
762 return TrySetVectorLength(4);
763 case Primitive::kPrimInt:
764 *restrictions |= kNoDiv;
765 return TrySetVectorLength(2);
766 case Primitive::kPrimFloat:
767 return TrySetVectorLength(2);
768 default:
769 return false;
770 }
771 case kX86:
772 case kX86_64:
773 // Allow vectorization for SSE4-enabled X86 devices only (128-bit vectors).
774 if (features->AsX86InstructionSetFeatures()->HasSSE4_1()) {
775 switch (type) {
776 case Primitive::kPrimBoolean:
777 case Primitive::kPrimByte:
778 *restrictions |= kNoMul | kNoDiv | kNoShift;
779 return TrySetVectorLength(16);
780 case Primitive::kPrimChar:
781 case Primitive::kPrimShort:
782 *restrictions |= kNoDiv;
783 return TrySetVectorLength(8);
784 case Primitive::kPrimInt:
785 *restrictions |= kNoDiv;
786 return TrySetVectorLength(4);
787 case Primitive::kPrimLong:
788 *restrictions |= kNoMul | kNoDiv | kNoShr;
789 return TrySetVectorLength(2);
790 case Primitive::kPrimFloat:
791 return TrySetVectorLength(4);
792 case Primitive::kPrimDouble:
793 return TrySetVectorLength(2);
794 default:
795 break;
796 } // switch type
797 }
798 return false;
799 case kMips:
800 case kMips64:
801 // TODO: implement MIPS SIMD.
802 return false;
803 default:
804 return false;
805 } // switch instruction set
806}
807
808bool HLoopOptimization::TrySetVectorLength(uint32_t length) {
809 DCHECK(IsPowerOfTwo(length) && length >= 2u);
810 // First time set?
811 if (vector_length_ == 0) {
812 vector_length_ = length;
813 }
814 // Different types are acceptable within a loop-body, as long as all the corresponding vector
815 // lengths match exactly to obtain a uniform traversal through the vector iteration space
816 // (idiomatic exceptions to this rule can be handled by further unrolling sub-expressions).
817 return vector_length_ == length;
818}
819
820void HLoopOptimization::GenerateVecInv(HInstruction* org, Primitive::Type type) {
821 if (vector_map_->find(org) == vector_map_->end()) {
822 // In scalar code, just use a self pass-through for scalar invariants
823 // (viz. expression remains itself).
824 if (vector_mode_ == kSequential) {
825 vector_map_->Put(org, org);
826 return;
827 }
828 // In vector code, explicit scalar expansion is needed.
829 HInstruction* vector = new (global_allocator_) HVecReplicateScalar(
830 global_allocator_, org, type, vector_length_);
831 vector_map_->Put(org, Insert(vector_preheader_, vector));
832 }
833}
834
835void HLoopOptimization::GenerateVecSub(HInstruction* org, HInstruction* offset) {
836 if (vector_map_->find(org) == vector_map_->end()) {
837 HInstruction* subscript = vector_phi_;
838 if (offset != nullptr) {
839 subscript = new (global_allocator_) HAdd(Primitive::kPrimInt, subscript, offset);
840 if (org->IsPhi()) {
841 Insert(vector_body_, subscript); // lacks layout placeholder
842 }
843 }
844 vector_map_->Put(org, subscript);
845 }
846}
847
848void HLoopOptimization::GenerateVecMem(HInstruction* org,
849 HInstruction* opa,
850 HInstruction* opb,
851 Primitive::Type type) {
852 HInstruction* vector = nullptr;
853 if (vector_mode_ == kVector) {
854 // Vector store or load.
855 if (opb != nullptr) {
856 vector = new (global_allocator_) HVecStore(
857 global_allocator_, org->InputAt(0), opa, opb, type, vector_length_);
858 } else {
859 vector = new (global_allocator_) HVecLoad(
860 global_allocator_, org->InputAt(0), opa, type, vector_length_);
861 }
862 } else {
863 // Scalar store or load.
864 DCHECK(vector_mode_ == kSequential);
865 if (opb != nullptr) {
866 vector = new (global_allocator_) HArraySet(org->InputAt(0), opa, opb, type, kNoDexPc);
867 } else {
868 vector = new (global_allocator_) HArrayGet(org->InputAt(0), opa, type, kNoDexPc);
869 }
870 }
871 vector_map_->Put(org, vector);
872}
873
874#define GENERATE_VEC(x, y) \
875 if (vector_mode_ == kVector) { \
876 vector = (x); \
877 } else { \
878 DCHECK(vector_mode_ == kSequential); \
879 vector = (y); \
880 } \
881 break;
882
883void HLoopOptimization::GenerateVecOp(HInstruction* org,
884 HInstruction* opa,
885 HInstruction* opb,
886 Primitive::Type type) {
887 if (vector_mode_ == kSequential) {
888 // Scalar code follows implicit integral promotion.
889 if (type == Primitive::kPrimBoolean ||
890 type == Primitive::kPrimByte ||
891 type == Primitive::kPrimChar ||
892 type == Primitive::kPrimShort) {
893 type = Primitive::kPrimInt;
894 }
895 }
896 HInstruction* vector = nullptr;
897 switch (org->GetKind()) {
898 case HInstruction::kNeg:
899 DCHECK(opb == nullptr);
900 GENERATE_VEC(
901 new (global_allocator_) HVecNeg(global_allocator_, opa, type, vector_length_),
902 new (global_allocator_) HNeg(type, opa));
903 case HInstruction::kNot:
904 DCHECK(opb == nullptr);
905 GENERATE_VEC(
906 new (global_allocator_) HVecNot(global_allocator_, opa, type, vector_length_),
907 new (global_allocator_) HNot(type, opa));
908 case HInstruction::kBooleanNot:
909 DCHECK(opb == nullptr);
910 GENERATE_VEC(
911 new (global_allocator_) HVecNot(global_allocator_, opa, type, vector_length_),
912 new (global_allocator_) HBooleanNot(opa));
913 case HInstruction::kTypeConversion:
914 DCHECK(opb == nullptr);
915 GENERATE_VEC(
916 new (global_allocator_) HVecCnv(global_allocator_, opa, type, vector_length_),
917 new (global_allocator_) HTypeConversion(type, opa, kNoDexPc));
918 case HInstruction::kAdd:
919 GENERATE_VEC(
920 new (global_allocator_) HVecAdd(global_allocator_, opa, opb, type, vector_length_),
921 new (global_allocator_) HAdd(type, opa, opb));
922 case HInstruction::kSub:
923 GENERATE_VEC(
924 new (global_allocator_) HVecSub(global_allocator_, opa, opb, type, vector_length_),
925 new (global_allocator_) HSub(type, opa, opb));
926 case HInstruction::kMul:
927 GENERATE_VEC(
928 new (global_allocator_) HVecMul(global_allocator_, opa, opb, type, vector_length_),
929 new (global_allocator_) HMul(type, opa, opb));
930 case HInstruction::kDiv:
931 GENERATE_VEC(
932 new (global_allocator_) HVecDiv(global_allocator_, opa, opb, type, vector_length_),
933 new (global_allocator_) HDiv(type, opa, opb, kNoDexPc));
934 case HInstruction::kAnd:
935 GENERATE_VEC(
936 new (global_allocator_) HVecAnd(global_allocator_, opa, opb, type, vector_length_),
937 new (global_allocator_) HAnd(type, opa, opb));
938 case HInstruction::kOr:
939 GENERATE_VEC(
940 new (global_allocator_) HVecOr(global_allocator_, opa, opb, type, vector_length_),
941 new (global_allocator_) HOr(type, opa, opb));
942 case HInstruction::kXor:
943 GENERATE_VEC(
944 new (global_allocator_) HVecXor(global_allocator_, opa, opb, type, vector_length_),
945 new (global_allocator_) HXor(type, opa, opb));
946 case HInstruction::kShl:
947 GENERATE_VEC(
948 new (global_allocator_) HVecShl(global_allocator_, opa, opb, type, vector_length_),
949 new (global_allocator_) HShl(type, opa, opb));
950 case HInstruction::kShr:
951 GENERATE_VEC(
952 new (global_allocator_) HVecShr(global_allocator_, opa, opb, type, vector_length_),
953 new (global_allocator_) HShr(type, opa, opb));
954 case HInstruction::kUShr:
955 GENERATE_VEC(
956 new (global_allocator_) HVecUShr(global_allocator_, opa, opb, type, vector_length_),
957 new (global_allocator_) HUShr(type, opa, opb));
958 case HInstruction::kInvokeStaticOrDirect: {
959 // TODO: coming soon.
960 break;
961 }
962 default:
963 break;
964 } // switch
965 CHECK(vector != nullptr) << "Unsupported SIMD operator";
966 vector_map_->Put(org, vector);
967}
968
969#undef GENERATE_VEC
970
971//
972// Helpers.
973//
974
975bool HLoopOptimization::TrySetPhiInduction(HPhi* phi, bool restrict_uses) {
976 DCHECK(iset_->empty());
Aart Bikcc42be02016-10-20 16:14:16 -0700977 ArenaSet<HInstruction*>* set = induction_range_.LookupCycle(phi);
978 if (set != nullptr) {
979 for (HInstruction* i : *set) {
Aart Bike3dedc52016-11-02 17:50:27 -0700980 // Check that, other than instructions that are no longer in the graph (removed earlier)
Aart Bikf8f5a162017-02-06 15:35:29 -0800981 // each instruction is removable and, when restrict uses are requested, other than for phi,
982 // all uses are contained within the cycle.
Aart Bike3dedc52016-11-02 17:50:27 -0700983 if (!i->IsInBlock()) {
984 continue;
985 } else if (!i->IsRemovable()) {
986 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -0800987 } else if (i != phi && restrict_uses) {
Aart Bikcc42be02016-10-20 16:14:16 -0700988 for (const HUseListNode<HInstruction*>& use : i->GetUses()) {
989 if (set->find(use.GetUser()) == set->end()) {
990 return false;
991 }
992 }
993 }
Aart Bike3dedc52016-11-02 17:50:27 -0700994 iset_->insert(i); // copy
Aart Bikcc42be02016-10-20 16:14:16 -0700995 }
Aart Bikcc42be02016-10-20 16:14:16 -0700996 return true;
997 }
998 return false;
999}
1000
1001// Find: phi: Phi(init, addsub)
1002// s: SuspendCheck
1003// c: Condition(phi, bound)
1004// i: If(c)
1005// TODO: Find a less pattern matching approach?
Aart Bikf8f5a162017-02-06 15:35:29 -08001006bool HLoopOptimization::TrySetSimpleLoopHeader(HBasicBlock* block) {
Aart Bikcc42be02016-10-20 16:14:16 -07001007 DCHECK(iset_->empty());
1008 HInstruction* phi = block->GetFirstPhi();
Aart Bikf8f5a162017-02-06 15:35:29 -08001009 if (phi != nullptr &&
1010 phi->GetNext() == nullptr &&
1011 TrySetPhiInduction(phi->AsPhi(), /*restrict_uses*/ false)) {
Aart Bikcc42be02016-10-20 16:14:16 -07001012 HInstruction* s = block->GetFirstInstruction();
1013 if (s != nullptr && s->IsSuspendCheck()) {
1014 HInstruction* c = s->GetNext();
1015 if (c != nullptr && c->IsCondition() && c->GetUses().HasExactlyOneElement()) {
1016 HInstruction* i = c->GetNext();
1017 if (i != nullptr && i->IsIf() && i->InputAt(0) == c) {
1018 iset_->insert(c);
1019 iset_->insert(s);
1020 return true;
1021 }
1022 }
1023 }
1024 }
1025 return false;
1026}
1027
1028bool HLoopOptimization::IsEmptyBody(HBasicBlock* block) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001029 if (!block->GetPhis().IsEmpty()) {
1030 return false;
1031 }
1032 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
1033 HInstruction* instruction = it.Current();
1034 if (!instruction->IsGoto() && iset_->find(instruction) == iset_->end()) {
1035 return false;
Aart Bikcc42be02016-10-20 16:14:16 -07001036 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001037 }
1038 return true;
1039}
1040
1041bool HLoopOptimization::IsUsedOutsideLoop(HLoopInformation* loop_info,
1042 HInstruction* instruction) {
1043 for (const HUseListNode<HInstruction*>& use : instruction->GetUses()) {
1044 if (use.GetUser()->GetBlock()->GetLoopInformation() != loop_info) {
1045 return true;
1046 }
Aart Bikcc42be02016-10-20 16:14:16 -07001047 }
1048 return false;
1049}
1050
Aart Bik482095d2016-10-10 15:39:10 -07001051bool HLoopOptimization::IsOnlyUsedAfterLoop(HLoopInformation* loop_info,
Aart Bik8c4a8542016-10-06 11:36:57 -07001052 HInstruction* instruction,
Aart Bik6b69e0a2017-01-11 10:20:43 -08001053 bool collect_loop_uses,
Aart Bik8c4a8542016-10-06 11:36:57 -07001054 /*out*/ int32_t* use_count) {
1055 for (const HUseListNode<HInstruction*>& use : instruction->GetUses()) {
1056 HInstruction* user = use.GetUser();
1057 if (iset_->find(user) == iset_->end()) { // not excluded?
1058 HLoopInformation* other_loop_info = user->GetBlock()->GetLoopInformation();
Aart Bik482095d2016-10-10 15:39:10 -07001059 if (other_loop_info != nullptr && other_loop_info->IsIn(*loop_info)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -08001060 // If collect_loop_uses is set, simply keep adding those uses to the set.
1061 // Otherwise, reject uses inside the loop that were not already in the set.
1062 if (collect_loop_uses) {
1063 iset_->insert(user);
1064 continue;
1065 }
Aart Bik8c4a8542016-10-06 11:36:57 -07001066 return false;
1067 }
1068 ++*use_count;
1069 }
1070 }
1071 return true;
1072}
1073
Aart Bik807868e2016-11-03 17:51:43 -07001074bool HLoopOptimization::TryReplaceWithLastValue(HInstruction* instruction, HBasicBlock* block) {
1075 // Try to replace outside uses with the last value. Environment uses can consume this
1076 // value too, since any first true use is outside the loop (although this may imply
1077 // that de-opting may look "ahead" a bit on the phi value). If there are only environment
1078 // uses, the value is dropped altogether, since the computations have no effect.
1079 if (induction_range_.CanGenerateLastValue(instruction)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -08001080 HInstruction* replacement = induction_range_.GenerateLastValue(instruction, graph_, block);
1081 const HUseList<HInstruction*>& uses = instruction->GetUses();
1082 for (auto it = uses.begin(), end = uses.end(); it != end;) {
1083 HInstruction* user = it->GetUser();
1084 size_t index = it->GetIndex();
1085 ++it; // increment before replacing
1086 if (iset_->find(user) == iset_->end()) { // not excluded?
1087 user->ReplaceInput(replacement, index);
1088 induction_range_.Replace(user, instruction, replacement); // update induction
1089 }
1090 }
1091 const HUseList<HEnvironment*>& env_uses = instruction->GetEnvUses();
1092 for (auto it = env_uses.begin(), end = env_uses.end(); it != end;) {
1093 HEnvironment* user = it->GetUser();
1094 size_t index = it->GetIndex();
1095 ++it; // increment before replacing
1096 if (iset_->find(user->GetHolder()) == iset_->end()) { // not excluded?
1097 user->RemoveAsUserOfInput(index);
1098 user->SetRawEnvAt(index, replacement);
1099 replacement->AddEnvUseAt(user, index);
1100 }
1101 }
1102 induction_simplication_count_++;
Aart Bik807868e2016-11-03 17:51:43 -07001103 return true;
Aart Bik8c4a8542016-10-06 11:36:57 -07001104 }
Aart Bik807868e2016-11-03 17:51:43 -07001105 return false;
Aart Bik8c4a8542016-10-06 11:36:57 -07001106}
1107
Aart Bikf8f5a162017-02-06 15:35:29 -08001108bool HLoopOptimization::TryAssignLastValue(HLoopInformation* loop_info,
1109 HInstruction* instruction,
1110 HBasicBlock* block,
1111 bool collect_loop_uses) {
1112 // Assigning the last value is always successful if there are no uses.
1113 // Otherwise, it succeeds in a no early-exit loop by generating the
1114 // proper last value assignment.
1115 int32_t use_count = 0;
1116 return IsOnlyUsedAfterLoop(loop_info, instruction, collect_loop_uses, &use_count) &&
1117 (use_count == 0 ||
1118 (!IsEarlyExit(loop_info) && TryReplaceWithLastValue(instruction, block)));
1119}
1120
Aart Bik6b69e0a2017-01-11 10:20:43 -08001121void HLoopOptimization::RemoveDeadInstructions(const HInstructionList& list) {
1122 for (HBackwardInstructionIterator i(list); !i.Done(); i.Advance()) {
1123 HInstruction* instruction = i.Current();
1124 if (instruction->IsDeadAndRemovable()) {
1125 simplified_ = true;
1126 instruction->GetBlock()->RemoveInstructionOrPhi(instruction);
1127 }
1128 }
1129}
1130
Aart Bik281c6812016-08-26 11:31:48 -07001131} // namespace art