Upstream version 7.36.149.0
[platform/framework/web/crosswalk.git] / src / v8 / src / ic.cc
1 // Copyright 2012 the V8 project authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "v8.h"
6
7 #include "accessors.h"
8 #include "api.h"
9 #include "arguments.h"
10 #include "codegen.h"
11 #include "conversions.h"
12 #include "execution.h"
13 #include "ic-inl.h"
14 #include "runtime.h"
15 #include "stub-cache.h"
16
17 namespace v8 {
18 namespace internal {
19
20 #ifdef DEBUG
21 char IC::TransitionMarkFromState(IC::State state) {
22   switch (state) {
23     case UNINITIALIZED: return '0';
24     case PREMONOMORPHIC: return '.';
25     case MONOMORPHIC: return '1';
26     case MONOMORPHIC_PROTOTYPE_FAILURE: return '^';
27     case POLYMORPHIC: return 'P';
28     case MEGAMORPHIC: return 'N';
29     case GENERIC: return 'G';
30
31     // We never see the debugger states here, because the state is
32     // computed from the original code - not the patched code. Let
33     // these cases fall through to the unreachable code below.
34     case DEBUG_STUB: break;
35   }
36   UNREACHABLE();
37   return 0;
38 }
39
40
41 const char* GetTransitionMarkModifier(KeyedAccessStoreMode mode) {
42   if (mode == STORE_NO_TRANSITION_HANDLE_COW) return ".COW";
43   if (mode == STORE_NO_TRANSITION_IGNORE_OUT_OF_BOUNDS) {
44     return ".IGNORE_OOB";
45   }
46   if (IsGrowStoreMode(mode)) return ".GROW";
47   return "";
48 }
49
50
51 void IC::TraceIC(const char* type,
52                  Handle<Object> name) {
53   if (FLAG_trace_ic) {
54     Code* new_target = raw_target();
55     State new_state = new_target->ic_state();
56     PrintF("[%s%s in ", new_target->is_keyed_stub() ? "Keyed" : "", type);
57     StackFrameIterator it(isolate());
58     while (it.frame()->fp() != this->fp()) it.Advance();
59     StackFrame* raw_frame = it.frame();
60     if (raw_frame->is_internal()) {
61       Code* apply_builtin = isolate()->builtins()->builtin(
62           Builtins::kFunctionApply);
63       if (raw_frame->unchecked_code() == apply_builtin) {
64         PrintF("apply from ");
65         it.Advance();
66         raw_frame = it.frame();
67       }
68     }
69     JavaScriptFrame::PrintTop(isolate(), stdout, false, true);
70     ExtraICState extra_state = new_target->extra_ic_state();
71     const char* modifier = "";
72     if (new_target->kind() == Code::KEYED_STORE_IC) {
73       modifier = GetTransitionMarkModifier(
74           KeyedStoreIC::GetKeyedAccessStoreMode(extra_state));
75     }
76     PrintF(" (%c->%c%s)",
77            TransitionMarkFromState(state()),
78            TransitionMarkFromState(new_state),
79            modifier);
80     name->Print();
81     PrintF("]\n");
82   }
83 }
84
85 #define TRACE_GENERIC_IC(isolate, type, reason)                 \
86   do {                                                          \
87     if (FLAG_trace_ic) {                                        \
88       PrintF("[%s patching generic stub in ", type);            \
89       JavaScriptFrame::PrintTop(isolate, stdout, false, true);  \
90       PrintF(" (%s)]\n", reason);                               \
91     }                                                           \
92   } while (false)
93
94 #else
95 #define TRACE_GENERIC_IC(isolate, type, reason)
96 #endif  // DEBUG
97
98 #define TRACE_IC(type, name)             \
99   ASSERT((TraceIC(type, name), true))
100
101 IC::IC(FrameDepth depth, Isolate* isolate)
102     : isolate_(isolate),
103       target_set_(false),
104       target_maps_set_(false) {
105   // To improve the performance of the (much used) IC code, we unfold a few
106   // levels of the stack frame iteration code. This yields a ~35% speedup when
107   // running DeltaBlue and a ~25% speedup of gbemu with the '--nouse-ic' flag.
108   const Address entry =
109       Isolate::c_entry_fp(isolate->thread_local_top());
110   Address constant_pool = NULL;
111   if (FLAG_enable_ool_constant_pool) {
112     constant_pool = Memory::Address_at(
113         entry + ExitFrameConstants::kConstantPoolOffset);
114   }
115   Address* pc_address =
116       reinterpret_cast<Address*>(entry + ExitFrameConstants::kCallerPCOffset);
117   Address fp = Memory::Address_at(entry + ExitFrameConstants::kCallerFPOffset);
118   // If there's another JavaScript frame on the stack or a
119   // StubFailureTrampoline, we need to look one frame further down the stack to
120   // find the frame pointer and the return address stack slot.
121   if (depth == EXTRA_CALL_FRAME) {
122     if (FLAG_enable_ool_constant_pool) {
123       constant_pool = Memory::Address_at(
124           fp + StandardFrameConstants::kConstantPoolOffset);
125     }
126     const int kCallerPCOffset = StandardFrameConstants::kCallerPCOffset;
127     pc_address = reinterpret_cast<Address*>(fp + kCallerPCOffset);
128     fp = Memory::Address_at(fp + StandardFrameConstants::kCallerFPOffset);
129   }
130 #ifdef DEBUG
131   StackFrameIterator it(isolate);
132   for (int i = 0; i < depth + 1; i++) it.Advance();
133   StackFrame* frame = it.frame();
134   ASSERT(fp == frame->fp() && pc_address == frame->pc_address());
135 #endif
136   fp_ = fp;
137   if (FLAG_enable_ool_constant_pool) {
138     raw_constant_pool_ = handle(
139         ConstantPoolArray::cast(reinterpret_cast<Object*>(constant_pool)),
140         isolate);
141   }
142   pc_address_ = StackFrame::ResolveReturnAddressLocation(pc_address);
143   target_ = handle(raw_target(), isolate);
144   state_ = target_->ic_state();
145   extra_ic_state_ = target_->extra_ic_state();
146 }
147
148
149 SharedFunctionInfo* IC::GetSharedFunctionInfo() const {
150   // Compute the JavaScript frame for the frame pointer of this IC
151   // structure. We need this to be able to find the function
152   // corresponding to the frame.
153   StackFrameIterator it(isolate());
154   while (it.frame()->fp() != this->fp()) it.Advance();
155   JavaScriptFrame* frame = JavaScriptFrame::cast(it.frame());
156   // Find the function on the stack and both the active code for the
157   // function and the original code.
158   JSFunction* function = frame->function();
159   return function->shared();
160 }
161
162
163 Code* IC::GetCode() const {
164   HandleScope scope(isolate());
165   Handle<SharedFunctionInfo> shared(GetSharedFunctionInfo(), isolate());
166   Code* code = shared->code();
167   return code;
168 }
169
170
171 Code* IC::GetOriginalCode() const {
172   HandleScope scope(isolate());
173   Handle<SharedFunctionInfo> shared(GetSharedFunctionInfo(), isolate());
174   ASSERT(Debug::HasDebugInfo(shared));
175   Code* original_code = Debug::GetDebugInfo(shared)->original_code();
176   ASSERT(original_code->IsCode());
177   return original_code;
178 }
179
180
181 static bool HasInterceptorGetter(JSObject* object) {
182   return !object->GetNamedInterceptor()->getter()->IsUndefined();
183 }
184
185
186 static bool HasInterceptorSetter(JSObject* object) {
187   return !object->GetNamedInterceptor()->setter()->IsUndefined();
188 }
189
190
191 static void LookupForRead(Handle<Object> object,
192                           Handle<String> name,
193                           LookupResult* lookup) {
194   // Skip all the objects with named interceptors, but
195   // without actual getter.
196   while (true) {
197     object->Lookup(name, lookup);
198     // Besides normal conditions (property not found or it's not
199     // an interceptor), bail out if lookup is not cacheable: we won't
200     // be able to IC it anyway and regular lookup should work fine.
201     if (!lookup->IsInterceptor() || !lookup->IsCacheable()) {
202       return;
203     }
204
205     Handle<JSObject> holder(lookup->holder(), lookup->isolate());
206     if (HasInterceptorGetter(*holder)) {
207       return;
208     }
209
210     holder->LocalLookupRealNamedProperty(name, lookup);
211     if (lookup->IsFound()) {
212       ASSERT(!lookup->IsInterceptor());
213       return;
214     }
215
216     Handle<Object> proto(holder->GetPrototype(), lookup->isolate());
217     if (proto->IsNull()) {
218       ASSERT(!lookup->IsFound());
219       return;
220     }
221
222     object = proto;
223   }
224 }
225
226
227 bool IC::TryRemoveInvalidPrototypeDependentStub(Handle<Object> receiver,
228                                                 Handle<String> name) {
229   if (!IsNameCompatibleWithMonomorphicPrototypeFailure(name)) return false;
230
231   InlineCacheHolderFlag cache_holder =
232       Code::ExtractCacheHolderFromFlags(target()->flags());
233
234   switch (cache_holder) {
235     case OWN_MAP:
236       // The stub was generated for JSObject but called for non-JSObject.
237       // IC::GetCodeCacheHolder is not applicable.
238       if (!receiver->IsJSObject()) return false;
239       break;
240     case PROTOTYPE_MAP:
241       // IC::GetCodeCacheHolder is not applicable.
242       if (receiver->GetPrototype(isolate())->IsNull()) return false;
243       break;
244   }
245
246   Handle<Map> map(
247       IC::GetCodeCacheHolder(isolate(), *receiver, cache_holder)->map());
248
249   // Decide whether the inline cache failed because of changes to the
250   // receiver itself or changes to one of its prototypes.
251   //
252   // If there are changes to the receiver itself, the map of the
253   // receiver will have changed and the current target will not be in
254   // the receiver map's code cache.  Therefore, if the current target
255   // is in the receiver map's code cache, the inline cache failed due
256   // to prototype check failure.
257   int index = map->IndexInCodeCache(*name, *target());
258   if (index >= 0) {
259     map->RemoveFromCodeCache(*name, *target(), index);
260     // Handlers are stored in addition to the ICs on the map. Remove those, too.
261     TryRemoveInvalidHandlers(map, name);
262     return true;
263   }
264
265   // The stub is not in the cache. We've ruled out all other kinds of failure
266   // except for proptotype chain changes, a deprecated map, a map that's
267   // different from the one that the stub expects, elements kind changes, or a
268   // constant global property that will become mutable. Threat all those
269   // situations as prototype failures (stay monomorphic if possible).
270
271   // If the IC is shared between multiple receivers (slow dictionary mode), then
272   // the map cannot be deprecated and the stub invalidated.
273   if (cache_holder == OWN_MAP) {
274     Map* old_map = FirstTargetMap();
275     if (old_map == *map) return true;
276     if (old_map != NULL) {
277       if (old_map->is_deprecated()) return true;
278       if (IsMoreGeneralElementsKindTransition(old_map->elements_kind(),
279                                               map->elements_kind())) {
280         return true;
281       }
282     }
283   }
284
285   if (receiver->IsGlobalObject()) {
286     LookupResult lookup(isolate());
287     GlobalObject* global = GlobalObject::cast(*receiver);
288     global->LocalLookupRealNamedProperty(name, &lookup);
289     if (!lookup.IsFound()) return false;
290     PropertyCell* cell = global->GetPropertyCell(&lookup);
291     return cell->type()->IsConstant();
292   }
293
294   return false;
295 }
296
297
298 void IC::TryRemoveInvalidHandlers(Handle<Map> map, Handle<String> name) {
299   CodeHandleList handlers;
300   target()->FindHandlers(&handlers);
301   for (int i = 0; i < handlers.length(); i++) {
302     Handle<Code> handler = handlers.at(i);
303     int index = map->IndexInCodeCache(*name, *handler);
304     if (index >= 0) {
305       map->RemoveFromCodeCache(*name, *handler, index);
306       return;
307     }
308   }
309 }
310
311
312 bool IC::IsNameCompatibleWithMonomorphicPrototypeFailure(Handle<Object> name) {
313   if (target()->is_keyed_stub()) {
314     // Determine whether the failure is due to a name failure.
315     if (!name->IsName()) return false;
316     Name* stub_name = target()->FindFirstName();
317     if (*name != stub_name) return false;
318   }
319
320   return true;
321 }
322
323
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));
331     }
332     return;
333   }
334   if (receiver->IsUndefined() || receiver->IsNull()) return;
335
336   // Remove the target from the code cache if it became invalid
337   // because of changes in the prototype chain to avoid hitting it
338   // again.
339   if (TryRemoveInvalidPrototypeDependentStub(
340           receiver, Handle<String>::cast(name)) &&
341       TryMarkMonomorphicPrototypeFailure(name)) {
342     return;
343   }
344
345   // The builtins object is special.  It only changes when JavaScript
346   // builtins are loaded lazily.  It is important to keep inline
347   // caches for the builtins object monomorphic.  Therefore, if we get
348   // an inline cache miss for the builtins object after lazily loading
349   // JavaScript builtins, we return uninitialized as the state to
350   // force the inline cache back to monomorphic state.
351   if (receiver->IsJSBuiltinsObject()) state_ = UNINITIALIZED;
352 }
353
354
355 MaybeHandle<Object> IC::TypeError(const char* type,
356                                   Handle<Object> object,
357                                   Handle<Object> key) {
358   HandleScope scope(isolate());
359   Handle<Object> args[2] = { key, object };
360   Handle<Object> error = isolate()->factory()->NewTypeError(
361       type, HandleVector(args, 2));
362   return isolate()->Throw<Object>(error);
363 }
364
365
366 MaybeHandle<Object> IC::ReferenceError(const char* type, Handle<String> name) {
367   HandleScope scope(isolate());
368   Handle<Object> error = isolate()->factory()->NewReferenceError(
369       type, HandleVector(&name, 1));
370   return isolate()->Throw<Object>(error);
371 }
372
373
374 static int ComputeTypeInfoCountDelta(IC::State old_state, IC::State new_state) {
375   bool was_uninitialized =
376       old_state == UNINITIALIZED || old_state == PREMONOMORPHIC;
377   bool is_uninitialized =
378       new_state == UNINITIALIZED || new_state == PREMONOMORPHIC;
379   return (was_uninitialized && !is_uninitialized) ?  1 :
380          (!was_uninitialized && is_uninitialized) ? -1 : 0;
381 }
382
383
384 void IC::PostPatching(Address address, Code* target, Code* old_target) {
385   Isolate* isolate = target->GetHeap()->isolate();
386   Code* host = isolate->
387       inner_pointer_to_code_cache()->GetCacheEntry(address)->code;
388   if (host->kind() != Code::FUNCTION) return;
389
390   if (FLAG_type_info_threshold > 0 &&
391       old_target->is_inline_cache_stub() &&
392       target->is_inline_cache_stub()) {
393     int delta = ComputeTypeInfoCountDelta(old_target->ic_state(),
394                                           target->ic_state());
395     // Call ICs don't have interesting state changes from this point
396     // of view.
397     ASSERT(target->kind() != Code::CALL_IC || delta == 0);
398
399     // Not all Code objects have TypeFeedbackInfo.
400     if (host->type_feedback_info()->IsTypeFeedbackInfo() && delta != 0) {
401       TypeFeedbackInfo* info =
402           TypeFeedbackInfo::cast(host->type_feedback_info());
403       info->change_ic_with_type_info_count(delta);
404     }
405   }
406   if (host->type_feedback_info()->IsTypeFeedbackInfo()) {
407     TypeFeedbackInfo* info =
408         TypeFeedbackInfo::cast(host->type_feedback_info());
409     info->change_own_type_change_checksum();
410   }
411   host->set_profiler_ticks(0);
412   isolate->runtime_profiler()->NotifyICChanged();
413   // TODO(2029): When an optimized function is patched, it would
414   // be nice to propagate the corresponding type information to its
415   // unoptimized version for the benefit of later inlining.
416 }
417
418
419 void IC::RegisterWeakMapDependency(Handle<Code> stub) {
420   if (FLAG_collect_maps && FLAG_weak_embedded_maps_in_ic &&
421       stub->CanBeWeakStub()) {
422     ASSERT(!stub->is_weak_stub());
423     MapHandleList maps;
424     stub->FindAllMaps(&maps);
425     if (maps.length() == 1 && stub->IsWeakObjectInIC(*maps.at(0))) {
426       Map::AddDependentIC(maps.at(0), stub);
427       stub->mark_as_weak_stub();
428       if (FLAG_enable_ool_constant_pool) {
429         stub->constant_pool()->set_weak_object_state(
430             ConstantPoolArray::WEAK_OBJECTS_IN_IC);
431       }
432     }
433   }
434 }
435
436
437 void IC::InvalidateMaps(Code* stub) {
438   ASSERT(stub->is_weak_stub());
439   stub->mark_as_invalidated_weak_stub();
440   Isolate* isolate = stub->GetIsolate();
441   Heap* heap = isolate->heap();
442   Object* undefined = heap->undefined_value();
443   int mode_mask = RelocInfo::ModeMask(RelocInfo::EMBEDDED_OBJECT);
444   for (RelocIterator it(stub, mode_mask); !it.done(); it.next()) {
445     RelocInfo::Mode mode = it.rinfo()->rmode();
446     if (mode == RelocInfo::EMBEDDED_OBJECT &&
447         it.rinfo()->target_object()->IsMap()) {
448       it.rinfo()->set_target_object(undefined, SKIP_WRITE_BARRIER);
449     }
450   }
451   CPU::FlushICache(stub->instruction_start(), stub->instruction_size());
452 }
453
454
455 void IC::Clear(Isolate* isolate, Address address,
456     ConstantPoolArray* constant_pool) {
457   Code* target = GetTargetAtAddress(address, constant_pool);
458
459   // Don't clear debug break inline cache as it will remove the break point.
460   if (target->is_debug_stub()) return;
461
462   switch (target->kind()) {
463     case Code::LOAD_IC:
464       return LoadIC::Clear(isolate, address, target, constant_pool);
465     case Code::KEYED_LOAD_IC:
466       return KeyedLoadIC::Clear(isolate, address, target, constant_pool);
467     case Code::STORE_IC:
468       return StoreIC::Clear(isolate, address, target, constant_pool);
469     case Code::KEYED_STORE_IC:
470       return KeyedStoreIC::Clear(isolate, address, target, constant_pool);
471     case Code::CALL_IC:
472       return CallIC::Clear(isolate, address, target, constant_pool);
473     case Code::COMPARE_IC:
474       return CompareIC::Clear(isolate, address, target, constant_pool);
475     case Code::COMPARE_NIL_IC:
476       return CompareNilIC::Clear(address, target, constant_pool);
477     case Code::BINARY_OP_IC:
478     case Code::TO_BOOLEAN_IC:
479       // Clearing these is tricky and does not
480       // make any performance difference.
481       return;
482     default: UNREACHABLE();
483   }
484 }
485
486
487 void KeyedLoadIC::Clear(Isolate* isolate,
488                         Address address,
489                         Code* target,
490                         ConstantPoolArray* constant_pool) {
491   if (IsCleared(target)) return;
492   // Make sure to also clear the map used in inline fast cases.  If we
493   // do not clear these maps, cached code can keep objects alive
494   // through the embedded maps.
495   SetTargetAtAddress(address, *pre_monomorphic_stub(isolate), constant_pool);
496 }
497
498
499 void CallIC::Clear(Isolate* isolate,
500                    Address address,
501                    Code* target,
502                    ConstantPoolArray* constant_pool) {
503   // Currently, CallIC doesn't have state changes.
504   ASSERT(target->ic_state() == v8::internal::GENERIC);
505 }
506
507
508 void LoadIC::Clear(Isolate* isolate,
509                    Address address,
510                    Code* target,
511                    ConstantPoolArray* constant_pool) {
512   if (IsCleared(target)) return;
513   Code* code = target->GetIsolate()->stub_cache()->FindPreMonomorphicIC(
514       Code::LOAD_IC, target->extra_ic_state());
515   SetTargetAtAddress(address, code, constant_pool);
516 }
517
518
519 void StoreIC::Clear(Isolate* isolate,
520                     Address address,
521                     Code* target,
522                     ConstantPoolArray* constant_pool) {
523   if (IsCleared(target)) return;
524   Code* code = target->GetIsolate()->stub_cache()->FindPreMonomorphicIC(
525       Code::STORE_IC, target->extra_ic_state());
526   SetTargetAtAddress(address, code, constant_pool);
527 }
528
529
530 void KeyedStoreIC::Clear(Isolate* isolate,
531                          Address address,
532                          Code* target,
533                          ConstantPoolArray* constant_pool) {
534   if (IsCleared(target)) return;
535   SetTargetAtAddress(address,
536       *pre_monomorphic_stub(
537           isolate, StoreIC::GetStrictMode(target->extra_ic_state())),
538       constant_pool);
539 }
540
541
542 void CompareIC::Clear(Isolate* isolate,
543                       Address address,
544                       Code* target,
545                       ConstantPoolArray* constant_pool) {
546   ASSERT(target->major_key() == CodeStub::CompareIC);
547   CompareIC::State handler_state;
548   Token::Value op;
549   ICCompareStub::DecodeMinorKey(target->stub_info(), NULL, NULL,
550                                 &handler_state, &op);
551   // Only clear CompareICs that can retain objects.
552   if (handler_state != KNOWN_OBJECT) return;
553   SetTargetAtAddress(address, GetRawUninitialized(isolate, op), constant_pool);
554   PatchInlinedSmiCode(address, DISABLE_INLINED_SMI_CHECK);
555 }
556
557
558 static bool MigrateDeprecated(Handle<Object> object) {
559   if (!object->IsJSObject()) return false;
560   Handle<JSObject> receiver = Handle<JSObject>::cast(object);
561   if (!receiver->map()->is_deprecated()) return false;
562   JSObject::MigrateInstance(Handle<JSObject>::cast(object));
563   return true;
564 }
565
566
567 MaybeHandle<Object> LoadIC::Load(Handle<Object> object, Handle<String> name) {
568   // If the object is undefined or null it's illegal to try to get any
569   // of its properties; throw a TypeError in that case.
570   if (object->IsUndefined() || object->IsNull()) {
571     return TypeError("non_object_property_load", object, name);
572   }
573
574   if (FLAG_use_ic) {
575     // Use specialized code for getting prototype of functions.
576     if (object->IsJSFunction() &&
577         String::Equals(isolate()->factory()->prototype_string(), name) &&
578         Handle<JSFunction>::cast(object)->should_have_prototype()) {
579       Handle<Code> stub;
580       if (state() == UNINITIALIZED) {
581         stub = pre_monomorphic_stub();
582       } else if (state() == PREMONOMORPHIC) {
583         FunctionPrototypeStub function_prototype_stub(isolate(), kind());
584         stub = function_prototype_stub.GetCode();
585       } else if (state() != MEGAMORPHIC) {
586         ASSERT(state() != GENERIC);
587         stub = megamorphic_stub();
588       }
589       if (!stub.is_null()) {
590         set_target(*stub);
591         if (FLAG_trace_ic) PrintF("[LoadIC : +#prototype /function]\n");
592       }
593       return Accessors::FunctionGetPrototype(Handle<JSFunction>::cast(object));
594     }
595   }
596
597   // Check if the name is trivially convertible to an index and get
598   // the element or char if so.
599   uint32_t index;
600   if (kind() == Code::KEYED_LOAD_IC && name->AsArrayIndex(&index)) {
601     // Rewrite to the generic keyed load stub.
602     if (FLAG_use_ic) set_target(*generic_stub());
603     Handle<Object> result;
604     ASSIGN_RETURN_ON_EXCEPTION(
605         isolate(),
606         result,
607         Runtime::GetElementOrCharAt(isolate(), object, index),
608         Object);
609     return result;
610   }
611
612   bool use_ic = MigrateDeprecated(object) ? false : FLAG_use_ic;
613
614   // Named lookup in the object.
615   LookupResult lookup(isolate());
616   LookupForRead(object, name, &lookup);
617
618   // If we did not find a property, check if we need to throw an exception.
619   if (!lookup.IsFound()) {
620     if (IsUndeclaredGlobal(object)) {
621       return ReferenceError("not_defined", name);
622     }
623     LOG(isolate(), SuspectReadEvent(*name, *object));
624   }
625
626   // Update inline cache and stub cache.
627   if (use_ic) UpdateCaches(&lookup, object, name);
628
629   PropertyAttributes attr;
630   // Get the property.
631   Handle<Object> result;
632   ASSIGN_RETURN_ON_EXCEPTION(
633       isolate(),
634       result,
635       Object::GetProperty(object, object, &lookup, name, &attr),
636       Object);
637   // If the property is not present, check if we need to throw an exception.
638   if ((lookup.IsInterceptor() || lookup.IsHandler()) &&
639       attr == ABSENT && IsUndeclaredGlobal(object)) {
640     return ReferenceError("not_defined", name);
641   }
642
643   return result;
644 }
645
646
647 static bool AddOneReceiverMapIfMissing(MapHandleList* receiver_maps,
648                                        Handle<Map> new_receiver_map) {
649   ASSERT(!new_receiver_map.is_null());
650   for (int current = 0; current < receiver_maps->length(); ++current) {
651     if (!receiver_maps->at(current).is_null() &&
652         receiver_maps->at(current).is_identical_to(new_receiver_map)) {
653       return false;
654     }
655   }
656   receiver_maps->Add(new_receiver_map);
657   return true;
658 }
659
660
661 bool IC::UpdatePolymorphicIC(Handle<HeapType> type,
662                              Handle<String> name,
663                              Handle<Code> code) {
664   if (!code->is_handler()) return false;
665   TypeHandleList types;
666   CodeHandleList handlers;
667
668   TargetTypes(&types);
669   int number_of_types = types.length();
670   int deprecated_types = 0;
671   int handler_to_overwrite = -1;
672
673   for (int i = 0; i < number_of_types; i++) {
674     Handle<HeapType> current_type = types.at(i);
675     if (current_type->IsClass() &&
676         current_type->AsClass()->Map()->is_deprecated()) {
677       // Filter out deprecated maps to ensure their instances get migrated.
678       ++deprecated_types;
679     } else if (type->NowIs(current_type)) {
680       // If the receiver type is already in the polymorphic IC, this indicates
681       // there was a prototoype chain failure. In that case, just overwrite the
682       // handler.
683       handler_to_overwrite = i;
684     } else if (handler_to_overwrite == -1 &&
685                current_type->IsClass() &&
686                type->IsClass() &&
687                IsTransitionOfMonomorphicTarget(*current_type->AsClass()->Map(),
688                                                *type->AsClass()->Map())) {
689       handler_to_overwrite = i;
690     }
691   }
692
693   int number_of_valid_types =
694     number_of_types - deprecated_types - (handler_to_overwrite != -1);
695
696   if (number_of_valid_types >= 4) return false;
697   if (number_of_types == 0) return false;
698   if (!target()->FindHandlers(&handlers, types.length())) return false;
699
700   number_of_valid_types++;
701   if (handler_to_overwrite >= 0) {
702     handlers.Set(handler_to_overwrite, code);
703     if (!type->NowIs(types.at(handler_to_overwrite))) {
704       types.Set(handler_to_overwrite, type);
705     }
706   } else {
707     types.Add(type);
708     handlers.Add(code);
709   }
710
711   Handle<Code> ic = isolate()->stub_cache()->ComputePolymorphicIC(
712       kind(), &types, &handlers, number_of_valid_types, name, extra_ic_state());
713   set_target(*ic);
714   return true;
715 }
716
717
718 Handle<HeapType> IC::CurrentTypeOf(Handle<Object> object, Isolate* isolate) {
719   return object->IsJSGlobalObject()
720       ? HeapType::Constant(Handle<JSGlobalObject>::cast(object), isolate)
721       : HeapType::NowOf(object, isolate);
722 }
723
724
725 Handle<Map> IC::TypeToMap(HeapType* type, Isolate* isolate) {
726   if (type->Is(HeapType::Number()))
727     return isolate->factory()->heap_number_map();
728   if (type->Is(HeapType::Boolean())) return isolate->factory()->boolean_map();
729   if (type->Is(HeapType::Float32x4()))
730     return isolate->factory()->float32x4_map();
731   if (type->Is(HeapType::Float64x2()))
732     return isolate->factory()->float64x2_map();
733   if (type->Is(HeapType::Int32x4()))
734     return isolate->factory()->int32x4_map();
735   if (type->IsConstant()) {
736     return handle(
737         Handle<JSGlobalObject>::cast(type->AsConstant()->Value())->map());
738   }
739   ASSERT(type->IsClass());
740   return type->AsClass()->Map();
741 }
742
743
744 template <class T>
745 typename T::TypeHandle IC::MapToType(Handle<Map> map,
746                                      typename T::Region* region) {
747   if (map->instance_type() == HEAP_NUMBER_TYPE) {
748     return T::Number(region);
749   } else if (map->instance_type() == FLOAT32x4_TYPE) {
750     return T::Float32x4(region);
751   } else if (map->instance_type() == FLOAT64x2_TYPE) {
752     return T::Float64x2(region);
753   } else if (map->instance_type() == INT32x4_TYPE) {
754     return T::Int32x4(region);
755   } else if (map->instance_type() == ODDBALL_TYPE) {
756     // The only oddballs that can be recorded in ICs are booleans.
757     return T::Boolean(region);
758   } else {
759     return T::Class(map, region);
760   }
761 }
762
763
764 template
765 Type* IC::MapToType<Type>(Handle<Map> map, Zone* zone);
766
767
768 template
769 Handle<HeapType> IC::MapToType<HeapType>(Handle<Map> map, Isolate* region);
770
771
772 void IC::UpdateMonomorphicIC(Handle<HeapType> type,
773                              Handle<Code> handler,
774                              Handle<String> name) {
775   if (!handler->is_handler()) return set_target(*handler);
776   Handle<Code> ic = isolate()->stub_cache()->ComputeMonomorphicIC(
777       kind(), name, type, handler, extra_ic_state());
778   set_target(*ic);
779 }
780
781
782 void IC::CopyICToMegamorphicCache(Handle<String> name) {
783   TypeHandleList types;
784   CodeHandleList handlers;
785   TargetTypes(&types);
786   if (!target()->FindHandlers(&handlers, types.length())) return;
787   for (int i = 0; i < types.length(); i++) {
788     UpdateMegamorphicCache(*types.at(i), *name, *handlers.at(i));
789   }
790 }
791
792
793 bool IC::IsTransitionOfMonomorphicTarget(Map* source_map, Map* target_map) {
794   if (source_map == NULL) return true;
795   if (target_map == NULL) return false;
796   ElementsKind target_elements_kind = target_map->elements_kind();
797   bool more_general_transition =
798       IsMoreGeneralElementsKindTransition(
799         source_map->elements_kind(), target_elements_kind);
800   Map* transitioned_map = more_general_transition
801       ? source_map->LookupElementsTransitionMap(target_elements_kind)
802       : NULL;
803
804   return transitioned_map == target_map;
805 }
806
807
808 void IC::PatchCache(Handle<HeapType> type,
809                     Handle<String> name,
810                     Handle<Code> code) {
811   switch (state()) {
812     case UNINITIALIZED:
813     case PREMONOMORPHIC:
814     case MONOMORPHIC_PROTOTYPE_FAILURE:
815       UpdateMonomorphicIC(type, code, name);
816       break;
817     case MONOMORPHIC:  // Fall through.
818     case POLYMORPHIC:
819       if (!target()->is_keyed_stub()) {
820         if (UpdatePolymorphicIC(type, name, code)) break;
821         CopyICToMegamorphicCache(name);
822       }
823       set_target(*megamorphic_stub());
824       // Fall through.
825     case MEGAMORPHIC:
826       UpdateMegamorphicCache(*type, *name, *code);
827       break;
828     case DEBUG_STUB:
829       break;
830     case GENERIC:
831       UNREACHABLE();
832       break;
833   }
834 }
835
836
837 Handle<Code> LoadIC::initialize_stub(Isolate* isolate,
838                                      ExtraICState extra_state) {
839   return isolate->stub_cache()->ComputeLoad(UNINITIALIZED, extra_state);
840 }
841
842
843 Handle<Code> LoadIC::pre_monomorphic_stub(Isolate* isolate,
844                                           ExtraICState extra_state) {
845   return isolate->stub_cache()->ComputeLoad(PREMONOMORPHIC, extra_state);
846 }
847
848
849 Handle<Code> LoadIC::megamorphic_stub() {
850   return isolate()->stub_cache()->ComputeLoad(MEGAMORPHIC, extra_ic_state());
851 }
852
853
854 Handle<Code> LoadIC::SimpleFieldLoad(int offset,
855                                      bool inobject,
856                                      Representation representation) {
857   if (kind() == Code::LOAD_IC) {
858     LoadFieldStub stub(isolate(), inobject, offset, representation);
859     return stub.GetCode();
860   } else {
861     KeyedLoadFieldStub stub(isolate(), inobject, offset, representation);
862     return stub.GetCode();
863   }
864 }
865
866
867 void LoadIC::UpdateCaches(LookupResult* lookup,
868                           Handle<Object> object,
869                           Handle<String> name) {
870   if (state() == UNINITIALIZED) {
871     // This is the first time we execute this inline cache.
872     // Set the target to the pre monomorphic stub to delay
873     // setting the monomorphic state.
874     set_target(*pre_monomorphic_stub());
875     TRACE_IC("LoadIC", name);
876     return;
877   }
878
879   Handle<HeapType> type = CurrentTypeOf(object, isolate());
880   Handle<Code> code;
881   if (!lookup->IsCacheable()) {
882     // Bail out if the result is not cacheable.
883     code = slow_stub();
884   } else if (!lookup->IsProperty()) {
885     if (kind() == Code::LOAD_IC) {
886       code = isolate()->stub_cache()->ComputeLoadNonexistent(name, type);
887     } else {
888       code = slow_stub();
889     }
890   } else {
891     code = ComputeHandler(lookup, object, name);
892   }
893
894   PatchCache(type, name, code);
895   TRACE_IC("LoadIC", name);
896 }
897
898
899 void IC::UpdateMegamorphicCache(HeapType* type, Name* name, Code* code) {
900   // Cache code holding map should be consistent with
901   // GenerateMonomorphicCacheProbe.
902   Map* map = *TypeToMap(type, isolate());
903   isolate()->stub_cache()->Set(name, map, code);
904 }
905
906
907 Handle<Code> IC::ComputeHandler(LookupResult* lookup,
908                                 Handle<Object> object,
909                                 Handle<String> name,
910                                 Handle<Object> value) {
911   InlineCacheHolderFlag cache_holder = GetCodeCacheForObject(*object);
912   Handle<HeapObject> stub_holder(GetCodeCacheHolder(
913       isolate(), *object, cache_holder));
914
915   Handle<Code> code = isolate()->stub_cache()->FindHandler(
916       name, handle(stub_holder->map()), kind(), cache_holder,
917       lookup->holder()->HasFastProperties() ? Code::FAST : Code::NORMAL);
918   if (!code.is_null()) {
919     return code;
920   }
921
922   code = CompileHandler(lookup, object, name, value, cache_holder);
923   ASSERT(code->is_handler());
924
925   if (code->type() != Code::NORMAL) {
926     HeapObject::UpdateMapCodeCache(stub_holder, name, code);
927   }
928
929   return code;
930 }
931
932
933 Handle<Code> LoadIC::CompileHandler(LookupResult* lookup,
934                                     Handle<Object> object,
935                                     Handle<String> name,
936                                     Handle<Object> unused,
937                                     InlineCacheHolderFlag cache_holder) {
938   if (object->IsString() &&
939       String::Equals(isolate()->factory()->length_string(), name)) {
940     int length_index = String::kLengthOffset / kPointerSize;
941     return SimpleFieldLoad(length_index);
942   }
943
944   if (object->IsStringWrapper() &&
945       String::Equals(isolate()->factory()->length_string(), name)) {
946     if (kind() == Code::LOAD_IC) {
947       StringLengthStub string_length_stub(isolate());
948       return string_length_stub.GetCode();
949     } else {
950       KeyedStringLengthStub string_length_stub(isolate());
951       return string_length_stub.GetCode();
952     }
953   }
954
955   Handle<HeapType> type = CurrentTypeOf(object, isolate());
956   Handle<JSObject> holder(lookup->holder());
957   LoadStubCompiler compiler(isolate(), kNoExtraICState, cache_holder, kind());
958
959   switch (lookup->type()) {
960     case FIELD: {
961       PropertyIndex field = lookup->GetFieldIndex();
962       if (object.is_identical_to(holder)) {
963         return SimpleFieldLoad(field.translate(holder),
964                                field.is_inobject(holder),
965                                lookup->representation());
966       }
967       return compiler.CompileLoadField(
968           type, holder, name, field, lookup->representation());
969     }
970     case CONSTANT: {
971       Handle<Object> constant(lookup->GetConstant(), isolate());
972       // TODO(2803): Don't compute a stub for cons strings because they cannot
973       // be embedded into code.
974       if (constant->IsConsString()) break;
975       return compiler.CompileLoadConstant(type, holder, name, constant);
976     }
977     case NORMAL:
978       if (kind() != Code::LOAD_IC) break;
979       if (holder->IsGlobalObject()) {
980         Handle<GlobalObject> global = Handle<GlobalObject>::cast(holder);
981         Handle<PropertyCell> cell(
982             global->GetPropertyCell(lookup), isolate());
983         Handle<Code> code = compiler.CompileLoadGlobal(
984             type, global, cell, name, lookup->IsDontDelete());
985         // TODO(verwaest): Move caching of these NORMAL stubs outside as well.
986         Handle<HeapObject> stub_holder(GetCodeCacheHolder(
987             isolate(), *object, cache_holder));
988         HeapObject::UpdateMapCodeCache(stub_holder, name, code);
989         return code;
990       }
991       // There is only one shared stub for loading normalized
992       // properties. It does not traverse the prototype chain, so the
993       // property must be found in the object for the stub to be
994       // applicable.
995       if (!object.is_identical_to(holder)) break;
996       return isolate()->builtins()->LoadIC_Normal();
997     case CALLBACKS: {
998       // Use simple field loads for some well-known callback properties.
999       if (object->IsJSObject()) {
1000         Handle<JSObject> receiver = Handle<JSObject>::cast(object);
1001         Handle<HeapType> type = IC::MapToType<HeapType>(
1002             handle(receiver->map()), isolate());
1003         int object_offset;
1004         if (Accessors::IsJSObjectFieldAccessor<HeapType>(
1005                 type, name, &object_offset)) {
1006           return SimpleFieldLoad(object_offset / kPointerSize);
1007         }
1008       }
1009
1010       Handle<Object> callback(lookup->GetCallbackObject(), isolate());
1011       if (callback->IsExecutableAccessorInfo()) {
1012         Handle<ExecutableAccessorInfo> info =
1013             Handle<ExecutableAccessorInfo>::cast(callback);
1014         if (v8::ToCData<Address>(info->getter()) == 0) break;
1015         if (!info->IsCompatibleReceiver(*object)) break;
1016         return compiler.CompileLoadCallback(type, holder, name, info);
1017       } else if (callback->IsAccessorPair()) {
1018         Handle<Object> getter(Handle<AccessorPair>::cast(callback)->getter(),
1019                               isolate());
1020         if (!getter->IsJSFunction()) break;
1021         if (holder->IsGlobalObject()) break;
1022         if (!holder->HasFastProperties()) break;
1023         Handle<JSFunction> function = Handle<JSFunction>::cast(getter);
1024         if (!object->IsJSObject() &&
1025             !function->IsBuiltin() &&
1026             function->shared()->strict_mode() == SLOPPY) {
1027           // Calling sloppy non-builtins with a value as the receiver
1028           // requires boxing.
1029           break;
1030         }
1031         CallOptimization call_optimization(function);
1032         if (call_optimization.is_simple_api_call() &&
1033             call_optimization.IsCompatibleReceiver(object, holder)) {
1034           return compiler.CompileLoadCallback(
1035               type, holder, name, call_optimization);
1036         }
1037         return compiler.CompileLoadViaGetter(type, holder, name, function);
1038       }
1039       // TODO(dcarney): Handle correctly.
1040       ASSERT(callback->IsDeclaredAccessorInfo());
1041       break;
1042     }
1043     case INTERCEPTOR:
1044       ASSERT(HasInterceptorGetter(*holder));
1045       return compiler.CompileLoadInterceptor(type, holder, name);
1046     default:
1047       break;
1048   }
1049
1050   return slow_stub();
1051 }
1052
1053
1054 static Handle<Object> TryConvertKey(Handle<Object> key, Isolate* isolate) {
1055   // This helper implements a few common fast cases for converting
1056   // non-smi keys of keyed loads/stores to a smi or a string.
1057   if (key->IsHeapNumber()) {
1058     double value = Handle<HeapNumber>::cast(key)->value();
1059     if (std::isnan(value)) {
1060       key = isolate->factory()->nan_string();
1061     } else {
1062       int int_value = FastD2I(value);
1063       if (value == int_value && Smi::IsValid(int_value)) {
1064         key = Handle<Smi>(Smi::FromInt(int_value), isolate);
1065       }
1066     }
1067   } else if (key->IsUndefined()) {
1068     key = isolate->factory()->undefined_string();
1069   }
1070   return key;
1071 }
1072
1073
1074 Handle<Code> KeyedLoadIC::LoadElementStub(Handle<JSObject> receiver) {
1075   // Don't handle megamorphic property accesses for INTERCEPTORS or CALLBACKS
1076   // via megamorphic stubs, since they don't have a map in their relocation info
1077   // and so the stubs can't be harvested for the object needed for a map check.
1078   if (target()->type() != Code::NORMAL) {
1079     TRACE_GENERIC_IC(isolate(), "KeyedIC", "non-NORMAL target type");
1080     return generic_stub();
1081   }
1082
1083   Handle<Map> receiver_map(receiver->map(), isolate());
1084   MapHandleList target_receiver_maps;
1085   if (target().is_identical_to(string_stub())) {
1086     target_receiver_maps.Add(isolate()->factory()->string_map());
1087   } else {
1088     TargetMaps(&target_receiver_maps);
1089   }
1090   if (target_receiver_maps.length() == 0) {
1091     return isolate()->stub_cache()->ComputeKeyedLoadElement(receiver_map);
1092   }
1093
1094   // The first time a receiver is seen that is a transitioned version of the
1095   // previous monomorphic receiver type, assume the new ElementsKind is the
1096   // monomorphic type. This benefits global arrays that only transition
1097   // once, and all call sites accessing them are faster if they remain
1098   // monomorphic. If this optimistic assumption is not true, the IC will
1099   // miss again and it will become polymorphic and support both the
1100   // untransitioned and transitioned maps.
1101   if (state() == MONOMORPHIC &&
1102       IsMoreGeneralElementsKindTransition(
1103           target_receiver_maps.at(0)->elements_kind(),
1104           receiver->GetElementsKind())) {
1105     return isolate()->stub_cache()->ComputeKeyedLoadElement(receiver_map);
1106   }
1107
1108   ASSERT(state() != GENERIC);
1109
1110   // Determine the list of receiver maps that this call site has seen,
1111   // adding the map that was just encountered.
1112   if (!AddOneReceiverMapIfMissing(&target_receiver_maps, receiver_map)) {
1113     // If the miss wasn't due to an unseen map, a polymorphic stub
1114     // won't help, use the generic stub.
1115     TRACE_GENERIC_IC(isolate(), "KeyedIC", "same map added twice");
1116     return generic_stub();
1117   }
1118
1119   // If the maximum number of receiver maps has been exceeded, use the generic
1120   // version of the IC.
1121   if (target_receiver_maps.length() > kMaxKeyedPolymorphism) {
1122     TRACE_GENERIC_IC(isolate(), "KeyedIC", "max polymorph exceeded");
1123     return generic_stub();
1124   }
1125
1126   return isolate()->stub_cache()->ComputeLoadElementPolymorphic(
1127       &target_receiver_maps);
1128 }
1129
1130
1131 MaybeHandle<Object> KeyedLoadIC::Load(Handle<Object> object,
1132                                       Handle<Object> key) {
1133   if (MigrateDeprecated(object)) {
1134     Handle<Object> result;
1135     ASSIGN_RETURN_ON_EXCEPTION(
1136         isolate(),
1137         result,
1138         Runtime::GetObjectProperty(isolate(), object, key),
1139         Object);
1140     return result;
1141   }
1142
1143   Handle<Object> load_handle;
1144   Handle<Code> stub = generic_stub();
1145
1146   // Check for non-string values that can be converted into an
1147   // internalized string directly or is representable as a smi.
1148   key = TryConvertKey(key, isolate());
1149
1150   if (key->IsInternalizedString()) {
1151     ASSIGN_RETURN_ON_EXCEPTION(
1152         isolate(),
1153         load_handle,
1154         LoadIC::Load(object, Handle<String>::cast(key)),
1155         Object);
1156   } else if (FLAG_use_ic && !object->IsAccessCheckNeeded()) {
1157     if (object->IsString() && key->IsNumber()) {
1158       if (state() == UNINITIALIZED) stub = string_stub();
1159     } else if (object->IsJSObject()) {
1160       Handle<JSObject> receiver = Handle<JSObject>::cast(object);
1161       if (receiver->elements()->map() ==
1162           isolate()->heap()->sloppy_arguments_elements_map()) {
1163         stub = sloppy_arguments_stub();
1164       } else if (receiver->HasIndexedInterceptor()) {
1165         stub = indexed_interceptor_stub();
1166       } else if (!Object::ToSmi(isolate(), key).is_null() &&
1167                  (!target().is_identical_to(sloppy_arguments_stub()))) {
1168         stub = LoadElementStub(receiver);
1169       }
1170     }
1171   }
1172
1173   if (!is_target_set()) {
1174     if (*stub == *generic_stub()) {
1175       TRACE_GENERIC_IC(isolate(), "KeyedLoadIC", "set generic");
1176     }
1177     set_target(*stub);
1178     TRACE_IC("LoadIC", key);
1179   }
1180
1181   if (!load_handle.is_null()) return load_handle;
1182   Handle<Object> result;
1183   ASSIGN_RETURN_ON_EXCEPTION(
1184       isolate(),
1185       result,
1186       Runtime::GetObjectProperty(isolate(), object, key),
1187       Object);
1188   return result;
1189 }
1190
1191
1192 static bool LookupForWrite(Handle<JSObject> receiver,
1193                            Handle<String> name,
1194                            Handle<Object> value,
1195                            LookupResult* lookup,
1196                            IC* ic) {
1197   Handle<JSObject> holder = receiver;
1198   receiver->Lookup(name, lookup);
1199   if (lookup->IsFound()) {
1200     if (lookup->IsInterceptor() && !HasInterceptorSetter(lookup->holder())) {
1201       receiver->LocalLookupRealNamedProperty(name, lookup);
1202       if (!lookup->IsFound()) return false;
1203     }
1204
1205     if (lookup->IsReadOnly() || !lookup->IsCacheable()) return false;
1206     if (lookup->holder() == *receiver) return lookup->CanHoldValue(value);
1207     if (lookup->IsPropertyCallbacks()) return true;
1208     // JSGlobalProxy either stores on the global object in the prototype, or
1209     // goes into the runtime if access checks are needed, so this is always
1210     // safe.
1211     if (receiver->IsJSGlobalProxy()) {
1212       return lookup->holder() == receiver->GetPrototype();
1213     }
1214     // Currently normal holders in the prototype chain are not supported. They
1215     // would require a runtime positive lookup and verification that the details
1216     // have not changed.
1217     if (lookup->IsInterceptor() || lookup->IsNormal()) return false;
1218     holder = Handle<JSObject>(lookup->holder(), lookup->isolate());
1219   }
1220
1221   // While normally LookupTransition gets passed the receiver, in this case we
1222   // pass the holder of the property that we overwrite. This keeps the holder in
1223   // the LookupResult intact so we can later use it to generate a prototype
1224   // chain check. This avoids a double lookup, but requires us to pass in the
1225   // receiver when trying to fetch extra information from the transition.
1226   receiver->map()->LookupTransition(*holder, *name, lookup);
1227   if (!lookup->IsTransition() || lookup->IsReadOnly()) return false;
1228
1229   // If the value that's being stored does not fit in the field that the
1230   // instance would transition to, create a new transition that fits the value.
1231   // This has to be done before generating the IC, since that IC will embed the
1232   // transition target.
1233   // Ensure the instance and its map were migrated before trying to update the
1234   // transition target.
1235   ASSERT(!receiver->map()->is_deprecated());
1236   if (!lookup->CanHoldValue(value)) {
1237     Handle<Map> target(lookup->GetTransitionTarget());
1238     Representation field_representation = value->OptimalRepresentation();
1239     Handle<HeapType> field_type = value->OptimalType(
1240         lookup->isolate(), field_representation);
1241     Map::GeneralizeRepresentation(
1242         target, target->LastAdded(),
1243         field_representation, field_type, FORCE_FIELD);
1244     // Lookup the transition again since the transition tree may have changed
1245     // entirely by the migration above.
1246     receiver->map()->LookupTransition(*holder, *name, lookup);
1247     if (!lookup->IsTransition()) return false;
1248     return ic->TryMarkMonomorphicPrototypeFailure(name);
1249   }
1250
1251   return true;
1252 }
1253
1254
1255 MaybeHandle<Object> StoreIC::Store(Handle<Object> object,
1256                                    Handle<String> name,
1257                                    Handle<Object> value,
1258                                    JSReceiver::StoreFromKeyed store_mode) {
1259   if (MigrateDeprecated(object) || object->IsJSProxy()) {
1260     Handle<JSReceiver> receiver = Handle<JSReceiver>::cast(object);
1261     Handle<Object> result;
1262     ASSIGN_RETURN_ON_EXCEPTION(
1263         isolate(),
1264         result,
1265         JSReceiver::SetProperty(receiver, name, value, NONE, strict_mode()),
1266         Object);
1267     return result;
1268   }
1269
1270   // If the object is undefined or null it's illegal to try to set any
1271   // properties on it; throw a TypeError in that case.
1272   if (object->IsUndefined() || object->IsNull()) {
1273     return TypeError("non_object_property_store", object, name);
1274   }
1275
1276   // The length property of string values is read-only. Throw in strict mode.
1277   if (strict_mode() == STRICT && object->IsString() &&
1278       String::Equals(isolate()->factory()->length_string(), name)) {
1279     return TypeError("strict_read_only_property", object, name);
1280   }
1281
1282   // Ignore other stores where the receiver is not a JSObject.
1283   // TODO(1475): Must check prototype chains of object wrappers.
1284   if (!object->IsJSObject()) return value;
1285
1286   Handle<JSObject> receiver = Handle<JSObject>::cast(object);
1287
1288   // Check if the given name is an array index.
1289   uint32_t index;
1290   if (name->AsArrayIndex(&index)) {
1291     Handle<Object> result;
1292     ASSIGN_RETURN_ON_EXCEPTION(
1293         isolate(),
1294         result,
1295         JSObject::SetElement(receiver, index, value, NONE, strict_mode()),
1296         Object);
1297     return value;
1298   }
1299
1300   // Observed objects are always modified through the runtime.
1301   if (receiver->map()->is_observed()) {
1302     Handle<Object> result;
1303     ASSIGN_RETURN_ON_EXCEPTION(
1304         isolate(),
1305         result,
1306         JSReceiver::SetProperty(
1307             receiver, name, value, NONE, strict_mode(), store_mode),
1308         Object);
1309     return result;
1310   }
1311
1312   LookupResult lookup(isolate());
1313   bool can_store = LookupForWrite(receiver, name, value, &lookup, this);
1314   if (!can_store &&
1315       strict_mode() == STRICT &&
1316       !(lookup.IsProperty() && lookup.IsReadOnly()) &&
1317       object->IsGlobalObject()) {
1318     // Strict mode doesn't allow setting non-existent global property.
1319     return ReferenceError("not_defined", name);
1320   }
1321   if (FLAG_use_ic) {
1322     if (state() == UNINITIALIZED) {
1323       Handle<Code> stub = pre_monomorphic_stub();
1324       set_target(*stub);
1325       TRACE_IC("StoreIC", name);
1326     } else if (can_store) {
1327       UpdateCaches(&lookup, receiver, name, value);
1328     } else if (!name->IsCacheable(isolate()) ||
1329                lookup.IsNormal() ||
1330                (lookup.IsField() && lookup.CanHoldValue(value))) {
1331       Handle<Code> stub = generic_stub();
1332       set_target(*stub);
1333     }
1334   }
1335
1336   // Set the property.
1337   Handle<Object> result;
1338   ASSIGN_RETURN_ON_EXCEPTION(
1339       isolate(),
1340       result,
1341       JSReceiver::SetProperty(
1342           receiver, name, value, NONE, strict_mode(), store_mode),
1343       Object);
1344   return result;
1345 }
1346
1347
1348 void CallIC::State::Print(StringStream* stream) const {
1349   stream->Add("(args(%d), ",
1350               argc_);
1351   stream->Add("%s, ",
1352               call_type_ == CallIC::METHOD ? "METHOD" : "FUNCTION");
1353 }
1354
1355
1356 Handle<Code> CallIC::initialize_stub(Isolate* isolate,
1357                                      int argc,
1358                                      CallType call_type) {
1359   CallICStub stub(isolate, State::DefaultCallState(argc, call_type));
1360   Handle<Code> code = stub.GetCode();
1361   return code;
1362 }
1363
1364
1365 Handle<Code> StoreIC::initialize_stub(Isolate* isolate,
1366                                       StrictMode strict_mode) {
1367   ExtraICState extra_state = ComputeExtraICState(strict_mode);
1368   Handle<Code> ic = isolate->stub_cache()->ComputeStore(
1369       UNINITIALIZED, extra_state);
1370   return ic;
1371 }
1372
1373
1374 Handle<Code> StoreIC::megamorphic_stub() {
1375   return isolate()->stub_cache()->ComputeStore(MEGAMORPHIC, extra_ic_state());
1376 }
1377
1378
1379 Handle<Code> StoreIC::generic_stub() const {
1380   return isolate()->stub_cache()->ComputeStore(GENERIC, extra_ic_state());
1381 }
1382
1383
1384 Handle<Code> StoreIC::pre_monomorphic_stub(Isolate* isolate,
1385                                            StrictMode strict_mode) {
1386   ExtraICState state = ComputeExtraICState(strict_mode);
1387   return isolate->stub_cache()->ComputeStore(PREMONOMORPHIC, state);
1388 }
1389
1390
1391 void StoreIC::UpdateCaches(LookupResult* lookup,
1392                            Handle<JSObject> receiver,
1393                            Handle<String> name,
1394                            Handle<Object> value) {
1395   ASSERT(lookup->IsFound());
1396
1397   // These are not cacheable, so we never see such LookupResults here.
1398   ASSERT(!lookup->IsHandler());
1399
1400   Handle<Code> code = ComputeHandler(lookup, receiver, name, value);
1401
1402   PatchCache(CurrentTypeOf(receiver, isolate()), name, code);
1403   TRACE_IC("StoreIC", name);
1404 }
1405
1406
1407 Handle<Code> StoreIC::CompileHandler(LookupResult* lookup,
1408                                      Handle<Object> object,
1409                                      Handle<String> name,
1410                                      Handle<Object> value,
1411                                      InlineCacheHolderFlag cache_holder) {
1412   if (object->IsAccessCheckNeeded()) return slow_stub();
1413   ASSERT(cache_holder == OWN_MAP);
1414   // This is currently guaranteed by checks in StoreIC::Store.
1415   Handle<JSObject> receiver = Handle<JSObject>::cast(object);
1416
1417   Handle<JSObject> holder(lookup->holder());
1418   // Handlers do not use strict mode.
1419   StoreStubCompiler compiler(isolate(), SLOPPY, kind());
1420   if (lookup->IsTransition()) {
1421     // Explicitly pass in the receiver map since LookupForWrite may have
1422     // stored something else than the receiver in the holder.
1423     Handle<Map> transition(lookup->GetTransitionTarget());
1424     PropertyDetails details = lookup->GetPropertyDetails();
1425
1426     if (details.type() != CALLBACKS && details.attributes() == NONE) {
1427       return compiler.CompileStoreTransition(
1428           receiver, lookup, transition, name);
1429     }
1430   } else {
1431     switch (lookup->type()) {
1432       case FIELD:
1433         return compiler.CompileStoreField(receiver, lookup, name);
1434       case NORMAL:
1435         if (kind() == Code::KEYED_STORE_IC) break;
1436         if (receiver->IsJSGlobalProxy() || receiver->IsGlobalObject()) {
1437           // The stub generated for the global object picks the value directly
1438           // from the property cell. So the property must be directly on the
1439           // global object.
1440           Handle<GlobalObject> global = receiver->IsJSGlobalProxy()
1441               ? handle(GlobalObject::cast(receiver->GetPrototype()))
1442               : Handle<GlobalObject>::cast(receiver);
1443           Handle<PropertyCell> cell(global->GetPropertyCell(lookup), isolate());
1444           Handle<HeapType> union_type = PropertyCell::UpdatedType(cell, value);
1445           StoreGlobalStub stub(
1446               isolate(), union_type->IsConstant(), receiver->IsJSGlobalProxy());
1447           Handle<Code> code = stub.GetCodeCopyFromTemplate(global, cell);
1448           // TODO(verwaest): Move caching of these NORMAL stubs outside as well.
1449           HeapObject::UpdateMapCodeCache(receiver, name, code);
1450           return code;
1451         }
1452         ASSERT(holder.is_identical_to(receiver));
1453         return isolate()->builtins()->StoreIC_Normal();
1454       case CALLBACKS: {
1455         Handle<Object> callback(lookup->GetCallbackObject(), isolate());
1456         if (callback->IsExecutableAccessorInfo()) {
1457           Handle<ExecutableAccessorInfo> info =
1458               Handle<ExecutableAccessorInfo>::cast(callback);
1459           if (v8::ToCData<Address>(info->setter()) == 0) break;
1460           if (!holder->HasFastProperties()) break;
1461           if (!info->IsCompatibleReceiver(*receiver)) break;
1462           return compiler.CompileStoreCallback(receiver, holder, name, info);
1463         } else if (callback->IsAccessorPair()) {
1464           Handle<Object> setter(
1465               Handle<AccessorPair>::cast(callback)->setter(), isolate());
1466           if (!setter->IsJSFunction()) break;
1467           if (holder->IsGlobalObject()) break;
1468           if (!holder->HasFastProperties()) break;
1469           Handle<JSFunction> function = Handle<JSFunction>::cast(setter);
1470           CallOptimization call_optimization(function);
1471           if (call_optimization.is_simple_api_call() &&
1472               call_optimization.IsCompatibleReceiver(receiver, holder)) {
1473             return compiler.CompileStoreCallback(
1474                 receiver, holder, name, call_optimization);
1475           }
1476           return compiler.CompileStoreViaSetter(
1477               receiver, holder, name, Handle<JSFunction>::cast(setter));
1478         }
1479         // TODO(dcarney): Handle correctly.
1480         ASSERT(callback->IsDeclaredAccessorInfo());
1481         break;
1482       }
1483       case INTERCEPTOR:
1484         if (kind() == Code::KEYED_STORE_IC) break;
1485         ASSERT(HasInterceptorSetter(*holder));
1486         return compiler.CompileStoreInterceptor(receiver, name);
1487       case CONSTANT:
1488         break;
1489       case NONEXISTENT:
1490       case HANDLER:
1491         UNREACHABLE();
1492         break;
1493     }
1494   }
1495   return slow_stub();
1496 }
1497
1498
1499 Handle<Code> KeyedStoreIC::StoreElementStub(Handle<JSObject> receiver,
1500                                             KeyedAccessStoreMode store_mode) {
1501   // Don't handle megamorphic property accesses for INTERCEPTORS or CALLBACKS
1502   // via megamorphic stubs, since they don't have a map in their relocation info
1503   // and so the stubs can't be harvested for the object needed for a map check.
1504   if (target()->type() != Code::NORMAL) {
1505     TRACE_GENERIC_IC(isolate(), "KeyedIC", "non-NORMAL target type");
1506     return generic_stub();
1507   }
1508
1509   Handle<Map> receiver_map(receiver->map(), isolate());
1510   MapHandleList target_receiver_maps;
1511   TargetMaps(&target_receiver_maps);
1512   if (target_receiver_maps.length() == 0) {
1513     Handle<Map> monomorphic_map =
1514         ComputeTransitionedMap(receiver_map, store_mode);
1515     store_mode = GetNonTransitioningStoreMode(store_mode);
1516     return isolate()->stub_cache()->ComputeKeyedStoreElement(
1517         monomorphic_map, strict_mode(), store_mode);
1518   }
1519
1520   // There are several special cases where an IC that is MONOMORPHIC can still
1521   // transition to a different GetNonTransitioningStoreMode IC that handles a
1522   // superset of the original IC. Handle those here if the receiver map hasn't
1523   // changed or it has transitioned to a more general kind.
1524   KeyedAccessStoreMode old_store_mode =
1525       KeyedStoreIC::GetKeyedAccessStoreMode(target()->extra_ic_state());
1526   Handle<Map> previous_receiver_map = target_receiver_maps.at(0);
1527   if (state() == MONOMORPHIC) {
1528     Handle<Map> transitioned_receiver_map = receiver_map;
1529     if (IsTransitionStoreMode(store_mode)) {
1530       transitioned_receiver_map =
1531           ComputeTransitionedMap(receiver_map, store_mode);
1532     }
1533     if ((receiver_map.is_identical_to(previous_receiver_map) &&
1534          IsTransitionStoreMode(store_mode)) ||
1535         IsTransitionOfMonomorphicTarget(*previous_receiver_map,
1536                                         *transitioned_receiver_map)) {
1537       // If the "old" and "new" maps are in the same elements map family, or
1538       // if they at least come from the same origin for a transitioning store,
1539       // stay MONOMORPHIC and use the map for the most generic ElementsKind.
1540       store_mode = GetNonTransitioningStoreMode(store_mode);
1541       return isolate()->stub_cache()->ComputeKeyedStoreElement(
1542           transitioned_receiver_map, strict_mode(), store_mode);
1543     } else if (*previous_receiver_map == receiver->map() &&
1544                old_store_mode == STANDARD_STORE &&
1545                (store_mode == STORE_AND_GROW_NO_TRANSITION ||
1546                 store_mode == STORE_NO_TRANSITION_IGNORE_OUT_OF_BOUNDS ||
1547                 store_mode == STORE_NO_TRANSITION_HANDLE_COW)) {
1548       // A "normal" IC that handles stores can switch to a version that can
1549       // grow at the end of the array, handle OOB accesses or copy COW arrays
1550       // and still stay MONOMORPHIC.
1551       return isolate()->stub_cache()->ComputeKeyedStoreElement(
1552           receiver_map, strict_mode(), store_mode);
1553     }
1554   }
1555
1556   ASSERT(state() != GENERIC);
1557
1558   bool map_added =
1559       AddOneReceiverMapIfMissing(&target_receiver_maps, receiver_map);
1560
1561   if (IsTransitionStoreMode(store_mode)) {
1562     Handle<Map> transitioned_receiver_map =
1563         ComputeTransitionedMap(receiver_map, store_mode);
1564     map_added |= AddOneReceiverMapIfMissing(&target_receiver_maps,
1565                                             transitioned_receiver_map);
1566   }
1567
1568   if (!map_added) {
1569     // If the miss wasn't due to an unseen map, a polymorphic stub
1570     // won't help, use the generic stub.
1571     TRACE_GENERIC_IC(isolate(), "KeyedIC", "same map added twice");
1572     return generic_stub();
1573   }
1574
1575   // If the maximum number of receiver maps has been exceeded, use the generic
1576   // version of the IC.
1577   if (target_receiver_maps.length() > kMaxKeyedPolymorphism) {
1578     TRACE_GENERIC_IC(isolate(), "KeyedIC", "max polymorph exceeded");
1579     return generic_stub();
1580   }
1581
1582   // Make sure all polymorphic handlers have the same store mode, otherwise the
1583   // generic stub must be used.
1584   store_mode = GetNonTransitioningStoreMode(store_mode);
1585   if (old_store_mode != STANDARD_STORE) {
1586     if (store_mode == STANDARD_STORE) {
1587       store_mode = old_store_mode;
1588     } else if (store_mode != old_store_mode) {
1589       TRACE_GENERIC_IC(isolate(), "KeyedIC", "store mode mismatch");
1590       return generic_stub();
1591     }
1592   }
1593
1594   // If the store mode isn't the standard mode, make sure that all polymorphic
1595   // receivers are either external arrays, or all "normal" arrays. Otherwise,
1596   // use the generic stub.
1597   if (store_mode != STANDARD_STORE) {
1598     int external_arrays = 0;
1599     for (int i = 0; i < target_receiver_maps.length(); ++i) {
1600       if (target_receiver_maps[i]->has_external_array_elements() ||
1601           target_receiver_maps[i]->has_fixed_typed_array_elements()) {
1602         external_arrays++;
1603       }
1604     }
1605     if (external_arrays != 0 &&
1606         external_arrays != target_receiver_maps.length()) {
1607       TRACE_GENERIC_IC(isolate(), "KeyedIC",
1608           "unsupported combination of external and normal arrays");
1609       return generic_stub();
1610     }
1611   }
1612
1613   return isolate()->stub_cache()->ComputeStoreElementPolymorphic(
1614       &target_receiver_maps, store_mode, strict_mode());
1615 }
1616
1617
1618 Handle<Map> KeyedStoreIC::ComputeTransitionedMap(
1619     Handle<Map> map,
1620     KeyedAccessStoreMode store_mode) {
1621   switch (store_mode) {
1622     case STORE_TRANSITION_SMI_TO_OBJECT:
1623     case STORE_TRANSITION_DOUBLE_TO_OBJECT:
1624     case STORE_AND_GROW_TRANSITION_SMI_TO_OBJECT:
1625     case STORE_AND_GROW_TRANSITION_DOUBLE_TO_OBJECT:
1626       return Map::TransitionElementsTo(map, FAST_ELEMENTS);
1627     case STORE_TRANSITION_SMI_TO_DOUBLE:
1628     case STORE_AND_GROW_TRANSITION_SMI_TO_DOUBLE:
1629       return Map::TransitionElementsTo(map, FAST_DOUBLE_ELEMENTS);
1630     case STORE_TRANSITION_HOLEY_SMI_TO_OBJECT:
1631     case STORE_TRANSITION_HOLEY_DOUBLE_TO_OBJECT:
1632     case STORE_AND_GROW_TRANSITION_HOLEY_SMI_TO_OBJECT:
1633     case STORE_AND_GROW_TRANSITION_HOLEY_DOUBLE_TO_OBJECT:
1634       return Map::TransitionElementsTo(map, FAST_HOLEY_ELEMENTS);
1635     case STORE_TRANSITION_HOLEY_SMI_TO_DOUBLE:
1636     case STORE_AND_GROW_TRANSITION_HOLEY_SMI_TO_DOUBLE:
1637       return Map::TransitionElementsTo(map, FAST_HOLEY_DOUBLE_ELEMENTS);
1638     case STORE_NO_TRANSITION_IGNORE_OUT_OF_BOUNDS:
1639       ASSERT(map->has_external_array_elements());
1640       // Fall through
1641     case STORE_NO_TRANSITION_HANDLE_COW:
1642     case STANDARD_STORE:
1643     case STORE_AND_GROW_NO_TRANSITION:
1644       return map;
1645   }
1646   UNREACHABLE();
1647   return MaybeHandle<Map>().ToHandleChecked();
1648 }
1649
1650
1651 bool IsOutOfBoundsAccess(Handle<JSObject> receiver,
1652                          int index) {
1653   if (receiver->IsJSArray()) {
1654     return JSArray::cast(*receiver)->length()->IsSmi() &&
1655         index >= Smi::cast(JSArray::cast(*receiver)->length())->value();
1656   }
1657   return index >= receiver->elements()->length();
1658 }
1659
1660
1661 KeyedAccessStoreMode KeyedStoreIC::GetStoreMode(Handle<JSObject> receiver,
1662                                                 Handle<Object> key,
1663                                                 Handle<Object> value) {
1664   Handle<Smi> smi_key = Object::ToSmi(isolate(), key).ToHandleChecked();
1665   int index = smi_key->value();
1666   bool oob_access = IsOutOfBoundsAccess(receiver, index);
1667   // Don't consider this a growing store if the store would send the receiver to
1668   // dictionary mode.
1669   bool allow_growth = receiver->IsJSArray() && oob_access &&
1670       !receiver->WouldConvertToSlowElements(key);
1671   if (allow_growth) {
1672     // Handle growing array in stub if necessary.
1673     if (receiver->HasFastSmiElements()) {
1674       if (value->IsHeapNumber()) {
1675         if (receiver->HasFastHoleyElements()) {
1676           return STORE_AND_GROW_TRANSITION_HOLEY_SMI_TO_DOUBLE;
1677         } else {
1678           return STORE_AND_GROW_TRANSITION_SMI_TO_DOUBLE;
1679         }
1680       }
1681       if (value->IsHeapObject()) {
1682         if (receiver->HasFastHoleyElements()) {
1683           return STORE_AND_GROW_TRANSITION_HOLEY_SMI_TO_OBJECT;
1684         } else {
1685           return STORE_AND_GROW_TRANSITION_SMI_TO_OBJECT;
1686         }
1687       }
1688     } else if (receiver->HasFastDoubleElements()) {
1689       if (!value->IsSmi() && !value->IsHeapNumber()) {
1690         if (receiver->HasFastHoleyElements()) {
1691           return STORE_AND_GROW_TRANSITION_HOLEY_DOUBLE_TO_OBJECT;
1692         } else {
1693           return STORE_AND_GROW_TRANSITION_DOUBLE_TO_OBJECT;
1694         }
1695       }
1696     }
1697     return STORE_AND_GROW_NO_TRANSITION;
1698   } else {
1699     // Handle only in-bounds elements accesses.
1700     if (receiver->HasFastSmiElements()) {
1701       if (value->IsHeapNumber()) {
1702         if (receiver->HasFastHoleyElements()) {
1703           return STORE_TRANSITION_HOLEY_SMI_TO_DOUBLE;
1704         } else {
1705           return STORE_TRANSITION_SMI_TO_DOUBLE;
1706         }
1707       } else if (value->IsHeapObject()) {
1708         if (receiver->HasFastHoleyElements()) {
1709           return STORE_TRANSITION_HOLEY_SMI_TO_OBJECT;
1710         } else {
1711           return STORE_TRANSITION_SMI_TO_OBJECT;
1712         }
1713       }
1714     } else if (receiver->HasFastDoubleElements()) {
1715       if (!value->IsSmi() && !value->IsHeapNumber()) {
1716         if (receiver->HasFastHoleyElements()) {
1717           return STORE_TRANSITION_HOLEY_DOUBLE_TO_OBJECT;
1718         } else {
1719           return STORE_TRANSITION_DOUBLE_TO_OBJECT;
1720         }
1721       }
1722     }
1723     if (!FLAG_trace_external_array_abuse &&
1724         receiver->map()->has_external_array_elements() && oob_access) {
1725       return STORE_NO_TRANSITION_IGNORE_OUT_OF_BOUNDS;
1726     }
1727     Heap* heap = receiver->GetHeap();
1728     if (receiver->elements()->map() == heap->fixed_cow_array_map()) {
1729       return STORE_NO_TRANSITION_HANDLE_COW;
1730     } else {
1731       return STANDARD_STORE;
1732     }
1733   }
1734 }
1735
1736
1737 MaybeHandle<Object> KeyedStoreIC::Store(Handle<Object> object,
1738                                         Handle<Object> key,
1739                                         Handle<Object> value) {
1740   if (MigrateDeprecated(object)) {
1741     Handle<Object> result;
1742     ASSIGN_RETURN_ON_EXCEPTION(
1743         isolate(),
1744         result,
1745         Runtime::SetObjectProperty(
1746             isolate(), object, key, value, NONE, strict_mode()),
1747         Object);
1748     return result;
1749   }
1750
1751   // Check for non-string values that can be converted into an
1752   // internalized string directly or is representable as a smi.
1753   key = TryConvertKey(key, isolate());
1754
1755   Handle<Object> store_handle;
1756   Handle<Code> stub = generic_stub();
1757
1758   if (key->IsInternalizedString()) {
1759     ASSIGN_RETURN_ON_EXCEPTION(
1760         isolate(),
1761         store_handle,
1762         StoreIC::Store(object,
1763                        Handle<String>::cast(key),
1764                        value,
1765                        JSReceiver::MAY_BE_STORE_FROM_KEYED),
1766         Object);
1767   } else {
1768     bool use_ic = FLAG_use_ic &&
1769         !object->IsStringWrapper() &&
1770         !object->IsAccessCheckNeeded() &&
1771         !object->IsJSGlobalProxy() &&
1772         !(object->IsJSObject() &&
1773           JSObject::cast(*object)->map()->is_observed());
1774     if (use_ic && !object->IsSmi()) {
1775       // Don't use ICs for maps of the objects in Array's prototype chain. We
1776       // expect to be able to trap element sets to objects with those maps in
1777       // the runtime to enable optimization of element hole access.
1778       Handle<HeapObject> heap_object = Handle<HeapObject>::cast(object);
1779       if (heap_object->map()->IsMapInArrayPrototypeChain()) use_ic = false;
1780     }
1781
1782     if (use_ic) {
1783       ASSERT(!object->IsAccessCheckNeeded());
1784
1785       if (object->IsJSObject()) {
1786         Handle<JSObject> receiver = Handle<JSObject>::cast(object);
1787         bool key_is_smi_like = !Object::ToSmi(isolate(), key).is_null();
1788         if (receiver->elements()->map() ==
1789             isolate()->heap()->sloppy_arguments_elements_map()) {
1790           if (strict_mode() == SLOPPY) {
1791             stub = sloppy_arguments_stub();
1792           }
1793         } else if (key_is_smi_like &&
1794                    !(target().is_identical_to(sloppy_arguments_stub()))) {
1795           // We should go generic if receiver isn't a dictionary, but our
1796           // prototype chain does have dictionary elements. This ensures that
1797           // other non-dictionary receivers in the polymorphic case benefit
1798           // from fast path keyed stores.
1799           if (!(receiver->map()->DictionaryElementsInPrototypeChainOnly())) {
1800             KeyedAccessStoreMode store_mode =
1801                 GetStoreMode(receiver, key, value);
1802             stub = StoreElementStub(receiver, store_mode);
1803           }
1804         }
1805       }
1806     }
1807   }
1808
1809   if (!is_target_set()) {
1810     if (*stub == *generic_stub()) {
1811       TRACE_GENERIC_IC(isolate(), "KeyedStoreIC", "set generic");
1812     }
1813     ASSERT(!stub.is_null());
1814     set_target(*stub);
1815     TRACE_IC("StoreIC", key);
1816   }
1817
1818   if (!store_handle.is_null()) return store_handle;
1819   Handle<Object> result;
1820   ASSIGN_RETURN_ON_EXCEPTION(
1821       isolate(),
1822       result,
1823       Runtime::SetObjectProperty(
1824           isolate(), object, key, value,  NONE, strict_mode()),
1825       Object);
1826   return result;
1827 }
1828
1829
1830 CallIC::State::State(ExtraICState extra_ic_state)
1831     : argc_(ArgcBits::decode(extra_ic_state)),
1832       call_type_(CallTypeBits::decode(extra_ic_state)) {
1833 }
1834
1835
1836 ExtraICState CallIC::State::GetExtraICState() const {
1837   ExtraICState extra_ic_state =
1838       ArgcBits::encode(argc_) |
1839       CallTypeBits::encode(call_type_);
1840   return extra_ic_state;
1841 }
1842
1843
1844 void CallIC::HandleMiss(Handle<Object> receiver,
1845                         Handle<Object> function,
1846                         Handle<FixedArray> vector,
1847                         Handle<Smi> slot) {
1848   State state(target()->extra_ic_state());
1849   Object* feedback = vector->get(slot->value());
1850
1851   if (feedback->IsJSFunction() || !function->IsJSFunction()) {
1852     // We are going generic.
1853     ASSERT(!function->IsJSFunction() || *function != feedback);
1854
1855     vector->set(slot->value(),
1856                 *TypeFeedbackInfo::MegamorphicSentinel(isolate()),
1857                 SKIP_WRITE_BARRIER);
1858     TRACE_GENERIC_IC(isolate(), "CallIC", "megamorphic");
1859   } else {
1860     // If we came here feedback must be the uninitialized sentinel,
1861     // and we are going monomorphic.
1862     ASSERT(feedback == *TypeFeedbackInfo::UninitializedSentinel(isolate()));
1863     Handle<JSFunction> js_function = Handle<JSFunction>::cast(function);
1864     Handle<Object> name(js_function->shared()->name(), isolate());
1865     TRACE_IC("CallIC", name);
1866     vector->set(slot->value(), *function);
1867   }
1868 }
1869
1870
1871 #undef TRACE_IC
1872
1873
1874 // ----------------------------------------------------------------------------
1875 // Static IC stub generators.
1876 //
1877
1878 // Used from ic-<arch>.cc.
1879 RUNTIME_FUNCTION(CallIC_Miss) {
1880   HandleScope scope(isolate);
1881   ASSERT(args.length() == 4);
1882   CallIC ic(isolate);
1883   Handle<Object> receiver = args.at<Object>(0);
1884   Handle<Object> function = args.at<Object>(1);
1885   Handle<FixedArray> vector = args.at<FixedArray>(2);
1886   Handle<Smi> slot = args.at<Smi>(3);
1887   ic.HandleMiss(receiver, function, vector, slot);
1888   return *function;
1889 }
1890
1891
1892 // Used from ic-<arch>.cc.
1893 RUNTIME_FUNCTION(LoadIC_Miss) {
1894   HandleScope scope(isolate);
1895   ASSERT(args.length() == 2);
1896   LoadIC ic(IC::NO_EXTRA_FRAME, isolate);
1897   Handle<Object> receiver = args.at<Object>(0);
1898   Handle<String> key = args.at<String>(1);
1899   ic.UpdateState(receiver, key);
1900   Handle<Object> result;
1901   ASSIGN_RETURN_FAILURE_ON_EXCEPTION(isolate, result, ic.Load(receiver, key));
1902   return *result;
1903 }
1904
1905
1906 // Used from ic-<arch>.cc
1907 RUNTIME_FUNCTION(KeyedLoadIC_Miss) {
1908   HandleScope scope(isolate);
1909   ASSERT(args.length() == 2);
1910   KeyedLoadIC ic(IC::NO_EXTRA_FRAME, isolate);
1911   Handle<Object> receiver = args.at<Object>(0);
1912   Handle<Object> key = args.at<Object>(1);
1913   ic.UpdateState(receiver, key);
1914   Handle<Object> result;
1915   ASSIGN_RETURN_FAILURE_ON_EXCEPTION(isolate, result, ic.Load(receiver, key));
1916   return *result;
1917 }
1918
1919
1920 RUNTIME_FUNCTION(KeyedLoadIC_MissFromStubFailure) {
1921   HandleScope scope(isolate);
1922   ASSERT(args.length() == 2);
1923   KeyedLoadIC ic(IC::EXTRA_CALL_FRAME, isolate);
1924   Handle<Object> receiver = args.at<Object>(0);
1925   Handle<Object> key = args.at<Object>(1);
1926   ic.UpdateState(receiver, key);
1927   Handle<Object> result;
1928   ASSIGN_RETURN_FAILURE_ON_EXCEPTION(isolate, result, ic.Load(receiver, key));
1929   return *result;
1930 }
1931
1932
1933 // Used from ic-<arch>.cc.
1934 RUNTIME_FUNCTION(StoreIC_Miss) {
1935   HandleScope scope(isolate);
1936   ASSERT(args.length() == 3);
1937   StoreIC ic(IC::NO_EXTRA_FRAME, isolate);
1938   Handle<Object> receiver = args.at<Object>(0);
1939   Handle<String> key = args.at<String>(1);
1940   ic.UpdateState(receiver, key);
1941   Handle<Object> result;
1942   ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
1943       isolate,
1944       result,
1945       ic.Store(receiver, key, args.at<Object>(2)));
1946   return *result;
1947 }
1948
1949
1950 RUNTIME_FUNCTION(StoreIC_MissFromStubFailure) {
1951   HandleScope scope(isolate);
1952   ASSERT(args.length() == 3);
1953   StoreIC ic(IC::EXTRA_CALL_FRAME, isolate);
1954   Handle<Object> receiver = args.at<Object>(0);
1955   Handle<String> key = args.at<String>(1);
1956   ic.UpdateState(receiver, key);
1957   Handle<Object> result;
1958   ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
1959       isolate,
1960       result,
1961       ic.Store(receiver, key, args.at<Object>(2)));
1962   return *result;
1963 }
1964
1965
1966 RUNTIME_FUNCTION(StoreIC_ArrayLength) {
1967   HandleScope scope(isolate);
1968
1969   ASSERT(args.length() == 2);
1970   Handle<JSArray> receiver = args.at<JSArray>(0);
1971   Handle<Object> len = args.at<Object>(1);
1972
1973   // The generated code should filter out non-Smis before we get here.
1974   ASSERT(len->IsSmi());
1975
1976 #ifdef DEBUG
1977   // The length property has to be a writable callback property.
1978   LookupResult debug_lookup(isolate);
1979   receiver->LocalLookup(isolate->factory()->length_string(), &debug_lookup);
1980   ASSERT(debug_lookup.IsPropertyCallbacks() && !debug_lookup.IsReadOnly());
1981 #endif
1982
1983   RETURN_FAILURE_ON_EXCEPTION(
1984       isolate, JSArray::SetElementsLength(receiver, len));
1985   return *len;
1986 }
1987
1988
1989 // Extend storage is called in a store inline cache when
1990 // it is necessary to extend the properties array of a
1991 // JSObject.
1992 RUNTIME_FUNCTION(SharedStoreIC_ExtendStorage) {
1993   HandleScope shs(isolate);
1994   ASSERT(args.length() == 3);
1995
1996   // Convert the parameters
1997   Handle<JSObject> object = args.at<JSObject>(0);
1998   Handle<Map> transition = args.at<Map>(1);
1999   Handle<Object> value = args.at<Object>(2);
2000
2001   // Check the object has run out out property space.
2002   ASSERT(object->HasFastProperties());
2003   ASSERT(object->map()->unused_property_fields() == 0);
2004
2005   // Expand the properties array.
2006   Handle<FixedArray> old_storage = handle(object->properties(), isolate);
2007   int new_unused = transition->unused_property_fields();
2008   int new_size = old_storage->length() + new_unused + 1;
2009
2010   Handle<FixedArray> new_storage = FixedArray::CopySize(old_storage, new_size);
2011
2012   Handle<Object> to_store = value;
2013
2014   PropertyDetails details = transition->instance_descriptors()->GetDetails(
2015       transition->LastAdded());
2016   if (details.representation().IsDouble()) {
2017     to_store = isolate->factory()->NewHeapNumber(value->Number());
2018   }
2019
2020   new_storage->set(old_storage->length(), *to_store);
2021
2022   // Set the new property value and do the map transition.
2023   object->set_properties(*new_storage);
2024   object->set_map(*transition);
2025
2026   // Return the stored value.
2027   return *value;
2028 }
2029
2030
2031 // Used from ic-<arch>.cc.
2032 RUNTIME_FUNCTION(KeyedStoreIC_Miss) {
2033   HandleScope scope(isolate);
2034   ASSERT(args.length() == 3);
2035   KeyedStoreIC ic(IC::NO_EXTRA_FRAME, isolate);
2036   Handle<Object> receiver = args.at<Object>(0);
2037   Handle<Object> key = args.at<Object>(1);
2038   ic.UpdateState(receiver, key);
2039   Handle<Object> result;
2040   ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
2041       isolate,
2042       result,
2043       ic.Store(receiver, key, args.at<Object>(2)));
2044   return *result;
2045 }
2046
2047
2048 RUNTIME_FUNCTION(KeyedStoreIC_MissFromStubFailure) {
2049   HandleScope scope(isolate);
2050   ASSERT(args.length() == 3);
2051   KeyedStoreIC ic(IC::EXTRA_CALL_FRAME, isolate);
2052   Handle<Object> receiver = args.at<Object>(0);
2053   Handle<Object> key = args.at<Object>(1);
2054   ic.UpdateState(receiver, key);
2055   Handle<Object> result;
2056   ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
2057       isolate,
2058       result,
2059       ic.Store(receiver, key, args.at<Object>(2)));
2060   return *result;
2061 }
2062
2063
2064 RUNTIME_FUNCTION(StoreIC_Slow) {
2065   HandleScope scope(isolate);
2066   ASSERT(args.length() == 3);
2067   StoreIC ic(IC::NO_EXTRA_FRAME, isolate);
2068   Handle<Object> object = args.at<Object>(0);
2069   Handle<Object> key = args.at<Object>(1);
2070   Handle<Object> value = args.at<Object>(2);
2071   StrictMode strict_mode = ic.strict_mode();
2072   Handle<Object> result;
2073   ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
2074       isolate, result,
2075       Runtime::SetObjectProperty(
2076           isolate, object, key, value, NONE, strict_mode));
2077   return *result;
2078 }
2079
2080
2081 RUNTIME_FUNCTION(KeyedStoreIC_Slow) {
2082   HandleScope scope(isolate);
2083   ASSERT(args.length() == 3);
2084   KeyedStoreIC ic(IC::NO_EXTRA_FRAME, isolate);
2085   Handle<Object> object = args.at<Object>(0);
2086   Handle<Object> key = args.at<Object>(1);
2087   Handle<Object> value = args.at<Object>(2);
2088   StrictMode strict_mode = ic.strict_mode();
2089   Handle<Object> result;
2090   ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
2091       isolate, result,
2092       Runtime::SetObjectProperty(
2093           isolate, object, key, value, NONE, strict_mode));
2094   return *result;
2095 }
2096
2097
2098 RUNTIME_FUNCTION(ElementsTransitionAndStoreIC_Miss) {
2099   HandleScope scope(isolate);
2100   ASSERT(args.length() == 4);
2101   KeyedStoreIC ic(IC::EXTRA_CALL_FRAME, isolate);
2102   Handle<Object> value = args.at<Object>(0);
2103   Handle<Map> map = args.at<Map>(1);
2104   Handle<Object> key = args.at<Object>(2);
2105   Handle<Object> object = args.at<Object>(3);
2106   StrictMode strict_mode = ic.strict_mode();
2107   if (object->IsJSObject()) {
2108     JSObject::TransitionElementsKind(Handle<JSObject>::cast(object),
2109                                      map->elements_kind());
2110   }
2111   Handle<Object> result;
2112   ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
2113       isolate, result,
2114       Runtime::SetObjectProperty(
2115           isolate, object, key, value, NONE, strict_mode));
2116   return *result;
2117 }
2118
2119
2120 BinaryOpIC::State::State(Isolate* isolate, ExtraICState extra_ic_state)
2121     : isolate_(isolate) {
2122   // We don't deserialize the SSE2 Field, since this is only used to be able
2123   // to include SSE2 as well as non-SSE2 versions in the snapshot. For code
2124   // generation we always want it to reflect the current state.
2125   op_ = static_cast<Token::Value>(
2126       FIRST_TOKEN + OpField::decode(extra_ic_state));
2127   mode_ = OverwriteModeField::decode(extra_ic_state);
2128   fixed_right_arg_ = Maybe<int>(
2129       HasFixedRightArgField::decode(extra_ic_state),
2130       1 << FixedRightArgValueField::decode(extra_ic_state));
2131   left_kind_ = LeftKindField::decode(extra_ic_state);
2132   if (fixed_right_arg_.has_value) {
2133     right_kind_ = Smi::IsValid(fixed_right_arg_.value) ? SMI : INT32;
2134   } else {
2135     right_kind_ = RightKindField::decode(extra_ic_state);
2136   }
2137   result_kind_ = ResultKindField::decode(extra_ic_state);
2138   ASSERT_LE(FIRST_TOKEN, op_);
2139   ASSERT_LE(op_, LAST_TOKEN);
2140 }
2141
2142
2143 ExtraICState BinaryOpIC::State::GetExtraICState() const {
2144   bool sse2 = (Max(result_kind_, Max(left_kind_, right_kind_)) > SMI &&
2145                CpuFeatures::IsSafeForSnapshot(isolate(), SSE2));
2146   ExtraICState extra_ic_state =
2147       SSE2Field::encode(sse2) |
2148       OpField::encode(op_ - FIRST_TOKEN) |
2149       OverwriteModeField::encode(mode_) |
2150       LeftKindField::encode(left_kind_) |
2151       ResultKindField::encode(result_kind_) |
2152       HasFixedRightArgField::encode(fixed_right_arg_.has_value);
2153   if (fixed_right_arg_.has_value) {
2154     extra_ic_state = FixedRightArgValueField::update(
2155         extra_ic_state, WhichPowerOf2(fixed_right_arg_.value));
2156   } else {
2157     extra_ic_state = RightKindField::update(extra_ic_state, right_kind_);
2158   }
2159   return extra_ic_state;
2160 }
2161
2162
2163 // static
2164 void BinaryOpIC::State::GenerateAheadOfTime(
2165     Isolate* isolate, void (*Generate)(Isolate*, const State&)) {
2166   // TODO(olivf) We should investigate why adding stubs to the snapshot is so
2167   // expensive at runtime. When solved we should be able to add most binops to
2168   // the snapshot instead of hand-picking them.
2169   // Generated list of commonly used stubs
2170 #define GENERATE(op, left_kind, right_kind, result_kind, mode)  \
2171   do {                                                          \
2172     State state(isolate, op, mode);                             \
2173     state.left_kind_ = left_kind;                               \
2174     state.fixed_right_arg_.has_value = false;                   \
2175     state.right_kind_ = right_kind;                             \
2176     state.result_kind_ = result_kind;                           \
2177     Generate(isolate, state);                                   \
2178   } while (false)
2179   GENERATE(Token::ADD, INT32, INT32, INT32, NO_OVERWRITE);
2180   GENERATE(Token::ADD, INT32, INT32, INT32, OVERWRITE_LEFT);
2181   GENERATE(Token::ADD, INT32, INT32, NUMBER, NO_OVERWRITE);
2182   GENERATE(Token::ADD, INT32, INT32, NUMBER, OVERWRITE_LEFT);
2183   GENERATE(Token::ADD, INT32, NUMBER, NUMBER, NO_OVERWRITE);
2184   GENERATE(Token::ADD, INT32, NUMBER, NUMBER, OVERWRITE_LEFT);
2185   GENERATE(Token::ADD, INT32, NUMBER, NUMBER, OVERWRITE_RIGHT);
2186   GENERATE(Token::ADD, INT32, SMI, INT32, NO_OVERWRITE);
2187   GENERATE(Token::ADD, INT32, SMI, INT32, OVERWRITE_LEFT);
2188   GENERATE(Token::ADD, INT32, SMI, INT32, OVERWRITE_RIGHT);
2189   GENERATE(Token::ADD, NUMBER, INT32, NUMBER, NO_OVERWRITE);
2190   GENERATE(Token::ADD, NUMBER, INT32, NUMBER, OVERWRITE_LEFT);
2191   GENERATE(Token::ADD, NUMBER, INT32, NUMBER, OVERWRITE_RIGHT);
2192   GENERATE(Token::ADD, NUMBER, NUMBER, NUMBER, NO_OVERWRITE);
2193   GENERATE(Token::ADD, NUMBER, NUMBER, NUMBER, OVERWRITE_LEFT);
2194   GENERATE(Token::ADD, NUMBER, NUMBER, NUMBER, OVERWRITE_RIGHT);
2195   GENERATE(Token::ADD, NUMBER, SMI, NUMBER, NO_OVERWRITE);
2196   GENERATE(Token::ADD, NUMBER, SMI, NUMBER, OVERWRITE_LEFT);
2197   GENERATE(Token::ADD, NUMBER, SMI, NUMBER, OVERWRITE_RIGHT);
2198   GENERATE(Token::ADD, SMI, INT32, INT32, NO_OVERWRITE);
2199   GENERATE(Token::ADD, SMI, INT32, INT32, OVERWRITE_LEFT);
2200   GENERATE(Token::ADD, SMI, INT32, NUMBER, NO_OVERWRITE);
2201   GENERATE(Token::ADD, SMI, NUMBER, NUMBER, NO_OVERWRITE);
2202   GENERATE(Token::ADD, SMI, NUMBER, NUMBER, OVERWRITE_LEFT);
2203   GENERATE(Token::ADD, SMI, NUMBER, NUMBER, OVERWRITE_RIGHT);
2204   GENERATE(Token::ADD, SMI, SMI, INT32, OVERWRITE_LEFT);
2205   GENERATE(Token::ADD, SMI, SMI, SMI, OVERWRITE_RIGHT);
2206   GENERATE(Token::BIT_AND, INT32, INT32, INT32, NO_OVERWRITE);
2207   GENERATE(Token::BIT_AND, INT32, INT32, INT32, OVERWRITE_LEFT);
2208   GENERATE(Token::BIT_AND, INT32, INT32, INT32, OVERWRITE_RIGHT);
2209   GENERATE(Token::BIT_AND, INT32, INT32, SMI, NO_OVERWRITE);
2210   GENERATE(Token::BIT_AND, INT32, INT32, SMI, OVERWRITE_RIGHT);
2211   GENERATE(Token::BIT_AND, INT32, SMI, INT32, NO_OVERWRITE);
2212   GENERATE(Token::BIT_AND, INT32, SMI, INT32, OVERWRITE_RIGHT);
2213   GENERATE(Token::BIT_AND, INT32, SMI, SMI, NO_OVERWRITE);
2214   GENERATE(Token::BIT_AND, INT32, SMI, SMI, OVERWRITE_LEFT);
2215   GENERATE(Token::BIT_AND, INT32, SMI, SMI, OVERWRITE_RIGHT);
2216   GENERATE(Token::BIT_AND, NUMBER, INT32, INT32, OVERWRITE_RIGHT);
2217   GENERATE(Token::BIT_AND, NUMBER, SMI, SMI, NO_OVERWRITE);
2218   GENERATE(Token::BIT_AND, NUMBER, SMI, SMI, OVERWRITE_RIGHT);
2219   GENERATE(Token::BIT_AND, SMI, INT32, INT32, NO_OVERWRITE);
2220   GENERATE(Token::BIT_AND, SMI, INT32, SMI, OVERWRITE_RIGHT);
2221   GENERATE(Token::BIT_AND, SMI, NUMBER, SMI, OVERWRITE_RIGHT);
2222   GENERATE(Token::BIT_AND, SMI, SMI, SMI, NO_OVERWRITE);
2223   GENERATE(Token::BIT_AND, SMI, SMI, SMI, OVERWRITE_LEFT);
2224   GENERATE(Token::BIT_AND, SMI, SMI, SMI, OVERWRITE_RIGHT);
2225   GENERATE(Token::BIT_OR, INT32, INT32, INT32, OVERWRITE_LEFT);
2226   GENERATE(Token::BIT_OR, INT32, INT32, INT32, OVERWRITE_RIGHT);
2227   GENERATE(Token::BIT_OR, INT32, INT32, SMI, OVERWRITE_LEFT);
2228   GENERATE(Token::BIT_OR, INT32, SMI, INT32, NO_OVERWRITE);
2229   GENERATE(Token::BIT_OR, INT32, SMI, INT32, OVERWRITE_LEFT);
2230   GENERATE(Token::BIT_OR, INT32, SMI, INT32, OVERWRITE_RIGHT);
2231   GENERATE(Token::BIT_OR, INT32, SMI, SMI, NO_OVERWRITE);
2232   GENERATE(Token::BIT_OR, INT32, SMI, SMI, OVERWRITE_RIGHT);
2233   GENERATE(Token::BIT_OR, NUMBER, SMI, INT32, NO_OVERWRITE);
2234   GENERATE(Token::BIT_OR, NUMBER, SMI, INT32, OVERWRITE_LEFT);
2235   GENERATE(Token::BIT_OR, NUMBER, SMI, INT32, OVERWRITE_RIGHT);
2236   GENERATE(Token::BIT_OR, NUMBER, SMI, SMI, NO_OVERWRITE);
2237   GENERATE(Token::BIT_OR, NUMBER, SMI, SMI, OVERWRITE_LEFT);
2238   GENERATE(Token::BIT_OR, SMI, INT32, INT32, OVERWRITE_LEFT);
2239   GENERATE(Token::BIT_OR, SMI, INT32, INT32, OVERWRITE_RIGHT);
2240   GENERATE(Token::BIT_OR, SMI, INT32, SMI, OVERWRITE_RIGHT);
2241   GENERATE(Token::BIT_OR, SMI, SMI, SMI, OVERWRITE_LEFT);
2242   GENERATE(Token::BIT_OR, SMI, SMI, SMI, OVERWRITE_RIGHT);
2243   GENERATE(Token::BIT_XOR, INT32, INT32, INT32, NO_OVERWRITE);
2244   GENERATE(Token::BIT_XOR, INT32, INT32, INT32, OVERWRITE_LEFT);
2245   GENERATE(Token::BIT_XOR, INT32, INT32, INT32, OVERWRITE_RIGHT);
2246   GENERATE(Token::BIT_XOR, INT32, INT32, SMI, NO_OVERWRITE);
2247   GENERATE(Token::BIT_XOR, INT32, INT32, SMI, OVERWRITE_LEFT);
2248   GENERATE(Token::BIT_XOR, INT32, NUMBER, SMI, NO_OVERWRITE);
2249   GENERATE(Token::BIT_XOR, INT32, SMI, INT32, NO_OVERWRITE);
2250   GENERATE(Token::BIT_XOR, INT32, SMI, INT32, OVERWRITE_LEFT);
2251   GENERATE(Token::BIT_XOR, INT32, SMI, INT32, OVERWRITE_RIGHT);
2252   GENERATE(Token::BIT_XOR, NUMBER, INT32, INT32, NO_OVERWRITE);
2253   GENERATE(Token::BIT_XOR, NUMBER, SMI, INT32, NO_OVERWRITE);
2254   GENERATE(Token::BIT_XOR, NUMBER, SMI, SMI, NO_OVERWRITE);
2255   GENERATE(Token::BIT_XOR, SMI, INT32, INT32, NO_OVERWRITE);
2256   GENERATE(Token::BIT_XOR, SMI, INT32, INT32, OVERWRITE_LEFT);
2257   GENERATE(Token::BIT_XOR, SMI, INT32, SMI, OVERWRITE_LEFT);
2258   GENERATE(Token::BIT_XOR, SMI, SMI, SMI, NO_OVERWRITE);
2259   GENERATE(Token::BIT_XOR, SMI, SMI, SMI, OVERWRITE_LEFT);
2260   GENERATE(Token::BIT_XOR, SMI, SMI, SMI, OVERWRITE_RIGHT);
2261   GENERATE(Token::DIV, INT32, INT32, INT32, NO_OVERWRITE);
2262   GENERATE(Token::DIV, INT32, INT32, NUMBER, NO_OVERWRITE);
2263   GENERATE(Token::DIV, INT32, NUMBER, NUMBER, NO_OVERWRITE);
2264   GENERATE(Token::DIV, INT32, NUMBER, NUMBER, OVERWRITE_LEFT);
2265   GENERATE(Token::DIV, INT32, SMI, INT32, NO_OVERWRITE);
2266   GENERATE(Token::DIV, INT32, SMI, NUMBER, NO_OVERWRITE);
2267   GENERATE(Token::DIV, NUMBER, INT32, NUMBER, NO_OVERWRITE);
2268   GENERATE(Token::DIV, NUMBER, INT32, NUMBER, OVERWRITE_LEFT);
2269   GENERATE(Token::DIV, NUMBER, NUMBER, NUMBER, NO_OVERWRITE);
2270   GENERATE(Token::DIV, NUMBER, NUMBER, NUMBER, OVERWRITE_LEFT);
2271   GENERATE(Token::DIV, NUMBER, NUMBER, NUMBER, OVERWRITE_RIGHT);
2272   GENERATE(Token::DIV, NUMBER, SMI, NUMBER, NO_OVERWRITE);
2273   GENERATE(Token::DIV, NUMBER, SMI, NUMBER, OVERWRITE_LEFT);
2274   GENERATE(Token::DIV, SMI, INT32, INT32, NO_OVERWRITE);
2275   GENERATE(Token::DIV, SMI, INT32, NUMBER, NO_OVERWRITE);
2276   GENERATE(Token::DIV, SMI, INT32, NUMBER, OVERWRITE_LEFT);
2277   GENERATE(Token::DIV, SMI, NUMBER, NUMBER, NO_OVERWRITE);
2278   GENERATE(Token::DIV, SMI, NUMBER, NUMBER, OVERWRITE_LEFT);
2279   GENERATE(Token::DIV, SMI, NUMBER, NUMBER, OVERWRITE_RIGHT);
2280   GENERATE(Token::DIV, SMI, SMI, NUMBER, NO_OVERWRITE);
2281   GENERATE(Token::DIV, SMI, SMI, NUMBER, OVERWRITE_LEFT);
2282   GENERATE(Token::DIV, SMI, SMI, NUMBER, OVERWRITE_RIGHT);
2283   GENERATE(Token::DIV, SMI, SMI, SMI, NO_OVERWRITE);
2284   GENERATE(Token::DIV, SMI, SMI, SMI, OVERWRITE_LEFT);
2285   GENERATE(Token::DIV, SMI, SMI, SMI, OVERWRITE_RIGHT);
2286   GENERATE(Token::MOD, NUMBER, SMI, NUMBER, OVERWRITE_LEFT);
2287   GENERATE(Token::MOD, SMI, SMI, SMI, NO_OVERWRITE);
2288   GENERATE(Token::MOD, SMI, SMI, SMI, OVERWRITE_LEFT);
2289   GENERATE(Token::MUL, INT32, INT32, INT32, NO_OVERWRITE);
2290   GENERATE(Token::MUL, INT32, INT32, NUMBER, NO_OVERWRITE);
2291   GENERATE(Token::MUL, INT32, NUMBER, NUMBER, NO_OVERWRITE);
2292   GENERATE(Token::MUL, INT32, NUMBER, NUMBER, OVERWRITE_LEFT);
2293   GENERATE(Token::MUL, INT32, SMI, INT32, NO_OVERWRITE);
2294   GENERATE(Token::MUL, INT32, SMI, INT32, OVERWRITE_LEFT);
2295   GENERATE(Token::MUL, INT32, SMI, NUMBER, NO_OVERWRITE);
2296   GENERATE(Token::MUL, NUMBER, INT32, NUMBER, NO_OVERWRITE);
2297   GENERATE(Token::MUL, NUMBER, INT32, NUMBER, OVERWRITE_LEFT);
2298   GENERATE(Token::MUL, NUMBER, INT32, NUMBER, OVERWRITE_RIGHT);
2299   GENERATE(Token::MUL, NUMBER, NUMBER, NUMBER, NO_OVERWRITE);
2300   GENERATE(Token::MUL, NUMBER, NUMBER, NUMBER, OVERWRITE_LEFT);
2301   GENERATE(Token::MUL, NUMBER, SMI, NUMBER, NO_OVERWRITE);
2302   GENERATE(Token::MUL, NUMBER, SMI, NUMBER, OVERWRITE_LEFT);
2303   GENERATE(Token::MUL, NUMBER, SMI, NUMBER, OVERWRITE_RIGHT);
2304   GENERATE(Token::MUL, SMI, INT32, INT32, NO_OVERWRITE);
2305   GENERATE(Token::MUL, SMI, INT32, INT32, OVERWRITE_LEFT);
2306   GENERATE(Token::MUL, SMI, INT32, NUMBER, NO_OVERWRITE);
2307   GENERATE(Token::MUL, SMI, NUMBER, NUMBER, NO_OVERWRITE);
2308   GENERATE(Token::MUL, SMI, NUMBER, NUMBER, OVERWRITE_LEFT);
2309   GENERATE(Token::MUL, SMI, NUMBER, NUMBER, OVERWRITE_RIGHT);
2310   GENERATE(Token::MUL, SMI, SMI, INT32, NO_OVERWRITE);
2311   GENERATE(Token::MUL, SMI, SMI, NUMBER, NO_OVERWRITE);
2312   GENERATE(Token::MUL, SMI, SMI, NUMBER, OVERWRITE_LEFT);
2313   GENERATE(Token::MUL, SMI, SMI, SMI, NO_OVERWRITE);
2314   GENERATE(Token::MUL, SMI, SMI, SMI, OVERWRITE_LEFT);
2315   GENERATE(Token::MUL, SMI, SMI, SMI, OVERWRITE_RIGHT);
2316   GENERATE(Token::SAR, INT32, SMI, INT32, OVERWRITE_RIGHT);
2317   GENERATE(Token::SAR, INT32, SMI, SMI, NO_OVERWRITE);
2318   GENERATE(Token::SAR, INT32, SMI, SMI, OVERWRITE_RIGHT);
2319   GENERATE(Token::SAR, NUMBER, SMI, SMI, NO_OVERWRITE);
2320   GENERATE(Token::SAR, NUMBER, SMI, SMI, OVERWRITE_RIGHT);
2321   GENERATE(Token::SAR, SMI, SMI, SMI, OVERWRITE_LEFT);
2322   GENERATE(Token::SAR, SMI, SMI, SMI, OVERWRITE_RIGHT);
2323   GENERATE(Token::SHL, INT32, SMI, INT32, NO_OVERWRITE);
2324   GENERATE(Token::SHL, INT32, SMI, INT32, OVERWRITE_RIGHT);
2325   GENERATE(Token::SHL, INT32, SMI, SMI, NO_OVERWRITE);
2326   GENERATE(Token::SHL, INT32, SMI, SMI, OVERWRITE_RIGHT);
2327   GENERATE(Token::SHL, NUMBER, SMI, SMI, OVERWRITE_RIGHT);
2328   GENERATE(Token::SHL, SMI, SMI, INT32, NO_OVERWRITE);
2329   GENERATE(Token::SHL, SMI, SMI, INT32, OVERWRITE_LEFT);
2330   GENERATE(Token::SHL, SMI, SMI, INT32, OVERWRITE_RIGHT);
2331   GENERATE(Token::SHL, SMI, SMI, SMI, NO_OVERWRITE);
2332   GENERATE(Token::SHL, SMI, SMI, SMI, OVERWRITE_LEFT);
2333   GENERATE(Token::SHL, SMI, SMI, SMI, OVERWRITE_RIGHT);
2334   GENERATE(Token::SHR, INT32, SMI, SMI, NO_OVERWRITE);
2335   GENERATE(Token::SHR, INT32, SMI, SMI, OVERWRITE_LEFT);
2336   GENERATE(Token::SHR, INT32, SMI, SMI, OVERWRITE_RIGHT);
2337   GENERATE(Token::SHR, NUMBER, SMI, SMI, NO_OVERWRITE);
2338   GENERATE(Token::SHR, NUMBER, SMI, SMI, OVERWRITE_LEFT);
2339   GENERATE(Token::SHR, NUMBER, SMI, INT32, OVERWRITE_RIGHT);
2340   GENERATE(Token::SHR, SMI, SMI, SMI, NO_OVERWRITE);
2341   GENERATE(Token::SHR, SMI, SMI, SMI, OVERWRITE_LEFT);
2342   GENERATE(Token::SHR, SMI, SMI, SMI, OVERWRITE_RIGHT);
2343   GENERATE(Token::SUB, INT32, INT32, INT32, NO_OVERWRITE);
2344   GENERATE(Token::SUB, INT32, INT32, INT32, OVERWRITE_LEFT);
2345   GENERATE(Token::SUB, INT32, NUMBER, NUMBER, NO_OVERWRITE);
2346   GENERATE(Token::SUB, INT32, NUMBER, NUMBER, OVERWRITE_RIGHT);
2347   GENERATE(Token::SUB, INT32, SMI, INT32, OVERWRITE_LEFT);
2348   GENERATE(Token::SUB, INT32, SMI, INT32, OVERWRITE_RIGHT);
2349   GENERATE(Token::SUB, NUMBER, INT32, NUMBER, NO_OVERWRITE);
2350   GENERATE(Token::SUB, NUMBER, INT32, NUMBER, OVERWRITE_LEFT);
2351   GENERATE(Token::SUB, NUMBER, NUMBER, NUMBER, NO_OVERWRITE);
2352   GENERATE(Token::SUB, NUMBER, NUMBER, NUMBER, OVERWRITE_LEFT);
2353   GENERATE(Token::SUB, NUMBER, NUMBER, NUMBER, OVERWRITE_RIGHT);
2354   GENERATE(Token::SUB, NUMBER, SMI, NUMBER, NO_OVERWRITE);
2355   GENERATE(Token::SUB, NUMBER, SMI, NUMBER, OVERWRITE_LEFT);
2356   GENERATE(Token::SUB, NUMBER, SMI, NUMBER, OVERWRITE_RIGHT);
2357   GENERATE(Token::SUB, SMI, INT32, INT32, NO_OVERWRITE);
2358   GENERATE(Token::SUB, SMI, NUMBER, NUMBER, NO_OVERWRITE);
2359   GENERATE(Token::SUB, SMI, NUMBER, NUMBER, OVERWRITE_LEFT);
2360   GENERATE(Token::SUB, SMI, NUMBER, NUMBER, OVERWRITE_RIGHT);
2361   GENERATE(Token::SUB, SMI, SMI, SMI, NO_OVERWRITE);
2362   GENERATE(Token::SUB, SMI, SMI, SMI, OVERWRITE_LEFT);
2363   GENERATE(Token::SUB, SMI, SMI, SMI, OVERWRITE_RIGHT);
2364 #undef GENERATE
2365 #define GENERATE(op, left_kind, fixed_right_arg_value, result_kind, mode) \
2366   do {                                                                    \
2367     State state(isolate, op, mode);                                       \
2368     state.left_kind_ = left_kind;                                         \
2369     state.fixed_right_arg_.has_value = true;                              \
2370     state.fixed_right_arg_.value = fixed_right_arg_value;                 \
2371     state.right_kind_ = SMI;                                              \
2372     state.result_kind_ = result_kind;                                     \
2373     Generate(isolate, state);                                             \
2374   } while (false)
2375   GENERATE(Token::MOD, SMI, 2, SMI, NO_OVERWRITE);
2376   GENERATE(Token::MOD, SMI, 4, SMI, NO_OVERWRITE);
2377   GENERATE(Token::MOD, SMI, 4, SMI, OVERWRITE_LEFT);
2378   GENERATE(Token::MOD, SMI, 8, SMI, NO_OVERWRITE);
2379   GENERATE(Token::MOD, SMI, 16, SMI, OVERWRITE_LEFT);
2380   GENERATE(Token::MOD, SMI, 32, SMI, NO_OVERWRITE);
2381   GENERATE(Token::MOD, SMI, 2048, SMI, NO_OVERWRITE);
2382 #undef GENERATE
2383 }
2384
2385
2386 Type* BinaryOpIC::State::GetResultType(Zone* zone) const {
2387   Kind result_kind = result_kind_;
2388   if (HasSideEffects()) {
2389     result_kind = NONE;
2390   } else if (result_kind == GENERIC && op_ == Token::ADD) {
2391     return Type::Union(Type::Number(zone), Type::String(zone), zone);
2392   } else if (result_kind == NUMBER && op_ == Token::SHR) {
2393     return Type::Unsigned32(zone);
2394   }
2395   ASSERT_NE(GENERIC, result_kind);
2396   return KindToType(result_kind, zone);
2397 }
2398
2399
2400 void BinaryOpIC::State::Print(StringStream* stream) const {
2401   stream->Add("(%s", Token::Name(op_));
2402   if (mode_ == OVERWRITE_LEFT) stream->Add("_ReuseLeft");
2403   else if (mode_ == OVERWRITE_RIGHT) stream->Add("_ReuseRight");
2404   if (CouldCreateAllocationMementos()) stream->Add("_CreateAllocationMementos");
2405   stream->Add(":%s*", KindToString(left_kind_));
2406   if (fixed_right_arg_.has_value) {
2407     stream->Add("%d", fixed_right_arg_.value);
2408   } else {
2409     stream->Add("%s", KindToString(right_kind_));
2410   }
2411   stream->Add("->%s)", KindToString(result_kind_));
2412 }
2413
2414
2415 void BinaryOpIC::State::Update(Handle<Object> left,
2416                                Handle<Object> right,
2417                                Handle<Object> result) {
2418   ExtraICState old_extra_ic_state = GetExtraICState();
2419
2420   left_kind_ = UpdateKind(left, left_kind_);
2421   right_kind_ = UpdateKind(right, right_kind_);
2422
2423   int32_t fixed_right_arg_value = 0;
2424   bool has_fixed_right_arg =
2425       op_ == Token::MOD &&
2426       right->ToInt32(&fixed_right_arg_value) &&
2427       fixed_right_arg_value > 0 &&
2428       IsPowerOf2(fixed_right_arg_value) &&
2429       FixedRightArgValueField::is_valid(WhichPowerOf2(fixed_right_arg_value)) &&
2430       (left_kind_ == SMI || left_kind_ == INT32) &&
2431       (result_kind_ == NONE || !fixed_right_arg_.has_value);
2432   fixed_right_arg_ = Maybe<int32_t>(has_fixed_right_arg,
2433                                     fixed_right_arg_value);
2434
2435   result_kind_ = UpdateKind(result, result_kind_);
2436
2437   if (!Token::IsTruncatingBinaryOp(op_)) {
2438     Kind input_kind = Max(left_kind_, right_kind_);
2439     if (result_kind_ < input_kind && input_kind <= NUMBER) {
2440       result_kind_ = input_kind;
2441     }
2442   }
2443
2444   // We don't want to distinguish INT32 and NUMBER for string add (because
2445   // NumberToString can't make use of this anyway).
2446   if (left_kind_ == STRING && right_kind_ == INT32) {
2447     ASSERT_EQ(STRING, result_kind_);
2448     ASSERT_EQ(Token::ADD, op_);
2449     right_kind_ = NUMBER;
2450   } else if (right_kind_ == STRING && left_kind_ == INT32) {
2451     ASSERT_EQ(STRING, result_kind_);
2452     ASSERT_EQ(Token::ADD, op_);
2453     left_kind_ = NUMBER;
2454   }
2455
2456   // Reset overwrite mode unless we can actually make use of it, or may be able
2457   // to make use of it at some point in the future.
2458   if ((mode_ == OVERWRITE_LEFT && left_kind_ > NUMBER) ||
2459       (mode_ == OVERWRITE_RIGHT && right_kind_ > NUMBER) ||
2460       result_kind_ > NUMBER) {
2461     mode_ = NO_OVERWRITE;
2462   }
2463
2464   if (old_extra_ic_state == GetExtraICState()) {
2465     // Tagged operations can lead to non-truncating HChanges
2466     if (left->IsUndefined() || left->IsBoolean()) {
2467       left_kind_ = GENERIC;
2468     } else if (right->IsUndefined() || right->IsBoolean()) {
2469       right_kind_ = GENERIC;
2470     } else {
2471       // Since the X87 is too precise, we might bail out on numbers which
2472       // actually would truncate with 64 bit precision.
2473       ASSERT(!CpuFeatures::IsSupported(SSE2));
2474       ASSERT(result_kind_ < NUMBER);
2475       result_kind_ = NUMBER;
2476     }
2477   }
2478 }
2479
2480
2481 BinaryOpIC::State::Kind BinaryOpIC::State::UpdateKind(Handle<Object> object,
2482                                                       Kind kind) const {
2483   Kind new_kind = GENERIC;
2484   bool is_truncating = Token::IsTruncatingBinaryOp(op());
2485   if (object->IsBoolean() && is_truncating) {
2486     // Booleans will be automatically truncated by HChange.
2487     new_kind = INT32;
2488   } else if (object->IsUndefined()) {
2489     // Undefined will be automatically truncated by HChange.
2490     new_kind = is_truncating ? INT32 : NUMBER;
2491   } else if (object->IsSmi()) {
2492     new_kind = SMI;
2493   } else if (object->IsHeapNumber()) {
2494     double value = Handle<HeapNumber>::cast(object)->value();
2495     new_kind = IsInt32Double(value) ? INT32 : NUMBER;
2496   } else if (object->IsString() && op() == Token::ADD) {
2497     new_kind = STRING;
2498   }
2499   if (new_kind == INT32 && SmiValuesAre32Bits()) {
2500     new_kind = NUMBER;
2501   }
2502   if (kind != NONE &&
2503       ((new_kind <= NUMBER && kind > NUMBER) ||
2504        (new_kind > NUMBER && kind <= NUMBER))) {
2505     new_kind = GENERIC;
2506   }
2507   return Max(kind, new_kind);
2508 }
2509
2510
2511 // static
2512 const char* BinaryOpIC::State::KindToString(Kind kind) {
2513   switch (kind) {
2514     case NONE: return "None";
2515     case SMI: return "Smi";
2516     case INT32: return "Int32";
2517     case NUMBER: return "Number";
2518     case STRING: return "String";
2519     case GENERIC: return "Generic";
2520   }
2521   UNREACHABLE();
2522   return NULL;
2523 }
2524
2525
2526 // static
2527 Type* BinaryOpIC::State::KindToType(Kind kind, Zone* zone) {
2528   switch (kind) {
2529     case NONE: return Type::None(zone);
2530     case SMI: return Type::SignedSmall(zone);
2531     case INT32: return Type::Signed32(zone);
2532     case NUMBER: return Type::Number(zone);
2533     case STRING: return Type::String(zone);
2534     case GENERIC: return Type::Any(zone);
2535   }
2536   UNREACHABLE();
2537   return NULL;
2538 }
2539
2540
2541 MaybeHandle<Object> BinaryOpIC::Transition(
2542     Handle<AllocationSite> allocation_site,
2543     Handle<Object> left,
2544     Handle<Object> right) {
2545   State state(isolate(), target()->extra_ic_state());
2546
2547   // Compute the actual result using the builtin for the binary operation.
2548   Object* builtin = isolate()->js_builtins_object()->javascript_builtin(
2549       TokenToJSBuiltin(state.op()));
2550   Handle<JSFunction> function = handle(JSFunction::cast(builtin), isolate());
2551   Handle<Object> result;
2552   ASSIGN_RETURN_ON_EXCEPTION(
2553       isolate(),
2554       result,
2555       Execution::Call(isolate(), function, left, 1, &right),
2556       Object);
2557
2558   // Execution::Call can execute arbitrary JavaScript, hence potentially
2559   // update the state of this very IC, so we must update the stored state.
2560   UpdateTarget();
2561   // Compute the new state.
2562   State old_state(isolate(), target()->extra_ic_state());
2563   state.Update(left, right, result);
2564
2565   // Check if we have a string operation here.
2566   Handle<Code> target;
2567   if (!allocation_site.is_null() || state.ShouldCreateAllocationMementos()) {
2568     // Setup the allocation site on-demand.
2569     if (allocation_site.is_null()) {
2570       allocation_site = isolate()->factory()->NewAllocationSite();
2571     }
2572
2573     // Install the stub with an allocation site.
2574     BinaryOpICWithAllocationSiteStub stub(isolate(), state);
2575     target = stub.GetCodeCopyFromTemplate(allocation_site);
2576
2577     // Sanity check the trampoline stub.
2578     ASSERT_EQ(*allocation_site, target->FindFirstAllocationSite());
2579   } else {
2580     // Install the generic stub.
2581     BinaryOpICStub stub(isolate(), state);
2582     target = stub.GetCode();
2583
2584     // Sanity check the generic stub.
2585     ASSERT_EQ(NULL, target->FindFirstAllocationSite());
2586   }
2587   set_target(*target);
2588
2589   if (FLAG_trace_ic) {
2590     char buffer[150];
2591     NoAllocationStringAllocator allocator(
2592         buffer, static_cast<unsigned>(sizeof(buffer)));
2593     StringStream stream(&allocator);
2594     stream.Add("[BinaryOpIC");
2595     old_state.Print(&stream);
2596     stream.Add(" => ");
2597     state.Print(&stream);
2598     stream.Add(" @ %p <- ", static_cast<void*>(*target));
2599     stream.OutputToStdOut();
2600     JavaScriptFrame::PrintTop(isolate(), stdout, false, true);
2601     if (!allocation_site.is_null()) {
2602       PrintF(" using allocation site %p", static_cast<void*>(*allocation_site));
2603     }
2604     PrintF("]\n");
2605   }
2606
2607   // Patch the inlined smi code as necessary.
2608   if (!old_state.UseInlinedSmiCode() && state.UseInlinedSmiCode()) {
2609     PatchInlinedSmiCode(address(), ENABLE_INLINED_SMI_CHECK);
2610   } else if (old_state.UseInlinedSmiCode() && !state.UseInlinedSmiCode()) {
2611     PatchInlinedSmiCode(address(), DISABLE_INLINED_SMI_CHECK);
2612   }
2613
2614   return result;
2615 }
2616
2617
2618 RUNTIME_FUNCTION(BinaryOpIC_Miss) {
2619   HandleScope scope(isolate);
2620   ASSERT_EQ(2, args.length());
2621   Handle<Object> left = args.at<Object>(BinaryOpICStub::kLeft);
2622   Handle<Object> right = args.at<Object>(BinaryOpICStub::kRight);
2623   BinaryOpIC ic(isolate);
2624   Handle<Object> result;
2625   ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
2626       isolate,
2627       result,
2628       ic.Transition(Handle<AllocationSite>::null(), left, right));
2629   return *result;
2630 }
2631
2632
2633 RUNTIME_FUNCTION(BinaryOpIC_MissWithAllocationSite) {
2634   HandleScope scope(isolate);
2635   ASSERT_EQ(3, args.length());
2636   Handle<AllocationSite> allocation_site = args.at<AllocationSite>(
2637       BinaryOpWithAllocationSiteStub::kAllocationSite);
2638   Handle<Object> left = args.at<Object>(
2639       BinaryOpWithAllocationSiteStub::kLeft);
2640   Handle<Object> right = args.at<Object>(
2641       BinaryOpWithAllocationSiteStub::kRight);
2642   BinaryOpIC ic(isolate);
2643   Handle<Object> result;
2644   ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
2645       isolate,
2646       result,
2647       ic.Transition(allocation_site, left, right));
2648   return *result;
2649 }
2650
2651
2652 Code* CompareIC::GetRawUninitialized(Isolate* isolate, Token::Value op) {
2653   ICCompareStub stub(isolate, op, UNINITIALIZED, UNINITIALIZED, UNINITIALIZED);
2654   Code* code = NULL;
2655   CHECK(stub.FindCodeInCache(&code));
2656   return code;
2657 }
2658
2659
2660 Handle<Code> CompareIC::GetUninitialized(Isolate* isolate, Token::Value op) {
2661   ICCompareStub stub(isolate, op, UNINITIALIZED, UNINITIALIZED, UNINITIALIZED);
2662   return stub.GetCode();
2663 }
2664
2665
2666 const char* CompareIC::GetStateName(State state) {
2667   switch (state) {
2668     case UNINITIALIZED: return "UNINITIALIZED";
2669     case SMI: return "SMI";
2670     case NUMBER: return "NUMBER";
2671     case INTERNALIZED_STRING: return "INTERNALIZED_STRING";
2672     case STRING: return "STRING";
2673     case UNIQUE_NAME: return "UNIQUE_NAME";
2674     case OBJECT: return "OBJECT";
2675     case KNOWN_OBJECT: return "KNOWN_OBJECT";
2676     case GENERIC: return "GENERIC";
2677   }
2678   UNREACHABLE();
2679   return NULL;
2680 }
2681
2682
2683 Type* CompareIC::StateToType(
2684     Zone* zone,
2685     CompareIC::State state,
2686     Handle<Map> map) {
2687   switch (state) {
2688     case CompareIC::UNINITIALIZED: return Type::None(zone);
2689     case CompareIC::SMI: return Type::SignedSmall(zone);
2690     case CompareIC::NUMBER: return Type::Number(zone);
2691     case CompareIC::STRING: return Type::String(zone);
2692     case CompareIC::INTERNALIZED_STRING: return Type::InternalizedString(zone);
2693     case CompareIC::UNIQUE_NAME: return Type::UniqueName(zone);
2694     case CompareIC::OBJECT: return Type::Receiver(zone);
2695     case CompareIC::KNOWN_OBJECT:
2696       return map.is_null() ? Type::Receiver(zone) : Type::Class(map, zone);
2697     case CompareIC::GENERIC: return Type::Any(zone);
2698   }
2699   UNREACHABLE();
2700   return NULL;
2701 }
2702
2703
2704 void CompareIC::StubInfoToType(int stub_minor_key,
2705                                Type** left_type,
2706                                Type** right_type,
2707                                Type** overall_type,
2708                                Handle<Map> map,
2709                                Zone* zone) {
2710   State left_state, right_state, handler_state;
2711   ICCompareStub::DecodeMinorKey(stub_minor_key, &left_state, &right_state,
2712                                 &handler_state, NULL);
2713   *left_type = StateToType(zone, left_state);
2714   *right_type = StateToType(zone, right_state);
2715   *overall_type = StateToType(zone, handler_state, map);
2716 }
2717
2718
2719 CompareIC::State CompareIC::NewInputState(State old_state,
2720                                           Handle<Object> value) {
2721   switch (old_state) {
2722     case UNINITIALIZED:
2723       if (value->IsSmi()) return SMI;
2724       if (value->IsHeapNumber()) return NUMBER;
2725       if (value->IsInternalizedString()) return INTERNALIZED_STRING;
2726       if (value->IsString()) return STRING;
2727       if (value->IsSymbol()) return UNIQUE_NAME;
2728       if (value->IsJSObject()) return OBJECT;
2729       break;
2730     case SMI:
2731       if (value->IsSmi()) return SMI;
2732       if (value->IsHeapNumber()) return NUMBER;
2733       break;
2734     case NUMBER:
2735       if (value->IsNumber()) return NUMBER;
2736       break;
2737     case INTERNALIZED_STRING:
2738       if (value->IsInternalizedString()) return INTERNALIZED_STRING;
2739       if (value->IsString()) return STRING;
2740       if (value->IsSymbol()) return UNIQUE_NAME;
2741       break;
2742     case STRING:
2743       if (value->IsString()) return STRING;
2744       break;
2745     case UNIQUE_NAME:
2746       if (value->IsUniqueName()) return UNIQUE_NAME;
2747       break;
2748     case OBJECT:
2749       if (value->IsJSObject()) return OBJECT;
2750       break;
2751     case GENERIC:
2752       break;
2753     case KNOWN_OBJECT:
2754       UNREACHABLE();
2755       break;
2756   }
2757   return GENERIC;
2758 }
2759
2760
2761 CompareIC::State CompareIC::TargetState(State old_state,
2762                                         State old_left,
2763                                         State old_right,
2764                                         bool has_inlined_smi_code,
2765                                         Handle<Object> x,
2766                                         Handle<Object> y) {
2767   switch (old_state) {
2768     case UNINITIALIZED:
2769       if (x->IsSmi() && y->IsSmi()) return SMI;
2770       if (x->IsNumber() && y->IsNumber()) return NUMBER;
2771       if (Token::IsOrderedRelationalCompareOp(op_)) {
2772         // Ordered comparisons treat undefined as NaN, so the
2773         // NUMBER stub will do the right thing.
2774         if ((x->IsNumber() && y->IsUndefined()) ||
2775             (y->IsNumber() && x->IsUndefined())) {
2776           return NUMBER;
2777         }
2778       }
2779       if (x->IsInternalizedString() && y->IsInternalizedString()) {
2780         // We compare internalized strings as plain ones if we need to determine
2781         // the order in a non-equality compare.
2782         return Token::IsEqualityOp(op_) ? INTERNALIZED_STRING : STRING;
2783       }
2784       if (x->IsString() && y->IsString()) return STRING;
2785       if (!Token::IsEqualityOp(op_)) return GENERIC;
2786       if (x->IsUniqueName() && y->IsUniqueName()) return UNIQUE_NAME;
2787       if (x->IsJSObject() && y->IsJSObject()) {
2788         if (Handle<JSObject>::cast(x)->map() ==
2789             Handle<JSObject>::cast(y)->map()) {
2790           return KNOWN_OBJECT;
2791         } else {
2792           return OBJECT;
2793         }
2794       }
2795       return GENERIC;
2796     case SMI:
2797       return x->IsNumber() && y->IsNumber() ? NUMBER : GENERIC;
2798     case INTERNALIZED_STRING:
2799       ASSERT(Token::IsEqualityOp(op_));
2800       if (x->IsString() && y->IsString()) return STRING;
2801       if (x->IsUniqueName() && y->IsUniqueName()) return UNIQUE_NAME;
2802       return GENERIC;
2803     case NUMBER:
2804       // If the failure was due to one side changing from smi to heap number,
2805       // then keep the state (if other changed at the same time, we will get
2806       // a second miss and then go to generic).
2807       if (old_left == SMI && x->IsHeapNumber()) return NUMBER;
2808       if (old_right == SMI && y->IsHeapNumber()) return NUMBER;
2809       return GENERIC;
2810     case KNOWN_OBJECT:
2811       ASSERT(Token::IsEqualityOp(op_));
2812       if (x->IsJSObject() && y->IsJSObject()) return OBJECT;
2813       return GENERIC;
2814     case STRING:
2815     case UNIQUE_NAME:
2816     case OBJECT:
2817     case GENERIC:
2818       return GENERIC;
2819   }
2820   UNREACHABLE();
2821   return GENERIC;  // Make the compiler happy.
2822 }
2823
2824
2825 Code* CompareIC::UpdateCaches(Handle<Object> x, Handle<Object> y) {
2826   HandleScope scope(isolate());
2827   State previous_left, previous_right, previous_state;
2828   ICCompareStub::DecodeMinorKey(target()->stub_info(), &previous_left,
2829                                 &previous_right, &previous_state, NULL);
2830   State new_left = NewInputState(previous_left, x);
2831   State new_right = NewInputState(previous_right, y);
2832   State state = TargetState(previous_state, previous_left, previous_right,
2833                             HasInlinedSmiCode(address()), x, y);
2834   ICCompareStub stub(isolate(), op_, new_left, new_right, state);
2835   if (state == KNOWN_OBJECT) {
2836     stub.set_known_map(
2837         Handle<Map>(Handle<JSObject>::cast(x)->map(), isolate()));
2838   }
2839   Handle<Code> new_target = stub.GetCode();
2840   set_target(*new_target);
2841
2842   if (FLAG_trace_ic) {
2843     PrintF("[CompareIC in ");
2844     JavaScriptFrame::PrintTop(isolate(), stdout, false, true);
2845     PrintF(" ((%s+%s=%s)->(%s+%s=%s))#%s @ %p]\n",
2846            GetStateName(previous_left),
2847            GetStateName(previous_right),
2848            GetStateName(previous_state),
2849            GetStateName(new_left),
2850            GetStateName(new_right),
2851            GetStateName(state),
2852            Token::Name(op_),
2853            static_cast<void*>(*stub.GetCode()));
2854   }
2855
2856   // Activate inlined smi code.
2857   if (previous_state == UNINITIALIZED) {
2858     PatchInlinedSmiCode(address(), ENABLE_INLINED_SMI_CHECK);
2859   }
2860
2861   return *new_target;
2862 }
2863
2864
2865 // Used from ICCompareStub::GenerateMiss in code-stubs-<arch>.cc.
2866 RUNTIME_FUNCTION(CompareIC_Miss) {
2867   HandleScope scope(isolate);
2868   ASSERT(args.length() == 3);
2869   CompareIC ic(isolate, static_cast<Token::Value>(args.smi_at(2)));
2870   return ic.UpdateCaches(args.at<Object>(0), args.at<Object>(1));
2871 }
2872
2873
2874 void CompareNilIC::Clear(Address address,
2875                          Code* target,
2876                          ConstantPoolArray* constant_pool) {
2877   if (IsCleared(target)) return;
2878   ExtraICState state = target->extra_ic_state();
2879
2880   CompareNilICStub stub(target->GetIsolate(),
2881                         state,
2882                         HydrogenCodeStub::UNINITIALIZED);
2883   stub.ClearState();
2884
2885   Code* code = NULL;
2886   CHECK(stub.FindCodeInCache(&code));
2887
2888   SetTargetAtAddress(address, code, constant_pool);
2889 }
2890
2891
2892 Handle<Object> CompareNilIC::DoCompareNilSlow(Isolate* isolate,
2893                                               NilValue nil,
2894                                               Handle<Object> object) {
2895   if (object->IsNull() || object->IsUndefined()) {
2896     return handle(Smi::FromInt(true), isolate);
2897   }
2898   return handle(Smi::FromInt(object->IsUndetectableObject()), isolate);
2899 }
2900
2901
2902 Handle<Object> CompareNilIC::CompareNil(Handle<Object> object) {
2903   ExtraICState extra_ic_state = target()->extra_ic_state();
2904
2905   CompareNilICStub stub(isolate(), extra_ic_state);
2906
2907   // Extract the current supported types from the patched IC and calculate what
2908   // types must be supported as a result of the miss.
2909   bool already_monomorphic = stub.IsMonomorphic();
2910
2911   stub.UpdateStatus(object);
2912
2913   NilValue nil = stub.GetNilValue();
2914
2915   // Find or create the specialized stub to support the new set of types.
2916   Handle<Code> code;
2917   if (stub.IsMonomorphic()) {
2918     Handle<Map> monomorphic_map(already_monomorphic && FirstTargetMap() != NULL
2919                                 ? FirstTargetMap()
2920                                 : HeapObject::cast(*object)->map());
2921     code = isolate()->stub_cache()->ComputeCompareNil(monomorphic_map, stub);
2922   } else {
2923     code = stub.GetCode();
2924   }
2925   set_target(*code);
2926   return DoCompareNilSlow(isolate(), nil, object);
2927 }
2928
2929
2930 RUNTIME_FUNCTION(CompareNilIC_Miss) {
2931   HandleScope scope(isolate);
2932   Handle<Object> object = args.at<Object>(0);
2933   CompareNilIC ic(isolate);
2934   return *ic.CompareNil(object);
2935 }
2936
2937
2938 RUNTIME_FUNCTION(Unreachable) {
2939   UNREACHABLE();
2940   CHECK(false);
2941   return isolate->heap()->undefined_value();
2942 }
2943
2944
2945 Builtins::JavaScript BinaryOpIC::TokenToJSBuiltin(Token::Value op) {
2946   switch (op) {
2947     default:
2948       UNREACHABLE();
2949     case Token::ADD:
2950       return Builtins::ADD;
2951       break;
2952     case Token::SUB:
2953       return Builtins::SUB;
2954       break;
2955     case Token::MUL:
2956       return Builtins::MUL;
2957       break;
2958     case Token::DIV:
2959       return Builtins::DIV;
2960       break;
2961     case Token::MOD:
2962       return Builtins::MOD;
2963       break;
2964     case Token::BIT_OR:
2965       return Builtins::BIT_OR;
2966       break;
2967     case Token::BIT_AND:
2968       return Builtins::BIT_AND;
2969       break;
2970     case Token::BIT_XOR:
2971       return Builtins::BIT_XOR;
2972       break;
2973     case Token::SAR:
2974       return Builtins::SAR;
2975       break;
2976     case Token::SHR:
2977       return Builtins::SHR;
2978       break;
2979     case Token::SHL:
2980       return Builtins::SHL;
2981       break;
2982   }
2983 }
2984
2985
2986 Handle<Object> ToBooleanIC::ToBoolean(Handle<Object> object) {
2987   ToBooleanStub stub(isolate(), target()->extra_ic_state());
2988   bool to_boolean_value = stub.UpdateStatus(object);
2989   Handle<Code> code = stub.GetCode();
2990   set_target(*code);
2991   return handle(Smi::FromInt(to_boolean_value ? 1 : 0), isolate());
2992 }
2993
2994
2995 RUNTIME_FUNCTION(ToBooleanIC_Miss) {
2996   ASSERT(args.length() == 1);
2997   HandleScope scope(isolate);
2998   Handle<Object> object = args.at<Object>(0);
2999   ToBooleanIC ic(isolate);
3000   return *ic.ToBoolean(object);
3001 }
3002
3003
3004 static const Address IC_utilities[] = {
3005 #define ADDR(name) FUNCTION_ADDR(name),
3006     IC_UTIL_LIST(ADDR)
3007     NULL
3008 #undef ADDR
3009 };
3010
3011
3012 Address IC::AddressFromUtilityId(IC::UtilityId id) {
3013   return IC_utilities[id];
3014 }
3015
3016
3017 } }  // namespace v8::internal