blob: cf467733b6a43891805f46c0b1b50471587f83fd [file] [log] [blame]
Steve Blocka7e24c12009-10-30 11:49:00 +00001// Copyright 2006-2009 the V8 project authors. All rights reserved.
2// Redistribution and use in source and binary forms, with or without
3// modification, are permitted provided that the following conditions are
4// met:
5//
6// * Redistributions of source code must retain the above copyright
7// notice, this list of conditions and the following disclaimer.
8// * Redistributions in binary form must reproduce the above
9// copyright notice, this list of conditions and the following
10// disclaimer in the documentation and/or other materials provided
11// with the distribution.
12// * Neither the name of Google Inc. nor the names of its
13// contributors may be used to endorse or promote products derived
14// from this software without specific prior written permission.
15//
16// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27
28#include "v8.h"
29
30#include "bootstrapper.h"
31#include "codegen-inl.h"
32#include "debug.h"
33#include "runtime.h"
34
35namespace v8 {
36namespace internal {
37
38MacroAssembler::MacroAssembler(void* buffer, int size)
39 : Assembler(buffer, size),
40 unresolved_(0),
41 generating_stub_(false),
42 allow_stub_calls_(true),
43 code_object_(Heap::undefined_value()) {
44}
45
46
47// We always generate arm code, never thumb code, even if V8 is compiled to
48// thumb, so we require inter-working support
49#if defined(__thumb__) && !defined(USE_THUMB_INTERWORK)
50#error "flag -mthumb-interwork missing"
51#endif
52
53
54// We do not support thumb inter-working with an arm architecture not supporting
55// the blx instruction (below v5t). If you know what CPU you are compiling for
56// you can use -march=armv7 or similar.
57#if defined(USE_THUMB_INTERWORK) && !defined(CAN_USE_THUMB_INSTRUCTIONS)
58# error "For thumb inter-working we require an architecture which supports blx"
59#endif
60
61
62// Using blx may yield better code, so use it when required or when available
63#if defined(USE_THUMB_INTERWORK) || defined(CAN_USE_ARMV5_INSTRUCTIONS)
64#define USE_BLX 1
65#endif
66
67// Using bx does not yield better code, so use it only when required
68#if defined(USE_THUMB_INTERWORK)
69#define USE_BX 1
70#endif
71
72
73void MacroAssembler::Jump(Register target, Condition cond) {
74#if USE_BX
75 bx(target, cond);
76#else
77 mov(pc, Operand(target), LeaveCC, cond);
78#endif
79}
80
81
82void MacroAssembler::Jump(intptr_t target, RelocInfo::Mode rmode,
83 Condition cond) {
84#if USE_BX
85 mov(ip, Operand(target, rmode), LeaveCC, cond);
86 bx(ip, cond);
87#else
88 mov(pc, Operand(target, rmode), LeaveCC, cond);
89#endif
90}
91
92
93void MacroAssembler::Jump(byte* target, RelocInfo::Mode rmode,
94 Condition cond) {
95 ASSERT(!RelocInfo::IsCodeTarget(rmode));
96 Jump(reinterpret_cast<intptr_t>(target), rmode, cond);
97}
98
99
100void MacroAssembler::Jump(Handle<Code> code, RelocInfo::Mode rmode,
101 Condition cond) {
102 ASSERT(RelocInfo::IsCodeTarget(rmode));
103 // 'code' is always generated ARM code, never THUMB code
104 Jump(reinterpret_cast<intptr_t>(code.location()), rmode, cond);
105}
106
107
108void MacroAssembler::Call(Register target, Condition cond) {
109#if USE_BLX
110 blx(target, cond);
111#else
112 // set lr for return at current pc + 8
113 mov(lr, Operand(pc), LeaveCC, cond);
114 mov(pc, Operand(target), LeaveCC, cond);
115#endif
116}
117
118
119void MacroAssembler::Call(intptr_t target, RelocInfo::Mode rmode,
120 Condition cond) {
121 // Set lr for return at current pc + 8.
122 mov(lr, Operand(pc), LeaveCC, cond);
123 // Emit a ldr<cond> pc, [pc + offset of target in constant pool].
124 mov(pc, Operand(target, rmode), LeaveCC, cond);
125 // If USE_BLX is defined, we could emit a 'mov ip, target', followed by a
126 // 'blx ip'; however, the code would not be shorter than the above sequence
127 // and the target address of the call would be referenced by the first
128 // instruction rather than the second one, which would make it harder to patch
129 // (two instructions before the return address, instead of one).
130 ASSERT(kCallTargetAddressOffset == kInstrSize);
131}
132
133
134void MacroAssembler::Call(byte* target, RelocInfo::Mode rmode,
135 Condition cond) {
136 ASSERT(!RelocInfo::IsCodeTarget(rmode));
137 Call(reinterpret_cast<intptr_t>(target), rmode, cond);
138}
139
140
141void MacroAssembler::Call(Handle<Code> code, RelocInfo::Mode rmode,
142 Condition cond) {
143 ASSERT(RelocInfo::IsCodeTarget(rmode));
144 // 'code' is always generated ARM code, never THUMB code
145 Call(reinterpret_cast<intptr_t>(code.location()), rmode, cond);
146}
147
148
149void MacroAssembler::Ret(Condition cond) {
150#if USE_BX
151 bx(lr, cond);
152#else
153 mov(pc, Operand(lr), LeaveCC, cond);
154#endif
155}
156
157
158void MacroAssembler::SmiJumpTable(Register index, Vector<Label*> targets) {
159 // Empty the const pool.
160 CheckConstPool(true, true);
161 add(pc, pc, Operand(index,
162 LSL,
163 assembler::arm::Instr::kInstrSizeLog2 - kSmiTagSize));
164 BlockConstPoolBefore(pc_offset() + (targets.length() + 1) * kInstrSize);
165 nop(); // Jump table alignment.
166 for (int i = 0; i < targets.length(); i++) {
167 b(targets[i]);
168 }
169}
170
171
172void MacroAssembler::LoadRoot(Register destination,
173 Heap::RootListIndex index,
174 Condition cond) {
175 ldr(destination, MemOperand(r10, index << kPointerSizeLog2), cond);
176}
177
178
179// Will clobber 4 registers: object, offset, scratch, ip. The
180// register 'object' contains a heap object pointer. The heap object
181// tag is shifted away.
182void MacroAssembler::RecordWrite(Register object, Register offset,
183 Register scratch) {
184 // This is how much we shift the remembered set bit offset to get the
185 // offset of the word in the remembered set. We divide by kBitsPerInt (32,
186 // shift right 5) and then multiply by kIntSize (4, shift left 2).
187 const int kRSetWordShift = 3;
188
189 Label fast, done;
190
191 // First, test that the object is not in the new space. We cannot set
192 // remembered set bits in the new space.
193 // object: heap object pointer (with tag)
194 // offset: offset to store location from the object
195 and_(scratch, object, Operand(Heap::NewSpaceMask()));
196 cmp(scratch, Operand(ExternalReference::new_space_start()));
197 b(eq, &done);
198
199 // Compute the bit offset in the remembered set.
200 // object: heap object pointer (with tag)
201 // offset: offset to store location from the object
202 mov(ip, Operand(Page::kPageAlignmentMask)); // load mask only once
203 and_(scratch, object, Operand(ip)); // offset into page of the object
204 add(offset, scratch, Operand(offset)); // add offset into the object
205 mov(offset, Operand(offset, LSR, kObjectAlignmentBits));
206
207 // Compute the page address from the heap object pointer.
208 // object: heap object pointer (with tag)
209 // offset: bit offset of store position in the remembered set
210 bic(object, object, Operand(ip));
211
212 // If the bit offset lies beyond the normal remembered set range, it is in
213 // the extra remembered set area of a large object.
214 // object: page start
215 // offset: bit offset of store position in the remembered set
216 cmp(offset, Operand(Page::kPageSize / kPointerSize));
217 b(lt, &fast);
218
219 // Adjust the bit offset to be relative to the start of the extra
220 // remembered set and the start address to be the address of the extra
221 // remembered set.
222 sub(offset, offset, Operand(Page::kPageSize / kPointerSize));
223 // Load the array length into 'scratch' and multiply by four to get the
224 // size in bytes of the elements.
225 ldr(scratch, MemOperand(object, Page::kObjectStartOffset
226 + FixedArray::kLengthOffset));
227 mov(scratch, Operand(scratch, LSL, kObjectAlignmentBits));
228 // Add the page header (including remembered set), array header, and array
229 // body size to the page address.
230 add(object, object, Operand(Page::kObjectStartOffset
231 + FixedArray::kHeaderSize));
232 add(object, object, Operand(scratch));
233
234 bind(&fast);
235 // Get address of the rset word.
236 // object: start of the remembered set (page start for the fast case)
237 // offset: bit offset of store position in the remembered set
238 bic(scratch, offset, Operand(kBitsPerInt - 1)); // clear the bit offset
239 add(object, object, Operand(scratch, LSR, kRSetWordShift));
240 // Get bit offset in the rset word.
241 // object: address of remembered set word
242 // offset: bit offset of store position
243 and_(offset, offset, Operand(kBitsPerInt - 1));
244
245 ldr(scratch, MemOperand(object));
246 mov(ip, Operand(1));
247 orr(scratch, scratch, Operand(ip, LSL, offset));
248 str(scratch, MemOperand(object));
249
250 bind(&done);
251}
252
253
254void MacroAssembler::EnterFrame(StackFrame::Type type) {
255 // r0-r3: preserved
256 stm(db_w, sp, cp.bit() | fp.bit() | lr.bit());
257 mov(ip, Operand(Smi::FromInt(type)));
258 push(ip);
259 mov(ip, Operand(CodeObject()));
260 push(ip);
261 add(fp, sp, Operand(3 * kPointerSize)); // Adjust FP to point to saved FP.
262}
263
264
265void MacroAssembler::LeaveFrame(StackFrame::Type type) {
266 // r0: preserved
267 // r1: preserved
268 // r2: preserved
269
270 // Drop the execution stack down to the frame pointer and restore
271 // the caller frame pointer and return address.
272 mov(sp, fp);
273 ldm(ia_w, sp, fp.bit() | lr.bit());
274}
275
276
277void MacroAssembler::EnterExitFrame(StackFrame::Type type) {
278 ASSERT(type == StackFrame::EXIT || type == StackFrame::EXIT_DEBUG);
279
280 // Compute the argv pointer and keep it in a callee-saved register.
281 // r0 is argc.
282 add(r6, sp, Operand(r0, LSL, kPointerSizeLog2));
283 sub(r6, r6, Operand(kPointerSize));
284
285 // Compute callee's stack pointer before making changes and save it as
286 // ip register so that it is restored as sp register on exit, thereby
287 // popping the args.
288
289 // ip = sp + kPointerSize * #args;
290 add(ip, sp, Operand(r0, LSL, kPointerSizeLog2));
291
292 // Align the stack at this point. After this point we have 5 pushes,
293 // so in fact we have to unalign here! See also the assert on the
294 // alignment in AlignStack.
295 AlignStack(1);
296
297 // Push in reverse order: caller_fp, sp_on_exit, and caller_pc.
298 stm(db_w, sp, fp.bit() | ip.bit() | lr.bit());
299 mov(fp, Operand(sp)); // setup new frame pointer
300
301 // Push debug marker.
302 mov(ip, Operand(type == StackFrame::EXIT_DEBUG ? 1 : 0));
303 push(ip);
304
305 // Save the frame pointer and the context in top.
306 mov(ip, Operand(ExternalReference(Top::k_c_entry_fp_address)));
307 str(fp, MemOperand(ip));
308 mov(ip, Operand(ExternalReference(Top::k_context_address)));
309 str(cp, MemOperand(ip));
310
311 // Setup argc and the builtin function in callee-saved registers.
312 mov(r4, Operand(r0));
313 mov(r5, Operand(r1));
314
315
316#ifdef ENABLE_DEBUGGER_SUPPORT
317 // Save the state of all registers to the stack from the memory
318 // location. This is needed to allow nested break points.
319 if (type == StackFrame::EXIT_DEBUG) {
320 // Use sp as base to push.
321 CopyRegistersFromMemoryToStack(sp, kJSCallerSaved);
322 }
323#endif
324}
325
326
327void MacroAssembler::AlignStack(int offset) {
328#if defined(V8_HOST_ARCH_ARM)
329 // Running on the real platform. Use the alignment as mandated by the local
330 // environment.
331 // Note: This will break if we ever start generating snapshots on one ARM
332 // platform for another ARM platform with a different alignment.
333 int activation_frame_alignment = OS::ActivationFrameAlignment();
334#else // defined(V8_HOST_ARCH_ARM)
335 // If we are using the simulator then we should always align to the expected
336 // alignment. As the simulator is used to generate snapshots we do not know
337 // if the target platform will need alignment, so we will always align at
338 // this point here.
339 int activation_frame_alignment = 2 * kPointerSize;
340#endif // defined(V8_HOST_ARCH_ARM)
341 if (activation_frame_alignment != kPointerSize) {
342 // This code needs to be made more general if this assert doesn't hold.
343 ASSERT(activation_frame_alignment == 2 * kPointerSize);
344 mov(r7, Operand(Smi::FromInt(0)));
345 tst(sp, Operand(activation_frame_alignment - offset));
346 push(r7, eq); // Conditional push instruction.
347 }
348}
349
350
351void MacroAssembler::LeaveExitFrame(StackFrame::Type type) {
352#ifdef ENABLE_DEBUGGER_SUPPORT
353 // Restore the memory copy of the registers by digging them out from
354 // the stack. This is needed to allow nested break points.
355 if (type == StackFrame::EXIT_DEBUG) {
356 // This code intentionally clobbers r2 and r3.
357 const int kCallerSavedSize = kNumJSCallerSaved * kPointerSize;
358 const int kOffset = ExitFrameConstants::kDebugMarkOffset - kCallerSavedSize;
359 add(r3, fp, Operand(kOffset));
360 CopyRegistersFromStackToMemory(r3, r2, kJSCallerSaved);
361 }
362#endif
363
364 // Clear top frame.
365 mov(r3, Operand(0));
366 mov(ip, Operand(ExternalReference(Top::k_c_entry_fp_address)));
367 str(r3, MemOperand(ip));
368
369 // Restore current context from top and clear it in debug mode.
370 mov(ip, Operand(ExternalReference(Top::k_context_address)));
371 ldr(cp, MemOperand(ip));
372#ifdef DEBUG
373 str(r3, MemOperand(ip));
374#endif
375
376 // Pop the arguments, restore registers, and return.
377 mov(sp, Operand(fp)); // respect ABI stack constraint
378 ldm(ia, sp, fp.bit() | sp.bit() | pc.bit());
379}
380
381
382void MacroAssembler::InvokePrologue(const ParameterCount& expected,
383 const ParameterCount& actual,
384 Handle<Code> code_constant,
385 Register code_reg,
386 Label* done,
387 InvokeFlag flag) {
388 bool definitely_matches = false;
389 Label regular_invoke;
390
391 // Check whether the expected and actual arguments count match. If not,
392 // setup registers according to contract with ArgumentsAdaptorTrampoline:
393 // r0: actual arguments count
394 // r1: function (passed through to callee)
395 // r2: expected arguments count
396 // r3: callee code entry
397
398 // The code below is made a lot easier because the calling code already sets
399 // up actual and expected registers according to the contract if values are
400 // passed in registers.
401 ASSERT(actual.is_immediate() || actual.reg().is(r0));
402 ASSERT(expected.is_immediate() || expected.reg().is(r2));
403 ASSERT((!code_constant.is_null() && code_reg.is(no_reg)) || code_reg.is(r3));
404
405 if (expected.is_immediate()) {
406 ASSERT(actual.is_immediate());
407 if (expected.immediate() == actual.immediate()) {
408 definitely_matches = true;
409 } else {
410 mov(r0, Operand(actual.immediate()));
411 const int sentinel = SharedFunctionInfo::kDontAdaptArgumentsSentinel;
412 if (expected.immediate() == sentinel) {
413 // Don't worry about adapting arguments for builtins that
414 // don't want that done. Skip adaption code by making it look
415 // like we have a match between expected and actual number of
416 // arguments.
417 definitely_matches = true;
418 } else {
419 mov(r2, Operand(expected.immediate()));
420 }
421 }
422 } else {
423 if (actual.is_immediate()) {
424 cmp(expected.reg(), Operand(actual.immediate()));
425 b(eq, &regular_invoke);
426 mov(r0, Operand(actual.immediate()));
427 } else {
428 cmp(expected.reg(), Operand(actual.reg()));
429 b(eq, &regular_invoke);
430 }
431 }
432
433 if (!definitely_matches) {
434 if (!code_constant.is_null()) {
435 mov(r3, Operand(code_constant));
436 add(r3, r3, Operand(Code::kHeaderSize - kHeapObjectTag));
437 }
438
439 Handle<Code> adaptor =
440 Handle<Code>(Builtins::builtin(Builtins::ArgumentsAdaptorTrampoline));
441 if (flag == CALL_FUNCTION) {
442 Call(adaptor, RelocInfo::CODE_TARGET);
443 b(done);
444 } else {
445 Jump(adaptor, RelocInfo::CODE_TARGET);
446 }
447 bind(&regular_invoke);
448 }
449}
450
451
452void MacroAssembler::InvokeCode(Register code,
453 const ParameterCount& expected,
454 const ParameterCount& actual,
455 InvokeFlag flag) {
456 Label done;
457
458 InvokePrologue(expected, actual, Handle<Code>::null(), code, &done, flag);
459 if (flag == CALL_FUNCTION) {
460 Call(code);
461 } else {
462 ASSERT(flag == JUMP_FUNCTION);
463 Jump(code);
464 }
465
466 // Continue here if InvokePrologue does handle the invocation due to
467 // mismatched parameter counts.
468 bind(&done);
469}
470
471
472void MacroAssembler::InvokeCode(Handle<Code> code,
473 const ParameterCount& expected,
474 const ParameterCount& actual,
475 RelocInfo::Mode rmode,
476 InvokeFlag flag) {
477 Label done;
478
479 InvokePrologue(expected, actual, code, no_reg, &done, flag);
480 if (flag == CALL_FUNCTION) {
481 Call(code, rmode);
482 } else {
483 Jump(code, rmode);
484 }
485
486 // Continue here if InvokePrologue does handle the invocation due to
487 // mismatched parameter counts.
488 bind(&done);
489}
490
491
492void MacroAssembler::InvokeFunction(Register fun,
493 const ParameterCount& actual,
494 InvokeFlag flag) {
495 // Contract with called JS functions requires that function is passed in r1.
496 ASSERT(fun.is(r1));
497
498 Register expected_reg = r2;
499 Register code_reg = r3;
500
501 ldr(code_reg, FieldMemOperand(r1, JSFunction::kSharedFunctionInfoOffset));
502 ldr(cp, FieldMemOperand(r1, JSFunction::kContextOffset));
503 ldr(expected_reg,
504 FieldMemOperand(code_reg,
505 SharedFunctionInfo::kFormalParameterCountOffset));
506 ldr(code_reg,
507 MemOperand(code_reg, SharedFunctionInfo::kCodeOffset - kHeapObjectTag));
508 add(code_reg, code_reg, Operand(Code::kHeaderSize - kHeapObjectTag));
509
510 ParameterCount expected(expected_reg);
511 InvokeCode(code_reg, expected, actual, flag);
512}
513
514
515#ifdef ENABLE_DEBUGGER_SUPPORT
516void MacroAssembler::SaveRegistersToMemory(RegList regs) {
517 ASSERT((regs & ~kJSCallerSaved) == 0);
518 // Copy the content of registers to memory location.
519 for (int i = 0; i < kNumJSCallerSaved; i++) {
520 int r = JSCallerSavedCode(i);
521 if ((regs & (1 << r)) != 0) {
522 Register reg = { r };
523 mov(ip, Operand(ExternalReference(Debug_Address::Register(i))));
524 str(reg, MemOperand(ip));
525 }
526 }
527}
528
529
530void MacroAssembler::RestoreRegistersFromMemory(RegList regs) {
531 ASSERT((regs & ~kJSCallerSaved) == 0);
532 // Copy the content of memory location to registers.
533 for (int i = kNumJSCallerSaved; --i >= 0;) {
534 int r = JSCallerSavedCode(i);
535 if ((regs & (1 << r)) != 0) {
536 Register reg = { r };
537 mov(ip, Operand(ExternalReference(Debug_Address::Register(i))));
538 ldr(reg, MemOperand(ip));
539 }
540 }
541}
542
543
544void MacroAssembler::CopyRegistersFromMemoryToStack(Register base,
545 RegList regs) {
546 ASSERT((regs & ~kJSCallerSaved) == 0);
547 // Copy the content of the memory location to the stack and adjust base.
548 for (int i = kNumJSCallerSaved; --i >= 0;) {
549 int r = JSCallerSavedCode(i);
550 if ((regs & (1 << r)) != 0) {
551 mov(ip, Operand(ExternalReference(Debug_Address::Register(i))));
552 ldr(ip, MemOperand(ip));
553 str(ip, MemOperand(base, 4, NegPreIndex));
554 }
555 }
556}
557
558
559void MacroAssembler::CopyRegistersFromStackToMemory(Register base,
560 Register scratch,
561 RegList regs) {
562 ASSERT((regs & ~kJSCallerSaved) == 0);
563 // Copy the content of the stack to the memory location and adjust base.
564 for (int i = 0; i < kNumJSCallerSaved; i++) {
565 int r = JSCallerSavedCode(i);
566 if ((regs & (1 << r)) != 0) {
567 mov(ip, Operand(ExternalReference(Debug_Address::Register(i))));
568 ldr(scratch, MemOperand(base, 4, PostIndex));
569 str(scratch, MemOperand(ip));
570 }
571 }
572}
573#endif
574
575
576void MacroAssembler::PushTryHandler(CodeLocation try_location,
577 HandlerType type) {
578 // Adjust this code if not the case.
579 ASSERT(StackHandlerConstants::kSize == 4 * kPointerSize);
580 // The pc (return address) is passed in register lr.
581 if (try_location == IN_JAVASCRIPT) {
582 if (type == TRY_CATCH_HANDLER) {
583 mov(r3, Operand(StackHandler::TRY_CATCH));
584 } else {
585 mov(r3, Operand(StackHandler::TRY_FINALLY));
586 }
587 ASSERT(StackHandlerConstants::kStateOffset == 1 * kPointerSize
588 && StackHandlerConstants::kFPOffset == 2 * kPointerSize
589 && StackHandlerConstants::kPCOffset == 3 * kPointerSize);
590 stm(db_w, sp, r3.bit() | fp.bit() | lr.bit());
591 // Save the current handler as the next handler.
592 mov(r3, Operand(ExternalReference(Top::k_handler_address)));
593 ldr(r1, MemOperand(r3));
594 ASSERT(StackHandlerConstants::kNextOffset == 0);
595 push(r1);
596 // Link this handler as the new current one.
597 str(sp, MemOperand(r3));
598 } else {
599 // Must preserve r0-r4, r5-r7 are available.
600 ASSERT(try_location == IN_JS_ENTRY);
601 // The frame pointer does not point to a JS frame so we save NULL
602 // for fp. We expect the code throwing an exception to check fp
603 // before dereferencing it to restore the context.
604 mov(ip, Operand(0)); // To save a NULL frame pointer.
605 mov(r6, Operand(StackHandler::ENTRY));
606 ASSERT(StackHandlerConstants::kStateOffset == 1 * kPointerSize
607 && StackHandlerConstants::kFPOffset == 2 * kPointerSize
608 && StackHandlerConstants::kPCOffset == 3 * kPointerSize);
609 stm(db_w, sp, r6.bit() | ip.bit() | lr.bit());
610 // Save the current handler as the next handler.
611 mov(r7, Operand(ExternalReference(Top::k_handler_address)));
612 ldr(r6, MemOperand(r7));
613 ASSERT(StackHandlerConstants::kNextOffset == 0);
614 push(r6);
615 // Link this handler as the new current one.
616 str(sp, MemOperand(r7));
617 }
618}
619
620
621Register MacroAssembler::CheckMaps(JSObject* object, Register object_reg,
622 JSObject* holder, Register holder_reg,
623 Register scratch,
624 Label* miss) {
625 // Make sure there's no overlap between scratch and the other
626 // registers.
627 ASSERT(!scratch.is(object_reg) && !scratch.is(holder_reg));
628
629 // Keep track of the current object in register reg.
630 Register reg = object_reg;
631 int depth = 1;
632
633 // Check the maps in the prototype chain.
634 // Traverse the prototype chain from the object and do map checks.
635 while (object != holder) {
636 depth++;
637
638 // Only global objects and objects that do not require access
639 // checks are allowed in stubs.
640 ASSERT(object->IsJSGlobalProxy() || !object->IsAccessCheckNeeded());
641
642 // Get the map of the current object.
643 ldr(scratch, FieldMemOperand(reg, HeapObject::kMapOffset));
644 cmp(scratch, Operand(Handle<Map>(object->map())));
645
646 // Branch on the result of the map check.
647 b(ne, miss);
648
649 // Check access rights to the global object. This has to happen
650 // after the map check so that we know that the object is
651 // actually a global object.
652 if (object->IsJSGlobalProxy()) {
653 CheckAccessGlobalProxy(reg, scratch, miss);
654 // Restore scratch register to be the map of the object. In the
655 // new space case below, we load the prototype from the map in
656 // the scratch register.
657 ldr(scratch, FieldMemOperand(reg, HeapObject::kMapOffset));
658 }
659
660 reg = holder_reg; // from now the object is in holder_reg
661 JSObject* prototype = JSObject::cast(object->GetPrototype());
662 if (Heap::InNewSpace(prototype)) {
663 // The prototype is in new space; we cannot store a reference
664 // to it in the code. Load it from the map.
665 ldr(reg, FieldMemOperand(scratch, Map::kPrototypeOffset));
666 } else {
667 // The prototype is in old space; load it directly.
668 mov(reg, Operand(Handle<JSObject>(prototype)));
669 }
670
671 // Go to the next object in the prototype chain.
672 object = prototype;
673 }
674
675 // Check the holder map.
676 ldr(scratch, FieldMemOperand(reg, HeapObject::kMapOffset));
677 cmp(scratch, Operand(Handle<Map>(object->map())));
678 b(ne, miss);
679
680 // Log the check depth.
681 LOG(IntEvent("check-maps-depth", depth));
682
683 // Perform security check for access to the global object and return
684 // the holder register.
685 ASSERT(object == holder);
686 ASSERT(object->IsJSGlobalProxy() || !object->IsAccessCheckNeeded());
687 if (object->IsJSGlobalProxy()) {
688 CheckAccessGlobalProxy(reg, scratch, miss);
689 }
690 return reg;
691}
692
693
694void MacroAssembler::CheckAccessGlobalProxy(Register holder_reg,
695 Register scratch,
696 Label* miss) {
697 Label same_contexts;
698
699 ASSERT(!holder_reg.is(scratch));
700 ASSERT(!holder_reg.is(ip));
701 ASSERT(!scratch.is(ip));
702
703 // Load current lexical context from the stack frame.
704 ldr(scratch, MemOperand(fp, StandardFrameConstants::kContextOffset));
705 // In debug mode, make sure the lexical context is set.
706#ifdef DEBUG
707 cmp(scratch, Operand(0));
708 Check(ne, "we should not have an empty lexical context");
709#endif
710
711 // Load the global context of the current context.
712 int offset = Context::kHeaderSize + Context::GLOBAL_INDEX * kPointerSize;
713 ldr(scratch, FieldMemOperand(scratch, offset));
714 ldr(scratch, FieldMemOperand(scratch, GlobalObject::kGlobalContextOffset));
715
716 // Check the context is a global context.
717 if (FLAG_debug_code) {
718 // TODO(119): avoid push(holder_reg)/pop(holder_reg)
719 // Cannot use ip as a temporary in this verification code. Due to the fact
720 // that ip is clobbered as part of cmp with an object Operand.
721 push(holder_reg); // Temporarily save holder on the stack.
722 // Read the first word and compare to the global_context_map.
723 ldr(holder_reg, FieldMemOperand(scratch, HeapObject::kMapOffset));
724 LoadRoot(ip, Heap::kGlobalContextMapRootIndex);
725 cmp(holder_reg, ip);
726 Check(eq, "JSGlobalObject::global_context should be a global context.");
727 pop(holder_reg); // Restore holder.
728 }
729
730 // Check if both contexts are the same.
731 ldr(ip, FieldMemOperand(holder_reg, JSGlobalProxy::kContextOffset));
732 cmp(scratch, Operand(ip));
733 b(eq, &same_contexts);
734
735 // Check the context is a global context.
736 if (FLAG_debug_code) {
737 // TODO(119): avoid push(holder_reg)/pop(holder_reg)
738 // Cannot use ip as a temporary in this verification code. Due to the fact
739 // that ip is clobbered as part of cmp with an object Operand.
740 push(holder_reg); // Temporarily save holder on the stack.
741 mov(holder_reg, ip); // Move ip to its holding place.
742 LoadRoot(ip, Heap::kNullValueRootIndex);
743 cmp(holder_reg, ip);
744 Check(ne, "JSGlobalProxy::context() should not be null.");
745
746 ldr(holder_reg, FieldMemOperand(holder_reg, HeapObject::kMapOffset));
747 LoadRoot(ip, Heap::kGlobalContextMapRootIndex);
748 cmp(holder_reg, ip);
749 Check(eq, "JSGlobalObject::global_context should be a global context.");
750 // Restore ip is not needed. ip is reloaded below.
751 pop(holder_reg); // Restore holder.
752 // Restore ip to holder's context.
753 ldr(ip, FieldMemOperand(holder_reg, JSGlobalProxy::kContextOffset));
754 }
755
756 // Check that the security token in the calling global object is
757 // compatible with the security token in the receiving global
758 // object.
759 int token_offset = Context::kHeaderSize +
760 Context::SECURITY_TOKEN_INDEX * kPointerSize;
761
762 ldr(scratch, FieldMemOperand(scratch, token_offset));
763 ldr(ip, FieldMemOperand(ip, token_offset));
764 cmp(scratch, Operand(ip));
765 b(ne, miss);
766
767 bind(&same_contexts);
768}
769
770
771void MacroAssembler::AllocateInNewSpace(int object_size,
772 Register result,
773 Register scratch1,
774 Register scratch2,
775 Label* gc_required,
776 AllocationFlags flags) {
777 ASSERT(!result.is(scratch1));
778 ASSERT(!scratch1.is(scratch2));
779
780 // Load address of new object into result and allocation top address into
781 // scratch1.
782 ExternalReference new_space_allocation_top =
783 ExternalReference::new_space_allocation_top_address();
784 mov(scratch1, Operand(new_space_allocation_top));
785 if ((flags & RESULT_CONTAINS_TOP) == 0) {
786 ldr(result, MemOperand(scratch1));
787 } else {
788#ifdef DEBUG
789 // Assert that result actually contains top on entry. scratch2 is used
790 // immediately below so this use of scratch2 does not cause difference with
791 // respect to register content between debug and release mode.
792 ldr(scratch2, MemOperand(scratch1));
793 cmp(result, scratch2);
794 Check(eq, "Unexpected allocation top");
795#endif
796 }
797
798 // Calculate new top and bail out if new space is exhausted. Use result
799 // to calculate the new top.
800 ExternalReference new_space_allocation_limit =
801 ExternalReference::new_space_allocation_limit_address();
802 mov(scratch2, Operand(new_space_allocation_limit));
803 ldr(scratch2, MemOperand(scratch2));
804 add(result, result, Operand(object_size * kPointerSize));
805 cmp(result, Operand(scratch2));
806 b(hi, gc_required);
807
808 // Update allocation top. result temporarily holds the new top,
809 str(result, MemOperand(scratch1));
810
811 // Tag and adjust back to start of new object.
812 if ((flags & TAG_OBJECT) != 0) {
813 sub(result, result, Operand((object_size * kPointerSize) -
814 kHeapObjectTag));
815 } else {
816 sub(result, result, Operand(object_size * kPointerSize));
817 }
818}
819
820
821void MacroAssembler::AllocateInNewSpace(Register object_size,
822 Register result,
823 Register scratch1,
824 Register scratch2,
825 Label* gc_required,
826 AllocationFlags flags) {
827 ASSERT(!result.is(scratch1));
828 ASSERT(!scratch1.is(scratch2));
829
830 // Load address of new object into result and allocation top address into
831 // scratch1.
832 ExternalReference new_space_allocation_top =
833 ExternalReference::new_space_allocation_top_address();
834 mov(scratch1, Operand(new_space_allocation_top));
835 if ((flags & RESULT_CONTAINS_TOP) == 0) {
836 ldr(result, MemOperand(scratch1));
837 } else {
838#ifdef DEBUG
839 // Assert that result actually contains top on entry. scratch2 is used
840 // immediately below so this use of scratch2 does not cause difference with
841 // respect to register content between debug and release mode.
842 ldr(scratch2, MemOperand(scratch1));
843 cmp(result, scratch2);
844 Check(eq, "Unexpected allocation top");
845#endif
846 }
847
848 // Calculate new top and bail out if new space is exhausted. Use result
849 // to calculate the new top. Object size is in words so a shift is required to
850 // get the number of bytes
851 ExternalReference new_space_allocation_limit =
852 ExternalReference::new_space_allocation_limit_address();
853 mov(scratch2, Operand(new_space_allocation_limit));
854 ldr(scratch2, MemOperand(scratch2));
855 add(result, result, Operand(object_size, LSL, kPointerSizeLog2));
856 cmp(result, Operand(scratch2));
857 b(hi, gc_required);
858
859 // Update allocation top. result temporarily holds the new top,
860 str(result, MemOperand(scratch1));
861
862 // Adjust back to start of new object.
863 sub(result, result, Operand(object_size, LSL, kPointerSizeLog2));
864
865 // Tag object if requested.
866 if ((flags & TAG_OBJECT) != 0) {
867 add(result, result, Operand(kHeapObjectTag));
868 }
869}
870
871
872void MacroAssembler::UndoAllocationInNewSpace(Register object,
873 Register scratch) {
874 ExternalReference new_space_allocation_top =
875 ExternalReference::new_space_allocation_top_address();
876
877 // Make sure the object has no tag before resetting top.
878 and_(object, object, Operand(~kHeapObjectTagMask));
879#ifdef DEBUG
880 // Check that the object un-allocated is below the current top.
881 mov(scratch, Operand(new_space_allocation_top));
882 ldr(scratch, MemOperand(scratch));
883 cmp(object, scratch);
884 Check(lt, "Undo allocation of non allocated memory");
885#endif
886 // Write the address of the object to un-allocate as the current top.
887 mov(scratch, Operand(new_space_allocation_top));
888 str(object, MemOperand(scratch));
889}
890
891
892void MacroAssembler::CompareObjectType(Register function,
893 Register map,
894 Register type_reg,
895 InstanceType type) {
896 ldr(map, FieldMemOperand(function, HeapObject::kMapOffset));
897 CompareInstanceType(map, type_reg, type);
898}
899
900
901void MacroAssembler::CompareInstanceType(Register map,
902 Register type_reg,
903 InstanceType type) {
904 ldrb(type_reg, FieldMemOperand(map, Map::kInstanceTypeOffset));
905 cmp(type_reg, Operand(type));
906}
907
908
909void MacroAssembler::TryGetFunctionPrototype(Register function,
910 Register result,
911 Register scratch,
912 Label* miss) {
913 // Check that the receiver isn't a smi.
914 BranchOnSmi(function, miss);
915
916 // Check that the function really is a function. Load map into result reg.
917 CompareObjectType(function, result, scratch, JS_FUNCTION_TYPE);
918 b(ne, miss);
919
920 // Make sure that the function has an instance prototype.
921 Label non_instance;
922 ldrb(scratch, FieldMemOperand(result, Map::kBitFieldOffset));
923 tst(scratch, Operand(1 << Map::kHasNonInstancePrototype));
924 b(ne, &non_instance);
925
926 // Get the prototype or initial map from the function.
927 ldr(result,
928 FieldMemOperand(function, JSFunction::kPrototypeOrInitialMapOffset));
929
930 // If the prototype or initial map is the hole, don't return it and
931 // simply miss the cache instead. This will allow us to allocate a
932 // prototype object on-demand in the runtime system.
933 LoadRoot(ip, Heap::kTheHoleValueRootIndex);
934 cmp(result, ip);
935 b(eq, miss);
936
937 // If the function does not have an initial map, we're done.
938 Label done;
939 CompareObjectType(result, scratch, scratch, MAP_TYPE);
940 b(ne, &done);
941
942 // Get the prototype from the initial map.
943 ldr(result, FieldMemOperand(result, Map::kPrototypeOffset));
944 jmp(&done);
945
946 // Non-instance prototype: Fetch prototype from constructor field
947 // in initial map.
948 bind(&non_instance);
949 ldr(result, FieldMemOperand(result, Map::kConstructorOffset));
950
951 // All done.
952 bind(&done);
953}
954
955
956void MacroAssembler::CallStub(CodeStub* stub, Condition cond) {
957 ASSERT(allow_stub_calls()); // stub calls are not allowed in some stubs
958 Call(stub->GetCode(), RelocInfo::CODE_TARGET, cond);
959}
960
961
962void MacroAssembler::StubReturn(int argc) {
963 ASSERT(argc >= 1 && generating_stub());
964 if (argc > 1)
965 add(sp, sp, Operand((argc - 1) * kPointerSize));
966 Ret();
967}
968
969
970void MacroAssembler::IllegalOperation(int num_arguments) {
971 if (num_arguments > 0) {
972 add(sp, sp, Operand(num_arguments * kPointerSize));
973 }
974 LoadRoot(r0, Heap::kUndefinedValueRootIndex);
975}
976
977
978void MacroAssembler::CallRuntime(Runtime::Function* f, int num_arguments) {
979 // All parameters are on the stack. r0 has the return value after call.
980
981 // If the expected number of arguments of the runtime function is
982 // constant, we check that the actual number of arguments match the
983 // expectation.
984 if (f->nargs >= 0 && f->nargs != num_arguments) {
985 IllegalOperation(num_arguments);
986 return;
987 }
988
989 Runtime::FunctionId function_id =
990 static_cast<Runtime::FunctionId>(f->stub_id);
991 RuntimeStub stub(function_id, num_arguments);
992 CallStub(&stub);
993}
994
995
996void MacroAssembler::CallRuntime(Runtime::FunctionId fid, int num_arguments) {
997 CallRuntime(Runtime::FunctionForId(fid), num_arguments);
998}
999
1000
1001void MacroAssembler::TailCallRuntime(const ExternalReference& ext,
1002 int num_arguments,
1003 int result_size) {
1004 // TODO(1236192): Most runtime routines don't need the number of
1005 // arguments passed in because it is constant. At some point we
1006 // should remove this need and make the runtime routine entry code
1007 // smarter.
1008 mov(r0, Operand(num_arguments));
1009 JumpToRuntime(ext);
1010}
1011
1012
1013void MacroAssembler::JumpToRuntime(const ExternalReference& builtin) {
1014#if defined(__thumb__)
1015 // Thumb mode builtin.
1016 ASSERT((reinterpret_cast<intptr_t>(builtin.address()) & 1) == 1);
1017#endif
1018 mov(r1, Operand(builtin));
1019 CEntryStub stub(1);
1020 Jump(stub.GetCode(), RelocInfo::CODE_TARGET);
1021}
1022
1023
1024Handle<Code> MacroAssembler::ResolveBuiltin(Builtins::JavaScript id,
1025 bool* resolved) {
1026 // Contract with compiled functions is that the function is passed in r1.
1027 int builtins_offset =
1028 JSBuiltinsObject::kJSBuiltinsOffset + (id * kPointerSize);
1029 ldr(r1, MemOperand(cp, Context::SlotOffset(Context::GLOBAL_INDEX)));
1030 ldr(r1, FieldMemOperand(r1, GlobalObject::kBuiltinsOffset));
1031 ldr(r1, FieldMemOperand(r1, builtins_offset));
1032
1033 return Builtins::GetCode(id, resolved);
1034}
1035
1036
1037void MacroAssembler::InvokeBuiltin(Builtins::JavaScript id,
1038 InvokeJSFlags flags) {
1039 bool resolved;
1040 Handle<Code> code = ResolveBuiltin(id, &resolved);
1041
1042 if (flags == CALL_JS) {
1043 Call(code, RelocInfo::CODE_TARGET);
1044 } else {
1045 ASSERT(flags == JUMP_JS);
1046 Jump(code, RelocInfo::CODE_TARGET);
1047 }
1048
1049 if (!resolved) {
1050 const char* name = Builtins::GetName(id);
1051 int argc = Builtins::GetArgumentsCount(id);
1052 uint32_t flags =
1053 Bootstrapper::FixupFlagsArgumentsCount::encode(argc) |
1054 Bootstrapper::FixupFlagsIsPCRelative::encode(true) |
1055 Bootstrapper::FixupFlagsUseCodeObject::encode(false);
1056 Unresolved entry = { pc_offset() - kInstrSize, flags, name };
1057 unresolved_.Add(entry);
1058 }
1059}
1060
1061
1062void MacroAssembler::GetBuiltinEntry(Register target, Builtins::JavaScript id) {
1063 bool resolved;
1064 Handle<Code> code = ResolveBuiltin(id, &resolved);
1065
1066 mov(target, Operand(code));
1067 if (!resolved) {
1068 const char* name = Builtins::GetName(id);
1069 int argc = Builtins::GetArgumentsCount(id);
1070 uint32_t flags =
1071 Bootstrapper::FixupFlagsArgumentsCount::encode(argc) |
1072 Bootstrapper::FixupFlagsIsPCRelative::encode(true) |
1073 Bootstrapper::FixupFlagsUseCodeObject::encode(true);
1074 Unresolved entry = { pc_offset() - kInstrSize, flags, name };
1075 unresolved_.Add(entry);
1076 }
1077
1078 add(target, target, Operand(Code::kHeaderSize - kHeapObjectTag));
1079}
1080
1081
1082void MacroAssembler::SetCounter(StatsCounter* counter, int value,
1083 Register scratch1, Register scratch2) {
1084 if (FLAG_native_code_counters && counter->Enabled()) {
1085 mov(scratch1, Operand(value));
1086 mov(scratch2, Operand(ExternalReference(counter)));
1087 str(scratch1, MemOperand(scratch2));
1088 }
1089}
1090
1091
1092void MacroAssembler::IncrementCounter(StatsCounter* counter, int value,
1093 Register scratch1, Register scratch2) {
1094 ASSERT(value > 0);
1095 if (FLAG_native_code_counters && counter->Enabled()) {
1096 mov(scratch2, Operand(ExternalReference(counter)));
1097 ldr(scratch1, MemOperand(scratch2));
1098 add(scratch1, scratch1, Operand(value));
1099 str(scratch1, MemOperand(scratch2));
1100 }
1101}
1102
1103
1104void MacroAssembler::DecrementCounter(StatsCounter* counter, int value,
1105 Register scratch1, Register scratch2) {
1106 ASSERT(value > 0);
1107 if (FLAG_native_code_counters && counter->Enabled()) {
1108 mov(scratch2, Operand(ExternalReference(counter)));
1109 ldr(scratch1, MemOperand(scratch2));
1110 sub(scratch1, scratch1, Operand(value));
1111 str(scratch1, MemOperand(scratch2));
1112 }
1113}
1114
1115
1116void MacroAssembler::Assert(Condition cc, const char* msg) {
1117 if (FLAG_debug_code)
1118 Check(cc, msg);
1119}
1120
1121
1122void MacroAssembler::Check(Condition cc, const char* msg) {
1123 Label L;
1124 b(cc, &L);
1125 Abort(msg);
1126 // will not return here
1127 bind(&L);
1128}
1129
1130
1131void MacroAssembler::Abort(const char* msg) {
1132 // We want to pass the msg string like a smi to avoid GC
1133 // problems, however msg is not guaranteed to be aligned
1134 // properly. Instead, we pass an aligned pointer that is
1135 // a proper v8 smi, but also pass the alignment difference
1136 // from the real pointer as a smi.
1137 intptr_t p1 = reinterpret_cast<intptr_t>(msg);
1138 intptr_t p0 = (p1 & ~kSmiTagMask) + kSmiTag;
1139 ASSERT(reinterpret_cast<Object*>(p0)->IsSmi());
1140#ifdef DEBUG
1141 if (msg != NULL) {
1142 RecordComment("Abort message: ");
1143 RecordComment(msg);
1144 }
1145#endif
1146 mov(r0, Operand(p0));
1147 push(r0);
1148 mov(r0, Operand(Smi::FromInt(p1 - p0)));
1149 push(r0);
1150 CallRuntime(Runtime::kAbort, 2);
1151 // will not return here
1152}
1153
1154
1155#ifdef ENABLE_DEBUGGER_SUPPORT
1156CodePatcher::CodePatcher(byte* address, int instructions)
1157 : address_(address),
1158 instructions_(instructions),
1159 size_(instructions * Assembler::kInstrSize),
1160 masm_(address, size_ + Assembler::kGap) {
1161 // Create a new macro assembler pointing to the address of the code to patch.
1162 // The size is adjusted with kGap on order for the assembler to generate size
1163 // bytes of instructions without failing with buffer size constraints.
1164 ASSERT(masm_.reloc_info_writer.pos() == address_ + size_ + Assembler::kGap);
1165}
1166
1167
1168CodePatcher::~CodePatcher() {
1169 // Indicate that code has changed.
1170 CPU::FlushICache(address_, size_);
1171
1172 // Check that the code was patched as expected.
1173 ASSERT(masm_.pc_ == address_ + size_);
1174 ASSERT(masm_.reloc_info_writer.pos() == address_ + size_ + Assembler::kGap);
1175}
1176
1177
1178void CodePatcher::Emit(Instr x) {
1179 masm()->emit(x);
1180}
1181
1182
1183void CodePatcher::Emit(Address addr) {
1184 masm()->emit(reinterpret_cast<Instr>(addr));
1185}
1186#endif // ENABLE_DEBUGGER_SUPPORT
1187
1188
1189} } // namespace v8::internal