1 // 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.
7 #include "src/double.h"
8 #include "src/factory.h"
9 #include "src/hydrogen-infer-representation.h"
10 #include "src/property-details-inl.h"
12 #if V8_TARGET_ARCH_IA32
13 #include "src/ia32/lithium-ia32.h" // NOLINT
14 #elif V8_TARGET_ARCH_X64
15 #include "src/x64/lithium-x64.h" // NOLINT
16 #elif V8_TARGET_ARCH_ARM64
17 #include "src/arm64/lithium-arm64.h" // NOLINT
18 #elif V8_TARGET_ARCH_ARM
19 #include "src/arm/lithium-arm.h" // NOLINT
20 #elif V8_TARGET_ARCH_MIPS
21 #include "src/mips/lithium-mips.h" // NOLINT
22 #elif V8_TARGET_ARCH_MIPS64
23 #include "src/mips64/lithium-mips64.h" // NOLINT
24 #elif V8_TARGET_ARCH_X87
25 #include "src/x87/lithium-x87.h" // NOLINT
27 #error Unsupported target architecture.
30 #include "src/base/safe_math.h"
35 #define DEFINE_COMPILE(type) \
36 LInstruction* H##type::CompileToLithium(LChunkBuilder* builder) { \
37 return builder->Do##type(this); \
39 HYDROGEN_CONCRETE_INSTRUCTION_LIST(DEFINE_COMPILE)
43 Isolate* HValue::isolate() const {
44 DCHECK(block() != NULL);
45 return block()->isolate();
49 void HValue::AssumeRepresentation(Representation r) {
50 if (CheckFlag(kFlexibleRepresentation)) {
51 ChangeRepresentation(r);
52 // The representation of the value is dictated by type feedback and
53 // will not be changed later.
54 ClearFlag(kFlexibleRepresentation);
59 void HValue::InferRepresentation(HInferRepresentationPhase* h_infer) {
60 DCHECK(CheckFlag(kFlexibleRepresentation));
61 Representation new_rep = RepresentationFromInputs();
62 UpdateRepresentation(new_rep, h_infer, "inputs");
63 new_rep = RepresentationFromUses();
64 UpdateRepresentation(new_rep, h_infer, "uses");
65 if (representation().IsSmi() && HasNonSmiUse()) {
67 Representation::Integer32(), h_infer, "use requirements");
72 Representation HValue::RepresentationFromUses() {
73 if (HasNoUses()) return Representation::None();
75 // Array of use counts for each representation.
76 int use_count[Representation::kNumRepresentations] = { 0 };
78 for (HUseIterator it(uses()); !it.Done(); it.Advance()) {
79 HValue* use = it.value();
80 Representation rep = use->observed_input_representation(it.index());
81 if (rep.IsNone()) continue;
82 if (FLAG_trace_representation) {
83 PrintF("#%d %s is used by #%d %s as %s%s\n",
84 id(), Mnemonic(), use->id(), use->Mnemonic(), rep.Mnemonic(),
85 (use->CheckFlag(kTruncatingToInt32) ? "-trunc" : ""));
87 use_count[rep.kind()] += 1;
89 if (IsPhi()) HPhi::cast(this)->AddIndirectUsesTo(&use_count[0]);
90 int tagged_count = use_count[Representation::kTagged];
91 int double_count = use_count[Representation::kDouble];
92 int int32_count = use_count[Representation::kInteger32];
93 int smi_count = use_count[Representation::kSmi];
95 if (tagged_count > 0) return Representation::Tagged();
96 if (double_count > 0) return Representation::Double();
97 if (int32_count > 0) return Representation::Integer32();
98 if (smi_count > 0) return Representation::Smi();
100 return Representation::None();
104 void HValue::UpdateRepresentation(Representation new_rep,
105 HInferRepresentationPhase* h_infer,
106 const char* reason) {
107 Representation r = representation();
108 if (new_rep.is_more_general_than(r)) {
109 if (CheckFlag(kCannotBeTagged) && new_rep.IsTagged()) return;
110 if (FLAG_trace_representation) {
111 PrintF("Changing #%d %s representation %s -> %s based on %s\n",
112 id(), Mnemonic(), r.Mnemonic(), new_rep.Mnemonic(), reason);
114 ChangeRepresentation(new_rep);
115 AddDependantsToWorklist(h_infer);
120 void HValue::AddDependantsToWorklist(HInferRepresentationPhase* h_infer) {
121 for (HUseIterator it(uses()); !it.Done(); it.Advance()) {
122 h_infer->AddToWorklist(it.value());
124 for (int i = 0; i < OperandCount(); ++i) {
125 h_infer->AddToWorklist(OperandAt(i));
130 static int32_t ConvertAndSetOverflow(Representation r,
134 if (result > Smi::kMaxValue) {
136 return Smi::kMaxValue;
138 if (result < Smi::kMinValue) {
140 return Smi::kMinValue;
143 if (result > kMaxInt) {
147 if (result < kMinInt) {
152 return static_cast<int32_t>(result);
156 static int32_t AddWithoutOverflow(Representation r,
160 int64_t result = static_cast<int64_t>(a) + static_cast<int64_t>(b);
161 return ConvertAndSetOverflow(r, result, overflow);
165 static int32_t SubWithoutOverflow(Representation r,
169 int64_t result = static_cast<int64_t>(a) - static_cast<int64_t>(b);
170 return ConvertAndSetOverflow(r, result, overflow);
174 static int32_t MulWithoutOverflow(const Representation& r,
178 int64_t result = static_cast<int64_t>(a) * static_cast<int64_t>(b);
179 return ConvertAndSetOverflow(r, result, overflow);
183 int32_t Range::Mask() const {
184 if (lower_ == upper_) return lower_;
187 while (res < upper_) {
188 res = (res << 1) | 1;
196 void Range::AddConstant(int32_t value) {
197 if (value == 0) return;
198 bool may_overflow = false; // Overflow is ignored here.
199 Representation r = Representation::Integer32();
200 lower_ = AddWithoutOverflow(r, lower_, value, &may_overflow);
201 upper_ = AddWithoutOverflow(r, upper_, value, &may_overflow);
208 void Range::Intersect(Range* other) {
209 upper_ = Min(upper_, other->upper_);
210 lower_ = Max(lower_, other->lower_);
211 bool b = CanBeMinusZero() && other->CanBeMinusZero();
212 set_can_be_minus_zero(b);
216 void Range::Union(Range* other) {
217 upper_ = Max(upper_, other->upper_);
218 lower_ = Min(lower_, other->lower_);
219 bool b = CanBeMinusZero() || other->CanBeMinusZero();
220 set_can_be_minus_zero(b);
224 void Range::CombinedMax(Range* other) {
225 upper_ = Max(upper_, other->upper_);
226 lower_ = Max(lower_, other->lower_);
227 set_can_be_minus_zero(CanBeMinusZero() || other->CanBeMinusZero());
231 void Range::CombinedMin(Range* other) {
232 upper_ = Min(upper_, other->upper_);
233 lower_ = Min(lower_, other->lower_);
234 set_can_be_minus_zero(CanBeMinusZero() || other->CanBeMinusZero());
238 void Range::Sar(int32_t value) {
239 int32_t bits = value & 0x1F;
240 lower_ = lower_ >> bits;
241 upper_ = upper_ >> bits;
242 set_can_be_minus_zero(false);
246 void Range::Shl(int32_t value) {
247 int32_t bits = value & 0x1F;
248 int old_lower = lower_;
249 int old_upper = upper_;
250 lower_ = lower_ << bits;
251 upper_ = upper_ << bits;
252 if (old_lower != lower_ >> bits || old_upper != upper_ >> bits) {
256 set_can_be_minus_zero(false);
260 bool Range::AddAndCheckOverflow(const Representation& r, Range* other) {
261 bool may_overflow = false;
262 lower_ = AddWithoutOverflow(r, lower_, other->lower(), &may_overflow);
263 upper_ = AddWithoutOverflow(r, upper_, other->upper(), &may_overflow);
272 bool Range::SubAndCheckOverflow(const Representation& r, Range* other) {
273 bool may_overflow = false;
274 lower_ = SubWithoutOverflow(r, lower_, other->upper(), &may_overflow);
275 upper_ = SubWithoutOverflow(r, upper_, other->lower(), &may_overflow);
284 void Range::KeepOrder() {
285 if (lower_ > upper_) {
286 int32_t tmp = lower_;
294 void Range::Verify() const {
295 DCHECK(lower_ <= upper_);
300 bool Range::MulAndCheckOverflow(const Representation& r, Range* other) {
301 bool may_overflow = false;
302 int v1 = MulWithoutOverflow(r, lower_, other->lower(), &may_overflow);
303 int v2 = MulWithoutOverflow(r, lower_, other->upper(), &may_overflow);
304 int v3 = MulWithoutOverflow(r, upper_, other->lower(), &may_overflow);
305 int v4 = MulWithoutOverflow(r, upper_, other->upper(), &may_overflow);
306 lower_ = Min(Min(v1, v2), Min(v3, v4));
307 upper_ = Max(Max(v1, v2), Max(v3, v4));
315 bool HValue::IsDefinedAfter(HBasicBlock* other) const {
316 return block()->block_id() > other->block_id();
320 HUseListNode* HUseListNode::tail() {
321 // Skip and remove dead items in the use list.
322 while (tail_ != NULL && tail_->value()->CheckFlag(HValue::kIsDead)) {
323 tail_ = tail_->tail_;
329 bool HValue::CheckUsesForFlag(Flag f) const {
330 for (HUseIterator it(uses()); !it.Done(); it.Advance()) {
331 if (it.value()->IsSimulate()) continue;
332 if (!it.value()->CheckFlag(f)) return false;
338 bool HValue::CheckUsesForFlag(Flag f, HValue** value) const {
339 for (HUseIterator it(uses()); !it.Done(); it.Advance()) {
340 if (it.value()->IsSimulate()) continue;
341 if (!it.value()->CheckFlag(f)) {
350 bool HValue::HasAtLeastOneUseWithFlagAndNoneWithout(Flag f) const {
351 bool return_value = false;
352 for (HUseIterator it(uses()); !it.Done(); it.Advance()) {
353 if (it.value()->IsSimulate()) continue;
354 if (!it.value()->CheckFlag(f)) return false;
361 HUseIterator::HUseIterator(HUseListNode* head) : next_(head) {
366 void HUseIterator::Advance() {
368 if (current_ != NULL) {
369 next_ = current_->tail();
370 value_ = current_->value();
371 index_ = current_->index();
376 int HValue::UseCount() const {
378 for (HUseIterator it(uses()); !it.Done(); it.Advance()) ++count;
383 HUseListNode* HValue::RemoveUse(HValue* value, int index) {
384 HUseListNode* previous = NULL;
385 HUseListNode* current = use_list_;
386 while (current != NULL) {
387 if (current->value() == value && current->index() == index) {
388 if (previous == NULL) {
389 use_list_ = current->tail();
391 previous->set_tail(current->tail());
397 current = current->tail();
401 // Do not reuse use list nodes in debug mode, zap them.
402 if (current != NULL) {
405 HUseListNode(current->value(), current->index(), NULL);
414 bool HValue::Equals(HValue* other) {
415 if (other->opcode() != opcode()) return false;
416 if (!other->representation().Equals(representation())) return false;
417 if (!other->type_.Equals(type_)) return false;
418 if (other->flags() != flags()) return false;
419 if (OperandCount() != other->OperandCount()) return false;
420 for (int i = 0; i < OperandCount(); ++i) {
421 if (OperandAt(i)->id() != other->OperandAt(i)->id()) return false;
423 bool result = DataEquals(other);
424 DCHECK(!result || Hashcode() == other->Hashcode());
429 intptr_t HValue::Hashcode() {
430 intptr_t result = opcode();
431 int count = OperandCount();
432 for (int i = 0; i < count; ++i) {
433 result = result * 19 + OperandAt(i)->id() + (result >> 7);
439 const char* HValue::Mnemonic() const {
441 #define MAKE_CASE(type) case k##type: return #type;
442 HYDROGEN_CONCRETE_INSTRUCTION_LIST(MAKE_CASE)
444 case kPhi: return "Phi";
450 bool HValue::CanReplaceWithDummyUses() {
451 return FLAG_unreachable_code_elimination &&
452 !(block()->IsReachable() ||
454 IsControlInstruction() ||
455 IsArgumentsObject() ||
456 IsCapturedObject() ||
463 bool HValue::IsInteger32Constant() {
464 return IsConstant() && HConstant::cast(this)->HasInteger32Value();
468 int32_t HValue::GetInteger32Constant() {
469 return HConstant::cast(this)->Integer32Value();
473 bool HValue::EqualsInteger32Constant(int32_t value) {
474 return IsInteger32Constant() && GetInteger32Constant() == value;
478 void HValue::SetOperandAt(int index, HValue* value) {
479 RegisterUse(index, value);
480 InternalSetOperandAt(index, value);
484 void HValue::DeleteAndReplaceWith(HValue* other) {
485 // We replace all uses first, so Delete can assert that there are none.
486 if (other != NULL) ReplaceAllUsesWith(other);
492 void HValue::ReplaceAllUsesWith(HValue* other) {
493 while (use_list_ != NULL) {
494 HUseListNode* list_node = use_list_;
495 HValue* value = list_node->value();
496 DCHECK(!value->block()->IsStartBlock());
497 value->InternalSetOperandAt(list_node->index(), other);
498 use_list_ = list_node->tail();
499 list_node->set_tail(other->use_list_);
500 other->use_list_ = list_node;
505 void HValue::Kill() {
506 // Instead of going through the entire use list of each operand, we only
507 // check the first item in each use list and rely on the tail() method to
508 // skip dead items, removing them lazily next time we traverse the list.
510 for (int i = 0; i < OperandCount(); ++i) {
511 HValue* operand = OperandAt(i);
512 if (operand == NULL) continue;
513 HUseListNode* first = operand->use_list_;
514 if (first != NULL && first->value()->CheckFlag(kIsDead)) {
515 operand->use_list_ = first->tail();
521 void HValue::SetBlock(HBasicBlock* block) {
522 DCHECK(block_ == NULL || block == NULL);
524 if (id_ == kNoNumber && block != NULL) {
525 id_ = block->graph()->GetNextValueID(this);
530 OStream& operator<<(OStream& os, const HValue& v) { return v.PrintTo(os); }
533 OStream& operator<<(OStream& os, const TypeOf& t) {
534 if (t.value->representation().IsTagged() &&
535 !t.value->type().Equals(HType::Tagged()))
537 return os << " type:" << t.value->type();
541 OStream& operator<<(OStream& os, const ChangesOf& c) {
542 GVNFlagSet changes_flags = c.value->ChangesFlags();
543 if (changes_flags.IsEmpty()) return os;
545 if (changes_flags == c.value->AllSideEffectsFlagSet()) {
548 bool add_comma = false;
549 #define PRINT_DO(Type) \
550 if (changes_flags.Contains(k##Type)) { \
551 if (add_comma) os << ","; \
555 GVN_TRACKED_FLAG_LIST(PRINT_DO);
556 GVN_UNTRACKED_FLAG_LIST(PRINT_DO);
563 bool HValue::HasMonomorphicJSObjectType() {
564 return !GetMonomorphicJSObjectMap().is_null();
568 bool HValue::UpdateInferredType() {
569 HType type = CalculateInferredType();
570 bool result = (!type.Equals(type_));
576 void HValue::RegisterUse(int index, HValue* new_value) {
577 HValue* old_value = OperandAt(index);
578 if (old_value == new_value) return;
580 HUseListNode* removed = NULL;
581 if (old_value != NULL) {
582 removed = old_value->RemoveUse(this, index);
585 if (new_value != NULL) {
586 if (removed == NULL) {
587 new_value->use_list_ = new(new_value->block()->zone()) HUseListNode(
588 this, index, new_value->use_list_);
590 removed->set_tail(new_value->use_list_);
591 new_value->use_list_ = removed;
597 void HValue::AddNewRange(Range* r, Zone* zone) {
598 if (!HasRange()) ComputeInitialRange(zone);
599 if (!HasRange()) range_ = new(zone) Range();
601 r->StackUpon(range_);
606 void HValue::RemoveLastAddedRange() {
608 DCHECK(range_->next() != NULL);
609 range_ = range_->next();
613 void HValue::ComputeInitialRange(Zone* zone) {
615 range_ = InferRange(zone);
620 OStream& operator<<(OStream& os, const HSourcePosition& p) {
623 } else if (FLAG_hydrogen_track_positions) {
624 return os << "<" << p.inlining_id() << ":" << p.position() << ">";
626 return os << "<0:" << p.raw() << ">";
631 OStream& HInstruction::PrintTo(OStream& os) const { // NOLINT
632 os << Mnemonic() << " ";
633 PrintDataTo(os) << ChangesOf(this) << TypeOf(this);
634 if (CheckFlag(HValue::kHasNoObservableSideEffects)) os << " [noOSE]";
635 if (CheckFlag(HValue::kIsDead)) os << " [dead]";
640 OStream& HInstruction::PrintDataTo(OStream& os) const { // NOLINT
641 for (int i = 0; i < OperandCount(); ++i) {
642 if (i > 0) os << " ";
643 os << NameOf(OperandAt(i));
649 void HInstruction::Unlink() {
651 DCHECK(!IsControlInstruction()); // Must never move control instructions.
652 DCHECK(!IsBlockEntry()); // Doesn't make sense to delete these.
653 DCHECK(previous_ != NULL);
654 previous_->next_ = next_;
656 DCHECK(block()->last() == this);
657 block()->set_last(previous_);
659 next_->previous_ = previous_;
665 void HInstruction::InsertBefore(HInstruction* next) {
667 DCHECK(!next->IsBlockEntry());
668 DCHECK(!IsControlInstruction());
669 DCHECK(!next->block()->IsStartBlock());
670 DCHECK(next->previous_ != NULL);
671 HInstruction* prev = next->previous();
673 next->previous_ = this;
676 SetBlock(next->block());
677 if (!has_position() && next->has_position()) {
678 set_position(next->position());
683 void HInstruction::InsertAfter(HInstruction* previous) {
685 DCHECK(!previous->IsControlInstruction());
686 DCHECK(!IsControlInstruction() || previous->next_ == NULL);
687 HBasicBlock* block = previous->block();
688 // Never insert anything except constants into the start block after finishing
690 if (block->IsStartBlock() && block->IsFinished() && !IsConstant()) {
691 DCHECK(block->end()->SecondSuccessor() == NULL);
692 InsertAfter(block->end()->FirstSuccessor()->first());
696 // If we're inserting after an instruction with side-effects that is
697 // followed by a simulate instruction, we need to insert after the
698 // simulate instruction instead.
699 HInstruction* next = previous->next_;
700 if (previous->HasObservableSideEffects() && next != NULL) {
701 DCHECK(next->IsSimulate());
703 next = previous->next_;
706 previous_ = previous;
709 previous->next_ = this;
710 if (next != NULL) next->previous_ = this;
711 if (block->last() == previous) {
712 block->set_last(this);
714 if (!has_position() && previous->has_position()) {
715 set_position(previous->position());
720 bool HInstruction::Dominates(HInstruction* other) {
721 if (block() != other->block()) {
722 return block()->Dominates(other->block());
724 // Both instructions are in the same basic block. This instruction
725 // should precede the other one in order to dominate it.
726 for (HInstruction* instr = next(); instr != NULL; instr = instr->next()) {
727 if (instr == other) {
736 void HInstruction::Verify() {
737 // Verify that input operands are defined before use.
738 HBasicBlock* cur_block = block();
739 for (int i = 0; i < OperandCount(); ++i) {
740 HValue* other_operand = OperandAt(i);
741 if (other_operand == NULL) continue;
742 HBasicBlock* other_block = other_operand->block();
743 if (cur_block == other_block) {
744 if (!other_operand->IsPhi()) {
745 HInstruction* cur = this->previous();
746 while (cur != NULL) {
747 if (cur == other_operand) break;
748 cur = cur->previous();
750 // Must reach other operand in the same block!
751 DCHECK(cur == other_operand);
754 // If the following assert fires, you may have forgotten an
756 DCHECK(other_block->Dominates(cur_block));
760 // Verify that instructions that may have side-effects are followed
761 // by a simulate instruction.
762 if (HasObservableSideEffects() && !IsOsrEntry()) {
763 DCHECK(next()->IsSimulate());
766 // Verify that instructions that can be eliminated by GVN have overridden
767 // HValue::DataEquals. The default implementation is UNREACHABLE. We
768 // don't actually care whether DataEquals returns true or false here.
769 if (CheckFlag(kUseGVN)) DataEquals(this);
771 // Verify that all uses are in the graph.
772 for (HUseIterator use = uses(); !use.Done(); use.Advance()) {
773 if (use.value()->IsInstruction()) {
774 DCHECK(HInstruction::cast(use.value())->IsLinked());
781 bool HInstruction::CanDeoptimize() {
782 // TODO(titzer): make this a virtual method?
784 case HValue::kAbnormalExit:
785 case HValue::kAccessArgumentsAt:
786 case HValue::kAllocate:
787 case HValue::kArgumentsElements:
788 case HValue::kArgumentsLength:
789 case HValue::kArgumentsObject:
790 case HValue::kBlockEntry:
791 case HValue::kBoundsCheckBaseIndexInformation:
792 case HValue::kCallFunction:
793 case HValue::kCallNew:
794 case HValue::kCallNewArray:
795 case HValue::kCallStub:
796 case HValue::kCallWithDescriptor:
797 case HValue::kCapturedObject:
798 case HValue::kClassOfTestAndBranch:
799 case HValue::kCompareGeneric:
800 case HValue::kCompareHoleAndBranch:
801 case HValue::kCompareMap:
802 case HValue::kCompareMinusZeroAndBranch:
803 case HValue::kCompareNumericAndBranch:
804 case HValue::kCompareObjectEqAndBranch:
805 case HValue::kConstant:
806 case HValue::kConstructDouble:
807 case HValue::kContext:
808 case HValue::kDebugBreak:
809 case HValue::kDeclareGlobals:
810 case HValue::kDoubleBits:
811 case HValue::kDummyUse:
812 case HValue::kEnterInlined:
813 case HValue::kEnvironmentMarker:
814 case HValue::kForceRepresentation:
815 case HValue::kGetCachedArrayIndex:
817 case HValue::kHasCachedArrayIndexAndBranch:
818 case HValue::kHasInstanceTypeAndBranch:
819 case HValue::kInnerAllocatedObject:
820 case HValue::kInstanceOf:
821 case HValue::kInstanceOfKnownGlobal:
822 case HValue::kIsConstructCallAndBranch:
823 case HValue::kIsObjectAndBranch:
824 case HValue::kIsSmiAndBranch:
825 case HValue::kIsStringAndBranch:
826 case HValue::kIsUndetectableAndBranch:
827 case HValue::kLeaveInlined:
828 case HValue::kLoadFieldByIndex:
829 case HValue::kLoadGlobalGeneric:
830 case HValue::kLoadNamedField:
831 case HValue::kLoadNamedGeneric:
832 case HValue::kLoadRoot:
833 case HValue::kMapEnumLength:
834 case HValue::kMathMinMax:
835 case HValue::kParameter:
837 case HValue::kPushArguments:
838 case HValue::kRegExpLiteral:
839 case HValue::kReturn:
840 case HValue::kSeqStringGetChar:
841 case HValue::kStoreCodeEntry:
842 case HValue::kStoreFrameContext:
843 case HValue::kStoreKeyed:
844 case HValue::kStoreNamedField:
845 case HValue::kStoreNamedGeneric:
846 case HValue::kStringCharCodeAt:
847 case HValue::kStringCharFromCode:
848 case HValue::kThisFunction:
849 case HValue::kTypeofIsAndBranch:
850 case HValue::kUnknownOSRValue:
851 case HValue::kUseConst:
855 case HValue::kAllocateBlockContext:
856 case HValue::kApplyArguments:
857 case HValue::kBitwise:
858 case HValue::kBoundsCheck:
859 case HValue::kBranch:
860 case HValue::kCallJSFunction:
861 case HValue::kCallRuntime:
862 case HValue::kChange:
863 case HValue::kCheckHeapObject:
864 case HValue::kCheckInstanceType:
865 case HValue::kCheckMapValue:
866 case HValue::kCheckMaps:
867 case HValue::kCheckSmi:
868 case HValue::kCheckValue:
869 case HValue::kClampToUint8:
870 case HValue::kDateField:
871 case HValue::kDeoptimize:
873 case HValue::kForInCacheArray:
874 case HValue::kForInPrepareMap:
875 case HValue::kFunctionLiteral:
876 case HValue::kInvokeFunction:
877 case HValue::kLoadContextSlot:
878 case HValue::kLoadFunctionPrototype:
879 case HValue::kLoadGlobalCell:
880 case HValue::kLoadKeyed:
881 case HValue::kLoadKeyedGeneric:
882 case HValue::kMathFloorOfDiv:
885 case HValue::kOsrEntry:
889 case HValue::kSeqStringSetChar:
892 case HValue::kSimulate:
893 case HValue::kStackCheck:
894 case HValue::kStoreContextSlot:
895 case HValue::kStoreGlobalCell:
896 case HValue::kStoreKeyedGeneric:
897 case HValue::kStringAdd:
898 case HValue::kStringCompareAndBranch:
900 case HValue::kToFastProperties:
901 case HValue::kTransitionElementsKind:
902 case HValue::kTrapAllocationMemento:
903 case HValue::kTypeof:
904 case HValue::kUnaryMathOperation:
905 case HValue::kWrapReceiver:
913 OStream& operator<<(OStream& os, const NameOf& v) {
914 return os << v.value->representation().Mnemonic() << v.value->id();
917 OStream& HDummyUse::PrintDataTo(OStream& os) const { // NOLINT
918 return os << NameOf(value());
922 OStream& HEnvironmentMarker::PrintDataTo(OStream& os) const { // NOLINT
923 return os << (kind() == BIND ? "bind" : "lookup") << " var[" << index()
928 OStream& HUnaryCall::PrintDataTo(OStream& os) const { // NOLINT
929 return os << NameOf(value()) << " #" << argument_count();
933 OStream& HCallJSFunction::PrintDataTo(OStream& os) const { // NOLINT
934 return os << NameOf(function()) << " #" << argument_count();
938 HCallJSFunction* HCallJSFunction::New(
943 bool pass_argument_count) {
944 bool has_stack_check = false;
945 if (function->IsConstant()) {
946 HConstant* fun_const = HConstant::cast(function);
947 Handle<JSFunction> jsfun =
948 Handle<JSFunction>::cast(fun_const->handle(zone->isolate()));
949 has_stack_check = !jsfun.is_null() &&
950 (jsfun->code()->kind() == Code::FUNCTION ||
951 jsfun->code()->kind() == Code::OPTIMIZED_FUNCTION);
954 return new(zone) HCallJSFunction(
955 function, argument_count, pass_argument_count,
960 OStream& HBinaryCall::PrintDataTo(OStream& os) const { // NOLINT
961 return os << NameOf(first()) << " " << NameOf(second()) << " #"
966 void HBoundsCheck::ApplyIndexChange() {
967 if (skip_check()) return;
969 DecompositionResult decomposition;
970 bool index_is_decomposable = index()->TryDecompose(&decomposition);
971 if (index_is_decomposable) {
972 DCHECK(decomposition.base() == base());
973 if (decomposition.offset() == offset() &&
974 decomposition.scale() == scale()) return;
979 ReplaceAllUsesWith(index());
981 HValue* current_index = decomposition.base();
982 int actual_offset = decomposition.offset() + offset();
983 int actual_scale = decomposition.scale() + scale();
985 Zone* zone = block()->graph()->zone();
986 HValue* context = block()->graph()->GetInvalidContext();
987 if (actual_offset != 0) {
988 HConstant* add_offset = HConstant::New(zone, context, actual_offset);
989 add_offset->InsertBefore(this);
990 HInstruction* add = HAdd::New(zone, context,
991 current_index, add_offset);
992 add->InsertBefore(this);
993 add->AssumeRepresentation(index()->representation());
994 add->ClearFlag(kCanOverflow);
998 if (actual_scale != 0) {
999 HConstant* sar_scale = HConstant::New(zone, context, actual_scale);
1000 sar_scale->InsertBefore(this);
1001 HInstruction* sar = HSar::New(zone, context,
1002 current_index, sar_scale);
1003 sar->InsertBefore(this);
1004 sar->AssumeRepresentation(index()->representation());
1005 current_index = sar;
1008 SetOperandAt(0, current_index);
1016 OStream& HBoundsCheck::PrintDataTo(OStream& os) const { // NOLINT
1017 os << NameOf(index()) << " " << NameOf(length());
1018 if (base() != NULL && (offset() != 0 || scale() != 0)) {
1020 if (base() != index()) {
1021 os << NameOf(index());
1025 os << " + " << offset() << ") >> " << scale() << ")";
1027 if (skip_check()) os << " [DISABLED]";
1032 void HBoundsCheck::InferRepresentation(HInferRepresentationPhase* h_infer) {
1033 DCHECK(CheckFlag(kFlexibleRepresentation));
1034 HValue* actual_index = index()->ActualValue();
1035 HValue* actual_length = length()->ActualValue();
1036 Representation index_rep = actual_index->representation();
1037 Representation length_rep = actual_length->representation();
1038 if (index_rep.IsTagged() && actual_index->type().IsSmi()) {
1039 index_rep = Representation::Smi();
1041 if (length_rep.IsTagged() && actual_length->type().IsSmi()) {
1042 length_rep = Representation::Smi();
1044 Representation r = index_rep.generalize(length_rep);
1045 if (r.is_more_general_than(Representation::Integer32())) {
1046 r = Representation::Integer32();
1048 UpdateRepresentation(r, h_infer, "boundscheck");
1052 Range* HBoundsCheck::InferRange(Zone* zone) {
1053 Representation r = representation();
1054 if (r.IsSmiOrInteger32() && length()->HasRange()) {
1055 int upper = length()->range()->upper() - (allow_equality() ? 0 : 1);
1058 Range* result = new(zone) Range(lower, upper);
1059 if (index()->HasRange()) {
1060 result->Intersect(index()->range());
1063 // In case of Smi representation, clamp result to Smi::kMaxValue.
1064 if (r.IsSmi()) result->ClampToSmi();
1067 return HValue::InferRange(zone);
1071 OStream& HBoundsCheckBaseIndexInformation::PrintDataTo(
1072 OStream& os) const { // NOLINT
1073 // TODO(svenpanne) This 2nd base_index() looks wrong...
1074 return os << "base: " << NameOf(base_index())
1075 << ", check: " << NameOf(base_index());
1079 OStream& HCallWithDescriptor::PrintDataTo(OStream& os) const { // NOLINT
1080 for (int i = 0; i < OperandCount(); i++) {
1081 os << NameOf(OperandAt(i)) << " ";
1083 return os << "#" << argument_count();
1087 OStream& HCallNewArray::PrintDataTo(OStream& os) const { // NOLINT
1088 os << ElementsKindToString(elements_kind()) << " ";
1089 return HBinaryCall::PrintDataTo(os);
1093 OStream& HCallRuntime::PrintDataTo(OStream& os) const { // NOLINT
1094 os << name()->ToCString().get() << " ";
1095 if (save_doubles() == kSaveFPRegs) os << "[save doubles] ";
1096 return os << "#" << argument_count();
1100 OStream& HClassOfTestAndBranch::PrintDataTo(OStream& os) const { // NOLINT
1101 return os << "class_of_test(" << NameOf(value()) << ", \""
1102 << class_name()->ToCString().get() << "\")";
1106 OStream& HWrapReceiver::PrintDataTo(OStream& os) const { // NOLINT
1107 return os << NameOf(receiver()) << " " << NameOf(function());
1111 OStream& HAccessArgumentsAt::PrintDataTo(OStream& os) const { // NOLINT
1112 return os << NameOf(arguments()) << "[" << NameOf(index()) << "], length "
1113 << NameOf(length());
1117 OStream& HAllocateBlockContext::PrintDataTo(OStream& os) const { // NOLINT
1118 return os << NameOf(context()) << " " << NameOf(function());
1122 OStream& HControlInstruction::PrintDataTo(OStream& os) const { // NOLINT
1124 bool first_block = true;
1125 for (HSuccessorIterator it(this); !it.Done(); it.Advance()) {
1126 if (!first_block) os << ", ";
1127 os << *it.Current();
1128 first_block = false;
1134 OStream& HUnaryControlInstruction::PrintDataTo(OStream& os) const { // NOLINT
1135 os << NameOf(value());
1136 return HControlInstruction::PrintDataTo(os);
1140 OStream& HReturn::PrintDataTo(OStream& os) const { // NOLINT
1141 return os << NameOf(value()) << " (pop " << NameOf(parameter_count())
1146 Representation HBranch::observed_input_representation(int index) {
1147 static const ToBooleanStub::Types tagged_types(
1148 ToBooleanStub::NULL_TYPE |
1149 ToBooleanStub::SPEC_OBJECT |
1150 ToBooleanStub::STRING |
1151 ToBooleanStub::SYMBOL);
1152 if (expected_input_types_.ContainsAnyOf(tagged_types)) {
1153 return Representation::Tagged();
1155 if (expected_input_types_.Contains(ToBooleanStub::UNDEFINED)) {
1156 if (expected_input_types_.Contains(ToBooleanStub::HEAP_NUMBER)) {
1157 return Representation::Double();
1159 return Representation::Tagged();
1161 if (expected_input_types_.Contains(ToBooleanStub::HEAP_NUMBER)) {
1162 return Representation::Double();
1164 if (expected_input_types_.Contains(ToBooleanStub::SMI)) {
1165 return Representation::Smi();
1167 return Representation::None();
1171 bool HBranch::KnownSuccessorBlock(HBasicBlock** block) {
1172 HValue* value = this->value();
1173 if (value->EmitAtUses()) {
1174 DCHECK(value->IsConstant());
1175 DCHECK(!value->representation().IsDouble());
1176 *block = HConstant::cast(value)->BooleanValue()
1178 : SecondSuccessor();
1186 OStream& HBranch::PrintDataTo(OStream& os) const { // NOLINT
1187 return HUnaryControlInstruction::PrintDataTo(os) << " "
1188 << expected_input_types();
1192 OStream& HCompareMap::PrintDataTo(OStream& os) const { // NOLINT
1193 os << NameOf(value()) << " (" << *map().handle() << ")";
1194 HControlInstruction::PrintDataTo(os);
1195 if (known_successor_index() == 0) {
1197 } else if (known_successor_index() == 1) {
1204 const char* HUnaryMathOperation::OpName() const {
1231 Range* HUnaryMathOperation::InferRange(Zone* zone) {
1232 Representation r = representation();
1233 if (op() == kMathClz32) return new(zone) Range(0, 32);
1234 if (r.IsSmiOrInteger32() && value()->HasRange()) {
1235 if (op() == kMathAbs) {
1236 int upper = value()->range()->upper();
1237 int lower = value()->range()->lower();
1238 bool spans_zero = value()->range()->CanBeZero();
1239 // Math.abs(kMinInt) overflows its representation, on which the
1240 // instruction deopts. Hence clamp it to kMaxInt.
1241 int abs_upper = upper == kMinInt ? kMaxInt : abs(upper);
1242 int abs_lower = lower == kMinInt ? kMaxInt : abs(lower);
1244 new(zone) Range(spans_zero ? 0 : Min(abs_lower, abs_upper),
1245 Max(abs_lower, abs_upper));
1246 // In case of Smi representation, clamp Math.abs(Smi::kMinValue) to
1248 if (r.IsSmi()) result->ClampToSmi();
1252 return HValue::InferRange(zone);
1256 OStream& HUnaryMathOperation::PrintDataTo(OStream& os) const { // NOLINT
1257 return os << OpName() << " " << NameOf(value());
1261 OStream& HUnaryOperation::PrintDataTo(OStream& os) const { // NOLINT
1262 return os << NameOf(value());
1266 OStream& HHasInstanceTypeAndBranch::PrintDataTo(OStream& os) const { // NOLINT
1267 os << NameOf(value());
1269 case FIRST_JS_RECEIVER_TYPE:
1270 if (to_ == LAST_TYPE) os << " spec_object";
1272 case JS_REGEXP_TYPE:
1273 if (to_ == JS_REGEXP_TYPE) os << " reg_exp";
1276 if (to_ == JS_ARRAY_TYPE) os << " array";
1278 case JS_FUNCTION_TYPE:
1279 if (to_ == JS_FUNCTION_TYPE) os << " function";
1288 OStream& HTypeofIsAndBranch::PrintDataTo(OStream& os) const { // NOLINT
1289 os << NameOf(value()) << " == " << type_literal()->ToCString().get();
1290 return HControlInstruction::PrintDataTo(os);
1294 static String* TypeOfString(HConstant* constant, Isolate* isolate) {
1295 Heap* heap = isolate->heap();
1296 if (constant->HasNumberValue()) return heap->number_string();
1297 if (constant->IsUndetectable()) return heap->undefined_string();
1298 if (constant->HasStringValue()) return heap->string_string();
1299 switch (constant->GetInstanceType()) {
1300 case ODDBALL_TYPE: {
1301 Unique<Object> unique = constant->GetUnique();
1302 if (unique.IsKnownGlobal(heap->true_value()) ||
1303 unique.IsKnownGlobal(heap->false_value())) {
1304 return heap->boolean_string();
1306 if (unique.IsKnownGlobal(heap->null_value())) {
1307 return heap->object_string();
1309 DCHECK(unique.IsKnownGlobal(heap->undefined_value()));
1310 return heap->undefined_string();
1313 return heap->symbol_string();
1314 case JS_FUNCTION_TYPE:
1315 case JS_FUNCTION_PROXY_TYPE:
1316 return heap->function_string();
1318 return heap->object_string();
1323 bool 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();
1330 } else if (value()->representation().IsSpecialization()) {
1332 type_literal_.IsKnownGlobal(isolate()->heap()->number_string());
1333 *block = number_type ? FirstSuccessor() : SecondSuccessor();
1341 OStream& HCheckMapValue::PrintDataTo(OStream& os) const { // NOLINT
1342 return os << NameOf(value()) << " " << NameOf(map());
1346 HValue* 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);
1357 OStream& HForInPrepareMap::PrintDataTo(OStream& os) const { // NOLINT
1358 return os << NameOf(enumerable());
1362 OStream& HForInCacheArray::PrintDataTo(OStream& os) const { // NOLINT
1363 return os << NameOf(enumerable()) << " " << NameOf(map()) << "[" << idx_
1368 OStream& HLoadFieldByIndex::PrintDataTo(OStream& os) const { // NOLINT
1369 return os << NameOf(object()) << " " << NameOf(index());
1373 static bool MatchLeftIsOnes(HValue* l, HValue* r, HValue** negated) {
1374 if (!l->EqualsInteger32Constant(~0)) return false;
1380 static bool MatchNegationViaXor(HValue* instr, HValue** negated) {
1381 if (!instr->IsBitwise()) return false;
1382 HBitwise* b = HBitwise::cast(instr);
1383 return (b->op() == Token::BIT_XOR) &&
1384 (MatchLeftIsOnes(b->left(), b->right(), negated) ||
1385 MatchLeftIsOnes(b->right(), b->left(), negated));
1389 static bool MatchDoubleNegation(HValue* instr, HValue** arg) {
1391 return MatchNegationViaXor(instr, &negated) &&
1392 MatchNegationViaXor(negated, arg);
1396 HValue* HBitwise::Canonicalize() {
1397 if (!representation().IsSmiOrInteger32()) return this;
1398 // If x is an int32, then x & -1 == x, x | 0 == x and x ^ 0 == x.
1399 int32_t nop_constant = (op() == Token::BIT_AND) ? -1 : 0;
1400 if (left()->EqualsInteger32Constant(nop_constant) &&
1401 !right()->CheckFlag(kUint32)) {
1404 if (right()->EqualsInteger32Constant(nop_constant) &&
1405 !left()->CheckFlag(kUint32)) {
1408 // Optimize double negation, a common pattern used for ToInt32(x).
1410 if (MatchDoubleNegation(this, &arg) && !arg->CheckFlag(kUint32)) {
1417 Representation HAdd::RepresentationFromInputs() {
1418 Representation left_rep = left()->representation();
1419 if (left_rep.IsExternal()) {
1420 return Representation::External();
1422 return HArithmeticBinaryOperation::RepresentationFromInputs();
1426 Representation HAdd::RequiredInputRepresentation(int index) {
1428 Representation left_rep = left()->representation();
1429 if (left_rep.IsExternal()) {
1430 return Representation::Integer32();
1433 return HArithmeticBinaryOperation::RequiredInputRepresentation(index);
1437 static bool IsIdentityOperation(HValue* arg1, HValue* arg2, int32_t identity) {
1438 return arg1->representation().IsSpecialization() &&
1439 arg2->EqualsInteger32Constant(identity);
1443 HValue* HAdd::Canonicalize() {
1444 // Adding 0 is an identity operation except in case of -0: -0 + 0 = +0
1445 if (IsIdentityOperation(left(), right(), 0) &&
1446 !left()->representation().IsDouble()) { // Left could be -0.
1449 if (IsIdentityOperation(right(), left(), 0) &&
1450 !left()->representation().IsDouble()) { // Right could be -0.
1457 HValue* HSub::Canonicalize() {
1458 if (IsIdentityOperation(left(), right(), 0)) return left();
1463 HValue* HMul::Canonicalize() {
1464 if (IsIdentityOperation(left(), right(), 1)) return left();
1465 if (IsIdentityOperation(right(), left(), 1)) return right();
1470 bool HMul::MulMinusOne() {
1471 if (left()->EqualsInteger32Constant(-1) ||
1472 right()->EqualsInteger32Constant(-1)) {
1480 HValue* HMod::Canonicalize() {
1485 HValue* HDiv::Canonicalize() {
1486 if (IsIdentityOperation(left(), right(), 1)) return left();
1491 HValue* HChange::Canonicalize() {
1492 return (from().Equals(to())) ? value() : this;
1496 HValue* HWrapReceiver::Canonicalize() {
1497 if (HasNoUses()) return NULL;
1498 if (receiver()->type().IsJSObject()) {
1505 OStream& HTypeof::PrintDataTo(OStream& os) const { // NOLINT
1506 return os << NameOf(value());
1510 HInstruction* HForceRepresentation::New(Zone* zone, HValue* context,
1511 HValue* value, Representation representation) {
1512 if (FLAG_fold_constants && value->IsConstant()) {
1513 HConstant* c = HConstant::cast(value);
1514 if (c->HasNumberValue()) {
1515 double double_res = c->DoubleValue();
1516 if (representation.IsDouble()) {
1517 return HConstant::New(zone, context, double_res);
1519 } else if (representation.CanContainDouble(double_res)) {
1520 return HConstant::New(zone, context,
1521 static_cast<int32_t>(double_res),
1526 return new(zone) HForceRepresentation(value, representation);
1530 OStream& HForceRepresentation::PrintDataTo(OStream& os) const { // NOLINT
1531 return os << representation().Mnemonic() << " " << NameOf(value());
1535 OStream& HChange::PrintDataTo(OStream& os) const { // NOLINT
1536 HUnaryOperation::PrintDataTo(os);
1537 os << " " << from().Mnemonic() << " to " << to().Mnemonic();
1539 if (CanTruncateToSmi()) os << " truncating-smi";
1540 if (CanTruncateToInt32()) os << " truncating-int32";
1541 if (CheckFlag(kBailoutOnMinusZero)) os << " -0?";
1542 if (CheckFlag(kAllowUndefinedAsNaN)) os << " allow-undefined-as-nan";
1547 HValue* HUnaryMathOperation::Canonicalize() {
1548 if (op() == kMathRound || op() == kMathFloor) {
1549 HValue* val = value();
1550 if (val->IsChange()) val = HChange::cast(val)->value();
1551 if (val->representation().IsSmiOrInteger32()) {
1552 if (val->representation().Equals(representation())) return val;
1553 return Prepend(new(block()->zone()) HChange(
1554 val, representation(), false, false));
1557 if (op() == kMathFloor && value()->IsDiv() && value()->HasOneUse()) {
1558 HDiv* hdiv = HDiv::cast(value());
1560 HValue* left = hdiv->left();
1561 if (left->representation().IsInteger32()) {
1562 // A value with an integer representation does not need to be transformed.
1563 } else if (left->IsChange() && HChange::cast(left)->from().IsInteger32()) {
1564 // A change from an integer32 can be replaced by the integer32 value.
1565 left = HChange::cast(left)->value();
1566 } else if (hdiv->observed_input_representation(1).IsSmiOrInteger32()) {
1567 left = Prepend(new(block()->zone()) HChange(
1568 left, Representation::Integer32(), false, false));
1573 HValue* right = hdiv->right();
1574 if (right->IsInteger32Constant()) {
1575 right = Prepend(HConstant::cast(right)->CopyToRepresentation(
1576 Representation::Integer32(), right->block()->zone()));
1577 } else if (right->representation().IsInteger32()) {
1578 // A value with an integer representation does not need to be transformed.
1579 } else if (right->IsChange() &&
1580 HChange::cast(right)->from().IsInteger32()) {
1581 // A change from an integer32 can be replaced by the integer32 value.
1582 right = HChange::cast(right)->value();
1583 } else if (hdiv->observed_input_representation(2).IsSmiOrInteger32()) {
1584 right = Prepend(new(block()->zone()) HChange(
1585 right, Representation::Integer32(), false, false));
1590 return Prepend(HMathFloorOfDiv::New(
1591 block()->zone(), context(), left, right));
1597 HValue* HCheckInstanceType::Canonicalize() {
1598 if ((check_ == IS_SPEC_OBJECT && value()->type().IsJSObject()) ||
1599 (check_ == IS_JS_ARRAY && value()->type().IsJSArray()) ||
1600 (check_ == IS_STRING && value()->type().IsString())) {
1604 if (check_ == IS_INTERNALIZED_STRING && value()->IsConstant()) {
1605 if (HConstant::cast(value())->HasInternalizedStringValue()) {
1613 void HCheckInstanceType::GetCheckInterval(InstanceType* first,
1614 InstanceType* last) {
1615 DCHECK(is_interval_check());
1617 case IS_SPEC_OBJECT:
1618 *first = FIRST_SPEC_OBJECT_TYPE;
1619 *last = LAST_SPEC_OBJECT_TYPE;
1622 *first = *last = JS_ARRAY_TYPE;
1630 void HCheckInstanceType::GetCheckMaskAndTag(uint8_t* mask, uint8_t* tag) {
1631 DCHECK(!is_interval_check());
1634 *mask = kIsNotStringMask;
1637 case IS_INTERNALIZED_STRING:
1638 *mask = kIsNotStringMask | kIsNotInternalizedMask;
1639 *tag = kInternalizedTag;
1647 OStream& HCheckMaps::PrintDataTo(OStream& os) const { // NOLINT
1648 os << NameOf(value()) << " [" << *maps()->at(0).handle();
1649 for (int i = 1; i < maps()->size(); ++i) {
1650 os << "," << *maps()->at(i).handle();
1653 if (IsStabilityCheck()) os << "(stability-check)";
1658 HValue* HCheckMaps::Canonicalize() {
1659 if (!IsStabilityCheck() && maps_are_stable() && value()->IsConstant()) {
1660 HConstant* c_value = HConstant::cast(value());
1661 if (c_value->HasObjectMap()) {
1662 for (int i = 0; i < maps()->size(); ++i) {
1663 if (c_value->ObjectMap() == maps()->at(i)) {
1664 if (maps()->size() > 1) {
1665 set_maps(new(block()->graph()->zone()) UniqueSet<Map>(
1666 maps()->at(i), block()->graph()->zone()));
1668 MarkAsStabilityCheck();
1678 OStream& HCheckValue::PrintDataTo(OStream& os) const { // NOLINT
1679 return os << NameOf(value()) << " " << Brief(*object().handle());
1683 HValue* HCheckValue::Canonicalize() {
1684 return (value()->IsConstant() &&
1685 HConstant::cast(value())->EqualsUnique(object_)) ? NULL : this;
1689 const char* HCheckInstanceType::GetCheckName() const {
1691 case IS_SPEC_OBJECT: return "object";
1692 case IS_JS_ARRAY: return "array";
1693 case IS_STRING: return "string";
1694 case IS_INTERNALIZED_STRING: return "internalized_string";
1701 OStream& HCheckInstanceType::PrintDataTo(OStream& os) const { // NOLINT
1702 os << GetCheckName() << " ";
1703 return HUnaryOperation::PrintDataTo(os);
1707 OStream& HCallStub::PrintDataTo(OStream& os) const { // NOLINT
1708 os << CodeStub::MajorName(major_key_, false) << " ";
1709 return HUnaryCall::PrintDataTo(os);
1713 OStream& HUnknownOSRValue::PrintDataTo(OStream& os) const { // NOLINT
1714 const char* type = "expression";
1715 if (environment_->is_local_index(index_)) type = "local";
1716 if (environment_->is_special_index(index_)) type = "special";
1717 if (environment_->is_parameter_index(index_)) type = "parameter";
1718 return os << type << " @ " << index_;
1722 OStream& HInstanceOf::PrintDataTo(OStream& os) const { // NOLINT
1723 return os << NameOf(left()) << " " << NameOf(right()) << " "
1724 << NameOf(context());
1728 Range* HValue::InferRange(Zone* zone) {
1730 if (representation().IsSmi() || type().IsSmi()) {
1731 result = new(zone) Range(Smi::kMinValue, Smi::kMaxValue);
1732 result->set_can_be_minus_zero(false);
1734 result = new(zone) Range();
1735 result->set_can_be_minus_zero(!CheckFlag(kAllUsesTruncatingToInt32));
1736 // TODO(jkummerow): The range cannot be minus zero when the upper type
1737 // bound is Integer32.
1743 Range* HChange::InferRange(Zone* zone) {
1744 Range* input_range = value()->range();
1745 if (from().IsInteger32() && !value()->CheckFlag(HInstruction::kUint32) &&
1748 input_range != NULL &&
1749 input_range->IsInSmiRange()))) {
1750 set_type(HType::Smi());
1751 ClearChangesFlag(kNewSpacePromotion);
1753 if (to().IsSmiOrTagged() &&
1754 input_range != NULL &&
1755 input_range->IsInSmiRange() &&
1756 (!SmiValuesAre32Bits() ||
1757 !value()->CheckFlag(HValue::kUint32) ||
1758 input_range->upper() != kMaxInt)) {
1759 // The Range class can't express upper bounds in the (kMaxInt, kMaxUint32]
1760 // interval, so we treat kMaxInt as a sentinel for this entire interval.
1761 ClearFlag(kCanOverflow);
1763 Range* result = (input_range != NULL)
1764 ? input_range->Copy(zone)
1765 : HValue::InferRange(zone);
1766 result->set_can_be_minus_zero(!to().IsSmiOrInteger32() ||
1767 !(CheckFlag(kAllUsesTruncatingToInt32) ||
1768 CheckFlag(kAllUsesTruncatingToSmi)));
1769 if (to().IsSmi()) result->ClampToSmi();
1774 Range* HConstant::InferRange(Zone* zone) {
1775 if (has_int32_value_) {
1776 Range* result = new(zone) Range(int32_value_, int32_value_);
1777 result->set_can_be_minus_zero(false);
1780 return HValue::InferRange(zone);
1784 HSourcePosition HPhi::position() const {
1785 return block()->first()->position();
1789 Range* HPhi::InferRange(Zone* zone) {
1790 Representation r = representation();
1791 if (r.IsSmiOrInteger32()) {
1792 if (block()->IsLoopHeader()) {
1793 Range* range = r.IsSmi()
1794 ? new(zone) Range(Smi::kMinValue, Smi::kMaxValue)
1795 : new(zone) Range(kMinInt, kMaxInt);
1798 Range* range = OperandAt(0)->range()->Copy(zone);
1799 for (int i = 1; i < OperandCount(); ++i) {
1800 range->Union(OperandAt(i)->range());
1805 return HValue::InferRange(zone);
1810 Range* HAdd::InferRange(Zone* zone) {
1811 Representation r = representation();
1812 if (r.IsSmiOrInteger32()) {
1813 Range* a = left()->range();
1814 Range* b = right()->range();
1815 Range* res = a->Copy(zone);
1816 if (!res->AddAndCheckOverflow(r, b) ||
1817 (r.IsInteger32() && CheckFlag(kAllUsesTruncatingToInt32)) ||
1818 (r.IsSmi() && CheckFlag(kAllUsesTruncatingToSmi))) {
1819 ClearFlag(kCanOverflow);
1821 res->set_can_be_minus_zero(!CheckFlag(kAllUsesTruncatingToSmi) &&
1822 !CheckFlag(kAllUsesTruncatingToInt32) &&
1823 a->CanBeMinusZero() && b->CanBeMinusZero());
1826 return HValue::InferRange(zone);
1831 Range* HSub::InferRange(Zone* zone) {
1832 Representation r = representation();
1833 if (r.IsSmiOrInteger32()) {
1834 Range* a = left()->range();
1835 Range* b = right()->range();
1836 Range* res = a->Copy(zone);
1837 if (!res->SubAndCheckOverflow(r, b) ||
1838 (r.IsInteger32() && CheckFlag(kAllUsesTruncatingToInt32)) ||
1839 (r.IsSmi() && CheckFlag(kAllUsesTruncatingToSmi))) {
1840 ClearFlag(kCanOverflow);
1842 res->set_can_be_minus_zero(!CheckFlag(kAllUsesTruncatingToSmi) &&
1843 !CheckFlag(kAllUsesTruncatingToInt32) &&
1844 a->CanBeMinusZero() && b->CanBeZero());
1847 return HValue::InferRange(zone);
1852 Range* HMul::InferRange(Zone* zone) {
1853 Representation r = representation();
1854 if (r.IsSmiOrInteger32()) {
1855 Range* a = left()->range();
1856 Range* b = right()->range();
1857 Range* res = a->Copy(zone);
1858 if (!res->MulAndCheckOverflow(r, b) ||
1859 (((r.IsInteger32() && CheckFlag(kAllUsesTruncatingToInt32)) ||
1860 (r.IsSmi() && CheckFlag(kAllUsesTruncatingToSmi))) &&
1862 // Truncated int multiplication is too precise and therefore not the
1863 // same as converting to Double and back.
1864 // Handle truncated integer multiplication by -1 special.
1865 ClearFlag(kCanOverflow);
1867 res->set_can_be_minus_zero(!CheckFlag(kAllUsesTruncatingToSmi) &&
1868 !CheckFlag(kAllUsesTruncatingToInt32) &&
1869 ((a->CanBeZero() && b->CanBeNegative()) ||
1870 (a->CanBeNegative() && b->CanBeZero())));
1873 return HValue::InferRange(zone);
1878 Range* HDiv::InferRange(Zone* zone) {
1879 if (representation().IsInteger32()) {
1880 Range* a = left()->range();
1881 Range* b = right()->range();
1882 Range* result = new(zone) Range();
1883 result->set_can_be_minus_zero(!CheckFlag(kAllUsesTruncatingToInt32) &&
1884 (a->CanBeMinusZero() ||
1885 (a->CanBeZero() && b->CanBeNegative())));
1886 if (!a->Includes(kMinInt) || !b->Includes(-1)) {
1887 ClearFlag(kCanOverflow);
1890 if (!b->CanBeZero()) {
1891 ClearFlag(kCanBeDivByZero);
1895 return HValue::InferRange(zone);
1900 Range* HMathFloorOfDiv::InferRange(Zone* zone) {
1901 if (representation().IsInteger32()) {
1902 Range* a = left()->range();
1903 Range* b = right()->range();
1904 Range* result = new(zone) Range();
1905 result->set_can_be_minus_zero(!CheckFlag(kAllUsesTruncatingToInt32) &&
1906 (a->CanBeMinusZero() ||
1907 (a->CanBeZero() && b->CanBeNegative())));
1908 if (!a->Includes(kMinInt)) {
1909 ClearFlag(kLeftCanBeMinInt);
1912 if (!a->CanBeNegative()) {
1913 ClearFlag(HValue::kLeftCanBeNegative);
1916 if (!a->CanBePositive()) {
1917 ClearFlag(HValue::kLeftCanBePositive);
1920 if (!a->Includes(kMinInt) || !b->Includes(-1)) {
1921 ClearFlag(kCanOverflow);
1924 if (!b->CanBeZero()) {
1925 ClearFlag(kCanBeDivByZero);
1929 return HValue::InferRange(zone);
1934 // Returns the absolute value of its argument minus one, avoiding undefined
1935 // behavior at kMinInt.
1936 static int32_t AbsMinus1(int32_t a) { return a < 0 ? -(a + 1) : (a - 1); }
1939 Range* HMod::InferRange(Zone* zone) {
1940 if (representation().IsInteger32()) {
1941 Range* a = left()->range();
1942 Range* b = right()->range();
1944 // The magnitude of the modulus is bounded by the right operand.
1945 int32_t positive_bound = Max(AbsMinus1(b->lower()), AbsMinus1(b->upper()));
1947 // The result of the modulo operation has the sign of its left operand.
1948 bool left_can_be_negative = a->CanBeMinusZero() || a->CanBeNegative();
1949 Range* result = new(zone) Range(left_can_be_negative ? -positive_bound : 0,
1950 a->CanBePositive() ? positive_bound : 0);
1952 result->set_can_be_minus_zero(!CheckFlag(kAllUsesTruncatingToInt32) &&
1953 left_can_be_negative);
1955 if (!a->CanBeNegative()) {
1956 ClearFlag(HValue::kLeftCanBeNegative);
1959 if (!a->Includes(kMinInt) || !b->Includes(-1)) {
1960 ClearFlag(HValue::kCanOverflow);
1963 if (!b->CanBeZero()) {
1964 ClearFlag(HValue::kCanBeDivByZero);
1968 return HValue::InferRange(zone);
1973 InductionVariableData* InductionVariableData::ExaminePhi(HPhi* phi) {
1974 if (phi->block()->loop_information() == NULL) return NULL;
1975 if (phi->OperandCount() != 2) return NULL;
1976 int32_t candidate_increment;
1978 candidate_increment = ComputeIncrement(phi, phi->OperandAt(0));
1979 if (candidate_increment != 0) {
1980 return new(phi->block()->graph()->zone())
1981 InductionVariableData(phi, phi->OperandAt(1), candidate_increment);
1984 candidate_increment = ComputeIncrement(phi, phi->OperandAt(1));
1985 if (candidate_increment != 0) {
1986 return new(phi->block()->graph()->zone())
1987 InductionVariableData(phi, phi->OperandAt(0), candidate_increment);
1995 * This function tries to match the following patterns (and all the relevant
1996 * variants related to |, & and + being commutative):
1997 * base | constant_or_mask
1998 * base & constant_and_mask
1999 * (base + constant_offset) & constant_and_mask
2000 * (base - constant_offset) & constant_and_mask
2002 void InductionVariableData::DecomposeBitwise(
2004 BitwiseDecompositionResult* result) {
2005 HValue* base = IgnoreOsrValue(value);
2006 result->base = value;
2008 if (!base->representation().IsInteger32()) return;
2010 if (base->IsBitwise()) {
2011 bool allow_offset = false;
2014 HBitwise* bitwise = HBitwise::cast(base);
2015 if (bitwise->right()->IsInteger32Constant()) {
2016 mask = bitwise->right()->GetInteger32Constant();
2017 base = bitwise->left();
2018 } else if (bitwise->left()->IsInteger32Constant()) {
2019 mask = bitwise->left()->GetInteger32Constant();
2020 base = bitwise->right();
2024 if (bitwise->op() == Token::BIT_AND) {
2025 result->and_mask = mask;
2026 allow_offset = true;
2027 } else if (bitwise->op() == Token::BIT_OR) {
2028 result->or_mask = mask;
2033 result->context = bitwise->context();
2036 if (base->IsAdd()) {
2037 HAdd* add = HAdd::cast(base);
2038 if (add->right()->IsInteger32Constant()) {
2040 } else if (add->left()->IsInteger32Constant()) {
2041 base = add->right();
2043 } else if (base->IsSub()) {
2044 HSub* sub = HSub::cast(base);
2045 if (sub->right()->IsInteger32Constant()) {
2051 result->base = base;
2056 void InductionVariableData::AddCheck(HBoundsCheck* check,
2057 int32_t upper_limit) {
2058 DCHECK(limit_validity() != NULL);
2059 if (limit_validity() != check->block() &&
2060 !limit_validity()->Dominates(check->block())) return;
2061 if (!phi()->block()->current_loop()->IsNestedInThisLoop(
2062 check->block()->current_loop())) return;
2064 ChecksRelatedToLength* length_checks = checks();
2065 while (length_checks != NULL) {
2066 if (length_checks->length() == check->length()) break;
2067 length_checks = length_checks->next();
2069 if (length_checks == NULL) {
2070 length_checks = new(check->block()->zone())
2071 ChecksRelatedToLength(check->length(), checks());
2072 checks_ = length_checks;
2075 length_checks->AddCheck(check, upper_limit);
2079 void InductionVariableData::ChecksRelatedToLength::CloseCurrentBlock() {
2080 if (checks() != NULL) {
2081 InductionVariableCheck* c = checks();
2082 HBasicBlock* current_block = c->check()->block();
2083 while (c != NULL && c->check()->block() == current_block) {
2084 c->set_upper_limit(current_upper_limit_);
2091 void InductionVariableData::ChecksRelatedToLength::UseNewIndexInCurrentBlock(
2096 DCHECK(first_check_in_block() != NULL);
2097 HValue* previous_index = first_check_in_block()->index();
2098 DCHECK(context != NULL);
2100 Zone* zone = index_base->block()->graph()->zone();
2101 set_added_constant(HConstant::New(zone, context, mask));
2102 if (added_index() != NULL) {
2103 added_constant()->InsertBefore(added_index());
2105 added_constant()->InsertBefore(first_check_in_block());
2108 if (added_index() == NULL) {
2109 first_check_in_block()->ReplaceAllUsesWith(first_check_in_block()->index());
2110 HInstruction* new_index = HBitwise::New(zone, context, token, index_base,
2112 DCHECK(new_index->IsBitwise());
2113 new_index->ClearAllSideEffects();
2114 new_index->AssumeRepresentation(Representation::Integer32());
2115 set_added_index(HBitwise::cast(new_index));
2116 added_index()->InsertBefore(first_check_in_block());
2118 DCHECK(added_index()->op() == token);
2120 added_index()->SetOperandAt(1, index_base);
2121 added_index()->SetOperandAt(2, added_constant());
2122 first_check_in_block()->SetOperandAt(0, added_index());
2123 if (previous_index->HasNoUses()) {
2124 previous_index->DeleteAndReplaceWith(NULL);
2128 void InductionVariableData::ChecksRelatedToLength::AddCheck(
2129 HBoundsCheck* check,
2130 int32_t upper_limit) {
2131 BitwiseDecompositionResult decomposition;
2132 InductionVariableData::DecomposeBitwise(check->index(), &decomposition);
2134 if (first_check_in_block() == NULL ||
2135 first_check_in_block()->block() != check->block()) {
2136 CloseCurrentBlock();
2138 first_check_in_block_ = check;
2139 set_added_index(NULL);
2140 set_added_constant(NULL);
2141 current_and_mask_in_block_ = decomposition.and_mask;
2142 current_or_mask_in_block_ = decomposition.or_mask;
2143 current_upper_limit_ = upper_limit;
2145 InductionVariableCheck* new_check = new(check->block()->graph()->zone())
2146 InductionVariableCheck(check, checks_, upper_limit);
2147 checks_ = new_check;
2151 if (upper_limit > current_upper_limit()) {
2152 current_upper_limit_ = upper_limit;
2155 if (decomposition.and_mask != 0 &&
2156 current_or_mask_in_block() == 0) {
2157 if (current_and_mask_in_block() == 0 ||
2158 decomposition.and_mask > current_and_mask_in_block()) {
2159 UseNewIndexInCurrentBlock(Token::BIT_AND,
2160 decomposition.and_mask,
2162 decomposition.context);
2163 current_and_mask_in_block_ = decomposition.and_mask;
2165 check->set_skip_check();
2167 if (current_and_mask_in_block() == 0) {
2168 if (decomposition.or_mask > current_or_mask_in_block()) {
2169 UseNewIndexInCurrentBlock(Token::BIT_OR,
2170 decomposition.or_mask,
2172 decomposition.context);
2173 current_or_mask_in_block_ = decomposition.or_mask;
2175 check->set_skip_check();
2178 if (!check->skip_check()) {
2179 InductionVariableCheck* new_check = new(check->block()->graph()->zone())
2180 InductionVariableCheck(check, checks_, upper_limit);
2181 checks_ = new_check;
2187 * This method detects if phi is an induction variable, with phi_operand as
2188 * its "incremented" value (the other operand would be the "base" value).
2190 * It cheks is phi_operand has the form "phi + constant".
2191 * If yes, the constant is the increment that the induction variable gets at
2192 * every loop iteration.
2193 * Otherwise it returns 0.
2195 int32_t InductionVariableData::ComputeIncrement(HPhi* phi,
2196 HValue* phi_operand) {
2197 if (!phi_operand->representation().IsInteger32()) return 0;
2199 if (phi_operand->IsAdd()) {
2200 HAdd* operation = HAdd::cast(phi_operand);
2201 if (operation->left() == phi &&
2202 operation->right()->IsInteger32Constant()) {
2203 return operation->right()->GetInteger32Constant();
2204 } else if (operation->right() == phi &&
2205 operation->left()->IsInteger32Constant()) {
2206 return operation->left()->GetInteger32Constant();
2208 } else if (phi_operand->IsSub()) {
2209 HSub* operation = HSub::cast(phi_operand);
2210 if (operation->left() == phi &&
2211 operation->right()->IsInteger32Constant()) {
2212 return -operation->right()->GetInteger32Constant();
2221 * Swaps the information in "update" with the one contained in "this".
2222 * The swapping is important because this method is used while doing a
2223 * dominator tree traversal, and "update" will retain the old data that
2224 * will be restored while backtracking.
2226 void InductionVariableData::UpdateAdditionalLimit(
2227 InductionVariableLimitUpdate* update) {
2228 DCHECK(update->updated_variable == this);
2229 if (update->limit_is_upper) {
2230 swap(&additional_upper_limit_, &update->limit);
2231 swap(&additional_upper_limit_is_included_, &update->limit_is_included);
2233 swap(&additional_lower_limit_, &update->limit);
2234 swap(&additional_lower_limit_is_included_, &update->limit_is_included);
2239 int32_t InductionVariableData::ComputeUpperLimit(int32_t and_mask,
2241 // Should be Smi::kMaxValue but it must fit 32 bits; lower is safe anyway.
2242 const int32_t MAX_LIMIT = 1 << 30;
2244 int32_t result = MAX_LIMIT;
2246 if (limit() != NULL &&
2247 limit()->IsInteger32Constant()) {
2248 int32_t limit_value = limit()->GetInteger32Constant();
2249 if (!limit_included()) {
2252 if (limit_value < result) result = limit_value;
2255 if (additional_upper_limit() != NULL &&
2256 additional_upper_limit()->IsInteger32Constant()) {
2257 int32_t limit_value = additional_upper_limit()->GetInteger32Constant();
2258 if (!additional_upper_limit_is_included()) {
2261 if (limit_value < result) result = limit_value;
2264 if (and_mask > 0 && and_mask < MAX_LIMIT) {
2265 if (and_mask < result) result = and_mask;
2269 // Add the effect of the or_mask.
2272 return result >= MAX_LIMIT ? kNoLimit : result;
2276 HValue* InductionVariableData::IgnoreOsrValue(HValue* v) {
2277 if (!v->IsPhi()) return v;
2278 HPhi* phi = HPhi::cast(v);
2279 if (phi->OperandCount() != 2) return v;
2280 if (phi->OperandAt(0)->block()->is_osr_entry()) {
2281 return phi->OperandAt(1);
2282 } else if (phi->OperandAt(1)->block()->is_osr_entry()) {
2283 return phi->OperandAt(0);
2290 InductionVariableData* InductionVariableData::GetInductionVariableData(
2292 v = IgnoreOsrValue(v);
2294 return HPhi::cast(v)->induction_variable_data();
2301 * Check if a conditional branch to "current_branch" with token "token" is
2302 * the branch that keeps the induction loop running (and, conversely, will
2303 * terminate it if the "other_branch" is taken).
2305 * Three conditions must be met:
2306 * - "current_branch" must be in the induction loop.
2307 * - "other_branch" must be out of the induction loop.
2308 * - "token" and the induction increment must be "compatible": the token should
2309 * be a condition that keeps the execution inside the loop until the limit is
2312 bool InductionVariableData::CheckIfBranchIsLoopGuard(
2314 HBasicBlock* current_branch,
2315 HBasicBlock* other_branch) {
2316 if (!phi()->block()->current_loop()->IsNestedInThisLoop(
2317 current_branch->current_loop())) {
2321 if (phi()->block()->current_loop()->IsNestedInThisLoop(
2322 other_branch->current_loop())) {
2326 if (increment() > 0 && (token == Token::LT || token == Token::LTE)) {
2329 if (increment() < 0 && (token == Token::GT || token == Token::GTE)) {
2332 if (Token::IsInequalityOp(token) && (increment() == 1 || increment() == -1)) {
2340 void InductionVariableData::ComputeLimitFromPredecessorBlock(
2342 LimitFromPredecessorBlock* result) {
2343 if (block->predecessors()->length() != 1) return;
2344 HBasicBlock* predecessor = block->predecessors()->at(0);
2345 HInstruction* end = predecessor->last();
2347 if (!end->IsCompareNumericAndBranch()) return;
2348 HCompareNumericAndBranch* branch = HCompareNumericAndBranch::cast(end);
2350 Token::Value token = branch->token();
2351 if (!Token::IsArithmeticCompareOp(token)) return;
2353 HBasicBlock* other_target;
2354 if (block == branch->SuccessorAt(0)) {
2355 other_target = branch->SuccessorAt(1);
2357 other_target = branch->SuccessorAt(0);
2358 token = Token::NegateCompareOp(token);
2359 DCHECK(block == branch->SuccessorAt(1));
2362 InductionVariableData* data;
2364 data = GetInductionVariableData(branch->left());
2365 HValue* limit = branch->right();
2367 data = GetInductionVariableData(branch->right());
2368 token = Token::ReverseCompareOp(token);
2369 limit = branch->left();
2373 result->variable = data;
2374 result->token = token;
2375 result->limit = limit;
2376 result->other_target = other_target;
2382 * Compute the limit that is imposed on an induction variable when entering
2384 * If the limit is the "proper" induction limit (the one that makes the loop
2385 * terminate when the induction variable reaches it) it is stored directly in
2386 * the induction variable data.
2387 * Otherwise the limit is written in "additional_limit" and the method
2390 bool InductionVariableData::ComputeInductionVariableLimit(
2392 InductionVariableLimitUpdate* additional_limit) {
2393 LimitFromPredecessorBlock limit;
2394 ComputeLimitFromPredecessorBlock(block, &limit);
2395 if (!limit.LimitIsValid()) return false;
2397 if (limit.variable->CheckIfBranchIsLoopGuard(limit.token,
2399 limit.other_target)) {
2400 limit.variable->limit_ = limit.limit;
2401 limit.variable->limit_included_ = limit.LimitIsIncluded();
2402 limit.variable->limit_validity_ = block;
2403 limit.variable->induction_exit_block_ = block->predecessors()->at(0);
2404 limit.variable->induction_exit_target_ = limit.other_target;
2407 additional_limit->updated_variable = limit.variable;
2408 additional_limit->limit = limit.limit;
2409 additional_limit->limit_is_upper = limit.LimitIsUpper();
2410 additional_limit->limit_is_included = limit.LimitIsIncluded();
2416 Range* HMathMinMax::InferRange(Zone* zone) {
2417 if (representation().IsSmiOrInteger32()) {
2418 Range* a = left()->range();
2419 Range* b = right()->range();
2420 Range* res = a->Copy(zone);
2421 if (operation_ == kMathMax) {
2422 res->CombinedMax(b);
2424 DCHECK(operation_ == kMathMin);
2425 res->CombinedMin(b);
2429 return HValue::InferRange(zone);
2434 void HPushArguments::AddInput(HValue* value) {
2435 inputs_.Add(NULL, value->block()->zone());
2436 SetOperandAt(OperandCount() - 1, value);
2440 OStream& HPhi::PrintTo(OStream& os) const { // NOLINT
2442 for (int i = 0; i < OperandCount(); ++i) {
2443 os << " " << NameOf(OperandAt(i)) << " ";
2445 return os << " uses:" << UseCount() << "_"
2446 << smi_non_phi_uses() + smi_indirect_uses() << "s_"
2447 << int32_non_phi_uses() + int32_indirect_uses() << "i_"
2448 << double_non_phi_uses() + double_indirect_uses() << "d_"
2449 << tagged_non_phi_uses() + tagged_indirect_uses() << "t"
2450 << TypeOf(this) << "]";
2454 void HPhi::AddInput(HValue* value) {
2455 inputs_.Add(NULL, value->block()->zone());
2456 SetOperandAt(OperandCount() - 1, value);
2457 // Mark phis that may have 'arguments' directly or indirectly as an operand.
2458 if (!CheckFlag(kIsArguments) && value->CheckFlag(kIsArguments)) {
2459 SetFlag(kIsArguments);
2464 bool HPhi::HasRealUses() {
2465 for (HUseIterator it(uses()); !it.Done(); it.Advance()) {
2466 if (!it.value()->IsPhi()) return true;
2472 HValue* HPhi::GetRedundantReplacement() {
2473 HValue* candidate = NULL;
2474 int count = OperandCount();
2476 while (position < count && candidate == NULL) {
2477 HValue* current = OperandAt(position++);
2478 if (current != this) candidate = current;
2480 while (position < count) {
2481 HValue* current = OperandAt(position++);
2482 if (current != this && current != candidate) return NULL;
2484 DCHECK(candidate != this);
2489 void HPhi::DeleteFromGraph() {
2490 DCHECK(block() != NULL);
2491 block()->RemovePhi(this);
2492 DCHECK(block() == NULL);
2496 void HPhi::InitRealUses(int phi_id) {
2497 // Initialize real uses.
2499 // Compute a conservative approximation of truncating uses before inferring
2500 // representations. The proper, exact computation will be done later, when
2501 // inserting representation changes.
2502 SetFlag(kTruncatingToSmi);
2503 SetFlag(kTruncatingToInt32);
2504 for (HUseIterator it(uses()); !it.Done(); it.Advance()) {
2505 HValue* value = it.value();
2506 if (!value->IsPhi()) {
2507 Representation rep = value->observed_input_representation(it.index());
2508 non_phi_uses_[rep.kind()] += 1;
2509 if (FLAG_trace_representation) {
2510 PrintF("#%d Phi is used by real #%d %s as %s\n",
2511 id(), value->id(), value->Mnemonic(), rep.Mnemonic());
2513 if (!value->IsSimulate()) {
2514 if (!value->CheckFlag(kTruncatingToSmi)) {
2515 ClearFlag(kTruncatingToSmi);
2517 if (!value->CheckFlag(kTruncatingToInt32)) {
2518 ClearFlag(kTruncatingToInt32);
2526 void HPhi::AddNonPhiUsesFrom(HPhi* other) {
2527 if (FLAG_trace_representation) {
2528 PrintF("adding to #%d Phi uses of #%d Phi: s%d i%d d%d t%d\n",
2530 other->non_phi_uses_[Representation::kSmi],
2531 other->non_phi_uses_[Representation::kInteger32],
2532 other->non_phi_uses_[Representation::kDouble],
2533 other->non_phi_uses_[Representation::kTagged]);
2536 for (int i = 0; i < Representation::kNumRepresentations; i++) {
2537 indirect_uses_[i] += other->non_phi_uses_[i];
2542 void HPhi::AddIndirectUsesTo(int* dest) {
2543 for (int i = 0; i < Representation::kNumRepresentations; i++) {
2544 dest[i] += indirect_uses_[i];
2549 void HSimulate::MergeWith(ZoneList<HSimulate*>* list) {
2550 while (!list->is_empty()) {
2551 HSimulate* from = list->RemoveLast();
2552 ZoneList<HValue*>* from_values = &from->values_;
2553 for (int i = 0; i < from_values->length(); ++i) {
2554 if (from->HasAssignedIndexAt(i)) {
2555 int index = from->GetAssignedIndexAt(i);
2556 if (HasValueForIndex(index)) continue;
2557 AddAssignedValue(index, from_values->at(i));
2559 if (pop_count_ > 0) {
2562 AddPushedValue(from_values->at(i));
2566 pop_count_ += from->pop_count_;
2567 from->DeleteAndReplaceWith(NULL);
2572 OStream& HSimulate::PrintDataTo(OStream& os) const { // NOLINT
2573 os << "id=" << ast_id().ToInt();
2574 if (pop_count_ > 0) os << " pop " << pop_count_;
2575 if (values_.length() > 0) {
2576 if (pop_count_ > 0) os << " /";
2577 for (int i = values_.length() - 1; i >= 0; --i) {
2578 if (HasAssignedIndexAt(i)) {
2579 os << " var[" << GetAssignedIndexAt(i) << "] = ";
2583 os << NameOf(values_[i]);
2584 if (i > 0) os << ",";
2591 void HSimulate::ReplayEnvironment(HEnvironment* env) {
2592 if (done_with_replay_) return;
2593 DCHECK(env != NULL);
2594 env->set_ast_id(ast_id());
2595 env->Drop(pop_count());
2596 for (int i = values()->length() - 1; i >= 0; --i) {
2597 HValue* value = values()->at(i);
2598 if (HasAssignedIndexAt(i)) {
2599 env->Bind(GetAssignedIndexAt(i), value);
2604 done_with_replay_ = true;
2608 static void ReplayEnvironmentNested(const ZoneList<HValue*>* values,
2609 HCapturedObject* other) {
2610 for (int i = 0; i < values->length(); ++i) {
2611 HValue* value = values->at(i);
2612 if (value->IsCapturedObject()) {
2613 if (HCapturedObject::cast(value)->capture_id() == other->capture_id()) {
2614 values->at(i) = other;
2616 ReplayEnvironmentNested(HCapturedObject::cast(value)->values(), other);
2623 // Replay captured objects by replacing all captured objects with the
2624 // same capture id in the current and all outer environments.
2625 void HCapturedObject::ReplayEnvironment(HEnvironment* env) {
2626 DCHECK(env != NULL);
2627 while (env != NULL) {
2628 ReplayEnvironmentNested(env->values(), this);
2634 OStream& HCapturedObject::PrintDataTo(OStream& os) const { // NOLINT
2635 os << "#" << capture_id() << " ";
2636 return HDematerializedObject::PrintDataTo(os);
2640 void HEnterInlined::RegisterReturnTarget(HBasicBlock* return_target,
2642 DCHECK(return_target->IsInlineReturnTarget());
2643 return_targets_.Add(return_target, zone);
2647 OStream& HEnterInlined::PrintDataTo(OStream& os) const { // NOLINT
2648 return os << function()->debug_name()->ToCString().get()
2649 << ", id=" << function()->id().ToInt();
2653 static bool IsInteger32(double value) {
2654 double roundtrip_value = static_cast<double>(static_cast<int32_t>(value));
2655 return BitCast<int64_t>(roundtrip_value) == BitCast<int64_t>(value);
2659 HConstant::HConstant(Handle<Object> object, Representation r)
2660 : HTemplateInstruction<0>(HType::FromValue(object)),
2661 object_(Unique<Object>::CreateUninitialized(object)),
2662 object_map_(Handle<Map>::null()),
2663 has_stable_map_value_(false),
2664 has_smi_value_(false),
2665 has_int32_value_(false),
2666 has_double_value_(false),
2667 has_external_reference_value_(false),
2668 is_not_in_new_space_(true),
2669 boolean_value_(object->BooleanValue()),
2670 is_undetectable_(false),
2671 instance_type_(kUnknownInstanceType) {
2672 if (object->IsHeapObject()) {
2673 Handle<HeapObject> heap_object = Handle<HeapObject>::cast(object);
2674 Isolate* isolate = heap_object->GetIsolate();
2675 Handle<Map> map(heap_object->map(), isolate);
2676 is_not_in_new_space_ = !isolate->heap()->InNewSpace(*object);
2677 instance_type_ = map->instance_type();
2678 is_undetectable_ = map->is_undetectable();
2679 if (map->is_stable()) object_map_ = Unique<Map>::CreateImmovable(map);
2680 has_stable_map_value_ = (instance_type_ == MAP_TYPE &&
2681 Handle<Map>::cast(heap_object)->is_stable());
2683 if (object->IsNumber()) {
2684 double n = object->Number();
2685 has_int32_value_ = IsInteger32(n);
2686 int32_value_ = DoubleToInt32(n);
2687 has_smi_value_ = has_int32_value_ && Smi::IsValid(int32_value_);
2689 has_double_value_ = true;
2690 // TODO(titzer): if this heap number is new space, tenure a new one.
2697 HConstant::HConstant(Unique<Object> object,
2698 Unique<Map> object_map,
2699 bool has_stable_map_value,
2702 bool is_not_in_new_space,
2704 bool is_undetectable,
2705 InstanceType instance_type)
2706 : HTemplateInstruction<0>(type),
2708 object_map_(object_map),
2709 has_stable_map_value_(has_stable_map_value),
2710 has_smi_value_(false),
2711 has_int32_value_(false),
2712 has_double_value_(false),
2713 has_external_reference_value_(false),
2714 is_not_in_new_space_(is_not_in_new_space),
2715 boolean_value_(boolean_value),
2716 is_undetectable_(is_undetectable),
2717 instance_type_(instance_type) {
2718 DCHECK(!object.handle().is_null());
2719 DCHECK(!type.IsTaggedNumber() || type.IsNone());
2724 HConstant::HConstant(int32_t integer_value,
2726 bool is_not_in_new_space,
2727 Unique<Object> object)
2729 object_map_(Handle<Map>::null()),
2730 has_stable_map_value_(false),
2731 has_smi_value_(Smi::IsValid(integer_value)),
2732 has_int32_value_(true),
2733 has_double_value_(true),
2734 has_external_reference_value_(false),
2735 is_not_in_new_space_(is_not_in_new_space),
2736 boolean_value_(integer_value != 0),
2737 is_undetectable_(false),
2738 int32_value_(integer_value),
2739 double_value_(FastI2D(integer_value)),
2740 instance_type_(kUnknownInstanceType) {
2741 // It's possible to create a constant with a value in Smi-range but stored
2742 // in a (pre-existing) HeapNumber. See crbug.com/349878.
2743 bool could_be_heapobject = r.IsTagged() && !object.handle().is_null();
2744 bool is_smi = has_smi_value_ && !could_be_heapobject;
2745 set_type(is_smi ? HType::Smi() : HType::TaggedNumber());
2750 HConstant::HConstant(double double_value,
2752 bool is_not_in_new_space,
2753 Unique<Object> object)
2755 object_map_(Handle<Map>::null()),
2756 has_stable_map_value_(false),
2757 has_int32_value_(IsInteger32(double_value)),
2758 has_double_value_(true),
2759 has_external_reference_value_(false),
2760 is_not_in_new_space_(is_not_in_new_space),
2761 boolean_value_(double_value != 0 && !std::isnan(double_value)),
2762 is_undetectable_(false),
2763 int32_value_(DoubleToInt32(double_value)),
2764 double_value_(double_value),
2765 instance_type_(kUnknownInstanceType) {
2766 has_smi_value_ = has_int32_value_ && Smi::IsValid(int32_value_);
2767 // It's possible to create a constant with a value in Smi-range but stored
2768 // in a (pre-existing) HeapNumber. See crbug.com/349878.
2769 bool could_be_heapobject = r.IsTagged() && !object.handle().is_null();
2770 bool is_smi = has_smi_value_ && !could_be_heapobject;
2771 set_type(is_smi ? HType::Smi() : HType::TaggedNumber());
2776 HConstant::HConstant(ExternalReference reference)
2777 : HTemplateInstruction<0>(HType::Any()),
2778 object_(Unique<Object>(Handle<Object>::null())),
2779 object_map_(Handle<Map>::null()),
2780 has_stable_map_value_(false),
2781 has_smi_value_(false),
2782 has_int32_value_(false),
2783 has_double_value_(false),
2784 has_external_reference_value_(true),
2785 is_not_in_new_space_(true),
2786 boolean_value_(true),
2787 is_undetectable_(false),
2788 external_reference_value_(reference),
2789 instance_type_(kUnknownInstanceType) {
2790 Initialize(Representation::External());
2794 void HConstant::Initialize(Representation r) {
2796 if (has_smi_value_ && SmiValuesAre31Bits()) {
2797 r = Representation::Smi();
2798 } else if (has_int32_value_) {
2799 r = Representation::Integer32();
2800 } else if (has_double_value_) {
2801 r = Representation::Double();
2802 } else if (has_external_reference_value_) {
2803 r = Representation::External();
2805 Handle<Object> object = object_.handle();
2806 if (object->IsJSObject()) {
2807 // Try to eagerly migrate JSObjects that have deprecated maps.
2808 Handle<JSObject> js_object = Handle<JSObject>::cast(object);
2809 if (js_object->map()->is_deprecated()) {
2810 JSObject::TryMigrateInstance(js_object);
2813 r = Representation::Tagged();
2816 set_representation(r);
2821 bool HConstant::ImmortalImmovable() const {
2822 if (has_int32_value_) {
2825 if (has_double_value_) {
2826 if (IsSpecialDouble()) {
2831 if (has_external_reference_value_) {
2835 DCHECK(!object_.handle().is_null());
2836 Heap* heap = isolate()->heap();
2837 DCHECK(!object_.IsKnownGlobal(heap->minus_zero_value()));
2838 DCHECK(!object_.IsKnownGlobal(heap->nan_value()));
2840 #define IMMORTAL_IMMOVABLE_ROOT(name) \
2841 object_.IsKnownGlobal(heap->name()) ||
2842 IMMORTAL_IMMOVABLE_ROOT_LIST(IMMORTAL_IMMOVABLE_ROOT)
2843 #undef IMMORTAL_IMMOVABLE_ROOT
2844 #define INTERNALIZED_STRING(name, value) \
2845 object_.IsKnownGlobal(heap->name()) ||
2846 INTERNALIZED_STRING_LIST(INTERNALIZED_STRING)
2847 #undef INTERNALIZED_STRING
2848 #define STRING_TYPE(NAME, size, name, Name) \
2849 object_.IsKnownGlobal(heap->name##_map()) ||
2850 STRING_TYPE_LIST(STRING_TYPE)
2856 bool HConstant::EmitAtUses() {
2858 if (block()->graph()->has_osr() &&
2859 block()->graph()->IsStandardConstant(this)) {
2860 // TODO(titzer): this seems like a hack that should be fixed by custom OSR.
2863 if (HasNoUses()) return true;
2864 if (IsCell()) return false;
2865 if (representation().IsDouble()) return false;
2866 if (representation().IsExternal()) return false;
2871 HConstant* HConstant::CopyToRepresentation(Representation r, Zone* zone) const {
2872 if (r.IsSmi() && !has_smi_value_) return NULL;
2873 if (r.IsInteger32() && !has_int32_value_) return NULL;
2874 if (r.IsDouble() && !has_double_value_) return NULL;
2875 if (r.IsExternal() && !has_external_reference_value_) return NULL;
2876 if (has_int32_value_) {
2877 return new(zone) HConstant(int32_value_, r, is_not_in_new_space_, object_);
2879 if (has_double_value_) {
2880 return new(zone) HConstant(double_value_, r, is_not_in_new_space_, object_);
2882 if (has_external_reference_value_) {
2883 return new(zone) HConstant(external_reference_value_);
2885 DCHECK(!object_.handle().is_null());
2886 return new(zone) HConstant(object_,
2888 has_stable_map_value_,
2891 is_not_in_new_space_,
2898 Maybe<HConstant*> HConstant::CopyToTruncatedInt32(Zone* zone) {
2899 HConstant* res = NULL;
2900 if (has_int32_value_) {
2901 res = new(zone) HConstant(int32_value_,
2902 Representation::Integer32(),
2903 is_not_in_new_space_,
2905 } else if (has_double_value_) {
2906 res = new(zone) HConstant(DoubleToInt32(double_value_),
2907 Representation::Integer32(),
2908 is_not_in_new_space_,
2911 return Maybe<HConstant*>(res != NULL, res);
2915 Maybe<HConstant*> HConstant::CopyToTruncatedNumber(Zone* zone) {
2916 HConstant* res = NULL;
2917 Handle<Object> handle = this->handle(zone->isolate());
2918 if (handle->IsBoolean()) {
2919 res = handle->BooleanValue() ?
2920 new(zone) HConstant(1) : new(zone) HConstant(0);
2921 } else if (handle->IsUndefined()) {
2922 res = new(zone) HConstant(base::OS::nan_value());
2923 } else if (handle->IsNull()) {
2924 res = new(zone) HConstant(0);
2926 return Maybe<HConstant*>(res != NULL, res);
2930 OStream& HConstant::PrintDataTo(OStream& os) const { // NOLINT
2931 if (has_int32_value_) {
2932 os << int32_value_ << " ";
2933 } else if (has_double_value_) {
2934 os << double_value_ << " ";
2935 } else if (has_external_reference_value_) {
2936 os << reinterpret_cast<void*>(external_reference_value_.address()) << " ";
2938 // The handle() method is silently and lazily mutating the object.
2939 Handle<Object> h = const_cast<HConstant*>(this)->handle(Isolate::Current());
2940 os << Brief(*h) << " ";
2941 if (HasStableMapValue()) os << "[stable-map] ";
2942 if (HasObjectMap()) os << "[map " << *ObjectMap().handle() << "] ";
2944 if (!is_not_in_new_space_) os << "[new space] ";
2949 OStream& HBinaryOperation::PrintDataTo(OStream& os) const { // NOLINT
2950 os << NameOf(left()) << " " << NameOf(right());
2951 if (CheckFlag(kCanOverflow)) os << " !";
2952 if (CheckFlag(kBailoutOnMinusZero)) os << " -0?";
2957 void HBinaryOperation::InferRepresentation(HInferRepresentationPhase* h_infer) {
2958 DCHECK(CheckFlag(kFlexibleRepresentation));
2959 Representation new_rep = RepresentationFromInputs();
2960 UpdateRepresentation(new_rep, h_infer, "inputs");
2962 if (representation().IsSmi() && HasNonSmiUse()) {
2963 UpdateRepresentation(
2964 Representation::Integer32(), h_infer, "use requirements");
2967 if (observed_output_representation_.IsNone()) {
2968 new_rep = RepresentationFromUses();
2969 UpdateRepresentation(new_rep, h_infer, "uses");
2971 new_rep = RepresentationFromOutput();
2972 UpdateRepresentation(new_rep, h_infer, "output");
2977 Representation HBinaryOperation::RepresentationFromInputs() {
2978 // Determine the worst case of observed input representations and
2979 // the currently assumed output representation.
2980 Representation rep = representation();
2981 for (int i = 1; i <= 2; ++i) {
2982 rep = rep.generalize(observed_input_representation(i));
2984 // If any of the actual input representation is more general than what we
2985 // have so far but not Tagged, use that representation instead.
2986 Representation left_rep = left()->representation();
2987 Representation right_rep = right()->representation();
2988 if (!left_rep.IsTagged()) rep = rep.generalize(left_rep);
2989 if (!right_rep.IsTagged()) rep = rep.generalize(right_rep);
2995 bool HBinaryOperation::IgnoreObservedOutputRepresentation(
2996 Representation current_rep) {
2997 return ((current_rep.IsInteger32() && CheckUsesForFlag(kTruncatingToInt32)) ||
2998 (current_rep.IsSmi() && CheckUsesForFlag(kTruncatingToSmi))) &&
2999 // Mul in Integer32 mode would be too precise.
3000 (!this->IsMul() || HMul::cast(this)->MulMinusOne());
3004 Representation HBinaryOperation::RepresentationFromOutput() {
3005 Representation rep = representation();
3006 // Consider observed output representation, but ignore it if it's Double,
3007 // this instruction is not a division, and all its uses are truncating
3009 if (observed_output_representation_.is_more_general_than(rep) &&
3010 !IgnoreObservedOutputRepresentation(rep)) {
3011 return observed_output_representation_;
3013 return Representation::None();
3017 void HBinaryOperation::AssumeRepresentation(Representation r) {
3018 set_observed_input_representation(1, r);
3019 set_observed_input_representation(2, r);
3020 HValue::AssumeRepresentation(r);
3024 void HMathMinMax::InferRepresentation(HInferRepresentationPhase* h_infer) {
3025 DCHECK(CheckFlag(kFlexibleRepresentation));
3026 Representation new_rep = RepresentationFromInputs();
3027 UpdateRepresentation(new_rep, h_infer, "inputs");
3028 // Do not care about uses.
3032 Range* HBitwise::InferRange(Zone* zone) {
3033 if (op() == Token::BIT_XOR) {
3034 if (left()->HasRange() && right()->HasRange()) {
3035 // The maximum value has the high bit, and all bits below, set:
3037 // If the range can be negative, the minimum int is a negative number with
3038 // the high bit, and all bits below, unset:
3040 // If it cannot be negative, conservatively choose 0 as minimum int.
3041 int64_t left_upper = left()->range()->upper();
3042 int64_t left_lower = left()->range()->lower();
3043 int64_t right_upper = right()->range()->upper();
3044 int64_t right_lower = right()->range()->lower();
3046 if (left_upper < 0) left_upper = ~left_upper;
3047 if (left_lower < 0) left_lower = ~left_lower;
3048 if (right_upper < 0) right_upper = ~right_upper;
3049 if (right_lower < 0) right_lower = ~right_lower;
3051 int high = MostSignificantBit(
3052 static_cast<uint32_t>(
3053 left_upper | left_lower | right_upper | right_lower));
3057 int32_t min = (left()->range()->CanBeNegative() ||
3058 right()->range()->CanBeNegative())
3059 ? static_cast<int32_t>(-limit) : 0;
3060 return new(zone) Range(min, static_cast<int32_t>(limit - 1));
3062 Range* result = HValue::InferRange(zone);
3063 result->set_can_be_minus_zero(false);
3066 const int32_t kDefaultMask = static_cast<int32_t>(0xffffffff);
3067 int32_t left_mask = (left()->range() != NULL)
3068 ? left()->range()->Mask()
3070 int32_t right_mask = (right()->range() != NULL)
3071 ? right()->range()->Mask()
3073 int32_t result_mask = (op() == Token::BIT_AND)
3074 ? left_mask & right_mask
3075 : left_mask | right_mask;
3076 if (result_mask >= 0) return new(zone) Range(0, result_mask);
3078 Range* result = HValue::InferRange(zone);
3079 result->set_can_be_minus_zero(false);
3084 Range* HSar::InferRange(Zone* zone) {
3085 if (right()->IsConstant()) {
3086 HConstant* c = HConstant::cast(right());
3087 if (c->HasInteger32Value()) {
3088 Range* result = (left()->range() != NULL)
3089 ? left()->range()->Copy(zone)
3090 : new(zone) Range();
3091 result->Sar(c->Integer32Value());
3095 return HValue::InferRange(zone);
3099 Range* HShr::InferRange(Zone* zone) {
3100 if (right()->IsConstant()) {
3101 HConstant* c = HConstant::cast(right());
3102 if (c->HasInteger32Value()) {
3103 int shift_count = c->Integer32Value() & 0x1f;
3104 if (left()->range()->CanBeNegative()) {
3105 // Only compute bounds if the result always fits into an int32.
3106 return (shift_count >= 1)
3107 ? new(zone) Range(0,
3108 static_cast<uint32_t>(0xffffffff) >> shift_count)
3109 : new(zone) Range();
3111 // For positive inputs we can use the >> operator.
3112 Range* result = (left()->range() != NULL)
3113 ? left()->range()->Copy(zone)
3114 : new(zone) Range();
3115 result->Sar(c->Integer32Value());
3120 return HValue::InferRange(zone);
3124 Range* HShl::InferRange(Zone* zone) {
3125 if (right()->IsConstant()) {
3126 HConstant* c = HConstant::cast(right());
3127 if (c->HasInteger32Value()) {
3128 Range* result = (left()->range() != NULL)
3129 ? left()->range()->Copy(zone)
3130 : new(zone) Range();
3131 result->Shl(c->Integer32Value());
3135 return HValue::InferRange(zone);
3139 Range* HLoadNamedField::InferRange(Zone* zone) {
3140 if (access().representation().IsInteger8()) {
3141 return new(zone) Range(kMinInt8, kMaxInt8);
3143 if (access().representation().IsUInteger8()) {
3144 return new(zone) Range(kMinUInt8, kMaxUInt8);
3146 if (access().representation().IsInteger16()) {
3147 return new(zone) Range(kMinInt16, kMaxInt16);
3149 if (access().representation().IsUInteger16()) {
3150 return new(zone) Range(kMinUInt16, kMaxUInt16);
3152 if (access().IsStringLength()) {
3153 return new(zone) Range(0, String::kMaxLength);
3155 return HValue::InferRange(zone);
3159 Range* HLoadKeyed::InferRange(Zone* zone) {
3160 switch (elements_kind()) {
3161 case EXTERNAL_INT8_ELEMENTS:
3162 return new(zone) Range(kMinInt8, kMaxInt8);
3163 case EXTERNAL_UINT8_ELEMENTS:
3164 case EXTERNAL_UINT8_CLAMPED_ELEMENTS:
3165 return new(zone) Range(kMinUInt8, kMaxUInt8);
3166 case EXTERNAL_INT16_ELEMENTS:
3167 return new(zone) Range(kMinInt16, kMaxInt16);
3168 case EXTERNAL_UINT16_ELEMENTS:
3169 return new(zone) Range(kMinUInt16, kMaxUInt16);
3171 return HValue::InferRange(zone);
3176 OStream& HCompareGeneric::PrintDataTo(OStream& os) const { // NOLINT
3177 os << Token::Name(token()) << " ";
3178 return HBinaryOperation::PrintDataTo(os);
3182 OStream& HStringCompareAndBranch::PrintDataTo(OStream& os) const { // NOLINT
3183 os << Token::Name(token()) << " ";
3184 return HControlInstruction::PrintDataTo(os);
3188 OStream& HCompareNumericAndBranch::PrintDataTo(OStream& os) const { // NOLINT
3189 os << Token::Name(token()) << " " << NameOf(left()) << " " << NameOf(right());
3190 return HControlInstruction::PrintDataTo(os);
3194 OStream& HCompareObjectEqAndBranch::PrintDataTo(OStream& os) const { // NOLINT
3195 os << NameOf(left()) << " " << NameOf(right());
3196 return HControlInstruction::PrintDataTo(os);
3200 bool HCompareObjectEqAndBranch::KnownSuccessorBlock(HBasicBlock** block) {
3201 if (known_successor_index() != kNoKnownSuccessorIndex) {
3202 *block = SuccessorAt(known_successor_index());
3205 if (FLAG_fold_constants && left()->IsConstant() && right()->IsConstant()) {
3206 *block = HConstant::cast(left())->DataEquals(HConstant::cast(right()))
3207 ? FirstSuccessor() : SecondSuccessor();
3215 bool ConstantIsObject(HConstant* constant, Isolate* isolate) {
3216 if (constant->HasNumberValue()) return false;
3217 if (constant->GetUnique().IsKnownGlobal(isolate->heap()->null_value())) {
3220 if (constant->IsUndetectable()) return false;
3221 InstanceType type = constant->GetInstanceType();
3222 return (FIRST_NONCALLABLE_SPEC_OBJECT_TYPE <= type) &&
3223 (type <= LAST_NONCALLABLE_SPEC_OBJECT_TYPE);
3227 bool HIsObjectAndBranch::KnownSuccessorBlock(HBasicBlock** block) {
3228 if (FLAG_fold_constants && value()->IsConstant()) {
3229 *block = ConstantIsObject(HConstant::cast(value()), isolate())
3230 ? FirstSuccessor() : SecondSuccessor();
3238 bool HIsStringAndBranch::KnownSuccessorBlock(HBasicBlock** block) {
3239 if (known_successor_index() != kNoKnownSuccessorIndex) {
3240 *block = SuccessorAt(known_successor_index());
3243 if (FLAG_fold_constants && value()->IsConstant()) {
3244 *block = HConstant::cast(value())->HasStringValue()
3245 ? FirstSuccessor() : SecondSuccessor();
3248 if (value()->type().IsString()) {
3249 *block = FirstSuccessor();
3252 if (value()->type().IsSmi() ||
3253 value()->type().IsNull() ||
3254 value()->type().IsBoolean() ||
3255 value()->type().IsUndefined() ||
3256 value()->type().IsJSObject()) {
3257 *block = SecondSuccessor();
3265 bool HIsUndetectableAndBranch::KnownSuccessorBlock(HBasicBlock** block) {
3266 if (FLAG_fold_constants && value()->IsConstant()) {
3267 *block = HConstant::cast(value())->IsUndetectable()
3268 ? FirstSuccessor() : SecondSuccessor();
3276 bool HHasInstanceTypeAndBranch::KnownSuccessorBlock(HBasicBlock** block) {
3277 if (FLAG_fold_constants && value()->IsConstant()) {
3278 InstanceType type = HConstant::cast(value())->GetInstanceType();
3279 *block = (from_ <= type) && (type <= to_)
3280 ? FirstSuccessor() : SecondSuccessor();
3288 void HCompareHoleAndBranch::InferRepresentation(
3289 HInferRepresentationPhase* h_infer) {
3290 ChangeRepresentation(value()->representation());
3294 bool HCompareNumericAndBranch::KnownSuccessorBlock(HBasicBlock** block) {
3295 if (left() == right() &&
3296 left()->representation().IsSmiOrInteger32()) {
3297 *block = (token() == Token::EQ ||
3298 token() == Token::EQ_STRICT ||
3299 token() == Token::LTE ||
3300 token() == Token::GTE)
3301 ? FirstSuccessor() : SecondSuccessor();
3309 bool HCompareMinusZeroAndBranch::KnownSuccessorBlock(HBasicBlock** block) {
3310 if (FLAG_fold_constants && value()->IsConstant()) {
3311 HConstant* constant = HConstant::cast(value());
3312 if (constant->HasDoubleValue()) {
3313 *block = IsMinusZero(constant->DoubleValue())
3314 ? FirstSuccessor() : SecondSuccessor();
3318 if (value()->representation().IsSmiOrInteger32()) {
3319 // A Smi or Integer32 cannot contain minus zero.
3320 *block = SecondSuccessor();
3328 void HCompareMinusZeroAndBranch::InferRepresentation(
3329 HInferRepresentationPhase* h_infer) {
3330 ChangeRepresentation(value()->representation());
3334 OStream& HGoto::PrintDataTo(OStream& os) const { // NOLINT
3335 return os << *SuccessorAt(0);
3339 void HCompareNumericAndBranch::InferRepresentation(
3340 HInferRepresentationPhase* h_infer) {
3341 Representation left_rep = left()->representation();
3342 Representation right_rep = right()->representation();
3343 Representation observed_left = observed_input_representation(0);
3344 Representation observed_right = observed_input_representation(1);
3346 Representation rep = Representation::None();
3347 rep = rep.generalize(observed_left);
3348 rep = rep.generalize(observed_right);
3349 if (rep.IsNone() || rep.IsSmiOrInteger32()) {
3350 if (!left_rep.IsTagged()) rep = rep.generalize(left_rep);
3351 if (!right_rep.IsTagged()) rep = rep.generalize(right_rep);
3353 rep = Representation::Double();
3356 if (rep.IsDouble()) {
3357 // According to the ES5 spec (11.9.3, 11.8.5), Equality comparisons (==, ===
3358 // and !=) have special handling of undefined, e.g. undefined == undefined
3359 // is 'true'. Relational comparisons have a different semantic, first
3360 // calling ToPrimitive() on their arguments. The standard Crankshaft
3361 // tagged-to-double conversion to ensure the HCompareNumericAndBranch's
3362 // inputs are doubles caused 'undefined' to be converted to NaN. That's
3363 // compatible out-of-the box with ordered relational comparisons (<, >, <=,
3364 // >=). However, for equality comparisons (and for 'in' and 'instanceof'),
3365 // it is not consistent with the spec. For example, it would cause undefined
3366 // == undefined (should be true) to be evaluated as NaN == NaN
3367 // (false). Therefore, any comparisons other than ordered relational
3368 // comparisons must cause a deopt when one of their arguments is undefined.
3370 if (Token::IsOrderedRelationalCompareOp(token_)) {
3371 SetFlag(kAllowUndefinedAsNaN);
3374 ChangeRepresentation(rep);
3378 OStream& HParameter::PrintDataTo(OStream& os) const { // NOLINT
3379 return os << index();
3383 OStream& HLoadNamedField::PrintDataTo(OStream& os) const { // NOLINT
3384 os << NameOf(object()) << access_;
3386 if (maps() != NULL) {
3387 os << " [" << *maps()->at(0).handle();
3388 for (int i = 1; i < maps()->size(); ++i) {
3389 os << "," << *maps()->at(i).handle();
3394 if (HasDependency()) os << " " << NameOf(dependency());
3399 OStream& HLoadNamedGeneric::PrintDataTo(OStream& os) const { // NOLINT
3400 Handle<String> n = Handle<String>::cast(name());
3401 return os << NameOf(object()) << "." << n->ToCString().get();
3405 OStream& HLoadKeyed::PrintDataTo(OStream& os) const { // NOLINT
3406 if (!is_external()) {
3407 os << NameOf(elements());
3409 DCHECK(elements_kind() >= FIRST_EXTERNAL_ARRAY_ELEMENTS_KIND &&
3410 elements_kind() <= LAST_EXTERNAL_ARRAY_ELEMENTS_KIND);
3411 os << NameOf(elements()) << "." << ElementsKindToString(elements_kind());
3414 os << "[" << NameOf(key());
3415 if (IsDehoisted()) os << " + " << base_offset();
3418 if (HasDependency()) os << " " << NameOf(dependency());
3419 if (RequiresHoleCheck()) os << " check_hole";
3424 bool HLoadKeyed::TryIncreaseBaseOffset(uint32_t increase_by_value) {
3425 // The base offset is usually simply the size of the array header, except
3426 // with dehoisting adds an addition offset due to a array index key
3427 // manipulation, in which case it becomes (array header size +
3428 // constant-offset-from-key * kPointerSize)
3429 uint32_t base_offset = BaseOffsetField::decode(bit_field_);
3430 v8::base::internal::CheckedNumeric<uint32_t> addition_result = base_offset;
3431 addition_result += increase_by_value;
3432 if (!addition_result.IsValid()) return false;
3433 base_offset = addition_result.ValueOrDie();
3434 if (!BaseOffsetField::is_valid(base_offset)) return false;
3435 bit_field_ = BaseOffsetField::update(bit_field_, base_offset);
3440 bool HLoadKeyed::UsesMustHandleHole() const {
3441 if (IsFastPackedElementsKind(elements_kind())) {
3445 if (IsExternalArrayElementsKind(elements_kind())) {
3449 if (hole_mode() == ALLOW_RETURN_HOLE) {
3450 if (IsFastDoubleElementsKind(elements_kind())) {
3451 return AllUsesCanTreatHoleAsNaN();
3456 if (IsFastDoubleElementsKind(elements_kind())) {
3460 // Holes are only returned as tagged values.
3461 if (!representation().IsTagged()) {
3465 for (HUseIterator it(uses()); !it.Done(); it.Advance()) {
3466 HValue* use = it.value();
3467 if (!use->IsChange()) return false;
3474 bool HLoadKeyed::AllUsesCanTreatHoleAsNaN() const {
3475 return IsFastDoubleElementsKind(elements_kind()) &&
3476 CheckUsesForFlag(HValue::kAllowUndefinedAsNaN);
3480 bool HLoadKeyed::RequiresHoleCheck() const {
3481 if (IsFastPackedElementsKind(elements_kind())) {
3485 if (IsExternalArrayElementsKind(elements_kind())) {
3489 return !UsesMustHandleHole();
3493 OStream& HLoadKeyedGeneric::PrintDataTo(OStream& os) const { // NOLINT
3494 return os << NameOf(object()) << "[" << NameOf(key()) << "]";
3498 HValue* HLoadKeyedGeneric::Canonicalize() {
3499 // Recognize generic keyed loads that use property name generated
3500 // by for-in statement as a key and rewrite them into fast property load
3502 if (key()->IsLoadKeyed()) {
3503 HLoadKeyed* key_load = HLoadKeyed::cast(key());
3504 if (key_load->elements()->IsForInCacheArray()) {
3505 HForInCacheArray* names_cache =
3506 HForInCacheArray::cast(key_load->elements());
3508 if (names_cache->enumerable() == object()) {
3509 HForInCacheArray* index_cache =
3510 names_cache->index_cache();
3511 HCheckMapValue* map_check =
3512 HCheckMapValue::New(block()->graph()->zone(),
3513 block()->graph()->GetInvalidContext(),
3515 names_cache->map());
3516 HInstruction* index = HLoadKeyed::New(
3517 block()->graph()->zone(),
3518 block()->graph()->GetInvalidContext(),
3522 key_load->elements_kind());
3523 map_check->InsertBefore(this);
3524 index->InsertBefore(this);
3525 return Prepend(new(block()->zone()) HLoadFieldByIndex(
3535 OStream& HStoreNamedGeneric::PrintDataTo(OStream& os) const { // NOLINT
3536 Handle<String> n = Handle<String>::cast(name());
3537 return os << NameOf(object()) << "." << n->ToCString().get() << " = "
3542 OStream& HStoreNamedField::PrintDataTo(OStream& os) const { // NOLINT
3543 os << NameOf(object()) << access_ << " = " << NameOf(value());
3544 if (NeedsWriteBarrier()) os << " (write-barrier)";
3545 if (has_transition()) os << " (transition map " << *transition_map() << ")";
3550 OStream& HStoreKeyed::PrintDataTo(OStream& os) const { // NOLINT
3551 if (!is_external()) {
3552 os << NameOf(elements());
3554 DCHECK(elements_kind() >= FIRST_EXTERNAL_ARRAY_ELEMENTS_KIND &&
3555 elements_kind() <= LAST_EXTERNAL_ARRAY_ELEMENTS_KIND);
3556 os << NameOf(elements()) << "." << ElementsKindToString(elements_kind());
3559 os << "[" << NameOf(key());
3560 if (IsDehoisted()) os << " + " << base_offset();
3561 return os << "] = " << NameOf(value());
3565 OStream& HStoreKeyedGeneric::PrintDataTo(OStream& os) const { // NOLINT
3566 return os << NameOf(object()) << "[" << NameOf(key())
3567 << "] = " << NameOf(value());
3571 OStream& HTransitionElementsKind::PrintDataTo(OStream& os) const { // NOLINT
3572 os << NameOf(object());
3573 ElementsKind from_kind = original_map().handle()->elements_kind();
3574 ElementsKind to_kind = transitioned_map().handle()->elements_kind();
3575 os << " " << *original_map().handle() << " ["
3576 << ElementsAccessor::ForKind(from_kind)->name() << "] -> "
3577 << *transitioned_map().handle() << " ["
3578 << ElementsAccessor::ForKind(to_kind)->name() << "]";
3579 if (IsSimpleMapChangeTransition(from_kind, to_kind)) os << " (simple)";
3584 OStream& HLoadGlobalCell::PrintDataTo(OStream& os) const { // NOLINT
3585 os << "[" << *cell().handle() << "]";
3586 if (!details_.IsDontDelete()) os << " (deleteable)";
3587 if (details_.IsReadOnly()) os << " (read-only)";
3592 bool HLoadGlobalCell::RequiresHoleCheck() const {
3593 if (details_.IsDontDelete() && !details_.IsReadOnly()) return false;
3594 for (HUseIterator it(uses()); !it.Done(); it.Advance()) {
3595 HValue* use = it.value();
3596 if (!use->IsChange()) return true;
3602 OStream& HLoadGlobalGeneric::PrintDataTo(OStream& os) const { // NOLINT
3603 return os << name()->ToCString().get() << " ";
3607 OStream& HInnerAllocatedObject::PrintDataTo(OStream& os) const { // NOLINT
3608 os << NameOf(base_object()) << " offset ";
3609 return offset()->PrintTo(os);
3613 OStream& HStoreGlobalCell::PrintDataTo(OStream& os) const { // NOLINT
3614 os << "[" << *cell().handle() << "] = " << NameOf(value());
3615 if (!details_.IsDontDelete()) os << " (deleteable)";
3616 if (details_.IsReadOnly()) os << " (read-only)";
3621 OStream& HLoadContextSlot::PrintDataTo(OStream& os) const { // NOLINT
3622 return os << NameOf(value()) << "[" << slot_index() << "]";
3626 OStream& HStoreContextSlot::PrintDataTo(OStream& os) const { // NOLINT
3627 return os << NameOf(context()) << "[" << slot_index()
3628 << "] = " << NameOf(value());
3632 // Implementation of type inference and type conversions. Calculates
3633 // the inferred type of this instruction based on the input operands.
3635 HType HValue::CalculateInferredType() {
3640 HType HPhi::CalculateInferredType() {
3641 if (OperandCount() == 0) return HType::Tagged();
3642 HType result = OperandAt(0)->type();
3643 for (int i = 1; i < OperandCount(); ++i) {
3644 HType current = OperandAt(i)->type();
3645 result = result.Combine(current);
3651 HType HChange::CalculateInferredType() {
3652 if (from().IsDouble() && to().IsTagged()) return HType::HeapNumber();
3657 Representation HUnaryMathOperation::RepresentationFromInputs() {
3658 if (SupportsFlexibleFloorAndRound() &&
3659 (op_ == kMathFloor || op_ == kMathRound)) {
3660 // Floor and Round always take a double input. The integral result can be
3661 // used as an integer or a double. Infer the representation from the uses.
3662 return Representation::None();
3664 Representation rep = representation();
3665 // If any of the actual input representation is more general than what we
3666 // have so far but not Tagged, use that representation instead.
3667 Representation input_rep = value()->representation();
3668 if (!input_rep.IsTagged()) {
3669 rep = rep.generalize(input_rep);
3675 bool HAllocate::HandleSideEffectDominator(GVNFlag side_effect,
3676 HValue* dominator) {
3677 DCHECK(side_effect == kNewSpacePromotion);
3678 Zone* zone = block()->zone();
3679 if (!FLAG_use_allocation_folding) return false;
3681 // Try to fold allocations together with their dominating allocations.
3682 if (!dominator->IsAllocate()) {
3683 if (FLAG_trace_allocation_folding) {
3684 PrintF("#%d (%s) cannot fold into #%d (%s)\n",
3685 id(), Mnemonic(), dominator->id(), dominator->Mnemonic());
3690 // Check whether we are folding within the same block for local folding.
3691 if (FLAG_use_local_allocation_folding && dominator->block() != block()) {
3692 if (FLAG_trace_allocation_folding) {
3693 PrintF("#%d (%s) cannot fold into #%d (%s), crosses basic blocks\n",
3694 id(), Mnemonic(), dominator->id(), dominator->Mnemonic());
3699 HAllocate* dominator_allocate = HAllocate::cast(dominator);
3700 HValue* dominator_size = dominator_allocate->size();
3701 HValue* current_size = size();
3703 // TODO(hpayer): Add support for non-constant allocation in dominator.
3704 if (!dominator_size->IsInteger32Constant()) {
3705 if (FLAG_trace_allocation_folding) {
3706 PrintF("#%d (%s) cannot fold into #%d (%s), "
3707 "dynamic allocation size in dominator\n",
3708 id(), Mnemonic(), dominator->id(), dominator->Mnemonic());
3713 dominator_allocate = GetFoldableDominator(dominator_allocate);
3714 if (dominator_allocate == NULL) {
3718 if (!has_size_upper_bound()) {
3719 if (FLAG_trace_allocation_folding) {
3720 PrintF("#%d (%s) cannot fold into #%d (%s), "
3721 "can't estimate total allocation size\n",
3722 id(), Mnemonic(), dominator->id(), dominator->Mnemonic());
3727 if (!current_size->IsInteger32Constant()) {
3728 // If it's not constant then it is a size_in_bytes calculation graph
3729 // like this: (const_header_size + const_element_size * size).
3730 DCHECK(current_size->IsInstruction());
3732 HInstruction* current_instr = HInstruction::cast(current_size);
3733 if (!current_instr->Dominates(dominator_allocate)) {
3734 if (FLAG_trace_allocation_folding) {
3735 PrintF("#%d (%s) cannot fold into #%d (%s), dynamic size "
3736 "value does not dominate target allocation\n",
3737 id(), Mnemonic(), dominator_allocate->id(),
3738 dominator_allocate->Mnemonic());
3744 DCHECK((IsNewSpaceAllocation() &&
3745 dominator_allocate->IsNewSpaceAllocation()) ||
3746 (IsOldDataSpaceAllocation() &&
3747 dominator_allocate->IsOldDataSpaceAllocation()) ||
3748 (IsOldPointerSpaceAllocation() &&
3749 dominator_allocate->IsOldPointerSpaceAllocation()));
3751 // First update the size of the dominator allocate instruction.
3752 dominator_size = dominator_allocate->size();
3753 int32_t original_object_size =
3754 HConstant::cast(dominator_size)->GetInteger32Constant();
3755 int32_t dominator_size_constant = original_object_size;
3757 if (MustAllocateDoubleAligned()) {
3758 if ((dominator_size_constant & kDoubleAlignmentMask) != 0) {
3759 dominator_size_constant += kDoubleSize / 2;
3763 int32_t current_size_max_value = size_upper_bound()->GetInteger32Constant();
3764 int32_t new_dominator_size = dominator_size_constant + current_size_max_value;
3766 // Since we clear the first word after folded memory, we cannot use the
3767 // whole Page::kMaxRegularHeapObjectSize memory.
3768 if (new_dominator_size > Page::kMaxRegularHeapObjectSize - kPointerSize) {
3769 if (FLAG_trace_allocation_folding) {
3770 PrintF("#%d (%s) cannot fold into #%d (%s) due to size: %d\n",
3771 id(), Mnemonic(), dominator_allocate->id(),
3772 dominator_allocate->Mnemonic(), new_dominator_size);
3777 HInstruction* new_dominator_size_value;
3779 if (current_size->IsInteger32Constant()) {
3780 new_dominator_size_value =
3781 HConstant::CreateAndInsertBefore(zone,
3784 Representation::None(),
3785 dominator_allocate);
3787 HValue* new_dominator_size_constant =
3788 HConstant::CreateAndInsertBefore(zone,
3790 dominator_size_constant,
3791 Representation::Integer32(),
3792 dominator_allocate);
3794 // Add old and new size together and insert.
3795 current_size->ChangeRepresentation(Representation::Integer32());
3797 new_dominator_size_value = HAdd::New(zone, context(),
3798 new_dominator_size_constant, current_size);
3799 new_dominator_size_value->ClearFlag(HValue::kCanOverflow);
3800 new_dominator_size_value->ChangeRepresentation(Representation::Integer32());
3802 new_dominator_size_value->InsertBefore(dominator_allocate);
3805 dominator_allocate->UpdateSize(new_dominator_size_value);
3807 if (MustAllocateDoubleAligned()) {
3808 if (!dominator_allocate->MustAllocateDoubleAligned()) {
3809 dominator_allocate->MakeDoubleAligned();
3813 bool keep_new_space_iterable = FLAG_log_gc || FLAG_heap_stats;
3815 keep_new_space_iterable = keep_new_space_iterable || FLAG_verify_heap;
3818 if (keep_new_space_iterable && dominator_allocate->IsNewSpaceAllocation()) {
3819 dominator_allocate->MakePrefillWithFiller();
3821 // TODO(hpayer): This is a short-term hack to make allocation mementos
3822 // work again in new space.
3823 dominator_allocate->ClearNextMapWord(original_object_size);
3826 dominator_allocate->UpdateClearNextMapWord(MustClearNextMapWord());
3828 // After that replace the dominated allocate instruction.
3829 HInstruction* inner_offset = HConstant::CreateAndInsertBefore(
3832 dominator_size_constant,
3833 Representation::None(),
3836 HInstruction* dominated_allocate_instr =
3837 HInnerAllocatedObject::New(zone,
3842 dominated_allocate_instr->InsertBefore(this);
3843 DeleteAndReplaceWith(dominated_allocate_instr);
3844 if (FLAG_trace_allocation_folding) {
3845 PrintF("#%d (%s) folded into #%d (%s)\n",
3846 id(), Mnemonic(), dominator_allocate->id(),
3847 dominator_allocate->Mnemonic());
3853 HAllocate* HAllocate::GetFoldableDominator(HAllocate* dominator) {
3854 if (!IsFoldable(dominator)) {
3855 // We cannot hoist old space allocations over new space allocations.
3856 if (IsNewSpaceAllocation() || dominator->IsNewSpaceAllocation()) {
3857 if (FLAG_trace_allocation_folding) {
3858 PrintF("#%d (%s) cannot fold into #%d (%s), new space hoisting\n",
3859 id(), Mnemonic(), dominator->id(), dominator->Mnemonic());
3864 HAllocate* dominator_dominator = dominator->dominating_allocate_;
3866 // We can hoist old data space allocations over an old pointer space
3867 // allocation and vice versa. For that we have to check the dominator
3868 // of the dominator allocate instruction.
3869 if (dominator_dominator == NULL) {
3870 dominating_allocate_ = dominator;
3871 if (FLAG_trace_allocation_folding) {
3872 PrintF("#%d (%s) cannot fold into #%d (%s), different spaces\n",
3873 id(), Mnemonic(), dominator->id(), dominator->Mnemonic());
3878 // We can just fold old space allocations that are in the same basic block,
3879 // since it is not guaranteed that we fill up the whole allocated old
3881 // TODO(hpayer): Remove this limitation and add filler maps for each each
3882 // allocation as soon as we have store elimination.
3883 if (block()->block_id() != dominator_dominator->block()->block_id()) {
3884 if (FLAG_trace_allocation_folding) {
3885 PrintF("#%d (%s) cannot fold into #%d (%s), different basic blocks\n",
3886 id(), Mnemonic(), dominator_dominator->id(),
3887 dominator_dominator->Mnemonic());
3892 DCHECK((IsOldDataSpaceAllocation() &&
3893 dominator_dominator->IsOldDataSpaceAllocation()) ||
3894 (IsOldPointerSpaceAllocation() &&
3895 dominator_dominator->IsOldPointerSpaceAllocation()));
3897 int32_t current_size = HConstant::cast(size())->GetInteger32Constant();
3898 HStoreNamedField* dominator_free_space_size =
3899 dominator->filler_free_space_size_;
3900 if (dominator_free_space_size != NULL) {
3901 // We already hoisted one old space allocation, i.e., we already installed
3902 // a filler map. Hence, we just have to update the free space size.
3903 dominator->UpdateFreeSpaceFiller(current_size);
3905 // This is the first old space allocation that gets hoisted. We have to
3906 // install a filler map since the follwing allocation may cause a GC.
3907 dominator->CreateFreeSpaceFiller(current_size);
3910 // We can hoist the old space allocation over the actual dominator.
3911 return dominator_dominator;
3917 void HAllocate::UpdateFreeSpaceFiller(int32_t free_space_size) {
3918 DCHECK(filler_free_space_size_ != NULL);
3919 Zone* zone = block()->zone();
3920 // We must explicitly force Smi representation here because on x64 we
3921 // would otherwise automatically choose int32, but the actual store
3922 // requires a Smi-tagged value.
3923 HConstant* new_free_space_size = HConstant::CreateAndInsertBefore(
3926 filler_free_space_size_->value()->GetInteger32Constant() +
3928 Representation::Smi(),
3929 filler_free_space_size_);
3930 filler_free_space_size_->UpdateValue(new_free_space_size);
3934 void HAllocate::CreateFreeSpaceFiller(int32_t free_space_size) {
3935 DCHECK(filler_free_space_size_ == NULL);
3936 Zone* zone = block()->zone();
3937 HInstruction* free_space_instr =
3938 HInnerAllocatedObject::New(zone, context(), dominating_allocate_,
3939 dominating_allocate_->size(), type());
3940 free_space_instr->InsertBefore(this);
3941 HConstant* filler_map = HConstant::CreateAndInsertAfter(
3942 zone, Unique<Map>::CreateImmovable(
3943 isolate()->factory()->free_space_map()), true, free_space_instr);
3944 HInstruction* store_map = HStoreNamedField::New(zone, context(),
3945 free_space_instr, HObjectAccess::ForMap(), filler_map);
3946 store_map->SetFlag(HValue::kHasNoObservableSideEffects);
3947 store_map->InsertAfter(filler_map);
3949 // We must explicitly force Smi representation here because on x64 we
3950 // would otherwise automatically choose int32, but the actual store
3951 // requires a Smi-tagged value.
3952 HConstant* filler_size = HConstant::CreateAndInsertAfter(
3953 zone, context(), free_space_size, Representation::Smi(), store_map);
3954 // Must force Smi representation for x64 (see comment above).
3955 HObjectAccess access =
3956 HObjectAccess::ForMapAndOffset(isolate()->factory()->free_space_map(),
3957 FreeSpace::kSizeOffset,
3958 Representation::Smi());
3959 HStoreNamedField* store_size = HStoreNamedField::New(zone, context(),
3960 free_space_instr, access, filler_size);
3961 store_size->SetFlag(HValue::kHasNoObservableSideEffects);
3962 store_size->InsertAfter(filler_size);
3963 filler_free_space_size_ = store_size;
3967 void HAllocate::ClearNextMapWord(int offset) {
3968 if (MustClearNextMapWord()) {
3969 Zone* zone = block()->zone();
3970 HObjectAccess access =
3971 HObjectAccess::ForObservableJSObjectOffset(offset);
3972 HStoreNamedField* clear_next_map =
3973 HStoreNamedField::New(zone, context(), this, access,
3974 block()->graph()->GetConstant0());
3975 clear_next_map->ClearAllSideEffects();
3976 clear_next_map->InsertAfter(this);
3981 OStream& HAllocate::PrintDataTo(OStream& os) const { // NOLINT
3982 os << NameOf(size()) << " (";
3983 if (IsNewSpaceAllocation()) os << "N";
3984 if (IsOldPointerSpaceAllocation()) os << "P";
3985 if (IsOldDataSpaceAllocation()) os << "D";
3986 if (MustAllocateDoubleAligned()) os << "A";
3987 if (MustPrefillWithFiller()) os << "F";
3992 bool HStoreKeyed::TryIncreaseBaseOffset(uint32_t increase_by_value) {
3993 // The base offset is usually simply the size of the array header, except
3994 // with dehoisting adds an addition offset due to a array index key
3995 // manipulation, in which case it becomes (array header size +
3996 // constant-offset-from-key * kPointerSize)
3997 v8::base::internal::CheckedNumeric<uint32_t> addition_result = base_offset_;
3998 addition_result += increase_by_value;
3999 if (!addition_result.IsValid()) return false;
4000 base_offset_ = addition_result.ValueOrDie();
4005 bool HStoreKeyed::NeedsCanonicalization() {
4006 // If value is an integer or smi or comes from the result of a keyed load or
4007 // constant then it is either be a non-hole value or in the case of a constant
4008 // the hole is only being stored explicitly: no need for canonicalization.
4010 // The exception to that is keyed loads from external float or double arrays:
4011 // these can load arbitrary representation of NaN.
4013 if (value()->IsConstant()) {
4017 if (value()->IsLoadKeyed()) {
4018 return IsExternalFloatOrDoubleElementsKind(
4019 HLoadKeyed::cast(value())->elements_kind());
4022 if (value()->IsChange()) {
4023 if (HChange::cast(value())->from().IsSmiOrInteger32()) {
4026 if (HChange::cast(value())->value()->type().IsSmi()) {
4034 #define H_CONSTANT_INT(val) \
4035 HConstant::New(zone, context, static_cast<int32_t>(val))
4036 #define H_CONSTANT_DOUBLE(val) \
4037 HConstant::New(zone, context, static_cast<double>(val))
4039 #define DEFINE_NEW_H_SIMPLE_ARITHMETIC_INSTR(HInstr, op) \
4040 HInstruction* HInstr::New( \
4041 Zone* zone, HValue* context, HValue* left, HValue* right) { \
4042 if (FLAG_fold_constants && left->IsConstant() && right->IsConstant()) { \
4043 HConstant* c_left = HConstant::cast(left); \
4044 HConstant* c_right = HConstant::cast(right); \
4045 if ((c_left->HasNumberValue() && c_right->HasNumberValue())) { \
4046 double double_res = c_left->DoubleValue() op c_right->DoubleValue(); \
4047 if (IsInt32Double(double_res)) { \
4048 return H_CONSTANT_INT(double_res); \
4050 return H_CONSTANT_DOUBLE(double_res); \
4053 return new(zone) HInstr(context, left, right); \
4057 DEFINE_NEW_H_SIMPLE_ARITHMETIC_INSTR(HAdd, +)
4058 DEFINE_NEW_H_SIMPLE_ARITHMETIC_INSTR(HMul, *)
4059 DEFINE_NEW_H_SIMPLE_ARITHMETIC_INSTR(HSub, -)
4061 #undef DEFINE_NEW_H_SIMPLE_ARITHMETIC_INSTR
4064 HInstruction* HStringAdd::New(Zone* zone,
4068 PretenureFlag pretenure_flag,
4069 StringAddFlags flags,
4070 Handle<AllocationSite> allocation_site) {
4071 if (FLAG_fold_constants && left->IsConstant() && right->IsConstant()) {
4072 HConstant* c_right = HConstant::cast(right);
4073 HConstant* c_left = HConstant::cast(left);
4074 if (c_left->HasStringValue() && c_right->HasStringValue()) {
4075 Handle<String> left_string = c_left->StringValue();
4076 Handle<String> right_string = c_right->StringValue();
4077 // Prevent possible exception by invalid string length.
4078 if (left_string->length() + right_string->length() < String::kMaxLength) {
4079 MaybeHandle<String> concat = zone->isolate()->factory()->NewConsString(
4080 c_left->StringValue(), c_right->StringValue());
4081 return HConstant::New(zone, context, concat.ToHandleChecked());
4085 return new(zone) HStringAdd(
4086 context, left, right, pretenure_flag, flags, allocation_site);
4090 OStream& HStringAdd::PrintDataTo(OStream& os) const { // NOLINT
4091 if ((flags() & STRING_ADD_CHECK_BOTH) == STRING_ADD_CHECK_BOTH) {
4093 } else if ((flags() & STRING_ADD_CHECK_BOTH) == STRING_ADD_CHECK_LEFT) {
4095 } else if ((flags() & STRING_ADD_CHECK_BOTH) == STRING_ADD_CHECK_RIGHT) {
4096 os << "_CheckRight";
4098 HBinaryOperation::PrintDataTo(os);
4100 if (pretenure_flag() == NOT_TENURED)
4102 else if (pretenure_flag() == TENURED)
4108 HInstruction* HStringCharFromCode::New(
4109 Zone* zone, HValue* context, HValue* char_code) {
4110 if (FLAG_fold_constants && char_code->IsConstant()) {
4111 HConstant* c_code = HConstant::cast(char_code);
4112 Isolate* isolate = zone->isolate();
4113 if (c_code->HasNumberValue()) {
4114 if (std::isfinite(c_code->DoubleValue())) {
4115 uint32_t code = c_code->NumberValueAsInteger32() & 0xffff;
4116 return HConstant::New(zone, context,
4117 isolate->factory()->LookupSingleCharacterStringFromCode(code));
4119 return HConstant::New(zone, context, isolate->factory()->empty_string());
4122 return new(zone) HStringCharFromCode(context, char_code);
4126 HInstruction* HUnaryMathOperation::New(
4127 Zone* zone, HValue* context, HValue* value, BuiltinFunctionId op) {
4129 if (!FLAG_fold_constants) break;
4130 if (!value->IsConstant()) break;
4131 HConstant* constant = HConstant::cast(value);
4132 if (!constant->HasNumberValue()) break;
4133 double d = constant->DoubleValue();
4134 if (std::isnan(d)) { // NaN poisons everything.
4135 return H_CONSTANT_DOUBLE(base::OS::nan_value());
4137 if (std::isinf(d)) { // +Infinity and -Infinity.
4140 return H_CONSTANT_DOUBLE((d > 0.0) ? d : 0.0);
4143 return H_CONSTANT_DOUBLE((d > 0.0) ? d : base::OS::nan_value());
4146 return H_CONSTANT_DOUBLE((d > 0.0) ? d : -d);
4150 return H_CONSTANT_DOUBLE(d);
4152 return H_CONSTANT_INT(32);
4160 return H_CONSTANT_DOUBLE(fast_exp(d));
4162 return H_CONSTANT_DOUBLE(std::log(d));
4164 return H_CONSTANT_DOUBLE(fast_sqrt(d));
4166 return H_CONSTANT_DOUBLE(power_double_double(d, 0.5));
4168 return H_CONSTANT_DOUBLE((d >= 0.0) ? d + 0.0 : -d);
4170 // -0.5 .. -0.0 round to -0.0.
4171 if ((d >= -0.5 && Double(d).Sign() < 0)) return H_CONSTANT_DOUBLE(-0.0);
4172 // Doubles are represented as Significant * 2 ^ Exponent. If the
4173 // Exponent is not negative, the double value is already an integer.
4174 if (Double(d).Exponent() >= 0) return H_CONSTANT_DOUBLE(d);
4175 return H_CONSTANT_DOUBLE(Floor(d + 0.5));
4177 return H_CONSTANT_DOUBLE(static_cast<double>(static_cast<float>(d)));
4179 return H_CONSTANT_DOUBLE(Floor(d));
4181 uint32_t i = DoubleToUint32(d);
4182 return H_CONSTANT_INT(
4183 (i == 0) ? 32 : CompilerIntrinsics::CountLeadingZeros(i));
4190 return new(zone) HUnaryMathOperation(context, value, op);
4194 Representation HUnaryMathOperation::RepresentationFromUses() {
4195 if (op_ != kMathFloor && op_ != kMathRound) {
4196 return HValue::RepresentationFromUses();
4199 // The instruction can have an int32 or double output. Prefer a double
4200 // representation if there are double uses.
4201 bool use_double = false;
4203 for (HUseIterator it(uses()); !it.Done(); it.Advance()) {
4204 HValue* use = it.value();
4205 int use_index = it.index();
4206 Representation rep_observed = use->observed_input_representation(use_index);
4207 Representation rep_required = use->RequiredInputRepresentation(use_index);
4208 use_double |= (rep_observed.IsDouble() || rep_required.IsDouble());
4209 if (use_double && !FLAG_trace_representation) {
4210 // Having seen one double is enough.
4213 if (FLAG_trace_representation) {
4214 if (!rep_required.IsDouble() || rep_observed.IsDouble()) {
4215 PrintF("#%d %s is used by #%d %s as %s%s\n",
4216 id(), Mnemonic(), use->id(),
4217 use->Mnemonic(), rep_observed.Mnemonic(),
4218 (use->CheckFlag(kTruncatingToInt32) ? "-trunc" : ""));
4220 PrintF("#%d %s is required by #%d %s as %s%s\n",
4221 id(), Mnemonic(), use->id(),
4222 use->Mnemonic(), rep_required.Mnemonic(),
4223 (use->CheckFlag(kTruncatingToInt32) ? "-trunc" : ""));
4227 return use_double ? Representation::Double() : Representation::Integer32();
4231 HInstruction* HPower::New(Zone* zone,
4235 if (FLAG_fold_constants && left->IsConstant() && right->IsConstant()) {
4236 HConstant* c_left = HConstant::cast(left);
4237 HConstant* c_right = HConstant::cast(right);
4238 if (c_left->HasNumberValue() && c_right->HasNumberValue()) {
4239 double result = power_helper(c_left->DoubleValue(),
4240 c_right->DoubleValue());
4241 return H_CONSTANT_DOUBLE(std::isnan(result) ? base::OS::nan_value()
4245 return new(zone) HPower(left, right);
4249 HInstruction* HMathMinMax::New(
4250 Zone* zone, HValue* context, HValue* left, HValue* right, Operation op) {
4251 if (FLAG_fold_constants && left->IsConstant() && right->IsConstant()) {
4252 HConstant* c_left = HConstant::cast(left);
4253 HConstant* c_right = HConstant::cast(right);
4254 if (c_left->HasNumberValue() && c_right->HasNumberValue()) {
4255 double d_left = c_left->DoubleValue();
4256 double d_right = c_right->DoubleValue();
4257 if (op == kMathMin) {
4258 if (d_left > d_right) return H_CONSTANT_DOUBLE(d_right);
4259 if (d_left < d_right) return H_CONSTANT_DOUBLE(d_left);
4260 if (d_left == d_right) {
4261 // Handle +0 and -0.
4262 return H_CONSTANT_DOUBLE((Double(d_left).Sign() == -1) ? d_left
4266 if (d_left < d_right) return H_CONSTANT_DOUBLE(d_right);
4267 if (d_left > d_right) return H_CONSTANT_DOUBLE(d_left);
4268 if (d_left == d_right) {
4269 // Handle +0 and -0.
4270 return H_CONSTANT_DOUBLE((Double(d_left).Sign() == -1) ? d_right
4274 // All comparisons failed, must be NaN.
4275 return H_CONSTANT_DOUBLE(base::OS::nan_value());
4278 return new(zone) HMathMinMax(context, left, right, op);
4282 HInstruction* HMod::New(Zone* zone,
4286 if (FLAG_fold_constants && left->IsConstant() && right->IsConstant()) {
4287 HConstant* c_left = HConstant::cast(left);
4288 HConstant* c_right = HConstant::cast(right);
4289 if (c_left->HasInteger32Value() && c_right->HasInteger32Value()) {
4290 int32_t dividend = c_left->Integer32Value();
4291 int32_t divisor = c_right->Integer32Value();
4292 if (dividend == kMinInt && divisor == -1) {
4293 return H_CONSTANT_DOUBLE(-0.0);
4296 int32_t res = dividend % divisor;
4297 if ((res == 0) && (dividend < 0)) {
4298 return H_CONSTANT_DOUBLE(-0.0);
4300 return H_CONSTANT_INT(res);
4304 return new(zone) HMod(context, left, right);
4308 HInstruction* HDiv::New(
4309 Zone* zone, HValue* context, HValue* left, HValue* right) {
4310 // If left and right are constant values, try to return a constant value.
4311 if (FLAG_fold_constants && left->IsConstant() && right->IsConstant()) {
4312 HConstant* c_left = HConstant::cast(left);
4313 HConstant* c_right = HConstant::cast(right);
4314 if ((c_left->HasNumberValue() && c_right->HasNumberValue())) {
4315 if (c_right->DoubleValue() != 0) {
4316 double double_res = c_left->DoubleValue() / c_right->DoubleValue();
4317 if (IsInt32Double(double_res)) {
4318 return H_CONSTANT_INT(double_res);
4320 return H_CONSTANT_DOUBLE(double_res);
4322 int sign = Double(c_left->DoubleValue()).Sign() *
4323 Double(c_right->DoubleValue()).Sign(); // Right could be -0.
4324 return H_CONSTANT_DOUBLE(sign * V8_INFINITY);
4328 return new(zone) HDiv(context, left, right);
4332 HInstruction* HBitwise::New(
4333 Zone* zone, HValue* context, Token::Value op, HValue* left, HValue* right) {
4334 if (FLAG_fold_constants && left->IsConstant() && right->IsConstant()) {
4335 HConstant* c_left = HConstant::cast(left);
4336 HConstant* c_right = HConstant::cast(right);
4337 if ((c_left->HasNumberValue() && c_right->HasNumberValue())) {
4339 int32_t v_left = c_left->NumberValueAsInteger32();
4340 int32_t v_right = c_right->NumberValueAsInteger32();
4342 case Token::BIT_XOR:
4343 result = v_left ^ v_right;
4345 case Token::BIT_AND:
4346 result = v_left & v_right;
4349 result = v_left | v_right;
4352 result = 0; // Please the compiler.
4355 return H_CONSTANT_INT(result);
4358 return new(zone) HBitwise(context, op, left, right);
4362 #define DEFINE_NEW_H_BITWISE_INSTR(HInstr, result) \
4363 HInstruction* HInstr::New( \
4364 Zone* zone, HValue* context, HValue* left, HValue* right) { \
4365 if (FLAG_fold_constants && left->IsConstant() && right->IsConstant()) { \
4366 HConstant* c_left = HConstant::cast(left); \
4367 HConstant* c_right = HConstant::cast(right); \
4368 if ((c_left->HasNumberValue() && c_right->HasNumberValue())) { \
4369 return H_CONSTANT_INT(result); \
4372 return new(zone) HInstr(context, left, right); \
4376 DEFINE_NEW_H_BITWISE_INSTR(HSar,
4377 c_left->NumberValueAsInteger32() >> (c_right->NumberValueAsInteger32() & 0x1f))
4378 DEFINE_NEW_H_BITWISE_INSTR(HShl,
4379 c_left->NumberValueAsInteger32() << (c_right->NumberValueAsInteger32() & 0x1f))
4381 #undef DEFINE_NEW_H_BITWISE_INSTR
4384 HInstruction* HShr::New(
4385 Zone* zone, HValue* context, HValue* left, HValue* right) {
4386 if (FLAG_fold_constants && left->IsConstant() && right->IsConstant()) {
4387 HConstant* c_left = HConstant::cast(left);
4388 HConstant* c_right = HConstant::cast(right);
4389 if ((c_left->HasNumberValue() && c_right->HasNumberValue())) {
4390 int32_t left_val = c_left->NumberValueAsInteger32();
4391 int32_t right_val = c_right->NumberValueAsInteger32() & 0x1f;
4392 if ((right_val == 0) && (left_val < 0)) {
4393 return H_CONSTANT_DOUBLE(static_cast<uint32_t>(left_val));
4395 return H_CONSTANT_INT(static_cast<uint32_t>(left_val) >> right_val);
4398 return new(zone) HShr(context, left, right);
4402 HInstruction* HSeqStringGetChar::New(Zone* zone,
4404 String::Encoding encoding,
4407 if (FLAG_fold_constants && string->IsConstant() && index->IsConstant()) {
4408 HConstant* c_string = HConstant::cast(string);
4409 HConstant* c_index = HConstant::cast(index);
4410 if (c_string->HasStringValue() && c_index->HasInteger32Value()) {
4411 Handle<String> s = c_string->StringValue();
4412 int32_t i = c_index->Integer32Value();
4414 DCHECK_LT(i, s->length());
4415 return H_CONSTANT_INT(s->Get(i));
4418 return new(zone) HSeqStringGetChar(encoding, string, index);
4422 #undef H_CONSTANT_INT
4423 #undef H_CONSTANT_DOUBLE
4426 OStream& HBitwise::PrintDataTo(OStream& os) const { // NOLINT
4427 os << Token::Name(op_) << " ";
4428 return HBitwiseBinaryOperation::PrintDataTo(os);
4432 void HPhi::SimplifyConstantInputs() {
4433 // Convert constant inputs to integers when all uses are truncating.
4434 // This must happen before representation inference takes place.
4435 if (!CheckUsesForFlag(kTruncatingToInt32)) return;
4436 for (int i = 0; i < OperandCount(); ++i) {
4437 if (!OperandAt(i)->IsConstant()) return;
4439 HGraph* graph = block()->graph();
4440 for (int i = 0; i < OperandCount(); ++i) {
4441 HConstant* operand = HConstant::cast(OperandAt(i));
4442 if (operand->HasInteger32Value()) {
4444 } else if (operand->HasDoubleValue()) {
4445 HConstant* integer_input =
4446 HConstant::New(graph->zone(), graph->GetInvalidContext(),
4447 DoubleToInt32(operand->DoubleValue()));
4448 integer_input->InsertAfter(operand);
4449 SetOperandAt(i, integer_input);
4450 } else if (operand->HasBooleanValue()) {
4451 SetOperandAt(i, operand->BooleanValue() ? graph->GetConstant1()
4452 : graph->GetConstant0());
4453 } else if (operand->ImmortalImmovable()) {
4454 SetOperandAt(i, graph->GetConstant0());
4457 // Overwrite observed input representations because they are likely Tagged.
4458 for (HUseIterator it(uses()); !it.Done(); it.Advance()) {
4459 HValue* use = it.value();
4460 if (use->IsBinaryOperation()) {
4461 HBinaryOperation::cast(use)->set_observed_input_representation(
4462 it.index(), Representation::Smi());
4468 void HPhi::InferRepresentation(HInferRepresentationPhase* h_infer) {
4469 DCHECK(CheckFlag(kFlexibleRepresentation));
4470 Representation new_rep = RepresentationFromInputs();
4471 UpdateRepresentation(new_rep, h_infer, "inputs");
4472 new_rep = RepresentationFromUses();
4473 UpdateRepresentation(new_rep, h_infer, "uses");
4474 new_rep = RepresentationFromUseRequirements();
4475 UpdateRepresentation(new_rep, h_infer, "use requirements");
4479 Representation HPhi::RepresentationFromInputs() {
4480 Representation r = Representation::None();
4481 for (int i = 0; i < OperandCount(); ++i) {
4482 r = r.generalize(OperandAt(i)->KnownOptimalRepresentation());
4488 // Returns a representation if all uses agree on the same representation.
4489 // Integer32 is also returned when some uses are Smi but others are Integer32.
4490 Representation HValue::RepresentationFromUseRequirements() {
4491 Representation rep = Representation::None();
4492 for (HUseIterator it(uses()); !it.Done(); it.Advance()) {
4493 // Ignore the use requirement from never run code
4494 if (it.value()->block()->IsUnreachable()) continue;
4496 // We check for observed_input_representation elsewhere.
4497 Representation use_rep =
4498 it.value()->RequiredInputRepresentation(it.index());
4503 if (use_rep.IsNone() || rep.Equals(use_rep)) continue;
4504 if (rep.generalize(use_rep).IsInteger32()) {
4505 rep = Representation::Integer32();
4508 return Representation::None();
4514 bool HValue::HasNonSmiUse() {
4515 for (HUseIterator it(uses()); !it.Done(); it.Advance()) {
4516 // We check for observed_input_representation elsewhere.
4517 Representation use_rep =
4518 it.value()->RequiredInputRepresentation(it.index());
4519 if (!use_rep.IsNone() &&
4521 !use_rep.IsTagged()) {
4529 // Node-specific verification code is only included in debug mode.
4532 void HPhi::Verify() {
4533 DCHECK(OperandCount() == block()->predecessors()->length());
4534 for (int i = 0; i < OperandCount(); ++i) {
4535 HValue* value = OperandAt(i);
4536 HBasicBlock* defining_block = value->block();
4537 HBasicBlock* predecessor_block = block()->predecessors()->at(i);
4538 DCHECK(defining_block == predecessor_block ||
4539 defining_block->Dominates(predecessor_block));
4544 void HSimulate::Verify() {
4545 HInstruction::Verify();
4546 DCHECK(HasAstId() || next()->IsEnterInlined());
4550 void HCheckHeapObject::Verify() {
4551 HInstruction::Verify();
4552 DCHECK(HasNoUses());
4556 void HCheckValue::Verify() {
4557 HInstruction::Verify();
4558 DCHECK(HasNoUses());
4564 HObjectAccess HObjectAccess::ForFixedArrayHeader(int offset) {
4565 DCHECK(offset >= 0);
4566 DCHECK(offset < FixedArray::kHeaderSize);
4567 if (offset == FixedArray::kLengthOffset) return ForFixedArrayLength();
4568 return HObjectAccess(kInobject, offset);
4572 HObjectAccess HObjectAccess::ForMapAndOffset(Handle<Map> map, int offset,
4573 Representation representation) {
4574 DCHECK(offset >= 0);
4575 Portion portion = kInobject;
4577 if (offset == JSObject::kElementsOffset) {
4578 portion = kElementsPointer;
4579 } else if (offset == JSObject::kMapOffset) {
4582 bool existing_inobject_property = true;
4583 if (!map.is_null()) {
4584 existing_inobject_property = (offset <
4585 map->instance_size() - map->unused_property_fields() * kPointerSize);
4587 return HObjectAccess(portion, offset, representation, Handle<String>::null(),
4588 false, existing_inobject_property);
4592 HObjectAccess HObjectAccess::ForAllocationSiteOffset(int offset) {
4594 case AllocationSite::kTransitionInfoOffset:
4595 return HObjectAccess(kInobject, offset, Representation::Tagged());
4596 case AllocationSite::kNestedSiteOffset:
4597 return HObjectAccess(kInobject, offset, Representation::Tagged());
4598 case AllocationSite::kPretenureDataOffset:
4599 return HObjectAccess(kInobject, offset, Representation::Smi());
4600 case AllocationSite::kPretenureCreateCountOffset:
4601 return HObjectAccess(kInobject, offset, Representation::Smi());
4602 case AllocationSite::kDependentCodeOffset:
4603 return HObjectAccess(kInobject, offset, Representation::Tagged());
4604 case AllocationSite::kWeakNextOffset:
4605 return HObjectAccess(kInobject, offset, Representation::Tagged());
4609 return HObjectAccess(kInobject, offset);
4613 HObjectAccess HObjectAccess::ForContextSlot(int index) {
4615 Portion portion = kInobject;
4616 int offset = Context::kHeaderSize + index * kPointerSize;
4617 DCHECK_EQ(offset, Context::SlotOffset(index) + kHeapObjectTag);
4618 return HObjectAccess(portion, offset, Representation::Tagged());
4622 HObjectAccess HObjectAccess::ForJSArrayOffset(int offset) {
4623 DCHECK(offset >= 0);
4624 Portion portion = kInobject;
4626 if (offset == JSObject::kElementsOffset) {
4627 portion = kElementsPointer;
4628 } else if (offset == JSArray::kLengthOffset) {
4629 portion = kArrayLengths;
4630 } else if (offset == JSObject::kMapOffset) {
4633 return HObjectAccess(portion, offset);
4637 HObjectAccess HObjectAccess::ForBackingStoreOffset(int offset,
4638 Representation representation) {
4639 DCHECK(offset >= 0);
4640 return HObjectAccess(kBackingStore, offset, representation,
4641 Handle<String>::null(), false, false);
4645 HObjectAccess HObjectAccess::ForField(Handle<Map> map,
4646 LookupResult* lookup,
4647 Handle<String> name) {
4648 DCHECK(lookup->IsField() || lookup->IsTransitionToField());
4650 Representation representation;
4651 if (lookup->IsField()) {
4652 index = lookup->GetLocalFieldIndexFromMap(*map);
4653 representation = lookup->representation();
4655 Map* transition = lookup->GetTransitionTarget();
4656 int descriptor = transition->LastAdded();
4657 index = transition->instance_descriptors()->GetFieldIndex(descriptor) -
4658 map->inobject_properties();
4659 PropertyDetails details =
4660 transition->instance_descriptors()->GetDetails(descriptor);
4661 representation = details.representation();
4664 // Negative property indices are in-object properties, indexed
4665 // from the end of the fixed part of the object.
4666 int offset = (index * kPointerSize) + map->instance_size();
4667 return HObjectAccess(kInobject, offset, representation, name, false, true);
4669 // Non-negative property indices are in the properties array.
4670 int offset = (index * kPointerSize) + FixedArray::kHeaderSize;
4671 return HObjectAccess(kBackingStore, offset, representation, name,
4677 HObjectAccess HObjectAccess::ForCellPayload(Isolate* isolate) {
4678 return HObjectAccess(
4679 kInobject, Cell::kValueOffset, Representation::Tagged(),
4680 Handle<String>(isolate->heap()->cell_value_string()));
4684 void HObjectAccess::SetGVNFlags(HValue *instr, PropertyAccessType access_type) {
4685 // set the appropriate GVN flags for a given load or store instruction
4686 if (access_type == STORE) {
4687 // track dominating allocations in order to eliminate write barriers
4688 instr->SetDependsOnFlag(::v8::internal::kNewSpacePromotion);
4689 instr->SetFlag(HValue::kTrackSideEffectDominators);
4691 // try to GVN loads, but don't hoist above map changes
4692 instr->SetFlag(HValue::kUseGVN);
4693 instr->SetDependsOnFlag(::v8::internal::kMaps);
4696 switch (portion()) {
4698 if (access_type == STORE) {
4699 instr->SetChangesFlag(::v8::internal::kArrayLengths);
4701 instr->SetDependsOnFlag(::v8::internal::kArrayLengths);
4704 case kStringLengths:
4705 if (access_type == STORE) {
4706 instr->SetChangesFlag(::v8::internal::kStringLengths);
4708 instr->SetDependsOnFlag(::v8::internal::kStringLengths);
4712 if (access_type == STORE) {
4713 instr->SetChangesFlag(::v8::internal::kInobjectFields);
4715 instr->SetDependsOnFlag(::v8::internal::kInobjectFields);
4719 if (access_type == STORE) {
4720 instr->SetChangesFlag(::v8::internal::kDoubleFields);
4722 instr->SetDependsOnFlag(::v8::internal::kDoubleFields);
4726 if (access_type == STORE) {
4727 instr->SetChangesFlag(::v8::internal::kBackingStoreFields);
4729 instr->SetDependsOnFlag(::v8::internal::kBackingStoreFields);
4732 case kElementsPointer:
4733 if (access_type == STORE) {
4734 instr->SetChangesFlag(::v8::internal::kElementsPointer);
4736 instr->SetDependsOnFlag(::v8::internal::kElementsPointer);
4740 if (access_type == STORE) {
4741 instr->SetChangesFlag(::v8::internal::kMaps);
4743 instr->SetDependsOnFlag(::v8::internal::kMaps);
4746 case kExternalMemory:
4747 if (access_type == STORE) {
4748 instr->SetChangesFlag(::v8::internal::kExternalMemory);
4750 instr->SetDependsOnFlag(::v8::internal::kExternalMemory);
4757 OStream& operator<<(OStream& os, const HObjectAccess& access) {
4760 switch (access.portion()) {
4761 case HObjectAccess::kArrayLengths:
4762 case HObjectAccess::kStringLengths:
4765 case HObjectAccess::kElementsPointer:
4768 case HObjectAccess::kMaps:
4771 case HObjectAccess::kDouble: // fall through
4772 case HObjectAccess::kInobject:
4773 if (!access.name().is_null()) {
4774 os << Handle<String>::cast(access.name())->ToCString().get();
4776 os << "[in-object]";
4778 case HObjectAccess::kBackingStore:
4779 if (!access.name().is_null()) {
4780 os << Handle<String>::cast(access.name())->ToCString().get();
4782 os << "[backing-store]";
4784 case HObjectAccess::kExternalMemory:
4785 os << "[external-memory]";
4789 return os << "@" << access.offset();
4792 } } // namespace v8::internal