• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 "src/v8.h"
6 
7 #include "src/accessors.h"
8 #include "src/api.h"
9 #include "src/arguments.h"
10 #include "src/codegen.h"
11 #include "src/conversions.h"
12 #include "src/execution.h"
13 #include "src/ic-inl.h"
14 #include "src/runtime.h"
15 #include "src/stub-cache.h"
16 
17 namespace v8 {
18 namespace internal {
19 
20 #ifdef DEBUG
TransitionMarkFromState(IC::State state)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 
GetTransitionMarkModifier(KeyedAccessStoreMode mode)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 
TraceIC(const char * type,Handle<Object> name)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 
IC(FrameDepth depth,Isolate * isolate)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 
GetSharedFunctionInfo() const149 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 
GetCode() const163 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 
GetOriginalCode() const171 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 
HasInterceptorGetter(JSObject * object)181 static bool HasInterceptorGetter(JSObject* object) {
182   return !object->GetNamedInterceptor()->getter()->IsUndefined();
183 }
184 
185 
HasInterceptorSetter(JSObject * object)186 static bool HasInterceptorSetter(JSObject* object) {
187   return !object->GetNamedInterceptor()->setter()->IsUndefined();
188 }
189 
190 
LookupForRead(Handle<Object> object,Handle<String> name,LookupResult * lookup)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->LookupOwnRealNamedProperty(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 
TryRemoveInvalidPrototypeDependentStub(Handle<Object> receiver,Handle<String> name)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->LookupOwnRealNamedProperty(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 
TryRemoveInvalidHandlers(Handle<Map> map,Handle<String> name)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 
IsNameCompatibleWithMonomorphicPrototypeFailure(Handle<Object> name)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 
UpdateState(Handle<Object> receiver,Handle<Object> name)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 
TypeError(const char * type,Handle<Object> object,Handle<Object> key)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 
ReferenceError(const char * type,Handle<String> name)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 
ComputeTypeInfoCountDelta(IC::State old_state,IC::State new_state)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 
PostPatching(Address address,Code * target,Code * old_target)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 
RegisterWeakMapDependency(Handle<Code> stub)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 
InvalidateMaps(Code * stub)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 
Clear(Isolate * isolate,Address address,ConstantPoolArray * constant_pool)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 
Clear(Isolate * isolate,Address address,Code * target,ConstantPoolArray * constant_pool)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 
Clear(Isolate * isolate,Address address,Code * target,ConstantPoolArray * constant_pool)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 }
505 
506 
Clear(Isolate * isolate,Address address,Code * target,ConstantPoolArray * constant_pool)507 void LoadIC::Clear(Isolate* isolate,
508                    Address address,
509                    Code* target,
510                    ConstantPoolArray* constant_pool) {
511   if (IsCleared(target)) return;
512   Code* code = target->GetIsolate()->stub_cache()->FindPreMonomorphicIC(
513       Code::LOAD_IC, target->extra_ic_state());
514   SetTargetAtAddress(address, code, constant_pool);
515 }
516 
517 
Clear(Isolate * isolate,Address address,Code * target,ConstantPoolArray * constant_pool)518 void StoreIC::Clear(Isolate* isolate,
519                     Address address,
520                     Code* target,
521                     ConstantPoolArray* constant_pool) {
522   if (IsCleared(target)) return;
523   Code* code = target->GetIsolate()->stub_cache()->FindPreMonomorphicIC(
524       Code::STORE_IC, target->extra_ic_state());
525   SetTargetAtAddress(address, code, constant_pool);
526 }
527 
528 
Clear(Isolate * isolate,Address address,Code * target,ConstantPoolArray * constant_pool)529 void KeyedStoreIC::Clear(Isolate* isolate,
530                          Address address,
531                          Code* target,
532                          ConstantPoolArray* constant_pool) {
533   if (IsCleared(target)) return;
534   SetTargetAtAddress(address,
535       *pre_monomorphic_stub(
536           isolate, StoreIC::GetStrictMode(target->extra_ic_state())),
537       constant_pool);
538 }
539 
540 
Clear(Isolate * isolate,Address address,Code * target,ConstantPoolArray * constant_pool)541 void CompareIC::Clear(Isolate* isolate,
542                       Address address,
543                       Code* target,
544                       ConstantPoolArray* constant_pool) {
545   ASSERT(target->major_key() == CodeStub::CompareIC);
546   CompareIC::State handler_state;
547   Token::Value op;
548   ICCompareStub::DecodeMinorKey(target->stub_info(), NULL, NULL,
549                                 &handler_state, &op);
550   // Only clear CompareICs that can retain objects.
551   if (handler_state != KNOWN_OBJECT) return;
552   SetTargetAtAddress(address, GetRawUninitialized(isolate, op), constant_pool);
553   PatchInlinedSmiCode(address, DISABLE_INLINED_SMI_CHECK);
554 }
555 
556 
megamorphic_stub()557 Handle<Code> KeyedLoadIC::megamorphic_stub() {
558   if (FLAG_compiled_keyed_generic_loads) {
559     return KeyedLoadGenericElementStub(isolate()).GetCode();
560   } else {
561     return isolate()->builtins()->KeyedLoadIC_Generic();
562   }
563 }
564 
generic_stub() const565 Handle<Code> KeyedLoadIC::generic_stub() const {
566   if (FLAG_compiled_keyed_generic_loads) {
567     return KeyedLoadGenericElementStub(isolate()).GetCode();
568   } else {
569     return isolate()->builtins()->KeyedLoadIC_Generic();
570   }
571 }
572 
573 
MigrateDeprecated(Handle<Object> object)574 static bool MigrateDeprecated(Handle<Object> object) {
575   if (!object->IsJSObject()) return false;
576   Handle<JSObject> receiver = Handle<JSObject>::cast(object);
577   if (!receiver->map()->is_deprecated()) return false;
578   JSObject::MigrateInstance(Handle<JSObject>::cast(object));
579   return true;
580 }
581 
582 
Load(Handle<Object> object,Handle<String> name)583 MaybeHandle<Object> LoadIC::Load(Handle<Object> object, Handle<String> name) {
584   // If the object is undefined or null it's illegal to try to get any
585   // of its properties; throw a TypeError in that case.
586   if (object->IsUndefined() || object->IsNull()) {
587     return TypeError("non_object_property_load", object, name);
588   }
589 
590   if (FLAG_use_ic) {
591     // Use specialized code for getting prototype of functions.
592     if (object->IsJSFunction() &&
593         String::Equals(isolate()->factory()->prototype_string(), name) &&
594         Handle<JSFunction>::cast(object)->should_have_prototype()) {
595       Handle<Code> stub;
596       if (state() == UNINITIALIZED) {
597         stub = pre_monomorphic_stub();
598       } else if (state() == PREMONOMORPHIC) {
599         FunctionPrototypeStub function_prototype_stub(isolate(), kind());
600         stub = function_prototype_stub.GetCode();
601       } else if (state() != MEGAMORPHIC) {
602         ASSERT(state() != GENERIC);
603         stub = megamorphic_stub();
604       }
605       if (!stub.is_null()) {
606         set_target(*stub);
607         if (FLAG_trace_ic) PrintF("[LoadIC : +#prototype /function]\n");
608       }
609       return Accessors::FunctionGetPrototype(Handle<JSFunction>::cast(object));
610     }
611   }
612 
613   // Check if the name is trivially convertible to an index and get
614   // the element or char if so.
615   uint32_t index;
616   if (kind() == Code::KEYED_LOAD_IC && name->AsArrayIndex(&index)) {
617     // Rewrite to the generic keyed load stub.
618     if (FLAG_use_ic) set_target(*generic_stub());
619     Handle<Object> result;
620     ASSIGN_RETURN_ON_EXCEPTION(
621         isolate(),
622         result,
623         Runtime::GetElementOrCharAt(isolate(), object, index),
624         Object);
625     return result;
626   }
627 
628   bool use_ic = MigrateDeprecated(object) ? false : FLAG_use_ic;
629 
630   // Named lookup in the object.
631   LookupResult lookup(isolate());
632   LookupForRead(object, name, &lookup);
633 
634   // If we did not find a property, check if we need to throw an exception.
635   if (!lookup.IsFound()) {
636     if (IsUndeclaredGlobal(object)) {
637       return ReferenceError("not_defined", name);
638     }
639     LOG(isolate(), SuspectReadEvent(*name, *object));
640   }
641 
642   // Update inline cache and stub cache.
643   if (use_ic) UpdateCaches(&lookup, object, name);
644 
645   // Get the property.
646   LookupIterator it(object, name);
647   Handle<Object> result;
648   ASSIGN_RETURN_ON_EXCEPTION(
649       isolate(), result, Object::GetProperty(&it), Object);
650   // If the property is not present, check if we need to throw an exception.
651   if ((lookup.IsInterceptor() || lookup.IsHandler()) &&
652       !it.IsFound() && IsUndeclaredGlobal(object)) {
653     return ReferenceError("not_defined", name);
654   }
655 
656   return result;
657 }
658 
659 
AddOneReceiverMapIfMissing(MapHandleList * receiver_maps,Handle<Map> new_receiver_map)660 static bool AddOneReceiverMapIfMissing(MapHandleList* receiver_maps,
661                                        Handle<Map> new_receiver_map) {
662   ASSERT(!new_receiver_map.is_null());
663   for (int current = 0; current < receiver_maps->length(); ++current) {
664     if (!receiver_maps->at(current).is_null() &&
665         receiver_maps->at(current).is_identical_to(new_receiver_map)) {
666       return false;
667     }
668   }
669   receiver_maps->Add(new_receiver_map);
670   return true;
671 }
672 
673 
UpdatePolymorphicIC(Handle<HeapType> type,Handle<String> name,Handle<Code> code)674 bool IC::UpdatePolymorphicIC(Handle<HeapType> type,
675                              Handle<String> name,
676                              Handle<Code> code) {
677   if (!code->is_handler()) return false;
678   TypeHandleList types;
679   CodeHandleList handlers;
680 
681   TargetTypes(&types);
682   int number_of_types = types.length();
683   int deprecated_types = 0;
684   int handler_to_overwrite = -1;
685 
686   for (int i = 0; i < number_of_types; i++) {
687     Handle<HeapType> current_type = types.at(i);
688     if (current_type->IsClass() &&
689         current_type->AsClass()->Map()->is_deprecated()) {
690       // Filter out deprecated maps to ensure their instances get migrated.
691       ++deprecated_types;
692     } else if (type->NowIs(current_type)) {
693       // If the receiver type is already in the polymorphic IC, this indicates
694       // there was a prototoype chain failure. In that case, just overwrite the
695       // handler.
696       handler_to_overwrite = i;
697     } else if (handler_to_overwrite == -1 &&
698                current_type->IsClass() &&
699                type->IsClass() &&
700                IsTransitionOfMonomorphicTarget(*current_type->AsClass()->Map(),
701                                                *type->AsClass()->Map())) {
702       handler_to_overwrite = i;
703     }
704   }
705 
706   int number_of_valid_types =
707     number_of_types - deprecated_types - (handler_to_overwrite != -1);
708 
709   if (number_of_valid_types >= 4) return false;
710   if (number_of_types == 0) return false;
711   if (!target()->FindHandlers(&handlers, types.length())) return false;
712 
713   number_of_valid_types++;
714   if (handler_to_overwrite >= 0) {
715     handlers.Set(handler_to_overwrite, code);
716     if (!type->NowIs(types.at(handler_to_overwrite))) {
717       types.Set(handler_to_overwrite, type);
718     }
719   } else {
720     types.Add(type);
721     handlers.Add(code);
722   }
723 
724   Handle<Code> ic = isolate()->stub_cache()->ComputePolymorphicIC(
725       kind(), &types, &handlers, number_of_valid_types, name, extra_ic_state());
726   set_target(*ic);
727   return true;
728 }
729 
730 
CurrentTypeOf(Handle<Object> object,Isolate * isolate)731 Handle<HeapType> IC::CurrentTypeOf(Handle<Object> object, Isolate* isolate) {
732   return object->IsJSGlobalObject()
733       ? HeapType::Constant(Handle<JSGlobalObject>::cast(object), isolate)
734       : HeapType::NowOf(object, isolate);
735 }
736 
737 
TypeToMap(HeapType * type,Isolate * isolate)738 Handle<Map> IC::TypeToMap(HeapType* type, Isolate* isolate) {
739   if (type->Is(HeapType::Number()))
740     return isolate->factory()->heap_number_map();
741   if (type->Is(HeapType::Boolean())) return isolate->factory()->boolean_map();
742   if (type->IsConstant()) {
743     return handle(
744         Handle<JSGlobalObject>::cast(type->AsConstant()->Value())->map());
745   }
746   ASSERT(type->IsClass());
747   return type->AsClass()->Map();
748 }
749 
750 
751 template <class T>
MapToType(Handle<Map> map,typename T::Region * region)752 typename T::TypeHandle IC::MapToType(Handle<Map> map,
753                                      typename T::Region* region) {
754   if (map->instance_type() == HEAP_NUMBER_TYPE) {
755     return T::Number(region);
756   } else if (map->instance_type() == ODDBALL_TYPE) {
757     // The only oddballs that can be recorded in ICs are booleans.
758     return T::Boolean(region);
759   } else {
760     return T::Class(map, region);
761   }
762 }
763 
764 
765 template
766 Type* IC::MapToType<Type>(Handle<Map> map, Zone* zone);
767 
768 
769 template
770 Handle<HeapType> IC::MapToType<HeapType>(Handle<Map> map, Isolate* region);
771 
772 
UpdateMonomorphicIC(Handle<HeapType> type,Handle<Code> handler,Handle<String> name)773 void IC::UpdateMonomorphicIC(Handle<HeapType> type,
774                              Handle<Code> handler,
775                              Handle<String> name) {
776   if (!handler->is_handler()) return set_target(*handler);
777   Handle<Code> ic = isolate()->stub_cache()->ComputeMonomorphicIC(
778       kind(), name, type, handler, extra_ic_state());
779   set_target(*ic);
780 }
781 
782 
CopyICToMegamorphicCache(Handle<String> name)783 void IC::CopyICToMegamorphicCache(Handle<String> name) {
784   TypeHandleList types;
785   CodeHandleList handlers;
786   TargetTypes(&types);
787   if (!target()->FindHandlers(&handlers, types.length())) return;
788   for (int i = 0; i < types.length(); i++) {
789     UpdateMegamorphicCache(*types.at(i), *name, *handlers.at(i));
790   }
791 }
792 
793 
IsTransitionOfMonomorphicTarget(Map * source_map,Map * target_map)794 bool IC::IsTransitionOfMonomorphicTarget(Map* source_map, Map* target_map) {
795   if (source_map == NULL) return true;
796   if (target_map == NULL) return false;
797   ElementsKind target_elements_kind = target_map->elements_kind();
798   bool more_general_transition =
799       IsMoreGeneralElementsKindTransition(
800         source_map->elements_kind(), target_elements_kind);
801   Map* transitioned_map = more_general_transition
802       ? source_map->LookupElementsTransitionMap(target_elements_kind)
803       : NULL;
804 
805   return transitioned_map == target_map;
806 }
807 
808 
PatchCache(Handle<HeapType> type,Handle<String> name,Handle<Code> code)809 void IC::PatchCache(Handle<HeapType> type,
810                     Handle<String> name,
811                     Handle<Code> code) {
812   switch (state()) {
813     case UNINITIALIZED:
814     case PREMONOMORPHIC:
815     case MONOMORPHIC_PROTOTYPE_FAILURE:
816       UpdateMonomorphicIC(type, code, name);
817       break;
818     case MONOMORPHIC:  // Fall through.
819     case POLYMORPHIC:
820       if (!target()->is_keyed_stub()) {
821         if (UpdatePolymorphicIC(type, name, code)) break;
822         CopyICToMegamorphicCache(name);
823       }
824       set_target(*megamorphic_stub());
825       // Fall through.
826     case MEGAMORPHIC:
827       UpdateMegamorphicCache(*type, *name, *code);
828       break;
829     case DEBUG_STUB:
830       break;
831     case GENERIC:
832       UNREACHABLE();
833       break;
834   }
835 }
836 
837 
initialize_stub(Isolate * isolate,ExtraICState extra_state)838 Handle<Code> LoadIC::initialize_stub(Isolate* isolate,
839                                      ExtraICState extra_state) {
840   return isolate->stub_cache()->ComputeLoad(UNINITIALIZED, extra_state);
841 }
842 
843 
pre_monomorphic_stub(Isolate * isolate,ExtraICState extra_state)844 Handle<Code> LoadIC::pre_monomorphic_stub(Isolate* isolate,
845                                           ExtraICState extra_state) {
846   return isolate->stub_cache()->ComputeLoad(PREMONOMORPHIC, extra_state);
847 }
848 
849 
megamorphic_stub()850 Handle<Code> LoadIC::megamorphic_stub() {
851   return isolate()->stub_cache()->ComputeLoad(MEGAMORPHIC, extra_ic_state());
852 }
853 
854 
SimpleFieldLoad(FieldIndex index)855 Handle<Code> LoadIC::SimpleFieldLoad(FieldIndex index) {
856   if (kind() == Code::LOAD_IC) {
857     LoadFieldStub stub(isolate(), index);
858     return stub.GetCode();
859   } else {
860     KeyedLoadFieldStub stub(isolate(), index);
861     return stub.GetCode();
862   }
863 }
864 
865 
UpdateCaches(LookupResult * lookup,Handle<Object> object,Handle<String> name)866 void LoadIC::UpdateCaches(LookupResult* lookup,
867                           Handle<Object> object,
868                           Handle<String> name) {
869   if (state() == UNINITIALIZED) {
870     // This is the first time we execute this inline cache.
871     // Set the target to the pre monomorphic stub to delay
872     // setting the monomorphic state.
873     set_target(*pre_monomorphic_stub());
874     TRACE_IC("LoadIC", name);
875     return;
876   }
877 
878   Handle<HeapType> type = CurrentTypeOf(object, isolate());
879   Handle<Code> code;
880   if (!lookup->IsCacheable()) {
881     // Bail out if the result is not cacheable.
882     code = slow_stub();
883   } else if (!lookup->IsProperty()) {
884     if (kind() == Code::LOAD_IC) {
885       code = isolate()->stub_cache()->ComputeLoadNonexistent(name, type);
886     } else {
887       code = slow_stub();
888     }
889   } else {
890     code = ComputeHandler(lookup, object, name);
891   }
892 
893   PatchCache(type, name, code);
894   TRACE_IC("LoadIC", name);
895 }
896 
897 
UpdateMegamorphicCache(HeapType * type,Name * name,Code * code)898 void IC::UpdateMegamorphicCache(HeapType* type, Name* name, Code* code) {
899   // Cache code holding map should be consistent with
900   // GenerateMonomorphicCacheProbe.
901   Map* map = *TypeToMap(type, isolate());
902   isolate()->stub_cache()->Set(name, map, code);
903 }
904 
905 
ComputeHandler(LookupResult * lookup,Handle<Object> object,Handle<String> name,Handle<Object> value)906 Handle<Code> IC::ComputeHandler(LookupResult* lookup,
907                                 Handle<Object> object,
908                                 Handle<String> name,
909                                 Handle<Object> value) {
910   InlineCacheHolderFlag cache_holder = GetCodeCacheForObject(*object);
911   Handle<HeapObject> stub_holder(GetCodeCacheHolder(
912       isolate(), *object, cache_holder));
913 
914   Handle<Code> code = isolate()->stub_cache()->FindHandler(
915       name, handle(stub_holder->map()), kind(), cache_holder,
916       lookup->holder()->HasFastProperties() ? Code::FAST : Code::NORMAL);
917   if (!code.is_null()) {
918     return code;
919   }
920 
921   code = CompileHandler(lookup, object, name, value, cache_holder);
922   ASSERT(code->is_handler());
923 
924   if (code->type() != Code::NORMAL) {
925     HeapObject::UpdateMapCodeCache(stub_holder, name, code);
926   }
927 
928   return code;
929 }
930 
931 
CompileHandler(LookupResult * lookup,Handle<Object> object,Handle<String> name,Handle<Object> unused,InlineCacheHolderFlag cache_holder)932 Handle<Code> LoadIC::CompileHandler(LookupResult* lookup,
933                                     Handle<Object> object,
934                                     Handle<String> name,
935                                     Handle<Object> unused,
936                                     InlineCacheHolderFlag cache_holder) {
937   if (object->IsString() &&
938       String::Equals(isolate()->factory()->length_string(), name)) {
939     FieldIndex index = FieldIndex::ForInObjectOffset(String::kLengthOffset);
940     return SimpleFieldLoad(index);
941   }
942 
943   if (object->IsStringWrapper() &&
944       String::Equals(isolate()->factory()->length_string(), name)) {
945     if (kind() == Code::LOAD_IC) {
946       StringLengthStub string_length_stub(isolate());
947       return string_length_stub.GetCode();
948     } else {
949       KeyedStringLengthStub string_length_stub(isolate());
950       return string_length_stub.GetCode();
951     }
952   }
953 
954   Handle<HeapType> type = CurrentTypeOf(object, isolate());
955   Handle<JSObject> holder(lookup->holder());
956   LoadStubCompiler compiler(isolate(), kNoExtraICState, cache_holder, kind());
957 
958   switch (lookup->type()) {
959     case FIELD: {
960       FieldIndex field = lookup->GetFieldIndex();
961       if (object.is_identical_to(holder)) {
962         return SimpleFieldLoad(field);
963       }
964       return compiler.CompileLoadField(
965           type, holder, name, field, lookup->representation());
966     }
967     case CONSTANT: {
968       Handle<Object> constant(lookup->GetConstant(), isolate());
969       // TODO(2803): Don't compute a stub for cons strings because they cannot
970       // be embedded into code.
971       if (constant->IsConsString()) break;
972       return compiler.CompileLoadConstant(type, holder, name, constant);
973     }
974     case NORMAL:
975       if (kind() != Code::LOAD_IC) break;
976       if (holder->IsGlobalObject()) {
977         Handle<GlobalObject> global = Handle<GlobalObject>::cast(holder);
978         Handle<PropertyCell> cell(
979             global->GetPropertyCell(lookup), isolate());
980         Handle<Code> code = compiler.CompileLoadGlobal(
981             type, global, cell, name, lookup->IsDontDelete());
982         // TODO(verwaest): Move caching of these NORMAL stubs outside as well.
983         Handle<HeapObject> stub_holder(GetCodeCacheHolder(
984             isolate(), *object, cache_holder));
985         HeapObject::UpdateMapCodeCache(stub_holder, name, code);
986         return code;
987       }
988       // There is only one shared stub for loading normalized
989       // properties. It does not traverse the prototype chain, so the
990       // property must be found in the object for the stub to be
991       // applicable.
992       if (!object.is_identical_to(holder)) break;
993       return isolate()->builtins()->LoadIC_Normal();
994     case CALLBACKS: {
995       // Use simple field loads for some well-known callback properties.
996       if (object->IsJSObject()) {
997         Handle<JSObject> receiver = Handle<JSObject>::cast(object);
998         Handle<Map> map(receiver->map());
999         Handle<HeapType> type = IC::MapToType<HeapType>(
1000             handle(receiver->map()), isolate());
1001         int object_offset;
1002         if (Accessors::IsJSObjectFieldAccessor<HeapType>(
1003                 type, name, &object_offset)) {
1004           FieldIndex index = FieldIndex::ForInObjectOffset(
1005               object_offset, receiver->map());
1006           return SimpleFieldLoad(index);
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 
TryConvertKey(Handle<Object> key,Isolate * isolate)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 
LoadElementStub(Handle<JSObject> receiver)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 
Load(Handle<Object> object,Handle<Object> key)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     Code* generic = *generic_stub();
1175     if (*stub == generic) {
1176       TRACE_GENERIC_IC(isolate(), "KeyedLoadIC", "set generic");
1177     }
1178     set_target(*stub);
1179     TRACE_IC("LoadIC", key);
1180   }
1181 
1182   if (!load_handle.is_null()) return load_handle;
1183   Handle<Object> result;
1184   ASSIGN_RETURN_ON_EXCEPTION(
1185       isolate(),
1186       result,
1187       Runtime::GetObjectProperty(isolate(), object, key),
1188       Object);
1189   return result;
1190 }
1191 
1192 
LookupForWrite(Handle<JSObject> receiver,Handle<String> name,Handle<Object> value,LookupResult * lookup,IC * ic)1193 static bool LookupForWrite(Handle<JSObject> receiver,
1194                            Handle<String> name,
1195                            Handle<Object> value,
1196                            LookupResult* lookup,
1197                            IC* ic) {
1198   Handle<JSObject> holder = receiver;
1199   receiver->Lookup(name, lookup);
1200   if (lookup->IsFound()) {
1201     if (lookup->IsInterceptor() && !HasInterceptorSetter(lookup->holder())) {
1202       receiver->LookupOwnRealNamedProperty(name, lookup);
1203       if (!lookup->IsFound()) return false;
1204     }
1205 
1206     if (lookup->IsReadOnly() || !lookup->IsCacheable()) return false;
1207     if (lookup->holder() == *receiver) return lookup->CanHoldValue(value);
1208     if (lookup->IsPropertyCallbacks()) return true;
1209     // JSGlobalProxy either stores on the global object in the prototype, or
1210     // goes into the runtime if access checks are needed, so this is always
1211     // safe.
1212     if (receiver->IsJSGlobalProxy()) {
1213       return lookup->holder() == receiver->GetPrototype();
1214     }
1215     // Currently normal holders in the prototype chain are not supported. They
1216     // would require a runtime positive lookup and verification that the details
1217     // have not changed.
1218     if (lookup->IsInterceptor() || lookup->IsNormal()) return false;
1219     holder = Handle<JSObject>(lookup->holder(), lookup->isolate());
1220   }
1221 
1222   // While normally LookupTransition gets passed the receiver, in this case we
1223   // pass the holder of the property that we overwrite. This keeps the holder in
1224   // the LookupResult intact so we can later use it to generate a prototype
1225   // chain check. This avoids a double lookup, but requires us to pass in the
1226   // receiver when trying to fetch extra information from the transition.
1227   receiver->map()->LookupTransition(*holder, *name, lookup);
1228   if (!lookup->IsTransition() || lookup->IsReadOnly()) return false;
1229 
1230   // If the value that's being stored does not fit in the field that the
1231   // instance would transition to, create a new transition that fits the value.
1232   // This has to be done before generating the IC, since that IC will embed the
1233   // transition target.
1234   // Ensure the instance and its map were migrated before trying to update the
1235   // transition target.
1236   ASSERT(!receiver->map()->is_deprecated());
1237   if (!lookup->CanHoldValue(value)) {
1238     Handle<Map> target(lookup->GetTransitionTarget());
1239     Representation field_representation = value->OptimalRepresentation();
1240     Handle<HeapType> field_type = value->OptimalType(
1241         lookup->isolate(), field_representation);
1242     Map::GeneralizeRepresentation(
1243         target, target->LastAdded(),
1244         field_representation, field_type, FORCE_FIELD);
1245     // Lookup the transition again since the transition tree may have changed
1246     // entirely by the migration above.
1247     receiver->map()->LookupTransition(*holder, *name, lookup);
1248     if (!lookup->IsTransition()) return false;
1249     return ic->TryMarkMonomorphicPrototypeFailure(name);
1250   }
1251 
1252   return true;
1253 }
1254 
1255 
Store(Handle<Object> object,Handle<String> name,Handle<Object> value,JSReceiver::StoreFromKeyed store_mode)1256 MaybeHandle<Object> StoreIC::Store(Handle<Object> object,
1257                                    Handle<String> name,
1258                                    Handle<Object> value,
1259                                    JSReceiver::StoreFromKeyed store_mode) {
1260   if (MigrateDeprecated(object) || object->IsJSProxy()) {
1261     Handle<JSReceiver> receiver = Handle<JSReceiver>::cast(object);
1262     Handle<Object> result;
1263     ASSIGN_RETURN_ON_EXCEPTION(
1264         isolate(),
1265         result,
1266         JSReceiver::SetProperty(receiver, name, value, NONE, strict_mode()),
1267         Object);
1268     return result;
1269   }
1270 
1271   // If the object is undefined or null it's illegal to try to set any
1272   // properties on it; throw a TypeError in that case.
1273   if (object->IsUndefined() || object->IsNull()) {
1274     return TypeError("non_object_property_store", object, name);
1275   }
1276 
1277   // The length property of string values is read-only. Throw in strict mode.
1278   if (strict_mode() == STRICT && object->IsString() &&
1279       String::Equals(isolate()->factory()->length_string(), name)) {
1280     return TypeError("strict_read_only_property", object, name);
1281   }
1282 
1283   // Ignore other stores where the receiver is not a JSObject.
1284   // TODO(1475): Must check prototype chains of object wrappers.
1285   if (!object->IsJSObject()) return value;
1286 
1287   Handle<JSObject> receiver = Handle<JSObject>::cast(object);
1288 
1289   // Check if the given name is an array index.
1290   uint32_t index;
1291   if (name->AsArrayIndex(&index)) {
1292     Handle<Object> result;
1293     ASSIGN_RETURN_ON_EXCEPTION(
1294         isolate(),
1295         result,
1296         JSObject::SetElement(receiver, index, value, NONE, strict_mode()),
1297         Object);
1298     return value;
1299   }
1300 
1301   // Observed objects are always modified through the runtime.
1302   if (receiver->map()->is_observed()) {
1303     Handle<Object> result;
1304     ASSIGN_RETURN_ON_EXCEPTION(
1305         isolate(),
1306         result,
1307         JSReceiver::SetProperty(
1308             receiver, name, value, NONE, strict_mode(), store_mode),
1309         Object);
1310     return result;
1311   }
1312 
1313   LookupResult lookup(isolate());
1314   bool can_store = LookupForWrite(receiver, name, value, &lookup, this);
1315   if (!can_store &&
1316       strict_mode() == STRICT &&
1317       !(lookup.IsProperty() && lookup.IsReadOnly()) &&
1318       object->IsGlobalObject()) {
1319     // Strict mode doesn't allow setting non-existent global property.
1320     return ReferenceError("not_defined", name);
1321   }
1322   if (FLAG_use_ic) {
1323     if (state() == UNINITIALIZED) {
1324       Handle<Code> stub = pre_monomorphic_stub();
1325       set_target(*stub);
1326       TRACE_IC("StoreIC", name);
1327     } else if (can_store) {
1328       UpdateCaches(&lookup, receiver, name, value);
1329     } else if (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 
Print(StringStream * stream) const1348 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 
initialize_stub(Isolate * isolate,int argc,CallType call_type)1356 Handle<Code> CallIC::initialize_stub(Isolate* isolate,
1357                                      int argc,
1358                                      CallType call_type) {
1359   CallICStub stub(isolate, State(argc, call_type));
1360   Handle<Code> code = stub.GetCode();
1361   return code;
1362 }
1363 
1364 
initialize_stub(Isolate * isolate,StrictMode strict_mode)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 
megamorphic_stub()1374 Handle<Code> StoreIC::megamorphic_stub() {
1375   return isolate()->stub_cache()->ComputeStore(MEGAMORPHIC, extra_ic_state());
1376 }
1377 
1378 
generic_stub() const1379 Handle<Code> StoreIC::generic_stub() const {
1380   return isolate()->stub_cache()->ComputeStore(GENERIC, extra_ic_state());
1381 }
1382 
1383 
pre_monomorphic_stub(Isolate * isolate,StrictMode strict_mode)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 
UpdateCaches(LookupResult * lookup,Handle<JSObject> receiver,Handle<String> name,Handle<Object> value)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 
CompileHandler(LookupResult * lookup,Handle<Object> object,Handle<String> name,Handle<Object> value,InlineCacheHolderFlag cache_holder)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 
StoreElementStub(Handle<JSObject> receiver,KeyedAccessStoreMode store_mode)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 
ComputeTransitionedMap(Handle<Map> map,KeyedAccessStoreMode store_mode)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 
IsOutOfBoundsAccess(Handle<JSObject> receiver,int index)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 
GetStoreMode(Handle<JSObject> receiver,Handle<Object> key,Handle<Object> value)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 
Store(Handle<Object> object,Handle<Object> key,Handle<Object> value)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 (store_handle.is_null()) {
1810     ASSIGN_RETURN_ON_EXCEPTION(
1811         isolate(),
1812         store_handle,
1813         Runtime::SetObjectProperty(
1814             isolate(), object, key, value, NONE, strict_mode()),
1815         Object);
1816   }
1817 
1818   if (!is_target_set()) {
1819     Code* generic = *generic_stub();
1820     if (*stub == generic) {
1821       TRACE_GENERIC_IC(isolate(), "KeyedStoreIC", "set generic");
1822     }
1823     ASSERT(!stub.is_null());
1824     set_target(*stub);
1825     TRACE_IC("StoreIC", key);
1826   }
1827 
1828   return store_handle;
1829 }
1830 
1831 
State(ExtraICState extra_ic_state)1832 CallIC::State::State(ExtraICState extra_ic_state)
1833     : argc_(ArgcBits::decode(extra_ic_state)),
1834       call_type_(CallTypeBits::decode(extra_ic_state)) {
1835 }
1836 
1837 
GetExtraICState() const1838 ExtraICState CallIC::State::GetExtraICState() const {
1839   ExtraICState extra_ic_state =
1840       ArgcBits::encode(argc_) |
1841       CallTypeBits::encode(call_type_);
1842   return extra_ic_state;
1843 }
1844 
1845 
DoCustomHandler(Handle<Object> receiver,Handle<Object> function,Handle<FixedArray> vector,Handle<Smi> slot,const State & state)1846 bool CallIC::DoCustomHandler(Handle<Object> receiver,
1847                              Handle<Object> function,
1848                              Handle<FixedArray> vector,
1849                              Handle<Smi> slot,
1850                              const State& state) {
1851   ASSERT(FLAG_use_ic && function->IsJSFunction());
1852 
1853   // Are we the array function?
1854   Handle<JSFunction> array_function = Handle<JSFunction>(
1855       isolate()->context()->native_context()->array_function(), isolate());
1856   if (array_function.is_identical_to(Handle<JSFunction>::cast(function))) {
1857     // Alter the slot.
1858     Object* feedback = vector->get(slot->value());
1859     if (!feedback->IsAllocationSite()) {
1860       Handle<AllocationSite> new_site =
1861           isolate()->factory()->NewAllocationSite();
1862       vector->set(slot->value(), *new_site);
1863     }
1864 
1865     CallIC_ArrayStub stub(isolate(), state);
1866     set_target(*stub.GetCode());
1867     Handle<String> name;
1868     if (array_function->shared()->name()->IsString()) {
1869       name = Handle<String>(String::cast(array_function->shared()->name()),
1870                             isolate());
1871     }
1872 
1873     TRACE_IC("CallIC (Array call)", name);
1874     return true;
1875   }
1876   return false;
1877 }
1878 
1879 
PatchMegamorphic(Handle<FixedArray> vector,Handle<Smi> slot)1880 void CallIC::PatchMegamorphic(Handle<FixedArray> vector,
1881                               Handle<Smi> slot) {
1882   State state(target()->extra_ic_state());
1883 
1884   // We are going generic.
1885   vector->set(slot->value(),
1886               *TypeFeedbackInfo::MegamorphicSentinel(isolate()),
1887               SKIP_WRITE_BARRIER);
1888 
1889   CallICStub stub(isolate(), state);
1890   Handle<Code> code = stub.GetCode();
1891   set_target(*code);
1892 
1893   TRACE_GENERIC_IC(isolate(), "CallIC", "megamorphic");
1894 }
1895 
1896 
HandleMiss(Handle<Object> receiver,Handle<Object> function,Handle<FixedArray> vector,Handle<Smi> slot)1897 void CallIC::HandleMiss(Handle<Object> receiver,
1898                         Handle<Object> function,
1899                         Handle<FixedArray> vector,
1900                         Handle<Smi> slot) {
1901   State state(target()->extra_ic_state());
1902   Object* feedback = vector->get(slot->value());
1903 
1904   // Hand-coded MISS handling is easier if CallIC slots don't contain smis.
1905   ASSERT(!feedback->IsSmi());
1906 
1907   if (feedback->IsJSFunction() || !function->IsJSFunction()) {
1908     // We are going generic.
1909     vector->set(slot->value(),
1910                 *TypeFeedbackInfo::MegamorphicSentinel(isolate()),
1911                 SKIP_WRITE_BARRIER);
1912 
1913     TRACE_GENERIC_IC(isolate(), "CallIC", "megamorphic");
1914   } else {
1915     // The feedback is either uninitialized or an allocation site.
1916     // It might be an allocation site because if we re-compile the full code
1917     // to add deoptimization support, we call with the default call-ic, and
1918     // merely need to patch the target to match the feedback.
1919     // TODO(mvstanton): the better approach is to dispense with patching
1920     // altogether, which is in progress.
1921     ASSERT(feedback == *TypeFeedbackInfo::UninitializedSentinel(isolate()) ||
1922            feedback->IsAllocationSite());
1923 
1924     // Do we want to install a custom handler?
1925     if (FLAG_use_ic &&
1926         DoCustomHandler(receiver, function, vector, slot, state)) {
1927       return;
1928     }
1929 
1930     Handle<JSFunction> js_function = Handle<JSFunction>::cast(function);
1931     Handle<Object> name(js_function->shared()->name(), isolate());
1932     TRACE_IC("CallIC", name);
1933     vector->set(slot->value(), *function);
1934   }
1935 }
1936 
1937 
1938 #undef TRACE_IC
1939 
1940 
1941 // ----------------------------------------------------------------------------
1942 // Static IC stub generators.
1943 //
1944 
1945 // Used from ic-<arch>.cc.
RUNTIME_FUNCTION(CallIC_Miss)1946 RUNTIME_FUNCTION(CallIC_Miss) {
1947   Logger::TimerEventScope timer(
1948       isolate, Logger::TimerEventScope::v8_ic_miss);
1949   HandleScope scope(isolate);
1950   ASSERT(args.length() == 4);
1951   CallIC ic(isolate);
1952   Handle<Object> receiver = args.at<Object>(0);
1953   Handle<Object> function = args.at<Object>(1);
1954   Handle<FixedArray> vector = args.at<FixedArray>(2);
1955   Handle<Smi> slot = args.at<Smi>(3);
1956   ic.HandleMiss(receiver, function, vector, slot);
1957   return *function;
1958 }
1959 
1960 
RUNTIME_FUNCTION(CallIC_Customization_Miss)1961 RUNTIME_FUNCTION(CallIC_Customization_Miss) {
1962   Logger::TimerEventScope timer(
1963       isolate, Logger::TimerEventScope::v8_ic_miss);
1964   HandleScope scope(isolate);
1965   ASSERT(args.length() == 4);
1966   // A miss on a custom call ic always results in going megamorphic.
1967   CallIC ic(isolate);
1968   Handle<Object> function = args.at<Object>(1);
1969   Handle<FixedArray> vector = args.at<FixedArray>(2);
1970   Handle<Smi> slot = args.at<Smi>(3);
1971   ic.PatchMegamorphic(vector, slot);
1972   return *function;
1973 }
1974 
1975 
1976 // Used from ic-<arch>.cc.
RUNTIME_FUNCTION(LoadIC_Miss)1977 RUNTIME_FUNCTION(LoadIC_Miss) {
1978   Logger::TimerEventScope timer(
1979       isolate, Logger::TimerEventScope::v8_ic_miss);
1980   HandleScope scope(isolate);
1981   ASSERT(args.length() == 2);
1982   LoadIC ic(IC::NO_EXTRA_FRAME, isolate);
1983   Handle<Object> receiver = args.at<Object>(0);
1984   Handle<String> key = args.at<String>(1);
1985   ic.UpdateState(receiver, key);
1986   Handle<Object> result;
1987   ASSIGN_RETURN_FAILURE_ON_EXCEPTION(isolate, result, ic.Load(receiver, key));
1988   return *result;
1989 }
1990 
1991 
1992 // Used from ic-<arch>.cc
RUNTIME_FUNCTION(KeyedLoadIC_Miss)1993 RUNTIME_FUNCTION(KeyedLoadIC_Miss) {
1994   Logger::TimerEventScope timer(
1995       isolate, Logger::TimerEventScope::v8_ic_miss);
1996   HandleScope scope(isolate);
1997   ASSERT(args.length() == 2);
1998   KeyedLoadIC ic(IC::NO_EXTRA_FRAME, isolate);
1999   Handle<Object> receiver = args.at<Object>(0);
2000   Handle<Object> key = args.at<Object>(1);
2001   ic.UpdateState(receiver, key);
2002   Handle<Object> result;
2003   ASSIGN_RETURN_FAILURE_ON_EXCEPTION(isolate, result, ic.Load(receiver, key));
2004   return *result;
2005 }
2006 
2007 
RUNTIME_FUNCTION(KeyedLoadIC_MissFromStubFailure)2008 RUNTIME_FUNCTION(KeyedLoadIC_MissFromStubFailure) {
2009   Logger::TimerEventScope timer(
2010       isolate, Logger::TimerEventScope::v8_ic_miss);
2011   HandleScope scope(isolate);
2012   ASSERT(args.length() == 2);
2013   KeyedLoadIC ic(IC::EXTRA_CALL_FRAME, isolate);
2014   Handle<Object> receiver = args.at<Object>(0);
2015   Handle<Object> key = args.at<Object>(1);
2016   ic.UpdateState(receiver, key);
2017   Handle<Object> result;
2018   ASSIGN_RETURN_FAILURE_ON_EXCEPTION(isolate, result, ic.Load(receiver, key));
2019   return *result;
2020 }
2021 
2022 
2023 // Used from ic-<arch>.cc.
RUNTIME_FUNCTION(StoreIC_Miss)2024 RUNTIME_FUNCTION(StoreIC_Miss) {
2025   Logger::TimerEventScope timer(
2026       isolate, Logger::TimerEventScope::v8_ic_miss);
2027   HandleScope scope(isolate);
2028   ASSERT(args.length() == 3);
2029   StoreIC ic(IC::NO_EXTRA_FRAME, isolate);
2030   Handle<Object> receiver = args.at<Object>(0);
2031   Handle<String> key = args.at<String>(1);
2032   ic.UpdateState(receiver, key);
2033   Handle<Object> result;
2034   ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
2035       isolate,
2036       result,
2037       ic.Store(receiver, key, args.at<Object>(2)));
2038   return *result;
2039 }
2040 
2041 
RUNTIME_FUNCTION(StoreIC_MissFromStubFailure)2042 RUNTIME_FUNCTION(StoreIC_MissFromStubFailure) {
2043   Logger::TimerEventScope timer(
2044       isolate, Logger::TimerEventScope::v8_ic_miss);
2045   HandleScope scope(isolate);
2046   ASSERT(args.length() == 3);
2047   StoreIC ic(IC::EXTRA_CALL_FRAME, isolate);
2048   Handle<Object> receiver = args.at<Object>(0);
2049   Handle<String> key = args.at<String>(1);
2050   ic.UpdateState(receiver, key);
2051   Handle<Object> result;
2052   ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
2053       isolate,
2054       result,
2055       ic.Store(receiver, key, args.at<Object>(2)));
2056   return *result;
2057 }
2058 
2059 
RUNTIME_FUNCTION(StoreIC_ArrayLength)2060 RUNTIME_FUNCTION(StoreIC_ArrayLength) {
2061   Logger::TimerEventScope timer(
2062       isolate, Logger::TimerEventScope::v8_ic_miss);
2063   HandleScope scope(isolate);
2064 
2065   ASSERT(args.length() == 2);
2066   Handle<JSArray> receiver = args.at<JSArray>(0);
2067   Handle<Object> len = args.at<Object>(1);
2068 
2069   // The generated code should filter out non-Smis before we get here.
2070   ASSERT(len->IsSmi());
2071 
2072 #ifdef DEBUG
2073   // The length property has to be a writable callback property.
2074   LookupResult debug_lookup(isolate);
2075   receiver->LookupOwn(isolate->factory()->length_string(), &debug_lookup);
2076   ASSERT(debug_lookup.IsPropertyCallbacks() && !debug_lookup.IsReadOnly());
2077 #endif
2078 
2079   RETURN_FAILURE_ON_EXCEPTION(
2080       isolate, JSArray::SetElementsLength(receiver, len));
2081   return *len;
2082 }
2083 
2084 
2085 // Extend storage is called in a store inline cache when
2086 // it is necessary to extend the properties array of a
2087 // JSObject.
RUNTIME_FUNCTION(SharedStoreIC_ExtendStorage)2088 RUNTIME_FUNCTION(SharedStoreIC_ExtendStorage) {
2089   Logger::TimerEventScope timer(
2090       isolate, Logger::TimerEventScope::v8_ic_miss);
2091   HandleScope shs(isolate);
2092   ASSERT(args.length() == 3);
2093 
2094   // Convert the parameters
2095   Handle<JSObject> object = args.at<JSObject>(0);
2096   Handle<Map> transition = args.at<Map>(1);
2097   Handle<Object> value = args.at<Object>(2);
2098 
2099   // Check the object has run out out property space.
2100   ASSERT(object->HasFastProperties());
2101   ASSERT(object->map()->unused_property_fields() == 0);
2102 
2103   // Expand the properties array.
2104   Handle<FixedArray> old_storage = handle(object->properties(), isolate);
2105   int new_unused = transition->unused_property_fields();
2106   int new_size = old_storage->length() + new_unused + 1;
2107 
2108   Handle<FixedArray> new_storage = FixedArray::CopySize(old_storage, new_size);
2109 
2110   Handle<Object> to_store = value;
2111 
2112   PropertyDetails details = transition->instance_descriptors()->GetDetails(
2113       transition->LastAdded());
2114   if (details.representation().IsDouble()) {
2115     to_store = isolate->factory()->NewHeapNumber(value->Number());
2116   }
2117 
2118   new_storage->set(old_storage->length(), *to_store);
2119 
2120   // Set the new property value and do the map transition.
2121   object->set_properties(*new_storage);
2122   object->set_map(*transition);
2123 
2124   // Return the stored value.
2125   return *value;
2126 }
2127 
2128 
2129 // Used from ic-<arch>.cc.
RUNTIME_FUNCTION(KeyedStoreIC_Miss)2130 RUNTIME_FUNCTION(KeyedStoreIC_Miss) {
2131   Logger::TimerEventScope timer(
2132       isolate, Logger::TimerEventScope::v8_ic_miss);
2133   HandleScope scope(isolate);
2134   ASSERT(args.length() == 3);
2135   KeyedStoreIC ic(IC::NO_EXTRA_FRAME, isolate);
2136   Handle<Object> receiver = args.at<Object>(0);
2137   Handle<Object> key = args.at<Object>(1);
2138   ic.UpdateState(receiver, key);
2139   Handle<Object> result;
2140   ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
2141       isolate,
2142       result,
2143       ic.Store(receiver, key, args.at<Object>(2)));
2144   return *result;
2145 }
2146 
2147 
RUNTIME_FUNCTION(KeyedStoreIC_MissFromStubFailure)2148 RUNTIME_FUNCTION(KeyedStoreIC_MissFromStubFailure) {
2149   Logger::TimerEventScope timer(
2150       isolate, Logger::TimerEventScope::v8_ic_miss);
2151   HandleScope scope(isolate);
2152   ASSERT(args.length() == 3);
2153   KeyedStoreIC ic(IC::EXTRA_CALL_FRAME, isolate);
2154   Handle<Object> receiver = args.at<Object>(0);
2155   Handle<Object> key = args.at<Object>(1);
2156   ic.UpdateState(receiver, key);
2157   Handle<Object> result;
2158   ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
2159       isolate,
2160       result,
2161       ic.Store(receiver, key, args.at<Object>(2)));
2162   return *result;
2163 }
2164 
2165 
RUNTIME_FUNCTION(StoreIC_Slow)2166 RUNTIME_FUNCTION(StoreIC_Slow) {
2167   HandleScope scope(isolate);
2168   ASSERT(args.length() == 3);
2169   StoreIC ic(IC::NO_EXTRA_FRAME, isolate);
2170   Handle<Object> object = args.at<Object>(0);
2171   Handle<Object> key = args.at<Object>(1);
2172   Handle<Object> value = args.at<Object>(2);
2173   StrictMode strict_mode = ic.strict_mode();
2174   Handle<Object> result;
2175   ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
2176       isolate, result,
2177       Runtime::SetObjectProperty(
2178           isolate, object, key, value, NONE, strict_mode));
2179   return *result;
2180 }
2181 
2182 
RUNTIME_FUNCTION(KeyedStoreIC_Slow)2183 RUNTIME_FUNCTION(KeyedStoreIC_Slow) {
2184   HandleScope scope(isolate);
2185   ASSERT(args.length() == 3);
2186   KeyedStoreIC ic(IC::NO_EXTRA_FRAME, isolate);
2187   Handle<Object> object = args.at<Object>(0);
2188   Handle<Object> key = args.at<Object>(1);
2189   Handle<Object> value = args.at<Object>(2);
2190   StrictMode strict_mode = ic.strict_mode();
2191   Handle<Object> result;
2192   ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
2193       isolate, result,
2194       Runtime::SetObjectProperty(
2195           isolate, object, key, value, NONE, strict_mode));
2196   return *result;
2197 }
2198 
2199 
RUNTIME_FUNCTION(ElementsTransitionAndStoreIC_Miss)2200 RUNTIME_FUNCTION(ElementsTransitionAndStoreIC_Miss) {
2201   Logger::TimerEventScope timer(
2202       isolate, Logger::TimerEventScope::v8_ic_miss);
2203   HandleScope scope(isolate);
2204   ASSERT(args.length() == 4);
2205   KeyedStoreIC ic(IC::EXTRA_CALL_FRAME, isolate);
2206   Handle<Object> value = args.at<Object>(0);
2207   Handle<Map> map = args.at<Map>(1);
2208   Handle<Object> key = args.at<Object>(2);
2209   Handle<Object> object = args.at<Object>(3);
2210   StrictMode strict_mode = ic.strict_mode();
2211   if (object->IsJSObject()) {
2212     JSObject::TransitionElementsKind(Handle<JSObject>::cast(object),
2213                                      map->elements_kind());
2214   }
2215   Handle<Object> result;
2216   ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
2217       isolate, result,
2218       Runtime::SetObjectProperty(
2219           isolate, object, key, value, NONE, strict_mode));
2220   return *result;
2221 }
2222 
2223 
State(Isolate * isolate,ExtraICState extra_ic_state)2224 BinaryOpIC::State::State(Isolate* isolate, ExtraICState extra_ic_state)
2225     : isolate_(isolate) {
2226   op_ = static_cast<Token::Value>(
2227       FIRST_TOKEN + OpField::decode(extra_ic_state));
2228   mode_ = OverwriteModeField::decode(extra_ic_state);
2229   fixed_right_arg_ = Maybe<int>(
2230       HasFixedRightArgField::decode(extra_ic_state),
2231       1 << FixedRightArgValueField::decode(extra_ic_state));
2232   left_kind_ = LeftKindField::decode(extra_ic_state);
2233   if (fixed_right_arg_.has_value) {
2234     right_kind_ = Smi::IsValid(fixed_right_arg_.value) ? SMI : INT32;
2235   } else {
2236     right_kind_ = RightKindField::decode(extra_ic_state);
2237   }
2238   result_kind_ = ResultKindField::decode(extra_ic_state);
2239   ASSERT_LE(FIRST_TOKEN, op_);
2240   ASSERT_LE(op_, LAST_TOKEN);
2241 }
2242 
2243 
GetExtraICState() const2244 ExtraICState BinaryOpIC::State::GetExtraICState() const {
2245   ExtraICState extra_ic_state =
2246       OpField::encode(op_ - FIRST_TOKEN) |
2247       OverwriteModeField::encode(mode_) |
2248       LeftKindField::encode(left_kind_) |
2249       ResultKindField::encode(result_kind_) |
2250       HasFixedRightArgField::encode(fixed_right_arg_.has_value);
2251   if (fixed_right_arg_.has_value) {
2252     extra_ic_state = FixedRightArgValueField::update(
2253         extra_ic_state, WhichPowerOf2(fixed_right_arg_.value));
2254   } else {
2255     extra_ic_state = RightKindField::update(extra_ic_state, right_kind_);
2256   }
2257   return extra_ic_state;
2258 }
2259 
2260 
2261 // static
GenerateAheadOfTime(Isolate * isolate,void (* Generate)(Isolate *,const State &))2262 void BinaryOpIC::State::GenerateAheadOfTime(
2263     Isolate* isolate, void (*Generate)(Isolate*, const State&)) {
2264   // TODO(olivf) We should investigate why adding stubs to the snapshot is so
2265   // expensive at runtime. When solved we should be able to add most binops to
2266   // the snapshot instead of hand-picking them.
2267   // Generated list of commonly used stubs
2268 #define GENERATE(op, left_kind, right_kind, result_kind, mode)  \
2269   do {                                                          \
2270     State state(isolate, op, mode);                             \
2271     state.left_kind_ = left_kind;                               \
2272     state.fixed_right_arg_.has_value = false;                   \
2273     state.right_kind_ = right_kind;                             \
2274     state.result_kind_ = result_kind;                           \
2275     Generate(isolate, state);                                   \
2276   } while (false)
2277   GENERATE(Token::ADD, INT32, INT32, INT32, NO_OVERWRITE);
2278   GENERATE(Token::ADD, INT32, INT32, INT32, OVERWRITE_LEFT);
2279   GENERATE(Token::ADD, INT32, INT32, NUMBER, NO_OVERWRITE);
2280   GENERATE(Token::ADD, INT32, INT32, NUMBER, OVERWRITE_LEFT);
2281   GENERATE(Token::ADD, INT32, NUMBER, NUMBER, NO_OVERWRITE);
2282   GENERATE(Token::ADD, INT32, NUMBER, NUMBER, OVERWRITE_LEFT);
2283   GENERATE(Token::ADD, INT32, NUMBER, NUMBER, OVERWRITE_RIGHT);
2284   GENERATE(Token::ADD, INT32, SMI, INT32, NO_OVERWRITE);
2285   GENERATE(Token::ADD, INT32, SMI, INT32, OVERWRITE_LEFT);
2286   GENERATE(Token::ADD, INT32, SMI, INT32, OVERWRITE_RIGHT);
2287   GENERATE(Token::ADD, NUMBER, INT32, NUMBER, NO_OVERWRITE);
2288   GENERATE(Token::ADD, NUMBER, INT32, NUMBER, OVERWRITE_LEFT);
2289   GENERATE(Token::ADD, NUMBER, INT32, NUMBER, OVERWRITE_RIGHT);
2290   GENERATE(Token::ADD, NUMBER, NUMBER, NUMBER, NO_OVERWRITE);
2291   GENERATE(Token::ADD, NUMBER, NUMBER, NUMBER, OVERWRITE_LEFT);
2292   GENERATE(Token::ADD, NUMBER, NUMBER, NUMBER, OVERWRITE_RIGHT);
2293   GENERATE(Token::ADD, NUMBER, SMI, NUMBER, NO_OVERWRITE);
2294   GENERATE(Token::ADD, NUMBER, SMI, NUMBER, OVERWRITE_LEFT);
2295   GENERATE(Token::ADD, NUMBER, SMI, NUMBER, OVERWRITE_RIGHT);
2296   GENERATE(Token::ADD, SMI, INT32, INT32, NO_OVERWRITE);
2297   GENERATE(Token::ADD, SMI, INT32, INT32, OVERWRITE_LEFT);
2298   GENERATE(Token::ADD, SMI, INT32, NUMBER, NO_OVERWRITE);
2299   GENERATE(Token::ADD, SMI, NUMBER, NUMBER, NO_OVERWRITE);
2300   GENERATE(Token::ADD, SMI, NUMBER, NUMBER, OVERWRITE_LEFT);
2301   GENERATE(Token::ADD, SMI, NUMBER, NUMBER, OVERWRITE_RIGHT);
2302   GENERATE(Token::ADD, SMI, SMI, INT32, OVERWRITE_LEFT);
2303   GENERATE(Token::ADD, SMI, SMI, SMI, OVERWRITE_RIGHT);
2304   GENERATE(Token::BIT_AND, INT32, INT32, INT32, NO_OVERWRITE);
2305   GENERATE(Token::BIT_AND, INT32, INT32, INT32, OVERWRITE_LEFT);
2306   GENERATE(Token::BIT_AND, INT32, INT32, INT32, OVERWRITE_RIGHT);
2307   GENERATE(Token::BIT_AND, INT32, INT32, SMI, NO_OVERWRITE);
2308   GENERATE(Token::BIT_AND, INT32, INT32, SMI, OVERWRITE_RIGHT);
2309   GENERATE(Token::BIT_AND, INT32, SMI, INT32, NO_OVERWRITE);
2310   GENERATE(Token::BIT_AND, INT32, SMI, INT32, OVERWRITE_RIGHT);
2311   GENERATE(Token::BIT_AND, INT32, SMI, SMI, NO_OVERWRITE);
2312   GENERATE(Token::BIT_AND, INT32, SMI, SMI, OVERWRITE_LEFT);
2313   GENERATE(Token::BIT_AND, INT32, SMI, SMI, OVERWRITE_RIGHT);
2314   GENERATE(Token::BIT_AND, NUMBER, INT32, INT32, OVERWRITE_RIGHT);
2315   GENERATE(Token::BIT_AND, NUMBER, SMI, SMI, NO_OVERWRITE);
2316   GENERATE(Token::BIT_AND, NUMBER, SMI, SMI, OVERWRITE_RIGHT);
2317   GENERATE(Token::BIT_AND, SMI, INT32, INT32, NO_OVERWRITE);
2318   GENERATE(Token::BIT_AND, SMI, INT32, SMI, OVERWRITE_RIGHT);
2319   GENERATE(Token::BIT_AND, SMI, NUMBER, SMI, OVERWRITE_RIGHT);
2320   GENERATE(Token::BIT_AND, SMI, SMI, SMI, NO_OVERWRITE);
2321   GENERATE(Token::BIT_AND, SMI, SMI, SMI, OVERWRITE_LEFT);
2322   GENERATE(Token::BIT_AND, SMI, SMI, SMI, OVERWRITE_RIGHT);
2323   GENERATE(Token::BIT_OR, INT32, INT32, INT32, OVERWRITE_LEFT);
2324   GENERATE(Token::BIT_OR, INT32, INT32, INT32, OVERWRITE_RIGHT);
2325   GENERATE(Token::BIT_OR, INT32, INT32, SMI, OVERWRITE_LEFT);
2326   GENERATE(Token::BIT_OR, INT32, SMI, INT32, NO_OVERWRITE);
2327   GENERATE(Token::BIT_OR, INT32, SMI, INT32, OVERWRITE_LEFT);
2328   GENERATE(Token::BIT_OR, INT32, SMI, INT32, OVERWRITE_RIGHT);
2329   GENERATE(Token::BIT_OR, INT32, SMI, SMI, NO_OVERWRITE);
2330   GENERATE(Token::BIT_OR, INT32, SMI, SMI, OVERWRITE_RIGHT);
2331   GENERATE(Token::BIT_OR, NUMBER, SMI, INT32, NO_OVERWRITE);
2332   GENERATE(Token::BIT_OR, NUMBER, SMI, INT32, OVERWRITE_LEFT);
2333   GENERATE(Token::BIT_OR, NUMBER, SMI, INT32, OVERWRITE_RIGHT);
2334   GENERATE(Token::BIT_OR, NUMBER, SMI, SMI, NO_OVERWRITE);
2335   GENERATE(Token::BIT_OR, NUMBER, SMI, SMI, OVERWRITE_LEFT);
2336   GENERATE(Token::BIT_OR, SMI, INT32, INT32, OVERWRITE_LEFT);
2337   GENERATE(Token::BIT_OR, SMI, INT32, INT32, OVERWRITE_RIGHT);
2338   GENERATE(Token::BIT_OR, SMI, INT32, SMI, OVERWRITE_RIGHT);
2339   GENERATE(Token::BIT_OR, SMI, SMI, SMI, OVERWRITE_LEFT);
2340   GENERATE(Token::BIT_OR, SMI, SMI, SMI, OVERWRITE_RIGHT);
2341   GENERATE(Token::BIT_XOR, INT32, INT32, INT32, NO_OVERWRITE);
2342   GENERATE(Token::BIT_XOR, INT32, INT32, INT32, OVERWRITE_LEFT);
2343   GENERATE(Token::BIT_XOR, INT32, INT32, INT32, OVERWRITE_RIGHT);
2344   GENERATE(Token::BIT_XOR, INT32, INT32, SMI, NO_OVERWRITE);
2345   GENERATE(Token::BIT_XOR, INT32, INT32, SMI, OVERWRITE_LEFT);
2346   GENERATE(Token::BIT_XOR, INT32, NUMBER, SMI, NO_OVERWRITE);
2347   GENERATE(Token::BIT_XOR, INT32, SMI, INT32, NO_OVERWRITE);
2348   GENERATE(Token::BIT_XOR, INT32, SMI, INT32, OVERWRITE_LEFT);
2349   GENERATE(Token::BIT_XOR, INT32, SMI, INT32, OVERWRITE_RIGHT);
2350   GENERATE(Token::BIT_XOR, NUMBER, INT32, INT32, NO_OVERWRITE);
2351   GENERATE(Token::BIT_XOR, NUMBER, SMI, INT32, NO_OVERWRITE);
2352   GENERATE(Token::BIT_XOR, NUMBER, SMI, SMI, NO_OVERWRITE);
2353   GENERATE(Token::BIT_XOR, SMI, INT32, INT32, NO_OVERWRITE);
2354   GENERATE(Token::BIT_XOR, SMI, INT32, INT32, OVERWRITE_LEFT);
2355   GENERATE(Token::BIT_XOR, SMI, INT32, SMI, OVERWRITE_LEFT);
2356   GENERATE(Token::BIT_XOR, SMI, SMI, SMI, NO_OVERWRITE);
2357   GENERATE(Token::BIT_XOR, SMI, SMI, SMI, OVERWRITE_LEFT);
2358   GENERATE(Token::BIT_XOR, SMI, SMI, SMI, OVERWRITE_RIGHT);
2359   GENERATE(Token::DIV, INT32, INT32, INT32, NO_OVERWRITE);
2360   GENERATE(Token::DIV, INT32, INT32, NUMBER, NO_OVERWRITE);
2361   GENERATE(Token::DIV, INT32, NUMBER, NUMBER, NO_OVERWRITE);
2362   GENERATE(Token::DIV, INT32, NUMBER, NUMBER, OVERWRITE_LEFT);
2363   GENERATE(Token::DIV, INT32, SMI, INT32, NO_OVERWRITE);
2364   GENERATE(Token::DIV, INT32, SMI, NUMBER, NO_OVERWRITE);
2365   GENERATE(Token::DIV, NUMBER, INT32, NUMBER, NO_OVERWRITE);
2366   GENERATE(Token::DIV, NUMBER, INT32, NUMBER, OVERWRITE_LEFT);
2367   GENERATE(Token::DIV, NUMBER, NUMBER, NUMBER, NO_OVERWRITE);
2368   GENERATE(Token::DIV, NUMBER, NUMBER, NUMBER, OVERWRITE_LEFT);
2369   GENERATE(Token::DIV, NUMBER, NUMBER, NUMBER, OVERWRITE_RIGHT);
2370   GENERATE(Token::DIV, NUMBER, SMI, NUMBER, NO_OVERWRITE);
2371   GENERATE(Token::DIV, NUMBER, SMI, NUMBER, OVERWRITE_LEFT);
2372   GENERATE(Token::DIV, SMI, INT32, INT32, NO_OVERWRITE);
2373   GENERATE(Token::DIV, SMI, INT32, NUMBER, NO_OVERWRITE);
2374   GENERATE(Token::DIV, SMI, INT32, NUMBER, OVERWRITE_LEFT);
2375   GENERATE(Token::DIV, SMI, NUMBER, NUMBER, NO_OVERWRITE);
2376   GENERATE(Token::DIV, SMI, NUMBER, NUMBER, OVERWRITE_LEFT);
2377   GENERATE(Token::DIV, SMI, NUMBER, NUMBER, OVERWRITE_RIGHT);
2378   GENERATE(Token::DIV, SMI, SMI, NUMBER, NO_OVERWRITE);
2379   GENERATE(Token::DIV, SMI, SMI, NUMBER, OVERWRITE_LEFT);
2380   GENERATE(Token::DIV, SMI, SMI, NUMBER, OVERWRITE_RIGHT);
2381   GENERATE(Token::DIV, SMI, SMI, SMI, NO_OVERWRITE);
2382   GENERATE(Token::DIV, SMI, SMI, SMI, OVERWRITE_LEFT);
2383   GENERATE(Token::DIV, SMI, SMI, SMI, OVERWRITE_RIGHT);
2384   GENERATE(Token::MOD, NUMBER, SMI, NUMBER, OVERWRITE_LEFT);
2385   GENERATE(Token::MOD, SMI, SMI, SMI, NO_OVERWRITE);
2386   GENERATE(Token::MOD, SMI, SMI, SMI, OVERWRITE_LEFT);
2387   GENERATE(Token::MUL, INT32, INT32, INT32, NO_OVERWRITE);
2388   GENERATE(Token::MUL, INT32, INT32, NUMBER, NO_OVERWRITE);
2389   GENERATE(Token::MUL, INT32, NUMBER, NUMBER, NO_OVERWRITE);
2390   GENERATE(Token::MUL, INT32, NUMBER, NUMBER, OVERWRITE_LEFT);
2391   GENERATE(Token::MUL, INT32, SMI, INT32, NO_OVERWRITE);
2392   GENERATE(Token::MUL, INT32, SMI, INT32, OVERWRITE_LEFT);
2393   GENERATE(Token::MUL, INT32, SMI, NUMBER, NO_OVERWRITE);
2394   GENERATE(Token::MUL, NUMBER, INT32, NUMBER, NO_OVERWRITE);
2395   GENERATE(Token::MUL, NUMBER, INT32, NUMBER, OVERWRITE_LEFT);
2396   GENERATE(Token::MUL, NUMBER, INT32, NUMBER, OVERWRITE_RIGHT);
2397   GENERATE(Token::MUL, NUMBER, NUMBER, NUMBER, NO_OVERWRITE);
2398   GENERATE(Token::MUL, NUMBER, NUMBER, NUMBER, OVERWRITE_LEFT);
2399   GENERATE(Token::MUL, NUMBER, SMI, NUMBER, NO_OVERWRITE);
2400   GENERATE(Token::MUL, NUMBER, SMI, NUMBER, OVERWRITE_LEFT);
2401   GENERATE(Token::MUL, NUMBER, SMI, NUMBER, OVERWRITE_RIGHT);
2402   GENERATE(Token::MUL, SMI, INT32, INT32, NO_OVERWRITE);
2403   GENERATE(Token::MUL, SMI, INT32, INT32, OVERWRITE_LEFT);
2404   GENERATE(Token::MUL, SMI, INT32, NUMBER, NO_OVERWRITE);
2405   GENERATE(Token::MUL, SMI, NUMBER, NUMBER, NO_OVERWRITE);
2406   GENERATE(Token::MUL, SMI, NUMBER, NUMBER, OVERWRITE_LEFT);
2407   GENERATE(Token::MUL, SMI, NUMBER, NUMBER, OVERWRITE_RIGHT);
2408   GENERATE(Token::MUL, SMI, SMI, INT32, NO_OVERWRITE);
2409   GENERATE(Token::MUL, SMI, SMI, NUMBER, NO_OVERWRITE);
2410   GENERATE(Token::MUL, SMI, SMI, NUMBER, OVERWRITE_LEFT);
2411   GENERATE(Token::MUL, SMI, SMI, SMI, NO_OVERWRITE);
2412   GENERATE(Token::MUL, SMI, SMI, SMI, OVERWRITE_LEFT);
2413   GENERATE(Token::MUL, SMI, SMI, SMI, OVERWRITE_RIGHT);
2414   GENERATE(Token::SAR, INT32, SMI, INT32, OVERWRITE_RIGHT);
2415   GENERATE(Token::SAR, INT32, SMI, SMI, NO_OVERWRITE);
2416   GENERATE(Token::SAR, INT32, SMI, SMI, OVERWRITE_RIGHT);
2417   GENERATE(Token::SAR, NUMBER, SMI, SMI, NO_OVERWRITE);
2418   GENERATE(Token::SAR, NUMBER, SMI, SMI, OVERWRITE_RIGHT);
2419   GENERATE(Token::SAR, SMI, SMI, SMI, OVERWRITE_LEFT);
2420   GENERATE(Token::SAR, SMI, SMI, SMI, OVERWRITE_RIGHT);
2421   GENERATE(Token::SHL, INT32, SMI, INT32, NO_OVERWRITE);
2422   GENERATE(Token::SHL, INT32, SMI, INT32, OVERWRITE_RIGHT);
2423   GENERATE(Token::SHL, INT32, SMI, SMI, NO_OVERWRITE);
2424   GENERATE(Token::SHL, INT32, SMI, SMI, OVERWRITE_RIGHT);
2425   GENERATE(Token::SHL, NUMBER, SMI, SMI, OVERWRITE_RIGHT);
2426   GENERATE(Token::SHL, SMI, SMI, INT32, NO_OVERWRITE);
2427   GENERATE(Token::SHL, SMI, SMI, INT32, OVERWRITE_LEFT);
2428   GENERATE(Token::SHL, SMI, SMI, INT32, OVERWRITE_RIGHT);
2429   GENERATE(Token::SHL, SMI, SMI, SMI, NO_OVERWRITE);
2430   GENERATE(Token::SHL, SMI, SMI, SMI, OVERWRITE_LEFT);
2431   GENERATE(Token::SHL, SMI, SMI, SMI, OVERWRITE_RIGHT);
2432   GENERATE(Token::SHR, INT32, SMI, SMI, NO_OVERWRITE);
2433   GENERATE(Token::SHR, INT32, SMI, SMI, OVERWRITE_LEFT);
2434   GENERATE(Token::SHR, INT32, SMI, SMI, OVERWRITE_RIGHT);
2435   GENERATE(Token::SHR, NUMBER, SMI, SMI, NO_OVERWRITE);
2436   GENERATE(Token::SHR, NUMBER, SMI, SMI, OVERWRITE_LEFT);
2437   GENERATE(Token::SHR, NUMBER, SMI, INT32, OVERWRITE_RIGHT);
2438   GENERATE(Token::SHR, SMI, SMI, SMI, NO_OVERWRITE);
2439   GENERATE(Token::SHR, SMI, SMI, SMI, OVERWRITE_LEFT);
2440   GENERATE(Token::SHR, SMI, SMI, SMI, OVERWRITE_RIGHT);
2441   GENERATE(Token::SUB, INT32, INT32, INT32, NO_OVERWRITE);
2442   GENERATE(Token::SUB, INT32, INT32, INT32, OVERWRITE_LEFT);
2443   GENERATE(Token::SUB, INT32, NUMBER, NUMBER, NO_OVERWRITE);
2444   GENERATE(Token::SUB, INT32, NUMBER, NUMBER, OVERWRITE_RIGHT);
2445   GENERATE(Token::SUB, INT32, SMI, INT32, OVERWRITE_LEFT);
2446   GENERATE(Token::SUB, INT32, SMI, INT32, OVERWRITE_RIGHT);
2447   GENERATE(Token::SUB, NUMBER, INT32, NUMBER, NO_OVERWRITE);
2448   GENERATE(Token::SUB, NUMBER, INT32, NUMBER, OVERWRITE_LEFT);
2449   GENERATE(Token::SUB, NUMBER, NUMBER, NUMBER, NO_OVERWRITE);
2450   GENERATE(Token::SUB, NUMBER, NUMBER, NUMBER, OVERWRITE_LEFT);
2451   GENERATE(Token::SUB, NUMBER, NUMBER, NUMBER, OVERWRITE_RIGHT);
2452   GENERATE(Token::SUB, NUMBER, SMI, NUMBER, NO_OVERWRITE);
2453   GENERATE(Token::SUB, NUMBER, SMI, NUMBER, OVERWRITE_LEFT);
2454   GENERATE(Token::SUB, NUMBER, SMI, NUMBER, OVERWRITE_RIGHT);
2455   GENERATE(Token::SUB, SMI, INT32, INT32, NO_OVERWRITE);
2456   GENERATE(Token::SUB, SMI, NUMBER, NUMBER, NO_OVERWRITE);
2457   GENERATE(Token::SUB, SMI, NUMBER, NUMBER, OVERWRITE_LEFT);
2458   GENERATE(Token::SUB, SMI, NUMBER, NUMBER, OVERWRITE_RIGHT);
2459   GENERATE(Token::SUB, SMI, SMI, SMI, NO_OVERWRITE);
2460   GENERATE(Token::SUB, SMI, SMI, SMI, OVERWRITE_LEFT);
2461   GENERATE(Token::SUB, SMI, SMI, SMI, OVERWRITE_RIGHT);
2462 #undef GENERATE
2463 #define GENERATE(op, left_kind, fixed_right_arg_value, result_kind, mode) \
2464   do {                                                                    \
2465     State state(isolate, op, mode);                                       \
2466     state.left_kind_ = left_kind;                                         \
2467     state.fixed_right_arg_.has_value = true;                              \
2468     state.fixed_right_arg_.value = fixed_right_arg_value;                 \
2469     state.right_kind_ = SMI;                                              \
2470     state.result_kind_ = result_kind;                                     \
2471     Generate(isolate, state);                                             \
2472   } while (false)
2473   GENERATE(Token::MOD, SMI, 2, SMI, NO_OVERWRITE);
2474   GENERATE(Token::MOD, SMI, 4, SMI, NO_OVERWRITE);
2475   GENERATE(Token::MOD, SMI, 4, SMI, OVERWRITE_LEFT);
2476   GENERATE(Token::MOD, SMI, 8, SMI, NO_OVERWRITE);
2477   GENERATE(Token::MOD, SMI, 16, SMI, OVERWRITE_LEFT);
2478   GENERATE(Token::MOD, SMI, 32, SMI, NO_OVERWRITE);
2479   GENERATE(Token::MOD, SMI, 2048, SMI, NO_OVERWRITE);
2480 #undef GENERATE
2481 }
2482 
2483 
GetResultType(Zone * zone) const2484 Type* BinaryOpIC::State::GetResultType(Zone* zone) const {
2485   Kind result_kind = result_kind_;
2486   if (HasSideEffects()) {
2487     result_kind = NONE;
2488   } else if (result_kind == GENERIC && op_ == Token::ADD) {
2489     return Type::Union(Type::Number(zone), Type::String(zone), zone);
2490   } else if (result_kind == NUMBER && op_ == Token::SHR) {
2491     return Type::Unsigned32(zone);
2492   }
2493   ASSERT_NE(GENERIC, result_kind);
2494   return KindToType(result_kind, zone);
2495 }
2496 
2497 
Print(StringStream * stream) const2498 void BinaryOpIC::State::Print(StringStream* stream) const {
2499   stream->Add("(%s", Token::Name(op_));
2500   if (mode_ == OVERWRITE_LEFT) stream->Add("_ReuseLeft");
2501   else if (mode_ == OVERWRITE_RIGHT) stream->Add("_ReuseRight");
2502   if (CouldCreateAllocationMementos()) stream->Add("_CreateAllocationMementos");
2503   stream->Add(":%s*", KindToString(left_kind_));
2504   if (fixed_right_arg_.has_value) {
2505     stream->Add("%d", fixed_right_arg_.value);
2506   } else {
2507     stream->Add("%s", KindToString(right_kind_));
2508   }
2509   stream->Add("->%s)", KindToString(result_kind_));
2510 }
2511 
2512 
Update(Handle<Object> left,Handle<Object> right,Handle<Object> result)2513 void BinaryOpIC::State::Update(Handle<Object> left,
2514                                Handle<Object> right,
2515                                Handle<Object> result) {
2516   ExtraICState old_extra_ic_state = GetExtraICState();
2517 
2518   left_kind_ = UpdateKind(left, left_kind_);
2519   right_kind_ = UpdateKind(right, right_kind_);
2520 
2521   int32_t fixed_right_arg_value = 0;
2522   bool has_fixed_right_arg =
2523       op_ == Token::MOD &&
2524       right->ToInt32(&fixed_right_arg_value) &&
2525       fixed_right_arg_value > 0 &&
2526       IsPowerOf2(fixed_right_arg_value) &&
2527       FixedRightArgValueField::is_valid(WhichPowerOf2(fixed_right_arg_value)) &&
2528       (left_kind_ == SMI || left_kind_ == INT32) &&
2529       (result_kind_ == NONE || !fixed_right_arg_.has_value);
2530   fixed_right_arg_ = Maybe<int32_t>(has_fixed_right_arg,
2531                                     fixed_right_arg_value);
2532 
2533   result_kind_ = UpdateKind(result, result_kind_);
2534 
2535   if (!Token::IsTruncatingBinaryOp(op_)) {
2536     Kind input_kind = Max(left_kind_, right_kind_);
2537     if (result_kind_ < input_kind && input_kind <= NUMBER) {
2538       result_kind_ = input_kind;
2539     }
2540   }
2541 
2542   // We don't want to distinguish INT32 and NUMBER for string add (because
2543   // NumberToString can't make use of this anyway).
2544   if (left_kind_ == STRING && right_kind_ == INT32) {
2545     ASSERT_EQ(STRING, result_kind_);
2546     ASSERT_EQ(Token::ADD, op_);
2547     right_kind_ = NUMBER;
2548   } else if (right_kind_ == STRING && left_kind_ == INT32) {
2549     ASSERT_EQ(STRING, result_kind_);
2550     ASSERT_EQ(Token::ADD, op_);
2551     left_kind_ = NUMBER;
2552   }
2553 
2554   // Reset overwrite mode unless we can actually make use of it, or may be able
2555   // to make use of it at some point in the future.
2556   if ((mode_ == OVERWRITE_LEFT && left_kind_ > NUMBER) ||
2557       (mode_ == OVERWRITE_RIGHT && right_kind_ > NUMBER) ||
2558       result_kind_ > NUMBER) {
2559     mode_ = NO_OVERWRITE;
2560   }
2561 
2562   if (old_extra_ic_state == GetExtraICState()) {
2563     // Tagged operations can lead to non-truncating HChanges
2564     if (left->IsUndefined() || left->IsBoolean()) {
2565       left_kind_ = GENERIC;
2566     } else {
2567       ASSERT(right->IsUndefined() || right->IsBoolean());
2568       right_kind_ = GENERIC;
2569     }
2570   }
2571 }
2572 
2573 
UpdateKind(Handle<Object> object,Kind kind) const2574 BinaryOpIC::State::Kind BinaryOpIC::State::UpdateKind(Handle<Object> object,
2575                                                       Kind kind) const {
2576   Kind new_kind = GENERIC;
2577   bool is_truncating = Token::IsTruncatingBinaryOp(op());
2578   if (object->IsBoolean() && is_truncating) {
2579     // Booleans will be automatically truncated by HChange.
2580     new_kind = INT32;
2581   } else if (object->IsUndefined()) {
2582     // Undefined will be automatically truncated by HChange.
2583     new_kind = is_truncating ? INT32 : NUMBER;
2584   } else if (object->IsSmi()) {
2585     new_kind = SMI;
2586   } else if (object->IsHeapNumber()) {
2587     double value = Handle<HeapNumber>::cast(object)->value();
2588     new_kind = IsInt32Double(value) ? INT32 : NUMBER;
2589   } else if (object->IsString() && op() == Token::ADD) {
2590     new_kind = STRING;
2591   }
2592   if (new_kind == INT32 && SmiValuesAre32Bits()) {
2593     new_kind = NUMBER;
2594   }
2595   if (kind != NONE &&
2596       ((new_kind <= NUMBER && kind > NUMBER) ||
2597        (new_kind > NUMBER && kind <= NUMBER))) {
2598     new_kind = GENERIC;
2599   }
2600   return Max(kind, new_kind);
2601 }
2602 
2603 
2604 // static
KindToString(Kind kind)2605 const char* BinaryOpIC::State::KindToString(Kind kind) {
2606   switch (kind) {
2607     case NONE: return "None";
2608     case SMI: return "Smi";
2609     case INT32: return "Int32";
2610     case NUMBER: return "Number";
2611     case STRING: return "String";
2612     case GENERIC: return "Generic";
2613   }
2614   UNREACHABLE();
2615   return NULL;
2616 }
2617 
2618 
2619 // static
KindToType(Kind kind,Zone * zone)2620 Type* BinaryOpIC::State::KindToType(Kind kind, Zone* zone) {
2621   switch (kind) {
2622     case NONE: return Type::None(zone);
2623     case SMI: return Type::SignedSmall(zone);
2624     case INT32: return Type::Signed32(zone);
2625     case NUMBER: return Type::Number(zone);
2626     case STRING: return Type::String(zone);
2627     case GENERIC: return Type::Any(zone);
2628   }
2629   UNREACHABLE();
2630   return NULL;
2631 }
2632 
2633 
Transition(Handle<AllocationSite> allocation_site,Handle<Object> left,Handle<Object> right)2634 MaybeHandle<Object> BinaryOpIC::Transition(
2635     Handle<AllocationSite> allocation_site,
2636     Handle<Object> left,
2637     Handle<Object> right) {
2638   State state(isolate(), target()->extra_ic_state());
2639 
2640   // Compute the actual result using the builtin for the binary operation.
2641   Object* builtin = isolate()->js_builtins_object()->javascript_builtin(
2642       TokenToJSBuiltin(state.op()));
2643   Handle<JSFunction> function = handle(JSFunction::cast(builtin), isolate());
2644   Handle<Object> result;
2645   ASSIGN_RETURN_ON_EXCEPTION(
2646       isolate(),
2647       result,
2648       Execution::Call(isolate(), function, left, 1, &right),
2649       Object);
2650 
2651   // Execution::Call can execute arbitrary JavaScript, hence potentially
2652   // update the state of this very IC, so we must update the stored state.
2653   UpdateTarget();
2654   // Compute the new state.
2655   State old_state(isolate(), target()->extra_ic_state());
2656   state.Update(left, right, result);
2657 
2658   // Check if we have a string operation here.
2659   Handle<Code> target;
2660   if (!allocation_site.is_null() || state.ShouldCreateAllocationMementos()) {
2661     // Setup the allocation site on-demand.
2662     if (allocation_site.is_null()) {
2663       allocation_site = isolate()->factory()->NewAllocationSite();
2664     }
2665 
2666     // Install the stub with an allocation site.
2667     BinaryOpICWithAllocationSiteStub stub(isolate(), state);
2668     target = stub.GetCodeCopyFromTemplate(allocation_site);
2669 
2670     // Sanity check the trampoline stub.
2671     ASSERT_EQ(*allocation_site, target->FindFirstAllocationSite());
2672   } else {
2673     // Install the generic stub.
2674     BinaryOpICStub stub(isolate(), state);
2675     target = stub.GetCode();
2676 
2677     // Sanity check the generic stub.
2678     ASSERT_EQ(NULL, target->FindFirstAllocationSite());
2679   }
2680   set_target(*target);
2681 
2682   if (FLAG_trace_ic) {
2683     char buffer[150];
2684     NoAllocationStringAllocator allocator(
2685         buffer, static_cast<unsigned>(sizeof(buffer)));
2686     StringStream stream(&allocator);
2687     stream.Add("[BinaryOpIC");
2688     old_state.Print(&stream);
2689     stream.Add(" => ");
2690     state.Print(&stream);
2691     stream.Add(" @ %p <- ", static_cast<void*>(*target));
2692     stream.OutputToStdOut();
2693     JavaScriptFrame::PrintTop(isolate(), stdout, false, true);
2694     if (!allocation_site.is_null()) {
2695       PrintF(" using allocation site %p", static_cast<void*>(*allocation_site));
2696     }
2697     PrintF("]\n");
2698   }
2699 
2700   // Patch the inlined smi code as necessary.
2701   if (!old_state.UseInlinedSmiCode() && state.UseInlinedSmiCode()) {
2702     PatchInlinedSmiCode(address(), ENABLE_INLINED_SMI_CHECK);
2703   } else if (old_state.UseInlinedSmiCode() && !state.UseInlinedSmiCode()) {
2704     PatchInlinedSmiCode(address(), DISABLE_INLINED_SMI_CHECK);
2705   }
2706 
2707   return result;
2708 }
2709 
2710 
RUNTIME_FUNCTION(BinaryOpIC_Miss)2711 RUNTIME_FUNCTION(BinaryOpIC_Miss) {
2712   Logger::TimerEventScope timer(
2713       isolate, Logger::TimerEventScope::v8_ic_miss);
2714   HandleScope scope(isolate);
2715   ASSERT_EQ(2, args.length());
2716   Handle<Object> left = args.at<Object>(BinaryOpICStub::kLeft);
2717   Handle<Object> right = args.at<Object>(BinaryOpICStub::kRight);
2718   BinaryOpIC ic(isolate);
2719   Handle<Object> result;
2720   ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
2721       isolate,
2722       result,
2723       ic.Transition(Handle<AllocationSite>::null(), left, right));
2724   return *result;
2725 }
2726 
2727 
RUNTIME_FUNCTION(BinaryOpIC_MissWithAllocationSite)2728 RUNTIME_FUNCTION(BinaryOpIC_MissWithAllocationSite) {
2729   Logger::TimerEventScope timer(
2730       isolate, Logger::TimerEventScope::v8_ic_miss);
2731   HandleScope scope(isolate);
2732   ASSERT_EQ(3, args.length());
2733   Handle<AllocationSite> allocation_site = args.at<AllocationSite>(
2734       BinaryOpWithAllocationSiteStub::kAllocationSite);
2735   Handle<Object> left = args.at<Object>(
2736       BinaryOpWithAllocationSiteStub::kLeft);
2737   Handle<Object> right = args.at<Object>(
2738       BinaryOpWithAllocationSiteStub::kRight);
2739   BinaryOpIC ic(isolate);
2740   Handle<Object> result;
2741   ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
2742       isolate,
2743       result,
2744       ic.Transition(allocation_site, left, right));
2745   return *result;
2746 }
2747 
2748 
GetRawUninitialized(Isolate * isolate,Token::Value op)2749 Code* CompareIC::GetRawUninitialized(Isolate* isolate, Token::Value op) {
2750   ICCompareStub stub(isolate, op, UNINITIALIZED, UNINITIALIZED, UNINITIALIZED);
2751   Code* code = NULL;
2752   CHECK(stub.FindCodeInCache(&code));
2753   return code;
2754 }
2755 
2756 
GetUninitialized(Isolate * isolate,Token::Value op)2757 Handle<Code> CompareIC::GetUninitialized(Isolate* isolate, Token::Value op) {
2758   ICCompareStub stub(isolate, op, UNINITIALIZED, UNINITIALIZED, UNINITIALIZED);
2759   return stub.GetCode();
2760 }
2761 
2762 
GetStateName(State state)2763 const char* CompareIC::GetStateName(State state) {
2764   switch (state) {
2765     case UNINITIALIZED: return "UNINITIALIZED";
2766     case SMI: return "SMI";
2767     case NUMBER: return "NUMBER";
2768     case INTERNALIZED_STRING: return "INTERNALIZED_STRING";
2769     case STRING: return "STRING";
2770     case UNIQUE_NAME: return "UNIQUE_NAME";
2771     case OBJECT: return "OBJECT";
2772     case KNOWN_OBJECT: return "KNOWN_OBJECT";
2773     case GENERIC: return "GENERIC";
2774   }
2775   UNREACHABLE();
2776   return NULL;
2777 }
2778 
2779 
StateToType(Zone * zone,CompareIC::State state,Handle<Map> map)2780 Type* CompareIC::StateToType(
2781     Zone* zone,
2782     CompareIC::State state,
2783     Handle<Map> map) {
2784   switch (state) {
2785     case CompareIC::UNINITIALIZED: return Type::None(zone);
2786     case CompareIC::SMI: return Type::SignedSmall(zone);
2787     case CompareIC::NUMBER: return Type::Number(zone);
2788     case CompareIC::STRING: return Type::String(zone);
2789     case CompareIC::INTERNALIZED_STRING: return Type::InternalizedString(zone);
2790     case CompareIC::UNIQUE_NAME: return Type::UniqueName(zone);
2791     case CompareIC::OBJECT: return Type::Receiver(zone);
2792     case CompareIC::KNOWN_OBJECT:
2793       return map.is_null() ? Type::Receiver(zone) : Type::Class(map, zone);
2794     case CompareIC::GENERIC: return Type::Any(zone);
2795   }
2796   UNREACHABLE();
2797   return NULL;
2798 }
2799 
2800 
StubInfoToType(int stub_minor_key,Type ** left_type,Type ** right_type,Type ** overall_type,Handle<Map> map,Zone * zone)2801 void CompareIC::StubInfoToType(int stub_minor_key,
2802                                Type** left_type,
2803                                Type** right_type,
2804                                Type** overall_type,
2805                                Handle<Map> map,
2806                                Zone* zone) {
2807   State left_state, right_state, handler_state;
2808   ICCompareStub::DecodeMinorKey(stub_minor_key, &left_state, &right_state,
2809                                 &handler_state, NULL);
2810   *left_type = StateToType(zone, left_state);
2811   *right_type = StateToType(zone, right_state);
2812   *overall_type = StateToType(zone, handler_state, map);
2813 }
2814 
2815 
NewInputState(State old_state,Handle<Object> value)2816 CompareIC::State CompareIC::NewInputState(State old_state,
2817                                           Handle<Object> value) {
2818   switch (old_state) {
2819     case UNINITIALIZED:
2820       if (value->IsSmi()) return SMI;
2821       if (value->IsHeapNumber()) return NUMBER;
2822       if (value->IsInternalizedString()) return INTERNALIZED_STRING;
2823       if (value->IsString()) return STRING;
2824       if (value->IsSymbol()) return UNIQUE_NAME;
2825       if (value->IsJSObject()) return OBJECT;
2826       break;
2827     case SMI:
2828       if (value->IsSmi()) return SMI;
2829       if (value->IsHeapNumber()) return NUMBER;
2830       break;
2831     case NUMBER:
2832       if (value->IsNumber()) return NUMBER;
2833       break;
2834     case INTERNALIZED_STRING:
2835       if (value->IsInternalizedString()) return INTERNALIZED_STRING;
2836       if (value->IsString()) return STRING;
2837       if (value->IsSymbol()) return UNIQUE_NAME;
2838       break;
2839     case STRING:
2840       if (value->IsString()) return STRING;
2841       break;
2842     case UNIQUE_NAME:
2843       if (value->IsUniqueName()) return UNIQUE_NAME;
2844       break;
2845     case OBJECT:
2846       if (value->IsJSObject()) return OBJECT;
2847       break;
2848     case GENERIC:
2849       break;
2850     case KNOWN_OBJECT:
2851       UNREACHABLE();
2852       break;
2853   }
2854   return GENERIC;
2855 }
2856 
2857 
TargetState(State old_state,State old_left,State old_right,bool has_inlined_smi_code,Handle<Object> x,Handle<Object> y)2858 CompareIC::State CompareIC::TargetState(State old_state,
2859                                         State old_left,
2860                                         State old_right,
2861                                         bool has_inlined_smi_code,
2862                                         Handle<Object> x,
2863                                         Handle<Object> y) {
2864   switch (old_state) {
2865     case UNINITIALIZED:
2866       if (x->IsSmi() && y->IsSmi()) return SMI;
2867       if (x->IsNumber() && y->IsNumber()) return NUMBER;
2868       if (Token::IsOrderedRelationalCompareOp(op_)) {
2869         // Ordered comparisons treat undefined as NaN, so the
2870         // NUMBER stub will do the right thing.
2871         if ((x->IsNumber() && y->IsUndefined()) ||
2872             (y->IsNumber() && x->IsUndefined())) {
2873           return NUMBER;
2874         }
2875       }
2876       if (x->IsInternalizedString() && y->IsInternalizedString()) {
2877         // We compare internalized strings as plain ones if we need to determine
2878         // the order in a non-equality compare.
2879         return Token::IsEqualityOp(op_) ? INTERNALIZED_STRING : STRING;
2880       }
2881       if (x->IsString() && y->IsString()) return STRING;
2882       if (!Token::IsEqualityOp(op_)) return GENERIC;
2883       if (x->IsUniqueName() && y->IsUniqueName()) return UNIQUE_NAME;
2884       if (x->IsJSObject() && y->IsJSObject()) {
2885         if (Handle<JSObject>::cast(x)->map() ==
2886             Handle<JSObject>::cast(y)->map()) {
2887           return KNOWN_OBJECT;
2888         } else {
2889           return OBJECT;
2890         }
2891       }
2892       return GENERIC;
2893     case SMI:
2894       return x->IsNumber() && y->IsNumber() ? NUMBER : GENERIC;
2895     case INTERNALIZED_STRING:
2896       ASSERT(Token::IsEqualityOp(op_));
2897       if (x->IsString() && y->IsString()) return STRING;
2898       if (x->IsUniqueName() && y->IsUniqueName()) return UNIQUE_NAME;
2899       return GENERIC;
2900     case NUMBER:
2901       // If the failure was due to one side changing from smi to heap number,
2902       // then keep the state (if other changed at the same time, we will get
2903       // a second miss and then go to generic).
2904       if (old_left == SMI && x->IsHeapNumber()) return NUMBER;
2905       if (old_right == SMI && y->IsHeapNumber()) return NUMBER;
2906       return GENERIC;
2907     case KNOWN_OBJECT:
2908       ASSERT(Token::IsEqualityOp(op_));
2909       if (x->IsJSObject() && y->IsJSObject()) return OBJECT;
2910       return GENERIC;
2911     case STRING:
2912     case UNIQUE_NAME:
2913     case OBJECT:
2914     case GENERIC:
2915       return GENERIC;
2916   }
2917   UNREACHABLE();
2918   return GENERIC;  // Make the compiler happy.
2919 }
2920 
2921 
UpdateCaches(Handle<Object> x,Handle<Object> y)2922 Code* CompareIC::UpdateCaches(Handle<Object> x, Handle<Object> y) {
2923   HandleScope scope(isolate());
2924   State previous_left, previous_right, previous_state;
2925   ICCompareStub::DecodeMinorKey(target()->stub_info(), &previous_left,
2926                                 &previous_right, &previous_state, NULL);
2927   State new_left = NewInputState(previous_left, x);
2928   State new_right = NewInputState(previous_right, y);
2929   State state = TargetState(previous_state, previous_left, previous_right,
2930                             HasInlinedSmiCode(address()), x, y);
2931   ICCompareStub stub(isolate(), op_, new_left, new_right, state);
2932   if (state == KNOWN_OBJECT) {
2933     stub.set_known_map(
2934         Handle<Map>(Handle<JSObject>::cast(x)->map(), isolate()));
2935   }
2936   Handle<Code> new_target = stub.GetCode();
2937   set_target(*new_target);
2938 
2939   if (FLAG_trace_ic) {
2940     PrintF("[CompareIC in ");
2941     JavaScriptFrame::PrintTop(isolate(), stdout, false, true);
2942     PrintF(" ((%s+%s=%s)->(%s+%s=%s))#%s @ %p]\n",
2943            GetStateName(previous_left),
2944            GetStateName(previous_right),
2945            GetStateName(previous_state),
2946            GetStateName(new_left),
2947            GetStateName(new_right),
2948            GetStateName(state),
2949            Token::Name(op_),
2950            static_cast<void*>(*stub.GetCode()));
2951   }
2952 
2953   // Activate inlined smi code.
2954   if (previous_state == UNINITIALIZED) {
2955     PatchInlinedSmiCode(address(), ENABLE_INLINED_SMI_CHECK);
2956   }
2957 
2958   return *new_target;
2959 }
2960 
2961 
2962 // Used from ICCompareStub::GenerateMiss in code-stubs-<arch>.cc.
RUNTIME_FUNCTION(CompareIC_Miss)2963 RUNTIME_FUNCTION(CompareIC_Miss) {
2964   Logger::TimerEventScope timer(
2965       isolate, Logger::TimerEventScope::v8_ic_miss);
2966   HandleScope scope(isolate);
2967   ASSERT(args.length() == 3);
2968   CompareIC ic(isolate, static_cast<Token::Value>(args.smi_at(2)));
2969   return ic.UpdateCaches(args.at<Object>(0), args.at<Object>(1));
2970 }
2971 
2972 
Clear(Address address,Code * target,ConstantPoolArray * constant_pool)2973 void CompareNilIC::Clear(Address address,
2974                          Code* target,
2975                          ConstantPoolArray* constant_pool) {
2976   if (IsCleared(target)) return;
2977   ExtraICState state = target->extra_ic_state();
2978 
2979   CompareNilICStub stub(target->GetIsolate(),
2980                         state,
2981                         HydrogenCodeStub::UNINITIALIZED);
2982   stub.ClearState();
2983 
2984   Code* code = NULL;
2985   CHECK(stub.FindCodeInCache(&code));
2986 
2987   SetTargetAtAddress(address, code, constant_pool);
2988 }
2989 
2990 
DoCompareNilSlow(Isolate * isolate,NilValue nil,Handle<Object> object)2991 Handle<Object> CompareNilIC::DoCompareNilSlow(Isolate* isolate,
2992                                               NilValue nil,
2993                                               Handle<Object> object) {
2994   if (object->IsNull() || object->IsUndefined()) {
2995     return handle(Smi::FromInt(true), isolate);
2996   }
2997   return handle(Smi::FromInt(object->IsUndetectableObject()), isolate);
2998 }
2999 
3000 
CompareNil(Handle<Object> object)3001 Handle<Object> CompareNilIC::CompareNil(Handle<Object> object) {
3002   ExtraICState extra_ic_state = target()->extra_ic_state();
3003 
3004   CompareNilICStub stub(isolate(), extra_ic_state);
3005 
3006   // Extract the current supported types from the patched IC and calculate what
3007   // types must be supported as a result of the miss.
3008   bool already_monomorphic = stub.IsMonomorphic();
3009 
3010   stub.UpdateStatus(object);
3011 
3012   NilValue nil = stub.GetNilValue();
3013 
3014   // Find or create the specialized stub to support the new set of types.
3015   Handle<Code> code;
3016   if (stub.IsMonomorphic()) {
3017     Handle<Map> monomorphic_map(already_monomorphic && FirstTargetMap() != NULL
3018                                 ? FirstTargetMap()
3019                                 : HeapObject::cast(*object)->map());
3020     code = isolate()->stub_cache()->ComputeCompareNil(monomorphic_map, &stub);
3021   } else {
3022     code = stub.GetCode();
3023   }
3024   set_target(*code);
3025   return DoCompareNilSlow(isolate(), nil, object);
3026 }
3027 
3028 
RUNTIME_FUNCTION(CompareNilIC_Miss)3029 RUNTIME_FUNCTION(CompareNilIC_Miss) {
3030   Logger::TimerEventScope timer(
3031       isolate, Logger::TimerEventScope::v8_ic_miss);
3032   HandleScope scope(isolate);
3033   Handle<Object> object = args.at<Object>(0);
3034   CompareNilIC ic(isolate);
3035   return *ic.CompareNil(object);
3036 }
3037 
3038 
RUNTIME_FUNCTION(Unreachable)3039 RUNTIME_FUNCTION(Unreachable) {
3040   UNREACHABLE();
3041   CHECK(false);
3042   return isolate->heap()->undefined_value();
3043 }
3044 
3045 
TokenToJSBuiltin(Token::Value op)3046 Builtins::JavaScript BinaryOpIC::TokenToJSBuiltin(Token::Value op) {
3047   switch (op) {
3048     default:
3049       UNREACHABLE();
3050     case Token::ADD:
3051       return Builtins::ADD;
3052       break;
3053     case Token::SUB:
3054       return Builtins::SUB;
3055       break;
3056     case Token::MUL:
3057       return Builtins::MUL;
3058       break;
3059     case Token::DIV:
3060       return Builtins::DIV;
3061       break;
3062     case Token::MOD:
3063       return Builtins::MOD;
3064       break;
3065     case Token::BIT_OR:
3066       return Builtins::BIT_OR;
3067       break;
3068     case Token::BIT_AND:
3069       return Builtins::BIT_AND;
3070       break;
3071     case Token::BIT_XOR:
3072       return Builtins::BIT_XOR;
3073       break;
3074     case Token::SAR:
3075       return Builtins::SAR;
3076       break;
3077     case Token::SHR:
3078       return Builtins::SHR;
3079       break;
3080     case Token::SHL:
3081       return Builtins::SHL;
3082       break;
3083   }
3084 }
3085 
3086 
ToBoolean(Handle<Object> object)3087 Handle<Object> ToBooleanIC::ToBoolean(Handle<Object> object) {
3088   ToBooleanStub stub(isolate(), target()->extra_ic_state());
3089   bool to_boolean_value = stub.UpdateStatus(object);
3090   Handle<Code> code = stub.GetCode();
3091   set_target(*code);
3092   return handle(Smi::FromInt(to_boolean_value ? 1 : 0), isolate());
3093 }
3094 
3095 
RUNTIME_FUNCTION(ToBooleanIC_Miss)3096 RUNTIME_FUNCTION(ToBooleanIC_Miss) {
3097   Logger::TimerEventScope timer(
3098       isolate, Logger::TimerEventScope::v8_ic_miss);
3099   ASSERT(args.length() == 1);
3100   HandleScope scope(isolate);
3101   Handle<Object> object = args.at<Object>(0);
3102   ToBooleanIC ic(isolate);
3103   return *ic.ToBoolean(object);
3104 }
3105 
3106 
3107 static const Address IC_utilities[] = {
3108 #define ADDR(name) FUNCTION_ADDR(name),
3109     IC_UTIL_LIST(ADDR)
3110     NULL
3111 #undef ADDR
3112 };
3113 
3114 
AddressFromUtilityId(IC::UtilityId id)3115 Address IC::AddressFromUtilityId(IC::UtilityId id) {
3116   return IC_utilities[id];
3117 }
3118 
3119 
3120 } }  // namespace v8::internal
3121