Move DFG inline caching logic into jit/
[WebKit-https.git] / Source / JavaScriptCore / jit / JIT.cpp
1 /*
2  * Copyright (C) 2008, 2009, 2012, 2013 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 #include "JIT.h"
30
31 // This probably does not belong here; adding here for now as a quick Windows build fix.
32 #if ENABLE(ASSEMBLER) && CPU(X86) && !OS(MAC_OS_X)
33 #include "MacroAssembler.h"
34 JSC::MacroAssemblerX86Common::SSE2CheckState JSC::MacroAssemblerX86Common::s_sse2CheckState = NotCheckedSSE2;
35 #endif
36
37 #include "CodeBlock.h"
38 #include "DFGCapabilities.h"
39 #include "Interpreter.h"
40 #include "JITInlines.h"
41 #include "JITStubCall.h"
42 #include "JSArray.h"
43 #include "JSFunction.h"
44 #include "LinkBuffer.h"
45 #include "Operations.h"
46 #include "RepatchBuffer.h"
47 #include "ResultType.h"
48 #include "SamplingTool.h"
49 #include "SlowPathCall.h"
50 #include <wtf/CryptographicallyRandomNumber.h>
51
52 using namespace std;
53
54 namespace JSC {
55
56 void ctiPatchNearCallByReturnAddress(CodeBlock* codeblock, ReturnAddressPtr returnAddress, MacroAssemblerCodePtr newCalleeFunction)
57 {
58     RepatchBuffer repatchBuffer(codeblock);
59     repatchBuffer.relinkNearCallerToTrampoline(returnAddress, newCalleeFunction);
60 }
61
62 void ctiPatchCallByReturnAddress(CodeBlock* codeblock, ReturnAddressPtr returnAddress, MacroAssemblerCodePtr newCalleeFunction)
63 {
64     RepatchBuffer repatchBuffer(codeblock);
65     repatchBuffer.relinkCallerToTrampoline(returnAddress, newCalleeFunction);
66 }
67
68 void ctiPatchCallByReturnAddress(CodeBlock* codeblock, ReturnAddressPtr returnAddress, FunctionPtr newCalleeFunction)
69 {
70     RepatchBuffer repatchBuffer(codeblock);
71     repatchBuffer.relinkCallerToFunction(returnAddress, newCalleeFunction);
72 }
73
74 JIT::JIT(VM* vm, CodeBlock* codeBlock)
75     : JSInterfaceJIT(vm, codeBlock)
76     , m_interpreter(vm->interpreter)
77     , m_labels(codeBlock ? codeBlock->numberOfInstructions() : 0)
78     , m_bytecodeOffset((unsigned)-1)
79     , m_propertyAccessInstructionIndex(UINT_MAX)
80     , m_byValInstructionIndex(UINT_MAX)
81     , m_callLinkInfoIndex(UINT_MAX)
82 #if USE(JSVALUE32_64)
83     , m_jumpTargetIndex(0)
84     , m_mappedBytecodeOffset((unsigned)-1)
85     , m_mappedVirtualRegisterIndex(JSStack::ReturnPC)
86     , m_mappedTag((RegisterID)-1)
87     , m_mappedPayload((RegisterID)-1)
88 #else
89     , m_lastResultBytecodeRegister(std::numeric_limits<int>::max())
90     , m_jumpTargetsPosition(0)
91 #endif
92     , m_randomGenerator(cryptographicallyRandomNumber())
93 #if ENABLE(VALUE_PROFILER)
94     , m_canBeOptimized(false)
95     , m_shouldEmitProfiling(false)
96 #endif
97 {
98 }
99
100 #if ENABLE(DFG_JIT)
101 void JIT::emitEnterOptimizationCheck()
102 {
103     if (!canBeOptimized())
104         return;
105
106     Jump skipOptimize = branchAdd32(Signed, TrustedImm32(Options::executionCounterIncrementForEntry()), AbsoluteAddress(m_codeBlock->addressOfJITExecuteCounter()));
107     JITStubCall stubCall(this, cti_optimize);
108     stubCall.addArgument(TrustedImm32(m_bytecodeOffset));
109     ASSERT(!m_bytecodeOffset);
110     stubCall.call();
111     skipOptimize.link(this);
112 }
113 #endif
114
115 #define NEXT_OPCODE(name) \
116     m_bytecodeOffset += OPCODE_LENGTH(name); \
117     break;
118
119 #if USE(JSVALUE32_64)
120 #define DEFINE_BINARY_OP(name) \
121     case op_##name: { \
122         JITSlowPathCall slowPathCall(this, currentInstruction, slow_path_##name); \
123         slowPathCall.call(); \
124         NEXT_OPCODE(op_##name); \
125     }
126
127 #define DEFINE_UNARY_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 #else // USE(JSVALUE32_64)
135
136 #define DEFINE_BINARY_OP(name) \
137     case op_##name: { \
138         JITSlowPathCall slowPathCall(this, currentInstruction, slow_path_##name); \
139         slowPathCall.call(); \
140         NEXT_OPCODE(op_##name); \
141     }
142
143 #define DEFINE_UNARY_OP(name) \
144     case op_##name: { \
145         JITSlowPathCall slowPathCall(this, currentInstruction, slow_path_##name); \
146         slowPathCall.call(); \
147         NEXT_OPCODE(op_##name); \
148     }
149 #endif // USE(JSVALUE32_64)
150
151 #define DEFINE_OP(name) \
152     case name: { \
153         emit_##name(currentInstruction); \
154         NEXT_OPCODE(name); \
155     }
156
157 #define DEFINE_SLOWCASE_OP(name) \
158     case name: { \
159         emitSlow_##name(currentInstruction, iter); \
160         NEXT_OPCODE(name); \
161     }
162
163 void JIT::privateCompileMainPass()
164 {
165     Instruction* instructionsBegin = m_codeBlock->instructions().begin();
166     unsigned instructionCount = m_codeBlock->instructions().size();
167
168     m_callLinkInfoIndex = 0;
169
170     for (m_bytecodeOffset = 0; m_bytecodeOffset < instructionCount; ) {
171         if (m_disassembler)
172             m_disassembler->setForBytecodeMainPath(m_bytecodeOffset, label());
173         Instruction* currentInstruction = instructionsBegin + m_bytecodeOffset;
174         ASSERT_WITH_MESSAGE(m_interpreter->isOpcode(currentInstruction->u.opcode), "privateCompileMainPass gone bad @ %d", m_bytecodeOffset);
175
176 #if ENABLE(OPCODE_SAMPLING)
177         if (m_bytecodeOffset > 0) // Avoid the overhead of sampling op_enter twice.
178             sampleInstruction(currentInstruction);
179 #endif
180
181 #if USE(JSVALUE64)
182         if (atJumpTarget())
183             killLastResultRegister();
184 #endif
185
186         m_labels[m_bytecodeOffset] = label();
187
188 #if ENABLE(JIT_VERBOSE)
189         dataLogF("Old JIT emitting code for bc#%u at offset 0x%lx.\n", m_bytecodeOffset, (long)debugOffset());
190 #endif
191         
192         OpcodeID opcodeID = m_interpreter->getOpcodeID(currentInstruction->u.opcode);
193
194         if (m_compilation) {
195             add64(
196                 TrustedImm32(1),
197                 AbsoluteAddress(m_compilation->executionCounterFor(Profiler::OriginStack(Profiler::Origin(
198                     m_compilation->bytecodes(), m_bytecodeOffset)))->address()));
199         }
200
201         switch (opcodeID) {
202         DEFINE_BINARY_OP(del_by_val)
203         DEFINE_BINARY_OP(in)
204         DEFINE_BINARY_OP(less)
205         DEFINE_BINARY_OP(lesseq)
206         DEFINE_BINARY_OP(greater)
207         DEFINE_BINARY_OP(greatereq)
208         DEFINE_UNARY_OP(is_function)
209         DEFINE_UNARY_OP(is_object)
210         DEFINE_UNARY_OP(typeof)
211
212         DEFINE_OP(op_add)
213         DEFINE_OP(op_bitand)
214         DEFINE_OP(op_bitor)
215         DEFINE_OP(op_bitxor)
216         DEFINE_OP(op_call)
217         DEFINE_OP(op_call_eval)
218         DEFINE_OP(op_call_varargs)
219         DEFINE_OP(op_catch)
220         DEFINE_OP(op_construct)
221         DEFINE_OP(op_get_callee)
222         DEFINE_OP(op_create_this)
223         DEFINE_OP(op_to_this)
224         DEFINE_OP(op_init_lazy_reg)
225         DEFINE_OP(op_create_arguments)
226         DEFINE_OP(op_debug)
227         DEFINE_OP(op_del_by_id)
228         DEFINE_OP(op_div)
229         DEFINE_OP(op_end)
230         DEFINE_OP(op_enter)
231         DEFINE_OP(op_create_activation)
232         DEFINE_OP(op_eq)
233         DEFINE_OP(op_eq_null)
234         case op_get_by_id_out_of_line:
235         case op_get_array_length:
236         DEFINE_OP(op_get_by_id)
237         DEFINE_OP(op_get_arguments_length)
238         DEFINE_OP(op_get_by_val)
239         DEFINE_OP(op_get_argument_by_val)
240         DEFINE_OP(op_get_by_pname)
241         DEFINE_OP(op_get_pnames)
242         DEFINE_OP(op_check_has_instance)
243         DEFINE_OP(op_instanceof)
244         DEFINE_OP(op_is_undefined)
245         DEFINE_OP(op_is_boolean)
246         DEFINE_OP(op_is_number)
247         DEFINE_OP(op_is_string)
248         DEFINE_OP(op_jeq_null)
249         DEFINE_OP(op_jfalse)
250         DEFINE_OP(op_jmp)
251         DEFINE_OP(op_jneq_null)
252         DEFINE_OP(op_jneq_ptr)
253         DEFINE_OP(op_jless)
254         DEFINE_OP(op_jlesseq)
255         DEFINE_OP(op_jgreater)
256         DEFINE_OP(op_jgreatereq)
257         DEFINE_OP(op_jnless)
258         DEFINE_OP(op_jnlesseq)
259         DEFINE_OP(op_jngreater)
260         DEFINE_OP(op_jngreatereq)
261         DEFINE_OP(op_jtrue)
262         DEFINE_OP(op_loop_hint)
263         DEFINE_OP(op_lshift)
264         DEFINE_OP(op_mod)
265         DEFINE_OP(op_mov)
266         DEFINE_OP(op_mul)
267         DEFINE_OP(op_negate)
268         DEFINE_OP(op_neq)
269         DEFINE_OP(op_neq_null)
270         DEFINE_OP(op_new_array)
271         DEFINE_OP(op_new_array_with_size)
272         DEFINE_OP(op_new_array_buffer)
273         DEFINE_OP(op_new_func)
274         DEFINE_OP(op_new_func_exp)
275         DEFINE_OP(op_new_object)
276         DEFINE_OP(op_new_regexp)
277         DEFINE_OP(op_next_pname)
278         DEFINE_OP(op_not)
279         DEFINE_OP(op_nstricteq)
280         DEFINE_OP(op_pop_scope)
281         DEFINE_OP(op_dec)
282         DEFINE_OP(op_inc)
283         DEFINE_OP(op_profile_did_call)
284         DEFINE_OP(op_profile_will_call)
285         DEFINE_OP(op_push_name_scope)
286         DEFINE_OP(op_push_with_scope)
287         case op_put_by_id_out_of_line:
288         case op_put_by_id_transition_direct:
289         case op_put_by_id_transition_normal:
290         case op_put_by_id_transition_direct_out_of_line:
291         case op_put_by_id_transition_normal_out_of_line:
292         DEFINE_OP(op_put_by_id)
293         DEFINE_OP(op_put_by_index)
294         DEFINE_OP(op_put_by_val)
295         DEFINE_OP(op_put_getter_setter)
296         case op_init_global_const_nop:
297             NEXT_OPCODE(op_init_global_const_nop);
298         DEFINE_OP(op_init_global_const)
299
300         DEFINE_OP(op_ret)
301         DEFINE_OP(op_ret_object_or_this)
302         DEFINE_OP(op_rshift)
303         DEFINE_OP(op_urshift)
304         DEFINE_OP(op_strcat)
305         DEFINE_OP(op_stricteq)
306         DEFINE_OP(op_sub)
307         DEFINE_OP(op_switch_char)
308         DEFINE_OP(op_switch_imm)
309         DEFINE_OP(op_switch_string)
310         DEFINE_OP(op_tear_off_activation)
311         DEFINE_OP(op_tear_off_arguments)
312         DEFINE_OP(op_throw)
313         DEFINE_OP(op_throw_static_error)
314         DEFINE_OP(op_to_number)
315         DEFINE_OP(op_to_primitive)
316
317         DEFINE_OP(op_resolve_scope)
318         DEFINE_OP(op_get_from_scope)
319         DEFINE_OP(op_put_to_scope)
320
321         case op_get_by_id_chain:
322         case op_get_by_id_generic:
323         case op_get_by_id_proto:
324         case op_get_by_id_self:
325         case op_get_by_id_getter_chain:
326         case op_get_by_id_getter_proto:
327         case op_get_by_id_getter_self:
328         case op_get_by_id_custom_chain:
329         case op_get_by_id_custom_proto:
330         case op_get_by_id_custom_self:
331         case op_get_string_length:
332         case op_put_by_id_generic:
333         case op_put_by_id_replace:
334         case op_put_by_id_transition:
335             RELEASE_ASSERT_NOT_REACHED();
336         }
337     }
338
339     RELEASE_ASSERT(m_callLinkInfoIndex == m_callStructureStubCompilationInfo.size());
340
341 #ifndef NDEBUG
342     // Reset this, in order to guard its use with ASSERTs.
343     m_bytecodeOffset = (unsigned)-1;
344 #endif
345 }
346
347 void JIT::privateCompileLinkPass()
348 {
349     unsigned jmpTableCount = m_jmpTable.size();
350     for (unsigned i = 0; i < jmpTableCount; ++i)
351         m_jmpTable[i].from.linkTo(m_labels[m_jmpTable[i].toBytecodeOffset], this);
352     m_jmpTable.clear();
353 }
354
355 void JIT::privateCompileSlowCases()
356 {
357     Instruction* instructionsBegin = m_codeBlock->instructions().begin();
358
359     m_propertyAccessInstructionIndex = 0;
360     m_byValInstructionIndex = 0;
361     m_callLinkInfoIndex = 0;
362     
363 #if ENABLE(VALUE_PROFILER)
364     // Use this to assert that slow-path code associates new profiling sites with existing
365     // ValueProfiles rather than creating new ones. This ensures that for a given instruction
366     // (say, get_by_id) we get combined statistics for both the fast-path executions of that
367     // instructions and the slow-path executions. Furthermore, if the slow-path code created
368     // new ValueProfiles then the ValueProfiles would no longer be sorted by bytecode offset,
369     // which would break the invariant necessary to use CodeBlock::valueProfileForBytecodeOffset().
370     unsigned numberOfValueProfiles = m_codeBlock->numberOfValueProfiles();
371 #endif
372
373     for (Vector<SlowCaseEntry>::iterator iter = m_slowCases.begin(); iter != m_slowCases.end();) {
374 #if USE(JSVALUE64)
375         killLastResultRegister();
376 #endif
377
378         m_bytecodeOffset = iter->to;
379
380         unsigned firstTo = m_bytecodeOffset;
381
382         Instruction* currentInstruction = instructionsBegin + m_bytecodeOffset;
383         
384 #if ENABLE(VALUE_PROFILER)
385         RareCaseProfile* rareCaseProfile = 0;
386         if (shouldEmitProfiling())
387             rareCaseProfile = m_codeBlock->addRareCaseProfile(m_bytecodeOffset);
388 #endif
389
390 #if ENABLE(JIT_VERBOSE)
391         dataLogF("Old JIT emitting slow code for bc#%u at offset 0x%lx.\n", m_bytecodeOffset, (long)debugOffset());
392 #endif
393         
394         if (m_disassembler)
395             m_disassembler->setForBytecodeSlowPath(m_bytecodeOffset, label());
396
397         switch (m_interpreter->getOpcodeID(currentInstruction->u.opcode)) {
398         DEFINE_SLOWCASE_OP(op_add)
399         DEFINE_SLOWCASE_OP(op_bitand)
400         DEFINE_SLOWCASE_OP(op_bitor)
401         DEFINE_SLOWCASE_OP(op_bitxor)
402         DEFINE_SLOWCASE_OP(op_call)
403         DEFINE_SLOWCASE_OP(op_call_eval)
404         DEFINE_SLOWCASE_OP(op_call_varargs)
405         DEFINE_SLOWCASE_OP(op_construct)
406         DEFINE_SLOWCASE_OP(op_to_this)
407         DEFINE_SLOWCASE_OP(op_create_this)
408         DEFINE_SLOWCASE_OP(op_div)
409         DEFINE_SLOWCASE_OP(op_eq)
410         case op_get_by_id_out_of_line:
411         case op_get_array_length:
412         DEFINE_SLOWCASE_OP(op_get_by_id)
413         DEFINE_SLOWCASE_OP(op_get_arguments_length)
414         DEFINE_SLOWCASE_OP(op_get_by_val)
415         DEFINE_SLOWCASE_OP(op_get_argument_by_val)
416         DEFINE_SLOWCASE_OP(op_get_by_pname)
417         DEFINE_SLOWCASE_OP(op_check_has_instance)
418         DEFINE_SLOWCASE_OP(op_instanceof)
419         DEFINE_SLOWCASE_OP(op_jfalse)
420         DEFINE_SLOWCASE_OP(op_jless)
421         DEFINE_SLOWCASE_OP(op_jlesseq)
422         DEFINE_SLOWCASE_OP(op_jgreater)
423         DEFINE_SLOWCASE_OP(op_jgreatereq)
424         DEFINE_SLOWCASE_OP(op_jnless)
425         DEFINE_SLOWCASE_OP(op_jnlesseq)
426         DEFINE_SLOWCASE_OP(op_jngreater)
427         DEFINE_SLOWCASE_OP(op_jngreatereq)
428         DEFINE_SLOWCASE_OP(op_jtrue)
429         DEFINE_SLOWCASE_OP(op_loop_hint)
430         DEFINE_SLOWCASE_OP(op_lshift)
431         DEFINE_SLOWCASE_OP(op_mod)
432         DEFINE_SLOWCASE_OP(op_mul)
433         DEFINE_SLOWCASE_OP(op_negate)
434         DEFINE_SLOWCASE_OP(op_neq)
435         DEFINE_SLOWCASE_OP(op_new_object)
436         DEFINE_SLOWCASE_OP(op_not)
437         DEFINE_SLOWCASE_OP(op_nstricteq)
438         DEFINE_SLOWCASE_OP(op_dec)
439         DEFINE_SLOWCASE_OP(op_inc)
440         case op_put_by_id_out_of_line:
441         case op_put_by_id_transition_direct:
442         case op_put_by_id_transition_normal:
443         case op_put_by_id_transition_direct_out_of_line:
444         case op_put_by_id_transition_normal_out_of_line:
445         DEFINE_SLOWCASE_OP(op_put_by_id)
446         DEFINE_SLOWCASE_OP(op_put_by_val)
447         DEFINE_SLOWCASE_OP(op_rshift)
448         DEFINE_SLOWCASE_OP(op_urshift)
449         DEFINE_SLOWCASE_OP(op_stricteq)
450         DEFINE_SLOWCASE_OP(op_sub)
451         DEFINE_SLOWCASE_OP(op_to_number)
452         DEFINE_SLOWCASE_OP(op_to_primitive)
453
454         DEFINE_SLOWCASE_OP(op_resolve_scope)
455         DEFINE_SLOWCASE_OP(op_get_from_scope)
456         DEFINE_SLOWCASE_OP(op_put_to_scope)
457
458         default:
459             RELEASE_ASSERT_NOT_REACHED();
460         }
461
462         RELEASE_ASSERT_WITH_MESSAGE(iter == m_slowCases.end() || firstTo != iter->to, "Not enough jumps linked in slow case codegen.");
463         RELEASE_ASSERT_WITH_MESSAGE(firstTo == (iter - 1)->to, "Too many jumps linked in slow case codegen.");
464         
465 #if ENABLE(VALUE_PROFILER)
466         if (shouldEmitProfiling())
467             add32(TrustedImm32(1), AbsoluteAddress(&rareCaseProfile->m_counter));
468 #endif
469
470         emitJumpSlowToHot(jump(), 0);
471     }
472
473     RELEASE_ASSERT(m_propertyAccessInstructionIndex == m_propertyAccessCompilationInfo.size());
474     RELEASE_ASSERT(m_callLinkInfoIndex == m_callStructureStubCompilationInfo.size());
475 #if ENABLE(VALUE_PROFILER)
476     RELEASE_ASSERT(numberOfValueProfiles == m_codeBlock->numberOfValueProfiles());
477 #endif
478
479 #ifndef NDEBUG
480     // Reset this, in order to guard its use with ASSERTs.
481     m_bytecodeOffset = (unsigned)-1;
482 #endif
483 }
484
485 ALWAYS_INLINE void PropertyStubCompilationInfo::copyToStubInfo(StructureStubInfo& info, LinkBuffer &linkBuffer)
486 {
487     ASSERT(bytecodeIndex != std::numeric_limits<unsigned>::max());
488     info.codeOrigin = CodeOrigin(bytecodeIndex);
489     info.callReturnLocation = linkBuffer.locationOf(callReturnLocation);
490     info.hotPathBegin = linkBuffer.locationOf(hotPathBegin);
491
492     switch (m_type) {
493     case GetById: {
494         CodeLocationLabel hotPathBeginLocation = linkBuffer.locationOf(hotPathBegin);
495         info.patch.baseline.u.get.structureToCompare = MacroAssembler::differenceBetweenCodePtr(hotPathBeginLocation, linkBuffer.locationOf(getStructureToCompare));
496         info.patch.baseline.u.get.structureCheck = MacroAssembler::differenceBetweenCodePtr(hotPathBeginLocation, linkBuffer.locationOf(getStructureCheck));
497         info.patch.baseline.u.get.propertyStorageLoad = MacroAssembler::differenceBetweenCodePtr(hotPathBeginLocation, linkBuffer.locationOf(propertyStorageLoad));
498 #if USE(JSVALUE64)
499         info.patch.baseline.u.get.displacementLabel = MacroAssembler::differenceBetweenCodePtr(hotPathBeginLocation, linkBuffer.locationOf(getDisplacementLabel));
500 #else
501         info.patch.baseline.u.get.displacementLabel1 = MacroAssembler::differenceBetweenCodePtr(hotPathBeginLocation, linkBuffer.locationOf(getDisplacementLabel1));
502         info.patch.baseline.u.get.displacementLabel2 = MacroAssembler::differenceBetweenCodePtr(hotPathBeginLocation, linkBuffer.locationOf(getDisplacementLabel2));
503 #endif
504         info.patch.baseline.u.get.putResult = MacroAssembler::differenceBetweenCodePtr(hotPathBeginLocation, linkBuffer.locationOf(getPutResult));
505         info.patch.baseline.u.get.coldPathBegin = MacroAssembler::differenceBetweenCodePtr(linkBuffer.locationOf(getColdPathBegin), linkBuffer.locationOf(callReturnLocation));
506         break;
507     }
508     case PutById:
509         CodeLocationLabel hotPathBeginLocation = linkBuffer.locationOf(hotPathBegin);
510         info.patch.baseline.u.put.structureToCompare = MacroAssembler::differenceBetweenCodePtr(hotPathBeginLocation, linkBuffer.locationOf(putStructureToCompare));
511         info.patch.baseline.u.put.propertyStorageLoad = MacroAssembler::differenceBetweenCodePtr(hotPathBeginLocation, linkBuffer.locationOf(propertyStorageLoad));
512 #if USE(JSVALUE64)
513         info.patch.baseline.u.put.displacementLabel = MacroAssembler::differenceBetweenCodePtr(hotPathBeginLocation, linkBuffer.locationOf(putDisplacementLabel));
514 #else
515         info.patch.baseline.u.put.displacementLabel1 = MacroAssembler::differenceBetweenCodePtr(hotPathBeginLocation, linkBuffer.locationOf(putDisplacementLabel1));
516         info.patch.baseline.u.put.displacementLabel2 = MacroAssembler::differenceBetweenCodePtr(hotPathBeginLocation, linkBuffer.locationOf(putDisplacementLabel2));
517 #endif
518         break;
519     }
520 }
521
522 CompilationResult JIT::privateCompile(JITCompilationEffort effort)
523 {
524 #if ENABLE(VALUE_PROFILER)
525     DFG::CapabilityLevel level = m_codeBlock->capabilityLevel();
526     switch (level) {
527     case DFG::CannotCompile:
528         m_canBeOptimized = false;
529         m_canBeOptimizedOrInlined = false;
530         m_shouldEmitProfiling = false;
531         break;
532     case DFG::CanInline:
533         m_canBeOptimized = false;
534         m_canBeOptimizedOrInlined = true;
535         m_shouldEmitProfiling = true;
536         break;
537     case DFG::CanCompile:
538     case DFG::CanCompileAndInline:
539         m_canBeOptimized = true;
540         m_canBeOptimizedOrInlined = true;
541         m_shouldEmitProfiling = true;
542         break;
543     default:
544         RELEASE_ASSERT_NOT_REACHED();
545         break;
546     }
547     
548     switch (m_codeBlock->codeType()) {
549     case GlobalCode:
550     case EvalCode:
551         m_codeBlock->m_shouldAlwaysBeInlined = false;
552         break;
553     case FunctionCode:
554         // We could have already set it to false because we detected an uninlineable call.
555         // Don't override that observation.
556         m_codeBlock->m_shouldAlwaysBeInlined &= canInline(level) && DFG::mightInlineFunction(m_codeBlock);
557         break;
558     }
559 #endif
560     
561     if (Options::showDisassembly() || m_vm->m_perBytecodeProfiler)
562         m_disassembler = adoptPtr(new JITDisassembler(m_codeBlock));
563     if (m_vm->m_perBytecodeProfiler) {
564         m_compilation = adoptRef(
565             new Profiler::Compilation(
566                 m_vm->m_perBytecodeProfiler->ensureBytecodesFor(m_codeBlock),
567                 Profiler::Baseline));
568         m_compilation->addProfiledBytecodes(*m_vm->m_perBytecodeProfiler, m_codeBlock);
569     }
570     
571     if (m_disassembler)
572         m_disassembler->setStartOfCode(label());
573
574     // Just add a little bit of randomness to the codegen
575     if (m_randomGenerator.getUint32() & 1)
576         nop();
577
578     preserveReturnAddressAfterCall(regT2);
579     emitPutToCallFrameHeader(regT2, JSStack::ReturnPC);
580     emitPutImmediateToCallFrameHeader(m_codeBlock, JSStack::CodeBlock);
581
582     Label beginLabel(this);
583
584     sampleCodeBlock(m_codeBlock);
585 #if ENABLE(OPCODE_SAMPLING)
586     sampleInstruction(m_codeBlock->instructions().begin());
587 #endif
588
589     Jump stackCheck;
590     if (m_codeBlock->codeType() == FunctionCode) {
591 #if ENABLE(DFG_JIT)
592 #if DFG_ENABLE(SUCCESS_STATS)
593         static SamplingCounter counter("orignalJIT");
594         emitCount(counter);
595 #endif
596 #endif
597
598 #if ENABLE(VALUE_PROFILER)
599         ASSERT(m_bytecodeOffset == (unsigned)-1);
600         if (shouldEmitProfiling()) {
601             for (int argument = 0; argument < m_codeBlock->numParameters(); ++argument) {
602                 // If this is a constructor, then we want to put in a dummy profiling site (to
603                 // keep things consistent) but we don't actually want to record the dummy value.
604                 if (m_codeBlock->m_isConstructor && !argument)
605                     continue;
606                 int offset = CallFrame::argumentOffsetIncludingThis(argument) * static_cast<int>(sizeof(Register));
607 #if USE(JSVALUE64)
608                 load64(Address(callFrameRegister, offset), regT0);
609 #elif USE(JSVALUE32_64)
610                 load32(Address(callFrameRegister, offset + OBJECT_OFFSETOF(JSValue, u.asBits.payload)), regT0);
611                 load32(Address(callFrameRegister, offset + OBJECT_OFFSETOF(JSValue, u.asBits.tag)), regT1);
612 #endif
613                 emitValueProfilingSite(m_codeBlock->valueProfileForArgument(argument), regT4);
614             }
615         }
616 #endif
617
618         addPtr(TrustedImm32(-m_codeBlock->m_numCalleeRegisters * sizeof(Register)), callFrameRegister, regT1);
619         stackCheck = branchPtr(Above, AbsoluteAddress(m_vm->interpreter->stack().addressOfEnd()), regT1);
620     }
621
622     Label functionBody = label();
623     
624     privateCompileMainPass();
625     privateCompileLinkPass();
626     privateCompileSlowCases();
627     
628     if (m_disassembler)
629         m_disassembler->setEndOfSlowPath(label());
630
631     Label arityCheck;
632     if (m_codeBlock->codeType() == FunctionCode) {
633         stackCheck.link(this);
634         m_bytecodeOffset = 0;
635         JITStubCall(this, cti_stack_check).call();
636 #ifndef NDEBUG
637         m_bytecodeOffset = (unsigned)-1; // Reset this, in order to guard its use with ASSERTs.
638 #endif
639         jump(functionBody);
640
641         arityCheck = label();
642         store8(TrustedImm32(0), &m_codeBlock->m_shouldAlwaysBeInlined);
643         preserveReturnAddressAfterCall(regT2);
644         emitPutToCallFrameHeader(regT2, JSStack::ReturnPC);
645         emitPutImmediateToCallFrameHeader(m_codeBlock, JSStack::CodeBlock);
646
647         load32(payloadFor(JSStack::ArgumentCount), regT1);
648         branch32(AboveOrEqual, regT1, TrustedImm32(m_codeBlock->m_numParameters)).linkTo(beginLabel, this);
649
650         m_bytecodeOffset = 0;
651
652         JITStubCall(this, m_codeBlock->m_isConstructor ? cti_op_construct_arityCheck : cti_op_call_arityCheck).call(regT0);
653         branchTest32(Zero, regT0).linkTo(beginLabel, this);
654         emitNakedCall(m_vm->getCTIStub(arityFixup).code());
655
656 #if !ASSERT_DISABLED
657         m_bytecodeOffset = (unsigned)-1; // Reset this, in order to guard its use with ASSERTs.
658 #endif
659
660         jump(beginLabel);
661     }
662
663     ASSERT(m_jmpTable.isEmpty());
664     
665     if (m_disassembler)
666         m_disassembler->setEndOfCode(label());
667
668     LinkBuffer patchBuffer(*m_vm, this, m_codeBlock, effort);
669     if (patchBuffer.didFailToAllocate())
670         return CompilationFailed;
671
672     // Translate vPC offsets into addresses in JIT generated code, for switch tables.
673     for (unsigned i = 0; i < m_switches.size(); ++i) {
674         SwitchRecord record = m_switches[i];
675         unsigned bytecodeOffset = record.bytecodeOffset;
676
677         if (record.type != SwitchRecord::String) {
678             ASSERT(record.type == SwitchRecord::Immediate || record.type == SwitchRecord::Character); 
679             ASSERT(record.jumpTable.simpleJumpTable->branchOffsets.size() == record.jumpTable.simpleJumpTable->ctiOffsets.size());
680
681             record.jumpTable.simpleJumpTable->ctiDefault = patchBuffer.locationOf(m_labels[bytecodeOffset + record.defaultOffset]);
682
683             for (unsigned j = 0; j < record.jumpTable.simpleJumpTable->branchOffsets.size(); ++j) {
684                 unsigned offset = record.jumpTable.simpleJumpTable->branchOffsets[j];
685                 record.jumpTable.simpleJumpTable->ctiOffsets[j] = offset ? patchBuffer.locationOf(m_labels[bytecodeOffset + offset]) : record.jumpTable.simpleJumpTable->ctiDefault;
686             }
687         } else {
688             ASSERT(record.type == SwitchRecord::String);
689
690             record.jumpTable.stringJumpTable->ctiDefault = patchBuffer.locationOf(m_labels[bytecodeOffset + record.defaultOffset]);
691
692             StringJumpTable::StringOffsetTable::iterator end = record.jumpTable.stringJumpTable->offsetTable.end();            
693             for (StringJumpTable::StringOffsetTable::iterator it = record.jumpTable.stringJumpTable->offsetTable.begin(); it != end; ++it) {
694                 unsigned offset = it->value.branchOffset;
695                 it->value.ctiOffset = offset ? patchBuffer.locationOf(m_labels[bytecodeOffset + offset]) : record.jumpTable.stringJumpTable->ctiDefault;
696             }
697         }
698     }
699
700     for (size_t i = 0; i < m_codeBlock->numberOfExceptionHandlers(); ++i) {
701         HandlerInfo& handler = m_codeBlock->exceptionHandler(i);
702         handler.nativeCode = patchBuffer.locationOf(m_labels[handler.target]);
703     }
704
705     for (Vector<CallRecord>::iterator iter = m_calls.begin(); iter != m_calls.end(); ++iter) {
706         if (iter->to)
707             patchBuffer.link(iter->from, FunctionPtr(iter->to));
708     }
709
710     m_codeBlock->callReturnIndexVector().reserveCapacity(m_calls.size());
711     for (Vector<CallRecord>::iterator iter = m_calls.begin(); iter != m_calls.end(); ++iter)
712         m_codeBlock->callReturnIndexVector().append(CallReturnOffsetToBytecodeOffset(patchBuffer.returnAddressOffset(iter->from), iter->bytecodeOffset));
713
714     m_codeBlock->setNumberOfStructureStubInfos(m_propertyAccessCompilationInfo.size());
715     for (unsigned i = 0; i < m_propertyAccessCompilationInfo.size(); ++i)
716         m_propertyAccessCompilationInfo[i].copyToStubInfo(m_codeBlock->structureStubInfo(i), patchBuffer);
717     m_codeBlock->setNumberOfByValInfos(m_byValCompilationInfo.size());
718     for (unsigned i = 0; i < m_byValCompilationInfo.size(); ++i) {
719         CodeLocationJump badTypeJump = CodeLocationJump(patchBuffer.locationOf(m_byValCompilationInfo[i].badTypeJump));
720         CodeLocationLabel doneTarget = patchBuffer.locationOf(m_byValCompilationInfo[i].doneTarget);
721         CodeLocationLabel slowPathTarget = patchBuffer.locationOf(m_byValCompilationInfo[i].slowPathTarget);
722         CodeLocationCall returnAddress = patchBuffer.locationOf(m_byValCompilationInfo[i].returnAddress);
723         
724         m_codeBlock->byValInfo(i) = ByValInfo(
725             m_byValCompilationInfo[i].bytecodeIndex,
726             badTypeJump,
727             m_byValCompilationInfo[i].arrayMode,
728             differenceBetweenCodePtr(badTypeJump, doneTarget),
729             differenceBetweenCodePtr(returnAddress, slowPathTarget));
730     }
731     m_codeBlock->setNumberOfCallLinkInfos(m_callStructureStubCompilationInfo.size());
732     for (unsigned i = 0; i < m_codeBlock->numberOfCallLinkInfos(); ++i) {
733         CallLinkInfo& info = m_codeBlock->callLinkInfo(i);
734         info.callType = m_callStructureStubCompilationInfo[i].callType;
735         info.codeOrigin = CodeOrigin(m_callStructureStubCompilationInfo[i].bytecodeIndex);
736         info.callReturnLocation = patchBuffer.locationOfNearCall(m_callStructureStubCompilationInfo[i].callReturnLocation);
737         info.hotPathBegin = patchBuffer.locationOf(m_callStructureStubCompilationInfo[i].hotPathBegin);
738         info.hotPathOther = patchBuffer.locationOfNearCall(m_callStructureStubCompilationInfo[i].hotPathOther);
739         info.calleeGPR = regT0;
740     }
741
742 #if ENABLE(DFG_JIT) || ENABLE(LLINT)
743     if (canBeOptimizedOrInlined()
744 #if ENABLE(LLINT)
745         || true
746 #endif
747         ) {
748         CompactJITCodeMap::Encoder jitCodeMapEncoder;
749         for (unsigned bytecodeOffset = 0; bytecodeOffset < m_labels.size(); ++bytecodeOffset) {
750             if (m_labels[bytecodeOffset].isSet())
751                 jitCodeMapEncoder.append(bytecodeOffset, patchBuffer.offsetOf(m_labels[bytecodeOffset]));
752         }
753         m_codeBlock->setJITCodeMap(jitCodeMapEncoder.finish());
754     }
755 #endif
756
757     MacroAssemblerCodePtr withArityCheck;
758     if (m_codeBlock->codeType() == FunctionCode)
759         withArityCheck = patchBuffer.locationOf(arityCheck);
760
761     if (Options::showDisassembly())
762         m_disassembler->dump(patchBuffer);
763     if (m_compilation) {
764         m_disassembler->reportToProfiler(m_compilation.get(), patchBuffer);
765         m_vm->m_perBytecodeProfiler->addCompilation(m_compilation);
766     }
767     
768     CodeRef result = patchBuffer.finalizeCodeWithoutDisassembly();
769     
770     m_vm->machineCodeBytesPerBytecodeWordForBaselineJIT.add(
771         static_cast<double>(result.size()) /
772         static_cast<double>(m_codeBlock->instructions().size()));
773     
774     m_codeBlock->shrinkToFit(CodeBlock::LateShrink);
775     m_codeBlock->setJITCode(
776         adoptRef(new DirectJITCode(result, JITCode::BaselineJIT)),
777         withArityCheck);
778     
779 #if ENABLE(JIT_VERBOSE)
780     dataLogF("JIT generated code for %p at [%p, %p).\n", m_codeBlock, result.executableMemory()->start(), result.executableMemory()->end());
781 #endif
782     
783     return CompilationSuccessful;
784 }
785
786 void JIT::linkFor(ExecState* exec, JSFunction* callee, CodeBlock* callerCodeBlock, CodeBlock* calleeCodeBlock, JIT::CodePtr code, CallLinkInfo* callLinkInfo, VM* vm, CodeSpecializationKind kind)
787 {
788     RepatchBuffer repatchBuffer(callerCodeBlock);
789
790     ASSERT(!callLinkInfo->isLinked());
791     callLinkInfo->callee.set(*vm, callLinkInfo->hotPathBegin, callerCodeBlock->ownerExecutable(), callee);
792     callLinkInfo->lastSeenCallee.set(*vm, callerCodeBlock->ownerExecutable(), callee);
793     repatchBuffer.relink(callLinkInfo->hotPathOther, code);
794
795     if (calleeCodeBlock)
796         calleeCodeBlock->linkIncomingCall(exec, callLinkInfo);
797
798     // Patch the slow patch so we do not continue to try to link.
799     if (kind == CodeForCall) {
800         ASSERT(callLinkInfo->callType == CallLinkInfo::Call
801                || callLinkInfo->callType == CallLinkInfo::CallVarargs);
802         if (callLinkInfo->callType == CallLinkInfo::Call) {
803             repatchBuffer.relink(callLinkInfo->callReturnLocation, vm->getCTIStub(oldStyleLinkClosureCallGenerator).code());
804             return;
805         }
806
807         repatchBuffer.relink(callLinkInfo->callReturnLocation, vm->getCTIStub(oldStyleVirtualCallGenerator).code());
808         return;
809     }
810
811     ASSERT(kind == CodeForConstruct);
812     repatchBuffer.relink(callLinkInfo->callReturnLocation, vm->getCTIStub(oldStyleVirtualConstructGenerator).code());
813 }
814
815 void JIT::linkSlowCall(CodeBlock* callerCodeBlock, CallLinkInfo* callLinkInfo)
816 {
817     RepatchBuffer repatchBuffer(callerCodeBlock);
818
819     repatchBuffer.relink(callLinkInfo->callReturnLocation, callerCodeBlock->vm()->getCTIStub(oldStyleVirtualCallGenerator).code());
820 }
821
822 } // namespace JSC
823
824 #endif // ENABLE(JIT)