[ES6] "super" and "this" should be lexically bound inside an arrow function and shoul...
[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         unsigned bytecodeOffset = m_bytecodeOffset;
185         
186         switch (opcodeID) {
187         DEFINE_SLOW_OP(del_by_val)
188         DEFINE_SLOW_OP(in)
189         DEFINE_SLOW_OP(less)
190         DEFINE_SLOW_OP(lesseq)
191         DEFINE_SLOW_OP(greater)
192         DEFINE_SLOW_OP(greatereq)
193         DEFINE_SLOW_OP(is_function)
194         DEFINE_SLOW_OP(is_object_or_null)
195         DEFINE_SLOW_OP(typeof)
196
197         DEFINE_OP(op_add)
198         DEFINE_OP(op_bitand)
199         DEFINE_OP(op_bitor)
200         DEFINE_OP(op_bitxor)
201         DEFINE_OP(op_call)
202         DEFINE_OP(op_tail_call)
203         DEFINE_OP(op_call_eval)
204         DEFINE_OP(op_call_varargs)
205         DEFINE_OP(op_tail_call_varargs)
206         DEFINE_OP(op_construct_varargs)
207         DEFINE_OP(op_catch)
208         DEFINE_OP(op_construct)
209         DEFINE_OP(op_create_this)
210         DEFINE_OP(op_to_this)
211         DEFINE_OP(op_create_direct_arguments)
212         DEFINE_OP(op_create_scoped_arguments)
213         DEFINE_OP(op_create_out_of_band_arguments)
214         DEFINE_OP(op_copy_rest)
215         DEFINE_OP(op_get_rest_length)
216         DEFINE_OP(op_check_tdz)
217         DEFINE_OP(op_assert)
218         DEFINE_OP(op_save)
219         DEFINE_OP(op_resume)
220         DEFINE_OP(op_debug)
221         DEFINE_OP(op_del_by_id)
222         DEFINE_OP(op_div)
223         DEFINE_OP(op_end)
224         DEFINE_OP(op_enter)
225         DEFINE_OP(op_get_scope)
226         DEFINE_OP(op_eq)
227         DEFINE_OP(op_eq_null)
228         case op_get_array_length:
229         DEFINE_OP(op_get_by_id)
230         DEFINE_OP(op_get_by_val)
231         DEFINE_OP(op_check_has_instance)
232         DEFINE_OP(op_instanceof)
233         DEFINE_OP(op_is_undefined)
234         DEFINE_OP(op_is_boolean)
235         DEFINE_OP(op_is_number)
236         DEFINE_OP(op_is_string)
237         DEFINE_OP(op_is_object)
238         DEFINE_OP(op_jeq_null)
239         DEFINE_OP(op_jfalse)
240         DEFINE_OP(op_jmp)
241         DEFINE_OP(op_jneq_null)
242         DEFINE_OP(op_jneq_ptr)
243         DEFINE_OP(op_jless)
244         DEFINE_OP(op_jlesseq)
245         DEFINE_OP(op_jgreater)
246         DEFINE_OP(op_jgreatereq)
247         DEFINE_OP(op_jnless)
248         DEFINE_OP(op_jnlesseq)
249         DEFINE_OP(op_jngreater)
250         DEFINE_OP(op_jngreatereq)
251         DEFINE_OP(op_jtrue)
252         DEFINE_OP(op_loop_hint)
253         DEFINE_OP(op_lshift)
254         DEFINE_OP(op_mod)
255         DEFINE_OP(op_mov)
256         DEFINE_OP(op_mul)
257         DEFINE_OP(op_negate)
258         DEFINE_OP(op_neq)
259         DEFINE_OP(op_neq_null)
260         DEFINE_OP(op_new_array)
261         DEFINE_OP(op_new_array_with_size)
262         DEFINE_OP(op_new_array_buffer)
263         DEFINE_OP(op_new_func)
264         DEFINE_OP(op_new_func_exp)
265         DEFINE_OP(op_new_generator_func)
266         DEFINE_OP(op_new_generator_func_exp)
267         DEFINE_OP(op_new_arrow_func_exp) 
268         DEFINE_OP(op_new_object)
269         DEFINE_OP(op_new_regexp)
270         DEFINE_OP(op_not)
271         DEFINE_OP(op_nstricteq)
272         DEFINE_OP(op_dec)
273         DEFINE_OP(op_inc)
274         DEFINE_OP(op_profile_did_call)
275         DEFINE_OP(op_profile_will_call)
276         DEFINE_OP(op_profile_type)
277         DEFINE_OP(op_profile_control_flow)
278         DEFINE_OP(op_push_with_scope)
279         DEFINE_OP(op_create_lexical_environment)
280         DEFINE_OP(op_get_parent_scope)
281         DEFINE_OP(op_put_by_id)
282         DEFINE_OP(op_put_by_index)
283         case op_put_by_val_direct:
284         DEFINE_OP(op_put_by_val)
285         DEFINE_OP(op_put_getter_by_id)
286         DEFINE_OP(op_put_setter_by_id)
287         DEFINE_OP(op_put_getter_setter_by_id)
288         DEFINE_OP(op_put_getter_by_val)
289         DEFINE_OP(op_put_setter_by_val)
290
291         DEFINE_OP(op_ret)
292         DEFINE_OP(op_rshift)
293         DEFINE_OP(op_unsigned)
294         DEFINE_OP(op_urshift)
295         DEFINE_OP(op_strcat)
296         DEFINE_OP(op_stricteq)
297         DEFINE_OP(op_sub)
298         DEFINE_OP(op_switch_char)
299         DEFINE_OP(op_switch_imm)
300         DEFINE_OP(op_switch_string)
301         DEFINE_OP(op_throw)
302         DEFINE_OP(op_throw_static_error)
303         DEFINE_OP(op_to_number)
304         DEFINE_OP(op_to_string)
305         DEFINE_OP(op_to_primitive)
306
307         DEFINE_OP(op_resolve_scope)
308         DEFINE_OP(op_get_from_scope)
309         DEFINE_OP(op_put_to_scope)
310         DEFINE_OP(op_get_from_arguments)
311         DEFINE_OP(op_put_to_arguments)
312
313         DEFINE_OP(op_get_enumerable_length)
314         DEFINE_OP(op_has_generic_property)
315         DEFINE_OP(op_has_structure_property)
316         DEFINE_OP(op_has_indexed_property)
317         DEFINE_OP(op_get_direct_pname)
318         DEFINE_OP(op_get_property_enumerator)
319         DEFINE_OP(op_enumerator_structure_pname)
320         DEFINE_OP(op_enumerator_generic_pname)
321         DEFINE_OP(op_to_index_string)
322         default:
323             RELEASE_ASSERT_NOT_REACHED();
324         }
325
326         if (false)
327             dataLog("At ", bytecodeOffset, ": ", m_slowCases.size(), "\n");
328     }
329
330     RELEASE_ASSERT(m_callLinkInfoIndex == m_callCompilationInfo.size());
331
332 #ifndef NDEBUG
333     // Reset this, in order to guard its use with ASSERTs.
334     m_bytecodeOffset = std::numeric_limits<unsigned>::max();
335 #endif
336 }
337
338 void JIT::privateCompileLinkPass()
339 {
340     unsigned jmpTableCount = m_jmpTable.size();
341     for (unsigned i = 0; i < jmpTableCount; ++i)
342         m_jmpTable[i].from.linkTo(m_labels[m_jmpTable[i].toBytecodeOffset], this);
343     m_jmpTable.clear();
344 }
345
346 void JIT::privateCompileSlowCases()
347 {
348     Instruction* instructionsBegin = m_codeBlock->instructions().begin();
349
350     m_getByIdIndex = 0;
351     m_putByIdIndex = 0;
352     m_byValInstructionIndex = 0;
353     m_callLinkInfoIndex = 0;
354     
355     // Use this to assert that slow-path code associates new profiling sites with existing
356     // ValueProfiles rather than creating new ones. This ensures that for a given instruction
357     // (say, get_by_id) we get combined statistics for both the fast-path executions of that
358     // instructions and the slow-path executions. Furthermore, if the slow-path code created
359     // new ValueProfiles then the ValueProfiles would no longer be sorted by bytecode offset,
360     // which would break the invariant necessary to use CodeBlock::valueProfileForBytecodeOffset().
361     unsigned numberOfValueProfiles = m_codeBlock->numberOfValueProfiles();
362
363     for (Vector<SlowCaseEntry>::iterator iter = m_slowCases.begin(); iter != m_slowCases.end();) {
364         m_bytecodeOffset = iter->to;
365
366         unsigned firstTo = m_bytecodeOffset;
367
368         Instruction* currentInstruction = instructionsBegin + m_bytecodeOffset;
369         
370         RareCaseProfile* rareCaseProfile = 0;
371         if (shouldEmitProfiling())
372             rareCaseProfile = m_codeBlock->addRareCaseProfile(m_bytecodeOffset);
373
374 #if ENABLE(JIT_VERBOSE)
375         dataLogF("Old JIT emitting slow code for bc#%u at offset 0x%lx.\n", m_bytecodeOffset, (long)debugOffset());
376 #endif
377         
378         if (m_disassembler)
379             m_disassembler->setForBytecodeSlowPath(m_bytecodeOffset, label());
380
381         switch (m_interpreter->getOpcodeID(currentInstruction->u.opcode)) {
382         DEFINE_SLOWCASE_OP(op_add)
383         DEFINE_SLOWCASE_OP(op_bitand)
384         DEFINE_SLOWCASE_OP(op_bitor)
385         DEFINE_SLOWCASE_OP(op_bitxor)
386         DEFINE_SLOWCASE_OP(op_call)
387         DEFINE_SLOWCASE_OP(op_tail_call)
388         DEFINE_SLOWCASE_OP(op_call_eval)
389         DEFINE_SLOWCASE_OP(op_call_varargs)
390         DEFINE_SLOWCASE_OP(op_tail_call_varargs)
391         DEFINE_SLOWCASE_OP(op_construct_varargs)
392         DEFINE_SLOWCASE_OP(op_construct)
393         DEFINE_SLOWCASE_OP(op_to_this)
394         DEFINE_SLOWCASE_OP(op_check_tdz)
395         DEFINE_SLOWCASE_OP(op_create_this)
396         DEFINE_SLOWCASE_OP(op_div)
397         DEFINE_SLOWCASE_OP(op_eq)
398         case op_get_array_length:
399         DEFINE_SLOWCASE_OP(op_get_by_id)
400         DEFINE_SLOWCASE_OP(op_get_by_val)
401         DEFINE_SLOWCASE_OP(op_check_has_instance)
402         DEFINE_SLOWCASE_OP(op_instanceof)
403         DEFINE_SLOWCASE_OP(op_jfalse)
404         DEFINE_SLOWCASE_OP(op_jless)
405         DEFINE_SLOWCASE_OP(op_jlesseq)
406         DEFINE_SLOWCASE_OP(op_jgreater)
407         DEFINE_SLOWCASE_OP(op_jgreatereq)
408         DEFINE_SLOWCASE_OP(op_jnless)
409         DEFINE_SLOWCASE_OP(op_jnlesseq)
410         DEFINE_SLOWCASE_OP(op_jngreater)
411         DEFINE_SLOWCASE_OP(op_jngreatereq)
412         DEFINE_SLOWCASE_OP(op_jtrue)
413         DEFINE_SLOWCASE_OP(op_loop_hint)
414         DEFINE_SLOWCASE_OP(op_lshift)
415         DEFINE_SLOWCASE_OP(op_mod)
416         DEFINE_SLOWCASE_OP(op_mul)
417         DEFINE_SLOWCASE_OP(op_negate)
418         DEFINE_SLOWCASE_OP(op_neq)
419         DEFINE_SLOWCASE_OP(op_new_object)
420         DEFINE_SLOWCASE_OP(op_not)
421         DEFINE_SLOWCASE_OP(op_nstricteq)
422         DEFINE_SLOWCASE_OP(op_dec)
423         DEFINE_SLOWCASE_OP(op_inc)
424         DEFINE_SLOWCASE_OP(op_put_by_id)
425         case op_put_by_val_direct:
426         DEFINE_SLOWCASE_OP(op_put_by_val)
427         DEFINE_SLOWCASE_OP(op_rshift)
428         DEFINE_SLOWCASE_OP(op_unsigned)
429         DEFINE_SLOWCASE_OP(op_urshift)
430         DEFINE_SLOWCASE_OP(op_stricteq)
431         DEFINE_SLOWCASE_OP(op_sub)
432         DEFINE_SLOWCASE_OP(op_to_number)
433         DEFINE_SLOWCASE_OP(op_to_string)
434         DEFINE_SLOWCASE_OP(op_to_primitive)
435         DEFINE_SLOWCASE_OP(op_has_indexed_property)
436         DEFINE_SLOWCASE_OP(op_has_structure_property)
437         DEFINE_SLOWCASE_OP(op_get_direct_pname)
438
439         DEFINE_SLOWCASE_OP(op_resolve_scope)
440         DEFINE_SLOWCASE_OP(op_get_from_scope)
441         DEFINE_SLOWCASE_OP(op_put_to_scope)
442
443         default:
444             RELEASE_ASSERT_NOT_REACHED();
445         }
446
447         if (false)
448             dataLog("At ", firstTo, " slow: ", iter - m_slowCases.begin(), "\n");
449
450         RELEASE_ASSERT_WITH_MESSAGE(iter == m_slowCases.end() || firstTo != iter->to, "Not enough jumps linked in slow case codegen.");
451         RELEASE_ASSERT_WITH_MESSAGE(firstTo == (iter - 1)->to, "Too many jumps linked in slow case codegen.");
452         
453         if (shouldEmitProfiling())
454             add32(TrustedImm32(1), AbsoluteAddress(&rareCaseProfile->m_counter));
455
456         emitJumpSlowToHot(jump(), 0);
457     }
458
459     RELEASE_ASSERT(m_getByIdIndex == m_getByIds.size());
460     RELEASE_ASSERT(m_putByIdIndex == m_putByIds.size());
461     RELEASE_ASSERT(m_callLinkInfoIndex == m_callCompilationInfo.size());
462     RELEASE_ASSERT(numberOfValueProfiles == m_codeBlock->numberOfValueProfiles());
463
464 #ifndef NDEBUG
465     // Reset this, in order to guard its use with ASSERTs.
466     m_bytecodeOffset = std::numeric_limits<unsigned>::max();
467 #endif
468 }
469
470 CompilationResult JIT::privateCompile(JITCompilationEffort effort)
471 {
472     DFG::CapabilityLevel level = m_codeBlock->capabilityLevel();
473     switch (level) {
474     case DFG::CannotCompile:
475         m_canBeOptimized = false;
476         m_canBeOptimizedOrInlined = false;
477         m_shouldEmitProfiling = false;
478         break;
479     case DFG::CanCompile:
480     case DFG::CanCompileAndInline:
481         m_canBeOptimized = true;
482         m_canBeOptimizedOrInlined = true;
483         m_shouldEmitProfiling = true;
484         break;
485     default:
486         RELEASE_ASSERT_NOT_REACHED();
487         break;
488     }
489     
490     switch (m_codeBlock->codeType()) {
491     case GlobalCode:
492     case ModuleCode:
493     case EvalCode:
494         m_codeBlock->m_shouldAlwaysBeInlined = false;
495         break;
496     case FunctionCode:
497         // We could have already set it to false because we detected an uninlineable call.
498         // Don't override that observation.
499         m_codeBlock->m_shouldAlwaysBeInlined &= canInline(level) && DFG::mightInlineFunction(m_codeBlock);
500         break;
501     }
502
503     m_codeBlock->setCalleeSaveRegisters(RegisterSet::llintBaselineCalleeSaveRegisters()); // Might be able to remove as this is probably already set to this value.
504
505     // This ensures that we have the most up to date type information when performing typecheck optimizations for op_profile_type.
506     if (m_vm->typeProfiler())
507         m_vm->typeProfilerLog()->processLogEntries(ASCIILiteral("Preparing for JIT compilation."));
508     
509     if (Options::dumpDisassembly() || m_vm->m_perBytecodeProfiler)
510         m_disassembler = std::make_unique<JITDisassembler>(m_codeBlock);
511     if (m_vm->m_perBytecodeProfiler) {
512         m_compilation = adoptRef(
513             new Profiler::Compilation(
514                 m_vm->m_perBytecodeProfiler->ensureBytecodesFor(m_codeBlock),
515                 Profiler::Baseline));
516         m_compilation->addProfiledBytecodes(*m_vm->m_perBytecodeProfiler, m_codeBlock);
517     }
518     
519     if (m_disassembler)
520         m_disassembler->setStartOfCode(label());
521
522     // Just add a little bit of randomness to the codegen
523     if (m_randomGenerator.getUint32() & 1)
524         nop();
525
526     emitFunctionPrologue();
527     emitPutToCallFrameHeader(m_codeBlock, JSStack::CodeBlock);
528
529     Label beginLabel(this);
530
531     sampleCodeBlock(m_codeBlock);
532 #if ENABLE(OPCODE_SAMPLING)
533     sampleInstruction(m_codeBlock->instructions().begin());
534 #endif
535
536     if (m_codeBlock->codeType() == FunctionCode) {
537         ASSERT(m_bytecodeOffset == std::numeric_limits<unsigned>::max());
538         if (shouldEmitProfiling()) {
539             for (int argument = 0; argument < m_codeBlock->numParameters(); ++argument) {
540                 // If this is a constructor, then we want to put in a dummy profiling site (to
541                 // keep things consistent) but we don't actually want to record the dummy value.
542                 if (m_codeBlock->m_isConstructor && !argument)
543                     continue;
544                 int offset = CallFrame::argumentOffsetIncludingThis(argument) * static_cast<int>(sizeof(Register));
545 #if USE(JSVALUE64)
546                 load64(Address(callFrameRegister, offset), regT0);
547 #elif USE(JSVALUE32_64)
548                 load32(Address(callFrameRegister, offset + OBJECT_OFFSETOF(JSValue, u.asBits.payload)), regT0);
549                 load32(Address(callFrameRegister, offset + OBJECT_OFFSETOF(JSValue, u.asBits.tag)), regT1);
550 #endif
551                 emitValueProfilingSite(m_codeBlock->valueProfileForArgument(argument));
552             }
553         }
554     }
555
556     addPtr(TrustedImm32(stackPointerOffsetFor(m_codeBlock) * sizeof(Register)), callFrameRegister, regT1);
557     Jump stackOverflow = branchPtr(Above, AbsoluteAddress(m_vm->addressOfStackLimit()), regT1);
558
559     move(regT1, stackPointerRegister);
560     checkStackPointerAlignment();
561
562     emitSaveCalleeSaves();
563     emitMaterializeTagCheckRegisters();
564
565     privateCompileMainPass();
566     privateCompileLinkPass();
567     privateCompileSlowCases();
568     
569     if (m_disassembler)
570         m_disassembler->setEndOfSlowPath(label());
571
572     stackOverflow.link(this);
573     m_bytecodeOffset = 0;
574     if (maxFrameExtentForSlowPathCall)
575         addPtr(TrustedImm32(-maxFrameExtentForSlowPathCall), stackPointerRegister);
576     callOperationWithCallFrameRollbackOnException(operationThrowStackOverflowError, m_codeBlock);
577
578     Label arityCheck;
579     if (m_codeBlock->codeType() == FunctionCode) {
580         arityCheck = label();
581         store8(TrustedImm32(0), &m_codeBlock->m_shouldAlwaysBeInlined);
582         emitFunctionPrologue();
583         emitPutToCallFrameHeader(m_codeBlock, JSStack::CodeBlock);
584
585         load32(payloadFor(JSStack::ArgumentCount), regT1);
586         branch32(AboveOrEqual, regT1, TrustedImm32(m_codeBlock->m_numParameters)).linkTo(beginLabel, this);
587
588         m_bytecodeOffset = 0;
589
590         if (maxFrameExtentForSlowPathCall)
591             addPtr(TrustedImm32(-maxFrameExtentForSlowPathCall), stackPointerRegister);
592         callOperationWithCallFrameRollbackOnException(m_codeBlock->m_isConstructor ? operationConstructArityCheck : operationCallArityCheck);
593         if (maxFrameExtentForSlowPathCall)
594             addPtr(TrustedImm32(maxFrameExtentForSlowPathCall), stackPointerRegister);
595         branchTest32(Zero, returnValueGPR).linkTo(beginLabel, this);
596         move(returnValueGPR, GPRInfo::argumentGPR0);
597         emitNakedCall(m_vm->getCTIStub(arityFixupGenerator).code());
598
599 #if !ASSERT_DISABLED
600         m_bytecodeOffset = std::numeric_limits<unsigned>::max(); // Reset this, in order to guard its use with ASSERTs.
601 #endif
602
603         jump(beginLabel);
604     }
605
606     ASSERT(m_jmpTable.isEmpty());
607     
608     privateCompileExceptionHandlers();
609     
610     if (m_disassembler)
611         m_disassembler->setEndOfCode(label());
612
613     LinkBuffer patchBuffer(*m_vm, *this, m_codeBlock, effort);
614     if (patchBuffer.didFailToAllocate())
615         return CompilationFailed;
616
617     // Translate vPC offsets into addresses in JIT generated code, for switch tables.
618     for (unsigned i = 0; i < m_switches.size(); ++i) {
619         SwitchRecord record = m_switches[i];
620         unsigned bytecodeOffset = record.bytecodeOffset;
621
622         if (record.type != SwitchRecord::String) {
623             ASSERT(record.type == SwitchRecord::Immediate || record.type == SwitchRecord::Character); 
624             ASSERT(record.jumpTable.simpleJumpTable->branchOffsets.size() == record.jumpTable.simpleJumpTable->ctiOffsets.size());
625
626             record.jumpTable.simpleJumpTable->ctiDefault = patchBuffer.locationOf(m_labels[bytecodeOffset + record.defaultOffset]);
627
628             for (unsigned j = 0; j < record.jumpTable.simpleJumpTable->branchOffsets.size(); ++j) {
629                 unsigned offset = record.jumpTable.simpleJumpTable->branchOffsets[j];
630                 record.jumpTable.simpleJumpTable->ctiOffsets[j] = offset ? patchBuffer.locationOf(m_labels[bytecodeOffset + offset]) : record.jumpTable.simpleJumpTable->ctiDefault;
631             }
632         } else {
633             ASSERT(record.type == SwitchRecord::String);
634
635             record.jumpTable.stringJumpTable->ctiDefault = patchBuffer.locationOf(m_labels[bytecodeOffset + record.defaultOffset]);
636
637             StringJumpTable::StringOffsetTable::iterator end = record.jumpTable.stringJumpTable->offsetTable.end();            
638             for (StringJumpTable::StringOffsetTable::iterator it = record.jumpTable.stringJumpTable->offsetTable.begin(); it != end; ++it) {
639                 unsigned offset = it->value.branchOffset;
640                 it->value.ctiOffset = offset ? patchBuffer.locationOf(m_labels[bytecodeOffset + offset]) : record.jumpTable.stringJumpTable->ctiDefault;
641             }
642         }
643     }
644
645     for (size_t i = 0; i < m_codeBlock->numberOfExceptionHandlers(); ++i) {
646         HandlerInfo& handler = m_codeBlock->exceptionHandler(i);
647         handler.nativeCode = patchBuffer.locationOf(m_labels[handler.target]);
648     }
649
650     for (Vector<CallRecord>::iterator iter = m_calls.begin(); iter != m_calls.end(); ++iter) {
651         if (iter->to)
652             patchBuffer.link(iter->from, FunctionPtr(iter->to));
653     }
654
655     for (unsigned i = m_getByIds.size(); i--;)
656         m_getByIds[i].finalize(patchBuffer);
657     for (unsigned i = m_putByIds.size(); i--;)
658         m_putByIds[i].finalize(patchBuffer);
659
660     for (const auto& byValCompilationInfo : m_byValCompilationInfo) {
661         PatchableJump patchableNotIndexJump = byValCompilationInfo.notIndexJump;
662         CodeLocationJump notIndexJump = CodeLocationJump();
663         if (Jump(patchableNotIndexJump).isSet())
664             notIndexJump = CodeLocationJump(patchBuffer.locationOf(patchableNotIndexJump));
665         CodeLocationJump badTypeJump = CodeLocationJump(patchBuffer.locationOf(byValCompilationInfo.badTypeJump));
666         CodeLocationLabel doneTarget = patchBuffer.locationOf(byValCompilationInfo.doneTarget);
667         CodeLocationLabel nextHotPathTarget = patchBuffer.locationOf(byValCompilationInfo.nextHotPathTarget);
668         CodeLocationLabel slowPathTarget = patchBuffer.locationOf(byValCompilationInfo.slowPathTarget);
669         CodeLocationCall returnAddress = patchBuffer.locationOf(byValCompilationInfo.returnAddress);
670
671         *byValCompilationInfo.byValInfo = ByValInfo(
672             byValCompilationInfo.bytecodeIndex,
673             notIndexJump,
674             badTypeJump,
675             byValCompilationInfo.arrayMode,
676             byValCompilationInfo.arrayProfile,
677             differenceBetweenCodePtr(badTypeJump, doneTarget),
678             differenceBetweenCodePtr(badTypeJump, nextHotPathTarget),
679             differenceBetweenCodePtr(returnAddress, slowPathTarget));
680     }
681     for (unsigned i = 0; i < m_callCompilationInfo.size(); ++i) {
682         CallCompilationInfo& compilationInfo = m_callCompilationInfo[i];
683         CallLinkInfo& info = *compilationInfo.callLinkInfo;
684         info.setCallLocations(patchBuffer.locationOfNearCall(compilationInfo.callReturnLocation),
685             patchBuffer.locationOf(compilationInfo.hotPathBegin),
686             patchBuffer.locationOfNearCall(compilationInfo.hotPathOther));
687     }
688
689     CompactJITCodeMap::Encoder jitCodeMapEncoder;
690     for (unsigned bytecodeOffset = 0; bytecodeOffset < m_labels.size(); ++bytecodeOffset) {
691         if (m_labels[bytecodeOffset].isSet())
692             jitCodeMapEncoder.append(bytecodeOffset, patchBuffer.offsetOf(m_labels[bytecodeOffset]));
693     }
694     m_codeBlock->setJITCodeMap(jitCodeMapEncoder.finish());
695
696     MacroAssemblerCodePtr withArityCheck;
697     if (m_codeBlock->codeType() == FunctionCode)
698         withArityCheck = patchBuffer.locationOf(arityCheck);
699
700     if (Options::dumpDisassembly()) {
701         m_disassembler->dump(patchBuffer);
702         patchBuffer.didAlreadyDisassemble();
703     }
704     if (m_compilation) {
705         m_disassembler->reportToProfiler(m_compilation.get(), patchBuffer);
706         m_vm->m_perBytecodeProfiler->addCompilation(m_compilation);
707     }
708     
709     CodeRef result = FINALIZE_CODE(
710         patchBuffer,
711         ("Baseline JIT code for %s", toCString(CodeBlockWithJITType(m_codeBlock, JITCode::BaselineJIT)).data()));
712     
713     m_vm->machineCodeBytesPerBytecodeWordForBaselineJIT.add(
714         static_cast<double>(result.size()) /
715         static_cast<double>(m_codeBlock->instructions().size()));
716     
717     m_codeBlock->shrinkToFit(CodeBlock::LateShrink);
718     m_codeBlock->setJITCode(
719         adoptRef(new DirectJITCode(result, withArityCheck, JITCode::BaselineJIT)));
720     
721 #if ENABLE(JIT_VERBOSE)
722     dataLogF("JIT generated code for %p at [%p, %p).\n", m_codeBlock, result.executableMemory()->start(), result.executableMemory()->end());
723 #endif
724     
725     return CompilationSuccessful;
726 }
727
728 void JIT::privateCompileExceptionHandlers()
729 {
730     if (!m_exceptionChecksWithCallFrameRollback.empty()) {
731         m_exceptionChecksWithCallFrameRollback.link(this);
732
733         copyCalleeSavesToVMCalleeSavesBuffer();
734
735         // lookupExceptionHandlerFromCallerFrame is passed two arguments, the VM and the exec (the CallFrame*).
736
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(lookupExceptionHandlerFromCallerFrame).value()));
746         jumpToExceptionHandler();
747     }
748
749     if (!m_exceptionChecks.empty()) {
750         m_exceptionChecks.link(this);
751
752         copyCalleeSavesToVMCalleeSavesBuffer();
753
754         // lookupExceptionHandler is passed two arguments, the VM and the exec (the CallFrame*).
755         move(TrustedImmPtr(vm()), GPRInfo::argumentGPR0);
756         move(GPRInfo::callFrameRegister, GPRInfo::argumentGPR1);
757
758 #if CPU(X86)
759         // FIXME: should use the call abstraction, but this is currently in the SpeculativeJIT layer!
760         poke(GPRInfo::argumentGPR0);
761         poke(GPRInfo::argumentGPR1, 1);
762 #endif
763         m_calls.append(CallRecord(call(), std::numeric_limits<unsigned>::max(), FunctionPtr(lookupExceptionHandler).value()));
764         jumpToExceptionHandler();
765     }
766 }
767
768 unsigned JIT::frameRegisterCountFor(CodeBlock* codeBlock)
769 {
770     ASSERT(static_cast<unsigned>(codeBlock->m_numCalleeLocals) == WTF::roundUpToMultipleOf(stackAlignmentRegisters(), static_cast<unsigned>(codeBlock->m_numCalleeLocals)));
771
772     return roundLocalRegisterCountForFramePointerOffset(codeBlock->m_numCalleeLocals + maxFrameExtentForSlowPathCallInRegisters);
773 }
774
775 int JIT::stackPointerOffsetFor(CodeBlock* codeBlock)
776 {
777     return virtualRegisterForLocal(frameRegisterCountFor(codeBlock) - 1).offset();
778 }
779
780 } // namespace JSC
781
782 #endif // ENABLE(JIT)