node-matchers.h 27.1 KB
Newer Older
1 2 3 4 5 6 7
// Copyright 2014 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef V8_COMPILER_NODE_MATCHERS_H_
#define V8_COMPILER_NODE_MATCHERS_H_

8
#include <cmath>
9
#include <limits>
10

11
#include "src/base/bounds.h"
12
#include "src/base/compiler-specific.h"
13
#include "src/base/numbers/double.h"
14 15
#include "src/codegen/external-reference.h"
#include "src/common/globals.h"
16
#include "src/compiler/common-operator.h"
17
#include "src/compiler/machine-operator.h"
18
#include "src/compiler/node.h"
19
#include "src/compiler/operator.h"
20
#include "src/objects/heap-object.h"
21 22 23 24 25

namespace v8 {
namespace internal {
namespace compiler {

26 27
class JSHeapBroker;

28 29 30 31 32
// A pattern matcher for nodes.
struct NodeMatcher {
  explicit NodeMatcher(Node* node) : node_(node) {}

  Node* node() const { return node_; }
33
  const Operator* op() const { return node()->op(); }
34 35 36 37 38 39 40
  IrOpcode::Value opcode() const { return node()->opcode(); }

  bool HasProperty(Operator::Property property) const {
    return op()->HasProperty(property);
  }
  Node* InputAt(int index) const { return node()->InputAt(index); }

41 42
  bool Equals(const Node* node) const { return node_ == node; }

43 44
  bool IsComparison() const;

45
#define DEFINE_IS_OPCODE(Opcode, ...) \
46 47 48 49 50 51 52 53
  bool Is##Opcode() const { return opcode() == IrOpcode::k##Opcode; }
  ALL_OP_LIST(DEFINE_IS_OPCODE)
#undef DEFINE_IS_OPCODE

 private:
  Node* node_;
};

54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
inline Node* SkipValueIdentities(Node* node) {
#ifdef DEBUG
  bool seen_fold_constant = false;
#endif
  do {
#ifdef DEBUG
    if (node->opcode() == IrOpcode::kFoldConstant) {
      DCHECK(!seen_fold_constant);
      seen_fold_constant = true;
    }
#endif
  } while (NodeProperties::IsValueIdentity(node, &node));
  DCHECK_NOT_NULL(node);
  return node;
}
69 70

// A pattern matcher for abitrary value constants.
71 72 73 74 75 76 77
//
// Note that value identities on the input node are skipped when matching. The
// resolved value may not be a parameter of the input node. The node() method
// returns the unmodified input node. This is by design, as reducers may wish to
// match value constants but delay reducing the node until a later phase. For
// example, binary operator reducers may opt to keep FoldConstant operands while
// applying a reduction that match on the constant value of the FoldConstant.
78
template <typename T, IrOpcode::Value kOpcode>
79
struct ValueMatcher : public NodeMatcher {
80
  using ValueType = T;
81

82 83 84 85 86 87
  explicit ValueMatcher(Node* node)
      : NodeMatcher(node), resolved_value_(), has_resolved_value_(false) {
    node = SkipValueIdentities(node);
    has_resolved_value_ = node->opcode() == kOpcode;
    if (has_resolved_value_) {
      resolved_value_ = OpParameter<T>(node->op());
88
    }
89 90
  }

91 92
  bool HasResolvedValue() const { return has_resolved_value_; }
  const T& ResolvedValue() const {
93
    CHECK(HasResolvedValue());
94
    return resolved_value_;
95 96 97
  }

 private:
98 99
  T resolved_value_;
  bool has_resolved_value_;
100 101
};

102 103 104
template <>
inline ValueMatcher<uint32_t, IrOpcode::kInt32Constant>::ValueMatcher(
    Node* node)
105 106 107 108 109
    : NodeMatcher(node), resolved_value_(), has_resolved_value_(false) {
  node = SkipValueIdentities(node);
  has_resolved_value_ = node->opcode() == IrOpcode::kInt32Constant;
  if (has_resolved_value_) {
    resolved_value_ = static_cast<uint32_t>(OpParameter<int32_t>(node->op()));
110 111 112
  }
}

113 114
template <>
inline ValueMatcher<int64_t, IrOpcode::kInt64Constant>::ValueMatcher(Node* node)
115 116 117 118 119 120 121 122
    : NodeMatcher(node), resolved_value_(), has_resolved_value_(false) {
  node = SkipValueIdentities(node);
  if (node->opcode() == IrOpcode::kInt32Constant) {
    resolved_value_ = OpParameter<int32_t>(node->op());
    has_resolved_value_ = true;
  } else if (node->opcode() == IrOpcode::kInt64Constant) {
    resolved_value_ = OpParameter<int64_t>(node->op());
    has_resolved_value_ = true;
123 124 125 126 127 128
  }
}

template <>
inline ValueMatcher<uint64_t, IrOpcode::kInt64Constant>::ValueMatcher(
    Node* node)
129 130 131 132 133 134 135 136
    : NodeMatcher(node), resolved_value_(), has_resolved_value_(false) {
  node = SkipValueIdentities(node);
  if (node->opcode() == IrOpcode::kInt32Constant) {
    resolved_value_ = static_cast<uint32_t>(OpParameter<int32_t>(node->op()));
    has_resolved_value_ = true;
  } else if (node->opcode() == IrOpcode::kInt64Constant) {
    resolved_value_ = static_cast<uint64_t>(OpParameter<int64_t>(node->op()));
    has_resolved_value_ = true;
137 138
  }
}
139

140
// A pattern matcher for integer constants.
141
template <typename T, IrOpcode::Value kOpcode>
142
struct IntMatcher final : public ValueMatcher<T, kOpcode> {
143
  explicit IntMatcher(Node* node) : ValueMatcher<T, kOpcode>(node) {}
144

145
  bool Is(const T& value) const {
146
    return this->HasResolvedValue() && this->ResolvedValue() == value;
147 148
  }
  bool IsInRange(const T& low, const T& high) const {
149 150
    return this->HasResolvedValue() &&
           base::IsInRange(this->ResolvedValue(), low, high);
151
  }
152
  bool IsMultipleOf(T n) const {
153
    return this->HasResolvedValue() && (this->ResolvedValue() % n) == 0;
154
  }
155
  bool IsPowerOf2() const {
156 157
    return this->HasResolvedValue() && this->ResolvedValue() > 0 &&
           (this->ResolvedValue() & (this->ResolvedValue() - 1)) == 0;
158
  }
159
  bool IsNegativePowerOf2() const {
160 161 162 163 164 165
    return this->HasResolvedValue() && this->ResolvedValue() < 0 &&
           ((this->ResolvedValue() == std::numeric_limits<T>::min()) ||
            (-this->ResolvedValue() & (-this->ResolvedValue() - 1)) == 0);
  }
  bool IsNegative() const {
    return this->HasResolvedValue() && this->ResolvedValue() < 0;
166
  }
167 168
};

169 170 171 172
using Int32Matcher = IntMatcher<int32_t, IrOpcode::kInt32Constant>;
using Uint32Matcher = IntMatcher<uint32_t, IrOpcode::kInt32Constant>;
using Int64Matcher = IntMatcher<int64_t, IrOpcode::kInt64Constant>;
using Uint64Matcher = IntMatcher<uint64_t, IrOpcode::kInt64Constant>;
173 174
using V128ConstMatcher =
    ValueMatcher<S128ImmediateParameter, IrOpcode::kS128Const>;
175
#if V8_HOST_ARCH_32_BIT
176 177
using IntPtrMatcher = Int32Matcher;
using UintPtrMatcher = Uint32Matcher;
178
#else
179 180
using IntPtrMatcher = Int64Matcher;
using UintPtrMatcher = Uint64Matcher;
181
#endif
182 183 184


// A pattern matcher for floating point constants.
185
template <typename T, IrOpcode::Value kOpcode>
186
struct FloatMatcher final : public ValueMatcher<T, kOpcode> {
187
  explicit FloatMatcher(Node* node) : ValueMatcher<T, kOpcode>(node) {}
188

189
  bool Is(const T& value) const {
190
    return this->HasResolvedValue() && this->ResolvedValue() == value;
191 192
  }
  bool IsInRange(const T& low, const T& high) const {
193 194
    return this->HasResolvedValue() && low <= this->ResolvedValue() &&
           this->ResolvedValue() <= high;
195
  }
196
  bool IsMinusZero() const {
197 198 199 200 201 202 203 204 205 206
    return this->Is(0.0) && std::signbit(this->ResolvedValue());
  }
  bool IsNegative() const {
    return this->HasResolvedValue() && this->ResolvedValue() < 0.0;
  }
  bool IsNaN() const {
    return this->HasResolvedValue() && std::isnan(this->ResolvedValue());
  }
  bool IsZero() const {
    return this->Is(0.0) && !std::signbit(this->ResolvedValue());
207
  }
208
  bool IsNormal() const {
209
    return this->HasResolvedValue() && std::isnormal(this->ResolvedValue());
210
  }
211
  bool IsInteger() const {
212 213
    return this->HasResolvedValue() &&
           std::nearbyint(this->ResolvedValue()) == this->ResolvedValue();
214
  }
215
  bool IsPositiveOrNegativePowerOf2() const {
216
    if (!this->HasResolvedValue() || (this->ResolvedValue() == 0.0)) {
217 218
      return false;
    }
219
    base::Double value = base::Double(this->ResolvedValue());
220
    return !value.IsInfinite() && base::bits::IsPowerOfTwo(value.Significand());
221
  }
222 223
};

224 225 226
using Float32Matcher = FloatMatcher<float, IrOpcode::kFloat32Constant>;
using Float64Matcher = FloatMatcher<double, IrOpcode::kFloat64Constant>;
using NumberMatcher = FloatMatcher<double, IrOpcode::kNumberConstant>;
227

228
// A pattern matcher for heap object constants.
229 230 231 232 233
template <IrOpcode::Value kHeapConstantOpcode>
struct HeapObjectMatcherImpl final
    : public ValueMatcher<Handle<HeapObject>, kHeapConstantOpcode> {
  explicit HeapObjectMatcherImpl(Node* node)
      : ValueMatcher<Handle<HeapObject>, kHeapConstantOpcode>(node) {}
234 235

  bool Is(Handle<HeapObject> const& value) const {
236 237
    return this->HasResolvedValue() &&
           this->ResolvedValue().address() == value.address();
238
  }
239

240
  HeapObjectRef Ref(JSHeapBroker* broker) const {
241 242 243 244 245 246 247 248
    // TODO(jgruber,chromium:1209798): Using kAssumeMemoryFence works around
    // the fact that the graph stores handles (and not refs). The assumption is
    // that any handle inserted into the graph is safe to read; but we don't
    // preserve the reason why it is safe to read. Thus we must over-approximate
    // here and assume the existence of a memory fence. In the future, we should
    // consider having the graph store ObjectRefs or ObjectData pointer instead,
    // which would make new ref construction here unnecessary.
    return MakeRefAssumeMemoryFence(broker, this->ResolvedValue());
249
  }
250 251
};

252 253 254
using HeapObjectMatcher = HeapObjectMatcherImpl<IrOpcode::kHeapConstant>;
using CompressedHeapObjectMatcher =
    HeapObjectMatcherImpl<IrOpcode::kCompressedHeapConstant>;
255

256
// A pattern matcher for external reference constants.
257
struct ExternalReferenceMatcher final
258 259 260
    : public ValueMatcher<ExternalReference, IrOpcode::kExternalConstant> {
  explicit ExternalReferenceMatcher(Node* node)
      : ValueMatcher<ExternalReference, IrOpcode::kExternalConstant>(node) {}
261
  bool Is(const ExternalReference& value) const {
262
    return this->HasResolvedValue() && this->ResolvedValue() == value;
263
  }
264 265 266 267 268 269 270 271 272 273
};


// For shorter pattern matching code, this struct matches the inputs to
// machine-level load operations.
template <typename Object>
struct LoadMatcher : public NodeMatcher {
  explicit LoadMatcher(Node* node)
      : NodeMatcher(node), object_(InputAt(0)), index_(InputAt(1)) {}

274
  using ObjectMatcher = Object;
275 276 277 278 279 280 281 282 283 284

  Object const& object() const { return object_; }
  IntPtrMatcher const& index() const { return index_; }

 private:
  Object const object_;
  IntPtrMatcher const index_;
};


285 286 287 288
// For shorter pattern matching code, this struct matches both the left and
// right hand sides of a binary operation and can put constants on the right
// if they appear on the left hand side of a commutative operation.
template <typename Left, typename Right>
289
struct BinopMatcher : public NodeMatcher {
290 291 292 293
  explicit BinopMatcher(Node* node)
      : NodeMatcher(node), left_(InputAt(0)), right_(InputAt(1)) {
    if (HasProperty(Operator::kCommutative)) PutConstantOnRight();
  }
294 295 296 297
  BinopMatcher(Node* node, bool allow_input_swap)
      : NodeMatcher(node), left_(InputAt(0)), right_(InputAt(1)) {
    if (allow_input_swap) PutConstantOnRight();
  }
298

299 300
  using LeftMatcher = Left;
  using RightMatcher = Right;
301

302 303 304
  const Left& left() const { return left_; }
  const Right& right() const { return right_; }

305 306 307
  bool IsFoldable() const {
    return left().HasResolvedValue() && right().HasResolvedValue();
  }
308 309
  bool LeftEqualsRight() const { return left().node() == right().node(); }

310 311 312 313 314 315 316 317 318
  bool OwnsInput(Node* input) {
    for (Node* use : input->uses()) {
      if (use != node()) {
        return false;
      }
    }
    return true;
  }

319 320 321
 protected:
  void SwapInputs() {
    std::swap(left_, right_);
322
    // TODO(turbofan): This modification should notify the reducers using
323 324
    // BinopMatcher. Alternatively, all reducers (especially value numbering)
    // could ignore the ordering for commutative binops.
325 326 327 328
    node()->ReplaceInput(0, left().node());
    node()->ReplaceInput(1, right().node());
  }

329 330
 private:
  void PutConstantOnRight() {
331
    if (left().HasResolvedValue() && !right().HasResolvedValue()) {
332
      SwapInputs();
333 334 335 336 337 338 339
    }
  }

  Left left_;
  Right right_;
};

340 341 342 343 344 345 346 347 348 349 350
using Int32BinopMatcher = BinopMatcher<Int32Matcher, Int32Matcher>;
using Uint32BinopMatcher = BinopMatcher<Uint32Matcher, Uint32Matcher>;
using Int64BinopMatcher = BinopMatcher<Int64Matcher, Int64Matcher>;
using Uint64BinopMatcher = BinopMatcher<Uint64Matcher, Uint64Matcher>;
using IntPtrBinopMatcher = BinopMatcher<IntPtrMatcher, IntPtrMatcher>;
using UintPtrBinopMatcher = BinopMatcher<UintPtrMatcher, UintPtrMatcher>;
using Float32BinopMatcher = BinopMatcher<Float32Matcher, Float32Matcher>;
using Float64BinopMatcher = BinopMatcher<Float64Matcher, Float64Matcher>;
using NumberBinopMatcher = BinopMatcher<NumberMatcher, NumberMatcher>;
using HeapObjectBinopMatcher =
    BinopMatcher<HeapObjectMatcher, HeapObjectMatcher>;
351 352
using CompressedHeapObjectBinopMatcher =
    BinopMatcher<CompressedHeapObjectMatcher, CompressedHeapObjectMatcher>;
353

354 355 356 357 358 359 360
template <class BinopMatcher, IrOpcode::Value kMulOpcode,
          IrOpcode::Value kShiftOpcode>
struct ScaleMatcher {
  explicit ScaleMatcher(Node* node, bool allow_power_of_two_plus_one = false)
      : scale_(-1), power_of_two_plus_one_(false) {
    if (node->InputCount() < 2) return;
    BinopMatcher m(node);
361
    if (node->opcode() == kShiftOpcode) {
362
      if (m.right().HasResolvedValue()) {
363
        typename BinopMatcher::RightMatcher::ValueType value =
364
            m.right().ResolvedValue();
365
        if (value >= 0 && value <= 3) {
366
          scale_ = static_cast<int>(value);
367 368
        }
      }
369
    } else if (node->opcode() == kMulOpcode) {
370
      if (m.right().HasResolvedValue()) {
371
        typename BinopMatcher::RightMatcher::ValueType value =
372
            m.right().ResolvedValue();
373
        if (value == 1) {
374
          scale_ = 0;
375
        } else if (value == 2) {
376
          scale_ = 1;
377
        } else if (value == 4) {
378
          scale_ = 2;
379
        } else if (value == 8) {
380 381 382 383 384 385 386 387 388 389 390 391
          scale_ = 3;
        } else if (allow_power_of_two_plus_one) {
          if (value == 3) {
            scale_ = 1;
            power_of_two_plus_one_ = true;
          } else if (value == 5) {
            scale_ = 2;
            power_of_two_plus_one_ = true;
          } else if (value == 9) {
            scale_ = 3;
            power_of_two_plus_one_ = true;
          }
392 393 394 395 396
        }
      }
    }
  }

397 398 399 400 401 402 403 404 405
  bool matches() const { return scale_ != -1; }
  int scale() const { return scale_; }
  bool power_of_two_plus_one() const { return power_of_two_plus_one_; }

 private:
  int scale_;
  bool power_of_two_plus_one_;
};

406 407 408 409
using Int32ScaleMatcher =
    ScaleMatcher<Int32BinopMatcher, IrOpcode::kInt32Mul, IrOpcode::kWord32Shl>;
using Int64ScaleMatcher =
    ScaleMatcher<Int64BinopMatcher, IrOpcode::kInt64Mul, IrOpcode::kWord64Shl>;
410

411 412 413
template <class BinopMatcher, IrOpcode::Value AddOpcode,
          IrOpcode::Value SubOpcode, IrOpcode::Value kMulOpcode,
          IrOpcode::Value kShiftOpcode>
414
struct AddMatcher : public BinopMatcher {
415 416
  static const IrOpcode::Value kAddOpcode = AddOpcode;
  static const IrOpcode::Value kSubOpcode = SubOpcode;
417
  using Matcher = ScaleMatcher<BinopMatcher, kMulOpcode, kShiftOpcode>;
418

419 420 421 422 423 424
  AddMatcher(Node* node, bool allow_input_swap)
      : BinopMatcher(node, allow_input_swap),
        scale_(-1),
        power_of_two_plus_one_(false) {
    Initialize(node, allow_input_swap);
  }
425
  explicit AddMatcher(Node* node)
426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444
      : BinopMatcher(node, node->op()->HasProperty(Operator::kCommutative)),
        scale_(-1),
        power_of_two_plus_one_(false) {
    Initialize(node, node->op()->HasProperty(Operator::kCommutative));
  }

  bool HasIndexInput() const { return scale_ != -1; }
  Node* IndexInput() const {
    DCHECK(HasIndexInput());
    return this->left().node()->InputAt(0);
  }
  int scale() const {
    DCHECK(HasIndexInput());
    return scale_;
  }
  bool power_of_two_plus_one() const { return power_of_two_plus_one_; }

 private:
  void Initialize(Node* node, bool allow_input_swap) {
445 446 447 448 449 450 451
    Matcher left_matcher(this->left().node(), true);
    if (left_matcher.matches()) {
      scale_ = left_matcher.scale();
      power_of_two_plus_one_ = left_matcher.power_of_two_plus_one();
      return;
    }

452
    if (!allow_input_swap) {
453 454 455 456 457 458 459 460 461
      return;
    }

    Matcher right_matcher(this->right().node(), true);
    if (right_matcher.matches()) {
      scale_ = right_matcher.scale();
      power_of_two_plus_one_ = right_matcher.power_of_two_plus_one();
      this->SwapInputs();
      return;
462
    }
463

464 465 466 467
    if ((this->left().opcode() != kSubOpcode &&
         this->left().opcode() != kAddOpcode) &&
        (this->right().opcode() == kAddOpcode ||
         this->right().opcode() == kSubOpcode)) {
468
      this->SwapInputs();
469 470 471 472 473
    }
  }

  int scale_;
  bool power_of_two_plus_one_;
474 475
};

476 477 478 479 480 481
using Int32AddMatcher =
    AddMatcher<Int32BinopMatcher, IrOpcode::kInt32Add, IrOpcode::kInt32Sub,
               IrOpcode::kInt32Mul, IrOpcode::kWord32Shl>;
using Int64AddMatcher =
    AddMatcher<Int64BinopMatcher, IrOpcode::kInt64Add, IrOpcode::kInt64Sub,
               IrOpcode::kInt64Mul, IrOpcode::kWord64Shl>;
482

483
enum DisplacementMode { kPositiveDisplacement, kNegativeDisplacement };
484

485 486 487 488 489 490 491
enum class AddressOption : uint8_t {
  kAllowNone = 0u,
  kAllowInputSwap = 1u << 0,
  kAllowScale = 1u << 1,
  kAllowAll = kAllowInputSwap | kAllowScale
};

492
using AddressOptions = base::Flags<AddressOption, uint8_t>;
493
DEFINE_OPERATORS_FOR_FLAGS(AddressOptions)
494

495
template <class AddMatcher>
496
struct BaseWithIndexAndDisplacementMatcher {
497
  BaseWithIndexAndDisplacementMatcher(Node* node, AddressOptions options)
498
      : matches_(false),
499
        index_(nullptr),
500
        scale_(0),
501
        base_(nullptr),
502 503
        displacement_(nullptr),
        displacement_mode_(kPositiveDisplacement) {
504
    Initialize(node, options);
505 506
  }

507
  explicit BaseWithIndexAndDisplacementMatcher(Node* node)
508
      : matches_(false),
509
        index_(nullptr),
510
        scale_(0),
511
        base_(nullptr),
512 513
        displacement_(nullptr),
        displacement_mode_(kPositiveDisplacement) {
514 515 516 517
    Initialize(node, AddressOption::kAllowScale |
                         (node->op()->HasProperty(Operator::kCommutative)
                              ? AddressOption::kAllowInputSwap
                              : AddressOption::kAllowNone));
518 519 520 521 522 523 524
  }

  bool matches() const { return matches_; }
  Node* index() const { return index_; }
  int scale() const { return scale_; }
  Node* base() const { return base_; }
  Node* displacement() const { return displacement_; }
525
  DisplacementMode displacement_mode() const { return displacement_mode_; }
526 527 528 529 530 531 532

 private:
  bool matches_;
  Node* index_;
  int scale_;
  Node* base_;
  Node* displacement_;
533
  DisplacementMode displacement_mode_;
534

535
  void Initialize(Node* node, AddressOptions options) {
536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551
    // The BaseWithIndexAndDisplacementMatcher canonicalizes the order of
    // displacements and scale factors that are used as inputs, so instead of
    // enumerating all possible patterns by brute force, checking for node
    // clusters using the following templates in the following order suffices to
    // find all of the interesting cases (S = index * scale, B = base input, D =
    // displacement input):
    // (S + (B + D))
    // (S + (B + B))
    // (S + D)
    // (S + B)
    // ((S + D) + B)
    // ((S + B) + D)
    // ((B + D) + B)
    // ((B + B) + D)
    // (B + D)
    // (B + B)
552
    if (node->InputCount() < 2) return;
553
    AddMatcher m(node, options & AddressOption::kAllowInputSwap);
554 555
    Node* left = m.left().node();
    Node* right = m.right().node();
556 557 558 559
    Node* displacement = nullptr;
    Node* base = nullptr;
    Node* index = nullptr;
    Node* scale_expression = nullptr;
560
    bool power_of_two_plus_one = false;
561
    DisplacementMode displacement_mode = kPositiveDisplacement;
562
    int scale = 0;
563
    if (m.HasIndexInput() && OwnedByAddressingOperand(left)) {
564 565 566 567
      index = m.IndexInput();
      scale = m.scale();
      scale_expression = left;
      power_of_two_plus_one = m.power_of_two_plus_one();
568
      bool match_found = false;
569
      if (right->opcode() == AddMatcher::kSubOpcode &&
570
          OwnedByAddressingOperand(right)) {
571
        AddMatcher right_matcher(right);
572
        if (right_matcher.right().HasResolvedValue()) {
573
          // (S + (B - D))
574 575
          base = right_matcher.left().node();
          displacement = right_matcher.right().node();
576 577 578 579 580
          displacement_mode = kNegativeDisplacement;
          match_found = true;
        }
      }
      if (!match_found) {
581
        if (right->opcode() == AddMatcher::kAddOpcode &&
582
            OwnedByAddressingOperand(right)) {
583
          AddMatcher right_matcher(right);
584
          if (right_matcher.right().HasResolvedValue()) {
585 586 587 588 589 590 591
            // (S + (B + D))
            base = right_matcher.left().node();
            displacement = right_matcher.right().node();
          } else {
            // (S + (B + B))
            base = right;
          }
592
        } else if (m.right().HasResolvedValue()) {
593 594
          // (S + D)
          displacement = right;
595
        } else {
596
          // (S + B)
597
          base = right;
598 599 600
        }
      }
    } else {
601
      bool match_found = false;
602
      if (left->opcode() == AddMatcher::kSubOpcode &&
603
          OwnedByAddressingOperand(left)) {
604
        AddMatcher left_matcher(left);
605 606
        Node* left_left = left_matcher.left().node();
        Node* left_right = left_matcher.right().node();
607
        if (left_matcher.right().HasResolvedValue()) {
608 609
          if (left_matcher.HasIndexInput() && left_left->OwnedBy(left)) {
            // ((S - D) + B)
610 611 612 613 614
            index = left_matcher.IndexInput();
            scale = left_matcher.scale();
            scale_expression = left_left;
            power_of_two_plus_one = left_matcher.power_of_two_plus_one();
            displacement = left_right;
615
            displacement_mode = kNegativeDisplacement;
616
            base = right;
617
          } else {
618
            // ((B - D) + B)
619 620
            index = left_left;
            displacement = left_right;
621
            displacement_mode = kNegativeDisplacement;
622
            base = right;
623 624 625 626 627
          }
          match_found = true;
        }
      }
      if (!match_found) {
628
        if (left->opcode() == AddMatcher::kAddOpcode &&
629
            OwnedByAddressingOperand(left)) {
630 631 632 633
          AddMatcher left_matcher(left);
          Node* left_left = left_matcher.left().node();
          Node* left_right = left_matcher.right().node();
          if (left_matcher.HasIndexInput() && left_left->OwnedBy(left)) {
634
            if (left_matcher.right().HasResolvedValue()) {
635 636 637 638 639 640 641
              // ((S + D) + B)
              index = left_matcher.IndexInput();
              scale = left_matcher.scale();
              scale_expression = left_left;
              power_of_two_plus_one = left_matcher.power_of_two_plus_one();
              displacement = left_right;
              base = right;
642
            } else if (m.right().HasResolvedValue()) {
643 644 645 646 647 648 649 650 651 652 653 654 655
              if (left->OwnedBy(node)) {
                // ((S + B) + D)
                index = left_matcher.IndexInput();
                scale = left_matcher.scale();
                scale_expression = left_left;
                power_of_two_plus_one = left_matcher.power_of_two_plus_one();
                base = left_right;
                displacement = right;
              } else {
                // (B + D)
                base = left;
                displacement = right;
              }
656 657 658 659 660 661
            } else {
              // (B + B)
              index = left;
              base = right;
            }
          } else {
662
            if (left_matcher.right().HasResolvedValue()) {
663 664 665 666
              // ((B + D) + B)
              index = left_left;
              displacement = left_right;
              base = right;
667
            } else if (m.right().HasResolvedValue()) {
668 669 670 671 672 673 674 675 676 677
              if (left->OwnedBy(node)) {
                // ((B + B) + D)
                index = left_left;
                base = left_right;
                displacement = right;
              } else {
                // (B + D)
                base = left;
                displacement = right;
              }
678 679 680 681 682 683 684
            } else {
              // (B + B)
              index = left;
              base = right;
            }
          }
        } else {
685
          if (m.right().HasResolvedValue()) {
686 687
            // (B + D)
            base = left;
688
            displacement = right;
689
          } else {
690
            // (B + B)
691 692
            base = left;
            index = right;
693 694 695 696
          }
        }
      }
    }
697
    int64_t value = 0;
698
    if (displacement != nullptr) {
699
      switch (displacement->opcode()) {
700
        case IrOpcode::kInt32Constant: {
701
          value = OpParameter<int32_t>(displacement->op());
702 703 704
          break;
        }
        case IrOpcode::kInt64Constant: {
705
          value = OpParameter<int64_t>(displacement->op());
706 707 708 709 710 711 712
          break;
        }
        default:
          UNREACHABLE();
          break;
      }
      if (value == 0) {
713
        displacement = nullptr;
714 715 716
      }
    }
    if (power_of_two_plus_one) {
717
      if (base != nullptr) {
718 719 720 721 722 723 724 725
        // If the scale requires explicitly using the index as the base, but a
        // base is already part of the match, then the (1 << N + 1) scale factor
        // can't be folded into the match and the entire index * scale
        // calculation must be computed separately.
        index = scale_expression;
        scale = 0;
      } else {
        base = index;
726 727
      }
    }
728 729 730 731
    if (!(options & AddressOption::kAllowScale) && scale != 0) {
      index = scale_expression;
      scale = 0;
    }
732 733
    base_ = base;
    displacement_ = displacement;
734
    displacement_mode_ = displacement_mode;
735 736
    index_ = index;
    scale_ = scale;
737 738
    matches_ = true;
  }
739 740 741 742 743 744

  static bool OwnedByAddressingOperand(Node* node) {
    for (auto use : node->use_edges()) {
      Node* from = use.from();
      switch (from->opcode()) {
        case IrOpcode::kLoad:
745
        case IrOpcode::kLoadImmutable:
746
        case IrOpcode::kProtectedLoad:
747 748 749 750 751
        case IrOpcode::kInt32Add:
        case IrOpcode::kInt64Add:
          // Skip addressing uses.
          break;
        case IrOpcode::kStore:
752
        case IrOpcode::kProtectedStore:
753 754 755 756 757 758 759 760 761 762 763
          // If the stored value is this node, it is not an addressing use.
          if (from->InputAt(2) == node) return false;
          // Otherwise it is used as an address and skipped.
          break;
        default:
          // Non-addressing use found.
          return false;
      }
    }
    return true;
  }
764 765
};

766 767 768 769
using BaseWithIndexAndDisplacement32Matcher =
    BaseWithIndexAndDisplacementMatcher<Int32AddMatcher>;
using BaseWithIndexAndDisplacement64Matcher =
    BaseWithIndexAndDisplacementMatcher<Int64AddMatcher>;
770

771
struct V8_EXPORT_PRIVATE BranchMatcher : public NON_EXPORTED_BASE(NodeMatcher) {
772 773 774 775 776 777 778 779 780 781 782 783 784
  explicit BranchMatcher(Node* branch);

  bool Matched() const { return if_true_ && if_false_; }

  Node* Branch() const { return node(); }
  Node* IfTrue() const { return if_true_; }
  Node* IfFalse() const { return if_false_; }

 private:
  Node* if_true_;
  Node* if_false_;
};

785 786
struct V8_EXPORT_PRIVATE DiamondMatcher
    : public NON_EXPORTED_BASE(NodeMatcher) {
787 788 789 790 791 792 793 794 795 796 797 798
  explicit DiamondMatcher(Node* merge);

  bool Matched() const { return branch_; }
  bool IfProjectionsAreOwned() const {
    return if_true_->OwnedBy(node()) && if_false_->OwnedBy(node());
  }

  Node* Branch() const { return branch_; }
  Node* IfTrue() const { return if_true_; }
  Node* IfFalse() const { return if_false_; }
  Node* Merge() const { return node(); }

799 800 801 802 803 804 805 806 807 808 809 810 811 812
  Node* TrueInputOf(Node* phi) const {
    DCHECK(IrOpcode::IsPhiOpcode(phi->opcode()));
    DCHECK_EQ(3, phi->InputCount());
    DCHECK_EQ(Merge(), phi->InputAt(2));
    return phi->InputAt(if_true_ == Merge()->InputAt(0) ? 0 : 1);
  }

  Node* FalseInputOf(Node* phi) const {
    DCHECK(IrOpcode::IsPhiOpcode(phi->opcode()));
    DCHECK_EQ(3, phi->InputCount());
    DCHECK_EQ(Merge(), phi->InputAt(2));
    return phi->InputAt(if_true_ == Merge()->InputAt(0) ? 1 : 0);
  }

813 814 815 816 817 818
 private:
  Node* branch_;
  Node* if_true_;
  Node* if_false_;
};

819 820 821
}  // namespace compiler
}  // namespace internal
}  // namespace v8
822 823

#endif  // V8_COMPILER_NODE_MATCHERS_H_