6a3b16dc4d8e38def3fb3334e172d399c1eea18f
[WebKit-https.git] / Source / JavaScriptCore / jit / JITOperations.cpp
1 /*
2  * Copyright (C) 2013-2017 Apple Inc. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  *
13  * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
14  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE INC. OR
17  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
18  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
19  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
20  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
21  * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
23  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
24  */
25
26 #include "config.h"
27 #include "JITOperations.h"
28
29 #if ENABLE(JIT)
30
31 #include "ArithProfile.h"
32 #include "ArrayConstructor.h"
33 #include "CommonSlowPaths.h"
34 #include "DFGCompilationMode.h"
35 #include "DFGDriver.h"
36 #include "DFGOSREntry.h"
37 #include "DFGThunks.h"
38 #include "DFGWorklist.h"
39 #include "Debugger.h"
40 #include "DirectArguments.h"
41 #include "Error.h"
42 #include "ErrorHandlingScope.h"
43 #include "EvalCodeBlock.h"
44 #include "ExceptionFuzz.h"
45 #include "FTLOSREntry.h"
46 #include "FrameTracers.h"
47 #include "FunctionCodeBlock.h"
48 #include "GetterSetter.h"
49 #include "HostCallReturnValue.h"
50 #include "ICStats.h"
51 #include "Interpreter.h"
52 #include "JIT.h"
53 #include "JITExceptions.h"
54 #include "JITToDFGDeferredCompilationCallback.h"
55 #include "JSAsyncFunction.h"
56 #include "JSAsyncGeneratorFunction.h"
57 #include "JSCInlines.h"
58 #include "JSGeneratorFunction.h"
59 #include "JSGlobalObjectFunctions.h"
60 #include "JSLexicalEnvironment.h"
61 #include "JSPropertyNameEnumerator.h"
62 #include "JSWithScope.h"
63 #include "ModuleProgramCodeBlock.h"
64 #include "ObjectConstructor.h"
65 #include "PolymorphicAccess.h"
66 #include "ProgramCodeBlock.h"
67 #include "PropertyName.h"
68 #include "RegExpObject.h"
69 #include "Repatch.h"
70 #include "ScopedArguments.h"
71 #include "ShadowChicken.h"
72 #include "StructureStubInfo.h"
73 #include "SuperSampler.h"
74 #include "TestRunnerUtils.h"
75 #include "ThunkGenerators.h"
76 #include "TypeProfilerLog.h"
77 #include "VMInlines.h"
78 #include <wtf/InlineASM.h>
79
80 namespace JSC {
81
82 extern "C" {
83
84 #if COMPILER(MSVC)
85 void * _ReturnAddress(void);
86 #pragma intrinsic(_ReturnAddress)
87
88 #define OUR_RETURN_ADDRESS _ReturnAddress()
89 #else
90 #define OUR_RETURN_ADDRESS __builtin_return_address(0)
91 #endif
92
93 #if ENABLE(OPCODE_SAMPLING)
94 #define CTI_SAMPLER vm->interpreter->sampler()
95 #else
96 #define CTI_SAMPLER 0
97 #endif
98
99
100 void JIT_OPERATION operationThrowStackOverflowError(ExecState* exec, CodeBlock* codeBlock)
101 {
102     // We pass in our own code block, because the callframe hasn't been populated.
103     VM* vm = codeBlock->vm();
104     auto scope = DECLARE_THROW_SCOPE(*vm);
105
106     EntryFrame* entryFrame = vm->topEntryFrame;
107     CallFrame* callerFrame = exec->callerFrame(entryFrame);
108     if (!callerFrame) {
109         callerFrame = exec;
110         entryFrame = vm->topEntryFrame;
111     }
112
113     NativeCallFrameTracerWithRestore tracer(vm, entryFrame, callerFrame);
114     throwStackOverflowError(callerFrame, scope);
115 }
116
117 #if ENABLE(WEBASSEMBLY)
118 void JIT_OPERATION operationThrowDivideError(ExecState* exec)
119 {
120     VM* vm = &exec->vm();
121     auto scope = DECLARE_THROW_SCOPE(*vm);
122
123     EntryFrame* entryFrame = vm->topEntryFrame;
124     CallFrame* callerFrame = exec->callerFrame(entryFrame);
125
126     NativeCallFrameTracerWithRestore tracer(vm, entryFrame, callerFrame);
127     ErrorHandlingScope errorScope(*vm);
128     throwException(callerFrame, scope, createError(callerFrame, ASCIILiteral("Division by zero or division overflow.")));
129 }
130
131 void JIT_OPERATION operationThrowOutOfBoundsAccessError(ExecState* exec)
132 {
133     VM* vm = &exec->vm();
134     auto scope = DECLARE_THROW_SCOPE(*vm);
135
136     EntryFrame* entryFrame = vm->topEntryFrame;
137     CallFrame* callerFrame = exec->callerFrame(entryFrame);
138
139     NativeCallFrameTracerWithRestore tracer(vm, entryFrame, callerFrame);
140     ErrorHandlingScope errorScope(*vm);
141     throwException(callerFrame, scope, createError(callerFrame, ASCIILiteral("Out-of-bounds access.")));
142 }
143 #endif
144
145 int32_t JIT_OPERATION operationCallArityCheck(ExecState* exec)
146 {
147     VM* vm = &exec->vm();
148     auto scope = DECLARE_THROW_SCOPE(*vm);
149
150     int32_t missingArgCount = CommonSlowPaths::arityCheckFor(exec, *vm, CodeForCall);
151     if (missingArgCount < 0) {
152         EntryFrame* entryFrame = vm->topEntryFrame;
153         CallFrame* callerFrame = exec->callerFrame(entryFrame);
154         NativeCallFrameTracerWithRestore tracer(vm, entryFrame, callerFrame);
155         throwStackOverflowError(callerFrame, scope);
156     }
157
158     return missingArgCount;
159 }
160
161 int32_t JIT_OPERATION operationConstructArityCheck(ExecState* exec)
162 {
163     VM* vm = &exec->vm();
164     auto scope = DECLARE_THROW_SCOPE(*vm);
165
166     int32_t missingArgCount = CommonSlowPaths::arityCheckFor(exec, *vm, CodeForConstruct);
167     if (missingArgCount < 0) {
168         EntryFrame* entryFrame = vm->topEntryFrame;
169         CallFrame* callerFrame = exec->callerFrame(entryFrame);
170         NativeCallFrameTracerWithRestore tracer(vm, entryFrame, callerFrame);
171         throwStackOverflowError(callerFrame, scope);
172     }
173
174     return missingArgCount;
175 }
176
177 EncodedJSValue JIT_OPERATION operationTryGetById(ExecState* exec, StructureStubInfo* stubInfo, EncodedJSValue base, UniquedStringImpl* uid)
178 {
179     VM* vm = &exec->vm();
180     NativeCallFrameTracer tracer(vm, exec);
181     Identifier ident = Identifier::fromUid(vm, uid);
182     stubInfo->tookSlowPath = true;
183
184     JSValue baseValue = JSValue::decode(base);
185     PropertySlot slot(baseValue, PropertySlot::InternalMethodType::VMInquiry);
186     baseValue.getPropertySlot(exec, ident, slot);
187
188     return JSValue::encode(slot.getPureResult());
189 }
190
191
192 EncodedJSValue JIT_OPERATION operationTryGetByIdGeneric(ExecState* exec, EncodedJSValue base, UniquedStringImpl* uid)
193 {
194     VM* vm = &exec->vm();
195     NativeCallFrameTracer tracer(vm, exec);
196     Identifier ident = Identifier::fromUid(vm, uid);
197
198     JSValue baseValue = JSValue::decode(base);
199     PropertySlot slot(baseValue, PropertySlot::InternalMethodType::VMInquiry);
200     baseValue.getPropertySlot(exec, ident, slot);
201
202     return JSValue::encode(slot.getPureResult());
203 }
204
205 EncodedJSValue JIT_OPERATION operationTryGetByIdOptimize(ExecState* exec, StructureStubInfo* stubInfo, EncodedJSValue base, UniquedStringImpl* uid)
206 {
207     VM* vm = &exec->vm();
208     NativeCallFrameTracer tracer(vm, exec);
209     auto scope = DECLARE_THROW_SCOPE(*vm);
210     Identifier ident = Identifier::fromUid(vm, uid);
211
212     JSValue baseValue = JSValue::decode(base);
213     PropertySlot slot(baseValue, PropertySlot::InternalMethodType::VMInquiry);
214
215     baseValue.getPropertySlot(exec, ident, slot);
216     RETURN_IF_EXCEPTION(scope, encodedJSValue());
217
218     if (stubInfo->considerCaching(exec->codeBlock(), baseValue.structureOrNull()) && !slot.isTaintedByOpaqueObject() && (slot.isCacheableValue() || slot.isCacheableGetter() || slot.isUnset()))
219         repatchGetByID(exec, baseValue, ident, slot, *stubInfo, GetByIDKind::Try);
220
221     return JSValue::encode(slot.getPureResult());
222 }
223
224 EncodedJSValue JIT_OPERATION operationGetById(ExecState* exec, StructureStubInfo* stubInfo, EncodedJSValue base, UniquedStringImpl* uid)
225 {
226     SuperSamplerScope superSamplerScope(false);
227     
228     VM* vm = &exec->vm();
229     NativeCallFrameTracer tracer(vm, exec);
230     
231     stubInfo->tookSlowPath = true;
232     
233     JSValue baseValue = JSValue::decode(base);
234     PropertySlot slot(baseValue, PropertySlot::InternalMethodType::Get);
235     Identifier ident = Identifier::fromUid(vm, uid);
236     
237     LOG_IC((ICEvent::OperationGetById, baseValue.classInfoOrNull(*vm), ident));
238     return JSValue::encode(baseValue.get(exec, ident, slot));
239 }
240
241 EncodedJSValue JIT_OPERATION operationGetByIdGeneric(ExecState* exec, EncodedJSValue base, UniquedStringImpl* uid)
242 {
243     SuperSamplerScope superSamplerScope(false);
244     
245     VM* vm = &exec->vm();
246     NativeCallFrameTracer tracer(vm, exec);
247     
248     JSValue baseValue = JSValue::decode(base);
249     PropertySlot slot(baseValue, PropertySlot::InternalMethodType::Get);
250     Identifier ident = Identifier::fromUid(vm, uid);
251     LOG_IC((ICEvent::OperationGetByIdGeneric, baseValue.classInfoOrNull(*vm), ident));
252     return JSValue::encode(baseValue.get(exec, ident, slot));
253 }
254
255 EncodedJSValue JIT_OPERATION operationGetByIdOptimize(ExecState* exec, StructureStubInfo* stubInfo, EncodedJSValue base, UniquedStringImpl* uid)
256 {
257     SuperSamplerScope superSamplerScope(false);
258     
259     VM* vm = &exec->vm();
260     NativeCallFrameTracer tracer(vm, exec);
261     Identifier ident = Identifier::fromUid(vm, uid);
262
263     JSValue baseValue = JSValue::decode(base);
264     LOG_IC((ICEvent::OperationGetByIdOptimize, baseValue.classInfoOrNull(*vm), ident));
265
266     return JSValue::encode(baseValue.getPropertySlot(exec, ident, [&] (bool found, PropertySlot& slot) -> JSValue {
267         if (stubInfo->considerCaching(exec->codeBlock(), baseValue.structureOrNull()))
268             repatchGetByID(exec, baseValue, ident, slot, *stubInfo, GetByIDKind::Normal);
269         return found ? slot.getValue(exec, ident) : jsUndefined();
270     }));
271 }
272
273 EncodedJSValue JIT_OPERATION operationGetByIdWithThisGeneric(ExecState* exec, StructureStubInfo* stubInfo, EncodedJSValue base, EncodedJSValue thisEncoded, UniquedStringImpl* uid)
274 {
275     SuperSamplerScope superSamplerScope(false);
276
277     VM* vm = &exec->vm();
278     NativeCallFrameTracer tracer(vm, exec);
279     Identifier ident = Identifier::fromUid(vm, uid);
280
281     stubInfo->tookSlowPath = true;
282
283     JSValue baseValue = JSValue::decode(base);
284     JSValue thisValue = JSValue::decode(thisEncoded);
285     PropertySlot slot(thisValue, PropertySlot::InternalMethodType::Get);
286
287     return JSValue::encode(baseValue.get(exec, ident, slot));
288 }
289
290 EncodedJSValue JIT_OPERATION operationGetByIdWithThisOptimize(ExecState* exec, StructureStubInfo* stubInfo, EncodedJSValue base, EncodedJSValue thisEncoded, UniquedStringImpl* uid)
291 {
292     SuperSamplerScope superSamplerScope(false);
293     
294     VM* vm = &exec->vm();
295     NativeCallFrameTracer tracer(vm, exec);
296     Identifier ident = Identifier::fromUid(vm, uid);
297
298     JSValue baseValue = JSValue::decode(base);
299     JSValue thisValue = JSValue::decode(thisEncoded);
300     LOG_IC((ICEvent::OperationGetByIdWithThisOptimize, baseValue.classInfoOrNull(*vm), ident));
301
302     PropertySlot slot(thisValue, PropertySlot::InternalMethodType::Get);
303     return JSValue::encode(baseValue.getPropertySlot(exec, ident, slot, [&] (bool found, PropertySlot& slot) -> JSValue {
304         if (stubInfo->considerCaching(exec->codeBlock(), baseValue.structureOrNull()))
305             repatchGetByID(exec, baseValue, ident, slot, *stubInfo, GetByIDKind::WithThis);
306         return found ? slot.getValue(exec, ident) : jsUndefined();
307     }));
308 }
309
310 EncodedJSValue JIT_OPERATION operationInOptimize(ExecState* exec, StructureStubInfo* stubInfo, JSCell* base, UniquedStringImpl* key)
311 {
312     SuperSamplerScope superSamplerScope(false);
313     
314     VM* vm = &exec->vm();
315     NativeCallFrameTracer tracer(vm, exec);
316     auto scope = DECLARE_THROW_SCOPE(*vm);
317
318     if (!base->isObject()) {
319         throwException(exec, scope, createInvalidInParameterError(exec, base));
320         return JSValue::encode(jsUndefined());
321     }
322     
323     AccessType accessType = static_cast<AccessType>(stubInfo->accessType);
324
325     Identifier ident = Identifier::fromUid(vm, key);
326     LOG_IC((ICEvent::OperationInOptimize, base->classInfo(*vm), ident));
327     PropertySlot slot(base, PropertySlot::InternalMethodType::HasProperty);
328     bool result = asObject(base)->getPropertySlot(exec, ident, slot);
329     RETURN_IF_EXCEPTION(scope, encodedJSValue());
330     
331     RELEASE_ASSERT(accessType == stubInfo->accessType);
332     
333     if (stubInfo->considerCaching(exec->codeBlock(), asObject(base)->structure()))
334         repatchIn(exec, base, ident, result, slot, *stubInfo);
335     
336     return JSValue::encode(jsBoolean(result));
337 }
338
339 EncodedJSValue JIT_OPERATION operationIn(ExecState* exec, StructureStubInfo* stubInfo, JSCell* base, UniquedStringImpl* key)
340 {
341     SuperSamplerScope superSamplerScope(false);
342     
343     VM* vm = &exec->vm();
344     NativeCallFrameTracer tracer(vm, exec);
345     auto scope = DECLARE_THROW_SCOPE(*vm);
346
347     stubInfo->tookSlowPath = true;
348
349     if (!base->isObject()) {
350         throwException(exec, scope, createInvalidInParameterError(exec, base));
351         return JSValue::encode(jsUndefined());
352     }
353
354     Identifier ident = Identifier::fromUid(vm, key);
355     LOG_IC((ICEvent::OperationIn, base->classInfo(*vm), ident));
356     scope.release();
357     return JSValue::encode(jsBoolean(asObject(base)->hasProperty(exec, ident)));
358 }
359
360 EncodedJSValue JIT_OPERATION operationGenericIn(ExecState* exec, JSCell* base, EncodedJSValue key)
361 {
362     SuperSamplerScope superSamplerScope(false);
363     
364     VM* vm = &exec->vm();
365     NativeCallFrameTracer tracer(vm, exec);
366
367     return JSValue::encode(jsBoolean(CommonSlowPaths::opIn(exec, base, JSValue::decode(key))));
368 }
369
370 void JIT_OPERATION operationPutByIdStrict(ExecState* exec, StructureStubInfo* stubInfo, EncodedJSValue encodedValue, EncodedJSValue encodedBase, UniquedStringImpl* uid)
371 {
372     SuperSamplerScope superSamplerScope(false);
373     
374     VM* vm = &exec->vm();
375     NativeCallFrameTracer tracer(vm, exec);
376     
377     stubInfo->tookSlowPath = true;
378     
379     JSValue baseValue = JSValue::decode(encodedBase);
380     Identifier ident = Identifier::fromUid(vm, uid);
381     LOG_IC((ICEvent::OperationPutByIdStrict, baseValue.classInfoOrNull(*vm), ident));
382
383     PutPropertySlot slot(baseValue, true, exec->codeBlock()->putByIdContext());
384     baseValue.putInline(exec, ident, JSValue::decode(encodedValue), slot);
385 }
386
387 void JIT_OPERATION operationPutByIdNonStrict(ExecState* exec, StructureStubInfo* stubInfo, EncodedJSValue encodedValue, EncodedJSValue encodedBase, UniquedStringImpl* uid)
388 {
389     SuperSamplerScope superSamplerScope(false);
390     
391     VM* vm = &exec->vm();
392     NativeCallFrameTracer tracer(vm, exec);
393     
394     stubInfo->tookSlowPath = true;
395     
396     JSValue baseValue = JSValue::decode(encodedBase);
397     Identifier ident = Identifier::fromUid(vm, uid);
398     LOG_IC((ICEvent::OperationPutByIdNonStrict, baseValue.classInfoOrNull(*vm), ident));
399     PutPropertySlot slot(baseValue, false, exec->codeBlock()->putByIdContext());
400     baseValue.putInline(exec, ident, JSValue::decode(encodedValue), slot);
401 }
402
403 void JIT_OPERATION operationPutByIdDirectStrict(ExecState* exec, StructureStubInfo* stubInfo, EncodedJSValue encodedValue, EncodedJSValue encodedBase, UniquedStringImpl* uid)
404 {
405     SuperSamplerScope superSamplerScope(false);
406     
407     VM* vm = &exec->vm();
408     NativeCallFrameTracer tracer(vm, exec);
409     
410     stubInfo->tookSlowPath = true;
411     
412     JSValue baseValue = JSValue::decode(encodedBase);
413     Identifier ident = Identifier::fromUid(vm, uid);
414     LOG_IC((ICEvent::OperationPutByIdDirectStrict, baseValue.classInfoOrNull(*vm), ident));
415     PutPropertySlot slot(baseValue, true, exec->codeBlock()->putByIdContext());
416     asObject(baseValue)->putDirect(*vm, ident, JSValue::decode(encodedValue), slot);
417 }
418
419 void JIT_OPERATION operationPutByIdDirectNonStrict(ExecState* exec, StructureStubInfo* stubInfo, EncodedJSValue encodedValue, EncodedJSValue encodedBase, UniquedStringImpl* uid)
420 {
421     SuperSamplerScope superSamplerScope(false);
422     
423     VM* vm = &exec->vm();
424     NativeCallFrameTracer tracer(vm, exec);
425     
426     stubInfo->tookSlowPath = true;
427     
428     JSValue baseValue = JSValue::decode(encodedBase);
429     Identifier ident = Identifier::fromUid(vm, uid);
430     LOG_IC((ICEvent::OperationPutByIdDirectNonStrict, baseValue.classInfoOrNull(*vm), ident));
431     PutPropertySlot slot(baseValue, false, exec->codeBlock()->putByIdContext());
432     asObject(baseValue)->putDirect(*vm, ident, JSValue::decode(encodedValue), slot);
433 }
434
435 void JIT_OPERATION operationPutByIdStrictOptimize(ExecState* exec, StructureStubInfo* stubInfo, EncodedJSValue encodedValue, EncodedJSValue encodedBase, UniquedStringImpl* uid)
436 {
437     SuperSamplerScope superSamplerScope(false);
438     
439     VM* vm = &exec->vm();
440     NativeCallFrameTracer tracer(vm, exec);
441     auto scope = DECLARE_THROW_SCOPE(*vm);
442
443     Identifier ident = Identifier::fromUid(vm, uid);
444     AccessType accessType = static_cast<AccessType>(stubInfo->accessType);
445
446     JSValue value = JSValue::decode(encodedValue);
447     JSValue baseValue = JSValue::decode(encodedBase);
448     LOG_IC((ICEvent::OperationPutByIdStrictOptimize, baseValue.classInfoOrNull(*vm), ident));
449     CodeBlock* codeBlock = exec->codeBlock();
450     PutPropertySlot slot(baseValue, true, codeBlock->putByIdContext());
451
452     Structure* structure = baseValue.isCell() ? baseValue.asCell()->structure(*vm) : nullptr;
453     baseValue.putInline(exec, ident, value, slot);
454     RETURN_IF_EXCEPTION(scope, void());
455
456     if (accessType != static_cast<AccessType>(stubInfo->accessType))
457         return;
458     
459     if (stubInfo->considerCaching(codeBlock, structure))
460         repatchPutByID(exec, baseValue, structure, ident, slot, *stubInfo, NotDirect);
461 }
462
463 void JIT_OPERATION operationPutByIdNonStrictOptimize(ExecState* exec, StructureStubInfo* stubInfo, EncodedJSValue encodedValue, EncodedJSValue encodedBase, UniquedStringImpl* uid)
464 {
465     SuperSamplerScope superSamplerScope(false);
466     
467     VM* vm = &exec->vm();
468     NativeCallFrameTracer tracer(vm, exec);
469     auto scope = DECLARE_THROW_SCOPE(*vm);
470
471     Identifier ident = Identifier::fromUid(vm, uid);
472     AccessType accessType = static_cast<AccessType>(stubInfo->accessType);
473
474     JSValue value = JSValue::decode(encodedValue);
475     JSValue baseValue = JSValue::decode(encodedBase);
476     LOG_IC((ICEvent::OperationPutByIdNonStrictOptimize, baseValue.classInfoOrNull(*vm), ident));
477     CodeBlock* codeBlock = exec->codeBlock();
478     PutPropertySlot slot(baseValue, false, codeBlock->putByIdContext());
479
480     Structure* structure = baseValue.isCell() ? baseValue.asCell()->structure(*vm) : nullptr;    
481     baseValue.putInline(exec, ident, value, slot);
482     RETURN_IF_EXCEPTION(scope, void());
483
484     if (accessType != static_cast<AccessType>(stubInfo->accessType))
485         return;
486     
487     if (stubInfo->considerCaching(codeBlock, structure))
488         repatchPutByID(exec, baseValue, structure, ident, slot, *stubInfo, NotDirect);
489 }
490
491 void JIT_OPERATION operationPutByIdDirectStrictOptimize(ExecState* exec, StructureStubInfo* stubInfo, EncodedJSValue encodedValue, EncodedJSValue encodedBase, UniquedStringImpl* uid)
492 {
493     SuperSamplerScope superSamplerScope(false);
494     
495     VM* vm = &exec->vm();
496     NativeCallFrameTracer tracer(vm, exec);
497     
498     Identifier ident = Identifier::fromUid(vm, uid);
499     AccessType accessType = static_cast<AccessType>(stubInfo->accessType);
500
501     JSValue value = JSValue::decode(encodedValue);
502     JSObject* baseObject = asObject(JSValue::decode(encodedBase));
503     LOG_IC((ICEvent::OperationPutByIdDirectStrictOptimize, baseObject->classInfo(*vm), ident));
504     CodeBlock* codeBlock = exec->codeBlock();
505     PutPropertySlot slot(baseObject, true, codeBlock->putByIdContext());
506     
507     Structure* structure = baseObject->structure(*vm);
508     baseObject->putDirect(*vm, ident, value, slot);
509     
510     if (accessType != static_cast<AccessType>(stubInfo->accessType))
511         return;
512     
513     if (stubInfo->considerCaching(codeBlock, structure))
514         repatchPutByID(exec, baseObject, structure, ident, slot, *stubInfo, Direct);
515 }
516
517 void JIT_OPERATION operationPutByIdDirectNonStrictOptimize(ExecState* exec, StructureStubInfo* stubInfo, EncodedJSValue encodedValue, EncodedJSValue encodedBase, UniquedStringImpl* uid)
518 {
519     SuperSamplerScope superSamplerScope(false);
520     
521     VM* vm = &exec->vm();
522     NativeCallFrameTracer tracer(vm, exec);
523     
524     Identifier ident = Identifier::fromUid(vm, uid);
525     AccessType accessType = static_cast<AccessType>(stubInfo->accessType);
526
527     JSValue value = JSValue::decode(encodedValue);
528     JSObject* baseObject = asObject(JSValue::decode(encodedBase));
529     LOG_IC((ICEvent::OperationPutByIdDirectNonStrictOptimize, baseObject->classInfo(*vm), ident));
530     CodeBlock* codeBlock = exec->codeBlock();
531     PutPropertySlot slot(baseObject, false, codeBlock->putByIdContext());
532     
533     Structure* structure = baseObject->structure(*vm);
534     baseObject->putDirect(*vm, ident, value, slot);
535     
536     if (accessType != static_cast<AccessType>(stubInfo->accessType))
537         return;
538     
539     if (stubInfo->considerCaching(codeBlock, structure))
540         repatchPutByID(exec, baseObject, structure, ident, slot, *stubInfo, Direct);
541 }
542
543 ALWAYS_INLINE static bool isStringOrSymbol(JSValue value)
544 {
545     return value.isString() || value.isSymbol();
546 }
547
548 static void putByVal(CallFrame* callFrame, JSValue baseValue, JSValue subscript, JSValue value, ByValInfo* byValInfo)
549 {
550     VM& vm = callFrame->vm();
551     auto scope = DECLARE_THROW_SCOPE(vm);
552     if (LIKELY(subscript.isUInt32())) {
553         byValInfo->tookSlowPath = true;
554         uint32_t i = subscript.asUInt32();
555         if (baseValue.isObject()) {
556             JSObject* object = asObject(baseValue);
557             if (object->canSetIndexQuickly(i)) {
558                 object->setIndexQuickly(vm, i, value);
559                 return;
560             }
561
562             // FIXME: This will make us think that in-bounds typed array accesses are actually
563             // out-of-bounds.
564             // https://bugs.webkit.org/show_bug.cgi?id=149886
565             byValInfo->arrayProfile->setOutOfBounds();
566             scope.release();
567             object->methodTable(vm)->putByIndex(object, callFrame, i, value, callFrame->codeBlock()->isStrictMode());
568             return;
569         }
570
571         scope.release();
572         baseValue.putByIndex(callFrame, i, value, callFrame->codeBlock()->isStrictMode());
573         return;
574     }
575
576     auto property = subscript.toPropertyKey(callFrame);
577     // Don't put to an object if toString threw an exception.
578     RETURN_IF_EXCEPTION(scope, void());
579
580     if (byValInfo->stubInfo && (!isStringOrSymbol(subscript) || byValInfo->cachedId != property))
581         byValInfo->tookSlowPath = true;
582
583     scope.release();
584     PutPropertySlot slot(baseValue, callFrame->codeBlock()->isStrictMode());
585     baseValue.putInline(callFrame, property, value, slot);
586 }
587
588 static void directPutByVal(CallFrame* callFrame, JSObject* baseObject, JSValue subscript, JSValue value, ByValInfo* byValInfo)
589 {
590     VM& vm = callFrame->vm();
591     auto scope = DECLARE_THROW_SCOPE(vm);
592     bool isStrictMode = callFrame->codeBlock()->isStrictMode();
593     if (LIKELY(subscript.isUInt32())) {
594         // Despite its name, JSValue::isUInt32 will return true only for positive boxed int32_t; all those values are valid array indices.
595         byValInfo->tookSlowPath = true;
596         uint32_t index = subscript.asUInt32();
597         ASSERT(isIndex(index));
598
599         switch (baseObject->indexingType()) {
600         case ALL_INT32_INDEXING_TYPES:
601         case ALL_DOUBLE_INDEXING_TYPES:
602         case ALL_CONTIGUOUS_INDEXING_TYPES:
603         case ALL_ARRAY_STORAGE_INDEXING_TYPES:
604             if (index < baseObject->butterfly()->vectorLength())
605                 break;
606             FALLTHROUGH;
607         default:
608             byValInfo->arrayProfile->setOutOfBounds();
609             break;
610         }
611
612         scope.release();
613         baseObject->putDirectIndex(callFrame, index, value, 0, isStrictMode ? PutDirectIndexShouldThrow : PutDirectIndexShouldNotThrow);
614         return;
615     }
616
617     if (subscript.isDouble()) {
618         double subscriptAsDouble = subscript.asDouble();
619         uint32_t subscriptAsUInt32 = static_cast<uint32_t>(subscriptAsDouble);
620         if (subscriptAsDouble == subscriptAsUInt32 && isIndex(subscriptAsUInt32)) {
621             byValInfo->tookSlowPath = true;
622             scope.release();
623             baseObject->putDirectIndex(callFrame, subscriptAsUInt32, value, 0, isStrictMode ? PutDirectIndexShouldThrow : PutDirectIndexShouldNotThrow);
624             return;
625         }
626     }
627
628     // Don't put to an object if toString threw an exception.
629     auto property = subscript.toPropertyKey(callFrame);
630     RETURN_IF_EXCEPTION(scope, void());
631
632     if (std::optional<uint32_t> index = parseIndex(property)) {
633         byValInfo->tookSlowPath = true;
634         scope.release();
635         baseObject->putDirectIndex(callFrame, index.value(), value, 0, isStrictMode ? PutDirectIndexShouldThrow : PutDirectIndexShouldNotThrow);
636         return;
637     }
638
639     if (byValInfo->stubInfo && (!isStringOrSymbol(subscript) || byValInfo->cachedId != property))
640         byValInfo->tookSlowPath = true;
641
642     PutPropertySlot slot(baseObject, isStrictMode);
643     baseObject->putDirect(vm, property, value, slot);
644 }
645
646 enum class OptimizationResult {
647     NotOptimized,
648     SeenOnce,
649     Optimized,
650     GiveUp,
651 };
652
653 static OptimizationResult tryPutByValOptimize(ExecState* exec, JSValue baseValue, JSValue subscript, ByValInfo* byValInfo, ReturnAddressPtr returnAddress)
654 {
655     // See if it's worth optimizing at all.
656     OptimizationResult optimizationResult = OptimizationResult::NotOptimized;
657
658     VM& vm = exec->vm();
659
660     if (baseValue.isObject() && subscript.isInt32()) {
661         JSObject* object = asObject(baseValue);
662
663         ASSERT(exec->bytecodeOffset());
664         ASSERT(!byValInfo->stubRoutine);
665
666         Structure* structure = object->structure(vm);
667         if (hasOptimizableIndexing(structure)) {
668             // Attempt to optimize.
669             JITArrayMode arrayMode = jitArrayModeForStructure(structure);
670             if (jitArrayModePermitsPut(arrayMode) && arrayMode != byValInfo->arrayMode) {
671                 CodeBlock* codeBlock = exec->codeBlock();
672                 ConcurrentJSLocker locker(codeBlock->m_lock);
673                 byValInfo->arrayProfile->computeUpdatedPrediction(locker, codeBlock, structure);
674
675                 JIT::compilePutByVal(&vm, codeBlock, byValInfo, returnAddress, arrayMode);
676                 optimizationResult = OptimizationResult::Optimized;
677             }
678         }
679
680         // If we failed to patch and we have some object that intercepts indexed get, then don't even wait until 10 times.
681         if (optimizationResult != OptimizationResult::Optimized && object->structure(vm)->typeInfo().interceptsGetOwnPropertySlotByIndexEvenWhenLengthIsNotZero())
682             optimizationResult = OptimizationResult::GiveUp;
683     }
684
685     if (baseValue.isObject() && isStringOrSymbol(subscript)) {
686         const Identifier propertyName = subscript.toPropertyKey(exec);
687         if (subscript.isSymbol() || !parseIndex(propertyName)) {
688             ASSERT(exec->bytecodeOffset());
689             ASSERT(!byValInfo->stubRoutine);
690             if (byValInfo->seen) {
691                 if (byValInfo->cachedId == propertyName) {
692                     JIT::compilePutByValWithCachedId(&vm, exec->codeBlock(), byValInfo, returnAddress, NotDirect, propertyName);
693                     optimizationResult = OptimizationResult::Optimized;
694                 } else {
695                     // Seem like a generic property access site.
696                     optimizationResult = OptimizationResult::GiveUp;
697                 }
698             } else {
699                 CodeBlock* codeBlock = exec->codeBlock();
700                 ConcurrentJSLocker locker(codeBlock->m_lock);
701                 byValInfo->seen = true;
702                 byValInfo->cachedId = propertyName;
703                 if (subscript.isSymbol())
704                     byValInfo->cachedSymbol.set(vm, codeBlock, asSymbol(subscript));
705                 optimizationResult = OptimizationResult::SeenOnce;
706             }
707         }
708     }
709
710     if (optimizationResult != OptimizationResult::Optimized && optimizationResult != OptimizationResult::SeenOnce) {
711         // If we take slow path more than 10 times without patching then make sure we
712         // never make that mistake again. For cases where we see non-index-intercepting
713         // objects, this gives 10 iterations worth of opportunity for us to observe
714         // that the put_by_val may be polymorphic. We count up slowPathCount even if
715         // the result is GiveUp.
716         if (++byValInfo->slowPathCount >= 10)
717             optimizationResult = OptimizationResult::GiveUp;
718     }
719
720     return optimizationResult;
721 }
722
723 void JIT_OPERATION operationPutByValOptimize(ExecState* exec, EncodedJSValue encodedBaseValue, EncodedJSValue encodedSubscript, EncodedJSValue encodedValue, ByValInfo* byValInfo)
724 {
725     VM& vm = exec->vm();
726     NativeCallFrameTracer tracer(&vm, exec);
727
728     JSValue baseValue = JSValue::decode(encodedBaseValue);
729     JSValue subscript = JSValue::decode(encodedSubscript);
730     JSValue value = JSValue::decode(encodedValue);
731     if (tryPutByValOptimize(exec, baseValue, subscript, byValInfo, ReturnAddressPtr(OUR_RETURN_ADDRESS)) == OptimizationResult::GiveUp) {
732         // Don't ever try to optimize.
733         byValInfo->tookSlowPath = true;
734         ctiPatchCallByReturnAddress(ReturnAddressPtr(OUR_RETURN_ADDRESS), FunctionPtr(operationPutByValGeneric));
735     }
736     putByVal(exec, baseValue, subscript, value, byValInfo);
737 }
738
739 static OptimizationResult tryDirectPutByValOptimize(ExecState* exec, JSObject* object, JSValue subscript, ByValInfo* byValInfo, ReturnAddressPtr returnAddress)
740 {
741     // See if it's worth optimizing at all.
742     OptimizationResult optimizationResult = OptimizationResult::NotOptimized;
743
744     VM& vm = exec->vm();
745
746     if (subscript.isInt32()) {
747         ASSERT(exec->bytecodeOffset());
748         ASSERT(!byValInfo->stubRoutine);
749
750         Structure* structure = object->structure(vm);
751         if (hasOptimizableIndexing(structure)) {
752             // Attempt to optimize.
753             JITArrayMode arrayMode = jitArrayModeForStructure(structure);
754             if (jitArrayModePermitsPutDirect(arrayMode) && arrayMode != byValInfo->arrayMode) {
755                 CodeBlock* codeBlock = exec->codeBlock();
756                 ConcurrentJSLocker locker(codeBlock->m_lock);
757                 byValInfo->arrayProfile->computeUpdatedPrediction(locker, codeBlock, structure);
758
759                 JIT::compileDirectPutByVal(&vm, codeBlock, byValInfo, returnAddress, arrayMode);
760                 optimizationResult = OptimizationResult::Optimized;
761             }
762         }
763
764         // If we failed to patch and we have some object that intercepts indexed get, then don't even wait until 10 times.
765         if (optimizationResult != OptimizationResult::Optimized && object->structure(vm)->typeInfo().interceptsGetOwnPropertySlotByIndexEvenWhenLengthIsNotZero())
766             optimizationResult = OptimizationResult::GiveUp;
767     } else if (isStringOrSymbol(subscript)) {
768         const Identifier propertyName = subscript.toPropertyKey(exec);
769         if (subscript.isSymbol() || !parseIndex(propertyName)) {
770             ASSERT(exec->bytecodeOffset());
771             ASSERT(!byValInfo->stubRoutine);
772             if (byValInfo->seen) {
773                 if (byValInfo->cachedId == propertyName) {
774                     JIT::compilePutByValWithCachedId(&vm, exec->codeBlock(), byValInfo, returnAddress, Direct, propertyName);
775                     optimizationResult = OptimizationResult::Optimized;
776                 } else {
777                     // Seem like a generic property access site.
778                     optimizationResult = OptimizationResult::GiveUp;
779                 }
780             } else {
781                 CodeBlock* codeBlock = exec->codeBlock();
782                 ConcurrentJSLocker locker(codeBlock->m_lock);
783                 byValInfo->seen = true;
784                 byValInfo->cachedId = propertyName;
785                 if (subscript.isSymbol())
786                     byValInfo->cachedSymbol.set(vm, codeBlock, asSymbol(subscript));
787                 optimizationResult = OptimizationResult::SeenOnce;
788             }
789         }
790     }
791
792     if (optimizationResult != OptimizationResult::Optimized && optimizationResult != OptimizationResult::SeenOnce) {
793         // If we take slow path more than 10 times without patching then make sure we
794         // never make that mistake again. For cases where we see non-index-intercepting
795         // objects, this gives 10 iterations worth of opportunity for us to observe
796         // that the get_by_val may be polymorphic. We count up slowPathCount even if
797         // the result is GiveUp.
798         if (++byValInfo->slowPathCount >= 10)
799             optimizationResult = OptimizationResult::GiveUp;
800     }
801
802     return optimizationResult;
803 }
804
805 void JIT_OPERATION operationDirectPutByValOptimize(ExecState* exec, EncodedJSValue encodedBaseValue, EncodedJSValue encodedSubscript, EncodedJSValue encodedValue, ByValInfo* byValInfo)
806 {
807     VM& vm = exec->vm();
808     NativeCallFrameTracer tracer(&vm, exec);
809
810     JSValue baseValue = JSValue::decode(encodedBaseValue);
811     JSValue subscript = JSValue::decode(encodedSubscript);
812     JSValue value = JSValue::decode(encodedValue);
813     RELEASE_ASSERT(baseValue.isObject());
814     JSObject* object = asObject(baseValue);
815     if (tryDirectPutByValOptimize(exec, object, subscript, byValInfo, ReturnAddressPtr(OUR_RETURN_ADDRESS)) == OptimizationResult::GiveUp) {
816         // Don't ever try to optimize.
817         byValInfo->tookSlowPath = true;
818         ctiPatchCallByReturnAddress(ReturnAddressPtr(OUR_RETURN_ADDRESS), FunctionPtr(operationDirectPutByValGeneric));
819     }
820
821     directPutByVal(exec, object, subscript, value, byValInfo);
822 }
823
824 void JIT_OPERATION operationPutByValGeneric(ExecState* exec, EncodedJSValue encodedBaseValue, EncodedJSValue encodedSubscript, EncodedJSValue encodedValue, ByValInfo* byValInfo)
825 {
826     VM& vm = exec->vm();
827     NativeCallFrameTracer tracer(&vm, exec);
828     
829     JSValue baseValue = JSValue::decode(encodedBaseValue);
830     JSValue subscript = JSValue::decode(encodedSubscript);
831     JSValue value = JSValue::decode(encodedValue);
832
833     putByVal(exec, baseValue, subscript, value, byValInfo);
834 }
835
836
837 void JIT_OPERATION operationDirectPutByValGeneric(ExecState* exec, EncodedJSValue encodedBaseValue, EncodedJSValue encodedSubscript, EncodedJSValue encodedValue, ByValInfo* byValInfo)
838 {
839     VM& vm = exec->vm();
840     NativeCallFrameTracer tracer(&vm, exec);
841     
842     JSValue baseValue = JSValue::decode(encodedBaseValue);
843     JSValue subscript = JSValue::decode(encodedSubscript);
844     JSValue value = JSValue::decode(encodedValue);
845     RELEASE_ASSERT(baseValue.isObject());
846     directPutByVal(exec, asObject(baseValue), subscript, value, byValInfo);
847 }
848
849 EncodedJSValue JIT_OPERATION operationCallEval(ExecState* exec, ExecState* execCallee)
850 {
851     VM* vm = &exec->vm();
852     auto scope = DECLARE_THROW_SCOPE(*vm);
853
854     execCallee->setCodeBlock(0);
855     
856     if (!isHostFunction(execCallee->guaranteedJSValueCallee(), globalFuncEval))
857         return JSValue::encode(JSValue());
858
859     JSValue result = eval(execCallee);
860     RETURN_IF_EXCEPTION(scope, encodedJSValue());
861     
862     return JSValue::encode(result);
863 }
864
865 static SlowPathReturnType handleHostCall(ExecState* execCallee, JSValue callee, CallLinkInfo* callLinkInfo)
866 {
867     ExecState* exec = execCallee->callerFrame();
868     VM* vm = &exec->vm();
869     auto scope = DECLARE_THROW_SCOPE(*vm);
870
871     execCallee->setCodeBlock(0);
872
873     if (callLinkInfo->specializationKind() == CodeForCall) {
874         CallData callData;
875         CallType callType = getCallData(callee, callData);
876     
877         ASSERT(callType != CallType::JS);
878     
879         if (callType == CallType::Host) {
880             NativeCallFrameTracer tracer(vm, execCallee);
881             execCallee->setCallee(asObject(callee));
882             vm->hostCallReturnValue = JSValue::decode(callData.native.function(execCallee));
883             if (UNLIKELY(scope.exception())) {
884                 return encodeResult(
885                     vm->getCTIStub(throwExceptionFromCallSlowPathGenerator).code().executableAddress(),
886                     reinterpret_cast<void*>(KeepTheFrame));
887             }
888
889             return encodeResult(
890                 bitwise_cast<void*>(getHostCallReturnValue),
891                 reinterpret_cast<void*>(callLinkInfo->callMode() == CallMode::Tail ? ReuseTheFrame : KeepTheFrame));
892         }
893     
894         ASSERT(callType == CallType::None);
895         throwException(exec, scope, createNotAFunctionError(exec, callee));
896         return encodeResult(
897             vm->getCTIStub(throwExceptionFromCallSlowPathGenerator).code().executableAddress(),
898             reinterpret_cast<void*>(KeepTheFrame));
899     }
900
901     ASSERT(callLinkInfo->specializationKind() == CodeForConstruct);
902     
903     ConstructData constructData;
904     ConstructType constructType = getConstructData(callee, constructData);
905     
906     ASSERT(constructType != ConstructType::JS);
907     
908     if (constructType == ConstructType::Host) {
909         NativeCallFrameTracer tracer(vm, execCallee);
910         execCallee->setCallee(asObject(callee));
911         vm->hostCallReturnValue = JSValue::decode(constructData.native.function(execCallee));
912         if (UNLIKELY(scope.exception())) {
913             return encodeResult(
914                 vm->getCTIStub(throwExceptionFromCallSlowPathGenerator).code().executableAddress(),
915                 reinterpret_cast<void*>(KeepTheFrame));
916         }
917
918         return encodeResult(bitwise_cast<void*>(getHostCallReturnValue), reinterpret_cast<void*>(KeepTheFrame));
919     }
920     
921     ASSERT(constructType == ConstructType::None);
922     throwException(exec, scope, createNotAConstructorError(exec, callee));
923     return encodeResult(
924         vm->getCTIStub(throwExceptionFromCallSlowPathGenerator).code().executableAddress(),
925         reinterpret_cast<void*>(KeepTheFrame));
926 }
927
928 SlowPathReturnType JIT_OPERATION operationLinkCall(ExecState* execCallee, CallLinkInfo* callLinkInfo)
929 {
930     ExecState* exec = execCallee->callerFrame();
931     VM* vm = &exec->vm();
932     auto throwScope = DECLARE_THROW_SCOPE(*vm);
933
934     CodeSpecializationKind kind = callLinkInfo->specializationKind();
935     NativeCallFrameTracer tracer(vm, exec);
936     
937     RELEASE_ASSERT(!callLinkInfo->isDirect());
938     
939     JSValue calleeAsValue = execCallee->guaranteedJSValueCallee();
940     JSCell* calleeAsFunctionCell = getJSFunction(calleeAsValue);
941     if (!calleeAsFunctionCell) {
942         if (calleeAsValue.isCell() && calleeAsValue.asCell()->type() == InternalFunctionType) {
943             MacroAssemblerCodePtr codePtr = vm->getCTIInternalFunctionTrampolineFor(kind);
944             RELEASE_ASSERT(!!codePtr);
945
946             if (!callLinkInfo->seenOnce())
947                 callLinkInfo->setSeen();
948             else
949                 linkFor(execCallee, *callLinkInfo, nullptr, asObject(calleeAsValue), codePtr);
950
951             return encodeResult(codePtr.executableAddress(), reinterpret_cast<void*>(callLinkInfo->callMode() == CallMode::Tail ? ReuseTheFrame : KeepTheFrame));
952         }
953         throwScope.release();
954         return handleHostCall(execCallee, calleeAsValue, callLinkInfo);
955     }
956
957     JSFunction* callee = jsCast<JSFunction*>(calleeAsFunctionCell);
958     JSScope* scope = callee->scopeUnchecked();
959     ExecutableBase* executable = callee->executable();
960
961     MacroAssemblerCodePtr codePtr;
962     CodeBlock* codeBlock = nullptr;
963     if (executable->isHostFunction()) {
964         codePtr = executable->entrypointFor(kind, MustCheckArity);
965     } else {
966         FunctionExecutable* functionExecutable = static_cast<FunctionExecutable*>(executable);
967
968         if (!isCall(kind) && functionExecutable->constructAbility() == ConstructAbility::CannotConstruct) {
969             throwException(exec, throwScope, createNotAConstructorError(exec, callee));
970             return encodeResult(
971                 vm->getCTIStub(throwExceptionFromCallSlowPathGenerator).code().executableAddress(),
972                 reinterpret_cast<void*>(KeepTheFrame));
973         }
974
975         CodeBlock** codeBlockSlot = execCallee->addressOfCodeBlock();
976         JSObject* error = functionExecutable->prepareForExecution<FunctionExecutable>(*vm, callee, scope, kind, *codeBlockSlot);
977         EXCEPTION_ASSERT(throwScope.exception() == reinterpret_cast<Exception*>(error));
978         if (error) {
979             return encodeResult(
980                 vm->getCTIStub(throwExceptionFromCallSlowPathGenerator).code().executableAddress(),
981                 reinterpret_cast<void*>(KeepTheFrame));
982         }
983         codeBlock = *codeBlockSlot;
984         ArityCheckMode arity;
985         if (execCallee->argumentCountIncludingThis() < static_cast<size_t>(codeBlock->numParameters()) || callLinkInfo->isVarargs())
986             arity = MustCheckArity;
987         else
988             arity = ArityCheckNotRequired;
989         codePtr = functionExecutable->entrypointFor(kind, arity);
990     }
991     if (!callLinkInfo->seenOnce())
992         callLinkInfo->setSeen();
993     else
994         linkFor(execCallee, *callLinkInfo, codeBlock, callee, codePtr);
995     
996     return encodeResult(codePtr.executableAddress(), reinterpret_cast<void*>(callLinkInfo->callMode() == CallMode::Tail ? ReuseTheFrame : KeepTheFrame));
997 }
998
999 void JIT_OPERATION operationLinkDirectCall(ExecState* exec, CallLinkInfo* callLinkInfo, JSFunction* callee)
1000 {
1001     VM* vm = &exec->vm();
1002     auto throwScope = DECLARE_THROW_SCOPE(*vm);
1003
1004     CodeSpecializationKind kind = callLinkInfo->specializationKind();
1005     NativeCallFrameTracer tracer(vm, exec);
1006     
1007     RELEASE_ASSERT(callLinkInfo->isDirect());
1008     
1009     // This would happen if the executable died during GC but the CodeBlock did not die. That should
1010     // not happen because the CodeBlock should have a weak reference to any executable it uses for
1011     // this purpose.
1012     RELEASE_ASSERT(callLinkInfo->executable());
1013     
1014     // Having a CodeBlock indicates that this is linked. We shouldn't be taking this path if it's
1015     // linked.
1016     RELEASE_ASSERT(!callLinkInfo->codeBlock());
1017     
1018     // We just don't support this yet.
1019     RELEASE_ASSERT(!callLinkInfo->isVarargs());
1020     
1021     ExecutableBase* executable = callLinkInfo->executable();
1022     RELEASE_ASSERT(callee->executable() == callLinkInfo->executable());
1023
1024     JSScope* scope = callee->scopeUnchecked();
1025
1026     MacroAssemblerCodePtr codePtr;
1027     CodeBlock* codeBlock = nullptr;
1028     if (executable->isHostFunction())
1029         codePtr = executable->entrypointFor(kind, MustCheckArity);
1030     else {
1031         FunctionExecutable* functionExecutable = static_cast<FunctionExecutable*>(executable);
1032
1033         RELEASE_ASSERT(isCall(kind) || functionExecutable->constructAbility() != ConstructAbility::CannotConstruct);
1034         
1035         JSObject* error = functionExecutable->prepareForExecution<FunctionExecutable>(*vm, callee, scope, kind, codeBlock);
1036         EXCEPTION_ASSERT_UNUSED(throwScope, throwScope.exception() == reinterpret_cast<Exception*>(error));
1037         if (error)
1038             return;
1039         ArityCheckMode arity;
1040         unsigned argumentStackSlots = callLinkInfo->maxNumArguments();
1041         if (argumentStackSlots < static_cast<size_t>(codeBlock->numParameters()))
1042             arity = MustCheckArity;
1043         else
1044             arity = ArityCheckNotRequired;
1045         codePtr = functionExecutable->entrypointFor(kind, arity);
1046     }
1047     
1048     linkDirectFor(exec, *callLinkInfo, codeBlock, codePtr);
1049 }
1050
1051 inline SlowPathReturnType virtualForWithFunction(
1052     ExecState* execCallee, CallLinkInfo* callLinkInfo, JSCell*& calleeAsFunctionCell)
1053 {
1054     ExecState* exec = execCallee->callerFrame();
1055     VM* vm = &exec->vm();
1056     auto throwScope = DECLARE_THROW_SCOPE(*vm);
1057
1058     CodeSpecializationKind kind = callLinkInfo->specializationKind();
1059     NativeCallFrameTracer tracer(vm, exec);
1060
1061     JSValue calleeAsValue = execCallee->guaranteedJSValueCallee();
1062     calleeAsFunctionCell = getJSFunction(calleeAsValue);
1063     if (UNLIKELY(!calleeAsFunctionCell)) {
1064         if (calleeAsValue.isCell() && calleeAsValue.asCell()->type() == InternalFunctionType) {
1065             MacroAssemblerCodePtr codePtr = vm->getCTIInternalFunctionTrampolineFor(kind);
1066             ASSERT(!!codePtr);
1067             return encodeResult(codePtr.executableAddress(), reinterpret_cast<void*>(callLinkInfo->callMode() == CallMode::Tail ? ReuseTheFrame : KeepTheFrame));
1068         }
1069         throwScope.release();
1070         return handleHostCall(execCallee, calleeAsValue, callLinkInfo);
1071     }
1072     
1073     JSFunction* function = jsCast<JSFunction*>(calleeAsFunctionCell);
1074     JSScope* scope = function->scopeUnchecked();
1075     ExecutableBase* executable = function->executable();
1076     if (UNLIKELY(!executable->hasJITCodeFor(kind))) {
1077         FunctionExecutable* functionExecutable = static_cast<FunctionExecutable*>(executable);
1078
1079         if (!isCall(kind) && functionExecutable->constructAbility() == ConstructAbility::CannotConstruct) {
1080             throwException(exec, throwScope, createNotAConstructorError(exec, function));
1081             return encodeResult(
1082                 vm->getCTIStub(throwExceptionFromCallSlowPathGenerator).code().executableAddress(),
1083                 reinterpret_cast<void*>(KeepTheFrame));
1084         }
1085
1086         CodeBlock** codeBlockSlot = execCallee->addressOfCodeBlock();
1087         JSObject* error = functionExecutable->prepareForExecution<FunctionExecutable>(*vm, function, scope, kind, *codeBlockSlot);
1088         EXCEPTION_ASSERT(throwScope.exception() == reinterpret_cast<Exception*>(error));
1089         if (error) {
1090             return encodeResult(
1091                 vm->getCTIStub(throwExceptionFromCallSlowPathGenerator).code().executableAddress(),
1092                 reinterpret_cast<void*>(KeepTheFrame));
1093         }
1094     }
1095     return encodeResult(executable->entrypointFor(
1096         kind, MustCheckArity).executableAddress(),
1097         reinterpret_cast<void*>(callLinkInfo->callMode() == CallMode::Tail ? ReuseTheFrame : KeepTheFrame));
1098 }
1099
1100 SlowPathReturnType JIT_OPERATION operationLinkPolymorphicCall(ExecState* execCallee, CallLinkInfo* callLinkInfo)
1101 {
1102     ASSERT(callLinkInfo->specializationKind() == CodeForCall);
1103     JSCell* calleeAsFunctionCell;
1104     SlowPathReturnType result = virtualForWithFunction(execCallee, callLinkInfo, calleeAsFunctionCell);
1105
1106     linkPolymorphicCall(execCallee, *callLinkInfo, CallVariant(calleeAsFunctionCell));
1107     
1108     return result;
1109 }
1110
1111 SlowPathReturnType JIT_OPERATION operationVirtualCall(ExecState* execCallee, CallLinkInfo* callLinkInfo)
1112 {
1113     JSCell* calleeAsFunctionCellIgnored;
1114     return virtualForWithFunction(execCallee, callLinkInfo, calleeAsFunctionCellIgnored);
1115 }
1116
1117 size_t JIT_OPERATION operationCompareLess(ExecState* exec, EncodedJSValue encodedOp1, EncodedJSValue encodedOp2)
1118 {
1119     VM* vm = &exec->vm();
1120     NativeCallFrameTracer tracer(vm, exec);
1121     
1122     return jsLess<true>(exec, JSValue::decode(encodedOp1), JSValue::decode(encodedOp2));
1123 }
1124
1125 size_t JIT_OPERATION operationCompareLessEq(ExecState* exec, EncodedJSValue encodedOp1, EncodedJSValue encodedOp2)
1126 {
1127     VM* vm = &exec->vm();
1128     NativeCallFrameTracer tracer(vm, exec);
1129
1130     return jsLessEq<true>(exec, JSValue::decode(encodedOp1), JSValue::decode(encodedOp2));
1131 }
1132
1133 size_t JIT_OPERATION operationCompareGreater(ExecState* exec, EncodedJSValue encodedOp1, EncodedJSValue encodedOp2)
1134 {
1135     VM* vm = &exec->vm();
1136     NativeCallFrameTracer tracer(vm, exec);
1137
1138     return jsLess<false>(exec, JSValue::decode(encodedOp2), JSValue::decode(encodedOp1));
1139 }
1140
1141 size_t JIT_OPERATION operationCompareGreaterEq(ExecState* exec, EncodedJSValue encodedOp1, EncodedJSValue encodedOp2)
1142 {
1143     VM* vm = &exec->vm();
1144     NativeCallFrameTracer tracer(vm, exec);
1145
1146     return jsLessEq<false>(exec, JSValue::decode(encodedOp2), JSValue::decode(encodedOp1));
1147 }
1148
1149 size_t JIT_OPERATION operationCompareEq(ExecState* exec, EncodedJSValue encodedOp1, EncodedJSValue encodedOp2)
1150 {
1151     VM* vm = &exec->vm();
1152     NativeCallFrameTracer tracer(vm, exec);
1153
1154     return JSValue::equalSlowCaseInline(exec, JSValue::decode(encodedOp1), JSValue::decode(encodedOp2));
1155 }
1156
1157 #if USE(JSVALUE64)
1158 EncodedJSValue JIT_OPERATION operationCompareStringEq(ExecState* exec, JSCell* left, JSCell* right)
1159 #else
1160 size_t JIT_OPERATION operationCompareStringEq(ExecState* exec, JSCell* left, JSCell* right)
1161 #endif
1162 {
1163     VM* vm = &exec->vm();
1164     NativeCallFrameTracer tracer(vm, exec);
1165
1166     bool result = asString(left)->equal(exec, asString(right));
1167 #if USE(JSVALUE64)
1168     return JSValue::encode(jsBoolean(result));
1169 #else
1170     return result;
1171 #endif
1172 }
1173
1174 EncodedJSValue JIT_OPERATION operationNewArrayWithProfile(ExecState* exec, ArrayAllocationProfile* profile, const JSValue* values, int size)
1175 {
1176     VM* vm = &exec->vm();
1177     NativeCallFrameTracer tracer(vm, exec);
1178     return JSValue::encode(constructArrayNegativeIndexed(exec, profile, values, size));
1179 }
1180
1181 EncodedJSValue JIT_OPERATION operationNewArrayWithSizeAndProfile(ExecState* exec, ArrayAllocationProfile* profile, EncodedJSValue size)
1182 {
1183     VM* vm = &exec->vm();
1184     NativeCallFrameTracer tracer(vm, exec);
1185     JSValue sizeValue = JSValue::decode(size);
1186     return JSValue::encode(constructArrayWithSizeQuirk(exec, profile, exec->lexicalGlobalObject(), sizeValue));
1187 }
1188
1189 }
1190
1191 template<typename FunctionType>
1192 static EncodedJSValue operationNewFunctionCommon(ExecState* exec, JSScope* scope, JSCell* functionExecutable, bool isInvalidated)
1193 {
1194     VM& vm = exec->vm();
1195     ASSERT(functionExecutable->inherits(vm, FunctionExecutable::info()));
1196     NativeCallFrameTracer tracer(&vm, exec);
1197     if (isInvalidated)
1198         return JSValue::encode(FunctionType::createWithInvalidatedReallocationWatchpoint(vm, static_cast<FunctionExecutable*>(functionExecutable), scope));
1199     return JSValue::encode(FunctionType::create(vm, static_cast<FunctionExecutable*>(functionExecutable), scope));
1200 }
1201
1202 extern "C" {
1203
1204 EncodedJSValue JIT_OPERATION operationNewFunction(ExecState* exec, JSScope* scope, JSCell* functionExecutable)
1205 {
1206     return operationNewFunctionCommon<JSFunction>(exec, scope, functionExecutable, false);
1207 }
1208
1209 EncodedJSValue JIT_OPERATION operationNewFunctionWithInvalidatedReallocationWatchpoint(ExecState* exec, JSScope* scope, JSCell* functionExecutable)
1210 {
1211     return operationNewFunctionCommon<JSFunction>(exec, scope, functionExecutable, true);
1212 }
1213
1214 EncodedJSValue JIT_OPERATION operationNewGeneratorFunction(ExecState* exec, JSScope* scope, JSCell* functionExecutable)
1215 {
1216     return operationNewFunctionCommon<JSGeneratorFunction>(exec, scope, functionExecutable, false);
1217 }
1218
1219 EncodedJSValue JIT_OPERATION operationNewGeneratorFunctionWithInvalidatedReallocationWatchpoint(ExecState* exec, JSScope* scope, JSCell* functionExecutable)
1220 {
1221     return operationNewFunctionCommon<JSGeneratorFunction>(exec, scope, functionExecutable, true);
1222 }
1223
1224 EncodedJSValue JIT_OPERATION operationNewAsyncFunction(ExecState* exec, JSScope* scope, JSCell* functionExecutable)
1225 {
1226     return operationNewFunctionCommon<JSAsyncFunction>(exec, scope, functionExecutable, false);
1227 }
1228
1229 EncodedJSValue JIT_OPERATION operationNewAsyncFunctionWithInvalidatedReallocationWatchpoint(ExecState* exec, JSScope* scope, JSCell* functionExecutable)
1230 {
1231     return operationNewFunctionCommon<JSAsyncFunction>(exec, scope, functionExecutable, true);
1232 }
1233
1234 EncodedJSValue JIT_OPERATION operationNewAsyncGeneratorFunction(ExecState* exec, JSScope* scope, JSCell* functionExecutable)
1235 {
1236     return operationNewFunctionCommon<JSAsyncGeneratorFunction>(exec, scope, functionExecutable, false);
1237 }
1238     
1239 EncodedJSValue JIT_OPERATION operationNewAsyncGeneratorFunctionWithInvalidatedReallocationWatchpoint(ExecState* exec, JSScope* scope, JSCell* functionExecutable)
1240 {
1241     return operationNewFunctionCommon<JSAsyncGeneratorFunction>(exec, scope, functionExecutable, true);
1242 }
1243     
1244 void JIT_OPERATION operationSetFunctionName(ExecState* exec, JSCell* funcCell, EncodedJSValue encodedName)
1245 {
1246     VM* vm = &exec->vm();
1247     NativeCallFrameTracer tracer(vm, exec);
1248
1249     JSFunction* func = jsCast<JSFunction*>(funcCell);
1250     JSValue name = JSValue::decode(encodedName);
1251     func->setFunctionName(exec, name);
1252 }
1253
1254 JSCell* JIT_OPERATION operationNewObject(ExecState* exec, Structure* structure)
1255 {
1256     VM* vm = &exec->vm();
1257     NativeCallFrameTracer tracer(vm, exec);
1258
1259     return constructEmptyObject(exec, structure);
1260 }
1261
1262 EncodedJSValue JIT_OPERATION operationNewRegexp(ExecState* exec, void* regexpPtr)
1263 {
1264     SuperSamplerScope superSamplerScope(false);
1265     VM& vm = exec->vm();
1266     NativeCallFrameTracer tracer(&vm, exec);
1267     auto scope = DECLARE_THROW_SCOPE(vm);
1268
1269     RegExp* regexp = static_cast<RegExp*>(regexpPtr);
1270     if (!regexp->isValid()) {
1271         throwException(exec, scope, createSyntaxError(exec, regexp->errorMessage()));
1272         return JSValue::encode(jsUndefined());
1273     }
1274
1275     return JSValue::encode(RegExpObject::create(vm, exec->lexicalGlobalObject()->regExpStructure(), regexp));
1276 }
1277
1278 // The only reason for returning an UnusedPtr (instead of void) is so that we can reuse the
1279 // existing DFG slow path generator machinery when creating the slow path for CheckTraps
1280 // in the DFG. If a DFG slow path generator that supports a void return type is added in the
1281 // future, we can switch to using that then.
1282 UnusedPtr JIT_OPERATION operationHandleTraps(ExecState* exec)
1283 {
1284     VM& vm = exec->vm();
1285     NativeCallFrameTracer tracer(&vm, exec);
1286     ASSERT(vm.needTrapHandling());
1287     vm.handleTraps(exec);
1288     return nullptr;
1289 }
1290
1291 void JIT_OPERATION operationDebug(ExecState* exec, int32_t debugHookType)
1292 {
1293     VM& vm = exec->vm();
1294     NativeCallFrameTracer tracer(&vm, exec);
1295
1296     vm.interpreter->debug(exec, static_cast<DebugHookType>(debugHookType));
1297 }
1298
1299 #if ENABLE(DFG_JIT)
1300 static void updateAllPredictionsAndOptimizeAfterWarmUp(CodeBlock* codeBlock)
1301 {
1302     codeBlock->updateAllPredictions();
1303     codeBlock->optimizeAfterWarmUp();
1304 }
1305
1306 SlowPathReturnType JIT_OPERATION operationOptimize(ExecState* exec, int32_t bytecodeIndex)
1307 {
1308     VM& vm = exec->vm();
1309     NativeCallFrameTracer tracer(&vm, exec);
1310
1311     // Defer GC for a while so that it doesn't run between when we enter into this
1312     // slow path and when we figure out the state of our code block. This prevents
1313     // a number of awkward reentrancy scenarios, including:
1314     //
1315     // - The optimized version of our code block being jettisoned by GC right after
1316     //   we concluded that we wanted to use it, but have not planted it into the JS
1317     //   stack yet.
1318     //
1319     // - An optimized version of our code block being installed just as we decided
1320     //   that it wasn't ready yet.
1321     //
1322     // Note that jettisoning won't happen if we already initiated OSR, because in
1323     // that case we would have already planted the optimized code block into the JS
1324     // stack.
1325     DeferGCForAWhile deferGC(vm.heap);
1326     
1327     CodeBlock* codeBlock = exec->codeBlock();
1328     if (UNLIKELY(codeBlock->jitType() != JITCode::BaselineJIT)) {
1329         dataLog("Unexpected code block in Baseline->DFG tier-up: ", *codeBlock, "\n");
1330         RELEASE_ASSERT_NOT_REACHED();
1331     }
1332     
1333     if (bytecodeIndex) {
1334         // If we're attempting to OSR from a loop, assume that this should be
1335         // separately optimized.
1336         codeBlock->m_shouldAlwaysBeInlined = false;
1337     }
1338
1339     if (UNLIKELY(Options::verboseOSR())) {
1340         dataLog(
1341             *codeBlock, ": Entered optimize with bytecodeIndex = ", bytecodeIndex,
1342             ", executeCounter = ", codeBlock->jitExecuteCounter(),
1343             ", optimizationDelayCounter = ", codeBlock->reoptimizationRetryCounter(),
1344             ", exitCounter = ");
1345         if (codeBlock->hasOptimizedReplacement())
1346             dataLog(codeBlock->replacement()->osrExitCounter());
1347         else
1348             dataLog("N/A");
1349         dataLog("\n");
1350     }
1351
1352     if (!codeBlock->checkIfOptimizationThresholdReached()) {
1353         CODEBLOCK_LOG_EVENT(codeBlock, "delayOptimizeToDFG", ("counter = ", codeBlock->jitExecuteCounter()));
1354         codeBlock->updateAllPredictions();
1355         if (UNLIKELY(Options::verboseOSR()))
1356             dataLog("Choosing not to optimize ", *codeBlock, " yet, because the threshold hasn't been reached.\n");
1357         return encodeResult(0, 0);
1358     }
1359     
1360     Debugger* debugger = codeBlock->globalObject()->debugger();
1361     if (UNLIKELY(debugger && (debugger->isStepping() || codeBlock->baselineAlternative()->hasDebuggerRequests()))) {
1362         CODEBLOCK_LOG_EVENT(codeBlock, "delayOptimizeToDFG", ("debugger is stepping or has requests"));
1363         updateAllPredictionsAndOptimizeAfterWarmUp(codeBlock);
1364         return encodeResult(0, 0);
1365     }
1366
1367     if (codeBlock->m_shouldAlwaysBeInlined) {
1368         CODEBLOCK_LOG_EVENT(codeBlock, "delayOptimizeToDFG", ("should always be inlined"));
1369         updateAllPredictionsAndOptimizeAfterWarmUp(codeBlock);
1370         if (UNLIKELY(Options::verboseOSR()))
1371             dataLog("Choosing not to optimize ", *codeBlock, " yet, because m_shouldAlwaysBeInlined == true.\n");
1372         return encodeResult(0, 0);
1373     }
1374
1375     // We cannot be in the process of asynchronous compilation and also have an optimized
1376     // replacement.
1377     DFG::Worklist* worklist = DFG::existingGlobalDFGWorklistOrNull();
1378     ASSERT(
1379         !worklist
1380         || !(worklist->compilationState(DFG::CompilationKey(codeBlock, DFG::DFGMode)) != DFG::Worklist::NotKnown
1381         && codeBlock->hasOptimizedReplacement()));
1382
1383     DFG::Worklist::State worklistState;
1384     if (worklist) {
1385         // The call to DFG::Worklist::completeAllReadyPlansForVM() will complete all ready
1386         // (i.e. compiled) code blocks. But if it completes ours, we also need to know
1387         // what the result was so that we don't plow ahead and attempt OSR or immediate
1388         // reoptimization. This will have already also set the appropriate JIT execution
1389         // count threshold depending on what happened, so if the compilation was anything
1390         // but successful we just want to return early. See the case for worklistState ==
1391         // DFG::Worklist::Compiled, below.
1392         
1393         // Note that we could have alternatively just called Worklist::compilationState()
1394         // here, and if it returned Compiled, we could have then called
1395         // completeAndScheduleOSR() below. But that would have meant that it could take
1396         // longer for code blocks to be completed: they would only complete when *their*
1397         // execution count trigger fired; but that could take a while since the firing is
1398         // racy. It could also mean that code blocks that never run again after being
1399         // compiled would sit on the worklist until next GC. That's fine, but it's
1400         // probably a waste of memory. Our goal here is to complete code blocks as soon as
1401         // possible in order to minimize the chances of us executing baseline code after
1402         // optimized code is already available.
1403         worklistState = worklist->completeAllReadyPlansForVM(
1404             vm, DFG::CompilationKey(codeBlock, DFG::DFGMode));
1405     } else
1406         worklistState = DFG::Worklist::NotKnown;
1407
1408     if (worklistState == DFG::Worklist::Compiling) {
1409         CODEBLOCK_LOG_EVENT(codeBlock, "delayOptimizeToDFG", ("compiling"));
1410         // We cannot be in the process of asynchronous compilation and also have an optimized
1411         // replacement.
1412         RELEASE_ASSERT(!codeBlock->hasOptimizedReplacement());
1413         codeBlock->setOptimizationThresholdBasedOnCompilationResult(CompilationDeferred);
1414         return encodeResult(0, 0);
1415     }
1416
1417     if (worklistState == DFG::Worklist::Compiled) {
1418         // If we don't have an optimized replacement but we did just get compiled, then
1419         // the compilation failed or was invalidated, in which case the execution count
1420         // thresholds have already been set appropriately by
1421         // CodeBlock::setOptimizationThresholdBasedOnCompilationResult() and we have
1422         // nothing left to do.
1423         if (!codeBlock->hasOptimizedReplacement()) {
1424             CODEBLOCK_LOG_EVENT(codeBlock, "delayOptimizeToDFG", ("compiled and failed"));
1425             codeBlock->updateAllPredictions();
1426             if (UNLIKELY(Options::verboseOSR()))
1427                 dataLog("Code block ", *codeBlock, " was compiled but it doesn't have an optimized replacement.\n");
1428             return encodeResult(0, 0);
1429         }
1430     } else if (codeBlock->hasOptimizedReplacement()) {
1431         if (UNLIKELY(Options::verboseOSR()))
1432             dataLog("Considering OSR ", *codeBlock, " -> ", *codeBlock->replacement(), ".\n");
1433         // If we have an optimized replacement, then it must be the case that we entered
1434         // cti_optimize from a loop. That's because if there's an optimized replacement,
1435         // then all calls to this function will be relinked to the replacement and so
1436         // the prologue OSR will never fire.
1437         
1438         // This is an interesting threshold check. Consider that a function OSR exits
1439         // in the middle of a loop, while having a relatively low exit count. The exit
1440         // will reset the execution counter to some target threshold, meaning that this
1441         // code won't be reached until that loop heats up for >=1000 executions. But then
1442         // we do a second check here, to see if we should either reoptimize, or just
1443         // attempt OSR entry. Hence it might even be correct for
1444         // shouldReoptimizeFromLoopNow() to always return true. But we make it do some
1445         // additional checking anyway, to reduce the amount of recompilation thrashing.
1446         if (codeBlock->replacement()->shouldReoptimizeFromLoopNow()) {
1447             CODEBLOCK_LOG_EVENT(codeBlock, "delayOptimizeToDFG", ("should reoptimize from loop now"));
1448             if (UNLIKELY(Options::verboseOSR())) {
1449                 dataLog(
1450                     "Triggering reoptimization of ", *codeBlock,
1451                     "(", *codeBlock->replacement(), ") (in loop).\n");
1452             }
1453             codeBlock->replacement()->jettison(Profiler::JettisonDueToBaselineLoopReoptimizationTrigger, CountReoptimization);
1454             return encodeResult(0, 0);
1455         }
1456     } else {
1457         if (!codeBlock->shouldOptimizeNow()) {
1458             CODEBLOCK_LOG_EVENT(codeBlock, "delayOptimizeToDFG", ("insufficient profiling"));
1459             if (UNLIKELY(Options::verboseOSR())) {
1460                 dataLog(
1461                     "Delaying optimization for ", *codeBlock,
1462                     " because of insufficient profiling.\n");
1463             }
1464             return encodeResult(0, 0);
1465         }
1466
1467         if (UNLIKELY(Options::verboseOSR()))
1468             dataLog("Triggering optimized compilation of ", *codeBlock, "\n");
1469
1470         unsigned numVarsWithValues;
1471         if (bytecodeIndex)
1472             numVarsWithValues = codeBlock->m_numCalleeLocals;
1473         else
1474             numVarsWithValues = 0;
1475         Operands<JSValue> mustHandleValues(codeBlock->numParameters(), numVarsWithValues);
1476         int localsUsedForCalleeSaves = static_cast<int>(CodeBlock::llintBaselineCalleeSaveSpaceAsVirtualRegisters());
1477         for (size_t i = 0; i < mustHandleValues.size(); ++i) {
1478             int operand = mustHandleValues.operandForIndex(i);
1479             if (operandIsLocal(operand) && VirtualRegister(operand).toLocal() < localsUsedForCalleeSaves)
1480                 continue;
1481             mustHandleValues[i] = exec->uncheckedR(operand).jsValue();
1482         }
1483
1484         CodeBlock* replacementCodeBlock = codeBlock->newReplacement();
1485         CompilationResult result = DFG::compile(
1486             vm, replacementCodeBlock, nullptr, DFG::DFGMode, bytecodeIndex,
1487             mustHandleValues, JITToDFGDeferredCompilationCallback::create());
1488         
1489         if (result != CompilationSuccessful) {
1490             CODEBLOCK_LOG_EVENT(codeBlock, "delayOptimizeToDFG", ("compilation failed"));
1491             return encodeResult(0, 0);
1492         }
1493     }
1494     
1495     CodeBlock* optimizedCodeBlock = codeBlock->replacement();
1496     ASSERT(JITCode::isOptimizingJIT(optimizedCodeBlock->jitType()));
1497     
1498     if (void* dataBuffer = DFG::prepareOSREntry(exec, optimizedCodeBlock, bytecodeIndex)) {
1499         CODEBLOCK_LOG_EVENT(optimizedCodeBlock, "osrEntry", ("at bc#", bytecodeIndex));
1500         if (UNLIKELY(Options::verboseOSR())) {
1501             dataLog(
1502                 "Performing OSR ", *codeBlock, " -> ", *optimizedCodeBlock, ".\n");
1503         }
1504
1505         codeBlock->optimizeSoon();
1506         codeBlock->unlinkedCodeBlock()->setDidOptimize(TrueTriState);
1507         return encodeResult(vm.getCTIStub(DFG::osrEntryThunkGenerator).code().executableAddress(), dataBuffer);
1508     }
1509
1510     if (UNLIKELY(Options::verboseOSR())) {
1511         dataLog(
1512             "Optimizing ", *codeBlock, " -> ", *codeBlock->replacement(),
1513             " succeeded, OSR failed, after a delay of ",
1514             codeBlock->optimizationDelayCounter(), ".\n");
1515     }
1516
1517     // Count the OSR failure as a speculation failure. If this happens a lot, then
1518     // reoptimize.
1519     optimizedCodeBlock->countOSRExit();
1520
1521     // We are a lot more conservative about triggering reoptimization after OSR failure than
1522     // before it. If we enter the optimize_from_loop trigger with a bucket full of fail
1523     // already, then we really would like to reoptimize immediately. But this case covers
1524     // something else: there weren't many (or any) speculation failures before, but we just
1525     // failed to enter the speculative code because some variable had the wrong value or
1526     // because the OSR code decided for any spurious reason that it did not want to OSR
1527     // right now. So, we only trigger reoptimization only upon the more conservative (non-loop)
1528     // reoptimization trigger.
1529     if (optimizedCodeBlock->shouldReoptimizeNow()) {
1530         CODEBLOCK_LOG_EVENT(codeBlock, "delayOptimizeToDFG", ("should reoptimize now"));
1531         if (UNLIKELY(Options::verboseOSR())) {
1532             dataLog(
1533                 "Triggering reoptimization of ", *codeBlock, " -> ",
1534                 *codeBlock->replacement(), " (after OSR fail).\n");
1535         }
1536         optimizedCodeBlock->jettison(Profiler::JettisonDueToBaselineLoopReoptimizationTriggerOnOSREntryFail, CountReoptimization);
1537         return encodeResult(0, 0);
1538     }
1539
1540     // OSR failed this time, but it might succeed next time! Let the code run a bit
1541     // longer and then try again.
1542     codeBlock->optimizeAfterWarmUp();
1543     
1544     CODEBLOCK_LOG_EVENT(codeBlock, "delayOptimizeToDFG", ("OSR failed"));
1545     return encodeResult(0, 0);
1546 }
1547
1548 char* JIT_OPERATION operationTryOSREnterAtCatch(ExecState* exec, uint32_t bytecodeIndex)
1549 {
1550     VM& vm = exec->vm();
1551     NativeCallFrameTracer tracer(&vm, exec);
1552
1553     CodeBlock* optimizedReplacement = exec->codeBlock()->replacement();
1554     switch (optimizedReplacement->jitType()) {
1555     case JITCode::DFGJIT:
1556     case JITCode::FTLJIT:
1557         return static_cast<char*>(DFG::prepareCatchOSREntry(exec, optimizedReplacement, bytecodeIndex));
1558     default:
1559         break;
1560     }
1561     return nullptr;
1562 }
1563
1564 char* JIT_OPERATION operationTryOSREnterAtCatchAndValueProfile(ExecState* exec, uint32_t bytecodeIndex)
1565 {
1566     VM& vm = exec->vm();
1567     NativeCallFrameTracer tracer(&vm, exec);
1568
1569     CodeBlock* codeBlock = exec->codeBlock();
1570     CodeBlock* optimizedReplacement = codeBlock->replacement();
1571
1572     switch (optimizedReplacement->jitType()) {
1573     case JITCode::DFGJIT:
1574     case JITCode::FTLJIT:
1575         return static_cast<char*>(DFG::prepareCatchOSREntry(exec, optimizedReplacement, bytecodeIndex));
1576     default:
1577         break;
1578     }
1579
1580     codeBlock->ensureCatchLivenessIsComputedForBytecodeOffset(bytecodeIndex);
1581     ValueProfileAndOperandBuffer* buffer = static_cast<ValueProfileAndOperandBuffer*>(codeBlock->instructions()[bytecodeIndex + 3].u.pointer);
1582     buffer->forEach([&] (ValueProfileAndOperand& profile) {
1583         profile.m_profile.m_buckets[0] = JSValue::encode(exec->uncheckedR(profile.m_operand).jsValue());
1584     });
1585
1586     return nullptr;
1587 }
1588
1589 #endif
1590
1591 void JIT_OPERATION operationPutByIndex(ExecState* exec, EncodedJSValue encodedArrayValue, int32_t index, EncodedJSValue encodedValue)
1592 {
1593     VM& vm = exec->vm();
1594     NativeCallFrameTracer tracer(&vm, exec);
1595
1596     JSValue arrayValue = JSValue::decode(encodedArrayValue);
1597     ASSERT(isJSArray(arrayValue));
1598     asArray(arrayValue)->putDirectIndex(exec, index, JSValue::decode(encodedValue));
1599 }
1600
1601 enum class AccessorType {
1602     Getter,
1603     Setter
1604 };
1605
1606 static void putAccessorByVal(ExecState* exec, JSObject* base, JSValue subscript, int32_t attribute, JSObject* accessor, AccessorType accessorType)
1607 {
1608     VM& vm = exec->vm();
1609     auto scope = DECLARE_THROW_SCOPE(vm);
1610     auto propertyKey = subscript.toPropertyKey(exec);
1611     RETURN_IF_EXCEPTION(scope, void());
1612
1613     scope.release();
1614     if (accessorType == AccessorType::Getter)
1615         base->putGetter(exec, propertyKey, accessor, attribute);
1616     else
1617         base->putSetter(exec, propertyKey, accessor, attribute);
1618 }
1619
1620 void JIT_OPERATION operationPutGetterById(ExecState* exec, JSCell* object, UniquedStringImpl* uid, int32_t options, JSCell* getter)
1621 {
1622     VM& vm = exec->vm();
1623     NativeCallFrameTracer tracer(&vm, exec);
1624
1625     ASSERT(object && object->isObject());
1626     JSObject* baseObj = object->getObject();
1627
1628     ASSERT(getter->isObject());
1629     baseObj->putGetter(exec, uid, getter, options);
1630 }
1631
1632 void JIT_OPERATION operationPutSetterById(ExecState* exec, JSCell* object, UniquedStringImpl* uid, int32_t options, JSCell* setter)
1633 {
1634     VM& vm = exec->vm();
1635     NativeCallFrameTracer tracer(&vm, exec);
1636
1637     ASSERT(object && object->isObject());
1638     JSObject* baseObj = object->getObject();
1639
1640     ASSERT(setter->isObject());
1641     baseObj->putSetter(exec, uid, setter, options);
1642 }
1643
1644 void JIT_OPERATION operationPutGetterByVal(ExecState* exec, JSCell* base, EncodedJSValue encodedSubscript, int32_t attribute, JSCell* getter)
1645 {
1646     VM& vm = exec->vm();
1647     NativeCallFrameTracer tracer(&vm, exec);
1648
1649     putAccessorByVal(exec, asObject(base), JSValue::decode(encodedSubscript), attribute, asObject(getter), AccessorType::Getter);
1650 }
1651
1652 void JIT_OPERATION operationPutSetterByVal(ExecState* exec, JSCell* base, EncodedJSValue encodedSubscript, int32_t attribute, JSCell* setter)
1653 {
1654     VM& vm = exec->vm();
1655     NativeCallFrameTracer tracer(&vm, exec);
1656
1657     putAccessorByVal(exec, asObject(base), JSValue::decode(encodedSubscript), attribute, asObject(setter), AccessorType::Setter);
1658 }
1659
1660 #if USE(JSVALUE64)
1661 void JIT_OPERATION operationPutGetterSetter(ExecState* exec, JSCell* object, UniquedStringImpl* uid, int32_t attribute, EncodedJSValue encodedGetterValue, EncodedJSValue encodedSetterValue)
1662 {
1663     VM& vm = exec->vm();
1664     NativeCallFrameTracer tracer(&vm, exec);
1665
1666     ASSERT(object && object->isObject());
1667     JSObject* baseObj = asObject(object);
1668
1669     GetterSetter* accessor = GetterSetter::create(vm, exec->lexicalGlobalObject());
1670
1671     JSValue getter = JSValue::decode(encodedGetterValue);
1672     JSValue setter = JSValue::decode(encodedSetterValue);
1673     ASSERT(getter.isObject() || getter.isUndefined());
1674     ASSERT(setter.isObject() || setter.isUndefined());
1675     ASSERT(getter.isObject() || setter.isObject());
1676
1677     if (!getter.isUndefined())
1678         accessor->setGetter(vm, exec->lexicalGlobalObject(), asObject(getter));
1679     if (!setter.isUndefined())
1680         accessor->setSetter(vm, exec->lexicalGlobalObject(), asObject(setter));
1681     baseObj->putDirectAccessor(exec, uid, accessor, attribute);
1682 }
1683
1684 #else
1685 void JIT_OPERATION operationPutGetterSetter(ExecState* exec, JSCell* object, UniquedStringImpl* uid, int32_t attribute, JSCell* getter, JSCell* setter)
1686 {
1687     VM& vm = exec->vm();
1688     NativeCallFrameTracer tracer(&vm, exec);
1689
1690     ASSERT(object && object->isObject());
1691     JSObject* baseObj = asObject(object);
1692
1693     GetterSetter* accessor = GetterSetter::create(vm, exec->lexicalGlobalObject());
1694
1695     ASSERT(!getter || getter->isObject());
1696     ASSERT(!setter || setter->isObject());
1697     ASSERT(getter || setter);
1698
1699     if (getter)
1700         accessor->setGetter(vm, exec->lexicalGlobalObject(), getter->getObject());
1701     if (setter)
1702         accessor->setSetter(vm, exec->lexicalGlobalObject(), setter->getObject());
1703     baseObj->putDirectAccessor(exec, uid, accessor, attribute);
1704 }
1705 #endif
1706
1707 void JIT_OPERATION operationPopScope(ExecState* exec, int32_t scopeReg)
1708 {
1709     VM& vm = exec->vm();
1710     NativeCallFrameTracer tracer(&vm, exec);
1711
1712     JSScope* scope = exec->uncheckedR(scopeReg).Register::scope();
1713     exec->uncheckedR(scopeReg) = scope->next();
1714 }
1715
1716 int32_t JIT_OPERATION operationInstanceOfCustom(ExecState* exec, EncodedJSValue encodedValue, JSObject* constructor, EncodedJSValue encodedHasInstance)
1717 {
1718     VM& vm = exec->vm();
1719     NativeCallFrameTracer tracer(&vm, exec);
1720
1721     JSValue value = JSValue::decode(encodedValue);
1722     JSValue hasInstanceValue = JSValue::decode(encodedHasInstance);
1723
1724     ASSERT(hasInstanceValue != exec->lexicalGlobalObject()->functionProtoHasInstanceSymbolFunction() || !constructor->structure()->typeInfo().implementsDefaultHasInstance());
1725
1726     if (constructor->hasInstance(exec, value, hasInstanceValue))
1727         return 1;
1728     return 0;
1729 }
1730
1731 }
1732
1733 static bool canAccessArgumentIndexQuickly(JSObject& object, uint32_t index)
1734 {
1735     switch (object.structure()->typeInfo().type()) {
1736     case DirectArgumentsType: {
1737         DirectArguments* directArguments = jsCast<DirectArguments*>(&object);
1738         if (directArguments->isMappedArgumentInDFG(index))
1739             return true;
1740         break;
1741     }
1742     case ScopedArgumentsType: {
1743         ScopedArguments* scopedArguments = jsCast<ScopedArguments*>(&object);
1744         if (scopedArguments->isMappedArgumentInDFG(index))
1745             return true;
1746         break;
1747     }
1748     default:
1749         break;
1750     }
1751     return false;
1752 }
1753
1754 static JSValue getByVal(ExecState* exec, JSValue baseValue, JSValue subscript, ByValInfo* byValInfo, ReturnAddressPtr returnAddress)
1755 {
1756     VM& vm = exec->vm();
1757     auto scope = DECLARE_THROW_SCOPE(vm);
1758
1759     if (LIKELY(baseValue.isCell() && subscript.isString())) {
1760         Structure& structure = *baseValue.asCell()->structure(vm);
1761         if (JSCell::canUseFastGetOwnProperty(structure)) {
1762             if (RefPtr<AtomicStringImpl> existingAtomicString = asString(subscript)->toExistingAtomicString(exec)) {
1763                 if (JSValue result = baseValue.asCell()->fastGetOwnProperty(vm, structure, existingAtomicString.get())) {
1764                     ASSERT(exec->bytecodeOffset());
1765                     if (byValInfo->stubInfo && byValInfo->cachedId.impl() != existingAtomicString)
1766                         byValInfo->tookSlowPath = true;
1767                     return result;
1768                 }
1769             }
1770         }
1771     }
1772
1773     if (subscript.isUInt32()) {
1774         ASSERT(exec->bytecodeOffset());
1775         byValInfo->tookSlowPath = true;
1776
1777         uint32_t i = subscript.asUInt32();
1778         if (isJSString(baseValue)) {
1779             if (asString(baseValue)->canGetIndex(i)) {
1780                 ctiPatchCallByReturnAddress(returnAddress, FunctionPtr(operationGetByValString));
1781                 scope.release();
1782                 return asString(baseValue)->getIndex(exec, i);
1783             }
1784             byValInfo->arrayProfile->setOutOfBounds();
1785         } else if (baseValue.isObject()) {
1786             JSObject* object = asObject(baseValue);
1787             if (object->canGetIndexQuickly(i))
1788                 return object->getIndexQuickly(i);
1789
1790             if (!canAccessArgumentIndexQuickly(*object, i)) {
1791                 // FIXME: This will make us think that in-bounds typed array accesses are actually
1792                 // out-of-bounds.
1793                 // https://bugs.webkit.org/show_bug.cgi?id=149886
1794                 byValInfo->arrayProfile->setOutOfBounds();
1795             }
1796         }
1797
1798         scope.release();
1799         return baseValue.get(exec, i);
1800     }
1801
1802     baseValue.requireObjectCoercible(exec);
1803     RETURN_IF_EXCEPTION(scope, JSValue());
1804     auto property = subscript.toPropertyKey(exec);
1805     RETURN_IF_EXCEPTION(scope, JSValue());
1806
1807     ASSERT(exec->bytecodeOffset());
1808     if (byValInfo->stubInfo && (!isStringOrSymbol(subscript) || byValInfo->cachedId != property))
1809         byValInfo->tookSlowPath = true;
1810
1811     scope.release();
1812     return baseValue.get(exec, property);
1813 }
1814
1815 static OptimizationResult tryGetByValOptimize(ExecState* exec, JSValue baseValue, JSValue subscript, ByValInfo* byValInfo, ReturnAddressPtr returnAddress)
1816 {
1817     // See if it's worth optimizing this at all.
1818     OptimizationResult optimizationResult = OptimizationResult::NotOptimized;
1819
1820     VM& vm = exec->vm();
1821
1822     if (baseValue.isObject() && subscript.isInt32()) {
1823         JSObject* object = asObject(baseValue);
1824
1825         ASSERT(exec->bytecodeOffset());
1826         ASSERT(!byValInfo->stubRoutine);
1827
1828         if (hasOptimizableIndexing(object->structure(vm))) {
1829             // Attempt to optimize.
1830             Structure* structure = object->structure(vm);
1831             JITArrayMode arrayMode = jitArrayModeForStructure(structure);
1832             if (arrayMode != byValInfo->arrayMode) {
1833                 // If we reached this case, we got an interesting array mode we did not expect when we compiled.
1834                 // Let's update the profile to do better next time.
1835                 CodeBlock* codeBlock = exec->codeBlock();
1836                 ConcurrentJSLocker locker(codeBlock->m_lock);
1837                 byValInfo->arrayProfile->computeUpdatedPrediction(locker, codeBlock, structure);
1838
1839                 JIT::compileGetByVal(&vm, exec->codeBlock(), byValInfo, returnAddress, arrayMode);
1840                 optimizationResult = OptimizationResult::Optimized;
1841             }
1842         }
1843
1844         // If we failed to patch and we have some object that intercepts indexed get, then don't even wait until 10 times.
1845         if (optimizationResult != OptimizationResult::Optimized && object->structure(vm)->typeInfo().interceptsGetOwnPropertySlotByIndexEvenWhenLengthIsNotZero())
1846             optimizationResult = OptimizationResult::GiveUp;
1847     }
1848
1849     if (baseValue.isObject() && isStringOrSymbol(subscript)) {
1850         const Identifier propertyName = subscript.toPropertyKey(exec);
1851         if (subscript.isSymbol() || !parseIndex(propertyName)) {
1852             ASSERT(exec->bytecodeOffset());
1853             ASSERT(!byValInfo->stubRoutine);
1854             if (byValInfo->seen) {
1855                 if (byValInfo->cachedId == propertyName) {
1856                     JIT::compileGetByValWithCachedId(&vm, exec->codeBlock(), byValInfo, returnAddress, propertyName);
1857                     optimizationResult = OptimizationResult::Optimized;
1858                 } else {
1859                     // Seem like a generic property access site.
1860                     optimizationResult = OptimizationResult::GiveUp;
1861                 }
1862             } else {
1863                 CodeBlock* codeBlock = exec->codeBlock();
1864                 ConcurrentJSLocker locker(codeBlock->m_lock);
1865                 byValInfo->seen = true;
1866                 byValInfo->cachedId = propertyName;
1867                 if (subscript.isSymbol())
1868                     byValInfo->cachedSymbol.set(vm, codeBlock, asSymbol(subscript));
1869                 optimizationResult = OptimizationResult::SeenOnce;
1870             }
1871         }
1872     }
1873
1874     if (optimizationResult != OptimizationResult::Optimized && optimizationResult != OptimizationResult::SeenOnce) {
1875         // If we take slow path more than 10 times without patching then make sure we
1876         // never make that mistake again. For cases where we see non-index-intercepting
1877         // objects, this gives 10 iterations worth of opportunity for us to observe
1878         // that the get_by_val may be polymorphic. We count up slowPathCount even if
1879         // the result is GiveUp.
1880         if (++byValInfo->slowPathCount >= 10)
1881             optimizationResult = OptimizationResult::GiveUp;
1882     }
1883
1884     return optimizationResult;
1885 }
1886
1887 extern "C" {
1888
1889 EncodedJSValue JIT_OPERATION operationGetByValGeneric(ExecState* exec, EncodedJSValue encodedBase, EncodedJSValue encodedSubscript, ByValInfo* byValInfo)
1890 {
1891     VM& vm = exec->vm();
1892     NativeCallFrameTracer tracer(&vm, exec);
1893     JSValue baseValue = JSValue::decode(encodedBase);
1894     JSValue subscript = JSValue::decode(encodedSubscript);
1895
1896     JSValue result = getByVal(exec, baseValue, subscript, byValInfo, ReturnAddressPtr(OUR_RETURN_ADDRESS));
1897     return JSValue::encode(result);
1898 }
1899
1900 EncodedJSValue JIT_OPERATION operationGetByValOptimize(ExecState* exec, EncodedJSValue encodedBase, EncodedJSValue encodedSubscript, ByValInfo* byValInfo)
1901 {
1902     VM& vm = exec->vm();
1903     NativeCallFrameTracer tracer(&vm, exec);
1904
1905     JSValue baseValue = JSValue::decode(encodedBase);
1906     JSValue subscript = JSValue::decode(encodedSubscript);
1907     ReturnAddressPtr returnAddress = ReturnAddressPtr(OUR_RETURN_ADDRESS);
1908     if (tryGetByValOptimize(exec, baseValue, subscript, byValInfo, returnAddress) == OptimizationResult::GiveUp) {
1909         // Don't ever try to optimize.
1910         byValInfo->tookSlowPath = true;
1911         ctiPatchCallByReturnAddress(returnAddress, FunctionPtr(operationGetByValGeneric));
1912     }
1913
1914     return JSValue::encode(getByVal(exec, baseValue, subscript, byValInfo, returnAddress));
1915 }
1916
1917 EncodedJSValue JIT_OPERATION operationHasIndexedPropertyDefault(ExecState* exec, EncodedJSValue encodedBase, EncodedJSValue encodedSubscript, ByValInfo* byValInfo)
1918 {
1919     VM& vm = exec->vm();
1920     NativeCallFrameTracer tracer(&vm, exec);
1921     JSValue baseValue = JSValue::decode(encodedBase);
1922     JSValue subscript = JSValue::decode(encodedSubscript);
1923     
1924     ASSERT(baseValue.isObject());
1925     ASSERT(subscript.isUInt32());
1926
1927     JSObject* object = asObject(baseValue);
1928     bool didOptimize = false;
1929
1930     ASSERT(exec->bytecodeOffset());
1931     ASSERT(!byValInfo->stubRoutine);
1932     
1933     if (hasOptimizableIndexing(object->structure(vm))) {
1934         // Attempt to optimize.
1935         JITArrayMode arrayMode = jitArrayModeForStructure(object->structure(vm));
1936         if (arrayMode != byValInfo->arrayMode) {
1937             JIT::compileHasIndexedProperty(&vm, exec->codeBlock(), byValInfo, ReturnAddressPtr(OUR_RETURN_ADDRESS), arrayMode);
1938             didOptimize = true;
1939         }
1940     }
1941     
1942     if (!didOptimize) {
1943         // If we take slow path more than 10 times without patching then make sure we
1944         // never make that mistake again. Or, if we failed to patch and we have some object
1945         // that intercepts indexed get, then don't even wait until 10 times. For cases
1946         // where we see non-index-intercepting objects, this gives 10 iterations worth of
1947         // opportunity for us to observe that the get_by_val may be polymorphic.
1948         if (++byValInfo->slowPathCount >= 10
1949             || object->structure(vm)->typeInfo().interceptsGetOwnPropertySlotByIndexEvenWhenLengthIsNotZero()) {
1950             // Don't ever try to optimize.
1951             ctiPatchCallByReturnAddress(ReturnAddressPtr(OUR_RETURN_ADDRESS), FunctionPtr(operationHasIndexedPropertyGeneric));
1952         }
1953     }
1954
1955     uint32_t index = subscript.asUInt32();
1956     if (object->canGetIndexQuickly(index))
1957         return JSValue::encode(JSValue(JSValue::JSTrue));
1958
1959     if (!canAccessArgumentIndexQuickly(*object, index)) {
1960         // FIXME: This will make us think that in-bounds typed array accesses are actually
1961         // out-of-bounds.
1962         // https://bugs.webkit.org/show_bug.cgi?id=149886
1963         byValInfo->arrayProfile->setOutOfBounds();
1964     }
1965     return JSValue::encode(jsBoolean(object->hasPropertyGeneric(exec, index, PropertySlot::InternalMethodType::GetOwnProperty)));
1966 }
1967     
1968 EncodedJSValue JIT_OPERATION operationHasIndexedPropertyGeneric(ExecState* exec, EncodedJSValue encodedBase, EncodedJSValue encodedSubscript, ByValInfo* byValInfo)
1969 {
1970     VM& vm = exec->vm();
1971     NativeCallFrameTracer tracer(&vm, exec);
1972     JSValue baseValue = JSValue::decode(encodedBase);
1973     JSValue subscript = JSValue::decode(encodedSubscript);
1974     
1975     ASSERT(baseValue.isObject());
1976     ASSERT(subscript.isUInt32());
1977
1978     JSObject* object = asObject(baseValue);
1979     uint32_t index = subscript.asUInt32();
1980     if (object->canGetIndexQuickly(index))
1981         return JSValue::encode(JSValue(JSValue::JSTrue));
1982
1983     if (!canAccessArgumentIndexQuickly(*object, index)) {
1984         // FIXME: This will make us think that in-bounds typed array accesses are actually
1985         // out-of-bounds.
1986         // https://bugs.webkit.org/show_bug.cgi?id=149886
1987         byValInfo->arrayProfile->setOutOfBounds();
1988     }
1989     return JSValue::encode(jsBoolean(object->hasPropertyGeneric(exec, subscript.asUInt32(), PropertySlot::InternalMethodType::GetOwnProperty)));
1990 }
1991     
1992 EncodedJSValue JIT_OPERATION operationGetByValString(ExecState* exec, EncodedJSValue encodedBase, EncodedJSValue encodedSubscript, ByValInfo* byValInfo)
1993 {
1994     VM& vm = exec->vm();
1995     NativeCallFrameTracer tracer(&vm, exec);
1996     auto scope = DECLARE_THROW_SCOPE(vm);
1997     JSValue baseValue = JSValue::decode(encodedBase);
1998     JSValue subscript = JSValue::decode(encodedSubscript);
1999     
2000     JSValue result;
2001     if (LIKELY(subscript.isUInt32())) {
2002         uint32_t i = subscript.asUInt32();
2003         if (isJSString(baseValue) && asString(baseValue)->canGetIndex(i)) {
2004             scope.release();
2005             return JSValue::encode(asString(baseValue)->getIndex(exec, i));
2006         }
2007         result = baseValue.get(exec, i);
2008         RETURN_IF_EXCEPTION(scope, encodedJSValue());
2009         if (!isJSString(baseValue)) {
2010             ASSERT(exec->bytecodeOffset());
2011             ctiPatchCallByReturnAddress(ReturnAddressPtr(OUR_RETURN_ADDRESS), FunctionPtr(byValInfo->stubRoutine ? operationGetByValGeneric : operationGetByValOptimize));
2012         }
2013     } else {
2014         baseValue.requireObjectCoercible(exec);
2015         RETURN_IF_EXCEPTION(scope, encodedJSValue());
2016         auto property = subscript.toPropertyKey(exec);
2017         RETURN_IF_EXCEPTION(scope, encodedJSValue());
2018         scope.release();
2019         result = baseValue.get(exec, property);
2020     }
2021
2022     return JSValue::encode(result);
2023 }
2024
2025 EncodedJSValue JIT_OPERATION operationDeleteByIdJSResult(ExecState* exec, EncodedJSValue base, UniquedStringImpl* uid)
2026 {
2027     return JSValue::encode(jsBoolean(operationDeleteById(exec, base, uid)));
2028 }
2029
2030 size_t JIT_OPERATION operationDeleteById(ExecState* exec, EncodedJSValue encodedBase, UniquedStringImpl* uid)
2031 {
2032     VM& vm = exec->vm();
2033     NativeCallFrameTracer tracer(&vm, exec);
2034     auto scope = DECLARE_THROW_SCOPE(vm);
2035
2036     JSObject* baseObj = JSValue::decode(encodedBase).toObject(exec);
2037     RETURN_IF_EXCEPTION(scope, false);
2038     if (!baseObj)
2039         return false;
2040     bool couldDelete = baseObj->methodTable(vm)->deleteProperty(baseObj, exec, Identifier::fromUid(&vm, uid));
2041     RETURN_IF_EXCEPTION(scope, false);
2042     if (!couldDelete && exec->codeBlock()->isStrictMode())
2043         throwTypeError(exec, scope, ASCIILiteral(UnableToDeletePropertyError));
2044     return couldDelete;
2045 }
2046
2047 EncodedJSValue JIT_OPERATION operationDeleteByValJSResult(ExecState* exec, EncodedJSValue base,  EncodedJSValue key)
2048 {
2049     return JSValue::encode(jsBoolean(operationDeleteByVal(exec, base, key)));
2050 }
2051
2052 size_t JIT_OPERATION operationDeleteByVal(ExecState* exec, EncodedJSValue encodedBase, EncodedJSValue encodedKey)
2053 {
2054     VM& vm = exec->vm();
2055     NativeCallFrameTracer tracer(&vm, exec);
2056     auto scope = DECLARE_THROW_SCOPE(vm);
2057
2058     JSObject* baseObj = JSValue::decode(encodedBase).toObject(exec);
2059     RETURN_IF_EXCEPTION(scope, false);
2060     JSValue key = JSValue::decode(encodedKey);
2061     if (!baseObj)
2062         return false;
2063
2064     bool couldDelete;
2065     uint32_t index;
2066     if (key.getUInt32(index))
2067         couldDelete = baseObj->methodTable(vm)->deletePropertyByIndex(baseObj, exec, index);
2068     else {
2069         Identifier property = key.toPropertyKey(exec);
2070         RETURN_IF_EXCEPTION(scope, false);
2071         couldDelete = baseObj->methodTable(vm)->deleteProperty(baseObj, exec, property);
2072     }
2073     RETURN_IF_EXCEPTION(scope, false);
2074     if (!couldDelete && exec->codeBlock()->isStrictMode())
2075         throwTypeError(exec, scope, ASCIILiteral(UnableToDeletePropertyError));
2076     return couldDelete;
2077 }
2078
2079 JSCell* JIT_OPERATION operationPushWithScope(ExecState* exec, JSCell* currentScopeCell, EncodedJSValue objectValue)
2080 {
2081     VM& vm = exec->vm();
2082     NativeCallFrameTracer tracer(&vm, exec);
2083     auto scope = DECLARE_THROW_SCOPE(vm);
2084
2085     JSObject* object = JSValue::decode(objectValue).toObject(exec);
2086     RETURN_IF_EXCEPTION(scope, nullptr);
2087
2088     JSScope* currentScope = jsCast<JSScope*>(currentScopeCell);
2089
2090     return JSWithScope::create(vm, exec->lexicalGlobalObject(), currentScope, object);
2091 }
2092
2093 JSCell* JIT_OPERATION operationPushWithScopeObject(ExecState* exec, JSCell* currentScopeCell, JSObject* object)
2094 {
2095     VM& vm = exec->vm();
2096     NativeCallFrameTracer tracer(&vm, exec);
2097     JSScope* currentScope = jsCast<JSScope*>(currentScopeCell);
2098     return JSWithScope::create(vm, exec->lexicalGlobalObject(), currentScope, object);
2099 }
2100
2101 EncodedJSValue JIT_OPERATION operationInstanceOf(ExecState* exec, EncodedJSValue encodedValue, EncodedJSValue encodedProto)
2102 {
2103     VM& vm = exec->vm();
2104     NativeCallFrameTracer tracer(&vm, exec);
2105     JSValue value = JSValue::decode(encodedValue);
2106     JSValue proto = JSValue::decode(encodedProto);
2107     
2108     bool result = JSObject::defaultHasInstance(exec, value, proto);
2109     return JSValue::encode(jsBoolean(result));
2110 }
2111
2112 int32_t JIT_OPERATION operationSizeFrameForForwardArguments(ExecState* exec, EncodedJSValue, int32_t numUsedStackSlots, int32_t)
2113 {
2114     VM& vm = exec->vm();
2115     NativeCallFrameTracer tracer(&vm, exec);
2116     return sizeFrameForForwardArguments(exec, vm, numUsedStackSlots);
2117 }
2118
2119 int32_t JIT_OPERATION operationSizeFrameForVarargs(ExecState* exec, EncodedJSValue encodedArguments, int32_t numUsedStackSlots, int32_t firstVarArgOffset)
2120 {
2121     VM& vm = exec->vm();
2122     NativeCallFrameTracer tracer(&vm, exec);
2123     JSValue arguments = JSValue::decode(encodedArguments);
2124     return sizeFrameForVarargs(exec, vm, arguments, numUsedStackSlots, firstVarArgOffset);
2125 }
2126
2127 CallFrame* JIT_OPERATION operationSetupForwardArgumentsFrame(ExecState* exec, CallFrame* newCallFrame, EncodedJSValue, int32_t, int32_t length)
2128 {
2129     VM& vm = exec->vm();
2130     NativeCallFrameTracer tracer(&vm, exec);
2131     setupForwardArgumentsFrame(exec, newCallFrame, length);
2132     return newCallFrame;
2133 }
2134
2135 CallFrame* JIT_OPERATION operationSetupVarargsFrame(ExecState* exec, CallFrame* newCallFrame, EncodedJSValue encodedArguments, int32_t firstVarArgOffset, int32_t length)
2136 {
2137     VM& vm = exec->vm();
2138     NativeCallFrameTracer tracer(&vm, exec);
2139     JSValue arguments = JSValue::decode(encodedArguments);
2140     setupVarargsFrame(exec, newCallFrame, arguments, firstVarArgOffset, length);
2141     return newCallFrame;
2142 }
2143
2144 char* JIT_OPERATION operationSwitchCharWithUnknownKeyType(ExecState* exec, EncodedJSValue encodedKey, size_t tableIndex)
2145 {
2146     VM& vm = exec->vm();
2147     NativeCallFrameTracer tracer(&vm, exec);
2148     JSValue key = JSValue::decode(encodedKey);
2149     CodeBlock* codeBlock = exec->codeBlock();
2150
2151     SimpleJumpTable& jumpTable = codeBlock->switchJumpTable(tableIndex);
2152     void* result = jumpTable.ctiDefault.executableAddress();
2153
2154     if (key.isString()) {
2155         StringImpl* value = asString(key)->value(exec).impl();
2156         if (value->length() == 1)
2157             result = jumpTable.ctiForValue((*value)[0]).executableAddress();
2158     }
2159
2160     return reinterpret_cast<char*>(result);
2161 }
2162
2163 char* JIT_OPERATION operationSwitchImmWithUnknownKeyType(ExecState* exec, EncodedJSValue encodedKey, size_t tableIndex)
2164 {
2165     VM& vm = exec->vm();
2166     NativeCallFrameTracer tracer(&vm, exec);
2167     JSValue key = JSValue::decode(encodedKey);
2168     CodeBlock* codeBlock = exec->codeBlock();
2169
2170     SimpleJumpTable& jumpTable = codeBlock->switchJumpTable(tableIndex);
2171     void* result;
2172     if (key.isInt32())
2173         result = jumpTable.ctiForValue(key.asInt32()).executableAddress();
2174     else if (key.isDouble() && key.asDouble() == static_cast<int32_t>(key.asDouble()))
2175         result = jumpTable.ctiForValue(static_cast<int32_t>(key.asDouble())).executableAddress();
2176     else
2177         result = jumpTable.ctiDefault.executableAddress();
2178     return reinterpret_cast<char*>(result);
2179 }
2180
2181 char* JIT_OPERATION operationSwitchStringWithUnknownKeyType(ExecState* exec, EncodedJSValue encodedKey, size_t tableIndex)
2182 {
2183     VM& vm = exec->vm();
2184     NativeCallFrameTracer tracer(&vm, exec);
2185     JSValue key = JSValue::decode(encodedKey);
2186     CodeBlock* codeBlock = exec->codeBlock();
2187
2188     void* result;
2189     StringJumpTable& jumpTable = codeBlock->stringSwitchJumpTable(tableIndex);
2190
2191     if (key.isString()) {
2192         StringImpl* value = asString(key)->value(exec).impl();
2193         result = jumpTable.ctiForValue(value).executableAddress();
2194     } else
2195         result = jumpTable.ctiDefault.executableAddress();
2196
2197     return reinterpret_cast<char*>(result);
2198 }
2199
2200 EncodedJSValue JIT_OPERATION operationGetFromScope(ExecState* exec, Instruction* bytecodePC)
2201 {
2202     VM& vm = exec->vm();
2203     NativeCallFrameTracer tracer(&vm, exec);
2204     auto throwScope = DECLARE_THROW_SCOPE(vm);
2205
2206     CodeBlock* codeBlock = exec->codeBlock();
2207     Instruction* pc = bytecodePC;
2208
2209     const Identifier& ident = codeBlock->identifier(pc[3].u.operand);
2210     JSObject* scope = jsCast<JSObject*>(exec->uncheckedR(pc[2].u.operand).jsValue());
2211     GetPutInfo getPutInfo(pc[4].u.operand);
2212
2213     // ModuleVar is always converted to ClosureVar for get_from_scope.
2214     ASSERT(getPutInfo.resolveType() != ModuleVar);
2215
2216     throwScope.release();
2217     return JSValue::encode(scope->getPropertySlot(exec, ident, [&] (bool found, PropertySlot& slot) -> JSValue {
2218         if (!found) {
2219             if (getPutInfo.resolveMode() == ThrowIfNotFound)
2220                 throwException(exec, throwScope, createUndefinedVariableError(exec, ident));
2221             return jsUndefined();
2222         }
2223
2224         JSValue result = JSValue();
2225         if (scope->isGlobalLexicalEnvironment()) {
2226             // When we can't statically prove we need a TDZ check, we must perform the check on the slow path.
2227             result = slot.getValue(exec, ident);
2228             if (result == jsTDZValue()) {
2229                 throwException(exec, throwScope, createTDZError(exec));
2230                 return jsUndefined();
2231             }
2232         }
2233
2234         CommonSlowPaths::tryCacheGetFromScopeGlobal(exec, vm, pc, scope, slot, ident);
2235
2236         if (!result)
2237             return slot.getValue(exec, ident);
2238         return result;
2239     }));
2240 }
2241
2242 void JIT_OPERATION operationPutToScope(ExecState* exec, Instruction* bytecodePC)
2243 {
2244     VM& vm = exec->vm();
2245     NativeCallFrameTracer tracer(&vm, exec);
2246     auto throwScope = DECLARE_THROW_SCOPE(vm);
2247
2248     Instruction* pc = bytecodePC;
2249
2250     CodeBlock* codeBlock = exec->codeBlock();
2251     const Identifier& ident = codeBlock->identifier(pc[2].u.operand);
2252     JSObject* scope = jsCast<JSObject*>(exec->uncheckedR(pc[1].u.operand).jsValue());
2253     JSValue value = exec->r(pc[3].u.operand).jsValue();
2254     GetPutInfo getPutInfo = GetPutInfo(pc[4].u.operand);
2255
2256     // ModuleVar does not keep the scope register value alive in DFG.
2257     ASSERT(getPutInfo.resolveType() != ModuleVar);
2258
2259     if (getPutInfo.resolveType() == LocalClosureVar) {
2260         JSLexicalEnvironment* environment = jsCast<JSLexicalEnvironment*>(scope);
2261         environment->variableAt(ScopeOffset(pc[6].u.operand)).set(vm, environment, value);
2262         if (WatchpointSet* set = pc[5].u.watchpointSet)
2263             set->touch(vm, "Executed op_put_scope<LocalClosureVar>");
2264         return;
2265     }
2266
2267     bool hasProperty = scope->hasProperty(exec, ident);
2268     EXCEPTION_ASSERT(!throwScope.exception() || !hasProperty);
2269     if (hasProperty
2270         && scope->isGlobalLexicalEnvironment()
2271         && !isInitialization(getPutInfo.initializationMode())) {
2272         // When we can't statically prove we need a TDZ check, we must perform the check on the slow path.
2273         PropertySlot slot(scope, PropertySlot::InternalMethodType::Get);
2274         JSGlobalLexicalEnvironment::getOwnPropertySlot(scope, exec, ident, slot);
2275         if (slot.getValue(exec, ident) == jsTDZValue()) {
2276             throwException(exec, throwScope, createTDZError(exec));
2277             return;
2278         }
2279     }
2280
2281     if (getPutInfo.resolveMode() == ThrowIfNotFound && !hasProperty) {
2282         throwException(exec, throwScope, createUndefinedVariableError(exec, ident));
2283         return;
2284     }
2285
2286     PutPropertySlot slot(scope, codeBlock->isStrictMode(), PutPropertySlot::UnknownContext, isInitialization(getPutInfo.initializationMode()));
2287     scope->methodTable(vm)->put(scope, exec, ident, value, slot);
2288     
2289     RETURN_IF_EXCEPTION(throwScope, void());
2290
2291     CommonSlowPaths::tryCachePutToScopeGlobal(exec, codeBlock, pc, scope, getPutInfo, slot, ident);
2292 }
2293
2294 void JIT_OPERATION operationThrow(ExecState* exec, EncodedJSValue encodedExceptionValue)
2295 {
2296     VM* vm = &exec->vm();
2297     NativeCallFrameTracer tracer(vm, exec);
2298     auto scope = DECLARE_THROW_SCOPE(*vm);
2299
2300     JSValue exceptionValue = JSValue::decode(encodedExceptionValue);
2301     throwException(exec, scope, exceptionValue);
2302
2303     // Results stored out-of-band in vm.targetMachinePCForThrow & vm.callFrameForCatch
2304     genericUnwind(vm, exec);
2305 }
2306
2307 char* JIT_OPERATION operationReallocateButterflyToHavePropertyStorageWithInitialCapacity(ExecState* exec, JSObject* object)
2308 {
2309     VM& vm = exec->vm();
2310     NativeCallFrameTracer tracer(&vm, exec);
2311
2312     ASSERT(!object->structure()->outOfLineCapacity());
2313     Butterfly* result = object->allocateMoreOutOfLineStorage(vm, 0, initialOutOfLineCapacity);
2314     object->nukeStructureAndSetButterfly(vm, object->structureID(), result);
2315     return reinterpret_cast<char*>(result);
2316 }
2317
2318 char* JIT_OPERATION operationReallocateButterflyToGrowPropertyStorage(ExecState* exec, JSObject* object, size_t newSize)
2319 {
2320     VM& vm = exec->vm();
2321     NativeCallFrameTracer tracer(&vm, exec);
2322
2323     Butterfly* result = object->allocateMoreOutOfLineStorage(vm, object->structure()->outOfLineCapacity(), newSize);
2324     object->nukeStructureAndSetButterfly(vm, object->structureID(), result);
2325     return reinterpret_cast<char*>(result);
2326 }
2327
2328 void JIT_OPERATION operationOSRWriteBarrier(ExecState* exec, JSCell* cell)
2329 {
2330     VM* vm = &exec->vm();
2331     NativeCallFrameTracer tracer(vm, exec);
2332     vm->heap.writeBarrier(cell);
2333 }
2334
2335 void JIT_OPERATION operationWriteBarrierSlowPath(ExecState* exec, JSCell* cell)
2336 {
2337     VM* vm = &exec->vm();
2338     NativeCallFrameTracer tracer(vm, exec);
2339     vm->heap.writeBarrierSlowPath(cell);
2340 }
2341
2342 void JIT_OPERATION lookupExceptionHandler(VM* vm, ExecState* exec)
2343 {
2344     NativeCallFrameTracer tracer(vm, exec);
2345     genericUnwind(vm, exec);
2346     ASSERT(vm->targetMachinePCForThrow);
2347 }
2348
2349 void JIT_OPERATION lookupExceptionHandlerFromCallerFrame(VM* vm, ExecState* exec)
2350 {
2351     vm->topCallFrame = exec->callerFrame();
2352     genericUnwind(vm, exec, UnwindFromCallerFrame);
2353     ASSERT(vm->targetMachinePCForThrow);
2354 }
2355
2356 void JIT_OPERATION operationVMHandleException(ExecState* exec)
2357 {
2358     VM* vm = &exec->vm();
2359     NativeCallFrameTracer tracer(vm, exec);
2360     genericUnwind(vm, exec);
2361 }
2362
2363 // This function "should" just take the ExecState*, but doing so would make it more difficult
2364 // to call from exception check sites. So, unlike all of our other functions, we allow
2365 // ourselves to play some gnarly ABI tricks just to simplify the calling convention. This is
2366 // particularly safe here since this is never called on the critical path - it's only for
2367 // testing.
2368 void JIT_OPERATION operationExceptionFuzz(ExecState* exec)
2369 {
2370     VM* vm = &exec->vm();
2371     NativeCallFrameTracer tracer(vm, exec);
2372     auto scope = DECLARE_THROW_SCOPE(*vm);
2373     UNUSED_PARAM(scope);
2374 #if COMPILER(GCC_OR_CLANG)
2375     void* returnPC = __builtin_return_address(0);
2376     doExceptionFuzzing(exec, scope, "JITOperations", returnPC);
2377 #endif // COMPILER(GCC_OR_CLANG)
2378 }
2379
2380 EncodedJSValue JIT_OPERATION operationHasGenericProperty(ExecState* exec, EncodedJSValue encodedBaseValue, JSCell* propertyName)
2381 {
2382     VM& vm = exec->vm();
2383     NativeCallFrameTracer tracer(&vm, exec);
2384     JSValue baseValue = JSValue::decode(encodedBaseValue);
2385     if (baseValue.isUndefinedOrNull())
2386         return JSValue::encode(jsBoolean(false));
2387
2388     JSObject* base = baseValue.toObject(exec);
2389     if (!base)
2390         return JSValue::encode(JSValue());
2391     return JSValue::encode(jsBoolean(base->hasPropertyGeneric(exec, asString(propertyName)->toIdentifier(exec), PropertySlot::InternalMethodType::GetOwnProperty)));
2392 }
2393
2394 JSCell* JIT_OPERATION operationGetPropertyEnumerator(ExecState* exec, JSCell* cell)
2395 {
2396     VM& vm = exec->vm();
2397     NativeCallFrameTracer tracer(&vm, exec);
2398     auto scope = DECLARE_THROW_SCOPE(vm);
2399
2400     JSObject* base = cell->toObject(exec, exec->lexicalGlobalObject());
2401     RETURN_IF_EXCEPTION(scope, { });
2402
2403     scope.release();
2404     return propertyNameEnumerator(exec, base);
2405 }
2406
2407 EncodedJSValue JIT_OPERATION operationNextEnumeratorPname(ExecState* exec, JSCell* enumeratorCell, int32_t index)
2408 {
2409     VM& vm = exec->vm();
2410     NativeCallFrameTracer tracer(&vm, exec);
2411     JSPropertyNameEnumerator* enumerator = jsCast<JSPropertyNameEnumerator*>(enumeratorCell);
2412     JSString* propertyName = enumerator->propertyNameAtIndex(index);
2413     return JSValue::encode(propertyName ? propertyName : jsNull());
2414 }
2415
2416 JSCell* JIT_OPERATION operationToIndexString(ExecState* exec, int32_t index)
2417 {
2418     VM& vm = exec->vm();
2419     NativeCallFrameTracer tracer(&vm, exec);
2420     return jsString(exec, Identifier::from(exec, index).string());
2421 }
2422
2423 ALWAYS_INLINE static EncodedJSValue unprofiledAdd(ExecState* exec, EncodedJSValue encodedOp1, EncodedJSValue encodedOp2)
2424 {
2425     VM* vm = &exec->vm();
2426     NativeCallFrameTracer tracer(vm, exec);
2427     
2428     JSValue op1 = JSValue::decode(encodedOp1);
2429     JSValue op2 = JSValue::decode(encodedOp2);
2430     
2431     return JSValue::encode(jsAdd(exec, op1, op2));
2432 }
2433
2434 ALWAYS_INLINE static EncodedJSValue profiledAdd(ExecState* exec, EncodedJSValue encodedOp1, EncodedJSValue encodedOp2, ArithProfile& arithProfile)
2435 {
2436     VM* vm = &exec->vm();
2437     NativeCallFrameTracer tracer(vm, exec);
2438     
2439     JSValue op1 = JSValue::decode(encodedOp1);
2440     JSValue op2 = JSValue::decode(encodedOp2);
2441
2442     arithProfile.observeLHSAndRHS(op1, op2);
2443     JSValue result = jsAdd(exec, op1, op2);
2444     arithProfile.observeResult(result);
2445
2446     return JSValue::encode(result);
2447 }
2448
2449 EncodedJSValue JIT_OPERATION operationValueAdd(ExecState* exec, EncodedJSValue encodedOp1, EncodedJSValue encodedOp2)
2450 {
2451     return unprofiledAdd(exec, encodedOp1, encodedOp2);
2452 }
2453
2454 EncodedJSValue JIT_OPERATION operationValueAddProfiled(ExecState* exec, EncodedJSValue encodedOp1, EncodedJSValue encodedOp2, ArithProfile* arithProfile)
2455 {
2456     ASSERT(arithProfile);
2457     return profiledAdd(exec, encodedOp1, encodedOp2, *arithProfile);
2458 }
2459
2460 EncodedJSValue JIT_OPERATION operationValueAddProfiledOptimize(ExecState* exec, EncodedJSValue encodedOp1, EncodedJSValue encodedOp2, JITAddIC* addIC)
2461 {
2462     VM* vm = &exec->vm();
2463     NativeCallFrameTracer tracer(vm, exec);
2464     
2465     JSValue op1 = JSValue::decode(encodedOp1);
2466     JSValue op2 = JSValue::decode(encodedOp2);
2467
2468     ArithProfile* arithProfile = addIC->arithProfile();
2469     ASSERT(arithProfile);
2470     arithProfile->observeLHSAndRHS(op1, op2);
2471     auto nonOptimizeVariant = operationValueAddProfiledNoOptimize;
2472     addIC->generateOutOfLine(exec->codeBlock(), nonOptimizeVariant);
2473
2474 #if ENABLE(MATH_IC_STATS)
2475     exec->codeBlock()->dumpMathICStats();
2476 #endif
2477     
2478     JSValue result = jsAdd(exec, op1, op2);
2479     arithProfile->observeResult(result);
2480
2481     return JSValue::encode(result);
2482 }
2483
2484 EncodedJSValue JIT_OPERATION operationValueAddProfiledNoOptimize(ExecState* exec, EncodedJSValue encodedOp1, EncodedJSValue encodedOp2, JITAddIC* addIC)
2485 {
2486     VM* vm = &exec->vm();
2487     NativeCallFrameTracer tracer(vm, exec);
2488
2489     ArithProfile* arithProfile = addIC->arithProfile();
2490     ASSERT(arithProfile);
2491     return profiledAdd(exec, encodedOp1, encodedOp2, *arithProfile);
2492 }
2493
2494 EncodedJSValue JIT_OPERATION operationValueAddOptimize(ExecState* exec, EncodedJSValue encodedOp1, EncodedJSValue encodedOp2, JITAddIC* addIC)
2495 {
2496     VM* vm = &exec->vm();
2497     NativeCallFrameTracer tracer(vm, exec);
2498
2499     JSValue op1 = JSValue::decode(encodedOp1);
2500     JSValue op2 = JSValue::decode(encodedOp2);
2501
2502     auto nonOptimizeVariant = operationValueAddNoOptimize;
2503     if (ArithProfile* arithProfile = addIC->arithProfile())
2504         arithProfile->observeLHSAndRHS(op1, op2);
2505     addIC->generateOutOfLine(exec->codeBlock(), nonOptimizeVariant);
2506
2507 #if ENABLE(MATH_IC_STATS)
2508     exec->codeBlock()->dumpMathICStats();
2509 #endif
2510
2511     return JSValue::encode(jsAdd(exec, op1, op2));
2512 }
2513
2514 EncodedJSValue JIT_OPERATION operationValueAddNoOptimize(ExecState* exec, EncodedJSValue encodedOp1, EncodedJSValue encodedOp2, JITAddIC*)
2515 {
2516     VM* vm = &exec->vm();
2517     NativeCallFrameTracer tracer(vm, exec);
2518     
2519     JSValue op1 = JSValue::decode(encodedOp1);
2520     JSValue op2 = JSValue::decode(encodedOp2);
2521     
2522     JSValue result = jsAdd(exec, op1, op2);
2523
2524     return JSValue::encode(result);
2525 }
2526
2527 ALWAYS_INLINE static EncodedJSValue unprofiledMul(VM& vm, ExecState* exec, EncodedJSValue encodedOp1, EncodedJSValue encodedOp2)
2528 {
2529     auto scope = DECLARE_THROW_SCOPE(vm);
2530     JSValue op1 = JSValue::decode(encodedOp1);
2531     JSValue op2 = JSValue::decode(encodedOp2);
2532
2533     double a = op1.toNumber(exec);
2534     RETURN_IF_EXCEPTION(scope, encodedJSValue());
2535     scope.release();
2536     double b = op2.toNumber(exec);
2537     return JSValue::encode(jsNumber(a * b));
2538 }
2539
2540 ALWAYS_INLINE static EncodedJSValue profiledMul(VM& vm, ExecState* exec, EncodedJSValue encodedOp1, EncodedJSValue encodedOp2, ArithProfile& arithProfile, bool shouldObserveLHSAndRHSTypes = true)
2541 {
2542     auto scope = DECLARE_THROW_SCOPE(vm);
2543     JSValue op1 = JSValue::decode(encodedOp1);
2544     JSValue op2 = JSValue::decode(encodedOp2);
2545
2546     if (shouldObserveLHSAndRHSTypes)
2547         arithProfile.observeLHSAndRHS(op1, op2);
2548
2549     double a = op1.toNumber(exec);
2550     RETURN_IF_EXCEPTION(scope, encodedJSValue());
2551     double b = op2.toNumber(exec);
2552     RETURN_IF_EXCEPTION(scope, encodedJSValue());
2553     
2554     JSValue result = jsNumber(a * b);
2555     arithProfile.observeResult(result);
2556     return JSValue::encode(result);
2557 }
2558
2559 EncodedJSValue JIT_OPERATION operationValueMul(ExecState* exec, EncodedJSValue encodedOp1, EncodedJSValue encodedOp2)
2560 {
2561     VM* vm = &exec->vm();
2562     NativeCallFrameTracer tracer(vm, exec);
2563
2564     return unprofiledMul(*vm, exec, encodedOp1, encodedOp2);
2565 }
2566
2567 EncodedJSValue JIT_OPERATION operationValueMulNoOptimize(ExecState* exec, EncodedJSValue encodedOp1, EncodedJSValue encodedOp2, JITMulIC*)
2568 {
2569     VM* vm = &exec->vm();
2570     NativeCallFrameTracer tracer(vm, exec);
2571
2572     return unprofiledMul(*vm, exec, encodedOp1, encodedOp2);
2573 }
2574
2575 EncodedJSValue JIT_OPERATION operationValueMulOptimize(ExecState* exec, EncodedJSValue encodedOp1, EncodedJSValue encodedOp2, JITMulIC* mulIC)
2576 {
2577     VM* vm = &exec->vm();
2578     NativeCallFrameTracer tracer(vm, exec);
2579
2580     auto nonOptimizeVariant = operationValueMulNoOptimize;
2581     if (ArithProfile* arithProfile = mulIC->arithProfile())
2582         arithProfile->observeLHSAndRHS(JSValue::decode(encodedOp1), JSValue::decode(encodedOp2));
2583     mulIC->generateOutOfLine(exec->codeBlock(), nonOptimizeVariant);
2584
2585 #if ENABLE(MATH_IC_STATS)
2586     exec->codeBlock()->dumpMathICStats();
2587 #endif
2588
2589     return unprofiledMul(*vm, exec, encodedOp1, encodedOp2);
2590 }
2591
2592 EncodedJSValue JIT_OPERATION operationValueMulProfiled(ExecState* exec, EncodedJSValue encodedOp1, EncodedJSValue encodedOp2, ArithProfile* arithProfile)
2593 {
2594     VM* vm = &exec->vm();
2595     NativeCallFrameTracer tracer(vm, exec);
2596
2597     ASSERT(arithProfile);
2598     return profiledMul(*vm, exec, encodedOp1, encodedOp2, *arithProfile);
2599 }
2600
2601 EncodedJSValue JIT_OPERATION operationValueMulProfiledOptimize(ExecState* exec, EncodedJSValue encodedOp1, EncodedJSValue encodedOp2, JITMulIC* mulIC)
2602 {
2603     VM* vm = &exec->vm();
2604     NativeCallFrameTracer tracer(vm, exec);
2605
2606     ArithProfile* arithProfile = mulIC->arithProfile();
2607     ASSERT(arithProfile);
2608     arithProfile->observeLHSAndRHS(JSValue::decode(encodedOp1), JSValue::decode(encodedOp2));
2609     auto nonOptimizeVariant = operationValueMulProfiledNoOptimize;
2610     mulIC->generateOutOfLine(exec->codeBlock(), nonOptimizeVariant);
2611
2612 #if ENABLE(MATH_IC_STATS)
2613     exec->codeBlock()->dumpMathICStats();
2614 #endif
2615
2616     return profiledMul(*vm, exec, encodedOp1, encodedOp2, *arithProfile, false);
2617 }
2618
2619 EncodedJSValue JIT_OPERATION operationValueMulProfiledNoOptimize(ExecState* exec, EncodedJSValue encodedOp1, EncodedJSValue encodedOp2, JITMulIC* mulIC)
2620 {
2621     VM* vm = &exec->vm();
2622     NativeCallFrameTracer tracer(vm, exec);
2623
2624     ArithProfile* arithProfile = mulIC->arithProfile();
2625     ASSERT(arithProfile);
2626     return profiledMul(*vm, exec, encodedOp1, encodedOp2, *arithProfile);
2627 }
2628
2629 ALWAYS_INLINE static EncodedJSValue unprofiledNegate(ExecState* exec, EncodedJSValue encodedOperand)
2630 {
2631     VM& vm = exec->vm();
2632     auto scope = DECLARE_THROW_SCOPE(vm);
2633     NativeCallFrameTracer tracer(&vm, exec);
2634     
2635     JSValue operand = JSValue::decode(encodedOperand);
2636     double number = operand.toNumber(exec);
2637     RETURN_IF_EXCEPTION(scope, encodedJSValue());
2638     return JSValue::encode(jsNumber(-number));
2639 }
2640
2641 ALWAYS_INLINE static EncodedJSValue profiledNegate(ExecState* exec, EncodedJSValue encodedOperand, ArithProfile& arithProfile)
2642 {
2643     VM& vm = exec->vm();
2644     auto scope = DECLARE_THROW_SCOPE(vm);
2645     NativeCallFrameTracer tracer(&vm, exec);
2646
2647     JSValue operand = JSValue::decode(encodedOperand);
2648     arithProfile.observeLHS(operand);
2649     double number = operand.toNumber(exec);
2650     RETURN_IF_EXCEPTION(scope, encodedJSValue());
2651
2652     JSValue result = jsNumber(-number);
2653     arithProfile.observeResult(result);
2654     return JSValue::encode(result);
2655 }
2656
2657 EncodedJSValue JIT_OPERATION operationArithNegate(ExecState* exec, EncodedJSValue operand)
2658 {
2659     return unprofiledNegate(exec, operand);
2660 }
2661
2662 EncodedJSValue JIT_OPERATION operationArithNegateProfiled(ExecState* exec, EncodedJSValue operand, ArithProfile* arithProfile)
2663 {
2664     ASSERT(arithProfile);
2665     return profiledNegate(exec, operand, *arithProfile);
2666 }
2667
2668 EncodedJSValue JIT_OPERATION operationArithNegateProfiledOptimize(ExecState* exec, EncodedJSValue encodedOperand, JITNegIC* negIC)
2669 {
2670     VM& vm = exec->vm();
2671     auto scope = DECLARE_THROW_SCOPE(vm);
2672     NativeCallFrameTracer tracer(&vm, exec);
2673     
2674     JSValue operand = JSValue::decode(encodedOperand);
2675
2676     ArithProfile* arithProfile = negIC->arithProfile();
2677     ASSERT(arithProfile);
2678     arithProfile->observeLHS(operand);
2679     negIC->generateOutOfLine(exec->codeBlock(), operationArithNegateProfiled);
2680
2681 #if ENABLE(MATH_IC_STATS)
2682     exec->codeBlock()->dumpMathICStats();
2683 #endif
2684     
2685     double number = operand.toNumber(exec);
2686     RETURN_IF_EXCEPTION(scope, encodedJSValue());
2687     JSValue result = jsNumber(-number);
2688     arithProfile->observeResult(result);
2689     return JSValue::encode(result);
2690 }
2691
2692 EncodedJSValue JIT_OPERATION operationArithNegateOptimize(ExecState* exec, EncodedJSValue encodedOperand, JITNegIC* negIC)
2693 {
2694     VM& vm = exec->vm();
2695     auto scope = DECLARE_THROW_SCOPE(vm);
2696     NativeCallFrameTracer tracer(&vm, exec);
2697
2698     JSValue operand = JSValue::decode(encodedOperand);
2699
2700     if (ArithProfile* arithProfile = negIC->arithProfile())
2701         arithProfile->observeLHS(operand);
2702     negIC->generateOutOfLine(exec->codeBlock(), operationArithNegate);
2703
2704 #if ENABLE(MATH_IC_STATS)
2705     exec->codeBlock()->dumpMathICStats();
2706 #endif
2707
2708     double number = operand.toNumber(exec);
2709     RETURN_IF_EXCEPTION(scope, encodedJSValue());
2710     return JSValue::encode(jsNumber(-number));
2711 }
2712
2713 ALWAYS_INLINE static EncodedJSValue unprofiledSub(VM& vm, ExecState* exec, EncodedJSValue encodedOp1, EncodedJSValue encodedOp2)
2714 {
2715     auto scope = DECLARE_THROW_SCOPE(vm);
2716     JSValue op1 = JSValue::decode(encodedOp1);
2717     JSValue op2 = JSValue::decode(encodedOp2);
2718
2719     double a = op1.toNumber(exec);
2720     RETURN_IF_EXCEPTION(scope, encodedJSValue());
2721     scope.release();
2722     double b = op2.toNumber(exec);
2723     return JSValue::encode(jsNumber(a - b));
2724 }
2725
2726 ALWAYS_INLINE static EncodedJSValue profiledSub(VM& vm, ExecState* exec, EncodedJSValue encodedOp1, EncodedJSValue encodedOp2, ArithProfile& arithProfile, bool shouldObserveLHSAndRHSTypes = true)
2727 {
2728     auto scope = DECLARE_THROW_SCOPE(vm);
2729     JSValue op1 = JSValue::decode(encodedOp1);
2730     JSValue op2 = JSValue::decode(encodedOp2);
2731
2732     if (shouldObserveLHSAndRHSTypes)
2733         arithProfile.observeLHSAndRHS(op1, op2);
2734
2735     double a = op1.toNumber(exec);
2736     RETURN_IF_EXCEPTION(scope, encodedJSValue());
2737     double b = op2.toNumber(exec);
2738     RETURN_IF_EXCEPTION(scope, encodedJSValue());
2739     
2740     JSValue result = jsNumber(a - b);
2741     arithProfile.observeResult(result);
2742     return JSValue::encode(result);
2743 }
2744
2745 EncodedJSValue JIT_OPERATION operationValueSub(ExecState* exec, EncodedJSValue encodedOp1, EncodedJSValue encodedOp2)
2746 {
2747     VM* vm = &exec->vm();
2748     NativeCallFrameTracer tracer(vm, exec);
2749     return unprofiledSub(*vm, exec, encodedOp1, encodedOp2);
2750 }
2751
2752 EncodedJSValue JIT_OPERATION operationValueSubProfiled(ExecState* exec, EncodedJSValue encodedOp1, EncodedJSValue encodedOp2, ArithProfile* arithProfile)
2753 {
2754     ASSERT(arithProfile);
2755
2756     VM* vm = &exec->vm();
2757     NativeCallFrameTracer tracer(vm, exec);
2758
2759     return profiledSub(*vm, exec, encodedOp1, encodedOp2, *arithProfile);
2760 }
2761
2762 EncodedJSValue JIT_OPERATION operationValueSubOptimize(ExecState* exec, EncodedJSValue encodedOp1, EncodedJSValue encodedOp2, JITSubIC* subIC)
2763 {
2764     VM* vm = &exec->vm();
2765     NativeCallFrameTracer tracer(vm, exec);
2766
2767     auto nonOptimizeVariant = operationValueSubNoOptimize;
2768     if (ArithProfile* arithProfile = subIC->arithProfile())
2769         arithProfile->observeLHSAndRHS(JSValue::decode(encodedOp1), JSValue::decode(encodedOp2));
2770     subIC->generateOutOfLine(exec->codeBlock(), nonOptimizeVariant);
2771
2772 #if ENABLE(MATH_IC_STATS)
2773     exec->codeBlock()->dumpMathICStats();
2774 #endif
2775
2776     return unprofiledSub(*vm, exec, encodedOp1, encodedOp2);
2777 }
2778
2779 EncodedJSValue JIT_OPERATION operationValueSubNoOptimize(ExecState* exec, EncodedJSValue encodedOp1, EncodedJSValue encodedOp2, JITSubIC*)
2780 {
2781     VM* vm = &exec->vm();
2782     NativeCallFrameTracer tracer(vm, exec);
2783
2784     return unprofiledSub(*vm, exec, encodedOp1, encodedOp2);
2785 }
2786
2787 EncodedJSValue JIT_OPERATION operationValueSubProfiledOptimize(ExecState* exec, EncodedJSValue encodedOp1, EncodedJSValue encodedOp2, JITSubIC* subIC)
2788 {
2789     VM* vm = &exec->vm();
2790     NativeCallFrameTracer tracer(vm, exec);
2791
2792     ArithProfile* arithProfile = subIC->arithProfile();
2793     ASSERT(arithProfile);
2794     arithProfile->observeLHSAndRHS(JSValue::decode(encodedOp1), JSValue::decode(encodedOp2));
2795     auto nonOptimizeVariant = operationValueSubProfiledNoOptimize;
2796     subIC->generateOutOfLine(exec->codeBlock(), nonOptimizeVariant);
2797
2798 #if ENABLE(MATH_IC_STATS)
2799     exec->codeBlock()->dumpMathICStats();
2800 #endif
2801
2802     return profiledSub(*vm, exec, encodedOp1, encodedOp2, *arithProfile, false);
2803 }
2804
2805 EncodedJSValue JIT_OPERATION operationValueSubProfiledNoOptimize(ExecState* exec, EncodedJSValue encodedOp1, EncodedJSValue encodedOp2, JITSubIC* subIC)
2806 {
2807     VM* vm = &exec->vm();
2808     NativeCallFrameTracer tracer(vm, exec);
2809
2810     ArithProfile* arithProfile = subIC->arithProfile();
2811     ASSERT(arithProfile);
2812     return profiledSub(*vm, exec, encodedOp1, encodedOp2, *arithProfile);
2813 }
2814
2815 void JIT_OPERATION operationProcessTypeProfilerLog(ExecState* exec)
2816 {
2817     VM& vm = exec->vm();
2818     NativeCallFrameTracer tracer(&vm, exec);
2819     vm.typeProfilerLog()->processLogEntries(ASCIILiteral("Log Full, called from inside baseline JIT"));
2820 }
2821
2822 void JIT_OPERATION operationProcessShadowChickenLog(ExecState* exec)
2823 {
2824     VM& vm = exec->vm();
2825     NativeCallFrameTracer tracer(&vm, exec);
2826     vm.shadowChicken().update(vm, exec);
2827 }
2828
2829 int32_t JIT_OPERATION operationCheckIfExceptionIsUncatchableAndNotifyProfiler(ExecState* exec)
2830 {
2831     VM& vm = exec->vm();
2832     NativeCallFrameTracer tracer(&vm, exec);
2833     auto scope = DECLARE_THROW_SCOPE(vm);
2834     RELEASE_ASSERT(!!scope.exception());
2835
2836     if (isTerminatedExecutionException(vm, scope.exception())) {
2837         genericUnwind(&vm, exec);
2838         return 1;
2839     }
2840     return 0;
2841 }
2842
2843 } // extern "C"
2844
2845 // Note: getHostCallReturnValueWithExecState() needs to be placed before the
2846 // definition of getHostCallReturnValue() below because the Windows build
2847 // requires it.
2848 extern "C" EncodedJSValue HOST_CALL_RETURN_VALUE_OPTION getHostCallReturnValueWithExecState(ExecState* exec)
2849 {
2850     if (!exec)
2851         return JSValue::encode(JSValue());
2852     return JSValue::encode(exec->vm().hostCallReturnValue);
2853 }
2854
2855 #if COMPILER(GCC_OR_CLANG) && CPU(X86_64)
2856 asm (
2857 ".globl " SYMBOL_STRING(getHostCallReturnValue) "\n"
2858 HIDE_SYMBOL(getHostCallReturnValue) "\n"
2859 SYMBOL_STRING(getHostCallReturnValue) ":" "\n"
2860     "lea -8(%rsp), %rdi\n"
2861     "jmp " LOCAL_REFERENCE(getHostCallReturnValueWithExecState) "\n"
2862 );
2863
2864 #elif COMPILER(GCC_OR_CLANG) && CPU(X86)
2865 asm (
2866 ".text" "\n" \
2867 ".globl " SYMBOL_STRING(getHostCallReturnValue) "\n"
2868 HIDE_SYMBOL(getHostCallReturnValue) "\n"
2869 SYMBOL_STRING(getHostCallReturnValue) ":" "\n"
2870     "push %ebp\n"
2871     "mov %esp, %eax\n"
2872     "leal -4(%esp), %esp\n"
2873     "push %eax\n"
2874     "call " LOCAL_REFERENCE(getHostCallReturnValueWithExecState) "\n"
2875     "leal 8(%esp), %esp\n"
2876     "pop %ebp\n"
2877     "ret\n"
2878 );
2879
2880 #elif COMPILER(GCC_OR_CLANG) && CPU(ARM_THUMB2)
2881 asm (
2882 ".text" "\n"
2883 ".align 2" "\n"
2884 ".globl " SYMBOL_STRING(getHostCallReturnValue) "\n"
2885 HIDE_SYMBOL(getHostCallReturnValue) "\n"
2886 ".thumb" "\n"
2887 ".thumb_func " THUMB_FUNC_PARAM(getHostCallReturnValue) "\n"
2888 SYMBOL_STRING(getHostCallReturnValue) ":" "\n"
2889     "sub r0, sp, #8" "\n"
2890     "b " LOCAL_REFERENCE(getHostCallReturnValueWithExecState) "\n"
2891 );
2892
2893 #elif COMPILER(GCC_OR_CLANG) && CPU(ARM_TRADITIONAL)
2894 asm (
2895 ".text" "\n"
2896 ".globl " SYMBOL_STRING(getHostCallReturnValue) "\n"
2897 HIDE_SYMBOL(getHostCallReturnValue) "\n"
2898 INLINE_ARM_FUNCTION(getHostCallReturnValue)
2899 SYMBOL_STRING(getHostCallReturnValue) ":" "\n"
2900     "sub r0, sp, #8" "\n"
2901     "b " LOCAL_REFERENCE(getHostCallReturnValueWithExecState) "\n"
2902 );
2903
2904 #elif CPU(ARM64)
2905 asm (
2906 ".text" "\n"
2907 ".align 2" "\n"
2908 ".globl " SYMBOL_STRING(getHostCallReturnValue) "\n"
2909 HIDE_SYMBOL(getHostCallReturnValue) "\n"
2910 SYMBOL_STRING(getHostCallReturnValue) ":" "\n"
2911      "sub x0, sp, #16" "\n"
2912      "b " LOCAL_REFERENCE(getHostCallReturnValueWithExecState) "\n"
2913 );
2914
2915 #elif COMPILER(GCC_OR_CLANG) && CPU(MIPS)
2916
2917 #if WTF_MIPS_PIC
2918 #define LOAD_FUNCTION_TO_T9(function) \
2919         ".set noreorder" "\n" \
2920         ".cpload $25" "\n" \
2921         ".set reorder" "\n" \
2922         "la $t9, " LOCAL_REFERENCE(function) "\n"
2923 #else
2924 #define LOAD_FUNCTION_TO_T9(function) "" "\n"
2925 #endif
2926
2927 asm (
2928 ".text" "\n"
2929 ".globl " SYMBOL_STRING(getHostCallReturnValue) "\n"
2930 HIDE_SYMBOL(getHostCallReturnValue) "\n"
2931 SYMBOL_STRING(getHostCallReturnValue) ":" "\n"
2932     LOAD_FUNCTION_TO_T9(getHostCallReturnValueWithExecState)
2933     "addi $a0, $sp, -8" "\n"
2934     "b " LOCAL_REFERENCE(getHostCallReturnValueWithExecState) "\n"
2935 );
2936
2937 #elif COMPILER(MSVC) && CPU(X86)
2938 extern "C" {
2939     __declspec(naked) EncodedJSValue HOST_CALL_RETURN_VALUE_OPTION getHostCallReturnValue()
2940     {
2941         __asm lea eax, [esp - 4]
2942         __asm mov [esp + 4], eax;
2943         __asm jmp getHostCallReturnValueWithExecState
2944     }
2945 }
2946 #endif
2947
2948 } // namespace JSC
2949
2950 #endif // ENABLE(JIT)