blob: 37f2d79536ea015b45b9d58e773d77a05279acd7 [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
26 * classification, the lexicographically first entry-phi is rotated to the front.
27 */
28static void RotateEntryPhiFirst(HLoopInformation* loop,
29 ArenaVector<HInstruction*>* scc,
30 ArenaVector<HInstruction*>* new_scc) {
31 // Find very first entry-phi.
32 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
44 // If found, bring that entry-phi to front.
45 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 Bik30efb4e2015-07-30 12:14:31 -070056//
57// Class methods.
58//
59
60HInductionVarAnalysis::HInductionVarAnalysis(HGraph* graph)
61 : HOptimization(graph, kInductionPassName),
62 global_depth_(0),
Vladimir Marko5233f932015-09-29 19:01:15 +010063 stack_(graph->GetArena()->Adapter(kArenaAllocInductionVarAnalysis)),
64 scc_(graph->GetArena()->Adapter(kArenaAllocInductionVarAnalysis)),
65 map_(std::less<HInstruction*>(),
66 graph->GetArena()->Adapter(kArenaAllocInductionVarAnalysis)),
67 cycle_(std::less<HInstruction*>(),
68 graph->GetArena()->Adapter(kArenaAllocInductionVarAnalysis)),
69 induction_(std::less<HLoopInformation*>(),
70 graph->GetArena()->Adapter(kArenaAllocInductionVarAnalysis)) {
Aart Bik30efb4e2015-07-30 12:14:31 -070071}
72
73void HInductionVarAnalysis::Run() {
Aart Bik7d57d7f2015-12-09 14:39:48 -080074 // Detects sequence variables (generalized induction variables) during an outer to inner
75 // traversal of all loops using Gerlek's algorithm. The order is important to enable
76 // range analysis on outer loop while visiting inner loops.
77 for (HReversePostOrderIterator it_graph(*graph_); !it_graph.Done(); it_graph.Advance()) {
Aart Bik30efb4e2015-07-30 12:14:31 -070078 HBasicBlock* graph_block = it_graph.Current();
Nicolas Geoffray15bd2282016-01-05 15:55:41 +000079 // Don't analyze irreducible loops.
80 // TODO(ajcbik): could/should we remove this restriction?
81 if (graph_block->IsLoopHeader() && !graph_block->GetLoopInformation()->IsIrreducible()) {
Aart Bik30efb4e2015-07-30 12:14:31 -070082 VisitLoop(graph_block->GetLoopInformation());
83 }
84 }
85}
86
87void HInductionVarAnalysis::VisitLoop(HLoopInformation* loop) {
88 // Find strongly connected components (SSCs) in the SSA graph of this loop using Tarjan's
89 // algorithm. Due to the descendant-first nature, classification happens "on-demand".
90 global_depth_ = 0;
Aart Bike609b7c2015-08-27 13:46:58 -070091 DCHECK(stack_.empty());
Aart Bik30efb4e2015-07-30 12:14:31 -070092 map_.clear();
93
94 for (HBlocksInLoopIterator it_loop(*loop); !it_loop.Done(); it_loop.Advance()) {
95 HBasicBlock* loop_block = it_loop.Current();
Aart Bike609b7c2015-08-27 13:46:58 -070096 DCHECK(loop_block->IsInLoop());
Aart Bik30efb4e2015-07-30 12:14:31 -070097 if (loop_block->GetLoopInformation() != loop) {
98 continue; // Inner loops already visited.
99 }
100 // Visit phi-operations and instructions.
101 for (HInstructionIterator it(loop_block->GetPhis()); !it.Done(); it.Advance()) {
102 HInstruction* instruction = it.Current();
Aart Bike609b7c2015-08-27 13:46:58 -0700103 if (!IsVisitedNode(instruction)) {
Aart Bik30efb4e2015-07-30 12:14:31 -0700104 VisitNode(loop, instruction);
105 }
106 }
107 for (HInstructionIterator it(loop_block->GetInstructions()); !it.Done(); it.Advance()) {
108 HInstruction* instruction = it.Current();
Aart Bike609b7c2015-08-27 13:46:58 -0700109 if (!IsVisitedNode(instruction)) {
Aart Bik30efb4e2015-07-30 12:14:31 -0700110 VisitNode(loop, instruction);
111 }
112 }
113 }
114
Aart Bike609b7c2015-08-27 13:46:58 -0700115 DCHECK(stack_.empty());
Aart Bik30efb4e2015-07-30 12:14:31 -0700116 map_.clear();
Aart Bikd14c5952015-09-08 15:25:15 -0700117
118 // Determine the loop's trip count.
119 VisitControl(loop);
Aart Bik30efb4e2015-07-30 12:14:31 -0700120}
121
122void HInductionVarAnalysis::VisitNode(HLoopInformation* loop, HInstruction* instruction) {
Aart Bik30efb4e2015-07-30 12:14:31 -0700123 const uint32_t d1 = ++global_depth_;
Aart Bike609b7c2015-08-27 13:46:58 -0700124 map_.Put(instruction, NodeInfo(d1));
Aart Bik30efb4e2015-07-30 12:14:31 -0700125 stack_.push_back(instruction);
126
127 // Visit all descendants.
128 uint32_t low = d1;
129 for (size_t i = 0, count = instruction->InputCount(); i < count; ++i) {
130 low = std::min(low, VisitDescendant(loop, instruction->InputAt(i)));
131 }
132
133 // Lower or found SCC?
134 if (low < d1) {
Aart Bike609b7c2015-08-27 13:46:58 -0700135 map_.find(instruction)->second.depth = low;
Aart Bik30efb4e2015-07-30 12:14:31 -0700136 } else {
137 scc_.clear();
138 cycle_.clear();
139
140 // Pop the stack to build the SCC for classification.
141 while (!stack_.empty()) {
142 HInstruction* x = stack_.back();
143 scc_.push_back(x);
144 stack_.pop_back();
Aart Bike609b7c2015-08-27 13:46:58 -0700145 map_.find(x)->second.done = true;
Aart Bik30efb4e2015-07-30 12:14:31 -0700146 if (x == instruction) {
147 break;
148 }
149 }
150
151 // Classify the SCC.
Aart Bikf475bee2015-09-16 12:50:25 -0700152 if (scc_.size() == 1 && !scc_[0]->IsLoopHeaderPhi()) {
Aart Bik30efb4e2015-07-30 12:14:31 -0700153 ClassifyTrivial(loop, scc_[0]);
154 } else {
155 ClassifyNonTrivial(loop);
156 }
157
158 scc_.clear();
159 cycle_.clear();
160 }
161}
162
163uint32_t HInductionVarAnalysis::VisitDescendant(HLoopInformation* loop, HInstruction* instruction) {
164 // If the definition is either outside the loop (loop invariant entry value)
165 // or assigned in inner loop (inner exit value), the traversal stops.
166 HLoopInformation* otherLoop = instruction->GetBlock()->GetLoopInformation();
167 if (otherLoop != loop) {
168 return global_depth_;
169 }
170
171 // Inspect descendant node.
Aart Bike609b7c2015-08-27 13:46:58 -0700172 if (!IsVisitedNode(instruction)) {
Aart Bik30efb4e2015-07-30 12:14:31 -0700173 VisitNode(loop, instruction);
Aart Bike609b7c2015-08-27 13:46:58 -0700174 return map_.find(instruction)->second.depth;
Aart Bik30efb4e2015-07-30 12:14:31 -0700175 } else {
Aart Bike609b7c2015-08-27 13:46:58 -0700176 auto it = map_.find(instruction);
Aart Bik30efb4e2015-07-30 12:14:31 -0700177 return it->second.done ? global_depth_ : it->second.depth;
178 }
179}
180
181void HInductionVarAnalysis::ClassifyTrivial(HLoopInformation* loop, HInstruction* instruction) {
182 InductionInfo* info = nullptr;
183 if (instruction->IsPhi()) {
Aart Bikf475bee2015-09-16 12:50:25 -0700184 info = TransferPhi(loop, instruction, /* input_index */ 0);
Aart Bik30efb4e2015-07-30 12:14:31 -0700185 } else if (instruction->IsAdd()) {
186 info = TransferAddSub(LookupInfo(loop, instruction->InputAt(0)),
187 LookupInfo(loop, instruction->InputAt(1)), kAdd);
188 } else if (instruction->IsSub()) {
189 info = TransferAddSub(LookupInfo(loop, instruction->InputAt(0)),
190 LookupInfo(loop, instruction->InputAt(1)), kSub);
191 } else if (instruction->IsMul()) {
192 info = TransferMul(LookupInfo(loop, instruction->InputAt(0)),
193 LookupInfo(loop, instruction->InputAt(1)));
Aart Bike609b7c2015-08-27 13:46:58 -0700194 } else if (instruction->IsShl()) {
195 info = TransferShl(LookupInfo(loop, instruction->InputAt(0)),
196 LookupInfo(loop, instruction->InputAt(1)),
197 instruction->InputAt(0)->GetType());
Aart Bik30efb4e2015-07-30 12:14:31 -0700198 } else if (instruction->IsNeg()) {
199 info = TransferNeg(LookupInfo(loop, instruction->InputAt(0)));
Aart Bike609b7c2015-08-27 13:46:58 -0700200 } else if (instruction->IsBoundsCheck()) {
201 info = LookupInfo(loop, instruction->InputAt(0)); // Pass-through.
202 } else if (instruction->IsTypeConversion()) {
203 HTypeConversion* conversion = instruction->AsTypeConversion();
204 // TODO: accept different conversion scenarios.
205 if (conversion->GetResultType() == conversion->GetInputType()) {
206 info = LookupInfo(loop, conversion->GetInput());
207 }
Aart Bik30efb4e2015-07-30 12:14:31 -0700208 }
209
210 // Successfully classified?
211 if (info != nullptr) {
212 AssignInfo(loop, instruction, info);
213 }
214}
215
216void HInductionVarAnalysis::ClassifyNonTrivial(HLoopInformation* loop) {
217 const size_t size = scc_.size();
Aart Bike609b7c2015-08-27 13:46:58 -0700218 DCHECK_GE(size, 1u);
Aart Bik22af3be2015-09-10 12:50:58 -0700219
220 // Rotate proper entry-phi to front.
221 if (size > 1) {
Vladimir Marko5233f932015-09-29 19:01:15 +0100222 ArenaVector<HInstruction*> other(graph_->GetArena()->Adapter(kArenaAllocInductionVarAnalysis));
Aart Bik22af3be2015-09-10 12:50:58 -0700223 RotateEntryPhiFirst(loop, &scc_, &other);
224 }
225
Aart Bikf475bee2015-09-16 12:50:25 -0700226 // Analyze from entry-phi onwards.
Aart Bik22af3be2015-09-10 12:50:58 -0700227 HInstruction* phi = scc_[0];
Aart Bikf475bee2015-09-16 12:50:25 -0700228 if (!phi->IsLoopHeaderPhi()) {
Aart Bik30efb4e2015-07-30 12:14:31 -0700229 return;
230 }
Aart Bikf475bee2015-09-16 12:50:25 -0700231
232 // External link should be loop invariant.
233 InductionInfo* initial = LookupInfo(loop, phi->InputAt(0));
Aart Bik30efb4e2015-07-30 12:14:31 -0700234 if (initial == nullptr || initial->induction_class != kInvariant) {
235 return;
236 }
237
Aart Bikf475bee2015-09-16 12:50:25 -0700238 // Singleton is wrap-around induction if all internal links have the same meaning.
Aart Bik30efb4e2015-07-30 12:14:31 -0700239 if (size == 1) {
Aart Bikf475bee2015-09-16 12:50:25 -0700240 InductionInfo* update = TransferPhi(loop, phi, /* input_index */ 1);
Aart Bik30efb4e2015-07-30 12:14:31 -0700241 if (update != nullptr) {
Aart Bik471a2032015-09-04 18:22:11 -0700242 AssignInfo(loop, phi, CreateInduction(kWrapAround, initial, update));
Aart Bik30efb4e2015-07-30 12:14:31 -0700243 }
244 return;
245 }
246
247 // Inspect remainder of the cycle that resides in scc_. The cycle_ mapping assigns
Aart Bike609b7c2015-08-27 13:46:58 -0700248 // temporary meaning to its nodes, seeded from the phi instruction and back.
Aart Bik22af3be2015-09-10 12:50:58 -0700249 for (size_t i = 1; i < size; i++) {
Aart Bike609b7c2015-08-27 13:46:58 -0700250 HInstruction* instruction = scc_[i];
Aart Bik30efb4e2015-07-30 12:14:31 -0700251 InductionInfo* update = nullptr;
Aart Bike609b7c2015-08-27 13:46:58 -0700252 if (instruction->IsPhi()) {
Aart Bikf475bee2015-09-16 12:50:25 -0700253 update = SolvePhiAllInputs(loop, phi, instruction);
Aart Bike609b7c2015-08-27 13:46:58 -0700254 } else if (instruction->IsAdd()) {
255 update = SolveAddSub(
256 loop, phi, instruction, instruction->InputAt(0), instruction->InputAt(1), kAdd, true);
257 } else if (instruction->IsSub()) {
258 update = SolveAddSub(
259 loop, phi, instruction, instruction->InputAt(0), instruction->InputAt(1), kSub, true);
Aart Bik30efb4e2015-07-30 12:14:31 -0700260 }
261 if (update == nullptr) {
262 return;
263 }
Aart Bike609b7c2015-08-27 13:46:58 -0700264 cycle_.Put(instruction, update);
Aart Bik30efb4e2015-07-30 12:14:31 -0700265 }
266
Aart Bikf475bee2015-09-16 12:50:25 -0700267 // Success if all internal links received the same temporary meaning.
268 InductionInfo* induction = SolvePhi(phi, /* input_index */ 1);
269 if (induction != nullptr) {
Aart Bike609b7c2015-08-27 13:46:58 -0700270 switch (induction->induction_class) {
271 case kInvariant:
Aart Bik22af3be2015-09-10 12:50:58 -0700272 // Classify first phi and then the rest of the cycle "on-demand".
273 // Statements are scanned in order.
Aart Bik471a2032015-09-04 18:22:11 -0700274 AssignInfo(loop, phi, CreateInduction(kLinear, induction, initial));
Aart Bik22af3be2015-09-10 12:50:58 -0700275 for (size_t i = 1; i < size; i++) {
Aart Bike609b7c2015-08-27 13:46:58 -0700276 ClassifyTrivial(loop, scc_[i]);
277 }
278 break;
279 case kPeriodic:
Aart Bik22af3be2015-09-10 12:50:58 -0700280 // Classify all elements in the cycle with the found periodic induction while
281 // rotating each first element to the end. Lastly, phi is classified.
282 // Statements are scanned in reverse order.
283 for (size_t i = size - 1; i >= 1; i--) {
284 AssignInfo(loop, scc_[i], induction);
Aart Bike609b7c2015-08-27 13:46:58 -0700285 induction = RotatePeriodicInduction(induction->op_b, induction->op_a);
286 }
287 AssignInfo(loop, phi, induction);
288 break;
289 default:
290 break;
Aart Bik30efb4e2015-07-30 12:14:31 -0700291 }
292 }
293}
294
Aart Bike609b7c2015-08-27 13:46:58 -0700295HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::RotatePeriodicInduction(
296 InductionInfo* induction,
297 InductionInfo* last) {
298 // Rotates a periodic induction of the form
299 // (a, b, c, d, e)
300 // into
301 // (b, c, d, e, a)
302 // in preparation of assigning this to the previous variable in the sequence.
303 if (induction->induction_class == kInvariant) {
Aart Bik471a2032015-09-04 18:22:11 -0700304 return CreateInduction(kPeriodic, induction, last);
Aart Bike609b7c2015-08-27 13:46:58 -0700305 }
Aart Bik471a2032015-09-04 18:22:11 -0700306 return CreateInduction(kPeriodic, induction->op_a, RotatePeriodicInduction(induction->op_b, last));
Aart Bike609b7c2015-08-27 13:46:58 -0700307}
308
Aart Bikf475bee2015-09-16 12:50:25 -0700309HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::TransferPhi(HLoopInformation* loop,
310 HInstruction* phi,
311 size_t input_index) {
312 // Match all phi inputs from input_index onwards exactly.
313 const size_t count = phi->InputCount();
314 DCHECK_LT(input_index, count);
315 InductionInfo* a = LookupInfo(loop, phi->InputAt(input_index));
316 for (size_t i = input_index + 1; i < count; i++) {
317 InductionInfo* b = LookupInfo(loop, phi->InputAt(i));
318 if (!InductionEqual(a, b)) {
319 return nullptr;
320 }
Aart Bik30efb4e2015-07-30 12:14:31 -0700321 }
Aart Bikf475bee2015-09-16 12:50:25 -0700322 return a;
Aart Bik30efb4e2015-07-30 12:14:31 -0700323}
324
325HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::TransferAddSub(InductionInfo* a,
326 InductionInfo* b,
327 InductionOp op) {
Aart Bike609b7c2015-08-27 13:46:58 -0700328 // Transfer over an addition or subtraction: any invariant, linear, wrap-around, or periodic
329 // can be combined with an invariant to yield a similar result. Even two linear inputs can
330 // be combined. All other combinations fail, however.
Aart Bik30efb4e2015-07-30 12:14:31 -0700331 if (a != nullptr && b != nullptr) {
332 if (a->induction_class == kInvariant && b->induction_class == kInvariant) {
Aart Bik471a2032015-09-04 18:22:11 -0700333 return CreateInvariantOp(op, a, b);
Aart Bik30efb4e2015-07-30 12:14:31 -0700334 } else if (a->induction_class == kLinear && b->induction_class == kLinear) {
Aart Bik471a2032015-09-04 18:22:11 -0700335 return CreateInduction(
Aart Bike609b7c2015-08-27 13:46:58 -0700336 kLinear, TransferAddSub(a->op_a, b->op_a, op), TransferAddSub(a->op_b, b->op_b, op));
337 } else if (a->induction_class == kInvariant) {
338 InductionInfo* new_a = b->op_a;
339 InductionInfo* new_b = TransferAddSub(a, b->op_b, op);
340 if (b->induction_class != kLinear) {
341 DCHECK(b->induction_class == kWrapAround || b->induction_class == kPeriodic);
342 new_a = TransferAddSub(a, new_a, op);
343 } else if (op == kSub) { // Negation required.
344 new_a = TransferNeg(new_a);
345 }
Aart Bik471a2032015-09-04 18:22:11 -0700346 return CreateInduction(b->induction_class, new_a, new_b);
Aart Bike609b7c2015-08-27 13:46:58 -0700347 } else if (b->induction_class == kInvariant) {
348 InductionInfo* new_a = a->op_a;
349 InductionInfo* new_b = TransferAddSub(a->op_b, b, op);
350 if (a->induction_class != kLinear) {
351 DCHECK(a->induction_class == kWrapAround || a->induction_class == kPeriodic);
352 new_a = TransferAddSub(new_a, b, op);
353 }
Aart Bik471a2032015-09-04 18:22:11 -0700354 return CreateInduction(a->induction_class, new_a, new_b);
Aart Bik30efb4e2015-07-30 12:14:31 -0700355 }
356 }
357 return nullptr;
358}
359
360HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::TransferMul(InductionInfo* a,
361 InductionInfo* b) {
Aart Bike609b7c2015-08-27 13:46:58 -0700362 // Transfer over a multiplication: any invariant, linear, wrap-around, or periodic
363 // can be multiplied with an invariant to yield a similar but multiplied result.
364 // Two non-invariant inputs cannot be multiplied, however.
Aart Bik30efb4e2015-07-30 12:14:31 -0700365 if (a != nullptr && b != nullptr) {
366 if (a->induction_class == kInvariant && b->induction_class == kInvariant) {
Aart Bik471a2032015-09-04 18:22:11 -0700367 return CreateInvariantOp(kMul, a, b);
Aart Bike609b7c2015-08-27 13:46:58 -0700368 } else if (a->induction_class == kInvariant) {
Aart Bik471a2032015-09-04 18:22:11 -0700369 return CreateInduction(b->induction_class, TransferMul(a, b->op_a), TransferMul(a, b->op_b));
Aart Bike609b7c2015-08-27 13:46:58 -0700370 } else if (b->induction_class == kInvariant) {
Aart Bik471a2032015-09-04 18:22:11 -0700371 return CreateInduction(a->induction_class, TransferMul(a->op_a, b), TransferMul(a->op_b, b));
Aart Bike609b7c2015-08-27 13:46:58 -0700372 }
373 }
374 return nullptr;
375}
376
377HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::TransferShl(InductionInfo* a,
378 InductionInfo* b,
Aart Bikd14c5952015-09-08 15:25:15 -0700379 Primitive::Type type) {
Aart Bike609b7c2015-08-27 13:46:58 -0700380 // Transfer over a shift left: treat shift by restricted constant as equivalent multiplication.
Aart Bik471a2032015-09-04 18:22:11 -0700381 int64_t value = -1;
382 if (a != nullptr && IsIntAndGet(b, &value)) {
Aart Bike609b7c2015-08-27 13:46:58 -0700383 // Obtain the constant needed for the multiplication. This yields an existing instruction
384 // if the constants is already there. Otherwise, this has a side effect on the HIR.
385 // The restriction on the shift factor avoids generating a negative constant
386 // (viz. 1 << 31 and 1L << 63 set the sign bit). The code assumes that generalization
387 // for shift factors outside [0,32) and [0,64) ranges is done by earlier simplification.
Aart Bikd14c5952015-09-08 15:25:15 -0700388 if ((type == Primitive::kPrimInt && 0 <= value && value < 31) ||
389 (type == Primitive::kPrimLong && 0 <= value && value < 63)) {
390 return TransferMul(a, CreateConstant(1 << value, type));
Aart Bik30efb4e2015-07-30 12:14:31 -0700391 }
392 }
393 return nullptr;
394}
395
396HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::TransferNeg(InductionInfo* a) {
Aart Bike609b7c2015-08-27 13:46:58 -0700397 // Transfer over a unary negation: an invariant, linear, wrap-around, or periodic input
398 // yields a similar but negated induction as result.
Aart Bik30efb4e2015-07-30 12:14:31 -0700399 if (a != nullptr) {
400 if (a->induction_class == kInvariant) {
Aart Bik471a2032015-09-04 18:22:11 -0700401 return CreateInvariantOp(kNeg, nullptr, a);
Aart Bik30efb4e2015-07-30 12:14:31 -0700402 }
Aart Bik471a2032015-09-04 18:22:11 -0700403 return CreateInduction(a->induction_class, TransferNeg(a->op_a), TransferNeg(a->op_b));
Aart Bik30efb4e2015-07-30 12:14:31 -0700404 }
405 return nullptr;
406}
407
Aart Bikf475bee2015-09-16 12:50:25 -0700408HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::SolvePhi(HInstruction* phi,
409 size_t input_index) {
410 // Match all phi inputs from input_index onwards exactly.
411 const size_t count = phi->InputCount();
412 DCHECK_LT(input_index, count);
413 auto ita = cycle_.find(phi->InputAt(input_index));
Aart Bik30efb4e2015-07-30 12:14:31 -0700414 if (ita != cycle_.end()) {
Aart Bikf475bee2015-09-16 12:50:25 -0700415 for (size_t i = input_index + 1; i < count; i++) {
416 auto itb = cycle_.find(phi->InputAt(i));
417 if (itb == cycle_.end() ||
418 !HInductionVarAnalysis::InductionEqual(ita->second, itb->second)) {
Aart Bik30efb4e2015-07-30 12:14:31 -0700419 return nullptr;
420 }
421 }
Aart Bikf475bee2015-09-16 12:50:25 -0700422 return ita->second;
423 }
424 return nullptr;
425}
426
427HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::SolvePhiAllInputs(
428 HLoopInformation* loop,
429 HInstruction* entry_phi,
430 HInstruction* phi) {
431 // Match all phi inputs.
432 InductionInfo* match = SolvePhi(phi, /* input_index */ 0);
433 if (match != nullptr) {
434 return match;
Aart Bik30efb4e2015-07-30 12:14:31 -0700435 }
Aart Bik30efb4e2015-07-30 12:14:31 -0700436
Aart Bikf475bee2015-09-16 12:50:25 -0700437 // Otherwise, try to solve for a periodic seeded from phi onward.
438 // Only tight multi-statement cycles are considered in order to
439 // simplify rotating the periodic during the final classification.
440 if (phi->IsLoopHeaderPhi() && phi->InputCount() == 2) {
441 InductionInfo* a = LookupInfo(loop, phi->InputAt(0));
Aart Bike609b7c2015-08-27 13:46:58 -0700442 if (a != nullptr && a->induction_class == kInvariant) {
Aart Bikf475bee2015-09-16 12:50:25 -0700443 if (phi->InputAt(1) == entry_phi) {
444 InductionInfo* initial = LookupInfo(loop, entry_phi->InputAt(0));
Aart Bik471a2032015-09-04 18:22:11 -0700445 return CreateInduction(kPeriodic, a, initial);
Aart Bike609b7c2015-08-27 13:46:58 -0700446 }
Aart Bikf475bee2015-09-16 12:50:25 -0700447 InductionInfo* b = SolvePhi(phi, /* input_index */ 1);
448 if (b != nullptr && b->induction_class == kPeriodic) {
449 return CreateInduction(kPeriodic, a, b);
Aart Bik30efb4e2015-07-30 12:14:31 -0700450 }
451 }
452 }
Aart Bik30efb4e2015-07-30 12:14:31 -0700453 return nullptr;
454}
455
Aart Bike609b7c2015-08-27 13:46:58 -0700456HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::SolveAddSub(HLoopInformation* loop,
Aart Bikf475bee2015-09-16 12:50:25 -0700457 HInstruction* entry_phi,
Aart Bike609b7c2015-08-27 13:46:58 -0700458 HInstruction* instruction,
459 HInstruction* x,
460 HInstruction* y,
461 InductionOp op,
462 bool is_first_call) {
463 // Solve within a cycle over an addition or subtraction: adding or subtracting an
464 // invariant value, seeded from phi, keeps adding to the stride of the induction.
465 InductionInfo* b = LookupInfo(loop, y);
466 if (b != nullptr && b->induction_class == kInvariant) {
Aart Bikf475bee2015-09-16 12:50:25 -0700467 if (x == entry_phi) {
Aart Bik471a2032015-09-04 18:22:11 -0700468 return (op == kAdd) ? b : CreateInvariantOp(kNeg, nullptr, b);
Aart Bike609b7c2015-08-27 13:46:58 -0700469 }
470 auto it = cycle_.find(x);
471 if (it != cycle_.end()) {
472 InductionInfo* a = it->second;
473 if (a->induction_class == kInvariant) {
Aart Bik471a2032015-09-04 18:22:11 -0700474 return CreateInvariantOp(op, a, b);
Aart Bike609b7c2015-08-27 13:46:58 -0700475 }
Aart Bik30efb4e2015-07-30 12:14:31 -0700476 }
477 }
Aart Bike609b7c2015-08-27 13:46:58 -0700478
479 // Try some alternatives before failing.
480 if (op == kAdd) {
481 // Try the other way around for an addition if considered for first time.
482 if (is_first_call) {
Aart Bikf475bee2015-09-16 12:50:25 -0700483 return SolveAddSub(loop, entry_phi, instruction, y, x, op, false);
Aart Bike609b7c2015-08-27 13:46:58 -0700484 }
485 } else if (op == kSub) {
Aart Bikf475bee2015-09-16 12:50:25 -0700486 // Solve within a tight cycle that is formed by exactly two instructions,
487 // one phi and one update, for a periodic idiom of the form k = c - k;
488 if (y == entry_phi && entry_phi->InputCount() == 2 && instruction == entry_phi->InputAt(1)) {
Aart Bike609b7c2015-08-27 13:46:58 -0700489 InductionInfo* a = LookupInfo(loop, x);
490 if (a != nullptr && a->induction_class == kInvariant) {
Aart Bikf475bee2015-09-16 12:50:25 -0700491 InductionInfo* initial = LookupInfo(loop, entry_phi->InputAt(0));
Aart Bik471a2032015-09-04 18:22:11 -0700492 return CreateInduction(kPeriodic, CreateInvariantOp(kSub, a, initial), initial);
Aart Bike609b7c2015-08-27 13:46:58 -0700493 }
494 }
495 }
496
Aart Bik30efb4e2015-07-30 12:14:31 -0700497 return nullptr;
498}
499
Aart Bikd14c5952015-09-08 15:25:15 -0700500void HInductionVarAnalysis::VisitControl(HLoopInformation* loop) {
501 HInstruction* control = loop->GetHeader()->GetLastInstruction();
502 if (control->IsIf()) {
503 HIf* ifs = control->AsIf();
504 HBasicBlock* if_true = ifs->IfTrueSuccessor();
505 HBasicBlock* if_false = ifs->IfFalseSuccessor();
506 HInstruction* if_expr = ifs->InputAt(0);
507 // Determine if loop has following structure in header.
508 // loop-header: ....
509 // if (condition) goto X
510 if (if_expr->IsCondition()) {
511 HCondition* condition = if_expr->AsCondition();
512 InductionInfo* a = LookupInfo(loop, condition->InputAt(0));
513 InductionInfo* b = LookupInfo(loop, condition->InputAt(1));
514 Primitive::Type type = condition->InputAt(0)->GetType();
515 // Determine if the loop control uses integral arithmetic and an if-exit (X outside) or an
516 // if-iterate (X inside), always expressed as if-iterate when passing into VisitCondition().
517 if (type != Primitive::kPrimInt && type != Primitive::kPrimLong) {
518 // Loop control is not 32/64-bit integral.
519 } else if (a == nullptr || b == nullptr) {
520 // Loop control is not a sequence.
521 } else if (if_true->GetLoopInformation() != loop && if_false->GetLoopInformation() == loop) {
522 VisitCondition(loop, a, b, type, condition->GetOppositeCondition());
523 } else if (if_true->GetLoopInformation() == loop && if_false->GetLoopInformation() != loop) {
524 VisitCondition(loop, a, b, type, condition->GetCondition());
525 }
526 }
527 }
528}
529
530void HInductionVarAnalysis::VisitCondition(HLoopInformation* loop,
531 InductionInfo* a,
532 InductionInfo* b,
533 Primitive::Type type,
534 IfCondition cmp) {
535 if (a->induction_class == kInvariant && b->induction_class == kLinear) {
Aart Bikf475bee2015-09-16 12:50:25 -0700536 // 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 -0700537 switch (cmp) {
538 case kCondLT: VisitCondition(loop, b, a, type, kCondGT); break;
539 case kCondLE: VisitCondition(loop, b, a, type, kCondGE); break;
540 case kCondGT: VisitCondition(loop, b, a, type, kCondLT); break;
541 case kCondGE: VisitCondition(loop, b, a, type, kCondLE); break;
Aart Bikf475bee2015-09-16 12:50:25 -0700542 case kCondNE: VisitCondition(loop, b, a, type, kCondNE); break;
Aart Bikd14c5952015-09-08 15:25:15 -0700543 default: break;
544 }
545 } else if (a->induction_class == kLinear && b->induction_class == kInvariant) {
Aart Bikf475bee2015-09-16 12:50:25 -0700546 // Analyze condition with induction at left-hand-side (e.g. i < U).
Aart Bik9401f532015-09-28 16:25:56 -0700547 InductionInfo* lower_expr = a->op_b;
548 InductionInfo* upper_expr = b;
Aart Bikd14c5952015-09-08 15:25:15 -0700549 InductionInfo* stride = a->op_a;
Aart Bik9401f532015-09-28 16:25:56 -0700550 int64_t stride_value = 0;
551 if (!IsIntAndGet(stride, &stride_value)) {
Aart Bikf475bee2015-09-16 12:50:25 -0700552 return;
553 }
Aart Bik9401f532015-09-28 16:25:56 -0700554 // Rewrite condition i != U into i < U or i > U if end condition is reached exactly.
555 if (cmp == kCondNE && ((stride_value == +1 && IsTaken(lower_expr, upper_expr, kCondLT)) ||
556 (stride_value == -1 && IsTaken(lower_expr, upper_expr, kCondGT)))) {
557 cmp = stride_value > 0 ? kCondLT : kCondGT;
Aart Bikd14c5952015-09-08 15:25:15 -0700558 }
Aart Bikf475bee2015-09-16 12:50:25 -0700559 // Normalize a linear loop control with a nonzero stride:
560 // stride > 0, either i < U or i <= U
561 // stride < 0, either i > U or i >= U
Aart Bikf475bee2015-09-16 12:50:25 -0700562 if ((stride_value > 0 && (cmp == kCondLT || cmp == kCondLE)) ||
563 (stride_value < 0 && (cmp == kCondGT || cmp == kCondGE))) {
Aart Bik9401f532015-09-28 16:25:56 -0700564 VisitTripCount(loop, lower_expr, upper_expr, stride, stride_value, type, cmp);
Aart Bikf475bee2015-09-16 12:50:25 -0700565 }
Aart Bikd14c5952015-09-08 15:25:15 -0700566 }
567}
568
569void HInductionVarAnalysis::VisitTripCount(HLoopInformation* loop,
Aart Bik9401f532015-09-28 16:25:56 -0700570 InductionInfo* lower_expr,
571 InductionInfo* upper_expr,
Aart Bikd14c5952015-09-08 15:25:15 -0700572 InductionInfo* stride,
Aart Bik9401f532015-09-28 16:25:56 -0700573 int64_t stride_value,
Aart Bikd14c5952015-09-08 15:25:15 -0700574 Primitive::Type type,
Aart Bikf475bee2015-09-16 12:50:25 -0700575 IfCondition cmp) {
Aart Bikd14c5952015-09-08 15:25:15 -0700576 // Any loop of the general form:
577 //
578 // for (i = L; i <= U; i += S) // S > 0
579 // or for (i = L; i >= U; i += S) // S < 0
580 // .. i ..
581 //
582 // can be normalized into:
583 //
584 // for (n = 0; n < TC; n++) // where TC = (U + S - L) / S
585 // .. L + S * n ..
586 //
Aart Bik9401f532015-09-28 16:25:56 -0700587 // taking the following into consideration:
Aart Bikd14c5952015-09-08 15:25:15 -0700588 //
Aart Bik9401f532015-09-28 16:25:56 -0700589 // (1) Using the same precision, the TC (trip-count) expression should be interpreted as
590 // an unsigned entity, for example, as in the following loop that uses the full range:
591 // for (int i = INT_MIN; i < INT_MAX; i++) // TC = UINT_MAX
592 // (2) The TC is only valid if the loop is taken, otherwise TC = 0, as in:
Aart Bik22f05872015-10-27 15:56:28 -0700593 // for (int i = 12; i < U; i++) // TC = 0 when U < 12
Aart Bik9401f532015-09-28 16:25:56 -0700594 // If this cannot be determined at compile-time, the TC is only valid within the
Aart Bik22f05872015-10-27 15:56:28 -0700595 // loop-body proper, not the loop-header unless enforced with an explicit taken-test.
Aart Bik9401f532015-09-28 16:25:56 -0700596 // (3) The TC is only valid if the loop is finite, otherwise TC has no value, as in:
597 // for (int i = 0; i <= U; i++) // TC = Inf when U = INT_MAX
598 // If this cannot be determined at compile-time, the TC is only valid when enforced
Aart Bik22f05872015-10-27 15:56:28 -0700599 // with an explicit finite-test.
Aart Bik9401f532015-09-28 16:25:56 -0700600 // (4) For loops which early-exits, the TC forms an upper bound, as in:
601 // for (int i = 0; i < 10 && ....; i++) // TC <= 10
Aart Bik22f05872015-10-27 15:56:28 -0700602 InductionInfo* trip_count = upper_expr;
Aart Bik9401f532015-09-28 16:25:56 -0700603 const bool is_taken = IsTaken(lower_expr, upper_expr, cmp);
604 const bool is_finite = IsFinite(upper_expr, stride_value, type, cmp);
605 const bool cancels = (cmp == kCondLT || cmp == kCondGT) && std::abs(stride_value) == 1;
Aart Bikd14c5952015-09-08 15:25:15 -0700606 if (!cancels) {
607 // Convert exclusive integral inequality into inclusive integral inequality,
608 // viz. condition i < U is i <= U - 1 and condition i > U is i >= U + 1.
Aart Bikf475bee2015-09-16 12:50:25 -0700609 if (cmp == kCondLT) {
Aart Bik22f05872015-10-27 15:56:28 -0700610 trip_count = CreateInvariantOp(kSub, trip_count, CreateConstant(1, type));
Aart Bikf475bee2015-09-16 12:50:25 -0700611 } else if (cmp == kCondGT) {
Aart Bik22f05872015-10-27 15:56:28 -0700612 trip_count = CreateInvariantOp(kAdd, trip_count, CreateConstant(1, type));
Aart Bikd14c5952015-09-08 15:25:15 -0700613 }
614 // Compensate for stride.
Aart Bik22f05872015-10-27 15:56:28 -0700615 trip_count = CreateInvariantOp(kAdd, trip_count, stride);
Aart Bikd14c5952015-09-08 15:25:15 -0700616 }
Aart Bik22f05872015-10-27 15:56:28 -0700617 trip_count = CreateInvariantOp(kDiv, CreateInvariantOp(kSub, trip_count, lower_expr), stride);
Aart Bikd14c5952015-09-08 15:25:15 -0700618 // Assign the trip-count expression to the loop control. Clients that use the information
Aart Bik9401f532015-09-28 16:25:56 -0700619 // should be aware that the expression is only valid under the conditions listed above.
Aart Bik22f05872015-10-27 15:56:28 -0700620 InductionOp tcKind = kTripCountInBodyUnsafe; // needs both tests
Aart Bik9401f532015-09-28 16:25:56 -0700621 if (is_taken && is_finite) {
Aart Bik22f05872015-10-27 15:56:28 -0700622 tcKind = kTripCountInLoop; // needs neither test
Aart Bik9401f532015-09-28 16:25:56 -0700623 } else if (is_finite) {
Aart Bik22f05872015-10-27 15:56:28 -0700624 tcKind = kTripCountInBody; // needs taken-test
Aart Bik9401f532015-09-28 16:25:56 -0700625 } else if (is_taken) {
Aart Bik22f05872015-10-27 15:56:28 -0700626 tcKind = kTripCountInLoopUnsafe; // needs finite-test
Aart Bik9401f532015-09-28 16:25:56 -0700627 }
Aart Bik22f05872015-10-27 15:56:28 -0700628 InductionOp op = kNop;
629 switch (cmp) {
630 case kCondLT: op = kLT; break;
631 case kCondLE: op = kLE; break;
632 case kCondGT: op = kGT; break;
633 case kCondGE: op = kGE; break;
634 default: LOG(FATAL) << "CONDITION UNREACHABLE";
635 }
636 InductionInfo* taken_test = CreateInvariantOp(op, lower_expr, upper_expr);
637 AssignInfo(loop,
638 loop->GetHeader()->GetLastInstruction(),
639 CreateTripCount(tcKind, trip_count, taken_test));
Aart Bik9401f532015-09-28 16:25:56 -0700640}
641
642bool HInductionVarAnalysis::IsTaken(InductionInfo* lower_expr,
643 InductionInfo* upper_expr,
644 IfCondition cmp) {
645 int64_t lower_value;
646 int64_t upper_value;
647 if (IsIntAndGet(lower_expr, &lower_value) && IsIntAndGet(upper_expr, &upper_value)) {
648 switch (cmp) {
649 case kCondLT: return lower_value < upper_value;
650 case kCondLE: return lower_value <= upper_value;
651 case kCondGT: return lower_value > upper_value;
652 case kCondGE: return lower_value >= upper_value;
Aart Bike9f37602015-10-09 11:15:55 -0700653 default: LOG(FATAL) << "CONDITION UNREACHABLE";
Aart Bik9401f532015-09-28 16:25:56 -0700654 }
655 }
656 return false; // not certain, may be untaken
657}
658
659bool HInductionVarAnalysis::IsFinite(InductionInfo* upper_expr,
660 int64_t stride_value,
661 Primitive::Type type,
662 IfCondition cmp) {
663 const int64_t min = type == Primitive::kPrimInt
664 ? std::numeric_limits<int32_t>::min()
665 : std::numeric_limits<int64_t>::min();
666 const int64_t max = type == Primitive::kPrimInt
667 ? std::numeric_limits<int32_t>::max()
668 : std::numeric_limits<int64_t>::max();
669 // Some rules under which it is certain at compile-time that the loop is finite.
670 int64_t value;
671 switch (cmp) {
672 case kCondLT:
673 return stride_value == 1 ||
674 (IsIntAndGet(upper_expr, &value) && value <= (max - stride_value + 1));
675 case kCondLE:
676 return (IsIntAndGet(upper_expr, &value) && value <= (max - stride_value));
677 case kCondGT:
678 return stride_value == -1 ||
679 (IsIntAndGet(upper_expr, &value) && value >= (min - stride_value - 1));
680 case kCondGE:
681 return (IsIntAndGet(upper_expr, &value) && value >= (min - stride_value));
Aart Bike9f37602015-10-09 11:15:55 -0700682 default:
683 LOG(FATAL) << "CONDITION UNREACHABLE";
Aart Bik9401f532015-09-28 16:25:56 -0700684 }
685 return false; // not certain, may be infinite
Aart Bikd14c5952015-09-08 15:25:15 -0700686}
687
Aart Bik30efb4e2015-07-30 12:14:31 -0700688void HInductionVarAnalysis::AssignInfo(HLoopInformation* loop,
689 HInstruction* instruction,
690 InductionInfo* info) {
Aart Bike609b7c2015-08-27 13:46:58 -0700691 auto it = induction_.find(loop);
692 if (it == induction_.end()) {
693 it = induction_.Put(loop,
694 ArenaSafeMap<HInstruction*, InductionInfo*>(
Vladimir Marko5233f932015-09-29 19:01:15 +0100695 std::less<HInstruction*>(),
696 graph_->GetArena()->Adapter(kArenaAllocInductionVarAnalysis)));
Aart Bike609b7c2015-08-27 13:46:58 -0700697 }
698 it->second.Put(instruction, info);
Aart Bik30efb4e2015-07-30 12:14:31 -0700699}
700
Aart Bike609b7c2015-08-27 13:46:58 -0700701HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::LookupInfo(HLoopInformation* loop,
702 HInstruction* instruction) {
703 auto it = induction_.find(loop);
704 if (it != induction_.end()) {
705 auto loop_it = it->second.find(instruction);
706 if (loop_it != it->second.end()) {
707 return loop_it->second;
708 }
Aart Bik30efb4e2015-07-30 12:14:31 -0700709 }
Mingyao Yang4b467ed2015-11-19 17:04:22 -0800710 if (loop->IsDefinedOutOfTheLoop(instruction)) {
Aart Bik471a2032015-09-04 18:22:11 -0700711 InductionInfo* info = CreateInvariantFetch(instruction);
Aart Bike609b7c2015-08-27 13:46:58 -0700712 AssignInfo(loop, instruction, info);
713 return info;
714 }
715 return nullptr;
Aart Bik30efb4e2015-07-30 12:14:31 -0700716}
717
Aart Bikd14c5952015-09-08 15:25:15 -0700718HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::CreateConstant(int64_t value,
719 Primitive::Type type) {
720 if (type == Primitive::kPrimInt) {
721 return CreateInvariantFetch(graph_->GetIntConstant(value));
722 }
723 DCHECK_EQ(type, Primitive::kPrimLong);
724 return CreateInvariantFetch(graph_->GetLongConstant(value));
725}
726
Aart Bik471a2032015-09-04 18:22:11 -0700727HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::CreateSimplifiedInvariant(
728 InductionOp op,
729 InductionInfo* a,
730 InductionInfo* b) {
731 // Perform some light-weight simplifications during construction of a new invariant.
732 // This often safes memory and yields a more concise representation of the induction.
733 // More exhaustive simplifications are done by later phases once induction nodes are
734 // translated back into HIR code (e.g. by loop optimizations or BCE).
735 int64_t value = -1;
736 if (IsIntAndGet(a, &value)) {
737 if (value == 0) {
738 // Simplify 0 + b = b, 0 * b = 0.
739 if (op == kAdd) {
740 return b;
741 } else if (op == kMul) {
742 return a;
743 }
Aart Bikd14c5952015-09-08 15:25:15 -0700744 } else if (op == kMul) {
745 // Simplify 1 * b = b, -1 * b = -b
746 if (value == 1) {
747 return b;
748 } else if (value == -1) {
Aart Bik7d57d7f2015-12-09 14:39:48 -0800749 return CreateSimplifiedInvariant(kNeg, nullptr, b);
Aart Bikd14c5952015-09-08 15:25:15 -0700750 }
Aart Bik471a2032015-09-04 18:22:11 -0700751 }
752 }
753 if (IsIntAndGet(b, &value)) {
754 if (value == 0) {
Aart Bikd14c5952015-09-08 15:25:15 -0700755 // Simplify a + 0 = a, a - 0 = a, a * 0 = 0, -0 = 0.
Aart Bik471a2032015-09-04 18:22:11 -0700756 if (op == kAdd || op == kSub) {
757 return a;
758 } else if (op == kMul || op == kNeg) {
759 return b;
760 }
Aart Bikd14c5952015-09-08 15:25:15 -0700761 } else if (op == kMul || op == kDiv) {
762 // Simplify a * 1 = a, a / 1 = a, a * -1 = -a, a / -1 = -a
763 if (value == 1) {
764 return a;
765 } else if (value == -1) {
Aart Bik7d57d7f2015-12-09 14:39:48 -0800766 return CreateSimplifiedInvariant(kNeg, nullptr, a);
Aart Bikd14c5952015-09-08 15:25:15 -0700767 }
Aart Bik471a2032015-09-04 18:22:11 -0700768 }
769 } else if (b->operation == kNeg) {
Aart Bikd14c5952015-09-08 15:25:15 -0700770 // Simplify a + (-b) = a - b, a - (-b) = a + b, -(-b) = b.
771 if (op == kAdd) {
Aart Bik7d57d7f2015-12-09 14:39:48 -0800772 return CreateSimplifiedInvariant(kSub, a, b->op_b);
Aart Bikd14c5952015-09-08 15:25:15 -0700773 } else if (op == kSub) {
Aart Bik7d57d7f2015-12-09 14:39:48 -0800774 return CreateSimplifiedInvariant(kAdd, a, b->op_b);
Aart Bikd14c5952015-09-08 15:25:15 -0700775 } else if (op == kNeg) {
776 return b->op_b;
Aart Bik471a2032015-09-04 18:22:11 -0700777 }
Aart Bik7d57d7f2015-12-09 14:39:48 -0800778 } else if (b->operation == kSub) {
779 // Simplify - (a - b) = b - a.
780 if (op == kNeg) {
781 return CreateSimplifiedInvariant(kSub, b->op_b, b->op_a);
782 }
Aart Bik471a2032015-09-04 18:22:11 -0700783 }
784 return new (graph_->GetArena()) InductionInfo(kInvariant, op, a, b, nullptr);
785}
786
Aart Bik7d57d7f2015-12-09 14:39:48 -0800787bool HInductionVarAnalysis::IsIntAndGet(InductionInfo* info, int64_t* value) {
788 if (info != nullptr && info->induction_class == kInvariant) {
789 // A direct constant fetch.
790 if (info->operation == kFetch) {
791 DCHECK(info->fetch);
792 if (info->fetch->IsIntConstant()) {
793 *value = info->fetch->AsIntConstant()->GetValue();
794 return true;
795 } else if (info->fetch->IsLongConstant()) {
796 *value = info->fetch->AsLongConstant()->GetValue();
797 return true;
798 }
799 }
800 // Use range analysis to resolve compound values.
801 InductionVarRange range(this);
802 int32_t min_val = 0;
803 int32_t max_val = 0;
804 if (range.IsConstantRange(info, &min_val, &max_val) && min_val == max_val) {
805 *value = min_val;
806 return true;
807 }
808 }
809 return false;
810}
811
Aart Bik30efb4e2015-07-30 12:14:31 -0700812bool HInductionVarAnalysis::InductionEqual(InductionInfo* info1,
813 InductionInfo* info2) {
814 // Test structural equality only, without accounting for simplifications.
815 if (info1 != nullptr && info2 != nullptr) {
816 return
817 info1->induction_class == info2->induction_class &&
818 info1->operation == info2->operation &&
819 info1->fetch == info2->fetch &&
820 InductionEqual(info1->op_a, info2->op_a) &&
821 InductionEqual(info1->op_b, info2->op_b);
822 }
823 // Otherwise only two nullptrs are considered equal.
824 return info1 == info2;
825}
826
827std::string HInductionVarAnalysis::InductionToString(InductionInfo* info) {
828 if (info != nullptr) {
829 if (info->induction_class == kInvariant) {
830 std::string inv = "(";
831 inv += InductionToString(info->op_a);
832 switch (info->operation) {
Aart Bik22f05872015-10-27 15:56:28 -0700833 case kNop: inv += " @ "; break;
834 case kAdd: inv += " + "; break;
Aart Bik30efb4e2015-07-30 12:14:31 -0700835 case kSub:
Aart Bik22f05872015-10-27 15:56:28 -0700836 case kNeg: inv += " - "; break;
837 case kMul: inv += " * "; break;
838 case kDiv: inv += " / "; break;
839 case kLT: inv += " < "; break;
840 case kLE: inv += " <= "; break;
841 case kGT: inv += " > "; break;
842 case kGE: inv += " >= "; break;
Aart Bik30efb4e2015-07-30 12:14:31 -0700843 case kFetch:
Aart Bike609b7c2015-08-27 13:46:58 -0700844 DCHECK(info->fetch);
Aart Bik7d57d7f2015-12-09 14:39:48 -0800845 if (info->fetch->IsIntConstant()) {
846 inv += std::to_string(info->fetch->AsIntConstant()->GetValue());
847 } else if (info->fetch->IsLongConstant()) {
848 inv += std::to_string(info->fetch->AsLongConstant()->GetValue());
Aart Bik471a2032015-09-04 18:22:11 -0700849 } else {
850 inv += std::to_string(info->fetch->GetId()) + ":" + info->fetch->DebugName();
851 }
Aart Bik30efb4e2015-07-30 12:14:31 -0700852 break;
Aart Bik22f05872015-10-27 15:56:28 -0700853 case kTripCountInLoop: inv += " (TC-loop) "; break;
854 case kTripCountInBody: inv += " (TC-body) "; break;
855 case kTripCountInLoopUnsafe: inv += " (TC-loop-unsafe) "; break;
856 case kTripCountInBodyUnsafe: inv += " (TC-body-unsafe) "; break;
Aart Bik30efb4e2015-07-30 12:14:31 -0700857 }
858 inv += InductionToString(info->op_b);
859 return inv + ")";
860 } else {
Aart Bike609b7c2015-08-27 13:46:58 -0700861 DCHECK(info->operation == kNop);
Aart Bik30efb4e2015-07-30 12:14:31 -0700862 if (info->induction_class == kLinear) {
863 return "(" + InductionToString(info->op_a) + " * i + " +
864 InductionToString(info->op_b) + ")";
865 } else if (info->induction_class == kWrapAround) {
866 return "wrap(" + InductionToString(info->op_a) + ", " +
867 InductionToString(info->op_b) + ")";
868 } else if (info->induction_class == kPeriodic) {
869 return "periodic(" + InductionToString(info->op_a) + ", " +
870 InductionToString(info->op_b) + ")";
871 }
872 }
873 }
874 return "";
875}
876
877} // namespace art