blob: 55fcb12fa85a57c5aa1db68a4bf6fc356b6dce6a [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 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*>(),
97 graph->GetArena()->Adapter(kArenaAllocInductionVarAnalysis)) {
Aart Bik30efb4e2015-07-30 12:14:31 -070098}
99
100void HInductionVarAnalysis::Run() {
Aart Bik7d57d7f2015-12-09 14:39:48 -0800101 // Detects sequence variables (generalized induction variables) during an outer to inner
102 // traversal of all loops using Gerlek's algorithm. The order is important to enable
103 // range analysis on outer loop while visiting inner loops.
104 for (HReversePostOrderIterator it_graph(*graph_); !it_graph.Done(); it_graph.Advance()) {
Aart Bik30efb4e2015-07-30 12:14:31 -0700105 HBasicBlock* graph_block = it_graph.Current();
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000106 // Don't analyze irreducible loops.
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000107 if (graph_block->IsLoopHeader() && !graph_block->GetLoopInformation()->IsIrreducible()) {
Aart Bik30efb4e2015-07-30 12:14:31 -0700108 VisitLoop(graph_block->GetLoopInformation());
109 }
110 }
111}
112
113void HInductionVarAnalysis::VisitLoop(HLoopInformation* loop) {
114 // Find strongly connected components (SSCs) in the SSA graph of this loop using Tarjan's
115 // algorithm. Due to the descendant-first nature, classification happens "on-demand".
116 global_depth_ = 0;
Aart Bike609b7c2015-08-27 13:46:58 -0700117 DCHECK(stack_.empty());
Aart Bik30efb4e2015-07-30 12:14:31 -0700118 map_.clear();
119
120 for (HBlocksInLoopIterator it_loop(*loop); !it_loop.Done(); it_loop.Advance()) {
121 HBasicBlock* loop_block = it_loop.Current();
Aart Bike609b7c2015-08-27 13:46:58 -0700122 DCHECK(loop_block->IsInLoop());
Aart Bik30efb4e2015-07-30 12:14:31 -0700123 if (loop_block->GetLoopInformation() != loop) {
Aart Bik7dc96932016-10-12 10:01:05 -0700124 continue; // Inner loops visited later.
Aart Bik30efb4e2015-07-30 12:14:31 -0700125 }
126 // Visit phi-operations and instructions.
127 for (HInstructionIterator it(loop_block->GetPhis()); !it.Done(); it.Advance()) {
128 HInstruction* instruction = it.Current();
Aart Bike609b7c2015-08-27 13:46:58 -0700129 if (!IsVisitedNode(instruction)) {
Aart Bik30efb4e2015-07-30 12:14:31 -0700130 VisitNode(loop, instruction);
131 }
132 }
133 for (HInstructionIterator it(loop_block->GetInstructions()); !it.Done(); it.Advance()) {
134 HInstruction* instruction = it.Current();
Aart Bike609b7c2015-08-27 13:46:58 -0700135 if (!IsVisitedNode(instruction)) {
Aart Bik30efb4e2015-07-30 12:14:31 -0700136 VisitNode(loop, instruction);
137 }
138 }
139 }
140
Aart Bike609b7c2015-08-27 13:46:58 -0700141 DCHECK(stack_.empty());
Aart Bik30efb4e2015-07-30 12:14:31 -0700142 map_.clear();
Aart Bikd14c5952015-09-08 15:25:15 -0700143
Aart Bik78296912016-03-25 13:14:53 -0700144 // Determine the loop's trip-count.
Aart Bikd14c5952015-09-08 15:25:15 -0700145 VisitControl(loop);
Aart Bik30efb4e2015-07-30 12:14:31 -0700146}
147
148void HInductionVarAnalysis::VisitNode(HLoopInformation* loop, HInstruction* instruction) {
Aart Bik30efb4e2015-07-30 12:14:31 -0700149 const uint32_t d1 = ++global_depth_;
Aart Bike609b7c2015-08-27 13:46:58 -0700150 map_.Put(instruction, NodeInfo(d1));
Aart Bik30efb4e2015-07-30 12:14:31 -0700151 stack_.push_back(instruction);
152
153 // Visit all descendants.
154 uint32_t low = d1;
Vladimir Marko372f10e2016-05-17 16:30:10 +0100155 for (HInstruction* input : instruction->GetInputs()) {
156 low = std::min(low, VisitDescendant(loop, input));
Aart Bik30efb4e2015-07-30 12:14:31 -0700157 }
158
159 // Lower or found SCC?
160 if (low < d1) {
Aart Bike609b7c2015-08-27 13:46:58 -0700161 map_.find(instruction)->second.depth = low;
Aart Bik30efb4e2015-07-30 12:14:31 -0700162 } else {
163 scc_.clear();
164 cycle_.clear();
165
166 // Pop the stack to build the SCC for classification.
167 while (!stack_.empty()) {
168 HInstruction* x = stack_.back();
169 scc_.push_back(x);
170 stack_.pop_back();
Aart Bike609b7c2015-08-27 13:46:58 -0700171 map_.find(x)->second.done = true;
Aart Bik30efb4e2015-07-30 12:14:31 -0700172 if (x == instruction) {
173 break;
174 }
175 }
176
Aart Bik0d345cf2016-03-16 10:49:38 -0700177 // Type of induction.
178 type_ = scc_[0]->GetType();
179
Aart Bik30efb4e2015-07-30 12:14:31 -0700180 // Classify the SCC.
Aart Bikf475bee2015-09-16 12:50:25 -0700181 if (scc_.size() == 1 && !scc_[0]->IsLoopHeaderPhi()) {
Aart Bik30efb4e2015-07-30 12:14:31 -0700182 ClassifyTrivial(loop, scc_[0]);
183 } else {
184 ClassifyNonTrivial(loop);
185 }
186
187 scc_.clear();
188 cycle_.clear();
189 }
190}
191
192uint32_t HInductionVarAnalysis::VisitDescendant(HLoopInformation* loop, HInstruction* instruction) {
193 // If the definition is either outside the loop (loop invariant entry value)
194 // or assigned in inner loop (inner exit value), the traversal stops.
195 HLoopInformation* otherLoop = instruction->GetBlock()->GetLoopInformation();
196 if (otherLoop != loop) {
197 return global_depth_;
198 }
199
200 // Inspect descendant node.
Aart Bike609b7c2015-08-27 13:46:58 -0700201 if (!IsVisitedNode(instruction)) {
Aart Bik30efb4e2015-07-30 12:14:31 -0700202 VisitNode(loop, instruction);
Aart Bike609b7c2015-08-27 13:46:58 -0700203 return map_.find(instruction)->second.depth;
Aart Bik30efb4e2015-07-30 12:14:31 -0700204 } else {
Aart Bike609b7c2015-08-27 13:46:58 -0700205 auto it = map_.find(instruction);
Aart Bik30efb4e2015-07-30 12:14:31 -0700206 return it->second.done ? global_depth_ : it->second.depth;
207 }
208}
209
210void HInductionVarAnalysis::ClassifyTrivial(HLoopInformation* loop, HInstruction* instruction) {
211 InductionInfo* info = nullptr;
212 if (instruction->IsPhi()) {
Aart Bikf475bee2015-09-16 12:50:25 -0700213 info = TransferPhi(loop, instruction, /* input_index */ 0);
Aart Bik30efb4e2015-07-30 12:14:31 -0700214 } else if (instruction->IsAdd()) {
215 info = TransferAddSub(LookupInfo(loop, instruction->InputAt(0)),
216 LookupInfo(loop, instruction->InputAt(1)), kAdd);
217 } else if (instruction->IsSub()) {
218 info = TransferAddSub(LookupInfo(loop, instruction->InputAt(0)),
219 LookupInfo(loop, instruction->InputAt(1)), kSub);
220 } else if (instruction->IsMul()) {
221 info = TransferMul(LookupInfo(loop, instruction->InputAt(0)),
222 LookupInfo(loop, instruction->InputAt(1)));
Aart Bike609b7c2015-08-27 13:46:58 -0700223 } else if (instruction->IsShl()) {
224 info = TransferShl(LookupInfo(loop, instruction->InputAt(0)),
225 LookupInfo(loop, instruction->InputAt(1)),
226 instruction->InputAt(0)->GetType());
Aart Bik30efb4e2015-07-30 12:14:31 -0700227 } else if (instruction->IsNeg()) {
228 info = TransferNeg(LookupInfo(loop, instruction->InputAt(0)));
Aart Bik0d345cf2016-03-16 10:49:38 -0700229 } else if (instruction->IsTypeConversion()) {
230 info = TransferCnv(LookupInfo(loop, instruction->InputAt(0)),
231 instruction->AsTypeConversion()->GetInputType(),
232 instruction->AsTypeConversion()->GetResultType());
233
Aart Bike609b7c2015-08-27 13:46:58 -0700234 } else if (instruction->IsBoundsCheck()) {
235 info = LookupInfo(loop, instruction->InputAt(0)); // Pass-through.
Aart Bik30efb4e2015-07-30 12:14:31 -0700236 }
237
238 // Successfully classified?
239 if (info != nullptr) {
240 AssignInfo(loop, instruction, info);
241 }
242}
243
244void HInductionVarAnalysis::ClassifyNonTrivial(HLoopInformation* loop) {
245 const size_t size = scc_.size();
Aart Bike609b7c2015-08-27 13:46:58 -0700246 DCHECK_GE(size, 1u);
Aart Bik22af3be2015-09-10 12:50:58 -0700247
248 // Rotate proper entry-phi to front.
249 if (size > 1) {
Vladimir Marko5233f932015-09-29 19:01:15 +0100250 ArenaVector<HInstruction*> other(graph_->GetArena()->Adapter(kArenaAllocInductionVarAnalysis));
Aart Bik22af3be2015-09-10 12:50:58 -0700251 RotateEntryPhiFirst(loop, &scc_, &other);
252 }
253
Aart Bikf475bee2015-09-16 12:50:25 -0700254 // Analyze from entry-phi onwards.
Aart Bik22af3be2015-09-10 12:50:58 -0700255 HInstruction* phi = scc_[0];
Aart Bikf475bee2015-09-16 12:50:25 -0700256 if (!phi->IsLoopHeaderPhi()) {
Aart Bik30efb4e2015-07-30 12:14:31 -0700257 return;
258 }
Aart Bikf475bee2015-09-16 12:50:25 -0700259
260 // External link should be loop invariant.
261 InductionInfo* initial = LookupInfo(loop, phi->InputAt(0));
Aart Bik30efb4e2015-07-30 12:14:31 -0700262 if (initial == nullptr || initial->induction_class != kInvariant) {
263 return;
264 }
265
Aart Bikf475bee2015-09-16 12:50:25 -0700266 // Singleton is wrap-around induction if all internal links have the same meaning.
Aart Bik30efb4e2015-07-30 12:14:31 -0700267 if (size == 1) {
Aart Bikf475bee2015-09-16 12:50:25 -0700268 InductionInfo* update = TransferPhi(loop, phi, /* input_index */ 1);
Aart Bik30efb4e2015-07-30 12:14:31 -0700269 if (update != nullptr) {
Aart Bik0d345cf2016-03-16 10:49:38 -0700270 AssignInfo(loop, phi, CreateInduction(kWrapAround, initial, update, type_));
Aart Bik30efb4e2015-07-30 12:14:31 -0700271 }
272 return;
273 }
274
275 // Inspect remainder of the cycle that resides in scc_. The cycle_ mapping assigns
Aart Bike609b7c2015-08-27 13:46:58 -0700276 // temporary meaning to its nodes, seeded from the phi instruction and back.
Aart Bik22af3be2015-09-10 12:50:58 -0700277 for (size_t i = 1; i < size; i++) {
Aart Bike609b7c2015-08-27 13:46:58 -0700278 HInstruction* instruction = scc_[i];
Aart Bik30efb4e2015-07-30 12:14:31 -0700279 InductionInfo* update = nullptr;
Aart Bike609b7c2015-08-27 13:46:58 -0700280 if (instruction->IsPhi()) {
Aart Bikf475bee2015-09-16 12:50:25 -0700281 update = SolvePhiAllInputs(loop, phi, instruction);
Aart Bike609b7c2015-08-27 13:46:58 -0700282 } else if (instruction->IsAdd()) {
283 update = SolveAddSub(
284 loop, phi, instruction, instruction->InputAt(0), instruction->InputAt(1), kAdd, true);
285 } else if (instruction->IsSub()) {
286 update = SolveAddSub(
287 loop, phi, instruction, instruction->InputAt(0), instruction->InputAt(1), kSub, true);
Aart Bik7dc96932016-10-12 10:01:05 -0700288 } else if (instruction->IsXor()) {
289 update = SolveXor(
290 loop, phi, instruction, instruction->InputAt(0), instruction->InputAt(1), true);
Aart Bik0d345cf2016-03-16 10:49:38 -0700291 } else if (instruction->IsTypeConversion()) {
292 update = SolveCnv(instruction->AsTypeConversion());
Aart Bik30efb4e2015-07-30 12:14:31 -0700293 }
294 if (update == nullptr) {
295 return;
296 }
Aart Bike609b7c2015-08-27 13:46:58 -0700297 cycle_.Put(instruction, update);
Aart Bik30efb4e2015-07-30 12:14:31 -0700298 }
299
Aart Bikf475bee2015-09-16 12:50:25 -0700300 // Success if all internal links received the same temporary meaning.
301 InductionInfo* induction = SolvePhi(phi, /* input_index */ 1);
302 if (induction != nullptr) {
Aart Bike609b7c2015-08-27 13:46:58 -0700303 switch (induction->induction_class) {
304 case kInvariant:
Aart Bik22af3be2015-09-10 12:50:58 -0700305 // Classify first phi and then the rest of the cycle "on-demand".
306 // Statements are scanned in order.
Aart Bik0d345cf2016-03-16 10:49:38 -0700307 AssignInfo(loop, phi, CreateInduction(kLinear, induction, initial, type_));
Aart Bik22af3be2015-09-10 12:50:58 -0700308 for (size_t i = 1; i < size; i++) {
Aart Bike609b7c2015-08-27 13:46:58 -0700309 ClassifyTrivial(loop, scc_[i]);
310 }
311 break;
312 case kPeriodic:
Aart Bik22af3be2015-09-10 12:50:58 -0700313 // Classify all elements in the cycle with the found periodic induction while
314 // rotating each first element to the end. Lastly, phi is classified.
315 // Statements are scanned in reverse order.
316 for (size_t i = size - 1; i >= 1; i--) {
317 AssignInfo(loop, scc_[i], induction);
Aart Bike609b7c2015-08-27 13:46:58 -0700318 induction = RotatePeriodicInduction(induction->op_b, induction->op_a);
319 }
320 AssignInfo(loop, phi, induction);
321 break;
322 default:
323 break;
Aart Bik30efb4e2015-07-30 12:14:31 -0700324 }
325 }
326}
327
Aart Bike609b7c2015-08-27 13:46:58 -0700328HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::RotatePeriodicInduction(
329 InductionInfo* induction,
330 InductionInfo* last) {
331 // Rotates a periodic induction of the form
332 // (a, b, c, d, e)
333 // into
334 // (b, c, d, e, a)
335 // in preparation of assigning this to the previous variable in the sequence.
336 if (induction->induction_class == kInvariant) {
Aart Bik0d345cf2016-03-16 10:49:38 -0700337 return CreateInduction(kPeriodic, induction, last, type_);
Aart Bike609b7c2015-08-27 13:46:58 -0700338 }
Aart Bik0d345cf2016-03-16 10:49:38 -0700339 return CreateInduction(
340 kPeriodic, induction->op_a, RotatePeriodicInduction(induction->op_b, last), type_);
Aart Bike609b7c2015-08-27 13:46:58 -0700341}
342
Aart Bikf475bee2015-09-16 12:50:25 -0700343HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::TransferPhi(HLoopInformation* loop,
344 HInstruction* phi,
345 size_t input_index) {
346 // Match all phi inputs from input_index onwards exactly.
Vladimir Markoe9004912016-06-16 16:50:52 +0100347 HInputsRef inputs = phi->GetInputs();
Vladimir Marko372f10e2016-05-17 16:30:10 +0100348 DCHECK_LT(input_index, inputs.size());
349 InductionInfo* a = LookupInfo(loop, inputs[input_index]);
350 for (size_t i = input_index + 1; i < inputs.size(); i++) {
351 InductionInfo* b = LookupInfo(loop, inputs[i]);
Aart Bikf475bee2015-09-16 12:50:25 -0700352 if (!InductionEqual(a, b)) {
353 return nullptr;
354 }
Aart Bik30efb4e2015-07-30 12:14:31 -0700355 }
Aart Bikf475bee2015-09-16 12:50:25 -0700356 return a;
Aart Bik30efb4e2015-07-30 12:14:31 -0700357}
358
359HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::TransferAddSub(InductionInfo* a,
360 InductionInfo* b,
361 InductionOp op) {
Aart Bike609b7c2015-08-27 13:46:58 -0700362 // Transfer over an addition or subtraction: any invariant, linear, wrap-around, or periodic
363 // can be combined with an invariant to yield a similar result. Even two linear inputs can
364 // be combined. All other combinations fail, 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(op, a, b);
Aart Bik30efb4e2015-07-30 12:14:31 -0700368 } else if (a->induction_class == kLinear && b->induction_class == kLinear) {
Aart Bik0d345cf2016-03-16 10:49:38 -0700369 return CreateInduction(kLinear,
370 TransferAddSub(a->op_a, b->op_a, op),
371 TransferAddSub(a->op_b, b->op_b, op),
372 type_);
Aart Bike609b7c2015-08-27 13:46:58 -0700373 } else if (a->induction_class == kInvariant) {
374 InductionInfo* new_a = b->op_a;
375 InductionInfo* new_b = TransferAddSub(a, b->op_b, op);
376 if (b->induction_class != kLinear) {
377 DCHECK(b->induction_class == kWrapAround || b->induction_class == kPeriodic);
378 new_a = TransferAddSub(a, new_a, op);
379 } else if (op == kSub) { // Negation required.
380 new_a = TransferNeg(new_a);
381 }
Aart Bik0d345cf2016-03-16 10:49:38 -0700382 return CreateInduction(b->induction_class, new_a, new_b, type_);
Aart Bike609b7c2015-08-27 13:46:58 -0700383 } else if (b->induction_class == kInvariant) {
384 InductionInfo* new_a = a->op_a;
385 InductionInfo* new_b = TransferAddSub(a->op_b, b, op);
386 if (a->induction_class != kLinear) {
387 DCHECK(a->induction_class == kWrapAround || a->induction_class == kPeriodic);
388 new_a = TransferAddSub(new_a, b, op);
389 }
Aart Bik0d345cf2016-03-16 10:49:38 -0700390 return CreateInduction(a->induction_class, new_a, new_b, type_);
Aart Bik30efb4e2015-07-30 12:14:31 -0700391 }
392 }
393 return nullptr;
394}
395
396HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::TransferMul(InductionInfo* a,
397 InductionInfo* b) {
Aart Bike609b7c2015-08-27 13:46:58 -0700398 // Transfer over a multiplication: any invariant, linear, wrap-around, or periodic
399 // can be multiplied with an invariant to yield a similar but multiplied result.
400 // Two non-invariant inputs cannot be multiplied, however.
Aart Bik30efb4e2015-07-30 12:14:31 -0700401 if (a != nullptr && b != nullptr) {
402 if (a->induction_class == kInvariant && b->induction_class == kInvariant) {
Aart Bik471a2032015-09-04 18:22:11 -0700403 return CreateInvariantOp(kMul, a, b);
Aart Bike609b7c2015-08-27 13:46:58 -0700404 } else if (a->induction_class == kInvariant) {
Aart Bik0d345cf2016-03-16 10:49:38 -0700405 return CreateInduction(b->induction_class,
406 TransferMul(a, b->op_a),
407 TransferMul(a, b->op_b),
408 type_);
Aart Bike609b7c2015-08-27 13:46:58 -0700409 } else if (b->induction_class == kInvariant) {
Aart Bik0d345cf2016-03-16 10:49:38 -0700410 return CreateInduction(a->induction_class,
411 TransferMul(a->op_a, b),
412 TransferMul(a->op_b, b),
413 type_);
Aart Bike609b7c2015-08-27 13:46:58 -0700414 }
415 }
416 return nullptr;
417}
418
419HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::TransferShl(InductionInfo* a,
420 InductionInfo* b,
Aart Bikd14c5952015-09-08 15:25:15 -0700421 Primitive::Type type) {
Aart Bike609b7c2015-08-27 13:46:58 -0700422 // Transfer over a shift left: treat shift by restricted constant as equivalent multiplication.
Aart Bik471a2032015-09-04 18:22:11 -0700423 int64_t value = -1;
Aart Bik97412c922016-02-19 20:14:38 -0800424 if (a != nullptr && IsExact(b, &value)) {
Aart Bike609b7c2015-08-27 13:46:58 -0700425 // Obtain the constant needed for the multiplication. This yields an existing instruction
426 // if the constants is already there. Otherwise, this has a side effect on the HIR.
427 // The restriction on the shift factor avoids generating a negative constant
428 // (viz. 1 << 31 and 1L << 63 set the sign bit). The code assumes that generalization
429 // for shift factors outside [0,32) and [0,64) ranges is done by earlier simplification.
Aart Bikd14c5952015-09-08 15:25:15 -0700430 if ((type == Primitive::kPrimInt && 0 <= value && value < 31) ||
431 (type == Primitive::kPrimLong && 0 <= value && value < 63)) {
432 return TransferMul(a, CreateConstant(1 << value, type));
Aart Bik30efb4e2015-07-30 12:14:31 -0700433 }
434 }
435 return nullptr;
436}
437
438HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::TransferNeg(InductionInfo* a) {
Aart Bike609b7c2015-08-27 13:46:58 -0700439 // Transfer over a unary negation: an invariant, linear, wrap-around, or periodic input
440 // yields a similar but negated induction as result.
Aart Bik30efb4e2015-07-30 12:14:31 -0700441 if (a != nullptr) {
442 if (a->induction_class == kInvariant) {
Aart Bik471a2032015-09-04 18:22:11 -0700443 return CreateInvariantOp(kNeg, nullptr, a);
Aart Bik30efb4e2015-07-30 12:14:31 -0700444 }
Aart Bik0d345cf2016-03-16 10:49:38 -0700445 return CreateInduction(a->induction_class, TransferNeg(a->op_a), TransferNeg(a->op_b), type_);
446 }
447 return nullptr;
448}
449
450HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::TransferCnv(InductionInfo* a,
451 Primitive::Type from,
452 Primitive::Type to) {
453 if (a != nullptr) {
454 // Allow narrowing conversion in certain cases.
455 if (IsNarrowingIntegralConversion(from, to)) {
456 if (a->induction_class == kLinear) {
457 if (a->type == to || (a->type == from && IsNarrowingIntegralConversion(from, to))) {
458 return CreateInduction(kLinear, a->op_a, a->op_b, to);
459 }
460 }
461 // TODO: other cases useful too?
462 }
Aart Bik30efb4e2015-07-30 12:14:31 -0700463 }
464 return nullptr;
465}
466
Aart Bikf475bee2015-09-16 12:50:25 -0700467HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::SolvePhi(HInstruction* phi,
468 size_t input_index) {
469 // Match all phi inputs from input_index onwards exactly.
Vladimir Markoe9004912016-06-16 16:50:52 +0100470 HInputsRef inputs = phi->GetInputs();
Vladimir Marko372f10e2016-05-17 16:30:10 +0100471 DCHECK_LT(input_index, inputs.size());
472 auto ita = cycle_.find(inputs[input_index]);
Aart Bik30efb4e2015-07-30 12:14:31 -0700473 if (ita != cycle_.end()) {
Vladimir Marko372f10e2016-05-17 16:30:10 +0100474 for (size_t i = input_index + 1; i < inputs.size(); i++) {
475 auto itb = cycle_.find(inputs[i]);
Aart Bikf475bee2015-09-16 12:50:25 -0700476 if (itb == cycle_.end() ||
477 !HInductionVarAnalysis::InductionEqual(ita->second, itb->second)) {
Aart Bik30efb4e2015-07-30 12:14:31 -0700478 return nullptr;
479 }
480 }
Aart Bikf475bee2015-09-16 12:50:25 -0700481 return ita->second;
482 }
483 return nullptr;
484}
485
486HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::SolvePhiAllInputs(
487 HLoopInformation* loop,
488 HInstruction* entry_phi,
489 HInstruction* phi) {
490 // Match all phi inputs.
491 InductionInfo* match = SolvePhi(phi, /* input_index */ 0);
492 if (match != nullptr) {
493 return match;
Aart Bik30efb4e2015-07-30 12:14:31 -0700494 }
Aart Bik30efb4e2015-07-30 12:14:31 -0700495
Aart Bikf475bee2015-09-16 12:50:25 -0700496 // Otherwise, try to solve for a periodic seeded from phi onward.
497 // Only tight multi-statement cycles are considered in order to
498 // simplify rotating the periodic during the final classification.
499 if (phi->IsLoopHeaderPhi() && phi->InputCount() == 2) {
500 InductionInfo* a = LookupInfo(loop, phi->InputAt(0));
Aart Bike609b7c2015-08-27 13:46:58 -0700501 if (a != nullptr && a->induction_class == kInvariant) {
Aart Bikf475bee2015-09-16 12:50:25 -0700502 if (phi->InputAt(1) == entry_phi) {
503 InductionInfo* initial = LookupInfo(loop, entry_phi->InputAt(0));
Aart Bik0d345cf2016-03-16 10:49:38 -0700504 return CreateInduction(kPeriodic, a, initial, type_);
Aart Bike609b7c2015-08-27 13:46:58 -0700505 }
Aart Bikf475bee2015-09-16 12:50:25 -0700506 InductionInfo* b = SolvePhi(phi, /* input_index */ 1);
507 if (b != nullptr && b->induction_class == kPeriodic) {
Aart Bik0d345cf2016-03-16 10:49:38 -0700508 return CreateInduction(kPeriodic, a, b, type_);
Aart Bik30efb4e2015-07-30 12:14:31 -0700509 }
510 }
511 }
Aart Bik30efb4e2015-07-30 12:14:31 -0700512 return nullptr;
513}
514
Aart Bike609b7c2015-08-27 13:46:58 -0700515HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::SolveAddSub(HLoopInformation* loop,
Aart Bikf475bee2015-09-16 12:50:25 -0700516 HInstruction* entry_phi,
Aart Bike609b7c2015-08-27 13:46:58 -0700517 HInstruction* instruction,
518 HInstruction* x,
519 HInstruction* y,
520 InductionOp op,
521 bool is_first_call) {
522 // Solve within a cycle over an addition or subtraction: adding or subtracting an
523 // invariant value, seeded from phi, keeps adding to the stride of the induction.
524 InductionInfo* b = LookupInfo(loop, y);
525 if (b != nullptr && b->induction_class == kInvariant) {
Aart Bikf475bee2015-09-16 12:50:25 -0700526 if (x == entry_phi) {
Aart Bik471a2032015-09-04 18:22:11 -0700527 return (op == kAdd) ? b : CreateInvariantOp(kNeg, nullptr, b);
Aart Bike609b7c2015-08-27 13:46:58 -0700528 }
529 auto it = cycle_.find(x);
530 if (it != cycle_.end()) {
531 InductionInfo* a = it->second;
532 if (a->induction_class == kInvariant) {
Aart Bik471a2032015-09-04 18:22:11 -0700533 return CreateInvariantOp(op, a, b);
Aart Bike609b7c2015-08-27 13:46:58 -0700534 }
Aart Bik30efb4e2015-07-30 12:14:31 -0700535 }
536 }
Aart Bike609b7c2015-08-27 13:46:58 -0700537
538 // Try some alternatives before failing.
539 if (op == kAdd) {
540 // Try the other way around for an addition if considered for first time.
541 if (is_first_call) {
Aart Bikf475bee2015-09-16 12:50:25 -0700542 return SolveAddSub(loop, entry_phi, instruction, y, x, op, false);
Aart Bike609b7c2015-08-27 13:46:58 -0700543 }
544 } else if (op == kSub) {
Aart Bikf475bee2015-09-16 12:50:25 -0700545 // Solve within a tight cycle that is formed by exactly two instructions,
546 // one phi and one update, for a periodic idiom of the form k = c - k;
547 if (y == entry_phi && entry_phi->InputCount() == 2 && instruction == entry_phi->InputAt(1)) {
Aart Bike609b7c2015-08-27 13:46:58 -0700548 InductionInfo* a = LookupInfo(loop, x);
549 if (a != nullptr && a->induction_class == kInvariant) {
Aart Bikf475bee2015-09-16 12:50:25 -0700550 InductionInfo* initial = LookupInfo(loop, entry_phi->InputAt(0));
Aart Bik0d345cf2016-03-16 10:49:38 -0700551 return CreateInduction(kPeriodic, CreateInvariantOp(kSub, a, initial), initial, type_);
Aart Bike609b7c2015-08-27 13:46:58 -0700552 }
553 }
554 }
555
Aart Bik30efb4e2015-07-30 12:14:31 -0700556 return nullptr;
557}
558
Aart Bik7dc96932016-10-12 10:01:05 -0700559HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::SolveXor(HLoopInformation* loop,
560 HInstruction* entry_phi,
561 HInstruction* instruction,
562 HInstruction* x,
563 HInstruction* y,
564 bool is_first_call) {
565 InductionInfo* b = LookupInfo(loop, y);
566 // Solve within a tight cycle on x = x ^ c.
567 if (b != nullptr && b->induction_class == kInvariant) {
568 if (x == entry_phi && entry_phi->InputCount() == 2 && instruction == entry_phi->InputAt(1)) {
569 InductionInfo* initial = LookupInfo(loop, entry_phi->InputAt(0));
570 return CreateInduction(kPeriodic, CreateInvariantOp(kXor, initial, b), initial, type_);
571 }
572 }
573 // Try the other way around if considered for first time.
574 if (is_first_call) {
575 return SolveXor(loop, entry_phi, instruction, y, x, false);
576 }
577 return nullptr;
578}
579
Aart Bik0d345cf2016-03-16 10:49:38 -0700580HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::SolveCnv(HTypeConversion* conversion) {
581 Primitive::Type from = conversion->GetInputType();
582 Primitive::Type to = conversion->GetResultType();
583 // A narrowing conversion is allowed within the cycle of a linear induction, provided that the
584 // narrowest encountered type is recorded with the induction to account for the precision loss.
585 if (IsNarrowingIntegralConversion(from, to)) {
586 auto it = cycle_.find(conversion->GetInput());
587 if (it != cycle_.end() && it->second->induction_class == kInvariant) {
588 type_ = Narrowest(type_, to);
589 return it->second;
590 }
591 }
592 return nullptr;
593}
594
Aart Bikd14c5952015-09-08 15:25:15 -0700595void HInductionVarAnalysis::VisitControl(HLoopInformation* loop) {
596 HInstruction* control = loop->GetHeader()->GetLastInstruction();
597 if (control->IsIf()) {
598 HIf* ifs = control->AsIf();
599 HBasicBlock* if_true = ifs->IfTrueSuccessor();
600 HBasicBlock* if_false = ifs->IfFalseSuccessor();
601 HInstruction* if_expr = ifs->InputAt(0);
602 // Determine if loop has following structure in header.
603 // loop-header: ....
604 // if (condition) goto X
605 if (if_expr->IsCondition()) {
606 HCondition* condition = if_expr->AsCondition();
607 InductionInfo* a = LookupInfo(loop, condition->InputAt(0));
608 InductionInfo* b = LookupInfo(loop, condition->InputAt(1));
609 Primitive::Type type = condition->InputAt(0)->GetType();
Aart Bik0d345cf2016-03-16 10:49:38 -0700610 // Determine if the loop control uses a known sequence on an if-exit (X outside) or on
611 // an if-iterate (X inside), expressed as if-iterate when passed into VisitCondition().
612 if (a == nullptr || b == nullptr) {
613 return; // Loop control is not a sequence.
Aart Bikd14c5952015-09-08 15:25:15 -0700614 } else if (if_true->GetLoopInformation() != loop && if_false->GetLoopInformation() == loop) {
615 VisitCondition(loop, a, b, type, condition->GetOppositeCondition());
616 } else if (if_true->GetLoopInformation() == loop && if_false->GetLoopInformation() != loop) {
617 VisitCondition(loop, a, b, type, condition->GetCondition());
618 }
619 }
620 }
621}
622
623void HInductionVarAnalysis::VisitCondition(HLoopInformation* loop,
624 InductionInfo* a,
625 InductionInfo* b,
626 Primitive::Type type,
627 IfCondition cmp) {
628 if (a->induction_class == kInvariant && b->induction_class == kLinear) {
Aart Bikf475bee2015-09-16 12:50:25 -0700629 // 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 -0700630 switch (cmp) {
631 case kCondLT: VisitCondition(loop, b, a, type, kCondGT); break;
632 case kCondLE: VisitCondition(loop, b, a, type, kCondGE); break;
633 case kCondGT: VisitCondition(loop, b, a, type, kCondLT); break;
634 case kCondGE: VisitCondition(loop, b, a, type, kCondLE); break;
Aart Bikf475bee2015-09-16 12:50:25 -0700635 case kCondNE: VisitCondition(loop, b, a, type, kCondNE); break;
Aart Bikd14c5952015-09-08 15:25:15 -0700636 default: break;
637 }
638 } else if (a->induction_class == kLinear && b->induction_class == kInvariant) {
Aart Bikf475bee2015-09-16 12:50:25 -0700639 // Analyze condition with induction at left-hand-side (e.g. i < U).
Aart Bik9401f532015-09-28 16:25:56 -0700640 InductionInfo* lower_expr = a->op_b;
641 InductionInfo* upper_expr = b;
Aart Bik97412c922016-02-19 20:14:38 -0800642 InductionInfo* stride_expr = a->op_a;
643 // Constant stride?
Aart Bik9401f532015-09-28 16:25:56 -0700644 int64_t stride_value = 0;
Aart Bik97412c922016-02-19 20:14:38 -0800645 if (!IsExact(stride_expr, &stride_value)) {
Aart Bikf475bee2015-09-16 12:50:25 -0700646 return;
647 }
Aart Bik358af832016-02-24 14:17:53 -0800648 // Rewrite condition i != U into strict end condition i < U or i > U if this end condition
649 // is reached exactly (tested by verifying if the loop has a unit stride and the non-strict
650 // condition would be always taken).
651 if (cmp == kCondNE && ((stride_value == +1 && IsTaken(lower_expr, upper_expr, kCondLE)) ||
652 (stride_value == -1 && IsTaken(lower_expr, upper_expr, kCondGE)))) {
Aart Bik9401f532015-09-28 16:25:56 -0700653 cmp = stride_value > 0 ? kCondLT : kCondGT;
Aart Bikd14c5952015-09-08 15:25:15 -0700654 }
Aart Bik0d345cf2016-03-16 10:49:38 -0700655 // Only accept integral condition. A mismatch between the type of condition and the induction
656 // is only allowed if the, necessarily narrower, induction range fits the narrower control.
657 if (type != Primitive::kPrimInt && type != Primitive::kPrimLong) {
658 return; // not integral
659 } else if (type != a->type &&
660 !FitsNarrowerControl(lower_expr, upper_expr, stride_value, a->type, cmp)) {
661 return; // mismatched type
662 }
Aart Bikf475bee2015-09-16 12:50:25 -0700663 // Normalize a linear loop control with a nonzero stride:
664 // stride > 0, either i < U or i <= U
665 // stride < 0, either i > U or i >= U
Aart Bikf475bee2015-09-16 12:50:25 -0700666 if ((stride_value > 0 && (cmp == kCondLT || cmp == kCondLE)) ||
667 (stride_value < 0 && (cmp == kCondGT || cmp == kCondGE))) {
Aart Bik97412c922016-02-19 20:14:38 -0800668 VisitTripCount(loop, lower_expr, upper_expr, stride_expr, stride_value, type, cmp);
Aart Bikf475bee2015-09-16 12:50:25 -0700669 }
Aart Bikd14c5952015-09-08 15:25:15 -0700670 }
671}
672
673void HInductionVarAnalysis::VisitTripCount(HLoopInformation* loop,
Aart Bik9401f532015-09-28 16:25:56 -0700674 InductionInfo* lower_expr,
675 InductionInfo* upper_expr,
Aart Bik97412c922016-02-19 20:14:38 -0800676 InductionInfo* stride_expr,
Aart Bik9401f532015-09-28 16:25:56 -0700677 int64_t stride_value,
Aart Bikd14c5952015-09-08 15:25:15 -0700678 Primitive::Type type,
Aart Bikf475bee2015-09-16 12:50:25 -0700679 IfCondition cmp) {
Aart Bikd14c5952015-09-08 15:25:15 -0700680 // Any loop of the general form:
681 //
682 // for (i = L; i <= U; i += S) // S > 0
683 // or for (i = L; i >= U; i += S) // S < 0
684 // .. i ..
685 //
686 // can be normalized into:
687 //
688 // for (n = 0; n < TC; n++) // where TC = (U + S - L) / S
689 // .. L + S * n ..
690 //
Aart Bik9401f532015-09-28 16:25:56 -0700691 // taking the following into consideration:
Aart Bikd14c5952015-09-08 15:25:15 -0700692 //
Aart Bik9401f532015-09-28 16:25:56 -0700693 // (1) Using the same precision, the TC (trip-count) expression should be interpreted as
694 // an unsigned entity, for example, as in the following loop that uses the full range:
695 // for (int i = INT_MIN; i < INT_MAX; i++) // TC = UINT_MAX
696 // (2) The TC is only valid if the loop is taken, otherwise TC = 0, as in:
Aart Bikd5cc6832016-06-22 16:34:46 -0700697 // for (int i = 12; i < U; i++) // TC = 0 when U <= 12
Aart Bik9401f532015-09-28 16:25:56 -0700698 // If this cannot be determined at compile-time, the TC is only valid within the
Aart Bik22f05872015-10-27 15:56:28 -0700699 // loop-body proper, not the loop-header unless enforced with an explicit taken-test.
Aart Bik9401f532015-09-28 16:25:56 -0700700 // (3) The TC is only valid if the loop is finite, otherwise TC has no value, as in:
701 // for (int i = 0; i <= U; i++) // TC = Inf when U = INT_MAX
702 // If this cannot be determined at compile-time, the TC is only valid when enforced
Aart Bik22f05872015-10-27 15:56:28 -0700703 // with an explicit finite-test.
Aart Bik9401f532015-09-28 16:25:56 -0700704 // (4) For loops which early-exits, the TC forms an upper bound, as in:
705 // for (int i = 0; i < 10 && ....; i++) // TC <= 10
Aart Bik22f05872015-10-27 15:56:28 -0700706 InductionInfo* trip_count = upper_expr;
Aart Bik9401f532015-09-28 16:25:56 -0700707 const bool is_taken = IsTaken(lower_expr, upper_expr, cmp);
708 const bool is_finite = IsFinite(upper_expr, stride_value, type, cmp);
709 const bool cancels = (cmp == kCondLT || cmp == kCondGT) && std::abs(stride_value) == 1;
Aart Bikd14c5952015-09-08 15:25:15 -0700710 if (!cancels) {
711 // Convert exclusive integral inequality into inclusive integral inequality,
712 // viz. condition i < U is i <= U - 1 and condition i > U is i >= U + 1.
Aart Bikf475bee2015-09-16 12:50:25 -0700713 if (cmp == kCondLT) {
Aart Bik22f05872015-10-27 15:56:28 -0700714 trip_count = CreateInvariantOp(kSub, trip_count, CreateConstant(1, type));
Aart Bikf475bee2015-09-16 12:50:25 -0700715 } else if (cmp == kCondGT) {
Aart Bik22f05872015-10-27 15:56:28 -0700716 trip_count = CreateInvariantOp(kAdd, trip_count, CreateConstant(1, type));
Aart Bikd14c5952015-09-08 15:25:15 -0700717 }
718 // Compensate for stride.
Aart Bik97412c922016-02-19 20:14:38 -0800719 trip_count = CreateInvariantOp(kAdd, trip_count, stride_expr);
Aart Bikd14c5952015-09-08 15:25:15 -0700720 }
Aart Bik97412c922016-02-19 20:14:38 -0800721 trip_count = CreateInvariantOp(
722 kDiv, CreateInvariantOp(kSub, trip_count, lower_expr), stride_expr);
Aart Bikd14c5952015-09-08 15:25:15 -0700723 // Assign the trip-count expression to the loop control. Clients that use the information
Aart Bik9401f532015-09-28 16:25:56 -0700724 // should be aware that the expression is only valid under the conditions listed above.
Aart Bik22f05872015-10-27 15:56:28 -0700725 InductionOp tcKind = kTripCountInBodyUnsafe; // needs both tests
Aart Bik9401f532015-09-28 16:25:56 -0700726 if (is_taken && is_finite) {
Aart Bik22f05872015-10-27 15:56:28 -0700727 tcKind = kTripCountInLoop; // needs neither test
Aart Bik9401f532015-09-28 16:25:56 -0700728 } else if (is_finite) {
Aart Bik22f05872015-10-27 15:56:28 -0700729 tcKind = kTripCountInBody; // needs taken-test
Aart Bik9401f532015-09-28 16:25:56 -0700730 } else if (is_taken) {
Aart Bik22f05872015-10-27 15:56:28 -0700731 tcKind = kTripCountInLoopUnsafe; // needs finite-test
Aart Bik9401f532015-09-28 16:25:56 -0700732 }
Aart Bik22f05872015-10-27 15:56:28 -0700733 InductionOp op = kNop;
734 switch (cmp) {
735 case kCondLT: op = kLT; break;
736 case kCondLE: op = kLE; break;
737 case kCondGT: op = kGT; break;
738 case kCondGE: op = kGE; break;
739 default: LOG(FATAL) << "CONDITION UNREACHABLE";
740 }
Aart Bik009cace2016-09-16 10:15:19 -0700741 // Associate trip count with control instruction, rather than the condition (even
742 // though it's its use) since former provides a convenient use-free placeholder.
743 HInstruction* control = loop->GetHeader()->GetLastInstruction();
Aart Bik22f05872015-10-27 15:56:28 -0700744 InductionInfo* taken_test = CreateInvariantOp(op, lower_expr, upper_expr);
Aart Bik009cace2016-09-16 10:15:19 -0700745 DCHECK(control->IsIf());
746 AssignInfo(loop, control, CreateTripCount(tcKind, trip_count, taken_test, type));
Aart Bik9401f532015-09-28 16:25:56 -0700747}
748
749bool HInductionVarAnalysis::IsTaken(InductionInfo* lower_expr,
750 InductionInfo* upper_expr,
751 IfCondition cmp) {
752 int64_t lower_value;
753 int64_t upper_value;
Aart Bik97412c922016-02-19 20:14:38 -0800754 switch (cmp) {
755 case kCondLT:
756 return IsAtMost(lower_expr, &lower_value)
757 && IsAtLeast(upper_expr, &upper_value)
758 && lower_value < upper_value;
759 case kCondLE:
760 return IsAtMost(lower_expr, &lower_value)
761 && IsAtLeast(upper_expr, &upper_value)
762 && lower_value <= upper_value;
763 case kCondGT:
764 return IsAtLeast(lower_expr, &lower_value)
765 && IsAtMost(upper_expr, &upper_value)
766 && lower_value > upper_value;
767 case kCondGE:
768 return IsAtLeast(lower_expr, &lower_value)
769 && IsAtMost(upper_expr, &upper_value)
770 && lower_value >= upper_value;
771 default:
772 LOG(FATAL) << "CONDITION UNREACHABLE";
Aart Bik9401f532015-09-28 16:25:56 -0700773 }
774 return false; // not certain, may be untaken
775}
776
777bool HInductionVarAnalysis::IsFinite(InductionInfo* upper_expr,
778 int64_t stride_value,
779 Primitive::Type type,
780 IfCondition cmp) {
Aart Bik0d345cf2016-03-16 10:49:38 -0700781 const int64_t min = Primitive::MinValueOfIntegralType(type);
782 const int64_t max = Primitive::MaxValueOfIntegralType(type);
Aart Bik9401f532015-09-28 16:25:56 -0700783 // Some rules under which it is certain at compile-time that the loop is finite.
784 int64_t value;
785 switch (cmp) {
786 case kCondLT:
787 return stride_value == 1 ||
Aart Bik97412c922016-02-19 20:14:38 -0800788 (IsAtMost(upper_expr, &value) && value <= (max - stride_value + 1));
Aart Bik9401f532015-09-28 16:25:56 -0700789 case kCondLE:
Aart Bik97412c922016-02-19 20:14:38 -0800790 return (IsAtMost(upper_expr, &value) && value <= (max - stride_value));
Aart Bik9401f532015-09-28 16:25:56 -0700791 case kCondGT:
792 return stride_value == -1 ||
Aart Bik97412c922016-02-19 20:14:38 -0800793 (IsAtLeast(upper_expr, &value) && value >= (min - stride_value - 1));
Aart Bik9401f532015-09-28 16:25:56 -0700794 case kCondGE:
Aart Bik97412c922016-02-19 20:14:38 -0800795 return (IsAtLeast(upper_expr, &value) && value >= (min - stride_value));
Aart Bike9f37602015-10-09 11:15:55 -0700796 default:
797 LOG(FATAL) << "CONDITION UNREACHABLE";
Aart Bik9401f532015-09-28 16:25:56 -0700798 }
799 return false; // not certain, may be infinite
Aart Bikd14c5952015-09-08 15:25:15 -0700800}
801
Aart Bik0d345cf2016-03-16 10:49:38 -0700802bool HInductionVarAnalysis::FitsNarrowerControl(InductionInfo* lower_expr,
803 InductionInfo* upper_expr,
804 int64_t stride_value,
805 Primitive::Type type,
806 IfCondition cmp) {
807 int64_t min = Primitive::MinValueOfIntegralType(type);
808 int64_t max = Primitive::MaxValueOfIntegralType(type);
809 // Inclusive test need one extra.
810 if (stride_value != 1 && stride_value != -1) {
811 return false; // non-unit stride
812 } else if (cmp == kCondLE) {
813 max--;
814 } else if (cmp == kCondGE) {
815 min++;
816 }
817 // Do both bounds fit the range?
Vladimir Marko0e2f2ff2016-03-22 12:31:54 +0000818 // Note: The `value` is initialized to please valgrind - the compiler can reorder
819 // the return value check with the `value` check, b/27651442 .
820 int64_t value = 0;
Aart Bik0d345cf2016-03-16 10:49:38 -0700821 return IsAtLeast(lower_expr, &value) && value >= min &&
822 IsAtMost(lower_expr, &value) && value <= max &&
823 IsAtLeast(upper_expr, &value) && value >= min &&
824 IsAtMost(upper_expr, &value) && value <= max;
825}
826
Aart Bik30efb4e2015-07-30 12:14:31 -0700827void HInductionVarAnalysis::AssignInfo(HLoopInformation* loop,
828 HInstruction* instruction,
829 InductionInfo* info) {
Aart Bike609b7c2015-08-27 13:46:58 -0700830 auto it = induction_.find(loop);
831 if (it == induction_.end()) {
832 it = induction_.Put(loop,
833 ArenaSafeMap<HInstruction*, InductionInfo*>(
Vladimir Marko5233f932015-09-29 19:01:15 +0100834 std::less<HInstruction*>(),
835 graph_->GetArena()->Adapter(kArenaAllocInductionVarAnalysis)));
Aart Bike609b7c2015-08-27 13:46:58 -0700836 }
837 it->second.Put(instruction, info);
Aart Bik30efb4e2015-07-30 12:14:31 -0700838}
839
Aart Bike609b7c2015-08-27 13:46:58 -0700840HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::LookupInfo(HLoopInformation* loop,
841 HInstruction* instruction) {
842 auto it = induction_.find(loop);
843 if (it != induction_.end()) {
844 auto loop_it = it->second.find(instruction);
845 if (loop_it != it->second.end()) {
846 return loop_it->second;
847 }
Aart Bik30efb4e2015-07-30 12:14:31 -0700848 }
Mingyao Yang4b467ed2015-11-19 17:04:22 -0800849 if (loop->IsDefinedOutOfTheLoop(instruction)) {
Aart Bik471a2032015-09-04 18:22:11 -0700850 InductionInfo* info = CreateInvariantFetch(instruction);
Aart Bike609b7c2015-08-27 13:46:58 -0700851 AssignInfo(loop, instruction, info);
852 return info;
853 }
854 return nullptr;
Aart Bik30efb4e2015-07-30 12:14:31 -0700855}
856
Aart Bikd14c5952015-09-08 15:25:15 -0700857HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::CreateConstant(int64_t value,
858 Primitive::Type type) {
859 if (type == Primitive::kPrimInt) {
860 return CreateInvariantFetch(graph_->GetIntConstant(value));
861 }
862 DCHECK_EQ(type, Primitive::kPrimLong);
863 return CreateInvariantFetch(graph_->GetLongConstant(value));
864}
865
Aart Bik471a2032015-09-04 18:22:11 -0700866HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::CreateSimplifiedInvariant(
867 InductionOp op,
868 InductionInfo* a,
869 InductionInfo* b) {
870 // Perform some light-weight simplifications during construction of a new invariant.
871 // This often safes memory and yields a more concise representation of the induction.
872 // More exhaustive simplifications are done by later phases once induction nodes are
873 // translated back into HIR code (e.g. by loop optimizations or BCE).
874 int64_t value = -1;
Aart Bik97412c922016-02-19 20:14:38 -0800875 if (IsExact(a, &value)) {
Aart Bik471a2032015-09-04 18:22:11 -0700876 if (value == 0) {
Aart Bik7dc96932016-10-12 10:01:05 -0700877 // Simplify 0 + b = b, 0 ^ b = b, 0 * b = 0.
878 if (op == kAdd || op == kXor) {
Aart Bik471a2032015-09-04 18:22:11 -0700879 return b;
880 } else if (op == kMul) {
881 return a;
882 }
Aart Bikd14c5952015-09-08 15:25:15 -0700883 } else if (op == kMul) {
884 // Simplify 1 * b = b, -1 * b = -b
885 if (value == 1) {
886 return b;
887 } else if (value == -1) {
Aart Bik7d57d7f2015-12-09 14:39:48 -0800888 return CreateSimplifiedInvariant(kNeg, nullptr, b);
Aart Bikd14c5952015-09-08 15:25:15 -0700889 }
Aart Bik471a2032015-09-04 18:22:11 -0700890 }
891 }
Aart Bik97412c922016-02-19 20:14:38 -0800892 if (IsExact(b, &value)) {
Aart Bik471a2032015-09-04 18:22:11 -0700893 if (value == 0) {
Aart Bik7dc96932016-10-12 10:01:05 -0700894 // Simplify a + 0 = a, a - 0 = a, a ^ 0 = a, a * 0 = 0, -0 = 0.
895 if (op == kAdd || op == kSub || op == kXor) {
Aart Bik471a2032015-09-04 18:22:11 -0700896 return a;
897 } else if (op == kMul || op == kNeg) {
898 return b;
899 }
Aart Bikd14c5952015-09-08 15:25:15 -0700900 } else if (op == kMul || op == kDiv) {
901 // Simplify a * 1 = a, a / 1 = a, a * -1 = -a, a / -1 = -a
902 if (value == 1) {
903 return a;
904 } else if (value == -1) {
Aart Bik7d57d7f2015-12-09 14:39:48 -0800905 return CreateSimplifiedInvariant(kNeg, nullptr, a);
Aart Bikd14c5952015-09-08 15:25:15 -0700906 }
Aart Bik471a2032015-09-04 18:22:11 -0700907 }
908 } else if (b->operation == kNeg) {
Aart Bikd14c5952015-09-08 15:25:15 -0700909 // Simplify a + (-b) = a - b, a - (-b) = a + b, -(-b) = b.
910 if (op == kAdd) {
Aart Bik7d57d7f2015-12-09 14:39:48 -0800911 return CreateSimplifiedInvariant(kSub, a, b->op_b);
Aart Bikd14c5952015-09-08 15:25:15 -0700912 } else if (op == kSub) {
Aart Bik7d57d7f2015-12-09 14:39:48 -0800913 return CreateSimplifiedInvariant(kAdd, a, b->op_b);
Aart Bikd14c5952015-09-08 15:25:15 -0700914 } else if (op == kNeg) {
915 return b->op_b;
Aart Bik471a2032015-09-04 18:22:11 -0700916 }
Aart Bik7d57d7f2015-12-09 14:39:48 -0800917 } else if (b->operation == kSub) {
918 // Simplify - (a - b) = b - a.
919 if (op == kNeg) {
920 return CreateSimplifiedInvariant(kSub, b->op_b, b->op_a);
921 }
Aart Bik471a2032015-09-04 18:22:11 -0700922 }
Aart Bik0d345cf2016-03-16 10:49:38 -0700923 return new (graph_->GetArena()) InductionInfo(kInvariant, op, a, b, nullptr, b->type);
Aart Bik471a2032015-09-04 18:22:11 -0700924}
925
Aart Bik97412c922016-02-19 20:14:38 -0800926bool HInductionVarAnalysis::IsExact(InductionInfo* info, int64_t* value) {
927 return InductionVarRange(this).IsConstant(info, InductionVarRange::kExact, value);
928}
929
930bool HInductionVarAnalysis::IsAtMost(InductionInfo* info, int64_t* value) {
931 return InductionVarRange(this).IsConstant(info, InductionVarRange::kAtMost, value);
932}
933
934bool HInductionVarAnalysis::IsAtLeast(InductionInfo* info, int64_t* value) {
935 return InductionVarRange(this).IsConstant(info, InductionVarRange::kAtLeast, value);
Aart Bik7d57d7f2015-12-09 14:39:48 -0800936}
937
Aart Bik30efb4e2015-07-30 12:14:31 -0700938bool HInductionVarAnalysis::InductionEqual(InductionInfo* info1,
939 InductionInfo* info2) {
940 // Test structural equality only, without accounting for simplifications.
941 if (info1 != nullptr && info2 != nullptr) {
942 return
943 info1->induction_class == info2->induction_class &&
944 info1->operation == info2->operation &&
945 info1->fetch == info2->fetch &&
Aart Bik78296912016-03-25 13:14:53 -0700946 info1->type == info2->type &&
Aart Bik30efb4e2015-07-30 12:14:31 -0700947 InductionEqual(info1->op_a, info2->op_a) &&
948 InductionEqual(info1->op_b, info2->op_b);
949 }
950 // Otherwise only two nullptrs are considered equal.
951 return info1 == info2;
952}
953
954std::string HInductionVarAnalysis::InductionToString(InductionInfo* info) {
955 if (info != nullptr) {
956 if (info->induction_class == kInvariant) {
957 std::string inv = "(";
958 inv += InductionToString(info->op_a);
959 switch (info->operation) {
Aart Bik22f05872015-10-27 15:56:28 -0700960 case kNop: inv += " @ "; break;
961 case kAdd: inv += " + "; break;
Aart Bik30efb4e2015-07-30 12:14:31 -0700962 case kSub:
Aart Bik22f05872015-10-27 15:56:28 -0700963 case kNeg: inv += " - "; break;
964 case kMul: inv += " * "; break;
965 case kDiv: inv += " / "; break;
Aart Bik7dc96932016-10-12 10:01:05 -0700966 case kXor: inv += " ^ "; break;
Aart Bik22f05872015-10-27 15:56:28 -0700967 case kLT: inv += " < "; break;
968 case kLE: inv += " <= "; break;
969 case kGT: inv += " > "; break;
970 case kGE: inv += " >= "; break;
Aart Bik30efb4e2015-07-30 12:14:31 -0700971 case kFetch:
Aart Bike609b7c2015-08-27 13:46:58 -0700972 DCHECK(info->fetch);
Aart Bik7d57d7f2015-12-09 14:39:48 -0800973 if (info->fetch->IsIntConstant()) {
974 inv += std::to_string(info->fetch->AsIntConstant()->GetValue());
975 } else if (info->fetch->IsLongConstant()) {
976 inv += std::to_string(info->fetch->AsLongConstant()->GetValue());
Aart Bik471a2032015-09-04 18:22:11 -0700977 } else {
978 inv += std::to_string(info->fetch->GetId()) + ":" + info->fetch->DebugName();
979 }
Aart Bik30efb4e2015-07-30 12:14:31 -0700980 break;
Aart Bik22f05872015-10-27 15:56:28 -0700981 case kTripCountInLoop: inv += " (TC-loop) "; break;
982 case kTripCountInBody: inv += " (TC-body) "; break;
983 case kTripCountInLoopUnsafe: inv += " (TC-loop-unsafe) "; break;
984 case kTripCountInBodyUnsafe: inv += " (TC-body-unsafe) "; break;
Aart Bik30efb4e2015-07-30 12:14:31 -0700985 }
986 inv += InductionToString(info->op_b);
Aart Bik0d345cf2016-03-16 10:49:38 -0700987 inv += ")";
988 return inv;
Aart Bik30efb4e2015-07-30 12:14:31 -0700989 } else {
Aart Bike609b7c2015-08-27 13:46:58 -0700990 DCHECK(info->operation == kNop);
Aart Bik30efb4e2015-07-30 12:14:31 -0700991 if (info->induction_class == kLinear) {
992 return "(" + InductionToString(info->op_a) + " * i + " +
Aart Bik0d345cf2016-03-16 10:49:38 -0700993 InductionToString(info->op_b) + "):" +
994 Primitive::PrettyDescriptor(info->type);
Aart Bik30efb4e2015-07-30 12:14:31 -0700995 } else if (info->induction_class == kWrapAround) {
996 return "wrap(" + InductionToString(info->op_a) + ", " +
Aart Bik0d345cf2016-03-16 10:49:38 -0700997 InductionToString(info->op_b) + "):" +
998 Primitive::PrettyDescriptor(info->type);
Aart Bik30efb4e2015-07-30 12:14:31 -0700999 } else if (info->induction_class == kPeriodic) {
1000 return "periodic(" + InductionToString(info->op_a) + ", " +
Aart Bik0d345cf2016-03-16 10:49:38 -07001001 InductionToString(info->op_b) + "):" +
1002 Primitive::PrettyDescriptor(info->type);
Aart Bik30efb4e2015-07-30 12:14:31 -07001003 }
1004 }
1005 }
1006 return "";
1007}
1008
1009} // namespace art