scopeinfo.cc 19.1 KB
Newer Older
1
// Copyright 2006-2008 the V8 project authors. All rights reserved.
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
//       copyright notice, this list of conditions and the following
//       disclaimer in the documentation and/or other materials provided
//       with the distribution.
//     * Neither the name of Google Inc. nor the names of its
//       contributors may be used to endorse or promote products derived
//       from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#include <stdlib.h>

#include "v8.h"

#include "scopeinfo.h"
#include "scopes.h"

35 36
namespace v8 {
namespace internal {
37 38 39


static int CompareLocal(Variable* const* v, Variable* const* w) {
40 41
  Slot* s = (*v)->AsSlot();
  Slot* t = (*w)->AsSlot();
42 43 44 45 46 47 48 49 50 51 52 53
  // We may have rewritten parameters (that are in the arguments object)
  // and which may have a NULL slot... - find a better solution...
  int x = (s != NULL ? s->index() : 0);
  int y = (t != NULL ? t->index() : 0);
  // Consider sorting them according to type as well?
  return x - y;
}


template<class Allocator>
ScopeInfo<Allocator>::ScopeInfo(Scope* scope)
    : function_name_(Factory::empty_symbol()),
54
      calls_eval_(scope->calls_eval()),
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
      parameters_(scope->num_parameters()),
      stack_slots_(scope->num_stack_slots()),
      context_slots_(scope->num_heap_slots()),
      context_modes_(scope->num_heap_slots()) {
  // Add parameters.
  for (int i = 0; i < scope->num_parameters(); i++) {
    ASSERT(parameters_.length() == i);
    parameters_.Add(scope->parameter(i)->name());
  }

  // Add stack locals and collect heap locals.
  // We are assuming that the locals' slots are allocated in
  // increasing order, so we can simply add them to the
  // ScopeInfo lists. However, due to usage analysis, this is
  // not true for context-allocated locals: Some of them
  // may be parameters which are allocated before the
  // non-parameter locals. When the non-parameter locals are
  // sorted according to usage, the allocated slot indices may
  // not be in increasing order with the variable list anymore.
  // Thus, we first collect the context-allocated locals, and then
  // sort them by context slot index before adding them to the
  // ScopeInfo list.
  List<Variable*, Allocator> locals(32);  // 32 is a wild guess
  ASSERT(locals.is_empty());
  scope->CollectUsedVariables(&locals);
  locals.Sort(&CompareLocal);

  List<Variable*, Allocator> heap_locals(locals.length());
  for (int i = 0; i < locals.length(); i++) {
    Variable* var = locals[i];
85
    if (var->is_used()) {
86
      Slot* slot = var->AsSlot();
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
      if (slot != NULL) {
        switch (slot->type()) {
          case Slot::PARAMETER:
            // explicitly added to parameters_ above - ignore
            break;

          case Slot::LOCAL:
            ASSERT(stack_slots_.length() == slot->index());
            stack_slots_.Add(var->name());
            break;

          case Slot::CONTEXT:
            heap_locals.Add(var);
            break;

          case Slot::LOOKUP:
103
            // This is currently not used.
104 105 106 107 108 109 110 111 112 113 114
            UNREACHABLE();
            break;
        }
      }
    }
  }

  // Add heap locals.
  if (scope->num_heap_slots() > 0) {
    // Add user-defined slots.
    for (int i = 0; i < heap_locals.length(); i++) {
115
      ASSERT(heap_locals[i]->AsSlot()->index() - Context::MIN_CONTEXT_SLOTS ==
116
             context_slots_.length());
117
      ASSERT(heap_locals[i]->AsSlot()->index() - Context::MIN_CONTEXT_SLOTS ==
118 119 120 121 122 123 124 125 126 127 128 129 130 131 132
             context_modes_.length());
      context_slots_.Add(heap_locals[i]->name());
      context_modes_.Add(heap_locals[i]->mode());
    }

  } else {
    ASSERT(heap_locals.length() == 0);
  }

  // Add the function context slot, if present.
  // For now, this must happen at the very end because of the
  // ordering of the scope info slots and the respective slot indices.
  if (scope->is_function_scope()) {
    Variable* var = scope->function();
    if (var != NULL &&
133
        var->is_used() &&
134
        var->AsSlot()->type() == Slot::CONTEXT) {
135 136 137 138 139
      function_name_ = var->name();
      // Note that we must not find the function name in the context slot
      // list - instead it must be handled separately in the
      // Contexts::Lookup() function. Thus record an empty symbol here so we
      // get the correct number of context slots.
140
      ASSERT(var->AsSlot()->index() - Context::MIN_CONTEXT_SLOTS ==
141
             context_slots_.length());
142
      ASSERT(var->AsSlot()->index() - Context::MIN_CONTEXT_SLOTS ==
143 144 145 146 147 148 149 150
             context_modes_.length());
      context_slots_.Add(Factory::empty_symbol());
      context_modes_.Add(Variable::INTERNAL);
    }
  }
}


151
// Encoding format in a FixedArray object:
152 153 154
//
// - function name
//
155 156
// - calls eval boolean flag
//
157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215
// - number of variables in the context object (smi) (= function context
//   slot index + 1)
// - list of pairs (name, Var mode) of context-allocated variables (starting
//   with context slot 0)
//
// - number of parameters (smi)
// - list of parameter names (starting with parameter 0 first)
//
// - number of variables on the stack (smi)
// - list of names of stack-allocated variables (starting with stack slot 0)

// The ScopeInfo representation could be simplified and the ScopeInfo
// re-implemented (with almost the same interface). Here is a
// suggestion for the new format:
//
// - have a single list with all variable names (parameters, stack locals,
//   context locals), followed by a list of non-Object* values containing
//   the variables information (what kind, index, attributes)
// - searching the linear list of names is fast and yields an index into the
//   list if the variable name is found
// - that list index is then used to find the variable information in the
//   subsequent list
// - the list entries don't have to be in any particular order, so all the
//   current sorting business can go away
// - the ScopeInfo lookup routines can be reduced to perhaps a single lookup
//   which returns all information at once
// - when gathering the information from a Scope, we only need to iterate
//   through the local variables (parameters and context info is already
//   present)


static inline Object** ReadInt(Object** p, int* x) {
  *x = (reinterpret_cast<Smi*>(*p++))->value();
  return p;
}


static inline Object** ReadBool(Object** p, bool* x) {
  *x = (reinterpret_cast<Smi*>(*p++))->value() != 0;
  return p;
}


static inline Object** ReadSymbol(Object** p, Handle<String>* s) {
  *s = Handle<String>(reinterpret_cast<String*>(*p++));
  return p;
}


template <class Allocator>
static Object** ReadList(Object** p, List<Handle<String>, Allocator >* list) {
  ASSERT(list->is_empty());
  int n;
  p = ReadInt(p, &n);
  while (n-- > 0) {
    Handle<String> s;
    p = ReadSymbol(p, &s);
    list->Add(s);
  }
216
  return p;
217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234
}


template <class Allocator>
static Object** ReadList(Object** p,
                         List<Handle<String>, Allocator>* list,
                         List<Variable::Mode, Allocator>* modes) {
  ASSERT(list->is_empty());
  int n;
  p = ReadInt(p, &n);
  while (n-- > 0) {
    Handle<String> s;
    int m;
    p = ReadSymbol(p, &s);
    p = ReadInt(p, &m);
    list->Add(s);
    modes->Add(static_cast<Variable::Mode>(m));
  }
235
  return p;
236 237 238 239
}


template<class Allocator>
240
ScopeInfo<Allocator>::ScopeInfo(SerializedScopeInfo* data)
241 242 243 244 245
  : function_name_(Factory::empty_symbol()),
    parameters_(4),
    stack_slots_(8),
    context_slots_(8),
    context_modes_(8) {
246 247
  if (data->length() > 0) {
    Object** p0 = data->data_start();
248 249 250 251 252 253 254 255
    Object** p = p0;
    p = ReadSymbol(p, &function_name_);
    p = ReadBool(p, &calls_eval_);
    p = ReadList<Allocator>(p, &context_slots_, &context_modes_);
    p = ReadList<Allocator>(p, &parameters_);
    p = ReadList<Allocator>(p, &stack_slots_);
    ASSERT((p - p0) == FixedArray::cast(data)->length());
  }
256 257 258 259 260 261 262 263 264
}


static inline Object** WriteInt(Object** p, int x) {
  *p++ = Smi::FromInt(x);
  return p;
}


265 266 267 268 269 270
static inline Object** WriteBool(Object** p, bool b) {
  *p++ = Smi::FromInt(b ? 1 : 0);
  return p;
}


271 272 273 274 275 276 277 278 279 280 281 282 283
static inline Object** WriteSymbol(Object** p, Handle<String> s) {
  *p++ = *s;
  return p;
}


template <class Allocator>
static Object** WriteList(Object** p, List<Handle<String>, Allocator >* list) {
  const int n = list->length();
  p = WriteInt(p, n);
  for (int i = 0; i < n; i++) {
    p = WriteSymbol(p, list->at(i));
  }
284
  return p;
285 286 287 288 289 290 291 292 293 294 295 296 297
}


template <class Allocator>
static Object** WriteList(Object** p,
                          List<Handle<String>, Allocator>* list,
                          List<Variable::Mode, Allocator>* modes) {
  const int n = list->length();
  p = WriteInt(p, n);
  for (int i = 0; i < n; i++) {
    p = WriteSymbol(p, list->at(i));
    p = WriteInt(p, modes->at(i));
  }
298
  return p;
299 300 301 302
}


template<class Allocator>
303 304 305
Handle<SerializedScopeInfo> ScopeInfo<Allocator>::Serialize() {
  // function name, calls eval, length for 3 tables:
  const int extra_slots = 1 + 1 + 3;
306 307 308 309
  int length = extra_slots +
               context_slots_.length() * 2 +
               parameters_.length() +
               stack_slots_.length();
310

311 312
  Handle<SerializedScopeInfo> data(
      SerializedScopeInfo::cast(*Factory::NewFixedArray(length, TENURED)));
313
  AssertNoAllocation nogc;
314

315
  Object** p0 = data->data_start();
316 317 318 319 320 321 322
  Object** p = p0;
  p = WriteSymbol(p, function_name_);
  p = WriteBool(p, calls_eval_);
  p = WriteList(p, &context_slots_, &context_modes_);
  p = WriteList(p, &parameters_);
  p = WriteList(p, &stack_slots_);
  ASSERT((p - p0) == length);
323

324
  return data;
325 326 327
}


328 329 330 331 332 333 334 335 336 337 338
template<class Allocator>
Handle<String> ScopeInfo<Allocator>::LocalName(int i) const {
  // A local variable can be allocated either on the stack or in the context.
  // For variables allocated in the context they are always preceded by
  // Context::MIN_CONTEXT_SLOTS of fixed allocated slots in the context.
  if (i < number_of_stack_slots()) {
    return stack_slot_name(i);
  } else {
    return context_slot_name(i - number_of_stack_slots() +
                             Context::MIN_CONTEXT_SLOTS);
  }
339 340 341
}


342 343 344 345 346 347 348 349
template<class Allocator>
int ScopeInfo<Allocator>::NumberOfLocals() const {
  int number_of_locals = number_of_stack_slots();
  if (number_of_context_slots() > 0) {
    ASSERT(number_of_context_slots() >= Context::MIN_CONTEXT_SLOTS);
    number_of_locals += number_of_context_slots() - Context::MIN_CONTEXT_SLOTS;
  }
  return number_of_locals;
350 351 352
}


353 354 355
Handle<SerializedScopeInfo> SerializedScopeInfo::Create(Scope* scope) {
  ScopeInfo<ZoneListAllocationPolicy> sinfo(scope);
  return sinfo.Serialize();
356 357 358
}


359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390
SerializedScopeInfo* SerializedScopeInfo::Empty() {
  return reinterpret_cast<SerializedScopeInfo*>(Heap::empty_fixed_array());
}


Object** SerializedScopeInfo::ContextEntriesAddr() {
  ASSERT(length() > 0);
  return data_start() + 2;  // +2 for function name and calls eval.
}


Object** SerializedScopeInfo::ParameterEntriesAddr() {
  ASSERT(length() > 0);
  Object** p = ContextEntriesAddr();
  int number_of_context_slots;
  p = ReadInt(p, &number_of_context_slots);
  return p + number_of_context_slots*2;  // *2 for pairs
}


Object** SerializedScopeInfo::StackSlotEntriesAddr() {
  ASSERT(length() > 0);
  Object** p = ParameterEntriesAddr();
  int number_of_parameter_slots;
  p = ReadInt(p, &number_of_parameter_slots);
  return p + number_of_parameter_slots;
}


bool SerializedScopeInfo::CallsEval() {
  if (length() > 0) {
    Object** p = data_start() + 1;  // +1 for function name.
391 392 393 394 395 396 397 398
    bool calls_eval;
    p = ReadBool(p, &calls_eval);
    return calls_eval;
  }
  return true;
}


399 400 401 402 403 404
int SerializedScopeInfo::NumberOfStackSlots() {
  if (length() > 0) {
    Object** p = StackSlotEntriesAddr();
    int number_of_stack_slots;
    ReadInt(p, &number_of_stack_slots);
    return number_of_stack_slots;
405 406 407 408 409
  }
  return 0;
}


410 411 412 413 414 415
int SerializedScopeInfo::NumberOfContextSlots() {
  if (length() > 0) {
    Object** p = ContextEntriesAddr();
    int number_of_context_slots;
    ReadInt(p, &number_of_context_slots);
    return number_of_context_slots + Context::MIN_CONTEXT_SLOTS;
416 417 418 419 420
  }
  return 0;
}


421 422 423 424 425 426
bool SerializedScopeInfo::HasHeapAllocatedLocals() {
  if (length() > 0) {
    Object** p = ContextEntriesAddr();
    int number_of_context_slots;
    ReadInt(p, &number_of_context_slots);
    return number_of_context_slots > 0;
427 428 429 430 431
  }
  return false;
}


432
int SerializedScopeInfo::StackSlotIndex(String* name) {
433
  ASSERT(name->IsSymbol());
434 435 436 437 438
  if (length() > 0) {
    // Slots start after length entry.
    Object** p0 = StackSlotEntriesAddr();
    int number_of_stack_slots;
    p0 = ReadInt(p0, &number_of_stack_slots);
439
    Object** p = p0;
440 441
    Object** end = p0 + number_of_stack_slots;
    while (p != end) {
442
      if (*p == name) return static_cast<int>(p - p0);
443 444 445 446 447 448
      p++;
    }
  }
  return -1;
}

449
int SerializedScopeInfo::ContextSlotIndex(String* name, Variable::Mode* mode) {
450
  ASSERT(name->IsSymbol());
451
  int result = ContextSlotCache::Lookup(this, name, mode);
452
  if (result != ContextSlotCache::kNotFound) return result;
453 454 455 456 457
  if (length() > 0) {
    // Slots start after length entry.
    Object** p0 = ContextEntriesAddr();
    int number_of_context_slots;
    p0 = ReadInt(p0, &number_of_context_slots);
458
    Object** p = p0;
459 460
    Object** end = p0 + number_of_context_slots * 2;
    while (p != end) {
461 462
      if (*p == name) {
        ASSERT(((p - p0) & 1) == 0);
463 464 465 466
        int v;
        ReadInt(p + 1, &v);
        Variable::Mode mode_value = static_cast<Variable::Mode>(v);
        if (mode != NULL) *mode = mode_value;
467
        result = static_cast<int>((p - p0) >> 1) + Context::MIN_CONTEXT_SLOTS;
468
        ContextSlotCache::Update(this, name, mode_value, result);
469
        return result;
470 471 472 473
      }
      p += 2;
    }
  }
474
  ContextSlotCache::Update(this, name, Variable::INTERNAL, -1);
475 476 477 478
  return -1;
}


479
int SerializedScopeInfo::ParameterIndex(String* name) {
480
  ASSERT(name->IsSymbol());
481
  if (length() > 0) {
482 483 484 485 486 487 488 489 490 491
    // We must read parameters from the end since for
    // multiply declared parameters the value of the
    // last declaration of that parameter is used
    // inside a function (and thus we need to look
    // at the last index). Was bug# 1110337.
    //
    // Eventually, we should only register such parameters
    // once, with corresponding index. This requires a new
    // implementation of the ScopeInfo code. See also other
    // comments in this file regarding this.
492 493 494 495
    Object** p = ParameterEntriesAddr();
    int number_of_parameter_slots;
    Object** p0 = ReadInt(p, &number_of_parameter_slots);
    p = p0 + number_of_parameter_slots;
496 497
    while (p > p0) {
      p--;
498
      if (*p == name) return static_cast<int>(p - p0);
499 500 501 502 503 504
    }
  }
  return -1;
}


505
int SerializedScopeInfo::FunctionContextSlotIndex(String* name) {
506
  ASSERT(name->IsSymbol());
507 508
  if (length() > 0) {
    Object** p = data_start();
509
    if (*p == name) {
510 511 512 513
      p = ContextEntriesAddr();
      int number_of_context_slots;
      ReadInt(p, &number_of_context_slots);
      ASSERT(number_of_context_slots != 0);
514
      // The function context slot is the last entry.
515
      return number_of_context_slots + Context::MIN_CONTEXT_SLOTS - 1;
516 517 518 519 520 521
    }
  }
  return -1;
}


522
int ContextSlotCache::Hash(Object* data, String* name) {
523 524
  // Uses only lower 32 bits if pointers are larger.
  uintptr_t addr_hash =
525
      static_cast<uint32_t>(reinterpret_cast<uintptr_t>(data)) >> 2;
526
  return static_cast<int>((addr_hash ^ name->Hash()) % kLength);
527 528 529
}


530
int ContextSlotCache::Lookup(Object* data,
531 532
                             String* name,
                             Variable::Mode* mode) {
533
  int index = Hash(data, name);
534
  Key& key = keys_[index];
535
  if ((key.data == data) && key.name->Equals(name)) {
536 537 538 539 540 541 542 543
    Value result(values_[index]);
    if (mode != NULL) *mode = result.mode();
    return result.index() + kNotFound;
  }
  return kNotFound;
}


544
void ContextSlotCache::Update(Object* data,
545 546 547 548 549 550
                              String* name,
                              Variable::Mode mode,
                              int slot_index) {
  String* symbol;
  ASSERT(slot_index > kNotFound);
  if (Heap::LookupSymbolIfExists(name, &symbol)) {
551
    int index = Hash(data, symbol);
552
    Key& key = keys_[index];
553
    key.data = data;
554 555 556 557
    key.name = symbol;
    // Please note value only takes a uint as index.
    values_[index] = Value(mode, slot_index - kNotFound).raw();
#ifdef DEBUG
558
    ValidateEntry(data, name, mode, slot_index);
559 560 561 562 563 564
#endif
  }
}


void ContextSlotCache::Clear() {
565
  for (int index = 0; index < kLength; index++) keys_[index].data = NULL;
566 567 568 569 570 571 572 573 574
}


ContextSlotCache::Key ContextSlotCache::keys_[ContextSlotCache::kLength];


uint32_t ContextSlotCache::values_[ContextSlotCache::kLength];


575
#ifdef DEBUG
576

577
void ContextSlotCache::ValidateEntry(Object* data,
578 579 580 581 582
                                     String* name,
                                     Variable::Mode mode,
                                     int slot_index) {
  String* symbol;
  if (Heap::LookupSymbolIfExists(name, &symbol)) {
583
    int index = Hash(data, name);
584
    Key& key = keys_[index];
585
    ASSERT(key.data == data);
586 587 588 589 590 591 592 593
    ASSERT(key.name->Equals(name));
    Value result(values_[index]);
    ASSERT(result.mode() == mode);
    ASSERT(result.index() + kNotFound == slot_index);
  }
}


594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633
template <class Allocator>
static void PrintList(const char* list_name,
                      int nof_internal_slots,
                      List<Handle<String>, Allocator>& list) {
  if (list.length() > 0) {
    PrintF("\n  // %s\n", list_name);
    if (nof_internal_slots > 0) {
      PrintF("  %2d - %2d [internal slots]\n", 0 , nof_internal_slots - 1);
    }
    for (int i = 0; i < list.length(); i++) {
      PrintF("  %2d ", i + nof_internal_slots);
      list[i]->ShortPrint();
      PrintF("\n");
    }
  }
}


template<class Allocator>
void ScopeInfo<Allocator>::Print() {
  PrintF("ScopeInfo ");
  if (function_name_->length() > 0)
    function_name_->ShortPrint();
  else
    PrintF("/* no function name */");
  PrintF("{");

  PrintList<Allocator>("parameters", 0, parameters_);
  PrintList<Allocator>("stack slots", 0, stack_slots_);
  PrintList<Allocator>("context slots", Context::MIN_CONTEXT_SLOTS,
                       context_slots_);

  PrintF("}\n");
}
#endif  // DEBUG


// Make sure the classes get instantiated by the template system.
template class ScopeInfo<FreeStoreAllocationPolicy>;
template class ScopeInfo<PreallocatedStorage>;
634
template class ScopeInfo<ZoneListAllocationPolicy>;
635 636

} }  // namespace v8::internal