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