common-operator-reducer.cc 19.9 KB
Newer Older
1 2 3 4 5 6
// 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.

#include "src/compiler/common-operator-reducer.h"

7 8
#include <algorithm>

9
#include "src/compiler/common-operator.h"
10
#include "src/compiler/graph.h"
11
#include "src/compiler/js-heap-broker.h"
12
#include "src/compiler/machine-operator.h"
13
#include "src/compiler/node-matchers.h"
14
#include "src/compiler/node-properties.h"
15
#include "src/compiler/node.h"
16 17 18 19 20

namespace v8 {
namespace internal {
namespace compiler {

21 22
namespace {

23
Decision DecideCondition(JSHeapBroker* broker, Node* const cond) {
24 25
  Node* unwrapped = SkipValueIdentities(cond);
  switch (unwrapped->opcode()) {
26
    case IrOpcode::kInt32Constant: {
27 28
      Int32Matcher m(unwrapped);
      return m.ResolvedValue() ? Decision::kTrue : Decision::kFalse;
29 30
    }
    case IrOpcode::kHeapConstant: {
31
      HeapObjectMatcher m(unwrapped);
32 33 34
      base::Optional<bool> maybe_result = m.Ref(broker).TryGetBooleanValue();
      if (!maybe_result.has_value()) return Decision::kUnknown;
      return *maybe_result ? Decision::kTrue : Decision::kFalse;
35 36 37 38 39 40 41 42
    }
    default:
      return Decision::kUnknown;
  }
}

}  // namespace

43
CommonOperatorReducer::CommonOperatorReducer(Editor* editor, Graph* graph,
44
                                             JSHeapBroker* broker,
45
                                             CommonOperatorBuilder* common,
46 47
                                             MachineOperatorBuilder* machine,
                                             Zone* temp_zone)
48 49
    : AdvancedReducer(editor),
      graph_(graph),
50
      broker_(broker),
51 52
      common_(common),
      machine_(machine),
53 54
      dead_(graph->NewNode(common->Dead())),
      zone_(temp_zone) {
55 56
  NodeProperties::SetType(dead_, Type::None());
}
57

58
Reduction CommonOperatorReducer::Reduce(Node* node) {
59 60
  DisallowHeapAccessIf no_heap_access(broker() == nullptr ||
                                      !broker()->is_concurrent_inlining());
61
  switch (node->opcode()) {
62 63
    case IrOpcode::kBranch:
      return ReduceBranch(node);
64 65 66
    case IrOpcode::kDeoptimizeIf:
    case IrOpcode::kDeoptimizeUnless:
      return ReduceDeoptimizeConditional(node);
67 68
    case IrOpcode::kMerge:
      return ReduceMerge(node);
69
    case IrOpcode::kEffectPhi:
70 71 72
      return ReduceEffectPhi(node);
    case IrOpcode::kPhi:
      return ReducePhi(node);
73 74
    case IrOpcode::kReturn:
      return ReduceReturn(node);
75 76
    case IrOpcode::kSelect:
      return ReduceSelect(node);
77 78
    case IrOpcode::kSwitch:
      return ReduceSwitch(node);
79 80
    case IrOpcode::kStaticAssert:
      return ReduceStaticAssert(node);
81 82 83
    case IrOpcode::kTrapIf:
    case IrOpcode::kTrapUnless:
      return ReduceTrapConditional(node);
84
    default:
85
      break;
86 87 88 89 90
  }
  return NoChange();
}


91 92 93
Reduction CommonOperatorReducer::ReduceBranch(Node* node) {
  DCHECK_EQ(IrOpcode::kBranch, node->opcode());
  Node* const cond = node->InputAt(0);
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
  // Swap IfTrue/IfFalse on {branch} if {cond} is a BooleanNot and use the input
  // to BooleanNot as new condition for {branch}. Note we assume that {cond} was
  // already properly optimized before we get here (as guaranteed by the graph
  // reduction logic). The same applies if {cond} is a Select acting as boolean
  // not (i.e. true being returned in the false case and vice versa).
  if (cond->opcode() == IrOpcode::kBooleanNot ||
      (cond->opcode() == IrOpcode::kSelect &&
       DecideCondition(broker(), cond->InputAt(1)) == Decision::kFalse &&
       DecideCondition(broker(), cond->InputAt(2)) == Decision::kTrue)) {
    for (Node* const use : node->uses()) {
      switch (use->opcode()) {
        case IrOpcode::kIfTrue:
          NodeProperties::ChangeOp(use, common()->IfFalse());
          break;
        case IrOpcode::kIfFalse:
          NodeProperties::ChangeOp(use, common()->IfTrue());
          break;
        default:
          UNREACHABLE();
113 114 115 116 117
      }
    }
    // Update the condition of {branch}. No need to mark the uses for revisit,
    // since we tell the graph reducer that the {branch} was changed and the
    // graph reduction logic will ensure that the uses are revisited properly.
118 119 120 121
    node->ReplaceInput(0, cond->InputAt(0));
    // Negate the hint for {branch}.
    NodeProperties::ChangeOp(
        node, common()->Branch(NegateBranchHint(BranchHintOf(node->op()))));
122 123
    return Changed(node);
  }
124
  Decision const decision = DecideCondition(broker(), cond);
125 126 127 128 129
  if (decision == Decision::kUnknown) return NoChange();
  Node* const control = node->InputAt(1);
  for (Node* const use : node->uses()) {
    switch (use->opcode()) {
      case IrOpcode::kIfTrue:
130
        Replace(use, (decision == Decision::kTrue) ? control : dead());
131 132
        break;
      case IrOpcode::kIfFalse:
133
        Replace(use, (decision == Decision::kFalse) ? control : dead());
134 135 136 137 138
        break;
      default:
        UNREACHABLE();
    }
  }
139
  return Replace(dead());
140 141
}

142 143 144 145
Reduction CommonOperatorReducer::ReduceDeoptimizeConditional(Node* node) {
  DCHECK(node->opcode() == IrOpcode::kDeoptimizeIf ||
         node->opcode() == IrOpcode::kDeoptimizeUnless);
  bool condition_is_true = node->opcode() == IrOpcode::kDeoptimizeUnless;
146
  DeoptimizeParameters p = DeoptimizeParametersOf(node->op());
147 148 149 150
  Node* condition = NodeProperties::GetValueInput(node, 0);
  Node* frame_state = NodeProperties::GetValueInput(node, 1);
  Node* effect = NodeProperties::GetEffectInput(node);
  Node* control = NodeProperties::GetControlInput(node);
151 152 153 154 155 156 157 158 159 160 161
  // Swap DeoptimizeIf/DeoptimizeUnless on {node} if {cond} is a BooleaNot
  // and use the input to BooleanNot as new condition for {node}.  Note we
  // assume that {cond} was already properly optimized before we get here
  // (as guaranteed by the graph reduction logic).
  if (condition->opcode() == IrOpcode::kBooleanNot) {
    NodeProperties::ReplaceValueInput(node, condition->InputAt(0), 0);
    NodeProperties::ChangeOp(
        node,
        condition_is_true
            ? common()->DeoptimizeIf(p.kind(), p.reason(), p.feedback())
            : common()->DeoptimizeUnless(p.kind(), p.reason(), p.feedback()));
162 163
    return Changed(node);
  }
164
  Decision const decision = DecideCondition(broker(), condition);
165 166
  if (decision == Decision::kUnknown) return NoChange();
  if (condition_is_true == (decision == Decision::kTrue)) {
167 168
    ReplaceWithValue(node, dead(), effect, control);
  } else {
169
    control = graph()->NewNode(
170 171
        common()->Deoptimize(p.kind(), p.reason(), p.feedback()), frame_state,
        effect, control);
172 173 174
    // TODO(bmeurer): This should be on the AdvancedReducer somehow.
    NodeProperties::MergeControlToEnd(graph(), common(), control);
    Revisit(graph()->end());
175 176 177
  }
  return Replace(dead());
}
178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206

Reduction CommonOperatorReducer::ReduceMerge(Node* node) {
  DCHECK_EQ(IrOpcode::kMerge, node->opcode());
  //
  // Check if this is a merge that belongs to an unused diamond, which means
  // that:
  //
  //  a) the {Merge} has no {Phi} or {EffectPhi} uses, and
  //  b) the {Merge} has two inputs, one {IfTrue} and one {IfFalse}, which are
  //     both owned by the Merge, and
  //  c) and the {IfTrue} and {IfFalse} nodes point to the same {Branch}.
  //
  if (node->InputCount() == 2) {
    for (Node* const use : node->uses()) {
      if (IrOpcode::IsPhiOpcode(use->opcode())) return NoChange();
    }
    Node* if_true = node->InputAt(0);
    Node* if_false = node->InputAt(1);
    if (if_true->opcode() != IrOpcode::kIfTrue) std::swap(if_true, if_false);
    if (if_true->opcode() == IrOpcode::kIfTrue &&
        if_false->opcode() == IrOpcode::kIfFalse &&
        if_true->InputAt(0) == if_false->InputAt(0) && if_true->OwnedBy(node) &&
        if_false->OwnedBy(node)) {
      Node* const branch = if_true->InputAt(0);
      DCHECK_EQ(IrOpcode::kBranch, branch->opcode());
      DCHECK(branch->OwnedBy(if_true, if_false));
      Node* const control = branch->InputAt(1);
      // Mark the {branch} as {Dead}.
      branch->TrimInputCount(0);
207
      NodeProperties::ChangeOp(branch, common()->Dead());
208 209 210 211 212 213 214
      return Replace(control);
    }
  }
  return NoChange();
}


215 216
Reduction CommonOperatorReducer::ReduceEffectPhi(Node* node) {
  DCHECK_EQ(IrOpcode::kEffectPhi, node->opcode());
217 218 219 220
  Node::Inputs inputs = node->inputs();
  int const effect_input_count = inputs.count() - 1;
  DCHECK_LE(1, effect_input_count);
  Node* const merge = inputs[effect_input_count];
221
  DCHECK(IrOpcode::IsMergeOpcode(merge->opcode()));
222 223
  DCHECK_EQ(effect_input_count, merge->InputCount());
  Node* const effect = inputs[0];
224
  DCHECK_NE(node, effect);
225 226
  for (int i = 1; i < effect_input_count; ++i) {
    Node* const input = inputs[i];
227 228 229 230
    if (input == node) {
      // Ignore redundant inputs.
      DCHECK_EQ(IrOpcode::kLoop, merge->opcode());
      continue;
231
    }
232
    if (input != effect) return NoChange();
233
  }
234 235 236
  // We might now be able to further reduce the {merge} node.
  Revisit(merge);
  return Replace(effect);
237 238 239 240 241
}


Reduction CommonOperatorReducer::ReducePhi(Node* node) {
  DCHECK_EQ(IrOpcode::kPhi, node->opcode());
242 243 244 245
  Node::Inputs inputs = node->inputs();
  int const value_input_count = inputs.count() - 1;
  DCHECK_LE(1, value_input_count);
  Node* const merge = inputs[value_input_count];
246
  DCHECK(IrOpcode::IsMergeOpcode(merge->opcode()));
247 248 249 250 251 252 253
  DCHECK_EQ(value_input_count, merge->InputCount());
  if (value_input_count == 2) {
    Node* vtrue = inputs[0];
    Node* vfalse = inputs[1];
    Node::Inputs merge_inputs = merge->inputs();
    Node* if_true = merge_inputs[0];
    Node* if_false = merge_inputs[1];
254 255 256 257 258 259 260 261
    if (if_true->opcode() != IrOpcode::kIfTrue) {
      std::swap(if_true, if_false);
      std::swap(vtrue, vfalse);
    }
    if (if_true->opcode() == IrOpcode::kIfTrue &&
        if_false->opcode() == IrOpcode::kIfFalse &&
        if_true->InputAt(0) == if_false->InputAt(0)) {
      Node* const branch = if_true->InputAt(0);
262 263
      // Check that the branch is not dead already.
      if (branch->opcode() != IrOpcode::kBranch) return NoChange();
264
      Node* const cond = branch->InputAt(0);
265 266 267
      if (cond->opcode() == IrOpcode::kFloat32LessThan) {
        Float32BinopMatcher mcond(cond);
        if (mcond.left().Is(0.0) && mcond.right().Equals(vtrue) &&
268
            vfalse->opcode() == IrOpcode::kFloat32Sub) {
269 270
          Float32BinopMatcher mvfalse(vfalse);
          if (mvfalse.left().IsZero() && mvfalse.right().Equals(vtrue)) {
271 272
            // We might now be able to further reduce the {merge} node.
            Revisit(merge);
273 274 275 276 277 278
            return Change(node, machine()->Float32Abs(), vtrue);
          }
        }
      } else if (cond->opcode() == IrOpcode::kFloat64LessThan) {
        Float64BinopMatcher mcond(cond);
        if (mcond.left().Is(0.0) && mcond.right().Equals(vtrue) &&
279
            vfalse->opcode() == IrOpcode::kFloat64Sub) {
280 281
          Float64BinopMatcher mvfalse(vfalse);
          if (mvfalse.left().IsZero() && mvfalse.right().Equals(vtrue)) {
282 283
            // We might now be able to further reduce the {merge} node.
            Revisit(merge);
284 285 286
            return Change(node, machine()->Float64Abs(), vtrue);
          }
        }
287 288
      }
    }
289
  }
290
  Node* const value = inputs[0];
291
  DCHECK_NE(node, value);
292 293
  for (int i = 1; i < value_input_count; ++i) {
    Node* const input = inputs[i];
294 295 296 297
    if (input == node) {
      // Ignore redundant inputs.
      DCHECK_EQ(IrOpcode::kLoop, merge->opcode());
      continue;
298
    }
299
    if (input != value) return NoChange();
300
  }
301 302 303
  // We might now be able to further reduce the {merge} node.
  Revisit(merge);
  return Replace(value);
304 305
}

306 307
Reduction CommonOperatorReducer::ReduceReturn(Node* node) {
  DCHECK_EQ(IrOpcode::kReturn, node->opcode());
308 309 310 311 312 313
  Node* effect = NodeProperties::GetEffectInput(node);
  if (effect->opcode() == IrOpcode::kCheckpoint) {
    // Any {Return} node can never be used to insert a deoptimization point,
    // hence checkpoints can be cut out of the effect chain flowing into it.
    effect = NodeProperties::GetEffectInput(effect);
    NodeProperties::ReplaceEffectInput(node, effect);
314
    return Changed(node).FollowedBy(ReduceReturn(node));
315
  }
316 317 318 319
  // TODO(ahaas): Extend the reduction below to multiple return values.
  if (ValueInputCountOfReturn(node->op()) != 1) {
    return NoChange();
  }
320 321 322
  Node* pop_count = NodeProperties::GetValueInput(node, 0);
  Node* value = NodeProperties::GetValueInput(node, 1);
  Node* control = NodeProperties::GetControlInput(node);
323 324 325
  if (value->opcode() == IrOpcode::kPhi &&
      NodeProperties::GetControlInput(value) == control &&
      control->opcode() == IrOpcode::kMerge) {
326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345
    // This optimization pushes {Return} nodes through merges. It checks that
    // the return value is actually a {Phi} and the return control dependency
    // is the {Merge} to which the {Phi} belongs.

    // Value1 ... ValueN Control1 ... ControlN
    //   ^          ^       ^            ^
    //   |          |       |            |
    //   +----+-----+       +------+-----+
    //        |                    |
    //       Phi --------------> Merge
    //        ^                    ^
    //        |                    |
    //        |  +-----------------+
    //        |  |
    //       Return -----> Effect
    //         ^
    //         |
    //        End

    // Now the effect input to the {Return} node can be either an {EffectPhi}
346 347 348
    // hanging off the same {Merge}, or the effect chain doesn't depend on the
    // {Phi} or the {Merge}, in which case we know that the effect input must
    // somehow dominate all merged branches.
349

350 351 352 353
    Node::Inputs control_inputs = control->inputs();
    Node::Inputs value_inputs = value->inputs();
    DCHECK_NE(0, control_inputs.count());
    DCHECK_EQ(control_inputs.count(), value_inputs.count() - 1);
354 355
    DCHECK_EQ(IrOpcode::kEnd, graph()->end()->opcode());
    DCHECK_NE(0, graph()->end()->InputCount());
356
    if (control->OwnedBy(node, value) && value->OwnedBy(node)) {
357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384
      for (int i = 0; i < control_inputs.count(); ++i) {
        // Create a new {Return} and connect it to {end}. We don't need to mark
        // {end} as revisit, because we mark {node} as {Dead} below, which was
        // previously connected to {end}, so we know for sure that at some point
        // the reducer logic will visit {end} again.
        Node* ret = graph()->NewNode(node->op(), pop_count, value_inputs[i],
                                     effect, control_inputs[i]);
        NodeProperties::MergeControlToEnd(graph(), common(), ret);
      }
      // Mark the Merge {control} and Return {node} as {dead}.
      Replace(control, dead());
      return Replace(dead());
    } else if (effect->opcode() == IrOpcode::kEffectPhi &&
               NodeProperties::GetControlInput(effect) == control) {
      Node::Inputs effect_inputs = effect->inputs();
      DCHECK_EQ(control_inputs.count(), effect_inputs.count() - 1);
      for (int i = 0; i < control_inputs.count(); ++i) {
        // Create a new {Return} and connect it to {end}. We don't need to mark
        // {end} as revisit, because we mark {node} as {Dead} below, which was
        // previously connected to {end}, so we know for sure that at some point
        // the reducer logic will visit {end} again.
        Node* ret = graph()->NewNode(node->op(), pop_count, value_inputs[i],
                                     effect_inputs[i], control_inputs[i]);
        NodeProperties::MergeControlToEnd(graph(), common(), ret);
      }
      // Mark the Merge {control} and Return {node} as {dead}.
      Replace(control, dead());
      return Replace(dead());
385 386
    }
  }
387
  return NoChange();
388 389
}

390 391
Reduction CommonOperatorReducer::ReduceSelect(Node* node) {
  DCHECK_EQ(IrOpcode::kSelect, node->opcode());
392 393 394
  Node* const cond = node->InputAt(0);
  Node* const vtrue = node->InputAt(1);
  Node* const vfalse = node->InputAt(2);
395
  if (vtrue == vfalse) return Replace(vtrue);
396
  switch (DecideCondition(broker(), cond)) {
397 398 399 400 401 402 403
    case Decision::kTrue:
      return Replace(vtrue);
    case Decision::kFalse:
      return Replace(vfalse);
    case Decision::kUnknown:
      break;
  }
404 405 406 407
  switch (cond->opcode()) {
    case IrOpcode::kFloat32LessThan: {
      Float32BinopMatcher mcond(cond);
      if (mcond.left().Is(0.0) && mcond.right().Equals(vtrue) &&
408
          vfalse->opcode() == IrOpcode::kFloat32Sub) {
409 410 411 412
        Float32BinopMatcher mvfalse(vfalse);
        if (mvfalse.left().IsZero() && mvfalse.right().Equals(vtrue)) {
          return Change(node, machine()->Float32Abs(), vtrue);
        }
413
      }
414
      break;
415
    }
416 417 418
    case IrOpcode::kFloat64LessThan: {
      Float64BinopMatcher mcond(cond);
      if (mcond.left().Is(0.0) && mcond.right().Equals(vtrue) &&
419
          vfalse->opcode() == IrOpcode::kFloat64Sub) {
420 421 422 423 424 425
        Float64BinopMatcher mvfalse(vfalse);
        if (mvfalse.left().IsZero() && mvfalse.right().Equals(vtrue)) {
          return Change(node, machine()->Float64Abs(), vtrue);
        }
      }
      break;
426
    }
427 428
    default:
      break;
429 430 431 432
  }
  return NoChange();
}

433 434 435 436 437 438 439 440 441 442
Reduction CommonOperatorReducer::ReduceSwitch(Node* node) {
  DCHECK_EQ(IrOpcode::kSwitch, node->opcode());
  Node* const switched_value = node->InputAt(0);
  Node* const control = node->InputAt(1);

  // Attempt to constant match the switched value against the IfValue cases. If
  // no case matches, then use the IfDefault. We don't bother marking
  // non-matching cases as dead code (same for an unused IfDefault), because the
  // Switch itself will be marked as dead code.
  Int32Matcher mswitched(switched_value);
443
  if (mswitched.HasResolvedValue()) {
444 445 446 447 448 449 450 451 452
    bool matched = false;

    size_t const projection_count = node->op()->ControlOutputCount();
    Node** projections = zone_->NewArray<Node*>(projection_count);
    NodeProperties::CollectControlProjections(node, projections,
                                              projection_count);
    for (size_t i = 0; i < projection_count - 1; i++) {
      Node* if_value = projections[i];
      DCHECK_EQ(IrOpcode::kIfValue, if_value->opcode());
453
      const IfValueParameters& p = IfValueParametersOf(if_value->op());
454
      if (p.value() == mswitched.ResolvedValue()) {
455 456 457 458 459 460 461 462 463 464 465 466 467 468
        matched = true;
        Replace(if_value, control);
        break;
      }
    }
    if (!matched) {
      Node* if_default = projections[projection_count - 1];
      DCHECK_EQ(IrOpcode::kIfDefault, if_default->opcode());
      Replace(if_default, control);
    }
    return Replace(dead());
  }
  return NoChange();
}
469

470 471 472 473 474 475 476 477 478 479 480 481
Reduction CommonOperatorReducer::ReduceStaticAssert(Node* node) {
  DCHECK_EQ(IrOpcode::kStaticAssert, node->opcode());
  Node* const cond = node->InputAt(0);
  Decision decision = DecideCondition(broker(), cond);
  if (decision == Decision::kTrue) {
    RelaxEffectsAndControls(node);
    return Changed(node);
  } else {
    return NoChange();
  }
}

482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505
Reduction CommonOperatorReducer::ReduceTrapConditional(Node* trap) {
  DCHECK(trap->opcode() == IrOpcode::kTrapIf ||
         trap->opcode() == IrOpcode::kTrapUnless);
  bool trapping_condition = trap->opcode() == IrOpcode::kTrapIf;
  Node* const cond = trap->InputAt(0);
  Decision decision = DecideCondition(broker(), cond);

  if (decision == Decision::kUnknown) {
    return NoChange();
  } else if ((decision == Decision::kTrue) == trapping_condition) {
    // This will always trap. Mark its outputs as dead and connect it to
    // graph()->end().
    ReplaceWithValue(trap, dead(), dead(), dead());
    Node* effect = NodeProperties::GetEffectInput(trap);
    Node* control = graph()->NewNode(common()->Throw(), effect, trap);
    NodeProperties::MergeControlToEnd(graph(), common(), control);
    Revisit(graph()->end());
    return Changed(trap);
  } else {
    // This will not trap, remove it.
    return Replace(NodeProperties::GetControlInput(trap));
  }
}

506 507 508 509
Reduction CommonOperatorReducer::Change(Node* node, Operator const* op,
                                        Node* a) {
  node->ReplaceInput(0, a);
  node->TrimInputCount(1);
510
  NodeProperties::ChangeOp(node, op);
511 512 513 514 515 516 517 518 519
  return Changed(node);
}


Reduction CommonOperatorReducer::Change(Node* node, Operator const* op, Node* a,
                                        Node* b) {
  node->ReplaceInput(0, a);
  node->ReplaceInput(1, b);
  node->TrimInputCount(2);
520
  NodeProperties::ChangeOp(node, op);
521 522 523
  return Changed(node);
}

524 525 526
}  // namespace compiler
}  // namespace internal
}  // namespace v8