deoptimizer-ia32.cc revision 69a99ed0b2b2ef69d393c371b03db3a98aaf880e
1// Copyright 2011 the V8 project authors. All rights reserved.
2// Redistribution and use in source and binary forms, with or without
3// modification, are permitted provided that the following conditions are
4// met:
5//
6//     * Redistributions of source code must retain the above copyright
7//       notice, this list of conditions and the following disclaimer.
8//     * Redistributions in binary form must reproduce the above
9//       copyright notice, this list of conditions and the following
10//       disclaimer in the documentation and/or other materials provided
11//       with the distribution.
12//     * Neither the name of Google Inc. nor the names of its
13//       contributors may be used to endorse or promote products derived
14//       from this software without specific prior written permission.
15//
16// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27
28#include "v8.h"
29
30#if defined(V8_TARGET_ARCH_IA32)
31
32#include "codegen.h"
33#include "deoptimizer.h"
34#include "full-codegen.h"
35#include "safepoint-table.h"
36
37namespace v8 {
38namespace internal {
39
40const int Deoptimizer::table_entry_size_ = 10;
41
42
43int Deoptimizer::patch_size() {
44  return Assembler::kCallInstructionLength;
45}
46
47
48static void ZapCodeRange(Address start, Address end) {
49#ifdef DEBUG
50  ASSERT(start <= end);
51  int size = end - start;
52  CodePatcher destroyer(start, size);
53  while (size-- > 0) destroyer.masm()->int3();
54#endif
55}
56
57
58void Deoptimizer::EnsureRelocSpaceForLazyDeoptimization(Handle<Code> code) {
59  Isolate* isolate = code->GetIsolate();
60  HandleScope scope(isolate);
61
62  // Compute the size of relocation information needed for the code
63  // patching in Deoptimizer::DeoptimizeFunction.
64  int min_reloc_size = 0;
65  Address prev_reloc_address = code->instruction_start();
66  Address code_start_address = code->instruction_start();
67  SafepointTable table(*code);
68  for (unsigned i = 0; i < table.length(); ++i) {
69    Address curr_reloc_address = code_start_address + table.GetPcOffset(i);
70    ASSERT_GE(curr_reloc_address, prev_reloc_address);
71    SafepointEntry safepoint_entry = table.GetEntry(i);
72    int deoptimization_index = safepoint_entry.deoptimization_index();
73    if (deoptimization_index != Safepoint::kNoDeoptimizationIndex) {
74      // The gap code is needed to get to the state expected at the
75      // bailout and we need to skip the call opcode to get to the
76      // address that needs reloc.
77      curr_reloc_address += safepoint_entry.gap_code_size() + 1;
78      int pc_delta = curr_reloc_address - prev_reloc_address;
79      // We use RUNTIME_ENTRY reloc info which has a size of 2 bytes
80      // if encodable with small pc delta encoding and up to 6 bytes
81      // otherwise.
82      if (pc_delta <= RelocInfo::kMaxSmallPCDelta) {
83        min_reloc_size += 2;
84      } else {
85        min_reloc_size += 6;
86      }
87      prev_reloc_address = curr_reloc_address;
88    }
89  }
90
91  // If the relocation information is not big enough we create a new
92  // relocation info object that is padded with comments to make it
93  // big enough for lazy doptimization.
94  int reloc_length = code->relocation_info()->length();
95  if (min_reloc_size > reloc_length) {
96    int comment_reloc_size = RelocInfo::kMinRelocCommentSize;
97    // Padding needed.
98    int min_padding = min_reloc_size - reloc_length;
99    // Number of comments needed to take up at least that much space.
100    int additional_comments =
101        (min_padding + comment_reloc_size - 1) / comment_reloc_size;
102    // Actual padding size.
103    int padding = additional_comments * comment_reloc_size;
104    // Allocate new relocation info and copy old relocation to the end
105    // of the new relocation info array because relocation info is
106    // written and read backwards.
107    Factory* factory = isolate->factory();
108    Handle<ByteArray> new_reloc =
109        factory->NewByteArray(reloc_length + padding, TENURED);
110    memcpy(new_reloc->GetDataStartAddress() + padding,
111           code->relocation_info()->GetDataStartAddress(),
112           reloc_length);
113    // Create a relocation writer to write the comments in the padding
114    // space. Use position 0 for everything to ensure short encoding.
115    RelocInfoWriter reloc_info_writer(
116        new_reloc->GetDataStartAddress() + padding, 0);
117    intptr_t comment_string
118        = reinterpret_cast<intptr_t>(RelocInfo::kFillerCommentString);
119    RelocInfo rinfo(0, RelocInfo::COMMENT, comment_string);
120    for (int i = 0; i < additional_comments; ++i) {
121#ifdef DEBUG
122      byte* pos_before = reloc_info_writer.pos();
123#endif
124      reloc_info_writer.Write(&rinfo);
125      ASSERT(RelocInfo::kMinRelocCommentSize ==
126             pos_before - reloc_info_writer.pos());
127    }
128    // Replace relocation information on the code object.
129    code->set_relocation_info(*new_reloc);
130  }
131}
132
133
134void Deoptimizer::DeoptimizeFunction(JSFunction* function) {
135  if (!function->IsOptimized()) return;
136
137  Isolate* isolate = function->GetIsolate();
138  HandleScope scope(isolate);
139  AssertNoAllocation no_allocation;
140
141  // Get the optimized code.
142  Code* code = function->code();
143  Address code_start_address = code->instruction_start();
144
145  // We will overwrite the code's relocation info in-place. Relocation info
146  // is written backward. The relocation info is the payload of a byte
147  // array.  Later on we will slide this to the start of the byte array and
148  // create a filler object in the remaining space.
149  ByteArray* reloc_info = code->relocation_info();
150  Address reloc_end_address = reloc_info->address() + reloc_info->Size();
151  RelocInfoWriter reloc_info_writer(reloc_end_address, code_start_address);
152
153  // For each return after a safepoint insert a call to the corresponding
154  // deoptimization entry.  Since the call is a relative encoding, write new
155  // reloc info.  We do not need any of the existing reloc info because the
156  // existing code will not be used again (we zap it in debug builds).
157  SafepointTable table(code);
158  Address prev_address = code_start_address;
159  for (unsigned i = 0; i < table.length(); ++i) {
160    Address curr_address = code_start_address + table.GetPcOffset(i);
161    ASSERT_GE(curr_address, prev_address);
162    ZapCodeRange(prev_address, curr_address);
163
164    SafepointEntry safepoint_entry = table.GetEntry(i);
165    int deoptimization_index = safepoint_entry.deoptimization_index();
166    if (deoptimization_index != Safepoint::kNoDeoptimizationIndex) {
167      // The gap code is needed to get to the state expected at the bailout.
168      curr_address += safepoint_entry.gap_code_size();
169
170      CodePatcher patcher(curr_address, patch_size());
171      Address deopt_entry = GetDeoptimizationEntry(deoptimization_index, LAZY);
172      patcher.masm()->call(deopt_entry, RelocInfo::NONE);
173
174      // We use RUNTIME_ENTRY for deoptimization bailouts.
175      RelocInfo rinfo(curr_address + 1,  // 1 after the call opcode.
176                      RelocInfo::RUNTIME_ENTRY,
177                      reinterpret_cast<intptr_t>(deopt_entry));
178      reloc_info_writer.Write(&rinfo);
179      ASSERT_GE(reloc_info_writer.pos(),
180                reloc_info->address() + ByteArray::kHeaderSize);
181      curr_address += patch_size();
182    }
183    prev_address = curr_address;
184  }
185  ZapCodeRange(prev_address,
186               code_start_address + code->safepoint_table_offset());
187
188  // Move the relocation info to the beginning of the byte array.
189  int new_reloc_size = reloc_end_address - reloc_info_writer.pos();
190  memmove(code->relocation_start(), reloc_info_writer.pos(), new_reloc_size);
191
192  // The relocation info is in place, update the size.
193  reloc_info->set_length(new_reloc_size);
194
195  // Handle the junk part after the new relocation info. We will create
196  // a non-live object in the extra space at the end of the former reloc info.
197  Address junk_address = reloc_info->address() + reloc_info->Size();
198  ASSERT(junk_address <= reloc_end_address);
199  isolate->heap()->CreateFillerObjectAt(junk_address,
200                                        reloc_end_address - junk_address);
201
202  // Add the deoptimizing code to the list.
203  DeoptimizingCodeListNode* node = new DeoptimizingCodeListNode(code);
204  DeoptimizerData* data = isolate->deoptimizer_data();
205  node->set_next(data->deoptimizing_code_list_);
206  data->deoptimizing_code_list_ = node;
207
208  // Set the code for the function to non-optimized version.
209  function->ReplaceCode(function->shared()->code());
210
211  if (FLAG_trace_deopt) {
212    PrintF("[forced deoptimization: ");
213    function->PrintName();
214    PrintF(" / %x]\n", reinterpret_cast<uint32_t>(function));
215#ifdef DEBUG
216    if (FLAG_print_code) {
217      code->PrintLn();
218    }
219#endif
220  }
221}
222
223
224void Deoptimizer::PatchStackCheckCodeAt(Address pc_after,
225                                        Code* check_code,
226                                        Code* replacement_code) {
227  Address call_target_address = pc_after - kIntSize;
228  ASSERT(check_code->entry() ==
229         Assembler::target_address_at(call_target_address));
230  // The stack check code matches the pattern:
231  //
232  //     cmp esp, <limit>
233  //     jae ok
234  //     call <stack guard>
235  //     test eax, <loop nesting depth>
236  // ok: ...
237  //
238  // We will patch away the branch so the code is:
239  //
240  //     cmp esp, <limit>  ;; Not changed
241  //     nop
242  //     nop
243  //     call <on-stack replacment>
244  //     test eax, <loop nesting depth>
245  // ok:
246  ASSERT(*(call_target_address - 3) == 0x73 &&  // jae
247         *(call_target_address - 2) == 0x07 &&  // offset
248         *(call_target_address - 1) == 0xe8);   // call
249  *(call_target_address - 3) = 0x90;  // nop
250  *(call_target_address - 2) = 0x90;  // nop
251  Assembler::set_target_address_at(call_target_address,
252                                   replacement_code->entry());
253}
254
255
256void Deoptimizer::RevertStackCheckCodeAt(Address pc_after,
257                                         Code* check_code,
258                                         Code* replacement_code) {
259  Address call_target_address = pc_after - kIntSize;
260  ASSERT(replacement_code->entry() ==
261         Assembler::target_address_at(call_target_address));
262  // Replace the nops from patching (Deoptimizer::PatchStackCheckCode) to
263  // restore the conditional branch.
264  ASSERT(*(call_target_address - 3) == 0x90 &&  // nop
265         *(call_target_address - 2) == 0x90 &&  // nop
266         *(call_target_address - 1) == 0xe8);   // call
267  *(call_target_address - 3) = 0x73;  // jae
268  *(call_target_address - 2) = 0x07;  // offset
269  Assembler::set_target_address_at(call_target_address,
270                                   check_code->entry());
271}
272
273
274static int LookupBailoutId(DeoptimizationInputData* data, unsigned ast_id) {
275  ByteArray* translations = data->TranslationByteArray();
276  int length = data->DeoptCount();
277  for (int i = 0; i < length; i++) {
278    if (static_cast<unsigned>(data->AstId(i)->value()) == ast_id) {
279      TranslationIterator it(translations,  data->TranslationIndex(i)->value());
280      int value = it.Next();
281      ASSERT(Translation::BEGIN == static_cast<Translation::Opcode>(value));
282      // Read the number of frames.
283      value = it.Next();
284      if (value == 1) return i;
285    }
286  }
287  UNREACHABLE();
288  return -1;
289}
290
291
292void Deoptimizer::DoComputeOsrOutputFrame() {
293  DeoptimizationInputData* data = DeoptimizationInputData::cast(
294      optimized_code_->deoptimization_data());
295  unsigned ast_id = data->OsrAstId()->value();
296  // TODO(kasperl): This should not be the bailout_id_. It should be
297  // the ast id. Confusing.
298  ASSERT(bailout_id_ == ast_id);
299
300  int bailout_id = LookupBailoutId(data, ast_id);
301  unsigned translation_index = data->TranslationIndex(bailout_id)->value();
302  ByteArray* translations = data->TranslationByteArray();
303
304  TranslationIterator iterator(translations, translation_index);
305  Translation::Opcode opcode =
306      static_cast<Translation::Opcode>(iterator.Next());
307  ASSERT(Translation::BEGIN == opcode);
308  USE(opcode);
309  int count = iterator.Next();
310  ASSERT(count == 1);
311  USE(count);
312
313  opcode = static_cast<Translation::Opcode>(iterator.Next());
314  USE(opcode);
315  ASSERT(Translation::FRAME == opcode);
316  unsigned node_id = iterator.Next();
317  USE(node_id);
318  ASSERT(node_id == ast_id);
319  JSFunction* function = JSFunction::cast(ComputeLiteral(iterator.Next()));
320  USE(function);
321  ASSERT(function == function_);
322  unsigned height = iterator.Next();
323  unsigned height_in_bytes = height * kPointerSize;
324  USE(height_in_bytes);
325
326  unsigned fixed_size = ComputeFixedSize(function_);
327  unsigned input_frame_size = input_->GetFrameSize();
328  ASSERT(fixed_size + height_in_bytes == input_frame_size);
329
330  unsigned stack_slot_size = optimized_code_->stack_slots() * kPointerSize;
331  unsigned outgoing_height = data->ArgumentsStackHeight(bailout_id)->value();
332  unsigned outgoing_size = outgoing_height * kPointerSize;
333  unsigned output_frame_size = fixed_size + stack_slot_size + outgoing_size;
334  ASSERT(outgoing_size == 0);  // OSR does not happen in the middle of a call.
335
336  if (FLAG_trace_osr) {
337    PrintF("[on-stack replacement: begin 0x%08" V8PRIxPTR " ",
338           reinterpret_cast<intptr_t>(function_));
339    function_->PrintName();
340    PrintF(" => node=%u, frame=%d->%d]\n",
341           ast_id,
342           input_frame_size,
343           output_frame_size);
344  }
345
346  // There's only one output frame in the OSR case.
347  output_count_ = 1;
348  output_ = new FrameDescription*[1];
349  output_[0] = new(output_frame_size) FrameDescription(
350      output_frame_size, function_);
351#ifdef DEBUG
352  output_[0]->SetKind(Code::OPTIMIZED_FUNCTION);
353#endif
354
355  // Clear the incoming parameters in the optimized frame to avoid
356  // confusing the garbage collector.
357  unsigned output_offset = output_frame_size - kPointerSize;
358  int parameter_count = function_->shared()->formal_parameter_count() + 1;
359  for (int i = 0; i < parameter_count; ++i) {
360    output_[0]->SetFrameSlot(output_offset, 0);
361    output_offset -= kPointerSize;
362  }
363
364  // Translate the incoming parameters. This may overwrite some of the
365  // incoming argument slots we've just cleared.
366  int input_offset = input_frame_size - kPointerSize;
367  bool ok = true;
368  int limit = input_offset - (parameter_count * kPointerSize);
369  while (ok && input_offset > limit) {
370    ok = DoOsrTranslateCommand(&iterator, &input_offset);
371  }
372
373  // There are no translation commands for the caller's pc and fp, the
374  // context, and the function.  Set them up explicitly.
375  for (int i =  StandardFrameConstants::kCallerPCOffset;
376       ok && i >=  StandardFrameConstants::kMarkerOffset;
377       i -= kPointerSize) {
378    uint32_t input_value = input_->GetFrameSlot(input_offset);
379    if (FLAG_trace_osr) {
380      const char* name = "UNKNOWN";
381      switch (i) {
382        case StandardFrameConstants::kCallerPCOffset:
383          name = "caller's pc";
384          break;
385        case StandardFrameConstants::kCallerFPOffset:
386          name = "fp";
387          break;
388        case StandardFrameConstants::kContextOffset:
389          name = "context";
390          break;
391        case StandardFrameConstants::kMarkerOffset:
392          name = "function";
393          break;
394      }
395      PrintF("    [esp + %d] <- 0x%08x ; [esp + %d] (fixed part - %s)\n",
396             output_offset,
397             input_value,
398             input_offset,
399             name);
400    }
401    output_[0]->SetFrameSlot(output_offset, input_->GetFrameSlot(input_offset));
402    input_offset -= kPointerSize;
403    output_offset -= kPointerSize;
404  }
405
406  // Translate the rest of the frame.
407  while (ok && input_offset >= 0) {
408    ok = DoOsrTranslateCommand(&iterator, &input_offset);
409  }
410
411  // If translation of any command failed, continue using the input frame.
412  if (!ok) {
413    delete output_[0];
414    output_[0] = input_;
415    output_[0]->SetPc(reinterpret_cast<uint32_t>(from_));
416  } else {
417    // Setup the frame pointer and the context pointer.
418    output_[0]->SetRegister(ebp.code(), input_->GetRegister(ebp.code()));
419    output_[0]->SetRegister(esi.code(), input_->GetRegister(esi.code()));
420
421    unsigned pc_offset = data->OsrPcOffset()->value();
422    uint32_t pc = reinterpret_cast<uint32_t>(
423        optimized_code_->entry() + pc_offset);
424    output_[0]->SetPc(pc);
425  }
426  Code* continuation =
427      function->GetIsolate()->builtins()->builtin(Builtins::kNotifyOSR);
428  output_[0]->SetContinuation(
429      reinterpret_cast<uint32_t>(continuation->entry()));
430
431  if (FLAG_trace_osr) {
432    PrintF("[on-stack replacement translation %s: 0x%08" V8PRIxPTR " ",
433           ok ? "finished" : "aborted",
434           reinterpret_cast<intptr_t>(function));
435    function->PrintName();
436    PrintF(" => pc=0x%0x]\n", output_[0]->GetPc());
437  }
438}
439
440
441void Deoptimizer::DoComputeFrame(TranslationIterator* iterator,
442                                 int frame_index) {
443  // Read the ast node id, function, and frame height for this output frame.
444  Translation::Opcode opcode =
445      static_cast<Translation::Opcode>(iterator->Next());
446  USE(opcode);
447  ASSERT(Translation::FRAME == opcode);
448  int node_id = iterator->Next();
449  JSFunction* function = JSFunction::cast(ComputeLiteral(iterator->Next()));
450  unsigned height = iterator->Next();
451  unsigned height_in_bytes = height * kPointerSize;
452  if (FLAG_trace_deopt) {
453    PrintF("  translating ");
454    function->PrintName();
455    PrintF(" => node=%d, height=%d\n", node_id, height_in_bytes);
456  }
457
458  // The 'fixed' part of the frame consists of the incoming parameters and
459  // the part described by JavaScriptFrameConstants.
460  unsigned fixed_frame_size = ComputeFixedSize(function);
461  unsigned input_frame_size = input_->GetFrameSize();
462  unsigned output_frame_size = height_in_bytes + fixed_frame_size;
463
464  // Allocate and store the output frame description.
465  FrameDescription* output_frame =
466      new(output_frame_size) FrameDescription(output_frame_size, function);
467#ifdef DEBUG
468  output_frame->SetKind(Code::FUNCTION);
469#endif
470
471  bool is_bottommost = (0 == frame_index);
472  bool is_topmost = (output_count_ - 1 == frame_index);
473  ASSERT(frame_index >= 0 && frame_index < output_count_);
474  ASSERT(output_[frame_index] == NULL);
475  output_[frame_index] = output_frame;
476
477  // The top address for the bottommost output frame can be computed from
478  // the input frame pointer and the output frame's height.  For all
479  // subsequent output frames, it can be computed from the previous one's
480  // top address and the current frame's size.
481  uint32_t top_address;
482  if (is_bottommost) {
483    // 2 = context and function in the frame.
484    top_address =
485        input_->GetRegister(ebp.code()) - (2 * kPointerSize) - height_in_bytes;
486  } else {
487    top_address = output_[frame_index - 1]->GetTop() - output_frame_size;
488  }
489  output_frame->SetTop(top_address);
490
491  // Compute the incoming parameter translation.
492  int parameter_count = function->shared()->formal_parameter_count() + 1;
493  unsigned output_offset = output_frame_size;
494  unsigned input_offset = input_frame_size;
495  for (int i = 0; i < parameter_count; ++i) {
496    output_offset -= kPointerSize;
497    DoTranslateCommand(iterator, frame_index, output_offset);
498  }
499  input_offset -= (parameter_count * kPointerSize);
500
501  // There are no translation commands for the caller's pc and fp, the
502  // context, and the function.  Synthesize their values and set them up
503  // explicitly.
504  //
505  // The caller's pc for the bottommost output frame is the same as in the
506  // input frame.  For all subsequent output frames, it can be read from the
507  // previous one.  This frame's pc can be computed from the non-optimized
508  // function code and AST id of the bailout.
509  output_offset -= kPointerSize;
510  input_offset -= kPointerSize;
511  intptr_t value;
512  if (is_bottommost) {
513    value = input_->GetFrameSlot(input_offset);
514  } else {
515    value = output_[frame_index - 1]->GetPc();
516  }
517  output_frame->SetFrameSlot(output_offset, value);
518  if (FLAG_trace_deopt) {
519    PrintF("    0x%08x: [top + %d] <- 0x%08x ; caller's pc\n",
520           top_address + output_offset, output_offset, value);
521  }
522
523  // The caller's frame pointer for the bottommost output frame is the same
524  // as in the input frame.  For all subsequent output frames, it can be
525  // read from the previous one.  Also compute and set this frame's frame
526  // pointer.
527  output_offset -= kPointerSize;
528  input_offset -= kPointerSize;
529  if (is_bottommost) {
530    value = input_->GetFrameSlot(input_offset);
531  } else {
532    value = output_[frame_index - 1]->GetFp();
533  }
534  output_frame->SetFrameSlot(output_offset, value);
535  intptr_t fp_value = top_address + output_offset;
536  ASSERT(!is_bottommost || input_->GetRegister(ebp.code()) == fp_value);
537  output_frame->SetFp(fp_value);
538  if (is_topmost) output_frame->SetRegister(ebp.code(), fp_value);
539  if (FLAG_trace_deopt) {
540    PrintF("    0x%08x: [top + %d] <- 0x%08x ; caller's fp\n",
541           fp_value, output_offset, value);
542  }
543
544  // For the bottommost output frame the context can be gotten from the input
545  // frame. For all subsequent output frames it can be gotten from the function
546  // so long as we don't inline functions that need local contexts.
547  output_offset -= kPointerSize;
548  input_offset -= kPointerSize;
549  if (is_bottommost) {
550    value = input_->GetFrameSlot(input_offset);
551  } else {
552    value = reinterpret_cast<uint32_t>(function->context());
553  }
554  output_frame->SetFrameSlot(output_offset, value);
555  if (is_topmost) output_frame->SetRegister(esi.code(), value);
556  if (FLAG_trace_deopt) {
557    PrintF("    0x%08x: [top + %d] <- 0x%08x ; context\n",
558           top_address + output_offset, output_offset, value);
559  }
560
561  // The function was mentioned explicitly in the BEGIN_FRAME.
562  output_offset -= kPointerSize;
563  input_offset -= kPointerSize;
564  value = reinterpret_cast<uint32_t>(function);
565  // The function for the bottommost output frame should also agree with the
566  // input frame.
567  ASSERT(!is_bottommost || input_->GetFrameSlot(input_offset) == value);
568  output_frame->SetFrameSlot(output_offset, value);
569  if (FLAG_trace_deopt) {
570    PrintF("    0x%08x: [top + %d] <- 0x%08x ; function\n",
571           top_address + output_offset, output_offset, value);
572  }
573
574  // Translate the rest of the frame.
575  for (unsigned i = 0; i < height; ++i) {
576    output_offset -= kPointerSize;
577    DoTranslateCommand(iterator, frame_index, output_offset);
578  }
579  ASSERT(0 == output_offset);
580
581  // Compute this frame's PC, state, and continuation.
582  Code* non_optimized_code = function->shared()->code();
583  FixedArray* raw_data = non_optimized_code->deoptimization_data();
584  DeoptimizationOutputData* data = DeoptimizationOutputData::cast(raw_data);
585  Address start = non_optimized_code->instruction_start();
586  unsigned pc_and_state = GetOutputInfo(data, node_id, function->shared());
587  unsigned pc_offset = FullCodeGenerator::PcField::decode(pc_and_state);
588  uint32_t pc_value = reinterpret_cast<uint32_t>(start + pc_offset);
589  output_frame->SetPc(pc_value);
590
591  FullCodeGenerator::State state =
592      FullCodeGenerator::StateField::decode(pc_and_state);
593  output_frame->SetState(Smi::FromInt(state));
594
595  // Set the continuation for the topmost frame.
596  if (is_topmost && bailout_type_ != DEBUGGER) {
597    Builtins* builtins = isolate_->builtins();
598    Code* continuation = (bailout_type_ == EAGER)
599        ? builtins->builtin(Builtins::kNotifyDeoptimized)
600        : builtins->builtin(Builtins::kNotifyLazyDeoptimized);
601    output_frame->SetContinuation(
602        reinterpret_cast<uint32_t>(continuation->entry()));
603  }
604}
605
606
607void Deoptimizer::FillInputFrame(Address tos, JavaScriptFrame* frame) {
608  // Set the register values. The values are not important as there are no
609  // callee saved registers in JavaScript frames, so all registers are
610  // spilled. Registers ebp and esp are set to the correct values though.
611
612  for (int i = 0; i < Register::kNumRegisters; i++) {
613    input_->SetRegister(i, i * 4);
614  }
615  input_->SetRegister(esp.code(), reinterpret_cast<intptr_t>(frame->sp()));
616  input_->SetRegister(ebp.code(), reinterpret_cast<intptr_t>(frame->fp()));
617  for (int i = 0; i < DoubleRegister::kNumAllocatableRegisters; i++) {
618    input_->SetDoubleRegister(i, 0.0);
619  }
620
621  // Fill the frame content from the actual data on the frame.
622  for (unsigned i = 0; i < input_->GetFrameSize(); i += kPointerSize) {
623    input_->SetFrameSlot(i, Memory::uint32_at(tos + i));
624  }
625}
626
627
628#define __ masm()->
629
630void Deoptimizer::EntryGenerator::Generate() {
631  GeneratePrologue();
632  CpuFeatures::Scope scope(SSE2);
633
634  Isolate* isolate = masm()->isolate();
635
636  // Save all general purpose registers before messing with them.
637  const int kNumberOfRegisters = Register::kNumRegisters;
638
639  const int kDoubleRegsSize = kDoubleSize *
640                              XMMRegister::kNumAllocatableRegisters;
641  __ sub(Operand(esp), Immediate(kDoubleRegsSize));
642  for (int i = 0; i < XMMRegister::kNumAllocatableRegisters; ++i) {
643    XMMRegister xmm_reg = XMMRegister::FromAllocationIndex(i);
644    int offset = i * kDoubleSize;
645    __ movdbl(Operand(esp, offset), xmm_reg);
646  }
647
648  __ pushad();
649
650  const int kSavedRegistersAreaSize = kNumberOfRegisters * kPointerSize +
651                                      kDoubleRegsSize;
652
653  // Get the bailout id from the stack.
654  __ mov(ebx, Operand(esp, kSavedRegistersAreaSize));
655
656  // Get the address of the location in the code object if possible
657  // and compute the fp-to-sp delta in register edx.
658  if (type() == EAGER) {
659    __ Set(ecx, Immediate(0));
660    __ lea(edx, Operand(esp, kSavedRegistersAreaSize + 1 * kPointerSize));
661  } else {
662    __ mov(ecx, Operand(esp, kSavedRegistersAreaSize + 1 * kPointerSize));
663    __ lea(edx, Operand(esp, kSavedRegistersAreaSize + 2 * kPointerSize));
664  }
665  __ sub(edx, Operand(ebp));
666  __ neg(edx);
667
668  // Allocate a new deoptimizer object.
669  __ PrepareCallCFunction(6, eax);
670  __ mov(eax, Operand(ebp, JavaScriptFrameConstants::kFunctionOffset));
671  __ mov(Operand(esp, 0 * kPointerSize), eax);  // Function.
672  __ mov(Operand(esp, 1 * kPointerSize), Immediate(type()));  // Bailout type.
673  __ mov(Operand(esp, 2 * kPointerSize), ebx);  // Bailout id.
674  __ mov(Operand(esp, 3 * kPointerSize), ecx);  // Code address or 0.
675  __ mov(Operand(esp, 4 * kPointerSize), edx);  // Fp-to-sp delta.
676  __ mov(Operand(esp, 5 * kPointerSize),
677         Immediate(ExternalReference::isolate_address()));
678  __ CallCFunction(ExternalReference::new_deoptimizer_function(isolate), 6);
679
680  // Preserve deoptimizer object in register eax and get the input
681  // frame descriptor pointer.
682  __ mov(ebx, Operand(eax, Deoptimizer::input_offset()));
683
684  // Fill in the input registers.
685  for (int i = kNumberOfRegisters - 1; i >= 0; i--) {
686    int offset = (i * kPointerSize) + FrameDescription::registers_offset();
687    __ pop(Operand(ebx, offset));
688  }
689
690  // Fill in the double input registers.
691  int double_regs_offset = FrameDescription::double_registers_offset();
692  for (int i = 0; i < XMMRegister::kNumAllocatableRegisters; ++i) {
693    int dst_offset = i * kDoubleSize + double_regs_offset;
694    int src_offset = i * kDoubleSize;
695    __ movdbl(xmm0, Operand(esp, src_offset));
696    __ movdbl(Operand(ebx, dst_offset), xmm0);
697  }
698
699  // Remove the bailout id and the double registers from the stack.
700  if (type() == EAGER) {
701    __ add(Operand(esp), Immediate(kDoubleRegsSize + kPointerSize));
702  } else {
703    __ add(Operand(esp), Immediate(kDoubleRegsSize + 2 * kPointerSize));
704  }
705
706  // Compute a pointer to the unwinding limit in register ecx; that is
707  // the first stack slot not part of the input frame.
708  __ mov(ecx, Operand(ebx, FrameDescription::frame_size_offset()));
709  __ add(ecx, Operand(esp));
710
711  // Unwind the stack down to - but not including - the unwinding
712  // limit and copy the contents of the activation frame to the input
713  // frame description.
714  __ lea(edx, Operand(ebx, FrameDescription::frame_content_offset()));
715  Label pop_loop;
716  __ bind(&pop_loop);
717  __ pop(Operand(edx, 0));
718  __ add(Operand(edx), Immediate(sizeof(uint32_t)));
719  __ cmp(ecx, Operand(esp));
720  __ j(not_equal, &pop_loop);
721
722  // Compute the output frame in the deoptimizer.
723  __ push(eax);
724  __ PrepareCallCFunction(1, ebx);
725  __ mov(Operand(esp, 0 * kPointerSize), eax);
726  __ CallCFunction(
727      ExternalReference::compute_output_frames_function(isolate), 1);
728  __ pop(eax);
729
730  // Replace the current frame with the output frames.
731  Label outer_push_loop, inner_push_loop;
732  // Outer loop state: eax = current FrameDescription**, edx = one past the
733  // last FrameDescription**.
734  __ mov(edx, Operand(eax, Deoptimizer::output_count_offset()));
735  __ mov(eax, Operand(eax, Deoptimizer::output_offset()));
736  __ lea(edx, Operand(eax, edx, times_4, 0));
737  __ bind(&outer_push_loop);
738  // Inner loop state: ebx = current FrameDescription*, ecx = loop index.
739  __ mov(ebx, Operand(eax, 0));
740  __ mov(ecx, Operand(ebx, FrameDescription::frame_size_offset()));
741  __ bind(&inner_push_loop);
742  __ sub(Operand(ecx), Immediate(sizeof(uint32_t)));
743  __ push(Operand(ebx, ecx, times_1, FrameDescription::frame_content_offset()));
744  __ test(ecx, Operand(ecx));
745  __ j(not_zero, &inner_push_loop);
746  __ add(Operand(eax), Immediate(kPointerSize));
747  __ cmp(eax, Operand(edx));
748  __ j(below, &outer_push_loop);
749
750  // In case of OSR, we have to restore the XMM registers.
751  if (type() == OSR) {
752    for (int i = 0; i < XMMRegister::kNumAllocatableRegisters; ++i) {
753      XMMRegister xmm_reg = XMMRegister::FromAllocationIndex(i);
754      int src_offset = i * kDoubleSize + double_regs_offset;
755      __ movdbl(xmm_reg, Operand(ebx, src_offset));
756    }
757  }
758
759  // Push state, pc, and continuation from the last output frame.
760  if (type() != OSR) {
761    __ push(Operand(ebx, FrameDescription::state_offset()));
762  }
763  __ push(Operand(ebx, FrameDescription::pc_offset()));
764  __ push(Operand(ebx, FrameDescription::continuation_offset()));
765
766
767  // Push the registers from the last output frame.
768  for (int i = 0; i < kNumberOfRegisters; i++) {
769    int offset = (i * kPointerSize) + FrameDescription::registers_offset();
770    __ push(Operand(ebx, offset));
771  }
772
773  // Restore the registers from the stack.
774  __ popad();
775
776  // Return to the continuation point.
777  __ ret(0);
778}
779
780
781void Deoptimizer::TableEntryGenerator::GeneratePrologue() {
782  // Create a sequence of deoptimization entries.
783  Label done;
784  for (int i = 0; i < count(); i++) {
785    int start = masm()->pc_offset();
786    USE(start);
787    __ push_imm32(i);
788    __ jmp(&done);
789    ASSERT(masm()->pc_offset() - start == table_entry_size_);
790  }
791  __ bind(&done);
792}
793
794#undef __
795
796
797} }  // namespace v8::internal
798
799#endif  // V8_TARGET_ARCH_IA32
800