blob: 5ff250ff2e959c7386c8089caed4539c8bb2abe1 [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
294VariableProxy* Scope::NewTemporary(Handle<String> name) {
ager@chromium.org3e875802009-06-29 08:26:34 +0000295 Variable* var = new Variable(this, name, Variable::TEMPORARY, true,
296 Variable::NORMAL);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000297 VariableProxy* tmp = new VariableProxy(name, false, false);
298 tmp->BindTo(var);
299 temps_.Add(var);
300 return tmp;
301}
302
303
304void Scope::AddDeclaration(Declaration* declaration) {
305 decls_.Add(declaration);
306}
307
308
309void Scope::SetIllegalRedeclaration(Expression* expression) {
310 // Only set the illegal redeclaration expression the
311 // first time the function is called.
312 if (!HasIllegalRedeclaration()) {
313 illegal_redecl_ = expression;
314 }
315 ASSERT(HasIllegalRedeclaration());
316}
317
318
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000319void Scope::VisitIllegalRedeclaration(AstVisitor* visitor) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000320 ASSERT(HasIllegalRedeclaration());
321 illegal_redecl_->Accept(visitor);
322}
323
324
325template<class Allocator>
326void Scope::CollectUsedVariables(List<Variable*, Allocator>* locals) {
327 // Collect variables in this scope.
328 // Note that the function_ variable - if present - is not
329 // collected here but handled separately in ScopeInfo
330 // which is the current user of this function).
331 for (int i = 0; i < temps_.length(); i++) {
332 Variable* var = temps_[i];
ager@chromium.orgce5e87b2010-03-10 10:24:18 +0000333 if (var->is_used()) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000334 locals->Add(var);
335 }
336 }
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000337 for (VariableMap::Entry* p = variables_.Start();
338 p != NULL;
339 p = variables_.Next(p)) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000340 Variable* var = reinterpret_cast<Variable*>(p->value);
ager@chromium.orgce5e87b2010-03-10 10:24:18 +0000341 if (var->is_used()) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000342 locals->Add(var);
343 }
344 }
345}
346
347
348// Make sure the method gets instantiated by the template system.
349template void Scope::CollectUsedVariables(
350 List<Variable*, FreeStoreAllocationPolicy>* locals);
351template void Scope::CollectUsedVariables(
352 List<Variable*, PreallocatedStorage>* locals);
kasperl@chromium.org71affb52009-05-26 05:44:31 +0000353template void Scope::CollectUsedVariables(
354 List<Variable*, ZoneListAllocationPolicy>* locals);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000355
356
ager@chromium.org381abbb2009-02-25 13:23:22 +0000357void Scope::AllocateVariables(Handle<Context> context) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000358 ASSERT(outer_scope_ == NULL); // eval or global scopes only
359
360 // 1) Propagate scope information.
361 // If we are in an eval scope, we may have other outer scopes about
362 // which we don't know anything at this point. Thus we must be conservative
363 // and assume they may invoke eval themselves. Eventually we could capture
364 // this information in the ScopeInfo and then use it here (by traversing
365 // the call chain stack, at compile time).
ager@chromium.org381abbb2009-02-25 13:23:22 +0000366 bool eval_scope = is_eval_scope();
367 PropagateScopeInfo(eval_scope, eval_scope);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000368
369 // 2) Resolve variables.
370 Scope* global_scope = NULL;
371 if (is_global_scope()) global_scope = this;
ager@chromium.org381abbb2009-02-25 13:23:22 +0000372 ResolveVariablesRecursively(global_scope, context);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000373
374 // 3) Allocate variables.
375 AllocateVariablesRecursively();
376}
377
378
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000379bool Scope::AllowsLazyCompilation() const {
380 return !force_eager_compilation_ && HasTrivialOuterContext();
381}
382
383
384bool Scope::HasTrivialContext() const {
385 // A function scope has a trivial context if it always is the global
386 // context. We iteratively scan out the context chain to see if
387 // there is anything that makes this scope non-trivial; otherwise we
388 // return true.
389 for (const Scope* scope = this; scope != NULL; scope = scope->outer_scope_) {
390 if (scope->is_eval_scope()) return false;
391 if (scope->scope_inside_with_) return false;
392 if (scope->num_heap_slots_ > 0) return false;
393 }
394 return true;
395}
396
397
398bool Scope::HasTrivialOuterContext() const {
399 Scope* outer = outer_scope_;
400 if (outer == NULL) return true;
401 // Note that the outer context may be trivial in general, but the current
402 // scope may be inside a 'with' statement in which case the outer context
403 // for this scope is not trivial.
404 return !scope_inside_with_ && outer->HasTrivialContext();
405}
406
407
408int Scope::ContextChainLength(Scope* scope) {
409 int n = 0;
410 for (Scope* s = this; s != scope; s = s->outer_scope_) {
411 ASSERT(s != NULL); // scope must be in the scope chain
412 if (s->num_heap_slots() > 0) n++;
413 }
414 return n;
415}
416
417
418#ifdef DEBUG
419static const char* Header(Scope::Type type) {
420 switch (type) {
421 case Scope::EVAL_SCOPE: return "eval";
422 case Scope::FUNCTION_SCOPE: return "function";
423 case Scope::GLOBAL_SCOPE: return "global";
424 }
425 UNREACHABLE();
426 return NULL;
427}
428
429
430static void Indent(int n, const char* str) {
431 PrintF("%*s%s", n, "", str);
432}
433
434
435static void PrintName(Handle<String> name) {
436 SmartPointer<char> s = name->ToCString(DISALLOW_NULLS);
437 PrintF("%s", *s);
438}
439
440
441static void PrintVar(PrettyPrinter* printer, int indent, Variable* var) {
ager@chromium.orgce5e87b2010-03-10 10:24:18 +0000442 if (var->is_used() || var->rewrite() != NULL) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000443 Indent(indent, Variable::Mode2String(var->mode()));
444 PrintF(" ");
445 PrintName(var->name());
446 PrintF("; // ");
ager@chromium.orgce5e87b2010-03-10 10:24:18 +0000447 if (var->rewrite() != NULL) {
448 PrintF("%s, ", printer->Print(var->rewrite()));
449 if (var->is_accessed_from_inner_scope()) PrintF(", ");
450 }
451 if (var->is_accessed_from_inner_scope()) PrintF("inner scope access");
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000452 PrintF("\n");
453 }
454}
455
456
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000457static void PrintMap(PrettyPrinter* printer, int indent, VariableMap* map) {
458 for (VariableMap::Entry* p = map->Start(); p != NULL; p = map->Next(p)) {
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000459 Variable* var = reinterpret_cast<Variable*>(p->value);
460 PrintVar(printer, indent, var);
461 }
462}
463
464
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000465void Scope::Print(int n) {
466 int n0 = (n > 0 ? n : 0);
467 int n1 = n0 + 2; // indentation
468
469 // Print header.
470 Indent(n0, Header(type_));
471 if (scope_name_->length() > 0) {
472 PrintF(" ");
473 PrintName(scope_name_);
474 }
475
476 // Print parameters, if any.
477 if (is_function_scope()) {
478 PrintF(" (");
479 for (int i = 0; i < params_.length(); i++) {
480 if (i > 0) PrintF(", ");
481 PrintName(params_[i]->name());
482 }
483 PrintF(")");
484 }
485
486 PrintF(" {\n");
487
488 // Function name, if any (named function literals, only).
489 if (function_ != NULL) {
490 Indent(n1, "// (local) function name: ");
491 PrintName(function_->name());
492 PrintF("\n");
493 }
494
495 // Scope info.
496 if (HasTrivialOuterContext()) {
497 Indent(n1, "// scope has trivial outer context\n");
498 }
499 if (scope_inside_with_) Indent(n1, "// scope inside 'with'\n");
500 if (scope_contains_with_) Indent(n1, "// scope contains 'with'\n");
501 if (scope_calls_eval_) Indent(n1, "// scope calls 'eval'\n");
502 if (outer_scope_calls_eval_) Indent(n1, "// outer scope calls 'eval'\n");
503 if (inner_scope_calls_eval_) Indent(n1, "// inner scope calls 'eval'\n");
ager@chromium.org381abbb2009-02-25 13:23:22 +0000504 if (outer_scope_is_eval_scope_) {
505 Indent(n1, "// outer scope is 'eval' scope\n");
506 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000507 if (num_stack_slots_ > 0) { Indent(n1, "// ");
508 PrintF("%d stack slots\n", num_stack_slots_); }
509 if (num_heap_slots_ > 0) { Indent(n1, "// ");
510 PrintF("%d heap slots\n", num_heap_slots_); }
511
512 // Print locals.
513 PrettyPrinter printer;
514 Indent(n1, "// function var\n");
515 if (function_ != NULL) {
516 PrintVar(&printer, n1, function_);
517 }
518
519 Indent(n1, "// temporary vars\n");
520 for (int i = 0; i < temps_.length(); i++) {
521 PrintVar(&printer, n1, temps_[i]);
522 }
523
524 Indent(n1, "// local vars\n");
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000525 PrintMap(&printer, n1, &variables_);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000526
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000527 Indent(n1, "// dynamic vars\n");
528 if (dynamics_ != NULL) {
529 PrintMap(&printer, n1, dynamics_->GetMap(Variable::DYNAMIC));
530 PrintMap(&printer, n1, dynamics_->GetMap(Variable::DYNAMIC_LOCAL));
531 PrintMap(&printer, n1, dynamics_->GetMap(Variable::DYNAMIC_GLOBAL));
532 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000533
534 // Print inner scopes (disable by providing negative n).
535 if (n >= 0) {
536 for (int i = 0; i < inner_scopes_.length(); i++) {
537 PrintF("\n");
538 inner_scopes_[i]->Print(n1);
539 }
540 }
541
542 Indent(n0, "}\n");
543}
544#endif // DEBUG
545
546
ager@chromium.org381abbb2009-02-25 13:23:22 +0000547Variable* Scope::NonLocal(Handle<String> name, Variable::Mode mode) {
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000548 if (dynamics_ == NULL) dynamics_ = new DynamicScopePart();
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000549 VariableMap* map = dynamics_->GetMap(mode);
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000550 Variable* var = map->Lookup(name);
551 if (var == NULL) {
552 // Declare a new non-local.
ager@chromium.org3e875802009-06-29 08:26:34 +0000553 var = map->Declare(NULL, name, mode, true, Variable::NORMAL);
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000554 // Allocate it by giving it a dynamic lookup.
555 var->rewrite_ = new Slot(var, Slot::LOOKUP, -1);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000556 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000557 return var;
558}
559
560
561// Lookup a variable starting with this scope. The result is either
ager@chromium.orgfe22fc42009-11-05 11:55:54 +0000562// the statically resolved variable belonging to an outer scope, or
563// NULL. It may be NULL because a) we couldn't find a variable, or b)
564// because the variable is just a guess (and may be shadowed by
565// another variable that is introduced dynamically via an 'eval' call
566// or a 'with' statement).
ager@chromium.org381abbb2009-02-25 13:23:22 +0000567Variable* Scope::LookupRecursive(Handle<String> name,
568 bool inner_lookup,
569 Variable** invalidated_local) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000570 // If we find a variable, but the current scope calls 'eval', the found
571 // variable may not be the correct one (the 'eval' may introduce a
572 // property with the same name). In that case, remember that the variable
573 // found is just a guess.
574 bool guess = scope_calls_eval_;
575
576 // Try to find the variable in this scope.
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000577 Variable* var = LocalLookup(name);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000578
579 if (var != NULL) {
580 // We found a variable. If this is not an inner lookup, we are done.
581 // (Even if there is an 'eval' in this scope which introduces the
582 // same variable again, the resulting variable remains the same.
583 // Note that enclosing 'with' statements are handled at the call site.)
584 if (!inner_lookup)
585 return var;
586
587 } else {
588 // We did not find a variable locally. Check against the function variable,
589 // if any. We can do this for all scopes, since the function variable is
590 // only present - if at all - for function scopes.
591 //
592 // This lookup corresponds to a lookup in the "intermediate" scope sitting
593 // between this scope and the outer scope. (ECMA-262, 3rd., requires that
594 // the name of named function literal is kept in an intermediate scope
ager@chromium.org32912102009-01-16 10:38:43 +0000595 // in between this scope and the next outer scope.)
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000596 if (function_ != NULL && function_->name().is_identical_to(name)) {
597 var = function_;
598
599 } else if (outer_scope_ != NULL) {
ager@chromium.org381abbb2009-02-25 13:23:22 +0000600 var = outer_scope_->LookupRecursive(name, true, invalidated_local);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000601 // We may have found a variable in an outer scope. However, if
602 // the current scope is inside a 'with', the actual variable may
603 // be a property introduced via the 'with' statement. Then, the
604 // variable we may have found is just a guess.
605 if (scope_inside_with_)
606 guess = true;
607 }
608
609 // If we did not find a variable, we are done.
610 if (var == NULL)
611 return NULL;
612 }
613
614 ASSERT(var != NULL);
615
616 // If this is a lookup from an inner scope, mark the variable.
617 if (inner_lookup)
618 var->is_accessed_from_inner_scope_ = true;
619
ager@chromium.orgfe22fc42009-11-05 11:55:54 +0000620 // If the variable we have found is just a guess, invalidate the
621 // result. If the found variable is local, record that fact so we
622 // can generate fast code to get it if it is not shadowed by eval.
ager@chromium.org381abbb2009-02-25 13:23:22 +0000623 if (guess) {
ager@chromium.orgfe22fc42009-11-05 11:55:54 +0000624 if (!var->is_global()) *invalidated_local = var;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000625 var = NULL;
ager@chromium.org381abbb2009-02-25 13:23:22 +0000626 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000627
628 return var;
629}
630
631
ager@chromium.org381abbb2009-02-25 13:23:22 +0000632void Scope::ResolveVariable(Scope* global_scope,
633 Handle<Context> context,
634 VariableProxy* proxy) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000635 ASSERT(global_scope == NULL || global_scope->is_global_scope());
636
637 // If the proxy is already resolved there's nothing to do
638 // (functions and consts may be resolved by the parser).
639 if (proxy->var() != NULL) return;
640
641 // Otherwise, try to resolve the variable.
ager@chromium.org381abbb2009-02-25 13:23:22 +0000642 Variable* invalidated_local = NULL;
643 Variable* var = LookupRecursive(proxy->name(), false, &invalidated_local);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000644
645 if (proxy->inside_with()) {
646 // If we are inside a local 'with' statement, all bets are off
647 // and we cannot resolve the proxy to a local variable even if
648 // we found an outer matching variable.
649 // Note that we must do a lookup anyway, because if we find one,
650 // we must mark that variable as potentially accessed from this
651 // inner scope (the property may not be in the 'with' object).
ager@chromium.org381abbb2009-02-25 13:23:22 +0000652 var = NonLocal(proxy->name(), Variable::DYNAMIC);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000653
654 } else {
655 // We are not inside a local 'with' statement.
656
657 if (var == NULL) {
658 // We did not find the variable. We have a global variable
659 // if we are in the global scope (we know already that we
660 // are outside a 'with' statement) or if there is no way
661 // that the variable might be introduced dynamically (through
662 // a local or outer eval() call, or an outer 'with' statement),
663 // or we don't know about the outer scope (because we are
664 // in an eval scope).
ager@chromium.org381abbb2009-02-25 13:23:22 +0000665 if (is_global_scope() ||
666 !(scope_inside_with_ || outer_scope_is_eval_scope_ ||
667 scope_calls_eval_ || outer_scope_calls_eval_)) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000668 // We must have a global variable.
669 ASSERT(global_scope != NULL);
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000670 var = global_scope->DeclareGlobal(proxy->name());
ager@chromium.org381abbb2009-02-25 13:23:22 +0000671
672 } else if (scope_inside_with_) {
673 // If we are inside a with statement we give up and look up
674 // the variable at runtime.
675 var = NonLocal(proxy->name(), Variable::DYNAMIC);
676
677 } else if (invalidated_local != NULL) {
678 // No with statements are involved and we found a local
679 // variable that might be shadowed by eval introduced
680 // variables.
681 var = NonLocal(proxy->name(), Variable::DYNAMIC_LOCAL);
682 var->set_local_if_not_shadowed(invalidated_local);
683
684 } else if (outer_scope_is_eval_scope_) {
685 // No with statements and we did not find a local and the code
686 // is executed with a call to eval. The context contains
687 // scope information that we can use to determine if the
688 // variable is global if it is not shadowed by eval-introduced
689 // variables.
690 if (context->GlobalIfNotShadowedByEval(proxy->name())) {
691 var = NonLocal(proxy->name(), Variable::DYNAMIC_GLOBAL);
692
693 } else {
694 var = NonLocal(proxy->name(), Variable::DYNAMIC);
695 }
696
697 } else {
698 // No with statements and we did not find a local and the code
699 // is not executed with a call to eval. We know that this
700 // variable is global unless it is shadowed by eval-introduced
701 // variables.
702 var = NonLocal(proxy->name(), Variable::DYNAMIC_GLOBAL);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000703 }
704 }
705 }
706
707 proxy->BindTo(var);
708}
709
710
ager@chromium.org381abbb2009-02-25 13:23:22 +0000711void Scope::ResolveVariablesRecursively(Scope* global_scope,
712 Handle<Context> context) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000713 ASSERT(global_scope == NULL || global_scope->is_global_scope());
714
715 // Resolve unresolved variables for this scope.
716 for (int i = 0; i < unresolved_.length(); i++) {
ager@chromium.org381abbb2009-02-25 13:23:22 +0000717 ResolveVariable(global_scope, context, unresolved_[i]);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000718 }
719
720 // Resolve unresolved variables for inner scopes.
721 for (int i = 0; i < inner_scopes_.length(); i++) {
ager@chromium.org381abbb2009-02-25 13:23:22 +0000722 inner_scopes_[i]->ResolveVariablesRecursively(global_scope, context);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000723 }
724}
725
726
ager@chromium.org381abbb2009-02-25 13:23:22 +0000727bool Scope::PropagateScopeInfo(bool outer_scope_calls_eval,
728 bool outer_scope_is_eval_scope) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000729 if (outer_scope_calls_eval) {
730 outer_scope_calls_eval_ = true;
731 }
732
ager@chromium.org381abbb2009-02-25 13:23:22 +0000733 if (outer_scope_is_eval_scope) {
734 outer_scope_is_eval_scope_ = true;
735 }
736
737 bool calls_eval = scope_calls_eval_ || outer_scope_calls_eval_;
738 bool is_eval = is_eval_scope() || outer_scope_is_eval_scope_;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000739 for (int i = 0; i < inner_scopes_.length(); i++) {
740 Scope* inner_scope = inner_scopes_[i];
ager@chromium.org381abbb2009-02-25 13:23:22 +0000741 if (inner_scope->PropagateScopeInfo(calls_eval, is_eval)) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000742 inner_scope_calls_eval_ = true;
743 }
744 if (inner_scope->force_eager_compilation_) {
745 force_eager_compilation_ = true;
746 }
747 }
748
749 return scope_calls_eval_ || inner_scope_calls_eval_;
750}
751
752
753bool Scope::MustAllocate(Variable* var) {
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000754 // Give var a read/write use if there is a chance it might be accessed
755 // via an eval() call. This is only possible if the variable has a
756 // visible name.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000757 if ((var->is_this() || var->name()->length() > 0) &&
758 (var->is_accessed_from_inner_scope_ ||
759 scope_calls_eval_ || inner_scope_calls_eval_ ||
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000760 scope_contains_with_)) {
ager@chromium.orgce5e87b2010-03-10 10:24:18 +0000761 var->set_is_used(true);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000762 }
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000763 // Global variables do not need to be allocated.
ager@chromium.orgce5e87b2010-03-10 10:24:18 +0000764 return !var->is_global() && var->is_used();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000765}
766
767
768bool Scope::MustAllocateInContext(Variable* var) {
769 // If var is accessed from an inner scope, or if there is a
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000770 // possibility that it might be accessed from the current or an inner
771 // scope (through an eval() call), it must be allocated in the
772 // context. Exception: temporary variables are not allocated in the
773 // context.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000774 return
775 var->mode() != Variable::TEMPORARY &&
776 (var->is_accessed_from_inner_scope_ ||
777 scope_calls_eval_ || inner_scope_calls_eval_ ||
778 scope_contains_with_ || var->is_global());
779}
780
781
782bool Scope::HasArgumentsParameter() {
783 for (int i = 0; i < params_.length(); i++) {
784 if (params_[i]->name().is_identical_to(Factory::arguments_symbol()))
785 return true;
786 }
787 return false;
788}
789
790
791void Scope::AllocateStackSlot(Variable* var) {
792 var->rewrite_ = new Slot(var, Slot::LOCAL, num_stack_slots_++);
793}
794
795
796void Scope::AllocateHeapSlot(Variable* var) {
797 var->rewrite_ = new Slot(var, Slot::CONTEXT, num_heap_slots_++);
798}
799
800
801void Scope::AllocateParameterLocals() {
802 ASSERT(is_function_scope());
kasperl@chromium.org68ac0092009-07-09 06:00:35 +0000803 Variable* arguments = LocalLookup(Factory::arguments_symbol());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000804 ASSERT(arguments != NULL); // functions have 'arguments' declared implicitly
805 if (MustAllocate(arguments) && !HasArgumentsParameter()) {
806 // 'arguments' is used. Unless there is also a parameter called
807 // 'arguments', we must be conservative and access all parameters via
808 // the arguments object: The i'th parameter is rewritten into
809 // '.arguments[i]' (*). If we have a parameter named 'arguments', a
810 // (new) value is always assigned to it via the function
811 // invocation. Then 'arguments' denotes that specific parameter value
812 // and cannot be used to access the parameters, which is why we don't
813 // need to rewrite in that case.
814 //
815 // (*) Instead of having a parameter called 'arguments', we may have an
816 // assignment to 'arguments' in the function body, at some arbitrary
817 // point in time (possibly through an 'eval()' call!). After that
818 // assignment any re-write of parameters would be invalid (was bug
819 // 881452). Thus, we introduce a shadow '.arguments'
820 // variable which also points to the arguments object. For rewrites we
821 // use '.arguments' which remains valid even if we assign to
822 // 'arguments'. To summarize: If we need to rewrite, we allocate an
823 // 'arguments' object dynamically upon function invocation. The compiler
824 // introduces 2 local variables 'arguments' and '.arguments', both of
825 // which originally point to the arguments object that was
826 // allocated. All parameters are rewritten into property accesses via
827 // the '.arguments' variable. Thus, any changes to properties of
828 // 'arguments' are reflected in the variables and vice versa. If the
829 // 'arguments' variable is changed, '.arguments' still points to the
830 // correct arguments object and the rewrites still work.
831
832 // We are using 'arguments'. Tell the code generator that is needs to
833 // allocate the arguments object by setting 'arguments_'.
whesse@chromium.org4a1fe7d2010-09-27 12:32:04 +0000834 arguments_ = arguments;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000835
836 // We also need the '.arguments' shadow variable. Declare it and create
837 // and bind the corresponding proxy. It's ok to declare it only now
838 // because it's a local variable that is allocated after the parameters
839 // have been allocated.
840 //
841 // Note: This is "almost" at temporary variable but we cannot use
842 // NewTemporary() because the mode needs to be INTERNAL since this
843 // variable may be allocated in the heap-allocated context (temporaries
844 // are never allocated in the context).
whesse@chromium.org4a1fe7d2010-09-27 12:32:04 +0000845 arguments_shadow_ = new Variable(this,
846 Factory::arguments_shadow_symbol(),
847 Variable::INTERNAL,
848 true,
849 Variable::ARGUMENTS);
850 arguments_shadow_->set_is_used(true);
851 temps_.Add(arguments_shadow_);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000852
853 // Allocate the parameters by rewriting them into '.arguments[i]' accesses.
854 for (int i = 0; i < params_.length(); i++) {
855 Variable* var = params_[i];
856 ASSERT(var->scope() == this);
857 if (MustAllocate(var)) {
858 if (MustAllocateInContext(var)) {
859 // It is ok to set this only now, because arguments is a local
860 // variable that is allocated after the parameters have been
861 // allocated.
whesse@chromium.org4a1fe7d2010-09-27 12:32:04 +0000862 arguments_shadow_->is_accessed_from_inner_scope_ = true;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000863 }
864 var->rewrite_ =
whesse@chromium.org4a1fe7d2010-09-27 12:32:04 +0000865 new Property(new VariableProxy(arguments_shadow_),
866 new Literal(Handle<Object>(Smi::FromInt(i))),
867 RelocInfo::kNoPosition,
868 Property::SYNTHETIC);
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