1 // Copyright 2012 the V8 project authors. All rights reserved.
2 // Redistribution and use in source and binary forms, with or without
3 // modification, are permitted provided that the following conditions are
6 // * Redistributions of source code must retain the above copyright
7 // notice, this list of conditions and the following disclaimer.
8 // * Redistributions in binary form must reproduce the above
9 // copyright notice, this list of conditions and the following
10 // disclaimer in the documentation and/or other materials provided
11 // with the distribution.
12 // * Neither the name of Google Inc. nor the names of its
13 // contributors may be used to endorse or promote products derived
14 // from this software without specific prior written permission.
16 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 #include "accessors.h"
32 #include "arguments.h"
34 #include "execution.h"
37 #include "stub-cache.h"
38 #include "v8conversions.h"
44 char IC::TransitionMarkFromState(IC::State state) {
46 case UNINITIALIZED: return '0';
47 case PREMONOMORPHIC: return '.';
48 case MONOMORPHIC: return '1';
49 case MONOMORPHIC_PROTOTYPE_FAILURE: return '^';
50 case POLYMORPHIC: return 'P';
51 case MEGAMORPHIC: return 'N';
52 case GENERIC: return 'G';
54 // We never see the debugger states here, because the state is
55 // computed from the original code - not the patched code. Let
56 // these cases fall through to the unreachable code below.
57 case DEBUG_STUB: break;
64 const char* GetTransitionMarkModifier(KeyedAccessStoreMode mode) {
65 if (mode == STORE_NO_TRANSITION_HANDLE_COW) return ".COW";
66 if (mode == STORE_NO_TRANSITION_IGNORE_OUT_OF_BOUNDS) {
69 if (IsGrowStoreMode(mode)) return ".GROW";
74 void IC::TraceIC(const char* type,
75 Handle<Object> name) {
77 Code* new_target = raw_target();
78 State new_state = new_target->ic_state();
79 PrintF("[%s%s in ", new_target->is_keyed_stub() ? "Keyed" : "", type);
80 StackFrameIterator it(isolate());
81 while (it.frame()->fp() != this->fp()) it.Advance();
82 StackFrame* raw_frame = it.frame();
83 if (raw_frame->is_internal()) {
84 Code* apply_builtin = isolate()->builtins()->builtin(
85 Builtins::kFunctionApply);
86 if (raw_frame->unchecked_code() == apply_builtin) {
87 PrintF("apply from ");
89 raw_frame = it.frame();
92 JavaScriptFrame::PrintTop(isolate(), stdout, false, true);
93 ExtraICState extra_state = new_target->extra_ic_state();
94 const char* modifier =
95 GetTransitionMarkModifier(
96 KeyedStoreIC::GetKeyedAccessStoreMode(extra_state));
98 TransitionMarkFromState(state()),
99 TransitionMarkFromState(new_state),
106 #define TRACE_GENERIC_IC(isolate, type, reason) \
108 if (FLAG_trace_ic) { \
109 PrintF("[%s patching generic stub in ", type); \
110 JavaScriptFrame::PrintTop(isolate, stdout, false, true); \
111 PrintF(" (%s)]\n", reason); \
116 #define TRACE_GENERIC_IC(isolate, type, reason)
119 #define TRACE_IC(type, name) \
120 ASSERT((TraceIC(type, name), true))
122 IC::IC(FrameDepth depth, Isolate* isolate)
125 // To improve the performance of the (much used) IC code, we unfold a few
126 // levels of the stack frame iteration code. This yields a ~35% speedup when
127 // running DeltaBlue and a ~25% speedup of gbemu with the '--nouse-ic' flag.
128 const Address entry =
129 Isolate::c_entry_fp(isolate->thread_local_top());
130 Address* pc_address =
131 reinterpret_cast<Address*>(entry + ExitFrameConstants::kCallerPCOffset);
132 Address fp = Memory::Address_at(entry + ExitFrameConstants::kCallerFPOffset);
133 // If there's another JavaScript frame on the stack or a
134 // StubFailureTrampoline, we need to look one frame further down the stack to
135 // find the frame pointer and the return address stack slot.
136 if (depth == EXTRA_CALL_FRAME) {
137 const int kCallerPCOffset = StandardFrameConstants::kCallerPCOffset;
138 pc_address = reinterpret_cast<Address*>(fp + kCallerPCOffset);
139 fp = Memory::Address_at(fp + StandardFrameConstants::kCallerFPOffset);
142 StackFrameIterator it(isolate);
143 for (int i = 0; i < depth + 1; i++) it.Advance();
144 StackFrame* frame = it.frame();
145 ASSERT(fp == frame->fp() && pc_address == frame->pc_address());
148 pc_address_ = StackFrame::ResolveReturnAddressLocation(pc_address);
149 target_ = handle(raw_target(), isolate);
150 state_ = target_->ic_state();
151 extra_ic_state_ = target_->needs_extended_extra_ic_state(target_->kind())
152 ? target_->extended_extra_ic_state()
153 : target_->extra_ic_state();
157 #ifdef ENABLE_DEBUGGER_SUPPORT
158 Address IC::OriginalCodeAddress() const {
159 HandleScope scope(isolate());
160 // Compute the JavaScript frame for the frame pointer of this IC
161 // structure. We need this to be able to find the function
162 // corresponding to the frame.
163 StackFrameIterator it(isolate());
164 while (it.frame()->fp() != this->fp()) it.Advance();
165 JavaScriptFrame* frame = JavaScriptFrame::cast(it.frame());
166 // Find the function on the stack and both the active code for the
167 // function and the original code.
168 JSFunction* function = frame->function();
169 Handle<SharedFunctionInfo> shared(function->shared(), isolate());
170 Code* code = shared->code();
171 ASSERT(Debug::HasDebugInfo(shared));
172 Code* original_code = Debug::GetDebugInfo(shared)->original_code();
173 ASSERT(original_code->IsCode());
174 // Get the address of the call site in the active code. This is the
175 // place where the call to DebugBreakXXX is and where the IC
176 // normally would be.
177 Address addr = Assembler::target_address_from_return_address(pc());
178 // Return the address in the original code. This is the place where
179 // the call which has been overwritten by the DebugBreakXXX resides
180 // and the place where the inline cache system should look.
182 original_code->instruction_start() - code->instruction_start();
188 static bool HasInterceptorGetter(JSObject* object) {
189 return !object->GetNamedInterceptor()->getter()->IsUndefined();
193 static bool HasInterceptorSetter(JSObject* object) {
194 return !object->GetNamedInterceptor()->setter()->IsUndefined();
198 static void LookupForRead(Handle<Object> object,
200 LookupResult* lookup) {
201 // Skip all the objects with named interceptors, but
202 // without actual getter.
204 object->Lookup(*name, lookup);
205 // Besides normal conditions (property not found or it's not
206 // an interceptor), bail out if lookup is not cacheable: we won't
207 // be able to IC it anyway and regular lookup should work fine.
208 if (!lookup->IsInterceptor() || !lookup->IsCacheable()) {
212 Handle<JSObject> holder(lookup->holder(), lookup->isolate());
213 if (HasInterceptorGetter(*holder)) {
217 holder->LocalLookupRealNamedProperty(*name, lookup);
218 if (lookup->IsFound()) {
219 ASSERT(!lookup->IsInterceptor());
223 Handle<Object> proto(holder->GetPrototype(), lookup->isolate());
224 if (proto->IsNull()) {
225 ASSERT(!lookup->IsFound());
234 bool IC::TryRemoveInvalidPrototypeDependentStub(Handle<Object> receiver,
235 Handle<String> name) {
236 if (target()->is_keyed_stub()) {
237 // Determine whether the failure is due to a name failure.
238 if (!name->IsName()) return false;
239 Name* stub_name = target()->FindFirstName();
240 if (*name != stub_name) return false;
243 InlineCacheHolderFlag cache_holder =
244 Code::ExtractCacheHolderFromFlags(target()->flags());
246 switch (cache_holder) {
248 // The stub was generated for JSObject but called for non-JSObject.
249 // IC::GetCodeCacheHolder is not applicable.
250 if (!receiver->IsJSObject()) return false;
253 // IC::GetCodeCacheHolder is not applicable.
254 if (receiver->GetPrototype(isolate())->IsNull()) return false;
259 IC::GetCodeCacheHolder(isolate(), *receiver, cache_holder)->map());
261 // Decide whether the inline cache failed because of changes to the
262 // receiver itself or changes to one of its prototypes.
264 // If there are changes to the receiver itself, the map of the
265 // receiver will have changed and the current target will not be in
266 // the receiver map's code cache. Therefore, if the current target
267 // is in the receiver map's code cache, the inline cache failed due
268 // to prototype check failure.
269 int index = map->IndexInCodeCache(*name, *target());
271 map->RemoveFromCodeCache(*name, *target(), index);
272 // Handlers are stored in addition to the ICs on the map. Remove those, too.
273 TryRemoveInvalidHandlers(map, name);
277 // The stub is not in the cache. We've ruled out all other kinds of failure
278 // except for proptotype chain changes, a deprecated map, a map that's
279 // different from the one that the stub expects, elements kind changes, or a
280 // constant global property that will become mutable. Threat all those
281 // situations as prototype failures (stay monomorphic if possible).
283 // If the IC is shared between multiple receivers (slow dictionary mode), then
284 // the map cannot be deprecated and the stub invalidated.
285 if (cache_holder == OWN_MAP) {
286 Map* old_map = target()->FindFirstMap();
287 if (old_map == *map) return true;
288 if (old_map != NULL) {
289 if (old_map->is_deprecated()) return true;
290 if (IsMoreGeneralElementsKindTransition(old_map->elements_kind(),
291 map->elements_kind())) {
297 if (receiver->IsGlobalObject()) {
298 LookupResult lookup(isolate());
299 GlobalObject* global = GlobalObject::cast(*receiver);
300 global->LocalLookupRealNamedProperty(*name, &lookup);
301 if (!lookup.IsFound()) return false;
302 PropertyCell* cell = global->GetPropertyCell(&lookup);
303 return cell->type()->IsConstant();
310 void IC::TryRemoveInvalidHandlers(Handle<Map> map, Handle<String> name) {
311 CodeHandleList handlers;
312 target()->FindHandlers(&handlers);
313 for (int i = 0; i < handlers.length(); i++) {
314 Handle<Code> handler = handlers.at(i);
315 int index = map->IndexInCodeCache(*name, *handler);
317 map->RemoveFromCodeCache(*name, *handler, index);
324 void IC::UpdateState(Handle<Object> receiver, Handle<Object> name) {
325 if (!name->IsString()) return;
326 if (state() != MONOMORPHIC) {
327 if (state() == POLYMORPHIC && receiver->IsHeapObject()) {
328 TryRemoveInvalidHandlers(
329 handle(Handle<HeapObject>::cast(receiver)->map()),
330 Handle<String>::cast(name));
334 if (receiver->IsUndefined() || receiver->IsNull()) return;
336 // Remove the target from the code cache if it became invalid
337 // because of changes in the prototype chain to avoid hitting it
339 if (TryRemoveInvalidPrototypeDependentStub(
340 receiver, Handle<String>::cast(name))) {
341 return MarkMonomorphicPrototypeFailure();
344 // The builtins object is special. It only changes when JavaScript
345 // builtins are loaded lazily. It is important to keep inline
346 // caches for the builtins object monomorphic. Therefore, if we get
347 // an inline cache miss for the builtins object after lazily loading
348 // JavaScript builtins, we return uninitialized as the state to
349 // force the inline cache back to monomorphic state.
350 if (receiver->IsJSBuiltinsObject()) state_ = UNINITIALIZED;
354 Failure* IC::TypeError(const char* type,
355 Handle<Object> object,
356 Handle<Object> key) {
357 HandleScope scope(isolate());
358 Handle<Object> args[2] = { key, object };
359 Handle<Object> error = isolate()->factory()->NewTypeError(
360 type, HandleVector(args, 2));
361 return isolate()->Throw(*error);
365 Failure* IC::ReferenceError(const char* type, Handle<String> name) {
366 HandleScope scope(isolate());
367 Handle<Object> error = isolate()->factory()->NewReferenceError(
368 type, HandleVector(&name, 1));
369 return isolate()->Throw(*error);
373 static int ComputeTypeInfoCountDelta(IC::State old_state, IC::State new_state) {
374 bool was_uninitialized =
375 old_state == UNINITIALIZED || old_state == PREMONOMORPHIC;
376 bool is_uninitialized =
377 new_state == UNINITIALIZED || new_state == PREMONOMORPHIC;
378 return (was_uninitialized && !is_uninitialized) ? 1 :
379 (!was_uninitialized && is_uninitialized) ? -1 : 0;
383 void IC::PostPatching(Address address, Code* target, Code* old_target) {
384 Isolate* isolate = target->GetHeap()->isolate();
385 Code* host = isolate->
386 inner_pointer_to_code_cache()->GetCacheEntry(address)->code;
387 if (host->kind() != Code::FUNCTION) return;
389 if (FLAG_type_info_threshold > 0 &&
390 old_target->is_inline_cache_stub() &&
391 target->is_inline_cache_stub()) {
392 int delta = ComputeTypeInfoCountDelta(old_target->ic_state(),
394 // Not all Code objects have TypeFeedbackInfo.
395 if (host->type_feedback_info()->IsTypeFeedbackInfo() && delta != 0) {
396 TypeFeedbackInfo* info =
397 TypeFeedbackInfo::cast(host->type_feedback_info());
398 info->change_ic_with_type_info_count(delta);
401 if (host->type_feedback_info()->IsTypeFeedbackInfo()) {
402 TypeFeedbackInfo* info =
403 TypeFeedbackInfo::cast(host->type_feedback_info());
404 info->change_own_type_change_checksum();
406 host->set_profiler_ticks(0);
407 isolate->runtime_profiler()->NotifyICChanged();
408 // TODO(2029): When an optimized function is patched, it would
409 // be nice to propagate the corresponding type information to its
410 // unoptimized version for the benefit of later inlining.
414 void IC::Clear(Isolate* isolate, Address address) {
415 Code* target = GetTargetAtAddress(address);
417 // Don't clear debug break inline cache as it will remove the break point.
418 if (target->is_debug_stub()) return;
420 switch (target->kind()) {
421 case Code::LOAD_IC: return LoadIC::Clear(isolate, address, target);
422 case Code::KEYED_LOAD_IC:
423 return KeyedLoadIC::Clear(isolate, address, target);
424 case Code::STORE_IC: return StoreIC::Clear(isolate, address, target);
425 case Code::KEYED_STORE_IC:
426 return KeyedStoreIC::Clear(isolate, address, target);
427 case Code::CALL_IC: return CallIC::Clear(address, target);
428 case Code::KEYED_CALL_IC: return KeyedCallIC::Clear(address, target);
429 case Code::COMPARE_IC: return CompareIC::Clear(isolate, address, target);
430 case Code::COMPARE_NIL_IC: return CompareNilIC::Clear(address, target);
431 case Code::BINARY_OP_IC:
432 case Code::TO_BOOLEAN_IC:
433 // Clearing these is tricky and does not
434 // make any performance difference.
436 default: UNREACHABLE();
441 void CallICBase::Clear(Address address, Code* target) {
442 if (IsCleared(target)) return;
443 Code* code = target->GetIsolate()->stub_cache()->FindCallInitialize(
444 target->arguments_count(), target->kind());
445 SetTargetAtAddress(address, code);
449 void KeyedLoadIC::Clear(Isolate* isolate, Address address, Code* target) {
450 if (IsCleared(target)) return;
451 // Make sure to also clear the map used in inline fast cases. If we
452 // do not clear these maps, cached code can keep objects alive
453 // through the embedded maps.
454 SetTargetAtAddress(address, *pre_monomorphic_stub(isolate));
458 void LoadIC::Clear(Isolate* isolate, Address address, Code* target) {
459 if (IsCleared(target)) return;
460 Code* code = target->GetIsolate()->stub_cache()->FindPreMonomorphicIC(
461 Code::LOAD_IC, target->extra_ic_state());
462 SetTargetAtAddress(address, code);
466 void StoreIC::Clear(Isolate* isolate, Address address, Code* target) {
467 if (IsCleared(target)) return;
468 Code* code = target->GetIsolate()->stub_cache()->FindPreMonomorphicIC(
469 Code::STORE_IC, target->extra_ic_state());
470 SetTargetAtAddress(address, code);
474 void KeyedStoreIC::Clear(Isolate* isolate, Address address, Code* target) {
475 if (IsCleared(target)) return;
476 SetTargetAtAddress(address,
477 *pre_monomorphic_stub(
478 isolate, StoreIC::GetStrictMode(target->extra_ic_state())));
482 void CompareIC::Clear(Isolate* isolate, Address address, Code* target) {
483 ASSERT(target->major_key() == CodeStub::CompareIC);
484 CompareIC::State handler_state;
486 ICCompareStub::DecodeMinorKey(target->stub_info(), NULL, NULL,
487 &handler_state, &op);
488 // Only clear CompareICs that can retain objects.
489 if (handler_state != KNOWN_OBJECT) return;
490 SetTargetAtAddress(address, GetRawUninitialized(isolate, op));
491 PatchInlinedSmiCode(address, DISABLE_INLINED_SMI_CHECK);
495 Handle<Object> CallICBase::TryCallAsFunction(Handle<Object> object) {
496 Handle<Object> delegate = Execution::GetFunctionDelegate(isolate(), object);
498 if (delegate->IsJSFunction() && !object->IsJSFunctionProxy()) {
499 // Patch the receiver and use the delegate as the function to
500 // invoke. This is used for invoking objects as if they were functions.
501 const int argc = target()->arguments_count();
502 StackFrameLocator locator(isolate());
503 JavaScriptFrame* frame = locator.FindJavaScriptFrame(0);
504 int index = frame->ComputeExpressionsCount() - (argc + 1);
505 frame->SetExpression(index, *object);
512 void CallICBase::ReceiverToObjectIfRequired(Handle<Object> callee,
513 Handle<Object> object) {
514 while (callee->IsJSFunctionProxy()) {
515 callee = Handle<Object>(JSFunctionProxy::cast(*callee)->call_trap(),
519 if (callee->IsJSFunction()) {
520 Handle<JSFunction> function = Handle<JSFunction>::cast(callee);
521 if (!function->shared()->is_classic_mode() || function->IsBuiltin()) {
522 // Do not wrap receiver for strict mode functions or for builtins.
527 // And only wrap string, number or boolean.
528 if (object->IsString() || object->IsNumber() || object->IsBoolean()) {
529 // Change the receiver to the result of calling ToObject on it.
530 const int argc = this->target()->arguments_count();
531 StackFrameLocator locator(isolate());
532 JavaScriptFrame* frame = locator.FindJavaScriptFrame(0);
533 int index = frame->ComputeExpressionsCount() - (argc + 1);
534 frame->SetExpression(index, *isolate()->factory()->ToObject(object));
539 static bool MigrateDeprecated(Handle<Object> object) {
540 if (!object->IsJSObject()) return false;
541 Handle<JSObject> receiver = Handle<JSObject>::cast(object);
542 if (!receiver->map()->is_deprecated()) return false;
543 JSObject::MigrateInstance(Handle<JSObject>::cast(object));
548 MaybeObject* CallICBase::LoadFunction(Handle<Object> object,
549 Handle<String> name) {
550 bool use_ic = MigrateDeprecated(object) ? false : FLAG_use_ic;
552 // If the object is undefined or null it's illegal to try to get any
553 // of its properties; throw a TypeError in that case.
554 if (object->IsUndefined() || object->IsNull()) {
555 return TypeError("non_object_property_call", object, name);
558 // Check if the name is trivially convertible to an index and get
559 // the element if so.
561 if (name->AsArrayIndex(&index)) {
562 Handle<Object> result = Object::GetElement(isolate(), object, index);
563 RETURN_IF_EMPTY_HANDLE(isolate(), result);
564 if (result->IsJSFunction()) return *result;
566 // Try to find a suitable function delegate for the object at hand.
567 result = TryCallAsFunction(result);
568 if (result->IsJSFunction()) return *result;
570 // Otherwise, it will fail in the lookup step.
573 // Lookup the property in the object.
574 LookupResult lookup(isolate());
575 LookupForRead(object, name, &lookup);
577 if (!lookup.IsFound()) {
578 // If the object does not have the requested property, check which
579 // exception we need to throw.
580 return object->IsGlobalObject()
581 ? ReferenceError("not_defined", name)
582 : TypeError("undefined_method", object, name);
585 // Lookup is valid: Update inline cache and stub cache.
586 if (use_ic) UpdateCaches(&lookup, object, name);
589 PropertyAttributes attr;
590 Handle<Object> result =
591 Object::GetProperty(object, object, &lookup, name, &attr);
592 RETURN_IF_EMPTY_HANDLE(isolate(), result);
594 if (lookup.IsInterceptor() && attr == ABSENT) {
595 // If the object does not have the requested property, check which
596 // exception we need to throw.
597 return object->IsGlobalObject()
598 ? ReferenceError("not_defined", name)
599 : TypeError("undefined_method", object, name);
602 ASSERT(!result->IsTheHole());
604 // Make receiver an object if the callee requires it. Strict mode or builtin
605 // functions do not wrap the receiver, non-strict functions and objects
606 // called as functions do.
607 ReceiverToObjectIfRequired(result, object);
609 if (result->IsJSFunction()) {
610 Handle<JSFunction> function = Handle<JSFunction>::cast(result);
611 #ifdef ENABLE_DEBUGGER_SUPPORT
612 // Handle stepping into a function if step into is active.
613 Debug* debug = isolate()->debug();
614 if (debug->StepInActive()) {
615 // Protect the result in a handle as the debugger can allocate and might
617 debug->HandleStepIn(function, object, fp(), false);
623 // Try to find a suitable function delegate for the object at hand.
624 result = TryCallAsFunction(result);
625 if (result->IsJSFunction()) return *result;
627 return TypeError("property_not_function", object, name);
631 Handle<Code> CallICBase::ComputeMonomorphicStub(LookupResult* lookup,
632 Handle<Object> object,
633 Handle<String> name) {
634 int argc = target()->arguments_count();
635 Handle<JSObject> holder(lookup->holder(), isolate());
636 switch (lookup->type()) {
638 PropertyIndex index = lookup->GetFieldIndex();
639 return isolate()->stub_cache()->ComputeCallField(
640 argc, kind_, extra_ic_state(), name, object, holder, index);
643 if (!lookup->IsConstantFunction()) return Handle<Code>::null();
644 // Get the constant function and compute the code stub for this
645 // call; used for rewriting to monomorphic state and making sure
646 // that the code stub is in the stub cache.
647 Handle<JSFunction> function(lookup->GetConstantFunction(), isolate());
648 return isolate()->stub_cache()->ComputeCallConstant(
649 argc, kind_, extra_ic_state(), name, object, holder, function);
652 // If we return a null handle, the IC will not be patched.
653 if (!object->IsJSObject()) return Handle<Code>::null();
654 Handle<JSObject> receiver = Handle<JSObject>::cast(object);
656 if (holder->IsGlobalObject()) {
657 Handle<GlobalObject> global = Handle<GlobalObject>::cast(holder);
658 Handle<PropertyCell> cell(
659 global->GetPropertyCell(lookup), isolate());
660 if (!cell->value()->IsJSFunction()) return Handle<Code>::null();
661 Handle<JSFunction> function(JSFunction::cast(cell->value()));
662 return isolate()->stub_cache()->ComputeCallGlobal(
663 argc, kind_, extra_ic_state(), name,
664 receiver, global, cell, function);
666 // There is only one shared stub for calling normalized
667 // properties. It does not traverse the prototype chain, so the
668 // property must be found in the receiver for the stub to be
670 if (!holder.is_identical_to(receiver)) return Handle<Code>::null();
671 return isolate()->stub_cache()->ComputeCallNormal(
672 argc, kind_, extra_ic_state());
677 ASSERT(HasInterceptorGetter(*holder));
678 return isolate()->stub_cache()->ComputeCallInterceptor(
679 argc, kind_, extra_ic_state(), name, object, holder);
681 return Handle<Code>::null();
686 Handle<Code> CallICBase::megamorphic_stub() {
687 return isolate()->stub_cache()->ComputeCallMegamorphic(
688 target()->arguments_count(), kind_, extra_ic_state());
692 Handle<Code> CallICBase::pre_monomorphic_stub() {
693 return isolate()->stub_cache()->ComputeCallPreMonomorphic(
694 target()->arguments_count(), kind_, extra_ic_state());
698 void CallICBase::UpdateCaches(LookupResult* lookup,
699 Handle<Object> object,
700 Handle<String> name) {
701 // Bail out if we didn't find a result.
702 if (!lookup->IsProperty() || !lookup->IsCacheable()) return;
704 if (state() == UNINITIALIZED) {
705 set_target(*pre_monomorphic_stub());
706 TRACE_IC("CallIC", name);
710 Handle<Code> code = ComputeMonomorphicStub(lookup, object, name);
711 // If there's no appropriate stub we simply avoid updating the caches.
712 // TODO(verwaest): Install a slow fallback in this case to avoid not learning,
713 // and deopting Crankshaft code.
714 if (code.is_null()) return;
716 Handle<JSObject> cache_object = object->IsJSObject()
717 ? Handle<JSObject>::cast(object)
718 : Handle<JSObject>(JSObject::cast(object->GetPrototype(isolate())),
721 PatchCache(CurrentTypeOf(cache_object, isolate()), name, code);
722 TRACE_IC("CallIC", name);
726 MaybeObject* KeyedCallIC::LoadFunction(Handle<Object> object,
727 Handle<Object> key) {
728 if (key->IsInternalizedString()) {
729 return CallICBase::LoadFunction(object, Handle<String>::cast(key));
732 if (object->IsUndefined() || object->IsNull()) {
733 return TypeError("non_object_property_call", object, key);
736 bool use_ic = MigrateDeprecated(object)
737 ? false : FLAG_use_ic && !object->IsAccessCheckNeeded();
739 if (use_ic && state() != MEGAMORPHIC) {
740 ASSERT(!object->IsJSGlobalProxy());
741 int argc = target()->arguments_count();
744 // Use the KeyedArrayCallStub if the call is of the form array[smi](...),
745 // where array is an instance of one of the initial array maps (without
746 // extra named properties).
747 // TODO(verwaest): Also support keyed calls on instances of other maps.
748 if (object->IsJSArray() && key->IsSmi()) {
749 Handle<JSArray> array = Handle<JSArray>::cast(object);
750 ElementsKind kind = array->map()->elements_kind();
751 if (IsFastObjectElementsKind(kind) &&
752 array->map() == isolate()->get_initial_js_array_map(kind)) {
753 KeyedArrayCallStub stub_gen(IsHoleyElementsKind(kind), argc);
754 stub = stub_gen.GetCode(isolate());
758 if (stub.is_null()) {
759 stub = isolate()->stub_cache()->ComputeCallMegamorphic(
760 argc, Code::KEYED_CALL_IC, kNoExtraICState);
761 if (object->IsJSObject()) {
762 Handle<JSObject> receiver = Handle<JSObject>::cast(object);
763 if (receiver->elements()->map() ==
764 isolate()->heap()->non_strict_arguments_elements_map()) {
765 stub = isolate()->stub_cache()->ComputeCallArguments(argc);
768 ASSERT(!stub.is_null());
771 TRACE_IC("CallIC", key);
774 Handle<Object> result = GetProperty(isolate(), object, key);
775 RETURN_IF_EMPTY_HANDLE(isolate(), result);
777 // Make receiver an object if the callee requires it. Strict mode or builtin
778 // functions do not wrap the receiver, non-strict functions and objects
779 // called as functions do.
780 ReceiverToObjectIfRequired(result, object);
781 if (result->IsJSFunction()) return *result;
783 result = TryCallAsFunction(result);
784 if (result->IsJSFunction()) return *result;
786 return TypeError("property_not_function", object, key);
790 MaybeObject* LoadIC::Load(Handle<Object> object,
791 Handle<String> name) {
792 // If the object is undefined or null it's illegal to try to get any
793 // of its properties; throw a TypeError in that case.
794 if (object->IsUndefined() || object->IsNull()) {
795 return TypeError("non_object_property_load", object, name);
799 // Use specialized code for getting the length of strings and
800 // string wrapper objects. The length property of string wrapper
801 // objects is read-only and therefore always returns the length of
802 // the underlying string value. See ECMA-262 15.5.5.1.
803 if (object->IsStringWrapper() &&
804 name->Equals(isolate()->heap()->length_string())) {
806 if (state() == UNINITIALIZED) {
807 stub = pre_monomorphic_stub();
808 } else if (state() == PREMONOMORPHIC || state() == MONOMORPHIC) {
809 StringLengthStub string_length_stub(kind());
810 stub = string_length_stub.GetCode(isolate());
811 } else if (state() != MEGAMORPHIC) {
812 ASSERT(state() != GENERIC);
813 stub = megamorphic_stub();
815 if (!stub.is_null()) {
817 if (FLAG_trace_ic) PrintF("[LoadIC : +#length /stringwrapper]\n");
819 // Get the string if we have a string wrapper object.
820 String* string = String::cast(JSValue::cast(*object)->value());
821 return Smi::FromInt(string->length());
824 // Use specialized code for getting prototype of functions.
825 if (object->IsJSFunction() &&
826 name->Equals(isolate()->heap()->prototype_string()) &&
827 Handle<JSFunction>::cast(object)->should_have_prototype()) {
829 if (state() == UNINITIALIZED) {
830 stub = pre_monomorphic_stub();
831 } else if (state() == PREMONOMORPHIC) {
832 FunctionPrototypeStub function_prototype_stub(kind());
833 stub = function_prototype_stub.GetCode(isolate());
834 } else if (state() != MEGAMORPHIC) {
835 ASSERT(state() != GENERIC);
836 stub = megamorphic_stub();
838 if (!stub.is_null()) {
840 if (FLAG_trace_ic) PrintF("[LoadIC : +#prototype /function]\n");
842 return *Accessors::FunctionGetPrototype(Handle<JSFunction>::cast(object));
846 // Check if the name is trivially convertible to an index and get
847 // the element or char if so.
849 if (kind() == Code::KEYED_LOAD_IC && name->AsArrayIndex(&index)) {
850 // Rewrite to the generic keyed load stub.
851 if (FLAG_use_ic) set_target(*generic_stub());
852 return Runtime::GetElementOrCharAtOrFail(isolate(), object, index);
855 bool use_ic = MigrateDeprecated(object) ? false : FLAG_use_ic;
857 // Named lookup in the object.
858 LookupResult lookup(isolate());
859 LookupForRead(object, name, &lookup);
861 // If we did not find a property, check if we need to throw an exception.
862 if (!lookup.IsFound()) {
863 if (IsUndeclaredGlobal(object)) {
864 return ReferenceError("not_defined", name);
866 LOG(isolate(), SuspectReadEvent(*name, *object));
869 // Update inline cache and stub cache.
870 if (use_ic) UpdateCaches(&lookup, object, name);
872 PropertyAttributes attr;
874 Handle<Object> result =
875 Object::GetProperty(object, object, &lookup, name, &attr);
876 RETURN_IF_EMPTY_HANDLE(isolate(), result);
877 // If the property is not present, check if we need to throw an
879 if ((lookup.IsInterceptor() || lookup.IsHandler()) &&
880 attr == ABSENT && IsUndeclaredGlobal(object)) {
881 return ReferenceError("not_defined", name);
887 static bool AddOneReceiverMapIfMissing(MapHandleList* receiver_maps,
888 Handle<Map> new_receiver_map) {
889 ASSERT(!new_receiver_map.is_null());
890 for (int current = 0; current < receiver_maps->length(); ++current) {
891 if (!receiver_maps->at(current).is_null() &&
892 receiver_maps->at(current).is_identical_to(new_receiver_map)) {
896 receiver_maps->Add(new_receiver_map);
901 bool IC::UpdatePolymorphicIC(Handle<HeapType> type,
904 if (!code->is_handler()) return false;
905 TypeHandleList types;
906 CodeHandleList handlers;
908 int number_of_valid_types;
909 int handler_to_overwrite = -1;
911 target()->FindAllTypes(&types);
912 int number_of_types = types.length();
913 number_of_valid_types = number_of_types;
915 for (int i = 0; i < number_of_types; i++) {
916 Handle<HeapType> current_type = types.at(i);
917 // Filter out deprecated maps to ensure their instances get migrated.
918 if (current_type->IsClass() && current_type->AsClass()->is_deprecated()) {
919 number_of_valid_types--;
920 // If the receiver type is already in the polymorphic IC, this indicates
921 // there was a prototoype chain failure. In that case, just overwrite the
923 } else if (type->IsCurrently(current_type)) {
924 ASSERT(handler_to_overwrite == -1);
925 number_of_valid_types--;
926 handler_to_overwrite = i;
930 if (number_of_valid_types >= 4) return false;
931 if (number_of_types == 0) return false;
932 if (!target()->FindHandlers(&handlers, types.length())) return false;
934 number_of_valid_types++;
935 if (handler_to_overwrite >= 0) {
936 handlers.Set(handler_to_overwrite, code);
942 Handle<Code> ic = isolate()->stub_cache()->ComputePolymorphicIC(
943 &types, &handlers, number_of_valid_types, name, extra_ic_state());
949 Handle<HeapType> IC::CurrentTypeOf(Handle<Object> object, Isolate* isolate) {
950 return object->IsJSGlobalObject()
951 ? HeapType::Constant(Handle<JSGlobalObject>::cast(object), isolate)
952 : HeapType::OfCurrently(object, isolate);
956 Handle<Map> IC::TypeToMap(HeapType* type, Isolate* isolate) {
957 if (type->Is(HeapType::Number()))
958 return isolate->factory()->heap_number_map();
959 if (type->Is(HeapType::Boolean())) return isolate->factory()->oddball_map();
960 if (type->IsConstant()) {
961 return handle(Handle<JSGlobalObject>::cast(type->AsConstant())->map());
963 ASSERT(type->IsClass());
964 return type->AsClass();
968 Handle<HeapType> IC::MapToType(Handle<Map> map) {
969 Isolate* isolate = map->GetIsolate();
970 if (map->instance_type() == HEAP_NUMBER_TYPE) {
971 return HeapType::Number(isolate);
972 } else if (map->instance_type() == ODDBALL_TYPE) {
973 // The only oddballs that can be recorded in ICs are booleans.
974 return HeapType::Boolean(isolate);
976 return HeapType::Class(map, isolate);
981 void IC::UpdateMonomorphicIC(Handle<HeapType> type,
982 Handle<Code> handler,
983 Handle<String> name) {
984 if (!handler->is_handler()) return set_target(*handler);
985 Handle<Code> ic = isolate()->stub_cache()->ComputeMonomorphicIC(
986 name, type, handler, extra_ic_state());
991 void IC::CopyICToMegamorphicCache(Handle<String> name) {
992 TypeHandleList types;
993 CodeHandleList handlers;
994 target()->FindAllTypes(&types);
995 if (!target()->FindHandlers(&handlers, types.length())) return;
996 for (int i = 0; i < types.length(); i++) {
997 UpdateMegamorphicCache(*types.at(i), *name, *handlers.at(i));
1002 bool IC::IsTransitionOfMonomorphicTarget(Handle<HeapType> type) {
1003 if (!type->IsClass()) return false;
1004 Map* receiver_map = *type->AsClass();
1005 Map* current_map = target()->FindFirstMap();
1006 ElementsKind receiver_elements_kind = receiver_map->elements_kind();
1007 bool more_general_transition =
1008 IsMoreGeneralElementsKindTransition(
1009 current_map->elements_kind(), receiver_elements_kind);
1010 Map* transitioned_map = more_general_transition
1011 ? current_map->LookupElementsTransitionMap(receiver_elements_kind)
1014 return transitioned_map == receiver_map;
1018 void IC::PatchCache(Handle<HeapType> type,
1019 Handle<String> name,
1020 Handle<Code> code) {
1023 case PREMONOMORPHIC:
1024 case MONOMORPHIC_PROTOTYPE_FAILURE:
1025 UpdateMonomorphicIC(type, code, name);
1028 // For now, call stubs are allowed to rewrite to the same stub. This
1029 // happens e.g., when the field does not contain a function.
1030 ASSERT(target()->is_call_stub() ||
1031 target()->is_keyed_call_stub() ||
1032 !target().is_identical_to(code));
1033 Code* old_handler = target()->FindFirstHandler();
1034 if (old_handler == *code && IsTransitionOfMonomorphicTarget(type)) {
1035 UpdateMonomorphicIC(type, code, name);
1041 if (!target()->is_keyed_stub()) {
1042 if (UpdatePolymorphicIC(type, name, code)) break;
1043 CopyICToMegamorphicCache(name);
1045 set_target(*megamorphic_stub());
1048 UpdateMegamorphicCache(*type, *name, *code);
1059 Handle<Code> LoadIC::initialize_stub(Isolate* isolate, ContextualMode mode) {
1060 Handle<Code> ic = isolate->stub_cache()->ComputeLoad(
1061 UNINITIALIZED, ComputeExtraICState(mode));
1066 Handle<Code> LoadIC::pre_monomorphic_stub(Isolate* isolate,
1067 ContextualMode mode) {
1068 return isolate->stub_cache()->ComputeLoad(
1069 PREMONOMORPHIC, ComputeExtraICState(mode));
1073 Handle<Code> LoadIC::megamorphic_stub() {
1074 return isolate()->stub_cache()->ComputeLoad(
1075 MEGAMORPHIC, extra_ic_state());
1079 Handle<Code> LoadIC::SimpleFieldLoad(int offset,
1081 Representation representation) {
1082 if (kind() == Code::LOAD_IC) {
1083 LoadFieldStub stub(inobject, offset, representation);
1084 return stub.GetCode(isolate());
1086 KeyedLoadFieldStub stub(inobject, offset, representation);
1087 return stub.GetCode(isolate());
1092 void LoadIC::UpdateCaches(LookupResult* lookup,
1093 Handle<Object> object,
1094 Handle<String> name) {
1095 if (state() == UNINITIALIZED) {
1096 // This is the first time we execute this inline cache.
1097 // Set the target to the pre monomorphic stub to delay
1098 // setting the monomorphic state.
1099 set_target(*pre_monomorphic_stub());
1100 TRACE_IC("LoadIC", name);
1104 Handle<HeapType> type = CurrentTypeOf(object, isolate());
1106 if (!lookup->IsCacheable()) {
1107 // Bail out if the result is not cacheable.
1109 } else if (!lookup->IsProperty()) {
1110 if (kind() == Code::LOAD_IC) {
1111 code = isolate()->stub_cache()->ComputeLoadNonexistent(name, type);
1116 code = ComputeHandler(lookup, object, name);
1119 PatchCache(type, name, code);
1120 TRACE_IC("LoadIC", name);
1124 void IC::UpdateMegamorphicCache(HeapType* type, Name* name, Code* code) {
1125 // Cache code holding map should be consistent with
1126 // GenerateMonomorphicCacheProbe.
1127 Map* map = *TypeToMap(type, isolate());
1128 isolate()->stub_cache()->Set(name, map, code);
1132 Handle<Code> IC::ComputeHandler(LookupResult* lookup,
1133 Handle<Object> object,
1134 Handle<String> name,
1135 Handle<Object> value) {
1136 InlineCacheHolderFlag cache_holder = GetCodeCacheForObject(*object);
1137 Handle<HeapObject> stub_holder(GetCodeCacheHolder(
1138 isolate(), *object, cache_holder));
1140 Handle<Code> code = isolate()->stub_cache()->FindHandler(
1141 name, handle(stub_holder->map()), kind(), cache_holder);
1142 if (!code.is_null()) return code;
1144 code = CompileHandler(lookup, object, name, value, cache_holder);
1145 ASSERT(code->is_handler());
1147 if (code->type() != Code::NORMAL) {
1148 HeapObject::UpdateMapCodeCache(stub_holder, name, code);
1155 Handle<Code> LoadIC::CompileHandler(LookupResult* lookup,
1156 Handle<Object> object,
1157 Handle<String> name,
1158 Handle<Object> unused,
1159 InlineCacheHolderFlag cache_holder) {
1160 if (object->IsString() && name->Equals(isolate()->heap()->length_string())) {
1161 int length_index = String::kLengthOffset / kPointerSize;
1162 return SimpleFieldLoad(length_index);
1165 Handle<HeapType> type = CurrentTypeOf(object, isolate());
1166 Handle<JSObject> holder(lookup->holder());
1167 LoadStubCompiler compiler(isolate(), kNoExtraICState, cache_holder, kind());
1169 switch (lookup->type()) {
1171 PropertyIndex field = lookup->GetFieldIndex();
1172 if (object.is_identical_to(holder)) {
1173 return SimpleFieldLoad(field.translate(holder),
1174 field.is_inobject(holder),
1175 lookup->representation());
1177 return compiler.CompileLoadField(
1178 type, holder, name, field, lookup->representation());
1181 Handle<Object> constant(lookup->GetConstant(), isolate());
1182 // TODO(2803): Don't compute a stub for cons strings because they cannot
1183 // be embedded into code.
1184 if (constant->IsConsString()) break;
1185 return compiler.CompileLoadConstant(type, holder, name, constant);
1188 if (kind() != Code::LOAD_IC) break;
1189 if (holder->IsGlobalObject()) {
1190 Handle<GlobalObject> global = Handle<GlobalObject>::cast(holder);
1191 Handle<PropertyCell> cell(
1192 global->GetPropertyCell(lookup), isolate());
1193 Handle<Code> code = compiler.CompileLoadGlobal(
1194 type, global, cell, name, lookup->IsDontDelete());
1195 // TODO(verwaest): Move caching of these NORMAL stubs outside as well.
1196 Handle<HeapObject> stub_holder(GetCodeCacheHolder(
1197 isolate(), *object, cache_holder));
1198 HeapObject::UpdateMapCodeCache(stub_holder, name, code);
1201 // There is only one shared stub for loading normalized
1202 // properties. It does not traverse the prototype chain, so the
1203 // property must be found in the object for the stub to be
1205 if (!object.is_identical_to(holder)) break;
1206 return isolate()->builtins()->LoadIC_Normal();
1208 // Use simple field loads for some well-known callback properties.
1209 if (object->IsJSObject()) {
1210 Handle<JSObject> receiver = Handle<JSObject>::cast(object);
1211 Handle<Map> map(receiver->map());
1213 if (Accessors::IsJSObjectFieldAccessor(map, name, &object_offset)) {
1214 return SimpleFieldLoad(object_offset / kPointerSize);
1218 Handle<Object> callback(lookup->GetCallbackObject(), isolate());
1219 if (callback->IsExecutableAccessorInfo()) {
1220 Handle<ExecutableAccessorInfo> info =
1221 Handle<ExecutableAccessorInfo>::cast(callback);
1222 if (v8::ToCData<Address>(info->getter()) == 0) break;
1223 if (!info->IsCompatibleReceiver(*object)) break;
1224 return compiler.CompileLoadCallback(type, holder, name, info);
1225 } else if (callback->IsAccessorPair()) {
1226 Handle<Object> getter(Handle<AccessorPair>::cast(callback)->getter(),
1228 if (!getter->IsJSFunction()) break;
1229 if (holder->IsGlobalObject()) break;
1230 if (!holder->HasFastProperties()) break;
1231 Handle<JSFunction> function = Handle<JSFunction>::cast(getter);
1232 if (!object->IsJSObject() &&
1233 !function->IsBuiltin() &&
1234 function->shared()->is_classic_mode()) {
1235 // Calling non-strict non-builtins with a value as the receiver
1239 CallOptimization call_optimization(function);
1240 if (call_optimization.is_simple_api_call() &&
1241 call_optimization.IsCompatibleReceiver(*object)) {
1242 return compiler.CompileLoadCallback(
1243 type, holder, name, call_optimization);
1245 return compiler.CompileLoadViaGetter(type, holder, name, function);
1247 // TODO(dcarney): Handle correctly.
1248 if (callback->IsDeclaredAccessorInfo()) break;
1249 ASSERT(callback->IsForeign());
1250 // No IC support for old-style native accessors.
1254 ASSERT(HasInterceptorGetter(*holder));
1255 return compiler.CompileLoadInterceptor(type, holder, name);
1264 static Handle<Object> TryConvertKey(Handle<Object> key, Isolate* isolate) {
1265 // This helper implements a few common fast cases for converting
1266 // non-smi keys of keyed loads/stores to a smi or a string.
1267 if (key->IsHeapNumber()) {
1268 double value = Handle<HeapNumber>::cast(key)->value();
1269 if (std::isnan(value)) {
1270 key = isolate->factory()->nan_string();
1272 int int_value = FastD2I(value);
1273 if (value == int_value && Smi::IsValid(int_value)) {
1274 key = Handle<Smi>(Smi::FromInt(int_value), isolate);
1277 } else if (key->IsUndefined()) {
1278 key = isolate->factory()->undefined_string();
1284 Handle<Code> KeyedLoadIC::LoadElementStub(Handle<JSObject> receiver) {
1285 // Don't handle megamorphic property accesses for INTERCEPTORS or CALLBACKS
1286 // via megamorphic stubs, since they don't have a map in their relocation info
1287 // and so the stubs can't be harvested for the object needed for a map check.
1288 if (target()->type() != Code::NORMAL) {
1289 TRACE_GENERIC_IC(isolate(), "KeyedIC", "non-NORMAL target type");
1290 return generic_stub();
1293 Handle<Map> receiver_map(receiver->map(), isolate());
1294 MapHandleList target_receiver_maps;
1295 if (state() == UNINITIALIZED || state() == PREMONOMORPHIC) {
1296 // Optimistically assume that ICs that haven't reached the MONOMORPHIC state
1297 // yet will do so and stay there.
1298 return isolate()->stub_cache()->ComputeKeyedLoadElement(receiver_map);
1301 if (target().is_identical_to(string_stub())) {
1302 target_receiver_maps.Add(isolate()->factory()->string_map());
1304 target()->FindAllMaps(&target_receiver_maps);
1305 if (target_receiver_maps.length() == 0) {
1306 return isolate()->stub_cache()->ComputeKeyedLoadElement(receiver_map);
1310 // The first time a receiver is seen that is a transitioned version of the
1311 // previous monomorphic receiver type, assume the new ElementsKind is the
1312 // monomorphic type. This benefits global arrays that only transition
1313 // once, and all call sites accessing them are faster if they remain
1314 // monomorphic. If this optimistic assumption is not true, the IC will
1315 // miss again and it will become polymorphic and support both the
1316 // untransitioned and transitioned maps.
1317 if (state() == MONOMORPHIC &&
1318 IsMoreGeneralElementsKindTransition(
1319 target_receiver_maps.at(0)->elements_kind(),
1320 receiver->GetElementsKind())) {
1321 return isolate()->stub_cache()->ComputeKeyedLoadElement(receiver_map);
1324 ASSERT(state() != GENERIC);
1326 // Determine the list of receiver maps that this call site has seen,
1327 // adding the map that was just encountered.
1328 if (!AddOneReceiverMapIfMissing(&target_receiver_maps, receiver_map)) {
1329 // If the miss wasn't due to an unseen map, a polymorphic stub
1330 // won't help, use the generic stub.
1331 TRACE_GENERIC_IC(isolate(), "KeyedIC", "same map added twice");
1332 return generic_stub();
1335 // If the maximum number of receiver maps has been exceeded, use the generic
1336 // version of the IC.
1337 if (target_receiver_maps.length() > kMaxKeyedPolymorphism) {
1338 TRACE_GENERIC_IC(isolate(), "KeyedIC", "max polymorph exceeded");
1339 return generic_stub();
1342 return isolate()->stub_cache()->ComputeLoadElementPolymorphic(
1343 &target_receiver_maps);
1347 MaybeObject* KeyedLoadIC::Load(Handle<Object> object, Handle<Object> key) {
1348 if (MigrateDeprecated(object)) {
1349 return Runtime::GetObjectPropertyOrFail(isolate(), object, key);
1352 MaybeObject* maybe_object = NULL;
1353 Handle<Code> stub = generic_stub();
1355 // Check for values that can be converted into an internalized string directly
1356 // or is representable as a smi.
1357 key = TryConvertKey(key, isolate());
1359 if (key->IsInternalizedString()) {
1360 maybe_object = LoadIC::Load(object, Handle<String>::cast(key));
1361 if (maybe_object->IsFailure()) return maybe_object;
1362 } else if (FLAG_use_ic && !object->IsAccessCheckNeeded()) {
1363 ASSERT(!object->IsJSGlobalProxy());
1364 if (object->IsString() && key->IsNumber()) {
1365 if (state() == UNINITIALIZED) stub = string_stub();
1366 } else if (object->IsJSObject()) {
1367 Handle<JSObject> receiver = Handle<JSObject>::cast(object);
1368 if (receiver->elements()->map() ==
1369 isolate()->heap()->non_strict_arguments_elements_map()) {
1370 stub = non_strict_arguments_stub();
1371 } else if (receiver->HasIndexedInterceptor()) {
1372 stub = indexed_interceptor_stub();
1373 } else if (!key->ToSmi()->IsFailure() &&
1374 (!target().is_identical_to(non_strict_arguments_stub()))) {
1375 stub = LoadElementStub(receiver);
1380 if (!is_target_set()) {
1381 if (*stub == *generic_stub()) {
1382 TRACE_GENERIC_IC(isolate(), "KeyedLoadIC", "set generic");
1384 ASSERT(!stub.is_null());
1386 TRACE_IC("LoadIC", key);
1389 if (maybe_object != NULL) return maybe_object;
1390 return Runtime::GetObjectPropertyOrFail(isolate(), object, key);
1394 static bool LookupForWrite(Handle<JSObject> receiver,
1395 Handle<String> name,
1396 Handle<Object> value,
1397 LookupResult* lookup,
1399 Handle<JSObject> holder = receiver;
1400 receiver->Lookup(*name, lookup);
1401 if (lookup->IsFound()) {
1402 if (lookup->IsReadOnly() || !lookup->IsCacheable()) return false;
1404 if (lookup->holder() == *receiver) {
1405 if (lookup->IsInterceptor() && !HasInterceptorSetter(*receiver)) {
1406 receiver->LocalLookupRealNamedProperty(*name, lookup);
1407 return lookup->IsFound() &&
1408 !lookup->IsReadOnly() &&
1409 lookup->CanHoldValue(value) &&
1410 lookup->IsCacheable();
1412 return lookup->CanHoldValue(value);
1415 if (lookup->IsPropertyCallbacks()) return true;
1416 // JSGlobalProxy always goes via the runtime, so it's safe to cache.
1417 if (receiver->IsJSGlobalProxy()) return true;
1418 // Currently normal holders in the prototype chain are not supported. They
1419 // would require a runtime positive lookup and verification that the details
1420 // have not changed.
1421 if (lookup->IsInterceptor() || lookup->IsNormal()) return false;
1422 holder = Handle<JSObject>(lookup->holder(), lookup->isolate());
1425 // While normally LookupTransition gets passed the receiver, in this case we
1426 // pass the holder of the property that we overwrite. This keeps the holder in
1427 // the LookupResult intact so we can later use it to generate a prototype
1428 // chain check. This avoids a double lookup, but requires us to pass in the
1429 // receiver when trying to fetch extra information from the transition.
1430 receiver->map()->LookupTransition(*holder, *name, lookup);
1431 if (!lookup->IsTransition()) return false;
1432 PropertyDetails target_details =
1433 lookup->GetTransitionDetails(receiver->map());
1434 if (target_details.IsReadOnly()) return false;
1436 // If the value that's being stored does not fit in the field that the
1437 // instance would transition to, create a new transition that fits the value.
1438 // This has to be done before generating the IC, since that IC will embed the
1439 // transition target.
1440 // Ensure the instance and its map were migrated before trying to update the
1441 // transition target.
1442 ASSERT(!receiver->map()->is_deprecated());
1443 if (!value->FitsRepresentation(target_details.representation())) {
1444 Handle<Map> target(lookup->GetTransitionMapFromMap(receiver->map()));
1445 Map::GeneralizeRepresentation(
1446 target, target->LastAdded(),
1447 value->OptimalRepresentation(), FORCE_FIELD);
1448 // Lookup the transition again since the transition tree may have changed
1449 // entirely by the migration above.
1450 receiver->map()->LookupTransition(*holder, *name, lookup);
1451 if (!lookup->IsTransition()) return false;
1452 ic->MarkMonomorphicPrototypeFailure();
1458 MaybeObject* StoreIC::Store(Handle<Object> object,
1459 Handle<String> name,
1460 Handle<Object> value,
1461 JSReceiver::StoreFromKeyed store_mode) {
1462 if (MigrateDeprecated(object) || object->IsJSProxy()) {
1463 Handle<Object> result = JSReceiver::SetProperty(
1464 Handle<JSReceiver>::cast(object), name, value, NONE, strict_mode());
1465 RETURN_IF_EMPTY_HANDLE(isolate(), result);
1469 // If the object is undefined or null it's illegal to try to set any
1470 // properties on it; throw a TypeError in that case.
1471 if (object->IsUndefined() || object->IsNull()) {
1472 return TypeError("non_object_property_store", object, name);
1475 // The length property of string values is read-only. Throw in strict mode.
1476 if (strict_mode() == kStrictMode && object->IsString() &&
1477 name->Equals(isolate()->heap()->length_string())) {
1478 return TypeError("strict_read_only_property", object, name);
1481 // Ignore other stores where the receiver is not a JSObject.
1482 // TODO(1475): Must check prototype chains of object wrappers.
1483 if (!object->IsJSObject()) return *value;
1485 Handle<JSObject> receiver = Handle<JSObject>::cast(object);
1487 // Check if the given name is an array index.
1489 if (name->AsArrayIndex(&index)) {
1490 Handle<Object> result =
1491 JSObject::SetElement(receiver, index, value, NONE, strict_mode());
1492 RETURN_IF_EMPTY_HANDLE(isolate(), result);
1496 // Observed objects are always modified through the runtime.
1497 if (FLAG_harmony_observation && receiver->map()->is_observed()) {
1498 Handle<Object> result = JSReceiver::SetProperty(
1499 receiver, name, value, NONE, strict_mode(), store_mode);
1500 RETURN_IF_EMPTY_HANDLE(isolate(), result);
1504 // Use specialized code for setting the length of arrays with fast
1505 // properties. Slow properties might indicate redefinition of the length
1506 // property. Note that when redefined using Object.freeze, it's possible
1507 // to have fast properties but a read-only length.
1509 receiver->IsJSArray() &&
1510 name->Equals(isolate()->heap()->length_string()) &&
1511 Handle<JSArray>::cast(receiver)->AllowsSetElementsLength() &&
1512 receiver->HasFastProperties() &&
1513 !receiver->map()->is_frozen()) {
1515 StoreArrayLengthStub(kind(), strict_mode()).GetCode(isolate());
1517 TRACE_IC("StoreIC", name);
1518 Handle<Object> result = JSReceiver::SetProperty(
1519 receiver, name, value, NONE, strict_mode(), store_mode);
1520 RETURN_IF_EMPTY_HANDLE(isolate(), result);
1524 LookupResult lookup(isolate());
1525 bool can_store = LookupForWrite(receiver, name, value, &lookup, this);
1527 strict_mode() == kStrictMode &&
1528 !(lookup.IsProperty() && lookup.IsReadOnly()) &&
1529 object->IsGlobalObject()) {
1530 // Strict mode doesn't allow setting non-existent global property.
1531 return ReferenceError("not_defined", name);
1534 if (state() == UNINITIALIZED) {
1535 Handle<Code> stub = pre_monomorphic_stub();
1537 TRACE_IC("StoreIC", name);
1538 } else if (can_store) {
1539 UpdateCaches(&lookup, receiver, name, value);
1540 } else if (!name->IsCacheable(isolate()) ||
1541 lookup.IsNormal() ||
1542 (lookup.IsField() && lookup.CanHoldValue(value))) {
1543 Handle<Code> stub = generic_stub();
1548 // Set the property.
1549 Handle<Object> result = JSReceiver::SetProperty(
1550 receiver, name, value, NONE, strict_mode(), store_mode);
1551 RETURN_IF_EMPTY_HANDLE(isolate(), result);
1556 Handle<Code> StoreIC::initialize_stub(Isolate* isolate,
1557 StrictModeFlag strict_mode) {
1558 ExtraICState extra_state = ComputeExtraICState(strict_mode);
1559 Handle<Code> ic = isolate->stub_cache()->ComputeStore(
1560 UNINITIALIZED, extra_state);
1565 Handle<Code> StoreIC::megamorphic_stub() {
1566 return isolate()->stub_cache()->ComputeStore(MEGAMORPHIC, extra_ic_state());
1570 Handle<Code> StoreIC::generic_stub() const {
1571 return isolate()->stub_cache()->ComputeStore(GENERIC, extra_ic_state());
1575 Handle<Code> StoreIC::pre_monomorphic_stub(Isolate* isolate,
1576 StrictModeFlag strict_mode) {
1577 ExtraICState state = ComputeExtraICState(strict_mode);
1578 return isolate->stub_cache()->ComputeStore(PREMONOMORPHIC, state);
1582 void StoreIC::UpdateCaches(LookupResult* lookup,
1583 Handle<JSObject> receiver,
1584 Handle<String> name,
1585 Handle<Object> value) {
1586 ASSERT(lookup->IsFound());
1588 // These are not cacheable, so we never see such LookupResults here.
1589 ASSERT(!lookup->IsHandler());
1591 Handle<Code> code = ComputeHandler(lookup, receiver, name, value);
1593 PatchCache(CurrentTypeOf(receiver, isolate()), name, code);
1594 TRACE_IC("StoreIC", name);
1598 Handle<Code> StoreIC::CompileHandler(LookupResult* lookup,
1599 Handle<Object> object,
1600 Handle<String> name,
1601 Handle<Object> value,
1602 InlineCacheHolderFlag cache_holder) {
1603 if (object->IsJSGlobalProxy()) return slow_stub();
1604 ASSERT(cache_holder == OWN_MAP);
1605 // This is currently guaranteed by checks in StoreIC::Store.
1606 Handle<JSObject> receiver = Handle<JSObject>::cast(object);
1608 Handle<JSObject> holder(lookup->holder());
1609 // Handlers do not use strict mode.
1610 StoreStubCompiler compiler(isolate(), kNonStrictMode, kind());
1611 switch (lookup->type()) {
1613 return compiler.CompileStoreField(receiver, lookup, name);
1615 // Explicitly pass in the receiver map since LookupForWrite may have
1616 // stored something else than the receiver in the holder.
1617 Handle<Map> transition(
1618 lookup->GetTransitionTarget(receiver->map()), isolate());
1619 int descriptor = transition->LastAdded();
1621 DescriptorArray* target_descriptors = transition->instance_descriptors();
1622 PropertyDetails details = target_descriptors->GetDetails(descriptor);
1624 if (details.type() == CALLBACKS || details.attributes() != NONE) break;
1626 return compiler.CompileStoreTransition(
1627 receiver, lookup, transition, name);
1630 if (kind() == Code::KEYED_STORE_IC) break;
1631 if (receiver->IsGlobalObject()) {
1632 // The stub generated for the global object picks the value directly
1633 // from the property cell. So the property must be directly on the
1635 Handle<GlobalObject> global = Handle<GlobalObject>::cast(receiver);
1636 Handle<PropertyCell> cell(global->GetPropertyCell(lookup), isolate());
1637 Handle<HeapType> union_type = PropertyCell::UpdatedType(cell, value);
1638 StoreGlobalStub stub(union_type->IsConstant());
1640 Handle<Code> code = stub.GetCodeCopyFromTemplate(
1641 isolate(), receiver->map(), *cell);
1642 // TODO(verwaest): Move caching of these NORMAL stubs outside as well.
1643 HeapObject::UpdateMapCodeCache(receiver, name, code);
1646 ASSERT(holder.is_identical_to(receiver));
1647 return isolate()->builtins()->StoreIC_Normal();
1649 if (kind() == Code::KEYED_STORE_IC) break;
1650 Handle<Object> callback(lookup->GetCallbackObject(), isolate());
1651 if (callback->IsExecutableAccessorInfo()) {
1652 Handle<ExecutableAccessorInfo> info =
1653 Handle<ExecutableAccessorInfo>::cast(callback);
1654 if (v8::ToCData<Address>(info->setter()) == 0) break;
1655 if (!holder->HasFastProperties()) break;
1656 if (!info->IsCompatibleReceiver(*receiver)) break;
1657 return compiler.CompileStoreCallback(receiver, holder, name, info);
1658 } else if (callback->IsAccessorPair()) {
1659 Handle<Object> setter(
1660 Handle<AccessorPair>::cast(callback)->setter(), isolate());
1661 if (!setter->IsJSFunction()) break;
1662 if (holder->IsGlobalObject()) break;
1663 if (!holder->HasFastProperties()) break;
1664 Handle<JSFunction> function = Handle<JSFunction>::cast(setter);
1665 CallOptimization call_optimization(function);
1666 if (call_optimization.is_simple_api_call() &&
1667 call_optimization.IsCompatibleReceiver(*receiver)) {
1668 return compiler.CompileStoreCallback(
1669 receiver, holder, name, call_optimization);
1671 return compiler.CompileStoreViaSetter(
1672 receiver, holder, name, Handle<JSFunction>::cast(setter));
1674 // TODO(dcarney): Handle correctly.
1675 if (callback->IsDeclaredAccessorInfo()) break;
1676 ASSERT(callback->IsForeign());
1677 // No IC support for old-style native accessors.
1681 if (kind() == Code::KEYED_STORE_IC) break;
1682 ASSERT(HasInterceptorSetter(*receiver));
1683 return compiler.CompileStoreInterceptor(receiver, name);
1695 Handle<Code> KeyedStoreIC::StoreElementStub(Handle<JSObject> receiver,
1696 KeyedAccessStoreMode store_mode) {
1697 // Don't handle megamorphic property accesses for INTERCEPTORS or CALLBACKS
1698 // via megamorphic stubs, since they don't have a map in their relocation info
1699 // and so the stubs can't be harvested for the object needed for a map check.
1700 if (target()->type() != Code::NORMAL) {
1701 TRACE_GENERIC_IC(isolate(), "KeyedIC", "non-NORMAL target type");
1702 return generic_stub();
1705 Handle<Map> receiver_map(receiver->map(), isolate());
1706 if (state() == UNINITIALIZED || state() == PREMONOMORPHIC) {
1707 // Optimistically assume that ICs that haven't reached the MONOMORPHIC state
1708 // yet will do so and stay there.
1709 Handle<Map> monomorphic_map = ComputeTransitionedMap(receiver, store_mode);
1710 store_mode = GetNonTransitioningStoreMode(store_mode);
1711 return isolate()->stub_cache()->ComputeKeyedStoreElement(
1712 monomorphic_map, strict_mode(), store_mode);
1715 MapHandleList target_receiver_maps;
1716 target()->FindAllMaps(&target_receiver_maps);
1717 if (target_receiver_maps.length() == 0) {
1718 // In the case that there is a non-map-specific IC is installed (e.g. keyed
1719 // stores into properties in dictionary mode), then there will be not
1720 // receiver maps in the target.
1721 return generic_stub();
1724 // There are several special cases where an IC that is MONOMORPHIC can still
1725 // transition to a different GetNonTransitioningStoreMode IC that handles a
1726 // superset of the original IC. Handle those here if the receiver map hasn't
1727 // changed or it has transitioned to a more general kind.
1728 KeyedAccessStoreMode old_store_mode =
1729 KeyedStoreIC::GetKeyedAccessStoreMode(target()->extra_ic_state());
1730 Handle<Map> previous_receiver_map = target_receiver_maps.at(0);
1731 if (state() == MONOMORPHIC) {
1732 // If the "old" and "new" maps are in the same elements map family, stay
1733 // MONOMORPHIC and use the map for the most generic ElementsKind.
1734 Handle<Map> transitioned_receiver_map = receiver_map;
1735 if (IsTransitionStoreMode(store_mode)) {
1736 transitioned_receiver_map =
1737 ComputeTransitionedMap(receiver, store_mode);
1739 if (IsTransitionOfMonomorphicTarget(MapToType(transitioned_receiver_map))) {
1740 // Element family is the same, use the "worst" case map.
1741 store_mode = GetNonTransitioningStoreMode(store_mode);
1742 return isolate()->stub_cache()->ComputeKeyedStoreElement(
1743 transitioned_receiver_map, strict_mode(), store_mode);
1744 } else if (*previous_receiver_map == receiver->map() &&
1745 old_store_mode == STANDARD_STORE &&
1746 (IsGrowStoreMode(store_mode) ||
1747 store_mode == STORE_NO_TRANSITION_IGNORE_OUT_OF_BOUNDS ||
1748 store_mode == STORE_NO_TRANSITION_HANDLE_COW)) {
1749 // A "normal" IC that handles stores can switch to a version that can
1750 // grow at the end of the array, handle OOB accesses or copy COW arrays
1751 // and still stay MONOMORPHIC.
1752 return isolate()->stub_cache()->ComputeKeyedStoreElement(
1753 receiver_map, strict_mode(), store_mode);
1757 ASSERT(state() != GENERIC);
1760 AddOneReceiverMapIfMissing(&target_receiver_maps, receiver_map);
1762 if (IsTransitionStoreMode(store_mode)) {
1763 Handle<Map> transitioned_receiver_map =
1764 ComputeTransitionedMap(receiver, store_mode);
1765 map_added |= AddOneReceiverMapIfMissing(&target_receiver_maps,
1766 transitioned_receiver_map);
1770 // If the miss wasn't due to an unseen map, a polymorphic stub
1771 // won't help, use the generic stub.
1772 TRACE_GENERIC_IC(isolate(), "KeyedIC", "same map added twice");
1773 return generic_stub();
1776 // If the maximum number of receiver maps has been exceeded, use the generic
1777 // version of the IC.
1778 if (target_receiver_maps.length() > kMaxKeyedPolymorphism) {
1779 TRACE_GENERIC_IC(isolate(), "KeyedIC", "max polymorph exceeded");
1780 return generic_stub();
1783 // Make sure all polymorphic handlers have the same store mode, otherwise the
1784 // generic stub must be used.
1785 store_mode = GetNonTransitioningStoreMode(store_mode);
1786 if (old_store_mode != STANDARD_STORE) {
1787 if (store_mode == STANDARD_STORE) {
1788 store_mode = old_store_mode;
1789 } else if (store_mode != old_store_mode) {
1790 TRACE_GENERIC_IC(isolate(), "KeyedIC", "store mode mismatch");
1791 return generic_stub();
1795 // If the store mode isn't the standard mode, make sure that all polymorphic
1796 // receivers are either external arrays, or all "normal" arrays. Otherwise,
1797 // use the generic stub.
1798 if (store_mode != STANDARD_STORE) {
1799 int external_arrays = 0;
1800 for (int i = 0; i < target_receiver_maps.length(); ++i) {
1801 if (target_receiver_maps[i]->has_external_array_elements() ||
1802 target_receiver_maps[i]->has_fixed_typed_array_elements()) {
1806 if (external_arrays != 0 &&
1807 external_arrays != target_receiver_maps.length()) {
1808 TRACE_GENERIC_IC(isolate(), "KeyedIC",
1809 "unsupported combination of external and normal arrays");
1810 return generic_stub();
1814 return isolate()->stub_cache()->ComputeStoreElementPolymorphic(
1815 &target_receiver_maps, store_mode, strict_mode());
1819 Handle<Map> KeyedStoreIC::ComputeTransitionedMap(
1820 Handle<JSObject> receiver,
1821 KeyedAccessStoreMode store_mode) {
1822 switch (store_mode) {
1823 case STORE_TRANSITION_SMI_TO_OBJECT:
1824 case STORE_TRANSITION_DOUBLE_TO_OBJECT:
1825 case STORE_AND_GROW_TRANSITION_SMI_TO_OBJECT:
1826 case STORE_AND_GROW_TRANSITION_DOUBLE_TO_OBJECT:
1827 return JSObject::GetElementsTransitionMap(receiver, FAST_ELEMENTS);
1828 case STORE_TRANSITION_SMI_TO_DOUBLE:
1829 case STORE_AND_GROW_TRANSITION_SMI_TO_DOUBLE:
1830 return JSObject::GetElementsTransitionMap(receiver, FAST_DOUBLE_ELEMENTS);
1831 case STORE_TRANSITION_HOLEY_SMI_TO_OBJECT:
1832 case STORE_TRANSITION_HOLEY_DOUBLE_TO_OBJECT:
1833 case STORE_AND_GROW_TRANSITION_HOLEY_SMI_TO_OBJECT:
1834 case STORE_AND_GROW_TRANSITION_HOLEY_DOUBLE_TO_OBJECT:
1835 return JSObject::GetElementsTransitionMap(receiver,
1836 FAST_HOLEY_ELEMENTS);
1837 case STORE_TRANSITION_HOLEY_SMI_TO_DOUBLE:
1838 case STORE_AND_GROW_TRANSITION_HOLEY_SMI_TO_DOUBLE:
1839 return JSObject::GetElementsTransitionMap(receiver,
1840 FAST_HOLEY_DOUBLE_ELEMENTS);
1841 case STORE_NO_TRANSITION_IGNORE_OUT_OF_BOUNDS:
1842 ASSERT(receiver->map()->has_external_array_elements());
1844 case STORE_NO_TRANSITION_HANDLE_COW:
1845 case STANDARD_STORE:
1846 case STORE_AND_GROW_NO_TRANSITION:
1847 return Handle<Map>(receiver->map(), isolate());
1849 return Handle<Map>::null();
1853 bool IsOutOfBoundsAccess(Handle<JSObject> receiver,
1855 if (receiver->IsJSArray()) {
1856 return JSArray::cast(*receiver)->length()->IsSmi() &&
1857 index >= Smi::cast(JSArray::cast(*receiver)->length())->value();
1859 return index >= receiver->elements()->length();
1863 KeyedAccessStoreMode KeyedStoreIC::GetStoreMode(Handle<JSObject> receiver,
1865 Handle<Object> value) {
1866 ASSERT(!key->ToSmi()->IsFailure());
1867 Smi* smi_key = NULL;
1868 key->ToSmi()->To(&smi_key);
1869 int index = smi_key->value();
1870 bool oob_access = IsOutOfBoundsAccess(receiver, index);
1871 bool allow_growth = receiver->IsJSArray() && oob_access;
1873 // Handle growing array in stub if necessary.
1874 if (receiver->HasFastSmiElements()) {
1875 if (value->IsHeapNumber()) {
1876 if (receiver->HasFastHoleyElements()) {
1877 return STORE_AND_GROW_TRANSITION_HOLEY_SMI_TO_DOUBLE;
1879 return STORE_AND_GROW_TRANSITION_SMI_TO_DOUBLE;
1882 if (value->IsHeapObject()) {
1883 if (receiver->HasFastHoleyElements()) {
1884 return STORE_AND_GROW_TRANSITION_HOLEY_SMI_TO_OBJECT;
1886 return STORE_AND_GROW_TRANSITION_SMI_TO_OBJECT;
1889 } else if (receiver->HasFastDoubleElements()) {
1890 if (!value->IsSmi() && !value->IsHeapNumber()) {
1891 if (receiver->HasFastHoleyElements()) {
1892 return STORE_AND_GROW_TRANSITION_HOLEY_DOUBLE_TO_OBJECT;
1894 return STORE_AND_GROW_TRANSITION_DOUBLE_TO_OBJECT;
1898 return STORE_AND_GROW_NO_TRANSITION;
1900 // Handle only in-bounds elements accesses.
1901 if (receiver->HasFastSmiElements()) {
1902 if (value->IsHeapNumber()) {
1903 if (receiver->HasFastHoleyElements()) {
1904 return STORE_TRANSITION_HOLEY_SMI_TO_DOUBLE;
1906 return STORE_TRANSITION_SMI_TO_DOUBLE;
1908 } else if (value->IsHeapObject()) {
1909 if (receiver->HasFastHoleyElements()) {
1910 return STORE_TRANSITION_HOLEY_SMI_TO_OBJECT;
1912 return STORE_TRANSITION_SMI_TO_OBJECT;
1915 } else if (receiver->HasFastDoubleElements()) {
1916 if (!value->IsSmi() && !value->IsHeapNumber()) {
1917 if (receiver->HasFastHoleyElements()) {
1918 return STORE_TRANSITION_HOLEY_DOUBLE_TO_OBJECT;
1920 return STORE_TRANSITION_DOUBLE_TO_OBJECT;
1924 if (!FLAG_trace_external_array_abuse &&
1925 receiver->map()->has_external_array_elements() && oob_access) {
1926 return STORE_NO_TRANSITION_IGNORE_OUT_OF_BOUNDS;
1928 Heap* heap = receiver->GetHeap();
1929 if (receiver->elements()->map() == heap->fixed_cow_array_map()) {
1930 return STORE_NO_TRANSITION_HANDLE_COW;
1932 return STANDARD_STORE;
1938 MaybeObject* KeyedStoreIC::Store(Handle<Object> object,
1940 Handle<Object> value) {
1941 if (MigrateDeprecated(object)) {
1942 Handle<Object> result = Runtime::SetObjectProperty(isolate(), object,
1947 RETURN_IF_EMPTY_HANDLE(isolate(), result);
1951 // Check for values that can be converted into an internalized string directly
1952 // or is representable as a smi.
1953 key = TryConvertKey(key, isolate());
1955 MaybeObject* maybe_object = NULL;
1956 Handle<Code> stub = generic_stub();
1958 if (key->IsInternalizedString()) {
1959 maybe_object = StoreIC::Store(object,
1960 Handle<String>::cast(key),
1962 JSReceiver::MAY_BE_STORE_FROM_KEYED);
1963 if (maybe_object->IsFailure()) return maybe_object;
1965 bool use_ic = FLAG_use_ic && !object->IsAccessCheckNeeded() &&
1966 !(FLAG_harmony_observation && object->IsJSObject() &&
1967 JSObject::cast(*object)->map()->is_observed());
1968 if (use_ic && !object->IsSmi()) {
1969 // Don't use ICs for maps of the objects in Array's prototype chain. We
1970 // expect to be able to trap element sets to objects with those maps in
1971 // the runtime to enable optimization of element hole access.
1972 Handle<HeapObject> heap_object = Handle<HeapObject>::cast(object);
1973 if (heap_object->map()->IsMapInArrayPrototypeChain()) use_ic = false;
1977 ASSERT(!object->IsJSGlobalProxy());
1979 if (object->IsJSObject()) {
1980 Handle<JSObject> receiver = Handle<JSObject>::cast(object);
1981 bool key_is_smi_like = key->IsSmi() || !key->ToSmi()->IsFailure();
1982 if (receiver->elements()->map() ==
1983 isolate()->heap()->non_strict_arguments_elements_map()) {
1984 stub = non_strict_arguments_stub();
1985 } else if (key_is_smi_like &&
1986 !(target().is_identical_to(non_strict_arguments_stub()))) {
1987 // We should go generic if receiver isn't a dictionary, but our
1988 // prototype chain does have dictionary elements. This ensures that
1989 // other non-dictionary receivers in the polymorphic case benefit
1990 // from fast path keyed stores.
1991 if (!(receiver->map()->DictionaryElementsInPrototypeChainOnly())) {
1992 KeyedAccessStoreMode store_mode =
1993 GetStoreMode(receiver, key, value);
1994 stub = StoreElementStub(receiver, store_mode);
2001 if (!is_target_set()) {
2002 if (*stub == *generic_stub()) {
2003 TRACE_GENERIC_IC(isolate(), "KeyedStoreIC", "set generic");
2005 ASSERT(!stub.is_null());
2007 TRACE_IC("StoreIC", key);
2010 if (maybe_object) return maybe_object;
2011 Handle<Object> result = Runtime::SetObjectProperty(isolate(), object, key,
2015 RETURN_IF_EMPTY_HANDLE(isolate(), result);
2023 // ----------------------------------------------------------------------------
2024 // Static IC stub generators.
2027 // Used from ic-<arch>.cc.
2028 RUNTIME_FUNCTION(MaybeObject*, CallIC_Miss) {
2029 HandleScope scope(isolate);
2030 ASSERT(args.length() == 2);
2032 Handle<Object> receiver = args.at<Object>(0);
2033 Handle<String> key = args.at<String>(1);
2034 ic.UpdateState(receiver, key);
2035 MaybeObject* maybe_result = ic.LoadFunction(receiver, key);
2036 JSFunction* raw_function;
2037 if (!maybe_result->To(&raw_function)) return maybe_result;
2039 // The first time the inline cache is updated may be the first time the
2040 // function it references gets called. If the function is lazily compiled
2041 // then the first call will trigger a compilation. We check for this case
2042 // and we do the compilation immediately, instead of waiting for the stub
2043 // currently attached to the JSFunction object to trigger compilation.
2044 if (raw_function->is_compiled()) return raw_function;
2046 Handle<JSFunction> function(raw_function);
2047 Compiler::EnsureCompiled(function, CLEAR_EXCEPTION);
2052 // Used from ic-<arch>.cc.
2053 RUNTIME_FUNCTION(MaybeObject*, KeyedCallIC_Miss) {
2054 HandleScope scope(isolate);
2055 ASSERT(args.length() == 2);
2056 KeyedCallIC ic(isolate);
2057 Handle<Object> receiver = args.at<Object>(0);
2058 Handle<Object> key = args.at<Object>(1);
2059 ic.UpdateState(receiver, key);
2060 MaybeObject* maybe_result = ic.LoadFunction(receiver, key);
2061 // Result could be a function or a failure.
2062 JSFunction* raw_function = NULL;
2063 if (!maybe_result->To(&raw_function)) return maybe_result;
2065 if (raw_function->is_compiled()) return raw_function;
2067 Handle<JSFunction> function(raw_function, isolate);
2068 Compiler::EnsureCompiled(function, CLEAR_EXCEPTION);
2073 // Used from ic-<arch>.cc.
2074 RUNTIME_FUNCTION(MaybeObject*, LoadIC_Miss) {
2075 HandleScope scope(isolate);
2076 ASSERT(args.length() == 2);
2077 LoadIC ic(IC::NO_EXTRA_FRAME, isolate);
2078 Handle<Object> receiver = args.at<Object>(0);
2079 Handle<String> key = args.at<String>(1);
2080 ic.UpdateState(receiver, key);
2081 return ic.Load(receiver, key);
2085 // Used from ic-<arch>.cc
2086 RUNTIME_FUNCTION(MaybeObject*, KeyedLoadIC_Miss) {
2087 HandleScope scope(isolate);
2088 ASSERT(args.length() == 2);
2089 KeyedLoadIC ic(IC::NO_EXTRA_FRAME, isolate);
2090 Handle<Object> receiver = args.at<Object>(0);
2091 Handle<Object> key = args.at<Object>(1);
2092 ic.UpdateState(receiver, key);
2093 return ic.Load(receiver, key);
2097 RUNTIME_FUNCTION(MaybeObject*, KeyedLoadIC_MissFromStubFailure) {
2098 HandleScope scope(isolate);
2099 ASSERT(args.length() == 2);
2100 KeyedLoadIC ic(IC::EXTRA_CALL_FRAME, isolate);
2101 Handle<Object> receiver = args.at<Object>(0);
2102 Handle<Object> key = args.at<Object>(1);
2103 ic.UpdateState(receiver, key);
2104 return ic.Load(receiver, key);
2108 // Used from ic-<arch>.cc.
2109 RUNTIME_FUNCTION(MaybeObject*, StoreIC_Miss) {
2110 HandleScope scope(isolate);
2111 ASSERT(args.length() == 3);
2112 StoreIC ic(IC::NO_EXTRA_FRAME, isolate);
2113 Handle<Object> receiver = args.at<Object>(0);
2114 Handle<String> key = args.at<String>(1);
2115 ic.UpdateState(receiver, key);
2116 return ic.Store(receiver, key, args.at<Object>(2));
2120 RUNTIME_FUNCTION(MaybeObject*, StoreIC_MissFromStubFailure) {
2121 HandleScope scope(isolate);
2122 ASSERT(args.length() == 3);
2123 StoreIC ic(IC::EXTRA_CALL_FRAME, isolate);
2124 Handle<Object> receiver = args.at<Object>(0);
2125 Handle<String> key = args.at<String>(1);
2126 ic.UpdateState(receiver, key);
2127 return ic.Store(receiver, key, args.at<Object>(2));
2131 RUNTIME_FUNCTION(MaybeObject*, KeyedCallIC_MissFromStubFailure) {
2132 HandleScope scope(isolate);
2133 ASSERT(args.length() == 2);
2134 KeyedCallIC ic(isolate);
2135 Arguments* caller_args = reinterpret_cast<Arguments*>(args[0]);
2136 Handle<Object> key = args.at<Object>(1);
2137 Handle<Object> receiver((*caller_args)[0], isolate);
2139 ic.UpdateState(receiver, key);
2140 MaybeObject* maybe_result = ic.LoadFunction(receiver, key);
2141 // Result could be a function or a failure.
2142 JSFunction* raw_function = NULL;
2143 if (!maybe_result->To(&raw_function)) return maybe_result;
2145 if (raw_function->is_compiled()) return raw_function;
2147 Handle<JSFunction> function(raw_function, isolate);
2148 Compiler::EnsureCompiled(function, CLEAR_EXCEPTION);
2153 RUNTIME_FUNCTION(MaybeObject*, StoreIC_ArrayLength) {
2154 SealHandleScope shs(isolate);
2156 ASSERT(args.length() == 2);
2157 JSArray* receiver = JSArray::cast(args[0]);
2158 Object* len = args[1];
2160 // The generated code should filter out non-Smis before we get here.
2161 ASSERT(len->IsSmi());
2164 // The length property has to be a writable callback property.
2165 LookupResult debug_lookup(isolate);
2166 receiver->LocalLookup(isolate->heap()->length_string(), &debug_lookup);
2167 ASSERT(debug_lookup.IsPropertyCallbacks() && !debug_lookup.IsReadOnly());
2171 MaybeObject* maybe_result = receiver->SetElementsLength(len);
2172 if (!maybe_result->To(&result)) return maybe_result;
2178 // Extend storage is called in a store inline cache when
2179 // it is necessary to extend the properties array of a
2181 RUNTIME_FUNCTION(MaybeObject*, SharedStoreIC_ExtendStorage) {
2182 SealHandleScope shs(isolate);
2183 ASSERT(args.length() == 3);
2185 // Convert the parameters
2186 JSObject* object = JSObject::cast(args[0]);
2187 Map* transition = Map::cast(args[1]);
2188 Object* value = args[2];
2190 // Check the object has run out out property space.
2191 ASSERT(object->HasFastProperties());
2192 ASSERT(object->map()->unused_property_fields() == 0);
2194 // Expand the properties array.
2195 FixedArray* old_storage = object->properties();
2196 int new_unused = transition->unused_property_fields();
2197 int new_size = old_storage->length() + new_unused + 1;
2199 MaybeObject* maybe_result = old_storage->CopySize(new_size);
2200 if (!maybe_result->ToObject(&result)) return maybe_result;
2202 FixedArray* new_storage = FixedArray::cast(result);
2204 Object* to_store = value;
2206 if (FLAG_track_double_fields) {
2207 DescriptorArray* descriptors = transition->instance_descriptors();
2208 PropertyDetails details = descriptors->GetDetails(transition->LastAdded());
2209 if (details.representation().IsDouble()) {
2210 MaybeObject* maybe_storage =
2211 isolate->heap()->AllocateHeapNumber(value->Number());
2212 if (!maybe_storage->To(&to_store)) return maybe_storage;
2216 new_storage->set(old_storage->length(), to_store);
2218 // Set the new property value and do the map transition.
2219 object->set_properties(new_storage);
2220 object->set_map(transition);
2222 // Return the stored value.
2227 // Used from ic-<arch>.cc.
2228 RUNTIME_FUNCTION(MaybeObject*, KeyedStoreIC_Miss) {
2229 HandleScope scope(isolate);
2230 ASSERT(args.length() == 3);
2231 KeyedStoreIC ic(IC::NO_EXTRA_FRAME, isolate);
2232 Handle<Object> receiver = args.at<Object>(0);
2233 Handle<Object> key = args.at<Object>(1);
2234 ic.UpdateState(receiver, key);
2235 return ic.Store(receiver, key, args.at<Object>(2));
2239 RUNTIME_FUNCTION(MaybeObject*, KeyedStoreIC_MissFromStubFailure) {
2240 HandleScope scope(isolate);
2241 ASSERT(args.length() == 3);
2242 KeyedStoreIC ic(IC::EXTRA_CALL_FRAME, isolate);
2243 Handle<Object> receiver = args.at<Object>(0);
2244 Handle<Object> key = args.at<Object>(1);
2245 ic.UpdateState(receiver, key);
2246 return ic.Store(receiver, key, args.at<Object>(2));
2250 RUNTIME_FUNCTION(MaybeObject*, StoreIC_Slow) {
2251 HandleScope scope(isolate);
2252 ASSERT(args.length() == 3);
2253 StoreIC ic(IC::NO_EXTRA_FRAME, isolate);
2254 Handle<Object> object = args.at<Object>(0);
2255 Handle<Object> key = args.at<Object>(1);
2256 Handle<Object> value = args.at<Object>(2);
2257 StrictModeFlag strict_mode = ic.strict_mode();
2258 Handle<Object> result = Runtime::SetObjectProperty(isolate, object, key,
2262 RETURN_IF_EMPTY_HANDLE(isolate, result);
2267 RUNTIME_FUNCTION(MaybeObject*, KeyedStoreIC_Slow) {
2268 HandleScope scope(isolate);
2269 ASSERT(args.length() == 3);
2270 KeyedStoreIC ic(IC::NO_EXTRA_FRAME, isolate);
2271 Handle<Object> object = args.at<Object>(0);
2272 Handle<Object> key = args.at<Object>(1);
2273 Handle<Object> value = args.at<Object>(2);
2274 StrictModeFlag strict_mode = ic.strict_mode();
2275 Handle<Object> result = Runtime::SetObjectProperty(isolate, object, key,
2279 RETURN_IF_EMPTY_HANDLE(isolate, result);
2284 RUNTIME_FUNCTION(MaybeObject*, ElementsTransitionAndStoreIC_Miss) {
2285 HandleScope scope(isolate);
2286 ASSERT(args.length() == 4);
2287 KeyedStoreIC ic(IC::EXTRA_CALL_FRAME, isolate);
2288 Handle<Object> value = args.at<Object>(0);
2289 Handle<Map> map = args.at<Map>(1);
2290 Handle<Object> key = args.at<Object>(2);
2291 Handle<Object> object = args.at<Object>(3);
2292 StrictModeFlag strict_mode = ic.strict_mode();
2293 if (object->IsJSObject()) {
2294 JSObject::TransitionElementsKind(Handle<JSObject>::cast(object),
2295 map->elements_kind());
2297 Handle<Object> result = Runtime::SetObjectProperty(isolate, object, key,
2301 RETURN_IF_EMPTY_HANDLE(isolate, result);
2306 BinaryOpIC::State::State(ExtraICState extra_ic_state) {
2307 // We don't deserialize the SSE2 Field, since this is only used to be able
2308 // to include SSE2 as well as non-SSE2 versions in the snapshot. For code
2309 // generation we always want it to reflect the current state.
2310 op_ = static_cast<Token::Value>(
2311 FIRST_TOKEN + OpField::decode(extra_ic_state));
2312 mode_ = OverwriteModeField::decode(extra_ic_state);
2313 fixed_right_arg_ = Maybe<int>(
2314 HasFixedRightArgField::decode(extra_ic_state),
2315 1 << FixedRightArgValueField::decode(extra_ic_state));
2316 left_kind_ = LeftKindField::decode(extra_ic_state);
2317 if (fixed_right_arg_.has_value) {
2318 right_kind_ = Smi::IsValid(fixed_right_arg_.value) ? SMI : INT32;
2320 right_kind_ = RightKindField::decode(extra_ic_state);
2322 result_kind_ = ResultKindField::decode(extra_ic_state);
2323 ASSERT_LE(FIRST_TOKEN, op_);
2324 ASSERT_LE(op_, LAST_TOKEN);
2328 ExtraICState BinaryOpIC::State::GetExtraICState() const {
2329 bool sse2 = (Max(result_kind_, Max(left_kind_, right_kind_)) > SMI &&
2330 CpuFeatures::IsSafeForSnapshot(SSE2));
2331 ExtraICState extra_ic_state =
2332 SSE2Field::encode(sse2) |
2333 OpField::encode(op_ - FIRST_TOKEN) |
2334 OverwriteModeField::encode(mode_) |
2335 LeftKindField::encode(left_kind_) |
2336 ResultKindField::encode(result_kind_) |
2337 HasFixedRightArgField::encode(fixed_right_arg_.has_value);
2338 if (fixed_right_arg_.has_value) {
2339 extra_ic_state = FixedRightArgValueField::update(
2340 extra_ic_state, WhichPowerOf2(fixed_right_arg_.value));
2342 extra_ic_state = RightKindField::update(extra_ic_state, right_kind_);
2344 return extra_ic_state;
2349 void BinaryOpIC::State::GenerateAheadOfTime(
2350 Isolate* isolate, void (*Generate)(Isolate*, const State&)) {
2351 // TODO(olivf) We should investigate why adding stubs to the snapshot is so
2352 // expensive at runtime. When solved we should be able to add most binops to
2353 // the snapshot instead of hand-picking them.
2354 // Generated list of commonly used stubs
2355 #define GENERATE(op, left_kind, right_kind, result_kind, mode) \
2357 State state(op, mode); \
2358 state.left_kind_ = left_kind; \
2359 state.fixed_right_arg_.has_value = false; \
2360 state.right_kind_ = right_kind; \
2361 state.result_kind_ = result_kind; \
2362 Generate(isolate, state); \
2364 GENERATE(Token::ADD, INT32, INT32, INT32, NO_OVERWRITE);
2365 GENERATE(Token::ADD, INT32, INT32, INT32, OVERWRITE_LEFT);
2366 GENERATE(Token::ADD, INT32, INT32, NUMBER, NO_OVERWRITE);
2367 GENERATE(Token::ADD, INT32, INT32, NUMBER, OVERWRITE_LEFT);
2368 GENERATE(Token::ADD, INT32, NUMBER, NUMBER, NO_OVERWRITE);
2369 GENERATE(Token::ADD, INT32, NUMBER, NUMBER, OVERWRITE_LEFT);
2370 GENERATE(Token::ADD, INT32, NUMBER, NUMBER, OVERWRITE_RIGHT);
2371 GENERATE(Token::ADD, INT32, SMI, INT32, NO_OVERWRITE);
2372 GENERATE(Token::ADD, INT32, SMI, INT32, OVERWRITE_LEFT);
2373 GENERATE(Token::ADD, INT32, SMI, INT32, OVERWRITE_RIGHT);
2374 GENERATE(Token::ADD, NUMBER, INT32, NUMBER, NO_OVERWRITE);
2375 GENERATE(Token::ADD, NUMBER, INT32, NUMBER, OVERWRITE_LEFT);
2376 GENERATE(Token::ADD, NUMBER, INT32, NUMBER, OVERWRITE_RIGHT);
2377 GENERATE(Token::ADD, NUMBER, NUMBER, NUMBER, NO_OVERWRITE);
2378 GENERATE(Token::ADD, NUMBER, NUMBER, NUMBER, OVERWRITE_LEFT);
2379 GENERATE(Token::ADD, NUMBER, NUMBER, NUMBER, OVERWRITE_RIGHT);
2380 GENERATE(Token::ADD, NUMBER, SMI, NUMBER, NO_OVERWRITE);
2381 GENERATE(Token::ADD, NUMBER, SMI, NUMBER, OVERWRITE_LEFT);
2382 GENERATE(Token::ADD, NUMBER, SMI, NUMBER, OVERWRITE_RIGHT);
2383 GENERATE(Token::ADD, SMI, INT32, INT32, NO_OVERWRITE);
2384 GENERATE(Token::ADD, SMI, INT32, INT32, OVERWRITE_LEFT);
2385 GENERATE(Token::ADD, SMI, INT32, NUMBER, NO_OVERWRITE);
2386 GENERATE(Token::ADD, SMI, NUMBER, NUMBER, NO_OVERWRITE);
2387 GENERATE(Token::ADD, SMI, NUMBER, NUMBER, OVERWRITE_LEFT);
2388 GENERATE(Token::ADD, SMI, NUMBER, NUMBER, OVERWRITE_RIGHT);
2389 GENERATE(Token::ADD, SMI, SMI, INT32, OVERWRITE_LEFT);
2390 GENERATE(Token::ADD, SMI, SMI, SMI, OVERWRITE_RIGHT);
2391 GENERATE(Token::BIT_AND, INT32, INT32, INT32, NO_OVERWRITE);
2392 GENERATE(Token::BIT_AND, INT32, INT32, INT32, OVERWRITE_LEFT);
2393 GENERATE(Token::BIT_AND, INT32, INT32, INT32, OVERWRITE_RIGHT);
2394 GENERATE(Token::BIT_AND, INT32, INT32, SMI, NO_OVERWRITE);
2395 GENERATE(Token::BIT_AND, INT32, INT32, SMI, OVERWRITE_RIGHT);
2396 GENERATE(Token::BIT_AND, INT32, SMI, INT32, NO_OVERWRITE);
2397 GENERATE(Token::BIT_AND, INT32, SMI, INT32, OVERWRITE_RIGHT);
2398 GENERATE(Token::BIT_AND, INT32, SMI, SMI, NO_OVERWRITE);
2399 GENERATE(Token::BIT_AND, INT32, SMI, SMI, OVERWRITE_LEFT);
2400 GENERATE(Token::BIT_AND, INT32, SMI, SMI, OVERWRITE_RIGHT);
2401 GENERATE(Token::BIT_AND, NUMBER, INT32, INT32, OVERWRITE_RIGHT);
2402 GENERATE(Token::BIT_AND, NUMBER, SMI, SMI, NO_OVERWRITE);
2403 GENERATE(Token::BIT_AND, NUMBER, SMI, SMI, OVERWRITE_RIGHT);
2404 GENERATE(Token::BIT_AND, SMI, INT32, INT32, NO_OVERWRITE);
2405 GENERATE(Token::BIT_AND, SMI, INT32, SMI, OVERWRITE_RIGHT);
2406 GENERATE(Token::BIT_AND, SMI, NUMBER, SMI, OVERWRITE_RIGHT);
2407 GENERATE(Token::BIT_AND, SMI, SMI, SMI, NO_OVERWRITE);
2408 GENERATE(Token::BIT_AND, SMI, SMI, SMI, OVERWRITE_LEFT);
2409 GENERATE(Token::BIT_AND, SMI, SMI, SMI, OVERWRITE_RIGHT);
2410 GENERATE(Token::BIT_OR, INT32, INT32, INT32, OVERWRITE_LEFT);
2411 GENERATE(Token::BIT_OR, INT32, INT32, INT32, OVERWRITE_RIGHT);
2412 GENERATE(Token::BIT_OR, INT32, INT32, SMI, OVERWRITE_LEFT);
2413 GENERATE(Token::BIT_OR, INT32, SMI, INT32, NO_OVERWRITE);
2414 GENERATE(Token::BIT_OR, INT32, SMI, INT32, OVERWRITE_LEFT);
2415 GENERATE(Token::BIT_OR, INT32, SMI, INT32, OVERWRITE_RIGHT);
2416 GENERATE(Token::BIT_OR, INT32, SMI, SMI, NO_OVERWRITE);
2417 GENERATE(Token::BIT_OR, INT32, SMI, SMI, OVERWRITE_RIGHT);
2418 GENERATE(Token::BIT_OR, NUMBER, SMI, INT32, NO_OVERWRITE);
2419 GENERATE(Token::BIT_OR, NUMBER, SMI, INT32, OVERWRITE_LEFT);
2420 GENERATE(Token::BIT_OR, NUMBER, SMI, INT32, OVERWRITE_RIGHT);
2421 GENERATE(Token::BIT_OR, NUMBER, SMI, SMI, NO_OVERWRITE);
2422 GENERATE(Token::BIT_OR, NUMBER, SMI, SMI, OVERWRITE_LEFT);
2423 GENERATE(Token::BIT_OR, SMI, INT32, INT32, OVERWRITE_LEFT);
2424 GENERATE(Token::BIT_OR, SMI, INT32, INT32, OVERWRITE_RIGHT);
2425 GENERATE(Token::BIT_OR, SMI, INT32, SMI, OVERWRITE_RIGHT);
2426 GENERATE(Token::BIT_OR, SMI, SMI, SMI, OVERWRITE_LEFT);
2427 GENERATE(Token::BIT_OR, SMI, SMI, SMI, OVERWRITE_RIGHT);
2428 GENERATE(Token::BIT_XOR, INT32, INT32, INT32, NO_OVERWRITE);
2429 GENERATE(Token::BIT_XOR, INT32, INT32, INT32, OVERWRITE_LEFT);
2430 GENERATE(Token::BIT_XOR, INT32, INT32, INT32, OVERWRITE_RIGHT);
2431 GENERATE(Token::BIT_XOR, INT32, INT32, SMI, NO_OVERWRITE);
2432 GENERATE(Token::BIT_XOR, INT32, INT32, SMI, OVERWRITE_LEFT);
2433 GENERATE(Token::BIT_XOR, INT32, NUMBER, SMI, NO_OVERWRITE);
2434 GENERATE(Token::BIT_XOR, INT32, SMI, INT32, NO_OVERWRITE);
2435 GENERATE(Token::BIT_XOR, INT32, SMI, INT32, OVERWRITE_LEFT);
2436 GENERATE(Token::BIT_XOR, INT32, SMI, INT32, OVERWRITE_RIGHT);
2437 GENERATE(Token::BIT_XOR, NUMBER, INT32, INT32, NO_OVERWRITE);
2438 GENERATE(Token::BIT_XOR, NUMBER, SMI, INT32, NO_OVERWRITE);
2439 GENERATE(Token::BIT_XOR, NUMBER, SMI, SMI, NO_OVERWRITE);
2440 GENERATE(Token::BIT_XOR, SMI, INT32, INT32, NO_OVERWRITE);
2441 GENERATE(Token::BIT_XOR, SMI, INT32, INT32, OVERWRITE_LEFT);
2442 GENERATE(Token::BIT_XOR, SMI, INT32, SMI, OVERWRITE_LEFT);
2443 GENERATE(Token::BIT_XOR, SMI, SMI, SMI, NO_OVERWRITE);
2444 GENERATE(Token::BIT_XOR, SMI, SMI, SMI, OVERWRITE_LEFT);
2445 GENERATE(Token::BIT_XOR, SMI, SMI, SMI, OVERWRITE_RIGHT);
2446 GENERATE(Token::DIV, INT32, INT32, INT32, NO_OVERWRITE);
2447 GENERATE(Token::DIV, INT32, INT32, NUMBER, NO_OVERWRITE);
2448 GENERATE(Token::DIV, INT32, NUMBER, NUMBER, NO_OVERWRITE);
2449 GENERATE(Token::DIV, INT32, NUMBER, NUMBER, OVERWRITE_LEFT);
2450 GENERATE(Token::DIV, INT32, SMI, INT32, NO_OVERWRITE);
2451 GENERATE(Token::DIV, INT32, SMI, NUMBER, NO_OVERWRITE);
2452 GENERATE(Token::DIV, NUMBER, INT32, NUMBER, NO_OVERWRITE);
2453 GENERATE(Token::DIV, NUMBER, INT32, NUMBER, OVERWRITE_LEFT);
2454 GENERATE(Token::DIV, NUMBER, NUMBER, NUMBER, NO_OVERWRITE);
2455 GENERATE(Token::DIV, NUMBER, NUMBER, NUMBER, OVERWRITE_LEFT);
2456 GENERATE(Token::DIV, NUMBER, NUMBER, NUMBER, OVERWRITE_RIGHT);
2457 GENERATE(Token::DIV, NUMBER, SMI, NUMBER, NO_OVERWRITE);
2458 GENERATE(Token::DIV, NUMBER, SMI, NUMBER, OVERWRITE_LEFT);
2459 GENERATE(Token::DIV, SMI, INT32, INT32, NO_OVERWRITE);
2460 GENERATE(Token::DIV, SMI, INT32, NUMBER, NO_OVERWRITE);
2461 GENERATE(Token::DIV, SMI, INT32, NUMBER, OVERWRITE_LEFT);
2462 GENERATE(Token::DIV, SMI, NUMBER, NUMBER, NO_OVERWRITE);
2463 GENERATE(Token::DIV, SMI, NUMBER, NUMBER, OVERWRITE_LEFT);
2464 GENERATE(Token::DIV, SMI, NUMBER, NUMBER, OVERWRITE_RIGHT);
2465 GENERATE(Token::DIV, SMI, SMI, NUMBER, NO_OVERWRITE);
2466 GENERATE(Token::DIV, SMI, SMI, NUMBER, OVERWRITE_LEFT);
2467 GENERATE(Token::DIV, SMI, SMI, NUMBER, OVERWRITE_RIGHT);
2468 GENERATE(Token::DIV, SMI, SMI, SMI, NO_OVERWRITE);
2469 GENERATE(Token::DIV, SMI, SMI, SMI, OVERWRITE_LEFT);
2470 GENERATE(Token::DIV, SMI, SMI, SMI, OVERWRITE_RIGHT);
2471 GENERATE(Token::MOD, NUMBER, SMI, NUMBER, OVERWRITE_LEFT);
2472 GENERATE(Token::MOD, SMI, SMI, SMI, NO_OVERWRITE);
2473 GENERATE(Token::MOD, SMI, SMI, SMI, OVERWRITE_LEFT);
2474 GENERATE(Token::MUL, INT32, INT32, INT32, NO_OVERWRITE);
2475 GENERATE(Token::MUL, INT32, INT32, NUMBER, NO_OVERWRITE);
2476 GENERATE(Token::MUL, INT32, NUMBER, NUMBER, NO_OVERWRITE);
2477 GENERATE(Token::MUL, INT32, NUMBER, NUMBER, OVERWRITE_LEFT);
2478 GENERATE(Token::MUL, INT32, SMI, INT32, NO_OVERWRITE);
2479 GENERATE(Token::MUL, INT32, SMI, INT32, OVERWRITE_LEFT);
2480 GENERATE(Token::MUL, INT32, SMI, NUMBER, NO_OVERWRITE);
2481 GENERATE(Token::MUL, NUMBER, INT32, NUMBER, NO_OVERWRITE);
2482 GENERATE(Token::MUL, NUMBER, INT32, NUMBER, OVERWRITE_LEFT);
2483 GENERATE(Token::MUL, NUMBER, INT32, NUMBER, OVERWRITE_RIGHT);
2484 GENERATE(Token::MUL, NUMBER, NUMBER, NUMBER, NO_OVERWRITE);
2485 GENERATE(Token::MUL, NUMBER, NUMBER, NUMBER, OVERWRITE_LEFT);
2486 GENERATE(Token::MUL, NUMBER, SMI, NUMBER, NO_OVERWRITE);
2487 GENERATE(Token::MUL, NUMBER, SMI, NUMBER, OVERWRITE_LEFT);
2488 GENERATE(Token::MUL, NUMBER, SMI, NUMBER, OVERWRITE_RIGHT);
2489 GENERATE(Token::MUL, SMI, INT32, INT32, NO_OVERWRITE);
2490 GENERATE(Token::MUL, SMI, INT32, INT32, OVERWRITE_LEFT);
2491 GENERATE(Token::MUL, SMI, INT32, NUMBER, NO_OVERWRITE);
2492 GENERATE(Token::MUL, SMI, NUMBER, NUMBER, NO_OVERWRITE);
2493 GENERATE(Token::MUL, SMI, NUMBER, NUMBER, OVERWRITE_LEFT);
2494 GENERATE(Token::MUL, SMI, NUMBER, NUMBER, OVERWRITE_RIGHT);
2495 GENERATE(Token::MUL, SMI, SMI, INT32, NO_OVERWRITE);
2496 GENERATE(Token::MUL, SMI, SMI, NUMBER, NO_OVERWRITE);
2497 GENERATE(Token::MUL, SMI, SMI, NUMBER, OVERWRITE_LEFT);
2498 GENERATE(Token::MUL, SMI, SMI, SMI, NO_OVERWRITE);
2499 GENERATE(Token::MUL, SMI, SMI, SMI, OVERWRITE_LEFT);
2500 GENERATE(Token::MUL, SMI, SMI, SMI, OVERWRITE_RIGHT);
2501 GENERATE(Token::SAR, INT32, SMI, INT32, OVERWRITE_RIGHT);
2502 GENERATE(Token::SAR, INT32, SMI, SMI, NO_OVERWRITE);
2503 GENERATE(Token::SAR, INT32, SMI, SMI, OVERWRITE_RIGHT);
2504 GENERATE(Token::SAR, NUMBER, SMI, SMI, NO_OVERWRITE);
2505 GENERATE(Token::SAR, NUMBER, SMI, SMI, OVERWRITE_RIGHT);
2506 GENERATE(Token::SAR, SMI, SMI, SMI, OVERWRITE_LEFT);
2507 GENERATE(Token::SAR, SMI, SMI, SMI, OVERWRITE_RIGHT);
2508 GENERATE(Token::SHL, INT32, SMI, INT32, NO_OVERWRITE);
2509 GENERATE(Token::SHL, INT32, SMI, INT32, OVERWRITE_RIGHT);
2510 GENERATE(Token::SHL, INT32, SMI, SMI, NO_OVERWRITE);
2511 GENERATE(Token::SHL, INT32, SMI, SMI, OVERWRITE_RIGHT);
2512 GENERATE(Token::SHL, NUMBER, SMI, SMI, OVERWRITE_RIGHT);
2513 GENERATE(Token::SHL, SMI, SMI, INT32, NO_OVERWRITE);
2514 GENERATE(Token::SHL, SMI, SMI, INT32, OVERWRITE_LEFT);
2515 GENERATE(Token::SHL, SMI, SMI, INT32, OVERWRITE_RIGHT);
2516 GENERATE(Token::SHL, SMI, SMI, SMI, NO_OVERWRITE);
2517 GENERATE(Token::SHL, SMI, SMI, SMI, OVERWRITE_LEFT);
2518 GENERATE(Token::SHL, SMI, SMI, SMI, OVERWRITE_RIGHT);
2519 GENERATE(Token::SHR, INT32, SMI, SMI, NO_OVERWRITE);
2520 GENERATE(Token::SHR, INT32, SMI, SMI, OVERWRITE_LEFT);
2521 GENERATE(Token::SHR, INT32, SMI, SMI, OVERWRITE_RIGHT);
2522 GENERATE(Token::SHR, NUMBER, SMI, SMI, NO_OVERWRITE);
2523 GENERATE(Token::SHR, NUMBER, SMI, SMI, OVERWRITE_LEFT);
2524 GENERATE(Token::SHR, NUMBER, SMI, INT32, OVERWRITE_RIGHT);
2525 GENERATE(Token::SHR, SMI, SMI, SMI, NO_OVERWRITE);
2526 GENERATE(Token::SHR, SMI, SMI, SMI, OVERWRITE_LEFT);
2527 GENERATE(Token::SHR, SMI, SMI, SMI, OVERWRITE_RIGHT);
2528 GENERATE(Token::SUB, INT32, INT32, INT32, NO_OVERWRITE);
2529 GENERATE(Token::SUB, INT32, INT32, INT32, OVERWRITE_LEFT);
2530 GENERATE(Token::SUB, INT32, NUMBER, NUMBER, NO_OVERWRITE);
2531 GENERATE(Token::SUB, INT32, NUMBER, NUMBER, OVERWRITE_RIGHT);
2532 GENERATE(Token::SUB, INT32, SMI, INT32, OVERWRITE_LEFT);
2533 GENERATE(Token::SUB, INT32, SMI, INT32, OVERWRITE_RIGHT);
2534 GENERATE(Token::SUB, NUMBER, INT32, NUMBER, NO_OVERWRITE);
2535 GENERATE(Token::SUB, NUMBER, INT32, NUMBER, OVERWRITE_LEFT);
2536 GENERATE(Token::SUB, NUMBER, NUMBER, NUMBER, NO_OVERWRITE);
2537 GENERATE(Token::SUB, NUMBER, NUMBER, NUMBER, OVERWRITE_LEFT);
2538 GENERATE(Token::SUB, NUMBER, NUMBER, NUMBER, OVERWRITE_RIGHT);
2539 GENERATE(Token::SUB, NUMBER, SMI, NUMBER, NO_OVERWRITE);
2540 GENERATE(Token::SUB, NUMBER, SMI, NUMBER, OVERWRITE_LEFT);
2541 GENERATE(Token::SUB, NUMBER, SMI, NUMBER, OVERWRITE_RIGHT);
2542 GENERATE(Token::SUB, SMI, INT32, INT32, NO_OVERWRITE);
2543 GENERATE(Token::SUB, SMI, NUMBER, NUMBER, NO_OVERWRITE);
2544 GENERATE(Token::SUB, SMI, NUMBER, NUMBER, OVERWRITE_LEFT);
2545 GENERATE(Token::SUB, SMI, NUMBER, NUMBER, OVERWRITE_RIGHT);
2546 GENERATE(Token::SUB, SMI, SMI, SMI, NO_OVERWRITE);
2547 GENERATE(Token::SUB, SMI, SMI, SMI, OVERWRITE_LEFT);
2548 GENERATE(Token::SUB, SMI, SMI, SMI, OVERWRITE_RIGHT);
2550 #define GENERATE(op, left_kind, fixed_right_arg_value, result_kind, mode) \
2552 State state(op, mode); \
2553 state.left_kind_ = left_kind; \
2554 state.fixed_right_arg_.has_value = true; \
2555 state.fixed_right_arg_.value = fixed_right_arg_value; \
2556 state.right_kind_ = SMI; \
2557 state.result_kind_ = result_kind; \
2558 Generate(isolate, state); \
2560 GENERATE(Token::MOD, SMI, 2, SMI, NO_OVERWRITE);
2561 GENERATE(Token::MOD, SMI, 4, SMI, NO_OVERWRITE);
2562 GENERATE(Token::MOD, SMI, 4, SMI, OVERWRITE_LEFT);
2563 GENERATE(Token::MOD, SMI, 8, SMI, NO_OVERWRITE);
2564 GENERATE(Token::MOD, SMI, 16, SMI, OVERWRITE_LEFT);
2565 GENERATE(Token::MOD, SMI, 32, SMI, NO_OVERWRITE);
2566 GENERATE(Token::MOD, SMI, 2048, SMI, NO_OVERWRITE);
2571 Type* BinaryOpIC::State::GetResultType(Zone* zone) const {
2572 Kind result_kind = result_kind_;
2573 if (HasSideEffects()) {
2575 } else if (result_kind == GENERIC && op_ == Token::ADD) {
2576 return Type::Union(Type::Number(zone), Type::String(zone), zone);
2577 } else if (result_kind == NUMBER && op_ == Token::SHR) {
2578 return Type::Unsigned32(zone);
2580 ASSERT_NE(GENERIC, result_kind);
2581 return KindToType(result_kind, zone);
2585 void BinaryOpIC::State::Print(StringStream* stream) const {
2586 stream->Add("(%s", Token::Name(op_));
2587 if (mode_ == OVERWRITE_LEFT) stream->Add("_ReuseLeft");
2588 else if (mode_ == OVERWRITE_RIGHT) stream->Add("_ReuseRight");
2589 if (CouldCreateAllocationMementos()) stream->Add("_CreateAllocationMementos");
2590 stream->Add(":%s*", KindToString(left_kind_));
2591 if (fixed_right_arg_.has_value) {
2592 stream->Add("%d", fixed_right_arg_.value);
2594 stream->Add("%s", KindToString(right_kind_));
2596 stream->Add("->%s)", KindToString(result_kind_));
2600 void BinaryOpIC::State::Update(Handle<Object> left,
2601 Handle<Object> right,
2602 Handle<Object> result) {
2603 ExtraICState old_extra_ic_state = GetExtraICState();
2605 left_kind_ = UpdateKind(left, left_kind_);
2606 right_kind_ = UpdateKind(right, right_kind_);
2608 int32_t fixed_right_arg_value = 0;
2609 bool has_fixed_right_arg =
2610 op_ == Token::MOD &&
2611 right->ToInt32(&fixed_right_arg_value) &&
2612 fixed_right_arg_value > 0 &&
2613 IsPowerOf2(fixed_right_arg_value) &&
2614 FixedRightArgValueField::is_valid(WhichPowerOf2(fixed_right_arg_value)) &&
2615 (left_kind_ == SMI || left_kind_ == INT32) &&
2616 (result_kind_ == NONE || !fixed_right_arg_.has_value);
2617 fixed_right_arg_ = Maybe<int32_t>(has_fixed_right_arg,
2618 fixed_right_arg_value);
2620 result_kind_ = UpdateKind(result, result_kind_);
2622 if (!Token::IsTruncatingBinaryOp(op_)) {
2623 Kind input_kind = Max(left_kind_, right_kind_);
2624 if (result_kind_ < input_kind && input_kind <= NUMBER) {
2625 result_kind_ = input_kind;
2629 // We don't want to distinguish INT32 and NUMBER for string add (because
2630 // NumberToString can't make use of this anyway).
2631 if (left_kind_ == STRING && right_kind_ == INT32) {
2632 ASSERT_EQ(STRING, result_kind_);
2633 ASSERT_EQ(Token::ADD, op_);
2634 right_kind_ = NUMBER;
2635 } else if (right_kind_ == STRING && left_kind_ == INT32) {
2636 ASSERT_EQ(STRING, result_kind_);
2637 ASSERT_EQ(Token::ADD, op_);
2638 left_kind_ = NUMBER;
2641 // Reset overwrite mode unless we can actually make use of it, or may be able
2642 // to make use of it at some point in the future.
2643 if ((mode_ == OVERWRITE_LEFT && left_kind_ > NUMBER) ||
2644 (mode_ == OVERWRITE_RIGHT && right_kind_ > NUMBER) ||
2645 result_kind_ > NUMBER) {
2646 mode_ = NO_OVERWRITE;
2649 if (old_extra_ic_state == GetExtraICState()) {
2650 // Tagged operations can lead to non-truncating HChanges
2651 if (left->IsUndefined() || left->IsBoolean()) {
2652 left_kind_ = GENERIC;
2653 } else if (right->IsUndefined() || right->IsBoolean()) {
2654 right_kind_ = GENERIC;
2656 // Since the X87 is too precise, we might bail out on numbers which
2657 // actually would truncate with 64 bit precision.
2658 ASSERT(!CpuFeatures::IsSupported(SSE2));
2659 ASSERT(result_kind_ < NUMBER);
2660 result_kind_ = NUMBER;
2666 BinaryOpIC::State::Kind BinaryOpIC::State::UpdateKind(Handle<Object> object,
2668 Kind new_kind = GENERIC;
2669 bool is_truncating = Token::IsTruncatingBinaryOp(op());
2670 if (object->IsBoolean() && is_truncating) {
2671 // Booleans will be automatically truncated by HChange.
2673 } else if (object->IsUndefined()) {
2674 // Undefined will be automatically truncated by HChange.
2675 new_kind = is_truncating ? INT32 : NUMBER;
2676 } else if (object->IsSmi()) {
2678 } else if (object->IsHeapNumber()) {
2679 double value = Handle<HeapNumber>::cast(object)->value();
2680 new_kind = IsInt32Double(value) ? INT32 : NUMBER;
2681 } else if (object->IsString() && op() == Token::ADD) {
2684 if (new_kind == INT32 && SmiValuesAre32Bits()) {
2688 ((new_kind <= NUMBER && kind > NUMBER) ||
2689 (new_kind > NUMBER && kind <= NUMBER))) {
2692 return Max(kind, new_kind);
2697 const char* BinaryOpIC::State::KindToString(Kind kind) {
2699 case NONE: return "None";
2700 case SMI: return "Smi";
2701 case INT32: return "Int32";
2702 case NUMBER: return "Number";
2703 case STRING: return "String";
2704 case GENERIC: return "Generic";
2712 Type* BinaryOpIC::State::KindToType(Kind kind, Zone* zone) {
2714 case NONE: return Type::None(zone);
2715 case SMI: return Type::Smi(zone);
2716 case INT32: return Type::Signed32(zone);
2717 case NUMBER: return Type::Number(zone);
2718 case STRING: return Type::String(zone);
2719 case GENERIC: return Type::Any(zone);
2726 MaybeObject* BinaryOpIC::Transition(Handle<AllocationSite> allocation_site,
2727 Handle<Object> left,
2728 Handle<Object> right) {
2729 State state(target()->extended_extra_ic_state());
2731 // Compute the actual result using the builtin for the binary operation.
2732 Object* builtin = isolate()->js_builtins_object()->javascript_builtin(
2733 TokenToJSBuiltin(state.op()));
2734 Handle<JSFunction> function = handle(JSFunction::cast(builtin), isolate());
2735 bool caught_exception;
2736 Handle<Object> result = Execution::Call(
2737 isolate(), function, left, 1, &right, &caught_exception);
2738 if (caught_exception) return Failure::Exception();
2740 // Compute the new state.
2741 State old_state = state;
2742 state.Update(left, right, result);
2744 // Check if we have a string operation here.
2745 Handle<Code> target;
2746 if (!allocation_site.is_null() || state.ShouldCreateAllocationMementos()) {
2747 // Setup the allocation site on-demand.
2748 if (allocation_site.is_null()) {
2749 allocation_site = isolate()->factory()->NewAllocationSite();
2752 // Install the stub with an allocation site.
2753 BinaryOpICWithAllocationSiteStub stub(state);
2754 target = stub.GetCodeCopyFromTemplate(isolate(), allocation_site);
2756 // Sanity check the trampoline stub.
2757 ASSERT_EQ(*allocation_site, target->FindFirstAllocationSite());
2759 // Install the generic stub.
2760 BinaryOpICStub stub(state);
2761 target = stub.GetCode(isolate());
2763 // Sanity check the generic stub.
2764 ASSERT_EQ(NULL, target->FindFirstAllocationSite());
2766 set_target(*target);
2768 if (FLAG_trace_ic) {
2770 NoAllocationStringAllocator allocator(
2771 buffer, static_cast<unsigned>(sizeof(buffer)));
2772 StringStream stream(&allocator);
2773 stream.Add("[BinaryOpIC");
2774 old_state.Print(&stream);
2776 state.Print(&stream);
2777 stream.Add(" @ %p <- ", static_cast<void*>(*target));
2778 stream.OutputToStdOut();
2779 JavaScriptFrame::PrintTop(isolate(), stdout, false, true);
2780 if (!allocation_site.is_null()) {
2781 PrintF(" using allocation site %p", static_cast<void*>(*allocation_site));
2786 // Patch the inlined smi code as necessary.
2787 if (!old_state.UseInlinedSmiCode() && state.UseInlinedSmiCode()) {
2788 PatchInlinedSmiCode(address(), ENABLE_INLINED_SMI_CHECK);
2789 } else if (old_state.UseInlinedSmiCode() && !state.UseInlinedSmiCode()) {
2790 PatchInlinedSmiCode(address(), DISABLE_INLINED_SMI_CHECK);
2797 RUNTIME_FUNCTION(MaybeObject*, BinaryOpIC_Miss) {
2798 HandleScope scope(isolate);
2799 ASSERT_EQ(2, args.length());
2800 Handle<Object> left = args.at<Object>(BinaryOpICStub::kLeft);
2801 Handle<Object> right = args.at<Object>(BinaryOpICStub::kRight);
2802 BinaryOpIC ic(isolate);
2803 return ic.Transition(Handle<AllocationSite>::null(), left, right);
2807 RUNTIME_FUNCTION(MaybeObject*, BinaryOpIC_MissWithAllocationSite) {
2808 HandleScope scope(isolate);
2809 ASSERT_EQ(3, args.length());
2810 Handle<AllocationSite> allocation_site = args.at<AllocationSite>(
2811 BinaryOpWithAllocationSiteStub::kAllocationSite);
2812 Handle<Object> left = args.at<Object>(
2813 BinaryOpWithAllocationSiteStub::kLeft);
2814 Handle<Object> right = args.at<Object>(
2815 BinaryOpWithAllocationSiteStub::kRight);
2816 BinaryOpIC ic(isolate);
2817 return ic.Transition(allocation_site, left, right);
2821 Code* CompareIC::GetRawUninitialized(Isolate* isolate, Token::Value op) {
2822 ICCompareStub stub(op, UNINITIALIZED, UNINITIALIZED, UNINITIALIZED);
2824 CHECK(stub.FindCodeInCache(&code, isolate));
2829 Handle<Code> CompareIC::GetUninitialized(Isolate* isolate, Token::Value op) {
2830 ICCompareStub stub(op, UNINITIALIZED, UNINITIALIZED, UNINITIALIZED);
2831 return stub.GetCode(isolate);
2835 const char* CompareIC::GetStateName(State state) {
2837 case UNINITIALIZED: return "UNINITIALIZED";
2838 case SMI: return "SMI";
2839 case NUMBER: return "NUMBER";
2840 case INTERNALIZED_STRING: return "INTERNALIZED_STRING";
2841 case STRING: return "STRING";
2842 case UNIQUE_NAME: return "UNIQUE_NAME";
2843 case OBJECT: return "OBJECT";
2844 case KNOWN_OBJECT: return "KNOWN_OBJECT";
2845 case GENERIC: return "GENERIC";
2852 Type* CompareIC::StateToType(
2854 CompareIC::State state,
2857 case CompareIC::UNINITIALIZED: return Type::None(zone);
2858 case CompareIC::SMI: return Type::Smi(zone);
2859 case CompareIC::NUMBER: return Type::Number(zone);
2860 case CompareIC::STRING: return Type::String(zone);
2861 case CompareIC::INTERNALIZED_STRING: return Type::InternalizedString(zone);
2862 case CompareIC::UNIQUE_NAME: return Type::UniqueName(zone);
2863 case CompareIC::OBJECT: return Type::Receiver(zone);
2864 case CompareIC::KNOWN_OBJECT:
2865 return map.is_null() ? Type::Receiver(zone) : Type::Class(map, zone);
2866 case CompareIC::GENERIC: return Type::Any(zone);
2873 void CompareIC::StubInfoToType(int stub_minor_key,
2876 Type** overall_type,
2879 State left_state, right_state, handler_state;
2880 ICCompareStub::DecodeMinorKey(stub_minor_key, &left_state, &right_state,
2881 &handler_state, NULL);
2882 *left_type = StateToType(zone, left_state);
2883 *right_type = StateToType(zone, right_state);
2884 *overall_type = StateToType(zone, handler_state, map);
2888 CompareIC::State CompareIC::NewInputState(State old_state,
2889 Handle<Object> value) {
2890 switch (old_state) {
2892 if (value->IsSmi()) return SMI;
2893 if (value->IsHeapNumber()) return NUMBER;
2894 if (value->IsInternalizedString()) return INTERNALIZED_STRING;
2895 if (value->IsString()) return STRING;
2896 if (value->IsSymbol()) return UNIQUE_NAME;
2897 if (value->IsJSObject()) return OBJECT;
2900 if (value->IsSmi()) return SMI;
2901 if (value->IsHeapNumber()) return NUMBER;
2904 if (value->IsNumber()) return NUMBER;
2906 case INTERNALIZED_STRING:
2907 if (value->IsInternalizedString()) return INTERNALIZED_STRING;
2908 if (value->IsString()) return STRING;
2909 if (value->IsSymbol()) return UNIQUE_NAME;
2912 if (value->IsString()) return STRING;
2915 if (value->IsUniqueName()) return UNIQUE_NAME;
2918 if (value->IsJSObject()) return OBJECT;
2930 CompareIC::State CompareIC::TargetState(State old_state,
2933 bool has_inlined_smi_code,
2936 switch (old_state) {
2938 if (x->IsSmi() && y->IsSmi()) return SMI;
2939 if (x->IsNumber() && y->IsNumber()) return NUMBER;
2940 if (Token::IsOrderedRelationalCompareOp(op_)) {
2941 // Ordered comparisons treat undefined as NaN, so the
2942 // NUMBER stub will do the right thing.
2943 if ((x->IsNumber() && y->IsUndefined()) ||
2944 (y->IsNumber() && x->IsUndefined())) {
2948 if (x->IsInternalizedString() && y->IsInternalizedString()) {
2949 // We compare internalized strings as plain ones if we need to determine
2950 // the order in a non-equality compare.
2951 return Token::IsEqualityOp(op_) ? INTERNALIZED_STRING : STRING;
2953 if (x->IsString() && y->IsString()) return STRING;
2954 if (!Token::IsEqualityOp(op_)) return GENERIC;
2955 if (x->IsUniqueName() && y->IsUniqueName()) return UNIQUE_NAME;
2956 if (x->IsJSObject() && y->IsJSObject()) {
2957 if (Handle<JSObject>::cast(x)->map() ==
2958 Handle<JSObject>::cast(y)->map()) {
2959 return KNOWN_OBJECT;
2966 return x->IsNumber() && y->IsNumber() ? NUMBER : GENERIC;
2967 case INTERNALIZED_STRING:
2968 ASSERT(Token::IsEqualityOp(op_));
2969 if (x->IsString() && y->IsString()) return STRING;
2970 if (x->IsUniqueName() && y->IsUniqueName()) return UNIQUE_NAME;
2973 // If the failure was due to one side changing from smi to heap number,
2974 // then keep the state (if other changed at the same time, we will get
2975 // a second miss and then go to generic).
2976 if (old_left == SMI && x->IsHeapNumber()) return NUMBER;
2977 if (old_right == SMI && y->IsHeapNumber()) return NUMBER;
2980 ASSERT(Token::IsEqualityOp(op_));
2981 if (x->IsJSObject() && y->IsJSObject()) return OBJECT;
2990 return GENERIC; // Make the compiler happy.
2994 Code* CompareIC::UpdateCaches(Handle<Object> x, Handle<Object> y) {
2995 HandleScope scope(isolate());
2996 State previous_left, previous_right, previous_state;
2997 ICCompareStub::DecodeMinorKey(target()->stub_info(), &previous_left,
2998 &previous_right, &previous_state, NULL);
2999 State new_left = NewInputState(previous_left, x);
3000 State new_right = NewInputState(previous_right, y);
3001 State state = TargetState(previous_state, previous_left, previous_right,
3002 HasInlinedSmiCode(address()), x, y);
3003 ICCompareStub stub(op_, new_left, new_right, state);
3004 if (state == KNOWN_OBJECT) {
3006 Handle<Map>(Handle<JSObject>::cast(x)->map(), isolate()));
3008 Handle<Code> new_target = stub.GetCode(isolate());
3009 set_target(*new_target);
3011 if (FLAG_trace_ic) {
3012 PrintF("[CompareIC in ");
3013 JavaScriptFrame::PrintTop(isolate(), stdout, false, true);
3014 PrintF(" ((%s+%s=%s)->(%s+%s=%s))#%s @ %p]\n",
3015 GetStateName(previous_left),
3016 GetStateName(previous_right),
3017 GetStateName(previous_state),
3018 GetStateName(new_left),
3019 GetStateName(new_right),
3020 GetStateName(state),
3022 static_cast<void*>(*stub.GetCode(isolate())));
3025 // Activate inlined smi code.
3026 if (previous_state == UNINITIALIZED) {
3027 PatchInlinedSmiCode(address(), ENABLE_INLINED_SMI_CHECK);
3034 // Used from ICCompareStub::GenerateMiss in code-stubs-<arch>.cc.
3035 RUNTIME_FUNCTION(Code*, CompareIC_Miss) {
3036 HandleScope scope(isolate);
3037 ASSERT(args.length() == 3);
3038 CompareIC ic(isolate, static_cast<Token::Value>(args.smi_at(2)));
3039 return ic.UpdateCaches(args.at<Object>(0), args.at<Object>(1));
3043 void CompareNilIC::Clear(Address address, Code* target) {
3044 if (IsCleared(target)) return;
3045 ExtraICState state = target->extended_extra_ic_state();
3047 CompareNilICStub stub(state, HydrogenCodeStub::UNINITIALIZED);
3051 CHECK(stub.FindCodeInCache(&code, target->GetIsolate()));
3053 SetTargetAtAddress(address, code);
3057 MaybeObject* CompareNilIC::DoCompareNilSlow(NilValue nil,
3058 Handle<Object> object) {
3059 if (object->IsNull() || object->IsUndefined()) {
3060 return Smi::FromInt(true);
3062 return Smi::FromInt(object->IsUndetectableObject());
3066 MaybeObject* CompareNilIC::CompareNil(Handle<Object> object) {
3067 ExtraICState extra_ic_state = target()->extended_extra_ic_state();
3069 CompareNilICStub stub(extra_ic_state);
3071 // Extract the current supported types from the patched IC and calculate what
3072 // types must be supported as a result of the miss.
3073 bool already_monomorphic = stub.IsMonomorphic();
3075 stub.UpdateStatus(object);
3077 NilValue nil = stub.GetNilValue();
3079 // Find or create the specialized stub to support the new set of types.
3081 if (stub.IsMonomorphic()) {
3082 Handle<Map> monomorphic_map(already_monomorphic
3083 ? target()->FindFirstMap()
3084 : HeapObject::cast(*object)->map());
3085 code = isolate()->stub_cache()->ComputeCompareNil(monomorphic_map, stub);
3087 code = stub.GetCode(isolate());
3090 return DoCompareNilSlow(nil, object);
3094 RUNTIME_FUNCTION(MaybeObject*, CompareNilIC_Miss) {
3095 HandleScope scope(isolate);
3096 Handle<Object> object = args.at<Object>(0);
3097 CompareNilIC ic(isolate);
3098 return ic.CompareNil(object);
3102 RUNTIME_FUNCTION(MaybeObject*, Unreachable) {
3105 return isolate->heap()->undefined_value();
3109 Builtins::JavaScript BinaryOpIC::TokenToJSBuiltin(Token::Value op) {
3114 return Builtins::ADD;
3117 return Builtins::SUB;
3120 return Builtins::MUL;
3123 return Builtins::DIV;
3126 return Builtins::MOD;
3129 return Builtins::BIT_OR;
3131 case Token::BIT_AND:
3132 return Builtins::BIT_AND;
3134 case Token::BIT_XOR:
3135 return Builtins::BIT_XOR;
3138 return Builtins::SAR;
3141 return Builtins::SHR;
3144 return Builtins::SHL;
3150 MaybeObject* ToBooleanIC::ToBoolean(Handle<Object> object) {
3151 ToBooleanStub stub(target()->extended_extra_ic_state());
3152 bool to_boolean_value = stub.UpdateStatus(object);
3153 Handle<Code> code = stub.GetCode(isolate());
3155 return Smi::FromInt(to_boolean_value ? 1 : 0);
3159 RUNTIME_FUNCTION(MaybeObject*, ToBooleanIC_Miss) {
3160 ASSERT(args.length() == 1);
3161 HandleScope scope(isolate);
3162 Handle<Object> object = args.at<Object>(0);
3163 ToBooleanIC ic(isolate);
3164 return ic.ToBoolean(object);
3168 static const Address IC_utilities[] = {
3169 #define ADDR(name) FUNCTION_ADDR(name),
3176 Address IC::AddressFromUtilityId(IC::UtilityId id) {
3177 return IC_utilities[id];
3181 } } // namespace v8::internal