Merge r171389, r171495, r171508, r171510, r171605, r171606, r171611, r171614, r171763...
[WebKit-https.git] / Source / JavaScriptCore / jit / JIT.cpp
1 /*
2  * Copyright (C) 2008, 2009, 2012, 2013, 2014 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 // This probably does not belong here; adding here for now as a quick Windows build fix.
33 #if ENABLE(ASSEMBLER) && CPU(X86) && !OS(MAC_OS_X)
34 #include "MacroAssembler.h"
35 JSC::MacroAssemblerX86Common::SSE2CheckState JSC::MacroAssemblerX86Common::s_sse2CheckState = NotCheckedSSE2;
36 #endif
37
38 #include "ArityCheckFailReturnThunks.h"
39 #include "CodeBlock.h"
40 #include "DFGCapabilities.h"
41 #include "Interpreter.h"
42 #include "JITInlines.h"
43 #include "JITOperations.h"
44 #include "JSArray.h"
45 #include "JSFunction.h"
46 #include "LinkBuffer.h"
47 #include "MaxFrameExtentForSlowPathCall.h"
48 #include "JSCInlines.h"
49 #include "ProfilerDatabase.h"
50 #include "RepatchBuffer.h"
51 #include "ResultType.h"
52 #include "SamplingTool.h"
53 #include "SlowPathCall.h"
54 #include "StackAlignment.h"
55 #include <wtf/CryptographicallyRandomNumber.h>
56
57 using namespace std;
58
59 namespace JSC {
60
61 void ctiPatchNearCallByReturnAddress(CodeBlock* codeblock, ReturnAddressPtr returnAddress, MacroAssemblerCodePtr newCalleeFunction)
62 {
63     RepatchBuffer repatchBuffer(codeblock);
64     repatchBuffer.relinkNearCallerToTrampoline(returnAddress, newCalleeFunction);
65 }
66
67 void ctiPatchCallByReturnAddress(CodeBlock* codeblock, ReturnAddressPtr returnAddress, MacroAssemblerCodePtr newCalleeFunction)
68 {
69     RepatchBuffer repatchBuffer(codeblock);
70     repatchBuffer.relinkCallerToTrampoline(returnAddress, newCalleeFunction);
71 }
72
73 void ctiPatchCallByReturnAddress(CodeBlock* codeblock, ReturnAddressPtr returnAddress, FunctionPtr newCalleeFunction)
74 {
75     RepatchBuffer repatchBuffer(codeblock);
76     repatchBuffer.relinkCallerToFunction(returnAddress, newCalleeFunction);
77 }
78
79 JIT::JIT(VM* vm, CodeBlock* codeBlock)
80     : JSInterfaceJIT(vm, codeBlock)
81     , m_interpreter(vm->interpreter)
82     , m_labels(codeBlock ? codeBlock->numberOfInstructions() : 0)
83     , m_bytecodeOffset((unsigned)-1)
84     , m_getByIdIndex(UINT_MAX)
85     , m_putByIdIndex(UINT_MAX)
86     , m_byValInstructionIndex(UINT_MAX)
87     , m_callLinkInfoIndex(UINT_MAX)
88     , m_randomGenerator(cryptographicallyRandomNumber())
89     , m_canBeOptimized(false)
90     , m_shouldEmitProfiling(false)
91 {
92 }
93
94 #if ENABLE(DFG_JIT)
95 void JIT::emitEnterOptimizationCheck()
96 {
97     if (!canBeOptimized())
98         return;
99
100     JumpList skipOptimize;
101     
102     skipOptimize.append(branchAdd32(Signed, TrustedImm32(Options::executionCounterIncrementForEntry()), AbsoluteAddress(m_codeBlock->addressOfJITExecuteCounter())));
103     ASSERT(!m_bytecodeOffset);
104     callOperation(operationOptimize, m_bytecodeOffset);
105     skipOptimize.append(branchTestPtr(Zero, returnValueGPR));
106     move(returnValueGPR2, stackPointerRegister);
107     jump(returnValueGPR);
108     skipOptimize.link(this);
109 }
110 #endif
111
112 void JIT::assertStackPointerOffset()
113 {
114     if (ASSERT_DISABLED)
115         return;
116     
117     addPtr(TrustedImm32(stackPointerOffsetFor(m_codeBlock) * sizeof(Register)), callFrameRegister, regT0);
118     Jump ok = branchPtr(Equal, regT0, stackPointerRegister);
119     breakpoint();
120     ok.link(this);
121 }
122
123 #define NEXT_OPCODE(name) \
124     m_bytecodeOffset += OPCODE_LENGTH(name); \
125     break;
126
127 #define DEFINE_SLOW_OP(name) \
128     case op_##name: { \
129         JITSlowPathCall slowPathCall(this, currentInstruction, slow_path_##name); \
130         slowPathCall.call(); \
131         NEXT_OPCODE(op_##name); \
132     }
133
134 #define DEFINE_OP(name) \
135     case name: { \
136         emit_##name(currentInstruction); \
137         NEXT_OPCODE(name); \
138     }
139
140 #define DEFINE_SLOWCASE_OP(name) \
141     case name: { \
142         emitSlow_##name(currentInstruction, iter); \
143         NEXT_OPCODE(name); \
144     }
145
146 void JIT::privateCompileMainPass()
147 {
148     jitAssertTagsInPlace();
149     jitAssertArgumentCountSane();
150     
151     Instruction* instructionsBegin = m_codeBlock->instructions().begin();
152     unsigned instructionCount = m_codeBlock->instructions().size();
153
154     m_callLinkInfoIndex = 0;
155
156     for (m_bytecodeOffset = 0; m_bytecodeOffset < instructionCount; ) {
157         if (m_disassembler)
158             m_disassembler->setForBytecodeMainPath(m_bytecodeOffset, label());
159         Instruction* currentInstruction = instructionsBegin + m_bytecodeOffset;
160         ASSERT_WITH_MESSAGE(m_interpreter->isOpcode(currentInstruction->u.opcode), "privateCompileMainPass gone bad @ %d", m_bytecodeOffset);
161
162 #if ENABLE(OPCODE_SAMPLING)
163         if (m_bytecodeOffset > 0) // Avoid the overhead of sampling op_enter twice.
164             sampleInstruction(currentInstruction);
165 #endif
166
167         m_labels[m_bytecodeOffset] = label();
168
169 #if ENABLE(JIT_VERBOSE)
170         dataLogF("Old JIT emitting code for bc#%u at offset 0x%lx.\n", m_bytecodeOffset, (long)debugOffset());
171 #endif
172         
173         OpcodeID opcodeID = m_interpreter->getOpcodeID(currentInstruction->u.opcode);
174
175         if (m_compilation) {
176             add64(
177                 TrustedImm32(1),
178                 AbsoluteAddress(m_compilation->executionCounterFor(Profiler::OriginStack(Profiler::Origin(
179                     m_compilation->bytecodes(), m_bytecodeOffset)))->address()));
180         }
181         
182         if (Options::eagerlyUpdateTopCallFrame())
183             updateTopCallFrame();
184         
185         switch (opcodeID) {
186         DEFINE_SLOW_OP(del_by_val)
187         DEFINE_SLOW_OP(in)
188         DEFINE_SLOW_OP(less)
189         DEFINE_SLOW_OP(lesseq)
190         DEFINE_SLOW_OP(greater)
191         DEFINE_SLOW_OP(greatereq)
192         DEFINE_SLOW_OP(is_function)
193         DEFINE_SLOW_OP(is_object)
194         DEFINE_SLOW_OP(typeof)
195
196         DEFINE_OP(op_touch_entry)
197         DEFINE_OP(op_add)
198         DEFINE_OP(op_bitand)
199         DEFINE_OP(op_bitor)
200         DEFINE_OP(op_bitxor)
201         DEFINE_OP(op_call)
202         DEFINE_OP(op_call_eval)
203         DEFINE_OP(op_call_varargs)
204         DEFINE_OP(op_construct_varargs)
205         DEFINE_OP(op_catch)
206         DEFINE_OP(op_construct)
207         DEFINE_OP(op_get_callee)
208         DEFINE_OP(op_create_this)
209         DEFINE_OP(op_to_this)
210         DEFINE_OP(op_init_lazy_reg)
211         DEFINE_OP(op_create_arguments)
212         DEFINE_OP(op_debug)
213         DEFINE_OP(op_del_by_id)
214         DEFINE_OP(op_div)
215         DEFINE_OP(op_end)
216         DEFINE_OP(op_enter)
217         DEFINE_OP(op_create_activation)
218         DEFINE_OP(op_eq)
219         DEFINE_OP(op_eq_null)
220         case op_get_by_id_out_of_line:
221         case op_get_array_length:
222         DEFINE_OP(op_get_by_id)
223         DEFINE_OP(op_get_arguments_length)
224         DEFINE_OP(op_get_by_val)
225         DEFINE_OP(op_get_argument_by_val)
226         DEFINE_OP(op_check_has_instance)
227         DEFINE_OP(op_instanceof)
228         DEFINE_OP(op_is_undefined)
229         DEFINE_OP(op_is_boolean)
230         DEFINE_OP(op_is_number)
231         DEFINE_OP(op_is_string)
232         DEFINE_OP(op_jeq_null)
233         DEFINE_OP(op_jfalse)
234         DEFINE_OP(op_jmp)
235         DEFINE_OP(op_jneq_null)
236         DEFINE_OP(op_jneq_ptr)
237         DEFINE_OP(op_jless)
238         DEFINE_OP(op_jlesseq)
239         DEFINE_OP(op_jgreater)
240         DEFINE_OP(op_jgreatereq)
241         DEFINE_OP(op_jnless)
242         DEFINE_OP(op_jnlesseq)
243         DEFINE_OP(op_jngreater)
244         DEFINE_OP(op_jngreatereq)
245         DEFINE_OP(op_jtrue)
246         DEFINE_OP(op_loop_hint)
247         DEFINE_OP(op_lshift)
248         DEFINE_OP(op_mod)
249         DEFINE_OP(op_captured_mov)
250         DEFINE_OP(op_mov)
251         DEFINE_OP(op_mul)
252         DEFINE_OP(op_negate)
253         DEFINE_OP(op_neq)
254         DEFINE_OP(op_neq_null)
255         DEFINE_OP(op_new_array)
256         DEFINE_OP(op_new_array_with_size)
257         DEFINE_OP(op_new_array_buffer)
258         DEFINE_OP(op_new_func)
259         DEFINE_OP(op_new_captured_func)
260         DEFINE_OP(op_new_func_exp)
261         DEFINE_OP(op_new_object)
262         DEFINE_OP(op_new_regexp)
263         DEFINE_OP(op_not)
264         DEFINE_OP(op_nstricteq)
265         DEFINE_OP(op_pop_scope)
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_push_name_scope)
271         DEFINE_OP(op_push_with_scope)
272         case op_put_by_id_out_of_line:
273         case op_put_by_id_transition_direct:
274         case op_put_by_id_transition_normal:
275         case op_put_by_id_transition_direct_out_of_line:
276         case op_put_by_id_transition_normal_out_of_line:
277         DEFINE_OP(op_put_by_id)
278         DEFINE_OP(op_put_by_index)
279         case op_put_by_val_direct:
280         DEFINE_OP(op_put_by_val)
281         DEFINE_OP(op_put_getter_setter)
282         case op_init_global_const_nop:
283             NEXT_OPCODE(op_init_global_const_nop);
284         DEFINE_OP(op_init_global_const)
285
286         DEFINE_OP(op_ret)
287         DEFINE_OP(op_ret_object_or_this)
288         DEFINE_OP(op_rshift)
289         DEFINE_OP(op_unsigned)
290         DEFINE_OP(op_urshift)
291         DEFINE_OP(op_strcat)
292         DEFINE_OP(op_stricteq)
293         DEFINE_OP(op_sub)
294         DEFINE_OP(op_switch_char)
295         DEFINE_OP(op_switch_imm)
296         DEFINE_OP(op_switch_string)
297         DEFINE_OP(op_tear_off_activation)
298         DEFINE_OP(op_tear_off_arguments)
299         DEFINE_OP(op_throw)
300         DEFINE_OP(op_throw_static_error)
301         DEFINE_OP(op_to_number)
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
308         DEFINE_OP(op_get_enumerable_length)
309         DEFINE_OP(op_has_generic_property)
310         DEFINE_OP(op_has_structure_property)
311         DEFINE_OP(op_has_indexed_property)
312         DEFINE_OP(op_get_direct_pname)
313         DEFINE_OP(op_get_structure_property_enumerator)
314         DEFINE_OP(op_get_generic_property_enumerator)
315         DEFINE_OP(op_next_enumerator_pname)
316         DEFINE_OP(op_to_index_string)
317         default:
318             RELEASE_ASSERT_NOT_REACHED();
319         }
320     }
321
322     RELEASE_ASSERT(m_callLinkInfoIndex == m_callCompilationInfo.size());
323
324 #ifndef NDEBUG
325     // Reset this, in order to guard its use with ASSERTs.
326     m_bytecodeOffset = (unsigned)-1;
327 #endif
328 }
329
330 void JIT::privateCompileLinkPass()
331 {
332     unsigned jmpTableCount = m_jmpTable.size();
333     for (unsigned i = 0; i < jmpTableCount; ++i)
334         m_jmpTable[i].from.linkTo(m_labels[m_jmpTable[i].toBytecodeOffset], this);
335     m_jmpTable.clear();
336 }
337
338 void JIT::privateCompileSlowCases()
339 {
340     Instruction* instructionsBegin = m_codeBlock->instructions().begin();
341
342     m_getByIdIndex = 0;
343     m_putByIdIndex = 0;
344     m_byValInstructionIndex = 0;
345     m_callLinkInfoIndex = 0;
346     
347     // Use this to assert that slow-path code associates new profiling sites with existing
348     // ValueProfiles rather than creating new ones. This ensures that for a given instruction
349     // (say, get_by_id) we get combined statistics for both the fast-path executions of that
350     // instructions and the slow-path executions. Furthermore, if the slow-path code created
351     // new ValueProfiles then the ValueProfiles would no longer be sorted by bytecode offset,
352     // which would break the invariant necessary to use CodeBlock::valueProfileForBytecodeOffset().
353     unsigned numberOfValueProfiles = m_codeBlock->numberOfValueProfiles();
354
355     for (Vector<SlowCaseEntry>::iterator iter = m_slowCases.begin(); iter != m_slowCases.end();) {
356         m_bytecodeOffset = iter->to;
357
358         unsigned firstTo = m_bytecodeOffset;
359
360         Instruction* currentInstruction = instructionsBegin + m_bytecodeOffset;
361         
362         RareCaseProfile* rareCaseProfile = 0;
363         if (shouldEmitProfiling())
364             rareCaseProfile = m_codeBlock->addRareCaseProfile(m_bytecodeOffset);
365
366 #if ENABLE(JIT_VERBOSE)
367         dataLogF("Old JIT emitting slow code for bc#%u at offset 0x%lx.\n", m_bytecodeOffset, (long)debugOffset());
368 #endif
369         
370         if (m_disassembler)
371             m_disassembler->setForBytecodeSlowPath(m_bytecodeOffset, label());
372
373         switch (m_interpreter->getOpcodeID(currentInstruction->u.opcode)) {
374         DEFINE_SLOWCASE_OP(op_add)
375         DEFINE_SLOWCASE_OP(op_bitand)
376         DEFINE_SLOWCASE_OP(op_bitor)
377         DEFINE_SLOWCASE_OP(op_bitxor)
378         DEFINE_SLOWCASE_OP(op_call)
379         DEFINE_SLOWCASE_OP(op_call_eval)
380         DEFINE_SLOWCASE_OP(op_call_varargs)
381         DEFINE_SLOWCASE_OP(op_construct_varargs)
382         DEFINE_SLOWCASE_OP(op_construct)
383         DEFINE_SLOWCASE_OP(op_to_this)
384         DEFINE_SLOWCASE_OP(op_create_this)
385         DEFINE_SLOWCASE_OP(op_captured_mov)
386         DEFINE_SLOWCASE_OP(op_div)
387         DEFINE_SLOWCASE_OP(op_eq)
388         DEFINE_SLOWCASE_OP(op_get_callee)
389         case op_get_by_id_out_of_line:
390         case op_get_array_length:
391         DEFINE_SLOWCASE_OP(op_get_by_id)
392         DEFINE_SLOWCASE_OP(op_get_arguments_length)
393         DEFINE_SLOWCASE_OP(op_get_by_val)
394         DEFINE_SLOWCASE_OP(op_get_argument_by_val)
395         DEFINE_SLOWCASE_OP(op_check_has_instance)
396         DEFINE_SLOWCASE_OP(op_instanceof)
397         DEFINE_SLOWCASE_OP(op_jfalse)
398         DEFINE_SLOWCASE_OP(op_jless)
399         DEFINE_SLOWCASE_OP(op_jlesseq)
400         DEFINE_SLOWCASE_OP(op_jgreater)
401         DEFINE_SLOWCASE_OP(op_jgreatereq)
402         DEFINE_SLOWCASE_OP(op_jnless)
403         DEFINE_SLOWCASE_OP(op_jnlesseq)
404         DEFINE_SLOWCASE_OP(op_jngreater)
405         DEFINE_SLOWCASE_OP(op_jngreatereq)
406         DEFINE_SLOWCASE_OP(op_jtrue)
407         DEFINE_SLOWCASE_OP(op_loop_hint)
408         DEFINE_SLOWCASE_OP(op_lshift)
409         DEFINE_SLOWCASE_OP(op_mod)
410         DEFINE_SLOWCASE_OP(op_mul)
411         DEFINE_SLOWCASE_OP(op_negate)
412         DEFINE_SLOWCASE_OP(op_neq)
413         DEFINE_SLOWCASE_OP(op_new_object)
414         DEFINE_SLOWCASE_OP(op_not)
415         DEFINE_SLOWCASE_OP(op_nstricteq)
416         DEFINE_SLOWCASE_OP(op_dec)
417         DEFINE_SLOWCASE_OP(op_inc)
418         case op_put_by_id_out_of_line:
419         case op_put_by_id_transition_direct:
420         case op_put_by_id_transition_normal:
421         case op_put_by_id_transition_direct_out_of_line:
422         case op_put_by_id_transition_normal_out_of_line:
423         DEFINE_SLOWCASE_OP(op_put_by_id)
424         case op_put_by_val_direct:
425         DEFINE_SLOWCASE_OP(op_put_by_val)
426         DEFINE_SLOWCASE_OP(op_rshift)
427         DEFINE_SLOWCASE_OP(op_unsigned)
428         DEFINE_SLOWCASE_OP(op_urshift)
429         DEFINE_SLOWCASE_OP(op_stricteq)
430         DEFINE_SLOWCASE_OP(op_sub)
431         DEFINE_SLOWCASE_OP(op_to_number)
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 = (unsigned)-1;
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::CanInline:
475         m_canBeOptimized = false;
476         m_canBeOptimizedOrInlined = true;
477         m_shouldEmitProfiling = true;
478         break;
479     case DFG::CanCompile:
480     case DFG::CanCompileAndInline:
481         m_canBeOptimized = true;
482         m_canBeOptimizedOrInlined = true;
483         m_shouldEmitProfiling = true;
484         break;
485     default:
486         RELEASE_ASSERT_NOT_REACHED();
487         break;
488     }
489     
490     switch (m_codeBlock->codeType()) {
491     case GlobalCode:
492     case EvalCode:
493         m_codeBlock->m_shouldAlwaysBeInlined = false;
494         break;
495     case FunctionCode:
496         // We could have already set it to false because we detected an uninlineable call.
497         // Don't override that observation.
498         m_codeBlock->m_shouldAlwaysBeInlined &= canInline(level) && DFG::mightInlineFunction(m_codeBlock);
499         break;
500     }
501     
502     if (Options::showDisassembly() || m_vm->m_perBytecodeProfiler)
503         m_disassembler = adoptPtr(new JITDisassembler(m_codeBlock));
504     if (m_vm->m_perBytecodeProfiler) {
505         m_compilation = adoptRef(
506             new Profiler::Compilation(
507                 m_vm->m_perBytecodeProfiler->ensureBytecodesFor(m_codeBlock),
508                 Profiler::Baseline));
509         m_compilation->addProfiledBytecodes(*m_vm->m_perBytecodeProfiler, m_codeBlock);
510     }
511     
512     if (m_disassembler)
513         m_disassembler->setStartOfCode(label());
514
515     // Just add a little bit of randomness to the codegen
516     if (m_randomGenerator.getUint32() & 1)
517         nop();
518
519     emitFunctionPrologue();
520     emitPutImmediateToCallFrameHeader(m_codeBlock, JSStack::CodeBlock);
521
522     Label beginLabel(this);
523
524     sampleCodeBlock(m_codeBlock);
525 #if ENABLE(OPCODE_SAMPLING)
526     sampleInstruction(m_codeBlock->instructions().begin());
527 #endif
528
529     Jump stackOverflow;
530     if (m_codeBlock->codeType() == FunctionCode) {
531         ASSERT(m_bytecodeOffset == (unsigned)-1);
532         if (shouldEmitProfiling()) {
533             for (int argument = 0; argument < m_codeBlock->numParameters(); ++argument) {
534                 // If this is a constructor, then we want to put in a dummy profiling site (to
535                 // keep things consistent) but we don't actually want to record the dummy value.
536                 if (m_codeBlock->m_isConstructor && !argument)
537                     continue;
538                 int offset = CallFrame::argumentOffsetIncludingThis(argument) * static_cast<int>(sizeof(Register));
539 #if USE(JSVALUE64)
540                 load64(Address(callFrameRegister, offset), regT0);
541 #elif USE(JSVALUE32_64)
542                 load32(Address(callFrameRegister, offset + OBJECT_OFFSETOF(JSValue, u.asBits.payload)), regT0);
543                 load32(Address(callFrameRegister, offset + OBJECT_OFFSETOF(JSValue, u.asBits.tag)), regT1);
544 #endif
545                 emitValueProfilingSite(m_codeBlock->valueProfileForArgument(argument));
546             }
547         }
548
549         addPtr(TrustedImm32(stackPointerOffsetFor(m_codeBlock) * sizeof(Register)), callFrameRegister, regT1);
550         stackOverflow = branchPtr(Above, AbsoluteAddress(m_vm->addressOfStackLimit()), regT1);
551     }
552
553     addPtr(TrustedImm32(stackPointerOffsetFor(m_codeBlock) * sizeof(Register)), callFrameRegister, stackPointerRegister);
554     checkStackPointerAlignment();
555
556     privateCompileMainPass();
557     privateCompileLinkPass();
558     privateCompileSlowCases();
559     
560     if (m_disassembler)
561         m_disassembler->setEndOfSlowPath(label());
562
563     Label arityCheck;
564     if (m_codeBlock->codeType() == FunctionCode) {
565         stackOverflow.link(this);
566         m_bytecodeOffset = 0;
567         if (maxFrameExtentForSlowPathCall)
568             addPtr(TrustedImm32(-maxFrameExtentForSlowPathCall), stackPointerRegister);
569         callOperationWithCallFrameRollbackOnException(operationThrowStackOverflowError, m_codeBlock);
570
571         arityCheck = label();
572         store8(TrustedImm32(0), &m_codeBlock->m_shouldAlwaysBeInlined);
573         emitFunctionPrologue();
574         emitPutImmediateToCallFrameHeader(m_codeBlock, JSStack::CodeBlock);
575
576         load32(payloadFor(JSStack::ArgumentCount), regT1);
577         branch32(AboveOrEqual, regT1, TrustedImm32(m_codeBlock->m_numParameters)).linkTo(beginLabel, this);
578
579         m_bytecodeOffset = 0;
580
581         if (maxFrameExtentForSlowPathCall)
582             addPtr(TrustedImm32(-maxFrameExtentForSlowPathCall), stackPointerRegister);
583         callOperationWithCallFrameRollbackOnException(m_codeBlock->m_isConstructor ? operationConstructArityCheck : operationCallArityCheck);
584         if (maxFrameExtentForSlowPathCall)
585             addPtr(TrustedImm32(maxFrameExtentForSlowPathCall), stackPointerRegister);
586         if (returnValueGPR != regT0)
587             move(returnValueGPR, regT0);
588         branchTest32(Zero, regT0).linkTo(beginLabel, this);
589         GPRReg thunkReg;
590 #if USE(JSVALUE64)
591         thunkReg = GPRInfo::regT7;
592 #else
593         thunkReg = GPRInfo::regT5;
594 #endif
595         move(TrustedImmPtr(m_vm->arityCheckFailReturnThunks->returnPCsFor(*m_vm, m_codeBlock->numParameters())), thunkReg);
596         loadPtr(BaseIndex(thunkReg, regT0, timesPtr()), thunkReg);
597         emitNakedCall(m_vm->getCTIStub(arityFixupGenerator).code());
598
599 #if !ASSERT_DISABLED
600         m_bytecodeOffset = (unsigned)-1; // 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     m_codeBlock->setNumberOfByValInfos(m_byValCompilationInfo.size());
661     for (unsigned i = 0; i < m_byValCompilationInfo.size(); ++i) {
662         CodeLocationJump badTypeJump = CodeLocationJump(patchBuffer.locationOf(m_byValCompilationInfo[i].badTypeJump));
663         CodeLocationLabel doneTarget = patchBuffer.locationOf(m_byValCompilationInfo[i].doneTarget);
664         CodeLocationLabel slowPathTarget = patchBuffer.locationOf(m_byValCompilationInfo[i].slowPathTarget);
665         CodeLocationCall returnAddress = patchBuffer.locationOf(m_byValCompilationInfo[i].returnAddress);
666         
667         m_codeBlock->byValInfo(i) = ByValInfo(
668             m_byValCompilationInfo[i].bytecodeIndex,
669             badTypeJump,
670             m_byValCompilationInfo[i].arrayMode,
671             differenceBetweenCodePtr(badTypeJump, doneTarget),
672             differenceBetweenCodePtr(returnAddress, slowPathTarget));
673     }
674     for (unsigned i = 0; i < m_callCompilationInfo.size(); ++i) {
675         CallCompilationInfo& compilationInfo = m_callCompilationInfo[i];
676         CallLinkInfo& info = *compilationInfo.callLinkInfo;
677         info.callReturnLocation = patchBuffer.locationOfNearCall(compilationInfo.callReturnLocation);
678         info.hotPathBegin = patchBuffer.locationOf(compilationInfo.hotPathBegin);
679         info.hotPathOther = patchBuffer.locationOfNearCall(compilationInfo.hotPathOther);
680     }
681
682     CompactJITCodeMap::Encoder jitCodeMapEncoder;
683     for (unsigned bytecodeOffset = 0; bytecodeOffset < m_labels.size(); ++bytecodeOffset) {
684         if (m_labels[bytecodeOffset].isSet())
685             jitCodeMapEncoder.append(bytecodeOffset, patchBuffer.offsetOf(m_labels[bytecodeOffset]));
686     }
687     m_codeBlock->setJITCodeMap(jitCodeMapEncoder.finish());
688
689     MacroAssemblerCodePtr withArityCheck;
690     if (m_codeBlock->codeType() == FunctionCode)
691         withArityCheck = patchBuffer.locationOf(arityCheck);
692
693     if (Options::showDisassembly())
694         m_disassembler->dump(patchBuffer);
695     if (m_compilation) {
696         m_disassembler->reportToProfiler(m_compilation.get(), patchBuffer);
697         m_vm->m_perBytecodeProfiler->addCompilation(m_compilation);
698     }
699     
700     CodeRef result = patchBuffer.finalizeCodeWithoutDisassembly();
701     
702     m_vm->machineCodeBytesPerBytecodeWordForBaselineJIT.add(
703         static_cast<double>(result.size()) /
704         static_cast<double>(m_codeBlock->instructions().size()));
705     
706     m_codeBlock->shrinkToFit(CodeBlock::LateShrink);
707     m_codeBlock->setJITCode(
708         adoptRef(new DirectJITCode(result, withArityCheck, JITCode::BaselineJIT)));
709     
710 #if ENABLE(JIT_VERBOSE)
711     dataLogF("JIT generated code for %p at [%p, %p).\n", m_codeBlock, result.executableMemory()->start(), result.executableMemory()->end());
712 #endif
713     
714     return CompilationSuccessful;
715 }
716
717 void JIT::privateCompileExceptionHandlers()
718 {
719     if (m_exceptionChecks.empty() && m_exceptionChecksWithCallFrameRollback.empty())
720         return;
721
722     Jump doLookup;
723
724     if (!m_exceptionChecksWithCallFrameRollback.empty()) {
725         m_exceptionChecksWithCallFrameRollback.link(this);
726         emitGetCallerFrameFromCallFrameHeaderPtr(GPRInfo::argumentGPR1);
727         doLookup = jump();
728     }
729
730     if (!m_exceptionChecks.empty())
731         m_exceptionChecks.link(this);
732     
733     // lookupExceptionHandler is passed two arguments, the VM and the exec (the CallFrame*).
734     move(GPRInfo::callFrameRegister, GPRInfo::argumentGPR1);
735
736     if (doLookup.isSet())
737         doLookup.link(this);
738
739     move(TrustedImmPtr(vm()), GPRInfo::argumentGPR0);
740
741 #if CPU(X86)
742     // FIXME: should use the call abstraction, but this is currently in the SpeculativeJIT layer!
743     poke(GPRInfo::argumentGPR0);
744     poke(GPRInfo::argumentGPR1, 1);
745 #endif
746     m_calls.append(CallRecord(call(), (unsigned)-1, FunctionPtr(lookupExceptionHandler).value()));
747     jumpToExceptionHandler();
748 }
749
750 unsigned JIT::frameRegisterCountFor(CodeBlock* codeBlock)
751 {
752     ASSERT(static_cast<unsigned>(codeBlock->m_numCalleeRegisters) == WTF::roundUpToMultipleOf(stackAlignmentRegisters(), static_cast<unsigned>(codeBlock->m_numCalleeRegisters)));
753
754     return roundLocalRegisterCountForFramePointerOffset(codeBlock->m_numCalleeRegisters + maxFrameExtentForSlowPathCallInRegisters);
755 }
756
757 int JIT::stackPointerOffsetFor(CodeBlock* codeBlock)
758 {
759     return virtualRegisterForLocal(frameRegisterCountFor(codeBlock) - 1).offset();
760 }
761
762 } // namespace JSC
763
764 #endif // ENABLE(JIT)