blob: 7717eaaf78991cfbf41d88e002161216f7ab0358 [file] [log] [blame]
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001// Copyright 2006-2008 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
30#include "prettyprinter.h"
31#include "scopeinfo.h"
32#include "scopes.h"
33
34namespace v8 { namespace internal {
35
36// ----------------------------------------------------------------------------
37// A Zone allocator for use with LocalsMap.
38
39class ZoneAllocator: public Allocator {
40 public:
41 /* nothing to do */
42 virtual ~ZoneAllocator() {}
43
44 virtual void* New(size_t size) { return Zone::New(size); }
45
46 /* ignored - Zone is freed in one fell swoop */
47 virtual void Delete(void* p) {}
48};
49
50
51static ZoneAllocator LocalsMapAllocator;
52
53
54// ----------------------------------------------------------------------------
55// Implementation of LocalsMap
56//
57// Note: We are storing the handle locations as key values in the hash map.
58// When inserting a new variable via Declare(), we rely on the fact that
59// the handle location remains alive for the duration of that variable
60// use. Because a Variable holding a handle with the same location exists
61// this is ensured.
62
63static bool Match(void* key1, void* key2) {
64 String* name1 = *reinterpret_cast<String**>(key1);
65 String* name2 = *reinterpret_cast<String**>(key2);
66 ASSERT(name1->IsSymbol());
67 ASSERT(name2->IsSymbol());
68 return name1 == name2;
69}
70
71
72// Dummy constructor
73LocalsMap::LocalsMap(bool gotta_love_static_overloading) : HashMap() {}
74
75LocalsMap::LocalsMap() : HashMap(Match, &LocalsMapAllocator, 8) {}
76LocalsMap::~LocalsMap() {}
77
78
79Variable* LocalsMap::Declare(Scope* scope,
80 Handle<String> name,
81 Variable::Mode mode,
82 bool is_valid_LHS,
83 bool is_this) {
84 HashMap::Entry* p = HashMap::Lookup(name.location(), name->Hash(), true);
85 if (p->value == NULL) {
86 // The variable has not been declared yet -> insert it.
87 ASSERT(p->key == name.location());
88 p->value = new Variable(scope, name, mode, is_valid_LHS, is_this);
89 }
90 return reinterpret_cast<Variable*>(p->value);
91}
92
93
94Variable* LocalsMap::Lookup(Handle<String> name) {
95 HashMap::Entry* p = HashMap::Lookup(name.location(), name->Hash(), false);
96 if (p != NULL) {
97 ASSERT(*reinterpret_cast<String**>(p->key) == *name);
98 ASSERT(p->value != NULL);
99 return reinterpret_cast<Variable*>(p->value);
100 }
101 return NULL;
102}
103
104
105// ----------------------------------------------------------------------------
106// Implementation of Scope
107
108
109// Dummy constructor
110Scope::Scope()
111 : inner_scopes_(0),
112 locals_(false),
113 temps_(0),
114 params_(0),
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000115 dynamics_(NULL),
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000116 unresolved_(0),
117 decls_(0) {
118}
119
120
121Scope::Scope(Scope* outer_scope, Type type)
122 : outer_scope_(outer_scope),
123 inner_scopes_(4),
124 type_(type),
125 scope_name_(Factory::empty_symbol()),
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000126 temps_(4),
127 params_(4),
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000128 dynamics_(NULL),
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000129 unresolved_(16),
130 decls_(4),
131 receiver_(NULL),
132 function_(NULL),
133 arguments_(NULL),
134 arguments_shadow_(NULL),
135 illegal_redecl_(NULL),
136 scope_inside_with_(false),
137 scope_contains_with_(false),
138 scope_calls_eval_(false),
139 outer_scope_calls_eval_(false),
140 inner_scope_calls_eval_(false),
ager@chromium.org381abbb2009-02-25 13:23:22 +0000141 outer_scope_is_eval_scope_(false),
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000142 force_eager_compilation_(false),
143 num_stack_slots_(0),
144 num_heap_slots_(0) {
145 // At some point we might want to provide outer scopes to
146 // eval scopes (by walking the stack and reading the scope info).
147 // In that case, the ASSERT below needs to be adjusted.
148 ASSERT((type == GLOBAL_SCOPE || type == EVAL_SCOPE) == (outer_scope == NULL));
149 ASSERT(!HasIllegalRedeclaration());
150}
151
152
153void Scope::Initialize(bool inside_with) {
154 // Add this scope as a new inner scope of the outer scope.
155 if (outer_scope_ != NULL) {
156 outer_scope_->inner_scopes_.Add(this);
157 scope_inside_with_ = outer_scope_->scope_inside_with_ || inside_with;
158 } else {
159 scope_inside_with_ = inside_with;
160 }
161
162 // Declare convenience variables.
163 // Declare and allocate receiver (even for the global scope, and even
164 // if naccesses_ == 0).
165 // NOTE: When loading parameters in the global scope, we must take
166 // care not to access them as properties of the global object, but
167 // instead load them directly from the stack. Currently, the only
168 // such parameter is 'this' which is passed on the stack when
169 // invoking scripts
170 { Variable* var =
171 locals_.Declare(this, Factory::this_symbol(), Variable::VAR, false, true);
172 var->rewrite_ = new Slot(var, Slot::PARAMETER, -1);
173 receiver_ = new VariableProxy(Factory::this_symbol(), true, false);
174 receiver_->BindTo(var);
175 }
176
177 if (is_function_scope()) {
178 // Declare 'arguments' variable which exists in all functions.
179 // Note that it may never be accessed, in which case it won't
180 // be allocated during variable allocation.
181 Declare(Factory::arguments_symbol(), Variable::VAR);
182 }
183}
184
185
186
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000187Variable* Scope::LookupLocal(Handle<String> name) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000188 return locals_.Lookup(name);
189}
190
191
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000192Variable* Scope::Lookup(Handle<String> name) {
193 for (Scope* scope = this;
194 scope != NULL;
195 scope = scope->outer_scope()) {
196 Variable* var = scope->LookupLocal(name);
197 if (var != NULL) return var;
198 }
199 return NULL;
200}
201
202
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000203Variable* Scope::DeclareFunctionVar(Handle<String> name) {
204 ASSERT(is_function_scope() && function_ == NULL);
205 function_ = new Variable(this, name, Variable::CONST, true, false);
206 return function_;
207}
208
209
210Variable* Scope::Declare(Handle<String> name, Variable::Mode mode) {
211 // DYNAMIC variables are introduces during variable allocation,
212 // INTERNAL variables are allocated explicitly, and TEMPORARY
213 // variables are allocated via NewTemporary().
214 ASSERT(mode == Variable::VAR || mode == Variable::CONST);
215 return locals_.Declare(this, name, mode, true, false);
216}
217
218
219void Scope::AddParameter(Variable* var) {
220 ASSERT(is_function_scope());
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000221 ASSERT(LookupLocal(var->name()) == var);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000222 params_.Add(var);
223}
224
225
226VariableProxy* Scope::NewUnresolved(Handle<String> name, bool inside_with) {
227 // Note that we must not share the unresolved variables with
228 // the same name because they may be removed selectively via
229 // RemoveUnresolved().
230 VariableProxy* proxy = new VariableProxy(name, false, inside_with);
231 unresolved_.Add(proxy);
232 return proxy;
233}
234
235
236void Scope::RemoveUnresolved(VariableProxy* var) {
237 // Most likely (always?) any variable we want to remove
238 // was just added before, so we search backwards.
239 for (int i = unresolved_.length(); i-- > 0;) {
240 if (unresolved_[i] == var) {
241 unresolved_.Remove(i);
242 return;
243 }
244 }
245}
246
247
248VariableProxy* Scope::NewTemporary(Handle<String> name) {
249 Variable* var = new Variable(this, name, Variable::TEMPORARY, true, false);
250 VariableProxy* tmp = new VariableProxy(name, false, false);
251 tmp->BindTo(var);
252 temps_.Add(var);
253 return tmp;
254}
255
256
257void Scope::AddDeclaration(Declaration* declaration) {
258 decls_.Add(declaration);
259}
260
261
262void Scope::SetIllegalRedeclaration(Expression* expression) {
263 // Only set the illegal redeclaration expression the
264 // first time the function is called.
265 if (!HasIllegalRedeclaration()) {
266 illegal_redecl_ = expression;
267 }
268 ASSERT(HasIllegalRedeclaration());
269}
270
271
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000272void Scope::VisitIllegalRedeclaration(AstVisitor* visitor) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000273 ASSERT(HasIllegalRedeclaration());
274 illegal_redecl_->Accept(visitor);
275}
276
277
278template<class Allocator>
279void Scope::CollectUsedVariables(List<Variable*, Allocator>* locals) {
280 // Collect variables in this scope.
281 // Note that the function_ variable - if present - is not
282 // collected here but handled separately in ScopeInfo
283 // which is the current user of this function).
284 for (int i = 0; i < temps_.length(); i++) {
285 Variable* var = temps_[i];
286 if (var->var_uses()->is_used()) {
287 locals->Add(var);
288 }
289 }
290 for (LocalsMap::Entry* p = locals_.Start(); p != NULL; p = locals_.Next(p)) {
291 Variable* var = reinterpret_cast<Variable*>(p->value);
292 if (var->var_uses()->is_used()) {
293 locals->Add(var);
294 }
295 }
296}
297
298
299// Make sure the method gets instantiated by the template system.
300template void Scope::CollectUsedVariables(
301 List<Variable*, FreeStoreAllocationPolicy>* locals);
302template void Scope::CollectUsedVariables(
303 List<Variable*, PreallocatedStorage>* locals);
304
305
ager@chromium.org381abbb2009-02-25 13:23:22 +0000306void Scope::AllocateVariables(Handle<Context> context) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000307 ASSERT(outer_scope_ == NULL); // eval or global scopes only
308
309 // 1) Propagate scope information.
310 // If we are in an eval scope, we may have other outer scopes about
311 // which we don't know anything at this point. Thus we must be conservative
312 // and assume they may invoke eval themselves. Eventually we could capture
313 // this information in the ScopeInfo and then use it here (by traversing
314 // the call chain stack, at compile time).
ager@chromium.org381abbb2009-02-25 13:23:22 +0000315 bool eval_scope = is_eval_scope();
316 PropagateScopeInfo(eval_scope, eval_scope);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000317
318 // 2) Resolve variables.
319 Scope* global_scope = NULL;
320 if (is_global_scope()) global_scope = this;
ager@chromium.org381abbb2009-02-25 13:23:22 +0000321 ResolveVariablesRecursively(global_scope, context);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000322
323 // 3) Allocate variables.
324 AllocateVariablesRecursively();
325}
326
327
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000328bool Scope::AllowsLazyCompilation() const {
329 return !force_eager_compilation_ && HasTrivialOuterContext();
330}
331
332
333bool Scope::HasTrivialContext() const {
334 // A function scope has a trivial context if it always is the global
335 // context. We iteratively scan out the context chain to see if
336 // there is anything that makes this scope non-trivial; otherwise we
337 // return true.
338 for (const Scope* scope = this; scope != NULL; scope = scope->outer_scope_) {
339 if (scope->is_eval_scope()) return false;
340 if (scope->scope_inside_with_) return false;
341 if (scope->num_heap_slots_ > 0) return false;
342 }
343 return true;
344}
345
346
347bool Scope::HasTrivialOuterContext() const {
348 Scope* outer = outer_scope_;
349 if (outer == NULL) return true;
350 // Note that the outer context may be trivial in general, but the current
351 // scope may be inside a 'with' statement in which case the outer context
352 // for this scope is not trivial.
353 return !scope_inside_with_ && outer->HasTrivialContext();
354}
355
356
357int Scope::ContextChainLength(Scope* scope) {
358 int n = 0;
359 for (Scope* s = this; s != scope; s = s->outer_scope_) {
360 ASSERT(s != NULL); // scope must be in the scope chain
361 if (s->num_heap_slots() > 0) n++;
362 }
363 return n;
364}
365
366
367#ifdef DEBUG
368static const char* Header(Scope::Type type) {
369 switch (type) {
370 case Scope::EVAL_SCOPE: return "eval";
371 case Scope::FUNCTION_SCOPE: return "function";
372 case Scope::GLOBAL_SCOPE: return "global";
373 }
374 UNREACHABLE();
375 return NULL;
376}
377
378
379static void Indent(int n, const char* str) {
380 PrintF("%*s%s", n, "", str);
381}
382
383
384static void PrintName(Handle<String> name) {
385 SmartPointer<char> s = name->ToCString(DISALLOW_NULLS);
386 PrintF("%s", *s);
387}
388
389
390static void PrintVar(PrettyPrinter* printer, int indent, Variable* var) {
391 if (var->var_uses()->is_used() || var->rewrite() != NULL) {
392 Indent(indent, Variable::Mode2String(var->mode()));
393 PrintF(" ");
394 PrintName(var->name());
395 PrintF("; // ");
396 if (var->rewrite() != NULL) PrintF("%s, ", printer->Print(var->rewrite()));
397 if (var->is_accessed_from_inner_scope()) PrintF("inner scope access, ");
398 PrintF("var ");
399 var->var_uses()->Print();
400 PrintF(", obj ");
401 var->obj_uses()->Print();
402 PrintF("\n");
403 }
404}
405
406
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000407static void PrintMap(PrettyPrinter* printer, int indent, LocalsMap* map) {
408 for (LocalsMap::Entry* p = map->Start(); p != NULL; p = map->Next(p)) {
409 Variable* var = reinterpret_cast<Variable*>(p->value);
410 PrintVar(printer, indent, var);
411 }
412}
413
414
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000415void Scope::Print(int n) {
416 int n0 = (n > 0 ? n : 0);
417 int n1 = n0 + 2; // indentation
418
419 // Print header.
420 Indent(n0, Header(type_));
421 if (scope_name_->length() > 0) {
422 PrintF(" ");
423 PrintName(scope_name_);
424 }
425
426 // Print parameters, if any.
427 if (is_function_scope()) {
428 PrintF(" (");
429 for (int i = 0; i < params_.length(); i++) {
430 if (i > 0) PrintF(", ");
431 PrintName(params_[i]->name());
432 }
433 PrintF(")");
434 }
435
436 PrintF(" {\n");
437
438 // Function name, if any (named function literals, only).
439 if (function_ != NULL) {
440 Indent(n1, "// (local) function name: ");
441 PrintName(function_->name());
442 PrintF("\n");
443 }
444
445 // Scope info.
446 if (HasTrivialOuterContext()) {
447 Indent(n1, "// scope has trivial outer context\n");
448 }
449 if (scope_inside_with_) Indent(n1, "// scope inside 'with'\n");
450 if (scope_contains_with_) Indent(n1, "// scope contains 'with'\n");
451 if (scope_calls_eval_) Indent(n1, "// scope calls 'eval'\n");
452 if (outer_scope_calls_eval_) Indent(n1, "// outer scope calls 'eval'\n");
453 if (inner_scope_calls_eval_) Indent(n1, "// inner scope calls 'eval'\n");
ager@chromium.org381abbb2009-02-25 13:23:22 +0000454 if (outer_scope_is_eval_scope_) {
455 Indent(n1, "// outer scope is 'eval' scope\n");
456 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000457 if (num_stack_slots_ > 0) { Indent(n1, "// ");
458 PrintF("%d stack slots\n", num_stack_slots_); }
459 if (num_heap_slots_ > 0) { Indent(n1, "// ");
460 PrintF("%d heap slots\n", num_heap_slots_); }
461
462 // Print locals.
463 PrettyPrinter printer;
464 Indent(n1, "// function var\n");
465 if (function_ != NULL) {
466 PrintVar(&printer, n1, function_);
467 }
468
469 Indent(n1, "// temporary vars\n");
470 for (int i = 0; i < temps_.length(); i++) {
471 PrintVar(&printer, n1, temps_[i]);
472 }
473
474 Indent(n1, "// local vars\n");
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000475 PrintMap(&printer, n1, &locals_);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000476
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000477 Indent(n1, "// dynamic vars\n");
478 if (dynamics_ != NULL) {
479 PrintMap(&printer, n1, dynamics_->GetMap(Variable::DYNAMIC));
480 PrintMap(&printer, n1, dynamics_->GetMap(Variable::DYNAMIC_LOCAL));
481 PrintMap(&printer, n1, dynamics_->GetMap(Variable::DYNAMIC_GLOBAL));
482 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000483
484 // Print inner scopes (disable by providing negative n).
485 if (n >= 0) {
486 for (int i = 0; i < inner_scopes_.length(); i++) {
487 PrintF("\n");
488 inner_scopes_[i]->Print(n1);
489 }
490 }
491
492 Indent(n0, "}\n");
493}
494#endif // DEBUG
495
496
ager@chromium.org381abbb2009-02-25 13:23:22 +0000497Variable* Scope::NonLocal(Handle<String> name, Variable::Mode mode) {
kasperl@chromium.orgb3284ad2009-05-18 06:12:45 +0000498 if (dynamics_ == NULL) dynamics_ = new DynamicScopePart();
499 LocalsMap* map = dynamics_->GetMap(mode);
500 Variable* var = map->Lookup(name);
501 if (var == NULL) {
502 // Declare a new non-local.
503 var = map->Declare(NULL, name, mode, true, false);
504 // Allocate it by giving it a dynamic lookup.
505 var->rewrite_ = new Slot(var, Slot::LOOKUP, -1);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000506 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000507 return var;
508}
509
510
511// Lookup a variable starting with this scope. The result is either
512// the statically resolved (local!) variable belonging to an outer scope,
513// or NULL. It may be NULL because a) we couldn't find a variable, or b)
514// because the variable is just a guess (and may be shadowed by another
515// variable that is introduced dynamically via an 'eval' call or a 'with'
516// statement).
ager@chromium.org381abbb2009-02-25 13:23:22 +0000517Variable* Scope::LookupRecursive(Handle<String> name,
518 bool inner_lookup,
519 Variable** invalidated_local) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000520 // If we find a variable, but the current scope calls 'eval', the found
521 // variable may not be the correct one (the 'eval' may introduce a
522 // property with the same name). In that case, remember that the variable
523 // found is just a guess.
524 bool guess = scope_calls_eval_;
525
526 // Try to find the variable in this scope.
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000527 Variable* var = LookupLocal(name);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000528
529 if (var != NULL) {
530 // We found a variable. If this is not an inner lookup, we are done.
531 // (Even if there is an 'eval' in this scope which introduces the
532 // same variable again, the resulting variable remains the same.
533 // Note that enclosing 'with' statements are handled at the call site.)
534 if (!inner_lookup)
535 return var;
536
537 } else {
538 // We did not find a variable locally. Check against the function variable,
539 // if any. We can do this for all scopes, since the function variable is
540 // only present - if at all - for function scopes.
541 //
542 // This lookup corresponds to a lookup in the "intermediate" scope sitting
543 // between this scope and the outer scope. (ECMA-262, 3rd., requires that
544 // the name of named function literal is kept in an intermediate scope
ager@chromium.org32912102009-01-16 10:38:43 +0000545 // in between this scope and the next outer scope.)
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000546 if (function_ != NULL && function_->name().is_identical_to(name)) {
547 var = function_;
548
549 } else if (outer_scope_ != NULL) {
ager@chromium.org381abbb2009-02-25 13:23:22 +0000550 var = outer_scope_->LookupRecursive(name, true, invalidated_local);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000551 // We may have found a variable in an outer scope. However, if
552 // the current scope is inside a 'with', the actual variable may
553 // be a property introduced via the 'with' statement. Then, the
554 // variable we may have found is just a guess.
555 if (scope_inside_with_)
556 guess = true;
557 }
558
559 // If we did not find a variable, we are done.
560 if (var == NULL)
561 return NULL;
562 }
563
564 ASSERT(var != NULL);
565
566 // If this is a lookup from an inner scope, mark the variable.
567 if (inner_lookup)
568 var->is_accessed_from_inner_scope_ = true;
569
570 // If the variable we have found is just a guess, invalidate the result.
ager@chromium.org381abbb2009-02-25 13:23:22 +0000571 if (guess) {
572 *invalidated_local = var;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000573 var = NULL;
ager@chromium.org381abbb2009-02-25 13:23:22 +0000574 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000575
576 return var;
577}
578
579
ager@chromium.org381abbb2009-02-25 13:23:22 +0000580void Scope::ResolveVariable(Scope* global_scope,
581 Handle<Context> context,
582 VariableProxy* proxy) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000583 ASSERT(global_scope == NULL || global_scope->is_global_scope());
584
585 // If the proxy is already resolved there's nothing to do
586 // (functions and consts may be resolved by the parser).
587 if (proxy->var() != NULL) return;
588
589 // Otherwise, try to resolve the variable.
ager@chromium.org381abbb2009-02-25 13:23:22 +0000590 Variable* invalidated_local = NULL;
591 Variable* var = LookupRecursive(proxy->name(), false, &invalidated_local);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000592
593 if (proxy->inside_with()) {
594 // If we are inside a local 'with' statement, all bets are off
595 // and we cannot resolve the proxy to a local variable even if
596 // we found an outer matching variable.
597 // Note that we must do a lookup anyway, because if we find one,
598 // we must mark that variable as potentially accessed from this
599 // inner scope (the property may not be in the 'with' object).
ager@chromium.org381abbb2009-02-25 13:23:22 +0000600 var = NonLocal(proxy->name(), Variable::DYNAMIC);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000601
602 } else {
603 // We are not inside a local 'with' statement.
604
605 if (var == NULL) {
606 // We did not find the variable. We have a global variable
607 // if we are in the global scope (we know already that we
608 // are outside a 'with' statement) or if there is no way
609 // that the variable might be introduced dynamically (through
610 // a local or outer eval() call, or an outer 'with' statement),
611 // or we don't know about the outer scope (because we are
612 // in an eval scope).
ager@chromium.org381abbb2009-02-25 13:23:22 +0000613 if (is_global_scope() ||
614 !(scope_inside_with_ || outer_scope_is_eval_scope_ ||
615 scope_calls_eval_ || outer_scope_calls_eval_)) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000616 // We must have a global variable.
617 ASSERT(global_scope != NULL);
618 var = new Variable(global_scope, proxy->name(),
619 Variable::DYNAMIC, true, false);
ager@chromium.org381abbb2009-02-25 13:23:22 +0000620
621 } else if (scope_inside_with_) {
622 // If we are inside a with statement we give up and look up
623 // the variable at runtime.
624 var = NonLocal(proxy->name(), Variable::DYNAMIC);
625
626 } else if (invalidated_local != NULL) {
627 // No with statements are involved and we found a local
628 // variable that might be shadowed by eval introduced
629 // variables.
630 var = NonLocal(proxy->name(), Variable::DYNAMIC_LOCAL);
631 var->set_local_if_not_shadowed(invalidated_local);
632
633 } else if (outer_scope_is_eval_scope_) {
634 // No with statements and we did not find a local and the code
635 // is executed with a call to eval. The context contains
636 // scope information that we can use to determine if the
637 // variable is global if it is not shadowed by eval-introduced
638 // variables.
639 if (context->GlobalIfNotShadowedByEval(proxy->name())) {
640 var = NonLocal(proxy->name(), Variable::DYNAMIC_GLOBAL);
641
642 } else {
643 var = NonLocal(proxy->name(), Variable::DYNAMIC);
644 }
645
646 } else {
647 // No with statements and we did not find a local and the code
648 // is not executed with a call to eval. We know that this
649 // variable is global unless it is shadowed by eval-introduced
650 // variables.
651 var = NonLocal(proxy->name(), Variable::DYNAMIC_GLOBAL);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000652 }
653 }
654 }
655
656 proxy->BindTo(var);
657}
658
659
ager@chromium.org381abbb2009-02-25 13:23:22 +0000660void Scope::ResolveVariablesRecursively(Scope* global_scope,
661 Handle<Context> context) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000662 ASSERT(global_scope == NULL || global_scope->is_global_scope());
663
664 // Resolve unresolved variables for this scope.
665 for (int i = 0; i < unresolved_.length(); i++) {
ager@chromium.org381abbb2009-02-25 13:23:22 +0000666 ResolveVariable(global_scope, context, unresolved_[i]);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000667 }
668
669 // Resolve unresolved variables for inner scopes.
670 for (int i = 0; i < inner_scopes_.length(); i++) {
ager@chromium.org381abbb2009-02-25 13:23:22 +0000671 inner_scopes_[i]->ResolveVariablesRecursively(global_scope, context);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000672 }
673}
674
675
ager@chromium.org381abbb2009-02-25 13:23:22 +0000676bool Scope::PropagateScopeInfo(bool outer_scope_calls_eval,
677 bool outer_scope_is_eval_scope) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000678 if (outer_scope_calls_eval) {
679 outer_scope_calls_eval_ = true;
680 }
681
ager@chromium.org381abbb2009-02-25 13:23:22 +0000682 if (outer_scope_is_eval_scope) {
683 outer_scope_is_eval_scope_ = true;
684 }
685
686 bool calls_eval = scope_calls_eval_ || outer_scope_calls_eval_;
687 bool is_eval = is_eval_scope() || outer_scope_is_eval_scope_;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000688 for (int i = 0; i < inner_scopes_.length(); i++) {
689 Scope* inner_scope = inner_scopes_[i];
ager@chromium.org381abbb2009-02-25 13:23:22 +0000690 if (inner_scope->PropagateScopeInfo(calls_eval, is_eval)) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000691 inner_scope_calls_eval_ = true;
692 }
693 if (inner_scope->force_eager_compilation_) {
694 force_eager_compilation_ = true;
695 }
696 }
697
698 return scope_calls_eval_ || inner_scope_calls_eval_;
699}
700
701
702bool Scope::MustAllocate(Variable* var) {
703 // Give var a read/write use if there is a chance it might be
704 // accessed via an eval() call, or if it is a global variable.
705 // This is only possible if the variable has a visible name.
706 if ((var->is_this() || var->name()->length() > 0) &&
707 (var->is_accessed_from_inner_scope_ ||
708 scope_calls_eval_ || inner_scope_calls_eval_ ||
709 scope_contains_with_ || var->is_global())) {
710 var->var_uses()->RecordAccess(1);
711 }
712 return var->var_uses()->is_used();
713}
714
715
716bool Scope::MustAllocateInContext(Variable* var) {
717 // If var is accessed from an inner scope, or if there is a
718 // possibility that it might be accessed from the current or
719 // an inner scope (through an eval() call), it must be allocated
720 // in the context.
721 // Exceptions: Global variables and temporary variables must
722 // never be allocated in the (FixedArray part of the) context.
723 return
724 var->mode() != Variable::TEMPORARY &&
725 (var->is_accessed_from_inner_scope_ ||
726 scope_calls_eval_ || inner_scope_calls_eval_ ||
727 scope_contains_with_ || var->is_global());
728}
729
730
731bool Scope::HasArgumentsParameter() {
732 for (int i = 0; i < params_.length(); i++) {
733 if (params_[i]->name().is_identical_to(Factory::arguments_symbol()))
734 return true;
735 }
736 return false;
737}
738
739
740void Scope::AllocateStackSlot(Variable* var) {
741 var->rewrite_ = new Slot(var, Slot::LOCAL, num_stack_slots_++);
742}
743
744
745void Scope::AllocateHeapSlot(Variable* var) {
746 var->rewrite_ = new Slot(var, Slot::CONTEXT, num_heap_slots_++);
747}
748
749
750void Scope::AllocateParameterLocals() {
751 ASSERT(is_function_scope());
ager@chromium.orga74f0da2008-12-03 16:05:52 +0000752 Variable* arguments = LookupLocal(Factory::arguments_symbol());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000753 ASSERT(arguments != NULL); // functions have 'arguments' declared implicitly
754 if (MustAllocate(arguments) && !HasArgumentsParameter()) {
755 // 'arguments' is used. Unless there is also a parameter called
756 // 'arguments', we must be conservative and access all parameters via
757 // the arguments object: The i'th parameter is rewritten into
758 // '.arguments[i]' (*). If we have a parameter named 'arguments', a
759 // (new) value is always assigned to it via the function
760 // invocation. Then 'arguments' denotes that specific parameter value
761 // and cannot be used to access the parameters, which is why we don't
762 // need to rewrite in that case.
763 //
764 // (*) Instead of having a parameter called 'arguments', we may have an
765 // assignment to 'arguments' in the function body, at some arbitrary
766 // point in time (possibly through an 'eval()' call!). After that
767 // assignment any re-write of parameters would be invalid (was bug
768 // 881452). Thus, we introduce a shadow '.arguments'
769 // variable which also points to the arguments object. For rewrites we
770 // use '.arguments' which remains valid even if we assign to
771 // 'arguments'. To summarize: If we need to rewrite, we allocate an
772 // 'arguments' object dynamically upon function invocation. The compiler
773 // introduces 2 local variables 'arguments' and '.arguments', both of
774 // which originally point to the arguments object that was
775 // allocated. All parameters are rewritten into property accesses via
776 // the '.arguments' variable. Thus, any changes to properties of
777 // 'arguments' are reflected in the variables and vice versa. If the
778 // 'arguments' variable is changed, '.arguments' still points to the
779 // correct arguments object and the rewrites still work.
780
781 // We are using 'arguments'. Tell the code generator that is needs to
782 // allocate the arguments object by setting 'arguments_'.
783 arguments_ = new VariableProxy(Factory::arguments_symbol(), false, false);
784 arguments_->BindTo(arguments);
785
786 // We also need the '.arguments' shadow variable. Declare it and create
787 // and bind the corresponding proxy. It's ok to declare it only now
788 // because it's a local variable that is allocated after the parameters
789 // have been allocated.
790 //
791 // Note: This is "almost" at temporary variable but we cannot use
792 // NewTemporary() because the mode needs to be INTERNAL since this
793 // variable may be allocated in the heap-allocated context (temporaries
794 // are never allocated in the context).
795 Variable* arguments_shadow =
796 new Variable(this, Factory::arguments_shadow_symbol(),
797 Variable::INTERNAL, true, false);
798 arguments_shadow_ =
799 new VariableProxy(Factory::arguments_shadow_symbol(), false, false);
800 arguments_shadow_->BindTo(arguments_shadow);
801 temps_.Add(arguments_shadow);
802
803 // Allocate the parameters by rewriting them into '.arguments[i]' accesses.
804 for (int i = 0; i < params_.length(); i++) {
805 Variable* var = params_[i];
806 ASSERT(var->scope() == this);
807 if (MustAllocate(var)) {
808 if (MustAllocateInContext(var)) {
809 // It is ok to set this only now, because arguments is a local
810 // variable that is allocated after the parameters have been
811 // allocated.
812 arguments_shadow->is_accessed_from_inner_scope_ = true;
813 }
814 var->rewrite_ =
815 new Property(arguments_shadow_,
816 new Literal(Handle<Object>(Smi::FromInt(i))),
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000817 RelocInfo::kNoPosition,
818 Property::SYNTHETIC);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000819 arguments_shadow->var_uses()->RecordUses(var->var_uses());
820 }
821 }
822
823 } else {
824 // The arguments object is not used, so we can access parameters directly.
825 // The same parameter may occur multiple times in the parameters_ list.
826 // If it does, and if it is not copied into the context object, it must
827 // receive the highest parameter index for that parameter; thus iteration
828 // order is relevant!
829 for (int i = 0; i < params_.length(); i++) {
830 Variable* var = params_[i];
831 ASSERT(var->scope() == this);
832 if (MustAllocate(var)) {
833 if (MustAllocateInContext(var)) {
834 ASSERT(var->rewrite_ == NULL ||
835 (var->slot() != NULL && var->slot()->type() == Slot::CONTEXT));
836 if (var->rewrite_ == NULL) {
837 // Only set the heap allocation if the parameter has not
838 // been allocated yet.
839 AllocateHeapSlot(var);
840 }
841 } else {
842 ASSERT(var->rewrite_ == NULL ||
843 (var->slot() != NULL &&
844 var->slot()->type() == Slot::PARAMETER));
845 // Set the parameter index always, even if the parameter
846 // was seen before! (We need to access the actual parameter
847 // supplied for the last occurrence of a multiply declared
848 // parameter.)
849 var->rewrite_ = new Slot(var, Slot::PARAMETER, i);
850 }
851 }
852 }
853 }
854}
855
856
857void Scope::AllocateNonParameterLocal(Variable* var) {
858 ASSERT(var->scope() == this);
859 ASSERT(var->rewrite_ == NULL ||
860 (!var->IsVariable(Factory::result_symbol())) ||
861 (var->slot() == NULL || var->slot()->type() != Slot::LOCAL));
862 if (MustAllocate(var) && var->rewrite_ == NULL) {
863 if (MustAllocateInContext(var)) {
864 AllocateHeapSlot(var);
865 } else {
866 AllocateStackSlot(var);
867 }
868 }
869}
870
871
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000872void Scope::AllocateNonParameterLocals() {
873 // Each variable occurs exactly once in the locals_ list; all
874 // variables that have no rewrite yet are non-parameter locals.
875
876 // Sort them according to use such that the locals with more uses
877 // get allocated first.
878 if (FLAG_usage_computation) {
879 // This is currently not implemented.
880 }
881
882 for (int i = 0; i < temps_.length(); i++) {
883 AllocateNonParameterLocal(temps_[i]);
884 }
885
886 for (LocalsMap::Entry* p = locals_.Start(); p != NULL; p = locals_.Next(p)) {
887 Variable* var = reinterpret_cast<Variable*>(p->value);
888 AllocateNonParameterLocal(var);
889 }
890
891 // Note: For now, function_ must be allocated at the very end. If
892 // it gets allocated in the context, it must be the last slot in the
893 // context, because of the current ScopeInfo implementation (see
894 // ScopeInfo::ScopeInfo(FunctionScope* scope) constructor).
895 if (function_ != NULL) {
896 AllocateNonParameterLocal(function_);
897 }
898}
899
900
901void Scope::AllocateVariablesRecursively() {
902 // The number of slots required for variables.
903 num_stack_slots_ = 0;
904 num_heap_slots_ = Context::MIN_CONTEXT_SLOTS;
905
906 // Allocate variables for inner scopes.
907 for (int i = 0; i < inner_scopes_.length(); i++) {
908 inner_scopes_[i]->AllocateVariablesRecursively();
909 }
910
911 // Allocate variables for this scope.
912 // Parameters must be allocated first, if any.
913 if (is_function_scope()) AllocateParameterLocals();
914 AllocateNonParameterLocals();
915
916 // Allocate context if necessary.
917 bool must_have_local_context = false;
918 if (scope_calls_eval_ || scope_contains_with_) {
919 // The context for the eval() call or 'with' statement in this scope.
920 // Unless we are in the global or an eval scope, we need a local
921 // context even if we didn't statically allocate any locals in it,
922 // and the compiler will access the context variable. If we are
923 // not in an inner scope, the scope is provided from the outside.
924 must_have_local_context = is_function_scope();
925 }
926
927 // If we didn't allocate any locals in the local context, then we only
928 // need the minimal number of slots if we must have a local context.
929 if (num_heap_slots_ == Context::MIN_CONTEXT_SLOTS &&
930 !must_have_local_context) {
931 num_heap_slots_ = 0;
932 }
933
934 // Allocation done.
935 ASSERT(num_heap_slots_ == 0 || num_heap_slots_ >= Context::MIN_CONTEXT_SLOTS);
936}
937
938} } // namespace v8::internal