1 // Copyright 2012 the V8 project authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #if V8_TARGET_ARCH_X64
6
7 #include "src/api/api-arguments.h"
8 #include "src/base/bits-iterator.h"
9 #include "src/base/iterator.h"
10 #include "src/codegen/code-factory.h"
11 // For interpreter_entry_return_pc_offset. TODO(jkummerow): Drop.
12 #include "src/codegen/macro-assembler-inl.h"
13 #include "src/codegen/register-configuration.h"
14 #include "src/codegen/x64/assembler-x64.h"
15 #include "src/deoptimizer/deoptimizer.h"
16 #include "src/execution/frame-constants.h"
17 #include "src/execution/frames.h"
18 #include "src/heap/heap-inl.h"
19 #include "src/logging/counters.h"
20 #include "src/objects/cell.h"
21 #include "src/objects/debug-objects.h"
22 #include "src/objects/foreign.h"
23 #include "src/objects/heap-number.h"
24 #include "src/objects/js-generator.h"
25 #include "src/objects/objects-inl.h"
26 #include "src/objects/smi.h"
27 #include "src/wasm/baseline/liftoff-assembler-defs.h"
28 #include "src/wasm/object-access.h"
29 #include "src/wasm/wasm-constants.h"
30 #include "src/wasm/wasm-linkage.h"
31 #include "src/wasm/wasm-objects.h"
32
33 namespace v8 {
34 namespace internal {
35
36 #define __ ACCESS_MASM(masm)
37
Generate_Adaptor(MacroAssembler * masm,Address address)38 void Builtins::Generate_Adaptor(MacroAssembler* masm, Address address) {
39 __ LoadAddress(kJavaScriptCallExtraArg1Register,
40 ExternalReference::Create(address));
41 __ Jump(BUILTIN_CODE(masm->isolate(), AdaptorWithBuiltinExitFrame),
42 RelocInfo::CODE_TARGET);
43 }
44
GenerateTailCallToReturnedCode(MacroAssembler * masm,Runtime::FunctionId function_id)45 static void GenerateTailCallToReturnedCode(MacroAssembler* masm,
46 Runtime::FunctionId function_id) {
47 // ----------- S t a t e -------------
48 // -- rax : actual argument count
49 // -- rdx : new target (preserved for callee)
50 // -- rdi : target function (preserved for callee)
51 // -----------------------------------
52 {
53 FrameScope scope(masm, StackFrame::INTERNAL);
54 // Push a copy of the target function, the new target and the actual
55 // argument count.
56 __ Push(kJavaScriptCallTargetRegister);
57 __ Push(kJavaScriptCallNewTargetRegister);
58 __ SmiTag(kJavaScriptCallArgCountRegister);
59 __ Push(kJavaScriptCallArgCountRegister);
60 // Function is also the parameter to the runtime call.
61 __ Push(kJavaScriptCallTargetRegister);
62
63 __ CallRuntime(function_id, 1);
64 __ movq(rcx, rax);
65
66 // Restore target function, new target and actual argument count.
67 __ Pop(kJavaScriptCallArgCountRegister);
68 __ SmiUntag(kJavaScriptCallArgCountRegister);
69 __ Pop(kJavaScriptCallNewTargetRegister);
70 __ Pop(kJavaScriptCallTargetRegister);
71 }
72 static_assert(kJavaScriptCallCodeStartRegister == rcx, "ABI mismatch");
73 __ JumpCodeObject(rcx);
74 }
75
76 namespace {
77
Generate_JSBuiltinsConstructStubHelper(MacroAssembler * masm)78 void Generate_JSBuiltinsConstructStubHelper(MacroAssembler* masm) {
79 // ----------- S t a t e -------------
80 // -- rax: number of arguments
81 // -- rdi: constructor function
82 // -- rdx: new target
83 // -- rsi: context
84 // -----------------------------------
85
86 Label stack_overflow;
87 __ StackOverflowCheck(rax, rcx, &stack_overflow, Label::kFar);
88
89 // Enter a construct frame.
90 {
91 FrameScope scope(masm, StackFrame::CONSTRUCT);
92
93 // Preserve the incoming parameters on the stack.
94 __ SmiTag(rcx, rax);
95 __ Push(rsi);
96 __ Push(rcx);
97
98 // TODO(victorgomes): When the arguments adaptor is completely removed, we
99 // should get the formal parameter count and copy the arguments in its
100 // correct position (including any undefined), instead of delaying this to
101 // InvokeFunction.
102
103 // Set up pointer to first argument (skip receiver).
104 __ leaq(rbx, Operand(rbp, StandardFrameConstants::kCallerSPOffset +
105 kSystemPointerSize));
106 // Copy arguments to the expression stack.
107 __ PushArray(rbx, rax, rcx);
108 // The receiver for the builtin/api call.
109 __ PushRoot(RootIndex::kTheHoleValue);
110
111 // Call the function.
112 // rax: number of arguments (untagged)
113 // rdi: constructor function
114 // rdx: new target
115 __ InvokeFunction(rdi, rdx, rax, CALL_FUNCTION);
116
117 // Restore smi-tagged arguments count from the frame.
118 __ movq(rbx, Operand(rbp, ConstructFrameConstants::kLengthOffset));
119
120 // Leave construct frame.
121 }
122
123 // Remove caller arguments from the stack and return.
124 __ PopReturnAddressTo(rcx);
125 SmiIndex index = masm->SmiToIndex(rbx, rbx, kSystemPointerSizeLog2);
126 __ leaq(rsp, Operand(rsp, index.reg, index.scale, 1 * kSystemPointerSize));
127 __ PushReturnAddressFrom(rcx);
128
129 __ ret(0);
130
131 __ bind(&stack_overflow);
132 {
133 FrameScope scope(masm, StackFrame::INTERNAL);
134 __ CallRuntime(Runtime::kThrowStackOverflow);
135 __ int3(); // This should be unreachable.
136 }
137 }
138
139 } // namespace
140
141 // The construct stub for ES5 constructor functions and ES6 class constructors.
Generate_JSConstructStubGeneric(MacroAssembler * masm)142 void Builtins::Generate_JSConstructStubGeneric(MacroAssembler* masm) {
143 // ----------- S t a t e -------------
144 // -- rax: number of arguments (untagged)
145 // -- rdi: constructor function
146 // -- rdx: new target
147 // -- rsi: context
148 // -- sp[...]: constructor arguments
149 // -----------------------------------
150
151 FrameScope scope(masm, StackFrame::MANUAL);
152 // Enter a construct frame.
153 __ EnterFrame(StackFrame::CONSTRUCT);
154 Label post_instantiation_deopt_entry, not_create_implicit_receiver;
155
156 // Preserve the incoming parameters on the stack.
157 __ SmiTag(rcx, rax);
158 __ Push(rsi);
159 __ Push(rcx);
160 __ Push(rdi);
161 __ PushRoot(RootIndex::kTheHoleValue);
162 __ Push(rdx);
163
164 // ----------- S t a t e -------------
165 // -- sp[0*kSystemPointerSize]: new target
166 // -- sp[1*kSystemPointerSize]: padding
167 // -- rdi and sp[2*kSystemPointerSize]: constructor function
168 // -- sp[3*kSystemPointerSize]: argument count
169 // -- sp[4*kSystemPointerSize]: context
170 // -----------------------------------
171
172 __ LoadTaggedPointerField(
173 rbx, FieldOperand(rdi, JSFunction::kSharedFunctionInfoOffset));
174 __ movl(rbx, FieldOperand(rbx, SharedFunctionInfo::kFlagsOffset));
175 __ DecodeField<SharedFunctionInfo::FunctionKindBits>(rbx);
176 __ JumpIfIsInRange(rbx, kDefaultDerivedConstructor, kDerivedConstructor,
177 ¬_create_implicit_receiver, Label::kNear);
178
179 // If not derived class constructor: Allocate the new receiver object.
180 __ IncrementCounter(masm->isolate()->counters()->constructed_objects(), 1);
181 __ Call(BUILTIN_CODE(masm->isolate(), FastNewObject), RelocInfo::CODE_TARGET);
182 __ jmp(&post_instantiation_deopt_entry, Label::kNear);
183
184 // Else: use TheHoleValue as receiver for constructor call
185 __ bind(¬_create_implicit_receiver);
186 __ LoadRoot(rax, RootIndex::kTheHoleValue);
187
188 // ----------- S t a t e -------------
189 // -- rax implicit receiver
190 // -- Slot 4 / sp[0*kSystemPointerSize] new target
191 // -- Slot 3 / sp[1*kSystemPointerSize] padding
192 // -- Slot 2 / sp[2*kSystemPointerSize] constructor function
193 // -- Slot 1 / sp[3*kSystemPointerSize] number of arguments (tagged)
194 // -- Slot 0 / sp[4*kSystemPointerSize] context
195 // -----------------------------------
196 // Deoptimizer enters here.
197 masm->isolate()->heap()->SetConstructStubCreateDeoptPCOffset(
198 masm->pc_offset());
199 __ bind(&post_instantiation_deopt_entry);
200
201 // Restore new target.
202 __ Pop(rdx);
203
204 // Push the allocated receiver to the stack.
205 __ Push(rax);
206
207 // We need two copies because we may have to return the original one
208 // and the calling conventions dictate that the called function pops the
209 // receiver. The second copy is pushed after the arguments, we saved in r8
210 // since rax needs to store the number of arguments before
211 // InvokingFunction.
212 __ movq(r8, rax);
213
214 // Set up pointer to first argument (skip receiver).
215 __ leaq(rbx, Operand(rbp, StandardFrameConstants::kCallerSPOffset +
216 kSystemPointerSize));
217
218 // Restore constructor function and argument count.
219 __ movq(rdi, Operand(rbp, ConstructFrameConstants::kConstructorOffset));
220 __ SmiUntag(rax, Operand(rbp, ConstructFrameConstants::kLengthOffset));
221
222 // Check if we have enough stack space to push all arguments.
223 // Argument count in rax. Clobbers rcx.
224 Label stack_overflow;
225 __ StackOverflowCheck(rax, rcx, &stack_overflow);
226
227 // TODO(victorgomes): When the arguments adaptor is completely removed, we
228 // should get the formal parameter count and copy the arguments in its
229 // correct position (including any undefined), instead of delaying this to
230 // InvokeFunction.
231
232 // Copy arguments to the expression stack.
233 __ PushArray(rbx, rax, rcx);
234
235 // Push implicit receiver.
236 __ Push(r8);
237
238 // Call the function.
239 __ InvokeFunction(rdi, rdx, rax, CALL_FUNCTION);
240
241 // ----------- S t a t e -------------
242 // -- rax constructor result
243 // -- sp[0*kSystemPointerSize] implicit receiver
244 // -- sp[1*kSystemPointerSize] padding
245 // -- sp[2*kSystemPointerSize] constructor function
246 // -- sp[3*kSystemPointerSize] number of arguments
247 // -- sp[4*kSystemPointerSize] context
248 // -----------------------------------
249
250 // Store offset of return address for deoptimizer.
251 masm->isolate()->heap()->SetConstructStubInvokeDeoptPCOffset(
252 masm->pc_offset());
253
254 // If the result is an object (in the ECMA sense), we should get rid
255 // of the receiver and use the result; see ECMA-262 section 13.2.2-7
256 // on page 74.
257 Label use_receiver, do_throw, leave_and_return, check_result;
258
259 // If the result is undefined, we'll use the implicit receiver. Otherwise we
260 // do a smi check and fall through to check if the return value is a valid
261 // receiver.
262 __ JumpIfNotRoot(rax, RootIndex::kUndefinedValue, &check_result,
263 Label::kNear);
264
265 // Throw away the result of the constructor invocation and use the
266 // on-stack receiver as the result.
267 __ bind(&use_receiver);
268 __ movq(rax, Operand(rsp, 0 * kSystemPointerSize));
269 __ JumpIfRoot(rax, RootIndex::kTheHoleValue, &do_throw, Label::kNear);
270
271 __ bind(&leave_and_return);
272 // Restore the arguments count.
273 __ movq(rbx, Operand(rbp, ConstructFrameConstants::kLengthOffset));
274 __ LeaveFrame(StackFrame::CONSTRUCT);
275 // Remove caller arguments from the stack and return.
276 __ PopReturnAddressTo(rcx);
277 SmiIndex index = masm->SmiToIndex(rbx, rbx, kSystemPointerSizeLog2);
278 __ leaq(rsp, Operand(rsp, index.reg, index.scale, 1 * kSystemPointerSize));
279 __ PushReturnAddressFrom(rcx);
280 __ ret(0);
281
282 // If the result is a smi, it is *not* an object in the ECMA sense.
283 __ bind(&check_result);
284 __ JumpIfSmi(rax, &use_receiver, Label::kNear);
285
286 // If the type of the result (stored in its map) is less than
287 // FIRST_JS_RECEIVER_TYPE, it is not an object in the ECMA sense.
288 STATIC_ASSERT(LAST_JS_RECEIVER_TYPE == LAST_TYPE);
289 __ CmpObjectType(rax, FIRST_JS_RECEIVER_TYPE, rcx);
290 __ j(above_equal, &leave_and_return, Label::kNear);
291 __ jmp(&use_receiver);
292
293 __ bind(&do_throw);
294 // Restore context from the frame.
295 __ movq(rsi, Operand(rbp, ConstructFrameConstants::kContextOffset));
296 __ CallRuntime(Runtime::kThrowConstructorReturnedNonObject);
297 // We don't return here.
298 __ int3();
299
300 __ bind(&stack_overflow);
301 // Restore the context from the frame.
302 __ movq(rsi, Operand(rbp, ConstructFrameConstants::kContextOffset));
303 __ CallRuntime(Runtime::kThrowStackOverflow);
304 // This should be unreachable.
305 __ int3();
306 }
307
Generate_JSBuiltinsConstructStub(MacroAssembler * masm)308 void Builtins::Generate_JSBuiltinsConstructStub(MacroAssembler* masm) {
309 Generate_JSBuiltinsConstructStubHelper(masm);
310 }
311
Generate_ConstructedNonConstructable(MacroAssembler * masm)312 void Builtins::Generate_ConstructedNonConstructable(MacroAssembler* masm) {
313 FrameScope scope(masm, StackFrame::INTERNAL);
314 __ Push(rdi);
315 __ CallRuntime(Runtime::kThrowConstructedNonConstructable);
316 }
317
318 namespace {
319
320 // Called with the native C calling convention. The corresponding function
321 // signature is either:
322 // using JSEntryFunction = GeneratedCode<Address(
323 // Address root_register_value, Address new_target, Address target,
324 // Address receiver, intptr_t argc, Address** argv)>;
325 // or
326 // using JSEntryFunction = GeneratedCode<Address(
327 // Address root_register_value, MicrotaskQueue* microtask_queue)>;
Generate_JSEntryVariant(MacroAssembler * masm,StackFrame::Type type,Builtins::Name entry_trampoline)328 void Generate_JSEntryVariant(MacroAssembler* masm, StackFrame::Type type,
329 Builtins::Name entry_trampoline) {
330 Label invoke, handler_entry, exit;
331 Label not_outermost_js, not_outermost_js_2;
332
333 { // NOLINT. Scope block confuses linter.
334 NoRootArrayScope uninitialized_root_register(masm);
335 // Set up frame.
336 __ pushq(rbp);
337 __ movq(rbp, rsp);
338
339 // Push the stack frame type.
340 __ Push(Immediate(StackFrame::TypeToMarker(type)));
341 // Reserve a slot for the context. It is filled after the root register has
342 // been set up.
343 __ AllocateStackSpace(kSystemPointerSize);
344 // Save callee-saved registers (X64/X32/Win64 calling conventions).
345 __ pushq(r12);
346 __ pushq(r13);
347 __ pushq(r14);
348 __ pushq(r15);
349 #ifdef V8_TARGET_OS_WIN
350 __ pushq(rdi); // Only callee save in Win64 ABI, argument in AMD64 ABI.
351 __ pushq(rsi); // Only callee save in Win64 ABI, argument in AMD64 ABI.
352 #endif
353 __ pushq(rbx);
354
355 #ifdef V8_TARGET_OS_WIN
356 // On Win64 XMM6-XMM15 are callee-save.
357 __ AllocateStackSpace(EntryFrameConstants::kXMMRegistersBlockSize);
358 __ movdqu(Operand(rsp, EntryFrameConstants::kXMMRegisterSize * 0), xmm6);
359 __ movdqu(Operand(rsp, EntryFrameConstants::kXMMRegisterSize * 1), xmm7);
360 __ movdqu(Operand(rsp, EntryFrameConstants::kXMMRegisterSize * 2), xmm8);
361 __ movdqu(Operand(rsp, EntryFrameConstants::kXMMRegisterSize * 3), xmm9);
362 __ movdqu(Operand(rsp, EntryFrameConstants::kXMMRegisterSize * 4), xmm10);
363 __ movdqu(Operand(rsp, EntryFrameConstants::kXMMRegisterSize * 5), xmm11);
364 __ movdqu(Operand(rsp, EntryFrameConstants::kXMMRegisterSize * 6), xmm12);
365 __ movdqu(Operand(rsp, EntryFrameConstants::kXMMRegisterSize * 7), xmm13);
366 __ movdqu(Operand(rsp, EntryFrameConstants::kXMMRegisterSize * 8), xmm14);
367 __ movdqu(Operand(rsp, EntryFrameConstants::kXMMRegisterSize * 9), xmm15);
368 STATIC_ASSERT(EntryFrameConstants::kCalleeSaveXMMRegisters == 10);
369 STATIC_ASSERT(EntryFrameConstants::kXMMRegistersBlockSize ==
370 EntryFrameConstants::kXMMRegisterSize *
371 EntryFrameConstants::kCalleeSaveXMMRegisters);
372 #endif
373
374 // Initialize the root register.
375 // C calling convention. The first argument is passed in arg_reg_1.
376 __ movq(kRootRegister, arg_reg_1);
377 }
378
379 // Save copies of the top frame descriptor on the stack.
380 ExternalReference c_entry_fp = ExternalReference::Create(
381 IsolateAddressId::kCEntryFPAddress, masm->isolate());
382 {
383 Operand c_entry_fp_operand = masm->ExternalReferenceAsOperand(c_entry_fp);
384 __ Push(c_entry_fp_operand);
385 }
386
387 // Store the context address in the previously-reserved slot.
388 ExternalReference context_address = ExternalReference::Create(
389 IsolateAddressId::kContextAddress, masm->isolate());
390 __ Load(kScratchRegister, context_address);
391 static constexpr int kOffsetToContextSlot = -2 * kSystemPointerSize;
392 __ movq(Operand(rbp, kOffsetToContextSlot), kScratchRegister);
393
394 // If this is the outermost JS call, set js_entry_sp value.
395 ExternalReference js_entry_sp = ExternalReference::Create(
396 IsolateAddressId::kJSEntrySPAddress, masm->isolate());
397 __ Load(rax, js_entry_sp);
398 __ testq(rax, rax);
399 __ j(not_zero, ¬_outermost_js);
400 __ Push(Immediate(StackFrame::OUTERMOST_JSENTRY_FRAME));
401 __ movq(rax, rbp);
402 __ Store(js_entry_sp, rax);
403 Label cont;
404 __ jmp(&cont);
405 __ bind(¬_outermost_js);
406 __ Push(Immediate(StackFrame::INNER_JSENTRY_FRAME));
407 __ bind(&cont);
408
409 // Jump to a faked try block that does the invoke, with a faked catch
410 // block that sets the pending exception.
411 __ jmp(&invoke);
412 __ bind(&handler_entry);
413
414 // Store the current pc as the handler offset. It's used later to create the
415 // handler table.
416 masm->isolate()->builtins()->SetJSEntryHandlerOffset(handler_entry.pos());
417
418 // Caught exception: Store result (exception) in the pending exception
419 // field in the JSEnv and return a failure sentinel.
420 ExternalReference pending_exception = ExternalReference::Create(
421 IsolateAddressId::kPendingExceptionAddress, masm->isolate());
422 __ Store(pending_exception, rax);
423 __ LoadRoot(rax, RootIndex::kException);
424 __ jmp(&exit);
425
426 // Invoke: Link this frame into the handler chain.
427 __ bind(&invoke);
428 __ PushStackHandler();
429
430 // Invoke the function by calling through JS entry trampoline builtin and
431 // pop the faked function when we return.
432 Handle<Code> trampoline_code =
433 masm->isolate()->builtins()->builtin_handle(entry_trampoline);
434 __ Call(trampoline_code, RelocInfo::CODE_TARGET);
435
436 // Unlink this frame from the handler chain.
437 __ PopStackHandler();
438
439 __ bind(&exit);
440 // Check if the current stack frame is marked as the outermost JS frame.
441 __ Pop(rbx);
442 __ cmpq(rbx, Immediate(StackFrame::OUTERMOST_JSENTRY_FRAME));
443 __ j(not_equal, ¬_outermost_js_2);
444 __ Move(kScratchRegister, js_entry_sp);
445 __ movq(Operand(kScratchRegister, 0), Immediate(0));
446 __ bind(¬_outermost_js_2);
447
448 // Restore the top frame descriptor from the stack.
449 {
450 Operand c_entry_fp_operand = masm->ExternalReferenceAsOperand(c_entry_fp);
451 __ Pop(c_entry_fp_operand);
452 }
453
454 // Restore callee-saved registers (X64 conventions).
455 #ifdef V8_TARGET_OS_WIN
456 // On Win64 XMM6-XMM15 are callee-save
457 __ movdqu(xmm6, Operand(rsp, EntryFrameConstants::kXMMRegisterSize * 0));
458 __ movdqu(xmm7, Operand(rsp, EntryFrameConstants::kXMMRegisterSize * 1));
459 __ movdqu(xmm8, Operand(rsp, EntryFrameConstants::kXMMRegisterSize * 2));
460 __ movdqu(xmm9, Operand(rsp, EntryFrameConstants::kXMMRegisterSize * 3));
461 __ movdqu(xmm10, Operand(rsp, EntryFrameConstants::kXMMRegisterSize * 4));
462 __ movdqu(xmm11, Operand(rsp, EntryFrameConstants::kXMMRegisterSize * 5));
463 __ movdqu(xmm12, Operand(rsp, EntryFrameConstants::kXMMRegisterSize * 6));
464 __ movdqu(xmm13, Operand(rsp, EntryFrameConstants::kXMMRegisterSize * 7));
465 __ movdqu(xmm14, Operand(rsp, EntryFrameConstants::kXMMRegisterSize * 8));
466 __ movdqu(xmm15, Operand(rsp, EntryFrameConstants::kXMMRegisterSize * 9));
467 __ addq(rsp, Immediate(EntryFrameConstants::kXMMRegistersBlockSize));
468 #endif
469
470 __ popq(rbx);
471 #ifdef V8_TARGET_OS_WIN
472 // Callee save on in Win64 ABI, arguments/volatile in AMD64 ABI.
473 __ popq(rsi);
474 __ popq(rdi);
475 #endif
476 __ popq(r15);
477 __ popq(r14);
478 __ popq(r13);
479 __ popq(r12);
480 __ addq(rsp, Immediate(2 * kSystemPointerSize)); // remove markers
481
482 // Restore frame pointer and return.
483 __ popq(rbp);
484 __ ret(0);
485 }
486
487 } // namespace
488
Generate_JSEntry(MacroAssembler * masm)489 void Builtins::Generate_JSEntry(MacroAssembler* masm) {
490 Generate_JSEntryVariant(masm, StackFrame::ENTRY,
491 Builtins::kJSEntryTrampoline);
492 }
493
Generate_JSConstructEntry(MacroAssembler * masm)494 void Builtins::Generate_JSConstructEntry(MacroAssembler* masm) {
495 Generate_JSEntryVariant(masm, StackFrame::CONSTRUCT_ENTRY,
496 Builtins::kJSConstructEntryTrampoline);
497 }
498
Generate_JSRunMicrotasksEntry(MacroAssembler * masm)499 void Builtins::Generate_JSRunMicrotasksEntry(MacroAssembler* masm) {
500 Generate_JSEntryVariant(masm, StackFrame::ENTRY,
501 Builtins::kRunMicrotasksTrampoline);
502 }
503
Generate_JSEntryTrampolineHelper(MacroAssembler * masm,bool is_construct)504 static void Generate_JSEntryTrampolineHelper(MacroAssembler* masm,
505 bool is_construct) {
506 // Expects six C++ function parameters.
507 // - Address root_register_value
508 // - Address new_target (tagged Object pointer)
509 // - Address function (tagged JSFunction pointer)
510 // - Address receiver (tagged Object pointer)
511 // - intptr_t argc
512 // - Address** argv (pointer to array of tagged Object pointers)
513 // (see Handle::Invoke in execution.cc).
514
515 // Open a C++ scope for the FrameScope.
516 {
517 // Platform specific argument handling. After this, the stack contains
518 // an internal frame and the pushed function and receiver, and
519 // register rax and rbx holds the argument count and argument array,
520 // while rdi holds the function pointer, rsi the context, and rdx the
521 // new.target.
522
523 // MSVC parameters in:
524 // rcx : root_register_value
525 // rdx : new_target
526 // r8 : function
527 // r9 : receiver
528 // [rsp+0x20] : argc
529 // [rsp+0x28] : argv
530 //
531 // GCC parameters in:
532 // rdi : root_register_value
533 // rsi : new_target
534 // rdx : function
535 // rcx : receiver
536 // r8 : argc
537 // r9 : argv
538
539 __ movq(rdi, arg_reg_3);
540 __ Move(rdx, arg_reg_2);
541 // rdi : function
542 // rdx : new_target
543
544 // Clear the context before we push it when entering the internal frame.
545 __ Set(rsi, 0);
546
547 // Enter an internal frame.
548 FrameScope scope(masm, StackFrame::INTERNAL);
549
550 // Setup the context (we need to use the caller context from the isolate).
551 ExternalReference context_address = ExternalReference::Create(
552 IsolateAddressId::kContextAddress, masm->isolate());
553 __ movq(rsi, masm->ExternalReferenceAsOperand(context_address));
554
555 // Push the function onto the stack.
556 __ Push(rdi);
557
558 #ifdef V8_TARGET_OS_WIN
559 // Load the previous frame pointer to access C arguments on stack
560 __ movq(kScratchRegister, Operand(rbp, 0));
561 // Load the number of arguments and setup pointer to the arguments.
562 __ movq(rax, Operand(kScratchRegister, EntryFrameConstants::kArgcOffset));
563 __ movq(rbx, Operand(kScratchRegister, EntryFrameConstants::kArgvOffset));
564 #else // V8_TARGET_OS_WIN
565 // Load the number of arguments and setup pointer to the arguments.
566 __ movq(rax, r8);
567 __ movq(rbx, r9);
568 __ movq(r9, arg_reg_4); // Temporarily saving the receiver.
569 #endif // V8_TARGET_OS_WIN
570
571 // Current stack contents:
572 // [rsp + kSystemPointerSize] : Internal frame
573 // [rsp] : function
574 // Current register contents:
575 // rax : argc
576 // rbx : argv
577 // rsi : context
578 // rdi : function
579 // rdx : new.target
580 // r9 : receiver
581
582 // Check if we have enough stack space to push all arguments.
583 // Argument count in rax. Clobbers rcx.
584 Label enough_stack_space, stack_overflow;
585 __ StackOverflowCheck(rax, rcx, &stack_overflow, Label::kNear);
586 __ jmp(&enough_stack_space, Label::kNear);
587
588 __ bind(&stack_overflow);
589 __ CallRuntime(Runtime::kThrowStackOverflow);
590 // This should be unreachable.
591 __ int3();
592
593 __ bind(&enough_stack_space);
594
595 // Copy arguments to the stack in a loop.
596 // Register rbx points to array of pointers to handle locations.
597 // Push the values of these handles.
598 Label loop, entry;
599 __ movq(rcx, rax);
600 __ jmp(&entry, Label::kNear);
601 __ bind(&loop);
602 __ movq(kScratchRegister, Operand(rbx, rcx, times_system_pointer_size, 0));
603 __ Push(Operand(kScratchRegister, 0)); // dereference handle
604 __ bind(&entry);
605 __ decq(rcx);
606 __ j(greater_equal, &loop, Label::kNear);
607
608 // Push the receiver.
609 __ Push(r9);
610
611 // Invoke the builtin code.
612 Handle<Code> builtin = is_construct
613 ? BUILTIN_CODE(masm->isolate(), Construct)
614 : masm->isolate()->builtins()->Call();
615 __ Call(builtin, RelocInfo::CODE_TARGET);
616
617 // Exit the internal frame. Notice that this also removes the empty
618 // context and the function left on the stack by the code
619 // invocation.
620 }
621
622 __ ret(0);
623 }
624
Generate_JSEntryTrampoline(MacroAssembler * masm)625 void Builtins::Generate_JSEntryTrampoline(MacroAssembler* masm) {
626 Generate_JSEntryTrampolineHelper(masm, false);
627 }
628
Generate_JSConstructEntryTrampoline(MacroAssembler * masm)629 void Builtins::Generate_JSConstructEntryTrampoline(MacroAssembler* masm) {
630 Generate_JSEntryTrampolineHelper(masm, true);
631 }
632
Generate_RunMicrotasksTrampoline(MacroAssembler * masm)633 void Builtins::Generate_RunMicrotasksTrampoline(MacroAssembler* masm) {
634 // arg_reg_2: microtask_queue
635 __ movq(RunMicrotasksDescriptor::MicrotaskQueueRegister(), arg_reg_2);
636 __ Jump(BUILTIN_CODE(masm->isolate(), RunMicrotasks), RelocInfo::CODE_TARGET);
637 }
638
GetSharedFunctionInfoBytecode(MacroAssembler * masm,Register sfi_data,Register scratch1)639 static void GetSharedFunctionInfoBytecode(MacroAssembler* masm,
640 Register sfi_data,
641 Register scratch1) {
642 Label done;
643
644 __ CmpObjectType(sfi_data, INTERPRETER_DATA_TYPE, scratch1);
645 __ j(not_equal, &done, Label::kNear);
646
647 __ LoadTaggedPointerField(
648 sfi_data, FieldOperand(sfi_data, InterpreterData::kBytecodeArrayOffset));
649
650 __ bind(&done);
651 }
652
653 // static
Generate_ResumeGeneratorTrampoline(MacroAssembler * masm)654 void Builtins::Generate_ResumeGeneratorTrampoline(MacroAssembler* masm) {
655 // ----------- S t a t e -------------
656 // -- rax : the value to pass to the generator
657 // -- rdx : the JSGeneratorObject to resume
658 // -- rsp[0] : return address
659 // -----------------------------------
660 __ AssertGeneratorObject(rdx);
661
662 // Store input value into generator object.
663 __ StoreTaggedField(
664 FieldOperand(rdx, JSGeneratorObject::kInputOrDebugPosOffset), rax);
665 __ RecordWriteField(rdx, JSGeneratorObject::kInputOrDebugPosOffset, rax, rcx,
666 kDontSaveFPRegs);
667
668 Register decompr_scratch1 = COMPRESS_POINTERS_BOOL ? r11 : no_reg;
669
670 // Load suspended function and context.
671 __ LoadTaggedPointerField(
672 rdi, FieldOperand(rdx, JSGeneratorObject::kFunctionOffset));
673 __ LoadTaggedPointerField(rsi, FieldOperand(rdi, JSFunction::kContextOffset));
674
675 // Flood function if we are stepping.
676 Label prepare_step_in_if_stepping, prepare_step_in_suspended_generator;
677 Label stepping_prepared;
678 ExternalReference debug_hook =
679 ExternalReference::debug_hook_on_function_call_address(masm->isolate());
680 Operand debug_hook_operand = masm->ExternalReferenceAsOperand(debug_hook);
681 __ cmpb(debug_hook_operand, Immediate(0));
682 __ j(not_equal, &prepare_step_in_if_stepping);
683
684 // Flood function if we need to continue stepping in the suspended generator.
685 ExternalReference debug_suspended_generator =
686 ExternalReference::debug_suspended_generator_address(masm->isolate());
687 Operand debug_suspended_generator_operand =
688 masm->ExternalReferenceAsOperand(debug_suspended_generator);
689 __ cmpq(rdx, debug_suspended_generator_operand);
690 __ j(equal, &prepare_step_in_suspended_generator);
691 __ bind(&stepping_prepared);
692
693 // Check the stack for overflow. We are not trying to catch interruptions
694 // (i.e. debug break and preemption) here, so check the "real stack limit".
695 Label stack_overflow;
696 __ cmpq(rsp, __ StackLimitAsOperand(StackLimitKind::kRealStackLimit));
697 __ j(below, &stack_overflow);
698
699 // Pop return address.
700 __ PopReturnAddressTo(rax);
701
702 // ----------- S t a t e -------------
703 // -- rax : return address
704 // -- rdx : the JSGeneratorObject to resume
705 // -- rdi : generator function
706 // -- rsi : generator context
707 // -----------------------------------
708
709 // Copy the function arguments from the generator object's register file.
710 __ LoadTaggedPointerField(
711 rcx, FieldOperand(rdi, JSFunction::kSharedFunctionInfoOffset));
712 __ movzxwq(
713 rcx, FieldOperand(rcx, SharedFunctionInfo::kFormalParameterCountOffset));
714
715 __ LoadTaggedPointerField(
716 rbx, FieldOperand(rdx, JSGeneratorObject::kParametersAndRegistersOffset));
717
718 {
719 {
720 Label done_loop, loop;
721 __ movq(r9, rcx);
722
723 __ bind(&loop);
724 __ decq(r9);
725 __ j(less, &done_loop, Label::kNear);
726 __ PushTaggedAnyField(
727 FieldOperand(rbx, r9, times_tagged_size, FixedArray::kHeaderSize),
728 decompr_scratch1);
729 __ jmp(&loop);
730
731 __ bind(&done_loop);
732 }
733
734 // Push the receiver.
735 __ PushTaggedPointerField(
736 FieldOperand(rdx, JSGeneratorObject::kReceiverOffset),
737 decompr_scratch1);
738 }
739
740 // Underlying function needs to have bytecode available.
741 if (FLAG_debug_code) {
742 __ LoadTaggedPointerField(
743 rcx, FieldOperand(rdi, JSFunction::kSharedFunctionInfoOffset));
744 __ LoadTaggedPointerField(
745 rcx, FieldOperand(rcx, SharedFunctionInfo::kFunctionDataOffset));
746 GetSharedFunctionInfoBytecode(masm, rcx, kScratchRegister);
747 __ CmpObjectType(rcx, BYTECODE_ARRAY_TYPE, rcx);
748 __ Assert(equal, AbortReason::kMissingBytecodeArray);
749 }
750
751 // Resume (Ignition/TurboFan) generator object.
752 {
753 __ PushReturnAddressFrom(rax);
754 __ LoadTaggedPointerField(
755 rax, FieldOperand(rdi, JSFunction::kSharedFunctionInfoOffset));
756 __ movzxwq(rax, FieldOperand(
757 rax, SharedFunctionInfo::kFormalParameterCountOffset));
758 // We abuse new.target both to indicate that this is a resume call and to
759 // pass in the generator object. In ordinary calls, new.target is always
760 // undefined because generator functions are non-constructable.
761 static_assert(kJavaScriptCallCodeStartRegister == rcx, "ABI mismatch");
762 __ LoadTaggedPointerField(rcx, FieldOperand(rdi, JSFunction::kCodeOffset));
763 __ JumpCodeObject(rcx);
764 }
765
766 __ bind(&prepare_step_in_if_stepping);
767 {
768 FrameScope scope(masm, StackFrame::INTERNAL);
769 __ Push(rdx);
770 __ Push(rdi);
771 // Push hole as receiver since we do not use it for stepping.
772 __ PushRoot(RootIndex::kTheHoleValue);
773 __ CallRuntime(Runtime::kDebugOnFunctionCall);
774 __ Pop(rdx);
775 __ LoadTaggedPointerField(
776 rdi, FieldOperand(rdx, JSGeneratorObject::kFunctionOffset));
777 }
778 __ jmp(&stepping_prepared);
779
780 __ bind(&prepare_step_in_suspended_generator);
781 {
782 FrameScope scope(masm, StackFrame::INTERNAL);
783 __ Push(rdx);
784 __ CallRuntime(Runtime::kDebugPrepareStepInSuspendedGenerator);
785 __ Pop(rdx);
786 __ LoadTaggedPointerField(
787 rdi, FieldOperand(rdx, JSGeneratorObject::kFunctionOffset));
788 }
789 __ jmp(&stepping_prepared);
790
791 __ bind(&stack_overflow);
792 {
793 FrameScope scope(masm, StackFrame::INTERNAL);
794 __ CallRuntime(Runtime::kThrowStackOverflow);
795 __ int3(); // This should be unreachable.
796 }
797 }
798
799 // TODO(juliana): if we remove the code below then we don't need all
800 // the parameters.
ReplaceClosureCodeWithOptimizedCode(MacroAssembler * masm,Register optimized_code,Register closure,Register scratch1,Register scratch2)801 static void ReplaceClosureCodeWithOptimizedCode(MacroAssembler* masm,
802 Register optimized_code,
803 Register closure,
804 Register scratch1,
805 Register scratch2) {
806 // Store the optimized code in the closure.
807 __ StoreTaggedField(FieldOperand(closure, JSFunction::kCodeOffset),
808 optimized_code);
809 __ movq(scratch1, optimized_code); // Write barrier clobbers scratch1 below.
810 __ RecordWriteField(closure, JSFunction::kCodeOffset, scratch1, scratch2,
811 kDontSaveFPRegs, OMIT_REMEMBERED_SET, OMIT_SMI_CHECK);
812 }
813
LeaveInterpreterFrame(MacroAssembler * masm,Register scratch1,Register scratch2)814 static void LeaveInterpreterFrame(MacroAssembler* masm, Register scratch1,
815 Register scratch2) {
816 Register params_size = scratch1;
817 // Get the size of the formal parameters + receiver (in bytes).
818 __ movq(params_size,
819 Operand(rbp, InterpreterFrameConstants::kBytecodeArrayFromFp));
820 __ movl(params_size,
821 FieldOperand(params_size, BytecodeArray::kParameterSizeOffset));
822
823 #ifdef V8_NO_ARGUMENTS_ADAPTOR
824 Register actual_params_size = scratch2;
825 // Compute the size of the actual parameters + receiver (in bytes).
826 __ movq(actual_params_size,
827 Operand(rbp, StandardFrameConstants::kArgCOffset));
828 __ leaq(actual_params_size,
829 Operand(actual_params_size, times_system_pointer_size,
830 kSystemPointerSize));
831
832 // If actual is bigger than formal, then we should use it to free up the stack
833 // arguments.
834 Label corrected_args_count;
835 __ cmpq(params_size, actual_params_size);
836 __ j(greater_equal, &corrected_args_count, Label::kNear);
837 __ movq(params_size, actual_params_size);
838 __ bind(&corrected_args_count);
839 #endif
840
841 // Leave the frame (also dropping the register file).
842 __ leave();
843
844 // Drop receiver + arguments.
845 Register return_pc = scratch2;
846 __ PopReturnAddressTo(return_pc);
847 __ addq(rsp, params_size);
848 __ PushReturnAddressFrom(return_pc);
849 }
850
851 // Tail-call |function_id| if |actual_marker| == |expected_marker|
TailCallRuntimeIfMarkerEquals(MacroAssembler * masm,Register actual_marker,OptimizationMarker expected_marker,Runtime::FunctionId function_id)852 static void TailCallRuntimeIfMarkerEquals(MacroAssembler* masm,
853 Register actual_marker,
854 OptimizationMarker expected_marker,
855 Runtime::FunctionId function_id) {
856 Label no_match;
857 __ Cmp(actual_marker, expected_marker);
858 __ j(not_equal, &no_match);
859 GenerateTailCallToReturnedCode(masm, function_id);
860 __ bind(&no_match);
861 }
862
MaybeOptimizeCode(MacroAssembler * masm,Register feedback_vector,Register optimization_marker)863 static void MaybeOptimizeCode(MacroAssembler* masm, Register feedback_vector,
864 Register optimization_marker) {
865 // ----------- S t a t e -------------
866 // -- rax : actual argument count
867 // -- rdx : new target (preserved for callee if needed, and caller)
868 // -- rdi : target function (preserved for callee if needed, and caller)
869 // -- feedback vector (preserved for caller if needed)
870 // -- optimization_marker : a Smi containing a non-zero optimization marker.
871 // -----------------------------------
872
873 DCHECK(!AreAliased(feedback_vector, rdx, rdi, optimization_marker));
874
875 // TODO(v8:8394): The logging of first execution will break if
876 // feedback vectors are not allocated. We need to find a different way of
877 // logging these events if required.
878 TailCallRuntimeIfMarkerEquals(masm, optimization_marker,
879 OptimizationMarker::kLogFirstExecution,
880 Runtime::kFunctionFirstExecution);
881 TailCallRuntimeIfMarkerEquals(masm, optimization_marker,
882 OptimizationMarker::kCompileOptimized,
883 Runtime::kCompileOptimized_NotConcurrent);
884 TailCallRuntimeIfMarkerEquals(masm, optimization_marker,
885 OptimizationMarker::kCompileOptimizedConcurrent,
886 Runtime::kCompileOptimized_Concurrent);
887
888 // Marker should be one of LogFirstExecution / CompileOptimized /
889 // CompileOptimizedConcurrent. InOptimizationQueue and None shouldn't reach
890 // here.
891 if (FLAG_debug_code) {
892 __ int3();
893 }
894 }
895
TailCallOptimizedCodeSlot(MacroAssembler * masm,Register optimized_code_entry,Register scratch1,Register scratch2)896 static void TailCallOptimizedCodeSlot(MacroAssembler* masm,
897 Register optimized_code_entry,
898 Register scratch1, Register scratch2) {
899 // ----------- S t a t e -------------
900 // -- rax : actual argument count
901 // -- rdx : new target (preserved for callee if needed, and caller)
902 // -- rdi : target function (preserved for callee if needed, and caller)
903 // -----------------------------------
904
905 Register closure = rdi;
906
907 Label heal_optimized_code_slot;
908
909 // If the optimized code is cleared, go to runtime to update the optimization
910 // marker field.
911 __ LoadWeakValue(optimized_code_entry, &heal_optimized_code_slot);
912
913 // Check if the optimized code is marked for deopt. If it is, call the
914 // runtime to clear it.
915 __ LoadTaggedPointerField(
916 scratch1,
917 FieldOperand(optimized_code_entry, Code::kCodeDataContainerOffset));
918 __ testl(FieldOperand(scratch1, CodeDataContainer::kKindSpecificFlagsOffset),
919 Immediate(1 << Code::kMarkedForDeoptimizationBit));
920 __ j(not_zero, &heal_optimized_code_slot);
921
922 // Optimized code is good, get it into the closure and link the closure into
923 // the optimized functions list, then tail call the optimized code.
924 ReplaceClosureCodeWithOptimizedCode(masm, optimized_code_entry, closure,
925 scratch1, scratch2);
926 static_assert(kJavaScriptCallCodeStartRegister == rcx, "ABI mismatch");
927 __ Move(rcx, optimized_code_entry);
928 __ JumpCodeObject(rcx);
929
930 // Optimized code slot contains deoptimized code or code is cleared and
931 // optimized code marker isn't updated. Evict the code, update the marker
932 // and re-enter the closure's code.
933 __ bind(&heal_optimized_code_slot);
934 GenerateTailCallToReturnedCode(masm, Runtime::kHealOptimizedCodeSlot);
935 }
936
937 // Advance the current bytecode offset. This simulates what all bytecode
938 // handlers do upon completion of the underlying operation. Will bail out to a
939 // label if the bytecode (without prefix) is a return bytecode. Will not advance
940 // the bytecode offset if the current bytecode is a JumpLoop, instead just
941 // re-executing the JumpLoop to jump to the correct bytecode.
AdvanceBytecodeOffsetOrReturn(MacroAssembler * masm,Register bytecode_array,Register bytecode_offset,Register bytecode,Register scratch1,Register scratch2,Label * if_return)942 static void AdvanceBytecodeOffsetOrReturn(MacroAssembler* masm,
943 Register bytecode_array,
944 Register bytecode_offset,
945 Register bytecode, Register scratch1,
946 Register scratch2, Label* if_return) {
947 Register bytecode_size_table = scratch1;
948
949 // The bytecode offset value will be increased by one in wide and extra wide
950 // cases. In the case of having a wide or extra wide JumpLoop bytecode, we
951 // will restore the original bytecode. In order to simplify the code, we have
952 // a backup of it.
953 Register original_bytecode_offset = scratch2;
954 DCHECK(!AreAliased(bytecode_array, bytecode_offset, bytecode,
955 bytecode_size_table, original_bytecode_offset));
956
957 __ movq(original_bytecode_offset, bytecode_offset);
958
959 __ Move(bytecode_size_table,
960 ExternalReference::bytecode_size_table_address());
961
962 // Check if the bytecode is a Wide or ExtraWide prefix bytecode.
963 Label process_bytecode, extra_wide;
964 STATIC_ASSERT(0 == static_cast<int>(interpreter::Bytecode::kWide));
965 STATIC_ASSERT(1 == static_cast<int>(interpreter::Bytecode::kExtraWide));
966 STATIC_ASSERT(2 == static_cast<int>(interpreter::Bytecode::kDebugBreakWide));
967 STATIC_ASSERT(3 ==
968 static_cast<int>(interpreter::Bytecode::kDebugBreakExtraWide));
969 __ cmpb(bytecode, Immediate(0x3));
970 __ j(above, &process_bytecode, Label::kNear);
971 // The code to load the next bytecode is common to both wide and extra wide.
972 // We can hoist them up here. incl has to happen before testb since it
973 // modifies the ZF flag.
974 __ incl(bytecode_offset);
975 __ testb(bytecode, Immediate(0x1));
976 __ movzxbq(bytecode, Operand(bytecode_array, bytecode_offset, times_1, 0));
977 __ j(not_equal, &extra_wide, Label::kNear);
978
979 // Update table to the wide scaled table.
980 __ addq(bytecode_size_table,
981 Immediate(kIntSize * interpreter::Bytecodes::kBytecodeCount));
982 __ jmp(&process_bytecode, Label::kNear);
983
984 __ bind(&extra_wide);
985 // Update table to the extra wide scaled table.
986 __ addq(bytecode_size_table,
987 Immediate(2 * kIntSize * interpreter::Bytecodes::kBytecodeCount));
988
989 __ bind(&process_bytecode);
990
991 // Bailout to the return label if this is a return bytecode.
992 #define JUMP_IF_EQUAL(NAME) \
993 __ cmpb(bytecode, \
994 Immediate(static_cast<int>(interpreter::Bytecode::k##NAME))); \
995 __ j(equal, if_return, Label::kFar);
996 RETURN_BYTECODE_LIST(JUMP_IF_EQUAL)
997 #undef JUMP_IF_EQUAL
998
999 // If this is a JumpLoop, re-execute it to perform the jump to the beginning
1000 // of the loop.
1001 Label end, not_jump_loop;
1002 __ cmpb(bytecode,
1003 Immediate(static_cast<int>(interpreter::Bytecode::kJumpLoop)));
1004 __ j(not_equal, ¬_jump_loop, Label::kNear);
1005 // We need to restore the original bytecode_offset since we might have
1006 // increased it to skip the wide / extra-wide prefix bytecode.
1007 __ movq(bytecode_offset, original_bytecode_offset);
1008 __ jmp(&end, Label::kNear);
1009
1010 __ bind(¬_jump_loop);
1011 // Otherwise, load the size of the current bytecode and advance the offset.
1012 __ addl(bytecode_offset,
1013 Operand(bytecode_size_table, bytecode, times_int_size, 0));
1014
1015 __ bind(&end);
1016 }
1017
1018 // Generate code for entering a JS function with the interpreter.
1019 // On entry to the function the receiver and arguments have been pushed on the
1020 // stack left to right.
1021 //
1022 // The live registers are:
1023 // o rax: actual argument count (not including the receiver)
1024 // o rdi: the JS function object being called
1025 // o rdx: the incoming new target or generator object
1026 // o rsi: our context
1027 // o rbp: the caller's frame pointer
1028 // o rsp: stack pointer (pointing to return address)
1029 //
1030 // The function builds an interpreter frame. See InterpreterFrameConstants in
1031 // frames.h for its layout.
Generate_InterpreterEntryTrampoline(MacroAssembler * masm)1032 void Builtins::Generate_InterpreterEntryTrampoline(MacroAssembler* masm) {
1033 Register closure = rdi;
1034 Register feedback_vector = rbx;
1035
1036 // Get the bytecode array from the function object and load it into
1037 // kInterpreterBytecodeArrayRegister.
1038 __ LoadTaggedPointerField(
1039 kScratchRegister,
1040 FieldOperand(closure, JSFunction::kSharedFunctionInfoOffset));
1041 __ LoadTaggedPointerField(
1042 kInterpreterBytecodeArrayRegister,
1043 FieldOperand(kScratchRegister, SharedFunctionInfo::kFunctionDataOffset));
1044 GetSharedFunctionInfoBytecode(masm, kInterpreterBytecodeArrayRegister,
1045 kScratchRegister);
1046
1047 // The bytecode array could have been flushed from the shared function info,
1048 // if so, call into CompileLazy.
1049 Label compile_lazy;
1050 __ CmpObjectType(kInterpreterBytecodeArrayRegister, BYTECODE_ARRAY_TYPE,
1051 kScratchRegister);
1052 __ j(not_equal, &compile_lazy);
1053
1054 // Load the feedback vector from the closure.
1055 __ LoadTaggedPointerField(
1056 feedback_vector, FieldOperand(closure, JSFunction::kFeedbackCellOffset));
1057 __ LoadTaggedPointerField(feedback_vector,
1058 FieldOperand(feedback_vector, Cell::kValueOffset));
1059
1060 Label push_stack_frame;
1061 // Check if feedback vector is valid. If valid, check for optimized code
1062 // and update invocation count. Otherwise, setup the stack frame.
1063 __ LoadTaggedPointerField(
1064 rcx, FieldOperand(feedback_vector, HeapObject::kMapOffset));
1065 __ CmpInstanceType(rcx, FEEDBACK_VECTOR_TYPE);
1066 __ j(not_equal, &push_stack_frame);
1067
1068 // Read off the optimization state in the feedback vector.
1069 Register optimization_state = rcx;
1070 __ movl(optimization_state,
1071 FieldOperand(feedback_vector, FeedbackVector::kFlagsOffset));
1072
1073 // Check if there is optimized code or a optimization marker that needs to be
1074 // processed.
1075 Label has_optimized_code_or_marker;
1076 __ testl(
1077 optimization_state,
1078 Immediate(FeedbackVector::kHasOptimizedCodeOrCompileOptimizedMarkerMask));
1079 __ j(not_zero, &has_optimized_code_or_marker);
1080
1081 Label not_optimized;
1082 __ bind(¬_optimized);
1083
1084 // Increment invocation count for the function.
1085 __ incl(
1086 FieldOperand(feedback_vector, FeedbackVector::kInvocationCountOffset));
1087
1088 // Open a frame scope to indicate that there is a frame on the stack. The
1089 // MANUAL indicates that the scope shouldn't actually generate code to set up
1090 // the frame (that is done below).
1091 __ bind(&push_stack_frame);
1092 FrameScope frame_scope(masm, StackFrame::MANUAL);
1093 __ pushq(rbp); // Caller's frame pointer.
1094 __ movq(rbp, rsp);
1095 __ Push(kContextRegister); // Callee's context.
1096 __ Push(kJavaScriptCallTargetRegister); // Callee's JS function.
1097 __ Push(kJavaScriptCallArgCountRegister); // Actual argument count.
1098
1099 // Reset code age and the OSR arming. The OSR field and BytecodeAgeOffset are
1100 // 8-bit fields next to each other, so we could just optimize by writing a
1101 // 16-bit. These static asserts guard our assumption is valid.
1102 STATIC_ASSERT(BytecodeArray::kBytecodeAgeOffset ==
1103 BytecodeArray::kOsrNestingLevelOffset + kCharSize);
1104 STATIC_ASSERT(BytecodeArray::kNoAgeBytecodeAge == 0);
1105 __ movw(FieldOperand(kInterpreterBytecodeArrayRegister,
1106 BytecodeArray::kOsrNestingLevelOffset),
1107 Immediate(0));
1108
1109 // Load initial bytecode offset.
1110 __ movq(kInterpreterBytecodeOffsetRegister,
1111 Immediate(BytecodeArray::kHeaderSize - kHeapObjectTag));
1112
1113 // Push bytecode array and Smi tagged bytecode offset.
1114 __ Push(kInterpreterBytecodeArrayRegister);
1115 __ SmiTag(rcx, kInterpreterBytecodeOffsetRegister);
1116 __ Push(rcx);
1117
1118 // Allocate the local and temporary register file on the stack.
1119 Label stack_overflow;
1120 {
1121 // Load frame size from the BytecodeArray object.
1122 __ movl(rcx, FieldOperand(kInterpreterBytecodeArrayRegister,
1123 BytecodeArray::kFrameSizeOffset));
1124
1125 // Do a stack check to ensure we don't go over the limit.
1126 __ movq(rax, rsp);
1127 __ subq(rax, rcx);
1128 __ cmpq(rax, __ StackLimitAsOperand(StackLimitKind::kRealStackLimit));
1129 __ j(below, &stack_overflow);
1130
1131 // If ok, push undefined as the initial value for all register file entries.
1132 Label loop_header;
1133 Label loop_check;
1134 __ LoadRoot(kInterpreterAccumulatorRegister, RootIndex::kUndefinedValue);
1135 __ j(always, &loop_check, Label::kNear);
1136 __ bind(&loop_header);
1137 // TODO(rmcilroy): Consider doing more than one push per loop iteration.
1138 __ Push(kInterpreterAccumulatorRegister);
1139 // Continue loop if not done.
1140 __ bind(&loop_check);
1141 __ subq(rcx, Immediate(kSystemPointerSize));
1142 __ j(greater_equal, &loop_header, Label::kNear);
1143 }
1144
1145 // If the bytecode array has a valid incoming new target or generator object
1146 // register, initialize it with incoming value which was passed in rdx.
1147 Label no_incoming_new_target_or_generator_register;
1148 __ movsxlq(
1149 rcx,
1150 FieldOperand(kInterpreterBytecodeArrayRegister,
1151 BytecodeArray::kIncomingNewTargetOrGeneratorRegisterOffset));
1152 __ testl(rcx, rcx);
1153 __ j(zero, &no_incoming_new_target_or_generator_register, Label::kNear);
1154 __ movq(Operand(rbp, rcx, times_system_pointer_size, 0), rdx);
1155 __ bind(&no_incoming_new_target_or_generator_register);
1156
1157 // Perform interrupt stack check.
1158 // TODO(solanes): Merge with the real stack limit check above.
1159 Label stack_check_interrupt, after_stack_check_interrupt;
1160 __ cmpq(rsp, __ StackLimitAsOperand(StackLimitKind::kInterruptStackLimit));
1161 __ j(below, &stack_check_interrupt);
1162 __ bind(&after_stack_check_interrupt);
1163
1164 // The accumulator is already loaded with undefined.
1165
1166 // Load the dispatch table into a register and dispatch to the bytecode
1167 // handler at the current bytecode offset.
1168 Label do_dispatch;
1169 __ bind(&do_dispatch);
1170 __ Move(
1171 kInterpreterDispatchTableRegister,
1172 ExternalReference::interpreter_dispatch_table_address(masm->isolate()));
1173 __ movzxbq(r11, Operand(kInterpreterBytecodeArrayRegister,
1174 kInterpreterBytecodeOffsetRegister, times_1, 0));
1175 __ movq(kJavaScriptCallCodeStartRegister,
1176 Operand(kInterpreterDispatchTableRegister, r11,
1177 times_system_pointer_size, 0));
1178 __ call(kJavaScriptCallCodeStartRegister);
1179 masm->isolate()->heap()->SetInterpreterEntryReturnPCOffset(masm->pc_offset());
1180
1181 // Any returns to the entry trampoline are either due to the return bytecode
1182 // or the interpreter tail calling a builtin and then a dispatch.
1183
1184 // Get bytecode array and bytecode offset from the stack frame.
1185 __ movq(kInterpreterBytecodeArrayRegister,
1186 Operand(rbp, InterpreterFrameConstants::kBytecodeArrayFromFp));
1187 __ SmiUntag(kInterpreterBytecodeOffsetRegister,
1188 Operand(rbp, InterpreterFrameConstants::kBytecodeOffsetFromFp));
1189
1190 // Either return, or advance to the next bytecode and dispatch.
1191 Label do_return;
1192 __ movzxbq(rbx, Operand(kInterpreterBytecodeArrayRegister,
1193 kInterpreterBytecodeOffsetRegister, times_1, 0));
1194 AdvanceBytecodeOffsetOrReturn(masm, kInterpreterBytecodeArrayRegister,
1195 kInterpreterBytecodeOffsetRegister, rbx, rcx,
1196 r11, &do_return);
1197 __ jmp(&do_dispatch);
1198
1199 __ bind(&do_return);
1200 // The return value is in rax.
1201 LeaveInterpreterFrame(masm, rbx, rcx);
1202 __ ret(0);
1203
1204 __ bind(&stack_check_interrupt);
1205 // Modify the bytecode offset in the stack to be kFunctionEntryBytecodeOffset
1206 // for the call to the StackGuard.
1207 __ Move(Operand(rbp, InterpreterFrameConstants::kBytecodeOffsetFromFp),
1208 Smi::FromInt(BytecodeArray::kHeaderSize - kHeapObjectTag +
1209 kFunctionEntryBytecodeOffset));
1210 __ CallRuntime(Runtime::kStackGuard);
1211
1212 // After the call, restore the bytecode array, bytecode offset and accumulator
1213 // registers again. Also, restore the bytecode offset in the stack to its
1214 // previous value.
1215 __ movq(kInterpreterBytecodeArrayRegister,
1216 Operand(rbp, InterpreterFrameConstants::kBytecodeArrayFromFp));
1217 __ movq(kInterpreterBytecodeOffsetRegister,
1218 Immediate(BytecodeArray::kHeaderSize - kHeapObjectTag));
1219 __ LoadRoot(kInterpreterAccumulatorRegister, RootIndex::kUndefinedValue);
1220
1221 __ SmiTag(rcx, kInterpreterBytecodeArrayRegister);
1222 __ movq(Operand(rbp, InterpreterFrameConstants::kBytecodeOffsetFromFp), rcx);
1223
1224 __ jmp(&after_stack_check_interrupt);
1225
1226 __ bind(&compile_lazy);
1227 GenerateTailCallToReturnedCode(masm, Runtime::kCompileLazy);
1228 __ int3(); // Should not return.
1229
1230 __ bind(&has_optimized_code_or_marker);
1231 Label maybe_has_optimized_code;
1232
1233 __ testl(
1234 optimization_state,
1235 Immediate(FeedbackVector::kHasCompileOptimizedOrLogFirstExecutionMarker));
1236 __ j(zero, &maybe_has_optimized_code);
1237
1238 Register optimization_marker = optimization_state;
1239 __ DecodeField<FeedbackVector::OptimizationMarkerBits>(optimization_marker);
1240 MaybeOptimizeCode(masm, feedback_vector, optimization_marker);
1241 // Fall through if there's no runnable optimized code.
1242 __ jmp(¬_optimized);
1243
1244 __ bind(&maybe_has_optimized_code);
1245 Register optimized_code_entry = optimization_state;
1246 __ LoadAnyTaggedField(
1247 optimized_code_entry,
1248 FieldOperand(feedback_vector, FeedbackVector::kMaybeOptimizedCodeOffset));
1249 TailCallOptimizedCodeSlot(masm, optimized_code_entry, r11, r15);
1250
1251 __ bind(&stack_overflow);
1252 __ CallRuntime(Runtime::kThrowStackOverflow);
1253 __ int3(); // Should not return.
1254 }
1255
Generate_InterpreterPushArgs(MacroAssembler * masm,Register num_args,Register start_address,Register scratch)1256 static void Generate_InterpreterPushArgs(MacroAssembler* masm,
1257 Register num_args,
1258 Register start_address,
1259 Register scratch) {
1260 // Find the argument with lowest address.
1261 __ movq(scratch, num_args);
1262 __ negq(scratch);
1263 __ leaq(start_address,
1264 Operand(start_address, scratch, times_system_pointer_size,
1265 kSystemPointerSize));
1266 // Push the arguments.
1267 __ PushArray(start_address, num_args, scratch,
1268 TurboAssembler::PushArrayOrder::kReverse);
1269 }
1270
1271 // static
Generate_InterpreterPushArgsThenCallImpl(MacroAssembler * masm,ConvertReceiverMode receiver_mode,InterpreterPushArgsMode mode)1272 void Builtins::Generate_InterpreterPushArgsThenCallImpl(
1273 MacroAssembler* masm, ConvertReceiverMode receiver_mode,
1274 InterpreterPushArgsMode mode) {
1275 DCHECK(mode != InterpreterPushArgsMode::kArrayFunction);
1276 // ----------- S t a t e -------------
1277 // -- rax : the number of arguments (not including the receiver)
1278 // -- rbx : the address of the first argument to be pushed. Subsequent
1279 // arguments should be consecutive above this, in the same order as
1280 // they are to be pushed onto the stack.
1281 // -- rdi : the target to call (can be any Object).
1282 // -----------------------------------
1283 Label stack_overflow;
1284
1285 if (mode == InterpreterPushArgsMode::kWithFinalSpread) {
1286 // The spread argument should not be pushed.
1287 __ decl(rax);
1288 }
1289
1290 __ leal(rcx, Operand(rax, 1)); // Add one for receiver.
1291
1292 // Add a stack check before pushing arguments.
1293 __ StackOverflowCheck(rcx, rdx, &stack_overflow);
1294
1295 // Pop return address to allow tail-call after pushing arguments.
1296 __ PopReturnAddressTo(kScratchRegister);
1297
1298 if (receiver_mode == ConvertReceiverMode::kNullOrUndefined) {
1299 // Don't copy receiver.
1300 __ decq(rcx);
1301 }
1302
1303 // rbx and rdx will be modified.
1304 Generate_InterpreterPushArgs(masm, rcx, rbx, rdx);
1305
1306 // Push "undefined" as the receiver arg if we need to.
1307 if (receiver_mode == ConvertReceiverMode::kNullOrUndefined) {
1308 __ PushRoot(RootIndex::kUndefinedValue);
1309 }
1310
1311 if (mode == InterpreterPushArgsMode::kWithFinalSpread) {
1312 // Pass the spread in the register rbx.
1313 // rbx already points to the penultime argument, the spread
1314 // is below that.
1315 __ movq(rbx, Operand(rbx, -kSystemPointerSize));
1316 }
1317
1318 // Call the target.
1319 __ PushReturnAddressFrom(kScratchRegister); // Re-push return address.
1320
1321 if (mode == InterpreterPushArgsMode::kWithFinalSpread) {
1322 __ Jump(BUILTIN_CODE(masm->isolate(), CallWithSpread),
1323 RelocInfo::CODE_TARGET);
1324 } else {
1325 __ Jump(masm->isolate()->builtins()->Call(receiver_mode),
1326 RelocInfo::CODE_TARGET);
1327 }
1328
1329 // Throw stack overflow exception.
1330 __ bind(&stack_overflow);
1331 {
1332 __ TailCallRuntime(Runtime::kThrowStackOverflow);
1333 // This should be unreachable.
1334 __ int3();
1335 }
1336 }
1337
1338 // static
Generate_InterpreterPushArgsThenConstructImpl(MacroAssembler * masm,InterpreterPushArgsMode mode)1339 void Builtins::Generate_InterpreterPushArgsThenConstructImpl(
1340 MacroAssembler* masm, InterpreterPushArgsMode mode) {
1341 // ----------- S t a t e -------------
1342 // -- rax : the number of arguments (not including the receiver)
1343 // -- rdx : the new target (either the same as the constructor or
1344 // the JSFunction on which new was invoked initially)
1345 // -- rdi : the constructor to call (can be any Object)
1346 // -- rbx : the allocation site feedback if available, undefined otherwise
1347 // -- rcx : the address of the first argument to be pushed. Subsequent
1348 // arguments should be consecutive above this, in the same order as
1349 // they are to be pushed onto the stack.
1350 // -----------------------------------
1351 Label stack_overflow;
1352
1353 // Add a stack check before pushing arguments.
1354 __ StackOverflowCheck(rax, r8, &stack_overflow);
1355
1356 // Pop return address to allow tail-call after pushing arguments.
1357 __ PopReturnAddressTo(kScratchRegister);
1358
1359 if (mode == InterpreterPushArgsMode::kWithFinalSpread) {
1360 // The spread argument should not be pushed.
1361 __ decl(rax);
1362 }
1363
1364 // rcx and r8 will be modified.
1365 Generate_InterpreterPushArgs(masm, rax, rcx, r8);
1366
1367 // Push slot for the receiver to be constructed.
1368 __ Push(Immediate(0));
1369
1370 if (mode == InterpreterPushArgsMode::kWithFinalSpread) {
1371 // Pass the spread in the register rbx.
1372 __ movq(rbx, Operand(rcx, -kSystemPointerSize));
1373 // Push return address in preparation for the tail-call.
1374 __ PushReturnAddressFrom(kScratchRegister);
1375 } else {
1376 __ PushReturnAddressFrom(kScratchRegister);
1377 __ AssertUndefinedOrAllocationSite(rbx);
1378 }
1379
1380 if (mode == InterpreterPushArgsMode::kArrayFunction) {
1381 // Tail call to the array construct stub (still in the caller
1382 // context at this point).
1383 __ AssertFunction(rdi);
1384 // Jump to the constructor function (rax, rbx, rdx passed on).
1385 Handle<Code> code = BUILTIN_CODE(masm->isolate(), ArrayConstructorImpl);
1386 __ Jump(code, RelocInfo::CODE_TARGET);
1387 } else if (mode == InterpreterPushArgsMode::kWithFinalSpread) {
1388 // Call the constructor (rax, rdx, rdi passed on).
1389 __ Jump(BUILTIN_CODE(masm->isolate(), ConstructWithSpread),
1390 RelocInfo::CODE_TARGET);
1391 } else {
1392 DCHECK_EQ(InterpreterPushArgsMode::kOther, mode);
1393 // Call the constructor (rax, rdx, rdi passed on).
1394 __ Jump(BUILTIN_CODE(masm->isolate(), Construct), RelocInfo::CODE_TARGET);
1395 }
1396
1397 // Throw stack overflow exception.
1398 __ bind(&stack_overflow);
1399 {
1400 __ TailCallRuntime(Runtime::kThrowStackOverflow);
1401 // This should be unreachable.
1402 __ int3();
1403 }
1404 }
1405
Generate_InterpreterEnterBytecode(MacroAssembler * masm)1406 static void Generate_InterpreterEnterBytecode(MacroAssembler* masm) {
1407 // Set the return address to the correct point in the interpreter entry
1408 // trampoline.
1409 Label builtin_trampoline, trampoline_loaded;
1410 Smi interpreter_entry_return_pc_offset(
1411 masm->isolate()->heap()->interpreter_entry_return_pc_offset());
1412 DCHECK_NE(interpreter_entry_return_pc_offset, Smi::zero());
1413
1414 // If the SFI function_data is an InterpreterData, the function will have a
1415 // custom copy of the interpreter entry trampoline for profiling. If so,
1416 // get the custom trampoline, otherwise grab the entry address of the global
1417 // trampoline.
1418 __ movq(rbx, Operand(rbp, StandardFrameConstants::kFunctionOffset));
1419 __ LoadTaggedPointerField(
1420 rbx, FieldOperand(rbx, JSFunction::kSharedFunctionInfoOffset));
1421 __ LoadTaggedPointerField(
1422 rbx, FieldOperand(rbx, SharedFunctionInfo::kFunctionDataOffset));
1423 __ CmpObjectType(rbx, INTERPRETER_DATA_TYPE, kScratchRegister);
1424 __ j(not_equal, &builtin_trampoline, Label::kNear);
1425
1426 __ LoadTaggedPointerField(
1427 rbx, FieldOperand(rbx, InterpreterData::kInterpreterTrampolineOffset));
1428 __ addq(rbx, Immediate(Code::kHeaderSize - kHeapObjectTag));
1429 __ jmp(&trampoline_loaded, Label::kNear);
1430
1431 __ bind(&builtin_trampoline);
1432 // TODO(jgruber): Replace this by a lookup in the builtin entry table.
1433 __ movq(rbx,
1434 __ ExternalReferenceAsOperand(
1435 ExternalReference::
1436 address_of_interpreter_entry_trampoline_instruction_start(
1437 masm->isolate()),
1438 kScratchRegister));
1439
1440 __ bind(&trampoline_loaded);
1441 __ addq(rbx, Immediate(interpreter_entry_return_pc_offset.value()));
1442 __ Push(rbx);
1443
1444 // Initialize dispatch table register.
1445 __ Move(
1446 kInterpreterDispatchTableRegister,
1447 ExternalReference::interpreter_dispatch_table_address(masm->isolate()));
1448
1449 // Get the bytecode array pointer from the frame.
1450 __ movq(kInterpreterBytecodeArrayRegister,
1451 Operand(rbp, InterpreterFrameConstants::kBytecodeArrayFromFp));
1452
1453 if (FLAG_debug_code) {
1454 // Check function data field is actually a BytecodeArray object.
1455 __ AssertNotSmi(kInterpreterBytecodeArrayRegister);
1456 __ CmpObjectType(kInterpreterBytecodeArrayRegister, BYTECODE_ARRAY_TYPE,
1457 rbx);
1458 __ Assert(
1459 equal,
1460 AbortReason::kFunctionDataShouldBeBytecodeArrayOnInterpreterEntry);
1461 }
1462
1463 // Get the target bytecode offset from the frame.
1464 __ SmiUntag(kInterpreterBytecodeOffsetRegister,
1465 Operand(rbp, InterpreterFrameConstants::kBytecodeOffsetFromFp));
1466
1467 if (FLAG_debug_code) {
1468 Label okay;
1469 __ cmpq(kInterpreterBytecodeOffsetRegister,
1470 Immediate(BytecodeArray::kHeaderSize - kHeapObjectTag));
1471 __ j(greater_equal, &okay, Label::kNear);
1472 __ int3();
1473 __ bind(&okay);
1474 }
1475
1476 // Dispatch to the target bytecode.
1477 __ movzxbq(r11, Operand(kInterpreterBytecodeArrayRegister,
1478 kInterpreterBytecodeOffsetRegister, times_1, 0));
1479 __ movq(kJavaScriptCallCodeStartRegister,
1480 Operand(kInterpreterDispatchTableRegister, r11,
1481 times_system_pointer_size, 0));
1482 __ jmp(kJavaScriptCallCodeStartRegister);
1483 }
1484
Generate_InterpreterEnterBytecodeAdvance(MacroAssembler * masm)1485 void Builtins::Generate_InterpreterEnterBytecodeAdvance(MacroAssembler* masm) {
1486 // Get bytecode array and bytecode offset from the stack frame.
1487 __ movq(kInterpreterBytecodeArrayRegister,
1488 Operand(rbp, InterpreterFrameConstants::kBytecodeArrayFromFp));
1489 __ SmiUntag(kInterpreterBytecodeOffsetRegister,
1490 Operand(rbp, InterpreterFrameConstants::kBytecodeOffsetFromFp));
1491
1492 Label enter_bytecode, function_entry_bytecode;
1493 __ cmpq(kInterpreterBytecodeOffsetRegister,
1494 Immediate(BytecodeArray::kHeaderSize - kHeapObjectTag +
1495 kFunctionEntryBytecodeOffset));
1496 __ j(equal, &function_entry_bytecode);
1497
1498 // Load the current bytecode.
1499 __ movzxbq(rbx, Operand(kInterpreterBytecodeArrayRegister,
1500 kInterpreterBytecodeOffsetRegister, times_1, 0));
1501
1502 // Advance to the next bytecode.
1503 Label if_return;
1504 AdvanceBytecodeOffsetOrReturn(masm, kInterpreterBytecodeArrayRegister,
1505 kInterpreterBytecodeOffsetRegister, rbx, rcx,
1506 r11, &if_return);
1507
1508 __ bind(&enter_bytecode);
1509 // Convert new bytecode offset to a Smi and save in the stackframe.
1510 __ SmiTag(kInterpreterBytecodeOffsetRegister);
1511 __ movq(Operand(rbp, InterpreterFrameConstants::kBytecodeOffsetFromFp),
1512 kInterpreterBytecodeOffsetRegister);
1513
1514 Generate_InterpreterEnterBytecode(masm);
1515
1516 __ bind(&function_entry_bytecode);
1517 // If the code deoptimizes during the implicit function entry stack interrupt
1518 // check, it will have a bailout ID of kFunctionEntryBytecodeOffset, which is
1519 // not a valid bytecode offset. Detect this case and advance to the first
1520 // actual bytecode.
1521 __ movq(kInterpreterBytecodeOffsetRegister,
1522 Immediate(BytecodeArray::kHeaderSize - kHeapObjectTag));
1523 __ jmp(&enter_bytecode);
1524
1525 // We should never take the if_return path.
1526 __ bind(&if_return);
1527 __ Abort(AbortReason::kInvalidBytecodeAdvance);
1528 }
1529
Generate_InterpreterEnterBytecodeDispatch(MacroAssembler * masm)1530 void Builtins::Generate_InterpreterEnterBytecodeDispatch(MacroAssembler* masm) {
1531 Generate_InterpreterEnterBytecode(masm);
1532 }
1533
1534 namespace {
Generate_ContinueToBuiltinHelper(MacroAssembler * masm,bool java_script_builtin,bool with_result)1535 void Generate_ContinueToBuiltinHelper(MacroAssembler* masm,
1536 bool java_script_builtin,
1537 bool with_result) {
1538 const RegisterConfiguration* config(RegisterConfiguration::Default());
1539 int allocatable_register_count = config->num_allocatable_general_registers();
1540 if (with_result) {
1541 if (java_script_builtin) {
1542 // kScratchRegister is not included in the allocateable registers.
1543 __ movq(kScratchRegister, rax);
1544 } else {
1545 // Overwrite the hole inserted by the deoptimizer with the return value
1546 // from the LAZY deopt point.
1547 __ movq(
1548 Operand(rsp, config->num_allocatable_general_registers() *
1549 kSystemPointerSize +
1550 BuiltinContinuationFrameConstants::kFixedFrameSize),
1551 rax);
1552 }
1553 }
1554 for (int i = allocatable_register_count - 1; i >= 0; --i) {
1555 int code = config->GetAllocatableGeneralCode(i);
1556 __ popq(Register::from_code(code));
1557 if (java_script_builtin && code == kJavaScriptCallArgCountRegister.code()) {
1558 __ SmiUntag(Register::from_code(code));
1559 }
1560 }
1561 if (with_result && java_script_builtin) {
1562 // Overwrite the hole inserted by the deoptimizer with the return value from
1563 // the LAZY deopt point. rax contains the arguments count, the return value
1564 // from LAZY is always the last argument.
1565 __ movq(Operand(rsp, rax, times_system_pointer_size,
1566 BuiltinContinuationFrameConstants::kFixedFrameSize),
1567 kScratchRegister);
1568 }
1569 __ movq(
1570 rbp,
1571 Operand(rsp, BuiltinContinuationFrameConstants::kFixedFrameSizeFromFp));
1572 const int offsetToPC =
1573 BuiltinContinuationFrameConstants::kFixedFrameSizeFromFp -
1574 kSystemPointerSize;
1575 __ popq(Operand(rsp, offsetToPC));
1576 __ Drop(offsetToPC / kSystemPointerSize);
1577
1578 // Replace the builtin index Smi on the stack with the instruction start
1579 // address of the builtin from the builtins table, and then Ret to this
1580 // address
1581 __ movq(kScratchRegister, Operand(rsp, 0));
1582 __ movq(kScratchRegister,
1583 __ EntryFromBuiltinIndexAsOperand(kScratchRegister));
1584 __ movq(Operand(rsp, 0), kScratchRegister);
1585
1586 __ Ret();
1587 }
1588 } // namespace
1589
Generate_ContinueToCodeStubBuiltin(MacroAssembler * masm)1590 void Builtins::Generate_ContinueToCodeStubBuiltin(MacroAssembler* masm) {
1591 Generate_ContinueToBuiltinHelper(masm, false, false);
1592 }
1593
Generate_ContinueToCodeStubBuiltinWithResult(MacroAssembler * masm)1594 void Builtins::Generate_ContinueToCodeStubBuiltinWithResult(
1595 MacroAssembler* masm) {
1596 Generate_ContinueToBuiltinHelper(masm, false, true);
1597 }
1598
Generate_ContinueToJavaScriptBuiltin(MacroAssembler * masm)1599 void Builtins::Generate_ContinueToJavaScriptBuiltin(MacroAssembler* masm) {
1600 Generate_ContinueToBuiltinHelper(masm, true, false);
1601 }
1602
Generate_ContinueToJavaScriptBuiltinWithResult(MacroAssembler * masm)1603 void Builtins::Generate_ContinueToJavaScriptBuiltinWithResult(
1604 MacroAssembler* masm) {
1605 Generate_ContinueToBuiltinHelper(masm, true, true);
1606 }
1607
Generate_NotifyDeoptimized(MacroAssembler * masm)1608 void Builtins::Generate_NotifyDeoptimized(MacroAssembler* masm) {
1609 // Enter an internal frame.
1610 {
1611 FrameScope scope(masm, StackFrame::INTERNAL);
1612 __ CallRuntime(Runtime::kNotifyDeoptimized);
1613 // Tear down internal frame.
1614 }
1615
1616 DCHECK_EQ(kInterpreterAccumulatorRegister.code(), rax.code());
1617 __ movq(rax, Operand(rsp, kPCOnStackSize));
1618 __ ret(1 * kSystemPointerSize); // Remove rax.
1619 }
1620
1621 // static
Generate_FunctionPrototypeApply(MacroAssembler * masm)1622 void Builtins::Generate_FunctionPrototypeApply(MacroAssembler* masm) {
1623 // ----------- S t a t e -------------
1624 // -- rax : argc
1625 // -- rsp[0] : return address
1626 // -- rsp[1] : receiver
1627 // -- rsp[2] : thisArg
1628 // -- rsp[3] : argArray
1629 // -----------------------------------
1630
1631 // 1. Load receiver into rdi, argArray into rbx (if present), remove all
1632 // arguments from the stack (including the receiver), and push thisArg (if
1633 // present) instead.
1634 {
1635 Label no_arg_array, no_this_arg;
1636 StackArgumentsAccessor args(rax);
1637 __ LoadRoot(rdx, RootIndex::kUndefinedValue);
1638 __ movq(rbx, rdx);
1639 __ movq(rdi, args[0]);
1640 __ testq(rax, rax);
1641 __ j(zero, &no_this_arg, Label::kNear);
1642 {
1643 __ movq(rdx, args[1]);
1644 __ cmpq(rax, Immediate(1));
1645 __ j(equal, &no_arg_array, Label::kNear);
1646 __ movq(rbx, args[2]);
1647 __ bind(&no_arg_array);
1648 }
1649 __ bind(&no_this_arg);
1650 __ PopReturnAddressTo(rcx);
1651 __ leaq(rsp,
1652 Operand(rsp, rax, times_system_pointer_size, kSystemPointerSize));
1653 __ Push(rdx);
1654 __ PushReturnAddressFrom(rcx);
1655 }
1656
1657 // ----------- S t a t e -------------
1658 // -- rbx : argArray
1659 // -- rdi : receiver
1660 // -- rsp[0] : return address
1661 // -- rsp[8] : thisArg
1662 // -----------------------------------
1663
1664 // 2. We don't need to check explicitly for callable receiver here,
1665 // since that's the first thing the Call/CallWithArrayLike builtins
1666 // will do.
1667
1668 // 3. Tail call with no arguments if argArray is null or undefined.
1669 Label no_arguments;
1670 __ JumpIfRoot(rbx, RootIndex::kNullValue, &no_arguments, Label::kNear);
1671 __ JumpIfRoot(rbx, RootIndex::kUndefinedValue, &no_arguments, Label::kNear);
1672
1673 // 4a. Apply the receiver to the given argArray.
1674 __ Jump(BUILTIN_CODE(masm->isolate(), CallWithArrayLike),
1675 RelocInfo::CODE_TARGET);
1676
1677 // 4b. The argArray is either null or undefined, so we tail call without any
1678 // arguments to the receiver. Since we did not create a frame for
1679 // Function.prototype.apply() yet, we use a normal Call builtin here.
1680 __ bind(&no_arguments);
1681 {
1682 __ Set(rax, 0);
1683 __ Jump(masm->isolate()->builtins()->Call(), RelocInfo::CODE_TARGET);
1684 }
1685 }
1686
1687 // static
Generate_FunctionPrototypeCall(MacroAssembler * masm)1688 void Builtins::Generate_FunctionPrototypeCall(MacroAssembler* masm) {
1689 // Stack Layout:
1690 // rsp[0] : Return address
1691 // rsp[8] : Argument 0 (receiver: callable to call)
1692 // rsp[16] : Argument 1
1693 // ...
1694 // rsp[8 * n] : Argument n-1
1695 // rsp[8 * (n + 1)] : Argument n
1696 // rax contains the number of arguments, n, not counting the receiver.
1697
1698 // 1. Get the callable to call (passed as receiver) from the stack.
1699 {
1700 StackArgumentsAccessor args(rax);
1701 __ movq(rdi, args.GetReceiverOperand());
1702 }
1703
1704 // 2. Save the return address and drop the callable.
1705 __ PopReturnAddressTo(rbx);
1706 __ Pop(kScratchRegister);
1707
1708 // 3. Make sure we have at least one argument.
1709 {
1710 Label done;
1711 __ testq(rax, rax);
1712 __ j(not_zero, &done, Label::kNear);
1713 __ PushRoot(RootIndex::kUndefinedValue);
1714 __ incq(rax);
1715 __ bind(&done);
1716 }
1717
1718 // 4. Push back the return address one slot down on the stack (overwriting the
1719 // original callable), making the original first argument the new receiver.
1720 __ PushReturnAddressFrom(rbx);
1721 __ decq(rax); // One fewer argument (first argument is new receiver).
1722
1723 // 5. Call the callable.
1724 // Since we did not create a frame for Function.prototype.call() yet,
1725 // we use a normal Call builtin here.
1726 __ Jump(masm->isolate()->builtins()->Call(), RelocInfo::CODE_TARGET);
1727 }
1728
Generate_ReflectApply(MacroAssembler * masm)1729 void Builtins::Generate_ReflectApply(MacroAssembler* masm) {
1730 // ----------- S t a t e -------------
1731 // -- rax : argc
1732 // -- rsp[0] : return address
1733 // -- rsp[8] : receiver
1734 // -- rsp[16] : target (if argc >= 1)
1735 // -- rsp[24] : thisArgument (if argc >= 2)
1736 // -- rsp[32] : argumentsList (if argc == 3)
1737 // -----------------------------------
1738
1739 // 1. Load target into rdi (if present), argumentsList into rbx (if present),
1740 // remove all arguments from the stack (including the receiver), and push
1741 // thisArgument (if present) instead.
1742 {
1743 Label done;
1744 StackArgumentsAccessor args(rax);
1745 __ LoadRoot(rdi, RootIndex::kUndefinedValue);
1746 __ movq(rdx, rdi);
1747 __ movq(rbx, rdi);
1748 __ cmpq(rax, Immediate(1));
1749 __ j(below, &done, Label::kNear);
1750 __ movq(rdi, args[1]); // target
1751 __ j(equal, &done, Label::kNear);
1752 __ movq(rdx, args[2]); // thisArgument
1753 __ cmpq(rax, Immediate(3));
1754 __ j(below, &done, Label::kNear);
1755 __ movq(rbx, args[3]); // argumentsList
1756 __ bind(&done);
1757 __ PopReturnAddressTo(rcx);
1758 __ leaq(rsp,
1759 Operand(rsp, rax, times_system_pointer_size, kSystemPointerSize));
1760 __ Push(rdx);
1761 __ PushReturnAddressFrom(rcx);
1762 }
1763
1764 // ----------- S t a t e -------------
1765 // -- rbx : argumentsList
1766 // -- rdi : target
1767 // -- rsp[0] : return address
1768 // -- rsp[8] : thisArgument
1769 // -----------------------------------
1770
1771 // 2. We don't need to check explicitly for callable target here,
1772 // since that's the first thing the Call/CallWithArrayLike builtins
1773 // will do.
1774
1775 // 3. Apply the target to the given argumentsList.
1776 __ Jump(BUILTIN_CODE(masm->isolate(), CallWithArrayLike),
1777 RelocInfo::CODE_TARGET);
1778 }
1779
Generate_ReflectConstruct(MacroAssembler * masm)1780 void Builtins::Generate_ReflectConstruct(MacroAssembler* masm) {
1781 // ----------- S t a t e -------------
1782 // -- rax : argc
1783 // -- rsp[0] : return address
1784 // -- rsp[8] : receiver
1785 // -- rsp[16] : target
1786 // -- rsp[24] : argumentsList
1787 // -- rsp[32] : new.target (optional)
1788 // -----------------------------------
1789
1790 // 1. Load target into rdi (if present), argumentsList into rbx (if present),
1791 // new.target into rdx (if present, otherwise use target), remove all
1792 // arguments from the stack (including the receiver), and push thisArgument
1793 // (if present) instead.
1794 {
1795 Label done;
1796 StackArgumentsAccessor args(rax);
1797 __ LoadRoot(rdi, RootIndex::kUndefinedValue);
1798 __ movq(rdx, rdi);
1799 __ movq(rbx, rdi);
1800 __ cmpq(rax, Immediate(1));
1801 __ j(below, &done, Label::kNear);
1802 __ movq(rdi, args[1]); // target
1803 __ movq(rdx, rdi); // new.target defaults to target
1804 __ j(equal, &done, Label::kNear);
1805 __ movq(rbx, args[2]); // argumentsList
1806 __ cmpq(rax, Immediate(3));
1807 __ j(below, &done, Label::kNear);
1808 __ movq(rdx, args[3]); // new.target
1809 __ bind(&done);
1810 __ PopReturnAddressTo(rcx);
1811 __ leaq(rsp,
1812 Operand(rsp, rax, times_system_pointer_size, kSystemPointerSize));
1813 __ PushRoot(RootIndex::kUndefinedValue);
1814 __ PushReturnAddressFrom(rcx);
1815 }
1816
1817 // ----------- S t a t e -------------
1818 // -- rbx : argumentsList
1819 // -- rdx : new.target
1820 // -- rdi : target
1821 // -- rsp[0] : return address
1822 // -- rsp[8] : receiver (undefined)
1823 // -----------------------------------
1824
1825 // 2. We don't need to check explicitly for constructor target here,
1826 // since that's the first thing the Construct/ConstructWithArrayLike
1827 // builtins will do.
1828
1829 // 3. We don't need to check explicitly for constructor new.target here,
1830 // since that's the second thing the Construct/ConstructWithArrayLike
1831 // builtins will do.
1832
1833 // 4. Construct the target with the given new.target and argumentsList.
1834 __ Jump(BUILTIN_CODE(masm->isolate(), ConstructWithArrayLike),
1835 RelocInfo::CODE_TARGET);
1836 }
1837
EnterArgumentsAdaptorFrame(MacroAssembler * masm)1838 static void EnterArgumentsAdaptorFrame(MacroAssembler* masm) {
1839 __ pushq(rbp);
1840 __ movq(rbp, rsp);
1841
1842 // Store the arguments adaptor context sentinel.
1843 __ Push(Immediate(StackFrame::TypeToMarker(StackFrame::ARGUMENTS_ADAPTOR)));
1844
1845 // Push the function on the stack.
1846 __ Push(rdi);
1847
1848 // Preserve the number of arguments on the stack. Must preserve rax,
1849 // rbx and rcx because these registers are used when copying the
1850 // arguments and the receiver.
1851 __ SmiTag(r8, rax);
1852 __ Push(r8);
1853
1854 __ Push(Immediate(0)); // Padding.
1855 }
1856
LeaveArgumentsAdaptorFrame(MacroAssembler * masm)1857 static void LeaveArgumentsAdaptorFrame(MacroAssembler* masm) {
1858 // Retrieve the number of arguments from the stack. Number is a Smi.
1859 __ movq(rbx, Operand(rbp, ArgumentsAdaptorFrameConstants::kLengthOffset));
1860
1861 // Leave the frame.
1862 __ movq(rsp, rbp);
1863 __ popq(rbp);
1864
1865 // Remove caller arguments from the stack.
1866 __ PopReturnAddressTo(rcx);
1867 SmiIndex index = masm->SmiToIndex(rbx, rbx, kSystemPointerSizeLog2);
1868 __ leaq(rsp, Operand(rsp, index.reg, index.scale, 1 * kSystemPointerSize));
1869 __ PushReturnAddressFrom(rcx);
1870 }
1871
Generate_ArgumentsAdaptorTrampoline(MacroAssembler * masm)1872 void Builtins::Generate_ArgumentsAdaptorTrampoline(MacroAssembler* masm) {
1873 // ----------- S t a t e -------------
1874 // -- rax : actual number of arguments
1875 // -- rbx : expected number of arguments
1876 // -- rdx : new target (passed through to callee)
1877 // -- rdi : function (passed through to callee)
1878 // -----------------------------------
1879
1880 Label dont_adapt_arguments, stack_overflow;
1881 __ cmpq(rbx, Immediate(kDontAdaptArgumentsSentinel));
1882 __ j(equal, &dont_adapt_arguments);
1883 __ LoadTaggedPointerField(
1884 rcx, FieldOperand(rdi, JSFunction::kSharedFunctionInfoOffset));
1885
1886 // -------------------------------------------
1887 // Adapt arguments.
1888 // -------------------------------------------
1889 {
1890 EnterArgumentsAdaptorFrame(masm);
1891 __ StackOverflowCheck(rbx, rcx, &stack_overflow);
1892
1893 Label under_application, over_application, invoke;
1894 __ cmpq(rax, rbx);
1895 __ j(less, &under_application, Label::kNear);
1896
1897 // Enough parameters: Actual >= expected.
1898 __ bind(&over_application);
1899 {
1900 // Copy receiver and all expected arguments.
1901 const int offset = StandardFrameConstants::kCallerSPOffset;
1902 __ leaq(r8, Operand(rbp, rbx, times_system_pointer_size, offset));
1903 __ Set(rax, -1); // account for receiver
1904
1905 Label copy;
1906 __ bind(©);
1907 __ incq(rax);
1908 __ Push(Operand(r8, 0));
1909 __ subq(r8, Immediate(kSystemPointerSize));
1910 __ cmpq(rax, rbx);
1911 __ j(less, ©);
1912 __ jmp(&invoke, Label::kNear);
1913 }
1914
1915 // Too few parameters: Actual < expected.
1916 __ bind(&under_application);
1917 {
1918 // Fill remaining expected arguments with undefined values.
1919 Label fill;
1920 __ LoadRoot(kScratchRegister, RootIndex::kUndefinedValue);
1921 __ movq(r8, rbx);
1922 __ subq(r8, rax);
1923 __ bind(&fill);
1924 __ Push(kScratchRegister);
1925 __ decq(r8);
1926 __ j(greater, &fill);
1927
1928 // Copy receiver and all actual arguments.
1929 const int offset = StandardFrameConstants::kCallerSPOffset;
1930 __ leaq(r9, Operand(rbp, rax, times_system_pointer_size, offset));
1931 __ Set(r8, -1); // account for receiver
1932
1933 Label copy;
1934 __ bind(©);
1935 __ incq(r8);
1936 __ Push(Operand(r9, 0));
1937 __ subq(r9, Immediate(kSystemPointerSize));
1938 __ cmpq(r8, rax);
1939 __ j(less, ©);
1940
1941 // Update actual number of arguments.
1942 __ movq(rax, rbx);
1943 }
1944
1945 // Call the entry point.
1946 __ bind(&invoke);
1947 // rax : expected number of arguments
1948 // rdx : new target (passed through to callee)
1949 // rdi : function (passed through to callee)
1950 static_assert(kJavaScriptCallCodeStartRegister == rcx, "ABI mismatch");
1951 __ LoadTaggedPointerField(rcx, FieldOperand(rdi, JSFunction::kCodeOffset));
1952 __ CallCodeObject(rcx);
1953
1954 // Store offset of return address for deoptimizer.
1955 masm->isolate()->heap()->SetArgumentsAdaptorDeoptPCOffset(
1956 masm->pc_offset());
1957
1958 // Leave frame and return.
1959 LeaveArgumentsAdaptorFrame(masm);
1960 __ ret(0);
1961 }
1962
1963 // -------------------------------------------
1964 // Don't adapt arguments.
1965 // -------------------------------------------
1966 __ bind(&dont_adapt_arguments);
1967 static_assert(kJavaScriptCallCodeStartRegister == rcx, "ABI mismatch");
1968 __ LoadTaggedPointerField(rcx, FieldOperand(rdi, JSFunction::kCodeOffset));
1969 __ JumpCodeObject(rcx);
1970
1971 __ bind(&stack_overflow);
1972 {
1973 FrameScope frame(masm, StackFrame::MANUAL);
1974 __ CallRuntime(Runtime::kThrowStackOverflow);
1975 __ int3();
1976 }
1977 }
1978
1979 // static
Generate_CallOrConstructVarargs(MacroAssembler * masm,Handle<Code> code)1980 void Builtins::Generate_CallOrConstructVarargs(MacroAssembler* masm,
1981 Handle<Code> code) {
1982 // ----------- S t a t e -------------
1983 // -- rdi : target
1984 // -- rax : number of parameters on the stack (not including the receiver)
1985 // -- rbx : arguments list (a FixedArray)
1986 // -- rcx : len (number of elements to push from args)
1987 // -- rdx : new.target (for [[Construct]])
1988 // -- rsp[0] : return address
1989 // -----------------------------------
1990 Register scratch = r11;
1991
1992 if (masm->emit_debug_code()) {
1993 // Allow rbx to be a FixedArray, or a FixedDoubleArray if rcx == 0.
1994 Label ok, fail;
1995 __ AssertNotSmi(rbx);
1996 Register map = r9;
1997 __ LoadTaggedPointerField(map, FieldOperand(rbx, HeapObject::kMapOffset));
1998 __ CmpInstanceType(map, FIXED_ARRAY_TYPE);
1999 __ j(equal, &ok);
2000 __ CmpInstanceType(map, FIXED_DOUBLE_ARRAY_TYPE);
2001 __ j(not_equal, &fail);
2002 __ Cmp(rcx, 0);
2003 __ j(equal, &ok);
2004 // Fall through.
2005 __ bind(&fail);
2006 __ Abort(AbortReason::kOperandIsNotAFixedArray);
2007
2008 __ bind(&ok);
2009 }
2010
2011 Label stack_overflow;
2012 __ StackOverflowCheck(rcx, r8, &stack_overflow, Label::kNear);
2013
2014 // Push additional arguments onto the stack.
2015 // Move the arguments already in the stack,
2016 // including the receiver and the return address.
2017 {
2018 Label copy, check;
2019 Register src = r8, dest = rsp, num = r9, current = r11;
2020 __ movq(src, rsp);
2021 __ leaq(kScratchRegister, Operand(rcx, times_system_pointer_size, 0));
2022 __ AllocateStackSpace(kScratchRegister);
2023 __ leaq(num, Operand(rax, 2)); // Number of words to copy.
2024 // +2 for receiver and return address.
2025 __ Set(current, 0);
2026 __ jmp(&check);
2027 __ bind(©);
2028 __ movq(kScratchRegister,
2029 Operand(src, current, times_system_pointer_size, 0));
2030 __ movq(Operand(dest, current, times_system_pointer_size, 0),
2031 kScratchRegister);
2032 __ incq(current);
2033 __ bind(&check);
2034 __ cmpq(current, num);
2035 __ j(less, ©);
2036 __ leaq(r8, Operand(rsp, num, times_system_pointer_size, 0));
2037 }
2038
2039 // Copy the additional arguments onto the stack.
2040 {
2041 Register value = scratch;
2042 Register src = rbx, dest = r8, num = rcx, current = r9;
2043 __ Set(current, 0);
2044 Label done, push, loop;
2045 __ bind(&loop);
2046 __ cmpl(current, num);
2047 __ j(equal, &done, Label::kNear);
2048 // Turn the hole into undefined as we go.
2049 __ LoadAnyTaggedField(value, FieldOperand(src, current, times_tagged_size,
2050 FixedArray::kHeaderSize));
2051 __ CompareRoot(value, RootIndex::kTheHoleValue);
2052 __ j(not_equal, &push, Label::kNear);
2053 __ LoadRoot(value, RootIndex::kUndefinedValue);
2054 __ bind(&push);
2055 __ movq(Operand(dest, current, times_system_pointer_size, 0), value);
2056 __ incl(current);
2057 __ jmp(&loop);
2058 __ bind(&done);
2059 __ addq(rax, current);
2060 }
2061
2062 // Tail-call to the actual Call or Construct builtin.
2063 __ Jump(code, RelocInfo::CODE_TARGET);
2064
2065 __ bind(&stack_overflow);
2066 __ TailCallRuntime(Runtime::kThrowStackOverflow);
2067 }
2068
2069 // static
Generate_CallOrConstructForwardVarargs(MacroAssembler * masm,CallOrConstructMode mode,Handle<Code> code)2070 void Builtins::Generate_CallOrConstructForwardVarargs(MacroAssembler* masm,
2071 CallOrConstructMode mode,
2072 Handle<Code> code) {
2073 // ----------- S t a t e -------------
2074 // -- rax : the number of arguments (not including the receiver)
2075 // -- rdx : the new target (for [[Construct]] calls)
2076 // -- rdi : the target to call (can be any Object)
2077 // -- rcx : start index (to support rest parameters)
2078 // -----------------------------------
2079
2080 // Check if new.target has a [[Construct]] internal method.
2081 if (mode == CallOrConstructMode::kConstruct) {
2082 Label new_target_constructor, new_target_not_constructor;
2083 __ JumpIfSmi(rdx, &new_target_not_constructor, Label::kNear);
2084 __ LoadTaggedPointerField(rbx, FieldOperand(rdx, HeapObject::kMapOffset));
2085 __ testb(FieldOperand(rbx, Map::kBitFieldOffset),
2086 Immediate(Map::Bits1::IsConstructorBit::kMask));
2087 __ j(not_zero, &new_target_constructor, Label::kNear);
2088 __ bind(&new_target_not_constructor);
2089 {
2090 FrameScope scope(masm, StackFrame::MANUAL);
2091 __ EnterFrame(StackFrame::INTERNAL);
2092 __ Push(rdx);
2093 __ CallRuntime(Runtime::kThrowNotConstructor);
2094 }
2095 __ bind(&new_target_constructor);
2096 }
2097
2098 #ifdef V8_NO_ARGUMENTS_ADAPTOR
2099 // TODO(victorgomes): Remove this copy when all the arguments adaptor frame
2100 // code is erased.
2101 __ movq(rbx, rbp);
2102 __ movq(r8, Operand(rbp, StandardFrameConstants::kArgCOffset));
2103 #else
2104 // Check if we have an arguments adaptor frame below the function frame.
2105 Label arguments_adaptor, arguments_done;
2106 __ movq(rbx, Operand(rbp, StandardFrameConstants::kCallerFPOffset));
2107 __ cmpq(Operand(rbx, CommonFrameConstants::kContextOrFrameTypeOffset),
2108 Immediate(StackFrame::TypeToMarker(StackFrame::ARGUMENTS_ADAPTOR)));
2109 __ j(equal, &arguments_adaptor, Label::kNear);
2110 {
2111 __ movq(r8, Operand(rbp, StandardFrameConstants::kFunctionOffset));
2112 __ LoadTaggedPointerField(
2113 r8, FieldOperand(r8, JSFunction::kSharedFunctionInfoOffset));
2114 __ movzxwq(
2115 r8, FieldOperand(r8, SharedFunctionInfo::kFormalParameterCountOffset));
2116 __ movq(rbx, rbp);
2117 }
2118 __ jmp(&arguments_done, Label::kNear);
2119 __ bind(&arguments_adaptor);
2120 {
2121 __ SmiUntag(r8,
2122 Operand(rbx, ArgumentsAdaptorFrameConstants::kLengthOffset));
2123 }
2124 __ bind(&arguments_done);
2125 #endif
2126
2127 Label stack_done, stack_overflow;
2128 __ subl(r8, rcx);
2129 __ j(less_equal, &stack_done);
2130 {
2131 // ----------- S t a t e -------------
2132 // -- rax : the number of arguments already in the stack (not including the
2133 // receiver)
2134 // -- rbx : point to the caller stack frame
2135 // -- rcx : start index (to support rest parameters)
2136 // -- rdx : the new target (for [[Construct]] calls)
2137 // -- rdi : the target to call (can be any Object)
2138 // -- r8 : number of arguments to copy, i.e. arguments count - start index
2139 // -----------------------------------
2140
2141 // Check for stack overflow.
2142 __ StackOverflowCheck(r8, r12, &stack_overflow, Label::kNear);
2143
2144 // Forward the arguments from the caller frame.
2145 // Move the arguments already in the stack,
2146 // including the receiver and the return address.
2147 {
2148 Label copy, check;
2149 Register src = r9, dest = rsp, num = r12, current = r11;
2150 __ movq(src, rsp);
2151 __ leaq(kScratchRegister, Operand(r8, times_system_pointer_size, 0));
2152 __ AllocateStackSpace(kScratchRegister);
2153 __ leaq(num, Operand(rax, 2)); // Number of words to copy.
2154 // +2 for receiver and return address.
2155 __ Set(current, 0);
2156 __ jmp(&check);
2157 __ bind(©);
2158 __ movq(kScratchRegister,
2159 Operand(src, current, times_system_pointer_size, 0));
2160 __ movq(Operand(dest, current, times_system_pointer_size, 0),
2161 kScratchRegister);
2162 __ incq(current);
2163 __ bind(&check);
2164 __ cmpq(current, num);
2165 __ j(less, ©);
2166 __ leaq(r9, Operand(rsp, num, times_system_pointer_size, 0));
2167 }
2168
2169 __ addl(rax, r8); // Update total number of arguments.
2170
2171 // Point to the first argument to copy (skipping receiver).
2172 __ leaq(rcx, Operand(rcx, times_system_pointer_size,
2173 CommonFrameConstants::kFixedFrameSizeAboveFp +
2174 kSystemPointerSize));
2175 __ addq(rbx, rcx);
2176
2177 // Copy the additional caller arguments onto the stack.
2178 // TODO(victorgomes): Consider using forward order as potentially more cache
2179 // friendly.
2180 {
2181 Register src = rbx, dest = r9, num = r8;
2182 Label loop;
2183 __ bind(&loop);
2184 __ decq(num);
2185 __ movq(kScratchRegister,
2186 Operand(src, num, times_system_pointer_size, 0));
2187 __ movq(Operand(dest, num, times_system_pointer_size, 0),
2188 kScratchRegister);
2189 __ j(not_zero, &loop);
2190 }
2191 }
2192 __ jmp(&stack_done, Label::kNear);
2193 __ bind(&stack_overflow);
2194 __ TailCallRuntime(Runtime::kThrowStackOverflow);
2195 __ bind(&stack_done);
2196
2197 // Tail-call to the {code} handler.
2198 __ Jump(code, RelocInfo::CODE_TARGET);
2199 }
2200
2201 // static
Generate_CallFunction(MacroAssembler * masm,ConvertReceiverMode mode)2202 void Builtins::Generate_CallFunction(MacroAssembler* masm,
2203 ConvertReceiverMode mode) {
2204 // ----------- S t a t e -------------
2205 // -- rax : the number of arguments (not including the receiver)
2206 // -- rdi : the function to call (checked to be a JSFunction)
2207 // -----------------------------------
2208
2209 StackArgumentsAccessor args(rax);
2210 __ AssertFunction(rdi);
2211
2212 // ES6 section 9.2.1 [[Call]] ( thisArgument, argumentsList)
2213 // Check that the function is not a "classConstructor".
2214 Label class_constructor;
2215 __ LoadTaggedPointerField(
2216 rdx, FieldOperand(rdi, JSFunction::kSharedFunctionInfoOffset));
2217 __ testl(FieldOperand(rdx, SharedFunctionInfo::kFlagsOffset),
2218 Immediate(SharedFunctionInfo::IsClassConstructorBit::kMask));
2219 __ j(not_zero, &class_constructor);
2220
2221 // ----------- S t a t e -------------
2222 // -- rax : the number of arguments (not including the receiver)
2223 // -- rdx : the shared function info.
2224 // -- rdi : the function to call (checked to be a JSFunction)
2225 // -----------------------------------
2226
2227 // Enter the context of the function; ToObject has to run in the function
2228 // context, and we also need to take the global proxy from the function
2229 // context in case of conversion.
2230 __ LoadTaggedPointerField(rsi, FieldOperand(rdi, JSFunction::kContextOffset));
2231 // We need to convert the receiver for non-native sloppy mode functions.
2232 Label done_convert;
2233 __ testl(FieldOperand(rdx, SharedFunctionInfo::kFlagsOffset),
2234 Immediate(SharedFunctionInfo::IsNativeBit::kMask |
2235 SharedFunctionInfo::IsStrictBit::kMask));
2236 __ j(not_zero, &done_convert);
2237 {
2238 // ----------- S t a t e -------------
2239 // -- rax : the number of arguments (not including the receiver)
2240 // -- rdx : the shared function info.
2241 // -- rdi : the function to call (checked to be a JSFunction)
2242 // -- rsi : the function context.
2243 // -----------------------------------
2244
2245 if (mode == ConvertReceiverMode::kNullOrUndefined) {
2246 // Patch receiver to global proxy.
2247 __ LoadGlobalProxy(rcx);
2248 } else {
2249 Label convert_to_object, convert_receiver;
2250 __ movq(rcx, args.GetReceiverOperand());
2251 __ JumpIfSmi(rcx, &convert_to_object, Label::kNear);
2252 STATIC_ASSERT(LAST_JS_RECEIVER_TYPE == LAST_TYPE);
2253 __ CmpObjectType(rcx, FIRST_JS_RECEIVER_TYPE, rbx);
2254 __ j(above_equal, &done_convert);
2255 if (mode != ConvertReceiverMode::kNotNullOrUndefined) {
2256 Label convert_global_proxy;
2257 __ JumpIfRoot(rcx, RootIndex::kUndefinedValue, &convert_global_proxy,
2258 Label::kNear);
2259 __ JumpIfNotRoot(rcx, RootIndex::kNullValue, &convert_to_object,
2260 Label::kNear);
2261 __ bind(&convert_global_proxy);
2262 {
2263 // Patch receiver to global proxy.
2264 __ LoadGlobalProxy(rcx);
2265 }
2266 __ jmp(&convert_receiver);
2267 }
2268 __ bind(&convert_to_object);
2269 {
2270 // Convert receiver using ToObject.
2271 // TODO(bmeurer): Inline the allocation here to avoid building the frame
2272 // in the fast case? (fall back to AllocateInNewSpace?)
2273 FrameScope scope(masm, StackFrame::INTERNAL);
2274 __ SmiTag(rax);
2275 __ Push(rax);
2276 __ Push(rdi);
2277 __ movq(rax, rcx);
2278 __ Push(rsi);
2279 __ Call(BUILTIN_CODE(masm->isolate(), ToObject),
2280 RelocInfo::CODE_TARGET);
2281 __ Pop(rsi);
2282 __ movq(rcx, rax);
2283 __ Pop(rdi);
2284 __ Pop(rax);
2285 __ SmiUntag(rax);
2286 }
2287 __ LoadTaggedPointerField(
2288 rdx, FieldOperand(rdi, JSFunction::kSharedFunctionInfoOffset));
2289 __ bind(&convert_receiver);
2290 }
2291 __ movq(args.GetReceiverOperand(), rcx);
2292 }
2293 __ bind(&done_convert);
2294
2295 // ----------- S t a t e -------------
2296 // -- rax : the number of arguments (not including the receiver)
2297 // -- rdx : the shared function info.
2298 // -- rdi : the function to call (checked to be a JSFunction)
2299 // -- rsi : the function context.
2300 // -----------------------------------
2301
2302 __ movzxwq(
2303 rbx, FieldOperand(rdx, SharedFunctionInfo::kFormalParameterCountOffset));
2304
2305 __ InvokeFunctionCode(rdi, no_reg, rbx, rax, JUMP_FUNCTION);
2306
2307 // The function is a "classConstructor", need to raise an exception.
2308 __ bind(&class_constructor);
2309 {
2310 FrameScope frame(masm, StackFrame::INTERNAL);
2311 __ Push(rdi);
2312 __ CallRuntime(Runtime::kThrowConstructorNonCallableError);
2313 }
2314 }
2315
2316 namespace {
2317
Generate_PushBoundArguments(MacroAssembler * masm)2318 void Generate_PushBoundArguments(MacroAssembler* masm) {
2319 // ----------- S t a t e -------------
2320 // -- rax : the number of arguments (not including the receiver)
2321 // -- rdx : new.target (only in case of [[Construct]])
2322 // -- rdi : target (checked to be a JSBoundFunction)
2323 // -----------------------------------
2324
2325 // Load [[BoundArguments]] into rcx and length of that into rbx.
2326 Label no_bound_arguments;
2327 __ LoadTaggedPointerField(
2328 rcx, FieldOperand(rdi, JSBoundFunction::kBoundArgumentsOffset));
2329 __ SmiUntagField(rbx, FieldOperand(rcx, FixedArray::kLengthOffset));
2330 __ testl(rbx, rbx);
2331 __ j(zero, &no_bound_arguments);
2332 {
2333 // ----------- S t a t e -------------
2334 // -- rax : the number of arguments (not including the receiver)
2335 // -- rdx : new.target (only in case of [[Construct]])
2336 // -- rdi : target (checked to be a JSBoundFunction)
2337 // -- rcx : the [[BoundArguments]] (implemented as FixedArray)
2338 // -- rbx : the number of [[BoundArguments]] (checked to be non-zero)
2339 // -----------------------------------
2340
2341 // TODO(victor): Use Generate_StackOverflowCheck here.
2342 // Check the stack for overflow.
2343 {
2344 Label done;
2345 __ shlq(rbx, Immediate(kSystemPointerSizeLog2));
2346 __ movq(kScratchRegister, rsp);
2347 __ subq(kScratchRegister, rbx);
2348
2349 // We are not trying to catch interruptions (i.e. debug break and
2350 // preemption) here, so check the "real stack limit".
2351 __ cmpq(kScratchRegister,
2352 __ StackLimitAsOperand(StackLimitKind::kRealStackLimit));
2353 __ j(above_equal, &done, Label::kNear);
2354 {
2355 FrameScope scope(masm, StackFrame::MANUAL);
2356 __ EnterFrame(StackFrame::INTERNAL);
2357 __ CallRuntime(Runtime::kThrowStackOverflow);
2358 }
2359 __ bind(&done);
2360 }
2361
2362 // Save Return Address and Receiver into registers.
2363 __ Pop(r8);
2364 __ Pop(r10);
2365
2366 // Push [[BoundArguments]] to the stack.
2367 {
2368 Label loop;
2369 __ LoadTaggedPointerField(
2370 rcx, FieldOperand(rdi, JSBoundFunction::kBoundArgumentsOffset));
2371 __ SmiUntagField(rbx, FieldOperand(rcx, FixedArray::kLengthOffset));
2372 __ addq(rax, rbx); // Adjust effective number of arguments.
2373 __ bind(&loop);
2374 // Instead of doing decl(rbx) here subtract kTaggedSize from the header
2375 // offset in order to be able to move decl(rbx) right before the loop
2376 // condition. This is necessary in order to avoid flags corruption by
2377 // pointer decompression code.
2378 __ LoadAnyTaggedField(
2379 r12, FieldOperand(rcx, rbx, times_tagged_size,
2380 FixedArray::kHeaderSize - kTaggedSize));
2381 __ Push(r12);
2382 __ decl(rbx);
2383 __ j(greater, &loop);
2384 }
2385
2386 // Recover Receiver and Return Address.
2387 __ Push(r10);
2388 __ Push(r8);
2389 }
2390 __ bind(&no_bound_arguments);
2391 }
2392
2393 } // namespace
2394
2395 // static
Generate_CallBoundFunctionImpl(MacroAssembler * masm)2396 void Builtins::Generate_CallBoundFunctionImpl(MacroAssembler* masm) {
2397 // ----------- S t a t e -------------
2398 // -- rax : the number of arguments (not including the receiver)
2399 // -- rdi : the function to call (checked to be a JSBoundFunction)
2400 // -----------------------------------
2401 __ AssertBoundFunction(rdi);
2402
2403 // Patch the receiver to [[BoundThis]].
2404 StackArgumentsAccessor args(rax);
2405 __ LoadAnyTaggedField(rbx,
2406 FieldOperand(rdi, JSBoundFunction::kBoundThisOffset));
2407 __ movq(args.GetReceiverOperand(), rbx);
2408
2409 // Push the [[BoundArguments]] onto the stack.
2410 Generate_PushBoundArguments(masm);
2411
2412 // Call the [[BoundTargetFunction]] via the Call builtin.
2413 __ LoadTaggedPointerField(
2414 rdi, FieldOperand(rdi, JSBoundFunction::kBoundTargetFunctionOffset));
2415 __ Jump(BUILTIN_CODE(masm->isolate(), Call_ReceiverIsAny),
2416 RelocInfo::CODE_TARGET);
2417 }
2418
2419 // static
Generate_Call(MacroAssembler * masm,ConvertReceiverMode mode)2420 void Builtins::Generate_Call(MacroAssembler* masm, ConvertReceiverMode mode) {
2421 // ----------- S t a t e -------------
2422 // -- rax : the number of arguments (not including the receiver)
2423 // -- rdi : the target to call (can be any Object)
2424 // -----------------------------------
2425 StackArgumentsAccessor args(rax);
2426
2427 Label non_callable;
2428 __ JumpIfSmi(rdi, &non_callable);
2429 __ CmpObjectType(rdi, JS_FUNCTION_TYPE, rcx);
2430 __ Jump(masm->isolate()->builtins()->CallFunction(mode),
2431 RelocInfo::CODE_TARGET, equal);
2432
2433 __ CmpInstanceType(rcx, JS_BOUND_FUNCTION_TYPE);
2434 __ Jump(BUILTIN_CODE(masm->isolate(), CallBoundFunction),
2435 RelocInfo::CODE_TARGET, equal);
2436
2437 // Check if target has a [[Call]] internal method.
2438 __ testb(FieldOperand(rcx, Map::kBitFieldOffset),
2439 Immediate(Map::Bits1::IsCallableBit::kMask));
2440 __ j(zero, &non_callable, Label::kNear);
2441
2442 // Check if target is a proxy and call CallProxy external builtin
2443 __ CmpInstanceType(rcx, JS_PROXY_TYPE);
2444 __ Jump(BUILTIN_CODE(masm->isolate(), CallProxy), RelocInfo::CODE_TARGET,
2445 equal);
2446
2447 // 2. Call to something else, which might have a [[Call]] internal method (if
2448 // not we raise an exception).
2449
2450 // Overwrite the original receiver with the (original) target.
2451 __ movq(args.GetReceiverOperand(), rdi);
2452 // Let the "call_as_function_delegate" take care of the rest.
2453 __ LoadNativeContextSlot(Context::CALL_AS_FUNCTION_DELEGATE_INDEX, rdi);
2454 __ Jump(masm->isolate()->builtins()->CallFunction(
2455 ConvertReceiverMode::kNotNullOrUndefined),
2456 RelocInfo::CODE_TARGET);
2457
2458 // 3. Call to something that is not callable.
2459 __ bind(&non_callable);
2460 {
2461 FrameScope scope(masm, StackFrame::INTERNAL);
2462 __ Push(rdi);
2463 __ CallRuntime(Runtime::kThrowCalledNonCallable);
2464 }
2465 }
2466
2467 // static
Generate_ConstructFunction(MacroAssembler * masm)2468 void Builtins::Generate_ConstructFunction(MacroAssembler* masm) {
2469 // ----------- S t a t e -------------
2470 // -- rax : the number of arguments (not including the receiver)
2471 // -- rdx : the new target (checked to be a constructor)
2472 // -- rdi : the constructor to call (checked to be a JSFunction)
2473 // -----------------------------------
2474 __ AssertConstructor(rdi);
2475 __ AssertFunction(rdi);
2476
2477 // Calling convention for function specific ConstructStubs require
2478 // rbx to contain either an AllocationSite or undefined.
2479 __ LoadRoot(rbx, RootIndex::kUndefinedValue);
2480
2481 // Jump to JSBuiltinsConstructStub or JSConstructStubGeneric.
2482 __ LoadTaggedPointerField(
2483 rcx, FieldOperand(rdi, JSFunction::kSharedFunctionInfoOffset));
2484 __ testl(FieldOperand(rcx, SharedFunctionInfo::kFlagsOffset),
2485 Immediate(SharedFunctionInfo::ConstructAsBuiltinBit::kMask));
2486 __ Jump(BUILTIN_CODE(masm->isolate(), JSBuiltinsConstructStub),
2487 RelocInfo::CODE_TARGET, not_zero);
2488
2489 __ Jump(BUILTIN_CODE(masm->isolate(), JSConstructStubGeneric),
2490 RelocInfo::CODE_TARGET);
2491 }
2492
2493 // static
Generate_ConstructBoundFunction(MacroAssembler * masm)2494 void Builtins::Generate_ConstructBoundFunction(MacroAssembler* masm) {
2495 // ----------- S t a t e -------------
2496 // -- rax : the number of arguments (not including the receiver)
2497 // -- rdx : the new target (checked to be a constructor)
2498 // -- rdi : the constructor to call (checked to be a JSBoundFunction)
2499 // -----------------------------------
2500 __ AssertConstructor(rdi);
2501 __ AssertBoundFunction(rdi);
2502
2503 // Push the [[BoundArguments]] onto the stack.
2504 Generate_PushBoundArguments(masm);
2505
2506 // Patch new.target to [[BoundTargetFunction]] if new.target equals target.
2507 {
2508 Label done;
2509 __ cmpq(rdi, rdx);
2510 __ j(not_equal, &done, Label::kNear);
2511 __ LoadTaggedPointerField(
2512 rdx, FieldOperand(rdi, JSBoundFunction::kBoundTargetFunctionOffset));
2513 __ bind(&done);
2514 }
2515
2516 // Construct the [[BoundTargetFunction]] via the Construct builtin.
2517 __ LoadTaggedPointerField(
2518 rdi, FieldOperand(rdi, JSBoundFunction::kBoundTargetFunctionOffset));
2519 __ Jump(BUILTIN_CODE(masm->isolate(), Construct), RelocInfo::CODE_TARGET);
2520 }
2521
2522 // static
Generate_Construct(MacroAssembler * masm)2523 void Builtins::Generate_Construct(MacroAssembler* masm) {
2524 // ----------- S t a t e -------------
2525 // -- rax : the number of arguments (not including the receiver)
2526 // -- rdx : the new target (either the same as the constructor or
2527 // the JSFunction on which new was invoked initially)
2528 // -- rdi : the constructor to call (can be any Object)
2529 // -----------------------------------
2530 StackArgumentsAccessor args(rax);
2531
2532 // Check if target is a Smi.
2533 Label non_constructor;
2534 __ JumpIfSmi(rdi, &non_constructor);
2535
2536 // Check if target has a [[Construct]] internal method.
2537 __ LoadTaggedPointerField(rcx, FieldOperand(rdi, HeapObject::kMapOffset));
2538 __ testb(FieldOperand(rcx, Map::kBitFieldOffset),
2539 Immediate(Map::Bits1::IsConstructorBit::kMask));
2540 __ j(zero, &non_constructor);
2541
2542 // Dispatch based on instance type.
2543 __ CmpInstanceType(rcx, JS_FUNCTION_TYPE);
2544 __ Jump(BUILTIN_CODE(masm->isolate(), ConstructFunction),
2545 RelocInfo::CODE_TARGET, equal);
2546
2547 // Only dispatch to bound functions after checking whether they are
2548 // constructors.
2549 __ CmpInstanceType(rcx, JS_BOUND_FUNCTION_TYPE);
2550 __ Jump(BUILTIN_CODE(masm->isolate(), ConstructBoundFunction),
2551 RelocInfo::CODE_TARGET, equal);
2552
2553 // Only dispatch to proxies after checking whether they are constructors.
2554 __ CmpInstanceType(rcx, JS_PROXY_TYPE);
2555 __ Jump(BUILTIN_CODE(masm->isolate(), ConstructProxy), RelocInfo::CODE_TARGET,
2556 equal);
2557
2558 // Called Construct on an exotic Object with a [[Construct]] internal method.
2559 {
2560 // Overwrite the original receiver with the (original) target.
2561 __ movq(args.GetReceiverOperand(), rdi);
2562 // Let the "call_as_constructor_delegate" take care of the rest.
2563 __ LoadNativeContextSlot(Context::CALL_AS_CONSTRUCTOR_DELEGATE_INDEX, rdi);
2564 __ Jump(masm->isolate()->builtins()->CallFunction(),
2565 RelocInfo::CODE_TARGET);
2566 }
2567
2568 // Called Construct on an Object that doesn't have a [[Construct]] internal
2569 // method.
2570 __ bind(&non_constructor);
2571 __ Jump(BUILTIN_CODE(masm->isolate(), ConstructedNonConstructable),
2572 RelocInfo::CODE_TARGET);
2573 }
2574
Generate_InterpreterOnStackReplacement(MacroAssembler * masm)2575 void Builtins::Generate_InterpreterOnStackReplacement(MacroAssembler* masm) {
2576 {
2577 FrameScope scope(masm, StackFrame::INTERNAL);
2578 __ CallRuntime(Runtime::kCompileForOnStackReplacement);
2579 }
2580
2581 Label skip;
2582 // If the code object is null, just return to the caller.
2583 __ testq(rax, rax);
2584 __ j(not_equal, &skip, Label::kNear);
2585 __ ret(0);
2586
2587 __ bind(&skip);
2588
2589 // Drop the handler frame that is be sitting on top of the actual
2590 // JavaScript frame. This is the case then OSR is triggered from bytecode.
2591 __ leave();
2592
2593 // Load deoptimization data from the code object.
2594 __ LoadTaggedPointerField(rbx,
2595 FieldOperand(rax, Code::kDeoptimizationDataOffset));
2596
2597 // Load the OSR entrypoint offset from the deoptimization data.
2598 __ SmiUntagField(
2599 rbx, FieldOperand(rbx, FixedArray::OffsetOfElementAt(
2600 DeoptimizationData::kOsrPcOffsetIndex)));
2601
2602 // Compute the target address = code_obj + header_size + osr_offset
2603 __ leaq(rax, FieldOperand(rax, rbx, times_1, Code::kHeaderSize));
2604
2605 // Overwrite the return address on the stack.
2606 __ movq(StackOperandForReturnAddress(0), rax);
2607
2608 // And "return" to the OSR entry point of the function.
2609 __ ret(0);
2610 }
2611
Generate_WasmCompileLazy(MacroAssembler * masm)2612 void Builtins::Generate_WasmCompileLazy(MacroAssembler* masm) {
2613 // The function index was pushed to the stack by the caller as int32.
2614 __ Pop(r11);
2615 // Convert to Smi for the runtime call.
2616 __ SmiTag(r11);
2617 {
2618 HardAbortScope hard_abort(masm); // Avoid calls to Abort.
2619 FrameScope scope(masm, StackFrame::WASM_COMPILE_LAZY);
2620
2621 // Save all parameter registers (see wasm-linkage.cc). They might be
2622 // overwritten in the runtime call below. We don't have any callee-saved
2623 // registers in wasm, so no need to store anything else.
2624 static_assert(WasmCompileLazyFrameConstants::kNumberOfSavedGpParamRegs ==
2625 arraysize(wasm::kGpParamRegisters),
2626 "frame size mismatch");
2627 for (Register reg : wasm::kGpParamRegisters) {
2628 __ Push(reg);
2629 }
2630 static_assert(WasmCompileLazyFrameConstants::kNumberOfSavedFpParamRegs ==
2631 arraysize(wasm::kFpParamRegisters),
2632 "frame size mismatch");
2633 __ AllocateStackSpace(kSimd128Size * arraysize(wasm::kFpParamRegisters));
2634 int offset = 0;
2635 for (DoubleRegister reg : wasm::kFpParamRegisters) {
2636 __ movdqu(Operand(rsp, offset), reg);
2637 offset += kSimd128Size;
2638 }
2639
2640 // Push the Wasm instance as an explicit argument to WasmCompileLazy.
2641 __ Push(kWasmInstanceRegister);
2642 // Push the function index as second argument.
2643 __ Push(r11);
2644 // Initialize the JavaScript context with 0. CEntry will use it to
2645 // set the current context on the isolate.
2646 __ Move(kContextRegister, Smi::zero());
2647 __ CallRuntime(Runtime::kWasmCompileLazy, 2);
2648 // The entrypoint address is the return value.
2649 __ movq(r11, kReturnRegister0);
2650
2651 // Restore registers.
2652 for (DoubleRegister reg : base::Reversed(wasm::kFpParamRegisters)) {
2653 offset -= kSimd128Size;
2654 __ movdqu(reg, Operand(rsp, offset));
2655 }
2656 DCHECK_EQ(0, offset);
2657 __ addq(rsp, Immediate(kSimd128Size * arraysize(wasm::kFpParamRegisters)));
2658 for (Register reg : base::Reversed(wasm::kGpParamRegisters)) {
2659 __ Pop(reg);
2660 }
2661 }
2662 // Finally, jump to the entrypoint.
2663 __ jmp(r11);
2664 }
2665
Generate_WasmDebugBreak(MacroAssembler * masm)2666 void Builtins::Generate_WasmDebugBreak(MacroAssembler* masm) {
2667 HardAbortScope hard_abort(masm); // Avoid calls to Abort.
2668 {
2669 FrameScope scope(masm, StackFrame::WASM_DEBUG_BREAK);
2670
2671 // Save all parameter registers. They might hold live values, we restore
2672 // them after the runtime call.
2673 for (int reg_code : base::bits::IterateBitsBackwards(
2674 WasmDebugBreakFrameConstants::kPushedGpRegs)) {
2675 __ Push(Register::from_code(reg_code));
2676 }
2677
2678 constexpr int kFpStackSize =
2679 kSimd128Size * WasmDebugBreakFrameConstants::kNumPushedFpRegisters;
2680 __ AllocateStackSpace(kFpStackSize);
2681 int offset = kFpStackSize;
2682 for (int reg_code : base::bits::IterateBitsBackwards(
2683 WasmDebugBreakFrameConstants::kPushedFpRegs)) {
2684 offset -= kSimd128Size;
2685 __ movdqu(Operand(rsp, offset), DoubleRegister::from_code(reg_code));
2686 }
2687
2688 // Initialize the JavaScript context with 0. CEntry will use it to
2689 // set the current context on the isolate.
2690 __ Move(kContextRegister, Smi::zero());
2691 __ CallRuntime(Runtime::kWasmDebugBreak, 0);
2692
2693 // Restore registers.
2694 for (int reg_code :
2695 base::bits::IterateBits(WasmDebugBreakFrameConstants::kPushedFpRegs)) {
2696 __ movdqu(DoubleRegister::from_code(reg_code), Operand(rsp, offset));
2697 offset += kSimd128Size;
2698 }
2699 __ addq(rsp, Immediate(kFpStackSize));
2700 for (int reg_code :
2701 base::bits::IterateBits(WasmDebugBreakFrameConstants::kPushedGpRegs)) {
2702 __ Pop(Register::from_code(reg_code));
2703 }
2704 }
2705
2706 __ ret(0);
2707 }
2708
Generate_CEntry(MacroAssembler * masm,int result_size,SaveFPRegsMode save_doubles,ArgvMode argv_mode,bool builtin_exit_frame)2709 void Builtins::Generate_CEntry(MacroAssembler* masm, int result_size,
2710 SaveFPRegsMode save_doubles, ArgvMode argv_mode,
2711 bool builtin_exit_frame) {
2712 // rax: number of arguments including receiver
2713 // rbx: pointer to C function (C callee-saved)
2714 // rbp: frame pointer of calling JS frame (restored after C call)
2715 // rsp: stack pointer (restored after C call)
2716 // rsi: current context (restored)
2717 //
2718 // If argv_mode == kArgvInRegister:
2719 // r15: pointer to the first argument
2720
2721 #ifdef V8_TARGET_OS_WIN
2722 // Windows 64-bit ABI passes arguments in rcx, rdx, r8, r9. It requires the
2723 // stack to be aligned to 16 bytes. It only allows a single-word to be
2724 // returned in register rax. Larger return sizes must be written to an address
2725 // passed as a hidden first argument.
2726 const Register kCCallArg0 = rcx;
2727 const Register kCCallArg1 = rdx;
2728 const Register kCCallArg2 = r8;
2729 const Register kCCallArg3 = r9;
2730 const int kArgExtraStackSpace = 2;
2731 const int kMaxRegisterResultSize = 1;
2732 #else
2733 // GCC / Clang passes arguments in rdi, rsi, rdx, rcx, r8, r9. Simple results
2734 // are returned in rax, and a struct of two pointers are returned in rax+rdx.
2735 // Larger return sizes must be written to an address passed as a hidden first
2736 // argument.
2737 const Register kCCallArg0 = rdi;
2738 const Register kCCallArg1 = rsi;
2739 const Register kCCallArg2 = rdx;
2740 const Register kCCallArg3 = rcx;
2741 const int kArgExtraStackSpace = 0;
2742 const int kMaxRegisterResultSize = 2;
2743 #endif // V8_TARGET_OS_WIN
2744
2745 // Enter the exit frame that transitions from JavaScript to C++.
2746 int arg_stack_space =
2747 kArgExtraStackSpace +
2748 (result_size <= kMaxRegisterResultSize ? 0 : result_size);
2749 if (argv_mode == kArgvInRegister) {
2750 DCHECK(save_doubles == kDontSaveFPRegs);
2751 DCHECK(!builtin_exit_frame);
2752 __ EnterApiExitFrame(arg_stack_space);
2753 // Move argc into r14 (argv is already in r15).
2754 __ movq(r14, rax);
2755 } else {
2756 __ EnterExitFrame(
2757 arg_stack_space, save_doubles == kSaveFPRegs,
2758 builtin_exit_frame ? StackFrame::BUILTIN_EXIT : StackFrame::EXIT);
2759 }
2760
2761 // rbx: pointer to builtin function (C callee-saved).
2762 // rbp: frame pointer of exit frame (restored after C call).
2763 // rsp: stack pointer (restored after C call).
2764 // r14: number of arguments including receiver (C callee-saved).
2765 // r15: argv pointer (C callee-saved).
2766
2767 // Check stack alignment.
2768 if (FLAG_debug_code) {
2769 __ CheckStackAlignment();
2770 }
2771
2772 // Call C function. The arguments object will be created by stubs declared by
2773 // DECLARE_RUNTIME_FUNCTION().
2774 if (result_size <= kMaxRegisterResultSize) {
2775 // Pass a pointer to the Arguments object as the first argument.
2776 // Return result in single register (rax), or a register pair (rax, rdx).
2777 __ movq(kCCallArg0, r14); // argc.
2778 __ movq(kCCallArg1, r15); // argv.
2779 __ Move(kCCallArg2, ExternalReference::isolate_address(masm->isolate()));
2780 } else {
2781 DCHECK_LE(result_size, 2);
2782 // Pass a pointer to the result location as the first argument.
2783 __ leaq(kCCallArg0, StackSpaceOperand(kArgExtraStackSpace));
2784 // Pass a pointer to the Arguments object as the second argument.
2785 __ movq(kCCallArg1, r14); // argc.
2786 __ movq(kCCallArg2, r15); // argv.
2787 __ Move(kCCallArg3, ExternalReference::isolate_address(masm->isolate()));
2788 }
2789 __ call(rbx);
2790
2791 if (result_size > kMaxRegisterResultSize) {
2792 // Read result values stored on stack. Result is stored
2793 // above the the two Arguments object slots on Win64.
2794 DCHECK_LE(result_size, 2);
2795 __ movq(kReturnRegister0, StackSpaceOperand(kArgExtraStackSpace + 0));
2796 __ movq(kReturnRegister1, StackSpaceOperand(kArgExtraStackSpace + 1));
2797 }
2798 // Result is in rax or rdx:rax - do not destroy these registers!
2799
2800 // Check result for exception sentinel.
2801 Label exception_returned;
2802 __ CompareRoot(rax, RootIndex::kException);
2803 __ j(equal, &exception_returned);
2804
2805 // Check that there is no pending exception, otherwise we
2806 // should have returned the exception sentinel.
2807 if (FLAG_debug_code) {
2808 Label okay;
2809 __ LoadRoot(r14, RootIndex::kTheHoleValue);
2810 ExternalReference pending_exception_address = ExternalReference::Create(
2811 IsolateAddressId::kPendingExceptionAddress, masm->isolate());
2812 Operand pending_exception_operand =
2813 masm->ExternalReferenceAsOperand(pending_exception_address);
2814 __ cmp_tagged(r14, pending_exception_operand);
2815 __ j(equal, &okay, Label::kNear);
2816 __ int3();
2817 __ bind(&okay);
2818 }
2819
2820 // Exit the JavaScript to C++ exit frame.
2821 __ LeaveExitFrame(save_doubles == kSaveFPRegs, argv_mode == kArgvOnStack);
2822 __ ret(0);
2823
2824 // Handling of exception.
2825 __ bind(&exception_returned);
2826
2827 ExternalReference pending_handler_context_address = ExternalReference::Create(
2828 IsolateAddressId::kPendingHandlerContextAddress, masm->isolate());
2829 ExternalReference pending_handler_entrypoint_address =
2830 ExternalReference::Create(
2831 IsolateAddressId::kPendingHandlerEntrypointAddress, masm->isolate());
2832 ExternalReference pending_handler_fp_address = ExternalReference::Create(
2833 IsolateAddressId::kPendingHandlerFPAddress, masm->isolate());
2834 ExternalReference pending_handler_sp_address = ExternalReference::Create(
2835 IsolateAddressId::kPendingHandlerSPAddress, masm->isolate());
2836
2837 // Ask the runtime for help to determine the handler. This will set rax to
2838 // contain the current pending exception, don't clobber it.
2839 ExternalReference find_handler =
2840 ExternalReference::Create(Runtime::kUnwindAndFindExceptionHandler);
2841 {
2842 FrameScope scope(masm, StackFrame::MANUAL);
2843 __ movq(arg_reg_1, Immediate(0)); // argc.
2844 __ movq(arg_reg_2, Immediate(0)); // argv.
2845 __ Move(arg_reg_3, ExternalReference::isolate_address(masm->isolate()));
2846 __ PrepareCallCFunction(3);
2847 __ CallCFunction(find_handler, 3);
2848 }
2849 // Retrieve the handler context, SP and FP.
2850 __ movq(rsi,
2851 masm->ExternalReferenceAsOperand(pending_handler_context_address));
2852 __ movq(rsp, masm->ExternalReferenceAsOperand(pending_handler_sp_address));
2853 __ movq(rbp, masm->ExternalReferenceAsOperand(pending_handler_fp_address));
2854
2855 // If the handler is a JS frame, restore the context to the frame. Note that
2856 // the context will be set to (rsi == 0) for non-JS frames.
2857 Label skip;
2858 __ testq(rsi, rsi);
2859 __ j(zero, &skip, Label::kNear);
2860 __ movq(Operand(rbp, StandardFrameConstants::kContextOffset), rsi);
2861 __ bind(&skip);
2862
2863 // Reset the masking register. This is done independent of the underlying
2864 // feature flag {FLAG_untrusted_code_mitigations} to make the snapshot work
2865 // with both configurations. It is safe to always do this, because the
2866 // underlying register is caller-saved and can be arbitrarily clobbered.
2867 __ ResetSpeculationPoisonRegister();
2868
2869 // Compute the handler entry address and jump to it.
2870 __ movq(rdi,
2871 masm->ExternalReferenceAsOperand(pending_handler_entrypoint_address));
2872 __ jmp(rdi);
2873 }
2874
Generate_DoubleToI(MacroAssembler * masm)2875 void Builtins::Generate_DoubleToI(MacroAssembler* masm) {
2876 Label check_negative, process_64_bits, done;
2877
2878 // Account for return address and saved regs.
2879 const int kArgumentOffset = 4 * kSystemPointerSize;
2880
2881 MemOperand mantissa_operand(MemOperand(rsp, kArgumentOffset));
2882 MemOperand exponent_operand(
2883 MemOperand(rsp, kArgumentOffset + kDoubleSize / 2));
2884
2885 // The result is returned on the stack.
2886 MemOperand return_operand = mantissa_operand;
2887
2888 Register scratch1 = rbx;
2889
2890 // Since we must use rcx for shifts below, use some other register (rax)
2891 // to calculate the result if ecx is the requested return register.
2892 Register result_reg = rax;
2893 // Save ecx if it isn't the return register and therefore volatile, or if it
2894 // is the return register, then save the temp register we use in its stead
2895 // for the result.
2896 Register save_reg = rax;
2897 __ pushq(rcx);
2898 __ pushq(scratch1);
2899 __ pushq(save_reg);
2900
2901 __ movl(scratch1, mantissa_operand);
2902 __ Movsd(kScratchDoubleReg, mantissa_operand);
2903 __ movl(rcx, exponent_operand);
2904
2905 __ andl(rcx, Immediate(HeapNumber::kExponentMask));
2906 __ shrl(rcx, Immediate(HeapNumber::kExponentShift));
2907 __ leal(result_reg, MemOperand(rcx, -HeapNumber::kExponentBias));
2908 __ cmpl(result_reg, Immediate(HeapNumber::kMantissaBits));
2909 __ j(below, &process_64_bits, Label::kNear);
2910
2911 // Result is entirely in lower 32-bits of mantissa
2912 int delta = HeapNumber::kExponentBias + Double::kPhysicalSignificandSize;
2913 __ subl(rcx, Immediate(delta));
2914 __ xorl(result_reg, result_reg);
2915 __ cmpl(rcx, Immediate(31));
2916 __ j(above, &done, Label::kNear);
2917 __ shll_cl(scratch1);
2918 __ jmp(&check_negative, Label::kNear);
2919
2920 __ bind(&process_64_bits);
2921 __ Cvttsd2siq(result_reg, kScratchDoubleReg);
2922 __ jmp(&done, Label::kNear);
2923
2924 // If the double was negative, negate the integer result.
2925 __ bind(&check_negative);
2926 __ movl(result_reg, scratch1);
2927 __ negl(result_reg);
2928 __ cmpl(exponent_operand, Immediate(0));
2929 __ cmovl(greater, result_reg, scratch1);
2930
2931 // Restore registers
2932 __ bind(&done);
2933 __ movl(return_operand, result_reg);
2934 __ popq(save_reg);
2935 __ popq(scratch1);
2936 __ popq(rcx);
2937 __ ret(0);
2938 }
2939
2940 namespace {
2941 // Helper functions for the GenericJSToWasmWrapper.
PrepareForBuiltinCall(MacroAssembler * masm,MemOperand GCScanSlotPlace,const int GCScanSlotCount,Register current_param,Register param_limit,Register current_int_param_slot,Register current_float_param_slot,Register valuetypes_array_ptr,Register wasm_instance,Register function_data)2942 void PrepareForBuiltinCall(MacroAssembler* masm, MemOperand GCScanSlotPlace,
2943 const int GCScanSlotCount, Register current_param,
2944 Register param_limit,
2945 Register current_int_param_slot,
2946 Register current_float_param_slot,
2947 Register valuetypes_array_ptr,
2948 Register wasm_instance, Register function_data) {
2949 // Pushes and puts the values in order onto the stack before builtin calls for
2950 // the GenericJSToWasmWrapper.
2951 __ movq(GCScanSlotPlace, Immediate(GCScanSlotCount));
2952 __ pushq(current_param);
2953 __ pushq(param_limit);
2954 __ pushq(current_int_param_slot);
2955 __ pushq(current_float_param_slot);
2956 __ pushq(valuetypes_array_ptr);
2957 __ pushq(wasm_instance);
2958 __ pushq(function_data);
2959 // We had to prepare the parameters for the Call: we have to put the context
2960 // into rsi.
2961 __ LoadAnyTaggedField(
2962 rsi,
2963 MemOperand(wasm_instance, wasm::ObjectAccess::ToTagged(
2964 WasmInstanceObject::kNativeContextOffset)));
2965 }
2966
RestoreAfterBuiltinCall(MacroAssembler * masm,Register function_data,Register wasm_instance,Register valuetypes_array_ptr,Register current_float_param_slot,Register current_int_param_slot,Register param_limit,Register current_param)2967 void RestoreAfterBuiltinCall(MacroAssembler* masm, Register function_data,
2968 Register wasm_instance,
2969 Register valuetypes_array_ptr,
2970 Register current_float_param_slot,
2971 Register current_int_param_slot,
2972 Register param_limit, Register current_param) {
2973 // Pop and load values from the stack in order into the registers after
2974 // builtin calls for the GenericJSToWasmWrapper.
2975 __ popq(function_data);
2976 __ popq(wasm_instance);
2977 __ popq(valuetypes_array_ptr);
2978 __ popq(current_float_param_slot);
2979 __ popq(current_int_param_slot);
2980 __ popq(param_limit);
2981 __ popq(current_param);
2982 }
2983 } // namespace
2984
Generate_GenericJSToWasmWrapper(MacroAssembler * masm)2985 void Builtins::Generate_GenericJSToWasmWrapper(MacroAssembler* masm) {
2986 // Set up the stackframe.
2987 __ EnterFrame(StackFrame::JS_TO_WASM);
2988
2989 // -------------------------------------------
2990 // Compute offsets and prepare for GC.
2991 // -------------------------------------------
2992 // We will have to save a value indicating the GC the number
2993 // of values on the top of the stack that have to be scanned before calling
2994 // the Wasm function.
2995 constexpr int kFrameMarkerOffset = -kSystemPointerSize;
2996 constexpr int kGCScanSlotCountOffset =
2997 kFrameMarkerOffset - kSystemPointerSize;
2998 constexpr int kParamCountOffset = kGCScanSlotCountOffset - kSystemPointerSize;
2999 constexpr int kReturnCountOffset = kParamCountOffset - kSystemPointerSize;
3000 constexpr int kValueTypesArrayStartOffset =
3001 kReturnCountOffset - kSystemPointerSize;
3002 // We set and use this slot only when moving parameters into the parameter
3003 // registers (so no GC scan is needed).
3004 constexpr int kFunctionDataOffset =
3005 kValueTypesArrayStartOffset - kSystemPointerSize;
3006 constexpr int kLastSpillOffset = kFunctionDataOffset;
3007 constexpr int kNumSpillSlots = 5;
3008 __ subq(rsp, Immediate(kNumSpillSlots * kSystemPointerSize));
3009
3010 // -------------------------------------------
3011 // Load the Wasm exported function data and the Wasm instance.
3012 // -------------------------------------------
3013 Register closure = rdi;
3014 Register shared_function_info = closure;
3015 __ LoadAnyTaggedField(
3016 shared_function_info,
3017 MemOperand(
3018 closure,
3019 wasm::ObjectAccess::SharedFunctionInfoOffsetInTaggedJSFunction()));
3020 closure = no_reg;
3021 Register function_data = shared_function_info;
3022 __ LoadAnyTaggedField(
3023 function_data,
3024 MemOperand(shared_function_info,
3025 SharedFunctionInfo::kFunctionDataOffset - kHeapObjectTag));
3026 shared_function_info = no_reg;
3027
3028 Register wasm_instance = rsi;
3029 __ LoadAnyTaggedField(
3030 wasm_instance,
3031 MemOperand(function_data,
3032 WasmExportedFunctionData::kInstanceOffset - kHeapObjectTag));
3033
3034 // -------------------------------------------
3035 // Increment the call count in function data.
3036 // -------------------------------------------
3037 __ SmiAddConstant(
3038 MemOperand(function_data,
3039 WasmExportedFunctionData::kCallCountOffset - kHeapObjectTag),
3040 Smi::FromInt(1));
3041
3042 // -------------------------------------------
3043 // Check if the call count reached the threshold.
3044 // -------------------------------------------
3045 Label compile_wrapper, compile_wrapper_done;
3046 __ SmiCompare(
3047 MemOperand(function_data,
3048 WasmExportedFunctionData::kCallCountOffset - kHeapObjectTag),
3049 Smi::FromInt(wasm::kGenericWrapperThreshold));
3050 __ j(greater_equal, &compile_wrapper);
3051 __ bind(&compile_wrapper_done);
3052
3053 // -------------------------------------------
3054 // Load values from the signature.
3055 // -------------------------------------------
3056 Register foreign_signature = r11;
3057 __ LoadAnyTaggedField(
3058 foreign_signature,
3059 MemOperand(function_data,
3060 WasmExportedFunctionData::kSignatureOffset - kHeapObjectTag));
3061 Register signature = foreign_signature;
3062 __ LoadExternalPointerField(
3063 signature,
3064 FieldOperand(foreign_signature, Foreign::kForeignAddressOffset),
3065 kForeignForeignAddressTag);
3066 foreign_signature = no_reg;
3067 Register return_count = r8;
3068 __ movq(return_count,
3069 MemOperand(signature, wasm::FunctionSig::kReturnCountOffset));
3070 Register param_count = rcx;
3071 __ movq(param_count,
3072 MemOperand(signature, wasm::FunctionSig::kParameterCountOffset));
3073 Register valuetypes_array_ptr = signature;
3074 __ movq(valuetypes_array_ptr,
3075 MemOperand(signature, wasm::FunctionSig::kRepsOffset));
3076 signature = no_reg;
3077
3078 // -------------------------------------------
3079 // Store signature-related values to the stack.
3080 // -------------------------------------------
3081 // We store values on the stack to restore them after function calls.
3082 // We cannot push values onto the stack right before the wasm call. The wasm
3083 // function expects the parameters, that didn't fit into the registers, on the
3084 // top of the stack.
3085 __ movq(MemOperand(rbp, kParamCountOffset), param_count);
3086 __ movq(MemOperand(rbp, kReturnCountOffset), return_count);
3087 __ movq(MemOperand(rbp, kValueTypesArrayStartOffset), valuetypes_array_ptr);
3088
3089 // -------------------------------------------
3090 // Parameter handling.
3091 // -------------------------------------------
3092 Label prepare_for_wasm_call;
3093 __ Cmp(param_count, 0);
3094
3095 // IF we have 0 params: jump through parameter handling.
3096 __ j(equal, &prepare_for_wasm_call);
3097
3098 // -------------------------------------------
3099 // Create 2 sections for integer and float params.
3100 // -------------------------------------------
3101 // We will create 2 sections on the stack for the evaluated parameters:
3102 // Integer and Float section, both with parameter count size. We will place
3103 // the parameters into these sections depending on their valuetype. This way
3104 // we can easily fill the general purpose and floating point parameter
3105 // registers and place the remaining parameters onto the stack in proper order
3106 // for the Wasm function. These remaining params are the final stack
3107 // parameters for the call to WebAssembly. Example of the stack layout after
3108 // processing 2 int and 1 float parameters when param_count is 4.
3109 // +-----------------+
3110 // | rbp |
3111 // |-----------------|-------------------------------
3112 // | | Slots we defined
3113 // | Saved values | when setting up
3114 // | | the stack
3115 // | |
3116 // +-Integer section-+--- <--- start_int_section ----
3117 // | 1st int param |
3118 // |- - - - - - - - -|
3119 // | 2nd int param |
3120 // |- - - - - - - - -| <----- current_int_param_slot
3121 // | | (points to the stackslot
3122 // |- - - - - - - - -| where the next int param should be placed)
3123 // | |
3124 // +--Float section--+--- <--- start_float_section --
3125 // | 1st float param |
3126 // |- - - - - - - - -| <---- current_float_param_slot
3127 // | | (points to the stackslot
3128 // |- - - - - - - - -| where the next float param should be placed)
3129 // | |
3130 // |- - - - - - - - -|
3131 // | |
3132 // +---Final stack---+------------------------------
3133 // +-parameters for--+------------------------------
3134 // +-the Wasm call---+------------------------------
3135 // | . . . |
3136
3137 constexpr int kIntegerSectionStartOffset =
3138 kLastSpillOffset - kSystemPointerSize;
3139 // For Integer section.
3140 // Set the current_int_param_slot to point to the start of the section.
3141 Register current_int_param_slot = r14;
3142 __ leaq(current_int_param_slot, MemOperand(rsp, -kSystemPointerSize));
3143 Register params_size = param_count;
3144 param_count = no_reg;
3145 __ shlq(params_size, Immediate(kSystemPointerSizeLog2));
3146 __ subq(rsp, params_size);
3147
3148 // For Float section.
3149 // Set the current_float_param_slot to point to the start of the section.
3150 Register current_float_param_slot = r15;
3151 __ leaq(current_float_param_slot, MemOperand(rsp, -kSystemPointerSize));
3152 __ subq(rsp, params_size);
3153 params_size = no_reg;
3154 param_count = rcx;
3155 __ movq(param_count, MemOperand(rbp, kParamCountOffset));
3156
3157 // -------------------------------------------
3158 // Set up for the param evaluation loop.
3159 // -------------------------------------------
3160 // We will loop through the params starting with the 1st param.
3161 // The order of processing the params is important. We have to evaluate them
3162 // in an increasing order.
3163 // Not reversed Reversed
3164 // +-----------------+------+-----------------+---------------
3165 // | receiver | | param n |
3166 // |- - - - - - - - -| |- - - - - - - - -|
3167 // | param 1 | | param n-1 | Caller
3168 // | ... | | ... | frame slots
3169 // | param n-1 | | param 1 |
3170 // |- - - - - - - - -| |- - - - - - - - -|
3171 // | param n | | receiver |
3172 // -+-----------------+------+-----------------+---------------
3173 // | return addr | | return addr |
3174 // |- - - - - - - - -|<-FP->|- - - - - - - - -|
3175 // | rbp | | rbp | Spill slots
3176 // |- - - - - - - - -| |- - - - - - - - -|
3177 //
3178 // [rbp + current_param] gives us the parameter we are processing.
3179 // We iterate through half-open interval <1st param, [rbp + param_limit]).
3180
3181 Register current_param = rbx;
3182 Register param_limit = rdx;
3183 constexpr int kReceiverOnStackSize = kSystemPointerSize;
3184 __ movq(current_param,
3185 Immediate(kFPOnStackSize + kPCOnStackSize + kReceiverOnStackSize));
3186 __ movq(param_limit, param_count);
3187 __ shlq(param_limit, Immediate(kSystemPointerSizeLog2));
3188 __ addq(param_limit,
3189 Immediate(kFPOnStackSize + kPCOnStackSize + kReceiverOnStackSize));
3190 const int increment = kSystemPointerSize;
3191 Register param = rax;
3192 // We have to check the types of the params. The ValueType array contains
3193 // first the return then the param types.
3194 constexpr int kValueTypeSize = sizeof(wasm::ValueType);
3195 STATIC_ASSERT(kValueTypeSize == 4);
3196 const int32_t kValueTypeSizeLog2 = log2(kValueTypeSize);
3197 // Set the ValueType array pointer to point to the first parameter.
3198 Register returns_size = return_count;
3199 return_count = no_reg;
3200 __ shlq(returns_size, Immediate(kValueTypeSizeLog2));
3201 __ addq(valuetypes_array_ptr, returns_size);
3202 returns_size = no_reg;
3203 Register valuetype = r12;
3204
3205 // -------------------------------------------
3206 // Param evaluation loop.
3207 // -------------------------------------------
3208 Label loop_through_params;
3209 __ bind(&loop_through_params);
3210
3211 __ movq(param, MemOperand(rbp, current_param, times_1, 0));
3212 __ movl(valuetype,
3213 Operand(valuetypes_array_ptr, wasm::ValueType::bit_field_offset()));
3214
3215 // -------------------------------------------
3216 // Param conversion.
3217 // -------------------------------------------
3218 // If param is a Smi we can easily convert it. Otherwise we'll call a builtin
3219 // for conversion.
3220 Label convert_param;
3221 __ cmpq(valuetype, Immediate(wasm::kWasmI32.raw_bit_field()));
3222 __ j(not_equal, &convert_param);
3223 __ JumpIfNotSmi(param, &convert_param);
3224 // Change the paramfrom Smi to int32.
3225 __ SmiUntag(param);
3226 // Zero extend.
3227 __ movl(param, param);
3228 // Place the param into the proper slot in Integer section.
3229 __ movq(MemOperand(current_int_param_slot, 0), param);
3230 __ subq(current_int_param_slot, Immediate(kSystemPointerSize));
3231
3232 // -------------------------------------------
3233 // Param conversion done.
3234 // -------------------------------------------
3235 Label param_conversion_done;
3236 __ bind(¶m_conversion_done);
3237
3238 __ addq(current_param, Immediate(increment));
3239 __ addq(valuetypes_array_ptr, Immediate(kValueTypeSize));
3240
3241 __ cmpq(current_param, param_limit);
3242 __ j(not_equal, &loop_through_params);
3243
3244 // -------------------------------------------
3245 // Move the parameters into the proper param registers.
3246 // -------------------------------------------
3247 // The Wasm function expects that the params can be popped from the top of the
3248 // stack in an increasing order.
3249 // We can always move the values on the beginning of the sections into the GP
3250 // or FP parameter registers. If the parameter count is less than the number
3251 // of parameter registers, we may move values into the registers that are not
3252 // in the section.
3253 // ----------- S t a t e -------------
3254 // -- r8 : start_int_section
3255 // -- rdi : start_float_section
3256 // -- r14 : current_int_param_slot
3257 // -- r15 : current_float_param_slot
3258 // -- r11 : valuetypes_array_ptr
3259 // -- r12 : valuetype
3260 // -- rsi : wasm_instance
3261 // -- GpParamRegisters = rax, rdx, rcx, rbx, r9
3262 // -----------------------------------
3263
3264 Register temp_params_size = rax;
3265 __ movq(temp_params_size, MemOperand(rbp, kParamCountOffset));
3266 __ shlq(temp_params_size, Immediate(kSystemPointerSizeLog2));
3267 // We want to use the register of the function_data = rdi.
3268 __ movq(MemOperand(rbp, kFunctionDataOffset), function_data);
3269 Register start_float_section = function_data;
3270 function_data = no_reg;
3271 __ movq(start_float_section, rbp);
3272 __ addq(start_float_section, Immediate(kIntegerSectionStartOffset));
3273 __ subq(start_float_section, temp_params_size);
3274 temp_params_size = no_reg;
3275 // Fill the FP param registers.
3276 __ Movsd(xmm1, MemOperand(start_float_section, 0));
3277 __ Movsd(xmm2, MemOperand(start_float_section, -kSystemPointerSize));
3278 __ Movsd(xmm3, MemOperand(start_float_section, -2 * kSystemPointerSize));
3279 __ Movsd(xmm4, MemOperand(start_float_section, -3 * kSystemPointerSize));
3280 __ Movsd(xmm5, MemOperand(start_float_section, -4 * kSystemPointerSize));
3281 __ Movsd(xmm6, MemOperand(start_float_section, -5 * kSystemPointerSize));
3282 // We want the start to point to the last properly placed param.
3283 __ subq(start_float_section, Immediate(5 * kSystemPointerSize));
3284
3285 Register start_int_section = r8;
3286 __ movq(start_int_section, rbp);
3287 __ addq(start_int_section, Immediate(kIntegerSectionStartOffset));
3288 // Fill the GP param registers.
3289 __ movq(rax, MemOperand(start_int_section, 0));
3290 __ movq(rdx, MemOperand(start_int_section, -kSystemPointerSize));
3291 __ movq(rcx, MemOperand(start_int_section, -2 * kSystemPointerSize));
3292 __ movq(rbx, MemOperand(start_int_section, -3 * kSystemPointerSize));
3293 __ movq(r9, MemOperand(start_int_section, -4 * kSystemPointerSize));
3294 // We want the start to point to the last properly placed param.
3295 __ subq(start_int_section, Immediate(4 * kSystemPointerSize));
3296
3297 // -------------------------------------------
3298 // Place the final stack parameters to the proper place.
3299 // -------------------------------------------
3300 // We want the current_param_slot (insertion) pointers to point at the last
3301 // param of the section instead of the next free slot.
3302 __ addq(current_int_param_slot, Immediate(kSystemPointerSize));
3303 __ addq(current_float_param_slot, Immediate(kSystemPointerSize));
3304
3305 // -------------------------------------------
3306 // Final stack parameters loop.
3307 // -------------------------------------------
3308 // The parameters that didn't fit into the registers should be placed on the
3309 // top of the stack contiguously. The interval of parameters between the
3310 // start_section and the current_param_slot pointers define the remaining
3311 // parameters of the section.
3312 // We can iterate through the valuetypes array to decide from which section we
3313 // need to push the parameter onto the top of the stack. By iterating in a
3314 // reversed order we can easily pick the last parameter of the proper section.
3315 // The parameter of the section is pushed on the top of the stack only if the
3316 // interval of remaining params is not empty. This way we ensure that only
3317 // params that didn't fit into param registers are pushed again.
3318
3319 Label loop_through_valuetypes;
3320 __ bind(&loop_through_valuetypes);
3321
3322 // We iterated through the valuetypes array, we are one field over the end in
3323 // the beginning. Also, we have to decrement it in each iteration.
3324 __ subq(valuetypes_array_ptr, Immediate(kValueTypeSize));
3325
3326 // Check if there are still remaining integer params.
3327 Label continue_loop;
3328 __ cmpq(start_int_section, current_int_param_slot);
3329 // If there are remaining integer params.
3330 __ j(greater, &continue_loop);
3331
3332 // Check if there are still remaining float params.
3333 __ cmpq(start_float_section, current_float_param_slot);
3334 // If there aren't any params remaining.
3335 Label params_done;
3336 __ j(less_equal, ¶ms_done);
3337
3338 __ bind(&continue_loop);
3339 __ movl(valuetype,
3340 Operand(valuetypes_array_ptr, wasm::ValueType::bit_field_offset()));
3341 Label place_integer_param;
3342 Label place_float_param;
3343 __ cmpq(valuetype, Immediate(wasm::kWasmI32.raw_bit_field()));
3344 __ j(equal, &place_integer_param);
3345
3346 __ cmpq(valuetype, Immediate(wasm::kWasmI64.raw_bit_field()));
3347 __ j(equal, &place_integer_param);
3348
3349 __ cmpq(valuetype, Immediate(wasm::kWasmF32.raw_bit_field()));
3350 __ j(equal, &place_float_param);
3351
3352 __ cmpq(valuetype, Immediate(wasm::kWasmF64.raw_bit_field()));
3353 __ j(equal, &place_float_param);
3354
3355 __ int3();
3356
3357 __ bind(&place_integer_param);
3358 __ cmpq(start_int_section, current_int_param_slot);
3359 // If there aren't any integer params remaining, just floats, then go to the
3360 // next valuetype.
3361 __ j(less_equal, &loop_through_valuetypes);
3362
3363 // Copy the param from the integer section to the actual parameter area.
3364 __ pushq(MemOperand(current_int_param_slot, 0));
3365 __ addq(current_int_param_slot, Immediate(kSystemPointerSize));
3366 __ jmp(&loop_through_valuetypes);
3367
3368 __ bind(&place_float_param);
3369 __ cmpq(start_float_section, current_float_param_slot);
3370 // If there aren't any float params remaining, just integers, then go to the
3371 // next valuetype.
3372 __ j(less_equal, &loop_through_valuetypes);
3373
3374 // Copy the param from the float section to the actual parameter area.
3375 __ pushq(MemOperand(current_float_param_slot, 0));
3376 __ addq(current_float_param_slot, Immediate(kSystemPointerSize));
3377 __ jmp(&loop_through_valuetypes);
3378
3379 __ bind(¶ms_done);
3380 // Restore function_data after we are done with parameter placement.
3381 function_data = rdi;
3382 __ movq(function_data, MemOperand(rbp, kFunctionDataOffset));
3383
3384 __ bind(&prepare_for_wasm_call);
3385 // -------------------------------------------
3386 // Prepare for the Wasm call.
3387 // -------------------------------------------
3388 // Set thread_in_wasm_flag.
3389 Register thread_in_wasm_flag_addr = r12;
3390 __ movq(
3391 thread_in_wasm_flag_addr,
3392 MemOperand(kRootRegister, Isolate::thread_in_wasm_flag_address_offset()));
3393 __ movl(MemOperand(thread_in_wasm_flag_addr, 0), Immediate(1));
3394
3395 Register jump_table_start = thread_in_wasm_flag_addr;
3396 __ movq(jump_table_start,
3397 MemOperand(wasm_instance,
3398 wasm::ObjectAccess::ToTagged(
3399 WasmInstanceObject::kJumpTableStartOffset)));
3400 thread_in_wasm_flag_addr = no_reg;
3401
3402 Register jump_table_offset = function_data;
3403 __ LoadAnyTaggedField(
3404 jump_table_offset,
3405 MemOperand(
3406 function_data,
3407 WasmExportedFunctionData::kJumpTableOffsetOffset - kHeapObjectTag));
3408
3409 // Change from smi to integer.
3410 __ SmiUntag(jump_table_offset);
3411
3412 Register function_entry = jump_table_offset;
3413 __ addq(function_entry, jump_table_start);
3414 jump_table_offset = no_reg;
3415 jump_table_start = no_reg;
3416
3417 // We set the indicating value for the GC to the proper one for Wasm call.
3418 constexpr int kWasmCallGCScanSlotCount = 0;
3419 __ movq(MemOperand(rbp, kGCScanSlotCountOffset),
3420 Immediate(kWasmCallGCScanSlotCount));
3421
3422 // -------------------------------------------
3423 // Call the Wasm function.
3424 // -------------------------------------------
3425 __ call(function_entry);
3426 function_entry = no_reg;
3427
3428 // -------------------------------------------
3429 // Resetting after the Wasm call.
3430 // -------------------------------------------
3431 // Restore rsp to free the reserved stack slots for the sections.
3432 __ leaq(rsp, MemOperand(rbp, kLastSpillOffset));
3433
3434 // Unset thread_in_wasm_flag.
3435 thread_in_wasm_flag_addr = r8;
3436 __ movq(
3437 thread_in_wasm_flag_addr,
3438 MemOperand(kRootRegister, Isolate::thread_in_wasm_flag_address_offset()));
3439 __ movl(MemOperand(thread_in_wasm_flag_addr, 0), Immediate(0));
3440 thread_in_wasm_flag_addr = no_reg;
3441
3442 // -------------------------------------------
3443 // Return handling.
3444 // -------------------------------------------
3445 return_count = r8;
3446 __ movq(return_count, MemOperand(rbp, kReturnCountOffset));
3447 Register return_reg = rax;
3448
3449 // If we have 1 return value, then jump to conversion.
3450 __ cmpl(return_count, Immediate(1));
3451 Label convert_return;
3452 __ j(equal, &convert_return);
3453
3454 // Otherwise load undefined.
3455 __ LoadRoot(return_reg, RootIndex::kUndefinedValue);
3456
3457 Label return_done;
3458 __ bind(&return_done);
3459 __ movq(param_count, MemOperand(rbp, kParamCountOffset));
3460
3461 // -------------------------------------------
3462 // Deconstrunct the stack frame.
3463 // -------------------------------------------
3464 __ LeaveFrame(StackFrame::JS_TO_WASM);
3465
3466 // We have to remove the caller frame slots:
3467 // - JS arguments
3468 // - the receiver
3469 // and transfer the control to the return address (the return address is
3470 // expected to be on the top of the stack).
3471 // We cannot use just the ret instruction for this, because we cannot pass the
3472 // number of slots to remove in a Register as an argument.
3473 Register return_addr = rbx;
3474 __ popq(return_addr);
3475 Register caller_frame_slots_count = param_count;
3476 __ addq(caller_frame_slots_count, Immediate(1));
3477 __ shlq(caller_frame_slots_count, Immediate(kSystemPointerSizeLog2));
3478 __ addq(rsp, caller_frame_slots_count);
3479 __ pushq(return_addr);
3480 __ ret(0);
3481
3482 // --------------------------------------------------------------------------
3483 // Deferred code.
3484 // --------------------------------------------------------------------------
3485
3486 // -------------------------------------------
3487 // Param conversion builtins.
3488 // -------------------------------------------
3489 __ bind(&convert_param);
3490 // The order of pushes is important. We want the heap objects, that should be
3491 // scanned by GC, to be on the top of the stack.
3492 // We have to set the indicating value for the GC to the number of values on
3493 // the top of the stack that have to be scanned before calling the builtin
3494 // function.
3495 // The builtin expects the parameter to be in register param = rax.
3496
3497 constexpr int kBuiltinCallGCScanSlotCount = 2;
3498 PrepareForBuiltinCall(masm, MemOperand(rbp, kGCScanSlotCountOffset),
3499 kBuiltinCallGCScanSlotCount, current_param, param_limit,
3500 current_int_param_slot, current_float_param_slot,
3501 valuetypes_array_ptr, wasm_instance, function_data);
3502
3503 Label param_kWasmI32_not_smi;
3504 Label param_kWasmI64;
3505 Label param_kWasmF32;
3506 Label param_kWasmF64;
3507
3508 __ cmpq(valuetype, Immediate(wasm::kWasmI32.raw_bit_field()));
3509 __ j(equal, ¶m_kWasmI32_not_smi);
3510
3511 __ cmpq(valuetype, Immediate(wasm::kWasmI64.raw_bit_field()));
3512 __ j(equal, ¶m_kWasmI64);
3513
3514 __ cmpq(valuetype, Immediate(wasm::kWasmF32.raw_bit_field()));
3515 __ j(equal, ¶m_kWasmF32);
3516
3517 __ cmpq(valuetype, Immediate(wasm::kWasmF64.raw_bit_field()));
3518 __ j(equal, ¶m_kWasmF64);
3519
3520 __ int3();
3521
3522 __ bind(¶m_kWasmI32_not_smi);
3523 __ Call(BUILTIN_CODE(masm->isolate(), WasmTaggedNonSmiToInt32),
3524 RelocInfo::CODE_TARGET);
3525 // Param is the result of the builtin.
3526 __ AssertZeroExtended(param);
3527 RestoreAfterBuiltinCall(masm, function_data, wasm_instance,
3528 valuetypes_array_ptr, current_float_param_slot,
3529 current_int_param_slot, param_limit, current_param);
3530 __ movq(MemOperand(current_int_param_slot, 0), param);
3531 __ subq(current_int_param_slot, Immediate(kSystemPointerSize));
3532 __ jmp(¶m_conversion_done);
3533
3534 __ bind(¶m_kWasmI64);
3535 __ Call(BUILTIN_CODE(masm->isolate(), BigIntToI64), RelocInfo::CODE_TARGET);
3536 RestoreAfterBuiltinCall(masm, function_data, wasm_instance,
3537 valuetypes_array_ptr, current_float_param_slot,
3538 current_int_param_slot, param_limit, current_param);
3539 __ movq(MemOperand(current_int_param_slot, 0), param);
3540 __ subq(current_int_param_slot, Immediate(kSystemPointerSize));
3541 __ jmp(¶m_conversion_done);
3542
3543 __ bind(¶m_kWasmF32);
3544 __ Call(BUILTIN_CODE(masm->isolate(), WasmTaggedToFloat64),
3545 RelocInfo::CODE_TARGET);
3546 RestoreAfterBuiltinCall(masm, function_data, wasm_instance,
3547 valuetypes_array_ptr, current_float_param_slot,
3548 current_int_param_slot, param_limit, current_param);
3549 // Clear higher bits.
3550 __ Xorpd(xmm1, xmm1);
3551 // Truncate float64 to float32.
3552 __ Cvtsd2ss(xmm1, xmm0);
3553 __ Movsd(MemOperand(current_float_param_slot, 0), xmm1);
3554 __ subq(current_float_param_slot, Immediate(kSystemPointerSize));
3555 __ jmp(¶m_conversion_done);
3556
3557 __ bind(¶m_kWasmF64);
3558 __ Call(BUILTIN_CODE(masm->isolate(), WasmTaggedToFloat64),
3559 RelocInfo::CODE_TARGET);
3560 RestoreAfterBuiltinCall(masm, function_data, wasm_instance,
3561 valuetypes_array_ptr, current_float_param_slot,
3562 current_int_param_slot, param_limit, current_param);
3563 __ Movsd(MemOperand(current_float_param_slot, 0), xmm0);
3564 __ subq(current_float_param_slot, Immediate(kSystemPointerSize));
3565 __ jmp(¶m_conversion_done);
3566
3567 // -------------------------------------------
3568 // Return conversions.
3569 // -------------------------------------------
3570 __ bind(&convert_return);
3571 // We have to make sure that the kGCScanSlotCount is set correctly when we
3572 // call the builtins for conversion. For these builtins it's the same as for
3573 // the Wasm call, that is, kGCScanSlotCount = 0, so we don't have to reset it.
3574 // We don't need the JS context for these builtin calls.
3575
3576 __ movq(valuetypes_array_ptr, MemOperand(rbp, kValueTypesArrayStartOffset));
3577 // The first valuetype of the array is the return's valuetype.
3578 __ movl(valuetype,
3579 Operand(valuetypes_array_ptr, wasm::ValueType::bit_field_offset()));
3580
3581 Label return_kWasmI32;
3582 Label return_kWasmI64;
3583 Label return_kWasmF32;
3584 Label return_kWasmF64;
3585
3586 __ cmpq(valuetype, Immediate(wasm::kWasmI32.raw_bit_field()));
3587 __ j(equal, &return_kWasmI32);
3588
3589 __ cmpq(valuetype, Immediate(wasm::kWasmI64.raw_bit_field()));
3590 __ j(equal, &return_kWasmI64);
3591
3592 __ cmpq(valuetype, Immediate(wasm::kWasmF32.raw_bit_field()));
3593 __ j(equal, &return_kWasmF32);
3594
3595 __ cmpq(valuetype, Immediate(wasm::kWasmF64.raw_bit_field()));
3596 __ j(equal, &return_kWasmF64);
3597
3598 __ int3();
3599
3600 __ bind(&return_kWasmI32);
3601 Label to_heapnumber;
3602 // If pointer compression is disabled, we can convert the return to a smi.
3603 if (SmiValuesAre32Bits()) {
3604 __ SmiTag(return_reg);
3605 } else {
3606 Register temp = rbx;
3607 __ movq(temp, return_reg);
3608 // Double the return value to test if it can be a Smi.
3609 __ addl(temp, return_reg);
3610 temp = no_reg;
3611 // If there was overflow, convert the return value to a HeapNumber.
3612 __ j(overflow, &to_heapnumber);
3613 // If there was no overflow, we can convert to Smi.
3614 __ SmiTag(return_reg);
3615 }
3616 __ jmp(&return_done);
3617
3618 // Handle the conversion of the I32 return value to HeapNumber when it cannot
3619 // be a smi.
3620 __ bind(&to_heapnumber);
3621 __ Call(BUILTIN_CODE(masm->isolate(), WasmInt32ToHeapNumber),
3622 RelocInfo::CODE_TARGET);
3623 __ jmp(&return_done);
3624
3625 __ bind(&return_kWasmI64);
3626 __ Call(BUILTIN_CODE(masm->isolate(), I64ToBigInt), RelocInfo::CODE_TARGET);
3627 __ jmp(&return_done);
3628
3629 __ bind(&return_kWasmF32);
3630 // The builtin expects the value to be in xmm0.
3631 __ Movss(xmm0, xmm1);
3632 __ Call(BUILTIN_CODE(masm->isolate(), WasmFloat32ToNumber),
3633 RelocInfo::CODE_TARGET);
3634 __ jmp(&return_done);
3635
3636 __ bind(&return_kWasmF64);
3637 // The builtin expects the value to be in xmm0.
3638 __ Movsd(xmm0, xmm1);
3639 __ Call(BUILTIN_CODE(masm->isolate(), WasmFloat64ToNumber),
3640 RelocInfo::CODE_TARGET);
3641 __ jmp(&return_done);
3642
3643 // -------------------------------------------
3644 // Kick off compilation.
3645 // -------------------------------------------
3646 __ bind(&compile_wrapper);
3647 // Enable GC.
3648 MemOperand GCScanSlotPlace = MemOperand(rbp, kGCScanSlotCountOffset);
3649 __ movq(GCScanSlotPlace, Immediate(4));
3650 // Save registers to the stack.
3651 __ pushq(wasm_instance);
3652 __ pushq(function_data);
3653 // Push the arguments for the runtime call.
3654 __ Push(wasm_instance); // first argument
3655 __ Push(function_data); // second argument
3656 // Set up context.
3657 __ Move(kContextRegister, Smi::zero());
3658 // Call the runtime function that kicks off compilation.
3659 __ CallRuntime(Runtime::kWasmCompileWrapper, 2);
3660 // Pop the result.
3661 __ movq(r9, kReturnRegister0);
3662 // Restore registers from the stack.
3663 __ popq(function_data);
3664 __ popq(wasm_instance);
3665 __ jmp(&compile_wrapper_done);
3666 }
3667
3668 namespace {
3669
Offset(ExternalReference ref0,ExternalReference ref1)3670 int Offset(ExternalReference ref0, ExternalReference ref1) {
3671 int64_t offset = (ref0.address() - ref1.address());
3672 // Check that fits into int.
3673 DCHECK(static_cast<int>(offset) == offset);
3674 return static_cast<int>(offset);
3675 }
3676
3677 // Calls an API function. Allocates HandleScope, extracts returned value
3678 // from handle and propagates exceptions. Clobbers r14, r15, rbx and
3679 // caller-save registers. Restores context. On return removes
3680 // stack_space * kSystemPointerSize (GCed).
CallApiFunctionAndReturn(MacroAssembler * masm,Register function_address,ExternalReference thunk_ref,Register thunk_last_arg,int stack_space,Operand * stack_space_operand,Operand return_value_operand)3681 void CallApiFunctionAndReturn(MacroAssembler* masm, Register function_address,
3682 ExternalReference thunk_ref,
3683 Register thunk_last_arg, int stack_space,
3684 Operand* stack_space_operand,
3685 Operand return_value_operand) {
3686 Label prologue;
3687 Label promote_scheduled_exception;
3688 Label delete_allocated_handles;
3689 Label leave_exit_frame;
3690
3691 Isolate* isolate = masm->isolate();
3692 Factory* factory = isolate->factory();
3693 ExternalReference next_address =
3694 ExternalReference::handle_scope_next_address(isolate);
3695 const int kNextOffset = 0;
3696 const int kLimitOffset = Offset(
3697 ExternalReference::handle_scope_limit_address(isolate), next_address);
3698 const int kLevelOffset = Offset(
3699 ExternalReference::handle_scope_level_address(isolate), next_address);
3700 ExternalReference scheduled_exception_address =
3701 ExternalReference::scheduled_exception_address(isolate);
3702
3703 DCHECK(rdx == function_address || r8 == function_address);
3704 // Allocate HandleScope in callee-save registers.
3705 Register prev_next_address_reg = r14;
3706 Register prev_limit_reg = rbx;
3707 Register base_reg = r15;
3708 __ Move(base_reg, next_address);
3709 __ movq(prev_next_address_reg, Operand(base_reg, kNextOffset));
3710 __ movq(prev_limit_reg, Operand(base_reg, kLimitOffset));
3711 __ addl(Operand(base_reg, kLevelOffset), Immediate(1));
3712
3713 Label profiler_enabled, end_profiler_check;
3714 __ Move(rax, ExternalReference::is_profiling_address(isolate));
3715 __ cmpb(Operand(rax, 0), Immediate(0));
3716 __ j(not_zero, &profiler_enabled);
3717 __ Move(rax, ExternalReference::address_of_runtime_stats_flag());
3718 __ cmpl(Operand(rax, 0), Immediate(0));
3719 __ j(not_zero, &profiler_enabled);
3720 {
3721 // Call the api function directly.
3722 __ Move(rax, function_address);
3723 __ jmp(&end_profiler_check);
3724 }
3725 __ bind(&profiler_enabled);
3726 {
3727 // Third parameter is the address of the actual getter function.
3728 __ Move(thunk_last_arg, function_address);
3729 __ Move(rax, thunk_ref);
3730 }
3731 __ bind(&end_profiler_check);
3732
3733 // Call the api function!
3734 __ call(rax);
3735
3736 // Load the value from ReturnValue
3737 __ movq(rax, return_value_operand);
3738 __ bind(&prologue);
3739
3740 // No more valid handles (the result handle was the last one). Restore
3741 // previous handle scope.
3742 __ subl(Operand(base_reg, kLevelOffset), Immediate(1));
3743 __ movq(Operand(base_reg, kNextOffset), prev_next_address_reg);
3744 __ cmpq(prev_limit_reg, Operand(base_reg, kLimitOffset));
3745 __ j(not_equal, &delete_allocated_handles);
3746
3747 // Leave the API exit frame.
3748 __ bind(&leave_exit_frame);
3749 if (stack_space_operand != nullptr) {
3750 DCHECK_EQ(stack_space, 0);
3751 __ movq(rbx, *stack_space_operand);
3752 }
3753 __ LeaveApiExitFrame();
3754
3755 // Check if the function scheduled an exception.
3756 __ Move(rdi, scheduled_exception_address);
3757 __ Cmp(Operand(rdi, 0), factory->the_hole_value());
3758 __ j(not_equal, &promote_scheduled_exception);
3759
3760 #if DEBUG
3761 // Check if the function returned a valid JavaScript value.
3762 Label ok;
3763 Register return_value = rax;
3764 Register map = rcx;
3765
3766 __ JumpIfSmi(return_value, &ok, Label::kNear);
3767 __ LoadTaggedPointerField(map,
3768 FieldOperand(return_value, HeapObject::kMapOffset));
3769
3770 __ CmpInstanceType(map, LAST_NAME_TYPE);
3771 __ j(below_equal, &ok, Label::kNear);
3772
3773 __ CmpInstanceType(map, FIRST_JS_RECEIVER_TYPE);
3774 __ j(above_equal, &ok, Label::kNear);
3775
3776 __ CompareRoot(map, RootIndex::kHeapNumberMap);
3777 __ j(equal, &ok, Label::kNear);
3778
3779 __ CompareRoot(map, RootIndex::kBigIntMap);
3780 __ j(equal, &ok, Label::kNear);
3781
3782 __ CompareRoot(return_value, RootIndex::kUndefinedValue);
3783 __ j(equal, &ok, Label::kNear);
3784
3785 __ CompareRoot(return_value, RootIndex::kTrueValue);
3786 __ j(equal, &ok, Label::kNear);
3787
3788 __ CompareRoot(return_value, RootIndex::kFalseValue);
3789 __ j(equal, &ok, Label::kNear);
3790
3791 __ CompareRoot(return_value, RootIndex::kNullValue);
3792 __ j(equal, &ok, Label::kNear);
3793
3794 __ Abort(AbortReason::kAPICallReturnedInvalidObject);
3795
3796 __ bind(&ok);
3797 #endif
3798
3799 if (stack_space_operand == nullptr) {
3800 DCHECK_NE(stack_space, 0);
3801 __ ret(stack_space * kSystemPointerSize);
3802 } else {
3803 DCHECK_EQ(stack_space, 0);
3804 __ PopReturnAddressTo(rcx);
3805 __ addq(rsp, rbx);
3806 __ jmp(rcx);
3807 }
3808
3809 // Re-throw by promoting a scheduled exception.
3810 __ bind(&promote_scheduled_exception);
3811 __ TailCallRuntime(Runtime::kPromoteScheduledException);
3812
3813 // HandleScope limit has changed. Delete allocated extensions.
3814 __ bind(&delete_allocated_handles);
3815 __ movq(Operand(base_reg, kLimitOffset), prev_limit_reg);
3816 __ movq(prev_limit_reg, rax);
3817 __ LoadAddress(arg_reg_1, ExternalReference::isolate_address(isolate));
3818 __ LoadAddress(rax, ExternalReference::delete_handle_scope_extensions());
3819 __ call(rax);
3820 __ movq(rax, prev_limit_reg);
3821 __ jmp(&leave_exit_frame);
3822 }
3823
3824 } // namespace
3825
3826 // TODO(jgruber): Instead of explicitly setting up implicit_args_ on the stack
3827 // in CallApiCallback, we could use the calling convention to set up the stack
3828 // correctly in the first place.
3829 //
3830 // TODO(jgruber): I suspect that most of CallApiCallback could be implemented
3831 // as a C++ trampoline, vastly simplifying the assembly implementation.
3832
Generate_CallApiCallback(MacroAssembler * masm)3833 void Builtins::Generate_CallApiCallback(MacroAssembler* masm) {
3834 // ----------- S t a t e -------------
3835 // -- rsi : context
3836 // -- rdx : api function address
3837 // -- rcx : arguments count (not including the receiver)
3838 // -- rbx : call data
3839 // -- rdi : holder
3840 // -- rsp[0] : return address
3841 // -- rsp[8] : argument 0 (receiver)
3842 // -- rsp[16] : argument 1
3843 // -- ...
3844 // -- rsp[argc * 8] : argument (argc - 1)
3845 // -- rsp[(argc + 1) * 8] : argument argc
3846 // -----------------------------------
3847
3848 Register api_function_address = rdx;
3849 Register argc = rcx;
3850 Register call_data = rbx;
3851 Register holder = rdi;
3852
3853 DCHECK(!AreAliased(api_function_address, argc, holder, call_data,
3854 kScratchRegister));
3855
3856 using FCA = FunctionCallbackArguments;
3857
3858 STATIC_ASSERT(FCA::kArgsLength == 6);
3859 STATIC_ASSERT(FCA::kNewTargetIndex == 5);
3860 STATIC_ASSERT(FCA::kDataIndex == 4);
3861 STATIC_ASSERT(FCA::kReturnValueOffset == 3);
3862 STATIC_ASSERT(FCA::kReturnValueDefaultValueIndex == 2);
3863 STATIC_ASSERT(FCA::kIsolateIndex == 1);
3864 STATIC_ASSERT(FCA::kHolderIndex == 0);
3865
3866 // Set up FunctionCallbackInfo's implicit_args on the stack as follows:
3867 //
3868 // Current state:
3869 // rsp[0]: return address
3870 //
3871 // Target state:
3872 // rsp[0 * kSystemPointerSize]: return address
3873 // rsp[1 * kSystemPointerSize]: kHolder
3874 // rsp[2 * kSystemPointerSize]: kIsolate
3875 // rsp[3 * kSystemPointerSize]: undefined (kReturnValueDefaultValue)
3876 // rsp[4 * kSystemPointerSize]: undefined (kReturnValue)
3877 // rsp[5 * kSystemPointerSize]: kData
3878 // rsp[6 * kSystemPointerSize]: undefined (kNewTarget)
3879
3880 __ PopReturnAddressTo(rax);
3881 __ LoadRoot(kScratchRegister, RootIndex::kUndefinedValue);
3882 __ Push(kScratchRegister);
3883 __ Push(call_data);
3884 __ Push(kScratchRegister);
3885 __ Push(kScratchRegister);
3886 __ PushAddress(ExternalReference::isolate_address(masm->isolate()));
3887 __ Push(holder);
3888 __ PushReturnAddressFrom(rax);
3889
3890 // Keep a pointer to kHolder (= implicit_args) in a scratch register.
3891 // We use it below to set up the FunctionCallbackInfo object.
3892 Register scratch = rbx;
3893 __ leaq(scratch, Operand(rsp, 1 * kSystemPointerSize));
3894
3895 // Allocate the v8::Arguments structure in the arguments' space since
3896 // it's not controlled by GC.
3897 static constexpr int kApiStackSpace = 4;
3898 __ EnterApiExitFrame(kApiStackSpace);
3899
3900 // FunctionCallbackInfo::implicit_args_ (points at kHolder as set up above).
3901 __ movq(StackSpaceOperand(0), scratch);
3902
3903 // FunctionCallbackInfo::values_ (points at the first varargs argument passed
3904 // on the stack).
3905 __ leaq(scratch,
3906 Operand(scratch, (FCA::kArgsLength + 1) * kSystemPointerSize));
3907 __ movq(StackSpaceOperand(1), scratch);
3908
3909 // FunctionCallbackInfo::length_.
3910 __ movq(StackSpaceOperand(2), argc);
3911
3912 // We also store the number of bytes to drop from the stack after returning
3913 // from the API function here.
3914 __ leaq(kScratchRegister,
3915 Operand(argc, times_system_pointer_size,
3916 (FCA::kArgsLength + 1 /* receiver */) * kSystemPointerSize));
3917 __ movq(StackSpaceOperand(3), kScratchRegister);
3918
3919 Register arguments_arg = arg_reg_1;
3920 Register callback_arg = arg_reg_2;
3921
3922 // It's okay if api_function_address == callback_arg
3923 // but not arguments_arg
3924 DCHECK(api_function_address != arguments_arg);
3925
3926 // v8::InvocationCallback's argument.
3927 __ leaq(arguments_arg, StackSpaceOperand(0));
3928
3929 ExternalReference thunk_ref = ExternalReference::invoke_function_callback();
3930
3931 // There are two stack slots above the arguments we constructed on the stack:
3932 // the stored ebp (pushed by EnterApiExitFrame), and the return address.
3933 static constexpr int kStackSlotsAboveFCA = 2;
3934 Operand return_value_operand(
3935 rbp,
3936 (kStackSlotsAboveFCA + FCA::kReturnValueOffset) * kSystemPointerSize);
3937
3938 static constexpr int kUseStackSpaceOperand = 0;
3939 Operand stack_space_operand = StackSpaceOperand(3);
3940 CallApiFunctionAndReturn(masm, api_function_address, thunk_ref, callback_arg,
3941 kUseStackSpaceOperand, &stack_space_operand,
3942 return_value_operand);
3943 }
3944
Generate_CallApiGetter(MacroAssembler * masm)3945 void Builtins::Generate_CallApiGetter(MacroAssembler* masm) {
3946 Register name_arg = arg_reg_1;
3947 Register accessor_info_arg = arg_reg_2;
3948 Register getter_arg = arg_reg_3;
3949 Register api_function_address = r8;
3950 Register receiver = ApiGetterDescriptor::ReceiverRegister();
3951 Register holder = ApiGetterDescriptor::HolderRegister();
3952 Register callback = ApiGetterDescriptor::CallbackRegister();
3953 Register scratch = rax;
3954 Register decompr_scratch1 = COMPRESS_POINTERS_BOOL ? r11 : no_reg;
3955
3956 DCHECK(!AreAliased(receiver, holder, callback, scratch, decompr_scratch1));
3957
3958 // Build v8::PropertyCallbackInfo::args_ array on the stack and push property
3959 // name below the exit frame to make GC aware of them.
3960 STATIC_ASSERT(PropertyCallbackArguments::kShouldThrowOnErrorIndex == 0);
3961 STATIC_ASSERT(PropertyCallbackArguments::kHolderIndex == 1);
3962 STATIC_ASSERT(PropertyCallbackArguments::kIsolateIndex == 2);
3963 STATIC_ASSERT(PropertyCallbackArguments::kReturnValueDefaultValueIndex == 3);
3964 STATIC_ASSERT(PropertyCallbackArguments::kReturnValueOffset == 4);
3965 STATIC_ASSERT(PropertyCallbackArguments::kDataIndex == 5);
3966 STATIC_ASSERT(PropertyCallbackArguments::kThisIndex == 6);
3967 STATIC_ASSERT(PropertyCallbackArguments::kArgsLength == 7);
3968
3969 // Insert additional parameters into the stack frame above return address.
3970 __ PopReturnAddressTo(scratch);
3971 __ Push(receiver);
3972 __ PushTaggedAnyField(FieldOperand(callback, AccessorInfo::kDataOffset),
3973 decompr_scratch1);
3974 __ LoadRoot(kScratchRegister, RootIndex::kUndefinedValue);
3975 __ Push(kScratchRegister); // return value
3976 __ Push(kScratchRegister); // return value default
3977 __ PushAddress(ExternalReference::isolate_address(masm->isolate()));
3978 __ Push(holder);
3979 __ Push(Smi::zero()); // should_throw_on_error -> false
3980 __ PushTaggedPointerField(FieldOperand(callback, AccessorInfo::kNameOffset),
3981 decompr_scratch1);
3982 __ PushReturnAddressFrom(scratch);
3983
3984 // v8::PropertyCallbackInfo::args_ array and name handle.
3985 const int kStackUnwindSpace = PropertyCallbackArguments::kArgsLength + 1;
3986
3987 // Allocate v8::PropertyCallbackInfo in non-GCed stack space.
3988 const int kArgStackSpace = 1;
3989
3990 // Load address of v8::PropertyAccessorInfo::args_ array.
3991 __ leaq(scratch, Operand(rsp, 2 * kSystemPointerSize));
3992
3993 __ EnterApiExitFrame(kArgStackSpace);
3994
3995 // Create v8::PropertyCallbackInfo object on the stack and initialize
3996 // it's args_ field.
3997 Operand info_object = StackSpaceOperand(0);
3998 __ movq(info_object, scratch);
3999
4000 __ leaq(name_arg, Operand(scratch, -kSystemPointerSize));
4001 // The context register (rsi) has been saved in EnterApiExitFrame and
4002 // could be used to pass arguments.
4003 __ leaq(accessor_info_arg, info_object);
4004
4005 ExternalReference thunk_ref =
4006 ExternalReference::invoke_accessor_getter_callback();
4007
4008 // It's okay if api_function_address == getter_arg
4009 // but not accessor_info_arg or name_arg
4010 DCHECK(api_function_address != accessor_info_arg);
4011 DCHECK(api_function_address != name_arg);
4012 __ LoadTaggedPointerField(
4013 scratch, FieldOperand(callback, AccessorInfo::kJsGetterOffset));
4014 __ LoadExternalPointerField(
4015 api_function_address,
4016 FieldOperand(scratch, Foreign::kForeignAddressOffset),
4017 kForeignForeignAddressTag);
4018
4019 // +3 is to skip prolog, return address and name handle.
4020 Operand return_value_operand(
4021 rbp,
4022 (PropertyCallbackArguments::kReturnValueOffset + 3) * kSystemPointerSize);
4023 Operand* const kUseStackSpaceConstant = nullptr;
4024 CallApiFunctionAndReturn(masm, api_function_address, thunk_ref, getter_arg,
4025 kStackUnwindSpace, kUseStackSpaceConstant,
4026 return_value_operand);
4027 }
4028
Generate_DirectCEntry(MacroAssembler * masm)4029 void Builtins::Generate_DirectCEntry(MacroAssembler* masm) {
4030 __ int3(); // Unused on this architecture.
4031 }
4032
4033 namespace {
4034
Generate_DeoptimizationEntry(MacroAssembler * masm,DeoptimizeKind deopt_kind)4035 void Generate_DeoptimizationEntry(MacroAssembler* masm,
4036 DeoptimizeKind deopt_kind) {
4037 Isolate* isolate = masm->isolate();
4038
4039 // Save all double registers, they will later be copied to the deoptimizer's
4040 // FrameDescription.
4041 static constexpr int kDoubleRegsSize =
4042 kDoubleSize * XMMRegister::kNumRegisters;
4043 __ AllocateStackSpace(kDoubleRegsSize);
4044
4045 const RegisterConfiguration* config = RegisterConfiguration::Default();
4046 for (int i = 0; i < config->num_allocatable_double_registers(); ++i) {
4047 int code = config->GetAllocatableDoubleCode(i);
4048 XMMRegister xmm_reg = XMMRegister::from_code(code);
4049 int offset = code * kDoubleSize;
4050 __ Movsd(Operand(rsp, offset), xmm_reg);
4051 }
4052
4053 // Save all general purpose registers, they will later be copied to the
4054 // deoptimizer's FrameDescription.
4055 static constexpr int kNumberOfRegisters = Register::kNumRegisters;
4056 for (int i = 0; i < kNumberOfRegisters; i++) {
4057 __ pushq(Register::from_code(i));
4058 }
4059
4060 static constexpr int kSavedRegistersAreaSize =
4061 kNumberOfRegisters * kSystemPointerSize + kDoubleRegsSize;
4062 static constexpr int kCurrentOffsetToReturnAddress = kSavedRegistersAreaSize;
4063 static constexpr int kCurrentOffsetToParentSP =
4064 kCurrentOffsetToReturnAddress + kPCOnStackSize;
4065
4066 __ Store(
4067 ExternalReference::Create(IsolateAddressId::kCEntryFPAddress, isolate),
4068 rbp);
4069
4070 // We use this to keep the value of the fifth argument temporarily.
4071 // Unfortunately we can't store it directly in r8 (used for passing
4072 // this on linux), since it is another parameter passing register on windows.
4073 Register arg5 = r11;
4074
4075 __ movq(arg_reg_3, Immediate(Deoptimizer::kFixedExitSizeMarker));
4076 // Get the address of the location in the code object
4077 // and compute the fp-to-sp delta in register arg5.
4078 __ movq(arg_reg_4, Operand(rsp, kCurrentOffsetToReturnAddress));
4079 // Load the fp-to-sp-delta.
4080 __ leaq(arg5, Operand(rsp, kCurrentOffsetToParentSP));
4081 __ subq(arg5, rbp);
4082 __ negq(arg5);
4083
4084 // Allocate a new deoptimizer object.
4085 __ PrepareCallCFunction(6);
4086 __ movq(rax, Immediate(0));
4087 Label context_check;
4088 __ movq(rdi, Operand(rbp, CommonFrameConstants::kContextOrFrameTypeOffset));
4089 __ JumpIfSmi(rdi, &context_check);
4090 __ movq(rax, Operand(rbp, StandardFrameConstants::kFunctionOffset));
4091 __ bind(&context_check);
4092 __ movq(arg_reg_1, rax);
4093 __ Set(arg_reg_2, static_cast<int>(deopt_kind));
4094 // Args 3 and 4 are already in the right registers.
4095
4096 // On windows put the arguments on the stack (PrepareCallCFunction
4097 // has created space for this). On linux pass the arguments in r8 and r9.
4098 #ifdef V8_TARGET_OS_WIN
4099 __ movq(Operand(rsp, 4 * kSystemPointerSize), arg5);
4100 __ LoadAddress(arg5, ExternalReference::isolate_address(isolate));
4101 __ movq(Operand(rsp, 5 * kSystemPointerSize), arg5);
4102 #else
4103 __ movq(r8, arg5);
4104 __ LoadAddress(r9, ExternalReference::isolate_address(isolate));
4105 #endif
4106
4107 {
4108 AllowExternalCallThatCantCauseGC scope(masm);
4109 __ CallCFunction(ExternalReference::new_deoptimizer_function(), 6);
4110 }
4111 // Preserve deoptimizer object in register rax and get the input
4112 // frame descriptor pointer.
4113 __ movq(rbx, Operand(rax, Deoptimizer::input_offset()));
4114
4115 // Fill in the input registers.
4116 for (int i = kNumberOfRegisters - 1; i >= 0; i--) {
4117 int offset =
4118 (i * kSystemPointerSize) + FrameDescription::registers_offset();
4119 __ PopQuad(Operand(rbx, offset));
4120 }
4121
4122 // Fill in the double input registers.
4123 int double_regs_offset = FrameDescription::double_registers_offset();
4124 for (int i = 0; i < XMMRegister::kNumRegisters; i++) {
4125 int dst_offset = i * kDoubleSize + double_regs_offset;
4126 __ popq(Operand(rbx, dst_offset));
4127 }
4128
4129 // Mark the stack as not iterable for the CPU profiler which won't be able to
4130 // walk the stack without the return address.
4131 __ movb(__ ExternalReferenceAsOperand(
4132 ExternalReference::stack_is_iterable_address(isolate)),
4133 Immediate(0));
4134
4135 // Remove the return address from the stack.
4136 __ addq(rsp, Immediate(kPCOnStackSize));
4137
4138 // Compute a pointer to the unwinding limit in register rcx; that is
4139 // the first stack slot not part of the input frame.
4140 __ movq(rcx, Operand(rbx, FrameDescription::frame_size_offset()));
4141 __ addq(rcx, rsp);
4142
4143 // Unwind the stack down to - but not including - the unwinding
4144 // limit and copy the contents of the activation frame to the input
4145 // frame description.
4146 __ leaq(rdx, Operand(rbx, FrameDescription::frame_content_offset()));
4147 Label pop_loop_header;
4148 __ jmp(&pop_loop_header);
4149 Label pop_loop;
4150 __ bind(&pop_loop);
4151 __ Pop(Operand(rdx, 0));
4152 __ addq(rdx, Immediate(sizeof(intptr_t)));
4153 __ bind(&pop_loop_header);
4154 __ cmpq(rcx, rsp);
4155 __ j(not_equal, &pop_loop);
4156
4157 // Compute the output frame in the deoptimizer.
4158 __ pushq(rax);
4159 __ PrepareCallCFunction(2);
4160 __ movq(arg_reg_1, rax);
4161 __ LoadAddress(arg_reg_2, ExternalReference::isolate_address(isolate));
4162 {
4163 AllowExternalCallThatCantCauseGC scope(masm);
4164 __ CallCFunction(ExternalReference::compute_output_frames_function(), 2);
4165 }
4166 __ popq(rax);
4167
4168 __ movq(rsp, Operand(rax, Deoptimizer::caller_frame_top_offset()));
4169
4170 // Replace the current (input) frame with the output frames.
4171 Label outer_push_loop, inner_push_loop, outer_loop_header, inner_loop_header;
4172 // Outer loop state: rax = current FrameDescription**, rdx = one past the
4173 // last FrameDescription**.
4174 __ movl(rdx, Operand(rax, Deoptimizer::output_count_offset()));
4175 __ movq(rax, Operand(rax, Deoptimizer::output_offset()));
4176 __ leaq(rdx, Operand(rax, rdx, times_system_pointer_size, 0));
4177 __ jmp(&outer_loop_header);
4178 __ bind(&outer_push_loop);
4179 // Inner loop state: rbx = current FrameDescription*, rcx = loop index.
4180 __ movq(rbx, Operand(rax, 0));
4181 __ movq(rcx, Operand(rbx, FrameDescription::frame_size_offset()));
4182 __ jmp(&inner_loop_header);
4183 __ bind(&inner_push_loop);
4184 __ subq(rcx, Immediate(sizeof(intptr_t)));
4185 __ Push(Operand(rbx, rcx, times_1, FrameDescription::frame_content_offset()));
4186 __ bind(&inner_loop_header);
4187 __ testq(rcx, rcx);
4188 __ j(not_zero, &inner_push_loop);
4189 __ addq(rax, Immediate(kSystemPointerSize));
4190 __ bind(&outer_loop_header);
4191 __ cmpq(rax, rdx);
4192 __ j(below, &outer_push_loop);
4193
4194 for (int i = 0; i < config->num_allocatable_double_registers(); ++i) {
4195 int code = config->GetAllocatableDoubleCode(i);
4196 XMMRegister xmm_reg = XMMRegister::from_code(code);
4197 int src_offset = code * kDoubleSize + double_regs_offset;
4198 __ Movsd(xmm_reg, Operand(rbx, src_offset));
4199 }
4200
4201 // Push pc and continuation from the last output frame.
4202 __ PushQuad(Operand(rbx, FrameDescription::pc_offset()));
4203 __ PushQuad(Operand(rbx, FrameDescription::continuation_offset()));
4204
4205 // Push the registers from the last output frame.
4206 for (int i = 0; i < kNumberOfRegisters; i++) {
4207 int offset =
4208 (i * kSystemPointerSize) + FrameDescription::registers_offset();
4209 __ PushQuad(Operand(rbx, offset));
4210 }
4211
4212 // Restore the registers from the stack.
4213 for (int i = kNumberOfRegisters - 1; i >= 0; i--) {
4214 Register r = Register::from_code(i);
4215 // Do not restore rsp, simply pop the value into the next register
4216 // and overwrite this afterwards.
4217 if (r == rsp) {
4218 DCHECK_GT(i, 0);
4219 r = Register::from_code(i - 1);
4220 }
4221 __ popq(r);
4222 }
4223
4224 __ movb(__ ExternalReferenceAsOperand(
4225 ExternalReference::stack_is_iterable_address(isolate)),
4226 Immediate(1));
4227
4228 // Return to the continuation point.
4229 __ ret(0);
4230 }
4231
4232 } // namespace
4233
Generate_DeoptimizationEntry_Eager(MacroAssembler * masm)4234 void Builtins::Generate_DeoptimizationEntry_Eager(MacroAssembler* masm) {
4235 Generate_DeoptimizationEntry(masm, DeoptimizeKind::kEager);
4236 }
4237
Generate_DeoptimizationEntry_Soft(MacroAssembler * masm)4238 void Builtins::Generate_DeoptimizationEntry_Soft(MacroAssembler* masm) {
4239 Generate_DeoptimizationEntry(masm, DeoptimizeKind::kSoft);
4240 }
4241
Generate_DeoptimizationEntry_Bailout(MacroAssembler * masm)4242 void Builtins::Generate_DeoptimizationEntry_Bailout(MacroAssembler* masm) {
4243 Generate_DeoptimizationEntry(masm, DeoptimizeKind::kBailout);
4244 }
4245
Generate_DeoptimizationEntry_Lazy(MacroAssembler * masm)4246 void Builtins::Generate_DeoptimizationEntry_Lazy(MacroAssembler* masm) {
4247 Generate_DeoptimizationEntry(masm, DeoptimizeKind::kLazy);
4248 }
4249
4250 #undef __
4251
4252 } // namespace internal
4253 } // namespace v8
4254
4255 #endif // V8_TARGET_ARCH_X64
4256