1// Copyright 2013 the V8 project authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "src/crankshaft/hydrogen-dehoist.h"
6
7#include "src/base/safe_math.h"
8#include "src/objects-inl.h"
9
10namespace v8 {
11namespace internal {
12
13static void DehoistArrayIndex(ArrayInstructionInterface* array_operation) {
14  HValue* index = array_operation->GetKey()->ActualValue();
15  if (!index->representation().IsSmiOrInteger32()) return;
16  if (!index->IsAdd() && !index->IsSub()) return;
17
18  HConstant* constant;
19  HValue* subexpression;
20  HBinaryOperation* binary_operation = HBinaryOperation::cast(index);
21  if (binary_operation->left()->IsConstant() && index->IsAdd()) {
22    subexpression = binary_operation->right();
23    constant = HConstant::cast(binary_operation->left());
24  } else if (binary_operation->right()->IsConstant()) {
25    subexpression = binary_operation->left();
26    constant = HConstant::cast(binary_operation->right());
27  } else {
28    return;
29  }
30
31  if (!constant->HasInteger32Value()) return;
32  v8::base::internal::CheckedNumeric<int32_t> checked_value =
33      constant->Integer32Value();
34  int32_t sign = binary_operation->IsSub() ? -1 : 1;
35  checked_value = checked_value * sign;
36
37  // Multiply value by elements size, bailing out on overflow.
38  int32_t elements_kind_size =
39      1 << ElementsKindToShiftSize(array_operation->elements_kind());
40  checked_value = checked_value * elements_kind_size;
41  if (!checked_value.IsValid()) return;
42  int32_t value = checked_value.ValueOrDie();
43  if (value < 0) return;
44
45  // Ensure that the array operation can add value to existing base offset
46  // without overflowing.
47  if (!array_operation->TryIncreaseBaseOffset(value)) return;
48
49  array_operation->SetKey(subexpression);
50  if (binary_operation->HasNoUses()) {
51    binary_operation->DeleteAndReplaceWith(NULL);
52  }
53
54  array_operation->SetDehoisted(true);
55}
56
57
58void HDehoistIndexComputationsPhase::Run() {
59  const ZoneList<HBasicBlock*>* blocks(graph()->blocks());
60  for (int i = 0; i < blocks->length(); ++i) {
61    for (HInstructionIterator it(blocks->at(i)); !it.Done(); it.Advance()) {
62      HInstruction* instr = it.Current();
63      if (instr->IsLoadKeyed()) {
64        DehoistArrayIndex(HLoadKeyed::cast(instr));
65      } else if (instr->IsStoreKeyed()) {
66        DehoistArrayIndex(HStoreKeyed::cast(instr));
67      }
68    }
69  }
70}
71
72}  // namespace internal
73}  // namespace v8
74