Introduce get_by_id like IC into get_by_val when the given name is String or Symbol
[WebKit-https.git] / Source / JavaScriptCore / jit / JIT.cpp
1 /*
2  * Copyright (C) 2008, 2009, 2012-2015 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 "ArityCheckFailReturnThunks.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 "JSFunction.h"
41 #include "LinkBuffer.h"
42 #include "MaxFrameExtentForSlowPathCall.h"
43 #include "JSCInlines.h"
44 #include "ProfilerDatabase.h"
45 #include "RepatchBuffer.h"
46 #include "ResultType.h"
47 #include "SamplingTool.h"
48 #include "SlowPathCall.h"
49 #include "StackAlignment.h"
50 #include "TypeProfilerLog.h"
51 #include <wtf/CryptographicallyRandomNumber.h>
52
53 using namespace std;
54
55 namespace JSC {
56
57 void ctiPatchNearCallByReturnAddress(CodeBlock* codeblock, ReturnAddressPtr returnAddress, MacroAssemblerCodePtr newCalleeFunction)
58 {
59     RepatchBuffer repatchBuffer(codeblock);
60     repatchBuffer.relinkNearCallerToTrampoline(returnAddress, newCalleeFunction);
61 }
62
63 void ctiPatchCallByReturnAddress(CodeBlock* codeblock, ReturnAddressPtr returnAddress, MacroAssemblerCodePtr newCalleeFunction)
64 {
65     RepatchBuffer repatchBuffer(codeblock);
66     repatchBuffer.relinkCallerToTrampoline(returnAddress, newCalleeFunction);
67 }
68
69 void ctiPatchCallByReturnAddress(CodeBlock* codeblock, ReturnAddressPtr returnAddress, FunctionPtr newCalleeFunction)
70 {
71     RepatchBuffer repatchBuffer(codeblock);
72     repatchBuffer.relinkCallerToFunction(returnAddress, newCalleeFunction);
73 }
74
75 JIT::JIT(VM* vm, CodeBlock* codeBlock)
76     : JSInterfaceJIT(vm, codeBlock)
77     , m_interpreter(vm->interpreter)
78     , m_labels(codeBlock ? codeBlock->numberOfInstructions() : 0)
79     , m_bytecodeOffset(std::numeric_limits<unsigned>::max())
80     , m_getByIdIndex(UINT_MAX)
81     , m_putByIdIndex(UINT_MAX)
82     , m_byValInstructionIndex(UINT_MAX)
83     , m_callLinkInfoIndex(UINT_MAX)
84     , m_randomGenerator(cryptographicallyRandomNumber())
85     , m_canBeOptimized(false)
86     , m_shouldEmitProfiling(false)
87 {
88 }
89
90 #if ENABLE(DFG_JIT)
91 void JIT::emitEnterOptimizationCheck()
92 {
93     if (!canBeOptimized())
94         return;
95
96     JumpList skipOptimize;
97     
98     skipOptimize.append(branchAdd32(Signed, TrustedImm32(Options::executionCounterIncrementForEntry()), AbsoluteAddress(m_codeBlock->addressOfJITExecuteCounter())));
99     ASSERT(!m_bytecodeOffset);
100     callOperation(operationOptimize, m_bytecodeOffset);
101     skipOptimize.append(branchTestPtr(Zero, returnValueGPR));
102     move(returnValueGPR2, stackPointerRegister);
103     jump(returnValueGPR);
104     skipOptimize.link(this);
105 }
106 #endif
107
108 void JIT::emitNotifyWrite(WatchpointSet* set)
109 {
110     if (!set || set->state() == IsInvalidated)
111         return;
112     
113     addSlowCase(branch8(NotEqual, AbsoluteAddress(set->addressOfState()), TrustedImm32(IsInvalidated)));
114 }
115
116 void JIT::assertStackPointerOffset()
117 {
118     if (ASSERT_DISABLED)
119         return;
120     
121     addPtr(TrustedImm32(stackPointerOffsetFor(m_codeBlock) * sizeof(Register)), callFrameRegister, regT0);
122     Jump ok = branchPtr(Equal, regT0, stackPointerRegister);
123     breakpoint();
124     ok.link(this);
125 }
126
127 #define NEXT_OPCODE(name) \
128     m_bytecodeOffset += OPCODE_LENGTH(name); \
129     break;
130
131 #define DEFINE_SLOW_OP(name) \
132     case op_##name: { \
133         JITSlowPathCall slowPathCall(this, currentInstruction, slow_path_##name); \
134         slowPathCall.call(); \
135         NEXT_OPCODE(op_##name); \
136     }
137
138 #define DEFINE_OP(name) \
139     case name: { \
140         emit_##name(currentInstruction); \
141         NEXT_OPCODE(name); \
142     }
143
144 #define DEFINE_SLOWCASE_OP(name) \
145     case name: { \
146         emitSlow_##name(currentInstruction, iter); \
147         NEXT_OPCODE(name); \
148     }
149
150 void JIT::privateCompileMainPass()
151 {
152     jitAssertTagsInPlace();
153     jitAssertArgumentCountSane();
154     
155     Instruction* instructionsBegin = m_codeBlock->instructions().begin();
156     unsigned instructionCount = m_codeBlock->instructions().size();
157
158     m_callLinkInfoIndex = 0;
159
160     for (m_bytecodeOffset = 0; m_bytecodeOffset < instructionCount; ) {
161         if (m_disassembler)
162             m_disassembler->setForBytecodeMainPath(m_bytecodeOffset, label());
163         Instruction* currentInstruction = instructionsBegin + m_bytecodeOffset;
164         ASSERT_WITH_MESSAGE(m_interpreter->isOpcode(currentInstruction->u.opcode), "privateCompileMainPass gone bad @ %d", m_bytecodeOffset);
165
166 #if ENABLE(OPCODE_SAMPLING)
167         if (m_bytecodeOffset > 0) // Avoid the overhead of sampling op_enter twice.
168             sampleInstruction(currentInstruction);
169 #endif
170
171         m_labels[m_bytecodeOffset] = label();
172
173 #if ENABLE(JIT_VERBOSE)
174         dataLogF("Old JIT emitting code for bc#%u at offset 0x%lx.\n", m_bytecodeOffset, (long)debugOffset());
175 #endif
176         
177         OpcodeID opcodeID = m_interpreter->getOpcodeID(currentInstruction->u.opcode);
178
179         if (m_compilation) {
180             add64(
181                 TrustedImm32(1),
182                 AbsoluteAddress(m_compilation->executionCounterFor(Profiler::OriginStack(Profiler::Origin(
183                     m_compilation->bytecodes(), m_bytecodeOffset)))->address()));
184         }
185         
186         if (Options::eagerlyUpdateTopCallFrame())
187             updateTopCallFrame();
188         
189         switch (opcodeID) {
190         DEFINE_SLOW_OP(del_by_val)
191         DEFINE_SLOW_OP(in)
192         DEFINE_SLOW_OP(less)
193         DEFINE_SLOW_OP(lesseq)
194         DEFINE_SLOW_OP(greater)
195         DEFINE_SLOW_OP(greatereq)
196         DEFINE_SLOW_OP(is_function)
197         DEFINE_SLOW_OP(is_object_or_null)
198         DEFINE_SLOW_OP(typeof)
199
200         DEFINE_OP(op_add)
201         DEFINE_OP(op_bitand)
202         DEFINE_OP(op_bitor)
203         DEFINE_OP(op_bitxor)
204         DEFINE_OP(op_call)
205         DEFINE_OP(op_call_eval)
206         DEFINE_OP(op_call_varargs)
207         DEFINE_OP(op_construct_varargs)
208         DEFINE_OP(op_catch)
209         DEFINE_OP(op_construct)
210         DEFINE_OP(op_create_this)
211         DEFINE_OP(op_to_this)
212         DEFINE_OP(op_create_direct_arguments)
213         DEFINE_OP(op_create_scoped_arguments)
214         DEFINE_OP(op_create_out_of_band_arguments)
215         DEFINE_OP(op_check_tdz)
216         DEFINE_OP(op_debug)
217         DEFINE_OP(op_del_by_id)
218         DEFINE_OP(op_div)
219         DEFINE_OP(op_end)
220         DEFINE_OP(op_enter)
221         DEFINE_OP(op_get_scope)
222         DEFINE_OP(op_eq)
223         DEFINE_OP(op_eq_null)
224         case op_get_by_id_out_of_line:
225         case op_get_array_length:
226         DEFINE_OP(op_get_by_id)
227         DEFINE_OP(op_get_by_val)
228         DEFINE_OP(op_check_has_instance)
229         DEFINE_OP(op_instanceof)
230         DEFINE_OP(op_is_undefined)
231         DEFINE_OP(op_is_boolean)
232         DEFINE_OP(op_is_number)
233         DEFINE_OP(op_is_string)
234         DEFINE_OP(op_is_object)
235         DEFINE_OP(op_jeq_null)
236         DEFINE_OP(op_jfalse)
237         DEFINE_OP(op_jmp)
238         DEFINE_OP(op_jneq_null)
239         DEFINE_OP(op_jneq_ptr)
240         DEFINE_OP(op_jless)
241         DEFINE_OP(op_jlesseq)
242         DEFINE_OP(op_jgreater)
243         DEFINE_OP(op_jgreatereq)
244         DEFINE_OP(op_jnless)
245         DEFINE_OP(op_jnlesseq)
246         DEFINE_OP(op_jngreater)
247         DEFINE_OP(op_jngreatereq)
248         DEFINE_OP(op_jtrue)
249         DEFINE_OP(op_loop_hint)
250         DEFINE_OP(op_lshift)
251         DEFINE_OP(op_mod)
252         DEFINE_OP(op_mov)
253         DEFINE_OP(op_mul)
254         DEFINE_OP(op_negate)
255         DEFINE_OP(op_neq)
256         DEFINE_OP(op_neq_null)
257         DEFINE_OP(op_new_array)
258         DEFINE_OP(op_new_array_with_size)
259         DEFINE_OP(op_new_array_buffer)
260         DEFINE_OP(op_new_func)
261         DEFINE_OP(op_new_func_exp)
262         DEFINE_OP(op_new_object)
263         DEFINE_OP(op_new_regexp)
264         DEFINE_OP(op_not)
265         DEFINE_OP(op_nstricteq)
266         DEFINE_OP(op_dec)
267         DEFINE_OP(op_inc)
268         DEFINE_OP(op_profile_did_call)
269         DEFINE_OP(op_profile_will_call)
270         DEFINE_OP(op_profile_type)
271         DEFINE_OP(op_profile_control_flow)
272         DEFINE_OP(op_push_with_scope)
273         DEFINE_OP(op_create_lexical_environment)
274         DEFINE_OP(op_get_parent_scope)
275         case op_put_by_id_out_of_line:
276         case op_put_by_id_transition_direct:
277         case op_put_by_id_transition_normal:
278         case op_put_by_id_transition_direct_out_of_line:
279         case op_put_by_id_transition_normal_out_of_line:
280         DEFINE_OP(op_put_by_id)
281         DEFINE_OP(op_put_by_index)
282         case op_put_by_val_direct:
283         DEFINE_OP(op_put_by_val)
284         DEFINE_OP(op_put_getter_by_id)
285         DEFINE_OP(op_put_setter_by_id)
286         DEFINE_OP(op_put_getter_setter)
287
288         DEFINE_OP(op_ret)
289         DEFINE_OP(op_rshift)
290         DEFINE_OP(op_unsigned)
291         DEFINE_OP(op_urshift)
292         DEFINE_OP(op_strcat)
293         DEFINE_OP(op_stricteq)
294         DEFINE_OP(op_sub)
295         DEFINE_OP(op_switch_char)
296         DEFINE_OP(op_switch_imm)
297         DEFINE_OP(op_switch_string)
298         DEFINE_OP(op_throw)
299         DEFINE_OP(op_throw_static_error)
300         DEFINE_OP(op_to_number)
301         DEFINE_OP(op_to_string)
302         DEFINE_OP(op_to_primitive)
303
304         DEFINE_OP(op_resolve_scope)
305         DEFINE_OP(op_get_from_scope)
306         DEFINE_OP(op_put_to_scope)
307         DEFINE_OP(op_get_from_arguments)
308         DEFINE_OP(op_put_to_arguments)
309
310         DEFINE_OP(op_get_enumerable_length)
311         DEFINE_OP(op_has_generic_property)
312         DEFINE_OP(op_has_structure_property)
313         DEFINE_OP(op_has_indexed_property)
314         DEFINE_OP(op_get_direct_pname)
315         DEFINE_OP(op_get_property_enumerator)
316         DEFINE_OP(op_enumerator_structure_pname)
317         DEFINE_OP(op_enumerator_generic_pname)
318         DEFINE_OP(op_to_index_string)
319         default:
320             RELEASE_ASSERT_NOT_REACHED();
321         }
322     }
323
324     RELEASE_ASSERT(m_callLinkInfoIndex == m_callCompilationInfo.size());
325
326 #ifndef NDEBUG
327     // Reset this, in order to guard its use with ASSERTs.
328     m_bytecodeOffset = std::numeric_limits<unsigned>::max();
329 #endif
330 }
331
332 void JIT::privateCompileLinkPass()
333 {
334     unsigned jmpTableCount = m_jmpTable.size();
335     for (unsigned i = 0; i < jmpTableCount; ++i)
336         m_jmpTable[i].from.linkTo(m_labels[m_jmpTable[i].toBytecodeOffset], this);
337     m_jmpTable.clear();
338 }
339
340 void JIT::privateCompileSlowCases()
341 {
342     Instruction* instructionsBegin = m_codeBlock->instructions().begin();
343
344     m_getByIdIndex = 0;
345     m_putByIdIndex = 0;
346     m_byValInstructionIndex = 0;
347     m_callLinkInfoIndex = 0;
348     
349     // Use this to assert that slow-path code associates new profiling sites with existing
350     // ValueProfiles rather than creating new ones. This ensures that for a given instruction
351     // (say, get_by_id) we get combined statistics for both the fast-path executions of that
352     // instructions and the slow-path executions. Furthermore, if the slow-path code created
353     // new ValueProfiles then the ValueProfiles would no longer be sorted by bytecode offset,
354     // which would break the invariant necessary to use CodeBlock::valueProfileForBytecodeOffset().
355     unsigned numberOfValueProfiles = m_codeBlock->numberOfValueProfiles();
356
357     for (Vector<SlowCaseEntry>::iterator iter = m_slowCases.begin(); iter != m_slowCases.end();) {
358         m_bytecodeOffset = iter->to;
359
360         unsigned firstTo = m_bytecodeOffset;
361
362         Instruction* currentInstruction = instructionsBegin + m_bytecodeOffset;
363         
364         RareCaseProfile* rareCaseProfile = 0;
365         if (shouldEmitProfiling())
366             rareCaseProfile = m_codeBlock->addRareCaseProfile(m_bytecodeOffset);
367
368 #if ENABLE(JIT_VERBOSE)
369         dataLogF("Old JIT emitting slow code for bc#%u at offset 0x%lx.\n", m_bytecodeOffset, (long)debugOffset());
370 #endif
371         
372         if (m_disassembler)
373             m_disassembler->setForBytecodeSlowPath(m_bytecodeOffset, label());
374
375         switch (m_interpreter->getOpcodeID(currentInstruction->u.opcode)) {
376         DEFINE_SLOWCASE_OP(op_add)
377         DEFINE_SLOWCASE_OP(op_bitand)
378         DEFINE_SLOWCASE_OP(op_bitor)
379         DEFINE_SLOWCASE_OP(op_bitxor)
380         DEFINE_SLOWCASE_OP(op_call)
381         DEFINE_SLOWCASE_OP(op_call_eval)
382         DEFINE_SLOWCASE_OP(op_call_varargs)
383         DEFINE_SLOWCASE_OP(op_construct_varargs)
384         DEFINE_SLOWCASE_OP(op_construct)
385         DEFINE_SLOWCASE_OP(op_to_this)
386         DEFINE_SLOWCASE_OP(op_check_tdz)
387         DEFINE_SLOWCASE_OP(op_create_this)
388         DEFINE_SLOWCASE_OP(op_div)
389         DEFINE_SLOWCASE_OP(op_eq)
390         case op_get_by_id_out_of_line:
391         case op_get_array_length:
392         DEFINE_SLOWCASE_OP(op_get_by_id)
393         DEFINE_SLOWCASE_OP(op_get_by_val)
394         DEFINE_SLOWCASE_OP(op_check_has_instance)
395         DEFINE_SLOWCASE_OP(op_instanceof)
396         DEFINE_SLOWCASE_OP(op_jfalse)
397         DEFINE_SLOWCASE_OP(op_jless)
398         DEFINE_SLOWCASE_OP(op_jlesseq)
399         DEFINE_SLOWCASE_OP(op_jgreater)
400         DEFINE_SLOWCASE_OP(op_jgreatereq)
401         DEFINE_SLOWCASE_OP(op_jnless)
402         DEFINE_SLOWCASE_OP(op_jnlesseq)
403         DEFINE_SLOWCASE_OP(op_jngreater)
404         DEFINE_SLOWCASE_OP(op_jngreatereq)
405         DEFINE_SLOWCASE_OP(op_jtrue)
406         DEFINE_SLOWCASE_OP(op_loop_hint)
407         DEFINE_SLOWCASE_OP(op_lshift)
408         DEFINE_SLOWCASE_OP(op_mod)
409         DEFINE_SLOWCASE_OP(op_mul)
410         DEFINE_SLOWCASE_OP(op_negate)
411         DEFINE_SLOWCASE_OP(op_neq)
412         DEFINE_SLOWCASE_OP(op_new_object)
413         DEFINE_SLOWCASE_OP(op_not)
414         DEFINE_SLOWCASE_OP(op_nstricteq)
415         DEFINE_SLOWCASE_OP(op_dec)
416         DEFINE_SLOWCASE_OP(op_inc)
417         case op_put_by_id_out_of_line:
418         case op_put_by_id_transition_direct:
419         case op_put_by_id_transition_normal:
420         case op_put_by_id_transition_direct_out_of_line:
421         case op_put_by_id_transition_normal_out_of_line:
422         DEFINE_SLOWCASE_OP(op_put_by_id)
423         case op_put_by_val_direct:
424         DEFINE_SLOWCASE_OP(op_put_by_val)
425         DEFINE_SLOWCASE_OP(op_rshift)
426         DEFINE_SLOWCASE_OP(op_unsigned)
427         DEFINE_SLOWCASE_OP(op_urshift)
428         DEFINE_SLOWCASE_OP(op_stricteq)
429         DEFINE_SLOWCASE_OP(op_sub)
430         DEFINE_SLOWCASE_OP(op_to_number)
431         DEFINE_SLOWCASE_OP(op_to_string)
432         DEFINE_SLOWCASE_OP(op_to_primitive)
433         DEFINE_SLOWCASE_OP(op_has_indexed_property)
434         DEFINE_SLOWCASE_OP(op_has_structure_property)
435         DEFINE_SLOWCASE_OP(op_get_direct_pname)
436
437         DEFINE_SLOWCASE_OP(op_resolve_scope)
438         DEFINE_SLOWCASE_OP(op_get_from_scope)
439         DEFINE_SLOWCASE_OP(op_put_to_scope)
440
441         default:
442             RELEASE_ASSERT_NOT_REACHED();
443         }
444
445         RELEASE_ASSERT_WITH_MESSAGE(iter == m_slowCases.end() || firstTo != iter->to, "Not enough jumps linked in slow case codegen.");
446         RELEASE_ASSERT_WITH_MESSAGE(firstTo == (iter - 1)->to, "Too many jumps linked in slow case codegen.");
447         
448         if (shouldEmitProfiling())
449             add32(TrustedImm32(1), AbsoluteAddress(&rareCaseProfile->m_counter));
450
451         emitJumpSlowToHot(jump(), 0);
452     }
453
454     RELEASE_ASSERT(m_getByIdIndex == m_getByIds.size());
455     RELEASE_ASSERT(m_putByIdIndex == m_putByIds.size());
456     RELEASE_ASSERT(m_callLinkInfoIndex == m_callCompilationInfo.size());
457     RELEASE_ASSERT(numberOfValueProfiles == m_codeBlock->numberOfValueProfiles());
458
459 #ifndef NDEBUG
460     // Reset this, in order to guard its use with ASSERTs.
461     m_bytecodeOffset = std::numeric_limits<unsigned>::max();
462 #endif
463 }
464
465 CompilationResult JIT::privateCompile(JITCompilationEffort effort)
466 {
467     DFG::CapabilityLevel level = m_codeBlock->capabilityLevel();
468     switch (level) {
469     case DFG::CannotCompile:
470         m_canBeOptimized = false;
471         m_canBeOptimizedOrInlined = false;
472         m_shouldEmitProfiling = false;
473         break;
474     case DFG::CanCompile:
475     case DFG::CanCompileAndInline:
476         m_canBeOptimized = true;
477         m_canBeOptimizedOrInlined = true;
478         m_shouldEmitProfiling = true;
479         break;
480     default:
481         RELEASE_ASSERT_NOT_REACHED();
482         break;
483     }
484     
485     switch (m_codeBlock->codeType()) {
486     case GlobalCode:
487     case EvalCode:
488         m_codeBlock->m_shouldAlwaysBeInlined = false;
489         break;
490     case FunctionCode:
491         // We could have already set it to false because we detected an uninlineable call.
492         // Don't override that observation.
493         m_codeBlock->m_shouldAlwaysBeInlined &= canInline(level) && DFG::mightInlineFunction(m_codeBlock);
494         break;
495     }
496
497     // This ensures that we have the most up to date type information when performing typecheck optimizations for op_profile_type.
498     if (m_vm->typeProfiler())
499         m_vm->typeProfilerLog()->processLogEntries(ASCIILiteral("Preparing for JIT compilation."));
500     
501     if (Options::showDisassembly() || m_vm->m_perBytecodeProfiler)
502         m_disassembler = std::make_unique<JITDisassembler>(m_codeBlock);
503     if (m_vm->m_perBytecodeProfiler) {
504         m_compilation = adoptRef(
505             new Profiler::Compilation(
506                 m_vm->m_perBytecodeProfiler->ensureBytecodesFor(m_codeBlock),
507                 Profiler::Baseline));
508         m_compilation->addProfiledBytecodes(*m_vm->m_perBytecodeProfiler, m_codeBlock);
509     }
510     
511     if (m_disassembler)
512         m_disassembler->setStartOfCode(label());
513
514     // Just add a little bit of randomness to the codegen
515     if (m_randomGenerator.getUint32() & 1)
516         nop();
517
518     emitFunctionPrologue();
519     emitPutImmediateToCallFrameHeader(m_codeBlock, JSStack::CodeBlock);
520
521     Label beginLabel(this);
522
523     sampleCodeBlock(m_codeBlock);
524 #if ENABLE(OPCODE_SAMPLING)
525     sampleInstruction(m_codeBlock->instructions().begin());
526 #endif
527
528     if (m_codeBlock->codeType() == FunctionCode) {
529         ASSERT(m_bytecodeOffset == std::numeric_limits<unsigned>::max());
530         if (shouldEmitProfiling()) {
531             for (int argument = 0; argument < m_codeBlock->numParameters(); ++argument) {
532                 // If this is a constructor, then we want to put in a dummy profiling site (to
533                 // keep things consistent) but we don't actually want to record the dummy value.
534                 if (m_codeBlock->m_isConstructor && !argument)
535                     continue;
536                 int offset = CallFrame::argumentOffsetIncludingThis(argument) * static_cast<int>(sizeof(Register));
537 #if USE(JSVALUE64)
538                 load64(Address(callFrameRegister, offset), regT0);
539 #elif USE(JSVALUE32_64)
540                 load32(Address(callFrameRegister, offset + OBJECT_OFFSETOF(JSValue, u.asBits.payload)), regT0);
541                 load32(Address(callFrameRegister, offset + OBJECT_OFFSETOF(JSValue, u.asBits.tag)), regT1);
542 #endif
543                 emitValueProfilingSite(m_codeBlock->valueProfileForArgument(argument));
544             }
545         }
546     }
547
548     addPtr(TrustedImm32(stackPointerOffsetFor(m_codeBlock) * sizeof(Register)), callFrameRegister, regT1);
549     Jump stackOverflow = branchPtr(Above, AbsoluteAddress(m_vm->addressOfStackLimit()), regT1);
550
551     move(regT1, stackPointerRegister);
552     checkStackPointerAlignment();
553
554     privateCompileMainPass();
555     privateCompileLinkPass();
556     privateCompileSlowCases();
557     
558     if (m_disassembler)
559         m_disassembler->setEndOfSlowPath(label());
560
561     stackOverflow.link(this);
562     m_bytecodeOffset = 0;
563     if (maxFrameExtentForSlowPathCall)
564         addPtr(TrustedImm32(-maxFrameExtentForSlowPathCall), stackPointerRegister);
565     callOperationWithCallFrameRollbackOnException(operationThrowStackOverflowError, m_codeBlock);
566
567     Label arityCheck;
568     if (m_codeBlock->codeType() == FunctionCode) {
569         arityCheck = label();
570         store8(TrustedImm32(0), &m_codeBlock->m_shouldAlwaysBeInlined);
571         emitFunctionPrologue();
572         emitPutImmediateToCallFrameHeader(m_codeBlock, JSStack::CodeBlock);
573
574         load32(payloadFor(JSStack::ArgumentCount), regT1);
575         branch32(AboveOrEqual, regT1, TrustedImm32(m_codeBlock->m_numParameters)).linkTo(beginLabel, this);
576
577         m_bytecodeOffset = 0;
578
579         if (maxFrameExtentForSlowPathCall)
580             addPtr(TrustedImm32(-maxFrameExtentForSlowPathCall), stackPointerRegister);
581         callOperationWithCallFrameRollbackOnException(m_codeBlock->m_isConstructor ? operationConstructArityCheck : operationCallArityCheck);
582         if (maxFrameExtentForSlowPathCall)
583             addPtr(TrustedImm32(maxFrameExtentForSlowPathCall), stackPointerRegister);
584         if (returnValueGPR != regT0)
585             move(returnValueGPR, regT0);
586         branchTest32(Zero, regT0).linkTo(beginLabel, this);
587         GPRReg thunkReg;
588 #if USE(JSVALUE64)
589         thunkReg = GPRInfo::regT7;
590 #else
591         thunkReg = GPRInfo::regT5;
592 #endif
593         CodeLocationLabel* failThunkLabels =
594             m_vm->arityCheckFailReturnThunks->returnPCsFor(*m_vm, m_codeBlock->numParameters());
595         move(TrustedImmPtr(failThunkLabels), thunkReg);
596         loadPtr(BaseIndex(thunkReg, regT0, timesPtr()), thunkReg);
597         emitNakedCall(m_vm->getCTIStub(arityFixupGenerator).code());
598
599 #if !ASSERT_DISABLED
600         m_bytecodeOffset = std::numeric_limits<unsigned>::max(); // Reset this, in order to guard its use with ASSERTs.
601 #endif
602
603         jump(beginLabel);
604     }
605
606     ASSERT(m_jmpTable.isEmpty());
607     
608     privateCompileExceptionHandlers();
609     
610     if (m_disassembler)
611         m_disassembler->setEndOfCode(label());
612
613     LinkBuffer patchBuffer(*m_vm, *this, m_codeBlock, effort);
614     if (patchBuffer.didFailToAllocate())
615         return CompilationFailed;
616
617     // Translate vPC offsets into addresses in JIT generated code, for switch tables.
618     for (unsigned i = 0; i < m_switches.size(); ++i) {
619         SwitchRecord record = m_switches[i];
620         unsigned bytecodeOffset = record.bytecodeOffset;
621
622         if (record.type != SwitchRecord::String) {
623             ASSERT(record.type == SwitchRecord::Immediate || record.type == SwitchRecord::Character); 
624             ASSERT(record.jumpTable.simpleJumpTable->branchOffsets.size() == record.jumpTable.simpleJumpTable->ctiOffsets.size());
625
626             record.jumpTable.simpleJumpTable->ctiDefault = patchBuffer.locationOf(m_labels[bytecodeOffset + record.defaultOffset]);
627
628             for (unsigned j = 0; j < record.jumpTable.simpleJumpTable->branchOffsets.size(); ++j) {
629                 unsigned offset = record.jumpTable.simpleJumpTable->branchOffsets[j];
630                 record.jumpTable.simpleJumpTable->ctiOffsets[j] = offset ? patchBuffer.locationOf(m_labels[bytecodeOffset + offset]) : record.jumpTable.simpleJumpTable->ctiDefault;
631             }
632         } else {
633             ASSERT(record.type == SwitchRecord::String);
634
635             record.jumpTable.stringJumpTable->ctiDefault = patchBuffer.locationOf(m_labels[bytecodeOffset + record.defaultOffset]);
636
637             StringJumpTable::StringOffsetTable::iterator end = record.jumpTable.stringJumpTable->offsetTable.end();            
638             for (StringJumpTable::StringOffsetTable::iterator it = record.jumpTable.stringJumpTable->offsetTable.begin(); it != end; ++it) {
639                 unsigned offset = it->value.branchOffset;
640                 it->value.ctiOffset = offset ? patchBuffer.locationOf(m_labels[bytecodeOffset + offset]) : record.jumpTable.stringJumpTable->ctiDefault;
641             }
642         }
643     }
644
645     for (size_t i = 0; i < m_codeBlock->numberOfExceptionHandlers(); ++i) {
646         HandlerInfo& handler = m_codeBlock->exceptionHandler(i);
647         handler.nativeCode = patchBuffer.locationOf(m_labels[handler.target]);
648     }
649
650     for (Vector<CallRecord>::iterator iter = m_calls.begin(); iter != m_calls.end(); ++iter) {
651         if (iter->to)
652             patchBuffer.link(iter->from, FunctionPtr(iter->to));
653     }
654
655     for (unsigned i = m_getByIds.size(); i--;)
656         m_getByIds[i].finalize(patchBuffer);
657     for (unsigned i = m_putByIds.size(); i--;)
658         m_putByIds[i].finalize(patchBuffer);
659
660     for (const auto& byValCompilationInfo : m_byValCompilationInfo) {
661         PatchableJump patchableNotIndexJump = byValCompilationInfo.notIndexJump;
662         CodeLocationJump notIndexJump = CodeLocationJump();
663         if (Jump(patchableNotIndexJump).isSet())
664             notIndexJump = CodeLocationJump(patchBuffer.locationOf(patchableNotIndexJump));
665         CodeLocationJump badTypeJump = CodeLocationJump(patchBuffer.locationOf(byValCompilationInfo.badTypeJump));
666         CodeLocationLabel doneTarget = patchBuffer.locationOf(byValCompilationInfo.doneTarget);
667         CodeLocationLabel slowPathTarget = patchBuffer.locationOf(byValCompilationInfo.slowPathTarget);
668         CodeLocationCall returnAddress = patchBuffer.locationOf(byValCompilationInfo.returnAddress);
669
670         *byValCompilationInfo.byValInfo = ByValInfo(
671             byValCompilationInfo.bytecodeIndex,
672             notIndexJump,
673             badTypeJump,
674             byValCompilationInfo.arrayMode,
675             byValCompilationInfo.arrayProfile,
676             differenceBetweenCodePtr(badTypeJump, doneTarget),
677             differenceBetweenCodePtr(returnAddress, slowPathTarget));
678     }
679     for (unsigned i = 0; i < m_callCompilationInfo.size(); ++i) {
680         CallCompilationInfo& compilationInfo = m_callCompilationInfo[i];
681         CallLinkInfo& info = *compilationInfo.callLinkInfo;
682         info.setCallLocations(patchBuffer.locationOfNearCall(compilationInfo.callReturnLocation),
683             patchBuffer.locationOf(compilationInfo.hotPathBegin),
684             patchBuffer.locationOfNearCall(compilationInfo.hotPathOther));
685     }
686
687     CompactJITCodeMap::Encoder jitCodeMapEncoder;
688     for (unsigned bytecodeOffset = 0; bytecodeOffset < m_labels.size(); ++bytecodeOffset) {
689         if (m_labels[bytecodeOffset].isSet())
690             jitCodeMapEncoder.append(bytecodeOffset, patchBuffer.offsetOf(m_labels[bytecodeOffset]));
691     }
692     m_codeBlock->setJITCodeMap(jitCodeMapEncoder.finish());
693
694     MacroAssemblerCodePtr withArityCheck;
695     if (m_codeBlock->codeType() == FunctionCode)
696         withArityCheck = patchBuffer.locationOf(arityCheck);
697
698     if (Options::showDisassembly()) {
699         m_disassembler->dump(patchBuffer);
700         patchBuffer.didAlreadyDisassemble();
701     }
702     if (m_compilation) {
703         m_disassembler->reportToProfiler(m_compilation.get(), patchBuffer);
704         m_vm->m_perBytecodeProfiler->addCompilation(m_compilation);
705     }
706     
707     CodeRef result = FINALIZE_CODE(
708         patchBuffer,
709         ("Baseline JIT code for %s", toCString(CodeBlockWithJITType(m_codeBlock, JITCode::BaselineJIT)).data()));
710     
711     m_vm->machineCodeBytesPerBytecodeWordForBaselineJIT.add(
712         static_cast<double>(result.size()) /
713         static_cast<double>(m_codeBlock->instructions().size()));
714     
715     m_codeBlock->shrinkToFit(CodeBlock::LateShrink);
716     m_codeBlock->setJITCode(
717         adoptRef(new DirectJITCode(result, withArityCheck, JITCode::BaselineJIT)));
718     
719 #if ENABLE(JIT_VERBOSE)
720     dataLogF("JIT generated code for %p at [%p, %p).\n", m_codeBlock, result.executableMemory()->start(), result.executableMemory()->end());
721 #endif
722     
723     return CompilationSuccessful;
724 }
725
726 void JIT::privateCompileExceptionHandlers()
727 {
728     if (!m_exceptionChecksWithCallFrameRollback.empty()) {
729         m_exceptionChecksWithCallFrameRollback.link(this);
730
731         // lookupExceptionHandlerFromCallerFrame is passed two arguments, the VM and the exec (the CallFrame*).
732
733         move(TrustedImmPtr(vm()), GPRInfo::argumentGPR0);
734         move(GPRInfo::callFrameRegister, GPRInfo::argumentGPR1);
735
736 #if CPU(X86)
737         // FIXME: should use the call abstraction, but this is currently in the SpeculativeJIT layer!
738         poke(GPRInfo::argumentGPR0);
739         poke(GPRInfo::argumentGPR1, 1);
740 #endif
741         m_calls.append(CallRecord(call(), std::numeric_limits<unsigned>::max(), FunctionPtr(lookupExceptionHandlerFromCallerFrame).value()));
742         jumpToExceptionHandler();
743     }
744
745     if (!m_exceptionChecks.empty()) {
746         m_exceptionChecks.link(this);
747
748         // lookupExceptionHandler is passed two arguments, the VM and the exec (the CallFrame*).
749         move(TrustedImmPtr(vm()), GPRInfo::argumentGPR0);
750         move(GPRInfo::callFrameRegister, GPRInfo::argumentGPR1);
751
752 #if CPU(X86)
753         // FIXME: should use the call abstraction, but this is currently in the SpeculativeJIT layer!
754         poke(GPRInfo::argumentGPR0);
755         poke(GPRInfo::argumentGPR1, 1);
756 #endif
757         m_calls.append(CallRecord(call(), std::numeric_limits<unsigned>::max(), FunctionPtr(lookupExceptionHandler).value()));
758         jumpToExceptionHandler();
759     }
760 }
761
762 unsigned JIT::frameRegisterCountFor(CodeBlock* codeBlock)
763 {
764     ASSERT(static_cast<unsigned>(codeBlock->m_numCalleeRegisters) == WTF::roundUpToMultipleOf(stackAlignmentRegisters(), static_cast<unsigned>(codeBlock->m_numCalleeRegisters)));
765
766     return roundLocalRegisterCountForFramePointerOffset(codeBlock->m_numCalleeRegisters + maxFrameExtentForSlowPathCallInRegisters);
767 }
768
769 int JIT::stackPointerOffsetFor(CodeBlock* codeBlock)
770 {
771     return virtualRegisterForLocal(frameRegisterCountFor(codeBlock) - 1).offset();
772 }
773
774 } // namespace JSC
775
776 #endif // ENABLE(JIT)