blob: 4dd6a9bc30cce502e62fb01c475300a473aa50cc [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#include "serialize.h"
35
36namespace v8 {
37namespace internal {
38
39// -------------------------------------------------------------------------
40// MacroAssembler implementation.
41
42MacroAssembler::MacroAssembler(void* buffer, int size)
43 : Assembler(buffer, size),
44 unresolved_(0),
45 generating_stub_(false),
46 allow_stub_calls_(true),
47 code_object_(Heap::undefined_value()) {
48}
49
50
51static void RecordWriteHelper(MacroAssembler* masm,
52 Register object,
53 Register addr,
54 Register scratch) {
55 Label fast;
56
57 // Compute the page start address from the heap object pointer, and reuse
58 // the 'object' register for it.
59 masm->and_(object, ~Page::kPageAlignmentMask);
60 Register page_start = object;
61
62 // Compute the bit addr in the remembered set/index of the pointer in the
63 // page. Reuse 'addr' as pointer_offset.
64 masm->sub(addr, Operand(page_start));
65 masm->shr(addr, kObjectAlignmentBits);
66 Register pointer_offset = addr;
67
68 // If the bit offset lies beyond the normal remembered set range, it is in
69 // the extra remembered set area of a large object.
70 masm->cmp(pointer_offset, Page::kPageSize / kPointerSize);
71 masm->j(less, &fast);
72
73 // Adjust 'page_start' so that addressing using 'pointer_offset' hits the
74 // extra remembered set after the large object.
75
76 // Find the length of the large object (FixedArray).
77 masm->mov(scratch, Operand(page_start, Page::kObjectStartOffset
78 + FixedArray::kLengthOffset));
79 Register array_length = scratch;
80
81 // Extra remembered set starts right after the large object (a FixedArray), at
82 // page_start + kObjectStartOffset + objectSize
83 // where objectSize is FixedArray::kHeaderSize + kPointerSize * array_length.
84 // Add the delta between the end of the normal RSet and the start of the
85 // extra RSet to 'page_start', so that addressing the bit using
86 // 'pointer_offset' hits the extra RSet words.
87 masm->lea(page_start,
88 Operand(page_start, array_length, times_pointer_size,
89 Page::kObjectStartOffset + FixedArray::kHeaderSize
90 - Page::kRSetEndOffset));
91
92 // NOTE: For now, we use the bit-test-and-set (bts) x86 instruction
93 // to limit code size. We should probably evaluate this decision by
94 // measuring the performance of an equivalent implementation using
95 // "simpler" instructions
96 masm->bind(&fast);
97 masm->bts(Operand(page_start, Page::kRSetOffset), pointer_offset);
98}
99
100
101class RecordWriteStub : public CodeStub {
102 public:
103 RecordWriteStub(Register object, Register addr, Register scratch)
104 : object_(object), addr_(addr), scratch_(scratch) { }
105
106 void Generate(MacroAssembler* masm);
107
108 private:
109 Register object_;
110 Register addr_;
111 Register scratch_;
112
113#ifdef DEBUG
114 void Print() {
115 PrintF("RecordWriteStub (object reg %d), (addr reg %d), (scratch reg %d)\n",
116 object_.code(), addr_.code(), scratch_.code());
117 }
118#endif
119
120 // Minor key encoding in 12 bits of three registers (object, address and
121 // scratch) OOOOAAAASSSS.
122 class ScratchBits: public BitField<uint32_t, 0, 4> {};
123 class AddressBits: public BitField<uint32_t, 4, 4> {};
124 class ObjectBits: public BitField<uint32_t, 8, 4> {};
125
126 Major MajorKey() { return RecordWrite; }
127
128 int MinorKey() {
129 // Encode the registers.
130 return ObjectBits::encode(object_.code()) |
131 AddressBits::encode(addr_.code()) |
132 ScratchBits::encode(scratch_.code());
133 }
134};
135
136
137void RecordWriteStub::Generate(MacroAssembler* masm) {
138 RecordWriteHelper(masm, object_, addr_, scratch_);
139 masm->ret(0);
140}
141
142
143// Set the remembered set bit for [object+offset].
144// object is the object being stored into, value is the object being stored.
145// If offset is zero, then the scratch register contains the array index into
146// the elements array represented as a Smi.
147// All registers are clobbered by the operation.
148void MacroAssembler::RecordWrite(Register object, int offset,
149 Register value, Register scratch) {
Leon Clarke4515c472010-02-03 11:58:03 +0000150 // The compiled code assumes that record write doesn't change the
151 // context register, so we check that none of the clobbered
152 // registers are esi.
153 ASSERT(!object.is(esi) && !value.is(esi) && !scratch.is(esi));
154
Steve Blocka7e24c12009-10-30 11:49:00 +0000155 // First, check if a remembered set write is even needed. The tests below
156 // catch stores of Smis and stores into young gen (which does not have space
157 // for the remembered set bits.
158 Label done;
159
160 // Skip barrier if writing a smi.
161 ASSERT_EQ(0, kSmiTag);
162 test(value, Immediate(kSmiTagMask));
163 j(zero, &done);
164
165 if (Serializer::enabled()) {
166 // Can't do arithmetic on external references if it might get serialized.
167 mov(value, Operand(object));
168 and_(value, Heap::NewSpaceMask());
169 cmp(Operand(value), Immediate(ExternalReference::new_space_start()));
170 j(equal, &done);
171 } else {
172 int32_t new_space_start = reinterpret_cast<int32_t>(
173 ExternalReference::new_space_start().address());
174 lea(value, Operand(object, -new_space_start));
175 and_(value, Heap::NewSpaceMask());
176 j(equal, &done);
177 }
178
179 if ((offset > 0) && (offset < Page::kMaxHeapObjectSize)) {
180 // Compute the bit offset in the remembered set, leave it in 'value'.
181 lea(value, Operand(object, offset));
182 and_(value, Page::kPageAlignmentMask);
183 shr(value, kPointerSizeLog2);
184
185 // Compute the page address from the heap object pointer, leave it in
186 // 'object'.
187 and_(object, ~Page::kPageAlignmentMask);
188
189 // NOTE: For now, we use the bit-test-and-set (bts) x86 instruction
190 // to limit code size. We should probably evaluate this decision by
191 // measuring the performance of an equivalent implementation using
192 // "simpler" instructions
193 bts(Operand(object, Page::kRSetOffset), value);
194 } else {
195 Register dst = scratch;
196 if (offset != 0) {
197 lea(dst, Operand(object, offset));
198 } else {
199 // array access: calculate the destination address in the same manner as
200 // KeyedStoreIC::GenerateGeneric. Multiply a smi by 2 to get an offset
201 // into an array of words.
202 ASSERT_EQ(1, kSmiTagSize);
203 ASSERT_EQ(0, kSmiTag);
204 lea(dst, Operand(object, dst, times_half_pointer_size,
205 FixedArray::kHeaderSize - kHeapObjectTag));
206 }
207 // If we are already generating a shared stub, not inlining the
208 // record write code isn't going to save us any memory.
209 if (generating_stub()) {
210 RecordWriteHelper(this, object, dst, value);
211 } else {
212 RecordWriteStub stub(object, dst, value);
213 CallStub(&stub);
214 }
215 }
216
217 bind(&done);
Leon Clarke4515c472010-02-03 11:58:03 +0000218
219 // Clobber all input registers when running with the debug-code flag
220 // turned on to provoke errors.
221 if (FLAG_debug_code) {
222 mov(object, Immediate(bit_cast<int32_t>(kZapValue)));
223 mov(value, Immediate(bit_cast<int32_t>(kZapValue)));
224 mov(scratch, Immediate(bit_cast<int32_t>(kZapValue)));
225 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000226}
227
228
Steve Blockd0582a62009-12-15 09:54:21 +0000229void MacroAssembler::StackLimitCheck(Label* on_stack_overflow) {
230 cmp(esp,
231 Operand::StaticVariable(ExternalReference::address_of_stack_limit()));
232 j(below, on_stack_overflow);
233}
234
235
Steve Blocka7e24c12009-10-30 11:49:00 +0000236#ifdef ENABLE_DEBUGGER_SUPPORT
237void MacroAssembler::SaveRegistersToMemory(RegList regs) {
238 ASSERT((regs & ~kJSCallerSaved) == 0);
239 // Copy the content of registers to memory location.
240 for (int i = 0; i < kNumJSCallerSaved; i++) {
241 int r = JSCallerSavedCode(i);
242 if ((regs & (1 << r)) != 0) {
243 Register reg = { r };
244 ExternalReference reg_addr =
245 ExternalReference(Debug_Address::Register(i));
246 mov(Operand::StaticVariable(reg_addr), reg);
247 }
248 }
249}
250
251
252void MacroAssembler::RestoreRegistersFromMemory(RegList regs) {
253 ASSERT((regs & ~kJSCallerSaved) == 0);
254 // Copy the content of memory location to registers.
255 for (int i = kNumJSCallerSaved; --i >= 0;) {
256 int r = JSCallerSavedCode(i);
257 if ((regs & (1 << r)) != 0) {
258 Register reg = { r };
259 ExternalReference reg_addr =
260 ExternalReference(Debug_Address::Register(i));
261 mov(reg, Operand::StaticVariable(reg_addr));
262 }
263 }
264}
265
266
267void MacroAssembler::PushRegistersFromMemory(RegList regs) {
268 ASSERT((regs & ~kJSCallerSaved) == 0);
269 // Push the content of the memory location to the stack.
270 for (int i = 0; i < kNumJSCallerSaved; i++) {
271 int r = JSCallerSavedCode(i);
272 if ((regs & (1 << r)) != 0) {
273 ExternalReference reg_addr =
274 ExternalReference(Debug_Address::Register(i));
275 push(Operand::StaticVariable(reg_addr));
276 }
277 }
278}
279
280
281void MacroAssembler::PopRegistersToMemory(RegList regs) {
282 ASSERT((regs & ~kJSCallerSaved) == 0);
283 // Pop the content from the stack to the memory location.
284 for (int i = kNumJSCallerSaved; --i >= 0;) {
285 int r = JSCallerSavedCode(i);
286 if ((regs & (1 << r)) != 0) {
287 ExternalReference reg_addr =
288 ExternalReference(Debug_Address::Register(i));
289 pop(Operand::StaticVariable(reg_addr));
290 }
291 }
292}
293
294
295void MacroAssembler::CopyRegistersFromStackToMemory(Register base,
296 Register scratch,
297 RegList regs) {
298 ASSERT((regs & ~kJSCallerSaved) == 0);
299 // Copy the content of the stack to the memory location and adjust base.
300 for (int i = kNumJSCallerSaved; --i >= 0;) {
301 int r = JSCallerSavedCode(i);
302 if ((regs & (1 << r)) != 0) {
303 mov(scratch, Operand(base, 0));
304 ExternalReference reg_addr =
305 ExternalReference(Debug_Address::Register(i));
306 mov(Operand::StaticVariable(reg_addr), scratch);
307 lea(base, Operand(base, kPointerSize));
308 }
309 }
310}
311#endif
312
313void MacroAssembler::Set(Register dst, const Immediate& x) {
314 if (x.is_zero()) {
315 xor_(dst, Operand(dst)); // shorter than mov
316 } else {
317 mov(dst, x);
318 }
319}
320
321
322void MacroAssembler::Set(const Operand& dst, const Immediate& x) {
323 mov(dst, x);
324}
325
326
327void MacroAssembler::CmpObjectType(Register heap_object,
328 InstanceType type,
329 Register map) {
330 mov(map, FieldOperand(heap_object, HeapObject::kMapOffset));
331 CmpInstanceType(map, type);
332}
333
334
335void MacroAssembler::CmpInstanceType(Register map, InstanceType type) {
336 cmpb(FieldOperand(map, Map::kInstanceTypeOffset),
337 static_cast<int8_t>(type));
338}
339
340
Andrei Popescu31002712010-02-23 13:46:05 +0000341void MacroAssembler::CheckMap(Register obj,
342 Handle<Map> map,
343 Label* fail,
344 bool is_heap_object) {
345 if (!is_heap_object) {
346 test(obj, Immediate(kSmiTagMask));
347 j(zero, fail);
348 }
349 cmp(FieldOperand(obj, HeapObject::kMapOffset), Immediate(map));
350 j(not_equal, fail);
351}
352
353
Leon Clarkee46be812010-01-19 14:06:41 +0000354Condition MacroAssembler::IsObjectStringType(Register heap_object,
355 Register map,
356 Register instance_type) {
357 mov(map, FieldOperand(heap_object, HeapObject::kMapOffset));
358 movzx_b(instance_type, FieldOperand(map, Map::kInstanceTypeOffset));
359 ASSERT(kNotStringTag != 0);
360 test(instance_type, Immediate(kIsNotStringMask));
361 return zero;
362}
363
364
Steve Blocka7e24c12009-10-30 11:49:00 +0000365void MacroAssembler::FCmp() {
Steve Blockd0582a62009-12-15 09:54:21 +0000366 if (CpuFeatures::IsSupported(CMOV)) {
Steve Block3ce2e202009-11-05 08:53:23 +0000367 fucomip();
368 ffree(0);
369 fincstp();
370 } else {
371 fucompp();
372 push(eax);
373 fnstsw_ax();
374 sahf();
375 pop(eax);
376 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000377}
378
379
380void MacroAssembler::EnterFrame(StackFrame::Type type) {
381 push(ebp);
382 mov(ebp, Operand(esp));
383 push(esi);
384 push(Immediate(Smi::FromInt(type)));
385 push(Immediate(CodeObject()));
386 if (FLAG_debug_code) {
387 cmp(Operand(esp, 0), Immediate(Factory::undefined_value()));
388 Check(not_equal, "code object not properly patched");
389 }
390}
391
392
393void MacroAssembler::LeaveFrame(StackFrame::Type type) {
394 if (FLAG_debug_code) {
395 cmp(Operand(ebp, StandardFrameConstants::kMarkerOffset),
396 Immediate(Smi::FromInt(type)));
397 Check(equal, "stack frame types must match");
398 }
399 leave();
400}
401
Steve Blockd0582a62009-12-15 09:54:21 +0000402void MacroAssembler::EnterExitFramePrologue(ExitFrame::Mode mode) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000403 // Setup the frame structure on the stack.
404 ASSERT(ExitFrameConstants::kCallerSPDisplacement == +2 * kPointerSize);
405 ASSERT(ExitFrameConstants::kCallerPCOffset == +1 * kPointerSize);
406 ASSERT(ExitFrameConstants::kCallerFPOffset == 0 * kPointerSize);
407 push(ebp);
408 mov(ebp, Operand(esp));
409
410 // Reserve room for entry stack pointer and push the debug marker.
411 ASSERT(ExitFrameConstants::kSPOffset == -1 * kPointerSize);
412 push(Immediate(0)); // saved entry sp, patched before call
Steve Blockd0582a62009-12-15 09:54:21 +0000413 if (mode == ExitFrame::MODE_DEBUG) {
414 push(Immediate(0));
415 } else {
416 push(Immediate(CodeObject()));
417 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000418
419 // Save the frame pointer and the context in top.
420 ExternalReference c_entry_fp_address(Top::k_c_entry_fp_address);
421 ExternalReference context_address(Top::k_context_address);
422 mov(Operand::StaticVariable(c_entry_fp_address), ebp);
423 mov(Operand::StaticVariable(context_address), esi);
Steve Blockd0582a62009-12-15 09:54:21 +0000424}
Steve Blocka7e24c12009-10-30 11:49:00 +0000425
Steve Blockd0582a62009-12-15 09:54:21 +0000426void MacroAssembler::EnterExitFrameEpilogue(ExitFrame::Mode mode, int argc) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000427#ifdef ENABLE_DEBUGGER_SUPPORT
428 // Save the state of all registers to the stack from the memory
429 // location. This is needed to allow nested break points.
Steve Blockd0582a62009-12-15 09:54:21 +0000430 if (mode == ExitFrame::MODE_DEBUG) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000431 // TODO(1243899): This should be symmetric to
432 // CopyRegistersFromStackToMemory() but it isn't! esp is assumed
433 // correct here, but computed for the other call. Very error
434 // prone! FIX THIS. Actually there are deeper problems with
435 // register saving than this asymmetry (see the bug report
436 // associated with this issue).
437 PushRegistersFromMemory(kJSCallerSaved);
438 }
439#endif
440
Steve Blockd0582a62009-12-15 09:54:21 +0000441 // Reserve space for arguments.
442 sub(Operand(esp), Immediate(argc * kPointerSize));
Steve Blocka7e24c12009-10-30 11:49:00 +0000443
444 // Get the required frame alignment for the OS.
445 static const int kFrameAlignment = OS::ActivationFrameAlignment();
446 if (kFrameAlignment > 0) {
447 ASSERT(IsPowerOf2(kFrameAlignment));
448 and_(esp, -kFrameAlignment);
449 }
450
451 // Patch the saved entry sp.
452 mov(Operand(ebp, ExitFrameConstants::kSPOffset), esp);
453}
454
455
Steve Blockd0582a62009-12-15 09:54:21 +0000456void MacroAssembler::EnterExitFrame(ExitFrame::Mode mode) {
457 EnterExitFramePrologue(mode);
458
459 // Setup argc and argv in callee-saved registers.
460 int offset = StandardFrameConstants::kCallerSPOffset - kPointerSize;
461 mov(edi, Operand(eax));
462 lea(esi, Operand(ebp, eax, times_4, offset));
463
464 EnterExitFrameEpilogue(mode, 2);
465}
466
467
468void MacroAssembler::EnterApiExitFrame(ExitFrame::Mode mode,
469 int stack_space,
470 int argc) {
471 EnterExitFramePrologue(mode);
472
473 int offset = StandardFrameConstants::kCallerSPOffset - kPointerSize;
474 lea(esi, Operand(ebp, (stack_space * kPointerSize) + offset));
475
476 EnterExitFrameEpilogue(mode, argc);
477}
478
479
480void MacroAssembler::LeaveExitFrame(ExitFrame::Mode mode) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000481#ifdef ENABLE_DEBUGGER_SUPPORT
482 // Restore the memory copy of the registers by digging them out from
483 // the stack. This is needed to allow nested break points.
Steve Blockd0582a62009-12-15 09:54:21 +0000484 if (mode == ExitFrame::MODE_DEBUG) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000485 // It's okay to clobber register ebx below because we don't need
486 // the function pointer after this.
487 const int kCallerSavedSize = kNumJSCallerSaved * kPointerSize;
Steve Blockd0582a62009-12-15 09:54:21 +0000488 int kOffset = ExitFrameConstants::kCodeOffset - kCallerSavedSize;
Steve Blocka7e24c12009-10-30 11:49:00 +0000489 lea(ebx, Operand(ebp, kOffset));
490 CopyRegistersFromStackToMemory(ebx, ecx, kJSCallerSaved);
491 }
492#endif
493
494 // Get the return address from the stack and restore the frame pointer.
495 mov(ecx, Operand(ebp, 1 * kPointerSize));
496 mov(ebp, Operand(ebp, 0 * kPointerSize));
497
498 // Pop the arguments and the receiver from the caller stack.
499 lea(esp, Operand(esi, 1 * kPointerSize));
500
501 // Restore current context from top and clear it in debug mode.
502 ExternalReference context_address(Top::k_context_address);
503 mov(esi, Operand::StaticVariable(context_address));
504#ifdef DEBUG
505 mov(Operand::StaticVariable(context_address), Immediate(0));
506#endif
507
508 // Push the return address to get ready to return.
509 push(ecx);
510
511 // Clear the top frame.
512 ExternalReference c_entry_fp_address(Top::k_c_entry_fp_address);
513 mov(Operand::StaticVariable(c_entry_fp_address), Immediate(0));
514}
515
516
517void MacroAssembler::PushTryHandler(CodeLocation try_location,
518 HandlerType type) {
519 // Adjust this code if not the case.
520 ASSERT(StackHandlerConstants::kSize == 4 * kPointerSize);
521 // The pc (return address) is already on TOS.
522 if (try_location == IN_JAVASCRIPT) {
523 if (type == TRY_CATCH_HANDLER) {
524 push(Immediate(StackHandler::TRY_CATCH));
525 } else {
526 push(Immediate(StackHandler::TRY_FINALLY));
527 }
528 push(ebp);
529 } else {
530 ASSERT(try_location == IN_JS_ENTRY);
531 // The frame pointer does not point to a JS frame so we save NULL
532 // for ebp. We expect the code throwing an exception to check ebp
533 // before dereferencing it to restore the context.
534 push(Immediate(StackHandler::ENTRY));
535 push(Immediate(0)); // NULL frame pointer.
536 }
537 // Save the current handler as the next handler.
538 push(Operand::StaticVariable(ExternalReference(Top::k_handler_address)));
539 // Link this handler as the new current one.
540 mov(Operand::StaticVariable(ExternalReference(Top::k_handler_address)), esp);
541}
542
543
Leon Clarkee46be812010-01-19 14:06:41 +0000544void MacroAssembler::PopTryHandler() {
545 ASSERT_EQ(0, StackHandlerConstants::kNextOffset);
546 pop(Operand::StaticVariable(ExternalReference(Top::k_handler_address)));
547 add(Operand(esp), Immediate(StackHandlerConstants::kSize - kPointerSize));
548}
549
550
Steve Blocka7e24c12009-10-30 11:49:00 +0000551Register MacroAssembler::CheckMaps(JSObject* object, Register object_reg,
552 JSObject* holder, Register holder_reg,
553 Register scratch,
554 Label* miss) {
555 // Make sure there's no overlap between scratch and the other
556 // registers.
557 ASSERT(!scratch.is(object_reg) && !scratch.is(holder_reg));
558
559 // Keep track of the current object in register reg.
560 Register reg = object_reg;
561 int depth = 1;
562
563 // Check the maps in the prototype chain.
564 // Traverse the prototype chain from the object and do map checks.
565 while (object != holder) {
566 depth++;
567
568 // Only global objects and objects that do not require access
569 // checks are allowed in stubs.
570 ASSERT(object->IsJSGlobalProxy() || !object->IsAccessCheckNeeded());
571
572 JSObject* prototype = JSObject::cast(object->GetPrototype());
573 if (Heap::InNewSpace(prototype)) {
574 // Get the map of the current object.
575 mov(scratch, FieldOperand(reg, HeapObject::kMapOffset));
576 cmp(Operand(scratch), Immediate(Handle<Map>(object->map())));
577 // Branch on the result of the map check.
578 j(not_equal, miss, not_taken);
579 // Check access rights to the global object. This has to happen
580 // after the map check so that we know that the object is
581 // actually a global object.
582 if (object->IsJSGlobalProxy()) {
583 CheckAccessGlobalProxy(reg, scratch, miss);
584
585 // Restore scratch register to be the map of the object.
586 // We load the prototype from the map in the scratch register.
587 mov(scratch, FieldOperand(reg, HeapObject::kMapOffset));
588 }
589 // The prototype is in new space; we cannot store a reference
590 // to it in the code. Load it from the map.
591 reg = holder_reg; // from now the object is in holder_reg
592 mov(reg, FieldOperand(scratch, Map::kPrototypeOffset));
593
594 } else {
595 // Check the map of the current object.
596 cmp(FieldOperand(reg, HeapObject::kMapOffset),
597 Immediate(Handle<Map>(object->map())));
598 // Branch on the result of the map check.
599 j(not_equal, miss, not_taken);
600 // Check access rights to the global object. This has to happen
601 // after the map check so that we know that the object is
602 // actually a global object.
603 if (object->IsJSGlobalProxy()) {
604 CheckAccessGlobalProxy(reg, scratch, miss);
605 }
606 // The prototype is in old space; load it directly.
607 reg = holder_reg; // from now the object is in holder_reg
608 mov(reg, Handle<JSObject>(prototype));
609 }
610
611 // Go to the next object in the prototype chain.
612 object = prototype;
613 }
614
615 // Check the holder map.
616 cmp(FieldOperand(reg, HeapObject::kMapOffset),
617 Immediate(Handle<Map>(holder->map())));
618 j(not_equal, miss, not_taken);
619
620 // Log the check depth.
621 LOG(IntEvent("check-maps-depth", depth));
622
623 // Perform security check for access to the global object and return
624 // the holder register.
625 ASSERT(object == holder);
626 ASSERT(object->IsJSGlobalProxy() || !object->IsAccessCheckNeeded());
627 if (object->IsJSGlobalProxy()) {
628 CheckAccessGlobalProxy(reg, scratch, miss);
629 }
630 return reg;
631}
632
633
634void MacroAssembler::CheckAccessGlobalProxy(Register holder_reg,
635 Register scratch,
636 Label* miss) {
637 Label same_contexts;
638
639 ASSERT(!holder_reg.is(scratch));
640
641 // Load current lexical context from the stack frame.
642 mov(scratch, Operand(ebp, StandardFrameConstants::kContextOffset));
643
644 // When generating debug code, make sure the lexical context is set.
645 if (FLAG_debug_code) {
646 cmp(Operand(scratch), Immediate(0));
647 Check(not_equal, "we should not have an empty lexical context");
648 }
649 // Load the global context of the current context.
650 int offset = Context::kHeaderSize + Context::GLOBAL_INDEX * kPointerSize;
651 mov(scratch, FieldOperand(scratch, offset));
652 mov(scratch, FieldOperand(scratch, GlobalObject::kGlobalContextOffset));
653
654 // Check the context is a global context.
655 if (FLAG_debug_code) {
656 push(scratch);
657 // Read the first word and compare to global_context_map.
658 mov(scratch, FieldOperand(scratch, HeapObject::kMapOffset));
659 cmp(scratch, Factory::global_context_map());
660 Check(equal, "JSGlobalObject::global_context should be a global context.");
661 pop(scratch);
662 }
663
664 // Check if both contexts are the same.
665 cmp(scratch, FieldOperand(holder_reg, JSGlobalProxy::kContextOffset));
666 j(equal, &same_contexts, taken);
667
668 // Compare security tokens, save holder_reg on the stack so we can use it
669 // as a temporary register.
670 //
671 // TODO(119): avoid push(holder_reg)/pop(holder_reg)
672 push(holder_reg);
673 // Check that the security token in the calling global object is
674 // compatible with the security token in the receiving global
675 // object.
676 mov(holder_reg, FieldOperand(holder_reg, JSGlobalProxy::kContextOffset));
677
678 // Check the context is a global context.
679 if (FLAG_debug_code) {
680 cmp(holder_reg, Factory::null_value());
681 Check(not_equal, "JSGlobalProxy::context() should not be null.");
682
683 push(holder_reg);
684 // Read the first word and compare to global_context_map(),
685 mov(holder_reg, FieldOperand(holder_reg, HeapObject::kMapOffset));
686 cmp(holder_reg, Factory::global_context_map());
687 Check(equal, "JSGlobalObject::global_context should be a global context.");
688 pop(holder_reg);
689 }
690
691 int token_offset = Context::kHeaderSize +
692 Context::SECURITY_TOKEN_INDEX * kPointerSize;
693 mov(scratch, FieldOperand(scratch, token_offset));
694 cmp(scratch, FieldOperand(holder_reg, token_offset));
695 pop(holder_reg);
696 j(not_equal, miss, not_taken);
697
698 bind(&same_contexts);
699}
700
701
702void MacroAssembler::LoadAllocationTopHelper(Register result,
703 Register result_end,
704 Register scratch,
705 AllocationFlags flags) {
706 ExternalReference new_space_allocation_top =
707 ExternalReference::new_space_allocation_top_address();
708
709 // Just return if allocation top is already known.
710 if ((flags & RESULT_CONTAINS_TOP) != 0) {
711 // No use of scratch if allocation top is provided.
712 ASSERT(scratch.is(no_reg));
713#ifdef DEBUG
714 // Assert that result actually contains top on entry.
715 cmp(result, Operand::StaticVariable(new_space_allocation_top));
716 Check(equal, "Unexpected allocation top");
717#endif
718 return;
719 }
720
721 // Move address of new object to result. Use scratch register if available.
722 if (scratch.is(no_reg)) {
723 mov(result, Operand::StaticVariable(new_space_allocation_top));
724 } else {
725 ASSERT(!scratch.is(result_end));
726 mov(Operand(scratch), Immediate(new_space_allocation_top));
727 mov(result, Operand(scratch, 0));
728 }
729}
730
731
732void MacroAssembler::UpdateAllocationTopHelper(Register result_end,
733 Register scratch) {
Steve Blockd0582a62009-12-15 09:54:21 +0000734 if (FLAG_debug_code) {
735 test(result_end, Immediate(kObjectAlignmentMask));
736 Check(zero, "Unaligned allocation in new space");
737 }
738
Steve Blocka7e24c12009-10-30 11:49:00 +0000739 ExternalReference new_space_allocation_top =
740 ExternalReference::new_space_allocation_top_address();
741
742 // Update new top. Use scratch if available.
743 if (scratch.is(no_reg)) {
744 mov(Operand::StaticVariable(new_space_allocation_top), result_end);
745 } else {
746 mov(Operand(scratch, 0), result_end);
747 }
748}
749
750
751void MacroAssembler::AllocateInNewSpace(int object_size,
752 Register result,
753 Register result_end,
754 Register scratch,
755 Label* gc_required,
756 AllocationFlags flags) {
757 ASSERT(!result.is(result_end));
758
759 // Load address of new object into result.
760 LoadAllocationTopHelper(result, result_end, scratch, flags);
761
762 // Calculate new top and bail out if new space is exhausted.
763 ExternalReference new_space_allocation_limit =
764 ExternalReference::new_space_allocation_limit_address();
765 lea(result_end, Operand(result, object_size));
766 cmp(result_end, Operand::StaticVariable(new_space_allocation_limit));
767 j(above, gc_required, not_taken);
768
Steve Blocka7e24c12009-10-30 11:49:00 +0000769 // Tag result if requested.
770 if ((flags & TAG_OBJECT) != 0) {
Leon Clarkee46be812010-01-19 14:06:41 +0000771 lea(result, Operand(result, kHeapObjectTag));
Steve Blocka7e24c12009-10-30 11:49:00 +0000772 }
Leon Clarkee46be812010-01-19 14:06:41 +0000773
774 // Update allocation top.
775 UpdateAllocationTopHelper(result_end, scratch);
Steve Blocka7e24c12009-10-30 11:49:00 +0000776}
777
778
779void MacroAssembler::AllocateInNewSpace(int header_size,
780 ScaleFactor element_size,
781 Register element_count,
782 Register result,
783 Register result_end,
784 Register scratch,
785 Label* gc_required,
786 AllocationFlags flags) {
787 ASSERT(!result.is(result_end));
788
789 // Load address of new object into result.
790 LoadAllocationTopHelper(result, result_end, scratch, flags);
791
792 // Calculate new top and bail out if new space is exhausted.
793 ExternalReference new_space_allocation_limit =
794 ExternalReference::new_space_allocation_limit_address();
795 lea(result_end, Operand(result, element_count, element_size, header_size));
796 cmp(result_end, Operand::StaticVariable(new_space_allocation_limit));
797 j(above, gc_required);
798
Steve Blocka7e24c12009-10-30 11:49:00 +0000799 // Tag result if requested.
800 if ((flags & TAG_OBJECT) != 0) {
Leon Clarkee46be812010-01-19 14:06:41 +0000801 lea(result, Operand(result, kHeapObjectTag));
Steve Blocka7e24c12009-10-30 11:49:00 +0000802 }
Leon Clarkee46be812010-01-19 14:06:41 +0000803
804 // Update allocation top.
805 UpdateAllocationTopHelper(result_end, scratch);
Steve Blocka7e24c12009-10-30 11:49:00 +0000806}
807
808
809void MacroAssembler::AllocateInNewSpace(Register object_size,
810 Register result,
811 Register result_end,
812 Register scratch,
813 Label* gc_required,
814 AllocationFlags flags) {
815 ASSERT(!result.is(result_end));
816
817 // Load address of new object into result.
818 LoadAllocationTopHelper(result, result_end, scratch, flags);
819
820 // Calculate new top and bail out if new space is exhausted.
821 ExternalReference new_space_allocation_limit =
822 ExternalReference::new_space_allocation_limit_address();
823 if (!object_size.is(result_end)) {
824 mov(result_end, object_size);
825 }
826 add(result_end, Operand(result));
827 cmp(result_end, Operand::StaticVariable(new_space_allocation_limit));
828 j(above, gc_required, not_taken);
829
Steve Blocka7e24c12009-10-30 11:49:00 +0000830 // Tag result if requested.
831 if ((flags & TAG_OBJECT) != 0) {
Leon Clarkee46be812010-01-19 14:06:41 +0000832 lea(result, Operand(result, kHeapObjectTag));
Steve Blocka7e24c12009-10-30 11:49:00 +0000833 }
Leon Clarkee46be812010-01-19 14:06:41 +0000834
835 // Update allocation top.
836 UpdateAllocationTopHelper(result_end, scratch);
Steve Blocka7e24c12009-10-30 11:49:00 +0000837}
838
839
840void MacroAssembler::UndoAllocationInNewSpace(Register object) {
841 ExternalReference new_space_allocation_top =
842 ExternalReference::new_space_allocation_top_address();
843
844 // Make sure the object has no tag before resetting top.
845 and_(Operand(object), Immediate(~kHeapObjectTagMask));
846#ifdef DEBUG
847 cmp(object, Operand::StaticVariable(new_space_allocation_top));
848 Check(below, "Undo allocation of non allocated memory");
849#endif
850 mov(Operand::StaticVariable(new_space_allocation_top), object);
851}
852
853
Steve Block3ce2e202009-11-05 08:53:23 +0000854void MacroAssembler::AllocateHeapNumber(Register result,
855 Register scratch1,
856 Register scratch2,
857 Label* gc_required) {
858 // Allocate heap number in new space.
859 AllocateInNewSpace(HeapNumber::kSize,
860 result,
861 scratch1,
862 scratch2,
863 gc_required,
864 TAG_OBJECT);
865
866 // Set the map.
867 mov(FieldOperand(result, HeapObject::kMapOffset),
868 Immediate(Factory::heap_number_map()));
869}
870
871
Steve Blockd0582a62009-12-15 09:54:21 +0000872void MacroAssembler::AllocateTwoByteString(Register result,
873 Register length,
874 Register scratch1,
875 Register scratch2,
876 Register scratch3,
877 Label* gc_required) {
878 // Calculate the number of bytes needed for the characters in the string while
879 // observing object alignment.
880 ASSERT((SeqTwoByteString::kHeaderSize & kObjectAlignmentMask) == 0);
Steve Blockd0582a62009-12-15 09:54:21 +0000881 ASSERT(kShortSize == 2);
Leon Clarkee46be812010-01-19 14:06:41 +0000882 // scratch1 = length * 2 + kObjectAlignmentMask.
883 lea(scratch1, Operand(length, length, times_1, kObjectAlignmentMask));
Steve Blockd0582a62009-12-15 09:54:21 +0000884 and_(Operand(scratch1), Immediate(~kObjectAlignmentMask));
885
886 // Allocate two byte string in new space.
887 AllocateInNewSpace(SeqTwoByteString::kHeaderSize,
888 times_1,
889 scratch1,
890 result,
891 scratch2,
892 scratch3,
893 gc_required,
894 TAG_OBJECT);
895
896 // Set the map, length and hash field.
897 mov(FieldOperand(result, HeapObject::kMapOffset),
898 Immediate(Factory::string_map()));
899 mov(FieldOperand(result, String::kLengthOffset), length);
900 mov(FieldOperand(result, String::kHashFieldOffset),
901 Immediate(String::kEmptyHashField));
902}
903
904
905void MacroAssembler::AllocateAsciiString(Register result,
906 Register length,
907 Register scratch1,
908 Register scratch2,
909 Register scratch3,
910 Label* gc_required) {
911 // Calculate the number of bytes needed for the characters in the string while
912 // observing object alignment.
913 ASSERT((SeqAsciiString::kHeaderSize & kObjectAlignmentMask) == 0);
914 mov(scratch1, length);
915 ASSERT(kCharSize == 1);
916 add(Operand(scratch1), Immediate(kObjectAlignmentMask));
917 and_(Operand(scratch1), Immediate(~kObjectAlignmentMask));
918
919 // Allocate ascii string in new space.
920 AllocateInNewSpace(SeqAsciiString::kHeaderSize,
921 times_1,
922 scratch1,
923 result,
924 scratch2,
925 scratch3,
926 gc_required,
927 TAG_OBJECT);
928
929 // Set the map, length and hash field.
930 mov(FieldOperand(result, HeapObject::kMapOffset),
931 Immediate(Factory::ascii_string_map()));
932 mov(FieldOperand(result, String::kLengthOffset), length);
933 mov(FieldOperand(result, String::kHashFieldOffset),
934 Immediate(String::kEmptyHashField));
935}
936
937
938void MacroAssembler::AllocateConsString(Register result,
939 Register scratch1,
940 Register scratch2,
941 Label* gc_required) {
942 // Allocate heap number in new space.
943 AllocateInNewSpace(ConsString::kSize,
944 result,
945 scratch1,
946 scratch2,
947 gc_required,
948 TAG_OBJECT);
949
950 // Set the map. The other fields are left uninitialized.
951 mov(FieldOperand(result, HeapObject::kMapOffset),
952 Immediate(Factory::cons_string_map()));
953}
954
955
956void MacroAssembler::AllocateAsciiConsString(Register result,
957 Register scratch1,
958 Register scratch2,
959 Label* gc_required) {
960 // Allocate heap number in new space.
961 AllocateInNewSpace(ConsString::kSize,
962 result,
963 scratch1,
964 scratch2,
965 gc_required,
966 TAG_OBJECT);
967
968 // Set the map. The other fields are left uninitialized.
969 mov(FieldOperand(result, HeapObject::kMapOffset),
970 Immediate(Factory::cons_ascii_string_map()));
971}
972
973
Steve Blocka7e24c12009-10-30 11:49:00 +0000974void MacroAssembler::NegativeZeroTest(CodeGenerator* cgen,
975 Register result,
976 Register op,
977 JumpTarget* then_target) {
978 JumpTarget ok;
979 test(result, Operand(result));
980 ok.Branch(not_zero, taken);
981 test(op, Operand(op));
982 then_target->Branch(sign, not_taken);
983 ok.Bind();
984}
985
986
987void MacroAssembler::NegativeZeroTest(Register result,
988 Register op,
989 Label* then_label) {
990 Label ok;
991 test(result, Operand(result));
992 j(not_zero, &ok, taken);
993 test(op, Operand(op));
994 j(sign, then_label, not_taken);
995 bind(&ok);
996}
997
998
999void MacroAssembler::NegativeZeroTest(Register result,
1000 Register op1,
1001 Register op2,
1002 Register scratch,
1003 Label* then_label) {
1004 Label ok;
1005 test(result, Operand(result));
1006 j(not_zero, &ok, taken);
1007 mov(scratch, Operand(op1));
1008 or_(scratch, Operand(op2));
1009 j(sign, then_label, not_taken);
1010 bind(&ok);
1011}
1012
1013
1014void MacroAssembler::TryGetFunctionPrototype(Register function,
1015 Register result,
1016 Register scratch,
1017 Label* miss) {
1018 // Check that the receiver isn't a smi.
1019 test(function, Immediate(kSmiTagMask));
1020 j(zero, miss, not_taken);
1021
1022 // Check that the function really is a function.
1023 CmpObjectType(function, JS_FUNCTION_TYPE, result);
1024 j(not_equal, miss, not_taken);
1025
1026 // Make sure that the function has an instance prototype.
1027 Label non_instance;
1028 movzx_b(scratch, FieldOperand(result, Map::kBitFieldOffset));
1029 test(scratch, Immediate(1 << Map::kHasNonInstancePrototype));
1030 j(not_zero, &non_instance, not_taken);
1031
1032 // Get the prototype or initial map from the function.
1033 mov(result,
1034 FieldOperand(function, JSFunction::kPrototypeOrInitialMapOffset));
1035
1036 // If the prototype or initial map is the hole, don't return it and
1037 // simply miss the cache instead. This will allow us to allocate a
1038 // prototype object on-demand in the runtime system.
1039 cmp(Operand(result), Immediate(Factory::the_hole_value()));
1040 j(equal, miss, not_taken);
1041
1042 // If the function does not have an initial map, we're done.
1043 Label done;
1044 CmpObjectType(result, MAP_TYPE, scratch);
1045 j(not_equal, &done);
1046
1047 // Get the prototype from the initial map.
1048 mov(result, FieldOperand(result, Map::kPrototypeOffset));
1049 jmp(&done);
1050
1051 // Non-instance prototype: Fetch prototype from constructor field
1052 // in initial map.
1053 bind(&non_instance);
1054 mov(result, FieldOperand(result, Map::kConstructorOffset));
1055
1056 // All done.
1057 bind(&done);
1058}
1059
1060
1061void MacroAssembler::CallStub(CodeStub* stub) {
Leon Clarkee46be812010-01-19 14:06:41 +00001062 ASSERT(allow_stub_calls()); // Calls are not allowed in some stubs.
Steve Blocka7e24c12009-10-30 11:49:00 +00001063 call(stub->GetCode(), RelocInfo::CODE_TARGET);
1064}
1065
1066
Leon Clarkee46be812010-01-19 14:06:41 +00001067Object* MacroAssembler::TryCallStub(CodeStub* stub) {
1068 ASSERT(allow_stub_calls()); // Calls are not allowed in some stubs.
1069 Object* result = stub->TryGetCode();
1070 if (!result->IsFailure()) {
1071 call(Handle<Code>(Code::cast(result)), RelocInfo::CODE_TARGET);
1072 }
1073 return result;
1074}
1075
1076
Steve Blockd0582a62009-12-15 09:54:21 +00001077void MacroAssembler::TailCallStub(CodeStub* stub) {
Leon Clarkee46be812010-01-19 14:06:41 +00001078 ASSERT(allow_stub_calls()); // Calls are not allowed in some stubs.
Steve Blockd0582a62009-12-15 09:54:21 +00001079 jmp(stub->GetCode(), RelocInfo::CODE_TARGET);
1080}
1081
1082
Leon Clarkee46be812010-01-19 14:06:41 +00001083Object* MacroAssembler::TryTailCallStub(CodeStub* stub) {
1084 ASSERT(allow_stub_calls()); // Calls are not allowed in some stubs.
1085 Object* result = stub->TryGetCode();
1086 if (!result->IsFailure()) {
1087 jmp(Handle<Code>(Code::cast(result)), RelocInfo::CODE_TARGET);
1088 }
1089 return result;
1090}
1091
1092
Steve Blocka7e24c12009-10-30 11:49:00 +00001093void MacroAssembler::StubReturn(int argc) {
1094 ASSERT(argc >= 1 && generating_stub());
1095 ret((argc - 1) * kPointerSize);
1096}
1097
1098
1099void MacroAssembler::IllegalOperation(int num_arguments) {
1100 if (num_arguments > 0) {
1101 add(Operand(esp), Immediate(num_arguments * kPointerSize));
1102 }
1103 mov(eax, Immediate(Factory::undefined_value()));
1104}
1105
1106
1107void MacroAssembler::CallRuntime(Runtime::FunctionId id, int num_arguments) {
1108 CallRuntime(Runtime::FunctionForId(id), num_arguments);
1109}
1110
1111
Leon Clarkee46be812010-01-19 14:06:41 +00001112Object* MacroAssembler::TryCallRuntime(Runtime::FunctionId id,
1113 int num_arguments) {
1114 return TryCallRuntime(Runtime::FunctionForId(id), num_arguments);
1115}
1116
1117
Steve Blocka7e24c12009-10-30 11:49:00 +00001118void MacroAssembler::CallRuntime(Runtime::Function* f, int num_arguments) {
1119 // If the expected number of arguments of the runtime function is
1120 // constant, we check that the actual number of arguments match the
1121 // expectation.
1122 if (f->nargs >= 0 && f->nargs != num_arguments) {
1123 IllegalOperation(num_arguments);
1124 return;
1125 }
1126
Leon Clarke4515c472010-02-03 11:58:03 +00001127 // TODO(1236192): Most runtime routines don't need the number of
1128 // arguments passed in because it is constant. At some point we
1129 // should remove this need and make the runtime routine entry code
1130 // smarter.
1131 Set(eax, Immediate(num_arguments));
1132 mov(ebx, Immediate(ExternalReference(f)));
1133 CEntryStub ces(1);
1134 CallStub(&ces);
Steve Blocka7e24c12009-10-30 11:49:00 +00001135}
1136
1137
Leon Clarkee46be812010-01-19 14:06:41 +00001138Object* MacroAssembler::TryCallRuntime(Runtime::Function* f,
1139 int num_arguments) {
1140 if (f->nargs >= 0 && f->nargs != num_arguments) {
1141 IllegalOperation(num_arguments);
1142 // Since we did not call the stub, there was no allocation failure.
1143 // Return some non-failure object.
1144 return Heap::undefined_value();
1145 }
1146
Leon Clarke4515c472010-02-03 11:58:03 +00001147 // TODO(1236192): Most runtime routines don't need the number of
1148 // arguments passed in because it is constant. At some point we
1149 // should remove this need and make the runtime routine entry code
1150 // smarter.
1151 Set(eax, Immediate(num_arguments));
1152 mov(ebx, Immediate(ExternalReference(f)));
1153 CEntryStub ces(1);
1154 return TryCallStub(&ces);
Leon Clarkee46be812010-01-19 14:06:41 +00001155}
1156
1157
Steve Blocka7e24c12009-10-30 11:49:00 +00001158void MacroAssembler::TailCallRuntime(const ExternalReference& ext,
1159 int num_arguments,
1160 int result_size) {
1161 // TODO(1236192): Most runtime routines don't need the number of
1162 // arguments passed in because it is constant. At some point we
1163 // should remove this need and make the runtime routine entry code
1164 // smarter.
1165 Set(eax, Immediate(num_arguments));
1166 JumpToRuntime(ext);
1167}
1168
1169
Steve Blockd0582a62009-12-15 09:54:21 +00001170void MacroAssembler::PushHandleScope(Register scratch) {
1171 // Push the number of extensions, smi-tagged so the gc will ignore it.
1172 ExternalReference extensions_address =
1173 ExternalReference::handle_scope_extensions_address();
1174 mov(scratch, Operand::StaticVariable(extensions_address));
1175 ASSERT_EQ(0, kSmiTag);
1176 shl(scratch, kSmiTagSize);
1177 push(scratch);
1178 mov(Operand::StaticVariable(extensions_address), Immediate(0));
1179 // Push next and limit pointers which will be wordsize aligned and
1180 // hence automatically smi tagged.
1181 ExternalReference next_address =
1182 ExternalReference::handle_scope_next_address();
1183 push(Operand::StaticVariable(next_address));
1184 ExternalReference limit_address =
1185 ExternalReference::handle_scope_limit_address();
1186 push(Operand::StaticVariable(limit_address));
1187}
1188
1189
Leon Clarkee46be812010-01-19 14:06:41 +00001190Object* MacroAssembler::PopHandleScopeHelper(Register saved,
1191 Register scratch,
1192 bool gc_allowed) {
1193 Object* result = NULL;
Steve Blockd0582a62009-12-15 09:54:21 +00001194 ExternalReference extensions_address =
1195 ExternalReference::handle_scope_extensions_address();
1196 Label write_back;
1197 mov(scratch, Operand::StaticVariable(extensions_address));
1198 cmp(Operand(scratch), Immediate(0));
1199 j(equal, &write_back);
1200 // Calling a runtime function messes with registers so we save and
1201 // restore any one we're asked not to change
1202 if (saved.is_valid()) push(saved);
Leon Clarkee46be812010-01-19 14:06:41 +00001203 if (gc_allowed) {
1204 CallRuntime(Runtime::kDeleteHandleScopeExtensions, 0);
1205 } else {
1206 result = TryCallRuntime(Runtime::kDeleteHandleScopeExtensions, 0);
1207 if (result->IsFailure()) return result;
1208 }
Steve Blockd0582a62009-12-15 09:54:21 +00001209 if (saved.is_valid()) pop(saved);
1210
1211 bind(&write_back);
1212 ExternalReference limit_address =
1213 ExternalReference::handle_scope_limit_address();
1214 pop(Operand::StaticVariable(limit_address));
1215 ExternalReference next_address =
1216 ExternalReference::handle_scope_next_address();
1217 pop(Operand::StaticVariable(next_address));
1218 pop(scratch);
1219 shr(scratch, kSmiTagSize);
1220 mov(Operand::StaticVariable(extensions_address), scratch);
Leon Clarkee46be812010-01-19 14:06:41 +00001221
1222 return result;
1223}
1224
1225
1226void MacroAssembler::PopHandleScope(Register saved, Register scratch) {
1227 PopHandleScopeHelper(saved, scratch, true);
1228}
1229
1230
1231Object* MacroAssembler::TryPopHandleScope(Register saved, Register scratch) {
1232 return PopHandleScopeHelper(saved, scratch, false);
Steve Blockd0582a62009-12-15 09:54:21 +00001233}
1234
1235
Steve Blocka7e24c12009-10-30 11:49:00 +00001236void MacroAssembler::JumpToRuntime(const ExternalReference& ext) {
1237 // Set the entry point and jump to the C entry runtime stub.
1238 mov(ebx, Immediate(ext));
1239 CEntryStub ces(1);
1240 jmp(ces.GetCode(), RelocInfo::CODE_TARGET);
1241}
1242
1243
1244void MacroAssembler::InvokePrologue(const ParameterCount& expected,
1245 const ParameterCount& actual,
1246 Handle<Code> code_constant,
1247 const Operand& code_operand,
1248 Label* done,
1249 InvokeFlag flag) {
1250 bool definitely_matches = false;
1251 Label invoke;
1252 if (expected.is_immediate()) {
1253 ASSERT(actual.is_immediate());
1254 if (expected.immediate() == actual.immediate()) {
1255 definitely_matches = true;
1256 } else {
1257 mov(eax, actual.immediate());
1258 const int sentinel = SharedFunctionInfo::kDontAdaptArgumentsSentinel;
1259 if (expected.immediate() == sentinel) {
1260 // Don't worry about adapting arguments for builtins that
1261 // don't want that done. Skip adaption code by making it look
1262 // like we have a match between expected and actual number of
1263 // arguments.
1264 definitely_matches = true;
1265 } else {
1266 mov(ebx, expected.immediate());
1267 }
1268 }
1269 } else {
1270 if (actual.is_immediate()) {
1271 // Expected is in register, actual is immediate. This is the
1272 // case when we invoke function values without going through the
1273 // IC mechanism.
1274 cmp(expected.reg(), actual.immediate());
1275 j(equal, &invoke);
1276 ASSERT(expected.reg().is(ebx));
1277 mov(eax, actual.immediate());
1278 } else if (!expected.reg().is(actual.reg())) {
1279 // Both expected and actual are in (different) registers. This
1280 // is the case when we invoke functions using call and apply.
1281 cmp(expected.reg(), Operand(actual.reg()));
1282 j(equal, &invoke);
1283 ASSERT(actual.reg().is(eax));
1284 ASSERT(expected.reg().is(ebx));
1285 }
1286 }
1287
1288 if (!definitely_matches) {
1289 Handle<Code> adaptor =
1290 Handle<Code>(Builtins::builtin(Builtins::ArgumentsAdaptorTrampoline));
1291 if (!code_constant.is_null()) {
1292 mov(edx, Immediate(code_constant));
1293 add(Operand(edx), Immediate(Code::kHeaderSize - kHeapObjectTag));
1294 } else if (!code_operand.is_reg(edx)) {
1295 mov(edx, code_operand);
1296 }
1297
1298 if (flag == CALL_FUNCTION) {
1299 call(adaptor, RelocInfo::CODE_TARGET);
1300 jmp(done);
1301 } else {
1302 jmp(adaptor, RelocInfo::CODE_TARGET);
1303 }
1304 bind(&invoke);
1305 }
1306}
1307
1308
1309void MacroAssembler::InvokeCode(const Operand& code,
1310 const ParameterCount& expected,
1311 const ParameterCount& actual,
1312 InvokeFlag flag) {
1313 Label done;
1314 InvokePrologue(expected, actual, Handle<Code>::null(), code, &done, flag);
1315 if (flag == CALL_FUNCTION) {
1316 call(code);
1317 } else {
1318 ASSERT(flag == JUMP_FUNCTION);
1319 jmp(code);
1320 }
1321 bind(&done);
1322}
1323
1324
1325void MacroAssembler::InvokeCode(Handle<Code> code,
1326 const ParameterCount& expected,
1327 const ParameterCount& actual,
1328 RelocInfo::Mode rmode,
1329 InvokeFlag flag) {
1330 Label done;
1331 Operand dummy(eax);
1332 InvokePrologue(expected, actual, code, dummy, &done, flag);
1333 if (flag == CALL_FUNCTION) {
1334 call(code, rmode);
1335 } else {
1336 ASSERT(flag == JUMP_FUNCTION);
1337 jmp(code, rmode);
1338 }
1339 bind(&done);
1340}
1341
1342
1343void MacroAssembler::InvokeFunction(Register fun,
1344 const ParameterCount& actual,
1345 InvokeFlag flag) {
1346 ASSERT(fun.is(edi));
1347 mov(edx, FieldOperand(edi, JSFunction::kSharedFunctionInfoOffset));
1348 mov(esi, FieldOperand(edi, JSFunction::kContextOffset));
1349 mov(ebx, FieldOperand(edx, SharedFunctionInfo::kFormalParameterCountOffset));
1350 mov(edx, FieldOperand(edx, SharedFunctionInfo::kCodeOffset));
1351 lea(edx, FieldOperand(edx, Code::kHeaderSize));
1352
1353 ParameterCount expected(ebx);
1354 InvokeCode(Operand(edx), expected, actual, flag);
1355}
1356
1357
1358void MacroAssembler::InvokeBuiltin(Builtins::JavaScript id, InvokeFlag flag) {
1359 bool resolved;
1360 Handle<Code> code = ResolveBuiltin(id, &resolved);
1361
1362 // Calls are not allowed in some stubs.
1363 ASSERT(flag == JUMP_FUNCTION || allow_stub_calls());
1364
1365 // Rely on the assertion to check that the number of provided
1366 // arguments match the expected number of arguments. Fake a
1367 // parameter count to avoid emitting code to do the check.
1368 ParameterCount expected(0);
1369 InvokeCode(Handle<Code>(code), expected, expected,
1370 RelocInfo::CODE_TARGET, flag);
1371
1372 const char* name = Builtins::GetName(id);
1373 int argc = Builtins::GetArgumentsCount(id);
1374
1375 if (!resolved) {
1376 uint32_t flags =
1377 Bootstrapper::FixupFlagsArgumentsCount::encode(argc) |
Steve Blocka7e24c12009-10-30 11:49:00 +00001378 Bootstrapper::FixupFlagsUseCodeObject::encode(false);
1379 Unresolved entry = { pc_offset() - sizeof(int32_t), flags, name };
1380 unresolved_.Add(entry);
1381 }
1382}
1383
1384
1385void MacroAssembler::GetBuiltinEntry(Register target, Builtins::JavaScript id) {
1386 bool resolved;
1387 Handle<Code> code = ResolveBuiltin(id, &resolved);
1388
1389 const char* name = Builtins::GetName(id);
1390 int argc = Builtins::GetArgumentsCount(id);
1391
1392 mov(Operand(target), Immediate(code));
1393 if (!resolved) {
1394 uint32_t flags =
1395 Bootstrapper::FixupFlagsArgumentsCount::encode(argc) |
Steve Blocka7e24c12009-10-30 11:49:00 +00001396 Bootstrapper::FixupFlagsUseCodeObject::encode(true);
1397 Unresolved entry = { pc_offset() - sizeof(int32_t), flags, name };
1398 unresolved_.Add(entry);
1399 }
1400 add(Operand(target), Immediate(Code::kHeaderSize - kHeapObjectTag));
1401}
1402
1403
1404Handle<Code> MacroAssembler::ResolveBuiltin(Builtins::JavaScript id,
1405 bool* resolved) {
1406 // Move the builtin function into the temporary function slot by
1407 // reading it from the builtins object. NOTE: We should be able to
1408 // reduce this to two instructions by putting the function table in
1409 // the global object instead of the "builtins" object and by using a
1410 // real register for the function.
1411 mov(edx, Operand(esi, Context::SlotOffset(Context::GLOBAL_INDEX)));
1412 mov(edx, FieldOperand(edx, GlobalObject::kBuiltinsOffset));
1413 int builtins_offset =
1414 JSBuiltinsObject::kJSBuiltinsOffset + (id * kPointerSize);
1415 mov(edi, FieldOperand(edx, builtins_offset));
1416
Steve Blocka7e24c12009-10-30 11:49:00 +00001417 return Builtins::GetCode(id, resolved);
1418}
1419
1420
Steve Blockd0582a62009-12-15 09:54:21 +00001421void MacroAssembler::LoadContext(Register dst, int context_chain_length) {
1422 if (context_chain_length > 0) {
1423 // Move up the chain of contexts to the context containing the slot.
1424 mov(dst, Operand(esi, Context::SlotOffset(Context::CLOSURE_INDEX)));
1425 // Load the function context (which is the incoming, outer context).
1426 mov(dst, FieldOperand(dst, JSFunction::kContextOffset));
1427 for (int i = 1; i < context_chain_length; i++) {
1428 mov(dst, Operand(dst, Context::SlotOffset(Context::CLOSURE_INDEX)));
1429 mov(dst, FieldOperand(dst, JSFunction::kContextOffset));
1430 }
1431 // The context may be an intermediate context, not a function context.
1432 mov(dst, Operand(dst, Context::SlotOffset(Context::FCONTEXT_INDEX)));
1433 } else { // Slot is in the current function context.
1434 // The context may be an intermediate context, not a function context.
1435 mov(dst, Operand(esi, Context::SlotOffset(Context::FCONTEXT_INDEX)));
1436 }
1437}
1438
1439
1440
Steve Blocka7e24c12009-10-30 11:49:00 +00001441void MacroAssembler::Ret() {
1442 ret(0);
1443}
1444
1445
Leon Clarkee46be812010-01-19 14:06:41 +00001446void MacroAssembler::Drop(int stack_elements) {
1447 if (stack_elements > 0) {
1448 add(Operand(esp), Immediate(stack_elements * kPointerSize));
1449 }
1450}
1451
1452
1453void MacroAssembler::Move(Register dst, Handle<Object> value) {
1454 mov(dst, value);
1455}
1456
1457
Steve Blocka7e24c12009-10-30 11:49:00 +00001458void MacroAssembler::SetCounter(StatsCounter* counter, int value) {
1459 if (FLAG_native_code_counters && counter->Enabled()) {
1460 mov(Operand::StaticVariable(ExternalReference(counter)), Immediate(value));
1461 }
1462}
1463
1464
1465void MacroAssembler::IncrementCounter(StatsCounter* counter, int value) {
1466 ASSERT(value > 0);
1467 if (FLAG_native_code_counters && counter->Enabled()) {
1468 Operand operand = Operand::StaticVariable(ExternalReference(counter));
1469 if (value == 1) {
1470 inc(operand);
1471 } else {
1472 add(operand, Immediate(value));
1473 }
1474 }
1475}
1476
1477
1478void MacroAssembler::DecrementCounter(StatsCounter* counter, int value) {
1479 ASSERT(value > 0);
1480 if (FLAG_native_code_counters && counter->Enabled()) {
1481 Operand operand = Operand::StaticVariable(ExternalReference(counter));
1482 if (value == 1) {
1483 dec(operand);
1484 } else {
1485 sub(operand, Immediate(value));
1486 }
1487 }
1488}
1489
1490
Leon Clarked91b9f72010-01-27 17:25:45 +00001491void MacroAssembler::IncrementCounter(Condition cc,
1492 StatsCounter* counter,
1493 int value) {
1494 ASSERT(value > 0);
1495 if (FLAG_native_code_counters && counter->Enabled()) {
1496 Label skip;
1497 j(NegateCondition(cc), &skip);
1498 pushfd();
1499 IncrementCounter(counter, value);
1500 popfd();
1501 bind(&skip);
1502 }
1503}
1504
1505
1506void MacroAssembler::DecrementCounter(Condition cc,
1507 StatsCounter* counter,
1508 int value) {
1509 ASSERT(value > 0);
1510 if (FLAG_native_code_counters && counter->Enabled()) {
1511 Label skip;
1512 j(NegateCondition(cc), &skip);
1513 pushfd();
1514 DecrementCounter(counter, value);
1515 popfd();
1516 bind(&skip);
1517 }
1518}
1519
1520
Steve Blocka7e24c12009-10-30 11:49:00 +00001521void MacroAssembler::Assert(Condition cc, const char* msg) {
1522 if (FLAG_debug_code) Check(cc, msg);
1523}
1524
1525
1526void MacroAssembler::Check(Condition cc, const char* msg) {
1527 Label L;
1528 j(cc, &L, taken);
1529 Abort(msg);
1530 // will not return here
1531 bind(&L);
1532}
1533
1534
1535void MacroAssembler::Abort(const char* msg) {
1536 // We want to pass the msg string like a smi to avoid GC
1537 // problems, however msg is not guaranteed to be aligned
1538 // properly. Instead, we pass an aligned pointer that is
1539 // a proper v8 smi, but also pass the alignment difference
1540 // from the real pointer as a smi.
1541 intptr_t p1 = reinterpret_cast<intptr_t>(msg);
1542 intptr_t p0 = (p1 & ~kSmiTagMask) + kSmiTag;
1543 ASSERT(reinterpret_cast<Object*>(p0)->IsSmi());
1544#ifdef DEBUG
1545 if (msg != NULL) {
1546 RecordComment("Abort message: ");
1547 RecordComment(msg);
1548 }
1549#endif
Steve Blockd0582a62009-12-15 09:54:21 +00001550 // Disable stub call restrictions to always allow calls to abort.
1551 set_allow_stub_calls(true);
1552
Steve Blocka7e24c12009-10-30 11:49:00 +00001553 push(eax);
1554 push(Immediate(p0));
1555 push(Immediate(reinterpret_cast<intptr_t>(Smi::FromInt(p1 - p0))));
1556 CallRuntime(Runtime::kAbort, 2);
1557 // will not return here
Steve Blockd0582a62009-12-15 09:54:21 +00001558 int3();
Steve Blocka7e24c12009-10-30 11:49:00 +00001559}
1560
1561
Leon Clarked91b9f72010-01-27 17:25:45 +00001562void MacroAssembler::JumpIfNotBothSequentialAsciiStrings(Register object1,
1563 Register object2,
1564 Register scratch1,
1565 Register scratch2,
1566 Label* failure) {
1567 // Check that both objects are not smis.
1568 ASSERT_EQ(0, kSmiTag);
1569 mov(scratch1, Operand(object1));
1570 and_(scratch1, Operand(object2));
1571 test(scratch1, Immediate(kSmiTagMask));
1572 j(zero, failure);
1573
1574 // Load instance type for both strings.
1575 mov(scratch1, FieldOperand(object1, HeapObject::kMapOffset));
1576 mov(scratch2, FieldOperand(object2, HeapObject::kMapOffset));
1577 movzx_b(scratch1, FieldOperand(scratch1, Map::kInstanceTypeOffset));
1578 movzx_b(scratch2, FieldOperand(scratch2, Map::kInstanceTypeOffset));
1579
1580 // Check that both are flat ascii strings.
1581 const int kFlatAsciiStringMask =
1582 kIsNotStringMask | kStringRepresentationMask | kStringEncodingMask;
1583 const int kFlatAsciiStringTag = ASCII_STRING_TYPE;
1584 // Interleave bits from both instance types and compare them in one check.
1585 ASSERT_EQ(0, kFlatAsciiStringMask & (kFlatAsciiStringMask << 3));
1586 and_(scratch1, kFlatAsciiStringMask);
1587 and_(scratch2, kFlatAsciiStringMask);
1588 lea(scratch1, Operand(scratch1, scratch2, times_8, 0));
1589 cmp(scratch1, kFlatAsciiStringTag | (kFlatAsciiStringTag << 3));
1590 j(not_equal, failure);
1591}
1592
1593
Steve Blocka7e24c12009-10-30 11:49:00 +00001594CodePatcher::CodePatcher(byte* address, int size)
1595 : address_(address), size_(size), masm_(address, size + Assembler::kGap) {
1596 // Create a new macro assembler pointing to the address of the code to patch.
1597 // The size is adjusted with kGap on order for the assembler to generate size
1598 // bytes of instructions without failing with buffer size constraints.
1599 ASSERT(masm_.reloc_info_writer.pos() == address_ + size_ + Assembler::kGap);
1600}
1601
1602
1603CodePatcher::~CodePatcher() {
1604 // Indicate that code has changed.
1605 CPU::FlushICache(address_, size_);
1606
1607 // Check that the code was patched as expected.
1608 ASSERT(masm_.pc_ == address_ + size_);
1609 ASSERT(masm_.reloc_info_writer.pos() == address_ + size_ + Assembler::kGap);
1610}
1611
1612
1613} } // namespace v8::internal