AssemblyHelpers should not have a VM field
[WebKit-https.git] / Source / JavaScriptCore / jit / JIT.cpp
1 /*
2  * Copyright (C) 2008-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
28 #if ENABLE(JIT)
29
30 #include "JIT.h"
31
32 #include "BytecodeGraph.h"
33 #include "CodeBlock.h"
34 #include "CodeBlockWithJITType.h"
35 #include "DFGCapabilities.h"
36 #include "Interpreter.h"
37 #include "JITInlines.h"
38 #include "JITOperations.h"
39 #include "JSArray.h"
40 #include "JSCInlines.h"
41 #include "JSFunction.h"
42 #include "LinkBuffer.h"
43 #include "MaxFrameExtentForSlowPathCall.h"
44 #include "PCToCodeOriginMap.h"
45 #include "ProfilerDatabase.h"
46 #include "ProgramCodeBlock.h"
47 #include "ResultType.h"
48 #include "SlowPathCall.h"
49 #include "StackAlignment.h"
50 #include "TypeProfilerLog.h"
51 #include <wtf/CryptographicallyRandomNumber.h>
52 #include <wtf/GraphNodeWorklist.h>
53 #include <wtf/SimpleStats.h>
54
55 using namespace std;
56
57 namespace JSC {
58
59 double totalBaselineCompileTime;
60 double totalDFGCompileTime;
61 double totalFTLCompileTime;
62 double totalFTLDFGCompileTime;
63 double totalFTLB3CompileTime;
64
65 void ctiPatchCallByReturnAddress(ReturnAddressPtr returnAddress, FunctionPtr newCalleeFunction)
66 {
67     MacroAssembler::repatchCall(
68         CodeLocationCall(MacroAssemblerCodePtr(returnAddress)),
69         newCalleeFunction);
70 }
71
72 JIT::CodeRef JIT::compileCTINativeCall(VM* vm, NativeFunction func)
73 {
74     if (!vm->canUseJIT())
75         return CodeRef::createLLIntCodeRef(llint_native_call_trampoline);
76     JIT jit(vm, 0);
77     return jit.privateCompileCTINativeCall(vm, func);
78 }
79
80 JIT::JIT(VM* vm, CodeBlock* codeBlock, unsigned loopOSREntryBytecodeOffset)
81     : JSInterfaceJIT(vm, codeBlock)
82     , m_interpreter(vm->interpreter)
83     , m_labels(codeBlock ? codeBlock->numberOfInstructions() : 0)
84     , m_bytecodeOffset(std::numeric_limits<unsigned>::max())
85     , m_getByIdIndex(UINT_MAX)
86     , m_getByIdWithThisIndex(UINT_MAX)
87     , m_putByIdIndex(UINT_MAX)
88     , m_byValInstructionIndex(UINT_MAX)
89     , m_callLinkInfoIndex(UINT_MAX)
90     , m_randomGenerator(cryptographicallyRandomNumber())
91     , m_pcToCodeOriginMapBuilder(*vm)
92     , m_canBeOptimized(false)
93     , m_shouldEmitProfiling(false)
94     , m_loopOSREntryBytecodeOffset(loopOSREntryBytecodeOffset)
95 {
96 }
97
98 JIT::~JIT()
99 {
100 }
101
102 #if ENABLE(DFG_JIT)
103 void JIT::emitEnterOptimizationCheck()
104 {
105     if (!canBeOptimized())
106         return;
107
108     JumpList skipOptimize;
109     
110     skipOptimize.append(branchAdd32(Signed, TrustedImm32(Options::executionCounterIncrementForEntry()), AbsoluteAddress(m_codeBlock->addressOfJITExecuteCounter())));
111     ASSERT(!m_bytecodeOffset);
112
113     copyCalleeSavesFromFrameOrRegisterToVMEntryFrameCalleeSavesBuffer(*vm());
114
115     callOperation(operationOptimize, m_bytecodeOffset);
116     skipOptimize.append(branchTestPtr(Zero, returnValueGPR));
117     move(returnValueGPR2, stackPointerRegister);
118     jump(returnValueGPR);
119     skipOptimize.link(this);
120 }
121 #endif
122
123 void JIT::emitNotifyWrite(WatchpointSet* set)
124 {
125     if (!set || set->state() == IsInvalidated) {
126         addSlowCase(Jump());
127         return;
128     }
129     
130     addSlowCase(branch8(NotEqual, AbsoluteAddress(set->addressOfState()), TrustedImm32(IsInvalidated)));
131 }
132
133 void JIT::emitNotifyWrite(GPRReg pointerToSet)
134 {
135     addSlowCase(branch8(NotEqual, Address(pointerToSet, WatchpointSet::offsetOfState()), TrustedImm32(IsInvalidated)));
136 }
137
138 void JIT::assertStackPointerOffset()
139 {
140     if (ASSERT_DISABLED)
141         return;
142     
143     addPtr(TrustedImm32(stackPointerOffsetFor(m_codeBlock) * sizeof(Register)), callFrameRegister, regT0);
144     Jump ok = branchPtr(Equal, regT0, stackPointerRegister);
145     breakpoint();
146     ok.link(this);
147 }
148
149 #define NEXT_OPCODE(name) \
150     m_bytecodeOffset += OPCODE_LENGTH(name); \
151     break;
152
153 #define DEFINE_SLOW_OP(name) \
154     case op_##name: { \
155         if (m_bytecodeOffset >= startBytecodeOffset) { \
156             JITSlowPathCall slowPathCall(this, currentInstruction, slow_path_##name); \
157             slowPathCall.call(); \
158         } \
159         NEXT_OPCODE(op_##name); \
160     }
161
162 #define DEFINE_OP(name) \
163     case name: { \
164         if (m_bytecodeOffset >= startBytecodeOffset) { \
165             emit_##name(currentInstruction); \
166         } \
167         NEXT_OPCODE(name); \
168     }
169
170 #define DEFINE_SLOWCASE_OP(name) \
171     case name: { \
172         emitSlow_##name(currentInstruction, iter); \
173         NEXT_OPCODE(name); \
174     }
175
176 void JIT::privateCompileMainPass()
177 {
178     if (false)
179         dataLog("Compiling ", *m_codeBlock, "\n");
180     
181     jitAssertTagsInPlace();
182     jitAssertArgumentCountSane();
183     
184     Instruction* instructionsBegin = m_codeBlock->instructions().begin();
185     unsigned instructionCount = m_instructions.size();
186
187     m_callLinkInfoIndex = 0;
188
189     unsigned startBytecodeOffset = 0;
190     if (m_loopOSREntryBytecodeOffset && m_codeBlock->inherits(*m_codeBlock->vm(), ProgramCodeBlock::info())) {
191         // We can only do this optimization because we execute ProgramCodeBlock's exactly once.
192         // This optimization would be invalid otherwise. When the LLInt determines it wants to
193         // do OSR entry into the baseline JIT in a loop, it will pass in the bytecode offset it
194         // was executing at when it kicked off our compilation. We only need to compile code for
195         // anything reachable from that bytecode offset.
196
197         // We only bother building the bytecode graph if it could save time and executable
198         // memory. We pick an arbitrary offset where we deem this is profitable.
199         if (m_loopOSREntryBytecodeOffset >= 200) {
200             // As a simplification, we don't find all bytecode ranges that are unreachable.
201             // Instead, we just find the minimum bytecode offset that is reachable, and
202             // compile code from that bytecode offset onwards.
203
204             BytecodeGraph<CodeBlock> graph(m_codeBlock, m_instructions);
205             BytecodeBasicBlock* block = graph.findBasicBlockForBytecodeOffset(m_loopOSREntryBytecodeOffset);
206             RELEASE_ASSERT(block);
207
208             GraphNodeWorklist<BytecodeBasicBlock*> worklist;
209             startBytecodeOffset = UINT_MAX;
210             worklist.push(block);
211             while (BytecodeBasicBlock* block = worklist.pop()) {
212                 startBytecodeOffset = std::min(startBytecodeOffset, block->leaderOffset());
213                 worklist.pushAll(block->successors());
214             }
215         }
216     }
217
218     for (m_bytecodeOffset = 0; m_bytecodeOffset < instructionCount; ) {
219         if (m_bytecodeOffset == startBytecodeOffset && startBytecodeOffset > 0) {
220             // We've proven all bytecode instructions up until here are unreachable.
221             // Let's ensure that by crashing if it's ever hit.
222             breakpoint();
223         }
224
225         if (m_disassembler)
226             m_disassembler->setForBytecodeMainPath(m_bytecodeOffset, label());
227         Instruction* currentInstruction = instructionsBegin + m_bytecodeOffset;
228         ASSERT_WITH_MESSAGE(m_interpreter->isOpcode(currentInstruction->u.opcode), "privateCompileMainPass gone bad @ %d", m_bytecodeOffset);
229
230         m_pcToCodeOriginMapBuilder.appendItem(label(), CodeOrigin(m_bytecodeOffset));
231
232 #if ENABLE(OPCODE_SAMPLING)
233         if (m_bytecodeOffset > 0) // Avoid the overhead of sampling op_enter twice.
234             sampleInstruction(currentInstruction);
235 #endif
236
237         m_labels[m_bytecodeOffset] = label();
238
239 #if ENABLE(JIT_VERBOSE)
240         dataLogF("Old JIT emitting code for bc#%u at offset 0x%lx.\n", m_bytecodeOffset, (long)debugOffset());
241 #endif
242         
243         OpcodeID opcodeID = m_interpreter->getOpcodeID(currentInstruction->u.opcode);
244
245         if (m_compilation) {
246             add64(
247                 TrustedImm32(1),
248                 AbsoluteAddress(m_compilation->executionCounterFor(Profiler::OriginStack(Profiler::Origin(
249                     m_compilation->bytecodes(), m_bytecodeOffset)))->address()));
250         }
251         
252         if (Options::eagerlyUpdateTopCallFrame())
253             updateTopCallFrame();
254
255         unsigned bytecodeOffset = m_bytecodeOffset;
256
257         switch (opcodeID) {
258         DEFINE_SLOW_OP(in)
259         DEFINE_SLOW_OP(less)
260         DEFINE_SLOW_OP(lesseq)
261         DEFINE_SLOW_OP(greater)
262         DEFINE_SLOW_OP(greatereq)
263         DEFINE_SLOW_OP(is_function)
264         DEFINE_SLOW_OP(is_object_or_null)
265         DEFINE_SLOW_OP(typeof)
266
267         DEFINE_OP(op_add)
268         DEFINE_OP(op_bitand)
269         DEFINE_OP(op_bitor)
270         DEFINE_OP(op_bitxor)
271         DEFINE_OP(op_call)
272         DEFINE_OP(op_tail_call)
273         DEFINE_OP(op_call_eval)
274         DEFINE_OP(op_call_varargs)
275         DEFINE_OP(op_tail_call_varargs)
276         DEFINE_OP(op_tail_call_forward_arguments)
277         DEFINE_OP(op_construct_varargs)
278         DEFINE_OP(op_catch)
279         DEFINE_OP(op_construct)
280         DEFINE_OP(op_create_this)
281         DEFINE_OP(op_to_this)
282         DEFINE_OP(op_create_direct_arguments)
283         DEFINE_OP(op_create_scoped_arguments)
284         DEFINE_OP(op_create_cloned_arguments)
285         DEFINE_OP(op_get_argument)
286         DEFINE_OP(op_argument_count)
287         DEFINE_OP(op_create_rest)
288         DEFINE_OP(op_get_rest_length)
289         DEFINE_OP(op_check_tdz)
290         DEFINE_OP(op_assert)
291         DEFINE_OP(op_debug)
292         DEFINE_OP(op_del_by_id)
293         DEFINE_OP(op_del_by_val)
294         DEFINE_OP(op_div)
295         DEFINE_OP(op_end)
296         DEFINE_OP(op_enter)
297         DEFINE_OP(op_get_scope)
298         DEFINE_OP(op_eq)
299         DEFINE_OP(op_eq_null)
300         DEFINE_OP(op_try_get_by_id)
301         case op_get_array_length:
302         case op_get_by_id_proto_load:
303         case op_get_by_id_unset:
304         DEFINE_OP(op_get_by_id)
305         DEFINE_OP(op_get_by_id_with_this)
306         DEFINE_OP(op_get_by_val)
307         DEFINE_OP(op_get_by_val_with_this)
308         DEFINE_OP(op_overrides_has_instance)
309         DEFINE_OP(op_instanceof)
310         DEFINE_OP(op_instanceof_custom)
311         DEFINE_OP(op_is_empty)
312         DEFINE_OP(op_is_undefined)
313         DEFINE_OP(op_is_boolean)
314         DEFINE_OP(op_is_number)
315         DEFINE_OP(op_is_object)
316         DEFINE_OP(op_is_cell_with_type)
317         DEFINE_OP(op_jeq_null)
318         DEFINE_OP(op_jfalse)
319         DEFINE_OP(op_jmp)
320         DEFINE_OP(op_jneq_null)
321         DEFINE_OP(op_jneq_ptr)
322         DEFINE_OP(op_jless)
323         DEFINE_OP(op_jlesseq)
324         DEFINE_OP(op_jgreater)
325         DEFINE_OP(op_jgreatereq)
326         DEFINE_OP(op_jnless)
327         DEFINE_OP(op_jnlesseq)
328         DEFINE_OP(op_jngreater)
329         DEFINE_OP(op_jngreatereq)
330         DEFINE_OP(op_jtrue)
331         DEFINE_OP(op_loop_hint)
332         DEFINE_OP(op_check_traps)
333         DEFINE_OP(op_lshift)
334         DEFINE_OP(op_mod)
335         DEFINE_OP(op_mov)
336         DEFINE_OP(op_mul)
337         DEFINE_OP(op_negate)
338         DEFINE_OP(op_neq)
339         DEFINE_OP(op_neq_null)
340         DEFINE_OP(op_new_array)
341         DEFINE_OP(op_new_array_with_size)
342         DEFINE_OP(op_new_array_buffer)
343         DEFINE_OP(op_new_array_with_spread)
344         DEFINE_OP(op_spread)
345         DEFINE_OP(op_new_func)
346         DEFINE_OP(op_new_func_exp)
347         DEFINE_OP(op_new_generator_func)
348         DEFINE_OP(op_new_generator_func_exp)
349         DEFINE_OP(op_new_async_func)
350         DEFINE_OP(op_new_async_func_exp)
351         DEFINE_OP(op_new_object)
352         DEFINE_OP(op_new_regexp)
353         DEFINE_OP(op_not)
354         DEFINE_OP(op_nstricteq)
355         DEFINE_OP(op_dec)
356         DEFINE_OP(op_inc)
357         DEFINE_OP(op_pow)
358         DEFINE_OP(op_profile_type)
359         DEFINE_OP(op_profile_control_flow)
360         DEFINE_OP(op_push_with_scope)
361         DEFINE_OP(op_create_lexical_environment)
362         DEFINE_OP(op_get_parent_scope)
363         DEFINE_OP(op_put_by_id)
364         DEFINE_OP(op_put_by_id_with_this)
365         DEFINE_OP(op_put_by_index)
366         case op_put_by_val_direct:
367         DEFINE_OP(op_put_by_val)
368         DEFINE_OP(op_put_by_val_with_this)
369         DEFINE_OP(op_put_getter_by_id)
370         DEFINE_OP(op_put_setter_by_id)
371         DEFINE_OP(op_put_getter_setter_by_id)
372         DEFINE_OP(op_put_getter_by_val)
373         DEFINE_OP(op_put_setter_by_val)
374         DEFINE_OP(op_define_data_property)
375         DEFINE_OP(op_define_accessor_property)
376
377         DEFINE_OP(op_ret)
378         DEFINE_OP(op_rshift)
379         DEFINE_OP(op_unsigned)
380         DEFINE_OP(op_urshift)
381         DEFINE_OP(op_set_function_name)
382         DEFINE_OP(op_strcat)
383         DEFINE_OP(op_stricteq)
384         DEFINE_OP(op_sub)
385         DEFINE_OP(op_switch_char)
386         DEFINE_OP(op_switch_imm)
387         DEFINE_OP(op_switch_string)
388         DEFINE_OP(op_throw)
389         DEFINE_OP(op_throw_static_error)
390         DEFINE_OP(op_to_number)
391         DEFINE_OP(op_to_string)
392         DEFINE_OP(op_to_primitive)
393
394         DEFINE_OP(op_resolve_scope)
395         DEFINE_OP(op_get_from_scope)
396         DEFINE_OP(op_put_to_scope)
397         DEFINE_OP(op_get_from_arguments)
398         DEFINE_OP(op_put_to_arguments)
399
400         DEFINE_OP(op_get_enumerable_length)
401         DEFINE_OP(op_has_generic_property)
402         DEFINE_OP(op_has_structure_property)
403         DEFINE_OP(op_has_indexed_property)
404         DEFINE_OP(op_get_direct_pname)
405         DEFINE_OP(op_get_property_enumerator)
406         DEFINE_OP(op_enumerator_structure_pname)
407         DEFINE_OP(op_enumerator_generic_pname)
408         DEFINE_OP(op_to_index_string)
409             
410         DEFINE_OP(op_log_shadow_chicken_prologue)
411         DEFINE_OP(op_log_shadow_chicken_tail)
412         default:
413             RELEASE_ASSERT_NOT_REACHED();
414         }
415
416         if (false)
417             dataLog("At ", bytecodeOffset, ": ", m_slowCases.size(), "\n");
418     }
419
420     RELEASE_ASSERT(m_callLinkInfoIndex == m_callCompilationInfo.size());
421
422 #ifndef NDEBUG
423     // Reset this, in order to guard its use with ASSERTs.
424     m_bytecodeOffset = std::numeric_limits<unsigned>::max();
425 #endif
426 }
427
428 void JIT::privateCompileLinkPass()
429 {
430     unsigned jmpTableCount = m_jmpTable.size();
431     for (unsigned i = 0; i < jmpTableCount; ++i)
432         m_jmpTable[i].from.linkTo(m_labels[m_jmpTable[i].toBytecodeOffset], this);
433     m_jmpTable.clear();
434 }
435
436 void JIT::privateCompileSlowCases()
437 {
438     Instruction* instructionsBegin = m_codeBlock->instructions().begin();
439
440     m_getByIdIndex = 0;
441     m_getByIdWithThisIndex = 0;
442     m_putByIdIndex = 0;
443     m_byValInstructionIndex = 0;
444     m_callLinkInfoIndex = 0;
445     
446     // Use this to assert that slow-path code associates new profiling sites with existing
447     // ValueProfiles rather than creating new ones. This ensures that for a given instruction
448     // (say, get_by_id) we get combined statistics for both the fast-path executions of that
449     // instructions and the slow-path executions. Furthermore, if the slow-path code created
450     // new ValueProfiles then the ValueProfiles would no longer be sorted by bytecode offset,
451     // which would break the invariant necessary to use CodeBlock::valueProfileForBytecodeOffset().
452     unsigned numberOfValueProfiles = m_codeBlock->numberOfValueProfiles();
453
454     for (Vector<SlowCaseEntry>::iterator iter = m_slowCases.begin(); iter != m_slowCases.end();) {
455         m_bytecodeOffset = iter->to;
456
457         m_pcToCodeOriginMapBuilder.appendItem(label(), CodeOrigin(m_bytecodeOffset));
458
459         unsigned firstTo = m_bytecodeOffset;
460
461         Instruction* currentInstruction = instructionsBegin + m_bytecodeOffset;
462         
463         RareCaseProfile* rareCaseProfile = 0;
464         if (shouldEmitProfiling())
465             rareCaseProfile = m_codeBlock->addRareCaseProfile(m_bytecodeOffset);
466
467 #if ENABLE(JIT_VERBOSE)
468         dataLogF("Old JIT emitting slow code for bc#%u at offset 0x%lx.\n", m_bytecodeOffset, (long)debugOffset());
469 #endif
470         
471         if (m_disassembler)
472             m_disassembler->setForBytecodeSlowPath(m_bytecodeOffset, label());
473
474         switch (m_interpreter->getOpcodeID(currentInstruction->u.opcode)) {
475         DEFINE_SLOWCASE_OP(op_add)
476         DEFINE_SLOWCASE_OP(op_bitand)
477         DEFINE_SLOWCASE_OP(op_bitor)
478         DEFINE_SLOWCASE_OP(op_bitxor)
479         DEFINE_SLOWCASE_OP(op_call)
480         DEFINE_SLOWCASE_OP(op_tail_call)
481         DEFINE_SLOWCASE_OP(op_call_eval)
482         DEFINE_SLOWCASE_OP(op_call_varargs)
483         DEFINE_SLOWCASE_OP(op_tail_call_varargs)
484         DEFINE_SLOWCASE_OP(op_tail_call_forward_arguments)
485         DEFINE_SLOWCASE_OP(op_construct_varargs)
486         DEFINE_SLOWCASE_OP(op_construct)
487         DEFINE_SLOWCASE_OP(op_to_this)
488         DEFINE_SLOWCASE_OP(op_check_tdz)
489         DEFINE_SLOWCASE_OP(op_create_this)
490         DEFINE_SLOWCASE_OP(op_div)
491         DEFINE_SLOWCASE_OP(op_eq)
492         DEFINE_SLOWCASE_OP(op_try_get_by_id)
493         case op_get_array_length:
494         case op_get_by_id_proto_load:
495         case op_get_by_id_unset:
496         DEFINE_SLOWCASE_OP(op_get_by_id)
497         DEFINE_SLOWCASE_OP(op_get_by_id_with_this)
498         DEFINE_SLOWCASE_OP(op_get_by_val)
499         DEFINE_SLOWCASE_OP(op_instanceof)
500         DEFINE_SLOWCASE_OP(op_instanceof_custom)
501         DEFINE_SLOWCASE_OP(op_jless)
502         DEFINE_SLOWCASE_OP(op_jlesseq)
503         DEFINE_SLOWCASE_OP(op_jgreater)
504         DEFINE_SLOWCASE_OP(op_jgreatereq)
505         DEFINE_SLOWCASE_OP(op_jnless)
506         DEFINE_SLOWCASE_OP(op_jnlesseq)
507         DEFINE_SLOWCASE_OP(op_jngreater)
508         DEFINE_SLOWCASE_OP(op_jngreatereq)
509         DEFINE_SLOWCASE_OP(op_loop_hint)
510         DEFINE_SLOWCASE_OP(op_check_traps)
511         DEFINE_SLOWCASE_OP(op_lshift)
512         DEFINE_SLOWCASE_OP(op_mod)
513         DEFINE_SLOWCASE_OP(op_mul)
514         DEFINE_SLOWCASE_OP(op_negate)
515         DEFINE_SLOWCASE_OP(op_neq)
516         DEFINE_SLOWCASE_OP(op_new_object)
517         DEFINE_SLOWCASE_OP(op_not)
518         DEFINE_SLOWCASE_OP(op_nstricteq)
519         DEFINE_SLOWCASE_OP(op_dec)
520         DEFINE_SLOWCASE_OP(op_inc)
521         DEFINE_SLOWCASE_OP(op_put_by_id)
522         case op_put_by_val_direct:
523         DEFINE_SLOWCASE_OP(op_put_by_val)
524         DEFINE_SLOWCASE_OP(op_rshift)
525         DEFINE_SLOWCASE_OP(op_unsigned)
526         DEFINE_SLOWCASE_OP(op_urshift)
527         DEFINE_SLOWCASE_OP(op_stricteq)
528         DEFINE_SLOWCASE_OP(op_sub)
529         DEFINE_SLOWCASE_OP(op_to_number)
530         DEFINE_SLOWCASE_OP(op_to_string)
531         DEFINE_SLOWCASE_OP(op_to_primitive)
532         DEFINE_SLOWCASE_OP(op_has_indexed_property)
533         DEFINE_SLOWCASE_OP(op_has_structure_property)
534         DEFINE_SLOWCASE_OP(op_get_direct_pname)
535
536         DEFINE_SLOWCASE_OP(op_resolve_scope)
537         DEFINE_SLOWCASE_OP(op_get_from_scope)
538         DEFINE_SLOWCASE_OP(op_put_to_scope)
539
540         default:
541             RELEASE_ASSERT_NOT_REACHED();
542         }
543
544         if (false)
545             dataLog("At ", firstTo, " slow: ", iter - m_slowCases.begin(), "\n");
546
547         RELEASE_ASSERT_WITH_MESSAGE(iter == m_slowCases.end() || firstTo != iter->to, "Not enough jumps linked in slow case codegen.");
548         RELEASE_ASSERT_WITH_MESSAGE(firstTo == (iter - 1)->to, "Too many jumps linked in slow case codegen.");
549         
550         if (shouldEmitProfiling())
551             add32(TrustedImm32(1), AbsoluteAddress(&rareCaseProfile->m_counter));
552
553         emitJumpSlowToHot(jump(), 0);
554     }
555
556     RELEASE_ASSERT(m_getByIdIndex == m_getByIds.size());
557     RELEASE_ASSERT(m_getByIdWithThisIndex == m_getByIdsWithThis.size());
558     RELEASE_ASSERT(m_putByIdIndex == m_putByIds.size());
559     RELEASE_ASSERT(m_callLinkInfoIndex == m_callCompilationInfo.size());
560     RELEASE_ASSERT(numberOfValueProfiles == m_codeBlock->numberOfValueProfiles());
561
562 #ifndef NDEBUG
563     // Reset this, in order to guard its use with ASSERTs.
564     m_bytecodeOffset = std::numeric_limits<unsigned>::max();
565 #endif
566 }
567
568 void JIT::compileWithoutLinking(JITCompilationEffort effort)
569 {
570     double before = 0;
571     if (UNLIKELY(computeCompileTimes()))
572         before = monotonicallyIncreasingTimeMS();
573     
574     {
575         ConcurrentJSLocker locker(m_codeBlock->m_lock);
576         m_instructions = m_codeBlock->instructions().clone();
577     }
578
579     DFG::CapabilityLevel level = m_codeBlock->capabilityLevel();
580     switch (level) {
581     case DFG::CannotCompile:
582         m_canBeOptimized = false;
583         m_canBeOptimizedOrInlined = false;
584         m_shouldEmitProfiling = false;
585         break;
586     case DFG::CanCompile:
587     case DFG::CanCompileAndInline:
588         m_canBeOptimized = true;
589         m_canBeOptimizedOrInlined = true;
590         m_shouldEmitProfiling = true;
591         break;
592     default:
593         RELEASE_ASSERT_NOT_REACHED();
594         break;
595     }
596     
597     switch (m_codeBlock->codeType()) {
598     case GlobalCode:
599     case ModuleCode:
600     case EvalCode:
601         m_codeBlock->m_shouldAlwaysBeInlined = false;
602         break;
603     case FunctionCode:
604         // We could have already set it to false because we detected an uninlineable call.
605         // Don't override that observation.
606         m_codeBlock->m_shouldAlwaysBeInlined &= canInline(level) && DFG::mightInlineFunction(m_codeBlock);
607         break;
608     }
609
610     if (Options::dumpDisassembly() || (m_vm->m_perBytecodeProfiler && Options::disassembleBaselineForProfiler()))
611         m_disassembler = std::make_unique<JITDisassembler>(m_codeBlock);
612     if (m_vm->m_perBytecodeProfiler) {
613         m_compilation = adoptRef(
614             new Profiler::Compilation(
615                 m_vm->m_perBytecodeProfiler->ensureBytecodesFor(m_codeBlock),
616                 Profiler::Baseline));
617         m_compilation->addProfiledBytecodes(*m_vm->m_perBytecodeProfiler, m_codeBlock);
618     }
619     
620     m_pcToCodeOriginMapBuilder.appendItem(label(), CodeOrigin(0, nullptr));
621
622     if (m_disassembler)
623         m_disassembler->setStartOfCode(label());
624
625     // Just add a little bit of randomness to the codegen
626     if (m_randomGenerator.getUint32() & 1)
627         nop();
628
629     emitFunctionPrologue();
630     emitPutToCallFrameHeader(m_codeBlock, CallFrameSlot::codeBlock);
631
632     Label beginLabel(this);
633
634     sampleCodeBlock(m_codeBlock);
635 #if ENABLE(OPCODE_SAMPLING)
636     sampleInstruction(m_codeBlock->instructions().begin());
637 #endif
638
639     if (m_codeBlock->codeType() == FunctionCode) {
640         ASSERT(m_bytecodeOffset == std::numeric_limits<unsigned>::max());
641         if (shouldEmitProfiling()) {
642             for (int argument = 0; argument < m_codeBlock->numParameters(); ++argument) {
643                 // If this is a constructor, then we want to put in a dummy profiling site (to
644                 // keep things consistent) but we don't actually want to record the dummy value.
645                 if (m_codeBlock->m_isConstructor && !argument)
646                     continue;
647                 int offset = CallFrame::argumentOffsetIncludingThis(argument) * static_cast<int>(sizeof(Register));
648 #if USE(JSVALUE64)
649                 load64(Address(callFrameRegister, offset), regT0);
650 #elif USE(JSVALUE32_64)
651                 load32(Address(callFrameRegister, offset + OBJECT_OFFSETOF(JSValue, u.asBits.payload)), regT0);
652                 load32(Address(callFrameRegister, offset + OBJECT_OFFSETOF(JSValue, u.asBits.tag)), regT1);
653 #endif
654                 emitValueProfilingSite(m_codeBlock->valueProfileForArgument(argument));
655             }
656         }
657     }
658
659     addPtr(TrustedImm32(stackPointerOffsetFor(m_codeBlock) * sizeof(Register)), callFrameRegister, regT1);
660     Jump stackOverflow = branchPtr(Above, AbsoluteAddress(m_vm->addressOfSoftStackLimit()), regT1);
661
662     move(regT1, stackPointerRegister);
663     checkStackPointerAlignment();
664
665     emitSaveCalleeSaves();
666     emitMaterializeTagCheckRegisters();
667     
668     RELEASE_ASSERT(!JITCode::isJIT(m_codeBlock->jitType()));
669
670     privateCompileMainPass();
671     privateCompileLinkPass();
672     privateCompileSlowCases();
673     
674     if (m_disassembler)
675         m_disassembler->setEndOfSlowPath(label());
676     m_pcToCodeOriginMapBuilder.appendItem(label(), PCToCodeOriginMapBuilder::defaultCodeOrigin());
677
678     stackOverflow.link(this);
679     m_bytecodeOffset = 0;
680     if (maxFrameExtentForSlowPathCall)
681         addPtr(TrustedImm32(-maxFrameExtentForSlowPathCall), stackPointerRegister);
682     callOperationWithCallFrameRollbackOnException(operationThrowStackOverflowError, m_codeBlock);
683
684     if (m_codeBlock->codeType() == FunctionCode) {
685         m_arityCheck = label();
686         store8(TrustedImm32(0), &m_codeBlock->m_shouldAlwaysBeInlined);
687         emitFunctionPrologue();
688         emitPutToCallFrameHeader(m_codeBlock, CallFrameSlot::codeBlock);
689
690         load32(payloadFor(CallFrameSlot::argumentCount), regT1);
691         branch32(AboveOrEqual, regT1, TrustedImm32(m_codeBlock->m_numParameters)).linkTo(beginLabel, this);
692
693         m_bytecodeOffset = 0;
694
695         if (maxFrameExtentForSlowPathCall)
696             addPtr(TrustedImm32(-maxFrameExtentForSlowPathCall), stackPointerRegister);
697         callOperationWithCallFrameRollbackOnException(m_codeBlock->m_isConstructor ? operationConstructArityCheck : operationCallArityCheck);
698         if (maxFrameExtentForSlowPathCall)
699             addPtr(TrustedImm32(maxFrameExtentForSlowPathCall), stackPointerRegister);
700         branchTest32(Zero, returnValueGPR).linkTo(beginLabel, this);
701         move(returnValueGPR, GPRInfo::argumentGPR0);
702         emitNakedCall(m_vm->getCTIStub(arityFixupGenerator).code());
703
704 #if !ASSERT_DISABLED
705         m_bytecodeOffset = std::numeric_limits<unsigned>::max(); // Reset this, in order to guard its use with ASSERTs.
706 #endif
707
708         jump(beginLabel);
709     }
710
711     ASSERT(m_jmpTable.isEmpty());
712     
713     privateCompileExceptionHandlers();
714     
715     if (m_disassembler)
716         m_disassembler->setEndOfCode(label());
717     m_pcToCodeOriginMapBuilder.appendItem(label(), PCToCodeOriginMapBuilder::defaultCodeOrigin());
718
719     m_linkBuffer = std::unique_ptr<LinkBuffer>(new LinkBuffer(*m_vm, *this, m_codeBlock, effort));
720
721     double after = 0;
722     if (UNLIKELY(computeCompileTimes())) {
723         after = monotonicallyIncreasingTimeMS();
724
725         if (Options::reportTotalCompileTimes())
726             totalBaselineCompileTime += after - before;
727     }
728     if (UNLIKELY(reportCompileTimes())) {
729         CString codeBlockName = toCString(*m_codeBlock);
730         
731         dataLog("Optimized ", codeBlockName, " with Baseline JIT into ", m_linkBuffer->size(), " bytes in ", after - before, " ms.\n");
732     }
733 }
734
735 CompilationResult JIT::link()
736 {
737     LinkBuffer& patchBuffer = *m_linkBuffer;
738     
739     if (patchBuffer.didFailToAllocate())
740         return CompilationFailed;
741
742     // Translate vPC offsets into addresses in JIT generated code, for switch tables.
743     for (auto& record : m_switches) {
744         unsigned bytecodeOffset = record.bytecodeOffset;
745
746         if (record.type != SwitchRecord::String) {
747             ASSERT(record.type == SwitchRecord::Immediate || record.type == SwitchRecord::Character); 
748             ASSERT(record.jumpTable.simpleJumpTable->branchOffsets.size() == record.jumpTable.simpleJumpTable->ctiOffsets.size());
749
750             record.jumpTable.simpleJumpTable->ctiDefault = patchBuffer.locationOf(m_labels[bytecodeOffset + record.defaultOffset]);
751
752             for (unsigned j = 0; j < record.jumpTable.simpleJumpTable->branchOffsets.size(); ++j) {
753                 unsigned offset = record.jumpTable.simpleJumpTable->branchOffsets[j];
754                 record.jumpTable.simpleJumpTable->ctiOffsets[j] = offset ? patchBuffer.locationOf(m_labels[bytecodeOffset + offset]) : record.jumpTable.simpleJumpTable->ctiDefault;
755             }
756         } else {
757             ASSERT(record.type == SwitchRecord::String);
758
759             record.jumpTable.stringJumpTable->ctiDefault = patchBuffer.locationOf(m_labels[bytecodeOffset + record.defaultOffset]);
760
761             for (auto& location : record.jumpTable.stringJumpTable->offsetTable.values()) {
762                 unsigned offset = location.branchOffset;
763                 location.ctiOffset = offset ? patchBuffer.locationOf(m_labels[bytecodeOffset + offset]) : record.jumpTable.stringJumpTable->ctiDefault;
764             }
765         }
766     }
767
768     for (size_t i = 0; i < m_codeBlock->numberOfExceptionHandlers(); ++i) {
769         HandlerInfo& handler = m_codeBlock->exceptionHandler(i);
770         handler.nativeCode = patchBuffer.locationOf(m_labels[handler.target]);
771     }
772
773     for (auto& record : m_calls) {
774         if (record.to)
775             patchBuffer.link(record.from, FunctionPtr(record.to));
776     }
777
778     for (unsigned i = m_getByIds.size(); i--;)
779         m_getByIds[i].finalize(patchBuffer);
780     for (unsigned i = m_getByIdsWithThis.size(); i--;)
781         m_getByIdsWithThis[i].finalize(patchBuffer);
782     for (unsigned i = m_putByIds.size(); i--;)
783         m_putByIds[i].finalize(patchBuffer);
784
785     if (m_byValCompilationInfo.size()) {
786         CodeLocationLabel exceptionHandler = patchBuffer.locationOf(m_exceptionHandler);
787
788         for (const auto& byValCompilationInfo : m_byValCompilationInfo) {
789             PatchableJump patchableNotIndexJump = byValCompilationInfo.notIndexJump;
790             CodeLocationJump notIndexJump = CodeLocationJump();
791             if (Jump(patchableNotIndexJump).isSet())
792                 notIndexJump = CodeLocationJump(patchBuffer.locationOf(patchableNotIndexJump));
793             CodeLocationJump badTypeJump = CodeLocationJump(patchBuffer.locationOf(byValCompilationInfo.badTypeJump));
794             CodeLocationLabel doneTarget = patchBuffer.locationOf(byValCompilationInfo.doneTarget);
795             CodeLocationLabel nextHotPathTarget = patchBuffer.locationOf(byValCompilationInfo.nextHotPathTarget);
796             CodeLocationLabel slowPathTarget = patchBuffer.locationOf(byValCompilationInfo.slowPathTarget);
797             CodeLocationCall returnAddress = patchBuffer.locationOf(byValCompilationInfo.returnAddress);
798
799             *byValCompilationInfo.byValInfo = ByValInfo(
800                 byValCompilationInfo.bytecodeIndex,
801                 notIndexJump,
802                 badTypeJump,
803                 exceptionHandler,
804                 byValCompilationInfo.arrayMode,
805                 byValCompilationInfo.arrayProfile,
806                 differenceBetweenCodePtr(badTypeJump, doneTarget),
807                 differenceBetweenCodePtr(badTypeJump, nextHotPathTarget),
808                 differenceBetweenCodePtr(returnAddress, slowPathTarget));
809         }
810     }
811
812     for (auto& compilationInfo : m_callCompilationInfo) {
813         CallLinkInfo& info = *compilationInfo.callLinkInfo;
814         info.setCallLocations(
815             CodeLocationLabel(patchBuffer.locationOfNearCall(compilationInfo.callReturnLocation)),
816             CodeLocationLabel(patchBuffer.locationOf(compilationInfo.hotPathBegin)),
817             patchBuffer.locationOfNearCall(compilationInfo.hotPathOther));
818     }
819
820     CompactJITCodeMap::Encoder jitCodeMapEncoder;
821     for (unsigned bytecodeOffset = 0; bytecodeOffset < m_labels.size(); ++bytecodeOffset) {
822         if (m_labels[bytecodeOffset].isSet())
823             jitCodeMapEncoder.append(bytecodeOffset, patchBuffer.offsetOf(m_labels[bytecodeOffset]));
824     }
825     m_codeBlock->setJITCodeMap(jitCodeMapEncoder.finish());
826
827     MacroAssemblerCodePtr withArityCheck;
828     if (m_codeBlock->codeType() == FunctionCode)
829         withArityCheck = patchBuffer.locationOf(m_arityCheck);
830
831     if (Options::dumpDisassembly()) {
832         m_disassembler->dump(patchBuffer);
833         patchBuffer.didAlreadyDisassemble();
834     }
835     if (m_compilation) {
836         if (Options::disassembleBaselineForProfiler())
837             m_disassembler->reportToProfiler(m_compilation.get(), patchBuffer);
838         m_vm->m_perBytecodeProfiler->addCompilation(m_codeBlock, *m_compilation);
839     }
840
841     if (m_pcToCodeOriginMapBuilder.didBuildMapping())
842         m_codeBlock->setPCToCodeOriginMap(std::make_unique<PCToCodeOriginMap>(WTFMove(m_pcToCodeOriginMapBuilder), patchBuffer));
843     
844     CodeRef result = FINALIZE_CODE(
845         patchBuffer,
846         ("Baseline JIT code for %s", toCString(CodeBlockWithJITType(m_codeBlock, JITCode::BaselineJIT)).data()));
847     
848     m_vm->machineCodeBytesPerBytecodeWordForBaselineJIT->add(
849         static_cast<double>(result.size()) /
850         static_cast<double>(m_instructions.size()));
851
852     m_codeBlock->shrinkToFit(CodeBlock::LateShrink);
853     m_codeBlock->setJITCode(
854         adoptRef(*new DirectJITCode(result, withArityCheck, JITCode::BaselineJIT)));
855
856 #if ENABLE(JIT_VERBOSE)
857     dataLogF("JIT generated code for %p at [%p, %p).\n", m_codeBlock, result.executableMemory()->start(), result.executableMemory()->end());
858 #endif
859     
860     return CompilationSuccessful;
861 }
862
863 CompilationResult JIT::privateCompile(JITCompilationEffort effort)
864 {
865     doMainThreadPreparationBeforeCompile();
866     compileWithoutLinking(effort);
867     return link();
868 }
869
870 void JIT::privateCompileExceptionHandlers()
871 {
872     if (!m_exceptionChecksWithCallFrameRollback.empty()) {
873         m_exceptionChecksWithCallFrameRollback.link(this);
874
875         copyCalleeSavesToVMEntryFrameCalleeSavesBuffer(*vm());
876
877         // lookupExceptionHandlerFromCallerFrame is passed two arguments, the VM and the exec (the CallFrame*).
878
879         move(TrustedImmPtr(vm()), GPRInfo::argumentGPR0);
880         move(GPRInfo::callFrameRegister, GPRInfo::argumentGPR1);
881
882 #if CPU(X86)
883         // FIXME: should use the call abstraction, but this is currently in the SpeculativeJIT layer!
884         poke(GPRInfo::argumentGPR0);
885         poke(GPRInfo::argumentGPR1, 1);
886 #endif
887         m_calls.append(CallRecord(call(), std::numeric_limits<unsigned>::max(), FunctionPtr(lookupExceptionHandlerFromCallerFrame).value()));
888         jumpToExceptionHandler(*vm());
889     }
890
891     if (!m_exceptionChecks.empty() || m_byValCompilationInfo.size()) {
892         m_exceptionHandler = label();
893         m_exceptionChecks.link(this);
894
895         copyCalleeSavesToVMEntryFrameCalleeSavesBuffer(*vm());
896
897         // lookupExceptionHandler is passed two arguments, the VM and the exec (the CallFrame*).
898         move(TrustedImmPtr(vm()), GPRInfo::argumentGPR0);
899         move(GPRInfo::callFrameRegister, GPRInfo::argumentGPR1);
900
901 #if CPU(X86)
902         // FIXME: should use the call abstraction, but this is currently in the SpeculativeJIT layer!
903         poke(GPRInfo::argumentGPR0);
904         poke(GPRInfo::argumentGPR1, 1);
905 #endif
906         m_calls.append(CallRecord(call(), std::numeric_limits<unsigned>::max(), FunctionPtr(lookupExceptionHandler).value()));
907         jumpToExceptionHandler(*vm());
908     }
909 }
910
911 void JIT::doMainThreadPreparationBeforeCompile()
912 {
913     // This ensures that we have the most up to date type information when performing typecheck optimizations for op_profile_type.
914     if (m_vm->typeProfiler())
915         m_vm->typeProfilerLog()->processLogEntries(ASCIILiteral("Preparing for JIT compilation."));
916 }
917
918 unsigned JIT::frameRegisterCountFor(CodeBlock* codeBlock)
919 {
920     ASSERT(static_cast<unsigned>(codeBlock->m_numCalleeLocals) == WTF::roundUpToMultipleOf(stackAlignmentRegisters(), static_cast<unsigned>(codeBlock->m_numCalleeLocals)));
921
922     return roundLocalRegisterCountForFramePointerOffset(codeBlock->m_numCalleeLocals + maxFrameExtentForSlowPathCallInRegisters);
923 }
924
925 int JIT::stackPointerOffsetFor(CodeBlock* codeBlock)
926 {
927     return virtualRegisterForLocal(frameRegisterCountFor(codeBlock) - 1).offset();
928 }
929
930 bool JIT::reportCompileTimes()
931 {
932     return Options::reportCompileTimes() || Options::reportBaselineCompileTimes();
933 }
934
935 bool JIT::computeCompileTimes()
936 {
937     return reportCompileTimes() || Options::reportTotalCompileTimes();
938 }
939
940 HashMap<CString, double> JIT::compileTimeStats()
941 {
942     HashMap<CString, double> result;
943     if (Options::reportTotalCompileTimes()) {
944         result.add("Total Compile Time", totalBaselineCompileTime + totalDFGCompileTime + totalFTLCompileTime);
945         result.add("Baseline Compile Time", totalBaselineCompileTime);
946 #if ENABLE(DFG_JIT)
947         result.add("DFG Compile Time", totalDFGCompileTime);
948 #if ENABLE(FTL_JIT)
949         result.add("FTL Compile Time", totalFTLCompileTime);
950         result.add("FTL (DFG) Compile Time", totalFTLDFGCompileTime);
951         result.add("FTL (B3) Compile Time", totalFTLB3CompileTime);
952 #endif // ENABLE(FTL_JIT)
953 #endif // ENABLE(DFG_JIT)
954     }
955     return result;
956 }
957
958 } // namespace JSC
959
960 #endif // ENABLE(JIT)