ssa_liveness_analysis.cc revision 6058455d486219994921b63a2d774dc9908415a2
1/*
2 * Copyright (C) 2014 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 "ssa_liveness_analysis.h"
18
19#include "base/bit_vector-inl.h"
20#include "code_generator.h"
21#include "nodes.h"
22
23namespace art {
24
25void SsaLivenessAnalysis::Analyze() {
26  LinearizeGraph();
27  NumberInstructions();
28  ComputeLiveness();
29}
30
31static bool IsLoop(HLoopInformation* info) {
32  return info != nullptr;
33}
34
35static bool InSameLoop(HLoopInformation* first_loop, HLoopInformation* second_loop) {
36  return first_loop == second_loop;
37}
38
39static bool IsInnerLoop(HLoopInformation* outer, HLoopInformation* inner) {
40  return (inner != outer)
41      && (inner != nullptr)
42      && (outer != nullptr)
43      && inner->IsIn(*outer);
44}
45
46static void AddToListForLinearization(GrowableArray<HBasicBlock*>* worklist, HBasicBlock* block) {
47  size_t insert_at = worklist->Size();
48  HLoopInformation* block_loop = block->GetLoopInformation();
49  for (; insert_at > 0; --insert_at) {
50    HBasicBlock* current = worklist->Get(insert_at - 1);
51    HLoopInformation* current_loop = current->GetLoopInformation();
52    if (InSameLoop(block_loop, current_loop)
53        || !IsLoop(current_loop)
54        || IsInnerLoop(current_loop, block_loop)) {
55      // The block can be processed immediately.
56      break;
57    }
58  }
59  worklist->InsertAt(insert_at, block);
60}
61
62void SsaLivenessAnalysis::LinearizeGraph() {
63  // Create a reverse post ordering with the following properties:
64  // - Blocks in a loop are consecutive,
65  // - Back-edge is the last block before loop exits.
66
67  // (1): Record the number of forward predecessors for each block. This is to
68  //      ensure the resulting order is reverse post order. We could use the
69  //      current reverse post order in the graph, but it would require making
70  //      order queries to a GrowableArray, which is not the best data structure
71  //      for it.
72  GrowableArray<uint32_t> forward_predecessors(graph_->GetArena(), graph_->GetBlocks().Size());
73  forward_predecessors.SetSize(graph_->GetBlocks().Size());
74  for (HReversePostOrderIterator it(*graph_); !it.Done(); it.Advance()) {
75    HBasicBlock* block = it.Current();
76    size_t number_of_forward_predecessors = block->GetPredecessors().size();
77    if (block->IsLoopHeader()) {
78      number_of_forward_predecessors -= block->GetLoopInformation()->NumberOfBackEdges();
79    }
80    forward_predecessors.Put(block->GetBlockId(), number_of_forward_predecessors);
81  }
82
83  // (2): Following a worklist approach, first start with the entry block, and
84  //      iterate over the successors. When all non-back edge predecessors of a
85  //      successor block are visited, the successor block is added in the worklist
86  //      following an order that satisfies the requirements to build our linear graph.
87  GrowableArray<HBasicBlock*> worklist(graph_->GetArena(), 1);
88  worklist.Add(graph_->GetEntryBlock());
89  do {
90    HBasicBlock* current = worklist.Pop();
91    graph_->linear_order_.Add(current);
92    for (HBasicBlock* successor : current->GetSuccessors()) {
93      int block_id = successor->GetBlockId();
94      size_t number_of_remaining_predecessors = forward_predecessors.Get(block_id);
95      if (number_of_remaining_predecessors == 1) {
96        AddToListForLinearization(&worklist, successor);
97      }
98      forward_predecessors.Put(block_id, number_of_remaining_predecessors - 1);
99    }
100  } while (!worklist.IsEmpty());
101}
102
103void SsaLivenessAnalysis::NumberInstructions() {
104  int ssa_index = 0;
105  size_t lifetime_position = 0;
106  // Each instruction gets a lifetime position, and a block gets a lifetime
107  // start and end position. Non-phi instructions have a distinct lifetime position than
108  // the block they are in. Phi instructions have the lifetime start of their block as
109  // lifetime position.
110  //
111  // Because the register allocator will insert moves in the graph, we need
112  // to differentiate between the start and end of an instruction. Adding 2 to
113  // the lifetime position for each instruction ensures the start of an
114  // instruction is different than the end of the previous instruction.
115  for (HLinearOrderIterator it(*graph_); !it.Done(); it.Advance()) {
116    HBasicBlock* block = it.Current();
117    block->SetLifetimeStart(lifetime_position);
118
119    for (HInstructionIterator inst_it(block->GetPhis()); !inst_it.Done(); inst_it.Advance()) {
120      HInstruction* current = inst_it.Current();
121      codegen_->AllocateLocations(current);
122      LocationSummary* locations = current->GetLocations();
123      if (locations != nullptr && locations->Out().IsValid()) {
124        instructions_from_ssa_index_.Add(current);
125        current->SetSsaIndex(ssa_index++);
126        current->SetLiveInterval(
127            LiveInterval::MakeInterval(graph_->GetArena(), current->GetType(), current));
128      }
129      current->SetLifetimePosition(lifetime_position);
130    }
131    lifetime_position += 2;
132
133    // Add a null marker to notify we are starting a block.
134    instructions_from_lifetime_position_.Add(nullptr);
135
136    for (HInstructionIterator inst_it(block->GetInstructions()); !inst_it.Done();
137         inst_it.Advance()) {
138      HInstruction* current = inst_it.Current();
139      codegen_->AllocateLocations(current);
140      LocationSummary* locations = current->GetLocations();
141      if (locations != nullptr && locations->Out().IsValid()) {
142        instructions_from_ssa_index_.Add(current);
143        current->SetSsaIndex(ssa_index++);
144        current->SetLiveInterval(
145            LiveInterval::MakeInterval(graph_->GetArena(), current->GetType(), current));
146      }
147      instructions_from_lifetime_position_.Add(current);
148      current->SetLifetimePosition(lifetime_position);
149      lifetime_position += 2;
150    }
151
152    block->SetLifetimeEnd(lifetime_position);
153  }
154  number_of_ssa_values_ = ssa_index;
155}
156
157void SsaLivenessAnalysis::ComputeLiveness() {
158  for (HLinearOrderIterator it(*graph_); !it.Done(); it.Advance()) {
159    HBasicBlock* block = it.Current();
160    block_infos_.Put(
161        block->GetBlockId(),
162        new (graph_->GetArena()) BlockInfo(graph_->GetArena(), *block, number_of_ssa_values_));
163  }
164
165  // Compute the live ranges, as well as the initial live_in, live_out, and kill sets.
166  // This method does not handle backward branches for the sets, therefore live_in
167  // and live_out sets are not yet correct.
168  ComputeLiveRanges();
169
170  // Do a fixed point calculation to take into account backward branches,
171  // that will update live_in of loop headers, and therefore live_out and live_in
172  // of blocks in the loop.
173  ComputeLiveInAndLiveOutSets();
174}
175
176void SsaLivenessAnalysis::ComputeLiveRanges() {
177  // Do a post order visit, adding inputs of instructions live in the block where
178  // that instruction is defined, and killing instructions that are being visited.
179  for (HLinearPostOrderIterator it(*graph_); !it.Done(); it.Advance()) {
180    HBasicBlock* block = it.Current();
181
182    BitVector* kill = GetKillSet(*block);
183    BitVector* live_in = GetLiveInSet(*block);
184
185    // Set phi inputs of successors of this block corresponding to this block
186    // as live_in.
187    for (HBasicBlock* successor : block->GetSuccessors()) {
188      live_in->Union(GetLiveInSet(*successor));
189      size_t phi_input_index = successor->GetPredecessorIndexOf(block);
190      for (HInstructionIterator inst_it(successor->GetPhis()); !inst_it.Done(); inst_it.Advance()) {
191        HInstruction* phi = inst_it.Current();
192        HInstruction* input = phi->InputAt(phi_input_index);
193        input->GetLiveInterval()->AddPhiUse(phi, phi_input_index, block);
194        // A phi input whose last user is the phi dies at the end of the predecessor block,
195        // and not at the phi's lifetime position.
196        live_in->SetBit(input->GetSsaIndex());
197      }
198    }
199
200    // Add a range that covers this block to all instructions live_in because of successors.
201    // Instructions defined in this block will have their start of the range adjusted.
202    for (uint32_t idx : live_in->Indexes()) {
203      HInstruction* current = instructions_from_ssa_index_.Get(idx);
204      current->GetLiveInterval()->AddRange(block->GetLifetimeStart(), block->GetLifetimeEnd());
205    }
206
207    for (HBackwardInstructionIterator back_it(block->GetInstructions()); !back_it.Done();
208         back_it.Advance()) {
209      HInstruction* current = back_it.Current();
210      if (current->HasSsaIndex()) {
211        // Kill the instruction and shorten its interval.
212        kill->SetBit(current->GetSsaIndex());
213        live_in->ClearBit(current->GetSsaIndex());
214        current->GetLiveInterval()->SetFrom(current->GetLifetimePosition());
215      }
216
217      // Process the environment first, because we know their uses come after
218      // or at the same liveness position of inputs.
219      for (HEnvironment* environment = current->GetEnvironment();
220           environment != nullptr;
221           environment = environment->GetParent()) {
222        // Handle environment uses. See statements (b) and (c) of the
223        // SsaLivenessAnalysis.
224        for (size_t i = 0, e = environment->Size(); i < e; ++i) {
225          HInstruction* instruction = environment->GetInstructionAt(i);
226          bool should_be_live = ShouldBeLiveForEnvironment(current, instruction);
227          if (should_be_live) {
228            DCHECK(instruction->HasSsaIndex());
229            live_in->SetBit(instruction->GetSsaIndex());
230          }
231          if (instruction != nullptr) {
232            instruction->GetLiveInterval()->AddUse(
233                current, environment, i, should_be_live);
234          }
235        }
236      }
237
238      // All inputs of an instruction must be live.
239      for (size_t i = 0, e = current->InputCount(); i < e; ++i) {
240        HInstruction* input = current->InputAt(i);
241        // Some instructions 'inline' their inputs, that is they do not need
242        // to be materialized.
243        if (input->HasSsaIndex() && current->GetLocations()->InAt(i).IsValid()) {
244          live_in->SetBit(input->GetSsaIndex());
245          input->GetLiveInterval()->AddUse(current, /* environment */ nullptr, i);
246        }
247      }
248    }
249
250    // Kill phis defined in this block.
251    for (HInstructionIterator inst_it(block->GetPhis()); !inst_it.Done(); inst_it.Advance()) {
252      HInstruction* current = inst_it.Current();
253      if (current->HasSsaIndex()) {
254        kill->SetBit(current->GetSsaIndex());
255        live_in->ClearBit(current->GetSsaIndex());
256        LiveInterval* interval = current->GetLiveInterval();
257        DCHECK((interval->GetFirstRange() == nullptr)
258               || (interval->GetStart() == current->GetLifetimePosition()));
259        interval->SetFrom(current->GetLifetimePosition());
260      }
261    }
262
263    if (block->IsLoopHeader()) {
264      size_t last_position = block->GetLoopInformation()->GetLifetimeEnd();
265      // For all live_in instructions at the loop header, we need to create a range
266      // that covers the full loop.
267      for (uint32_t idx : live_in->Indexes()) {
268        HInstruction* current = instructions_from_ssa_index_.Get(idx);
269        current->GetLiveInterval()->AddLoopRange(block->GetLifetimeStart(), last_position);
270      }
271    }
272  }
273}
274
275void SsaLivenessAnalysis::ComputeLiveInAndLiveOutSets() {
276  bool changed;
277  do {
278    changed = false;
279
280    for (HPostOrderIterator it(*graph_); !it.Done(); it.Advance()) {
281      const HBasicBlock& block = *it.Current();
282
283      // The live_in set depends on the kill set (which does not
284      // change in this loop), and the live_out set.  If the live_out
285      // set does not change, there is no need to update the live_in set.
286      if (UpdateLiveOut(block) && UpdateLiveIn(block)) {
287        changed = true;
288      }
289    }
290  } while (changed);
291}
292
293bool SsaLivenessAnalysis::UpdateLiveOut(const HBasicBlock& block) {
294  BitVector* live_out = GetLiveOutSet(block);
295  bool changed = false;
296  // The live_out set of a block is the union of live_in sets of its successors.
297  for (HBasicBlock* successor : block.GetSuccessors()) {
298    if (live_out->Union(GetLiveInSet(*successor))) {
299      changed = true;
300    }
301  }
302  return changed;
303}
304
305
306bool SsaLivenessAnalysis::UpdateLiveIn(const HBasicBlock& block) {
307  BitVector* live_out = GetLiveOutSet(block);
308  BitVector* kill = GetKillSet(block);
309  BitVector* live_in = GetLiveInSet(block);
310  // If live_out is updated (because of backward branches), we need to make
311  // sure instructions in live_out are also in live_in, unless they are killed
312  // by this block.
313  return live_in->UnionIfNotIn(live_out, kill);
314}
315
316static int RegisterOrLowRegister(Location location) {
317  return location.IsPair() ? location.low() : location.reg();
318}
319
320int LiveInterval::FindFirstRegisterHint(size_t* free_until,
321                                        const SsaLivenessAnalysis& liveness) const {
322  DCHECK(!IsHighInterval());
323  if (IsTemp()) return kNoRegister;
324
325  if (GetParent() == this && defined_by_ != nullptr) {
326    // This is the first interval for the instruction. Try to find
327    // a register based on its definition.
328    DCHECK_EQ(defined_by_->GetLiveInterval(), this);
329    int hint = FindHintAtDefinition();
330    if (hint != kNoRegister && free_until[hint] > GetStart()) {
331      return hint;
332    }
333  }
334
335  if (IsSplit() && liveness.IsAtBlockBoundary(GetStart() / 2)) {
336    // If the start of this interval is at a block boundary, we look at the
337    // location of the interval in blocks preceding the block this interval
338    // starts at. If one location is a register we return it as a hint. This
339    // will avoid a move between the two blocks.
340    HBasicBlock* block = liveness.GetBlockFromPosition(GetStart() / 2);
341    size_t next_register_use = FirstRegisterUse();
342    for (HBasicBlock* predecessor : block->GetPredecessors()) {
343      size_t position = predecessor->GetLifetimeEnd() - 1;
344      // We know positions above GetStart() do not have a location yet.
345      if (position < GetStart()) {
346        LiveInterval* existing = GetParent()->GetSiblingAt(position);
347        if (existing != nullptr
348            && existing->HasRegister()
349            // It's worth using that register if it is available until
350            // the next use.
351            && (free_until[existing->GetRegister()] >= next_register_use)) {
352          return existing->GetRegister();
353        }
354      }
355    }
356  }
357
358  UsePosition* use = first_use_;
359  size_t start = GetStart();
360  size_t end = GetEnd();
361  while (use != nullptr && use->GetPosition() <= end) {
362    size_t use_position = use->GetPosition();
363    if (use_position >= start && !use->IsSynthesized()) {
364      HInstruction* user = use->GetUser();
365      size_t input_index = use->GetInputIndex();
366      if (user->IsPhi()) {
367        // If the phi has a register, try to use the same.
368        Location phi_location = user->GetLiveInterval()->ToLocation();
369        if (phi_location.IsRegisterKind()) {
370          DCHECK(SameRegisterKind(phi_location));
371          int reg = RegisterOrLowRegister(phi_location);
372          if (free_until[reg] >= use_position) {
373            return reg;
374          }
375        }
376        // If the instruction dies at the phi assignment, we can try having the
377        // same register.
378        if (end == user->GetBlock()->GetPredecessor(input_index)->GetLifetimeEnd()) {
379          for (size_t i = 0, e = user->InputCount(); i < e; ++i) {
380            if (i == input_index) {
381              continue;
382            }
383            HInstruction* input = user->InputAt(i);
384            Location location = input->GetLiveInterval()->GetLocationAt(
385                user->GetBlock()->GetPredecessor(i)->GetLifetimeEnd() - 1);
386            if (location.IsRegisterKind()) {
387              int reg = RegisterOrLowRegister(location);
388              if (free_until[reg] >= use_position) {
389                return reg;
390              }
391            }
392          }
393        }
394      } else {
395        // If the instruction is expected in a register, try to use it.
396        LocationSummary* locations = user->GetLocations();
397        Location expected = locations->InAt(use->GetInputIndex());
398        // We use the user's lifetime position - 1 (and not `use_position`) because the
399        // register is blocked at the beginning of the user.
400        size_t position = user->GetLifetimePosition() - 1;
401        if (expected.IsRegisterKind()) {
402          DCHECK(SameRegisterKind(expected));
403          int reg = RegisterOrLowRegister(expected);
404          if (free_until[reg] >= position) {
405            return reg;
406          }
407        }
408      }
409    }
410    use = use->GetNext();
411  }
412
413  return kNoRegister;
414}
415
416int LiveInterval::FindHintAtDefinition() const {
417  if (defined_by_->IsPhi()) {
418    // Try to use the same register as one of the inputs.
419    const ArenaVector<HBasicBlock*>& predecessors = defined_by_->GetBlock()->GetPredecessors();
420    for (size_t i = 0, e = defined_by_->InputCount(); i < e; ++i) {
421      HInstruction* input = defined_by_->InputAt(i);
422      DCHECK_LT(i, predecessors.size());
423      size_t end = predecessors[i]->GetLifetimeEnd();
424      LiveInterval* input_interval = input->GetLiveInterval()->GetSiblingAt(end - 1);
425      if (input_interval->GetEnd() == end) {
426        // If the input dies at the end of the predecessor, we know its register can
427        // be reused.
428        Location input_location = input_interval->ToLocation();
429        if (input_location.IsRegisterKind()) {
430          DCHECK(SameRegisterKind(input_location));
431          return RegisterOrLowRegister(input_location);
432        }
433      }
434    }
435  } else {
436    LocationSummary* locations = GetDefinedBy()->GetLocations();
437    Location out = locations->Out();
438    if (out.IsUnallocated() && out.GetPolicy() == Location::kSameAsFirstInput) {
439      // Try to use the same register as the first input.
440      LiveInterval* input_interval =
441          GetDefinedBy()->InputAt(0)->GetLiveInterval()->GetSiblingAt(GetStart() - 1);
442      if (input_interval->GetEnd() == GetStart()) {
443        // If the input dies at the start of this instruction, we know its register can
444        // be reused.
445        Location location = input_interval->ToLocation();
446        if (location.IsRegisterKind()) {
447          DCHECK(SameRegisterKind(location));
448          return RegisterOrLowRegister(location);
449        }
450      }
451    }
452  }
453  return kNoRegister;
454}
455
456bool LiveInterval::SameRegisterKind(Location other) const {
457  if (IsFloatingPoint()) {
458    if (IsLowInterval() || IsHighInterval()) {
459      return other.IsFpuRegisterPair();
460    } else {
461      return other.IsFpuRegister();
462    }
463  } else {
464    if (IsLowInterval() || IsHighInterval()) {
465      return other.IsRegisterPair();
466    } else {
467      return other.IsRegister();
468    }
469  }
470}
471
472bool LiveInterval::NeedsTwoSpillSlots() const {
473  return type_ == Primitive::kPrimLong || type_ == Primitive::kPrimDouble;
474}
475
476Location LiveInterval::ToLocation() const {
477  DCHECK(!IsHighInterval());
478  if (HasRegister()) {
479    if (IsFloatingPoint()) {
480      if (HasHighInterval()) {
481        return Location::FpuRegisterPairLocation(GetRegister(), GetHighInterval()->GetRegister());
482      } else {
483        return Location::FpuRegisterLocation(GetRegister());
484      }
485    } else {
486      if (HasHighInterval()) {
487        return Location::RegisterPairLocation(GetRegister(), GetHighInterval()->GetRegister());
488      } else {
489        return Location::RegisterLocation(GetRegister());
490      }
491    }
492  } else {
493    HInstruction* defined_by = GetParent()->GetDefinedBy();
494    if (defined_by->IsConstant()) {
495      return defined_by->GetLocations()->Out();
496    } else if (GetParent()->HasSpillSlot()) {
497      if (NeedsTwoSpillSlots()) {
498        return Location::DoubleStackSlot(GetParent()->GetSpillSlot());
499      } else {
500        return Location::StackSlot(GetParent()->GetSpillSlot());
501      }
502    } else {
503      return Location();
504    }
505  }
506}
507
508Location LiveInterval::GetLocationAt(size_t position) {
509  LiveInterval* sibling = GetSiblingAt(position);
510  DCHECK(sibling != nullptr);
511  return sibling->ToLocation();
512}
513
514LiveInterval* LiveInterval::GetSiblingAt(size_t position) {
515  LiveInterval* current = this;
516  while (current != nullptr && !current->IsDefinedAt(position)) {
517    current = current->GetNextSibling();
518  }
519  return current;
520}
521
522}  // namespace art
523