blob: dea0b63ba5bd1ac98a5b7c7a831e20e5efb61bd4 [file] [log] [blame]
Leon Clarked91b9f72010-01-27 17:25:45 +00001// Copyright 2010 the V8 project authors. All rights reserved.
Steve Blocka7e24c12009-10-30 11:49:00 +00002// 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#include "bootstrapper.h"
31#include "codegen-inl.h"
Steve Blockd0582a62009-12-15 09:54:21 +000032#include "compiler.h"
Steve Blocka7e24c12009-10-30 11:49:00 +000033#include "debug.h"
Steve Block6ded16b2010-05-10 14:33:55 +010034#include "ic-inl.h"
35#include "jsregexp.h"
Steve Blocka7e24c12009-10-30 11:49:00 +000036#include "parser.h"
Steve Block6ded16b2010-05-10 14:33:55 +010037#include "regexp-macro-assembler.h"
38#include "regexp-stack.h"
Steve Blocka7e24c12009-10-30 11:49:00 +000039#include "register-allocator-inl.h"
40#include "runtime.h"
41#include "scopes.h"
Steve Block6ded16b2010-05-10 14:33:55 +010042#include "virtual-frame-inl.h"
Steve Blocka7e24c12009-10-30 11:49:00 +000043
44namespace v8 {
45namespace internal {
46
47#define __ ACCESS_MASM(masm_)
48
49static void EmitIdenticalObjectComparison(MacroAssembler* masm,
50 Label* slow,
Leon Clarkee46be812010-01-19 14:06:41 +000051 Condition cc,
52 bool never_nan_nan);
Steve Blocka7e24c12009-10-30 11:49:00 +000053static void EmitSmiNonsmiComparison(MacroAssembler* masm,
Leon Clarkee46be812010-01-19 14:06:41 +000054 Label* lhs_not_nan,
Steve Blocka7e24c12009-10-30 11:49:00 +000055 Label* slow,
56 bool strict);
57static void EmitTwoNonNanDoubleComparison(MacroAssembler* masm, Condition cc);
58static void EmitStrictTwoHeapObjectCompare(MacroAssembler* masm);
59static void MultiplyByKnownInt(MacroAssembler* masm,
60 Register source,
61 Register destination,
62 int known_int);
63static bool IsEasyToMultiplyBy(int x);
64
65
66
67// -------------------------------------------------------------------------
68// Platform-specific DeferredCode functions.
69
70void DeferredCode::SaveRegisters() {
71 for (int i = 0; i < RegisterAllocator::kNumRegisters; i++) {
72 int action = registers_[i];
73 if (action == kPush) {
74 __ push(RegisterAllocator::ToRegister(i));
75 } else if (action != kIgnore && (action & kSyncedFlag) == 0) {
76 __ str(RegisterAllocator::ToRegister(i), MemOperand(fp, action));
77 }
78 }
79}
80
81
82void DeferredCode::RestoreRegisters() {
83 // Restore registers in reverse order due to the stack.
84 for (int i = RegisterAllocator::kNumRegisters - 1; i >= 0; i--) {
85 int action = registers_[i];
86 if (action == kPush) {
87 __ pop(RegisterAllocator::ToRegister(i));
88 } else if (action != kIgnore) {
89 action &= ~kSyncedFlag;
90 __ ldr(RegisterAllocator::ToRegister(i), MemOperand(fp, action));
91 }
92 }
93}
94
95
96// -------------------------------------------------------------------------
97// CodeGenState implementation.
98
99CodeGenState::CodeGenState(CodeGenerator* owner)
100 : owner_(owner),
Steve Blocka7e24c12009-10-30 11:49:00 +0000101 true_target_(NULL),
102 false_target_(NULL),
103 previous_(NULL) {
104 owner_->set_state(this);
105}
106
107
108CodeGenState::CodeGenState(CodeGenerator* owner,
Steve Blocka7e24c12009-10-30 11:49:00 +0000109 JumpTarget* true_target,
110 JumpTarget* false_target)
111 : owner_(owner),
Steve Blocka7e24c12009-10-30 11:49:00 +0000112 true_target_(true_target),
113 false_target_(false_target),
114 previous_(owner->state()) {
115 owner_->set_state(this);
116}
117
118
119CodeGenState::~CodeGenState() {
120 ASSERT(owner_->state() == this);
121 owner_->set_state(previous_);
122}
123
124
125// -------------------------------------------------------------------------
126// CodeGenerator implementation
127
Andrei Popescu31002712010-02-23 13:46:05 +0000128CodeGenerator::CodeGenerator(MacroAssembler* masm)
129 : deferred_(8),
Leon Clarke4515c472010-02-03 11:58:03 +0000130 masm_(masm),
Andrei Popescu31002712010-02-23 13:46:05 +0000131 info_(NULL),
Steve Blocka7e24c12009-10-30 11:49:00 +0000132 frame_(NULL),
133 allocator_(NULL),
134 cc_reg_(al),
135 state_(NULL),
Steve Block6ded16b2010-05-10 14:33:55 +0100136 loop_nesting_(0),
Steve Blocka7e24c12009-10-30 11:49:00 +0000137 function_return_is_shadowed_(false) {
138}
139
140
141// Calling conventions:
142// fp: caller's frame pointer
143// sp: stack pointer
144// r1: called JS function
145// cp: callee's context
146
Andrei Popescu402d9372010-02-26 13:31:12 +0000147void CodeGenerator::Generate(CompilationInfo* info) {
Steve Blockd0582a62009-12-15 09:54:21 +0000148 // Record the position for debugging purposes.
Andrei Popescu31002712010-02-23 13:46:05 +0000149 CodeForFunctionPosition(info->function());
Steve Block6ded16b2010-05-10 14:33:55 +0100150 Comment cmnt(masm_, "[ function compiled by virtual frame code generator");
Steve Blocka7e24c12009-10-30 11:49:00 +0000151
152 // Initialize state.
Andrei Popescu31002712010-02-23 13:46:05 +0000153 info_ = info;
Steve Blocka7e24c12009-10-30 11:49:00 +0000154 ASSERT(allocator_ == NULL);
155 RegisterAllocator register_allocator(this);
156 allocator_ = &register_allocator;
157 ASSERT(frame_ == NULL);
158 frame_ = new VirtualFrame();
159 cc_reg_ = al;
Steve Block6ded16b2010-05-10 14:33:55 +0100160
161 // Adjust for function-level loop nesting.
162 ASSERT_EQ(0, loop_nesting_);
163 loop_nesting_ = info->loop_nesting();
164
Steve Blocka7e24c12009-10-30 11:49:00 +0000165 {
166 CodeGenState state(this);
167
168 // Entry:
169 // Stack: receiver, arguments
170 // lr: return address
171 // fp: caller's frame pointer
172 // sp: stack pointer
173 // r1: called JS function
174 // cp: callee's context
175 allocator_->Initialize();
Leon Clarke4515c472010-02-03 11:58:03 +0000176
Steve Blocka7e24c12009-10-30 11:49:00 +0000177#ifdef DEBUG
178 if (strlen(FLAG_stop_at) > 0 &&
Andrei Popescu31002712010-02-23 13:46:05 +0000179 info->function()->name()->IsEqualTo(CStrVector(FLAG_stop_at))) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000180 frame_->SpillAll();
181 __ stop("stop-at");
182 }
183#endif
184
Andrei Popescu402d9372010-02-26 13:31:12 +0000185 if (info->mode() == CompilationInfo::PRIMARY) {
Leon Clarke4515c472010-02-03 11:58:03 +0000186 frame_->Enter();
187 // tos: code slot
188
189 // Allocate space for locals and initialize them. This also checks
190 // for stack overflow.
191 frame_->AllocateStackSlots();
192
Steve Block6ded16b2010-05-10 14:33:55 +0100193 VirtualFrame::SpilledScope spilled_scope(frame_);
Andrei Popescu31002712010-02-23 13:46:05 +0000194 int heap_slots = scope()->num_heap_slots();
Leon Clarke4515c472010-02-03 11:58:03 +0000195 if (heap_slots > 0) {
196 // Allocate local context.
197 // Get outer context and create a new context based on it.
198 __ ldr(r0, frame_->Function());
199 frame_->EmitPush(r0);
200 if (heap_slots <= FastNewContextStub::kMaximumSlots) {
201 FastNewContextStub stub(heap_slots);
202 frame_->CallStub(&stub, 1);
203 } else {
204 frame_->CallRuntime(Runtime::kNewContext, 1);
205 }
206
207#ifdef DEBUG
208 JumpTarget verified_true;
Steve Block6ded16b2010-05-10 14:33:55 +0100209 __ cmp(r0, cp);
Leon Clarke4515c472010-02-03 11:58:03 +0000210 verified_true.Branch(eq);
211 __ stop("NewContext: r0 is expected to be the same as cp");
212 verified_true.Bind();
213#endif
214 // Update context local.
215 __ str(cp, frame_->Context());
216 }
217
218 // TODO(1241774): Improve this code:
219 // 1) only needed if we have a context
220 // 2) no need to recompute context ptr every single time
221 // 3) don't copy parameter operand code from SlotOperand!
222 {
223 Comment cmnt2(masm_, "[ copy context parameters into .context");
Leon Clarke4515c472010-02-03 11:58:03 +0000224 // Note that iteration order is relevant here! If we have the same
225 // parameter twice (e.g., function (x, y, x)), and that parameter
226 // needs to be copied into the context, it must be the last argument
227 // passed to the parameter that needs to be copied. This is a rare
228 // case so we don't check for it, instead we rely on the copying
229 // order: such a parameter is copied repeatedly into the same
230 // context location and thus the last value is what is seen inside
231 // the function.
Andrei Popescu31002712010-02-23 13:46:05 +0000232 for (int i = 0; i < scope()->num_parameters(); i++) {
233 Variable* par = scope()->parameter(i);
Leon Clarke4515c472010-02-03 11:58:03 +0000234 Slot* slot = par->slot();
235 if (slot != NULL && slot->type() == Slot::CONTEXT) {
Andrei Popescu31002712010-02-23 13:46:05 +0000236 ASSERT(!scope()->is_global_scope()); // No params in global scope.
Leon Clarke4515c472010-02-03 11:58:03 +0000237 __ ldr(r1, frame_->ParameterAt(i));
238 // Loads r2 with context; used below in RecordWrite.
239 __ str(r1, SlotOperand(slot, r2));
240 // Load the offset into r3.
241 int slot_offset =
242 FixedArray::kHeaderSize + slot->index() * kPointerSize;
243 __ mov(r3, Operand(slot_offset));
244 __ RecordWrite(r2, r3, r1);
245 }
246 }
247 }
248
249 // Store the arguments object. This must happen after context
Steve Block6ded16b2010-05-10 14:33:55 +0100250 // initialization because the arguments object may be stored in
251 // the context.
252 if (ArgumentsMode() != NO_ARGUMENTS_ALLOCATION) {
253 StoreArgumentsObject(true);
Leon Clarke4515c472010-02-03 11:58:03 +0000254 }
255
256 // Initialize ThisFunction reference if present.
Andrei Popescu31002712010-02-23 13:46:05 +0000257 if (scope()->is_function_scope() && scope()->function() != NULL) {
Leon Clarke4515c472010-02-03 11:58:03 +0000258 __ mov(ip, Operand(Factory::the_hole_value()));
259 frame_->EmitPush(ip);
Andrei Popescu31002712010-02-23 13:46:05 +0000260 StoreToSlot(scope()->function()->slot(), NOT_CONST_INIT);
Leon Clarke4515c472010-02-03 11:58:03 +0000261 }
262 } else {
263 // When used as the secondary compiler for splitting, r1, cp,
264 // fp, and lr have been pushed on the stack. Adjust the virtual
265 // frame to match this state.
266 frame_->Adjust(4);
Andrei Popescu402d9372010-02-26 13:31:12 +0000267
268 // Bind all the bailout labels to the beginning of the function.
269 List<CompilationInfo::Bailout*>* bailouts = info->bailouts();
270 for (int i = 0; i < bailouts->length(); i++) {
271 __ bind(bailouts->at(i)->label());
272 }
Leon Clarke4515c472010-02-03 11:58:03 +0000273 }
274
Steve Blocka7e24c12009-10-30 11:49:00 +0000275 // Initialize the function return target after the locals are set
276 // up, because it needs the expected frame height from the frame.
277 function_return_.set_direction(JumpTarget::BIDIRECTIONAL);
278 function_return_is_shadowed_ = false;
279
Steve Blocka7e24c12009-10-30 11:49:00 +0000280 // Generate code to 'execute' declarations and initialize functions
281 // (source elements). In case of an illegal redeclaration we need to
282 // handle that instead of processing the declarations.
Andrei Popescu31002712010-02-23 13:46:05 +0000283 if (scope()->HasIllegalRedeclaration()) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000284 Comment cmnt(masm_, "[ illegal redeclarations");
Andrei Popescu31002712010-02-23 13:46:05 +0000285 scope()->VisitIllegalRedeclaration(this);
Steve Blocka7e24c12009-10-30 11:49:00 +0000286 } else {
287 Comment cmnt(masm_, "[ declarations");
Andrei Popescu31002712010-02-23 13:46:05 +0000288 ProcessDeclarations(scope()->declarations());
Steve Blocka7e24c12009-10-30 11:49:00 +0000289 // Bail out if a stack-overflow exception occurred when processing
290 // declarations.
291 if (HasStackOverflow()) return;
292 }
293
294 if (FLAG_trace) {
295 frame_->CallRuntime(Runtime::kTraceEnter, 0);
296 // Ignore the return value.
297 }
298
299 // Compile the body of the function in a vanilla state. Don't
300 // bother compiling all the code if the scope has an illegal
301 // redeclaration.
Andrei Popescu31002712010-02-23 13:46:05 +0000302 if (!scope()->HasIllegalRedeclaration()) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000303 Comment cmnt(masm_, "[ function body");
304#ifdef DEBUG
305 bool is_builtin = Bootstrapper::IsActive();
306 bool should_trace =
307 is_builtin ? FLAG_trace_builtin_calls : FLAG_trace_calls;
308 if (should_trace) {
309 frame_->CallRuntime(Runtime::kDebugTrace, 0);
310 // Ignore the return value.
311 }
312#endif
Andrei Popescu31002712010-02-23 13:46:05 +0000313 VisitStatementsAndSpill(info->function()->body());
Steve Blocka7e24c12009-10-30 11:49:00 +0000314 }
315 }
316
317 // Generate the return sequence if necessary.
318 if (has_valid_frame() || function_return_.is_linked()) {
319 if (!function_return_.is_linked()) {
Andrei Popescu31002712010-02-23 13:46:05 +0000320 CodeForReturnPosition(info->function());
Steve Blocka7e24c12009-10-30 11:49:00 +0000321 }
322 // exit
323 // r0: result
324 // sp: stack pointer
325 // fp: frame pointer
326 // cp: callee's context
327 __ LoadRoot(r0, Heap::kUndefinedValueRootIndex);
328
329 function_return_.Bind();
330 if (FLAG_trace) {
331 // Push the return value on the stack as the parameter.
332 // Runtime::TraceExit returns the parameter as it is.
333 frame_->EmitPush(r0);
334 frame_->CallRuntime(Runtime::kTraceExit, 1);
335 }
336
Steve Block6ded16b2010-05-10 14:33:55 +0100337#ifdef DEBUG
Steve Blocka7e24c12009-10-30 11:49:00 +0000338 // Add a label for checking the size of the code used for returning.
339 Label check_exit_codesize;
340 masm_->bind(&check_exit_codesize);
Steve Block6ded16b2010-05-10 14:33:55 +0100341#endif
342 // Make sure that the constant pool is not emitted inside of the return
343 // sequence.
344 { Assembler::BlockConstPoolScope block_const_pool(masm_);
345 // Tear down the frame which will restore the caller's frame pointer and
346 // the link register.
347 frame_->Exit();
Steve Blocka7e24c12009-10-30 11:49:00 +0000348
Steve Block6ded16b2010-05-10 14:33:55 +0100349 // Here we use masm_-> instead of the __ macro to avoid the code coverage
350 // tool from instrumenting as we rely on the code size here.
351 int32_t sp_delta = (scope()->num_parameters() + 1) * kPointerSize;
352 masm_->add(sp, sp, Operand(sp_delta));
353 masm_->Jump(lr);
354
355#ifdef DEBUG
356 // Check that the size of the code used for returning matches what is
357 // expected by the debugger. If the sp_delts above cannot be encoded in
358 // the add instruction the add will generate two instructions.
359 int return_sequence_length =
360 masm_->InstructionsGeneratedSince(&check_exit_codesize);
361 CHECK(return_sequence_length == Assembler::kJSReturnSequenceLength ||
362 return_sequence_length == Assembler::kJSReturnSequenceLength + 1);
363#endif
Steve Blockd0582a62009-12-15 09:54:21 +0000364 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000365 }
366
Steve Block6ded16b2010-05-10 14:33:55 +0100367 // Adjust for function-level loop nesting.
368 ASSERT(loop_nesting_ == info->loop_nesting());
369 loop_nesting_ = 0;
370
Steve Blocka7e24c12009-10-30 11:49:00 +0000371 // Code generation state must be reset.
372 ASSERT(!has_cc());
373 ASSERT(state_ == NULL);
Steve Block6ded16b2010-05-10 14:33:55 +0100374 ASSERT(loop_nesting() == 0);
Steve Blocka7e24c12009-10-30 11:49:00 +0000375 ASSERT(!function_return_is_shadowed_);
376 function_return_.Unuse();
377 DeleteFrame();
378
379 // Process any deferred code using the register allocator.
380 if (!HasStackOverflow()) {
381 ProcessDeferred();
382 }
383
384 allocator_ = NULL;
Steve Blocka7e24c12009-10-30 11:49:00 +0000385}
386
387
388MemOperand CodeGenerator::SlotOperand(Slot* slot, Register tmp) {
389 // Currently, this assertion will fail if we try to assign to
390 // a constant variable that is constant because it is read-only
391 // (such as the variable referring to a named function expression).
392 // We need to implement assignments to read-only variables.
393 // Ideally, we should do this during AST generation (by converting
394 // such assignments into expression statements); however, in general
395 // we may not be able to make the decision until past AST generation,
396 // that is when the entire program is known.
397 ASSERT(slot != NULL);
398 int index = slot->index();
399 switch (slot->type()) {
400 case Slot::PARAMETER:
401 return frame_->ParameterAt(index);
402
403 case Slot::LOCAL:
404 return frame_->LocalAt(index);
405
406 case Slot::CONTEXT: {
407 // Follow the context chain if necessary.
408 ASSERT(!tmp.is(cp)); // do not overwrite context register
409 Register context = cp;
410 int chain_length = scope()->ContextChainLength(slot->var()->scope());
411 for (int i = 0; i < chain_length; i++) {
412 // Load the closure.
413 // (All contexts, even 'with' contexts, have a closure,
414 // and it is the same for all contexts inside a function.
415 // There is no need to go to the function context first.)
416 __ ldr(tmp, ContextOperand(context, Context::CLOSURE_INDEX));
417 // Load the function context (which is the incoming, outer context).
418 __ ldr(tmp, FieldMemOperand(tmp, JSFunction::kContextOffset));
419 context = tmp;
420 }
421 // We may have a 'with' context now. Get the function context.
422 // (In fact this mov may never be the needed, since the scope analysis
423 // may not permit a direct context access in this case and thus we are
424 // always at a function context. However it is safe to dereference be-
425 // cause the function context of a function context is itself. Before
426 // deleting this mov we should try to create a counter-example first,
427 // though...)
428 __ ldr(tmp, ContextOperand(context, Context::FCONTEXT_INDEX));
429 return ContextOperand(tmp, index);
430 }
431
432 default:
433 UNREACHABLE();
434 return MemOperand(r0, 0);
435 }
436}
437
438
439MemOperand CodeGenerator::ContextSlotOperandCheckExtensions(
440 Slot* slot,
441 Register tmp,
442 Register tmp2,
443 JumpTarget* slow) {
444 ASSERT(slot->type() == Slot::CONTEXT);
445 Register context = cp;
446
447 for (Scope* s = scope(); s != slot->var()->scope(); s = s->outer_scope()) {
448 if (s->num_heap_slots() > 0) {
449 if (s->calls_eval()) {
450 // Check that extension is NULL.
451 __ ldr(tmp2, ContextOperand(context, Context::EXTENSION_INDEX));
452 __ tst(tmp2, tmp2);
453 slow->Branch(ne);
454 }
455 __ ldr(tmp, ContextOperand(context, Context::CLOSURE_INDEX));
456 __ ldr(tmp, FieldMemOperand(tmp, JSFunction::kContextOffset));
457 context = tmp;
458 }
459 }
460 // Check that last extension is NULL.
461 __ ldr(tmp2, ContextOperand(context, Context::EXTENSION_INDEX));
462 __ tst(tmp2, tmp2);
463 slow->Branch(ne);
464 __ ldr(tmp, ContextOperand(context, Context::FCONTEXT_INDEX));
465 return ContextOperand(tmp, slot->index());
466}
467
468
469// Loads a value on TOS. If it is a boolean value, the result may have been
470// (partially) translated into branches, or it may have set the condition
471// code register. If force_cc is set, the value is forced to set the
472// condition code register and no value is pushed. If the condition code
473// register was set, has_cc() is true and cc_reg_ contains the condition to
474// test for 'true'.
475void CodeGenerator::LoadCondition(Expression* x,
Steve Blocka7e24c12009-10-30 11:49:00 +0000476 JumpTarget* true_target,
477 JumpTarget* false_target,
478 bool force_cc) {
479 ASSERT(!has_cc());
480 int original_height = frame_->height();
481
Steve Blockd0582a62009-12-15 09:54:21 +0000482 { CodeGenState new_state(this, true_target, false_target);
Steve Blocka7e24c12009-10-30 11:49:00 +0000483 Visit(x);
484
485 // If we hit a stack overflow, we may not have actually visited
486 // the expression. In that case, we ensure that we have a
487 // valid-looking frame state because we will continue to generate
488 // code as we unwind the C++ stack.
489 //
490 // It's possible to have both a stack overflow and a valid frame
491 // state (eg, a subexpression overflowed, visiting it returned
492 // with a dummied frame state, and visiting this expression
493 // returned with a normal-looking state).
494 if (HasStackOverflow() &&
495 has_valid_frame() &&
496 !has_cc() &&
497 frame_->height() == original_height) {
Steve Block6ded16b2010-05-10 14:33:55 +0100498 frame_->SpillAll();
Steve Blocka7e24c12009-10-30 11:49:00 +0000499 true_target->Jump();
500 }
501 }
502 if (force_cc && frame_ != NULL && !has_cc()) {
503 // Convert the TOS value to a boolean in the condition code register.
504 ToBoolean(true_target, false_target);
505 }
506 ASSERT(!force_cc || !has_valid_frame() || has_cc());
507 ASSERT(!has_valid_frame() ||
508 (has_cc() && frame_->height() == original_height) ||
509 (!has_cc() && frame_->height() == original_height + 1));
510}
511
512
Steve Blockd0582a62009-12-15 09:54:21 +0000513void CodeGenerator::Load(Expression* expr) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000514#ifdef DEBUG
515 int original_height = frame_->height();
516#endif
517 JumpTarget true_target;
518 JumpTarget false_target;
Steve Blockd0582a62009-12-15 09:54:21 +0000519 LoadCondition(expr, &true_target, &false_target, false);
Steve Blocka7e24c12009-10-30 11:49:00 +0000520
521 if (has_cc()) {
522 // Convert cc_reg_ into a boolean value.
Steve Block6ded16b2010-05-10 14:33:55 +0100523 VirtualFrame::SpilledScope scope(frame_);
Steve Blocka7e24c12009-10-30 11:49:00 +0000524 JumpTarget loaded;
525 JumpTarget materialize_true;
526 materialize_true.Branch(cc_reg_);
527 __ LoadRoot(r0, Heap::kFalseValueRootIndex);
528 frame_->EmitPush(r0);
529 loaded.Jump();
530 materialize_true.Bind();
531 __ LoadRoot(r0, Heap::kTrueValueRootIndex);
532 frame_->EmitPush(r0);
533 loaded.Bind();
534 cc_reg_ = al;
535 }
536
537 if (true_target.is_linked() || false_target.is_linked()) {
Steve Block6ded16b2010-05-10 14:33:55 +0100538 VirtualFrame::SpilledScope scope(frame_);
Steve Blocka7e24c12009-10-30 11:49:00 +0000539 // We have at least one condition value that has been "translated"
540 // into a branch, thus it needs to be loaded explicitly.
541 JumpTarget loaded;
542 if (frame_ != NULL) {
543 loaded.Jump(); // Don't lose the current TOS.
544 }
545 bool both = true_target.is_linked() && false_target.is_linked();
546 // Load "true" if necessary.
547 if (true_target.is_linked()) {
548 true_target.Bind();
549 __ LoadRoot(r0, Heap::kTrueValueRootIndex);
550 frame_->EmitPush(r0);
551 }
552 // If both "true" and "false" need to be loaded jump across the code for
553 // "false".
554 if (both) {
555 loaded.Jump();
556 }
557 // Load "false" if necessary.
558 if (false_target.is_linked()) {
559 false_target.Bind();
560 __ LoadRoot(r0, Heap::kFalseValueRootIndex);
561 frame_->EmitPush(r0);
562 }
563 // A value is loaded on all paths reaching this point.
564 loaded.Bind();
565 }
566 ASSERT(has_valid_frame());
567 ASSERT(!has_cc());
Steve Block6ded16b2010-05-10 14:33:55 +0100568 ASSERT_EQ(original_height + 1, frame_->height());
Steve Blocka7e24c12009-10-30 11:49:00 +0000569}
570
571
572void CodeGenerator::LoadGlobal() {
Steve Block6ded16b2010-05-10 14:33:55 +0100573 Register reg = frame_->GetTOSRegister();
574 __ ldr(reg, GlobalObject());
575 frame_->EmitPush(reg);
Steve Blocka7e24c12009-10-30 11:49:00 +0000576}
577
578
579void CodeGenerator::LoadGlobalReceiver(Register scratch) {
Steve Block6ded16b2010-05-10 14:33:55 +0100580 VirtualFrame::SpilledScope spilled_scope(frame_);
Steve Blocka7e24c12009-10-30 11:49:00 +0000581 __ ldr(scratch, ContextOperand(cp, Context::GLOBAL_INDEX));
582 __ ldr(scratch,
583 FieldMemOperand(scratch, GlobalObject::kGlobalReceiverOffset));
584 frame_->EmitPush(scratch);
585}
586
587
Steve Block6ded16b2010-05-10 14:33:55 +0100588ArgumentsAllocationMode CodeGenerator::ArgumentsMode() {
589 if (scope()->arguments() == NULL) return NO_ARGUMENTS_ALLOCATION;
590 ASSERT(scope()->arguments_shadow() != NULL);
591 // We don't want to do lazy arguments allocation for functions that
592 // have heap-allocated contexts, because it interfers with the
593 // uninitialized const tracking in the context objects.
594 return (scope()->num_heap_slots() > 0)
595 ? EAGER_ARGUMENTS_ALLOCATION
596 : LAZY_ARGUMENTS_ALLOCATION;
597}
598
599
600void CodeGenerator::StoreArgumentsObject(bool initial) {
601 VirtualFrame::SpilledScope spilled_scope(frame_);
602
603 ArgumentsAllocationMode mode = ArgumentsMode();
604 ASSERT(mode != NO_ARGUMENTS_ALLOCATION);
605
606 Comment cmnt(masm_, "[ store arguments object");
607 if (mode == LAZY_ARGUMENTS_ALLOCATION && initial) {
608 // When using lazy arguments allocation, we store the hole value
609 // as a sentinel indicating that the arguments object hasn't been
610 // allocated yet.
611 __ LoadRoot(ip, Heap::kTheHoleValueRootIndex);
612 frame_->EmitPush(ip);
613 } else {
614 ArgumentsAccessStub stub(ArgumentsAccessStub::NEW_OBJECT);
615 __ ldr(r2, frame_->Function());
616 // The receiver is below the arguments, the return address, and the
617 // frame pointer on the stack.
618 const int kReceiverDisplacement = 2 + scope()->num_parameters();
619 __ add(r1, fp, Operand(kReceiverDisplacement * kPointerSize));
620 __ mov(r0, Operand(Smi::FromInt(scope()->num_parameters())));
621 frame_->Adjust(3);
622 __ Push(r2, r1, r0);
623 frame_->CallStub(&stub, 3);
624 frame_->EmitPush(r0);
625 }
626
627 Variable* arguments = scope()->arguments()->var();
628 Variable* shadow = scope()->arguments_shadow()->var();
629 ASSERT(arguments != NULL && arguments->slot() != NULL);
630 ASSERT(shadow != NULL && shadow->slot() != NULL);
631 JumpTarget done;
632 if (mode == LAZY_ARGUMENTS_ALLOCATION && !initial) {
633 // We have to skip storing into the arguments slot if it has
634 // already been written to. This can happen if the a function
635 // has a local variable named 'arguments'.
636 LoadFromSlot(scope()->arguments()->var()->slot(), NOT_INSIDE_TYPEOF);
637 frame_->EmitPop(r0);
638 __ LoadRoot(ip, Heap::kTheHoleValueRootIndex);
639 __ cmp(r0, ip);
640 done.Branch(ne);
641 }
642 StoreToSlot(arguments->slot(), NOT_CONST_INIT);
643 if (mode == LAZY_ARGUMENTS_ALLOCATION) done.Bind();
644 StoreToSlot(shadow->slot(), NOT_CONST_INIT);
645}
646
647
Steve Blockd0582a62009-12-15 09:54:21 +0000648void CodeGenerator::LoadTypeofExpression(Expression* expr) {
649 // Special handling of identifiers as subexpressions of typeof.
Steve Block6ded16b2010-05-10 14:33:55 +0100650 VirtualFrame::SpilledScope spilled_scope(frame_);
Steve Blockd0582a62009-12-15 09:54:21 +0000651 Variable* variable = expr->AsVariableProxy()->AsVariable();
Steve Blocka7e24c12009-10-30 11:49:00 +0000652 if (variable != NULL && !variable->is_this() && variable->is_global()) {
Steve Blockd0582a62009-12-15 09:54:21 +0000653 // For a global variable we build the property reference
654 // <global>.<variable> and perform a (regular non-contextual) property
655 // load to make sure we do not get reference errors.
Steve Blocka7e24c12009-10-30 11:49:00 +0000656 Slot global(variable, Slot::CONTEXT, Context::GLOBAL_INDEX);
657 Literal key(variable->name());
Steve Blocka7e24c12009-10-30 11:49:00 +0000658 Property property(&global, &key, RelocInfo::kNoPosition);
Steve Blockd0582a62009-12-15 09:54:21 +0000659 Reference ref(this, &property);
Steve Block6ded16b2010-05-10 14:33:55 +0100660 ref.GetValue();
Steve Blockd0582a62009-12-15 09:54:21 +0000661 } else if (variable != NULL && variable->slot() != NULL) {
662 // For a variable that rewrites to a slot, we signal it is the immediate
663 // subexpression of a typeof.
Steve Block6ded16b2010-05-10 14:33:55 +0100664 LoadFromSlotCheckForArguments(variable->slot(), INSIDE_TYPEOF);
Steve Blockd0582a62009-12-15 09:54:21 +0000665 frame_->SpillAll();
Steve Blocka7e24c12009-10-30 11:49:00 +0000666 } else {
Steve Blockd0582a62009-12-15 09:54:21 +0000667 // Anything else can be handled normally.
668 LoadAndSpill(expr);
Steve Blocka7e24c12009-10-30 11:49:00 +0000669 }
670}
671
672
Leon Clarked91b9f72010-01-27 17:25:45 +0000673Reference::Reference(CodeGenerator* cgen,
674 Expression* expression,
675 bool persist_after_get)
676 : cgen_(cgen),
677 expression_(expression),
678 type_(ILLEGAL),
679 persist_after_get_(persist_after_get) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000680 cgen->LoadReference(this);
681}
682
683
684Reference::~Reference() {
Leon Clarked91b9f72010-01-27 17:25:45 +0000685 ASSERT(is_unloaded() || is_illegal());
Steve Blocka7e24c12009-10-30 11:49:00 +0000686}
687
688
689void CodeGenerator::LoadReference(Reference* ref) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000690 Comment cmnt(masm_, "[ LoadReference");
691 Expression* e = ref->expression();
692 Property* property = e->AsProperty();
693 Variable* var = e->AsVariableProxy()->AsVariable();
694
695 if (property != NULL) {
696 // The expression is either a property or a variable proxy that rewrites
697 // to a property.
Steve Block6ded16b2010-05-10 14:33:55 +0100698 Load(property->obj());
Leon Clarkee46be812010-01-19 14:06:41 +0000699 if (property->key()->IsPropertyName()) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000700 ref->set_type(Reference::NAMED);
701 } else {
Steve Block6ded16b2010-05-10 14:33:55 +0100702 Load(property->key());
Steve Blocka7e24c12009-10-30 11:49:00 +0000703 ref->set_type(Reference::KEYED);
704 }
705 } else if (var != NULL) {
706 // The expression is a variable proxy that does not rewrite to a
707 // property. Global variables are treated as named property references.
708 if (var->is_global()) {
709 LoadGlobal();
710 ref->set_type(Reference::NAMED);
711 } else {
712 ASSERT(var->slot() != NULL);
713 ref->set_type(Reference::SLOT);
714 }
715 } else {
716 // Anything else is a runtime error.
Steve Block6ded16b2010-05-10 14:33:55 +0100717 VirtualFrame::SpilledScope spilled_scope(frame_);
Steve Blocka7e24c12009-10-30 11:49:00 +0000718 LoadAndSpill(e);
719 frame_->CallRuntime(Runtime::kThrowReferenceError, 1);
720 }
721}
722
723
724void CodeGenerator::UnloadReference(Reference* ref) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000725 int size = ref->size();
Leon Clarked91b9f72010-01-27 17:25:45 +0000726 ref->set_unloaded();
Steve Block6ded16b2010-05-10 14:33:55 +0100727 if (size == 0) return;
728
729 // Pop a reference from the stack while preserving TOS.
730 VirtualFrame::RegisterAllocationScope scope(this);
731 Comment cmnt(masm_, "[ UnloadReference");
732 if (size > 0) {
733 Register tos = frame_->PopToRegister();
734 frame_->Drop(size);
735 frame_->EmitPush(tos);
736 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000737}
738
739
740// ECMA-262, section 9.2, page 30: ToBoolean(). Convert the given
741// register to a boolean in the condition code register. The code
742// may jump to 'false_target' in case the register converts to 'false'.
743void CodeGenerator::ToBoolean(JumpTarget* true_target,
744 JumpTarget* false_target) {
Steve Block6ded16b2010-05-10 14:33:55 +0100745 VirtualFrame::SpilledScope spilled_scope(frame_);
Steve Blocka7e24c12009-10-30 11:49:00 +0000746 // Note: The generated code snippet does not change stack variables.
747 // Only the condition code should be set.
748 frame_->EmitPop(r0);
749
750 // Fast case checks
751
752 // Check if the value is 'false'.
753 __ LoadRoot(ip, Heap::kFalseValueRootIndex);
754 __ cmp(r0, ip);
755 false_target->Branch(eq);
756
757 // Check if the value is 'true'.
758 __ LoadRoot(ip, Heap::kTrueValueRootIndex);
759 __ cmp(r0, ip);
760 true_target->Branch(eq);
761
762 // Check if the value is 'undefined'.
763 __ LoadRoot(ip, Heap::kUndefinedValueRootIndex);
764 __ cmp(r0, ip);
765 false_target->Branch(eq);
766
767 // Check if the value is a smi.
768 __ cmp(r0, Operand(Smi::FromInt(0)));
769 false_target->Branch(eq);
770 __ tst(r0, Operand(kSmiTagMask));
771 true_target->Branch(eq);
772
773 // Slow case: call the runtime.
774 frame_->EmitPush(r0);
775 frame_->CallRuntime(Runtime::kToBool, 1);
776 // Convert the result (r0) to a condition code.
777 __ LoadRoot(ip, Heap::kFalseValueRootIndex);
778 __ cmp(r0, ip);
779
780 cc_reg_ = ne;
781}
782
783
784void CodeGenerator::GenericBinaryOperation(Token::Value op,
785 OverwriteMode overwrite_mode,
786 int constant_rhs) {
Steve Block6ded16b2010-05-10 14:33:55 +0100787 VirtualFrame::SpilledScope spilled_scope(frame_);
Steve Blocka7e24c12009-10-30 11:49:00 +0000788 // sp[0] : y
789 // sp[1] : x
790 // result : r0
791
792 // Stub is entered with a call: 'return address' is in lr.
793 switch (op) {
Steve Block6ded16b2010-05-10 14:33:55 +0100794 case Token::ADD:
795 case Token::SUB:
796 case Token::MUL:
797 case Token::DIV:
798 case Token::MOD:
799 case Token::BIT_OR:
800 case Token::BIT_AND:
801 case Token::BIT_XOR:
802 case Token::SHL:
803 case Token::SHR:
804 case Token::SAR: {
805 frame_->EmitPop(r0); // r0 : y
806 frame_->EmitPop(r1); // r1 : x
807 GenericBinaryOpStub stub(op, overwrite_mode, r1, r0, constant_rhs);
808 frame_->CallStub(&stub, 0);
809 break;
810 }
811
812 case Token::COMMA:
813 frame_->EmitPop(r0);
814 // Simply discard left value.
815 frame_->Drop();
816 break;
817
818 default:
819 // Other cases should have been handled before this point.
820 UNREACHABLE();
821 break;
822 }
823}
824
825
826void CodeGenerator::VirtualFrameBinaryOperation(Token::Value op,
827 OverwriteMode overwrite_mode,
828 int constant_rhs) {
829 // top of virtual frame: y
830 // 2nd elt. on virtual frame : x
831 // result : top of virtual frame
832
833 // Stub is entered with a call: 'return address' is in lr.
834 switch (op) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000835 case Token::ADD: // fall through.
836 case Token::SUB: // fall through.
837 case Token::MUL:
838 case Token::DIV:
839 case Token::MOD:
840 case Token::BIT_OR:
841 case Token::BIT_AND:
842 case Token::BIT_XOR:
843 case Token::SHL:
844 case Token::SHR:
845 case Token::SAR: {
Steve Block6ded16b2010-05-10 14:33:55 +0100846 Register rhs = frame_->PopToRegister();
847 Register lhs = frame_->PopToRegister(rhs); // Don't pop to rhs register.
848 {
849 VirtualFrame::SpilledScope spilled_scope(frame_);
850 GenericBinaryOpStub stub(op, overwrite_mode, lhs, rhs, constant_rhs);
851 frame_->CallStub(&stub, 0);
852 }
853 frame_->EmitPush(r0);
Steve Blocka7e24c12009-10-30 11:49:00 +0000854 break;
855 }
856
Steve Block6ded16b2010-05-10 14:33:55 +0100857 case Token::COMMA: {
858 Register scratch = frame_->PopToRegister();
859 // Simply discard left value.
Steve Blocka7e24c12009-10-30 11:49:00 +0000860 frame_->Drop();
Steve Block6ded16b2010-05-10 14:33:55 +0100861 frame_->EmitPush(scratch);
Steve Blocka7e24c12009-10-30 11:49:00 +0000862 break;
Steve Block6ded16b2010-05-10 14:33:55 +0100863 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000864
865 default:
866 // Other cases should have been handled before this point.
867 UNREACHABLE();
868 break;
869 }
870}
871
872
873class DeferredInlineSmiOperation: public DeferredCode {
874 public:
875 DeferredInlineSmiOperation(Token::Value op,
876 int value,
877 bool reversed,
Steve Block6ded16b2010-05-10 14:33:55 +0100878 OverwriteMode overwrite_mode,
879 Register tos)
Steve Blocka7e24c12009-10-30 11:49:00 +0000880 : op_(op),
881 value_(value),
882 reversed_(reversed),
Steve Block6ded16b2010-05-10 14:33:55 +0100883 overwrite_mode_(overwrite_mode),
884 tos_register_(tos) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000885 set_comment("[ DeferredInlinedSmiOperation");
886 }
887
888 virtual void Generate();
889
890 private:
891 Token::Value op_;
892 int value_;
893 bool reversed_;
894 OverwriteMode overwrite_mode_;
Steve Block6ded16b2010-05-10 14:33:55 +0100895 Register tos_register_;
Steve Blocka7e24c12009-10-30 11:49:00 +0000896};
897
898
899void DeferredInlineSmiOperation::Generate() {
Steve Block6ded16b2010-05-10 14:33:55 +0100900 Register lhs = r1;
901 Register rhs = r0;
Steve Blocka7e24c12009-10-30 11:49:00 +0000902 switch (op_) {
903 case Token::ADD: {
904 // Revert optimistic add.
905 if (reversed_) {
Steve Block6ded16b2010-05-10 14:33:55 +0100906 __ sub(r0, tos_register_, Operand(Smi::FromInt(value_)));
Steve Blocka7e24c12009-10-30 11:49:00 +0000907 __ mov(r1, Operand(Smi::FromInt(value_)));
908 } else {
Steve Block6ded16b2010-05-10 14:33:55 +0100909 __ sub(r1, tos_register_, Operand(Smi::FromInt(value_)));
Steve Blocka7e24c12009-10-30 11:49:00 +0000910 __ mov(r0, Operand(Smi::FromInt(value_)));
911 }
912 break;
913 }
914
915 case Token::SUB: {
916 // Revert optimistic sub.
917 if (reversed_) {
Steve Block6ded16b2010-05-10 14:33:55 +0100918 __ rsb(r0, tos_register_, Operand(Smi::FromInt(value_)));
Steve Blocka7e24c12009-10-30 11:49:00 +0000919 __ mov(r1, Operand(Smi::FromInt(value_)));
920 } else {
Steve Block6ded16b2010-05-10 14:33:55 +0100921 __ add(r1, tos_register_, Operand(Smi::FromInt(value_)));
Steve Blocka7e24c12009-10-30 11:49:00 +0000922 __ mov(r0, Operand(Smi::FromInt(value_)));
923 }
924 break;
925 }
926
927 // For these operations there is no optimistic operation that needs to be
928 // reverted.
929 case Token::MUL:
930 case Token::MOD:
931 case Token::BIT_OR:
932 case Token::BIT_XOR:
933 case Token::BIT_AND: {
934 if (reversed_) {
Steve Block6ded16b2010-05-10 14:33:55 +0100935 if (tos_register_.is(r0)) {
936 __ mov(r1, Operand(Smi::FromInt(value_)));
937 } else {
938 ASSERT(tos_register_.is(r1));
939 __ mov(r0, Operand(Smi::FromInt(value_)));
940 lhs = r0;
941 rhs = r1;
942 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000943 } else {
Steve Block6ded16b2010-05-10 14:33:55 +0100944 if (tos_register_.is(r1)) {
945 __ mov(r0, Operand(Smi::FromInt(value_)));
946 } else {
947 ASSERT(tos_register_.is(r0));
948 __ mov(r1, Operand(Smi::FromInt(value_)));
949 lhs = r0;
950 rhs = r1;
951 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000952 }
953 break;
954 }
955
956 case Token::SHL:
957 case Token::SHR:
958 case Token::SAR: {
959 if (!reversed_) {
Steve Block6ded16b2010-05-10 14:33:55 +0100960 if (tos_register_.is(r1)) {
961 __ mov(r0, Operand(Smi::FromInt(value_)));
962 } else {
963 ASSERT(tos_register_.is(r0));
964 __ mov(r1, Operand(Smi::FromInt(value_)));
965 lhs = r0;
966 rhs = r1;
967 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000968 } else {
969 UNREACHABLE(); // Should have been handled in SmiOperation.
970 }
971 break;
972 }
973
974 default:
975 // Other cases should have been handled before this point.
976 UNREACHABLE();
977 break;
978 }
979
Steve Block6ded16b2010-05-10 14:33:55 +0100980 GenericBinaryOpStub stub(op_, overwrite_mode_, lhs, rhs, value_);
Steve Blocka7e24c12009-10-30 11:49:00 +0000981 __ CallStub(&stub);
Steve Block6ded16b2010-05-10 14:33:55 +0100982 // The generic stub returns its value in r0, but that's not
983 // necessarily what we want. We want whatever the inlined code
984 // expected, which is that the answer is in the same register as
985 // the operand was.
986 __ Move(tos_register_, r0);
Steve Blocka7e24c12009-10-30 11:49:00 +0000987}
988
989
990static bool PopCountLessThanEqual2(unsigned int x) {
991 x &= x - 1;
992 return (x & (x - 1)) == 0;
993}
994
995
996// Returns the index of the lowest bit set.
997static int BitPosition(unsigned x) {
998 int bit_posn = 0;
999 while ((x & 0xf) == 0) {
1000 bit_posn += 4;
1001 x >>= 4;
1002 }
1003 while ((x & 1) == 0) {
1004 bit_posn++;
1005 x >>= 1;
1006 }
1007 return bit_posn;
1008}
1009
1010
1011void CodeGenerator::SmiOperation(Token::Value op,
1012 Handle<Object> value,
1013 bool reversed,
1014 OverwriteMode mode) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001015 int int_value = Smi::cast(*value)->value();
1016
Steve Block6ded16b2010-05-10 14:33:55 +01001017 bool something_to_inline;
1018 switch (op) {
1019 case Token::ADD:
1020 case Token::SUB:
1021 case Token::BIT_AND:
1022 case Token::BIT_OR:
1023 case Token::BIT_XOR: {
1024 something_to_inline = true;
1025 break;
1026 }
1027 case Token::SHL:
1028 case Token::SHR:
1029 case Token::SAR: {
1030 if (reversed) {
1031 something_to_inline = false;
1032 } else {
1033 something_to_inline = true;
1034 }
1035 break;
1036 }
1037 case Token::MOD: {
1038 if (reversed || int_value < 2 || !IsPowerOf2(int_value)) {
1039 something_to_inline = false;
1040 } else {
1041 something_to_inline = true;
1042 }
1043 break;
1044 }
1045 case Token::MUL: {
1046 if (!IsEasyToMultiplyBy(int_value)) {
1047 something_to_inline = false;
1048 } else {
1049 something_to_inline = true;
1050 }
1051 break;
1052 }
1053 default: {
1054 something_to_inline = false;
1055 break;
1056 }
1057 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001058
Steve Block6ded16b2010-05-10 14:33:55 +01001059 if (!something_to_inline) {
1060 if (!reversed) {
1061 // Push the rhs onto the virtual frame by putting it in a TOS register.
1062 Register rhs = frame_->GetTOSRegister();
1063 __ mov(rhs, Operand(value));
1064 frame_->EmitPush(rhs);
1065 VirtualFrameBinaryOperation(op, mode, int_value);
1066 } else {
1067 // Pop the rhs, then push lhs and rhs in the right order. Only performs
1068 // at most one pop, the rest takes place in TOS registers.
1069 Register lhs = frame_->GetTOSRegister(); // Get reg for pushing.
1070 Register rhs = frame_->PopToRegister(lhs); // Don't use lhs for this.
1071 __ mov(lhs, Operand(value));
1072 frame_->EmitPush(lhs);
1073 frame_->EmitPush(rhs);
1074 VirtualFrameBinaryOperation(op, mode, kUnknownIntValue);
1075 }
1076 return;
1077 }
1078
1079 // We move the top of stack to a register (normally no move is invoved).
1080 Register tos = frame_->PopToRegister();
1081 // All other registers are spilled. The deferred code expects one argument
1082 // in a register and all other values are flushed to the stack. The
1083 // answer is returned in the same register that the top of stack argument was
1084 // in.
1085 frame_->SpillAll();
1086
Steve Blocka7e24c12009-10-30 11:49:00 +00001087 switch (op) {
1088 case Token::ADD: {
1089 DeferredCode* deferred =
Steve Block6ded16b2010-05-10 14:33:55 +01001090 new DeferredInlineSmiOperation(op, int_value, reversed, mode, tos);
Steve Blocka7e24c12009-10-30 11:49:00 +00001091
Steve Block6ded16b2010-05-10 14:33:55 +01001092 __ add(tos, tos, Operand(value), SetCC);
Steve Blocka7e24c12009-10-30 11:49:00 +00001093 deferred->Branch(vs);
Steve Block6ded16b2010-05-10 14:33:55 +01001094 __ tst(tos, Operand(kSmiTagMask));
Steve Blocka7e24c12009-10-30 11:49:00 +00001095 deferred->Branch(ne);
1096 deferred->BindExit();
Steve Block6ded16b2010-05-10 14:33:55 +01001097 frame_->EmitPush(tos);
Steve Blocka7e24c12009-10-30 11:49:00 +00001098 break;
1099 }
1100
1101 case Token::SUB: {
1102 DeferredCode* deferred =
Steve Block6ded16b2010-05-10 14:33:55 +01001103 new DeferredInlineSmiOperation(op, int_value, reversed, mode, tos);
Steve Blocka7e24c12009-10-30 11:49:00 +00001104
1105 if (reversed) {
Steve Block6ded16b2010-05-10 14:33:55 +01001106 __ rsb(tos, tos, Operand(value), SetCC);
Steve Blocka7e24c12009-10-30 11:49:00 +00001107 } else {
Steve Block6ded16b2010-05-10 14:33:55 +01001108 __ sub(tos, tos, Operand(value), SetCC);
Steve Blocka7e24c12009-10-30 11:49:00 +00001109 }
1110 deferred->Branch(vs);
Steve Block6ded16b2010-05-10 14:33:55 +01001111 __ tst(tos, Operand(kSmiTagMask));
Steve Blocka7e24c12009-10-30 11:49:00 +00001112 deferred->Branch(ne);
1113 deferred->BindExit();
Steve Block6ded16b2010-05-10 14:33:55 +01001114 frame_->EmitPush(tos);
Steve Blocka7e24c12009-10-30 11:49:00 +00001115 break;
1116 }
1117
1118
1119 case Token::BIT_OR:
1120 case Token::BIT_XOR:
1121 case Token::BIT_AND: {
1122 DeferredCode* deferred =
Steve Block6ded16b2010-05-10 14:33:55 +01001123 new DeferredInlineSmiOperation(op, int_value, reversed, mode, tos);
1124 __ tst(tos, Operand(kSmiTagMask));
Steve Blocka7e24c12009-10-30 11:49:00 +00001125 deferred->Branch(ne);
1126 switch (op) {
Steve Block6ded16b2010-05-10 14:33:55 +01001127 case Token::BIT_OR: __ orr(tos, tos, Operand(value)); break;
1128 case Token::BIT_XOR: __ eor(tos, tos, Operand(value)); break;
1129 case Token::BIT_AND: __ and_(tos, tos, Operand(value)); break;
Steve Blocka7e24c12009-10-30 11:49:00 +00001130 default: UNREACHABLE();
1131 }
1132 deferred->BindExit();
Steve Block6ded16b2010-05-10 14:33:55 +01001133 frame_->EmitPush(tos);
Steve Blocka7e24c12009-10-30 11:49:00 +00001134 break;
1135 }
1136
1137 case Token::SHL:
1138 case Token::SHR:
1139 case Token::SAR: {
Steve Block6ded16b2010-05-10 14:33:55 +01001140 ASSERT(!reversed);
1141 Register scratch = VirtualFrame::scratch0();
1142 Register scratch2 = VirtualFrame::scratch1();
Steve Blocka7e24c12009-10-30 11:49:00 +00001143 int shift_value = int_value & 0x1f; // least significant 5 bits
1144 DeferredCode* deferred =
Steve Block6ded16b2010-05-10 14:33:55 +01001145 new DeferredInlineSmiOperation(op, shift_value, false, mode, tos);
1146 __ tst(tos, Operand(kSmiTagMask));
Steve Blocka7e24c12009-10-30 11:49:00 +00001147 deferred->Branch(ne);
Steve Block6ded16b2010-05-10 14:33:55 +01001148 __ mov(scratch, Operand(tos, ASR, kSmiTagSize)); // remove tags
Steve Blocka7e24c12009-10-30 11:49:00 +00001149 switch (op) {
1150 case Token::SHL: {
1151 if (shift_value != 0) {
Steve Block6ded16b2010-05-10 14:33:55 +01001152 __ mov(scratch, Operand(scratch, LSL, shift_value));
Steve Blocka7e24c12009-10-30 11:49:00 +00001153 }
Steve Block6ded16b2010-05-10 14:33:55 +01001154 // check that the *signed* result fits in a smi
1155 __ add(scratch2, scratch, Operand(0x40000000), SetCC);
Steve Blocka7e24c12009-10-30 11:49:00 +00001156 deferred->Branch(mi);
1157 break;
1158 }
1159 case Token::SHR: {
1160 // LSR by immediate 0 means shifting 32 bits.
1161 if (shift_value != 0) {
Steve Block6ded16b2010-05-10 14:33:55 +01001162 __ mov(scratch, Operand(scratch, LSR, shift_value));
Steve Blocka7e24c12009-10-30 11:49:00 +00001163 }
1164 // check that the *unsigned* result fits in a smi
1165 // neither of the two high-order bits can be set:
1166 // - 0x80000000: high bit would be lost when smi tagging
1167 // - 0x40000000: this number would convert to negative when
1168 // smi tagging these two cases can only happen with shifts
1169 // by 0 or 1 when handed a valid smi
Steve Block6ded16b2010-05-10 14:33:55 +01001170 __ tst(scratch, Operand(0xc0000000));
Steve Blocka7e24c12009-10-30 11:49:00 +00001171 deferred->Branch(ne);
1172 break;
1173 }
1174 case Token::SAR: {
1175 if (shift_value != 0) {
1176 // ASR by immediate 0 means shifting 32 bits.
Steve Block6ded16b2010-05-10 14:33:55 +01001177 __ mov(scratch, Operand(scratch, ASR, shift_value));
Steve Blocka7e24c12009-10-30 11:49:00 +00001178 }
1179 break;
1180 }
1181 default: UNREACHABLE();
1182 }
Steve Block6ded16b2010-05-10 14:33:55 +01001183 __ mov(tos, Operand(scratch, LSL, kSmiTagSize));
Steve Blocka7e24c12009-10-30 11:49:00 +00001184 deferred->BindExit();
Steve Block6ded16b2010-05-10 14:33:55 +01001185 frame_->EmitPush(tos);
Steve Blocka7e24c12009-10-30 11:49:00 +00001186 break;
1187 }
1188
1189 case Token::MOD: {
Steve Block6ded16b2010-05-10 14:33:55 +01001190 ASSERT(!reversed);
1191 ASSERT(int_value >= 2);
1192 ASSERT(IsPowerOf2(int_value));
Steve Blocka7e24c12009-10-30 11:49:00 +00001193 DeferredCode* deferred =
Steve Block6ded16b2010-05-10 14:33:55 +01001194 new DeferredInlineSmiOperation(op, int_value, reversed, mode, tos);
Steve Blocka7e24c12009-10-30 11:49:00 +00001195 unsigned mask = (0x80000000u | kSmiTagMask);
Steve Block6ded16b2010-05-10 14:33:55 +01001196 __ tst(tos, Operand(mask));
Steve Blocka7e24c12009-10-30 11:49:00 +00001197 deferred->Branch(ne); // Go to deferred code on non-Smis and negative.
1198 mask = (int_value << kSmiTagSize) - 1;
Steve Block6ded16b2010-05-10 14:33:55 +01001199 __ and_(tos, tos, Operand(mask));
Steve Blocka7e24c12009-10-30 11:49:00 +00001200 deferred->BindExit();
Steve Block6ded16b2010-05-10 14:33:55 +01001201 frame_->EmitPush(tos);
Steve Blocka7e24c12009-10-30 11:49:00 +00001202 break;
1203 }
1204
1205 case Token::MUL: {
Steve Block6ded16b2010-05-10 14:33:55 +01001206 ASSERT(IsEasyToMultiplyBy(int_value));
Steve Blocka7e24c12009-10-30 11:49:00 +00001207 DeferredCode* deferred =
Steve Block6ded16b2010-05-10 14:33:55 +01001208 new DeferredInlineSmiOperation(op, int_value, reversed, mode, tos);
Steve Blocka7e24c12009-10-30 11:49:00 +00001209 unsigned max_smi_that_wont_overflow = Smi::kMaxValue / int_value;
1210 max_smi_that_wont_overflow <<= kSmiTagSize;
1211 unsigned mask = 0x80000000u;
1212 while ((mask & max_smi_that_wont_overflow) == 0) {
1213 mask |= mask >> 1;
1214 }
1215 mask |= kSmiTagMask;
1216 // This does a single mask that checks for a too high value in a
1217 // conservative way and for a non-Smi. It also filters out negative
1218 // numbers, unfortunately, but since this code is inline we prefer
1219 // brevity to comprehensiveness.
Steve Block6ded16b2010-05-10 14:33:55 +01001220 __ tst(tos, Operand(mask));
Steve Blocka7e24c12009-10-30 11:49:00 +00001221 deferred->Branch(ne);
Steve Block6ded16b2010-05-10 14:33:55 +01001222 MultiplyByKnownInt(masm_, tos, tos, int_value);
Steve Blocka7e24c12009-10-30 11:49:00 +00001223 deferred->BindExit();
Steve Block6ded16b2010-05-10 14:33:55 +01001224 frame_->EmitPush(tos);
Steve Blocka7e24c12009-10-30 11:49:00 +00001225 break;
1226 }
1227
1228 default:
Steve Block6ded16b2010-05-10 14:33:55 +01001229 UNREACHABLE();
Steve Blocka7e24c12009-10-30 11:49:00 +00001230 break;
1231 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001232}
1233
1234
1235void CodeGenerator::Comparison(Condition cc,
1236 Expression* left,
1237 Expression* right,
1238 bool strict) {
Steve Block6ded16b2010-05-10 14:33:55 +01001239 VirtualFrame::RegisterAllocationScope scope(this);
Steve Blocka7e24c12009-10-30 11:49:00 +00001240
Steve Block6ded16b2010-05-10 14:33:55 +01001241 if (left != NULL) Load(left);
1242 if (right != NULL) Load(right);
1243
Steve Blocka7e24c12009-10-30 11:49:00 +00001244 // sp[0] : y
1245 // sp[1] : x
1246 // result : cc register
1247
1248 // Strict only makes sense for equality comparisons.
1249 ASSERT(!strict || cc == eq);
1250
Steve Block6ded16b2010-05-10 14:33:55 +01001251 Register lhs;
1252 Register rhs;
1253
1254 // We load the top two stack positions into registers chosen by the virtual
1255 // frame. This should keep the register shuffling to a minimum.
Steve Blocka7e24c12009-10-30 11:49:00 +00001256 // Implement '>' and '<=' by reversal to obtain ECMA-262 conversion order.
1257 if (cc == gt || cc == le) {
1258 cc = ReverseCondition(cc);
Steve Block6ded16b2010-05-10 14:33:55 +01001259 lhs = frame_->PopToRegister();
1260 rhs = frame_->PopToRegister(lhs); // Don't pop to the same register again!
Steve Blocka7e24c12009-10-30 11:49:00 +00001261 } else {
Steve Block6ded16b2010-05-10 14:33:55 +01001262 rhs = frame_->PopToRegister();
1263 lhs = frame_->PopToRegister(rhs); // Don't pop to the same register again!
Steve Blocka7e24c12009-10-30 11:49:00 +00001264 }
Steve Block6ded16b2010-05-10 14:33:55 +01001265
1266 ASSERT(rhs.is(r0) || rhs.is(r1));
1267 ASSERT(lhs.is(r0) || lhs.is(r1));
1268
1269 // Now we have the two sides in r0 and r1. We flush any other registers
1270 // because the stub doesn't know about register allocation.
1271 frame_->SpillAll();
1272 Register scratch = VirtualFrame::scratch0();
1273 __ orr(scratch, lhs, Operand(rhs));
1274 __ tst(scratch, Operand(kSmiTagMask));
1275 JumpTarget smi;
Steve Blocka7e24c12009-10-30 11:49:00 +00001276 smi.Branch(eq);
1277
1278 // Perform non-smi comparison by stub.
1279 // CompareStub takes arguments in r0 and r1, returns <0, >0 or 0 in r0.
1280 // We call with 0 args because there are 0 on the stack.
Steve Block6ded16b2010-05-10 14:33:55 +01001281 if (!rhs.is(r0)) {
1282 __ Swap(rhs, lhs, ip);
1283 }
1284
Steve Blocka7e24c12009-10-30 11:49:00 +00001285 CompareStub stub(cc, strict);
1286 frame_->CallStub(&stub, 0);
1287 __ cmp(r0, Operand(0));
Steve Block6ded16b2010-05-10 14:33:55 +01001288 JumpTarget exit;
Steve Blocka7e24c12009-10-30 11:49:00 +00001289 exit.Jump();
1290
1291 // Do smi comparisons by pointer comparison.
1292 smi.Bind();
Steve Block6ded16b2010-05-10 14:33:55 +01001293 __ cmp(lhs, Operand(rhs));
Steve Blocka7e24c12009-10-30 11:49:00 +00001294
1295 exit.Bind();
1296 cc_reg_ = cc;
1297}
1298
1299
Steve Blocka7e24c12009-10-30 11:49:00 +00001300// Call the function on the stack with the given arguments.
1301void CodeGenerator::CallWithArguments(ZoneList<Expression*>* args,
Leon Clarkee46be812010-01-19 14:06:41 +00001302 CallFunctionFlags flags,
1303 int position) {
Steve Block6ded16b2010-05-10 14:33:55 +01001304 VirtualFrame::SpilledScope spilled_scope(frame_);
Steve Blocka7e24c12009-10-30 11:49:00 +00001305 // Push the arguments ("left-to-right") on the stack.
1306 int arg_count = args->length();
1307 for (int i = 0; i < arg_count; i++) {
1308 LoadAndSpill(args->at(i));
1309 }
1310
1311 // Record the position for debugging purposes.
1312 CodeForSourcePosition(position);
1313
1314 // Use the shared code stub to call the function.
1315 InLoopFlag in_loop = loop_nesting() > 0 ? IN_LOOP : NOT_IN_LOOP;
Leon Clarkee46be812010-01-19 14:06:41 +00001316 CallFunctionStub call_function(arg_count, in_loop, flags);
Steve Blocka7e24c12009-10-30 11:49:00 +00001317 frame_->CallStub(&call_function, arg_count + 1);
1318
1319 // Restore context and pop function from the stack.
1320 __ ldr(cp, frame_->Context());
1321 frame_->Drop(); // discard the TOS
1322}
1323
1324
Steve Block6ded16b2010-05-10 14:33:55 +01001325void CodeGenerator::CallApplyLazy(Expression* applicand,
1326 Expression* receiver,
1327 VariableProxy* arguments,
1328 int position) {
1329 // An optimized implementation of expressions of the form
1330 // x.apply(y, arguments).
1331 // If the arguments object of the scope has not been allocated,
1332 // and x.apply is Function.prototype.apply, this optimization
1333 // just copies y and the arguments of the current function on the
1334 // stack, as receiver and arguments, and calls x.
1335 // In the implementation comments, we call x the applicand
1336 // and y the receiver.
1337 VirtualFrame::SpilledScope spilled_scope(frame_);
1338
1339 ASSERT(ArgumentsMode() == LAZY_ARGUMENTS_ALLOCATION);
1340 ASSERT(arguments->IsArguments());
1341
1342 // Load applicand.apply onto the stack. This will usually
1343 // give us a megamorphic load site. Not super, but it works.
1344 LoadAndSpill(applicand);
1345 Handle<String> name = Factory::LookupAsciiSymbol("apply");
1346 frame_->CallLoadIC(name, RelocInfo::CODE_TARGET);
1347 frame_->EmitPush(r0);
1348
1349 // Load the receiver and the existing arguments object onto the
1350 // expression stack. Avoid allocating the arguments object here.
1351 LoadAndSpill(receiver);
1352 LoadFromSlot(scope()->arguments()->var()->slot(), NOT_INSIDE_TYPEOF);
1353
1354 // Emit the source position information after having loaded the
1355 // receiver and the arguments.
1356 CodeForSourcePosition(position);
1357 // Contents of the stack at this point:
1358 // sp[0]: arguments object of the current function or the hole.
1359 // sp[1]: receiver
1360 // sp[2]: applicand.apply
1361 // sp[3]: applicand.
1362
1363 // Check if the arguments object has been lazily allocated
1364 // already. If so, just use that instead of copying the arguments
1365 // from the stack. This also deals with cases where a local variable
1366 // named 'arguments' has been introduced.
1367 __ ldr(r0, MemOperand(sp, 0));
1368
1369 Label slow, done;
1370 __ LoadRoot(ip, Heap::kTheHoleValueRootIndex);
1371 __ cmp(ip, r0);
1372 __ b(ne, &slow);
1373
1374 Label build_args;
1375 // Get rid of the arguments object probe.
1376 frame_->Drop();
1377 // Stack now has 3 elements on it.
1378 // Contents of stack at this point:
1379 // sp[0]: receiver
1380 // sp[1]: applicand.apply
1381 // sp[2]: applicand.
1382
1383 // Check that the receiver really is a JavaScript object.
1384 __ ldr(r0, MemOperand(sp, 0));
1385 __ BranchOnSmi(r0, &build_args);
1386 // We allow all JSObjects including JSFunctions. As long as
1387 // JS_FUNCTION_TYPE is the last instance type and it is right
1388 // after LAST_JS_OBJECT_TYPE, we do not have to check the upper
1389 // bound.
1390 ASSERT(LAST_TYPE == JS_FUNCTION_TYPE);
1391 ASSERT(JS_FUNCTION_TYPE == LAST_JS_OBJECT_TYPE + 1);
1392 __ CompareObjectType(r0, r1, r2, FIRST_JS_OBJECT_TYPE);
1393 __ b(lt, &build_args);
1394
1395 // Check that applicand.apply is Function.prototype.apply.
1396 __ ldr(r0, MemOperand(sp, kPointerSize));
1397 __ BranchOnSmi(r0, &build_args);
1398 __ CompareObjectType(r0, r1, r2, JS_FUNCTION_TYPE);
1399 __ b(ne, &build_args);
1400 __ ldr(r0, FieldMemOperand(r0, JSFunction::kSharedFunctionInfoOffset));
1401 Handle<Code> apply_code(Builtins::builtin(Builtins::FunctionApply));
1402 __ ldr(r1, FieldMemOperand(r0, SharedFunctionInfo::kCodeOffset));
1403 __ cmp(r1, Operand(apply_code));
1404 __ b(ne, &build_args);
1405
1406 // Check that applicand is a function.
1407 __ ldr(r1, MemOperand(sp, 2 * kPointerSize));
1408 __ BranchOnSmi(r1, &build_args);
1409 __ CompareObjectType(r1, r2, r3, JS_FUNCTION_TYPE);
1410 __ b(ne, &build_args);
1411
1412 // Copy the arguments to this function possibly from the
1413 // adaptor frame below it.
1414 Label invoke, adapted;
1415 __ ldr(r2, MemOperand(fp, StandardFrameConstants::kCallerFPOffset));
1416 __ ldr(r3, MemOperand(r2, StandardFrameConstants::kContextOffset));
1417 __ cmp(r3, Operand(Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR)));
1418 __ b(eq, &adapted);
1419
1420 // No arguments adaptor frame. Copy fixed number of arguments.
1421 __ mov(r0, Operand(scope()->num_parameters()));
1422 for (int i = 0; i < scope()->num_parameters(); i++) {
1423 __ ldr(r2, frame_->ParameterAt(i));
1424 __ push(r2);
1425 }
1426 __ jmp(&invoke);
1427
1428 // Arguments adaptor frame present. Copy arguments from there, but
1429 // avoid copying too many arguments to avoid stack overflows.
1430 __ bind(&adapted);
1431 static const uint32_t kArgumentsLimit = 1 * KB;
1432 __ ldr(r0, MemOperand(r2, ArgumentsAdaptorFrameConstants::kLengthOffset));
1433 __ mov(r0, Operand(r0, LSR, kSmiTagSize));
1434 __ mov(r3, r0);
1435 __ cmp(r0, Operand(kArgumentsLimit));
1436 __ b(gt, &build_args);
1437
1438 // Loop through the arguments pushing them onto the execution
1439 // stack. We don't inform the virtual frame of the push, so we don't
1440 // have to worry about getting rid of the elements from the virtual
1441 // frame.
1442 Label loop;
1443 // r3 is a small non-negative integer, due to the test above.
1444 __ cmp(r3, Operand(0));
1445 __ b(eq, &invoke);
1446 // Compute the address of the first argument.
1447 __ add(r2, r2, Operand(r3, LSL, kPointerSizeLog2));
1448 __ add(r2, r2, Operand(kPointerSize));
1449 __ bind(&loop);
1450 // Post-decrement argument address by kPointerSize on each iteration.
1451 __ ldr(r4, MemOperand(r2, kPointerSize, NegPostIndex));
1452 __ push(r4);
1453 __ sub(r3, r3, Operand(1), SetCC);
1454 __ b(gt, &loop);
1455
1456 // Invoke the function.
1457 __ bind(&invoke);
1458 ParameterCount actual(r0);
1459 __ InvokeFunction(r1, actual, CALL_FUNCTION);
1460 // Drop applicand.apply and applicand from the stack, and push
1461 // the result of the function call, but leave the spilled frame
1462 // unchanged, with 3 elements, so it is correct when we compile the
1463 // slow-case code.
1464 __ add(sp, sp, Operand(2 * kPointerSize));
1465 __ push(r0);
1466 // Stack now has 1 element:
1467 // sp[0]: result
1468 __ jmp(&done);
1469
1470 // Slow-case: Allocate the arguments object since we know it isn't
1471 // there, and fall-through to the slow-case where we call
1472 // applicand.apply.
1473 __ bind(&build_args);
1474 // Stack now has 3 elements, because we have jumped from where:
1475 // sp[0]: receiver
1476 // sp[1]: applicand.apply
1477 // sp[2]: applicand.
1478 StoreArgumentsObject(false);
1479
1480 // Stack and frame now have 4 elements.
1481 __ bind(&slow);
1482
1483 // Generic computation of x.apply(y, args) with no special optimization.
1484 // Flip applicand.apply and applicand on the stack, so
1485 // applicand looks like the receiver of the applicand.apply call.
1486 // Then process it as a normal function call.
1487 __ ldr(r0, MemOperand(sp, 3 * kPointerSize));
1488 __ ldr(r1, MemOperand(sp, 2 * kPointerSize));
1489 __ str(r0, MemOperand(sp, 2 * kPointerSize));
1490 __ str(r1, MemOperand(sp, 3 * kPointerSize));
1491
1492 CallFunctionStub call_function(2, NOT_IN_LOOP, NO_CALL_FUNCTION_FLAGS);
1493 frame_->CallStub(&call_function, 3);
1494 // The function and its two arguments have been dropped.
1495 frame_->Drop(); // Drop the receiver as well.
1496 frame_->EmitPush(r0);
1497 // Stack now has 1 element:
1498 // sp[0]: result
1499 __ bind(&done);
1500
1501 // Restore the context register after a call.
1502 __ ldr(cp, frame_->Context());
1503}
1504
1505
Steve Blocka7e24c12009-10-30 11:49:00 +00001506void CodeGenerator::Branch(bool if_true, JumpTarget* target) {
Steve Block6ded16b2010-05-10 14:33:55 +01001507 VirtualFrame::SpilledScope spilled_scope(frame_);
Steve Blocka7e24c12009-10-30 11:49:00 +00001508 ASSERT(has_cc());
1509 Condition cc = if_true ? cc_reg_ : NegateCondition(cc_reg_);
1510 target->Branch(cc);
1511 cc_reg_ = al;
1512}
1513
1514
1515void CodeGenerator::CheckStack() {
Steve Block6ded16b2010-05-10 14:33:55 +01001516 VirtualFrame::SpilledScope spilled_scope(frame_);
Steve Blockd0582a62009-12-15 09:54:21 +00001517 Comment cmnt(masm_, "[ check stack");
1518 __ LoadRoot(ip, Heap::kStackLimitRootIndex);
1519 // Put the lr setup instruction in the delay slot. kInstrSize is added to
1520 // the implicit 8 byte offset that always applies to operations with pc and
1521 // gives a return address 12 bytes down.
1522 masm_->add(lr, pc, Operand(Assembler::kInstrSize));
1523 masm_->cmp(sp, Operand(ip));
1524 StackCheckStub stub;
1525 // Call the stub if lower.
1526 masm_->mov(pc,
1527 Operand(reinterpret_cast<intptr_t>(stub.GetCode().location()),
1528 RelocInfo::CODE_TARGET),
1529 LeaveCC,
1530 lo);
Steve Blocka7e24c12009-10-30 11:49:00 +00001531}
1532
1533
1534void CodeGenerator::VisitStatements(ZoneList<Statement*>* statements) {
1535#ifdef DEBUG
1536 int original_height = frame_->height();
1537#endif
Steve Block6ded16b2010-05-10 14:33:55 +01001538 VirtualFrame::SpilledScope spilled_scope(frame_);
Steve Blocka7e24c12009-10-30 11:49:00 +00001539 for (int i = 0; frame_ != NULL && i < statements->length(); i++) {
1540 VisitAndSpill(statements->at(i));
1541 }
1542 ASSERT(!has_valid_frame() || frame_->height() == original_height);
1543}
1544
1545
1546void CodeGenerator::VisitBlock(Block* node) {
1547#ifdef DEBUG
1548 int original_height = frame_->height();
1549#endif
Steve Block6ded16b2010-05-10 14:33:55 +01001550 VirtualFrame::SpilledScope spilled_scope(frame_);
Steve Blocka7e24c12009-10-30 11:49:00 +00001551 Comment cmnt(masm_, "[ Block");
1552 CodeForStatementPosition(node);
1553 node->break_target()->set_direction(JumpTarget::FORWARD_ONLY);
1554 VisitStatementsAndSpill(node->statements());
1555 if (node->break_target()->is_linked()) {
1556 node->break_target()->Bind();
1557 }
1558 node->break_target()->Unuse();
1559 ASSERT(!has_valid_frame() || frame_->height() == original_height);
1560}
1561
1562
1563void CodeGenerator::DeclareGlobals(Handle<FixedArray> pairs) {
Steve Block3ce2e202009-11-05 08:53:23 +00001564 frame_->EmitPush(cp);
Steve Block6ded16b2010-05-10 14:33:55 +01001565 frame_->EmitPush(Operand(pairs));
1566 frame_->EmitPush(Operand(Smi::FromInt(is_eval() ? 1 : 0)));
1567
1568 VirtualFrame::SpilledScope spilled_scope(frame_);
Steve Blocka7e24c12009-10-30 11:49:00 +00001569 frame_->CallRuntime(Runtime::kDeclareGlobals, 3);
1570 // The result is discarded.
1571}
1572
1573
1574void CodeGenerator::VisitDeclaration(Declaration* node) {
1575#ifdef DEBUG
1576 int original_height = frame_->height();
1577#endif
Steve Blocka7e24c12009-10-30 11:49:00 +00001578 Comment cmnt(masm_, "[ Declaration");
1579 Variable* var = node->proxy()->var();
1580 ASSERT(var != NULL); // must have been resolved
1581 Slot* slot = var->slot();
1582
1583 // If it was not possible to allocate the variable at compile time,
1584 // we need to "declare" it at runtime to make sure it actually
1585 // exists in the local context.
1586 if (slot != NULL && slot->type() == Slot::LOOKUP) {
1587 // Variables with a "LOOKUP" slot were introduced as non-locals
1588 // during variable resolution and must have mode DYNAMIC.
1589 ASSERT(var->is_dynamic());
1590 // For now, just do a runtime call.
1591 frame_->EmitPush(cp);
Steve Block6ded16b2010-05-10 14:33:55 +01001592 frame_->EmitPush(Operand(var->name()));
Steve Blocka7e24c12009-10-30 11:49:00 +00001593 // Declaration nodes are always declared in only two modes.
1594 ASSERT(node->mode() == Variable::VAR || node->mode() == Variable::CONST);
1595 PropertyAttributes attr = node->mode() == Variable::VAR ? NONE : READ_ONLY;
Steve Block6ded16b2010-05-10 14:33:55 +01001596 frame_->EmitPush(Operand(Smi::FromInt(attr)));
Steve Blocka7e24c12009-10-30 11:49:00 +00001597 // Push initial value, if any.
1598 // Note: For variables we must not push an initial value (such as
1599 // 'undefined') because we may have a (legal) redeclaration and we
1600 // must not destroy the current value.
1601 if (node->mode() == Variable::CONST) {
Steve Block6ded16b2010-05-10 14:33:55 +01001602 frame_->EmitPushRoot(Heap::kTheHoleValueRootIndex);
Steve Blocka7e24c12009-10-30 11:49:00 +00001603 } else if (node->fun() != NULL) {
Steve Block6ded16b2010-05-10 14:33:55 +01001604 Load(node->fun());
Steve Blocka7e24c12009-10-30 11:49:00 +00001605 } else {
Steve Block6ded16b2010-05-10 14:33:55 +01001606 frame_->EmitPush(Operand(0));
Steve Blocka7e24c12009-10-30 11:49:00 +00001607 }
Steve Block6ded16b2010-05-10 14:33:55 +01001608
1609 VirtualFrame::SpilledScope spilled_scope(frame_);
Steve Blocka7e24c12009-10-30 11:49:00 +00001610 frame_->CallRuntime(Runtime::kDeclareContextSlot, 4);
1611 // Ignore the return value (declarations are statements).
Steve Block6ded16b2010-05-10 14:33:55 +01001612
Steve Blocka7e24c12009-10-30 11:49:00 +00001613 ASSERT(frame_->height() == original_height);
1614 return;
1615 }
1616
1617 ASSERT(!var->is_global());
1618
1619 // If we have a function or a constant, we need to initialize the variable.
1620 Expression* val = NULL;
1621 if (node->mode() == Variable::CONST) {
1622 val = new Literal(Factory::the_hole_value());
1623 } else {
1624 val = node->fun(); // NULL if we don't have a function
1625 }
1626
1627 if (val != NULL) {
Steve Block6ded16b2010-05-10 14:33:55 +01001628 // Set initial value.
1629 Reference target(this, node->proxy());
1630 Load(val);
1631 target.SetValue(NOT_CONST_INIT);
1632
Steve Blocka7e24c12009-10-30 11:49:00 +00001633 // Get rid of the assigned value (declarations are statements).
1634 frame_->Drop();
1635 }
1636 ASSERT(frame_->height() == original_height);
1637}
1638
1639
1640void CodeGenerator::VisitExpressionStatement(ExpressionStatement* node) {
1641#ifdef DEBUG
1642 int original_height = frame_->height();
1643#endif
Steve Block6ded16b2010-05-10 14:33:55 +01001644 VirtualFrame::SpilledScope spilled_scope(frame_);
Steve Blocka7e24c12009-10-30 11:49:00 +00001645 Comment cmnt(masm_, "[ ExpressionStatement");
1646 CodeForStatementPosition(node);
1647 Expression* expression = node->expression();
1648 expression->MarkAsStatement();
1649 LoadAndSpill(expression);
1650 frame_->Drop();
1651 ASSERT(frame_->height() == original_height);
1652}
1653
1654
1655void CodeGenerator::VisitEmptyStatement(EmptyStatement* node) {
1656#ifdef DEBUG
1657 int original_height = frame_->height();
1658#endif
Steve Block6ded16b2010-05-10 14:33:55 +01001659 VirtualFrame::SpilledScope spilled_scope(frame_);
Steve Blocka7e24c12009-10-30 11:49:00 +00001660 Comment cmnt(masm_, "// EmptyStatement");
1661 CodeForStatementPosition(node);
1662 // nothing to do
1663 ASSERT(frame_->height() == original_height);
1664}
1665
1666
1667void CodeGenerator::VisitIfStatement(IfStatement* node) {
1668#ifdef DEBUG
1669 int original_height = frame_->height();
1670#endif
Steve Block6ded16b2010-05-10 14:33:55 +01001671 VirtualFrame::SpilledScope spilled_scope(frame_);
Steve Blocka7e24c12009-10-30 11:49:00 +00001672 Comment cmnt(masm_, "[ IfStatement");
1673 // Generate different code depending on which parts of the if statement
1674 // are present or not.
1675 bool has_then_stm = node->HasThenStatement();
1676 bool has_else_stm = node->HasElseStatement();
1677
1678 CodeForStatementPosition(node);
1679
1680 JumpTarget exit;
1681 if (has_then_stm && has_else_stm) {
1682 Comment cmnt(masm_, "[ IfThenElse");
1683 JumpTarget then;
1684 JumpTarget else_;
1685 // if (cond)
Steve Blockd0582a62009-12-15 09:54:21 +00001686 LoadConditionAndSpill(node->condition(), &then, &else_, true);
Steve Blocka7e24c12009-10-30 11:49:00 +00001687 if (frame_ != NULL) {
1688 Branch(false, &else_);
1689 }
1690 // then
1691 if (frame_ != NULL || then.is_linked()) {
1692 then.Bind();
1693 VisitAndSpill(node->then_statement());
1694 }
1695 if (frame_ != NULL) {
1696 exit.Jump();
1697 }
1698 // else
1699 if (else_.is_linked()) {
1700 else_.Bind();
1701 VisitAndSpill(node->else_statement());
1702 }
1703
1704 } else if (has_then_stm) {
1705 Comment cmnt(masm_, "[ IfThen");
1706 ASSERT(!has_else_stm);
1707 JumpTarget then;
1708 // if (cond)
Steve Blockd0582a62009-12-15 09:54:21 +00001709 LoadConditionAndSpill(node->condition(), &then, &exit, true);
Steve Blocka7e24c12009-10-30 11:49:00 +00001710 if (frame_ != NULL) {
1711 Branch(false, &exit);
1712 }
1713 // then
1714 if (frame_ != NULL || then.is_linked()) {
1715 then.Bind();
1716 VisitAndSpill(node->then_statement());
1717 }
1718
1719 } else if (has_else_stm) {
1720 Comment cmnt(masm_, "[ IfElse");
1721 ASSERT(!has_then_stm);
1722 JumpTarget else_;
1723 // if (!cond)
Steve Blockd0582a62009-12-15 09:54:21 +00001724 LoadConditionAndSpill(node->condition(), &exit, &else_, true);
Steve Blocka7e24c12009-10-30 11:49:00 +00001725 if (frame_ != NULL) {
1726 Branch(true, &exit);
1727 }
1728 // else
1729 if (frame_ != NULL || else_.is_linked()) {
1730 else_.Bind();
1731 VisitAndSpill(node->else_statement());
1732 }
1733
1734 } else {
1735 Comment cmnt(masm_, "[ If");
1736 ASSERT(!has_then_stm && !has_else_stm);
1737 // if (cond)
Steve Blockd0582a62009-12-15 09:54:21 +00001738 LoadConditionAndSpill(node->condition(), &exit, &exit, false);
Steve Blocka7e24c12009-10-30 11:49:00 +00001739 if (frame_ != NULL) {
1740 if (has_cc()) {
1741 cc_reg_ = al;
1742 } else {
1743 frame_->Drop();
1744 }
1745 }
1746 }
1747
1748 // end
1749 if (exit.is_linked()) {
1750 exit.Bind();
1751 }
1752 ASSERT(!has_valid_frame() || frame_->height() == original_height);
1753}
1754
1755
1756void CodeGenerator::VisitContinueStatement(ContinueStatement* node) {
Steve Block6ded16b2010-05-10 14:33:55 +01001757 VirtualFrame::SpilledScope spilled_scope(frame_);
Steve Blocka7e24c12009-10-30 11:49:00 +00001758 Comment cmnt(masm_, "[ ContinueStatement");
1759 CodeForStatementPosition(node);
1760 node->target()->continue_target()->Jump();
1761}
1762
1763
1764void CodeGenerator::VisitBreakStatement(BreakStatement* node) {
Steve Block6ded16b2010-05-10 14:33:55 +01001765 VirtualFrame::SpilledScope spilled_scope(frame_);
Steve Blocka7e24c12009-10-30 11:49:00 +00001766 Comment cmnt(masm_, "[ BreakStatement");
1767 CodeForStatementPosition(node);
1768 node->target()->break_target()->Jump();
1769}
1770
1771
1772void CodeGenerator::VisitReturnStatement(ReturnStatement* node) {
Steve Block6ded16b2010-05-10 14:33:55 +01001773 VirtualFrame::SpilledScope spilled_scope(frame_);
Steve Blocka7e24c12009-10-30 11:49:00 +00001774 Comment cmnt(masm_, "[ ReturnStatement");
1775
1776 CodeForStatementPosition(node);
1777 LoadAndSpill(node->expression());
1778 if (function_return_is_shadowed_) {
1779 frame_->EmitPop(r0);
1780 function_return_.Jump();
1781 } else {
1782 // Pop the result from the frame and prepare the frame for
1783 // returning thus making it easier to merge.
1784 frame_->EmitPop(r0);
1785 frame_->PrepareForReturn();
1786
1787 function_return_.Jump();
1788 }
1789}
1790
1791
1792void CodeGenerator::VisitWithEnterStatement(WithEnterStatement* node) {
1793#ifdef DEBUG
1794 int original_height = frame_->height();
1795#endif
Steve Block6ded16b2010-05-10 14:33:55 +01001796 VirtualFrame::SpilledScope spilled_scope(frame_);
Steve Blocka7e24c12009-10-30 11:49:00 +00001797 Comment cmnt(masm_, "[ WithEnterStatement");
1798 CodeForStatementPosition(node);
1799 LoadAndSpill(node->expression());
1800 if (node->is_catch_block()) {
1801 frame_->CallRuntime(Runtime::kPushCatchContext, 1);
1802 } else {
1803 frame_->CallRuntime(Runtime::kPushContext, 1);
1804 }
1805#ifdef DEBUG
1806 JumpTarget verified_true;
Steve Block6ded16b2010-05-10 14:33:55 +01001807 __ cmp(r0, cp);
Steve Blocka7e24c12009-10-30 11:49:00 +00001808 verified_true.Branch(eq);
1809 __ stop("PushContext: r0 is expected to be the same as cp");
1810 verified_true.Bind();
1811#endif
1812 // Update context local.
1813 __ str(cp, frame_->Context());
1814 ASSERT(frame_->height() == original_height);
1815}
1816
1817
1818void CodeGenerator::VisitWithExitStatement(WithExitStatement* node) {
1819#ifdef DEBUG
1820 int original_height = frame_->height();
1821#endif
Steve Block6ded16b2010-05-10 14:33:55 +01001822 VirtualFrame::SpilledScope spilled_scope(frame_);
Steve Blocka7e24c12009-10-30 11:49:00 +00001823 Comment cmnt(masm_, "[ WithExitStatement");
1824 CodeForStatementPosition(node);
1825 // Pop context.
1826 __ ldr(cp, ContextOperand(cp, Context::PREVIOUS_INDEX));
1827 // Update context local.
1828 __ str(cp, frame_->Context());
1829 ASSERT(frame_->height() == original_height);
1830}
1831
1832
1833void CodeGenerator::VisitSwitchStatement(SwitchStatement* node) {
1834#ifdef DEBUG
1835 int original_height = frame_->height();
1836#endif
Steve Block6ded16b2010-05-10 14:33:55 +01001837 VirtualFrame::SpilledScope spilled_scope(frame_);
Steve Blocka7e24c12009-10-30 11:49:00 +00001838 Comment cmnt(masm_, "[ SwitchStatement");
1839 CodeForStatementPosition(node);
1840 node->break_target()->set_direction(JumpTarget::FORWARD_ONLY);
1841
1842 LoadAndSpill(node->tag());
1843
1844 JumpTarget next_test;
1845 JumpTarget fall_through;
1846 JumpTarget default_entry;
1847 JumpTarget default_exit(JumpTarget::BIDIRECTIONAL);
1848 ZoneList<CaseClause*>* cases = node->cases();
1849 int length = cases->length();
1850 CaseClause* default_clause = NULL;
1851
1852 for (int i = 0; i < length; i++) {
1853 CaseClause* clause = cases->at(i);
1854 if (clause->is_default()) {
1855 // Remember the default clause and compile it at the end.
1856 default_clause = clause;
1857 continue;
1858 }
1859
1860 Comment cmnt(masm_, "[ Case clause");
1861 // Compile the test.
1862 next_test.Bind();
1863 next_test.Unuse();
1864 // Duplicate TOS.
1865 __ ldr(r0, frame_->Top());
1866 frame_->EmitPush(r0);
1867 Comparison(eq, NULL, clause->label(), true);
1868 Branch(false, &next_test);
1869
1870 // Before entering the body from the test, remove the switch value from
1871 // the stack.
1872 frame_->Drop();
1873
1874 // Label the body so that fall through is enabled.
1875 if (i > 0 && cases->at(i - 1)->is_default()) {
1876 default_exit.Bind();
1877 } else {
1878 fall_through.Bind();
1879 fall_through.Unuse();
1880 }
1881 VisitStatementsAndSpill(clause->statements());
1882
1883 // If control flow can fall through from the body, jump to the next body
1884 // or the end of the statement.
1885 if (frame_ != NULL) {
1886 if (i < length - 1 && cases->at(i + 1)->is_default()) {
1887 default_entry.Jump();
1888 } else {
1889 fall_through.Jump();
1890 }
1891 }
1892 }
1893
1894 // The final "test" removes the switch value.
1895 next_test.Bind();
1896 frame_->Drop();
1897
1898 // If there is a default clause, compile it.
1899 if (default_clause != NULL) {
1900 Comment cmnt(masm_, "[ Default clause");
1901 default_entry.Bind();
1902 VisitStatementsAndSpill(default_clause->statements());
1903 // If control flow can fall out of the default and there is a case after
1904 // it, jup to that case's body.
1905 if (frame_ != NULL && default_exit.is_bound()) {
1906 default_exit.Jump();
1907 }
1908 }
1909
1910 if (fall_through.is_linked()) {
1911 fall_through.Bind();
1912 }
1913
1914 if (node->break_target()->is_linked()) {
1915 node->break_target()->Bind();
1916 }
1917 node->break_target()->Unuse();
1918 ASSERT(!has_valid_frame() || frame_->height() == original_height);
1919}
1920
1921
Steve Block3ce2e202009-11-05 08:53:23 +00001922void CodeGenerator::VisitDoWhileStatement(DoWhileStatement* node) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001923#ifdef DEBUG
1924 int original_height = frame_->height();
1925#endif
Steve Block6ded16b2010-05-10 14:33:55 +01001926 VirtualFrame::SpilledScope spilled_scope(frame_);
Steve Block3ce2e202009-11-05 08:53:23 +00001927 Comment cmnt(masm_, "[ DoWhileStatement");
Steve Blocka7e24c12009-10-30 11:49:00 +00001928 CodeForStatementPosition(node);
1929 node->break_target()->set_direction(JumpTarget::FORWARD_ONLY);
Steve Block3ce2e202009-11-05 08:53:23 +00001930 JumpTarget body(JumpTarget::BIDIRECTIONAL);
Steve Block6ded16b2010-05-10 14:33:55 +01001931 IncrementLoopNesting();
Steve Blocka7e24c12009-10-30 11:49:00 +00001932
Steve Block3ce2e202009-11-05 08:53:23 +00001933 // Label the top of the loop for the backward CFG edge. If the test
1934 // is always true we can use the continue target, and if the test is
1935 // always false there is no need.
1936 ConditionAnalysis info = AnalyzeCondition(node->cond());
1937 switch (info) {
1938 case ALWAYS_TRUE:
Steve Blocka7e24c12009-10-30 11:49:00 +00001939 node->continue_target()->set_direction(JumpTarget::BIDIRECTIONAL);
1940 node->continue_target()->Bind();
Steve Block3ce2e202009-11-05 08:53:23 +00001941 break;
1942 case ALWAYS_FALSE:
1943 node->continue_target()->set_direction(JumpTarget::FORWARD_ONLY);
1944 break;
1945 case DONT_KNOW:
1946 node->continue_target()->set_direction(JumpTarget::FORWARD_ONLY);
1947 body.Bind();
1948 break;
1949 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001950
Steve Block3ce2e202009-11-05 08:53:23 +00001951 CheckStack(); // TODO(1222600): ignore if body contains calls.
1952 VisitAndSpill(node->body());
Steve Blocka7e24c12009-10-30 11:49:00 +00001953
Steve Blockd0582a62009-12-15 09:54:21 +00001954 // Compile the test.
Steve Block3ce2e202009-11-05 08:53:23 +00001955 switch (info) {
1956 case ALWAYS_TRUE:
1957 // If control can fall off the end of the body, jump back to the
1958 // top.
Steve Blocka7e24c12009-10-30 11:49:00 +00001959 if (has_valid_frame()) {
Steve Block3ce2e202009-11-05 08:53:23 +00001960 node->continue_target()->Jump();
Steve Blocka7e24c12009-10-30 11:49:00 +00001961 }
1962 break;
Steve Block3ce2e202009-11-05 08:53:23 +00001963 case ALWAYS_FALSE:
1964 // If we have a continue in the body, we only have to bind its
1965 // jump target.
1966 if (node->continue_target()->is_linked()) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001967 node->continue_target()->Bind();
Steve Blocka7e24c12009-10-30 11:49:00 +00001968 }
Steve Block3ce2e202009-11-05 08:53:23 +00001969 break;
1970 case DONT_KNOW:
1971 // We have to compile the test expression if it can be reached by
1972 // control flow falling out of the body or via continue.
1973 if (node->continue_target()->is_linked()) {
1974 node->continue_target()->Bind();
1975 }
1976 if (has_valid_frame()) {
Steve Blockd0582a62009-12-15 09:54:21 +00001977 Comment cmnt(masm_, "[ DoWhileCondition");
1978 CodeForDoWhileConditionPosition(node);
1979 LoadConditionAndSpill(node->cond(), &body, node->break_target(), true);
Steve Blocka7e24c12009-10-30 11:49:00 +00001980 if (has_valid_frame()) {
Steve Block3ce2e202009-11-05 08:53:23 +00001981 // A invalid frame here indicates that control did not
1982 // fall out of the test expression.
1983 Branch(true, &body);
Steve Blocka7e24c12009-10-30 11:49:00 +00001984 }
1985 }
1986 break;
Steve Blocka7e24c12009-10-30 11:49:00 +00001987 }
1988
1989 if (node->break_target()->is_linked()) {
1990 node->break_target()->Bind();
1991 }
Steve Block6ded16b2010-05-10 14:33:55 +01001992 DecrementLoopNesting();
Steve Block3ce2e202009-11-05 08:53:23 +00001993 ASSERT(!has_valid_frame() || frame_->height() == original_height);
1994}
1995
1996
1997void CodeGenerator::VisitWhileStatement(WhileStatement* node) {
1998#ifdef DEBUG
1999 int original_height = frame_->height();
2000#endif
Steve Block6ded16b2010-05-10 14:33:55 +01002001 VirtualFrame::SpilledScope spilled_scope(frame_);
Steve Block3ce2e202009-11-05 08:53:23 +00002002 Comment cmnt(masm_, "[ WhileStatement");
2003 CodeForStatementPosition(node);
2004
2005 // If the test is never true and has no side effects there is no need
2006 // to compile the test or body.
2007 ConditionAnalysis info = AnalyzeCondition(node->cond());
2008 if (info == ALWAYS_FALSE) return;
2009
2010 node->break_target()->set_direction(JumpTarget::FORWARD_ONLY);
Steve Block6ded16b2010-05-10 14:33:55 +01002011 IncrementLoopNesting();
Steve Block3ce2e202009-11-05 08:53:23 +00002012
2013 // Label the top of the loop with the continue target for the backward
2014 // CFG edge.
2015 node->continue_target()->set_direction(JumpTarget::BIDIRECTIONAL);
2016 node->continue_target()->Bind();
2017
2018 if (info == DONT_KNOW) {
2019 JumpTarget body;
Steve Blockd0582a62009-12-15 09:54:21 +00002020 LoadConditionAndSpill(node->cond(), &body, node->break_target(), true);
Steve Block3ce2e202009-11-05 08:53:23 +00002021 if (has_valid_frame()) {
2022 // A NULL frame indicates that control did not fall out of the
2023 // test expression.
2024 Branch(false, node->break_target());
2025 }
2026 if (has_valid_frame() || body.is_linked()) {
2027 body.Bind();
2028 }
2029 }
2030
2031 if (has_valid_frame()) {
2032 CheckStack(); // TODO(1222600): ignore if body contains calls.
2033 VisitAndSpill(node->body());
2034
2035 // If control flow can fall out of the body, jump back to the top.
2036 if (has_valid_frame()) {
2037 node->continue_target()->Jump();
2038 }
2039 }
2040 if (node->break_target()->is_linked()) {
2041 node->break_target()->Bind();
2042 }
Steve Block6ded16b2010-05-10 14:33:55 +01002043 DecrementLoopNesting();
Steve Block3ce2e202009-11-05 08:53:23 +00002044 ASSERT(!has_valid_frame() || frame_->height() == original_height);
2045}
2046
2047
2048void CodeGenerator::VisitForStatement(ForStatement* node) {
2049#ifdef DEBUG
2050 int original_height = frame_->height();
2051#endif
Steve Block6ded16b2010-05-10 14:33:55 +01002052 VirtualFrame::SpilledScope spilled_scope(frame_);
Steve Block3ce2e202009-11-05 08:53:23 +00002053 Comment cmnt(masm_, "[ ForStatement");
2054 CodeForStatementPosition(node);
2055 if (node->init() != NULL) {
2056 VisitAndSpill(node->init());
2057 }
2058
2059 // If the test is never true there is no need to compile the test or
2060 // body.
2061 ConditionAnalysis info = AnalyzeCondition(node->cond());
2062 if (info == ALWAYS_FALSE) return;
2063
2064 node->break_target()->set_direction(JumpTarget::FORWARD_ONLY);
Steve Block6ded16b2010-05-10 14:33:55 +01002065 IncrementLoopNesting();
Steve Block3ce2e202009-11-05 08:53:23 +00002066
2067 // If there is no update statement, label the top of the loop with the
2068 // continue target, otherwise with the loop target.
2069 JumpTarget loop(JumpTarget::BIDIRECTIONAL);
2070 if (node->next() == NULL) {
2071 node->continue_target()->set_direction(JumpTarget::BIDIRECTIONAL);
2072 node->continue_target()->Bind();
2073 } else {
2074 node->continue_target()->set_direction(JumpTarget::FORWARD_ONLY);
2075 loop.Bind();
2076 }
2077
2078 // If the test is always true, there is no need to compile it.
2079 if (info == DONT_KNOW) {
2080 JumpTarget body;
Steve Blockd0582a62009-12-15 09:54:21 +00002081 LoadConditionAndSpill(node->cond(), &body, node->break_target(), true);
Steve Block3ce2e202009-11-05 08:53:23 +00002082 if (has_valid_frame()) {
2083 Branch(false, node->break_target());
2084 }
2085 if (has_valid_frame() || body.is_linked()) {
2086 body.Bind();
2087 }
2088 }
2089
2090 if (has_valid_frame()) {
2091 CheckStack(); // TODO(1222600): ignore if body contains calls.
2092 VisitAndSpill(node->body());
2093
2094 if (node->next() == NULL) {
2095 // If there is no update statement and control flow can fall out
2096 // of the loop, jump directly to the continue label.
2097 if (has_valid_frame()) {
2098 node->continue_target()->Jump();
2099 }
2100 } else {
2101 // If there is an update statement and control flow can reach it
2102 // via falling out of the body of the loop or continuing, we
2103 // compile the update statement.
2104 if (node->continue_target()->is_linked()) {
2105 node->continue_target()->Bind();
2106 }
2107 if (has_valid_frame()) {
2108 // Record source position of the statement as this code which is
2109 // after the code for the body actually belongs to the loop
2110 // statement and not the body.
2111 CodeForStatementPosition(node);
2112 VisitAndSpill(node->next());
2113 loop.Jump();
2114 }
2115 }
2116 }
2117 if (node->break_target()->is_linked()) {
2118 node->break_target()->Bind();
2119 }
Steve Block6ded16b2010-05-10 14:33:55 +01002120 DecrementLoopNesting();
Steve Blocka7e24c12009-10-30 11:49:00 +00002121 ASSERT(!has_valid_frame() || frame_->height() == original_height);
2122}
2123
2124
2125void CodeGenerator::VisitForInStatement(ForInStatement* node) {
2126#ifdef DEBUG
2127 int original_height = frame_->height();
2128#endif
Steve Block6ded16b2010-05-10 14:33:55 +01002129 VirtualFrame::SpilledScope spilled_scope(frame_);
Steve Blocka7e24c12009-10-30 11:49:00 +00002130 Comment cmnt(masm_, "[ ForInStatement");
2131 CodeForStatementPosition(node);
2132
2133 JumpTarget primitive;
2134 JumpTarget jsobject;
2135 JumpTarget fixed_array;
2136 JumpTarget entry(JumpTarget::BIDIRECTIONAL);
2137 JumpTarget end_del_check;
2138 JumpTarget exit;
2139
2140 // Get the object to enumerate over (converted to JSObject).
2141 LoadAndSpill(node->enumerable());
2142
2143 // Both SpiderMonkey and kjs ignore null and undefined in contrast
2144 // to the specification. 12.6.4 mandates a call to ToObject.
2145 frame_->EmitPop(r0);
2146 __ LoadRoot(ip, Heap::kUndefinedValueRootIndex);
2147 __ cmp(r0, ip);
2148 exit.Branch(eq);
2149 __ LoadRoot(ip, Heap::kNullValueRootIndex);
2150 __ cmp(r0, ip);
2151 exit.Branch(eq);
2152
2153 // Stack layout in body:
2154 // [iteration counter (Smi)]
2155 // [length of array]
2156 // [FixedArray]
2157 // [Map or 0]
2158 // [Object]
2159
2160 // Check if enumerable is already a JSObject
2161 __ tst(r0, Operand(kSmiTagMask));
2162 primitive.Branch(eq);
2163 __ CompareObjectType(r0, r1, r1, FIRST_JS_OBJECT_TYPE);
2164 jsobject.Branch(hs);
2165
2166 primitive.Bind();
2167 frame_->EmitPush(r0);
Steve Blockd0582a62009-12-15 09:54:21 +00002168 frame_->InvokeBuiltin(Builtins::TO_OBJECT, CALL_JS, 1);
Steve Blocka7e24c12009-10-30 11:49:00 +00002169
2170 jsobject.Bind();
2171 // Get the set of properties (as a FixedArray or Map).
Steve Blockd0582a62009-12-15 09:54:21 +00002172 // r0: value to be iterated over
2173 frame_->EmitPush(r0); // Push the object being iterated over.
2174
2175 // Check cache validity in generated code. This is a fast case for
2176 // the JSObject::IsSimpleEnum cache validity checks. If we cannot
2177 // guarantee cache validity, call the runtime system to check cache
2178 // validity or get the property names in a fixed array.
2179 JumpTarget call_runtime;
2180 JumpTarget loop(JumpTarget::BIDIRECTIONAL);
2181 JumpTarget check_prototype;
2182 JumpTarget use_cache;
2183 __ mov(r1, Operand(r0));
2184 loop.Bind();
2185 // Check that there are no elements.
2186 __ ldr(r2, FieldMemOperand(r1, JSObject::kElementsOffset));
2187 __ LoadRoot(r4, Heap::kEmptyFixedArrayRootIndex);
2188 __ cmp(r2, r4);
2189 call_runtime.Branch(ne);
2190 // Check that instance descriptors are not empty so that we can
2191 // check for an enum cache. Leave the map in r3 for the subsequent
2192 // prototype load.
2193 __ ldr(r3, FieldMemOperand(r1, HeapObject::kMapOffset));
2194 __ ldr(r2, FieldMemOperand(r3, Map::kInstanceDescriptorsOffset));
2195 __ LoadRoot(ip, Heap::kEmptyDescriptorArrayRootIndex);
2196 __ cmp(r2, ip);
2197 call_runtime.Branch(eq);
2198 // Check that there in an enum cache in the non-empty instance
2199 // descriptors. This is the case if the next enumeration index
2200 // field does not contain a smi.
2201 __ ldr(r2, FieldMemOperand(r2, DescriptorArray::kEnumerationIndexOffset));
2202 __ tst(r2, Operand(kSmiTagMask));
2203 call_runtime.Branch(eq);
2204 // For all objects but the receiver, check that the cache is empty.
2205 // r4: empty fixed array root.
2206 __ cmp(r1, r0);
2207 check_prototype.Branch(eq);
2208 __ ldr(r2, FieldMemOperand(r2, DescriptorArray::kEnumCacheBridgeCacheOffset));
2209 __ cmp(r2, r4);
2210 call_runtime.Branch(ne);
2211 check_prototype.Bind();
2212 // Load the prototype from the map and loop if non-null.
2213 __ ldr(r1, FieldMemOperand(r3, Map::kPrototypeOffset));
2214 __ LoadRoot(ip, Heap::kNullValueRootIndex);
2215 __ cmp(r1, ip);
2216 loop.Branch(ne);
2217 // The enum cache is valid. Load the map of the object being
2218 // iterated over and use the cache for the iteration.
2219 __ ldr(r0, FieldMemOperand(r0, HeapObject::kMapOffset));
2220 use_cache.Jump();
2221
2222 call_runtime.Bind();
2223 // Call the runtime to get the property names for the object.
2224 frame_->EmitPush(r0); // push the object (slot 4) for the runtime call
Steve Blocka7e24c12009-10-30 11:49:00 +00002225 frame_->CallRuntime(Runtime::kGetPropertyNamesFast, 1);
2226
Steve Blockd0582a62009-12-15 09:54:21 +00002227 // If we got a map from the runtime call, we can do a fast
2228 // modification check. Otherwise, we got a fixed array, and we have
2229 // to do a slow check.
2230 // r0: map or fixed array (result from call to
2231 // Runtime::kGetPropertyNamesFast)
Steve Blocka7e24c12009-10-30 11:49:00 +00002232 __ mov(r2, Operand(r0));
2233 __ ldr(r1, FieldMemOperand(r2, HeapObject::kMapOffset));
2234 __ LoadRoot(ip, Heap::kMetaMapRootIndex);
2235 __ cmp(r1, ip);
2236 fixed_array.Branch(ne);
2237
Steve Blockd0582a62009-12-15 09:54:21 +00002238 use_cache.Bind();
Steve Blocka7e24c12009-10-30 11:49:00 +00002239 // Get enum cache
Steve Blockd0582a62009-12-15 09:54:21 +00002240 // r0: map (either the result from a call to
2241 // Runtime::kGetPropertyNamesFast or has been fetched directly from
2242 // the object)
Steve Blocka7e24c12009-10-30 11:49:00 +00002243 __ mov(r1, Operand(r0));
2244 __ ldr(r1, FieldMemOperand(r1, Map::kInstanceDescriptorsOffset));
2245 __ ldr(r1, FieldMemOperand(r1, DescriptorArray::kEnumerationIndexOffset));
2246 __ ldr(r2,
2247 FieldMemOperand(r1, DescriptorArray::kEnumCacheBridgeCacheOffset));
2248
2249 frame_->EmitPush(r0); // map
2250 frame_->EmitPush(r2); // enum cache bridge cache
2251 __ ldr(r0, FieldMemOperand(r2, FixedArray::kLengthOffset));
2252 __ mov(r0, Operand(r0, LSL, kSmiTagSize));
2253 frame_->EmitPush(r0);
2254 __ mov(r0, Operand(Smi::FromInt(0)));
2255 frame_->EmitPush(r0);
2256 entry.Jump();
2257
2258 fixed_array.Bind();
2259 __ mov(r1, Operand(Smi::FromInt(0)));
2260 frame_->EmitPush(r1); // insert 0 in place of Map
2261 frame_->EmitPush(r0);
2262
2263 // Push the length of the array and the initial index onto the stack.
2264 __ ldr(r0, FieldMemOperand(r0, FixedArray::kLengthOffset));
2265 __ mov(r0, Operand(r0, LSL, kSmiTagSize));
2266 frame_->EmitPush(r0);
2267 __ mov(r0, Operand(Smi::FromInt(0))); // init index
2268 frame_->EmitPush(r0);
2269
2270 // Condition.
2271 entry.Bind();
2272 // sp[0] : index
2273 // sp[1] : array/enum cache length
2274 // sp[2] : array or enum cache
2275 // sp[3] : 0 or map
2276 // sp[4] : enumerable
2277 // Grab the current frame's height for the break and continue
2278 // targets only after all the state is pushed on the frame.
2279 node->break_target()->set_direction(JumpTarget::FORWARD_ONLY);
2280 node->continue_target()->set_direction(JumpTarget::FORWARD_ONLY);
2281
2282 __ ldr(r0, frame_->ElementAt(0)); // load the current count
2283 __ ldr(r1, frame_->ElementAt(1)); // load the length
Steve Block6ded16b2010-05-10 14:33:55 +01002284 __ cmp(r0, r1); // compare to the array length
Steve Blocka7e24c12009-10-30 11:49:00 +00002285 node->break_target()->Branch(hs);
2286
2287 __ ldr(r0, frame_->ElementAt(0));
2288
2289 // Get the i'th entry of the array.
2290 __ ldr(r2, frame_->ElementAt(2));
2291 __ add(r2, r2, Operand(FixedArray::kHeaderSize - kHeapObjectTag));
2292 __ ldr(r3, MemOperand(r2, r0, LSL, kPointerSizeLog2 - kSmiTagSize));
2293
2294 // Get Map or 0.
2295 __ ldr(r2, frame_->ElementAt(3));
2296 // Check if this (still) matches the map of the enumerable.
2297 // If not, we have to filter the key.
2298 __ ldr(r1, frame_->ElementAt(4));
2299 __ ldr(r1, FieldMemOperand(r1, HeapObject::kMapOffset));
2300 __ cmp(r1, Operand(r2));
2301 end_del_check.Branch(eq);
2302
2303 // Convert the entry to a string (or null if it isn't a property anymore).
2304 __ ldr(r0, frame_->ElementAt(4)); // push enumerable
2305 frame_->EmitPush(r0);
2306 frame_->EmitPush(r3); // push entry
Steve Blockd0582a62009-12-15 09:54:21 +00002307 frame_->InvokeBuiltin(Builtins::FILTER_KEY, CALL_JS, 2);
Steve Blocka7e24c12009-10-30 11:49:00 +00002308 __ mov(r3, Operand(r0));
2309
2310 // If the property has been removed while iterating, we just skip it.
2311 __ LoadRoot(ip, Heap::kNullValueRootIndex);
2312 __ cmp(r3, ip);
2313 node->continue_target()->Branch(eq);
2314
2315 end_del_check.Bind();
2316 // Store the entry in the 'each' expression and take another spin in the
2317 // loop. r3: i'th entry of the enum cache (or string there of)
2318 frame_->EmitPush(r3); // push entry
2319 { Reference each(this, node->each());
2320 if (!each.is_illegal()) {
2321 if (each.size() > 0) {
2322 __ ldr(r0, frame_->ElementAt(each.size()));
2323 frame_->EmitPush(r0);
Leon Clarked91b9f72010-01-27 17:25:45 +00002324 each.SetValue(NOT_CONST_INIT);
2325 frame_->Drop(2);
2326 } else {
2327 // If the reference was to a slot we rely on the convenient property
2328 // that it doesn't matter whether a value (eg, r3 pushed above) is
2329 // right on top of or right underneath a zero-sized reference.
2330 each.SetValue(NOT_CONST_INIT);
2331 frame_->Drop();
Steve Blocka7e24c12009-10-30 11:49:00 +00002332 }
2333 }
2334 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002335 // Body.
2336 CheckStack(); // TODO(1222600): ignore if body contains calls.
2337 VisitAndSpill(node->body());
2338
2339 // Next. Reestablish a spilled frame in case we are coming here via
2340 // a continue in the body.
2341 node->continue_target()->Bind();
2342 frame_->SpillAll();
2343 frame_->EmitPop(r0);
2344 __ add(r0, r0, Operand(Smi::FromInt(1)));
2345 frame_->EmitPush(r0);
2346 entry.Jump();
2347
2348 // Cleanup. No need to spill because VirtualFrame::Drop is safe for
2349 // any frame.
2350 node->break_target()->Bind();
2351 frame_->Drop(5);
2352
2353 // Exit.
2354 exit.Bind();
2355 node->continue_target()->Unuse();
2356 node->break_target()->Unuse();
2357 ASSERT(frame_->height() == original_height);
2358}
2359
2360
Steve Block3ce2e202009-11-05 08:53:23 +00002361void CodeGenerator::VisitTryCatchStatement(TryCatchStatement* node) {
Steve Blocka7e24c12009-10-30 11:49:00 +00002362#ifdef DEBUG
2363 int original_height = frame_->height();
2364#endif
Steve Block6ded16b2010-05-10 14:33:55 +01002365 VirtualFrame::SpilledScope spilled_scope(frame_);
Steve Block3ce2e202009-11-05 08:53:23 +00002366 Comment cmnt(masm_, "[ TryCatchStatement");
Steve Blocka7e24c12009-10-30 11:49:00 +00002367 CodeForStatementPosition(node);
2368
2369 JumpTarget try_block;
2370 JumpTarget exit;
2371
2372 try_block.Call();
2373 // --- Catch block ---
2374 frame_->EmitPush(r0);
2375
2376 // Store the caught exception in the catch variable.
Leon Clarkee46be812010-01-19 14:06:41 +00002377 Variable* catch_var = node->catch_var()->var();
2378 ASSERT(catch_var != NULL && catch_var->slot() != NULL);
2379 StoreToSlot(catch_var->slot(), NOT_CONST_INIT);
Steve Blocka7e24c12009-10-30 11:49:00 +00002380
2381 // Remove the exception from the stack.
2382 frame_->Drop();
2383
2384 VisitStatementsAndSpill(node->catch_block()->statements());
2385 if (frame_ != NULL) {
2386 exit.Jump();
2387 }
2388
2389
2390 // --- Try block ---
2391 try_block.Bind();
2392
2393 frame_->PushTryHandler(TRY_CATCH_HANDLER);
2394 int handler_height = frame_->height();
2395
2396 // Shadow the labels for all escapes from the try block, including
2397 // returns. During shadowing, the original label is hidden as the
2398 // LabelShadow and operations on the original actually affect the
2399 // shadowing label.
2400 //
2401 // We should probably try to unify the escaping labels and the return
2402 // label.
2403 int nof_escapes = node->escaping_targets()->length();
2404 List<ShadowTarget*> shadows(1 + nof_escapes);
2405
2406 // Add the shadow target for the function return.
2407 static const int kReturnShadowIndex = 0;
2408 shadows.Add(new ShadowTarget(&function_return_));
2409 bool function_return_was_shadowed = function_return_is_shadowed_;
2410 function_return_is_shadowed_ = true;
2411 ASSERT(shadows[kReturnShadowIndex]->other_target() == &function_return_);
2412
2413 // Add the remaining shadow targets.
2414 for (int i = 0; i < nof_escapes; i++) {
2415 shadows.Add(new ShadowTarget(node->escaping_targets()->at(i)));
2416 }
2417
2418 // Generate code for the statements in the try block.
2419 VisitStatementsAndSpill(node->try_block()->statements());
2420
2421 // Stop the introduced shadowing and count the number of required unlinks.
2422 // After shadowing stops, the original labels are unshadowed and the
2423 // LabelShadows represent the formerly shadowing labels.
2424 bool has_unlinks = false;
2425 for (int i = 0; i < shadows.length(); i++) {
2426 shadows[i]->StopShadowing();
2427 has_unlinks = has_unlinks || shadows[i]->is_linked();
2428 }
2429 function_return_is_shadowed_ = function_return_was_shadowed;
2430
2431 // Get an external reference to the handler address.
2432 ExternalReference handler_address(Top::k_handler_address);
2433
2434 // If we can fall off the end of the try block, unlink from try chain.
2435 if (has_valid_frame()) {
2436 // The next handler address is on top of the frame. Unlink from
2437 // the handler list and drop the rest of this handler from the
2438 // frame.
2439 ASSERT(StackHandlerConstants::kNextOffset == 0);
2440 frame_->EmitPop(r1);
2441 __ mov(r3, Operand(handler_address));
2442 __ str(r1, MemOperand(r3));
2443 frame_->Drop(StackHandlerConstants::kSize / kPointerSize - 1);
2444 if (has_unlinks) {
2445 exit.Jump();
2446 }
2447 }
2448
2449 // Generate unlink code for the (formerly) shadowing labels that have been
2450 // jumped to. Deallocate each shadow target.
2451 for (int i = 0; i < shadows.length(); i++) {
2452 if (shadows[i]->is_linked()) {
2453 // Unlink from try chain;
2454 shadows[i]->Bind();
2455 // Because we can be jumping here (to spilled code) from unspilled
2456 // code, we need to reestablish a spilled frame at this block.
2457 frame_->SpillAll();
2458
2459 // Reload sp from the top handler, because some statements that we
2460 // break from (eg, for...in) may have left stuff on the stack.
2461 __ mov(r3, Operand(handler_address));
2462 __ ldr(sp, MemOperand(r3));
2463 frame_->Forget(frame_->height() - handler_height);
2464
2465 ASSERT(StackHandlerConstants::kNextOffset == 0);
2466 frame_->EmitPop(r1);
2467 __ str(r1, MemOperand(r3));
2468 frame_->Drop(StackHandlerConstants::kSize / kPointerSize - 1);
2469
2470 if (!function_return_is_shadowed_ && i == kReturnShadowIndex) {
2471 frame_->PrepareForReturn();
2472 }
2473 shadows[i]->other_target()->Jump();
2474 }
2475 }
2476
2477 exit.Bind();
2478 ASSERT(!has_valid_frame() || frame_->height() == original_height);
2479}
2480
2481
Steve Block3ce2e202009-11-05 08:53:23 +00002482void CodeGenerator::VisitTryFinallyStatement(TryFinallyStatement* node) {
Steve Blocka7e24c12009-10-30 11:49:00 +00002483#ifdef DEBUG
2484 int original_height = frame_->height();
2485#endif
Steve Block6ded16b2010-05-10 14:33:55 +01002486 VirtualFrame::SpilledScope spilled_scope(frame_);
Steve Block3ce2e202009-11-05 08:53:23 +00002487 Comment cmnt(masm_, "[ TryFinallyStatement");
Steve Blocka7e24c12009-10-30 11:49:00 +00002488 CodeForStatementPosition(node);
2489
2490 // State: Used to keep track of reason for entering the finally
2491 // block. Should probably be extended to hold information for
2492 // break/continue from within the try block.
2493 enum { FALLING, THROWING, JUMPING };
2494
2495 JumpTarget try_block;
2496 JumpTarget finally_block;
2497
2498 try_block.Call();
2499
2500 frame_->EmitPush(r0); // save exception object on the stack
2501 // In case of thrown exceptions, this is where we continue.
2502 __ mov(r2, Operand(Smi::FromInt(THROWING)));
2503 finally_block.Jump();
2504
2505 // --- Try block ---
2506 try_block.Bind();
2507
2508 frame_->PushTryHandler(TRY_FINALLY_HANDLER);
2509 int handler_height = frame_->height();
2510
2511 // Shadow the labels for all escapes from the try block, including
2512 // returns. Shadowing hides the original label as the LabelShadow and
2513 // operations on the original actually affect the shadowing label.
2514 //
2515 // We should probably try to unify the escaping labels and the return
2516 // label.
2517 int nof_escapes = node->escaping_targets()->length();
2518 List<ShadowTarget*> shadows(1 + nof_escapes);
2519
2520 // Add the shadow target for the function return.
2521 static const int kReturnShadowIndex = 0;
2522 shadows.Add(new ShadowTarget(&function_return_));
2523 bool function_return_was_shadowed = function_return_is_shadowed_;
2524 function_return_is_shadowed_ = true;
2525 ASSERT(shadows[kReturnShadowIndex]->other_target() == &function_return_);
2526
2527 // Add the remaining shadow targets.
2528 for (int i = 0; i < nof_escapes; i++) {
2529 shadows.Add(new ShadowTarget(node->escaping_targets()->at(i)));
2530 }
2531
2532 // Generate code for the statements in the try block.
2533 VisitStatementsAndSpill(node->try_block()->statements());
2534
2535 // Stop the introduced shadowing and count the number of required unlinks.
2536 // After shadowing stops, the original labels are unshadowed and the
2537 // LabelShadows represent the formerly shadowing labels.
2538 int nof_unlinks = 0;
2539 for (int i = 0; i < shadows.length(); i++) {
2540 shadows[i]->StopShadowing();
2541 if (shadows[i]->is_linked()) nof_unlinks++;
2542 }
2543 function_return_is_shadowed_ = function_return_was_shadowed;
2544
2545 // Get an external reference to the handler address.
2546 ExternalReference handler_address(Top::k_handler_address);
2547
2548 // If we can fall off the end of the try block, unlink from the try
2549 // chain and set the state on the frame to FALLING.
2550 if (has_valid_frame()) {
2551 // The next handler address is on top of the frame.
2552 ASSERT(StackHandlerConstants::kNextOffset == 0);
2553 frame_->EmitPop(r1);
2554 __ mov(r3, Operand(handler_address));
2555 __ str(r1, MemOperand(r3));
2556 frame_->Drop(StackHandlerConstants::kSize / kPointerSize - 1);
2557
2558 // Fake a top of stack value (unneeded when FALLING) and set the
2559 // state in r2, then jump around the unlink blocks if any.
2560 __ LoadRoot(r0, Heap::kUndefinedValueRootIndex);
2561 frame_->EmitPush(r0);
2562 __ mov(r2, Operand(Smi::FromInt(FALLING)));
2563 if (nof_unlinks > 0) {
2564 finally_block.Jump();
2565 }
2566 }
2567
2568 // Generate code to unlink and set the state for the (formerly)
2569 // shadowing targets that have been jumped to.
2570 for (int i = 0; i < shadows.length(); i++) {
2571 if (shadows[i]->is_linked()) {
2572 // If we have come from the shadowed return, the return value is
2573 // in (a non-refcounted reference to) r0. We must preserve it
2574 // until it is pushed.
2575 //
2576 // Because we can be jumping here (to spilled code) from
2577 // unspilled code, we need to reestablish a spilled frame at
2578 // this block.
2579 shadows[i]->Bind();
2580 frame_->SpillAll();
2581
2582 // Reload sp from the top handler, because some statements that
2583 // we break from (eg, for...in) may have left stuff on the
2584 // stack.
2585 __ mov(r3, Operand(handler_address));
2586 __ ldr(sp, MemOperand(r3));
2587 frame_->Forget(frame_->height() - handler_height);
2588
2589 // Unlink this handler and drop it from the frame. The next
2590 // handler address is currently on top of the frame.
2591 ASSERT(StackHandlerConstants::kNextOffset == 0);
2592 frame_->EmitPop(r1);
2593 __ str(r1, MemOperand(r3));
2594 frame_->Drop(StackHandlerConstants::kSize / kPointerSize - 1);
2595
2596 if (i == kReturnShadowIndex) {
2597 // If this label shadowed the function return, materialize the
2598 // return value on the stack.
2599 frame_->EmitPush(r0);
2600 } else {
2601 // Fake TOS for targets that shadowed breaks and continues.
2602 __ LoadRoot(r0, Heap::kUndefinedValueRootIndex);
2603 frame_->EmitPush(r0);
2604 }
2605 __ mov(r2, Operand(Smi::FromInt(JUMPING + i)));
2606 if (--nof_unlinks > 0) {
2607 // If this is not the last unlink block, jump around the next.
2608 finally_block.Jump();
2609 }
2610 }
2611 }
2612
2613 // --- Finally block ---
2614 finally_block.Bind();
2615
2616 // Push the state on the stack.
2617 frame_->EmitPush(r2);
2618
2619 // We keep two elements on the stack - the (possibly faked) result
2620 // and the state - while evaluating the finally block.
2621 //
2622 // Generate code for the statements in the finally block.
2623 VisitStatementsAndSpill(node->finally_block()->statements());
2624
2625 if (has_valid_frame()) {
2626 // Restore state and return value or faked TOS.
2627 frame_->EmitPop(r2);
2628 frame_->EmitPop(r0);
2629 }
2630
2631 // Generate code to jump to the right destination for all used
2632 // formerly shadowing targets. Deallocate each shadow target.
2633 for (int i = 0; i < shadows.length(); i++) {
2634 if (has_valid_frame() && shadows[i]->is_bound()) {
2635 JumpTarget* original = shadows[i]->other_target();
2636 __ cmp(r2, Operand(Smi::FromInt(JUMPING + i)));
2637 if (!function_return_is_shadowed_ && i == kReturnShadowIndex) {
2638 JumpTarget skip;
2639 skip.Branch(ne);
2640 frame_->PrepareForReturn();
2641 original->Jump();
2642 skip.Bind();
2643 } else {
2644 original->Branch(eq);
2645 }
2646 }
2647 }
2648
2649 if (has_valid_frame()) {
2650 // Check if we need to rethrow the exception.
2651 JumpTarget exit;
2652 __ cmp(r2, Operand(Smi::FromInt(THROWING)));
2653 exit.Branch(ne);
2654
2655 // Rethrow exception.
2656 frame_->EmitPush(r0);
2657 frame_->CallRuntime(Runtime::kReThrow, 1);
2658
2659 // Done.
2660 exit.Bind();
2661 }
2662 ASSERT(!has_valid_frame() || frame_->height() == original_height);
2663}
2664
2665
2666void CodeGenerator::VisitDebuggerStatement(DebuggerStatement* node) {
2667#ifdef DEBUG
2668 int original_height = frame_->height();
2669#endif
Steve Block6ded16b2010-05-10 14:33:55 +01002670 VirtualFrame::SpilledScope spilled_scope(frame_);
Steve Blocka7e24c12009-10-30 11:49:00 +00002671 Comment cmnt(masm_, "[ DebuggerStatament");
2672 CodeForStatementPosition(node);
2673#ifdef ENABLE_DEBUGGER_SUPPORT
Andrei Popescu402d9372010-02-26 13:31:12 +00002674 frame_->DebugBreak();
Steve Blocka7e24c12009-10-30 11:49:00 +00002675#endif
2676 // Ignore the return value.
2677 ASSERT(frame_->height() == original_height);
2678}
2679
2680
Steve Block6ded16b2010-05-10 14:33:55 +01002681void CodeGenerator::InstantiateFunction(
2682 Handle<SharedFunctionInfo> function_info) {
2683 VirtualFrame::SpilledScope spilled_scope(frame_);
2684 __ mov(r0, Operand(function_info));
Leon Clarkee46be812010-01-19 14:06:41 +00002685 // Use the fast case closure allocation code that allocates in new
2686 // space for nested functions that don't need literals cloning.
Steve Block6ded16b2010-05-10 14:33:55 +01002687 if (scope()->is_function_scope() && function_info->num_literals() == 0) {
Leon Clarkee46be812010-01-19 14:06:41 +00002688 FastNewClosureStub stub;
2689 frame_->EmitPush(r0);
2690 frame_->CallStub(&stub, 1);
2691 frame_->EmitPush(r0);
2692 } else {
2693 // Create a new closure.
2694 frame_->EmitPush(cp);
2695 frame_->EmitPush(r0);
2696 frame_->CallRuntime(Runtime::kNewClosure, 2);
2697 frame_->EmitPush(r0);
2698 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002699}
2700
2701
2702void CodeGenerator::VisitFunctionLiteral(FunctionLiteral* node) {
2703#ifdef DEBUG
2704 int original_height = frame_->height();
2705#endif
Steve Block6ded16b2010-05-10 14:33:55 +01002706 VirtualFrame::SpilledScope spilled_scope(frame_);
Steve Blocka7e24c12009-10-30 11:49:00 +00002707 Comment cmnt(masm_, "[ FunctionLiteral");
2708
Steve Block6ded16b2010-05-10 14:33:55 +01002709 // Build the function info and instantiate it.
2710 Handle<SharedFunctionInfo> function_info =
2711 Compiler::BuildFunctionInfo(node, script(), this);
Steve Blocka7e24c12009-10-30 11:49:00 +00002712 // Check for stack-overflow exception.
2713 if (HasStackOverflow()) {
2714 ASSERT(frame_->height() == original_height);
2715 return;
2716 }
Steve Block6ded16b2010-05-10 14:33:55 +01002717 InstantiateFunction(function_info);
2718 ASSERT_EQ(original_height + 1, frame_->height());
Steve Blocka7e24c12009-10-30 11:49:00 +00002719}
2720
2721
Steve Block6ded16b2010-05-10 14:33:55 +01002722void CodeGenerator::VisitSharedFunctionInfoLiteral(
2723 SharedFunctionInfoLiteral* node) {
Steve Blocka7e24c12009-10-30 11:49:00 +00002724#ifdef DEBUG
2725 int original_height = frame_->height();
2726#endif
Steve Block6ded16b2010-05-10 14:33:55 +01002727 VirtualFrame::SpilledScope spilled_scope(frame_);
2728 Comment cmnt(masm_, "[ SharedFunctionInfoLiteral");
2729 InstantiateFunction(node->shared_function_info());
2730 ASSERT_EQ(original_height + 1, frame_->height());
Steve Blocka7e24c12009-10-30 11:49:00 +00002731}
2732
2733
2734void CodeGenerator::VisitConditional(Conditional* node) {
2735#ifdef DEBUG
2736 int original_height = frame_->height();
2737#endif
Steve Block6ded16b2010-05-10 14:33:55 +01002738 VirtualFrame::SpilledScope spilled_scope(frame_);
Steve Blocka7e24c12009-10-30 11:49:00 +00002739 Comment cmnt(masm_, "[ Conditional");
2740 JumpTarget then;
2741 JumpTarget else_;
Steve Blockd0582a62009-12-15 09:54:21 +00002742 LoadConditionAndSpill(node->condition(), &then, &else_, true);
Steve Blocka7e24c12009-10-30 11:49:00 +00002743 if (has_valid_frame()) {
2744 Branch(false, &else_);
2745 }
2746 if (has_valid_frame() || then.is_linked()) {
2747 then.Bind();
Steve Blockd0582a62009-12-15 09:54:21 +00002748 LoadAndSpill(node->then_expression());
Steve Blocka7e24c12009-10-30 11:49:00 +00002749 }
2750 if (else_.is_linked()) {
2751 JumpTarget exit;
2752 if (has_valid_frame()) exit.Jump();
2753 else_.Bind();
Steve Blockd0582a62009-12-15 09:54:21 +00002754 LoadAndSpill(node->else_expression());
Steve Blocka7e24c12009-10-30 11:49:00 +00002755 if (exit.is_linked()) exit.Bind();
2756 }
Steve Block6ded16b2010-05-10 14:33:55 +01002757 ASSERT_EQ(original_height + 1, frame_->height());
Steve Blocka7e24c12009-10-30 11:49:00 +00002758}
2759
2760
2761void CodeGenerator::LoadFromSlot(Slot* slot, TypeofState typeof_state) {
Steve Blocka7e24c12009-10-30 11:49:00 +00002762 if (slot->type() == Slot::LOOKUP) {
2763 ASSERT(slot->var()->is_dynamic());
2764
Steve Block6ded16b2010-05-10 14:33:55 +01002765 // JumpTargets do not yet support merging frames so the frame must be
2766 // spilled when jumping to these targets.
Steve Blocka7e24c12009-10-30 11:49:00 +00002767 JumpTarget slow;
2768 JumpTarget done;
2769
2770 // Generate fast-case code for variables that might be shadowed by
2771 // eval-introduced variables. Eval is used a lot without
2772 // introducing variables. In those cases, we do not want to
2773 // perform a runtime call for all variables in the scope
2774 // containing the eval.
2775 if (slot->var()->mode() == Variable::DYNAMIC_GLOBAL) {
Steve Block6ded16b2010-05-10 14:33:55 +01002776 LoadFromGlobalSlotCheckExtensions(slot, typeof_state, &slow);
Steve Blocka7e24c12009-10-30 11:49:00 +00002777 // If there was no control flow to slow, we can exit early.
2778 if (!slow.is_linked()) {
2779 frame_->EmitPush(r0);
2780 return;
2781 }
Steve Block6ded16b2010-05-10 14:33:55 +01002782 frame_->SpillAll();
Steve Blocka7e24c12009-10-30 11:49:00 +00002783
2784 done.Jump();
2785
2786 } else if (slot->var()->mode() == Variable::DYNAMIC_LOCAL) {
Steve Block6ded16b2010-05-10 14:33:55 +01002787 frame_->SpillAll();
Steve Blocka7e24c12009-10-30 11:49:00 +00002788 Slot* potential_slot = slot->var()->local_if_not_shadowed()->slot();
2789 // Only generate the fast case for locals that rewrite to slots.
2790 // This rules out argument loads.
2791 if (potential_slot != NULL) {
2792 __ ldr(r0,
2793 ContextSlotOperandCheckExtensions(potential_slot,
2794 r1,
2795 r2,
2796 &slow));
2797 if (potential_slot->var()->mode() == Variable::CONST) {
2798 __ LoadRoot(ip, Heap::kTheHoleValueRootIndex);
2799 __ cmp(r0, ip);
2800 __ LoadRoot(r0, Heap::kUndefinedValueRootIndex, eq);
2801 }
2802 // There is always control flow to slow from
2803 // ContextSlotOperandCheckExtensions so we have to jump around
2804 // it.
2805 done.Jump();
2806 }
2807 }
2808
2809 slow.Bind();
Steve Block6ded16b2010-05-10 14:33:55 +01002810 VirtualFrame::SpilledScope spilled_scope(frame_);
Steve Blocka7e24c12009-10-30 11:49:00 +00002811 frame_->EmitPush(cp);
2812 __ mov(r0, Operand(slot->var()->name()));
2813 frame_->EmitPush(r0);
2814
2815 if (typeof_state == INSIDE_TYPEOF) {
2816 frame_->CallRuntime(Runtime::kLoadContextSlotNoReferenceError, 2);
2817 } else {
2818 frame_->CallRuntime(Runtime::kLoadContextSlot, 2);
2819 }
2820
2821 done.Bind();
2822 frame_->EmitPush(r0);
2823
2824 } else {
Steve Block6ded16b2010-05-10 14:33:55 +01002825 Register scratch = VirtualFrame::scratch0();
2826 frame_->EmitPush(SlotOperand(slot, scratch));
Steve Blocka7e24c12009-10-30 11:49:00 +00002827 if (slot->var()->mode() == Variable::CONST) {
2828 // Const slots may contain 'the hole' value (the constant hasn't been
2829 // initialized yet) which needs to be converted into the 'undefined'
2830 // value.
2831 Comment cmnt(masm_, "[ Unhole const");
Steve Block6ded16b2010-05-10 14:33:55 +01002832 frame_->EmitPop(scratch);
Steve Blocka7e24c12009-10-30 11:49:00 +00002833 __ LoadRoot(ip, Heap::kTheHoleValueRootIndex);
Steve Block6ded16b2010-05-10 14:33:55 +01002834 __ cmp(scratch, ip);
2835 __ LoadRoot(scratch, Heap::kUndefinedValueRootIndex, eq);
2836 frame_->EmitPush(scratch);
Steve Blocka7e24c12009-10-30 11:49:00 +00002837 }
2838 }
2839}
2840
2841
Steve Block6ded16b2010-05-10 14:33:55 +01002842void CodeGenerator::LoadFromSlotCheckForArguments(Slot* slot,
2843 TypeofState state) {
2844 LoadFromSlot(slot, state);
2845
2846 // Bail out quickly if we're not using lazy arguments allocation.
2847 if (ArgumentsMode() != LAZY_ARGUMENTS_ALLOCATION) return;
2848
2849 // ... or if the slot isn't a non-parameter arguments slot.
2850 if (slot->type() == Slot::PARAMETER || !slot->is_arguments()) return;
2851
2852 VirtualFrame::SpilledScope spilled_scope(frame_);
2853
2854 // Load the loaded value from the stack into r0 but leave it on the
2855 // stack.
2856 __ ldr(r0, MemOperand(sp, 0));
2857
2858 // If the loaded value is the sentinel that indicates that we
2859 // haven't loaded the arguments object yet, we need to do it now.
2860 JumpTarget exit;
2861 __ LoadRoot(ip, Heap::kTheHoleValueRootIndex);
2862 __ cmp(r0, ip);
2863 exit.Branch(ne);
2864 frame_->Drop();
2865 StoreArgumentsObject(false);
2866 exit.Bind();
2867}
2868
2869
Leon Clarkee46be812010-01-19 14:06:41 +00002870void CodeGenerator::StoreToSlot(Slot* slot, InitState init_state) {
2871 ASSERT(slot != NULL);
2872 if (slot->type() == Slot::LOOKUP) {
Steve Block6ded16b2010-05-10 14:33:55 +01002873 VirtualFrame::SpilledScope spilled_scope(frame_);
Leon Clarkee46be812010-01-19 14:06:41 +00002874 ASSERT(slot->var()->is_dynamic());
2875
2876 // For now, just do a runtime call.
2877 frame_->EmitPush(cp);
2878 __ mov(r0, Operand(slot->var()->name()));
2879 frame_->EmitPush(r0);
2880
2881 if (init_state == CONST_INIT) {
2882 // Same as the case for a normal store, but ignores attribute
2883 // (e.g. READ_ONLY) of context slot so that we can initialize
2884 // const properties (introduced via eval("const foo = (some
2885 // expr);")). Also, uses the current function context instead of
2886 // the top context.
2887 //
2888 // Note that we must declare the foo upon entry of eval(), via a
2889 // context slot declaration, but we cannot initialize it at the
2890 // same time, because the const declaration may be at the end of
2891 // the eval code (sigh...) and the const variable may have been
2892 // used before (where its value is 'undefined'). Thus, we can only
2893 // do the initialization when we actually encounter the expression
2894 // and when the expression operands are defined and valid, and
2895 // thus we need the split into 2 operations: declaration of the
2896 // context slot followed by initialization.
2897 frame_->CallRuntime(Runtime::kInitializeConstContextSlot, 3);
2898 } else {
2899 frame_->CallRuntime(Runtime::kStoreContextSlot, 3);
2900 }
2901 // Storing a variable must keep the (new) value on the expression
2902 // stack. This is necessary for compiling assignment expressions.
2903 frame_->EmitPush(r0);
2904
2905 } else {
2906 ASSERT(!slot->var()->is_dynamic());
Steve Block6ded16b2010-05-10 14:33:55 +01002907 Register scratch = VirtualFrame::scratch0();
2908 VirtualFrame::RegisterAllocationScope scope(this);
Leon Clarkee46be812010-01-19 14:06:41 +00002909
Steve Block6ded16b2010-05-10 14:33:55 +01002910 // The frame must be spilled when branching to this target.
Leon Clarkee46be812010-01-19 14:06:41 +00002911 JumpTarget exit;
Steve Block6ded16b2010-05-10 14:33:55 +01002912
Leon Clarkee46be812010-01-19 14:06:41 +00002913 if (init_state == CONST_INIT) {
2914 ASSERT(slot->var()->mode() == Variable::CONST);
2915 // Only the first const initialization must be executed (the slot
2916 // still contains 'the hole' value). When the assignment is
2917 // executed, the code is identical to a normal store (see below).
2918 Comment cmnt(masm_, "[ Init const");
Steve Block6ded16b2010-05-10 14:33:55 +01002919 __ ldr(scratch, SlotOperand(slot, scratch));
Leon Clarkee46be812010-01-19 14:06:41 +00002920 __ LoadRoot(ip, Heap::kTheHoleValueRootIndex);
Steve Block6ded16b2010-05-10 14:33:55 +01002921 __ cmp(scratch, ip);
2922 frame_->SpillAll();
Leon Clarkee46be812010-01-19 14:06:41 +00002923 exit.Branch(ne);
2924 }
2925
2926 // We must execute the store. Storing a variable must keep the
2927 // (new) value on the stack. This is necessary for compiling
2928 // assignment expressions.
2929 //
2930 // Note: We will reach here even with slot->var()->mode() ==
2931 // Variable::CONST because of const declarations which will
2932 // initialize consts to 'the hole' value and by doing so, end up
2933 // calling this code. r2 may be loaded with context; used below in
2934 // RecordWrite.
Steve Block6ded16b2010-05-10 14:33:55 +01002935 Register tos = frame_->Peek();
2936 __ str(tos, SlotOperand(slot, scratch));
Leon Clarkee46be812010-01-19 14:06:41 +00002937 if (slot->type() == Slot::CONTEXT) {
2938 // Skip write barrier if the written value is a smi.
Steve Block6ded16b2010-05-10 14:33:55 +01002939 __ tst(tos, Operand(kSmiTagMask));
2940 // We don't use tos any more after here.
2941 VirtualFrame::SpilledScope spilled_scope(frame_);
Leon Clarkee46be812010-01-19 14:06:41 +00002942 exit.Branch(eq);
Steve Block6ded16b2010-05-10 14:33:55 +01002943 // scratch is loaded with context when calling SlotOperand above.
Leon Clarkee46be812010-01-19 14:06:41 +00002944 int offset = FixedArray::kHeaderSize + slot->index() * kPointerSize;
2945 __ mov(r3, Operand(offset));
Steve Block6ded16b2010-05-10 14:33:55 +01002946 // r1 could be identical with tos, but that doesn't matter.
2947 __ RecordWrite(scratch, r3, r1);
Leon Clarkee46be812010-01-19 14:06:41 +00002948 }
2949 // If we definitely did not jump over the assignment, we do not need
2950 // to bind the exit label. Doing so can defeat peephole
2951 // optimization.
2952 if (init_state == CONST_INIT || slot->type() == Slot::CONTEXT) {
Steve Block6ded16b2010-05-10 14:33:55 +01002953 frame_->SpillAll();
Leon Clarkee46be812010-01-19 14:06:41 +00002954 exit.Bind();
2955 }
2956 }
2957}
2958
2959
Steve Blocka7e24c12009-10-30 11:49:00 +00002960void CodeGenerator::LoadFromGlobalSlotCheckExtensions(Slot* slot,
2961 TypeofState typeof_state,
Steve Blocka7e24c12009-10-30 11:49:00 +00002962 JumpTarget* slow) {
2963 // Check that no extension objects have been created by calls to
2964 // eval from the current scope to the global scope.
Steve Block6ded16b2010-05-10 14:33:55 +01002965 Register tmp = frame_->scratch0();
2966 Register tmp2 = frame_->scratch1();
Steve Blocka7e24c12009-10-30 11:49:00 +00002967 Register context = cp;
2968 Scope* s = scope();
2969 while (s != NULL) {
2970 if (s->num_heap_slots() > 0) {
2971 if (s->calls_eval()) {
Steve Block6ded16b2010-05-10 14:33:55 +01002972 frame_->SpillAll();
Steve Blocka7e24c12009-10-30 11:49:00 +00002973 // Check that extension is NULL.
2974 __ ldr(tmp2, ContextOperand(context, Context::EXTENSION_INDEX));
2975 __ tst(tmp2, tmp2);
2976 slow->Branch(ne);
2977 }
2978 // Load next context in chain.
2979 __ ldr(tmp, ContextOperand(context, Context::CLOSURE_INDEX));
2980 __ ldr(tmp, FieldMemOperand(tmp, JSFunction::kContextOffset));
2981 context = tmp;
2982 }
2983 // If no outer scope calls eval, we do not need to check more
2984 // context extensions.
2985 if (!s->outer_scope_calls_eval() || s->is_eval_scope()) break;
2986 s = s->outer_scope();
2987 }
2988
2989 if (s->is_eval_scope()) {
Steve Block6ded16b2010-05-10 14:33:55 +01002990 frame_->SpillAll();
Steve Blocka7e24c12009-10-30 11:49:00 +00002991 Label next, fast;
Steve Block6ded16b2010-05-10 14:33:55 +01002992 __ Move(tmp, context);
Steve Blocka7e24c12009-10-30 11:49:00 +00002993 __ bind(&next);
2994 // Terminate at global context.
2995 __ ldr(tmp2, FieldMemOperand(tmp, HeapObject::kMapOffset));
2996 __ LoadRoot(ip, Heap::kGlobalContextMapRootIndex);
2997 __ cmp(tmp2, ip);
2998 __ b(eq, &fast);
2999 // Check that extension is NULL.
3000 __ ldr(tmp2, ContextOperand(tmp, Context::EXTENSION_INDEX));
3001 __ tst(tmp2, tmp2);
3002 slow->Branch(ne);
3003 // Load next context in chain.
3004 __ ldr(tmp, ContextOperand(tmp, Context::CLOSURE_INDEX));
3005 __ ldr(tmp, FieldMemOperand(tmp, JSFunction::kContextOffset));
3006 __ b(&next);
3007 __ bind(&fast);
3008 }
3009
Steve Blocka7e24c12009-10-30 11:49:00 +00003010 // Load the global object.
3011 LoadGlobal();
Steve Block6ded16b2010-05-10 14:33:55 +01003012 // Setup the name register and call load IC.
3013 frame_->CallLoadIC(slot->var()->name(),
3014 typeof_state == INSIDE_TYPEOF
3015 ? RelocInfo::CODE_TARGET
3016 : RelocInfo::CODE_TARGET_CONTEXT);
Steve Blocka7e24c12009-10-30 11:49:00 +00003017 // Drop the global object. The result is in r0.
3018 frame_->Drop();
3019}
3020
3021
3022void CodeGenerator::VisitSlot(Slot* node) {
3023#ifdef DEBUG
3024 int original_height = frame_->height();
3025#endif
Steve Blocka7e24c12009-10-30 11:49:00 +00003026 Comment cmnt(masm_, "[ Slot");
Steve Block6ded16b2010-05-10 14:33:55 +01003027 LoadFromSlotCheckForArguments(node, NOT_INSIDE_TYPEOF);
3028 ASSERT_EQ(original_height + 1, frame_->height());
Steve Blocka7e24c12009-10-30 11:49:00 +00003029}
3030
3031
3032void CodeGenerator::VisitVariableProxy(VariableProxy* node) {
3033#ifdef DEBUG
3034 int original_height = frame_->height();
3035#endif
Steve Blocka7e24c12009-10-30 11:49:00 +00003036 Comment cmnt(masm_, "[ VariableProxy");
3037
3038 Variable* var = node->var();
3039 Expression* expr = var->rewrite();
3040 if (expr != NULL) {
3041 Visit(expr);
3042 } else {
3043 ASSERT(var->is_global());
3044 Reference ref(this, node);
Steve Block6ded16b2010-05-10 14:33:55 +01003045 ref.GetValue();
Steve Blocka7e24c12009-10-30 11:49:00 +00003046 }
Steve Block6ded16b2010-05-10 14:33:55 +01003047 ASSERT_EQ(original_height + 1, frame_->height());
Steve Blocka7e24c12009-10-30 11:49:00 +00003048}
3049
3050
3051void CodeGenerator::VisitLiteral(Literal* node) {
3052#ifdef DEBUG
3053 int original_height = frame_->height();
3054#endif
Steve Blocka7e24c12009-10-30 11:49:00 +00003055 Comment cmnt(masm_, "[ Literal");
Steve Block6ded16b2010-05-10 14:33:55 +01003056 Register reg = frame_->GetTOSRegister();
3057 __ mov(reg, Operand(node->handle()));
3058 frame_->EmitPush(reg);
3059 ASSERT_EQ(original_height + 1, frame_->height());
Steve Blocka7e24c12009-10-30 11:49:00 +00003060}
3061
3062
3063void CodeGenerator::VisitRegExpLiteral(RegExpLiteral* node) {
3064#ifdef DEBUG
3065 int original_height = frame_->height();
3066#endif
Steve Block6ded16b2010-05-10 14:33:55 +01003067 VirtualFrame::SpilledScope spilled_scope(frame_);
Steve Blocka7e24c12009-10-30 11:49:00 +00003068 Comment cmnt(masm_, "[ RexExp Literal");
3069
3070 // Retrieve the literal array and check the allocated entry.
3071
3072 // Load the function of this activation.
3073 __ ldr(r1, frame_->Function());
3074
3075 // Load the literals array of the function.
3076 __ ldr(r1, FieldMemOperand(r1, JSFunction::kLiteralsOffset));
3077
3078 // Load the literal at the ast saved index.
3079 int literal_offset =
3080 FixedArray::kHeaderSize + node->literal_index() * kPointerSize;
3081 __ ldr(r2, FieldMemOperand(r1, literal_offset));
3082
3083 JumpTarget done;
3084 __ LoadRoot(ip, Heap::kUndefinedValueRootIndex);
3085 __ cmp(r2, ip);
3086 done.Branch(ne);
3087
3088 // If the entry is undefined we call the runtime system to computed
3089 // the literal.
3090 frame_->EmitPush(r1); // literal array (0)
3091 __ mov(r0, Operand(Smi::FromInt(node->literal_index())));
3092 frame_->EmitPush(r0); // literal index (1)
3093 __ mov(r0, Operand(node->pattern())); // RegExp pattern (2)
3094 frame_->EmitPush(r0);
3095 __ mov(r0, Operand(node->flags())); // RegExp flags (3)
3096 frame_->EmitPush(r0);
3097 frame_->CallRuntime(Runtime::kMaterializeRegExpLiteral, 4);
3098 __ mov(r2, Operand(r0));
3099
3100 done.Bind();
3101 // Push the literal.
3102 frame_->EmitPush(r2);
Steve Block6ded16b2010-05-10 14:33:55 +01003103 ASSERT_EQ(original_height + 1, frame_->height());
Steve Blocka7e24c12009-10-30 11:49:00 +00003104}
3105
3106
Steve Blocka7e24c12009-10-30 11:49:00 +00003107void CodeGenerator::VisitObjectLiteral(ObjectLiteral* node) {
3108#ifdef DEBUG
3109 int original_height = frame_->height();
3110#endif
Steve Block6ded16b2010-05-10 14:33:55 +01003111 VirtualFrame::SpilledScope spilled_scope(frame_);
Steve Blocka7e24c12009-10-30 11:49:00 +00003112 Comment cmnt(masm_, "[ ObjectLiteral");
3113
Steve Blocka7e24c12009-10-30 11:49:00 +00003114 // Load the function of this activation.
Steve Block6ded16b2010-05-10 14:33:55 +01003115 __ ldr(r3, frame_->Function());
Leon Clarkee46be812010-01-19 14:06:41 +00003116 // Literal array.
Steve Block6ded16b2010-05-10 14:33:55 +01003117 __ ldr(r3, FieldMemOperand(r3, JSFunction::kLiteralsOffset));
Leon Clarkee46be812010-01-19 14:06:41 +00003118 // Literal index.
Steve Block6ded16b2010-05-10 14:33:55 +01003119 __ mov(r2, Operand(Smi::FromInt(node->literal_index())));
Leon Clarkee46be812010-01-19 14:06:41 +00003120 // Constant properties.
Steve Block6ded16b2010-05-10 14:33:55 +01003121 __ mov(r1, Operand(node->constant_properties()));
3122 // Should the object literal have fast elements?
3123 __ mov(r0, Operand(Smi::FromInt(node->fast_elements() ? 1 : 0)));
3124 frame_->EmitPushMultiple(4, r3.bit() | r2.bit() | r1.bit() | r0.bit());
Leon Clarkee46be812010-01-19 14:06:41 +00003125 if (node->depth() > 1) {
Steve Block6ded16b2010-05-10 14:33:55 +01003126 frame_->CallRuntime(Runtime::kCreateObjectLiteral, 4);
Leon Clarkee46be812010-01-19 14:06:41 +00003127 } else {
Steve Block6ded16b2010-05-10 14:33:55 +01003128 frame_->CallRuntime(Runtime::kCreateObjectLiteralShallow, 4);
Steve Blocka7e24c12009-10-30 11:49:00 +00003129 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003130 frame_->EmitPush(r0); // save the result
Steve Blocka7e24c12009-10-30 11:49:00 +00003131 for (int i = 0; i < node->properties()->length(); i++) {
Andrei Popescu402d9372010-02-26 13:31:12 +00003132 // At the start of each iteration, the top of stack contains
3133 // the newly created object literal.
Steve Blocka7e24c12009-10-30 11:49:00 +00003134 ObjectLiteral::Property* property = node->properties()->at(i);
3135 Literal* key = property->key();
3136 Expression* value = property->value();
3137 switch (property->kind()) {
3138 case ObjectLiteral::Property::CONSTANT:
3139 break;
3140 case ObjectLiteral::Property::MATERIALIZED_LITERAL:
3141 if (CompileTimeValue::IsCompileTimeValue(property->value())) break;
3142 // else fall through
Andrei Popescu402d9372010-02-26 13:31:12 +00003143 case ObjectLiteral::Property::COMPUTED:
3144 if (key->handle()->IsSymbol()) {
3145 Handle<Code> ic(Builtins::builtin(Builtins::StoreIC_Initialize));
3146 LoadAndSpill(value);
3147 frame_->EmitPop(r0);
3148 __ mov(r2, Operand(key->handle()));
3149 __ ldr(r1, frame_->Top()); // Load the receiver.
3150 frame_->CallCodeObject(ic, RelocInfo::CODE_TARGET, 0);
3151 break;
3152 }
3153 // else fall through
Steve Blocka7e24c12009-10-30 11:49:00 +00003154 case ObjectLiteral::Property::PROTOTYPE: {
Andrei Popescu402d9372010-02-26 13:31:12 +00003155 __ ldr(r0, frame_->Top());
Steve Blocka7e24c12009-10-30 11:49:00 +00003156 frame_->EmitPush(r0); // dup the result
3157 LoadAndSpill(key);
3158 LoadAndSpill(value);
3159 frame_->CallRuntime(Runtime::kSetProperty, 3);
Steve Blocka7e24c12009-10-30 11:49:00 +00003160 break;
3161 }
3162 case ObjectLiteral::Property::SETTER: {
Andrei Popescu402d9372010-02-26 13:31:12 +00003163 __ ldr(r0, frame_->Top());
Steve Blocka7e24c12009-10-30 11:49:00 +00003164 frame_->EmitPush(r0);
3165 LoadAndSpill(key);
3166 __ mov(r0, Operand(Smi::FromInt(1)));
3167 frame_->EmitPush(r0);
3168 LoadAndSpill(value);
3169 frame_->CallRuntime(Runtime::kDefineAccessor, 4);
Steve Blocka7e24c12009-10-30 11:49:00 +00003170 break;
3171 }
3172 case ObjectLiteral::Property::GETTER: {
Andrei Popescu402d9372010-02-26 13:31:12 +00003173 __ ldr(r0, frame_->Top());
Steve Blocka7e24c12009-10-30 11:49:00 +00003174 frame_->EmitPush(r0);
3175 LoadAndSpill(key);
3176 __ mov(r0, Operand(Smi::FromInt(0)));
3177 frame_->EmitPush(r0);
3178 LoadAndSpill(value);
3179 frame_->CallRuntime(Runtime::kDefineAccessor, 4);
Steve Blocka7e24c12009-10-30 11:49:00 +00003180 break;
3181 }
3182 }
3183 }
Steve Block6ded16b2010-05-10 14:33:55 +01003184 ASSERT_EQ(original_height + 1, frame_->height());
Steve Blocka7e24c12009-10-30 11:49:00 +00003185}
3186
3187
Steve Blocka7e24c12009-10-30 11:49:00 +00003188void CodeGenerator::VisitArrayLiteral(ArrayLiteral* node) {
3189#ifdef DEBUG
3190 int original_height = frame_->height();
3191#endif
Steve Block6ded16b2010-05-10 14:33:55 +01003192 VirtualFrame::SpilledScope spilled_scope(frame_);
Steve Blocka7e24c12009-10-30 11:49:00 +00003193 Comment cmnt(masm_, "[ ArrayLiteral");
3194
Steve Blocka7e24c12009-10-30 11:49:00 +00003195 // Load the function of this activation.
Leon Clarkee46be812010-01-19 14:06:41 +00003196 __ ldr(r2, frame_->Function());
Andrei Popescu402d9372010-02-26 13:31:12 +00003197 // Load the literals array of the function.
Leon Clarkee46be812010-01-19 14:06:41 +00003198 __ ldr(r2, FieldMemOperand(r2, JSFunction::kLiteralsOffset));
Leon Clarkee46be812010-01-19 14:06:41 +00003199 __ mov(r1, Operand(Smi::FromInt(node->literal_index())));
Leon Clarkee46be812010-01-19 14:06:41 +00003200 __ mov(r0, Operand(node->constant_elements()));
3201 frame_->EmitPushMultiple(3, r2.bit() | r1.bit() | r0.bit());
Andrei Popescu402d9372010-02-26 13:31:12 +00003202 int length = node->values()->length();
Leon Clarkee46be812010-01-19 14:06:41 +00003203 if (node->depth() > 1) {
3204 frame_->CallRuntime(Runtime::kCreateArrayLiteral, 3);
Andrei Popescu402d9372010-02-26 13:31:12 +00003205 } else if (length > FastCloneShallowArrayStub::kMaximumLength) {
Leon Clarkee46be812010-01-19 14:06:41 +00003206 frame_->CallRuntime(Runtime::kCreateArrayLiteralShallow, 3);
Andrei Popescu402d9372010-02-26 13:31:12 +00003207 } else {
3208 FastCloneShallowArrayStub stub(length);
3209 frame_->CallStub(&stub, 3);
Steve Blocka7e24c12009-10-30 11:49:00 +00003210 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003211 frame_->EmitPush(r0); // save the result
Leon Clarkee46be812010-01-19 14:06:41 +00003212 // r0: created object literal
Steve Blocka7e24c12009-10-30 11:49:00 +00003213
3214 // Generate code to set the elements in the array that are not
3215 // literals.
3216 for (int i = 0; i < node->values()->length(); i++) {
3217 Expression* value = node->values()->at(i);
3218
3219 // If value is a literal the property value is already set in the
3220 // boilerplate object.
3221 if (value->AsLiteral() != NULL) continue;
3222 // If value is a materialized literal the property value is already set
3223 // in the boilerplate object if it is simple.
3224 if (CompileTimeValue::IsCompileTimeValue(value)) continue;
3225
3226 // The property must be set by generated code.
3227 LoadAndSpill(value);
3228 frame_->EmitPop(r0);
3229
3230 // Fetch the object literal.
3231 __ ldr(r1, frame_->Top());
3232 // Get the elements array.
3233 __ ldr(r1, FieldMemOperand(r1, JSObject::kElementsOffset));
3234
3235 // Write to the indexed properties array.
3236 int offset = i * kPointerSize + FixedArray::kHeaderSize;
3237 __ str(r0, FieldMemOperand(r1, offset));
3238
3239 // Update the write barrier for the array address.
3240 __ mov(r3, Operand(offset));
3241 __ RecordWrite(r1, r3, r2);
3242 }
Steve Block6ded16b2010-05-10 14:33:55 +01003243 ASSERT_EQ(original_height + 1, frame_->height());
Steve Blocka7e24c12009-10-30 11:49:00 +00003244}
3245
3246
3247void CodeGenerator::VisitCatchExtensionObject(CatchExtensionObject* node) {
3248#ifdef DEBUG
3249 int original_height = frame_->height();
3250#endif
Steve Block6ded16b2010-05-10 14:33:55 +01003251 VirtualFrame::SpilledScope spilled_scope(frame_);
Steve Blocka7e24c12009-10-30 11:49:00 +00003252 // Call runtime routine to allocate the catch extension object and
3253 // assign the exception value to the catch variable.
3254 Comment cmnt(masm_, "[ CatchExtensionObject");
3255 LoadAndSpill(node->key());
3256 LoadAndSpill(node->value());
3257 frame_->CallRuntime(Runtime::kCreateCatchExtensionObject, 2);
3258 frame_->EmitPush(r0);
Steve Block6ded16b2010-05-10 14:33:55 +01003259 ASSERT_EQ(original_height + 1, frame_->height());
3260}
3261
3262
3263void CodeGenerator::EmitSlotAssignment(Assignment* node) {
3264#ifdef DEBUG
3265 int original_height = frame_->height();
3266#endif
3267 Comment cmnt(masm(), "[ Variable Assignment");
3268 Variable* var = node->target()->AsVariableProxy()->AsVariable();
3269 ASSERT(var != NULL);
3270 Slot* slot = var->slot();
3271 ASSERT(slot != NULL);
3272
3273 // Evaluate the right-hand side.
3274 if (node->is_compound()) {
3275 // For a compound assignment the right-hand side is a binary operation
3276 // between the current property value and the actual right-hand side.
3277 LoadFromSlotCheckForArguments(slot, NOT_INSIDE_TYPEOF);
3278
3279 // Perform the binary operation.
3280 Literal* literal = node->value()->AsLiteral();
3281 bool overwrite_value =
3282 (node->value()->AsBinaryOperation() != NULL &&
3283 node->value()->AsBinaryOperation()->ResultOverwriteAllowed());
3284 if (literal != NULL && literal->handle()->IsSmi()) {
3285 SmiOperation(node->binary_op(),
3286 literal->handle(),
3287 false,
3288 overwrite_value ? OVERWRITE_RIGHT : NO_OVERWRITE);
3289 } else {
3290 Load(node->value());
3291 VirtualFrameBinaryOperation(
3292 node->binary_op(), overwrite_value ? OVERWRITE_RIGHT : NO_OVERWRITE);
3293 }
3294 } else {
3295 Load(node->value());
3296 }
3297
3298 // Perform the assignment.
3299 if (var->mode() != Variable::CONST || node->op() == Token::INIT_CONST) {
3300 CodeForSourcePosition(node->position());
3301 StoreToSlot(slot,
3302 node->op() == Token::INIT_CONST ? CONST_INIT : NOT_CONST_INIT);
3303 }
3304 ASSERT_EQ(original_height + 1, frame_->height());
3305}
3306
3307
3308void CodeGenerator::EmitNamedPropertyAssignment(Assignment* node) {
3309#ifdef DEBUG
3310 int original_height = frame_->height();
3311#endif
3312 Comment cmnt(masm(), "[ Named Property Assignment");
3313 Variable* var = node->target()->AsVariableProxy()->AsVariable();
3314 Property* prop = node->target()->AsProperty();
3315 ASSERT(var == NULL || (prop == NULL && var->is_global()));
3316
3317 // Initialize name and evaluate the receiver sub-expression if necessary. If
3318 // the receiver is trivial it is not placed on the stack at this point, but
3319 // loaded whenever actually needed.
3320 Handle<String> name;
3321 bool is_trivial_receiver = false;
3322 if (var != NULL) {
3323 name = var->name();
3324 } else {
3325 Literal* lit = prop->key()->AsLiteral();
3326 ASSERT_NOT_NULL(lit);
3327 name = Handle<String>::cast(lit->handle());
3328 // Do not materialize the receiver on the frame if it is trivial.
3329 is_trivial_receiver = prop->obj()->IsTrivial();
3330 if (!is_trivial_receiver) Load(prop->obj());
3331 }
3332
3333 // Change to slow case in the beginning of an initialization block to
3334 // avoid the quadratic behavior of repeatedly adding fast properties.
3335 if (node->starts_initialization_block()) {
3336 // Initialization block consists of assignments of the form expr.x = ..., so
3337 // this will never be an assignment to a variable, so there must be a
3338 // receiver object.
3339 ASSERT_EQ(NULL, var);
3340 if (is_trivial_receiver) {
3341 Load(prop->obj());
3342 } else {
3343 frame_->Dup();
3344 }
3345 frame_->CallRuntime(Runtime::kToSlowProperties, 1);
3346 }
3347
3348 // Change to fast case at the end of an initialization block. To prepare for
3349 // that add an extra copy of the receiver to the frame, so that it can be
3350 // converted back to fast case after the assignment.
3351 if (node->ends_initialization_block() && !is_trivial_receiver) {
3352 frame_->Dup();
3353 }
3354
3355 // Stack layout:
3356 // [tos] : receiver (only materialized if non-trivial)
3357 // [tos+1] : receiver if at the end of an initialization block
3358
3359 // Evaluate the right-hand side.
3360 if (node->is_compound()) {
3361 // For a compound assignment the right-hand side is a binary operation
3362 // between the current property value and the actual right-hand side.
3363 if (is_trivial_receiver) {
3364 Load(prop->obj());
3365 } else if (var != NULL) {
3366 LoadGlobal();
3367 } else {
3368 frame_->Dup();
3369 }
3370 EmitNamedLoad(name, var != NULL);
3371 frame_->Drop(); // Receiver is left on the stack.
3372 frame_->EmitPush(r0);
3373
3374 // Perform the binary operation.
3375 Literal* literal = node->value()->AsLiteral();
3376 bool overwrite_value =
3377 (node->value()->AsBinaryOperation() != NULL &&
3378 node->value()->AsBinaryOperation()->ResultOverwriteAllowed());
3379 if (literal != NULL && literal->handle()->IsSmi()) {
3380 SmiOperation(node->binary_op(),
3381 literal->handle(),
3382 false,
3383 overwrite_value ? OVERWRITE_RIGHT : NO_OVERWRITE);
3384 } else {
3385 Load(node->value());
3386 VirtualFrameBinaryOperation(
3387 node->binary_op(), overwrite_value ? OVERWRITE_RIGHT : NO_OVERWRITE);
3388 }
3389 } else {
3390 // For non-compound assignment just load the right-hand side.
3391 Load(node->value());
3392 }
3393
3394 // Stack layout:
3395 // [tos] : value
3396 // [tos+1] : receiver (only materialized if non-trivial)
3397 // [tos+2] : receiver if at the end of an initialization block
3398
3399 // Perform the assignment. It is safe to ignore constants here.
3400 ASSERT(var == NULL || var->mode() != Variable::CONST);
3401 ASSERT_NE(Token::INIT_CONST, node->op());
3402 if (is_trivial_receiver) {
3403 // Load the receiver and swap with the value.
3404 Load(prop->obj());
3405 Register t0 = frame_->PopToRegister();
3406 Register t1 = frame_->PopToRegister(t0);
3407 frame_->EmitPush(t0);
3408 frame_->EmitPush(t1);
3409 }
3410 CodeForSourcePosition(node->position());
3411 bool is_contextual = (var != NULL);
3412 EmitNamedStore(name, is_contextual);
3413 frame_->EmitPush(r0);
3414
3415 // Change to fast case at the end of an initialization block.
3416 if (node->ends_initialization_block()) {
3417 ASSERT_EQ(NULL, var);
3418 // The argument to the runtime call is the receiver.
3419 if (is_trivial_receiver) {
3420 Load(prop->obj());
3421 } else {
3422 // A copy of the receiver is below the value of the assignment. Swap
3423 // the receiver and the value of the assignment expression.
3424 Register t0 = frame_->PopToRegister();
3425 Register t1 = frame_->PopToRegister(t0);
3426 frame_->EmitPush(t0);
3427 frame_->EmitPush(t1);
3428 }
3429 frame_->CallRuntime(Runtime::kToFastProperties, 1);
3430 }
3431
3432 // Stack layout:
3433 // [tos] : result
3434
3435 ASSERT_EQ(original_height + 1, frame_->height());
3436}
3437
3438
3439void CodeGenerator::EmitKeyedPropertyAssignment(Assignment* node) {
3440#ifdef DEBUG
3441 int original_height = frame_->height();
3442#endif
3443 Comment cmnt(masm_, "[ Keyed Property Assignment");
3444 Property* prop = node->target()->AsProperty();
3445 ASSERT_NOT_NULL(prop);
3446
3447 // Evaluate the receiver subexpression.
3448 Load(prop->obj());
3449
3450 // Change to slow case in the beginning of an initialization block to
3451 // avoid the quadratic behavior of repeatedly adding fast properties.
3452 if (node->starts_initialization_block()) {
3453 frame_->Dup();
3454 frame_->CallRuntime(Runtime::kToSlowProperties, 1);
3455 }
3456
3457 // Change to fast case at the end of an initialization block. To prepare for
3458 // that add an extra copy of the receiver to the frame, so that it can be
3459 // converted back to fast case after the assignment.
3460 if (node->ends_initialization_block()) {
3461 frame_->Dup();
3462 }
3463
3464 // Evaluate the key subexpression.
3465 Load(prop->key());
3466
3467 // Stack layout:
3468 // [tos] : key
3469 // [tos+1] : receiver
3470 // [tos+2] : receiver if at the end of an initialization block
3471
3472 // Evaluate the right-hand side.
3473 if (node->is_compound()) {
3474 // For a compound assignment the right-hand side is a binary operation
3475 // between the current property value and the actual right-hand side.
3476 // Load of the current value leaves receiver and key on the stack.
3477 EmitKeyedLoad();
3478 frame_->EmitPush(r0);
3479
3480 // Perform the binary operation.
3481 Literal* literal = node->value()->AsLiteral();
3482 bool overwrite_value =
3483 (node->value()->AsBinaryOperation() != NULL &&
3484 node->value()->AsBinaryOperation()->ResultOverwriteAllowed());
3485 if (literal != NULL && literal->handle()->IsSmi()) {
3486 SmiOperation(node->binary_op(),
3487 literal->handle(),
3488 false,
3489 overwrite_value ? OVERWRITE_RIGHT : NO_OVERWRITE);
3490 } else {
3491 Load(node->value());
3492 VirtualFrameBinaryOperation(
3493 node->binary_op(), overwrite_value ? OVERWRITE_RIGHT : NO_OVERWRITE);
3494 }
3495 } else {
3496 // For non-compound assignment just load the right-hand side.
3497 Load(node->value());
3498 }
3499
3500 // Stack layout:
3501 // [tos] : value
3502 // [tos+1] : key
3503 // [tos+2] : receiver
3504 // [tos+3] : receiver if at the end of an initialization block
3505
3506 // Perform the assignment. It is safe to ignore constants here.
3507 ASSERT(node->op() != Token::INIT_CONST);
3508 CodeForSourcePosition(node->position());
3509 frame_->PopToR0();
3510 EmitKeyedStore(prop->key()->type());
3511 frame_->Drop(2); // Key and receiver are left on the stack.
3512 frame_->EmitPush(r0);
3513
3514 // Stack layout:
3515 // [tos] : result
3516 // [tos+1] : receiver if at the end of an initialization block
3517
3518 // Change to fast case at the end of an initialization block.
3519 if (node->ends_initialization_block()) {
3520 // The argument to the runtime call is the extra copy of the receiver,
3521 // which is below the value of the assignment. Swap the receiver and
3522 // the value of the assignment expression.
3523 Register t0 = frame_->PopToRegister();
3524 Register t1 = frame_->PopToRegister(t0);
3525 frame_->EmitPush(t1);
3526 frame_->EmitPush(t0);
3527 frame_->CallRuntime(Runtime::kToFastProperties, 1);
3528 }
3529
3530 // Stack layout:
3531 // [tos] : result
3532
3533 ASSERT_EQ(original_height + 1, frame_->height());
Steve Blocka7e24c12009-10-30 11:49:00 +00003534}
3535
3536
3537void CodeGenerator::VisitAssignment(Assignment* node) {
Steve Block6ded16b2010-05-10 14:33:55 +01003538 VirtualFrame::RegisterAllocationScope scope(this);
Steve Blocka7e24c12009-10-30 11:49:00 +00003539#ifdef DEBUG
3540 int original_height = frame_->height();
3541#endif
Steve Blocka7e24c12009-10-30 11:49:00 +00003542 Comment cmnt(masm_, "[ Assignment");
3543
Steve Block6ded16b2010-05-10 14:33:55 +01003544 Variable* var = node->target()->AsVariableProxy()->AsVariable();
3545 Property* prop = node->target()->AsProperty();
Steve Blocka7e24c12009-10-30 11:49:00 +00003546
Steve Block6ded16b2010-05-10 14:33:55 +01003547 if (var != NULL && !var->is_global()) {
3548 EmitSlotAssignment(node);
Steve Blocka7e24c12009-10-30 11:49:00 +00003549
Steve Block6ded16b2010-05-10 14:33:55 +01003550 } else if ((prop != NULL && prop->key()->IsPropertyName()) ||
3551 (var != NULL && var->is_global())) {
3552 // Properties whose keys are property names and global variables are
3553 // treated as named property references. We do not need to consider
3554 // global 'this' because it is not a valid left-hand side.
3555 EmitNamedPropertyAssignment(node);
Steve Blocka7e24c12009-10-30 11:49:00 +00003556
Steve Block6ded16b2010-05-10 14:33:55 +01003557 } else if (prop != NULL) {
3558 // Other properties (including rewritten parameters for a function that
3559 // uses arguments) are keyed property assignments.
3560 EmitKeyedPropertyAssignment(node);
3561
3562 } else {
3563 // Invalid left-hand side.
3564 Load(node->target());
3565 frame_->CallRuntime(Runtime::kThrowReferenceError, 1);
3566 // The runtime call doesn't actually return but the code generator will
3567 // still generate code and expects a certain frame height.
3568 frame_->EmitPush(r0);
Steve Blocka7e24c12009-10-30 11:49:00 +00003569 }
Steve Block6ded16b2010-05-10 14:33:55 +01003570 ASSERT_EQ(original_height + 1, frame_->height());
Steve Blocka7e24c12009-10-30 11:49:00 +00003571}
3572
3573
3574void CodeGenerator::VisitThrow(Throw* node) {
3575#ifdef DEBUG
3576 int original_height = frame_->height();
3577#endif
Steve Block6ded16b2010-05-10 14:33:55 +01003578 VirtualFrame::SpilledScope spilled_scope(frame_);
Steve Blocka7e24c12009-10-30 11:49:00 +00003579 Comment cmnt(masm_, "[ Throw");
3580
3581 LoadAndSpill(node->exception());
3582 CodeForSourcePosition(node->position());
3583 frame_->CallRuntime(Runtime::kThrow, 1);
3584 frame_->EmitPush(r0);
Steve Block6ded16b2010-05-10 14:33:55 +01003585 ASSERT_EQ(original_height + 1, frame_->height());
Steve Blocka7e24c12009-10-30 11:49:00 +00003586}
3587
3588
3589void CodeGenerator::VisitProperty(Property* node) {
3590#ifdef DEBUG
3591 int original_height = frame_->height();
3592#endif
Steve Blocka7e24c12009-10-30 11:49:00 +00003593 Comment cmnt(masm_, "[ Property");
3594
3595 { Reference property(this, node);
Steve Block6ded16b2010-05-10 14:33:55 +01003596 property.GetValue();
Steve Blocka7e24c12009-10-30 11:49:00 +00003597 }
Steve Block6ded16b2010-05-10 14:33:55 +01003598 ASSERT_EQ(original_height + 1, frame_->height());
Steve Blocka7e24c12009-10-30 11:49:00 +00003599}
3600
3601
3602void CodeGenerator::VisitCall(Call* node) {
3603#ifdef DEBUG
3604 int original_height = frame_->height();
3605#endif
Steve Block6ded16b2010-05-10 14:33:55 +01003606 VirtualFrame::SpilledScope spilled_scope(frame_);
Steve Blocka7e24c12009-10-30 11:49:00 +00003607 Comment cmnt(masm_, "[ Call");
3608
3609 Expression* function = node->expression();
3610 ZoneList<Expression*>* args = node->arguments();
3611
3612 // Standard function call.
3613 // Check if the function is a variable or a property.
3614 Variable* var = function->AsVariableProxy()->AsVariable();
3615 Property* property = function->AsProperty();
3616
3617 // ------------------------------------------------------------------------
3618 // Fast-case: Use inline caching.
3619 // ---
3620 // According to ECMA-262, section 11.2.3, page 44, the function to call
3621 // must be resolved after the arguments have been evaluated. The IC code
3622 // automatically handles this by loading the arguments before the function
3623 // is resolved in cache misses (this also holds for megamorphic calls).
3624 // ------------------------------------------------------------------------
3625
3626 if (var != NULL && var->is_possibly_eval()) {
3627 // ----------------------------------
3628 // JavaScript example: 'eval(arg)' // eval is not known to be shadowed
3629 // ----------------------------------
3630
3631 // In a call to eval, we first call %ResolvePossiblyDirectEval to
3632 // resolve the function we need to call and the receiver of the
3633 // call. Then we call the resolved function using the given
3634 // arguments.
3635 // Prepare stack for call to resolved function.
3636 LoadAndSpill(function);
3637 __ LoadRoot(r2, Heap::kUndefinedValueRootIndex);
3638 frame_->EmitPush(r2); // Slot for receiver
3639 int arg_count = args->length();
3640 for (int i = 0; i < arg_count; i++) {
3641 LoadAndSpill(args->at(i));
3642 }
3643
3644 // Prepare stack for call to ResolvePossiblyDirectEval.
3645 __ ldr(r1, MemOperand(sp, arg_count * kPointerSize + kPointerSize));
3646 frame_->EmitPush(r1);
3647 if (arg_count > 0) {
3648 __ ldr(r1, MemOperand(sp, arg_count * kPointerSize));
3649 frame_->EmitPush(r1);
3650 } else {
3651 frame_->EmitPush(r2);
3652 }
3653
Leon Clarkee46be812010-01-19 14:06:41 +00003654 // Push the receiver.
3655 __ ldr(r1, frame_->Receiver());
3656 frame_->EmitPush(r1);
3657
Steve Blocka7e24c12009-10-30 11:49:00 +00003658 // Resolve the call.
Leon Clarkee46be812010-01-19 14:06:41 +00003659 frame_->CallRuntime(Runtime::kResolvePossiblyDirectEval, 3);
Steve Blocka7e24c12009-10-30 11:49:00 +00003660
3661 // Touch up stack with the right values for the function and the receiver.
Leon Clarkee46be812010-01-19 14:06:41 +00003662 __ str(r0, MemOperand(sp, (arg_count + 1) * kPointerSize));
Steve Blocka7e24c12009-10-30 11:49:00 +00003663 __ str(r1, MemOperand(sp, arg_count * kPointerSize));
3664
3665 // Call the function.
3666 CodeForSourcePosition(node->position());
3667
3668 InLoopFlag in_loop = loop_nesting() > 0 ? IN_LOOP : NOT_IN_LOOP;
Leon Clarkee46be812010-01-19 14:06:41 +00003669 CallFunctionStub call_function(arg_count, in_loop, RECEIVER_MIGHT_BE_VALUE);
Steve Blocka7e24c12009-10-30 11:49:00 +00003670 frame_->CallStub(&call_function, arg_count + 1);
3671
3672 __ ldr(cp, frame_->Context());
3673 // Remove the function from the stack.
3674 frame_->Drop();
3675 frame_->EmitPush(r0);
3676
3677 } else if (var != NULL && !var->is_this() && var->is_global()) {
3678 // ----------------------------------
3679 // JavaScript example: 'foo(1, 2, 3)' // foo is global
3680 // ----------------------------------
Steve Blocka7e24c12009-10-30 11:49:00 +00003681 // Pass the global object as the receiver and let the IC stub
3682 // patch the stack to use the global proxy as 'this' in the
3683 // invoked function.
3684 LoadGlobal();
3685
3686 // Load the arguments.
3687 int arg_count = args->length();
3688 for (int i = 0; i < arg_count; i++) {
3689 LoadAndSpill(args->at(i));
3690 }
3691
Andrei Popescu402d9372010-02-26 13:31:12 +00003692 // Setup the name register and call the IC initialization code.
3693 __ mov(r2, Operand(var->name()));
Steve Blocka7e24c12009-10-30 11:49:00 +00003694 InLoopFlag in_loop = loop_nesting() > 0 ? IN_LOOP : NOT_IN_LOOP;
3695 Handle<Code> stub = ComputeCallInitialize(arg_count, in_loop);
3696 CodeForSourcePosition(node->position());
3697 frame_->CallCodeObject(stub, RelocInfo::CODE_TARGET_CONTEXT,
3698 arg_count + 1);
3699 __ ldr(cp, frame_->Context());
Steve Blocka7e24c12009-10-30 11:49:00 +00003700 frame_->EmitPush(r0);
3701
3702 } else if (var != NULL && var->slot() != NULL &&
3703 var->slot()->type() == Slot::LOOKUP) {
3704 // ----------------------------------
3705 // JavaScript example: 'with (obj) foo(1, 2, 3)' // foo is in obj
3706 // ----------------------------------
3707
3708 // Load the function
3709 frame_->EmitPush(cp);
3710 __ mov(r0, Operand(var->name()));
3711 frame_->EmitPush(r0);
3712 frame_->CallRuntime(Runtime::kLoadContextSlot, 2);
3713 // r0: slot value; r1: receiver
3714
3715 // Load the receiver.
3716 frame_->EmitPush(r0); // function
3717 frame_->EmitPush(r1); // receiver
3718
3719 // Call the function.
Leon Clarkee46be812010-01-19 14:06:41 +00003720 CallWithArguments(args, NO_CALL_FUNCTION_FLAGS, node->position());
Steve Blocka7e24c12009-10-30 11:49:00 +00003721 frame_->EmitPush(r0);
3722
3723 } else if (property != NULL) {
3724 // Check if the key is a literal string.
3725 Literal* literal = property->key()->AsLiteral();
3726
3727 if (literal != NULL && literal->handle()->IsSymbol()) {
3728 // ------------------------------------------------------------------
3729 // JavaScript example: 'object.foo(1, 2, 3)' or 'map["key"](1, 2, 3)'
3730 // ------------------------------------------------------------------
3731
Steve Block6ded16b2010-05-10 14:33:55 +01003732 Handle<String> name = Handle<String>::cast(literal->handle());
Steve Blocka7e24c12009-10-30 11:49:00 +00003733
Steve Block6ded16b2010-05-10 14:33:55 +01003734 if (ArgumentsMode() == LAZY_ARGUMENTS_ALLOCATION &&
3735 name->IsEqualTo(CStrVector("apply")) &&
3736 args->length() == 2 &&
3737 args->at(1)->AsVariableProxy() != NULL &&
3738 args->at(1)->AsVariableProxy()->IsArguments()) {
3739 // Use the optimized Function.prototype.apply that avoids
3740 // allocating lazily allocated arguments objects.
3741 CallApplyLazy(property->obj(),
3742 args->at(0),
3743 args->at(1)->AsVariableProxy(),
3744 node->position());
3745
3746 } else {
3747 LoadAndSpill(property->obj()); // Receiver.
3748 // Load the arguments.
3749 int arg_count = args->length();
3750 for (int i = 0; i < arg_count; i++) {
3751 LoadAndSpill(args->at(i));
3752 }
3753
3754 // Set the name register and call the IC initialization code.
3755 __ mov(r2, Operand(name));
3756 InLoopFlag in_loop = loop_nesting() > 0 ? IN_LOOP : NOT_IN_LOOP;
3757 Handle<Code> stub = ComputeCallInitialize(arg_count, in_loop);
3758 CodeForSourcePosition(node->position());
3759 frame_->CallCodeObject(stub, RelocInfo::CODE_TARGET, arg_count + 1);
3760 __ ldr(cp, frame_->Context());
3761 frame_->EmitPush(r0);
3762 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003763
3764 } else {
3765 // -------------------------------------------
3766 // JavaScript example: 'array[index](1, 2, 3)'
3767 // -------------------------------------------
3768
Leon Clarked91b9f72010-01-27 17:25:45 +00003769 LoadAndSpill(property->obj());
3770 LoadAndSpill(property->key());
Steve Block6ded16b2010-05-10 14:33:55 +01003771 EmitKeyedLoad();
Leon Clarked91b9f72010-01-27 17:25:45 +00003772 frame_->Drop(); // key
3773 // Put the function below the receiver.
Steve Blocka7e24c12009-10-30 11:49:00 +00003774 if (property->is_synthetic()) {
Leon Clarked91b9f72010-01-27 17:25:45 +00003775 // Use the global receiver.
3776 frame_->Drop();
3777 frame_->EmitPush(r0);
Steve Blocka7e24c12009-10-30 11:49:00 +00003778 LoadGlobalReceiver(r0);
3779 } else {
Leon Clarked91b9f72010-01-27 17:25:45 +00003780 frame_->EmitPop(r1); // receiver
3781 frame_->EmitPush(r0); // function
3782 frame_->EmitPush(r1); // receiver
Steve Blocka7e24c12009-10-30 11:49:00 +00003783 }
3784
3785 // Call the function.
Leon Clarkee46be812010-01-19 14:06:41 +00003786 CallWithArguments(args, RECEIVER_MIGHT_BE_VALUE, node->position());
Steve Blocka7e24c12009-10-30 11:49:00 +00003787 frame_->EmitPush(r0);
3788 }
3789
3790 } else {
3791 // ----------------------------------
3792 // JavaScript example: 'foo(1, 2, 3)' // foo is not global
3793 // ----------------------------------
3794
3795 // Load the function.
3796 LoadAndSpill(function);
3797
3798 // Pass the global proxy as the receiver.
3799 LoadGlobalReceiver(r0);
3800
3801 // Call the function.
Leon Clarkee46be812010-01-19 14:06:41 +00003802 CallWithArguments(args, NO_CALL_FUNCTION_FLAGS, node->position());
Steve Blocka7e24c12009-10-30 11:49:00 +00003803 frame_->EmitPush(r0);
3804 }
Steve Block6ded16b2010-05-10 14:33:55 +01003805 ASSERT_EQ(original_height + 1, frame_->height());
Steve Blocka7e24c12009-10-30 11:49:00 +00003806}
3807
3808
3809void CodeGenerator::VisitCallNew(CallNew* node) {
3810#ifdef DEBUG
3811 int original_height = frame_->height();
3812#endif
Steve Block6ded16b2010-05-10 14:33:55 +01003813 VirtualFrame::SpilledScope spilled_scope(frame_);
Steve Blocka7e24c12009-10-30 11:49:00 +00003814 Comment cmnt(masm_, "[ CallNew");
3815
3816 // According to ECMA-262, section 11.2.2, page 44, the function
3817 // expression in new calls must be evaluated before the
3818 // arguments. This is different from ordinary calls, where the
3819 // actual function to call is resolved after the arguments have been
3820 // evaluated.
3821
3822 // Compute function to call and use the global object as the
3823 // receiver. There is no need to use the global proxy here because
3824 // it will always be replaced with a newly allocated object.
3825 LoadAndSpill(node->expression());
3826 LoadGlobal();
3827
3828 // Push the arguments ("left-to-right") on the stack.
3829 ZoneList<Expression*>* args = node->arguments();
3830 int arg_count = args->length();
3831 for (int i = 0; i < arg_count; i++) {
3832 LoadAndSpill(args->at(i));
3833 }
3834
3835 // r0: the number of arguments.
Steve Blocka7e24c12009-10-30 11:49:00 +00003836 __ mov(r0, Operand(arg_count));
Steve Blocka7e24c12009-10-30 11:49:00 +00003837 // Load the function into r1 as per calling convention.
Steve Blocka7e24c12009-10-30 11:49:00 +00003838 __ ldr(r1, frame_->ElementAt(arg_count + 1));
3839
3840 // Call the construct call builtin that handles allocation and
3841 // constructor invocation.
3842 CodeForSourcePosition(node->position());
3843 Handle<Code> ic(Builtins::builtin(Builtins::JSConstructCall));
Leon Clarke4515c472010-02-03 11:58:03 +00003844 frame_->CallCodeObject(ic, RelocInfo::CONSTRUCT_CALL, arg_count + 1);
Steve Blocka7e24c12009-10-30 11:49:00 +00003845
3846 // Discard old TOS value and push r0 on the stack (same as Pop(), push(r0)).
3847 __ str(r0, frame_->Top());
Steve Block6ded16b2010-05-10 14:33:55 +01003848 ASSERT_EQ(original_height + 1, frame_->height());
Steve Blocka7e24c12009-10-30 11:49:00 +00003849}
3850
3851
3852void CodeGenerator::GenerateClassOf(ZoneList<Expression*>* args) {
Steve Block6ded16b2010-05-10 14:33:55 +01003853 VirtualFrame::SpilledScope spilled_scope(frame_);
Steve Blocka7e24c12009-10-30 11:49:00 +00003854 ASSERT(args->length() == 1);
3855 JumpTarget leave, null, function, non_function_constructor;
3856
3857 // Load the object into r0.
3858 LoadAndSpill(args->at(0));
3859 frame_->EmitPop(r0);
3860
3861 // If the object is a smi, we return null.
3862 __ tst(r0, Operand(kSmiTagMask));
3863 null.Branch(eq);
3864
3865 // Check that the object is a JS object but take special care of JS
3866 // functions to make sure they have 'Function' as their class.
3867 __ CompareObjectType(r0, r0, r1, FIRST_JS_OBJECT_TYPE);
3868 null.Branch(lt);
3869
3870 // As long as JS_FUNCTION_TYPE is the last instance type and it is
3871 // right after LAST_JS_OBJECT_TYPE, we can avoid checking for
3872 // LAST_JS_OBJECT_TYPE.
3873 ASSERT(LAST_TYPE == JS_FUNCTION_TYPE);
3874 ASSERT(JS_FUNCTION_TYPE == LAST_JS_OBJECT_TYPE + 1);
3875 __ cmp(r1, Operand(JS_FUNCTION_TYPE));
3876 function.Branch(eq);
3877
3878 // Check if the constructor in the map is a function.
3879 __ ldr(r0, FieldMemOperand(r0, Map::kConstructorOffset));
3880 __ CompareObjectType(r0, r1, r1, JS_FUNCTION_TYPE);
3881 non_function_constructor.Branch(ne);
3882
3883 // The r0 register now contains the constructor function. Grab the
3884 // instance class name from there.
3885 __ ldr(r0, FieldMemOperand(r0, JSFunction::kSharedFunctionInfoOffset));
3886 __ ldr(r0, FieldMemOperand(r0, SharedFunctionInfo::kInstanceClassNameOffset));
3887 frame_->EmitPush(r0);
3888 leave.Jump();
3889
3890 // Functions have class 'Function'.
3891 function.Bind();
3892 __ mov(r0, Operand(Factory::function_class_symbol()));
3893 frame_->EmitPush(r0);
3894 leave.Jump();
3895
3896 // Objects with a non-function constructor have class 'Object'.
3897 non_function_constructor.Bind();
3898 __ mov(r0, Operand(Factory::Object_symbol()));
3899 frame_->EmitPush(r0);
3900 leave.Jump();
3901
3902 // Non-JS objects have class null.
3903 null.Bind();
3904 __ LoadRoot(r0, Heap::kNullValueRootIndex);
3905 frame_->EmitPush(r0);
3906
3907 // All done.
3908 leave.Bind();
3909}
3910
3911
3912void CodeGenerator::GenerateValueOf(ZoneList<Expression*>* args) {
Steve Block6ded16b2010-05-10 14:33:55 +01003913 VirtualFrame::SpilledScope spilled_scope(frame_);
Steve Blocka7e24c12009-10-30 11:49:00 +00003914 ASSERT(args->length() == 1);
3915 JumpTarget leave;
3916 LoadAndSpill(args->at(0));
3917 frame_->EmitPop(r0); // r0 contains object.
3918 // if (object->IsSmi()) return the object.
3919 __ tst(r0, Operand(kSmiTagMask));
3920 leave.Branch(eq);
3921 // It is a heap object - get map. If (!object->IsJSValue()) return the object.
3922 __ CompareObjectType(r0, r1, r1, JS_VALUE_TYPE);
3923 leave.Branch(ne);
3924 // Load the value.
3925 __ ldr(r0, FieldMemOperand(r0, JSValue::kValueOffset));
3926 leave.Bind();
3927 frame_->EmitPush(r0);
3928}
3929
3930
3931void CodeGenerator::GenerateSetValueOf(ZoneList<Expression*>* args) {
Steve Block6ded16b2010-05-10 14:33:55 +01003932 VirtualFrame::SpilledScope spilled_scope(frame_);
Steve Blocka7e24c12009-10-30 11:49:00 +00003933 ASSERT(args->length() == 2);
3934 JumpTarget leave;
3935 LoadAndSpill(args->at(0)); // Load the object.
3936 LoadAndSpill(args->at(1)); // Load the value.
3937 frame_->EmitPop(r0); // r0 contains value
3938 frame_->EmitPop(r1); // r1 contains object
3939 // if (object->IsSmi()) return object.
3940 __ tst(r1, Operand(kSmiTagMask));
3941 leave.Branch(eq);
3942 // It is a heap object - get map. If (!object->IsJSValue()) return the object.
3943 __ CompareObjectType(r1, r2, r2, JS_VALUE_TYPE);
3944 leave.Branch(ne);
3945 // Store the value.
3946 __ str(r0, FieldMemOperand(r1, JSValue::kValueOffset));
3947 // Update the write barrier.
3948 __ mov(r2, Operand(JSValue::kValueOffset - kHeapObjectTag));
3949 __ RecordWrite(r1, r2, r3);
3950 // Leave.
3951 leave.Bind();
3952 frame_->EmitPush(r0);
3953}
3954
3955
3956void CodeGenerator::GenerateIsSmi(ZoneList<Expression*>* args) {
Steve Block6ded16b2010-05-10 14:33:55 +01003957 VirtualFrame::SpilledScope spilled_scope(frame_);
Steve Blocka7e24c12009-10-30 11:49:00 +00003958 ASSERT(args->length() == 1);
3959 LoadAndSpill(args->at(0));
3960 frame_->EmitPop(r0);
3961 __ tst(r0, Operand(kSmiTagMask));
3962 cc_reg_ = eq;
3963}
3964
3965
3966void CodeGenerator::GenerateLog(ZoneList<Expression*>* args) {
Steve Block6ded16b2010-05-10 14:33:55 +01003967 VirtualFrame::SpilledScope spilled_scope(frame_);
Steve Blocka7e24c12009-10-30 11:49:00 +00003968 // See comment in CodeGenerator::GenerateLog in codegen-ia32.cc.
3969 ASSERT_EQ(args->length(), 3);
3970#ifdef ENABLE_LOGGING_AND_PROFILING
3971 if (ShouldGenerateLog(args->at(0))) {
3972 LoadAndSpill(args->at(1));
3973 LoadAndSpill(args->at(2));
3974 __ CallRuntime(Runtime::kLog, 2);
3975 }
3976#endif
3977 __ LoadRoot(r0, Heap::kUndefinedValueRootIndex);
3978 frame_->EmitPush(r0);
3979}
3980
3981
3982void CodeGenerator::GenerateIsNonNegativeSmi(ZoneList<Expression*>* args) {
Steve Block6ded16b2010-05-10 14:33:55 +01003983 VirtualFrame::SpilledScope spilled_scope(frame_);
Steve Blocka7e24c12009-10-30 11:49:00 +00003984 ASSERT(args->length() == 1);
3985 LoadAndSpill(args->at(0));
3986 frame_->EmitPop(r0);
3987 __ tst(r0, Operand(kSmiTagMask | 0x80000000u));
3988 cc_reg_ = eq;
3989}
3990
3991
Steve Block6ded16b2010-05-10 14:33:55 +01003992// Generates the Math.pow method - currently just calls runtime.
3993void CodeGenerator::GenerateMathPow(ZoneList<Expression*>* args) {
3994 ASSERT(args->length() == 2);
3995 Load(args->at(0));
3996 Load(args->at(1));
3997 frame_->CallRuntime(Runtime::kMath_pow, 2);
3998 frame_->EmitPush(r0);
3999}
4000
4001
4002// Generates the Math.sqrt method - currently just calls runtime.
4003void CodeGenerator::GenerateMathSqrt(ZoneList<Expression*>* args) {
4004 ASSERT(args->length() == 1);
4005 Load(args->at(0));
4006 frame_->CallRuntime(Runtime::kMath_sqrt, 1);
4007 frame_->EmitPush(r0);
4008}
4009
4010
4011// This generates code that performs a charCodeAt() call or returns
Steve Blocka7e24c12009-10-30 11:49:00 +00004012// undefined in order to trigger the slow case, Runtime_StringCharCodeAt.
Steve Block6ded16b2010-05-10 14:33:55 +01004013// It can handle flat, 8 and 16 bit characters and cons strings where the
4014// answer is found in the left hand branch of the cons. The slow case will
4015// flatten the string, which will ensure that the answer is in the left hand
4016// side the next time around.
Steve Blocka7e24c12009-10-30 11:49:00 +00004017void CodeGenerator::GenerateFastCharCodeAt(ZoneList<Expression*>* args) {
Steve Block6ded16b2010-05-10 14:33:55 +01004018 VirtualFrame::SpilledScope spilled_scope(frame_);
Steve Blocka7e24c12009-10-30 11:49:00 +00004019 ASSERT(args->length() == 2);
Steve Blockd0582a62009-12-15 09:54:21 +00004020 Comment(masm_, "[ GenerateFastCharCodeAt");
4021
4022 LoadAndSpill(args->at(0));
4023 LoadAndSpill(args->at(1));
Steve Block6ded16b2010-05-10 14:33:55 +01004024 frame_->EmitPop(r1); // Index.
4025 frame_->EmitPop(r2); // String.
Steve Blockd0582a62009-12-15 09:54:21 +00004026
Steve Block6ded16b2010-05-10 14:33:55 +01004027 Label slow_case;
4028 Label exit;
4029 StringHelper::GenerateFastCharCodeAt(masm_,
4030 r2,
4031 r1,
4032 r3,
4033 r0,
4034 &slow_case,
4035 &slow_case,
4036 &slow_case,
4037 &slow_case);
4038 __ jmp(&exit);
Steve Blockd0582a62009-12-15 09:54:21 +00004039
Steve Block6ded16b2010-05-10 14:33:55 +01004040 __ bind(&slow_case);
4041 // Move the undefined value into the result register, which will
4042 // trigger the slow case.
Steve Blocka7e24c12009-10-30 11:49:00 +00004043 __ LoadRoot(r0, Heap::kUndefinedValueRootIndex);
Steve Blockd0582a62009-12-15 09:54:21 +00004044
Steve Block6ded16b2010-05-10 14:33:55 +01004045 __ bind(&exit);
Steve Blocka7e24c12009-10-30 11:49:00 +00004046 frame_->EmitPush(r0);
4047}
4048
4049
Steve Block6ded16b2010-05-10 14:33:55 +01004050void CodeGenerator::GenerateCharFromCode(ZoneList<Expression*>* args) {
4051 Comment(masm_, "[ GenerateCharFromCode");
4052 ASSERT(args->length() == 1);
4053
4054 Register code = r1;
4055 Register scratch = ip;
4056 Register result = r0;
4057
4058 LoadAndSpill(args->at(0));
4059 frame_->EmitPop(code);
4060
4061 StringHelper::GenerateCharFromCode(masm_,
4062 code,
4063 scratch,
4064 result,
4065 CALL_FUNCTION);
4066 frame_->EmitPush(result);
4067}
4068
4069
Steve Blocka7e24c12009-10-30 11:49:00 +00004070void CodeGenerator::GenerateIsArray(ZoneList<Expression*>* args) {
Steve Block6ded16b2010-05-10 14:33:55 +01004071 VirtualFrame::SpilledScope spilled_scope(frame_);
Steve Blocka7e24c12009-10-30 11:49:00 +00004072 ASSERT(args->length() == 1);
4073 LoadAndSpill(args->at(0));
4074 JumpTarget answer;
4075 // We need the CC bits to come out as not_equal in the case where the
4076 // object is a smi. This can't be done with the usual test opcode so
4077 // we use XOR to get the right CC bits.
4078 frame_->EmitPop(r0);
4079 __ and_(r1, r0, Operand(kSmiTagMask));
4080 __ eor(r1, r1, Operand(kSmiTagMask), SetCC);
4081 answer.Branch(ne);
4082 // It is a heap object - get the map. Check if the object is a JS array.
4083 __ CompareObjectType(r0, r1, r1, JS_ARRAY_TYPE);
4084 answer.Bind();
4085 cc_reg_ = eq;
4086}
4087
4088
Andrei Popescu402d9372010-02-26 13:31:12 +00004089void CodeGenerator::GenerateIsRegExp(ZoneList<Expression*>* args) {
Steve Block6ded16b2010-05-10 14:33:55 +01004090 VirtualFrame::SpilledScope spilled_scope(frame_);
Andrei Popescu402d9372010-02-26 13:31:12 +00004091 ASSERT(args->length() == 1);
4092 LoadAndSpill(args->at(0));
4093 JumpTarget answer;
4094 // We need the CC bits to come out as not_equal in the case where the
4095 // object is a smi. This can't be done with the usual test opcode so
4096 // we use XOR to get the right CC bits.
4097 frame_->EmitPop(r0);
4098 __ and_(r1, r0, Operand(kSmiTagMask));
4099 __ eor(r1, r1, Operand(kSmiTagMask), SetCC);
4100 answer.Branch(ne);
4101 // It is a heap object - get the map. Check if the object is a regexp.
4102 __ CompareObjectType(r0, r1, r1, JS_REGEXP_TYPE);
4103 answer.Bind();
4104 cc_reg_ = eq;
4105}
4106
4107
Steve Blockd0582a62009-12-15 09:54:21 +00004108void CodeGenerator::GenerateIsObject(ZoneList<Expression*>* args) {
4109 // This generates a fast version of:
4110 // (typeof(arg) === 'object' || %_ClassOf(arg) == 'RegExp')
Steve Block6ded16b2010-05-10 14:33:55 +01004111 VirtualFrame::SpilledScope spilled_scope(frame_);
Steve Blockd0582a62009-12-15 09:54:21 +00004112 ASSERT(args->length() == 1);
4113 LoadAndSpill(args->at(0));
4114 frame_->EmitPop(r1);
4115 __ tst(r1, Operand(kSmiTagMask));
4116 false_target()->Branch(eq);
4117
4118 __ LoadRoot(ip, Heap::kNullValueRootIndex);
4119 __ cmp(r1, ip);
4120 true_target()->Branch(eq);
4121
4122 Register map_reg = r2;
4123 __ ldr(map_reg, FieldMemOperand(r1, HeapObject::kMapOffset));
4124 // Undetectable objects behave like undefined when tested with typeof.
4125 __ ldrb(r1, FieldMemOperand(map_reg, Map::kBitFieldOffset));
4126 __ and_(r1, r1, Operand(1 << Map::kIsUndetectable));
4127 __ cmp(r1, Operand(1 << Map::kIsUndetectable));
4128 false_target()->Branch(eq);
4129
4130 __ ldrb(r1, FieldMemOperand(map_reg, Map::kInstanceTypeOffset));
4131 __ cmp(r1, Operand(FIRST_JS_OBJECT_TYPE));
4132 false_target()->Branch(lt);
4133 __ cmp(r1, Operand(LAST_JS_OBJECT_TYPE));
4134 cc_reg_ = le;
4135}
4136
4137
4138void CodeGenerator::GenerateIsFunction(ZoneList<Expression*>* args) {
4139 // This generates a fast version of:
4140 // (%_ClassOf(arg) === 'Function')
Steve Block6ded16b2010-05-10 14:33:55 +01004141 VirtualFrame::SpilledScope spilled_scope(frame_);
Steve Blockd0582a62009-12-15 09:54:21 +00004142 ASSERT(args->length() == 1);
4143 LoadAndSpill(args->at(0));
4144 frame_->EmitPop(r0);
4145 __ tst(r0, Operand(kSmiTagMask));
4146 false_target()->Branch(eq);
4147 Register map_reg = r2;
4148 __ CompareObjectType(r0, map_reg, r1, JS_FUNCTION_TYPE);
4149 cc_reg_ = eq;
4150}
4151
4152
Leon Clarked91b9f72010-01-27 17:25:45 +00004153void CodeGenerator::GenerateIsUndetectableObject(ZoneList<Expression*>* args) {
Steve Block6ded16b2010-05-10 14:33:55 +01004154 VirtualFrame::SpilledScope spilled_scope(frame_);
Leon Clarked91b9f72010-01-27 17:25:45 +00004155 ASSERT(args->length() == 1);
4156 LoadAndSpill(args->at(0));
4157 frame_->EmitPop(r0);
4158 __ tst(r0, Operand(kSmiTagMask));
4159 false_target()->Branch(eq);
4160 __ ldr(r1, FieldMemOperand(r0, HeapObject::kMapOffset));
4161 __ ldrb(r1, FieldMemOperand(r1, Map::kBitFieldOffset));
4162 __ tst(r1, Operand(1 << Map::kIsUndetectable));
4163 cc_reg_ = ne;
4164}
4165
4166
Steve Blocka7e24c12009-10-30 11:49:00 +00004167void CodeGenerator::GenerateIsConstructCall(ZoneList<Expression*>* args) {
Steve Block6ded16b2010-05-10 14:33:55 +01004168 VirtualFrame::SpilledScope spilled_scope(frame_);
Steve Blocka7e24c12009-10-30 11:49:00 +00004169 ASSERT(args->length() == 0);
4170
4171 // Get the frame pointer for the calling frame.
4172 __ ldr(r2, MemOperand(fp, StandardFrameConstants::kCallerFPOffset));
4173
4174 // Skip the arguments adaptor frame if it exists.
4175 Label check_frame_marker;
4176 __ ldr(r1, MemOperand(r2, StandardFrameConstants::kContextOffset));
4177 __ cmp(r1, Operand(Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR)));
4178 __ b(ne, &check_frame_marker);
4179 __ ldr(r2, MemOperand(r2, StandardFrameConstants::kCallerFPOffset));
4180
4181 // Check the marker in the calling frame.
4182 __ bind(&check_frame_marker);
4183 __ ldr(r1, MemOperand(r2, StandardFrameConstants::kMarkerOffset));
4184 __ cmp(r1, Operand(Smi::FromInt(StackFrame::CONSTRUCT)));
4185 cc_reg_ = eq;
4186}
4187
4188
4189void CodeGenerator::GenerateArgumentsLength(ZoneList<Expression*>* args) {
Steve Block6ded16b2010-05-10 14:33:55 +01004190 VirtualFrame::SpilledScope spilled_scope(frame_);
Steve Blocka7e24c12009-10-30 11:49:00 +00004191 ASSERT(args->length() == 0);
4192
Steve Block6ded16b2010-05-10 14:33:55 +01004193 Label exit;
4194
4195 // Get the number of formal parameters.
Andrei Popescu31002712010-02-23 13:46:05 +00004196 __ mov(r0, Operand(Smi::FromInt(scope()->num_parameters())));
Steve Blocka7e24c12009-10-30 11:49:00 +00004197
Steve Block6ded16b2010-05-10 14:33:55 +01004198 // Check if the calling frame is an arguments adaptor frame.
4199 __ ldr(r2, MemOperand(fp, StandardFrameConstants::kCallerFPOffset));
4200 __ ldr(r3, MemOperand(r2, StandardFrameConstants::kContextOffset));
4201 __ cmp(r3, Operand(Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR)));
4202 __ b(ne, &exit);
4203
4204 // Arguments adaptor case: Read the arguments length from the
4205 // adaptor frame.
4206 __ ldr(r0, MemOperand(r2, ArgumentsAdaptorFrameConstants::kLengthOffset));
4207
4208 __ bind(&exit);
Steve Blocka7e24c12009-10-30 11:49:00 +00004209 frame_->EmitPush(r0);
4210}
4211
4212
Steve Block6ded16b2010-05-10 14:33:55 +01004213void CodeGenerator::GenerateArguments(ZoneList<Expression*>* args) {
4214 VirtualFrame::SpilledScope spilled_scope(frame_);
Steve Blocka7e24c12009-10-30 11:49:00 +00004215 ASSERT(args->length() == 1);
4216
4217 // Satisfy contract with ArgumentsAccessStub:
4218 // Load the key into r1 and the formal parameters count into r0.
4219 LoadAndSpill(args->at(0));
4220 frame_->EmitPop(r1);
Andrei Popescu31002712010-02-23 13:46:05 +00004221 __ mov(r0, Operand(Smi::FromInt(scope()->num_parameters())));
Steve Blocka7e24c12009-10-30 11:49:00 +00004222
4223 // Call the shared stub to get to arguments[key].
4224 ArgumentsAccessStub stub(ArgumentsAccessStub::READ_ELEMENT);
4225 frame_->CallStub(&stub, 0);
4226 frame_->EmitPush(r0);
4227}
4228
4229
Steve Block6ded16b2010-05-10 14:33:55 +01004230void CodeGenerator::GenerateRandomHeapNumber(
4231 ZoneList<Expression*>* args) {
4232 VirtualFrame::SpilledScope spilled_scope(frame_);
Steve Blocka7e24c12009-10-30 11:49:00 +00004233 ASSERT(args->length() == 0);
Steve Block6ded16b2010-05-10 14:33:55 +01004234
4235 Label slow_allocate_heapnumber;
4236 Label heapnumber_allocated;
4237
4238 __ AllocateHeapNumber(r4, r1, r2, &slow_allocate_heapnumber);
4239 __ jmp(&heapnumber_allocated);
4240
4241 __ bind(&slow_allocate_heapnumber);
4242 // To allocate a heap number, and ensure that it is not a smi, we
4243 // call the runtime function FUnaryMinus on 0, returning the double
4244 // -0.0. A new, distinct heap number is returned each time.
4245 __ mov(r0, Operand(Smi::FromInt(0)));
4246 __ push(r0);
4247 __ CallRuntime(Runtime::kNumberUnaryMinus, 1);
4248 __ mov(r4, Operand(r0));
4249
4250 __ bind(&heapnumber_allocated);
4251
4252 // Convert 32 random bits in r0 to 0.(32 random bits) in a double
4253 // by computing:
4254 // ( 1.(20 0s)(32 random bits) x 2^20 ) - (1.0 x 2^20)).
4255 if (CpuFeatures::IsSupported(VFP3)) {
4256 __ PrepareCallCFunction(0, r1);
4257 __ CallCFunction(ExternalReference::random_uint32_function(), 0);
4258
4259 CpuFeatures::Scope scope(VFP3);
4260 // 0x41300000 is the top half of 1.0 x 2^20 as a double.
4261 // Create this constant using mov/orr to avoid PC relative load.
4262 __ mov(r1, Operand(0x41000000));
4263 __ orr(r1, r1, Operand(0x300000));
4264 // Move 0x41300000xxxxxxxx (x = random bits) to VFP.
4265 __ vmov(d7, r0, r1);
4266 // Move 0x4130000000000000 to VFP.
4267 __ mov(r0, Operand(0));
4268 __ vmov(d8, r0, r1);
4269 // Subtract and store the result in the heap number.
4270 __ vsub(d7, d7, d8);
4271 __ sub(r0, r4, Operand(kHeapObjectTag));
4272 __ vstr(d7, r0, HeapNumber::kValueOffset);
4273 frame_->EmitPush(r4);
4274 } else {
4275 __ mov(r0, Operand(r4));
4276 __ PrepareCallCFunction(1, r1);
4277 __ CallCFunction(
4278 ExternalReference::fill_heap_number_with_random_function(), 1);
4279 frame_->EmitPush(r0);
4280 }
Steve Blocka7e24c12009-10-30 11:49:00 +00004281}
4282
4283
Steve Blockd0582a62009-12-15 09:54:21 +00004284void CodeGenerator::GenerateStringAdd(ZoneList<Expression*>* args) {
4285 ASSERT_EQ(2, args->length());
4286
4287 Load(args->at(0));
4288 Load(args->at(1));
4289
Andrei Popescu31002712010-02-23 13:46:05 +00004290 StringAddStub stub(NO_STRING_ADD_FLAGS);
4291 frame_->CallStub(&stub, 2);
Steve Blockd0582a62009-12-15 09:54:21 +00004292 frame_->EmitPush(r0);
4293}
4294
4295
Leon Clarkee46be812010-01-19 14:06:41 +00004296void CodeGenerator::GenerateSubString(ZoneList<Expression*>* args) {
4297 ASSERT_EQ(3, args->length());
4298
4299 Load(args->at(0));
4300 Load(args->at(1));
4301 Load(args->at(2));
4302
Andrei Popescu31002712010-02-23 13:46:05 +00004303 SubStringStub stub;
4304 frame_->CallStub(&stub, 3);
Leon Clarkee46be812010-01-19 14:06:41 +00004305 frame_->EmitPush(r0);
4306}
4307
4308
4309void CodeGenerator::GenerateStringCompare(ZoneList<Expression*>* args) {
4310 ASSERT_EQ(2, args->length());
4311
4312 Load(args->at(0));
4313 Load(args->at(1));
4314
Leon Clarked91b9f72010-01-27 17:25:45 +00004315 StringCompareStub stub;
4316 frame_->CallStub(&stub, 2);
Leon Clarkee46be812010-01-19 14:06:41 +00004317 frame_->EmitPush(r0);
4318}
4319
4320
4321void CodeGenerator::GenerateRegExpExec(ZoneList<Expression*>* args) {
4322 ASSERT_EQ(4, args->length());
4323
4324 Load(args->at(0));
4325 Load(args->at(1));
4326 Load(args->at(2));
4327 Load(args->at(3));
Steve Block6ded16b2010-05-10 14:33:55 +01004328 RegExpExecStub stub;
4329 frame_->CallStub(&stub, 4);
4330 frame_->EmitPush(r0);
4331}
Leon Clarkee46be812010-01-19 14:06:41 +00004332
Steve Block6ded16b2010-05-10 14:33:55 +01004333
4334void CodeGenerator::GenerateRegExpConstructResult(ZoneList<Expression*>* args) {
4335 // No stub. This code only occurs a few times in regexp.js.
4336 const int kMaxInlineLength = 100;
4337 ASSERT_EQ(3, args->length());
4338 Load(args->at(0)); // Size of array, smi.
4339 Load(args->at(1)); // "index" property value.
4340 Load(args->at(2)); // "input" property value.
4341 {
4342 VirtualFrame::SpilledScope spilled_scope(frame_);
4343 Label slowcase;
4344 Label done;
4345 __ ldr(r1, MemOperand(sp, kPointerSize * 2));
4346 STATIC_ASSERT(kSmiTag == 0);
4347 STATIC_ASSERT(kSmiTagSize == 1);
4348 __ tst(r1, Operand(kSmiTagMask));
4349 __ b(ne, &slowcase);
4350 __ cmp(r1, Operand(Smi::FromInt(kMaxInlineLength)));
4351 __ b(hi, &slowcase);
4352 // Smi-tagging is equivalent to multiplying by 2.
4353 // Allocate RegExpResult followed by FixedArray with size in ebx.
4354 // JSArray: [Map][empty properties][Elements][Length-smi][index][input]
4355 // Elements: [Map][Length][..elements..]
4356 // Size of JSArray with two in-object properties and the header of a
4357 // FixedArray.
4358 int objects_size =
4359 (JSRegExpResult::kSize + FixedArray::kHeaderSize) / kPointerSize;
4360 __ mov(r5, Operand(r1, LSR, kSmiTagSize + kSmiShiftSize));
4361 __ add(r2, r5, Operand(objects_size));
4362 __ AllocateInNewSpace(r2, // In: Size, in words.
4363 r0, // Out: Start of allocation (tagged).
4364 r3, // Scratch register.
4365 r4, // Scratch register.
4366 &slowcase,
4367 TAG_OBJECT);
4368 // r0: Start of allocated area, object-tagged.
4369 // r1: Number of elements in array, as smi.
4370 // r5: Number of elements, untagged.
4371
4372 // Set JSArray map to global.regexp_result_map().
4373 // Set empty properties FixedArray.
4374 // Set elements to point to FixedArray allocated right after the JSArray.
4375 // Interleave operations for better latency.
4376 __ ldr(r2, ContextOperand(cp, Context::GLOBAL_INDEX));
4377 __ add(r3, r0, Operand(JSRegExpResult::kSize));
4378 __ mov(r4, Operand(Factory::empty_fixed_array()));
4379 __ ldr(r2, FieldMemOperand(r2, GlobalObject::kGlobalContextOffset));
4380 __ str(r3, FieldMemOperand(r0, JSObject::kElementsOffset));
4381 __ ldr(r2, ContextOperand(r2, Context::REGEXP_RESULT_MAP_INDEX));
4382 __ str(r4, FieldMemOperand(r0, JSObject::kPropertiesOffset));
4383 __ str(r2, FieldMemOperand(r0, HeapObject::kMapOffset));
4384
4385 // Set input, index and length fields from arguments.
4386 __ ldm(ia_w, sp, static_cast<RegList>(r2.bit() | r4.bit()));
4387 __ str(r1, FieldMemOperand(r0, JSArray::kLengthOffset));
4388 __ add(sp, sp, Operand(kPointerSize));
4389 __ str(r4, FieldMemOperand(r0, JSRegExpResult::kIndexOffset));
4390 __ str(r2, FieldMemOperand(r0, JSRegExpResult::kInputOffset));
4391
4392 // Fill out the elements FixedArray.
4393 // r0: JSArray, tagged.
4394 // r3: FixedArray, tagged.
4395 // r5: Number of elements in array, untagged.
4396
4397 // Set map.
4398 __ mov(r2, Operand(Factory::fixed_array_map()));
4399 __ str(r2, FieldMemOperand(r3, HeapObject::kMapOffset));
4400 // Set FixedArray length.
4401 __ str(r5, FieldMemOperand(r3, FixedArray::kLengthOffset));
4402 // Fill contents of fixed-array with the-hole.
4403 __ mov(r2, Operand(Factory::the_hole_value()));
4404 __ add(r3, r3, Operand(FixedArray::kHeaderSize - kHeapObjectTag));
4405 // Fill fixed array elements with hole.
4406 // r0: JSArray, tagged.
4407 // r2: the hole.
4408 // r3: Start of elements in FixedArray.
4409 // r5: Number of elements to fill.
4410 Label loop;
4411 __ tst(r5, Operand(r5));
4412 __ bind(&loop);
4413 __ b(le, &done); // Jump if r1 is negative or zero.
4414 __ sub(r5, r5, Operand(1), SetCC);
4415 __ str(r2, MemOperand(r3, r5, LSL, kPointerSizeLog2));
4416 __ jmp(&loop);
4417
4418 __ bind(&slowcase);
4419 __ CallRuntime(Runtime::kRegExpConstructResult, 3);
4420
4421 __ bind(&done);
4422 }
4423 frame_->Forget(3);
4424 frame_->EmitPush(r0);
4425}
4426
4427
4428class DeferredSearchCache: public DeferredCode {
4429 public:
4430 DeferredSearchCache(Register dst, Register cache, Register key)
4431 : dst_(dst), cache_(cache), key_(key) {
4432 set_comment("[ DeferredSearchCache");
4433 }
4434
4435 virtual void Generate();
4436
4437 private:
4438 Register dst_, cache_, key_;
4439};
4440
4441
4442void DeferredSearchCache::Generate() {
4443 __ Push(cache_, key_);
4444 __ CallRuntime(Runtime::kGetFromCache, 2);
4445 if (!dst_.is(r0)) {
4446 __ mov(dst_, r0);
4447 }
4448}
4449
4450
4451void CodeGenerator::GenerateGetFromCache(ZoneList<Expression*>* args) {
4452 ASSERT_EQ(2, args->length());
4453
4454 ASSERT_NE(NULL, args->at(0)->AsLiteral());
4455 int cache_id = Smi::cast(*(args->at(0)->AsLiteral()->handle()))->value();
4456
4457 Handle<FixedArray> jsfunction_result_caches(
4458 Top::global_context()->jsfunction_result_caches());
4459 if (jsfunction_result_caches->length() <= cache_id) {
4460 __ Abort("Attempt to use undefined cache.");
4461 __ LoadRoot(r0, Heap::kUndefinedValueRootIndex);
4462 frame_->EmitPush(r0);
4463 return;
4464 }
4465
4466 Load(args->at(1));
4467 frame_->EmitPop(r2);
4468
4469 __ ldr(r1, ContextOperand(cp, Context::GLOBAL_INDEX));
4470 __ ldr(r1, FieldMemOperand(r1, GlobalObject::kGlobalContextOffset));
4471 __ ldr(r1, ContextOperand(r1, Context::JSFUNCTION_RESULT_CACHES_INDEX));
4472 __ ldr(r1, FieldMemOperand(r1, FixedArray::OffsetOfElementAt(cache_id)));
4473
4474 DeferredSearchCache* deferred = new DeferredSearchCache(r0, r1, r2);
4475
4476 const int kFingerOffset =
4477 FixedArray::OffsetOfElementAt(JSFunctionResultCache::kFingerIndex);
4478 ASSERT(kSmiTag == 0 && kSmiTagSize == 1);
4479 __ ldr(r0, FieldMemOperand(r1, kFingerOffset));
4480 // r0 now holds finger offset as a smi.
4481 __ add(r3, r1, Operand(FixedArray::kHeaderSize - kHeapObjectTag));
4482 // r3 now points to the start of fixed array elements.
4483 __ ldr(r0, MemOperand(r3, r0, LSL, kPointerSizeLog2 - kSmiTagSize, PreIndex));
4484 // Note side effect of PreIndex: r3 now points to the key of the pair.
4485 __ cmp(r2, r0);
4486 deferred->Branch(ne);
4487
4488 __ ldr(r0, MemOperand(r3, kPointerSize));
4489
4490 deferred->BindExit();
Leon Clarkee46be812010-01-19 14:06:41 +00004491 frame_->EmitPush(r0);
4492}
4493
4494
Andrei Popescu402d9372010-02-26 13:31:12 +00004495void CodeGenerator::GenerateNumberToString(ZoneList<Expression*>* args) {
4496 ASSERT_EQ(args->length(), 1);
4497
4498 // Load the argument on the stack and jump to the runtime.
4499 Load(args->at(0));
4500
Steve Block6ded16b2010-05-10 14:33:55 +01004501 NumberToStringStub stub;
4502 frame_->CallStub(&stub, 1);
4503 frame_->EmitPush(r0);
4504}
4505
4506
4507class DeferredSwapElements: public DeferredCode {
4508 public:
4509 DeferredSwapElements(Register object, Register index1, Register index2)
4510 : object_(object), index1_(index1), index2_(index2) {
4511 set_comment("[ DeferredSwapElements");
4512 }
4513
4514 virtual void Generate();
4515
4516 private:
4517 Register object_, index1_, index2_;
4518};
4519
4520
4521void DeferredSwapElements::Generate() {
4522 __ push(object_);
4523 __ push(index1_);
4524 __ push(index2_);
4525 __ CallRuntime(Runtime::kSwapElements, 3);
4526}
4527
4528
4529void CodeGenerator::GenerateSwapElements(ZoneList<Expression*>* args) {
4530 Comment cmnt(masm_, "[ GenerateSwapElements");
4531
4532 ASSERT_EQ(3, args->length());
4533
4534 Load(args->at(0));
4535 Load(args->at(1));
4536 Load(args->at(2));
4537
4538 Register index2 = r2;
4539 Register index1 = r1;
4540 Register object = r0;
4541 Register tmp1 = r3;
4542 Register tmp2 = r4;
4543
4544 frame_->EmitPop(index2);
4545 frame_->EmitPop(index1);
4546 frame_->EmitPop(object);
4547
4548 DeferredSwapElements* deferred =
4549 new DeferredSwapElements(object, index1, index2);
4550
4551 // Fetch the map and check if array is in fast case.
4552 // Check that object doesn't require security checks and
4553 // has no indexed interceptor.
4554 __ CompareObjectType(object, tmp1, tmp2, FIRST_JS_OBJECT_TYPE);
4555 deferred->Branch(lt);
4556 __ ldrb(tmp2, FieldMemOperand(tmp1, Map::kBitFieldOffset));
4557 __ tst(tmp2, Operand(KeyedLoadIC::kSlowCaseBitFieldMask));
4558 deferred->Branch(nz);
4559
4560 // Check the object's elements are in fast case.
4561 __ ldr(tmp1, FieldMemOperand(object, JSObject::kElementsOffset));
4562 __ ldr(tmp2, FieldMemOperand(tmp1, HeapObject::kMapOffset));
4563 __ LoadRoot(ip, Heap::kFixedArrayMapRootIndex);
4564 __ cmp(tmp2, ip);
4565 deferred->Branch(ne);
4566
4567 // Smi-tagging is equivalent to multiplying by 2.
4568 STATIC_ASSERT(kSmiTag == 0);
4569 STATIC_ASSERT(kSmiTagSize == 1);
4570
4571 // Check that both indices are smis.
4572 __ mov(tmp2, index1);
4573 __ orr(tmp2, tmp2, index2);
4574 __ tst(tmp2, Operand(kSmiTagMask));
4575 deferred->Branch(nz);
4576
4577 // Bring the offsets into the fixed array in tmp1 into index1 and
4578 // index2.
4579 __ mov(tmp2, Operand(FixedArray::kHeaderSize - kHeapObjectTag));
4580 __ add(index1, tmp2, Operand(index1, LSL, kPointerSizeLog2 - kSmiTagSize));
4581 __ add(index2, tmp2, Operand(index2, LSL, kPointerSizeLog2 - kSmiTagSize));
4582
4583 // Swap elements.
4584 Register tmp3 = object;
4585 object = no_reg;
4586 __ ldr(tmp3, MemOperand(tmp1, index1));
4587 __ ldr(tmp2, MemOperand(tmp1, index2));
4588 __ str(tmp3, MemOperand(tmp1, index2));
4589 __ str(tmp2, MemOperand(tmp1, index1));
4590
4591 Label done;
4592 __ InNewSpace(tmp1, tmp2, eq, &done);
4593 // Possible optimization: do a check that both values are Smis
4594 // (or them and test against Smi mask.)
4595
4596 __ mov(tmp2, tmp1);
4597 RecordWriteStub recordWrite1(tmp1, index1, tmp3);
4598 __ CallStub(&recordWrite1);
4599
4600 RecordWriteStub recordWrite2(tmp2, index2, tmp3);
4601 __ CallStub(&recordWrite2);
4602
4603 __ bind(&done);
4604
4605 deferred->BindExit();
4606 __ LoadRoot(tmp1, Heap::kUndefinedValueRootIndex);
4607 frame_->EmitPush(tmp1);
4608}
4609
4610
4611void CodeGenerator::GenerateCallFunction(ZoneList<Expression*>* args) {
4612 Comment cmnt(masm_, "[ GenerateCallFunction");
4613
4614 ASSERT(args->length() >= 2);
4615
4616 int n_args = args->length() - 2; // for receiver and function.
4617 Load(args->at(0)); // receiver
4618 for (int i = 0; i < n_args; i++) {
4619 Load(args->at(i + 1));
4620 }
4621 Load(args->at(n_args + 1)); // function
4622 frame_->CallJSFunction(n_args);
Andrei Popescu402d9372010-02-26 13:31:12 +00004623 frame_->EmitPush(r0);
4624}
4625
4626
4627void CodeGenerator::GenerateMathSin(ZoneList<Expression*>* args) {
4628 ASSERT_EQ(args->length(), 1);
4629 // Load the argument on the stack and jump to the runtime.
4630 Load(args->at(0));
4631 frame_->CallRuntime(Runtime::kMath_sin, 1);
4632 frame_->EmitPush(r0);
4633}
4634
4635
4636void CodeGenerator::GenerateMathCos(ZoneList<Expression*>* args) {
4637 ASSERT_EQ(args->length(), 1);
4638 // Load the argument on the stack and jump to the runtime.
4639 Load(args->at(0));
4640 frame_->CallRuntime(Runtime::kMath_cos, 1);
4641 frame_->EmitPush(r0);
4642}
4643
4644
Steve Blocka7e24c12009-10-30 11:49:00 +00004645void CodeGenerator::GenerateObjectEquals(ZoneList<Expression*>* args) {
Steve Block6ded16b2010-05-10 14:33:55 +01004646 VirtualFrame::SpilledScope spilled_scope(frame_);
Steve Blocka7e24c12009-10-30 11:49:00 +00004647 ASSERT(args->length() == 2);
4648
4649 // Load the two objects into registers and perform the comparison.
4650 LoadAndSpill(args->at(0));
4651 LoadAndSpill(args->at(1));
4652 frame_->EmitPop(r0);
4653 frame_->EmitPop(r1);
Steve Block6ded16b2010-05-10 14:33:55 +01004654 __ cmp(r0, r1);
Steve Blocka7e24c12009-10-30 11:49:00 +00004655 cc_reg_ = eq;
4656}
4657
4658
4659void CodeGenerator::VisitCallRuntime(CallRuntime* node) {
4660#ifdef DEBUG
4661 int original_height = frame_->height();
4662#endif
Steve Block6ded16b2010-05-10 14:33:55 +01004663 VirtualFrame::SpilledScope spilled_scope(frame_);
Steve Blocka7e24c12009-10-30 11:49:00 +00004664 if (CheckForInlineRuntimeCall(node)) {
4665 ASSERT((has_cc() && frame_->height() == original_height) ||
4666 (!has_cc() && frame_->height() == original_height + 1));
4667 return;
4668 }
4669
4670 ZoneList<Expression*>* args = node->arguments();
4671 Comment cmnt(masm_, "[ CallRuntime");
4672 Runtime::Function* function = node->function();
4673
4674 if (function == NULL) {
4675 // Prepare stack for calling JS runtime function.
Steve Blocka7e24c12009-10-30 11:49:00 +00004676 // Push the builtins object found in the current global object.
4677 __ ldr(r1, GlobalObject());
4678 __ ldr(r0, FieldMemOperand(r1, GlobalObject::kBuiltinsOffset));
4679 frame_->EmitPush(r0);
4680 }
4681
4682 // Push the arguments ("left-to-right").
4683 int arg_count = args->length();
4684 for (int i = 0; i < arg_count; i++) {
4685 LoadAndSpill(args->at(i));
4686 }
4687
4688 if (function == NULL) {
4689 // Call the JS runtime function.
Andrei Popescu402d9372010-02-26 13:31:12 +00004690 __ mov(r2, Operand(node->name()));
Steve Blocka7e24c12009-10-30 11:49:00 +00004691 InLoopFlag in_loop = loop_nesting() > 0 ? IN_LOOP : NOT_IN_LOOP;
4692 Handle<Code> stub = ComputeCallInitialize(arg_count, in_loop);
4693 frame_->CallCodeObject(stub, RelocInfo::CODE_TARGET, arg_count + 1);
4694 __ ldr(cp, frame_->Context());
Steve Blocka7e24c12009-10-30 11:49:00 +00004695 frame_->EmitPush(r0);
4696 } else {
4697 // Call the C runtime function.
4698 frame_->CallRuntime(function, arg_count);
4699 frame_->EmitPush(r0);
4700 }
Steve Block6ded16b2010-05-10 14:33:55 +01004701 ASSERT_EQ(original_height + 1, frame_->height());
Steve Blocka7e24c12009-10-30 11:49:00 +00004702}
4703
4704
4705void CodeGenerator::VisitUnaryOperation(UnaryOperation* node) {
4706#ifdef DEBUG
4707 int original_height = frame_->height();
4708#endif
Steve Block6ded16b2010-05-10 14:33:55 +01004709 VirtualFrame::SpilledScope spilled_scope(frame_);
Steve Blocka7e24c12009-10-30 11:49:00 +00004710 Comment cmnt(masm_, "[ UnaryOperation");
4711
4712 Token::Value op = node->op();
4713
4714 if (op == Token::NOT) {
4715 LoadConditionAndSpill(node->expression(),
Steve Blocka7e24c12009-10-30 11:49:00 +00004716 false_target(),
4717 true_target(),
4718 true);
4719 // LoadCondition may (and usually does) leave a test and branch to
4720 // be emitted by the caller. In that case, negate the condition.
4721 if (has_cc()) cc_reg_ = NegateCondition(cc_reg_);
4722
4723 } else if (op == Token::DELETE) {
4724 Property* property = node->expression()->AsProperty();
4725 Variable* variable = node->expression()->AsVariableProxy()->AsVariable();
4726 if (property != NULL) {
4727 LoadAndSpill(property->obj());
4728 LoadAndSpill(property->key());
Steve Blockd0582a62009-12-15 09:54:21 +00004729 frame_->InvokeBuiltin(Builtins::DELETE, CALL_JS, 2);
Steve Blocka7e24c12009-10-30 11:49:00 +00004730
4731 } else if (variable != NULL) {
4732 Slot* slot = variable->slot();
4733 if (variable->is_global()) {
4734 LoadGlobal();
4735 __ mov(r0, Operand(variable->name()));
4736 frame_->EmitPush(r0);
Steve Blockd0582a62009-12-15 09:54:21 +00004737 frame_->InvokeBuiltin(Builtins::DELETE, CALL_JS, 2);
Steve Blocka7e24c12009-10-30 11:49:00 +00004738
4739 } else if (slot != NULL && slot->type() == Slot::LOOKUP) {
4740 // lookup the context holding the named variable
4741 frame_->EmitPush(cp);
4742 __ mov(r0, Operand(variable->name()));
4743 frame_->EmitPush(r0);
4744 frame_->CallRuntime(Runtime::kLookupContext, 2);
4745 // r0: context
4746 frame_->EmitPush(r0);
4747 __ mov(r0, Operand(variable->name()));
4748 frame_->EmitPush(r0);
Steve Blockd0582a62009-12-15 09:54:21 +00004749 frame_->InvokeBuiltin(Builtins::DELETE, CALL_JS, 2);
Steve Blocka7e24c12009-10-30 11:49:00 +00004750
4751 } else {
4752 // Default: Result of deleting non-global, not dynamically
4753 // introduced variables is false.
4754 __ LoadRoot(r0, Heap::kFalseValueRootIndex);
4755 }
4756
4757 } else {
4758 // Default: Result of deleting expressions is true.
4759 LoadAndSpill(node->expression()); // may have side-effects
4760 frame_->Drop();
4761 __ LoadRoot(r0, Heap::kTrueValueRootIndex);
4762 }
4763 frame_->EmitPush(r0);
4764
4765 } else if (op == Token::TYPEOF) {
4766 // Special case for loading the typeof expression; see comment on
4767 // LoadTypeofExpression().
4768 LoadTypeofExpression(node->expression());
4769 frame_->CallRuntime(Runtime::kTypeof, 1);
4770 frame_->EmitPush(r0); // r0 has result
4771
4772 } else {
Leon Clarke4515c472010-02-03 11:58:03 +00004773 bool overwrite =
4774 (node->expression()->AsBinaryOperation() != NULL &&
4775 node->expression()->AsBinaryOperation()->ResultOverwriteAllowed());
Steve Blocka7e24c12009-10-30 11:49:00 +00004776 LoadAndSpill(node->expression());
4777 frame_->EmitPop(r0);
4778 switch (op) {
4779 case Token::NOT:
4780 case Token::DELETE:
4781 case Token::TYPEOF:
4782 UNREACHABLE(); // handled above
4783 break;
4784
4785 case Token::SUB: {
Leon Clarkee46be812010-01-19 14:06:41 +00004786 GenericUnaryOpStub stub(Token::SUB, overwrite);
Steve Blocka7e24c12009-10-30 11:49:00 +00004787 frame_->CallStub(&stub, 0);
4788 break;
4789 }
4790
4791 case Token::BIT_NOT: {
4792 // smi check
4793 JumpTarget smi_label;
4794 JumpTarget continue_label;
4795 __ tst(r0, Operand(kSmiTagMask));
4796 smi_label.Branch(eq);
4797
Leon Clarke4515c472010-02-03 11:58:03 +00004798 GenericUnaryOpStub stub(Token::BIT_NOT, overwrite);
4799 frame_->CallStub(&stub, 0);
Steve Blocka7e24c12009-10-30 11:49:00 +00004800 continue_label.Jump();
Leon Clarke4515c472010-02-03 11:58:03 +00004801
Steve Blocka7e24c12009-10-30 11:49:00 +00004802 smi_label.Bind();
4803 __ mvn(r0, Operand(r0));
4804 __ bic(r0, r0, Operand(kSmiTagMask)); // bit-clear inverted smi-tag
4805 continue_label.Bind();
4806 break;
4807 }
4808
4809 case Token::VOID:
4810 // since the stack top is cached in r0, popping and then
4811 // pushing a value can be done by just writing to r0.
4812 __ LoadRoot(r0, Heap::kUndefinedValueRootIndex);
4813 break;
4814
4815 case Token::ADD: {
4816 // Smi check.
4817 JumpTarget continue_label;
4818 __ tst(r0, Operand(kSmiTagMask));
4819 continue_label.Branch(eq);
4820 frame_->EmitPush(r0);
Steve Blockd0582a62009-12-15 09:54:21 +00004821 frame_->InvokeBuiltin(Builtins::TO_NUMBER, CALL_JS, 1);
Steve Blocka7e24c12009-10-30 11:49:00 +00004822 continue_label.Bind();
4823 break;
4824 }
4825 default:
4826 UNREACHABLE();
4827 }
4828 frame_->EmitPush(r0); // r0 has result
4829 }
4830 ASSERT(!has_valid_frame() ||
4831 (has_cc() && frame_->height() == original_height) ||
4832 (!has_cc() && frame_->height() == original_height + 1));
4833}
4834
4835
4836void CodeGenerator::VisitCountOperation(CountOperation* node) {
4837#ifdef DEBUG
4838 int original_height = frame_->height();
4839#endif
Steve Block6ded16b2010-05-10 14:33:55 +01004840 VirtualFrame::SpilledScope spilled_scope(frame_);
Steve Blocka7e24c12009-10-30 11:49:00 +00004841 Comment cmnt(masm_, "[ CountOperation");
4842
4843 bool is_postfix = node->is_postfix();
4844 bool is_increment = node->op() == Token::INC;
4845
4846 Variable* var = node->expression()->AsVariableProxy()->AsVariable();
4847 bool is_const = (var != NULL && var->mode() == Variable::CONST);
4848
4849 // Postfix: Make room for the result.
4850 if (is_postfix) {
4851 __ mov(r0, Operand(0));
4852 frame_->EmitPush(r0);
4853 }
4854
Leon Clarked91b9f72010-01-27 17:25:45 +00004855 // A constant reference is not saved to, so a constant reference is not a
4856 // compound assignment reference.
4857 { Reference target(this, node->expression(), !is_const);
Steve Blocka7e24c12009-10-30 11:49:00 +00004858 if (target.is_illegal()) {
4859 // Spoof the virtual frame to have the expected height (one higher
4860 // than on entry).
4861 if (!is_postfix) {
4862 __ mov(r0, Operand(Smi::FromInt(0)));
4863 frame_->EmitPush(r0);
4864 }
Steve Block6ded16b2010-05-10 14:33:55 +01004865 ASSERT_EQ(original_height + 1, frame_->height());
Steve Blocka7e24c12009-10-30 11:49:00 +00004866 return;
4867 }
Steve Block6ded16b2010-05-10 14:33:55 +01004868 target.GetValue();
Steve Blocka7e24c12009-10-30 11:49:00 +00004869 frame_->EmitPop(r0);
4870
4871 JumpTarget slow;
4872 JumpTarget exit;
4873
4874 // Load the value (1) into register r1.
4875 __ mov(r1, Operand(Smi::FromInt(1)));
4876
4877 // Check for smi operand.
4878 __ tst(r0, Operand(kSmiTagMask));
4879 slow.Branch(ne);
4880
4881 // Postfix: Store the old value as the result.
4882 if (is_postfix) {
4883 __ str(r0, frame_->ElementAt(target.size()));
4884 }
4885
4886 // Perform optimistic increment/decrement.
4887 if (is_increment) {
4888 __ add(r0, r0, Operand(r1), SetCC);
4889 } else {
4890 __ sub(r0, r0, Operand(r1), SetCC);
4891 }
4892
4893 // If the increment/decrement didn't overflow, we're done.
4894 exit.Branch(vc);
4895
4896 // Revert optimistic increment/decrement.
4897 if (is_increment) {
4898 __ sub(r0, r0, Operand(r1));
4899 } else {
4900 __ add(r0, r0, Operand(r1));
4901 }
4902
4903 // Slow case: Convert to number.
4904 slow.Bind();
4905 {
4906 // Convert the operand to a number.
4907 frame_->EmitPush(r0);
Steve Blockd0582a62009-12-15 09:54:21 +00004908 frame_->InvokeBuiltin(Builtins::TO_NUMBER, CALL_JS, 1);
Steve Blocka7e24c12009-10-30 11:49:00 +00004909 }
4910 if (is_postfix) {
4911 // Postfix: store to result (on the stack).
4912 __ str(r0, frame_->ElementAt(target.size()));
4913 }
4914
4915 // Compute the new value.
4916 __ mov(r1, Operand(Smi::FromInt(1)));
4917 frame_->EmitPush(r0);
4918 frame_->EmitPush(r1);
4919 if (is_increment) {
4920 frame_->CallRuntime(Runtime::kNumberAdd, 2);
4921 } else {
4922 frame_->CallRuntime(Runtime::kNumberSub, 2);
4923 }
4924
4925 // Store the new value in the target if not const.
4926 exit.Bind();
4927 frame_->EmitPush(r0);
4928 if (!is_const) target.SetValue(NOT_CONST_INIT);
4929 }
4930
4931 // Postfix: Discard the new value and use the old.
4932 if (is_postfix) frame_->EmitPop(r0);
Steve Block6ded16b2010-05-10 14:33:55 +01004933 ASSERT_EQ(original_height + 1, frame_->height());
Steve Blocka7e24c12009-10-30 11:49:00 +00004934}
4935
4936
Steve Block6ded16b2010-05-10 14:33:55 +01004937void CodeGenerator::GenerateLogicalBooleanOperation(BinaryOperation* node) {
Steve Blocka7e24c12009-10-30 11:49:00 +00004938 // According to ECMA-262 section 11.11, page 58, the binary logical
4939 // operators must yield the result of one of the two expressions
4940 // before any ToBoolean() conversions. This means that the value
4941 // produced by a && or || operator is not necessarily a boolean.
4942
4943 // NOTE: If the left hand side produces a materialized value (not in
4944 // the CC register), we force the right hand side to do the
4945 // same. This is necessary because we may have to branch to the exit
4946 // after evaluating the left hand side (due to the shortcut
4947 // semantics), but the compiler must (statically) know if the result
4948 // of compiling the binary operation is materialized or not.
Steve Block6ded16b2010-05-10 14:33:55 +01004949 if (node->op() == Token::AND) {
Steve Blocka7e24c12009-10-30 11:49:00 +00004950 JumpTarget is_true;
4951 LoadConditionAndSpill(node->left(),
Steve Blocka7e24c12009-10-30 11:49:00 +00004952 &is_true,
4953 false_target(),
4954 false);
4955 if (has_valid_frame() && !has_cc()) {
4956 // The left-hand side result is on top of the virtual frame.
4957 JumpTarget pop_and_continue;
4958 JumpTarget exit;
4959
4960 __ ldr(r0, frame_->Top()); // Duplicate the stack top.
4961 frame_->EmitPush(r0);
4962 // Avoid popping the result if it converts to 'false' using the
4963 // standard ToBoolean() conversion as described in ECMA-262,
4964 // section 9.2, page 30.
4965 ToBoolean(&pop_and_continue, &exit);
4966 Branch(false, &exit);
4967
4968 // Pop the result of evaluating the first part.
4969 pop_and_continue.Bind();
4970 frame_->EmitPop(r0);
4971
4972 // Evaluate right side expression.
4973 is_true.Bind();
4974 LoadAndSpill(node->right());
4975
4976 // Exit (always with a materialized value).
4977 exit.Bind();
4978 } else if (has_cc() || is_true.is_linked()) {
4979 // The left-hand side is either (a) partially compiled to
4980 // control flow with a final branch left to emit or (b) fully
4981 // compiled to control flow and possibly true.
4982 if (has_cc()) {
4983 Branch(false, false_target());
4984 }
4985 is_true.Bind();
4986 LoadConditionAndSpill(node->right(),
Steve Blocka7e24c12009-10-30 11:49:00 +00004987 true_target(),
4988 false_target(),
4989 false);
4990 } else {
4991 // Nothing to do.
4992 ASSERT(!has_valid_frame() && !has_cc() && !is_true.is_linked());
4993 }
4994
Steve Block6ded16b2010-05-10 14:33:55 +01004995 } else {
4996 ASSERT(node->op() == Token::OR);
Steve Blocka7e24c12009-10-30 11:49:00 +00004997 JumpTarget is_false;
4998 LoadConditionAndSpill(node->left(),
Steve Blocka7e24c12009-10-30 11:49:00 +00004999 true_target(),
5000 &is_false,
5001 false);
5002 if (has_valid_frame() && !has_cc()) {
5003 // The left-hand side result is on top of the virtual frame.
5004 JumpTarget pop_and_continue;
5005 JumpTarget exit;
5006
5007 __ ldr(r0, frame_->Top());
5008 frame_->EmitPush(r0);
5009 // Avoid popping the result if it converts to 'true' using the
5010 // standard ToBoolean() conversion as described in ECMA-262,
5011 // section 9.2, page 30.
5012 ToBoolean(&exit, &pop_and_continue);
5013 Branch(true, &exit);
5014
5015 // Pop the result of evaluating the first part.
5016 pop_and_continue.Bind();
5017 frame_->EmitPop(r0);
5018
5019 // Evaluate right side expression.
5020 is_false.Bind();
5021 LoadAndSpill(node->right());
5022
5023 // Exit (always with a materialized value).
5024 exit.Bind();
5025 } else if (has_cc() || is_false.is_linked()) {
5026 // The left-hand side is either (a) partially compiled to
5027 // control flow with a final branch left to emit or (b) fully
5028 // compiled to control flow and possibly false.
5029 if (has_cc()) {
5030 Branch(true, true_target());
5031 }
5032 is_false.Bind();
5033 LoadConditionAndSpill(node->right(),
Steve Blocka7e24c12009-10-30 11:49:00 +00005034 true_target(),
5035 false_target(),
5036 false);
5037 } else {
5038 // Nothing to do.
5039 ASSERT(!has_valid_frame() && !has_cc() && !is_false.is_linked());
5040 }
Steve Block6ded16b2010-05-10 14:33:55 +01005041 }
5042}
Steve Blocka7e24c12009-10-30 11:49:00 +00005043
Steve Block6ded16b2010-05-10 14:33:55 +01005044
5045void CodeGenerator::VisitBinaryOperation(BinaryOperation* node) {
5046#ifdef DEBUG
5047 int original_height = frame_->height();
5048#endif
5049 Comment cmnt(masm_, "[ BinaryOperation");
5050
5051 if (node->op() == Token::AND || node->op() == Token::OR) {
5052 VirtualFrame::SpilledScope spilled_scope(frame_);
5053 GenerateLogicalBooleanOperation(node);
Steve Blocka7e24c12009-10-30 11:49:00 +00005054 } else {
5055 // Optimize for the case where (at least) one of the expressions
5056 // is a literal small integer.
5057 Literal* lliteral = node->left()->AsLiteral();
5058 Literal* rliteral = node->right()->AsLiteral();
5059 // NOTE: The code below assumes that the slow cases (calls to runtime)
5060 // never return a constant/immutable object.
5061 bool overwrite_left =
5062 (node->left()->AsBinaryOperation() != NULL &&
5063 node->left()->AsBinaryOperation()->ResultOverwriteAllowed());
5064 bool overwrite_right =
5065 (node->right()->AsBinaryOperation() != NULL &&
5066 node->right()->AsBinaryOperation()->ResultOverwriteAllowed());
5067
5068 if (rliteral != NULL && rliteral->handle()->IsSmi()) {
Steve Block6ded16b2010-05-10 14:33:55 +01005069 VirtualFrame::RegisterAllocationScope scope(this);
5070 Load(node->left());
Steve Blocka7e24c12009-10-30 11:49:00 +00005071 SmiOperation(node->op(),
5072 rliteral->handle(),
5073 false,
5074 overwrite_right ? OVERWRITE_RIGHT : NO_OVERWRITE);
Steve Blocka7e24c12009-10-30 11:49:00 +00005075 } else if (lliteral != NULL && lliteral->handle()->IsSmi()) {
Steve Block6ded16b2010-05-10 14:33:55 +01005076 VirtualFrame::RegisterAllocationScope scope(this);
5077 Load(node->right());
Steve Blocka7e24c12009-10-30 11:49:00 +00005078 SmiOperation(node->op(),
5079 lliteral->handle(),
5080 true,
5081 overwrite_left ? OVERWRITE_LEFT : NO_OVERWRITE);
Steve Blocka7e24c12009-10-30 11:49:00 +00005082 } else {
Steve Block6ded16b2010-05-10 14:33:55 +01005083 VirtualFrame::RegisterAllocationScope scope(this);
Steve Blocka7e24c12009-10-30 11:49:00 +00005084 OverwriteMode overwrite_mode = NO_OVERWRITE;
5085 if (overwrite_left) {
5086 overwrite_mode = OVERWRITE_LEFT;
5087 } else if (overwrite_right) {
5088 overwrite_mode = OVERWRITE_RIGHT;
5089 }
Steve Block6ded16b2010-05-10 14:33:55 +01005090 Load(node->left());
5091 Load(node->right());
5092 VirtualFrameBinaryOperation(node->op(), overwrite_mode);
Steve Blocka7e24c12009-10-30 11:49:00 +00005093 }
Steve Blocka7e24c12009-10-30 11:49:00 +00005094 }
5095 ASSERT(!has_valid_frame() ||
5096 (has_cc() && frame_->height() == original_height) ||
5097 (!has_cc() && frame_->height() == original_height + 1));
5098}
5099
5100
5101void CodeGenerator::VisitThisFunction(ThisFunction* node) {
5102#ifdef DEBUG
5103 int original_height = frame_->height();
5104#endif
Steve Block6ded16b2010-05-10 14:33:55 +01005105 VirtualFrame::SpilledScope spilled_scope(frame_);
Steve Blocka7e24c12009-10-30 11:49:00 +00005106 __ ldr(r0, frame_->Function());
5107 frame_->EmitPush(r0);
Steve Block6ded16b2010-05-10 14:33:55 +01005108 ASSERT_EQ(original_height + 1, frame_->height());
Steve Blocka7e24c12009-10-30 11:49:00 +00005109}
5110
5111
5112void CodeGenerator::VisitCompareOperation(CompareOperation* node) {
5113#ifdef DEBUG
5114 int original_height = frame_->height();
5115#endif
Steve Blocka7e24c12009-10-30 11:49:00 +00005116 Comment cmnt(masm_, "[ CompareOperation");
5117
Steve Block6ded16b2010-05-10 14:33:55 +01005118 VirtualFrame::RegisterAllocationScope nonspilled_scope(this);
5119
Steve Blocka7e24c12009-10-30 11:49:00 +00005120 // Get the expressions from the node.
5121 Expression* left = node->left();
5122 Expression* right = node->right();
5123 Token::Value op = node->op();
5124
5125 // To make null checks efficient, we check if either left or right is the
5126 // literal 'null'. If so, we optimize the code by inlining a null check
5127 // instead of calling the (very) general runtime routine for checking
5128 // equality.
5129 if (op == Token::EQ || op == Token::EQ_STRICT) {
5130 bool left_is_null =
5131 left->AsLiteral() != NULL && left->AsLiteral()->IsNull();
5132 bool right_is_null =
5133 right->AsLiteral() != NULL && right->AsLiteral()->IsNull();
5134 // The 'null' value can only be equal to 'null' or 'undefined'.
5135 if (left_is_null || right_is_null) {
Steve Block6ded16b2010-05-10 14:33:55 +01005136 Load(left_is_null ? right : left);
5137 Register tos = frame_->PopToRegister();
5138 // JumpTargets can't cope with register allocation yet.
5139 frame_->SpillAll();
Steve Blocka7e24c12009-10-30 11:49:00 +00005140 __ LoadRoot(ip, Heap::kNullValueRootIndex);
Steve Block6ded16b2010-05-10 14:33:55 +01005141 __ cmp(tos, ip);
Steve Blocka7e24c12009-10-30 11:49:00 +00005142
5143 // The 'null' value is only equal to 'undefined' if using non-strict
5144 // comparisons.
5145 if (op != Token::EQ_STRICT) {
5146 true_target()->Branch(eq);
5147
5148 __ LoadRoot(ip, Heap::kUndefinedValueRootIndex);
Steve Block6ded16b2010-05-10 14:33:55 +01005149 __ cmp(tos, Operand(ip));
Steve Blocka7e24c12009-10-30 11:49:00 +00005150 true_target()->Branch(eq);
5151
Steve Block6ded16b2010-05-10 14:33:55 +01005152 __ tst(tos, Operand(kSmiTagMask));
Steve Blocka7e24c12009-10-30 11:49:00 +00005153 false_target()->Branch(eq);
5154
5155 // It can be an undetectable object.
Steve Block6ded16b2010-05-10 14:33:55 +01005156 __ ldr(tos, FieldMemOperand(tos, HeapObject::kMapOffset));
5157 __ ldrb(tos, FieldMemOperand(tos, Map::kBitFieldOffset));
5158 __ and_(tos, tos, Operand(1 << Map::kIsUndetectable));
5159 __ cmp(tos, Operand(1 << Map::kIsUndetectable));
Steve Blocka7e24c12009-10-30 11:49:00 +00005160 }
5161
5162 cc_reg_ = eq;
5163 ASSERT(has_cc() && frame_->height() == original_height);
5164 return;
5165 }
5166 }
5167
5168 // To make typeof testing for natives implemented in JavaScript really
5169 // efficient, we generate special code for expressions of the form:
5170 // 'typeof <expression> == <string>'.
5171 UnaryOperation* operation = left->AsUnaryOperation();
5172 if ((op == Token::EQ || op == Token::EQ_STRICT) &&
5173 (operation != NULL && operation->op() == Token::TYPEOF) &&
5174 (right->AsLiteral() != NULL &&
5175 right->AsLiteral()->handle()->IsString())) {
5176 Handle<String> check(String::cast(*right->AsLiteral()->handle()));
5177
Steve Block6ded16b2010-05-10 14:33:55 +01005178 // Load the operand, move it to a register.
Steve Blocka7e24c12009-10-30 11:49:00 +00005179 LoadTypeofExpression(operation->expression());
Steve Block6ded16b2010-05-10 14:33:55 +01005180 Register tos = frame_->PopToRegister();
5181
5182 // JumpTargets can't cope with register allocation yet.
5183 frame_->SpillAll();
5184
5185 Register scratch = VirtualFrame::scratch0();
Steve Blocka7e24c12009-10-30 11:49:00 +00005186
5187 if (check->Equals(Heap::number_symbol())) {
Steve Block6ded16b2010-05-10 14:33:55 +01005188 __ tst(tos, Operand(kSmiTagMask));
Steve Blocka7e24c12009-10-30 11:49:00 +00005189 true_target()->Branch(eq);
Steve Block6ded16b2010-05-10 14:33:55 +01005190 __ ldr(tos, FieldMemOperand(tos, HeapObject::kMapOffset));
Steve Blocka7e24c12009-10-30 11:49:00 +00005191 __ LoadRoot(ip, Heap::kHeapNumberMapRootIndex);
Steve Block6ded16b2010-05-10 14:33:55 +01005192 __ cmp(tos, ip);
Steve Blocka7e24c12009-10-30 11:49:00 +00005193 cc_reg_ = eq;
5194
5195 } else if (check->Equals(Heap::string_symbol())) {
Steve Block6ded16b2010-05-10 14:33:55 +01005196 __ tst(tos, Operand(kSmiTagMask));
Steve Blocka7e24c12009-10-30 11:49:00 +00005197 false_target()->Branch(eq);
5198
Steve Block6ded16b2010-05-10 14:33:55 +01005199 __ ldr(tos, FieldMemOperand(tos, HeapObject::kMapOffset));
Steve Blocka7e24c12009-10-30 11:49:00 +00005200
5201 // It can be an undetectable string object.
Steve Block6ded16b2010-05-10 14:33:55 +01005202 __ ldrb(scratch, FieldMemOperand(tos, Map::kBitFieldOffset));
5203 __ and_(scratch, scratch, Operand(1 << Map::kIsUndetectable));
5204 __ cmp(scratch, Operand(1 << Map::kIsUndetectable));
Steve Blocka7e24c12009-10-30 11:49:00 +00005205 false_target()->Branch(eq);
5206
Steve Block6ded16b2010-05-10 14:33:55 +01005207 __ ldrb(scratch, FieldMemOperand(tos, Map::kInstanceTypeOffset));
5208 __ cmp(scratch, Operand(FIRST_NONSTRING_TYPE));
Steve Blocka7e24c12009-10-30 11:49:00 +00005209 cc_reg_ = lt;
5210
5211 } else if (check->Equals(Heap::boolean_symbol())) {
5212 __ LoadRoot(ip, Heap::kTrueValueRootIndex);
Steve Block6ded16b2010-05-10 14:33:55 +01005213 __ cmp(tos, ip);
Steve Blocka7e24c12009-10-30 11:49:00 +00005214 true_target()->Branch(eq);
5215 __ LoadRoot(ip, Heap::kFalseValueRootIndex);
Steve Block6ded16b2010-05-10 14:33:55 +01005216 __ cmp(tos, ip);
Steve Blocka7e24c12009-10-30 11:49:00 +00005217 cc_reg_ = eq;
5218
5219 } else if (check->Equals(Heap::undefined_symbol())) {
5220 __ LoadRoot(ip, Heap::kUndefinedValueRootIndex);
Steve Block6ded16b2010-05-10 14:33:55 +01005221 __ cmp(tos, ip);
Steve Blocka7e24c12009-10-30 11:49:00 +00005222 true_target()->Branch(eq);
5223
Steve Block6ded16b2010-05-10 14:33:55 +01005224 __ tst(tos, Operand(kSmiTagMask));
Steve Blocka7e24c12009-10-30 11:49:00 +00005225 false_target()->Branch(eq);
5226
5227 // It can be an undetectable object.
Steve Block6ded16b2010-05-10 14:33:55 +01005228 __ ldr(tos, FieldMemOperand(tos, HeapObject::kMapOffset));
5229 __ ldrb(scratch, FieldMemOperand(tos, Map::kBitFieldOffset));
5230 __ and_(scratch, scratch, Operand(1 << Map::kIsUndetectable));
5231 __ cmp(scratch, Operand(1 << Map::kIsUndetectable));
Steve Blocka7e24c12009-10-30 11:49:00 +00005232
5233 cc_reg_ = eq;
5234
5235 } else if (check->Equals(Heap::function_symbol())) {
Steve Block6ded16b2010-05-10 14:33:55 +01005236 __ tst(tos, Operand(kSmiTagMask));
Steve Blocka7e24c12009-10-30 11:49:00 +00005237 false_target()->Branch(eq);
Steve Block6ded16b2010-05-10 14:33:55 +01005238 Register map_reg = scratch;
5239 __ CompareObjectType(tos, map_reg, tos, JS_FUNCTION_TYPE);
Steve Blockd0582a62009-12-15 09:54:21 +00005240 true_target()->Branch(eq);
5241 // Regular expressions are callable so typeof == 'function'.
Steve Block6ded16b2010-05-10 14:33:55 +01005242 __ CompareInstanceType(map_reg, tos, JS_REGEXP_TYPE);
Steve Blocka7e24c12009-10-30 11:49:00 +00005243 cc_reg_ = eq;
5244
5245 } else if (check->Equals(Heap::object_symbol())) {
Steve Block6ded16b2010-05-10 14:33:55 +01005246 __ tst(tos, Operand(kSmiTagMask));
Steve Blocka7e24c12009-10-30 11:49:00 +00005247 false_target()->Branch(eq);
5248
Steve Blocka7e24c12009-10-30 11:49:00 +00005249 __ LoadRoot(ip, Heap::kNullValueRootIndex);
Steve Block6ded16b2010-05-10 14:33:55 +01005250 __ cmp(tos, ip);
Steve Blocka7e24c12009-10-30 11:49:00 +00005251 true_target()->Branch(eq);
5252
Steve Block6ded16b2010-05-10 14:33:55 +01005253 Register map_reg = scratch;
5254 __ CompareObjectType(tos, map_reg, tos, JS_REGEXP_TYPE);
Steve Blockd0582a62009-12-15 09:54:21 +00005255 false_target()->Branch(eq);
5256
Steve Blocka7e24c12009-10-30 11:49:00 +00005257 // It can be an undetectable object.
Steve Block6ded16b2010-05-10 14:33:55 +01005258 __ ldrb(tos, FieldMemOperand(map_reg, Map::kBitFieldOffset));
5259 __ and_(tos, tos, Operand(1 << Map::kIsUndetectable));
5260 __ cmp(tos, Operand(1 << Map::kIsUndetectable));
Steve Blocka7e24c12009-10-30 11:49:00 +00005261 false_target()->Branch(eq);
5262
Steve Block6ded16b2010-05-10 14:33:55 +01005263 __ ldrb(tos, FieldMemOperand(map_reg, Map::kInstanceTypeOffset));
5264 __ cmp(tos, Operand(FIRST_JS_OBJECT_TYPE));
Steve Blocka7e24c12009-10-30 11:49:00 +00005265 false_target()->Branch(lt);
Steve Block6ded16b2010-05-10 14:33:55 +01005266 __ cmp(tos, Operand(LAST_JS_OBJECT_TYPE));
Steve Blocka7e24c12009-10-30 11:49:00 +00005267 cc_reg_ = le;
5268
5269 } else {
5270 // Uncommon case: typeof testing against a string literal that is
5271 // never returned from the typeof operator.
5272 false_target()->Jump();
5273 }
5274 ASSERT(!has_valid_frame() ||
5275 (has_cc() && frame_->height() == original_height));
5276 return;
5277 }
5278
5279 switch (op) {
5280 case Token::EQ:
5281 Comparison(eq, left, right, false);
5282 break;
5283
5284 case Token::LT:
5285 Comparison(lt, left, right);
5286 break;
5287
5288 case Token::GT:
5289 Comparison(gt, left, right);
5290 break;
5291
5292 case Token::LTE:
5293 Comparison(le, left, right);
5294 break;
5295
5296 case Token::GTE:
5297 Comparison(ge, left, right);
5298 break;
5299
5300 case Token::EQ_STRICT:
5301 Comparison(eq, left, right, true);
5302 break;
5303
5304 case Token::IN: {
Steve Block6ded16b2010-05-10 14:33:55 +01005305 VirtualFrame::SpilledScope scope(frame_);
Steve Blocka7e24c12009-10-30 11:49:00 +00005306 LoadAndSpill(left);
5307 LoadAndSpill(right);
Steve Blockd0582a62009-12-15 09:54:21 +00005308 frame_->InvokeBuiltin(Builtins::IN, CALL_JS, 2);
Steve Blocka7e24c12009-10-30 11:49:00 +00005309 frame_->EmitPush(r0);
5310 break;
5311 }
5312
5313 case Token::INSTANCEOF: {
Steve Block6ded16b2010-05-10 14:33:55 +01005314 VirtualFrame::SpilledScope scope(frame_);
Steve Blocka7e24c12009-10-30 11:49:00 +00005315 LoadAndSpill(left);
5316 LoadAndSpill(right);
5317 InstanceofStub stub;
5318 frame_->CallStub(&stub, 2);
5319 // At this point if instanceof succeeded then r0 == 0.
5320 __ tst(r0, Operand(r0));
5321 cc_reg_ = eq;
5322 break;
5323 }
5324
5325 default:
5326 UNREACHABLE();
5327 }
5328 ASSERT((has_cc() && frame_->height() == original_height) ||
5329 (!has_cc() && frame_->height() == original_height + 1));
5330}
5331
5332
Steve Block6ded16b2010-05-10 14:33:55 +01005333class DeferredReferenceGetNamedValue: public DeferredCode {
5334 public:
5335 explicit DeferredReferenceGetNamedValue(Handle<String> name) : name_(name) {
5336 set_comment("[ DeferredReferenceGetNamedValue");
5337 }
5338
5339 virtual void Generate();
5340
5341 private:
5342 Handle<String> name_;
5343};
5344
5345
5346void DeferredReferenceGetNamedValue::Generate() {
5347 Register scratch1 = VirtualFrame::scratch0();
5348 Register scratch2 = VirtualFrame::scratch1();
5349 __ DecrementCounter(&Counters::named_load_inline, 1, scratch1, scratch2);
5350 __ IncrementCounter(&Counters::named_load_inline_miss, 1, scratch1, scratch2);
5351
5352 // Setup the registers and call load IC.
5353 // On entry to this deferred code, r0 is assumed to already contain the
5354 // receiver from the top of the stack.
5355 __ mov(r2, Operand(name_));
5356
5357 // The rest of the instructions in the deferred code must be together.
5358 { Assembler::BlockConstPoolScope block_const_pool(masm_);
5359 Handle<Code> ic(Builtins::builtin(Builtins::LoadIC_Initialize));
5360 __ Call(ic, RelocInfo::CODE_TARGET);
5361 // The call must be followed by a nop(1) instruction to indicate that the
5362 // in-object has been inlined.
5363 __ nop(PROPERTY_ACCESS_INLINED);
5364
5365 // Block the constant pool for one more instruction after leaving this
5366 // constant pool block scope to include the branch instruction ending the
5367 // deferred code.
5368 __ BlockConstPoolFor(1);
5369 }
5370}
5371
5372
5373class DeferredReferenceGetKeyedValue: public DeferredCode {
5374 public:
5375 DeferredReferenceGetKeyedValue() {
5376 set_comment("[ DeferredReferenceGetKeyedValue");
5377 }
5378
5379 virtual void Generate();
5380};
5381
5382
5383void DeferredReferenceGetKeyedValue::Generate() {
5384 Register scratch1 = VirtualFrame::scratch0();
5385 Register scratch2 = VirtualFrame::scratch1();
5386 __ DecrementCounter(&Counters::keyed_load_inline, 1, scratch1, scratch2);
5387 __ IncrementCounter(&Counters::keyed_load_inline_miss, 1, scratch1, scratch2);
5388
5389 // The rest of the instructions in the deferred code must be together.
5390 { Assembler::BlockConstPoolScope block_const_pool(masm_);
5391 // Call keyed load IC. It has all arguments on the stack and the key in r0.
5392 __ ldr(r0, MemOperand(sp, 0));
5393 Handle<Code> ic(Builtins::builtin(Builtins::KeyedLoadIC_Initialize));
5394 __ Call(ic, RelocInfo::CODE_TARGET);
5395 // The call must be followed by a nop instruction to indicate that the
5396 // keyed load has been inlined.
5397 __ nop(PROPERTY_ACCESS_INLINED);
5398
5399 // Block the constant pool for one more instruction after leaving this
5400 // constant pool block scope to include the branch instruction ending the
5401 // deferred code.
5402 __ BlockConstPoolFor(1);
5403 }
5404}
5405
5406
5407class DeferredReferenceSetKeyedValue: public DeferredCode {
5408 public:
5409 DeferredReferenceSetKeyedValue() {
5410 set_comment("[ DeferredReferenceSetKeyedValue");
5411 }
5412
5413 virtual void Generate();
5414};
5415
5416
5417void DeferredReferenceSetKeyedValue::Generate() {
5418 Register scratch1 = VirtualFrame::scratch0();
5419 Register scratch2 = VirtualFrame::scratch1();
5420 __ DecrementCounter(&Counters::keyed_store_inline, 1, scratch1, scratch2);
5421 __ IncrementCounter(
5422 &Counters::keyed_store_inline_miss, 1, scratch1, scratch2);
5423
5424 // The rest of the instructions in the deferred code must be together.
5425 { Assembler::BlockConstPoolScope block_const_pool(masm_);
5426 // Call keyed load IC. It has receiver amd key on the stack and the value to
5427 // store in r0.
5428 Handle<Code> ic(Builtins::builtin(Builtins::KeyedStoreIC_Initialize));
5429 __ Call(ic, RelocInfo::CODE_TARGET);
5430 // The call must be followed by a nop instruction to indicate that the
5431 // keyed store has been inlined.
5432 __ nop(PROPERTY_ACCESS_INLINED);
5433
5434 // Block the constant pool for one more instruction after leaving this
5435 // constant pool block scope to include the branch instruction ending the
5436 // deferred code.
5437 __ BlockConstPoolFor(1);
5438 }
5439}
5440
5441
5442void CodeGenerator::EmitNamedLoad(Handle<String> name, bool is_contextual) {
5443 if (is_contextual || scope()->is_global_scope() || loop_nesting() == 0) {
5444 Comment cmnt(masm(), "[ Load from named Property");
5445 // Setup the name register and call load IC.
5446 frame_->CallLoadIC(name,
5447 is_contextual
5448 ? RelocInfo::CODE_TARGET_CONTEXT
5449 : RelocInfo::CODE_TARGET);
5450 } else {
5451 // Inline the in-object property case.
5452 Comment cmnt(masm(), "[ Inlined named property load");
5453
5454 // Counter will be decremented in the deferred code. Placed here to avoid
5455 // having it in the instruction stream below where patching will occur.
5456 __ IncrementCounter(&Counters::named_load_inline, 1,
5457 frame_->scratch0(), frame_->scratch1());
5458
5459 // The following instructions are the inlined load of an in-object property.
5460 // Parts of this code is patched, so the exact instructions generated needs
5461 // to be fixed. Therefore the instruction pool is blocked when generating
5462 // this code
5463
5464 // Load the receiver from the stack.
5465 frame_->SpillAllButCopyTOSToR0();
5466
5467 DeferredReferenceGetNamedValue* deferred =
5468 new DeferredReferenceGetNamedValue(name);
5469
5470#ifdef DEBUG
5471 int kInlinedNamedLoadInstructions = 7;
5472 Label check_inlined_codesize;
5473 masm_->bind(&check_inlined_codesize);
5474#endif
5475
5476 { Assembler::BlockConstPoolScope block_const_pool(masm_);
5477 // Check that the receiver is a heap object.
5478 __ tst(r0, Operand(kSmiTagMask));
5479 deferred->Branch(eq);
5480
5481 // Check the map. The null map used below is patched by the inline cache
5482 // code.
5483 __ ldr(r2, FieldMemOperand(r0, HeapObject::kMapOffset));
5484 __ mov(r3, Operand(Factory::null_value()));
5485 __ cmp(r2, r3);
5486 deferred->Branch(ne);
5487
5488 // Initially use an invalid index. The index will be patched by the
5489 // inline cache code.
5490 __ ldr(r0, MemOperand(r0, 0));
5491
5492 // Make sure that the expected number of instructions are generated.
5493 ASSERT_EQ(kInlinedNamedLoadInstructions,
5494 masm_->InstructionsGeneratedSince(&check_inlined_codesize));
5495 }
5496
5497 deferred->BindExit();
5498 }
5499}
5500
5501
5502void CodeGenerator::EmitNamedStore(Handle<String> name, bool is_contextual) {
5503#ifdef DEBUG
5504 int expected_height = frame_->height() - (is_contextual ? 1 : 2);
5505#endif
5506 frame_->CallStoreIC(name, is_contextual);
5507
5508 ASSERT_EQ(expected_height, frame_->height());
5509}
5510
5511
5512void CodeGenerator::EmitKeyedLoad() {
5513 if (loop_nesting() == 0) {
5514 Comment cmnt(masm_, "[ Load from keyed property");
5515 frame_->CallKeyedLoadIC();
5516 } else {
5517 // Inline the keyed load.
5518 Comment cmnt(masm_, "[ Inlined load from keyed property");
5519
5520 // Counter will be decremented in the deferred code. Placed here to avoid
5521 // having it in the instruction stream below where patching will occur.
5522 __ IncrementCounter(&Counters::keyed_load_inline, 1,
5523 frame_->scratch0(), frame_->scratch1());
5524
5525 // Load the receiver and key from the stack.
5526 frame_->SpillAllButCopyTOSToR1R0();
5527 Register receiver = r0;
5528 Register key = r1;
5529 VirtualFrame::SpilledScope spilled(frame_);
5530
5531 DeferredReferenceGetKeyedValue* deferred =
5532 new DeferredReferenceGetKeyedValue();
5533
5534 // Check that the receiver is a heap object.
5535 __ tst(receiver, Operand(kSmiTagMask));
5536 deferred->Branch(eq);
5537
5538 // The following instructions are the part of the inlined load keyed
5539 // property code which can be patched. Therefore the exact number of
5540 // instructions generated need to be fixed, so the constant pool is blocked
5541 // while generating this code.
5542#ifdef DEBUG
5543 int kInlinedKeyedLoadInstructions = 19;
5544 Label check_inlined_codesize;
5545 masm_->bind(&check_inlined_codesize);
5546#endif
5547 { Assembler::BlockConstPoolScope block_const_pool(masm_);
5548 Register scratch1 = VirtualFrame::scratch0();
5549 Register scratch2 = VirtualFrame::scratch1();
5550 // Check the map. The null map used below is patched by the inline cache
5551 // code.
5552 __ ldr(scratch1, FieldMemOperand(receiver, HeapObject::kMapOffset));
5553 __ mov(scratch2, Operand(Factory::null_value()));
5554 __ cmp(scratch1, scratch2);
5555 deferred->Branch(ne);
5556
5557 // Check that the key is a smi.
5558 __ tst(key, Operand(kSmiTagMask));
5559 deferred->Branch(ne);
5560
5561 // Get the elements array from the receiver and check that it
5562 // is not a dictionary.
5563 __ ldr(scratch1, FieldMemOperand(receiver, JSObject::kElementsOffset));
5564 __ ldr(scratch2, FieldMemOperand(scratch1, JSObject::kMapOffset));
5565 __ LoadRoot(ip, Heap::kFixedArrayMapRootIndex);
5566 __ cmp(scratch2, ip);
5567 deferred->Branch(ne);
5568
5569 // Check that key is within bounds. Use unsigned comparison to handle
5570 // negative keys.
5571 __ ldr(scratch2, FieldMemOperand(scratch1, FixedArray::kLengthOffset));
5572 __ cmp(scratch2, Operand(key, ASR, kSmiTagSize));
5573 deferred->Branch(ls); // Unsigned less equal.
5574
5575 // Load and check that the result is not the hole (key is a smi).
5576 __ LoadRoot(scratch2, Heap::kTheHoleValueRootIndex);
5577 __ add(scratch1,
5578 scratch1,
5579 Operand(FixedArray::kHeaderSize - kHeapObjectTag));
5580 __ ldr(r0,
5581 MemOperand(scratch1, key, LSL,
5582 kPointerSizeLog2 - (kSmiTagSize + kSmiShiftSize)));
5583 __ cmp(r0, scratch2);
5584 // This is the only branch to deferred where r0 and r1 do not contain the
5585 // receiver and key. We can't just load undefined here because we have to
5586 // check the prototype.
5587 deferred->Branch(eq);
5588
5589 // Make sure that the expected number of instructions are generated.
5590 ASSERT_EQ(kInlinedKeyedLoadInstructions,
5591 masm_->InstructionsGeneratedSince(&check_inlined_codesize));
5592 }
5593
5594 deferred->BindExit();
5595 }
5596}
5597
5598
5599void CodeGenerator::EmitKeyedStore(StaticType* key_type) {
5600 VirtualFrame::SpilledScope scope(frame_);
5601 // Generate inlined version of the keyed store if the code is in a loop
5602 // and the key is likely to be a smi.
5603 if (loop_nesting() > 0 && key_type->IsLikelySmi()) {
5604 // Inline the keyed store.
5605 Comment cmnt(masm_, "[ Inlined store to keyed property");
5606
5607 DeferredReferenceSetKeyedValue* deferred =
5608 new DeferredReferenceSetKeyedValue();
5609
5610 // Counter will be decremented in the deferred code. Placed here to avoid
5611 // having it in the instruction stream below where patching will occur.
5612 __ IncrementCounter(&Counters::keyed_store_inline, 1,
5613 frame_->scratch0(), frame_->scratch1());
5614
5615 // Check that the value is a smi. As this inlined code does not set the
5616 // write barrier it is only possible to store smi values.
5617 __ tst(r0, Operand(kSmiTagMask));
5618 deferred->Branch(ne);
5619
5620 // Load the key and receiver from the stack.
5621 __ ldr(r1, MemOperand(sp, 0));
5622 __ ldr(r2, MemOperand(sp, kPointerSize));
5623
5624 // Check that the key is a smi.
5625 __ tst(r1, Operand(kSmiTagMask));
5626 deferred->Branch(ne);
5627
5628 // Check that the receiver is a heap object.
5629 __ tst(r2, Operand(kSmiTagMask));
5630 deferred->Branch(eq);
5631
5632 // Check that the receiver is a JSArray.
5633 __ CompareObjectType(r2, r3, r3, JS_ARRAY_TYPE);
5634 deferred->Branch(ne);
5635
5636 // Check that the key is within bounds. Both the key and the length of
5637 // the JSArray are smis. Use unsigned comparison to handle negative keys.
5638 __ ldr(r3, FieldMemOperand(r2, JSArray::kLengthOffset));
5639 __ cmp(r3, r1);
5640 deferred->Branch(ls); // Unsigned less equal.
5641
5642 // The following instructions are the part of the inlined store keyed
5643 // property code which can be patched. Therefore the exact number of
5644 // instructions generated need to be fixed, so the constant pool is blocked
5645 // while generating this code.
5646#ifdef DEBUG
5647 int kInlinedKeyedStoreInstructions = 7;
5648 Label check_inlined_codesize;
5649 masm_->bind(&check_inlined_codesize);
5650#endif
5651 { Assembler::BlockConstPoolScope block_const_pool(masm_);
5652 // Get the elements array from the receiver and check that it
5653 // is not a dictionary.
5654 __ ldr(r3, FieldMemOperand(r2, JSObject::kElementsOffset));
5655 __ ldr(r4, FieldMemOperand(r3, JSObject::kMapOffset));
5656 // Read the fixed array map from the constant pool (not from the root
5657 // array) so that the value can be patched. When debugging, we patch this
5658 // comparison to always fail so that we will hit the IC call in the
5659 // deferred code which will allow the debugger to break for fast case
5660 // stores.
5661 __ mov(r5, Operand(Factory::fixed_array_map()));
5662 __ cmp(r4, r5);
5663 deferred->Branch(ne);
5664
5665 // Store the value.
5666 __ add(r3, r3, Operand(FixedArray::kHeaderSize - kHeapObjectTag));
5667 __ str(r0, MemOperand(r3, r1, LSL,
5668 kPointerSizeLog2 - (kSmiTagSize + kSmiShiftSize)));
5669
5670 // Make sure that the expected number of instructions are generated.
5671 ASSERT_EQ(kInlinedKeyedStoreInstructions,
5672 masm_->InstructionsGeneratedSince(&check_inlined_codesize));
5673 }
5674
5675 deferred->BindExit();
5676 } else {
5677 frame()->CallKeyedStoreIC();
5678 }
Leon Clarked91b9f72010-01-27 17:25:45 +00005679}
5680
5681
Steve Blocka7e24c12009-10-30 11:49:00 +00005682#ifdef DEBUG
5683bool CodeGenerator::HasValidEntryRegisters() { return true; }
5684#endif
5685
5686
5687#undef __
5688#define __ ACCESS_MASM(masm)
5689
5690
5691Handle<String> Reference::GetName() {
5692 ASSERT(type_ == NAMED);
5693 Property* property = expression_->AsProperty();
5694 if (property == NULL) {
5695 // Global variable reference treated as a named property reference.
5696 VariableProxy* proxy = expression_->AsVariableProxy();
5697 ASSERT(proxy->AsVariable() != NULL);
5698 ASSERT(proxy->AsVariable()->is_global());
5699 return proxy->name();
5700 } else {
5701 Literal* raw_name = property->key()->AsLiteral();
5702 ASSERT(raw_name != NULL);
5703 return Handle<String>(String::cast(*raw_name->handle()));
5704 }
5705}
5706
5707
Steve Blockd0582a62009-12-15 09:54:21 +00005708void Reference::GetValue() {
Steve Blocka7e24c12009-10-30 11:49:00 +00005709 ASSERT(cgen_->HasValidEntryRegisters());
5710 ASSERT(!is_illegal());
5711 ASSERT(!cgen_->has_cc());
5712 MacroAssembler* masm = cgen_->masm();
5713 Property* property = expression_->AsProperty();
5714 if (property != NULL) {
5715 cgen_->CodeForSourcePosition(property->position());
5716 }
5717
5718 switch (type_) {
5719 case SLOT: {
5720 Comment cmnt(masm, "[ Load from Slot");
5721 Slot* slot = expression_->AsVariableProxy()->AsVariable()->slot();
5722 ASSERT(slot != NULL);
Steve Block6ded16b2010-05-10 14:33:55 +01005723 cgen_->LoadFromSlotCheckForArguments(slot, NOT_INSIDE_TYPEOF);
Steve Blocka7e24c12009-10-30 11:49:00 +00005724 break;
5725 }
5726
5727 case NAMED: {
Steve Blocka7e24c12009-10-30 11:49:00 +00005728 Variable* var = expression_->AsVariableProxy()->AsVariable();
Steve Block6ded16b2010-05-10 14:33:55 +01005729 bool is_global = var != NULL;
5730 ASSERT(!is_global || var->is_global());
5731 cgen_->EmitNamedLoad(GetName(), is_global);
5732 cgen_->frame()->EmitPush(r0);
Steve Blocka7e24c12009-10-30 11:49:00 +00005733 break;
5734 }
5735
5736 case KEYED: {
Steve Blocka7e24c12009-10-30 11:49:00 +00005737 ASSERT(property != NULL);
Steve Block6ded16b2010-05-10 14:33:55 +01005738 cgen_->EmitKeyedLoad();
Leon Clarked91b9f72010-01-27 17:25:45 +00005739 cgen_->frame()->EmitPush(r0);
Steve Blocka7e24c12009-10-30 11:49:00 +00005740 break;
5741 }
5742
5743 default:
5744 UNREACHABLE();
5745 }
Leon Clarked91b9f72010-01-27 17:25:45 +00005746
5747 if (!persist_after_get_) {
5748 cgen_->UnloadReference(this);
5749 }
Steve Blocka7e24c12009-10-30 11:49:00 +00005750}
5751
5752
5753void Reference::SetValue(InitState init_state) {
5754 ASSERT(!is_illegal());
5755 ASSERT(!cgen_->has_cc());
5756 MacroAssembler* masm = cgen_->masm();
5757 VirtualFrame* frame = cgen_->frame();
5758 Property* property = expression_->AsProperty();
5759 if (property != NULL) {
5760 cgen_->CodeForSourcePosition(property->position());
5761 }
5762
5763 switch (type_) {
5764 case SLOT: {
5765 Comment cmnt(masm, "[ Store to Slot");
5766 Slot* slot = expression_->AsVariableProxy()->AsVariable()->slot();
Leon Clarkee46be812010-01-19 14:06:41 +00005767 cgen_->StoreToSlot(slot, init_state);
Steve Block6ded16b2010-05-10 14:33:55 +01005768 set_unloaded();
Steve Blocka7e24c12009-10-30 11:49:00 +00005769 break;
5770 }
5771
5772 case NAMED: {
5773 Comment cmnt(masm, "[ Store to named Property");
Steve Block6ded16b2010-05-10 14:33:55 +01005774 cgen_->EmitNamedStore(GetName(), false);
Steve Blocka7e24c12009-10-30 11:49:00 +00005775 frame->EmitPush(r0);
Andrei Popescu402d9372010-02-26 13:31:12 +00005776 set_unloaded();
Steve Blocka7e24c12009-10-30 11:49:00 +00005777 break;
5778 }
5779
5780 case KEYED: {
Steve Block6ded16b2010-05-10 14:33:55 +01005781 VirtualFrame::SpilledScope scope(frame);
Steve Blocka7e24c12009-10-30 11:49:00 +00005782 Comment cmnt(masm, "[ Store to keyed Property");
5783 Property* property = expression_->AsProperty();
5784 ASSERT(property != NULL);
5785 cgen_->CodeForSourcePosition(property->position());
5786
Steve Block6ded16b2010-05-10 14:33:55 +01005787 frame->EmitPop(r0); // Value.
5788 cgen_->EmitKeyedStore(property->key()->type());
Steve Blocka7e24c12009-10-30 11:49:00 +00005789 frame->EmitPush(r0);
Leon Clarke4515c472010-02-03 11:58:03 +00005790 cgen_->UnloadReference(this);
Steve Blocka7e24c12009-10-30 11:49:00 +00005791 break;
5792 }
5793
5794 default:
5795 UNREACHABLE();
5796 }
5797}
5798
5799
Leon Clarkee46be812010-01-19 14:06:41 +00005800void FastNewClosureStub::Generate(MacroAssembler* masm) {
Steve Block6ded16b2010-05-10 14:33:55 +01005801 // Create a new closure from the given function info in new
5802 // space. Set the context to the current context in cp.
Leon Clarkee46be812010-01-19 14:06:41 +00005803 Label gc;
5804
Steve Block6ded16b2010-05-10 14:33:55 +01005805 // Pop the function info from the stack.
Leon Clarkee46be812010-01-19 14:06:41 +00005806 __ pop(r3);
5807
5808 // Attempt to allocate new JSFunction in new space.
5809 __ AllocateInNewSpace(JSFunction::kSize / kPointerSize,
5810 r0,
5811 r1,
5812 r2,
5813 &gc,
5814 TAG_OBJECT);
5815
5816 // Compute the function map in the current global context and set that
5817 // as the map of the allocated object.
5818 __ ldr(r2, MemOperand(cp, Context::SlotOffset(Context::GLOBAL_INDEX)));
5819 __ ldr(r2, FieldMemOperand(r2, GlobalObject::kGlobalContextOffset));
5820 __ ldr(r2, MemOperand(r2, Context::SlotOffset(Context::FUNCTION_MAP_INDEX)));
5821 __ str(r2, FieldMemOperand(r0, HeapObject::kMapOffset));
5822
Steve Block6ded16b2010-05-10 14:33:55 +01005823 // Initialize the rest of the function. We don't have to update the
5824 // write barrier because the allocated object is in new space.
5825 __ LoadRoot(r1, Heap::kEmptyFixedArrayRootIndex);
5826 __ LoadRoot(r2, Heap::kTheHoleValueRootIndex);
5827 __ str(r1, FieldMemOperand(r0, JSObject::kPropertiesOffset));
5828 __ str(r1, FieldMemOperand(r0, JSObject::kElementsOffset));
5829 __ str(r2, FieldMemOperand(r0, JSFunction::kPrototypeOrInitialMapOffset));
5830 __ str(r3, FieldMemOperand(r0, JSFunction::kSharedFunctionInfoOffset));
5831 __ str(cp, FieldMemOperand(r0, JSFunction::kContextOffset));
5832 __ str(r1, FieldMemOperand(r0, JSFunction::kLiteralsOffset));
Leon Clarkee46be812010-01-19 14:06:41 +00005833
Steve Block6ded16b2010-05-10 14:33:55 +01005834 // Return result. The argument function info has been popped already.
Leon Clarkee46be812010-01-19 14:06:41 +00005835 __ Ret();
5836
5837 // Create a new closure through the slower runtime call.
5838 __ bind(&gc);
Steve Block6ded16b2010-05-10 14:33:55 +01005839 __ Push(cp, r3);
5840 __ TailCallRuntime(Runtime::kNewClosure, 2, 1);
Leon Clarkee46be812010-01-19 14:06:41 +00005841}
5842
5843
5844void FastNewContextStub::Generate(MacroAssembler* masm) {
5845 // Try to allocate the context in new space.
5846 Label gc;
5847 int length = slots_ + Context::MIN_CONTEXT_SLOTS;
5848
5849 // Attempt to allocate the context in new space.
5850 __ AllocateInNewSpace(length + (FixedArray::kHeaderSize / kPointerSize),
5851 r0,
5852 r1,
5853 r2,
5854 &gc,
5855 TAG_OBJECT);
5856
5857 // Load the function from the stack.
Andrei Popescu402d9372010-02-26 13:31:12 +00005858 __ ldr(r3, MemOperand(sp, 0));
Leon Clarkee46be812010-01-19 14:06:41 +00005859
5860 // Setup the object header.
5861 __ LoadRoot(r2, Heap::kContextMapRootIndex);
5862 __ str(r2, FieldMemOperand(r0, HeapObject::kMapOffset));
5863 __ mov(r2, Operand(length));
5864 __ str(r2, FieldMemOperand(r0, Array::kLengthOffset));
5865
5866 // Setup the fixed slots.
5867 __ mov(r1, Operand(Smi::FromInt(0)));
5868 __ str(r3, MemOperand(r0, Context::SlotOffset(Context::CLOSURE_INDEX)));
5869 __ str(r0, MemOperand(r0, Context::SlotOffset(Context::FCONTEXT_INDEX)));
5870 __ str(r1, MemOperand(r0, Context::SlotOffset(Context::PREVIOUS_INDEX)));
5871 __ str(r1, MemOperand(r0, Context::SlotOffset(Context::EXTENSION_INDEX)));
5872
5873 // Copy the global object from the surrounding context.
5874 __ ldr(r1, MemOperand(cp, Context::SlotOffset(Context::GLOBAL_INDEX)));
5875 __ str(r1, MemOperand(r0, Context::SlotOffset(Context::GLOBAL_INDEX)));
5876
5877 // Initialize the rest of the slots to undefined.
5878 __ LoadRoot(r1, Heap::kUndefinedValueRootIndex);
5879 for (int i = Context::MIN_CONTEXT_SLOTS; i < length; i++) {
5880 __ str(r1, MemOperand(r0, Context::SlotOffset(i)));
5881 }
5882
5883 // Remove the on-stack argument and return.
5884 __ mov(cp, r0);
5885 __ pop();
5886 __ Ret();
5887
5888 // Need to collect. Call into runtime system.
5889 __ bind(&gc);
Steve Block6ded16b2010-05-10 14:33:55 +01005890 __ TailCallRuntime(Runtime::kNewContext, 1, 1);
Leon Clarkee46be812010-01-19 14:06:41 +00005891}
5892
5893
Andrei Popescu402d9372010-02-26 13:31:12 +00005894void FastCloneShallowArrayStub::Generate(MacroAssembler* masm) {
5895 // Stack layout on entry:
5896 //
5897 // [sp]: constant elements.
5898 // [sp + kPointerSize]: literal index.
5899 // [sp + (2 * kPointerSize)]: literals array.
5900
5901 // All sizes here are multiples of kPointerSize.
5902 int elements_size = (length_ > 0) ? FixedArray::SizeFor(length_) : 0;
5903 int size = JSArray::kSize + elements_size;
5904
5905 // Load boilerplate object into r3 and check if we need to create a
5906 // boilerplate.
5907 Label slow_case;
5908 __ ldr(r3, MemOperand(sp, 2 * kPointerSize));
5909 __ ldr(r0, MemOperand(sp, 1 * kPointerSize));
5910 __ add(r3, r3, Operand(FixedArray::kHeaderSize - kHeapObjectTag));
5911 __ ldr(r3, MemOperand(r3, r0, LSL, kPointerSizeLog2 - kSmiTagSize));
5912 __ LoadRoot(ip, Heap::kUndefinedValueRootIndex);
5913 __ cmp(r3, ip);
5914 __ b(eq, &slow_case);
5915
5916 // Allocate both the JS array and the elements array in one big
5917 // allocation. This avoids multiple limit checks.
5918 __ AllocateInNewSpace(size / kPointerSize,
5919 r0,
5920 r1,
5921 r2,
5922 &slow_case,
5923 TAG_OBJECT);
5924
5925 // Copy the JS array part.
5926 for (int i = 0; i < JSArray::kSize; i += kPointerSize) {
5927 if ((i != JSArray::kElementsOffset) || (length_ == 0)) {
5928 __ ldr(r1, FieldMemOperand(r3, i));
5929 __ str(r1, FieldMemOperand(r0, i));
5930 }
5931 }
5932
5933 if (length_ > 0) {
5934 // Get hold of the elements array of the boilerplate and setup the
5935 // elements pointer in the resulting object.
5936 __ ldr(r3, FieldMemOperand(r3, JSArray::kElementsOffset));
5937 __ add(r2, r0, Operand(JSArray::kSize));
5938 __ str(r2, FieldMemOperand(r0, JSArray::kElementsOffset));
5939
5940 // Copy the elements array.
5941 for (int i = 0; i < elements_size; i += kPointerSize) {
5942 __ ldr(r1, FieldMemOperand(r3, i));
5943 __ str(r1, FieldMemOperand(r2, i));
5944 }
5945 }
5946
5947 // Return and remove the on-stack parameters.
5948 __ add(sp, sp, Operand(3 * kPointerSize));
5949 __ Ret();
5950
5951 __ bind(&slow_case);
Steve Block6ded16b2010-05-10 14:33:55 +01005952 __ TailCallRuntime(Runtime::kCreateArrayLiteralShallow, 3, 1);
Steve Blocka7e24c12009-10-30 11:49:00 +00005953}
5954
5955
5956// Takes a Smi and converts to an IEEE 64 bit floating point value in two
5957// registers. The format is 1 sign bit, 11 exponent bits (biased 1023) and
5958// 52 fraction bits (20 in the first word, 32 in the second). Zeros is a
5959// scratch register. Destroys the source register. No GC occurs during this
5960// stub so you don't have to set up the frame.
5961class ConvertToDoubleStub : public CodeStub {
5962 public:
5963 ConvertToDoubleStub(Register result_reg_1,
5964 Register result_reg_2,
5965 Register source_reg,
5966 Register scratch_reg)
5967 : result1_(result_reg_1),
5968 result2_(result_reg_2),
5969 source_(source_reg),
5970 zeros_(scratch_reg) { }
5971
5972 private:
5973 Register result1_;
5974 Register result2_;
5975 Register source_;
5976 Register zeros_;
5977
5978 // Minor key encoding in 16 bits.
5979 class ModeBits: public BitField<OverwriteMode, 0, 2> {};
5980 class OpBits: public BitField<Token::Value, 2, 14> {};
5981
5982 Major MajorKey() { return ConvertToDouble; }
5983 int MinorKey() {
5984 // Encode the parameters in a unique 16 bit value.
5985 return result1_.code() +
5986 (result2_.code() << 4) +
5987 (source_.code() << 8) +
5988 (zeros_.code() << 12);
5989 }
5990
5991 void Generate(MacroAssembler* masm);
5992
5993 const char* GetName() { return "ConvertToDoubleStub"; }
5994
5995#ifdef DEBUG
5996 void Print() { PrintF("ConvertToDoubleStub\n"); }
5997#endif
5998};
5999
6000
6001void ConvertToDoubleStub::Generate(MacroAssembler* masm) {
6002#ifndef BIG_ENDIAN_FLOATING_POINT
6003 Register exponent = result1_;
6004 Register mantissa = result2_;
6005#else
6006 Register exponent = result2_;
6007 Register mantissa = result1_;
6008#endif
6009 Label not_special;
6010 // Convert from Smi to integer.
6011 __ mov(source_, Operand(source_, ASR, kSmiTagSize));
6012 // Move sign bit from source to destination. This works because the sign bit
6013 // in the exponent word of the double has the same position and polarity as
6014 // the 2's complement sign bit in a Smi.
6015 ASSERT(HeapNumber::kSignMask == 0x80000000u);
6016 __ and_(exponent, source_, Operand(HeapNumber::kSignMask), SetCC);
6017 // Subtract from 0 if source was negative.
6018 __ rsb(source_, source_, Operand(0), LeaveCC, ne);
Steve Block6ded16b2010-05-10 14:33:55 +01006019
6020 // We have -1, 0 or 1, which we treat specially. Register source_ contains
6021 // absolute value: it is either equal to 1 (special case of -1 and 1),
6022 // greater than 1 (not a special case) or less than 1 (special case of 0).
Steve Blocka7e24c12009-10-30 11:49:00 +00006023 __ cmp(source_, Operand(1));
6024 __ b(gt, &not_special);
6025
Steve Blocka7e24c12009-10-30 11:49:00 +00006026 // For 1 or -1 we need to or in the 0 exponent (biased to 1023).
6027 static const uint32_t exponent_word_for_1 =
6028 HeapNumber::kExponentBias << HeapNumber::kExponentShift;
Steve Block6ded16b2010-05-10 14:33:55 +01006029 __ orr(exponent, exponent, Operand(exponent_word_for_1), LeaveCC, eq);
Steve Blocka7e24c12009-10-30 11:49:00 +00006030 // 1, 0 and -1 all have 0 for the second word.
6031 __ mov(mantissa, Operand(0));
6032 __ Ret();
6033
6034 __ bind(&not_special);
Steve Block6ded16b2010-05-10 14:33:55 +01006035 // Count leading zeros. Uses mantissa for a scratch register on pre-ARM5.
Steve Blocka7e24c12009-10-30 11:49:00 +00006036 // Gets the wrong answer for 0, but we already checked for that case above.
Steve Block6ded16b2010-05-10 14:33:55 +01006037 __ CountLeadingZeros(source_, mantissa, zeros_);
Steve Blocka7e24c12009-10-30 11:49:00 +00006038 // Compute exponent and or it into the exponent register.
Steve Block6ded16b2010-05-10 14:33:55 +01006039 // We use mantissa as a scratch register here.
Steve Blocka7e24c12009-10-30 11:49:00 +00006040 __ rsb(mantissa, zeros_, Operand(31 + HeapNumber::kExponentBias));
6041 __ orr(exponent,
6042 exponent,
6043 Operand(mantissa, LSL, HeapNumber::kExponentShift));
6044 // Shift up the source chopping the top bit off.
6045 __ add(zeros_, zeros_, Operand(1));
6046 // This wouldn't work for 1.0 or -1.0 as the shift would be 32 which means 0.
6047 __ mov(source_, Operand(source_, LSL, zeros_));
6048 // Compute lower part of fraction (last 12 bits).
6049 __ mov(mantissa, Operand(source_, LSL, HeapNumber::kMantissaBitsInTopWord));
6050 // And the top (top 20 bits).
6051 __ orr(exponent,
6052 exponent,
6053 Operand(source_, LSR, 32 - HeapNumber::kMantissaBitsInTopWord));
6054 __ Ret();
6055}
6056
6057
Steve Blocka7e24c12009-10-30 11:49:00 +00006058// See comment for class.
Steve Blockd0582a62009-12-15 09:54:21 +00006059void WriteInt32ToHeapNumberStub::Generate(MacroAssembler* masm) {
Steve Blocka7e24c12009-10-30 11:49:00 +00006060 Label max_negative_int;
6061 // the_int_ has the answer which is a signed int32 but not a Smi.
6062 // We test for the special value that has a different exponent. This test
6063 // has the neat side effect of setting the flags according to the sign.
6064 ASSERT(HeapNumber::kSignMask == 0x80000000u);
6065 __ cmp(the_int_, Operand(0x80000000u));
6066 __ b(eq, &max_negative_int);
6067 // Set up the correct exponent in scratch_. All non-Smi int32s have the same.
6068 // A non-Smi integer is 1.xxx * 2^30 so the exponent is 30 (biased).
6069 uint32_t non_smi_exponent =
6070 (HeapNumber::kExponentBias + 30) << HeapNumber::kExponentShift;
6071 __ mov(scratch_, Operand(non_smi_exponent));
6072 // Set the sign bit in scratch_ if the value was negative.
6073 __ orr(scratch_, scratch_, Operand(HeapNumber::kSignMask), LeaveCC, cs);
6074 // Subtract from 0 if the value was negative.
6075 __ rsb(the_int_, the_int_, Operand(0), LeaveCC, cs);
6076 // We should be masking the implict first digit of the mantissa away here,
6077 // but it just ends up combining harmlessly with the last digit of the
6078 // exponent that happens to be 1. The sign bit is 0 so we shift 10 to get
6079 // the most significant 1 to hit the last bit of the 12 bit sign and exponent.
6080 ASSERT(((1 << HeapNumber::kExponentShift) & non_smi_exponent) != 0);
6081 const int shift_distance = HeapNumber::kNonMantissaBitsInTopWord - 2;
6082 __ orr(scratch_, scratch_, Operand(the_int_, LSR, shift_distance));
6083 __ str(scratch_, FieldMemOperand(the_heap_number_,
6084 HeapNumber::kExponentOffset));
6085 __ mov(scratch_, Operand(the_int_, LSL, 32 - shift_distance));
6086 __ str(scratch_, FieldMemOperand(the_heap_number_,
6087 HeapNumber::kMantissaOffset));
6088 __ Ret();
6089
6090 __ bind(&max_negative_int);
6091 // The max negative int32 is stored as a positive number in the mantissa of
6092 // a double because it uses a sign bit instead of using two's complement.
6093 // The actual mantissa bits stored are all 0 because the implicit most
6094 // significant 1 bit is not stored.
6095 non_smi_exponent += 1 << HeapNumber::kExponentShift;
6096 __ mov(ip, Operand(HeapNumber::kSignMask | non_smi_exponent));
6097 __ str(ip, FieldMemOperand(the_heap_number_, HeapNumber::kExponentOffset));
6098 __ mov(ip, Operand(0));
6099 __ str(ip, FieldMemOperand(the_heap_number_, HeapNumber::kMantissaOffset));
6100 __ Ret();
6101}
6102
6103
6104// Handle the case where the lhs and rhs are the same object.
6105// Equality is almost reflexive (everything but NaN), so this is a test
6106// for "identity and not NaN".
6107static void EmitIdenticalObjectComparison(MacroAssembler* masm,
6108 Label* slow,
Leon Clarkee46be812010-01-19 14:06:41 +00006109 Condition cc,
6110 bool never_nan_nan) {
Steve Blocka7e24c12009-10-30 11:49:00 +00006111 Label not_identical;
Leon Clarkee46be812010-01-19 14:06:41 +00006112 Label heap_number, return_equal;
6113 Register exp_mask_reg = r5;
Steve Block6ded16b2010-05-10 14:33:55 +01006114 __ cmp(r0, r1);
Steve Blocka7e24c12009-10-30 11:49:00 +00006115 __ b(ne, &not_identical);
6116
Leon Clarkee46be812010-01-19 14:06:41 +00006117 // The two objects are identical. If we know that one of them isn't NaN then
6118 // we now know they test equal.
6119 if (cc != eq || !never_nan_nan) {
6120 __ mov(exp_mask_reg, Operand(HeapNumber::kExponentMask));
Steve Blocka7e24c12009-10-30 11:49:00 +00006121
Leon Clarkee46be812010-01-19 14:06:41 +00006122 // Test for NaN. Sadly, we can't just compare to Factory::nan_value(),
6123 // so we do the second best thing - test it ourselves.
6124 // They are both equal and they are not both Smis so both of them are not
6125 // Smis. If it's not a heap number, then return equal.
6126 if (cc == lt || cc == gt) {
6127 __ CompareObjectType(r0, r4, r4, FIRST_JS_OBJECT_TYPE);
Steve Blocka7e24c12009-10-30 11:49:00 +00006128 __ b(ge, slow);
Leon Clarkee46be812010-01-19 14:06:41 +00006129 } else {
6130 __ CompareObjectType(r0, r4, r4, HEAP_NUMBER_TYPE);
6131 __ b(eq, &heap_number);
6132 // Comparing JS objects with <=, >= is complicated.
6133 if (cc != eq) {
6134 __ cmp(r4, Operand(FIRST_JS_OBJECT_TYPE));
6135 __ b(ge, slow);
6136 // Normally here we fall through to return_equal, but undefined is
6137 // special: (undefined == undefined) == true, but
6138 // (undefined <= undefined) == false! See ECMAScript 11.8.5.
6139 if (cc == le || cc == ge) {
6140 __ cmp(r4, Operand(ODDBALL_TYPE));
6141 __ b(ne, &return_equal);
6142 __ LoadRoot(r2, Heap::kUndefinedValueRootIndex);
Steve Block6ded16b2010-05-10 14:33:55 +01006143 __ cmp(r0, r2);
Leon Clarkee46be812010-01-19 14:06:41 +00006144 __ b(ne, &return_equal);
6145 if (cc == le) {
6146 // undefined <= undefined should fail.
6147 __ mov(r0, Operand(GREATER));
6148 } else {
6149 // undefined >= undefined should fail.
6150 __ mov(r0, Operand(LESS));
6151 }
6152 __ mov(pc, Operand(lr)); // Return.
Steve Blockd0582a62009-12-15 09:54:21 +00006153 }
Steve Blockd0582a62009-12-15 09:54:21 +00006154 }
Steve Blocka7e24c12009-10-30 11:49:00 +00006155 }
6156 }
Leon Clarkee46be812010-01-19 14:06:41 +00006157
Steve Blocka7e24c12009-10-30 11:49:00 +00006158 __ bind(&return_equal);
6159 if (cc == lt) {
6160 __ mov(r0, Operand(GREATER)); // Things aren't less than themselves.
6161 } else if (cc == gt) {
6162 __ mov(r0, Operand(LESS)); // Things aren't greater than themselves.
6163 } else {
Leon Clarkee46be812010-01-19 14:06:41 +00006164 __ mov(r0, Operand(EQUAL)); // Things are <=, >=, ==, === themselves.
Steve Blocka7e24c12009-10-30 11:49:00 +00006165 }
6166 __ mov(pc, Operand(lr)); // Return.
6167
Leon Clarkee46be812010-01-19 14:06:41 +00006168 if (cc != eq || !never_nan_nan) {
6169 // For less and greater we don't have to check for NaN since the result of
6170 // x < x is false regardless. For the others here is some code to check
6171 // for NaN.
6172 if (cc != lt && cc != gt) {
6173 __ bind(&heap_number);
6174 // It is a heap number, so return non-equal if it's NaN and equal if it's
6175 // not NaN.
Steve Blocka7e24c12009-10-30 11:49:00 +00006176
Leon Clarkee46be812010-01-19 14:06:41 +00006177 // The representation of NaN values has all exponent bits (52..62) set,
6178 // and not all mantissa bits (0..51) clear.
6179 // Read top bits of double representation (second word of value).
6180 __ ldr(r2, FieldMemOperand(r0, HeapNumber::kExponentOffset));
6181 // Test that exponent bits are all set.
6182 __ and_(r3, r2, Operand(exp_mask_reg));
6183 __ cmp(r3, Operand(exp_mask_reg));
6184 __ b(ne, &return_equal);
6185
6186 // Shift out flag and all exponent bits, retaining only mantissa.
6187 __ mov(r2, Operand(r2, LSL, HeapNumber::kNonMantissaBitsInTopWord));
6188 // Or with all low-bits of mantissa.
6189 __ ldr(r3, FieldMemOperand(r0, HeapNumber::kMantissaOffset));
6190 __ orr(r0, r3, Operand(r2), SetCC);
6191 // For equal we already have the right value in r0: Return zero (equal)
6192 // if all bits in mantissa are zero (it's an Infinity) and non-zero if
6193 // not (it's a NaN). For <= and >= we need to load r0 with the failing
6194 // value if it's a NaN.
6195 if (cc != eq) {
6196 // All-zero means Infinity means equal.
6197 __ mov(pc, Operand(lr), LeaveCC, eq); // Return equal
6198 if (cc == le) {
6199 __ mov(r0, Operand(GREATER)); // NaN <= NaN should fail.
6200 } else {
6201 __ mov(r0, Operand(LESS)); // NaN >= NaN should fail.
6202 }
Steve Blocka7e24c12009-10-30 11:49:00 +00006203 }
Leon Clarkee46be812010-01-19 14:06:41 +00006204 __ mov(pc, Operand(lr)); // Return.
Steve Blocka7e24c12009-10-30 11:49:00 +00006205 }
Leon Clarkee46be812010-01-19 14:06:41 +00006206 // No fall through here.
Steve Blocka7e24c12009-10-30 11:49:00 +00006207 }
Steve Blocka7e24c12009-10-30 11:49:00 +00006208
6209 __ bind(&not_identical);
6210}
6211
6212
6213// See comment at call site.
6214static void EmitSmiNonsmiComparison(MacroAssembler* masm,
Leon Clarkee46be812010-01-19 14:06:41 +00006215 Label* lhs_not_nan,
Steve Blocka7e24c12009-10-30 11:49:00 +00006216 Label* slow,
6217 bool strict) {
Leon Clarked91b9f72010-01-27 17:25:45 +00006218 Label rhs_is_smi;
Steve Blocka7e24c12009-10-30 11:49:00 +00006219 __ tst(r0, Operand(kSmiTagMask));
Leon Clarked91b9f72010-01-27 17:25:45 +00006220 __ b(eq, &rhs_is_smi);
Steve Blocka7e24c12009-10-30 11:49:00 +00006221
Leon Clarked91b9f72010-01-27 17:25:45 +00006222 // Lhs is a Smi. Check whether the rhs is a heap number.
Steve Blocka7e24c12009-10-30 11:49:00 +00006223 __ CompareObjectType(r0, r4, r4, HEAP_NUMBER_TYPE);
6224 if (strict) {
Leon Clarked91b9f72010-01-27 17:25:45 +00006225 // If rhs is not a number and lhs is a Smi then strict equality cannot
Steve Blocka7e24c12009-10-30 11:49:00 +00006226 // succeed. Return non-equal (r0 is already not zero)
6227 __ mov(pc, Operand(lr), LeaveCC, ne); // Return.
6228 } else {
6229 // Smi compared non-strictly with a non-Smi non-heap-number. Call
6230 // the runtime.
6231 __ b(ne, slow);
6232 }
6233
Leon Clarked91b9f72010-01-27 17:25:45 +00006234 // Lhs (r1) is a smi, rhs (r0) is a number.
Steve Blockd0582a62009-12-15 09:54:21 +00006235 if (CpuFeatures::IsSupported(VFP3)) {
Leon Clarked91b9f72010-01-27 17:25:45 +00006236 // Convert lhs to a double in d7 .
Steve Blockd0582a62009-12-15 09:54:21 +00006237 CpuFeatures::Scope scope(VFP3);
Leon Clarked91b9f72010-01-27 17:25:45 +00006238 __ mov(r7, Operand(r1, ASR, kSmiTagSize));
6239 __ vmov(s15, r7);
Steve Block6ded16b2010-05-10 14:33:55 +01006240 __ vcvt_f64_s32(d7, s15);
Leon Clarked91b9f72010-01-27 17:25:45 +00006241 // Load the double from rhs, tagged HeapNumber r0, to d6.
6242 __ sub(r7, r0, Operand(kHeapObjectTag));
6243 __ vldr(d6, r7, HeapNumber::kValueOffset);
Steve Blockd0582a62009-12-15 09:54:21 +00006244 } else {
Leon Clarked91b9f72010-01-27 17:25:45 +00006245 __ push(lr);
6246 // Convert lhs to a double in r2, r3.
Steve Blockd0582a62009-12-15 09:54:21 +00006247 __ mov(r7, Operand(r1));
6248 ConvertToDoubleStub stub1(r3, r2, r7, r6);
6249 __ Call(stub1.GetCode(), RelocInfo::CODE_TARGET);
Leon Clarked91b9f72010-01-27 17:25:45 +00006250 // Load rhs to a double in r0, r1.
6251 __ ldr(r1, FieldMemOperand(r0, HeapNumber::kValueOffset + kPointerSize));
6252 __ ldr(r0, FieldMemOperand(r0, HeapNumber::kValueOffset));
6253 __ pop(lr);
Steve Blockd0582a62009-12-15 09:54:21 +00006254 }
6255
Steve Blocka7e24c12009-10-30 11:49:00 +00006256 // We now have both loaded as doubles but we can skip the lhs nan check
Leon Clarked91b9f72010-01-27 17:25:45 +00006257 // since it's a smi.
Leon Clarkee46be812010-01-19 14:06:41 +00006258 __ jmp(lhs_not_nan);
Steve Blocka7e24c12009-10-30 11:49:00 +00006259
Leon Clarked91b9f72010-01-27 17:25:45 +00006260 __ bind(&rhs_is_smi);
6261 // Rhs is a smi. Check whether the non-smi lhs is a heap number.
Steve Blocka7e24c12009-10-30 11:49:00 +00006262 __ CompareObjectType(r1, r4, r4, HEAP_NUMBER_TYPE);
6263 if (strict) {
Leon Clarked91b9f72010-01-27 17:25:45 +00006264 // If lhs is not a number and rhs is a smi then strict equality cannot
Steve Blocka7e24c12009-10-30 11:49:00 +00006265 // succeed. Return non-equal.
6266 __ mov(r0, Operand(1), LeaveCC, ne); // Non-zero indicates not equal.
6267 __ mov(pc, Operand(lr), LeaveCC, ne); // Return.
6268 } else {
Leon Clarked91b9f72010-01-27 17:25:45 +00006269 // Smi compared non-strictly with a non-smi non-heap-number. Call
Steve Blocka7e24c12009-10-30 11:49:00 +00006270 // the runtime.
6271 __ b(ne, slow);
6272 }
6273
Leon Clarked91b9f72010-01-27 17:25:45 +00006274 // Rhs (r0) is a smi, lhs (r1) is a heap number.
Steve Blockd0582a62009-12-15 09:54:21 +00006275 if (CpuFeatures::IsSupported(VFP3)) {
Leon Clarked91b9f72010-01-27 17:25:45 +00006276 // Convert rhs to a double in d6 .
Steve Blockd0582a62009-12-15 09:54:21 +00006277 CpuFeatures::Scope scope(VFP3);
Leon Clarked91b9f72010-01-27 17:25:45 +00006278 // Load the double from lhs, tagged HeapNumber r1, to d7.
6279 __ sub(r7, r1, Operand(kHeapObjectTag));
6280 __ vldr(d7, r7, HeapNumber::kValueOffset);
6281 __ mov(r7, Operand(r0, ASR, kSmiTagSize));
6282 __ vmov(s13, r7);
Steve Block6ded16b2010-05-10 14:33:55 +01006283 __ vcvt_f64_s32(d6, s13);
Steve Blockd0582a62009-12-15 09:54:21 +00006284 } else {
Leon Clarked91b9f72010-01-27 17:25:45 +00006285 __ push(lr);
6286 // Load lhs to a double in r2, r3.
6287 __ ldr(r3, FieldMemOperand(r1, HeapNumber::kValueOffset + kPointerSize));
6288 __ ldr(r2, FieldMemOperand(r1, HeapNumber::kValueOffset));
6289 // Convert rhs to a double in r0, r1.
Steve Blockd0582a62009-12-15 09:54:21 +00006290 __ mov(r7, Operand(r0));
6291 ConvertToDoubleStub stub2(r1, r0, r7, r6);
6292 __ Call(stub2.GetCode(), RelocInfo::CODE_TARGET);
Leon Clarked91b9f72010-01-27 17:25:45 +00006293 __ pop(lr);
Steve Blockd0582a62009-12-15 09:54:21 +00006294 }
Steve Blocka7e24c12009-10-30 11:49:00 +00006295 // Fall through to both_loaded_as_doubles.
6296}
6297
6298
Leon Clarkee46be812010-01-19 14:06:41 +00006299void EmitNanCheck(MacroAssembler* masm, Label* lhs_not_nan, Condition cc) {
Steve Blocka7e24c12009-10-30 11:49:00 +00006300 bool exp_first = (HeapNumber::kExponentOffset == HeapNumber::kValueOffset);
Leon Clarkee46be812010-01-19 14:06:41 +00006301 Register rhs_exponent = exp_first ? r0 : r1;
6302 Register lhs_exponent = exp_first ? r2 : r3;
6303 Register rhs_mantissa = exp_first ? r1 : r0;
6304 Register lhs_mantissa = exp_first ? r3 : r2;
Steve Blocka7e24c12009-10-30 11:49:00 +00006305 Label one_is_nan, neither_is_nan;
Leon Clarkee46be812010-01-19 14:06:41 +00006306 Label lhs_not_nan_exp_mask_is_loaded;
Steve Blocka7e24c12009-10-30 11:49:00 +00006307
6308 Register exp_mask_reg = r5;
6309
6310 __ mov(exp_mask_reg, Operand(HeapNumber::kExponentMask));
Steve Blocka7e24c12009-10-30 11:49:00 +00006311 __ and_(r4, lhs_exponent, Operand(exp_mask_reg));
6312 __ cmp(r4, Operand(exp_mask_reg));
Leon Clarkee46be812010-01-19 14:06:41 +00006313 __ b(ne, &lhs_not_nan_exp_mask_is_loaded);
Steve Blocka7e24c12009-10-30 11:49:00 +00006314 __ mov(r4,
6315 Operand(lhs_exponent, LSL, HeapNumber::kNonMantissaBitsInTopWord),
6316 SetCC);
6317 __ b(ne, &one_is_nan);
6318 __ cmp(lhs_mantissa, Operand(0));
Leon Clarkee46be812010-01-19 14:06:41 +00006319 __ b(ne, &one_is_nan);
6320
6321 __ bind(lhs_not_nan);
6322 __ mov(exp_mask_reg, Operand(HeapNumber::kExponentMask));
6323 __ bind(&lhs_not_nan_exp_mask_is_loaded);
6324 __ and_(r4, rhs_exponent, Operand(exp_mask_reg));
6325 __ cmp(r4, Operand(exp_mask_reg));
6326 __ b(ne, &neither_is_nan);
6327 __ mov(r4,
6328 Operand(rhs_exponent, LSL, HeapNumber::kNonMantissaBitsInTopWord),
6329 SetCC);
6330 __ b(ne, &one_is_nan);
6331 __ cmp(rhs_mantissa, Operand(0));
Steve Blocka7e24c12009-10-30 11:49:00 +00006332 __ b(eq, &neither_is_nan);
6333
6334 __ bind(&one_is_nan);
6335 // NaN comparisons always fail.
6336 // Load whatever we need in r0 to make the comparison fail.
6337 if (cc == lt || cc == le) {
6338 __ mov(r0, Operand(GREATER));
6339 } else {
6340 __ mov(r0, Operand(LESS));
6341 }
6342 __ mov(pc, Operand(lr)); // Return.
6343
6344 __ bind(&neither_is_nan);
6345}
6346
6347
6348// See comment at call site.
6349static void EmitTwoNonNanDoubleComparison(MacroAssembler* masm, Condition cc) {
6350 bool exp_first = (HeapNumber::kExponentOffset == HeapNumber::kValueOffset);
Leon Clarkee46be812010-01-19 14:06:41 +00006351 Register rhs_exponent = exp_first ? r0 : r1;
6352 Register lhs_exponent = exp_first ? r2 : r3;
6353 Register rhs_mantissa = exp_first ? r1 : r0;
6354 Register lhs_mantissa = exp_first ? r3 : r2;
Steve Blocka7e24c12009-10-30 11:49:00 +00006355
6356 // r0, r1, r2, r3 have the two doubles. Neither is a NaN.
6357 if (cc == eq) {
6358 // Doubles are not equal unless they have the same bit pattern.
6359 // Exception: 0 and -0.
Leon Clarkee46be812010-01-19 14:06:41 +00006360 __ cmp(rhs_mantissa, Operand(lhs_mantissa));
6361 __ orr(r0, rhs_mantissa, Operand(lhs_mantissa), LeaveCC, ne);
Steve Blocka7e24c12009-10-30 11:49:00 +00006362 // Return non-zero if the numbers are unequal.
6363 __ mov(pc, Operand(lr), LeaveCC, ne);
6364
Leon Clarkee46be812010-01-19 14:06:41 +00006365 __ sub(r0, rhs_exponent, Operand(lhs_exponent), SetCC);
Steve Blocka7e24c12009-10-30 11:49:00 +00006366 // If exponents are equal then return 0.
6367 __ mov(pc, Operand(lr), LeaveCC, eq);
6368
6369 // Exponents are unequal. The only way we can return that the numbers
6370 // are equal is if one is -0 and the other is 0. We already dealt
6371 // with the case where both are -0 or both are 0.
6372 // We start by seeing if the mantissas (that are equal) or the bottom
6373 // 31 bits of the rhs exponent are non-zero. If so we return not
6374 // equal.
Leon Clarkee46be812010-01-19 14:06:41 +00006375 __ orr(r4, lhs_mantissa, Operand(lhs_exponent, LSL, kSmiTagSize), SetCC);
Steve Blocka7e24c12009-10-30 11:49:00 +00006376 __ mov(r0, Operand(r4), LeaveCC, ne);
6377 __ mov(pc, Operand(lr), LeaveCC, ne); // Return conditionally.
6378 // Now they are equal if and only if the lhs exponent is zero in its
6379 // low 31 bits.
Leon Clarkee46be812010-01-19 14:06:41 +00006380 __ mov(r0, Operand(rhs_exponent, LSL, kSmiTagSize));
Steve Blocka7e24c12009-10-30 11:49:00 +00006381 __ mov(pc, Operand(lr));
6382 } else {
6383 // Call a native function to do a comparison between two non-NaNs.
6384 // Call C routine that may not cause GC or other trouble.
Steve Block6ded16b2010-05-10 14:33:55 +01006385 __ push(lr);
6386 __ PrepareCallCFunction(4, r5); // Two doubles count as 4 arguments.
6387 __ CallCFunction(ExternalReference::compare_doubles(), 4);
6388 __ pop(pc); // Return.
Steve Blocka7e24c12009-10-30 11:49:00 +00006389 }
6390}
6391
6392
6393// See comment at call site.
6394static void EmitStrictTwoHeapObjectCompare(MacroAssembler* masm) {
6395 // If either operand is a JSObject or an oddball value, then they are
6396 // not equal since their pointers are different.
6397 // There is no test for undetectability in strict equality.
6398 ASSERT(LAST_TYPE == JS_FUNCTION_TYPE);
6399 Label first_non_object;
6400 // Get the type of the first operand into r2 and compare it with
6401 // FIRST_JS_OBJECT_TYPE.
6402 __ CompareObjectType(r0, r2, r2, FIRST_JS_OBJECT_TYPE);
6403 __ b(lt, &first_non_object);
6404
6405 // Return non-zero (r0 is not zero)
6406 Label return_not_equal;
6407 __ bind(&return_not_equal);
6408 __ mov(pc, Operand(lr)); // Return.
6409
6410 __ bind(&first_non_object);
6411 // Check for oddballs: true, false, null, undefined.
6412 __ cmp(r2, Operand(ODDBALL_TYPE));
6413 __ b(eq, &return_not_equal);
6414
6415 __ CompareObjectType(r1, r3, r3, FIRST_JS_OBJECT_TYPE);
6416 __ b(ge, &return_not_equal);
6417
6418 // Check for oddballs: true, false, null, undefined.
6419 __ cmp(r3, Operand(ODDBALL_TYPE));
6420 __ b(eq, &return_not_equal);
Leon Clarkee46be812010-01-19 14:06:41 +00006421
6422 // Now that we have the types we might as well check for symbol-symbol.
6423 // Ensure that no non-strings have the symbol bit set.
6424 ASSERT(kNotStringTag + kIsSymbolMask > LAST_TYPE);
6425 ASSERT(kSymbolTag != 0);
6426 __ and_(r2, r2, Operand(r3));
6427 __ tst(r2, Operand(kIsSymbolMask));
6428 __ b(ne, &return_not_equal);
Steve Blocka7e24c12009-10-30 11:49:00 +00006429}
6430
6431
6432// See comment at call site.
6433static void EmitCheckForTwoHeapNumbers(MacroAssembler* masm,
6434 Label* both_loaded_as_doubles,
6435 Label* not_heap_numbers,
6436 Label* slow) {
Leon Clarkee46be812010-01-19 14:06:41 +00006437 __ CompareObjectType(r0, r3, r2, HEAP_NUMBER_TYPE);
Steve Blocka7e24c12009-10-30 11:49:00 +00006438 __ b(ne, not_heap_numbers);
Leon Clarkee46be812010-01-19 14:06:41 +00006439 __ ldr(r2, FieldMemOperand(r1, HeapObject::kMapOffset));
6440 __ cmp(r2, r3);
Steve Blocka7e24c12009-10-30 11:49:00 +00006441 __ b(ne, slow); // First was a heap number, second wasn't. Go slow case.
6442
6443 // Both are heap numbers. Load them up then jump to the code we have
6444 // for that.
Leon Clarked91b9f72010-01-27 17:25:45 +00006445 if (CpuFeatures::IsSupported(VFP3)) {
6446 CpuFeatures::Scope scope(VFP3);
6447 __ sub(r7, r0, Operand(kHeapObjectTag));
6448 __ vldr(d6, r7, HeapNumber::kValueOffset);
6449 __ sub(r7, r1, Operand(kHeapObjectTag));
6450 __ vldr(d7, r7, HeapNumber::kValueOffset);
6451 } else {
6452 __ ldr(r2, FieldMemOperand(r1, HeapNumber::kValueOffset));
6453 __ ldr(r3, FieldMemOperand(r1, HeapNumber::kValueOffset + kPointerSize));
6454 __ ldr(r1, FieldMemOperand(r0, HeapNumber::kValueOffset + kPointerSize));
6455 __ ldr(r0, FieldMemOperand(r0, HeapNumber::kValueOffset));
6456 }
Steve Blocka7e24c12009-10-30 11:49:00 +00006457 __ jmp(both_loaded_as_doubles);
6458}
6459
6460
6461// Fast negative check for symbol-to-symbol equality.
6462static void EmitCheckForSymbols(MacroAssembler* masm, Label* slow) {
6463 // r2 is object type of r0.
Leon Clarkee46be812010-01-19 14:06:41 +00006464 // Ensure that no non-strings have the symbol bit set.
6465 ASSERT(kNotStringTag + kIsSymbolMask > LAST_TYPE);
6466 ASSERT(kSymbolTag != 0);
Steve Blocka7e24c12009-10-30 11:49:00 +00006467 __ tst(r2, Operand(kIsSymbolMask));
6468 __ b(eq, slow);
Leon Clarkee46be812010-01-19 14:06:41 +00006469 __ ldr(r3, FieldMemOperand(r1, HeapObject::kMapOffset));
6470 __ ldrb(r3, FieldMemOperand(r3, Map::kInstanceTypeOffset));
Steve Blocka7e24c12009-10-30 11:49:00 +00006471 __ tst(r3, Operand(kIsSymbolMask));
6472 __ b(eq, slow);
6473
6474 // Both are symbols. We already checked they weren't the same pointer
6475 // so they are not equal.
6476 __ mov(r0, Operand(1)); // Non-zero indicates not equal.
6477 __ mov(pc, Operand(lr)); // Return.
6478}
6479
6480
Steve Block6ded16b2010-05-10 14:33:55 +01006481void NumberToStringStub::GenerateLookupNumberStringCache(MacroAssembler* masm,
6482 Register object,
6483 Register result,
6484 Register scratch1,
6485 Register scratch2,
6486 Register scratch3,
6487 bool object_is_smi,
6488 Label* not_found) {
6489 // Use of registers. Register result is used as a temporary.
6490 Register number_string_cache = result;
6491 Register mask = scratch3;
6492
6493 // Load the number string cache.
6494 __ LoadRoot(number_string_cache, Heap::kNumberStringCacheRootIndex);
6495
6496 // Make the hash mask from the length of the number string cache. It
6497 // contains two elements (number and string) for each cache entry.
6498 __ ldr(mask, FieldMemOperand(number_string_cache, FixedArray::kLengthOffset));
6499 // Divide length by two (length is not a smi).
6500 __ mov(mask, Operand(mask, ASR, 1));
6501 __ sub(mask, mask, Operand(1)); // Make mask.
6502
6503 // Calculate the entry in the number string cache. The hash value in the
6504 // number string cache for smis is just the smi value, and the hash for
6505 // doubles is the xor of the upper and lower words. See
6506 // Heap::GetNumberStringCache.
6507 Label is_smi;
6508 Label load_result_from_cache;
6509 if (!object_is_smi) {
6510 __ BranchOnSmi(object, &is_smi);
6511 if (CpuFeatures::IsSupported(VFP3)) {
6512 CpuFeatures::Scope scope(VFP3);
6513 __ CheckMap(object,
6514 scratch1,
6515 Factory::heap_number_map(),
6516 not_found,
6517 true);
6518
6519 ASSERT_EQ(8, kDoubleSize);
6520 __ add(scratch1,
6521 object,
6522 Operand(HeapNumber::kValueOffset - kHeapObjectTag));
6523 __ ldm(ia, scratch1, scratch1.bit() | scratch2.bit());
6524 __ eor(scratch1, scratch1, Operand(scratch2));
6525 __ and_(scratch1, scratch1, Operand(mask));
6526
6527 // Calculate address of entry in string cache: each entry consists
6528 // of two pointer sized fields.
6529 __ add(scratch1,
6530 number_string_cache,
6531 Operand(scratch1, LSL, kPointerSizeLog2 + 1));
6532
6533 Register probe = mask;
6534 __ ldr(probe,
6535 FieldMemOperand(scratch1, FixedArray::kHeaderSize));
6536 __ BranchOnSmi(probe, not_found);
6537 __ sub(scratch2, object, Operand(kHeapObjectTag));
6538 __ vldr(d0, scratch2, HeapNumber::kValueOffset);
6539 __ sub(probe, probe, Operand(kHeapObjectTag));
6540 __ vldr(d1, probe, HeapNumber::kValueOffset);
6541 __ vcmp(d0, d1);
6542 __ vmrs(pc);
6543 __ b(ne, not_found); // The cache did not contain this value.
6544 __ b(&load_result_from_cache);
6545 } else {
6546 __ b(not_found);
6547 }
6548 }
6549
6550 __ bind(&is_smi);
6551 Register scratch = scratch1;
6552 __ and_(scratch, mask, Operand(object, ASR, 1));
6553 // Calculate address of entry in string cache: each entry consists
6554 // of two pointer sized fields.
6555 __ add(scratch,
6556 number_string_cache,
6557 Operand(scratch, LSL, kPointerSizeLog2 + 1));
6558
6559 // Check if the entry is the smi we are looking for.
6560 Register probe = mask;
6561 __ ldr(probe, FieldMemOperand(scratch, FixedArray::kHeaderSize));
6562 __ cmp(object, probe);
6563 __ b(ne, not_found);
6564
6565 // Get the result from the cache.
6566 __ bind(&load_result_from_cache);
6567 __ ldr(result,
6568 FieldMemOperand(scratch, FixedArray::kHeaderSize + kPointerSize));
6569 __ IncrementCounter(&Counters::number_to_string_native,
6570 1,
6571 scratch1,
6572 scratch2);
6573}
6574
6575
6576void NumberToStringStub::Generate(MacroAssembler* masm) {
6577 Label runtime;
6578
6579 __ ldr(r1, MemOperand(sp, 0));
6580
6581 // Generate code to lookup number in the number string cache.
6582 GenerateLookupNumberStringCache(masm, r1, r0, r2, r3, r4, false, &runtime);
6583 __ add(sp, sp, Operand(1 * kPointerSize));
6584 __ Ret();
6585
6586 __ bind(&runtime);
6587 // Handle number to string in the runtime system if not found in the cache.
6588 __ TailCallRuntime(Runtime::kNumberToStringSkipCache, 1, 1);
6589}
6590
6591
6592void RecordWriteStub::Generate(MacroAssembler* masm) {
6593 __ RecordWriteHelper(object_, offset_, scratch_);
6594 __ Ret();
6595}
6596
6597
Leon Clarked91b9f72010-01-27 17:25:45 +00006598// On entry r0 (rhs) and r1 (lhs) are the values to be compared.
6599// On exit r0 is 0, positive or negative to indicate the result of
6600// the comparison.
Steve Blocka7e24c12009-10-30 11:49:00 +00006601void CompareStub::Generate(MacroAssembler* masm) {
6602 Label slow; // Call builtin.
Leon Clarkee46be812010-01-19 14:06:41 +00006603 Label not_smis, both_loaded_as_doubles, lhs_not_nan;
Steve Blocka7e24c12009-10-30 11:49:00 +00006604
6605 // NOTICE! This code is only reached after a smi-fast-case check, so
6606 // it is certain that at least one operand isn't a smi.
6607
6608 // Handle the case where the objects are identical. Either returns the answer
6609 // or goes to slow. Only falls through if the objects were not identical.
Leon Clarkee46be812010-01-19 14:06:41 +00006610 EmitIdenticalObjectComparison(masm, &slow, cc_, never_nan_nan_);
Steve Blocka7e24c12009-10-30 11:49:00 +00006611
6612 // If either is a Smi (we know that not both are), then they can only
6613 // be strictly equal if the other is a HeapNumber.
6614 ASSERT_EQ(0, kSmiTag);
6615 ASSERT_EQ(0, Smi::FromInt(0));
6616 __ and_(r2, r0, Operand(r1));
6617 __ tst(r2, Operand(kSmiTagMask));
6618 __ b(ne, &not_smis);
6619 // One operand is a smi. EmitSmiNonsmiComparison generates code that can:
6620 // 1) Return the answer.
6621 // 2) Go to slow.
6622 // 3) Fall through to both_loaded_as_doubles.
Leon Clarkee46be812010-01-19 14:06:41 +00006623 // 4) Jump to lhs_not_nan.
Steve Blocka7e24c12009-10-30 11:49:00 +00006624 // In cases 3 and 4 we have found out we were dealing with a number-number
Leon Clarked91b9f72010-01-27 17:25:45 +00006625 // comparison. If VFP3 is supported the double values of the numbers have
6626 // been loaded into d7 and d6. Otherwise, the double values have been loaded
6627 // into r0, r1, r2, and r3.
Leon Clarkee46be812010-01-19 14:06:41 +00006628 EmitSmiNonsmiComparison(masm, &lhs_not_nan, &slow, strict_);
Steve Blocka7e24c12009-10-30 11:49:00 +00006629
6630 __ bind(&both_loaded_as_doubles);
Leon Clarked91b9f72010-01-27 17:25:45 +00006631 // The arguments have been converted to doubles and stored in d6 and d7, if
6632 // VFP3 is supported, or in r0, r1, r2, and r3.
Steve Blockd0582a62009-12-15 09:54:21 +00006633 if (CpuFeatures::IsSupported(VFP3)) {
Leon Clarkee46be812010-01-19 14:06:41 +00006634 __ bind(&lhs_not_nan);
Steve Blockd0582a62009-12-15 09:54:21 +00006635 CpuFeatures::Scope scope(VFP3);
Leon Clarkee46be812010-01-19 14:06:41 +00006636 Label no_nan;
Steve Blockd0582a62009-12-15 09:54:21 +00006637 // ARMv7 VFP3 instructions to implement double precision comparison.
Leon Clarkee46be812010-01-19 14:06:41 +00006638 __ vcmp(d7, d6);
6639 __ vmrs(pc); // Move vector status bits to normal status bits.
6640 Label nan;
6641 __ b(vs, &nan);
6642 __ mov(r0, Operand(EQUAL), LeaveCC, eq);
6643 __ mov(r0, Operand(LESS), LeaveCC, lt);
6644 __ mov(r0, Operand(GREATER), LeaveCC, gt);
6645 __ mov(pc, Operand(lr));
6646
6647 __ bind(&nan);
6648 // If one of the sides was a NaN then the v flag is set. Load r0 with
6649 // whatever it takes to make the comparison fail, since comparisons with NaN
6650 // always fail.
6651 if (cc_ == lt || cc_ == le) {
6652 __ mov(r0, Operand(GREATER));
6653 } else {
6654 __ mov(r0, Operand(LESS));
6655 }
Steve Blockd0582a62009-12-15 09:54:21 +00006656 __ mov(pc, Operand(lr));
6657 } else {
Leon Clarkee46be812010-01-19 14:06:41 +00006658 // Checks for NaN in the doubles we have loaded. Can return the answer or
6659 // fall through if neither is a NaN. Also binds lhs_not_nan.
6660 EmitNanCheck(masm, &lhs_not_nan, cc_);
Steve Blockd0582a62009-12-15 09:54:21 +00006661 // Compares two doubles in r0, r1, r2, r3 that are not NaNs. Returns the
6662 // answer. Never falls through.
6663 EmitTwoNonNanDoubleComparison(masm, cc_);
6664 }
Steve Blocka7e24c12009-10-30 11:49:00 +00006665
6666 __ bind(&not_smis);
6667 // At this point we know we are dealing with two different objects,
6668 // and neither of them is a Smi. The objects are in r0 and r1.
6669 if (strict_) {
6670 // This returns non-equal for some object types, or falls through if it
6671 // was not lucky.
6672 EmitStrictTwoHeapObjectCompare(masm);
6673 }
6674
6675 Label check_for_symbols;
Leon Clarked91b9f72010-01-27 17:25:45 +00006676 Label flat_string_check;
Steve Blocka7e24c12009-10-30 11:49:00 +00006677 // Check for heap-number-heap-number comparison. Can jump to slow case,
6678 // or load both doubles into r0, r1, r2, r3 and jump to the code that handles
6679 // that case. If the inputs are not doubles then jumps to check_for_symbols.
Leon Clarkee46be812010-01-19 14:06:41 +00006680 // In this case r2 will contain the type of r0. Never falls through.
Steve Blocka7e24c12009-10-30 11:49:00 +00006681 EmitCheckForTwoHeapNumbers(masm,
6682 &both_loaded_as_doubles,
6683 &check_for_symbols,
Leon Clarked91b9f72010-01-27 17:25:45 +00006684 &flat_string_check);
Steve Blocka7e24c12009-10-30 11:49:00 +00006685
6686 __ bind(&check_for_symbols);
Leon Clarkee46be812010-01-19 14:06:41 +00006687 // In the strict case the EmitStrictTwoHeapObjectCompare already took care of
6688 // symbols.
6689 if (cc_ == eq && !strict_) {
Steve Blocka7e24c12009-10-30 11:49:00 +00006690 // Either jumps to slow or returns the answer. Assumes that r2 is the type
6691 // of r0 on entry.
Leon Clarked91b9f72010-01-27 17:25:45 +00006692 EmitCheckForSymbols(masm, &flat_string_check);
Steve Blocka7e24c12009-10-30 11:49:00 +00006693 }
6694
Leon Clarked91b9f72010-01-27 17:25:45 +00006695 // Check for both being sequential ASCII strings, and inline if that is the
6696 // case.
6697 __ bind(&flat_string_check);
6698
6699 __ JumpIfNonSmisNotBothSequentialAsciiStrings(r0, r1, r2, r3, &slow);
6700
6701 __ IncrementCounter(&Counters::string_compare_native, 1, r2, r3);
6702 StringCompareStub::GenerateCompareFlatAsciiStrings(masm,
6703 r1,
6704 r0,
6705 r2,
6706 r3,
6707 r4,
6708 r5);
6709 // Never falls through to here.
6710
Steve Blocka7e24c12009-10-30 11:49:00 +00006711 __ bind(&slow);
Leon Clarked91b9f72010-01-27 17:25:45 +00006712
Steve Block6ded16b2010-05-10 14:33:55 +01006713 __ Push(r1, r0);
Steve Blocka7e24c12009-10-30 11:49:00 +00006714 // Figure out which native to call and setup the arguments.
6715 Builtins::JavaScript native;
Steve Blocka7e24c12009-10-30 11:49:00 +00006716 if (cc_ == eq) {
6717 native = strict_ ? Builtins::STRICT_EQUALS : Builtins::EQUALS;
6718 } else {
6719 native = Builtins::COMPARE;
6720 int ncr; // NaN compare result
6721 if (cc_ == lt || cc_ == le) {
6722 ncr = GREATER;
6723 } else {
6724 ASSERT(cc_ == gt || cc_ == ge); // remaining cases
6725 ncr = LESS;
6726 }
Steve Blocka7e24c12009-10-30 11:49:00 +00006727 __ mov(r0, Operand(Smi::FromInt(ncr)));
6728 __ push(r0);
6729 }
6730
6731 // Call the native; it returns -1 (less), 0 (equal), or 1 (greater)
6732 // tagged as a small integer.
Leon Clarkee46be812010-01-19 14:06:41 +00006733 __ InvokeBuiltin(native, JUMP_JS);
Steve Blocka7e24c12009-10-30 11:49:00 +00006734}
6735
6736
Steve Blocka7e24c12009-10-30 11:49:00 +00006737// We fall into this code if the operands were Smis, but the result was
6738// not (eg. overflow). We branch into this code (to the not_smi label) if
6739// the operands were not both Smi. The operands are in r0 and r1. In order
6740// to call the C-implemented binary fp operation routines we need to end up
6741// with the double precision floating point operands in r0 and r1 (for the
6742// value in r1) and r2 and r3 (for the value in r0).
Steve Block6ded16b2010-05-10 14:33:55 +01006743void GenericBinaryOpStub::HandleBinaryOpSlowCases(
6744 MacroAssembler* masm,
6745 Label* not_smi,
6746 Register lhs,
6747 Register rhs,
6748 const Builtins::JavaScript& builtin) {
6749 Label slow, slow_reverse, do_the_call;
6750 bool use_fp_registers = CpuFeatures::IsSupported(VFP3) && Token::MOD != op_;
Steve Blockd0582a62009-12-15 09:54:21 +00006751
Steve Block6ded16b2010-05-10 14:33:55 +01006752 ASSERT((lhs.is(r0) && rhs.is(r1)) || (lhs.is(r1) && rhs.is(r0)));
6753
6754 if (ShouldGenerateSmiCode()) {
6755 // Smi-smi case (overflow).
6756 // Since both are Smis there is no heap number to overwrite, so allocate.
6757 // The new heap number is in r5. r6 and r7 are scratch.
6758 __ AllocateHeapNumber(r5, r6, r7, lhs.is(r0) ? &slow_reverse : &slow);
6759
6760 // If we have floating point hardware, inline ADD, SUB, MUL, and DIV,
6761 // using registers d7 and d6 for the double values.
6762 if (use_fp_registers) {
6763 CpuFeatures::Scope scope(VFP3);
6764 __ mov(r7, Operand(rhs, ASR, kSmiTagSize));
6765 __ vmov(s15, r7);
6766 __ vcvt_f64_s32(d7, s15);
6767 __ mov(r7, Operand(lhs, ASR, kSmiTagSize));
6768 __ vmov(s13, r7);
6769 __ vcvt_f64_s32(d6, s13);
6770 } else {
6771 // Write Smi from rhs to r3 and r2 in double format. r6 is scratch.
6772 __ mov(r7, Operand(rhs));
6773 ConvertToDoubleStub stub1(r3, r2, r7, r6);
6774 __ push(lr);
6775 __ Call(stub1.GetCode(), RelocInfo::CODE_TARGET);
6776 // Write Smi from lhs to r1 and r0 in double format. r6 is scratch.
6777 __ mov(r7, Operand(lhs));
6778 ConvertToDoubleStub stub2(r1, r0, r7, r6);
6779 __ Call(stub2.GetCode(), RelocInfo::CODE_TARGET);
6780 __ pop(lr);
6781 }
6782 __ jmp(&do_the_call); // Tail call. No return.
Steve Blockd0582a62009-12-15 09:54:21 +00006783 }
6784
Steve Block6ded16b2010-05-10 14:33:55 +01006785 // We branch here if at least one of r0 and r1 is not a Smi.
6786 __ bind(not_smi);
6787
6788 // After this point we have the left hand side in r1 and the right hand side
6789 // in r0.
6790 if (lhs.is(r0)) {
6791 __ Swap(r0, r1, ip);
6792 }
6793
6794 if (ShouldGenerateFPCode()) {
6795 Label r0_is_smi, r1_is_smi, finished_loading_r0, finished_loading_r1;
6796
6797 if (runtime_operands_type_ == BinaryOpIC::DEFAULT) {
6798 switch (op_) {
6799 case Token::ADD:
6800 case Token::SUB:
6801 case Token::MUL:
6802 case Token::DIV:
6803 GenerateTypeTransition(masm);
6804 break;
6805
6806 default:
6807 break;
6808 }
6809 }
6810
6811 if (mode_ == NO_OVERWRITE) {
6812 // In the case where there is no chance of an overwritable float we may as
6813 // well do the allocation immediately while r0 and r1 are untouched.
6814 __ AllocateHeapNumber(r5, r6, r7, &slow);
6815 }
6816
6817 // Move r0 to a double in r2-r3.
6818 __ tst(r0, Operand(kSmiTagMask));
6819 __ b(eq, &r0_is_smi); // It's a Smi so don't check it's a heap number.
6820 __ CompareObjectType(r0, r4, r4, HEAP_NUMBER_TYPE);
6821 __ b(ne, &slow);
6822 if (mode_ == OVERWRITE_RIGHT) {
6823 __ mov(r5, Operand(r0)); // Overwrite this heap number.
6824 }
6825 if (use_fp_registers) {
6826 CpuFeatures::Scope scope(VFP3);
6827 // Load the double from tagged HeapNumber r0 to d7.
6828 __ sub(r7, r0, Operand(kHeapObjectTag));
6829 __ vldr(d7, r7, HeapNumber::kValueOffset);
6830 } else {
6831 // Calling convention says that second double is in r2 and r3.
6832 __ ldr(r2, FieldMemOperand(r0, HeapNumber::kValueOffset));
6833 __ ldr(r3, FieldMemOperand(r0, HeapNumber::kValueOffset + 4));
6834 }
6835 __ jmp(&finished_loading_r0);
6836 __ bind(&r0_is_smi);
6837 if (mode_ == OVERWRITE_RIGHT) {
6838 // We can't overwrite a Smi so get address of new heap number into r5.
6839 __ AllocateHeapNumber(r5, r6, r7, &slow);
6840 }
6841
6842 if (use_fp_registers) {
6843 CpuFeatures::Scope scope(VFP3);
6844 // Convert smi in r0 to double in d7.
6845 __ mov(r7, Operand(r0, ASR, kSmiTagSize));
6846 __ vmov(s15, r7);
6847 __ vcvt_f64_s32(d7, s15);
6848 } else {
6849 // Write Smi from r0 to r3 and r2 in double format.
6850 __ mov(r7, Operand(r0));
6851 ConvertToDoubleStub stub3(r3, r2, r7, r6);
6852 __ push(lr);
6853 __ Call(stub3.GetCode(), RelocInfo::CODE_TARGET);
6854 __ pop(lr);
6855 }
6856
6857 // HEAP_NUMBERS stub is slower than GENERIC on a pair of smis.
6858 // r0 is known to be a smi. If r1 is also a smi then switch to GENERIC.
6859 Label r1_is_not_smi;
6860 if (runtime_operands_type_ == BinaryOpIC::HEAP_NUMBERS) {
6861 __ tst(r1, Operand(kSmiTagMask));
6862 __ b(ne, &r1_is_not_smi);
6863 GenerateTypeTransition(masm);
6864 __ jmp(&r1_is_smi);
6865 }
6866
6867 __ bind(&finished_loading_r0);
6868
6869 // Move r1 to a double in r0-r1.
6870 __ tst(r1, Operand(kSmiTagMask));
6871 __ b(eq, &r1_is_smi); // It's a Smi so don't check it's a heap number.
6872 __ bind(&r1_is_not_smi);
6873 __ CompareObjectType(r1, r4, r4, HEAP_NUMBER_TYPE);
6874 __ b(ne, &slow);
6875 if (mode_ == OVERWRITE_LEFT) {
6876 __ mov(r5, Operand(r1)); // Overwrite this heap number.
6877 }
6878 if (use_fp_registers) {
6879 CpuFeatures::Scope scope(VFP3);
6880 // Load the double from tagged HeapNumber r1 to d6.
6881 __ sub(r7, r1, Operand(kHeapObjectTag));
6882 __ vldr(d6, r7, HeapNumber::kValueOffset);
6883 } else {
6884 // Calling convention says that first double is in r0 and r1.
6885 __ ldr(r0, FieldMemOperand(r1, HeapNumber::kValueOffset));
6886 __ ldr(r1, FieldMemOperand(r1, HeapNumber::kValueOffset + 4));
6887 }
6888 __ jmp(&finished_loading_r1);
6889 __ bind(&r1_is_smi);
6890 if (mode_ == OVERWRITE_LEFT) {
6891 // We can't overwrite a Smi so get address of new heap number into r5.
6892 __ AllocateHeapNumber(r5, r6, r7, &slow);
6893 }
6894
6895 if (use_fp_registers) {
6896 CpuFeatures::Scope scope(VFP3);
6897 // Convert smi in r1 to double in d6.
6898 __ mov(r7, Operand(r1, ASR, kSmiTagSize));
6899 __ vmov(s13, r7);
6900 __ vcvt_f64_s32(d6, s13);
6901 } else {
6902 // Write Smi from r1 to r1 and r0 in double format.
6903 __ mov(r7, Operand(r1));
6904 ConvertToDoubleStub stub4(r1, r0, r7, r6);
6905 __ push(lr);
6906 __ Call(stub4.GetCode(), RelocInfo::CODE_TARGET);
6907 __ pop(lr);
6908 }
6909
6910 __ bind(&finished_loading_r1);
6911
6912 __ bind(&do_the_call);
6913 // If we are inlining the operation using VFP3 instructions for
6914 // add, subtract, multiply, or divide, the arguments are in d6 and d7.
6915 if (use_fp_registers) {
6916 CpuFeatures::Scope scope(VFP3);
6917 // ARMv7 VFP3 instructions to implement
6918 // double precision, add, subtract, multiply, divide.
6919
6920 if (Token::MUL == op_) {
6921 __ vmul(d5, d6, d7);
6922 } else if (Token::DIV == op_) {
6923 __ vdiv(d5, d6, d7);
6924 } else if (Token::ADD == op_) {
6925 __ vadd(d5, d6, d7);
6926 } else if (Token::SUB == op_) {
6927 __ vsub(d5, d6, d7);
6928 } else {
6929 UNREACHABLE();
6930 }
6931 __ sub(r0, r5, Operand(kHeapObjectTag));
6932 __ vstr(d5, r0, HeapNumber::kValueOffset);
6933 __ add(r0, r0, Operand(kHeapObjectTag));
6934 __ mov(pc, lr);
6935 } else {
6936 // If we did not inline the operation, then the arguments are in:
6937 // r0: Left value (least significant part of mantissa).
6938 // r1: Left value (sign, exponent, top of mantissa).
6939 // r2: Right value (least significant part of mantissa).
6940 // r3: Right value (sign, exponent, top of mantissa).
6941 // r5: Address of heap number for result.
6942
6943 __ push(lr); // For later.
6944 __ PrepareCallCFunction(4, r4); // Two doubles count as 4 arguments.
6945 // Call C routine that may not cause GC or other trouble. r5 is callee
6946 // save.
6947 __ CallCFunction(ExternalReference::double_fp_operation(op_), 4);
6948 // Store answer in the overwritable heap number.
6949 #if !defined(USE_ARM_EABI)
6950 // Double returned in fp coprocessor register 0 and 1, encoded as register
6951 // cr8. Offsets must be divisible by 4 for coprocessor so we need to
6952 // substract the tag from r5.
6953 __ sub(r4, r5, Operand(kHeapObjectTag));
6954 __ stc(p1, cr8, MemOperand(r4, HeapNumber::kValueOffset));
6955 #else
6956 // Double returned in registers 0 and 1.
6957 __ str(r0, FieldMemOperand(r5, HeapNumber::kValueOffset));
6958 __ str(r1, FieldMemOperand(r5, HeapNumber::kValueOffset + 4));
6959 #endif
6960 __ mov(r0, Operand(r5));
6961 // And we are done.
6962 __ pop(pc);
6963 }
6964 }
6965
6966
6967 if (lhs.is(r0)) {
6968 __ b(&slow);
6969 __ bind(&slow_reverse);
6970 __ Swap(r0, r1, ip);
6971 }
Steve Blocka7e24c12009-10-30 11:49:00 +00006972
6973 // We jump to here if something goes wrong (one param is not a number of any
6974 // sort or new-space allocation fails).
6975 __ bind(&slow);
Steve Blockd0582a62009-12-15 09:54:21 +00006976
6977 // Push arguments to the stack
Steve Block6ded16b2010-05-10 14:33:55 +01006978 __ Push(r1, r0);
Steve Blockd0582a62009-12-15 09:54:21 +00006979
Steve Block6ded16b2010-05-10 14:33:55 +01006980 if (Token::ADD == op_) {
Steve Blockd0582a62009-12-15 09:54:21 +00006981 // Test for string arguments before calling runtime.
6982 // r1 : first argument
6983 // r0 : second argument
6984 // sp[0] : second argument
Andrei Popescu31002712010-02-23 13:46:05 +00006985 // sp[4] : first argument
Steve Blockd0582a62009-12-15 09:54:21 +00006986
Steve Block6ded16b2010-05-10 14:33:55 +01006987 Label not_strings, not_string1, string1, string1_smi2;
Steve Blockd0582a62009-12-15 09:54:21 +00006988 __ tst(r1, Operand(kSmiTagMask));
6989 __ b(eq, &not_string1);
6990 __ CompareObjectType(r1, r2, r2, FIRST_NONSTRING_TYPE);
6991 __ b(ge, &not_string1);
6992
6993 // First argument is a a string, test second.
6994 __ tst(r0, Operand(kSmiTagMask));
Steve Block6ded16b2010-05-10 14:33:55 +01006995 __ b(eq, &string1_smi2);
Steve Blockd0582a62009-12-15 09:54:21 +00006996 __ CompareObjectType(r0, r2, r2, FIRST_NONSTRING_TYPE);
6997 __ b(ge, &string1);
6998
6999 // First and second argument are strings.
Steve Block6ded16b2010-05-10 14:33:55 +01007000 StringAddStub string_add_stub(NO_STRING_CHECK_IN_STUB);
7001 __ TailCallStub(&string_add_stub);
7002
7003 __ bind(&string1_smi2);
7004 // First argument is a string, second is a smi. Try to lookup the number
7005 // string for the smi in the number string cache.
7006 NumberToStringStub::GenerateLookupNumberStringCache(
7007 masm, r0, r2, r4, r5, r6, true, &string1);
7008
7009 // Replace second argument on stack and tailcall string add stub to make
7010 // the result.
7011 __ str(r2, MemOperand(sp, 0));
7012 __ TailCallStub(&string_add_stub);
Steve Blockd0582a62009-12-15 09:54:21 +00007013
7014 // Only first argument is a string.
7015 __ bind(&string1);
7016 __ InvokeBuiltin(Builtins::STRING_ADD_LEFT, JUMP_JS);
7017
7018 // First argument was not a string, test second.
7019 __ bind(&not_string1);
7020 __ tst(r0, Operand(kSmiTagMask));
7021 __ b(eq, &not_strings);
7022 __ CompareObjectType(r0, r2, r2, FIRST_NONSTRING_TYPE);
7023 __ b(ge, &not_strings);
7024
7025 // Only second argument is a string.
Steve Blockd0582a62009-12-15 09:54:21 +00007026 __ InvokeBuiltin(Builtins::STRING_ADD_RIGHT, JUMP_JS);
7027
7028 __ bind(&not_strings);
7029 }
7030
Steve Blocka7e24c12009-10-30 11:49:00 +00007031 __ InvokeBuiltin(builtin, JUMP_JS); // Tail call. No return.
Steve Blocka7e24c12009-10-30 11:49:00 +00007032}
7033
7034
7035// Tries to get a signed int32 out of a double precision floating point heap
7036// number. Rounds towards 0. Fastest for doubles that are in the ranges
7037// -0x7fffffff to -0x40000000 or 0x40000000 to 0x7fffffff. This corresponds
7038// almost to the range of signed int32 values that are not Smis. Jumps to the
7039// label 'slow' if the double isn't in the range -0x80000000.0 to 0x80000000.0
7040// (excluding the endpoints).
7041static void GetInt32(MacroAssembler* masm,
7042 Register source,
7043 Register dest,
7044 Register scratch,
7045 Register scratch2,
7046 Label* slow) {
7047 Label right_exponent, done;
7048 // Get exponent word.
7049 __ ldr(scratch, FieldMemOperand(source, HeapNumber::kExponentOffset));
7050 // Get exponent alone in scratch2.
7051 __ and_(scratch2, scratch, Operand(HeapNumber::kExponentMask));
7052 // Load dest with zero. We use this either for the final shift or
7053 // for the answer.
7054 __ mov(dest, Operand(0));
7055 // Check whether the exponent matches a 32 bit signed int that is not a Smi.
7056 // A non-Smi integer is 1.xxx * 2^30 so the exponent is 30 (biased). This is
7057 // the exponent that we are fastest at and also the highest exponent we can
7058 // handle here.
7059 const uint32_t non_smi_exponent =
7060 (HeapNumber::kExponentBias + 30) << HeapNumber::kExponentShift;
7061 __ cmp(scratch2, Operand(non_smi_exponent));
7062 // If we have a match of the int32-but-not-Smi exponent then skip some logic.
7063 __ b(eq, &right_exponent);
7064 // If the exponent is higher than that then go to slow case. This catches
7065 // numbers that don't fit in a signed int32, infinities and NaNs.
7066 __ b(gt, slow);
7067
7068 // We know the exponent is smaller than 30 (biased). If it is less than
7069 // 0 (biased) then the number is smaller in magnitude than 1.0 * 2^0, ie
7070 // it rounds to zero.
7071 const uint32_t zero_exponent =
7072 (HeapNumber::kExponentBias + 0) << HeapNumber::kExponentShift;
7073 __ sub(scratch2, scratch2, Operand(zero_exponent), SetCC);
7074 // Dest already has a Smi zero.
7075 __ b(lt, &done);
Steve Blockd0582a62009-12-15 09:54:21 +00007076 if (!CpuFeatures::IsSupported(VFP3)) {
7077 // We have a shifted exponent between 0 and 30 in scratch2.
7078 __ mov(dest, Operand(scratch2, LSR, HeapNumber::kExponentShift));
7079 // We now have the exponent in dest. Subtract from 30 to get
7080 // how much to shift down.
7081 __ rsb(dest, dest, Operand(30));
7082 }
Steve Blocka7e24c12009-10-30 11:49:00 +00007083 __ bind(&right_exponent);
Steve Blockd0582a62009-12-15 09:54:21 +00007084 if (CpuFeatures::IsSupported(VFP3)) {
7085 CpuFeatures::Scope scope(VFP3);
7086 // ARMv7 VFP3 instructions implementing double precision to integer
7087 // conversion using round to zero.
7088 __ ldr(scratch2, FieldMemOperand(source, HeapNumber::kMantissaOffset));
Leon Clarkee46be812010-01-19 14:06:41 +00007089 __ vmov(d7, scratch2, scratch);
Steve Block6ded16b2010-05-10 14:33:55 +01007090 __ vcvt_s32_f64(s15, d7);
Leon Clarkee46be812010-01-19 14:06:41 +00007091 __ vmov(dest, s15);
Steve Blockd0582a62009-12-15 09:54:21 +00007092 } else {
7093 // Get the top bits of the mantissa.
7094 __ and_(scratch2, scratch, Operand(HeapNumber::kMantissaMask));
7095 // Put back the implicit 1.
7096 __ orr(scratch2, scratch2, Operand(1 << HeapNumber::kExponentShift));
7097 // Shift up the mantissa bits to take up the space the exponent used to
7098 // take. We just orred in the implicit bit so that took care of one and
7099 // we want to leave the sign bit 0 so we subtract 2 bits from the shift
7100 // distance.
7101 const int shift_distance = HeapNumber::kNonMantissaBitsInTopWord - 2;
7102 __ mov(scratch2, Operand(scratch2, LSL, shift_distance));
7103 // Put sign in zero flag.
7104 __ tst(scratch, Operand(HeapNumber::kSignMask));
7105 // Get the second half of the double. For some exponents we don't
7106 // actually need this because the bits get shifted out again, but
7107 // it's probably slower to test than just to do it.
7108 __ ldr(scratch, FieldMemOperand(source, HeapNumber::kMantissaOffset));
7109 // Shift down 22 bits to get the last 10 bits.
7110 __ orr(scratch, scratch2, Operand(scratch, LSR, 32 - shift_distance));
7111 // Move down according to the exponent.
7112 __ mov(dest, Operand(scratch, LSR, dest));
7113 // Fix sign if sign bit was set.
7114 __ rsb(dest, dest, Operand(0), LeaveCC, ne);
7115 }
Steve Blocka7e24c12009-10-30 11:49:00 +00007116 __ bind(&done);
7117}
7118
Steve Blocka7e24c12009-10-30 11:49:00 +00007119// For bitwise ops where the inputs are not both Smis we here try to determine
7120// whether both inputs are either Smis or at least heap numbers that can be
7121// represented by a 32 bit signed value. We truncate towards zero as required
7122// by the ES spec. If this is the case we do the bitwise op and see if the
7123// result is a Smi. If so, great, otherwise we try to find a heap number to
7124// write the answer into (either by allocating or by overwriting).
Steve Block6ded16b2010-05-10 14:33:55 +01007125// On entry the operands are in lhs and rhs. On exit the answer is in r0.
7126void GenericBinaryOpStub::HandleNonSmiBitwiseOp(MacroAssembler* masm,
7127 Register lhs,
7128 Register rhs) {
Steve Blocka7e24c12009-10-30 11:49:00 +00007129 Label slow, result_not_a_smi;
Steve Block6ded16b2010-05-10 14:33:55 +01007130 Label rhs_is_smi, lhs_is_smi;
7131 Label done_checking_rhs, done_checking_lhs;
Steve Blocka7e24c12009-10-30 11:49:00 +00007132
Steve Block6ded16b2010-05-10 14:33:55 +01007133 __ tst(lhs, Operand(kSmiTagMask));
7134 __ b(eq, &lhs_is_smi); // It's a Smi so don't check it's a heap number.
7135 __ CompareObjectType(lhs, r4, r4, HEAP_NUMBER_TYPE);
Steve Blocka7e24c12009-10-30 11:49:00 +00007136 __ b(ne, &slow);
Steve Block6ded16b2010-05-10 14:33:55 +01007137 GetInt32(masm, lhs, r3, r5, r4, &slow);
7138 __ jmp(&done_checking_lhs);
7139 __ bind(&lhs_is_smi);
7140 __ mov(r3, Operand(lhs, ASR, 1));
7141 __ bind(&done_checking_lhs);
Steve Blocka7e24c12009-10-30 11:49:00 +00007142
Steve Block6ded16b2010-05-10 14:33:55 +01007143 __ tst(rhs, Operand(kSmiTagMask));
7144 __ b(eq, &rhs_is_smi); // It's a Smi so don't check it's a heap number.
7145 __ CompareObjectType(rhs, r4, r4, HEAP_NUMBER_TYPE);
Steve Blocka7e24c12009-10-30 11:49:00 +00007146 __ b(ne, &slow);
Steve Block6ded16b2010-05-10 14:33:55 +01007147 GetInt32(masm, rhs, r2, r5, r4, &slow);
7148 __ jmp(&done_checking_rhs);
7149 __ bind(&rhs_is_smi);
7150 __ mov(r2, Operand(rhs, ASR, 1));
7151 __ bind(&done_checking_rhs);
7152
7153 ASSERT(((lhs.is(r0) && rhs.is(r1)) || (lhs.is(r1) && rhs.is(r0))));
Steve Blocka7e24c12009-10-30 11:49:00 +00007154
7155 // r0 and r1: Original operands (Smi or heap numbers).
7156 // r2 and r3: Signed int32 operands.
7157 switch (op_) {
7158 case Token::BIT_OR: __ orr(r2, r2, Operand(r3)); break;
7159 case Token::BIT_XOR: __ eor(r2, r2, Operand(r3)); break;
7160 case Token::BIT_AND: __ and_(r2, r2, Operand(r3)); break;
7161 case Token::SAR:
7162 // Use only the 5 least significant bits of the shift count.
7163 __ and_(r2, r2, Operand(0x1f));
7164 __ mov(r2, Operand(r3, ASR, r2));
7165 break;
7166 case Token::SHR:
7167 // Use only the 5 least significant bits of the shift count.
7168 __ and_(r2, r2, Operand(0x1f));
7169 __ mov(r2, Operand(r3, LSR, r2), SetCC);
7170 // SHR is special because it is required to produce a positive answer.
7171 // The code below for writing into heap numbers isn't capable of writing
7172 // the register as an unsigned int so we go to slow case if we hit this
7173 // case.
7174 __ b(mi, &slow);
7175 break;
7176 case Token::SHL:
7177 // Use only the 5 least significant bits of the shift count.
7178 __ and_(r2, r2, Operand(0x1f));
7179 __ mov(r2, Operand(r3, LSL, r2));
7180 break;
7181 default: UNREACHABLE();
7182 }
7183 // check that the *signed* result fits in a smi
7184 __ add(r3, r2, Operand(0x40000000), SetCC);
7185 __ b(mi, &result_not_a_smi);
7186 __ mov(r0, Operand(r2, LSL, kSmiTagSize));
7187 __ Ret();
7188
7189 Label have_to_allocate, got_a_heap_number;
7190 __ bind(&result_not_a_smi);
7191 switch (mode_) {
7192 case OVERWRITE_RIGHT: {
Steve Block6ded16b2010-05-10 14:33:55 +01007193 __ tst(rhs, Operand(kSmiTagMask));
Steve Blocka7e24c12009-10-30 11:49:00 +00007194 __ b(eq, &have_to_allocate);
Steve Block6ded16b2010-05-10 14:33:55 +01007195 __ mov(r5, Operand(rhs));
Steve Blocka7e24c12009-10-30 11:49:00 +00007196 break;
7197 }
7198 case OVERWRITE_LEFT: {
Steve Block6ded16b2010-05-10 14:33:55 +01007199 __ tst(lhs, Operand(kSmiTagMask));
Steve Blocka7e24c12009-10-30 11:49:00 +00007200 __ b(eq, &have_to_allocate);
Steve Block6ded16b2010-05-10 14:33:55 +01007201 __ mov(r5, Operand(lhs));
Steve Blocka7e24c12009-10-30 11:49:00 +00007202 break;
7203 }
7204 case NO_OVERWRITE: {
7205 // Get a new heap number in r5. r6 and r7 are scratch.
Steve Block6ded16b2010-05-10 14:33:55 +01007206 __ AllocateHeapNumber(r5, r6, r7, &slow);
Steve Blocka7e24c12009-10-30 11:49:00 +00007207 }
7208 default: break;
7209 }
7210 __ bind(&got_a_heap_number);
7211 // r2: Answer as signed int32.
7212 // r5: Heap number to write answer into.
7213
7214 // Nothing can go wrong now, so move the heap number to r0, which is the
7215 // result.
7216 __ mov(r0, Operand(r5));
7217
7218 // Tail call that writes the int32 in r2 to the heap number in r0, using
7219 // r3 as scratch. r0 is preserved and returned.
7220 WriteInt32ToHeapNumberStub stub(r2, r0, r3);
7221 __ Jump(stub.GetCode(), RelocInfo::CODE_TARGET);
7222
7223 if (mode_ != NO_OVERWRITE) {
7224 __ bind(&have_to_allocate);
7225 // Get a new heap number in r5. r6 and r7 are scratch.
Steve Block6ded16b2010-05-10 14:33:55 +01007226 __ AllocateHeapNumber(r5, r6, r7, &slow);
Steve Blocka7e24c12009-10-30 11:49:00 +00007227 __ jmp(&got_a_heap_number);
7228 }
7229
7230 // If all else failed then we go to the runtime system.
7231 __ bind(&slow);
Steve Block6ded16b2010-05-10 14:33:55 +01007232 __ Push(lhs, rhs); // Restore stack.
Steve Blocka7e24c12009-10-30 11:49:00 +00007233 switch (op_) {
7234 case Token::BIT_OR:
7235 __ InvokeBuiltin(Builtins::BIT_OR, JUMP_JS);
7236 break;
7237 case Token::BIT_AND:
7238 __ InvokeBuiltin(Builtins::BIT_AND, JUMP_JS);
7239 break;
7240 case Token::BIT_XOR:
7241 __ InvokeBuiltin(Builtins::BIT_XOR, JUMP_JS);
7242 break;
7243 case Token::SAR:
7244 __ InvokeBuiltin(Builtins::SAR, JUMP_JS);
7245 break;
7246 case Token::SHR:
7247 __ InvokeBuiltin(Builtins::SHR, JUMP_JS);
7248 break;
7249 case Token::SHL:
7250 __ InvokeBuiltin(Builtins::SHL, JUMP_JS);
7251 break;
7252 default:
7253 UNREACHABLE();
7254 }
7255}
7256
7257
7258// Can we multiply by x with max two shifts and an add.
7259// This answers yes to all integers from 2 to 10.
7260static bool IsEasyToMultiplyBy(int x) {
7261 if (x < 2) return false; // Avoid special cases.
7262 if (x > (Smi::kMaxValue + 1) >> 2) return false; // Almost always overflows.
7263 if (IsPowerOf2(x)) return true; // Simple shift.
7264 if (PopCountLessThanEqual2(x)) return true; // Shift and add and shift.
7265 if (IsPowerOf2(x + 1)) return true; // Patterns like 11111.
7266 return false;
7267}
7268
7269
7270// Can multiply by anything that IsEasyToMultiplyBy returns true for.
7271// Source and destination may be the same register. This routine does
7272// not set carry and overflow the way a mul instruction would.
7273static void MultiplyByKnownInt(MacroAssembler* masm,
7274 Register source,
7275 Register destination,
7276 int known_int) {
7277 if (IsPowerOf2(known_int)) {
7278 __ mov(destination, Operand(source, LSL, BitPosition(known_int)));
7279 } else if (PopCountLessThanEqual2(known_int)) {
7280 int first_bit = BitPosition(known_int);
7281 int second_bit = BitPosition(known_int ^ (1 << first_bit));
7282 __ add(destination, source, Operand(source, LSL, second_bit - first_bit));
7283 if (first_bit != 0) {
7284 __ mov(destination, Operand(destination, LSL, first_bit));
7285 }
7286 } else {
7287 ASSERT(IsPowerOf2(known_int + 1)); // Patterns like 1111.
7288 int the_bit = BitPosition(known_int + 1);
7289 __ rsb(destination, source, Operand(source, LSL, the_bit));
7290 }
7291}
7292
7293
7294// This function (as opposed to MultiplyByKnownInt) takes the known int in a
7295// a register for the cases where it doesn't know a good trick, and may deliver
7296// a result that needs shifting.
7297static void MultiplyByKnownInt2(
7298 MacroAssembler* masm,
7299 Register result,
7300 Register source,
7301 Register known_int_register, // Smi tagged.
7302 int known_int,
7303 int* required_shift) { // Including Smi tag shift
7304 switch (known_int) {
7305 case 3:
7306 __ add(result, source, Operand(source, LSL, 1));
7307 *required_shift = 1;
7308 break;
7309 case 5:
7310 __ add(result, source, Operand(source, LSL, 2));
7311 *required_shift = 1;
7312 break;
7313 case 6:
7314 __ add(result, source, Operand(source, LSL, 1));
7315 *required_shift = 2;
7316 break;
7317 case 7:
7318 __ rsb(result, source, Operand(source, LSL, 3));
7319 *required_shift = 1;
7320 break;
7321 case 9:
7322 __ add(result, source, Operand(source, LSL, 3));
7323 *required_shift = 1;
7324 break;
7325 case 10:
7326 __ add(result, source, Operand(source, LSL, 2));
7327 *required_shift = 2;
7328 break;
7329 default:
7330 ASSERT(!IsPowerOf2(known_int)); // That would be very inefficient.
7331 __ mul(result, source, known_int_register);
7332 *required_shift = 0;
7333 }
7334}
7335
7336
Leon Clarkee46be812010-01-19 14:06:41 +00007337const char* GenericBinaryOpStub::GetName() {
7338 if (name_ != NULL) return name_;
7339 const int len = 100;
7340 name_ = Bootstrapper::AllocateAutoDeletedArray(len);
7341 if (name_ == NULL) return "OOM";
7342 const char* op_name = Token::Name(op_);
7343 const char* overwrite_name;
7344 switch (mode_) {
7345 case NO_OVERWRITE: overwrite_name = "Alloc"; break;
7346 case OVERWRITE_RIGHT: overwrite_name = "OverwriteRight"; break;
7347 case OVERWRITE_LEFT: overwrite_name = "OverwriteLeft"; break;
7348 default: overwrite_name = "UnknownOverwrite"; break;
7349 }
7350
7351 OS::SNPrintF(Vector<char>(name_, len),
7352 "GenericBinaryOpStub_%s_%s%s",
7353 op_name,
7354 overwrite_name,
7355 specialized_on_rhs_ ? "_ConstantRhs" : 0);
7356 return name_;
7357}
7358
7359
Andrei Popescu31002712010-02-23 13:46:05 +00007360
Steve Blocka7e24c12009-10-30 11:49:00 +00007361void GenericBinaryOpStub::Generate(MacroAssembler* masm) {
Steve Block6ded16b2010-05-10 14:33:55 +01007362 // lhs_ : x
7363 // rhs_ : y
7364 // r0 : result
Steve Blocka7e24c12009-10-30 11:49:00 +00007365
Steve Block6ded16b2010-05-10 14:33:55 +01007366 Register result = r0;
7367 Register lhs = lhs_;
7368 Register rhs = rhs_;
7369
7370 // This code can't cope with other register allocations yet.
7371 ASSERT(result.is(r0) &&
7372 ((lhs.is(r0) && rhs.is(r1)) ||
7373 (lhs.is(r1) && rhs.is(r0))));
7374
7375 Register smi_test_reg = VirtualFrame::scratch0();
7376 Register scratch = VirtualFrame::scratch1();
7377
7378 // All ops need to know whether we are dealing with two Smis. Set up
7379 // smi_test_reg to tell us that.
7380 if (ShouldGenerateSmiCode()) {
7381 __ orr(smi_test_reg, lhs, Operand(rhs));
7382 }
Steve Blocka7e24c12009-10-30 11:49:00 +00007383
7384 switch (op_) {
7385 case Token::ADD: {
7386 Label not_smi;
7387 // Fast path.
Steve Block6ded16b2010-05-10 14:33:55 +01007388 if (ShouldGenerateSmiCode()) {
7389 ASSERT(kSmiTag == 0); // Adjust code below.
7390 __ tst(smi_test_reg, Operand(kSmiTagMask));
7391 __ b(ne, &not_smi);
7392 __ add(r0, r1, Operand(r0), SetCC); // Add y optimistically.
7393 // Return if no overflow.
7394 __ Ret(vc);
7395 __ sub(r0, r0, Operand(r1)); // Revert optimistic add.
7396 }
7397 HandleBinaryOpSlowCases(masm, &not_smi, lhs, rhs, Builtins::ADD);
Steve Blocka7e24c12009-10-30 11:49:00 +00007398 break;
7399 }
7400
7401 case Token::SUB: {
7402 Label not_smi;
7403 // Fast path.
Steve Block6ded16b2010-05-10 14:33:55 +01007404 if (ShouldGenerateSmiCode()) {
7405 ASSERT(kSmiTag == 0); // Adjust code below.
7406 __ tst(smi_test_reg, Operand(kSmiTagMask));
7407 __ b(ne, &not_smi);
7408 if (lhs.is(r1)) {
7409 __ sub(r0, r1, Operand(r0), SetCC); // Subtract y optimistically.
7410 // Return if no overflow.
7411 __ Ret(vc);
7412 __ sub(r0, r1, Operand(r0)); // Revert optimistic subtract.
7413 } else {
7414 __ sub(r0, r0, Operand(r1), SetCC); // Subtract y optimistically.
7415 // Return if no overflow.
7416 __ Ret(vc);
7417 __ add(r0, r0, Operand(r1)); // Revert optimistic subtract.
7418 }
7419 }
7420 HandleBinaryOpSlowCases(masm, &not_smi, lhs, rhs, Builtins::SUB);
Steve Blocka7e24c12009-10-30 11:49:00 +00007421 break;
7422 }
7423
7424 case Token::MUL: {
7425 Label not_smi, slow;
Steve Block6ded16b2010-05-10 14:33:55 +01007426 if (ShouldGenerateSmiCode()) {
7427 ASSERT(kSmiTag == 0); // adjust code below
7428 __ tst(smi_test_reg, Operand(kSmiTagMask));
7429 Register scratch2 = smi_test_reg;
7430 smi_test_reg = no_reg;
7431 __ b(ne, &not_smi);
7432 // Remove tag from one operand (but keep sign), so that result is Smi.
7433 __ mov(ip, Operand(rhs, ASR, kSmiTagSize));
7434 // Do multiplication
7435 // scratch = lower 32 bits of ip * lhs.
7436 __ smull(scratch, scratch2, lhs, ip);
7437 // Go slow on overflows (overflow bit is not set).
7438 __ mov(ip, Operand(scratch, ASR, 31));
7439 // No overflow if higher 33 bits are identical.
7440 __ cmp(ip, Operand(scratch2));
7441 __ b(ne, &slow);
7442 // Go slow on zero result to handle -0.
7443 __ tst(scratch, Operand(scratch));
7444 __ mov(result, Operand(scratch), LeaveCC, ne);
7445 __ Ret(ne);
7446 // We need -0 if we were multiplying a negative number with 0 to get 0.
7447 // We know one of them was zero.
7448 __ add(scratch2, rhs, Operand(lhs), SetCC);
7449 __ mov(result, Operand(Smi::FromInt(0)), LeaveCC, pl);
7450 __ Ret(pl); // Return Smi 0 if the non-zero one was positive.
7451 // Slow case. We fall through here if we multiplied a negative number
7452 // with 0, because that would mean we should produce -0.
7453 __ bind(&slow);
7454 }
7455 HandleBinaryOpSlowCases(masm, &not_smi, lhs, rhs, Builtins::MUL);
Steve Blocka7e24c12009-10-30 11:49:00 +00007456 break;
7457 }
7458
7459 case Token::DIV:
7460 case Token::MOD: {
7461 Label not_smi;
Steve Block6ded16b2010-05-10 14:33:55 +01007462 if (ShouldGenerateSmiCode() && specialized_on_rhs_) {
Steve Blocka7e24c12009-10-30 11:49:00 +00007463 Label smi_is_unsuitable;
Steve Block6ded16b2010-05-10 14:33:55 +01007464 __ BranchOnNotSmi(lhs, &not_smi);
Steve Blocka7e24c12009-10-30 11:49:00 +00007465 if (IsPowerOf2(constant_rhs_)) {
7466 if (op_ == Token::MOD) {
Steve Block6ded16b2010-05-10 14:33:55 +01007467 __ and_(rhs,
7468 lhs,
Steve Blocka7e24c12009-10-30 11:49:00 +00007469 Operand(0x80000000u | ((constant_rhs_ << kSmiTagSize) - 1)),
7470 SetCC);
7471 // We now have the answer, but if the input was negative we also
7472 // have the sign bit. Our work is done if the result is
7473 // positive or zero:
Steve Block6ded16b2010-05-10 14:33:55 +01007474 if (!rhs.is(r0)) {
7475 __ mov(r0, rhs, LeaveCC, pl);
7476 }
Steve Blocka7e24c12009-10-30 11:49:00 +00007477 __ Ret(pl);
7478 // A mod of a negative left hand side must return a negative number.
7479 // Unfortunately if the answer is 0 then we must return -0. And we
Steve Block6ded16b2010-05-10 14:33:55 +01007480 // already optimistically trashed rhs so we may need to restore it.
7481 __ eor(rhs, rhs, Operand(0x80000000u), SetCC);
Steve Blocka7e24c12009-10-30 11:49:00 +00007482 // Next two instructions are conditional on the answer being -0.
Steve Block6ded16b2010-05-10 14:33:55 +01007483 __ mov(rhs, Operand(Smi::FromInt(constant_rhs_)), LeaveCC, eq);
Steve Blocka7e24c12009-10-30 11:49:00 +00007484 __ b(eq, &smi_is_unsuitable);
7485 // We need to subtract the dividend. Eg. -3 % 4 == -3.
Steve Block6ded16b2010-05-10 14:33:55 +01007486 __ sub(result, rhs, Operand(Smi::FromInt(constant_rhs_)));
Steve Blocka7e24c12009-10-30 11:49:00 +00007487 } else {
7488 ASSERT(op_ == Token::DIV);
Steve Block6ded16b2010-05-10 14:33:55 +01007489 __ tst(lhs,
Steve Blocka7e24c12009-10-30 11:49:00 +00007490 Operand(0x80000000u | ((constant_rhs_ << kSmiTagSize) - 1)));
7491 __ b(ne, &smi_is_unsuitable); // Go slow on negative or remainder.
7492 int shift = 0;
7493 int d = constant_rhs_;
7494 while ((d & 1) == 0) {
7495 d >>= 1;
7496 shift++;
7497 }
Steve Block6ded16b2010-05-10 14:33:55 +01007498 __ mov(r0, Operand(lhs, LSR, shift));
Steve Blocka7e24c12009-10-30 11:49:00 +00007499 __ bic(r0, r0, Operand(kSmiTagMask));
7500 }
7501 } else {
7502 // Not a power of 2.
Steve Block6ded16b2010-05-10 14:33:55 +01007503 __ tst(lhs, Operand(0x80000000u));
Steve Blocka7e24c12009-10-30 11:49:00 +00007504 __ b(ne, &smi_is_unsuitable);
7505 // Find a fixed point reciprocal of the divisor so we can divide by
7506 // multiplying.
7507 double divisor = 1.0 / constant_rhs_;
7508 int shift = 32;
7509 double scale = 4294967296.0; // 1 << 32.
7510 uint32_t mul;
7511 // Maximise the precision of the fixed point reciprocal.
7512 while (true) {
7513 mul = static_cast<uint32_t>(scale * divisor);
7514 if (mul >= 0x7fffffff) break;
7515 scale *= 2.0;
7516 shift++;
7517 }
7518 mul++;
Steve Block6ded16b2010-05-10 14:33:55 +01007519 Register scratch2 = smi_test_reg;
7520 smi_test_reg = no_reg;
7521 __ mov(scratch2, Operand(mul));
7522 __ umull(scratch, scratch2, scratch2, lhs);
7523 __ mov(scratch2, Operand(scratch2, LSR, shift - 31));
7524 // scratch2 is lhs / rhs. scratch2 is not Smi tagged.
7525 // rhs is still the known rhs. rhs is Smi tagged.
7526 // lhs is still the unkown lhs. lhs is Smi tagged.
7527 int required_scratch_shift = 0; // Including the Smi tag shift of 1.
7528 // scratch = scratch2 * rhs.
Steve Blocka7e24c12009-10-30 11:49:00 +00007529 MultiplyByKnownInt2(masm,
Steve Block6ded16b2010-05-10 14:33:55 +01007530 scratch,
7531 scratch2,
7532 rhs,
Steve Blocka7e24c12009-10-30 11:49:00 +00007533 constant_rhs_,
Steve Block6ded16b2010-05-10 14:33:55 +01007534 &required_scratch_shift);
7535 // scratch << required_scratch_shift is now the Smi tagged rhs *
7536 // (lhs / rhs) where / indicates integer division.
Steve Blocka7e24c12009-10-30 11:49:00 +00007537 if (op_ == Token::DIV) {
Steve Block6ded16b2010-05-10 14:33:55 +01007538 __ cmp(lhs, Operand(scratch, LSL, required_scratch_shift));
Steve Blocka7e24c12009-10-30 11:49:00 +00007539 __ b(ne, &smi_is_unsuitable); // There was a remainder.
Steve Block6ded16b2010-05-10 14:33:55 +01007540 __ mov(result, Operand(scratch2, LSL, kSmiTagSize));
Steve Blocka7e24c12009-10-30 11:49:00 +00007541 } else {
7542 ASSERT(op_ == Token::MOD);
Steve Block6ded16b2010-05-10 14:33:55 +01007543 __ sub(result, lhs, Operand(scratch, LSL, required_scratch_shift));
Steve Blocka7e24c12009-10-30 11:49:00 +00007544 }
7545 }
7546 __ Ret();
7547 __ bind(&smi_is_unsuitable);
Steve Blocka7e24c12009-10-30 11:49:00 +00007548 }
Steve Block6ded16b2010-05-10 14:33:55 +01007549 HandleBinaryOpSlowCases(
7550 masm,
7551 &not_smi,
7552 lhs,
7553 rhs,
7554 op_ == Token::MOD ? Builtins::MOD : Builtins::DIV);
Steve Blocka7e24c12009-10-30 11:49:00 +00007555 break;
7556 }
7557
7558 case Token::BIT_OR:
7559 case Token::BIT_AND:
7560 case Token::BIT_XOR:
7561 case Token::SAR:
7562 case Token::SHR:
7563 case Token::SHL: {
7564 Label slow;
7565 ASSERT(kSmiTag == 0); // adjust code below
Steve Block6ded16b2010-05-10 14:33:55 +01007566 __ tst(smi_test_reg, Operand(kSmiTagMask));
Steve Blocka7e24c12009-10-30 11:49:00 +00007567 __ b(ne, &slow);
Steve Block6ded16b2010-05-10 14:33:55 +01007568 Register scratch2 = smi_test_reg;
7569 smi_test_reg = no_reg;
Steve Blocka7e24c12009-10-30 11:49:00 +00007570 switch (op_) {
Steve Block6ded16b2010-05-10 14:33:55 +01007571 case Token::BIT_OR: __ orr(result, rhs, Operand(lhs)); break;
7572 case Token::BIT_AND: __ and_(result, rhs, Operand(lhs)); break;
7573 case Token::BIT_XOR: __ eor(result, rhs, Operand(lhs)); break;
Steve Blocka7e24c12009-10-30 11:49:00 +00007574 case Token::SAR:
7575 // Remove tags from right operand.
Steve Block6ded16b2010-05-10 14:33:55 +01007576 __ GetLeastBitsFromSmi(scratch2, rhs, 5);
7577 __ mov(result, Operand(lhs, ASR, scratch2));
Steve Blocka7e24c12009-10-30 11:49:00 +00007578 // Smi tag result.
Steve Block6ded16b2010-05-10 14:33:55 +01007579 __ bic(result, result, Operand(kSmiTagMask));
Steve Blocka7e24c12009-10-30 11:49:00 +00007580 break;
7581 case Token::SHR:
7582 // Remove tags from operands. We can't do this on a 31 bit number
7583 // because then the 0s get shifted into bit 30 instead of bit 31.
Steve Block6ded16b2010-05-10 14:33:55 +01007584 __ mov(scratch, Operand(lhs, ASR, kSmiTagSize)); // x
7585 __ GetLeastBitsFromSmi(scratch2, rhs, 5);
7586 __ mov(scratch, Operand(scratch, LSR, scratch2));
Steve Blocka7e24c12009-10-30 11:49:00 +00007587 // Unsigned shift is not allowed to produce a negative number, so
7588 // check the sign bit and the sign bit after Smi tagging.
Steve Block6ded16b2010-05-10 14:33:55 +01007589 __ tst(scratch, Operand(0xc0000000));
Steve Blocka7e24c12009-10-30 11:49:00 +00007590 __ b(ne, &slow);
7591 // Smi tag result.
Steve Block6ded16b2010-05-10 14:33:55 +01007592 __ mov(result, Operand(scratch, LSL, kSmiTagSize));
Steve Blocka7e24c12009-10-30 11:49:00 +00007593 break;
7594 case Token::SHL:
7595 // Remove tags from operands.
Steve Block6ded16b2010-05-10 14:33:55 +01007596 __ mov(scratch, Operand(lhs, ASR, kSmiTagSize)); // x
7597 __ GetLeastBitsFromSmi(scratch2, rhs, 5);
7598 __ mov(scratch, Operand(scratch, LSL, scratch2));
Steve Blocka7e24c12009-10-30 11:49:00 +00007599 // Check that the signed result fits in a Smi.
Steve Block6ded16b2010-05-10 14:33:55 +01007600 __ add(scratch2, scratch, Operand(0x40000000), SetCC);
Steve Blocka7e24c12009-10-30 11:49:00 +00007601 __ b(mi, &slow);
Steve Block6ded16b2010-05-10 14:33:55 +01007602 __ mov(result, Operand(scratch, LSL, kSmiTagSize));
Steve Blocka7e24c12009-10-30 11:49:00 +00007603 break;
7604 default: UNREACHABLE();
7605 }
7606 __ Ret();
7607 __ bind(&slow);
Steve Block6ded16b2010-05-10 14:33:55 +01007608 HandleNonSmiBitwiseOp(masm, lhs, rhs);
Steve Blocka7e24c12009-10-30 11:49:00 +00007609 break;
7610 }
7611
7612 default: UNREACHABLE();
7613 }
7614 // This code should be unreachable.
7615 __ stop("Unreachable");
Steve Block6ded16b2010-05-10 14:33:55 +01007616
7617 // Generate an unreachable reference to the DEFAULT stub so that it can be
7618 // found at the end of this stub when clearing ICs at GC.
7619 // TODO(kaznacheev): Check performance impact and get rid of this.
7620 if (runtime_operands_type_ != BinaryOpIC::DEFAULT) {
7621 GenericBinaryOpStub uninit(MinorKey(), BinaryOpIC::DEFAULT);
7622 __ CallStub(&uninit);
7623 }
7624}
7625
7626
7627void GenericBinaryOpStub::GenerateTypeTransition(MacroAssembler* masm) {
7628 Label get_result;
7629
7630 __ Push(r1, r0);
7631
7632 // Internal frame is necessary to handle exceptions properly.
7633 __ EnterInternalFrame();
7634 // Call the stub proper to get the result in r0.
7635 __ Call(&get_result);
7636 __ LeaveInternalFrame();
7637
7638 __ push(r0);
7639
7640 __ mov(r0, Operand(Smi::FromInt(MinorKey())));
7641 __ push(r0);
7642 __ mov(r0, Operand(Smi::FromInt(op_)));
7643 __ push(r0);
7644 __ mov(r0, Operand(Smi::FromInt(runtime_operands_type_)));
7645 __ push(r0);
7646
7647 __ TailCallExternalReference(
7648 ExternalReference(IC_Utility(IC::kBinaryOp_Patch)),
7649 6,
7650 1);
7651
7652 // The entry point for the result calculation is assumed to be immediately
7653 // after this sequence.
7654 __ bind(&get_result);
7655}
7656
7657
7658Handle<Code> GetBinaryOpStub(int key, BinaryOpIC::TypeInfo type_info) {
7659 GenericBinaryOpStub stub(key, type_info);
7660 return stub.GetCode();
Steve Blocka7e24c12009-10-30 11:49:00 +00007661}
7662
7663
7664void StackCheckStub::Generate(MacroAssembler* masm) {
7665 // Do tail-call to runtime routine. Runtime routines expect at least one
7666 // argument, so give it a Smi.
7667 __ mov(r0, Operand(Smi::FromInt(0)));
7668 __ push(r0);
Steve Block6ded16b2010-05-10 14:33:55 +01007669 __ TailCallRuntime(Runtime::kStackGuard, 1, 1);
Steve Blocka7e24c12009-10-30 11:49:00 +00007670
7671 __ StubReturn(1);
7672}
7673
7674
Leon Clarkee46be812010-01-19 14:06:41 +00007675void GenericUnaryOpStub::Generate(MacroAssembler* masm) {
Leon Clarke4515c472010-02-03 11:58:03 +00007676 Label slow, done;
Leon Clarkee46be812010-01-19 14:06:41 +00007677
Leon Clarke4515c472010-02-03 11:58:03 +00007678 if (op_ == Token::SUB) {
7679 // Check whether the value is a smi.
7680 Label try_float;
7681 __ tst(r0, Operand(kSmiTagMask));
7682 __ b(ne, &try_float);
Steve Blocka7e24c12009-10-30 11:49:00 +00007683
Leon Clarke4515c472010-02-03 11:58:03 +00007684 // Go slow case if the value of the expression is zero
7685 // to make sure that we switch between 0 and -0.
7686 __ cmp(r0, Operand(0));
7687 __ b(eq, &slow);
Steve Blocka7e24c12009-10-30 11:49:00 +00007688
Leon Clarke4515c472010-02-03 11:58:03 +00007689 // The value of the expression is a smi that is not zero. Try
7690 // optimistic subtraction '0 - value'.
7691 __ rsb(r1, r0, Operand(0), SetCC);
7692 __ b(vs, &slow);
Steve Blocka7e24c12009-10-30 11:49:00 +00007693
Leon Clarke4515c472010-02-03 11:58:03 +00007694 __ mov(r0, Operand(r1)); // Set r0 to result.
7695 __ b(&done);
Steve Blocka7e24c12009-10-30 11:49:00 +00007696
Leon Clarke4515c472010-02-03 11:58:03 +00007697 __ bind(&try_float);
7698 __ CompareObjectType(r0, r1, r1, HEAP_NUMBER_TYPE);
7699 __ b(ne, &slow);
7700 // r0 is a heap number. Get a new heap number in r1.
7701 if (overwrite_) {
7702 __ ldr(r2, FieldMemOperand(r0, HeapNumber::kExponentOffset));
7703 __ eor(r2, r2, Operand(HeapNumber::kSignMask)); // Flip sign.
7704 __ str(r2, FieldMemOperand(r0, HeapNumber::kExponentOffset));
7705 } else {
Steve Block6ded16b2010-05-10 14:33:55 +01007706 __ AllocateHeapNumber(r1, r2, r3, &slow);
Leon Clarke4515c472010-02-03 11:58:03 +00007707 __ ldr(r3, FieldMemOperand(r0, HeapNumber::kMantissaOffset));
7708 __ ldr(r2, FieldMemOperand(r0, HeapNumber::kExponentOffset));
7709 __ str(r3, FieldMemOperand(r1, HeapNumber::kMantissaOffset));
7710 __ eor(r2, r2, Operand(HeapNumber::kSignMask)); // Flip sign.
7711 __ str(r2, FieldMemOperand(r1, HeapNumber::kExponentOffset));
7712 __ mov(r0, Operand(r1));
7713 }
7714 } else if (op_ == Token::BIT_NOT) {
7715 // Check if the operand is a heap number.
7716 __ CompareObjectType(r0, r1, r1, HEAP_NUMBER_TYPE);
7717 __ b(ne, &slow);
7718
7719 // Convert the heap number is r0 to an untagged integer in r1.
7720 GetInt32(masm, r0, r1, r2, r3, &slow);
7721
7722 // Do the bitwise operation (move negated) and check if the result
7723 // fits in a smi.
7724 Label try_float;
7725 __ mvn(r1, Operand(r1));
7726 __ add(r2, r1, Operand(0x40000000), SetCC);
7727 __ b(mi, &try_float);
7728 __ mov(r0, Operand(r1, LSL, kSmiTagSize));
7729 __ b(&done);
7730
7731 __ bind(&try_float);
7732 if (!overwrite_) {
7733 // Allocate a fresh heap number, but don't overwrite r0 until
7734 // we're sure we can do it without going through the slow case
7735 // that needs the value in r0.
Steve Block6ded16b2010-05-10 14:33:55 +01007736 __ AllocateHeapNumber(r2, r3, r4, &slow);
Leon Clarke4515c472010-02-03 11:58:03 +00007737 __ mov(r0, Operand(r2));
7738 }
7739
7740 // WriteInt32ToHeapNumberStub does not trigger GC, so we do not
7741 // have to set up a frame.
7742 WriteInt32ToHeapNumberStub stub(r1, r0, r2);
7743 __ push(lr);
7744 __ Call(stub.GetCode(), RelocInfo::CODE_TARGET);
7745 __ pop(lr);
7746 } else {
7747 UNIMPLEMENTED();
7748 }
7749
7750 __ bind(&done);
Steve Blocka7e24c12009-10-30 11:49:00 +00007751 __ StubReturn(1);
7752
Leon Clarke4515c472010-02-03 11:58:03 +00007753 // Handle the slow case by jumping to the JavaScript builtin.
Steve Blocka7e24c12009-10-30 11:49:00 +00007754 __ bind(&slow);
7755 __ push(r0);
Leon Clarke4515c472010-02-03 11:58:03 +00007756 switch (op_) {
7757 case Token::SUB:
7758 __ InvokeBuiltin(Builtins::UNARY_MINUS, JUMP_JS);
7759 break;
7760 case Token::BIT_NOT:
7761 __ InvokeBuiltin(Builtins::BIT_NOT, JUMP_JS);
7762 break;
7763 default:
7764 UNREACHABLE();
Steve Blocka7e24c12009-10-30 11:49:00 +00007765 }
Steve Blocka7e24c12009-10-30 11:49:00 +00007766}
7767
7768
7769void CEntryStub::GenerateThrowTOS(MacroAssembler* masm) {
7770 // r0 holds the exception.
7771
7772 // Adjust this code if not the case.
7773 ASSERT(StackHandlerConstants::kSize == 4 * kPointerSize);
7774
7775 // Drop the sp to the top of the handler.
7776 __ mov(r3, Operand(ExternalReference(Top::k_handler_address)));
7777 __ ldr(sp, MemOperand(r3));
7778
7779 // Restore the next handler and frame pointer, discard handler state.
7780 ASSERT(StackHandlerConstants::kNextOffset == 0);
7781 __ pop(r2);
7782 __ str(r2, MemOperand(r3));
7783 ASSERT(StackHandlerConstants::kFPOffset == 2 * kPointerSize);
7784 __ ldm(ia_w, sp, r3.bit() | fp.bit()); // r3: discarded state.
7785
7786 // Before returning we restore the context from the frame pointer if
7787 // not NULL. The frame pointer is NULL in the exception handler of a
7788 // JS entry frame.
7789 __ cmp(fp, Operand(0));
7790 // Set cp to NULL if fp is NULL.
7791 __ mov(cp, Operand(0), LeaveCC, eq);
7792 // Restore cp otherwise.
7793 __ ldr(cp, MemOperand(fp, StandardFrameConstants::kContextOffset), ne);
7794#ifdef DEBUG
7795 if (FLAG_debug_code) {
7796 __ mov(lr, Operand(pc));
7797 }
7798#endif
7799 ASSERT(StackHandlerConstants::kPCOffset == 3 * kPointerSize);
7800 __ pop(pc);
7801}
7802
7803
7804void CEntryStub::GenerateThrowUncatchable(MacroAssembler* masm,
7805 UncatchableExceptionType type) {
7806 // Adjust this code if not the case.
7807 ASSERT(StackHandlerConstants::kSize == 4 * kPointerSize);
7808
7809 // Drop sp to the top stack handler.
7810 __ mov(r3, Operand(ExternalReference(Top::k_handler_address)));
7811 __ ldr(sp, MemOperand(r3));
7812
7813 // Unwind the handlers until the ENTRY handler is found.
7814 Label loop, done;
7815 __ bind(&loop);
7816 // Load the type of the current stack handler.
7817 const int kStateOffset = StackHandlerConstants::kStateOffset;
7818 __ ldr(r2, MemOperand(sp, kStateOffset));
7819 __ cmp(r2, Operand(StackHandler::ENTRY));
7820 __ b(eq, &done);
7821 // Fetch the next handler in the list.
7822 const int kNextOffset = StackHandlerConstants::kNextOffset;
7823 __ ldr(sp, MemOperand(sp, kNextOffset));
7824 __ jmp(&loop);
7825 __ bind(&done);
7826
7827 // Set the top handler address to next handler past the current ENTRY handler.
7828 ASSERT(StackHandlerConstants::kNextOffset == 0);
7829 __ pop(r2);
7830 __ str(r2, MemOperand(r3));
7831
7832 if (type == OUT_OF_MEMORY) {
7833 // Set external caught exception to false.
7834 ExternalReference external_caught(Top::k_external_caught_exception_address);
7835 __ mov(r0, Operand(false));
7836 __ mov(r2, Operand(external_caught));
7837 __ str(r0, MemOperand(r2));
7838
7839 // Set pending exception and r0 to out of memory exception.
7840 Failure* out_of_memory = Failure::OutOfMemoryException();
7841 __ mov(r0, Operand(reinterpret_cast<int32_t>(out_of_memory)));
7842 __ mov(r2, Operand(ExternalReference(Top::k_pending_exception_address)));
7843 __ str(r0, MemOperand(r2));
7844 }
7845
7846 // Stack layout at this point. See also StackHandlerConstants.
7847 // sp -> state (ENTRY)
7848 // fp
7849 // lr
7850
7851 // Discard handler state (r2 is not used) and restore frame pointer.
7852 ASSERT(StackHandlerConstants::kFPOffset == 2 * kPointerSize);
7853 __ ldm(ia_w, sp, r2.bit() | fp.bit()); // r2: discarded state.
7854 // Before returning we restore the context from the frame pointer if
7855 // not NULL. The frame pointer is NULL in the exception handler of a
7856 // JS entry frame.
7857 __ cmp(fp, Operand(0));
7858 // Set cp to NULL if fp is NULL.
7859 __ mov(cp, Operand(0), LeaveCC, eq);
7860 // Restore cp otherwise.
7861 __ ldr(cp, MemOperand(fp, StandardFrameConstants::kContextOffset), ne);
7862#ifdef DEBUG
7863 if (FLAG_debug_code) {
7864 __ mov(lr, Operand(pc));
7865 }
7866#endif
7867 ASSERT(StackHandlerConstants::kPCOffset == 3 * kPointerSize);
7868 __ pop(pc);
7869}
7870
7871
7872void CEntryStub::GenerateCore(MacroAssembler* masm,
7873 Label* throw_normal_exception,
7874 Label* throw_termination_exception,
7875 Label* throw_out_of_memory_exception,
Steve Blocka7e24c12009-10-30 11:49:00 +00007876 bool do_gc,
Steve Block6ded16b2010-05-10 14:33:55 +01007877 bool always_allocate,
7878 int frame_alignment_skew) {
Steve Blocka7e24c12009-10-30 11:49:00 +00007879 // r0: result parameter for PerformGC, if any
7880 // r4: number of arguments including receiver (C callee-saved)
7881 // r5: pointer to builtin function (C callee-saved)
7882 // r6: pointer to the first argument (C callee-saved)
7883
7884 if (do_gc) {
7885 // Passing r0.
Steve Block6ded16b2010-05-10 14:33:55 +01007886 __ PrepareCallCFunction(1, r1);
7887 __ CallCFunction(ExternalReference::perform_gc_function(), 1);
Steve Blocka7e24c12009-10-30 11:49:00 +00007888 }
7889
7890 ExternalReference scope_depth =
7891 ExternalReference::heap_always_allocate_scope_depth();
7892 if (always_allocate) {
7893 __ mov(r0, Operand(scope_depth));
7894 __ ldr(r1, MemOperand(r0));
7895 __ add(r1, r1, Operand(1));
7896 __ str(r1, MemOperand(r0));
7897 }
7898
7899 // Call C built-in.
7900 // r0 = argc, r1 = argv
7901 __ mov(r0, Operand(r4));
7902 __ mov(r1, Operand(r6));
7903
Steve Block6ded16b2010-05-10 14:33:55 +01007904 int frame_alignment = MacroAssembler::ActivationFrameAlignment();
7905 int frame_alignment_mask = frame_alignment - 1;
7906#if defined(V8_HOST_ARCH_ARM)
7907 if (FLAG_debug_code) {
7908 if (frame_alignment > kPointerSize) {
7909 Label alignment_as_expected;
7910 ASSERT(IsPowerOf2(frame_alignment));
7911 __ sub(r2, sp, Operand(frame_alignment_skew));
7912 __ tst(r2, Operand(frame_alignment_mask));
7913 __ b(eq, &alignment_as_expected);
7914 // Don't use Check here, as it will call Runtime_Abort re-entering here.
7915 __ stop("Unexpected alignment");
7916 __ bind(&alignment_as_expected);
7917 }
7918 }
7919#endif
7920
7921 // Just before the call (jump) below lr is pushed, so the actual alignment is
7922 // adding one to the current skew.
7923 int alignment_before_call =
7924 (frame_alignment_skew + kPointerSize) & frame_alignment_mask;
7925 if (alignment_before_call > 0) {
7926 // Push until the alignment before the call is met.
7927 __ mov(r2, Operand(0));
7928 for (int i = alignment_before_call;
7929 (i & frame_alignment_mask) != 0;
7930 i += kPointerSize) {
7931 __ push(r2);
7932 }
7933 }
7934
Steve Blocka7e24c12009-10-30 11:49:00 +00007935 // TODO(1242173): To let the GC traverse the return address of the exit
7936 // frames, we need to know where the return address is. Right now,
7937 // we push it on the stack to be able to find it again, but we never
7938 // restore from it in case of changes, which makes it impossible to
7939 // support moving the C entry code stub. This should be fixed, but currently
7940 // this is OK because the CEntryStub gets generated so early in the V8 boot
7941 // sequence that it is not moving ever.
Steve Block6ded16b2010-05-10 14:33:55 +01007942 masm->add(lr, pc, Operand(4)); // Compute return address: (pc + 8) + 4
Steve Blocka7e24c12009-10-30 11:49:00 +00007943 masm->push(lr);
7944 masm->Jump(r5);
7945
Steve Block6ded16b2010-05-10 14:33:55 +01007946 // Restore sp back to before aligning the stack.
7947 if (alignment_before_call > 0) {
7948 __ add(sp, sp, Operand(alignment_before_call));
7949 }
7950
Steve Blocka7e24c12009-10-30 11:49:00 +00007951 if (always_allocate) {
7952 // It's okay to clobber r2 and r3 here. Don't mess with r0 and r1
7953 // though (contain the result).
7954 __ mov(r2, Operand(scope_depth));
7955 __ ldr(r3, MemOperand(r2));
7956 __ sub(r3, r3, Operand(1));
7957 __ str(r3, MemOperand(r2));
7958 }
7959
7960 // check for failure result
7961 Label failure_returned;
7962 ASSERT(((kFailureTag + 1) & kFailureTagMask) == 0);
7963 // Lower 2 bits of r2 are 0 iff r0 has failure tag.
7964 __ add(r2, r0, Operand(1));
7965 __ tst(r2, Operand(kFailureTagMask));
7966 __ b(eq, &failure_returned);
7967
7968 // Exit C frame and return.
7969 // r0:r1: result
7970 // sp: stack pointer
7971 // fp: frame pointer
Leon Clarke4515c472010-02-03 11:58:03 +00007972 __ LeaveExitFrame(mode_);
Steve Blocka7e24c12009-10-30 11:49:00 +00007973
7974 // check if we should retry or throw exception
7975 Label retry;
7976 __ bind(&failure_returned);
7977 ASSERT(Failure::RETRY_AFTER_GC == 0);
7978 __ tst(r0, Operand(((1 << kFailureTypeTagSize) - 1) << kFailureTagSize));
7979 __ b(eq, &retry);
7980
7981 // Special handling of out of memory exceptions.
7982 Failure* out_of_memory = Failure::OutOfMemoryException();
7983 __ cmp(r0, Operand(reinterpret_cast<int32_t>(out_of_memory)));
7984 __ b(eq, throw_out_of_memory_exception);
7985
7986 // Retrieve the pending exception and clear the variable.
7987 __ mov(ip, Operand(ExternalReference::the_hole_value_location()));
7988 __ ldr(r3, MemOperand(ip));
7989 __ mov(ip, Operand(ExternalReference(Top::k_pending_exception_address)));
7990 __ ldr(r0, MemOperand(ip));
7991 __ str(r3, MemOperand(ip));
7992
7993 // Special handling of termination exceptions which are uncatchable
7994 // by javascript code.
7995 __ cmp(r0, Operand(Factory::termination_exception()));
7996 __ b(eq, throw_termination_exception);
7997
7998 // Handle normal exception.
7999 __ jmp(throw_normal_exception);
8000
8001 __ bind(&retry); // pass last failure (r0) as parameter (r0) when retrying
8002}
8003
8004
Leon Clarke4515c472010-02-03 11:58:03 +00008005void CEntryStub::Generate(MacroAssembler* masm) {
Steve Blocka7e24c12009-10-30 11:49:00 +00008006 // Called from JavaScript; parameters are on stack as if calling JS function
8007 // r0: number of arguments including receiver
8008 // r1: pointer to builtin function
8009 // fp: frame pointer (restored after C call)
8010 // sp: stack pointer (restored as callee's sp after C call)
8011 // cp: current context (C callee-saved)
8012
Leon Clarke4515c472010-02-03 11:58:03 +00008013 // Result returned in r0 or r0+r1 by default.
8014
Steve Blocka7e24c12009-10-30 11:49:00 +00008015 // NOTE: Invocations of builtins may return failure objects
8016 // instead of a proper result. The builtin entry handles
8017 // this by performing a garbage collection and retrying the
8018 // builtin once.
8019
Steve Blocka7e24c12009-10-30 11:49:00 +00008020 // Enter the exit frame that transitions from JavaScript to C++.
Leon Clarke4515c472010-02-03 11:58:03 +00008021 __ EnterExitFrame(mode_);
Steve Blocka7e24c12009-10-30 11:49:00 +00008022
8023 // r4: number of arguments (C callee-saved)
8024 // r5: pointer to builtin function (C callee-saved)
8025 // r6: pointer to first argument (C callee-saved)
8026
8027 Label throw_normal_exception;
8028 Label throw_termination_exception;
8029 Label throw_out_of_memory_exception;
8030
8031 // Call into the runtime system.
8032 GenerateCore(masm,
8033 &throw_normal_exception,
8034 &throw_termination_exception,
8035 &throw_out_of_memory_exception,
Steve Blocka7e24c12009-10-30 11:49:00 +00008036 false,
Steve Block6ded16b2010-05-10 14:33:55 +01008037 false,
8038 -kPointerSize);
Steve Blocka7e24c12009-10-30 11:49:00 +00008039
8040 // Do space-specific GC and retry runtime call.
8041 GenerateCore(masm,
8042 &throw_normal_exception,
8043 &throw_termination_exception,
8044 &throw_out_of_memory_exception,
Steve Blocka7e24c12009-10-30 11:49:00 +00008045 true,
Steve Block6ded16b2010-05-10 14:33:55 +01008046 false,
8047 0);
Steve Blocka7e24c12009-10-30 11:49:00 +00008048
8049 // Do full GC and retry runtime call one final time.
8050 Failure* failure = Failure::InternalError();
8051 __ mov(r0, Operand(reinterpret_cast<int32_t>(failure)));
8052 GenerateCore(masm,
8053 &throw_normal_exception,
8054 &throw_termination_exception,
8055 &throw_out_of_memory_exception,
Steve Blocka7e24c12009-10-30 11:49:00 +00008056 true,
Steve Block6ded16b2010-05-10 14:33:55 +01008057 true,
8058 kPointerSize);
Steve Blocka7e24c12009-10-30 11:49:00 +00008059
8060 __ bind(&throw_out_of_memory_exception);
8061 GenerateThrowUncatchable(masm, OUT_OF_MEMORY);
8062
8063 __ bind(&throw_termination_exception);
8064 GenerateThrowUncatchable(masm, TERMINATION);
8065
8066 __ bind(&throw_normal_exception);
8067 GenerateThrowTOS(masm);
8068}
8069
8070
8071void JSEntryStub::GenerateBody(MacroAssembler* masm, bool is_construct) {
8072 // r0: code entry
8073 // r1: function
8074 // r2: receiver
8075 // r3: argc
8076 // [sp+0]: argv
8077
8078 Label invoke, exit;
8079
8080 // Called from C, so do not pop argc and args on exit (preserve sp)
8081 // No need to save register-passed args
8082 // Save callee-saved registers (incl. cp and fp), sp, and lr
8083 __ stm(db_w, sp, kCalleeSaved | lr.bit());
8084
8085 // Get address of argv, see stm above.
8086 // r0: code entry
8087 // r1: function
8088 // r2: receiver
8089 // r3: argc
Leon Clarke4515c472010-02-03 11:58:03 +00008090 __ ldr(r4, MemOperand(sp, (kNumCalleeSaved + 1) * kPointerSize)); // argv
Steve Blocka7e24c12009-10-30 11:49:00 +00008091
8092 // Push a frame with special values setup to mark it as an entry frame.
8093 // r0: code entry
8094 // r1: function
8095 // r2: receiver
8096 // r3: argc
8097 // r4: argv
8098 __ mov(r8, Operand(-1)); // Push a bad frame pointer to fail if it is used.
8099 int marker = is_construct ? StackFrame::ENTRY_CONSTRUCT : StackFrame::ENTRY;
8100 __ mov(r7, Operand(Smi::FromInt(marker)));
8101 __ mov(r6, Operand(Smi::FromInt(marker)));
8102 __ mov(r5, Operand(ExternalReference(Top::k_c_entry_fp_address)));
8103 __ ldr(r5, MemOperand(r5));
Steve Block6ded16b2010-05-10 14:33:55 +01008104 __ Push(r8, r7, r6, r5);
Steve Blocka7e24c12009-10-30 11:49:00 +00008105
8106 // Setup frame pointer for the frame to be pushed.
8107 __ add(fp, sp, Operand(-EntryFrameConstants::kCallerFPOffset));
8108
8109 // Call a faked try-block that does the invoke.
8110 __ bl(&invoke);
8111
8112 // Caught exception: Store result (exception) in the pending
8113 // exception field in the JSEnv and return a failure sentinel.
8114 // Coming in here the fp will be invalid because the PushTryHandler below
8115 // sets it to 0 to signal the existence of the JSEntry frame.
8116 __ mov(ip, Operand(ExternalReference(Top::k_pending_exception_address)));
8117 __ str(r0, MemOperand(ip));
8118 __ mov(r0, Operand(reinterpret_cast<int32_t>(Failure::Exception())));
8119 __ b(&exit);
8120
8121 // Invoke: Link this frame into the handler chain.
8122 __ bind(&invoke);
8123 // Must preserve r0-r4, r5-r7 are available.
8124 __ PushTryHandler(IN_JS_ENTRY, JS_ENTRY_HANDLER);
8125 // If an exception not caught by another handler occurs, this handler
8126 // returns control to the code after the bl(&invoke) above, which
8127 // restores all kCalleeSaved registers (including cp and fp) to their
8128 // saved values before returning a failure to C.
8129
8130 // Clear any pending exceptions.
8131 __ mov(ip, Operand(ExternalReference::the_hole_value_location()));
8132 __ ldr(r5, MemOperand(ip));
8133 __ mov(ip, Operand(ExternalReference(Top::k_pending_exception_address)));
8134 __ str(r5, MemOperand(ip));
8135
8136 // Invoke the function by calling through JS entry trampoline builtin.
8137 // Notice that we cannot store a reference to the trampoline code directly in
8138 // this stub, because runtime stubs are not traversed when doing GC.
8139
8140 // Expected registers by Builtins::JSEntryTrampoline
8141 // r0: code entry
8142 // r1: function
8143 // r2: receiver
8144 // r3: argc
8145 // r4: argv
8146 if (is_construct) {
8147 ExternalReference construct_entry(Builtins::JSConstructEntryTrampoline);
8148 __ mov(ip, Operand(construct_entry));
8149 } else {
8150 ExternalReference entry(Builtins::JSEntryTrampoline);
8151 __ mov(ip, Operand(entry));
8152 }
8153 __ ldr(ip, MemOperand(ip)); // deref address
8154
8155 // Branch and link to JSEntryTrampoline. We don't use the double underscore
8156 // macro for the add instruction because we don't want the coverage tool
8157 // inserting instructions here after we read the pc.
8158 __ mov(lr, Operand(pc));
8159 masm->add(pc, ip, Operand(Code::kHeaderSize - kHeapObjectTag));
8160
8161 // Unlink this frame from the handler chain. When reading the
8162 // address of the next handler, there is no need to use the address
8163 // displacement since the current stack pointer (sp) points directly
8164 // to the stack handler.
8165 __ ldr(r3, MemOperand(sp, StackHandlerConstants::kNextOffset));
8166 __ mov(ip, Operand(ExternalReference(Top::k_handler_address)));
8167 __ str(r3, MemOperand(ip));
8168 // No need to restore registers
8169 __ add(sp, sp, Operand(StackHandlerConstants::kSize));
8170
8171
8172 __ bind(&exit); // r0 holds result
8173 // Restore the top frame descriptors from the stack.
8174 __ pop(r3);
8175 __ mov(ip, Operand(ExternalReference(Top::k_c_entry_fp_address)));
8176 __ str(r3, MemOperand(ip));
8177
8178 // Reset the stack to the callee saved registers.
8179 __ add(sp, sp, Operand(-EntryFrameConstants::kCallerFPOffset));
8180
8181 // Restore callee-saved registers and return.
8182#ifdef DEBUG
8183 if (FLAG_debug_code) {
8184 __ mov(lr, Operand(pc));
8185 }
8186#endif
8187 __ ldm(ia_w, sp, kCalleeSaved | pc.bit());
8188}
8189
8190
8191// This stub performs an instanceof, calling the builtin function if
8192// necessary. Uses r1 for the object, r0 for the function that it may
8193// be an instance of (these are fetched from the stack).
8194void InstanceofStub::Generate(MacroAssembler* masm) {
8195 // Get the object - slow case for smis (we may need to throw an exception
8196 // depending on the rhs).
8197 Label slow, loop, is_instance, is_not_instance;
8198 __ ldr(r0, MemOperand(sp, 1 * kPointerSize));
8199 __ BranchOnSmi(r0, &slow);
8200
8201 // Check that the left hand is a JS object and put map in r3.
8202 __ CompareObjectType(r0, r3, r2, FIRST_JS_OBJECT_TYPE);
8203 __ b(lt, &slow);
8204 __ cmp(r2, Operand(LAST_JS_OBJECT_TYPE));
8205 __ b(gt, &slow);
8206
8207 // Get the prototype of the function (r4 is result, r2 is scratch).
Andrei Popescu402d9372010-02-26 13:31:12 +00008208 __ ldr(r1, MemOperand(sp, 0));
Steve Blocka7e24c12009-10-30 11:49:00 +00008209 __ TryGetFunctionPrototype(r1, r4, r2, &slow);
8210
8211 // Check that the function prototype is a JS object.
8212 __ BranchOnSmi(r4, &slow);
8213 __ CompareObjectType(r4, r5, r5, FIRST_JS_OBJECT_TYPE);
8214 __ b(lt, &slow);
8215 __ cmp(r5, Operand(LAST_JS_OBJECT_TYPE));
8216 __ b(gt, &slow);
8217
8218 // Register mapping: r3 is object map and r4 is function prototype.
8219 // Get prototype of object into r2.
8220 __ ldr(r2, FieldMemOperand(r3, Map::kPrototypeOffset));
8221
8222 // Loop through the prototype chain looking for the function prototype.
8223 __ bind(&loop);
8224 __ cmp(r2, Operand(r4));
8225 __ b(eq, &is_instance);
8226 __ LoadRoot(ip, Heap::kNullValueRootIndex);
8227 __ cmp(r2, ip);
8228 __ b(eq, &is_not_instance);
8229 __ ldr(r2, FieldMemOperand(r2, HeapObject::kMapOffset));
8230 __ ldr(r2, FieldMemOperand(r2, Map::kPrototypeOffset));
8231 __ jmp(&loop);
8232
8233 __ bind(&is_instance);
8234 __ mov(r0, Operand(Smi::FromInt(0)));
8235 __ pop();
8236 __ pop();
8237 __ mov(pc, Operand(lr)); // Return.
8238
8239 __ bind(&is_not_instance);
8240 __ mov(r0, Operand(Smi::FromInt(1)));
8241 __ pop();
8242 __ pop();
8243 __ mov(pc, Operand(lr)); // Return.
8244
8245 // Slow-case. Tail call builtin.
8246 __ bind(&slow);
Steve Blocka7e24c12009-10-30 11:49:00 +00008247 __ InvokeBuiltin(Builtins::INSTANCE_OF, JUMP_JS);
8248}
8249
8250
Steve Blocka7e24c12009-10-30 11:49:00 +00008251void ArgumentsAccessStub::GenerateReadElement(MacroAssembler* masm) {
8252 // The displacement is the offset of the last parameter (if any)
8253 // relative to the frame pointer.
8254 static const int kDisplacement =
8255 StandardFrameConstants::kCallerSPOffset - kPointerSize;
8256
8257 // Check that the key is a smi.
8258 Label slow;
8259 __ BranchOnNotSmi(r1, &slow);
8260
8261 // Check if the calling frame is an arguments adaptor frame.
8262 Label adaptor;
8263 __ ldr(r2, MemOperand(fp, StandardFrameConstants::kCallerFPOffset));
8264 __ ldr(r3, MemOperand(r2, StandardFrameConstants::kContextOffset));
8265 __ cmp(r3, Operand(Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR)));
8266 __ b(eq, &adaptor);
8267
8268 // Check index against formal parameters count limit passed in
Steve Blockd0582a62009-12-15 09:54:21 +00008269 // through register r0. Use unsigned comparison to get negative
Steve Blocka7e24c12009-10-30 11:49:00 +00008270 // check for free.
8271 __ cmp(r1, r0);
8272 __ b(cs, &slow);
8273
8274 // Read the argument from the stack and return it.
8275 __ sub(r3, r0, r1);
8276 __ add(r3, fp, Operand(r3, LSL, kPointerSizeLog2 - kSmiTagSize));
8277 __ ldr(r0, MemOperand(r3, kDisplacement));
8278 __ Jump(lr);
8279
8280 // Arguments adaptor case: Check index against actual arguments
8281 // limit found in the arguments adaptor frame. Use unsigned
8282 // comparison to get negative check for free.
8283 __ bind(&adaptor);
8284 __ ldr(r0, MemOperand(r2, ArgumentsAdaptorFrameConstants::kLengthOffset));
8285 __ cmp(r1, r0);
8286 __ b(cs, &slow);
8287
8288 // Read the argument from the adaptor frame and return it.
8289 __ sub(r3, r0, r1);
8290 __ add(r3, r2, Operand(r3, LSL, kPointerSizeLog2 - kSmiTagSize));
8291 __ ldr(r0, MemOperand(r3, kDisplacement));
8292 __ Jump(lr);
8293
8294 // Slow-case: Handle non-smi or out-of-bounds access to arguments
8295 // by calling the runtime system.
8296 __ bind(&slow);
8297 __ push(r1);
Steve Block6ded16b2010-05-10 14:33:55 +01008298 __ TailCallRuntime(Runtime::kGetArgumentsProperty, 1, 1);
Steve Blocka7e24c12009-10-30 11:49:00 +00008299}
8300
8301
8302void ArgumentsAccessStub::GenerateNewObject(MacroAssembler* masm) {
Andrei Popescu402d9372010-02-26 13:31:12 +00008303 // sp[0] : number of parameters
8304 // sp[4] : receiver displacement
8305 // sp[8] : function
8306
Steve Blocka7e24c12009-10-30 11:49:00 +00008307 // Check if the calling frame is an arguments adaptor frame.
Andrei Popescu402d9372010-02-26 13:31:12 +00008308 Label adaptor_frame, try_allocate, runtime;
Steve Blocka7e24c12009-10-30 11:49:00 +00008309 __ ldr(r2, MemOperand(fp, StandardFrameConstants::kCallerFPOffset));
8310 __ ldr(r3, MemOperand(r2, StandardFrameConstants::kContextOffset));
8311 __ cmp(r3, Operand(Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR)));
Andrei Popescu402d9372010-02-26 13:31:12 +00008312 __ b(eq, &adaptor_frame);
8313
8314 // Get the length from the frame.
8315 __ ldr(r1, MemOperand(sp, 0));
8316 __ b(&try_allocate);
Steve Blocka7e24c12009-10-30 11:49:00 +00008317
8318 // Patch the arguments.length and the parameters pointer.
Andrei Popescu402d9372010-02-26 13:31:12 +00008319 __ bind(&adaptor_frame);
8320 __ ldr(r1, MemOperand(r2, ArgumentsAdaptorFrameConstants::kLengthOffset));
8321 __ str(r1, MemOperand(sp, 0));
8322 __ add(r3, r2, Operand(r1, LSL, kPointerSizeLog2 - kSmiTagSize));
Steve Blocka7e24c12009-10-30 11:49:00 +00008323 __ add(r3, r3, Operand(StandardFrameConstants::kCallerSPOffset));
8324 __ str(r3, MemOperand(sp, 1 * kPointerSize));
8325
Andrei Popescu402d9372010-02-26 13:31:12 +00008326 // Try the new space allocation. Start out with computing the size
8327 // of the arguments object and the elements array (in words, not
8328 // bytes because AllocateInNewSpace expects words).
8329 Label add_arguments_object;
8330 __ bind(&try_allocate);
8331 __ cmp(r1, Operand(0));
8332 __ b(eq, &add_arguments_object);
8333 __ mov(r1, Operand(r1, LSR, kSmiTagSize));
8334 __ add(r1, r1, Operand(FixedArray::kHeaderSize / kPointerSize));
8335 __ bind(&add_arguments_object);
8336 __ add(r1, r1, Operand(Heap::kArgumentsObjectSize / kPointerSize));
8337
8338 // Do the allocation of both objects in one go.
8339 __ AllocateInNewSpace(r1, r0, r2, r3, &runtime, TAG_OBJECT);
8340
8341 // Get the arguments boilerplate from the current (global) context.
8342 int offset = Context::SlotOffset(Context::ARGUMENTS_BOILERPLATE_INDEX);
8343 __ ldr(r4, MemOperand(cp, Context::SlotOffset(Context::GLOBAL_INDEX)));
8344 __ ldr(r4, FieldMemOperand(r4, GlobalObject::kGlobalContextOffset));
8345 __ ldr(r4, MemOperand(r4, offset));
8346
8347 // Copy the JS object part.
8348 for (int i = 0; i < JSObject::kHeaderSize; i += kPointerSize) {
8349 __ ldr(r3, FieldMemOperand(r4, i));
8350 __ str(r3, FieldMemOperand(r0, i));
8351 }
8352
8353 // Setup the callee in-object property.
8354 ASSERT(Heap::arguments_callee_index == 0);
8355 __ ldr(r3, MemOperand(sp, 2 * kPointerSize));
8356 __ str(r3, FieldMemOperand(r0, JSObject::kHeaderSize));
8357
8358 // Get the length (smi tagged) and set that as an in-object property too.
8359 ASSERT(Heap::arguments_length_index == 1);
8360 __ ldr(r1, MemOperand(sp, 0 * kPointerSize));
8361 __ str(r1, FieldMemOperand(r0, JSObject::kHeaderSize + kPointerSize));
8362
8363 // If there are no actual arguments, we're done.
8364 Label done;
8365 __ cmp(r1, Operand(0));
8366 __ b(eq, &done);
8367
8368 // Get the parameters pointer from the stack and untag the length.
8369 __ ldr(r2, MemOperand(sp, 1 * kPointerSize));
8370 __ mov(r1, Operand(r1, LSR, kSmiTagSize));
8371
8372 // Setup the elements pointer in the allocated arguments object and
8373 // initialize the header in the elements fixed array.
8374 __ add(r4, r0, Operand(Heap::kArgumentsObjectSize));
8375 __ str(r4, FieldMemOperand(r0, JSObject::kElementsOffset));
8376 __ LoadRoot(r3, Heap::kFixedArrayMapRootIndex);
8377 __ str(r3, FieldMemOperand(r4, FixedArray::kMapOffset));
8378 __ str(r1, FieldMemOperand(r4, FixedArray::kLengthOffset));
8379
8380 // Copy the fixed array slots.
8381 Label loop;
8382 // Setup r4 to point to the first array slot.
8383 __ add(r4, r4, Operand(FixedArray::kHeaderSize - kHeapObjectTag));
8384 __ bind(&loop);
8385 // Pre-decrement r2 with kPointerSize on each iteration.
8386 // Pre-decrement in order to skip receiver.
8387 __ ldr(r3, MemOperand(r2, kPointerSize, NegPreIndex));
8388 // Post-increment r4 with kPointerSize on each iteration.
8389 __ str(r3, MemOperand(r4, kPointerSize, PostIndex));
8390 __ sub(r1, r1, Operand(1));
8391 __ cmp(r1, Operand(0));
8392 __ b(ne, &loop);
8393
8394 // Return and remove the on-stack parameters.
8395 __ bind(&done);
8396 __ add(sp, sp, Operand(3 * kPointerSize));
8397 __ Ret();
8398
Steve Blocka7e24c12009-10-30 11:49:00 +00008399 // Do the runtime call to allocate the arguments object.
8400 __ bind(&runtime);
Steve Block6ded16b2010-05-10 14:33:55 +01008401 __ TailCallRuntime(Runtime::kNewArgumentsFast, 3, 1);
8402}
8403
8404
8405void RegExpExecStub::Generate(MacroAssembler* masm) {
8406 // Just jump directly to runtime if native RegExp is not selected at compile
8407 // time or if regexp entry in generated code is turned off runtime switch or
8408 // at compilation.
8409#ifndef V8_NATIVE_REGEXP
8410 __ TailCallRuntime(Runtime::kRegExpExec, 4, 1);
8411#else // V8_NATIVE_REGEXP
8412 if (!FLAG_regexp_entry_native) {
8413 __ TailCallRuntime(Runtime::kRegExpExec, 4, 1);
8414 return;
8415 }
8416
8417 // Stack frame on entry.
8418 // sp[0]: last_match_info (expected JSArray)
8419 // sp[4]: previous index
8420 // sp[8]: subject string
8421 // sp[12]: JSRegExp object
8422
8423 static const int kLastMatchInfoOffset = 0 * kPointerSize;
8424 static const int kPreviousIndexOffset = 1 * kPointerSize;
8425 static const int kSubjectOffset = 2 * kPointerSize;
8426 static const int kJSRegExpOffset = 3 * kPointerSize;
8427
8428 Label runtime, invoke_regexp;
8429
8430 // Allocation of registers for this function. These are in callee save
8431 // registers and will be preserved by the call to the native RegExp code, as
8432 // this code is called using the normal C calling convention. When calling
8433 // directly from generated code the native RegExp code will not do a GC and
8434 // therefore the content of these registers are safe to use after the call.
8435 Register subject = r4;
8436 Register regexp_data = r5;
8437 Register last_match_info_elements = r6;
8438
8439 // Ensure that a RegExp stack is allocated.
8440 ExternalReference address_of_regexp_stack_memory_address =
8441 ExternalReference::address_of_regexp_stack_memory_address();
8442 ExternalReference address_of_regexp_stack_memory_size =
8443 ExternalReference::address_of_regexp_stack_memory_size();
8444 __ mov(r0, Operand(address_of_regexp_stack_memory_size));
8445 __ ldr(r0, MemOperand(r0, 0));
8446 __ tst(r0, Operand(r0));
8447 __ b(eq, &runtime);
8448
8449 // Check that the first argument is a JSRegExp object.
8450 __ ldr(r0, MemOperand(sp, kJSRegExpOffset));
8451 ASSERT_EQ(0, kSmiTag);
8452 __ tst(r0, Operand(kSmiTagMask));
8453 __ b(eq, &runtime);
8454 __ CompareObjectType(r0, r1, r1, JS_REGEXP_TYPE);
8455 __ b(ne, &runtime);
8456
8457 // Check that the RegExp has been compiled (data contains a fixed array).
8458 __ ldr(regexp_data, FieldMemOperand(r0, JSRegExp::kDataOffset));
8459 if (FLAG_debug_code) {
8460 __ tst(regexp_data, Operand(kSmiTagMask));
8461 __ Check(nz, "Unexpected type for RegExp data, FixedArray expected");
8462 __ CompareObjectType(regexp_data, r0, r0, FIXED_ARRAY_TYPE);
8463 __ Check(eq, "Unexpected type for RegExp data, FixedArray expected");
8464 }
8465
8466 // regexp_data: RegExp data (FixedArray)
8467 // Check the type of the RegExp. Only continue if type is JSRegExp::IRREGEXP.
8468 __ ldr(r0, FieldMemOperand(regexp_data, JSRegExp::kDataTagOffset));
8469 __ cmp(r0, Operand(Smi::FromInt(JSRegExp::IRREGEXP)));
8470 __ b(ne, &runtime);
8471
8472 // regexp_data: RegExp data (FixedArray)
8473 // Check that the number of captures fit in the static offsets vector buffer.
8474 __ ldr(r2,
8475 FieldMemOperand(regexp_data, JSRegExp::kIrregexpCaptureCountOffset));
8476 // Calculate number of capture registers (number_of_captures + 1) * 2. This
8477 // uses the asumption that smis are 2 * their untagged value.
8478 ASSERT_EQ(0, kSmiTag);
8479 ASSERT_EQ(1, kSmiTagSize + kSmiShiftSize);
8480 __ add(r2, r2, Operand(2)); // r2 was a smi.
8481 // Check that the static offsets vector buffer is large enough.
8482 __ cmp(r2, Operand(OffsetsVector::kStaticOffsetsVectorSize));
8483 __ b(hi, &runtime);
8484
8485 // r2: Number of capture registers
8486 // regexp_data: RegExp data (FixedArray)
8487 // Check that the second argument is a string.
8488 __ ldr(subject, MemOperand(sp, kSubjectOffset));
8489 __ tst(subject, Operand(kSmiTagMask));
8490 __ b(eq, &runtime);
8491 Condition is_string = masm->IsObjectStringType(subject, r0);
8492 __ b(NegateCondition(is_string), &runtime);
8493 // Get the length of the string to r3.
8494 __ ldr(r3, FieldMemOperand(subject, String::kLengthOffset));
8495
8496 // r2: Number of capture registers
8497 // r3: Length of subject string as a smi
8498 // subject: Subject string
8499 // regexp_data: RegExp data (FixedArray)
8500 // Check that the third argument is a positive smi less than the subject
8501 // string length. A negative value will be greater (unsigned comparison).
8502 __ ldr(r0, MemOperand(sp, kPreviousIndexOffset));
8503 __ tst(r0, Operand(kSmiTagMask));
8504 __ b(eq, &runtime);
8505 __ cmp(r3, Operand(r0));
8506 __ b(le, &runtime);
8507
8508 // r2: Number of capture registers
8509 // subject: Subject string
8510 // regexp_data: RegExp data (FixedArray)
8511 // Check that the fourth object is a JSArray object.
8512 __ ldr(r0, MemOperand(sp, kLastMatchInfoOffset));
8513 __ tst(r0, Operand(kSmiTagMask));
8514 __ b(eq, &runtime);
8515 __ CompareObjectType(r0, r1, r1, JS_ARRAY_TYPE);
8516 __ b(ne, &runtime);
8517 // Check that the JSArray is in fast case.
8518 __ ldr(last_match_info_elements,
8519 FieldMemOperand(r0, JSArray::kElementsOffset));
8520 __ ldr(r0, FieldMemOperand(last_match_info_elements, HeapObject::kMapOffset));
8521#if ANDROID
8522 __ LoadRoot(ip, Heap::kFixedArrayMapRootIndex);
8523#else
8524 __ LoadRoot(ip, kFixedArrayMapRootIndex);
8525#endif
8526 __ cmp(r0, ip);
8527 __ b(ne, &runtime);
8528 // Check that the last match info has space for the capture registers and the
8529 // additional information.
8530 __ ldr(r0,
8531 FieldMemOperand(last_match_info_elements, FixedArray::kLengthOffset));
8532 __ add(r2, r2, Operand(RegExpImpl::kLastMatchOverhead));
8533 __ cmp(r2, r0);
8534 __ b(gt, &runtime);
8535
8536 // subject: Subject string
8537 // regexp_data: RegExp data (FixedArray)
8538 // Check the representation and encoding of the subject string.
8539 Label seq_string;
8540 const int kStringRepresentationEncodingMask =
8541 kIsNotStringMask | kStringRepresentationMask | kStringEncodingMask;
8542 __ ldr(r0, FieldMemOperand(subject, HeapObject::kMapOffset));
8543 __ ldrb(r0, FieldMemOperand(r0, Map::kInstanceTypeOffset));
8544 __ and_(r1, r0, Operand(kStringRepresentationEncodingMask));
8545 // First check for sequential string.
8546 ASSERT_EQ(0, kStringTag);
8547 ASSERT_EQ(0, kSeqStringTag);
8548 __ tst(r1, Operand(kIsNotStringMask | kStringRepresentationMask));
8549 __ b(eq, &seq_string);
8550
8551 // subject: Subject string
8552 // regexp_data: RegExp data (FixedArray)
8553 // Check for flat cons string.
8554 // A flat cons string is a cons string where the second part is the empty
8555 // string. In that case the subject string is just the first part of the cons
8556 // string. Also in this case the first part of the cons string is known to be
8557 // a sequential string or an external string.
8558 __ and_(r0, r0, Operand(kStringRepresentationMask));
8559 __ cmp(r0, Operand(kConsStringTag));
8560 __ b(ne, &runtime);
8561 __ ldr(r0, FieldMemOperand(subject, ConsString::kSecondOffset));
8562 __ LoadRoot(r1, Heap::kEmptyStringRootIndex);
8563 __ cmp(r0, r1);
8564 __ b(ne, &runtime);
8565 __ ldr(subject, FieldMemOperand(subject, ConsString::kFirstOffset));
8566 __ ldr(r0, FieldMemOperand(subject, HeapObject::kMapOffset));
8567 __ ldrb(r0, FieldMemOperand(r0, Map::kInstanceTypeOffset));
8568 ASSERT_EQ(0, kSeqStringTag);
8569 __ tst(r0, Operand(kStringRepresentationMask));
8570 __ b(nz, &runtime);
8571 __ and_(r1, r0, Operand(kStringRepresentationEncodingMask));
8572
8573 __ bind(&seq_string);
8574 // r1: suject string type & kStringRepresentationEncodingMask
8575 // subject: Subject string
8576 // regexp_data: RegExp data (FixedArray)
8577 // Check that the irregexp code has been generated for an ascii string. If
8578 // it has, the field contains a code object otherwise it contains the hole.
8579#ifdef DEBUG
8580 const int kSeqAsciiString = kStringTag | kSeqStringTag | kAsciiStringTag;
8581 const int kSeqTwoByteString = kStringTag | kSeqStringTag | kTwoByteStringTag;
8582 CHECK_EQ(4, kSeqAsciiString);
8583 CHECK_EQ(0, kSeqTwoByteString);
8584#endif
8585 // Find the code object based on the assumptions above.
8586 __ mov(r3, Operand(r1, ASR, 2), SetCC);
8587 __ ldr(r7, FieldMemOperand(regexp_data, JSRegExp::kDataAsciiCodeOffset), ne);
8588 __ ldr(r7, FieldMemOperand(regexp_data, JSRegExp::kDataUC16CodeOffset), eq);
8589
8590 // Check that the irregexp code has been generated for the actual string
8591 // encoding. If it has, the field contains a code object otherwise it contains
8592 // the hole.
8593 __ CompareObjectType(r7, r0, r0, CODE_TYPE);
8594 __ b(ne, &runtime);
8595
8596 // r3: encoding of subject string (1 if ascii, 0 if two_byte);
8597 // r7: code
8598 // subject: Subject string
8599 // regexp_data: RegExp data (FixedArray)
8600 // Load used arguments before starting to push arguments for call to native
8601 // RegExp code to avoid handling changing stack height.
8602 __ ldr(r1, MemOperand(sp, kPreviousIndexOffset));
8603 __ mov(r1, Operand(r1, ASR, kSmiTagSize));
8604
8605 // r1: previous index
8606 // r3: encoding of subject string (1 if ascii, 0 if two_byte);
8607 // r7: code
8608 // subject: Subject string
8609 // regexp_data: RegExp data (FixedArray)
8610 // All checks done. Now push arguments for native regexp code.
8611 __ IncrementCounter(&Counters::regexp_entry_native, 1, r0, r2);
8612
8613 static const int kRegExpExecuteArguments = 7;
8614 __ push(lr);
8615 __ PrepareCallCFunction(kRegExpExecuteArguments, r0);
8616
8617 // Argument 7 (sp[8]): Indicate that this is a direct call from JavaScript.
8618 __ mov(r0, Operand(1));
8619 __ str(r0, MemOperand(sp, 2 * kPointerSize));
8620
8621 // Argument 6 (sp[4]): Start (high end) of backtracking stack memory area.
8622 __ mov(r0, Operand(address_of_regexp_stack_memory_address));
8623 __ ldr(r0, MemOperand(r0, 0));
8624 __ mov(r2, Operand(address_of_regexp_stack_memory_size));
8625 __ ldr(r2, MemOperand(r2, 0));
8626 __ add(r0, r0, Operand(r2));
8627 __ str(r0, MemOperand(sp, 1 * kPointerSize));
8628
8629 // Argument 5 (sp[0]): static offsets vector buffer.
8630 __ mov(r0, Operand(ExternalReference::address_of_static_offsets_vector()));
8631 __ str(r0, MemOperand(sp, 0 * kPointerSize));
8632
8633 // For arguments 4 and 3 get string length, calculate start of string data and
8634 // calculate the shift of the index (0 for ASCII and 1 for two byte).
8635 __ ldr(r0, FieldMemOperand(subject, String::kLengthOffset));
8636 __ mov(r0, Operand(r0, ASR, kSmiTagSize));
8637 ASSERT_EQ(SeqAsciiString::kHeaderSize, SeqTwoByteString::kHeaderSize);
8638 __ add(r9, subject, Operand(SeqAsciiString::kHeaderSize - kHeapObjectTag));
8639 __ eor(r3, r3, Operand(1));
8640 // Argument 4 (r3): End of string data
8641 // Argument 3 (r2): Start of string data
8642 __ add(r2, r9, Operand(r1, LSL, r3));
8643 __ add(r3, r9, Operand(r0, LSL, r3));
8644
8645 // Argument 2 (r1): Previous index.
8646 // Already there
8647
8648 // Argument 1 (r0): Subject string.
8649 __ mov(r0, subject);
8650
8651 // Locate the code entry and call it.
8652 __ add(r7, r7, Operand(Code::kHeaderSize - kHeapObjectTag));
8653 __ CallCFunction(r7, kRegExpExecuteArguments);
8654 __ pop(lr);
8655
8656 // r0: result
8657 // subject: subject string (callee saved)
8658 // regexp_data: RegExp data (callee saved)
8659 // last_match_info_elements: Last match info elements (callee saved)
8660
8661 // Check the result.
8662 Label success;
8663 __ cmp(r0, Operand(NativeRegExpMacroAssembler::SUCCESS));
8664 __ b(eq, &success);
8665 Label failure;
8666 __ cmp(r0, Operand(NativeRegExpMacroAssembler::FAILURE));
8667 __ b(eq, &failure);
8668 __ cmp(r0, Operand(NativeRegExpMacroAssembler::EXCEPTION));
8669 // If not exception it can only be retry. Handle that in the runtime system.
8670 __ b(ne, &runtime);
8671 // Result must now be exception. If there is no pending exception already a
8672 // stack overflow (on the backtrack stack) was detected in RegExp code but
8673 // haven't created the exception yet. Handle that in the runtime system.
8674 // TODO(592): Rerunning the RegExp to get the stack overflow exception.
8675 __ mov(r0, Operand(ExternalReference::the_hole_value_location()));
8676 __ ldr(r0, MemOperand(r0, 0));
8677 __ mov(r1, Operand(ExternalReference(Top::k_pending_exception_address)));
8678 __ ldr(r1, MemOperand(r1, 0));
8679 __ cmp(r0, r1);
8680 __ b(eq, &runtime);
8681 __ bind(&failure);
8682 // For failure and exception return null.
8683 __ mov(r0, Operand(Factory::null_value()));
8684 __ add(sp, sp, Operand(4 * kPointerSize));
8685 __ Ret();
8686
8687 // Process the result from the native regexp code.
8688 __ bind(&success);
8689 __ ldr(r1,
8690 FieldMemOperand(regexp_data, JSRegExp::kIrregexpCaptureCountOffset));
8691 // Calculate number of capture registers (number_of_captures + 1) * 2.
8692 ASSERT_EQ(0, kSmiTag);
8693 ASSERT_EQ(1, kSmiTagSize + kSmiShiftSize);
8694 __ add(r1, r1, Operand(2)); // r1 was a smi.
8695
8696 // r1: number of capture registers
8697 // r4: subject string
8698 // Store the capture count.
8699 __ mov(r2, Operand(r1, LSL, kSmiTagSize + kSmiShiftSize)); // To smi.
8700 __ str(r2, FieldMemOperand(last_match_info_elements,
8701 RegExpImpl::kLastCaptureCountOffset));
8702 // Store last subject and last input.
8703 __ mov(r3, last_match_info_elements); // Moved up to reduce latency.
8704 __ mov(r2, Operand(RegExpImpl::kLastSubjectOffset)); // Ditto.
8705 __ str(subject,
8706 FieldMemOperand(last_match_info_elements,
8707 RegExpImpl::kLastSubjectOffset));
8708 __ RecordWrite(r3, r2, r7);
8709 __ str(subject,
8710 FieldMemOperand(last_match_info_elements,
8711 RegExpImpl::kLastInputOffset));
8712 __ mov(r3, last_match_info_elements);
8713 __ mov(r2, Operand(RegExpImpl::kLastInputOffset));
8714 __ RecordWrite(r3, r2, r7);
8715
8716 // Get the static offsets vector filled by the native regexp code.
8717 ExternalReference address_of_static_offsets_vector =
8718 ExternalReference::address_of_static_offsets_vector();
8719 __ mov(r2, Operand(address_of_static_offsets_vector));
8720
8721 // r1: number of capture registers
8722 // r2: offsets vector
8723 Label next_capture, done;
8724 // Capture register counter starts from number of capture registers and
8725 // counts down until wraping after zero.
8726 __ add(r0,
8727 last_match_info_elements,
8728 Operand(RegExpImpl::kFirstCaptureOffset - kHeapObjectTag));
8729 __ bind(&next_capture);
8730 __ sub(r1, r1, Operand(1), SetCC);
8731 __ b(mi, &done);
8732 // Read the value from the static offsets vector buffer.
8733 __ ldr(r3, MemOperand(r2, kPointerSize, PostIndex));
8734 // Store the smi value in the last match info.
8735 __ mov(r3, Operand(r3, LSL, kSmiTagSize));
8736 __ str(r3, MemOperand(r0, kPointerSize, PostIndex));
8737 __ jmp(&next_capture);
8738 __ bind(&done);
8739
8740 // Return last match info.
8741 __ ldr(r0, MemOperand(sp, kLastMatchInfoOffset));
8742 __ add(sp, sp, Operand(4 * kPointerSize));
8743 __ Ret();
8744
8745 // Do the runtime call to execute the regexp.
8746 __ bind(&runtime);
8747 __ TailCallRuntime(Runtime::kRegExpExec, 4, 1);
8748#endif // V8_NATIVE_REGEXP
Steve Blocka7e24c12009-10-30 11:49:00 +00008749}
8750
8751
8752void CallFunctionStub::Generate(MacroAssembler* masm) {
8753 Label slow;
Leon Clarkee46be812010-01-19 14:06:41 +00008754
8755 // If the receiver might be a value (string, number or boolean) check for this
8756 // and box it if it is.
8757 if (ReceiverMightBeValue()) {
8758 // Get the receiver from the stack.
8759 // function, receiver [, arguments]
8760 Label receiver_is_value, receiver_is_js_object;
8761 __ ldr(r1, MemOperand(sp, argc_ * kPointerSize));
8762
8763 // Check if receiver is a smi (which is a number value).
8764 __ BranchOnSmi(r1, &receiver_is_value);
8765
8766 // Check if the receiver is a valid JS object.
8767 __ CompareObjectType(r1, r2, r2, FIRST_JS_OBJECT_TYPE);
8768 __ b(ge, &receiver_is_js_object);
8769
8770 // Call the runtime to box the value.
8771 __ bind(&receiver_is_value);
8772 __ EnterInternalFrame();
8773 __ push(r1);
8774 __ InvokeBuiltin(Builtins::TO_OBJECT, CALL_JS);
8775 __ LeaveInternalFrame();
8776 __ str(r0, MemOperand(sp, argc_ * kPointerSize));
8777
8778 __ bind(&receiver_is_js_object);
8779 }
8780
Steve Blocka7e24c12009-10-30 11:49:00 +00008781 // Get the function to call from the stack.
8782 // function, receiver [, arguments]
8783 __ ldr(r1, MemOperand(sp, (argc_ + 1) * kPointerSize));
8784
8785 // Check that the function is really a JavaScript function.
8786 // r1: pushed function (to be verified)
8787 __ BranchOnSmi(r1, &slow);
8788 // Get the map of the function object.
8789 __ CompareObjectType(r1, r2, r2, JS_FUNCTION_TYPE);
8790 __ b(ne, &slow);
8791
8792 // Fast-case: Invoke the function now.
8793 // r1: pushed function
8794 ParameterCount actual(argc_);
8795 __ InvokeFunction(r1, actual, JUMP_FUNCTION);
8796
8797 // Slow-case: Non-function called.
8798 __ bind(&slow);
Andrei Popescu402d9372010-02-26 13:31:12 +00008799 // CALL_NON_FUNCTION expects the non-function callee as receiver (instead
8800 // of the original receiver from the call site).
8801 __ str(r1, MemOperand(sp, argc_ * kPointerSize));
Steve Blocka7e24c12009-10-30 11:49:00 +00008802 __ mov(r0, Operand(argc_)); // Setup the number of arguments.
8803 __ mov(r2, Operand(0));
8804 __ GetBuiltinEntry(r3, Builtins::CALL_NON_FUNCTION);
8805 __ Jump(Handle<Code>(Builtins::builtin(Builtins::ArgumentsAdaptorTrampoline)),
8806 RelocInfo::CODE_TARGET);
8807}
8808
8809
Steve Block6ded16b2010-05-10 14:33:55 +01008810// Unfortunately you have to run without snapshots to see most of these
8811// names in the profile since most compare stubs end up in the snapshot.
Leon Clarkee46be812010-01-19 14:06:41 +00008812const char* CompareStub::GetName() {
Steve Block6ded16b2010-05-10 14:33:55 +01008813 if (name_ != NULL) return name_;
8814 const int kMaxNameLength = 100;
8815 name_ = Bootstrapper::AllocateAutoDeletedArray(kMaxNameLength);
8816 if (name_ == NULL) return "OOM";
8817
8818 const char* cc_name;
Leon Clarkee46be812010-01-19 14:06:41 +00008819 switch (cc_) {
Steve Block6ded16b2010-05-10 14:33:55 +01008820 case lt: cc_name = "LT"; break;
8821 case gt: cc_name = "GT"; break;
8822 case le: cc_name = "LE"; break;
8823 case ge: cc_name = "GE"; break;
8824 case eq: cc_name = "EQ"; break;
8825 case ne: cc_name = "NE"; break;
8826 default: cc_name = "UnknownCondition"; break;
Leon Clarkee46be812010-01-19 14:06:41 +00008827 }
Steve Block6ded16b2010-05-10 14:33:55 +01008828
8829 const char* strict_name = "";
8830 if (strict_ && (cc_ == eq || cc_ == ne)) {
8831 strict_name = "_STRICT";
8832 }
8833
8834 const char* never_nan_nan_name = "";
8835 if (never_nan_nan_ && (cc_ == eq || cc_ == ne)) {
8836 never_nan_nan_name = "_NO_NAN";
8837 }
8838
8839 const char* include_number_compare_name = "";
8840 if (!include_number_compare_) {
8841 include_number_compare_name = "_NO_NUMBER";
8842 }
8843
8844 OS::SNPrintF(Vector<char>(name_, kMaxNameLength),
8845 "CompareStub_%s%s%s%s",
8846 cc_name,
8847 strict_name,
8848 never_nan_nan_name,
8849 include_number_compare_name);
8850 return name_;
Leon Clarkee46be812010-01-19 14:06:41 +00008851}
8852
8853
Steve Blocka7e24c12009-10-30 11:49:00 +00008854int CompareStub::MinorKey() {
Steve Block6ded16b2010-05-10 14:33:55 +01008855 // Encode the three parameters in a unique 16 bit value. To avoid duplicate
8856 // stubs the never NaN NaN condition is only taken into account if the
8857 // condition is equals.
8858 ASSERT((static_cast<unsigned>(cc_) >> 28) < (1 << 13));
8859 return ConditionField::encode(static_cast<unsigned>(cc_) >> 28)
8860 | StrictField::encode(strict_)
8861 | NeverNanNanField::encode(cc_ == eq ? never_nan_nan_ : false)
8862 | IncludeNumberCompareField::encode(include_number_compare_);
Steve Blocka7e24c12009-10-30 11:49:00 +00008863}
8864
8865
Steve Block6ded16b2010-05-10 14:33:55 +01008866void StringHelper::GenerateFastCharCodeAt(MacroAssembler* masm,
8867 Register object,
8868 Register index,
8869 Register scratch,
8870 Register result,
8871 Label* receiver_not_string,
8872 Label* index_not_smi,
8873 Label* index_out_of_range,
8874 Label* slow_case) {
8875 Label not_a_flat_string;
8876 Label try_again_with_new_string;
8877 Label ascii_string;
8878 Label got_char_code;
8879
8880 // If the receiver is a smi trigger the non-string case.
8881 __ BranchOnSmi(object, receiver_not_string);
8882
8883 // Fetch the instance type of the receiver into result register.
8884 __ ldr(result, FieldMemOperand(object, HeapObject::kMapOffset));
8885 __ ldrb(result, FieldMemOperand(result, Map::kInstanceTypeOffset));
8886 // If the receiver is not a string trigger the non-string case.
8887 __ tst(result, Operand(kIsNotStringMask));
8888 __ b(ne, receiver_not_string);
8889
8890 // If the index is non-smi trigger the non-smi case.
8891 __ BranchOnNotSmi(index, index_not_smi);
8892
8893 // Check for index out of range.
8894 __ ldr(scratch, FieldMemOperand(object, String::kLengthOffset));
8895 // Now scratch has the length of the string. Compare with the index.
8896 __ cmp(scratch, Operand(index));
8897 __ b(ls, index_out_of_range);
8898
8899 __ bind(&try_again_with_new_string);
8900 // ----------- S t a t e -------------
8901 // -- object : string to access
8902 // -- result : instance type of the string
8903 // -- scratch : non-negative index < length
8904 // -----------------------------------
8905
8906 // We need special handling for non-flat strings.
8907 ASSERT_EQ(0, kSeqStringTag);
8908 __ tst(result, Operand(kStringRepresentationMask));
8909 __ b(ne, &not_a_flat_string);
8910
8911 // Check for 1-byte or 2-byte string.
8912 ASSERT_EQ(0, kTwoByteStringTag);
8913 __ tst(result, Operand(kStringEncodingMask));
8914 __ b(ne, &ascii_string);
8915
8916 // 2-byte string. We can add without shifting since the Smi tag size is the
8917 // log2 of the number of bytes in a two-byte character.
8918 ASSERT_EQ(1, kSmiTagSize);
8919 ASSERT_EQ(0, kSmiShiftSize);
8920 __ add(scratch, object, Operand(index));
8921 __ ldrh(result, FieldMemOperand(scratch, SeqTwoByteString::kHeaderSize));
8922 __ jmp(&got_char_code);
8923
8924 // Handle non-flat strings.
8925 __ bind(&not_a_flat_string);
8926 __ and_(result, result, Operand(kStringRepresentationMask));
8927 __ cmp(result, Operand(kConsStringTag));
8928 __ b(ne, slow_case);
8929
8930 // ConsString.
8931 // Check whether the right hand side is the empty string (i.e. if
8932 // this is really a flat string in a cons string). If that is not
8933 // the case we would rather go to the runtime system now to flatten
8934 // the string.
8935 __ ldr(result, FieldMemOperand(object, ConsString::kSecondOffset));
8936 __ LoadRoot(scratch, Heap::kEmptyStringRootIndex);
8937 __ cmp(result, Operand(scratch));
8938 __ b(ne, slow_case);
8939
8940 // Get the first of the two strings and load its instance type.
8941 __ ldr(object, FieldMemOperand(object, ConsString::kFirstOffset));
8942 __ ldr(result, FieldMemOperand(object, HeapObject::kMapOffset));
8943 __ ldrb(result, FieldMemOperand(result, Map::kInstanceTypeOffset));
8944 __ jmp(&try_again_with_new_string);
8945
8946 // ASCII string.
8947 __ bind(&ascii_string);
8948 __ add(scratch, object, Operand(index, LSR, kSmiTagSize));
8949 __ ldrb(result, FieldMemOperand(scratch, SeqAsciiString::kHeaderSize));
8950
8951 __ bind(&got_char_code);
8952 __ mov(result, Operand(result, LSL, kSmiTagSize));
8953}
8954
8955
8956void StringHelper::GenerateCharFromCode(MacroAssembler* masm,
8957 Register code,
8958 Register scratch,
8959 Register result,
8960 InvokeFlag flag) {
8961 ASSERT(!code.is(result));
8962
8963 Label slow_case;
8964 Label exit;
8965
8966 // Fast case of Heap::LookupSingleCharacterStringFromCode.
8967 ASSERT(kSmiTag == 0);
8968 ASSERT(kSmiShiftSize == 0);
8969 ASSERT(IsPowerOf2(String::kMaxAsciiCharCode + 1));
8970 __ tst(code, Operand(kSmiTagMask |
8971 ((~String::kMaxAsciiCharCode) << kSmiTagSize)));
8972 __ b(nz, &slow_case);
8973
8974 ASSERT(kSmiTag == 0);
8975 __ mov(result, Operand(Factory::single_character_string_cache()));
8976 __ add(result, result, Operand(code, LSL, kPointerSizeLog2 - kSmiTagSize));
8977 __ ldr(result, MemOperand(result, FixedArray::kHeaderSize - kHeapObjectTag));
8978 __ LoadRoot(scratch, Heap::kUndefinedValueRootIndex);
8979 __ cmp(result, scratch);
8980 __ b(eq, &slow_case);
8981 __ b(&exit);
8982
8983 __ bind(&slow_case);
8984 if (flag == CALL_FUNCTION) {
8985 __ push(code);
8986 __ CallRuntime(Runtime::kCharFromCode, 1);
8987 if (!result.is(r0)) {
8988 __ mov(result, r0);
8989 }
8990 } else {
8991 ASSERT(flag == JUMP_FUNCTION);
8992 ASSERT(result.is(r0));
8993 __ push(code);
8994 __ TailCallRuntime(Runtime::kCharFromCode, 1, 1);
8995 }
8996
8997 __ bind(&exit);
8998 if (flag == JUMP_FUNCTION) {
8999 ASSERT(result.is(r0));
9000 __ Ret();
9001 }
9002}
9003
9004
9005void StringHelper::GenerateCopyCharacters(MacroAssembler* masm,
9006 Register dest,
9007 Register src,
9008 Register count,
9009 Register scratch,
9010 bool ascii) {
Andrei Popescu31002712010-02-23 13:46:05 +00009011 Label loop;
9012 Label done;
9013 // This loop just copies one character at a time, as it is only used for very
9014 // short strings.
9015 if (!ascii) {
9016 __ add(count, count, Operand(count), SetCC);
9017 } else {
9018 __ cmp(count, Operand(0));
9019 }
9020 __ b(eq, &done);
9021
9022 __ bind(&loop);
9023 __ ldrb(scratch, MemOperand(src, 1, PostIndex));
9024 // Perform sub between load and dependent store to get the load time to
9025 // complete.
9026 __ sub(count, count, Operand(1), SetCC);
9027 __ strb(scratch, MemOperand(dest, 1, PostIndex));
9028 // last iteration.
9029 __ b(gt, &loop);
9030
9031 __ bind(&done);
9032}
9033
9034
9035enum CopyCharactersFlags {
9036 COPY_ASCII = 1,
9037 DEST_ALWAYS_ALIGNED = 2
9038};
9039
9040
Steve Block6ded16b2010-05-10 14:33:55 +01009041void StringHelper::GenerateCopyCharactersLong(MacroAssembler* masm,
9042 Register dest,
9043 Register src,
9044 Register count,
9045 Register scratch1,
9046 Register scratch2,
9047 Register scratch3,
9048 Register scratch4,
9049 Register scratch5,
9050 int flags) {
Andrei Popescu31002712010-02-23 13:46:05 +00009051 bool ascii = (flags & COPY_ASCII) != 0;
9052 bool dest_always_aligned = (flags & DEST_ALWAYS_ALIGNED) != 0;
9053
9054 if (dest_always_aligned && FLAG_debug_code) {
9055 // Check that destination is actually word aligned if the flag says
9056 // that it is.
9057 __ tst(dest, Operand(kPointerAlignmentMask));
9058 __ Check(eq, "Destination of copy not aligned.");
9059 }
9060
9061 const int kReadAlignment = 4;
9062 const int kReadAlignmentMask = kReadAlignment - 1;
9063 // Ensure that reading an entire aligned word containing the last character
9064 // of a string will not read outside the allocated area (because we pad up
9065 // to kObjectAlignment).
9066 ASSERT(kObjectAlignment >= kReadAlignment);
9067 // Assumes word reads and writes are little endian.
9068 // Nothing to do for zero characters.
9069 Label done;
9070 if (!ascii) {
9071 __ add(count, count, Operand(count), SetCC);
9072 } else {
9073 __ cmp(count, Operand(0));
9074 }
9075 __ b(eq, &done);
9076
9077 // Assume that you cannot read (or write) unaligned.
9078 Label byte_loop;
9079 // Must copy at least eight bytes, otherwise just do it one byte at a time.
9080 __ cmp(count, Operand(8));
9081 __ add(count, dest, Operand(count));
9082 Register limit = count; // Read until src equals this.
9083 __ b(lt, &byte_loop);
9084
9085 if (!dest_always_aligned) {
9086 // Align dest by byte copying. Copies between zero and three bytes.
9087 __ and_(scratch4, dest, Operand(kReadAlignmentMask), SetCC);
9088 Label dest_aligned;
9089 __ b(eq, &dest_aligned);
9090 __ cmp(scratch4, Operand(2));
9091 __ ldrb(scratch1, MemOperand(src, 1, PostIndex));
9092 __ ldrb(scratch2, MemOperand(src, 1, PostIndex), le);
9093 __ ldrb(scratch3, MemOperand(src, 1, PostIndex), lt);
9094 __ strb(scratch1, MemOperand(dest, 1, PostIndex));
9095 __ strb(scratch2, MemOperand(dest, 1, PostIndex), le);
9096 __ strb(scratch3, MemOperand(dest, 1, PostIndex), lt);
9097 __ bind(&dest_aligned);
9098 }
9099
9100 Label simple_loop;
9101
9102 __ sub(scratch4, dest, Operand(src));
9103 __ and_(scratch4, scratch4, Operand(0x03), SetCC);
9104 __ b(eq, &simple_loop);
9105 // Shift register is number of bits in a source word that
9106 // must be combined with bits in the next source word in order
9107 // to create a destination word.
9108
9109 // Complex loop for src/dst that are not aligned the same way.
9110 {
9111 Label loop;
9112 __ mov(scratch4, Operand(scratch4, LSL, 3));
9113 Register left_shift = scratch4;
9114 __ and_(src, src, Operand(~3)); // Round down to load previous word.
9115 __ ldr(scratch1, MemOperand(src, 4, PostIndex));
9116 // Store the "shift" most significant bits of scratch in the least
9117 // signficant bits (i.e., shift down by (32-shift)).
9118 __ rsb(scratch2, left_shift, Operand(32));
9119 Register right_shift = scratch2;
9120 __ mov(scratch1, Operand(scratch1, LSR, right_shift));
9121
9122 __ bind(&loop);
9123 __ ldr(scratch3, MemOperand(src, 4, PostIndex));
9124 __ sub(scratch5, limit, Operand(dest));
9125 __ orr(scratch1, scratch1, Operand(scratch3, LSL, left_shift));
9126 __ str(scratch1, MemOperand(dest, 4, PostIndex));
9127 __ mov(scratch1, Operand(scratch3, LSR, right_shift));
9128 // Loop if four or more bytes left to copy.
9129 // Compare to eight, because we did the subtract before increasing dst.
9130 __ sub(scratch5, scratch5, Operand(8), SetCC);
9131 __ b(ge, &loop);
9132 }
9133 // There is now between zero and three bytes left to copy (negative that
9134 // number is in scratch5), and between one and three bytes already read into
9135 // scratch1 (eight times that number in scratch4). We may have read past
9136 // the end of the string, but because objects are aligned, we have not read
9137 // past the end of the object.
9138 // Find the minimum of remaining characters to move and preloaded characters
9139 // and write those as bytes.
9140 __ add(scratch5, scratch5, Operand(4), SetCC);
9141 __ b(eq, &done);
9142 __ cmp(scratch4, Operand(scratch5, LSL, 3), ne);
9143 // Move minimum of bytes read and bytes left to copy to scratch4.
9144 __ mov(scratch5, Operand(scratch4, LSR, 3), LeaveCC, lt);
9145 // Between one and three (value in scratch5) characters already read into
9146 // scratch ready to write.
9147 __ cmp(scratch5, Operand(2));
9148 __ strb(scratch1, MemOperand(dest, 1, PostIndex));
9149 __ mov(scratch1, Operand(scratch1, LSR, 8), LeaveCC, ge);
9150 __ strb(scratch1, MemOperand(dest, 1, PostIndex), ge);
9151 __ mov(scratch1, Operand(scratch1, LSR, 8), LeaveCC, gt);
9152 __ strb(scratch1, MemOperand(dest, 1, PostIndex), gt);
9153 // Copy any remaining bytes.
9154 __ b(&byte_loop);
9155
9156 // Simple loop.
9157 // Copy words from src to dst, until less than four bytes left.
9158 // Both src and dest are word aligned.
9159 __ bind(&simple_loop);
9160 {
9161 Label loop;
9162 __ bind(&loop);
9163 __ ldr(scratch1, MemOperand(src, 4, PostIndex));
9164 __ sub(scratch3, limit, Operand(dest));
9165 __ str(scratch1, MemOperand(dest, 4, PostIndex));
9166 // Compare to 8, not 4, because we do the substraction before increasing
9167 // dest.
9168 __ cmp(scratch3, Operand(8));
9169 __ b(ge, &loop);
9170 }
9171
9172 // Copy bytes from src to dst until dst hits limit.
9173 __ bind(&byte_loop);
9174 __ cmp(dest, Operand(limit));
9175 __ ldrb(scratch1, MemOperand(src, 1, PostIndex), lt);
9176 __ b(ge, &done);
9177 __ strb(scratch1, MemOperand(dest, 1, PostIndex));
9178 __ b(&byte_loop);
9179
9180 __ bind(&done);
9181}
9182
9183
Steve Block6ded16b2010-05-10 14:33:55 +01009184void StringHelper::GenerateTwoCharacterSymbolTableProbe(MacroAssembler* masm,
9185 Register c1,
9186 Register c2,
9187 Register scratch1,
9188 Register scratch2,
9189 Register scratch3,
9190 Register scratch4,
9191 Register scratch5,
9192 Label* not_found) {
9193 // Register scratch3 is the general scratch register in this function.
9194 Register scratch = scratch3;
9195
9196 // Make sure that both characters are not digits as such strings has a
9197 // different hash algorithm. Don't try to look for these in the symbol table.
9198 Label not_array_index;
9199 __ sub(scratch, c1, Operand(static_cast<int>('0')));
9200 __ cmp(scratch, Operand(static_cast<int>('9' - '0')));
9201 __ b(hi, &not_array_index);
9202 __ sub(scratch, c2, Operand(static_cast<int>('0')));
9203 __ cmp(scratch, Operand(static_cast<int>('9' - '0')));
9204
9205 // If check failed combine both characters into single halfword.
9206 // This is required by the contract of the method: code at the
9207 // not_found branch expects this combination in c1 register
9208 __ orr(c1, c1, Operand(c2, LSL, kBitsPerByte), LeaveCC, ls);
9209 __ b(ls, not_found);
9210
9211 __ bind(&not_array_index);
9212 // Calculate the two character string hash.
9213 Register hash = scratch1;
9214 StringHelper::GenerateHashInit(masm, hash, c1);
9215 StringHelper::GenerateHashAddCharacter(masm, hash, c2);
9216 StringHelper::GenerateHashGetHash(masm, hash);
9217
9218 // Collect the two characters in a register.
9219 Register chars = c1;
9220 __ orr(chars, chars, Operand(c2, LSL, kBitsPerByte));
9221
9222 // chars: two character string, char 1 in byte 0 and char 2 in byte 1.
9223 // hash: hash of two character string.
9224
9225 // Load symbol table
9226 // Load address of first element of the symbol table.
9227 Register symbol_table = c2;
9228 __ LoadRoot(symbol_table, Heap::kSymbolTableRootIndex);
9229
9230 // Load undefined value
9231 Register undefined = scratch4;
9232 __ LoadRoot(undefined, Heap::kUndefinedValueRootIndex);
9233
9234 // Calculate capacity mask from the symbol table capacity.
9235 Register mask = scratch2;
9236 __ ldr(mask, FieldMemOperand(symbol_table, SymbolTable::kCapacityOffset));
9237 __ mov(mask, Operand(mask, ASR, 1));
9238 __ sub(mask, mask, Operand(1));
9239
9240 // Calculate untagged address of the first element of the symbol table.
9241 Register first_symbol_table_element = symbol_table;
9242 __ add(first_symbol_table_element, symbol_table,
9243 Operand(SymbolTable::kElementsStartOffset - kHeapObjectTag));
9244
9245 // Registers
9246 // chars: two character string, char 1 in byte 0 and char 2 in byte 1.
9247 // hash: hash of two character string
9248 // mask: capacity mask
9249 // first_symbol_table_element: address of the first element of
9250 // the symbol table
9251 // scratch: -
9252
9253 // Perform a number of probes in the symbol table.
9254 static const int kProbes = 4;
9255 Label found_in_symbol_table;
9256 Label next_probe[kProbes];
9257 for (int i = 0; i < kProbes; i++) {
9258 Register candidate = scratch5; // Scratch register contains candidate.
9259
9260 // Calculate entry in symbol table.
9261 if (i > 0) {
9262 __ add(candidate, hash, Operand(SymbolTable::GetProbeOffset(i)));
9263 } else {
9264 __ mov(candidate, hash);
9265 }
9266
9267 __ and_(candidate, candidate, Operand(mask));
9268
9269 // Load the entry from the symble table.
9270 ASSERT_EQ(1, SymbolTable::kEntrySize);
9271 __ ldr(candidate,
9272 MemOperand(first_symbol_table_element,
9273 candidate,
9274 LSL,
9275 kPointerSizeLog2));
9276
9277 // If entry is undefined no string with this hash can be found.
9278 __ cmp(candidate, undefined);
9279 __ b(eq, not_found);
9280
9281 // If length is not 2 the string is not a candidate.
9282 __ ldr(scratch, FieldMemOperand(candidate, String::kLengthOffset));
9283 __ cmp(scratch, Operand(Smi::FromInt(2)));
9284 __ b(ne, &next_probe[i]);
9285
9286 // Check that the candidate is a non-external ascii string.
9287 __ ldr(scratch, FieldMemOperand(candidate, HeapObject::kMapOffset));
9288 __ ldrb(scratch, FieldMemOperand(scratch, Map::kInstanceTypeOffset));
9289 __ JumpIfInstanceTypeIsNotSequentialAscii(scratch, scratch,
9290 &next_probe[i]);
9291
9292 // Check if the two characters match.
9293 // Assumes that word load is little endian.
9294 __ ldrh(scratch, FieldMemOperand(candidate, SeqAsciiString::kHeaderSize));
9295 __ cmp(chars, scratch);
9296 __ b(eq, &found_in_symbol_table);
9297 __ bind(&next_probe[i]);
9298 }
9299
9300 // No matching 2 character string found by probing.
9301 __ jmp(not_found);
9302
9303 // Scratch register contains result when we fall through to here.
9304 Register result = scratch;
9305 __ bind(&found_in_symbol_table);
9306 __ Move(r0, result);
9307}
9308
9309
9310void StringHelper::GenerateHashInit(MacroAssembler* masm,
9311 Register hash,
9312 Register character) {
9313 // hash = character + (character << 10);
9314 __ add(hash, character, Operand(character, LSL, 10));
9315 // hash ^= hash >> 6;
9316 __ eor(hash, hash, Operand(hash, ASR, 6));
9317}
9318
9319
9320void StringHelper::GenerateHashAddCharacter(MacroAssembler* masm,
9321 Register hash,
9322 Register character) {
9323 // hash += character;
9324 __ add(hash, hash, Operand(character));
9325 // hash += hash << 10;
9326 __ add(hash, hash, Operand(hash, LSL, 10));
9327 // hash ^= hash >> 6;
9328 __ eor(hash, hash, Operand(hash, ASR, 6));
9329}
9330
9331
9332void StringHelper::GenerateHashGetHash(MacroAssembler* masm,
9333 Register hash) {
9334 // hash += hash << 3;
9335 __ add(hash, hash, Operand(hash, LSL, 3));
9336 // hash ^= hash >> 11;
9337 __ eor(hash, hash, Operand(hash, ASR, 11));
9338 // hash += hash << 15;
9339 __ add(hash, hash, Operand(hash, LSL, 15), SetCC);
9340
9341 // if (hash == 0) hash = 27;
9342 __ mov(hash, Operand(27), LeaveCC, nz);
9343}
9344
9345
Andrei Popescu31002712010-02-23 13:46:05 +00009346void SubStringStub::Generate(MacroAssembler* masm) {
9347 Label runtime;
9348
9349 // Stack frame on entry.
9350 // lr: return address
9351 // sp[0]: to
9352 // sp[4]: from
9353 // sp[8]: string
9354
9355 // This stub is called from the native-call %_SubString(...), so
9356 // nothing can be assumed about the arguments. It is tested that:
9357 // "string" is a sequential string,
9358 // both "from" and "to" are smis, and
9359 // 0 <= from <= to <= string.length.
9360 // If any of these assumptions fail, we call the runtime system.
9361
9362 static const int kToOffset = 0 * kPointerSize;
9363 static const int kFromOffset = 1 * kPointerSize;
9364 static const int kStringOffset = 2 * kPointerSize;
9365
9366
9367 // Check bounds and smi-ness.
9368 __ ldr(r7, MemOperand(sp, kToOffset));
9369 __ ldr(r6, MemOperand(sp, kFromOffset));
9370 ASSERT_EQ(0, kSmiTag);
9371 ASSERT_EQ(1, kSmiTagSize + kSmiShiftSize);
9372 // I.e., arithmetic shift right by one un-smi-tags.
9373 __ mov(r2, Operand(r7, ASR, 1), SetCC);
9374 __ mov(r3, Operand(r6, ASR, 1), SetCC, cc);
9375 // If either r2 or r6 had the smi tag bit set, then carry is set now.
9376 __ b(cs, &runtime); // Either "from" or "to" is not a smi.
9377 __ b(mi, &runtime); // From is negative.
9378
9379 __ sub(r2, r2, Operand(r3), SetCC);
9380 __ b(mi, &runtime); // Fail if from > to.
Steve Block6ded16b2010-05-10 14:33:55 +01009381 // Special handling of sub-strings of length 1 and 2. One character strings
9382 // are handled in the runtime system (looked up in the single character
9383 // cache). Two character strings are looked for in the symbol cache.
Andrei Popescu31002712010-02-23 13:46:05 +00009384 __ cmp(r2, Operand(2));
Steve Block6ded16b2010-05-10 14:33:55 +01009385 __ b(lt, &runtime);
Andrei Popescu31002712010-02-23 13:46:05 +00009386
9387 // r2: length
Steve Block6ded16b2010-05-10 14:33:55 +01009388 // r3: from index (untaged smi)
Andrei Popescu31002712010-02-23 13:46:05 +00009389 // r6: from (smi)
9390 // r7: to (smi)
9391
9392 // Make sure first argument is a sequential (or flat) string.
9393 __ ldr(r5, MemOperand(sp, kStringOffset));
9394 ASSERT_EQ(0, kSmiTag);
9395 __ tst(r5, Operand(kSmiTagMask));
9396 __ b(eq, &runtime);
9397 Condition is_string = masm->IsObjectStringType(r5, r1);
9398 __ b(NegateCondition(is_string), &runtime);
9399
9400 // r1: instance type
9401 // r2: length
Steve Block6ded16b2010-05-10 14:33:55 +01009402 // r3: from index (untaged smi)
Andrei Popescu31002712010-02-23 13:46:05 +00009403 // r5: string
9404 // r6: from (smi)
9405 // r7: to (smi)
9406 Label seq_string;
9407 __ and_(r4, r1, Operand(kStringRepresentationMask));
9408 ASSERT(kSeqStringTag < kConsStringTag);
9409 ASSERT(kExternalStringTag > kConsStringTag);
9410 __ cmp(r4, Operand(kConsStringTag));
9411 __ b(gt, &runtime); // External strings go to runtime.
9412 __ b(lt, &seq_string); // Sequential strings are handled directly.
9413
9414 // Cons string. Try to recurse (once) on the first substring.
9415 // (This adds a little more generality than necessary to handle flattened
9416 // cons strings, but not much).
9417 __ ldr(r5, FieldMemOperand(r5, ConsString::kFirstOffset));
9418 __ ldr(r4, FieldMemOperand(r5, HeapObject::kMapOffset));
9419 __ ldrb(r1, FieldMemOperand(r4, Map::kInstanceTypeOffset));
9420 __ tst(r1, Operand(kStringRepresentationMask));
9421 ASSERT_EQ(0, kSeqStringTag);
9422 __ b(ne, &runtime); // Cons and External strings go to runtime.
9423
9424 // Definitly a sequential string.
9425 __ bind(&seq_string);
9426
9427 // r1: instance type.
9428 // r2: length
Steve Block6ded16b2010-05-10 14:33:55 +01009429 // r3: from index (untaged smi)
Andrei Popescu31002712010-02-23 13:46:05 +00009430 // r5: string
9431 // r6: from (smi)
9432 // r7: to (smi)
9433 __ ldr(r4, FieldMemOperand(r5, String::kLengthOffset));
Steve Block6ded16b2010-05-10 14:33:55 +01009434 __ cmp(r4, Operand(r7));
Andrei Popescu31002712010-02-23 13:46:05 +00009435 __ b(lt, &runtime); // Fail if to > length.
9436
9437 // r1: instance type.
9438 // r2: result string length.
Steve Block6ded16b2010-05-10 14:33:55 +01009439 // r3: from index (untaged smi)
Andrei Popescu31002712010-02-23 13:46:05 +00009440 // r5: string.
9441 // r6: from offset (smi)
9442 // Check for flat ascii string.
9443 Label non_ascii_flat;
9444 __ tst(r1, Operand(kStringEncodingMask));
9445 ASSERT_EQ(0, kTwoByteStringTag);
9446 __ b(eq, &non_ascii_flat);
9447
Steve Block6ded16b2010-05-10 14:33:55 +01009448 Label result_longer_than_two;
9449 __ cmp(r2, Operand(2));
9450 __ b(gt, &result_longer_than_two);
9451
9452 // Sub string of length 2 requested.
9453 // Get the two characters forming the sub string.
9454 __ add(r5, r5, Operand(r3));
9455 __ ldrb(r3, FieldMemOperand(r5, SeqAsciiString::kHeaderSize));
9456 __ ldrb(r4, FieldMemOperand(r5, SeqAsciiString::kHeaderSize + 1));
9457
9458 // Try to lookup two character string in symbol table.
9459 Label make_two_character_string;
9460 StringHelper::GenerateTwoCharacterSymbolTableProbe(
9461 masm, r3, r4, r1, r5, r6, r7, r9, &make_two_character_string);
9462 __ IncrementCounter(&Counters::sub_string_native, 1, r3, r4);
9463 __ add(sp, sp, Operand(3 * kPointerSize));
9464 __ Ret();
9465
9466 // r2: result string length.
9467 // r3: two characters combined into halfword in little endian byte order.
9468 __ bind(&make_two_character_string);
9469 __ AllocateAsciiString(r0, r2, r4, r5, r9, &runtime);
9470 __ strh(r3, FieldMemOperand(r0, SeqAsciiString::kHeaderSize));
9471 __ IncrementCounter(&Counters::sub_string_native, 1, r3, r4);
9472 __ add(sp, sp, Operand(3 * kPointerSize));
9473 __ Ret();
9474
9475 __ bind(&result_longer_than_two);
9476
Andrei Popescu31002712010-02-23 13:46:05 +00009477 // Allocate the result.
9478 __ AllocateAsciiString(r0, r2, r3, r4, r1, &runtime);
9479
9480 // r0: result string.
9481 // r2: result string length.
9482 // r5: string.
9483 // r6: from offset (smi)
9484 // Locate first character of result.
9485 __ add(r1, r0, Operand(SeqAsciiString::kHeaderSize - kHeapObjectTag));
9486 // Locate 'from' character of string.
9487 __ add(r5, r5, Operand(SeqAsciiString::kHeaderSize - kHeapObjectTag));
9488 __ add(r5, r5, Operand(r6, ASR, 1));
9489
9490 // r0: result string.
9491 // r1: first character of result string.
9492 // r2: result string length.
9493 // r5: first character of sub string to copy.
9494 ASSERT_EQ(0, SeqAsciiString::kHeaderSize & kObjectAlignmentMask);
Steve Block6ded16b2010-05-10 14:33:55 +01009495 StringHelper::GenerateCopyCharactersLong(masm, r1, r5, r2, r3, r4, r6, r7, r9,
9496 COPY_ASCII | DEST_ALWAYS_ALIGNED);
Andrei Popescu31002712010-02-23 13:46:05 +00009497 __ IncrementCounter(&Counters::sub_string_native, 1, r3, r4);
9498 __ add(sp, sp, Operand(3 * kPointerSize));
9499 __ Ret();
9500
9501 __ bind(&non_ascii_flat);
9502 // r2: result string length.
9503 // r5: string.
9504 // r6: from offset (smi)
9505 // Check for flat two byte string.
9506
9507 // Allocate the result.
9508 __ AllocateTwoByteString(r0, r2, r1, r3, r4, &runtime);
9509
9510 // r0: result string.
9511 // r2: result string length.
9512 // r5: string.
9513 // Locate first character of result.
9514 __ add(r1, r0, Operand(SeqTwoByteString::kHeaderSize - kHeapObjectTag));
9515 // Locate 'from' character of string.
9516 __ add(r5, r5, Operand(SeqTwoByteString::kHeaderSize - kHeapObjectTag));
9517 // As "from" is a smi it is 2 times the value which matches the size of a two
9518 // byte character.
9519 __ add(r5, r5, Operand(r6));
9520
9521 // r0: result string.
9522 // r1: first character of result.
9523 // r2: result length.
9524 // r5: first character of string to copy.
9525 ASSERT_EQ(0, SeqTwoByteString::kHeaderSize & kObjectAlignmentMask);
Steve Block6ded16b2010-05-10 14:33:55 +01009526 StringHelper::GenerateCopyCharactersLong(masm, r1, r5, r2, r3, r4, r6, r7, r9,
9527 DEST_ALWAYS_ALIGNED);
Andrei Popescu31002712010-02-23 13:46:05 +00009528 __ IncrementCounter(&Counters::sub_string_native, 1, r3, r4);
9529 __ add(sp, sp, Operand(3 * kPointerSize));
9530 __ Ret();
9531
9532 // Just jump to runtime to create the sub string.
9533 __ bind(&runtime);
Steve Block6ded16b2010-05-10 14:33:55 +01009534 __ TailCallRuntime(Runtime::kSubString, 3, 1);
Andrei Popescu31002712010-02-23 13:46:05 +00009535}
Leon Clarked91b9f72010-01-27 17:25:45 +00009536
9537
9538void StringCompareStub::GenerateCompareFlatAsciiStrings(MacroAssembler* masm,
9539 Register left,
9540 Register right,
9541 Register scratch1,
9542 Register scratch2,
9543 Register scratch3,
9544 Register scratch4) {
9545 Label compare_lengths;
9546 // Find minimum length and length difference.
9547 __ ldr(scratch1, FieldMemOperand(left, String::kLengthOffset));
9548 __ ldr(scratch2, FieldMemOperand(right, String::kLengthOffset));
9549 __ sub(scratch3, scratch1, Operand(scratch2), SetCC);
9550 Register length_delta = scratch3;
9551 __ mov(scratch1, scratch2, LeaveCC, gt);
9552 Register min_length = scratch1;
Steve Block6ded16b2010-05-10 14:33:55 +01009553 ASSERT(kSmiTag == 0);
Leon Clarked91b9f72010-01-27 17:25:45 +00009554 __ tst(min_length, Operand(min_length));
9555 __ b(eq, &compare_lengths);
9556
Steve Block6ded16b2010-05-10 14:33:55 +01009557 // Untag smi.
9558 __ mov(min_length, Operand(min_length, ASR, kSmiTagSize));
9559
Leon Clarked91b9f72010-01-27 17:25:45 +00009560 // Setup registers so that we only need to increment one register
9561 // in the loop.
9562 __ add(scratch2, min_length,
9563 Operand(SeqAsciiString::kHeaderSize - kHeapObjectTag));
9564 __ add(left, left, Operand(scratch2));
9565 __ add(right, right, Operand(scratch2));
9566 // Registers left and right points to the min_length character of strings.
9567 __ rsb(min_length, min_length, Operand(-1));
9568 Register index = min_length;
9569 // Index starts at -min_length.
9570
9571 {
9572 // Compare loop.
9573 Label loop;
9574 __ bind(&loop);
9575 // Compare characters.
9576 __ add(index, index, Operand(1), SetCC);
9577 __ ldrb(scratch2, MemOperand(left, index), ne);
9578 __ ldrb(scratch4, MemOperand(right, index), ne);
9579 // Skip to compare lengths with eq condition true.
9580 __ b(eq, &compare_lengths);
9581 __ cmp(scratch2, scratch4);
9582 __ b(eq, &loop);
9583 // Fallthrough with eq condition false.
9584 }
9585 // Compare lengths - strings up to min-length are equal.
9586 __ bind(&compare_lengths);
9587 ASSERT(Smi::FromInt(EQUAL) == static_cast<Smi*>(0));
9588 // Use zero length_delta as result.
9589 __ mov(r0, Operand(length_delta), SetCC, eq);
9590 // Fall through to here if characters compare not-equal.
9591 __ mov(r0, Operand(Smi::FromInt(GREATER)), LeaveCC, gt);
9592 __ mov(r0, Operand(Smi::FromInt(LESS)), LeaveCC, lt);
9593 __ Ret();
9594}
9595
9596
9597void StringCompareStub::Generate(MacroAssembler* masm) {
9598 Label runtime;
9599
9600 // Stack frame on entry.
Andrei Popescu31002712010-02-23 13:46:05 +00009601 // sp[0]: right string
9602 // sp[4]: left string
9603 __ ldr(r0, MemOperand(sp, 1 * kPointerSize)); // left
9604 __ ldr(r1, MemOperand(sp, 0 * kPointerSize)); // right
Leon Clarked91b9f72010-01-27 17:25:45 +00009605
9606 Label not_same;
9607 __ cmp(r0, r1);
9608 __ b(ne, &not_same);
9609 ASSERT_EQ(0, EQUAL);
9610 ASSERT_EQ(0, kSmiTag);
9611 __ mov(r0, Operand(Smi::FromInt(EQUAL)));
9612 __ IncrementCounter(&Counters::string_compare_native, 1, r1, r2);
9613 __ add(sp, sp, Operand(2 * kPointerSize));
9614 __ Ret();
9615
9616 __ bind(&not_same);
9617
9618 // Check that both objects are sequential ascii strings.
9619 __ JumpIfNotBothSequentialAsciiStrings(r0, r1, r2, r3, &runtime);
9620
9621 // Compare flat ascii strings natively. Remove arguments from stack first.
9622 __ IncrementCounter(&Counters::string_compare_native, 1, r2, r3);
9623 __ add(sp, sp, Operand(2 * kPointerSize));
9624 GenerateCompareFlatAsciiStrings(masm, r0, r1, r2, r3, r4, r5);
9625
9626 // Call the runtime; it returns -1 (less), 0 (equal), or 1 (greater)
9627 // tagged as a small integer.
9628 __ bind(&runtime);
Steve Block6ded16b2010-05-10 14:33:55 +01009629 __ TailCallRuntime(Runtime::kStringCompare, 2, 1);
Leon Clarked91b9f72010-01-27 17:25:45 +00009630}
9631
9632
Andrei Popescu31002712010-02-23 13:46:05 +00009633void StringAddStub::Generate(MacroAssembler* masm) {
9634 Label string_add_runtime;
9635 // Stack on entry:
9636 // sp[0]: second argument.
9637 // sp[4]: first argument.
9638
9639 // Load the two arguments.
9640 __ ldr(r0, MemOperand(sp, 1 * kPointerSize)); // First argument.
9641 __ ldr(r1, MemOperand(sp, 0 * kPointerSize)); // Second argument.
9642
9643 // Make sure that both arguments are strings if not known in advance.
9644 if (string_check_) {
9645 ASSERT_EQ(0, kSmiTag);
9646 __ JumpIfEitherSmi(r0, r1, &string_add_runtime);
9647 // Load instance types.
9648 __ ldr(r4, FieldMemOperand(r0, HeapObject::kMapOffset));
9649 __ ldr(r5, FieldMemOperand(r1, HeapObject::kMapOffset));
9650 __ ldrb(r4, FieldMemOperand(r4, Map::kInstanceTypeOffset));
9651 __ ldrb(r5, FieldMemOperand(r5, Map::kInstanceTypeOffset));
9652 ASSERT_EQ(0, kStringTag);
9653 // If either is not a string, go to runtime.
9654 __ tst(r4, Operand(kIsNotStringMask));
9655 __ tst(r5, Operand(kIsNotStringMask), eq);
9656 __ b(ne, &string_add_runtime);
9657 }
9658
9659 // Both arguments are strings.
9660 // r0: first string
9661 // r1: second string
9662 // r4: first string instance type (if string_check_)
9663 // r5: second string instance type (if string_check_)
9664 {
9665 Label strings_not_empty;
9666 // Check if either of the strings are empty. In that case return the other.
9667 __ ldr(r2, FieldMemOperand(r0, String::kLengthOffset));
9668 __ ldr(r3, FieldMemOperand(r1, String::kLengthOffset));
Steve Block6ded16b2010-05-10 14:33:55 +01009669 ASSERT(kSmiTag == 0);
9670 __ cmp(r2, Operand(Smi::FromInt(0))); // Test if first string is empty.
Andrei Popescu31002712010-02-23 13:46:05 +00009671 __ mov(r0, Operand(r1), LeaveCC, eq); // If first is empty, return second.
Steve Block6ded16b2010-05-10 14:33:55 +01009672 ASSERT(kSmiTag == 0);
9673 // Else test if second string is empty.
9674 __ cmp(r3, Operand(Smi::FromInt(0)), ne);
Andrei Popescu31002712010-02-23 13:46:05 +00009675 __ b(ne, &strings_not_empty); // If either string was empty, return r0.
9676
9677 __ IncrementCounter(&Counters::string_add_native, 1, r2, r3);
9678 __ add(sp, sp, Operand(2 * kPointerSize));
9679 __ Ret();
9680
9681 __ bind(&strings_not_empty);
9682 }
9683
Steve Block6ded16b2010-05-10 14:33:55 +01009684 __ mov(r2, Operand(r2, ASR, kSmiTagSize));
9685 __ mov(r3, Operand(r3, ASR, kSmiTagSize));
Andrei Popescu31002712010-02-23 13:46:05 +00009686 // Both strings are non-empty.
9687 // r0: first string
9688 // r1: second string
9689 // r2: length of first string
9690 // r3: length of second string
9691 // r4: first string instance type (if string_check_)
9692 // r5: second string instance type (if string_check_)
9693 // Look at the length of the result of adding the two strings.
Steve Block6ded16b2010-05-10 14:33:55 +01009694 Label string_add_flat_result, longer_than_two;
Andrei Popescu31002712010-02-23 13:46:05 +00009695 // Adding two lengths can't overflow.
9696 ASSERT(String::kMaxLength * 2 > String::kMaxLength);
9697 __ add(r6, r2, Operand(r3));
9698 // Use the runtime system when adding two one character strings, as it
9699 // contains optimizations for this specific case using the symbol table.
9700 __ cmp(r6, Operand(2));
Steve Block6ded16b2010-05-10 14:33:55 +01009701 __ b(ne, &longer_than_two);
9702
9703 // Check that both strings are non-external ascii strings.
9704 if (!string_check_) {
9705 __ ldr(r4, FieldMemOperand(r0, HeapObject::kMapOffset));
9706 __ ldr(r5, FieldMemOperand(r1, HeapObject::kMapOffset));
9707 __ ldrb(r4, FieldMemOperand(r4, Map::kInstanceTypeOffset));
9708 __ ldrb(r5, FieldMemOperand(r5, Map::kInstanceTypeOffset));
9709 }
9710 __ JumpIfBothInstanceTypesAreNotSequentialAscii(r4, r5, r6, r7,
9711 &string_add_runtime);
9712
9713 // Get the two characters forming the sub string.
9714 __ ldrb(r2, FieldMemOperand(r0, SeqAsciiString::kHeaderSize));
9715 __ ldrb(r3, FieldMemOperand(r1, SeqAsciiString::kHeaderSize));
9716
9717 // Try to lookup two character string in symbol table. If it is not found
9718 // just allocate a new one.
9719 Label make_two_character_string;
9720 StringHelper::GenerateTwoCharacterSymbolTableProbe(
9721 masm, r2, r3, r6, r7, r4, r5, r9, &make_two_character_string);
9722 __ IncrementCounter(&Counters::string_add_native, 1, r2, r3);
9723 __ add(sp, sp, Operand(2 * kPointerSize));
9724 __ Ret();
9725
9726 __ bind(&make_two_character_string);
9727 // Resulting string has length 2 and first chars of two strings
9728 // are combined into single halfword in r2 register.
9729 // So we can fill resulting string without two loops by a single
9730 // halfword store instruction (which assumes that processor is
9731 // in a little endian mode)
9732 __ mov(r6, Operand(2));
9733 __ AllocateAsciiString(r0, r6, r4, r5, r9, &string_add_runtime);
9734 __ strh(r2, FieldMemOperand(r0, SeqAsciiString::kHeaderSize));
9735 __ IncrementCounter(&Counters::string_add_native, 1, r2, r3);
9736 __ add(sp, sp, Operand(2 * kPointerSize));
9737 __ Ret();
9738
9739 __ bind(&longer_than_two);
Andrei Popescu31002712010-02-23 13:46:05 +00009740 // Check if resulting string will be flat.
9741 __ cmp(r6, Operand(String::kMinNonFlatLength));
9742 __ b(lt, &string_add_flat_result);
9743 // Handle exceptionally long strings in the runtime system.
9744 ASSERT((String::kMaxLength & 0x80000000) == 0);
9745 ASSERT(IsPowerOf2(String::kMaxLength + 1));
9746 // kMaxLength + 1 is representable as shifted literal, kMaxLength is not.
9747 __ cmp(r6, Operand(String::kMaxLength + 1));
9748 __ b(hs, &string_add_runtime);
9749
9750 // If result is not supposed to be flat, allocate a cons string object.
9751 // If both strings are ascii the result is an ascii cons string.
9752 if (!string_check_) {
9753 __ ldr(r4, FieldMemOperand(r0, HeapObject::kMapOffset));
9754 __ ldr(r5, FieldMemOperand(r1, HeapObject::kMapOffset));
9755 __ ldrb(r4, FieldMemOperand(r4, Map::kInstanceTypeOffset));
9756 __ ldrb(r5, FieldMemOperand(r5, Map::kInstanceTypeOffset));
9757 }
9758 Label non_ascii, allocated;
9759 ASSERT_EQ(0, kTwoByteStringTag);
9760 __ tst(r4, Operand(kStringEncodingMask));
9761 __ tst(r5, Operand(kStringEncodingMask), ne);
9762 __ b(eq, &non_ascii);
9763
9764 // Allocate an ASCII cons string.
9765 __ AllocateAsciiConsString(r7, r6, r4, r5, &string_add_runtime);
9766 __ bind(&allocated);
9767 // Fill the fields of the cons string.
9768 __ str(r0, FieldMemOperand(r7, ConsString::kFirstOffset));
9769 __ str(r1, FieldMemOperand(r7, ConsString::kSecondOffset));
9770 __ mov(r0, Operand(r7));
9771 __ IncrementCounter(&Counters::string_add_native, 1, r2, r3);
9772 __ add(sp, sp, Operand(2 * kPointerSize));
9773 __ Ret();
9774
9775 __ bind(&non_ascii);
9776 // Allocate a two byte cons string.
9777 __ AllocateTwoByteConsString(r7, r6, r4, r5, &string_add_runtime);
9778 __ jmp(&allocated);
9779
9780 // Handle creating a flat result. First check that both strings are
9781 // sequential and that they have the same encoding.
9782 // r0: first string
9783 // r1: second string
9784 // r2: length of first string
9785 // r3: length of second string
9786 // r4: first string instance type (if string_check_)
9787 // r5: second string instance type (if string_check_)
9788 // r6: sum of lengths.
9789 __ bind(&string_add_flat_result);
9790 if (!string_check_) {
9791 __ ldr(r4, FieldMemOperand(r0, HeapObject::kMapOffset));
9792 __ ldr(r5, FieldMemOperand(r1, HeapObject::kMapOffset));
9793 __ ldrb(r4, FieldMemOperand(r4, Map::kInstanceTypeOffset));
9794 __ ldrb(r5, FieldMemOperand(r5, Map::kInstanceTypeOffset));
9795 }
9796 // Check that both strings are sequential.
9797 ASSERT_EQ(0, kSeqStringTag);
9798 __ tst(r4, Operand(kStringRepresentationMask));
9799 __ tst(r5, Operand(kStringRepresentationMask), eq);
9800 __ b(ne, &string_add_runtime);
9801 // Now check if both strings have the same encoding (ASCII/Two-byte).
9802 // r0: first string.
9803 // r1: second string.
9804 // r2: length of first string.
9805 // r3: length of second string.
9806 // r6: sum of lengths..
9807 Label non_ascii_string_add_flat_result;
9808 ASSERT(IsPowerOf2(kStringEncodingMask)); // Just one bit to test.
9809 __ eor(r7, r4, Operand(r5));
9810 __ tst(r7, Operand(kStringEncodingMask));
9811 __ b(ne, &string_add_runtime);
9812 // And see if it's ASCII or two-byte.
9813 __ tst(r4, Operand(kStringEncodingMask));
9814 __ b(eq, &non_ascii_string_add_flat_result);
9815
9816 // Both strings are sequential ASCII strings. We also know that they are
9817 // short (since the sum of the lengths is less than kMinNonFlatLength).
Steve Block6ded16b2010-05-10 14:33:55 +01009818 // r6: length of resulting flat string
Andrei Popescu31002712010-02-23 13:46:05 +00009819 __ AllocateAsciiString(r7, r6, r4, r5, r9, &string_add_runtime);
9820 // Locate first character of result.
9821 __ add(r6, r7, Operand(SeqAsciiString::kHeaderSize - kHeapObjectTag));
9822 // Locate first character of first argument.
9823 __ add(r0, r0, Operand(SeqAsciiString::kHeaderSize - kHeapObjectTag));
9824 // r0: first character of first string.
9825 // r1: second string.
9826 // r2: length of first string.
9827 // r3: length of second string.
9828 // r6: first character of result.
9829 // r7: result string.
Steve Block6ded16b2010-05-10 14:33:55 +01009830 StringHelper::GenerateCopyCharacters(masm, r6, r0, r2, r4, true);
Andrei Popescu31002712010-02-23 13:46:05 +00009831
9832 // Load second argument and locate first character.
9833 __ add(r1, r1, Operand(SeqAsciiString::kHeaderSize - kHeapObjectTag));
9834 // r1: first character of second string.
9835 // r3: length of second string.
9836 // r6: next character of result.
9837 // r7: result string.
Steve Block6ded16b2010-05-10 14:33:55 +01009838 StringHelper::GenerateCopyCharacters(masm, r6, r1, r3, r4, true);
Andrei Popescu31002712010-02-23 13:46:05 +00009839 __ mov(r0, Operand(r7));
9840 __ IncrementCounter(&Counters::string_add_native, 1, r2, r3);
9841 __ add(sp, sp, Operand(2 * kPointerSize));
9842 __ Ret();
9843
9844 __ bind(&non_ascii_string_add_flat_result);
9845 // Both strings are sequential two byte strings.
9846 // r0: first string.
9847 // r1: second string.
9848 // r2: length of first string.
9849 // r3: length of second string.
9850 // r6: sum of length of strings.
9851 __ AllocateTwoByteString(r7, r6, r4, r5, r9, &string_add_runtime);
9852 // r0: first string.
9853 // r1: second string.
9854 // r2: length of first string.
9855 // r3: length of second string.
9856 // r7: result string.
9857
9858 // Locate first character of result.
9859 __ add(r6, r7, Operand(SeqTwoByteString::kHeaderSize - kHeapObjectTag));
9860 // Locate first character of first argument.
9861 __ add(r0, r0, Operand(SeqTwoByteString::kHeaderSize - kHeapObjectTag));
9862
9863 // r0: first character of first string.
9864 // r1: second string.
9865 // r2: length of first string.
9866 // r3: length of second string.
9867 // r6: first character of result.
9868 // r7: result string.
Steve Block6ded16b2010-05-10 14:33:55 +01009869 StringHelper::GenerateCopyCharacters(masm, r6, r0, r2, r4, false);
Andrei Popescu31002712010-02-23 13:46:05 +00009870
9871 // Locate first character of second argument.
9872 __ add(r1, r1, Operand(SeqTwoByteString::kHeaderSize - kHeapObjectTag));
9873
9874 // r1: first character of second string.
9875 // r3: length of second string.
9876 // r6: next character of result (after copy of first string).
9877 // r7: result string.
Steve Block6ded16b2010-05-10 14:33:55 +01009878 StringHelper::GenerateCopyCharacters(masm, r6, r1, r3, r4, false);
Andrei Popescu31002712010-02-23 13:46:05 +00009879
9880 __ mov(r0, Operand(r7));
9881 __ IncrementCounter(&Counters::string_add_native, 1, r2, r3);
9882 __ add(sp, sp, Operand(2 * kPointerSize));
9883 __ Ret();
9884
9885 // Just jump to runtime to add the two strings.
9886 __ bind(&string_add_runtime);
Steve Block6ded16b2010-05-10 14:33:55 +01009887 __ TailCallRuntime(Runtime::kStringAdd, 2, 1);
Andrei Popescu31002712010-02-23 13:46:05 +00009888}
9889
9890
Steve Blocka7e24c12009-10-30 11:49:00 +00009891#undef __
9892
9893} } // namespace v8::internal