deoptimizer.cc 148 KB
Newer Older
1
// Copyright 2013 the V8 project authors. All rights reserved.
2 3
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
4

5
#include "src/deoptimizer.h"
6

7 8
#include <memory>

9
#include "src/accessors.h"
10
#include "src/assembler-inl.h"
11
#include "src/ast/prettyprinter.h"
12
#include "src/callable.h"
13
#include "src/counters.h"
14
#include "src/disasm.h"
15
#include "src/frames-inl.h"
16
#include "src/global-handles.h"
17
#include "src/heap/heap-inl.h"
18
#include "src/interpreter/interpreter.h"
19
#include "src/log.h"
20
#include "src/macro-assembler.h"
21
#include "src/objects/debug-objects-inl.h"
22
#include "src/objects/heap-number-inl.h"
23
#include "src/objects/smi.h"
24
#include "src/register-configuration.h"
25
#include "src/tracing/trace-event.h"
26
#include "src/v8.h"
27
#include "src/v8threads.h"
28

29 30
// Has to be the last include (doesn't have include guards)
#include "src/objects/object-macros.h"
31 32 33 34

namespace v8 {
namespace internal {

35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
// {FrameWriter} offers a stack writer abstraction for writing
// FrameDescriptions. The main service the class provides is managing
// {top_offset_}, i.e. the offset of the next slot to write to.
class FrameWriter {
 public:
  static const int NO_INPUT_INDEX = -1;
  FrameWriter(Deoptimizer* deoptimizer, FrameDescription* frame,
              CodeTracer::Scope* trace_scope)
      : deoptimizer_(deoptimizer),
        frame_(frame),
        trace_scope_(trace_scope),
        top_offset_(frame->GetFrameSize()) {}

  void PushRawValue(intptr_t value, const char* debug_hint) {
    PushValue(value);

    if (trace_scope_ != nullptr) {
      DebugPrintOutputValue(value, debug_hint);
    }
  }

56 57
  void PushRawObject(Object obj, const char* debug_hint) {
    intptr_t value = obj->ptr();
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
    PushValue(value);
    if (trace_scope_ != nullptr) {
      DebugPrintOutputObject(obj, top_offset_, debug_hint);
    }
  }

  void PushCallerPc(intptr_t pc) {
    top_offset_ -= kPCOnStackSize;
    frame_->SetCallerPc(top_offset_, pc);
    DebugPrintOutputValue(pc, "caller's pc\n");
  }

  void PushCallerFp(intptr_t fp) {
    top_offset_ -= kFPOnStackSize;
    frame_->SetCallerFp(top_offset_, fp);
    DebugPrintOutputValue(fp, "caller's fp\n");
  }

  void PushCallerConstantPool(intptr_t cp) {
77
    top_offset_ -= kSystemPointerSize;
78 79 80 81 82 83
    frame_->SetCallerConstantPool(top_offset_, cp);
    DebugPrintOutputValue(cp, "caller's constant_pool\n");
  }

  void PushTranslatedValue(const TranslatedFrame::iterator& iterator,
                           const char* debug_hint = "") {
84
    Object obj = iterator->GetRawValue();
85 86 87

    PushRawObject(obj, debug_hint);

88 89 90 91
    if (trace_scope_) {
      PrintF(trace_scope_->file(), " (input #%d)\n", iterator.input_index());
    }

92 93
    deoptimizer_->QueueValueForMaterialization(output_address(top_offset_), obj,
                                               iterator);
94 95 96 97 98 99 100
  }

  unsigned top_offset() const { return top_offset_; }

 private:
  void PushValue(intptr_t value) {
    CHECK_GE(top_offset_, 0);
101
    top_offset_ -= kSystemPointerSize;
102 103 104 105 106 107 108 109 110 111 112 113
    frame_->SetFrameSlot(top_offset_, value);
  }

  Address output_address(unsigned output_offset) {
    Address output_address =
        static_cast<Address>(frame_->GetTop()) + output_offset;
    return output_address;
  }

  void DebugPrintOutputValue(intptr_t value, const char* debug_hint = "") {
    if (trace_scope_ != nullptr) {
      PrintF(trace_scope_->file(),
114
             "    " V8PRIxPTR_FMT ": [top + %3d] <- " V8PRIxPTR_FMT " ;  %s",
115 116 117 118
             output_address(top_offset_), top_offset_, value, debug_hint);
    }
  }

119
  void DebugPrintOutputObject(Object obj, unsigned output_offset,
120 121
                              const char* debug_hint = "") {
    if (trace_scope_ != nullptr) {
122
      PrintF(trace_scope_->file(), "    " V8PRIxPTR_FMT ": [top + %3d] <- ",
123 124
             output_address(output_offset), output_offset);
      if (obj->IsSmi()) {
125
        PrintF(V8PRIxPTR_FMT " <Smi %d>", obj->ptr(), Smi::cast(obj)->value());
126 127 128 129 130 131 132 133 134 135 136 137 138
      } else {
        obj->ShortPrint(trace_scope_->file());
      }
      PrintF(trace_scope_->file(), " ;  %s", debug_hint);
    }
  }

  Deoptimizer* deoptimizer_;
  FrameDescription* frame_;
  CodeTracer::Scope* trace_scope_;
  unsigned top_offset_;
};

139
DeoptimizerData::DeoptimizerData(Heap* heap) : heap_(heap), current_(nullptr) {
140 141
  Code* start = &deopt_entry_code_[0];
  Code* end = &deopt_entry_code_[DeoptimizerData::kLastDeoptimizeKind + 1];
142
  heap_->RegisterStrongRoots(FullObjectSlot(start), FullObjectSlot(end));
143
}
144 145


146
DeoptimizerData::~DeoptimizerData() {
147
  Code* start = &deopt_entry_code_[0];
148
  heap_->UnregisterStrongRoots(FullObjectSlot(start));
149 150
}

151
Code DeoptimizerData::deopt_entry_code(DeoptimizeKind kind) {
152 153 154
  return deopt_entry_code_[static_cast<int>(kind)];
}

155
void DeoptimizerData::set_deopt_entry_code(DeoptimizeKind kind, Code code) {
156 157
  deopt_entry_code_[static_cast<int>(kind)] = code;
}
158

159
Code Deoptimizer::FindDeoptimizingCode(Address addr) {
160 161
  if (function_->IsHeapObject()) {
    // Search all deoptimizing code in the native context of the function.
162
    Isolate* isolate = isolate_;
163
    Context native_context = function_->context()->native_context();
164
    Object element = native_context->DeoptimizedCodeListHead();
165
    while (!element->IsUndefined(isolate)) {
166
      Code code = Code::cast(element);
167
      CHECK(code->kind() == Code::OPTIMIZED_FUNCTION);
168 169
      if (code->contains(addr)) return code;
      element = code->next_code_link();
170 171
    }
  }
172
  return Code();
173 174 175
}


176 177
// We rely on this function not causing a GC.  It is called from generated code
// without having a real stack frame in place.
178
Deoptimizer* Deoptimizer::New(Address raw_function, DeoptimizeKind kind,
179 180
                              unsigned bailout_id, Address from,
                              int fp_to_sp_delta, Isolate* isolate) {
181
  JSFunction function = JSFunction::cast(Object(raw_function));
182
  Deoptimizer* deoptimizer = new Deoptimizer(isolate, function, kind,
183
                                             bailout_id, from, fp_to_sp_delta);
184
  CHECK_NULL(isolate->deoptimizer_data()->current_);
185
  isolate->deoptimizer_data()->current_ = deoptimizer;
186 187 188
  return deoptimizer;
}

189 190
Deoptimizer* Deoptimizer::Grab(Isolate* isolate) {
  Deoptimizer* result = isolate->deoptimizer_data()->current_;
191
  CHECK_NOT_NULL(result);
192
  result->DeleteFrameDescriptions();
193
  isolate->deoptimizer_data()->current_ = nullptr;
194 195 196
  return result;
}

197 198
DeoptimizedFrameInfo* Deoptimizer::DebuggerInspectableFrame(
    JavaScriptFrame* frame,
199
    int jsframe_index,
200
    Isolate* isolate) {
201
  CHECK(frame->is_optimized());
202

203
  TranslatedState translated_values(frame);
204
  translated_values.Prepare(frame->fp());
205 206 207 208 209

  TranslatedState::iterator frame_it = translated_values.end();
  int counter = jsframe_index;
  for (auto it = translated_values.begin(); it != translated_values.end();
       it++) {
210
    if (it->kind() == TranslatedFrame::kInterpretedFunction ||
211 212 213
        it->kind() == TranslatedFrame::kJavaScriptBuiltinContinuation ||
        it->kind() ==
            TranslatedFrame::kJavaScriptBuiltinContinuationWithCatch) {
214 215 216 217 218 219 220 221
      if (counter == 0) {
        frame_it = it;
        break;
      }
      counter--;
    }
  }
  CHECK(frame_it != translated_values.end());
222 223 224
  // We only include kJavaScriptBuiltinContinuation frames above to get the
  // counting right.
  CHECK_EQ(frame_it->kind(), TranslatedFrame::kInterpretedFunction);
225

226 227
  DeoptimizedFrameInfo* info =
      new DeoptimizedFrameInfo(&translated_values, frame_it, isolate);
228 229 230 231

  return info;
}

232 233 234
namespace {
class ActivationsFinder : public ThreadVisitor {
 public:
235
  explicit ActivationsFinder(std::set<Code>* codes, Code topmost_optimized_code,
236 237 238 239 240 241 242 243 244 245 246
                             bool safe_to_deopt_topmost_optimized_code)
      : codes_(codes) {
#ifdef DEBUG
    topmost_ = topmost_optimized_code;
    safe_to_deopt_ = safe_to_deopt_topmost_optimized_code;
#endif
  }

  // Find the frames with activations of codes marked for deoptimization, search
  // for the trampoline to the deoptimizer call respective to each code, and use
  // it to replace the current pc on the stack.
247
  void VisitThread(Isolate* isolate, ThreadLocalTop* top) override {
248 249
    for (StackFrameIterator it(isolate, top); !it.done(); it.Advance()) {
      if (it.frame()->type() == StackFrame::OPTIMIZED) {
250
        Code code = it.frame()->LookupCode();
251 252 253 254 255 256 257 258
        if (code->kind() == Code::OPTIMIZED_FUNCTION &&
            code->marked_for_deoptimization()) {
          codes_->erase(code);
          // Obtain the trampoline to the deoptimizer call.
          SafepointEntry safepoint = code->GetSafepointEntry(it.frame()->pc());
          int trampoline_pc = safepoint.trampoline_pc();
          DCHECK_IMPLIES(code == topmost_, safe_to_deopt_);
          // Replace the current pc on the stack with the trampoline.
259
          it.frame()->set_pc(code->raw_instruction_start() + trampoline_pc);
260 261 262 263 264 265
        }
      }
    }
  }

 private:
266
  std::set<Code>* codes_;
267 268

#ifdef DEBUG
269
  Code topmost_;
270 271 272 273 274
  bool safe_to_deopt_;
#endif
};
}  // namespace

275
// Move marked code from the optimized code list to the deoptimized code list,
276
// and replace pc on the stack for codes marked for deoptimization.
277
void Deoptimizer::DeoptimizeMarkedCodeForContext(Context context) {
278
  DisallowHeapAllocation no_allocation;
279

280
  Isolate* isolate = context->GetIsolate();
281
  Code topmost_optimized_code;
282
  bool safe_to_deopt_topmost_optimized_code = false;
283
#ifdef DEBUG
284 285 286 287 288 289 290
  // Make sure all activations of optimized code can deopt at their current PC.
  // The topmost optimized code has special handling because it cannot be
  // deoptimized due to weak object dependency.
  for (StackFrameIterator it(isolate, isolate->thread_local_top());
       !it.done(); it.Advance()) {
    StackFrame::Type type = it.frame()->type();
    if (type == StackFrame::OPTIMIZED) {
291
      Code code = it.frame()->LookupCode();
292
      JSFunction function =
293
          static_cast<OptimizedFrame*>(it.frame())->function();
294 295 296 297
      if (FLAG_trace_deopt) {
        CodeTracer::Scope scope(isolate->GetCodeTracer());
        PrintF(scope.file(), "[deoptimizer found activation of function: ");
        function->PrintName(scope.file());
298
        PrintF(scope.file(), " / %" V8PRIxPTR "]\n", function.ptr());
299 300
      }
      SafepointEntry safepoint = code->GetSafepointEntry(it.frame()->pc());
Juliana Franco's avatar
Juliana Franco committed
301

302
      // Turbofan deopt is checked when we are patching addresses on stack.
303
      bool safe_if_deopt_triggered = safepoint.has_deoptimization_index();
304
      bool is_builtin_code = code->kind() == Code::BUILTIN;
305
      DCHECK(topmost_optimized_code.is_null() || safe_if_deopt_triggered ||
306
             is_builtin_code);
307
      if (topmost_optimized_code.is_null()) {
308
        topmost_optimized_code = code;
309
        safe_to_deopt_topmost_optimized_code = safe_if_deopt_triggered;
310 311 312 313 314
      }
    }
  }
#endif

315 316
  // We will use this set to mark those Code objects that are marked for
  // deoptimization and have not been found in stack frames.
317
  std::set<Code> codes;
318

319
  // Move marked code from the optimized code list to the deoptimized code list.
320
  // Walk over all optimized code objects in this native context.
321
  Code prev;
322
  Object element = context->OptimizedCodeListHead();
323
  while (!element->IsUndefined(isolate)) {
324
    Code code = Code::cast(element);
325
    CHECK_EQ(code->kind(), Code::OPTIMIZED_FUNCTION);
326
    Object next = code->next_code_link();
327

328
    if (code->marked_for_deoptimization()) {
329 330
      codes.insert(code);

331
      if (!prev.is_null()) {
332 333 334 335 336 337
        // Skip this code in the optimized code list.
        prev->set_next_code_link(next);
      } else {
        // There was no previous node, the next node is the new head.
        context->SetOptimizedCodeListHead(next);
      }
338

339 340 341 342 343 344 345 346
      // Move the code to the _deoptimized_ code list.
      code->set_next_code_link(context->DeoptimizedCodeListHead());
      context->SetDeoptimizedCodeListHead(code);
    } else {
      // Not marked; preserve this element.
      prev = code;
    }
    element = next;
347 348
  }

349 350 351 352 353 354 355 356
  ActivationsFinder visitor(&codes, topmost_optimized_code,
                            safe_to_deopt_topmost_optimized_code);
  // Iterate over the stack of this thread.
  visitor.VisitThread(isolate, isolate->thread_local_top());
  // In addition to iterate over the stack of this thread, we also
  // need to consider all the other threads as they may also use
  // the code currently beings deoptimized.
  isolate->thread_manager()->IterateArchivedThreads(&visitor);
357

358
  // If there's no activation of a code in any stack then we can remove its
359 360
  // deoptimization data. We do this to ensure that code objects that are
  // unlinked don't transitively keep objects alive unnecessarily.
361
  for (Code code : codes) {
362
    isolate->heap()->InvalidateCodeDeoptimizationData(code);
363
  }
364 365
}

366

367
void Deoptimizer::DeoptimizeAll(Isolate* isolate) {
368
  RuntimeCallTimerScope runtimeTimer(isolate,
369
                                     RuntimeCallCounterId::kDeoptimizeCode);
370
  TimerEventScope<TimerEventDeoptimizeCode> timer(isolate);
371
  TRACE_EVENT0("v8", "V8.DeoptimizeCode");
372
  if (FLAG_trace_deopt) {
373 374
    CodeTracer::Scope scope(isolate->GetCodeTracer());
    PrintF(scope.file(), "[deoptimize all code in all contexts]\n");
375
  }
376
  isolate->AbortConcurrentOptimization(BlockingBehavior::kBlock);
377
  DisallowHeapAllocation no_allocation;
378
  // For all contexts, mark all code, then deoptimize.
379
  Object context = isolate->heap()->native_contexts_list();
380
  while (!context->IsUndefined(isolate)) {
381
    Context native_context = Context::cast(context);
382 383
    MarkAllCodeForContext(native_context);
    DeoptimizeMarkedCodeForContext(native_context);
384
    context = native_context->next_context_link();
385 386 387 388
  }
}


389
void Deoptimizer::DeoptimizeMarkedCode(Isolate* isolate) {
390
  RuntimeCallTimerScope runtimeTimer(isolate,
391
                                     RuntimeCallCounterId::kDeoptimizeCode);
392
  TimerEventScope<TimerEventDeoptimizeCode> timer(isolate);
393
  TRACE_EVENT0("v8", "V8.DeoptimizeCode");
394
  if (FLAG_trace_deopt) {
395 396
    CodeTracer::Scope scope(isolate->GetCodeTracer());
    PrintF(scope.file(), "[deoptimize marked code in all contexts]\n");
397
  }
398
  DisallowHeapAllocation no_allocation;
399
  // For all contexts, deoptimize code already marked.
400
  Object context = isolate->heap()->native_contexts_list();
401
  while (!context->IsUndefined(isolate)) {
402
    Context native_context = Context::cast(context);
403
    DeoptimizeMarkedCodeForContext(native_context);
404
    context = native_context->next_context_link();
405 406 407
  }
}

408
void Deoptimizer::MarkAllCodeForContext(Context context) {
409
  Object element = context->OptimizedCodeListHead();
410 411
  Isolate* isolate = context->GetIsolate();
  while (!element->IsUndefined(isolate)) {
412
    Code code = Code::cast(element);
413
    CHECK_EQ(code->kind(), Code::OPTIMIZED_FUNCTION);
414 415 416
    code->set_marked_for_deoptimization(true);
    element = code->next_code_link();
  }
417 418
}

419
void Deoptimizer::DeoptimizeFunction(JSFunction function, Code code) {
420 421
  Isolate* isolate = function->GetIsolate();
  RuntimeCallTimerScope runtimeTimer(isolate,
422
                                     RuntimeCallCounterId::kDeoptimizeCode);
423
  TimerEventScope<TimerEventDeoptimizeCode> timer(isolate);
424
  TRACE_EVENT0("v8", "V8.DeoptimizeCode");
425
  function->ResetIfBytecodeFlushed();
426
  if (code.is_null()) code = function->code();
427

428 429 430 431 432
  if (code->kind() == Code::OPTIMIZED_FUNCTION) {
    // Mark the code for deoptimization and unlink any functions that also
    // refer to that code. The code cannot be shared across native contexts,
    // so we only need to search one.
    code->set_marked_for_deoptimization(true);
433 434 435 436 437 438 439 440
    // The code in the function's optimized code feedback vector slot might
    // be different from the code on the function - evict it if necessary.
    function->feedback_vector()->EvictOptimizedCodeMarkedForDeoptimization(
        function->shared(), "unlinking code marked for deopt");
    if (!code->deopt_already_counted()) {
      function->feedback_vector()->increment_deopt_count();
      code->set_deopt_already_counted(true);
    }
441
    DeoptimizeMarkedCodeForContext(function->context()->native_context());
442 443 444
  }
}

445
void Deoptimizer::ComputeOutputFrames(Deoptimizer* deoptimizer) {
446 447 448
  deoptimizer->DoComputeOutputFrames();
}

449 450 451 452 453 454 455 456
const char* Deoptimizer::MessageFor(DeoptimizeKind kind) {
  switch (kind) {
    case DeoptimizeKind::kEager:
      return "eager";
    case DeoptimizeKind::kSoft:
      return "soft";
    case DeoptimizeKind::kLazy:
      return "lazy";
457
  }
458
  FATAL("Unsupported deopt kind");
459
  return nullptr;
460 461
}

462
Deoptimizer::Deoptimizer(Isolate* isolate, JSFunction function,
463
                         DeoptimizeKind kind, unsigned bailout_id, Address from,
464
                         int fp_to_sp_delta)
465 466
    : isolate_(isolate),
      function_(function),
467
      bailout_id_(bailout_id),
468
      deopt_kind_(kind),
469 470
      from_(from),
      fp_to_sp_delta_(fp_to_sp_delta),
471 472 473
      deoptimizing_throw_(false),
      catch_handler_data_(-1),
      catch_handler_pc_offset_(-1),
474
      input_(nullptr),
475
      output_count_(0),
476
      jsframe_count_(0),
477
      output_(nullptr),
478 479 480 481 482 483
      caller_frame_top_(0),
      caller_fp_(0),
      caller_pc_(0),
      caller_constant_pool_(0),
      input_frame_context_(0),
      stack_fp_(0),
484
      trace_scope_(nullptr) {
485 486 487 488 489
  if (isolate->deoptimizer_lazy_throw()) {
    isolate->set_deoptimizer_lazy_throw(false);
    deoptimizing_throw_ = true;
  }

490
  DCHECK_NE(from, kNullAddress);
491
  compiled_code_ = FindOptimizedCode();
492
  DCHECK(!compiled_code_.is_null());
493

494
  DCHECK(function->IsJSFunction());
495 496 497
  trace_scope_ = FLAG_trace_deopt
                     ? new CodeTracer::Scope(isolate->GetCodeTracer())
                     : nullptr;
498
#ifdef DEBUG
499
  DCHECK(AllowHeapAllocation::IsAllowed());
500 501
  disallow_heap_allocation_ = new DisallowHeapAllocation();
#endif  // DEBUG
502 503
  if (compiled_code_->kind() != Code::OPTIMIZED_FUNCTION ||
      !compiled_code_->deopt_already_counted()) {
504 505 506 507
    // If the function is optimized, and we haven't counted that deopt yet, then
    // increment the function's deopt count so that we can avoid optimising
    // functions that deopt too often.

508
    if (deopt_kind_ == DeoptimizeKind::kSoft) {
509 510 511
      // Soft deopts shouldn't count against the overall deoptimization count
      // that can eventually lead to disabling optimization for a function.
      isolate->counters()->soft_deopts_executed()->Increment();
512
    } else if (!function.is_null()) {
513
      function->feedback_vector()->increment_deopt_count();
514 515
    }
  }
516
  if (compiled_code_->kind() == Code::OPTIMIZED_FUNCTION) {
517
    compiled_code_->set_deopt_already_counted(true);
518
    PROFILE(isolate_,
519
            CodeDeoptEvent(compiled_code_, kind, from_, fp_to_sp_delta_));
520
  }
521
  unsigned size = ComputeInputFrameSize();
522
  int parameter_count =
523
      function->shared()->internal_formal_parameter_count() + 1;
524
  input_ = new (size) FrameDescription(size, parameter_count);
525 526
}

527 528 529 530
Code Deoptimizer::FindOptimizedCode() {
  Code compiled_code = FindDeoptimizingCode(from_);
  return !compiled_code.is_null() ? compiled_code
                                  : isolate_->FindCodeObject(from_);
531 532 533 534
}


void Deoptimizer::PrintFunctionName() {
535
  if (function_->IsHeapObject() && function_->IsJSFunction()) {
536
    function_->ShortPrint(trace_scope_->file());
537
  } else {
538 539
    PrintF(trace_scope_->file(),
           "%s", Code::Kind2String(compiled_code_->kind()));
540 541 542
  }
}

543
Handle<JSFunction> Deoptimizer::function() const {
544
  return Handle<JSFunction>(function_, isolate());
545 546
}
Handle<Code> Deoptimizer::compiled_code() const {
547
  return Handle<Code>(compiled_code_, isolate());
548
}
549

550
Deoptimizer::~Deoptimizer() {
551
  DCHECK(input_ == nullptr && output_ == nullptr);
552
  DCHECK_NULL(disallow_heap_allocation_);
553
  delete trace_scope_;
554 555 556 557 558 559 560 561 562
}


void Deoptimizer::DeleteFrameDescriptions() {
  delete input_;
  for (int i = 0; i < output_count_; ++i) {
    if (output_[i] != input_) delete output_[i];
  }
  delete[] output_;
563 564
  input_ = nullptr;
  output_ = nullptr;
565
#ifdef DEBUG
566
  DCHECK(!AllowHeapAllocation::IsAllowed());
567
  DCHECK_NOT_NULL(disallow_heap_allocation_);
568
  delete disallow_heap_allocation_;
569
  disallow_heap_allocation_ = nullptr;
570
#endif  // DEBUG
571 572
}

573
Address Deoptimizer::GetDeoptimizationEntry(Isolate* isolate,
574
                                            DeoptimizeKind kind) {
575
  DeoptimizerData* data = isolate->deoptimizer_data();
576
  CHECK_LE(kind, DeoptimizerData::kLastDeoptimizeKind);
577
  CHECK(!data->deopt_entry_code(kind).is_null());
578
  return data->deopt_entry_code(kind)->raw_instruction_start();
579 580
}

581 582
bool Deoptimizer::IsDeoptimizationEntry(Isolate* isolate, Address addr,
                                        DeoptimizeKind type) {
583 584
  DeoptimizerData* data = isolate->deoptimizer_data();
  CHECK_LE(type, DeoptimizerData::kLastDeoptimizeKind);
585 586
  Code code = data->deopt_entry_code(type);
  if (code.is_null()) return false;
587
  return addr == code->raw_instruction_start();
588 589 590 591
}

bool Deoptimizer::IsDeoptimizationEntry(Isolate* isolate, Address addr,
                                        DeoptimizeKind* type) {
592
  if (IsDeoptimizationEntry(isolate, addr, DeoptimizeKind::kEager)) {
593 594 595
    *type = DeoptimizeKind::kEager;
    return true;
  }
596
  if (IsDeoptimizationEntry(isolate, addr, DeoptimizeKind::kSoft)) {
597 598 599
    *type = DeoptimizeKind::kSoft;
    return true;
  }
600
  if (IsDeoptimizationEntry(isolate, addr, DeoptimizeKind::kLazy)) {
601 602 603 604 605 606
    *type = DeoptimizeKind::kLazy;
    return true;
  }
  return false;
}

607
int Deoptimizer::GetDeoptimizedCodeCount(Isolate* isolate) {
608
  int length = 0;
609
  // Count all entries in the deoptimizing code list of every context.
610
  Object context = isolate->heap()->native_contexts_list();
611
  while (!context->IsUndefined(isolate)) {
612
    Context native_context = Context::cast(context);
613
    Object element = native_context->DeoptimizedCodeListHead();
614
    while (!element->IsUndefined(isolate)) {
615
      Code code = Code::cast(element);
616
      DCHECK(code->kind() == Code::OPTIMIZED_FUNCTION);
617 618 619
      if (!code->marked_for_deoptimization()) {
        length++;
      }
620 621
      element = code->next_code_link();
    }
622
    context = Context::cast(context)->next_context_link();
623 624 625 626
  }
  return length;
}

627 628 629 630 631 632
namespace {

int LookupCatchHandler(TranslatedFrame* translated_frame, int* data_out) {
  switch (translated_frame->kind()) {
    case TranslatedFrame::kInterpretedFunction: {
      int bytecode_offset = translated_frame->node_id().ToInt();
633 634
      HandlerTable table(
          translated_frame->raw_shared_info()->GetBytecodeArray());
635
      return table.LookupRange(bytecode_offset, data_out, nullptr);
636
    }
637 638 639
    case TranslatedFrame::kJavaScriptBuiltinContinuationWithCatch: {
      return 0;
    }
640 641 642 643 644 645
    default:
      break;
  }
  return -1;
}

646 647 648 649
bool ShouldPadArguments(int arg_count) {
  return kPadArguments && (arg_count % 2 != 0);
}

650
}  // namespace
651

652 653
// We rely on this function not causing a GC.  It is called from generated code
// without having a real stack frame in place.
654
void Deoptimizer::DoComputeOutputFrames() {
655
  base::ElapsedTimer timer;
656 657 658

  // Determine basic deoptimization information.  The optimized frame is
  // described by the input data.
659
  DeoptimizationData input_data =
660
      DeoptimizationData::cast(compiled_code_->deoptimization_data());
661

662 663 664 665 666 667 668 669 670 671
  {
    // Read caller's PC, caller's FP and caller's constant pool values
    // from input frame. Compute caller's frame top address.

    Register fp_reg = JavaScriptFrame::fp_register();
    stack_fp_ = input_->GetRegister(fp_reg.code());

    caller_frame_top_ = stack_fp_ + ComputeInputFrameAboveFpFixedSize();

    Address fp_address = input_->GetFramePointerAddress();
672
    caller_fp_ = Memory<intptr_t>(fp_address);
673
    caller_pc_ =
674 675
        Memory<intptr_t>(fp_address + CommonFrameConstants::kCallerPCOffset);
    input_frame_context_ = Memory<intptr_t>(
676 677 678
        fp_address + CommonFrameConstants::kContextOrFrameTypeOffset);

    if (FLAG_enable_embedded_constant_pool) {
679
      caller_constant_pool_ = Memory<intptr_t>(
680 681 682 683
          fp_address + CommonFrameConstants::kConstantPoolOffset);
    }
  }

684
  if (trace_scope_ != nullptr) {
685
    timer.Start();
686
    PrintF(trace_scope_->file(), "[deoptimizing (DEOPT %s): begin ",
687
           MessageFor(deopt_kind_));
688
    PrintFunctionName();
689
    PrintF(trace_scope_->file(),
690
           " (opt #%d) @%d, FP to SP delta: %d, caller sp: " V8PRIxPTR_FMT
691 692 693
           "]\n",
           input_data->OptimizationId()->value(), bailout_id_, fp_to_sp_delta_,
           caller_frame_top_);
694 695
    if (deopt_kind_ == DeoptimizeKind::kEager ||
        deopt_kind_ == DeoptimizeKind::kSoft) {
696 697
      compiled_code_->PrintDeoptLocation(
          trace_scope_->file(), "            ;;; deoptimize at ", from_);
698
    }
699 700
  }

701
  BailoutId node_id = input_data->BytecodeOffset(bailout_id_);
702
  ByteArray translations = input_data->TranslationByteArray();
703 704 705
  unsigned translation_index =
      input_data->TranslationIndex(bailout_id_)->value();

706 707
  TranslationIterator state_iterator(translations, translation_index);
  translated_state_.Init(
708
      isolate_, input_->GetFramePointerAddress(), &state_iterator,
709
      input_data->LiteralArray(), input_->GetRegisterValues(),
710 711 712 713
      trace_scope_ == nullptr ? nullptr : trace_scope_->file(),
      function_->IsHeapObject()
          ? function_->shared()->internal_formal_parameter_count()
          : 0);
714

715
  // Do the input frame to output frame(s) translation.
716
  size_t count = translated_state_.frames().size();
717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732
  // If we are supposed to go to the catch handler, find the catching frame
  // for the catch and make sure we only deoptimize upto that frame.
  if (deoptimizing_throw_) {
    size_t catch_handler_frame_index = count;
    for (size_t i = count; i-- > 0;) {
      catch_handler_pc_offset_ = LookupCatchHandler(
          &(translated_state_.frames()[i]), &catch_handler_data_);
      if (catch_handler_pc_offset_ >= 0) {
        catch_handler_frame_index = i;
        break;
      }
    }
    CHECK_LT(catch_handler_frame_index, count);
    count = catch_handler_frame_index + 1;
  }

733
  DCHECK_NULL(output_);
734
  output_ = new FrameDescription*[count];
735
  for (size_t i = 0; i < count; ++i) {
736
    output_[i] = nullptr;
737
  }
738
  output_count_ = static_cast<int>(count);
739 740

  // Translate each output frame.
741 742
  int frame_index = 0;  // output_frame_index
  for (size_t i = 0; i < count; ++i, ++frame_index) {
743
    // Read the ast node id, function, and frame height for this output frame.
744
    TranslatedFrame* translated_frame = &(translated_state_.frames()[i]);
745
    bool handle_exception = deoptimizing_throw_ && i == count - 1;
746
    switch (translated_frame->kind()) {
747
      case TranslatedFrame::kInterpretedFunction:
748
        DoComputeInterpretedFrame(translated_frame, frame_index,
749
                                  handle_exception);
750 751
        jsframe_count_++;
        break;
752
      case TranslatedFrame::kArgumentsAdaptor:
753 754
        DoComputeArgumentsAdaptorFrame(translated_frame, frame_index);
        break;
755
      case TranslatedFrame::kConstructStub:
756
        DoComputeConstructStubFrame(translated_frame, frame_index);
757
        break;
758
      case TranslatedFrame::kBuiltinContinuation:
759 760
        DoComputeBuiltinContinuation(translated_frame, frame_index,
                                     BuiltinContinuationMode::STUB);
761 762
        break;
      case TranslatedFrame::kJavaScriptBuiltinContinuation:
763 764 765 766 767 768 769 770 771
        DoComputeBuiltinContinuation(translated_frame, frame_index,
                                     BuiltinContinuationMode::JAVASCRIPT);
        break;
      case TranslatedFrame::kJavaScriptBuiltinContinuationWithCatch:
        DoComputeBuiltinContinuation(
            translated_frame, frame_index,
            handle_exception
                ? BuiltinContinuationMode::JAVASCRIPT_HANDLE_EXCEPTION
                : BuiltinContinuationMode::JAVASCRIPT_WITH_CATCH);
772
        break;
773 774
      case TranslatedFrame::kInvalid:
        FATAL("invalid frame");
775 776
        break;
    }
777 778
  }

779 780 781
  FrameDescription* topmost = output_[count - 1];
  topmost->GetRegisterValues()->SetRegister(kRootRegister.code(),
                                            isolate()->isolate_root());
782

783
  // Print some helpful diagnostic information.
784
  if (trace_scope_ != nullptr) {
785
    double ms = timer.Elapsed().InMillisecondsF();
786
    int index = output_count_ - 1;  // Index of the topmost frame.
787
    PrintF(trace_scope_->file(), "[deoptimizing (%s): end ",
788
           MessageFor(deopt_kind_));
789
    PrintFunctionName();
790
    PrintF(trace_scope_->file(),
791
           " @%d => node=%d, pc=" V8PRIxPTR_FMT ", caller sp=" V8PRIxPTR_FMT
792
           ", took %0.3f ms]\n",
793
           bailout_id_, node_id.ToInt(), output_[index]->GetPc(),
794
           caller_frame_top_, ms);
795 796 797
  }
}

798 799
void Deoptimizer::DoComputeInterpretedFrame(TranslatedFrame* translated_frame,
                                            int frame_index,
800
                                            bool goto_catch_handler) {
801
  SharedFunctionInfo shared = translated_frame->raw_shared_info();
802

803
  TranslatedFrame::iterator value_iterator = translated_frame->begin();
804 805
  bool is_bottommost = (0 == frame_index);
  bool is_topmost = (output_count_ - 1 == frame_index);
806

807
  int bytecode_offset = translated_frame->node_id().ToInt();
808 809 810 811
  int height = translated_frame->height();
  int register_count = height - 1;  // Exclude accumulator.
  int register_stack_slot_count =
      InterpreterFrameConstants::RegisterStackSlotCount(register_count);
812
  int height_in_bytes = register_stack_slot_count * kSystemPointerSize;
813

814 815
  // The topmost frame will contain the accumulator.
  if (is_topmost) {
816 817
    height_in_bytes += kSystemPointerSize;
    if (PadTopOfStackRegister()) height_in_bytes += kSystemPointerSize;
818
  }
819

820
  TranslatedFrame::iterator function_iterator = value_iterator++;
821
  if (trace_scope_ != nullptr) {
822
    PrintF(trace_scope_->file(), "  translating interpreted frame ");
823
    std::unique_ptr<char[]> name = shared->DebugName()->ToCString();
824
    PrintF(trace_scope_->file(), "%s", name.get());
825 826 827 828 829 830
    PrintF(trace_scope_->file(), " => bytecode_offset=%d, height=%d%s\n",
           bytecode_offset, height_in_bytes,
           goto_catch_handler ? " (throw)" : "");
  }
  if (goto_catch_handler) {
    bytecode_offset = catch_handler_pc_offset_;
831 832 833
  }

  // The 'fixed' part of the frame consists of the incoming parameters and
834 835
  // the part described by InterpreterFrameConstants. This will include
  // argument padding, when needed.
836
  unsigned fixed_frame_size = ComputeInterpretedFixedSize(shared);
837 838 839
  unsigned output_frame_size = height_in_bytes + fixed_frame_size;

  // Allocate and store the output frame description.
840 841 842
  int parameter_count = shared->internal_formal_parameter_count() + 1;
  FrameDescription* output_frame = new (output_frame_size)
      FrameDescription(output_frame_size, parameter_count);
843
  FrameWriter frame_writer(this, output_frame, trace_scope_);
844 845 846 847 848

  CHECK(frame_index >= 0 && frame_index < output_count_);
  CHECK_NULL(output_[frame_index]);
  output_[frame_index] = output_frame;

849 850
  // The top address of the frame is computed from the previous frame's top and
  // this frame's size.
851 852
  intptr_t top_address;
  if (is_bottommost) {
853
    top_address = caller_frame_top_ - output_frame_size;
854 855 856 857 858 859
  } else {
    top_address = output_[frame_index - 1]->GetTop() - output_frame_size;
  }
  output_frame->SetTop(top_address);

  // Compute the incoming parameter translation.
860

861
  ReadOnlyRoots roots(isolate());
862
  if (ShouldPadArguments(parameter_count)) {
863
    frame_writer.PushRawObject(roots.the_hole_value(), "padding\n");
864 865
  }

866
  for (int i = 0; i < parameter_count; ++i, ++value_iterator) {
867
    frame_writer.PushTranslatedValue(value_iterator, "stack parameter");
868 869
  }

870 871
  DCHECK_EQ(output_frame->GetLastArgumentSlotOffset(),
            frame_writer.top_offset());
872 873 874 875
  if (trace_scope_ != nullptr) {
    PrintF(trace_scope_->file(), "    -------------------------\n");
  }

876
  // There are no translation commands for the caller's pc and fp, the
877
  // context, the function and the bytecode offset.  Synthesize
878 879 880 881 882 883 884
  // their values and set them up
  // explicitly.
  //
  // The caller's pc for the bottommost output frame is the same as in the
  // input frame.  For all subsequent output frames, it can be read from the
  // previous one.  This frame's pc can be computed from the non-optimized
  // function code and AST id of the bailout.
885 886 887
  const intptr_t caller_pc =
      is_bottommost ? caller_pc_ : output_[frame_index - 1]->GetPc();
  frame_writer.PushCallerPc(caller_pc);
888 889 890 891 892

  // The caller's frame pointer for the bottommost output frame is the same
  // as in the input frame.  For all subsequent output frames, it can be
  // read from the previous one.  Also compute and set this frame's frame
  // pointer.
893 894 895 896 897
  const intptr_t caller_fp =
      is_bottommost ? caller_fp_ : output_[frame_index - 1]->GetFp();
  frame_writer.PushCallerFp(caller_fp);

  intptr_t fp_value = top_address + frame_writer.top_offset();
898
  output_frame->SetFp(fp_value);
899 900 901 902
  if (is_topmost) {
    Register fp_reg = InterpretedFrame::fp_register();
    output_frame->SetRegister(fp_reg.code(), fp_value);
  }
903 904 905 906 907

  if (FLAG_enable_embedded_constant_pool) {
    // For the bottommost output frame the constant pool pointer can be gotten
    // from the input frame. For subsequent output frames, it can be read from
    // the previous frame.
908 909 910 911
    const intptr_t caller_cp =
        is_bottommost ? caller_constant_pool_
                      : output_[frame_index - 1]->GetConstantPool();
    frame_writer.PushCallerConstantPool(caller_cp);
912 913 914 915 916
  }

  // For the bottommost output frame the context can be gotten from the input
  // frame. For all subsequent output frames it can be gotten from the function
  // so long as we don't inline functions that need local contexts.
917 918 919

  // When deoptimizing into a catch block, we need to take the context
  // from a register that was specified in the handler table.
920
  TranslatedFrame::iterator context_pos = value_iterator++;
921 922 923 924 925 926 927
  if (goto_catch_handler) {
    // Skip to the translated value of the register specified
    // in the handler table.
    for (int i = 0; i < catch_handler_data_ + 1; ++i) {
      context_pos++;
    }
  }
928
  // Read the context from the translations.
929 930
  Object context = context_pos->GetRawValue();
  output_frame->SetContext(static_cast<intptr_t>(context->ptr()));
931
  frame_writer.PushTranslatedValue(context_pos, "context");
932

933
  // The function was mentioned explicitly in the BEGIN_FRAME.
934
  frame_writer.PushTranslatedValue(function_iterator, "function");
935

936
  // Set the bytecode array pointer.
937 938 939
  Object bytecode_array = shared->HasBreakInfo()
                              ? shared->GetDebugInfo()->DebugBytecodeArray()
                              : shared->GetBytecodeArray();
940
  frame_writer.PushRawObject(bytecode_array, "bytecode array\n");
941

942 943
  // The bytecode offset was mentioned explicitly in the BEGIN_FRAME.
  int raw_bytecode_offset =
944
      BytecodeArray::kHeaderSize - kHeapObjectTag + bytecode_offset;
945
  Smi smi_bytecode_offset = Smi::FromInt(raw_bytecode_offset);
946
  frame_writer.PushRawObject(smi_bytecode_offset, "bytecode offset\n");
947

948 949 950 951
  if (trace_scope_ != nullptr) {
    PrintF(trace_scope_->file(), "    -------------------------\n");
  }

952
  // Translate the rest of the interpreter registers in the frame.
953 954 955 956 957
  // The return_value_offset is counted from the top. Here, we compute the
  // register index (counted from the start).
  int return_value_first_reg =
      register_count - translated_frame->return_value_offset();
  int return_value_count = translated_frame->return_value_count();
958
  for (int i = 0; i < register_count; ++i, ++value_iterator) {
959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981
    // Ensure we write the return value if we have one and we are returning
    // normally to a lazy deopt point.
    if (is_topmost && !goto_catch_handler &&
        deopt_kind_ == DeoptimizeKind::kLazy && i >= return_value_first_reg &&
        i < return_value_first_reg + return_value_count) {
      int return_index = i - return_value_first_reg;
      if (return_index == 0) {
        frame_writer.PushRawValue(input_->GetRegister(kReturnRegister0.code()),
                                  "return value 0\n");
        // We do not handle the situation when one return value should go into
        // the accumulator and another one into an ordinary register. Since
        // the interpreter should never create such situation, just assert
        // this does not happen.
        CHECK_LE(return_value_first_reg + return_value_count, register_count);
      } else {
        CHECK_EQ(return_index, 1);
        frame_writer.PushRawValue(input_->GetRegister(kReturnRegister1.code()),
                                  "return value 1\n");
      }
    } else {
      // This is not return value, just write the value from the translations.
      frame_writer.PushTranslatedValue(value_iterator, "stack parameter");
    }
982 983
  }

984 985 986 987 988 989
  int register_slots_written = register_count;
  DCHECK_LE(register_slots_written, register_stack_slot_count);
  // Some architectures must pad the stack frame with extra stack slots
  // to ensure the stack frame is aligned. Do this now.
  while (register_slots_written < register_stack_slot_count) {
    register_slots_written++;
990
    frame_writer.PushRawObject(roots.the_hole_value(), "padding\n");
991 992
  }

993 994
  // Translate the accumulator register (depending on frame position).
  if (is_topmost) {
995
    if (PadTopOfStackRegister()) {
996
      frame_writer.PushRawObject(roots.the_hole_value(), "padding\n");
997 998 999
    }
    // For topmost frame, put the accumulator on the stack. The
    // {NotifyDeoptimized} builtin pops it off the topmost frame (possibly
1000 1001 1002 1003 1004
    // after materialization).
    if (goto_catch_handler) {
      // If we are lazy deopting to a catch handler, we set the accumulator to
      // the exception (which lives in the result register).
      intptr_t accumulator_value =
1005
          input_->GetRegister(kInterpreterAccumulatorRegister.code());
1006
      frame_writer.PushRawObject(Object(accumulator_value), "accumulator\n");
1007
    } else {
1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018
      // If we are lazily deoptimizing make sure we store the deopt
      // return value into the appropriate slot.
      if (deopt_kind_ == DeoptimizeKind::kLazy &&
          translated_frame->return_value_offset() == 0 &&
          translated_frame->return_value_count() > 0) {
        CHECK_EQ(translated_frame->return_value_count(), 1);
        frame_writer.PushRawValue(input_->GetRegister(kReturnRegister0.code()),
                                  "return value 0\n");
      } else {
        frame_writer.PushTranslatedValue(value_iterator, "accumulator");
      }
1019
    }
1020
    ++value_iterator;  // Move over the accumulator.
1021
  } else {
1022 1023
    // For non-topmost frames, skip the accumulator translation. For those
    // frames, the return value from the callee will become the accumulator.
1024
    ++value_iterator;
1025
  }
1026
  CHECK_EQ(translated_frame->end(), value_iterator);
1027
  CHECK_EQ(0u, frame_writer.top_offset());
1028

1029 1030 1031 1032
  // Compute this frame's PC and state. The PC will be a special builtin that
  // continues the bytecode dispatch. Note that non-topmost and lazy-style
  // bailout handlers also advance the bytecode offset before dispatch, hence
  // simulating what normal handlers do upon completion of the operation.
1033
  Builtins* builtins = isolate_->builtins();
1034
  Code dispatch_builtin =
1035 1036
      (!is_topmost || (deopt_kind_ == DeoptimizeKind::kLazy)) &&
              !goto_catch_handler
1037 1038
          ? builtins->builtin(Builtins::kInterpreterEnterBytecodeAdvance)
          : builtins->builtin(Builtins::kInterpreterEnterBytecodeDispatch);
1039
  output_frame->SetPc(
1040
      static_cast<intptr_t>(dispatch_builtin->InstructionStart()));
1041 1042 1043 1044

  // Update constant pool.
  if (FLAG_enable_embedded_constant_pool) {
    intptr_t constant_pool_value =
1045
        static_cast<intptr_t>(dispatch_builtin->constant_pool());
1046 1047 1048 1049 1050 1051 1052 1053
    output_frame->SetConstantPool(constant_pool_value);
    if (is_topmost) {
      Register constant_pool_reg =
          InterpretedFrame::constant_pool_pointer_register();
      output_frame->SetRegister(constant_pool_reg.code(), constant_pool_value);
    }
  }

1054 1055 1056 1057
  // Clear the context register. The context might be a de-materialized object
  // and will be materialized by {Runtime_NotifyDeoptimized}. For additional
  // safety we use Smi(0) instead of the potential {arguments_marker} here.
  if (is_topmost) {
1058
    intptr_t context_value = static_cast<intptr_t>(Smi::zero().ptr());
1059 1060
    Register context_reg = JavaScriptFrame::context_register();
    output_frame->SetRegister(context_reg.code(), context_value);
1061
    // Set the continuation for the topmost frame.
1062
    Code continuation = builtins->builtin(Builtins::kNotifyDeoptimized);
1063
    output_frame->SetContinuation(
1064
        static_cast<intptr_t>(continuation->InstructionStart()));
1065 1066 1067
  }
}

1068 1069
void Deoptimizer::DoComputeArgumentsAdaptorFrame(
    TranslatedFrame* translated_frame, int frame_index) {
1070
  TranslatedFrame::iterator value_iterator = translated_frame->begin();
1071
  bool is_bottommost = (0 == frame_index);
1072 1073

  unsigned height = translated_frame->height();
1074
  unsigned height_in_bytes = height * kSystemPointerSize;
1075
  int parameter_count = height;
1076 1077
  if (ShouldPadArguments(parameter_count))
    height_in_bytes += kSystemPointerSize;
1078

1079
  TranslatedFrame::iterator function_iterator = value_iterator++;
1080
  if (trace_scope_ != nullptr) {
1081 1082
    PrintF(trace_scope_->file(),
           "  translating arguments adaptor => height=%d\n", height_in_bytes);
1083 1084
  }

1085
  unsigned fixed_frame_size = ArgumentsAdaptorFrameConstants::kFixedFrameSize;
1086 1087 1088
  unsigned output_frame_size = height_in_bytes + fixed_frame_size;

  // Allocate and store the output frame description.
1089 1090
  FrameDescription* output_frame = new (output_frame_size)
      FrameDescription(output_frame_size, parameter_count);
1091
  FrameWriter frame_writer(this, output_frame, trace_scope_);
1092

1093 1094
  // Arguments adaptor can not be topmost.
  CHECK(frame_index < output_count_ - 1);
1095
  CHECK_NULL(output_[frame_index]);
1096 1097
  output_[frame_index] = output_frame;

1098 1099
  // The top address of the frame is computed from the previous frame's top and
  // this frame's size.
1100
  intptr_t top_address;
1101 1102 1103 1104 1105
  if (is_bottommost) {
    top_address = caller_frame_top_ - output_frame_size;
  } else {
    top_address = output_[frame_index - 1]->GetTop() - output_frame_size;
  }
1106 1107
  output_frame->SetTop(top_address);

1108
  ReadOnlyRoots roots(isolate());
1109
  if (ShouldPadArguments(parameter_count)) {
1110
    frame_writer.PushRawObject(roots.the_hole_value(), "padding\n");
1111 1112 1113
  }

  // Compute the incoming parameter translation.
1114
  for (int i = 0; i < parameter_count; ++i, ++value_iterator) {
1115
    frame_writer.PushTranslatedValue(value_iterator, "stack parameter");
1116 1117
  }

1118 1119 1120
  DCHECK_EQ(output_frame->GetLastArgumentSlotOffset(),
            frame_writer.top_offset());

1121
  // Read caller's PC from the previous frame.
1122 1123 1124
  const intptr_t caller_pc =
      is_bottommost ? caller_pc_ : output_[frame_index - 1]->GetPc();
  frame_writer.PushCallerPc(caller_pc);
1125 1126

  // Read caller's FP from the previous frame, and set this frame's FP.
1127 1128 1129 1130 1131
  const intptr_t caller_fp =
      is_bottommost ? caller_fp_ : output_[frame_index - 1]->GetFp();
  frame_writer.PushCallerFp(caller_fp);

  intptr_t fp_value = top_address + frame_writer.top_offset();
1132 1133
  output_frame->SetFp(fp_value);

1134
  if (FLAG_enable_embedded_constant_pool) {
1135
    // Read the caller's constant pool from the previous frame.
1136 1137 1138 1139
    const intptr_t caller_cp =
        is_bottommost ? caller_constant_pool_
                      : output_[frame_index - 1]->GetConstantPool();
    frame_writer.PushCallerConstantPool(caller_cp);
1140 1141
  }

1142
  // A marker value is used in place of the context.
1143 1144
  intptr_t marker = StackFrame::TypeToMarker(StackFrame::ARGUMENTS_ADAPTOR);
  frame_writer.PushRawValue(marker, "context (adaptor sentinel)\n");
1145 1146

  // The function was mentioned explicitly in the ARGUMENTS_ADAPTOR_FRAME.
1147
  frame_writer.PushTranslatedValue(function_iterator, "function\n");
1148 1149

  // Number of incoming arguments.
1150
  frame_writer.PushRawObject(Smi::FromInt(height - 1), "argc\n");
1151

1152
  frame_writer.PushRawObject(roots.the_hole_value(), "padding\n");
1153

1154
  CHECK_EQ(translated_frame->end(), value_iterator);
1155
  DCHECK_EQ(0, frame_writer.top_offset());
1156 1157

  Builtins* builtins = isolate_->builtins();
1158
  Code adaptor_trampoline =
1159
      builtins->builtin(Builtins::kArgumentsAdaptorTrampoline);
1160
  intptr_t pc_value = static_cast<intptr_t>(
1161
      adaptor_trampoline->InstructionStart() +
1162 1163
      isolate_->heap()->arguments_adaptor_deopt_pc_offset()->value());
  output_frame->SetPc(pc_value);
1164
  if (FLAG_enable_embedded_constant_pool) {
1165
    intptr_t constant_pool_value =
1166
        static_cast<intptr_t>(adaptor_trampoline->constant_pool());
1167 1168
    output_frame->SetConstantPool(constant_pool_value);
  }
1169 1170
}

1171 1172
void Deoptimizer::DoComputeConstructStubFrame(TranslatedFrame* translated_frame,
                                              int frame_index) {
1173
  TranslatedFrame::iterator value_iterator = translated_frame->begin();
1174 1175 1176
  bool is_topmost = (output_count_ - 1 == frame_index);
  // The construct frame could become topmost only if we inlined a constructor
  // call which does a tail call (otherwise the tail callee's frame would be
1177 1178
  // the topmost one). So it could only be the DeoptimizeKind::kLazy case.
  CHECK(!is_topmost || deopt_kind_ == DeoptimizeKind::kLazy);
1179

1180
  Builtins* builtins = isolate_->builtins();
1181
  Code construct_stub = builtins->builtin(Builtins::kJSConstructStubGeneric);
1182
  BailoutId bailout_id = translated_frame->node_id();
1183
  unsigned height = translated_frame->height();
1184
  unsigned parameter_count = height - 1;  // Exclude the context.
1185
  unsigned height_in_bytes = parameter_count * kSystemPointerSize;
1186 1187 1188 1189

  // If the construct frame appears to be topmost we should ensure that the
  // value of result register is preserved during continuation execution.
  // We do this here by "pushing" the result of the constructor function to the
1190 1191
  // top of the reconstructed stack and popping it in
  // {Builtins::kNotifyDeoptimized}.
1192
  if (is_topmost) {
1193 1194
    height_in_bytes += kSystemPointerSize;
    if (PadTopOfStackRegister()) height_in_bytes += kSystemPointerSize;
1195 1196
  }

1197 1198
  if (ShouldPadArguments(parameter_count))
    height_in_bytes += kSystemPointerSize;
1199

1200
  TranslatedFrame::iterator function_iterator = value_iterator++;
1201
  if (trace_scope_ != nullptr) {
1202
    PrintF(trace_scope_->file(),
1203 1204 1205 1206
           "  translating construct stub => bailout_id=%d (%s), height=%d\n",
           bailout_id.ToInt(),
           bailout_id == BailoutId::ConstructStubCreate() ? "create" : "invoke",
           height_in_bytes);
1207 1208
  }

1209
  unsigned fixed_frame_size = ConstructFrameConstants::kFixedFrameSize;
1210 1211 1212
  unsigned output_frame_size = height_in_bytes + fixed_frame_size;

  // Allocate and store the output frame description.
1213 1214
  FrameDescription* output_frame = new (output_frame_size)
      FrameDescription(output_frame_size, parameter_count);
1215
  FrameWriter frame_writer(this, output_frame, trace_scope_);
1216

1217 1218
  // Construct stub can not be topmost.
  DCHECK(frame_index > 0 && frame_index < output_count_);
1219
  DCHECK_NULL(output_[frame_index]);
1220 1221
  output_[frame_index] = output_frame;

1222 1223
  // The top address of the frame is computed from the previous frame's top and
  // this frame's size.
1224 1225 1226 1227
  intptr_t top_address;
  top_address = output_[frame_index - 1]->GetTop() - output_frame_size;
  output_frame->SetTop(top_address);

1228
  ReadOnlyRoots roots(isolate());
1229
  if (ShouldPadArguments(parameter_count)) {
1230
    frame_writer.PushRawObject(roots.the_hole_value(), "padding\n");
1231 1232
  }

1233 1234 1235 1236 1237
  // The allocated receiver of a construct stub frame is passed as the
  // receiver parameter through the translation. It might be encoding
  // a captured object, so we need save it for later.
  TranslatedFrame::iterator receiver_iterator = value_iterator;

1238
  // Compute the incoming parameter translation.
1239
  for (unsigned i = 0; i < parameter_count; ++i, ++value_iterator) {
1240
    frame_writer.PushTranslatedValue(value_iterator, "stack parameter");
1241 1242
  }

1243 1244 1245
  DCHECK_EQ(output_frame->GetLastArgumentSlotOffset(),
            frame_writer.top_offset());

1246
  // Read caller's PC from the previous frame.
1247 1248
  const intptr_t caller_pc = output_[frame_index - 1]->GetPc();
  frame_writer.PushCallerPc(caller_pc);
1249 1250

  // Read caller's FP from the previous frame, and set this frame's FP.
1251 1252 1253 1254
  const intptr_t caller_fp = output_[frame_index - 1]->GetFp();
  frame_writer.PushCallerFp(caller_fp);

  intptr_t fp_value = top_address + frame_writer.top_offset();
1255
  output_frame->SetFp(fp_value);
1256 1257 1258 1259
  if (is_topmost) {
    Register fp_reg = JavaScriptFrame::fp_register();
    output_frame->SetRegister(fp_reg.code(), fp_value);
  }
1260

1261
  if (FLAG_enable_embedded_constant_pool) {
1262
    // Read the caller's constant pool from the previous frame.
1263 1264
    const intptr_t caller_cp = output_[frame_index - 1]->GetConstantPool();
    frame_writer.PushCallerConstantPool(caller_cp);
1265 1266
  }

1267
  // A marker value is used to mark the frame.
1268 1269
  intptr_t marker = StackFrame::TypeToMarker(StackFrame::CONSTRUCT);
  frame_writer.PushRawValue(marker, "context (construct stub sentinel)\n");
1270

1271
  frame_writer.PushTranslatedValue(value_iterator++, "context");
1272 1273

  // Number of incoming arguments.
1274
  frame_writer.PushRawObject(Smi::FromInt(parameter_count - 1), "argc\n");
1275

1276 1277
  // The constructor function was mentioned explicitly in the
  // CONSTRUCT_STUB_FRAME.
Maxim Mazurok's avatar
Maxim Mazurok committed
1278
  frame_writer.PushTranslatedValue(function_iterator, "constructor function\n");
1279 1280

  // The deopt info contains the implicit receiver or the new target at the
1281 1282
  // position of the receiver. Copy it to the top of stack, with the hole value
  // as padding to maintain alignment.
1283

1284
  frame_writer.PushRawObject(roots.the_hole_value(), "padding\n");
1285

1286 1287 1288 1289 1290 1291
  CHECK(bailout_id == BailoutId::ConstructStubCreate() ||
        bailout_id == BailoutId::ConstructStubInvoke());
  const char* debug_hint = bailout_id == BailoutId::ConstructStubCreate()
                               ? "new target\n"
                               : "allocated receiver\n";
  frame_writer.PushTranslatedValue(receiver_iterator, debug_hint);
1292

1293
  if (is_topmost) {
1294
    if (PadTopOfStackRegister()) {
1295
      frame_writer.PushRawObject(roots.the_hole_value(), "padding\n");
1296
    }
1297
    // Ensure the result is restored back when we return to the stub.
1298
    Register result_reg = kReturnRegister0;
1299 1300
    intptr_t result = input_->GetRegister(result_reg.code());
    frame_writer.PushRawValue(result, "subcall result\n");
1301 1302
  }

1303
  CHECK_EQ(translated_frame->end(), value_iterator);
1304
  CHECK_EQ(0u, frame_writer.top_offset());
1305

1306 1307
  // Compute this frame's PC.
  DCHECK(bailout_id.IsValidForConstructStub());
1308
  Address start = construct_stub->InstructionStart();
1309 1310 1311 1312
  int pc_offset =
      bailout_id == BailoutId::ConstructStubCreate()
          ? isolate_->heap()->construct_stub_create_deopt_pc_offset()->value()
          : isolate_->heap()->construct_stub_invoke_deopt_pc_offset()->value();
1313
  intptr_t pc_value = static_cast<intptr_t>(start + pc_offset);
1314 1315 1316
  output_frame->SetPc(pc_value);

  // Update constant pool.
1317
  if (FLAG_enable_embedded_constant_pool) {
1318
    intptr_t constant_pool_value =
1319
        static_cast<intptr_t>(construct_stub->constant_pool());
1320
    output_frame->SetConstantPool(constant_pool_value);
1321 1322 1323
    if (is_topmost) {
      Register constant_pool_reg =
          JavaScriptFrame::constant_pool_pointer_register();
1324
      output_frame->SetRegister(constant_pool_reg.code(), constant_pool_value);
1325 1326 1327
    }
  }

1328 1329 1330 1331
  // Clear the context register. The context might be a de-materialized object
  // and will be materialized by {Runtime_NotifyDeoptimized}. For additional
  // safety we use Smi(0) instead of the potential {arguments_marker} here.
  if (is_topmost) {
1332
    intptr_t context_value = static_cast<intptr_t>(Smi::zero().ptr());
1333 1334 1335 1336
    Register context_reg = JavaScriptFrame::context_register();
    output_frame->SetRegister(context_reg.code(), context_value);
  }

1337 1338 1339
  // Set the continuation for the topmost frame.
  if (is_topmost) {
    Builtins* builtins = isolate_->builtins();
1340
    DCHECK_EQ(DeoptimizeKind::kLazy, deopt_kind_);
1341
    Code continuation = builtins->builtin(Builtins::kNotifyDeoptimized);
1342
    output_frame->SetContinuation(
1343
        static_cast<intptr_t>(continuation->InstructionStart()));
1344
  }
1345 1346
}

1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403
bool Deoptimizer::BuiltinContinuationModeIsJavaScript(
    BuiltinContinuationMode mode) {
  switch (mode) {
    case BuiltinContinuationMode::STUB:
      return false;
    case BuiltinContinuationMode::JAVASCRIPT:
    case BuiltinContinuationMode::JAVASCRIPT_WITH_CATCH:
    case BuiltinContinuationMode::JAVASCRIPT_HANDLE_EXCEPTION:
      return true;
  }
  UNREACHABLE();
}

bool Deoptimizer::BuiltinContinuationModeIsWithCatch(
    BuiltinContinuationMode mode) {
  switch (mode) {
    case BuiltinContinuationMode::STUB:
    case BuiltinContinuationMode::JAVASCRIPT:
      return false;
    case BuiltinContinuationMode::JAVASCRIPT_WITH_CATCH:
    case BuiltinContinuationMode::JAVASCRIPT_HANDLE_EXCEPTION:
      return true;
  }
  UNREACHABLE();
}

StackFrame::Type Deoptimizer::BuiltinContinuationModeToFrameType(
    BuiltinContinuationMode mode) {
  switch (mode) {
    case BuiltinContinuationMode::STUB:
      return StackFrame::BUILTIN_CONTINUATION;
    case BuiltinContinuationMode::JAVASCRIPT:
      return StackFrame::JAVA_SCRIPT_BUILTIN_CONTINUATION;
    case BuiltinContinuationMode::JAVASCRIPT_WITH_CATCH:
      return StackFrame::JAVA_SCRIPT_BUILTIN_CONTINUATION_WITH_CATCH;
    case BuiltinContinuationMode::JAVASCRIPT_HANDLE_EXCEPTION:
      return StackFrame::JAVA_SCRIPT_BUILTIN_CONTINUATION_WITH_CATCH;
  }
  UNREACHABLE();
}

Builtins::Name Deoptimizer::TrampolineForBuiltinContinuation(
    BuiltinContinuationMode mode, bool must_handle_result) {
  switch (mode) {
    case BuiltinContinuationMode::STUB:
      return must_handle_result ? Builtins::kContinueToCodeStubBuiltinWithResult
                                : Builtins::kContinueToCodeStubBuiltin;
    case BuiltinContinuationMode::JAVASCRIPT:
    case BuiltinContinuationMode::JAVASCRIPT_WITH_CATCH:
    case BuiltinContinuationMode::JAVASCRIPT_HANDLE_EXCEPTION:
      return must_handle_result
                 ? Builtins::kContinueToJavaScriptBuiltinWithResult
                 : Builtins::kContinueToJavaScriptBuiltin;
  }
  UNREACHABLE();
}

1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424
// BuiltinContinuationFrames capture the machine state that is expected as input
// to a builtin, including both input register values and stack parameters. When
// the frame is reactivated (i.e. the frame below it returns), a
// ContinueToBuiltin stub restores the register state from the frame and tail
// calls to the actual target builtin, making it appear that the stub had been
// directly called by the frame above it. The input values to populate the frame
// are taken from the deopt's FrameState.
//
// Frame translation happens in two modes, EAGER and LAZY. In EAGER mode, all of
// the parameters to the Builtin are explicitly specified in the TurboFan
// FrameState node. In LAZY mode, there is always one fewer parameters specified
// in the FrameState than expected by the Builtin. In that case, construction of
// BuiltinContinuationFrame adds the final missing parameter during
// deoptimization, and that parameter is always on the stack and contains the
// value returned from the callee of the call site triggering the LAZY deopt
// (e.g. rax on x64). This requires that continuation Builtins for LAZY deopts
// must have at least one stack parameter.
//
//                TO
//    |          ....           |
//    +-------------------------+
1425
//    | arg padding (arch dept) |<- at most 1*kSystemPointerSize
1426
//    +-------------------------+
1427 1428 1429 1430 1431
//    |     builtin param 0     |<- FrameState input value n becomes
//    +-------------------------+
//    |           ...           |
//    +-------------------------+
//    |     builtin param m     |<- FrameState input value n+m-1, or in
1432
//    +-----needs-alignment-----+   the LAZY case, return LAZY result value
1433 1434 1435
//    | ContinueToBuiltin entry |
//    +-------------------------+
// |  |    saved frame (FP)     |
1436
// |  +=====needs=alignment=====+<- fpreg
1437 1438 1439 1440
// |  |constant pool (if ool_cp)|
// v  +-------------------------+
//    |BUILTIN_CONTINUATION mark|
//    +-------------------------+
1441 1442 1443 1444
//    |  JSFunction (or zero)   |<- only if JavaScript builtin
//    +-------------------------+
//    |  frame height above FP  |
//    +-------------------------+
1445 1446
//    |         context         |<- this non-standard context slot contains
//    +-------------------------+   the context, even for non-JS builtins.
1447
//    |     builtin address     |
1448 1449 1450 1451 1452 1453
//    +-------------------------+
//    | builtin input GPR reg0  |<- populated from deopt FrameState using
//    +-------------------------+   the builtin's CallInterfaceDescriptor
//    |          ...            |   to map a FrameState's 0..n-1 inputs to
//    +-------------------------+   the builtin's n input register params.
//    | builtin input GPR regn  |
1454 1455
//    +-------------------------+
//    | reg padding (arch dept) |
1456
//    +-----needs--alignment----+
1457 1458 1459
//    | res padding (arch dept) |<- only if {is_topmost}; result is pop'd by
//    +-------------------------+<- kNotifyDeopt ASM stub and moved to acc
//    |      result  value      |<- reg, as ContinueToBuiltin stub expects.
1460
//    +-----needs-alignment-----+<- spreg
1461 1462 1463
//
void Deoptimizer::DoComputeBuiltinContinuation(
    TranslatedFrame* translated_frame, int frame_index,
1464
    BuiltinContinuationMode mode) {
1465 1466 1467 1468
  TranslatedFrame::iterator value_iterator = translated_frame->begin();

  // The output frame must have room for all of the parameters that need to be
  // passed to the builtin continuation.
1469
  const int height_in_words = translated_frame->height();
1470 1471 1472

  BailoutId bailout_id = translated_frame->node_id();
  Builtins::Name builtin_name = Builtins::GetBuiltinFromBailoutId(bailout_id);
1473
  Code builtin = isolate()->builtins()->builtin(builtin_name);
1474 1475 1476 1477 1478
  Callable continuation_callable =
      Builtins::CallableFor(isolate(), builtin_name);
  CallInterfaceDescriptor continuation_descriptor =
      continuation_callable.descriptor();

1479 1480
  const bool is_bottommost = (0 == frame_index);
  const bool is_topmost = (output_count_ - 1 == frame_index);
1481 1482
  const bool must_handle_result =
      !is_topmost || deopt_kind_ == DeoptimizeKind::kLazy;
1483

1484
  const RegisterConfiguration* config(RegisterConfiguration::Default());
1485 1486 1487 1488 1489
  const int allocatable_register_count =
      config->num_allocatable_general_registers();
  const int padding_slot_count =
      BuiltinContinuationFrameConstants::PaddingSlotCount(
          allocatable_register_count);
1490

1491
  const int register_parameter_count =
1492 1493 1494
      continuation_descriptor.GetRegisterParameterCount();
  // Make sure to account for the context by removing it from the register
  // parameter count.
1495 1496 1497
  const int translated_stack_parameters =
      height_in_words - register_parameter_count - 1;
  const int stack_param_count =
1498 1499
      translated_stack_parameters + (must_handle_result ? 1 : 0) +
      (BuiltinContinuationModeIsWithCatch(mode) ? 1 : 0);
1500 1501
  const int stack_param_pad_count =
      ShouldPadArguments(stack_param_count) ? 1 : 0;
1502

1503 1504 1505 1506 1507
  // If the builtins frame appears to be topmost we should ensure that the
  // value of result register is preserved during continuation execution.
  // We do this here by "pushing" the result of callback function to the
  // top of the reconstructed stack and popping it in
  // {Builtins::kNotifyDeoptimized}.
1508 1509 1510 1511
  const int push_result_count =
      is_topmost ? (PadTopOfStackRegister() ? 2 : 1) : 0;

  const unsigned output_frame_size =
1512 1513 1514
      kSystemPointerSize * (stack_param_count + stack_param_pad_count +
                            allocatable_register_count + padding_slot_count +
                            push_result_count) +
1515 1516 1517
      BuiltinContinuationFrameConstants::kFixedFrameSize;

  const unsigned output_frame_size_above_fp =
1518 1519
      kSystemPointerSize * (allocatable_register_count + padding_slot_count +
                            push_result_count) +
1520 1521
      (BuiltinContinuationFrameConstants::kFixedFrameSize -
       BuiltinContinuationFrameConstants::kFixedFrameSizeAboveFp);
1522

1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538
  // Validate types of parameters. They must all be tagged except for argc for
  // JS builtins.
  bool has_argc = false;
  for (int i = 0; i < register_parameter_count; ++i) {
    MachineType type = continuation_descriptor.GetParameterType(i);
    int code = continuation_descriptor.GetRegisterParameter(i).code();
    // Only tagged and int32 arguments are supported, and int32 only for the
    // arguments count on JavaScript builtins.
    if (type == MachineType::Int32()) {
      CHECK_EQ(code, kJavaScriptCallArgCountRegister.code());
      has_argc = true;
    } else {
      // Any other argument must be a tagged value.
      CHECK(IsAnyTagged(type.representation()));
    }
  }
1539
  CHECK_EQ(BuiltinContinuationModeIsJavaScript(mode), has_argc);
1540

1541
  if (trace_scope_ != nullptr) {
1542
    PrintF(trace_scope_->file(),
1543 1544 1545 1546 1547
           "  translating BuiltinContinuation to %s,"
           " register param count %d,"
           " stack param count %d\n",
           Builtins::name(builtin_name), register_parameter_count,
           stack_param_count);
1548 1549
  }

1550 1551
  FrameDescription* output_frame = new (output_frame_size)
      FrameDescription(output_frame_size, stack_param_count);
1552
  output_[frame_index] = output_frame;
1553
  FrameWriter frame_writer(this, output_frame, trace_scope_);
1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564

  // The top address of the frame is computed from the previous frame's top and
  // this frame's size.
  intptr_t top_address;
  if (is_bottommost) {
    top_address = caller_frame_top_ - output_frame_size;
  } else {
    top_address = output_[frame_index - 1]->GetTop() - output_frame_size;
  }
  output_frame->SetTop(top_address);

1565 1566 1567
  // Get the possible JSFunction for the case that this is a
  // JavaScriptBuiltinContinuationFrame, which needs the JSFunction pointer
  // like a normal JavaScriptFrame.
1568
  const intptr_t maybe_function = value_iterator->GetRawValue()->ptr();
1569 1570
  ++value_iterator;

1571
  ReadOnlyRoots roots(isolate());
1572
  if (ShouldPadArguments(stack_param_count)) {
1573
    frame_writer.PushRawObject(roots.the_hole_value(), "padding\n");
1574
  }
1575

1576
  for (int i = 0; i < translated_stack_parameters; ++i, ++value_iterator) {
1577
    frame_writer.PushTranslatedValue(value_iterator, "stack parameter");
1578 1579
  }

1580 1581 1582 1583 1584 1585
  switch (mode) {
    case BuiltinContinuationMode::STUB:
      break;
    case BuiltinContinuationMode::JAVASCRIPT:
      break;
    case BuiltinContinuationMode::JAVASCRIPT_WITH_CATCH: {
1586
      frame_writer.PushRawObject(roots.the_hole_value(),
1587
                                 "placeholder for exception on lazy deopt\n");
1588 1589 1590 1591
    } break;
    case BuiltinContinuationMode::JAVASCRIPT_HANDLE_EXCEPTION: {
      intptr_t accumulator_value =
          input_->GetRegister(kInterpreterAccumulatorRegister.code());
1592
      frame_writer.PushRawObject(Object(accumulator_value),
1593
                                 "exception (from accumulator)\n");
1594 1595 1596
    } break;
  }

1597
  if (must_handle_result) {
1598
    frame_writer.PushRawObject(roots.the_hole_value(),
1599
                               "placeholder for return result on lazy deopt\n");
1600 1601
  }

1602 1603 1604 1605 1606 1607
  DCHECK_EQ(output_frame->GetLastArgumentSlotOffset(),
            frame_writer.top_offset());

  std::vector<TranslatedFrame::iterator> register_values;
  int total_registers = config->num_general_registers();
  register_values.resize(total_registers, {value_iterator});
1608

1609
  for (int i = 0; i < register_parameter_count; ++i, ++value_iterator) {
1610
    int code = continuation_descriptor.GetRegisterParameter(i).code();
1611
    register_values[code] = value_iterator;
1612 1613 1614 1615 1616 1617 1618
  }

  // The context register is always implicit in the CallInterfaceDescriptor but
  // its register must be explicitly set when continuing to the builtin. Make
  // sure that it's harvested from the translation and copied into the register
  // set (it was automatically added at the end of the FrameState by the
  // instruction selector).
1619 1620
  Object context = value_iterator->GetRawValue();
  const intptr_t value = context->ptr();
1621 1622
  TranslatedFrame::iterator context_register_value = value_iterator++;
  register_values[kContextRegister.code()] = context_register_value;
1623 1624 1625 1626
  output_frame->SetContext(value);
  output_frame->SetRegister(kContextRegister.code(), value);

  // Set caller's PC (JSFunction continuation).
1627 1628 1629
  const intptr_t caller_pc =
      is_bottommost ? caller_pc_ : output_[frame_index - 1]->GetPc();
  frame_writer.PushCallerPc(caller_pc);
1630 1631

  // Read caller's FP from the previous frame, and set this frame's FP.
1632 1633 1634 1635 1636
  const intptr_t caller_fp =
      is_bottommost ? caller_fp_ : output_[frame_index - 1]->GetFp();
  frame_writer.PushCallerFp(caller_fp);

  const intptr_t fp_value = top_address + frame_writer.top_offset();
1637 1638
  output_frame->SetFp(fp_value);

1639
  DCHECK_EQ(output_frame_size_above_fp, frame_writer.top_offset());
1640

1641 1642
  if (FLAG_enable_embedded_constant_pool) {
    // Read the caller's constant pool from the previous frame.
1643 1644 1645 1646
    const intptr_t caller_cp =
        is_bottommost ? caller_constant_pool_
                      : output_[frame_index - 1]->GetConstantPool();
    frame_writer.PushCallerConstantPool(caller_cp);
1647 1648 1649
  }

  // A marker value is used in place of the context.
1650
  const intptr_t marker =
1651
      StackFrame::TypeToMarker(BuiltinContinuationModeToFrameType(mode));
1652 1653
  frame_writer.PushRawValue(marker,
                            "context (builtin continuation sentinel)\n");
1654

1655 1656 1657 1658 1659
  if (BuiltinContinuationModeIsJavaScript(mode)) {
    frame_writer.PushRawValue(maybe_function, "JSFunction\n");
  } else {
    frame_writer.PushRawValue(0, "unused\n");
  }
1660

1661 1662
  // The delta from the SP to the FP; used to reconstruct SP in
  // Isolate::UnwindAndFindHandler.
1663 1664
  frame_writer.PushRawObject(Smi::FromInt(output_frame_size_above_fp),
                             "frame height at deoptimization\n");
1665

1666 1667
  // The context even if this is a stub contininuation frame. We can't use the
  // usual context slot, because we must store the frame marker there.
1668 1669
  frame_writer.PushTranslatedValue(context_register_value,
                                   "builtin JavaScript context\n");
1670

1671
  // The builtin to continue to.
1672
  frame_writer.PushRawObject(builtin, "builtin address\n");
1673 1674 1675

  for (int i = 0; i < allocatable_register_count; ++i) {
    int code = config->GetAllocatableGeneralCode(i);
1676
    ScopedVector<char> str(128);
1677
    if (trace_scope_ != nullptr) {
1678
      if (BuiltinContinuationModeIsJavaScript(mode) &&
1679 1680 1681 1682
          code == kJavaScriptCallArgCountRegister.code()) {
        SNPrintF(
            str,
            "tagged argument count %s (will be untagged by continuation)\n",
1683
            RegisterName(Register::from_code(code)));
1684 1685
      } else {
        SNPrintF(str, "builtin register argument %s\n",
1686
                 RegisterName(Register::from_code(code)));
1687
      }
1688
    }
1689 1690
    frame_writer.PushTranslatedValue(
        register_values[code], trace_scope_ != nullptr ? str.start() : "");
1691 1692
  }

1693 1694 1695
  // Some architectures must pad the stack frame with extra stack slots
  // to ensure the stack frame is aligned.
  for (int i = 0; i < padding_slot_count; ++i) {
1696
    frame_writer.PushRawObject(roots.the_hole_value(), "padding\n");
1697 1698 1699 1700
  }

  if (is_topmost) {
    if (PadTopOfStackRegister()) {
1701
      frame_writer.PushRawObject(roots.the_hole_value(), "padding\n");
1702 1703
    }
    // Ensure the result is restored back when we return to the stub.
1704

1705
    if (must_handle_result) {
1706 1707 1708
      Register result_reg = kReturnRegister0;
      frame_writer.PushRawValue(input_->GetRegister(result_reg.code()),
                                "callback result\n");
1709
    } else {
1710
      frame_writer.PushRawObject(roots.undefined_value(), "callback result\n");
1711 1712 1713
    }
  }

1714
  CHECK_EQ(translated_frame->end(), value_iterator);
1715
  CHECK_EQ(0u, frame_writer.top_offset());
1716

1717
  // Clear the context register. The context might be a de-materialized object
1718
  // and will be materialized by {Runtime_NotifyDeoptimized}. For additional
1719 1720
  // safety we use Smi(0) instead of the potential {arguments_marker} here.
  if (is_topmost) {
1721
    intptr_t context_value = static_cast<intptr_t>(Smi::zero().ptr());
1722 1723 1724 1725
    Register context_reg = JavaScriptFrame::context_register();
    output_frame->SetRegister(context_reg.code(), context_value);
  }

1726 1727 1728
  // Ensure the frame pointer register points to the callee's frame. The builtin
  // will build its own frame once we continue to it.
  Register fp_reg = JavaScriptFrame::fp_register();
1729
  output_frame->SetRegister(fp_reg.code(), fp_value);
1730

1731
  Code continue_to_builtin = isolate()->builtins()->builtin(
1732
      TrampolineForBuiltinContinuation(mode, must_handle_result));
1733
  output_frame->SetPc(
1734
      static_cast<intptr_t>(continue_to_builtin->InstructionStart()));
1735

1736
  Code continuation =
1737
      isolate()->builtins()->builtin(Builtins::kNotifyDeoptimized);
1738
  output_frame->SetContinuation(
1739
      static_cast<intptr_t>(continuation->InstructionStart()));
1740
}
1741

1742
void Deoptimizer::MaterializeHeapObjects() {
1743
  translated_state_.Prepare(static_cast<Address>(stack_fp_));
1744 1745
  if (FLAG_deopt_every_n_times > 0) {
    // Doing a GC here will find problems with the deoptimized frames.
1746
    isolate_->heap()->CollectAllGarbage(Heap::kNoGCFlags,
1747
                                        GarbageCollectionReason::kTesting);
1748
  }
1749

1750 1751
  for (auto& materialization : values_to_materialize_) {
    Handle<Object> value = materialization.value_->GetValue();
1752

1753
    if (trace_scope_ != nullptr) {
1754
      PrintF("Materialization [" V8PRIxPTR_FMT "] <- " V8PRIxPTR_FMT " ;  ",
1755
             static_cast<intptr_t>(materialization.output_slot_address_),
1756
             value->ptr());
1757 1758
      value->ShortPrint(trace_scope_->file());
      PrintF(trace_scope_->file(), "\n");
1759
    }
1760

1761 1762
    *(reinterpret_cast<Address*>(materialization.output_slot_address_)) =
        value->ptr();
1763
  }
jarin@chromium.org's avatar
jarin@chromium.org committed
1764

1765 1766
  translated_state_.VerifyMaterializedObjects();

1767 1768 1769 1770 1771 1772
  bool feedback_updated = translated_state_.DoUpdateFeedback();
  if (trace_scope_ != nullptr && feedback_updated) {
    PrintF(trace_scope_->file(), "Feedback updated");
    compiled_code_->PrintDeoptLocation(trace_scope_->file(),
                                       " from deoptimization at ", from_);
  }
1773

1774
  isolate_->materialized_object_store()->Remove(
1775
      static_cast<Address>(stack_fp_));
1776 1777
}

1778
void Deoptimizer::QueueValueForMaterialization(
1779
    Address output_address, Object obj,
1780
    const TranslatedFrame::iterator& iterator) {
1781
  if (obj == ReadOnlyRoots(isolate_).arguments_marker()) {
1782 1783 1784
    values_to_materialize_.push_back({output_address, iterator});
  }
}
1785

1786
unsigned Deoptimizer::ComputeInputFrameAboveFpFixedSize() const {
1787
  unsigned fixed_size = CommonFrameConstants::kFixedFrameSizeAboveFp;
1788 1789
  // TODO(jkummerow): If {function_->IsSmi()} can indeed be true, then
  // {function_} should not have type {JSFunction}.
1790 1791 1792
  if (!function_->IsSmi()) {
    fixed_size += ComputeIncomingArgumentSize(function_->shared());
  }
1793 1794 1795 1796
  return fixed_size;
}

unsigned Deoptimizer::ComputeInputFrameSize() const {
1797 1798
  // The fp-to-sp delta already takes the context, constant pool pointer and the
  // function into account so we have to avoid double counting them.
1799 1800
  unsigned fixed_size_above_fp = ComputeInputFrameAboveFpFixedSize();
  unsigned result = fixed_size_above_fp + fp_to_sp_delta_;
1801 1802
  if (compiled_code_->kind() == Code::OPTIMIZED_FUNCTION) {
    unsigned stack_slots = compiled_code_->stack_slots();
1803 1804
    unsigned outgoing_size = 0;
    //        ComputeOutgoingArgumentSize(compiled_code_, bailout_id_);
1805
    CHECK_EQ(fixed_size_above_fp + (stack_slots * kSystemPointerSize) -
1806 1807
                 CommonFrameConstants::kFixedFrameSizeAboveFp + outgoing_size,
             result);
1808
  }
1809
  return result;
1810 1811
}

1812
// static
1813
unsigned Deoptimizer::ComputeInterpretedFixedSize(SharedFunctionInfo shared) {
1814
  // The fixed part of the frame consists of the return address, frame
1815
  // pointer, function, context, bytecode offset and all the incoming arguments.
1816
  return ComputeIncomingArgumentSize(shared) +
1817 1818 1819
         InterpreterFrameConstants::kFixedFrameSize;
}

1820
// static
1821
unsigned Deoptimizer::ComputeIncomingArgumentSize(SharedFunctionInfo shared) {
1822 1823
  int parameter_slots = shared->internal_formal_parameter_count() + 1;
  if (kPadArguments) parameter_slots = RoundUp(parameter_slots, 2);
1824
  return parameter_slots * kSystemPointerSize;
1825
}
1826

1827
void Deoptimizer::EnsureCodeForDeoptimizationEntry(Isolate* isolate,
1828 1829 1830
                                                   DeoptimizeKind kind) {
  CHECK(kind == DeoptimizeKind::kEager || kind == DeoptimizeKind::kSoft ||
        kind == DeoptimizeKind::kLazy);
1831
  DeoptimizerData* data = isolate->deoptimizer_data();
1832
  if (!data->deopt_entry_code(kind).is_null()) return;
1833

1834 1835
  MacroAssembler masm(isolate, CodeObjectRequired::kYes,
                      NewAssemblerBuffer(16 * KB));
1836
  masm.set_emit_debug_code(false);
1837
  GenerateDeoptimizationEntries(&masm, masm.isolate(), kind);
1838
  CodeDesc desc;
1839
  masm.GetCode(isolate, &desc);
1840
  DCHECK(!RelocInfo::RequiresRelocationAfterCodegen(desc));
1841

1842 1843 1844
  // Allocate the code as immovable since the entry addresses will be used
  // directly and there is no support for relocating them.
  Handle<Code> code = isolate->factory()->NewCode(
1845
      desc, Code::STUB, Handle<Object>(), Builtins::kNoBuiltinId,
1846
      MaybeHandle<ByteArray>(), MaybeHandle<DeoptimizationData>(), kImmovable);
1847
  CHECK(isolate->heap()->IsImmovable(*code));
1848

1849
  CHECK(data->deopt_entry_code(kind).is_null());
1850
  data->set_deopt_entry_code(kind, *code);
1851
}
1852

1853
void Deoptimizer::EnsureCodeForDeoptimizationEntries(Isolate* isolate) {
1854 1855 1856
  EnsureCodeForDeoptimizationEntry(isolate, DeoptimizeKind::kEager);
  EnsureCodeForDeoptimizationEntry(isolate, DeoptimizeKind::kLazy);
  EnsureCodeForDeoptimizationEntry(isolate, DeoptimizeKind::kSoft);
1857 1858
}

1859
FrameDescription::FrameDescription(uint32_t frame_size, int parameter_count)
1860
    : frame_size_(frame_size),
1861
      parameter_count_(parameter_count),
1862 1863
      top_(kZapUint32),
      pc_(kZapUint32),
1864
      fp_(kZapUint32),
1865 1866
      context_(kZapUint32),
      constant_pool_(kZapUint32) {
1867 1868
  // Zap all the registers.
  for (int r = 0; r < Register::kNumRegisters; r++) {
1869 1870 1871
    // TODO(jbramley): It isn't safe to use kZapUint32 here. If the register
    // isn't used before the next safepoint, the GC will try to scan it as a
    // tagged value. kZapUint32 looks like a valid tagged pointer, but it isn't.
1872 1873 1874 1875 1876 1877 1878
#if defined(V8_OS_WIN) && defined(V8_TARGET_ARCH_ARM64)
    // x18 is reserved as platform register on Windows arm64 platform
    const int kPlatformRegister = 18;
    if (r != kPlatformRegister) {
      SetRegister(r, kZapUint32);
    }
#else
1879
    SetRegister(r, kZapUint32);
1880
#endif
1881 1882 1883
  }

  // Zap all the slots.
1884
  for (unsigned o = 0; o < frame_size; o += kSystemPointerSize) {
1885 1886 1887 1888
    SetFrameSlot(o, kZapUint32);
  }
}

1889
void TranslationBuffer::Add(int32_t value) {
1890
  // This wouldn't handle kMinInt correctly if it ever encountered it.
1891
  DCHECK_NE(value, kMinInt);
1892 1893
  // Encode the sign bit in the least significant bit.
  bool is_negative = (value < 0);
1894 1895
  uint32_t bits = (static_cast<uint32_t>(is_negative ? -value : value) << 1) |
                  static_cast<uint32_t>(is_negative);
1896 1897 1898 1899
  // Encode the individual bytes using the least significant bit of
  // each byte to indicate whether or not more bytes follow.
  do {
    uint32_t next = bits >> 7;
1900
    contents_.push_back(((bits << 1) & 0xFF) | (next != 0));
1901 1902 1903 1904
    bits = next;
  } while (bits != 0);
}

1905
TranslationIterator::TranslationIterator(ByteArray buffer, int index)
1906 1907 1908
    : buffer_(buffer), index_(index) {
  DCHECK(index >= 0 && index < buffer->length());
}
1909 1910 1911 1912 1913 1914

int32_t TranslationIterator::Next() {
  // Run through the bytes until we reach one with a least significant
  // bit of zero (marks the end).
  uint32_t bits = 0;
  for (int i = 0; true; i += 7) {
1915
    DCHECK(HasNext());
1916 1917 1918 1919 1920 1921 1922 1923 1924 1925
    uint8_t next = buffer_->get(index_++);
    bits |= (next >> 1) << i;
    if ((next & 1) == 0) break;
  }
  // The bits encode the sign in the least significant bit.
  bool is_negative = (bits & 1) == 1;
  int32_t result = bits >> 1;
  return is_negative ? -result : result;
}

1926
bool TranslationIterator::HasNext() const { return index_ < buffer_->length(); }
1927

1928
Handle<ByteArray> TranslationBuffer::CreateByteArray(Factory* factory) {
1929 1930
  Handle<ByteArray> result = factory->NewByteArray(CurrentIndex(), TENURED);
  contents_.CopyTo(result->GetDataStartAddress());
1931 1932 1933
  return result;
}

1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951
void Translation::BeginBuiltinContinuationFrame(BailoutId bailout_id,
                                                int literal_id,
                                                unsigned height) {
  buffer_->Add(BUILTIN_CONTINUATION_FRAME);
  buffer_->Add(bailout_id.ToInt());
  buffer_->Add(literal_id);
  buffer_->Add(height);
}

void Translation::BeginJavaScriptBuiltinContinuationFrame(BailoutId bailout_id,
                                                          int literal_id,
                                                          unsigned height) {
  buffer_->Add(JAVA_SCRIPT_BUILTIN_CONTINUATION_FRAME);
  buffer_->Add(bailout_id.ToInt());
  buffer_->Add(literal_id);
  buffer_->Add(height);
}

1952 1953 1954 1955 1956 1957 1958 1959
void Translation::BeginJavaScriptBuiltinContinuationWithCatchFrame(
    BailoutId bailout_id, int literal_id, unsigned height) {
  buffer_->Add(JAVA_SCRIPT_BUILTIN_CONTINUATION_WITH_CATCH_FRAME);
  buffer_->Add(bailout_id.ToInt());
  buffer_->Add(literal_id);
  buffer_->Add(height);
}

1960 1961
void Translation::BeginConstructStubFrame(BailoutId bailout_id, int literal_id,
                                          unsigned height) {
1962
  buffer_->Add(CONSTRUCT_STUB_FRAME);
1963
  buffer_->Add(bailout_id.ToInt());
1964 1965
  buffer_->Add(literal_id);
  buffer_->Add(height);
1966 1967 1968
}


1969
void Translation::BeginArgumentsAdaptorFrame(int literal_id, unsigned height) {
1970 1971 1972
  buffer_->Add(ARGUMENTS_ADAPTOR_FRAME);
  buffer_->Add(literal_id);
  buffer_->Add(height);
1973 1974
}

1975
void Translation::BeginInterpretedFrame(BailoutId bytecode_offset,
1976 1977 1978
                                        int literal_id, unsigned height,
                                        int return_value_offset,
                                        int return_value_count) {
1979 1980 1981 1982
  buffer_->Add(INTERPRETED_FRAME);
  buffer_->Add(bytecode_offset.ToInt());
  buffer_->Add(literal_id);
  buffer_->Add(height);
1983 1984
  buffer_->Add(return_value_offset);
  buffer_->Add(return_value_count);
1985 1986
}

1987
void Translation::ArgumentsElements(CreateArgumentsType type) {
1988
  buffer_->Add(ARGUMENTS_ELEMENTS);
1989
  buffer_->Add(static_cast<uint8_t>(type));
1990
}
1991

1992
void Translation::ArgumentsLength(CreateArgumentsType type) {
1993
  buffer_->Add(ARGUMENTS_LENGTH);
1994
  buffer_->Add(static_cast<uint8_t>(type));
1995 1996
}

1997
void Translation::BeginCapturedObject(int length) {
1998 1999
  buffer_->Add(CAPTURED_OBJECT);
  buffer_->Add(length);
2000 2001 2002 2003
}


void Translation::DuplicateObject(int object_index) {
2004 2005
  buffer_->Add(DUPLICATED_OBJECT);
  buffer_->Add(object_index);
2006 2007 2008
}


2009
void Translation::StoreRegister(Register reg) {
2010 2011
  buffer_->Add(REGISTER);
  buffer_->Add(reg.code());
2012 2013 2014 2015
}


void Translation::StoreInt32Register(Register reg) {
2016 2017
  buffer_->Add(INT32_REGISTER);
  buffer_->Add(reg.code());
2018 2019
}

2020 2021 2022 2023
void Translation::StoreInt64Register(Register reg) {
  buffer_->Add(INT64_REGISTER);
  buffer_->Add(reg.code());
}
2024

2025
void Translation::StoreUint32Register(Register reg) {
2026 2027
  buffer_->Add(UINT32_REGISTER);
  buffer_->Add(reg.code());
2028 2029 2030
}


2031
void Translation::StoreBoolRegister(Register reg) {
2032 2033
  buffer_->Add(BOOL_REGISTER);
  buffer_->Add(reg.code());
2034 2035
}

2036
void Translation::StoreFloatRegister(FloatRegister reg) {
2037 2038
  buffer_->Add(FLOAT_REGISTER);
  buffer_->Add(reg.code());
2039
}
2040

2041
void Translation::StoreDoubleRegister(DoubleRegister reg) {
2042 2043
  buffer_->Add(DOUBLE_REGISTER);
  buffer_->Add(reg.code());
2044 2045 2046 2047
}


void Translation::StoreStackSlot(int index) {
2048 2049
  buffer_->Add(STACK_SLOT);
  buffer_->Add(index);
2050 2051 2052 2053
}


void Translation::StoreInt32StackSlot(int index) {
2054 2055
  buffer_->Add(INT32_STACK_SLOT);
  buffer_->Add(index);
2056 2057
}

2058 2059 2060 2061
void Translation::StoreInt64StackSlot(int index) {
  buffer_->Add(INT64_STACK_SLOT);
  buffer_->Add(index);
}
2062

2063
void Translation::StoreUint32StackSlot(int index) {
2064 2065
  buffer_->Add(UINT32_STACK_SLOT);
  buffer_->Add(index);
2066 2067 2068
}


2069
void Translation::StoreBoolStackSlot(int index) {
2070 2071
  buffer_->Add(BOOL_STACK_SLOT);
  buffer_->Add(index);
2072 2073
}

2074
void Translation::StoreFloatStackSlot(int index) {
2075 2076
  buffer_->Add(FLOAT_STACK_SLOT);
  buffer_->Add(index);
2077
}
2078

2079
void Translation::StoreDoubleStackSlot(int index) {
2080 2081
  buffer_->Add(DOUBLE_STACK_SLOT);
  buffer_->Add(index);
2082 2083 2084 2085
}


void Translation::StoreLiteral(int literal_id) {
2086 2087
  buffer_->Add(LITERAL);
  buffer_->Add(literal_id);
2088 2089
}

2090 2091 2092 2093 2094
void Translation::AddUpdateFeedback(int vector_literal, int slot) {
  buffer_->Add(UPDATE_FEEDBACK);
  buffer_->Add(vector_literal);
  buffer_->Add(slot);
}
2095

2096
void Translation::StoreJSFrameFunction() {
2097
  StoreStackSlot((StandardFrameConstants::kCallerPCOffset -
2098
                  StandardFrameConstants::kFunctionOffset) /
2099
                 kSystemPointerSize);
2100 2101
}

2102 2103
int Translation::NumberOfOperandsFor(Opcode opcode) {
  switch (opcode) {
2104
    case DUPLICATED_OBJECT:
2105 2106
    case ARGUMENTS_ELEMENTS:
    case ARGUMENTS_LENGTH:
2107
    case CAPTURED_OBJECT:
2108 2109
    case REGISTER:
    case INT32_REGISTER:
2110
    case INT64_REGISTER:
2111
    case UINT32_REGISTER:
2112
    case BOOL_REGISTER:
2113
    case FLOAT_REGISTER:
2114 2115 2116
    case DOUBLE_REGISTER:
    case STACK_SLOT:
    case INT32_STACK_SLOT:
2117
    case INT64_STACK_SLOT:
2118
    case UINT32_STACK_SLOT:
2119
    case BOOL_STACK_SLOT:
2120
    case FLOAT_STACK_SLOT:
2121 2122 2123
    case DOUBLE_STACK_SLOT:
    case LITERAL:
      return 1;
2124
    case ARGUMENTS_ADAPTOR_FRAME:
2125
    case UPDATE_FEEDBACK:
2126
      return 2;
2127
    case BEGIN:
2128
    case CONSTRUCT_STUB_FRAME:
2129 2130
    case BUILTIN_CONTINUATION_FRAME:
    case JAVA_SCRIPT_BUILTIN_CONTINUATION_FRAME:
2131
    case JAVA_SCRIPT_BUILTIN_CONTINUATION_WITH_CATCH_FRAME:
2132
      return 3;
2133 2134
    case INTERPRETED_FRAME:
      return 5;
2135
  }
2136
  FATAL("Unexpected translation type");
2137 2138 2139 2140
  return -1;
}


2141
#if defined(OBJECT_PRINT) || defined(ENABLE_DISASSEMBLER)
2142 2143

const char* Translation::StringFor(Opcode opcode) {
2144
#define TRANSLATION_OPCODE_CASE(item)   case item: return #item;
2145
  switch (opcode) {
2146
    TRANSLATION_OPCODE_LIST(TRANSLATION_OPCODE_CASE)
2147
  }
2148
#undef TRANSLATION_OPCODE_CASE
2149 2150 2151 2152 2153 2154
  UNREACHABLE();
}

#endif


jarin@chromium.org's avatar
jarin@chromium.org committed
2155 2156 2157 2158 2159 2160
Handle<FixedArray> MaterializedObjectStore::Get(Address fp) {
  int index = StackIdToIndex(fp);
  if (index == -1) {
    return Handle<FixedArray>::null();
  }
  Handle<FixedArray> array = GetStackEntries();
2161
  CHECK_GT(array->length(), index);
2162
  return Handle<FixedArray>::cast(Handle<Object>(array->get(index), isolate()));
jarin@chromium.org's avatar
jarin@chromium.org committed
2163 2164 2165 2166
}


void MaterializedObjectStore::Set(Address fp,
2167
                                  Handle<FixedArray> materialized_objects) {
jarin@chromium.org's avatar
jarin@chromium.org committed
2168 2169
  int index = StackIdToIndex(fp);
  if (index == -1) {
2170 2171
    index = static_cast<int>(frame_fps_.size());
    frame_fps_.push_back(fp);
jarin@chromium.org's avatar
jarin@chromium.org committed
2172 2173 2174 2175 2176 2177 2178
  }

  Handle<FixedArray> array = EnsureStackEntries(index + 1);
  array->set(index, *materialized_objects);
}


2179
bool MaterializedObjectStore::Remove(Address fp) {
2180 2181 2182
  auto it = std::find(frame_fps_.begin(), frame_fps_.end(), fp);
  if (it == frame_fps_.end()) return false;
  int index = static_cast<int>(std::distance(frame_fps_.begin(), it));
jarin@chromium.org's avatar
jarin@chromium.org committed
2183

2184
  frame_fps_.erase(it);
2185
  FixedArray array = isolate()->heap()->materialized_objects();
2186

2187
  CHECK_LT(index, array->length());
2188 2189
  int fps_size = static_cast<int>(frame_fps_.size());
  for (int i = index; i < fps_size; i++) {
jarin@chromium.org's avatar
jarin@chromium.org committed
2190 2191
    array->set(i, array->get(i + 1));
  }
2192
  array->set(fps_size, ReadOnlyRoots(isolate()).undefined_value());
2193
  return true;
jarin@chromium.org's avatar
jarin@chromium.org committed
2194 2195 2196 2197
}


int MaterializedObjectStore::StackIdToIndex(Address fp) {
2198 2199 2200 2201
  auto it = std::find(frame_fps_.begin(), frame_fps_.end(), fp);
  return it == frame_fps_.end()
             ? -1
             : static_cast<int>(std::distance(frame_fps_.begin(), it));
jarin@chromium.org's avatar
jarin@chromium.org committed
2202 2203 2204 2205
}


Handle<FixedArray> MaterializedObjectStore::GetStackEntries() {
2206 2207
  return Handle<FixedArray>(isolate()->heap()->materialized_objects(),
                            isolate());
jarin@chromium.org's avatar
jarin@chromium.org committed
2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226
}


Handle<FixedArray> MaterializedObjectStore::EnsureStackEntries(int length) {
  Handle<FixedArray> array = GetStackEntries();
  if (array->length() >= length) {
    return array;
  }

  int new_length = length > 10 ? length : 10;
  if (new_length < 2 * array->length()) {
    new_length = 2 * array->length();
  }

  Handle<FixedArray> new_array =
      isolate()->factory()->NewFixedArray(new_length, TENURED);
  for (int i = 0; i < array->length(); i++) {
    new_array->set(i, array->get(i));
  }
2227
  HeapObject undefined_value = ReadOnlyRoots(isolate()).undefined_value();
jarin@chromium.org's avatar
jarin@chromium.org committed
2228
  for (int i = array->length(); i < length; i++) {
2229
    new_array->set(i, undefined_value);
jarin@chromium.org's avatar
jarin@chromium.org committed
2230
  }
2231
  isolate()->heap()->SetRootMaterializedObjects(*new_array);
jarin@chromium.org's avatar
jarin@chromium.org committed
2232
  return new_array;
2233 2234
}

2235
namespace {
2236

2237 2238
Handle<Object> GetValueForDebugger(TranslatedFrame::iterator it,
                                   Isolate* isolate) {
2239
  if (it->GetRawValue() == ReadOnlyRoots(isolate).arguments_marker()) {
2240
    if (!it->IsMaterializableByDebugger()) {
2241
      return isolate->factory()->optimized_out();
2242
    }
2243
  }
2244 2245
  return it->GetValue();
}
2246

2247 2248 2249 2250 2251
}  // namespace

DeoptimizedFrameInfo::DeoptimizedFrameInfo(TranslatedState* state,
                                           TranslatedState::iterator frame_it,
                                           Isolate* isolate) {
2252 2253 2254
  int parameter_count =
      frame_it->shared_info()->internal_formal_parameter_count();
  TranslatedFrame::iterator stack_it = frame_it->begin();
2255

2256 2257 2258 2259 2260 2261
  // Get the function. Note that this might materialize the function.
  // In case the debugger mutates this value, we should deoptimize
  // the function and remember the value in the materialized value store.
  function_ = Handle<JSFunction>::cast(stack_it->GetValue());
  stack_it++;  // Skip the function.
  stack_it++;  // Skip the receiver.
2262

2263 2264 2265
  DCHECK_EQ(TranslatedFrame::kInterpretedFunction, frame_it->kind());
  source_position_ = Deoptimizer::ComputeSourcePositionFromBytecodeArray(
      *frame_it->shared_info(), frame_it->node_id());
2266

2267 2268
  DCHECK_EQ(parameter_count,
            function_->shared()->internal_formal_parameter_count());
2269 2270 2271

  parameters_.resize(static_cast<size_t>(parameter_count));
  for (int i = 0; i < parameter_count; i++) {
2272
    Handle<Object> parameter = GetValueForDebugger(stack_it, isolate);
2273 2274 2275 2276 2277 2278 2279 2280 2281 2282
    SetParameter(i, parameter);
    stack_it++;
  }

  // Get the context.
  context_ = GetValueForDebugger(stack_it, isolate);
  stack_it++;

  // Get the expression stack.
  int stack_height = frame_it->height();
2283
  if (frame_it->kind() == TranslatedFrame::kInterpretedFunction) {
2284
    // For interpreter frames, we should not count the accumulator.
2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295
    // TODO(jarin): Clean up the indexing in translated frames.
    stack_height--;
  }
  expression_stack_.resize(static_cast<size_t>(stack_height));
  for (int i = 0; i < stack_height; i++) {
    Handle<Object> expression = GetValueForDebugger(stack_it, isolate);
    SetExpression(i, expression);
    stack_it++;
  }

  // For interpreter frame, skip the accumulator.
2296
  if (frame_it->kind() == TranslatedFrame::kInterpretedFunction) {
2297 2298 2299
    stack_it++;
  }
  CHECK(stack_it == frame_it->end());
2300 2301
}

2302
Deoptimizer::DeoptInfo Deoptimizer::GetDeoptInfo(Code code, Address pc) {
2303
  CHECK(code->InstructionStart() <= pc && pc <= code->InstructionEnd());
2304
  SourcePosition last_position = SourcePosition::Unknown();
2305
  DeoptimizeReason last_reason = DeoptimizeReason::kUnknown;
2306
  int last_deopt_id = kNoDeoptimizationId;
2307
  int mask = RelocInfo::ModeMask(RelocInfo::DEOPT_REASON) |
2308
             RelocInfo::ModeMask(RelocInfo::DEOPT_ID) |
2309 2310
             RelocInfo::ModeMask(RelocInfo::DEOPT_SCRIPT_OFFSET) |
             RelocInfo::ModeMask(RelocInfo::DEOPT_INLINING_ID);
2311 2312
  for (RelocIterator it(code, mask); !it.done(); it.next()) {
    RelocInfo* info = it.rinfo();
2313
    if (info->pc() >= pc) break;
2314 2315 2316 2317 2318 2319
    if (info->rmode() == RelocInfo::DEOPT_SCRIPT_OFFSET) {
      int script_offset = static_cast<int>(info->data());
      it.next();
      DCHECK(it.rinfo()->rmode() == RelocInfo::DEOPT_INLINING_ID);
      int inlining_id = static_cast<int>(it.rinfo()->data());
      last_position = SourcePosition(script_offset, inlining_id);
2320
    } else if (info->rmode() == RelocInfo::DEOPT_ID) {
2321
      last_deopt_id = static_cast<int>(info->data());
2322
    } else if (info->rmode() == RelocInfo::DEOPT_REASON) {
2323
      last_reason = static_cast<DeoptimizeReason>(info->data());
2324 2325
    }
  }
2326
  return DeoptInfo(last_position, last_reason, last_deopt_id);
2327
}
2328 2329


2330 2331
// static
int Deoptimizer::ComputeSourcePositionFromBytecodeArray(
2332
    SharedFunctionInfo shared, BailoutId node_id) {
2333
  DCHECK(shared->HasBytecodeArray());
2334
  return AbstractCode::cast(shared->GetBytecodeArray())
2335
      ->SourcePosition(node_id.ToInt());
2336 2337
}

2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356
// static
TranslatedValue TranslatedValue::NewDeferredObject(TranslatedState* container,
                                                   int length,
                                                   int object_index) {
  TranslatedValue slot(container, kCapturedObject);
  slot.materialization_info_ = {object_index, length};
  return slot;
}


// static
TranslatedValue TranslatedValue::NewDuplicateObject(TranslatedState* container,
                                                    int id) {
  TranslatedValue slot(container, kDuplicatedObject);
  slot.materialization_info_ = {id, -1};
  return slot;
}


2357 2358
// static
TranslatedValue TranslatedValue::NewFloat(TranslatedState* container,
2359
                                          Float32 value) {
2360 2361 2362 2363 2364
  TranslatedValue slot(container, kFloat);
  slot.float_value_ = value;
  return slot;
}

2365 2366
// static
TranslatedValue TranslatedValue::NewDouble(TranslatedState* container,
2367
                                           Float64 value) {
2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381
  TranslatedValue slot(container, kDouble);
  slot.double_value_ = value;
  return slot;
}


// static
TranslatedValue TranslatedValue::NewInt32(TranslatedState* container,
                                          int32_t value) {
  TranslatedValue slot(container, kInt32);
  slot.int32_value_ = value;
  return slot;
}

2382 2383 2384 2385 2386 2387 2388
// static
TranslatedValue TranslatedValue::NewInt64(TranslatedState* container,
                                          int64_t value) {
  TranslatedValue slot(container, kInt64);
  slot.int64_value_ = value;
  return slot;
}
2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409

// static
TranslatedValue TranslatedValue::NewUInt32(TranslatedState* container,
                                           uint32_t value) {
  TranslatedValue slot(container, kUInt32);
  slot.uint32_value_ = value;
  return slot;
}


// static
TranslatedValue TranslatedValue::NewBool(TranslatedState* container,
                                         uint32_t value) {
  TranslatedValue slot(container, kBoolBit);
  slot.uint32_value_ = value;
  return slot;
}


// static
TranslatedValue TranslatedValue::NewTagged(TranslatedState* container,
2410
                                           Object literal) {
2411 2412 2413 2414 2415 2416
  TranslatedValue slot(container, kTagged);
  slot.raw_literal_ = literal;
  return slot;
}

// static
2417 2418
TranslatedValue TranslatedValue::NewInvalid(TranslatedState* container) {
  return TranslatedValue(container, kInvalid);
2419 2420 2421 2422 2423
}


Isolate* TranslatedValue::isolate() const { return container_->isolate(); }

2424
Object TranslatedValue::raw_literal() const {
2425 2426 2427 2428 2429 2430 2431 2432 2433
  DCHECK_EQ(kTagged, kind());
  return raw_literal_;
}

int32_t TranslatedValue::int32_value() const {
  DCHECK_EQ(kInt32, kind());
  return int32_value_;
}

2434 2435 2436 2437
int64_t TranslatedValue::int64_value() const {
  DCHECK_EQ(kInt64, kind());
  return int64_value_;
}
2438 2439 2440 2441 2442 2443

uint32_t TranslatedValue::uint32_value() const {
  DCHECK(kind() == kUInt32 || kind() == kBoolBit);
  return uint32_value_;
}

2444
Float32 TranslatedValue::float_value() const {
2445 2446 2447
  DCHECK_EQ(kFloat, kind());
  return float_value_;
}
2448

2449
Float64 TranslatedValue::double_value() const {
2450 2451 2452 2453 2454 2455
  DCHECK_EQ(kDouble, kind());
  return double_value_;
}


int TranslatedValue::object_length() const {
2456
  DCHECK_EQ(kind(), kCapturedObject);
2457 2458 2459 2460 2461
  return materialization_info_.length_;
}


int TranslatedValue::object_index() const {
2462
  DCHECK(kind() == kCapturedObject || kind() == kDuplicatedObject);
2463 2464 2465
  return materialization_info_.id_;
}

2466
Object TranslatedValue::GetRawValue() const {
2467
  // If we have a value, return it.
2468 2469
  if (materialization_state() == kFinished) {
    return *storage_;
2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484
  }

  // Otherwise, do a best effort to get the value without allocation.
  switch (kind()) {
    case kTagged:
      return raw_literal();

    case kInt32: {
      bool is_smi = Smi::IsValid(int32_value());
      if (is_smi) {
        return Smi::FromInt(int32_value());
      }
      break;
    }

2485 2486 2487 2488 2489 2490 2491 2492 2493
    case kInt64: {
      bool is_smi = (int64_value() >= static_cast<int64_t>(Smi::kMinValue) &&
                     int64_value() <= static_cast<int64_t>(Smi::kMaxValue));
      if (is_smi) {
        return Smi::FromIntptr(static_cast<intptr_t>(int64_value()));
      }
      break;
    }

2494 2495 2496 2497 2498 2499 2500 2501 2502 2503
    case kUInt32: {
      bool is_smi = (uint32_value() <= static_cast<uintptr_t>(Smi::kMaxValue));
      if (is_smi) {
        return Smi::FromInt(static_cast<int32_t>(uint32_value()));
      }
      break;
    }

    case kBoolBit: {
      if (uint32_value() == 0) {
2504
        return ReadOnlyRoots(isolate()).false_value();
2505
      } else {
2506
        CHECK_EQ(1U, uint32_value());
2507
        return ReadOnlyRoots(isolate()).true_value();
2508 2509 2510 2511 2512 2513 2514 2515 2516
      }
    }

    default:
      break;
  }

  // If we could not get the value without allocation, return the arguments
  // marker.
2517
  return ReadOnlyRoots(isolate()).arguments_marker();
2518 2519
}

2520 2521 2522 2523 2524
void TranslatedValue::set_initialized_storage(Handle<Object> storage) {
  DCHECK_EQ(kUninitialized, materialization_state());
  storage_ = storage;
  materialization_state_ = kFinished;
}
2525 2526 2527

Handle<Object> TranslatedValue::GetValue() {
  // If we already have a value, then get it.
2528
  if (materialization_state() == kFinished) return storage_;
2529 2530 2531 2532 2533

  // Otherwise we have to materialize.
  switch (kind()) {
    case TranslatedValue::kTagged:
    case TranslatedValue::kInt32:
2534
    case TranslatedValue::kInt64:
2535 2536
    case TranslatedValue::kUInt32:
    case TranslatedValue::kBoolBit:
2537
    case TranslatedValue::kFloat:
2538 2539
    case TranslatedValue::kDouble: {
      MaterializeSimple();
2540
      return storage_;
2541 2542 2543
    }

    case TranslatedValue::kCapturedObject:
2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560
    case TranslatedValue::kDuplicatedObject: {
      // We need to materialize the object (or possibly even object graphs).
      // To make the object verifier happy, we materialize in two steps.

      // 1. Allocate storage for reachable objects. This makes sure that for
      //    each object we have allocated space on heap. The space will be
      //    a byte array that will be later initialized, or a fully
      //    initialized object if it is safe to allocate one that will
      //    pass the verifier.
      container_->EnsureObjectAllocatedAt(this);

      // 2. Initialize the objects. If we have allocated only byte arrays
      //    for some objects, we now overwrite the byte arrays with the
      //    correct object fields. Note that this phase does not allocate
      //    any new objects, so it does not trigger the object verifier.
      return container_->InitializeObjectAt(this);
    }
2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572

    case TranslatedValue::kInvalid:
      FATAL("unexpected case");
      return Handle<Object>::null();
  }

  FATAL("internal error: value missing");
  return Handle<Object>::null();
}

void TranslatedValue::MaterializeSimple() {
  // If we already have materialized, return.
2573
  if (materialization_state() == kFinished) return;
2574

2575
  Object raw_value = GetRawValue();
2576
  if (raw_value != ReadOnlyRoots(isolate()).arguments_marker()) {
2577
    // We can get the value without allocation, just return it here.
2578
    set_initialized_storage(Handle<Object>(raw_value, isolate()));
2579 2580 2581 2582
    return;
  }

  switch (kind()) {
2583
    case kInt32:
2584 2585
      set_initialized_storage(
          Handle<Object>(isolate()->factory()->NewNumber(int32_value())));
2586 2587
      return;

2588 2589 2590 2591 2592
    case kInt64:
      set_initialized_storage(Handle<Object>(
          isolate()->factory()->NewNumber(static_cast<double>(int64_value()))));
      return;

2593
    case kUInt32:
2594 2595
      set_initialized_storage(
          Handle<Object>(isolate()->factory()->NewNumber(uint32_value())));
2596 2597
      return;

2598 2599
    case kFloat: {
      double scalar_value = float_value().get_scalar();
2600 2601
      set_initialized_storage(
          Handle<Object>(isolate()->factory()->NewNumber(scalar_value)));
2602
      return;
2603
    }
2604

2605 2606
    case kDouble: {
      double scalar_value = double_value().get_scalar();
2607 2608
      set_initialized_storage(
          Handle<Object>(isolate()->factory()->NewNumber(scalar_value)));
2609
      return;
2610
    }
2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632

    case kCapturedObject:
    case kDuplicatedObject:
    case kInvalid:
    case kTagged:
    case kBoolBit:
      FATAL("internal error: unexpected materialization.");
      break;
  }
}


bool TranslatedValue::IsMaterializedObject() const {
  switch (kind()) {
    case kCapturedObject:
    case kDuplicatedObject:
      return true;
    default:
      return false;
  }
}

2633 2634 2635 2636
bool TranslatedValue::IsMaterializableByDebugger() const {
  // At the moment, we only allow materialization of doubles.
  return (kind() == kDouble);
}
2637 2638

int TranslatedValue::GetChildrenCount() const {
2639
  if (kind() == kCapturedObject) {
2640 2641 2642 2643 2644 2645
    return object_length();
  } else {
    return 0;
  }
}

2646
uint64_t TranslatedState::GetUInt64Slot(Address fp, int slot_offset) {
2647 2648 2649
#if V8_TARGET_ARCH_32_BIT
  return ReadUnalignedValue<uint64_t>(fp + slot_offset);
#else
2650
  return Memory<uint64_t>(fp + slot_offset);
2651
#endif
2652
}
2653 2654 2655 2656

uint32_t TranslatedState::GetUInt32Slot(Address fp, int slot_offset) {
  Address address = fp + slot_offset;
#if V8_TARGET_BIG_ENDIAN && V8_HOST_ARCH_64_BIT
2657
  return Memory<uint32_t>(address + kIntSize);
2658
#else
2659
  return Memory<uint32_t>(address);
2660 2661 2662
#endif
}

2663
Float32 TranslatedState::GetFloatSlot(Address fp, int slot_offset) {
2664
#if !V8_TARGET_ARCH_S390X && !V8_TARGET_ARCH_PPC64
2665
  return Float32::FromBits(GetUInt32Slot(fp, slot_offset));
2666
#else
2667
  return Float32::FromBits(Memory<uint32_t>(fp + slot_offset));
2668
#endif
2669 2670 2671
}

Float64 TranslatedState::GetDoubleSlot(Address fp, int slot_offset) {
2672
  return Float64::FromBits(GetUInt64Slot(fp, slot_offset));
2673
}
2674 2675 2676

void TranslatedValue::Handlify() {
  if (kind() == kTagged) {
2677
    set_initialized_storage(Handle<Object>(raw_literal(), isolate()));
2678
    raw_literal_ = Object();
2679 2680 2681
  }
}

2682
TranslatedFrame TranslatedFrame::InterpretedFrame(
2683
    BailoutId bytecode_offset, SharedFunctionInfo shared_info, int height,
2684 2685 2686
    int return_value_offset, int return_value_count) {
  TranslatedFrame frame(kInterpretedFunction, shared_info, height,
                        return_value_offset, return_value_count);
2687 2688 2689 2690
  frame.node_id_ = bytecode_offset;
  return frame;
}

2691
TranslatedFrame TranslatedFrame::ArgumentsAdaptorFrame(
2692
    SharedFunctionInfo shared_info, int height) {
2693
  return TranslatedFrame(kArgumentsAdaptor, shared_info, height);
2694 2695
}

2696
TranslatedFrame TranslatedFrame::ConstructStubFrame(
2697
    BailoutId bailout_id, SharedFunctionInfo shared_info, int height) {
2698
  TranslatedFrame frame(kConstructStub, shared_info, height);
2699 2700
  frame.node_id_ = bailout_id;
  return frame;
2701 2702
}

2703
TranslatedFrame TranslatedFrame::BuiltinContinuationFrame(
2704
    BailoutId bailout_id, SharedFunctionInfo shared_info, int height) {
2705
  TranslatedFrame frame(kBuiltinContinuation, shared_info, height);
2706 2707 2708 2709 2710
  frame.node_id_ = bailout_id;
  return frame;
}

TranslatedFrame TranslatedFrame::JavaScriptBuiltinContinuationFrame(
2711
    BailoutId bailout_id, SharedFunctionInfo shared_info, int height) {
2712
  TranslatedFrame frame(kJavaScriptBuiltinContinuation, shared_info, height);
2713 2714 2715
  frame.node_id_ = bailout_id;
  return frame;
}
2716

2717
TranslatedFrame TranslatedFrame::JavaScriptBuiltinContinuationWithCatchFrame(
2718
    BailoutId bailout_id, SharedFunctionInfo shared_info, int height) {
2719 2720 2721 2722 2723 2724
  TranslatedFrame frame(kJavaScriptBuiltinContinuationWithCatch, shared_info,
                        height);
  frame.node_id_ = bailout_id;
  return frame;
}

2725 2726
int TranslatedFrame::GetValueCount() {
  switch (kind()) {
2727 2728 2729
    case kInterpretedFunction: {
      int parameter_count =
          raw_shared_info_->internal_formal_parameter_count() + 1;
2730 2731
      // + 2 for function and context.
      return height_ + parameter_count + 2;
2732 2733
    }

2734 2735
    case kArgumentsAdaptor:
    case kConstructStub:
2736 2737
    case kBuiltinContinuation:
    case kJavaScriptBuiltinContinuation:
2738
    case kJavaScriptBuiltinContinuationWithCatch:
2739 2740
      return 1 + height_;

2741 2742 2743 2744 2745 2746 2747 2748
    case kInvalid:
      UNREACHABLE();
      break;
  }
  UNREACHABLE();
}


2749
void TranslatedFrame::Handlify() {
2750
  if (!raw_shared_info_.is_null()) {
2751 2752
    shared_info_ = Handle<SharedFunctionInfo>(raw_shared_info_,
                                              raw_shared_info_->GetIsolate());
2753
    raw_shared_info_ = SharedFunctionInfo();
2754 2755 2756 2757 2758 2759 2760
  }
  for (auto& value : values_) {
    value.Handlify();
  }
}

TranslatedFrame TranslatedState::CreateNextTranslatedFrame(
2761
    TranslationIterator* iterator, FixedArray literal_array, Address fp,
2762
    FILE* trace_file) {
2763 2764 2765
  Translation::Opcode opcode =
      static_cast<Translation::Opcode>(iterator->Next());
  switch (opcode) {
2766 2767
    case Translation::INTERPRETED_FRAME: {
      BailoutId bytecode_offset = BailoutId(iterator->Next());
2768
      SharedFunctionInfo shared_info =
2769 2770
          SharedFunctionInfo::cast(literal_array->get(iterator->Next()));
      int height = iterator->Next();
2771 2772
      int return_value_offset = iterator->Next();
      int return_value_count = iterator->Next();
2773
      if (trace_file != nullptr) {
2774
        std::unique_ptr<char[]> name = shared_info->DebugName()->ToCString();
2775 2776 2777
        PrintF(trace_file, "  reading input frame %s", name.get());
        int arg_count = shared_info->internal_formal_parameter_count() + 1;
        PrintF(trace_file,
2778 2779 2780 2781
               " => bytecode_offset=%d, args=%d, height=%d, retval=%i(#%i); "
               "inputs:\n",
               bytecode_offset.ToInt(), arg_count, height, return_value_offset,
               return_value_count);
2782 2783
      }
      return TranslatedFrame::InterpretedFrame(bytecode_offset, shared_info,
2784 2785
                                               height, return_value_offset,
                                               return_value_count);
2786 2787
    }

2788
    case Translation::ARGUMENTS_ADAPTOR_FRAME: {
2789
      SharedFunctionInfo shared_info =
2790
          SharedFunctionInfo::cast(literal_array->get(iterator->Next()));
2791 2792
      int height = iterator->Next();
      if (trace_file != nullptr) {
2793
        std::unique_ptr<char[]> name = shared_info->DebugName()->ToCString();
2794
        PrintF(trace_file, "  reading arguments adaptor frame %s", name.get());
2795 2796
        PrintF(trace_file, " => height=%d; inputs:\n", height);
      }
2797
      return TranslatedFrame::ArgumentsAdaptorFrame(shared_info, height);
2798 2799 2800
    }

    case Translation::CONSTRUCT_STUB_FRAME: {
2801
      BailoutId bailout_id = BailoutId(iterator->Next());
2802
      SharedFunctionInfo shared_info =
2803
          SharedFunctionInfo::cast(literal_array->get(iterator->Next()));
2804 2805
      int height = iterator->Next();
      if (trace_file != nullptr) {
2806
        std::unique_ptr<char[]> name = shared_info->DebugName()->ToCString();
2807
        PrintF(trace_file, "  reading construct stub frame %s", name.get());
2808 2809
        PrintF(trace_file, " => bailout_id=%d, height=%d; inputs:\n",
               bailout_id.ToInt(), height);
2810
      }
2811 2812
      return TranslatedFrame::ConstructStubFrame(bailout_id, shared_info,
                                                 height);
2813 2814
    }

2815 2816
    case Translation::BUILTIN_CONTINUATION_FRAME: {
      BailoutId bailout_id = BailoutId(iterator->Next());
2817
      SharedFunctionInfo shared_info =
2818 2819 2820 2821 2822 2823 2824 2825 2826
          SharedFunctionInfo::cast(literal_array->get(iterator->Next()));
      int height = iterator->Next();
      if (trace_file != nullptr) {
        std::unique_ptr<char[]> name = shared_info->DebugName()->ToCString();
        PrintF(trace_file, "  reading builtin continuation frame %s",
               name.get());
        PrintF(trace_file, " => bailout_id=%d, height=%d; inputs:\n",
               bailout_id.ToInt(), height);
      }
2827 2828 2829
      // Add one to the height to account for the context which was implicitly
      // added to the translation during code generation.
      int height_with_context = height + 1;
2830
      return TranslatedFrame::BuiltinContinuationFrame(bailout_id, shared_info,
2831
                                                       height_with_context);
2832 2833 2834 2835
    }

    case Translation::JAVA_SCRIPT_BUILTIN_CONTINUATION_FRAME: {
      BailoutId bailout_id = BailoutId(iterator->Next());
2836
      SharedFunctionInfo shared_info =
2837 2838 2839 2840 2841 2842 2843 2844 2845
          SharedFunctionInfo::cast(literal_array->get(iterator->Next()));
      int height = iterator->Next();
      if (trace_file != nullptr) {
        std::unique_ptr<char[]> name = shared_info->DebugName()->ToCString();
        PrintF(trace_file, "  reading JavaScript builtin continuation frame %s",
               name.get());
        PrintF(trace_file, " => bailout_id=%d, height=%d; inputs:\n",
               bailout_id.ToInt(), height);
      }
2846 2847 2848
      // Add one to the height to account for the context which was implicitly
      // added to the translation during code generation.
      int height_with_context = height + 1;
2849
      return TranslatedFrame::JavaScriptBuiltinContinuationFrame(
2850
          bailout_id, shared_info, height_with_context);
2851
    }
2852 2853
    case Translation::JAVA_SCRIPT_BUILTIN_CONTINUATION_WITH_CATCH_FRAME: {
      BailoutId bailout_id = BailoutId(iterator->Next());
2854
      SharedFunctionInfo shared_info =
2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870
          SharedFunctionInfo::cast(literal_array->get(iterator->Next()));
      int height = iterator->Next();
      if (trace_file != nullptr) {
        std::unique_ptr<char[]> name = shared_info->DebugName()->ToCString();
        PrintF(trace_file,
               "  reading JavaScript builtin continuation frame with catch %s",
               name.get());
        PrintF(trace_file, " => bailout_id=%d, height=%d; inputs:\n",
               bailout_id.ToInt(), height);
      }
      // Add one to the height to account for the context which was implicitly
      // added to the translation during code generation.
      int height_with_context = height + 1;
      return TranslatedFrame::JavaScriptBuiltinContinuationWithCatchFrame(
          bailout_id, shared_info, height_with_context);
    }
2871
    case Translation::UPDATE_FEEDBACK:
2872 2873
    case Translation::BEGIN:
    case Translation::DUPLICATED_OBJECT:
2874
    case Translation::ARGUMENTS_ELEMENTS:
2875
    case Translation::ARGUMENTS_LENGTH:
2876 2877 2878
    case Translation::CAPTURED_OBJECT:
    case Translation::REGISTER:
    case Translation::INT32_REGISTER:
2879
    case Translation::INT64_REGISTER:
2880 2881
    case Translation::UINT32_REGISTER:
    case Translation::BOOL_REGISTER:
2882
    case Translation::FLOAT_REGISTER:
2883 2884 2885
    case Translation::DOUBLE_REGISTER:
    case Translation::STACK_SLOT:
    case Translation::INT32_STACK_SLOT:
2886
    case Translation::INT64_STACK_SLOT:
2887 2888
    case Translation::UINT32_STACK_SLOT:
    case Translation::BOOL_STACK_SLOT:
2889
    case Translation::FLOAT_STACK_SLOT:
2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911
    case Translation::DOUBLE_STACK_SLOT:
    case Translation::LITERAL:
      break;
  }
  FATAL("We should never get here - unexpected deopt info.");
  return TranslatedFrame::InvalidFrame();
}

// static
void TranslatedFrame::AdvanceIterator(
    std::deque<TranslatedValue>::iterator* iter) {
  int values_to_skip = 1;
  while (values_to_skip > 0) {
    // Consume the current element.
    values_to_skip--;
    // Add all the children.
    values_to_skip += (*iter)->GetChildrenCount();

    (*iter)++;
  }
}

2912
Address TranslatedState::ComputeArgumentsPosition(Address input_frame_pointer,
2913 2914
                                                  CreateArgumentsType type,
                                                  int* length) {
2915 2916
  Address parent_frame_pointer = *reinterpret_cast<Address*>(
      input_frame_pointer + StandardFrameConstants::kCallerFPOffset);
2917
  intptr_t parent_frame_type = Memory<intptr_t>(
2918
      parent_frame_pointer + CommonFrameConstants::kContextOrFrameTypeOffset);
2919

2920 2921 2922
  Address arguments_frame;
  if (parent_frame_type ==
      StackFrame::TypeToMarker(StackFrame::ARGUMENTS_ADAPTOR)) {
2923
    if (length)
2924
      *length = Smi::cast(*FullObjectSlot(
2925
                              parent_frame_pointer +
2926
                              ArgumentsAdaptorFrameConstants::kLengthOffset))
2927
                    ->value();
2928 2929
    arguments_frame = parent_frame_pointer;
  } else {
2930
    if (length) *length = formal_parameter_count_;
2931 2932 2933
    arguments_frame = input_frame_pointer;
  }

2934
  if (type == CreateArgumentsType::kRestParameter) {
2935 2936
    // If the actual number of arguments is less than the number of formal
    // parameters, we have zero rest parameters.
2937
    if (length) *length = std::max(0, *length - formal_parameter_count_);
2938 2939
  }

2940 2941 2942 2943
  return arguments_frame;
}

// Creates translated values for an arguments backing store, or the backing
2944
// store for rest parameters depending on the given {type}. The TranslatedValue
2945 2946 2947
// objects for the fields are not read from the TranslationIterator, but instead
// created on-the-fly based on dynamic information in the optimized frame.
void TranslatedState::CreateArgumentsElementsTranslatedValues(
2948
    int frame_index, Address input_frame_pointer, CreateArgumentsType type,
2949
    FILE* trace_file) {
2950 2951 2952 2953
  TranslatedFrame& frame = frames_[frame_index];

  int length;
  Address arguments_frame =
2954
      ComputeArgumentsPosition(input_frame_pointer, type, &length);
2955

2956 2957
  int object_index = static_cast<int>(object_positions_.size());
  int value_index = static_cast<int>(frame.values_.size());
2958
  if (trace_file != nullptr) {
2959 2960
    PrintF(trace_file, "arguments elements object #%d (type = %d, length = %d)",
           object_index, static_cast<uint8_t>(type), length);
2961
  }
2962

2963 2964
  object_positions_.push_back({frame_index, value_index});
  frame.Add(TranslatedValue::NewDeferredObject(
2965
      this, length + FixedArray::kHeaderSize / kTaggedSize, object_index));
2966

2967 2968
  ReadOnlyRoots roots(isolate_);
  frame.Add(TranslatedValue::NewTagged(this, roots.fixed_array_map()));
2969 2970
  frame.Add(TranslatedValue::NewInt32(this, length));

2971 2972 2973 2974 2975 2976 2977
  int number_of_holes = 0;
  if (type == CreateArgumentsType::kMappedArguments) {
    // If the actual number of arguments is less than the number of formal
    // parameters, we have fewer holes to fill to not overshoot the length.
    number_of_holes = Min(formal_parameter_count_, length);
  }
  for (int i = 0; i < number_of_holes; ++i) {
2978
    frame.Add(TranslatedValue::NewTagged(this, roots.the_hole_value()));
2979 2980
  }
  for (int i = length - number_of_holes - 1; i >= 0; --i) {
2981 2982
    Address argument_slot = arguments_frame +
                            CommonFrameConstants::kFixedFrameSizeAboveFp +
2983
                            i * kSystemPointerSize;
2984
    frame.Add(TranslatedValue::NewTagged(this, *FullObjectSlot(argument_slot)));
2985 2986
  }
}
2987

2988 2989
// We can't intermix stack decoding and allocations because the deoptimization
// infrastracture is not GC safe.
2990
// Thus we build a temporary structure in malloced space.
2991 2992 2993 2994 2995 2996 2997
// The TranslatedValue objects created correspond to the static translation
// instructions from the TranslationIterator, except for
// Translation::ARGUMENTS_ELEMENTS, where the number and values of the
// FixedArray elements depend on dynamic information from the optimized frame.
// Returns the number of expected nested translations from the
// TranslationIterator.
int TranslatedState::CreateNextTranslatedValue(
2998
    int frame_index, TranslationIterator* iterator, FixedArray literal_array,
2999
    Address fp, RegisterValues* registers, FILE* trace_file) {
3000 3001
  disasm::NameConverter converter;

3002 3003 3004
  TranslatedFrame& frame = frames_[frame_index];
  int value_index = static_cast<int>(frame.values_.size());

3005 3006 3007 3008
  Translation::Opcode opcode =
      static_cast<Translation::Opcode>(iterator->Next());
  switch (opcode) {
    case Translation::BEGIN:
3009
    case Translation::INTERPRETED_FRAME:
3010 3011
    case Translation::ARGUMENTS_ADAPTOR_FRAME:
    case Translation::CONSTRUCT_STUB_FRAME:
3012
    case Translation::JAVA_SCRIPT_BUILTIN_CONTINUATION_FRAME:
3013
    case Translation::JAVA_SCRIPT_BUILTIN_CONTINUATION_WITH_CATCH_FRAME:
3014
    case Translation::BUILTIN_CONTINUATION_FRAME:
3015
    case Translation::UPDATE_FEEDBACK:
3016 3017 3018 3019 3020 3021 3022 3023 3024
      // Peeled off before getting here.
      break;

    case Translation::DUPLICATED_OBJECT: {
      int object_id = iterator->Next();
      if (trace_file != nullptr) {
        PrintF(trace_file, "duplicated object #%d", object_id);
      }
      object_positions_.push_back(object_positions_[object_id]);
3025 3026 3027 3028
      TranslatedValue translated_value =
          TranslatedValue::NewDuplicateObject(this, object_id);
      frame.Add(translated_value);
      return translated_value.GetChildrenCount();
3029 3030
    }

3031
    case Translation::ARGUMENTS_ELEMENTS: {
3032 3033 3034
      CreateArgumentsType arguments_type =
          static_cast<CreateArgumentsType>(iterator->Next());
      CreateArgumentsElementsTranslatedValues(frame_index, fp, arguments_type,
3035
                                              trace_file);
3036
      return 0;
3037 3038
    }

3039
    case Translation::ARGUMENTS_LENGTH: {
3040 3041
      CreateArgumentsType arguments_type =
          static_cast<CreateArgumentsType>(iterator->Next());
3042
      int length;
3043
      ComputeArgumentsPosition(fp, arguments_type, &length);
3044
      if (trace_file != nullptr) {
3045 3046
        PrintF(trace_file, "arguments length field (type = %d, length = %d)",
               static_cast<uint8_t>(arguments_type), length);
3047
      }
3048 3049 3050 3051
      frame.Add(TranslatedValue::NewInt32(this, length));
      return 0;
    }

3052 3053 3054 3055 3056 3057 3058 3059
    case Translation::CAPTURED_OBJECT: {
      int field_count = iterator->Next();
      int object_index = static_cast<int>(object_positions_.size());
      if (trace_file != nullptr) {
        PrintF(trace_file, "captured object #%d (length = %d)", object_index,
               field_count);
      }
      object_positions_.push_back({frame_index, value_index});
3060 3061 3062 3063
      TranslatedValue translated_value =
          TranslatedValue::NewDeferredObject(this, field_count, object_index);
      frame.Add(translated_value);
      return translated_value.GetChildrenCount();
3064 3065 3066 3067
    }

    case Translation::REGISTER: {
      int input_reg = iterator->Next();
3068 3069 3070 3071 3072
      if (registers == nullptr) {
        TranslatedValue translated_value = TranslatedValue::NewInvalid(this);
        frame.Add(translated_value);
        return translated_value.GetChildrenCount();
      }
3073 3074
      intptr_t value = registers->GetRegister(input_reg);
      if (trace_file != nullptr) {
3075
        PrintF(trace_file, V8PRIxPTR_FMT " ; %s ", value,
3076
               converter.NameOfCPURegister(input_reg));
3077
        Object(value)->ShortPrint(trace_file);
3078
      }
3079
      TranslatedValue translated_value =
3080
          TranslatedValue::NewTagged(this, Object(value));
3081 3082
      frame.Add(translated_value);
      return translated_value.GetChildrenCount();
3083 3084 3085 3086
    }

    case Translation::INT32_REGISTER: {
      int input_reg = iterator->Next();
3087 3088 3089 3090 3091
      if (registers == nullptr) {
        TranslatedValue translated_value = TranslatedValue::NewInvalid(this);
        frame.Add(translated_value);
        return translated_value.GetChildrenCount();
      }
3092 3093
      intptr_t value = registers->GetRegister(input_reg);
      if (trace_file != nullptr) {
3094
        PrintF(trace_file, "%" V8PRIdPTR " ; %s (int32)", value,
3095 3096
               converter.NameOfCPURegister(input_reg));
      }
3097 3098 3099 3100
      TranslatedValue translated_value =
          TranslatedValue::NewInt32(this, static_cast<int32_t>(value));
      frame.Add(translated_value);
      return translated_value.GetChildrenCount();
3101 3102
    }

3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120
    case Translation::INT64_REGISTER: {
      int input_reg = iterator->Next();
      if (registers == nullptr) {
        TranslatedValue translated_value = TranslatedValue::NewInvalid(this);
        frame.Add(translated_value);
        return translated_value.GetChildrenCount();
      }
      intptr_t value = registers->GetRegister(input_reg);
      if (trace_file != nullptr) {
        PrintF(trace_file, "%" V8PRIdPTR " ; %s (int64)", value,
               converter.NameOfCPURegister(input_reg));
      }
      TranslatedValue translated_value =
          TranslatedValue::NewInt64(this, static_cast<int64_t>(value));
      frame.Add(translated_value);
      return translated_value.GetChildrenCount();
    }

3121 3122
    case Translation::UINT32_REGISTER: {
      int input_reg = iterator->Next();
3123 3124 3125 3126 3127
      if (registers == nullptr) {
        TranslatedValue translated_value = TranslatedValue::NewInvalid(this);
        frame.Add(translated_value);
        return translated_value.GetChildrenCount();
      }
3128 3129
      intptr_t value = registers->GetRegister(input_reg);
      if (trace_file != nullptr) {
3130
        PrintF(trace_file, "%" V8PRIuPTR " ; %s (uint32)", value,
3131 3132
               converter.NameOfCPURegister(input_reg));
      }
3133 3134 3135 3136
      TranslatedValue translated_value =
          TranslatedValue::NewUInt32(this, static_cast<uint32_t>(value));
      frame.Add(translated_value);
      return translated_value.GetChildrenCount();
3137 3138 3139 3140
    }

    case Translation::BOOL_REGISTER: {
      int input_reg = iterator->Next();
3141 3142 3143 3144 3145
      if (registers == nullptr) {
        TranslatedValue translated_value = TranslatedValue::NewInvalid(this);
        frame.Add(translated_value);
        return translated_value.GetChildrenCount();
      }
3146 3147 3148 3149 3150
      intptr_t value = registers->GetRegister(input_reg);
      if (trace_file != nullptr) {
        PrintF(trace_file, "%" V8PRIdPTR " ; %s (bool)", value,
               converter.NameOfCPURegister(input_reg));
      }
3151 3152 3153 3154
      TranslatedValue translated_value =
          TranslatedValue::NewBool(this, static_cast<uint32_t>(value));
      frame.Add(translated_value);
      return translated_value.GetChildrenCount();
3155 3156
    }

3157 3158
    case Translation::FLOAT_REGISTER: {
      int input_reg = iterator->Next();
3159 3160 3161 3162 3163
      if (registers == nullptr) {
        TranslatedValue translated_value = TranslatedValue::NewInvalid(this);
        frame.Add(translated_value);
        return translated_value.GetChildrenCount();
      }
3164
      Float32 value = registers->GetFloatRegister(input_reg);
3165
      if (trace_file != nullptr) {
3166 3167
        PrintF(trace_file, "%e ; %s (float)", value.get_scalar(),
               RegisterName(FloatRegister::from_code(input_reg)));
3168
      }
3169 3170 3171
      TranslatedValue translated_value = TranslatedValue::NewFloat(this, value);
      frame.Add(translated_value);
      return translated_value.GetChildrenCount();
3172 3173
    }

3174 3175
    case Translation::DOUBLE_REGISTER: {
      int input_reg = iterator->Next();
3176 3177 3178 3179 3180
      if (registers == nullptr) {
        TranslatedValue translated_value = TranslatedValue::NewInvalid(this);
        frame.Add(translated_value);
        return translated_value.GetChildrenCount();
      }
3181
      Float64 value = registers->GetDoubleRegister(input_reg);
3182
      if (trace_file != nullptr) {
3183 3184
        PrintF(trace_file, "%e ; %s (double)", value.get_scalar(),
               RegisterName(DoubleRegister::from_code(input_reg)));
3185
      }
3186 3187 3188 3189
      TranslatedValue translated_value =
          TranslatedValue::NewDouble(this, value);
      frame.Add(translated_value);
      return translated_value.GetChildrenCount();
3190 3191 3192
    }

    case Translation::STACK_SLOT: {
3193 3194
      int slot_offset =
          OptimizedFrame::StackSlotOffsetRelativeToFp(iterator->Next());
3195 3196
      intptr_t value = *(reinterpret_cast<intptr_t*>(fp + slot_offset));
      if (trace_file != nullptr) {
3197
        PrintF(trace_file, V8PRIxPTR_FMT " ;  [fp %c %3d]  ", value,
3198
               slot_offset < 0 ? '-' : '+', std::abs(slot_offset));
3199
        Object(value)->ShortPrint(trace_file);
3200
      }
3201
      TranslatedValue translated_value =
3202
          TranslatedValue::NewTagged(this, Object(value));
3203 3204
      frame.Add(translated_value);
      return translated_value.GetChildrenCount();
3205 3206 3207
    }

    case Translation::INT32_STACK_SLOT: {
3208 3209
      int slot_offset =
          OptimizedFrame::StackSlotOffsetRelativeToFp(iterator->Next());
3210 3211
      uint32_t value = GetUInt32Slot(fp, slot_offset);
      if (trace_file != nullptr) {
3212
        PrintF(trace_file, "%d ; (int32) [fp %c %3d] ",
3213 3214 3215
               static_cast<int32_t>(value), slot_offset < 0 ? '-' : '+',
               std::abs(slot_offset));
      }
3216 3217 3218
      TranslatedValue translated_value = TranslatedValue::NewInt32(this, value);
      frame.Add(translated_value);
      return translated_value.GetChildrenCount();
3219 3220
    }

3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234
    case Translation::INT64_STACK_SLOT: {
      int slot_offset =
          OptimizedFrame::StackSlotOffsetRelativeToFp(iterator->Next());
      uint64_t value = GetUInt64Slot(fp, slot_offset);
      if (trace_file != nullptr) {
        PrintF(trace_file, "%" V8PRIdPTR " ; (int64) [fp %c %3d] ",
               static_cast<intptr_t>(value), slot_offset < 0 ? '-' : '+',
               std::abs(slot_offset));
      }
      TranslatedValue translated_value = TranslatedValue::NewInt64(this, value);
      frame.Add(translated_value);
      return translated_value.GetChildrenCount();
    }

3235
    case Translation::UINT32_STACK_SLOT: {
3236 3237
      int slot_offset =
          OptimizedFrame::StackSlotOffsetRelativeToFp(iterator->Next());
3238 3239
      uint32_t value = GetUInt32Slot(fp, slot_offset);
      if (trace_file != nullptr) {
3240
        PrintF(trace_file, "%u ; (uint32) [fp %c %3d] ", value,
3241 3242
               slot_offset < 0 ? '-' : '+', std::abs(slot_offset));
      }
3243 3244 3245 3246
      TranslatedValue translated_value =
          TranslatedValue::NewUInt32(this, value);
      frame.Add(translated_value);
      return translated_value.GetChildrenCount();
3247 3248 3249
    }

    case Translation::BOOL_STACK_SLOT: {
3250 3251
      int slot_offset =
          OptimizedFrame::StackSlotOffsetRelativeToFp(iterator->Next());
3252 3253
      uint32_t value = GetUInt32Slot(fp, slot_offset);
      if (trace_file != nullptr) {
3254
        PrintF(trace_file, "%u ; (bool) [fp %c %3d] ", value,
3255 3256
               slot_offset < 0 ? '-' : '+', std::abs(slot_offset));
      }
3257 3258 3259
      TranslatedValue translated_value = TranslatedValue::NewBool(this, value);
      frame.Add(translated_value);
      return translated_value.GetChildrenCount();
3260 3261
    }

3262 3263 3264
    case Translation::FLOAT_STACK_SLOT: {
      int slot_offset =
          OptimizedFrame::StackSlotOffsetRelativeToFp(iterator->Next());
3265
      Float32 value = GetFloatSlot(fp, slot_offset);
3266
      if (trace_file != nullptr) {
3267
        PrintF(trace_file, "%e ; (float) [fp %c %3d] ", value.get_scalar(),
3268 3269
               slot_offset < 0 ? '-' : '+', std::abs(slot_offset));
      }
3270 3271 3272
      TranslatedValue translated_value = TranslatedValue::NewFloat(this, value);
      frame.Add(translated_value);
      return translated_value.GetChildrenCount();
3273 3274
    }

3275
    case Translation::DOUBLE_STACK_SLOT: {
3276 3277
      int slot_offset =
          OptimizedFrame::StackSlotOffsetRelativeToFp(iterator->Next());
3278
      Float64 value = GetDoubleSlot(fp, slot_offset);
3279
      if (trace_file != nullptr) {
3280
        PrintF(trace_file, "%e ; (double) [fp %c %d] ", value.get_scalar(),
3281 3282
               slot_offset < 0 ? '-' : '+', std::abs(slot_offset));
      }
3283 3284 3285 3286
      TranslatedValue translated_value =
          TranslatedValue::NewDouble(this, value);
      frame.Add(translated_value);
      return translated_value.GetChildrenCount();
3287 3288 3289 3290
    }

    case Translation::LITERAL: {
      int literal_index = iterator->Next();
3291
      Object value = literal_array->get(literal_index);
3292
      if (trace_file != nullptr) {
3293 3294 3295
        PrintF(trace_file, V8PRIxPTR_FMT " ; (literal %2d) ", value->ptr(),
               literal_index);
        value->ShortPrint(trace_file);
3296 3297
      }

3298 3299 3300 3301
      TranslatedValue translated_value =
          TranslatedValue::NewTagged(this, value);
      frame.Add(translated_value);
      return translated_value.GetChildrenCount();
3302 3303 3304 3305 3306 3307
    }
  }

  FATAL("We should never get here - unexpected deopt info.");
}

3308
TranslatedState::TranslatedState(const JavaScriptFrame* frame) {
3309
  int deopt_index = Safepoint::kNoDeoptimizationIndex;
3310
  DeoptimizationData data =
3311 3312
      static_cast<const OptimizedFrame*>(frame)->GetDeoptimizationData(
          &deopt_index);
3313
  DCHECK(!data.is_null() && deopt_index != Safepoint::kNoDeoptimizationIndex);
3314 3315
  TranslationIterator it(data->TranslationByteArray(),
                         data->TranslationIndex(deopt_index)->value());
3316 3317
  Init(frame->isolate(), frame->fp(), &it, data->LiteralArray(),
       nullptr /* registers */, nullptr /* trace file */,
3318
       frame->function()->shared()->internal_formal_parameter_count());
3319 3320
}

3321
void TranslatedState::Init(Isolate* isolate, Address input_frame_pointer,
3322
                           TranslationIterator* iterator,
3323
                           FixedArray literal_array, RegisterValues* registers,
3324
                           FILE* trace_file, int formal_parameter_count) {
3325 3326
  DCHECK(frames_.empty());

3327
  formal_parameter_count_ = formal_parameter_count;
3328
  isolate_ = isolate;
3329

3330 3331 3332 3333 3334 3335
  // Read out the 'header' translation.
  Translation::Opcode opcode =
      static_cast<Translation::Opcode>(iterator->Next());
  CHECK(opcode == Translation::BEGIN);

  int count = iterator->Next();
3336
  frames_.reserve(count);
3337
  iterator->Next();  // Drop JS frames count.
3338 3339 3340
  int update_feedback_count = iterator->Next();
  CHECK_GE(update_feedback_count, 0);
  CHECK_LE(update_feedback_count, 1);
3341

3342
  if (update_feedback_count == 1) {
3343
    ReadUpdateFeedback(iterator, literal_array, trace_file);
3344
  }
3345 3346 3347 3348

  std::stack<int> nested_counts;

  // Read the frames
3349
  for (int frame_index = 0; frame_index < count; frame_index++) {
3350
    // Read the frame descriptor.
3351 3352
    frames_.push_back(CreateNextTranslatedFrame(
        iterator, literal_array, input_frame_pointer, trace_file));
3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371
    TranslatedFrame& frame = frames_.back();

    // Read the values.
    int values_to_process = frame.GetValueCount();
    while (values_to_process > 0 || !nested_counts.empty()) {
      if (trace_file != nullptr) {
        if (nested_counts.empty()) {
          // For top level values, print the value number.
          PrintF(trace_file, "    %3i: ",
                 frame.GetValueCount() - values_to_process);
        } else {
          // Take care of indenting for nested values.
          PrintF(trace_file, "         ");
          for (size_t j = 0; j < nested_counts.size(); j++) {
            PrintF(trace_file, "  ");
          }
        }
      }

3372 3373 3374
      int nested_count =
          CreateNextTranslatedValue(frame_index, iterator, literal_array,
                                    input_frame_pointer, registers, trace_file);
3375 3376 3377 3378 3379 3380 3381

      if (trace_file != nullptr) {
        PrintF(trace_file, "\n");
      }

      // Update the value count and resolve the nesting.
      values_to_process--;
3382
      if (nested_count > 0) {
3383
        nested_counts.push(values_to_process);
3384
        values_to_process = nested_count;
3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398
      } else {
        while (values_to_process == 0 && !nested_counts.empty()) {
          values_to_process = nested_counts.top();
          nested_counts.pop();
        }
      }
    }
  }

  CHECK(!iterator->HasNext() ||
        static_cast<Translation::Opcode>(iterator->Next()) ==
            Translation::BEGIN);
}

3399
void TranslatedState::Prepare(Address stack_frame_pointer) {
3400
  for (auto& frame : frames_) frame.Handlify();
3401

3402
  if (!feedback_vector_.is_null()) {
3403 3404
    feedback_vector_handle_ =
        Handle<FeedbackVector>(feedback_vector_, isolate());
3405
    feedback_vector_ = FeedbackVector();
3406
  }
3407 3408 3409 3410 3411
  stack_frame_pointer_ = stack_frame_pointer;

  UpdateFromPreviouslyMaterializedObjects();
}

3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463
TranslatedValue* TranslatedState::GetValueByObjectIndex(int object_index) {
  CHECK_LT(static_cast<size_t>(object_index), object_positions_.size());
  TranslatedState::ObjectPosition pos = object_positions_[object_index];
  return &(frames_[pos.frame_index_].values_[pos.value_index_]);
}

Handle<Object> TranslatedState::InitializeObjectAt(TranslatedValue* slot) {
  slot = ResolveCapturedObject(slot);

  DisallowHeapAllocation no_allocation;
  if (slot->materialization_state() != TranslatedValue::kFinished) {
    std::stack<int> worklist;
    worklist.push(slot->object_index());
    slot->mark_finished();

    while (!worklist.empty()) {
      int index = worklist.top();
      worklist.pop();
      InitializeCapturedObjectAt(index, &worklist, no_allocation);
    }
  }
  return slot->GetStorage();
}

void TranslatedState::InitializeCapturedObjectAt(
    int object_index, std::stack<int>* worklist,
    const DisallowHeapAllocation& no_allocation) {
  CHECK_LT(static_cast<size_t>(object_index), object_positions_.size());
  TranslatedState::ObjectPosition pos = object_positions_[object_index];
  int value_index = pos.value_index_;

  TranslatedFrame* frame = &(frames_[pos.frame_index_]);
  TranslatedValue* slot = &(frame->values_[value_index]);
  value_index++;

  CHECK_EQ(TranslatedValue::kFinished, slot->materialization_state());
  CHECK_EQ(TranslatedValue::kCapturedObject, slot->kind());

  // Ensure all fields are initialized.
  int children_init_index = value_index;
  for (int i = 0; i < slot->GetChildrenCount(); i++) {
    // If the field is an object that has not been initialized yet, queue it
    // for initialization (and mark it as such).
    TranslatedValue* child_slot = frame->ValueAt(children_init_index);
    if (child_slot->kind() == TranslatedValue::kCapturedObject ||
        child_slot->kind() == TranslatedValue::kDuplicatedObject) {
      child_slot = ResolveCapturedObject(child_slot);
      if (child_slot->materialization_state() != TranslatedValue::kFinished) {
        DCHECK_EQ(TranslatedValue::kAllocated,
                  child_slot->materialization_state());
        worklist->push(child_slot->object_index());
        child_slot->mark_finished();
3464 3465
      }
    }
3466
    SkipSlots(1, frame, &children_init_index);
3467 3468
  }

3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483
  // Read the map.
  // The map should never be materialized, so let us check we already have
  // an existing object here.
  CHECK_EQ(frame->values_[value_index].kind(), TranslatedValue::kTagged);
  Handle<Map> map = Handle<Map>::cast(frame->values_[value_index].GetValue());
  CHECK(map->IsMap());
  value_index++;

  // Handle the special cases.
  switch (map->instance_type()) {
    case MUTABLE_HEAP_NUMBER_TYPE:
    case FIXED_DOUBLE_ARRAY_TYPE:
      return;

    case FIXED_ARRAY_TYPE:
3484
    case AWAIT_CONTEXT_TYPE:
3485 3486 3487 3488 3489 3490 3491 3492 3493
    case BLOCK_CONTEXT_TYPE:
    case CATCH_CONTEXT_TYPE:
    case DEBUG_EVALUATE_CONTEXT_TYPE:
    case EVAL_CONTEXT_TYPE:
    case FUNCTION_CONTEXT_TYPE:
    case MODULE_CONTEXT_TYPE:
    case NATIVE_CONTEXT_TYPE:
    case SCRIPT_CONTEXT_TYPE:
    case WITH_CONTEXT_TYPE:
3494
    case OBJECT_BOILERPLATE_DESCRIPTION_TYPE:
3495
    case HASH_TABLE_TYPE:
3496 3497 3498 3499 3500 3501 3502
    case ORDERED_HASH_MAP_TYPE:
    case ORDERED_HASH_SET_TYPE:
    case NAME_DICTIONARY_TYPE:
    case GLOBAL_DICTIONARY_TYPE:
    case NUMBER_DICTIONARY_TYPE:
    case SIMPLE_NUMBER_DICTIONARY_TYPE:
    case STRING_TABLE_TYPE:
3503
    case PROPERTY_ARRAY_TYPE:
3504
    case SCRIPT_CONTEXT_TABLE_TYPE:
3505 3506 3507 3508 3509 3510 3511 3512
      InitializeObjectWithTaggedFieldsAt(frame, &value_index, slot, map,
                                         no_allocation);
      break;

    default:
      CHECK(map->IsJSObjectMap());
      InitializeJSObjectAt(frame, &value_index, slot, map, no_allocation);
      break;
3513
  }
3514 3515
  CHECK_EQ(value_index, children_init_index);
}
3516

3517 3518
void TranslatedState::EnsureObjectAllocatedAt(TranslatedValue* slot) {
  slot = ResolveCapturedObject(slot);
3519

3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563
  if (slot->materialization_state() == TranslatedValue::kUninitialized) {
    std::stack<int> worklist;
    worklist.push(slot->object_index());
    slot->mark_allocated();

    while (!worklist.empty()) {
      int index = worklist.top();
      worklist.pop();
      EnsureCapturedObjectAllocatedAt(index, &worklist);
    }
  }
}

void TranslatedState::MaterializeFixedDoubleArray(TranslatedFrame* frame,
                                                  int* value_index,
                                                  TranslatedValue* slot,
                                                  Handle<Map> map) {
  int length = Smi::cast(frame->values_[*value_index].GetRawValue())->value();
  (*value_index)++;
  Handle<FixedDoubleArray> array = Handle<FixedDoubleArray>::cast(
      isolate()->factory()->NewFixedDoubleArray(length));
  CHECK_GT(length, 0);
  for (int i = 0; i < length; i++) {
    CHECK_NE(TranslatedValue::kCapturedObject,
             frame->values_[*value_index].kind());
    Handle<Object> value = frame->values_[*value_index].GetValue();
    if (value->IsNumber()) {
      array->set(i, value->Number());
    } else {
      CHECK(value.is_identical_to(isolate()->factory()->the_hole_value()));
      array->set_the_hole(isolate(), i);
    }
    (*value_index)++;
  }
  slot->set_storage(array);
}

void TranslatedState::MaterializeMutableHeapNumber(TranslatedFrame* frame,
                                                   int* value_index,
                                                   TranslatedValue* slot) {
  CHECK_NE(TranslatedValue::kCapturedObject,
           frame->values_[*value_index].kind());
  Handle<Object> value = frame->values_[*value_index].GetValue();
  CHECK(value->IsNumber());
3564 3565
  Handle<MutableHeapNumber> box =
      isolate()->factory()->NewMutableHeapNumber(value->Number());
3566 3567 3568 3569 3570 3571 3572 3573 3574 3575
  (*value_index)++;
  slot->set_storage(box);
}

namespace {

enum DoubleStorageKind : uint8_t {
  kStoreTagged,
  kStoreUnboxedDouble,
  kStoreMutableHeapNumber,
3576 3577
};

3578
}  // namespace
3579

3580 3581 3582 3583 3584 3585
void TranslatedState::SkipSlots(int slots_to_skip, TranslatedFrame* frame,
                                int* value_index) {
  while (slots_to_skip > 0) {
    TranslatedValue* slot = &(frame->values_[*value_index]);
    (*value_index)++;
    slots_to_skip--;
3586

3587 3588
    if (slot->kind() == TranslatedValue::kCapturedObject) {
      slots_to_skip += slot->GetChildrenCount();
3589
    }
3590
  }
3591
}
3592

3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614
void TranslatedState::EnsureCapturedObjectAllocatedAt(
    int object_index, std::stack<int>* worklist) {
  CHECK_LT(static_cast<size_t>(object_index), object_positions_.size());
  TranslatedState::ObjectPosition pos = object_positions_[object_index];
  int value_index = pos.value_index_;

  TranslatedFrame* frame = &(frames_[pos.frame_index_]);
  TranslatedValue* slot = &(frame->values_[value_index]);
  value_index++;

  CHECK_EQ(TranslatedValue::kAllocated, slot->materialization_state());
  CHECK_EQ(TranslatedValue::kCapturedObject, slot->kind());

  // Read the map.
  // The map should never be materialized, so let us check we already have
  // an existing object here.
  CHECK_EQ(frame->values_[value_index].kind(), TranslatedValue::kTagged);
  Handle<Map> map = Handle<Map>::cast(frame->values_[value_index].GetValue());
  CHECK(map->IsMap());
  value_index++;

  // Handle the special cases.
3615
  switch (map->instance_type()) {
3616 3617 3618 3619 3620
    case FIXED_DOUBLE_ARRAY_TYPE:
      // Materialize (i.e. allocate&initialize) the array and return since
      // there is no need to process the children.
      return MaterializeFixedDoubleArray(frame, &value_index, slot, map);

3621
    case MUTABLE_HEAP_NUMBER_TYPE:
3622 3623 3624 3625 3626
      // Materialize (i.e. allocate&initialize) the heap number and return.
      // There is no need to process the children.
      return MaterializeMutableHeapNumber(frame, &value_index, slot);

    case FIXED_ARRAY_TYPE:
3627
    case SCRIPT_CONTEXT_TABLE_TYPE:
3628
    case AWAIT_CONTEXT_TYPE:
3629 3630 3631 3632 3633 3634 3635 3636 3637
    case BLOCK_CONTEXT_TYPE:
    case CATCH_CONTEXT_TYPE:
    case DEBUG_EVALUATE_CONTEXT_TYPE:
    case EVAL_CONTEXT_TYPE:
    case FUNCTION_CONTEXT_TYPE:
    case MODULE_CONTEXT_TYPE:
    case NATIVE_CONTEXT_TYPE:
    case SCRIPT_CONTEXT_TYPE:
    case WITH_CONTEXT_TYPE:
3638 3639 3640 3641 3642 3643 3644 3645
    case HASH_TABLE_TYPE:
    case ORDERED_HASH_MAP_TYPE:
    case ORDERED_HASH_SET_TYPE:
    case NAME_DICTIONARY_TYPE:
    case GLOBAL_DICTIONARY_TYPE:
    case NUMBER_DICTIONARY_TYPE:
    case SIMPLE_NUMBER_DICTIONARY_TYPE:
    case STRING_TABLE_TYPE: {
3646 3647 3648
      // Check we have the right size.
      int array_length =
          Smi::cast(frame->values_[value_index].GetRawValue())->value();
3649

3650
      int instance_size = FixedArray::SizeFor(array_length);
3651
      CHECK_EQ(instance_size, slot->GetChildrenCount() * kTaggedSize);
3652

3653
      // Canonicalize empty fixed array.
3654
      if (*map == ReadOnlyRoots(isolate()).empty_fixed_array()->map() &&
3655 3656 3657 3658 3659 3660
          array_length == 0) {
        slot->set_storage(isolate()->factory()->empty_fixed_array());
      } else {
        slot->set_storage(AllocateStorageFor(slot));
      }

3661 3662 3663
      // Make sure all the remaining children (after the map) are allocated.
      return EnsureChildrenAllocated(slot->GetChildrenCount() - 1, frame,
                                     &value_index, worklist);
3664
    }
3665

3666 3667 3668 3669 3670 3671
    case PROPERTY_ARRAY_TYPE: {
      // Check we have the right size.
      int length_or_hash =
          Smi::cast(frame->values_[value_index].GetRawValue())->value();
      int array_length = PropertyArray::LengthField::decode(length_or_hash);
      int instance_size = PropertyArray::SizeFor(array_length);
3672
      CHECK_EQ(instance_size, slot->GetChildrenCount() * kTaggedSize);
3673 3674

      slot->set_storage(AllocateStorageFor(slot));
3675 3676 3677
      // Make sure all the remaining children (after the map) are allocated.
      return EnsureChildrenAllocated(slot->GetChildrenCount() - 1, frame,
                                     &value_index, worklist);
3678
    }
3679 3680 3681 3682 3683

    default:
      CHECK(map->IsJSObjectMap());
      EnsureJSObjectAllocated(slot, map);
      TranslatedValue* properties_slot = &(frame->values_[value_index]);
3684
      value_index++;
3685 3686 3687 3688 3689 3690
      if (properties_slot->kind() == TranslatedValue::kCapturedObject) {
        // If we are materializing the property array, make sure we put
        // the mutable heap numbers at the right places.
        EnsurePropertiesAllocatedAndMarked(properties_slot, map);
        EnsureChildrenAllocated(properties_slot->GetChildrenCount(), frame,
                                &value_index, worklist);
3691
      }
3692 3693 3694 3695
      // Make sure all the remaining children (after the map and properties) are
      // allocated.
      return EnsureChildrenAllocated(slot->GetChildrenCount() - 2, frame,
                                     &value_index, worklist);
3696
  }
3697
  UNREACHABLE();
3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722
}

void TranslatedState::EnsureChildrenAllocated(int count, TranslatedFrame* frame,
                                              int* value_index,
                                              std::stack<int>* worklist) {
  // Ensure all children are allocated.
  for (int i = 0; i < count; i++) {
    // If the field is an object that has not been allocated yet, queue it
    // for initialization (and mark it as such).
    TranslatedValue* child_slot = frame->ValueAt(*value_index);
    if (child_slot->kind() == TranslatedValue::kCapturedObject ||
        child_slot->kind() == TranslatedValue::kDuplicatedObject) {
      child_slot = ResolveCapturedObject(child_slot);
      if (child_slot->materialization_state() ==
          TranslatedValue::kUninitialized) {
        worklist->push(child_slot->object_index());
        child_slot->mark_allocated();
      }
    } else {
      // Make sure the simple values (heap numbers, etc.) are properly
      // initialized.
      child_slot->MaterializeSimple();
    }
    SkipSlots(1, frame, value_index);
  }
3723
}
3724

3725 3726 3727 3728
void TranslatedState::EnsurePropertiesAllocatedAndMarked(
    TranslatedValue* properties_slot, Handle<Map> map) {
  CHECK_EQ(TranslatedValue::kUninitialized,
           properties_slot->materialization_state());
3729

3730 3731 3732
  Handle<ByteArray> object_storage = AllocateStorageFor(properties_slot);
  properties_slot->mark_allocated();
  properties_slot->set_storage(object_storage);
3733

3734
  // Set markers for the double properties.
3735
  Handle<DescriptorArray> descriptors(map->instance_descriptors(), isolate());
3736 3737 3738 3739 3740 3741 3742
  int field_count = map->NumberOfOwnDescriptors();
  for (int i = 0; i < field_count; i++) {
    FieldIndex index = FieldIndex::ForDescriptor(*map, i);
    if (descriptors->GetDetails(i).representation().IsDouble() &&
        !index.is_inobject()) {
      CHECK(!map->IsUnboxedDoubleField(index));
      int outobject_index = index.outobject_array_index();
3743
      int array_index = outobject_index * kTaggedSize;
3744
      object_storage->set(array_index, kStoreMutableHeapNumber);
3745
    }
3746 3747
  }
}
3748

3749 3750
Handle<ByteArray> TranslatedState::AllocateStorageFor(TranslatedValue* slot) {
  int allocate_size =
3751
      ByteArray::LengthFor(slot->GetChildrenCount() * kTaggedSize);
3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763
  // It is important to allocate all the objects tenured so that the marker
  // does not visit them.
  Handle<ByteArray> object_storage =
      isolate()->factory()->NewByteArray(allocate_size, TENURED);
  for (int i = 0; i < object_storage->length(); i++) {
    object_storage->set(i, kStoreTagged);
  }
  return object_storage;
}

void TranslatedState::EnsureJSObjectAllocated(TranslatedValue* slot,
                                              Handle<Map> map) {
3764
  CHECK_EQ(map->instance_size(), slot->GetChildrenCount() * kTaggedSize);
3765 3766 3767

  Handle<ByteArray> object_storage = AllocateStorageFor(slot);
  // Now we handle the interesting (JSObject) case.
3768
  Handle<DescriptorArray> descriptors(map->instance_descriptors(), isolate());
3769 3770 3771 3772 3773 3774 3775
  int field_count = map->NumberOfOwnDescriptors();

  // Set markers for the double properties.
  for (int i = 0; i < field_count; i++) {
    FieldIndex index = FieldIndex::ForDescriptor(*map, i);
    if (descriptors->GetDetails(i).representation().IsDouble() &&
        index.is_inobject()) {
3776 3777
      CHECK_GE(index.index(), FixedArray::kHeaderSize / kTaggedSize);
      int array_index = index.index() * kTaggedSize - FixedArray::kHeaderSize;
3778 3779 3780 3781
      uint8_t marker = map->IsUnboxedDoubleField(index)
                           ? kStoreUnboxedDouble
                           : kStoreMutableHeapNumber;
      object_storage->set(array_index, marker);
3782
    }
3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796
  }
  slot->set_storage(object_storage);
}

Handle<Object> TranslatedState::GetValueAndAdvance(TranslatedFrame* frame,
                                                   int* value_index) {
  TranslatedValue* slot = frame->ValueAt(*value_index);
  SkipSlots(1, frame, value_index);
  if (slot->kind() == TranslatedValue::kDuplicatedObject) {
    slot = ResolveCapturedObject(slot);
  }
  CHECK_NE(TranslatedValue::kUninitialized, slot->materialization_state());
  return slot->GetStorage();
}
3797

3798 3799 3800 3801 3802
void TranslatedState::InitializeJSObjectAt(
    TranslatedFrame* frame, int* value_index, TranslatedValue* slot,
    Handle<Map> map, const DisallowHeapAllocation& no_allocation) {
  Handle<HeapObject> object_storage = Handle<HeapObject>::cast(slot->storage_);
  DCHECK_EQ(TranslatedValue::kCapturedObject, slot->kind());
3803

3804 3805
  // The object should have at least a map and some payload.
  CHECK_GE(slot->GetChildrenCount(), 2);
3806

3807 3808
  // Notify the concurrent marker about the layout change.
  isolate()->heap()->NotifyObjectLayoutChange(
3809
      *object_storage, slot->GetChildrenCount() * kTaggedSize, no_allocation);
3810

3811 3812 3813 3814 3815
  // Fill the property array field.
  {
    Handle<Object> properties = GetValueAndAdvance(frame, value_index);
    WRITE_FIELD(*object_storage, JSObject::kPropertiesOrHashOffset,
                *properties);
3816 3817
    WRITE_BARRIER(*object_storage, JSObject::kPropertiesOrHashOffset,
                  *properties);
3818 3819 3820 3821
  }

  // For all the other fields we first look at the fixed array and check the
  // marker to see if we store an unboxed double.
3822
  DCHECK_EQ(kTaggedSize, JSObject::kPropertiesOrHashOffset);
3823 3824 3825 3826 3827 3828 3829
  for (int i = 2; i < slot->GetChildrenCount(); i++) {
    // Initialize and extract the value from its slot.
    Handle<Object> field_value = GetValueAndAdvance(frame, value_index);

    // Read out the marker and ensure the field is consistent with
    // what the markers in the storage say (note that all heap numbers
    // should be fully initialized by now).
3830
    int offset = i * kTaggedSize;
3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843
    uint8_t marker = READ_UINT8_FIELD(*object_storage, offset);
    if (marker == kStoreUnboxedDouble) {
      double double_field_value;
      if (field_value->IsSmi()) {
        double_field_value = Smi::cast(*field_value)->value();
      } else {
        CHECK(field_value->IsHeapNumber());
        double_field_value = HeapNumber::cast(*field_value)->value();
      }
      WRITE_DOUBLE_FIELD(*object_storage, offset, double_field_value);
    } else if (marker == kStoreMutableHeapNumber) {
      CHECK(field_value->IsMutableHeapNumber());
      WRITE_FIELD(*object_storage, offset, *field_value);
3844
      WRITE_BARRIER(*object_storage, offset, *field_value);
3845 3846 3847
    } else {
      CHECK_EQ(kStoreTagged, marker);
      WRITE_FIELD(*object_storage, offset, *field_value);
3848
      WRITE_BARRIER(*object_storage, offset, *field_value);
3849
    }
3850 3851 3852
  }
  object_storage->synchronized_set_map(*map);
}
3853

3854 3855 3856 3857 3858
void TranslatedState::InitializeObjectWithTaggedFieldsAt(
    TranslatedFrame* frame, int* value_index, TranslatedValue* slot,
    Handle<Map> map, const DisallowHeapAllocation& no_allocation) {
  Handle<HeapObject> object_storage = Handle<HeapObject>::cast(slot->storage_);

3859
  // Skip the writes if we already have the canonical empty fixed array.
3860
  if (*object_storage == ReadOnlyRoots(isolate()).empty_fixed_array()) {
3861 3862 3863 3864 3865 3866
    CHECK_EQ(2, slot->GetChildrenCount());
    Handle<Object> length_value = GetValueAndAdvance(frame, value_index);
    CHECK_EQ(*length_value, Smi::FromInt(0));
    return;
  }

3867 3868
  // Notify the concurrent marker about the layout change.
  isolate()->heap()->NotifyObjectLayoutChange(
3869
      *object_storage, slot->GetChildrenCount() * kTaggedSize, no_allocation);
3870 3871 3872 3873

  // Write the fields to the object.
  for (int i = 1; i < slot->GetChildrenCount(); i++) {
    Handle<Object> field_value = GetValueAndAdvance(frame, value_index);
3874
    int offset = i * kTaggedSize;
3875 3876 3877 3878 3879 3880 3881 3882 3883
    uint8_t marker = READ_UINT8_FIELD(*object_storage, offset);
    if (i > 1 && marker == kStoreMutableHeapNumber) {
      CHECK(field_value->IsMutableHeapNumber());
    } else {
      CHECK(marker == kStoreTagged || i == 1);
      CHECK(!field_value->IsMutableHeapNumber());
    }

    WRITE_FIELD(*object_storage, offset, *field_value);
3884
    WRITE_BARRIER(*object_storage, offset, *field_value);
3885 3886
  }

3887
  object_storage->synchronized_set_map(*map);
3888 3889
}

3890 3891 3892 3893 3894 3895
TranslatedValue* TranslatedState::ResolveCapturedObject(TranslatedValue* slot) {
  while (slot->kind() == TranslatedValue::kDuplicatedObject) {
    slot = GetValueByObjectIndex(slot->object_index());
  }
  CHECK_EQ(TranslatedValue::kCapturedObject, slot->kind());
  return slot;
3896 3897
}

3898 3899
TranslatedFrame* TranslatedState::GetFrameFromJSFrameIndex(int jsframe_index) {
  for (size_t i = 0; i < frames_.size(); i++) {
3900
    if (frames_[i].kind() == TranslatedFrame::kInterpretedFunction ||
3901 3902 3903
        frames_[i].kind() == TranslatedFrame::kJavaScriptBuiltinContinuation ||
        frames_[i].kind() ==
            TranslatedFrame::kJavaScriptBuiltinContinuationWithCatch) {
3904 3905 3906 3907 3908 3909 3910 3911 3912 3913
      if (jsframe_index > 0) {
        jsframe_index--;
      } else {
        return &(frames_[i]);
      }
    }
  }
  return nullptr;
}

3914 3915 3916
TranslatedFrame* TranslatedState::GetArgumentsInfoFromJSFrameIndex(
    int jsframe_index, int* args_count) {
  for (size_t i = 0; i < frames_.size(); i++) {
3917
    if (frames_[i].kind() == TranslatedFrame::kInterpretedFunction ||
3918 3919 3920
        frames_[i].kind() == TranslatedFrame::kJavaScriptBuiltinContinuation ||
        frames_[i].kind() ==
            TranslatedFrame::kJavaScriptBuiltinContinuationWithCatch) {
3921 3922 3923
      if (jsframe_index > 0) {
        jsframe_index--;
      } else {
3924 3925
        // We have the JS function frame, now check if it has arguments
        // adaptor.
3926 3927 3928 3929 3930 3931
        if (i > 0 &&
            frames_[i - 1].kind() == TranslatedFrame::kArgumentsAdaptor) {
          *args_count = frames_[i - 1].height();
          return &(frames_[i - 1]);
        }
        *args_count =
3932
            frames_[i].shared_info()->internal_formal_parameter_count() + 1;
3933 3934 3935 3936 3937 3938 3939
        return &(frames_[i]);
      }
    }
  }
  return nullptr;
}

3940
void TranslatedState::StoreMaterializedValuesAndDeopt(JavaScriptFrame* frame) {
3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951
  MaterializedObjectStore* materialized_store =
      isolate_->materialized_object_store();
  Handle<FixedArray> previously_materialized_objects =
      materialized_store->Get(stack_frame_pointer_);

  Handle<Object> marker = isolate_->factory()->arguments_marker();

  int length = static_cast<int>(object_positions_.size());
  bool new_store = false;
  if (previously_materialized_objects.is_null()) {
    previously_materialized_objects =
3952
        isolate_->factory()->NewFixedArray(length, TENURED);
3953 3954 3955 3956 3957 3958
    for (int i = 0; i < length; i++) {
      previously_materialized_objects->set(i, *marker);
    }
    new_store = true;
  }

3959
  CHECK_EQ(length, previously_materialized_objects->length());
3960 3961 3962 3963 3964 3965 3966

  bool value_changed = false;
  for (int i = 0; i < length; i++) {
    TranslatedState::ObjectPosition pos = object_positions_[i];
    TranslatedValue* value_info =
        &(frames_[pos.frame_index_].values_[pos.value_index_]);

3967
    CHECK(value_info->IsMaterializedObject());
3968

3969 3970 3971 3972
    // Skip duplicate objects (i.e., those that point to some
    // other object id).
    if (value_info->object_index() != i) continue;

3973 3974 3975 3976 3977 3978 3979
    Handle<Object> value(value_info->GetRawValue(), isolate_);

    if (!value.is_identical_to(marker)) {
      if (previously_materialized_objects->get(i) == *marker) {
        previously_materialized_objects->set(i, *value);
        value_changed = true;
      } else {
3980
        CHECK(previously_materialized_objects->get(i) == *value);
3981 3982 3983 3984 3985 3986
      }
    }
  }
  if (new_store && value_changed) {
    materialized_store->Set(stack_frame_pointer_,
                            previously_materialized_objects);
3987
    CHECK_EQ(frames_[0].kind(), TranslatedFrame::kInterpretedFunction);
3988 3989
    CHECK_EQ(frame->function(), frames_[0].front().GetRawValue());
    Deoptimizer::DeoptimizeFunction(frame->function(), frame->LookupCode());
3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004
  }
}

void TranslatedState::UpdateFromPreviouslyMaterializedObjects() {
  MaterializedObjectStore* materialized_store =
      isolate_->materialized_object_store();
  Handle<FixedArray> previously_materialized_objects =
      materialized_store->Get(stack_frame_pointer_);

  // If we have no previously materialized objects, there is nothing to do.
  if (previously_materialized_objects.is_null()) return;

  Handle<Object> marker = isolate_->factory()->arguments_marker();

  int length = static_cast<int>(object_positions_.size());
4005
  CHECK_EQ(length, previously_materialized_objects->length());
4006 4007 4008 4009 4010 4011 4012 4013

  for (int i = 0; i < length; i++) {
    // For a previously materialized objects, inject their value into the
    // translated values.
    if (previously_materialized_objects->get(i) != *marker) {
      TranslatedState::ObjectPosition pos = object_positions_[i];
      TranslatedValue* value_info =
          &(frames_[pos.frame_index_].values_[pos.value_index_]);
4014
      CHECK(value_info->IsMaterializedObject());
4015

4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031
      if (value_info->kind() == TranslatedValue::kCapturedObject) {
        value_info->set_initialized_storage(
            Handle<Object>(previously_materialized_objects->get(i), isolate_));
      }
    }
  }
}

void TranslatedState::VerifyMaterializedObjects() {
#if VERIFY_HEAP
  int length = static_cast<int>(object_positions_.size());
  for (int i = 0; i < length; i++) {
    TranslatedValue* slot = GetValueByObjectIndex(i);
    if (slot->kind() == TranslatedValue::kCapturedObject) {
      CHECK_EQ(slot, GetValueByObjectIndex(slot->object_index()));
      if (slot->materialization_state() == TranslatedValue::kFinished) {
4032
        slot->GetStorage()->ObjectVerify(isolate());
4033 4034 4035 4036
      } else {
        CHECK_EQ(slot->materialization_state(),
                 TranslatedValue::kUninitialized);
      }
4037 4038
    }
  }
4039
#endif
4040 4041
}

4042
bool TranslatedState::DoUpdateFeedback() {
4043 4044
  if (!feedback_vector_handle_.is_null()) {
    CHECK(!feedback_slot_.IsInvalid());
4045
    isolate()->CountUsage(v8::Isolate::kDeoptimizerDisableSpeculation);
4046
    FeedbackNexus nexus(feedback_vector_handle_, feedback_slot_);
4047
    nexus.SetSpeculationMode(SpeculationMode::kDisallowSpeculation);
4048
    return true;
4049
  }
4050
  return false;
4051 4052 4053
}

void TranslatedState::ReadUpdateFeedback(TranslationIterator* iterator,
4054
                                         FixedArray literal_array,
4055
                                         FILE* trace_file) {
4056 4057 4058
  CHECK_EQ(Translation::UPDATE_FEEDBACK, iterator->Next());
  feedback_vector_ = FeedbackVector::cast(literal_array->get(iterator->Next()));
  feedback_slot_ = FeedbackSlot(iterator->Next());
4059 4060 4061 4062
  if (trace_file != nullptr) {
    PrintF(trace_file, "  reading FeedbackVector (slot %d)\n",
           feedback_slot_.ToInt());
  }
4063 4064
}

4065 4066
}  // namespace internal
}  // namespace v8
4067 4068 4069

// Undefine the heap manipulation macros.
#include "src/objects/object-macros-undef.h"