blob: 3565e11b58f710e280f1080c0fb479e5e01376f9 [file] [log] [blame]
ager@chromium.orgb61a0d12010-10-13 08:35:23 +00001// Copyright 2010 the V8 project authors. All rights reserved.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +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
ager@chromium.orgb61a0d12010-10-13 08:35:23 +000030#include "scopes.h"
31
32#include "bootstrapper.h"
33#include "compiler.h"
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000034#include "prettyprinter.h"
35#include "scopeinfo.h"
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000036
kasperl@chromium.org71affb52009-05-26 05:44:31 +000037namespace v8 {
38namespace internal {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000039
40// ----------------------------------------------------------------------------
41// A Zone allocator for use with LocalsMap.
42
43class ZoneAllocator: public Allocator {
44 public:
45 /* nothing to do */
46 virtual ~ZoneAllocator() {}
47
ager@chromium.orgc4c92722009-11-18 14:12:51 +000048 virtual void* New(size_t size) { return Zone::New(static_cast<int>(size)); }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +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
kasperl@chromium.org68ac0092009-07-09 06:00:35 +000077VariableMap::VariableMap(bool gotta_love_static_overloading) : HashMap() {}
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000078
kasperl@chromium.org68ac0092009-07-09 06:00:35 +000079VariableMap::VariableMap() : HashMap(Match, &LocalsMapAllocator, 8) {}
80VariableMap::~VariableMap() {}
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000081
82
kasperl@chromium.org68ac0092009-07-09 06:00:35 +000083Variable* VariableMap::Declare(Scope* scope,
84 Handle<String> name,
85 Variable::Mode mode,
86 bool is_valid_lhs,
87 Variable::Kind kind) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000088 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());
kasperl@chromium.org68ac0092009-07-09 06:00:35 +000092 p->value = new Variable(scope, name, mode, is_valid_lhs, kind);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000093 }
94 return reinterpret_cast<Variable*>(p->value);
95}
96
97
kasperl@chromium.org68ac0092009-07-09 06:00:35 +000098Variable* VariableMap::Lookup(Handle<String> name) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000099 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
sgjesse@chromium.org911335c2009-08-19 12:59:44 +0000114Scope::Scope(Type type)
115 : outer_scope_(NULL),
116 inner_scopes_(0),
117 type_(type),
118 scope_name_(Factory::empty_symbol()),
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000119 variables_(false),
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000120 temps_(0),
121 params_(0),
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000122 dynamics_(NULL),
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000123 unresolved_(0),
sgjesse@chromium.org911335c2009-08-19 12:59:44 +0000124 decls_(0),
125 receiver_(NULL),
126 function_(NULL),
127 arguments_(NULL),
128 arguments_shadow_(NULL),
129 illegal_redecl_(NULL),
130 scope_inside_with_(false),
131 scope_contains_with_(false),
132 scope_calls_eval_(false),
133 outer_scope_calls_eval_(false),
134 inner_scope_calls_eval_(false),
135 outer_scope_is_eval_scope_(false),
136 force_eager_compilation_(false),
137 num_stack_slots_(0),
138 num_heap_slots_(0) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000139}
140
141
142Scope::Scope(Scope* outer_scope, Type type)
143 : outer_scope_(outer_scope),
144 inner_scopes_(4),
145 type_(type),
146 scope_name_(Factory::empty_symbol()),
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000147 temps_(4),
148 params_(4),
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000149 dynamics_(NULL),
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000150 unresolved_(16),
151 decls_(4),
152 receiver_(NULL),
153 function_(NULL),
154 arguments_(NULL),
155 arguments_shadow_(NULL),
156 illegal_redecl_(NULL),
157 scope_inside_with_(false),
158 scope_contains_with_(false),
159 scope_calls_eval_(false),
160 outer_scope_calls_eval_(false),
161 inner_scope_calls_eval_(false),
ager@chromium.org381abbb2009-02-25 13:23:22 +0000162 outer_scope_is_eval_scope_(false),
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000163 force_eager_compilation_(false),
164 num_stack_slots_(0),
165 num_heap_slots_(0) {
166 // At some point we might want to provide outer scopes to
167 // eval scopes (by walking the stack and reading the scope info).
168 // In that case, the ASSERT below needs to be adjusted.
169 ASSERT((type == GLOBAL_SCOPE || type == EVAL_SCOPE) == (outer_scope == NULL));
170 ASSERT(!HasIllegalRedeclaration());
171}
172
173
ager@chromium.orgb61a0d12010-10-13 08:35:23 +0000174bool Scope::Analyze(CompilationInfo* info) {
175 ASSERT(info->function() != NULL);
176 Scope* top = info->function()->scope();
177 while (top->outer_scope() != NULL) top = top->outer_scope();
178 top->AllocateVariables(info->calling_context());
179
180#ifdef DEBUG
181 if (Bootstrapper::IsActive()
182 ? FLAG_print_builtin_scopes
183 : FLAG_print_scopes) {
184 info->function()->scope()->Print();
185 }
186#endif
187
188 info->SetScope(info->function()->scope());
189 return true; // Can not fail.
190}
191
192
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000193void Scope::Initialize(bool inside_with) {
194 // Add this scope as a new inner scope of the outer scope.
195 if (outer_scope_ != NULL) {
196 outer_scope_->inner_scopes_.Add(this);
197 scope_inside_with_ = outer_scope_->scope_inside_with_ || inside_with;
198 } else {
199 scope_inside_with_ = inside_with;
200 }
201
202 // Declare convenience variables.
203 // Declare and allocate receiver (even for the global scope, and even
204 // if naccesses_ == 0).
205 // NOTE: When loading parameters in the global scope, we must take
206 // care not to access them as properties of the global object, but
207 // instead load them directly from the stack. Currently, the only
208 // such parameter is 'this' which is passed on the stack when
209 // invoking scripts
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000210 Variable* var =
211 variables_.Declare(this, Factory::this_symbol(), Variable::VAR,
212 false, Variable::THIS);
213 var->rewrite_ = new Slot(var, Slot::PARAMETER, -1);
kmillikin@chromium.org13bd2942009-12-16 15:36:05 +0000214 receiver_ = var;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000215
216 if (is_function_scope()) {
217 // Declare 'arguments' variable which exists in all functions.
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000218 // Note that it might never be accessed, in which case it won't be
219 // allocated during variable allocation.
220 variables_.Declare(this, Factory::arguments_symbol(), Variable::VAR,
221 true, Variable::ARGUMENTS);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000222 }
223}
224
225
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000226Variable* Scope::LocalLookup(Handle<String> name) {
227 return variables_.Lookup(name);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000228}
229
230
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000231Variable* Scope::Lookup(Handle<String> name) {
232 for (Scope* scope = this;
233 scope != NULL;
234 scope = scope->outer_scope()) {
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000235 Variable* var = scope->LocalLookup(name);
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000236 if (var != NULL) return var;
237 }
238 return NULL;
239}
240
241
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000242Variable* Scope::DeclareFunctionVar(Handle<String> name) {
243 ASSERT(is_function_scope() && function_ == NULL);
ager@chromium.org3e875802009-06-29 08:26:34 +0000244 function_ = new Variable(this, name, Variable::CONST, true, Variable::NORMAL);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000245 return function_;
246}
247
248
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000249Variable* Scope::DeclareLocal(Handle<String> name, Variable::Mode mode) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000250 // DYNAMIC variables are introduces during variable allocation,
251 // INTERNAL variables are allocated explicitly, and TEMPORARY
252 // variables are allocated via NewTemporary().
253 ASSERT(mode == Variable::VAR || mode == Variable::CONST);
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000254 return variables_.Declare(this, name, mode, true, Variable::NORMAL);
255}
256
257
258Variable* Scope::DeclareGlobal(Handle<String> name) {
259 ASSERT(is_global_scope());
fschneider@chromium.org0c20e672010-01-14 15:28:53 +0000260 return variables_.Declare(this, name, Variable::DYNAMIC_GLOBAL, true,
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000261 Variable::NORMAL);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000262}
263
264
265void Scope::AddParameter(Variable* var) {
266 ASSERT(is_function_scope());
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000267 ASSERT(LocalLookup(var->name()) == var);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000268 params_.Add(var);
269}
270
271
272VariableProxy* Scope::NewUnresolved(Handle<String> name, bool inside_with) {
273 // Note that we must not share the unresolved variables with
274 // the same name because they may be removed selectively via
275 // RemoveUnresolved().
276 VariableProxy* proxy = new VariableProxy(name, false, inside_with);
277 unresolved_.Add(proxy);
278 return proxy;
279}
280
281
282void Scope::RemoveUnresolved(VariableProxy* var) {
283 // Most likely (always?) any variable we want to remove
284 // was just added before, so we search backwards.
285 for (int i = unresolved_.length(); i-- > 0;) {
286 if (unresolved_[i] == var) {
287 unresolved_.Remove(i);
288 return;
289 }
290 }
291}
292
293
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000294Variable* Scope::NewTemporary(Handle<String> name) {
295 Variable* var =
296 new Variable(this, name, Variable::TEMPORARY, true, Variable::NORMAL);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000297 temps_.Add(var);
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000298 return var;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000299}
300
301
302void Scope::AddDeclaration(Declaration* declaration) {
303 decls_.Add(declaration);
304}
305
306
307void Scope::SetIllegalRedeclaration(Expression* expression) {
308 // Only set the illegal redeclaration expression the
309 // first time the function is called.
310 if (!HasIllegalRedeclaration()) {
311 illegal_redecl_ = expression;
312 }
313 ASSERT(HasIllegalRedeclaration());
314}
315
316
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000317void Scope::VisitIllegalRedeclaration(AstVisitor* visitor) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000318 ASSERT(HasIllegalRedeclaration());
319 illegal_redecl_->Accept(visitor);
320}
321
322
323template<class Allocator>
324void Scope::CollectUsedVariables(List<Variable*, Allocator>* locals) {
325 // Collect variables in this scope.
326 // Note that the function_ variable - if present - is not
327 // collected here but handled separately in ScopeInfo
328 // which is the current user of this function).
329 for (int i = 0; i < temps_.length(); i++) {
330 Variable* var = temps_[i];
ager@chromium.orgce5e87b2010-03-10 10:24:18 +0000331 if (var->is_used()) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000332 locals->Add(var);
333 }
334 }
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000335 for (VariableMap::Entry* p = variables_.Start();
336 p != NULL;
337 p = variables_.Next(p)) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000338 Variable* var = reinterpret_cast<Variable*>(p->value);
ager@chromium.orgce5e87b2010-03-10 10:24:18 +0000339 if (var->is_used()) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000340 locals->Add(var);
341 }
342 }
343}
344
345
346// Make sure the method gets instantiated by the template system.
347template void Scope::CollectUsedVariables(
348 List<Variable*, FreeStoreAllocationPolicy>* locals);
349template void Scope::CollectUsedVariables(
350 List<Variable*, PreallocatedStorage>* locals);
kasperl@chromium.org71affb52009-05-26 05:44:31 +0000351template void Scope::CollectUsedVariables(
352 List<Variable*, ZoneListAllocationPolicy>* locals);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000353
354
ager@chromium.org381abbb2009-02-25 13:23:22 +0000355void Scope::AllocateVariables(Handle<Context> context) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000356 ASSERT(outer_scope_ == NULL); // eval or global scopes only
357
358 // 1) Propagate scope information.
359 // If we are in an eval scope, we may have other outer scopes about
360 // which we don't know anything at this point. Thus we must be conservative
361 // and assume they may invoke eval themselves. Eventually we could capture
362 // this information in the ScopeInfo and then use it here (by traversing
363 // the call chain stack, at compile time).
ager@chromium.org381abbb2009-02-25 13:23:22 +0000364 bool eval_scope = is_eval_scope();
365 PropagateScopeInfo(eval_scope, eval_scope);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000366
367 // 2) Resolve variables.
368 Scope* global_scope = NULL;
369 if (is_global_scope()) global_scope = this;
ager@chromium.org381abbb2009-02-25 13:23:22 +0000370 ResolveVariablesRecursively(global_scope, context);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000371
372 // 3) Allocate variables.
373 AllocateVariablesRecursively();
374}
375
376
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000377bool Scope::AllowsLazyCompilation() const {
378 return !force_eager_compilation_ && HasTrivialOuterContext();
379}
380
381
382bool Scope::HasTrivialContext() const {
383 // A function scope has a trivial context if it always is the global
384 // context. We iteratively scan out the context chain to see if
385 // there is anything that makes this scope non-trivial; otherwise we
386 // return true.
387 for (const Scope* scope = this; scope != NULL; scope = scope->outer_scope_) {
388 if (scope->is_eval_scope()) return false;
389 if (scope->scope_inside_with_) return false;
390 if (scope->num_heap_slots_ > 0) return false;
391 }
392 return true;
393}
394
395
396bool Scope::HasTrivialOuterContext() const {
397 Scope* outer = outer_scope_;
398 if (outer == NULL) return true;
399 // Note that the outer context may be trivial in general, but the current
400 // scope may be inside a 'with' statement in which case the outer context
401 // for this scope is not trivial.
402 return !scope_inside_with_ && outer->HasTrivialContext();
403}
404
405
406int Scope::ContextChainLength(Scope* scope) {
407 int n = 0;
408 for (Scope* s = this; s != scope; s = s->outer_scope_) {
409 ASSERT(s != NULL); // scope must be in the scope chain
410 if (s->num_heap_slots() > 0) n++;
411 }
412 return n;
413}
414
415
416#ifdef DEBUG
417static const char* Header(Scope::Type type) {
418 switch (type) {
419 case Scope::EVAL_SCOPE: return "eval";
420 case Scope::FUNCTION_SCOPE: return "function";
421 case Scope::GLOBAL_SCOPE: return "global";
422 }
423 UNREACHABLE();
424 return NULL;
425}
426
427
428static void Indent(int n, const char* str) {
429 PrintF("%*s%s", n, "", str);
430}
431
432
433static void PrintName(Handle<String> name) {
434 SmartPointer<char> s = name->ToCString(DISALLOW_NULLS);
435 PrintF("%s", *s);
436}
437
438
439static void PrintVar(PrettyPrinter* printer, int indent, Variable* var) {
ager@chromium.orgce5e87b2010-03-10 10:24:18 +0000440 if (var->is_used() || var->rewrite() != NULL) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000441 Indent(indent, Variable::Mode2String(var->mode()));
442 PrintF(" ");
443 PrintName(var->name());
444 PrintF("; // ");
ager@chromium.orgce5e87b2010-03-10 10:24:18 +0000445 if (var->rewrite() != NULL) {
446 PrintF("%s, ", printer->Print(var->rewrite()));
447 if (var->is_accessed_from_inner_scope()) PrintF(", ");
448 }
449 if (var->is_accessed_from_inner_scope()) PrintF("inner scope access");
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000450 PrintF("\n");
451 }
452}
453
454
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000455static void PrintMap(PrettyPrinter* printer, int indent, VariableMap* map) {
456 for (VariableMap::Entry* p = map->Start(); p != NULL; p = map->Next(p)) {
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000457 Variable* var = reinterpret_cast<Variable*>(p->value);
458 PrintVar(printer, indent, var);
459 }
460}
461
462
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000463void Scope::Print(int n) {
464 int n0 = (n > 0 ? n : 0);
465 int n1 = n0 + 2; // indentation
466
467 // Print header.
468 Indent(n0, Header(type_));
469 if (scope_name_->length() > 0) {
470 PrintF(" ");
471 PrintName(scope_name_);
472 }
473
474 // Print parameters, if any.
475 if (is_function_scope()) {
476 PrintF(" (");
477 for (int i = 0; i < params_.length(); i++) {
478 if (i > 0) PrintF(", ");
479 PrintName(params_[i]->name());
480 }
481 PrintF(")");
482 }
483
484 PrintF(" {\n");
485
486 // Function name, if any (named function literals, only).
487 if (function_ != NULL) {
488 Indent(n1, "// (local) function name: ");
489 PrintName(function_->name());
490 PrintF("\n");
491 }
492
493 // Scope info.
494 if (HasTrivialOuterContext()) {
495 Indent(n1, "// scope has trivial outer context\n");
496 }
497 if (scope_inside_with_) Indent(n1, "// scope inside 'with'\n");
498 if (scope_contains_with_) Indent(n1, "// scope contains 'with'\n");
499 if (scope_calls_eval_) Indent(n1, "// scope calls 'eval'\n");
500 if (outer_scope_calls_eval_) Indent(n1, "// outer scope calls 'eval'\n");
501 if (inner_scope_calls_eval_) Indent(n1, "// inner scope calls 'eval'\n");
ager@chromium.org381abbb2009-02-25 13:23:22 +0000502 if (outer_scope_is_eval_scope_) {
503 Indent(n1, "// outer scope is 'eval' scope\n");
504 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000505 if (num_stack_slots_ > 0) { Indent(n1, "// ");
506 PrintF("%d stack slots\n", num_stack_slots_); }
507 if (num_heap_slots_ > 0) { Indent(n1, "// ");
508 PrintF("%d heap slots\n", num_heap_slots_); }
509
510 // Print locals.
511 PrettyPrinter printer;
512 Indent(n1, "// function var\n");
513 if (function_ != NULL) {
514 PrintVar(&printer, n1, function_);
515 }
516
517 Indent(n1, "// temporary vars\n");
518 for (int i = 0; i < temps_.length(); i++) {
519 PrintVar(&printer, n1, temps_[i]);
520 }
521
522 Indent(n1, "// local vars\n");
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000523 PrintMap(&printer, n1, &variables_);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000524
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000525 Indent(n1, "// dynamic vars\n");
526 if (dynamics_ != NULL) {
527 PrintMap(&printer, n1, dynamics_->GetMap(Variable::DYNAMIC));
528 PrintMap(&printer, n1, dynamics_->GetMap(Variable::DYNAMIC_LOCAL));
529 PrintMap(&printer, n1, dynamics_->GetMap(Variable::DYNAMIC_GLOBAL));
530 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000531
532 // Print inner scopes (disable by providing negative n).
533 if (n >= 0) {
534 for (int i = 0; i < inner_scopes_.length(); i++) {
535 PrintF("\n");
536 inner_scopes_[i]->Print(n1);
537 }
538 }
539
540 Indent(n0, "}\n");
541}
542#endif // DEBUG
543
544
ager@chromium.org381abbb2009-02-25 13:23:22 +0000545Variable* Scope::NonLocal(Handle<String> name, Variable::Mode mode) {
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000546 if (dynamics_ == NULL) dynamics_ = new DynamicScopePart();
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000547 VariableMap* map = dynamics_->GetMap(mode);
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000548 Variable* var = map->Lookup(name);
549 if (var == NULL) {
550 // Declare a new non-local.
ager@chromium.org3e875802009-06-29 08:26:34 +0000551 var = map->Declare(NULL, name, mode, true, Variable::NORMAL);
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000552 // Allocate it by giving it a dynamic lookup.
553 var->rewrite_ = new Slot(var, Slot::LOOKUP, -1);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000554 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000555 return var;
556}
557
558
559// Lookup a variable starting with this scope. The result is either
ager@chromium.orgfe22fc42009-11-05 11:55:54 +0000560// the statically resolved variable belonging to an outer scope, or
561// NULL. It may be NULL because a) we couldn't find a variable, or b)
562// because the variable is just a guess (and may be shadowed by
563// another variable that is introduced dynamically via an 'eval' call
564// or a 'with' statement).
ager@chromium.org381abbb2009-02-25 13:23:22 +0000565Variable* Scope::LookupRecursive(Handle<String> name,
566 bool inner_lookup,
567 Variable** invalidated_local) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000568 // If we find a variable, but the current scope calls 'eval', the found
569 // variable may not be the correct one (the 'eval' may introduce a
570 // property with the same name). In that case, remember that the variable
571 // found is just a guess.
572 bool guess = scope_calls_eval_;
573
574 // Try to find the variable in this scope.
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000575 Variable* var = LocalLookup(name);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000576
577 if (var != NULL) {
578 // We found a variable. If this is not an inner lookup, we are done.
579 // (Even if there is an 'eval' in this scope which introduces the
580 // same variable again, the resulting variable remains the same.
581 // Note that enclosing 'with' statements are handled at the call site.)
582 if (!inner_lookup)
583 return var;
584
585 } else {
586 // We did not find a variable locally. Check against the function variable,
587 // if any. We can do this for all scopes, since the function variable is
588 // only present - if at all - for function scopes.
589 //
590 // This lookup corresponds to a lookup in the "intermediate" scope sitting
591 // between this scope and the outer scope. (ECMA-262, 3rd., requires that
592 // the name of named function literal is kept in an intermediate scope
ager@chromium.org32912102009-01-16 10:38:43 +0000593 // in between this scope and the next outer scope.)
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000594 if (function_ != NULL && function_->name().is_identical_to(name)) {
595 var = function_;
596
597 } else if (outer_scope_ != NULL) {
ager@chromium.org381abbb2009-02-25 13:23:22 +0000598 var = outer_scope_->LookupRecursive(name, true, invalidated_local);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000599 // We may have found a variable in an outer scope. However, if
600 // the current scope is inside a 'with', the actual variable may
601 // be a property introduced via the 'with' statement. Then, the
602 // variable we may have found is just a guess.
603 if (scope_inside_with_)
604 guess = true;
605 }
606
607 // If we did not find a variable, we are done.
608 if (var == NULL)
609 return NULL;
610 }
611
612 ASSERT(var != NULL);
613
614 // If this is a lookup from an inner scope, mark the variable.
615 if (inner_lookup)
616 var->is_accessed_from_inner_scope_ = true;
617
ager@chromium.orgfe22fc42009-11-05 11:55:54 +0000618 // If the variable we have found is just a guess, invalidate the
619 // result. If the found variable is local, record that fact so we
620 // can generate fast code to get it if it is not shadowed by eval.
ager@chromium.org381abbb2009-02-25 13:23:22 +0000621 if (guess) {
ager@chromium.orgfe22fc42009-11-05 11:55:54 +0000622 if (!var->is_global()) *invalidated_local = var;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000623 var = NULL;
ager@chromium.org381abbb2009-02-25 13:23:22 +0000624 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000625
626 return var;
627}
628
629
ager@chromium.org381abbb2009-02-25 13:23:22 +0000630void Scope::ResolveVariable(Scope* global_scope,
631 Handle<Context> context,
632 VariableProxy* proxy) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000633 ASSERT(global_scope == NULL || global_scope->is_global_scope());
634
635 // If the proxy is already resolved there's nothing to do
636 // (functions and consts may be resolved by the parser).
637 if (proxy->var() != NULL) return;
638
639 // Otherwise, try to resolve the variable.
ager@chromium.org381abbb2009-02-25 13:23:22 +0000640 Variable* invalidated_local = NULL;
641 Variable* var = LookupRecursive(proxy->name(), false, &invalidated_local);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000642
643 if (proxy->inside_with()) {
644 // If we are inside a local 'with' statement, all bets are off
645 // and we cannot resolve the proxy to a local variable even if
646 // we found an outer matching variable.
647 // Note that we must do a lookup anyway, because if we find one,
648 // we must mark that variable as potentially accessed from this
649 // inner scope (the property may not be in the 'with' object).
ager@chromium.org381abbb2009-02-25 13:23:22 +0000650 var = NonLocal(proxy->name(), Variable::DYNAMIC);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000651
652 } else {
653 // We are not inside a local 'with' statement.
654
655 if (var == NULL) {
656 // We did not find the variable. We have a global variable
657 // if we are in the global scope (we know already that we
658 // are outside a 'with' statement) or if there is no way
659 // that the variable might be introduced dynamically (through
660 // a local or outer eval() call, or an outer 'with' statement),
661 // or we don't know about the outer scope (because we are
662 // in an eval scope).
ager@chromium.org381abbb2009-02-25 13:23:22 +0000663 if (is_global_scope() ||
664 !(scope_inside_with_ || outer_scope_is_eval_scope_ ||
665 scope_calls_eval_ || outer_scope_calls_eval_)) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000666 // We must have a global variable.
667 ASSERT(global_scope != NULL);
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000668 var = global_scope->DeclareGlobal(proxy->name());
ager@chromium.org381abbb2009-02-25 13:23:22 +0000669
670 } else if (scope_inside_with_) {
671 // If we are inside a with statement we give up and look up
672 // the variable at runtime.
673 var = NonLocal(proxy->name(), Variable::DYNAMIC);
674
675 } else if (invalidated_local != NULL) {
676 // No with statements are involved and we found a local
677 // variable that might be shadowed by eval introduced
678 // variables.
679 var = NonLocal(proxy->name(), Variable::DYNAMIC_LOCAL);
680 var->set_local_if_not_shadowed(invalidated_local);
681
682 } else if (outer_scope_is_eval_scope_) {
683 // No with statements and we did not find a local and the code
684 // is executed with a call to eval. The context contains
685 // scope information that we can use to determine if the
686 // variable is global if it is not shadowed by eval-introduced
687 // variables.
688 if (context->GlobalIfNotShadowedByEval(proxy->name())) {
689 var = NonLocal(proxy->name(), Variable::DYNAMIC_GLOBAL);
690
691 } else {
692 var = NonLocal(proxy->name(), Variable::DYNAMIC);
693 }
694
695 } else {
696 // No with statements and we did not find a local and the code
697 // is not executed with a call to eval. We know that this
698 // variable is global unless it is shadowed by eval-introduced
699 // variables.
700 var = NonLocal(proxy->name(), Variable::DYNAMIC_GLOBAL);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000701 }
702 }
703 }
704
705 proxy->BindTo(var);
706}
707
708
ager@chromium.org381abbb2009-02-25 13:23:22 +0000709void Scope::ResolveVariablesRecursively(Scope* global_scope,
710 Handle<Context> context) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000711 ASSERT(global_scope == NULL || global_scope->is_global_scope());
712
713 // Resolve unresolved variables for this scope.
714 for (int i = 0; i < unresolved_.length(); i++) {
ager@chromium.org381abbb2009-02-25 13:23:22 +0000715 ResolveVariable(global_scope, context, unresolved_[i]);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000716 }
717
718 // Resolve unresolved variables for inner scopes.
719 for (int i = 0; i < inner_scopes_.length(); i++) {
ager@chromium.org381abbb2009-02-25 13:23:22 +0000720 inner_scopes_[i]->ResolveVariablesRecursively(global_scope, context);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000721 }
722}
723
724
ager@chromium.org381abbb2009-02-25 13:23:22 +0000725bool Scope::PropagateScopeInfo(bool outer_scope_calls_eval,
726 bool outer_scope_is_eval_scope) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000727 if (outer_scope_calls_eval) {
728 outer_scope_calls_eval_ = true;
729 }
730
ager@chromium.org381abbb2009-02-25 13:23:22 +0000731 if (outer_scope_is_eval_scope) {
732 outer_scope_is_eval_scope_ = true;
733 }
734
735 bool calls_eval = scope_calls_eval_ || outer_scope_calls_eval_;
736 bool is_eval = is_eval_scope() || outer_scope_is_eval_scope_;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000737 for (int i = 0; i < inner_scopes_.length(); i++) {
738 Scope* inner_scope = inner_scopes_[i];
ager@chromium.org381abbb2009-02-25 13:23:22 +0000739 if (inner_scope->PropagateScopeInfo(calls_eval, is_eval)) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000740 inner_scope_calls_eval_ = true;
741 }
742 if (inner_scope->force_eager_compilation_) {
743 force_eager_compilation_ = true;
744 }
745 }
746
747 return scope_calls_eval_ || inner_scope_calls_eval_;
748}
749
750
751bool Scope::MustAllocate(Variable* var) {
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000752 // Give var a read/write use if there is a chance it might be accessed
753 // via an eval() call. This is only possible if the variable has a
754 // visible name.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000755 if ((var->is_this() || var->name()->length() > 0) &&
756 (var->is_accessed_from_inner_scope_ ||
757 scope_calls_eval_ || inner_scope_calls_eval_ ||
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000758 scope_contains_with_)) {
ager@chromium.orgce5e87b2010-03-10 10:24:18 +0000759 var->set_is_used(true);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000760 }
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000761 // Global variables do not need to be allocated.
ager@chromium.orgce5e87b2010-03-10 10:24:18 +0000762 return !var->is_global() && var->is_used();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000763}
764
765
766bool Scope::MustAllocateInContext(Variable* var) {
767 // If var is accessed from an inner scope, or if there is a
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000768 // possibility that it might be accessed from the current or an inner
769 // scope (through an eval() call), it must be allocated in the
770 // context. Exception: temporary variables are not allocated in the
771 // context.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000772 return
773 var->mode() != Variable::TEMPORARY &&
774 (var->is_accessed_from_inner_scope_ ||
775 scope_calls_eval_ || inner_scope_calls_eval_ ||
776 scope_contains_with_ || var->is_global());
777}
778
779
780bool Scope::HasArgumentsParameter() {
781 for (int i = 0; i < params_.length(); i++) {
782 if (params_[i]->name().is_identical_to(Factory::arguments_symbol()))
783 return true;
784 }
785 return false;
786}
787
788
789void Scope::AllocateStackSlot(Variable* var) {
790 var->rewrite_ = new Slot(var, Slot::LOCAL, num_stack_slots_++);
791}
792
793
794void Scope::AllocateHeapSlot(Variable* var) {
795 var->rewrite_ = new Slot(var, Slot::CONTEXT, num_heap_slots_++);
796}
797
798
799void Scope::AllocateParameterLocals() {
800 ASSERT(is_function_scope());
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000801 Variable* arguments = LocalLookup(Factory::arguments_symbol());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000802 ASSERT(arguments != NULL); // functions have 'arguments' declared implicitly
803 if (MustAllocate(arguments) && !HasArgumentsParameter()) {
804 // 'arguments' is used. Unless there is also a parameter called
805 // 'arguments', we must be conservative and access all parameters via
806 // the arguments object: The i'th parameter is rewritten into
807 // '.arguments[i]' (*). If we have a parameter named 'arguments', a
808 // (new) value is always assigned to it via the function
809 // invocation. Then 'arguments' denotes that specific parameter value
810 // and cannot be used to access the parameters, which is why we don't
811 // need to rewrite in that case.
812 //
813 // (*) Instead of having a parameter called 'arguments', we may have an
814 // assignment to 'arguments' in the function body, at some arbitrary
815 // point in time (possibly through an 'eval()' call!). After that
816 // assignment any re-write of parameters would be invalid (was bug
817 // 881452). Thus, we introduce a shadow '.arguments'
818 // variable which also points to the arguments object. For rewrites we
819 // use '.arguments' which remains valid even if we assign to
820 // 'arguments'. To summarize: If we need to rewrite, we allocate an
821 // 'arguments' object dynamically upon function invocation. The compiler
822 // introduces 2 local variables 'arguments' and '.arguments', both of
823 // which originally point to the arguments object that was
824 // allocated. All parameters are rewritten into property accesses via
825 // the '.arguments' variable. Thus, any changes to properties of
826 // 'arguments' are reflected in the variables and vice versa. If the
827 // 'arguments' variable is changed, '.arguments' still points to the
828 // correct arguments object and the rewrites still work.
829
830 // We are using 'arguments'. Tell the code generator that is needs to
831 // allocate the arguments object by setting 'arguments_'.
whesse@chromium.org4a1fe7d2010-09-27 12:32:04 +0000832 arguments_ = arguments;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000833
834 // We also need the '.arguments' shadow variable. Declare it and create
835 // and bind the corresponding proxy. It's ok to declare it only now
836 // because it's a local variable that is allocated after the parameters
837 // have been allocated.
838 //
839 // Note: This is "almost" at temporary variable but we cannot use
840 // NewTemporary() because the mode needs to be INTERNAL since this
841 // variable may be allocated in the heap-allocated context (temporaries
842 // are never allocated in the context).
whesse@chromium.org4a1fe7d2010-09-27 12:32:04 +0000843 arguments_shadow_ = new Variable(this,
844 Factory::arguments_shadow_symbol(),
845 Variable::INTERNAL,
846 true,
847 Variable::ARGUMENTS);
848 arguments_shadow_->set_is_used(true);
849 temps_.Add(arguments_shadow_);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000850
851 // Allocate the parameters by rewriting them into '.arguments[i]' accesses.
852 for (int i = 0; i < params_.length(); i++) {
853 Variable* var = params_[i];
854 ASSERT(var->scope() == this);
855 if (MustAllocate(var)) {
856 if (MustAllocateInContext(var)) {
857 // It is ok to set this only now, because arguments is a local
858 // variable that is allocated after the parameters have been
859 // allocated.
whesse@chromium.org4a1fe7d2010-09-27 12:32:04 +0000860 arguments_shadow_->is_accessed_from_inner_scope_ = true;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000861 }
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000862 Property* rewrite =
whesse@chromium.org4a1fe7d2010-09-27 12:32:04 +0000863 new Property(new VariableProxy(arguments_shadow_),
864 new Literal(Handle<Object>(Smi::FromInt(i))),
865 RelocInfo::kNoPosition,
866 Property::SYNTHETIC);
kasperl@chromium.orga5551262010-12-07 12:49:48 +0000867 rewrite->set_is_arguments_access(true);
868 var->rewrite_ = rewrite;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000869 }
870 }
871
872 } else {
873 // The arguments object is not used, so we can access parameters directly.
874 // The same parameter may occur multiple times in the parameters_ list.
875 // If it does, and if it is not copied into the context object, it must
876 // receive the highest parameter index for that parameter; thus iteration
877 // order is relevant!
878 for (int i = 0; i < params_.length(); i++) {
879 Variable* var = params_[i];
880 ASSERT(var->scope() == this);
881 if (MustAllocate(var)) {
882 if (MustAllocateInContext(var)) {
883 ASSERT(var->rewrite_ == NULL ||
whesse@chromium.org4a1fe7d2010-09-27 12:32:04 +0000884 (var->AsSlot() != NULL &&
885 var->AsSlot()->type() == Slot::CONTEXT));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000886 if (var->rewrite_ == NULL) {
887 // Only set the heap allocation if the parameter has not
888 // been allocated yet.
889 AllocateHeapSlot(var);
890 }
891 } else {
892 ASSERT(var->rewrite_ == NULL ||
whesse@chromium.org4a1fe7d2010-09-27 12:32:04 +0000893 (var->AsSlot() != NULL &&
894 var->AsSlot()->type() == Slot::PARAMETER));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000895 // Set the parameter index always, even if the parameter
896 // was seen before! (We need to access the actual parameter
897 // supplied for the last occurrence of a multiply declared
898 // parameter.)
899 var->rewrite_ = new Slot(var, Slot::PARAMETER, i);
900 }
901 }
902 }
903 }
904}
905
906
907void Scope::AllocateNonParameterLocal(Variable* var) {
908 ASSERT(var->scope() == this);
909 ASSERT(var->rewrite_ == NULL ||
910 (!var->IsVariable(Factory::result_symbol())) ||
whesse@chromium.org4a1fe7d2010-09-27 12:32:04 +0000911 (var->AsSlot() == NULL || var->AsSlot()->type() != Slot::LOCAL));
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000912 if (var->rewrite_ == NULL && MustAllocate(var)) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000913 if (MustAllocateInContext(var)) {
914 AllocateHeapSlot(var);
915 } else {
916 AllocateStackSlot(var);
917 }
918 }
919}
920
921
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000922void Scope::AllocateNonParameterLocals() {
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000923 // All variables that have no rewrite yet are non-parameter locals.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000924 for (int i = 0; i < temps_.length(); i++) {
925 AllocateNonParameterLocal(temps_[i]);
926 }
927
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000928 for (VariableMap::Entry* p = variables_.Start();
929 p != NULL;
930 p = variables_.Next(p)) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000931 Variable* var = reinterpret_cast<Variable*>(p->value);
932 AllocateNonParameterLocal(var);
933 }
934
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000935 // For now, function_ must be allocated at the very end. If it gets
936 // allocated in the context, it must be the last slot in the context,
937 // because of the current ScopeInfo implementation (see
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000938 // ScopeInfo::ScopeInfo(FunctionScope* scope) constructor).
939 if (function_ != NULL) {
940 AllocateNonParameterLocal(function_);
941 }
942}
943
944
945void Scope::AllocateVariablesRecursively() {
946 // The number of slots required for variables.
947 num_stack_slots_ = 0;
948 num_heap_slots_ = Context::MIN_CONTEXT_SLOTS;
949
950 // Allocate variables for inner scopes.
951 for (int i = 0; i < inner_scopes_.length(); i++) {
952 inner_scopes_[i]->AllocateVariablesRecursively();
953 }
954
955 // Allocate variables for this scope.
956 // Parameters must be allocated first, if any.
957 if (is_function_scope()) AllocateParameterLocals();
958 AllocateNonParameterLocals();
959
960 // Allocate context if necessary.
961 bool must_have_local_context = false;
962 if (scope_calls_eval_ || scope_contains_with_) {
963 // The context for the eval() call or 'with' statement in this scope.
964 // Unless we are in the global or an eval scope, we need a local
965 // context even if we didn't statically allocate any locals in it,
966 // and the compiler will access the context variable. If we are
967 // not in an inner scope, the scope is provided from the outside.
968 must_have_local_context = is_function_scope();
969 }
970
971 // If we didn't allocate any locals in the local context, then we only
972 // need the minimal number of slots if we must have a local context.
973 if (num_heap_slots_ == Context::MIN_CONTEXT_SLOTS &&
974 !must_have_local_context) {
975 num_heap_slots_ = 0;
976 }
977
978 // Allocation done.
979 ASSERT(num_heap_slots_ == 0 || num_heap_slots_ >= Context::MIN_CONTEXT_SLOTS);
980}
981
982} } // namespace v8::internal