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