1 // Copyright 2016 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/compiler/typed-optimization.h"
6
7 #include "src/base/optional.h"
8 #include "src/compiler/compilation-dependencies.h"
9 #include "src/compiler/js-graph.h"
10 #include "src/compiler/js-heap-broker.h"
11 #include "src/compiler/node-matchers.h"
12 #include "src/compiler/node-properties.h"
13 #include "src/compiler/simplified-operator.h"
14 #include "src/compiler/type-cache.h"
15 #include "src/execution/isolate-inl.h"
16
17 namespace v8 {
18 namespace internal {
19 namespace compiler {
20
TypedOptimization(Editor * editor,CompilationDependencies * dependencies,JSGraph * jsgraph,JSHeapBroker * broker)21 TypedOptimization::TypedOptimization(Editor* editor,
22 CompilationDependencies* dependencies,
23 JSGraph* jsgraph, JSHeapBroker* broker)
24 : AdvancedReducer(editor),
25 dependencies_(dependencies),
26 jsgraph_(jsgraph),
27 broker_(broker),
28 true_type_(
29 Type::Constant(broker, factory()->true_value(), graph()->zone())),
30 false_type_(
31 Type::Constant(broker, factory()->false_value(), graph()->zone())),
32 type_cache_(TypeCache::Get()) {}
33
34 TypedOptimization::~TypedOptimization() = default;
35
Reduce(Node * node)36 Reduction TypedOptimization::Reduce(Node* node) {
37 DisallowHeapAccess no_heap_access;
38 switch (node->opcode()) {
39 case IrOpcode::kConvertReceiver:
40 return ReduceConvertReceiver(node);
41 case IrOpcode::kMaybeGrowFastElements:
42 return ReduceMaybeGrowFastElements(node);
43 case IrOpcode::kCheckHeapObject:
44 return ReduceCheckHeapObject(node);
45 case IrOpcode::kCheckBounds:
46 return ReduceCheckBounds(node);
47 case IrOpcode::kCheckNotTaggedHole:
48 return ReduceCheckNotTaggedHole(node);
49 case IrOpcode::kCheckMaps:
50 return ReduceCheckMaps(node);
51 case IrOpcode::kCheckNumber:
52 return ReduceCheckNumber(node);
53 case IrOpcode::kCheckString:
54 return ReduceCheckString(node);
55 case IrOpcode::kCheckEqualsInternalizedString:
56 return ReduceCheckEqualsInternalizedString(node);
57 case IrOpcode::kCheckEqualsSymbol:
58 return ReduceCheckEqualsSymbol(node);
59 case IrOpcode::kLoadField:
60 return ReduceLoadField(node);
61 case IrOpcode::kNumberCeil:
62 case IrOpcode::kNumberRound:
63 case IrOpcode::kNumberTrunc:
64 return ReduceNumberRoundop(node);
65 case IrOpcode::kNumberFloor:
66 return ReduceNumberFloor(node);
67 case IrOpcode::kNumberSilenceNaN:
68 return ReduceNumberSilenceNaN(node);
69 case IrOpcode::kNumberToUint8Clamped:
70 return ReduceNumberToUint8Clamped(node);
71 case IrOpcode::kPhi:
72 return ReducePhi(node);
73 case IrOpcode::kReferenceEqual:
74 return ReduceReferenceEqual(node);
75 case IrOpcode::kStringEqual:
76 case IrOpcode::kStringLessThan:
77 case IrOpcode::kStringLessThanOrEqual:
78 return ReduceStringComparison(node);
79 case IrOpcode::kStringLength:
80 return ReduceStringLength(node);
81 case IrOpcode::kSameValue:
82 return ReduceSameValue(node);
83 case IrOpcode::kSelect:
84 return ReduceSelect(node);
85 case IrOpcode::kTypeOf:
86 return ReduceTypeOf(node);
87 case IrOpcode::kToBoolean:
88 return ReduceToBoolean(node);
89 case IrOpcode::kSpeculativeToNumber:
90 return ReduceSpeculativeToNumber(node);
91 case IrOpcode::kSpeculativeNumberAdd:
92 return ReduceSpeculativeNumberAdd(node);
93 case IrOpcode::kSpeculativeNumberSubtract:
94 case IrOpcode::kSpeculativeNumberMultiply:
95 case IrOpcode::kSpeculativeNumberDivide:
96 case IrOpcode::kSpeculativeNumberModulus:
97 return ReduceSpeculativeNumberBinop(node);
98 case IrOpcode::kSpeculativeNumberEqual:
99 case IrOpcode::kSpeculativeNumberLessThan:
100 case IrOpcode::kSpeculativeNumberLessThanOrEqual:
101 return ReduceSpeculativeNumberComparison(node);
102 default:
103 break;
104 }
105 return NoChange();
106 }
107
108 namespace {
109
GetStableMapFromObjectType(JSHeapBroker * broker,Type object_type)110 base::Optional<MapRef> GetStableMapFromObjectType(JSHeapBroker* broker,
111 Type object_type) {
112 if (object_type.IsHeapConstant()) {
113 HeapObjectRef object = object_type.AsHeapConstant()->Ref();
114 MapRef object_map = object.map();
115 if (object_map.is_stable()) return object_map;
116 }
117 return {};
118 }
119
ResolveSameValueRenames(Node * node)120 Node* ResolveSameValueRenames(Node* node) {
121 while (true) {
122 switch (node->opcode()) {
123 case IrOpcode::kCheckHeapObject:
124 case IrOpcode::kCheckNumber:
125 case IrOpcode::kCheckSmi:
126 case IrOpcode::kFinishRegion:
127 case IrOpcode::kTypeGuard:
128 if (node->IsDead()) {
129 return node;
130 } else {
131 node = node->InputAt(0);
132 continue;
133 }
134 default:
135 return node;
136 }
137 }
138 }
139
140 } // namespace
141
ReduceConvertReceiver(Node * node)142 Reduction TypedOptimization::ReduceConvertReceiver(Node* node) {
143 Node* const value = NodeProperties::GetValueInput(node, 0);
144 Type const value_type = NodeProperties::GetType(value);
145 Node* const global_proxy = NodeProperties::GetValueInput(node, 1);
146 if (value_type.Is(Type::Receiver())) {
147 ReplaceWithValue(node, value);
148 return Replace(value);
149 } else if (value_type.Is(Type::NullOrUndefined())) {
150 ReplaceWithValue(node, global_proxy);
151 return Replace(global_proxy);
152 }
153 return NoChange();
154 }
155
ReduceCheckHeapObject(Node * node)156 Reduction TypedOptimization::ReduceCheckHeapObject(Node* node) {
157 Node* const input = NodeProperties::GetValueInput(node, 0);
158 Type const input_type = NodeProperties::GetType(input);
159 if (!input_type.Maybe(Type::SignedSmall())) {
160 ReplaceWithValue(node, input);
161 return Replace(input);
162 }
163 return NoChange();
164 }
165
ReduceMaybeGrowFastElements(Node * node)166 Reduction TypedOptimization::ReduceMaybeGrowFastElements(Node* node) {
167 Node* const elements = NodeProperties::GetValueInput(node, 1);
168 Node* const index = NodeProperties::GetValueInput(node, 2);
169 Node* const length = NodeProperties::GetValueInput(node, 3);
170 Node* const effect = NodeProperties::GetEffectInput(node);
171 Node* const control = NodeProperties::GetControlInput(node);
172
173 Type const index_type = NodeProperties::GetType(index);
174 Type const length_type = NodeProperties::GetType(length);
175 CHECK(index_type.Is(Type::Unsigned31()));
176 CHECK(length_type.Is(Type::Unsigned31()));
177
178 if (!index_type.IsNone() && !length_type.IsNone() &&
179 index_type.Max() < length_type.Min()) {
180 Node* check_bounds = graph()->NewNode(
181 simplified()->CheckBounds(FeedbackSource{},
182 CheckBoundsFlag::kAbortOnOutOfBounds),
183 index, length, effect, control);
184 ReplaceWithValue(node, elements, check_bounds);
185 return Replace(check_bounds);
186 }
187
188 return NoChange();
189 }
190
ReduceCheckBounds(Node * node)191 Reduction TypedOptimization::ReduceCheckBounds(Node* node) {
192 CheckBoundsParameters const& p = CheckBoundsParametersOf(node->op());
193 Node* const input = NodeProperties::GetValueInput(node, 0);
194 Type const input_type = NodeProperties::GetType(input);
195 if (p.flags() & CheckBoundsFlag::kConvertStringAndMinusZero &&
196 !input_type.Maybe(Type::String()) &&
197 !input_type.Maybe(Type::MinusZero())) {
198 NodeProperties::ChangeOp(
199 node,
200 simplified()->CheckBounds(
201 p.check_parameters().feedback(),
202 p.flags().without(CheckBoundsFlag::kConvertStringAndMinusZero)));
203 return Changed(node);
204 }
205 return NoChange();
206 }
207
ReduceCheckNotTaggedHole(Node * node)208 Reduction TypedOptimization::ReduceCheckNotTaggedHole(Node* node) {
209 Node* const input = NodeProperties::GetValueInput(node, 0);
210 Type const input_type = NodeProperties::GetType(input);
211 if (!input_type.Maybe(Type::Hole())) {
212 ReplaceWithValue(node, input);
213 return Replace(input);
214 }
215 return NoChange();
216 }
217
ReduceCheckMaps(Node * node)218 Reduction TypedOptimization::ReduceCheckMaps(Node* node) {
219 // The CheckMaps(o, ...map...) can be eliminated if map is stable,
220 // o has type Constant(object) and map == object->map, and either
221 // (1) map cannot transition further, or
222 // (2) we can add a code dependency on the stability of map
223 // (to guard the Constant type information).
224 Node* const object = NodeProperties::GetValueInput(node, 0);
225 Type const object_type = NodeProperties::GetType(object);
226 Node* const effect = NodeProperties::GetEffectInput(node);
227 base::Optional<MapRef> object_map =
228 GetStableMapFromObjectType(broker(), object_type);
229 if (object_map.has_value()) {
230 for (int i = 1; i < node->op()->ValueInputCount(); ++i) {
231 Node* const map = NodeProperties::GetValueInput(node, i);
232 Type const map_type = NodeProperties::GetType(map);
233 if (map_type.IsHeapConstant() &&
234 map_type.AsHeapConstant()->Ref().equals(*object_map)) {
235 if (object_map->CanTransition()) {
236 dependencies()->DependOnStableMap(*object_map);
237 }
238 return Replace(effect);
239 }
240 }
241 }
242 return NoChange();
243 }
244
ReduceCheckNumber(Node * node)245 Reduction TypedOptimization::ReduceCheckNumber(Node* node) {
246 Node* const input = NodeProperties::GetValueInput(node, 0);
247 Type const input_type = NodeProperties::GetType(input);
248 if (input_type.Is(Type::Number())) {
249 ReplaceWithValue(node, input);
250 return Replace(input);
251 }
252 return NoChange();
253 }
254
ReduceCheckString(Node * node)255 Reduction TypedOptimization::ReduceCheckString(Node* node) {
256 Node* const input = NodeProperties::GetValueInput(node, 0);
257 Type const input_type = NodeProperties::GetType(input);
258 if (input_type.Is(Type::String())) {
259 ReplaceWithValue(node, input);
260 return Replace(input);
261 }
262 return NoChange();
263 }
264
ReduceCheckEqualsInternalizedString(Node * node)265 Reduction TypedOptimization::ReduceCheckEqualsInternalizedString(Node* node) {
266 Node* const exp = NodeProperties::GetValueInput(node, 0);
267 Type const exp_type = NodeProperties::GetType(exp);
268 Node* const val = NodeProperties::GetValueInput(node, 1);
269 Type const val_type = NodeProperties::GetType(val);
270 Node* const effect = NodeProperties::GetEffectInput(node);
271 if (val_type.Is(exp_type)) return Replace(effect);
272 // TODO(turbofan): Should we also try to optimize the
273 // non-internalized String case for {val} here?
274 return NoChange();
275 }
276
ReduceCheckEqualsSymbol(Node * node)277 Reduction TypedOptimization::ReduceCheckEqualsSymbol(Node* node) {
278 Node* const exp = NodeProperties::GetValueInput(node, 0);
279 Type const exp_type = NodeProperties::GetType(exp);
280 Node* const val = NodeProperties::GetValueInput(node, 1);
281 Type const val_type = NodeProperties::GetType(val);
282 Node* const effect = NodeProperties::GetEffectInput(node);
283 if (val_type.Is(exp_type)) return Replace(effect);
284 return NoChange();
285 }
286
ReduceLoadField(Node * node)287 Reduction TypedOptimization::ReduceLoadField(Node* node) {
288 Node* const object = NodeProperties::GetValueInput(node, 0);
289 Type const object_type = NodeProperties::GetType(object);
290 FieldAccess const& access = FieldAccessOf(node->op());
291 if (access.base_is_tagged == kTaggedBase &&
292 access.offset == HeapObject::kMapOffset) {
293 // We can replace LoadField[Map](o) with map if is stable, and
294 // o has type Constant(object) and map == object->map, and either
295 // (1) map cannot transition further, or
296 // (2) deoptimization is enabled and we can add a code dependency on the
297 // stability of map (to guard the Constant type information).
298 base::Optional<MapRef> object_map =
299 GetStableMapFromObjectType(broker(), object_type);
300 if (object_map.has_value()) {
301 dependencies()->DependOnStableMap(*object_map);
302 Node* const value = jsgraph()->Constant(*object_map);
303 ReplaceWithValue(node, value);
304 return Replace(value);
305 }
306 }
307 return NoChange();
308 }
309
ReduceNumberFloor(Node * node)310 Reduction TypedOptimization::ReduceNumberFloor(Node* node) {
311 Node* const input = NodeProperties::GetValueInput(node, 0);
312 Type const input_type = NodeProperties::GetType(input);
313 if (input_type.Is(type_cache_->kIntegerOrMinusZeroOrNaN)) {
314 return Replace(input);
315 }
316 if (input_type.Is(Type::PlainNumber()) &&
317 (input->opcode() == IrOpcode::kNumberDivide ||
318 input->opcode() == IrOpcode::kSpeculativeNumberDivide)) {
319 Node* const lhs = NodeProperties::GetValueInput(input, 0);
320 Type const lhs_type = NodeProperties::GetType(lhs);
321 Node* const rhs = NodeProperties::GetValueInput(input, 1);
322 Type const rhs_type = NodeProperties::GetType(rhs);
323 if (lhs_type.Is(Type::Unsigned32()) && rhs_type.Is(Type::Unsigned32())) {
324 // We can replace
325 //
326 // NumberFloor(NumberDivide(lhs: unsigned32,
327 // rhs: unsigned32)): plain-number
328 //
329 // with
330 //
331 // NumberToUint32(NumberDivide(lhs, rhs))
332 //
333 // and just smash the type [0...lhs.Max] on the {node},
334 // as the truncated result must be lower than {lhs}'s maximum
335 // value (note that {rhs} cannot be less than 1 due to the
336 // plain-number type constraint on the {node}).
337 NodeProperties::ChangeOp(node, simplified()->NumberToUint32());
338 NodeProperties::SetType(node,
339 Type::Range(0, lhs_type.Max(), graph()->zone()));
340 return Changed(node);
341 }
342 }
343 return NoChange();
344 }
345
ReduceNumberRoundop(Node * node)346 Reduction TypedOptimization::ReduceNumberRoundop(Node* node) {
347 Node* const input = NodeProperties::GetValueInput(node, 0);
348 Type const input_type = NodeProperties::GetType(input);
349 if (input_type.Is(type_cache_->kIntegerOrMinusZeroOrNaN)) {
350 return Replace(input);
351 }
352 return NoChange();
353 }
354
ReduceNumberSilenceNaN(Node * node)355 Reduction TypedOptimization::ReduceNumberSilenceNaN(Node* node) {
356 Node* const input = NodeProperties::GetValueInput(node, 0);
357 Type const input_type = NodeProperties::GetType(input);
358 if (input_type.Is(Type::OrderedNumber())) {
359 return Replace(input);
360 }
361 return NoChange();
362 }
363
ReduceNumberToUint8Clamped(Node * node)364 Reduction TypedOptimization::ReduceNumberToUint8Clamped(Node* node) {
365 Node* const input = NodeProperties::GetValueInput(node, 0);
366 Type const input_type = NodeProperties::GetType(input);
367 if (input_type.Is(type_cache_->kUint8)) {
368 return Replace(input);
369 }
370 return NoChange();
371 }
372
ReducePhi(Node * node)373 Reduction TypedOptimization::ReducePhi(Node* node) {
374 // Try to narrow the type of the Phi {node}, which might be more precise now
375 // after lowering based on types, i.e. a SpeculativeNumberAdd has a more
376 // precise type than the JSAdd that was in the graph when the Typer was run.
377 DCHECK_EQ(IrOpcode::kPhi, node->opcode());
378 // Prevent new types from being propagated through loop-related Phis for now.
379 // This is to avoid slow convergence of type narrowing when we learn very
380 // precise information about loop variables.
381 if (NodeProperties::GetControlInput(node, 0)->opcode() == IrOpcode::kLoop) {
382 return NoChange();
383 }
384 int arity = node->op()->ValueInputCount();
385 Type type = NodeProperties::GetType(node->InputAt(0));
386 for (int i = 1; i < arity; ++i) {
387 type = Type::Union(type, NodeProperties::GetType(node->InputAt(i)),
388 graph()->zone());
389 }
390 Type const node_type = NodeProperties::GetType(node);
391 if (!node_type.Is(type)) {
392 type = Type::Intersect(node_type, type, graph()->zone());
393 NodeProperties::SetType(node, type);
394 return Changed(node);
395 }
396 return NoChange();
397 }
398
ReduceReferenceEqual(Node * node)399 Reduction TypedOptimization::ReduceReferenceEqual(Node* node) {
400 DCHECK_EQ(IrOpcode::kReferenceEqual, node->opcode());
401 Node* const lhs = NodeProperties::GetValueInput(node, 0);
402 Node* const rhs = NodeProperties::GetValueInput(node, 1);
403 Type const lhs_type = NodeProperties::GetType(lhs);
404 Type const rhs_type = NodeProperties::GetType(rhs);
405 if (!lhs_type.Maybe(rhs_type)) {
406 Node* replacement = jsgraph()->FalseConstant();
407 // Make sure we do not widen the type.
408 if (NodeProperties::GetType(replacement)
409 .Is(NodeProperties::GetType(node))) {
410 return Replace(jsgraph()->FalseConstant());
411 }
412 }
413 return NoChange();
414 }
415
NumberComparisonFor(const Operator * op)416 const Operator* TypedOptimization::NumberComparisonFor(const Operator* op) {
417 switch (op->opcode()) {
418 case IrOpcode::kStringEqual:
419 return simplified()->NumberEqual();
420 case IrOpcode::kStringLessThan:
421 return simplified()->NumberLessThan();
422 case IrOpcode::kStringLessThanOrEqual:
423 return simplified()->NumberLessThanOrEqual();
424 default:
425 break;
426 }
427 UNREACHABLE();
428 }
429
430 Reduction TypedOptimization::
TryReduceStringComparisonOfStringFromSingleCharCodeToConstant(Node * comparison,const StringRef & string,bool inverted)431 TryReduceStringComparisonOfStringFromSingleCharCodeToConstant(
432 Node* comparison, const StringRef& string, bool inverted) {
433 switch (comparison->opcode()) {
434 case IrOpcode::kStringEqual:
435 if (string.length() != 1) {
436 // String.fromCharCode(x) always has length 1.
437 return Replace(jsgraph()->BooleanConstant(false));
438 }
439 break;
440 case IrOpcode::kStringLessThan:
441 V8_FALLTHROUGH;
442 case IrOpcode::kStringLessThanOrEqual:
443 if (string.length() == 0) {
444 // String.fromCharCode(x) <= "" is always false,
445 // "" < String.fromCharCode(x) is always true.
446 return Replace(jsgraph()->BooleanConstant(inverted));
447 }
448 break;
449 default:
450 UNREACHABLE();
451 }
452 return NoChange();
453 }
454
455 // Try to reduces a string comparison of the form
456 // String.fromCharCode(x) {comparison} {constant} if inverted is false,
457 // and {constant} {comparison} String.fromCharCode(x) if inverted is true.
458 Reduction
TryReduceStringComparisonOfStringFromSingleCharCode(Node * comparison,Node * from_char_code,Type constant_type,bool inverted)459 TypedOptimization::TryReduceStringComparisonOfStringFromSingleCharCode(
460 Node* comparison, Node* from_char_code, Type constant_type, bool inverted) {
461 DCHECK_EQ(IrOpcode::kStringFromSingleCharCode, from_char_code->opcode());
462
463 if (!constant_type.IsHeapConstant()) return NoChange();
464 ObjectRef constant = constant_type.AsHeapConstant()->Ref();
465
466 if (!constant.IsString()) return NoChange();
467 StringRef string = constant.AsString();
468
469 // Check if comparison can be resolved statically.
470 Reduction red = TryReduceStringComparisonOfStringFromSingleCharCodeToConstant(
471 comparison, string, inverted);
472 if (red.Changed()) return red;
473
474 const Operator* comparison_op = NumberComparisonFor(comparison->op());
475 Node* from_char_code_repl = NodeProperties::GetValueInput(from_char_code, 0);
476 Type from_char_code_repl_type = NodeProperties::GetType(from_char_code_repl);
477 if (!from_char_code_repl_type.Is(type_cache_->kUint16)) {
478 // Convert to signed int32 to satisfy type of {NumberBitwiseAnd}.
479 from_char_code_repl =
480 graph()->NewNode(simplified()->NumberToInt32(), from_char_code_repl);
481 from_char_code_repl = graph()->NewNode(
482 simplified()->NumberBitwiseAnd(), from_char_code_repl,
483 jsgraph()->Constant(std::numeric_limits<uint16_t>::max()));
484 }
485 Node* constant_repl = jsgraph()->Constant(string.GetFirstChar());
486
487 Node* number_comparison = nullptr;
488 if (inverted) {
489 // "x..." <= String.fromCharCode(z) is true if x < z.
490 if (string.length() > 1 &&
491 comparison->opcode() == IrOpcode::kStringLessThanOrEqual) {
492 comparison_op = simplified()->NumberLessThan();
493 }
494 number_comparison =
495 graph()->NewNode(comparison_op, constant_repl, from_char_code_repl);
496 } else {
497 // String.fromCharCode(z) < "x..." is true if z <= x.
498 if (string.length() > 1 &&
499 comparison->opcode() == IrOpcode::kStringLessThan) {
500 comparison_op = simplified()->NumberLessThanOrEqual();
501 }
502 number_comparison =
503 graph()->NewNode(comparison_op, from_char_code_repl, constant_repl);
504 }
505 ReplaceWithValue(comparison, number_comparison);
506 return Replace(number_comparison);
507 }
508
ReduceStringComparison(Node * node)509 Reduction TypedOptimization::ReduceStringComparison(Node* node) {
510 DCHECK(IrOpcode::kStringEqual == node->opcode() ||
511 IrOpcode::kStringLessThan == node->opcode() ||
512 IrOpcode::kStringLessThanOrEqual == node->opcode());
513 Node* const lhs = NodeProperties::GetValueInput(node, 0);
514 Node* const rhs = NodeProperties::GetValueInput(node, 1);
515 Type lhs_type = NodeProperties::GetType(lhs);
516 Type rhs_type = NodeProperties::GetType(rhs);
517 if (lhs->opcode() == IrOpcode::kStringFromSingleCharCode) {
518 if (rhs->opcode() == IrOpcode::kStringFromSingleCharCode) {
519 Node* left = NodeProperties::GetValueInput(lhs, 0);
520 Node* right = NodeProperties::GetValueInput(rhs, 0);
521 Type left_type = NodeProperties::GetType(left);
522 Type right_type = NodeProperties::GetType(right);
523 if (!left_type.Is(type_cache_->kUint16)) {
524 // Convert to signed int32 to satisfy type of {NumberBitwiseAnd}.
525 left = graph()->NewNode(simplified()->NumberToInt32(), left);
526 left = graph()->NewNode(
527 simplified()->NumberBitwiseAnd(), left,
528 jsgraph()->Constant(std::numeric_limits<uint16_t>::max()));
529 }
530 if (!right_type.Is(type_cache_->kUint16)) {
531 // Convert to signed int32 to satisfy type of {NumberBitwiseAnd}.
532 right = graph()->NewNode(simplified()->NumberToInt32(), right);
533 right = graph()->NewNode(
534 simplified()->NumberBitwiseAnd(), right,
535 jsgraph()->Constant(std::numeric_limits<uint16_t>::max()));
536 }
537 Node* equal =
538 graph()->NewNode(NumberComparisonFor(node->op()), left, right);
539 ReplaceWithValue(node, equal);
540 return Replace(equal);
541 } else {
542 return TryReduceStringComparisonOfStringFromSingleCharCode(
543 node, lhs, rhs_type, false);
544 }
545 } else if (rhs->opcode() == IrOpcode::kStringFromSingleCharCode) {
546 return TryReduceStringComparisonOfStringFromSingleCharCode(node, rhs,
547 lhs_type, true);
548 }
549 return NoChange();
550 }
551
ReduceStringLength(Node * node)552 Reduction TypedOptimization::ReduceStringLength(Node* node) {
553 DCHECK_EQ(IrOpcode::kStringLength, node->opcode());
554 Node* const input = NodeProperties::GetValueInput(node, 0);
555 switch (input->opcode()) {
556 case IrOpcode::kHeapConstant: {
557 // Constant-fold the String::length of the {input}.
558 HeapObjectMatcher m(input);
559 if (m.Ref(broker()).IsString()) {
560 uint32_t const length = m.Ref(broker()).AsString().length();
561 Node* value = jsgraph()->Constant(length);
562 return Replace(value);
563 }
564 break;
565 }
566 case IrOpcode::kStringConcat: {
567 // The first value input to the {input} is the resulting length.
568 return Replace(input->InputAt(0));
569 }
570 default:
571 break;
572 }
573 return NoChange();
574 }
575
ReduceSameValue(Node * node)576 Reduction TypedOptimization::ReduceSameValue(Node* node) {
577 DCHECK_EQ(IrOpcode::kSameValue, node->opcode());
578 Node* const lhs = NodeProperties::GetValueInput(node, 0);
579 Node* const rhs = NodeProperties::GetValueInput(node, 1);
580 Type const lhs_type = NodeProperties::GetType(lhs);
581 Type const rhs_type = NodeProperties::GetType(rhs);
582 if (ResolveSameValueRenames(lhs) == ResolveSameValueRenames(rhs)) {
583 if (NodeProperties::GetType(node).IsNone()) {
584 return NoChange();
585 }
586 // SameValue(x,x) => #true
587 return Replace(jsgraph()->TrueConstant());
588 } else if (lhs_type.Is(Type::Unique()) && rhs_type.Is(Type::Unique())) {
589 // SameValue(x:unique,y:unique) => ReferenceEqual(x,y)
590 NodeProperties::ChangeOp(node, simplified()->ReferenceEqual());
591 return Changed(node);
592 } else if (lhs_type.Is(Type::String()) && rhs_type.Is(Type::String())) {
593 // SameValue(x:string,y:string) => StringEqual(x,y)
594 NodeProperties::ChangeOp(node, simplified()->StringEqual());
595 return Changed(node);
596 } else if (lhs_type.Is(Type::MinusZero())) {
597 // SameValue(x:minus-zero,y) => ObjectIsMinusZero(y)
598 node->RemoveInput(0);
599 NodeProperties::ChangeOp(node, simplified()->ObjectIsMinusZero());
600 return Changed(node);
601 } else if (rhs_type.Is(Type::MinusZero())) {
602 // SameValue(x,y:minus-zero) => ObjectIsMinusZero(x)
603 node->RemoveInput(1);
604 NodeProperties::ChangeOp(node, simplified()->ObjectIsMinusZero());
605 return Changed(node);
606 } else if (lhs_type.Is(Type::NaN())) {
607 // SameValue(x:nan,y) => ObjectIsNaN(y)
608 node->RemoveInput(0);
609 NodeProperties::ChangeOp(node, simplified()->ObjectIsNaN());
610 return Changed(node);
611 } else if (rhs_type.Is(Type::NaN())) {
612 // SameValue(x,y:nan) => ObjectIsNaN(x)
613 node->RemoveInput(1);
614 NodeProperties::ChangeOp(node, simplified()->ObjectIsNaN());
615 return Changed(node);
616 } else if (lhs_type.Is(Type::PlainNumber()) &&
617 rhs_type.Is(Type::PlainNumber())) {
618 // SameValue(x:plain-number,y:plain-number) => NumberEqual(x,y)
619 NodeProperties::ChangeOp(node, simplified()->NumberEqual());
620 return Changed(node);
621 }
622 return NoChange();
623 }
624
ReduceSelect(Node * node)625 Reduction TypedOptimization::ReduceSelect(Node* node) {
626 DCHECK_EQ(IrOpcode::kSelect, node->opcode());
627 Node* const condition = NodeProperties::GetValueInput(node, 0);
628 Type const condition_type = NodeProperties::GetType(condition);
629 Node* const vtrue = NodeProperties::GetValueInput(node, 1);
630 Type const vtrue_type = NodeProperties::GetType(vtrue);
631 Node* const vfalse = NodeProperties::GetValueInput(node, 2);
632 Type const vfalse_type = NodeProperties::GetType(vfalse);
633 if (condition_type.Is(true_type_)) {
634 // Select(condition:true, vtrue, vfalse) => vtrue
635 return Replace(vtrue);
636 }
637 if (condition_type.Is(false_type_)) {
638 // Select(condition:false, vtrue, vfalse) => vfalse
639 return Replace(vfalse);
640 }
641 if (vtrue_type.Is(true_type_) && vfalse_type.Is(false_type_)) {
642 // Select(condition, vtrue:true, vfalse:false) => condition
643 return Replace(condition);
644 }
645 if (vtrue_type.Is(false_type_) && vfalse_type.Is(true_type_)) {
646 // Select(condition, vtrue:false, vfalse:true) => BooleanNot(condition)
647 node->TrimInputCount(1);
648 NodeProperties::ChangeOp(node, simplified()->BooleanNot());
649 return Changed(node);
650 }
651 // Try to narrow the type of the Select {node}, which might be more precise
652 // now after lowering based on types.
653 Type type = Type::Union(vtrue_type, vfalse_type, graph()->zone());
654 Type const node_type = NodeProperties::GetType(node);
655 if (!node_type.Is(type)) {
656 type = Type::Intersect(node_type, type, graph()->zone());
657 NodeProperties::SetType(node, type);
658 return Changed(node);
659 }
660 return NoChange();
661 }
662
ReduceSpeculativeToNumber(Node * node)663 Reduction TypedOptimization::ReduceSpeculativeToNumber(Node* node) {
664 DCHECK_EQ(IrOpcode::kSpeculativeToNumber, node->opcode());
665 Node* const input = NodeProperties::GetValueInput(node, 0);
666 Type const input_type = NodeProperties::GetType(input);
667 if (input_type.Is(Type::Number())) {
668 // SpeculativeToNumber(x:number) => x
669 ReplaceWithValue(node, input);
670 return Replace(input);
671 }
672 return NoChange();
673 }
674
ReduceTypeOf(Node * node)675 Reduction TypedOptimization::ReduceTypeOf(Node* node) {
676 Node* const input = node->InputAt(0);
677 Type const type = NodeProperties::GetType(input);
678 Factory* const f = factory();
679 if (type.Is(Type::Boolean())) {
680 return Replace(
681 jsgraph()->Constant(ObjectRef(broker(), f->boolean_string())));
682 } else if (type.Is(Type::Number())) {
683 return Replace(
684 jsgraph()->Constant(ObjectRef(broker(), f->number_string())));
685 } else if (type.Is(Type::String())) {
686 return Replace(
687 jsgraph()->Constant(ObjectRef(broker(), f->string_string())));
688 } else if (type.Is(Type::BigInt())) {
689 return Replace(
690 jsgraph()->Constant(ObjectRef(broker(), f->bigint_string())));
691 } else if (type.Is(Type::Symbol())) {
692 return Replace(
693 jsgraph()->Constant(ObjectRef(broker(), f->symbol_string())));
694 } else if (type.Is(Type::OtherUndetectableOrUndefined())) {
695 return Replace(
696 jsgraph()->Constant(ObjectRef(broker(), f->undefined_string())));
697 } else if (type.Is(Type::NonCallableOrNull())) {
698 return Replace(
699 jsgraph()->Constant(ObjectRef(broker(), f->object_string())));
700 } else if (type.Is(Type::Function())) {
701 return Replace(
702 jsgraph()->Constant(ObjectRef(broker(), f->function_string())));
703 }
704 return NoChange();
705 }
706
ReduceToBoolean(Node * node)707 Reduction TypedOptimization::ReduceToBoolean(Node* node) {
708 Node* const input = node->InputAt(0);
709 Type const input_type = NodeProperties::GetType(input);
710 if (input_type.Is(Type::Boolean())) {
711 // ToBoolean(x:boolean) => x
712 return Replace(input);
713 } else if (input_type.Is(Type::OrderedNumber())) {
714 // SToBoolean(x:ordered-number) => BooleanNot(NumberEqual(x,#0))
715 node->ReplaceInput(0, graph()->NewNode(simplified()->NumberEqual(), input,
716 jsgraph()->ZeroConstant()));
717 node->TrimInputCount(1);
718 NodeProperties::ChangeOp(node, simplified()->BooleanNot());
719 return Changed(node);
720 } else if (input_type.Is(Type::Number())) {
721 // ToBoolean(x:number) => NumberToBoolean(x)
722 node->TrimInputCount(1);
723 NodeProperties::ChangeOp(node, simplified()->NumberToBoolean());
724 return Changed(node);
725 } else if (input_type.Is(Type::DetectableReceiverOrNull())) {
726 // ToBoolean(x:detectable receiver \/ null)
727 // => BooleanNot(ReferenceEqual(x,#null))
728 node->ReplaceInput(0, graph()->NewNode(simplified()->ReferenceEqual(),
729 input, jsgraph()->NullConstant()));
730 node->TrimInputCount(1);
731 NodeProperties::ChangeOp(node, simplified()->BooleanNot());
732 return Changed(node);
733 } else if (input_type.Is(Type::ReceiverOrNullOrUndefined())) {
734 // ToBoolean(x:receiver \/ null \/ undefined)
735 // => BooleanNot(ObjectIsUndetectable(x))
736 node->ReplaceInput(
737 0, graph()->NewNode(simplified()->ObjectIsUndetectable(), input));
738 node->TrimInputCount(1);
739 NodeProperties::ChangeOp(node, simplified()->BooleanNot());
740 return Changed(node);
741 } else if (input_type.Is(Type::String())) {
742 // ToBoolean(x:string) => BooleanNot(ReferenceEqual(x,""))
743 node->ReplaceInput(0,
744 graph()->NewNode(simplified()->ReferenceEqual(), input,
745 jsgraph()->EmptyStringConstant()));
746 node->TrimInputCount(1);
747 NodeProperties::ChangeOp(node, simplified()->BooleanNot());
748 return Changed(node);
749 }
750 return NoChange();
751 }
752
753 namespace {
BothAre(Type t1,Type t2,Type t3)754 bool BothAre(Type t1, Type t2, Type t3) { return t1.Is(t3) && t2.Is(t3); }
755
NeitherCanBe(Type t1,Type t2,Type t3)756 bool NeitherCanBe(Type t1, Type t2, Type t3) {
757 return !t1.Maybe(t3) && !t2.Maybe(t3);
758 }
759
NumberOpFromSpeculativeNumberOp(SimplifiedOperatorBuilder * simplified,const Operator * op)760 const Operator* NumberOpFromSpeculativeNumberOp(
761 SimplifiedOperatorBuilder* simplified, const Operator* op) {
762 switch (op->opcode()) {
763 case IrOpcode::kSpeculativeNumberEqual:
764 return simplified->NumberEqual();
765 case IrOpcode::kSpeculativeNumberLessThan:
766 return simplified->NumberLessThan();
767 case IrOpcode::kSpeculativeNumberLessThanOrEqual:
768 return simplified->NumberLessThanOrEqual();
769 case IrOpcode::kSpeculativeNumberAdd:
770 // Handled by ReduceSpeculativeNumberAdd.
771 UNREACHABLE();
772 case IrOpcode::kSpeculativeNumberSubtract:
773 return simplified->NumberSubtract();
774 case IrOpcode::kSpeculativeNumberMultiply:
775 return simplified->NumberMultiply();
776 case IrOpcode::kSpeculativeNumberDivide:
777 return simplified->NumberDivide();
778 case IrOpcode::kSpeculativeNumberModulus:
779 return simplified->NumberModulus();
780 default:
781 break;
782 }
783 UNREACHABLE();
784 }
785
786 } // namespace
787
ReduceSpeculativeNumberAdd(Node * node)788 Reduction TypedOptimization::ReduceSpeculativeNumberAdd(Node* node) {
789 Node* const lhs = NodeProperties::GetValueInput(node, 0);
790 Node* const rhs = NodeProperties::GetValueInput(node, 1);
791 Type const lhs_type = NodeProperties::GetType(lhs);
792 Type const rhs_type = NodeProperties::GetType(rhs);
793 NumberOperationHint hint = NumberOperationHintOf(node->op());
794 if ((hint == NumberOperationHint::kNumber ||
795 hint == NumberOperationHint::kNumberOrOddball) &&
796 BothAre(lhs_type, rhs_type, Type::PlainPrimitive()) &&
797 NeitherCanBe(lhs_type, rhs_type, Type::StringOrReceiver())) {
798 // SpeculativeNumberAdd(x:-string, y:-string) =>
799 // NumberAdd(ToNumber(x), ToNumber(y))
800 Node* const toNum_lhs = ConvertPlainPrimitiveToNumber(lhs);
801 Node* const toNum_rhs = ConvertPlainPrimitiveToNumber(rhs);
802 Node* const value =
803 graph()->NewNode(simplified()->NumberAdd(), toNum_lhs, toNum_rhs);
804 ReplaceWithValue(node, value);
805 return Replace(value);
806 }
807 return NoChange();
808 }
809
ReduceJSToNumberInput(Node * input)810 Reduction TypedOptimization::ReduceJSToNumberInput(Node* input) {
811 // Try constant-folding of JSToNumber with constant inputs.
812 Type input_type = NodeProperties::GetType(input);
813
814 if (input_type.Is(Type::String())) {
815 HeapObjectMatcher m(input);
816 if (m.HasResolvedValue() && m.Ref(broker()).IsString()) {
817 StringRef input_value = m.Ref(broker()).AsString();
818 double number;
819 ASSIGN_RETURN_NO_CHANGE_IF_DATA_MISSING(number, input_value.ToNumber());
820 return Replace(jsgraph()->Constant(number));
821 }
822 }
823 if (input_type.IsHeapConstant()) {
824 HeapObjectRef input_value = input_type.AsHeapConstant()->Ref();
825 double value;
826 if (input_value.OddballToNumber().To(&value)) {
827 return Replace(jsgraph()->Constant(value));
828 }
829 }
830 if (input_type.Is(Type::Number())) {
831 // JSToNumber(x:number) => x
832 return Changed(input);
833 }
834 if (input_type.Is(Type::Undefined())) {
835 // JSToNumber(undefined) => #NaN
836 return Replace(jsgraph()->NaNConstant());
837 }
838 if (input_type.Is(Type::Null())) {
839 // JSToNumber(null) => #0
840 return Replace(jsgraph()->ZeroConstant());
841 }
842 return NoChange();
843 }
844
ConvertPlainPrimitiveToNumber(Node * node)845 Node* TypedOptimization::ConvertPlainPrimitiveToNumber(Node* node) {
846 DCHECK(NodeProperties::GetType(node).Is(Type::PlainPrimitive()));
847 // Avoid inserting too many eager ToNumber() operations.
848 Reduction const reduction = ReduceJSToNumberInput(node);
849 if (reduction.Changed()) return reduction.replacement();
850 if (NodeProperties::GetType(node).Is(Type::Number())) {
851 return node;
852 }
853 return graph()->NewNode(simplified()->PlainPrimitiveToNumber(), node);
854 }
855
ReduceSpeculativeNumberBinop(Node * node)856 Reduction TypedOptimization::ReduceSpeculativeNumberBinop(Node* node) {
857 Node* const lhs = NodeProperties::GetValueInput(node, 0);
858 Node* const rhs = NodeProperties::GetValueInput(node, 1);
859 Type const lhs_type = NodeProperties::GetType(lhs);
860 Type const rhs_type = NodeProperties::GetType(rhs);
861 NumberOperationHint hint = NumberOperationHintOf(node->op());
862 if ((hint == NumberOperationHint::kNumber ||
863 hint == NumberOperationHint::kNumberOrOddball) &&
864 BothAre(lhs_type, rhs_type, Type::NumberOrUndefinedOrNullOrBoolean())) {
865 // We intentionally do this only in the Number and NumberOrOddball hint case
866 // because simplified lowering of these speculative ops may do some clever
867 // reductions in the other cases.
868 Node* const toNum_lhs = ConvertPlainPrimitiveToNumber(lhs);
869 Node* const toNum_rhs = ConvertPlainPrimitiveToNumber(rhs);
870 Node* const value = graph()->NewNode(
871 NumberOpFromSpeculativeNumberOp(simplified(), node->op()), toNum_lhs,
872 toNum_rhs);
873 ReplaceWithValue(node, value);
874 return Replace(value);
875 }
876 return NoChange();
877 }
878
ReduceSpeculativeNumberComparison(Node * node)879 Reduction TypedOptimization::ReduceSpeculativeNumberComparison(Node* node) {
880 Node* const lhs = NodeProperties::GetValueInput(node, 0);
881 Node* const rhs = NodeProperties::GetValueInput(node, 1);
882 Type const lhs_type = NodeProperties::GetType(lhs);
883 Type const rhs_type = NodeProperties::GetType(rhs);
884 if (BothAre(lhs_type, rhs_type, Type::Signed32()) ||
885 BothAre(lhs_type, rhs_type, Type::Unsigned32())) {
886 Node* const value = graph()->NewNode(
887 NumberOpFromSpeculativeNumberOp(simplified(), node->op()), lhs, rhs);
888 ReplaceWithValue(node, value);
889 return Replace(value);
890 }
891 return NoChange();
892 }
893
factory() const894 Factory* TypedOptimization::factory() const {
895 return jsgraph()->isolate()->factory();
896 }
897
graph() const898 Graph* TypedOptimization::graph() const { return jsgraph()->graph(); }
899
simplified() const900 SimplifiedOperatorBuilder* TypedOptimization::simplified() const {
901 return jsgraph()->simplified();
902 }
903
904 } // namespace compiler
905 } // namespace internal
906 } // namespace v8
907