38090087edfeaf63354ae62cc333235dff0ec93b
[platform/framework/web/crosswalk.git] / src / v8 / src / ia32 / deoptimizer-ia32.cc
1 // Copyright 2012 the V8 project authors. All rights reserved.
2 // Redistribution and use in source and binary forms, with or without
3 // modification, are permitted provided that the following conditions are
4 // met:
5 //
6 //     * Redistributions of source code must retain the above copyright
7 //       notice, this list of conditions and the following disclaimer.
8 //     * Redistributions in binary form must reproduce the above
9 //       copyright notice, this list of conditions and the following
10 //       disclaimer in the documentation and/or other materials provided
11 //       with the distribution.
12 //     * Neither the name of Google Inc. nor the names of its
13 //       contributors may be used to endorse or promote products derived
14 //       from this software without specific prior written permission.
15 //
16 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27
28 #include "v8.h"
29
30 #if V8_TARGET_ARCH_IA32
31
32 #include "codegen.h"
33 #include "deoptimizer.h"
34 #include "full-codegen.h"
35 #include "safepoint-table.h"
36
37 namespace v8 {
38 namespace internal {
39
40 const int Deoptimizer::table_entry_size_ = 10;
41
42
43 int Deoptimizer::patch_size() {
44   return Assembler::kCallInstructionLength;
45 }
46
47
48 void Deoptimizer::EnsureRelocSpaceForLazyDeoptimization(Handle<Code> code) {
49   Isolate* isolate = code->GetIsolate();
50   HandleScope scope(isolate);
51
52   // Compute the size of relocation information needed for the code
53   // patching in Deoptimizer::DeoptimizeFunction.
54   int min_reloc_size = 0;
55   int prev_pc_offset = 0;
56   DeoptimizationInputData* deopt_data =
57       DeoptimizationInputData::cast(code->deoptimization_data());
58   for (int i = 0; i < deopt_data->DeoptCount(); i++) {
59     int pc_offset = deopt_data->Pc(i)->value();
60     if (pc_offset == -1) continue;
61     ASSERT_GE(pc_offset, prev_pc_offset);
62     int pc_delta = pc_offset - prev_pc_offset;
63     // We use RUNTIME_ENTRY reloc info which has a size of 2 bytes
64     // if encodable with small pc delta encoding and up to 6 bytes
65     // otherwise.
66     if (pc_delta <= RelocInfo::kMaxSmallPCDelta) {
67       min_reloc_size += 2;
68     } else {
69       min_reloc_size += 6;
70     }
71     prev_pc_offset = pc_offset;
72   }
73
74   // If the relocation information is not big enough we create a new
75   // relocation info object that is padded with comments to make it
76   // big enough for lazy doptimization.
77   int reloc_length = code->relocation_info()->length();
78   if (min_reloc_size > reloc_length) {
79     int comment_reloc_size = RelocInfo::kMinRelocCommentSize;
80     // Padding needed.
81     int min_padding = min_reloc_size - reloc_length;
82     // Number of comments needed to take up at least that much space.
83     int additional_comments =
84         (min_padding + comment_reloc_size - 1) / comment_reloc_size;
85     // Actual padding size.
86     int padding = additional_comments * comment_reloc_size;
87     // Allocate new relocation info and copy old relocation to the end
88     // of the new relocation info array because relocation info is
89     // written and read backwards.
90     Factory* factory = isolate->factory();
91     Handle<ByteArray> new_reloc =
92         factory->NewByteArray(reloc_length + padding, TENURED);
93     OS::MemCopy(new_reloc->GetDataStartAddress() + padding,
94                 code->relocation_info()->GetDataStartAddress(),
95                 reloc_length);
96     // Create a relocation writer to write the comments in the padding
97     // space. Use position 0 for everything to ensure short encoding.
98     RelocInfoWriter reloc_info_writer(
99         new_reloc->GetDataStartAddress() + padding, 0);
100     intptr_t comment_string
101         = reinterpret_cast<intptr_t>(RelocInfo::kFillerCommentString);
102     RelocInfo rinfo(0, RelocInfo::COMMENT, comment_string, NULL);
103     for (int i = 0; i < additional_comments; ++i) {
104 #ifdef DEBUG
105       byte* pos_before = reloc_info_writer.pos();
106 #endif
107       reloc_info_writer.Write(&rinfo);
108       ASSERT(RelocInfo::kMinRelocCommentSize ==
109              pos_before - reloc_info_writer.pos());
110     }
111     // Replace relocation information on the code object.
112     code->set_relocation_info(*new_reloc);
113   }
114 }
115
116
117 void Deoptimizer::PatchCodeForDeoptimization(Isolate* isolate, Code* code) {
118   Address code_start_address = code->instruction_start();
119   // We will overwrite the code's relocation info in-place. Relocation info
120   // is written backward. The relocation info is the payload of a byte
121   // array.  Later on we will slide this to the start of the byte array and
122   // create a filler object in the remaining space.
123   ByteArray* reloc_info = code->relocation_info();
124   Address reloc_end_address = reloc_info->address() + reloc_info->Size();
125   RelocInfoWriter reloc_info_writer(reloc_end_address, code_start_address);
126
127   // For each LLazyBailout instruction insert a call to the corresponding
128   // deoptimization entry.
129
130   // Since the call is a relative encoding, write new
131   // reloc info.  We do not need any of the existing reloc info because the
132   // existing code will not be used again (we zap it in debug builds).
133   //
134   // Emit call to lazy deoptimization at all lazy deopt points.
135   DeoptimizationInputData* deopt_data =
136       DeoptimizationInputData::cast(code->deoptimization_data());
137 #ifdef DEBUG
138   Address prev_call_address = NULL;
139 #endif
140   for (int i = 0; i < deopt_data->DeoptCount(); i++) {
141     if (deopt_data->Pc(i)->value() == -1) continue;
142     // Patch lazy deoptimization entry.
143     Address call_address = code_start_address + deopt_data->Pc(i)->value();
144     CodePatcher patcher(call_address, patch_size());
145     Address deopt_entry = GetDeoptimizationEntry(isolate, i, LAZY);
146     patcher.masm()->call(deopt_entry, RelocInfo::NONE32);
147     // We use RUNTIME_ENTRY for deoptimization bailouts.
148     RelocInfo rinfo(call_address + 1,  // 1 after the call opcode.
149                     RelocInfo::RUNTIME_ENTRY,
150                     reinterpret_cast<intptr_t>(deopt_entry),
151                     NULL);
152     reloc_info_writer.Write(&rinfo);
153     ASSERT_GE(reloc_info_writer.pos(),
154               reloc_info->address() + ByteArray::kHeaderSize);
155     ASSERT(prev_call_address == NULL ||
156            call_address >= prev_call_address + patch_size());
157     ASSERT(call_address + patch_size() <= code->instruction_end());
158 #ifdef DEBUG
159     prev_call_address = call_address;
160 #endif
161   }
162
163   // Move the relocation info to the beginning of the byte array.
164   int new_reloc_size = reloc_end_address - reloc_info_writer.pos();
165   OS::MemMove(
166       code->relocation_start(), reloc_info_writer.pos(), new_reloc_size);
167
168   // The relocation info is in place, update the size.
169   reloc_info->set_length(new_reloc_size);
170
171   // Handle the junk part after the new relocation info. We will create
172   // a non-live object in the extra space at the end of the former reloc info.
173   Address junk_address = reloc_info->address() + reloc_info->Size();
174   ASSERT(junk_address <= reloc_end_address);
175   isolate->heap()->CreateFillerObjectAt(junk_address,
176                                         reloc_end_address - junk_address);
177 }
178
179
180 void Deoptimizer::FillInputFrame(Address tos, JavaScriptFrame* frame) {
181   // Set the register values. The values are not important as there are no
182   // callee saved registers in JavaScript frames, so all registers are
183   // spilled. Registers ebp and esp are set to the correct values though.
184
185   for (int i = 0; i < Register::kNumRegisters; i++) {
186     input_->SetRegister(i, i * 4);
187   }
188   input_->SetRegister(esp.code(), reinterpret_cast<intptr_t>(frame->sp()));
189   input_->SetRegister(ebp.code(), reinterpret_cast<intptr_t>(frame->fp()));
190   simd128_value_t zero = {{0.0, 0.0}};
191   for (int i = 0; i < DoubleRegister::NumAllocatableRegisters(); i++) {
192     input_->SetSIMD128Register(i, zero);
193   }
194
195   // Fill the frame content from the actual data on the frame.
196   for (unsigned i = 0; i < input_->GetFrameSize(); i += kPointerSize) {
197     input_->SetFrameSlot(i, Memory::uint32_at(tos + i));
198   }
199 }
200
201
202 void Deoptimizer::SetPlatformCompiledStubRegisters(
203     FrameDescription* output_frame, CodeStubInterfaceDescriptor* descriptor) {
204   intptr_t handler =
205       reinterpret_cast<intptr_t>(descriptor->deoptimization_handler_);
206   int params = descriptor->GetHandlerParameterCount();
207   output_frame->SetRegister(eax.code(), params);
208   output_frame->SetRegister(ebx.code(), handler);
209 }
210
211
212 void Deoptimizer::CopySIMD128Registers(FrameDescription* output_frame) {
213   if (!CpuFeatures::IsSupported(SSE2)) return;
214   for (int i = 0; i < XMMRegister::kNumAllocatableRegisters; ++i) {
215     simd128_value_t xmm_value = input_->GetSIMD128Register(i);
216     output_frame->SetSIMD128Register(i, xmm_value);
217   }
218 }
219
220
221 bool Deoptimizer::HasAlignmentPadding(JSFunction* function) {
222   int parameter_count = function->shared()->formal_parameter_count() + 1;
223   unsigned input_frame_size = input_->GetFrameSize();
224   unsigned alignment_state_offset =
225       input_frame_size - parameter_count * kPointerSize -
226       StandardFrameConstants::kFixedFrameSize -
227       kPointerSize;
228   ASSERT(JavaScriptFrameConstants::kDynamicAlignmentStateOffset ==
229       JavaScriptFrameConstants::kLocal0Offset);
230   int32_t alignment_state = input_->GetFrameSlot(alignment_state_offset);
231   return (alignment_state == kAlignmentPaddingPushed);
232 }
233
234
235 Code* Deoptimizer::NotifyStubFailureBuiltin() {
236   Builtins::Name name = CpuFeatures::IsSupported(SSE2) ?
237       Builtins::kNotifyStubFailureSaveDoubles : Builtins::kNotifyStubFailure;
238   return isolate_->builtins()->builtin(name);
239 }
240
241
242 #define __ masm()->
243
244 void Deoptimizer::EntryGenerator::Generate() {
245   GeneratePrologue();
246
247   // Save all general purpose registers before messing with them.
248   const int kNumberOfRegisters = Register::kNumRegisters;
249
250   const int kXMMRegsSize = kSIMD128Size *
251       XMMRegister::kNumAllocatableRegisters;
252   __ sub(esp, Immediate(kXMMRegsSize));
253   if (CpuFeatures::IsSupported(SSE2)) {
254     CpuFeatureScope scope(masm(), SSE2);
255     for (int i = 0; i < XMMRegister::kNumAllocatableRegisters; ++i) {
256       XMMRegister xmm_reg = XMMRegister::FromAllocationIndex(i);
257       int offset = i * kSIMD128Size;
258       __ movups(Operand(esp, offset), xmm_reg);
259     }
260   }
261
262   __ pushad();
263
264   const int kSavedRegistersAreaSize = kNumberOfRegisters * kPointerSize +
265                                       kXMMRegsSize;
266
267   // Get the bailout id from the stack.
268   __ mov(ebx, Operand(esp, kSavedRegistersAreaSize));
269
270   // Get the address of the location in the code object
271   // and compute the fp-to-sp delta in register edx.
272   __ mov(ecx, Operand(esp, kSavedRegistersAreaSize + 1 * kPointerSize));
273   __ lea(edx, Operand(esp, kSavedRegistersAreaSize + 2 * kPointerSize));
274
275   __ sub(edx, ebp);
276   __ neg(edx);
277
278   // Allocate a new deoptimizer object.
279   __ PrepareCallCFunction(6, eax);
280   __ mov(eax, Operand(ebp, JavaScriptFrameConstants::kFunctionOffset));
281   __ mov(Operand(esp, 0 * kPointerSize), eax);  // Function.
282   __ mov(Operand(esp, 1 * kPointerSize), Immediate(type()));  // Bailout type.
283   __ mov(Operand(esp, 2 * kPointerSize), ebx);  // Bailout id.
284   __ mov(Operand(esp, 3 * kPointerSize), ecx);  // Code address or 0.
285   __ mov(Operand(esp, 4 * kPointerSize), edx);  // Fp-to-sp delta.
286   __ mov(Operand(esp, 5 * kPointerSize),
287          Immediate(ExternalReference::isolate_address(isolate())));
288   {
289     AllowExternalCallThatCantCauseGC scope(masm());
290     __ CallCFunction(ExternalReference::new_deoptimizer_function(isolate()), 6);
291   }
292
293   // Preserve deoptimizer object in register eax and get the input
294   // frame descriptor pointer.
295   __ mov(ebx, Operand(eax, Deoptimizer::input_offset()));
296
297   // Fill in the input registers.
298   for (int i = kNumberOfRegisters - 1; i >= 0; i--) {
299     int offset = (i * kPointerSize) + FrameDescription::registers_offset();
300     __ pop(Operand(ebx, offset));
301   }
302
303   int xmm_regs_offset = FrameDescription::simd128_registers_offset();
304   if (CpuFeatures::IsSupported(SSE2)) {
305     CpuFeatureScope scope(masm(), SSE2);
306     // Fill in the xmm input registers.
307     for (int i = 0; i < XMMRegister::kNumAllocatableRegisters; ++i) {
308       int dst_offset = i * kSIMD128Size + xmm_regs_offset;
309       int src_offset = i * kSIMD128Size;
310       __ movups(xmm0, Operand(esp, src_offset));
311       __ movups(Operand(ebx, dst_offset), xmm0);
312     }
313   }
314
315   // Clear FPU all exceptions.
316   // TODO(ulan): Find out why the TOP register is not zero here in some cases,
317   // and check that the generated code never deoptimizes with unbalanced stack.
318   __ fnclex();
319
320   // Remove the bailout id, return address and the double registers.
321   __ add(esp, Immediate(kXMMRegsSize + 2 * kPointerSize));
322
323   // Compute a pointer to the unwinding limit in register ecx; that is
324   // the first stack slot not part of the input frame.
325   __ mov(ecx, Operand(ebx, FrameDescription::frame_size_offset()));
326   __ add(ecx, esp);
327
328   // Unwind the stack down to - but not including - the unwinding
329   // limit and copy the contents of the activation frame to the input
330   // frame description.
331   __ lea(edx, Operand(ebx, FrameDescription::frame_content_offset()));
332   Label pop_loop_header;
333   __ jmp(&pop_loop_header);
334   Label pop_loop;
335   __ bind(&pop_loop);
336   __ pop(Operand(edx, 0));
337   __ add(edx, Immediate(sizeof(uint32_t)));
338   __ bind(&pop_loop_header);
339   __ cmp(ecx, esp);
340   __ j(not_equal, &pop_loop);
341
342   // Compute the output frame in the deoptimizer.
343   __ push(eax);
344   __ PrepareCallCFunction(1, ebx);
345   __ mov(Operand(esp, 0 * kPointerSize), eax);
346   {
347     AllowExternalCallThatCantCauseGC scope(masm());
348     __ CallCFunction(
349         ExternalReference::compute_output_frames_function(isolate()), 1);
350   }
351   __ pop(eax);
352
353   // If frame was dynamically aligned, pop padding.
354   Label no_padding;
355   __ cmp(Operand(eax, Deoptimizer::has_alignment_padding_offset()),
356          Immediate(0));
357   __ j(equal, &no_padding);
358   __ pop(ecx);
359   if (FLAG_debug_code) {
360     __ cmp(ecx, Immediate(kAlignmentZapValue));
361     __ Assert(equal, kAlignmentMarkerExpected);
362   }
363   __ bind(&no_padding);
364
365   // Replace the current frame with the output frames.
366   Label outer_push_loop, inner_push_loop,
367       outer_loop_header, inner_loop_header;
368   // Outer loop state: eax = current FrameDescription**, edx = one past the
369   // last FrameDescription**.
370   __ mov(edx, Operand(eax, Deoptimizer::output_count_offset()));
371   __ mov(eax, Operand(eax, Deoptimizer::output_offset()));
372   __ lea(edx, Operand(eax, edx, times_4, 0));
373   __ jmp(&outer_loop_header);
374   __ bind(&outer_push_loop);
375   // Inner loop state: ebx = current FrameDescription*, ecx = loop index.
376   __ mov(ebx, Operand(eax, 0));
377   __ mov(ecx, Operand(ebx, FrameDescription::frame_size_offset()));
378   __ jmp(&inner_loop_header);
379   __ bind(&inner_push_loop);
380   __ sub(ecx, Immediate(sizeof(uint32_t)));
381   __ push(Operand(ebx, ecx, times_1, FrameDescription::frame_content_offset()));
382   __ bind(&inner_loop_header);
383   __ test(ecx, ecx);
384   __ j(not_zero, &inner_push_loop);
385   __ add(eax, Immediate(kPointerSize));
386   __ bind(&outer_loop_header);
387   __ cmp(eax, edx);
388   __ j(below, &outer_push_loop);
389
390   // In case of a failed STUB, we have to restore the XMM registers.
391   if (CpuFeatures::IsSupported(SSE2)) {
392     CpuFeatureScope scope(masm(), SSE2);
393     for (int i = 0; i < XMMRegister::kNumAllocatableRegisters; ++i) {
394       XMMRegister xmm_reg = XMMRegister::FromAllocationIndex(i);
395       int src_offset = i * kSIMD128Size + xmm_regs_offset;
396       __ movups(xmm_reg, Operand(ebx, src_offset));
397     }
398   }
399
400   // Push state, pc, and continuation from the last output frame.
401   __ push(Operand(ebx, FrameDescription::state_offset()));
402   __ push(Operand(ebx, FrameDescription::pc_offset()));
403   __ push(Operand(ebx, FrameDescription::continuation_offset()));
404
405
406   // Push the registers from the last output frame.
407   for (int i = 0; i < kNumberOfRegisters; i++) {
408     int offset = (i * kPointerSize) + FrameDescription::registers_offset();
409     __ push(Operand(ebx, offset));
410   }
411
412   // Restore the registers from the stack.
413   __ popad();
414
415   // Return to the continuation point.
416   __ ret(0);
417 }
418
419
420 void Deoptimizer::TableEntryGenerator::GeneratePrologue() {
421   // Create a sequence of deoptimization entries.
422   Label done;
423   for (int i = 0; i < count(); i++) {
424     int start = masm()->pc_offset();
425     USE(start);
426     __ push_imm32(i);
427     __ jmp(&done);
428     ASSERT(masm()->pc_offset() - start == table_entry_size_);
429   }
430   __ bind(&done);
431 }
432
433
434 void FrameDescription::SetCallerPc(unsigned offset, intptr_t value) {
435   SetFrameSlot(offset, value);
436 }
437
438
439 void FrameDescription::SetCallerFp(unsigned offset, intptr_t value) {
440   SetFrameSlot(offset, value);
441 }
442
443
444 double FrameDescription::GetDoubleRegister(unsigned n) const {
445   ASSERT(n < ARRAY_SIZE(simd128_registers_));
446   return simd128_registers_[n].d[0];
447 }
448
449
450 void FrameDescription::SetDoubleRegister(unsigned n, double value) {
451   ASSERT(n < ARRAY_SIZE(simd128_registers_));
452   simd128_registers_[n].d[0] = value;
453 }
454
455
456 #undef __
457
458
459 } }  // namespace v8::internal
460
461 #endif  // V8_TARGET_ARCH_IA32