Baseline JIT should use the DFG's PutById IC
[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 "JITStubCall.h"
43 #include "JSArray.h"
44 #include "JSFunction.h"
45 #include "LinkBuffer.h"
46 #include "Operations.h"
47 #include "RepatchBuffer.h"
48 #include "ResultType.h"
49 #include "SamplingTool.h"
50 #include "SlowPathCall.h"
51 #include <wtf/CryptographicallyRandomNumber.h>
52
53 using namespace std;
54
55 namespace JSC {
56
57 void ctiPatchNearCallByReturnAddress(CodeBlock* codeblock, ReturnAddressPtr returnAddress, MacroAssemblerCodePtr newCalleeFunction)
58 {
59     RepatchBuffer repatchBuffer(codeblock);
60     repatchBuffer.relinkNearCallerToTrampoline(returnAddress, newCalleeFunction);
61 }
62
63 void ctiPatchCallByReturnAddress(CodeBlock* codeblock, ReturnAddressPtr returnAddress, MacroAssemblerCodePtr newCalleeFunction)
64 {
65     RepatchBuffer repatchBuffer(codeblock);
66     repatchBuffer.relinkCallerToTrampoline(returnAddress, newCalleeFunction);
67 }
68
69 void ctiPatchCallByReturnAddress(CodeBlock* codeblock, ReturnAddressPtr returnAddress, FunctionPtr newCalleeFunction)
70 {
71     RepatchBuffer repatchBuffer(codeblock);
72     repatchBuffer.relinkCallerToFunction(returnAddress, newCalleeFunction);
73 }
74
75 JIT::JIT(VM* vm, CodeBlock* codeBlock)
76     : JSInterfaceJIT(vm, codeBlock)
77     , m_interpreter(vm->interpreter)
78     , m_labels(codeBlock ? codeBlock->numberOfInstructions() : 0)
79     , m_bytecodeOffset((unsigned)-1)
80     , m_propertyAccessInstructionIndex(UINT_MAX)
81     , m_byValInstructionIndex(UINT_MAX)
82     , m_callLinkInfoIndex(UINT_MAX)
83 #if USE(JSVALUE32_64)
84     , m_jumpTargetIndex(0)
85     , m_mappedBytecodeOffset((unsigned)-1)
86     , m_mappedVirtualRegisterIndex(JSStack::ReturnPC)
87     , m_mappedTag((RegisterID)-1)
88     , m_mappedPayload((RegisterID)-1)
89 #else
90     , m_lastResultBytecodeRegister(std::numeric_limits<int>::max())
91     , m_jumpTargetsPosition(0)
92 #endif
93     , m_randomGenerator(cryptographicallyRandomNumber())
94 #if ENABLE(VALUE_PROFILER)
95     , m_canBeOptimized(false)
96     , m_shouldEmitProfiling(false)
97 #endif
98 {
99 }
100
101 #if ENABLE(DFG_JIT)
102 void JIT::emitEnterOptimizationCheck()
103 {
104     if (!canBeOptimized())
105         return;
106
107     Jump skipOptimize = branchAdd32(Signed, TrustedImm32(Options::executionCounterIncrementForEntry()), AbsoluteAddress(m_codeBlock->addressOfJITExecuteCounter()));
108     JITStubCall stubCall(this, cti_optimize);
109     stubCall.addArgument(TrustedImm32(m_bytecodeOffset));
110     ASSERT(!m_bytecodeOffset);
111     stubCall.call();
112     skipOptimize.link(this);
113 }
114 #endif
115
116 #define NEXT_OPCODE(name) \
117     m_bytecodeOffset += OPCODE_LENGTH(name); \
118     break;
119
120 #if USE(JSVALUE32_64)
121 #define DEFINE_BINARY_OP(name) \
122     case op_##name: { \
123         JITSlowPathCall slowPathCall(this, currentInstruction, slow_path_##name); \
124         slowPathCall.call(); \
125         NEXT_OPCODE(op_##name); \
126     }
127
128 #define DEFINE_UNARY_OP(name) \
129     case op_##name: { \
130         JITSlowPathCall slowPathCall(this, currentInstruction, slow_path_##name); \
131         slowPathCall.call(); \
132         NEXT_OPCODE(op_##name); \
133     }
134
135 #else // USE(JSVALUE32_64)
136
137 #define DEFINE_BINARY_OP(name) \
138     case op_##name: { \
139         JITSlowPathCall slowPathCall(this, currentInstruction, slow_path_##name); \
140         slowPathCall.call(); \
141         NEXT_OPCODE(op_##name); \
142     }
143
144 #define DEFINE_UNARY_OP(name) \
145     case op_##name: { \
146         JITSlowPathCall slowPathCall(this, currentInstruction, slow_path_##name); \
147         slowPathCall.call(); \
148         NEXT_OPCODE(op_##name); \
149     }
150 #endif // USE(JSVALUE32_64)
151
152 #define DEFINE_OP(name) \
153     case name: { \
154         emit_##name(currentInstruction); \
155         NEXT_OPCODE(name); \
156     }
157
158 #define DEFINE_SLOWCASE_OP(name) \
159     case name: { \
160         emitSlow_##name(currentInstruction, iter); \
161         NEXT_OPCODE(name); \
162     }
163
164 void JIT::privateCompileMainPass()
165 {
166     Instruction* instructionsBegin = m_codeBlock->instructions().begin();
167     unsigned instructionCount = m_codeBlock->instructions().size();
168
169     m_callLinkInfoIndex = 0;
170
171     for (m_bytecodeOffset = 0; m_bytecodeOffset < instructionCount; ) {
172         if (m_disassembler)
173             m_disassembler->setForBytecodeMainPath(m_bytecodeOffset, label());
174         Instruction* currentInstruction = instructionsBegin + m_bytecodeOffset;
175         ASSERT_WITH_MESSAGE(m_interpreter->isOpcode(currentInstruction->u.opcode), "privateCompileMainPass gone bad @ %d", m_bytecodeOffset);
176
177 #if ENABLE(OPCODE_SAMPLING)
178         if (m_bytecodeOffset > 0) // Avoid the overhead of sampling op_enter twice.
179             sampleInstruction(currentInstruction);
180 #endif
181
182 #if USE(JSVALUE64)
183         if (atJumpTarget())
184             killLastResultRegister();
185 #endif
186
187         m_labels[m_bytecodeOffset] = label();
188
189 #if ENABLE(JIT_VERBOSE)
190         dataLogF("Old JIT emitting code for bc#%u at offset 0x%lx.\n", m_bytecodeOffset, (long)debugOffset());
191 #endif
192         
193         OpcodeID opcodeID = m_interpreter->getOpcodeID(currentInstruction->u.opcode);
194
195         if (m_compilation) {
196             add64(
197                 TrustedImm32(1),
198                 AbsoluteAddress(m_compilation->executionCounterFor(Profiler::OriginStack(Profiler::Origin(
199                     m_compilation->bytecodes(), m_bytecodeOffset)))->address()));
200         }
201
202         switch (opcodeID) {
203         DEFINE_BINARY_OP(del_by_val)
204         DEFINE_BINARY_OP(in)
205         DEFINE_BINARY_OP(less)
206         DEFINE_BINARY_OP(lesseq)
207         DEFINE_BINARY_OP(greater)
208         DEFINE_BINARY_OP(greatereq)
209         DEFINE_UNARY_OP(is_function)
210         DEFINE_UNARY_OP(is_object)
211         DEFINE_UNARY_OP(typeof)
212
213         DEFINE_OP(op_add)
214         DEFINE_OP(op_bitand)
215         DEFINE_OP(op_bitor)
216         DEFINE_OP(op_bitxor)
217         DEFINE_OP(op_call)
218         DEFINE_OP(op_call_eval)
219         DEFINE_OP(op_call_varargs)
220         DEFINE_OP(op_catch)
221         DEFINE_OP(op_construct)
222         DEFINE_OP(op_get_callee)
223         DEFINE_OP(op_create_this)
224         DEFINE_OP(op_to_this)
225         DEFINE_OP(op_init_lazy_reg)
226         DEFINE_OP(op_create_arguments)
227         DEFINE_OP(op_debug)
228         DEFINE_OP(op_del_by_id)
229         DEFINE_OP(op_div)
230         DEFINE_OP(op_end)
231         DEFINE_OP(op_enter)
232         DEFINE_OP(op_create_activation)
233         DEFINE_OP(op_eq)
234         DEFINE_OP(op_eq_null)
235         case op_get_by_id_out_of_line:
236         case op_get_array_length:
237         DEFINE_OP(op_get_by_id)
238         DEFINE_OP(op_get_arguments_length)
239         DEFINE_OP(op_get_by_val)
240         DEFINE_OP(op_get_argument_by_val)
241         DEFINE_OP(op_get_by_pname)
242         DEFINE_OP(op_get_pnames)
243         DEFINE_OP(op_check_has_instance)
244         DEFINE_OP(op_instanceof)
245         DEFINE_OP(op_is_undefined)
246         DEFINE_OP(op_is_boolean)
247         DEFINE_OP(op_is_number)
248         DEFINE_OP(op_is_string)
249         DEFINE_OP(op_jeq_null)
250         DEFINE_OP(op_jfalse)
251         DEFINE_OP(op_jmp)
252         DEFINE_OP(op_jneq_null)
253         DEFINE_OP(op_jneq_ptr)
254         DEFINE_OP(op_jless)
255         DEFINE_OP(op_jlesseq)
256         DEFINE_OP(op_jgreater)
257         DEFINE_OP(op_jgreatereq)
258         DEFINE_OP(op_jnless)
259         DEFINE_OP(op_jnlesseq)
260         DEFINE_OP(op_jngreater)
261         DEFINE_OP(op_jngreatereq)
262         DEFINE_OP(op_jtrue)
263         DEFINE_OP(op_loop_hint)
264         DEFINE_OP(op_lshift)
265         DEFINE_OP(op_mod)
266         DEFINE_OP(op_mov)
267         DEFINE_OP(op_mul)
268         DEFINE_OP(op_negate)
269         DEFINE_OP(op_neq)
270         DEFINE_OP(op_neq_null)
271         DEFINE_OP(op_new_array)
272         DEFINE_OP(op_new_array_with_size)
273         DEFINE_OP(op_new_array_buffer)
274         DEFINE_OP(op_new_func)
275         DEFINE_OP(op_new_func_exp)
276         DEFINE_OP(op_new_object)
277         DEFINE_OP(op_new_regexp)
278         DEFINE_OP(op_next_pname)
279         DEFINE_OP(op_not)
280         DEFINE_OP(op_nstricteq)
281         DEFINE_OP(op_pop_scope)
282         DEFINE_OP(op_dec)
283         DEFINE_OP(op_inc)
284         DEFINE_OP(op_profile_did_call)
285         DEFINE_OP(op_profile_will_call)
286         DEFINE_OP(op_push_name_scope)
287         DEFINE_OP(op_push_with_scope)
288         case op_put_by_id_out_of_line:
289         case op_put_by_id_transition_direct:
290         case op_put_by_id_transition_normal:
291         case op_put_by_id_transition_direct_out_of_line:
292         case op_put_by_id_transition_normal_out_of_line:
293         DEFINE_OP(op_put_by_id)
294         DEFINE_OP(op_put_by_index)
295         DEFINE_OP(op_put_by_val)
296         DEFINE_OP(op_put_getter_setter)
297         case op_init_global_const_nop:
298             NEXT_OPCODE(op_init_global_const_nop);
299         DEFINE_OP(op_init_global_const)
300
301         DEFINE_OP(op_ret)
302         DEFINE_OP(op_ret_object_or_this)
303         DEFINE_OP(op_rshift)
304         DEFINE_OP(op_urshift)
305         DEFINE_OP(op_strcat)
306         DEFINE_OP(op_stricteq)
307         DEFINE_OP(op_sub)
308         DEFINE_OP(op_switch_char)
309         DEFINE_OP(op_switch_imm)
310         DEFINE_OP(op_switch_string)
311         DEFINE_OP(op_tear_off_activation)
312         DEFINE_OP(op_tear_off_arguments)
313         DEFINE_OP(op_throw)
314         DEFINE_OP(op_throw_static_error)
315         DEFINE_OP(op_to_number)
316         DEFINE_OP(op_to_primitive)
317
318         DEFINE_OP(op_resolve_scope)
319         DEFINE_OP(op_get_from_scope)
320         DEFINE_OP(op_put_to_scope)
321
322         case op_get_by_id_chain:
323         case op_get_by_id_generic:
324         case op_get_by_id_proto:
325         case op_get_by_id_self:
326         case op_get_by_id_getter_chain:
327         case op_get_by_id_getter_proto:
328         case op_get_by_id_getter_self:
329         case op_get_by_id_custom_chain:
330         case op_get_by_id_custom_proto:
331         case op_get_by_id_custom_self:
332         case op_get_string_length:
333         case op_put_by_id_generic:
334         case op_put_by_id_replace:
335         case op_put_by_id_transition:
336             RELEASE_ASSERT_NOT_REACHED();
337         }
338     }
339
340     RELEASE_ASSERT(m_callLinkInfoIndex == m_callStructureStubCompilationInfo.size());
341
342 #ifndef NDEBUG
343     // Reset this, in order to guard its use with ASSERTs.
344     m_bytecodeOffset = (unsigned)-1;
345 #endif
346 }
347
348 void JIT::privateCompileLinkPass()
349 {
350     unsigned jmpTableCount = m_jmpTable.size();
351     for (unsigned i = 0; i < jmpTableCount; ++i)
352         m_jmpTable[i].from.linkTo(m_labels[m_jmpTable[i].toBytecodeOffset], this);
353     m_jmpTable.clear();
354 }
355
356 void JIT::privateCompileSlowCases()
357 {
358     Instruction* instructionsBegin = m_codeBlock->instructions().begin();
359
360     m_propertyAccessInstructionIndex = 0;
361     m_byValInstructionIndex = 0;
362     m_callLinkInfoIndex = 0;
363     
364 #if ENABLE(VALUE_PROFILER)
365     // Use this to assert that slow-path code associates new profiling sites with existing
366     // ValueProfiles rather than creating new ones. This ensures that for a given instruction
367     // (say, get_by_id) we get combined statistics for both the fast-path executions of that
368     // instructions and the slow-path executions. Furthermore, if the slow-path code created
369     // new ValueProfiles then the ValueProfiles would no longer be sorted by bytecode offset,
370     // which would break the invariant necessary to use CodeBlock::valueProfileForBytecodeOffset().
371     unsigned numberOfValueProfiles = m_codeBlock->numberOfValueProfiles();
372 #endif
373
374     for (Vector<SlowCaseEntry>::iterator iter = m_slowCases.begin(); iter != m_slowCases.end();) {
375 #if USE(JSVALUE64)
376         killLastResultRegister();
377 #endif
378
379         m_bytecodeOffset = iter->to;
380
381         unsigned firstTo = m_bytecodeOffset;
382
383         Instruction* currentInstruction = instructionsBegin + m_bytecodeOffset;
384         
385 #if ENABLE(VALUE_PROFILER)
386         RareCaseProfile* rareCaseProfile = 0;
387         if (shouldEmitProfiling())
388             rareCaseProfile = m_codeBlock->addRareCaseProfile(m_bytecodeOffset);
389 #endif
390
391 #if ENABLE(JIT_VERBOSE)
392         dataLogF("Old JIT emitting slow code for bc#%u at offset 0x%lx.\n", m_bytecodeOffset, (long)debugOffset());
393 #endif
394         
395         if (m_disassembler)
396             m_disassembler->setForBytecodeSlowPath(m_bytecodeOffset, label());
397
398         switch (m_interpreter->getOpcodeID(currentInstruction->u.opcode)) {
399         DEFINE_SLOWCASE_OP(op_add)
400         DEFINE_SLOWCASE_OP(op_bitand)
401         DEFINE_SLOWCASE_OP(op_bitor)
402         DEFINE_SLOWCASE_OP(op_bitxor)
403         DEFINE_SLOWCASE_OP(op_call)
404         DEFINE_SLOWCASE_OP(op_call_eval)
405         DEFINE_SLOWCASE_OP(op_call_varargs)
406         DEFINE_SLOWCASE_OP(op_construct)
407         DEFINE_SLOWCASE_OP(op_to_this)
408         DEFINE_SLOWCASE_OP(op_create_this)
409         DEFINE_SLOWCASE_OP(op_div)
410         DEFINE_SLOWCASE_OP(op_eq)
411         DEFINE_SLOWCASE_OP(op_get_callee)
412         case op_get_by_id_out_of_line:
413         case op_get_array_length:
414         DEFINE_SLOWCASE_OP(op_get_by_id)
415         DEFINE_SLOWCASE_OP(op_get_arguments_length)
416         DEFINE_SLOWCASE_OP(op_get_by_val)
417         DEFINE_SLOWCASE_OP(op_get_argument_by_val)
418         DEFINE_SLOWCASE_OP(op_get_by_pname)
419         DEFINE_SLOWCASE_OP(op_check_has_instance)
420         DEFINE_SLOWCASE_OP(op_instanceof)
421         DEFINE_SLOWCASE_OP(op_jfalse)
422         DEFINE_SLOWCASE_OP(op_jless)
423         DEFINE_SLOWCASE_OP(op_jlesseq)
424         DEFINE_SLOWCASE_OP(op_jgreater)
425         DEFINE_SLOWCASE_OP(op_jgreatereq)
426         DEFINE_SLOWCASE_OP(op_jnless)
427         DEFINE_SLOWCASE_OP(op_jnlesseq)
428         DEFINE_SLOWCASE_OP(op_jngreater)
429         DEFINE_SLOWCASE_OP(op_jngreatereq)
430         DEFINE_SLOWCASE_OP(op_jtrue)
431         DEFINE_SLOWCASE_OP(op_loop_hint)
432         DEFINE_SLOWCASE_OP(op_lshift)
433         DEFINE_SLOWCASE_OP(op_mod)
434         DEFINE_SLOWCASE_OP(op_mul)
435         DEFINE_SLOWCASE_OP(op_negate)
436         DEFINE_SLOWCASE_OP(op_neq)
437         DEFINE_SLOWCASE_OP(op_new_object)
438         DEFINE_SLOWCASE_OP(op_not)
439         DEFINE_SLOWCASE_OP(op_nstricteq)
440         DEFINE_SLOWCASE_OP(op_dec)
441         DEFINE_SLOWCASE_OP(op_inc)
442         case op_put_by_id_out_of_line:
443         case op_put_by_id_transition_direct:
444         case op_put_by_id_transition_normal:
445         case op_put_by_id_transition_direct_out_of_line:
446         case op_put_by_id_transition_normal_out_of_line:
447         DEFINE_SLOWCASE_OP(op_put_by_id)
448         DEFINE_SLOWCASE_OP(op_put_by_val)
449         DEFINE_SLOWCASE_OP(op_rshift)
450         DEFINE_SLOWCASE_OP(op_urshift)
451         DEFINE_SLOWCASE_OP(op_stricteq)
452         DEFINE_SLOWCASE_OP(op_sub)
453         DEFINE_SLOWCASE_OP(op_to_number)
454         DEFINE_SLOWCASE_OP(op_to_primitive)
455
456         DEFINE_SLOWCASE_OP(op_resolve_scope)
457         DEFINE_SLOWCASE_OP(op_get_from_scope)
458         DEFINE_SLOWCASE_OP(op_put_to_scope)
459
460         default:
461             RELEASE_ASSERT_NOT_REACHED();
462         }
463
464         RELEASE_ASSERT_WITH_MESSAGE(iter == m_slowCases.end() || firstTo != iter->to, "Not enough jumps linked in slow case codegen.");
465         RELEASE_ASSERT_WITH_MESSAGE(firstTo == (iter - 1)->to, "Too many jumps linked in slow case codegen.");
466         
467 #if ENABLE(VALUE_PROFILER)
468         if (shouldEmitProfiling())
469             add32(TrustedImm32(1), AbsoluteAddress(&rareCaseProfile->m_counter));
470 #endif
471
472         emitJumpSlowToHot(jump(), 0);
473     }
474
475     RELEASE_ASSERT(m_propertyAccessInstructionIndex == m_propertyAccessCompilationInfo.size());
476     RELEASE_ASSERT(m_callLinkInfoIndex == m_callStructureStubCompilationInfo.size());
477 #if ENABLE(VALUE_PROFILER)
478     RELEASE_ASSERT(numberOfValueProfiles == m_codeBlock->numberOfValueProfiles());
479 #endif
480
481 #ifndef NDEBUG
482     // Reset this, in order to guard its use with ASSERTs.
483     m_bytecodeOffset = (unsigned)-1;
484 #endif
485 }
486
487 ALWAYS_INLINE void PropertyStubCompilationInfo::copyToStubInfo(StructureStubInfo& info, LinkBuffer &linkBuffer)
488 {
489     ASSERT(bytecodeIndex != std::numeric_limits<unsigned>::max());
490     info.codeOrigin = CodeOrigin(bytecodeIndex);
491     info.callReturnLocation = linkBuffer.locationOf(callReturnLocation);
492
493     switch (m_type) {
494     case GetById: {
495         CodeLocationLabel hotPathBeginLocation = linkBuffer.locationOf(hotPathBegin);
496         info.hotPathBegin = hotPathBeginLocation;
497         info.patch.baseline.u.get.structureToCompare = MacroAssembler::differenceBetweenCodePtr(hotPathBeginLocation, linkBuffer.locationOf(structureToCompare));
498         info.patch.baseline.u.get.structureCheck = MacroAssembler::differenceBetweenCodePtr(hotPathBeginLocation, linkBuffer.locationOf(structureCheck));
499         info.patch.baseline.u.get.propertyStorageLoad = MacroAssembler::differenceBetweenCodePtr(hotPathBeginLocation, linkBuffer.locationOf(propertyStorageLoad));
500 #if USE(JSVALUE64)
501         info.patch.baseline.u.get.displacementLabel = MacroAssembler::differenceBetweenCodePtr(hotPathBeginLocation, linkBuffer.locationOf(getDisplacementLabel));
502 #else
503         info.patch.baseline.u.get.displacementLabel1 = MacroAssembler::differenceBetweenCodePtr(hotPathBeginLocation, linkBuffer.locationOf(getDisplacementLabel1));
504         info.patch.baseline.u.get.displacementLabel2 = MacroAssembler::differenceBetweenCodePtr(hotPathBeginLocation, linkBuffer.locationOf(getDisplacementLabel2));
505 #endif
506         info.patch.baseline.u.get.putResult = MacroAssembler::differenceBetweenCodePtr(hotPathBeginLocation, linkBuffer.locationOf(done));
507         info.patch.baseline.u.get.coldPathBegin = MacroAssembler::differenceBetweenCodePtr(linkBuffer.locationOf(coldPathBegin), linkBuffer.locationOf(callReturnLocation));
508         break;
509     }
510     case PutById:
511         info.patch.dfg.deltaCheckImmToCall = MacroAssembler::differenceBetweenCodePtr(linkBuffer.locationOf(structureToCompare), info.callReturnLocation);
512         info.patch.dfg.deltaCallToStructCheck = MacroAssembler::differenceBetweenCodePtr(info.callReturnLocation, linkBuffer.locationOf(structureCheck));
513 #if USE(JSVALUE64)
514         info.patch.dfg.deltaCallToLoadOrStore = MacroAssembler::differenceBetweenCodePtr(info.callReturnLocation, linkBuffer.locationOf(putDisplacementLabel));
515 #else
516         info.patch.dfg.deltaCallToTagLoadOrStore = MacroAssembler::differenceBetweenCodePtr(info.callReturnLocation, linkBuffer.locationOf(putDisplacementLabel2));
517         info.patch.dfg.deltaCallToPayloadLoadOrStore = MacroAssembler::differenceBetweenCodePtr(info.callReturnLocation, linkBuffer.locationOf(putDisplacementLabel1));
518 #endif
519         info.patch.dfg.deltaCallToSlowCase = MacroAssembler::differenceBetweenCodePtr(info.callReturnLocation, linkBuffer.locationOf(coldPathBegin));
520         info.patch.dfg.deltaCallToDone = MacroAssembler::differenceBetweenCodePtr(info.callReturnLocation, linkBuffer.locationOf(done));
521         info.patch.dfg.deltaCallToStorageLoad = MacroAssembler::differenceBetweenCodePtr(info.callReturnLocation, linkBuffer.locationOf(propertyStorageLoad));
522 #if USE(JSVALUE64)
523         info.patch.dfg.baseGPR = GPRInfo::regT0;
524         info.patch.dfg.valueGPR = GPRInfo::regT1;
525         RegisterSet usedRegisters;
526         usedRegisters.set(GPRInfo::regT0);
527         usedRegisters.set(GPRInfo::regT1);
528         usedRegisters.copyInfo(info.patch.dfg.usedRegisters);
529 #else
530         info.patch.dfg.baseGPR = GPRInfo::regT0;
531         info.patch.dfg.valueGPR = GPRInfo::regT2;
532         info.patch.dfg.valueTagGPR = GPRInfo::regT3;
533         RegisterSet usedRegisters;
534         usedRegisters.set(GPRInfo::regT0);
535         usedRegisters.set(GPRInfo::regT2);
536         usedRegisters.set(GPRInfo::regT3);
537         usedRegisters.copyInfo(info.patch.dfg.usedRegisters);
538 #endif
539         info.patch.dfg.registersFlushed = true;
540         break;
541     }
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(TrustedImmPtr(reinterpret_cast<void *>(~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     // lookupExceptionHandler leaves the handler CallFrame* in the returnValueGPR,
874     // and the address of the handler in returnValueGPR2.
875     jump(GPRInfo::returnValueGPR2);
876 }
877
878
879 } // namespace JSC
880
881 #endif // ENABLE(JIT)