blob: 9d82e0e31abfc70475b112ac8d28756517bcebd5 [file] [log] [blame]
Kristian Monsen80d68ea2010-09-08 11:05:35 +01001// Copyright 2010 the V8 project authors. All rights reserved.
2// Redistribution and use in source and binary forms, with or without
3// modification, are permitted provided that the following conditions are
4// met:
5//
6// * Redistributions of source code must retain the above copyright
7// notice, this list of conditions and the following disclaimer.
8// * Redistributions in binary form must reproduce the above
9// copyright notice, this list of conditions and the following
10// disclaimer in the documentation and/or other materials provided
11// with the distribution.
12// * Neither the name of Google Inc. nor the names of its
13// contributors may be used to endorse or promote products derived
14// from this software without specific prior written permission.
15//
16// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27
28#include "v8.h"
29
30#if defined(V8_TARGET_ARCH_X64)
31
32#include "bootstrapper.h"
33#include "code-stubs.h"
34#include "regexp-macro-assembler.h"
35
36namespace v8 {
37namespace internal {
38
39#define __ ACCESS_MASM(masm)
40void FastNewClosureStub::Generate(MacroAssembler* masm) {
41 // Create a new closure from the given function info in new
42 // space. Set the context to the current context in rsi.
43 Label gc;
44 __ AllocateInNewSpace(JSFunction::kSize, rax, rbx, rcx, &gc, TAG_OBJECT);
45
46 // Get the function info from the stack.
47 __ movq(rdx, Operand(rsp, 1 * kPointerSize));
48
49 // Compute the function map in the current global context and set that
50 // as the map of the allocated object.
51 __ movq(rcx, Operand(rsi, Context::SlotOffset(Context::GLOBAL_INDEX)));
52 __ movq(rcx, FieldOperand(rcx, GlobalObject::kGlobalContextOffset));
53 __ movq(rcx, Operand(rcx, Context::SlotOffset(Context::FUNCTION_MAP_INDEX)));
54 __ movq(FieldOperand(rax, JSObject::kMapOffset), rcx);
55
56 // Initialize the rest of the function. We don't have to update the
57 // write barrier because the allocated object is in new space.
58 __ LoadRoot(rbx, Heap::kEmptyFixedArrayRootIndex);
59 __ LoadRoot(rcx, Heap::kTheHoleValueRootIndex);
60 __ movq(FieldOperand(rax, JSObject::kPropertiesOffset), rbx);
61 __ movq(FieldOperand(rax, JSObject::kElementsOffset), rbx);
62 __ movq(FieldOperand(rax, JSFunction::kPrototypeOrInitialMapOffset), rcx);
63 __ movq(FieldOperand(rax, JSFunction::kSharedFunctionInfoOffset), rdx);
64 __ movq(FieldOperand(rax, JSFunction::kContextOffset), rsi);
65 __ movq(FieldOperand(rax, JSFunction::kLiteralsOffset), rbx);
66
67 // Initialize the code pointer in the function to be the one
68 // found in the shared function info object.
69 __ movq(rdx, FieldOperand(rdx, SharedFunctionInfo::kCodeOffset));
70 __ lea(rdx, FieldOperand(rdx, Code::kHeaderSize));
71 __ movq(FieldOperand(rax, JSFunction::kCodeEntryOffset), rdx);
72
73
74 // Return and remove the on-stack parameter.
75 __ ret(1 * kPointerSize);
76
77 // Create a new closure through the slower runtime call.
78 __ bind(&gc);
79 __ pop(rcx); // Temporarily remove return address.
80 __ pop(rdx);
81 __ push(rsi);
82 __ push(rdx);
83 __ push(rcx); // Restore return address.
84 __ TailCallRuntime(Runtime::kNewClosure, 2, 1);
85}
86
87
88void FastNewContextStub::Generate(MacroAssembler* masm) {
89 // Try to allocate the context in new space.
90 Label gc;
91 int length = slots_ + Context::MIN_CONTEXT_SLOTS;
92 __ AllocateInNewSpace((length * kPointerSize) + FixedArray::kHeaderSize,
93 rax, rbx, rcx, &gc, TAG_OBJECT);
94
95 // Get the function from the stack.
96 __ movq(rcx, Operand(rsp, 1 * kPointerSize));
97
98 // Setup the object header.
99 __ LoadRoot(kScratchRegister, Heap::kContextMapRootIndex);
100 __ movq(FieldOperand(rax, HeapObject::kMapOffset), kScratchRegister);
101 __ Move(FieldOperand(rax, FixedArray::kLengthOffset), Smi::FromInt(length));
102
103 // Setup the fixed slots.
104 __ xor_(rbx, rbx); // Set to NULL.
105 __ movq(Operand(rax, Context::SlotOffset(Context::CLOSURE_INDEX)), rcx);
106 __ movq(Operand(rax, Context::SlotOffset(Context::FCONTEXT_INDEX)), rax);
107 __ movq(Operand(rax, Context::SlotOffset(Context::PREVIOUS_INDEX)), rbx);
108 __ movq(Operand(rax, Context::SlotOffset(Context::EXTENSION_INDEX)), rbx);
109
110 // Copy the global object from the surrounding context.
111 __ movq(rbx, Operand(rsi, Context::SlotOffset(Context::GLOBAL_INDEX)));
112 __ movq(Operand(rax, Context::SlotOffset(Context::GLOBAL_INDEX)), rbx);
113
114 // Initialize the rest of the slots to undefined.
115 __ LoadRoot(rbx, Heap::kUndefinedValueRootIndex);
116 for (int i = Context::MIN_CONTEXT_SLOTS; i < length; i++) {
117 __ movq(Operand(rax, Context::SlotOffset(i)), rbx);
118 }
119
120 // Return and remove the on-stack parameter.
121 __ movq(rsi, rax);
122 __ ret(1 * kPointerSize);
123
124 // Need to collect. Call into runtime system.
125 __ bind(&gc);
126 __ TailCallRuntime(Runtime::kNewContext, 1, 1);
127}
128
129
130void FastCloneShallowArrayStub::Generate(MacroAssembler* masm) {
131 // Stack layout on entry:
132 //
133 // [rsp + kPointerSize]: constant elements.
134 // [rsp + (2 * kPointerSize)]: literal index.
135 // [rsp + (3 * kPointerSize)]: literals array.
136
137 // All sizes here are multiples of kPointerSize.
138 int elements_size = (length_ > 0) ? FixedArray::SizeFor(length_) : 0;
139 int size = JSArray::kSize + elements_size;
140
141 // Load boilerplate object into rcx and check if we need to create a
142 // boilerplate.
143 Label slow_case;
144 __ movq(rcx, Operand(rsp, 3 * kPointerSize));
145 __ movq(rax, Operand(rsp, 2 * kPointerSize));
146 SmiIndex index = masm->SmiToIndex(rax, rax, kPointerSizeLog2);
147 __ movq(rcx,
148 FieldOperand(rcx, index.reg, index.scale, FixedArray::kHeaderSize));
149 __ CompareRoot(rcx, Heap::kUndefinedValueRootIndex);
150 __ j(equal, &slow_case);
151
152 if (FLAG_debug_code) {
153 const char* message;
154 Heap::RootListIndex expected_map_index;
155 if (mode_ == CLONE_ELEMENTS) {
156 message = "Expected (writable) fixed array";
157 expected_map_index = Heap::kFixedArrayMapRootIndex;
158 } else {
159 ASSERT(mode_ == COPY_ON_WRITE_ELEMENTS);
160 message = "Expected copy-on-write fixed array";
161 expected_map_index = Heap::kFixedCOWArrayMapRootIndex;
162 }
163 __ push(rcx);
164 __ movq(rcx, FieldOperand(rcx, JSArray::kElementsOffset));
165 __ CompareRoot(FieldOperand(rcx, HeapObject::kMapOffset),
166 expected_map_index);
167 __ Assert(equal, message);
168 __ pop(rcx);
169 }
170
171 // Allocate both the JS array and the elements array in one big
172 // allocation. This avoids multiple limit checks.
173 __ AllocateInNewSpace(size, rax, rbx, rdx, &slow_case, TAG_OBJECT);
174
175 // Copy the JS array part.
176 for (int i = 0; i < JSArray::kSize; i += kPointerSize) {
177 if ((i != JSArray::kElementsOffset) || (length_ == 0)) {
178 __ movq(rbx, FieldOperand(rcx, i));
179 __ movq(FieldOperand(rax, i), rbx);
180 }
181 }
182
183 if (length_ > 0) {
184 // Get hold of the elements array of the boilerplate and setup the
185 // elements pointer in the resulting object.
186 __ movq(rcx, FieldOperand(rcx, JSArray::kElementsOffset));
187 __ lea(rdx, Operand(rax, JSArray::kSize));
188 __ movq(FieldOperand(rax, JSArray::kElementsOffset), rdx);
189
190 // Copy the elements array.
191 for (int i = 0; i < elements_size; i += kPointerSize) {
192 __ movq(rbx, FieldOperand(rcx, i));
193 __ movq(FieldOperand(rdx, i), rbx);
194 }
195 }
196
197 // Return and remove the on-stack parameters.
198 __ ret(3 * kPointerSize);
199
200 __ bind(&slow_case);
201 __ TailCallRuntime(Runtime::kCreateArrayLiteralShallow, 3, 1);
202}
203
204
205void ToBooleanStub::Generate(MacroAssembler* masm) {
Kristian Monsen0d5e1162010-09-30 15:31:59 +0100206 NearLabel false_result, true_result, not_string;
Kristian Monsen80d68ea2010-09-08 11:05:35 +0100207 __ movq(rax, Operand(rsp, 1 * kPointerSize));
208
209 // 'null' => false.
210 __ CompareRoot(rax, Heap::kNullValueRootIndex);
211 __ j(equal, &false_result);
212
213 // Get the map and type of the heap object.
214 // We don't use CmpObjectType because we manipulate the type field.
215 __ movq(rdx, FieldOperand(rax, HeapObject::kMapOffset));
216 __ movzxbq(rcx, FieldOperand(rdx, Map::kInstanceTypeOffset));
217
218 // Undetectable => false.
219 __ movzxbq(rbx, FieldOperand(rdx, Map::kBitFieldOffset));
220 __ and_(rbx, Immediate(1 << Map::kIsUndetectable));
221 __ j(not_zero, &false_result);
222
223 // JavaScript object => true.
224 __ cmpq(rcx, Immediate(FIRST_JS_OBJECT_TYPE));
225 __ j(above_equal, &true_result);
226
227 // String value => false iff empty.
228 __ cmpq(rcx, Immediate(FIRST_NONSTRING_TYPE));
229 __ j(above_equal, &not_string);
230 __ movq(rdx, FieldOperand(rax, String::kLengthOffset));
231 __ SmiTest(rdx);
232 __ j(zero, &false_result);
233 __ jmp(&true_result);
234
235 __ bind(&not_string);
236 __ CompareRoot(rdx, Heap::kHeapNumberMapRootIndex);
237 __ j(not_equal, &true_result);
238 // HeapNumber => false iff +0, -0, or NaN.
239 // These three cases set the zero flag when compared to zero using ucomisd.
240 __ xorpd(xmm0, xmm0);
241 __ ucomisd(xmm0, FieldOperand(rax, HeapNumber::kValueOffset));
242 __ j(zero, &false_result);
243 // Fall through to |true_result|.
244
245 // Return 1/0 for true/false in rax.
246 __ bind(&true_result);
247 __ movq(rax, Immediate(1));
248 __ ret(1 * kPointerSize);
249 __ bind(&false_result);
250 __ xor_(rax, rax);
251 __ ret(1 * kPointerSize);
252}
253
254
255const char* GenericBinaryOpStub::GetName() {
256 if (name_ != NULL) return name_;
257 const int kMaxNameLength = 100;
258 name_ = Bootstrapper::AllocateAutoDeletedArray(kMaxNameLength);
259 if (name_ == NULL) return "OOM";
260 const char* op_name = Token::Name(op_);
261 const char* overwrite_name;
262 switch (mode_) {
263 case NO_OVERWRITE: overwrite_name = "Alloc"; break;
264 case OVERWRITE_RIGHT: overwrite_name = "OverwriteRight"; break;
265 case OVERWRITE_LEFT: overwrite_name = "OverwriteLeft"; break;
266 default: overwrite_name = "UnknownOverwrite"; break;
267 }
268
269 OS::SNPrintF(Vector<char>(name_, kMaxNameLength),
270 "GenericBinaryOpStub_%s_%s%s_%s%s_%s_%s",
271 op_name,
272 overwrite_name,
273 (flags_ & NO_SMI_CODE_IN_STUB) ? "_NoSmiInStub" : "",
274 args_in_registers_ ? "RegArgs" : "StackArgs",
275 args_reversed_ ? "_R" : "",
276 static_operands_type_.ToString(),
277 BinaryOpIC::GetName(runtime_operands_type_));
278 return name_;
279}
280
281
282void GenericBinaryOpStub::GenerateCall(
283 MacroAssembler* masm,
284 Register left,
285 Register right) {
286 if (!ArgsInRegistersSupported()) {
287 // Pass arguments on the stack.
288 __ push(left);
289 __ push(right);
290 } else {
291 // The calling convention with registers is left in rdx and right in rax.
292 Register left_arg = rdx;
293 Register right_arg = rax;
294 if (!(left.is(left_arg) && right.is(right_arg))) {
295 if (left.is(right_arg) && right.is(left_arg)) {
296 if (IsOperationCommutative()) {
297 SetArgsReversed();
298 } else {
299 __ xchg(left, right);
300 }
301 } else if (left.is(left_arg)) {
302 __ movq(right_arg, right);
303 } else if (right.is(right_arg)) {
304 __ movq(left_arg, left);
305 } else if (left.is(right_arg)) {
306 if (IsOperationCommutative()) {
307 __ movq(left_arg, right);
308 SetArgsReversed();
309 } else {
310 // Order of moves important to avoid destroying left argument.
311 __ movq(left_arg, left);
312 __ movq(right_arg, right);
313 }
314 } else if (right.is(left_arg)) {
315 if (IsOperationCommutative()) {
316 __ movq(right_arg, left);
317 SetArgsReversed();
318 } else {
319 // Order of moves important to avoid destroying right argument.
320 __ movq(right_arg, right);
321 __ movq(left_arg, left);
322 }
323 } else {
324 // Order of moves is not important.
325 __ movq(left_arg, left);
326 __ movq(right_arg, right);
327 }
328 }
329
330 // Update flags to indicate that arguments are in registers.
331 SetArgsInRegisters();
332 __ IncrementCounter(&Counters::generic_binary_stub_calls_regs, 1);
333 }
334
335 // Call the stub.
336 __ CallStub(this);
337}
338
339
340void GenericBinaryOpStub::GenerateCall(
341 MacroAssembler* masm,
342 Register left,
343 Smi* right) {
344 if (!ArgsInRegistersSupported()) {
345 // Pass arguments on the stack.
346 __ push(left);
347 __ Push(right);
348 } else {
349 // The calling convention with registers is left in rdx and right in rax.
350 Register left_arg = rdx;
351 Register right_arg = rax;
352 if (left.is(left_arg)) {
353 __ Move(right_arg, right);
354 } else if (left.is(right_arg) && IsOperationCommutative()) {
355 __ Move(left_arg, right);
356 SetArgsReversed();
357 } else {
358 // For non-commutative operations, left and right_arg might be
359 // the same register. Therefore, the order of the moves is
360 // important here in order to not overwrite left before moving
361 // it to left_arg.
362 __ movq(left_arg, left);
363 __ Move(right_arg, right);
364 }
365
366 // Update flags to indicate that arguments are in registers.
367 SetArgsInRegisters();
368 __ IncrementCounter(&Counters::generic_binary_stub_calls_regs, 1);
369 }
370
371 // Call the stub.
372 __ CallStub(this);
373}
374
375
376void GenericBinaryOpStub::GenerateCall(
377 MacroAssembler* masm,
378 Smi* left,
379 Register right) {
380 if (!ArgsInRegistersSupported()) {
381 // Pass arguments on the stack.
382 __ Push(left);
383 __ push(right);
384 } else {
385 // The calling convention with registers is left in rdx and right in rax.
386 Register left_arg = rdx;
387 Register right_arg = rax;
388 if (right.is(right_arg)) {
389 __ Move(left_arg, left);
390 } else if (right.is(left_arg) && IsOperationCommutative()) {
391 __ Move(right_arg, left);
392 SetArgsReversed();
393 } else {
394 // For non-commutative operations, right and left_arg might be
395 // the same register. Therefore, the order of the moves is
396 // important here in order to not overwrite right before moving
397 // it to right_arg.
398 __ movq(right_arg, right);
399 __ Move(left_arg, left);
400 }
401 // Update flags to indicate that arguments are in registers.
402 SetArgsInRegisters();
403 __ IncrementCounter(&Counters::generic_binary_stub_calls_regs, 1);
404 }
405
406 // Call the stub.
407 __ CallStub(this);
408}
409
410
411class FloatingPointHelper : public AllStatic {
412 public:
413 // Load the operands from rdx and rax into xmm0 and xmm1, as doubles.
414 // If the operands are not both numbers, jump to not_numbers.
415 // Leaves rdx and rax unchanged. SmiOperands assumes both are smis.
416 // NumberOperands assumes both are smis or heap numbers.
417 static void LoadSSE2SmiOperands(MacroAssembler* masm);
418 static void LoadSSE2NumberOperands(MacroAssembler* masm);
419 static void LoadSSE2UnknownOperands(MacroAssembler* masm,
420 Label* not_numbers);
421
422 // Takes the operands in rdx and rax and loads them as integers in rax
423 // and rcx.
424 static void LoadAsIntegers(MacroAssembler* masm,
425 Label* operand_conversion_failure,
426 Register heap_number_map);
427 // As above, but we know the operands to be numbers. In that case,
428 // conversion can't fail.
429 static void LoadNumbersAsIntegers(MacroAssembler* masm);
430};
431
432
433void GenericBinaryOpStub::GenerateSmiCode(MacroAssembler* masm, Label* slow) {
434 // 1. Move arguments into rdx, rax except for DIV and MOD, which need the
435 // dividend in rax and rdx free for the division. Use rax, rbx for those.
436 Comment load_comment(masm, "-- Load arguments");
437 Register left = rdx;
438 Register right = rax;
439 if (op_ == Token::DIV || op_ == Token::MOD) {
440 left = rax;
441 right = rbx;
442 if (HasArgsInRegisters()) {
443 __ movq(rbx, rax);
444 __ movq(rax, rdx);
445 }
446 }
447 if (!HasArgsInRegisters()) {
448 __ movq(right, Operand(rsp, 1 * kPointerSize));
449 __ movq(left, Operand(rsp, 2 * kPointerSize));
450 }
451
452 Label not_smis;
453 // 2. Smi check both operands.
454 if (static_operands_type_.IsSmi()) {
455 // Skip smi check if we know that both arguments are smis.
456 if (FLAG_debug_code) {
457 __ AbortIfNotSmi(left);
458 __ AbortIfNotSmi(right);
459 }
460 if (op_ == Token::BIT_OR) {
461 // Handle OR here, since we do extra smi-checking in the or code below.
462 __ SmiOr(right, right, left);
463 GenerateReturn(masm);
464 return;
465 }
466 } else {
467 if (op_ != Token::BIT_OR) {
468 // Skip the check for OR as it is better combined with the
469 // actual operation.
470 Comment smi_check_comment(masm, "-- Smi check arguments");
471 __ JumpIfNotBothSmi(left, right, &not_smis);
472 }
473 }
474
475 // 3. Operands are both smis (except for OR), perform the operation leaving
476 // the result in rax and check the result if necessary.
477 Comment perform_smi(masm, "-- Perform smi operation");
478 Label use_fp_on_smis;
479 switch (op_) {
480 case Token::ADD: {
481 ASSERT(right.is(rax));
482 __ SmiAdd(right, right, left, &use_fp_on_smis); // ADD is commutative.
483 break;
484 }
485
486 case Token::SUB: {
487 __ SmiSub(left, left, right, &use_fp_on_smis);
488 __ movq(rax, left);
489 break;
490 }
491
492 case Token::MUL:
493 ASSERT(right.is(rax));
494 __ SmiMul(right, right, left, &use_fp_on_smis); // MUL is commutative.
495 break;
496
497 case Token::DIV:
498 ASSERT(left.is(rax));
499 __ SmiDiv(left, left, right, &use_fp_on_smis);
500 break;
501
502 case Token::MOD:
503 ASSERT(left.is(rax));
504 __ SmiMod(left, left, right, slow);
505 break;
506
507 case Token::BIT_OR:
508 ASSERT(right.is(rax));
509 __ movq(rcx, right); // Save the right operand.
510 __ SmiOr(right, right, left); // BIT_OR is commutative.
511 __ testb(right, Immediate(kSmiTagMask));
512 __ j(not_zero, &not_smis);
513 break;
514
515 case Token::BIT_AND:
516 ASSERT(right.is(rax));
517 __ SmiAnd(right, right, left); // BIT_AND is commutative.
518 break;
519
520 case Token::BIT_XOR:
521 ASSERT(right.is(rax));
522 __ SmiXor(right, right, left); // BIT_XOR is commutative.
523 break;
524
525 case Token::SHL:
526 case Token::SHR:
527 case Token::SAR:
528 switch (op_) {
529 case Token::SAR:
530 __ SmiShiftArithmeticRight(left, left, right);
531 break;
532 case Token::SHR:
533 __ SmiShiftLogicalRight(left, left, right, slow);
534 break;
535 case Token::SHL:
536 __ SmiShiftLeft(left, left, right);
537 break;
538 default:
539 UNREACHABLE();
540 }
541 __ movq(rax, left);
542 break;
543
544 default:
545 UNREACHABLE();
546 break;
547 }
548
549 // 4. Emit return of result in rax.
550 GenerateReturn(masm);
551
552 // 5. For some operations emit inline code to perform floating point
553 // operations on known smis (e.g., if the result of the operation
554 // overflowed the smi range).
555 switch (op_) {
556 case Token::ADD:
557 case Token::SUB:
558 case Token::MUL:
559 case Token::DIV: {
560 ASSERT(use_fp_on_smis.is_linked());
561 __ bind(&use_fp_on_smis);
562 if (op_ == Token::DIV) {
563 __ movq(rdx, rax);
564 __ movq(rax, rbx);
565 }
566 // left is rdx, right is rax.
567 __ AllocateHeapNumber(rbx, rcx, slow);
568 FloatingPointHelper::LoadSSE2SmiOperands(masm);
569 switch (op_) {
570 case Token::ADD: __ addsd(xmm0, xmm1); break;
571 case Token::SUB: __ subsd(xmm0, xmm1); break;
572 case Token::MUL: __ mulsd(xmm0, xmm1); break;
573 case Token::DIV: __ divsd(xmm0, xmm1); break;
574 default: UNREACHABLE();
575 }
576 __ movsd(FieldOperand(rbx, HeapNumber::kValueOffset), xmm0);
577 __ movq(rax, rbx);
578 GenerateReturn(masm);
579 }
580 default:
581 break;
582 }
583
584 // 6. Non-smi operands, fall out to the non-smi code with the operands in
585 // rdx and rax.
586 Comment done_comment(masm, "-- Enter non-smi code");
587 __ bind(&not_smis);
588
589 switch (op_) {
590 case Token::DIV:
591 case Token::MOD:
592 // Operands are in rax, rbx at this point.
593 __ movq(rdx, rax);
594 __ movq(rax, rbx);
595 break;
596
597 case Token::BIT_OR:
598 // Right operand is saved in rcx and rax was destroyed by the smi
599 // operation.
600 __ movq(rax, rcx);
601 break;
602
603 default:
604 break;
605 }
606}
607
608
609void GenericBinaryOpStub::Generate(MacroAssembler* masm) {
610 Label call_runtime;
611
612 if (ShouldGenerateSmiCode()) {
613 GenerateSmiCode(masm, &call_runtime);
614 } else if (op_ != Token::MOD) {
615 if (!HasArgsInRegisters()) {
616 GenerateLoadArguments(masm);
617 }
618 }
619 // Floating point case.
620 if (ShouldGenerateFPCode()) {
621 switch (op_) {
622 case Token::ADD:
623 case Token::SUB:
624 case Token::MUL:
625 case Token::DIV: {
626 if (runtime_operands_type_ == BinaryOpIC::DEFAULT &&
627 HasSmiCodeInStub()) {
628 // Execution reaches this point when the first non-smi argument occurs
629 // (and only if smi code is generated). This is the right moment to
630 // patch to HEAP_NUMBERS state. The transition is attempted only for
631 // the four basic operations. The stub stays in the DEFAULT state
632 // forever for all other operations (also if smi code is skipped).
633 GenerateTypeTransition(masm);
634 break;
635 }
636
637 Label not_floats;
638 // rax: y
639 // rdx: x
640 if (static_operands_type_.IsNumber()) {
641 if (FLAG_debug_code) {
642 // Assert at runtime that inputs are only numbers.
643 __ AbortIfNotNumber(rdx);
644 __ AbortIfNotNumber(rax);
645 }
646 FloatingPointHelper::LoadSSE2NumberOperands(masm);
647 } else {
648 FloatingPointHelper::LoadSSE2UnknownOperands(masm, &call_runtime);
649 }
650
651 switch (op_) {
652 case Token::ADD: __ addsd(xmm0, xmm1); break;
653 case Token::SUB: __ subsd(xmm0, xmm1); break;
654 case Token::MUL: __ mulsd(xmm0, xmm1); break;
655 case Token::DIV: __ divsd(xmm0, xmm1); break;
656 default: UNREACHABLE();
657 }
658 // Allocate a heap number, if needed.
659 Label skip_allocation;
660 OverwriteMode mode = mode_;
661 if (HasArgsReversed()) {
662 if (mode == OVERWRITE_RIGHT) {
663 mode = OVERWRITE_LEFT;
664 } else if (mode == OVERWRITE_LEFT) {
665 mode = OVERWRITE_RIGHT;
666 }
667 }
668 switch (mode) {
669 case OVERWRITE_LEFT:
670 __ JumpIfNotSmi(rdx, &skip_allocation);
671 __ AllocateHeapNumber(rbx, rcx, &call_runtime);
672 __ movq(rdx, rbx);
673 __ bind(&skip_allocation);
674 __ movq(rax, rdx);
675 break;
676 case OVERWRITE_RIGHT:
677 // If the argument in rax is already an object, we skip the
678 // allocation of a heap number.
679 __ JumpIfNotSmi(rax, &skip_allocation);
680 // Fall through!
681 case NO_OVERWRITE:
682 // Allocate a heap number for the result. Keep rax and rdx intact
683 // for the possible runtime call.
684 __ AllocateHeapNumber(rbx, rcx, &call_runtime);
685 __ movq(rax, rbx);
686 __ bind(&skip_allocation);
687 break;
688 default: UNREACHABLE();
689 }
690 __ movsd(FieldOperand(rax, HeapNumber::kValueOffset), xmm0);
691 GenerateReturn(masm);
692 __ bind(&not_floats);
693 if (runtime_operands_type_ == BinaryOpIC::DEFAULT &&
694 !HasSmiCodeInStub()) {
695 // Execution reaches this point when the first non-number argument
696 // occurs (and only if smi code is skipped from the stub, otherwise
697 // the patching has already been done earlier in this case branch).
698 // A perfect moment to try patching to STRINGS for ADD operation.
699 if (op_ == Token::ADD) {
700 GenerateTypeTransition(masm);
701 }
702 }
703 break;
704 }
705 case Token::MOD: {
706 // For MOD we go directly to runtime in the non-smi case.
707 break;
708 }
709 case Token::BIT_OR:
710 case Token::BIT_AND:
711 case Token::BIT_XOR:
712 case Token::SAR:
713 case Token::SHL:
714 case Token::SHR: {
715 Label skip_allocation, non_smi_shr_result;
716 Register heap_number_map = r9;
717 __ LoadRoot(heap_number_map, Heap::kHeapNumberMapRootIndex);
718 if (static_operands_type_.IsNumber()) {
719 if (FLAG_debug_code) {
720 // Assert at runtime that inputs are only numbers.
721 __ AbortIfNotNumber(rdx);
722 __ AbortIfNotNumber(rax);
723 }
724 FloatingPointHelper::LoadNumbersAsIntegers(masm);
725 } else {
726 FloatingPointHelper::LoadAsIntegers(masm,
727 &call_runtime,
728 heap_number_map);
729 }
730 switch (op_) {
731 case Token::BIT_OR: __ orl(rax, rcx); break;
732 case Token::BIT_AND: __ andl(rax, rcx); break;
733 case Token::BIT_XOR: __ xorl(rax, rcx); break;
734 case Token::SAR: __ sarl_cl(rax); break;
735 case Token::SHL: __ shll_cl(rax); break;
736 case Token::SHR: {
737 __ shrl_cl(rax);
738 // Check if result is negative. This can only happen for a shift
739 // by zero.
740 __ testl(rax, rax);
741 __ j(negative, &non_smi_shr_result);
742 break;
743 }
744 default: UNREACHABLE();
745 }
746
747 STATIC_ASSERT(kSmiValueSize == 32);
748 // Tag smi result and return.
749 __ Integer32ToSmi(rax, rax);
750 GenerateReturn(masm);
751
752 // All bit-ops except SHR return a signed int32 that can be
753 // returned immediately as a smi.
754 // We might need to allocate a HeapNumber if we shift a negative
755 // number right by zero (i.e., convert to UInt32).
756 if (op_ == Token::SHR) {
757 ASSERT(non_smi_shr_result.is_linked());
758 __ bind(&non_smi_shr_result);
759 // Allocate a heap number if needed.
760 __ movl(rbx, rax); // rbx holds result value (uint32 value as int64).
761 switch (mode_) {
762 case OVERWRITE_LEFT:
763 case OVERWRITE_RIGHT:
764 // If the operand was an object, we skip the
765 // allocation of a heap number.
766 __ movq(rax, Operand(rsp, mode_ == OVERWRITE_RIGHT ?
767 1 * kPointerSize : 2 * kPointerSize));
768 __ JumpIfNotSmi(rax, &skip_allocation);
769 // Fall through!
770 case NO_OVERWRITE:
771 // Allocate heap number in new space.
772 // Not using AllocateHeapNumber macro in order to reuse
773 // already loaded heap_number_map.
774 __ AllocateInNewSpace(HeapNumber::kSize,
775 rax,
776 rcx,
777 no_reg,
778 &call_runtime,
779 TAG_OBJECT);
780 // Set the map.
781 if (FLAG_debug_code) {
782 __ AbortIfNotRootValue(heap_number_map,
783 Heap::kHeapNumberMapRootIndex,
784 "HeapNumberMap register clobbered.");
785 }
786 __ movq(FieldOperand(rax, HeapObject::kMapOffset),
787 heap_number_map);
788 __ bind(&skip_allocation);
789 break;
790 default: UNREACHABLE();
791 }
792 // Store the result in the HeapNumber and return.
793 __ cvtqsi2sd(xmm0, rbx);
794 __ movsd(FieldOperand(rax, HeapNumber::kValueOffset), xmm0);
795 GenerateReturn(masm);
796 }
797
798 break;
799 }
800 default: UNREACHABLE(); break;
801 }
802 }
803
804 // If all else fails, use the runtime system to get the correct
805 // result. If arguments was passed in registers now place them on the
806 // stack in the correct order below the return address.
807 __ bind(&call_runtime);
808
809 if (HasArgsInRegisters()) {
810 GenerateRegisterArgsPush(masm);
811 }
812
813 switch (op_) {
814 case Token::ADD: {
815 // Registers containing left and right operands respectively.
816 Register lhs, rhs;
817
818 if (HasArgsReversed()) {
819 lhs = rax;
820 rhs = rdx;
821 } else {
822 lhs = rdx;
823 rhs = rax;
824 }
825
826 // Test for string arguments before calling runtime.
827 Label not_strings, both_strings, not_string1, string1, string1_smi2;
828
829 // If this stub has already generated FP-specific code then the arguments
830 // are already in rdx and rax.
831 if (!ShouldGenerateFPCode() && !HasArgsInRegisters()) {
832 GenerateLoadArguments(masm);
833 }
834
835 Condition is_smi;
836 is_smi = masm->CheckSmi(lhs);
837 __ j(is_smi, &not_string1);
838 __ CmpObjectType(lhs, FIRST_NONSTRING_TYPE, r8);
839 __ j(above_equal, &not_string1);
840
841 // First argument is a a string, test second.
842 is_smi = masm->CheckSmi(rhs);
843 __ j(is_smi, &string1_smi2);
844 __ CmpObjectType(rhs, FIRST_NONSTRING_TYPE, r9);
845 __ j(above_equal, &string1);
846
847 // First and second argument are strings.
848 StringAddStub string_add_stub(NO_STRING_CHECK_IN_STUB);
849 __ TailCallStub(&string_add_stub);
850
851 __ bind(&string1_smi2);
852 // First argument is a string, second is a smi. Try to lookup the number
853 // string for the smi in the number string cache.
854 NumberToStringStub::GenerateLookupNumberStringCache(
855 masm, rhs, rbx, rcx, r8, true, &string1);
856
857 // Replace second argument on stack and tailcall string add stub to make
858 // the result.
859 __ movq(Operand(rsp, 1 * kPointerSize), rbx);
860 __ TailCallStub(&string_add_stub);
861
862 // Only first argument is a string.
863 __ bind(&string1);
864 __ InvokeBuiltin(Builtins::STRING_ADD_LEFT, JUMP_FUNCTION);
865
866 // First argument was not a string, test second.
867 __ bind(&not_string1);
868 is_smi = masm->CheckSmi(rhs);
869 __ j(is_smi, &not_strings);
870 __ CmpObjectType(rhs, FIRST_NONSTRING_TYPE, rhs);
871 __ j(above_equal, &not_strings);
872
873 // Only second argument is a string.
874 __ InvokeBuiltin(Builtins::STRING_ADD_RIGHT, JUMP_FUNCTION);
875
876 __ bind(&not_strings);
877 // Neither argument is a string.
878 __ InvokeBuiltin(Builtins::ADD, JUMP_FUNCTION);
879 break;
880 }
881 case Token::SUB:
882 __ InvokeBuiltin(Builtins::SUB, JUMP_FUNCTION);
883 break;
884 case Token::MUL:
885 __ InvokeBuiltin(Builtins::MUL, JUMP_FUNCTION);
886 break;
887 case Token::DIV:
888 __ InvokeBuiltin(Builtins::DIV, JUMP_FUNCTION);
889 break;
890 case Token::MOD:
891 __ InvokeBuiltin(Builtins::MOD, JUMP_FUNCTION);
892 break;
893 case Token::BIT_OR:
894 __ InvokeBuiltin(Builtins::BIT_OR, JUMP_FUNCTION);
895 break;
896 case Token::BIT_AND:
897 __ InvokeBuiltin(Builtins::BIT_AND, JUMP_FUNCTION);
898 break;
899 case Token::BIT_XOR:
900 __ InvokeBuiltin(Builtins::BIT_XOR, JUMP_FUNCTION);
901 break;
902 case Token::SAR:
903 __ InvokeBuiltin(Builtins::SAR, JUMP_FUNCTION);
904 break;
905 case Token::SHL:
906 __ InvokeBuiltin(Builtins::SHL, JUMP_FUNCTION);
907 break;
908 case Token::SHR:
909 __ InvokeBuiltin(Builtins::SHR, JUMP_FUNCTION);
910 break;
911 default:
912 UNREACHABLE();
913 }
914}
915
916
917void GenericBinaryOpStub::GenerateLoadArguments(MacroAssembler* masm) {
918 ASSERT(!HasArgsInRegisters());
919 __ movq(rax, Operand(rsp, 1 * kPointerSize));
920 __ movq(rdx, Operand(rsp, 2 * kPointerSize));
921}
922
923
924void GenericBinaryOpStub::GenerateReturn(MacroAssembler* masm) {
925 // If arguments are not passed in registers remove them from the stack before
926 // returning.
927 if (!HasArgsInRegisters()) {
928 __ ret(2 * kPointerSize); // Remove both operands
929 } else {
930 __ ret(0);
931 }
932}
933
934
935void GenericBinaryOpStub::GenerateRegisterArgsPush(MacroAssembler* masm) {
936 ASSERT(HasArgsInRegisters());
937 __ pop(rcx);
938 if (HasArgsReversed()) {
939 __ push(rax);
940 __ push(rdx);
941 } else {
942 __ push(rdx);
943 __ push(rax);
944 }
945 __ push(rcx);
946}
947
948
949void GenericBinaryOpStub::GenerateTypeTransition(MacroAssembler* masm) {
950 Label get_result;
951
952 // Ensure the operands are on the stack.
953 if (HasArgsInRegisters()) {
954 GenerateRegisterArgsPush(masm);
955 }
956
957 // Left and right arguments are already on stack.
958 __ pop(rcx); // Save the return address.
959
960 // Push this stub's key.
961 __ Push(Smi::FromInt(MinorKey()));
962
963 // Although the operation and the type info are encoded into the key,
964 // the encoding is opaque, so push them too.
965 __ Push(Smi::FromInt(op_));
966
967 __ Push(Smi::FromInt(runtime_operands_type_));
968
969 __ push(rcx); // The return address.
970
971 // Perform patching to an appropriate fast case and return the result.
972 __ TailCallExternalReference(
973 ExternalReference(IC_Utility(IC::kBinaryOp_Patch)),
974 5,
975 1);
976}
977
978
979Handle<Code> GetBinaryOpStub(int key, BinaryOpIC::TypeInfo type_info) {
980 GenericBinaryOpStub stub(key, type_info);
981 return stub.GetCode();
982}
983
984
985void TranscendentalCacheStub::Generate(MacroAssembler* masm) {
986 // Input on stack:
987 // rsp[8]: argument (should be number).
988 // rsp[0]: return address.
989 Label runtime_call;
990 Label runtime_call_clear_stack;
991 Label input_not_smi;
Kristian Monsen0d5e1162010-09-30 15:31:59 +0100992 NearLabel loaded;
Kristian Monsen80d68ea2010-09-08 11:05:35 +0100993 // Test that rax is a number.
994 __ movq(rax, Operand(rsp, kPointerSize));
995 __ JumpIfNotSmi(rax, &input_not_smi);
996 // Input is a smi. Untag and load it onto the FPU stack.
997 // Then load the bits of the double into rbx.
998 __ SmiToInteger32(rax, rax);
999 __ subq(rsp, Immediate(kPointerSize));
1000 __ cvtlsi2sd(xmm1, rax);
1001 __ movsd(Operand(rsp, 0), xmm1);
1002 __ movq(rbx, xmm1);
1003 __ movq(rdx, xmm1);
1004 __ fld_d(Operand(rsp, 0));
1005 __ addq(rsp, Immediate(kPointerSize));
1006 __ jmp(&loaded);
1007
1008 __ bind(&input_not_smi);
1009 // Check if input is a HeapNumber.
1010 __ Move(rbx, Factory::heap_number_map());
1011 __ cmpq(rbx, FieldOperand(rax, HeapObject::kMapOffset));
1012 __ j(not_equal, &runtime_call);
1013 // Input is a HeapNumber. Push it on the FPU stack and load its
1014 // bits into rbx.
1015 __ fld_d(FieldOperand(rax, HeapNumber::kValueOffset));
1016 __ movq(rbx, FieldOperand(rax, HeapNumber::kValueOffset));
1017 __ movq(rdx, rbx);
1018 __ bind(&loaded);
1019 // ST[0] == double value
1020 // rbx = bits of double value.
1021 // rdx = also bits of double value.
1022 // Compute hash (h is 32 bits, bits are 64 and the shifts are arithmetic):
1023 // h = h0 = bits ^ (bits >> 32);
1024 // h ^= h >> 16;
1025 // h ^= h >> 8;
1026 // h = h & (cacheSize - 1);
1027 // or h = (h0 ^ (h0 >> 8) ^ (h0 >> 16) ^ (h0 >> 24)) & (cacheSize - 1)
1028 __ sar(rdx, Immediate(32));
1029 __ xorl(rdx, rbx);
1030 __ movl(rcx, rdx);
1031 __ movl(rax, rdx);
1032 __ movl(rdi, rdx);
1033 __ sarl(rdx, Immediate(8));
1034 __ sarl(rcx, Immediate(16));
1035 __ sarl(rax, Immediate(24));
1036 __ xorl(rcx, rdx);
1037 __ xorl(rax, rdi);
1038 __ xorl(rcx, rax);
1039 ASSERT(IsPowerOf2(TranscendentalCache::kCacheSize));
1040 __ andl(rcx, Immediate(TranscendentalCache::kCacheSize - 1));
1041
1042 // ST[0] == double value.
1043 // rbx = bits of double value.
1044 // rcx = TranscendentalCache::hash(double value).
1045 __ movq(rax, ExternalReference::transcendental_cache_array_address());
1046 // rax points to cache array.
1047 __ movq(rax, Operand(rax, type_ * sizeof(TranscendentalCache::caches_[0])));
1048 // rax points to the cache for the type type_.
1049 // If NULL, the cache hasn't been initialized yet, so go through runtime.
1050 __ testq(rax, rax);
1051 __ j(zero, &runtime_call_clear_stack);
1052#ifdef DEBUG
1053 // Check that the layout of cache elements match expectations.
1054 { // NOLINT - doesn't like a single brace on a line.
1055 TranscendentalCache::Element test_elem[2];
1056 char* elem_start = reinterpret_cast<char*>(&test_elem[0]);
1057 char* elem2_start = reinterpret_cast<char*>(&test_elem[1]);
1058 char* elem_in0 = reinterpret_cast<char*>(&(test_elem[0].in[0]));
1059 char* elem_in1 = reinterpret_cast<char*>(&(test_elem[0].in[1]));
1060 char* elem_out = reinterpret_cast<char*>(&(test_elem[0].output));
1061 // Two uint_32's and a pointer per element.
1062 CHECK_EQ(16, static_cast<int>(elem2_start - elem_start));
1063 CHECK_EQ(0, static_cast<int>(elem_in0 - elem_start));
1064 CHECK_EQ(kIntSize, static_cast<int>(elem_in1 - elem_start));
1065 CHECK_EQ(2 * kIntSize, static_cast<int>(elem_out - elem_start));
1066 }
1067#endif
1068 // Find the address of the rcx'th entry in the cache, i.e., &rax[rcx*16].
1069 __ addl(rcx, rcx);
1070 __ lea(rcx, Operand(rax, rcx, times_8, 0));
1071 // Check if cache matches: Double value is stored in uint32_t[2] array.
Kristian Monsen0d5e1162010-09-30 15:31:59 +01001072 NearLabel cache_miss;
Kristian Monsen80d68ea2010-09-08 11:05:35 +01001073 __ cmpq(rbx, Operand(rcx, 0));
1074 __ j(not_equal, &cache_miss);
1075 // Cache hit!
1076 __ movq(rax, Operand(rcx, 2 * kIntSize));
1077 __ fstp(0); // Clear FPU stack.
1078 __ ret(kPointerSize);
1079
1080 __ bind(&cache_miss);
1081 // Update cache with new value.
1082 Label nan_result;
1083 GenerateOperation(masm, &nan_result);
1084 __ AllocateHeapNumber(rax, rdi, &runtime_call_clear_stack);
1085 __ movq(Operand(rcx, 0), rbx);
1086 __ movq(Operand(rcx, 2 * kIntSize), rax);
1087 __ fstp_d(FieldOperand(rax, HeapNumber::kValueOffset));
1088 __ ret(kPointerSize);
1089
1090 __ bind(&runtime_call_clear_stack);
1091 __ fstp(0);
1092 __ bind(&runtime_call);
1093 __ TailCallExternalReference(ExternalReference(RuntimeFunction()), 1, 1);
1094
1095 __ bind(&nan_result);
1096 __ fstp(0); // Remove argument from FPU stack.
1097 __ LoadRoot(rax, Heap::kNanValueRootIndex);
1098 __ movq(Operand(rcx, 0), rbx);
1099 __ movq(Operand(rcx, 2 * kIntSize), rax);
1100 __ ret(kPointerSize);
1101}
1102
1103
1104Runtime::FunctionId TranscendentalCacheStub::RuntimeFunction() {
1105 switch (type_) {
1106 // Add more cases when necessary.
1107 case TranscendentalCache::SIN: return Runtime::kMath_sin;
1108 case TranscendentalCache::COS: return Runtime::kMath_cos;
1109 default:
1110 UNIMPLEMENTED();
1111 return Runtime::kAbort;
1112 }
1113}
1114
1115
1116void TranscendentalCacheStub::GenerateOperation(MacroAssembler* masm,
1117 Label* on_nan_result) {
1118 // Registers:
1119 // rbx: Bits of input double. Must be preserved.
1120 // rcx: Pointer to cache entry. Must be preserved.
1121 // st(0): Input double
1122 Label done;
1123 ASSERT(type_ == TranscendentalCache::SIN ||
1124 type_ == TranscendentalCache::COS);
1125 // More transcendental types can be added later.
1126
1127 // Both fsin and fcos require arguments in the range +/-2^63 and
1128 // return NaN for infinities and NaN. They can share all code except
1129 // the actual fsin/fcos operation.
1130 Label in_range;
1131 // If argument is outside the range -2^63..2^63, fsin/cos doesn't
1132 // work. We must reduce it to the appropriate range.
1133 __ movq(rdi, rbx);
1134 // Move exponent and sign bits to low bits.
1135 __ shr(rdi, Immediate(HeapNumber::kMantissaBits));
1136 // Remove sign bit.
1137 __ andl(rdi, Immediate((1 << HeapNumber::kExponentBits) - 1));
1138 int supported_exponent_limit = (63 + HeapNumber::kExponentBias);
1139 __ cmpl(rdi, Immediate(supported_exponent_limit));
1140 __ j(below, &in_range);
1141 // Check for infinity and NaN. Both return NaN for sin.
1142 __ cmpl(rdi, Immediate(0x7ff));
1143 __ j(equal, on_nan_result);
1144
1145 // Use fpmod to restrict argument to the range +/-2*PI.
1146 __ fldpi();
1147 __ fadd(0);
1148 __ fld(1);
1149 // FPU Stack: input, 2*pi, input.
1150 {
1151 Label no_exceptions;
1152 __ fwait();
1153 __ fnstsw_ax();
1154 // Clear if Illegal Operand or Zero Division exceptions are set.
1155 __ testl(rax, Immediate(5)); // #IO and #ZD flags of FPU status word.
1156 __ j(zero, &no_exceptions);
1157 __ fnclex();
1158 __ bind(&no_exceptions);
1159 }
1160
1161 // Compute st(0) % st(1)
1162 {
Kristian Monsen0d5e1162010-09-30 15:31:59 +01001163 NearLabel partial_remainder_loop;
Kristian Monsen80d68ea2010-09-08 11:05:35 +01001164 __ bind(&partial_remainder_loop);
1165 __ fprem1();
1166 __ fwait();
1167 __ fnstsw_ax();
1168 __ testl(rax, Immediate(0x400)); // Check C2 bit of FPU status word.
1169 // If C2 is set, computation only has partial result. Loop to
1170 // continue computation.
1171 __ j(not_zero, &partial_remainder_loop);
1172 }
1173 // FPU Stack: input, 2*pi, input % 2*pi
1174 __ fstp(2);
1175 // FPU Stack: input % 2*pi, 2*pi,
1176 __ fstp(0);
1177 // FPU Stack: input % 2*pi
1178 __ bind(&in_range);
1179 switch (type_) {
1180 case TranscendentalCache::SIN:
1181 __ fsin();
1182 break;
1183 case TranscendentalCache::COS:
1184 __ fcos();
1185 break;
1186 default:
1187 UNREACHABLE();
1188 }
1189 __ bind(&done);
1190}
1191
1192
1193// Get the integer part of a heap number.
1194// Overwrites the contents of rdi, rbx and rcx. Result cannot be rdi or rbx.
1195void IntegerConvert(MacroAssembler* masm,
1196 Register result,
1197 Register source) {
1198 // Result may be rcx. If result and source are the same register, source will
1199 // be overwritten.
1200 ASSERT(!result.is(rdi) && !result.is(rbx));
1201 // TODO(lrn): When type info reaches here, if value is a 32-bit integer, use
1202 // cvttsd2si (32-bit version) directly.
1203 Register double_exponent = rbx;
1204 Register double_value = rdi;
Kristian Monsen0d5e1162010-09-30 15:31:59 +01001205 NearLabel done, exponent_63_plus;
Kristian Monsen80d68ea2010-09-08 11:05:35 +01001206 // Get double and extract exponent.
1207 __ movq(double_value, FieldOperand(source, HeapNumber::kValueOffset));
1208 // Clear result preemptively, in case we need to return zero.
1209 __ xorl(result, result);
1210 __ movq(xmm0, double_value); // Save copy in xmm0 in case we need it there.
1211 // Double to remove sign bit, shift exponent down to least significant bits.
1212 // and subtract bias to get the unshifted, unbiased exponent.
1213 __ lea(double_exponent, Operand(double_value, double_value, times_1, 0));
1214 __ shr(double_exponent, Immediate(64 - HeapNumber::kExponentBits));
1215 __ subl(double_exponent, Immediate(HeapNumber::kExponentBias));
1216 // Check whether the exponent is too big for a 63 bit unsigned integer.
1217 __ cmpl(double_exponent, Immediate(63));
1218 __ j(above_equal, &exponent_63_plus);
1219 // Handle exponent range 0..62.
1220 __ cvttsd2siq(result, xmm0);
1221 __ jmp(&done);
1222
1223 __ bind(&exponent_63_plus);
1224 // Exponent negative or 63+.
1225 __ cmpl(double_exponent, Immediate(83));
1226 // If exponent negative or above 83, number contains no significant bits in
1227 // the range 0..2^31, so result is zero, and rcx already holds zero.
1228 __ j(above, &done);
1229
1230 // Exponent in rage 63..83.
1231 // Mantissa * 2^exponent contains bits in the range 2^0..2^31, namely
1232 // the least significant exponent-52 bits.
1233
1234 // Negate low bits of mantissa if value is negative.
1235 __ addq(double_value, double_value); // Move sign bit to carry.
1236 __ sbbl(result, result); // And convert carry to -1 in result register.
1237 // if scratch2 is negative, do (scratch2-1)^-1, otherwise (scratch2-0)^0.
1238 __ addl(double_value, result);
1239 // Do xor in opposite directions depending on where we want the result
1240 // (depending on whether result is rcx or not).
1241
1242 if (result.is(rcx)) {
1243 __ xorl(double_value, result);
1244 // Left shift mantissa by (exponent - mantissabits - 1) to save the
1245 // bits that have positional values below 2^32 (the extra -1 comes from the
1246 // doubling done above to move the sign bit into the carry flag).
1247 __ leal(rcx, Operand(double_exponent, -HeapNumber::kMantissaBits - 1));
1248 __ shll_cl(double_value);
1249 __ movl(result, double_value);
1250 } else {
1251 // As the then-branch, but move double-value to result before shifting.
1252 __ xorl(result, double_value);
1253 __ leal(rcx, Operand(double_exponent, -HeapNumber::kMantissaBits - 1));
1254 __ shll_cl(result);
1255 }
1256
1257 __ bind(&done);
1258}
1259
1260
1261// Input: rdx, rax are the left and right objects of a bit op.
1262// Output: rax, rcx are left and right integers for a bit op.
1263void FloatingPointHelper::LoadNumbersAsIntegers(MacroAssembler* masm) {
1264 // Check float operands.
1265 Label done;
1266 Label rax_is_smi;
1267 Label rax_is_object;
1268 Label rdx_is_object;
1269
1270 __ JumpIfNotSmi(rdx, &rdx_is_object);
1271 __ SmiToInteger32(rdx, rdx);
1272 __ JumpIfSmi(rax, &rax_is_smi);
1273
1274 __ bind(&rax_is_object);
1275 IntegerConvert(masm, rcx, rax); // Uses rdi, rcx and rbx.
1276 __ jmp(&done);
1277
1278 __ bind(&rdx_is_object);
1279 IntegerConvert(masm, rdx, rdx); // Uses rdi, rcx and rbx.
1280 __ JumpIfNotSmi(rax, &rax_is_object);
1281 __ bind(&rax_is_smi);
1282 __ SmiToInteger32(rcx, rax);
1283
1284 __ bind(&done);
1285 __ movl(rax, rdx);
1286}
1287
1288
1289// Input: rdx, rax are the left and right objects of a bit op.
1290// Output: rax, rcx are left and right integers for a bit op.
1291void FloatingPointHelper::LoadAsIntegers(MacroAssembler* masm,
1292 Label* conversion_failure,
1293 Register heap_number_map) {
1294 // Check float operands.
1295 Label arg1_is_object, check_undefined_arg1;
1296 Label arg2_is_object, check_undefined_arg2;
1297 Label load_arg2, done;
1298
1299 __ JumpIfNotSmi(rdx, &arg1_is_object);
1300 __ SmiToInteger32(rdx, rdx);
1301 __ jmp(&load_arg2);
1302
1303 // If the argument is undefined it converts to zero (ECMA-262, section 9.5).
1304 __ bind(&check_undefined_arg1);
1305 __ CompareRoot(rdx, Heap::kUndefinedValueRootIndex);
1306 __ j(not_equal, conversion_failure);
1307 __ movl(rdx, Immediate(0));
1308 __ jmp(&load_arg2);
1309
1310 __ bind(&arg1_is_object);
1311 __ cmpq(FieldOperand(rdx, HeapObject::kMapOffset), heap_number_map);
1312 __ j(not_equal, &check_undefined_arg1);
1313 // Get the untagged integer version of the edx heap number in rcx.
1314 IntegerConvert(masm, rdx, rdx);
1315
1316 // Here rdx has the untagged integer, rax has a Smi or a heap number.
1317 __ bind(&load_arg2);
1318 // Test if arg2 is a Smi.
1319 __ JumpIfNotSmi(rax, &arg2_is_object);
1320 __ SmiToInteger32(rax, rax);
1321 __ movl(rcx, rax);
1322 __ jmp(&done);
1323
1324 // If the argument is undefined it converts to zero (ECMA-262, section 9.5).
1325 __ bind(&check_undefined_arg2);
1326 __ CompareRoot(rax, Heap::kUndefinedValueRootIndex);
1327 __ j(not_equal, conversion_failure);
1328 __ movl(rcx, Immediate(0));
1329 __ jmp(&done);
1330
1331 __ bind(&arg2_is_object);
1332 __ cmpq(FieldOperand(rax, HeapObject::kMapOffset), heap_number_map);
1333 __ j(not_equal, &check_undefined_arg2);
1334 // Get the untagged integer version of the rax heap number in rcx.
1335 IntegerConvert(masm, rcx, rax);
1336 __ bind(&done);
1337 __ movl(rax, rdx);
1338}
1339
1340
1341void FloatingPointHelper::LoadSSE2SmiOperands(MacroAssembler* masm) {
1342 __ SmiToInteger32(kScratchRegister, rdx);
1343 __ cvtlsi2sd(xmm0, kScratchRegister);
1344 __ SmiToInteger32(kScratchRegister, rax);
1345 __ cvtlsi2sd(xmm1, kScratchRegister);
1346}
1347
1348
1349void FloatingPointHelper::LoadSSE2NumberOperands(MacroAssembler* masm) {
1350 Label load_smi_rdx, load_nonsmi_rax, load_smi_rax, done;
1351 // Load operand in rdx into xmm0.
1352 __ JumpIfSmi(rdx, &load_smi_rdx);
1353 __ movsd(xmm0, FieldOperand(rdx, HeapNumber::kValueOffset));
1354 // Load operand in rax into xmm1.
1355 __ JumpIfSmi(rax, &load_smi_rax);
1356 __ bind(&load_nonsmi_rax);
1357 __ movsd(xmm1, FieldOperand(rax, HeapNumber::kValueOffset));
1358 __ jmp(&done);
1359
1360 __ bind(&load_smi_rdx);
1361 __ SmiToInteger32(kScratchRegister, rdx);
1362 __ cvtlsi2sd(xmm0, kScratchRegister);
1363 __ JumpIfNotSmi(rax, &load_nonsmi_rax);
1364
1365 __ bind(&load_smi_rax);
1366 __ SmiToInteger32(kScratchRegister, rax);
1367 __ cvtlsi2sd(xmm1, kScratchRegister);
1368
1369 __ bind(&done);
1370}
1371
1372
1373void FloatingPointHelper::LoadSSE2UnknownOperands(MacroAssembler* masm,
1374 Label* not_numbers) {
1375 Label load_smi_rdx, load_nonsmi_rax, load_smi_rax, load_float_rax, done;
1376 // Load operand in rdx into xmm0, or branch to not_numbers.
1377 __ LoadRoot(rcx, Heap::kHeapNumberMapRootIndex);
1378 __ JumpIfSmi(rdx, &load_smi_rdx);
1379 __ cmpq(FieldOperand(rdx, HeapObject::kMapOffset), rcx);
1380 __ j(not_equal, not_numbers); // Argument in rdx is not a number.
1381 __ movsd(xmm0, FieldOperand(rdx, HeapNumber::kValueOffset));
1382 // Load operand in rax into xmm1, or branch to not_numbers.
1383 __ JumpIfSmi(rax, &load_smi_rax);
1384
1385 __ bind(&load_nonsmi_rax);
1386 __ cmpq(FieldOperand(rax, HeapObject::kMapOffset), rcx);
1387 __ j(not_equal, not_numbers);
1388 __ movsd(xmm1, FieldOperand(rax, HeapNumber::kValueOffset));
1389 __ jmp(&done);
1390
1391 __ bind(&load_smi_rdx);
1392 __ SmiToInteger32(kScratchRegister, rdx);
1393 __ cvtlsi2sd(xmm0, kScratchRegister);
1394 __ JumpIfNotSmi(rax, &load_nonsmi_rax);
1395
1396 __ bind(&load_smi_rax);
1397 __ SmiToInteger32(kScratchRegister, rax);
1398 __ cvtlsi2sd(xmm1, kScratchRegister);
1399 __ bind(&done);
1400}
1401
1402
1403void GenericUnaryOpStub::Generate(MacroAssembler* masm) {
1404 Label slow, done;
1405
1406 if (op_ == Token::SUB) {
Kristian Monsen0d5e1162010-09-30 15:31:59 +01001407 if (include_smi_code_) {
1408 // Check whether the value is a smi.
1409 Label try_float;
1410 __ JumpIfNotSmi(rax, &try_float);
1411 if (negative_zero_ == kIgnoreNegativeZero) {
1412 __ SmiCompare(rax, Smi::FromInt(0));
1413 __ j(equal, &done);
1414 }
1415 __ SmiNeg(rax, rax, &done);
Kristian Monsen80d68ea2010-09-08 11:05:35 +01001416
Kristian Monsen0d5e1162010-09-30 15:31:59 +01001417 // Either zero or Smi::kMinValue, neither of which become a smi when
1418 // negated. We handle negative zero here if required. We always enter
1419 // the runtime system if we have Smi::kMinValue.
1420 if (negative_zero_ == kStrictNegativeZero) {
1421 __ SmiCompare(rax, Smi::FromInt(0));
1422 __ j(not_equal, &slow);
1423 __ Move(rax, Factory::minus_zero_value());
1424 __ jmp(&done);
1425 } else {
1426 __ SmiCompare(rax, Smi::FromInt(Smi::kMinValue));
1427 __ j(equal, &slow);
1428 __ jmp(&done);
1429 }
1430 // Try floating point case.
1431 __ bind(&try_float);
1432 } else if (FLAG_debug_code) {
1433 __ AbortIfSmi(rax);
Kristian Monsen80d68ea2010-09-08 11:05:35 +01001434 }
1435
Kristian Monsen80d68ea2010-09-08 11:05:35 +01001436 __ movq(rdx, FieldOperand(rax, HeapObject::kMapOffset));
1437 __ CompareRoot(rdx, Heap::kHeapNumberMapRootIndex);
1438 __ j(not_equal, &slow);
1439 // Operand is a float, negate its value by flipping sign bit.
1440 __ movq(rdx, FieldOperand(rax, HeapNumber::kValueOffset));
1441 __ movq(kScratchRegister, Immediate(0x01));
1442 __ shl(kScratchRegister, Immediate(63));
1443 __ xor_(rdx, kScratchRegister); // Flip sign.
1444 // rdx is value to store.
1445 if (overwrite_ == UNARY_OVERWRITE) {
1446 __ movq(FieldOperand(rax, HeapNumber::kValueOffset), rdx);
1447 } else {
1448 __ AllocateHeapNumber(rcx, rbx, &slow);
1449 // rcx: allocated 'empty' number
1450 __ movq(FieldOperand(rcx, HeapNumber::kValueOffset), rdx);
1451 __ movq(rax, rcx);
1452 }
1453 } else if (op_ == Token::BIT_NOT) {
Kristian Monsen0d5e1162010-09-30 15:31:59 +01001454 if (include_smi_code_) {
1455 Label try_float;
1456 __ JumpIfNotSmi(rax, &try_float);
1457 __ SmiNot(rax, rax);
1458 __ jmp(&done);
1459 // Try floating point case.
1460 __ bind(&try_float);
1461 } else if (FLAG_debug_code) {
1462 __ AbortIfSmi(rax);
1463 }
1464
Kristian Monsen80d68ea2010-09-08 11:05:35 +01001465 // Check if the operand is a heap number.
1466 __ movq(rdx, FieldOperand(rax, HeapObject::kMapOffset));
1467 __ CompareRoot(rdx, Heap::kHeapNumberMapRootIndex);
1468 __ j(not_equal, &slow);
1469
1470 // Convert the heap number in rax to an untagged integer in rcx.
1471 IntegerConvert(masm, rax, rax);
1472
1473 // Do the bitwise operation and smi tag the result.
1474 __ notl(rax);
1475 __ Integer32ToSmi(rax, rax);
1476 }
1477
1478 // Return from the stub.
1479 __ bind(&done);
1480 __ StubReturn(1);
1481
1482 // Handle the slow case by jumping to the JavaScript builtin.
1483 __ bind(&slow);
1484 __ pop(rcx); // pop return address
1485 __ push(rax);
1486 __ push(rcx); // push return address
1487 switch (op_) {
1488 case Token::SUB:
1489 __ InvokeBuiltin(Builtins::UNARY_MINUS, JUMP_FUNCTION);
1490 break;
1491 case Token::BIT_NOT:
1492 __ InvokeBuiltin(Builtins::BIT_NOT, JUMP_FUNCTION);
1493 break;
1494 default:
1495 UNREACHABLE();
1496 }
1497}
1498
1499
1500void ArgumentsAccessStub::GenerateReadElement(MacroAssembler* masm) {
1501 // The key is in rdx and the parameter count is in rax.
1502
1503 // The displacement is used for skipping the frame pointer on the
1504 // stack. It is the offset of the last parameter (if any) relative
1505 // to the frame pointer.
1506 static const int kDisplacement = 1 * kPointerSize;
1507
1508 // Check that the key is a smi.
1509 Label slow;
1510 __ JumpIfNotSmi(rdx, &slow);
1511
1512 // Check if the calling frame is an arguments adaptor frame.
1513 Label adaptor;
1514 __ movq(rbx, Operand(rbp, StandardFrameConstants::kCallerFPOffset));
1515 __ SmiCompare(Operand(rbx, StandardFrameConstants::kContextOffset),
1516 Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR));
1517 __ j(equal, &adaptor);
1518
1519 // Check index against formal parameters count limit passed in
1520 // through register rax. Use unsigned comparison to get negative
1521 // check for free.
1522 __ cmpq(rdx, rax);
1523 __ j(above_equal, &slow);
1524
1525 // Read the argument from the stack and return it.
1526 SmiIndex index = masm->SmiToIndex(rax, rax, kPointerSizeLog2);
1527 __ lea(rbx, Operand(rbp, index.reg, index.scale, 0));
1528 index = masm->SmiToNegativeIndex(rdx, rdx, kPointerSizeLog2);
1529 __ movq(rax, Operand(rbx, index.reg, index.scale, kDisplacement));
1530 __ Ret();
1531
1532 // Arguments adaptor case: Check index against actual arguments
1533 // limit found in the arguments adaptor frame. Use unsigned
1534 // comparison to get negative check for free.
1535 __ bind(&adaptor);
1536 __ movq(rcx, Operand(rbx, ArgumentsAdaptorFrameConstants::kLengthOffset));
1537 __ cmpq(rdx, rcx);
1538 __ j(above_equal, &slow);
1539
1540 // Read the argument from the stack and return it.
1541 index = masm->SmiToIndex(rax, rcx, kPointerSizeLog2);
1542 __ lea(rbx, Operand(rbx, index.reg, index.scale, 0));
1543 index = masm->SmiToNegativeIndex(rdx, rdx, kPointerSizeLog2);
1544 __ movq(rax, Operand(rbx, index.reg, index.scale, kDisplacement));
1545 __ Ret();
1546
1547 // Slow-case: Handle non-smi or out-of-bounds access to arguments
1548 // by calling the runtime system.
1549 __ bind(&slow);
1550 __ pop(rbx); // Return address.
1551 __ push(rdx);
1552 __ push(rbx);
1553 __ TailCallRuntime(Runtime::kGetArgumentsProperty, 1, 1);
1554}
1555
1556
1557void ArgumentsAccessStub::GenerateNewObject(MacroAssembler* masm) {
1558 // rsp[0] : return address
1559 // rsp[8] : number of parameters
1560 // rsp[16] : receiver displacement
1561 // rsp[24] : function
1562
1563 // The displacement is used for skipping the return address and the
1564 // frame pointer on the stack. It is the offset of the last
1565 // parameter (if any) relative to the frame pointer.
1566 static const int kDisplacement = 2 * kPointerSize;
1567
1568 // Check if the calling frame is an arguments adaptor frame.
1569 Label adaptor_frame, try_allocate, runtime;
1570 __ movq(rdx, Operand(rbp, StandardFrameConstants::kCallerFPOffset));
1571 __ SmiCompare(Operand(rdx, StandardFrameConstants::kContextOffset),
1572 Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR));
1573 __ j(equal, &adaptor_frame);
1574
1575 // Get the length from the frame.
1576 __ SmiToInteger32(rcx, Operand(rsp, 1 * kPointerSize));
1577 __ jmp(&try_allocate);
1578
1579 // Patch the arguments.length and the parameters pointer.
1580 __ bind(&adaptor_frame);
1581 __ SmiToInteger32(rcx,
1582 Operand(rdx,
1583 ArgumentsAdaptorFrameConstants::kLengthOffset));
1584 // Space on stack must already hold a smi.
1585 __ Integer32ToSmiField(Operand(rsp, 1 * kPointerSize), rcx);
1586 // Do not clobber the length index for the indexing operation since
1587 // it is used compute the size for allocation later.
1588 __ lea(rdx, Operand(rdx, rcx, times_pointer_size, kDisplacement));
1589 __ movq(Operand(rsp, 2 * kPointerSize), rdx);
1590
1591 // Try the new space allocation. Start out with computing the size of
1592 // the arguments object and the elements array.
1593 Label add_arguments_object;
1594 __ bind(&try_allocate);
1595 __ testl(rcx, rcx);
1596 __ j(zero, &add_arguments_object);
1597 __ leal(rcx, Operand(rcx, times_pointer_size, FixedArray::kHeaderSize));
1598 __ bind(&add_arguments_object);
1599 __ addl(rcx, Immediate(Heap::kArgumentsObjectSize));
1600
1601 // Do the allocation of both objects in one go.
1602 __ AllocateInNewSpace(rcx, rax, rdx, rbx, &runtime, TAG_OBJECT);
1603
1604 // Get the arguments boilerplate from the current (global) context.
1605 int offset = Context::SlotOffset(Context::ARGUMENTS_BOILERPLATE_INDEX);
1606 __ movq(rdi, Operand(rsi, Context::SlotOffset(Context::GLOBAL_INDEX)));
1607 __ movq(rdi, FieldOperand(rdi, GlobalObject::kGlobalContextOffset));
1608 __ movq(rdi, Operand(rdi, offset));
1609
1610 // Copy the JS object part.
1611 STATIC_ASSERT(JSObject::kHeaderSize == 3 * kPointerSize);
1612 __ movq(kScratchRegister, FieldOperand(rdi, 0 * kPointerSize));
1613 __ movq(rdx, FieldOperand(rdi, 1 * kPointerSize));
1614 __ movq(rbx, FieldOperand(rdi, 2 * kPointerSize));
1615 __ movq(FieldOperand(rax, 0 * kPointerSize), kScratchRegister);
1616 __ movq(FieldOperand(rax, 1 * kPointerSize), rdx);
1617 __ movq(FieldOperand(rax, 2 * kPointerSize), rbx);
1618
1619 // Setup the callee in-object property.
1620 ASSERT(Heap::arguments_callee_index == 0);
1621 __ movq(kScratchRegister, Operand(rsp, 3 * kPointerSize));
1622 __ movq(FieldOperand(rax, JSObject::kHeaderSize), kScratchRegister);
1623
1624 // Get the length (smi tagged) and set that as an in-object property too.
1625 ASSERT(Heap::arguments_length_index == 1);
1626 __ movq(rcx, Operand(rsp, 1 * kPointerSize));
1627 __ movq(FieldOperand(rax, JSObject::kHeaderSize + kPointerSize), rcx);
1628
1629 // If there are no actual arguments, we're done.
1630 Label done;
1631 __ SmiTest(rcx);
1632 __ j(zero, &done);
1633
1634 // Get the parameters pointer from the stack and untag the length.
1635 __ movq(rdx, Operand(rsp, 2 * kPointerSize));
1636
1637 // Setup the elements pointer in the allocated arguments object and
1638 // initialize the header in the elements fixed array.
1639 __ lea(rdi, Operand(rax, Heap::kArgumentsObjectSize));
1640 __ movq(FieldOperand(rax, JSObject::kElementsOffset), rdi);
1641 __ LoadRoot(kScratchRegister, Heap::kFixedArrayMapRootIndex);
1642 __ movq(FieldOperand(rdi, FixedArray::kMapOffset), kScratchRegister);
1643 __ movq(FieldOperand(rdi, FixedArray::kLengthOffset), rcx);
1644 __ SmiToInteger32(rcx, rcx); // Untag length for the loop below.
1645
1646 // Copy the fixed array slots.
1647 Label loop;
1648 __ bind(&loop);
1649 __ movq(kScratchRegister, Operand(rdx, -1 * kPointerSize)); // Skip receiver.
1650 __ movq(FieldOperand(rdi, FixedArray::kHeaderSize), kScratchRegister);
1651 __ addq(rdi, Immediate(kPointerSize));
1652 __ subq(rdx, Immediate(kPointerSize));
1653 __ decl(rcx);
1654 __ j(not_zero, &loop);
1655
1656 // Return and remove the on-stack parameters.
1657 __ bind(&done);
1658 __ ret(3 * kPointerSize);
1659
1660 // Do the runtime call to allocate the arguments object.
1661 __ bind(&runtime);
1662 __ TailCallRuntime(Runtime::kNewArgumentsFast, 3, 1);
1663}
1664
1665
1666void RegExpExecStub::Generate(MacroAssembler* masm) {
1667 // Just jump directly to runtime if native RegExp is not selected at compile
1668 // time or if regexp entry in generated code is turned off runtime switch or
1669 // at compilation.
1670#ifdef V8_INTERPRETED_REGEXP
1671 __ TailCallRuntime(Runtime::kRegExpExec, 4, 1);
1672#else // V8_INTERPRETED_REGEXP
1673 if (!FLAG_regexp_entry_native) {
1674 __ TailCallRuntime(Runtime::kRegExpExec, 4, 1);
1675 return;
1676 }
1677
1678 // Stack frame on entry.
1679 // esp[0]: return address
1680 // esp[8]: last_match_info (expected JSArray)
1681 // esp[16]: previous index
1682 // esp[24]: subject string
1683 // esp[32]: JSRegExp object
1684
1685 static const int kLastMatchInfoOffset = 1 * kPointerSize;
1686 static const int kPreviousIndexOffset = 2 * kPointerSize;
1687 static const int kSubjectOffset = 3 * kPointerSize;
1688 static const int kJSRegExpOffset = 4 * kPointerSize;
1689
1690 Label runtime;
1691
1692 // Ensure that a RegExp stack is allocated.
1693 ExternalReference address_of_regexp_stack_memory_address =
1694 ExternalReference::address_of_regexp_stack_memory_address();
1695 ExternalReference address_of_regexp_stack_memory_size =
1696 ExternalReference::address_of_regexp_stack_memory_size();
1697 __ movq(kScratchRegister, address_of_regexp_stack_memory_size);
1698 __ movq(kScratchRegister, Operand(kScratchRegister, 0));
1699 __ testq(kScratchRegister, kScratchRegister);
1700 __ j(zero, &runtime);
1701
1702
1703 // Check that the first argument is a JSRegExp object.
1704 __ movq(rax, Operand(rsp, kJSRegExpOffset));
1705 __ JumpIfSmi(rax, &runtime);
1706 __ CmpObjectType(rax, JS_REGEXP_TYPE, kScratchRegister);
1707 __ j(not_equal, &runtime);
1708 // Check that the RegExp has been compiled (data contains a fixed array).
1709 __ movq(rcx, FieldOperand(rax, JSRegExp::kDataOffset));
1710 if (FLAG_debug_code) {
1711 Condition is_smi = masm->CheckSmi(rcx);
1712 __ Check(NegateCondition(is_smi),
1713 "Unexpected type for RegExp data, FixedArray expected");
1714 __ CmpObjectType(rcx, FIXED_ARRAY_TYPE, kScratchRegister);
1715 __ Check(equal, "Unexpected type for RegExp data, FixedArray expected");
1716 }
1717
1718 // rcx: RegExp data (FixedArray)
1719 // Check the type of the RegExp. Only continue if type is JSRegExp::IRREGEXP.
1720 __ SmiToInteger32(rbx, FieldOperand(rcx, JSRegExp::kDataTagOffset));
1721 __ cmpl(rbx, Immediate(JSRegExp::IRREGEXP));
1722 __ j(not_equal, &runtime);
1723
1724 // rcx: RegExp data (FixedArray)
1725 // Check that the number of captures fit in the static offsets vector buffer.
1726 __ SmiToInteger32(rdx,
1727 FieldOperand(rcx, JSRegExp::kIrregexpCaptureCountOffset));
1728 // Calculate number of capture registers (number_of_captures + 1) * 2.
1729 __ leal(rdx, Operand(rdx, rdx, times_1, 2));
1730 // Check that the static offsets vector buffer is large enough.
1731 __ cmpl(rdx, Immediate(OffsetsVector::kStaticOffsetsVectorSize));
1732 __ j(above, &runtime);
1733
1734 // rcx: RegExp data (FixedArray)
1735 // rdx: Number of capture registers
1736 // Check that the second argument is a string.
1737 __ movq(rax, Operand(rsp, kSubjectOffset));
1738 __ JumpIfSmi(rax, &runtime);
1739 Condition is_string = masm->IsObjectStringType(rax, rbx, rbx);
1740 __ j(NegateCondition(is_string), &runtime);
1741
1742 // rax: Subject string.
1743 // rcx: RegExp data (FixedArray).
1744 // rdx: Number of capture registers.
1745 // Check that the third argument is a positive smi less than the string
1746 // length. A negative value will be greater (unsigned comparison).
1747 __ movq(rbx, Operand(rsp, kPreviousIndexOffset));
1748 __ JumpIfNotSmi(rbx, &runtime);
1749 __ SmiCompare(rbx, FieldOperand(rax, String::kLengthOffset));
1750 __ j(above_equal, &runtime);
1751
1752 // rcx: RegExp data (FixedArray)
1753 // rdx: Number of capture registers
1754 // Check that the fourth object is a JSArray object.
1755 __ movq(rax, Operand(rsp, kLastMatchInfoOffset));
1756 __ JumpIfSmi(rax, &runtime);
1757 __ CmpObjectType(rax, JS_ARRAY_TYPE, kScratchRegister);
1758 __ j(not_equal, &runtime);
1759 // Check that the JSArray is in fast case.
1760 __ movq(rbx, FieldOperand(rax, JSArray::kElementsOffset));
1761 __ movq(rax, FieldOperand(rbx, HeapObject::kMapOffset));
1762 __ Cmp(rax, Factory::fixed_array_map());
1763 __ j(not_equal, &runtime);
1764 // Check that the last match info has space for the capture registers and the
1765 // additional information. Ensure no overflow in add.
1766 STATIC_ASSERT(FixedArray::kMaxLength < kMaxInt - FixedArray::kLengthOffset);
1767 __ SmiToInteger32(rax, FieldOperand(rbx, FixedArray::kLengthOffset));
1768 __ addl(rdx, Immediate(RegExpImpl::kLastMatchOverhead));
1769 __ cmpl(rdx, rax);
1770 __ j(greater, &runtime);
1771
1772 // rcx: RegExp data (FixedArray)
1773 // Check the representation and encoding of the subject string.
Kristian Monsen0d5e1162010-09-30 15:31:59 +01001774 NearLabel seq_ascii_string, seq_two_byte_string, check_code;
Kristian Monsen80d68ea2010-09-08 11:05:35 +01001775 __ movq(rax, Operand(rsp, kSubjectOffset));
1776 __ movq(rbx, FieldOperand(rax, HeapObject::kMapOffset));
1777 __ movzxbl(rbx, FieldOperand(rbx, Map::kInstanceTypeOffset));
1778 // First check for flat two byte string.
1779 __ andb(rbx, Immediate(
1780 kIsNotStringMask | kStringRepresentationMask | kStringEncodingMask));
1781 STATIC_ASSERT((kStringTag | kSeqStringTag | kTwoByteStringTag) == 0);
1782 __ j(zero, &seq_two_byte_string);
1783 // Any other flat string must be a flat ascii string.
1784 __ testb(rbx, Immediate(kIsNotStringMask | kStringRepresentationMask));
1785 __ j(zero, &seq_ascii_string);
1786
1787 // Check for flat cons string.
1788 // A flat cons string is a cons string where the second part is the empty
1789 // string. In that case the subject string is just the first part of the cons
1790 // string. Also in this case the first part of the cons string is known to be
1791 // a sequential string or an external string.
1792 STATIC_ASSERT(kExternalStringTag !=0);
1793 STATIC_ASSERT((kConsStringTag & kExternalStringTag) == 0);
1794 __ testb(rbx, Immediate(kIsNotStringMask | kExternalStringTag));
1795 __ j(not_zero, &runtime);
1796 // String is a cons string.
1797 __ movq(rdx, FieldOperand(rax, ConsString::kSecondOffset));
1798 __ Cmp(rdx, Factory::empty_string());
1799 __ j(not_equal, &runtime);
1800 __ movq(rax, FieldOperand(rax, ConsString::kFirstOffset));
1801 __ movq(rbx, FieldOperand(rax, HeapObject::kMapOffset));
1802 // String is a cons string with empty second part.
1803 // rax: first part of cons string.
1804 // rbx: map of first part of cons string.
1805 // Is first part a flat two byte string?
1806 __ testb(FieldOperand(rbx, Map::kInstanceTypeOffset),
1807 Immediate(kStringRepresentationMask | kStringEncodingMask));
1808 STATIC_ASSERT((kSeqStringTag | kTwoByteStringTag) == 0);
1809 __ j(zero, &seq_two_byte_string);
1810 // Any other flat string must be ascii.
1811 __ testb(FieldOperand(rbx, Map::kInstanceTypeOffset),
1812 Immediate(kStringRepresentationMask));
1813 __ j(not_zero, &runtime);
1814
1815 __ bind(&seq_ascii_string);
1816 // rax: subject string (sequential ascii)
1817 // rcx: RegExp data (FixedArray)
1818 __ movq(r11, FieldOperand(rcx, JSRegExp::kDataAsciiCodeOffset));
1819 __ Set(rdi, 1); // Type is ascii.
1820 __ jmp(&check_code);
1821
1822 __ bind(&seq_two_byte_string);
1823 // rax: subject string (flat two-byte)
1824 // rcx: RegExp data (FixedArray)
1825 __ movq(r11, FieldOperand(rcx, JSRegExp::kDataUC16CodeOffset));
1826 __ Set(rdi, 0); // Type is two byte.
1827
1828 __ bind(&check_code);
1829 // Check that the irregexp code has been generated for the actual string
1830 // encoding. If it has, the field contains a code object otherwise it contains
1831 // the hole.
1832 __ CmpObjectType(r11, CODE_TYPE, kScratchRegister);
1833 __ j(not_equal, &runtime);
1834
1835 // rax: subject string
1836 // rdi: encoding of subject string (1 if ascii, 0 if two_byte);
1837 // r11: code
1838 // Load used arguments before starting to push arguments for call to native
1839 // RegExp code to avoid handling changing stack height.
1840 __ SmiToInteger64(rbx, Operand(rsp, kPreviousIndexOffset));
1841
1842 // rax: subject string
1843 // rbx: previous index
1844 // rdi: encoding of subject string (1 if ascii 0 if two_byte);
1845 // r11: code
1846 // All checks done. Now push arguments for native regexp code.
1847 __ IncrementCounter(&Counters::regexp_entry_native, 1);
1848
1849 // rsi is caller save on Windows and used to pass parameter on Linux.
1850 __ push(rsi);
1851
1852 static const int kRegExpExecuteArguments = 7;
1853 __ PrepareCallCFunction(kRegExpExecuteArguments);
1854 int argument_slots_on_stack =
1855 masm->ArgumentStackSlotsForCFunctionCall(kRegExpExecuteArguments);
1856
1857 // Argument 7: Indicate that this is a direct call from JavaScript.
1858 __ movq(Operand(rsp, (argument_slots_on_stack - 1) * kPointerSize),
1859 Immediate(1));
1860
1861 // Argument 6: Start (high end) of backtracking stack memory area.
1862 __ movq(kScratchRegister, address_of_regexp_stack_memory_address);
1863 __ movq(r9, Operand(kScratchRegister, 0));
1864 __ movq(kScratchRegister, address_of_regexp_stack_memory_size);
1865 __ addq(r9, Operand(kScratchRegister, 0));
1866 // Argument 6 passed in r9 on Linux and on the stack on Windows.
1867#ifdef _WIN64
1868 __ movq(Operand(rsp, (argument_slots_on_stack - 2) * kPointerSize), r9);
1869#endif
1870
1871 // Argument 5: static offsets vector buffer.
1872 __ movq(r8, ExternalReference::address_of_static_offsets_vector());
1873 // Argument 5 passed in r8 on Linux and on the stack on Windows.
1874#ifdef _WIN64
1875 __ movq(Operand(rsp, (argument_slots_on_stack - 3) * kPointerSize), r8);
1876#endif
1877
1878 // First four arguments are passed in registers on both Linux and Windows.
1879#ifdef _WIN64
1880 Register arg4 = r9;
1881 Register arg3 = r8;
1882 Register arg2 = rdx;
1883 Register arg1 = rcx;
1884#else
1885 Register arg4 = rcx;
1886 Register arg3 = rdx;
1887 Register arg2 = rsi;
1888 Register arg1 = rdi;
1889#endif
1890
1891 // Keep track on aliasing between argX defined above and the registers used.
1892 // rax: subject string
1893 // rbx: previous index
1894 // rdi: encoding of subject string (1 if ascii 0 if two_byte);
1895 // r11: code
1896
1897 // Argument 4: End of string data
1898 // Argument 3: Start of string data
Kristian Monsen0d5e1162010-09-30 15:31:59 +01001899 NearLabel setup_two_byte, setup_rest;
Kristian Monsen80d68ea2010-09-08 11:05:35 +01001900 __ testb(rdi, rdi);
1901 __ j(zero, &setup_two_byte);
1902 __ SmiToInteger32(rdi, FieldOperand(rax, String::kLengthOffset));
1903 __ lea(arg4, FieldOperand(rax, rdi, times_1, SeqAsciiString::kHeaderSize));
1904 __ lea(arg3, FieldOperand(rax, rbx, times_1, SeqAsciiString::kHeaderSize));
1905 __ jmp(&setup_rest);
1906 __ bind(&setup_two_byte);
1907 __ SmiToInteger32(rdi, FieldOperand(rax, String::kLengthOffset));
1908 __ lea(arg4, FieldOperand(rax, rdi, times_2, SeqTwoByteString::kHeaderSize));
1909 __ lea(arg3, FieldOperand(rax, rbx, times_2, SeqTwoByteString::kHeaderSize));
1910
1911 __ bind(&setup_rest);
1912 // Argument 2: Previous index.
1913 __ movq(arg2, rbx);
1914
1915 // Argument 1: Subject string.
1916 __ movq(arg1, rax);
1917
1918 // Locate the code entry and call it.
1919 __ addq(r11, Immediate(Code::kHeaderSize - kHeapObjectTag));
1920 __ CallCFunction(r11, kRegExpExecuteArguments);
1921
1922 // rsi is caller save, as it is used to pass parameter.
1923 __ pop(rsi);
1924
1925 // Check the result.
Kristian Monsen0d5e1162010-09-30 15:31:59 +01001926 NearLabel success;
Kristian Monsen80d68ea2010-09-08 11:05:35 +01001927 __ cmpl(rax, Immediate(NativeRegExpMacroAssembler::SUCCESS));
1928 __ j(equal, &success);
Kristian Monsen0d5e1162010-09-30 15:31:59 +01001929 NearLabel failure;
Kristian Monsen80d68ea2010-09-08 11:05:35 +01001930 __ cmpl(rax, Immediate(NativeRegExpMacroAssembler::FAILURE));
1931 __ j(equal, &failure);
1932 __ cmpl(rax, Immediate(NativeRegExpMacroAssembler::EXCEPTION));
1933 // If not exception it can only be retry. Handle that in the runtime system.
1934 __ j(not_equal, &runtime);
1935 // Result must now be exception. If there is no pending exception already a
1936 // stack overflow (on the backtrack stack) was detected in RegExp code but
1937 // haven't created the exception yet. Handle that in the runtime system.
1938 // TODO(592): Rerunning the RegExp to get the stack overflow exception.
1939 ExternalReference pending_exception_address(Top::k_pending_exception_address);
1940 __ movq(kScratchRegister, pending_exception_address);
1941 __ Cmp(kScratchRegister, Factory::the_hole_value());
1942 __ j(equal, &runtime);
1943 __ bind(&failure);
1944 // For failure and exception return null.
1945 __ Move(rax, Factory::null_value());
1946 __ ret(4 * kPointerSize);
1947
1948 // Load RegExp data.
1949 __ bind(&success);
1950 __ movq(rax, Operand(rsp, kJSRegExpOffset));
1951 __ movq(rcx, FieldOperand(rax, JSRegExp::kDataOffset));
1952 __ SmiToInteger32(rax,
1953 FieldOperand(rcx, JSRegExp::kIrregexpCaptureCountOffset));
1954 // Calculate number of capture registers (number_of_captures + 1) * 2.
1955 __ leal(rdx, Operand(rax, rax, times_1, 2));
1956
1957 // rdx: Number of capture registers
1958 // Load last_match_info which is still known to be a fast case JSArray.
1959 __ movq(rax, Operand(rsp, kLastMatchInfoOffset));
1960 __ movq(rbx, FieldOperand(rax, JSArray::kElementsOffset));
1961
1962 // rbx: last_match_info backing store (FixedArray)
1963 // rdx: number of capture registers
1964 // Store the capture count.
1965 __ Integer32ToSmi(kScratchRegister, rdx);
1966 __ movq(FieldOperand(rbx, RegExpImpl::kLastCaptureCountOffset),
1967 kScratchRegister);
1968 // Store last subject and last input.
1969 __ movq(rax, Operand(rsp, kSubjectOffset));
1970 __ movq(FieldOperand(rbx, RegExpImpl::kLastSubjectOffset), rax);
1971 __ movq(rcx, rbx);
1972 __ RecordWrite(rcx, RegExpImpl::kLastSubjectOffset, rax, rdi);
1973 __ movq(rax, Operand(rsp, kSubjectOffset));
1974 __ movq(FieldOperand(rbx, RegExpImpl::kLastInputOffset), rax);
1975 __ movq(rcx, rbx);
1976 __ RecordWrite(rcx, RegExpImpl::kLastInputOffset, rax, rdi);
1977
1978 // Get the static offsets vector filled by the native regexp code.
1979 __ movq(rcx, ExternalReference::address_of_static_offsets_vector());
1980
1981 // rbx: last_match_info backing store (FixedArray)
1982 // rcx: offsets vector
1983 // rdx: number of capture registers
Kristian Monsen0d5e1162010-09-30 15:31:59 +01001984 NearLabel next_capture, done;
Kristian Monsen80d68ea2010-09-08 11:05:35 +01001985 // Capture register counter starts from number of capture registers and
1986 // counts down until wraping after zero.
1987 __ bind(&next_capture);
1988 __ subq(rdx, Immediate(1));
1989 __ j(negative, &done);
1990 // Read the value from the static offsets vector buffer and make it a smi.
1991 __ movl(rdi, Operand(rcx, rdx, times_int_size, 0));
Kristian Monsen0d5e1162010-09-30 15:31:59 +01001992 __ Integer32ToSmi(rdi, rdi);
Kristian Monsen80d68ea2010-09-08 11:05:35 +01001993 // Store the smi value in the last match info.
1994 __ movq(FieldOperand(rbx,
1995 rdx,
1996 times_pointer_size,
1997 RegExpImpl::kFirstCaptureOffset),
1998 rdi);
1999 __ jmp(&next_capture);
2000 __ bind(&done);
2001
2002 // Return last match info.
2003 __ movq(rax, Operand(rsp, kLastMatchInfoOffset));
2004 __ ret(4 * kPointerSize);
2005
2006 // Do the runtime call to execute the regexp.
2007 __ bind(&runtime);
2008 __ TailCallRuntime(Runtime::kRegExpExec, 4, 1);
2009#endif // V8_INTERPRETED_REGEXP
2010}
2011
2012
2013void NumberToStringStub::GenerateLookupNumberStringCache(MacroAssembler* masm,
2014 Register object,
2015 Register result,
2016 Register scratch1,
2017 Register scratch2,
2018 bool object_is_smi,
2019 Label* not_found) {
2020 // Use of registers. Register result is used as a temporary.
2021 Register number_string_cache = result;
2022 Register mask = scratch1;
2023 Register scratch = scratch2;
2024
2025 // Load the number string cache.
2026 __ LoadRoot(number_string_cache, Heap::kNumberStringCacheRootIndex);
2027
2028 // Make the hash mask from the length of the number string cache. It
2029 // contains two elements (number and string) for each cache entry.
2030 __ SmiToInteger32(
2031 mask, FieldOperand(number_string_cache, FixedArray::kLengthOffset));
2032 __ shrl(mask, Immediate(1));
2033 __ subq(mask, Immediate(1)); // Make mask.
2034
2035 // Calculate the entry in the number string cache. The hash value in the
2036 // number string cache for smis is just the smi value, and the hash for
2037 // doubles is the xor of the upper and lower words. See
2038 // Heap::GetNumberStringCache.
2039 Label is_smi;
2040 Label load_result_from_cache;
2041 if (!object_is_smi) {
2042 __ JumpIfSmi(object, &is_smi);
2043 __ CheckMap(object, Factory::heap_number_map(), not_found, true);
2044
2045 STATIC_ASSERT(8 == kDoubleSize);
2046 __ movl(scratch, FieldOperand(object, HeapNumber::kValueOffset + 4));
2047 __ xor_(scratch, FieldOperand(object, HeapNumber::kValueOffset));
2048 GenerateConvertHashCodeToIndex(masm, scratch, mask);
2049
2050 Register index = scratch;
2051 Register probe = mask;
2052 __ movq(probe,
2053 FieldOperand(number_string_cache,
2054 index,
2055 times_1,
2056 FixedArray::kHeaderSize));
2057 __ JumpIfSmi(probe, not_found);
2058 ASSERT(CpuFeatures::IsSupported(SSE2));
2059 CpuFeatures::Scope fscope(SSE2);
2060 __ movsd(xmm0, FieldOperand(object, HeapNumber::kValueOffset));
2061 __ movsd(xmm1, FieldOperand(probe, HeapNumber::kValueOffset));
2062 __ ucomisd(xmm0, xmm1);
2063 __ j(parity_even, not_found); // Bail out if NaN is involved.
2064 __ j(not_equal, not_found); // The cache did not contain this value.
2065 __ jmp(&load_result_from_cache);
2066 }
2067
2068 __ bind(&is_smi);
2069 __ SmiToInteger32(scratch, object);
2070 GenerateConvertHashCodeToIndex(masm, scratch, mask);
2071
2072 Register index = scratch;
2073 // Check if the entry is the smi we are looking for.
2074 __ cmpq(object,
2075 FieldOperand(number_string_cache,
2076 index,
2077 times_1,
2078 FixedArray::kHeaderSize));
2079 __ j(not_equal, not_found);
2080
2081 // Get the result from the cache.
2082 __ bind(&load_result_from_cache);
2083 __ movq(result,
2084 FieldOperand(number_string_cache,
2085 index,
2086 times_1,
2087 FixedArray::kHeaderSize + kPointerSize));
2088 __ IncrementCounter(&Counters::number_to_string_native, 1);
2089}
2090
2091
2092void NumberToStringStub::GenerateConvertHashCodeToIndex(MacroAssembler* masm,
2093 Register hash,
2094 Register mask) {
2095 __ and_(hash, mask);
2096 // Each entry in string cache consists of two pointer sized fields,
2097 // but times_twice_pointer_size (multiplication by 16) scale factor
2098 // is not supported by addrmode on x64 platform.
2099 // So we have to premultiply entry index before lookup.
2100 __ shl(hash, Immediate(kPointerSizeLog2 + 1));
2101}
2102
2103
2104void NumberToStringStub::Generate(MacroAssembler* masm) {
2105 Label runtime;
2106
2107 __ movq(rbx, Operand(rsp, kPointerSize));
2108
2109 // Generate code to lookup number in the number string cache.
2110 GenerateLookupNumberStringCache(masm, rbx, rax, r8, r9, false, &runtime);
2111 __ ret(1 * kPointerSize);
2112
2113 __ bind(&runtime);
2114 // Handle number to string in the runtime system if not found in the cache.
2115 __ TailCallRuntime(Runtime::kNumberToStringSkipCache, 1, 1);
2116}
2117
2118
2119static int NegativeComparisonResult(Condition cc) {
2120 ASSERT(cc != equal);
2121 ASSERT((cc == less) || (cc == less_equal)
2122 || (cc == greater) || (cc == greater_equal));
2123 return (cc == greater || cc == greater_equal) ? LESS : GREATER;
2124}
2125
2126
2127void CompareStub::Generate(MacroAssembler* masm) {
2128 ASSERT(lhs_.is(no_reg) && rhs_.is(no_reg));
2129
2130 Label check_unequal_objects, done;
Kristian Monsen0d5e1162010-09-30 15:31:59 +01002131
2132 // Compare two smis if required.
2133 if (include_smi_compare_) {
2134 Label non_smi, smi_done;
2135 __ JumpIfNotBothSmi(rax, rdx, &non_smi);
2136 __ subq(rdx, rax);
2137 __ j(no_overflow, &smi_done);
2138 __ neg(rdx); // Correct sign in case of overflow.
2139 __ bind(&smi_done);
2140 __ movq(rax, rdx);
2141 __ ret(0);
2142 __ bind(&non_smi);
2143 } else if (FLAG_debug_code) {
2144 Label ok;
2145 __ JumpIfNotSmi(rdx, &ok);
2146 __ JumpIfNotSmi(rax, &ok);
2147 __ Abort("CompareStub: smi operands");
2148 __ bind(&ok);
2149 }
2150
Kristian Monsen80d68ea2010-09-08 11:05:35 +01002151 // The compare stub returns a positive, negative, or zero 64-bit integer
2152 // value in rax, corresponding to result of comparing the two inputs.
2153 // NOTICE! This code is only reached after a smi-fast-case check, so
2154 // it is certain that at least one operand isn't a smi.
2155
2156 // Two identical objects are equal unless they are both NaN or undefined.
2157 {
Kristian Monsen0d5e1162010-09-30 15:31:59 +01002158 NearLabel not_identical;
Kristian Monsen80d68ea2010-09-08 11:05:35 +01002159 __ cmpq(rax, rdx);
2160 __ j(not_equal, &not_identical);
2161
2162 if (cc_ != equal) {
2163 // Check for undefined. undefined OP undefined is false even though
2164 // undefined == undefined.
Kristian Monsen0d5e1162010-09-30 15:31:59 +01002165 NearLabel check_for_nan;
Kristian Monsen80d68ea2010-09-08 11:05:35 +01002166 __ CompareRoot(rdx, Heap::kUndefinedValueRootIndex);
2167 __ j(not_equal, &check_for_nan);
2168 __ Set(rax, NegativeComparisonResult(cc_));
2169 __ ret(0);
2170 __ bind(&check_for_nan);
2171 }
2172
2173 // Test for NaN. Sadly, we can't just compare to Factory::nan_value(),
2174 // so we do the second best thing - test it ourselves.
2175 // Note: if cc_ != equal, never_nan_nan_ is not used.
2176 // We cannot set rax to EQUAL until just before return because
2177 // rax must be unchanged on jump to not_identical.
2178
2179 if (never_nan_nan_ && (cc_ == equal)) {
2180 __ Set(rax, EQUAL);
2181 __ ret(0);
2182 } else {
Kristian Monsen0d5e1162010-09-30 15:31:59 +01002183 NearLabel heap_number;
Kristian Monsen80d68ea2010-09-08 11:05:35 +01002184 // If it's not a heap number, then return equal for (in)equality operator.
2185 __ Cmp(FieldOperand(rdx, HeapObject::kMapOffset),
2186 Factory::heap_number_map());
2187 __ j(equal, &heap_number);
2188 if (cc_ != equal) {
2189 // Call runtime on identical JSObjects. Otherwise return equal.
2190 __ CmpObjectType(rax, FIRST_JS_OBJECT_TYPE, rcx);
2191 __ j(above_equal, &not_identical);
2192 }
2193 __ Set(rax, EQUAL);
2194 __ ret(0);
2195
2196 __ bind(&heap_number);
2197 // It is a heap number, so return equal if it's not NaN.
2198 // For NaN, return 1 for every condition except greater and
2199 // greater-equal. Return -1 for them, so the comparison yields
2200 // false for all conditions except not-equal.
2201 __ Set(rax, EQUAL);
2202 __ movsd(xmm0, FieldOperand(rdx, HeapNumber::kValueOffset));
2203 __ ucomisd(xmm0, xmm0);
2204 __ setcc(parity_even, rax);
2205 // rax is 0 for equal non-NaN heapnumbers, 1 for NaNs.
2206 if (cc_ == greater_equal || cc_ == greater) {
2207 __ neg(rax);
2208 }
2209 __ ret(0);
2210 }
2211
2212 __ bind(&not_identical);
2213 }
2214
2215 if (cc_ == equal) { // Both strict and non-strict.
2216 Label slow; // Fallthrough label.
2217
2218 // If we're doing a strict equality comparison, we don't have to do
2219 // type conversion, so we generate code to do fast comparison for objects
2220 // and oddballs. Non-smi numbers and strings still go through the usual
2221 // slow-case code.
2222 if (strict_) {
2223 // If either is a Smi (we know that not both are), then they can only
2224 // be equal if the other is a HeapNumber. If so, use the slow case.
2225 {
2226 Label not_smis;
2227 __ SelectNonSmi(rbx, rax, rdx, &not_smis);
2228
2229 // Check if the non-smi operand is a heap number.
2230 __ Cmp(FieldOperand(rbx, HeapObject::kMapOffset),
2231 Factory::heap_number_map());
2232 // If heap number, handle it in the slow case.
2233 __ j(equal, &slow);
2234 // Return non-equal. ebx (the lower half of rbx) is not zero.
2235 __ movq(rax, rbx);
2236 __ ret(0);
2237
2238 __ bind(&not_smis);
2239 }
2240
2241 // If either operand is a JSObject or an oddball value, then they are not
2242 // equal since their pointers are different
2243 // There is no test for undetectability in strict equality.
2244
2245 // If the first object is a JS object, we have done pointer comparison.
2246 STATIC_ASSERT(LAST_TYPE == JS_FUNCTION_TYPE);
Kristian Monsen0d5e1162010-09-30 15:31:59 +01002247 NearLabel first_non_object;
Kristian Monsen80d68ea2010-09-08 11:05:35 +01002248 __ CmpObjectType(rax, FIRST_JS_OBJECT_TYPE, rcx);
2249 __ j(below, &first_non_object);
2250 // Return non-zero (eax (not rax) is not zero)
2251 Label return_not_equal;
2252 STATIC_ASSERT(kHeapObjectTag != 0);
2253 __ bind(&return_not_equal);
2254 __ ret(0);
2255
2256 __ bind(&first_non_object);
2257 // Check for oddballs: true, false, null, undefined.
2258 __ CmpInstanceType(rcx, ODDBALL_TYPE);
2259 __ j(equal, &return_not_equal);
2260
2261 __ CmpObjectType(rdx, FIRST_JS_OBJECT_TYPE, rcx);
2262 __ j(above_equal, &return_not_equal);
2263
2264 // Check for oddballs: true, false, null, undefined.
2265 __ CmpInstanceType(rcx, ODDBALL_TYPE);
2266 __ j(equal, &return_not_equal);
2267
2268 // Fall through to the general case.
2269 }
2270 __ bind(&slow);
2271 }
2272
2273 // Generate the number comparison code.
2274 if (include_number_compare_) {
2275 Label non_number_comparison;
Kristian Monsen0d5e1162010-09-30 15:31:59 +01002276 NearLabel unordered;
Kristian Monsen80d68ea2010-09-08 11:05:35 +01002277 FloatingPointHelper::LoadSSE2UnknownOperands(masm, &non_number_comparison);
2278 __ xorl(rax, rax);
2279 __ xorl(rcx, rcx);
2280 __ ucomisd(xmm0, xmm1);
2281
2282 // Don't base result on EFLAGS when a NaN is involved.
2283 __ j(parity_even, &unordered);
2284 // Return a result of -1, 0, or 1, based on EFLAGS.
2285 __ setcc(above, rax);
2286 __ setcc(below, rcx);
2287 __ subq(rax, rcx);
2288 __ ret(0);
2289
2290 // If one of the numbers was NaN, then the result is always false.
2291 // The cc is never not-equal.
2292 __ bind(&unordered);
2293 ASSERT(cc_ != not_equal);
2294 if (cc_ == less || cc_ == less_equal) {
2295 __ Set(rax, 1);
2296 } else {
2297 __ Set(rax, -1);
2298 }
2299 __ ret(0);
2300
2301 // The number comparison code did not provide a valid result.
2302 __ bind(&non_number_comparison);
2303 }
2304
2305 // Fast negative check for symbol-to-symbol equality.
2306 Label check_for_strings;
2307 if (cc_ == equal) {
2308 BranchIfNonSymbol(masm, &check_for_strings, rax, kScratchRegister);
2309 BranchIfNonSymbol(masm, &check_for_strings, rdx, kScratchRegister);
2310
2311 // We've already checked for object identity, so if both operands
2312 // are symbols they aren't equal. Register eax (not rax) already holds a
2313 // non-zero value, which indicates not equal, so just return.
2314 __ ret(0);
2315 }
2316
2317 __ bind(&check_for_strings);
2318
2319 __ JumpIfNotBothSequentialAsciiStrings(
2320 rdx, rax, rcx, rbx, &check_unequal_objects);
2321
2322 // Inline comparison of ascii strings.
2323 StringCompareStub::GenerateCompareFlatAsciiStrings(masm,
2324 rdx,
2325 rax,
2326 rcx,
2327 rbx,
2328 rdi,
2329 r8);
2330
2331#ifdef DEBUG
2332 __ Abort("Unexpected fall-through from string comparison");
2333#endif
2334
2335 __ bind(&check_unequal_objects);
2336 if (cc_ == equal && !strict_) {
2337 // Not strict equality. Objects are unequal if
2338 // they are both JSObjects and not undetectable,
2339 // and their pointers are different.
Kristian Monsen0d5e1162010-09-30 15:31:59 +01002340 NearLabel not_both_objects, return_unequal;
Kristian Monsen80d68ea2010-09-08 11:05:35 +01002341 // At most one is a smi, so we can test for smi by adding the two.
2342 // A smi plus a heap object has the low bit set, a heap object plus
2343 // a heap object has the low bit clear.
2344 STATIC_ASSERT(kSmiTag == 0);
2345 STATIC_ASSERT(kSmiTagMask == 1);
2346 __ lea(rcx, Operand(rax, rdx, times_1, 0));
2347 __ testb(rcx, Immediate(kSmiTagMask));
2348 __ j(not_zero, &not_both_objects);
2349 __ CmpObjectType(rax, FIRST_JS_OBJECT_TYPE, rbx);
2350 __ j(below, &not_both_objects);
2351 __ CmpObjectType(rdx, FIRST_JS_OBJECT_TYPE, rcx);
2352 __ j(below, &not_both_objects);
2353 __ testb(FieldOperand(rbx, Map::kBitFieldOffset),
2354 Immediate(1 << Map::kIsUndetectable));
2355 __ j(zero, &return_unequal);
2356 __ testb(FieldOperand(rcx, Map::kBitFieldOffset),
2357 Immediate(1 << Map::kIsUndetectable));
2358 __ j(zero, &return_unequal);
2359 // The objects are both undetectable, so they both compare as the value
2360 // undefined, and are equal.
2361 __ Set(rax, EQUAL);
2362 __ bind(&return_unequal);
2363 // Return non-equal by returning the non-zero object pointer in eax,
2364 // or return equal if we fell through to here.
2365 __ ret(0);
2366 __ bind(&not_both_objects);
2367 }
2368
2369 // Push arguments below the return address to prepare jump to builtin.
2370 __ pop(rcx);
2371 __ push(rdx);
2372 __ push(rax);
2373
2374 // Figure out which native to call and setup the arguments.
2375 Builtins::JavaScript builtin;
2376 if (cc_ == equal) {
2377 builtin = strict_ ? Builtins::STRICT_EQUALS : Builtins::EQUALS;
2378 } else {
2379 builtin = Builtins::COMPARE;
2380 __ Push(Smi::FromInt(NegativeComparisonResult(cc_)));
2381 }
2382
2383 // Restore return address on the stack.
2384 __ push(rcx);
2385
2386 // Call the native; it returns -1 (less), 0 (equal), or 1 (greater)
2387 // tagged as a small integer.
2388 __ InvokeBuiltin(builtin, JUMP_FUNCTION);
2389}
2390
2391
2392void CompareStub::BranchIfNonSymbol(MacroAssembler* masm,
2393 Label* label,
2394 Register object,
2395 Register scratch) {
2396 __ JumpIfSmi(object, label);
2397 __ movq(scratch, FieldOperand(object, HeapObject::kMapOffset));
2398 __ movzxbq(scratch,
2399 FieldOperand(scratch, Map::kInstanceTypeOffset));
2400 // Ensure that no non-strings have the symbol bit set.
2401 STATIC_ASSERT(LAST_TYPE < kNotStringTag + kIsSymbolMask);
2402 STATIC_ASSERT(kSymbolTag != 0);
2403 __ testb(scratch, Immediate(kIsSymbolMask));
2404 __ j(zero, label);
2405}
2406
2407
2408void StackCheckStub::Generate(MacroAssembler* masm) {
2409 // Because builtins always remove the receiver from the stack, we
2410 // have to fake one to avoid underflowing the stack. The receiver
2411 // must be inserted below the return address on the stack so we
2412 // temporarily store that in a register.
2413 __ pop(rax);
2414 __ Push(Smi::FromInt(0));
2415 __ push(rax);
2416
2417 // Do tail-call to runtime routine.
2418 __ TailCallRuntime(Runtime::kStackGuard, 1, 1);
2419}
2420
2421
2422void CallFunctionStub::Generate(MacroAssembler* masm) {
2423 Label slow;
2424
2425 // If the receiver might be a value (string, number or boolean) check for this
2426 // and box it if it is.
2427 if (ReceiverMightBeValue()) {
2428 // Get the receiver from the stack.
2429 // +1 ~ return address
2430 Label receiver_is_value, receiver_is_js_object;
2431 __ movq(rax, Operand(rsp, (argc_ + 1) * kPointerSize));
2432
2433 // Check if receiver is a smi (which is a number value).
2434 __ JumpIfSmi(rax, &receiver_is_value);
2435
2436 // Check if the receiver is a valid JS object.
2437 __ CmpObjectType(rax, FIRST_JS_OBJECT_TYPE, rdi);
2438 __ j(above_equal, &receiver_is_js_object);
2439
2440 // Call the runtime to box the value.
2441 __ bind(&receiver_is_value);
2442 __ EnterInternalFrame();
2443 __ push(rax);
2444 __ InvokeBuiltin(Builtins::TO_OBJECT, CALL_FUNCTION);
2445 __ LeaveInternalFrame();
2446 __ movq(Operand(rsp, (argc_ + 1) * kPointerSize), rax);
2447
2448 __ bind(&receiver_is_js_object);
2449 }
2450
2451 // Get the function to call from the stack.
2452 // +2 ~ receiver, return address
2453 __ movq(rdi, Operand(rsp, (argc_ + 2) * kPointerSize));
2454
2455 // Check that the function really is a JavaScript function.
2456 __ JumpIfSmi(rdi, &slow);
2457 // Goto slow case if we do not have a function.
2458 __ CmpObjectType(rdi, JS_FUNCTION_TYPE, rcx);
2459 __ j(not_equal, &slow);
2460
2461 // Fast-case: Just invoke the function.
2462 ParameterCount actual(argc_);
2463 __ InvokeFunction(rdi, actual, JUMP_FUNCTION);
2464
2465 // Slow-case: Non-function called.
2466 __ bind(&slow);
2467 // CALL_NON_FUNCTION expects the non-function callee as receiver (instead
2468 // of the original receiver from the call site).
2469 __ movq(Operand(rsp, (argc_ + 1) * kPointerSize), rdi);
2470 __ Set(rax, argc_);
2471 __ Set(rbx, 0);
2472 __ GetBuiltinEntry(rdx, Builtins::CALL_NON_FUNCTION);
2473 Handle<Code> adaptor(Builtins::builtin(Builtins::ArgumentsAdaptorTrampoline));
2474 __ Jump(adaptor, RelocInfo::CODE_TARGET);
2475}
2476
2477
2478void CEntryStub::GenerateThrowTOS(MacroAssembler* masm) {
2479 // Check that stack should contain next handler, frame pointer, state and
2480 // return address in that order.
2481 STATIC_ASSERT(StackHandlerConstants::kFPOffset + kPointerSize ==
2482 StackHandlerConstants::kStateOffset);
2483 STATIC_ASSERT(StackHandlerConstants::kStateOffset + kPointerSize ==
2484 StackHandlerConstants::kPCOffset);
2485
2486 ExternalReference handler_address(Top::k_handler_address);
2487 __ movq(kScratchRegister, handler_address);
2488 __ movq(rsp, Operand(kScratchRegister, 0));
2489 // get next in chain
2490 __ pop(rcx);
2491 __ movq(Operand(kScratchRegister, 0), rcx);
2492 __ pop(rbp); // pop frame pointer
2493 __ pop(rdx); // remove state
2494
2495 // Before returning we restore the context from the frame pointer if not NULL.
2496 // The frame pointer is NULL in the exception handler of a JS entry frame.
2497 __ xor_(rsi, rsi); // tentatively set context pointer to NULL
Kristian Monsen0d5e1162010-09-30 15:31:59 +01002498 NearLabel skip;
Kristian Monsen80d68ea2010-09-08 11:05:35 +01002499 __ cmpq(rbp, Immediate(0));
2500 __ j(equal, &skip);
2501 __ movq(rsi, Operand(rbp, StandardFrameConstants::kContextOffset));
2502 __ bind(&skip);
2503 __ ret(0);
2504}
2505
2506
2507void ApiGetterEntryStub::Generate(MacroAssembler* masm) {
2508 Label empty_result;
2509 Label prologue;
2510 Label promote_scheduled_exception;
2511 __ EnterApiExitFrame(kStackSpace, 0);
2512 ASSERT_EQ(kArgc, 4);
2513#ifdef _WIN64
2514 // All the parameters should be set up by a caller.
2515#else
2516 // Set 1st parameter register with property name.
2517 __ movq(rsi, rdx);
2518 // Second parameter register rdi should be set with pointer to AccessorInfo
2519 // by a caller.
2520#endif
2521 // Call the api function!
2522 __ movq(rax,
2523 reinterpret_cast<int64_t>(fun()->address()),
2524 RelocInfo::RUNTIME_ENTRY);
2525 __ call(rax);
2526 // Check if the function scheduled an exception.
2527 ExternalReference scheduled_exception_address =
2528 ExternalReference::scheduled_exception_address();
2529 __ movq(rsi, scheduled_exception_address);
2530 __ Cmp(Operand(rsi, 0), Factory::the_hole_value());
2531 __ j(not_equal, &promote_scheduled_exception);
2532#ifdef _WIN64
2533 // rax keeps a pointer to v8::Handle, unpack it.
2534 __ movq(rax, Operand(rax, 0));
2535#endif
2536 // Check if the result handle holds 0.
2537 __ testq(rax, rax);
2538 __ j(zero, &empty_result);
2539 // It was non-zero. Dereference to get the result value.
2540 __ movq(rax, Operand(rax, 0));
2541 __ bind(&prologue);
2542 __ LeaveExitFrame();
2543 __ ret(0);
2544 __ bind(&promote_scheduled_exception);
2545 __ TailCallRuntime(Runtime::kPromoteScheduledException, 0, 1);
2546 __ bind(&empty_result);
2547 // It was zero; the result is undefined.
2548 __ Move(rax, Factory::undefined_value());
2549 __ jmp(&prologue);
2550}
2551
2552
2553void CEntryStub::GenerateCore(MacroAssembler* masm,
2554 Label* throw_normal_exception,
2555 Label* throw_termination_exception,
2556 Label* throw_out_of_memory_exception,
2557 bool do_gc,
2558 bool always_allocate_scope,
2559 int /* alignment_skew */) {
2560 // rax: result parameter for PerformGC, if any.
2561 // rbx: pointer to C function (C callee-saved).
2562 // rbp: frame pointer (restored after C call).
2563 // rsp: stack pointer (restored after C call).
2564 // r14: number of arguments including receiver (C callee-saved).
2565 // r12: pointer to the first argument (C callee-saved).
2566 // This pointer is reused in LeaveExitFrame(), so it is stored in a
2567 // callee-saved register.
2568
2569 // Simple results returned in rax (both AMD64 and Win64 calling conventions).
2570 // Complex results must be written to address passed as first argument.
2571 // AMD64 calling convention: a struct of two pointers in rax+rdx
2572
2573 // Check stack alignment.
2574 if (FLAG_debug_code) {
2575 __ CheckStackAlignment();
2576 }
2577
2578 if (do_gc) {
2579 // Pass failure code returned from last attempt as first argument to
2580 // PerformGC. No need to use PrepareCallCFunction/CallCFunction here as the
2581 // stack is known to be aligned. This function takes one argument which is
2582 // passed in register.
2583#ifdef _WIN64
2584 __ movq(rcx, rax);
2585#else // _WIN64
2586 __ movq(rdi, rax);
2587#endif
2588 __ movq(kScratchRegister,
2589 FUNCTION_ADDR(Runtime::PerformGC),
2590 RelocInfo::RUNTIME_ENTRY);
2591 __ call(kScratchRegister);
2592 }
2593
2594 ExternalReference scope_depth =
2595 ExternalReference::heap_always_allocate_scope_depth();
2596 if (always_allocate_scope) {
2597 __ movq(kScratchRegister, scope_depth);
2598 __ incl(Operand(kScratchRegister, 0));
2599 }
2600
2601 // Call C function.
2602#ifdef _WIN64
2603 // Windows 64-bit ABI passes arguments in rcx, rdx, r8, r9
2604 // Store Arguments object on stack, below the 4 WIN64 ABI parameter slots.
2605 __ movq(Operand(rsp, 4 * kPointerSize), r14); // argc.
2606 __ movq(Operand(rsp, 5 * kPointerSize), r12); // argv.
2607 if (result_size_ < 2) {
2608 // Pass a pointer to the Arguments object as the first argument.
2609 // Return result in single register (rax).
2610 __ lea(rcx, Operand(rsp, 4 * kPointerSize));
2611 } else {
2612 ASSERT_EQ(2, result_size_);
2613 // Pass a pointer to the result location as the first argument.
2614 __ lea(rcx, Operand(rsp, 6 * kPointerSize));
2615 // Pass a pointer to the Arguments object as the second argument.
2616 __ lea(rdx, Operand(rsp, 4 * kPointerSize));
2617 }
2618
2619#else // _WIN64
2620 // GCC passes arguments in rdi, rsi, rdx, rcx, r8, r9.
2621 __ movq(rdi, r14); // argc.
2622 __ movq(rsi, r12); // argv.
2623#endif
2624 __ call(rbx);
2625 // Result is in rax - do not destroy this register!
2626
2627 if (always_allocate_scope) {
2628 __ movq(kScratchRegister, scope_depth);
2629 __ decl(Operand(kScratchRegister, 0));
2630 }
2631
2632 // Check for failure result.
2633 Label failure_returned;
2634 STATIC_ASSERT(((kFailureTag + 1) & kFailureTagMask) == 0);
2635#ifdef _WIN64
2636 // If return value is on the stack, pop it to registers.
2637 if (result_size_ > 1) {
2638 ASSERT_EQ(2, result_size_);
2639 // Read result values stored on stack. Result is stored
2640 // above the four argument mirror slots and the two
2641 // Arguments object slots.
2642 __ movq(rax, Operand(rsp, 6 * kPointerSize));
2643 __ movq(rdx, Operand(rsp, 7 * kPointerSize));
2644 }
2645#endif
2646 __ lea(rcx, Operand(rax, 1));
2647 // Lower 2 bits of rcx are 0 iff rax has failure tag.
2648 __ testl(rcx, Immediate(kFailureTagMask));
2649 __ j(zero, &failure_returned);
2650
2651 // Exit the JavaScript to C++ exit frame.
2652 __ LeaveExitFrame(result_size_);
2653 __ ret(0);
2654
2655 // Handling of failure.
2656 __ bind(&failure_returned);
2657
Kristian Monsen0d5e1162010-09-30 15:31:59 +01002658 NearLabel retry;
Kristian Monsen80d68ea2010-09-08 11:05:35 +01002659 // If the returned exception is RETRY_AFTER_GC continue at retry label
2660 STATIC_ASSERT(Failure::RETRY_AFTER_GC == 0);
2661 __ testl(rax, Immediate(((1 << kFailureTypeTagSize) - 1) << kFailureTagSize));
2662 __ j(zero, &retry);
2663
2664 // Special handling of out of memory exceptions.
2665 __ movq(kScratchRegister, Failure::OutOfMemoryException(), RelocInfo::NONE);
2666 __ cmpq(rax, kScratchRegister);
2667 __ j(equal, throw_out_of_memory_exception);
2668
2669 // Retrieve the pending exception and clear the variable.
2670 ExternalReference pending_exception_address(Top::k_pending_exception_address);
2671 __ movq(kScratchRegister, pending_exception_address);
2672 __ movq(rax, Operand(kScratchRegister, 0));
2673 __ movq(rdx, ExternalReference::the_hole_value_location());
2674 __ movq(rdx, Operand(rdx, 0));
2675 __ movq(Operand(kScratchRegister, 0), rdx);
2676
2677 // Special handling of termination exceptions which are uncatchable
2678 // by javascript code.
2679 __ CompareRoot(rax, Heap::kTerminationExceptionRootIndex);
2680 __ j(equal, throw_termination_exception);
2681
2682 // Handle normal exception.
2683 __ jmp(throw_normal_exception);
2684
2685 // Retry.
2686 __ bind(&retry);
2687}
2688
2689
2690void CEntryStub::GenerateThrowUncatchable(MacroAssembler* masm,
2691 UncatchableExceptionType type) {
2692 // Fetch top stack handler.
2693 ExternalReference handler_address(Top::k_handler_address);
2694 __ movq(kScratchRegister, handler_address);
2695 __ movq(rsp, Operand(kScratchRegister, 0));
2696
2697 // Unwind the handlers until the ENTRY handler is found.
Kristian Monsen0d5e1162010-09-30 15:31:59 +01002698 NearLabel loop, done;
Kristian Monsen80d68ea2010-09-08 11:05:35 +01002699 __ bind(&loop);
2700 // Load the type of the current stack handler.
2701 const int kStateOffset = StackHandlerConstants::kStateOffset;
2702 __ cmpq(Operand(rsp, kStateOffset), Immediate(StackHandler::ENTRY));
2703 __ j(equal, &done);
2704 // Fetch the next handler in the list.
2705 const int kNextOffset = StackHandlerConstants::kNextOffset;
2706 __ movq(rsp, Operand(rsp, kNextOffset));
2707 __ jmp(&loop);
2708 __ bind(&done);
2709
2710 // Set the top handler address to next handler past the current ENTRY handler.
2711 __ movq(kScratchRegister, handler_address);
2712 __ pop(Operand(kScratchRegister, 0));
2713
2714 if (type == OUT_OF_MEMORY) {
2715 // Set external caught exception to false.
2716 ExternalReference external_caught(Top::k_external_caught_exception_address);
2717 __ movq(rax, Immediate(false));
2718 __ store_rax(external_caught);
2719
2720 // Set pending exception and rax to out of memory exception.
2721 ExternalReference pending_exception(Top::k_pending_exception_address);
2722 __ movq(rax, Failure::OutOfMemoryException(), RelocInfo::NONE);
2723 __ store_rax(pending_exception);
2724 }
2725
2726 // Clear the context pointer.
2727 __ xor_(rsi, rsi);
2728
2729 // Restore registers from handler.
2730 STATIC_ASSERT(StackHandlerConstants::kNextOffset + kPointerSize ==
2731 StackHandlerConstants::kFPOffset);
2732 __ pop(rbp); // FP
2733 STATIC_ASSERT(StackHandlerConstants::kFPOffset + kPointerSize ==
2734 StackHandlerConstants::kStateOffset);
2735 __ pop(rdx); // State
2736
2737 STATIC_ASSERT(StackHandlerConstants::kStateOffset + kPointerSize ==
2738 StackHandlerConstants::kPCOffset);
2739 __ ret(0);
2740}
2741
2742
2743void CEntryStub::Generate(MacroAssembler* masm) {
2744 // rax: number of arguments including receiver
2745 // rbx: pointer to C function (C callee-saved)
2746 // rbp: frame pointer of calling JS frame (restored after C call)
2747 // rsp: stack pointer (restored after C call)
2748 // rsi: current context (restored)
2749
2750 // NOTE: Invocations of builtins may return failure objects
2751 // instead of a proper result. The builtin entry handles
2752 // this by performing a garbage collection and retrying the
2753 // builtin once.
2754
2755 // Enter the exit frame that transitions from JavaScript to C++.
2756 __ EnterExitFrame(result_size_);
2757
2758 // rax: Holds the context at this point, but should not be used.
2759 // On entry to code generated by GenerateCore, it must hold
2760 // a failure result if the collect_garbage argument to GenerateCore
2761 // is true. This failure result can be the result of code
2762 // generated by a previous call to GenerateCore. The value
2763 // of rax is then passed to Runtime::PerformGC.
2764 // rbx: pointer to builtin function (C callee-saved).
2765 // rbp: frame pointer of exit frame (restored after C call).
2766 // rsp: stack pointer (restored after C call).
2767 // r14: number of arguments including receiver (C callee-saved).
2768 // r12: argv pointer (C callee-saved).
2769
2770 Label throw_normal_exception;
2771 Label throw_termination_exception;
2772 Label throw_out_of_memory_exception;
2773
2774 // Call into the runtime system.
2775 GenerateCore(masm,
2776 &throw_normal_exception,
2777 &throw_termination_exception,
2778 &throw_out_of_memory_exception,
2779 false,
2780 false);
2781
2782 // Do space-specific GC and retry runtime call.
2783 GenerateCore(masm,
2784 &throw_normal_exception,
2785 &throw_termination_exception,
2786 &throw_out_of_memory_exception,
2787 true,
2788 false);
2789
2790 // Do full GC and retry runtime call one final time.
2791 Failure* failure = Failure::InternalError();
2792 __ movq(rax, failure, RelocInfo::NONE);
2793 GenerateCore(masm,
2794 &throw_normal_exception,
2795 &throw_termination_exception,
2796 &throw_out_of_memory_exception,
2797 true,
2798 true);
2799
2800 __ bind(&throw_out_of_memory_exception);
2801 GenerateThrowUncatchable(masm, OUT_OF_MEMORY);
2802
2803 __ bind(&throw_termination_exception);
2804 GenerateThrowUncatchable(masm, TERMINATION);
2805
2806 __ bind(&throw_normal_exception);
2807 GenerateThrowTOS(masm);
2808}
2809
2810
2811void JSEntryStub::GenerateBody(MacroAssembler* masm, bool is_construct) {
2812 Label invoke, exit;
2813#ifdef ENABLE_LOGGING_AND_PROFILING
2814 Label not_outermost_js, not_outermost_js_2;
2815#endif
2816
2817 // Setup frame.
2818 __ push(rbp);
2819 __ movq(rbp, rsp);
2820
2821 // Push the stack frame type marker twice.
2822 int marker = is_construct ? StackFrame::ENTRY_CONSTRUCT : StackFrame::ENTRY;
2823 // Scratch register is neither callee-save, nor an argument register on any
2824 // platform. It's free to use at this point.
2825 // Cannot use smi-register for loading yet.
2826 __ movq(kScratchRegister,
2827 reinterpret_cast<uint64_t>(Smi::FromInt(marker)),
2828 RelocInfo::NONE);
2829 __ push(kScratchRegister); // context slot
2830 __ push(kScratchRegister); // function slot
2831 // Save callee-saved registers (X64/Win64 calling conventions).
2832 __ push(r12);
2833 __ push(r13);
2834 __ push(r14);
2835 __ push(r15);
2836#ifdef _WIN64
2837 __ push(rdi); // Only callee save in Win64 ABI, argument in AMD64 ABI.
2838 __ push(rsi); // Only callee save in Win64 ABI, argument in AMD64 ABI.
2839#endif
2840 __ push(rbx);
2841 // TODO(X64): On Win64, if we ever use XMM6-XMM15, the low low 64 bits are
2842 // callee save as well.
2843
2844 // Save copies of the top frame descriptor on the stack.
2845 ExternalReference c_entry_fp(Top::k_c_entry_fp_address);
2846 __ load_rax(c_entry_fp);
2847 __ push(rax);
2848
2849 // Set up the roots and smi constant registers.
2850 // Needs to be done before any further smi loads.
2851 ExternalReference roots_address = ExternalReference::roots_address();
2852 __ movq(kRootRegister, roots_address);
2853 __ InitializeSmiConstantRegister();
2854
2855#ifdef ENABLE_LOGGING_AND_PROFILING
2856 // If this is the outermost JS call, set js_entry_sp value.
2857 ExternalReference js_entry_sp(Top::k_js_entry_sp_address);
2858 __ load_rax(js_entry_sp);
2859 __ testq(rax, rax);
2860 __ j(not_zero, &not_outermost_js);
2861 __ movq(rax, rbp);
2862 __ store_rax(js_entry_sp);
2863 __ bind(&not_outermost_js);
2864#endif
2865
2866 // Call a faked try-block that does the invoke.
2867 __ call(&invoke);
2868
2869 // Caught exception: Store result (exception) in the pending
2870 // exception field in the JSEnv and return a failure sentinel.
2871 ExternalReference pending_exception(Top::k_pending_exception_address);
2872 __ store_rax(pending_exception);
2873 __ movq(rax, Failure::Exception(), RelocInfo::NONE);
2874 __ jmp(&exit);
2875
2876 // Invoke: Link this frame into the handler chain.
2877 __ bind(&invoke);
2878 __ PushTryHandler(IN_JS_ENTRY, JS_ENTRY_HANDLER);
2879
2880 // Clear any pending exceptions.
2881 __ load_rax(ExternalReference::the_hole_value_location());
2882 __ store_rax(pending_exception);
2883
2884 // Fake a receiver (NULL).
2885 __ push(Immediate(0)); // receiver
2886
2887 // Invoke the function by calling through JS entry trampoline
2888 // builtin and pop the faked function when we return. We load the address
2889 // from an external reference instead of inlining the call target address
2890 // directly in the code, because the builtin stubs may not have been
2891 // generated yet at the time this code is generated.
2892 if (is_construct) {
2893 ExternalReference construct_entry(Builtins::JSConstructEntryTrampoline);
2894 __ load_rax(construct_entry);
2895 } else {
2896 ExternalReference entry(Builtins::JSEntryTrampoline);
2897 __ load_rax(entry);
2898 }
2899 __ lea(kScratchRegister, FieldOperand(rax, Code::kHeaderSize));
2900 __ call(kScratchRegister);
2901
2902 // Unlink this frame from the handler chain.
2903 __ movq(kScratchRegister, ExternalReference(Top::k_handler_address));
2904 __ pop(Operand(kScratchRegister, 0));
2905 // Pop next_sp.
2906 __ addq(rsp, Immediate(StackHandlerConstants::kSize - kPointerSize));
2907
2908#ifdef ENABLE_LOGGING_AND_PROFILING
2909 // If current EBP value is the same as js_entry_sp value, it means that
2910 // the current function is the outermost.
2911 __ movq(kScratchRegister, js_entry_sp);
2912 __ cmpq(rbp, Operand(kScratchRegister, 0));
2913 __ j(not_equal, &not_outermost_js_2);
2914 __ movq(Operand(kScratchRegister, 0), Immediate(0));
2915 __ bind(&not_outermost_js_2);
2916#endif
2917
2918 // Restore the top frame descriptor from the stack.
2919 __ bind(&exit);
2920 __ movq(kScratchRegister, ExternalReference(Top::k_c_entry_fp_address));
2921 __ pop(Operand(kScratchRegister, 0));
2922
2923 // Restore callee-saved registers (X64 conventions).
2924 __ pop(rbx);
2925#ifdef _WIN64
2926 // Callee save on in Win64 ABI, arguments/volatile in AMD64 ABI.
2927 __ pop(rsi);
2928 __ pop(rdi);
2929#endif
2930 __ pop(r15);
2931 __ pop(r14);
2932 __ pop(r13);
2933 __ pop(r12);
2934 __ addq(rsp, Immediate(2 * kPointerSize)); // remove markers
2935
2936 // Restore frame pointer and return.
2937 __ pop(rbp);
2938 __ ret(0);
2939}
2940
2941
2942void InstanceofStub::Generate(MacroAssembler* masm) {
2943 // Implements "value instanceof function" operator.
2944 // Expected input state:
2945 // rsp[0] : return address
2946 // rsp[1] : function pointer
2947 // rsp[2] : value
2948 // Returns a bitwise zero to indicate that the value
2949 // is and instance of the function and anything else to
2950 // indicate that the value is not an instance.
2951
2952 // Get the object - go slow case if it's a smi.
2953 Label slow;
2954 __ movq(rax, Operand(rsp, 2 * kPointerSize));
2955 __ JumpIfSmi(rax, &slow);
2956
2957 // Check that the left hand is a JS object. Leave its map in rax.
2958 __ CmpObjectType(rax, FIRST_JS_OBJECT_TYPE, rax);
2959 __ j(below, &slow);
2960 __ CmpInstanceType(rax, LAST_JS_OBJECT_TYPE);
2961 __ j(above, &slow);
2962
2963 // Get the prototype of the function.
2964 __ movq(rdx, Operand(rsp, 1 * kPointerSize));
2965 // rdx is function, rax is map.
2966
2967 // Look up the function and the map in the instanceof cache.
Kristian Monsen0d5e1162010-09-30 15:31:59 +01002968 NearLabel miss;
Kristian Monsen80d68ea2010-09-08 11:05:35 +01002969 __ CompareRoot(rdx, Heap::kInstanceofCacheFunctionRootIndex);
2970 __ j(not_equal, &miss);
2971 __ CompareRoot(rax, Heap::kInstanceofCacheMapRootIndex);
2972 __ j(not_equal, &miss);
2973 __ LoadRoot(rax, Heap::kInstanceofCacheAnswerRootIndex);
2974 __ ret(2 * kPointerSize);
2975
2976 __ bind(&miss);
2977 __ TryGetFunctionPrototype(rdx, rbx, &slow);
2978
2979 // Check that the function prototype is a JS object.
2980 __ JumpIfSmi(rbx, &slow);
2981 __ CmpObjectType(rbx, FIRST_JS_OBJECT_TYPE, kScratchRegister);
2982 __ j(below, &slow);
2983 __ CmpInstanceType(kScratchRegister, LAST_JS_OBJECT_TYPE);
2984 __ j(above, &slow);
2985
2986 // Register mapping:
2987 // rax is object map.
2988 // rdx is function.
2989 // rbx is function prototype.
2990 __ StoreRoot(rdx, Heap::kInstanceofCacheFunctionRootIndex);
2991 __ StoreRoot(rax, Heap::kInstanceofCacheMapRootIndex);
2992
2993 __ movq(rcx, FieldOperand(rax, Map::kPrototypeOffset));
2994
2995 // Loop through the prototype chain looking for the function prototype.
Kristian Monsen0d5e1162010-09-30 15:31:59 +01002996 NearLabel loop, is_instance, is_not_instance;
Kristian Monsen80d68ea2010-09-08 11:05:35 +01002997 __ LoadRoot(kScratchRegister, Heap::kNullValueRootIndex);
2998 __ bind(&loop);
2999 __ cmpq(rcx, rbx);
3000 __ j(equal, &is_instance);
3001 __ cmpq(rcx, kScratchRegister);
3002 // The code at is_not_instance assumes that kScratchRegister contains a
3003 // non-zero GCable value (the null object in this case).
3004 __ j(equal, &is_not_instance);
3005 __ movq(rcx, FieldOperand(rcx, HeapObject::kMapOffset));
3006 __ movq(rcx, FieldOperand(rcx, Map::kPrototypeOffset));
3007 __ jmp(&loop);
3008
3009 __ bind(&is_instance);
3010 __ xorl(rax, rax);
3011 // Store bitwise zero in the cache. This is a Smi in GC terms.
3012 STATIC_ASSERT(kSmiTag == 0);
3013 __ StoreRoot(rax, Heap::kInstanceofCacheAnswerRootIndex);
3014 __ ret(2 * kPointerSize);
3015
3016 __ bind(&is_not_instance);
3017 // We have to store a non-zero value in the cache.
3018 __ StoreRoot(kScratchRegister, Heap::kInstanceofCacheAnswerRootIndex);
3019 __ ret(2 * kPointerSize);
3020
3021 // Slow-case: Go through the JavaScript implementation.
3022 __ bind(&slow);
3023 __ InvokeBuiltin(Builtins::INSTANCE_OF, JUMP_FUNCTION);
3024}
3025
3026
3027int CompareStub::MinorKey() {
3028 // Encode the three parameters in a unique 16 bit value. To avoid duplicate
3029 // stubs the never NaN NaN condition is only taken into account if the
3030 // condition is equals.
3031 ASSERT(static_cast<unsigned>(cc_) < (1 << 12));
3032 ASSERT(lhs_.is(no_reg) && rhs_.is(no_reg));
3033 return ConditionField::encode(static_cast<unsigned>(cc_))
3034 | RegisterField::encode(false) // lhs_ and rhs_ are not used
3035 | StrictField::encode(strict_)
3036 | NeverNanNanField::encode(cc_ == equal ? never_nan_nan_ : false)
Kristian Monsen0d5e1162010-09-30 15:31:59 +01003037 | IncludeNumberCompareField::encode(include_number_compare_)
3038 | IncludeSmiCompareField::encode(include_smi_compare_);
Kristian Monsen80d68ea2010-09-08 11:05:35 +01003039}
3040
3041
3042// Unfortunately you have to run without snapshots to see most of these
3043// names in the profile since most compare stubs end up in the snapshot.
3044const char* CompareStub::GetName() {
3045 ASSERT(lhs_.is(no_reg) && rhs_.is(no_reg));
3046
3047 if (name_ != NULL) return name_;
3048 const int kMaxNameLength = 100;
3049 name_ = Bootstrapper::AllocateAutoDeletedArray(kMaxNameLength);
3050 if (name_ == NULL) return "OOM";
3051
3052 const char* cc_name;
3053 switch (cc_) {
3054 case less: cc_name = "LT"; break;
3055 case greater: cc_name = "GT"; break;
3056 case less_equal: cc_name = "LE"; break;
3057 case greater_equal: cc_name = "GE"; break;
3058 case equal: cc_name = "EQ"; break;
3059 case not_equal: cc_name = "NE"; break;
3060 default: cc_name = "UnknownCondition"; break;
3061 }
3062
3063 const char* strict_name = "";
3064 if (strict_ && (cc_ == equal || cc_ == not_equal)) {
3065 strict_name = "_STRICT";
3066 }
3067
3068 const char* never_nan_nan_name = "";
3069 if (never_nan_nan_ && (cc_ == equal || cc_ == not_equal)) {
3070 never_nan_nan_name = "_NO_NAN";
3071 }
3072
3073 const char* include_number_compare_name = "";
3074 if (!include_number_compare_) {
3075 include_number_compare_name = "_NO_NUMBER";
3076 }
3077
Kristian Monsen0d5e1162010-09-30 15:31:59 +01003078 const char* include_smi_compare_name = "";
3079 if (!include_smi_compare_) {
3080 include_smi_compare_name = "_NO_SMI";
3081 }
3082
Kristian Monsen80d68ea2010-09-08 11:05:35 +01003083 OS::SNPrintF(Vector<char>(name_, kMaxNameLength),
3084 "CompareStub_%s%s%s%s",
3085 cc_name,
3086 strict_name,
3087 never_nan_nan_name,
Kristian Monsen0d5e1162010-09-30 15:31:59 +01003088 include_number_compare_name,
3089 include_smi_compare_name);
Kristian Monsen80d68ea2010-09-08 11:05:35 +01003090 return name_;
3091}
3092
3093
3094// -------------------------------------------------------------------------
3095// StringCharCodeAtGenerator
3096
3097void StringCharCodeAtGenerator::GenerateFast(MacroAssembler* masm) {
3098 Label flat_string;
3099 Label ascii_string;
3100 Label got_char_code;
3101
3102 // If the receiver is a smi trigger the non-string case.
3103 __ JumpIfSmi(object_, receiver_not_string_);
3104
3105 // Fetch the instance type of the receiver into result register.
3106 __ movq(result_, FieldOperand(object_, HeapObject::kMapOffset));
3107 __ movzxbl(result_, FieldOperand(result_, Map::kInstanceTypeOffset));
3108 // If the receiver is not a string trigger the non-string case.
3109 __ testb(result_, Immediate(kIsNotStringMask));
3110 __ j(not_zero, receiver_not_string_);
3111
3112 // If the index is non-smi trigger the non-smi case.
3113 __ JumpIfNotSmi(index_, &index_not_smi_);
3114
3115 // Put smi-tagged index into scratch register.
3116 __ movq(scratch_, index_);
3117 __ bind(&got_smi_index_);
3118
3119 // Check for index out of range.
3120 __ SmiCompare(scratch_, FieldOperand(object_, String::kLengthOffset));
3121 __ j(above_equal, index_out_of_range_);
3122
3123 // We need special handling for non-flat strings.
3124 STATIC_ASSERT(kSeqStringTag == 0);
3125 __ testb(result_, Immediate(kStringRepresentationMask));
3126 __ j(zero, &flat_string);
3127
3128 // Handle non-flat strings.
3129 __ testb(result_, Immediate(kIsConsStringMask));
3130 __ j(zero, &call_runtime_);
3131
3132 // ConsString.
3133 // Check whether the right hand side is the empty string (i.e. if
3134 // this is really a flat string in a cons string). If that is not
3135 // the case we would rather go to the runtime system now to flatten
3136 // the string.
3137 __ CompareRoot(FieldOperand(object_, ConsString::kSecondOffset),
3138 Heap::kEmptyStringRootIndex);
3139 __ j(not_equal, &call_runtime_);
3140 // Get the first of the two strings and load its instance type.
3141 __ movq(object_, FieldOperand(object_, ConsString::kFirstOffset));
3142 __ movq(result_, FieldOperand(object_, HeapObject::kMapOffset));
3143 __ movzxbl(result_, FieldOperand(result_, Map::kInstanceTypeOffset));
3144 // If the first cons component is also non-flat, then go to runtime.
3145 STATIC_ASSERT(kSeqStringTag == 0);
3146 __ testb(result_, Immediate(kStringRepresentationMask));
3147 __ j(not_zero, &call_runtime_);
3148
3149 // Check for 1-byte or 2-byte string.
3150 __ bind(&flat_string);
3151 STATIC_ASSERT(kAsciiStringTag != 0);
3152 __ testb(result_, Immediate(kStringEncodingMask));
3153 __ j(not_zero, &ascii_string);
3154
3155 // 2-byte string.
3156 // Load the 2-byte character code into the result register.
3157 __ SmiToInteger32(scratch_, scratch_);
3158 __ movzxwl(result_, FieldOperand(object_,
3159 scratch_, times_2,
3160 SeqTwoByteString::kHeaderSize));
3161 __ jmp(&got_char_code);
3162
3163 // ASCII string.
3164 // Load the byte into the result register.
3165 __ bind(&ascii_string);
3166 __ SmiToInteger32(scratch_, scratch_);
3167 __ movzxbl(result_, FieldOperand(object_,
3168 scratch_, times_1,
3169 SeqAsciiString::kHeaderSize));
3170 __ bind(&got_char_code);
3171 __ Integer32ToSmi(result_, result_);
3172 __ bind(&exit_);
3173}
3174
3175
3176void StringCharCodeAtGenerator::GenerateSlow(
3177 MacroAssembler* masm, const RuntimeCallHelper& call_helper) {
3178 __ Abort("Unexpected fallthrough to CharCodeAt slow case");
3179
3180 // Index is not a smi.
3181 __ bind(&index_not_smi_);
3182 // If index is a heap number, try converting it to an integer.
3183 __ CheckMap(index_, Factory::heap_number_map(), index_not_number_, true);
3184 call_helper.BeforeCall(masm);
3185 __ push(object_);
3186 __ push(index_);
3187 __ push(index_); // Consumed by runtime conversion function.
3188 if (index_flags_ == STRING_INDEX_IS_NUMBER) {
3189 __ CallRuntime(Runtime::kNumberToIntegerMapMinusZero, 1);
3190 } else {
3191 ASSERT(index_flags_ == STRING_INDEX_IS_ARRAY_INDEX);
3192 // NumberToSmi discards numbers that are not exact integers.
3193 __ CallRuntime(Runtime::kNumberToSmi, 1);
3194 }
3195 if (!scratch_.is(rax)) {
3196 // Save the conversion result before the pop instructions below
3197 // have a chance to overwrite it.
3198 __ movq(scratch_, rax);
3199 }
3200 __ pop(index_);
3201 __ pop(object_);
3202 // Reload the instance type.
3203 __ movq(result_, FieldOperand(object_, HeapObject::kMapOffset));
3204 __ movzxbl(result_, FieldOperand(result_, Map::kInstanceTypeOffset));
3205 call_helper.AfterCall(masm);
3206 // If index is still not a smi, it must be out of range.
3207 __ JumpIfNotSmi(scratch_, index_out_of_range_);
3208 // Otherwise, return to the fast path.
3209 __ jmp(&got_smi_index_);
3210
3211 // Call runtime. We get here when the receiver is a string and the
3212 // index is a number, but the code of getting the actual character
3213 // is too complex (e.g., when the string needs to be flattened).
3214 __ bind(&call_runtime_);
3215 call_helper.BeforeCall(masm);
3216 __ push(object_);
3217 __ push(index_);
3218 __ CallRuntime(Runtime::kStringCharCodeAt, 2);
3219 if (!result_.is(rax)) {
3220 __ movq(result_, rax);
3221 }
3222 call_helper.AfterCall(masm);
3223 __ jmp(&exit_);
3224
3225 __ Abort("Unexpected fallthrough from CharCodeAt slow case");
3226}
3227
3228
3229// -------------------------------------------------------------------------
3230// StringCharFromCodeGenerator
3231
3232void StringCharFromCodeGenerator::GenerateFast(MacroAssembler* masm) {
3233 // Fast case of Heap::LookupSingleCharacterStringFromCode.
3234 __ JumpIfNotSmi(code_, &slow_case_);
3235 __ SmiCompare(code_, Smi::FromInt(String::kMaxAsciiCharCode));
3236 __ j(above, &slow_case_);
3237
3238 __ LoadRoot(result_, Heap::kSingleCharacterStringCacheRootIndex);
3239 SmiIndex index = masm->SmiToIndex(kScratchRegister, code_, kPointerSizeLog2);
3240 __ movq(result_, FieldOperand(result_, index.reg, index.scale,
3241 FixedArray::kHeaderSize));
3242 __ CompareRoot(result_, Heap::kUndefinedValueRootIndex);
3243 __ j(equal, &slow_case_);
3244 __ bind(&exit_);
3245}
3246
3247
3248void StringCharFromCodeGenerator::GenerateSlow(
3249 MacroAssembler* masm, const RuntimeCallHelper& call_helper) {
3250 __ Abort("Unexpected fallthrough to CharFromCode slow case");
3251
3252 __ bind(&slow_case_);
3253 call_helper.BeforeCall(masm);
3254 __ push(code_);
3255 __ CallRuntime(Runtime::kCharFromCode, 1);
3256 if (!result_.is(rax)) {
3257 __ movq(result_, rax);
3258 }
3259 call_helper.AfterCall(masm);
3260 __ jmp(&exit_);
3261
3262 __ Abort("Unexpected fallthrough from CharFromCode slow case");
3263}
3264
3265
3266// -------------------------------------------------------------------------
3267// StringCharAtGenerator
3268
3269void StringCharAtGenerator::GenerateFast(MacroAssembler* masm) {
3270 char_code_at_generator_.GenerateFast(masm);
3271 char_from_code_generator_.GenerateFast(masm);
3272}
3273
3274
3275void StringCharAtGenerator::GenerateSlow(
3276 MacroAssembler* masm, const RuntimeCallHelper& call_helper) {
3277 char_code_at_generator_.GenerateSlow(masm, call_helper);
3278 char_from_code_generator_.GenerateSlow(masm, call_helper);
3279}
3280
3281
3282void StringAddStub::Generate(MacroAssembler* masm) {
3283 Label string_add_runtime;
3284
3285 // Load the two arguments.
3286 __ movq(rax, Operand(rsp, 2 * kPointerSize)); // First argument.
3287 __ movq(rdx, Operand(rsp, 1 * kPointerSize)); // Second argument.
3288
3289 // Make sure that both arguments are strings if not known in advance.
3290 if (string_check_) {
3291 Condition is_smi;
3292 is_smi = masm->CheckSmi(rax);
3293 __ j(is_smi, &string_add_runtime);
3294 __ CmpObjectType(rax, FIRST_NONSTRING_TYPE, r8);
3295 __ j(above_equal, &string_add_runtime);
3296
3297 // First argument is a a string, test second.
3298 is_smi = masm->CheckSmi(rdx);
3299 __ j(is_smi, &string_add_runtime);
3300 __ CmpObjectType(rdx, FIRST_NONSTRING_TYPE, r9);
3301 __ j(above_equal, &string_add_runtime);
3302 }
3303
3304 // Both arguments are strings.
3305 // rax: first string
3306 // rdx: second string
3307 // Check if either of the strings are empty. In that case return the other.
Kristian Monsen0d5e1162010-09-30 15:31:59 +01003308 NearLabel second_not_zero_length, both_not_zero_length;
Kristian Monsen80d68ea2010-09-08 11:05:35 +01003309 __ movq(rcx, FieldOperand(rdx, String::kLengthOffset));
3310 __ SmiTest(rcx);
3311 __ j(not_zero, &second_not_zero_length);
3312 // Second string is empty, result is first string which is already in rax.
3313 __ IncrementCounter(&Counters::string_add_native, 1);
3314 __ ret(2 * kPointerSize);
3315 __ bind(&second_not_zero_length);
3316 __ movq(rbx, FieldOperand(rax, String::kLengthOffset));
3317 __ SmiTest(rbx);
3318 __ j(not_zero, &both_not_zero_length);
3319 // First string is empty, result is second string which is in rdx.
3320 __ movq(rax, rdx);
3321 __ IncrementCounter(&Counters::string_add_native, 1);
3322 __ ret(2 * kPointerSize);
3323
3324 // Both strings are non-empty.
3325 // rax: first string
3326 // rbx: length of first string
3327 // rcx: length of second string
3328 // rdx: second string
3329 // r8: map of first string if string check was performed above
3330 // r9: map of second string if string check was performed above
3331 Label string_add_flat_result, longer_than_two;
3332 __ bind(&both_not_zero_length);
3333
3334 // If arguments where known to be strings, maps are not loaded to r8 and r9
3335 // by the code above.
3336 if (!string_check_) {
3337 __ movq(r8, FieldOperand(rax, HeapObject::kMapOffset));
3338 __ movq(r9, FieldOperand(rdx, HeapObject::kMapOffset));
3339 }
3340 // Get the instance types of the two strings as they will be needed soon.
3341 __ movzxbl(r8, FieldOperand(r8, Map::kInstanceTypeOffset));
3342 __ movzxbl(r9, FieldOperand(r9, Map::kInstanceTypeOffset));
3343
3344 // Look at the length of the result of adding the two strings.
3345 STATIC_ASSERT(String::kMaxLength <= Smi::kMaxValue / 2);
Kristian Monsen0d5e1162010-09-30 15:31:59 +01003346 __ SmiAdd(rbx, rbx, rcx);
Kristian Monsen80d68ea2010-09-08 11:05:35 +01003347 // Use the runtime system when adding two one character strings, as it
3348 // contains optimizations for this specific case using the symbol table.
3349 __ SmiCompare(rbx, Smi::FromInt(2));
3350 __ j(not_equal, &longer_than_two);
3351
3352 // Check that both strings are non-external ascii strings.
3353 __ JumpIfBothInstanceTypesAreNotSequentialAscii(r8, r9, rbx, rcx,
3354 &string_add_runtime);
3355
3356 // Get the two characters forming the sub string.
3357 __ movzxbq(rbx, FieldOperand(rax, SeqAsciiString::kHeaderSize));
3358 __ movzxbq(rcx, FieldOperand(rdx, SeqAsciiString::kHeaderSize));
3359
3360 // Try to lookup two character string in symbol table. If it is not found
3361 // just allocate a new one.
3362 Label make_two_character_string, make_flat_ascii_string;
3363 StringHelper::GenerateTwoCharacterSymbolTableProbe(
3364 masm, rbx, rcx, r14, r11, rdi, r12, &make_two_character_string);
3365 __ IncrementCounter(&Counters::string_add_native, 1);
3366 __ ret(2 * kPointerSize);
3367
3368 __ bind(&make_two_character_string);
3369 __ Set(rbx, 2);
3370 __ jmp(&make_flat_ascii_string);
3371
3372 __ bind(&longer_than_two);
3373 // Check if resulting string will be flat.
3374 __ SmiCompare(rbx, Smi::FromInt(String::kMinNonFlatLength));
3375 __ j(below, &string_add_flat_result);
3376 // Handle exceptionally long strings in the runtime system.
3377 STATIC_ASSERT((String::kMaxLength & 0x80000000) == 0);
3378 __ SmiCompare(rbx, Smi::FromInt(String::kMaxLength));
3379 __ j(above, &string_add_runtime);
3380
3381 // If result is not supposed to be flat, allocate a cons string object. If
3382 // both strings are ascii the result is an ascii cons string.
3383 // rax: first string
3384 // rbx: length of resulting flat string
3385 // rdx: second string
3386 // r8: instance type of first string
3387 // r9: instance type of second string
3388 Label non_ascii, allocated, ascii_data;
3389 __ movl(rcx, r8);
3390 __ and_(rcx, r9);
3391 STATIC_ASSERT(kStringEncodingMask == kAsciiStringTag);
3392 __ testl(rcx, Immediate(kAsciiStringTag));
3393 __ j(zero, &non_ascii);
3394 __ bind(&ascii_data);
3395 // Allocate an acsii cons string.
3396 __ AllocateAsciiConsString(rcx, rdi, no_reg, &string_add_runtime);
3397 __ bind(&allocated);
3398 // Fill the fields of the cons string.
3399 __ movq(FieldOperand(rcx, ConsString::kLengthOffset), rbx);
3400 __ movq(FieldOperand(rcx, ConsString::kHashFieldOffset),
3401 Immediate(String::kEmptyHashField));
3402 __ movq(FieldOperand(rcx, ConsString::kFirstOffset), rax);
3403 __ movq(FieldOperand(rcx, ConsString::kSecondOffset), rdx);
3404 __ movq(rax, rcx);
3405 __ IncrementCounter(&Counters::string_add_native, 1);
3406 __ ret(2 * kPointerSize);
3407 __ bind(&non_ascii);
3408 // At least one of the strings is two-byte. Check whether it happens
3409 // to contain only ascii characters.
3410 // rcx: first instance type AND second instance type.
3411 // r8: first instance type.
3412 // r9: second instance type.
3413 __ testb(rcx, Immediate(kAsciiDataHintMask));
3414 __ j(not_zero, &ascii_data);
3415 __ xor_(r8, r9);
3416 STATIC_ASSERT(kAsciiStringTag != 0 && kAsciiDataHintTag != 0);
3417 __ andb(r8, Immediate(kAsciiStringTag | kAsciiDataHintTag));
3418 __ cmpb(r8, Immediate(kAsciiStringTag | kAsciiDataHintTag));
3419 __ j(equal, &ascii_data);
3420 // Allocate a two byte cons string.
3421 __ AllocateConsString(rcx, rdi, no_reg, &string_add_runtime);
3422 __ jmp(&allocated);
3423
3424 // Handle creating a flat result. First check that both strings are not
3425 // external strings.
3426 // rax: first string
3427 // rbx: length of resulting flat string as smi
3428 // rdx: second string
3429 // r8: instance type of first string
3430 // r9: instance type of first string
3431 __ bind(&string_add_flat_result);
3432 __ SmiToInteger32(rbx, rbx);
3433 __ movl(rcx, r8);
3434 __ and_(rcx, Immediate(kStringRepresentationMask));
3435 __ cmpl(rcx, Immediate(kExternalStringTag));
3436 __ j(equal, &string_add_runtime);
3437 __ movl(rcx, r9);
3438 __ and_(rcx, Immediate(kStringRepresentationMask));
3439 __ cmpl(rcx, Immediate(kExternalStringTag));
3440 __ j(equal, &string_add_runtime);
3441 // Now check if both strings are ascii strings.
3442 // rax: first string
3443 // rbx: length of resulting flat string
3444 // rdx: second string
3445 // r8: instance type of first string
3446 // r9: instance type of second string
3447 Label non_ascii_string_add_flat_result;
3448 STATIC_ASSERT(kStringEncodingMask == kAsciiStringTag);
3449 __ testl(r8, Immediate(kAsciiStringTag));
3450 __ j(zero, &non_ascii_string_add_flat_result);
3451 __ testl(r9, Immediate(kAsciiStringTag));
3452 __ j(zero, &string_add_runtime);
3453
3454 __ bind(&make_flat_ascii_string);
3455 // Both strings are ascii strings. As they are short they are both flat.
3456 __ AllocateAsciiString(rcx, rbx, rdi, r14, r11, &string_add_runtime);
3457 // rcx: result string
3458 __ movq(rbx, rcx);
3459 // Locate first character of result.
3460 __ addq(rcx, Immediate(SeqAsciiString::kHeaderSize - kHeapObjectTag));
3461 // Locate first character of first argument
3462 __ SmiToInteger32(rdi, FieldOperand(rax, String::kLengthOffset));
3463 __ addq(rax, Immediate(SeqAsciiString::kHeaderSize - kHeapObjectTag));
3464 // rax: first char of first argument
3465 // rbx: result string
3466 // rcx: first character of result
3467 // rdx: second string
3468 // rdi: length of first argument
3469 StringHelper::GenerateCopyCharacters(masm, rcx, rax, rdi, true);
3470 // Locate first character of second argument.
3471 __ SmiToInteger32(rdi, FieldOperand(rdx, String::kLengthOffset));
3472 __ addq(rdx, Immediate(SeqAsciiString::kHeaderSize - kHeapObjectTag));
3473 // rbx: result string
3474 // rcx: next character of result
3475 // rdx: first char of second argument
3476 // rdi: length of second argument
3477 StringHelper::GenerateCopyCharacters(masm, rcx, rdx, rdi, true);
3478 __ movq(rax, rbx);
3479 __ IncrementCounter(&Counters::string_add_native, 1);
3480 __ ret(2 * kPointerSize);
3481
3482 // Handle creating a flat two byte result.
3483 // rax: first string - known to be two byte
3484 // rbx: length of resulting flat string
3485 // rdx: second string
3486 // r8: instance type of first string
3487 // r9: instance type of first string
3488 __ bind(&non_ascii_string_add_flat_result);
3489 __ and_(r9, Immediate(kAsciiStringTag));
3490 __ j(not_zero, &string_add_runtime);
3491 // Both strings are two byte strings. As they are short they are both
3492 // flat.
3493 __ AllocateTwoByteString(rcx, rbx, rdi, r14, r11, &string_add_runtime);
3494 // rcx: result string
3495 __ movq(rbx, rcx);
3496 // Locate first character of result.
3497 __ addq(rcx, Immediate(SeqTwoByteString::kHeaderSize - kHeapObjectTag));
3498 // Locate first character of first argument.
3499 __ SmiToInteger32(rdi, FieldOperand(rax, String::kLengthOffset));
3500 __ addq(rax, Immediate(SeqTwoByteString::kHeaderSize - kHeapObjectTag));
3501 // rax: first char of first argument
3502 // rbx: result string
3503 // rcx: first character of result
3504 // rdx: second argument
3505 // rdi: length of first argument
3506 StringHelper::GenerateCopyCharacters(masm, rcx, rax, rdi, false);
3507 // Locate first character of second argument.
3508 __ SmiToInteger32(rdi, FieldOperand(rdx, String::kLengthOffset));
3509 __ addq(rdx, Immediate(SeqTwoByteString::kHeaderSize - kHeapObjectTag));
3510 // rbx: result string
3511 // rcx: next character of result
3512 // rdx: first char of second argument
3513 // rdi: length of second argument
3514 StringHelper::GenerateCopyCharacters(masm, rcx, rdx, rdi, false);
3515 __ movq(rax, rbx);
3516 __ IncrementCounter(&Counters::string_add_native, 1);
3517 __ ret(2 * kPointerSize);
3518
3519 // Just jump to runtime to add the two strings.
3520 __ bind(&string_add_runtime);
3521 __ TailCallRuntime(Runtime::kStringAdd, 2, 1);
3522}
3523
3524
3525void StringHelper::GenerateCopyCharacters(MacroAssembler* masm,
3526 Register dest,
3527 Register src,
3528 Register count,
3529 bool ascii) {
3530 Label loop;
3531 __ bind(&loop);
3532 // This loop just copies one character at a time, as it is only used for very
3533 // short strings.
3534 if (ascii) {
3535 __ movb(kScratchRegister, Operand(src, 0));
3536 __ movb(Operand(dest, 0), kScratchRegister);
3537 __ incq(src);
3538 __ incq(dest);
3539 } else {
3540 __ movzxwl(kScratchRegister, Operand(src, 0));
3541 __ movw(Operand(dest, 0), kScratchRegister);
3542 __ addq(src, Immediate(2));
3543 __ addq(dest, Immediate(2));
3544 }
3545 __ decl(count);
3546 __ j(not_zero, &loop);
3547}
3548
3549
3550void StringHelper::GenerateCopyCharactersREP(MacroAssembler* masm,
3551 Register dest,
3552 Register src,
3553 Register count,
3554 bool ascii) {
3555 // Copy characters using rep movs of doublewords. Align destination on 4 byte
3556 // boundary before starting rep movs. Copy remaining characters after running
3557 // rep movs.
3558 // Count is positive int32, dest and src are character pointers.
3559 ASSERT(dest.is(rdi)); // rep movs destination
3560 ASSERT(src.is(rsi)); // rep movs source
3561 ASSERT(count.is(rcx)); // rep movs count
3562
3563 // Nothing to do for zero characters.
Kristian Monsen0d5e1162010-09-30 15:31:59 +01003564 NearLabel done;
Kristian Monsen80d68ea2010-09-08 11:05:35 +01003565 __ testl(count, count);
3566 __ j(zero, &done);
3567
3568 // Make count the number of bytes to copy.
3569 if (!ascii) {
3570 STATIC_ASSERT(2 == sizeof(uc16));
3571 __ addl(count, count);
3572 }
3573
3574 // Don't enter the rep movs if there are less than 4 bytes to copy.
Kristian Monsen0d5e1162010-09-30 15:31:59 +01003575 NearLabel last_bytes;
Kristian Monsen80d68ea2010-09-08 11:05:35 +01003576 __ testl(count, Immediate(~7));
3577 __ j(zero, &last_bytes);
3578
3579 // Copy from edi to esi using rep movs instruction.
3580 __ movl(kScratchRegister, count);
3581 __ shr(count, Immediate(3)); // Number of doublewords to copy.
3582 __ repmovsq();
3583
3584 // Find number of bytes left.
3585 __ movl(count, kScratchRegister);
3586 __ and_(count, Immediate(7));
3587
3588 // Check if there are more bytes to copy.
3589 __ bind(&last_bytes);
3590 __ testl(count, count);
3591 __ j(zero, &done);
3592
3593 // Copy remaining characters.
3594 Label loop;
3595 __ bind(&loop);
3596 __ movb(kScratchRegister, Operand(src, 0));
3597 __ movb(Operand(dest, 0), kScratchRegister);
3598 __ incq(src);
3599 __ incq(dest);
3600 __ decl(count);
3601 __ j(not_zero, &loop);
3602
3603 __ bind(&done);
3604}
3605
3606void StringHelper::GenerateTwoCharacterSymbolTableProbe(MacroAssembler* masm,
3607 Register c1,
3608 Register c2,
3609 Register scratch1,
3610 Register scratch2,
3611 Register scratch3,
3612 Register scratch4,
3613 Label* not_found) {
3614 // Register scratch3 is the general scratch register in this function.
3615 Register scratch = scratch3;
3616
3617 // Make sure that both characters are not digits as such strings has a
3618 // different hash algorithm. Don't try to look for these in the symbol table.
Kristian Monsen0d5e1162010-09-30 15:31:59 +01003619 NearLabel not_array_index;
Kristian Monsen80d68ea2010-09-08 11:05:35 +01003620 __ leal(scratch, Operand(c1, -'0'));
3621 __ cmpl(scratch, Immediate(static_cast<int>('9' - '0')));
3622 __ j(above, &not_array_index);
3623 __ leal(scratch, Operand(c2, -'0'));
3624 __ cmpl(scratch, Immediate(static_cast<int>('9' - '0')));
3625 __ j(below_equal, not_found);
3626
3627 __ bind(&not_array_index);
3628 // Calculate the two character string hash.
3629 Register hash = scratch1;
3630 GenerateHashInit(masm, hash, c1, scratch);
3631 GenerateHashAddCharacter(masm, hash, c2, scratch);
3632 GenerateHashGetHash(masm, hash, scratch);
3633
3634 // Collect the two characters in a register.
3635 Register chars = c1;
3636 __ shl(c2, Immediate(kBitsPerByte));
3637 __ orl(chars, c2);
3638
3639 // chars: two character string, char 1 in byte 0 and char 2 in byte 1.
3640 // hash: hash of two character string.
3641
3642 // Load the symbol table.
3643 Register symbol_table = c2;
3644 __ LoadRoot(symbol_table, Heap::kSymbolTableRootIndex);
3645
3646 // Calculate capacity mask from the symbol table capacity.
3647 Register mask = scratch2;
3648 __ SmiToInteger32(mask,
3649 FieldOperand(symbol_table, SymbolTable::kCapacityOffset));
3650 __ decl(mask);
3651
3652 Register undefined = scratch4;
3653 __ LoadRoot(undefined, Heap::kUndefinedValueRootIndex);
3654
3655 // Registers
3656 // chars: two character string, char 1 in byte 0 and char 2 in byte 1.
3657 // hash: hash of two character string (32-bit int)
3658 // symbol_table: symbol table
3659 // mask: capacity mask (32-bit int)
3660 // undefined: undefined value
3661 // scratch: -
3662
3663 // Perform a number of probes in the symbol table.
3664 static const int kProbes = 4;
3665 Label found_in_symbol_table;
3666 Label next_probe[kProbes];
3667 for (int i = 0; i < kProbes; i++) {
3668 // Calculate entry in symbol table.
3669 __ movl(scratch, hash);
3670 if (i > 0) {
3671 __ addl(scratch, Immediate(SymbolTable::GetProbeOffset(i)));
3672 }
3673 __ andl(scratch, mask);
3674
3675 // Load the entry from the symble table.
3676 Register candidate = scratch; // Scratch register contains candidate.
3677 STATIC_ASSERT(SymbolTable::kEntrySize == 1);
3678 __ movq(candidate,
3679 FieldOperand(symbol_table,
3680 scratch,
3681 times_pointer_size,
3682 SymbolTable::kElementsStartOffset));
3683
3684 // If entry is undefined no string with this hash can be found.
3685 __ cmpq(candidate, undefined);
3686 __ j(equal, not_found);
3687
3688 // If length is not 2 the string is not a candidate.
3689 __ SmiCompare(FieldOperand(candidate, String::kLengthOffset),
3690 Smi::FromInt(2));
3691 __ j(not_equal, &next_probe[i]);
3692
3693 // We use kScratchRegister as a temporary register in assumption that
3694 // JumpIfInstanceTypeIsNotSequentialAscii does not use it implicitly
3695 Register temp = kScratchRegister;
3696
3697 // Check that the candidate is a non-external ascii string.
3698 __ movq(temp, FieldOperand(candidate, HeapObject::kMapOffset));
3699 __ movzxbl(temp, FieldOperand(temp, Map::kInstanceTypeOffset));
3700 __ JumpIfInstanceTypeIsNotSequentialAscii(
3701 temp, temp, &next_probe[i]);
3702
3703 // Check if the two characters match.
3704 __ movl(temp, FieldOperand(candidate, SeqAsciiString::kHeaderSize));
3705 __ andl(temp, Immediate(0x0000ffff));
3706 __ cmpl(chars, temp);
3707 __ j(equal, &found_in_symbol_table);
3708 __ bind(&next_probe[i]);
3709 }
3710
3711 // No matching 2 character string found by probing.
3712 __ jmp(not_found);
3713
3714 // Scratch register contains result when we fall through to here.
3715 Register result = scratch;
3716 __ bind(&found_in_symbol_table);
3717 if (!result.is(rax)) {
3718 __ movq(rax, result);
3719 }
3720}
3721
3722
3723void StringHelper::GenerateHashInit(MacroAssembler* masm,
3724 Register hash,
3725 Register character,
3726 Register scratch) {
3727 // hash = character + (character << 10);
3728 __ movl(hash, character);
3729 __ shll(hash, Immediate(10));
3730 __ addl(hash, character);
3731 // hash ^= hash >> 6;
3732 __ movl(scratch, hash);
3733 __ sarl(scratch, Immediate(6));
3734 __ xorl(hash, scratch);
3735}
3736
3737
3738void StringHelper::GenerateHashAddCharacter(MacroAssembler* masm,
3739 Register hash,
3740 Register character,
3741 Register scratch) {
3742 // hash += character;
3743 __ addl(hash, character);
3744 // hash += hash << 10;
3745 __ movl(scratch, hash);
3746 __ shll(scratch, Immediate(10));
3747 __ addl(hash, scratch);
3748 // hash ^= hash >> 6;
3749 __ movl(scratch, hash);
3750 __ sarl(scratch, Immediate(6));
3751 __ xorl(hash, scratch);
3752}
3753
3754
3755void StringHelper::GenerateHashGetHash(MacroAssembler* masm,
3756 Register hash,
3757 Register scratch) {
3758 // hash += hash << 3;
3759 __ leal(hash, Operand(hash, hash, times_8, 0));
3760 // hash ^= hash >> 11;
3761 __ movl(scratch, hash);
3762 __ sarl(scratch, Immediate(11));
3763 __ xorl(hash, scratch);
3764 // hash += hash << 15;
3765 __ movl(scratch, hash);
3766 __ shll(scratch, Immediate(15));
3767 __ addl(hash, scratch);
3768
3769 // if (hash == 0) hash = 27;
3770 Label hash_not_zero;
3771 __ j(not_zero, &hash_not_zero);
3772 __ movl(hash, Immediate(27));
3773 __ bind(&hash_not_zero);
3774}
3775
3776void SubStringStub::Generate(MacroAssembler* masm) {
3777 Label runtime;
3778
3779 // Stack frame on entry.
3780 // rsp[0]: return address
3781 // rsp[8]: to
3782 // rsp[16]: from
3783 // rsp[24]: string
3784
3785 const int kToOffset = 1 * kPointerSize;
3786 const int kFromOffset = kToOffset + kPointerSize;
3787 const int kStringOffset = kFromOffset + kPointerSize;
3788 const int kArgumentsSize = (kStringOffset + kPointerSize) - kToOffset;
3789
3790 // Make sure first argument is a string.
3791 __ movq(rax, Operand(rsp, kStringOffset));
3792 STATIC_ASSERT(kSmiTag == 0);
3793 __ testl(rax, Immediate(kSmiTagMask));
3794 __ j(zero, &runtime);
3795 Condition is_string = masm->IsObjectStringType(rax, rbx, rbx);
3796 __ j(NegateCondition(is_string), &runtime);
3797
3798 // rax: string
3799 // rbx: instance type
3800 // Calculate length of sub string using the smi values.
3801 Label result_longer_than_two;
3802 __ movq(rcx, Operand(rsp, kToOffset));
3803 __ movq(rdx, Operand(rsp, kFromOffset));
3804 __ JumpIfNotBothPositiveSmi(rcx, rdx, &runtime);
3805
Kristian Monsen0d5e1162010-09-30 15:31:59 +01003806 __ SmiSub(rcx, rcx, rdx); // Overflow doesn't happen.
Kristian Monsen80d68ea2010-09-08 11:05:35 +01003807 __ cmpq(FieldOperand(rax, String::kLengthOffset), rcx);
3808 Label return_rax;
3809 __ j(equal, &return_rax);
3810 // Special handling of sub-strings of length 1 and 2. One character strings
3811 // are handled in the runtime system (looked up in the single character
3812 // cache). Two character strings are looked for in the symbol cache.
3813 __ SmiToInteger32(rcx, rcx);
3814 __ cmpl(rcx, Immediate(2));
3815 __ j(greater, &result_longer_than_two);
3816 __ j(less, &runtime);
3817
3818 // Sub string of length 2 requested.
3819 // rax: string
3820 // rbx: instance type
3821 // rcx: sub string length (value is 2)
3822 // rdx: from index (smi)
3823 __ JumpIfInstanceTypeIsNotSequentialAscii(rbx, rbx, &runtime);
3824
3825 // Get the two characters forming the sub string.
3826 __ SmiToInteger32(rdx, rdx); // From index is no longer smi.
3827 __ movzxbq(rbx, FieldOperand(rax, rdx, times_1, SeqAsciiString::kHeaderSize));
3828 __ movzxbq(rcx,
3829 FieldOperand(rax, rdx, times_1, SeqAsciiString::kHeaderSize + 1));
3830
3831 // Try to lookup two character string in symbol table.
3832 Label make_two_character_string;
3833 StringHelper::GenerateTwoCharacterSymbolTableProbe(
3834 masm, rbx, rcx, rax, rdx, rdi, r14, &make_two_character_string);
3835 __ ret(3 * kPointerSize);
3836
3837 __ bind(&make_two_character_string);
3838 // Setup registers for allocating the two character string.
3839 __ movq(rax, Operand(rsp, kStringOffset));
3840 __ movq(rbx, FieldOperand(rax, HeapObject::kMapOffset));
3841 __ movzxbl(rbx, FieldOperand(rbx, Map::kInstanceTypeOffset));
3842 __ Set(rcx, 2);
3843
3844 __ bind(&result_longer_than_two);
3845
3846 // rax: string
3847 // rbx: instance type
3848 // rcx: result string length
3849 // Check for flat ascii string
3850 Label non_ascii_flat;
3851 __ JumpIfInstanceTypeIsNotSequentialAscii(rbx, rbx, &non_ascii_flat);
3852
3853 // Allocate the result.
3854 __ AllocateAsciiString(rax, rcx, rbx, rdx, rdi, &runtime);
3855
3856 // rax: result string
3857 // rcx: result string length
3858 __ movq(rdx, rsi); // esi used by following code.
3859 // Locate first character of result.
3860 __ lea(rdi, FieldOperand(rax, SeqAsciiString::kHeaderSize));
3861 // Load string argument and locate character of sub string start.
3862 __ movq(rsi, Operand(rsp, kStringOffset));
3863 __ movq(rbx, Operand(rsp, kFromOffset));
3864 {
3865 SmiIndex smi_as_index = masm->SmiToIndex(rbx, rbx, times_1);
3866 __ lea(rsi, Operand(rsi, smi_as_index.reg, smi_as_index.scale,
3867 SeqAsciiString::kHeaderSize - kHeapObjectTag));
3868 }
3869
3870 // rax: result string
3871 // rcx: result length
3872 // rdx: original value of rsi
3873 // rdi: first character of result
3874 // rsi: character of sub string start
3875 StringHelper::GenerateCopyCharactersREP(masm, rdi, rsi, rcx, true);
3876 __ movq(rsi, rdx); // Restore rsi.
3877 __ IncrementCounter(&Counters::sub_string_native, 1);
3878 __ ret(kArgumentsSize);
3879
3880 __ bind(&non_ascii_flat);
3881 // rax: string
3882 // rbx: instance type & kStringRepresentationMask | kStringEncodingMask
3883 // rcx: result string length
3884 // Check for sequential two byte string
3885 __ cmpb(rbx, Immediate(kSeqStringTag | kTwoByteStringTag));
3886 __ j(not_equal, &runtime);
3887
3888 // Allocate the result.
3889 __ AllocateTwoByteString(rax, rcx, rbx, rdx, rdi, &runtime);
3890
3891 // rax: result string
3892 // rcx: result string length
3893 __ movq(rdx, rsi); // esi used by following code.
3894 // Locate first character of result.
3895 __ lea(rdi, FieldOperand(rax, SeqTwoByteString::kHeaderSize));
3896 // Load string argument and locate character of sub string start.
3897 __ movq(rsi, Operand(rsp, kStringOffset));
3898 __ movq(rbx, Operand(rsp, kFromOffset));
3899 {
3900 SmiIndex smi_as_index = masm->SmiToIndex(rbx, rbx, times_2);
3901 __ lea(rsi, Operand(rsi, smi_as_index.reg, smi_as_index.scale,
3902 SeqAsciiString::kHeaderSize - kHeapObjectTag));
3903 }
3904
3905 // rax: result string
3906 // rcx: result length
3907 // rdx: original value of rsi
3908 // rdi: first character of result
3909 // rsi: character of sub string start
3910 StringHelper::GenerateCopyCharactersREP(masm, rdi, rsi, rcx, false);
3911 __ movq(rsi, rdx); // Restore esi.
3912
3913 __ bind(&return_rax);
3914 __ IncrementCounter(&Counters::sub_string_native, 1);
3915 __ ret(kArgumentsSize);
3916
3917 // Just jump to runtime to create the sub string.
3918 __ bind(&runtime);
3919 __ TailCallRuntime(Runtime::kSubString, 3, 1);
3920}
3921
3922
3923void StringCompareStub::GenerateCompareFlatAsciiStrings(MacroAssembler* masm,
3924 Register left,
3925 Register right,
3926 Register scratch1,
3927 Register scratch2,
3928 Register scratch3,
3929 Register scratch4) {
3930 // Ensure that you can always subtract a string length from a non-negative
3931 // number (e.g. another length).
3932 STATIC_ASSERT(String::kMaxLength < 0x7fffffff);
3933
3934 // Find minimum length and length difference.
3935 __ movq(scratch1, FieldOperand(left, String::kLengthOffset));
3936 __ movq(scratch4, scratch1);
3937 __ SmiSub(scratch4,
3938 scratch4,
Kristian Monsen0d5e1162010-09-30 15:31:59 +01003939 FieldOperand(right, String::kLengthOffset));
Kristian Monsen80d68ea2010-09-08 11:05:35 +01003940 // Register scratch4 now holds left.length - right.length.
3941 const Register length_difference = scratch4;
Kristian Monsen0d5e1162010-09-30 15:31:59 +01003942 NearLabel left_shorter;
Kristian Monsen80d68ea2010-09-08 11:05:35 +01003943 __ j(less, &left_shorter);
3944 // The right string isn't longer that the left one.
3945 // Get the right string's length by subtracting the (non-negative) difference
3946 // from the left string's length.
Kristian Monsen0d5e1162010-09-30 15:31:59 +01003947 __ SmiSub(scratch1, scratch1, length_difference);
Kristian Monsen80d68ea2010-09-08 11:05:35 +01003948 __ bind(&left_shorter);
3949 // Register scratch1 now holds Min(left.length, right.length).
3950 const Register min_length = scratch1;
3951
Kristian Monsen0d5e1162010-09-30 15:31:59 +01003952 NearLabel compare_lengths;
Kristian Monsen80d68ea2010-09-08 11:05:35 +01003953 // If min-length is zero, go directly to comparing lengths.
3954 __ SmiTest(min_length);
3955 __ j(zero, &compare_lengths);
3956
3957 __ SmiToInteger32(min_length, min_length);
3958
3959 // Registers scratch2 and scratch3 are free.
Kristian Monsen0d5e1162010-09-30 15:31:59 +01003960 NearLabel result_not_equal;
Kristian Monsen80d68ea2010-09-08 11:05:35 +01003961 Label loop;
3962 {
3963 // Check characters 0 .. min_length - 1 in a loop.
3964 // Use scratch3 as loop index, min_length as limit and scratch2
3965 // for computation.
3966 const Register index = scratch3;
3967 __ movl(index, Immediate(0)); // Index into strings.
3968 __ bind(&loop);
3969 // Compare characters.
3970 // TODO(lrn): Could we load more than one character at a time?
3971 __ movb(scratch2, FieldOperand(left,
3972 index,
3973 times_1,
3974 SeqAsciiString::kHeaderSize));
3975 // Increment index and use -1 modifier on next load to give
3976 // the previous load extra time to complete.
3977 __ addl(index, Immediate(1));
3978 __ cmpb(scratch2, FieldOperand(right,
3979 index,
3980 times_1,
3981 SeqAsciiString::kHeaderSize - 1));
3982 __ j(not_equal, &result_not_equal);
3983 __ cmpl(index, min_length);
3984 __ j(not_equal, &loop);
3985 }
3986 // Completed loop without finding different characters.
3987 // Compare lengths (precomputed).
3988 __ bind(&compare_lengths);
3989 __ SmiTest(length_difference);
3990 __ j(not_zero, &result_not_equal);
3991
3992 // Result is EQUAL.
3993 __ Move(rax, Smi::FromInt(EQUAL));
3994 __ ret(0);
3995
Kristian Monsen0d5e1162010-09-30 15:31:59 +01003996 NearLabel result_greater;
Kristian Monsen80d68ea2010-09-08 11:05:35 +01003997 __ bind(&result_not_equal);
3998 // Unequal comparison of left to right, either character or length.
3999 __ j(greater, &result_greater);
4000
4001 // Result is LESS.
4002 __ Move(rax, Smi::FromInt(LESS));
4003 __ ret(0);
4004
4005 // Result is GREATER.
4006 __ bind(&result_greater);
4007 __ Move(rax, Smi::FromInt(GREATER));
4008 __ ret(0);
4009}
4010
4011
4012void StringCompareStub::Generate(MacroAssembler* masm) {
4013 Label runtime;
4014
4015 // Stack frame on entry.
4016 // rsp[0]: return address
4017 // rsp[8]: right string
4018 // rsp[16]: left string
4019
4020 __ movq(rdx, Operand(rsp, 2 * kPointerSize)); // left
4021 __ movq(rax, Operand(rsp, 1 * kPointerSize)); // right
4022
4023 // Check for identity.
Kristian Monsen0d5e1162010-09-30 15:31:59 +01004024 NearLabel not_same;
Kristian Monsen80d68ea2010-09-08 11:05:35 +01004025 __ cmpq(rdx, rax);
4026 __ j(not_equal, &not_same);
4027 __ Move(rax, Smi::FromInt(EQUAL));
4028 __ IncrementCounter(&Counters::string_compare_native, 1);
4029 __ ret(2 * kPointerSize);
4030
4031 __ bind(&not_same);
4032
4033 // Check that both are sequential ASCII strings.
4034 __ JumpIfNotBothSequentialAsciiStrings(rdx, rax, rcx, rbx, &runtime);
4035
4036 // Inline comparison of ascii strings.
4037 __ IncrementCounter(&Counters::string_compare_native, 1);
4038 // Drop arguments from the stack
4039 __ pop(rcx);
4040 __ addq(rsp, Immediate(2 * kPointerSize));
4041 __ push(rcx);
4042 GenerateCompareFlatAsciiStrings(masm, rdx, rax, rcx, rbx, rdi, r8);
4043
4044 // Call the runtime; it returns -1 (less), 0 (equal), or 1 (greater)
4045 // tagged as a small integer.
4046 __ bind(&runtime);
4047 __ TailCallRuntime(Runtime::kStringCompare, 2, 1);
4048}
4049
4050#undef __
4051
4052} } // namespace v8::internal
4053
4054#endif // V8_TARGET_ARCH_X64