blob: a9c6228cd35c096636a22d9e2358434dfd48e5cc [file] [log] [blame]
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001// Copyright 2012 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-instructions.h"
6
7#include "src/base/bits.h"
8#include "src/base/safe_math.h"
9#include "src/crankshaft/hydrogen-infer-representation.h"
10#include "src/double.h"
11#include "src/elements.h"
12#include "src/factory.h"
13
14#if V8_TARGET_ARCH_IA32
15#include "src/crankshaft/ia32/lithium-ia32.h" // NOLINT
16#elif V8_TARGET_ARCH_X64
17#include "src/crankshaft/x64/lithium-x64.h" // NOLINT
18#elif V8_TARGET_ARCH_ARM64
19#include "src/crankshaft/arm64/lithium-arm64.h" // NOLINT
20#elif V8_TARGET_ARCH_ARM
21#include "src/crankshaft/arm/lithium-arm.h" // NOLINT
22#elif V8_TARGET_ARCH_PPC
23#include "src/crankshaft/ppc/lithium-ppc.h" // NOLINT
24#elif V8_TARGET_ARCH_MIPS
25#include "src/crankshaft/mips/lithium-mips.h" // NOLINT
26#elif V8_TARGET_ARCH_MIPS64
27#include "src/crankshaft/mips64/lithium-mips64.h" // NOLINT
28#elif V8_TARGET_ARCH_X87
29#include "src/crankshaft/x87/lithium-x87.h" // NOLINT
30#else
31#error Unsupported target architecture.
32#endif
33
34namespace v8 {
35namespace internal {
36
37#define DEFINE_COMPILE(type) \
38 LInstruction* H##type::CompileToLithium(LChunkBuilder* builder) { \
39 return builder->Do##type(this); \
40 }
41HYDROGEN_CONCRETE_INSTRUCTION_LIST(DEFINE_COMPILE)
42#undef DEFINE_COMPILE
43
44
45Isolate* HValue::isolate() const {
46 DCHECK(block() != NULL);
47 return block()->isolate();
48}
49
50
51void HValue::AssumeRepresentation(Representation r) {
52 if (CheckFlag(kFlexibleRepresentation)) {
53 ChangeRepresentation(r);
54 // The representation of the value is dictated by type feedback and
55 // will not be changed later.
56 ClearFlag(kFlexibleRepresentation);
57 }
58}
59
60
61void HValue::InferRepresentation(HInferRepresentationPhase* h_infer) {
62 DCHECK(CheckFlag(kFlexibleRepresentation));
63 Representation new_rep = RepresentationFromInputs();
64 UpdateRepresentation(new_rep, h_infer, "inputs");
65 new_rep = RepresentationFromUses();
66 UpdateRepresentation(new_rep, h_infer, "uses");
67 if (representation().IsSmi() && HasNonSmiUse()) {
68 UpdateRepresentation(
69 Representation::Integer32(), h_infer, "use requirements");
70 }
71}
72
73
74Representation HValue::RepresentationFromUses() {
75 if (HasNoUses()) return Representation::None();
76 Representation result = Representation::None();
77
78 for (HUseIterator it(uses()); !it.Done(); it.Advance()) {
79 HValue* use = it.value();
80 Representation rep = use->observed_input_representation(it.index());
81 result = result.generalize(rep);
82
83 if (FLAG_trace_representation) {
84 PrintF("#%d %s is used by #%d %s as %s%s\n",
85 id(), Mnemonic(), use->id(), use->Mnemonic(), rep.Mnemonic(),
86 (use->CheckFlag(kTruncatingToInt32) ? "-trunc" : ""));
87 }
88 }
89 if (IsPhi()) {
90 result = result.generalize(
91 HPhi::cast(this)->representation_from_indirect_uses());
92 }
93
94 // External representations are dealt with separately.
95 return result.IsExternal() ? Representation::None() : result;
96}
97
98
99void HValue::UpdateRepresentation(Representation new_rep,
100 HInferRepresentationPhase* h_infer,
101 const char* reason) {
102 Representation r = representation();
103 if (new_rep.is_more_general_than(r)) {
104 if (CheckFlag(kCannotBeTagged) && new_rep.IsTagged()) return;
105 if (FLAG_trace_representation) {
106 PrintF("Changing #%d %s representation %s -> %s based on %s\n",
107 id(), Mnemonic(), r.Mnemonic(), new_rep.Mnemonic(), reason);
108 }
109 ChangeRepresentation(new_rep);
110 AddDependantsToWorklist(h_infer);
111 }
112}
113
114
115void HValue::AddDependantsToWorklist(HInferRepresentationPhase* h_infer) {
116 for (HUseIterator it(uses()); !it.Done(); it.Advance()) {
117 h_infer->AddToWorklist(it.value());
118 }
119 for (int i = 0; i < OperandCount(); ++i) {
120 h_infer->AddToWorklist(OperandAt(i));
121 }
122}
123
124
125static int32_t ConvertAndSetOverflow(Representation r,
126 int64_t result,
127 bool* overflow) {
128 if (r.IsSmi()) {
129 if (result > Smi::kMaxValue) {
130 *overflow = true;
131 return Smi::kMaxValue;
132 }
133 if (result < Smi::kMinValue) {
134 *overflow = true;
135 return Smi::kMinValue;
136 }
137 } else {
138 if (result > kMaxInt) {
139 *overflow = true;
140 return kMaxInt;
141 }
142 if (result < kMinInt) {
143 *overflow = true;
144 return kMinInt;
145 }
146 }
147 return static_cast<int32_t>(result);
148}
149
150
151static int32_t AddWithoutOverflow(Representation r,
152 int32_t a,
153 int32_t b,
154 bool* overflow) {
155 int64_t result = static_cast<int64_t>(a) + static_cast<int64_t>(b);
156 return ConvertAndSetOverflow(r, result, overflow);
157}
158
159
160static int32_t SubWithoutOverflow(Representation r,
161 int32_t a,
162 int32_t b,
163 bool* overflow) {
164 int64_t result = static_cast<int64_t>(a) - static_cast<int64_t>(b);
165 return ConvertAndSetOverflow(r, result, overflow);
166}
167
168
169static int32_t MulWithoutOverflow(const Representation& r,
170 int32_t a,
171 int32_t b,
172 bool* overflow) {
173 int64_t result = static_cast<int64_t>(a) * static_cast<int64_t>(b);
174 return ConvertAndSetOverflow(r, result, overflow);
175}
176
177
178int32_t Range::Mask() const {
179 if (lower_ == upper_) return lower_;
180 if (lower_ >= 0) {
181 int32_t res = 1;
182 while (res < upper_) {
183 res = (res << 1) | 1;
184 }
185 return res;
186 }
187 return 0xffffffff;
188}
189
190
191void Range::AddConstant(int32_t value) {
192 if (value == 0) return;
193 bool may_overflow = false; // Overflow is ignored here.
194 Representation r = Representation::Integer32();
195 lower_ = AddWithoutOverflow(r, lower_, value, &may_overflow);
196 upper_ = AddWithoutOverflow(r, upper_, value, &may_overflow);
197#ifdef DEBUG
198 Verify();
199#endif
200}
201
202
203void Range::Intersect(Range* other) {
204 upper_ = Min(upper_, other->upper_);
205 lower_ = Max(lower_, other->lower_);
206 bool b = CanBeMinusZero() && other->CanBeMinusZero();
207 set_can_be_minus_zero(b);
208}
209
210
211void Range::Union(Range* other) {
212 upper_ = Max(upper_, other->upper_);
213 lower_ = Min(lower_, other->lower_);
214 bool b = CanBeMinusZero() || other->CanBeMinusZero();
215 set_can_be_minus_zero(b);
216}
217
218
219void Range::CombinedMax(Range* other) {
220 upper_ = Max(upper_, other->upper_);
221 lower_ = Max(lower_, other->lower_);
222 set_can_be_minus_zero(CanBeMinusZero() || other->CanBeMinusZero());
223}
224
225
226void Range::CombinedMin(Range* other) {
227 upper_ = Min(upper_, other->upper_);
228 lower_ = Min(lower_, other->lower_);
229 set_can_be_minus_zero(CanBeMinusZero() || other->CanBeMinusZero());
230}
231
232
233void Range::Sar(int32_t value) {
234 int32_t bits = value & 0x1F;
235 lower_ = lower_ >> bits;
236 upper_ = upper_ >> bits;
237 set_can_be_minus_zero(false);
238}
239
240
241void Range::Shl(int32_t value) {
242 int32_t bits = value & 0x1F;
243 int old_lower = lower_;
244 int old_upper = upper_;
245 lower_ = lower_ << bits;
246 upper_ = upper_ << bits;
247 if (old_lower != lower_ >> bits || old_upper != upper_ >> bits) {
248 upper_ = kMaxInt;
249 lower_ = kMinInt;
250 }
251 set_can_be_minus_zero(false);
252}
253
254
255bool Range::AddAndCheckOverflow(const Representation& r, Range* other) {
256 bool may_overflow = false;
257 lower_ = AddWithoutOverflow(r, lower_, other->lower(), &may_overflow);
258 upper_ = AddWithoutOverflow(r, upper_, other->upper(), &may_overflow);
259 KeepOrder();
260#ifdef DEBUG
261 Verify();
262#endif
263 return may_overflow;
264}
265
266
267bool Range::SubAndCheckOverflow(const Representation& r, Range* other) {
268 bool may_overflow = false;
269 lower_ = SubWithoutOverflow(r, lower_, other->upper(), &may_overflow);
270 upper_ = SubWithoutOverflow(r, upper_, other->lower(), &may_overflow);
271 KeepOrder();
272#ifdef DEBUG
273 Verify();
274#endif
275 return may_overflow;
276}
277
278
279void Range::KeepOrder() {
280 if (lower_ > upper_) {
281 int32_t tmp = lower_;
282 lower_ = upper_;
283 upper_ = tmp;
284 }
285}
286
287
288#ifdef DEBUG
289void Range::Verify() const {
290 DCHECK(lower_ <= upper_);
291}
292#endif
293
294
295bool Range::MulAndCheckOverflow(const Representation& r, Range* other) {
296 bool may_overflow = false;
297 int v1 = MulWithoutOverflow(r, lower_, other->lower(), &may_overflow);
298 int v2 = MulWithoutOverflow(r, lower_, other->upper(), &may_overflow);
299 int v3 = MulWithoutOverflow(r, upper_, other->lower(), &may_overflow);
300 int v4 = MulWithoutOverflow(r, upper_, other->upper(), &may_overflow);
301 lower_ = Min(Min(v1, v2), Min(v3, v4));
302 upper_ = Max(Max(v1, v2), Max(v3, v4));
303#ifdef DEBUG
304 Verify();
305#endif
306 return may_overflow;
307}
308
309
310bool HValue::IsDefinedAfter(HBasicBlock* other) const {
311 return block()->block_id() > other->block_id();
312}
313
314
315HUseListNode* HUseListNode::tail() {
316 // Skip and remove dead items in the use list.
317 while (tail_ != NULL && tail_->value()->CheckFlag(HValue::kIsDead)) {
318 tail_ = tail_->tail_;
319 }
320 return tail_;
321}
322
323
324bool HValue::CheckUsesForFlag(Flag f) const {
325 for (HUseIterator it(uses()); !it.Done(); it.Advance()) {
326 if (it.value()->IsSimulate()) continue;
327 if (!it.value()->CheckFlag(f)) return false;
328 }
329 return true;
330}
331
332
333bool HValue::CheckUsesForFlag(Flag f, HValue** value) const {
334 for (HUseIterator it(uses()); !it.Done(); it.Advance()) {
335 if (it.value()->IsSimulate()) continue;
336 if (!it.value()->CheckFlag(f)) {
337 *value = it.value();
338 return false;
339 }
340 }
341 return true;
342}
343
344
345bool HValue::HasAtLeastOneUseWithFlagAndNoneWithout(Flag f) const {
346 bool return_value = false;
347 for (HUseIterator it(uses()); !it.Done(); it.Advance()) {
348 if (it.value()->IsSimulate()) continue;
349 if (!it.value()->CheckFlag(f)) return false;
350 return_value = true;
351 }
352 return return_value;
353}
354
355
356HUseIterator::HUseIterator(HUseListNode* head) : next_(head) {
357 Advance();
358}
359
360
361void HUseIterator::Advance() {
362 current_ = next_;
363 if (current_ != NULL) {
364 next_ = current_->tail();
365 value_ = current_->value();
366 index_ = current_->index();
367 }
368}
369
370
371int HValue::UseCount() const {
372 int count = 0;
373 for (HUseIterator it(uses()); !it.Done(); it.Advance()) ++count;
374 return count;
375}
376
377
378HUseListNode* HValue::RemoveUse(HValue* value, int index) {
379 HUseListNode* previous = NULL;
380 HUseListNode* current = use_list_;
381 while (current != NULL) {
382 if (current->value() == value && current->index() == index) {
383 if (previous == NULL) {
384 use_list_ = current->tail();
385 } else {
386 previous->set_tail(current->tail());
387 }
388 break;
389 }
390
391 previous = current;
392 current = current->tail();
393 }
394
395#ifdef DEBUG
396 // Do not reuse use list nodes in debug mode, zap them.
397 if (current != NULL) {
398 HUseListNode* temp =
399 new(block()->zone())
400 HUseListNode(current->value(), current->index(), NULL);
401 current->Zap();
402 current = temp;
403 }
404#endif
405 return current;
406}
407
408
409bool HValue::Equals(HValue* other) {
410 if (other->opcode() != opcode()) return false;
411 if (!other->representation().Equals(representation())) return false;
412 if (!other->type_.Equals(type_)) return false;
413 if (other->flags() != flags()) return false;
414 if (OperandCount() != other->OperandCount()) return false;
415 for (int i = 0; i < OperandCount(); ++i) {
416 if (OperandAt(i)->id() != other->OperandAt(i)->id()) return false;
417 }
418 bool result = DataEquals(other);
419 DCHECK(!result || Hashcode() == other->Hashcode());
420 return result;
421}
422
423
424intptr_t HValue::Hashcode() {
425 intptr_t result = opcode();
426 int count = OperandCount();
427 for (int i = 0; i < count; ++i) {
428 result = result * 19 + OperandAt(i)->id() + (result >> 7);
429 }
430 return result;
431}
432
433
434const char* HValue::Mnemonic() const {
435 switch (opcode()) {
436#define MAKE_CASE(type) case k##type: return #type;
437 HYDROGEN_CONCRETE_INSTRUCTION_LIST(MAKE_CASE)
438#undef MAKE_CASE
439 case kPhi: return "Phi";
440 default: return "";
441 }
442}
443
444
445bool HValue::CanReplaceWithDummyUses() {
446 return FLAG_unreachable_code_elimination &&
447 !(block()->IsReachable() ||
448 IsBlockEntry() ||
449 IsControlInstruction() ||
450 IsArgumentsObject() ||
451 IsCapturedObject() ||
452 IsSimulate() ||
453 IsEnterInlined() ||
454 IsLeaveInlined());
455}
456
457
458bool HValue::IsInteger32Constant() {
459 return IsConstant() && HConstant::cast(this)->HasInteger32Value();
460}
461
462
463int32_t HValue::GetInteger32Constant() {
464 return HConstant::cast(this)->Integer32Value();
465}
466
467
468bool HValue::EqualsInteger32Constant(int32_t value) {
469 return IsInteger32Constant() && GetInteger32Constant() == value;
470}
471
472
473void HValue::SetOperandAt(int index, HValue* value) {
474 RegisterUse(index, value);
475 InternalSetOperandAt(index, value);
476}
477
478
479void HValue::DeleteAndReplaceWith(HValue* other) {
480 // We replace all uses first, so Delete can assert that there are none.
481 if (other != NULL) ReplaceAllUsesWith(other);
482 Kill();
483 DeleteFromGraph();
484}
485
486
487void HValue::ReplaceAllUsesWith(HValue* other) {
488 while (use_list_ != NULL) {
489 HUseListNode* list_node = use_list_;
490 HValue* value = list_node->value();
491 DCHECK(!value->block()->IsStartBlock());
492 value->InternalSetOperandAt(list_node->index(), other);
493 use_list_ = list_node->tail();
494 list_node->set_tail(other->use_list_);
495 other->use_list_ = list_node;
496 }
497}
498
499
500void HValue::Kill() {
501 // Instead of going through the entire use list of each operand, we only
502 // check the first item in each use list and rely on the tail() method to
503 // skip dead items, removing them lazily next time we traverse the list.
504 SetFlag(kIsDead);
505 for (int i = 0; i < OperandCount(); ++i) {
506 HValue* operand = OperandAt(i);
507 if (operand == NULL) continue;
508 HUseListNode* first = operand->use_list_;
509 if (first != NULL && first->value()->CheckFlag(kIsDead)) {
510 operand->use_list_ = first->tail();
511 }
512 }
513}
514
515
516void HValue::SetBlock(HBasicBlock* block) {
517 DCHECK(block_ == NULL || block == NULL);
518 block_ = block;
519 if (id_ == kNoNumber && block != NULL) {
520 id_ = block->graph()->GetNextValueID(this);
521 }
522}
523
524
525std::ostream& operator<<(std::ostream& os, const HValue& v) {
526 return v.PrintTo(os);
527}
528
529
530std::ostream& operator<<(std::ostream& os, const TypeOf& t) {
531 if (t.value->representation().IsTagged() &&
532 !t.value->type().Equals(HType::Tagged()))
533 return os;
534 return os << " type:" << t.value->type();
535}
536
537
538std::ostream& operator<<(std::ostream& os, const ChangesOf& c) {
539 GVNFlagSet changes_flags = c.value->ChangesFlags();
540 if (changes_flags.IsEmpty()) return os;
541 os << " changes[";
542 if (changes_flags == c.value->AllSideEffectsFlagSet()) {
543 os << "*";
544 } else {
545 bool add_comma = false;
546#define PRINT_DO(Type) \
547 if (changes_flags.Contains(k##Type)) { \
548 if (add_comma) os << ","; \
549 add_comma = true; \
550 os << #Type; \
551 }
552 GVN_TRACKED_FLAG_LIST(PRINT_DO);
553 GVN_UNTRACKED_FLAG_LIST(PRINT_DO);
554#undef PRINT_DO
555 }
556 return os << "]";
557}
558
559
560bool HValue::HasMonomorphicJSObjectType() {
561 return !GetMonomorphicJSObjectMap().is_null();
562}
563
564
565bool HValue::UpdateInferredType() {
566 HType type = CalculateInferredType();
567 bool result = (!type.Equals(type_));
568 type_ = type;
569 return result;
570}
571
572
573void HValue::RegisterUse(int index, HValue* new_value) {
574 HValue* old_value = OperandAt(index);
575 if (old_value == new_value) return;
576
577 HUseListNode* removed = NULL;
578 if (old_value != NULL) {
579 removed = old_value->RemoveUse(this, index);
580 }
581
582 if (new_value != NULL) {
583 if (removed == NULL) {
584 new_value->use_list_ = new(new_value->block()->zone()) HUseListNode(
585 this, index, new_value->use_list_);
586 } else {
587 removed->set_tail(new_value->use_list_);
588 new_value->use_list_ = removed;
589 }
590 }
591}
592
593
594void HValue::AddNewRange(Range* r, Zone* zone) {
595 if (!HasRange()) ComputeInitialRange(zone);
596 if (!HasRange()) range_ = new(zone) Range();
597 DCHECK(HasRange());
598 r->StackUpon(range_);
599 range_ = r;
600}
601
602
603void HValue::RemoveLastAddedRange() {
604 DCHECK(HasRange());
605 DCHECK(range_->next() != NULL);
606 range_ = range_->next();
607}
608
609
610void HValue::ComputeInitialRange(Zone* zone) {
611 DCHECK(!HasRange());
612 range_ = InferRange(zone);
613 DCHECK(HasRange());
614}
615
616
617std::ostream& HInstruction::PrintTo(std::ostream& os) const { // NOLINT
618 os << Mnemonic() << " ";
619 PrintDataTo(os) << ChangesOf(this) << TypeOf(this);
620 if (CheckFlag(HValue::kHasNoObservableSideEffects)) os << " [noOSE]";
621 if (CheckFlag(HValue::kIsDead)) os << " [dead]";
622 return os;
623}
624
625
626std::ostream& HInstruction::PrintDataTo(std::ostream& os) const { // NOLINT
627 for (int i = 0; i < OperandCount(); ++i) {
628 if (i > 0) os << " ";
629 os << NameOf(OperandAt(i));
630 }
631 return os;
632}
633
634
635void HInstruction::Unlink() {
636 DCHECK(IsLinked());
637 DCHECK(!IsControlInstruction()); // Must never move control instructions.
638 DCHECK(!IsBlockEntry()); // Doesn't make sense to delete these.
639 DCHECK(previous_ != NULL);
640 previous_->next_ = next_;
641 if (next_ == NULL) {
642 DCHECK(block()->last() == this);
643 block()->set_last(previous_);
644 } else {
645 next_->previous_ = previous_;
646 }
647 clear_block();
648}
649
650
651void HInstruction::InsertBefore(HInstruction* next) {
652 DCHECK(!IsLinked());
653 DCHECK(!next->IsBlockEntry());
654 DCHECK(!IsControlInstruction());
655 DCHECK(!next->block()->IsStartBlock());
656 DCHECK(next->previous_ != NULL);
657 HInstruction* prev = next->previous();
658 prev->next_ = this;
659 next->previous_ = this;
660 next_ = next;
661 previous_ = prev;
662 SetBlock(next->block());
663 if (!has_position() && next->has_position()) {
664 set_position(next->position());
665 }
666}
667
668
669void HInstruction::InsertAfter(HInstruction* previous) {
670 DCHECK(!IsLinked());
671 DCHECK(!previous->IsControlInstruction());
672 DCHECK(!IsControlInstruction() || previous->next_ == NULL);
673 HBasicBlock* block = previous->block();
674 // Never insert anything except constants into the start block after finishing
675 // it.
676 if (block->IsStartBlock() && block->IsFinished() && !IsConstant()) {
677 DCHECK(block->end()->SecondSuccessor() == NULL);
678 InsertAfter(block->end()->FirstSuccessor()->first());
679 return;
680 }
681
682 // If we're inserting after an instruction with side-effects that is
683 // followed by a simulate instruction, we need to insert after the
684 // simulate instruction instead.
685 HInstruction* next = previous->next_;
686 if (previous->HasObservableSideEffects() && next != NULL) {
687 DCHECK(next->IsSimulate());
688 previous = next;
689 next = previous->next_;
690 }
691
692 previous_ = previous;
693 next_ = next;
694 SetBlock(block);
695 previous->next_ = this;
696 if (next != NULL) next->previous_ = this;
697 if (block->last() == previous) {
698 block->set_last(this);
699 }
700 if (!has_position() && previous->has_position()) {
701 set_position(previous->position());
702 }
703}
704
705
706bool HInstruction::Dominates(HInstruction* other) {
707 if (block() != other->block()) {
708 return block()->Dominates(other->block());
709 }
710 // Both instructions are in the same basic block. This instruction
711 // should precede the other one in order to dominate it.
712 for (HInstruction* instr = next(); instr != NULL; instr = instr->next()) {
713 if (instr == other) {
714 return true;
715 }
716 }
717 return false;
718}
719
720
721#ifdef DEBUG
722void HInstruction::Verify() {
723 // Verify that input operands are defined before use.
724 HBasicBlock* cur_block = block();
725 for (int i = 0; i < OperandCount(); ++i) {
726 HValue* other_operand = OperandAt(i);
727 if (other_operand == NULL) continue;
728 HBasicBlock* other_block = other_operand->block();
729 if (cur_block == other_block) {
730 if (!other_operand->IsPhi()) {
731 HInstruction* cur = this->previous();
732 while (cur != NULL) {
733 if (cur == other_operand) break;
734 cur = cur->previous();
735 }
736 // Must reach other operand in the same block!
737 DCHECK(cur == other_operand);
738 }
739 } else {
740 // If the following assert fires, you may have forgotten an
741 // AddInstruction.
742 DCHECK(other_block->Dominates(cur_block));
743 }
744 }
745
746 // Verify that instructions that may have side-effects are followed
747 // by a simulate instruction.
748 if (HasObservableSideEffects() && !IsOsrEntry()) {
749 DCHECK(next()->IsSimulate());
750 }
751
752 // Verify that instructions that can be eliminated by GVN have overridden
753 // HValue::DataEquals. The default implementation is UNREACHABLE. We
754 // don't actually care whether DataEquals returns true or false here.
755 if (CheckFlag(kUseGVN)) DataEquals(this);
756
757 // Verify that all uses are in the graph.
758 for (HUseIterator use = uses(); !use.Done(); use.Advance()) {
759 if (use.value()->IsInstruction()) {
760 DCHECK(HInstruction::cast(use.value())->IsLinked());
761 }
762 }
763}
764#endif
765
766
767bool HInstruction::CanDeoptimize() {
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000768 switch (opcode()) {
769 case HValue::kAbnormalExit:
770 case HValue::kAccessArgumentsAt:
771 case HValue::kAllocate:
772 case HValue::kArgumentsElements:
773 case HValue::kArgumentsLength:
774 case HValue::kArgumentsObject:
775 case HValue::kBlockEntry:
776 case HValue::kBoundsCheckBaseIndexInformation:
777 case HValue::kCallFunction:
778 case HValue::kCallNewArray:
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000779 case HValue::kCapturedObject:
780 case HValue::kClassOfTestAndBranch:
781 case HValue::kCompareGeneric:
782 case HValue::kCompareHoleAndBranch:
783 case HValue::kCompareMap:
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000784 case HValue::kCompareNumericAndBranch:
785 case HValue::kCompareObjectEqAndBranch:
786 case HValue::kConstant:
787 case HValue::kConstructDouble:
788 case HValue::kContext:
789 case HValue::kDebugBreak:
790 case HValue::kDeclareGlobals:
791 case HValue::kDoubleBits:
792 case HValue::kDummyUse:
793 case HValue::kEnterInlined:
794 case HValue::kEnvironmentMarker:
795 case HValue::kForceRepresentation:
796 case HValue::kGetCachedArrayIndex:
797 case HValue::kGoto:
798 case HValue::kHasCachedArrayIndexAndBranch:
799 case HValue::kHasInstanceTypeAndBranch:
800 case HValue::kInnerAllocatedObject:
801 case HValue::kInstanceOf:
802 case HValue::kIsSmiAndBranch:
803 case HValue::kIsStringAndBranch:
804 case HValue::kIsUndetectableAndBranch:
805 case HValue::kLeaveInlined:
806 case HValue::kLoadFieldByIndex:
807 case HValue::kLoadGlobalGeneric:
808 case HValue::kLoadNamedField:
809 case HValue::kLoadNamedGeneric:
810 case HValue::kLoadRoot:
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000811 case HValue::kMathMinMax:
812 case HValue::kParameter:
813 case HValue::kPhi:
814 case HValue::kPushArguments:
815 case HValue::kReturn:
816 case HValue::kSeqStringGetChar:
817 case HValue::kStoreCodeEntry:
818 case HValue::kStoreFrameContext:
819 case HValue::kStoreKeyed:
820 case HValue::kStoreNamedField:
821 case HValue::kStoreNamedGeneric:
822 case HValue::kStringCharCodeAt:
823 case HValue::kStringCharFromCode:
824 case HValue::kThisFunction:
825 case HValue::kTypeofIsAndBranch:
826 case HValue::kUnknownOSRValue:
827 case HValue::kUseConst:
828 return false;
829
830 case HValue::kAdd:
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000831 case HValue::kApplyArguments:
832 case HValue::kBitwise:
833 case HValue::kBoundsCheck:
834 case HValue::kBranch:
835 case HValue::kCallJSFunction:
836 case HValue::kCallRuntime:
837 case HValue::kCallWithDescriptor:
838 case HValue::kChange:
839 case HValue::kCheckArrayBufferNotNeutered:
840 case HValue::kCheckHeapObject:
841 case HValue::kCheckInstanceType:
842 case HValue::kCheckMapValue:
843 case HValue::kCheckMaps:
844 case HValue::kCheckSmi:
845 case HValue::kCheckValue:
846 case HValue::kClampToUint8:
847 case HValue::kDeoptimize:
848 case HValue::kDiv:
849 case HValue::kForInCacheArray:
850 case HValue::kForInPrepareMap:
851 case HValue::kHasInPrototypeChainAndBranch:
852 case HValue::kInvokeFunction:
853 case HValue::kLoadContextSlot:
854 case HValue::kLoadFunctionPrototype:
855 case HValue::kLoadKeyed:
856 case HValue::kLoadKeyedGeneric:
857 case HValue::kMathFloorOfDiv:
858 case HValue::kMaybeGrowElements:
859 case HValue::kMod:
860 case HValue::kMul:
861 case HValue::kOsrEntry:
862 case HValue::kPower:
863 case HValue::kPrologue:
864 case HValue::kRor:
865 case HValue::kSar:
866 case HValue::kSeqStringSetChar:
867 case HValue::kShl:
868 case HValue::kShr:
869 case HValue::kSimulate:
870 case HValue::kStackCheck:
871 case HValue::kStoreContextSlot:
872 case HValue::kStoreKeyedGeneric:
873 case HValue::kStringAdd:
874 case HValue::kStringCompareAndBranch:
875 case HValue::kSub:
876 case HValue::kToFastProperties:
877 case HValue::kTransitionElementsKind:
878 case HValue::kTrapAllocationMemento:
879 case HValue::kTypeof:
880 case HValue::kUnaryMathOperation:
881 case HValue::kWrapReceiver:
882 return true;
883 }
884 UNREACHABLE();
885 return true;
886}
887
888
889std::ostream& operator<<(std::ostream& os, const NameOf& v) {
890 return os << v.value->representation().Mnemonic() << v.value->id();
891}
892
893std::ostream& HDummyUse::PrintDataTo(std::ostream& os) const { // NOLINT
894 return os << NameOf(value());
895}
896
897
898std::ostream& HEnvironmentMarker::PrintDataTo(
899 std::ostream& os) const { // NOLINT
900 return os << (kind() == BIND ? "bind" : "lookup") << " var[" << index()
901 << "]";
902}
903
904
905std::ostream& HUnaryCall::PrintDataTo(std::ostream& os) const { // NOLINT
906 return os << NameOf(value()) << " #" << argument_count();
907}
908
909
910std::ostream& HCallJSFunction::PrintDataTo(std::ostream& os) const { // NOLINT
911 return os << NameOf(function()) << " #" << argument_count();
912}
913
914
915HCallJSFunction* HCallJSFunction::New(Isolate* isolate, Zone* zone,
916 HValue* context, HValue* function,
917 int argument_count) {
918 bool has_stack_check = false;
919 if (function->IsConstant()) {
920 HConstant* fun_const = HConstant::cast(function);
921 Handle<JSFunction> jsfun =
922 Handle<JSFunction>::cast(fun_const->handle(isolate));
923 has_stack_check = !jsfun.is_null() &&
924 (jsfun->code()->kind() == Code::FUNCTION ||
925 jsfun->code()->kind() == Code::OPTIMIZED_FUNCTION);
926 }
927
928 return new (zone) HCallJSFunction(function, argument_count, has_stack_check);
929}
930
931
932std::ostream& HBinaryCall::PrintDataTo(std::ostream& os) const { // NOLINT
933 return os << NameOf(first()) << " " << NameOf(second()) << " #"
934 << argument_count();
935}
936
937
938std::ostream& HCallFunction::PrintDataTo(std::ostream& os) const { // NOLINT
939 os << NameOf(context()) << " " << NameOf(function());
940 if (HasVectorAndSlot()) {
941 os << " (type-feedback-vector icslot " << slot().ToInt() << ")";
942 }
943 os << " (convert mode" << convert_mode() << ")";
944 return os;
945}
946
947
948void HBoundsCheck::ApplyIndexChange() {
949 if (skip_check()) return;
950
951 DecompositionResult decomposition;
952 bool index_is_decomposable = index()->TryDecompose(&decomposition);
953 if (index_is_decomposable) {
954 DCHECK(decomposition.base() == base());
955 if (decomposition.offset() == offset() &&
956 decomposition.scale() == scale()) return;
957 } else {
958 return;
959 }
960
961 ReplaceAllUsesWith(index());
962
963 HValue* current_index = decomposition.base();
964 int actual_offset = decomposition.offset() + offset();
965 int actual_scale = decomposition.scale() + scale();
966
967 HGraph* graph = block()->graph();
968 Isolate* isolate = graph->isolate();
969 Zone* zone = graph->zone();
970 HValue* context = graph->GetInvalidContext();
971 if (actual_offset != 0) {
972 HConstant* add_offset =
973 HConstant::New(isolate, zone, context, actual_offset);
974 add_offset->InsertBefore(this);
975 HInstruction* add =
976 HAdd::New(isolate, zone, context, current_index, add_offset);
977 add->InsertBefore(this);
978 add->AssumeRepresentation(index()->representation());
979 add->ClearFlag(kCanOverflow);
980 current_index = add;
981 }
982
983 if (actual_scale != 0) {
984 HConstant* sar_scale = HConstant::New(isolate, zone, context, actual_scale);
985 sar_scale->InsertBefore(this);
986 HInstruction* sar =
987 HSar::New(isolate, zone, context, current_index, sar_scale);
988 sar->InsertBefore(this);
989 sar->AssumeRepresentation(index()->representation());
990 current_index = sar;
991 }
992
993 SetOperandAt(0, current_index);
994
995 base_ = NULL;
996 offset_ = 0;
997 scale_ = 0;
998}
999
1000
1001std::ostream& HBoundsCheck::PrintDataTo(std::ostream& os) const { // NOLINT
1002 os << NameOf(index()) << " " << NameOf(length());
1003 if (base() != NULL && (offset() != 0 || scale() != 0)) {
1004 os << " base: ((";
1005 if (base() != index()) {
1006 os << NameOf(index());
1007 } else {
1008 os << "index";
1009 }
1010 os << " + " << offset() << ") >> " << scale() << ")";
1011 }
1012 if (skip_check()) os << " [DISABLED]";
1013 return os;
1014}
1015
1016
1017void HBoundsCheck::InferRepresentation(HInferRepresentationPhase* h_infer) {
1018 DCHECK(CheckFlag(kFlexibleRepresentation));
1019 HValue* actual_index = index()->ActualValue();
1020 HValue* actual_length = length()->ActualValue();
1021 Representation index_rep = actual_index->representation();
1022 Representation length_rep = actual_length->representation();
1023 if (index_rep.IsTagged() && actual_index->type().IsSmi()) {
1024 index_rep = Representation::Smi();
1025 }
1026 if (length_rep.IsTagged() && actual_length->type().IsSmi()) {
1027 length_rep = Representation::Smi();
1028 }
1029 Representation r = index_rep.generalize(length_rep);
1030 if (r.is_more_general_than(Representation::Integer32())) {
1031 r = Representation::Integer32();
1032 }
1033 UpdateRepresentation(r, h_infer, "boundscheck");
1034}
1035
1036
1037Range* HBoundsCheck::InferRange(Zone* zone) {
1038 Representation r = representation();
1039 if (r.IsSmiOrInteger32() && length()->HasRange()) {
1040 int upper = length()->range()->upper() - (allow_equality() ? 0 : 1);
1041 int lower = 0;
1042
1043 Range* result = new(zone) Range(lower, upper);
1044 if (index()->HasRange()) {
1045 result->Intersect(index()->range());
1046 }
1047
1048 // In case of Smi representation, clamp result to Smi::kMaxValue.
1049 if (r.IsSmi()) result->ClampToSmi();
1050 return result;
1051 }
1052 return HValue::InferRange(zone);
1053}
1054
1055
1056std::ostream& HBoundsCheckBaseIndexInformation::PrintDataTo(
1057 std::ostream& os) const { // NOLINT
1058 // TODO(svenpanne) This 2nd base_index() looks wrong...
1059 return os << "base: " << NameOf(base_index())
1060 << ", check: " << NameOf(base_index());
1061}
1062
1063
1064std::ostream& HCallWithDescriptor::PrintDataTo(
1065 std::ostream& os) const { // NOLINT
1066 for (int i = 0; i < OperandCount(); i++) {
1067 os << NameOf(OperandAt(i)) << " ";
1068 }
1069 return os << "#" << argument_count();
1070}
1071
1072
1073std::ostream& HCallNewArray::PrintDataTo(std::ostream& os) const { // NOLINT
1074 os << ElementsKindToString(elements_kind()) << " ";
1075 return HBinaryCall::PrintDataTo(os);
1076}
1077
1078
1079std::ostream& HCallRuntime::PrintDataTo(std::ostream& os) const { // NOLINT
1080 os << function()->name << " ";
1081 if (save_doubles() == kSaveFPRegs) os << "[save doubles] ";
1082 return os << "#" << argument_count();
1083}
1084
1085
1086std::ostream& HClassOfTestAndBranch::PrintDataTo(
1087 std::ostream& os) const { // NOLINT
1088 return os << "class_of_test(" << NameOf(value()) << ", \""
1089 << class_name()->ToCString().get() << "\")";
1090}
1091
1092
1093std::ostream& HWrapReceiver::PrintDataTo(std::ostream& os) const { // NOLINT
1094 return os << NameOf(receiver()) << " " << NameOf(function());
1095}
1096
1097
1098std::ostream& HAccessArgumentsAt::PrintDataTo(
1099 std::ostream& os) const { // NOLINT
1100 return os << NameOf(arguments()) << "[" << NameOf(index()) << "], length "
1101 << NameOf(length());
1102}
1103
1104
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001105std::ostream& HControlInstruction::PrintDataTo(
1106 std::ostream& os) const { // NOLINT
1107 os << " goto (";
1108 bool first_block = true;
1109 for (HSuccessorIterator it(this); !it.Done(); it.Advance()) {
1110 if (!first_block) os << ", ";
1111 os << *it.Current();
1112 first_block = false;
1113 }
1114 return os << ")";
1115}
1116
1117
1118std::ostream& HUnaryControlInstruction::PrintDataTo(
1119 std::ostream& os) const { // NOLINT
1120 os << NameOf(value());
1121 return HControlInstruction::PrintDataTo(os);
1122}
1123
1124
1125std::ostream& HReturn::PrintDataTo(std::ostream& os) const { // NOLINT
1126 return os << NameOf(value()) << " (pop " << NameOf(parameter_count())
1127 << " values)";
1128}
1129
1130
1131Representation HBranch::observed_input_representation(int index) {
1132 if (expected_input_types_.Contains(ToBooleanStub::NULL_TYPE) ||
1133 expected_input_types_.Contains(ToBooleanStub::SPEC_OBJECT) ||
1134 expected_input_types_.Contains(ToBooleanStub::STRING) ||
1135 expected_input_types_.Contains(ToBooleanStub::SYMBOL) ||
1136 expected_input_types_.Contains(ToBooleanStub::SIMD_VALUE)) {
1137 return Representation::Tagged();
1138 }
1139 if (expected_input_types_.Contains(ToBooleanStub::UNDEFINED)) {
1140 if (expected_input_types_.Contains(ToBooleanStub::HEAP_NUMBER)) {
1141 return Representation::Double();
1142 }
1143 return Representation::Tagged();
1144 }
1145 if (expected_input_types_.Contains(ToBooleanStub::HEAP_NUMBER)) {
1146 return Representation::Double();
1147 }
1148 if (expected_input_types_.Contains(ToBooleanStub::SMI)) {
1149 return Representation::Smi();
1150 }
1151 return Representation::None();
1152}
1153
1154
1155bool HBranch::KnownSuccessorBlock(HBasicBlock** block) {
1156 HValue* value = this->value();
1157 if (value->EmitAtUses()) {
1158 DCHECK(value->IsConstant());
1159 DCHECK(!value->representation().IsDouble());
1160 *block = HConstant::cast(value)->BooleanValue()
1161 ? FirstSuccessor()
1162 : SecondSuccessor();
1163 return true;
1164 }
1165 *block = NULL;
1166 return false;
1167}
1168
1169
1170std::ostream& HBranch::PrintDataTo(std::ostream& os) const { // NOLINT
1171 return HUnaryControlInstruction::PrintDataTo(os) << " "
1172 << expected_input_types();
1173}
1174
1175
1176std::ostream& HCompareMap::PrintDataTo(std::ostream& os) const { // NOLINT
1177 os << NameOf(value()) << " (" << *map().handle() << ")";
1178 HControlInstruction::PrintDataTo(os);
1179 if (known_successor_index() == 0) {
1180 os << " [true]";
1181 } else if (known_successor_index() == 1) {
1182 os << " [false]";
1183 }
1184 return os;
1185}
1186
1187
1188const char* HUnaryMathOperation::OpName() const {
1189 switch (op()) {
1190 case kMathFloor:
1191 return "floor";
1192 case kMathFround:
1193 return "fround";
1194 case kMathRound:
1195 return "round";
1196 case kMathAbs:
1197 return "abs";
1198 case kMathLog:
1199 return "log";
1200 case kMathExp:
1201 return "exp";
1202 case kMathSqrt:
1203 return "sqrt";
1204 case kMathPowHalf:
1205 return "pow-half";
1206 case kMathClz32:
1207 return "clz32";
1208 default:
1209 UNREACHABLE();
1210 return NULL;
1211 }
1212}
1213
1214
1215Range* HUnaryMathOperation::InferRange(Zone* zone) {
1216 Representation r = representation();
1217 if (op() == kMathClz32) return new(zone) Range(0, 32);
1218 if (r.IsSmiOrInteger32() && value()->HasRange()) {
1219 if (op() == kMathAbs) {
1220 int upper = value()->range()->upper();
1221 int lower = value()->range()->lower();
1222 bool spans_zero = value()->range()->CanBeZero();
1223 // Math.abs(kMinInt) overflows its representation, on which the
1224 // instruction deopts. Hence clamp it to kMaxInt.
1225 int abs_upper = upper == kMinInt ? kMaxInt : abs(upper);
1226 int abs_lower = lower == kMinInt ? kMaxInt : abs(lower);
1227 Range* result =
1228 new(zone) Range(spans_zero ? 0 : Min(abs_lower, abs_upper),
1229 Max(abs_lower, abs_upper));
1230 // In case of Smi representation, clamp Math.abs(Smi::kMinValue) to
1231 // Smi::kMaxValue.
1232 if (r.IsSmi()) result->ClampToSmi();
1233 return result;
1234 }
1235 }
1236 return HValue::InferRange(zone);
1237}
1238
1239
1240std::ostream& HUnaryMathOperation::PrintDataTo(
1241 std::ostream& os) const { // NOLINT
1242 return os << OpName() << " " << NameOf(value());
1243}
1244
1245
1246std::ostream& HUnaryOperation::PrintDataTo(std::ostream& os) const { // NOLINT
1247 return os << NameOf(value());
1248}
1249
1250
1251std::ostream& HHasInstanceTypeAndBranch::PrintDataTo(
1252 std::ostream& os) const { // NOLINT
1253 os << NameOf(value());
1254 switch (from_) {
1255 case FIRST_JS_RECEIVER_TYPE:
1256 if (to_ == LAST_TYPE) os << " spec_object";
1257 break;
1258 case JS_REGEXP_TYPE:
1259 if (to_ == JS_REGEXP_TYPE) os << " reg_exp";
1260 break;
1261 case JS_ARRAY_TYPE:
1262 if (to_ == JS_ARRAY_TYPE) os << " array";
1263 break;
1264 case JS_FUNCTION_TYPE:
1265 if (to_ == JS_FUNCTION_TYPE) os << " function";
1266 break;
1267 default:
1268 break;
1269 }
1270 return os;
1271}
1272
1273
1274std::ostream& HTypeofIsAndBranch::PrintDataTo(
1275 std::ostream& os) const { // NOLINT
1276 os << NameOf(value()) << " == " << type_literal()->ToCString().get();
1277 return HControlInstruction::PrintDataTo(os);
1278}
1279
1280
1281namespace {
1282
1283String* TypeOfString(HConstant* constant, Isolate* isolate) {
1284 Heap* heap = isolate->heap();
1285 if (constant->HasNumberValue()) return heap->number_string();
1286 if (constant->IsUndetectable()) return heap->undefined_string();
1287 if (constant->HasStringValue()) return heap->string_string();
1288 switch (constant->GetInstanceType()) {
1289 case ODDBALL_TYPE: {
1290 Unique<Object> unique = constant->GetUnique();
1291 if (unique.IsKnownGlobal(heap->true_value()) ||
1292 unique.IsKnownGlobal(heap->false_value())) {
1293 return heap->boolean_string();
1294 }
1295 if (unique.IsKnownGlobal(heap->null_value())) {
1296 return heap->object_string();
1297 }
1298 DCHECK(unique.IsKnownGlobal(heap->undefined_value()));
1299 return heap->undefined_string();
1300 }
1301 case SYMBOL_TYPE:
1302 return heap->symbol_string();
1303 case SIMD128_VALUE_TYPE: {
1304 Unique<Map> map = constant->ObjectMap();
1305#define SIMD128_TYPE(TYPE, Type, type, lane_count, lane_type) \
1306 if (map.IsKnownGlobal(heap->type##_map())) { \
1307 return heap->type##_string(); \
1308 }
1309 SIMD128_TYPES(SIMD128_TYPE)
1310#undef SIMD128_TYPE
1311 UNREACHABLE();
1312 return nullptr;
1313 }
1314 default:
1315 if (constant->IsCallable()) return heap->function_string();
1316 return heap->object_string();
1317 }
1318}
1319
1320} // namespace
1321
1322
1323bool HTypeofIsAndBranch::KnownSuccessorBlock(HBasicBlock** block) {
1324 if (FLAG_fold_constants && value()->IsConstant()) {
1325 HConstant* constant = HConstant::cast(value());
1326 String* type_string = TypeOfString(constant, isolate());
1327 bool same_type = type_literal_.IsKnownGlobal(type_string);
1328 *block = same_type ? FirstSuccessor() : SecondSuccessor();
1329 return true;
1330 } else if (value()->representation().IsSpecialization()) {
1331 bool number_type =
1332 type_literal_.IsKnownGlobal(isolate()->heap()->number_string());
1333 *block = number_type ? FirstSuccessor() : SecondSuccessor();
1334 return true;
1335 }
1336 *block = NULL;
1337 return false;
1338}
1339
1340
1341std::ostream& HCheckMapValue::PrintDataTo(std::ostream& os) const { // NOLINT
1342 return os << NameOf(value()) << " " << NameOf(map());
1343}
1344
1345
1346HValue* HCheckMapValue::Canonicalize() {
1347 if (map()->IsConstant()) {
1348 HConstant* c_map = HConstant::cast(map());
1349 return HCheckMaps::CreateAndInsertAfter(
1350 block()->graph()->zone(), value(), c_map->MapValue(),
1351 c_map->HasStableMapValue(), this);
1352 }
1353 return this;
1354}
1355
1356
1357std::ostream& HForInPrepareMap::PrintDataTo(std::ostream& os) const { // NOLINT
1358 return os << NameOf(enumerable());
1359}
1360
1361
1362std::ostream& HForInCacheArray::PrintDataTo(std::ostream& os) const { // NOLINT
1363 return os << NameOf(enumerable()) << " " << NameOf(map()) << "[" << idx_
1364 << "]";
1365}
1366
1367
1368std::ostream& HLoadFieldByIndex::PrintDataTo(
1369 std::ostream& os) const { // NOLINT
1370 return os << NameOf(object()) << " " << NameOf(index());
1371}
1372
1373
1374static bool MatchLeftIsOnes(HValue* l, HValue* r, HValue** negated) {
1375 if (!l->EqualsInteger32Constant(~0)) return false;
1376 *negated = r;
1377 return true;
1378}
1379
1380
1381static bool MatchNegationViaXor(HValue* instr, HValue** negated) {
1382 if (!instr->IsBitwise()) return false;
1383 HBitwise* b = HBitwise::cast(instr);
1384 return (b->op() == Token::BIT_XOR) &&
1385 (MatchLeftIsOnes(b->left(), b->right(), negated) ||
1386 MatchLeftIsOnes(b->right(), b->left(), negated));
1387}
1388
1389
1390static bool MatchDoubleNegation(HValue* instr, HValue** arg) {
1391 HValue* negated;
1392 return MatchNegationViaXor(instr, &negated) &&
1393 MatchNegationViaXor(negated, arg);
1394}
1395
1396
1397HValue* HBitwise::Canonicalize() {
1398 if (!representation().IsSmiOrInteger32()) return this;
1399 // If x is an int32, then x & -1 == x, x | 0 == x and x ^ 0 == x.
1400 int32_t nop_constant = (op() == Token::BIT_AND) ? -1 : 0;
1401 if (left()->EqualsInteger32Constant(nop_constant) &&
1402 !right()->CheckFlag(kUint32)) {
1403 return right();
1404 }
1405 if (right()->EqualsInteger32Constant(nop_constant) &&
1406 !left()->CheckFlag(kUint32)) {
1407 return left();
1408 }
1409 // Optimize double negation, a common pattern used for ToInt32(x).
1410 HValue* arg;
1411 if (MatchDoubleNegation(this, &arg) && !arg->CheckFlag(kUint32)) {
1412 return arg;
1413 }
1414 return this;
1415}
1416
1417
1418// static
1419HInstruction* HAdd::New(Isolate* isolate, Zone* zone, HValue* context,
Ben Murdoch097c5b22016-05-18 11:27:45 +01001420 HValue* left, HValue* right,
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001421 ExternalAddType external_add_type) {
1422 // For everything else, you should use the other factory method without
1423 // ExternalAddType.
1424 DCHECK_EQ(external_add_type, AddOfExternalAndTagged);
Ben Murdoch097c5b22016-05-18 11:27:45 +01001425 return new (zone) HAdd(context, left, right, external_add_type);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001426}
1427
1428
1429Representation HAdd::RepresentationFromInputs() {
1430 Representation left_rep = left()->representation();
1431 if (left_rep.IsExternal()) {
1432 return Representation::External();
1433 }
1434 return HArithmeticBinaryOperation::RepresentationFromInputs();
1435}
1436
1437
1438Representation HAdd::RequiredInputRepresentation(int index) {
1439 if (index == 2) {
1440 Representation left_rep = left()->representation();
1441 if (left_rep.IsExternal()) {
1442 if (external_add_type_ == AddOfExternalAndTagged) {
1443 return Representation::Tagged();
1444 } else {
1445 return Representation::Integer32();
1446 }
1447 }
1448 }
1449 return HArithmeticBinaryOperation::RequiredInputRepresentation(index);
1450}
1451
1452
1453static bool IsIdentityOperation(HValue* arg1, HValue* arg2, int32_t identity) {
1454 return arg1->representation().IsSpecialization() &&
1455 arg2->EqualsInteger32Constant(identity);
1456}
1457
1458
1459HValue* HAdd::Canonicalize() {
1460 // Adding 0 is an identity operation except in case of -0: -0 + 0 = +0
1461 if (IsIdentityOperation(left(), right(), 0) &&
1462 !left()->representation().IsDouble()) { // Left could be -0.
1463 return left();
1464 }
1465 if (IsIdentityOperation(right(), left(), 0) &&
1466 !left()->representation().IsDouble()) { // Right could be -0.
1467 return right();
1468 }
1469 return this;
1470}
1471
1472
1473HValue* HSub::Canonicalize() {
1474 if (IsIdentityOperation(left(), right(), 0)) return left();
1475 return this;
1476}
1477
1478
1479HValue* HMul::Canonicalize() {
1480 if (IsIdentityOperation(left(), right(), 1)) return left();
1481 if (IsIdentityOperation(right(), left(), 1)) return right();
1482 return this;
1483}
1484
1485
1486bool HMul::MulMinusOne() {
1487 if (left()->EqualsInteger32Constant(-1) ||
1488 right()->EqualsInteger32Constant(-1)) {
1489 return true;
1490 }
1491
1492 return false;
1493}
1494
1495
1496HValue* HMod::Canonicalize() {
1497 return this;
1498}
1499
1500
1501HValue* HDiv::Canonicalize() {
1502 if (IsIdentityOperation(left(), right(), 1)) return left();
1503 return this;
1504}
1505
1506
1507HValue* HChange::Canonicalize() {
1508 return (from().Equals(to())) ? value() : this;
1509}
1510
1511
1512HValue* HWrapReceiver::Canonicalize() {
1513 if (HasNoUses()) return NULL;
1514 if (receiver()->type().IsJSReceiver()) {
1515 return receiver();
1516 }
1517 return this;
1518}
1519
1520
1521std::ostream& HTypeof::PrintDataTo(std::ostream& os) const { // NOLINT
1522 return os << NameOf(value());
1523}
1524
1525
1526HInstruction* HForceRepresentation::New(Isolate* isolate, Zone* zone,
1527 HValue* context, HValue* value,
1528 Representation representation) {
1529 if (FLAG_fold_constants && value->IsConstant()) {
1530 HConstant* c = HConstant::cast(value);
1531 c = c->CopyToRepresentation(representation, zone);
1532 if (c != NULL) return c;
1533 }
1534 return new(zone) HForceRepresentation(value, representation);
1535}
1536
1537
1538std::ostream& HForceRepresentation::PrintDataTo(
1539 std::ostream& os) const { // NOLINT
1540 return os << representation().Mnemonic() << " " << NameOf(value());
1541}
1542
1543
1544std::ostream& HChange::PrintDataTo(std::ostream& os) const { // NOLINT
1545 HUnaryOperation::PrintDataTo(os);
1546 os << " " << from().Mnemonic() << " to " << to().Mnemonic();
1547
1548 if (CanTruncateToSmi()) os << " truncating-smi";
1549 if (CanTruncateToInt32()) os << " truncating-int32";
1550 if (CheckFlag(kBailoutOnMinusZero)) os << " -0?";
1551 if (CheckFlag(kAllowUndefinedAsNaN)) os << " allow-undefined-as-nan";
1552 return os;
1553}
1554
1555
1556HValue* HUnaryMathOperation::Canonicalize() {
1557 if (op() == kMathRound || op() == kMathFloor) {
1558 HValue* val = value();
1559 if (val->IsChange()) val = HChange::cast(val)->value();
1560 if (val->representation().IsSmiOrInteger32()) {
1561 if (val->representation().Equals(representation())) return val;
1562 return Prepend(new(block()->zone()) HChange(
1563 val, representation(), false, false));
1564 }
1565 }
1566 if (op() == kMathFloor && value()->IsDiv() && value()->HasOneUse()) {
1567 HDiv* hdiv = HDiv::cast(value());
1568
1569 HValue* left = hdiv->left();
1570 if (left->representation().IsInteger32() && !left->CheckFlag(kUint32)) {
1571 // A value with an integer representation does not need to be transformed.
1572 } else if (left->IsChange() && HChange::cast(left)->from().IsInteger32() &&
1573 !HChange::cast(left)->value()->CheckFlag(kUint32)) {
1574 // A change from an integer32 can be replaced by the integer32 value.
1575 left = HChange::cast(left)->value();
1576 } else if (hdiv->observed_input_representation(1).IsSmiOrInteger32()) {
1577 left = Prepend(new(block()->zone()) HChange(
1578 left, Representation::Integer32(), false, false));
1579 } else {
1580 return this;
1581 }
1582
1583 HValue* right = hdiv->right();
1584 if (right->IsInteger32Constant()) {
1585 right = Prepend(HConstant::cast(right)->CopyToRepresentation(
1586 Representation::Integer32(), right->block()->zone()));
1587 } else if (right->representation().IsInteger32() &&
1588 !right->CheckFlag(kUint32)) {
1589 // A value with an integer representation does not need to be transformed.
1590 } else if (right->IsChange() &&
1591 HChange::cast(right)->from().IsInteger32() &&
1592 !HChange::cast(right)->value()->CheckFlag(kUint32)) {
1593 // A change from an integer32 can be replaced by the integer32 value.
1594 right = HChange::cast(right)->value();
1595 } else if (hdiv->observed_input_representation(2).IsSmiOrInteger32()) {
1596 right = Prepend(new(block()->zone()) HChange(
1597 right, Representation::Integer32(), false, false));
1598 } else {
1599 return this;
1600 }
1601
1602 return Prepend(HMathFloorOfDiv::New(
1603 block()->graph()->isolate(), block()->zone(), context(), left, right));
1604 }
1605 return this;
1606}
1607
1608
1609HValue* HCheckInstanceType::Canonicalize() {
1610 if ((check_ == IS_JS_RECEIVER && value()->type().IsJSReceiver()) ||
1611 (check_ == IS_JS_ARRAY && value()->type().IsJSArray()) ||
1612 (check_ == IS_STRING && value()->type().IsString())) {
1613 return value();
1614 }
1615
1616 if (check_ == IS_INTERNALIZED_STRING && value()->IsConstant()) {
1617 if (HConstant::cast(value())->HasInternalizedStringValue()) {
1618 return value();
1619 }
1620 }
1621 return this;
1622}
1623
1624
1625void HCheckInstanceType::GetCheckInterval(InstanceType* first,
1626 InstanceType* last) {
1627 DCHECK(is_interval_check());
1628 switch (check_) {
1629 case IS_JS_RECEIVER:
1630 *first = FIRST_JS_RECEIVER_TYPE;
1631 *last = LAST_JS_RECEIVER_TYPE;
1632 return;
1633 case IS_JS_ARRAY:
1634 *first = *last = JS_ARRAY_TYPE;
1635 return;
1636 case IS_JS_DATE:
1637 *first = *last = JS_DATE_TYPE;
1638 return;
1639 default:
1640 UNREACHABLE();
1641 }
1642}
1643
1644
1645void HCheckInstanceType::GetCheckMaskAndTag(uint8_t* mask, uint8_t* tag) {
1646 DCHECK(!is_interval_check());
1647 switch (check_) {
1648 case IS_STRING:
1649 *mask = kIsNotStringMask;
1650 *tag = kStringTag;
1651 return;
1652 case IS_INTERNALIZED_STRING:
1653 *mask = kIsNotStringMask | kIsNotInternalizedMask;
1654 *tag = kInternalizedTag;
1655 return;
1656 default:
1657 UNREACHABLE();
1658 }
1659}
1660
1661
1662std::ostream& HCheckMaps::PrintDataTo(std::ostream& os) const { // NOLINT
1663 os << NameOf(value()) << " [" << *maps()->at(0).handle();
1664 for (int i = 1; i < maps()->size(); ++i) {
1665 os << "," << *maps()->at(i).handle();
1666 }
1667 os << "]";
1668 if (IsStabilityCheck()) os << "(stability-check)";
1669 return os;
1670}
1671
1672
1673HValue* HCheckMaps::Canonicalize() {
1674 if (!IsStabilityCheck() && maps_are_stable() && value()->IsConstant()) {
1675 HConstant* c_value = HConstant::cast(value());
1676 if (c_value->HasObjectMap()) {
1677 for (int i = 0; i < maps()->size(); ++i) {
1678 if (c_value->ObjectMap() == maps()->at(i)) {
1679 if (maps()->size() > 1) {
1680 set_maps(new(block()->graph()->zone()) UniqueSet<Map>(
1681 maps()->at(i), block()->graph()->zone()));
1682 }
1683 MarkAsStabilityCheck();
1684 break;
1685 }
1686 }
1687 }
1688 }
1689 return this;
1690}
1691
1692
1693std::ostream& HCheckValue::PrintDataTo(std::ostream& os) const { // NOLINT
1694 return os << NameOf(value()) << " " << Brief(*object().handle());
1695}
1696
1697
1698HValue* HCheckValue::Canonicalize() {
1699 return (value()->IsConstant() &&
1700 HConstant::cast(value())->EqualsUnique(object_)) ? NULL : this;
1701}
1702
1703
1704const char* HCheckInstanceType::GetCheckName() const {
1705 switch (check_) {
1706 case IS_JS_RECEIVER: return "object";
1707 case IS_JS_ARRAY: return "array";
1708 case IS_JS_DATE:
1709 return "date";
1710 case IS_STRING: return "string";
1711 case IS_INTERNALIZED_STRING: return "internalized_string";
1712 }
1713 UNREACHABLE();
1714 return "";
1715}
1716
1717
1718std::ostream& HCheckInstanceType::PrintDataTo(
1719 std::ostream& os) const { // NOLINT
1720 os << GetCheckName() << " ";
1721 return HUnaryOperation::PrintDataTo(os);
1722}
1723
1724
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001725std::ostream& HUnknownOSRValue::PrintDataTo(std::ostream& os) const { // NOLINT
1726 const char* type = "expression";
1727 if (environment_->is_local_index(index_)) type = "local";
1728 if (environment_->is_special_index(index_)) type = "special";
1729 if (environment_->is_parameter_index(index_)) type = "parameter";
1730 return os << type << " @ " << index_;
1731}
1732
1733
1734std::ostream& HInstanceOf::PrintDataTo(std::ostream& os) const { // NOLINT
1735 return os << NameOf(left()) << " " << NameOf(right()) << " "
1736 << NameOf(context());
1737}
1738
1739
1740Range* HValue::InferRange(Zone* zone) {
1741 Range* result;
1742 if (representation().IsSmi() || type().IsSmi()) {
1743 result = new(zone) Range(Smi::kMinValue, Smi::kMaxValue);
1744 result->set_can_be_minus_zero(false);
1745 } else {
1746 result = new(zone) Range();
1747 result->set_can_be_minus_zero(!CheckFlag(kAllUsesTruncatingToInt32));
1748 // TODO(jkummerow): The range cannot be minus zero when the upper type
1749 // bound is Integer32.
1750 }
1751 return result;
1752}
1753
1754
1755Range* HChange::InferRange(Zone* zone) {
1756 Range* input_range = value()->range();
1757 if (from().IsInteger32() && !value()->CheckFlag(HInstruction::kUint32) &&
1758 (to().IsSmi() ||
1759 (to().IsTagged() &&
1760 input_range != NULL &&
1761 input_range->IsInSmiRange()))) {
1762 set_type(HType::Smi());
1763 ClearChangesFlag(kNewSpacePromotion);
1764 }
1765 if (to().IsSmiOrTagged() &&
1766 input_range != NULL &&
1767 input_range->IsInSmiRange() &&
1768 (!SmiValuesAre32Bits() ||
1769 !value()->CheckFlag(HValue::kUint32) ||
1770 input_range->upper() != kMaxInt)) {
1771 // The Range class can't express upper bounds in the (kMaxInt, kMaxUint32]
1772 // interval, so we treat kMaxInt as a sentinel for this entire interval.
1773 ClearFlag(kCanOverflow);
1774 }
1775 Range* result = (input_range != NULL)
1776 ? input_range->Copy(zone)
1777 : HValue::InferRange(zone);
1778 result->set_can_be_minus_zero(!to().IsSmiOrInteger32() ||
1779 !(CheckFlag(kAllUsesTruncatingToInt32) ||
1780 CheckFlag(kAllUsesTruncatingToSmi)));
1781 if (to().IsSmi()) result->ClampToSmi();
1782 return result;
1783}
1784
1785
1786Range* HConstant::InferRange(Zone* zone) {
1787 if (HasInteger32Value()) {
1788 Range* result = new(zone) Range(int32_value_, int32_value_);
1789 result->set_can_be_minus_zero(false);
1790 return result;
1791 }
1792 return HValue::InferRange(zone);
1793}
1794
1795
1796SourcePosition HPhi::position() const { return block()->first()->position(); }
1797
1798
1799Range* HPhi::InferRange(Zone* zone) {
1800 Representation r = representation();
1801 if (r.IsSmiOrInteger32()) {
1802 if (block()->IsLoopHeader()) {
1803 Range* range = r.IsSmi()
1804 ? new(zone) Range(Smi::kMinValue, Smi::kMaxValue)
1805 : new(zone) Range(kMinInt, kMaxInt);
1806 return range;
1807 } else {
1808 Range* range = OperandAt(0)->range()->Copy(zone);
1809 for (int i = 1; i < OperandCount(); ++i) {
1810 range->Union(OperandAt(i)->range());
1811 }
1812 return range;
1813 }
1814 } else {
1815 return HValue::InferRange(zone);
1816 }
1817}
1818
1819
1820Range* HAdd::InferRange(Zone* zone) {
1821 Representation r = representation();
1822 if (r.IsSmiOrInteger32()) {
1823 Range* a = left()->range();
1824 Range* b = right()->range();
1825 Range* res = a->Copy(zone);
1826 if (!res->AddAndCheckOverflow(r, b) ||
1827 (r.IsInteger32() && CheckFlag(kAllUsesTruncatingToInt32)) ||
1828 (r.IsSmi() && CheckFlag(kAllUsesTruncatingToSmi))) {
1829 ClearFlag(kCanOverflow);
1830 }
1831 res->set_can_be_minus_zero(!CheckFlag(kAllUsesTruncatingToSmi) &&
1832 !CheckFlag(kAllUsesTruncatingToInt32) &&
1833 a->CanBeMinusZero() && b->CanBeMinusZero());
1834 return res;
1835 } else {
1836 return HValue::InferRange(zone);
1837 }
1838}
1839
1840
1841Range* HSub::InferRange(Zone* zone) {
1842 Representation r = representation();
1843 if (r.IsSmiOrInteger32()) {
1844 Range* a = left()->range();
1845 Range* b = right()->range();
1846 Range* res = a->Copy(zone);
1847 if (!res->SubAndCheckOverflow(r, b) ||
1848 (r.IsInteger32() && CheckFlag(kAllUsesTruncatingToInt32)) ||
1849 (r.IsSmi() && CheckFlag(kAllUsesTruncatingToSmi))) {
1850 ClearFlag(kCanOverflow);
1851 }
1852 res->set_can_be_minus_zero(!CheckFlag(kAllUsesTruncatingToSmi) &&
1853 !CheckFlag(kAllUsesTruncatingToInt32) &&
1854 a->CanBeMinusZero() && b->CanBeZero());
1855 return res;
1856 } else {
1857 return HValue::InferRange(zone);
1858 }
1859}
1860
1861
1862Range* HMul::InferRange(Zone* zone) {
1863 Representation r = representation();
1864 if (r.IsSmiOrInteger32()) {
1865 Range* a = left()->range();
1866 Range* b = right()->range();
1867 Range* res = a->Copy(zone);
1868 if (!res->MulAndCheckOverflow(r, b) ||
1869 (((r.IsInteger32() && CheckFlag(kAllUsesTruncatingToInt32)) ||
1870 (r.IsSmi() && CheckFlag(kAllUsesTruncatingToSmi))) &&
1871 MulMinusOne())) {
1872 // Truncated int multiplication is too precise and therefore not the
1873 // same as converting to Double and back.
1874 // Handle truncated integer multiplication by -1 special.
1875 ClearFlag(kCanOverflow);
1876 }
1877 res->set_can_be_minus_zero(!CheckFlag(kAllUsesTruncatingToSmi) &&
1878 !CheckFlag(kAllUsesTruncatingToInt32) &&
1879 ((a->CanBeZero() && b->CanBeNegative()) ||
1880 (a->CanBeNegative() && b->CanBeZero())));
1881 return res;
1882 } else {
1883 return HValue::InferRange(zone);
1884 }
1885}
1886
1887
1888Range* HDiv::InferRange(Zone* zone) {
1889 if (representation().IsInteger32()) {
1890 Range* a = left()->range();
1891 Range* b = right()->range();
1892 Range* result = new(zone) Range();
1893 result->set_can_be_minus_zero(!CheckFlag(kAllUsesTruncatingToInt32) &&
1894 (a->CanBeMinusZero() ||
1895 (a->CanBeZero() && b->CanBeNegative())));
1896 if (!a->Includes(kMinInt) || !b->Includes(-1)) {
1897 ClearFlag(kCanOverflow);
1898 }
1899
1900 if (!b->CanBeZero()) {
1901 ClearFlag(kCanBeDivByZero);
1902 }
1903 return result;
1904 } else {
1905 return HValue::InferRange(zone);
1906 }
1907}
1908
1909
1910Range* HMathFloorOfDiv::InferRange(Zone* zone) {
1911 if (representation().IsInteger32()) {
1912 Range* a = left()->range();
1913 Range* b = right()->range();
1914 Range* result = new(zone) Range();
1915 result->set_can_be_minus_zero(!CheckFlag(kAllUsesTruncatingToInt32) &&
1916 (a->CanBeMinusZero() ||
1917 (a->CanBeZero() && b->CanBeNegative())));
1918 if (!a->Includes(kMinInt)) {
1919 ClearFlag(kLeftCanBeMinInt);
1920 }
1921
1922 if (!a->CanBeNegative()) {
1923 ClearFlag(HValue::kLeftCanBeNegative);
1924 }
1925
1926 if (!a->CanBePositive()) {
1927 ClearFlag(HValue::kLeftCanBePositive);
1928 }
1929
1930 if (!a->Includes(kMinInt) || !b->Includes(-1)) {
1931 ClearFlag(kCanOverflow);
1932 }
1933
1934 if (!b->CanBeZero()) {
1935 ClearFlag(kCanBeDivByZero);
1936 }
1937 return result;
1938 } else {
1939 return HValue::InferRange(zone);
1940 }
1941}
1942
1943
1944// Returns the absolute value of its argument minus one, avoiding undefined
1945// behavior at kMinInt.
1946static int32_t AbsMinus1(int32_t a) { return a < 0 ? -(a + 1) : (a - 1); }
1947
1948
1949Range* HMod::InferRange(Zone* zone) {
1950 if (representation().IsInteger32()) {
1951 Range* a = left()->range();
1952 Range* b = right()->range();
1953
1954 // The magnitude of the modulus is bounded by the right operand.
1955 int32_t positive_bound = Max(AbsMinus1(b->lower()), AbsMinus1(b->upper()));
1956
1957 // The result of the modulo operation has the sign of its left operand.
1958 bool left_can_be_negative = a->CanBeMinusZero() || a->CanBeNegative();
1959 Range* result = new(zone) Range(left_can_be_negative ? -positive_bound : 0,
1960 a->CanBePositive() ? positive_bound : 0);
1961
1962 result->set_can_be_minus_zero(!CheckFlag(kAllUsesTruncatingToInt32) &&
1963 left_can_be_negative);
1964
1965 if (!a->CanBeNegative()) {
1966 ClearFlag(HValue::kLeftCanBeNegative);
1967 }
1968
1969 if (!a->Includes(kMinInt) || !b->Includes(-1)) {
1970 ClearFlag(HValue::kCanOverflow);
1971 }
1972
1973 if (!b->CanBeZero()) {
1974 ClearFlag(HValue::kCanBeDivByZero);
1975 }
1976 return result;
1977 } else {
1978 return HValue::InferRange(zone);
1979 }
1980}
1981
1982
1983InductionVariableData* InductionVariableData::ExaminePhi(HPhi* phi) {
1984 if (phi->block()->loop_information() == NULL) return NULL;
1985 if (phi->OperandCount() != 2) return NULL;
1986 int32_t candidate_increment;
1987
1988 candidate_increment = ComputeIncrement(phi, phi->OperandAt(0));
1989 if (candidate_increment != 0) {
1990 return new(phi->block()->graph()->zone())
1991 InductionVariableData(phi, phi->OperandAt(1), candidate_increment);
1992 }
1993
1994 candidate_increment = ComputeIncrement(phi, phi->OperandAt(1));
1995 if (candidate_increment != 0) {
1996 return new(phi->block()->graph()->zone())
1997 InductionVariableData(phi, phi->OperandAt(0), candidate_increment);
1998 }
1999
2000 return NULL;
2001}
2002
2003
2004/*
2005 * This function tries to match the following patterns (and all the relevant
2006 * variants related to |, & and + being commutative):
2007 * base | constant_or_mask
2008 * base & constant_and_mask
2009 * (base + constant_offset) & constant_and_mask
2010 * (base - constant_offset) & constant_and_mask
2011 */
2012void InductionVariableData::DecomposeBitwise(
2013 HValue* value,
2014 BitwiseDecompositionResult* result) {
2015 HValue* base = IgnoreOsrValue(value);
2016 result->base = value;
2017
2018 if (!base->representation().IsInteger32()) return;
2019
2020 if (base->IsBitwise()) {
2021 bool allow_offset = false;
2022 int32_t mask = 0;
2023
2024 HBitwise* bitwise = HBitwise::cast(base);
2025 if (bitwise->right()->IsInteger32Constant()) {
2026 mask = bitwise->right()->GetInteger32Constant();
2027 base = bitwise->left();
2028 } else if (bitwise->left()->IsInteger32Constant()) {
2029 mask = bitwise->left()->GetInteger32Constant();
2030 base = bitwise->right();
2031 } else {
2032 return;
2033 }
2034 if (bitwise->op() == Token::BIT_AND) {
2035 result->and_mask = mask;
2036 allow_offset = true;
2037 } else if (bitwise->op() == Token::BIT_OR) {
2038 result->or_mask = mask;
2039 } else {
2040 return;
2041 }
2042
2043 result->context = bitwise->context();
2044
2045 if (allow_offset) {
2046 if (base->IsAdd()) {
2047 HAdd* add = HAdd::cast(base);
2048 if (add->right()->IsInteger32Constant()) {
2049 base = add->left();
2050 } else if (add->left()->IsInteger32Constant()) {
2051 base = add->right();
2052 }
2053 } else if (base->IsSub()) {
2054 HSub* sub = HSub::cast(base);
2055 if (sub->right()->IsInteger32Constant()) {
2056 base = sub->left();
2057 }
2058 }
2059 }
2060
2061 result->base = base;
2062 }
2063}
2064
2065
2066void InductionVariableData::AddCheck(HBoundsCheck* check,
2067 int32_t upper_limit) {
2068 DCHECK(limit_validity() != NULL);
2069 if (limit_validity() != check->block() &&
2070 !limit_validity()->Dominates(check->block())) return;
2071 if (!phi()->block()->current_loop()->IsNestedInThisLoop(
2072 check->block()->current_loop())) return;
2073
2074 ChecksRelatedToLength* length_checks = checks();
2075 while (length_checks != NULL) {
2076 if (length_checks->length() == check->length()) break;
2077 length_checks = length_checks->next();
2078 }
2079 if (length_checks == NULL) {
2080 length_checks = new(check->block()->zone())
2081 ChecksRelatedToLength(check->length(), checks());
2082 checks_ = length_checks;
2083 }
2084
2085 length_checks->AddCheck(check, upper_limit);
2086}
2087
2088
2089void InductionVariableData::ChecksRelatedToLength::CloseCurrentBlock() {
2090 if (checks() != NULL) {
2091 InductionVariableCheck* c = checks();
2092 HBasicBlock* current_block = c->check()->block();
2093 while (c != NULL && c->check()->block() == current_block) {
2094 c->set_upper_limit(current_upper_limit_);
2095 c = c->next();
2096 }
2097 }
2098}
2099
2100
2101void InductionVariableData::ChecksRelatedToLength::UseNewIndexInCurrentBlock(
2102 Token::Value token,
2103 int32_t mask,
2104 HValue* index_base,
2105 HValue* context) {
2106 DCHECK(first_check_in_block() != NULL);
2107 HValue* previous_index = first_check_in_block()->index();
2108 DCHECK(context != NULL);
2109
2110 Zone* zone = index_base->block()->graph()->zone();
2111 Isolate* isolate = index_base->block()->graph()->isolate();
2112 set_added_constant(HConstant::New(isolate, zone, context, mask));
2113 if (added_index() != NULL) {
2114 added_constant()->InsertBefore(added_index());
2115 } else {
2116 added_constant()->InsertBefore(first_check_in_block());
2117 }
2118
2119 if (added_index() == NULL) {
2120 first_check_in_block()->ReplaceAllUsesWith(first_check_in_block()->index());
2121 HInstruction* new_index = HBitwise::New(isolate, zone, context, token,
2122 index_base, added_constant());
2123 DCHECK(new_index->IsBitwise());
2124 new_index->ClearAllSideEffects();
2125 new_index->AssumeRepresentation(Representation::Integer32());
2126 set_added_index(HBitwise::cast(new_index));
2127 added_index()->InsertBefore(first_check_in_block());
2128 }
2129 DCHECK(added_index()->op() == token);
2130
2131 added_index()->SetOperandAt(1, index_base);
2132 added_index()->SetOperandAt(2, added_constant());
2133 first_check_in_block()->SetOperandAt(0, added_index());
2134 if (previous_index->HasNoUses()) {
2135 previous_index->DeleteAndReplaceWith(NULL);
2136 }
2137}
2138
2139void InductionVariableData::ChecksRelatedToLength::AddCheck(
2140 HBoundsCheck* check,
2141 int32_t upper_limit) {
2142 BitwiseDecompositionResult decomposition;
2143 InductionVariableData::DecomposeBitwise(check->index(), &decomposition);
2144
2145 if (first_check_in_block() == NULL ||
2146 first_check_in_block()->block() != check->block()) {
2147 CloseCurrentBlock();
2148
2149 first_check_in_block_ = check;
2150 set_added_index(NULL);
2151 set_added_constant(NULL);
2152 current_and_mask_in_block_ = decomposition.and_mask;
2153 current_or_mask_in_block_ = decomposition.or_mask;
2154 current_upper_limit_ = upper_limit;
2155
2156 InductionVariableCheck* new_check = new(check->block()->graph()->zone())
2157 InductionVariableCheck(check, checks_, upper_limit);
2158 checks_ = new_check;
2159 return;
2160 }
2161
2162 if (upper_limit > current_upper_limit()) {
2163 current_upper_limit_ = upper_limit;
2164 }
2165
2166 if (decomposition.and_mask != 0 &&
2167 current_or_mask_in_block() == 0) {
2168 if (current_and_mask_in_block() == 0 ||
2169 decomposition.and_mask > current_and_mask_in_block()) {
2170 UseNewIndexInCurrentBlock(Token::BIT_AND,
2171 decomposition.and_mask,
2172 decomposition.base,
2173 decomposition.context);
2174 current_and_mask_in_block_ = decomposition.and_mask;
2175 }
2176 check->set_skip_check();
2177 }
2178 if (current_and_mask_in_block() == 0) {
2179 if (decomposition.or_mask > current_or_mask_in_block()) {
2180 UseNewIndexInCurrentBlock(Token::BIT_OR,
2181 decomposition.or_mask,
2182 decomposition.base,
2183 decomposition.context);
2184 current_or_mask_in_block_ = decomposition.or_mask;
2185 }
2186 check->set_skip_check();
2187 }
2188
2189 if (!check->skip_check()) {
2190 InductionVariableCheck* new_check = new(check->block()->graph()->zone())
2191 InductionVariableCheck(check, checks_, upper_limit);
2192 checks_ = new_check;
2193 }
2194}
2195
2196
2197/*
2198 * This method detects if phi is an induction variable, with phi_operand as
2199 * its "incremented" value (the other operand would be the "base" value).
2200 *
2201 * It cheks is phi_operand has the form "phi + constant".
2202 * If yes, the constant is the increment that the induction variable gets at
2203 * every loop iteration.
2204 * Otherwise it returns 0.
2205 */
2206int32_t InductionVariableData::ComputeIncrement(HPhi* phi,
2207 HValue* phi_operand) {
2208 if (!phi_operand->representation().IsSmiOrInteger32()) return 0;
2209
2210 if (phi_operand->IsAdd()) {
2211 HAdd* operation = HAdd::cast(phi_operand);
2212 if (operation->left() == phi &&
2213 operation->right()->IsInteger32Constant()) {
2214 return operation->right()->GetInteger32Constant();
2215 } else if (operation->right() == phi &&
2216 operation->left()->IsInteger32Constant()) {
2217 return operation->left()->GetInteger32Constant();
2218 }
2219 } else if (phi_operand->IsSub()) {
2220 HSub* operation = HSub::cast(phi_operand);
2221 if (operation->left() == phi &&
2222 operation->right()->IsInteger32Constant()) {
2223 int constant = operation->right()->GetInteger32Constant();
2224 if (constant == kMinInt) return 0;
2225 return -constant;
2226 }
2227 }
2228
2229 return 0;
2230}
2231
2232
2233/*
2234 * Swaps the information in "update" with the one contained in "this".
2235 * The swapping is important because this method is used while doing a
2236 * dominator tree traversal, and "update" will retain the old data that
2237 * will be restored while backtracking.
2238 */
2239void InductionVariableData::UpdateAdditionalLimit(
2240 InductionVariableLimitUpdate* update) {
2241 DCHECK(update->updated_variable == this);
2242 if (update->limit_is_upper) {
2243 swap(&additional_upper_limit_, &update->limit);
2244 swap(&additional_upper_limit_is_included_, &update->limit_is_included);
2245 } else {
2246 swap(&additional_lower_limit_, &update->limit);
2247 swap(&additional_lower_limit_is_included_, &update->limit_is_included);
2248 }
2249}
2250
2251
2252int32_t InductionVariableData::ComputeUpperLimit(int32_t and_mask,
2253 int32_t or_mask) {
2254 // Should be Smi::kMaxValue but it must fit 32 bits; lower is safe anyway.
2255 const int32_t MAX_LIMIT = 1 << 30;
2256
2257 int32_t result = MAX_LIMIT;
2258
2259 if (limit() != NULL &&
2260 limit()->IsInteger32Constant()) {
2261 int32_t limit_value = limit()->GetInteger32Constant();
2262 if (!limit_included()) {
2263 limit_value--;
2264 }
2265 if (limit_value < result) result = limit_value;
2266 }
2267
2268 if (additional_upper_limit() != NULL &&
2269 additional_upper_limit()->IsInteger32Constant()) {
2270 int32_t limit_value = additional_upper_limit()->GetInteger32Constant();
2271 if (!additional_upper_limit_is_included()) {
2272 limit_value--;
2273 }
2274 if (limit_value < result) result = limit_value;
2275 }
2276
2277 if (and_mask > 0 && and_mask < MAX_LIMIT) {
2278 if (and_mask < result) result = and_mask;
2279 return result;
2280 }
2281
2282 // Add the effect of the or_mask.
2283 result |= or_mask;
2284
2285 return result >= MAX_LIMIT ? kNoLimit : result;
2286}
2287
2288
2289HValue* InductionVariableData::IgnoreOsrValue(HValue* v) {
2290 if (!v->IsPhi()) return v;
2291 HPhi* phi = HPhi::cast(v);
2292 if (phi->OperandCount() != 2) return v;
2293 if (phi->OperandAt(0)->block()->is_osr_entry()) {
2294 return phi->OperandAt(1);
2295 } else if (phi->OperandAt(1)->block()->is_osr_entry()) {
2296 return phi->OperandAt(0);
2297 } else {
2298 return v;
2299 }
2300}
2301
2302
2303InductionVariableData* InductionVariableData::GetInductionVariableData(
2304 HValue* v) {
2305 v = IgnoreOsrValue(v);
2306 if (v->IsPhi()) {
2307 return HPhi::cast(v)->induction_variable_data();
2308 }
2309 return NULL;
2310}
2311
2312
2313/*
2314 * Check if a conditional branch to "current_branch" with token "token" is
2315 * the branch that keeps the induction loop running (and, conversely, will
2316 * terminate it if the "other_branch" is taken).
2317 *
2318 * Three conditions must be met:
2319 * - "current_branch" must be in the induction loop.
2320 * - "other_branch" must be out of the induction loop.
2321 * - "token" and the induction increment must be "compatible": the token should
2322 * be a condition that keeps the execution inside the loop until the limit is
2323 * reached.
2324 */
2325bool InductionVariableData::CheckIfBranchIsLoopGuard(
2326 Token::Value token,
2327 HBasicBlock* current_branch,
2328 HBasicBlock* other_branch) {
2329 if (!phi()->block()->current_loop()->IsNestedInThisLoop(
2330 current_branch->current_loop())) {
2331 return false;
2332 }
2333
2334 if (phi()->block()->current_loop()->IsNestedInThisLoop(
2335 other_branch->current_loop())) {
2336 return false;
2337 }
2338
2339 if (increment() > 0 && (token == Token::LT || token == Token::LTE)) {
2340 return true;
2341 }
2342 if (increment() < 0 && (token == Token::GT || token == Token::GTE)) {
2343 return true;
2344 }
2345 if (Token::IsInequalityOp(token) && (increment() == 1 || increment() == -1)) {
2346 return true;
2347 }
2348
2349 return false;
2350}
2351
2352
2353void InductionVariableData::ComputeLimitFromPredecessorBlock(
2354 HBasicBlock* block,
2355 LimitFromPredecessorBlock* result) {
2356 if (block->predecessors()->length() != 1) return;
2357 HBasicBlock* predecessor = block->predecessors()->at(0);
2358 HInstruction* end = predecessor->last();
2359
2360 if (!end->IsCompareNumericAndBranch()) return;
2361 HCompareNumericAndBranch* branch = HCompareNumericAndBranch::cast(end);
2362
2363 Token::Value token = branch->token();
2364 if (!Token::IsArithmeticCompareOp(token)) return;
2365
2366 HBasicBlock* other_target;
2367 if (block == branch->SuccessorAt(0)) {
2368 other_target = branch->SuccessorAt(1);
2369 } else {
2370 other_target = branch->SuccessorAt(0);
2371 token = Token::NegateCompareOp(token);
2372 DCHECK(block == branch->SuccessorAt(1));
2373 }
2374
2375 InductionVariableData* data;
2376
2377 data = GetInductionVariableData(branch->left());
2378 HValue* limit = branch->right();
2379 if (data == NULL) {
2380 data = GetInductionVariableData(branch->right());
2381 token = Token::ReverseCompareOp(token);
2382 limit = branch->left();
2383 }
2384
2385 if (data != NULL) {
2386 result->variable = data;
2387 result->token = token;
2388 result->limit = limit;
2389 result->other_target = other_target;
2390 }
2391}
2392
2393
2394/*
2395 * Compute the limit that is imposed on an induction variable when entering
2396 * "block" (if any).
2397 * If the limit is the "proper" induction limit (the one that makes the loop
2398 * terminate when the induction variable reaches it) it is stored directly in
2399 * the induction variable data.
2400 * Otherwise the limit is written in "additional_limit" and the method
2401 * returns true.
2402 */
2403bool InductionVariableData::ComputeInductionVariableLimit(
2404 HBasicBlock* block,
2405 InductionVariableLimitUpdate* additional_limit) {
2406 LimitFromPredecessorBlock limit;
2407 ComputeLimitFromPredecessorBlock(block, &limit);
2408 if (!limit.LimitIsValid()) return false;
2409
2410 if (limit.variable->CheckIfBranchIsLoopGuard(limit.token,
2411 block,
2412 limit.other_target)) {
2413 limit.variable->limit_ = limit.limit;
2414 limit.variable->limit_included_ = limit.LimitIsIncluded();
2415 limit.variable->limit_validity_ = block;
2416 limit.variable->induction_exit_block_ = block->predecessors()->at(0);
2417 limit.variable->induction_exit_target_ = limit.other_target;
2418 return false;
2419 } else {
2420 additional_limit->updated_variable = limit.variable;
2421 additional_limit->limit = limit.limit;
2422 additional_limit->limit_is_upper = limit.LimitIsUpper();
2423 additional_limit->limit_is_included = limit.LimitIsIncluded();
2424 return true;
2425 }
2426}
2427
2428
2429Range* HMathMinMax::InferRange(Zone* zone) {
2430 if (representation().IsSmiOrInteger32()) {
2431 Range* a = left()->range();
2432 Range* b = right()->range();
2433 Range* res = a->Copy(zone);
2434 if (operation_ == kMathMax) {
2435 res->CombinedMax(b);
2436 } else {
2437 DCHECK(operation_ == kMathMin);
2438 res->CombinedMin(b);
2439 }
2440 return res;
2441 } else {
2442 return HValue::InferRange(zone);
2443 }
2444}
2445
2446
2447void HPushArguments::AddInput(HValue* value) {
2448 inputs_.Add(NULL, value->block()->zone());
2449 SetOperandAt(OperandCount() - 1, value);
2450}
2451
2452
2453std::ostream& HPhi::PrintTo(std::ostream& os) const { // NOLINT
2454 os << "[";
2455 for (int i = 0; i < OperandCount(); ++i) {
2456 os << " " << NameOf(OperandAt(i)) << " ";
2457 }
2458 return os << " uses" << UseCount()
2459 << representation_from_indirect_uses().Mnemonic() << " "
2460 << TypeOf(this) << "]";
2461}
2462
2463
2464void HPhi::AddInput(HValue* value) {
2465 inputs_.Add(NULL, value->block()->zone());
2466 SetOperandAt(OperandCount() - 1, value);
2467 // Mark phis that may have 'arguments' directly or indirectly as an operand.
2468 if (!CheckFlag(kIsArguments) && value->CheckFlag(kIsArguments)) {
2469 SetFlag(kIsArguments);
2470 }
2471}
2472
2473
2474bool HPhi::HasRealUses() {
2475 for (HUseIterator it(uses()); !it.Done(); it.Advance()) {
2476 if (!it.value()->IsPhi()) return true;
2477 }
2478 return false;
2479}
2480
2481
2482HValue* HPhi::GetRedundantReplacement() {
2483 HValue* candidate = NULL;
2484 int count = OperandCount();
2485 int position = 0;
2486 while (position < count && candidate == NULL) {
2487 HValue* current = OperandAt(position++);
2488 if (current != this) candidate = current;
2489 }
2490 while (position < count) {
2491 HValue* current = OperandAt(position++);
2492 if (current != this && current != candidate) return NULL;
2493 }
2494 DCHECK(candidate != this);
2495 return candidate;
2496}
2497
2498
2499void HPhi::DeleteFromGraph() {
2500 DCHECK(block() != NULL);
2501 block()->RemovePhi(this);
2502 DCHECK(block() == NULL);
2503}
2504
2505
2506void HPhi::InitRealUses(int phi_id) {
2507 // Initialize real uses.
2508 phi_id_ = phi_id;
2509 // Compute a conservative approximation of truncating uses before inferring
2510 // representations. The proper, exact computation will be done later, when
2511 // inserting representation changes.
2512 SetFlag(kTruncatingToSmi);
2513 SetFlag(kTruncatingToInt32);
2514 for (HUseIterator it(uses()); !it.Done(); it.Advance()) {
2515 HValue* value = it.value();
2516 if (!value->IsPhi()) {
2517 Representation rep = value->observed_input_representation(it.index());
2518 representation_from_non_phi_uses_ =
2519 representation_from_non_phi_uses().generalize(rep);
2520 if (rep.IsSmi() || rep.IsInteger32() || rep.IsDouble()) {
2521 has_type_feedback_from_uses_ = true;
2522 }
2523
2524 if (FLAG_trace_representation) {
2525 PrintF("#%d Phi is used by real #%d %s as %s\n",
2526 id(), value->id(), value->Mnemonic(), rep.Mnemonic());
2527 }
2528 if (!value->IsSimulate()) {
2529 if (!value->CheckFlag(kTruncatingToSmi)) {
2530 ClearFlag(kTruncatingToSmi);
2531 }
2532 if (!value->CheckFlag(kTruncatingToInt32)) {
2533 ClearFlag(kTruncatingToInt32);
2534 }
2535 }
2536 }
2537 }
2538}
2539
2540
2541void HPhi::AddNonPhiUsesFrom(HPhi* other) {
2542 if (FLAG_trace_representation) {
2543 PrintF(
2544 "generalizing use representation '%s' of #%d Phi "
2545 "with uses of #%d Phi '%s'\n",
2546 representation_from_indirect_uses().Mnemonic(), id(), other->id(),
2547 other->representation_from_non_phi_uses().Mnemonic());
2548 }
2549
2550 representation_from_indirect_uses_ =
2551 representation_from_indirect_uses().generalize(
2552 other->representation_from_non_phi_uses());
2553}
2554
2555
2556void HSimulate::MergeWith(ZoneList<HSimulate*>* list) {
2557 while (!list->is_empty()) {
2558 HSimulate* from = list->RemoveLast();
2559 ZoneList<HValue*>* from_values = &from->values_;
2560 for (int i = 0; i < from_values->length(); ++i) {
2561 if (from->HasAssignedIndexAt(i)) {
2562 int index = from->GetAssignedIndexAt(i);
2563 if (HasValueForIndex(index)) continue;
2564 AddAssignedValue(index, from_values->at(i));
2565 } else {
2566 if (pop_count_ > 0) {
2567 pop_count_--;
2568 } else {
2569 AddPushedValue(from_values->at(i));
2570 }
2571 }
2572 }
2573 pop_count_ += from->pop_count_;
2574 from->DeleteAndReplaceWith(NULL);
2575 }
2576}
2577
2578
2579std::ostream& HSimulate::PrintDataTo(std::ostream& os) const { // NOLINT
2580 os << "id=" << ast_id().ToInt();
2581 if (pop_count_ > 0) os << " pop " << pop_count_;
2582 if (values_.length() > 0) {
2583 if (pop_count_ > 0) os << " /";
2584 for (int i = values_.length() - 1; i >= 0; --i) {
2585 if (HasAssignedIndexAt(i)) {
2586 os << " var[" << GetAssignedIndexAt(i) << "] = ";
2587 } else {
2588 os << " push ";
2589 }
2590 os << NameOf(values_[i]);
2591 if (i > 0) os << ",";
2592 }
2593 }
2594 return os;
2595}
2596
2597
2598void HSimulate::ReplayEnvironment(HEnvironment* env) {
2599 if (is_done_with_replay()) return;
2600 DCHECK(env != NULL);
2601 env->set_ast_id(ast_id());
2602 env->Drop(pop_count());
2603 for (int i = values()->length() - 1; i >= 0; --i) {
2604 HValue* value = values()->at(i);
2605 if (HasAssignedIndexAt(i)) {
2606 env->Bind(GetAssignedIndexAt(i), value);
2607 } else {
2608 env->Push(value);
2609 }
2610 }
2611 set_done_with_replay();
2612}
2613
2614
2615static void ReplayEnvironmentNested(const ZoneList<HValue*>* values,
2616 HCapturedObject* other) {
2617 for (int i = 0; i < values->length(); ++i) {
2618 HValue* value = values->at(i);
2619 if (value->IsCapturedObject()) {
2620 if (HCapturedObject::cast(value)->capture_id() == other->capture_id()) {
2621 values->at(i) = other;
2622 } else {
2623 ReplayEnvironmentNested(HCapturedObject::cast(value)->values(), other);
2624 }
2625 }
2626 }
2627}
2628
2629
2630// Replay captured objects by replacing all captured objects with the
2631// same capture id in the current and all outer environments.
2632void HCapturedObject::ReplayEnvironment(HEnvironment* env) {
2633 DCHECK(env != NULL);
2634 while (env != NULL) {
2635 ReplayEnvironmentNested(env->values(), this);
2636 env = env->outer();
2637 }
2638}
2639
2640
2641std::ostream& HCapturedObject::PrintDataTo(std::ostream& os) const { // NOLINT
2642 os << "#" << capture_id() << " ";
2643 return HDematerializedObject::PrintDataTo(os);
2644}
2645
2646
2647void HEnterInlined::RegisterReturnTarget(HBasicBlock* return_target,
2648 Zone* zone) {
2649 DCHECK(return_target->IsInlineReturnTarget());
2650 return_targets_.Add(return_target, zone);
2651}
2652
2653
2654std::ostream& HEnterInlined::PrintDataTo(std::ostream& os) const { // NOLINT
2655 return os << function()->debug_name()->ToCString().get();
2656}
2657
2658
2659static bool IsInteger32(double value) {
2660 if (value >= std::numeric_limits<int32_t>::min() &&
2661 value <= std::numeric_limits<int32_t>::max()) {
2662 double roundtrip_value = static_cast<double>(static_cast<int32_t>(value));
2663 return bit_cast<int64_t>(roundtrip_value) == bit_cast<int64_t>(value);
2664 }
2665 return false;
2666}
2667
2668
2669HConstant::HConstant(Special special)
2670 : HTemplateInstruction<0>(HType::TaggedNumber()),
2671 object_(Handle<Object>::null()),
2672 object_map_(Handle<Map>::null()),
2673 bit_field_(HasDoubleValueField::encode(true) |
2674 InstanceTypeField::encode(kUnknownInstanceType)),
2675 int32_value_(0) {
2676 DCHECK_EQ(kHoleNaN, special);
2677 std::memcpy(&double_value_, &kHoleNanInt64, sizeof(double_value_));
2678 Initialize(Representation::Double());
2679}
2680
2681
2682HConstant::HConstant(Handle<Object> object, Representation r)
2683 : HTemplateInstruction<0>(HType::FromValue(object)),
2684 object_(Unique<Object>::CreateUninitialized(object)),
2685 object_map_(Handle<Map>::null()),
2686 bit_field_(
2687 HasStableMapValueField::encode(false) |
2688 HasSmiValueField::encode(false) | HasInt32ValueField::encode(false) |
2689 HasDoubleValueField::encode(false) |
2690 HasExternalReferenceValueField::encode(false) |
2691 IsNotInNewSpaceField::encode(true) |
2692 BooleanValueField::encode(object->BooleanValue()) |
2693 IsUndetectableField::encode(false) | IsCallableField::encode(false) |
2694 InstanceTypeField::encode(kUnknownInstanceType)) {
2695 if (object->IsHeapObject()) {
2696 Handle<HeapObject> heap_object = Handle<HeapObject>::cast(object);
2697 Isolate* isolate = heap_object->GetIsolate();
2698 Handle<Map> map(heap_object->map(), isolate);
2699 bit_field_ = IsNotInNewSpaceField::update(
2700 bit_field_, !isolate->heap()->InNewSpace(*object));
2701 bit_field_ = InstanceTypeField::update(bit_field_, map->instance_type());
2702 bit_field_ =
2703 IsUndetectableField::update(bit_field_, map->is_undetectable());
2704 bit_field_ = IsCallableField::update(bit_field_, map->is_callable());
2705 if (map->is_stable()) object_map_ = Unique<Map>::CreateImmovable(map);
2706 bit_field_ = HasStableMapValueField::update(
2707 bit_field_,
2708 HasMapValue() && Handle<Map>::cast(heap_object)->is_stable());
2709 }
2710 if (object->IsNumber()) {
2711 double n = object->Number();
2712 bool has_int32_value = IsInteger32(n);
2713 bit_field_ = HasInt32ValueField::update(bit_field_, has_int32_value);
2714 int32_value_ = DoubleToInt32(n);
2715 bit_field_ = HasSmiValueField::update(
2716 bit_field_, has_int32_value && Smi::IsValid(int32_value_));
2717 double_value_ = n;
2718 bit_field_ = HasDoubleValueField::update(bit_field_, true);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002719 }
2720
2721 Initialize(r);
2722}
2723
2724
2725HConstant::HConstant(Unique<Object> object, Unique<Map> object_map,
2726 bool has_stable_map_value, Representation r, HType type,
2727 bool is_not_in_new_space, bool boolean_value,
2728 bool is_undetectable, InstanceType instance_type)
2729 : HTemplateInstruction<0>(type),
2730 object_(object),
2731 object_map_(object_map),
2732 bit_field_(HasStableMapValueField::encode(has_stable_map_value) |
2733 HasSmiValueField::encode(false) |
2734 HasInt32ValueField::encode(false) |
2735 HasDoubleValueField::encode(false) |
2736 HasExternalReferenceValueField::encode(false) |
2737 IsNotInNewSpaceField::encode(is_not_in_new_space) |
2738 BooleanValueField::encode(boolean_value) |
2739 IsUndetectableField::encode(is_undetectable) |
2740 InstanceTypeField::encode(instance_type)) {
2741 DCHECK(!object.handle().is_null());
2742 DCHECK(!type.IsTaggedNumber() || type.IsNone());
2743 Initialize(r);
2744}
2745
2746
2747HConstant::HConstant(int32_t integer_value, Representation r,
2748 bool is_not_in_new_space, Unique<Object> object)
2749 : object_(object),
2750 object_map_(Handle<Map>::null()),
2751 bit_field_(HasStableMapValueField::encode(false) |
2752 HasSmiValueField::encode(Smi::IsValid(integer_value)) |
2753 HasInt32ValueField::encode(true) |
2754 HasDoubleValueField::encode(true) |
2755 HasExternalReferenceValueField::encode(false) |
2756 IsNotInNewSpaceField::encode(is_not_in_new_space) |
2757 BooleanValueField::encode(integer_value != 0) |
2758 IsUndetectableField::encode(false) |
2759 InstanceTypeField::encode(kUnknownInstanceType)),
2760 int32_value_(integer_value),
2761 double_value_(FastI2D(integer_value)) {
2762 // It's possible to create a constant with a value in Smi-range but stored
2763 // in a (pre-existing) HeapNumber. See crbug.com/349878.
2764 bool could_be_heapobject = r.IsTagged() && !object.handle().is_null();
2765 bool is_smi = HasSmiValue() && !could_be_heapobject;
2766 set_type(is_smi ? HType::Smi() : HType::TaggedNumber());
2767 Initialize(r);
2768}
2769
2770
2771HConstant::HConstant(double double_value, Representation r,
2772 bool is_not_in_new_space, Unique<Object> object)
2773 : object_(object),
2774 object_map_(Handle<Map>::null()),
2775 bit_field_(HasStableMapValueField::encode(false) |
2776 HasInt32ValueField::encode(IsInteger32(double_value)) |
2777 HasDoubleValueField::encode(true) |
2778 HasExternalReferenceValueField::encode(false) |
2779 IsNotInNewSpaceField::encode(is_not_in_new_space) |
2780 BooleanValueField::encode(double_value != 0 &&
2781 !std::isnan(double_value)) |
2782 IsUndetectableField::encode(false) |
2783 InstanceTypeField::encode(kUnknownInstanceType)),
2784 int32_value_(DoubleToInt32(double_value)),
2785 double_value_(double_value) {
2786 bit_field_ = HasSmiValueField::update(
2787 bit_field_, HasInteger32Value() && Smi::IsValid(int32_value_));
2788 // It's possible to create a constant with a value in Smi-range but stored
2789 // in a (pre-existing) HeapNumber. See crbug.com/349878.
2790 bool could_be_heapobject = r.IsTagged() && !object.handle().is_null();
2791 bool is_smi = HasSmiValue() && !could_be_heapobject;
2792 set_type(is_smi ? HType::Smi() : HType::TaggedNumber());
2793 Initialize(r);
2794}
2795
2796
2797HConstant::HConstant(ExternalReference reference)
2798 : HTemplateInstruction<0>(HType::Any()),
2799 object_(Unique<Object>(Handle<Object>::null())),
2800 object_map_(Handle<Map>::null()),
2801 bit_field_(
2802 HasStableMapValueField::encode(false) |
2803 HasSmiValueField::encode(false) | HasInt32ValueField::encode(false) |
2804 HasDoubleValueField::encode(false) |
2805 HasExternalReferenceValueField::encode(true) |
2806 IsNotInNewSpaceField::encode(true) | BooleanValueField::encode(true) |
2807 IsUndetectableField::encode(false) |
2808 InstanceTypeField::encode(kUnknownInstanceType)),
2809 external_reference_value_(reference) {
2810 Initialize(Representation::External());
2811}
2812
2813
2814void HConstant::Initialize(Representation r) {
2815 if (r.IsNone()) {
2816 if (HasSmiValue() && SmiValuesAre31Bits()) {
2817 r = Representation::Smi();
2818 } else if (HasInteger32Value()) {
2819 r = Representation::Integer32();
2820 } else if (HasDoubleValue()) {
2821 r = Representation::Double();
2822 } else if (HasExternalReferenceValue()) {
2823 r = Representation::External();
2824 } else {
2825 Handle<Object> object = object_.handle();
2826 if (object->IsJSObject()) {
2827 // Try to eagerly migrate JSObjects that have deprecated maps.
2828 Handle<JSObject> js_object = Handle<JSObject>::cast(object);
2829 if (js_object->map()->is_deprecated()) {
2830 JSObject::TryMigrateInstance(js_object);
2831 }
2832 }
2833 r = Representation::Tagged();
2834 }
2835 }
2836 if (r.IsSmi()) {
2837 // If we have an existing handle, zap it, because it might be a heap
2838 // number which we must not re-use when copying this HConstant to
2839 // Tagged representation later, because having Smi representation now
2840 // could cause heap object checks not to get emitted.
2841 object_ = Unique<Object>(Handle<Object>::null());
2842 }
2843 if (r.IsSmiOrInteger32() && object_.handle().is_null()) {
2844 // If it's not a heap object, it can't be in new space.
2845 bit_field_ = IsNotInNewSpaceField::update(bit_field_, true);
2846 }
2847 set_representation(r);
2848 SetFlag(kUseGVN);
2849}
2850
2851
2852bool HConstant::ImmortalImmovable() const {
2853 if (HasInteger32Value()) {
2854 return false;
2855 }
2856 if (HasDoubleValue()) {
2857 if (IsSpecialDouble()) {
2858 return true;
2859 }
2860 return false;
2861 }
2862 if (HasExternalReferenceValue()) {
2863 return false;
2864 }
2865
2866 DCHECK(!object_.handle().is_null());
2867 Heap* heap = isolate()->heap();
2868 DCHECK(!object_.IsKnownGlobal(heap->minus_zero_value()));
2869 DCHECK(!object_.IsKnownGlobal(heap->nan_value()));
2870 return
2871#define IMMORTAL_IMMOVABLE_ROOT(name) \
2872 object_.IsKnownGlobal(heap->root(Heap::k##name##RootIndex)) ||
2873 IMMORTAL_IMMOVABLE_ROOT_LIST(IMMORTAL_IMMOVABLE_ROOT)
2874#undef IMMORTAL_IMMOVABLE_ROOT
2875#define INTERNALIZED_STRING(name, value) \
2876 object_.IsKnownGlobal(heap->name()) ||
2877 INTERNALIZED_STRING_LIST(INTERNALIZED_STRING)
2878#undef INTERNALIZED_STRING
2879#define STRING_TYPE(NAME, size, name, Name) \
2880 object_.IsKnownGlobal(heap->name##_map()) ||
2881 STRING_TYPE_LIST(STRING_TYPE)
2882#undef STRING_TYPE
2883 false;
2884}
2885
2886
2887bool HConstant::EmitAtUses() {
2888 DCHECK(IsLinked());
2889 if (block()->graph()->has_osr() &&
2890 block()->graph()->IsStandardConstant(this)) {
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002891 return true;
2892 }
2893 if (HasNoUses()) return true;
2894 if (IsCell()) return false;
2895 if (representation().IsDouble()) return false;
2896 if (representation().IsExternal()) return false;
2897 return true;
2898}
2899
2900
2901HConstant* HConstant::CopyToRepresentation(Representation r, Zone* zone) const {
2902 if (r.IsSmi() && !HasSmiValue()) return NULL;
2903 if (r.IsInteger32() && !HasInteger32Value()) return NULL;
2904 if (r.IsDouble() && !HasDoubleValue()) return NULL;
2905 if (r.IsExternal() && !HasExternalReferenceValue()) return NULL;
2906 if (HasInteger32Value()) {
2907 return new (zone) HConstant(int32_value_, r, NotInNewSpace(), object_);
2908 }
2909 if (HasDoubleValue()) {
2910 return new (zone) HConstant(double_value_, r, NotInNewSpace(), object_);
2911 }
2912 if (HasExternalReferenceValue()) {
2913 return new(zone) HConstant(external_reference_value_);
2914 }
2915 DCHECK(!object_.handle().is_null());
2916 return new (zone) HConstant(object_, object_map_, HasStableMapValue(), r,
2917 type_, NotInNewSpace(), BooleanValue(),
2918 IsUndetectable(), GetInstanceType());
2919}
2920
2921
2922Maybe<HConstant*> HConstant::CopyToTruncatedInt32(Zone* zone) {
2923 HConstant* res = NULL;
2924 if (HasInteger32Value()) {
2925 res = new (zone) HConstant(int32_value_, Representation::Integer32(),
2926 NotInNewSpace(), object_);
2927 } else if (HasDoubleValue()) {
2928 res = new (zone)
2929 HConstant(DoubleToInt32(double_value_), Representation::Integer32(),
2930 NotInNewSpace(), object_);
2931 }
2932 return res != NULL ? Just(res) : Nothing<HConstant*>();
2933}
2934
2935
2936Maybe<HConstant*> HConstant::CopyToTruncatedNumber(Isolate* isolate,
2937 Zone* zone) {
2938 HConstant* res = NULL;
2939 Handle<Object> handle = this->handle(isolate);
2940 if (handle->IsBoolean()) {
2941 res = handle->BooleanValue() ?
2942 new(zone) HConstant(1) : new(zone) HConstant(0);
2943 } else if (handle->IsUndefined()) {
2944 res = new (zone) HConstant(std::numeric_limits<double>::quiet_NaN());
2945 } else if (handle->IsNull()) {
2946 res = new(zone) HConstant(0);
Ben Murdoch097c5b22016-05-18 11:27:45 +01002947 } else if (handle->IsString()) {
2948 res = new(zone) HConstant(String::ToNumber(Handle<String>::cast(handle)));
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002949 }
2950 return res != NULL ? Just(res) : Nothing<HConstant*>();
2951}
2952
2953
2954std::ostream& HConstant::PrintDataTo(std::ostream& os) const { // NOLINT
2955 if (HasInteger32Value()) {
2956 os << int32_value_ << " ";
2957 } else if (HasDoubleValue()) {
2958 os << double_value_ << " ";
2959 } else if (HasExternalReferenceValue()) {
2960 os << reinterpret_cast<void*>(external_reference_value_.address()) << " ";
2961 } else {
2962 // The handle() method is silently and lazily mutating the object.
2963 Handle<Object> h = const_cast<HConstant*>(this)->handle(isolate());
2964 os << Brief(*h) << " ";
2965 if (HasStableMapValue()) os << "[stable-map] ";
2966 if (HasObjectMap()) os << "[map " << *ObjectMap().handle() << "] ";
2967 }
2968 if (!NotInNewSpace()) os << "[new space] ";
2969 return os;
2970}
2971
2972
2973std::ostream& HBinaryOperation::PrintDataTo(std::ostream& os) const { // NOLINT
2974 os << NameOf(left()) << " " << NameOf(right());
2975 if (CheckFlag(kCanOverflow)) os << " !";
2976 if (CheckFlag(kBailoutOnMinusZero)) os << " -0?";
2977 return os;
2978}
2979
2980
2981void HBinaryOperation::InferRepresentation(HInferRepresentationPhase* h_infer) {
2982 DCHECK(CheckFlag(kFlexibleRepresentation));
2983 Representation new_rep = RepresentationFromInputs();
2984 UpdateRepresentation(new_rep, h_infer, "inputs");
2985
2986 if (representation().IsSmi() && HasNonSmiUse()) {
2987 UpdateRepresentation(
2988 Representation::Integer32(), h_infer, "use requirements");
2989 }
2990
2991 if (observed_output_representation_.IsNone()) {
2992 new_rep = RepresentationFromUses();
2993 UpdateRepresentation(new_rep, h_infer, "uses");
2994 } else {
2995 new_rep = RepresentationFromOutput();
2996 UpdateRepresentation(new_rep, h_infer, "output");
2997 }
2998}
2999
3000
3001Representation HBinaryOperation::RepresentationFromInputs() {
3002 // Determine the worst case of observed input representations and
3003 // the currently assumed output representation.
3004 Representation rep = representation();
3005 for (int i = 1; i <= 2; ++i) {
3006 rep = rep.generalize(observed_input_representation(i));
3007 }
3008 // If any of the actual input representation is more general than what we
3009 // have so far but not Tagged, use that representation instead.
3010 Representation left_rep = left()->representation();
3011 Representation right_rep = right()->representation();
3012 if (!left_rep.IsTagged()) rep = rep.generalize(left_rep);
3013 if (!right_rep.IsTagged()) rep = rep.generalize(right_rep);
3014
3015 return rep;
3016}
3017
3018
3019bool HBinaryOperation::IgnoreObservedOutputRepresentation(
3020 Representation current_rep) {
3021 return ((current_rep.IsInteger32() && CheckUsesForFlag(kTruncatingToInt32)) ||
3022 (current_rep.IsSmi() && CheckUsesForFlag(kTruncatingToSmi))) &&
3023 // Mul in Integer32 mode would be too precise.
3024 (!this->IsMul() || HMul::cast(this)->MulMinusOne());
3025}
3026
3027
3028Representation HBinaryOperation::RepresentationFromOutput() {
3029 Representation rep = representation();
3030 // Consider observed output representation, but ignore it if it's Double,
3031 // this instruction is not a division, and all its uses are truncating
3032 // to Integer32.
3033 if (observed_output_representation_.is_more_general_than(rep) &&
3034 !IgnoreObservedOutputRepresentation(rep)) {
3035 return observed_output_representation_;
3036 }
3037 return Representation::None();
3038}
3039
3040
3041void HBinaryOperation::AssumeRepresentation(Representation r) {
3042 set_observed_input_representation(1, r);
3043 set_observed_input_representation(2, r);
3044 HValue::AssumeRepresentation(r);
3045}
3046
3047
3048void HMathMinMax::InferRepresentation(HInferRepresentationPhase* h_infer) {
3049 DCHECK(CheckFlag(kFlexibleRepresentation));
3050 Representation new_rep = RepresentationFromInputs();
3051 UpdateRepresentation(new_rep, h_infer, "inputs");
3052 // Do not care about uses.
3053}
3054
3055
3056Range* HBitwise::InferRange(Zone* zone) {
3057 if (op() == Token::BIT_XOR) {
3058 if (left()->HasRange() && right()->HasRange()) {
3059 // The maximum value has the high bit, and all bits below, set:
3060 // (1 << high) - 1.
3061 // If the range can be negative, the minimum int is a negative number with
3062 // the high bit, and all bits below, unset:
3063 // -(1 << high).
3064 // If it cannot be negative, conservatively choose 0 as minimum int.
3065 int64_t left_upper = left()->range()->upper();
3066 int64_t left_lower = left()->range()->lower();
3067 int64_t right_upper = right()->range()->upper();
3068 int64_t right_lower = right()->range()->lower();
3069
3070 if (left_upper < 0) left_upper = ~left_upper;
3071 if (left_lower < 0) left_lower = ~left_lower;
3072 if (right_upper < 0) right_upper = ~right_upper;
3073 if (right_lower < 0) right_lower = ~right_lower;
3074
3075 int high = MostSignificantBit(
3076 static_cast<uint32_t>(
3077 left_upper | left_lower | right_upper | right_lower));
3078
3079 int64_t limit = 1;
3080 limit <<= high;
3081 int32_t min = (left()->range()->CanBeNegative() ||
3082 right()->range()->CanBeNegative())
3083 ? static_cast<int32_t>(-limit) : 0;
3084 return new(zone) Range(min, static_cast<int32_t>(limit - 1));
3085 }
3086 Range* result = HValue::InferRange(zone);
3087 result->set_can_be_minus_zero(false);
3088 return result;
3089 }
3090 const int32_t kDefaultMask = static_cast<int32_t>(0xffffffff);
3091 int32_t left_mask = (left()->range() != NULL)
3092 ? left()->range()->Mask()
3093 : kDefaultMask;
3094 int32_t right_mask = (right()->range() != NULL)
3095 ? right()->range()->Mask()
3096 : kDefaultMask;
3097 int32_t result_mask = (op() == Token::BIT_AND)
3098 ? left_mask & right_mask
3099 : left_mask | right_mask;
3100 if (result_mask >= 0) return new(zone) Range(0, result_mask);
3101
3102 Range* result = HValue::InferRange(zone);
3103 result->set_can_be_minus_zero(false);
3104 return result;
3105}
3106
3107
3108Range* HSar::InferRange(Zone* zone) {
3109 if (right()->IsConstant()) {
3110 HConstant* c = HConstant::cast(right());
3111 if (c->HasInteger32Value()) {
3112 Range* result = (left()->range() != NULL)
3113 ? left()->range()->Copy(zone)
3114 : new(zone) Range();
3115 result->Sar(c->Integer32Value());
3116 return result;
3117 }
3118 }
3119 return HValue::InferRange(zone);
3120}
3121
3122
3123Range* HShr::InferRange(Zone* zone) {
3124 if (right()->IsConstant()) {
3125 HConstant* c = HConstant::cast(right());
3126 if (c->HasInteger32Value()) {
3127 int shift_count = c->Integer32Value() & 0x1f;
3128 if (left()->range()->CanBeNegative()) {
3129 // Only compute bounds if the result always fits into an int32.
3130 return (shift_count >= 1)
3131 ? new(zone) Range(0,
3132 static_cast<uint32_t>(0xffffffff) >> shift_count)
3133 : new(zone) Range();
3134 } else {
3135 // For positive inputs we can use the >> operator.
3136 Range* result = (left()->range() != NULL)
3137 ? left()->range()->Copy(zone)
3138 : new(zone) Range();
3139 result->Sar(c->Integer32Value());
3140 return result;
3141 }
3142 }
3143 }
3144 return HValue::InferRange(zone);
3145}
3146
3147
3148Range* HShl::InferRange(Zone* zone) {
3149 if (right()->IsConstant()) {
3150 HConstant* c = HConstant::cast(right());
3151 if (c->HasInteger32Value()) {
3152 Range* result = (left()->range() != NULL)
3153 ? left()->range()->Copy(zone)
3154 : new(zone) Range();
3155 result->Shl(c->Integer32Value());
3156 return result;
3157 }
3158 }
3159 return HValue::InferRange(zone);
3160}
3161
3162
3163Range* HLoadNamedField::InferRange(Zone* zone) {
3164 if (access().representation().IsInteger8()) {
3165 return new(zone) Range(kMinInt8, kMaxInt8);
3166 }
3167 if (access().representation().IsUInteger8()) {
3168 return new(zone) Range(kMinUInt8, kMaxUInt8);
3169 }
3170 if (access().representation().IsInteger16()) {
3171 return new(zone) Range(kMinInt16, kMaxInt16);
3172 }
3173 if (access().representation().IsUInteger16()) {
3174 return new(zone) Range(kMinUInt16, kMaxUInt16);
3175 }
3176 if (access().IsStringLength()) {
3177 return new(zone) Range(0, String::kMaxLength);
3178 }
3179 return HValue::InferRange(zone);
3180}
3181
3182
3183Range* HLoadKeyed::InferRange(Zone* zone) {
3184 switch (elements_kind()) {
3185 case INT8_ELEMENTS:
3186 return new(zone) Range(kMinInt8, kMaxInt8);
3187 case UINT8_ELEMENTS:
3188 case UINT8_CLAMPED_ELEMENTS:
3189 return new(zone) Range(kMinUInt8, kMaxUInt8);
3190 case INT16_ELEMENTS:
3191 return new(zone) Range(kMinInt16, kMaxInt16);
3192 case UINT16_ELEMENTS:
3193 return new(zone) Range(kMinUInt16, kMaxUInt16);
3194 default:
3195 return HValue::InferRange(zone);
3196 }
3197}
3198
3199
3200std::ostream& HCompareGeneric::PrintDataTo(std::ostream& os) const { // NOLINT
3201 os << Token::Name(token()) << " ";
3202 return HBinaryOperation::PrintDataTo(os);
3203}
3204
3205
3206std::ostream& HStringCompareAndBranch::PrintDataTo(
3207 std::ostream& os) const { // NOLINT
3208 os << Token::Name(token()) << " ";
3209 return HControlInstruction::PrintDataTo(os);
3210}
3211
3212
3213std::ostream& HCompareNumericAndBranch::PrintDataTo(
3214 std::ostream& os) const { // NOLINT
3215 os << Token::Name(token()) << " " << NameOf(left()) << " " << NameOf(right());
3216 return HControlInstruction::PrintDataTo(os);
3217}
3218
3219
3220std::ostream& HCompareObjectEqAndBranch::PrintDataTo(
3221 std::ostream& os) const { // NOLINT
3222 os << NameOf(left()) << " " << NameOf(right());
3223 return HControlInstruction::PrintDataTo(os);
3224}
3225
3226
3227bool HCompareObjectEqAndBranch::KnownSuccessorBlock(HBasicBlock** block) {
3228 if (known_successor_index() != kNoKnownSuccessorIndex) {
3229 *block = SuccessorAt(known_successor_index());
3230 return true;
3231 }
3232 if (FLAG_fold_constants && left()->IsConstant() && right()->IsConstant()) {
3233 *block = HConstant::cast(left())->DataEquals(HConstant::cast(right()))
3234 ? FirstSuccessor() : SecondSuccessor();
3235 return true;
3236 }
3237 *block = NULL;
3238 return false;
3239}
3240
3241
3242bool HIsStringAndBranch::KnownSuccessorBlock(HBasicBlock** block) {
3243 if (known_successor_index() != kNoKnownSuccessorIndex) {
3244 *block = SuccessorAt(known_successor_index());
3245 return true;
3246 }
3247 if (FLAG_fold_constants && value()->IsConstant()) {
3248 *block = HConstant::cast(value())->HasStringValue()
3249 ? FirstSuccessor() : SecondSuccessor();
3250 return true;
3251 }
3252 if (value()->type().IsString()) {
3253 *block = FirstSuccessor();
3254 return true;
3255 }
3256 if (value()->type().IsSmi() ||
3257 value()->type().IsNull() ||
3258 value()->type().IsBoolean() ||
3259 value()->type().IsUndefined() ||
3260 value()->type().IsJSReceiver()) {
3261 *block = SecondSuccessor();
3262 return true;
3263 }
3264 *block = NULL;
3265 return false;
3266}
3267
3268
3269bool HIsUndetectableAndBranch::KnownSuccessorBlock(HBasicBlock** block) {
3270 if (FLAG_fold_constants && value()->IsConstant()) {
3271 *block = HConstant::cast(value())->IsUndetectable()
3272 ? FirstSuccessor() : SecondSuccessor();
3273 return true;
3274 }
3275 *block = NULL;
3276 return false;
3277}
3278
3279
3280bool HHasInstanceTypeAndBranch::KnownSuccessorBlock(HBasicBlock** block) {
3281 if (FLAG_fold_constants && value()->IsConstant()) {
3282 InstanceType type = HConstant::cast(value())->GetInstanceType();
3283 *block = (from_ <= type) && (type <= to_)
3284 ? FirstSuccessor() : SecondSuccessor();
3285 return true;
3286 }
3287 *block = NULL;
3288 return false;
3289}
3290
3291
3292void HCompareHoleAndBranch::InferRepresentation(
3293 HInferRepresentationPhase* h_infer) {
3294 ChangeRepresentation(value()->representation());
3295}
3296
3297
3298bool HCompareNumericAndBranch::KnownSuccessorBlock(HBasicBlock** block) {
3299 if (left() == right() &&
3300 left()->representation().IsSmiOrInteger32()) {
3301 *block = (token() == Token::EQ ||
3302 token() == Token::EQ_STRICT ||
3303 token() == Token::LTE ||
3304 token() == Token::GTE)
3305 ? FirstSuccessor() : SecondSuccessor();
3306 return true;
3307 }
3308 *block = NULL;
3309 return false;
3310}
3311
3312
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00003313std::ostream& HGoto::PrintDataTo(std::ostream& os) const { // NOLINT
3314 return os << *SuccessorAt(0);
3315}
3316
3317
3318void HCompareNumericAndBranch::InferRepresentation(
3319 HInferRepresentationPhase* h_infer) {
3320 Representation left_rep = left()->representation();
3321 Representation right_rep = right()->representation();
3322 Representation observed_left = observed_input_representation(0);
3323 Representation observed_right = observed_input_representation(1);
3324
3325 Representation rep = Representation::None();
3326 rep = rep.generalize(observed_left);
3327 rep = rep.generalize(observed_right);
3328 if (rep.IsNone() || rep.IsSmiOrInteger32()) {
3329 if (!left_rep.IsTagged()) rep = rep.generalize(left_rep);
3330 if (!right_rep.IsTagged()) rep = rep.generalize(right_rep);
3331 } else {
3332 rep = Representation::Double();
3333 }
3334
3335 if (rep.IsDouble()) {
3336 // According to the ES5 spec (11.9.3, 11.8.5), Equality comparisons (==, ===
3337 // and !=) have special handling of undefined, e.g. undefined == undefined
3338 // is 'true'. Relational comparisons have a different semantic, first
3339 // calling ToPrimitive() on their arguments. The standard Crankshaft
3340 // tagged-to-double conversion to ensure the HCompareNumericAndBranch's
3341 // inputs are doubles caused 'undefined' to be converted to NaN. That's
3342 // compatible out-of-the box with ordered relational comparisons (<, >, <=,
3343 // >=). However, for equality comparisons (and for 'in' and 'instanceof'),
3344 // it is not consistent with the spec. For example, it would cause undefined
3345 // == undefined (should be true) to be evaluated as NaN == NaN
3346 // (false). Therefore, any comparisons other than ordered relational
3347 // comparisons must cause a deopt when one of their arguments is undefined.
3348 // See also v8:1434
Ben Murdoch097c5b22016-05-18 11:27:45 +01003349 if (Token::IsOrderedRelationalCompareOp(token_)) {
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00003350 SetFlag(kAllowUndefinedAsNaN);
3351 }
3352 }
3353 ChangeRepresentation(rep);
3354}
3355
3356
3357std::ostream& HParameter::PrintDataTo(std::ostream& os) const { // NOLINT
3358 return os << index();
3359}
3360
3361
3362std::ostream& HLoadNamedField::PrintDataTo(std::ostream& os) const { // NOLINT
3363 os << NameOf(object()) << access_;
3364
3365 if (maps() != NULL) {
3366 os << " [" << *maps()->at(0).handle();
3367 for (int i = 1; i < maps()->size(); ++i) {
3368 os << "," << *maps()->at(i).handle();
3369 }
3370 os << "]";
3371 }
3372
3373 if (HasDependency()) os << " " << NameOf(dependency());
3374 return os;
3375}
3376
3377
3378std::ostream& HLoadNamedGeneric::PrintDataTo(
3379 std::ostream& os) const { // NOLINT
3380 Handle<String> n = Handle<String>::cast(name());
3381 return os << NameOf(object()) << "." << n->ToCString().get();
3382}
3383
3384
3385std::ostream& HLoadKeyed::PrintDataTo(std::ostream& os) const { // NOLINT
3386 if (!is_fixed_typed_array()) {
3387 os << NameOf(elements());
3388 } else {
3389 DCHECK(elements_kind() >= FIRST_FIXED_TYPED_ARRAY_ELEMENTS_KIND &&
3390 elements_kind() <= LAST_FIXED_TYPED_ARRAY_ELEMENTS_KIND);
3391 os << NameOf(elements()) << "." << ElementsKindToString(elements_kind());
3392 }
3393
3394 os << "[" << NameOf(key());
3395 if (IsDehoisted()) os << " + " << base_offset();
3396 os << "]";
3397
3398 if (HasDependency()) os << " " << NameOf(dependency());
3399 if (RequiresHoleCheck()) os << " check_hole";
3400 return os;
3401}
3402
3403
3404bool HLoadKeyed::TryIncreaseBaseOffset(uint32_t increase_by_value) {
3405 // The base offset is usually simply the size of the array header, except
3406 // with dehoisting adds an addition offset due to a array index key
3407 // manipulation, in which case it becomes (array header size +
3408 // constant-offset-from-key * kPointerSize)
3409 uint32_t base_offset = BaseOffsetField::decode(bit_field_);
3410 v8::base::internal::CheckedNumeric<uint32_t> addition_result = base_offset;
3411 addition_result += increase_by_value;
3412 if (!addition_result.IsValid()) return false;
3413 base_offset = addition_result.ValueOrDie();
3414 if (!BaseOffsetField::is_valid(base_offset)) return false;
3415 bit_field_ = BaseOffsetField::update(bit_field_, base_offset);
3416 return true;
3417}
3418
3419
3420bool HLoadKeyed::UsesMustHandleHole() const {
3421 if (IsFastPackedElementsKind(elements_kind())) {
3422 return false;
3423 }
3424
3425 if (IsFixedTypedArrayElementsKind(elements_kind())) {
3426 return false;
3427 }
3428
3429 if (hole_mode() == ALLOW_RETURN_HOLE) {
3430 if (IsFastDoubleElementsKind(elements_kind())) {
3431 return AllUsesCanTreatHoleAsNaN();
3432 }
3433 return true;
3434 }
3435
3436 if (IsFastDoubleElementsKind(elements_kind())) {
3437 return false;
3438 }
3439
3440 // Holes are only returned as tagged values.
3441 if (!representation().IsTagged()) {
3442 return false;
3443 }
3444
3445 for (HUseIterator it(uses()); !it.Done(); it.Advance()) {
3446 HValue* use = it.value();
3447 if (!use->IsChange()) return false;
3448 }
3449
3450 return true;
3451}
3452
3453
3454bool HLoadKeyed::AllUsesCanTreatHoleAsNaN() const {
3455 return IsFastDoubleElementsKind(elements_kind()) &&
3456 CheckUsesForFlag(HValue::kAllowUndefinedAsNaN);
3457}
3458
3459
3460bool HLoadKeyed::RequiresHoleCheck() const {
3461 if (IsFastPackedElementsKind(elements_kind())) {
3462 return false;
3463 }
3464
3465 if (IsFixedTypedArrayElementsKind(elements_kind())) {
3466 return false;
3467 }
3468
3469 if (hole_mode() == CONVERT_HOLE_TO_UNDEFINED) {
3470 return false;
3471 }
3472
3473 return !UsesMustHandleHole();
3474}
3475
3476
3477std::ostream& HLoadKeyedGeneric::PrintDataTo(
3478 std::ostream& os) const { // NOLINT
3479 return os << NameOf(object()) << "[" << NameOf(key()) << "]";
3480}
3481
3482
3483HValue* HLoadKeyedGeneric::Canonicalize() {
3484 // Recognize generic keyed loads that use property name generated
3485 // by for-in statement as a key and rewrite them into fast property load
3486 // by index.
3487 if (key()->IsLoadKeyed()) {
3488 HLoadKeyed* key_load = HLoadKeyed::cast(key());
3489 if (key_load->elements()->IsForInCacheArray()) {
3490 HForInCacheArray* names_cache =
3491 HForInCacheArray::cast(key_load->elements());
3492
3493 if (names_cache->enumerable() == object()) {
3494 HForInCacheArray* index_cache =
3495 names_cache->index_cache();
3496 HCheckMapValue* map_check = HCheckMapValue::New(
3497 block()->graph()->isolate(), block()->graph()->zone(),
3498 block()->graph()->GetInvalidContext(), object(),
3499 names_cache->map());
3500 HInstruction* index = HLoadKeyed::New(
3501 block()->graph()->isolate(), block()->graph()->zone(),
3502 block()->graph()->GetInvalidContext(), index_cache, key_load->key(),
3503 key_load->key(), nullptr, key_load->elements_kind());
3504 map_check->InsertBefore(this);
3505 index->InsertBefore(this);
3506 return Prepend(new(block()->zone()) HLoadFieldByIndex(
3507 object(), index));
3508 }
3509 }
3510 }
3511
3512 return this;
3513}
3514
3515
3516std::ostream& HStoreNamedGeneric::PrintDataTo(
3517 std::ostream& os) const { // NOLINT
3518 Handle<String> n = Handle<String>::cast(name());
3519 return os << NameOf(object()) << "." << n->ToCString().get() << " = "
3520 << NameOf(value());
3521}
3522
3523
3524std::ostream& HStoreNamedField::PrintDataTo(std::ostream& os) const { // NOLINT
3525 os << NameOf(object()) << access_ << " = " << NameOf(value());
3526 if (NeedsWriteBarrier()) os << " (write-barrier)";
3527 if (has_transition()) os << " (transition map " << *transition_map() << ")";
3528 return os;
3529}
3530
3531
3532std::ostream& HStoreKeyed::PrintDataTo(std::ostream& os) const { // NOLINT
3533 if (!is_fixed_typed_array()) {
3534 os << NameOf(elements());
3535 } else {
3536 DCHECK(elements_kind() >= FIRST_FIXED_TYPED_ARRAY_ELEMENTS_KIND &&
3537 elements_kind() <= LAST_FIXED_TYPED_ARRAY_ELEMENTS_KIND);
3538 os << NameOf(elements()) << "." << ElementsKindToString(elements_kind());
3539 }
3540
3541 os << "[" << NameOf(key());
3542 if (IsDehoisted()) os << " + " << base_offset();
3543 return os << "] = " << NameOf(value());
3544}
3545
3546
3547std::ostream& HStoreKeyedGeneric::PrintDataTo(
3548 std::ostream& os) const { // NOLINT
3549 return os << NameOf(object()) << "[" << NameOf(key())
3550 << "] = " << NameOf(value());
3551}
3552
3553
3554std::ostream& HTransitionElementsKind::PrintDataTo(
3555 std::ostream& os) const { // NOLINT
3556 os << NameOf(object());
3557 ElementsKind from_kind = original_map().handle()->elements_kind();
3558 ElementsKind to_kind = transitioned_map().handle()->elements_kind();
3559 os << " " << *original_map().handle() << " ["
3560 << ElementsAccessor::ForKind(from_kind)->name() << "] -> "
3561 << *transitioned_map().handle() << " ["
3562 << ElementsAccessor::ForKind(to_kind)->name() << "]";
3563 if (IsSimpleMapChangeTransition(from_kind, to_kind)) os << " (simple)";
3564 return os;
3565}
3566
3567
3568std::ostream& HLoadGlobalGeneric::PrintDataTo(
3569 std::ostream& os) const { // NOLINT
3570 return os << name()->ToCString().get() << " ";
3571}
3572
3573
3574std::ostream& HInnerAllocatedObject::PrintDataTo(
3575 std::ostream& os) const { // NOLINT
3576 os << NameOf(base_object()) << " offset ";
3577 return offset()->PrintTo(os);
3578}
3579
3580
3581std::ostream& HLoadContextSlot::PrintDataTo(std::ostream& os) const { // NOLINT
3582 return os << NameOf(value()) << "[" << slot_index() << "]";
3583}
3584
3585
3586std::ostream& HStoreContextSlot::PrintDataTo(
3587 std::ostream& os) const { // NOLINT
3588 return os << NameOf(context()) << "[" << slot_index()
3589 << "] = " << NameOf(value());
3590}
3591
3592
3593// Implementation of type inference and type conversions. Calculates
3594// the inferred type of this instruction based on the input operands.
3595
3596HType HValue::CalculateInferredType() {
3597 return type_;
3598}
3599
3600
3601HType HPhi::CalculateInferredType() {
3602 if (OperandCount() == 0) return HType::Tagged();
3603 HType result = OperandAt(0)->type();
3604 for (int i = 1; i < OperandCount(); ++i) {
3605 HType current = OperandAt(i)->type();
3606 result = result.Combine(current);
3607 }
3608 return result;
3609}
3610
3611
3612HType HChange::CalculateInferredType() {
3613 if (from().IsDouble() && to().IsTagged()) return HType::HeapNumber();
3614 return type();
3615}
3616
3617
3618Representation HUnaryMathOperation::RepresentationFromInputs() {
3619 if (SupportsFlexibleFloorAndRound() &&
3620 (op_ == kMathFloor || op_ == kMathRound)) {
3621 // Floor and Round always take a double input. The integral result can be
3622 // used as an integer or a double. Infer the representation from the uses.
3623 return Representation::None();
3624 }
3625 Representation rep = representation();
3626 // If any of the actual input representation is more general than what we
3627 // have so far but not Tagged, use that representation instead.
3628 Representation input_rep = value()->representation();
3629 if (!input_rep.IsTagged()) {
3630 rep = rep.generalize(input_rep);
3631 }
3632 return rep;
3633}
3634
3635
3636bool HAllocate::HandleSideEffectDominator(GVNFlag side_effect,
3637 HValue* dominator) {
3638 DCHECK(side_effect == kNewSpacePromotion);
3639 Zone* zone = block()->zone();
3640 Isolate* isolate = block()->isolate();
3641 if (!FLAG_use_allocation_folding) return false;
3642
3643 // Try to fold allocations together with their dominating allocations.
3644 if (!dominator->IsAllocate()) {
3645 if (FLAG_trace_allocation_folding) {
3646 PrintF("#%d (%s) cannot fold into #%d (%s)\n",
3647 id(), Mnemonic(), dominator->id(), dominator->Mnemonic());
3648 }
3649 return false;
3650 }
3651
3652 // Check whether we are folding within the same block for local folding.
3653 if (FLAG_use_local_allocation_folding && dominator->block() != block()) {
3654 if (FLAG_trace_allocation_folding) {
3655 PrintF("#%d (%s) cannot fold into #%d (%s), crosses basic blocks\n",
3656 id(), Mnemonic(), dominator->id(), dominator->Mnemonic());
3657 }
3658 return false;
3659 }
3660
3661 HAllocate* dominator_allocate = HAllocate::cast(dominator);
3662 HValue* dominator_size = dominator_allocate->size();
3663 HValue* current_size = size();
3664
3665 // TODO(hpayer): Add support for non-constant allocation in dominator.
3666 if (!dominator_size->IsInteger32Constant()) {
3667 if (FLAG_trace_allocation_folding) {
3668 PrintF("#%d (%s) cannot fold into #%d (%s), "
3669 "dynamic allocation size in dominator\n",
3670 id(), Mnemonic(), dominator->id(), dominator->Mnemonic());
3671 }
3672 return false;
3673 }
3674
3675
3676 if (!IsFoldable(dominator_allocate)) {
3677 if (FLAG_trace_allocation_folding) {
3678 PrintF("#%d (%s) cannot fold into #%d (%s), different spaces\n", id(),
3679 Mnemonic(), dominator->id(), dominator->Mnemonic());
3680 }
3681 return false;
3682 }
3683
3684 if (!has_size_upper_bound()) {
3685 if (FLAG_trace_allocation_folding) {
3686 PrintF("#%d (%s) cannot fold into #%d (%s), "
3687 "can't estimate total allocation size\n",
3688 id(), Mnemonic(), dominator->id(), dominator->Mnemonic());
3689 }
3690 return false;
3691 }
3692
3693 if (!current_size->IsInteger32Constant()) {
3694 // If it's not constant then it is a size_in_bytes calculation graph
3695 // like this: (const_header_size + const_element_size * size).
3696 DCHECK(current_size->IsInstruction());
3697
3698 HInstruction* current_instr = HInstruction::cast(current_size);
3699 if (!current_instr->Dominates(dominator_allocate)) {
3700 if (FLAG_trace_allocation_folding) {
3701 PrintF("#%d (%s) cannot fold into #%d (%s), dynamic size "
3702 "value does not dominate target allocation\n",
3703 id(), Mnemonic(), dominator_allocate->id(),
3704 dominator_allocate->Mnemonic());
3705 }
3706 return false;
3707 }
3708 }
3709
3710 DCHECK(
3711 (IsNewSpaceAllocation() && dominator_allocate->IsNewSpaceAllocation()) ||
3712 (IsOldSpaceAllocation() && dominator_allocate->IsOldSpaceAllocation()));
3713
3714 // First update the size of the dominator allocate instruction.
3715 dominator_size = dominator_allocate->size();
3716 int32_t original_object_size =
3717 HConstant::cast(dominator_size)->GetInteger32Constant();
3718 int32_t dominator_size_constant = original_object_size;
3719
3720 if (MustAllocateDoubleAligned()) {
3721 if ((dominator_size_constant & kDoubleAlignmentMask) != 0) {
3722 dominator_size_constant += kDoubleSize / 2;
3723 }
3724 }
3725
3726 int32_t current_size_max_value = size_upper_bound()->GetInteger32Constant();
3727 int32_t new_dominator_size = dominator_size_constant + current_size_max_value;
3728
3729 // Since we clear the first word after folded memory, we cannot use the
3730 // whole Page::kMaxRegularHeapObjectSize memory.
3731 if (new_dominator_size > Page::kMaxRegularHeapObjectSize - kPointerSize) {
3732 if (FLAG_trace_allocation_folding) {
3733 PrintF("#%d (%s) cannot fold into #%d (%s) due to size: %d\n",
3734 id(), Mnemonic(), dominator_allocate->id(),
3735 dominator_allocate->Mnemonic(), new_dominator_size);
3736 }
3737 return false;
3738 }
3739
3740 HInstruction* new_dominator_size_value;
3741
3742 if (current_size->IsInteger32Constant()) {
3743 new_dominator_size_value = HConstant::CreateAndInsertBefore(
3744 isolate, zone, context(), new_dominator_size, Representation::None(),
3745 dominator_allocate);
3746 } else {
3747 HValue* new_dominator_size_constant = HConstant::CreateAndInsertBefore(
3748 isolate, zone, context(), dominator_size_constant,
3749 Representation::Integer32(), dominator_allocate);
3750
3751 // Add old and new size together and insert.
3752 current_size->ChangeRepresentation(Representation::Integer32());
3753
3754 new_dominator_size_value = HAdd::New(
3755 isolate, zone, context(), new_dominator_size_constant, current_size);
3756 new_dominator_size_value->ClearFlag(HValue::kCanOverflow);
3757 new_dominator_size_value->ChangeRepresentation(Representation::Integer32());
3758
3759 new_dominator_size_value->InsertBefore(dominator_allocate);
3760 }
3761
3762 dominator_allocate->UpdateSize(new_dominator_size_value);
3763
3764 if (MustAllocateDoubleAligned()) {
3765 if (!dominator_allocate->MustAllocateDoubleAligned()) {
3766 dominator_allocate->MakeDoubleAligned();
3767 }
3768 }
3769
3770 bool keep_new_space_iterable = FLAG_log_gc || FLAG_heap_stats;
3771#ifdef VERIFY_HEAP
3772 keep_new_space_iterable = keep_new_space_iterable || FLAG_verify_heap;
3773#endif
3774
3775 if (keep_new_space_iterable && dominator_allocate->IsNewSpaceAllocation()) {
3776 dominator_allocate->MakePrefillWithFiller();
3777 } else {
3778 // TODO(hpayer): This is a short-term hack to make allocation mementos
3779 // work again in new space.
3780 dominator_allocate->ClearNextMapWord(original_object_size);
3781 }
3782
3783 dominator_allocate->UpdateClearNextMapWord(MustClearNextMapWord());
3784
3785 // After that replace the dominated allocate instruction.
3786 HInstruction* inner_offset = HConstant::CreateAndInsertBefore(
3787 isolate, zone, context(), dominator_size_constant, Representation::None(),
3788 this);
3789
3790 HInstruction* dominated_allocate_instr = HInnerAllocatedObject::New(
3791 isolate, zone, context(), dominator_allocate, inner_offset, type());
3792 dominated_allocate_instr->InsertBefore(this);
3793 DeleteAndReplaceWith(dominated_allocate_instr);
3794 if (FLAG_trace_allocation_folding) {
3795 PrintF("#%d (%s) folded into #%d (%s)\n",
3796 id(), Mnemonic(), dominator_allocate->id(),
3797 dominator_allocate->Mnemonic());
3798 }
3799 return true;
3800}
3801
3802
3803void HAllocate::UpdateFreeSpaceFiller(int32_t free_space_size) {
3804 DCHECK(filler_free_space_size_ != NULL);
3805 Zone* zone = block()->zone();
3806 // We must explicitly force Smi representation here because on x64 we
3807 // would otherwise automatically choose int32, but the actual store
3808 // requires a Smi-tagged value.
3809 HConstant* new_free_space_size = HConstant::CreateAndInsertBefore(
3810 block()->isolate(), zone, context(),
3811 filler_free_space_size_->value()->GetInteger32Constant() +
3812 free_space_size,
3813 Representation::Smi(), filler_free_space_size_);
3814 filler_free_space_size_->UpdateValue(new_free_space_size);
3815}
3816
3817
3818void HAllocate::CreateFreeSpaceFiller(int32_t free_space_size) {
3819 DCHECK(filler_free_space_size_ == NULL);
3820 Isolate* isolate = block()->isolate();
3821 Zone* zone = block()->zone();
3822 HInstruction* free_space_instr =
3823 HInnerAllocatedObject::New(isolate, zone, context(), dominating_allocate_,
3824 dominating_allocate_->size(), type());
3825 free_space_instr->InsertBefore(this);
3826 HConstant* filler_map = HConstant::CreateAndInsertAfter(
3827 zone, Unique<Map>::CreateImmovable(isolate->factory()->free_space_map()),
3828 true, free_space_instr);
3829 HInstruction* store_map =
3830 HStoreNamedField::New(isolate, zone, context(), free_space_instr,
3831 HObjectAccess::ForMap(), filler_map);
3832 store_map->SetFlag(HValue::kHasNoObservableSideEffects);
3833 store_map->InsertAfter(filler_map);
3834
3835 // We must explicitly force Smi representation here because on x64 we
3836 // would otherwise automatically choose int32, but the actual store
3837 // requires a Smi-tagged value.
3838 HConstant* filler_size =
3839 HConstant::CreateAndInsertAfter(isolate, zone, context(), free_space_size,
3840 Representation::Smi(), store_map);
3841 // Must force Smi representation for x64 (see comment above).
3842 HObjectAccess access = HObjectAccess::ForMapAndOffset(
3843 isolate->factory()->free_space_map(), FreeSpace::kSizeOffset,
3844 Representation::Smi());
3845 HStoreNamedField* store_size = HStoreNamedField::New(
3846 isolate, zone, context(), free_space_instr, access, filler_size);
3847 store_size->SetFlag(HValue::kHasNoObservableSideEffects);
3848 store_size->InsertAfter(filler_size);
3849 filler_free_space_size_ = store_size;
3850}
3851
3852
3853void HAllocate::ClearNextMapWord(int offset) {
3854 if (MustClearNextMapWord()) {
3855 Zone* zone = block()->zone();
3856 HObjectAccess access =
3857 HObjectAccess::ForObservableJSObjectOffset(offset);
3858 HStoreNamedField* clear_next_map =
3859 HStoreNamedField::New(block()->isolate(), zone, context(), this, access,
3860 block()->graph()->GetConstant0());
3861 clear_next_map->ClearAllSideEffects();
3862 clear_next_map->InsertAfter(this);
3863 }
3864}
3865
3866
3867std::ostream& HAllocate::PrintDataTo(std::ostream& os) const { // NOLINT
3868 os << NameOf(size()) << " (";
3869 if (IsNewSpaceAllocation()) os << "N";
3870 if (IsOldSpaceAllocation()) os << "P";
3871 if (MustAllocateDoubleAligned()) os << "A";
3872 if (MustPrefillWithFiller()) os << "F";
3873 return os << ")";
3874}
3875
3876
3877bool HStoreKeyed::TryIncreaseBaseOffset(uint32_t increase_by_value) {
3878 // The base offset is usually simply the size of the array header, except
3879 // with dehoisting adds an addition offset due to a array index key
3880 // manipulation, in which case it becomes (array header size +
3881 // constant-offset-from-key * kPointerSize)
3882 v8::base::internal::CheckedNumeric<uint32_t> addition_result = base_offset_;
3883 addition_result += increase_by_value;
3884 if (!addition_result.IsValid()) return false;
3885 base_offset_ = addition_result.ValueOrDie();
3886 return true;
3887}
3888
3889
3890bool HStoreKeyed::NeedsCanonicalization() {
3891 switch (value()->opcode()) {
3892 case kLoadKeyed: {
3893 ElementsKind load_kind = HLoadKeyed::cast(value())->elements_kind();
3894 return IsFixedFloatElementsKind(load_kind);
3895 }
3896 case kChange: {
3897 Representation from = HChange::cast(value())->from();
3898 return from.IsTagged() || from.IsHeapObject();
3899 }
3900 case kLoadNamedField:
3901 case kPhi: {
3902 // Better safe than sorry...
3903 return true;
3904 }
3905 default:
3906 return false;
3907 }
3908}
3909
3910
3911#define H_CONSTANT_INT(val) \
3912 HConstant::New(isolate, zone, context, static_cast<int32_t>(val))
3913#define H_CONSTANT_DOUBLE(val) \
3914 HConstant::New(isolate, zone, context, static_cast<double>(val))
3915
Ben Murdoch097c5b22016-05-18 11:27:45 +01003916#define DEFINE_NEW_H_SIMPLE_ARITHMETIC_INSTR(HInstr, op) \
3917 HInstruction* HInstr::New(Isolate* isolate, Zone* zone, HValue* context, \
3918 HValue* left, HValue* right) { \
3919 if (FLAG_fold_constants && left->IsConstant() && right->IsConstant()) { \
3920 HConstant* c_left = HConstant::cast(left); \
3921 HConstant* c_right = HConstant::cast(right); \
3922 if ((c_left->HasNumberValue() && c_right->HasNumberValue())) { \
3923 double double_res = c_left->DoubleValue() op c_right->DoubleValue(); \
3924 if (IsInt32Double(double_res)) { \
3925 return H_CONSTANT_INT(double_res); \
3926 } \
3927 return H_CONSTANT_DOUBLE(double_res); \
3928 } \
3929 } \
3930 return new (zone) HInstr(context, left, right); \
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00003931 }
3932
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00003933DEFINE_NEW_H_SIMPLE_ARITHMETIC_INSTR(HAdd, +)
3934DEFINE_NEW_H_SIMPLE_ARITHMETIC_INSTR(HMul, *)
3935DEFINE_NEW_H_SIMPLE_ARITHMETIC_INSTR(HSub, -)
3936
3937#undef DEFINE_NEW_H_SIMPLE_ARITHMETIC_INSTR
3938
3939
3940HInstruction* HStringAdd::New(Isolate* isolate, Zone* zone, HValue* context,
3941 HValue* left, HValue* right,
3942 PretenureFlag pretenure_flag,
3943 StringAddFlags flags,
3944 Handle<AllocationSite> allocation_site) {
3945 if (FLAG_fold_constants && left->IsConstant() && right->IsConstant()) {
3946 HConstant* c_right = HConstant::cast(right);
3947 HConstant* c_left = HConstant::cast(left);
3948 if (c_left->HasStringValue() && c_right->HasStringValue()) {
3949 Handle<String> left_string = c_left->StringValue();
3950 Handle<String> right_string = c_right->StringValue();
3951 // Prevent possible exception by invalid string length.
3952 if (left_string->length() + right_string->length() < String::kMaxLength) {
3953 MaybeHandle<String> concat = isolate->factory()->NewConsString(
3954 c_left->StringValue(), c_right->StringValue());
3955 return HConstant::New(isolate, zone, context, concat.ToHandleChecked());
3956 }
3957 }
3958 }
3959 return new (zone)
3960 HStringAdd(context, left, right, pretenure_flag, flags, allocation_site);
3961}
3962
3963
3964std::ostream& HStringAdd::PrintDataTo(std::ostream& os) const { // NOLINT
3965 if ((flags() & STRING_ADD_CHECK_BOTH) == STRING_ADD_CHECK_BOTH) {
3966 os << "_CheckBoth";
3967 } else if ((flags() & STRING_ADD_CHECK_BOTH) == STRING_ADD_CHECK_LEFT) {
3968 os << "_CheckLeft";
3969 } else if ((flags() & STRING_ADD_CHECK_BOTH) == STRING_ADD_CHECK_RIGHT) {
3970 os << "_CheckRight";
3971 }
3972 HBinaryOperation::PrintDataTo(os);
3973 os << " (";
3974 if (pretenure_flag() == NOT_TENURED)
3975 os << "N";
3976 else if (pretenure_flag() == TENURED)
3977 os << "D";
3978 return os << ")";
3979}
3980
3981
3982HInstruction* HStringCharFromCode::New(Isolate* isolate, Zone* zone,
3983 HValue* context, HValue* char_code) {
3984 if (FLAG_fold_constants && char_code->IsConstant()) {
3985 HConstant* c_code = HConstant::cast(char_code);
3986 if (c_code->HasNumberValue()) {
3987 if (std::isfinite(c_code->DoubleValue())) {
3988 uint32_t code = c_code->NumberValueAsInteger32() & 0xffff;
3989 return HConstant::New(
3990 isolate, zone, context,
3991 isolate->factory()->LookupSingleCharacterStringFromCode(code));
3992 }
3993 return HConstant::New(isolate, zone, context,
3994 isolate->factory()->empty_string());
3995 }
3996 }
3997 return new(zone) HStringCharFromCode(context, char_code);
3998}
3999
4000
4001HInstruction* HUnaryMathOperation::New(Isolate* isolate, Zone* zone,
4002 HValue* context, HValue* value,
4003 BuiltinFunctionId op) {
4004 do {
4005 if (!FLAG_fold_constants) break;
4006 if (!value->IsConstant()) break;
4007 HConstant* constant = HConstant::cast(value);
4008 if (!constant->HasNumberValue()) break;
4009 double d = constant->DoubleValue();
4010 if (std::isnan(d)) { // NaN poisons everything.
4011 return H_CONSTANT_DOUBLE(std::numeric_limits<double>::quiet_NaN());
4012 }
4013 if (std::isinf(d)) { // +Infinity and -Infinity.
4014 switch (op) {
4015 case kMathExp:
4016 return H_CONSTANT_DOUBLE((d > 0.0) ? d : 0.0);
4017 case kMathLog:
4018 case kMathSqrt:
4019 return H_CONSTANT_DOUBLE(
4020 (d > 0.0) ? d : std::numeric_limits<double>::quiet_NaN());
4021 case kMathPowHalf:
4022 case kMathAbs:
4023 return H_CONSTANT_DOUBLE((d > 0.0) ? d : -d);
4024 case kMathRound:
4025 case kMathFround:
4026 case kMathFloor:
4027 return H_CONSTANT_DOUBLE(d);
4028 case kMathClz32:
4029 return H_CONSTANT_INT(32);
4030 default:
4031 UNREACHABLE();
4032 break;
4033 }
4034 }
4035 switch (op) {
4036 case kMathExp:
4037 lazily_initialize_fast_exp(isolate);
4038 return H_CONSTANT_DOUBLE(fast_exp(d, isolate));
4039 case kMathLog:
4040 return H_CONSTANT_DOUBLE(std::log(d));
4041 case kMathSqrt:
4042 lazily_initialize_fast_sqrt(isolate);
4043 return H_CONSTANT_DOUBLE(fast_sqrt(d, isolate));
4044 case kMathPowHalf:
4045 return H_CONSTANT_DOUBLE(power_double_double(d, 0.5));
4046 case kMathAbs:
4047 return H_CONSTANT_DOUBLE((d >= 0.0) ? d + 0.0 : -d);
4048 case kMathRound:
4049 // -0.5 .. -0.0 round to -0.0.
4050 if ((d >= -0.5 && Double(d).Sign() < 0)) return H_CONSTANT_DOUBLE(-0.0);
4051 // Doubles are represented as Significant * 2 ^ Exponent. If the
4052 // Exponent is not negative, the double value is already an integer.
4053 if (Double(d).Exponent() >= 0) return H_CONSTANT_DOUBLE(d);
4054 return H_CONSTANT_DOUBLE(Floor(d + 0.5));
4055 case kMathFround:
4056 return H_CONSTANT_DOUBLE(static_cast<double>(static_cast<float>(d)));
4057 case kMathFloor:
4058 return H_CONSTANT_DOUBLE(Floor(d));
4059 case kMathClz32: {
4060 uint32_t i = DoubleToUint32(d);
4061 return H_CONSTANT_INT(base::bits::CountLeadingZeros32(i));
4062 }
4063 default:
4064 UNREACHABLE();
4065 break;
4066 }
4067 } while (false);
4068 return new(zone) HUnaryMathOperation(context, value, op);
4069}
4070
4071
4072Representation HUnaryMathOperation::RepresentationFromUses() {
4073 if (op_ != kMathFloor && op_ != kMathRound) {
4074 return HValue::RepresentationFromUses();
4075 }
4076
4077 // The instruction can have an int32 or double output. Prefer a double
4078 // representation if there are double uses.
4079 bool use_double = false;
4080
4081 for (HUseIterator it(uses()); !it.Done(); it.Advance()) {
4082 HValue* use = it.value();
4083 int use_index = it.index();
4084 Representation rep_observed = use->observed_input_representation(use_index);
4085 Representation rep_required = use->RequiredInputRepresentation(use_index);
4086 use_double |= (rep_observed.IsDouble() || rep_required.IsDouble());
4087 if (use_double && !FLAG_trace_representation) {
4088 // Having seen one double is enough.
4089 break;
4090 }
4091 if (FLAG_trace_representation) {
4092 if (!rep_required.IsDouble() || rep_observed.IsDouble()) {
4093 PrintF("#%d %s is used by #%d %s as %s%s\n",
4094 id(), Mnemonic(), use->id(),
4095 use->Mnemonic(), rep_observed.Mnemonic(),
4096 (use->CheckFlag(kTruncatingToInt32) ? "-trunc" : ""));
4097 } else {
4098 PrintF("#%d %s is required by #%d %s as %s%s\n",
4099 id(), Mnemonic(), use->id(),
4100 use->Mnemonic(), rep_required.Mnemonic(),
4101 (use->CheckFlag(kTruncatingToInt32) ? "-trunc" : ""));
4102 }
4103 }
4104 }
4105 return use_double ? Representation::Double() : Representation::Integer32();
4106}
4107
4108
4109HInstruction* HPower::New(Isolate* isolate, Zone* zone, HValue* context,
4110 HValue* left, HValue* right) {
4111 if (FLAG_fold_constants && left->IsConstant() && right->IsConstant()) {
4112 HConstant* c_left = HConstant::cast(left);
4113 HConstant* c_right = HConstant::cast(right);
4114 if (c_left->HasNumberValue() && c_right->HasNumberValue()) {
4115 double result =
4116 power_helper(isolate, c_left->DoubleValue(), c_right->DoubleValue());
4117 return H_CONSTANT_DOUBLE(std::isnan(result)
4118 ? std::numeric_limits<double>::quiet_NaN()
4119 : result);
4120 }
4121 }
4122 return new(zone) HPower(left, right);
4123}
4124
4125
4126HInstruction* HMathMinMax::New(Isolate* isolate, Zone* zone, HValue* context,
4127 HValue* left, HValue* right, Operation op) {
4128 if (FLAG_fold_constants && left->IsConstant() && right->IsConstant()) {
4129 HConstant* c_left = HConstant::cast(left);
4130 HConstant* c_right = HConstant::cast(right);
4131 if (c_left->HasNumberValue() && c_right->HasNumberValue()) {
4132 double d_left = c_left->DoubleValue();
4133 double d_right = c_right->DoubleValue();
4134 if (op == kMathMin) {
4135 if (d_left > d_right) return H_CONSTANT_DOUBLE(d_right);
4136 if (d_left < d_right) return H_CONSTANT_DOUBLE(d_left);
4137 if (d_left == d_right) {
4138 // Handle +0 and -0.
4139 return H_CONSTANT_DOUBLE((Double(d_left).Sign() == -1) ? d_left
4140 : d_right);
4141 }
4142 } else {
4143 if (d_left < d_right) return H_CONSTANT_DOUBLE(d_right);
4144 if (d_left > d_right) return H_CONSTANT_DOUBLE(d_left);
4145 if (d_left == d_right) {
4146 // Handle +0 and -0.
4147 return H_CONSTANT_DOUBLE((Double(d_left).Sign() == -1) ? d_right
4148 : d_left);
4149 }
4150 }
4151 // All comparisons failed, must be NaN.
4152 return H_CONSTANT_DOUBLE(std::numeric_limits<double>::quiet_NaN());
4153 }
4154 }
4155 return new(zone) HMathMinMax(context, left, right, op);
4156}
4157
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00004158HInstruction* HMod::New(Isolate* isolate, Zone* zone, HValue* context,
Ben Murdoch097c5b22016-05-18 11:27:45 +01004159 HValue* left, HValue* right) {
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00004160 if (FLAG_fold_constants && left->IsConstant() && right->IsConstant()) {
4161 HConstant* c_left = HConstant::cast(left);
4162 HConstant* c_right = HConstant::cast(right);
4163 if (c_left->HasInteger32Value() && c_right->HasInteger32Value()) {
4164 int32_t dividend = c_left->Integer32Value();
4165 int32_t divisor = c_right->Integer32Value();
4166 if (dividend == kMinInt && divisor == -1) {
4167 return H_CONSTANT_DOUBLE(-0.0);
4168 }
4169 if (divisor != 0) {
4170 int32_t res = dividend % divisor;
4171 if ((res == 0) && (dividend < 0)) {
4172 return H_CONSTANT_DOUBLE(-0.0);
4173 }
4174 return H_CONSTANT_INT(res);
4175 }
4176 }
4177 }
Ben Murdoch097c5b22016-05-18 11:27:45 +01004178 return new (zone) HMod(context, left, right);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00004179}
4180
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00004181HInstruction* HDiv::New(Isolate* isolate, Zone* zone, HValue* context,
Ben Murdoch097c5b22016-05-18 11:27:45 +01004182 HValue* left, HValue* right) {
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00004183 // If left and right are constant values, try to return a constant value.
4184 if (FLAG_fold_constants && left->IsConstant() && right->IsConstant()) {
4185 HConstant* c_left = HConstant::cast(left);
4186 HConstant* c_right = HConstant::cast(right);
4187 if ((c_left->HasNumberValue() && c_right->HasNumberValue())) {
4188 if (c_right->DoubleValue() != 0) {
4189 double double_res = c_left->DoubleValue() / c_right->DoubleValue();
4190 if (IsInt32Double(double_res)) {
4191 return H_CONSTANT_INT(double_res);
4192 }
4193 return H_CONSTANT_DOUBLE(double_res);
4194 } else {
4195 int sign = Double(c_left->DoubleValue()).Sign() *
4196 Double(c_right->DoubleValue()).Sign(); // Right could be -0.
4197 return H_CONSTANT_DOUBLE(sign * V8_INFINITY);
4198 }
4199 }
4200 }
Ben Murdoch097c5b22016-05-18 11:27:45 +01004201 return new (zone) HDiv(context, left, right);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00004202}
4203
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00004204HInstruction* HBitwise::New(Isolate* isolate, Zone* zone, HValue* context,
Ben Murdoch097c5b22016-05-18 11:27:45 +01004205 Token::Value op, HValue* left, HValue* right) {
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00004206 if (FLAG_fold_constants && left->IsConstant() && right->IsConstant()) {
4207 HConstant* c_left = HConstant::cast(left);
4208 HConstant* c_right = HConstant::cast(right);
4209 if ((c_left->HasNumberValue() && c_right->HasNumberValue())) {
4210 int32_t result;
4211 int32_t v_left = c_left->NumberValueAsInteger32();
4212 int32_t v_right = c_right->NumberValueAsInteger32();
4213 switch (op) {
4214 case Token::BIT_XOR:
4215 result = v_left ^ v_right;
4216 break;
4217 case Token::BIT_AND:
4218 result = v_left & v_right;
4219 break;
4220 case Token::BIT_OR:
4221 result = v_left | v_right;
4222 break;
4223 default:
4224 result = 0; // Please the compiler.
4225 UNREACHABLE();
4226 }
4227 return H_CONSTANT_INT(result);
4228 }
4229 }
Ben Murdoch097c5b22016-05-18 11:27:45 +01004230 return new (zone) HBitwise(context, op, left, right);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00004231}
4232
Ben Murdoch097c5b22016-05-18 11:27:45 +01004233#define DEFINE_NEW_H_BITWISE_INSTR(HInstr, result) \
4234 HInstruction* HInstr::New(Isolate* isolate, Zone* zone, HValue* context, \
4235 HValue* left, HValue* right) { \
4236 if (FLAG_fold_constants && left->IsConstant() && right->IsConstant()) { \
4237 HConstant* c_left = HConstant::cast(left); \
4238 HConstant* c_right = HConstant::cast(right); \
4239 if ((c_left->HasNumberValue() && c_right->HasNumberValue())) { \
4240 return H_CONSTANT_INT(result); \
4241 } \
4242 } \
4243 return new (zone) HInstr(context, left, right); \
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00004244 }
4245
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00004246DEFINE_NEW_H_BITWISE_INSTR(HSar,
4247c_left->NumberValueAsInteger32() >> (c_right->NumberValueAsInteger32() & 0x1f))
4248DEFINE_NEW_H_BITWISE_INSTR(HShl,
4249c_left->NumberValueAsInteger32() << (c_right->NumberValueAsInteger32() & 0x1f))
4250
4251#undef DEFINE_NEW_H_BITWISE_INSTR
4252
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00004253HInstruction* HShr::New(Isolate* isolate, Zone* zone, HValue* context,
Ben Murdoch097c5b22016-05-18 11:27:45 +01004254 HValue* left, HValue* right) {
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00004255 if (FLAG_fold_constants && left->IsConstant() && right->IsConstant()) {
4256 HConstant* c_left = HConstant::cast(left);
4257 HConstant* c_right = HConstant::cast(right);
4258 if ((c_left->HasNumberValue() && c_right->HasNumberValue())) {
4259 int32_t left_val = c_left->NumberValueAsInteger32();
4260 int32_t right_val = c_right->NumberValueAsInteger32() & 0x1f;
4261 if ((right_val == 0) && (left_val < 0)) {
4262 return H_CONSTANT_DOUBLE(static_cast<uint32_t>(left_val));
4263 }
4264 return H_CONSTANT_INT(static_cast<uint32_t>(left_val) >> right_val);
4265 }
4266 }
Ben Murdoch097c5b22016-05-18 11:27:45 +01004267 return new (zone) HShr(context, left, right);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00004268}
4269
4270
4271HInstruction* HSeqStringGetChar::New(Isolate* isolate, Zone* zone,
4272 HValue* context, String::Encoding encoding,
4273 HValue* string, HValue* index) {
4274 if (FLAG_fold_constants && string->IsConstant() && index->IsConstant()) {
4275 HConstant* c_string = HConstant::cast(string);
4276 HConstant* c_index = HConstant::cast(index);
4277 if (c_string->HasStringValue() && c_index->HasInteger32Value()) {
4278 Handle<String> s = c_string->StringValue();
4279 int32_t i = c_index->Integer32Value();
4280 DCHECK_LE(0, i);
4281 DCHECK_LT(i, s->length());
4282 return H_CONSTANT_INT(s->Get(i));
4283 }
4284 }
4285 return new(zone) HSeqStringGetChar(encoding, string, index);
4286}
4287
4288
4289#undef H_CONSTANT_INT
4290#undef H_CONSTANT_DOUBLE
4291
4292
4293std::ostream& HBitwise::PrintDataTo(std::ostream& os) const { // NOLINT
4294 os << Token::Name(op_) << " ";
4295 return HBitwiseBinaryOperation::PrintDataTo(os);
4296}
4297
4298
4299void HPhi::SimplifyConstantInputs() {
4300 // Convert constant inputs to integers when all uses are truncating.
4301 // This must happen before representation inference takes place.
4302 if (!CheckUsesForFlag(kTruncatingToInt32)) return;
4303 for (int i = 0; i < OperandCount(); ++i) {
4304 if (!OperandAt(i)->IsConstant()) return;
4305 }
4306 HGraph* graph = block()->graph();
4307 for (int i = 0; i < OperandCount(); ++i) {
4308 HConstant* operand = HConstant::cast(OperandAt(i));
4309 if (operand->HasInteger32Value()) {
4310 continue;
4311 } else if (operand->HasDoubleValue()) {
4312 HConstant* integer_input = HConstant::New(
4313 graph->isolate(), graph->zone(), graph->GetInvalidContext(),
4314 DoubleToInt32(operand->DoubleValue()));
4315 integer_input->InsertAfter(operand);
4316 SetOperandAt(i, integer_input);
4317 } else if (operand->HasBooleanValue()) {
4318 SetOperandAt(i, operand->BooleanValue() ? graph->GetConstant1()
4319 : graph->GetConstant0());
4320 } else if (operand->ImmortalImmovable()) {
4321 SetOperandAt(i, graph->GetConstant0());
4322 }
4323 }
4324 // Overwrite observed input representations because they are likely Tagged.
4325 for (HUseIterator it(uses()); !it.Done(); it.Advance()) {
4326 HValue* use = it.value();
4327 if (use->IsBinaryOperation()) {
4328 HBinaryOperation::cast(use)->set_observed_input_representation(
4329 it.index(), Representation::Smi());
4330 }
4331 }
4332}
4333
4334
4335void HPhi::InferRepresentation(HInferRepresentationPhase* h_infer) {
4336 DCHECK(CheckFlag(kFlexibleRepresentation));
4337 Representation new_rep = RepresentationFromUses();
4338 UpdateRepresentation(new_rep, h_infer, "uses");
4339 new_rep = RepresentationFromInputs();
4340 UpdateRepresentation(new_rep, h_infer, "inputs");
4341 new_rep = RepresentationFromUseRequirements();
4342 UpdateRepresentation(new_rep, h_infer, "use requirements");
4343}
4344
4345
4346Representation HPhi::RepresentationFromInputs() {
4347 Representation r = representation();
4348 for (int i = 0; i < OperandCount(); ++i) {
4349 // Ignore conservative Tagged assumption of parameters if we have
4350 // reason to believe that it's too conservative.
4351 if (has_type_feedback_from_uses() && OperandAt(i)->IsParameter()) {
4352 continue;
4353 }
4354
4355 r = r.generalize(OperandAt(i)->KnownOptimalRepresentation());
4356 }
4357 return r;
4358}
4359
4360
4361// Returns a representation if all uses agree on the same representation.
4362// Integer32 is also returned when some uses are Smi but others are Integer32.
4363Representation HValue::RepresentationFromUseRequirements() {
4364 Representation rep = Representation::None();
4365 for (HUseIterator it(uses()); !it.Done(); it.Advance()) {
4366 // Ignore the use requirement from never run code
4367 if (it.value()->block()->IsUnreachable()) continue;
4368
4369 // We check for observed_input_representation elsewhere.
4370 Representation use_rep =
4371 it.value()->RequiredInputRepresentation(it.index());
4372 if (rep.IsNone()) {
4373 rep = use_rep;
4374 continue;
4375 }
4376 if (use_rep.IsNone() || rep.Equals(use_rep)) continue;
4377 if (rep.generalize(use_rep).IsInteger32()) {
4378 rep = Representation::Integer32();
4379 continue;
4380 }
4381 return Representation::None();
4382 }
4383 return rep;
4384}
4385
4386
4387bool HValue::HasNonSmiUse() {
4388 for (HUseIterator it(uses()); !it.Done(); it.Advance()) {
4389 // We check for observed_input_representation elsewhere.
4390 Representation use_rep =
4391 it.value()->RequiredInputRepresentation(it.index());
4392 if (!use_rep.IsNone() &&
4393 !use_rep.IsSmi() &&
4394 !use_rep.IsTagged()) {
4395 return true;
4396 }
4397 }
4398 return false;
4399}
4400
4401
4402// Node-specific verification code is only included in debug mode.
4403#ifdef DEBUG
4404
4405void HPhi::Verify() {
4406 DCHECK(OperandCount() == block()->predecessors()->length());
4407 for (int i = 0; i < OperandCount(); ++i) {
4408 HValue* value = OperandAt(i);
4409 HBasicBlock* defining_block = value->block();
4410 HBasicBlock* predecessor_block = block()->predecessors()->at(i);
4411 DCHECK(defining_block == predecessor_block ||
4412 defining_block->Dominates(predecessor_block));
4413 }
4414}
4415
4416
4417void HSimulate::Verify() {
4418 HInstruction::Verify();
4419 DCHECK(HasAstId() || next()->IsEnterInlined());
4420}
4421
4422
4423void HCheckHeapObject::Verify() {
4424 HInstruction::Verify();
4425 DCHECK(HasNoUses());
4426}
4427
4428
4429void HCheckValue::Verify() {
4430 HInstruction::Verify();
4431 DCHECK(HasNoUses());
4432}
4433
4434#endif
4435
4436
4437HObjectAccess HObjectAccess::ForFixedArrayHeader(int offset) {
4438 DCHECK(offset >= 0);
4439 DCHECK(offset < FixedArray::kHeaderSize);
4440 if (offset == FixedArray::kLengthOffset) return ForFixedArrayLength();
4441 return HObjectAccess(kInobject, offset);
4442}
4443
4444
4445HObjectAccess HObjectAccess::ForMapAndOffset(Handle<Map> map, int offset,
4446 Representation representation) {
4447 DCHECK(offset >= 0);
4448 Portion portion = kInobject;
4449
4450 if (offset == JSObject::kElementsOffset) {
4451 portion = kElementsPointer;
4452 } else if (offset == JSObject::kMapOffset) {
4453 portion = kMaps;
4454 }
4455 bool existing_inobject_property = true;
4456 if (!map.is_null()) {
4457 existing_inobject_property = (offset <
4458 map->instance_size() - map->unused_property_fields() * kPointerSize);
4459 }
4460 return HObjectAccess(portion, offset, representation, Handle<String>::null(),
4461 false, existing_inobject_property);
4462}
4463
4464
4465HObjectAccess HObjectAccess::ForAllocationSiteOffset(int offset) {
4466 switch (offset) {
4467 case AllocationSite::kTransitionInfoOffset:
4468 return HObjectAccess(kInobject, offset, Representation::Tagged());
4469 case AllocationSite::kNestedSiteOffset:
4470 return HObjectAccess(kInobject, offset, Representation::Tagged());
4471 case AllocationSite::kPretenureDataOffset:
4472 return HObjectAccess(kInobject, offset, Representation::Smi());
4473 case AllocationSite::kPretenureCreateCountOffset:
4474 return HObjectAccess(kInobject, offset, Representation::Smi());
4475 case AllocationSite::kDependentCodeOffset:
4476 return HObjectAccess(kInobject, offset, Representation::Tagged());
4477 case AllocationSite::kWeakNextOffset:
4478 return HObjectAccess(kInobject, offset, Representation::Tagged());
4479 default:
4480 UNREACHABLE();
4481 }
4482 return HObjectAccess(kInobject, offset);
4483}
4484
4485
4486HObjectAccess HObjectAccess::ForContextSlot(int index) {
4487 DCHECK(index >= 0);
4488 Portion portion = kInobject;
4489 int offset = Context::kHeaderSize + index * kPointerSize;
4490 DCHECK_EQ(offset, Context::SlotOffset(index) + kHeapObjectTag);
4491 return HObjectAccess(portion, offset, Representation::Tagged());
4492}
4493
4494
4495HObjectAccess HObjectAccess::ForScriptContext(int index) {
4496 DCHECK(index >= 0);
4497 Portion portion = kInobject;
4498 int offset = ScriptContextTable::GetContextOffset(index);
4499 return HObjectAccess(portion, offset, Representation::Tagged());
4500}
4501
4502
4503HObjectAccess HObjectAccess::ForJSArrayOffset(int offset) {
4504 DCHECK(offset >= 0);
4505 Portion portion = kInobject;
4506
4507 if (offset == JSObject::kElementsOffset) {
4508 portion = kElementsPointer;
4509 } else if (offset == JSArray::kLengthOffset) {
4510 portion = kArrayLengths;
4511 } else if (offset == JSObject::kMapOffset) {
4512 portion = kMaps;
4513 }
4514 return HObjectAccess(portion, offset);
4515}
4516
4517
4518HObjectAccess HObjectAccess::ForBackingStoreOffset(int offset,
4519 Representation representation) {
4520 DCHECK(offset >= 0);
4521 return HObjectAccess(kBackingStore, offset, representation,
4522 Handle<String>::null(), false, false);
4523}
4524
4525
4526HObjectAccess HObjectAccess::ForField(Handle<Map> map, int index,
4527 Representation representation,
4528 Handle<Name> name) {
4529 if (index < 0) {
4530 // Negative property indices are in-object properties, indexed
4531 // from the end of the fixed part of the object.
4532 int offset = (index * kPointerSize) + map->instance_size();
4533 return HObjectAccess(kInobject, offset, representation, name, false, true);
4534 } else {
4535 // Non-negative property indices are in the properties array.
4536 int offset = (index * kPointerSize) + FixedArray::kHeaderSize;
4537 return HObjectAccess(kBackingStore, offset, representation, name,
4538 false, false);
4539 }
4540}
4541
4542
4543void HObjectAccess::SetGVNFlags(HValue *instr, PropertyAccessType access_type) {
4544 // set the appropriate GVN flags for a given load or store instruction
4545 if (access_type == STORE) {
4546 // track dominating allocations in order to eliminate write barriers
4547 instr->SetDependsOnFlag(::v8::internal::kNewSpacePromotion);
4548 instr->SetFlag(HValue::kTrackSideEffectDominators);
4549 } else {
4550 // try to GVN loads, but don't hoist above map changes
4551 instr->SetFlag(HValue::kUseGVN);
4552 instr->SetDependsOnFlag(::v8::internal::kMaps);
4553 }
4554
4555 switch (portion()) {
4556 case kArrayLengths:
4557 if (access_type == STORE) {
4558 instr->SetChangesFlag(::v8::internal::kArrayLengths);
4559 } else {
4560 instr->SetDependsOnFlag(::v8::internal::kArrayLengths);
4561 }
4562 break;
4563 case kStringLengths:
4564 if (access_type == STORE) {
4565 instr->SetChangesFlag(::v8::internal::kStringLengths);
4566 } else {
4567 instr->SetDependsOnFlag(::v8::internal::kStringLengths);
4568 }
4569 break;
4570 case kInobject:
4571 if (access_type == STORE) {
4572 instr->SetChangesFlag(::v8::internal::kInobjectFields);
4573 } else {
4574 instr->SetDependsOnFlag(::v8::internal::kInobjectFields);
4575 }
4576 break;
4577 case kDouble:
4578 if (access_type == STORE) {
4579 instr->SetChangesFlag(::v8::internal::kDoubleFields);
4580 } else {
4581 instr->SetDependsOnFlag(::v8::internal::kDoubleFields);
4582 }
4583 break;
4584 case kBackingStore:
4585 if (access_type == STORE) {
4586 instr->SetChangesFlag(::v8::internal::kBackingStoreFields);
4587 } else {
4588 instr->SetDependsOnFlag(::v8::internal::kBackingStoreFields);
4589 }
4590 break;
4591 case kElementsPointer:
4592 if (access_type == STORE) {
4593 instr->SetChangesFlag(::v8::internal::kElementsPointer);
4594 } else {
4595 instr->SetDependsOnFlag(::v8::internal::kElementsPointer);
4596 }
4597 break;
4598 case kMaps:
4599 if (access_type == STORE) {
4600 instr->SetChangesFlag(::v8::internal::kMaps);
4601 } else {
4602 instr->SetDependsOnFlag(::v8::internal::kMaps);
4603 }
4604 break;
4605 case kExternalMemory:
4606 if (access_type == STORE) {
4607 instr->SetChangesFlag(::v8::internal::kExternalMemory);
4608 } else {
4609 instr->SetDependsOnFlag(::v8::internal::kExternalMemory);
4610 }
4611 break;
4612 }
4613}
4614
4615
4616std::ostream& operator<<(std::ostream& os, const HObjectAccess& access) {
4617 os << ".";
4618
4619 switch (access.portion()) {
4620 case HObjectAccess::kArrayLengths:
4621 case HObjectAccess::kStringLengths:
4622 os << "%length";
4623 break;
4624 case HObjectAccess::kElementsPointer:
4625 os << "%elements";
4626 break;
4627 case HObjectAccess::kMaps:
4628 os << "%map";
4629 break;
4630 case HObjectAccess::kDouble: // fall through
4631 case HObjectAccess::kInobject:
4632 if (!access.name().is_null() && access.name()->IsString()) {
4633 os << Handle<String>::cast(access.name())->ToCString().get();
4634 }
4635 os << "[in-object]";
4636 break;
4637 case HObjectAccess::kBackingStore:
4638 if (!access.name().is_null() && access.name()->IsString()) {
4639 os << Handle<String>::cast(access.name())->ToCString().get();
4640 }
4641 os << "[backing-store]";
4642 break;
4643 case HObjectAccess::kExternalMemory:
4644 os << "[external-memory]";
4645 break;
4646 }
4647
4648 return os << "@" << access.offset();
4649}
4650
4651} // namespace internal
4652} // namespace v8