blob: d3f54ad3f2d9ad8b47fefae2d89fd692bd3e2eda [file] [log] [blame]
Ben Murdochf87a2032010-10-22 12:50:53 +01001// Copyright 2010 the V8 project authors. All rights reserved.
Steve Blocka7e24c12009-10-30 11:49:00 +00002// Redistribution and use in source and binary forms, with or without
3// modification, are permitted provided that the following conditions are
4// met:
5//
6// * Redistributions of source code must retain the above copyright
7// notice, this list of conditions and the following disclaimer.
8// * Redistributions in binary form must reproduce the above
9// copyright notice, this list of conditions and the following
10// disclaimer in the documentation and/or other materials provided
11// with the distribution.
12// * Neither the name of Google Inc. nor the names of its
13// contributors may be used to endorse or promote products derived
14// from this software without specific prior written permission.
15//
16// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27
28#include "v8.h"
29
Ben Murdochf87a2032010-10-22 12:50:53 +010030#include "scopes.h"
31
32#include "bootstrapper.h"
33#include "compiler.h"
Steve Blocka7e24c12009-10-30 11:49:00 +000034#include "prettyprinter.h"
35#include "scopeinfo.h"
Steve Blocka7e24c12009-10-30 11:49:00 +000036
37namespace v8 {
38namespace internal {
39
40// ----------------------------------------------------------------------------
41// A Zone allocator for use with LocalsMap.
42
43class ZoneAllocator: public Allocator {
44 public:
45 /* nothing to do */
46 virtual ~ZoneAllocator() {}
47
Steve Blockd0582a62009-12-15 09:54:21 +000048 virtual void* New(size_t size) { return Zone::New(static_cast<int>(size)); }
Steve Blocka7e24c12009-10-30 11:49:00 +000049
50 /* ignored - Zone is freed in one fell swoop */
51 virtual void Delete(void* p) {}
52};
53
54
55static ZoneAllocator LocalsMapAllocator;
56
57
58// ----------------------------------------------------------------------------
59// Implementation of LocalsMap
60//
61// Note: We are storing the handle locations as key values in the hash map.
62// When inserting a new variable via Declare(), we rely on the fact that
63// the handle location remains alive for the duration of that variable
64// use. Because a Variable holding a handle with the same location exists
65// this is ensured.
66
67static bool Match(void* key1, void* key2) {
68 String* name1 = *reinterpret_cast<String**>(key1);
69 String* name2 = *reinterpret_cast<String**>(key2);
70 ASSERT(name1->IsSymbol());
71 ASSERT(name2->IsSymbol());
72 return name1 == name2;
73}
74
75
76// Dummy constructor
77VariableMap::VariableMap(bool gotta_love_static_overloading) : HashMap() {}
78
79VariableMap::VariableMap() : HashMap(Match, &LocalsMapAllocator, 8) {}
80VariableMap::~VariableMap() {}
81
82
83Variable* VariableMap::Declare(Scope* scope,
84 Handle<String> name,
85 Variable::Mode mode,
86 bool is_valid_lhs,
87 Variable::Kind kind) {
88 HashMap::Entry* p = HashMap::Lookup(name.location(), name->Hash(), true);
89 if (p->value == NULL) {
90 // The variable has not been declared yet -> insert it.
91 ASSERT(p->key == name.location());
92 p->value = new Variable(scope, name, mode, is_valid_lhs, kind);
93 }
94 return reinterpret_cast<Variable*>(p->value);
95}
96
97
98Variable* VariableMap::Lookup(Handle<String> name) {
99 HashMap::Entry* p = HashMap::Lookup(name.location(), name->Hash(), false);
100 if (p != NULL) {
101 ASSERT(*reinterpret_cast<String**>(p->key) == *name);
102 ASSERT(p->value != NULL);
103 return reinterpret_cast<Variable*>(p->value);
104 }
105 return NULL;
106}
107
108
109// ----------------------------------------------------------------------------
110// Implementation of Scope
111
112
113// Dummy constructor
114Scope::Scope(Type type)
Ben Murdochb8e0da22011-05-16 14:20:40 +0100115 : inner_scopes_(0),
Steve Blocka7e24c12009-10-30 11:49:00 +0000116 variables_(false),
117 temps_(0),
118 params_(0),
Steve Blocka7e24c12009-10-30 11:49:00 +0000119 unresolved_(0),
Ben Murdochb8e0da22011-05-16 14:20:40 +0100120 decls_(0) {
121 SetDefaults(type, NULL, NULL);
122 ASSERT(!resolved());
Steve Blocka7e24c12009-10-30 11:49:00 +0000123}
124
125
126Scope::Scope(Scope* outer_scope, Type type)
Ben Murdochb8e0da22011-05-16 14:20:40 +0100127 : inner_scopes_(4),
128 variables_(),
Steve Blocka7e24c12009-10-30 11:49:00 +0000129 temps_(4),
130 params_(4),
Steve Blocka7e24c12009-10-30 11:49:00 +0000131 unresolved_(16),
Ben Murdochb8e0da22011-05-16 14:20:40 +0100132 decls_(4) {
133 SetDefaults(type, outer_scope, NULL);
Steve Blocka7e24c12009-10-30 11:49:00 +0000134 // At some point we might want to provide outer scopes to
135 // eval scopes (by walking the stack and reading the scope info).
136 // In that case, the ASSERT below needs to be adjusted.
137 ASSERT((type == GLOBAL_SCOPE || type == EVAL_SCOPE) == (outer_scope == NULL));
138 ASSERT(!HasIllegalRedeclaration());
Ben Murdochb8e0da22011-05-16 14:20:40 +0100139 ASSERT(!resolved());
Steve Blocka7e24c12009-10-30 11:49:00 +0000140}
141
142
Ben Murdochb8e0da22011-05-16 14:20:40 +0100143Scope::Scope(Scope* inner_scope, SerializedScopeInfo* scope_info)
144 : inner_scopes_(4),
145 variables_(),
146 temps_(4),
147 params_(4),
148 unresolved_(16),
149 decls_(4) {
150 ASSERT(scope_info != NULL);
151 SetDefaults(FUNCTION_SCOPE, inner_scope->outer_scope(), scope_info);
152 ASSERT(resolved());
153 InsertAfterScope(inner_scope);
154 if (scope_info->HasHeapAllocatedLocals()) {
155 num_heap_slots_ = scope_info_->NumberOfContextSlots();
156 }
157
158 // This scope's arguments shadow (if present) is context-allocated if an inner
159 // scope accesses this one's parameters. Allocate the arguments_shadow_
160 // variable if necessary.
161 Variable::Mode mode;
162 int arguments_shadow_index =
163 scope_info_->ContextSlotIndex(Heap::arguments_shadow_symbol(), &mode);
164 if (arguments_shadow_index >= 0) {
165 ASSERT(mode == Variable::INTERNAL);
166 arguments_shadow_ = new Variable(this,
167 Factory::arguments_shadow_symbol(),
168 Variable::INTERNAL,
169 true,
170 Variable::ARGUMENTS);
171 arguments_shadow_->set_rewrite(
172 new Slot(arguments_shadow_, Slot::CONTEXT, arguments_shadow_index));
173 arguments_shadow_->set_is_used(true);
174 }
175}
176
177
178
Ben Murdochf87a2032010-10-22 12:50:53 +0100179bool Scope::Analyze(CompilationInfo* info) {
180 ASSERT(info->function() != NULL);
181 Scope* top = info->function()->scope();
Ben Murdochb8e0da22011-05-16 14:20:40 +0100182
183 // If we have a serialized scope info, reuse it.
184 if (!info->closure().is_null()) {
185 SerializedScopeInfo* scope_info = info->closure()->shared()->scope_info();
186 if (scope_info != SerializedScopeInfo::Empty()) {
187 Scope* scope = top;
188 JSFunction* current = *info->closure();
189 do {
190 current = current->context()->closure();
191 SerializedScopeInfo* scope_info = current->shared()->scope_info();
192 if (scope_info != SerializedScopeInfo::Empty()) {
193 scope = new Scope(scope, scope_info);
194 } else {
195 ASSERT(current->context()->IsGlobalContext());
196 }
197 } while (!current->context()->IsGlobalContext());
198 }
199 }
200
Ben Murdochf87a2032010-10-22 12:50:53 +0100201 while (top->outer_scope() != NULL) top = top->outer_scope();
202 top->AllocateVariables(info->calling_context());
203
204#ifdef DEBUG
205 if (Bootstrapper::IsActive()
206 ? FLAG_print_builtin_scopes
207 : FLAG_print_scopes) {
208 info->function()->scope()->Print();
209 }
210#endif
211
212 info->SetScope(info->function()->scope());
213 return true; // Can not fail.
214}
215
216
Steve Blocka7e24c12009-10-30 11:49:00 +0000217void Scope::Initialize(bool inside_with) {
Ben Murdochb8e0da22011-05-16 14:20:40 +0100218 ASSERT(!resolved());
219
Steve Blocka7e24c12009-10-30 11:49:00 +0000220 // Add this scope as a new inner scope of the outer scope.
221 if (outer_scope_ != NULL) {
222 outer_scope_->inner_scopes_.Add(this);
223 scope_inside_with_ = outer_scope_->scope_inside_with_ || inside_with;
224 } else {
225 scope_inside_with_ = inside_with;
226 }
227
228 // Declare convenience variables.
229 // Declare and allocate receiver (even for the global scope, and even
230 // if naccesses_ == 0).
231 // NOTE: When loading parameters in the global scope, we must take
232 // care not to access them as properties of the global object, but
233 // instead load them directly from the stack. Currently, the only
234 // such parameter is 'this' which is passed on the stack when
235 // invoking scripts
236 Variable* var =
237 variables_.Declare(this, Factory::this_symbol(), Variable::VAR,
238 false, Variable::THIS);
Ben Murdochb8e0da22011-05-16 14:20:40 +0100239 var->set_rewrite(new Slot(var, Slot::PARAMETER, -1));
Leon Clarkee46be812010-01-19 14:06:41 +0000240 receiver_ = var;
Steve Blocka7e24c12009-10-30 11:49:00 +0000241
242 if (is_function_scope()) {
243 // Declare 'arguments' variable which exists in all functions.
244 // Note that it might never be accessed, in which case it won't be
245 // allocated during variable allocation.
246 variables_.Declare(this, Factory::arguments_symbol(), Variable::VAR,
247 true, Variable::ARGUMENTS);
248 }
249}
250
251
Steve Blocka7e24c12009-10-30 11:49:00 +0000252Variable* Scope::LocalLookup(Handle<String> name) {
Ben Murdochb8e0da22011-05-16 14:20:40 +0100253 Variable* result = variables_.Lookup(name);
254 if (result != NULL || !resolved()) {
255 return result;
256 }
257 // If the scope is resolved, we can find a variable in serialized scope info.
258
259 // We should never lookup 'arguments' in this scope
260 // as it is implicitly present in any scope.
261 ASSERT(*name != *Factory::arguments_symbol());
262
263 // Assert that there is no local slot with the given name.
264 ASSERT(scope_info_->StackSlotIndex(*name) < 0);
265
266 // Check context slot lookup.
267 Variable::Mode mode;
268 int index = scope_info_->ContextSlotIndex(*name, &mode);
269 if (index >= 0) {
270 Variable* var =
271 variables_.Declare(this, name, mode, true, Variable::NORMAL);
272 var->set_rewrite(new Slot(var, Slot::CONTEXT, index));
273 return var;
274 }
275
276 index = scope_info_->ParameterIndex(*name);
277 if (index >= 0) {
278 // ".arguments" must be present in context slots.
279 ASSERT(arguments_shadow_ != NULL);
280 Variable* var =
281 variables_.Declare(this, name, Variable::VAR, true, Variable::NORMAL);
282 Property* rewrite =
283 new Property(new VariableProxy(arguments_shadow_),
284 new Literal(Handle<Object>(Smi::FromInt(index))),
285 RelocInfo::kNoPosition,
286 Property::SYNTHETIC);
287 rewrite->set_is_arguments_access(true);
288 var->set_rewrite(rewrite);
289 return var;
290 }
291
292 index = scope_info_->FunctionContextSlotIndex(*name);
293 if (index >= 0) {
294 // Check that there is no local slot with the given name.
295 ASSERT(scope_info_->StackSlotIndex(*name) < 0);
296 Variable* var =
297 variables_.Declare(this, name, Variable::VAR, true, Variable::NORMAL);
298 var->set_rewrite(new Slot(var, Slot::CONTEXT, index));
299 return var;
300 }
301
302 return NULL;
Steve Blocka7e24c12009-10-30 11:49:00 +0000303}
304
305
306Variable* Scope::Lookup(Handle<String> name) {
307 for (Scope* scope = this;
308 scope != NULL;
309 scope = scope->outer_scope()) {
310 Variable* var = scope->LocalLookup(name);
311 if (var != NULL) return var;
312 }
313 return NULL;
314}
315
316
317Variable* Scope::DeclareFunctionVar(Handle<String> name) {
318 ASSERT(is_function_scope() && function_ == NULL);
319 function_ = new Variable(this, name, Variable::CONST, true, Variable::NORMAL);
320 return function_;
321}
322
323
324Variable* Scope::DeclareLocal(Handle<String> name, Variable::Mode mode) {
325 // DYNAMIC variables are introduces during variable allocation,
326 // INTERNAL variables are allocated explicitly, and TEMPORARY
327 // variables are allocated via NewTemporary().
Ben Murdochb8e0da22011-05-16 14:20:40 +0100328 ASSERT(!resolved());
Steve Blocka7e24c12009-10-30 11:49:00 +0000329 ASSERT(mode == Variable::VAR || mode == Variable::CONST);
330 return variables_.Declare(this, name, mode, true, Variable::NORMAL);
331}
332
333
334Variable* Scope::DeclareGlobal(Handle<String> name) {
335 ASSERT(is_global_scope());
Leon Clarkee46be812010-01-19 14:06:41 +0000336 return variables_.Declare(this, name, Variable::DYNAMIC_GLOBAL, true,
Steve Blocka7e24c12009-10-30 11:49:00 +0000337 Variable::NORMAL);
338}
339
340
341void Scope::AddParameter(Variable* var) {
342 ASSERT(is_function_scope());
343 ASSERT(LocalLookup(var->name()) == var);
344 params_.Add(var);
345}
346
347
348VariableProxy* Scope::NewUnresolved(Handle<String> name, bool inside_with) {
349 // Note that we must not share the unresolved variables with
350 // the same name because they may be removed selectively via
351 // RemoveUnresolved().
Ben Murdochb8e0da22011-05-16 14:20:40 +0100352 ASSERT(!resolved());
Steve Blocka7e24c12009-10-30 11:49:00 +0000353 VariableProxy* proxy = new VariableProxy(name, false, inside_with);
354 unresolved_.Add(proxy);
355 return proxy;
356}
357
358
359void Scope::RemoveUnresolved(VariableProxy* var) {
360 // Most likely (always?) any variable we want to remove
361 // was just added before, so we search backwards.
362 for (int i = unresolved_.length(); i-- > 0;) {
363 if (unresolved_[i] == var) {
364 unresolved_.Remove(i);
365 return;
366 }
367 }
368}
369
370
Ben Murdochb0fe1622011-05-05 13:52:32 +0100371Variable* Scope::NewTemporary(Handle<String> name) {
Ben Murdochb8e0da22011-05-16 14:20:40 +0100372 ASSERT(!resolved());
Ben Murdochb0fe1622011-05-05 13:52:32 +0100373 Variable* var =
374 new Variable(this, name, Variable::TEMPORARY, true, Variable::NORMAL);
Steve Blocka7e24c12009-10-30 11:49:00 +0000375 temps_.Add(var);
Ben Murdochb0fe1622011-05-05 13:52:32 +0100376 return var;
Steve Blocka7e24c12009-10-30 11:49:00 +0000377}
378
379
380void Scope::AddDeclaration(Declaration* declaration) {
381 decls_.Add(declaration);
382}
383
384
385void Scope::SetIllegalRedeclaration(Expression* expression) {
386 // Only set the illegal redeclaration expression the
387 // first time the function is called.
388 if (!HasIllegalRedeclaration()) {
389 illegal_redecl_ = expression;
390 }
391 ASSERT(HasIllegalRedeclaration());
392}
393
394
395void Scope::VisitIllegalRedeclaration(AstVisitor* visitor) {
396 ASSERT(HasIllegalRedeclaration());
397 illegal_redecl_->Accept(visitor);
398}
399
400
401template<class Allocator>
402void Scope::CollectUsedVariables(List<Variable*, Allocator>* locals) {
403 // Collect variables in this scope.
404 // Note that the function_ variable - if present - is not
405 // collected here but handled separately in ScopeInfo
406 // which is the current user of this function).
407 for (int i = 0; i < temps_.length(); i++) {
408 Variable* var = temps_[i];
Steve Block6ded16b2010-05-10 14:33:55 +0100409 if (var->is_used()) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000410 locals->Add(var);
411 }
412 }
413 for (VariableMap::Entry* p = variables_.Start();
414 p != NULL;
415 p = variables_.Next(p)) {
416 Variable* var = reinterpret_cast<Variable*>(p->value);
Steve Block6ded16b2010-05-10 14:33:55 +0100417 if (var->is_used()) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000418 locals->Add(var);
419 }
420 }
421}
422
423
424// Make sure the method gets instantiated by the template system.
425template void Scope::CollectUsedVariables(
426 List<Variable*, FreeStoreAllocationPolicy>* locals);
427template void Scope::CollectUsedVariables(
428 List<Variable*, PreallocatedStorage>* locals);
429template void Scope::CollectUsedVariables(
430 List<Variable*, ZoneListAllocationPolicy>* locals);
431
432
433void Scope::AllocateVariables(Handle<Context> context) {
434 ASSERT(outer_scope_ == NULL); // eval or global scopes only
435
436 // 1) Propagate scope information.
437 // If we are in an eval scope, we may have other outer scopes about
438 // which we don't know anything at this point. Thus we must be conservative
439 // and assume they may invoke eval themselves. Eventually we could capture
440 // this information in the ScopeInfo and then use it here (by traversing
441 // the call chain stack, at compile time).
442 bool eval_scope = is_eval_scope();
443 PropagateScopeInfo(eval_scope, eval_scope);
444
445 // 2) Resolve variables.
446 Scope* global_scope = NULL;
447 if (is_global_scope()) global_scope = this;
448 ResolveVariablesRecursively(global_scope, context);
449
450 // 3) Allocate variables.
451 AllocateVariablesRecursively();
452}
453
454
455bool Scope::AllowsLazyCompilation() const {
456 return !force_eager_compilation_ && HasTrivialOuterContext();
457}
458
459
460bool Scope::HasTrivialContext() const {
461 // A function scope has a trivial context if it always is the global
462 // context. We iteratively scan out the context chain to see if
463 // there is anything that makes this scope non-trivial; otherwise we
464 // return true.
465 for (const Scope* scope = this; scope != NULL; scope = scope->outer_scope_) {
466 if (scope->is_eval_scope()) return false;
467 if (scope->scope_inside_with_) return false;
468 if (scope->num_heap_slots_ > 0) return false;
469 }
470 return true;
471}
472
473
474bool Scope::HasTrivialOuterContext() const {
475 Scope* outer = outer_scope_;
476 if (outer == NULL) return true;
477 // Note that the outer context may be trivial in general, but the current
478 // scope may be inside a 'with' statement in which case the outer context
479 // for this scope is not trivial.
480 return !scope_inside_with_ && outer->HasTrivialContext();
481}
482
483
484int Scope::ContextChainLength(Scope* scope) {
485 int n = 0;
486 for (Scope* s = this; s != scope; s = s->outer_scope_) {
487 ASSERT(s != NULL); // scope must be in the scope chain
488 if (s->num_heap_slots() > 0) n++;
489 }
490 return n;
491}
492
493
494#ifdef DEBUG
495static const char* Header(Scope::Type type) {
496 switch (type) {
497 case Scope::EVAL_SCOPE: return "eval";
498 case Scope::FUNCTION_SCOPE: return "function";
499 case Scope::GLOBAL_SCOPE: return "global";
500 }
501 UNREACHABLE();
502 return NULL;
503}
504
505
506static void Indent(int n, const char* str) {
507 PrintF("%*s%s", n, "", str);
508}
509
510
511static void PrintName(Handle<String> name) {
512 SmartPointer<char> s = name->ToCString(DISALLOW_NULLS);
513 PrintF("%s", *s);
514}
515
516
517static void PrintVar(PrettyPrinter* printer, int indent, Variable* var) {
Steve Block6ded16b2010-05-10 14:33:55 +0100518 if (var->is_used() || var->rewrite() != NULL) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000519 Indent(indent, Variable::Mode2String(var->mode()));
520 PrintF(" ");
521 PrintName(var->name());
522 PrintF("; // ");
Steve Block6ded16b2010-05-10 14:33:55 +0100523 if (var->rewrite() != NULL) {
524 PrintF("%s, ", printer->Print(var->rewrite()));
525 if (var->is_accessed_from_inner_scope()) PrintF(", ");
526 }
527 if (var->is_accessed_from_inner_scope()) PrintF("inner scope access");
Steve Blocka7e24c12009-10-30 11:49:00 +0000528 PrintF("\n");
529 }
530}
531
532
533static void PrintMap(PrettyPrinter* printer, int indent, VariableMap* map) {
534 for (VariableMap::Entry* p = map->Start(); p != NULL; p = map->Next(p)) {
535 Variable* var = reinterpret_cast<Variable*>(p->value);
536 PrintVar(printer, indent, var);
537 }
538}
539
540
541void Scope::Print(int n) {
542 int n0 = (n > 0 ? n : 0);
543 int n1 = n0 + 2; // indentation
544
545 // Print header.
546 Indent(n0, Header(type_));
547 if (scope_name_->length() > 0) {
548 PrintF(" ");
549 PrintName(scope_name_);
550 }
551
552 // Print parameters, if any.
553 if (is_function_scope()) {
554 PrintF(" (");
555 for (int i = 0; i < params_.length(); i++) {
556 if (i > 0) PrintF(", ");
557 PrintName(params_[i]->name());
558 }
559 PrintF(")");
560 }
561
562 PrintF(" {\n");
563
564 // Function name, if any (named function literals, only).
565 if (function_ != NULL) {
566 Indent(n1, "// (local) function name: ");
567 PrintName(function_->name());
568 PrintF("\n");
569 }
570
571 // Scope info.
572 if (HasTrivialOuterContext()) {
573 Indent(n1, "// scope has trivial outer context\n");
574 }
575 if (scope_inside_with_) Indent(n1, "// scope inside 'with'\n");
576 if (scope_contains_with_) Indent(n1, "// scope contains 'with'\n");
577 if (scope_calls_eval_) Indent(n1, "// scope calls 'eval'\n");
578 if (outer_scope_calls_eval_) Indent(n1, "// outer scope calls 'eval'\n");
579 if (inner_scope_calls_eval_) Indent(n1, "// inner scope calls 'eval'\n");
580 if (outer_scope_is_eval_scope_) {
581 Indent(n1, "// outer scope is 'eval' scope\n");
582 }
583 if (num_stack_slots_ > 0) { Indent(n1, "// ");
584 PrintF("%d stack slots\n", num_stack_slots_); }
585 if (num_heap_slots_ > 0) { Indent(n1, "// ");
586 PrintF("%d heap slots\n", num_heap_slots_); }
587
588 // Print locals.
589 PrettyPrinter printer;
590 Indent(n1, "// function var\n");
591 if (function_ != NULL) {
592 PrintVar(&printer, n1, function_);
593 }
594
595 Indent(n1, "// temporary vars\n");
596 for (int i = 0; i < temps_.length(); i++) {
597 PrintVar(&printer, n1, temps_[i]);
598 }
599
600 Indent(n1, "// local vars\n");
601 PrintMap(&printer, n1, &variables_);
602
603 Indent(n1, "// dynamic vars\n");
604 if (dynamics_ != NULL) {
605 PrintMap(&printer, n1, dynamics_->GetMap(Variable::DYNAMIC));
606 PrintMap(&printer, n1, dynamics_->GetMap(Variable::DYNAMIC_LOCAL));
607 PrintMap(&printer, n1, dynamics_->GetMap(Variable::DYNAMIC_GLOBAL));
608 }
609
610 // Print inner scopes (disable by providing negative n).
611 if (n >= 0) {
612 for (int i = 0; i < inner_scopes_.length(); i++) {
613 PrintF("\n");
614 inner_scopes_[i]->Print(n1);
615 }
616 }
617
618 Indent(n0, "}\n");
619}
620#endif // DEBUG
621
622
623Variable* Scope::NonLocal(Handle<String> name, Variable::Mode mode) {
624 if (dynamics_ == NULL) dynamics_ = new DynamicScopePart();
625 VariableMap* map = dynamics_->GetMap(mode);
626 Variable* var = map->Lookup(name);
627 if (var == NULL) {
628 // Declare a new non-local.
629 var = map->Declare(NULL, name, mode, true, Variable::NORMAL);
630 // Allocate it by giving it a dynamic lookup.
Ben Murdochb8e0da22011-05-16 14:20:40 +0100631 var->set_rewrite(new Slot(var, Slot::LOOKUP, -1));
Steve Blocka7e24c12009-10-30 11:49:00 +0000632 }
633 return var;
634}
635
636
637// Lookup a variable starting with this scope. The result is either
Steve Blockd0582a62009-12-15 09:54:21 +0000638// the statically resolved variable belonging to an outer scope, or
639// NULL. It may be NULL because a) we couldn't find a variable, or b)
640// because the variable is just a guess (and may be shadowed by
641// another variable that is introduced dynamically via an 'eval' call
642// or a 'with' statement).
Steve Blocka7e24c12009-10-30 11:49:00 +0000643Variable* Scope::LookupRecursive(Handle<String> name,
644 bool inner_lookup,
645 Variable** invalidated_local) {
646 // If we find a variable, but the current scope calls 'eval', the found
647 // variable may not be the correct one (the 'eval' may introduce a
648 // property with the same name). In that case, remember that the variable
649 // found is just a guess.
650 bool guess = scope_calls_eval_;
651
652 // Try to find the variable in this scope.
653 Variable* var = LocalLookup(name);
654
655 if (var != NULL) {
656 // We found a variable. If this is not an inner lookup, we are done.
657 // (Even if there is an 'eval' in this scope which introduces the
658 // same variable again, the resulting variable remains the same.
659 // Note that enclosing 'with' statements are handled at the call site.)
660 if (!inner_lookup)
661 return var;
662
663 } else {
664 // We did not find a variable locally. Check against the function variable,
665 // if any. We can do this for all scopes, since the function variable is
666 // only present - if at all - for function scopes.
667 //
668 // This lookup corresponds to a lookup in the "intermediate" scope sitting
669 // between this scope and the outer scope. (ECMA-262, 3rd., requires that
670 // the name of named function literal is kept in an intermediate scope
671 // in between this scope and the next outer scope.)
672 if (function_ != NULL && function_->name().is_identical_to(name)) {
673 var = function_;
674
675 } else if (outer_scope_ != NULL) {
676 var = outer_scope_->LookupRecursive(name, true, invalidated_local);
677 // We may have found a variable in an outer scope. However, if
678 // the current scope is inside a 'with', the actual variable may
679 // be a property introduced via the 'with' statement. Then, the
680 // variable we may have found is just a guess.
681 if (scope_inside_with_)
682 guess = true;
683 }
684
685 // If we did not find a variable, we are done.
686 if (var == NULL)
687 return NULL;
688 }
689
690 ASSERT(var != NULL);
691
692 // If this is a lookup from an inner scope, mark the variable.
Ben Murdochb8e0da22011-05-16 14:20:40 +0100693 if (inner_lookup) {
694 var->MarkAsAccessedFromInnerScope();
695 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000696
Steve Blockd0582a62009-12-15 09:54:21 +0000697 // If the variable we have found is just a guess, invalidate the
698 // result. If the found variable is local, record that fact so we
699 // can generate fast code to get it if it is not shadowed by eval.
Steve Blocka7e24c12009-10-30 11:49:00 +0000700 if (guess) {
Steve Blockd0582a62009-12-15 09:54:21 +0000701 if (!var->is_global()) *invalidated_local = var;
Steve Blocka7e24c12009-10-30 11:49:00 +0000702 var = NULL;
703 }
704
705 return var;
706}
707
708
709void Scope::ResolveVariable(Scope* global_scope,
710 Handle<Context> context,
711 VariableProxy* proxy) {
712 ASSERT(global_scope == NULL || global_scope->is_global_scope());
713
714 // If the proxy is already resolved there's nothing to do
715 // (functions and consts may be resolved by the parser).
716 if (proxy->var() != NULL) return;
717
718 // Otherwise, try to resolve the variable.
719 Variable* invalidated_local = NULL;
720 Variable* var = LookupRecursive(proxy->name(), false, &invalidated_local);
721
722 if (proxy->inside_with()) {
723 // If we are inside a local 'with' statement, all bets are off
724 // and we cannot resolve the proxy to a local variable even if
725 // we found an outer matching variable.
726 // Note that we must do a lookup anyway, because if we find one,
727 // we must mark that variable as potentially accessed from this
728 // inner scope (the property may not be in the 'with' object).
729 var = NonLocal(proxy->name(), Variable::DYNAMIC);
730
731 } else {
732 // We are not inside a local 'with' statement.
733
734 if (var == NULL) {
735 // We did not find the variable. We have a global variable
736 // if we are in the global scope (we know already that we
737 // are outside a 'with' statement) or if there is no way
738 // that the variable might be introduced dynamically (through
739 // a local or outer eval() call, or an outer 'with' statement),
740 // or we don't know about the outer scope (because we are
741 // in an eval scope).
742 if (is_global_scope() ||
743 !(scope_inside_with_ || outer_scope_is_eval_scope_ ||
744 scope_calls_eval_ || outer_scope_calls_eval_)) {
745 // We must have a global variable.
746 ASSERT(global_scope != NULL);
747 var = global_scope->DeclareGlobal(proxy->name());
748
749 } else if (scope_inside_with_) {
750 // If we are inside a with statement we give up and look up
751 // the variable at runtime.
752 var = NonLocal(proxy->name(), Variable::DYNAMIC);
753
754 } else if (invalidated_local != NULL) {
755 // No with statements are involved and we found a local
756 // variable that might be shadowed by eval introduced
757 // variables.
758 var = NonLocal(proxy->name(), Variable::DYNAMIC_LOCAL);
759 var->set_local_if_not_shadowed(invalidated_local);
760
761 } else if (outer_scope_is_eval_scope_) {
762 // No with statements and we did not find a local and the code
763 // is executed with a call to eval. The context contains
764 // scope information that we can use to determine if the
765 // variable is global if it is not shadowed by eval-introduced
766 // variables.
767 if (context->GlobalIfNotShadowedByEval(proxy->name())) {
768 var = NonLocal(proxy->name(), Variable::DYNAMIC_GLOBAL);
769
770 } else {
771 var = NonLocal(proxy->name(), Variable::DYNAMIC);
772 }
773
774 } else {
775 // No with statements and we did not find a local and the code
776 // is not executed with a call to eval. We know that this
777 // variable is global unless it is shadowed by eval-introduced
778 // variables.
779 var = NonLocal(proxy->name(), Variable::DYNAMIC_GLOBAL);
780 }
781 }
782 }
783
784 proxy->BindTo(var);
785}
786
787
788void Scope::ResolveVariablesRecursively(Scope* global_scope,
789 Handle<Context> context) {
790 ASSERT(global_scope == NULL || global_scope->is_global_scope());
791
792 // Resolve unresolved variables for this scope.
793 for (int i = 0; i < unresolved_.length(); i++) {
794 ResolveVariable(global_scope, context, unresolved_[i]);
795 }
796
797 // Resolve unresolved variables for inner scopes.
798 for (int i = 0; i < inner_scopes_.length(); i++) {
799 inner_scopes_[i]->ResolveVariablesRecursively(global_scope, context);
800 }
801}
802
803
804bool Scope::PropagateScopeInfo(bool outer_scope_calls_eval,
805 bool outer_scope_is_eval_scope) {
806 if (outer_scope_calls_eval) {
807 outer_scope_calls_eval_ = true;
808 }
809
810 if (outer_scope_is_eval_scope) {
811 outer_scope_is_eval_scope_ = true;
812 }
813
814 bool calls_eval = scope_calls_eval_ || outer_scope_calls_eval_;
815 bool is_eval = is_eval_scope() || outer_scope_is_eval_scope_;
816 for (int i = 0; i < inner_scopes_.length(); i++) {
817 Scope* inner_scope = inner_scopes_[i];
818 if (inner_scope->PropagateScopeInfo(calls_eval, is_eval)) {
819 inner_scope_calls_eval_ = true;
820 }
821 if (inner_scope->force_eager_compilation_) {
822 force_eager_compilation_ = true;
823 }
824 }
825
826 return scope_calls_eval_ || inner_scope_calls_eval_;
827}
828
829
830bool Scope::MustAllocate(Variable* var) {
831 // Give var a read/write use if there is a chance it might be accessed
832 // via an eval() call. This is only possible if the variable has a
833 // visible name.
834 if ((var->is_this() || var->name()->length() > 0) &&
Ben Murdochb8e0da22011-05-16 14:20:40 +0100835 (var->is_accessed_from_inner_scope() ||
Steve Blocka7e24c12009-10-30 11:49:00 +0000836 scope_calls_eval_ || inner_scope_calls_eval_ ||
837 scope_contains_with_)) {
Steve Block6ded16b2010-05-10 14:33:55 +0100838 var->set_is_used(true);
Steve Blocka7e24c12009-10-30 11:49:00 +0000839 }
840 // Global variables do not need to be allocated.
Steve Block6ded16b2010-05-10 14:33:55 +0100841 return !var->is_global() && var->is_used();
Steve Blocka7e24c12009-10-30 11:49:00 +0000842}
843
844
845bool Scope::MustAllocateInContext(Variable* var) {
846 // If var is accessed from an inner scope, or if there is a
847 // possibility that it might be accessed from the current or an inner
848 // scope (through an eval() call), it must be allocated in the
849 // context. Exception: temporary variables are not allocated in the
850 // context.
851 return
852 var->mode() != Variable::TEMPORARY &&
Ben Murdochb8e0da22011-05-16 14:20:40 +0100853 (var->is_accessed_from_inner_scope() ||
Steve Blocka7e24c12009-10-30 11:49:00 +0000854 scope_calls_eval_ || inner_scope_calls_eval_ ||
855 scope_contains_with_ || var->is_global());
856}
857
858
859bool Scope::HasArgumentsParameter() {
860 for (int i = 0; i < params_.length(); i++) {
861 if (params_[i]->name().is_identical_to(Factory::arguments_symbol()))
862 return true;
863 }
864 return false;
865}
866
867
868void Scope::AllocateStackSlot(Variable* var) {
Ben Murdochb8e0da22011-05-16 14:20:40 +0100869 var->set_rewrite(new Slot(var, Slot::LOCAL, num_stack_slots_++));
Steve Blocka7e24c12009-10-30 11:49:00 +0000870}
871
872
873void Scope::AllocateHeapSlot(Variable* var) {
Ben Murdochb8e0da22011-05-16 14:20:40 +0100874 var->set_rewrite(new Slot(var, Slot::CONTEXT, num_heap_slots_++));
Steve Blocka7e24c12009-10-30 11:49:00 +0000875}
876
877
878void Scope::AllocateParameterLocals() {
879 ASSERT(is_function_scope());
880 Variable* arguments = LocalLookup(Factory::arguments_symbol());
881 ASSERT(arguments != NULL); // functions have 'arguments' declared implicitly
882 if (MustAllocate(arguments) && !HasArgumentsParameter()) {
883 // 'arguments' is used. Unless there is also a parameter called
884 // 'arguments', we must be conservative and access all parameters via
885 // the arguments object: The i'th parameter is rewritten into
886 // '.arguments[i]' (*). If we have a parameter named 'arguments', a
887 // (new) value is always assigned to it via the function
888 // invocation. Then 'arguments' denotes that specific parameter value
889 // and cannot be used to access the parameters, which is why we don't
890 // need to rewrite in that case.
891 //
892 // (*) Instead of having a parameter called 'arguments', we may have an
893 // assignment to 'arguments' in the function body, at some arbitrary
894 // point in time (possibly through an 'eval()' call!). After that
895 // assignment any re-write of parameters would be invalid (was bug
896 // 881452). Thus, we introduce a shadow '.arguments'
897 // variable which also points to the arguments object. For rewrites we
898 // use '.arguments' which remains valid even if we assign to
899 // 'arguments'. To summarize: If we need to rewrite, we allocate an
900 // 'arguments' object dynamically upon function invocation. The compiler
901 // introduces 2 local variables 'arguments' and '.arguments', both of
902 // which originally point to the arguments object that was
903 // allocated. All parameters are rewritten into property accesses via
904 // the '.arguments' variable. Thus, any changes to properties of
905 // 'arguments' are reflected in the variables and vice versa. If the
906 // 'arguments' variable is changed, '.arguments' still points to the
907 // correct arguments object and the rewrites still work.
908
909 // We are using 'arguments'. Tell the code generator that is needs to
910 // allocate the arguments object by setting 'arguments_'.
Kristian Monsen0d5e1162010-09-30 15:31:59 +0100911 arguments_ = arguments;
Steve Blocka7e24c12009-10-30 11:49:00 +0000912
913 // We also need the '.arguments' shadow variable. Declare it and create
914 // and bind the corresponding proxy. It's ok to declare it only now
915 // because it's a local variable that is allocated after the parameters
916 // have been allocated.
917 //
918 // Note: This is "almost" at temporary variable but we cannot use
919 // NewTemporary() because the mode needs to be INTERNAL since this
920 // variable may be allocated in the heap-allocated context (temporaries
921 // are never allocated in the context).
Kristian Monsen0d5e1162010-09-30 15:31:59 +0100922 arguments_shadow_ = new Variable(this,
923 Factory::arguments_shadow_symbol(),
924 Variable::INTERNAL,
925 true,
926 Variable::ARGUMENTS);
927 arguments_shadow_->set_is_used(true);
928 temps_.Add(arguments_shadow_);
Steve Blocka7e24c12009-10-30 11:49:00 +0000929
930 // Allocate the parameters by rewriting them into '.arguments[i]' accesses.
931 for (int i = 0; i < params_.length(); i++) {
932 Variable* var = params_[i];
933 ASSERT(var->scope() == this);
934 if (MustAllocate(var)) {
935 if (MustAllocateInContext(var)) {
936 // It is ok to set this only now, because arguments is a local
937 // variable that is allocated after the parameters have been
938 // allocated.
Ben Murdochb8e0da22011-05-16 14:20:40 +0100939 arguments_shadow_->MarkAsAccessedFromInnerScope();
Steve Blocka7e24c12009-10-30 11:49:00 +0000940 }
Ben Murdochb0fe1622011-05-05 13:52:32 +0100941 Property* rewrite =
Kristian Monsen0d5e1162010-09-30 15:31:59 +0100942 new Property(new VariableProxy(arguments_shadow_),
943 new Literal(Handle<Object>(Smi::FromInt(i))),
944 RelocInfo::kNoPosition,
945 Property::SYNTHETIC);
Ben Murdochb0fe1622011-05-05 13:52:32 +0100946 rewrite->set_is_arguments_access(true);
Ben Murdochb8e0da22011-05-16 14:20:40 +0100947 var->set_rewrite(rewrite);
Steve Blocka7e24c12009-10-30 11:49:00 +0000948 }
949 }
950
951 } else {
952 // The arguments object is not used, so we can access parameters directly.
953 // The same parameter may occur multiple times in the parameters_ list.
954 // If it does, and if it is not copied into the context object, it must
955 // receive the highest parameter index for that parameter; thus iteration
956 // order is relevant!
957 for (int i = 0; i < params_.length(); i++) {
958 Variable* var = params_[i];
959 ASSERT(var->scope() == this);
960 if (MustAllocate(var)) {
961 if (MustAllocateInContext(var)) {
Ben Murdochb8e0da22011-05-16 14:20:40 +0100962 ASSERT(var->rewrite() == NULL ||
Kristian Monsen0d5e1162010-09-30 15:31:59 +0100963 (var->AsSlot() != NULL &&
964 var->AsSlot()->type() == Slot::CONTEXT));
Ben Murdochb8e0da22011-05-16 14:20:40 +0100965 if (var->rewrite() == NULL) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000966 // Only set the heap allocation if the parameter has not
967 // been allocated yet.
968 AllocateHeapSlot(var);
969 }
970 } else {
Ben Murdochb8e0da22011-05-16 14:20:40 +0100971 ASSERT(var->rewrite() == NULL ||
Kristian Monsen0d5e1162010-09-30 15:31:59 +0100972 (var->AsSlot() != NULL &&
973 var->AsSlot()->type() == Slot::PARAMETER));
Steve Blocka7e24c12009-10-30 11:49:00 +0000974 // Set the parameter index always, even if the parameter
975 // was seen before! (We need to access the actual parameter
976 // supplied for the last occurrence of a multiply declared
977 // parameter.)
Ben Murdochb8e0da22011-05-16 14:20:40 +0100978 var->set_rewrite(new Slot(var, Slot::PARAMETER, i));
Steve Blocka7e24c12009-10-30 11:49:00 +0000979 }
980 }
981 }
982 }
983}
984
985
986void Scope::AllocateNonParameterLocal(Variable* var) {
987 ASSERT(var->scope() == this);
Ben Murdochb8e0da22011-05-16 14:20:40 +0100988 ASSERT(var->rewrite() == NULL ||
Steve Blocka7e24c12009-10-30 11:49:00 +0000989 (!var->IsVariable(Factory::result_symbol())) ||
Kristian Monsen0d5e1162010-09-30 15:31:59 +0100990 (var->AsSlot() == NULL || var->AsSlot()->type() != Slot::LOCAL));
Ben Murdochb8e0da22011-05-16 14:20:40 +0100991 if (var->rewrite() == NULL && MustAllocate(var)) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000992 if (MustAllocateInContext(var)) {
993 AllocateHeapSlot(var);
994 } else {
995 AllocateStackSlot(var);
996 }
997 }
998}
999
1000
1001void Scope::AllocateNonParameterLocals() {
1002 // All variables that have no rewrite yet are non-parameter locals.
1003 for (int i = 0; i < temps_.length(); i++) {
1004 AllocateNonParameterLocal(temps_[i]);
1005 }
1006
1007 for (VariableMap::Entry* p = variables_.Start();
1008 p != NULL;
1009 p = variables_.Next(p)) {
1010 Variable* var = reinterpret_cast<Variable*>(p->value);
1011 AllocateNonParameterLocal(var);
1012 }
1013
1014 // For now, function_ must be allocated at the very end. If it gets
1015 // allocated in the context, it must be the last slot in the context,
1016 // because of the current ScopeInfo implementation (see
1017 // ScopeInfo::ScopeInfo(FunctionScope* scope) constructor).
1018 if (function_ != NULL) {
1019 AllocateNonParameterLocal(function_);
1020 }
1021}
1022
1023
1024void Scope::AllocateVariablesRecursively() {
Steve Blocka7e24c12009-10-30 11:49:00 +00001025 // Allocate variables for inner scopes.
1026 for (int i = 0; i < inner_scopes_.length(); i++) {
1027 inner_scopes_[i]->AllocateVariablesRecursively();
1028 }
1029
Ben Murdochb8e0da22011-05-16 14:20:40 +01001030 // If scope is already resolved, we still need to allocate
1031 // variables in inner scopes which might not had been resolved yet.
1032 if (resolved()) return;
1033 // The number of slots required for variables.
1034 num_stack_slots_ = 0;
1035 num_heap_slots_ = Context::MIN_CONTEXT_SLOTS;
1036
Steve Blocka7e24c12009-10-30 11:49:00 +00001037 // Allocate variables for this scope.
1038 // Parameters must be allocated first, if any.
1039 if (is_function_scope()) AllocateParameterLocals();
1040 AllocateNonParameterLocals();
1041
1042 // Allocate context if necessary.
1043 bool must_have_local_context = false;
1044 if (scope_calls_eval_ || scope_contains_with_) {
1045 // The context for the eval() call or 'with' statement in this scope.
1046 // Unless we are in the global or an eval scope, we need a local
1047 // context even if we didn't statically allocate any locals in it,
1048 // and the compiler will access the context variable. If we are
1049 // not in an inner scope, the scope is provided from the outside.
1050 must_have_local_context = is_function_scope();
1051 }
1052
1053 // If we didn't allocate any locals in the local context, then we only
1054 // need the minimal number of slots if we must have a local context.
1055 if (num_heap_slots_ == Context::MIN_CONTEXT_SLOTS &&
1056 !must_have_local_context) {
1057 num_heap_slots_ = 0;
1058 }
1059
1060 // Allocation done.
1061 ASSERT(num_heap_slots_ == 0 || num_heap_slots_ >= Context::MIN_CONTEXT_SLOTS);
1062}
1063
1064} } // namespace v8::internal