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