blob: 1d1921a246c52eae645b0da229905628fde149ed [file] [log] [blame]
Aart Bik30efb4e2015-07-30 12:14:31 -07001/*
2 * Copyright (C) 2015 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 "induction_var_analysis.h"
Aart Bik22af3be2015-09-10 12:50:58 -070018#include "induction_var_range.h"
Aart Bik30efb4e2015-07-30 12:14:31 -070019
20namespace art {
21
22/**
Aart Bik22af3be2015-09-10 12:50:58 -070023 * Since graph traversal may enter a SCC at any position, an initial representation may be rotated,
24 * along dependences, viz. any of (a, b, c, d), (d, a, b, c) (c, d, a, b), (b, c, d, a) assuming
25 * a chain of dependences (mutual independent items may occur in arbitrary order). For proper
Aart Bikcc42be02016-10-20 16:14:16 -070026 * classification, the lexicographically first loop-phi is rotated to the front.
Aart Bik22af3be2015-09-10 12:50:58 -070027 */
28static void RotateEntryPhiFirst(HLoopInformation* loop,
29 ArenaVector<HInstruction*>* scc,
30 ArenaVector<HInstruction*>* new_scc) {
Aart Bikcc42be02016-10-20 16:14:16 -070031 // Find very first loop-phi.
Aart Bik22af3be2015-09-10 12:50:58 -070032 const HInstructionList& phis = loop->GetHeader()->GetPhis();
33 HInstruction* phi = nullptr;
34 size_t phi_pos = -1;
35 const size_t size = scc->size();
36 for (size_t i = 0; i < size; i++) {
Vladimir Markoec7802a2015-10-01 20:57:57 +010037 HInstruction* other = (*scc)[i];
Aart Bikf475bee2015-09-16 12:50:25 -070038 if (other->IsLoopHeaderPhi() && (phi == nullptr || phis.FoundBefore(other, phi))) {
39 phi = other;
Aart Bik22af3be2015-09-10 12:50:58 -070040 phi_pos = i;
41 }
42 }
43
Aart Bikcc42be02016-10-20 16:14:16 -070044 // If found, bring that loop-phi to front.
Aart Bik22af3be2015-09-10 12:50:58 -070045 if (phi != nullptr) {
46 new_scc->clear();
47 for (size_t i = 0; i < size; i++) {
Vladimir Markoec7802a2015-10-01 20:57:57 +010048 new_scc->push_back((*scc)[phi_pos]);
Aart Bik22af3be2015-09-10 12:50:58 -070049 if (++phi_pos >= size) phi_pos = 0;
50 }
51 DCHECK_EQ(size, new_scc->size());
52 scc->swap(*new_scc);
53 }
54}
55
Aart Bik0d345cf2016-03-16 10:49:38 -070056/**
57 * Returns true if the from/to types denote a narrowing, integral conversion (precision loss).
58 */
59static bool IsNarrowingIntegralConversion(Primitive::Type from, Primitive::Type to) {
60 switch (from) {
61 case Primitive::kPrimLong:
62 return to == Primitive::kPrimByte || to == Primitive::kPrimShort
63 || to == Primitive::kPrimChar || to == Primitive::kPrimInt;
64 case Primitive::kPrimInt:
65 return to == Primitive::kPrimByte || to == Primitive::kPrimShort
66 || to == Primitive::kPrimChar;
67 case Primitive::kPrimChar:
68 case Primitive::kPrimShort:
69 return to == Primitive::kPrimByte;
70 default:
71 return false;
72 }
73}
74
75/**
76 * Returns narrowest data type.
77 */
78static Primitive::Type Narrowest(Primitive::Type type1, Primitive::Type type2) {
79 return Primitive::ComponentSize(type1) <= Primitive::ComponentSize(type2) ? type1 : type2;
80}
81
Aart Bik30efb4e2015-07-30 12:14:31 -070082//
83// Class methods.
84//
85
86HInductionVarAnalysis::HInductionVarAnalysis(HGraph* graph)
87 : HOptimization(graph, kInductionPassName),
88 global_depth_(0),
Vladimir Marko5233f932015-09-29 19:01:15 +010089 stack_(graph->GetArena()->Adapter(kArenaAllocInductionVarAnalysis)),
Vladimir Marko5233f932015-09-29 19:01:15 +010090 map_(std::less<HInstruction*>(),
91 graph->GetArena()->Adapter(kArenaAllocInductionVarAnalysis)),
Aart Bik7dc96932016-10-12 10:01:05 -070092 scc_(graph->GetArena()->Adapter(kArenaAllocInductionVarAnalysis)),
Vladimir Marko5233f932015-09-29 19:01:15 +010093 cycle_(std::less<HInstruction*>(),
94 graph->GetArena()->Adapter(kArenaAllocInductionVarAnalysis)),
Aart Bik7dc96932016-10-12 10:01:05 -070095 type_(Primitive::kPrimVoid),
Vladimir Marko5233f932015-09-29 19:01:15 +010096 induction_(std::less<HLoopInformation*>(),
Aart Bikcc42be02016-10-20 16:14:16 -070097 graph->GetArena()->Adapter(kArenaAllocInductionVarAnalysis)),
98 cycles_(std::less<HPhi*>(),
99 graph->GetArena()->Adapter(kArenaAllocInductionVarAnalysis)) {
Aart Bik30efb4e2015-07-30 12:14:31 -0700100}
101
102void HInductionVarAnalysis::Run() {
Aart Bik7d57d7f2015-12-09 14:39:48 -0800103 // Detects sequence variables (generalized induction variables) during an outer to inner
104 // traversal of all loops using Gerlek's algorithm. The order is important to enable
105 // range analysis on outer loop while visiting inner loops.
106 for (HReversePostOrderIterator it_graph(*graph_); !it_graph.Done(); it_graph.Advance()) {
Aart Bik30efb4e2015-07-30 12:14:31 -0700107 HBasicBlock* graph_block = it_graph.Current();
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000108 // Don't analyze irreducible loops.
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000109 if (graph_block->IsLoopHeader() && !graph_block->GetLoopInformation()->IsIrreducible()) {
Aart Bik30efb4e2015-07-30 12:14:31 -0700110 VisitLoop(graph_block->GetLoopInformation());
111 }
112 }
113}
114
115void HInductionVarAnalysis::VisitLoop(HLoopInformation* loop) {
116 // Find strongly connected components (SSCs) in the SSA graph of this loop using Tarjan's
117 // algorithm. Due to the descendant-first nature, classification happens "on-demand".
118 global_depth_ = 0;
Aart Bike609b7c2015-08-27 13:46:58 -0700119 DCHECK(stack_.empty());
Aart Bik30efb4e2015-07-30 12:14:31 -0700120 map_.clear();
121
122 for (HBlocksInLoopIterator it_loop(*loop); !it_loop.Done(); it_loop.Advance()) {
123 HBasicBlock* loop_block = it_loop.Current();
Aart Bike609b7c2015-08-27 13:46:58 -0700124 DCHECK(loop_block->IsInLoop());
Aart Bik30efb4e2015-07-30 12:14:31 -0700125 if (loop_block->GetLoopInformation() != loop) {
Aart Bik7dc96932016-10-12 10:01:05 -0700126 continue; // Inner loops visited later.
Aart Bik30efb4e2015-07-30 12:14:31 -0700127 }
128 // Visit phi-operations and instructions.
129 for (HInstructionIterator it(loop_block->GetPhis()); !it.Done(); it.Advance()) {
130 HInstruction* instruction = it.Current();
Aart Bike609b7c2015-08-27 13:46:58 -0700131 if (!IsVisitedNode(instruction)) {
Aart Bik30efb4e2015-07-30 12:14:31 -0700132 VisitNode(loop, instruction);
133 }
134 }
135 for (HInstructionIterator it(loop_block->GetInstructions()); !it.Done(); it.Advance()) {
136 HInstruction* instruction = it.Current();
Aart Bike609b7c2015-08-27 13:46:58 -0700137 if (!IsVisitedNode(instruction)) {
Aart Bik30efb4e2015-07-30 12:14:31 -0700138 VisitNode(loop, instruction);
139 }
140 }
141 }
142
Aart Bike609b7c2015-08-27 13:46:58 -0700143 DCHECK(stack_.empty());
Aart Bik30efb4e2015-07-30 12:14:31 -0700144 map_.clear();
Aart Bikd14c5952015-09-08 15:25:15 -0700145
Aart Bik78296912016-03-25 13:14:53 -0700146 // Determine the loop's trip-count.
Aart Bikd14c5952015-09-08 15:25:15 -0700147 VisitControl(loop);
Aart Bik30efb4e2015-07-30 12:14:31 -0700148}
149
150void HInductionVarAnalysis::VisitNode(HLoopInformation* loop, HInstruction* instruction) {
Aart Bik30efb4e2015-07-30 12:14:31 -0700151 const uint32_t d1 = ++global_depth_;
Aart Bike609b7c2015-08-27 13:46:58 -0700152 map_.Put(instruction, NodeInfo(d1));
Aart Bik30efb4e2015-07-30 12:14:31 -0700153 stack_.push_back(instruction);
154
155 // Visit all descendants.
156 uint32_t low = d1;
Vladimir Marko372f10e2016-05-17 16:30:10 +0100157 for (HInstruction* input : instruction->GetInputs()) {
158 low = std::min(low, VisitDescendant(loop, input));
Aart Bik30efb4e2015-07-30 12:14:31 -0700159 }
160
161 // Lower or found SCC?
162 if (low < d1) {
Aart Bike609b7c2015-08-27 13:46:58 -0700163 map_.find(instruction)->second.depth = low;
Aart Bik30efb4e2015-07-30 12:14:31 -0700164 } else {
165 scc_.clear();
166 cycle_.clear();
167
168 // Pop the stack to build the SCC for classification.
169 while (!stack_.empty()) {
170 HInstruction* x = stack_.back();
171 scc_.push_back(x);
172 stack_.pop_back();
Aart Bike609b7c2015-08-27 13:46:58 -0700173 map_.find(x)->second.done = true;
Aart Bik30efb4e2015-07-30 12:14:31 -0700174 if (x == instruction) {
175 break;
176 }
177 }
178
Aart Bik0d345cf2016-03-16 10:49:38 -0700179 // Type of induction.
180 type_ = scc_[0]->GetType();
181
Aart Bik30efb4e2015-07-30 12:14:31 -0700182 // Classify the SCC.
Aart Bikf475bee2015-09-16 12:50:25 -0700183 if (scc_.size() == 1 && !scc_[0]->IsLoopHeaderPhi()) {
Aart Bik30efb4e2015-07-30 12:14:31 -0700184 ClassifyTrivial(loop, scc_[0]);
185 } else {
186 ClassifyNonTrivial(loop);
187 }
188
189 scc_.clear();
190 cycle_.clear();
191 }
192}
193
194uint32_t HInductionVarAnalysis::VisitDescendant(HLoopInformation* loop, HInstruction* instruction) {
195 // If the definition is either outside the loop (loop invariant entry value)
196 // or assigned in inner loop (inner exit value), the traversal stops.
197 HLoopInformation* otherLoop = instruction->GetBlock()->GetLoopInformation();
198 if (otherLoop != loop) {
199 return global_depth_;
200 }
201
202 // Inspect descendant node.
Aart Bike609b7c2015-08-27 13:46:58 -0700203 if (!IsVisitedNode(instruction)) {
Aart Bik30efb4e2015-07-30 12:14:31 -0700204 VisitNode(loop, instruction);
Aart Bike609b7c2015-08-27 13:46:58 -0700205 return map_.find(instruction)->second.depth;
Aart Bik30efb4e2015-07-30 12:14:31 -0700206 } else {
Aart Bike609b7c2015-08-27 13:46:58 -0700207 auto it = map_.find(instruction);
Aart Bik30efb4e2015-07-30 12:14:31 -0700208 return it->second.done ? global_depth_ : it->second.depth;
209 }
210}
211
212void HInductionVarAnalysis::ClassifyTrivial(HLoopInformation* loop, HInstruction* instruction) {
213 InductionInfo* info = nullptr;
214 if (instruction->IsPhi()) {
Aart Bikf475bee2015-09-16 12:50:25 -0700215 info = TransferPhi(loop, instruction, /* input_index */ 0);
Aart Bik30efb4e2015-07-30 12:14:31 -0700216 } else if (instruction->IsAdd()) {
217 info = TransferAddSub(LookupInfo(loop, instruction->InputAt(0)),
218 LookupInfo(loop, instruction->InputAt(1)), kAdd);
219 } else if (instruction->IsSub()) {
220 info = TransferAddSub(LookupInfo(loop, instruction->InputAt(0)),
221 LookupInfo(loop, instruction->InputAt(1)), kSub);
222 } else if (instruction->IsMul()) {
223 info = TransferMul(LookupInfo(loop, instruction->InputAt(0)),
224 LookupInfo(loop, instruction->InputAt(1)));
Aart Bike609b7c2015-08-27 13:46:58 -0700225 } else if (instruction->IsShl()) {
226 info = TransferShl(LookupInfo(loop, instruction->InputAt(0)),
227 LookupInfo(loop, instruction->InputAt(1)),
228 instruction->InputAt(0)->GetType());
Aart Bik30efb4e2015-07-30 12:14:31 -0700229 } else if (instruction->IsNeg()) {
230 info = TransferNeg(LookupInfo(loop, instruction->InputAt(0)));
Aart Bik0d345cf2016-03-16 10:49:38 -0700231 } else if (instruction->IsTypeConversion()) {
232 info = TransferCnv(LookupInfo(loop, instruction->InputAt(0)),
233 instruction->AsTypeConversion()->GetInputType(),
234 instruction->AsTypeConversion()->GetResultType());
235
Aart Bike609b7c2015-08-27 13:46:58 -0700236 } else if (instruction->IsBoundsCheck()) {
237 info = LookupInfo(loop, instruction->InputAt(0)); // Pass-through.
Aart Bik30efb4e2015-07-30 12:14:31 -0700238 }
239
240 // Successfully classified?
241 if (info != nullptr) {
242 AssignInfo(loop, instruction, info);
243 }
244}
245
246void HInductionVarAnalysis::ClassifyNonTrivial(HLoopInformation* loop) {
247 const size_t size = scc_.size();
Aart Bike609b7c2015-08-27 13:46:58 -0700248 DCHECK_GE(size, 1u);
Aart Bik22af3be2015-09-10 12:50:58 -0700249
Aart Bikcc42be02016-10-20 16:14:16 -0700250 // Rotate proper loop-phi to front.
Aart Bik22af3be2015-09-10 12:50:58 -0700251 if (size > 1) {
Vladimir Marko5233f932015-09-29 19:01:15 +0100252 ArenaVector<HInstruction*> other(graph_->GetArena()->Adapter(kArenaAllocInductionVarAnalysis));
Aart Bik22af3be2015-09-10 12:50:58 -0700253 RotateEntryPhiFirst(loop, &scc_, &other);
254 }
255
Aart Bikcc42be02016-10-20 16:14:16 -0700256 // Analyze from loop-phi onwards.
Aart Bik22af3be2015-09-10 12:50:58 -0700257 HInstruction* phi = scc_[0];
Aart Bikf475bee2015-09-16 12:50:25 -0700258 if (!phi->IsLoopHeaderPhi()) {
Aart Bik30efb4e2015-07-30 12:14:31 -0700259 return;
260 }
Aart Bikf475bee2015-09-16 12:50:25 -0700261
262 // External link should be loop invariant.
263 InductionInfo* initial = LookupInfo(loop, phi->InputAt(0));
Aart Bik30efb4e2015-07-30 12:14:31 -0700264 if (initial == nullptr || initial->induction_class != kInvariant) {
265 return;
266 }
267
Aart Bikcc42be02016-10-20 16:14:16 -0700268 // Store interesting cycle.
269 AssignCycle(phi->AsPhi());
270
Aart Bikf475bee2015-09-16 12:50:25 -0700271 // Singleton is wrap-around induction if all internal links have the same meaning.
Aart Bik30efb4e2015-07-30 12:14:31 -0700272 if (size == 1) {
Aart Bikf475bee2015-09-16 12:50:25 -0700273 InductionInfo* update = TransferPhi(loop, phi, /* input_index */ 1);
Aart Bik30efb4e2015-07-30 12:14:31 -0700274 if (update != nullptr) {
Aart Bik0d345cf2016-03-16 10:49:38 -0700275 AssignInfo(loop, phi, CreateInduction(kWrapAround, initial, update, type_));
Aart Bik30efb4e2015-07-30 12:14:31 -0700276 }
277 return;
278 }
279
280 // Inspect remainder of the cycle that resides in scc_. The cycle_ mapping assigns
Aart Bike609b7c2015-08-27 13:46:58 -0700281 // temporary meaning to its nodes, seeded from the phi instruction and back.
Aart Bik22af3be2015-09-10 12:50:58 -0700282 for (size_t i = 1; i < size; i++) {
Aart Bike609b7c2015-08-27 13:46:58 -0700283 HInstruction* instruction = scc_[i];
Aart Bik30efb4e2015-07-30 12:14:31 -0700284 InductionInfo* update = nullptr;
Aart Bike609b7c2015-08-27 13:46:58 -0700285 if (instruction->IsPhi()) {
Aart Bikf475bee2015-09-16 12:50:25 -0700286 update = SolvePhiAllInputs(loop, phi, instruction);
Aart Bike609b7c2015-08-27 13:46:58 -0700287 } else if (instruction->IsAdd()) {
288 update = SolveAddSub(
289 loop, phi, instruction, instruction->InputAt(0), instruction->InputAt(1), kAdd, true);
290 } else if (instruction->IsSub()) {
291 update = SolveAddSub(
292 loop, phi, instruction, instruction->InputAt(0), instruction->InputAt(1), kSub, true);
Aart Bik7dc96932016-10-12 10:01:05 -0700293 } else if (instruction->IsXor()) {
Aart Bik639cc8c2016-10-18 13:03:31 -0700294 update = SolveXor(loop, phi, instruction, instruction->InputAt(0), instruction->InputAt(1));
295 } else if (instruction->IsEqual()) {
296 update = SolveTest(loop, phi, instruction, 0);
297 } else if (instruction->IsNotEqual()) {
298 update = SolveTest(loop, phi, instruction, 1);
Aart Bik0d345cf2016-03-16 10:49:38 -0700299 } else if (instruction->IsTypeConversion()) {
300 update = SolveCnv(instruction->AsTypeConversion());
Aart Bik30efb4e2015-07-30 12:14:31 -0700301 }
302 if (update == nullptr) {
303 return;
304 }
Aart Bike609b7c2015-08-27 13:46:58 -0700305 cycle_.Put(instruction, update);
Aart Bik30efb4e2015-07-30 12:14:31 -0700306 }
307
Aart Bikf475bee2015-09-16 12:50:25 -0700308 // Success if all internal links received the same temporary meaning.
309 InductionInfo* induction = SolvePhi(phi, /* input_index */ 1);
310 if (induction != nullptr) {
Aart Bike609b7c2015-08-27 13:46:58 -0700311 switch (induction->induction_class) {
312 case kInvariant:
Aart Bik22af3be2015-09-10 12:50:58 -0700313 // Classify first phi and then the rest of the cycle "on-demand".
314 // Statements are scanned in order.
Aart Bik0d345cf2016-03-16 10:49:38 -0700315 AssignInfo(loop, phi, CreateInduction(kLinear, induction, initial, type_));
Aart Bik22af3be2015-09-10 12:50:58 -0700316 for (size_t i = 1; i < size; i++) {
Aart Bike609b7c2015-08-27 13:46:58 -0700317 ClassifyTrivial(loop, scc_[i]);
318 }
319 break;
320 case kPeriodic:
Aart Bik22af3be2015-09-10 12:50:58 -0700321 // Classify all elements in the cycle with the found periodic induction while
322 // rotating each first element to the end. Lastly, phi is classified.
323 // Statements are scanned in reverse order.
324 for (size_t i = size - 1; i >= 1; i--) {
325 AssignInfo(loop, scc_[i], induction);
Aart Bike609b7c2015-08-27 13:46:58 -0700326 induction = RotatePeriodicInduction(induction->op_b, induction->op_a);
327 }
328 AssignInfo(loop, phi, induction);
329 break;
330 default:
331 break;
Aart Bik30efb4e2015-07-30 12:14:31 -0700332 }
333 }
334}
335
Aart Bike609b7c2015-08-27 13:46:58 -0700336HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::RotatePeriodicInduction(
337 InductionInfo* induction,
338 InductionInfo* last) {
339 // Rotates a periodic induction of the form
340 // (a, b, c, d, e)
341 // into
342 // (b, c, d, e, a)
343 // in preparation of assigning this to the previous variable in the sequence.
344 if (induction->induction_class == kInvariant) {
Aart Bik0d345cf2016-03-16 10:49:38 -0700345 return CreateInduction(kPeriodic, induction, last, type_);
Aart Bike609b7c2015-08-27 13:46:58 -0700346 }
Aart Bik0d345cf2016-03-16 10:49:38 -0700347 return CreateInduction(
348 kPeriodic, induction->op_a, RotatePeriodicInduction(induction->op_b, last), type_);
Aart Bike609b7c2015-08-27 13:46:58 -0700349}
350
Aart Bikf475bee2015-09-16 12:50:25 -0700351HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::TransferPhi(HLoopInformation* loop,
352 HInstruction* phi,
353 size_t input_index) {
354 // Match all phi inputs from input_index onwards exactly.
Vladimir Markoe9004912016-06-16 16:50:52 +0100355 HInputsRef inputs = phi->GetInputs();
Vladimir Marko372f10e2016-05-17 16:30:10 +0100356 DCHECK_LT(input_index, inputs.size());
357 InductionInfo* a = LookupInfo(loop, inputs[input_index]);
358 for (size_t i = input_index + 1; i < inputs.size(); i++) {
359 InductionInfo* b = LookupInfo(loop, inputs[i]);
Aart Bikf475bee2015-09-16 12:50:25 -0700360 if (!InductionEqual(a, b)) {
361 return nullptr;
362 }
Aart Bik30efb4e2015-07-30 12:14:31 -0700363 }
Aart Bikf475bee2015-09-16 12:50:25 -0700364 return a;
Aart Bik30efb4e2015-07-30 12:14:31 -0700365}
366
367HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::TransferAddSub(InductionInfo* a,
368 InductionInfo* b,
369 InductionOp op) {
Aart Bike609b7c2015-08-27 13:46:58 -0700370 // Transfer over an addition or subtraction: any invariant, linear, wrap-around, or periodic
371 // can be combined with an invariant to yield a similar result. Even two linear inputs can
372 // be combined. All other combinations fail, however.
Aart Bik30efb4e2015-07-30 12:14:31 -0700373 if (a != nullptr && b != nullptr) {
Aart Bikcc42be02016-10-20 16:14:16 -0700374 type_ = Narrowest(type_, Narrowest(a->type, b->type));
Aart Bik30efb4e2015-07-30 12:14:31 -0700375 if (a->induction_class == kInvariant && b->induction_class == kInvariant) {
Aart Bik471a2032015-09-04 18:22:11 -0700376 return CreateInvariantOp(op, a, b);
Aart Bik30efb4e2015-07-30 12:14:31 -0700377 } else if (a->induction_class == kLinear && b->induction_class == kLinear) {
Aart Bik0d345cf2016-03-16 10:49:38 -0700378 return CreateInduction(kLinear,
379 TransferAddSub(a->op_a, b->op_a, op),
380 TransferAddSub(a->op_b, b->op_b, op),
381 type_);
Aart Bike609b7c2015-08-27 13:46:58 -0700382 } else if (a->induction_class == kInvariant) {
383 InductionInfo* new_a = b->op_a;
384 InductionInfo* new_b = TransferAddSub(a, b->op_b, op);
385 if (b->induction_class != kLinear) {
386 DCHECK(b->induction_class == kWrapAround || b->induction_class == kPeriodic);
387 new_a = TransferAddSub(a, new_a, op);
388 } else if (op == kSub) { // Negation required.
389 new_a = TransferNeg(new_a);
390 }
Aart Bik0d345cf2016-03-16 10:49:38 -0700391 return CreateInduction(b->induction_class, new_a, new_b, type_);
Aart Bike609b7c2015-08-27 13:46:58 -0700392 } else if (b->induction_class == kInvariant) {
393 InductionInfo* new_a = a->op_a;
394 InductionInfo* new_b = TransferAddSub(a->op_b, b, op);
395 if (a->induction_class != kLinear) {
396 DCHECK(a->induction_class == kWrapAround || a->induction_class == kPeriodic);
397 new_a = TransferAddSub(new_a, b, op);
398 }
Aart Bik0d345cf2016-03-16 10:49:38 -0700399 return CreateInduction(a->induction_class, new_a, new_b, type_);
Aart Bik30efb4e2015-07-30 12:14:31 -0700400 }
401 }
402 return nullptr;
403}
404
405HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::TransferMul(InductionInfo* a,
406 InductionInfo* b) {
Aart Bike609b7c2015-08-27 13:46:58 -0700407 // Transfer over a multiplication: any invariant, linear, wrap-around, or periodic
408 // can be multiplied with an invariant to yield a similar but multiplied result.
409 // Two non-invariant inputs cannot be multiplied, however.
Aart Bik30efb4e2015-07-30 12:14:31 -0700410 if (a != nullptr && b != nullptr) {
Aart Bikcc42be02016-10-20 16:14:16 -0700411 type_ = Narrowest(type_, Narrowest(a->type, b->type));
Aart Bik30efb4e2015-07-30 12:14:31 -0700412 if (a->induction_class == kInvariant && b->induction_class == kInvariant) {
Aart Bik471a2032015-09-04 18:22:11 -0700413 return CreateInvariantOp(kMul, a, b);
Aart Bike609b7c2015-08-27 13:46:58 -0700414 } else if (a->induction_class == kInvariant) {
Aart Bik0d345cf2016-03-16 10:49:38 -0700415 return CreateInduction(b->induction_class,
416 TransferMul(a, b->op_a),
417 TransferMul(a, b->op_b),
418 type_);
Aart Bike609b7c2015-08-27 13:46:58 -0700419 } else if (b->induction_class == kInvariant) {
Aart Bik0d345cf2016-03-16 10:49:38 -0700420 return CreateInduction(a->induction_class,
421 TransferMul(a->op_a, b),
422 TransferMul(a->op_b, b),
423 type_);
Aart Bike609b7c2015-08-27 13:46:58 -0700424 }
425 }
426 return nullptr;
427}
428
429HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::TransferShl(InductionInfo* a,
430 InductionInfo* b,
Aart Bikd14c5952015-09-08 15:25:15 -0700431 Primitive::Type type) {
Aart Bike609b7c2015-08-27 13:46:58 -0700432 // Transfer over a shift left: treat shift by restricted constant as equivalent multiplication.
Aart Bik471a2032015-09-04 18:22:11 -0700433 int64_t value = -1;
Aart Bik97412c922016-02-19 20:14:38 -0800434 if (a != nullptr && IsExact(b, &value)) {
Aart Bike609b7c2015-08-27 13:46:58 -0700435 // Obtain the constant needed for the multiplication. This yields an existing instruction
436 // if the constants is already there. Otherwise, this has a side effect on the HIR.
437 // The restriction on the shift factor avoids generating a negative constant
438 // (viz. 1 << 31 and 1L << 63 set the sign bit). The code assumes that generalization
439 // for shift factors outside [0,32) and [0,64) ranges is done by earlier simplification.
Aart Bikd14c5952015-09-08 15:25:15 -0700440 if ((type == Primitive::kPrimInt && 0 <= value && value < 31) ||
441 (type == Primitive::kPrimLong && 0 <= value && value < 63)) {
442 return TransferMul(a, CreateConstant(1 << value, type));
Aart Bik30efb4e2015-07-30 12:14:31 -0700443 }
444 }
445 return nullptr;
446}
447
448HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::TransferNeg(InductionInfo* a) {
Aart Bike609b7c2015-08-27 13:46:58 -0700449 // Transfer over a unary negation: an invariant, linear, wrap-around, or periodic input
450 // yields a similar but negated induction as result.
Aart Bik30efb4e2015-07-30 12:14:31 -0700451 if (a != nullptr) {
Aart Bikcc42be02016-10-20 16:14:16 -0700452 type_ = Narrowest(type_, a->type);
Aart Bik30efb4e2015-07-30 12:14:31 -0700453 if (a->induction_class == kInvariant) {
Aart Bik471a2032015-09-04 18:22:11 -0700454 return CreateInvariantOp(kNeg, nullptr, a);
Aart Bik30efb4e2015-07-30 12:14:31 -0700455 }
Aart Bik0d345cf2016-03-16 10:49:38 -0700456 return CreateInduction(a->induction_class, TransferNeg(a->op_a), TransferNeg(a->op_b), type_);
457 }
458 return nullptr;
459}
460
461HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::TransferCnv(InductionInfo* a,
462 Primitive::Type from,
463 Primitive::Type to) {
464 if (a != nullptr) {
465 // Allow narrowing conversion in certain cases.
466 if (IsNarrowingIntegralConversion(from, to)) {
467 if (a->induction_class == kLinear) {
468 if (a->type == to || (a->type == from && IsNarrowingIntegralConversion(from, to))) {
469 return CreateInduction(kLinear, a->op_a, a->op_b, to);
470 }
471 }
472 // TODO: other cases useful too?
473 }
Aart Bik30efb4e2015-07-30 12:14:31 -0700474 }
475 return nullptr;
476}
477
Aart Bikf475bee2015-09-16 12:50:25 -0700478HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::SolvePhi(HInstruction* phi,
479 size_t input_index) {
480 // Match all phi inputs from input_index onwards exactly.
Vladimir Markoe9004912016-06-16 16:50:52 +0100481 HInputsRef inputs = phi->GetInputs();
Vladimir Marko372f10e2016-05-17 16:30:10 +0100482 DCHECK_LT(input_index, inputs.size());
483 auto ita = cycle_.find(inputs[input_index]);
Aart Bik30efb4e2015-07-30 12:14:31 -0700484 if (ita != cycle_.end()) {
Vladimir Marko372f10e2016-05-17 16:30:10 +0100485 for (size_t i = input_index + 1; i < inputs.size(); i++) {
486 auto itb = cycle_.find(inputs[i]);
Aart Bikf475bee2015-09-16 12:50:25 -0700487 if (itb == cycle_.end() ||
488 !HInductionVarAnalysis::InductionEqual(ita->second, itb->second)) {
Aart Bik30efb4e2015-07-30 12:14:31 -0700489 return nullptr;
490 }
491 }
Aart Bikf475bee2015-09-16 12:50:25 -0700492 return ita->second;
493 }
494 return nullptr;
495}
496
497HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::SolvePhiAllInputs(
498 HLoopInformation* loop,
499 HInstruction* entry_phi,
500 HInstruction* phi) {
501 // Match all phi inputs.
502 InductionInfo* match = SolvePhi(phi, /* input_index */ 0);
503 if (match != nullptr) {
504 return match;
Aart Bik30efb4e2015-07-30 12:14:31 -0700505 }
Aart Bik30efb4e2015-07-30 12:14:31 -0700506
Aart Bikf475bee2015-09-16 12:50:25 -0700507 // Otherwise, try to solve for a periodic seeded from phi onward.
508 // Only tight multi-statement cycles are considered in order to
509 // simplify rotating the periodic during the final classification.
510 if (phi->IsLoopHeaderPhi() && phi->InputCount() == 2) {
511 InductionInfo* a = LookupInfo(loop, phi->InputAt(0));
Aart Bike609b7c2015-08-27 13:46:58 -0700512 if (a != nullptr && a->induction_class == kInvariant) {
Aart Bikf475bee2015-09-16 12:50:25 -0700513 if (phi->InputAt(1) == entry_phi) {
514 InductionInfo* initial = LookupInfo(loop, entry_phi->InputAt(0));
Aart Bik0d345cf2016-03-16 10:49:38 -0700515 return CreateInduction(kPeriodic, a, initial, type_);
Aart Bike609b7c2015-08-27 13:46:58 -0700516 }
Aart Bikf475bee2015-09-16 12:50:25 -0700517 InductionInfo* b = SolvePhi(phi, /* input_index */ 1);
518 if (b != nullptr && b->induction_class == kPeriodic) {
Aart Bik0d345cf2016-03-16 10:49:38 -0700519 return CreateInduction(kPeriodic, a, b, type_);
Aart Bik30efb4e2015-07-30 12:14:31 -0700520 }
521 }
522 }
Aart Bik30efb4e2015-07-30 12:14:31 -0700523 return nullptr;
524}
525
Aart Bike609b7c2015-08-27 13:46:58 -0700526HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::SolveAddSub(HLoopInformation* loop,
Aart Bikf475bee2015-09-16 12:50:25 -0700527 HInstruction* entry_phi,
Aart Bike609b7c2015-08-27 13:46:58 -0700528 HInstruction* instruction,
529 HInstruction* x,
530 HInstruction* y,
531 InductionOp op,
532 bool is_first_call) {
533 // Solve within a cycle over an addition or subtraction: adding or subtracting an
534 // invariant value, seeded from phi, keeps adding to the stride of the induction.
535 InductionInfo* b = LookupInfo(loop, y);
536 if (b != nullptr && b->induction_class == kInvariant) {
Aart Bikf475bee2015-09-16 12:50:25 -0700537 if (x == entry_phi) {
Aart Bik471a2032015-09-04 18:22:11 -0700538 return (op == kAdd) ? b : CreateInvariantOp(kNeg, nullptr, b);
Aart Bike609b7c2015-08-27 13:46:58 -0700539 }
540 auto it = cycle_.find(x);
541 if (it != cycle_.end()) {
542 InductionInfo* a = it->second;
543 if (a->induction_class == kInvariant) {
Aart Bik471a2032015-09-04 18:22:11 -0700544 return CreateInvariantOp(op, a, b);
Aart Bike609b7c2015-08-27 13:46:58 -0700545 }
Aart Bik30efb4e2015-07-30 12:14:31 -0700546 }
547 }
Aart Bike609b7c2015-08-27 13:46:58 -0700548
549 // Try some alternatives before failing.
550 if (op == kAdd) {
551 // Try the other way around for an addition if considered for first time.
552 if (is_first_call) {
Aart Bikf475bee2015-09-16 12:50:25 -0700553 return SolveAddSub(loop, entry_phi, instruction, y, x, op, false);
Aart Bike609b7c2015-08-27 13:46:58 -0700554 }
555 } else if (op == kSub) {
Aart Bikf475bee2015-09-16 12:50:25 -0700556 // Solve within a tight cycle that is formed by exactly two instructions,
557 // one phi and one update, for a periodic idiom of the form k = c - k;
558 if (y == entry_phi && entry_phi->InputCount() == 2 && instruction == entry_phi->InputAt(1)) {
Aart Bike609b7c2015-08-27 13:46:58 -0700559 InductionInfo* a = LookupInfo(loop, x);
560 if (a != nullptr && a->induction_class == kInvariant) {
Aart Bikf475bee2015-09-16 12:50:25 -0700561 InductionInfo* initial = LookupInfo(loop, entry_phi->InputAt(0));
Aart Bik0d345cf2016-03-16 10:49:38 -0700562 return CreateInduction(kPeriodic, CreateInvariantOp(kSub, a, initial), initial, type_);
Aart Bike609b7c2015-08-27 13:46:58 -0700563 }
564 }
565 }
566
Aart Bik30efb4e2015-07-30 12:14:31 -0700567 return nullptr;
568}
569
Aart Bik7dc96932016-10-12 10:01:05 -0700570HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::SolveXor(HLoopInformation* loop,
571 HInstruction* entry_phi,
572 HInstruction* instruction,
573 HInstruction* x,
Aart Bik639cc8c2016-10-18 13:03:31 -0700574 HInstruction* y) {
575 // Solve within a tight cycle on x = c ^ x or x = x ^ c.
576 if (entry_phi->InputCount() == 2 && instruction == entry_phi->InputAt(1)) {
577 InductionInfo* initial = LookupInfo(loop, entry_phi->InputAt(0));
578 InductionInfo* a = LookupInfo(loop, x);
579 if (a != nullptr && a->induction_class == kInvariant && entry_phi == y) {
580 return CreateInduction(kPeriodic, CreateInvariantOp(kXor, a, initial), initial, type_);
581 }
582 InductionInfo* b = LookupInfo(loop, y);
583 if (b != nullptr && b->induction_class == kInvariant && entry_phi == x) {
Aart Bik7dc96932016-10-12 10:01:05 -0700584 return CreateInduction(kPeriodic, CreateInvariantOp(kXor, initial, b), initial, type_);
585 }
586 }
Aart Bik639cc8c2016-10-18 13:03:31 -0700587 return nullptr;
588}
589
590HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::SolveTest(HLoopInformation* loop,
591 HInstruction* entry_phi,
592 HInstruction* instruction,
593 int64_t opposite_value) {
594 // Detect hidden XOR construction in tight cycles on x = (x == 0) or x = (x != 1).
595 int64_t value = -1;
596 HInstruction* x = instruction->InputAt(0);
597 HInstruction* y = instruction->InputAt(1);
598 if (IsExact(LookupInfo(loop, x), &value) && value == opposite_value) {
599 return SolveXor(loop, entry_phi, instruction, graph_->GetIntConstant(1), y);
600 } else if (IsExact(LookupInfo(loop, y), &value) && value == opposite_value) {
601 return SolveXor(loop, entry_phi, instruction, x, graph_->GetIntConstant(1));
Aart Bik7dc96932016-10-12 10:01:05 -0700602 }
603 return nullptr;
604}
605
Aart Bik0d345cf2016-03-16 10:49:38 -0700606HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::SolveCnv(HTypeConversion* conversion) {
607 Primitive::Type from = conversion->GetInputType();
608 Primitive::Type to = conversion->GetResultType();
609 // A narrowing conversion is allowed within the cycle of a linear induction, provided that the
610 // narrowest encountered type is recorded with the induction to account for the precision loss.
611 if (IsNarrowingIntegralConversion(from, to)) {
612 auto it = cycle_.find(conversion->GetInput());
613 if (it != cycle_.end() && it->second->induction_class == kInvariant) {
614 type_ = Narrowest(type_, to);
615 return it->second;
616 }
617 }
618 return nullptr;
619}
620
Aart Bikd14c5952015-09-08 15:25:15 -0700621void HInductionVarAnalysis::VisitControl(HLoopInformation* loop) {
622 HInstruction* control = loop->GetHeader()->GetLastInstruction();
623 if (control->IsIf()) {
624 HIf* ifs = control->AsIf();
625 HBasicBlock* if_true = ifs->IfTrueSuccessor();
626 HBasicBlock* if_false = ifs->IfFalseSuccessor();
627 HInstruction* if_expr = ifs->InputAt(0);
628 // Determine if loop has following structure in header.
629 // loop-header: ....
630 // if (condition) goto X
631 if (if_expr->IsCondition()) {
632 HCondition* condition = if_expr->AsCondition();
633 InductionInfo* a = LookupInfo(loop, condition->InputAt(0));
634 InductionInfo* b = LookupInfo(loop, condition->InputAt(1));
635 Primitive::Type type = condition->InputAt(0)->GetType();
Aart Bik0d345cf2016-03-16 10:49:38 -0700636 // Determine if the loop control uses a known sequence on an if-exit (X outside) or on
637 // an if-iterate (X inside), expressed as if-iterate when passed into VisitCondition().
638 if (a == nullptr || b == nullptr) {
639 return; // Loop control is not a sequence.
Aart Bikd14c5952015-09-08 15:25:15 -0700640 } else if (if_true->GetLoopInformation() != loop && if_false->GetLoopInformation() == loop) {
641 VisitCondition(loop, a, b, type, condition->GetOppositeCondition());
642 } else if (if_true->GetLoopInformation() == loop && if_false->GetLoopInformation() != loop) {
643 VisitCondition(loop, a, b, type, condition->GetCondition());
644 }
645 }
646 }
647}
648
649void HInductionVarAnalysis::VisitCondition(HLoopInformation* loop,
650 InductionInfo* a,
651 InductionInfo* b,
652 Primitive::Type type,
653 IfCondition cmp) {
654 if (a->induction_class == kInvariant && b->induction_class == kLinear) {
Aart Bikf475bee2015-09-16 12:50:25 -0700655 // Swap condition if induction is at right-hand-side (e.g. U > i is same as i < U).
Aart Bikd14c5952015-09-08 15:25:15 -0700656 switch (cmp) {
657 case kCondLT: VisitCondition(loop, b, a, type, kCondGT); break;
658 case kCondLE: VisitCondition(loop, b, a, type, kCondGE); break;
659 case kCondGT: VisitCondition(loop, b, a, type, kCondLT); break;
660 case kCondGE: VisitCondition(loop, b, a, type, kCondLE); break;
Aart Bikf475bee2015-09-16 12:50:25 -0700661 case kCondNE: VisitCondition(loop, b, a, type, kCondNE); break;
Aart Bikd14c5952015-09-08 15:25:15 -0700662 default: break;
663 }
664 } else if (a->induction_class == kLinear && b->induction_class == kInvariant) {
Aart Bikf475bee2015-09-16 12:50:25 -0700665 // Analyze condition with induction at left-hand-side (e.g. i < U).
Aart Bik9401f532015-09-28 16:25:56 -0700666 InductionInfo* lower_expr = a->op_b;
667 InductionInfo* upper_expr = b;
Aart Bik97412c922016-02-19 20:14:38 -0800668 InductionInfo* stride_expr = a->op_a;
669 // Constant stride?
Aart Bik9401f532015-09-28 16:25:56 -0700670 int64_t stride_value = 0;
Aart Bik97412c922016-02-19 20:14:38 -0800671 if (!IsExact(stride_expr, &stride_value)) {
Aart Bikf475bee2015-09-16 12:50:25 -0700672 return;
673 }
Aart Bik358af832016-02-24 14:17:53 -0800674 // Rewrite condition i != U into strict end condition i < U or i > U if this end condition
675 // is reached exactly (tested by verifying if the loop has a unit stride and the non-strict
676 // condition would be always taken).
677 if (cmp == kCondNE && ((stride_value == +1 && IsTaken(lower_expr, upper_expr, kCondLE)) ||
678 (stride_value == -1 && IsTaken(lower_expr, upper_expr, kCondGE)))) {
Aart Bik9401f532015-09-28 16:25:56 -0700679 cmp = stride_value > 0 ? kCondLT : kCondGT;
Aart Bikd14c5952015-09-08 15:25:15 -0700680 }
Aart Bik0d345cf2016-03-16 10:49:38 -0700681 // Only accept integral condition. A mismatch between the type of condition and the induction
682 // is only allowed if the, necessarily narrower, induction range fits the narrower control.
683 if (type != Primitive::kPrimInt && type != Primitive::kPrimLong) {
684 return; // not integral
685 } else if (type != a->type &&
686 !FitsNarrowerControl(lower_expr, upper_expr, stride_value, a->type, cmp)) {
687 return; // mismatched type
688 }
Aart Bikf475bee2015-09-16 12:50:25 -0700689 // Normalize a linear loop control with a nonzero stride:
690 // stride > 0, either i < U or i <= U
691 // stride < 0, either i > U or i >= U
Aart Bikf475bee2015-09-16 12:50:25 -0700692 if ((stride_value > 0 && (cmp == kCondLT || cmp == kCondLE)) ||
693 (stride_value < 0 && (cmp == kCondGT || cmp == kCondGE))) {
Aart Bik97412c922016-02-19 20:14:38 -0800694 VisitTripCount(loop, lower_expr, upper_expr, stride_expr, stride_value, type, cmp);
Aart Bikf475bee2015-09-16 12:50:25 -0700695 }
Aart Bikd14c5952015-09-08 15:25:15 -0700696 }
697}
698
699void HInductionVarAnalysis::VisitTripCount(HLoopInformation* loop,
Aart Bik9401f532015-09-28 16:25:56 -0700700 InductionInfo* lower_expr,
701 InductionInfo* upper_expr,
Aart Bik97412c922016-02-19 20:14:38 -0800702 InductionInfo* stride_expr,
Aart Bik9401f532015-09-28 16:25:56 -0700703 int64_t stride_value,
Aart Bikd14c5952015-09-08 15:25:15 -0700704 Primitive::Type type,
Aart Bikf475bee2015-09-16 12:50:25 -0700705 IfCondition cmp) {
Aart Bikd14c5952015-09-08 15:25:15 -0700706 // Any loop of the general form:
707 //
708 // for (i = L; i <= U; i += S) // S > 0
709 // or for (i = L; i >= U; i += S) // S < 0
710 // .. i ..
711 //
712 // can be normalized into:
713 //
714 // for (n = 0; n < TC; n++) // where TC = (U + S - L) / S
715 // .. L + S * n ..
716 //
Aart Bik9401f532015-09-28 16:25:56 -0700717 // taking the following into consideration:
Aart Bikd14c5952015-09-08 15:25:15 -0700718 //
Aart Bik9401f532015-09-28 16:25:56 -0700719 // (1) Using the same precision, the TC (trip-count) expression should be interpreted as
720 // an unsigned entity, for example, as in the following loop that uses the full range:
721 // for (int i = INT_MIN; i < INT_MAX; i++) // TC = UINT_MAX
722 // (2) The TC is only valid if the loop is taken, otherwise TC = 0, as in:
Aart Bikd5cc6832016-06-22 16:34:46 -0700723 // for (int i = 12; i < U; i++) // TC = 0 when U <= 12
Aart Bik9401f532015-09-28 16:25:56 -0700724 // If this cannot be determined at compile-time, the TC is only valid within the
Aart Bik22f05872015-10-27 15:56:28 -0700725 // loop-body proper, not the loop-header unless enforced with an explicit taken-test.
Aart Bik9401f532015-09-28 16:25:56 -0700726 // (3) The TC is only valid if the loop is finite, otherwise TC has no value, as in:
727 // for (int i = 0; i <= U; i++) // TC = Inf when U = INT_MAX
728 // If this cannot be determined at compile-time, the TC is only valid when enforced
Aart Bik22f05872015-10-27 15:56:28 -0700729 // with an explicit finite-test.
Aart Bik9401f532015-09-28 16:25:56 -0700730 // (4) For loops which early-exits, the TC forms an upper bound, as in:
731 // for (int i = 0; i < 10 && ....; i++) // TC <= 10
Aart Bik22f05872015-10-27 15:56:28 -0700732 InductionInfo* trip_count = upper_expr;
Aart Bik9401f532015-09-28 16:25:56 -0700733 const bool is_taken = IsTaken(lower_expr, upper_expr, cmp);
734 const bool is_finite = IsFinite(upper_expr, stride_value, type, cmp);
735 const bool cancels = (cmp == kCondLT || cmp == kCondGT) && std::abs(stride_value) == 1;
Aart Bikd14c5952015-09-08 15:25:15 -0700736 if (!cancels) {
737 // Convert exclusive integral inequality into inclusive integral inequality,
738 // viz. condition i < U is i <= U - 1 and condition i > U is i >= U + 1.
Aart Bikf475bee2015-09-16 12:50:25 -0700739 if (cmp == kCondLT) {
Aart Bik22f05872015-10-27 15:56:28 -0700740 trip_count = CreateInvariantOp(kSub, trip_count, CreateConstant(1, type));
Aart Bikf475bee2015-09-16 12:50:25 -0700741 } else if (cmp == kCondGT) {
Aart Bik22f05872015-10-27 15:56:28 -0700742 trip_count = CreateInvariantOp(kAdd, trip_count, CreateConstant(1, type));
Aart Bikd14c5952015-09-08 15:25:15 -0700743 }
744 // Compensate for stride.
Aart Bik97412c922016-02-19 20:14:38 -0800745 trip_count = CreateInvariantOp(kAdd, trip_count, stride_expr);
Aart Bikd14c5952015-09-08 15:25:15 -0700746 }
Aart Bik97412c922016-02-19 20:14:38 -0800747 trip_count = CreateInvariantOp(
748 kDiv, CreateInvariantOp(kSub, trip_count, lower_expr), stride_expr);
Aart Bikd14c5952015-09-08 15:25:15 -0700749 // Assign the trip-count expression to the loop control. Clients that use the information
Aart Bik9401f532015-09-28 16:25:56 -0700750 // should be aware that the expression is only valid under the conditions listed above.
Aart Bik22f05872015-10-27 15:56:28 -0700751 InductionOp tcKind = kTripCountInBodyUnsafe; // needs both tests
Aart Bik9401f532015-09-28 16:25:56 -0700752 if (is_taken && is_finite) {
Aart Bik22f05872015-10-27 15:56:28 -0700753 tcKind = kTripCountInLoop; // needs neither test
Aart Bik9401f532015-09-28 16:25:56 -0700754 } else if (is_finite) {
Aart Bik22f05872015-10-27 15:56:28 -0700755 tcKind = kTripCountInBody; // needs taken-test
Aart Bik9401f532015-09-28 16:25:56 -0700756 } else if (is_taken) {
Aart Bik22f05872015-10-27 15:56:28 -0700757 tcKind = kTripCountInLoopUnsafe; // needs finite-test
Aart Bik9401f532015-09-28 16:25:56 -0700758 }
Aart Bik22f05872015-10-27 15:56:28 -0700759 InductionOp op = kNop;
760 switch (cmp) {
761 case kCondLT: op = kLT; break;
762 case kCondLE: op = kLE; break;
763 case kCondGT: op = kGT; break;
764 case kCondGE: op = kGE; break;
765 default: LOG(FATAL) << "CONDITION UNREACHABLE";
766 }
Aart Bik009cace2016-09-16 10:15:19 -0700767 // Associate trip count with control instruction, rather than the condition (even
768 // though it's its use) since former provides a convenient use-free placeholder.
769 HInstruction* control = loop->GetHeader()->GetLastInstruction();
Aart Bik22f05872015-10-27 15:56:28 -0700770 InductionInfo* taken_test = CreateInvariantOp(op, lower_expr, upper_expr);
Aart Bik009cace2016-09-16 10:15:19 -0700771 DCHECK(control->IsIf());
772 AssignInfo(loop, control, CreateTripCount(tcKind, trip_count, taken_test, type));
Aart Bik9401f532015-09-28 16:25:56 -0700773}
774
775bool HInductionVarAnalysis::IsTaken(InductionInfo* lower_expr,
776 InductionInfo* upper_expr,
777 IfCondition cmp) {
778 int64_t lower_value;
779 int64_t upper_value;
Aart Bik97412c922016-02-19 20:14:38 -0800780 switch (cmp) {
781 case kCondLT:
782 return IsAtMost(lower_expr, &lower_value)
783 && IsAtLeast(upper_expr, &upper_value)
784 && lower_value < upper_value;
785 case kCondLE:
786 return IsAtMost(lower_expr, &lower_value)
787 && IsAtLeast(upper_expr, &upper_value)
788 && lower_value <= upper_value;
789 case kCondGT:
790 return IsAtLeast(lower_expr, &lower_value)
791 && IsAtMost(upper_expr, &upper_value)
792 && lower_value > upper_value;
793 case kCondGE:
794 return IsAtLeast(lower_expr, &lower_value)
795 && IsAtMost(upper_expr, &upper_value)
796 && lower_value >= upper_value;
797 default:
798 LOG(FATAL) << "CONDITION UNREACHABLE";
Aart Bik9401f532015-09-28 16:25:56 -0700799 }
800 return false; // not certain, may be untaken
801}
802
803bool HInductionVarAnalysis::IsFinite(InductionInfo* upper_expr,
804 int64_t stride_value,
805 Primitive::Type type,
806 IfCondition cmp) {
Aart Bik0d345cf2016-03-16 10:49:38 -0700807 const int64_t min = Primitive::MinValueOfIntegralType(type);
808 const int64_t max = Primitive::MaxValueOfIntegralType(type);
Aart Bik9401f532015-09-28 16:25:56 -0700809 // Some rules under which it is certain at compile-time that the loop is finite.
810 int64_t value;
811 switch (cmp) {
812 case kCondLT:
813 return stride_value == 1 ||
Aart Bik97412c922016-02-19 20:14:38 -0800814 (IsAtMost(upper_expr, &value) && value <= (max - stride_value + 1));
Aart Bik9401f532015-09-28 16:25:56 -0700815 case kCondLE:
Aart Bik97412c922016-02-19 20:14:38 -0800816 return (IsAtMost(upper_expr, &value) && value <= (max - stride_value));
Aart Bik9401f532015-09-28 16:25:56 -0700817 case kCondGT:
818 return stride_value == -1 ||
Aart Bik97412c922016-02-19 20:14:38 -0800819 (IsAtLeast(upper_expr, &value) && value >= (min - stride_value - 1));
Aart Bik9401f532015-09-28 16:25:56 -0700820 case kCondGE:
Aart Bik97412c922016-02-19 20:14:38 -0800821 return (IsAtLeast(upper_expr, &value) && value >= (min - stride_value));
Aart Bike9f37602015-10-09 11:15:55 -0700822 default:
823 LOG(FATAL) << "CONDITION UNREACHABLE";
Aart Bik9401f532015-09-28 16:25:56 -0700824 }
825 return false; // not certain, may be infinite
Aart Bikd14c5952015-09-08 15:25:15 -0700826}
827
Aart Bik0d345cf2016-03-16 10:49:38 -0700828bool HInductionVarAnalysis::FitsNarrowerControl(InductionInfo* lower_expr,
829 InductionInfo* upper_expr,
830 int64_t stride_value,
831 Primitive::Type type,
832 IfCondition cmp) {
833 int64_t min = Primitive::MinValueOfIntegralType(type);
834 int64_t max = Primitive::MaxValueOfIntegralType(type);
835 // Inclusive test need one extra.
836 if (stride_value != 1 && stride_value != -1) {
837 return false; // non-unit stride
838 } else if (cmp == kCondLE) {
839 max--;
840 } else if (cmp == kCondGE) {
841 min++;
842 }
843 // Do both bounds fit the range?
Vladimir Marko0e2f2ff2016-03-22 12:31:54 +0000844 // Note: The `value` is initialized to please valgrind - the compiler can reorder
845 // the return value check with the `value` check, b/27651442 .
846 int64_t value = 0;
Aart Bik0d345cf2016-03-16 10:49:38 -0700847 return IsAtLeast(lower_expr, &value) && value >= min &&
848 IsAtMost(lower_expr, &value) && value <= max &&
849 IsAtLeast(upper_expr, &value) && value >= min &&
850 IsAtMost(upper_expr, &value) && value <= max;
851}
852
Aart Bik30efb4e2015-07-30 12:14:31 -0700853void HInductionVarAnalysis::AssignInfo(HLoopInformation* loop,
854 HInstruction* instruction,
855 InductionInfo* info) {
Aart Bike609b7c2015-08-27 13:46:58 -0700856 auto it = induction_.find(loop);
857 if (it == induction_.end()) {
858 it = induction_.Put(loop,
859 ArenaSafeMap<HInstruction*, InductionInfo*>(
Vladimir Marko5233f932015-09-29 19:01:15 +0100860 std::less<HInstruction*>(),
861 graph_->GetArena()->Adapter(kArenaAllocInductionVarAnalysis)));
Aart Bike609b7c2015-08-27 13:46:58 -0700862 }
863 it->second.Put(instruction, info);
Aart Bik30efb4e2015-07-30 12:14:31 -0700864}
865
Aart Bike609b7c2015-08-27 13:46:58 -0700866HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::LookupInfo(HLoopInformation* loop,
867 HInstruction* instruction) {
868 auto it = induction_.find(loop);
869 if (it != induction_.end()) {
870 auto loop_it = it->second.find(instruction);
871 if (loop_it != it->second.end()) {
872 return loop_it->second;
873 }
Aart Bik30efb4e2015-07-30 12:14:31 -0700874 }
Mingyao Yang4b467ed2015-11-19 17:04:22 -0800875 if (loop->IsDefinedOutOfTheLoop(instruction)) {
Aart Bik471a2032015-09-04 18:22:11 -0700876 InductionInfo* info = CreateInvariantFetch(instruction);
Aart Bike609b7c2015-08-27 13:46:58 -0700877 AssignInfo(loop, instruction, info);
878 return info;
879 }
880 return nullptr;
Aart Bik30efb4e2015-07-30 12:14:31 -0700881}
882
Aart Bikd14c5952015-09-08 15:25:15 -0700883HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::CreateConstant(int64_t value,
884 Primitive::Type type) {
885 if (type == Primitive::kPrimInt) {
886 return CreateInvariantFetch(graph_->GetIntConstant(value));
887 }
888 DCHECK_EQ(type, Primitive::kPrimLong);
889 return CreateInvariantFetch(graph_->GetLongConstant(value));
890}
891
Aart Bik471a2032015-09-04 18:22:11 -0700892HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::CreateSimplifiedInvariant(
893 InductionOp op,
894 InductionInfo* a,
895 InductionInfo* b) {
896 // Perform some light-weight simplifications during construction of a new invariant.
897 // This often safes memory and yields a more concise representation of the induction.
898 // More exhaustive simplifications are done by later phases once induction nodes are
899 // translated back into HIR code (e.g. by loop optimizations or BCE).
900 int64_t value = -1;
Aart Bik97412c922016-02-19 20:14:38 -0800901 if (IsExact(a, &value)) {
Aart Bik471a2032015-09-04 18:22:11 -0700902 if (value == 0) {
Aart Bik7dc96932016-10-12 10:01:05 -0700903 // Simplify 0 + b = b, 0 ^ b = b, 0 * b = 0.
904 if (op == kAdd || op == kXor) {
Aart Bik471a2032015-09-04 18:22:11 -0700905 return b;
906 } else if (op == kMul) {
907 return a;
908 }
Aart Bikd14c5952015-09-08 15:25:15 -0700909 } else if (op == kMul) {
910 // Simplify 1 * b = b, -1 * b = -b
911 if (value == 1) {
912 return b;
913 } else if (value == -1) {
Aart Bik7d57d7f2015-12-09 14:39:48 -0800914 return CreateSimplifiedInvariant(kNeg, nullptr, b);
Aart Bikd14c5952015-09-08 15:25:15 -0700915 }
Aart Bik471a2032015-09-04 18:22:11 -0700916 }
917 }
Aart Bik97412c922016-02-19 20:14:38 -0800918 if (IsExact(b, &value)) {
Aart Bik471a2032015-09-04 18:22:11 -0700919 if (value == 0) {
Aart Bik7dc96932016-10-12 10:01:05 -0700920 // Simplify a + 0 = a, a - 0 = a, a ^ 0 = a, a * 0 = 0, -0 = 0.
921 if (op == kAdd || op == kSub || op == kXor) {
Aart Bik471a2032015-09-04 18:22:11 -0700922 return a;
923 } else if (op == kMul || op == kNeg) {
924 return b;
925 }
Aart Bikd14c5952015-09-08 15:25:15 -0700926 } else if (op == kMul || op == kDiv) {
927 // Simplify a * 1 = a, a / 1 = a, a * -1 = -a, a / -1 = -a
928 if (value == 1) {
929 return a;
930 } else if (value == -1) {
Aart Bik7d57d7f2015-12-09 14:39:48 -0800931 return CreateSimplifiedInvariant(kNeg, nullptr, a);
Aart Bikd14c5952015-09-08 15:25:15 -0700932 }
Aart Bik471a2032015-09-04 18:22:11 -0700933 }
934 } else if (b->operation == kNeg) {
Aart Bikd14c5952015-09-08 15:25:15 -0700935 // Simplify a + (-b) = a - b, a - (-b) = a + b, -(-b) = b.
936 if (op == kAdd) {
Aart Bik7d57d7f2015-12-09 14:39:48 -0800937 return CreateSimplifiedInvariant(kSub, a, b->op_b);
Aart Bikd14c5952015-09-08 15:25:15 -0700938 } else if (op == kSub) {
Aart Bik7d57d7f2015-12-09 14:39:48 -0800939 return CreateSimplifiedInvariant(kAdd, a, b->op_b);
Aart Bikd14c5952015-09-08 15:25:15 -0700940 } else if (op == kNeg) {
941 return b->op_b;
Aart Bik471a2032015-09-04 18:22:11 -0700942 }
Aart Bik7d57d7f2015-12-09 14:39:48 -0800943 } else if (b->operation == kSub) {
944 // Simplify - (a - b) = b - a.
945 if (op == kNeg) {
946 return CreateSimplifiedInvariant(kSub, b->op_b, b->op_a);
947 }
Aart Bik471a2032015-09-04 18:22:11 -0700948 }
Aart Bik0d345cf2016-03-16 10:49:38 -0700949 return new (graph_->GetArena()) InductionInfo(kInvariant, op, a, b, nullptr, b->type);
Aart Bik471a2032015-09-04 18:22:11 -0700950}
951
Aart Bikcc42be02016-10-20 16:14:16 -0700952
953void HInductionVarAnalysis::AssignCycle(HPhi* phi) {
954 ArenaSet<HInstruction*>* set = &cycles_.Put(phi, ArenaSet<HInstruction*>(
955 graph_->GetArena()->Adapter(kArenaAllocInductionVarAnalysis)))->second;
956 for (HInstruction* i : scc_) {
957 set->insert(i);
958 }
959}
960
961ArenaSet<HInstruction*>* HInductionVarAnalysis::LookupCycle(HPhi* phi) {
962 auto it = cycles_.find(phi);
963 if (it != cycles_.end()) {
964 return &it->second;
965 }
966 return nullptr;
967}
968
Aart Bik97412c922016-02-19 20:14:38 -0800969bool HInductionVarAnalysis::IsExact(InductionInfo* info, int64_t* value) {
970 return InductionVarRange(this).IsConstant(info, InductionVarRange::kExact, value);
971}
972
973bool HInductionVarAnalysis::IsAtMost(InductionInfo* info, int64_t* value) {
974 return InductionVarRange(this).IsConstant(info, InductionVarRange::kAtMost, value);
975}
976
977bool HInductionVarAnalysis::IsAtLeast(InductionInfo* info, int64_t* value) {
978 return InductionVarRange(this).IsConstant(info, InductionVarRange::kAtLeast, value);
Aart Bik7d57d7f2015-12-09 14:39:48 -0800979}
980
Aart Bik30efb4e2015-07-30 12:14:31 -0700981bool HInductionVarAnalysis::InductionEqual(InductionInfo* info1,
982 InductionInfo* info2) {
983 // Test structural equality only, without accounting for simplifications.
984 if (info1 != nullptr && info2 != nullptr) {
985 return
986 info1->induction_class == info2->induction_class &&
987 info1->operation == info2->operation &&
988 info1->fetch == info2->fetch &&
Aart Bik78296912016-03-25 13:14:53 -0700989 info1->type == info2->type &&
Aart Bik30efb4e2015-07-30 12:14:31 -0700990 InductionEqual(info1->op_a, info2->op_a) &&
991 InductionEqual(info1->op_b, info2->op_b);
992 }
993 // Otherwise only two nullptrs are considered equal.
994 return info1 == info2;
995}
996
997std::string HInductionVarAnalysis::InductionToString(InductionInfo* info) {
998 if (info != nullptr) {
999 if (info->induction_class == kInvariant) {
1000 std::string inv = "(";
1001 inv += InductionToString(info->op_a);
1002 switch (info->operation) {
Aart Bik22f05872015-10-27 15:56:28 -07001003 case kNop: inv += " @ "; break;
1004 case kAdd: inv += " + "; break;
Aart Bik30efb4e2015-07-30 12:14:31 -07001005 case kSub:
Aart Bik22f05872015-10-27 15:56:28 -07001006 case kNeg: inv += " - "; break;
1007 case kMul: inv += " * "; break;
1008 case kDiv: inv += " / "; break;
Aart Bik7dc96932016-10-12 10:01:05 -07001009 case kXor: inv += " ^ "; break;
Aart Bik22f05872015-10-27 15:56:28 -07001010 case kLT: inv += " < "; break;
1011 case kLE: inv += " <= "; break;
1012 case kGT: inv += " > "; break;
1013 case kGE: inv += " >= "; break;
Aart Bik30efb4e2015-07-30 12:14:31 -07001014 case kFetch:
Aart Bike609b7c2015-08-27 13:46:58 -07001015 DCHECK(info->fetch);
Aart Bik7d57d7f2015-12-09 14:39:48 -08001016 if (info->fetch->IsIntConstant()) {
1017 inv += std::to_string(info->fetch->AsIntConstant()->GetValue());
1018 } else if (info->fetch->IsLongConstant()) {
1019 inv += std::to_string(info->fetch->AsLongConstant()->GetValue());
Aart Bik471a2032015-09-04 18:22:11 -07001020 } else {
1021 inv += std::to_string(info->fetch->GetId()) + ":" + info->fetch->DebugName();
1022 }
Aart Bik30efb4e2015-07-30 12:14:31 -07001023 break;
Aart Bik22f05872015-10-27 15:56:28 -07001024 case kTripCountInLoop: inv += " (TC-loop) "; break;
1025 case kTripCountInBody: inv += " (TC-body) "; break;
1026 case kTripCountInLoopUnsafe: inv += " (TC-loop-unsafe) "; break;
1027 case kTripCountInBodyUnsafe: inv += " (TC-body-unsafe) "; break;
Aart Bik30efb4e2015-07-30 12:14:31 -07001028 }
1029 inv += InductionToString(info->op_b);
Aart Bik0d345cf2016-03-16 10:49:38 -07001030 inv += ")";
1031 return inv;
Aart Bik30efb4e2015-07-30 12:14:31 -07001032 } else {
Aart Bike609b7c2015-08-27 13:46:58 -07001033 DCHECK(info->operation == kNop);
Aart Bik30efb4e2015-07-30 12:14:31 -07001034 if (info->induction_class == kLinear) {
1035 return "(" + InductionToString(info->op_a) + " * i + " +
Aart Bik0d345cf2016-03-16 10:49:38 -07001036 InductionToString(info->op_b) + "):" +
1037 Primitive::PrettyDescriptor(info->type);
Aart Bik30efb4e2015-07-30 12:14:31 -07001038 } else if (info->induction_class == kWrapAround) {
1039 return "wrap(" + InductionToString(info->op_a) + ", " +
Aart Bik0d345cf2016-03-16 10:49:38 -07001040 InductionToString(info->op_b) + "):" +
1041 Primitive::PrettyDescriptor(info->type);
Aart Bik30efb4e2015-07-30 12:14:31 -07001042 } else if (info->induction_class == kPeriodic) {
1043 return "periodic(" + InductionToString(info->op_a) + ", " +
Aart Bik0d345cf2016-03-16 10:49:38 -07001044 InductionToString(info->op_b) + "):" +
1045 Primitive::PrettyDescriptor(info->type);
Aart Bik30efb4e2015-07-30 12:14:31 -07001046 }
1047 }
1048 }
1049 return "";
1050}
1051
1052} // namespace art