blob: 2d87667baef6cc69478a70bae76dfc97c16b1b62 [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);
Ben Murdochf87a2032010-10-22 12:50:53 +01001416 __ jmp(&slow); // zero, if not handled above, and Smi::kMinValue.
Kristian Monsen80d68ea2010-09-08 11:05:35 +01001417
Kristian Monsen0d5e1162010-09-30 15:31:59 +01001418 // Try floating point case.
1419 __ bind(&try_float);
1420 } else if (FLAG_debug_code) {
1421 __ AbortIfSmi(rax);
Kristian Monsen80d68ea2010-09-08 11:05:35 +01001422 }
1423
Kristian Monsen80d68ea2010-09-08 11:05:35 +01001424 __ movq(rdx, FieldOperand(rax, HeapObject::kMapOffset));
1425 __ CompareRoot(rdx, Heap::kHeapNumberMapRootIndex);
1426 __ j(not_equal, &slow);
1427 // Operand is a float, negate its value by flipping sign bit.
1428 __ movq(rdx, FieldOperand(rax, HeapNumber::kValueOffset));
1429 __ movq(kScratchRegister, Immediate(0x01));
1430 __ shl(kScratchRegister, Immediate(63));
1431 __ xor_(rdx, kScratchRegister); // Flip sign.
1432 // rdx is value to store.
1433 if (overwrite_ == UNARY_OVERWRITE) {
1434 __ movq(FieldOperand(rax, HeapNumber::kValueOffset), rdx);
1435 } else {
1436 __ AllocateHeapNumber(rcx, rbx, &slow);
1437 // rcx: allocated 'empty' number
1438 __ movq(FieldOperand(rcx, HeapNumber::kValueOffset), rdx);
1439 __ movq(rax, rcx);
1440 }
1441 } else if (op_ == Token::BIT_NOT) {
Kristian Monsen0d5e1162010-09-30 15:31:59 +01001442 if (include_smi_code_) {
1443 Label try_float;
1444 __ JumpIfNotSmi(rax, &try_float);
1445 __ SmiNot(rax, rax);
1446 __ jmp(&done);
1447 // Try floating point case.
1448 __ bind(&try_float);
1449 } else if (FLAG_debug_code) {
1450 __ AbortIfSmi(rax);
1451 }
1452
Kristian Monsen80d68ea2010-09-08 11:05:35 +01001453 // Check if the operand is a heap number.
1454 __ movq(rdx, FieldOperand(rax, HeapObject::kMapOffset));
1455 __ CompareRoot(rdx, Heap::kHeapNumberMapRootIndex);
1456 __ j(not_equal, &slow);
1457
1458 // Convert the heap number in rax to an untagged integer in rcx.
1459 IntegerConvert(masm, rax, rax);
1460
1461 // Do the bitwise operation and smi tag the result.
1462 __ notl(rax);
1463 __ Integer32ToSmi(rax, rax);
1464 }
1465
1466 // Return from the stub.
1467 __ bind(&done);
1468 __ StubReturn(1);
1469
1470 // Handle the slow case by jumping to the JavaScript builtin.
1471 __ bind(&slow);
1472 __ pop(rcx); // pop return address
1473 __ push(rax);
1474 __ push(rcx); // push return address
1475 switch (op_) {
1476 case Token::SUB:
1477 __ InvokeBuiltin(Builtins::UNARY_MINUS, JUMP_FUNCTION);
1478 break;
1479 case Token::BIT_NOT:
1480 __ InvokeBuiltin(Builtins::BIT_NOT, JUMP_FUNCTION);
1481 break;
1482 default:
1483 UNREACHABLE();
1484 }
1485}
1486
1487
1488void ArgumentsAccessStub::GenerateReadElement(MacroAssembler* masm) {
1489 // The key is in rdx and the parameter count is in rax.
1490
1491 // The displacement is used for skipping the frame pointer on the
1492 // stack. It is the offset of the last parameter (if any) relative
1493 // to the frame pointer.
1494 static const int kDisplacement = 1 * kPointerSize;
1495
1496 // Check that the key is a smi.
1497 Label slow;
1498 __ JumpIfNotSmi(rdx, &slow);
1499
1500 // Check if the calling frame is an arguments adaptor frame.
1501 Label adaptor;
1502 __ movq(rbx, Operand(rbp, StandardFrameConstants::kCallerFPOffset));
1503 __ SmiCompare(Operand(rbx, StandardFrameConstants::kContextOffset),
1504 Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR));
1505 __ j(equal, &adaptor);
1506
1507 // Check index against formal parameters count limit passed in
1508 // through register rax. Use unsigned comparison to get negative
1509 // check for free.
1510 __ cmpq(rdx, rax);
1511 __ j(above_equal, &slow);
1512
1513 // Read the argument from the stack and return it.
1514 SmiIndex index = masm->SmiToIndex(rax, rax, kPointerSizeLog2);
1515 __ lea(rbx, Operand(rbp, index.reg, index.scale, 0));
1516 index = masm->SmiToNegativeIndex(rdx, rdx, kPointerSizeLog2);
1517 __ movq(rax, Operand(rbx, index.reg, index.scale, kDisplacement));
1518 __ Ret();
1519
1520 // Arguments adaptor case: Check index against actual arguments
1521 // limit found in the arguments adaptor frame. Use unsigned
1522 // comparison to get negative check for free.
1523 __ bind(&adaptor);
1524 __ movq(rcx, Operand(rbx, ArgumentsAdaptorFrameConstants::kLengthOffset));
1525 __ cmpq(rdx, rcx);
1526 __ j(above_equal, &slow);
1527
1528 // Read the argument from the stack and return it.
1529 index = masm->SmiToIndex(rax, rcx, kPointerSizeLog2);
1530 __ lea(rbx, Operand(rbx, index.reg, index.scale, 0));
1531 index = masm->SmiToNegativeIndex(rdx, rdx, kPointerSizeLog2);
1532 __ movq(rax, Operand(rbx, index.reg, index.scale, kDisplacement));
1533 __ Ret();
1534
1535 // Slow-case: Handle non-smi or out-of-bounds access to arguments
1536 // by calling the runtime system.
1537 __ bind(&slow);
1538 __ pop(rbx); // Return address.
1539 __ push(rdx);
1540 __ push(rbx);
1541 __ TailCallRuntime(Runtime::kGetArgumentsProperty, 1, 1);
1542}
1543
1544
1545void ArgumentsAccessStub::GenerateNewObject(MacroAssembler* masm) {
1546 // rsp[0] : return address
1547 // rsp[8] : number of parameters
1548 // rsp[16] : receiver displacement
1549 // rsp[24] : function
1550
1551 // The displacement is used for skipping the return address and the
1552 // frame pointer on the stack. It is the offset of the last
1553 // parameter (if any) relative to the frame pointer.
1554 static const int kDisplacement = 2 * kPointerSize;
1555
1556 // Check if the calling frame is an arguments adaptor frame.
1557 Label adaptor_frame, try_allocate, runtime;
1558 __ movq(rdx, Operand(rbp, StandardFrameConstants::kCallerFPOffset));
1559 __ SmiCompare(Operand(rdx, StandardFrameConstants::kContextOffset),
1560 Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR));
1561 __ j(equal, &adaptor_frame);
1562
1563 // Get the length from the frame.
1564 __ SmiToInteger32(rcx, Operand(rsp, 1 * kPointerSize));
1565 __ jmp(&try_allocate);
1566
1567 // Patch the arguments.length and the parameters pointer.
1568 __ bind(&adaptor_frame);
1569 __ SmiToInteger32(rcx,
1570 Operand(rdx,
1571 ArgumentsAdaptorFrameConstants::kLengthOffset));
1572 // Space on stack must already hold a smi.
1573 __ Integer32ToSmiField(Operand(rsp, 1 * kPointerSize), rcx);
1574 // Do not clobber the length index for the indexing operation since
1575 // it is used compute the size for allocation later.
1576 __ lea(rdx, Operand(rdx, rcx, times_pointer_size, kDisplacement));
1577 __ movq(Operand(rsp, 2 * kPointerSize), rdx);
1578
1579 // Try the new space allocation. Start out with computing the size of
1580 // the arguments object and the elements array.
1581 Label add_arguments_object;
1582 __ bind(&try_allocate);
1583 __ testl(rcx, rcx);
1584 __ j(zero, &add_arguments_object);
1585 __ leal(rcx, Operand(rcx, times_pointer_size, FixedArray::kHeaderSize));
1586 __ bind(&add_arguments_object);
1587 __ addl(rcx, Immediate(Heap::kArgumentsObjectSize));
1588
1589 // Do the allocation of both objects in one go.
1590 __ AllocateInNewSpace(rcx, rax, rdx, rbx, &runtime, TAG_OBJECT);
1591
1592 // Get the arguments boilerplate from the current (global) context.
1593 int offset = Context::SlotOffset(Context::ARGUMENTS_BOILERPLATE_INDEX);
1594 __ movq(rdi, Operand(rsi, Context::SlotOffset(Context::GLOBAL_INDEX)));
1595 __ movq(rdi, FieldOperand(rdi, GlobalObject::kGlobalContextOffset));
1596 __ movq(rdi, Operand(rdi, offset));
1597
1598 // Copy the JS object part.
1599 STATIC_ASSERT(JSObject::kHeaderSize == 3 * kPointerSize);
1600 __ movq(kScratchRegister, FieldOperand(rdi, 0 * kPointerSize));
1601 __ movq(rdx, FieldOperand(rdi, 1 * kPointerSize));
1602 __ movq(rbx, FieldOperand(rdi, 2 * kPointerSize));
1603 __ movq(FieldOperand(rax, 0 * kPointerSize), kScratchRegister);
1604 __ movq(FieldOperand(rax, 1 * kPointerSize), rdx);
1605 __ movq(FieldOperand(rax, 2 * kPointerSize), rbx);
1606
1607 // Setup the callee in-object property.
1608 ASSERT(Heap::arguments_callee_index == 0);
1609 __ movq(kScratchRegister, Operand(rsp, 3 * kPointerSize));
1610 __ movq(FieldOperand(rax, JSObject::kHeaderSize), kScratchRegister);
1611
1612 // Get the length (smi tagged) and set that as an in-object property too.
1613 ASSERT(Heap::arguments_length_index == 1);
1614 __ movq(rcx, Operand(rsp, 1 * kPointerSize));
1615 __ movq(FieldOperand(rax, JSObject::kHeaderSize + kPointerSize), rcx);
1616
1617 // If there are no actual arguments, we're done.
1618 Label done;
1619 __ SmiTest(rcx);
1620 __ j(zero, &done);
1621
1622 // Get the parameters pointer from the stack and untag the length.
1623 __ movq(rdx, Operand(rsp, 2 * kPointerSize));
1624
1625 // Setup the elements pointer in the allocated arguments object and
1626 // initialize the header in the elements fixed array.
1627 __ lea(rdi, Operand(rax, Heap::kArgumentsObjectSize));
1628 __ movq(FieldOperand(rax, JSObject::kElementsOffset), rdi);
1629 __ LoadRoot(kScratchRegister, Heap::kFixedArrayMapRootIndex);
1630 __ movq(FieldOperand(rdi, FixedArray::kMapOffset), kScratchRegister);
1631 __ movq(FieldOperand(rdi, FixedArray::kLengthOffset), rcx);
1632 __ SmiToInteger32(rcx, rcx); // Untag length for the loop below.
1633
1634 // Copy the fixed array slots.
1635 Label loop;
1636 __ bind(&loop);
1637 __ movq(kScratchRegister, Operand(rdx, -1 * kPointerSize)); // Skip receiver.
1638 __ movq(FieldOperand(rdi, FixedArray::kHeaderSize), kScratchRegister);
1639 __ addq(rdi, Immediate(kPointerSize));
1640 __ subq(rdx, Immediate(kPointerSize));
1641 __ decl(rcx);
1642 __ j(not_zero, &loop);
1643
1644 // Return and remove the on-stack parameters.
1645 __ bind(&done);
1646 __ ret(3 * kPointerSize);
1647
1648 // Do the runtime call to allocate the arguments object.
1649 __ bind(&runtime);
1650 __ TailCallRuntime(Runtime::kNewArgumentsFast, 3, 1);
1651}
1652
1653
1654void RegExpExecStub::Generate(MacroAssembler* masm) {
1655 // Just jump directly to runtime if native RegExp is not selected at compile
1656 // time or if regexp entry in generated code is turned off runtime switch or
1657 // at compilation.
1658#ifdef V8_INTERPRETED_REGEXP
1659 __ TailCallRuntime(Runtime::kRegExpExec, 4, 1);
1660#else // V8_INTERPRETED_REGEXP
1661 if (!FLAG_regexp_entry_native) {
1662 __ TailCallRuntime(Runtime::kRegExpExec, 4, 1);
1663 return;
1664 }
1665
1666 // Stack frame on entry.
1667 // esp[0]: return address
1668 // esp[8]: last_match_info (expected JSArray)
1669 // esp[16]: previous index
1670 // esp[24]: subject string
1671 // esp[32]: JSRegExp object
1672
1673 static const int kLastMatchInfoOffset = 1 * kPointerSize;
1674 static const int kPreviousIndexOffset = 2 * kPointerSize;
1675 static const int kSubjectOffset = 3 * kPointerSize;
1676 static const int kJSRegExpOffset = 4 * kPointerSize;
1677
1678 Label runtime;
1679
1680 // Ensure that a RegExp stack is allocated.
1681 ExternalReference address_of_regexp_stack_memory_address =
1682 ExternalReference::address_of_regexp_stack_memory_address();
1683 ExternalReference address_of_regexp_stack_memory_size =
1684 ExternalReference::address_of_regexp_stack_memory_size();
1685 __ movq(kScratchRegister, address_of_regexp_stack_memory_size);
1686 __ movq(kScratchRegister, Operand(kScratchRegister, 0));
1687 __ testq(kScratchRegister, kScratchRegister);
1688 __ j(zero, &runtime);
1689
1690
1691 // Check that the first argument is a JSRegExp object.
1692 __ movq(rax, Operand(rsp, kJSRegExpOffset));
1693 __ JumpIfSmi(rax, &runtime);
1694 __ CmpObjectType(rax, JS_REGEXP_TYPE, kScratchRegister);
1695 __ j(not_equal, &runtime);
1696 // Check that the RegExp has been compiled (data contains a fixed array).
1697 __ movq(rcx, FieldOperand(rax, JSRegExp::kDataOffset));
1698 if (FLAG_debug_code) {
1699 Condition is_smi = masm->CheckSmi(rcx);
1700 __ Check(NegateCondition(is_smi),
1701 "Unexpected type for RegExp data, FixedArray expected");
1702 __ CmpObjectType(rcx, FIXED_ARRAY_TYPE, kScratchRegister);
1703 __ Check(equal, "Unexpected type for RegExp data, FixedArray expected");
1704 }
1705
1706 // rcx: RegExp data (FixedArray)
1707 // Check the type of the RegExp. Only continue if type is JSRegExp::IRREGEXP.
1708 __ SmiToInteger32(rbx, FieldOperand(rcx, JSRegExp::kDataTagOffset));
1709 __ cmpl(rbx, Immediate(JSRegExp::IRREGEXP));
1710 __ j(not_equal, &runtime);
1711
1712 // rcx: RegExp data (FixedArray)
1713 // Check that the number of captures fit in the static offsets vector buffer.
1714 __ SmiToInteger32(rdx,
1715 FieldOperand(rcx, JSRegExp::kIrregexpCaptureCountOffset));
1716 // Calculate number of capture registers (number_of_captures + 1) * 2.
1717 __ leal(rdx, Operand(rdx, rdx, times_1, 2));
1718 // Check that the static offsets vector buffer is large enough.
1719 __ cmpl(rdx, Immediate(OffsetsVector::kStaticOffsetsVectorSize));
1720 __ j(above, &runtime);
1721
1722 // rcx: RegExp data (FixedArray)
1723 // rdx: Number of capture registers
1724 // Check that the second argument is a string.
1725 __ movq(rax, Operand(rsp, kSubjectOffset));
1726 __ JumpIfSmi(rax, &runtime);
1727 Condition is_string = masm->IsObjectStringType(rax, rbx, rbx);
1728 __ j(NegateCondition(is_string), &runtime);
1729
1730 // rax: Subject string.
1731 // rcx: RegExp data (FixedArray).
1732 // rdx: Number of capture registers.
1733 // Check that the third argument is a positive smi less than the string
1734 // length. A negative value will be greater (unsigned comparison).
1735 __ movq(rbx, Operand(rsp, kPreviousIndexOffset));
1736 __ JumpIfNotSmi(rbx, &runtime);
1737 __ SmiCompare(rbx, FieldOperand(rax, String::kLengthOffset));
1738 __ j(above_equal, &runtime);
1739
1740 // rcx: RegExp data (FixedArray)
1741 // rdx: Number of capture registers
1742 // Check that the fourth object is a JSArray object.
1743 __ movq(rax, Operand(rsp, kLastMatchInfoOffset));
1744 __ JumpIfSmi(rax, &runtime);
1745 __ CmpObjectType(rax, JS_ARRAY_TYPE, kScratchRegister);
1746 __ j(not_equal, &runtime);
1747 // Check that the JSArray is in fast case.
1748 __ movq(rbx, FieldOperand(rax, JSArray::kElementsOffset));
1749 __ movq(rax, FieldOperand(rbx, HeapObject::kMapOffset));
1750 __ Cmp(rax, Factory::fixed_array_map());
1751 __ j(not_equal, &runtime);
1752 // Check that the last match info has space for the capture registers and the
1753 // additional information. Ensure no overflow in add.
1754 STATIC_ASSERT(FixedArray::kMaxLength < kMaxInt - FixedArray::kLengthOffset);
1755 __ SmiToInteger32(rax, FieldOperand(rbx, FixedArray::kLengthOffset));
1756 __ addl(rdx, Immediate(RegExpImpl::kLastMatchOverhead));
1757 __ cmpl(rdx, rax);
1758 __ j(greater, &runtime);
1759
1760 // rcx: RegExp data (FixedArray)
1761 // Check the representation and encoding of the subject string.
Kristian Monsen0d5e1162010-09-30 15:31:59 +01001762 NearLabel seq_ascii_string, seq_two_byte_string, check_code;
Kristian Monsen80d68ea2010-09-08 11:05:35 +01001763 __ movq(rax, Operand(rsp, kSubjectOffset));
1764 __ movq(rbx, FieldOperand(rax, HeapObject::kMapOffset));
1765 __ movzxbl(rbx, FieldOperand(rbx, Map::kInstanceTypeOffset));
1766 // First check for flat two byte string.
1767 __ andb(rbx, Immediate(
1768 kIsNotStringMask | kStringRepresentationMask | kStringEncodingMask));
1769 STATIC_ASSERT((kStringTag | kSeqStringTag | kTwoByteStringTag) == 0);
1770 __ j(zero, &seq_two_byte_string);
1771 // Any other flat string must be a flat ascii string.
1772 __ testb(rbx, Immediate(kIsNotStringMask | kStringRepresentationMask));
1773 __ j(zero, &seq_ascii_string);
1774
1775 // Check for flat cons string.
1776 // A flat cons string is a cons string where the second part is the empty
1777 // string. In that case the subject string is just the first part of the cons
1778 // string. Also in this case the first part of the cons string is known to be
1779 // a sequential string or an external string.
1780 STATIC_ASSERT(kExternalStringTag !=0);
1781 STATIC_ASSERT((kConsStringTag & kExternalStringTag) == 0);
1782 __ testb(rbx, Immediate(kIsNotStringMask | kExternalStringTag));
1783 __ j(not_zero, &runtime);
1784 // String is a cons string.
1785 __ movq(rdx, FieldOperand(rax, ConsString::kSecondOffset));
1786 __ Cmp(rdx, Factory::empty_string());
1787 __ j(not_equal, &runtime);
1788 __ movq(rax, FieldOperand(rax, ConsString::kFirstOffset));
1789 __ movq(rbx, FieldOperand(rax, HeapObject::kMapOffset));
1790 // String is a cons string with empty second part.
1791 // rax: first part of cons string.
1792 // rbx: map of first part of cons string.
1793 // Is first part a flat two byte string?
1794 __ testb(FieldOperand(rbx, Map::kInstanceTypeOffset),
1795 Immediate(kStringRepresentationMask | kStringEncodingMask));
1796 STATIC_ASSERT((kSeqStringTag | kTwoByteStringTag) == 0);
1797 __ j(zero, &seq_two_byte_string);
1798 // Any other flat string must be ascii.
1799 __ testb(FieldOperand(rbx, Map::kInstanceTypeOffset),
1800 Immediate(kStringRepresentationMask));
1801 __ j(not_zero, &runtime);
1802
1803 __ bind(&seq_ascii_string);
1804 // rax: subject string (sequential ascii)
1805 // rcx: RegExp data (FixedArray)
1806 __ movq(r11, FieldOperand(rcx, JSRegExp::kDataAsciiCodeOffset));
1807 __ Set(rdi, 1); // Type is ascii.
1808 __ jmp(&check_code);
1809
1810 __ bind(&seq_two_byte_string);
1811 // rax: subject string (flat two-byte)
1812 // rcx: RegExp data (FixedArray)
1813 __ movq(r11, FieldOperand(rcx, JSRegExp::kDataUC16CodeOffset));
1814 __ Set(rdi, 0); // Type is two byte.
1815
1816 __ bind(&check_code);
1817 // Check that the irregexp code has been generated for the actual string
1818 // encoding. If it has, the field contains a code object otherwise it contains
1819 // the hole.
1820 __ CmpObjectType(r11, CODE_TYPE, kScratchRegister);
1821 __ j(not_equal, &runtime);
1822
1823 // rax: subject string
1824 // rdi: encoding of subject string (1 if ascii, 0 if two_byte);
1825 // r11: code
1826 // Load used arguments before starting to push arguments for call to native
1827 // RegExp code to avoid handling changing stack height.
1828 __ SmiToInteger64(rbx, Operand(rsp, kPreviousIndexOffset));
1829
1830 // rax: subject string
1831 // rbx: previous index
1832 // rdi: encoding of subject string (1 if ascii 0 if two_byte);
1833 // r11: code
1834 // All checks done. Now push arguments for native regexp code.
1835 __ IncrementCounter(&Counters::regexp_entry_native, 1);
1836
1837 // rsi is caller save on Windows and used to pass parameter on Linux.
1838 __ push(rsi);
1839
1840 static const int kRegExpExecuteArguments = 7;
1841 __ PrepareCallCFunction(kRegExpExecuteArguments);
1842 int argument_slots_on_stack =
1843 masm->ArgumentStackSlotsForCFunctionCall(kRegExpExecuteArguments);
1844
1845 // Argument 7: Indicate that this is a direct call from JavaScript.
1846 __ movq(Operand(rsp, (argument_slots_on_stack - 1) * kPointerSize),
1847 Immediate(1));
1848
1849 // Argument 6: Start (high end) of backtracking stack memory area.
1850 __ movq(kScratchRegister, address_of_regexp_stack_memory_address);
1851 __ movq(r9, Operand(kScratchRegister, 0));
1852 __ movq(kScratchRegister, address_of_regexp_stack_memory_size);
1853 __ addq(r9, Operand(kScratchRegister, 0));
1854 // Argument 6 passed in r9 on Linux and on the stack on Windows.
1855#ifdef _WIN64
1856 __ movq(Operand(rsp, (argument_slots_on_stack - 2) * kPointerSize), r9);
1857#endif
1858
1859 // Argument 5: static offsets vector buffer.
1860 __ movq(r8, ExternalReference::address_of_static_offsets_vector());
1861 // Argument 5 passed in r8 on Linux and on the stack on Windows.
1862#ifdef _WIN64
1863 __ movq(Operand(rsp, (argument_slots_on_stack - 3) * kPointerSize), r8);
1864#endif
1865
1866 // First four arguments are passed in registers on both Linux and Windows.
1867#ifdef _WIN64
1868 Register arg4 = r9;
1869 Register arg3 = r8;
1870 Register arg2 = rdx;
1871 Register arg1 = rcx;
1872#else
1873 Register arg4 = rcx;
1874 Register arg3 = rdx;
1875 Register arg2 = rsi;
1876 Register arg1 = rdi;
1877#endif
1878
1879 // Keep track on aliasing between argX defined above and the registers used.
1880 // rax: subject string
1881 // rbx: previous index
1882 // rdi: encoding of subject string (1 if ascii 0 if two_byte);
1883 // r11: code
1884
1885 // Argument 4: End of string data
1886 // Argument 3: Start of string data
Kristian Monsen0d5e1162010-09-30 15:31:59 +01001887 NearLabel setup_two_byte, setup_rest;
Kristian Monsen80d68ea2010-09-08 11:05:35 +01001888 __ testb(rdi, rdi);
1889 __ j(zero, &setup_two_byte);
1890 __ SmiToInteger32(rdi, FieldOperand(rax, String::kLengthOffset));
1891 __ lea(arg4, FieldOperand(rax, rdi, times_1, SeqAsciiString::kHeaderSize));
1892 __ lea(arg3, FieldOperand(rax, rbx, times_1, SeqAsciiString::kHeaderSize));
1893 __ jmp(&setup_rest);
1894 __ bind(&setup_two_byte);
1895 __ SmiToInteger32(rdi, FieldOperand(rax, String::kLengthOffset));
1896 __ lea(arg4, FieldOperand(rax, rdi, times_2, SeqTwoByteString::kHeaderSize));
1897 __ lea(arg3, FieldOperand(rax, rbx, times_2, SeqTwoByteString::kHeaderSize));
1898
1899 __ bind(&setup_rest);
1900 // Argument 2: Previous index.
1901 __ movq(arg2, rbx);
1902
1903 // Argument 1: Subject string.
1904 __ movq(arg1, rax);
1905
1906 // Locate the code entry and call it.
1907 __ addq(r11, Immediate(Code::kHeaderSize - kHeapObjectTag));
1908 __ CallCFunction(r11, kRegExpExecuteArguments);
1909
1910 // rsi is caller save, as it is used to pass parameter.
1911 __ pop(rsi);
1912
1913 // Check the result.
Kristian Monsen0d5e1162010-09-30 15:31:59 +01001914 NearLabel success;
Kristian Monsen80d68ea2010-09-08 11:05:35 +01001915 __ cmpl(rax, Immediate(NativeRegExpMacroAssembler::SUCCESS));
1916 __ j(equal, &success);
Kristian Monsen0d5e1162010-09-30 15:31:59 +01001917 NearLabel failure;
Kristian Monsen80d68ea2010-09-08 11:05:35 +01001918 __ cmpl(rax, Immediate(NativeRegExpMacroAssembler::FAILURE));
1919 __ j(equal, &failure);
1920 __ cmpl(rax, Immediate(NativeRegExpMacroAssembler::EXCEPTION));
1921 // If not exception it can only be retry. Handle that in the runtime system.
1922 __ j(not_equal, &runtime);
1923 // Result must now be exception. If there is no pending exception already a
1924 // stack overflow (on the backtrack stack) was detected in RegExp code but
1925 // haven't created the exception yet. Handle that in the runtime system.
1926 // TODO(592): Rerunning the RegExp to get the stack overflow exception.
1927 ExternalReference pending_exception_address(Top::k_pending_exception_address);
1928 __ movq(kScratchRegister, pending_exception_address);
1929 __ Cmp(kScratchRegister, Factory::the_hole_value());
1930 __ j(equal, &runtime);
1931 __ bind(&failure);
1932 // For failure and exception return null.
1933 __ Move(rax, Factory::null_value());
1934 __ ret(4 * kPointerSize);
1935
1936 // Load RegExp data.
1937 __ bind(&success);
1938 __ movq(rax, Operand(rsp, kJSRegExpOffset));
1939 __ movq(rcx, FieldOperand(rax, JSRegExp::kDataOffset));
1940 __ SmiToInteger32(rax,
1941 FieldOperand(rcx, JSRegExp::kIrregexpCaptureCountOffset));
1942 // Calculate number of capture registers (number_of_captures + 1) * 2.
1943 __ leal(rdx, Operand(rax, rax, times_1, 2));
1944
1945 // rdx: Number of capture registers
1946 // Load last_match_info which is still known to be a fast case JSArray.
1947 __ movq(rax, Operand(rsp, kLastMatchInfoOffset));
1948 __ movq(rbx, FieldOperand(rax, JSArray::kElementsOffset));
1949
1950 // rbx: last_match_info backing store (FixedArray)
1951 // rdx: number of capture registers
1952 // Store the capture count.
1953 __ Integer32ToSmi(kScratchRegister, rdx);
1954 __ movq(FieldOperand(rbx, RegExpImpl::kLastCaptureCountOffset),
1955 kScratchRegister);
1956 // Store last subject and last input.
1957 __ movq(rax, Operand(rsp, kSubjectOffset));
1958 __ movq(FieldOperand(rbx, RegExpImpl::kLastSubjectOffset), rax);
1959 __ movq(rcx, rbx);
1960 __ RecordWrite(rcx, RegExpImpl::kLastSubjectOffset, rax, rdi);
1961 __ movq(rax, Operand(rsp, kSubjectOffset));
1962 __ movq(FieldOperand(rbx, RegExpImpl::kLastInputOffset), rax);
1963 __ movq(rcx, rbx);
1964 __ RecordWrite(rcx, RegExpImpl::kLastInputOffset, rax, rdi);
1965
1966 // Get the static offsets vector filled by the native regexp code.
1967 __ movq(rcx, ExternalReference::address_of_static_offsets_vector());
1968
1969 // rbx: last_match_info backing store (FixedArray)
1970 // rcx: offsets vector
1971 // rdx: number of capture registers
Kristian Monsen0d5e1162010-09-30 15:31:59 +01001972 NearLabel next_capture, done;
Kristian Monsen80d68ea2010-09-08 11:05:35 +01001973 // Capture register counter starts from number of capture registers and
1974 // counts down until wraping after zero.
1975 __ bind(&next_capture);
1976 __ subq(rdx, Immediate(1));
1977 __ j(negative, &done);
1978 // Read the value from the static offsets vector buffer and make it a smi.
1979 __ movl(rdi, Operand(rcx, rdx, times_int_size, 0));
Kristian Monsen0d5e1162010-09-30 15:31:59 +01001980 __ Integer32ToSmi(rdi, rdi);
Kristian Monsen80d68ea2010-09-08 11:05:35 +01001981 // Store the smi value in the last match info.
1982 __ movq(FieldOperand(rbx,
1983 rdx,
1984 times_pointer_size,
1985 RegExpImpl::kFirstCaptureOffset),
1986 rdi);
1987 __ jmp(&next_capture);
1988 __ bind(&done);
1989
1990 // Return last match info.
1991 __ movq(rax, Operand(rsp, kLastMatchInfoOffset));
1992 __ ret(4 * kPointerSize);
1993
1994 // Do the runtime call to execute the regexp.
1995 __ bind(&runtime);
1996 __ TailCallRuntime(Runtime::kRegExpExec, 4, 1);
1997#endif // V8_INTERPRETED_REGEXP
1998}
1999
2000
2001void NumberToStringStub::GenerateLookupNumberStringCache(MacroAssembler* masm,
2002 Register object,
2003 Register result,
2004 Register scratch1,
2005 Register scratch2,
2006 bool object_is_smi,
2007 Label* not_found) {
2008 // Use of registers. Register result is used as a temporary.
2009 Register number_string_cache = result;
2010 Register mask = scratch1;
2011 Register scratch = scratch2;
2012
2013 // Load the number string cache.
2014 __ LoadRoot(number_string_cache, Heap::kNumberStringCacheRootIndex);
2015
2016 // Make the hash mask from the length of the number string cache. It
2017 // contains two elements (number and string) for each cache entry.
2018 __ SmiToInteger32(
2019 mask, FieldOperand(number_string_cache, FixedArray::kLengthOffset));
2020 __ shrl(mask, Immediate(1));
2021 __ subq(mask, Immediate(1)); // Make mask.
2022
2023 // Calculate the entry in the number string cache. The hash value in the
2024 // number string cache for smis is just the smi value, and the hash for
2025 // doubles is the xor of the upper and lower words. See
2026 // Heap::GetNumberStringCache.
2027 Label is_smi;
2028 Label load_result_from_cache;
2029 if (!object_is_smi) {
2030 __ JumpIfSmi(object, &is_smi);
2031 __ CheckMap(object, Factory::heap_number_map(), not_found, true);
2032
2033 STATIC_ASSERT(8 == kDoubleSize);
2034 __ movl(scratch, FieldOperand(object, HeapNumber::kValueOffset + 4));
2035 __ xor_(scratch, FieldOperand(object, HeapNumber::kValueOffset));
2036 GenerateConvertHashCodeToIndex(masm, scratch, mask);
2037
2038 Register index = scratch;
2039 Register probe = mask;
2040 __ movq(probe,
2041 FieldOperand(number_string_cache,
2042 index,
2043 times_1,
2044 FixedArray::kHeaderSize));
2045 __ JumpIfSmi(probe, not_found);
2046 ASSERT(CpuFeatures::IsSupported(SSE2));
2047 CpuFeatures::Scope fscope(SSE2);
2048 __ movsd(xmm0, FieldOperand(object, HeapNumber::kValueOffset));
2049 __ movsd(xmm1, FieldOperand(probe, HeapNumber::kValueOffset));
2050 __ ucomisd(xmm0, xmm1);
2051 __ j(parity_even, not_found); // Bail out if NaN is involved.
2052 __ j(not_equal, not_found); // The cache did not contain this value.
2053 __ jmp(&load_result_from_cache);
2054 }
2055
2056 __ bind(&is_smi);
2057 __ SmiToInteger32(scratch, object);
2058 GenerateConvertHashCodeToIndex(masm, scratch, mask);
2059
2060 Register index = scratch;
2061 // Check if the entry is the smi we are looking for.
2062 __ cmpq(object,
2063 FieldOperand(number_string_cache,
2064 index,
2065 times_1,
2066 FixedArray::kHeaderSize));
2067 __ j(not_equal, not_found);
2068
2069 // Get the result from the cache.
2070 __ bind(&load_result_from_cache);
2071 __ movq(result,
2072 FieldOperand(number_string_cache,
2073 index,
2074 times_1,
2075 FixedArray::kHeaderSize + kPointerSize));
2076 __ IncrementCounter(&Counters::number_to_string_native, 1);
2077}
2078
2079
2080void NumberToStringStub::GenerateConvertHashCodeToIndex(MacroAssembler* masm,
2081 Register hash,
2082 Register mask) {
2083 __ and_(hash, mask);
2084 // Each entry in string cache consists of two pointer sized fields,
2085 // but times_twice_pointer_size (multiplication by 16) scale factor
2086 // is not supported by addrmode on x64 platform.
2087 // So we have to premultiply entry index before lookup.
2088 __ shl(hash, Immediate(kPointerSizeLog2 + 1));
2089}
2090
2091
2092void NumberToStringStub::Generate(MacroAssembler* masm) {
2093 Label runtime;
2094
2095 __ movq(rbx, Operand(rsp, kPointerSize));
2096
2097 // Generate code to lookup number in the number string cache.
2098 GenerateLookupNumberStringCache(masm, rbx, rax, r8, r9, false, &runtime);
2099 __ ret(1 * kPointerSize);
2100
2101 __ bind(&runtime);
2102 // Handle number to string in the runtime system if not found in the cache.
2103 __ TailCallRuntime(Runtime::kNumberToStringSkipCache, 1, 1);
2104}
2105
2106
2107static int NegativeComparisonResult(Condition cc) {
2108 ASSERT(cc != equal);
2109 ASSERT((cc == less) || (cc == less_equal)
2110 || (cc == greater) || (cc == greater_equal));
2111 return (cc == greater || cc == greater_equal) ? LESS : GREATER;
2112}
2113
2114
2115void CompareStub::Generate(MacroAssembler* masm) {
2116 ASSERT(lhs_.is(no_reg) && rhs_.is(no_reg));
2117
2118 Label check_unequal_objects, done;
Kristian Monsen0d5e1162010-09-30 15:31:59 +01002119
2120 // Compare two smis if required.
2121 if (include_smi_compare_) {
2122 Label non_smi, smi_done;
2123 __ JumpIfNotBothSmi(rax, rdx, &non_smi);
2124 __ subq(rdx, rax);
2125 __ j(no_overflow, &smi_done);
Ben Murdochf87a2032010-10-22 12:50:53 +01002126 __ not_(rdx); // Correct sign in case of overflow. rdx cannot be 0 here.
Kristian Monsen0d5e1162010-09-30 15:31:59 +01002127 __ bind(&smi_done);
2128 __ movq(rax, rdx);
2129 __ ret(0);
2130 __ bind(&non_smi);
2131 } else if (FLAG_debug_code) {
2132 Label ok;
2133 __ JumpIfNotSmi(rdx, &ok);
2134 __ JumpIfNotSmi(rax, &ok);
2135 __ Abort("CompareStub: smi operands");
2136 __ bind(&ok);
2137 }
2138
Kristian Monsen80d68ea2010-09-08 11:05:35 +01002139 // The compare stub returns a positive, negative, or zero 64-bit integer
2140 // value in rax, corresponding to result of comparing the two inputs.
2141 // NOTICE! This code is only reached after a smi-fast-case check, so
2142 // it is certain that at least one operand isn't a smi.
2143
2144 // Two identical objects are equal unless they are both NaN or undefined.
2145 {
Kristian Monsen0d5e1162010-09-30 15:31:59 +01002146 NearLabel not_identical;
Kristian Monsen80d68ea2010-09-08 11:05:35 +01002147 __ cmpq(rax, rdx);
2148 __ j(not_equal, &not_identical);
2149
2150 if (cc_ != equal) {
2151 // Check for undefined. undefined OP undefined is false even though
2152 // undefined == undefined.
Kristian Monsen0d5e1162010-09-30 15:31:59 +01002153 NearLabel check_for_nan;
Kristian Monsen80d68ea2010-09-08 11:05:35 +01002154 __ CompareRoot(rdx, Heap::kUndefinedValueRootIndex);
2155 __ j(not_equal, &check_for_nan);
2156 __ Set(rax, NegativeComparisonResult(cc_));
2157 __ ret(0);
2158 __ bind(&check_for_nan);
2159 }
2160
2161 // Test for NaN. Sadly, we can't just compare to Factory::nan_value(),
2162 // so we do the second best thing - test it ourselves.
2163 // Note: if cc_ != equal, never_nan_nan_ is not used.
2164 // We cannot set rax to EQUAL until just before return because
2165 // rax must be unchanged on jump to not_identical.
2166
2167 if (never_nan_nan_ && (cc_ == equal)) {
2168 __ Set(rax, EQUAL);
2169 __ ret(0);
2170 } else {
Kristian Monsen0d5e1162010-09-30 15:31:59 +01002171 NearLabel heap_number;
Kristian Monsen80d68ea2010-09-08 11:05:35 +01002172 // If it's not a heap number, then return equal for (in)equality operator.
2173 __ Cmp(FieldOperand(rdx, HeapObject::kMapOffset),
2174 Factory::heap_number_map());
2175 __ j(equal, &heap_number);
2176 if (cc_ != equal) {
2177 // Call runtime on identical JSObjects. Otherwise return equal.
2178 __ CmpObjectType(rax, FIRST_JS_OBJECT_TYPE, rcx);
2179 __ j(above_equal, &not_identical);
2180 }
2181 __ Set(rax, EQUAL);
2182 __ ret(0);
2183
2184 __ bind(&heap_number);
2185 // It is a heap number, so return equal if it's not NaN.
2186 // For NaN, return 1 for every condition except greater and
2187 // greater-equal. Return -1 for them, so the comparison yields
2188 // false for all conditions except not-equal.
2189 __ Set(rax, EQUAL);
2190 __ movsd(xmm0, FieldOperand(rdx, HeapNumber::kValueOffset));
2191 __ ucomisd(xmm0, xmm0);
2192 __ setcc(parity_even, rax);
2193 // rax is 0 for equal non-NaN heapnumbers, 1 for NaNs.
2194 if (cc_ == greater_equal || cc_ == greater) {
2195 __ neg(rax);
2196 }
2197 __ ret(0);
2198 }
2199
2200 __ bind(&not_identical);
2201 }
2202
2203 if (cc_ == equal) { // Both strict and non-strict.
2204 Label slow; // Fallthrough label.
2205
2206 // If we're doing a strict equality comparison, we don't have to do
2207 // type conversion, so we generate code to do fast comparison for objects
2208 // and oddballs. Non-smi numbers and strings still go through the usual
2209 // slow-case code.
2210 if (strict_) {
2211 // If either is a Smi (we know that not both are), then they can only
2212 // be equal if the other is a HeapNumber. If so, use the slow case.
2213 {
2214 Label not_smis;
2215 __ SelectNonSmi(rbx, rax, rdx, &not_smis);
2216
2217 // Check if the non-smi operand is a heap number.
2218 __ Cmp(FieldOperand(rbx, HeapObject::kMapOffset),
2219 Factory::heap_number_map());
2220 // If heap number, handle it in the slow case.
2221 __ j(equal, &slow);
2222 // Return non-equal. ebx (the lower half of rbx) is not zero.
2223 __ movq(rax, rbx);
2224 __ ret(0);
2225
2226 __ bind(&not_smis);
2227 }
2228
2229 // If either operand is a JSObject or an oddball value, then they are not
2230 // equal since their pointers are different
2231 // There is no test for undetectability in strict equality.
2232
2233 // If the first object is a JS object, we have done pointer comparison.
2234 STATIC_ASSERT(LAST_TYPE == JS_FUNCTION_TYPE);
Kristian Monsen0d5e1162010-09-30 15:31:59 +01002235 NearLabel first_non_object;
Kristian Monsen80d68ea2010-09-08 11:05:35 +01002236 __ CmpObjectType(rax, FIRST_JS_OBJECT_TYPE, rcx);
2237 __ j(below, &first_non_object);
2238 // Return non-zero (eax (not rax) is not zero)
2239 Label return_not_equal;
2240 STATIC_ASSERT(kHeapObjectTag != 0);
2241 __ bind(&return_not_equal);
2242 __ ret(0);
2243
2244 __ bind(&first_non_object);
2245 // Check for oddballs: true, false, null, undefined.
2246 __ CmpInstanceType(rcx, ODDBALL_TYPE);
2247 __ j(equal, &return_not_equal);
2248
2249 __ CmpObjectType(rdx, FIRST_JS_OBJECT_TYPE, rcx);
2250 __ j(above_equal, &return_not_equal);
2251
2252 // Check for oddballs: true, false, null, undefined.
2253 __ CmpInstanceType(rcx, ODDBALL_TYPE);
2254 __ j(equal, &return_not_equal);
2255
2256 // Fall through to the general case.
2257 }
2258 __ bind(&slow);
2259 }
2260
2261 // Generate the number comparison code.
2262 if (include_number_compare_) {
2263 Label non_number_comparison;
Kristian Monsen0d5e1162010-09-30 15:31:59 +01002264 NearLabel unordered;
Kristian Monsen80d68ea2010-09-08 11:05:35 +01002265 FloatingPointHelper::LoadSSE2UnknownOperands(masm, &non_number_comparison);
2266 __ xorl(rax, rax);
2267 __ xorl(rcx, rcx);
2268 __ ucomisd(xmm0, xmm1);
2269
2270 // Don't base result on EFLAGS when a NaN is involved.
2271 __ j(parity_even, &unordered);
2272 // Return a result of -1, 0, or 1, based on EFLAGS.
2273 __ setcc(above, rax);
2274 __ setcc(below, rcx);
2275 __ subq(rax, rcx);
2276 __ ret(0);
2277
2278 // If one of the numbers was NaN, then the result is always false.
2279 // The cc is never not-equal.
2280 __ bind(&unordered);
2281 ASSERT(cc_ != not_equal);
2282 if (cc_ == less || cc_ == less_equal) {
2283 __ Set(rax, 1);
2284 } else {
2285 __ Set(rax, -1);
2286 }
2287 __ ret(0);
2288
2289 // The number comparison code did not provide a valid result.
2290 __ bind(&non_number_comparison);
2291 }
2292
2293 // Fast negative check for symbol-to-symbol equality.
2294 Label check_for_strings;
2295 if (cc_ == equal) {
2296 BranchIfNonSymbol(masm, &check_for_strings, rax, kScratchRegister);
2297 BranchIfNonSymbol(masm, &check_for_strings, rdx, kScratchRegister);
2298
2299 // We've already checked for object identity, so if both operands
2300 // are symbols they aren't equal. Register eax (not rax) already holds a
2301 // non-zero value, which indicates not equal, so just return.
2302 __ ret(0);
2303 }
2304
2305 __ bind(&check_for_strings);
2306
2307 __ JumpIfNotBothSequentialAsciiStrings(
2308 rdx, rax, rcx, rbx, &check_unequal_objects);
2309
2310 // Inline comparison of ascii strings.
2311 StringCompareStub::GenerateCompareFlatAsciiStrings(masm,
2312 rdx,
2313 rax,
2314 rcx,
2315 rbx,
2316 rdi,
2317 r8);
2318
2319#ifdef DEBUG
2320 __ Abort("Unexpected fall-through from string comparison");
2321#endif
2322
2323 __ bind(&check_unequal_objects);
2324 if (cc_ == equal && !strict_) {
2325 // Not strict equality. Objects are unequal if
2326 // they are both JSObjects and not undetectable,
2327 // and their pointers are different.
Kristian Monsen0d5e1162010-09-30 15:31:59 +01002328 NearLabel not_both_objects, return_unequal;
Kristian Monsen80d68ea2010-09-08 11:05:35 +01002329 // At most one is a smi, so we can test for smi by adding the two.
2330 // A smi plus a heap object has the low bit set, a heap object plus
2331 // a heap object has the low bit clear.
2332 STATIC_ASSERT(kSmiTag == 0);
2333 STATIC_ASSERT(kSmiTagMask == 1);
2334 __ lea(rcx, Operand(rax, rdx, times_1, 0));
2335 __ testb(rcx, Immediate(kSmiTagMask));
2336 __ j(not_zero, &not_both_objects);
2337 __ CmpObjectType(rax, FIRST_JS_OBJECT_TYPE, rbx);
2338 __ j(below, &not_both_objects);
2339 __ CmpObjectType(rdx, FIRST_JS_OBJECT_TYPE, rcx);
2340 __ j(below, &not_both_objects);
2341 __ testb(FieldOperand(rbx, Map::kBitFieldOffset),
2342 Immediate(1 << Map::kIsUndetectable));
2343 __ j(zero, &return_unequal);
2344 __ testb(FieldOperand(rcx, Map::kBitFieldOffset),
2345 Immediate(1 << Map::kIsUndetectable));
2346 __ j(zero, &return_unequal);
2347 // The objects are both undetectable, so they both compare as the value
2348 // undefined, and are equal.
2349 __ Set(rax, EQUAL);
2350 __ bind(&return_unequal);
2351 // Return non-equal by returning the non-zero object pointer in eax,
2352 // or return equal if we fell through to here.
2353 __ ret(0);
2354 __ bind(&not_both_objects);
2355 }
2356
2357 // Push arguments below the return address to prepare jump to builtin.
2358 __ pop(rcx);
2359 __ push(rdx);
2360 __ push(rax);
2361
2362 // Figure out which native to call and setup the arguments.
2363 Builtins::JavaScript builtin;
2364 if (cc_ == equal) {
2365 builtin = strict_ ? Builtins::STRICT_EQUALS : Builtins::EQUALS;
2366 } else {
2367 builtin = Builtins::COMPARE;
2368 __ Push(Smi::FromInt(NegativeComparisonResult(cc_)));
2369 }
2370
2371 // Restore return address on the stack.
2372 __ push(rcx);
2373
2374 // Call the native; it returns -1 (less), 0 (equal), or 1 (greater)
2375 // tagged as a small integer.
2376 __ InvokeBuiltin(builtin, JUMP_FUNCTION);
2377}
2378
2379
2380void CompareStub::BranchIfNonSymbol(MacroAssembler* masm,
2381 Label* label,
2382 Register object,
2383 Register scratch) {
2384 __ JumpIfSmi(object, label);
2385 __ movq(scratch, FieldOperand(object, HeapObject::kMapOffset));
2386 __ movzxbq(scratch,
2387 FieldOperand(scratch, Map::kInstanceTypeOffset));
2388 // Ensure that no non-strings have the symbol bit set.
2389 STATIC_ASSERT(LAST_TYPE < kNotStringTag + kIsSymbolMask);
2390 STATIC_ASSERT(kSymbolTag != 0);
2391 __ testb(scratch, Immediate(kIsSymbolMask));
2392 __ j(zero, label);
2393}
2394
2395
2396void StackCheckStub::Generate(MacroAssembler* masm) {
Ben Murdochf87a2032010-10-22 12:50:53 +01002397 __ TailCallRuntime(Runtime::kStackGuard, 0, 1);
Kristian Monsen80d68ea2010-09-08 11:05:35 +01002398}
2399
2400
2401void CallFunctionStub::Generate(MacroAssembler* masm) {
2402 Label slow;
2403
2404 // If the receiver might be a value (string, number or boolean) check for this
2405 // and box it if it is.
2406 if (ReceiverMightBeValue()) {
2407 // Get the receiver from the stack.
2408 // +1 ~ return address
2409 Label receiver_is_value, receiver_is_js_object;
2410 __ movq(rax, Operand(rsp, (argc_ + 1) * kPointerSize));
2411
2412 // Check if receiver is a smi (which is a number value).
2413 __ JumpIfSmi(rax, &receiver_is_value);
2414
2415 // Check if the receiver is a valid JS object.
2416 __ CmpObjectType(rax, FIRST_JS_OBJECT_TYPE, rdi);
2417 __ j(above_equal, &receiver_is_js_object);
2418
2419 // Call the runtime to box the value.
2420 __ bind(&receiver_is_value);
2421 __ EnterInternalFrame();
2422 __ push(rax);
2423 __ InvokeBuiltin(Builtins::TO_OBJECT, CALL_FUNCTION);
2424 __ LeaveInternalFrame();
2425 __ movq(Operand(rsp, (argc_ + 1) * kPointerSize), rax);
2426
2427 __ bind(&receiver_is_js_object);
2428 }
2429
2430 // Get the function to call from the stack.
2431 // +2 ~ receiver, return address
2432 __ movq(rdi, Operand(rsp, (argc_ + 2) * kPointerSize));
2433
2434 // Check that the function really is a JavaScript function.
2435 __ JumpIfSmi(rdi, &slow);
2436 // Goto slow case if we do not have a function.
2437 __ CmpObjectType(rdi, JS_FUNCTION_TYPE, rcx);
2438 __ j(not_equal, &slow);
2439
2440 // Fast-case: Just invoke the function.
2441 ParameterCount actual(argc_);
2442 __ InvokeFunction(rdi, actual, JUMP_FUNCTION);
2443
2444 // Slow-case: Non-function called.
2445 __ bind(&slow);
2446 // CALL_NON_FUNCTION expects the non-function callee as receiver (instead
2447 // of the original receiver from the call site).
2448 __ movq(Operand(rsp, (argc_ + 1) * kPointerSize), rdi);
2449 __ Set(rax, argc_);
2450 __ Set(rbx, 0);
2451 __ GetBuiltinEntry(rdx, Builtins::CALL_NON_FUNCTION);
2452 Handle<Code> adaptor(Builtins::builtin(Builtins::ArgumentsAdaptorTrampoline));
2453 __ Jump(adaptor, RelocInfo::CODE_TARGET);
2454}
2455
2456
2457void CEntryStub::GenerateThrowTOS(MacroAssembler* masm) {
2458 // Check that stack should contain next handler, frame pointer, state and
2459 // return address in that order.
2460 STATIC_ASSERT(StackHandlerConstants::kFPOffset + kPointerSize ==
2461 StackHandlerConstants::kStateOffset);
2462 STATIC_ASSERT(StackHandlerConstants::kStateOffset + kPointerSize ==
2463 StackHandlerConstants::kPCOffset);
2464
2465 ExternalReference handler_address(Top::k_handler_address);
2466 __ movq(kScratchRegister, handler_address);
2467 __ movq(rsp, Operand(kScratchRegister, 0));
2468 // get next in chain
2469 __ pop(rcx);
2470 __ movq(Operand(kScratchRegister, 0), rcx);
2471 __ pop(rbp); // pop frame pointer
2472 __ pop(rdx); // remove state
2473
2474 // Before returning we restore the context from the frame pointer if not NULL.
2475 // The frame pointer is NULL in the exception handler of a JS entry frame.
2476 __ xor_(rsi, rsi); // tentatively set context pointer to NULL
Kristian Monsen0d5e1162010-09-30 15:31:59 +01002477 NearLabel skip;
Kristian Monsen80d68ea2010-09-08 11:05:35 +01002478 __ cmpq(rbp, Immediate(0));
2479 __ j(equal, &skip);
2480 __ movq(rsi, Operand(rbp, StandardFrameConstants::kContextOffset));
2481 __ bind(&skip);
2482 __ ret(0);
2483}
2484
2485
2486void ApiGetterEntryStub::Generate(MacroAssembler* masm) {
2487 Label empty_result;
2488 Label prologue;
2489 Label promote_scheduled_exception;
2490 __ EnterApiExitFrame(kStackSpace, 0);
2491 ASSERT_EQ(kArgc, 4);
2492#ifdef _WIN64
2493 // All the parameters should be set up by a caller.
2494#else
2495 // Set 1st parameter register with property name.
2496 __ movq(rsi, rdx);
2497 // Second parameter register rdi should be set with pointer to AccessorInfo
2498 // by a caller.
2499#endif
2500 // Call the api function!
2501 __ movq(rax,
2502 reinterpret_cast<int64_t>(fun()->address()),
2503 RelocInfo::RUNTIME_ENTRY);
2504 __ call(rax);
2505 // Check if the function scheduled an exception.
2506 ExternalReference scheduled_exception_address =
2507 ExternalReference::scheduled_exception_address();
2508 __ movq(rsi, scheduled_exception_address);
2509 __ Cmp(Operand(rsi, 0), Factory::the_hole_value());
2510 __ j(not_equal, &promote_scheduled_exception);
2511#ifdef _WIN64
2512 // rax keeps a pointer to v8::Handle, unpack it.
2513 __ movq(rax, Operand(rax, 0));
2514#endif
2515 // Check if the result handle holds 0.
2516 __ testq(rax, rax);
2517 __ j(zero, &empty_result);
2518 // It was non-zero. Dereference to get the result value.
2519 __ movq(rax, Operand(rax, 0));
2520 __ bind(&prologue);
2521 __ LeaveExitFrame();
2522 __ ret(0);
2523 __ bind(&promote_scheduled_exception);
2524 __ TailCallRuntime(Runtime::kPromoteScheduledException, 0, 1);
2525 __ bind(&empty_result);
2526 // It was zero; the result is undefined.
2527 __ Move(rax, Factory::undefined_value());
2528 __ jmp(&prologue);
2529}
2530
2531
2532void CEntryStub::GenerateCore(MacroAssembler* masm,
2533 Label* throw_normal_exception,
2534 Label* throw_termination_exception,
2535 Label* throw_out_of_memory_exception,
2536 bool do_gc,
2537 bool always_allocate_scope,
2538 int /* alignment_skew */) {
2539 // rax: result parameter for PerformGC, if any.
2540 // rbx: pointer to C function (C callee-saved).
2541 // rbp: frame pointer (restored after C call).
2542 // rsp: stack pointer (restored after C call).
2543 // r14: number of arguments including receiver (C callee-saved).
2544 // r12: pointer to the first argument (C callee-saved).
2545 // This pointer is reused in LeaveExitFrame(), so it is stored in a
2546 // callee-saved register.
2547
2548 // Simple results returned in rax (both AMD64 and Win64 calling conventions).
2549 // Complex results must be written to address passed as first argument.
2550 // AMD64 calling convention: a struct of two pointers in rax+rdx
2551
2552 // Check stack alignment.
2553 if (FLAG_debug_code) {
2554 __ CheckStackAlignment();
2555 }
2556
2557 if (do_gc) {
2558 // Pass failure code returned from last attempt as first argument to
2559 // PerformGC. No need to use PrepareCallCFunction/CallCFunction here as the
2560 // stack is known to be aligned. This function takes one argument which is
2561 // passed in register.
2562#ifdef _WIN64
2563 __ movq(rcx, rax);
2564#else // _WIN64
2565 __ movq(rdi, rax);
2566#endif
2567 __ movq(kScratchRegister,
2568 FUNCTION_ADDR(Runtime::PerformGC),
2569 RelocInfo::RUNTIME_ENTRY);
2570 __ call(kScratchRegister);
2571 }
2572
2573 ExternalReference scope_depth =
2574 ExternalReference::heap_always_allocate_scope_depth();
2575 if (always_allocate_scope) {
2576 __ movq(kScratchRegister, scope_depth);
2577 __ incl(Operand(kScratchRegister, 0));
2578 }
2579
2580 // Call C function.
2581#ifdef _WIN64
2582 // Windows 64-bit ABI passes arguments in rcx, rdx, r8, r9
2583 // Store Arguments object on stack, below the 4 WIN64 ABI parameter slots.
2584 __ movq(Operand(rsp, 4 * kPointerSize), r14); // argc.
2585 __ movq(Operand(rsp, 5 * kPointerSize), r12); // argv.
2586 if (result_size_ < 2) {
2587 // Pass a pointer to the Arguments object as the first argument.
2588 // Return result in single register (rax).
2589 __ lea(rcx, Operand(rsp, 4 * kPointerSize));
2590 } else {
2591 ASSERT_EQ(2, result_size_);
2592 // Pass a pointer to the result location as the first argument.
2593 __ lea(rcx, Operand(rsp, 6 * kPointerSize));
2594 // Pass a pointer to the Arguments object as the second argument.
2595 __ lea(rdx, Operand(rsp, 4 * kPointerSize));
2596 }
2597
2598#else // _WIN64
2599 // GCC passes arguments in rdi, rsi, rdx, rcx, r8, r9.
2600 __ movq(rdi, r14); // argc.
2601 __ movq(rsi, r12); // argv.
2602#endif
2603 __ call(rbx);
2604 // Result is in rax - do not destroy this register!
2605
2606 if (always_allocate_scope) {
2607 __ movq(kScratchRegister, scope_depth);
2608 __ decl(Operand(kScratchRegister, 0));
2609 }
2610
2611 // Check for failure result.
2612 Label failure_returned;
2613 STATIC_ASSERT(((kFailureTag + 1) & kFailureTagMask) == 0);
2614#ifdef _WIN64
2615 // If return value is on the stack, pop it to registers.
2616 if (result_size_ > 1) {
2617 ASSERT_EQ(2, result_size_);
2618 // Read result values stored on stack. Result is stored
2619 // above the four argument mirror slots and the two
2620 // Arguments object slots.
2621 __ movq(rax, Operand(rsp, 6 * kPointerSize));
2622 __ movq(rdx, Operand(rsp, 7 * kPointerSize));
2623 }
2624#endif
2625 __ lea(rcx, Operand(rax, 1));
2626 // Lower 2 bits of rcx are 0 iff rax has failure tag.
2627 __ testl(rcx, Immediate(kFailureTagMask));
2628 __ j(zero, &failure_returned);
2629
2630 // Exit the JavaScript to C++ exit frame.
2631 __ LeaveExitFrame(result_size_);
2632 __ ret(0);
2633
2634 // Handling of failure.
2635 __ bind(&failure_returned);
2636
Kristian Monsen0d5e1162010-09-30 15:31:59 +01002637 NearLabel retry;
Kristian Monsen80d68ea2010-09-08 11:05:35 +01002638 // If the returned exception is RETRY_AFTER_GC continue at retry label
2639 STATIC_ASSERT(Failure::RETRY_AFTER_GC == 0);
2640 __ testl(rax, Immediate(((1 << kFailureTypeTagSize) - 1) << kFailureTagSize));
2641 __ j(zero, &retry);
2642
2643 // Special handling of out of memory exceptions.
2644 __ movq(kScratchRegister, Failure::OutOfMemoryException(), RelocInfo::NONE);
2645 __ cmpq(rax, kScratchRegister);
2646 __ j(equal, throw_out_of_memory_exception);
2647
2648 // Retrieve the pending exception and clear the variable.
2649 ExternalReference pending_exception_address(Top::k_pending_exception_address);
2650 __ movq(kScratchRegister, pending_exception_address);
2651 __ movq(rax, Operand(kScratchRegister, 0));
2652 __ movq(rdx, ExternalReference::the_hole_value_location());
2653 __ movq(rdx, Operand(rdx, 0));
2654 __ movq(Operand(kScratchRegister, 0), rdx);
2655
2656 // Special handling of termination exceptions which are uncatchable
2657 // by javascript code.
2658 __ CompareRoot(rax, Heap::kTerminationExceptionRootIndex);
2659 __ j(equal, throw_termination_exception);
2660
2661 // Handle normal exception.
2662 __ jmp(throw_normal_exception);
2663
2664 // Retry.
2665 __ bind(&retry);
2666}
2667
2668
2669void CEntryStub::GenerateThrowUncatchable(MacroAssembler* masm,
2670 UncatchableExceptionType type) {
2671 // Fetch top stack handler.
2672 ExternalReference handler_address(Top::k_handler_address);
2673 __ movq(kScratchRegister, handler_address);
2674 __ movq(rsp, Operand(kScratchRegister, 0));
2675
2676 // Unwind the handlers until the ENTRY handler is found.
Kristian Monsen0d5e1162010-09-30 15:31:59 +01002677 NearLabel loop, done;
Kristian Monsen80d68ea2010-09-08 11:05:35 +01002678 __ bind(&loop);
2679 // Load the type of the current stack handler.
2680 const int kStateOffset = StackHandlerConstants::kStateOffset;
2681 __ cmpq(Operand(rsp, kStateOffset), Immediate(StackHandler::ENTRY));
2682 __ j(equal, &done);
2683 // Fetch the next handler in the list.
2684 const int kNextOffset = StackHandlerConstants::kNextOffset;
2685 __ movq(rsp, Operand(rsp, kNextOffset));
2686 __ jmp(&loop);
2687 __ bind(&done);
2688
2689 // Set the top handler address to next handler past the current ENTRY handler.
2690 __ movq(kScratchRegister, handler_address);
2691 __ pop(Operand(kScratchRegister, 0));
2692
2693 if (type == OUT_OF_MEMORY) {
2694 // Set external caught exception to false.
2695 ExternalReference external_caught(Top::k_external_caught_exception_address);
2696 __ movq(rax, Immediate(false));
2697 __ store_rax(external_caught);
2698
2699 // Set pending exception and rax to out of memory exception.
2700 ExternalReference pending_exception(Top::k_pending_exception_address);
2701 __ movq(rax, Failure::OutOfMemoryException(), RelocInfo::NONE);
2702 __ store_rax(pending_exception);
2703 }
2704
2705 // Clear the context pointer.
2706 __ xor_(rsi, rsi);
2707
2708 // Restore registers from handler.
2709 STATIC_ASSERT(StackHandlerConstants::kNextOffset + kPointerSize ==
2710 StackHandlerConstants::kFPOffset);
2711 __ pop(rbp); // FP
2712 STATIC_ASSERT(StackHandlerConstants::kFPOffset + kPointerSize ==
2713 StackHandlerConstants::kStateOffset);
2714 __ pop(rdx); // State
2715
2716 STATIC_ASSERT(StackHandlerConstants::kStateOffset + kPointerSize ==
2717 StackHandlerConstants::kPCOffset);
2718 __ ret(0);
2719}
2720
2721
2722void CEntryStub::Generate(MacroAssembler* masm) {
2723 // rax: number of arguments including receiver
2724 // rbx: pointer to C function (C callee-saved)
2725 // rbp: frame pointer of calling JS frame (restored after C call)
2726 // rsp: stack pointer (restored after C call)
2727 // rsi: current context (restored)
2728
2729 // NOTE: Invocations of builtins may return failure objects
2730 // instead of a proper result. The builtin entry handles
2731 // this by performing a garbage collection and retrying the
2732 // builtin once.
2733
2734 // Enter the exit frame that transitions from JavaScript to C++.
2735 __ EnterExitFrame(result_size_);
2736
2737 // rax: Holds the context at this point, but should not be used.
2738 // On entry to code generated by GenerateCore, it must hold
2739 // a failure result if the collect_garbage argument to GenerateCore
2740 // is true. This failure result can be the result of code
2741 // generated by a previous call to GenerateCore. The value
2742 // of rax is then passed to Runtime::PerformGC.
2743 // rbx: pointer to builtin function (C callee-saved).
2744 // rbp: frame pointer of exit frame (restored after C call).
2745 // rsp: stack pointer (restored after C call).
2746 // r14: number of arguments including receiver (C callee-saved).
2747 // r12: argv pointer (C callee-saved).
2748
2749 Label throw_normal_exception;
2750 Label throw_termination_exception;
2751 Label throw_out_of_memory_exception;
2752
2753 // Call into the runtime system.
2754 GenerateCore(masm,
2755 &throw_normal_exception,
2756 &throw_termination_exception,
2757 &throw_out_of_memory_exception,
2758 false,
2759 false);
2760
2761 // Do space-specific GC and retry runtime call.
2762 GenerateCore(masm,
2763 &throw_normal_exception,
2764 &throw_termination_exception,
2765 &throw_out_of_memory_exception,
2766 true,
2767 false);
2768
2769 // Do full GC and retry runtime call one final time.
2770 Failure* failure = Failure::InternalError();
2771 __ movq(rax, failure, RelocInfo::NONE);
2772 GenerateCore(masm,
2773 &throw_normal_exception,
2774 &throw_termination_exception,
2775 &throw_out_of_memory_exception,
2776 true,
2777 true);
2778
2779 __ bind(&throw_out_of_memory_exception);
2780 GenerateThrowUncatchable(masm, OUT_OF_MEMORY);
2781
2782 __ bind(&throw_termination_exception);
2783 GenerateThrowUncatchable(masm, TERMINATION);
2784
2785 __ bind(&throw_normal_exception);
2786 GenerateThrowTOS(masm);
2787}
2788
2789
2790void JSEntryStub::GenerateBody(MacroAssembler* masm, bool is_construct) {
2791 Label invoke, exit;
2792#ifdef ENABLE_LOGGING_AND_PROFILING
2793 Label not_outermost_js, not_outermost_js_2;
2794#endif
2795
2796 // Setup frame.
2797 __ push(rbp);
2798 __ movq(rbp, rsp);
2799
2800 // Push the stack frame type marker twice.
2801 int marker = is_construct ? StackFrame::ENTRY_CONSTRUCT : StackFrame::ENTRY;
2802 // Scratch register is neither callee-save, nor an argument register on any
2803 // platform. It's free to use at this point.
2804 // Cannot use smi-register for loading yet.
2805 __ movq(kScratchRegister,
2806 reinterpret_cast<uint64_t>(Smi::FromInt(marker)),
2807 RelocInfo::NONE);
2808 __ push(kScratchRegister); // context slot
2809 __ push(kScratchRegister); // function slot
2810 // Save callee-saved registers (X64/Win64 calling conventions).
2811 __ push(r12);
2812 __ push(r13);
2813 __ push(r14);
2814 __ push(r15);
2815#ifdef _WIN64
2816 __ push(rdi); // Only callee save in Win64 ABI, argument in AMD64 ABI.
2817 __ push(rsi); // Only callee save in Win64 ABI, argument in AMD64 ABI.
2818#endif
2819 __ push(rbx);
2820 // TODO(X64): On Win64, if we ever use XMM6-XMM15, the low low 64 bits are
2821 // callee save as well.
2822
2823 // Save copies of the top frame descriptor on the stack.
2824 ExternalReference c_entry_fp(Top::k_c_entry_fp_address);
2825 __ load_rax(c_entry_fp);
2826 __ push(rax);
2827
2828 // Set up the roots and smi constant registers.
2829 // Needs to be done before any further smi loads.
2830 ExternalReference roots_address = ExternalReference::roots_address();
2831 __ movq(kRootRegister, roots_address);
2832 __ InitializeSmiConstantRegister();
2833
2834#ifdef ENABLE_LOGGING_AND_PROFILING
2835 // If this is the outermost JS call, set js_entry_sp value.
2836 ExternalReference js_entry_sp(Top::k_js_entry_sp_address);
2837 __ load_rax(js_entry_sp);
2838 __ testq(rax, rax);
2839 __ j(not_zero, &not_outermost_js);
2840 __ movq(rax, rbp);
2841 __ store_rax(js_entry_sp);
2842 __ bind(&not_outermost_js);
2843#endif
2844
2845 // Call a faked try-block that does the invoke.
2846 __ call(&invoke);
2847
2848 // Caught exception: Store result (exception) in the pending
2849 // exception field in the JSEnv and return a failure sentinel.
2850 ExternalReference pending_exception(Top::k_pending_exception_address);
2851 __ store_rax(pending_exception);
2852 __ movq(rax, Failure::Exception(), RelocInfo::NONE);
2853 __ jmp(&exit);
2854
2855 // Invoke: Link this frame into the handler chain.
2856 __ bind(&invoke);
2857 __ PushTryHandler(IN_JS_ENTRY, JS_ENTRY_HANDLER);
2858
2859 // Clear any pending exceptions.
2860 __ load_rax(ExternalReference::the_hole_value_location());
2861 __ store_rax(pending_exception);
2862
2863 // Fake a receiver (NULL).
2864 __ push(Immediate(0)); // receiver
2865
2866 // Invoke the function by calling through JS entry trampoline
2867 // builtin and pop the faked function when we return. We load the address
2868 // from an external reference instead of inlining the call target address
2869 // directly in the code, because the builtin stubs may not have been
2870 // generated yet at the time this code is generated.
2871 if (is_construct) {
2872 ExternalReference construct_entry(Builtins::JSConstructEntryTrampoline);
2873 __ load_rax(construct_entry);
2874 } else {
2875 ExternalReference entry(Builtins::JSEntryTrampoline);
2876 __ load_rax(entry);
2877 }
2878 __ lea(kScratchRegister, FieldOperand(rax, Code::kHeaderSize));
2879 __ call(kScratchRegister);
2880
2881 // Unlink this frame from the handler chain.
2882 __ movq(kScratchRegister, ExternalReference(Top::k_handler_address));
2883 __ pop(Operand(kScratchRegister, 0));
2884 // Pop next_sp.
2885 __ addq(rsp, Immediate(StackHandlerConstants::kSize - kPointerSize));
2886
2887#ifdef ENABLE_LOGGING_AND_PROFILING
2888 // If current EBP value is the same as js_entry_sp value, it means that
2889 // the current function is the outermost.
2890 __ movq(kScratchRegister, js_entry_sp);
2891 __ cmpq(rbp, Operand(kScratchRegister, 0));
2892 __ j(not_equal, &not_outermost_js_2);
2893 __ movq(Operand(kScratchRegister, 0), Immediate(0));
2894 __ bind(&not_outermost_js_2);
2895#endif
2896
2897 // Restore the top frame descriptor from the stack.
2898 __ bind(&exit);
2899 __ movq(kScratchRegister, ExternalReference(Top::k_c_entry_fp_address));
2900 __ pop(Operand(kScratchRegister, 0));
2901
2902 // Restore callee-saved registers (X64 conventions).
2903 __ pop(rbx);
2904#ifdef _WIN64
2905 // Callee save on in Win64 ABI, arguments/volatile in AMD64 ABI.
2906 __ pop(rsi);
2907 __ pop(rdi);
2908#endif
2909 __ pop(r15);
2910 __ pop(r14);
2911 __ pop(r13);
2912 __ pop(r12);
2913 __ addq(rsp, Immediate(2 * kPointerSize)); // remove markers
2914
2915 // Restore frame pointer and return.
2916 __ pop(rbp);
2917 __ ret(0);
2918}
2919
2920
2921void InstanceofStub::Generate(MacroAssembler* masm) {
2922 // Implements "value instanceof function" operator.
2923 // Expected input state:
2924 // rsp[0] : return address
2925 // rsp[1] : function pointer
2926 // rsp[2] : value
2927 // Returns a bitwise zero to indicate that the value
2928 // is and instance of the function and anything else to
2929 // indicate that the value is not an instance.
2930
2931 // Get the object - go slow case if it's a smi.
2932 Label slow;
2933 __ movq(rax, Operand(rsp, 2 * kPointerSize));
2934 __ JumpIfSmi(rax, &slow);
2935
2936 // Check that the left hand is a JS object. Leave its map in rax.
2937 __ CmpObjectType(rax, FIRST_JS_OBJECT_TYPE, rax);
2938 __ j(below, &slow);
2939 __ CmpInstanceType(rax, LAST_JS_OBJECT_TYPE);
2940 __ j(above, &slow);
2941
2942 // Get the prototype of the function.
2943 __ movq(rdx, Operand(rsp, 1 * kPointerSize));
2944 // rdx is function, rax is map.
2945
2946 // Look up the function and the map in the instanceof cache.
Kristian Monsen0d5e1162010-09-30 15:31:59 +01002947 NearLabel miss;
Kristian Monsen80d68ea2010-09-08 11:05:35 +01002948 __ CompareRoot(rdx, Heap::kInstanceofCacheFunctionRootIndex);
2949 __ j(not_equal, &miss);
2950 __ CompareRoot(rax, Heap::kInstanceofCacheMapRootIndex);
2951 __ j(not_equal, &miss);
2952 __ LoadRoot(rax, Heap::kInstanceofCacheAnswerRootIndex);
2953 __ ret(2 * kPointerSize);
2954
2955 __ bind(&miss);
2956 __ TryGetFunctionPrototype(rdx, rbx, &slow);
2957
2958 // Check that the function prototype is a JS object.
2959 __ JumpIfSmi(rbx, &slow);
2960 __ CmpObjectType(rbx, FIRST_JS_OBJECT_TYPE, kScratchRegister);
2961 __ j(below, &slow);
2962 __ CmpInstanceType(kScratchRegister, LAST_JS_OBJECT_TYPE);
2963 __ j(above, &slow);
2964
2965 // Register mapping:
2966 // rax is object map.
2967 // rdx is function.
2968 // rbx is function prototype.
2969 __ StoreRoot(rdx, Heap::kInstanceofCacheFunctionRootIndex);
2970 __ StoreRoot(rax, Heap::kInstanceofCacheMapRootIndex);
2971
2972 __ movq(rcx, FieldOperand(rax, Map::kPrototypeOffset));
2973
2974 // Loop through the prototype chain looking for the function prototype.
Kristian Monsen0d5e1162010-09-30 15:31:59 +01002975 NearLabel loop, is_instance, is_not_instance;
Kristian Monsen80d68ea2010-09-08 11:05:35 +01002976 __ LoadRoot(kScratchRegister, Heap::kNullValueRootIndex);
2977 __ bind(&loop);
2978 __ cmpq(rcx, rbx);
2979 __ j(equal, &is_instance);
2980 __ cmpq(rcx, kScratchRegister);
2981 // The code at is_not_instance assumes that kScratchRegister contains a
2982 // non-zero GCable value (the null object in this case).
2983 __ j(equal, &is_not_instance);
2984 __ movq(rcx, FieldOperand(rcx, HeapObject::kMapOffset));
2985 __ movq(rcx, FieldOperand(rcx, Map::kPrototypeOffset));
2986 __ jmp(&loop);
2987
2988 __ bind(&is_instance);
2989 __ xorl(rax, rax);
2990 // Store bitwise zero in the cache. This is a Smi in GC terms.
2991 STATIC_ASSERT(kSmiTag == 0);
2992 __ StoreRoot(rax, Heap::kInstanceofCacheAnswerRootIndex);
2993 __ ret(2 * kPointerSize);
2994
2995 __ bind(&is_not_instance);
2996 // We have to store a non-zero value in the cache.
2997 __ StoreRoot(kScratchRegister, Heap::kInstanceofCacheAnswerRootIndex);
2998 __ ret(2 * kPointerSize);
2999
3000 // Slow-case: Go through the JavaScript implementation.
3001 __ bind(&slow);
3002 __ InvokeBuiltin(Builtins::INSTANCE_OF, JUMP_FUNCTION);
3003}
3004
3005
3006int CompareStub::MinorKey() {
3007 // Encode the three parameters in a unique 16 bit value. To avoid duplicate
3008 // stubs the never NaN NaN condition is only taken into account if the
3009 // condition is equals.
3010 ASSERT(static_cast<unsigned>(cc_) < (1 << 12));
3011 ASSERT(lhs_.is(no_reg) && rhs_.is(no_reg));
3012 return ConditionField::encode(static_cast<unsigned>(cc_))
3013 | RegisterField::encode(false) // lhs_ and rhs_ are not used
3014 | StrictField::encode(strict_)
3015 | NeverNanNanField::encode(cc_ == equal ? never_nan_nan_ : false)
Kristian Monsen0d5e1162010-09-30 15:31:59 +01003016 | IncludeNumberCompareField::encode(include_number_compare_)
3017 | IncludeSmiCompareField::encode(include_smi_compare_);
Kristian Monsen80d68ea2010-09-08 11:05:35 +01003018}
3019
3020
3021// Unfortunately you have to run without snapshots to see most of these
3022// names in the profile since most compare stubs end up in the snapshot.
3023const char* CompareStub::GetName() {
3024 ASSERT(lhs_.is(no_reg) && rhs_.is(no_reg));
3025
3026 if (name_ != NULL) return name_;
3027 const int kMaxNameLength = 100;
3028 name_ = Bootstrapper::AllocateAutoDeletedArray(kMaxNameLength);
3029 if (name_ == NULL) return "OOM";
3030
3031 const char* cc_name;
3032 switch (cc_) {
3033 case less: cc_name = "LT"; break;
3034 case greater: cc_name = "GT"; break;
3035 case less_equal: cc_name = "LE"; break;
3036 case greater_equal: cc_name = "GE"; break;
3037 case equal: cc_name = "EQ"; break;
3038 case not_equal: cc_name = "NE"; break;
3039 default: cc_name = "UnknownCondition"; break;
3040 }
3041
3042 const char* strict_name = "";
3043 if (strict_ && (cc_ == equal || cc_ == not_equal)) {
3044 strict_name = "_STRICT";
3045 }
3046
3047 const char* never_nan_nan_name = "";
3048 if (never_nan_nan_ && (cc_ == equal || cc_ == not_equal)) {
3049 never_nan_nan_name = "_NO_NAN";
3050 }
3051
3052 const char* include_number_compare_name = "";
3053 if (!include_number_compare_) {
3054 include_number_compare_name = "_NO_NUMBER";
3055 }
3056
Kristian Monsen0d5e1162010-09-30 15:31:59 +01003057 const char* include_smi_compare_name = "";
3058 if (!include_smi_compare_) {
3059 include_smi_compare_name = "_NO_SMI";
3060 }
3061
Kristian Monsen80d68ea2010-09-08 11:05:35 +01003062 OS::SNPrintF(Vector<char>(name_, kMaxNameLength),
3063 "CompareStub_%s%s%s%s",
3064 cc_name,
3065 strict_name,
3066 never_nan_nan_name,
Kristian Monsen0d5e1162010-09-30 15:31:59 +01003067 include_number_compare_name,
3068 include_smi_compare_name);
Kristian Monsen80d68ea2010-09-08 11:05:35 +01003069 return name_;
3070}
3071
3072
3073// -------------------------------------------------------------------------
3074// StringCharCodeAtGenerator
3075
3076void StringCharCodeAtGenerator::GenerateFast(MacroAssembler* masm) {
3077 Label flat_string;
3078 Label ascii_string;
3079 Label got_char_code;
3080
3081 // If the receiver is a smi trigger the non-string case.
3082 __ JumpIfSmi(object_, receiver_not_string_);
3083
3084 // Fetch the instance type of the receiver into result register.
3085 __ movq(result_, FieldOperand(object_, HeapObject::kMapOffset));
3086 __ movzxbl(result_, FieldOperand(result_, Map::kInstanceTypeOffset));
3087 // If the receiver is not a string trigger the non-string case.
3088 __ testb(result_, Immediate(kIsNotStringMask));
3089 __ j(not_zero, receiver_not_string_);
3090
3091 // If the index is non-smi trigger the non-smi case.
3092 __ JumpIfNotSmi(index_, &index_not_smi_);
3093
3094 // Put smi-tagged index into scratch register.
3095 __ movq(scratch_, index_);
3096 __ bind(&got_smi_index_);
3097
3098 // Check for index out of range.
3099 __ SmiCompare(scratch_, FieldOperand(object_, String::kLengthOffset));
3100 __ j(above_equal, index_out_of_range_);
3101
3102 // We need special handling for non-flat strings.
3103 STATIC_ASSERT(kSeqStringTag == 0);
3104 __ testb(result_, Immediate(kStringRepresentationMask));
3105 __ j(zero, &flat_string);
3106
3107 // Handle non-flat strings.
3108 __ testb(result_, Immediate(kIsConsStringMask));
3109 __ j(zero, &call_runtime_);
3110
3111 // ConsString.
3112 // Check whether the right hand side is the empty string (i.e. if
3113 // this is really a flat string in a cons string). If that is not
3114 // the case we would rather go to the runtime system now to flatten
3115 // the string.
3116 __ CompareRoot(FieldOperand(object_, ConsString::kSecondOffset),
3117 Heap::kEmptyStringRootIndex);
3118 __ j(not_equal, &call_runtime_);
3119 // Get the first of the two strings and load its instance type.
3120 __ movq(object_, FieldOperand(object_, ConsString::kFirstOffset));
3121 __ movq(result_, FieldOperand(object_, HeapObject::kMapOffset));
3122 __ movzxbl(result_, FieldOperand(result_, Map::kInstanceTypeOffset));
3123 // If the first cons component is also non-flat, then go to runtime.
3124 STATIC_ASSERT(kSeqStringTag == 0);
3125 __ testb(result_, Immediate(kStringRepresentationMask));
3126 __ j(not_zero, &call_runtime_);
3127
3128 // Check for 1-byte or 2-byte string.
3129 __ bind(&flat_string);
3130 STATIC_ASSERT(kAsciiStringTag != 0);
3131 __ testb(result_, Immediate(kStringEncodingMask));
3132 __ j(not_zero, &ascii_string);
3133
3134 // 2-byte string.
3135 // Load the 2-byte character code into the result register.
3136 __ SmiToInteger32(scratch_, scratch_);
3137 __ movzxwl(result_, FieldOperand(object_,
3138 scratch_, times_2,
3139 SeqTwoByteString::kHeaderSize));
3140 __ jmp(&got_char_code);
3141
3142 // ASCII string.
3143 // Load the byte into the result register.
3144 __ bind(&ascii_string);
3145 __ SmiToInteger32(scratch_, scratch_);
3146 __ movzxbl(result_, FieldOperand(object_,
3147 scratch_, times_1,
3148 SeqAsciiString::kHeaderSize));
3149 __ bind(&got_char_code);
3150 __ Integer32ToSmi(result_, result_);
3151 __ bind(&exit_);
3152}
3153
3154
3155void StringCharCodeAtGenerator::GenerateSlow(
3156 MacroAssembler* masm, const RuntimeCallHelper& call_helper) {
3157 __ Abort("Unexpected fallthrough to CharCodeAt slow case");
3158
3159 // Index is not a smi.
3160 __ bind(&index_not_smi_);
3161 // If index is a heap number, try converting it to an integer.
3162 __ CheckMap(index_, Factory::heap_number_map(), index_not_number_, true);
3163 call_helper.BeforeCall(masm);
3164 __ push(object_);
3165 __ push(index_);
3166 __ push(index_); // Consumed by runtime conversion function.
3167 if (index_flags_ == STRING_INDEX_IS_NUMBER) {
3168 __ CallRuntime(Runtime::kNumberToIntegerMapMinusZero, 1);
3169 } else {
3170 ASSERT(index_flags_ == STRING_INDEX_IS_ARRAY_INDEX);
3171 // NumberToSmi discards numbers that are not exact integers.
3172 __ CallRuntime(Runtime::kNumberToSmi, 1);
3173 }
3174 if (!scratch_.is(rax)) {
3175 // Save the conversion result before the pop instructions below
3176 // have a chance to overwrite it.
3177 __ movq(scratch_, rax);
3178 }
3179 __ pop(index_);
3180 __ pop(object_);
3181 // Reload the instance type.
3182 __ movq(result_, FieldOperand(object_, HeapObject::kMapOffset));
3183 __ movzxbl(result_, FieldOperand(result_, Map::kInstanceTypeOffset));
3184 call_helper.AfterCall(masm);
3185 // If index is still not a smi, it must be out of range.
3186 __ JumpIfNotSmi(scratch_, index_out_of_range_);
3187 // Otherwise, return to the fast path.
3188 __ jmp(&got_smi_index_);
3189
3190 // Call runtime. We get here when the receiver is a string and the
3191 // index is a number, but the code of getting the actual character
3192 // is too complex (e.g., when the string needs to be flattened).
3193 __ bind(&call_runtime_);
3194 call_helper.BeforeCall(masm);
3195 __ push(object_);
3196 __ push(index_);
3197 __ CallRuntime(Runtime::kStringCharCodeAt, 2);
3198 if (!result_.is(rax)) {
3199 __ movq(result_, rax);
3200 }
3201 call_helper.AfterCall(masm);
3202 __ jmp(&exit_);
3203
3204 __ Abort("Unexpected fallthrough from CharCodeAt slow case");
3205}
3206
3207
3208// -------------------------------------------------------------------------
3209// StringCharFromCodeGenerator
3210
3211void StringCharFromCodeGenerator::GenerateFast(MacroAssembler* masm) {
3212 // Fast case of Heap::LookupSingleCharacterStringFromCode.
3213 __ JumpIfNotSmi(code_, &slow_case_);
3214 __ SmiCompare(code_, Smi::FromInt(String::kMaxAsciiCharCode));
3215 __ j(above, &slow_case_);
3216
3217 __ LoadRoot(result_, Heap::kSingleCharacterStringCacheRootIndex);
3218 SmiIndex index = masm->SmiToIndex(kScratchRegister, code_, kPointerSizeLog2);
3219 __ movq(result_, FieldOperand(result_, index.reg, index.scale,
3220 FixedArray::kHeaderSize));
3221 __ CompareRoot(result_, Heap::kUndefinedValueRootIndex);
3222 __ j(equal, &slow_case_);
3223 __ bind(&exit_);
3224}
3225
3226
3227void StringCharFromCodeGenerator::GenerateSlow(
3228 MacroAssembler* masm, const RuntimeCallHelper& call_helper) {
3229 __ Abort("Unexpected fallthrough to CharFromCode slow case");
3230
3231 __ bind(&slow_case_);
3232 call_helper.BeforeCall(masm);
3233 __ push(code_);
3234 __ CallRuntime(Runtime::kCharFromCode, 1);
3235 if (!result_.is(rax)) {
3236 __ movq(result_, rax);
3237 }
3238 call_helper.AfterCall(masm);
3239 __ jmp(&exit_);
3240
3241 __ Abort("Unexpected fallthrough from CharFromCode slow case");
3242}
3243
3244
3245// -------------------------------------------------------------------------
3246// StringCharAtGenerator
3247
3248void StringCharAtGenerator::GenerateFast(MacroAssembler* masm) {
3249 char_code_at_generator_.GenerateFast(masm);
3250 char_from_code_generator_.GenerateFast(masm);
3251}
3252
3253
3254void StringCharAtGenerator::GenerateSlow(
3255 MacroAssembler* masm, const RuntimeCallHelper& call_helper) {
3256 char_code_at_generator_.GenerateSlow(masm, call_helper);
3257 char_from_code_generator_.GenerateSlow(masm, call_helper);
3258}
3259
3260
3261void StringAddStub::Generate(MacroAssembler* masm) {
3262 Label string_add_runtime;
3263
3264 // Load the two arguments.
3265 __ movq(rax, Operand(rsp, 2 * kPointerSize)); // First argument.
3266 __ movq(rdx, Operand(rsp, 1 * kPointerSize)); // Second argument.
3267
3268 // Make sure that both arguments are strings if not known in advance.
3269 if (string_check_) {
3270 Condition is_smi;
3271 is_smi = masm->CheckSmi(rax);
3272 __ j(is_smi, &string_add_runtime);
3273 __ CmpObjectType(rax, FIRST_NONSTRING_TYPE, r8);
3274 __ j(above_equal, &string_add_runtime);
3275
3276 // First argument is a a string, test second.
3277 is_smi = masm->CheckSmi(rdx);
3278 __ j(is_smi, &string_add_runtime);
3279 __ CmpObjectType(rdx, FIRST_NONSTRING_TYPE, r9);
3280 __ j(above_equal, &string_add_runtime);
3281 }
3282
3283 // Both arguments are strings.
3284 // rax: first string
3285 // rdx: second string
3286 // Check if either of the strings are empty. In that case return the other.
Kristian Monsen0d5e1162010-09-30 15:31:59 +01003287 NearLabel second_not_zero_length, both_not_zero_length;
Kristian Monsen80d68ea2010-09-08 11:05:35 +01003288 __ movq(rcx, FieldOperand(rdx, String::kLengthOffset));
3289 __ SmiTest(rcx);
3290 __ j(not_zero, &second_not_zero_length);
3291 // Second string is empty, result is first string which is already in rax.
3292 __ IncrementCounter(&Counters::string_add_native, 1);
3293 __ ret(2 * kPointerSize);
3294 __ bind(&second_not_zero_length);
3295 __ movq(rbx, FieldOperand(rax, String::kLengthOffset));
3296 __ SmiTest(rbx);
3297 __ j(not_zero, &both_not_zero_length);
3298 // First string is empty, result is second string which is in rdx.
3299 __ movq(rax, rdx);
3300 __ IncrementCounter(&Counters::string_add_native, 1);
3301 __ ret(2 * kPointerSize);
3302
3303 // Both strings are non-empty.
3304 // rax: first string
3305 // rbx: length of first string
3306 // rcx: length of second string
3307 // rdx: second string
3308 // r8: map of first string if string check was performed above
3309 // r9: map of second string if string check was performed above
3310 Label string_add_flat_result, longer_than_two;
3311 __ bind(&both_not_zero_length);
3312
3313 // If arguments where known to be strings, maps are not loaded to r8 and r9
3314 // by the code above.
3315 if (!string_check_) {
3316 __ movq(r8, FieldOperand(rax, HeapObject::kMapOffset));
3317 __ movq(r9, FieldOperand(rdx, HeapObject::kMapOffset));
3318 }
3319 // Get the instance types of the two strings as they will be needed soon.
3320 __ movzxbl(r8, FieldOperand(r8, Map::kInstanceTypeOffset));
3321 __ movzxbl(r9, FieldOperand(r9, Map::kInstanceTypeOffset));
3322
3323 // Look at the length of the result of adding the two strings.
3324 STATIC_ASSERT(String::kMaxLength <= Smi::kMaxValue / 2);
Kristian Monsen0d5e1162010-09-30 15:31:59 +01003325 __ SmiAdd(rbx, rbx, rcx);
Kristian Monsen80d68ea2010-09-08 11:05:35 +01003326 // Use the runtime system when adding two one character strings, as it
3327 // contains optimizations for this specific case using the symbol table.
3328 __ SmiCompare(rbx, Smi::FromInt(2));
3329 __ j(not_equal, &longer_than_two);
3330
3331 // Check that both strings are non-external ascii strings.
3332 __ JumpIfBothInstanceTypesAreNotSequentialAscii(r8, r9, rbx, rcx,
3333 &string_add_runtime);
3334
3335 // Get the two characters forming the sub string.
3336 __ movzxbq(rbx, FieldOperand(rax, SeqAsciiString::kHeaderSize));
3337 __ movzxbq(rcx, FieldOperand(rdx, SeqAsciiString::kHeaderSize));
3338
3339 // Try to lookup two character string in symbol table. If it is not found
3340 // just allocate a new one.
3341 Label make_two_character_string, make_flat_ascii_string;
3342 StringHelper::GenerateTwoCharacterSymbolTableProbe(
3343 masm, rbx, rcx, r14, r11, rdi, r12, &make_two_character_string);
3344 __ IncrementCounter(&Counters::string_add_native, 1);
3345 __ ret(2 * kPointerSize);
3346
3347 __ bind(&make_two_character_string);
3348 __ Set(rbx, 2);
3349 __ jmp(&make_flat_ascii_string);
3350
3351 __ bind(&longer_than_two);
3352 // Check if resulting string will be flat.
3353 __ SmiCompare(rbx, Smi::FromInt(String::kMinNonFlatLength));
3354 __ j(below, &string_add_flat_result);
3355 // Handle exceptionally long strings in the runtime system.
3356 STATIC_ASSERT((String::kMaxLength & 0x80000000) == 0);
3357 __ SmiCompare(rbx, Smi::FromInt(String::kMaxLength));
3358 __ j(above, &string_add_runtime);
3359
3360 // If result is not supposed to be flat, allocate a cons string object. If
3361 // both strings are ascii the result is an ascii cons string.
3362 // rax: first string
3363 // rbx: length of resulting flat string
3364 // rdx: second string
3365 // r8: instance type of first string
3366 // r9: instance type of second string
3367 Label non_ascii, allocated, ascii_data;
3368 __ movl(rcx, r8);
3369 __ and_(rcx, r9);
3370 STATIC_ASSERT(kStringEncodingMask == kAsciiStringTag);
3371 __ testl(rcx, Immediate(kAsciiStringTag));
3372 __ j(zero, &non_ascii);
3373 __ bind(&ascii_data);
3374 // Allocate an acsii cons string.
3375 __ AllocateAsciiConsString(rcx, rdi, no_reg, &string_add_runtime);
3376 __ bind(&allocated);
3377 // Fill the fields of the cons string.
3378 __ movq(FieldOperand(rcx, ConsString::kLengthOffset), rbx);
3379 __ movq(FieldOperand(rcx, ConsString::kHashFieldOffset),
3380 Immediate(String::kEmptyHashField));
3381 __ movq(FieldOperand(rcx, ConsString::kFirstOffset), rax);
3382 __ movq(FieldOperand(rcx, ConsString::kSecondOffset), rdx);
3383 __ movq(rax, rcx);
3384 __ IncrementCounter(&Counters::string_add_native, 1);
3385 __ ret(2 * kPointerSize);
3386 __ bind(&non_ascii);
3387 // At least one of the strings is two-byte. Check whether it happens
3388 // to contain only ascii characters.
3389 // rcx: first instance type AND second instance type.
3390 // r8: first instance type.
3391 // r9: second instance type.
3392 __ testb(rcx, Immediate(kAsciiDataHintMask));
3393 __ j(not_zero, &ascii_data);
3394 __ xor_(r8, r9);
3395 STATIC_ASSERT(kAsciiStringTag != 0 && kAsciiDataHintTag != 0);
3396 __ andb(r8, Immediate(kAsciiStringTag | kAsciiDataHintTag));
3397 __ cmpb(r8, Immediate(kAsciiStringTag | kAsciiDataHintTag));
3398 __ j(equal, &ascii_data);
3399 // Allocate a two byte cons string.
3400 __ AllocateConsString(rcx, rdi, no_reg, &string_add_runtime);
3401 __ jmp(&allocated);
3402
3403 // Handle creating a flat result. First check that both strings are not
3404 // external strings.
3405 // rax: first string
3406 // rbx: length of resulting flat string as smi
3407 // rdx: second string
3408 // r8: instance type of first string
3409 // r9: instance type of first string
3410 __ bind(&string_add_flat_result);
3411 __ SmiToInteger32(rbx, rbx);
3412 __ movl(rcx, r8);
3413 __ and_(rcx, Immediate(kStringRepresentationMask));
3414 __ cmpl(rcx, Immediate(kExternalStringTag));
3415 __ j(equal, &string_add_runtime);
3416 __ movl(rcx, r9);
3417 __ and_(rcx, Immediate(kStringRepresentationMask));
3418 __ cmpl(rcx, Immediate(kExternalStringTag));
3419 __ j(equal, &string_add_runtime);
3420 // Now check if both strings are ascii strings.
3421 // rax: first string
3422 // rbx: length of resulting flat string
3423 // rdx: second string
3424 // r8: instance type of first string
3425 // r9: instance type of second string
3426 Label non_ascii_string_add_flat_result;
3427 STATIC_ASSERT(kStringEncodingMask == kAsciiStringTag);
3428 __ testl(r8, Immediate(kAsciiStringTag));
3429 __ j(zero, &non_ascii_string_add_flat_result);
3430 __ testl(r9, Immediate(kAsciiStringTag));
3431 __ j(zero, &string_add_runtime);
3432
3433 __ bind(&make_flat_ascii_string);
3434 // Both strings are ascii strings. As they are short they are both flat.
3435 __ AllocateAsciiString(rcx, rbx, rdi, r14, r11, &string_add_runtime);
3436 // rcx: result string
3437 __ movq(rbx, rcx);
3438 // Locate first character of result.
3439 __ addq(rcx, Immediate(SeqAsciiString::kHeaderSize - kHeapObjectTag));
3440 // Locate first character of first argument
3441 __ SmiToInteger32(rdi, FieldOperand(rax, String::kLengthOffset));
3442 __ addq(rax, Immediate(SeqAsciiString::kHeaderSize - kHeapObjectTag));
3443 // rax: first char of first argument
3444 // rbx: result string
3445 // rcx: first character of result
3446 // rdx: second string
3447 // rdi: length of first argument
3448 StringHelper::GenerateCopyCharacters(masm, rcx, rax, rdi, true);
3449 // Locate first character of second argument.
3450 __ SmiToInteger32(rdi, FieldOperand(rdx, String::kLengthOffset));
3451 __ addq(rdx, Immediate(SeqAsciiString::kHeaderSize - kHeapObjectTag));
3452 // rbx: result string
3453 // rcx: next character of result
3454 // rdx: first char of second argument
3455 // rdi: length of second argument
3456 StringHelper::GenerateCopyCharacters(masm, rcx, rdx, rdi, true);
3457 __ movq(rax, rbx);
3458 __ IncrementCounter(&Counters::string_add_native, 1);
3459 __ ret(2 * kPointerSize);
3460
3461 // Handle creating a flat two byte result.
3462 // rax: first string - known to be two byte
3463 // rbx: length of resulting flat string
3464 // rdx: second string
3465 // r8: instance type of first string
3466 // r9: instance type of first string
3467 __ bind(&non_ascii_string_add_flat_result);
3468 __ and_(r9, Immediate(kAsciiStringTag));
3469 __ j(not_zero, &string_add_runtime);
3470 // Both strings are two byte strings. As they are short they are both
3471 // flat.
3472 __ AllocateTwoByteString(rcx, rbx, rdi, r14, r11, &string_add_runtime);
3473 // rcx: result string
3474 __ movq(rbx, rcx);
3475 // Locate first character of result.
3476 __ addq(rcx, Immediate(SeqTwoByteString::kHeaderSize - kHeapObjectTag));
3477 // Locate first character of first argument.
3478 __ SmiToInteger32(rdi, FieldOperand(rax, String::kLengthOffset));
3479 __ addq(rax, Immediate(SeqTwoByteString::kHeaderSize - kHeapObjectTag));
3480 // rax: first char of first argument
3481 // rbx: result string
3482 // rcx: first character of result
3483 // rdx: second argument
3484 // rdi: length of first argument
3485 StringHelper::GenerateCopyCharacters(masm, rcx, rax, rdi, false);
3486 // Locate first character of second argument.
3487 __ SmiToInteger32(rdi, FieldOperand(rdx, String::kLengthOffset));
3488 __ addq(rdx, Immediate(SeqTwoByteString::kHeaderSize - kHeapObjectTag));
3489 // rbx: result string
3490 // rcx: next character of result
3491 // rdx: first char of second argument
3492 // rdi: length of second argument
3493 StringHelper::GenerateCopyCharacters(masm, rcx, rdx, rdi, false);
3494 __ movq(rax, rbx);
3495 __ IncrementCounter(&Counters::string_add_native, 1);
3496 __ ret(2 * kPointerSize);
3497
3498 // Just jump to runtime to add the two strings.
3499 __ bind(&string_add_runtime);
3500 __ TailCallRuntime(Runtime::kStringAdd, 2, 1);
3501}
3502
3503
3504void StringHelper::GenerateCopyCharacters(MacroAssembler* masm,
3505 Register dest,
3506 Register src,
3507 Register count,
3508 bool ascii) {
3509 Label loop;
3510 __ bind(&loop);
3511 // This loop just copies one character at a time, as it is only used for very
3512 // short strings.
3513 if (ascii) {
3514 __ movb(kScratchRegister, Operand(src, 0));
3515 __ movb(Operand(dest, 0), kScratchRegister);
3516 __ incq(src);
3517 __ incq(dest);
3518 } else {
3519 __ movzxwl(kScratchRegister, Operand(src, 0));
3520 __ movw(Operand(dest, 0), kScratchRegister);
3521 __ addq(src, Immediate(2));
3522 __ addq(dest, Immediate(2));
3523 }
3524 __ decl(count);
3525 __ j(not_zero, &loop);
3526}
3527
3528
3529void StringHelper::GenerateCopyCharactersREP(MacroAssembler* masm,
3530 Register dest,
3531 Register src,
3532 Register count,
3533 bool ascii) {
3534 // Copy characters using rep movs of doublewords. Align destination on 4 byte
3535 // boundary before starting rep movs. Copy remaining characters after running
3536 // rep movs.
3537 // Count is positive int32, dest and src are character pointers.
3538 ASSERT(dest.is(rdi)); // rep movs destination
3539 ASSERT(src.is(rsi)); // rep movs source
3540 ASSERT(count.is(rcx)); // rep movs count
3541
3542 // Nothing to do for zero characters.
Kristian Monsen0d5e1162010-09-30 15:31:59 +01003543 NearLabel done;
Kristian Monsen80d68ea2010-09-08 11:05:35 +01003544 __ testl(count, count);
3545 __ j(zero, &done);
3546
3547 // Make count the number of bytes to copy.
3548 if (!ascii) {
3549 STATIC_ASSERT(2 == sizeof(uc16));
3550 __ addl(count, count);
3551 }
3552
3553 // Don't enter the rep movs if there are less than 4 bytes to copy.
Kristian Monsen0d5e1162010-09-30 15:31:59 +01003554 NearLabel last_bytes;
Kristian Monsen80d68ea2010-09-08 11:05:35 +01003555 __ testl(count, Immediate(~7));
3556 __ j(zero, &last_bytes);
3557
3558 // Copy from edi to esi using rep movs instruction.
3559 __ movl(kScratchRegister, count);
3560 __ shr(count, Immediate(3)); // Number of doublewords to copy.
3561 __ repmovsq();
3562
3563 // Find number of bytes left.
3564 __ movl(count, kScratchRegister);
3565 __ and_(count, Immediate(7));
3566
3567 // Check if there are more bytes to copy.
3568 __ bind(&last_bytes);
3569 __ testl(count, count);
3570 __ j(zero, &done);
3571
3572 // Copy remaining characters.
3573 Label loop;
3574 __ bind(&loop);
3575 __ movb(kScratchRegister, Operand(src, 0));
3576 __ movb(Operand(dest, 0), kScratchRegister);
3577 __ incq(src);
3578 __ incq(dest);
3579 __ decl(count);
3580 __ j(not_zero, &loop);
3581
3582 __ bind(&done);
3583}
3584
3585void StringHelper::GenerateTwoCharacterSymbolTableProbe(MacroAssembler* masm,
3586 Register c1,
3587 Register c2,
3588 Register scratch1,
3589 Register scratch2,
3590 Register scratch3,
3591 Register scratch4,
3592 Label* not_found) {
3593 // Register scratch3 is the general scratch register in this function.
3594 Register scratch = scratch3;
3595
3596 // Make sure that both characters are not digits as such strings has a
3597 // different hash algorithm. Don't try to look for these in the symbol table.
Kristian Monsen0d5e1162010-09-30 15:31:59 +01003598 NearLabel not_array_index;
Kristian Monsen80d68ea2010-09-08 11:05:35 +01003599 __ leal(scratch, Operand(c1, -'0'));
3600 __ cmpl(scratch, Immediate(static_cast<int>('9' - '0')));
3601 __ j(above, &not_array_index);
3602 __ leal(scratch, Operand(c2, -'0'));
3603 __ cmpl(scratch, Immediate(static_cast<int>('9' - '0')));
3604 __ j(below_equal, not_found);
3605
3606 __ bind(&not_array_index);
3607 // Calculate the two character string hash.
3608 Register hash = scratch1;
3609 GenerateHashInit(masm, hash, c1, scratch);
3610 GenerateHashAddCharacter(masm, hash, c2, scratch);
3611 GenerateHashGetHash(masm, hash, scratch);
3612
3613 // Collect the two characters in a register.
3614 Register chars = c1;
3615 __ shl(c2, Immediate(kBitsPerByte));
3616 __ orl(chars, c2);
3617
3618 // chars: two character string, char 1 in byte 0 and char 2 in byte 1.
3619 // hash: hash of two character string.
3620
3621 // Load the symbol table.
3622 Register symbol_table = c2;
3623 __ LoadRoot(symbol_table, Heap::kSymbolTableRootIndex);
3624
3625 // Calculate capacity mask from the symbol table capacity.
3626 Register mask = scratch2;
3627 __ SmiToInteger32(mask,
3628 FieldOperand(symbol_table, SymbolTable::kCapacityOffset));
3629 __ decl(mask);
3630
3631 Register undefined = scratch4;
3632 __ LoadRoot(undefined, Heap::kUndefinedValueRootIndex);
3633
3634 // Registers
3635 // chars: two character string, char 1 in byte 0 and char 2 in byte 1.
3636 // hash: hash of two character string (32-bit int)
3637 // symbol_table: symbol table
3638 // mask: capacity mask (32-bit int)
3639 // undefined: undefined value
3640 // scratch: -
3641
3642 // Perform a number of probes in the symbol table.
3643 static const int kProbes = 4;
3644 Label found_in_symbol_table;
3645 Label next_probe[kProbes];
3646 for (int i = 0; i < kProbes; i++) {
3647 // Calculate entry in symbol table.
3648 __ movl(scratch, hash);
3649 if (i > 0) {
3650 __ addl(scratch, Immediate(SymbolTable::GetProbeOffset(i)));
3651 }
3652 __ andl(scratch, mask);
3653
3654 // Load the entry from the symble table.
3655 Register candidate = scratch; // Scratch register contains candidate.
3656 STATIC_ASSERT(SymbolTable::kEntrySize == 1);
3657 __ movq(candidate,
3658 FieldOperand(symbol_table,
3659 scratch,
3660 times_pointer_size,
3661 SymbolTable::kElementsStartOffset));
3662
3663 // If entry is undefined no string with this hash can be found.
3664 __ cmpq(candidate, undefined);
3665 __ j(equal, not_found);
3666
3667 // If length is not 2 the string is not a candidate.
3668 __ SmiCompare(FieldOperand(candidate, String::kLengthOffset),
3669 Smi::FromInt(2));
3670 __ j(not_equal, &next_probe[i]);
3671
3672 // We use kScratchRegister as a temporary register in assumption that
3673 // JumpIfInstanceTypeIsNotSequentialAscii does not use it implicitly
3674 Register temp = kScratchRegister;
3675
3676 // Check that the candidate is a non-external ascii string.
3677 __ movq(temp, FieldOperand(candidate, HeapObject::kMapOffset));
3678 __ movzxbl(temp, FieldOperand(temp, Map::kInstanceTypeOffset));
3679 __ JumpIfInstanceTypeIsNotSequentialAscii(
3680 temp, temp, &next_probe[i]);
3681
3682 // Check if the two characters match.
3683 __ movl(temp, FieldOperand(candidate, SeqAsciiString::kHeaderSize));
3684 __ andl(temp, Immediate(0x0000ffff));
3685 __ cmpl(chars, temp);
3686 __ j(equal, &found_in_symbol_table);
3687 __ bind(&next_probe[i]);
3688 }
3689
3690 // No matching 2 character string found by probing.
3691 __ jmp(not_found);
3692
3693 // Scratch register contains result when we fall through to here.
3694 Register result = scratch;
3695 __ bind(&found_in_symbol_table);
3696 if (!result.is(rax)) {
3697 __ movq(rax, result);
3698 }
3699}
3700
3701
3702void StringHelper::GenerateHashInit(MacroAssembler* masm,
3703 Register hash,
3704 Register character,
3705 Register scratch) {
3706 // hash = character + (character << 10);
3707 __ movl(hash, character);
3708 __ shll(hash, Immediate(10));
3709 __ addl(hash, character);
3710 // hash ^= hash >> 6;
3711 __ movl(scratch, hash);
3712 __ sarl(scratch, Immediate(6));
3713 __ xorl(hash, scratch);
3714}
3715
3716
3717void StringHelper::GenerateHashAddCharacter(MacroAssembler* masm,
3718 Register hash,
3719 Register character,
3720 Register scratch) {
3721 // hash += character;
3722 __ addl(hash, character);
3723 // hash += hash << 10;
3724 __ movl(scratch, hash);
3725 __ shll(scratch, Immediate(10));
3726 __ addl(hash, scratch);
3727 // hash ^= hash >> 6;
3728 __ movl(scratch, hash);
3729 __ sarl(scratch, Immediate(6));
3730 __ xorl(hash, scratch);
3731}
3732
3733
3734void StringHelper::GenerateHashGetHash(MacroAssembler* masm,
3735 Register hash,
3736 Register scratch) {
3737 // hash += hash << 3;
3738 __ leal(hash, Operand(hash, hash, times_8, 0));
3739 // hash ^= hash >> 11;
3740 __ movl(scratch, hash);
3741 __ sarl(scratch, Immediate(11));
3742 __ xorl(hash, scratch);
3743 // hash += hash << 15;
3744 __ movl(scratch, hash);
3745 __ shll(scratch, Immediate(15));
3746 __ addl(hash, scratch);
3747
3748 // if (hash == 0) hash = 27;
3749 Label hash_not_zero;
3750 __ j(not_zero, &hash_not_zero);
3751 __ movl(hash, Immediate(27));
3752 __ bind(&hash_not_zero);
3753}
3754
3755void SubStringStub::Generate(MacroAssembler* masm) {
3756 Label runtime;
3757
3758 // Stack frame on entry.
3759 // rsp[0]: return address
3760 // rsp[8]: to
3761 // rsp[16]: from
3762 // rsp[24]: string
3763
3764 const int kToOffset = 1 * kPointerSize;
3765 const int kFromOffset = kToOffset + kPointerSize;
3766 const int kStringOffset = kFromOffset + kPointerSize;
3767 const int kArgumentsSize = (kStringOffset + kPointerSize) - kToOffset;
3768
3769 // Make sure first argument is a string.
3770 __ movq(rax, Operand(rsp, kStringOffset));
3771 STATIC_ASSERT(kSmiTag == 0);
3772 __ testl(rax, Immediate(kSmiTagMask));
3773 __ j(zero, &runtime);
3774 Condition is_string = masm->IsObjectStringType(rax, rbx, rbx);
3775 __ j(NegateCondition(is_string), &runtime);
3776
3777 // rax: string
3778 // rbx: instance type
3779 // Calculate length of sub string using the smi values.
3780 Label result_longer_than_two;
3781 __ movq(rcx, Operand(rsp, kToOffset));
3782 __ movq(rdx, Operand(rsp, kFromOffset));
Ben Murdochf87a2032010-10-22 12:50:53 +01003783 __ JumpUnlessBothNonNegativeSmi(rcx, rdx, &runtime);
Kristian Monsen80d68ea2010-09-08 11:05:35 +01003784
Kristian Monsen0d5e1162010-09-30 15:31:59 +01003785 __ SmiSub(rcx, rcx, rdx); // Overflow doesn't happen.
Kristian Monsen80d68ea2010-09-08 11:05:35 +01003786 __ cmpq(FieldOperand(rax, String::kLengthOffset), rcx);
3787 Label return_rax;
3788 __ j(equal, &return_rax);
3789 // Special handling of sub-strings of length 1 and 2. One character strings
3790 // are handled in the runtime system (looked up in the single character
3791 // cache). Two character strings are looked for in the symbol cache.
3792 __ SmiToInteger32(rcx, rcx);
3793 __ cmpl(rcx, Immediate(2));
3794 __ j(greater, &result_longer_than_two);
3795 __ j(less, &runtime);
3796
3797 // Sub string of length 2 requested.
3798 // rax: string
3799 // rbx: instance type
3800 // rcx: sub string length (value is 2)
3801 // rdx: from index (smi)
3802 __ JumpIfInstanceTypeIsNotSequentialAscii(rbx, rbx, &runtime);
3803
3804 // Get the two characters forming the sub string.
3805 __ SmiToInteger32(rdx, rdx); // From index is no longer smi.
3806 __ movzxbq(rbx, FieldOperand(rax, rdx, times_1, SeqAsciiString::kHeaderSize));
3807 __ movzxbq(rcx,
3808 FieldOperand(rax, rdx, times_1, SeqAsciiString::kHeaderSize + 1));
3809
3810 // Try to lookup two character string in symbol table.
3811 Label make_two_character_string;
3812 StringHelper::GenerateTwoCharacterSymbolTableProbe(
3813 masm, rbx, rcx, rax, rdx, rdi, r14, &make_two_character_string);
3814 __ ret(3 * kPointerSize);
3815
3816 __ bind(&make_two_character_string);
3817 // Setup registers for allocating the two character string.
3818 __ movq(rax, Operand(rsp, kStringOffset));
3819 __ movq(rbx, FieldOperand(rax, HeapObject::kMapOffset));
3820 __ movzxbl(rbx, FieldOperand(rbx, Map::kInstanceTypeOffset));
3821 __ Set(rcx, 2);
3822
3823 __ bind(&result_longer_than_two);
3824
3825 // rax: string
3826 // rbx: instance type
3827 // rcx: result string length
3828 // Check for flat ascii string
3829 Label non_ascii_flat;
3830 __ JumpIfInstanceTypeIsNotSequentialAscii(rbx, rbx, &non_ascii_flat);
3831
3832 // Allocate the result.
3833 __ AllocateAsciiString(rax, rcx, rbx, rdx, rdi, &runtime);
3834
3835 // rax: result string
3836 // rcx: result string length
3837 __ movq(rdx, rsi); // esi used by following code.
3838 // Locate first character of result.
3839 __ lea(rdi, FieldOperand(rax, SeqAsciiString::kHeaderSize));
3840 // Load string argument and locate character of sub string start.
3841 __ movq(rsi, Operand(rsp, kStringOffset));
3842 __ movq(rbx, Operand(rsp, kFromOffset));
3843 {
3844 SmiIndex smi_as_index = masm->SmiToIndex(rbx, rbx, times_1);
3845 __ lea(rsi, Operand(rsi, smi_as_index.reg, smi_as_index.scale,
3846 SeqAsciiString::kHeaderSize - kHeapObjectTag));
3847 }
3848
3849 // rax: result string
3850 // rcx: result length
3851 // rdx: original value of rsi
3852 // rdi: first character of result
3853 // rsi: character of sub string start
3854 StringHelper::GenerateCopyCharactersREP(masm, rdi, rsi, rcx, true);
3855 __ movq(rsi, rdx); // Restore rsi.
3856 __ IncrementCounter(&Counters::sub_string_native, 1);
3857 __ ret(kArgumentsSize);
3858
3859 __ bind(&non_ascii_flat);
3860 // rax: string
3861 // rbx: instance type & kStringRepresentationMask | kStringEncodingMask
3862 // rcx: result string length
3863 // Check for sequential two byte string
3864 __ cmpb(rbx, Immediate(kSeqStringTag | kTwoByteStringTag));
3865 __ j(not_equal, &runtime);
3866
3867 // Allocate the result.
3868 __ AllocateTwoByteString(rax, rcx, rbx, rdx, rdi, &runtime);
3869
3870 // rax: result string
3871 // rcx: result string length
3872 __ movq(rdx, rsi); // esi used by following code.
3873 // Locate first character of result.
3874 __ lea(rdi, FieldOperand(rax, SeqTwoByteString::kHeaderSize));
3875 // Load string argument and locate character of sub string start.
3876 __ movq(rsi, Operand(rsp, kStringOffset));
3877 __ movq(rbx, Operand(rsp, kFromOffset));
3878 {
3879 SmiIndex smi_as_index = masm->SmiToIndex(rbx, rbx, times_2);
3880 __ lea(rsi, Operand(rsi, smi_as_index.reg, smi_as_index.scale,
3881 SeqAsciiString::kHeaderSize - kHeapObjectTag));
3882 }
3883
3884 // rax: result string
3885 // rcx: result length
3886 // rdx: original value of rsi
3887 // rdi: first character of result
3888 // rsi: character of sub string start
3889 StringHelper::GenerateCopyCharactersREP(masm, rdi, rsi, rcx, false);
3890 __ movq(rsi, rdx); // Restore esi.
3891
3892 __ bind(&return_rax);
3893 __ IncrementCounter(&Counters::sub_string_native, 1);
3894 __ ret(kArgumentsSize);
3895
3896 // Just jump to runtime to create the sub string.
3897 __ bind(&runtime);
3898 __ TailCallRuntime(Runtime::kSubString, 3, 1);
3899}
3900
3901
3902void StringCompareStub::GenerateCompareFlatAsciiStrings(MacroAssembler* masm,
3903 Register left,
3904 Register right,
3905 Register scratch1,
3906 Register scratch2,
3907 Register scratch3,
3908 Register scratch4) {
3909 // Ensure that you can always subtract a string length from a non-negative
3910 // number (e.g. another length).
3911 STATIC_ASSERT(String::kMaxLength < 0x7fffffff);
3912
3913 // Find minimum length and length difference.
3914 __ movq(scratch1, FieldOperand(left, String::kLengthOffset));
3915 __ movq(scratch4, scratch1);
3916 __ SmiSub(scratch4,
3917 scratch4,
Kristian Monsen0d5e1162010-09-30 15:31:59 +01003918 FieldOperand(right, String::kLengthOffset));
Kristian Monsen80d68ea2010-09-08 11:05:35 +01003919 // Register scratch4 now holds left.length - right.length.
3920 const Register length_difference = scratch4;
Kristian Monsen0d5e1162010-09-30 15:31:59 +01003921 NearLabel left_shorter;
Kristian Monsen80d68ea2010-09-08 11:05:35 +01003922 __ j(less, &left_shorter);
3923 // The right string isn't longer that the left one.
3924 // Get the right string's length by subtracting the (non-negative) difference
3925 // from the left string's length.
Kristian Monsen0d5e1162010-09-30 15:31:59 +01003926 __ SmiSub(scratch1, scratch1, length_difference);
Kristian Monsen80d68ea2010-09-08 11:05:35 +01003927 __ bind(&left_shorter);
3928 // Register scratch1 now holds Min(left.length, right.length).
3929 const Register min_length = scratch1;
3930
Kristian Monsen0d5e1162010-09-30 15:31:59 +01003931 NearLabel compare_lengths;
Kristian Monsen80d68ea2010-09-08 11:05:35 +01003932 // If min-length is zero, go directly to comparing lengths.
3933 __ SmiTest(min_length);
3934 __ j(zero, &compare_lengths);
3935
3936 __ SmiToInteger32(min_length, min_length);
3937
3938 // Registers scratch2 and scratch3 are free.
Kristian Monsen0d5e1162010-09-30 15:31:59 +01003939 NearLabel result_not_equal;
Kristian Monsen80d68ea2010-09-08 11:05:35 +01003940 Label loop;
3941 {
3942 // Check characters 0 .. min_length - 1 in a loop.
3943 // Use scratch3 as loop index, min_length as limit and scratch2
3944 // for computation.
3945 const Register index = scratch3;
3946 __ movl(index, Immediate(0)); // Index into strings.
3947 __ bind(&loop);
3948 // Compare characters.
3949 // TODO(lrn): Could we load more than one character at a time?
3950 __ movb(scratch2, FieldOperand(left,
3951 index,
3952 times_1,
3953 SeqAsciiString::kHeaderSize));
3954 // Increment index and use -1 modifier on next load to give
3955 // the previous load extra time to complete.
3956 __ addl(index, Immediate(1));
3957 __ cmpb(scratch2, FieldOperand(right,
3958 index,
3959 times_1,
3960 SeqAsciiString::kHeaderSize - 1));
3961 __ j(not_equal, &result_not_equal);
3962 __ cmpl(index, min_length);
3963 __ j(not_equal, &loop);
3964 }
3965 // Completed loop without finding different characters.
3966 // Compare lengths (precomputed).
3967 __ bind(&compare_lengths);
3968 __ SmiTest(length_difference);
3969 __ j(not_zero, &result_not_equal);
3970
3971 // Result is EQUAL.
3972 __ Move(rax, Smi::FromInt(EQUAL));
3973 __ ret(0);
3974
Kristian Monsen0d5e1162010-09-30 15:31:59 +01003975 NearLabel result_greater;
Kristian Monsen80d68ea2010-09-08 11:05:35 +01003976 __ bind(&result_not_equal);
3977 // Unequal comparison of left to right, either character or length.
3978 __ j(greater, &result_greater);
3979
3980 // Result is LESS.
3981 __ Move(rax, Smi::FromInt(LESS));
3982 __ ret(0);
3983
3984 // Result is GREATER.
3985 __ bind(&result_greater);
3986 __ Move(rax, Smi::FromInt(GREATER));
3987 __ ret(0);
3988}
3989
3990
3991void StringCompareStub::Generate(MacroAssembler* masm) {
3992 Label runtime;
3993
3994 // Stack frame on entry.
3995 // rsp[0]: return address
3996 // rsp[8]: right string
3997 // rsp[16]: left string
3998
3999 __ movq(rdx, Operand(rsp, 2 * kPointerSize)); // left
4000 __ movq(rax, Operand(rsp, 1 * kPointerSize)); // right
4001
4002 // Check for identity.
Kristian Monsen0d5e1162010-09-30 15:31:59 +01004003 NearLabel not_same;
Kristian Monsen80d68ea2010-09-08 11:05:35 +01004004 __ cmpq(rdx, rax);
4005 __ j(not_equal, &not_same);
4006 __ Move(rax, Smi::FromInt(EQUAL));
4007 __ IncrementCounter(&Counters::string_compare_native, 1);
4008 __ ret(2 * kPointerSize);
4009
4010 __ bind(&not_same);
4011
4012 // Check that both are sequential ASCII strings.
4013 __ JumpIfNotBothSequentialAsciiStrings(rdx, rax, rcx, rbx, &runtime);
4014
4015 // Inline comparison of ascii strings.
4016 __ IncrementCounter(&Counters::string_compare_native, 1);
4017 // Drop arguments from the stack
4018 __ pop(rcx);
4019 __ addq(rsp, Immediate(2 * kPointerSize));
4020 __ push(rcx);
4021 GenerateCompareFlatAsciiStrings(masm, rdx, rax, rcx, rbx, rdi, r8);
4022
4023 // Call the runtime; it returns -1 (less), 0 (equal), or 1 (greater)
4024 // tagged as a small integer.
4025 __ bind(&runtime);
4026 __ TailCallRuntime(Runtime::kStringCompare, 2, 1);
4027}
4028
4029#undef __
4030
4031} } // namespace v8::internal
4032
4033#endif // V8_TARGET_ARCH_X64